Files
frontend/apps/sn/app/(map-layout)/map/components/gisEdit/GisEditPipeSessionPopup.tsx
T

342 lines
13 KiB
TypeScript

"use client";
import { useEffect, useMemo, useState } from "react";
import { Button } from "@common/components/ui";
import { getData } from "@/components/lib/api";
import { VerticalTable } from "@/components/ui/verticalTable";
import type { GisEditChange, GisEditPipeBasicInfo } from "./gisEditTypes";
import { MS_SWAGE_PPL_CODES, MS_SWAGE_PPL_USE_CODES } from "../common/table";
type Props = {
change: GisEditChange;
featureData: any;
onClose: () => void;
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: [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: [EMPTY_SELECT_OPTION, "지선", "간선"] },
{ id: "floCd", title: "흐름방식", type: "select", options: [EMPTY_SELECT_OPTION, "자연유하", "압송"] },
{ id: "layCd", title: "매설위치", type: "select", options: [EMPTY_SELECT_OPTION, "도로", "하상"] },
];
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);
const toEditableText = (value: unknown) => {
const text = String(value ?? "").trim();
return text === "-" ? "" : text;
};
const isInvalidPipeLookupKey = (value: string) =>
!value || value === "-" || /^NEW-/i.test(value) || /^(null|undefined)$/i.test(value);
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({
change,
featureData,
onClose,
onSave,
}: Props) {
const isNewPipe = change.editType === "ADD";
const baseFeatureValues = useMemo(() => buildBaseFeatureValues(featureData), [featureData]);
const [basicInfoTableData, setBasicInfoTableData] = useState<Record<string, any>>({});
const [inputInfoTableData, setInputInfoTableData] = useState<Record<string, any>>(
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 {
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,
...normalizeBasicFormValues(change.basicInfo ?? {}),
};
setBasicInfoTableData(initialBasicValues);
setInputInfoTableData(buildInitialInputDraft(change));
}, [baseFeatureValues, change.changeId, isNewPipe]);
useEffect(() => {
if (isNewPipe) return;
const fcltMngNo = String(change.featureRef?.fcltMngNo ?? "").trim();
const mngInstCd = String(change.featureRef?.mngInstCd ?? "").trim();
if (isInvalidPipeLookupKey(fcltMngNo) || isInvalidPipeLookupKey(mngInstCd)) return;
let isMounted = true;
const fetchPipeInputInfo = async () => {
try {
const safeFcltMngNo = encodeURIComponent(fcltMngNo);
const safeMngInstCd = encodeURIComponent(mngInstCd);
const result = await getData(`v1/fcltppl/${safeFcltMngNo}/${safeMngInstCd}`);
if (!isMounted || !result) return;
setInputInfoTableData((previous) => ({
...previous,
...pickFields(result, PIPE_VISIBLE_INPUT_FIELD_IDS),
...pickFields(change.basicInfo ?? {}, PIPE_VISIBLE_INPUT_FIELD_IDS),
}));
} catch {
// Optional pipe input details should not block the edit session.
}
};
fetchPipeInputInfo();
return () => {
isMounted = false;
};
}, [change.changeId, change.featureRef?.fcltMngNo, change.featureRef?.mngInstCd, isNewPipe]);
const buildMergedDraft = (
nextBasicInfoTableData: Record<string, any>,
nextInputInfoTableData: Record<string, any>,
): 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);
onSave(change.changeId, buildMergedDraft(nextFormData, inputInfoTableData));
};
const handleInputInfoChange = (nextFormData: Record<string, any>) => {
setInputInfoTableData(nextFormData);
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?.usgCd ? `(${getPipeUsageLabel(basicInfoTableData.usgCd)})` : ""}
{" "}정보 <br />관리번호 : {displayManagementNo || "신규"}
</h3>
</div>
<Button
onClick={onClose}
className="flex items-center space-x-4 text-white hover:text-gray-300 focus:outline-none"
size="xs"
>
✕
</Button>
</div>
<div className="overflow-y-auto overflow-x-hidden flex-1">
<VerticalTable
headName="기본정보"
tableData={basicInfoTableRows}
headlist={basicInfoFields}
pageSize={20}
total={0}
cellClick={undefined}
onPageChange={() => {}}
isEditable={true}
onFormDataChange={handleBasicInfoChange}
/>
<VerticalTable
headName="입력정보"
tableData={inputInfoTableRows}
headlist={PIPE_INPUT_INFO_FIELDS}
pageSize={20}
total={0}
cellClick={undefined}
onPageChange={() => {}}
isEditable={true}
onFormDataChange={handleInputInfoChange}
/>
</div>
</div>
);
}