gis 편집

This commit is contained in:
2026-06-01 15:49:50 +09:00
parent cdaaa34569
commit c7c69ea5a7
20 changed files with 2130 additions and 413 deletions
@@ -1,7 +1,9 @@
// 하수관로
export const MsSwagePplCol = [
{ id: 'fclt_mng_no', title: '시설관리번호' },
{ id: 'mngInstNm', title: '관리기관' },
{ id: 'inst_mng_no', title: '기관관리번호' },
{ id: 'flowDirectionBasis', title: '유하방향 근거' },
{ id: 'instl_ymd', title: '설치일자' },
{ id: 'elapsedYears', title: '경과년도' },
{ id: 'mapsht_no', title: '도엽번호' },
@@ -33,6 +35,7 @@ export const MsSwagePplCol2 = [
{ id: 'rowNumber', title: '일련\n번호' },
{ id: 'fcltMngNo', title: '시설\n관리번호' },
{ id: 'instMngNo', title: '기관\n관리번호' },
{ id: 'flowDirectionBasis', title: '유하방향\n근거' },
{ id: 'ctpvNm', title: '시도' },
{ id: 'sggNm', title: '시군구' },
{ id: "swtrmt_zone_nm", title: "처리구역" },
@@ -6,10 +6,9 @@ import { Button } from "@common/components/ui";
import { getData } from "@/components/lib/api";
import { VerticalTable } from "@/components/ui/verticalTable";
import { formatDisplayData } from "@/components/lib/utils/formatDisplayValue";
import type { GisEditChange, GisEditPipeBasicInfo } from "./gisEditTypes";
import { MS_SWAGE_PPL_CODES, MS_SWAGE_PPL_USE_CODES, MsSwagePplCol } from "../common/table";
import { MS_SWAGE_PPL_CODES, MS_SWAGE_PPL_USE_CODES } from "../common/table";
type Props = {
change: GisEditChange;
@@ -18,83 +17,146 @@ type Props = {
onSave: (changeId: string, draft: GisEditPipeBasicInfo) => void;
};
type MngInstOption = {
mngInstCd: string;
lwrInstNm: string;
};
const EMPTY_SELECT_OPTION = { value: "", label: "선택" };
const PIPE_BASIC_INFO_FIELDS = [
{ id: "mngInstCd", sourceId: "mng_inst_cd", title: "관리기관", type: "select", required: true },
{ id: "fcltMngNo", sourceId: "fclt_mng_no", title: "시설관리번호", type: "input", required: true },
{ id: "instMngNo", sourceId: "inst_mng_no", title: "기관관리번호", type: "input", required: true },
{ id: "instlYmd", sourceId: "instl_ymd", title: "설치일자", type: "date" },
{ id: "mapshtNo", sourceId: "mapsht_no", title: "도엽번호", type: "input" },
{ id: "pdmtVl", sourceId: "pdmt_vl", title: "관경(mm)", type: "input" },
{ id: "prlgVl", sourceId: "prlg_vl", title: "연장(m)", type: "input" },
{
id: "usgCd",
sourceId: "usg_cd",
title: "용도",
type: "select",
required: true,
options: [
EMPTY_SELECT_OPTION,
...MS_SWAGE_PPL_USE_CODES.map((item) => ({ value: item.val.trim(), label: item.text })),
],
},
{
id: "mqltCd",
sourceId: "mqlt_cd",
title: "재질",
type: "select",
options: [
EMPTY_SELECT_OPTION,
...MS_SWAGE_PPL_CODES.map((item) => ({ value: item.val.trim(), label: item.text })),
],
},
{ id: "avgGrdn", sourceId: "avg_grdn", title: "평균구배(m/m)", type: "input" },
{ id: "drtwMltvArea", sourceId: "drtw_mltv_area", title: "오수배수면적(m²)", type: "input" },
{ id: "exclnMltvArea", sourceId: "excln_mltv_area", title: "우수배수면적(m²)", type: "input" },
{ id: "tmptDpth", sourceId: "tmpt_dpth", title: "시점깊이(m)", type: "input" },
{ id: "tmptMhlMngNo", sourceId: "tmpt_mhl_mng_no", title: "시점맨홀관리번호", type: "input" },
{ id: "scendDpth", sourceId: "scend_dpth", title: "종점깊이(m)", type: "input" },
{ id: "scendMhlMngNo", sourceId: "scend_mhl_mng_no", title: "종점맨홀관리번호", type: "input" },
{ id: "trflnCnt", sourceId: "trfln_cnt", title: "차선수", type: "input" },
{ id: "vrtcLen", sourceId: "vrtc_len", title: "세로길이(m)", type: "input" },
{ id: "wdthLen", sourceId: "wdth_len", title: "가로길이(m)", type: "input" },
];
const PIPE_INPUT_INFO_FIELDS = [
{ id: "instlMbdyCd", title: "설치주체", type: "select", options: ["", "BTL", "재정사업"] },
{ id: "instlMbdyCd", title: "설치주체", type: "select", options: [EMPTY_SELECT_OPTION, "BTL", "재정사업"] },
{ id: "swtrmtZoneNm", title: "처리구역", type: "input" },
{ id: "mltvZoneNm", title: "배수구역", type: "input" },
{ id: "mltvDtdvNm", title: "배수분구", type: "input" },
{ id: "lineCd", title: "지선/간선", type: "select", options: ["", "지선", "간선"] },
{ id: "floCd", title: "흐름방식", type: "select", options: ["", "자연유하", "압송"] },
{ id: "layCd", title: "매설위치", type: "select", options: ["", "도로", "하상"] },
{ id: "lineCd", title: "지선/간선", type: "select", options: [EMPTY_SELECT_OPTION, "지선", "간선"] },
{ id: "floCd", title: "흐름방식", type: "select", options: [EMPTY_SELECT_OPTION, "자연유하", "압송"] },
{ id: "layCd", title: "매설위치", type: "select", options: [EMPTY_SELECT_OPTION, "도로", "하상"] },
];
const PIPE_BASIC_INFO_FIELDS = MsSwagePplCol.map((column) => {
if (column.id === "usg_cd") {
return {
...column,
type: "select",
options: ["", ...MS_SWAGE_PPL_USE_CODES.map((item) => item.text)],
};
}
const PIPE_VISIBLE_BASIC_FIELD_IDS = PIPE_BASIC_INFO_FIELDS.map((field) => field.id);
const PIPE_VISIBLE_INPUT_FIELD_IDS = PIPE_INPUT_INFO_FIELDS.map((field) => field.id);
if (column.id === "mqlt_cd") {
return {
...column,
type: "select",
options: ["", ...MS_SWAGE_PPL_CODES.map((item) => item.text)],
};
}
return {
...column,
type: "input",
};
});
const buildBaseFeatureValues = (featureData: any) => {
const resolveUsageText = (value: unknown) => {
const raw = String(value ?? "").trim();
const matched = MS_SWAGE_PPL_USE_CODES.find((item) => item.val === raw || item.text === raw);
return matched?.text ?? raw;
};
const resolveMaterialText = (value: unknown) => {
const raw = String(value ?? "").trim();
const matched = MS_SWAGE_PPL_CODES.find((item) => item.val === raw || item.text === raw);
return matched?.text ?? raw;
};
if (featureData?.values_) {
const formatted = formatDisplayData(featureData.values_);
return {
...formatted,
usg_cd: resolveUsageText(featureData.values_?.usg_cd ?? formatted.usg_cd),
mqlt_cd: resolveMaterialText(featureData.values_?.mqlt_cd ?? formatted.mqlt_cd),
};
}
if (featureData) {
const formatted = formatDisplayData(featureData);
return {
...formatted,
usg_cd: resolveUsageText(featureData?.usg_cd ?? formatted.usg_cd),
mqlt_cd: resolveMaterialText(featureData?.mqlt_cd ?? formatted.mqlt_cd),
};
}
return {};
const toEditableText = (value: unknown) => {
const text = String(value ?? "").trim();
return text === "-" ? "" : text;
};
const buildInitialInputDraft = (change: GisEditChange, baseValues: Record<string, any>) => ({
fcltMngNo: String(change.basicInfo?.fcltMngNo ?? change.featureRef?.fcltMngNo ?? baseValues.fclt_mng_no ?? baseValues.fcltMngNo ?? ""),
mngInstCd: String(change.basicInfo?.mngInstCd ?? change.featureRef?.mngInstCd ?? baseValues.mng_inst_cd ?? baseValues.mngInstCd ?? ""),
instlMbdyCd: String(change.basicInfo?.instlMbdyCd ?? ""),
swtrmtZoneNm: String(change.basicInfo?.swtrmtZoneNm ?? ""),
mltvZoneNm: String(change.basicInfo?.mltvZoneNm ?? ""),
mltvDtdvNm: String(change.basicInfo?.mltvDtdvNm ?? ""),
lineCd: String(change.basicInfo?.lineCd ?? ""),
floCd: String(change.basicInfo?.floCd ?? ""),
layCd: String(change.basicInfo?.layCd ?? ""),
const toDateInputValue = (value: unknown) => {
const text = toEditableText(value).replaceAll(".", "").replaceAll("-", "");
if (!/^\d{8}$/.test(text)) return "";
return `${text.slice(0, 4)}-${text.slice(4, 6)}-${text.slice(6, 8)}`;
};
const toDbYmdValue = (value: unknown) => toEditableText(value).replaceAll("-", "");
const getObjectValue = (values: Record<string, any>, field: { id: string; sourceId?: string }) =>
values[field.id] ?? (field.sourceId ? values[field.sourceId] : undefined);
const pickFields = (values: Record<string, any>, fieldIds: string[]) =>
fieldIds.reduce<Record<string, any>>((acc, fieldId) => {
if (Object.prototype.hasOwnProperty.call(values, fieldId)) {
acc[fieldId] = values[fieldId];
}
return acc;
}, {});
const normalizeBasicFormValues = (values: Record<string, any>) => {
const nextValues = pickFields(values, PIPE_VISIBLE_BASIC_FIELD_IDS);
if (Object.prototype.hasOwnProperty.call(nextValues, "instlYmd")) {
nextValues.instlYmd = toDateInputValue(nextValues.instlYmd);
}
return nextValues;
};
const buildBaseFeatureValues = (featureData: any) => {
const resolveUsageCode = (value: unknown) => {
const raw = String(value ?? "").trim();
const matched = MS_SWAGE_PPL_USE_CODES.find((item) => item.val === raw || item.text === raw);
return matched?.val.trim() ?? raw;
};
const resolveMaterialCode = (value: unknown) => {
const raw = String(value ?? "").trim();
const matched = MS_SWAGE_PPL_CODES.find((item) => item.val === raw || item.text === raw);
return matched?.val.trim() ?? raw;
};
const sourceValues = featureData?.values_ ?? featureData ?? {};
return PIPE_BASIC_INFO_FIELDS.reduce<Record<string, any>>((acc, field) => {
const rawValue = getObjectValue(sourceValues, field);
if (field.id === "usgCd") {
acc[field.id] = resolveUsageCode(rawValue);
return acc;
}
if (field.id === "mqltCd") {
acc[field.id] = resolveMaterialCode(rawValue);
return acc;
}
if (field.id === "instlYmd") {
acc[field.id] = toDateInputValue(rawValue);
return acc;
}
acc[field.id] = toEditableText(rawValue);
return acc;
}, {});
};
const getPipeUsageLabel = (value: unknown) => {
const raw = String(value ?? "").trim();
if (!raw) return "";
return MS_SWAGE_PPL_USE_CODES.find((item) => item.val.trim() === raw || item.text === raw)?.text ?? raw;
};
const buildInitialInputDraft = (change: GisEditChange) => ({
instlMbdyCd: toEditableText(change.basicInfo?.instlMbdyCd ?? ""),
swtrmtZoneNm: toEditableText(change.basicInfo?.swtrmtZoneNm ?? ""),
mltvZoneNm: toEditableText(change.basicInfo?.mltvZoneNm ?? ""),
mltvDtdvNm: toEditableText(change.basicInfo?.mltvDtdvNm ?? ""),
lineCd: toEditableText(change.basicInfo?.lineCd ?? ""),
floCd: toEditableText(change.basicInfo?.floCd ?? ""),
layCd: toEditableText(change.basicInfo?.layCd ?? ""),
});
export default function GisEditPipeSessionPopup({
@@ -107,22 +169,67 @@ export default function GisEditPipeSessionPopup({
const baseFeatureValues = useMemo(() => buildBaseFeatureValues(featureData), [featureData]);
const [basicInfoTableData, setBasicInfoTableData] = useState<Record<string, any>>({});
const [inputInfoTableData, setInputInfoTableData] = useState<Record<string, any>>(
buildInitialInputDraft(change, baseFeatureValues),
buildInitialInputDraft(change),
);
const [mngInstOptions, setMngInstOptions] = useState<MngInstOption[]>([]);
useEffect(() => {
let isMounted = true;
const fetchMngInstOptions = async () => {
try {
const result = await getData("v1/fcltppl/mngInsts");
if (!isMounted) return;
setMngInstOptions(Array.isArray(result) ? result : []);
} catch (error) {
console.error("관리기관 목록 조회 실패:", error);
if (isMounted) setMngInstOptions([]);
}
};
fetchMngInstOptions();
return () => {
isMounted = false;
};
}, []);
const mngInstSelectOptions = useMemo(
() => {
const sortedOptions = [...mngInstOptions].sort((a, b) =>
String(a.lwrInstNm ?? a.mngInstCd ?? "").localeCompare(
String(b.lwrInstNm ?? b.mngInstCd ?? ""),
"ko",
),
);
return [
EMPTY_SELECT_OPTION,
...sortedOptions.map((option) => ({
value: String(option.mngInstCd ?? "").trim(),
label: option.lwrInstNm || String(option.mngInstCd ?? "").trim(),
})),
];
},
[mngInstOptions],
);
const basicInfoFields = useMemo(
() =>
PIPE_BASIC_INFO_FIELDS.map((field) =>
field.id === "mngInstCd"
? { ...field, options: mngInstSelectOptions }
: field,
),
[mngInstSelectOptions],
);
useEffect(() => {
const initialBasicValues: Record<string, any> = {
...baseFeatureValues,
...(change.basicInfo ?? {}),
...normalizeBasicFormValues(change.basicInfo ?? {}),
};
if (isNewPipe) {
delete initialBasicValues.instl_ymd;
delete initialBasicValues.elapsedYears;
}
setBasicInfoTableData(initialBasicValues);
setInputInfoTableData(buildInitialInputDraft(change, baseFeatureValues));
setInputInfoTableData(buildInitialInputDraft(change));
}, [baseFeatureValues, change.changeId, isNewPipe]);
useEffect(() => {
@@ -140,10 +247,8 @@ export default function GisEditPipeSessionPopup({
setInputInfoTableData((previous) => ({
...previous,
...result,
...(change.basicInfo ?? {}),
fcltMngNo,
mngInstCd,
...pickFields(result, PIPE_VISIBLE_INPUT_FIELD_IDS),
...pickFields(change.basicInfo ?? {}, PIPE_VISIBLE_INPUT_FIELD_IDS),
}));
} catch (error) {
console.error("GIS 편집 관로 입력정보 조회 실패:", error);
@@ -156,20 +261,20 @@ export default function GisEditPipeSessionPopup({
};
}, [change.changeId, change.featureRef?.fcltMngNo, change.featureRef?.mngInstCd, isNewPipe]);
const editableBasicInfoFields = useMemo(
() => PIPE_BASIC_INFO_FIELDS.filter((field) => !(isNewPipe && (field.id === "instl_ymd" || field.id === "elapsedYears"))),
[isNewPipe],
);
const buildMergedDraft = (
nextBasicInfoTableData: Record<string, any>,
nextInputInfoTableData: Record<string, any>,
): GisEditPipeBasicInfo => ({
...nextBasicInfoTableData,
...nextInputInfoTableData,
fcltMngNo: String(nextInputInfoTableData.fcltMngNo ?? change.featureRef?.fcltMngNo ?? change.objectId ?? ""),
mngInstCd: String(nextInputInfoTableData.mngInstCd ?? change.featureRef?.mngInstCd ?? ""),
});
): GisEditPipeBasicInfo => {
const basicDraft = pickFields(nextBasicInfoTableData, PIPE_VISIBLE_BASIC_FIELD_IDS);
const inputDraft = pickFields(nextInputInfoTableData, PIPE_VISIBLE_INPUT_FIELD_IDS);
if (basicDraft.instlYmd) {
basicDraft.instlYmd = toDbYmdValue(basicDraft.instlYmd);
}
return {
...basicDraft,
...inputDraft,
};
};
const handleBasicInfoChange = (nextFormData: Record<string, any>) => {
setBasicInfoTableData(nextFormData);
@@ -181,14 +286,18 @@ export default function GisEditPipeSessionPopup({
onSave(change.changeId, buildMergedDraft(basicInfoTableData, nextFormData));
};
const basicInfoTableRows = useMemo(() => [basicInfoTableData], [basicInfoTableData]);
const inputInfoTableRows = useMemo(() => [inputInfoTableData], [inputInfoTableData]);
const displayManagementNo = toEditableText(change.featureRef?.fcltMngNo ?? change.objectId ?? "");
return (
<div id="popup" className="absolute top-0 right-0 w-[350px] h-[calc(100vh-5rem)] bg-white border-r border-gray-300 flex flex-col overflow-hidden transition-all duration-300 z-[50]">
<div className="card-header bg-primary flex items-center justify-between relative p-4">
<div className="flex items-center space-x-4 flex-1">
<h3 className="text-2xl font-medium text-white text-label whitespace-nowrap">
하수관로
{basicInfoTableData?.usg_cd ? `(${basicInfoTableData.usg_cd})` : ""}
{" "}정보 <br />관리번호 : {change.featureRef?.fcltMngNo ?? change.objectId ?? "-"}
{basicInfoTableData?.usgCd ? `(${getPipeUsageLabel(basicInfoTableData.usgCd)})` : ""}
{" "}정보 <br />관리번호 : {displayManagementNo || "신규"}
</h3>
</div>
<Button
@@ -202,8 +311,8 @@ export default function GisEditPipeSessionPopup({
<div className="overflow-y-auto overflow-x-hidden flex-1">
<VerticalTable
headName="기본정보"
tableData={[basicInfoTableData]}
headlist={editableBasicInfoFields}
tableData={basicInfoTableRows}
headlist={basicInfoFields}
pageSize={20}
total={0}
cellClick={undefined}
@@ -213,7 +322,7 @@ export default function GisEditPipeSessionPopup({
/>
<VerticalTable
headName="입력정보"
tableData={[inputInfoTableData]}
tableData={inputInfoTableRows}
headlist={PIPE_INPUT_INFO_FIELDS}
pageSize={20}
total={0}
@@ -23,6 +23,9 @@ const buildChangeItemClassName = (isFocused: boolean) =>
: "border-[#d8dee8] bg-[#fbfcfe] hover:border-[#bfd2e5] hover:bg-white"
}`;
const getChangeLabel = (change: GisEditSessionSnapshot["changes"][number]) =>
change.attributeOnly ? "상세정보수정" : TOOL_LABELS[change.editType];
type ChangeListProps = {
changes: GisEditSessionSnapshot["changes"];
focusedChangeId: string | null;
@@ -40,7 +43,7 @@ const ChangeList = ({ changes, focusedChangeId, onFocusChange }: ChangeListProps
>
<div className="flex items-center justify-between gap-3">
<div className="font-semibold text-[#173f67]">
{index + 1}. {TOOL_LABELS[change.editType]} / {change.objectLabel}
{index + 1}. {getChangeLabel(change)} / {change.objectLabel}
</div>
<div className="flex items-center gap-1.5">
{change.basicInfoSavedAt ? (
@@ -66,7 +69,6 @@ export default function GisEditSessionPanel({
selectedLayerName,
activeTool,
changes,
lastSavedPayload,
canUndo,
focusedChangeId,
onRemoveLastChange,
@@ -76,24 +78,12 @@ export default function GisEditSessionPanel({
}: Props) {
return (
<div
className={`rounded border border-[#d8dee8] bg-[rgba(255,255,255,0.98)] p-4 text-sm text-[#304255] shadow-[0_10px_26px_rgba(23,42,70,0.14)] ${className}`.trim()}
className={`rounded-lg border border-[#d8dee8] bg-[rgba(255,255,255,0.98)] p-4 text-sm text-[#304255] shadow-[0_10px_26px_rgba(23,42,70,0.14)] ${className}`.trim()}
>
<div className="mb-3 flex items-center justify-between gap-3">
<div>
<div className="text-[13px] font-bold text-[#173f67]">편집 세션</div>
<div className="mt-1 text-[12px] text-[#667485]">
레이어: {selectedLayerName || "미선택"} / 모드: {isEditMode ? (activeTool ? TOOL_LABELS[activeTool] : "대기") : "편집 모드 종료"}
</div>
<div className="text-[12px] text-[#667485]">
레이어: {selectedLayerName || "미선택"} / 모드: {isEditMode ? (activeTool ? TOOL_LABELS[activeTool] : "대기") : "편집 모드 종료"}
</div>
{isEditMode ? (
<div className="rounded-full border border-[#b8d3ef] bg-[#f2f8ff] px-2 py-1 text-[11px] font-semibold text-[#174e82]">
FE 로컬 세션
</div>
) : (
<div className="rounded-full border border-[#f2d18d] bg-[#fff8eb] px-2 py-1 text-[11px] font-semibold text-[#9a5b00]">
지도 미리보기 유지
</div>
)}
</div>
<div className="mb-3 flex flex-wrap items-center gap-2">
@@ -124,7 +114,7 @@ export default function GisEditSessionPanel({
저장할 편집 변경분이 없습니다.
</div>
) : (
<div className="max-h-[calc(100vh-220px)] min-h-[640px] overflow-y-auto pr-1">
<div className="max-h-[calc(100vh-190px)] overflow-y-auto pr-1">
<div className="space-y-2">
<ChangeList
changes={changes}
@@ -136,14 +126,6 @@ export default function GisEditSessionPanel({
)}
</div>
{lastSavedPayload ? (
<div className="mt-4 rounded border border-[#d8dee8] bg-[#0f172a] px-3 py-3 text-[11px] text-[#dbeafe]">
<div className="mb-2 font-semibold text-white">저장 payload 미리보기</div>
<pre className="max-h-[220px] overflow-auto whitespace-pre-wrap break-all">
{JSON.stringify(lastSavedPayload, null, 2)}
</pre>
</div>
) : null}
</div>
);
}
@@ -1,24 +1,28 @@
"use client";
import {
Check,
Move,
PenTool,
Plus,
Trash2,
X,
} from "lucide-react";
import { Button } from "@common/components/ui";
import type { GisEditLayerInfo, GisEditTool } from "./gisEditTypes";
import type { GisEditTool } from "./gisEditTypes";
type Props = {
isEditMode: boolean;
editableLayers: GisEditLayerInfo[];
selectedLayerId: string;
selectedLayer: GisEditLayerInfo | null;
activeTool: GisEditTool | null;
canUseTools: boolean;
canSave: boolean;
isSaving?: boolean;
sessionChangeCount?: number;
statusMessage: string;
onSelectLayer: (layerId: string) => void;
allowedTools?: GisEditTool[];
onOpenSession?: () => void;
onClose?: () => void;
onSelectTool: (tool: GisEditTool) => void;
onSave: () => void;
};
@@ -36,49 +40,38 @@ const TOOL_BUTTONS: Array<{
export default function GisEditToolbar({
isEditMode,
editableLayers,
selectedLayerId,
selectedLayer,
activeTool,
canUseTools,
canSave,
statusMessage,
onSelectLayer,
isSaving = false,
sessionChangeCount = 0,
statusMessage: _statusMessage,
allowedTools = [],
onOpenSession,
onClose,
onSelectTool,
onSave,
}: Props) {
if (!isEditMode) return null;
return (
<div className="absolute left-1/2 top-4 z-[60] flex w-[min(780px,calc(100%-2rem))] -translate-x-1/2 flex-col gap-2">
<div className="rounded border border-[#9bbddf] bg-[rgba(255,255,255,0.96)] px-3 py-3 shadow-[0_10px_26px_rgba(23,42,70,0.14)]">
<div className="flex flex-wrap items-center gap-2">
<select
className="h-9 min-w-[176px] rounded border border-[#9bbddf] bg-[#f8fbff] px-3 text-sm text-[#243548]"
value={selectedLayerId}
onChange={(event) => onSelectLayer(event.target.value)}
>
<option value="">레이어 선택</option>
{editableLayers.map((layer) => (
<option key={layer.layerId} value={layer.layerId} disabled={layer.editableYn !== "Y"}>
{layer.layerName}
</option>
))}
</select>
<div className="absolute left-1/2 top-4 z-[60] flex w-[min(860px,calc(100%-2rem))] -translate-x-1/2 flex-col">
<div className="card card-border flex !bg-white py-[1px]">
<div className="flex w-full flex-wrap items-center gap-2">
<div className="mr-1 flex min-w-[116px] items-center">
<span className="text-[1.3rem] font-bold leading-5 text-[#123b62]">하수관로 편집</span>
</div>
{TOOL_BUTTONS.map(({ tool, label, icon: Icon }) => {
const isActive = activeTool === tool;
const isToolEnabled =
canUseTools && Boolean(selectedLayer?.allowedTools.includes(tool));
canUseTools && allowedTools.includes(tool);
return (
<button
<Button
key={tool}
type="button"
className={`min-w-[92px] rounded border px-3 py-2 text-sm font-semibold transition ${
isActive
? "border-[#176db8] bg-[#176db8] text-white"
: "border-[#9bbddf] bg-[#eef7ff] text-[#0c5fa6]"
} disabled:cursor-not-allowed disabled:border-[#d6dde6] disabled:bg-[#f0f2f4] disabled:text-[#9aa8b7]`}
color={isActive ? "primary" : "white"}
size="sm"
className="mx-1 mt-1 min-w-[82px]"
disabled={!isToolEnabled}
onClick={() => onSelectTool(tool)}
>
@@ -86,34 +79,50 @@ export default function GisEditToolbar({
<Icon className="h-4 w-4" />
<span>{label}</span>
</span>
</button>
</Button>
);
})}
<button
<Button
type="button"
className="ml-auto rounded border border-[#a9d9bd] bg-[#e9f8ef] px-4 py-2 text-sm font-semibold text-[#16834f] transition disabled:cursor-not-allowed disabled:border-[#d6dde6] disabled:bg-[#f0f2f4] disabled:text-[#9aa8b7]"
disabled={!canSave}
color="white"
size="sm"
className="ml-auto mt-1 min-w-[112px]"
onClick={onOpenSession}
title="GIS 편집 세션 보기"
>
<span className="flex items-center justify-center gap-2">
<Check className="h-4 w-4" />
<span>편집 세션 {sessionChangeCount}</span>
</span>
</Button>
<Button
type="button"
color="primary"
size="sm"
className="mx-1 mt-1 min-w-[64px]"
disabled={!canSave || isSaving}
onClick={onSave}
>
저장
</button>
</div>
</div>
{isSaving ? "저장 중" : "저장"}
</Button>
<div className="rounded border border-[#d8dee8] bg-[rgba(255,255,255,0.94)] px-3 py-2 text-sm text-[#304255] shadow-[0_10px_26px_rgba(23,42,70,0.12)]">
{statusMessage}
<Button
type="button"
color="white"
size="sm"
className="mx-1 mt-1 min-w-[68px]"
onClick={onClose}
title="하수관로 편집 닫기"
>
<span className="flex items-center justify-center gap-2">
<X className="h-4 w-4" />
<span>닫기</span>
</span>
</Button>
</div>
</div>
{activeTool === "MOVE" ? (
<div className="self-center rounded-full border border-[#b8d3ef] bg-[rgba(242,248,255,0.96)] px-3 py-1 text-[12px] font-medium text-[#175f9c] shadow-[0_6px_18px_rgba(23,42,70,0.1)]">
이동 대상 선택 후 파란 미리보기 객체를 드래그해 위치를 조정하세요.
</div>
) : null}
{activeTool === "VERTEX_EDIT" ? (
<div className="self-center rounded-full border border-[#f2d18d] bg-[rgba(255,248,235,0.96)] px-3 py-1 text-[12px] font-medium text-[#9a5b00] shadow-[0_6px_18px_rgba(23,42,70,0.1)]">
편집 대상 선택 후 주황색 꼭지점 handle을 드래그해 형상을 조정하세요.
</div>
) : null}
</div>
);
}
@@ -15,16 +15,33 @@ export type GisEditFeatureRef = {
};
export type GisEditPipeBasicInfo = {
[key: string]: string | undefined;
fcltMngNo?: string;
mngInstCd?: string;
instlMbdyCd?: string;
swtrmtZoneNm?: string;
mltvZoneNm?: string;
mltvDtdvNm?: string;
lineCd?: string;
floCd?: string;
layCd?: string;
[key: string]: string | null | undefined;
fcltMngNo?: string | null;
mngInstCd?: string | null;
instMngNo?: string | null;
instlYmd?: string | null;
mapshtNo?: string | null;
pdmtVl?: string | null;
prlgVl?: string | null;
usgCd?: string | null;
mqltCd?: string | null;
avgGrdn?: string | null;
drtwMltvArea?: string | null;
exclnMltvArea?: string | null;
tmptDpth?: string | null;
tmptMhlMngNo?: string | null;
scendDpth?: string | null;
scendMhlMngNo?: string | null;
trflnCnt?: string | null;
vrtcLen?: string | null;
wdthLen?: string | null;
instlMbdyCd?: string | null;
swtrmtZoneNm?: string | null;
mltvZoneNm?: string | null;
mltvDtdvNm?: string | null;
lineCd?: string | null;
floCd?: string | null;
layCd?: string | null;
};
export type GisEditLayerInfo = {
@@ -43,12 +60,16 @@ export type GisEditChange = {
layerId: string;
layerName: string;
objectId?: string;
fid?: string;
baseEditSn?: string;
featureRef?: GisEditFeatureRef;
objectLabel: string;
beforeGeometry?: Record<string, unknown> | null;
afterGeometry?: Record<string, unknown> | null;
featureProperties?: Record<string, unknown> | null;
basicInfo?: GisEditPipeBasicInfo | null;
basicInfoSavedAt?: string | null;
attributeOnly?: boolean;
summary: string;
createdAt: string;
source: "MAP_SELECTION" | "MAP_CENTER" | "MAP_DRAW";
@@ -58,7 +79,7 @@ export type GisEditSavePayload = {
screenId: string;
layerId: string;
layerName: string;
saveTargetType: "VERSION";
saveTargetType: "VERSION" | "FINAL";
view: {
srs: string;
bbox: string | null;
@@ -68,8 +89,10 @@ export type GisEditSavePayload = {
editType: GisEditTool;
objectId?: string;
clientTempId?: string;
fid?: string;
baseEditSn?: string;
featureRef?: GisEditFeatureRef;
basicInfo?: GisEditPipeBasicInfo | null;
attributes?: GisEditPipeBasicInfo | null;
beforeGeometry?: Record<string, unknown> | null;
afterGeometry?: Record<string, unknown> | null;
geometry?: Record<string, unknown> | null;
@@ -19,6 +19,12 @@ type GisEditInteractionRequest = {
editType: "MOVE" | "VERTEX_EDIT";
};
const isActionableChange = (change: GisEditChange) =>
!change.attributeOnly || Boolean(change.basicInfoSavedAt);
const isGeometryChange = (change: GisEditChange) =>
!change.attributeOnly && change.editType !== "ADD";
const buildPreviewFocusMessage = (
change: Pick<GisEditChange, "editType" | "layerName" | "objectLabel">,
) => {
@@ -113,10 +119,57 @@ const EDITABLE_LAYER_RULES: Record<
const FLOW_DIRECTION_SRS = "EPSG:5179";
const SCREEN_ID = "SN_MN010301";
const GIS_EDIT_ALLOWED_LAYER_IDS = new Set(["tb_ms_swage_ppl"]);
const GIS_EDIT_PIPE_ATTRIBUTE_FIELD_IDS = [
"mngInstCd",
"fcltMngNo",
"instMngNo",
"instlYmd",
"mapshtNo",
"pdmtVl",
"prlgVl",
"usgCd",
"mqltCd",
"avgGrdn",
"drtwMltvArea",
"exclnMltvArea",
"tmptDpth",
"tmptMhlMngNo",
"scendDpth",
"scendMhlMngNo",
"trflnCnt",
"vrtcLen",
"wdthLen",
"instlMbdyCd",
"swtrmtZoneNm",
"mltvZoneNm",
"mltvDtdvNm",
"lineCd",
"floCd",
"layCd",
] as const;
const buildPipeSaveAttributes = (basicInfo: GisEditPipeBasicInfo | null | undefined) => {
if (!basicInfo) return undefined;
return GIS_EDIT_PIPE_ATTRIBUTE_FIELD_IDS.reduce<GisEditPipeBasicInfo>((acc, fieldId) => {
if (!Object.prototype.hasOwnProperty.call(basicInfo, fieldId)) return acc;
const value = basicInfo[fieldId];
const normalizedValue = fieldId === "instlYmd" ? String(value ?? "").replaceAll("-", "") : value;
acc[fieldId] =
typeof normalizedValue === "string" && normalizedValue.trim() === ""
? null
: normalizedValue;
return acc;
}, {});
};
export const EMPTY_GIS_EDIT_PIPE_BASIC_INFO: GisEditPipeBasicInfo = {
fcltMngNo: "",
mngInstCd: "",
fcltMngNo: "",
instMngNo: "",
instlYmd: "",
usgCd: "",
instlMbdyCd: "",
swtrmtZoneNm: "",
mltvZoneNm: "",
@@ -321,15 +374,52 @@ const getFeatureLayerId = (featureData: any) => {
return normalizeLayerIdCandidate(featureData?.lyrTypeNm ?? featureData?.lyrTyNm ?? "");
};
const stripLayerPrefix = (value: unknown) => {
const raw = String(value ?? "").trim();
if (!raw) return "";
const withoutNamespace = raw.includes(":") ? raw.split(":").pop() ?? raw : raw;
if (withoutNamespace.startsWith("tb_ms_swage_ppl.")) {
return withoutNamespace.slice("tb_ms_swage_ppl.".length);
}
return withoutNamespace;
};
const getFeatureFid = (featureData: any) =>
stripLayerPrefix(
featureData?.get?.("fid") ??
featureData?.values_?.fid ??
featureData?.fid ??
featureData?.getId?.() ??
featureData?.id_ ??
"",
);
const getFeatureObjectId = (featureData: any) =>
String(
featureData?.get?.("objectId") ??
featureData?.values_?.fclt_mng_no ??
featureData?.values_?.swtrmt_fclt_cd ??
getFeatureFid(featureData) ||
String(
featureData?.get?.("objectId") ??
featureData?.values_?.fclt_mng_no ??
featureData?.values_?.swtrmt_fclt_cd ??
featureData?.fcltMngNo ??
featureData?.fid ??
"",
),
).trim();
const getFeatureObjectLabel = (featureData: any) => {
const values = featureData?.values_ ?? {};
return String(
featureData?.get?.("fclt_mng_no") ??
values?.fclt_mng_no ??
featureData?.fcltMngNo ??
featureData?.fid ??
featureData?.get?.("objectId") ??
values?.swtrmt_fclt_cd ??
getFeatureFid(featureData) ??
"",
).trim();
};
const getFeatureRef = (featureData: any): GisEditFeatureRef | undefined => {
const mapValues = featureData?.values_ ?? {};
@@ -346,12 +436,7 @@ const getFeatureRef = (featureData: any): GisEditFeatureRef | undefined => {
featureData?.mngInstCd ??
"",
).trim() || undefined,
fid: String(
featureData?.getId?.() ??
featureData?.id_ ??
featureData?.fid ??
"",
).trim() || undefined,
fid: getFeatureFid(featureData) || undefined,
};
if (!featureRef.fcltMngNo && !featureRef.mngInstCd && !featureRef.fid) {
@@ -361,6 +446,32 @@ const getFeatureRef = (featureData: any): GisEditFeatureRef | undefined => {
return featureRef;
};
// 선택한 원본 관로의 속성 snapshot을 보관해 preview 재선택 시 상세정보가 비지 않게 한다.
const getFeatureProperties = (featureData: any): Record<string, unknown> | null => {
const values = featureData?.values_ ?? featureData?.getProperties?.() ?? featureData;
if (!values || typeof values !== "object") return null;
const { geometry, ...properties } = values;
return properties;
};
const normalizePipeGeometry = (
layerId: string,
geometry: Record<string, unknown> | null,
): Record<string, unknown> | null => {
if (layerId !== "tb_ms_swage_ppl" || !geometry) return geometry;
if (geometry.type !== "LineString") return geometry;
const coordinates = geometry.coordinates;
if (!Array.isArray(coordinates)) return geometry;
return {
...geometry,
type: "MultiLineString",
coordinates: [coordinates],
};
};
const createChangeId = (prefix: string, sequence: number) => {
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
return `${prefix}-${crypto.randomUUID()}`;
@@ -373,15 +484,15 @@ export const useGisEdit = (treeData: any[]) => {
// GIS 편집 모드 on/off는 우측 분석 메뉴의 GIS 편집 버튼과 직접 연결된다.
const [isEditMode, setIsEditMode] = useState(false);
// 현재 선택 레이어를 기준으로 허용 도구와 저장 payload의 layerId를 결정한다.
const [selectedLayerId, setSelectedLayerId] = useState("");
const [selectedLayerId, setSelectedLayerId] = useState("tb_ms_swage_ppl");
// 1차 구현에서는 activeTool과 지도 선택 이벤트를 조합해 변경분을 로컬 세션에 누적한다.
const [activeTool, setActiveTool] = useState<GisEditTool | null>(null);
// 저장 전까지의 변경분은 FE 로컬 편집 세션으로만 유지하고 BE API 연결 전 payload 검토 근거로 사용한다.
// 저장 전까지의 변경분은 FE 로컬 편집 세션으로만 유지한다.
const [changes, setChanges] = useState<GisEditChange[]>([]);
const [statusMessage, setStatusMessage] = useState(
"GIS편집 버튼을 켜면 레이어를 선택하고 편집 도구를 사용할 수 있습니다.",
"GIS편집 버튼을 켜면 하수관로 편집 도구를 사용할 수 있습니다.",
);
// 실제 저장 대신 마지막으로 조립한 payload를 세션 패널에서 미리보기로 노출한다.
// 이전 구현 호환용 상태다. 저장 버튼은 payload 미리보기를 노출하지 않고 즉시 API 호출 흐름으로 넘어간다.
const [lastSavedPayload, setLastSavedPayload] = useState<GisEditSavePayload | null>(null);
const [pendingInteraction, setPendingInteraction] = useState<GisEditInteractionRequest | null>(null);
const [focusedChangeId, setFocusedChangeId] = useState<string | null>(null);
@@ -394,7 +505,11 @@ export const useGisEdit = (treeData: any[]) => {
);
const canUseTools = Boolean(selectedLayer);
const canSave = changes.length > 0 && Boolean(selectedLayer);
const actionableChanges = useMemo(
() => changes.filter(isActionableChange),
[changes],
);
const canSave = actionableChanges.length > 0 && Boolean(selectedLayer);
const appendChange = useCallback((change: GisEditChange) => {
setLastSavedPayload(null);
@@ -407,11 +522,7 @@ export const useGisEdit = (treeData: any[]) => {
if (!targetChange) return;
setFocusedChangeId(changeId);
if (targetChange.editType === "MOVE" || targetChange.editType === "VERTEX_EDIT") {
setPendingInteraction({ changeId, editType: targetChange.editType });
} else {
setPendingInteraction(null);
}
setPendingInteraction(null);
setStatusMessage(buildPreviewFocusMessage(targetChange));
}, [changes]);
@@ -422,12 +533,26 @@ export const useGisEdit = (treeData: any[]) => {
) =>
changes.find(
(change) =>
!change.attributeOnly &&
change.editType === editType &&
change.layerId === layerId &&
String(change.objectId ?? "") === objectId,
) ?? null,
[changes]);
// 같은 원본 관로에 대한 삭제/이동/꼭지점편집 변경분은 하나만 유지해 도구 전환 시 세션 상태가 섞이지 않게 한다.
const findExistingGeometryChange = useCallback((
layerId: string,
objectId: string,
) =>
changes.find(
(change) =>
isGeometryChange(change) &&
change.layerId === layerId &&
String(change.objectId ?? "") === objectId,
) ?? null,
[changes]);
// 편집 모드를 끄더라도 작업 중 세션을 잃지 않도록 변경분은 유지하고 도구 상태만 정리한다.
const toggleEditMode = useCallback(() => {
setIsEditMode((previous) => {
@@ -438,7 +563,7 @@ export const useGisEdit = (treeData: any[]) => {
latestSelectionRef.current = null;
setStatusMessage(
next
? "편집 대상 레이어를 선택한 뒤 지도에서 편집 작업을 진행하세요."
? "하수관로 편집 도구를 선택한 뒤 지도에서 편집 작업을 진행하세요."
: "GIS 편집 모드를 종료했습니다. 편집 세션은 유지됩니다.",
);
return next;
@@ -510,6 +635,13 @@ export const useGisEdit = (treeData: any[]) => {
);
}, [appendChange, selectedLayer]);
const deactivateTool = useCallback(() => {
setActiveTool(null);
setPendingInteraction(null);
latestSelectionRef.current = null;
setStatusMessage("편집 도구 선택을 해제했습니다. 추가, 이동, 꼭지점편집, 삭제 모드가 모두 꺼졌습니다.");
}, []);
const registerAddGeometry = useCallback((geometry: Record<string, unknown> | null) => {
if (!selectedLayer || !geometry) {
setStatusMessage("추가 geometry를 확인하지 못했습니다.");
@@ -519,6 +651,7 @@ export const useGisEdit = (treeData: any[]) => {
changeSequenceRef.current += 1;
const clientTempId = `NEW-${changeSequenceRef.current}`;
const changeId = createChangeId(`ADD-${selectedLayer.layerId}`, changeSequenceRef.current);
const nextGeometry = normalizePipeGeometry(selectedLayer.layerId, geometry);
appendChange({
changeId,
@@ -529,12 +662,11 @@ export const useGisEdit = (treeData: any[]) => {
featureRef: undefined,
objectLabel: clientTempId,
beforeGeometry: null,
afterGeometry: geometry,
afterGeometry: nextGeometry,
basicInfo:
selectedLayer.layerId === "tb_ms_swage_ppl"
? {
...EMPTY_GIS_EDIT_PIPE_BASIC_INFO,
fcltMngNo: clientTempId,
}
: null,
basicInfoSavedAt: null,
@@ -557,6 +689,87 @@ export const useGisEdit = (treeData: any[]) => {
const previewChange = changes.find((change) => change.changeId === previewChangeId);
if (!previewChange) return { handled: true };
if (previewChange.editType === "ADD" && activeTool === "DELETE") {
setLastSavedPayload(null);
setChanges((previous) => previous.filter((change) => change.changeId !== previewChangeId));
setFocusedChangeId((current) => (current === previewChangeId ? null : current));
setPendingInteraction((current) => (current?.changeId === previewChangeId ? null : current));
latestSelectionRef.current = null;
setStatusMessage(`${previewChange.layerName} 신규 객체를 편집 세션에서 삭제했습니다.`);
return {
handled: true,
isPreviewSelection: true,
editType: "DELETE",
};
}
if (
previewChange.editType !== "ADD" &&
previewChange.editType !== "DELETE" &&
activeTool === "DELETE"
) {
setLastSavedPayload(null);
setChanges((previous) =>
previous.map((change) =>
change.changeId === previewChangeId
? {
...change,
editType: "DELETE",
afterGeometry: null,
summary: `${change.layerName} ${change.objectLabel} 객체를 임시 삭제 대상으로 표시했습니다.`,
}
: change,
),
);
setFocusedChangeId(previewChangeId);
setPendingInteraction(null);
latestSelectionRef.current = null;
setStatusMessage(`${previewChange.layerName} ${previewChange.objectLabel} 객체를 임시 삭제 대상으로 표시했습니다.`);
return {
handled: true,
isPreviewSelection: true,
changeId: previewChangeId,
editType: "DELETE",
fid: previewChange.fid ?? previewChange.featureRef?.fid ?? previewChange.objectId,
};
}
if (
previewChange.editType === "DELETE" &&
(activeTool === "MOVE" || activeTool === "VERTEX_EDIT")
) {
setFocusedChangeId(previewChangeId);
setPendingInteraction(null);
setStatusMessage("이미 삭제 예정인 관로입니다. 이동 또는 꼭지점편집이 필요하면 마지막 변경 취소 후 다시 선택하세요.");
return {
handled: true,
isPreviewSelection: true,
changeId: previewChangeId,
editType: activeTool,
fid: previewChange.fid ?? previewChange.featureRef?.fid ?? previewChange.objectId,
};
}
if (
previewChange.editType !== "DELETE" &&
(activeTool === "MOVE" || activeTool === "VERTEX_EDIT")
) {
setFocusedChangeId(previewChangeId);
setPendingInteraction({ changeId: previewChangeId, editType: activeTool });
const targetLabel = previewChange.editType === "ADD" ? "신규 객체" : previewChange.objectLabel;
setStatusMessage(
activeTool === "MOVE"
? `${previewChange.layerName} ${targetLabel}를 드래그해 위치를 조정하세요.`
: `${previewChange.layerName} ${targetLabel}의 꼭지점을 드래그해 형상을 조정하세요.`,
);
return {
handled: true,
isPreviewSelection: true,
changeId: previewChangeId,
editType: activeTool,
};
}
focusChange(previewChangeId);
return {
handled: true,
@@ -585,6 +798,47 @@ export const useGisEdit = (treeData: any[]) => {
return { handled: true };
}
const existingGeometryChange = findExistingGeometryChange(selectedLayer.layerId, objectId);
if (existingGeometryChange?.editType === "DELETE" && (activeTool === "MOVE" || activeTool === "VERTEX_EDIT")) {
focusChange(existingGeometryChange.changeId);
setPendingInteraction(null);
setStatusMessage("이미 삭제 예정인 관로입니다. 이동 또는 꼭지점편집이 필요하면 마지막 변경 취소 후 다시 선택하세요.");
return {
handled: true,
isPreviewSelection: false,
changeId: existingGeometryChange.changeId,
editType: "DELETE",
fid: existingGeometryChange.fid ?? existingGeometryChange.featureRef?.fid ?? objectId,
};
}
if (existingGeometryChange && existingGeometryChange.editType !== "DELETE" && activeTool === "DELETE") {
setLastSavedPayload(null);
setChanges((previous) =>
previous.map((change) =>
change.changeId === existingGeometryChange.changeId
? {
...change,
editType: "DELETE",
afterGeometry: null,
summary: `${change.layerName} ${change.objectLabel} 객체를 임시 삭제 대상으로 표시했습니다.`,
}
: change,
),
);
setFocusedChangeId(existingGeometryChange.changeId);
setPendingInteraction(null);
latestSelectionRef.current = null;
setStatusMessage(`${existingGeometryChange.layerName} ${existingGeometryChange.objectLabel} 객체를 임시 삭제 대상으로 표시했습니다.`);
return {
handled: true,
isPreviewSelection: false,
changeId: existingGeometryChange.changeId,
editType: "DELETE",
fid: existingGeometryChange.fid ?? existingGeometryChange.featureRef?.fid ?? objectId,
};
}
const selectionSignature = `${activeTool}:${selectedLayer.layerId}:${objectId}`;
const now = Date.now();
if (
@@ -598,30 +852,36 @@ export const useGisEdit = (treeData: any[]) => {
const existingChange = findExistingObjectChange(activeTool, selectedLayer.layerId, objectId);
if (existingChange) {
focusChange(existingChange.changeId);
if (activeTool === "MOVE" || activeTool === "VERTEX_EDIT") {
setPendingInteraction({ changeId: existingChange.changeId, editType: activeTool });
}
return {
handled: true,
isPreviewSelection: false,
changeId: existingChange.changeId,
editType: existingChange.editType,
fid: existingChange.fid ?? existingChange.featureRef?.fid ?? objectId,
};
}
const geometryObject = toGeometryObject(featureData);
const geometryType = normalizeGeometryType(geometryObject?.type);
const featureRef = getFeatureRef(featureData);
const objectLabel = getFeatureObjectLabel(featureData) || objectId;
const normalizedGeometryObject = normalizePipeGeometry(selectedLayer.layerId, geometryObject);
const nextGeometry =
activeTool === "MOVE"
? geometryObject
? normalizedGeometryObject
: activeTool === "VERTEX_EDIT"
? geometryObject
? normalizedGeometryObject
: activeTool === "DELETE"
? null
: geometryObject;
: normalizedGeometryObject;
const summaryMap: Record<GisEditTool, string> = {
MOVE: `${selectedLayer.layerName} ${objectId} 객체를 선택했습니다. 지도에서 드래그해 위치를 조정하세요.`,
VERTEX_EDIT: `${selectedLayer.layerName} ${objectId} 객체를 선택했습니다. 주황색 실꼭지점을 드래그하거나 흰색 midpoint를 끌어 새 꼭지점을 추가하세요.`,
DELETE: `${selectedLayer.layerName} ${objectId} 객체를 임시 삭제 대상으로 표시했습니다.`,
ADD: `${selectedLayer.layerName} ${objectId} 객체를 추가했습니다.`,
MOVE: `${selectedLayer.layerName} ${objectLabel} 객체를 선택했습니다. 지도에서 드래그해 위치를 조정하세요.`,
VERTEX_EDIT: `${selectedLayer.layerName} ${objectLabel} 객체를 선택했습니다. 주황색 실꼭지점을 드래그하거나 흰색 midpoint를 끌어 새 꼭지점을 추가하세요.`,
DELETE: `${selectedLayer.layerName} ${objectLabel} 객체를 임시 삭제 대상으로 표시했습니다.`,
ADD: `${selectedLayer.layerName} ${objectLabel} 객체를 추가했습니다.`,
};
changeSequenceRef.current += 1;
const changeId = createChangeId(`${activeTool}-${objectId}`, changeSequenceRef.current);
@@ -632,15 +892,17 @@ export const useGisEdit = (treeData: any[]) => {
layerId: selectedLayer.layerId,
layerName: selectedLayer.layerName,
objectId,
fid: featureRef?.fid ?? objectId,
featureRef,
objectLabel: objectId,
beforeGeometry: geometryObject,
objectLabel,
beforeGeometry: normalizedGeometryObject,
afterGeometry: nextGeometry,
featureProperties: getFeatureProperties(featureData),
basicInfo: null,
basicInfoSavedAt: null,
summary:
activeTool === "VERTEX_EDIT" && geometryType === "Point"
? `${selectedLayer.layerName} ${objectId}는 점형 객체여서 꼭지점편집 대신 geometry 검토 대상으로 기록했습니다.`
? `${selectedLayer.layerName} ${objectLabel}는 점형 객체여서 꼭지점편집 대신 geometry 검토 대상으로 기록했습니다.`
: summaryMap[activeTool],
createdAt: new Date().toISOString(),
source: "MAP_SELECTION",
@@ -656,12 +918,85 @@ export const useGisEdit = (treeData: any[]) => {
} else {
setPendingInteraction(null);
}
return { handled: true, isPreviewSelection: false, changeId, editType: activeTool };
}, [activeTool, appendChange, findExistingObjectChange, focusChange, isEditMode, selectedLayer]);
return { handled: true, isPreviewSelection: false, changeId, editType: activeTool, fid: featureRef?.fid ?? objectId };
}, [activeTool, appendChange, findExistingGeometryChange, findExistingObjectChange, focusChange, isEditMode, selectedLayer]);
const registerPipeDetailSelection = useCallback((featureData: any) => {
if (!isEditMode || !selectedLayer) return { handled: false };
if (selectedLayer.layerId !== "tb_ms_swage_ppl") return { handled: false };
const featureLayerId = getFeatureLayerId(featureData);
if (featureLayerId !== selectedLayer.layerId) {
setStatusMessage("하수관로를 선택해주세요.");
return { handled: true };
}
const objectId = getFeatureObjectId(featureData);
if (!objectId) {
setStatusMessage("선택 객체의 관리번호를 찾을 수 없어 상세정보 수정 화면을 열 수 없습니다.");
return { handled: true };
}
const existingChange =
changes.find(
(change) =>
change.layerId === selectedLayer.layerId &&
change.editType !== "DELETE" &&
String(change.objectId ?? "") === objectId,
) ?? null;
if (existingChange) {
focusChange(existingChange.changeId);
setPendingInteraction(null);
setStatusMessage(`${selectedLayer.layerName} ${objectId} 상세정보를 수정할 수 있습니다.`);
return {
handled: true,
isPreviewSelection: false,
changeId: existingChange.changeId,
editType: existingChange.editType as GisEditTool,
fid: existingChange.fid ?? existingChange.featureRef?.fid ?? objectId,
};
}
const geometryObject = toGeometryObject(featureData);
const normalizedGeometryObject = normalizePipeGeometry(selectedLayer.layerId, geometryObject);
const featureRef = getFeatureRef(featureData);
const objectLabel = getFeatureObjectLabel(featureData) || objectId;
changeSequenceRef.current += 1;
const changeId = createChangeId(`DETAIL-${objectId}`, changeSequenceRef.current);
appendChange({
changeId,
editType: "VERTEX_EDIT" as const,
layerId: selectedLayer.layerId,
layerName: selectedLayer.layerName,
objectId,
fid: featureRef?.fid ?? objectId,
featureRef,
objectLabel,
beforeGeometry: normalizedGeometryObject,
afterGeometry: normalizedGeometryObject,
featureProperties: getFeatureProperties(featureData),
basicInfo: null,
basicInfoSavedAt: null,
attributeOnly: true,
summary: `${selectedLayer.layerName} ${objectLabel} 상세정보 수정 대상으로 선택했습니다.`,
createdAt: new Date().toISOString(),
source: "MAP_SELECTION",
});
setFocusedChangeId(changeId);
setPendingInteraction(null);
setStatusMessage(`${selectedLayer.layerName} ${objectLabel} 상세정보를 수정할 수 있습니다.`);
return {
handled: true,
isPreviewSelection: false,
changeId,
editType: "VERTEX_EDIT",
fid: featureRef?.fid ?? objectId,
};
}, [appendChange, changes, focusChange, isEditMode, selectedLayer]);
// 저장 API가 붙기 전까지는 실제 전송 대신 최종 payload를 조립해 검증 패널에 남긴다.
const save = useCallback((map: any) => {
if (!selectedLayer || changes.length === 0) {
if (!selectedLayer || actionableChanges.length === 0) {
setStatusMessage("저장할 편집 변경분이 없습니다.");
return null;
}
@@ -670,28 +1005,28 @@ export const useGisEdit = (treeData: any[]) => {
screenId: SCREEN_ID,
layerId: selectedLayer.layerId,
layerName: selectedLayer.layerName,
saveTargetType: "VERSION",
saveTargetType: "FINAL",
view: {
srs: FLOW_DIRECTION_SRS,
bbox: buildBbox(map),
},
changes: changes.map((change) => ({
changes: actionableChanges.map((change) => ({
changeId: change.changeId,
editType: change.editType,
objectId: change.editType === "ADD" ? undefined : change.objectId,
clientTempId: change.editType === "ADD" ? change.objectId : undefined,
fid: change.editType === "ADD" ? undefined : change.fid ?? change.featureRef?.fid ?? change.objectId,
baseEditSn: change.editType === "ADD" ? undefined : change.baseEditSn,
featureRef: change.featureRef,
basicInfo: change.basicInfo ?? undefined,
attributes: buildPipeSaveAttributes(change.basicInfo),
beforeGeometry: change.beforeGeometry,
afterGeometry: change.editType === "DELETE" ? null : change.afterGeometry,
geometry: change.editType === "ADD" ? change.afterGeometry : undefined,
})),
};
setLastSavedPayload(payload);
setStatusMessage("관로 기본정보와 geometry를 함께 담은 최종 저장 payload를 생성했습니다. 현재는 FE 세션 검토 단계이며, 실제 DB 반영은 백엔드 저장 API가 필요합니다.");
return payload;
}, [changes, selectedLayer]);
}, [actionableChanges, selectedLayer]);
const removeLastChange = useCallback(() => {
setLastSavedPayload(null);
@@ -721,10 +1056,22 @@ export const useGisEdit = (treeData: any[]) => {
setStatusMessage("편집 세션을 초기화했습니다.");
}, []);
const discardSession = useCallback(() => {
setIsEditMode(false);
setLastSavedPayload(null);
setChanges([]);
setActiveTool(null);
setPendingInteraction(null);
setFocusedChangeId(null);
latestSelectionRef.current = null;
setStatusMessage("하수관로 편집을 종료하고 세션 변경분을 초기화했습니다.");
}, []);
const updateChangeGeometry = useCallback((
changeId: string,
afterGeometry: Record<string, unknown> | null,
summary: string,
options?: { keepVertexEditActive?: boolean },
) => {
setLastSavedPayload(null);
setChanges((previous) =>
@@ -739,6 +1086,14 @@ export const useGisEdit = (treeData: any[]) => {
),
);
setFocusedChangeId(changeId);
if (options?.keepVertexEditActive) {
setActiveTool("VERTEX_EDIT");
setPendingInteraction({ changeId, editType: "VERTEX_EDIT" });
} else {
setActiveTool(null);
setPendingInteraction(null);
}
latestSelectionRef.current = null;
setStatusMessage(summary);
}, []);
@@ -767,6 +1122,20 @@ export const useGisEdit = (treeData: any[]) => {
setStatusMessage("관로 기본정보를 편집 세션에 저장했습니다. 최종 GIS 저장 전까지는 DB에 반영되지 않습니다.");
}, []);
const updateChangeBaseEditSn = useCallback((changeId: string, baseEditSn: string) => {
setLastSavedPayload(null);
setChanges((previous) =>
previous.map((change) =>
change.changeId === changeId
? {
...change,
baseEditSn,
}
: change,
),
);
}, []);
const clearPendingInteraction = useCallback(() => {
setPendingInteraction(null);
}, []);
@@ -789,18 +1158,22 @@ export const useGisEdit = (treeData: any[]) => {
pendingInteraction,
focusedChangeId,
pendingApiMessage:
"현재 구현은 FE 로컬 편집 세션, 관로 기본정보 draft, 저장 payload 미리보기까지 포함합니다. BE 저장 API(`/api/v1/map/gisEditSessions/save`) 연결 전까지는 실제 저장 대신 payload를 검토합니다.",
canUndo: changes.length > 0,
"현재 구현은 FE 로컬 편집 세션, 관로 기본정보 draft, BE 저장 API(`/api/v1/map/gisEditSessions/save`) 최종본 저장까지 포함합니다.",
canUndo: actionableChanges.length > 0,
toggleEditMode,
selectLayer,
activateTool,
deactivateTool,
registerAddGeometry,
registerFeatureSelection,
registerPipeDetailSelection,
save,
removeLastChange,
clearChanges,
discardSession,
updateChangeGeometry,
updateChangeBasicInfo,
updateChangeBaseEditSn,
clearPendingInteraction,
focusChange,
announceStatus,
@@ -61,6 +61,11 @@ const linkedFacilityHighlightStyle = new Style({
zIndex: 9999,
});
type MngInstOption = {
mngInstCd: string;
lwrInstNm: string;
};
const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void, featureData: any }) => {
const { gisMap } = useGisContext() as unknown as { checkedLayerIds: React.MutableRefObject<number[]>; treeData: { lyrSn: number }[] | null; gisCore: any; gisMap: any; };
const [layerNm, setLayerNm] = useState<string>(""); // 레이어 이름 상태
@@ -80,6 +85,7 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
const [chmbrYdnts, setChmbrYdnts] = useState<string>(''); // 로딩 상태
const linkedFacilityFeatureRef = useRef<any>(null);
const linkedFacilityOriginalStyleRef = useRef<any>(null);
const [mngInstOptions, setMngInstOptions] = useState<MngInstOption[]>([]);
// 🎯 관로관리번호 추출
const pplMngNo = featureData?.values_?.fclt_mng_no || featureData?.fcltMngNo || "";
@@ -87,6 +93,10 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
const featureId = typeof featureData.getId === 'function'
? featureData.getId()
: featureData.fid;
const selectedLayerTypeName = featureData?.values_
? featureData?.id_?.split('.')?.[0]
: featureData?.lyrTypeNm;
const isPipeFeature = selectedLayerTypeName === 'tb_ms_swage_ppl';
// 🎯 데이터 전처리 메모이제이션
const processedData = useMemo(() => {
@@ -98,6 +108,81 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
};
}, [featureData?.values_]);
useEffect(() => {
let isMounted = true;
if (isPipeFeature) {
setMngInstOptions([]);
return () => {
isMounted = false;
};
}
const fetchMngInstOptions = async () => {
try {
const result = await getData("v1/fcltppl/mngInsts");
if (!isMounted) return;
const sortedOptions = Array.isArray(result)
? [...result].sort((a, b) =>
String(a?.lwrInstNm ?? a?.mngInstCd ?? "").localeCompare(
String(b?.lwrInstNm ?? b?.mngInstCd ?? ""),
"ko",
),
)
: [];
setMngInstOptions(sortedOptions);
} catch (error) {
console.error("관리기관 목록 조회 실패:", error);
if (isMounted) setMngInstOptions([]);
}
};
fetchMngInstOptions();
return () => {
isMounted = false;
};
}, [isPipeFeature]);
const mngInstNameMap = useMemo(() => {
const map = new Map<string, string>();
mngInstOptions.forEach((option) => {
const code = String(option.mngInstCd ?? "").trim();
if (!code) return;
map.set(code, option.lwrInstNm || code);
});
return map;
}, [mngInstOptions]);
const withMngInstName = (data: any) => {
if (!data || typeof data !== "object") return data;
const mngInstCd = String(data.mng_inst_cd ?? data.mngInstCd ?? "").trim();
if (!mngInstCd) return data;
return {
...data,
mngInstNm: mngInstNameMap.get(mngInstCd) ?? data.mngInstNm ?? data.mng_inst_nm ?? mngInstCd,
};
};
const hasDetailValue = (value: unknown) => {
if (value === null || value === undefined) return false;
if (typeof value === "string") return value.trim() !== "";
return true;
};
const mergeDetailData = (baseData: any, detailData: any) => {
if (!detailData || typeof detailData !== "object") return baseData;
const meaningfulDetailData = Object.entries(detailData).reduce<Record<string, unknown>>((acc, [key, value]) => {
if (hasDetailValue(value)) acc[key] = value;
return acc;
}, {});
return {
...(baseData ?? {}),
...meaningfulDetailData,
};
};
const clearLinkedFacilityHighlight = () => {
if (linkedFacilityFeatureRef.current) {
linkedFacilityFeatureRef.current.setStyle(linkedFacilityOriginalStyleRef.current ?? undefined);
@@ -306,6 +391,7 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
try {
const selectedLayerName = getSelectedLayers(); // 레이어 이름 가져오기
setLayerNm(selectedLayerName); // 상태 업데이트
const isPipeDetailLayer = selectedLayerName === '하수관로';
let data;
if (featureData['ol_uid']) data = featureData.values_; // Gis 레이어 클릭 이벤트일 때
@@ -334,7 +420,7 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
}
// 🎯 기본 데이터 포맷팅
const formattedData = formatDisplayData(data);
const formattedData = withMngInstName(formatDisplayData(data));
if (selectedLayerName === '하수관로') {
const installYmd = data.instl_ymd ?? data.instlYmd;
formattedData.elapsedYears = getElapsedYearsDisplayText(installYmd);
@@ -344,18 +430,22 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
}
}
setFetchData(formattedData);
setTableData(formattedData);
if (!isPipeDetailLayer) {
setFetchData(formattedData);
setTableData(formattedData);
}
switch (selectedLayerName) {
case '하수관로':
setButtonChk(true)
// ✅ codeMapper 사용하여 API 결과도 변환
setTableData(codeMapper({
layerName: selectedLayerName,
data: { ...formattedData }
}));
if (!isPipeDetailLayer) {
setTableData(withMngInstName(codeMapper({
layerName: selectedLayerName,
data: { ...formattedData }
})));
}
break;
case '하수맨홀':
setButtonChk(true)
@@ -422,12 +512,14 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
const result = await getData(apiEndpoint);
if (result) {
const processedApiData = codeMapper({
const mergedData = isPipeDetailLayer ? result : mergeDetailData(formattedData, result);
const processedApiData = withMngInstName(codeMapper({
layerName: selectedLayerName,
data: { ...result, ...tableData }
});
data: mergedData
}));
setFetchData(processedApiData);
setTableData(processedApiData);
}
} catch (apiError) {
console.error('API 데이터 로딩 중 오류:', apiError);
@@ -439,7 +531,7 @@ const FeatureClickEventPopup = ({ onClose, featureData }: { onClose: () => void,
};
fetchData();
}, [featureId, processedData]);
}, [featureId, processedData, mngInstNameMap]);
useEffect(() => {
const layerTypeNm = featureData?.values_
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,73 @@
"use client";
import { CalendarIcon } from "lucide-react";
import { useState, type ComponentProps } from "react";
import { Button, Calendar, Popover, PopoverContent, PopoverTrigger } from "@common/components/ui";
type CalendarProps = ComponentProps<typeof Calendar>;
type SearchDatePickerProps = {
selected?: Date;
onSelect: (date: Date | undefined) => void;
placeholder?: string;
className?: string;
disabled?: CalendarProps["disabled"];
defaultMonth?: CalendarProps["defaultMonth"];
};
const formatDateLabel = (date: Date) => {
const year = date.getFullYear();
const month = `${date.getMonth() + 1}`.padStart(2, "0");
const day = `${date.getDate()}`.padStart(2, "0");
return `${year}-${month}-${day}`;
};
export function SearchDatePicker({
selected,
onSelect,
placeholder = "날짜 선택",
className,
disabled,
defaultMonth,
}: SearchDatePickerProps) {
// 검색조건 달력은 날짜 선택과 동시에 Popover를 닫아야 하므로 open 상태를 화면 전용으로 제어한다.
const [open, setOpen] = useState(false);
const handleSelect = (date: Date | undefined) => {
onSelect(date);
if (date) {
setOpen(false);
}
};
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
className={[
"h-[3rem] w-[12rem] justify-start border-input !bg-background px-4 py-2 text-left text-[1.3rem] font-normal text-muted-foreground hover:!bg-accent",
className,
]
.filter(Boolean)
.join(" ")}
disabled={disabled === true}
>
<CalendarIcon className="!size-[1.6rem]" />
{selected ? formatDateLabel(selected) : <span>{placeholder}</span>}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0">
<Calendar
classNames={{ cell: "rounded-md" }}
mode="single"
selected={selected}
onSelect={handleSelect}
disabled={disabled}
defaultMonth={defaultMonth}
/>
</PopoverContent>
</Popover>
);
}
@@ -23,7 +23,7 @@ import { formatDate, handleDownload } from '@/components/lib/utils'
import LoadingOverlay from '@/components/ui/LoadingBar'
import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable } from '@common/business_components/ui'
import ListDiv from '@common/business_components/ui/list_div'
import { Button, DatePicker, Input, Label } from '@common/components/ui'
import { Button, Input, Label } from '@common/components/ui'
import { useEffect, useState } from 'react'
import { tableHeadlist } from '..'
import { useQuery } from "@tanstack/react-query";
@@ -31,6 +31,7 @@ import { ENDPOINT } from "@common/components/config";
import { getUserInfo } from "@common/components/api";
import { openWindowPopup } from '@/features/windowPopup/lib/openWindowPopup';
import { WINDOW_POPUP_MESSAGE_TYPE } from '@/features/windowPopup/model/types';
import { SearchDatePicker } from '../_components/SearchDatePicker';
const Page = () => {
@@ -176,20 +177,16 @@ const Page = () => {
<div className='flex items-center gap-5'>
<div className='flex items-center gap-2'>
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
<DatePicker mode={'single'}
<SearchDatePicker
selected={fromDate}
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }}
modifiers={{
disabled: { after: new Date() }
}}
disabled={{ after: new Date() }}
/>
<span>~</span>
<DatePicker mode={'single'}
<SearchDatePicker
selected={toDate}
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }}
modifiers={{
disabled: { after: new Date() }
}}
disabled={{ after: new Date() }}
/>
</div>
<div className='flex items-center'>
@@ -23,7 +23,7 @@ import { formatDate, handleDownload } from '@/components/lib/utils'
import LoadingOverlay from '@/components/ui/LoadingBar'
import { SearchDiv, SearchFormLeft, SearchFormRight, UiTable } from '@common/business_components/ui'
import ListDiv from '@common/business_components/ui/list_div'
import { Button, DatePicker, Input, Label } from '@common/components/ui'
import { Button, Input, Label } from '@common/components/ui'
import { useEffect, useState } from 'react'
import { tableHeadlistOldPp } from '..'
import { useQuery } from "@tanstack/react-query";
@@ -31,6 +31,7 @@ import { ENDPOINT } from "@common/components/config";
import { getUserInfo } from "@common/components/api";
import { openWindowPopup } from '@/features/windowPopup/lib/openWindowPopup';
import { WINDOW_POPUP_MESSAGE_TYPE } from '@/features/windowPopup/model/types';
import { SearchDatePicker } from '../_components/SearchDatePicker';
const Page = () => {
@@ -174,19 +175,15 @@ const Page = () => {
<div className='flex items-center gap-4'>
<div className='flex items-center space-x-2'>
<Label className="w-20 text-xl text-gray-600">등록기간</Label>
<DatePicker mode={'single'}
<SearchDatePicker
selected={fromDate}
onSelect={(date: Date | undefined) => { if (date) setFromDate(date) }}
modifiers={{
disabled: { after: new Date() }
}} />
disabled={{ after: new Date() }} />
<span>~</span>
<DatePicker mode={'single'}
<SearchDatePicker
selected={toDate}
onSelect={(date: Date | undefined) => { if (date) setToDate(date) }}
modifiers={{
disabled: { after: new Date() }
}} />
disabled={{ after: new Date() }} />
<div className='flex items-center'>
<Label className="w-20 text-xl text-gray-600">등록자</Label>
<Input
+26
View File
@@ -101,6 +101,32 @@ export const postData = async (url: string, data: object): Promise<any> => {
}
};
export const postRawJson = async (url: string, data: object): Promise<any> => {
const res = await fetch(resolveApiUrl(url), {
method: "POST",
headers: withSiteIdHeaders({
"Content-Type": "application/json",
}),
body: JSON.stringify(data),
});
if (res.status === 401) {
handleUnauthorizedResponse();
}
const text = await res.text();
const body = text && text.trim() ? JSON.parse(text) : null;
if (!res.ok) {
const message =
body?.message ??
`Failed to post data: ${res.status} ${res.statusText}`;
const error = new Error(message) as Error & { status?: number; body?: any };
error.status = res.status;
error.body = body;
throw error;
}
return body;
};
const parseDownloadFileName = (contentDisposition: string | null) => {
if (!contentDisposition) return undefined;
+55 -19
View File
@@ -45,17 +45,37 @@ type UiTableProps = {
onFormDataChange?: (formData: { [key: string]: string | number | boolean }) => void; // 추가
};
type UiSelectOption =
| string
| {
value?: string | number;
label?: string;
val?: string | number;
text?: string;
hidden?: boolean;
};
type UiHeadProps = {
id: string;
title: string;
align?: string;
type?: string;
options?: string[];
options?: UiSelectOption[];
placeholder?: string;
isNumber?: boolean;
length?: number;
required?: boolean;
};
const getSelectOptionValue = (option: UiSelectOption) =>
typeof option === "string" ? option : String(option.value ?? option.val ?? "");
const getSelectOptionLabel = (option: UiSelectOption) =>
typeof option === "string" ? option : String(option.label ?? option.text ?? getSelectOptionValue(option));
const isSelectOptionHidden = (option: UiSelectOption) =>
typeof option === "string" ? false : Boolean(option.hidden);
export function VerticalTable({
headName,
tableName1,
@@ -153,6 +173,7 @@ export function VerticalTable({
{/* 컬럼 제목 */}
<TableCell className={`font-bold bg-blue-100 text-xs w-[120px] whitespace-nowrap`}>
{head.title}
{head.required ? <span className="ml-1 text-red-600">*</span> : null}
</TableCell>
{/* 데이터 값 또는 입력 필드 */}
<TableCell className="text-xs">
@@ -160,21 +181,28 @@ export function VerticalTable({
head.type === "select" ? (
<select
id={head.id}
value={String(formData[head.id]) ?? "-"}
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
onChange={(e) => handleInputChange(head.id, e.target.value)}
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
>
{head.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
{head.options?.map((option, optionIndex) => {
const optionValue = getSelectOptionValue(option);
return (
<option
key={`${head.id}-${optionValue}-${optionIndex}`}
value={optionValue}
hidden={isSelectOptionHidden(option)}
>
{getSelectOptionLabel(option)}
</option>
);
})}
</select>
) : head.type === "input" ? (
) : head.type === "input" || head.type === "date" ? (
<div className="w-full">
<input
id={head.id}
type="text"
type={head.type === "date" ? "date" : "text"}
value={String(formData[head.id] ?? "")}
onChange={(e) => {
if (head.isNumber) {
@@ -241,8 +269,9 @@ export function VerticalTable({
<TableRow key={head.id}>
{/* 컬럼 제목 */}
<TableCell className={`font-bold bg-blue-100 text-xs w-[120px] whitespace-nowrap`}>
{head.title}
</TableCell>
{head.title}
{head.required ? <span className="ml-1 text-red-600">*</span> : null}
</TableCell>
{/* 데이터 값 또는 입력 필드 */}
<TableCell className="text-xs">
{children && children[head.id] ? children[head.id] : isEditable2 ? (
@@ -253,17 +282,24 @@ export function VerticalTable({
onChange={(e) => handleInputChange(head.id, e.target.value)}
className="w-full border border-gray-300 rounded-sm px-2 py-1 text-xl border-radius-0"
>
{head.options?.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
{head.options?.map((option, optionIndex) => {
const optionValue = getSelectOptionValue(option);
return (
<option
key={`${head.id}-${optionValue}-${optionIndex}`}
value={optionValue}
hidden={isSelectOptionHidden(option)}
>
{getSelectOptionLabel(option)}
</option>
);
})}
</select>
) : head.type === "input" ? (
) : head.type === "input" || head.type === "date" ? (
<div className="w-full">
<input
id={head.id}
type={head.isNumber ? "number" : "text"}
type={head.type === "date" ? "date" : head.isNumber ? "number" : "text"}
value={formData[head.id] !== undefined ? String(formData[head.id]) : ""}
onChange={(e) => {
if (head.isNumber) {
@@ -333,4 +369,4 @@ export function VerticalTable({
<Toaster position="top-center"></Toaster>
</>
);
}
}