refactor(sn): modularize map and features and standardize file naming
This commit is contained in:
@@ -0,0 +1,299 @@
|
||||
/** 침입수·RDII 분석의 적용연월 선택 상태와 월 목록을 제공한다. */
|
||||
import { useState, useEffect } from "react";
|
||||
import moment from "moment";
|
||||
import { getData } from "@/shared/api/sewerage-api";
|
||||
|
||||
export type TInftwtAnls = {
|
||||
inftwtAnlsSn: number;
|
||||
aplcnYm: string;
|
||||
ctpvCd: string;
|
||||
sggCd: string;
|
||||
swtrmtFcltNm: string;
|
||||
atflCd: string;
|
||||
atflId: string;
|
||||
atflInpNm: string;
|
||||
atflHrPttnNm: string;
|
||||
atflMpngNm: string;
|
||||
atflOilqNm: string;
|
||||
atflNm: string;
|
||||
drtwSwtcRt: number;
|
||||
anlsInfo: string;
|
||||
scsYn: string;
|
||||
};
|
||||
|
||||
export type TInftwtAnlsRslt = {
|
||||
inftwtAnlsSn: number;
|
||||
pplMngNo: string;
|
||||
anlsTm: string;
|
||||
predcOilq: number;
|
||||
};
|
||||
|
||||
export type TRdiiAnls = {
|
||||
rainInfwtAnlsSn: number;
|
||||
aplcnYm: string;
|
||||
ctpvCd: string;
|
||||
sggCd: string;
|
||||
swtrmtFcltNm: string;
|
||||
atflCd: string;
|
||||
atflId: string;
|
||||
atflInpNm: string;
|
||||
atflHrPttnNm: string;
|
||||
atflMpngNm: string;
|
||||
atflRainNm: string;
|
||||
atflNm: string;
|
||||
drtwSwtcRt: number;
|
||||
anlsInfo: string;
|
||||
scsYn: string;
|
||||
srcNm: string;
|
||||
};
|
||||
|
||||
export type TRdiiAnlsRslt = {
|
||||
rainInfwtAnlsSn: number;
|
||||
pplMngNo: string;
|
||||
anlsTm: string;
|
||||
predcOilq: number;
|
||||
minq: number;
|
||||
};
|
||||
|
||||
export type TOilqData = {
|
||||
inftwtAnlsSn: number;
|
||||
pplMngNo: string;
|
||||
mtrngDt: string;
|
||||
oilq: number;
|
||||
};
|
||||
|
||||
export type TRainData = {
|
||||
rainInfwtAnlsSn: number;
|
||||
mtrngDt: string;
|
||||
amrf: number;
|
||||
};
|
||||
|
||||
function roundTo(n: number, digits: number): number {
|
||||
const factor = Math.pow(10, digits);
|
||||
return Math.round(n * factor) / factor;
|
||||
}
|
||||
|
||||
const getOptionsAplcnYm = (yyyymms: string[]): { text: string; val: string; hidden?: boolean }[] => {
|
||||
const mapped: { text: string; val: string; hidden?: boolean }[] = yyyymms.map((dateStr) => ({
|
||||
text: `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}`,
|
||||
val: dateStr,
|
||||
}));
|
||||
mapped.unshift({ val: "0", text: "선택", hidden: true });
|
||||
return mapped;
|
||||
};
|
||||
|
||||
const selectAplcnYms = async (gubun: string) => {
|
||||
if (!gubun) return [];
|
||||
|
||||
try {
|
||||
const result = await getData(`v1/${gubun}/aplcnYm`);
|
||||
if (Array.isArray(result) && result.length > 0) {
|
||||
return getOptionsAplcnYm(result);
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const useAplcnYms = (gubun: string) => {
|
||||
const [data, setData] = useState<{ text: string; val: string; hidden?: boolean }[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gubun) {
|
||||
setData([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetch = async () => {
|
||||
const result = await selectAplcnYms(gubun);
|
||||
setData(result ?? []);
|
||||
};
|
||||
|
||||
void fetch();
|
||||
}, [gubun]);
|
||||
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getOptionsInftwtAnlsInfo = (anlsArr: TInftwtAnls[]): { text: string; val: number; hidden?: boolean }[] => {
|
||||
const options: { text: string; val: number; hidden?: boolean }[] = anlsArr.map((anls) => ({
|
||||
text: anls.anlsInfo,
|
||||
val: anls.inftwtAnlsSn,
|
||||
}));
|
||||
options.unshift({ val: 0, text: "선택", hidden: true });
|
||||
return options;
|
||||
};
|
||||
|
||||
export const selectInftwtAnls = async (aplcnYm: string) => {
|
||||
try {
|
||||
const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : "";
|
||||
const result = await getData(`v1/inftwtAnls${queryString ? `?${queryString}` : ""}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const getChartDataInftwtAnlsRslt = (arr: TInftwtAnlsRslt[]) => {
|
||||
return arr.map((anlsRslt) => ({
|
||||
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("HH시"),
|
||||
val: roundTo(anlsRslt.predcOilq, 2),
|
||||
}));
|
||||
};
|
||||
|
||||
export const selectInftwtAnlsRslt = async (inftwtAnlsSn: number, pplMngNo: string) => {
|
||||
try {
|
||||
if (!inftwtAnlsSn || !pplMngNo) return [];
|
||||
const result = await getData(`v1/inftwtAnlsRslt/ppl/${inftwtAnlsSn}/${pplMngNo}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const getChartDataOilq = (arr: TOilqData[]) => {
|
||||
return arr.map((anlsRslt) => ({
|
||||
label: anlsRslt.mtrngDt,
|
||||
val: roundTo(anlsRslt.oilq, 2),
|
||||
}));
|
||||
};
|
||||
|
||||
export const selectOilq = async (inftwtAnlsSn: number, pplMngNo: string) => {
|
||||
try {
|
||||
if (!inftwtAnlsSn || !pplMngNo) return [];
|
||||
const result = await getData(`v1/inftwtAnlsRslt/oilqPpl/${inftwtAnlsSn}/${pplMngNo}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const selectPplInftwtQty = async (inftwtAnlsSn: number, pplMngNo: string) => {
|
||||
try {
|
||||
if (!inftwtAnlsSn || !pplMngNo) return 0;
|
||||
const result = await getData(`v1/inftwtAnlsRslt/pplInftwtQty/${inftwtAnlsSn}/${pplMngNo}`);
|
||||
if (Array.isArray(result) && result.length > 0) {
|
||||
return result[0].avg_day_flow;
|
||||
}
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return 0;
|
||||
};
|
||||
|
||||
const buildPplMngNoCandidates = (pplMngNo: string) => {
|
||||
const normalized = String(pplMngNo ?? "").trim();
|
||||
if (!normalized) return [];
|
||||
const withoutPrefix = normalized.replace(/^L/, "");
|
||||
const withPrefix = withoutPrefix ? `L${withoutPrefix}` : "";
|
||||
return Array.from(new Set([normalized, withPrefix, withoutPrefix].filter(Boolean)));
|
||||
};
|
||||
|
||||
export const selectPplRdiiQty = async (rainInfwtAnlsSn: number, pplMngNo: string) => {
|
||||
if (!rainInfwtAnlsSn || !pplMngNo) return null;
|
||||
|
||||
for (const candidate of buildPplMngNoCandidates(pplMngNo)) {
|
||||
try {
|
||||
const result = await getData(`v1/rdiiAnlsRslt/pplRdiiQty/${rainInfwtAnlsSn}/${candidate}`);
|
||||
if (result) {
|
||||
return result;
|
||||
}
|
||||
} catch {
|
||||
// resultOnly mode fallback candidates should not raise console noise
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const getOptionsRdiiAnlsInfo = (anlsArr: TRdiiAnls[]): { text: string; val: number; hidden?: boolean }[] => {
|
||||
const options: { text: string; val: number; hidden?: boolean }[] = anlsArr.map((anls) => ({
|
||||
text: anls.anlsInfo,
|
||||
val: anls.rainInfwtAnlsSn,
|
||||
}));
|
||||
options.unshift({ val: 0, text: "선택", hidden: true });
|
||||
return options;
|
||||
};
|
||||
|
||||
export const selectRdiiAnls = async (aplcnYm: string) => {
|
||||
try {
|
||||
const queryString = aplcnYm ? `aplcnYmFrom=${aplcnYm}&aplcnYmTo=${aplcnYm}` : "";
|
||||
const result = await getData(`v1/rdiiAnls${queryString ? `?${queryString}` : ""}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const getChartDataRdiiAnlsRslt = (arr: TRdiiAnlsRslt[]) => {
|
||||
return arr.map((anlsRslt) => ({
|
||||
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
|
||||
lineVal0: roundTo(anlsRslt.predcOilq, 2),
|
||||
barVal0: 0,
|
||||
}));
|
||||
};
|
||||
|
||||
export const getChartDataRdiiAnlsRsltMinq = (arr: TRdiiAnlsRslt[]) => {
|
||||
return arr.map((anlsRslt) => ({
|
||||
label: moment(anlsRslt.anlsTm, "YYYYMMDDHHmmss").format("MM-DD HH시"),
|
||||
val: roundTo(anlsRslt.minq, 2),
|
||||
}));
|
||||
};
|
||||
|
||||
export const selectRdiiAnlsRslt = async (rainInfwtAnlsSn: number, pplMngNo: string) => {
|
||||
if (!rainInfwtAnlsSn || !pplMngNo) return [];
|
||||
|
||||
for (const candidate of buildPplMngNoCandidates(pplMngNo)) {
|
||||
try {
|
||||
const result = await getData(`v1/rdiiAnlsRslt/ppl/${rainInfwtAnlsSn}/${candidate}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
// resultOnly mode fallback candidates should not raise console noise
|
||||
}
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const selectRainData = async (rainInfwtAnlsSn: number) => {
|
||||
try {
|
||||
if (!rainInfwtAnlsSn) return [];
|
||||
const result = await getData(`v1/rdiiAnlsRslt/rainData/${rainInfwtAnlsSn}`);
|
||||
if (result && result.numberOfElements > 0) {
|
||||
return result.content;
|
||||
}
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const getChartDataRainData = (arr: TRainData[]) => {
|
||||
return arr.map((data) => ({
|
||||
label: moment(data.mtrngDt, "YYYY-MM-DD HH:mm:ss").format("MM-DD HH시"),
|
||||
lineVal0: 0,
|
||||
barVal0: roundTo(data.amrf, 2),
|
||||
}));
|
||||
};
|
||||
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* 화면명: 침입수 분석
|
||||
* 침입수 분석 조건 입력, 실행 상태와 분석결과를 표시한다.
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import moment from "moment";
|
||||
|
||||
import {
|
||||
CHART_FORM,
|
||||
type ChartConfig,
|
||||
MainChart,
|
||||
StandardFormField,
|
||||
StandardFormSection,
|
||||
StandardPopupLayout,
|
||||
} from "@common/business_components";
|
||||
import { SelectBox } from "@common/business_components/ui";
|
||||
import { Button, Input } from "@common/components";
|
||||
|
||||
import type { TInftwtAnls, TInftwtAnlsRslt, TOilqData } from "@/features/analysis-charts/model/aplcn-yms";
|
||||
import * as fn from "@/features/analysis-charts/model/aplcn-yms";
|
||||
|
||||
type ModalOpenProp = {
|
||||
pplMngNo?: string;
|
||||
inftwtAnlsSn?: number;
|
||||
aplcnYm?: string;
|
||||
analysisInfo?: string;
|
||||
resultOnly?: boolean;
|
||||
};
|
||||
|
||||
type DataType = {
|
||||
label: string;
|
||||
val: number;
|
||||
};
|
||||
|
||||
const INITIAL_ANALYSIS_OPTIONS = [{ val: 0, text: "선택" }];
|
||||
|
||||
const InfilChart = ({
|
||||
pplMngNo = "",
|
||||
inftwtAnlsSn = 0,
|
||||
aplcnYm = "",
|
||||
analysisInfo = "",
|
||||
resultOnly = false,
|
||||
}: ModalOpenProp) => {
|
||||
const [selectedAplcnYm, setSelectedAplcnYm] = useState("");
|
||||
const [inftwtAnlss, setInftwtAnlss] = useState<TInftwtAnls[]>([]);
|
||||
const [inftwtAnlsInfos, setInftwtAnlsInfos] = useState<
|
||||
{ text: string; val: number; hidden?: boolean }[]
|
||||
>(INITIAL_ANALYSIS_OPTIONS);
|
||||
const [inftwtAnls, setInftwtAnls] = useState<TInftwtAnls | null>(null);
|
||||
const [selectedInftwtAnls, setSelectedInftwtAnls] = useState<number>(0);
|
||||
const [chartData, setChartData] = useState<{
|
||||
chartData1: DataType[];
|
||||
chartData2: DataType[];
|
||||
}>({
|
||||
chartData1: [],
|
||||
chartData2: [],
|
||||
});
|
||||
const [inftwtQty, setInftwtQty] = useState<string>("0");
|
||||
|
||||
const aplcnYms = fn.useAplcnYms("inftwtAnlsRslt");
|
||||
const normalizedPplMngNo = pplMngNo ? `L${pplMngNo}` : "";
|
||||
const isResultOnlyMode =
|
||||
resultOnly && inftwtAnlsSn > 0 && Boolean(normalizedPplMngNo);
|
||||
|
||||
const chartForm = CHART_FORM.LINE;
|
||||
const chartConfig = {
|
||||
chartData1: { label: "순오수량", color: "red" },
|
||||
chartData2: { label: "실측하수량", color: "orange" },
|
||||
} as ChartConfig;
|
||||
|
||||
const hasChartData = useMemo(() => {
|
||||
return chartData.chartData1.length > 0 || chartData.chartData2.length > 0;
|
||||
}, [chartData]);
|
||||
|
||||
const calculateFallbackInftwtQty = (
|
||||
inftwtAnlsRslt: TInftwtAnlsRslt[],
|
||||
oilqRows: TOilqData[],
|
||||
) => {
|
||||
const predcValues = inftwtAnlsRslt
|
||||
.map((item) => Number(item.predcOilq))
|
||||
.filter((value) => Number.isFinite(value));
|
||||
const oilqValues = oilqRows
|
||||
.map((item) => Number(item.oilq))
|
||||
.filter((value) => Number.isFinite(value));
|
||||
|
||||
if (predcValues.length === 0 || oilqValues.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const avgPredc =
|
||||
predcValues.reduce((sum, value) => sum + value, 0) / predcValues.length;
|
||||
const avgOilq =
|
||||
oilqValues.reduce((sum, value) => sum + value, 0) / oilqValues.length;
|
||||
const dailyQty = (avgOilq - avgPredc) * 24;
|
||||
return Math.round(dailyQty / 10) * 10;
|
||||
};
|
||||
|
||||
const resetState = () => {
|
||||
setSelectedAplcnYm("");
|
||||
setInftwtAnlss([]);
|
||||
setInftwtAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
setInftwtAnls(null);
|
||||
setSelectedInftwtAnls(0);
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
setInftwtQty("0");
|
||||
};
|
||||
|
||||
const loadResultChart = async (targetInftwtAnlsSn: number) => {
|
||||
if (!targetInftwtAnlsSn || !normalizedPplMngNo) {
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
setInftwtQty("0");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const [inftwtAnlsRslt, oilq, qty] = await Promise.all([
|
||||
fn.selectInftwtAnlsRslt(targetInftwtAnlsSn, normalizedPplMngNo),
|
||||
fn.selectOilq(targetInftwtAnlsSn, normalizedPplMngNo).catch((err) => {
|
||||
console.error("selectOilq 에러:", err);
|
||||
return [];
|
||||
}),
|
||||
fn
|
||||
.selectPplInftwtQty(targetInftwtAnlsSn, normalizedPplMngNo)
|
||||
.catch((err) => {
|
||||
console.error("selectPplInftwtQty 에러:", err);
|
||||
return 0;
|
||||
}),
|
||||
]);
|
||||
|
||||
setChartData({
|
||||
chartData1: fn.getChartDataInftwtAnlsRslt(inftwtAnlsRslt ?? []),
|
||||
chartData2: fn.getChartDataOilq(oilq ?? []),
|
||||
});
|
||||
|
||||
const fallbackQty = calculateFallbackInftwtQty(
|
||||
inftwtAnlsRslt ?? [],
|
||||
oilq ?? [],
|
||||
);
|
||||
const normalizedQty = Number(qty ?? Number.NaN);
|
||||
const resolvedQty =
|
||||
Number.isFinite(normalizedQty) &&
|
||||
!(normalizedQty === 0 && fallbackQty !== 0)
|
||||
? normalizedQty
|
||||
: fallbackQty;
|
||||
|
||||
if (
|
||||
!Number.isFinite(normalizedQty) ||
|
||||
(normalizedQty === 0 && fallbackQty !== 0)
|
||||
) {
|
||||
console.warn(
|
||||
"Inftwt qty API returned empty or zero; using chart-data fallback qty.",
|
||||
{
|
||||
apiQty: qty,
|
||||
fallbackQty,
|
||||
resultCount: inftwtAnlsRslt?.length ?? 0,
|
||||
oilqCount: oilq?.length ?? 0,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
setInftwtQty(resolvedQty.toLocaleString("ko-KR"));
|
||||
} catch (error) {
|
||||
console.error("침입수 분석결과 차트 조회 중 오류:", error);
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
setInftwtQty("0");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isResultOnlyMode) return;
|
||||
|
||||
setSelectedAplcnYm(aplcnYm);
|
||||
setSelectedInftwtAnls(inftwtAnlsSn);
|
||||
setInftwtAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
void loadResultChart(inftwtAnlsSn);
|
||||
}, [aplcnYm, inftwtAnlsSn, isResultOnlyMode, normalizedPplMngNo]);
|
||||
|
||||
const handleAplcnYmChange = async (val: string | number) => {
|
||||
const selectedValue = String(val);
|
||||
|
||||
setSelectedAplcnYm(selectedValue);
|
||||
setInftwtAnlss([]);
|
||||
setInftwtAnls(null);
|
||||
setSelectedInftwtAnls(0);
|
||||
setInftwtQty("0");
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
|
||||
if (!selectedValue || selectedValue === "0") {
|
||||
setInftwtAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fn.selectInftwtAnls(selectedValue);
|
||||
const list = data ?? [];
|
||||
setInftwtAnlss(list);
|
||||
setInftwtAnlsInfos(fn.getOptionsInftwtAnlsInfo(list));
|
||||
} catch (error) {
|
||||
console.error("selectInftwtAnls 에러:", error);
|
||||
setInftwtAnlss([]);
|
||||
setInftwtAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
}
|
||||
};
|
||||
|
||||
const handleInftwtAnlsSnChange = (val: string | number) => {
|
||||
const selectedValue = Number(val);
|
||||
|
||||
setSelectedInftwtAnls(selectedValue);
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
setInftwtQty("0");
|
||||
|
||||
if (selectedValue === 0) {
|
||||
setInftwtAnls(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedAnls =
|
||||
inftwtAnlss.find((anls) => anls.inftwtAnlsSn === selectedValue) ?? null;
|
||||
setInftwtAnls(selectedAnls);
|
||||
};
|
||||
|
||||
const infilRsltChart = async () => {
|
||||
if (!selectedAplcnYm || selectedInftwtAnls === 0 || !normalizedPplMngNo) {
|
||||
setChartData({ chartData1: [], chartData2: [] });
|
||||
setInftwtQty("0");
|
||||
return;
|
||||
}
|
||||
|
||||
await loadResultChart(selectedInftwtAnls);
|
||||
};
|
||||
|
||||
/** 분석 메타데이터를 공통 표형 폼의 읽기 전용 셀로 표시한다. */
|
||||
const renderInfoField = (
|
||||
label: string,
|
||||
value?: string | number | null,
|
||||
span: 1 | 2 = 1,
|
||||
) => (
|
||||
<StandardFormField label={label} columns={2} span={span}>
|
||||
<Input className="w-full" value={value ?? ""} readOnly />
|
||||
</StandardFormField>
|
||||
);
|
||||
|
||||
const handleReset = () => {
|
||||
resetState();
|
||||
};
|
||||
|
||||
const renderResultPanel = () => (
|
||||
<section className="card card-border !m-0 min-w-0 overflow-hidden !p-[1.2rem]">
|
||||
<StandardFormSection title="침입수 분석결과" columns={2} wideLabels>
|
||||
<StandardFormField label="상수사용량 적용연월" columns={2}>
|
||||
<div className="flex min-h-[3.2rem] items-center justify-end text-[1.35rem] font-semibold tabular-nums text-foreground">
|
||||
{selectedAplcnYm
|
||||
? moment(selectedAplcnYm, "YYYYMM").format("YYYY-MM")
|
||||
: "-"}
|
||||
</div>
|
||||
</StandardFormField>
|
||||
<StandardFormField label="침입수량 산정결과" columns={2}>
|
||||
<div className="flex min-h-[3.2rem] items-center justify-end gap-3 whitespace-nowrap text-foreground">
|
||||
<span className="text-[1.15rem] text-muted-foreground">
|
||||
침입수량
|
||||
</span>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<strong className="text-[1.5rem] font-semibold tabular-nums">
|
||||
{inftwtQty}
|
||||
</strong>
|
||||
<span className="text-[1.1rem]">m³/d</span>
|
||||
</div>
|
||||
</div>
|
||||
</StandardFormField>
|
||||
</StandardFormSection>
|
||||
|
||||
<section className="mt-[1.2rem] overflow-hidden rounded-sm border border-border bg-background">
|
||||
<h4 className="border-b border-border bg-container px-4 py-3 text-[1.4rem] font-semibold text-label">
|
||||
침입수량 그래프
|
||||
</h4>
|
||||
<div className="min-h-[30rem] p-3">
|
||||
{hasChartData ? (
|
||||
<MainChart
|
||||
chartConfig={chartConfig}
|
||||
chartForm={chartForm}
|
||||
chartData={chartData}
|
||||
chartTitle=""
|
||||
yFieldText="유량(m³/h)"
|
||||
yFieldText2=""
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="flex min-h-[30rem] items-center justify-center text-[1.3rem] text-muted-foreground"
|
||||
role="status"
|
||||
>
|
||||
조회된 데이터가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
|
||||
const renderDefaultBody = () => (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-[1.2rem]">
|
||||
<StandardFormSection title="침입수 분석 조건" columns={2}>
|
||||
<StandardFormField label="상수사용월" columns={2}>
|
||||
<SelectBox
|
||||
className="w-full"
|
||||
selectClass="w-full"
|
||||
label=""
|
||||
selectArray={aplcnYms}
|
||||
value={selectedAplcnYm}
|
||||
onSelectValue={handleAplcnYmChange}
|
||||
/>
|
||||
</StandardFormField>
|
||||
<StandardFormField label="분석정보" columns={2}>
|
||||
<SelectBox
|
||||
className="w-full"
|
||||
selectClass="w-full"
|
||||
label=""
|
||||
selectArray={inftwtAnlsInfos}
|
||||
value={selectedInftwtAnls}
|
||||
onSelectValue={handleInftwtAnlsSnChange}
|
||||
/>
|
||||
</StandardFormField>
|
||||
{renderInfoField("오수전환율", inftwtAnls?.drtwSwtcRt ?? "")}
|
||||
{renderInfoField(
|
||||
"시간패턴 파일명",
|
||||
inftwtAnls?.atflHrPttnNm ?? "",
|
||||
)}
|
||||
{renderInfoField("수용가-맨홀 매칭", inftwtAnls?.atflMpngNm ?? "")}
|
||||
{renderInfoField("관망도 파일명", inftwtAnls?.atflInpNm ?? "")}
|
||||
{renderInfoField("유량 파일명", inftwtAnls?.atflOilqNm ?? "", 2)}
|
||||
</StandardFormSection>
|
||||
|
||||
{renderResultPanel()}
|
||||
</div>
|
||||
);
|
||||
|
||||
/** 조회·초기화 뒤에 창 닫기 성격의 취소 액션을 항상 마지막에 배치한다. */
|
||||
const renderFooterActions = () => (
|
||||
<div className="flex w-full items-center justify-center gap-2">
|
||||
{!isResultOnlyMode ? (
|
||||
<>
|
||||
<Button type="button" onClick={infilRsltChart}>
|
||||
조회
|
||||
</Button>
|
||||
<Button type="button" color="white" onClick={handleReset}>
|
||||
초기화
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<Button type="button" color="white" onClick={() => window.close()}>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<StandardPopupLayout
|
||||
title={isResultOnlyMode ? "침입수 분석결과" : "침입수 분석"}
|
||||
bodyClassName="overflow-x-hidden"
|
||||
footer={renderFooterActions()}
|
||||
showDefaultCancelAction={false}
|
||||
>
|
||||
{isResultOnlyMode ? renderResultPanel() : renderDefaultBody()}
|
||||
</StandardPopupLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(InfilChart);
|
||||
@@ -0,0 +1,348 @@
|
||||
/**
|
||||
* 화면명: RDII 분석
|
||||
* RDII 분석 조건 입력, 실행 상태와 분석결과를 표시한다.
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import moment from "moment";
|
||||
|
||||
import {
|
||||
CHART_FORM,
|
||||
type ChartConfig,
|
||||
MainChart,
|
||||
StandardFormField,
|
||||
StandardFormSection,
|
||||
StandardPopupLayout,
|
||||
} from "@common/business_components";
|
||||
import { SelectBox } from "@common/business_components/ui";
|
||||
import { Button, Input } from "@common/components";
|
||||
|
||||
import type { TRdiiAnls } from "@/features/analysis-charts/model/aplcn-yms";
|
||||
import * as fn from "@/features/analysis-charts/model/aplcn-yms";
|
||||
|
||||
type ModalOpenProp = {
|
||||
pplMngNo?: string;
|
||||
rainInfwtAnlsSn?: number;
|
||||
aplcnYm?: string;
|
||||
analysisInfo?: string;
|
||||
resultOnly?: boolean;
|
||||
};
|
||||
|
||||
type LineBarChartData = {
|
||||
label: string;
|
||||
lineVal0: number;
|
||||
barVal0: number;
|
||||
};
|
||||
|
||||
const INITIAL_ANALYSIS_OPTIONS = [{ val: 0, text: "선택" }];
|
||||
|
||||
const normalizePplMngNo = (value: string) => {
|
||||
const trimmed = String(value ?? "").trim();
|
||||
if (!trimmed) return "";
|
||||
return trimmed.startsWith("L") ? trimmed : `L${trimmed}`;
|
||||
};
|
||||
|
||||
const RdiiChart = ({
|
||||
pplMngNo = "",
|
||||
rainInfwtAnlsSn = 0,
|
||||
aplcnYm = "",
|
||||
analysisInfo = "",
|
||||
resultOnly = false,
|
||||
}: ModalOpenProp) => {
|
||||
const [selectedAplcnYm, setSelectedAplcnYm] = useState("");
|
||||
const [rdiiAnlss, setRdiiAnlss] = useState<TRdiiAnls[]>([]);
|
||||
const [rdiiAnlsInfos, setRdiiAnlsInfos] = useState<
|
||||
{ text: string; val: number; hidden?: boolean }[]
|
||||
>(INITIAL_ANALYSIS_OPTIONS);
|
||||
const [rdiiAnls, setRdiiAnls] = useState<TRdiiAnls | null>(null);
|
||||
const [selectedRainInfwtAnlsSn, setSelectedRainInfwtAnlsSn] =
|
||||
useState<number>(0);
|
||||
const [chartData, setChartData] = useState<LineBarChartData[]>([]);
|
||||
const [rdiiQty, setRdiiQty] = useState<string>("0");
|
||||
const [rainTotal, setRainTotal] = useState<string>("0");
|
||||
const [totalVolume, setTotalVolume] = useState<string>("0");
|
||||
|
||||
const normalizedPplMngNo = normalizePplMngNo(pplMngNo);
|
||||
const isResultOnlyMode =
|
||||
resultOnly && rainInfwtAnlsSn > 0 && Boolean(normalizedPplMngNo);
|
||||
const aplcnYms = fn.useAplcnYms(isResultOnlyMode ? "" : "rdiiAnlsRslt");
|
||||
|
||||
const chartForm = CHART_FORM.LINEBAR2;
|
||||
const chartConfig = {
|
||||
barVal0: {
|
||||
label: "강수량",
|
||||
color: "#33AAFF",
|
||||
},
|
||||
lineVal0: {
|
||||
label: "RDII",
|
||||
color: "#FF0000",
|
||||
},
|
||||
} as ChartConfig;
|
||||
|
||||
const hasChartData = useMemo(() => chartData.length > 0, [chartData]);
|
||||
|
||||
const resetState = () => {
|
||||
setSelectedAplcnYm("");
|
||||
setRdiiAnlss([]);
|
||||
setRdiiAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
setRdiiAnls(null);
|
||||
setSelectedRainInfwtAnlsSn(0);
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
};
|
||||
|
||||
const loadResultChart = async (targetRainInfwtAnlsSn: number) => {
|
||||
if (!targetRainInfwtAnlsSn || !normalizedPplMngNo) {
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const [rsltData, rainData, qtyData] = await Promise.all([
|
||||
fn.selectRdiiAnlsRslt(targetRainInfwtAnlsSn, normalizedPplMngNo),
|
||||
fn.selectRainData(targetRainInfwtAnlsSn),
|
||||
fn.selectPplRdiiQty(targetRainInfwtAnlsSn, normalizedPplMngNo),
|
||||
]);
|
||||
|
||||
const rsltDataFormatted = fn.getChartDataRdiiAnlsRslt(rsltData ?? []);
|
||||
const rainDataFormatted = fn.getChartDataRainData(rainData ?? []);
|
||||
const rainMap = new Map(
|
||||
rainDataFormatted.map((item) => [item.label, item.barVal0]),
|
||||
);
|
||||
|
||||
rsltDataFormatted.forEach((item) => {
|
||||
const matchedVal = rainMap.get(item.label);
|
||||
if (matchedVal !== undefined) {
|
||||
item.barVal0 = matchedVal;
|
||||
}
|
||||
});
|
||||
|
||||
setChartData(rsltDataFormatted);
|
||||
|
||||
const avgRdii = Number(qtyData?.rdiih ?? 0);
|
||||
const appliedRainfall = Number(qtyData?.raintotal ?? 0);
|
||||
const rdiiPerRainfall =
|
||||
qtyData?.raintotal && qtyData?.raintotal !== 0
|
||||
? Math.round(
|
||||
(avgRdii * Number(qtyData?.sustaintime ?? 0)) / qtyData.raintotal,
|
||||
)
|
||||
: 0;
|
||||
|
||||
setRdiiQty(Math.round(avgRdii * 24).toLocaleString("ko-KR"));
|
||||
setRainTotal(appliedRainfall.toLocaleString("ko-KR"));
|
||||
setTotalVolume(rdiiPerRainfall.toLocaleString("ko-KR"));
|
||||
} catch (error) {
|
||||
console.error("RDII 분석결과 차트 조회 중 오류:", error);
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isResultOnlyMode) return;
|
||||
|
||||
setSelectedAplcnYm(aplcnYm);
|
||||
setSelectedRainInfwtAnlsSn(rainInfwtAnlsSn);
|
||||
setRdiiAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
void loadResultChart(rainInfwtAnlsSn);
|
||||
}, [aplcnYm, isResultOnlyMode, normalizedPplMngNo, rainInfwtAnlsSn]);
|
||||
|
||||
const handleAplcnYmChange = async (val: string | number) => {
|
||||
const selectedValue = String(val);
|
||||
|
||||
setSelectedAplcnYm(selectedValue);
|
||||
setRdiiAnlss([]);
|
||||
setRdiiAnls(null);
|
||||
setSelectedRainInfwtAnlsSn(0);
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
|
||||
if (!selectedValue || selectedValue === "0") {
|
||||
setRdiiAnlsInfos(INITIAL_ANALYSIS_OPTIONS);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await fn.selectRdiiAnls(selectedValue);
|
||||
const list = data ?? [];
|
||||
setRdiiAnlss(list);
|
||||
setRdiiAnlsInfos(fn.getOptionsRdiiAnlsInfo(list));
|
||||
};
|
||||
|
||||
const handleRdiiAnlsSnChange = (val: string | number) => {
|
||||
const selectedValue = Number(val);
|
||||
|
||||
setSelectedRainInfwtAnlsSn(selectedValue);
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
|
||||
if (selectedValue === 0) {
|
||||
setRdiiAnls(null);
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedAnls =
|
||||
rdiiAnlss.find((anls) => anls.rainInfwtAnlsSn === selectedValue) ?? null;
|
||||
setRdiiAnls(selectedAnls);
|
||||
};
|
||||
|
||||
const fetchFilteredData = async () => {
|
||||
if (!selectedRainInfwtAnlsSn || !normalizedPplMngNo) {
|
||||
setChartData([]);
|
||||
setRdiiQty("0");
|
||||
setRainTotal("0");
|
||||
setTotalVolume("0");
|
||||
return;
|
||||
}
|
||||
|
||||
await loadResultChart(selectedRainInfwtAnlsSn);
|
||||
};
|
||||
|
||||
/** 분석 메타데이터를 공통 표형 폼의 읽기 전용 셀로 표시한다. */
|
||||
const renderInfoField = (
|
||||
label: string,
|
||||
value?: string | number | null,
|
||||
span: 1 | 2 = 1,
|
||||
) => (
|
||||
<StandardFormField label={label} columns={2} span={span}>
|
||||
<Input className="w-full" value={value ?? ""} readOnly />
|
||||
</StandardFormField>
|
||||
);
|
||||
|
||||
const renderResultPanel = () => (
|
||||
<section className="card card-border !m-0 min-w-0 overflow-hidden !p-[1.2rem]">
|
||||
<StandardFormSection title="RDII 분석결과" columns={2} wideLabels>
|
||||
<StandardFormField label="상수사용 적용연월" columns={2}>
|
||||
<div className="flex min-h-[3.2rem] items-center justify-end text-[1.35rem] font-semibold tabular-nums text-foreground">
|
||||
{selectedAplcnYm
|
||||
? moment(selectedAplcnYm, "YYYYMM").format("YYYY-MM")
|
||||
: "-"}
|
||||
</div>
|
||||
</StandardFormField>
|
||||
<StandardFormField label="강우유입수량 분석결과" columns={2}>
|
||||
<div className="grid min-h-[3.2rem] grid-cols-[minmax(0,1fr)_7rem_5rem] items-center gap-x-3 gap-y-1 text-[1.1rem] text-foreground">
|
||||
<span className="text-right text-muted-foreground">평균 RDII</span>
|
||||
<strong className="text-right text-[1.35rem] font-semibold tabular-nums">
|
||||
{rdiiQty}
|
||||
</strong>
|
||||
<span>m³/d</span>
|
||||
<span className="text-right text-muted-foreground">적용 강우량</span>
|
||||
<strong className="text-right text-[1.35rem] font-semibold tabular-nums">
|
||||
{rainTotal}
|
||||
</strong>
|
||||
<span>mm</span>
|
||||
<span className="text-right text-muted-foreground">
|
||||
강우량 대비 RDII
|
||||
</span>
|
||||
<strong className="text-right text-[1.35rem] font-semibold tabular-nums">
|
||||
{totalVolume}
|
||||
</strong>
|
||||
<span>m³/mm</span>
|
||||
</div>
|
||||
</StandardFormField>
|
||||
</StandardFormSection>
|
||||
|
||||
<section className="mt-[1.2rem] overflow-hidden rounded-sm border border-border bg-background">
|
||||
<h4 className="border-b border-border bg-container px-4 py-3 text-[1.4rem] font-semibold text-label">
|
||||
RDII 그래프
|
||||
</h4>
|
||||
<div className="min-h-[30rem] p-3">
|
||||
{hasChartData ? (
|
||||
<MainChart
|
||||
chartConfig={chartConfig}
|
||||
chartForm={chartForm}
|
||||
chartData={chartData}
|
||||
chartTitle=""
|
||||
yFieldText2="강수량(mm)"
|
||||
yFieldText="유량(m³/h)"
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="flex min-h-[30rem] items-center justify-center text-[1.3rem] text-muted-foreground"
|
||||
role="status"
|
||||
>
|
||||
조회된 데이터가 없습니다.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
);
|
||||
|
||||
const renderDefaultBody = () => (
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-[1.2rem]">
|
||||
<StandardFormSection title="RDII 분석 조건" columns={2}>
|
||||
<StandardFormField label="상수사용월" columns={2}>
|
||||
<SelectBox
|
||||
className="w-full"
|
||||
selectClass="w-full"
|
||||
label=""
|
||||
selectArray={aplcnYms}
|
||||
value={selectedAplcnYm}
|
||||
onSelectValue={handleAplcnYmChange}
|
||||
/>
|
||||
</StandardFormField>
|
||||
<StandardFormField label="분석정보" columns={2}>
|
||||
<SelectBox
|
||||
className="w-full"
|
||||
selectClass="w-full"
|
||||
label=""
|
||||
selectArray={rdiiAnlsInfos}
|
||||
value={selectedRainInfwtAnlsSn}
|
||||
onSelectValue={handleRdiiAnlsSnChange}
|
||||
/>
|
||||
</StandardFormField>
|
||||
{renderInfoField("오수전환율", rdiiAnls?.drtwSwtcRt ?? "")}
|
||||
{renderInfoField("수용가-맨홀 매칭", rdiiAnls?.atflMpngNm ?? "")}
|
||||
{renderInfoField("관망도 파일명", rdiiAnls?.atflInpNm ?? "")}
|
||||
{renderInfoField("강우 파일명", rdiiAnls?.atflRainNm ?? "")}
|
||||
{renderInfoField("RTK계수 출처", rdiiAnls?.srcNm ?? "", 2)}
|
||||
</StandardFormSection>
|
||||
|
||||
{renderResultPanel()}
|
||||
</div>
|
||||
);
|
||||
|
||||
/** 조회·초기화 뒤에 창 닫기 성격의 취소 액션을 항상 마지막에 배치한다. */
|
||||
const renderFooterActions = () => (
|
||||
<div className="flex w-full items-center justify-center gap-2">
|
||||
{!isResultOnlyMode ? (
|
||||
<>
|
||||
<Button type="button" onClick={fetchFilteredData}>
|
||||
조회
|
||||
</Button>
|
||||
<Button type="button" color="white" onClick={resetState}>
|
||||
초기화
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<Button type="button" color="white" onClick={() => window.close()}>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<StandardPopupLayout
|
||||
title={isResultOnlyMode ? "RDII 분석결과" : "RDII 분석"}
|
||||
bodyClassName="overflow-x-hidden"
|
||||
footer={renderFooterActions()}
|
||||
showDefaultCancelAction={false}
|
||||
>
|
||||
{isResultOnlyMode ? renderResultPanel() : renderDefaultBody()}
|
||||
</StandardPopupLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default React.memo(RdiiChart);
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { getData, postRawJson } from "@/components/lib/api";
|
||||
import { getData, postRawJson } from "@/shared/api/sewerage-api";
|
||||
import type {
|
||||
CfmtnBgtCode,
|
||||
CfmtnBgtPage,
|
||||
+6
-6
@@ -7,7 +7,7 @@ import { getSnRowNumber } from "@/shared/lib/row-number";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
import useOnsemiroAddrStore from "@/app/store/useOnsemiroAddrStore";
|
||||
import useOnsemiroAddrStore from "@/entities/reference-data/model/onsemiro-address-store";
|
||||
import {
|
||||
StandardDataTable,
|
||||
StandardPopupLayout,
|
||||
@@ -29,9 +29,9 @@ import {
|
||||
type PaginationState,
|
||||
} from "@tanstack/react-table";
|
||||
|
||||
import { postPopupMessageAndClose } from "../../windowPopup/lib/popupMessage";
|
||||
import type { WindowPopupContentProps } from "../../windowPopup/model/types";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "../../windowPopup/model/types";
|
||||
import { postPopupMessageAndClose } from "../../window-popup/lib/popup-message";
|
||||
import type { WindowPopupContentProps } from "../../window-popup/model/types";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "../../window-popup/model/types";
|
||||
import {
|
||||
getCfmtnBgtCodes,
|
||||
getCfmtnBgtPage,
|
||||
@@ -44,8 +44,8 @@ import type {
|
||||
CfmtnBgtRow,
|
||||
} from "../model/cfmtn-bgt-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import PopupSearchPanel from "@/features/windowPopup/ui/PopupSearchPanel";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import PopupSearchPanel from "@/features/window-popup/ui/popup-search-panel";
|
||||
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
|
||||
|
||||
type SelectOption = { text: string; val: string };
|
||||
+1
-6
@@ -5,12 +5,7 @@ import type {
|
||||
CtyFldngPrvtnBizSaveRequest,
|
||||
} from "../model/cty-fldng-prvtn-biz-types";
|
||||
|
||||
import {
|
||||
deleteData,
|
||||
getData,
|
||||
postRawJson,
|
||||
putData,
|
||||
} from "@/components/lib/api";
|
||||
import { deleteData, getData, postRawJson, putData } from "@/shared/api/sewerage-api";
|
||||
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
|
||||
|
||||
const API_PATH = "v1/ctyFldngPrvtnBiz";
|
||||
+3
-3
@@ -30,10 +30,10 @@ import type {
|
||||
CtyFldngPrvtnBizSaveRequest,
|
||||
} from "../model/cty-fldng-prvtn-biz-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import { useOperBusinessCommonCodes } from "@/shared/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/store/useStore";
|
||||
import { useOperBusinessCommonCodes } from "@/entities/business/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
|
||||
const DETAIL_META = [
|
||||
{ code: "EM", title: "중점관리지역 지정" },
|
||||
+3
-3
@@ -41,9 +41,9 @@ import type {
|
||||
CtyFldngPrvtnBizPage,
|
||||
} from "../model/cty-fldng-prvtn-biz-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { useOperBusinessCommonCodes } from "@/shared/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/store/useStore";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { useOperBusinessCommonCodes } from "@/entities/business/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
|
||||
const PAGE_SIZE = 10;
|
||||
const ALL = { text: "전체", val: "0" };
|
||||
@@ -1,11 +1,11 @@
|
||||
/** 준설 조회·등록·수정·삭제와 최근접 관로 HTTP 계약을 담당한다. */
|
||||
import {
|
||||
deleteData,
|
||||
getBlobData,
|
||||
getRawJson,
|
||||
postRawJson,
|
||||
putData,
|
||||
} from "@/components/lib/api";
|
||||
} from "@/shared/api/sewerage-api";
|
||||
import { getBlobData } from "@/shared/api/file-api";
|
||||
import { requestGridExcel } from "@/shared/api/grid-export";
|
||||
import { isDredgingBackendEnabled } from "./backend-mode";
|
||||
import { toDredgingApiError } from "./dredging-error";
|
||||
@@ -40,7 +40,9 @@ export type DredgingGridQuery = {
|
||||
sort?: string;
|
||||
};
|
||||
|
||||
export const fetchDredgingGridPage = async (query: DredgingGridQuery): Promise<{
|
||||
export const fetchDredgingGridPage = async (
|
||||
query: DredgingGridQuery,
|
||||
): Promise<{
|
||||
content: Array<Record<string, unknown> & { recordIds: string[] }>;
|
||||
totalElements: number;
|
||||
number: number;
|
||||
@@ -55,12 +57,18 @@ export const fetchDredgingGridPage = async (query: DredgingGridQuery): Promise<{
|
||||
};
|
||||
|
||||
/** 적용 조건 전체의 서버 XLSX를 받는다. page/size는 다운로드에 전달하지 않는다. */
|
||||
export const downloadDredgingGridExcel = (query: Omit<DredgingGridQuery, "page" | "size">): Promise<void> => {
|
||||
export const downloadDredgingGridExcel = (
|
||||
query: Omit<DredgingGridQuery, "page" | "size">,
|
||||
): Promise<void> => {
|
||||
const params = new URLSearchParams();
|
||||
Object.entries(query).forEach(([key, value]) => {
|
||||
if (value !== undefined && value !== "") params.set(key, String(value));
|
||||
});
|
||||
return requestGridExcel(`v1/dredging/grid/exportJobs?${params}`, {}, `준설관리_${query.viewType}_${query.fromDate}_${query.toDate}.xlsx`);
|
||||
return requestGridExcel(
|
||||
`v1/dredging/grid/exportJobs?${params}`,
|
||||
{},
|
||||
`준설관리_${query.viewType}_${query.fromDate}_${query.toDate}.xlsx`,
|
||||
);
|
||||
};
|
||||
|
||||
type LocationRequest = GeoPoint & {
|
||||
@@ -99,7 +107,6 @@ export const fetchDredgingRecords = async (params: {
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
/** 등록된 준설사진의 공통 첨부파일 참조를 조회한다. */
|
||||
export const fetchDredgingPhotos = async (
|
||||
dredgingJobSn: string | number,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { getCommonCodes } from "@/components/lib/common/apiHelpers";
|
||||
import { getCommonCodes } from "@/entities/code/api/common-code-api";
|
||||
|
||||
import type {
|
||||
DredgingLocationSource,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"use client";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { UiTableSort } from "@common/business_components";
|
||||
import { fetchDredgingGridPage } from "../api/dredging-api";
|
||||
import { isDredgingBackendEnabled } from "../api/backend-mode";
|
||||
import type { DredgingRecord, DredgingViewType } from "../model/types";
|
||||
import {
|
||||
PAGE_SIZE,
|
||||
DREDGING_LOAD_ERROR_MESSAGE,
|
||||
initialRecords,
|
||||
type TableRow,
|
||||
} from "../model/dredging-list-view";
|
||||
|
||||
type Query = {
|
||||
appliedFromDate: string;
|
||||
appliedToDate: string;
|
||||
appliedCtpvName: string;
|
||||
appliedSggName: string;
|
||||
viewType: DredgingViewType;
|
||||
currentPage: number;
|
||||
sort?: UiTableSort;
|
||||
searchVersion: number;
|
||||
};
|
||||
/** 서버 페이지·전체 건수·조회 상태를 소유한다. 로컬 demo 갱신은 명시적 명령으로만 제공한다. */
|
||||
export function useDredgingListData({
|
||||
appliedFromDate,
|
||||
appliedToDate,
|
||||
appliedCtpvName,
|
||||
appliedSggName,
|
||||
viewType,
|
||||
currentPage,
|
||||
sort,
|
||||
searchVersion,
|
||||
}: Query) {
|
||||
const [records, setRecords] = useState<DredgingRecord[]>(
|
||||
isDredgingBackendEnabled ? [] : initialRecords,
|
||||
);
|
||||
const [serverRows, setServerRows] = useState<TableRow[]>([]);
|
||||
const [serverTotal, setServerTotal] = useState(0);
|
||||
const [isLoading, setIsLoading] = useState(isDredgingBackendEnabled);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (!isDredgingBackendEnabled) return;
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
setIsLoading(true);
|
||||
setLoadError(null);
|
||||
try {
|
||||
const response = await fetchDredgingGridPage({
|
||||
viewType,
|
||||
fromDate: appliedFromDate,
|
||||
toDate: appliedToDate,
|
||||
ctpv: appliedCtpvName,
|
||||
sgg: appliedSggName,
|
||||
page: currentPage - 1,
|
||||
size: PAGE_SIZE,
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
});
|
||||
if (!cancelled) {
|
||||
setServerRows(response.content);
|
||||
setServerTotal(response.totalElements);
|
||||
setRecords(
|
||||
viewType === "MUNICIPALITY"
|
||||
? (response.content as unknown as DredgingRecord[])
|
||||
: [],
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setRecords([]);
|
||||
setServerRows([]);
|
||||
setServerTotal(0);
|
||||
setLoadError(DREDGING_LOAD_ERROR_MESSAGE);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// 조회 버튼과 등록 완료 이벤트에서 searchVersion을 증가시켜 명시적으로 재조회한다.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [
|
||||
searchVersion,
|
||||
currentPage,
|
||||
viewType,
|
||||
sort,
|
||||
appliedFromDate,
|
||||
appliedToDate,
|
||||
appliedCtpvName,
|
||||
appliedSggName,
|
||||
]);
|
||||
const prependDemoRecords = useCallback((rows: DredgingRecord[]) => {
|
||||
if (!isDredgingBackendEnabled)
|
||||
setRecords((current) => [...rows, ...current]);
|
||||
}, []);
|
||||
const removeDemoJob = useCallback(
|
||||
(jobSn: DredgingRecord["dredgingJobSn"]) => {
|
||||
if (!isDredgingBackendEnabled)
|
||||
setRecords((current) =>
|
||||
current.filter((row) => row.dredgingJobSn !== jobSn),
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
return {
|
||||
records,
|
||||
serverRows,
|
||||
serverTotal,
|
||||
isLoading,
|
||||
loadError,
|
||||
prependDemoRecords,
|
||||
removeDemoJob,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
/** 준설 목록·집계 표의 컬럼·표시 변환. 서버 조회/React 상태와 분리한다. */
|
||||
import type { DredgingRecord } from "./types";
|
||||
import { MS_SWAGE_PPL_CODES } from "@/entities/facility/model/facility-code-fallbacks";
|
||||
|
||||
export const PAGE_SIZE = 10;
|
||||
|
||||
export const ALL_REGION_OPTION = { text: "전체", val: "0" };
|
||||
|
||||
export const pipeMaterialNameByCode = new Map(
|
||||
MS_SWAGE_PPL_CODES.map((item) => [item.val.trim(), item.text]),
|
||||
);
|
||||
|
||||
export const resolvePipeMaterialName = (
|
||||
value: string,
|
||||
names: ReadonlyMap<string, string> = pipeMaterialNameByCode,
|
||||
) => {
|
||||
const normalizedValue = value.trim();
|
||||
if (!normalizedValue) return "확인불가";
|
||||
const normalizedCode = normalizedValue.toUpperCase();
|
||||
if (!/^MOP\d+$/.test(normalizedCode)) return normalizedValue;
|
||||
return names.get(normalizedCode) ?? "확인불가";
|
||||
};
|
||||
|
||||
// 백엔드·프록시 상세 오류 대신 사용자가 다음 행동을 알 수 있는 문구만 표시한다.
|
||||
export const DREDGING_LOAD_ERROR_MESSAGE =
|
||||
"준설현황을 불러오지 못했습니다. 잠시 후 다시 시도해주세요.";
|
||||
|
||||
export const currentYear = new Date().getFullYear();
|
||||
|
||||
export const formatLocalDate = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
/** 준설일자 기본 검색기간을 오늘까지의 최근 1년으로 생성한다. */
|
||||
export const createDefaultDredgingDateRange = () => {
|
||||
const to = new Date();
|
||||
const from = new Date(to);
|
||||
from.setFullYear(from.getFullYear() - 1);
|
||||
return {
|
||||
fromDate: formatLocalDate(from),
|
||||
toDate: formatLocalDate(to),
|
||||
};
|
||||
};
|
||||
|
||||
export const initialRecords: DredgingRecord[] = [
|
||||
{
|
||||
id: "mock-dredging-1",
|
||||
dredgingJobSn: "mock-dredging-job-1",
|
||||
pipeFid: "MOCK-PIPE-1",
|
||||
mngInstCd: "4173000",
|
||||
ctpv: "경기도",
|
||||
sgg: "양평군",
|
||||
treatmentZone: "양평처리구역",
|
||||
fcltMngNo: "PPL-DEMO-001",
|
||||
pipeDiameterMm: 450,
|
||||
pipeLengthM: 82.4,
|
||||
pipeMaterial: "콘크리트",
|
||||
installationYear: 2004,
|
||||
dredgingDate: `${currentYear}-05-14`,
|
||||
photoCount: 3,
|
||||
registeredDate: `${currentYear}-05-15`,
|
||||
longitude: 127.4875,
|
||||
latitude: 37.4916,
|
||||
snappedLongitude: 127.48751,
|
||||
snappedLatitude: 37.49159,
|
||||
registrationMode: "PHOTO",
|
||||
registrationSource: "EXIF",
|
||||
matchDistanceMeters: 4.28,
|
||||
isMock: true,
|
||||
},
|
||||
{
|
||||
id: "mock-dredging-2",
|
||||
dredgingJobSn: "mock-dredging-job-2",
|
||||
pipeFid: "MOCK-PIPE-2",
|
||||
mngInstCd: "1153000",
|
||||
ctpv: "서울특별시",
|
||||
sgg: "구로구",
|
||||
treatmentZone: "서남처리구역",
|
||||
fcltMngNo: "PPL-DEMO-002",
|
||||
pipeDiameterMm: 900,
|
||||
pipeLengthM: 116.7,
|
||||
pipeMaterial: "PVC",
|
||||
installationYear: 1992,
|
||||
dredgingDate: `${currentYear - 1}-11-08`,
|
||||
photoCount: 0,
|
||||
registeredDate: `${currentYear - 1}-11-09`,
|
||||
longitude: 126.8874,
|
||||
latitude: 37.4954,
|
||||
snappedLongitude: 126.88741,
|
||||
snappedLatitude: 37.49539,
|
||||
registrationMode: "MANUAL",
|
||||
registrationSource: "MANUAL",
|
||||
matchDistanceMeters: 8.15,
|
||||
isMock: true,
|
||||
},
|
||||
];
|
||||
|
||||
/** 상세·수정 팝업이 동일한 관로·위치 정보를 받도록 쿼리 파라미터를 한곳에서 구성한다. */
|
||||
export const buildDredgingPopupParams = (record: DredgingRecord) => ({
|
||||
sourcePath: window.location.pathname,
|
||||
id: record.id,
|
||||
dredgingJobSn: record.dredgingJobSn,
|
||||
pipeFid: record.pipeFid,
|
||||
mngInstCd: record.mngInstCd,
|
||||
ctpv: record.ctpv,
|
||||
sgg: record.sgg,
|
||||
treatmentZone: record.treatmentZone,
|
||||
fcltMngNo: record.fcltMngNo,
|
||||
pipeDiameterMm: record.pipeDiameterMm,
|
||||
pipeLengthM: record.pipeLengthM,
|
||||
pipeMaterial: record.pipeMaterial,
|
||||
installationYear: record.installationYear,
|
||||
dredgingDate: record.dredgingDate,
|
||||
photoCount: record.photoCount,
|
||||
registeredDate: record.registeredDate,
|
||||
longitude: record.longitude,
|
||||
latitude: record.latitude,
|
||||
snappedLongitude: record.snappedLongitude,
|
||||
snappedLatitude: record.snappedLatitude,
|
||||
registrationMode:
|
||||
record.registrationMode ??
|
||||
(record.photoCount === 0 && record.registrationSource === "MANUAL"
|
||||
? "MANUAL"
|
||||
: "PHOTO"),
|
||||
registrationSource: record.registrationSource,
|
||||
matchDistanceMeters: record.matchDistanceMeters,
|
||||
isMock: record.isMock,
|
||||
});
|
||||
|
||||
export type TableRow = Record<string, unknown> & {
|
||||
recordIds: string[];
|
||||
};
|
||||
|
||||
export type TableHeadDefinition = {
|
||||
id: string;
|
||||
title: string;
|
||||
align?: "left" | "center" | "right";
|
||||
};
|
||||
|
||||
export const municipalityHeadlist: TableHeadDefinition[] = [
|
||||
{ id: "rowNumber", title: "순번" },
|
||||
{ id: "ctpv", title: "시도" },
|
||||
{ id: "sgg", title: "시군구" },
|
||||
{ id: "treatmentZone", title: "처리구역" },
|
||||
{ id: "fcltMngNo", title: "관로 번호" },
|
||||
{ id: "pipeDiameterMm", title: "관경(mm)", align: "right" },
|
||||
{ id: "pipeLengthM", title: "관로연장(m)", align: "right" },
|
||||
{ id: "pipeMaterial", title: "관재질" },
|
||||
{ id: "installationYear", title: "매설년도" },
|
||||
{ id: "elapsedYears", title: "경과년도" },
|
||||
{ id: "dredgingDate", title: "준설일자" },
|
||||
{ id: "photoCount", title: "등록사진건수", align: "right" },
|
||||
{ id: "registeredDate", title: "등록일자" },
|
||||
];
|
||||
|
||||
export const diameterHeadlist: TableHeadDefinition[] = [
|
||||
{ id: "ctpv", title: "시도" },
|
||||
{ id: "totalLengthKm", title: "관로연장(km)", align: "right" },
|
||||
{ id: "diameter450", title: "450 이하", align: "right" },
|
||||
{ id: "diameter600", title: "450~600", align: "right" },
|
||||
{ id: "diameter700", title: "700", align: "right" },
|
||||
{ id: "diameter900", title: "800~900", align: "right" },
|
||||
{ id: "diameter1000", title: "1000", align: "right" },
|
||||
{ id: "diameter1200", title: "1200", align: "right" },
|
||||
{ id: "diameter1500", title: "1500 이상", align: "right" },
|
||||
];
|
||||
|
||||
export const elapsedYearHeadlist: TableHeadDefinition[] = [
|
||||
{ id: "ctpv", title: "시도" },
|
||||
{ id: "totalLengthKm", title: "관로연장(km)", align: "right" },
|
||||
{ id: "under10", title: "10년 미만", align: "right" },
|
||||
{ id: "year10To20", title: "10년~20년", align: "right" },
|
||||
{ id: "year20To30", title: "20년~30년", align: "right" },
|
||||
{ id: "over30", title: "30년 이상", align: "right" },
|
||||
{ id: "unknown", title: "확인불가", align: "right" },
|
||||
];
|
||||
|
||||
export const roundKm = (meters: number) => Number((meters / 1000).toFixed(3));
|
||||
|
||||
export const parseLocalDate = (value: string) => new Date(`${value}T00:00:00`);
|
||||
|
||||
export const formatTableValue = (value: unknown) => {
|
||||
if (typeof value === "number") return value.toLocaleString("ko-KR");
|
||||
if (value === null || value === undefined) return "";
|
||||
return String(value);
|
||||
};
|
||||
|
||||
export const groupByCtpv = (records: DredgingRecord[]) => {
|
||||
const groups = new Map<string, DredgingRecord[]>();
|
||||
for (const record of records) {
|
||||
groups.set(record.ctpv, [...(groups.get(record.ctpv) ?? []), record]);
|
||||
}
|
||||
return groups;
|
||||
};
|
||||
|
||||
export const buildDiameterRows = (records: DredgingRecord[]): TableRow[] =>
|
||||
Array.from(groupByCtpv(records), ([ctpv, items]) => {
|
||||
const sumLength = (predicate: (record: DredgingRecord) => boolean) =>
|
||||
roundKm(
|
||||
items
|
||||
.filter(predicate)
|
||||
.reduce((sum, record) => sum + record.pipeLengthM, 0),
|
||||
);
|
||||
|
||||
return {
|
||||
ctpv,
|
||||
totalLengthKm: roundKm(
|
||||
items.reduce((sum, record) => sum + record.pipeLengthM, 0),
|
||||
),
|
||||
diameter450: sumLength((record) => record.pipeDiameterMm <= 450),
|
||||
diameter600: sumLength(
|
||||
(record) => record.pipeDiameterMm > 450 && record.pipeDiameterMm <= 600,
|
||||
),
|
||||
diameter700: sumLength(
|
||||
(record) => record.pipeDiameterMm > 600 && record.pipeDiameterMm <= 700,
|
||||
),
|
||||
diameter900: sumLength(
|
||||
(record) => record.pipeDiameterMm > 700 && record.pipeDiameterMm <= 900,
|
||||
),
|
||||
diameter1000: sumLength(
|
||||
(record) =>
|
||||
record.pipeDiameterMm > 900 && record.pipeDiameterMm <= 1000,
|
||||
),
|
||||
diameter1200: sumLength(
|
||||
(record) =>
|
||||
record.pipeDiameterMm > 1000 && record.pipeDiameterMm <= 1200,
|
||||
),
|
||||
diameter1500: sumLength((record) => record.pipeDiameterMm >= 1500),
|
||||
recordIds: items.map((record) => record.id),
|
||||
};
|
||||
});
|
||||
|
||||
export const buildElapsedYearRows = (records: DredgingRecord[]): TableRow[] =>
|
||||
Array.from(groupByCtpv(records), ([ctpv, items]) => {
|
||||
const sumLength = (predicate: (record: DredgingRecord) => boolean) =>
|
||||
roundKm(
|
||||
items
|
||||
.filter(predicate)
|
||||
.reduce((sum, record) => sum + record.pipeLengthM, 0),
|
||||
);
|
||||
const elapsedYears = (record: DredgingRecord) =>
|
||||
record.installationYear === null
|
||||
? null
|
||||
: currentYear - record.installationYear;
|
||||
|
||||
return {
|
||||
ctpv,
|
||||
totalLengthKm: roundKm(
|
||||
items.reduce((sum, record) => sum + record.pipeLengthM, 0),
|
||||
),
|
||||
under10: sumLength((record) => {
|
||||
const elapsed = elapsedYears(record);
|
||||
return elapsed !== null && elapsed < 10;
|
||||
}),
|
||||
year10To20: sumLength((record) => {
|
||||
const elapsed = elapsedYears(record);
|
||||
return elapsed !== null && elapsed >= 10 && elapsed < 20;
|
||||
}),
|
||||
year20To30: sumLength((record) => {
|
||||
const elapsed = elapsedYears(record);
|
||||
return elapsed !== null && elapsed >= 20 && elapsed < 30;
|
||||
}),
|
||||
over30: sumLength((record) => {
|
||||
const elapsed = elapsedYears(record);
|
||||
return elapsed !== null && elapsed >= 30;
|
||||
}),
|
||||
unknown: sumLength((record) => elapsedYears(record) === null),
|
||||
recordIds: items.map((record) => record.id),
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,929 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
import { FileUpload } from "@common/business_components/ui/file-upload";
|
||||
import { StandardPopupLayout } from "@common/business_components";
|
||||
import {
|
||||
Button,
|
||||
InputDatePicker,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
} from "@common/components";
|
||||
import { useFacilityCodeCatalog } from "@/entities/facility/lib/use-facility-code-catalog";
|
||||
import { fileDownload } from "@/components/lib/utils/file-download";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
fetchDredgingPhotoBlob,
|
||||
fetchDredgingPhotos,
|
||||
findNearestPipeMatches,
|
||||
updateDredgingRecord,
|
||||
type AttachmentReference,
|
||||
} from "@/features/dredging/api/dredging-api";
|
||||
import { uploadDredgingPhotoDrafts } from "@/features/dredging/api/photo-upload";
|
||||
import { formatDredgingCapturedDate } from "@/features/dredging/lib/date";
|
||||
import { readPhotoMetadata } from "@/features/dredging/lib/exif";
|
||||
import { useDredgingCommonCodes } from "@/features/dredging/lib/use-dredging-common-codes";
|
||||
import { createDredgingClientUuid } from "@/features/dredging/lib/uuid";
|
||||
import {
|
||||
EMPTY_PHOTO_METADATA,
|
||||
type DredgingPhoto,
|
||||
type DredgingPhotoDraft,
|
||||
type DredgingRecord,
|
||||
type DredgingRegistrationMode,
|
||||
type GeoPoint,
|
||||
type PipeMatch,
|
||||
} from "@/features/dredging/model/types";
|
||||
|
||||
const DredgingLocationMap = dynamic(
|
||||
() => import("@/features/dredging/ui/dredging-location-map"),
|
||||
{
|
||||
ssr: false,
|
||||
},
|
||||
);
|
||||
|
||||
type Props = {
|
||||
record: DredgingRecord;
|
||||
mode?: "detail" | "edit";
|
||||
onUpdated?: () => void;
|
||||
};
|
||||
|
||||
type DredgingPhotoPreview = DredgingPhoto & {
|
||||
previewUrl: string | null;
|
||||
loadError: string | null;
|
||||
};
|
||||
|
||||
type NewPhotoPreview = DredgingPhotoDraft & {
|
||||
previewUrl: string;
|
||||
};
|
||||
|
||||
const resolveMaterialName = (
|
||||
value: string,
|
||||
pipeMaterialNameByCode: Map<string, string>,
|
||||
) => {
|
||||
const normalizedValue = value.trim();
|
||||
if (!normalizedValue) return "확인불가";
|
||||
const normalizedCode = normalizedValue.toUpperCase();
|
||||
if (!/^MOP\d+$/.test(normalizedCode)) return normalizedValue;
|
||||
return pipeMaterialNameByCode.get(normalizedCode) ?? "확인불가";
|
||||
};
|
||||
|
||||
const formatLocalDate = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
const parseLocalDate = (value: string) => new Date(`${value}T00:00:00`);
|
||||
|
||||
/** 상세 UI를 공통 기반으로 사용해 조회와 수정 상태의 시각 구조를 동일하게 유지한다. */
|
||||
const DredgingDetailPopupPage = ({
|
||||
record,
|
||||
mode = "detail",
|
||||
onUpdated,
|
||||
}: Props) => {
|
||||
const { MS_SWAGE_PPL_CODES } = useFacilityCodeCatalog();
|
||||
const materialNames = useMemo(
|
||||
() =>
|
||||
new Map(MS_SWAGE_PPL_CODES.map((item) => [item.val.trim(), item.text])),
|
||||
[MS_SWAGE_PPL_CODES],
|
||||
);
|
||||
const resolvePipeMaterialName = (value: string) =>
|
||||
resolveMaterialName(value, materialNames);
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { confirm } = useConfirm();
|
||||
// 수정 화면도 등록 화면과 같은 CMS 공통코드 표시명을 공유한다.
|
||||
const { registrationModeLabels, locationSourceLabels } =
|
||||
useDredgingCommonCodes();
|
||||
const editable = mode === "edit";
|
||||
const [photos, setPhotos] = useState<DredgingPhotoPreview[]>([]);
|
||||
const [newPhotos, setNewPhotos] = useState<NewPhotoPreview[]>([]);
|
||||
const newPhotoUrlsRef = useRef<string[]>([]);
|
||||
const [selectedPhotoKey, setSelectedPhotoKey] = useState<string | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [dredgingDate, setDredgingDate] = useState(record.dredgingDate);
|
||||
const [location, setLocation] = useState<GeoPoint>({
|
||||
longitude: record.longitude,
|
||||
latitude: record.latitude,
|
||||
});
|
||||
const [locationDraft, setLocationDraft] = useState<GeoPoint | null>(null);
|
||||
const [isEditingLocation, setIsEditingLocation] = useState(false);
|
||||
// 등록방식은 사진 필수 여부와 마스터의 등록구분을 함께 결정한다.
|
||||
const [registrationMode, setRegistrationMode] =
|
||||
useState<DredgingRegistrationMode>(
|
||||
record.registrationMode ??
|
||||
(record.photoCount === 0 && record.registrationSource === "MANUAL"
|
||||
? "MANUAL"
|
||||
: "PHOTO"),
|
||||
);
|
||||
const [locationSource, setLocationSource] = useState(
|
||||
record.registrationSource,
|
||||
);
|
||||
const [matchError, setMatchError] = useState<string | null>(null);
|
||||
const [isMatching, setIsMatching] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
// 원본 다운로드 중 연속 클릭을 막고 선택한 사진의 다운로드 진행 상태를 표시한다.
|
||||
const [isDownloadingPhoto, setIsDownloadingPhoto] = useState(false);
|
||||
const [statusMessage, setStatusMessage] = useState("");
|
||||
const uploadedAttachmentsRef = useRef(new Map<string, AttachmentReference>());
|
||||
|
||||
const initialMatchedPipe = useMemo<PipeMatch>(
|
||||
() => ({
|
||||
fid: record.pipeFid,
|
||||
mngInstCd: record.mngInstCd,
|
||||
fcltMngNo: record.fcltMngNo,
|
||||
pipeDiameterMm: record.pipeDiameterMm,
|
||||
pipeLengthM: record.pipeLengthM,
|
||||
pipeMaterial: record.pipeMaterial,
|
||||
installationYear: record.installationYear,
|
||||
swtrmtZoneFid: null,
|
||||
swtrmtZoneNm: record.treatmentZone,
|
||||
distanceMeters: record.matchDistanceMeters,
|
||||
snappedLongitude: record.snappedLongitude || record.longitude,
|
||||
snappedLatitude: record.snappedLatitude || record.latitude,
|
||||
isMock: record.isMock,
|
||||
}),
|
||||
[record],
|
||||
);
|
||||
const [matchedPipe, setMatchedPipe] = useState<PipeMatch>(initialMatchedPipe);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const createdUrls: string[] = [];
|
||||
|
||||
const load = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
setPhotos([]);
|
||||
setSelectedPhotoKey(null);
|
||||
|
||||
try {
|
||||
const items = await fetchDredgingPhotos(
|
||||
record.dredgingJobSn,
|
||||
record.pipeFid,
|
||||
);
|
||||
const previews = await Promise.all(
|
||||
items.map(async (photo): Promise<DredgingPhotoPreview> => {
|
||||
try {
|
||||
const blob = await fetchDredgingPhotoBlob(photo.atflId);
|
||||
const previewUrl = URL.createObjectURL(blob);
|
||||
createdUrls.push(previewUrl);
|
||||
return { ...photo, previewUrl, loadError: null };
|
||||
} catch (loadError) {
|
||||
return {
|
||||
...photo,
|
||||
previewUrl: null,
|
||||
loadError:
|
||||
loadError instanceof Error
|
||||
? loadError.message
|
||||
: "사진 원본을 불러오지 못했습니다.",
|
||||
};
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (!cancelled) {
|
||||
setPhotos(previews);
|
||||
setSelectedPhotoKey(
|
||||
previews[0] ? `existing-${previews[0].photoSn}` : null,
|
||||
);
|
||||
}
|
||||
} catch (loadError) {
|
||||
if (!cancelled) {
|
||||
setError(
|
||||
loadError instanceof Error
|
||||
? loadError.message
|
||||
: "등록된 준설사진을 불러오지 못했습니다.",
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
void load();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
createdUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
}, [record.dredgingJobSn, record.pipeFid]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
newPhotoUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const selectedExistingPhoto = selectedPhotoKey?.startsWith("existing-")
|
||||
? (photos.find(
|
||||
(photo) => `existing-${photo.photoSn}` === selectedPhotoKey,
|
||||
) ?? null)
|
||||
: null;
|
||||
const selectedNewPhoto = selectedPhotoKey?.startsWith("new-")
|
||||
? (newPhotos.find((photo) => `new-${photo.key}` === selectedPhotoKey) ??
|
||||
null)
|
||||
: null;
|
||||
|
||||
/** 저장된 사진은 공통 첨부 원본을 받고, 아직 저장하지 않은 신규 사진은 로컬 File을 내려받는다. */
|
||||
const handlePhotoDownload = async () => {
|
||||
// 다운로드 중 선택을 바꾸더라도 클릭한 시점의 파일과 파일명을 함께 유지한다.
|
||||
const existingPhoto = selectedExistingPhoto;
|
||||
const newPhoto = selectedNewPhoto;
|
||||
if (isDownloadingPhoto || (!existingPhoto && !newPhoto)) return;
|
||||
|
||||
setIsDownloadingPhoto(true);
|
||||
try {
|
||||
if (newPhoto) {
|
||||
fileDownload(newPhoto.file, newPhoto.file.name);
|
||||
} else if (existingPhoto) {
|
||||
const original = await fetchDredgingPhotoBlob(existingPhoto.atflId);
|
||||
fileDownload(
|
||||
original,
|
||||
existingPhoto.originalFileName || `준설사진_${existingPhoto.photoSn}`,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
alert("사진을 다운로드하지 못했습니다. 잠시 후 다시 시도해주세요.");
|
||||
} finally {
|
||||
setIsDownloadingPhoto(false);
|
||||
}
|
||||
};
|
||||
|
||||
const pipeInfo = [
|
||||
["시도", record.ctpv || "확인불가"],
|
||||
["시군구", record.sgg || "확인불가"],
|
||||
[
|
||||
"처리구역",
|
||||
matchedPipe.swtrmtZoneNm || record.treatmentZone || "확인불가",
|
||||
],
|
||||
["관경", `${matchedPipe.pipeDiameterMm.toLocaleString()} mm`],
|
||||
["관로연장", `${matchedPipe.pipeLengthM.toLocaleString()} m`],
|
||||
["관재질", resolvePipeMaterialName(matchedPipe.pipeMaterial)],
|
||||
[
|
||||
"매설년도",
|
||||
matchedPipe.installationYear
|
||||
? `${matchedPipe.installationYear}년`
|
||||
: "확인불가",
|
||||
],
|
||||
["위치등록", locationSourceLabels[locationSource] || locationSource],
|
||||
];
|
||||
const pipeInfoRows = Array.from(
|
||||
{ length: Math.ceil(pipeInfo.length / 2) },
|
||||
(_, index) => pipeInfo.slice(index * 2, index * 2 + 2),
|
||||
);
|
||||
const automaticMappingValue = `${matchedPipe.distanceMeters.toFixed(2)} m`;
|
||||
const totalPhotoCount = photos.length + newPhotos.length;
|
||||
|
||||
const handleNewFiles = async (files: File[] | null) => {
|
||||
const selectedFiles = files ?? [];
|
||||
if (photos.length + selectedFiles.length > 5) {
|
||||
alert(
|
||||
"관로별 사진은 기존 사진을 포함해 최대 5장까지 등록할 수 있습니다.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
newPhotoUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
newPhotoUrlsRef.current = [];
|
||||
const checking = selectedFiles.map<NewPhotoPreview>((file) => {
|
||||
const previewUrl = URL.createObjectURL(file);
|
||||
newPhotoUrlsRef.current.push(previewUrl);
|
||||
return {
|
||||
key: createDredgingClientUuid(),
|
||||
file,
|
||||
metadata: EMPTY_PHOTO_METADATA,
|
||||
previewUrl,
|
||||
};
|
||||
});
|
||||
setNewPhotos(checking);
|
||||
if (checking[0]) setSelectedPhotoKey(`new-${checking[0].key}`);
|
||||
|
||||
const parsed = await Promise.all(
|
||||
checking.map(async (photo) => ({
|
||||
...photo,
|
||||
metadata: await readPhotoMetadata(photo.file),
|
||||
})),
|
||||
);
|
||||
setNewPhotos(parsed);
|
||||
};
|
||||
|
||||
const removeExistingPhoto = (photoSn: number) => {
|
||||
const remaining = photos.filter((photo) => photo.photoSn !== photoSn);
|
||||
setPhotos(remaining);
|
||||
if (
|
||||
registrationMode === "PHOTO" &&
|
||||
remaining.length + newPhotos.length === 0
|
||||
) {
|
||||
setStatusMessage(
|
||||
"사진 기반 등록은 사진이 한 장 이상 필요합니다. 사진을 추가하거나 사진 없이 직접 등록을 선택해주세요.",
|
||||
);
|
||||
}
|
||||
if (selectedPhotoKey === `existing-${photoSn}`) setSelectedPhotoKey(null);
|
||||
};
|
||||
|
||||
const removeNewPhoto = (photoKey: string) => {
|
||||
const removed = newPhotos.find((photo) => photo.key === photoKey);
|
||||
if (removed) {
|
||||
URL.revokeObjectURL(removed.previewUrl);
|
||||
newPhotoUrlsRef.current = newPhotoUrlsRef.current.filter(
|
||||
(url) => url !== removed.previewUrl,
|
||||
);
|
||||
}
|
||||
const remaining = newPhotos.filter((photo) => photo.key !== photoKey);
|
||||
setNewPhotos(remaining);
|
||||
if (
|
||||
registrationMode === "PHOTO" &&
|
||||
photos.length + remaining.length === 0
|
||||
) {
|
||||
setStatusMessage(
|
||||
"사진 기반 등록은 사진이 한 장 이상 필요합니다. 사진을 추가하거나 사진 없이 직접 등록을 선택해주세요.",
|
||||
);
|
||||
}
|
||||
if (selectedPhotoKey === `new-${photoKey}`) setSelectedPhotoKey(null);
|
||||
};
|
||||
|
||||
/** 수정 중 등록방식을 바꾸고 직접 등록 선택 시 사진을 모두 삭제 대상으로 전환한다. */
|
||||
const changeRegistrationMode = async (nextMode: DredgingRegistrationMode) => {
|
||||
if (registrationMode === nextMode) return;
|
||||
if (
|
||||
nextMode === "MANUAL" &&
|
||||
totalPhotoCount > 0 &&
|
||||
!(await confirm(
|
||||
"사진 없이 직접 등록으로 변경하면 현재 사진이 모두 삭제됩니다. 변경하시겠습니까?",
|
||||
))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextMode === "MANUAL") {
|
||||
newPhotoUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
|
||||
newPhotoUrlsRef.current = [];
|
||||
setPhotos([]);
|
||||
setNewPhotos([]);
|
||||
setSelectedPhotoKey(null);
|
||||
setLocationSource("MANUAL");
|
||||
setStatusMessage(
|
||||
"사진 없이 직접 등록으로 변경했습니다. 현재 위치를 확인하고 필요하면 수정해주세요.",
|
||||
);
|
||||
} else {
|
||||
setStatusMessage(
|
||||
"사진 기반 등록은 사진이 한 장 이상 필요합니다. 준설사진을 추가해주세요.",
|
||||
);
|
||||
}
|
||||
setRegistrationMode(nextMode);
|
||||
};
|
||||
|
||||
const startLocationEditing = () => {
|
||||
setLocationDraft(location);
|
||||
setIsEditingLocation(true);
|
||||
setMatchError(null);
|
||||
};
|
||||
|
||||
const cancelLocationEditing = () => {
|
||||
setLocationDraft(null);
|
||||
setIsEditingLocation(false);
|
||||
setMatchError(null);
|
||||
};
|
||||
|
||||
const applyLocation = async () => {
|
||||
if (!locationDraft) {
|
||||
alert("지도에서 변경할 준설위치를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
setIsMatching(true);
|
||||
setMatchError(null);
|
||||
try {
|
||||
const locationKey = `edit-${record.dredgingJobSn}-${record.pipeFid}`;
|
||||
const matches = await findNearestPipeMatches([
|
||||
{ locationKey, ...locationDraft },
|
||||
]);
|
||||
const nextPipe = matches.get(locationKey);
|
||||
if (!nextPipe) {
|
||||
throw new Error(
|
||||
"50m 이내에 관로가 없습니다. 지도에서 준설위치를 다시 확인해주세요.",
|
||||
);
|
||||
}
|
||||
setLocation(locationDraft);
|
||||
setLocationSource("MANUAL");
|
||||
setMatchedPipe(nextPipe);
|
||||
setLocationDraft(null);
|
||||
setIsEditingLocation(false);
|
||||
setStatusMessage("변경한 위치와 최근접 관로를 확인했습니다.");
|
||||
} catch (matchFailure) {
|
||||
setMatchError(
|
||||
matchFailure instanceof Error
|
||||
? matchFailure.message
|
||||
: "최근접 관로를 찾지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setIsMatching(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
if (!dredgingDate) {
|
||||
alert("준설일자를 입력해주세요.");
|
||||
return;
|
||||
}
|
||||
if (dredgingDate > formatLocalDate(new Date())) {
|
||||
alert("미래 날짜는 준설일자로 수정할 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
if (registrationMode === "PHOTO" && totalPhotoCount === 0) {
|
||||
const message =
|
||||
"사진 기반 등록은 사진이 한 장 이상 필요합니다. 사진을 추가하거나 사진 없이 직접 등록을 선택해주세요.";
|
||||
setStatusMessage(message);
|
||||
alert(message);
|
||||
return;
|
||||
}
|
||||
if (isEditingLocation) {
|
||||
alert("선택한 지도 위치를 먼저 적용해주세요.");
|
||||
return;
|
||||
}
|
||||
setIsSaving(true);
|
||||
try {
|
||||
setStatusMessage(
|
||||
newPhotos.length > 0
|
||||
? "추가한 사진을 공통 첨부파일로 업로드하고 있습니다."
|
||||
: "수정 내용을 저장하고 있습니다.",
|
||||
);
|
||||
const attachments = await uploadDredgingPhotoDrafts(
|
||||
newPhotos,
|
||||
uploadedAttachmentsRef.current,
|
||||
);
|
||||
uploadedAttachmentsRef.current = attachments;
|
||||
await updateDredgingRecord(
|
||||
record.dredgingJobSn,
|
||||
{
|
||||
dredgingDate,
|
||||
originalPipeFid: record.pipeFid,
|
||||
registrationMode,
|
||||
location,
|
||||
locationSource:
|
||||
registrationMode === "MANUAL" ? "MANUAL" : locationSource,
|
||||
pipe: matchedPipe,
|
||||
retainedPhotoSns: photos.map((photo) => photo.photoSn),
|
||||
newPhotos,
|
||||
},
|
||||
attachments,
|
||||
);
|
||||
uploadedAttachmentsRef.current.clear();
|
||||
setStatusMessage("준설정보 수정을 완료했습니다.");
|
||||
onUpdated?.();
|
||||
alert("준설정보를 수정했습니다.", () => window.close());
|
||||
} catch (saveError) {
|
||||
const message =
|
||||
saveError instanceof Error
|
||||
? saveError.message
|
||||
: "준설정보를 수정하지 못했습니다.";
|
||||
setStatusMessage(message);
|
||||
alert(message);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<StandardPopupLayout
|
||||
title={`준설결과 ${editable ? "수정" : "상세"}`}
|
||||
showDefaultCancelAction={false}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
{editable ? (
|
||||
<Button
|
||||
type="button"
|
||||
disabled={isSaving || isMatching}
|
||||
onClick={() => void handleSave()}
|
||||
data-testid="dredging-edit-save-button"
|
||||
>
|
||||
{isSaving ? "저장 중..." : "저장"}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button
|
||||
type="button"
|
||||
color="white"
|
||||
disabled={isSaving}
|
||||
onClick={() => window.close()}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
bodyClassName="sn-dredging-register !overflow-hidden"
|
||||
>
|
||||
<div className="grid h-full min-h-0 flex-1 grid-cols-[minmax(44rem,48rem)_minmax(0,1fr)] gap-3">
|
||||
<aside className="flex min-h-0 min-w-0 flex-col gap-3 overflow-y-auto overscroll-contain pr-1 [scrollbar-gutter:stable]">
|
||||
<section className="card card-border !m-0 shrink-0 overflow-hidden !p-0">
|
||||
<div className="card-header !m-0">
|
||||
<h2 className="text-2xl font-medium text-label">관로 정보</h2>
|
||||
<span className="truncate text-base text-muted-foreground">
|
||||
관로번호 {matchedPipe.fcltMngNo || "확인불가"}
|
||||
</span>
|
||||
</div>
|
||||
<div className="p-3">
|
||||
<Table variant="secondary">
|
||||
<colgroup>
|
||||
<col width="18%" />
|
||||
<col width="32%" />
|
||||
<col width="18%" />
|
||||
<col width="32%" />
|
||||
</colgroup>
|
||||
<TableBody>
|
||||
<TableRow>
|
||||
<TableHead data-required={editable || undefined}>
|
||||
준설일자
|
||||
</TableHead>
|
||||
<TableCell className="border px-4">
|
||||
{editable ? (
|
||||
<div className="w-full max-w-[15.5rem]">
|
||||
<InputDatePicker
|
||||
value={parseLocalDate(dredgingDate)}
|
||||
onChange={(date) =>
|
||||
date && setDredgingDate(formatLocalDate(date))
|
||||
}
|
||||
className="w-full"
|
||||
disabled={isSaving}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
dredgingDate
|
||||
)}
|
||||
</TableCell>
|
||||
<TableHead>자동매핑</TableHead>
|
||||
<TableCell
|
||||
className="truncate border px-4"
|
||||
title={automaticMappingValue}
|
||||
>
|
||||
{automaticMappingValue}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
{pipeInfoRows.map((row, index) => {
|
||||
const first = row[0];
|
||||
const second = row[1];
|
||||
return (
|
||||
<TableRow key={`${first?.[0]}-${index}`}>
|
||||
<TableHead>{first?.[0]}</TableHead>
|
||||
<TableCell
|
||||
className="truncate border px-4"
|
||||
title={first?.[1]}
|
||||
>
|
||||
{first?.[1]}
|
||||
</TableCell>
|
||||
{second ? (
|
||||
<>
|
||||
<TableHead>{second[0]}</TableHead>
|
||||
<TableCell
|
||||
className="truncate border px-4"
|
||||
title={second[1]}
|
||||
>
|
||||
{second[1]}
|
||||
</TableCell>
|
||||
</>
|
||||
) : (
|
||||
<TableCell colSpan={2} className="border" />
|
||||
)}
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* 사진 수·원본 크기와 무관하게 남은 화면 높이를 사용하며, 작은 창에서만 좌측 정보가 스크롤된다. */}
|
||||
<section
|
||||
className="card card-border !m-0 flex !min-h-[40rem] flex-1 flex-col overflow-hidden !p-0"
|
||||
data-testid="dredging-detail-photo-panel"
|
||||
>
|
||||
<div className="card-header !m-0 shrink-0 gap-2">
|
||||
<h2 className="text-2xl font-medium text-label">준설 사진</h2>
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-end gap-2">
|
||||
{editable ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color={registrationMode === "PHOTO" ? "primary" : "white"}
|
||||
aria-pressed={registrationMode === "PHOTO"}
|
||||
onClick={() => void changeRegistrationMode("PHOTO")}
|
||||
data-testid="dredging-edit-photo-mode"
|
||||
>
|
||||
{registrationModeLabels.PHOTO}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color={
|
||||
registrationMode === "MANUAL" ? "primary" : "white"
|
||||
}
|
||||
aria-pressed={registrationMode === "MANUAL"}
|
||||
onClick={() => void changeRegistrationMode("MANUAL")}
|
||||
data-testid="dredging-edit-manual-mode"
|
||||
>
|
||||
{registrationModeLabels.MANUAL}
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
<span className="text-base text-muted-foreground">
|
||||
{totalPhotoCount}/5장
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editable && registrationMode === "PHOTO" ? (
|
||||
<div className="sn-dredging-photo-upload flex h-[5.2rem] shrink-0 items-center border-b border-border p-3">
|
||||
<FileUpload
|
||||
files={newPhotos.map((photo) => photo.file)}
|
||||
setFiles={(files) => void handleNewFiles(files)}
|
||||
fileTypes=".jpg,.jpeg,.png"
|
||||
maxFiles={Math.max(1, 5 - photos.length)}
|
||||
/>
|
||||
</div>
|
||||
) : editable ? (
|
||||
<div className="bg-secondary/30 flex h-[5.2rem] shrink-0 items-center justify-center border-b border-border px-3 py-3 text-center text-sm text-muted-foreground">
|
||||
사진 없이 지도에서 준설위치를 직접 지정합니다.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* 목록의 높이와 스크롤바 자리를 예약해 추가·삭제·로딩 상태에도 미리보기 위치를 유지한다. */}
|
||||
<div
|
||||
className="h-[12rem] shrink-0 overflow-y-auto overscroll-contain border-b border-border p-3 [scrollbar-gutter:stable]"
|
||||
data-testid="dredging-detail-photo-list-viewport"
|
||||
>
|
||||
{isLoading ? (
|
||||
<p className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
등록된 사진을 불러오는 중입니다.
|
||||
</p>
|
||||
) : error ? (
|
||||
<p
|
||||
role="alert"
|
||||
className="rounded-sm bg-rose-50 px-3 py-3 text-sm text-rose-700"
|
||||
>
|
||||
{error}
|
||||
</p>
|
||||
) : totalPhotoCount > 0 ? (
|
||||
<div
|
||||
className="space-y-1"
|
||||
data-testid="dredging-detail-photo-list"
|
||||
>
|
||||
{photos.map((photo, index) => {
|
||||
const key = `existing-${photo.photoSn}`;
|
||||
const selected = key === selectedPhotoKey;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className={`flex items-stretch overflow-hidden rounded-sm border border-border ${selected ? "bg-primary-transparent" : "bg-background"}`}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="white"
|
||||
className="h-auto min-w-0 flex-1 justify-start rounded-none border-0 px-3 py-2 text-left"
|
||||
onClick={() => setSelectedPhotoKey(key)}
|
||||
aria-pressed={selected}
|
||||
data-testid={`dredging-detail-photo-${photo.photoSn}`}
|
||||
>
|
||||
<span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-secondary text-sm font-semibold text-label">
|
||||
{index + 1}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
{/* 파일명 밑줄과 글자 하단이 잘리지 않도록 글자 크기보다 넉넉한 줄 높이를 사용한다. */}
|
||||
<strong
|
||||
className="min-w-0 flex-1 truncate !text-[1.2rem] !font-medium !leading-[1.8rem]"
|
||||
title={photo.originalFileName}
|
||||
>
|
||||
{photo.originalFileName ||
|
||||
`준설사진 ${index + 1}`}
|
||||
</strong>
|
||||
<span className="shrink-0 whitespace-nowrap !text-[1.2rem] !leading-[1.8rem] text-muted-foreground">
|
||||
{formatDredgingCapturedDate(photo.capturedAt) ??
|
||||
"촬영일시 없음"}
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
{editable ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
color="red"
|
||||
size="icon"
|
||||
aria-label={`${photo.originalFileName} 삭제`}
|
||||
className="h-auto w-10 rounded-none border-y-0 border-l border-r-0 border-border p-0"
|
||||
onClick={() => removeExistingPhoto(photo.photoSn)}
|
||||
>
|
||||
×
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{newPhotos.map((photo, index) => {
|
||||
const key = `new-${photo.key}`;
|
||||
const selected = key === selectedPhotoKey;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className={`flex items-stretch overflow-hidden rounded-sm border border-border ${selected ? "bg-primary-transparent" : "bg-background"}`}
|
||||
>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="white"
|
||||
className="h-auto min-w-0 flex-1 justify-start rounded-none border-0 px-3 py-2 text-left"
|
||||
onClick={() => setSelectedPhotoKey(key)}
|
||||
aria-pressed={selected}
|
||||
>
|
||||
<span className="flex size-7 shrink-0 items-center justify-center rounded-full bg-secondary text-sm font-semibold text-label">
|
||||
{photos.length + index + 1}
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<strong
|
||||
className="min-w-0 flex-1 truncate !text-[1.2rem] !font-medium !leading-[1.8rem]"
|
||||
title={photo.file.name}
|
||||
>
|
||||
신규 · {photo.file.name}
|
||||
</strong>
|
||||
<span className="shrink-0 whitespace-nowrap !text-[1.2rem] !leading-[1.8rem] text-muted-foreground">
|
||||
{formatDredgingCapturedDate(
|
||||
photo.metadata.capturedAt,
|
||||
) ?? "촬영일시 없음"}
|
||||
</span>
|
||||
</span>
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
color="red"
|
||||
size="icon"
|
||||
aria-label={`${photo.file.name} 삭제`}
|
||||
className="h-auto w-10 rounded-none border-y-0 border-l border-r-0 border-border p-0"
|
||||
onClick={() => removeNewPhoto(photo.key)}
|
||||
>
|
||||
×
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="flex h-full items-center justify-center text-sm text-muted-foreground">
|
||||
{editable && registrationMode === "PHOTO"
|
||||
? "사진을 추가하거나 사진 없이 직접 등록을 선택해주세요."
|
||||
: "등록된 사진이 없습니다."}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 사진 미리보기는 밝은 사진의 경계를 보장하는 미디어 캔버스이므로 고정 암색을 유지한다.
|
||||
이미지를 절대 배치해 원본 고유 크기가 부모 높이를 늘리지 않도록 한다. */}
|
||||
<div
|
||||
className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden bg-slate-900 p-2"
|
||||
data-testid="dredging-detail-photo-preview"
|
||||
>
|
||||
{/* 미리보기 위에 겹쳐 배치해 다운로드 버튼이 고정 사진 영역의 높이를 바꾸지 않게 한다. */}
|
||||
<div className="absolute right-2 top-2 z-10">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color="white"
|
||||
disabled={
|
||||
isLoading ||
|
||||
isSaving ||
|
||||
isDownloadingPhoto ||
|
||||
(!selectedExistingPhoto && !selectedNewPhoto)
|
||||
}
|
||||
onClick={() => void handlePhotoDownload()}
|
||||
data-testid="dredging-photo-download"
|
||||
>
|
||||
{isDownloadingPhoto ? "다운로드 중..." : "사진 다운로드"}
|
||||
</Button>
|
||||
</div>
|
||||
{selectedExistingPhoto?.previewUrl ? (
|
||||
<img
|
||||
src={selectedExistingPhoto.previewUrl}
|
||||
alt={selectedExistingPhoto.originalFileName || "준설사진"}
|
||||
className="absolute inset-0 h-full w-full object-contain p-2"
|
||||
/>
|
||||
) : selectedNewPhoto ? (
|
||||
<img
|
||||
src={selectedNewPhoto.previewUrl}
|
||||
alt={selectedNewPhoto.file.name}
|
||||
className="absolute inset-0 h-full w-full object-contain p-2"
|
||||
/>
|
||||
) : selectedExistingPhoto?.loadError ? (
|
||||
<p className="px-4 text-center text-sm text-rose-200">
|
||||
{selectedExistingPhoto.loadError}
|
||||
</p>
|
||||
) : (
|
||||
<p className="px-4 text-center text-sm text-slate-300">
|
||||
{editable && registrationMode === "MANUAL"
|
||||
? "사진 없이 직접 등록 중입니다. 오른쪽 지도에서 위치를 확인해주세요."
|
||||
: "사진목록에서 확인할 사진을 선택해주세요."}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{editable ? (
|
||||
<section className="card card-border !m-0 shrink-0 overflow-hidden !p-0">
|
||||
<div className="card-header !m-0 flex-wrap gap-x-2 gap-y-1 !border-b-0">
|
||||
<div className="min-w-0">
|
||||
<h2 className="text-2xl font-medium text-label">
|
||||
위치 및 관로
|
||||
</h2>
|
||||
<p
|
||||
className={`mt-1 truncate text-sm ${matchError ? "text-rose-700" : "text-muted-foreground"}`}
|
||||
>
|
||||
자동 연결 관로 · {matchedPipe.fcltMngNo} ·{" "}
|
||||
{matchError ?? `${matchedPipe.distanceMeters.toFixed(2)}m`}
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-2">
|
||||
{isEditingLocation ? (
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={!locationDraft || isMatching}
|
||||
onClick={() => void applyLocation()}
|
||||
>
|
||||
{isMatching ? "관로 찾는 중..." : "선택 위치 적용"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color="white"
|
||||
onClick={cancelLocationEditing}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
onClick={startLocationEditing}
|
||||
>
|
||||
위치 수정
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{/* 안내와 처리 상태는 위치·관로 카드의 마지막 줄에서 함께 확인한다. */}
|
||||
<p
|
||||
className="m-0 min-w-0 basis-full break-words text-sm leading-5 text-muted-foreground"
|
||||
data-testid="dredging-edit-status"
|
||||
>
|
||||
{statusMessage ||
|
||||
"준설일자·사진·위치와 자동 연결 관로를 확인해주세요."}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
</aside>
|
||||
|
||||
<section
|
||||
className="card card-border !m-0 flex min-h-0 min-w-0 flex-col overflow-hidden !p-0"
|
||||
data-testid="dredging-detail-map"
|
||||
>
|
||||
<div className="card-header !m-0 shrink-0">
|
||||
<h2 className="text-2xl font-medium text-label">준설 위치 지도</h2>
|
||||
{editable ? (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
위치 수정 버튼을 누른 뒤 지도에서 위치를 선택하세요.
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="min-h-0 flex-1 p-2">
|
||||
<DredgingLocationMap
|
||||
value={isEditingLocation ? locationDraft : location}
|
||||
matchedPipe={
|
||||
isEditingLocation && locationDraft ? null : matchedPipe
|
||||
}
|
||||
interactive={editable && isEditingLocation}
|
||||
onChange={setLocationDraft}
|
||||
statusText={
|
||||
isEditingLocation
|
||||
? "지도에서 변경할 준설위치를 클릭한 뒤 선택 위치 적용을 눌러주세요."
|
||||
: editable
|
||||
? "현재 준설위치와 자동 연결된 관로를 표시하고 있습니다."
|
||||
: "준설위치와 자동 연결된 관로를 표시하고 있습니다."
|
||||
}
|
||||
height="h-full min-h-0"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</StandardPopupLayout>
|
||||
);
|
||||
};
|
||||
|
||||
export default DredgingDetailPopupPage;
|
||||
@@ -0,0 +1,693 @@
|
||||
/**
|
||||
* ➡️ 경로 : 유지관리 정보 - 준설관리
|
||||
*
|
||||
* - SFR-010-012 화면설계서 50~55쪽을 기준으로 한 FE 선행 구현
|
||||
* - 사진 EXIF 촬영일/GPS, 지도 수동 위치, 최근접 관로 자동 매핑 흐름 제공
|
||||
* - 지자체별/관경별/경과년도별 조회와 XLSX 다운로드 제공
|
||||
*/
|
||||
"use client";
|
||||
import { useFacilityCodeCatalog } from "@/entities/facility/lib/use-facility-code-catalog";
|
||||
import { useDredgingListData } from "../lib/use-dredging-list-data";
|
||||
import {
|
||||
PAGE_SIZE,
|
||||
ALL_REGION_OPTION,
|
||||
resolvePipeMaterialName,
|
||||
currentYear,
|
||||
formatLocalDate,
|
||||
createDefaultDredgingDateRange,
|
||||
buildDredgingPopupParams,
|
||||
type TableRow,
|
||||
municipalityHeadlist,
|
||||
diameterHeadlist,
|
||||
elapsedYearHeadlist,
|
||||
parseLocalDate,
|
||||
formatTableValue,
|
||||
buildDiameterRows,
|
||||
buildElapsedYearRows,
|
||||
} from "../model/dredging-list-view";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import {
|
||||
StandardDataTable,
|
||||
StandardTableSortHeader,
|
||||
sortStandardTableRows,
|
||||
type UiTableSort,
|
||||
} from "@common/business_components";
|
||||
import {
|
||||
Button,
|
||||
InputDatePicker,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@common/components";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import {
|
||||
getCoreRowModel,
|
||||
useReactTable,
|
||||
type ColumnDef,
|
||||
type PaginationState,
|
||||
} from "@tanstack/react-table";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
|
||||
import {
|
||||
deleteDredgingRecord,
|
||||
downloadDredgingGridExcel,
|
||||
} from "@/features/dredging/api/dredging-api";
|
||||
import { isDredgingBackendEnabled } from "@/features/dredging/api/backend-mode";
|
||||
import { createDredgingClientUuid } from "@/features/dredging/lib/uuid";
|
||||
import type {
|
||||
DredgingRecord,
|
||||
DredgingSaveGroup,
|
||||
DredgingViewType,
|
||||
} from "@/features/dredging/model/types";
|
||||
|
||||
const Page = () => {
|
||||
const { MS_SWAGE_PPL_CODES: materialOptions } = useFacilityCodeCatalog();
|
||||
const materialNames = useMemo(
|
||||
() => new Map(materialOptions.map((option) => [option.val, option.text])),
|
||||
[materialOptions],
|
||||
);
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { confirm } = useConfirm();
|
||||
const defaultDredgingDateRange = useMemo(createDefaultDredgingDateRange, []);
|
||||
const {
|
||||
ctpv: ctpvRegionOptions,
|
||||
sgg: sggRegionOptions,
|
||||
fetchCtpv,
|
||||
fetchSgg,
|
||||
} = useStore();
|
||||
const [fromDate, setFromDate] = useState(defaultDredgingDateRange.fromDate);
|
||||
const [toDate, setToDate] = useState(defaultDredgingDateRange.toDate);
|
||||
// 날짜 입력 중에는 기존 결과를 유지하고 조회·초기화 시점에만 적용 기간을 갱신한다.
|
||||
const [appliedFromDate, setAppliedFromDate] = useState(
|
||||
defaultDredgingDateRange.fromDate,
|
||||
);
|
||||
const [appliedToDate, setAppliedToDate] = useState(
|
||||
defaultDredgingDateRange.toDate,
|
||||
);
|
||||
// 선택 UI는 행정구역 코드를, 준설 조회 API는 행정구역 명칭을 사용한다.
|
||||
const [ctpvCd, setCtpvCd] = useState("0");
|
||||
const [sggCd, setSggCd] = useState("0");
|
||||
const [ctpvName, setCtpvName] = useState("");
|
||||
const [sggName, setSggName] = useState("");
|
||||
const [appliedCtpvName, setAppliedCtpvName] = useState("");
|
||||
const [appliedSggName, setAppliedSggName] = useState("");
|
||||
const [viewType, setViewType] = useState<DredgingViewType>("MUNICIPALITY");
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [selectedRecordId, setSelectedRecordId] = useState<string | null>(null);
|
||||
// 삭제 중 중복 요청과 선택 변경을 막는다.
|
||||
const [isMutating, setIsMutating] = useState(false);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
// 조회구분별 전체 결과를 페이지 절단 전에 정렬하는 단일 상태다.
|
||||
const [sort, setSort] = useState<UiTableSort>();
|
||||
const [searchVersion, setSearchVersion] = useState(0);
|
||||
const {
|
||||
records,
|
||||
serverRows,
|
||||
serverTotal,
|
||||
isLoading: isQueryLoading,
|
||||
loadError,
|
||||
prependDemoRecords,
|
||||
removeDemoJob,
|
||||
} = useDredgingListData({
|
||||
appliedFromDate,
|
||||
appliedToDate,
|
||||
appliedCtpvName,
|
||||
appliedSggName,
|
||||
viewType,
|
||||
currentPage,
|
||||
sort,
|
||||
searchVersion,
|
||||
});
|
||||
const isLoading = isQueryLoading || isDownloading;
|
||||
|
||||
/** 공통 레이아웃에서 아직 지역 기준정보를 받지 못한 경우 조회를 보완한다. */
|
||||
useEffect(() => {
|
||||
if (ctpvRegionOptions.length === 0) void fetchCtpv();
|
||||
if (sggRegionOptions.length === 0) void fetchSgg();
|
||||
}, [ctpvRegionOptions.length, fetchCtpv, fetchSgg, sggRegionOptions.length]);
|
||||
|
||||
/** 선택한 시도 코드와 앞 두 자리가 같은 시군구만 후보로 제공한다. */
|
||||
const availableSggOptions = useMemo(() => {
|
||||
if (ctpvCd === "0") return [];
|
||||
const ctpvPrefix = ctpvCd.slice(0, 2);
|
||||
return sggRegionOptions.filter((option) =>
|
||||
String(option.val).startsWith(ctpvPrefix),
|
||||
);
|
||||
}, [ctpvCd, sggRegionOptions]);
|
||||
|
||||
// 조회 버튼을 누른 시점의 기간으로 실제 준설관리 API를 호출한다.
|
||||
|
||||
const filteredRecords = useMemo(
|
||||
() =>
|
||||
records.filter(
|
||||
(record) =>
|
||||
record.dredgingDate >= appliedFromDate &&
|
||||
record.dredgingDate <= appliedToDate &&
|
||||
(!appliedCtpvName || record.ctpv === appliedCtpvName) &&
|
||||
(!appliedSggName || record.sgg === appliedSggName),
|
||||
),
|
||||
[
|
||||
records,
|
||||
appliedFromDate,
|
||||
appliedToDate,
|
||||
appliedCtpvName,
|
||||
appliedSggName,
|
||||
searchVersion,
|
||||
],
|
||||
);
|
||||
|
||||
const tableRows = useMemo<TableRow[]>(() => {
|
||||
if (isDredgingBackendEnabled) {
|
||||
return serverRows.map((row) =>
|
||||
viewType === "MUNICIPALITY"
|
||||
? {
|
||||
...row,
|
||||
pipeMaterial: resolvePipeMaterialName(
|
||||
String(row.pipeMaterial ?? ""),
|
||||
materialNames,
|
||||
),
|
||||
installationYear: row.installationYear ?? "확인불가",
|
||||
elapsedYears: row.elapsedYears ?? "확인불가",
|
||||
}
|
||||
: row,
|
||||
);
|
||||
}
|
||||
if (viewType === "DIAMETER") return buildDiameterRows(filteredRecords);
|
||||
if (viewType === "ELAPSED_YEAR")
|
||||
return buildElapsedYearRows(filteredRecords);
|
||||
|
||||
return filteredRecords.map((record, index) => ({
|
||||
rowNumber: index + 1,
|
||||
...record,
|
||||
pipeLengthM: Number(record.pipeLengthM.toFixed(2)),
|
||||
pipeMaterial: resolvePipeMaterialName(record.pipeMaterial, materialNames),
|
||||
installationYear: record.installationYear ?? "확인불가",
|
||||
elapsedYears:
|
||||
record.installationYear === null
|
||||
? "확인불가"
|
||||
: currentYear - record.installationYear,
|
||||
recordIds: [record.id],
|
||||
}));
|
||||
}, [filteredRecords, viewType, serverRows, materialNames]);
|
||||
|
||||
// 운영 모드는 서버가 정렬·페이징하며 로컬 시연 모드만 메모리 처리를 유지한다.
|
||||
const sortedTableRows = useMemo(
|
||||
() =>
|
||||
isDredgingBackendEnabled
|
||||
? tableRows
|
||||
: sortStandardTableRows(tableRows, sort),
|
||||
[sort, tableRows],
|
||||
);
|
||||
|
||||
const pageRows = useMemo(
|
||||
() =>
|
||||
isDredgingBackendEnabled
|
||||
? sortedTableRows
|
||||
: sortedTableRows.slice(
|
||||
(currentPage - 1) * PAGE_SIZE,
|
||||
currentPage * PAGE_SIZE,
|
||||
),
|
||||
[currentPage, sortedTableRows],
|
||||
);
|
||||
|
||||
const selectedRecord =
|
||||
records.find((record) => record.id === selectedRecordId) ?? null;
|
||||
const canManageSelectedRecord =
|
||||
viewType === "MUNICIPALITY" && selectedRecord !== null && !isMutating;
|
||||
|
||||
const headlist =
|
||||
viewType === "MUNICIPALITY"
|
||||
? municipalityHeadlist
|
||||
: viewType === "DIAMETER"
|
||||
? diameterHeadlist
|
||||
: elapsedYearHeadlist;
|
||||
|
||||
const title = "준설 목록";
|
||||
|
||||
const columns = useMemo<ColumnDef<TableRow>[]>(
|
||||
() =>
|
||||
headlist.map((head) => ({
|
||||
id: head.id,
|
||||
accessorFn: (row) => row[head.id],
|
||||
// 표시명 컬럼까지 서버 전체 정렬을 사용한다.
|
||||
header: () => (
|
||||
<StandardTableSortHeader
|
||||
label={head.title}
|
||||
sortKey={head.id}
|
||||
sort={sort}
|
||||
onSortChange={(nextSort) => {
|
||||
setSort(nextSort);
|
||||
setCurrentPage(1);
|
||||
setSelectedRecordId(null);
|
||||
}}
|
||||
/>
|
||||
),
|
||||
cell: ({ getValue }) => formatTableValue(getValue()),
|
||||
meta: {
|
||||
align: head.align ?? "center",
|
||||
},
|
||||
})),
|
||||
[headlist, sort, viewType],
|
||||
);
|
||||
const pagination: PaginationState = {
|
||||
pageIndex: currentPage - 1,
|
||||
pageSize: PAGE_SIZE,
|
||||
};
|
||||
const selectedTableRowId = pageRows
|
||||
.find(
|
||||
(row) =>
|
||||
selectedRecordId !== null && row.recordIds.includes(selectedRecordId),
|
||||
)
|
||||
?.recordIds.join("|");
|
||||
const table = useReactTable({
|
||||
data: pageRows,
|
||||
columns,
|
||||
state: {
|
||||
pagination,
|
||||
rowSelection: selectedTableRowId ? { [selectedTableRowId]: true } : {},
|
||||
},
|
||||
rowCount: isDredgingBackendEnabled ? serverTotal : sortedTableRows.length,
|
||||
manualPagination: true,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
getRowId: (row) => row.recordIds.join("|"),
|
||||
onPaginationChange: (updater) => {
|
||||
const next =
|
||||
typeof updater === "function" ? updater(pagination) : updater;
|
||||
setCurrentPage(next.pageIndex + 1);
|
||||
setSelectedRecordId(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleSearch = () => {
|
||||
if (fromDate > toDate) {
|
||||
alert("조회 시작일은 종료일보다 늦을 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
setCurrentPage(1);
|
||||
setSelectedRecordId(null);
|
||||
setAppliedFromDate(fromDate);
|
||||
setAppliedToDate(toDate);
|
||||
setAppliedCtpvName(ctpvName);
|
||||
setAppliedSggName(sggName);
|
||||
setSearchVersion((version) => version + 1);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setFromDate(defaultDredgingDateRange.fromDate);
|
||||
setToDate(defaultDredgingDateRange.toDate);
|
||||
setAppliedFromDate(defaultDredgingDateRange.fromDate);
|
||||
setAppliedToDate(defaultDredgingDateRange.toDate);
|
||||
setViewType("MUNICIPALITY");
|
||||
setCtpvCd("0");
|
||||
setSggCd("0");
|
||||
setCtpvName("");
|
||||
setSggName("");
|
||||
setAppliedCtpvName("");
|
||||
setAppliedSggName("");
|
||||
setSort(undefined);
|
||||
setCurrentPage(1);
|
||||
setSelectedRecordId(null);
|
||||
setSearchVersion((version) => version + 1);
|
||||
};
|
||||
|
||||
const handleDownload = async () => {
|
||||
try {
|
||||
if (isDredgingBackendEnabled) {
|
||||
setIsDownloading(true);
|
||||
await downloadDredgingGridExcel({
|
||||
viewType,
|
||||
fromDate: appliedFromDate,
|
||||
toDate: appliedToDate,
|
||||
ctpv: appliedCtpvName,
|
||||
sgg: appliedSggName,
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const visibleHeads = headlist.filter((head) => head.id !== "recordIds");
|
||||
const excelRows = [
|
||||
visibleHeads.map((head) => head.title),
|
||||
...sortedTableRows.map((row) =>
|
||||
visibleHeads.map((head) => row[head.id] ?? ""),
|
||||
),
|
||||
];
|
||||
const { utils, writeFileXLSX } = await import("xlsx");
|
||||
const worksheet = utils.aoa_to_sheet(excelRows);
|
||||
worksheet["!cols"] = visibleHeads.map((head) => ({
|
||||
wch: Math.max(head.title.length * 2, 12),
|
||||
}));
|
||||
const workbook = utils.book_new();
|
||||
utils.book_append_sheet(workbook, worksheet, title.slice(0, 31));
|
||||
writeFileXLSX(
|
||||
workbook,
|
||||
`준설관리_${viewType}_${fromDate}_${toDate}.xlsx`,
|
||||
{ compression: true },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("준설현황 엑셀 다운로드 실패", error);
|
||||
alert("엑셀 파일을 생성하지 못했습니다.");
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaved = useCallback(
|
||||
(savedGroups: DredgingSaveGroup[]) => {
|
||||
if (isDredgingBackendEnabled) {
|
||||
setCurrentPage(1);
|
||||
setSelectedRecordId(null);
|
||||
setSearchVersion((version) => version + 1);
|
||||
return;
|
||||
}
|
||||
const registeredDate = formatLocalDate(new Date());
|
||||
const localJobSn = `local-job-${createDredgingClientUuid()}`;
|
||||
const addedRecords = savedGroups.map<DredgingRecord>((group, index) => ({
|
||||
id: `${localJobSn}-${index + 1}`,
|
||||
dredgingJobSn: localJobSn,
|
||||
pipeFid: group.pipe.fid,
|
||||
mngInstCd: group.pipe.mngInstCd,
|
||||
ctpv: ctpvName || "경기도",
|
||||
sgg: sggName || "양평군",
|
||||
treatmentZone: group.pipe.swtrmtZoneNm || "확인불가",
|
||||
fcltMngNo: group.pipe.fcltMngNo,
|
||||
pipeDiameterMm: group.pipe.pipeDiameterMm,
|
||||
pipeLengthM: group.pipe.pipeLengthM,
|
||||
pipeMaterial: group.pipe.pipeMaterial,
|
||||
installationYear: group.pipe.installationYear,
|
||||
dredgingDate: group.dredgingDate,
|
||||
photoCount: group.photos.length,
|
||||
registeredDate,
|
||||
longitude: group.location.longitude,
|
||||
latitude: group.location.latitude,
|
||||
snappedLongitude: group.pipe.snappedLongitude,
|
||||
snappedLatitude: group.pipe.snappedLatitude,
|
||||
registrationMode: group.registrationMode,
|
||||
registrationSource: group.locationSource,
|
||||
matchDistanceMeters: group.pipe.distanceMeters,
|
||||
isMock: group.pipe.isMock || !isDredgingBackendEnabled,
|
||||
}));
|
||||
prependDemoRecords(addedRecords);
|
||||
setCurrentPage(1);
|
||||
},
|
||||
[ctpvName, sggName, prependDemoRecords],
|
||||
);
|
||||
|
||||
/** 상세 화면과 같은 최대화 팝업에서 준설일자·사진·위치를 함께 수정한다. */
|
||||
const openEditRecord = () => {
|
||||
if (!canManageSelectedRecord || !selectedRecord) return;
|
||||
|
||||
const popup = openWindowPopup(
|
||||
"dredgingEdit",
|
||||
buildDredgingPopupParams(selectedRecord),
|
||||
{ maximize: true },
|
||||
);
|
||||
if (!popup) {
|
||||
alert(
|
||||
"준설정보 수정 팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** 선택 행이 속한 준설작업과 연결 관로·사진 참조를 물리 삭제하고 목록을 재조회한다. */
|
||||
const handleDeleteRecord = async () => {
|
||||
if (!canManageSelectedRecord || !selectedRecord) return;
|
||||
const confirmed = await confirm(
|
||||
`선택한 준설작업 전체를 삭제하시겠습니까?\n준설일자: ${selectedRecord.dredgingDate}\n현재 페이지에 보이지 않는 연결 관로와 사진도 모두 삭제됩니다.`,
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
setIsMutating(true);
|
||||
try {
|
||||
await deleteDredgingRecord(selectedRecord.dredgingJobSn);
|
||||
if (isDredgingBackendEnabled) {
|
||||
setSearchVersion((version) => version + 1);
|
||||
} else {
|
||||
removeDemoJob(selectedRecord.dredgingJobSn);
|
||||
}
|
||||
setSelectedRecordId(null);
|
||||
alert("준설정보를 삭제했습니다.");
|
||||
} catch (error) {
|
||||
alert(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "준설정보를 삭제하지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
setIsMutating(false);
|
||||
}
|
||||
};
|
||||
|
||||
/** 공통 WindowPopup 체계로 준설결과 등록 화면을 연다. */
|
||||
const openDredgingRegister = () => {
|
||||
const popup = openWindowPopup(
|
||||
"dredgingRegister",
|
||||
{ sourcePath: window.location.pathname },
|
||||
{ maximize: true },
|
||||
);
|
||||
if (!popup) {
|
||||
alert(
|
||||
"준설결과 등록 팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
/** 등록·수정 팝업의 저장 완료 메시지를 받아 목록을 최신 상태로 갱신한다. */
|
||||
useEffect(() => {
|
||||
const handlePopupMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== window.location.origin) return;
|
||||
if (event.data?.type === WINDOW_POPUP_MESSAGE_TYPE.DREDGING_UPDATED) {
|
||||
setSelectedRecordId(null);
|
||||
setCurrentPage(1);
|
||||
setSearchVersion((version) => version + 1);
|
||||
return;
|
||||
}
|
||||
if (event.data?.type !== WINDOW_POPUP_MESSAGE_TYPE.DREDGING_REGISTERED) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const savedGroups = JSON.parse(
|
||||
event.data?.payload?.groups ?? "[]",
|
||||
) as DredgingSaveGroup[];
|
||||
if (Array.isArray(savedGroups) && savedGroups.length > 0) {
|
||||
handleSaved(savedGroups);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("준설결과 등록 팝업 응답 처리 실패", error);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", handlePopupMessage);
|
||||
return () => window.removeEventListener("message", handlePopupMessage);
|
||||
}, [handleSaved]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<LoadingOverlay isLoading={isLoading || isMutating} />
|
||||
<div className="card card-border !mt-6">
|
||||
<form
|
||||
className="flex flex-col gap-6 p-2"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
handleSearch();
|
||||
}}
|
||||
>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">
|
||||
준설일자
|
||||
</Label>
|
||||
<InputDatePicker
|
||||
value={parseLocalDate(fromDate)}
|
||||
onChange={(date) => date && setFromDate(formatLocalDate(date))}
|
||||
className="w-[15.5rem]"
|
||||
/>
|
||||
<span>~</span>
|
||||
<InputDatePicker
|
||||
value={parseLocalDate(toDate)}
|
||||
onChange={(date) => date && setToDate(formatLocalDate(date))}
|
||||
className="w-[15.5rem]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">
|
||||
조회구분
|
||||
</Label>
|
||||
<Select
|
||||
value={viewType}
|
||||
onValueChange={(value) => {
|
||||
setViewType(value as DredgingViewType);
|
||||
setSort(undefined);
|
||||
setCurrentPage(1);
|
||||
setSelectedRecordId(null);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-[14.5rem]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="MUNICIPALITY">지자체별</SelectItem>
|
||||
<SelectItem value="DIAMETER">관경별</SelectItem>
|
||||
<SelectItem value="ELAPSED_YEAR">경과년도별</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">시도</Label>
|
||||
<Select
|
||||
value={ctpvCd}
|
||||
onValueChange={(value) => {
|
||||
const nextCtpvCd = String(value);
|
||||
setCtpvCd(nextCtpvCd);
|
||||
setSggCd("0");
|
||||
setCtpvName(
|
||||
ctpvRegionOptions.find(
|
||||
(option) => String(option.val) === nextCtpvCd,
|
||||
)?.text ?? "",
|
||||
);
|
||||
setSggName("");
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-[14rem]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{[ALL_REGION_OPTION, ...ctpvRegionOptions].map((option) => (
|
||||
<SelectItem
|
||||
key={String(option.val)}
|
||||
value={String(option.val)}
|
||||
>
|
||||
{option.text}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">
|
||||
시군구
|
||||
</Label>
|
||||
<Select
|
||||
value={sggCd}
|
||||
onValueChange={(value) => {
|
||||
const nextSggCd = String(value);
|
||||
setSggCd(nextSggCd);
|
||||
setSggName(
|
||||
availableSggOptions.find(
|
||||
(option) => String(option.val) === nextSggCd,
|
||||
)?.text ?? "",
|
||||
);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-[14rem]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{[ALL_REGION_OPTION, ...availableSggOptions].map((option) => (
|
||||
<SelectItem
|
||||
key={String(option.val)}
|
||||
value={String(option.val)}
|
||||
>
|
||||
{option.text}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-[7.4rem]">
|
||||
조회
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
color="white"
|
||||
className="w-[8.8rem]"
|
||||
onClick={handleReset}
|
||||
>
|
||||
초기화
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{loadError ? (
|
||||
<div
|
||||
role="alert"
|
||||
className="mt-3 flex items-center justify-between gap-3 rounded-sm border border-amber-200 bg-amber-50 px-4 py-2.5 text-sm text-amber-800"
|
||||
>
|
||||
<span>{loadError}</span>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color="primary"
|
||||
className="h-8 shrink-0 px-3"
|
||||
onClick={handleSearch}
|
||||
>
|
||||
다시 시도
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-4 w-full min-w-0 max-w-full overflow-hidden">
|
||||
<StandardDataTable
|
||||
table={table}
|
||||
title={title}
|
||||
onRowClick={(row) => {
|
||||
setSelectedRecordId(row.recordIds[0] ?? null);
|
||||
}}
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={
|
||||
isLoading || (isDredgingBackendEnabled && serverTotal === 0)
|
||||
}
|
||||
onClick={() => void handleDownload()}
|
||||
>
|
||||
엑셀다운로드
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={openDredgingRegister}
|
||||
data-testid="dredging-register-button"
|
||||
>
|
||||
등록
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
onClick={openEditRecord}
|
||||
disabled={!canManageSelectedRecord}
|
||||
data-testid="dredging-edit-button"
|
||||
>
|
||||
수정
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
color="red"
|
||||
onClick={() => void handleDeleteRecord()}
|
||||
disabled={!canManageSelectedRecord}
|
||||
data-testid="dredging-delete-button"
|
||||
>
|
||||
삭제
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Page;
|
||||
@@ -0,0 +1,399 @@
|
||||
"use client";
|
||||
|
||||
import Feature from "ol/Feature.js";
|
||||
import type { FeatureLike } from "ol/Feature.js";
|
||||
import Point from "ol/geom/Point.js";
|
||||
import type OlMap from "ol/Map.js";
|
||||
import type { EventsKey } from "ol/events.js";
|
||||
import { unByKey } from "ol/Observable.js";
|
||||
import { transform } from "ol/proj.js";
|
||||
import VectorLayer from "ol/layer/Vector.js";
|
||||
import VectorSource from "ol/source/Vector.js";
|
||||
import CircleStyle from "ol/style/Circle.js";
|
||||
import Fill from "ol/style/Fill.js";
|
||||
import Stroke from "ol/style/Stroke.js";
|
||||
import Style from "ol/style/Style.js";
|
||||
import type { StyleFunction, StyleLike } from "ol/style/Style.js";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { getRawJson } from "@/shared/api/sewerage-api";
|
||||
import Gis, { useGisContext } from "@common/business_components/ui/map/Gis";
|
||||
import GisApp from "@common/business_components/ui/map/lib/gis.core";
|
||||
|
||||
import type { GeoPoint, PipeMatch } from "@/features/dredging/model/types";
|
||||
|
||||
type DredgingLocationMapProps = {
|
||||
value: GeoPoint | null;
|
||||
onChange?: (point: GeoPoint) => void;
|
||||
interactive?: boolean;
|
||||
statusText?: string;
|
||||
matchedPipe?: PipeMatch | null;
|
||||
height?: string;
|
||||
};
|
||||
|
||||
type LayerSetting = Record<string, unknown> & {
|
||||
id?: string;
|
||||
lyrSn?: string;
|
||||
lyrTyNm?: string;
|
||||
useYn?: string;
|
||||
actlLyrYn?: string;
|
||||
exprsYn?: string;
|
||||
children?: LayerSetting[];
|
||||
};
|
||||
|
||||
type GisCore = {
|
||||
addWfsLayer: (setting: LayerSetting) => VectorLayer<VectorSource>;
|
||||
};
|
||||
|
||||
type GisContextValue = {
|
||||
gisMap: OlMap | null;
|
||||
gisCore: GisCore | null;
|
||||
};
|
||||
|
||||
const confirmedMarkerStyle = new Style({
|
||||
image: new CircleStyle({
|
||||
radius: 9,
|
||||
fill: new Fill({ color: "rgba(220, 38, 38, 0.9)" }),
|
||||
stroke: new Stroke({ color: "#ffffff", width: 3 }),
|
||||
}),
|
||||
});
|
||||
|
||||
const draftMarkerStyle = new Style({
|
||||
image: new CircleStyle({
|
||||
radius: 9,
|
||||
fill: new Fill({ color: "rgba(37, 99, 235, 0.9)" }),
|
||||
stroke: new Stroke({ color: "#ffffff", width: 3 }),
|
||||
}),
|
||||
});
|
||||
|
||||
const matchedPipeStyle = [
|
||||
new Style({
|
||||
stroke: new Stroke({ color: "rgba(255, 255, 255, 0.98)", width: 7 }),
|
||||
zIndex: 20,
|
||||
}),
|
||||
new Style({
|
||||
stroke: new Stroke({ color: "#f97316", width: 4 }),
|
||||
zIndex: 21,
|
||||
}),
|
||||
];
|
||||
|
||||
const normalizePipeFid = (fid: unknown) => {
|
||||
const value = String(fid ?? "").trim();
|
||||
const separatorIndex = value.lastIndexOf(".");
|
||||
return separatorIndex >= 0 ? value.slice(separatorIndex + 1) : value;
|
||||
};
|
||||
|
||||
const flattenLayerSettings = (items: LayerSetting[]): LayerSetting[] =>
|
||||
items.flatMap((item) => [
|
||||
item,
|
||||
...flattenLayerSettings(Array.isArray(item.children) ? item.children : []),
|
||||
]);
|
||||
|
||||
const isPipeLayerSetting = (setting: LayerSetting) =>
|
||||
setting.lyrTyNm === "tb_ms_swage_ppl" &&
|
||||
setting.useYn === "Y" &&
|
||||
setting.actlLyrYn === "Y" &&
|
||||
setting.exprsYn !== "N";
|
||||
|
||||
const resolveStyle = (
|
||||
style: StyleLike | null | undefined,
|
||||
feature: FeatureLike,
|
||||
resolution: number,
|
||||
) => (typeof style === "function" ? style(feature, resolution) : style);
|
||||
|
||||
/**
|
||||
* 공통 관망도와 같은 DB 레이어 설정으로 관로를 그리고, 이 화면이 소유한 마커와
|
||||
* 클릭 이벤트만 추가·정리한다.
|
||||
*/
|
||||
const LocationInteraction = ({
|
||||
value,
|
||||
onChange,
|
||||
interactive,
|
||||
matchedPipe,
|
||||
pipeLayerSettings,
|
||||
}: Required<Pick<DredgingLocationMapProps, "interactive">> &
|
||||
Omit<DredgingLocationMapProps, "interactive" | "height"> & {
|
||||
pipeLayerSettings: LayerSetting[];
|
||||
}) => {
|
||||
const { gisMap, gisCore } = useGisContext() as GisContextValue;
|
||||
const markerLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
|
||||
const pipeLayersRef = useRef<
|
||||
Array<{ layer: VectorLayer<VectorSource>; baseStyle: StyleLike | null }>
|
||||
>([]);
|
||||
const onChangeRef = useRef(onChange);
|
||||
const previousValueRef = useRef<GeoPoint | null>(null);
|
||||
const [pipeLoadState, setPipeLoadState] = useState<
|
||||
"idle" | "loading" | "loaded" | "error"
|
||||
>("idle");
|
||||
const [visiblePipeCount, setVisiblePipeCount] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
}, [onChange]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gisMap) return;
|
||||
const markerSource = new VectorSource();
|
||||
const markerLayer = new VectorLayer({
|
||||
source: markerSource,
|
||||
style: interactive ? draftMarkerStyle : confirmedMarkerStyle,
|
||||
zIndex: 999,
|
||||
});
|
||||
markerLayer.set("dredgingLocationLayer", true);
|
||||
gisMap.addLayer(markerLayer);
|
||||
markerLayerRef.current = markerLayer;
|
||||
|
||||
return () => {
|
||||
gisMap.removeLayer(markerLayer);
|
||||
markerLayerRef.current = null;
|
||||
};
|
||||
}, [gisMap]);
|
||||
|
||||
useEffect(() => {
|
||||
markerLayerRef.current?.setStyle(
|
||||
interactive ? draftMarkerStyle : confirmedMarkerStyle,
|
||||
);
|
||||
}, [interactive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gisMap || !interactive) return;
|
||||
const clickKey = gisMap.on("singleclick", (event) => {
|
||||
const [longitude, latitude] = transform(
|
||||
event.coordinate,
|
||||
GisApp.TO_PROJ,
|
||||
GisApp.FROM_PROJ,
|
||||
);
|
||||
if (
|
||||
longitude === undefined ||
|
||||
latitude === undefined ||
|
||||
!Number.isFinite(longitude) ||
|
||||
!Number.isFinite(latitude)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onChangeRef.current?.({ longitude, latitude });
|
||||
});
|
||||
return () => unByKey(clickKey);
|
||||
}, [gisMap, interactive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gisMap || !gisCore || pipeLayerSettings.length === 0) return;
|
||||
setPipeLoadState("loading");
|
||||
let loadErrors = 0;
|
||||
const sourceEventKeys: EventsKey[] = [];
|
||||
const layers = pipeLayerSettings.map((setting, index) => {
|
||||
const layer = gisCore.addWfsLayer({
|
||||
...setting,
|
||||
id: `dredging-pipe-${setting.lyrSn ?? setting.id ?? index}`,
|
||||
clickPsblYn: "N",
|
||||
});
|
||||
layer.set("dredgingPipeLayer", true);
|
||||
const source = layer.getSource();
|
||||
const refreshCount = () => {
|
||||
setVisiblePipeCount(
|
||||
pipeLayersRef.current.reduce(
|
||||
(count, item) =>
|
||||
count + (item.layer.getSource()?.getFeatures().length ?? 0),
|
||||
0,
|
||||
),
|
||||
);
|
||||
setPipeLoadState(loadErrors > 0 ? "error" : "loaded");
|
||||
};
|
||||
if (source) {
|
||||
sourceEventKeys.push(
|
||||
source.on("featuresloadstart", () =>
|
||||
setPipeLoadState("loading"),
|
||||
) as EventsKey,
|
||||
source.on("featuresloadend", refreshCount) as EventsKey,
|
||||
source.on("featuresloaderror", () => {
|
||||
loadErrors += 1;
|
||||
refreshCount();
|
||||
}) as EventsKey,
|
||||
);
|
||||
}
|
||||
return { layer, baseStyle: layer.getStyle() ?? null };
|
||||
});
|
||||
pipeLayersRef.current = layers;
|
||||
|
||||
return () => {
|
||||
unByKey(sourceEventKeys);
|
||||
layers.forEach(({ layer }) => gisMap.removeLayer(layer));
|
||||
pipeLayersRef.current = [];
|
||||
setVisiblePipeCount(0);
|
||||
setPipeLoadState("idle");
|
||||
};
|
||||
}, [gisCore, gisMap, pipeLayerSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
const matchedFid = normalizePipeFid(matchedPipe?.fid);
|
||||
pipeLayersRef.current.forEach(({ layer, baseStyle }) => {
|
||||
const styleFunction: StyleFunction = (feature, resolution) =>
|
||||
matchedFid && normalizePipeFid(feature.getId()) === matchedFid
|
||||
? matchedPipeStyle
|
||||
: (resolveStyle(baseStyle, feature, resolution) ?? undefined);
|
||||
layer.setStyle(styleFunction);
|
||||
layer.changed();
|
||||
});
|
||||
}, [matchedPipe?.fid, pipeLayerSettings]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!gisMap || !markerLayerRef.current) return;
|
||||
const source = markerLayerRef.current.getSource();
|
||||
source?.clear();
|
||||
if (!value) {
|
||||
previousValueRef.current = null;
|
||||
return;
|
||||
}
|
||||
|
||||
const coordinate = transform(
|
||||
[value.longitude, value.latitude],
|
||||
GisApp.FROM_PROJ,
|
||||
GisApp.TO_PROJ,
|
||||
);
|
||||
source?.addFeature(new Feature({ geometry: new Point(coordinate) }));
|
||||
|
||||
const previous = previousValueRef.current;
|
||||
const locationChanged =
|
||||
!previous ||
|
||||
previous.longitude !== value.longitude ||
|
||||
previous.latitude !== value.latitude;
|
||||
// 사진 GPS가 처음 들어오거나 등록 건을 바꾼 때만 이동한다. 위치수정 진입처럼
|
||||
// interactive 상태만 바뀐 경우에는 사용자가 보고 있던 지도 범위를 유지한다.
|
||||
if (locationChanged && (!interactive || previous === null)) {
|
||||
gisMap.getView().animate({ center: coordinate, zoom: 17, duration: 250 });
|
||||
}
|
||||
previousValueRef.current = value;
|
||||
}, [gisMap, interactive, value?.latitude, value?.longitude]);
|
||||
|
||||
const pipeStatusText = (() => {
|
||||
if (pipeLayerSettings.length === 0)
|
||||
return "관망도 레이어 설정을 불러오는 중입니다.";
|
||||
if (pipeLoadState === "loading") return "관망도 관로를 불러오는 중입니다.";
|
||||
if (pipeLoadState === "error")
|
||||
return visiblePipeCount > 0
|
||||
? `일부 관로만 표시 중 · ${visiblePipeCount.toLocaleString()}건`
|
||||
: "관망도 관로를 불러오지 못했습니다.";
|
||||
if (pipeLoadState === "loaded")
|
||||
return visiblePipeCount > 0
|
||||
? `관망도 관로 ${visiblePipeCount.toLocaleString()}건 표시`
|
||||
: "현재 지도 범위에 표시할 관로가 없습니다.";
|
||||
return "지도를 확대하면 관망도 관로가 표시됩니다.";
|
||||
})();
|
||||
|
||||
return (
|
||||
<div className="rounded-sm border border-border bg-background px-2 py-1.5 text-xs text-label shadow">
|
||||
<p className="font-medium">
|
||||
{interactive
|
||||
? "지도를 클릭해 준설위치를 선택하세요."
|
||||
: "등록 위치와 관망도 관로를 함께 확인합니다."}
|
||||
</p>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
<span>관로 색상·굵기: 관망도 레이어 설정</span>
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
{/* 선택 관로를 지도에서 식별하는 범례 의미색이므로 고정 주황색을 유지한다. */}
|
||||
<span className="inline-block h-1.5 w-6 rounded bg-[#f97316]" />
|
||||
자동 연결 관로
|
||||
</span>
|
||||
<span
|
||||
className={
|
||||
pipeLoadState === "error"
|
||||
? "text-rose-600"
|
||||
: "text-muted-foreground"
|
||||
}
|
||||
data-testid="dredging-pipe-map-status"
|
||||
>
|
||||
{pipeStatusText}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const DredgingLocationMap = ({
|
||||
value,
|
||||
onChange,
|
||||
interactive = true,
|
||||
statusText,
|
||||
matchedPipe,
|
||||
height = "h-[540px]",
|
||||
}: DredgingLocationMapProps) => {
|
||||
const gisMaps = useRef<OlMap | null>(null);
|
||||
const [pipeLayerSettings, setPipeLayerSettings] = useState<LayerSetting[]>(
|
||||
[],
|
||||
);
|
||||
const defaultLonLat = useMemo<[number, number]>(
|
||||
() => (value ? [value.longitude, value.latitude] : [127.75, 36]),
|
||||
// 지도 최초 생성 위치만 사용하며 이후 위치 변경은 marker effect가 담당한다.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const load = async () => {
|
||||
try {
|
||||
const body = await getRawJson(
|
||||
"/sewerage-service/api/v1/map/lyrStngs/SN_NETWORK",
|
||||
);
|
||||
const rows = (body?.data ?? body ?? []) as LayerSetting[];
|
||||
if (!cancelled) {
|
||||
setPipeLayerSettings(
|
||||
flattenLayerSettings(rows).filter(isPipeLayerSetting),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("준설 등록 관망도 레이어 설정 조회 실패", error);
|
||||
if (!cancelled) setPipeLayerSettings([]);
|
||||
}
|
||||
};
|
||||
void load();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 flex-col overflow-hidden rounded-sm border border-border">
|
||||
<Gis
|
||||
treeData={[]}
|
||||
gisMaps={gisMaps}
|
||||
isSearch={false}
|
||||
isMiniMap={false}
|
||||
isOpen={false}
|
||||
setIsOpen={() => undefined}
|
||||
featureData={null}
|
||||
setFeatureData={() => undefined}
|
||||
isSearchModalOpen={false}
|
||||
setIsSearchModalOpen={() => undefined}
|
||||
searchBar={
|
||||
<LocationInteraction
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
interactive={interactive}
|
||||
matchedPipe={matchedPipe}
|
||||
pipeLayerSettings={pipeLayerSettings}
|
||||
/>
|
||||
}
|
||||
defaultZoom={value ? 17 : 7.5}
|
||||
defaultLonLat={defaultLonLat}
|
||||
height={height}
|
||||
showZoomLevel={true}
|
||||
showFloatingSearchButton={false}
|
||||
treeTogglePosition="top"
|
||||
/>
|
||||
<div
|
||||
className="shrink-0 border-t bg-secondary px-3 py-1.5 text-xs text-label"
|
||||
data-testid="dredging-map-status"
|
||||
>
|
||||
{statusText ??
|
||||
(interactive
|
||||
? "지도에서 준설위치를 선택해주세요."
|
||||
: value
|
||||
? "등록된 준설위치가 표시되었습니다."
|
||||
: "위치가 등록되지 않았습니다.")}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DredgingLocationMap;
|
||||
@@ -0,0 +1,678 @@
|
||||
/**
|
||||
* 화면명: 준설실적 등록
|
||||
* 준설 사진을 등록하고 촬영정보·위치·인접 관로를 확인하여 준설실적을 저장하는 화면이다.
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
import { DredgingRegistrationBody } from "@/features/dredging/ui/dredging-registration-body";
|
||||
import { StandardPopupLayout } from "@common/business_components";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@common/components";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
findNearestPipeMatches,
|
||||
saveDredgingRegistrations,
|
||||
type AttachmentReference,
|
||||
} from "@/features/dredging/api/dredging-api";
|
||||
import { isDredgingBackendEnabled } from "@/features/dredging/api/backend-mode";
|
||||
import { uploadDredgingPhotos } from "@/features/dredging/api/photo-upload";
|
||||
import { readPhotoMetadata } from "@/features/dredging/lib/exif";
|
||||
import { useDredgingCommonCodes } from "@/features/dredging/lib/use-dredging-common-codes";
|
||||
import { createDredgingClientUuid } from "@/features/dredging/lib/uuid";
|
||||
import { createDredgingRegistrationSession } from "@/features/dredging/model/registration-request";
|
||||
import {
|
||||
EMPTY_PHOTO_METADATA,
|
||||
type DredgingDraftGroup,
|
||||
type DredgingPhotoDraft,
|
||||
type DredgingSaveGroup,
|
||||
type GeoPoint,
|
||||
} from "@/features/dredging/model/types";
|
||||
|
||||
// 무거운 OpenLayers 지도 모듈은 준설 등록 본문과 별도 chunk로 지연 로드한다.
|
||||
const DredgingLocationMap = dynamic(
|
||||
() => import("@/features/dredging/ui/dredging-location-map"),
|
||||
{
|
||||
ssr: false,
|
||||
},
|
||||
);
|
||||
|
||||
type DredgingRegisterModalProps = {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSaved: (groups: DredgingSaveGroup[]) => void;
|
||||
presentation?: "modal" | "popup";
|
||||
};
|
||||
|
||||
const createGroup = (): DredgingDraftGroup => ({
|
||||
id: createDredgingClientUuid(),
|
||||
registrationMode: "PHOTO",
|
||||
photos: [],
|
||||
manualLocation: null,
|
||||
matchedPipe: null,
|
||||
matchError: null,
|
||||
isMatching: false,
|
||||
});
|
||||
|
||||
const needsManualLocation = (group: DredgingDraftGroup) =>
|
||||
group.registrationMode === "MANUAL" ||
|
||||
group.photos.some((photo) => !photo.metadata.location);
|
||||
|
||||
const getResolvedLocation = (group: DredgingDraftGroup): GeoPoint | null => {
|
||||
if (group.manualLocation) return group.manualLocation;
|
||||
return (
|
||||
group.photos.find((photo) => photo.metadata.location)?.metadata.location ??
|
||||
null
|
||||
);
|
||||
};
|
||||
|
||||
const formatLocalDate = (date: Date) => {
|
||||
const year = date.getFullYear();
|
||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(date.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
|
||||
const parseLocalDate = (value: string) => new Date(`${value}T00:00:00`);
|
||||
|
||||
const DredgingRegisterModal = ({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
presentation = "modal",
|
||||
}: DredgingRegisterModalProps) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { confirm } = useConfirm();
|
||||
// 등록방식·위치출처·사진상태 코드값은 유지하고 CMS 코드명을 화면에 표시한다.
|
||||
const { registrationModeLabels, locationSourceLabels, photoStatusLabels } =
|
||||
useDredgingCommonCodes();
|
||||
const [groups, setGroups] = useState<DredgingDraftGroup[]>([]);
|
||||
const groupsRef = useRef<DredgingDraftGroup[]>([]);
|
||||
const [activeGroupId, setActiveGroupId] = useState<string | null>(null);
|
||||
const [editingLocationGroupId, setEditingLocationGroupId] = useState<
|
||||
string | null
|
||||
>(null);
|
||||
// 지도 클릭 좌표는 적용 전까지 원본 EXIF 또는 확정 수동 위치를 덮어쓰지 않는 임시 상태다.
|
||||
const [locationDraft, setLocationDraft] = useState<GeoPoint | null>(null);
|
||||
// 모든 등록 그룹은 하나의 준설작업이며 화면 상단의 단일 준설일자를 공유한다.
|
||||
const [representativeDredgingDate, setRepresentativeDredgingDate] =
|
||||
useState("");
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const uploadedAttachmentsRef = useRef(new Map<string, AttachmentReference>());
|
||||
// 재렌더와 실패 재시도 사이에 요청 ID를 유지하며 모달 재진입에서만 새 세션으로 교체한다.
|
||||
const registrationSessionRef = useRef<ReturnType<
|
||||
typeof createDredgingRegistrationSession
|
||||
> | null>(null);
|
||||
// React의 다음 렌더 전에 발생하는 연속 저장 클릭도 같은 실행으로 제한한다.
|
||||
const savingRef = useRef(false);
|
||||
const [statusMessage, setStatusMessage] = useState("");
|
||||
|
||||
const commitGroups = (
|
||||
updater: (current: DredgingDraftGroup[]) => DredgingDraftGroup[],
|
||||
) => {
|
||||
const next = updater(groupsRef.current);
|
||||
groupsRef.current = next;
|
||||
setGroups(next);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
registrationSessionRef.current = createDredgingRegistrationSession();
|
||||
uploadedAttachmentsRef.current.clear();
|
||||
const initial = [createGroup()];
|
||||
groupsRef.current = initial;
|
||||
setGroups(initial);
|
||||
setActiveGroupId(initial[0]?.id ?? null);
|
||||
setEditingLocationGroupId(null);
|
||||
setLocationDraft(null);
|
||||
setRepresentativeDredgingDate("");
|
||||
setStatusMessage("");
|
||||
}, [open]);
|
||||
|
||||
/**
|
||||
* 그룹의 모든 사진 위치 또는 수동 좌표를 서버 후보 조회 형식으로 만들고,
|
||||
* 결과가 하나의 관로로 수렴하는지 확인한다.
|
||||
*/
|
||||
const resolvePipeMatch = async (group: DredgingDraftGroup) => {
|
||||
const locations =
|
||||
group.manualLocation !== null
|
||||
? [
|
||||
{
|
||||
locationKey: `${group.id}-manual`,
|
||||
...group.manualLocation,
|
||||
},
|
||||
]
|
||||
: group.photos
|
||||
.filter((photo) => photo.metadata.location)
|
||||
.map((photo) => ({
|
||||
locationKey: photo.key,
|
||||
...photo.metadata.location!,
|
||||
}));
|
||||
|
||||
const expectedLocationCount =
|
||||
group.manualLocation !== null
|
||||
? 1
|
||||
: group.registrationMode === "MANUAL"
|
||||
? 0
|
||||
: group.photos.length;
|
||||
|
||||
if (
|
||||
locations.length === 0 ||
|
||||
(group.registrationMode === "PHOTO" &&
|
||||
locations.length !== expectedLocationCount)
|
||||
) {
|
||||
commitGroups((current) =>
|
||||
current.map((item) =>
|
||||
item.id === group.id
|
||||
? {
|
||||
...item,
|
||||
matchedPipe: null,
|
||||
matchError: "지도에서 준설위치를 먼저 등록해주세요.",
|
||||
isMatching: false,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
commitGroups((current) =>
|
||||
current.map((item) =>
|
||||
item.id === group.id
|
||||
? { ...item, isMatching: true, matchError: null }
|
||||
: item,
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
const matches = await findNearestPipeMatches(locations);
|
||||
if (matches.size !== locations.length) {
|
||||
throw new Error("탐색거리 안에서 관로를 찾지 못한 위치가 있습니다.");
|
||||
}
|
||||
|
||||
const matchedPipes = Array.from(matches.values());
|
||||
const pipeKeys = new Set(
|
||||
matchedPipes.map(
|
||||
(pipe) => `${pipe.mngInstCd.trim()}::${pipe.fcltMngNo}`,
|
||||
),
|
||||
);
|
||||
if (pipeKeys.size !== 1) {
|
||||
throw new Error(
|
||||
"사진 위치가 서로 다른 관로로 매핑됩니다. 관로 그룹을 분리해주세요.",
|
||||
);
|
||||
}
|
||||
|
||||
const matchedPipe = matchedPipes[0] ?? null;
|
||||
commitGroups((current) =>
|
||||
current.map((item) =>
|
||||
item.id === group.id
|
||||
? {
|
||||
...item,
|
||||
matchedPipe,
|
||||
matchError: matchedPipe
|
||||
? null
|
||||
: "최근접 관로를 찾지 못했습니다.",
|
||||
isMatching: false,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
} catch (error) {
|
||||
commitGroups((current) =>
|
||||
current.map((item) =>
|
||||
item.id === group.id
|
||||
? {
|
||||
...item,
|
||||
matchedPipe: null,
|
||||
matchError:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "최근접 관로 조회에 실패했습니다.",
|
||||
isMatching: false,
|
||||
}
|
||||
: item,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFilesChange = async (
|
||||
groupId: string,
|
||||
selectedFiles: File[] | null,
|
||||
) => {
|
||||
const files = selectedFiles ?? [];
|
||||
if (files.length > 5) {
|
||||
alert("관로별 사진은 최대 5장까지 선택할 수 있습니다.");
|
||||
return;
|
||||
}
|
||||
if (editingLocationGroupId === groupId) {
|
||||
cancelLocationEditing();
|
||||
}
|
||||
|
||||
const checkingPhotos: DredgingPhotoDraft[] = files.map((file) => ({
|
||||
key: createDredgingClientUuid(),
|
||||
file,
|
||||
metadata: EMPTY_PHOTO_METADATA,
|
||||
}));
|
||||
|
||||
commitGroups((current) =>
|
||||
current.map((group) =>
|
||||
group.id === groupId
|
||||
? {
|
||||
...group,
|
||||
photos: checkingPhotos,
|
||||
manualLocation: null,
|
||||
matchedPipe: null,
|
||||
matchError: null,
|
||||
isMatching: false,
|
||||
}
|
||||
: group,
|
||||
),
|
||||
);
|
||||
|
||||
const parsedPhotos = await Promise.all(
|
||||
checkingPhotos.map(async (photo) => ({
|
||||
...photo,
|
||||
metadata: await readPhotoMetadata(photo.file),
|
||||
})),
|
||||
);
|
||||
|
||||
// 최초 사진의 촬영일을 공통 준설일자 초깃값으로만 사용한다.
|
||||
// 이후 다른 사진을 추가하거나 탭을 바꿔도 사용자가 수정한 값은 덮어쓰지 않는다.
|
||||
const firstPhotoDate = parsedPhotos.find(
|
||||
(photo) => photo.metadata.dredgingDate,
|
||||
)?.metadata.dredgingDate;
|
||||
if (firstPhotoDate) {
|
||||
setRepresentativeDredgingDate((current) => current || firstPhotoDate);
|
||||
}
|
||||
|
||||
let nextGroup: DredgingDraftGroup | null = null;
|
||||
commitGroups((current) =>
|
||||
current.map((group) => {
|
||||
if (group.id !== groupId) return group;
|
||||
nextGroup = { ...group, photos: parsedPhotos };
|
||||
return nextGroup;
|
||||
}),
|
||||
);
|
||||
|
||||
if (nextGroup) {
|
||||
const groupToResolve: DredgingDraftGroup = nextGroup;
|
||||
if (!needsManualLocation(groupToResolve)) {
|
||||
await resolvePipeMatch(groupToResolve);
|
||||
} else {
|
||||
commitGroups((current) =>
|
||||
current.map((group) =>
|
||||
group.id === groupId
|
||||
? {
|
||||
...group,
|
||||
matchError: "GPS가 없는 사진은 지도 위치 등록이 필요합니다.",
|
||||
}
|
||||
: group,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 공통 첨부영역의 중복 파일목록은 숨기고 메타정보 표를 단일 파일목록으로 사용한다.
|
||||
* 표의 삭제 버튼도 공통 FileUpload와 같은 files 배열 갱신 흐름으로 연결한다.
|
||||
*/
|
||||
const removePhoto = (groupId: string, photoKey: string) => {
|
||||
const group = groupsRef.current.find((item) => item.id === groupId);
|
||||
if (!group) return;
|
||||
void handleFilesChange(
|
||||
groupId,
|
||||
group.photos
|
||||
.filter((photo) => photo.key !== photoKey)
|
||||
.map((photo) => photo.file),
|
||||
);
|
||||
};
|
||||
|
||||
const changeRegistrationMode = async (
|
||||
groupId: string,
|
||||
registrationMode: DredgingDraftGroup["registrationMode"],
|
||||
) => {
|
||||
const currentGroup = groupsRef.current.find(
|
||||
(group) => group.id === groupId,
|
||||
);
|
||||
if (!currentGroup || currentGroup.registrationMode === registrationMode) {
|
||||
return;
|
||||
}
|
||||
const hasEnteredData =
|
||||
currentGroup.photos.length > 0 || currentGroup.manualLocation !== null;
|
||||
if (
|
||||
hasEnteredData &&
|
||||
!(await confirm(
|
||||
"등록 방식을 변경하면 현재 사진과 입력한 위치가 초기화됩니다. 변경하시겠습니까?",
|
||||
))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
commitGroups((current) =>
|
||||
current.map((group) =>
|
||||
group.id === groupId
|
||||
? {
|
||||
...group,
|
||||
registrationMode,
|
||||
photos: registrationMode === "MANUAL" ? [] : group.photos,
|
||||
matchedPipe: null,
|
||||
matchError: null,
|
||||
manualLocation: null,
|
||||
}
|
||||
: group,
|
||||
),
|
||||
);
|
||||
setActiveGroupId(groupId);
|
||||
setLocationDraft(null);
|
||||
setEditingLocationGroupId(null);
|
||||
};
|
||||
|
||||
const updateManualLocation = async (
|
||||
groupId: string,
|
||||
manualLocation: GeoPoint,
|
||||
) => {
|
||||
const currentGroup = groupsRef.current.find(
|
||||
(group) => group.id === groupId,
|
||||
);
|
||||
if (!currentGroup) return;
|
||||
|
||||
const nextGroup = {
|
||||
...currentGroup,
|
||||
manualLocation,
|
||||
matchedPipe: null,
|
||||
matchError: null,
|
||||
};
|
||||
commitGroups((current) =>
|
||||
current.map((group) => (group.id === groupId ? nextGroup : group)),
|
||||
);
|
||||
await resolvePipeMatch(nextGroup);
|
||||
};
|
||||
|
||||
// 본문 하단 지도 편집은 현재 확정 위치를 복사한 임시 마커에서 시작한다.
|
||||
const startLocationEditing = (group: DredgingDraftGroup) => {
|
||||
setActiveGroupId(group.id);
|
||||
setEditingLocationGroupId(group.id);
|
||||
setLocationDraft(getResolvedLocation(group));
|
||||
setStatusMessage("");
|
||||
};
|
||||
|
||||
// 취소 시 적용하지 않은 지도 클릭 위치를 폐기하고 기존 위치를 유지한다.
|
||||
const cancelLocationEditing = () => {
|
||||
setEditingLocationGroupId(null);
|
||||
setLocationDraft(null);
|
||||
};
|
||||
|
||||
// 새 지도 좌표를 선택하면 이전 위치에서 발생한 저장 오류 안내를 즉시 비운다.
|
||||
const changeLocationDraft = (point: GeoPoint) => {
|
||||
setLocationDraft(point);
|
||||
setStatusMessage("");
|
||||
};
|
||||
|
||||
// 사용자가 명시적으로 적용한 위치만 확정 상태와 최근접 관로 조회에 반영한다.
|
||||
const applyLocationDraft = async () => {
|
||||
if (!editingLocationGroupId || !locationDraft) {
|
||||
alert("지도에서 준설위치를 선택해주세요.");
|
||||
return;
|
||||
}
|
||||
setStatusMessage("");
|
||||
await updateManualLocation(editingLocationGroupId, locationDraft);
|
||||
cancelLocationEditing();
|
||||
};
|
||||
|
||||
const validateAndBuildSaveGroups = () => {
|
||||
if (!representativeDredgingDate) {
|
||||
throw new Error("준설일자를 입력해주세요.");
|
||||
}
|
||||
if (representativeDredgingDate > formatLocalDate(new Date())) {
|
||||
throw new Error("미래 날짜는 준설일자로 등록할 수 없습니다.");
|
||||
}
|
||||
|
||||
const saveGroups: DredgingSaveGroup[] = [];
|
||||
for (let index = 0; index < groups.length; index += 1) {
|
||||
const group = groups[index]!;
|
||||
const label = `관로 ${index + 1}`;
|
||||
if (group.registrationMode === "PHOTO" && group.photos.length === 0) {
|
||||
throw new Error(`${label}: 사진을 선택해주세요.`);
|
||||
}
|
||||
if (group.photos.length > 5) {
|
||||
throw new Error(`${label}: 사진은 최대 5장까지 등록할 수 있습니다.`);
|
||||
}
|
||||
|
||||
const location = getResolvedLocation(group);
|
||||
if (!location) {
|
||||
throw new Error(`${label}: 지도에서 준설위치를 등록해주세요.`);
|
||||
}
|
||||
if (!group.matchedPipe) {
|
||||
throw new Error(
|
||||
`${label}: ${group.matchError ?? "최근접 관로 자동 매핑을 완료해주세요."}`,
|
||||
);
|
||||
}
|
||||
saveGroups.push({
|
||||
localId: group.id,
|
||||
registrationMode: group.registrationMode,
|
||||
dredgingDate: representativeDredgingDate,
|
||||
location,
|
||||
locationSource: group.manualLocation ? "MANUAL" : "EXIF",
|
||||
pipe: group.matchedPipe,
|
||||
photos: group.photos,
|
||||
});
|
||||
}
|
||||
return saveGroups;
|
||||
};
|
||||
|
||||
// 검증·업로드 후 등록 payload를 확정하며 HTTP 실패 시 세션 ID와 첨부를 유지한다.
|
||||
const handleSave = async () => {
|
||||
if (savingRef.current) return;
|
||||
try {
|
||||
const saveGroups = validateAndBuildSaveGroups();
|
||||
savingRef.current = true;
|
||||
setIsSaving(true);
|
||||
setStatusMessage(
|
||||
isDredgingBackendEnabled
|
||||
? "공통 첨부파일 업로드를 시작합니다."
|
||||
: "등록 내용을 확인하고 있습니다.",
|
||||
);
|
||||
|
||||
const attachments = await uploadDredgingPhotos(
|
||||
saveGroups,
|
||||
uploadedAttachmentsRef.current,
|
||||
);
|
||||
uploadedAttachmentsRef.current = attachments;
|
||||
setStatusMessage(
|
||||
isDredgingBackendEnabled
|
||||
? "준설 결과와 관로 매핑을 저장하고 있습니다."
|
||||
: "준설 결과 등록을 완료했습니다.",
|
||||
);
|
||||
const session =
|
||||
registrationSessionRef.current ?? createDredgingRegistrationSession();
|
||||
registrationSessionRef.current = session;
|
||||
await saveDredgingRegistrations(
|
||||
session.prepare(saveGroups, attachments, isDredgingBackendEnabled),
|
||||
);
|
||||
// 성공 안내가 닫히기 전 재클릭에도 같은 ID·첨부를 사용한다. 다음 open에서 초기화한다.
|
||||
onSaved(saveGroups);
|
||||
alert("준설 결과를 등록했습니다.", () => onOpenChange(false));
|
||||
} catch (error) {
|
||||
const message =
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "준설 결과 저장에 실패했습니다.";
|
||||
setStatusMessage(message);
|
||||
alert(message);
|
||||
} finally {
|
||||
savingRef.current = false;
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const activeGroup =
|
||||
groups.find((group) => group.id === activeGroupId) ?? groups[0] ?? null;
|
||||
const activeResolvedLocation = activeGroup
|
||||
? getResolvedLocation(activeGroup)
|
||||
: null;
|
||||
const isEditingActiveLocation =
|
||||
activeGroup !== null && editingLocationGroupId === activeGroup.id;
|
||||
// 지도에서 새로 찍은 좌표가 아직 확정 위치와 다른지 구분해 이전 좌표의 관로 오류를 노출하지 않는다.
|
||||
const hasUnappliedLocationDraft = Boolean(
|
||||
isEditingActiveLocation &&
|
||||
locationDraft &&
|
||||
(!activeResolvedLocation ||
|
||||
locationDraft.longitude !== activeResolvedLocation.longitude ||
|
||||
locationDraft.latitude !== activeResolvedLocation.latitude),
|
||||
);
|
||||
|
||||
// 새 관로 등록 건을 만든 뒤 즉시 해당 건을 편집 대상으로 전환한다.
|
||||
const addGroup = () => {
|
||||
const nextGroup = createGroup();
|
||||
commitGroups((current) => [...current, nextGroup]);
|
||||
setActiveGroupId(nextGroup.id);
|
||||
cancelLocationEditing();
|
||||
};
|
||||
|
||||
// 첫 번째 등록 건은 기준 건으로 유지하고 두 번째 건부터 탭의 X로 삭제한다.
|
||||
const removeGroup = (groupId: string) => {
|
||||
const removeIndex = groupsRef.current.findIndex(
|
||||
(group) => group.id === groupId,
|
||||
);
|
||||
if (removeIndex <= 0) return;
|
||||
const remainingGroups = groupsRef.current.filter(
|
||||
(group) => group.id !== groupId,
|
||||
);
|
||||
commitGroups(() => remainingGroups);
|
||||
if (activeGroupId === groupId) {
|
||||
setActiveGroupId(
|
||||
remainingGroups[Math.max(0, removeIndex - 1)]?.id ??
|
||||
remainingGroups[0]?.id ??
|
||||
null,
|
||||
);
|
||||
}
|
||||
cancelLocationEditing();
|
||||
};
|
||||
|
||||
// 등록 건을 바꾸면 적용하지 않은 지도 임시 위치는 폐기한다.
|
||||
const selectGroup = (groupId: string) => {
|
||||
setActiveGroupId(groupId);
|
||||
cancelLocationEditing();
|
||||
};
|
||||
|
||||
const modalBody = (
|
||||
<DredgingRegistrationBody
|
||||
presentation={presentation}
|
||||
groups={groups}
|
||||
activeGroup={activeGroup}
|
||||
representativeDredgingDate={representativeDredgingDate}
|
||||
setRepresentativeDredgingDate={setRepresentativeDredgingDate}
|
||||
parseLocalDate={parseLocalDate}
|
||||
formatLocalDate={formatLocalDate}
|
||||
getResolvedLocation={getResolvedLocation}
|
||||
addGroup={addGroup}
|
||||
removeGroup={removeGroup}
|
||||
selectGroup={selectGroup}
|
||||
changeRegistrationMode={changeRegistrationMode}
|
||||
handleFilesChange={handleFilesChange}
|
||||
removePhoto={removePhoto}
|
||||
registrationModeLabels={registrationModeLabels}
|
||||
photoStatusLabels={photoStatusLabels}
|
||||
locationSourceLabels={locationSourceLabels}
|
||||
isEditingActiveLocation={isEditingActiveLocation}
|
||||
locationDraft={locationDraft}
|
||||
applyLocationDraft={applyLocationDraft}
|
||||
cancelLocationEditing={cancelLocationEditing}
|
||||
startLocationEditing={startLocationEditing}
|
||||
activeResolvedLocation={activeResolvedLocation}
|
||||
hasUnappliedLocationDraft={hasUnappliedLocationDraft}
|
||||
statusMessage={statusMessage}
|
||||
changeLocationDraft={changeLocationDraft}
|
||||
LocationMap={DredgingLocationMap}
|
||||
/>
|
||||
);
|
||||
|
||||
if (presentation === "popup") {
|
||||
return (
|
||||
<StandardPopupLayout
|
||||
title="준설결과 등록"
|
||||
showDefaultCancelAction={false}
|
||||
actions={
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
disabled={isSaving}
|
||||
onClick={() => {
|
||||
void handleSave();
|
||||
}}
|
||||
data-testid="dredging-save-button"
|
||||
>
|
||||
{isSaving ? "저장 중..." : "저장"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
color="white"
|
||||
disabled={isSaving}
|
||||
onClick={() => window.close()}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
bodyClassName="!overflow-hidden"
|
||||
>
|
||||
{modalBody}
|
||||
</StandardPopupLayout>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (!isSaving) onOpenChange(nextOpen);
|
||||
}}
|
||||
>
|
||||
<DialogContent className="w-[92vw] !max-w-[1200px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>준설결과 업로드</DialogTitle>
|
||||
</DialogHeader>
|
||||
{open ? modalBody : null}
|
||||
<DialogFooter>
|
||||
<div className="flex w-full justify-end gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
disabled={isSaving}
|
||||
onClick={() => {
|
||||
void handleSave();
|
||||
}}
|
||||
data-testid="dredging-save-button"
|
||||
>
|
||||
{isSaving ? "저장 중..." : "저장"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
color="white"
|
||||
disabled={isSaving}
|
||||
onClick={() => onOpenChange(false)}
|
||||
>
|
||||
취소
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default DredgingRegisterModal;
|
||||
@@ -0,0 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { postPopupMessage } from "@/features/window-popup/lib/popup-message";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
|
||||
import DredgingRegisterModal from "@/features/dredging/ui/dredging-register-modal";
|
||||
|
||||
/** 기존 준설 등록 흐름을 공통 WindowPopup 화면 규격으로 표시한다. */
|
||||
const DredgingRegisterPopupPage = () => (
|
||||
<DredgingRegisterModal
|
||||
open
|
||||
presentation="popup"
|
||||
onSaved={(groups) => {
|
||||
postPopupMessage(WINDOW_POPUP_MESSAGE_TYPE.DREDGING_REGISTERED, {
|
||||
groups: JSON.stringify(groups),
|
||||
});
|
||||
}}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) window.close();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
export default DredgingRegisterPopupPage;
|
||||
@@ -21,14 +21,8 @@ import {
|
||||
PIPE_DETAIL_DEFECT_COLUMNS,
|
||||
} from "../model/exmn-detail-table";
|
||||
|
||||
import {
|
||||
getBlobData,
|
||||
getData,
|
||||
getRawJson,
|
||||
postMutiPart,
|
||||
postRawJson,
|
||||
putData,
|
||||
} from "@/components/lib/api";
|
||||
import { getBlobData, postMutiPart } from "@/shared/api/file-api";
|
||||
import { getData, getRawJson, postRawJson, putData } from "@/shared/api/sewerage-api";
|
||||
|
||||
/** 조사사업 API의 공통 기준 경로다. */
|
||||
const EXMN_BUSINESS_API_PATH = "v1/exmnBusinesses";
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { requestGridExcel } from "@/shared/api/grid-export";
|
||||
import { PPL_STATUS_LABELS } from "./exmn-business-api";
|
||||
import type { ExmnJobType } from "../model/exmn-business-types";
|
||||
import type { ExmnDetailDefectType } from "../model/exmn-detail-table";
|
||||
|
||||
type DetailExportRequest = {
|
||||
exmnBizId: string;
|
||||
jobType: ExmnJobType;
|
||||
trtdstId: string;
|
||||
gisManagementNo: string;
|
||||
defectType: ExmnDetailDefectType;
|
||||
mode: "PIPE" | "UNIT";
|
||||
sort?: string;
|
||||
defectColumns: Array<{ code: string; label: string }>;
|
||||
recordTypeLabels: Record<string, string>;
|
||||
pipeItemLabels: Record<string, string>;
|
||||
severityLabels: Record<string, string>;
|
||||
};
|
||||
|
||||
/** 현재 페이지 행을 받지 않고 적용조건 전체와 표시명만 서버 Excel 작업에 전달한다. */
|
||||
export function downloadExmnDetailExcel(
|
||||
request: DetailExportRequest,
|
||||
fileName: string,
|
||||
) {
|
||||
return requestGridExcel(
|
||||
"v1/exmnFacilities/exportJobs",
|
||||
{
|
||||
...request,
|
||||
pipeItemLabels: { ...PPL_STATUS_LABELS, ...request.pipeItemLabels },
|
||||
},
|
||||
fileName,
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getData, putData } from "@/components/lib/api";
|
||||
import { getData, putData } from "@/shared/api/sewerage-api";
|
||||
import type {
|
||||
TrtdstBatchRequest,
|
||||
TrtdstBatchResponse,
|
||||
|
||||
@@ -4,7 +4,7 @@ export * from "./lib/exmn-business-validation";
|
||||
export * from "./lib/trtdst-validation";
|
||||
export * from "./model/exmn-business-types";
|
||||
export * from "./model/trtdst-types";
|
||||
export * from "./ui/ExmnRegistrationPage";
|
||||
export * from "./ui/ExmnStatusPage";
|
||||
export * from "./ui/ExmnStatusDetailPanel";
|
||||
export * from "./ui/TrtdstManagementPage";
|
||||
export * from "./ui/exmn-registration-page";
|
||||
export * from "./ui/exmn-status-page";
|
||||
export * from "./ui/exmn-status-detail-panel";
|
||||
export * from "./ui/trtdst-management-page";
|
||||
|
||||
+1
-4
@@ -2,10 +2,7 @@
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
getCommonCodes,
|
||||
type CommonCodeItem,
|
||||
} from "@/components/lib/common/apiHelpers";
|
||||
import { getCommonCodes, type CommonCodeItem } from "@/entities/code/api/common-code-api";
|
||||
|
||||
type CodeLabelMap = Record<string, string>;
|
||||
type ExmnCodeGroup =
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import type { UiTableSort } from "@common/business_components";
|
||||
import {
|
||||
getExmnFacilityPage,
|
||||
getExmnPplUnitPage,
|
||||
} from "../api/exmn-business-api";
|
||||
import type { ExmnBusiness, ExmnJobType } from "../model/exmn-business-types";
|
||||
import type {
|
||||
ExmnDetailDefectType,
|
||||
ExmnPplUnitDetailRow,
|
||||
ExmnSurveyDetailRow,
|
||||
} from "../model/exmn-detail-table";
|
||||
|
||||
type DetailQuery = {
|
||||
business: Pick<ExmnBusiness, "exmnBizId">;
|
||||
jobType: ExmnJobType;
|
||||
selectedTrtdstId: string;
|
||||
appliedDetailNumberKeyword: string;
|
||||
defectType: ExmnDetailDefectType;
|
||||
visibleDefectColumns: ReadonlyArray<{ code: string }>;
|
||||
page: number;
|
||||
sort?: UiTableSort;
|
||||
isUnitMode: boolean;
|
||||
isDefectTypeView: boolean;
|
||||
searchRequestSeq: number;
|
||||
};
|
||||
|
||||
/** 상세 목록과 구간 목록의 서버 조회·전체 합계·요청 취소 경계를 소유한다.
|
||||
* 부모는 적용조건만 전달하며 현재 페이지 배열로 전체 합계를 계산하지 않는다.
|
||||
*/
|
||||
export function useExmnDetailData({
|
||||
business,
|
||||
jobType,
|
||||
selectedTrtdstId,
|
||||
appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
visibleDefectColumns,
|
||||
page,
|
||||
sort,
|
||||
isUnitMode,
|
||||
isDefectTypeView,
|
||||
searchRequestSeq,
|
||||
}: DetailQuery) {
|
||||
const [actualRows, setActualRows] = useState<ExmnSurveyDetailRow[]>([]);
|
||||
const [actualUnitRows, setActualUnitRows] = useState<ExmnPplUnitDetailRow[]>(
|
||||
[],
|
||||
);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [serverSummary, setServerSummary] =
|
||||
useState<ExmnSurveyDetailRow | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (isUnitMode || !selectedTrtdstId) {
|
||||
setActualRows([]);
|
||||
setIsLoading(false);
|
||||
setLoadError(null);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
setActualRows([]);
|
||||
setIsLoading(true);
|
||||
setLoadError(null);
|
||||
void getExmnFacilityPage({
|
||||
exmnBizId: business.exmnBizId,
|
||||
jobType,
|
||||
trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
defectCodes: visibleDefectColumns.map((column) => column.code).join(","),
|
||||
page: page - 1,
|
||||
size: 10,
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
})
|
||||
.then((result) => {
|
||||
if (active) {
|
||||
setActualRows(result.content);
|
||||
setTotal(result.totalElements);
|
||||
setServerSummary(result.summary);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!active) return;
|
||||
setActualRows([]);
|
||||
setTotal(0);
|
||||
setServerSummary(null);
|
||||
setLoadError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "조사 상세 집계 조회 중 오류가 발생했습니다.",
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [
|
||||
appliedDetailNumberKeyword,
|
||||
business.exmnBizId,
|
||||
defectType,
|
||||
isUnitMode,
|
||||
jobType,
|
||||
searchRequestSeq,
|
||||
selectedTrtdstId,
|
||||
page,
|
||||
sort,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isUnitMode || isDefectTypeView || !selectedTrtdstId) {
|
||||
setActualUnitRows([]);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
setActualUnitRows([]);
|
||||
setIsLoading(true);
|
||||
setLoadError(null);
|
||||
void getExmnPplUnitPage({
|
||||
exmnBizId: business.exmnBizId,
|
||||
trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword,
|
||||
page: page - 1,
|
||||
size: 10,
|
||||
})
|
||||
.then((result) => {
|
||||
if (active) {
|
||||
setActualUnitRows(result.content);
|
||||
setTotal(result.totalElements);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!active) return;
|
||||
setActualUnitRows([]);
|
||||
setTotal(0);
|
||||
setLoadError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "본단위구간 조회 중 오류가 발생했습니다.",
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [
|
||||
appliedDetailNumberKeyword,
|
||||
business.exmnBizId,
|
||||
isDefectTypeView,
|
||||
isUnitMode,
|
||||
searchRequestSeq,
|
||||
selectedTrtdstId,
|
||||
page,
|
||||
]);
|
||||
/** 처리분구 전환 직후 이전 행을 숨기는 기존 UI 동작을 유지한다. */
|
||||
const clearRows = () => {
|
||||
setActualRows([]);
|
||||
setActualUnitRows([]);
|
||||
};
|
||||
return {
|
||||
actualRows,
|
||||
actualUnitRows,
|
||||
total,
|
||||
serverSummary,
|
||||
isLoading,
|
||||
loadError,
|
||||
clearRows,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/** 조사 상세 표의 컬럼·표시 변환. 서버 조회/React 상태와 분리한다. */
|
||||
import type {
|
||||
ExmnDetailSeverity,
|
||||
ExmnDetailDefectType,
|
||||
ExmnPplDetailMode,
|
||||
ExmnSurveyDetailRow,
|
||||
} from "./exmn-detail-table";
|
||||
|
||||
export const DEFAULT_SEVERITY_LABELS: Record<ExmnDetailSeverity, string> = {
|
||||
L: "대",
|
||||
M: "중",
|
||||
S: "소",
|
||||
};
|
||||
|
||||
/** 관로 상세보기에서 조회 결과 표를 전환하는 모드 표시 문구다. */
|
||||
export const PPL_DETAIL_MODE_LABELS: Record<ExmnPplDetailMode, string> = {
|
||||
PIPE: "관로",
|
||||
UNIT: "본단위구간",
|
||||
};
|
||||
|
||||
export const DEFAULT_DEFECT_TYPE_LABELS: Record<ExmnDetailDefectType, string> =
|
||||
{
|
||||
ALL: "전체",
|
||||
STRUCTURAL: "구조적결함",
|
||||
OPERATIONAL: "운영적결함",
|
||||
};
|
||||
|
||||
export const FIXED_COLUMNS = [
|
||||
{ id: "reportNo", label: "보고서\n번호", width: 118 },
|
||||
{ id: "pipeNo", label: "관로\n번호", width: 120 },
|
||||
{ id: "upstreamManhole", label: "상류\n맨홀", width: 135 },
|
||||
{ id: "downstreamManhole", label: "하류\n맨홀", width: 135 },
|
||||
{ id: "drainageType", label: "배수\n방식", width: 82 },
|
||||
{ id: "pipeType", label: "관종", width: 76 },
|
||||
{ id: "specification", label: "규격", width: 82 },
|
||||
{ id: "extensionM", label: "연장", width: 86 },
|
||||
{ id: "drivingDistanceM", label: "주행\n거리", width: 92 },
|
||||
{ id: "structuralGrade", label: "구조적\n내부결함", width: 105 },
|
||||
{ id: "operationalGrade", label: "운영적\n내부결함", width: 105 },
|
||||
] as const;
|
||||
|
||||
export const REPORT_COLUMN_LEFT = 0;
|
||||
|
||||
export const PIPE_COLUMN_LEFT = FIXED_COLUMNS[0].width;
|
||||
|
||||
export const STICKY_COLUMN_COUNT = 2;
|
||||
|
||||
export const STICKY_DIVIDER_SHADOW = "2px 0 0 hsl(var(--border))";
|
||||
|
||||
export const SEVERITY_COLUMN_WIDTH = 52;
|
||||
|
||||
export type ExmnDetailFixedColumnId = (typeof FIXED_COLUMNS)[number]["id"];
|
||||
|
||||
/** 숫자를 엑셀 화면과 같은 최대 소수점 1자리 형식으로 표시한다. */
|
||||
export const formatNumber = (value: number) =>
|
||||
value.toLocaleString("ko-KR", { maximumFractionDigits: 1 });
|
||||
|
||||
/** 이상항목이 없는 셀은 0 대신 엑셀형 빈 상태인 하이픈으로 표시한다. */
|
||||
export const formatCount = (value: number | null | undefined) =>
|
||||
Number(value ?? 0) === 0 ? "-" : Number(value).toLocaleString("ko-KR");
|
||||
|
||||
/** 공통 고정 열의 행 값을 화면용 문자열로 변환한다. */
|
||||
export const getFixedCellValue = (
|
||||
row: ExmnSurveyDetailRow,
|
||||
columnId: ExmnDetailFixedColumnId,
|
||||
) => {
|
||||
if (columnId === "drainageType") {
|
||||
return row.drainageTypeName?.trim() || row.drainageType;
|
||||
}
|
||||
if (columnId === "pipeType") {
|
||||
return row.pipeTypeName?.trim() || row.pipeType;
|
||||
}
|
||||
const value = row[columnId];
|
||||
return typeof value === "number" ? formatNumber(value) : value;
|
||||
};
|
||||
+5
-5
@@ -4,8 +4,8 @@ import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
|
||||
import { postPopupMessage } from "@/features/windowPopup/lib/popupMessage";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
import { postPopupMessage } from "@/features/window-popup/lib/popup-message";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import {
|
||||
StandardFormField,
|
||||
StandardFormSection,
|
||||
@@ -37,9 +37,9 @@ import type {
|
||||
} from "../model/exmn-business-types";
|
||||
import type { TrtdstSettingDto } from "../model/trtdst-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { getStartYearArray } from "@/components/ui/YearRangeSelectBox";
|
||||
import useStore from "@/store/useStore";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { getStartYearArray } from "@/components/ui/year-range-select-box";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
|
||||
type Notice = { type: "success" | "error" | "info"; text: string } | null;
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"use client";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@common/components";
|
||||
import PopupSearchPanel, {
|
||||
PopupSearchActions,
|
||||
} from "@/features/window-popup/ui/popup-search-panel";
|
||||
import { PPL_DETAIL_MODE_LABELS } from "../model/exmn-detail-view";
|
||||
import type {
|
||||
ExmnSectionSummaryRow,
|
||||
ExmnJobType,
|
||||
} from "../model/exmn-business-types";
|
||||
import type { ExmnPplDetailMode } from "../model/exmn-detail-table";
|
||||
|
||||
type Props = {
|
||||
districtOptions: ExmnSectionSummaryRow[];
|
||||
selectedTrtdstId: string;
|
||||
trtdstId: string;
|
||||
trtdstNm: string;
|
||||
detailNumberKeyword: string;
|
||||
detailMode: ExmnPplDetailMode;
|
||||
jobType: ExmnJobType;
|
||||
onDistrictChange: (value: string) => void;
|
||||
onKeywordChange: (value: string) => void;
|
||||
onModeChange: (mode: ExmnPplDetailMode) => void;
|
||||
onSearch: () => void;
|
||||
onReset: () => void;
|
||||
};
|
||||
|
||||
/** 상세 검색 입력만 렌더링한다. 적용조건·조회·리셋 상태는 부모가 소유한다. */
|
||||
export function ExmnDetailSearchPanel({
|
||||
districtOptions,
|
||||
selectedTrtdstId,
|
||||
trtdstId,
|
||||
trtdstNm,
|
||||
detailNumberKeyword,
|
||||
detailMode,
|
||||
jobType,
|
||||
onDistrictChange,
|
||||
onKeywordChange,
|
||||
onModeChange,
|
||||
onSearch,
|
||||
onReset,
|
||||
}: Props) {
|
||||
return (
|
||||
<PopupSearchPanel contentClassName="gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label
|
||||
htmlFor="exmn-detail-district"
|
||||
className="mr-2 whitespace-nowrap text-label"
|
||||
>
|
||||
처리분구
|
||||
</Label>
|
||||
<Select value={selectedTrtdstId} onValueChange={onDistrictChange}>
|
||||
<SelectTrigger id="exmn-detail-district" className="w-[18rem]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{districtOptions.length > 0 ? (
|
||||
districtOptions.map((district) => (
|
||||
<SelectItem key={district.trtdstId} value={district.trtdstId}>
|
||||
{district.trtdstNm}
|
||||
</SelectItem>
|
||||
))
|
||||
) : (
|
||||
<SelectItem value={trtdstId}>{trtdstNm}</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Label
|
||||
htmlFor="exmn-detail-pipe-number"
|
||||
className="mr-2 whitespace-nowrap text-label"
|
||||
>
|
||||
관로번호
|
||||
</Label>
|
||||
<Input
|
||||
id="exmn-detail-pipe-number"
|
||||
className="w-[30rem]"
|
||||
value={detailNumberKeyword}
|
||||
placeholder="관로번호 입력"
|
||||
onChange={(event) => onKeywordChange(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") onSearch();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{jobType === "PPL" && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">상세구분</Label>
|
||||
<div
|
||||
className="flex items-center gap-1"
|
||||
role="group"
|
||||
aria-label="관로 상세보기 모드"
|
||||
>
|
||||
{(Object.keys(PPL_DETAIL_MODE_LABELS) as ExmnPplDetailMode[]).map(
|
||||
(mode) => (
|
||||
<Button
|
||||
key={mode}
|
||||
type="button"
|
||||
color={detailMode === mode ? "primary" : "white"}
|
||||
aria-pressed={detailMode === mode}
|
||||
onClick={() => onModeChange(mode)}
|
||||
>
|
||||
{PPL_DETAIL_MODE_LABELS[mode]}
|
||||
</Button>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PopupSearchActions>
|
||||
<Button type="button" color="primary" onClick={onSearch}>
|
||||
조회
|
||||
</Button>
|
||||
<Button type="button" color="white" onClick={onReset}>
|
||||
초기화
|
||||
</Button>
|
||||
</PopupSearchActions>
|
||||
</PopupSearchPanel>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -6,7 +6,7 @@ import {
|
||||
type ExmnDetailSeverity,
|
||||
type ExmnPplUnitDetailRow,
|
||||
} from "../model/exmn-detail-table";
|
||||
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
|
||||
import { useExmnCommonCodes } from "../lib/use-exmn-common-codes";
|
||||
|
||||
const DEFAULT_SEVERITY_LABELS: Record<ExmnDetailSeverity, string> = {
|
||||
L: "대",
|
||||
+7
-7
@@ -1,12 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { getSnRowNumber } from "@/shared/lib/row-number";
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { fileDownload } from "@/components/lib/utils";
|
||||
import { getStartYearArray } from "@/components/ui/YearRangeSelectBox";
|
||||
import { openWindowPopup } from "@/features/windowPopup/lib/openWindowPopup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
import useStore from "@/store/useStore";
|
||||
import { getStartYearArray } from "@/components/ui/year-range-select-box";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
@@ -38,8 +38,8 @@ import type {
|
||||
ExmnBusiness,
|
||||
ExmnBusinessSearchParams,
|
||||
} from "../model/exmn-business-types";
|
||||
import { ExmnStatusDetailPanel } from "./ExmnStatusDetailPanel";
|
||||
import { EXMN_TABLE_HEADER_CLASS } from "./ExmnStandardDataTable";
|
||||
import { ExmnStatusDetailPanel } from "./exmn-status-detail-panel";
|
||||
import { EXMN_TABLE_HEADER_CLASS } from "./exmn-standard-data-table";
|
||||
|
||||
const BUSINESS_LIST_PAGE_SIZE = 10;
|
||||
|
||||
+3
-3
@@ -1,9 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { handleUpload } from "@/components/lib/utils";
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { postPopupMessageAndClose } from "@/features/windowPopup/lib/popupMessage";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { postPopupMessageAndClose } from "@/features/window-popup/lib/popup-message";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import {
|
||||
StandardFormField,
|
||||
StandardFormSection,
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { openWindowPopup } from "@/features/windowPopup/lib/openWindowPopup";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import {
|
||||
StandardTableSortHeader,
|
||||
sortStandardTableRows,
|
||||
@@ -27,7 +27,7 @@ import type {
|
||||
ExmnSectionSummaryRow,
|
||||
} from "../model/exmn-business-types";
|
||||
import type { ExmnDetailDefectType } from "../model/exmn-detail-table";
|
||||
import { EXMN_TABLE_HEADER_HEIGHT_REM } from "./ExmnStandardDataTable";
|
||||
import { EXMN_TABLE_HEADER_HEIGHT_REM } from "./exmn-standard-data-table";
|
||||
|
||||
// 상세 본문 행 높이는 유지하되 세로 이동은 CS 목록과 같이 브라우저 기본 스크롤에 맡긴다.
|
||||
const SUMMARY_GRID_ROW_HEIGHT_REM = 3.2;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { ExmnRegistrationPage } from "./ExmnRegistrationPage";
|
||||
import { ExmnRegistrationPage } from "./exmn-registration-page";
|
||||
|
||||
/** 조사현황 URL도 PPT 3·4와 동일한 사업목록·행 선택 상세 통합 화면을 사용한다. */
|
||||
export function ExmnStatusPage() {
|
||||
+130
-326
@@ -1,4 +1,18 @@
|
||||
"use client";
|
||||
import { ExmnDetailSearchPanel } from "./exmn-detail-search-panel";
|
||||
import {
|
||||
DEFAULT_SEVERITY_LABELS,
|
||||
DEFAULT_DEFECT_TYPE_LABELS,
|
||||
FIXED_COLUMNS,
|
||||
REPORT_COLUMN_LEFT,
|
||||
PIPE_COLUMN_LEFT,
|
||||
STICKY_COLUMN_COUNT,
|
||||
STICKY_DIVIDER_SHADOW,
|
||||
SEVERITY_COLUMN_WIDTH,
|
||||
formatNumber,
|
||||
formatCount,
|
||||
getFixedCellValue,
|
||||
} from "../model/exmn-detail-view";
|
||||
|
||||
import type { UIEvent } from "react";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
@@ -8,29 +22,11 @@ import {
|
||||
StandardTableSortHeader,
|
||||
type UiTableSort,
|
||||
} from "@common/business_components";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
Table,
|
||||
} from "@common/components";
|
||||
import { requestGridExcel } from "@/shared/api/grid-export";
|
||||
import { Button, Table } from "@common/components";
|
||||
import { downloadExmnDetailExcel } from "../api/exmn-detail-export";
|
||||
import { getVisibleAnomalyTotals } from "../lib/exmn-detail-totals";
|
||||
import PopupSearchPanel, {
|
||||
PopupSearchActions,
|
||||
} from "@/features/windowPopup/ui/PopupSearchPanel";
|
||||
|
||||
import {
|
||||
PPL_STATUS_LABELS,
|
||||
getExmnFacilityPage,
|
||||
getExmnPplUnitPage,
|
||||
getExmnSectionSummaries,
|
||||
} from "../api/exmn-business-api";
|
||||
import { getExmnSectionSummaries } from "../api/exmn-business-api";
|
||||
import type {
|
||||
ExmnBusiness,
|
||||
ExmnJobType,
|
||||
@@ -45,49 +41,11 @@ import {
|
||||
type ExmnPplUnitDetailRow,
|
||||
type ExmnSurveyDetailRow,
|
||||
} from "../model/exmn-detail-table";
|
||||
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
|
||||
import { useExmnCommonCodes } from "../lib/use-exmn-common-codes";
|
||||
import { useExmnDetailData } from "../lib/use-exmn-detail-data";
|
||||
|
||||
import { ExmnPplUnitDetailTable } from "./ExmnPplUnitDetailTable";
|
||||
import { ExmnSurveyStandardDataTable } from "./ExmnSurveyStandardDataTable";
|
||||
|
||||
const DEFAULT_SEVERITY_LABELS: Record<ExmnDetailSeverity, string> = {
|
||||
L: "대",
|
||||
M: "중",
|
||||
S: "소",
|
||||
};
|
||||
|
||||
/** 관로 상세보기에서 조회 결과 표를 전환하는 모드 표시 문구다. */
|
||||
const PPL_DETAIL_MODE_LABELS: Record<ExmnPplDetailMode, string> = {
|
||||
PIPE: "관로",
|
||||
UNIT: "본단위구간",
|
||||
};
|
||||
|
||||
const DEFAULT_DEFECT_TYPE_LABELS: Record<ExmnDetailDefectType, string> = {
|
||||
ALL: "전체",
|
||||
STRUCTURAL: "구조적결함",
|
||||
OPERATIONAL: "운영적결함",
|
||||
};
|
||||
|
||||
const FIXED_COLUMNS = [
|
||||
{ id: "reportNo", label: "보고서\n번호", width: 118 },
|
||||
{ id: "pipeNo", label: "관로\n번호", width: 120 },
|
||||
{ id: "upstreamManhole", label: "상류\n맨홀", width: 135 },
|
||||
{ id: "downstreamManhole", label: "하류\n맨홀", width: 135 },
|
||||
{ id: "drainageType", label: "배수\n방식", width: 82 },
|
||||
{ id: "pipeType", label: "관종", width: 76 },
|
||||
{ id: "specification", label: "규격", width: 82 },
|
||||
{ id: "extensionM", label: "연장", width: 86 },
|
||||
{ id: "drivingDistanceM", label: "주행\n거리", width: 92 },
|
||||
{ id: "structuralGrade", label: "구조적\n내부결함", width: 105 },
|
||||
{ id: "operationalGrade", label: "운영적\n내부결함", width: 105 },
|
||||
] as const;
|
||||
|
||||
const REPORT_COLUMN_LEFT = 0;
|
||||
const PIPE_COLUMN_LEFT = FIXED_COLUMNS[0].width;
|
||||
const STICKY_COLUMN_COUNT = 2;
|
||||
const STICKY_DIVIDER_SHADOW = "2px 0 0 hsl(var(--border))";
|
||||
const SEVERITY_COLUMN_WIDTH = 52;
|
||||
type ExmnDetailFixedColumnId = (typeof FIXED_COLUMNS)[number]["id"];
|
||||
import { ExmnPplUnitDetailTable } from "./exmn-ppl-unit-detail-table";
|
||||
import { ExmnSurveyStandardDataTable } from "./exmn-survey-standard-data-table";
|
||||
|
||||
interface ExmnSurveyDetailPopupPageProps {
|
||||
business: ExmnBusiness;
|
||||
@@ -99,31 +57,6 @@ interface ExmnSurveyDetailPopupPageProps {
|
||||
|
||||
type Notice = { type: "info"; text: string } | null;
|
||||
|
||||
/** 숫자를 엑셀 화면과 같은 최대 소수점 1자리 형식으로 표시한다. */
|
||||
const formatNumber = (value: number) =>
|
||||
value.toLocaleString("ko-KR", { maximumFractionDigits: 1 });
|
||||
|
||||
/** 이상항목이 없는 셀은 0 대신 엑셀형 빈 상태인 하이픈으로 표시한다. */
|
||||
const formatCount = (value: number | null | undefined) =>
|
||||
Number(value ?? 0) === 0 ? "-" : Number(value).toLocaleString("ko-KR");
|
||||
|
||||
|
||||
/** 공통 고정 열의 행 값을 화면용 문자열로 변환한다. */
|
||||
const getFixedCellValue = (
|
||||
row: ExmnSurveyDetailRow,
|
||||
columnId: ExmnDetailFixedColumnId,
|
||||
) => {
|
||||
if (columnId === "drainageType") {
|
||||
return row.drainageTypeName?.trim() || row.drainageType;
|
||||
}
|
||||
if (columnId === "pipeType") {
|
||||
return row.pipeTypeName?.trim() || row.pipeType;
|
||||
}
|
||||
const value = row[columnId];
|
||||
return typeof value === "number" ? formatNumber(value) : value;
|
||||
};
|
||||
|
||||
|
||||
/** 엑셀 `01. 덕풍`·`01. 덕풍 (2)` 구조를 관로·맨홀 공통 WindowPopup으로 표시한다. */
|
||||
export function ExmnSurveyDetailPopupPage({
|
||||
business,
|
||||
@@ -159,19 +92,9 @@ export function ExmnSurveyDetailPopupPage({
|
||||
const [sort, setSort] = useState<UiTableSort>();
|
||||
/** 다운로드 미연결 등 현재 팝업 안내 메시지를 표시한다. */
|
||||
const [notice, setNotice] = useState<Notice>(null);
|
||||
/** 실제 DB 상세조회 결과와 요청 상태다. */
|
||||
const [actualRows, setActualRows] = useState<ExmnSurveyDetailRow[]>([]);
|
||||
// 표 행은 현재 페이지만 보관하고 합계는 서버의 전체 조건 합계를 별도로 사용한다.
|
||||
const [page, setPage] = useState(1);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [serverSummary, setServerSummary] = useState<ExmnSurveyDetailRow | null>(null);
|
||||
const summaryRows = useMemo(() => serverSummary ? [serverSummary] : [], [serverSummary]);
|
||||
const [actualUnitRows, setActualUnitRows] = useState<ExmnPplUnitDetailRow[]>(
|
||||
[],
|
||||
);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isDownloading, setIsDownloading] = useState(false);
|
||||
const [loadError, setLoadError] = useState<string | null>(null);
|
||||
const severityLabels: Record<ExmnDetailSeverity, string> = {
|
||||
...DEFAULT_SEVERITY_LABELS,
|
||||
...cmsSeverityLabels,
|
||||
@@ -231,6 +154,32 @@ export function ExmnSurveyDetailPopupPage({
|
||||
),
|
||||
[defectType, definition],
|
||||
);
|
||||
const {
|
||||
actualRows,
|
||||
actualUnitRows,
|
||||
total,
|
||||
serverSummary,
|
||||
isLoading,
|
||||
loadError,
|
||||
clearRows,
|
||||
} = useExmnDetailData({
|
||||
business,
|
||||
jobType,
|
||||
selectedTrtdstId,
|
||||
appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
visibleDefectColumns,
|
||||
page,
|
||||
sort,
|
||||
isUnitMode,
|
||||
isDefectTypeView,
|
||||
searchRequestSeq,
|
||||
});
|
||||
const summaryRows = useMemo(
|
||||
() => (serverSummary ? [serverSummary] : []),
|
||||
[serverSummary],
|
||||
);
|
||||
|
||||
/** 분류별 상세에서는 선택 결함이 한 건 이상 존재하는 시설 행만 표시한다. */
|
||||
const scopedRows = useMemo(() => {
|
||||
if (defectType === "ALL") return actualRows;
|
||||
@@ -266,7 +215,15 @@ export function ExmnSurveyDetailPopupPage({
|
||||
// 현재 페이지를 다시 정렬하지 않는다. 정렬 조건을 서버에 보내 전체 결과 순서를 적용한다.
|
||||
const rows = filteredRows;
|
||||
|
||||
useEffect(() => { setPage(1); }, [selectedTrtdstId, appliedDetailNumberKeyword, defectType, detailMode, jobType]);
|
||||
useEffect(() => {
|
||||
setPage(1);
|
||||
}, [
|
||||
selectedTrtdstId,
|
||||
appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
detailMode,
|
||||
jobType,
|
||||
]);
|
||||
|
||||
/** 관로·맨홀 조사유형 또는 결함 범위가 바뀌면 이전 검색 조건과 안내를 초기화한다. */
|
||||
useEffect(() => {
|
||||
@@ -302,112 +259,8 @@ export function ExmnSurveyDetailPopupPage({
|
||||
}, [business.exmnBizId, jobType, trtdstId]);
|
||||
|
||||
/** 전체 또는 결함 분류별 모드에서 선택 처리분구의 활성 시설과 JSONB 결함 집계를 조회한다. */
|
||||
useEffect(() => {
|
||||
if (isUnitMode || !selectedTrtdstId) {
|
||||
setActualRows([]);
|
||||
setIsLoading(false);
|
||||
setLoadError(null);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
setActualRows([]);
|
||||
setIsLoading(true);
|
||||
setLoadError(null);
|
||||
void getExmnFacilityPage({
|
||||
exmnBizId: business.exmnBizId,
|
||||
jobType,
|
||||
trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
defectCodes: visibleDefectColumns.map((column) => column.code).join(","),
|
||||
page: page - 1,
|
||||
size: 10,
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
})
|
||||
.then((result) => {
|
||||
if (active) {
|
||||
setActualRows(result.content);
|
||||
setTotal(result.totalElements);
|
||||
setServerSummary(result.summary);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!active) return;
|
||||
setActualRows([]);
|
||||
setTotal(0);
|
||||
setServerSummary(null);
|
||||
setLoadError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "조사 상세 집계 조회 중 오류가 발생했습니다.",
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [
|
||||
appliedDetailNumberKeyword,
|
||||
business.exmnBizId,
|
||||
defectType,
|
||||
isUnitMode,
|
||||
jobType,
|
||||
searchRequestSeq,
|
||||
selectedTrtdstId,
|
||||
page,
|
||||
sort,
|
||||
]);
|
||||
|
||||
/** 본단위구간 모드에서 선택 처리분구의 PPL_UNIT_V1을 실제 상세행으로 조회한다. */
|
||||
useEffect(() => {
|
||||
if (!isUnitMode || isDefectTypeView || !selectedTrtdstId) {
|
||||
setActualUnitRows([]);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
setActualUnitRows([]);
|
||||
setIsLoading(true);
|
||||
setLoadError(null);
|
||||
void getExmnPplUnitPage({
|
||||
exmnBizId: business.exmnBizId,
|
||||
trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword,
|
||||
page: page - 1,
|
||||
size: 10,
|
||||
})
|
||||
.then((result) => {
|
||||
if (active) {
|
||||
setActualUnitRows(result.content);
|
||||
setTotal(result.totalElements);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!active) return;
|
||||
setActualUnitRows([]);
|
||||
setTotal(0);
|
||||
setLoadError(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "본단위구간 조회 중 오류가 발생했습니다.",
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
if (active) setIsLoading(false);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [
|
||||
appliedDetailNumberKeyword,
|
||||
business.exmnBizId,
|
||||
isDefectTypeView,
|
||||
isUnitMode,
|
||||
searchRequestSeq,
|
||||
selectedTrtdstId,
|
||||
page,
|
||||
]);
|
||||
|
||||
/** 화면 조회 버튼으로 입력 번호를 확정해 상세 조회를 다시 실행한다. */
|
||||
const handleSearch = () => {
|
||||
@@ -514,25 +367,54 @@ export function ExmnSurveyDetailPopupPage({
|
||||
// 현재 페이지의 행은 전송하지 않고 적용조건·CMS 표시명으로 서버 전체 Excel을 생성한다.
|
||||
if (isDownloading) return;
|
||||
if (total === 0) {
|
||||
setNotice({ type: "info", text: "다운로드할 조사 상세현황 데이터가 없습니다." });
|
||||
setNotice({
|
||||
type: "info",
|
||||
text: "다운로드할 조사 상세현황 데이터가 없습니다.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
setIsDownloading(true);
|
||||
setNotice({ type: "info", text: "검색조건 전체의 Excel 자료를 준비하고 있습니다." });
|
||||
setNotice({
|
||||
type: "info",
|
||||
text: "검색조건 전체의 Excel 자료를 준비하고 있습니다.",
|
||||
});
|
||||
try {
|
||||
const filePrefix = `${selectedTrtdstNm}_${definition.defectGroupTitle}조사_${isUnitMode ? "본단위등급표" : defectTypeLabel}`
|
||||
.replace(/[\\/:*?"<>|]/g, "_");
|
||||
await requestGridExcel("v1/exmnFacilities/exportJobs", {
|
||||
exmnBizId: business.exmnBizId, jobType, trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword, defectType,
|
||||
mode: isUnitMode ? "UNIT" : "PIPE",
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
defectColumns: visibleDefectColumns.map((column) => ({ code: column.code, label: column.label })),
|
||||
recordTypeLabels, pipeItemLabels: { ...PPL_STATUS_LABELS, ...pipeItemLabels }, severityLabels,
|
||||
}, `${filePrefix}.xlsx`);
|
||||
setNotice({ type: "info", text: "검색조건 전체의 Excel 파일 다운로드를 시작했습니다." });
|
||||
const filePrefix =
|
||||
`${selectedTrtdstNm}_${definition.defectGroupTitle}조사_${isUnitMode ? "본단위등급표" : defectTypeLabel}`.replace(
|
||||
/[\\/:*?"<>|]/g,
|
||||
"_",
|
||||
);
|
||||
await downloadExmnDetailExcel(
|
||||
{
|
||||
exmnBizId: business.exmnBizId,
|
||||
jobType,
|
||||
trtdstId: selectedTrtdstId,
|
||||
gisManagementNo: appliedDetailNumberKeyword,
|
||||
defectType,
|
||||
mode: isUnitMode ? "UNIT" : "PIPE",
|
||||
sort: sort ? `${sort.key},${sort.direction}` : undefined,
|
||||
defectColumns: visibleDefectColumns.map((column) => ({
|
||||
code: column.code,
|
||||
label: column.label,
|
||||
})),
|
||||
recordTypeLabels,
|
||||
pipeItemLabels,
|
||||
severityLabels,
|
||||
},
|
||||
`${filePrefix}.xlsx`,
|
||||
);
|
||||
setNotice({
|
||||
type: "info",
|
||||
text: "검색조건 전체의 Excel 파일 다운로드를 시작했습니다.",
|
||||
});
|
||||
} catch (error) {
|
||||
setNotice({ type: "info", text: error instanceof Error ? error.message : "전체 Excel 자료를 불러오지 못했습니다." });
|
||||
setNotice({
|
||||
type: "info",
|
||||
text:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "전체 Excel 자료를 불러오지 못했습니다.",
|
||||
});
|
||||
} finally {
|
||||
setIsDownloading(false);
|
||||
}
|
||||
@@ -547,10 +429,7 @@ export function ExmnSurveyDetailPopupPage({
|
||||
[fixedColumns, visibleDefectColumns.length],
|
||||
);
|
||||
/** 본단위구간 요약은 조회된 한 관로의 단위 수와 상태·결함 기록 수를 사용한다. */
|
||||
const unitSectionCount = useMemo(
|
||||
() => total,
|
||||
[total],
|
||||
);
|
||||
const unitSectionCount = useMemo(() => total, [total]);
|
||||
/** 관로 집계와 본단위구간 행을 같은 StandardDataTable 데이터 유무 계약으로 전달한다. */
|
||||
const standardTableRows: Array<ExmnSurveyDetailRow | ExmnPplUnitDetailRow> =
|
||||
isUnitMode ? unitRows : rows;
|
||||
@@ -596,110 +475,32 @@ export function ExmnSurveyDetailPopupPage({
|
||||
|
||||
<section className="flex min-w-0 flex-col gap-[1.2rem]">
|
||||
{!isDefectTypeView && (
|
||||
<PopupSearchPanel contentClassName="gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Label
|
||||
htmlFor="exmn-detail-district"
|
||||
className="mr-2 whitespace-nowrap text-label"
|
||||
>
|
||||
처리분구
|
||||
</Label>
|
||||
<Select
|
||||
value={selectedTrtdstId}
|
||||
onValueChange={(value) => {
|
||||
setSelectedTrtdstId(value);
|
||||
setActualRows([]);
|
||||
setActualUnitRows([]);
|
||||
setDetailNumberKeyword("");
|
||||
setAppliedDetailNumberKeyword("");
|
||||
setNotice(null);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger id="exmn-detail-district" className="w-[18rem]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{districtOptions.length > 0 ? (
|
||||
districtOptions.map((district) => (
|
||||
<SelectItem
|
||||
key={district.trtdstId}
|
||||
value={district.trtdstId}
|
||||
>
|
||||
{district.trtdstNm}
|
||||
</SelectItem>
|
||||
))
|
||||
) : (
|
||||
<SelectItem value={trtdstId}>{trtdstNm}</SelectItem>
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Label
|
||||
htmlFor="exmn-detail-pipe-number"
|
||||
className="mr-2 whitespace-nowrap text-label"
|
||||
>
|
||||
관로번호
|
||||
</Label>
|
||||
<Input
|
||||
id="exmn-detail-pipe-number"
|
||||
className="w-[30rem]"
|
||||
value={detailNumberKeyword}
|
||||
placeholder="관로번호 입력"
|
||||
onChange={(event) => setDetailNumberKeyword(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") handleSearch();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{jobType === "PPL" && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Label className="mr-2 whitespace-nowrap text-label">
|
||||
상세구분
|
||||
</Label>
|
||||
<div
|
||||
className="flex items-center gap-1"
|
||||
role="group"
|
||||
aria-label="관로 상세보기 모드"
|
||||
>
|
||||
{(
|
||||
Object.keys(PPL_DETAIL_MODE_LABELS) as ExmnPplDetailMode[]
|
||||
).map((mode) => (
|
||||
<Button
|
||||
key={mode}
|
||||
type="button"
|
||||
color={detailMode === mode ? "primary" : "white"}
|
||||
aria-pressed={detailMode === mode}
|
||||
onClick={() => handleDetailModeChange(mode)}
|
||||
>
|
||||
{PPL_DETAIL_MODE_LABELS[mode]}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PopupSearchActions>
|
||||
<Button type="button" color="primary" onClick={handleSearch}>
|
||||
조회
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
color="white"
|
||||
onClick={() => {
|
||||
setSelectedTrtdstId(trtdstId);
|
||||
setDetailMode("PIPE");
|
||||
setDetailNumberKeyword("");
|
||||
setAppliedDetailNumberKeyword("");
|
||||
setNotice(null);
|
||||
}}
|
||||
>
|
||||
초기화
|
||||
</Button>
|
||||
</PopupSearchActions>
|
||||
</PopupSearchPanel>
|
||||
<ExmnDetailSearchPanel
|
||||
districtOptions={districtOptions}
|
||||
selectedTrtdstId={selectedTrtdstId}
|
||||
trtdstId={trtdstId}
|
||||
trtdstNm={trtdstNm}
|
||||
detailNumberKeyword={detailNumberKeyword}
|
||||
detailMode={detailMode}
|
||||
jobType={jobType}
|
||||
onDistrictChange={(value) => {
|
||||
setSelectedTrtdstId(value);
|
||||
clearRows();
|
||||
setDetailNumberKeyword("");
|
||||
setAppliedDetailNumberKeyword("");
|
||||
setNotice(null);
|
||||
}}
|
||||
onKeywordChange={setDetailNumberKeyword}
|
||||
onModeChange={handleDetailModeChange}
|
||||
onSearch={handleSearch}
|
||||
onReset={() => {
|
||||
setSelectedTrtdstId(trtdstId);
|
||||
setDetailMode("PIPE");
|
||||
setDetailNumberKeyword("");
|
||||
setAppliedDetailNumberKeyword("");
|
||||
setNotice(null);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{loadError && (
|
||||
@@ -835,7 +636,10 @@ export function ExmnSurveyDetailPopupPage({
|
||||
}
|
||||
sortKey={column.id}
|
||||
sort={sort}
|
||||
onSortChange={(nextSort) => { setSort(nextSort); setPage(1); }}
|
||||
onSortChange={(nextSort) => {
|
||||
setSort(nextSort);
|
||||
setPage(1);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span className="whitespace-pre-line">
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* 화면명: 관로조사 결과
|
||||
* 선택 시설의 조사 결과와 상세 판정 정보를 표시한다.
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import {
|
||||
Button,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableRow,
|
||||
} from "@common/components";
|
||||
|
||||
import { getExmnPipeReportAvailability } from "@/features/exmn";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
|
||||
type ExmnSurveyResultSectionProps = {
|
||||
featureData: any;
|
||||
};
|
||||
|
||||
const readRawFeatureProperty = (featureData: any, keys: string[]) => {
|
||||
for (const key of keys) {
|
||||
const value =
|
||||
featureData?.get?.(key) ??
|
||||
featureData?.values_?.[key] ??
|
||||
featureData?.[key];
|
||||
if (value !== undefined && value !== null) return value;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const readFeatureProperty = (featureData: any, keys: string[]) =>
|
||||
String(readRawFeatureProperty(featureData, keys) ?? "").trim();
|
||||
|
||||
const readBooleanFeatureProperty = (featureData: any, keys: string[]) => {
|
||||
const value = readRawFeatureProperty(featureData, keys);
|
||||
return (
|
||||
value === true ||
|
||||
String(value ?? "")
|
||||
.trim()
|
||||
.toLowerCase() === "true"
|
||||
);
|
||||
};
|
||||
|
||||
const displayValue = (value: string) => value || "-";
|
||||
|
||||
export default function ExmnSurveyResultSection({
|
||||
featureData,
|
||||
}: ExmnSurveyResultSectionProps) {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const exmnBizId = readFeatureProperty(featureData, ["exmnBizId"]);
|
||||
const jobType = readFeatureProperty(featureData, ["jobType"]);
|
||||
const pipeNumber = readFeatureProperty(featureData, [
|
||||
"gisManagementNo",
|
||||
"fclt_mng_no",
|
||||
"fcltMngNo",
|
||||
]);
|
||||
const reportAvailable = readBooleanFeatureProperty(featureData, [
|
||||
"reportAvailable",
|
||||
]);
|
||||
const canOpenPipeReport =
|
||||
jobType === "PPL" && Boolean(exmnBizId && pipeNumber);
|
||||
|
||||
const openPipeReport = async () => {
|
||||
if (!canOpenPipeReport) return;
|
||||
if (!reportAvailable) {
|
||||
alert("등록된 관로 조사보고서가 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const availability = await getExmnPipeReportAvailability(
|
||||
exmnBizId,
|
||||
pipeNumber,
|
||||
);
|
||||
if (!availability.available) {
|
||||
alert(
|
||||
availability.message?.trim() ||
|
||||
`선택한 관로번호의 조사보고서가 등록된 PDF에 없습니다: ${pipeNumber}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const reportWindow = openWindowPopup("exmnPipeReport", {
|
||||
exmnBizId,
|
||||
pipeNumber,
|
||||
reportNo: readFeatureProperty(featureData, ["reportNo"]),
|
||||
});
|
||||
if (!reportWindow) {
|
||||
alert(
|
||||
"팝업이 차단되었습니다. 브라우저의 팝업 허용 설정을 확인해주세요.",
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
alert(
|
||||
error instanceof Error && error.message
|
||||
? error.message
|
||||
: "관로 조사보고서 열람 가능 여부를 확인하지 못했습니다.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const rows = [
|
||||
["사업명", readFeatureProperty(featureData, ["bizNm"])],
|
||||
["사업차수", readFeatureProperty(featureData, ["bizCycl"])],
|
||||
["처리분구", readFeatureProperty(featureData, ["trtdstNm"])],
|
||||
["조사유형", jobType === "MNHL" ? "맨홀조사" : "관로조사"],
|
||||
["보고서번호", readFeatureProperty(featureData, ["reportNo"])],
|
||||
["구조적결함 등급", readFeatureProperty(featureData, ["structuralGrade"])],
|
||||
["운영적결함 등급", readFeatureProperty(featureData, ["operationalGrade"])],
|
||||
];
|
||||
|
||||
return (
|
||||
<section className="border-b border-border bg-background">
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="mx-3 text-2xl font-medium text-label">조사 결과</h3>
|
||||
{jobType === "PPL" && (
|
||||
<Button
|
||||
onClick={openPipeReport}
|
||||
disabled={!canOpenPipeReport}
|
||||
className="hover:bg-primary/90 mr-3 rounded-sm bg-primary px-4 py-2 text-sm font-medium text-primary-foreground disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
조사보고서 보기
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card !m-[1.2rem] !p-0">
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{rows.map(([label, value]) => (
|
||||
<TableRow key={label}>
|
||||
<TableCell className="w-[120px] whitespace-nowrap bg-secondary text-xs font-bold text-label">
|
||||
{label}
|
||||
</TableCell>
|
||||
<TableCell className="break-all text-left text-xs">
|
||||
{displayValue(value ?? "")}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { getSnRowNumber } from "@/shared/lib/row-number";
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import useStore from "@/store/useStore";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import {
|
||||
STANDARD_ROW_NUMBER_HEADER,
|
||||
StandardDataTable,
|
||||
@@ -0,0 +1,52 @@
|
||||
import { getData, postData } from "@/shared/api/sewerage-api";
|
||||
|
||||
const INPUT_RESOURCES = new Map<string, string>([
|
||||
["하수관로", "v1/fcltPpl"],
|
||||
["우수토실", "v1/fcltStofcbr"],
|
||||
["하수펌프장", "v1/fcltPump"],
|
||||
["하수맨홀", "v1/fcltMhl"],
|
||||
]);
|
||||
|
||||
/** 시설 종류와 자체입력 API의 기존 매핑. 미지원 종류의 조회는 수행하지 않는다. */
|
||||
export const supportsFacilityInput = (layerName: string) =>
|
||||
INPUT_RESOURCES.has(layerName);
|
||||
/** 미지원 시설을 잘못된 URL로 전송하지 않도록 API 경계에서 차단한다. */
|
||||
function requireInputResource(layerName: string): string {
|
||||
const resource = INPUT_RESOURCES.get(layerName);
|
||||
if (!resource)
|
||||
throw new Error(`자체입력을 지원하지 않는 시설입니다: ${layerName}`);
|
||||
return resource;
|
||||
}
|
||||
/** 자체입력에 사용하는 관리기관 목록을 조회한다. */
|
||||
export const fetchManagingInstitutions = () => getData("v1/fcltPpl/mngInsts");
|
||||
/** 선택 시설의 자체입력 정보만 조회한다. */
|
||||
export const fetchFacilityInput = (
|
||||
layerName: string,
|
||||
facilityNo: string,
|
||||
institutionCode: string,
|
||||
) =>
|
||||
getData(
|
||||
`${requireInputResource(layerName)}/${facilityNo}/${institutionCode}`,
|
||||
);
|
||||
/** 기존 시설별 등록 API와 요청 본문을 유지한다. */
|
||||
export const saveFacilityInput = (
|
||||
layerName: string,
|
||||
body: Record<string, unknown>,
|
||||
) => postData(requireInputResource(layerName), body);
|
||||
|
||||
/** 단건 관로의 기존 유하방향 보정 근거 조회 계약. cqlFiter는 기존 서버 파라미터명이다. */
|
||||
export async function fetchPipeFlowBasis(
|
||||
facilityNo: string,
|
||||
institutionCode: string,
|
||||
) {
|
||||
const escapeCqlLiteral = (value: string) => value.replace(/'/g, "''");
|
||||
const params = new URLSearchParams({
|
||||
lyrTypeNm: "tb_ms_swage_ppl",
|
||||
includeFlowDirectionBasis: "true",
|
||||
cqlFiter: `fclt_mng_no='${escapeCqlLiteral(facilityNo)}' and mng_inst_cd='${escapeCqlLiteral(institutionCode)}'`,
|
||||
page: "0",
|
||||
size: "1",
|
||||
});
|
||||
const response = await getData(`v1/fclts?${params.toString()}`);
|
||||
return Array.isArray(response?.data) ? response.data[0] : null;
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
/** 처리구역 관로분석정보와 보수이력을 조회·다운로드하는 API를 제공한다. */
|
||||
import { getBlobDataWithHeaders } from "@/shared/api/file-api";
|
||||
import { getData } from "@/shared/api/sewerage-api";
|
||||
|
||||
export type SwtrmtPrcsZoneAnalysisMetric = {
|
||||
avgInstlYear?: number | string | null;
|
||||
oldestInstlYear?: number | string | null;
|
||||
latestInstlYear?: number | string | null;
|
||||
pipeCount?: number | string | null;
|
||||
pipeLength?: number | string | null;
|
||||
};
|
||||
|
||||
export type SwtrmtPrcsZoneAnalysisResponse = {
|
||||
zone?: {
|
||||
zoneId?: string | number | null;
|
||||
swtrmtZoneNm?: string | null;
|
||||
ctpvCd?: string | null;
|
||||
ctpvNm?: string | null;
|
||||
sggCd?: string | null;
|
||||
sggNm?: string | null;
|
||||
swtrmtFcltCd?: string | null;
|
||||
swtrmtFcltNm?: string | null;
|
||||
};
|
||||
analysis?: {
|
||||
total?: SwtrmtPrcsZoneAnalysisMetric | null;
|
||||
combined?: SwtrmtPrcsZoneAnalysisMetric | null;
|
||||
rain?: SwtrmtPrcsZoneAnalysisMetric | null;
|
||||
sewage?: SwtrmtPrcsZoneAnalysisMetric | null;
|
||||
};
|
||||
excluded?: {
|
||||
missingInstlYearCount?: number | string | null;
|
||||
};
|
||||
};
|
||||
|
||||
type ZoneAnalysisSource = Record<string, any> | null | undefined;
|
||||
|
||||
export type RepairHistoryFilters = {
|
||||
useCd?: string;
|
||||
materialCode?: string;
|
||||
diameterFrom?: string;
|
||||
diameterTo?: string;
|
||||
};
|
||||
|
||||
export type RepairHistoryRow = {
|
||||
rowNo: number;
|
||||
fid: string;
|
||||
lyrTypeNm?: string | null;
|
||||
fcltMngNo?: string | null;
|
||||
repairCount: number;
|
||||
latestRepairYmd?: string | null;
|
||||
latestRepairYear?: number | null;
|
||||
elapsedYearsSinceRepair?: number | null;
|
||||
useCd?: string | null;
|
||||
useNm?: string | null;
|
||||
installationYear?: number | null;
|
||||
burialDepth?: number | null;
|
||||
materialCode?: string | null;
|
||||
materialName?: string | null;
|
||||
pdmtVl?: number | null;
|
||||
prlgVl?: number | null;
|
||||
geometryJson?: string | null;
|
||||
};
|
||||
|
||||
export type RepairHistoryResponse = {
|
||||
totalElements: number;
|
||||
totalPages: number;
|
||||
page: number;
|
||||
size: number;
|
||||
data: RepairHistoryRow[];
|
||||
};
|
||||
|
||||
const ANALYSIS_ENDPOINT_PREFIX = "v1/swagePrcsZones";
|
||||
/** 지도 전체 강조에 필요한 필드만 제공하며 표의 행 수와 독립적이다. */
|
||||
export type RepairHistoryMapFeature = Pick<
|
||||
RepairHistoryRow,
|
||||
"fid" | "geometryJson"
|
||||
>;
|
||||
|
||||
const firstValue = (...values: unknown[]) => {
|
||||
const value = values.find((item) => {
|
||||
if (item === null || item === undefined) return false;
|
||||
const text = String(item).trim();
|
||||
return text !== "" && text !== "-";
|
||||
});
|
||||
|
||||
return value === undefined ? "" : String(value).trim();
|
||||
};
|
||||
|
||||
export const getSwtrmtPrcsZoneId = (
|
||||
rawFeatureData: any,
|
||||
featureData: ZoneAnalysisSource,
|
||||
) => {
|
||||
const rawValues = rawFeatureData?.values_ ?? rawFeatureData ?? {};
|
||||
|
||||
return firstValue(
|
||||
rawFeatureData?.getId?.(),
|
||||
rawFeatureData?.id_,
|
||||
rawFeatureData?.fid,
|
||||
rawValues?.fid,
|
||||
featureData?.fid,
|
||||
rawValues?.swtrmt_zone_sn,
|
||||
rawValues?.swtrmtZoneSn,
|
||||
featureData?.swtrmt_zone_sn,
|
||||
featureData?.swtrmtZoneSn,
|
||||
rawValues?.zoneId,
|
||||
featureData?.zoneId,
|
||||
rawValues?.swtrmt_fclt_cd,
|
||||
rawValues?.swtrmtFcltCd,
|
||||
featureData?.swtrmt_fclt_cd,
|
||||
featureData?.swtrmtFcltCd,
|
||||
);
|
||||
};
|
||||
|
||||
export const getSwtrmtPrcsZoneAnalysisParams = (
|
||||
rawFeatureData: any,
|
||||
featureData: ZoneAnalysisSource,
|
||||
) => {
|
||||
const rawValues = rawFeatureData?.values_ ?? rawFeatureData ?? {};
|
||||
const params = new URLSearchParams();
|
||||
|
||||
const entries = {
|
||||
ctpvCd: firstValue(
|
||||
rawValues?.ctpv_cd,
|
||||
rawValues?.ctpvCd,
|
||||
featureData?.ctpv_cd,
|
||||
featureData?.ctpvCd,
|
||||
),
|
||||
sggCd: firstValue(
|
||||
rawValues?.sgg_cd,
|
||||
rawValues?.sggCd,
|
||||
featureData?.sgg_cd,
|
||||
featureData?.sggCd,
|
||||
),
|
||||
swtrmtFcltCd: firstValue(
|
||||
rawValues?.swtrmt_fclt_cd,
|
||||
rawValues?.swtrmtFcltCd,
|
||||
featureData?.swtrmt_fclt_cd,
|
||||
featureData?.swtrmtFcltCd,
|
||||
),
|
||||
swtrmtZoneNm: firstValue(
|
||||
rawValues?.swtrmt_zone_nm,
|
||||
rawValues?.swtrmtZoneNm,
|
||||
featureData?.swtrmt_zone_nm,
|
||||
featureData?.swtrmtZoneNm,
|
||||
),
|
||||
};
|
||||
|
||||
Object.entries(entries).forEach(([key, value]) => {
|
||||
if (value) params.append(key, value);
|
||||
});
|
||||
|
||||
return params;
|
||||
};
|
||||
|
||||
export const fetchSwtrmtPrcsZoneAnalysis = async (
|
||||
rawFeatureData: any,
|
||||
featureData: ZoneAnalysisSource,
|
||||
): Promise<SwtrmtPrcsZoneAnalysisResponse | null> => {
|
||||
const zoneId = getSwtrmtPrcsZoneId(rawFeatureData, featureData);
|
||||
if (!zoneId) return null;
|
||||
|
||||
const params = getSwtrmtPrcsZoneAnalysisParams(rawFeatureData, featureData);
|
||||
const query = params.toString();
|
||||
const path = `${ANALYSIS_ENDPOINT_PREFIX}/${encodeURIComponent(zoneId)}/pplAnalysis${query ? `?${query}` : ""}`;
|
||||
|
||||
return (await getData(path)) ?? {};
|
||||
};
|
||||
|
||||
const appendRepairHistoryFilters = (
|
||||
params: URLSearchParams,
|
||||
filters: RepairHistoryFilters,
|
||||
) => {
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
const normalized = String(value ?? "").trim();
|
||||
if (normalized) params.append(key, normalized);
|
||||
});
|
||||
};
|
||||
|
||||
const getRepairHistoryPath = (
|
||||
zoneId: string,
|
||||
filters: RepairHistoryFilters,
|
||||
suffix = "",
|
||||
extraParams: Record<string, string> = {},
|
||||
) => {
|
||||
const params = new URLSearchParams();
|
||||
appendRepairHistoryFilters(params, filters);
|
||||
Object.entries(extraParams).forEach(([key, value]) => {
|
||||
const normalized = value.trim();
|
||||
if (normalized) params.append(key, normalized);
|
||||
});
|
||||
const query = params.toString();
|
||||
return `${ANALYSIS_ENDPOINT_PREFIX}/${encodeURIComponent(zoneId)}/repairHistories${suffix}${query ? `?${query}` : ""}`;
|
||||
};
|
||||
|
||||
/** 목록은 현재 페이지 하나만 조회한다. 전체 지도/Excel과 호출 계약을 분리한다. */
|
||||
export const fetchRepairHistoryPage = async (
|
||||
zoneId: string,
|
||||
filters: RepairHistoryFilters,
|
||||
page: number,
|
||||
size: number,
|
||||
): Promise<RepairHistoryResponse> => {
|
||||
if (!zoneId.trim()) throw new Error("처리구역 식별값이 없습니다.");
|
||||
return getData(
|
||||
getRepairHistoryPath(zoneId, filters, "", {
|
||||
page: String(page),
|
||||
size: String(size),
|
||||
}),
|
||||
) as Promise<RepairHistoryResponse>;
|
||||
};
|
||||
|
||||
/** 검색조건에 맞는 전체 도형을 한 번 조회하며 목록 페이지 이동 시에는 호출하지 않는다. */
|
||||
export const fetchRepairHistoryMapFeatures = (
|
||||
zoneId: string,
|
||||
filters: RepairHistoryFilters,
|
||||
): Promise<RepairHistoryMapFeature[]> =>
|
||||
getData(getRepairHistoryPath(zoneId, filters, "/mapFeatures"));
|
||||
|
||||
/** 현재 조회 조건의 화면 목록 항목 파일을 내려받는다. */
|
||||
export const downloadRepairHistoriesByZoneId = async (
|
||||
zoneId: string,
|
||||
filters: RepairHistoryFilters,
|
||||
zoneName: string,
|
||||
) => {
|
||||
if (!zoneId.trim()) throw new Error("처리구역 식별값이 없습니다.");
|
||||
return getBlobDataWithHeaders(
|
||||
getRepairHistoryPath(zoneId, filters, "/download", { zoneName }),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,84 @@
|
||||
/** 선택한 지도 레이어 종류에 맞는 시설 상세 컴포넌트를 반환한다. */
|
||||
import MsSwagePpl from "@/features/facility-detail/ui/ms-swage-ppl"; // 하수관로
|
||||
import sewagePump from "@/features/facility-detail/ui/sewage-pump"; // 하수펌프
|
||||
import smh from "@/features/facility-detail/ui/smh";
|
||||
import Ssc from "@/features/facility-detail/ui/ssc";
|
||||
import StormWaterPump from "@/features/facility-detail/ui/storm-water-pump";
|
||||
import SwtrmtFclt from "@/features/facility-detail/ui/swtrmt-fclt";
|
||||
import SwtrmtPrcsZoneAnalysis from "@/features/facility-detail/ui/swtrmt-prcs-zone-analysis";
|
||||
|
||||
type LayerComponentProps = {
|
||||
featureData: any;
|
||||
isMainSsc?: boolean;
|
||||
isDrtwSewagePump?: boolean;
|
||||
rainMeasureData?: any;
|
||||
onSaveClick?: () => void;
|
||||
onFormDataChange?: (data: any) => void; // 추가
|
||||
chmbrXcnts: string;
|
||||
chmbrYdnts: string;
|
||||
gisObject?: Record<string, any>; // GIS 객체 추가
|
||||
rawFeatureData?: any;
|
||||
surveyResultContent?: React.ReactNode;
|
||||
};
|
||||
type LayerContentMap = {
|
||||
[key: string]: {
|
||||
component?: React.ComponentType<any>;
|
||||
props?: any;
|
||||
};
|
||||
};
|
||||
// 레이어 이름과 컴포넌트를 매핑
|
||||
// 레이어 선택시 변경되는 팝업 컨텐츠 동적으로 변경하도록 작업
|
||||
const layerContentMap: LayerContentMap = {
|
||||
하수처리시설: { component: SwtrmtFclt }, // 디지털 자료관 연계정보가 없으니 일단 주석 처리
|
||||
하수처리구역: { component: SwtrmtPrcsZoneAnalysis },
|
||||
우수토실: { component: Ssc },
|
||||
중점우수토실: { component: Ssc }, // 중점우수토실 여부 설정
|
||||
하수관로: { component: MsSwagePpl },
|
||||
하수맨홀: { component: smh },
|
||||
하수펌프장: { component: sewagePump },
|
||||
// "빗물펌프": { component: StormWaterPump },
|
||||
// "오수펌프": { component: sewagePump },
|
||||
};
|
||||
|
||||
// 동적 컴포넌트 반환 함수
|
||||
export const getLayerContentComponent = (
|
||||
layerNm: string,
|
||||
): React.FC<LayerComponentProps> | null => {
|
||||
const component = layerContentMap[layerNm];
|
||||
if (!component || !component.component) {
|
||||
// component가 없으면 null 반환
|
||||
return () => null;
|
||||
}
|
||||
return component.component as React.FC<LayerComponentProps>;
|
||||
};
|
||||
// 사용자 입력 필드 (보수 및 갱신, 청소 및 준설, 점검 및 진단)
|
||||
export const handleInputChange = (
|
||||
section: string,
|
||||
index: number,
|
||||
field: string,
|
||||
value: string,
|
||||
dataMap: {
|
||||
[key: string]: {
|
||||
data: {
|
||||
year: string;
|
||||
type: string;
|
||||
bizInfoNm: string;
|
||||
bizType: string;
|
||||
}[];
|
||||
setData: React.Dispatch<
|
||||
React.SetStateAction<
|
||||
{ year: string; type: string; bizInfoNm: string; bizType: string }[]
|
||||
>
|
||||
>;
|
||||
};
|
||||
},
|
||||
) => {
|
||||
const target = dataMap[section];
|
||||
if (!target) return;
|
||||
|
||||
const updated = [...target.data];
|
||||
if (updated[index]) {
|
||||
updated[index][field as keyof (typeof updated)[number]] = value;
|
||||
}
|
||||
target.setData(updated);
|
||||
};
|
||||
@@ -0,0 +1,248 @@
|
||||
import {
|
||||
FldngWtlvMapCol,
|
||||
FldngWtlvMapCol2,
|
||||
FldngDpthMapCol,
|
||||
} from "@/entities/facility/model/flood-columns";
|
||||
import {
|
||||
SwtrmtFcltCol,
|
||||
SwtrmtFcltCol2,
|
||||
} from "@/entities/facility/model/treatment-facility-columns";
|
||||
import {
|
||||
SwtrmtPrcsZoneCol,
|
||||
SwtrmtPrcsZoneCol2,
|
||||
} from "@/entities/facility/model/treatment-zone-columns";
|
||||
import {
|
||||
untrtSwgRainCol1,
|
||||
untrtSwgRainCol2,
|
||||
stofcbrCol,
|
||||
stofcbrCol2,
|
||||
} from "@/entities/facility/model/overflow-columns";
|
||||
import {
|
||||
MsSwagePplCol,
|
||||
MsSwagePplCol2,
|
||||
} from "@/entities/facility/model/pipe-columns";
|
||||
import {
|
||||
ExclnSewagePumpCol,
|
||||
ExclnSewagePumpCol2,
|
||||
DrtwSewagePumpCol,
|
||||
DrtwSewagePumpCol2,
|
||||
} from "@/entities/facility/model/pump-columns";
|
||||
import {
|
||||
MsSwageMhlCol,
|
||||
MsSwageMhlCol2,
|
||||
} from "@/entities/facility/model/manhole-columns";
|
||||
import { DRTW_SEWAGE_PUMP_USE_CODES } from "@/entities/facility/model/facility-code-fallbacks";
|
||||
import { normalizeFldngHstryWtlvDisplayId } from "@/entities/flood-history/lib/flood-history-utils";
|
||||
|
||||
type Column = { id: string; title: string };
|
||||
export type FacilitySelectionPatch = {
|
||||
isClicked?: boolean;
|
||||
headlist?: Column[];
|
||||
headlist2?: Column[];
|
||||
layerSpecificNm?: string;
|
||||
isDrtwSewagePump?: boolean;
|
||||
};
|
||||
|
||||
/** 시설 유형별 열/제목/표시 모드를 계산한다. React setter 없이 변경할 필드만 반환한다.
|
||||
* 지도 객체 선택과 목록 선택의 기존 분기(펌프 구분 포함)는 그대로 유지한다.
|
||||
*/
|
||||
export function resolveFacilitySelection(
|
||||
featureData: any,
|
||||
gisMap: any,
|
||||
featureId: any,
|
||||
) {
|
||||
const patch: FacilitySelectionPatch = {};
|
||||
const setIsClicked = (value: boolean) => {
|
||||
patch.isClicked = value;
|
||||
};
|
||||
const setHeadlist = (value: Column[]) => {
|
||||
patch.headlist = value;
|
||||
};
|
||||
const setHeadlist2 = (value: Column[]) => {
|
||||
patch.headlist2 = value;
|
||||
};
|
||||
const setLayerSpecificNm = (value: string) => {
|
||||
patch.layerSpecificNm = value;
|
||||
};
|
||||
const setIsDrtwSewagePump = (value: boolean) => {
|
||||
patch.isDrtwSewagePump = value;
|
||||
};
|
||||
|
||||
let result = null;
|
||||
const layers = gisMap.getLayers().getArray(); // gisMap에서 모든 레이어 가져오기
|
||||
let featureLayer: any = null; // 피처가 속한 레이어를 찾기 위한 변수
|
||||
layers.some((layer: any) => {
|
||||
const source = layer.getSource();
|
||||
// if (source && featureData && featureData.fid) {
|
||||
// featureLayer = layer; // 피처가 속한 레이어 찾기
|
||||
// }
|
||||
if (
|
||||
source &&
|
||||
source.hasFeature &&
|
||||
featureData &&
|
||||
typeof featureData.getId === "function" &&
|
||||
source.hasFeature(featureData)
|
||||
) {
|
||||
featureLayer = layer; // 피처가 속한 레이어 찾기
|
||||
return true; // 반복 종료
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
if (featureData["ol_uid"]) {
|
||||
// Gis 레이어 클릭 이벤트
|
||||
setIsClicked(true);
|
||||
const lyrTyNm = featureData.id_.split(".")[0];
|
||||
|
||||
switch (lyrTyNm) {
|
||||
case "tb_ms_swage_ppl": {
|
||||
result = "하수관로";
|
||||
setHeadlist(MsSwagePplCol);
|
||||
setLayerSpecificNm(featureData.values_.fclt_mng_no);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_mhl": {
|
||||
result = "하수맨홀";
|
||||
setHeadlist(MsSwageMhlCol);
|
||||
setLayerSpecificNm(featureData.values_.fclt_mng_no);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_pmstn": {
|
||||
const drtwPumpCode = DRTW_SEWAGE_PUMP_USE_CODES.find(
|
||||
(code) => code.text === "오수펌프장",
|
||||
);
|
||||
if (
|
||||
drtwPumpCode &&
|
||||
featureData.values_.usg_cd.trim() === drtwPumpCode.val
|
||||
) {
|
||||
setIsDrtwSewagePump(true);
|
||||
setHeadlist(DrtwSewagePumpCol);
|
||||
} else {
|
||||
setIsDrtwSewagePump(false);
|
||||
setHeadlist(ExclnSewagePumpCol);
|
||||
}
|
||||
setLayerSpecificNm(featureData.values_.fclt_mng_no);
|
||||
result = "하수펌프장";
|
||||
break;
|
||||
}
|
||||
case "tb_il_swage_prcs_fclt": {
|
||||
result = "하수처리시설";
|
||||
setHeadlist(SwtrmtFcltCol);
|
||||
setLayerSpecificNm(featureData.values_.swtrmt_fclt_cd);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_prcs_zone": {
|
||||
result = "하수처리구역";
|
||||
setHeadlist(SwtrmtPrcsZoneCol);
|
||||
setLayerSpecificNm(featureData.values_.swtrmt_fclt_cd);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_fldng_wtlv_map": {
|
||||
result = "침수흔적위선";
|
||||
setHeadlist(FldngWtlvMapCol);
|
||||
setLayerSpecificNm(
|
||||
normalizeFldngHstryWtlvDisplayId(
|
||||
featureData.values_.fid ?? featureId,
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_fldng_dpth_map": {
|
||||
result = "침수흔적심선";
|
||||
setHeadlist(FldngDpthMapCol);
|
||||
setLayerSpecificNm(
|
||||
String(featureId ?? "").replace(/^tb_ms_fldng_dpth_map\./, ""),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_stofcbr": {
|
||||
result = "우수토실";
|
||||
setHeadlist(stofcbrCol);
|
||||
setLayerSpecificNm(featureData.values_.fclt_mng_no);
|
||||
break;
|
||||
}
|
||||
case "om_dt_untrt_swg_rain": {
|
||||
result = "중점우수토실";
|
||||
setHeadlist(untrtSwgRainCol1);
|
||||
setHeadlist2(untrtSwgRainCol2);
|
||||
setLayerSpecificNm(featureData.values_.manage_no);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
result = featureLayer ? featureLayer.get("lyrNm") : null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// SearchModal 클릭 이벤트
|
||||
setIsClicked(false);
|
||||
const lyrTyNm = featureData.lyrTypeNm;
|
||||
|
||||
switch (lyrTyNm) {
|
||||
case "tb_ms_swage_ppl": {
|
||||
result = "하수관로";
|
||||
setHeadlist(MsSwagePplCol2);
|
||||
setLayerSpecificNm(featureData.fcltMngNo ?? featureData.swtrmtFcltCd);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_mhl": {
|
||||
result = "하수맨홀";
|
||||
setHeadlist(MsSwageMhlCol2);
|
||||
setLayerSpecificNm(featureData.fcltMngNo);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_pmstn": {
|
||||
const drtwPumpCode = DRTW_SEWAGE_PUMP_USE_CODES.find(
|
||||
(code) => code.text === "오수펌프장",
|
||||
);
|
||||
if (drtwPumpCode && featureData.usgCd.trim() === drtwPumpCode.val) {
|
||||
setIsDrtwSewagePump(false);
|
||||
setHeadlist(ExclnSewagePumpCol2);
|
||||
} else {
|
||||
setIsDrtwSewagePump(true);
|
||||
setHeadlist(DrtwSewagePumpCol2);
|
||||
}
|
||||
setLayerSpecificNm(featureData.fcltMngNo);
|
||||
result = "하수펌프장";
|
||||
break;
|
||||
}
|
||||
case "tb_il_swage_prcs_fclt": {
|
||||
result = "하수처리시설";
|
||||
setHeadlist(SwtrmtFcltCol2);
|
||||
setLayerSpecificNm(featureData.swtrmtFcltCd);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_swage_prcs_zone": {
|
||||
result = "하수처리구역";
|
||||
setHeadlist(SwtrmtPrcsZoneCol2);
|
||||
setLayerSpecificNm(featureData.swtrmtFcltCd);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_fldng_wtlv_map": {
|
||||
result = "침수흔적위선";
|
||||
setHeadlist(FldngWtlvMapCol2);
|
||||
setLayerSpecificNm(normalizeFldngHstryWtlvDisplayId(featureData.fid));
|
||||
break;
|
||||
}
|
||||
case "tb_ms_fldng_dpth_map": {
|
||||
result = "침수흔적심선";
|
||||
setHeadlist(FldngDpthMapCol);
|
||||
setLayerSpecificNm(
|
||||
String(featureData.fid ?? featureId ?? "").replace(
|
||||
/^tb_ms_fldng_dpth_map\./,
|
||||
"",
|
||||
),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "tb_ms_stofcbr": {
|
||||
result = "우수토실";
|
||||
setHeadlist(stofcbrCol2);
|
||||
setLayerSpecificNm(featureData.fcltMngNo);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { layerName: result, patch };
|
||||
}
|
||||
@@ -0,0 +1,910 @@
|
||||
/**
|
||||
* 화면명: 시설 상세정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창
|
||||
*
|
||||
* 📄 FeatureClickEventPopup
|
||||
* 시설물(피처) 클릭시 오른쪽 팝업창 컴포넌트
|
||||
*
|
||||
* - 지도 시설물(피처) 클릭 시 팝업 표시 및 데이터 로딩
|
||||
* - 레이어 유형에 따른 동적 테이블 및 헤드리스트 설정
|
||||
* - 자체입력정보 조회 및 저장 기능 (하수관로, 우수토실, 하수펌프장, 하수맨홀)
|
||||
* - 코드 매핑 및 데이터 포맷팅 처리
|
||||
* - 상류관로 검색, 침입수/RDII 분석 차트 표시
|
||||
* - 모달을 통한 저장 확인 및 API 연동
|
||||
*
|
||||
* 🔗 사용 API
|
||||
* - 하수관로 자체입력정보 조회: GET /api/v1/fcltPpl/{fcltMngNo}/{mngInstCd} (sewerage-service)
|
||||
* - 우수토실 자체입력정보 조회: GET /api/v1/fcltStofcbr/{fcltMngNo}/{mngInstCd} (sewerage-service)
|
||||
* - 하수펌프장 자체입력정보 조회: GET /api/v1/fcltPump/{fcltMngNo}/{mngInstCd} (sewerage-service)
|
||||
* - 하수맨홀 자체입력정보 조회: GET /api/v1/fcltMhl/{fcltMngNo}/{mngInstCd} (sewerage-service)
|
||||
* - 하수관로 자체입력정보 저장: POST /api/v1/fcltPpl (sewerage-service)
|
||||
* - 우수토실 자체입력정보 저장: POST /api/v1/fcltStofcbr (sewerage-service)
|
||||
* - 하수펌프장 자체입력정보 저장: POST /api/v1/fcltPump (sewerage-service)
|
||||
* - 하수맨홀 자체입력정보 저장: POST /api/v1/fcltMhl (sewerage-service)
|
||||
*/
|
||||
"use client";
|
||||
import { resolveFacilitySelection } from "../model/resolve-facility-selection";
|
||||
import {
|
||||
supportsFacilityInput,
|
||||
fetchManagingInstitutions,
|
||||
fetchFacilityInput,
|
||||
saveFacilityInput,
|
||||
fetchPipeFlowBasis,
|
||||
} from "../api/facility-input-api";
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import { useGisContext } from "@common/business_components/ui/map/Gis";
|
||||
import { Button } from "@common/components/ui";
|
||||
import { useEffect, useRef, useState, useMemo, useCallback } from "react";
|
||||
import Style from "ol/style/Style.js";
|
||||
import Fill from "ol/style/Fill.js";
|
||||
import Stroke from "ol/style/Stroke.js";
|
||||
import CircleStyle from "ol/style/Circle.js";
|
||||
import { getLayerContentComponent } from "@/features/facility-detail/lib/facility-panel-registry";
|
||||
import { useFacilityCodeCatalog } from "@/entities/facility/lib/use-facility-code-catalog";
|
||||
import { formatDisplayData } from "@/components/lib/utils/format-display-value";
|
||||
import { codeMapper as mapFacilityCodes } from "@/entities/facility/lib/code-mapper";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { searchUpperPpls } from "@/features/facility-detail/ui/smh";
|
||||
import {
|
||||
getElapsedYearsDisplayText,
|
||||
isInvalidInstallYmd,
|
||||
} from "@/entities/facility/lib/aged-pipe-utils";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import ExmnSurveyResultSection from "@/features/exmn/ui/exmn-survey-result-section";
|
||||
import {
|
||||
formatFldngHstryDateTime,
|
||||
normalizeFldngHstryWtlvApiFid,
|
||||
} from "@/entities/flood-history/lib/flood-history-utils";
|
||||
import { useFldngHstryFeatureClick } from "@/app/(map-layout)/map/components/fldng-hstry/fldng-hstry-feature-click";
|
||||
|
||||
const linkedFacilityHighlightStyle = new Style({
|
||||
image: new CircleStyle({
|
||||
radius: 18,
|
||||
fill: new Fill({
|
||||
color: "rgba(255, 235, 59, 0.35)",
|
||||
}),
|
||||
stroke: new Stroke({
|
||||
color: "rgba(255, 193, 7, 0.45)",
|
||||
width: 2,
|
||||
}),
|
||||
}),
|
||||
fill: new Fill({
|
||||
color: "rgba(255, 235, 59, 0.2)",
|
||||
}),
|
||||
stroke: new Stroke({
|
||||
color: "rgba(255, 193, 7, 0.35)",
|
||||
width: 2.5,
|
||||
}),
|
||||
zIndex: 9999,
|
||||
});
|
||||
|
||||
type MngInstOption = {
|
||||
mngInstCd: string;
|
||||
lwrInstNm: string;
|
||||
};
|
||||
|
||||
const FeatureClickEventPopup = ({
|
||||
onClose,
|
||||
featureData,
|
||||
surveyMode = false,
|
||||
}: {
|
||||
onClose: () => void;
|
||||
featureData: any;
|
||||
surveyMode?: boolean;
|
||||
}) => {
|
||||
const catalog = useFacilityCodeCatalog();
|
||||
const { MS_SWAGE_MHL_CODES } = catalog;
|
||||
const codeMapper = useCallback(
|
||||
(input: Parameters<typeof mapFacilityCodes>[0]) =>
|
||||
mapFacilityCodes({ ...input, catalog }),
|
||||
[catalog],
|
||||
);
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { confirm } = useConfirm();
|
||||
const { gisMap } = useGisContext() as unknown as {
|
||||
checkedLayerIds: React.MutableRefObject<number[]>;
|
||||
treeData: { lyrSn: number }[] | null;
|
||||
gisCore: any;
|
||||
gisMap: any;
|
||||
};
|
||||
const [layerNm, setLayerNm] = useState<string>(""); // 레이어 이름 상태
|
||||
const [layerSpecificNm, setLayerSpecificNm] = useState<string>(""); // 레이어 이름 상태
|
||||
const [tableData, setTableData] = useState<any>(null); // 피처 데이터
|
||||
const [headlist, setHeadlist] = useState<{ id: string; title: string }[]>([]); // 컬럼리스트 변경상태
|
||||
const [headlist2, setHeadlist2] = useState<{ id: string; title: string }[]>(
|
||||
[],
|
||||
); // 컬럼리스트 변경상태
|
||||
const [buttonChk, setButtonChk] = useState(true);
|
||||
const [fetchData, setFetchData] = useState<any>(); // api 호출여부
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const [isMainSsc, setIsMainSsc] = useState(false); // 중점우수토실 여부
|
||||
const [isDrtwSewagePump, setIsDrtwSewagePump] = useState(false); // 오수펌프장 여부
|
||||
// 🎯 InfilChart 및 RdiiChart 관련 상태 추가
|
||||
const [isClicked, setIsClicked] = useState(true); // 클릭 여부 상태
|
||||
const [isLoading, setIsLoading] = useState(false); // 로딩 상태
|
||||
const [chmbrXcnts, setChmbrXcnts] = useState<string>(""); // 로딩 상태
|
||||
const [chmbrYdnts, setChmbrYdnts] = useState<string>(""); // 로딩 상태
|
||||
const linkedFacilityFeatureRef = useRef<any>(null);
|
||||
const linkedFacilityOriginalStyleRef = useRef<any>(null);
|
||||
const flowDirectionBasisRequestCacheRef = useRef(
|
||||
new Map<string, Promise<any | null>>(),
|
||||
);
|
||||
const [mngInstOptions, setMngInstOptions] = useState<MngInstOption[]>([]);
|
||||
const {
|
||||
hasFldngHstryLinkedFeatures,
|
||||
fldngHstryFeatureClickHeadName,
|
||||
loadFldngHstryFeatureClickDetail,
|
||||
resetFldngHstryFeatureClick,
|
||||
} = useFldngHstryFeatureClick();
|
||||
const { ctpv, sgg, fetchCtpv, fetchSgg } = useStore();
|
||||
|
||||
// 🎯 관로관리번호 추출
|
||||
const pplMngNo =
|
||||
featureData?.values_?.fclt_mng_no || featureData?.fcltMngNo || "";
|
||||
|
||||
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(() => {
|
||||
if (!featureData?.values_) return null;
|
||||
|
||||
return {
|
||||
...featureData.values_,
|
||||
discharge_pipe_spec: `직경: ${featureData.values_.pipe_diameter || "-"} / 높이: ${featureData.values_.pipe_hg || "-"} / 길이: ${featureData.values_.pipe_lt || "-"}`,
|
||||
};
|
||||
}, [featureData?.values_]);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
if (isPipeFeature) {
|
||||
setMngInstOptions([]);
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}
|
||||
|
||||
const fetchMngInstOptions = async () => {
|
||||
try {
|
||||
const result = await fetchManagingInstitutions();
|
||||
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]);
|
||||
|
||||
useEffect(() => {
|
||||
if (ctpv.length === 0) void fetchCtpv();
|
||||
if (sgg.length === 0) void fetchSgg();
|
||||
}, [ctpv.length, fetchCtpv, fetchSgg, sgg.length]);
|
||||
|
||||
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 withResolvedRegionNames = (data: any) => {
|
||||
if (!data || typeof data !== "object") return data;
|
||||
|
||||
const stdgCd = String(data.stdg_cd ?? data.stdgCd ?? "").trim();
|
||||
const ctpvCd = String(
|
||||
data.ctpv_cd ?? data.ctpvCd ?? stdgCd.slice(0, 2),
|
||||
).trim();
|
||||
const sggCd = String(
|
||||
data.sgg_cd ?? data.sggCd ?? stdgCd.slice(0, 5),
|
||||
).trim();
|
||||
const resolvedCtpvNm =
|
||||
ctpv.find((item) => String(item.val).trim() === ctpvCd)?.text ?? "";
|
||||
const resolvedSggNm =
|
||||
sgg.find((item) => String(item.val).trim() === sggCd)?.text ?? "";
|
||||
|
||||
return {
|
||||
...data,
|
||||
ctpv_nm: data.ctpv_nm ?? data.ctpvNm ?? resolvedCtpvNm,
|
||||
ctpvNm: data.ctpvNm ?? data.ctpv_nm ?? resolvedCtpvNm,
|
||||
sgg_nm: data.sgg_nm ?? data.sggNm ?? resolvedSggNm,
|
||||
sggNm: data.sggNm ?? data.sgg_nm ?? resolvedSggNm,
|
||||
};
|
||||
};
|
||||
|
||||
const hasDetailValue = (value: unknown) => {
|
||||
if (value === null || value === undefined) return false;
|
||||
if (typeof value === "string") return value.trim() !== "";
|
||||
return true;
|
||||
};
|
||||
|
||||
const isValidDetailIdentifier = (value: unknown) => {
|
||||
if (typeof value !== "string") return false;
|
||||
const normalizedValue = value.trim();
|
||||
if (!normalizedValue) return false;
|
||||
if (normalizedValue.toLowerCase() === "null") return false;
|
||||
if (normalizedValue.toLowerCase() === "undefined") return false;
|
||||
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,
|
||||
);
|
||||
linkedFacilityFeatureRef.current.changed?.();
|
||||
}
|
||||
|
||||
linkedFacilityFeatureRef.current = null;
|
||||
linkedFacilityOriginalStyleRef.current = null;
|
||||
};
|
||||
|
||||
// 하수처리구역에 연결된 하수처리시설 피처를 찾아 기존 아이콘 위에 노랑 하이라이트를 덧씌운다.
|
||||
const highlightLinkedFacility = (facilityCode: string | null | undefined) => {
|
||||
clearLinkedFacilityHighlight();
|
||||
|
||||
if (!gisMap || !facilityCode) return;
|
||||
|
||||
const normalizedFacilityCode = String(facilityCode).trim();
|
||||
const layers = gisMap.getLayers().getArray();
|
||||
|
||||
for (const layer of layers) {
|
||||
const source = layer?.getSource?.();
|
||||
if (!source?.getFeatures) continue;
|
||||
|
||||
const features = source.getFeatures();
|
||||
const targetFeature = features.find((feature: any) => {
|
||||
const featureId = feature?.getId?.();
|
||||
const isFacilityLayer =
|
||||
typeof featureId === "string" &&
|
||||
featureId.startsWith("tb_il_swage_prcs_fclt.");
|
||||
const featureFacilityCode = feature?.get?.("swtrmt_fclt_cd");
|
||||
|
||||
return (
|
||||
isFacilityLayer &&
|
||||
String(featureFacilityCode ?? "").trim() === normalizedFacilityCode
|
||||
);
|
||||
});
|
||||
|
||||
if (targetFeature) {
|
||||
const originalFeatureStyle = targetFeature.getStyle?.();
|
||||
const featureLayer = targetFeature.getLayer?.();
|
||||
const layerStyleFn = featureLayer?.getStyleFunction?.() ?? null;
|
||||
|
||||
linkedFacilityOriginalStyleRef.current = originalFeatureStyle;
|
||||
linkedFacilityFeatureRef.current = targetFeature;
|
||||
targetFeature.setStyle((feature: any, resolution: number) => {
|
||||
let styles: any[] = [];
|
||||
|
||||
if (typeof originalFeatureStyle === "function") {
|
||||
const originalStyles = originalFeatureStyle(feature, resolution);
|
||||
if (Array.isArray(originalStyles)) styles.push(...originalStyles);
|
||||
else if (originalStyles) styles.push(originalStyles);
|
||||
} else if (originalFeatureStyle) {
|
||||
if (Array.isArray(originalFeatureStyle))
|
||||
styles.push(...originalFeatureStyle);
|
||||
else styles.push(originalFeatureStyle);
|
||||
} else if (layerStyleFn) {
|
||||
const layerStyles = layerStyleFn(feature, resolution);
|
||||
if (Array.isArray(layerStyles)) styles.push(...layerStyles);
|
||||
else if (layerStyles) styles.push(layerStyles);
|
||||
}
|
||||
|
||||
styles.push(linkedFacilityHighlightStyle);
|
||||
return styles;
|
||||
});
|
||||
targetFeature.changed?.();
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 피쳐데이터의 현재 레이어 이름 가져오는 함수
|
||||
const getSelectedLayers = () => {
|
||||
const { layerName, patch } = resolveFacilitySelection(
|
||||
featureData,
|
||||
gisMap,
|
||||
featureId,
|
||||
);
|
||||
if ("isClicked" in patch) setIsClicked(patch.isClicked as boolean);
|
||||
if ("headlist" in patch) setHeadlist(patch.headlist!);
|
||||
if ("headlist2" in patch) setHeadlist2(patch.headlist2!);
|
||||
if ("layerSpecificNm" in patch)
|
||||
setLayerSpecificNm(patch.layerSpecificNm as string);
|
||||
if ("isDrtwSewagePump" in patch)
|
||||
setIsDrtwSewagePump(patch.isDrtwSewagePump as boolean);
|
||||
return layerName;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
const commitLayerNm: typeof setLayerNm = (value) => {
|
||||
if (active) setLayerNm(value);
|
||||
};
|
||||
const commitFetchData: typeof setFetchData = (value) => {
|
||||
if (active) setFetchData(value);
|
||||
};
|
||||
const commitTableData: typeof setTableData = (value) => {
|
||||
if (active) setTableData(value);
|
||||
};
|
||||
const commitButtonChk: typeof setButtonChk = (value) => {
|
||||
if (active) setButtonChk(value);
|
||||
};
|
||||
const commitIsMainSsc: typeof setIsMainSsc = (value) => {
|
||||
if (active) setIsMainSsc(value);
|
||||
};
|
||||
const commitChmbrXcnts: typeof setChmbrXcnts = (value) => {
|
||||
if (active) setChmbrXcnts(value);
|
||||
};
|
||||
const commitChmbrYdnts: typeof setChmbrYdnts = (value) => {
|
||||
if (active) setChmbrYdnts(value);
|
||||
};
|
||||
const fetchData = async () => {
|
||||
if (!featureId) return;
|
||||
|
||||
try {
|
||||
const selectedLayerName = getSelectedLayers(); // 레이어 이름 가져오기
|
||||
commitLayerNm(selectedLayerName); // 상태 업데이트
|
||||
|
||||
let data;
|
||||
if (featureData["ol_uid"])
|
||||
data = featureData.values_; // Gis 레이어 클릭 이벤트일 때
|
||||
else data = featureData; // SearchModal 클릭 이벤트일 때
|
||||
|
||||
// 하수맨홀인 경우 용도코드를 텍스트로 변환
|
||||
if (selectedLayerName === "하수맨홀" && data) {
|
||||
// mqlt_cd 값 변환 (재질코드)
|
||||
if (data.mqlt_cd) {
|
||||
const materialCodeItem = MS_SWAGE_MHL_CODES.find(
|
||||
(code) => code.val === data.mqlt_cd.trim(),
|
||||
);
|
||||
if (materialCodeItem) data.mqlt_cd = `${materialCodeItem.text}`;
|
||||
}
|
||||
} else {
|
||||
// 중점우수토실인 경우 구분 값
|
||||
if (selectedLayerName === "중점우수토실" && data) {
|
||||
if (data.mesure_spot_se) {
|
||||
const mesureSpotSe = [
|
||||
{ id: "0", text: "합류식" },
|
||||
{ id: "1", text: "분류식" },
|
||||
];
|
||||
const mesureSpotSeItem = mesureSpotSe.find(
|
||||
(code) => code.id === data.mesure_spot_se.trim(),
|
||||
);
|
||||
if (mesureSpotSeItem) data.mesure_spot_se = mesureSpotSeItem.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 🎯 기본 데이터 포맷팅
|
||||
const normalizedRegionData =
|
||||
selectedLayerName === "침수흔적위선" ||
|
||||
selectedLayerName === "침수흔적심선"
|
||||
? withResolvedRegionNames(data)
|
||||
: data;
|
||||
const formattedData = withMngInstName(
|
||||
formatDisplayData(normalizedRegionData),
|
||||
);
|
||||
if (selectedLayerName === "침수흔적위선") {
|
||||
const fldngBgngDtm = formatFldngHstryDateTime(
|
||||
formattedData.bgngYmd ??
|
||||
formattedData.bgng_ymd ??
|
||||
data.bgngYmd ??
|
||||
data.bgng_ymd,
|
||||
formattedData.fldngBgngHm ??
|
||||
formattedData.fldng_bgng_hm ??
|
||||
data.fldngBgngHm ??
|
||||
data.fldng_bgng_hm,
|
||||
);
|
||||
const fldngEndDtm = formatFldngHstryDateTime(
|
||||
formattedData.endYmd ??
|
||||
formattedData.end_ymd ??
|
||||
data.endYmd ??
|
||||
data.end_ymd,
|
||||
formattedData.fldngEndHm ??
|
||||
formattedData.fldng_end_hm ??
|
||||
data.fldngEndHm ??
|
||||
data.fldng_end_hm,
|
||||
);
|
||||
|
||||
formattedData.fldng_bgng_dtm = fldngBgngDtm;
|
||||
formattedData.fldngBgngDtm = fldngBgngDtm;
|
||||
formattedData.fldng_end_dtm = fldngEndDtm;
|
||||
formattedData.fldngEndDtm = fldngEndDtm;
|
||||
}
|
||||
if (selectedLayerName === "하수관로") {
|
||||
const installYmd = data.instl_ymd ?? data.instlYmd;
|
||||
formattedData.elapsedYears = getElapsedYearsDisplayText(installYmd);
|
||||
if (isInvalidInstallYmd(installYmd)) {
|
||||
formattedData.instl_ymd = "확인불가";
|
||||
formattedData.instlYmd = "확인불가";
|
||||
}
|
||||
}
|
||||
let mergedDetailData = formattedData;
|
||||
|
||||
commitFetchData(formattedData);
|
||||
commitTableData(formattedData);
|
||||
|
||||
switch (selectedLayerName) {
|
||||
case "하수관로":
|
||||
commitButtonChk(true);
|
||||
|
||||
// ✅ codeMapper 사용하여 API 결과도 변환
|
||||
{
|
||||
const initialPipeData = withMngInstName(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: { ...formattedData },
|
||||
}),
|
||||
);
|
||||
commitFetchData(initialPipeData);
|
||||
commitTableData(initialPipeData);
|
||||
}
|
||||
break;
|
||||
case "하수맨홀":
|
||||
commitButtonChk(true);
|
||||
|
||||
// ✅ codeMapper 사용하여 API 결과도 변환
|
||||
commitTableData(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: { ...formattedData },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "하수펌프장":
|
||||
commitButtonChk(true);
|
||||
|
||||
commitTableData(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: { ...formattedData },
|
||||
}),
|
||||
);
|
||||
break;
|
||||
case "하수처리시설":
|
||||
commitButtonChk(false);
|
||||
break;
|
||||
case "하수처리구역":
|
||||
commitButtonChk(false);
|
||||
break;
|
||||
case "침수흔적위선":
|
||||
commitButtonChk(false);
|
||||
break;
|
||||
case "우수토실":
|
||||
commitButtonChk(true);
|
||||
commitIsMainSsc(false);
|
||||
break;
|
||||
case "중점우수토실":
|
||||
commitButtonChk(false);
|
||||
commitIsMainSsc(true);
|
||||
// 🎯 processedData도 포맷팅하여 설정
|
||||
const processedFormattedData = formatDisplayData(processedData);
|
||||
|
||||
commitFetchData([processedFormattedData]);
|
||||
commitTableData(processedFormattedData);
|
||||
// setIsLoading(false); // 기본 렌더링 완료
|
||||
|
||||
commitTableData(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: { ...processedFormattedData },
|
||||
}),
|
||||
);
|
||||
|
||||
commitChmbrXcnts(data.chmbr_xcnts);
|
||||
commitChmbrYdnts(data.chmbr_ydnts);
|
||||
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// 자체입력정보 API 엔드포인트 선택
|
||||
const fcltMngNo = String(
|
||||
featureData?.values_?.fclt_mng_no || featureData?.fcltMngNo || "",
|
||||
).trim();
|
||||
const mngInstCd = String(
|
||||
featureData?.values_?.mng_inst_cd || featureData?.mngInstCd || "",
|
||||
).trim();
|
||||
const canRequestDetail =
|
||||
isValidDetailIdentifier(fcltMngNo) &&
|
||||
isValidDetailIdentifier(mngInstCd);
|
||||
|
||||
// API에서 상세 데이터 가져오기
|
||||
if (supportsFacilityInput(selectedLayerName) && canRequestDetail) {
|
||||
try {
|
||||
const result = await fetchFacilityInput(
|
||||
selectedLayerName,
|
||||
fcltMngNo,
|
||||
mngInstCd,
|
||||
);
|
||||
|
||||
if (result) {
|
||||
mergedDetailData = mergeDetailData(mergedDetailData, result);
|
||||
const processedApiData = withMngInstName(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: mergedDetailData,
|
||||
}),
|
||||
);
|
||||
|
||||
commitFetchData(processedApiData);
|
||||
commitTableData(processedApiData);
|
||||
}
|
||||
} catch (apiError) {
|
||||
void apiError;
|
||||
console.warn("Pipe detail fallback kept initial feature data.");
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedLayerName === "하수관로" && canRequestDetail) {
|
||||
try {
|
||||
const requestCacheKey = `${fcltMngNo}::${mngInstCd}`;
|
||||
let flowDirectionRequest =
|
||||
flowDirectionBasisRequestCacheRef.current.get(requestCacheKey);
|
||||
if (!flowDirectionRequest) {
|
||||
flowDirectionRequest = fetchPipeFlowBasis(
|
||||
fcltMngNo,
|
||||
mngInstCd,
|
||||
).catch((error) => {
|
||||
flowDirectionBasisRequestCacheRef.current.delete(
|
||||
requestCacheKey,
|
||||
);
|
||||
throw error;
|
||||
});
|
||||
flowDirectionBasisRequestCacheRef.current.set(
|
||||
requestCacheKey,
|
||||
flowDirectionRequest,
|
||||
);
|
||||
}
|
||||
const enrichedPipe = await flowDirectionRequest;
|
||||
if (enrichedPipe) {
|
||||
mergedDetailData = mergeDetailData(
|
||||
mergedDetailData,
|
||||
enrichedPipe,
|
||||
);
|
||||
const processedPipeData = withMngInstName(
|
||||
codeMapper({
|
||||
layerName: selectedLayerName,
|
||||
data: mergedDetailData,
|
||||
}),
|
||||
);
|
||||
commitFetchData(processedPipeData);
|
||||
commitTableData(processedPipeData);
|
||||
}
|
||||
} catch (flowDirectionError) {
|
||||
console.warn(
|
||||
"관로 유하방향 근거 조회 실패, 기존 상세정보를 유지합니다.",
|
||||
flowDirectionError,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedLayerName === "침수흔적위선" && featureId) {
|
||||
resetFldngHstryFeatureClick();
|
||||
const fldngHstryFid = normalizeFldngHstryWtlvApiFid(featureId);
|
||||
if (!fldngHstryFid) {
|
||||
throw new Error("침수흔적도 fid가 비어 있습니다.");
|
||||
}
|
||||
|
||||
const fldngHstryDetail =
|
||||
await loadFldngHstryFeatureClickDetail(fldngHstryFid);
|
||||
const mergedFldngHstryData = {
|
||||
...formattedData,
|
||||
...fldngHstryDetail.rainAnalysis,
|
||||
};
|
||||
commitFetchData(mergedFldngHstryData);
|
||||
commitTableData(mergedFldngHstryData);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("데이터 로딩 중 오류:", error);
|
||||
}
|
||||
};
|
||||
|
||||
void fetchData();
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [featureId, processedData, mngInstNameMap, codeMapper]);
|
||||
|
||||
useEffect(() => {
|
||||
const layerTypeNm = featureData?.values_
|
||||
? featureData?.id_?.split(".")?.[0]
|
||||
: featureData?.lyrTypeNm;
|
||||
|
||||
if (layerTypeNm === "tb_ms_swage_prcs_zone") {
|
||||
const facilityCode =
|
||||
featureData?.values_?.swtrmt_fclt_cd ?? featureData?.swtrmtFcltCd;
|
||||
highlightLinkedFacility(facilityCode);
|
||||
return () => {
|
||||
clearLinkedFacilityHighlight();
|
||||
};
|
||||
}
|
||||
|
||||
clearLinkedFacilityHighlight();
|
||||
|
||||
return () => {
|
||||
clearLinkedFacilityHighlight();
|
||||
};
|
||||
}, [featureData, gisMap]);
|
||||
|
||||
// 저장 시 모달 띄우기
|
||||
const handleSaveClick = async () => {
|
||||
const shouldSave = await confirm("정보를 저장하시겠습니까?");
|
||||
if (!shouldSave) return;
|
||||
btnClickEvent();
|
||||
};
|
||||
|
||||
// 저장 버튼 이벤트
|
||||
const btnClickEvent = async () => {
|
||||
const bodyData: Record<string, any> = {};
|
||||
|
||||
if (buttonChk && contentRef.current) {
|
||||
const inputElements = contentRef.current.querySelectorAll("input");
|
||||
const selectElements = contentRef.current.querySelectorAll("select");
|
||||
|
||||
// 카멜케이스 변환 함수
|
||||
const toCamelCase = (str: string) =>
|
||||
str.replace(/_([a-z])/g, (_, char) => char.toUpperCase());
|
||||
|
||||
// select 태그의 값 가져오기
|
||||
selectElements.forEach((select) => {
|
||||
const camelCaseId = toCamelCase(select.id);
|
||||
bodyData[camelCaseId] = select.value;
|
||||
});
|
||||
|
||||
// // input 태그의 값 가져오기
|
||||
inputElements.forEach((input) => {
|
||||
const camelCaseId = toCamelCase(input.id);
|
||||
bodyData[camelCaseId] = input.value;
|
||||
});
|
||||
|
||||
// 레이어명에 따라 API 엔드포인트 분기처리
|
||||
let result = null;
|
||||
|
||||
bodyData["fcltMngNo"] =
|
||||
featureData.values_.fclt_mng_no.toString() || null;
|
||||
bodyData["mngInstCd"] =
|
||||
featureData.values_.mng_inst_cd.toString() || null;
|
||||
// 빈 키 제거
|
||||
if (bodyData[""] !== undefined) delete bodyData[""];
|
||||
|
||||
// 🎯 우수토실일 경우 prrtymngYn 값 변환
|
||||
if (layerNm === "우수토실" && bodyData.prrtymngYn) {
|
||||
if (bodyData.prrtymngYn === "중점우수토실") {
|
||||
bodyData.prrtymngYn = "Y";
|
||||
} else if (bodyData.prrtymngYn === "우수토실") {
|
||||
bodyData.prrtymngYn = "N";
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
result = await saveFacilityInput(layerNm, bodyData);
|
||||
|
||||
if (result) {
|
||||
alert("저장되었습니다");
|
||||
setFetchData(result.data || result);
|
||||
} else {
|
||||
alert("저장에 실패했습니다");
|
||||
console.error("API 응답 오류:", result);
|
||||
}
|
||||
} catch (error) {
|
||||
alert("저장 중 오류가 발생했습니다");
|
||||
console.error("API 요청 오류:", error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 레이어명에 따라 상세페이지 렌더링
|
||||
const ContentComponent = layerNm ? getLayerContentComponent(layerNm) : null;
|
||||
|
||||
return (
|
||||
<div
|
||||
id="popup"
|
||||
className="absolute right-0 top-0 z-[50] flex h-full max-h-[calc(100dvh-6rem)] w-[350px] max-w-full flex-col overflow-hidden border-r border-border bg-background transition-all duration-300"
|
||||
>
|
||||
<LoadingOverlay isLoading={isLoading} />
|
||||
{/* 제목·기능 버튼·닫기 버튼의 칸을 분리해 시설 종류나 제목 길이에 관계없이 겹침을 방지한다. */}
|
||||
<div className="card-header relative !mx-0 !grid shrink-0 grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2 bg-primary p-4">
|
||||
<div className="min-w-0">
|
||||
{surveyMode && (
|
||||
<h3 className="break-words text-2xl font-medium text-primary-foreground">
|
||||
조사관리 <br />
|
||||
관로번호 :{" "}
|
||||
{featureData?.get?.("gisManagementNo") ??
|
||||
featureData?.values_?.gisManagementNo ??
|
||||
featureData?.gisManagementNo ??
|
||||
layerSpecificNm}
|
||||
</h3>
|
||||
)}
|
||||
<h3
|
||||
className={`${surveyMode ? "hidden" : ""} break-words text-2xl font-medium text-primary-foreground`}
|
||||
>
|
||||
{layerNm}
|
||||
{tableData?.usg_cd && <>({tableData.usg_cd})</>} 정보 <br />
|
||||
관리번호 : {layerSpecificNm}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 하수관로일 때만 Infil/RDII 버튼 표시 */}
|
||||
{layerNm === "하수관로" && (
|
||||
<>
|
||||
<Button
|
||||
className="px-2"
|
||||
onClick={() => {
|
||||
const popupWindow = openWindowPopup("infilChart", {
|
||||
pplMngNo,
|
||||
});
|
||||
if (!popupWindow) {
|
||||
alert(
|
||||
"팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.",
|
||||
);
|
||||
}
|
||||
}}
|
||||
color="primary"
|
||||
>
|
||||
침입수분석
|
||||
</Button>
|
||||
<Button
|
||||
className="px-2"
|
||||
onClick={() => {
|
||||
const popupWindow = openWindowPopup("rdiiChart", {
|
||||
pplMngNo,
|
||||
});
|
||||
if (!popupWindow) {
|
||||
alert(
|
||||
"팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.",
|
||||
);
|
||||
}
|
||||
}}
|
||||
color="primary"
|
||||
>
|
||||
RDII분석
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{layerNm === "하수맨홀" && (
|
||||
<>
|
||||
<Button
|
||||
color="white"
|
||||
onClick={() => {
|
||||
setIsLoading(true);
|
||||
searchUpperPpls(gisMap, layerSpecificNm, alert).finally(() =>
|
||||
setIsLoading(false),
|
||||
);
|
||||
}}
|
||||
>
|
||||
상류관로 보기
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
onClick={onClose}
|
||||
className="text-primary-foreground/80 h-8 w-8 shrink-0 p-0 hover:text-primary-foreground focus:outline-none"
|
||||
size="xs"
|
||||
aria-label="시설 상세정보 닫기"
|
||||
title="닫기"
|
||||
>
|
||||
<span aria-hidden="true">✕</span>
|
||||
</Button>
|
||||
</div>
|
||||
{/* 표 카드를 flex로 압축하지 않고 내용 높이대로 쌓아 본문에서만 스크롤한다. */}
|
||||
<div
|
||||
className="min-h-0 min-w-0 flex-1 overflow-y-auto overflow-x-hidden"
|
||||
ref={contentRef}
|
||||
>
|
||||
<VerticalTable
|
||||
headName={
|
||||
layerNm === "침수흔적위선" && hasFldngHstryLinkedFeatures ? (
|
||||
fldngHstryFeatureClickHeadName
|
||||
) : layerNm === "하수관로" && tableData?.elapsedYears ? (
|
||||
<>
|
||||
기본정보{" "}
|
||||
<span className="ml-2 rounded-sm bg-red-50 px-2 py-0.5 text-[1.1rem] font-semibold text-red-700">
|
||||
경과년도 {tableData.elapsedYears}
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
"기본정보"
|
||||
)
|
||||
}
|
||||
tableName1={layerNm === "중점우수토실" ? "측정지점" : undefined}
|
||||
tableData={[tableData]}
|
||||
headlist={headlist}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
onPageChange={function (): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
// 두 번째 테이블 조건부 props
|
||||
showSecondTable={layerNm === "중점우수토실" ? true : false}
|
||||
tableName2={layerNm === "중점우수토실" ? "시설현황" : undefined}
|
||||
tableData2={
|
||||
layerNm === "중점우수토실" && tableData ? [tableData] : []
|
||||
}
|
||||
headlist2={layerNm === "중점우수토실" ? headlist2 : undefined}
|
||||
pageSize2={20}
|
||||
total2={0}
|
||||
isEditable2={buttonChk}
|
||||
/>
|
||||
{ContentComponent && (
|
||||
<ContentComponent
|
||||
featureData={fetchData}
|
||||
isMainSsc={isMainSsc}
|
||||
isDrtwSewagePump={isDrtwSewagePump}
|
||||
onSaveClick={handleSaveClick}
|
||||
chmbrXcnts={chmbrXcnts}
|
||||
chmbrYdnts={chmbrYdnts}
|
||||
gisObject={featureData?.values_ ?? featureData}
|
||||
rawFeatureData={featureData}
|
||||
surveyResultContent={
|
||||
surveyMode ? (
|
||||
<ExmnSurveyResultSection featureData={featureData} />
|
||||
) : undefined
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
export default FeatureClickEventPopup;
|
||||
@@ -0,0 +1,88 @@
|
||||
/** 시설 상세정보 화면의 운영정보 입력 영역을 공통 형식으로 표시한다. */
|
||||
import {
|
||||
Table,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
TableHead,
|
||||
TableBody,
|
||||
TableCell,
|
||||
} from "@common/components/ui";
|
||||
import React from "react";
|
||||
|
||||
interface InputSectionProps {
|
||||
title: string;
|
||||
data: { year: string; type: string; bizInfoNm: string; bizType: string }[];
|
||||
sectionKey: string;
|
||||
onInputChange: (
|
||||
section: string,
|
||||
index: number,
|
||||
field: string,
|
||||
value: string,
|
||||
) => void;
|
||||
}
|
||||
|
||||
const InputSection: React.FC<InputSectionProps> = ({
|
||||
title,
|
||||
data,
|
||||
sectionKey,
|
||||
onInputChange,
|
||||
}) => {
|
||||
return (
|
||||
<div>
|
||||
{/* 섹션 제목 */}
|
||||
<div className="card-header">
|
||||
<h3 className="mx-3 whitespace-nowrap text-2xl font-medium text-label">
|
||||
{title}
|
||||
</h3>
|
||||
</div>
|
||||
{/* 테이블 */}
|
||||
<div className="card !p-0r !m-[1.2rem]">
|
||||
<Table variant="secondary" className="w-full">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-auto whitespace-nowrap border border-border px-2 py-2 text-sm">
|
||||
구분
|
||||
</TableHead>
|
||||
<TableHead className="w-[80px] whitespace-nowrap border border-border px-2 py-2 text-sm">
|
||||
진단연도
|
||||
</TableHead>
|
||||
<TableHead className="w-auto whitespace-nowrap border border-border px-2 py-2 text-sm">
|
||||
사업명
|
||||
</TableHead>
|
||||
<TableHead className="w-auto whitespace-nowrap border border-border px-2 py-2 text-sm">
|
||||
유형
|
||||
</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{data.map((row, index) => (
|
||||
<TableRow key={index}>
|
||||
<TableCell className="w-auto whitespace-nowrap border border-border px-2 py-2 text-center text-sm leading-normal">
|
||||
{row.type}
|
||||
</TableCell>
|
||||
<TableCell className="w-[80px] whitespace-nowrap border border-border px-2 py-2 text-sm">
|
||||
<input
|
||||
type="text"
|
||||
value={row.year}
|
||||
onChange={(e) =>
|
||||
onInputChange(sectionKey, index, "year", e.target.value)
|
||||
}
|
||||
className="border-radius-0 w-full px-3 py-2 text-center text-base text-xl leading-normal"
|
||||
/>
|
||||
</TableCell>
|
||||
<TableCell className="w-auto border border-border px-2 py-2 text-center text-sm leading-normal">
|
||||
{row.bizInfoNm}
|
||||
</TableCell>
|
||||
<TableCell className="w-auto whitespace-nowrap border border-border px-2 py-2 text-center text-sm leading-normal">
|
||||
{row.bizType}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default InputSection;
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* 화면명: 하수관로 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (하수관로)
|
||||
*
|
||||
* 📄 MsSwagePpl
|
||||
* 하수관로 정보 컴포넌트
|
||||
*
|
||||
* - 하수관로의 자체입력정보 표시 및 편집 기능
|
||||
* - 보수 및 갱신, 청소 및 준설, 점검 및 진단 데이터 조회 및 표시
|
||||
* - VerticalTable을 통한 입력 폼 렌더링
|
||||
* - InputSection을 통한 운영 데이터 관리
|
||||
* - 저장 버튼을 통한 데이터 저장 기능
|
||||
*
|
||||
* 🔗 사용 API
|
||||
* - 시설별 운영 정보 조회: GET /api/v1/bizInfo/bizByFclt (sewerage-service)
|
||||
*/
|
||||
"use client";
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import React, { useState, useEffect } from "react";
|
||||
import InputSection from "@/features/facility-detail/ui/input-section";
|
||||
import { handleInputChange } from "@/features/facility-detail/lib/facility-panel-registry";
|
||||
import { getData } from "@/shared/api/sewerage-api";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
|
||||
// 하수관로
|
||||
const inputColumn = [
|
||||
{
|
||||
id: "instlMbdyCd",
|
||||
title: "설치주제",
|
||||
type: "select",
|
||||
options: ["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: ["도로", "하상"] },
|
||||
];
|
||||
|
||||
type operationDataType = {
|
||||
year: string;
|
||||
type: string;
|
||||
bizInfoNm: string;
|
||||
bizType: string;
|
||||
};
|
||||
|
||||
const MsSwagePpl = ({
|
||||
featureData,
|
||||
onSaveClick,
|
||||
surveyResultContent,
|
||||
}: {
|
||||
featureData: any;
|
||||
onSaveClick?: () => void;
|
||||
surveyResultContent?: React.ReactNode;
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<any>({});
|
||||
const [repairData, setRepairData] = useState<operationDataType[]>([]);
|
||||
const [cleaningData, setCleaningData] = useState<operationDataType[]>([]);
|
||||
const [inspectionData, setInspectionData] = useState<operationDataType[]>([]);
|
||||
const dataMap = {
|
||||
repair: { data: repairData, setData: setRepairData },
|
||||
cleaning: { data: cleaningData, setData: setCleaningData },
|
||||
inspection: { data: inspectionData, setData: setInspectionData },
|
||||
};
|
||||
|
||||
const { BIZ_SE_CD, BIZ_TY_CD } = useStore();
|
||||
const requestMngInstCd = String(
|
||||
featureData?.mng_inst_cd ?? featureData?.mngInstCd ?? "",
|
||||
).trim();
|
||||
const requestFcltMngNo = String(
|
||||
featureData?.fclt_mng_no ?? featureData?.fcltMngNo ?? "",
|
||||
).trim();
|
||||
// 조사관리 전용 탭은 기본·입력정보와 조사결과만 표시하고 일반 시설 유지관리 이력은 숨긴다.
|
||||
const showOperationSections = !surveyResultContent;
|
||||
|
||||
// 마운트 및 업데이트 시 API 호출
|
||||
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showOperationSections || !requestMngInstCd || !requestFcltMngNo) {
|
||||
setInspectionData([]);
|
||||
setCleaningData([]);
|
||||
setRepairData([]);
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const fetchAll = async () => {
|
||||
const operationData = await getData(
|
||||
`v1/bizInfo/bizByFclt?mngInstCd=${requestMngInstCd}&fcltMngNo=${requestFcltMngNo}&page=0&size=1`,
|
||||
);
|
||||
|
||||
let inspectionArr: operationDataType[] = [];
|
||||
let cleaningArr: operationDataType[] = [];
|
||||
let repairArr: operationDataType[] = [];
|
||||
|
||||
if (Array.isArray(operationData)) {
|
||||
operationData.forEach((item) => {
|
||||
if (!item.flfmt_yr) return;
|
||||
// biz_se_cd에 해당하는 type명 찾기
|
||||
const seCodeObj = BIZ_SE_CD.find(
|
||||
(code) => code.lwpoCd === item.biz_se_cd,
|
||||
);
|
||||
const tyCodeObj = BIZ_TY_CD.find(
|
||||
(code) => code.lwpoCd === item.biz_ty_cd,
|
||||
);
|
||||
const seTypeName = seCodeObj ? seCodeObj.lwpoCdNm : "";
|
||||
const tyTypeName = tyCodeObj ? tyCodeObj.lwpoCdNm : "";
|
||||
switch (item.biz_se_cd) {
|
||||
case "100":
|
||||
inspectionArr.push({
|
||||
year: String(item.flfmt_yr),
|
||||
type: seTypeName,
|
||||
bizInfoNm: String(item.biz_info_nm),
|
||||
bizType: tyTypeName,
|
||||
});
|
||||
break;
|
||||
case "203":
|
||||
cleaningArr.push({
|
||||
year: String(item.flfmt_yr),
|
||||
type: seTypeName,
|
||||
bizInfoNm: String(item.biz_info_nm),
|
||||
bizType: tyTypeName,
|
||||
});
|
||||
break;
|
||||
case "200":
|
||||
case "201":
|
||||
case "204":
|
||||
repairArr.push({
|
||||
year: String(item.flfmt_yr),
|
||||
type: seTypeName,
|
||||
bizInfoNm: String(item.biz_info_nm),
|
||||
bizType: tyTypeName,
|
||||
});
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!active) return;
|
||||
setInspectionData(inspectionArr);
|
||||
setCleaningData(cleaningArr);
|
||||
setRepairData(repairArr);
|
||||
};
|
||||
fetchAll().catch((error) => {
|
||||
if (!active) return;
|
||||
console.error("운영 이력 조회 실패:", error);
|
||||
setInspectionData([]);
|
||||
setCleaningData([]);
|
||||
setRepairData([]);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [
|
||||
BIZ_SE_CD,
|
||||
BIZ_TY_CD,
|
||||
requestFcltMngNo,
|
||||
requestMngInstCd,
|
||||
showOperationSections,
|
||||
]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<VerticalTable
|
||||
headName="입력정보"
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
{surveyResultContent}
|
||||
{showOperationSections && (
|
||||
<>
|
||||
<InputSection
|
||||
title="보수 및 갱신"
|
||||
data={repairData}
|
||||
sectionKey="repair"
|
||||
onInputChange={(section, index, field, value) =>
|
||||
handleInputChange(section, index, field, value, dataMap)
|
||||
}
|
||||
/>
|
||||
<InputSection
|
||||
title="청소 및 준설"
|
||||
data={cleaningData}
|
||||
sectionKey="cleaning"
|
||||
onInputChange={(section, index, field, value) =>
|
||||
handleInputChange(section, index, field, value, dataMap)
|
||||
}
|
||||
/>
|
||||
<InputSection
|
||||
title="점검 및 진단"
|
||||
data={inspectionData}
|
||||
sectionKey="inspection"
|
||||
onInputChange={(section, index, field, value) =>
|
||||
handleInputChange(section, index, field, value, dataMap)
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default MsSwagePpl;
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* 화면명: 하수펌프장 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (하수펌프장)
|
||||
*
|
||||
* 📄 sewagePump
|
||||
* 하수펌프장 정보 컴포넌트
|
||||
*
|
||||
* - 빗물펌프장 및 오수펌프장 구분에 따른 자체 입력 정보 표시 및 편집 기능
|
||||
* - VerticalTable을 통한 입력 폼 렌더링
|
||||
* - 저장 버튼을 통한 데이터 저장 기능
|
||||
*/
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import React, { useState, useEffect } from "react";
|
||||
// 빗물펌프장 자체 입력 정보
|
||||
const exclnInputColumn = [
|
||||
{ id: "swtrmtZoneNm", title: "배수구역", type: "input" },
|
||||
{ id: "mltvDtdvNm", title: "배수분구", type: "input" },
|
||||
{
|
||||
id: "designFrqYr",
|
||||
title: "설계빈도(년)",
|
||||
type: "input",
|
||||
placeholder: "예: 10",
|
||||
isNumber: true,
|
||||
length: 4,
|
||||
},
|
||||
];
|
||||
// 오수펌프장 자체 입력 정보
|
||||
const drtwInputColumn = [
|
||||
{ id: "swtrmtZoneNm", title: "처리구역", type: "input" },
|
||||
{ id: "mltvDtdvNm", title: "처리분구", type: "input" },
|
||||
];
|
||||
|
||||
const sewagePump = ({
|
||||
featureData,
|
||||
isDrtwSewagePump,
|
||||
onSaveClick,
|
||||
}: {
|
||||
featureData: any;
|
||||
isDrtwSewagePump?: boolean;
|
||||
onSaveClick?: () => void;
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<any>({});
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<VerticalTable
|
||||
headName="입력정보"
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={isDrtwSewagePump ? drtwInputColumn : exclnInputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default sewagePump;
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* 화면명: 하수맨홀 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (하수맨홀)
|
||||
*
|
||||
* 📄 Smh
|
||||
* 하수맨홀 정보 컴포넌트
|
||||
*
|
||||
* - 하수맨홀의 자체입력정보 표시 및 편집 기능
|
||||
* - VerticalTable을 통한 입력 폼 렌더링
|
||||
* - 상류관로 검색 및 지도 포커스 기능
|
||||
* - 저장 버튼을 통한 데이터 저장 기능
|
||||
*
|
||||
* 🔗 사용 API
|
||||
* - 상류관로 조회: GET /api/v1/fcltMhl/upperPpls/{fcltMngNo} (sewerage-service)
|
||||
*/
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import { type ReactNode, useEffect, useState } from "react";
|
||||
import GisApp from "@common/business_components/ui/map/lib/gis.core";
|
||||
import { getData } from "@/shared/api/sewerage-api";
|
||||
|
||||
// 상류관로 보기 함수 (FeatureClickEventPopup에서 사용)
|
||||
export async function searchUpperPpls(
|
||||
gisMap: any,
|
||||
fcltMngNo: any,
|
||||
notify: (message: string) => void,
|
||||
) {
|
||||
let data: any = null;
|
||||
try {
|
||||
data = await getData(`v1/fcltMhl/upperPpls/${fcltMngNo}`);
|
||||
} catch (error) {
|
||||
console.error("JSON parsing error:", error);
|
||||
notify(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
notify(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const select: any = GisApp.Module.select;
|
||||
let foundFeature: any = null;
|
||||
|
||||
(data || []).forEach((item: any) => {
|
||||
const pplMngNo = item.ppl_mng_no?.trim?.();
|
||||
|
||||
gisMap
|
||||
.getLayers()
|
||||
.getArray()
|
||||
.filter((e: any) => e.get("lyrTyNm") == "tb_ms_swage_ppl")
|
||||
.forEach((layer: any) => {
|
||||
const source = layer.getSource?.();
|
||||
if (source?.getFeatures) {
|
||||
const features = source.getFeatures();
|
||||
for (const f of features) {
|
||||
if (f.values_.fclt_mng_no?.trim?.() === pplMngNo) {
|
||||
foundFeature = f;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (foundFeature) select?.selectMultiFeature?.(foundFeature, true);
|
||||
});
|
||||
|
||||
if (!foundFeature) notify(`해당 맨홀의 상류관로를 찾을 수 없습니다.`);
|
||||
|
||||
const geometry = foundFeature?.getGeometry();
|
||||
if (geometry) {
|
||||
const extent = geometry.getExtent();
|
||||
gisMap.getView().fit(extent, {
|
||||
duration: 300,
|
||||
padding: [50, 50, 50, 50],
|
||||
maxZoom: 14,
|
||||
constrainResolution: true,
|
||||
nearest: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const inputColumn = [
|
||||
{ id: "swtrmtZoneNm", title: "처리구역", type: "input" },
|
||||
{ id: "mltvZoneNm", title: "배수구역", type: "input" },
|
||||
{ id: "mltvDtdvNm", title: "배수분구", type: "input" },
|
||||
{ id: "layCd", title: "매설위치", type: "select", options: ["도로", "하상"] },
|
||||
];
|
||||
const Smh = ({
|
||||
featureData,
|
||||
onSaveClick,
|
||||
surveyResultContent,
|
||||
}: {
|
||||
featureData: any;
|
||||
onSaveClick?: () => void;
|
||||
surveyResultContent?: ReactNode;
|
||||
}) => {
|
||||
const [formData, setFormData] = useState<any>({});
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<VerticalTable
|
||||
headName="입력정보"
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
{surveyResultContent}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Smh;
|
||||
@@ -0,0 +1,382 @@
|
||||
/**
|
||||
* 화면명: 우수토실 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (우수토실)
|
||||
*
|
||||
* 📄 Ssc
|
||||
* 우수토실 정보 컴포넌트
|
||||
*
|
||||
* - 우수토실의 자체입력정보 표시 및 편집 기능
|
||||
* - 중점우수토실 운영정보 모달 표시 (강우/측정 정보, 수량/수질측정 정보)
|
||||
* - VerticalTable을 통한 입력 폼 렌더링
|
||||
* - 저장 버튼을 통한 데이터 저장 기능
|
||||
*
|
||||
* 🔗 사용 API
|
||||
* - 위경도로 강우시 미처리 하수 목록 조회: GET /api/v1/onsemiro/getSwgRainsByGeomety (sewerage-service)
|
||||
* - 강우시 월류 하수 관리 모니터링 조회: GET /api/v1/onsemiro/swgRain/{adstDstrCd}/{manageNo}/mntrngs (sewerage-service)
|
||||
*/
|
||||
"use client";
|
||||
import { StandardPopupLayout } from "@common/business_components/ui";
|
||||
import { Button } from "@common/components/ui";
|
||||
import React, { useState, useEffect, useRef } from "react";
|
||||
import {
|
||||
untrtSwgRainCol3,
|
||||
untrtSwgRainCol4,
|
||||
untrtSwgRainCol5,
|
||||
} from "@/entities/facility/model/overflow-columns";
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import { getRawJson } from "@/shared/api/sewerage-api";
|
||||
import { formatDisplayData } from "@/components/lib/utils/format-display-value";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import MapPopupDataTable from "@/features/window-popup/ui/map-popup-data-table";
|
||||
|
||||
const inputColumn = [
|
||||
{
|
||||
id: "prrtymngYn",
|
||||
title: "중점여부",
|
||||
type: "select",
|
||||
options: ["우수토실", "중점우수토실"],
|
||||
},
|
||||
{ id: "swtrmtZoneNm", title: "처리구역", type: "input" },
|
||||
];
|
||||
|
||||
const toStandardHeadList = (headlist: typeof untrtSwgRainCol3) =>
|
||||
headlist.map((head) => ({
|
||||
...head,
|
||||
title: ["no", "rowNo", "rowNumber"].includes(head.id) ? "순번" : head.title,
|
||||
}));
|
||||
|
||||
const Ssc = ({
|
||||
featureData,
|
||||
isMainSsc,
|
||||
chmbrXcnts,
|
||||
chmbrYdnts,
|
||||
onSaveClick,
|
||||
renderMode = "inline",
|
||||
}: {
|
||||
featureData: any;
|
||||
isMainSsc?: boolean;
|
||||
chmbrXcnts?: string;
|
||||
chmbrYdnts?: string;
|
||||
onSaveClick?: () => void;
|
||||
renderMode?: "inline" | "popup";
|
||||
}) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const [formData, setFormData] = useState<any>({});
|
||||
const [rainMeasureData, setRainMeasureData] = useState<any[]>([]); // 강우, 측정 정보
|
||||
const [mntrngsData, setMntrngsData] = useState<any[]>([]); // 수량/수질측정 정보
|
||||
const [totalCount, setTotalCount] = useState<number>(0);
|
||||
const [totalDetailCount, setTotalDetailCount] = useState<number>(0);
|
||||
const [selectedRowIndex, setSelectedRowIndex] = useState<number>(-1);
|
||||
const [curPage, setCurPage] = useState<number>(1);
|
||||
const [curDetailPage, setCurDetailPage] = useState<number>(1);
|
||||
// 시설·페이지 재선택 시 오래된 측정 응답을 무시한다.
|
||||
const rainRequestSequence = useRef(0);
|
||||
const monitoringRequestSequence = useRef(0);
|
||||
useEffect(
|
||||
() => () => {
|
||||
rainRequestSequence.current += 1;
|
||||
monitoringRequestSequence.current += 1;
|
||||
},
|
||||
[chmbrXcnts, chmbrYdnts, featureData],
|
||||
);
|
||||
|
||||
// 강우, 측정 정보 API 호출 함수
|
||||
const fetchRainMeasureData = async (
|
||||
chmbrXcnts: string,
|
||||
chmbrYdnts: string,
|
||||
) => {
|
||||
const sequence = ++rainRequestSequence.current;
|
||||
if (!chmbrXcnts || !chmbrYdnts) {
|
||||
console.warn("추가 데이터 호출 실패: 필수 매개변수 누락", {
|
||||
chmbrXcnts,
|
||||
chmbrYdnts,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const queryParams = new URLSearchParams({
|
||||
chmbrXcnts: chmbrXcnts,
|
||||
chmbrYdnts: chmbrYdnts,
|
||||
page: `${curPage - 1}`,
|
||||
size: "3",
|
||||
});
|
||||
|
||||
const result = await getRawJson(
|
||||
`/sewerage-service/api/v1/onsemiro/getSwgRainsByGeomety?${queryParams.toString()}`,
|
||||
);
|
||||
if (sequence !== rainRequestSequence.current) return [];
|
||||
|
||||
// helper: "YYYY-MM-DD HH:MM:SS" -> "MM-DD HH:MM"
|
||||
const formatNoYearNoSec = (val: any) => {
|
||||
if (!val && val !== 0) return "-";
|
||||
const s = String(val);
|
||||
// 정규식으로 안전하게 매칭 후 변환
|
||||
const m = s.match(
|
||||
/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::\d{2})?$/,
|
||||
);
|
||||
if (m) {
|
||||
const [, , mm, dd, hh, min] = m;
|
||||
return `${mm}-${dd} ${hh}:${min}`;
|
||||
}
|
||||
// 포맷이 예상과 다르면, 길이에 따라 잘라보기
|
||||
if (s.length >= 16) return s.substring(5, 16); // "YYYY-" 제거하고 초 전까지
|
||||
return s;
|
||||
};
|
||||
|
||||
const processedDataArray: any[] = result.content.map((data: any) => {
|
||||
// 🎯 formatDisplayData로 기본 포맷팅 적용
|
||||
const formattedItem = formatDisplayData(data);
|
||||
const flwmtrInstTp =
|
||||
data.flwmtrInstTp === "R"
|
||||
? "이동식"
|
||||
: data.flwmtrInstTp === "S"
|
||||
? "고정식"
|
||||
: "-";
|
||||
const flwmtrMesureTp =
|
||||
data.flwmtrMesureTp === "R"
|
||||
? "레이더"
|
||||
: data.flwmtrMesureTp === "P"
|
||||
? "플륨"
|
||||
: data.flwmtrMesureTp === "U"
|
||||
? "초음파"
|
||||
: data.flwmtrMesureTp === "E"
|
||||
? "기타"
|
||||
: "-";
|
||||
const flwmtrCombined = `${flwmtrInstTp}, ${flwmtrMesureTp}`;
|
||||
// 🎯 추가 데이터 조합
|
||||
return {
|
||||
...formattedItem,
|
||||
rainInfo: `${data.rainInfo === "0" ? "강우량계" : data.observatory || "-"}`, // 강우정보 0: 강우량계,1: 관측기관 이면 OBSERVATORY 이값사용
|
||||
mesureIntrvl: `${data.mesureIntrvlGbn === "1" ? "1분" : data.mesureIntrvlGbn === "0" ? data.mesureIntrvl + "분" : "-"}`, // 측정간격
|
||||
flwmtrCombined: `${flwmtrCombined} / ${data.flwmtrKnd || "-"}`, // 유량계종류 및 모델명
|
||||
mesureBeginDt: data.mesureBeginDt
|
||||
? formatNoYearNoSec(data.mesureBeginDt)
|
||||
: "-", // 수량 측정시작일
|
||||
mesureEndDt: data.mesureEndDt
|
||||
? formatNoYearNoSec(data.mesureEndDt)
|
||||
: "-", // 수량 측정종료일
|
||||
qltwtrBeginDt: data.qltwtrBeginDt
|
||||
? formatNoYearNoSec(data.qltwtrBeginDt)
|
||||
: "-", // 수질 측정시작일(채수시작일)
|
||||
qltwtrEndDt: data.qltwtrEndDt
|
||||
? formatNoYearNoSec(data.qltwtrEndDt)
|
||||
: "-", // 수질 측정종료일(채수종료일)
|
||||
};
|
||||
});
|
||||
setRainMeasureData(processedDataArray);
|
||||
setTotalCount(result?.totalElements || 0);
|
||||
} catch (error) {
|
||||
if (sequence !== rainRequestSequence.current) return [];
|
||||
console.error("추가 데이터 로딩 실패:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// 수량/수질측정 정보 API 호출 함수
|
||||
const fetchMntrngsData = async (adstDstrCd: string, manageNo: string) => {
|
||||
const sequence = ++monitoringRequestSequence.current;
|
||||
if (!adstDstrCd || !manageNo) {
|
||||
console.warn("추가 데이터 호출 실패: 필수 매개변수 누락", {
|
||||
adstDstrCd,
|
||||
manageNo,
|
||||
});
|
||||
return [];
|
||||
}
|
||||
|
||||
try {
|
||||
const queryParams = new URLSearchParams({
|
||||
page: `${curDetailPage - 1}`,
|
||||
size: "3",
|
||||
});
|
||||
|
||||
const result = await getRawJson(
|
||||
`/sewerage-service/api/v1/onsemiro/swgRain/${adstDstrCd}/${manageNo}/mntrngs?${queryParams.toString()}`,
|
||||
);
|
||||
if (sequence !== monitoringRequestSequence.current) return [];
|
||||
|
||||
// 각 아이템 전처리
|
||||
const processedDataArray = result.content.map((data: any) => {
|
||||
// 기본 포맷팅 적용
|
||||
const formattedItem = formatDisplayData(data);
|
||||
return {
|
||||
...formattedItem,
|
||||
};
|
||||
});
|
||||
|
||||
setMntrngsData(processedDataArray);
|
||||
setTotalDetailCount(result?.totalElements || 0);
|
||||
} catch (error) {
|
||||
if (sequence !== monitoringRequestSequence.current) return [];
|
||||
console.error("추가 데이터 로딩 실패:", error);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
// 🎯 추가 데이터는 별도 useEffect로 비동기 로딩
|
||||
useEffect(() => {
|
||||
// 강우/측정 정보 데이터 호출
|
||||
if (isMainSsc && chmbrXcnts && chmbrYdnts) {
|
||||
fetchRainMeasureData(chmbrXcnts, chmbrYdnts);
|
||||
}
|
||||
}, [chmbrXcnts, chmbrYdnts]);
|
||||
|
||||
const openDetailPopup = () => {
|
||||
const popupWindow = openWindowPopup("sscDetail", {
|
||||
chmbrXcnts,
|
||||
chmbrYdnts,
|
||||
sourcePath: window.location.pathname,
|
||||
});
|
||||
|
||||
if (!popupWindow) {
|
||||
alert("팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.");
|
||||
}
|
||||
};
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
if (featureData) {
|
||||
setFormData(featureData);
|
||||
setMntrngsData([]);
|
||||
}
|
||||
}, [featureData]);
|
||||
|
||||
// featureData가 변경될 때 formData 초기화
|
||||
useEffect(() => {
|
||||
// showTable이 true일 때만 fetch (최초 렌더 방지)
|
||||
setSelectedRowIndex(-1);
|
||||
if (chmbrXcnts && chmbrYdnts) fetchRainMeasureData(chmbrXcnts, chmbrYdnts);
|
||||
}, [curPage]);
|
||||
|
||||
// 페이지 변경 시마다 데이터 fetch
|
||||
useEffect(() => {
|
||||
if (chmbrXcnts && chmbrYdnts && selectedRowIndex !== -1)
|
||||
fetchMntrngsData(
|
||||
rainMeasureData[selectedRowIndex].adstDstrCd,
|
||||
rainMeasureData[selectedRowIndex].manageNo,
|
||||
);
|
||||
}, [curDetailPage]);
|
||||
|
||||
// 폼 데이터가 변경될 때 호출될 핸들러
|
||||
const handleFormDataChange = (newFormData: any) => {
|
||||
setFormData(newFormData);
|
||||
};
|
||||
|
||||
// 저장 버튼 클릭 시 최신 formData를 부모에게 전달
|
||||
const handleSaveClick = () => {
|
||||
if (onSaveClick) {
|
||||
// 저장 전에 formData를 부모 컴포넌트의 handleSaveClick에 전달
|
||||
onSaveClick();
|
||||
}
|
||||
};
|
||||
|
||||
// 테이블 셀 클릭 핸들러 추가
|
||||
const handleCellClick = async (
|
||||
_row: Record<string, unknown>,
|
||||
index: number,
|
||||
) => {
|
||||
if (rainMeasureData[index]) {
|
||||
setSelectedRowIndex(index);
|
||||
await fetchMntrngsData(
|
||||
rainMeasureData[index].adstDstrCd,
|
||||
rainMeasureData[index].manageNo,
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const renderModalBody = () => (
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
<div className="space-y-4">
|
||||
{/* 강우정보 테이블 */}
|
||||
<MapPopupDataTable
|
||||
title="강우정보 목록"
|
||||
rows={rainMeasureData}
|
||||
headlist={toStandardHeadList(untrtSwgRainCol3)}
|
||||
pageSize={3}
|
||||
total={totalCount}
|
||||
page={curPage}
|
||||
onCellClick={handleCellClick}
|
||||
onPageChange={setCurPage}
|
||||
viewPagination={false}
|
||||
scrollMode="horizontal"
|
||||
minTableWidth="72rem"
|
||||
/>
|
||||
|
||||
{/* 측정정보 테이블 */}
|
||||
<MapPopupDataTable
|
||||
title="측정정보 목록"
|
||||
rows={rainMeasureData}
|
||||
headlist={toStandardHeadList(untrtSwgRainCol4)}
|
||||
pageSize={3}
|
||||
total={totalCount}
|
||||
page={curPage}
|
||||
onCellClick={handleCellClick}
|
||||
onPageChange={setCurPage}
|
||||
scrollMode="horizontal"
|
||||
minTableWidth="88rem"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{/* 수량/수질측정 정보 테이블 */}
|
||||
<MapPopupDataTable
|
||||
title="수량·수질측정 목록"
|
||||
rows={mntrngsData}
|
||||
headlist={toStandardHeadList(untrtSwgRainCol5)}
|
||||
pageSize={3}
|
||||
total={totalDetailCount}
|
||||
page={curDetailPage}
|
||||
onPageChange={setCurDetailPage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{!isMainSsc && (
|
||||
<VerticalTable
|
||||
headName="입력정보"
|
||||
tableData={featureData ? [formData] : []}
|
||||
headlist={inputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
showSaveButton={true}
|
||||
onSaveClick={handleSaveClick}
|
||||
onFormDataChange={handleFormDataChange} // 폼 데이터 변경 콜백 추가
|
||||
/>
|
||||
)}
|
||||
|
||||
{isMainSsc && renderMode !== "popup" && (
|
||||
<div>
|
||||
<div className="card-header">
|
||||
<h3 className="mx-3 text-2xl font-medium text-label">
|
||||
중점우수토실 운영정보
|
||||
</h3>
|
||||
</div>
|
||||
<Button
|
||||
className="mx-auto mt-3 block w-64"
|
||||
color="white"
|
||||
onClick={openDetailPopup}
|
||||
>
|
||||
상세보기
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isMainSsc && renderMode === "popup" && (
|
||||
<StandardPopupLayout title="중점우수토실 운영정보">
|
||||
{renderModalBody()}
|
||||
</StandardPopupLayout>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Ssc;
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* 화면명: 빗물펌프 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (빗물펌프)
|
||||
*
|
||||
* 📄 StormWaterPump
|
||||
* 빗물펌프 정보 컴포넌트
|
||||
*
|
||||
* - 빗물펌프의 자체입력정보 표시 및 편집 기능
|
||||
* - VerticalTable을 통한 입력 폼 렌더링
|
||||
*/
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import React from "react";
|
||||
const inputColumn = [
|
||||
{ id: "swtrmtZoneNm", title: "처리구역", type: "input" },
|
||||
{ id: "mltvDtdvNm", title: "배수분구", type: "input" },
|
||||
];
|
||||
// 빗물펌프
|
||||
const StormWaterPump = ({
|
||||
featureData,
|
||||
}: {
|
||||
featureData: Record<string, any>;
|
||||
}) => {
|
||||
const validKey = inputColumn.map((item) => item.id);
|
||||
const filteredData =
|
||||
featureData &&
|
||||
Object.entries(featureData)
|
||||
.filter(([key]) => validKey.includes(key))
|
||||
.reduce((obj: Record<string, any>, [key, value]) => {
|
||||
obj[key] = value;
|
||||
return obj;
|
||||
}, {});
|
||||
return (
|
||||
<VerticalTable
|
||||
headName="입력정보"
|
||||
tableData={[filteredData]}
|
||||
headlist={inputColumn}
|
||||
pageSize={0}
|
||||
total={0}
|
||||
children={undefined}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
export default StormWaterPump;
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* 화면명: 하수처리시설 정보
|
||||
* ➡️ 경로 : 하수관망도 메인 페이지 (시설물 클릭) - 오른쪽 팝업창 (하수처리시설)
|
||||
*
|
||||
* 📄 SwtrmtFclt
|
||||
* 하수처리시설 정보 컴포넌트
|
||||
*
|
||||
* - 하수처리시설의 디지털 자료관 연계 정보 표시
|
||||
* - VerticalTable을 통한 테이블 렌더링
|
||||
* - 조회 버튼을 통한 모달 표시 및 ReportTab 연동
|
||||
*/
|
||||
"use client";
|
||||
import React from "react";
|
||||
import { VerticalTable } from "@/components/ui/vertical-table";
|
||||
import { Button } from "@common/components/ui";
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
|
||||
// 하수처리시설
|
||||
const headList = [{ id: "title", title: "하수도정비 기본계획보고서" }];
|
||||
|
||||
const SwtrmtFclt = ({ gisObject }: { gisObject: any }) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const ctpvNm = gisObject?.ctpv_nm;
|
||||
const sggNm = gisObject?.sgg_nm;
|
||||
|
||||
const handleOpenReportPopup = () => {
|
||||
const popupWindow = openWindowPopup("reportTab", {
|
||||
ctpvNm,
|
||||
sggNm,
|
||||
sourcePath: window.location.pathname,
|
||||
});
|
||||
|
||||
if (!popupWindow) {
|
||||
alert("팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<VerticalTable
|
||||
children={{
|
||||
title: (
|
||||
<Button className="gray" onClick={handleOpenReportPopup}>
|
||||
조회
|
||||
</Button>
|
||||
),
|
||||
}}
|
||||
headName="디지털 자료관 연계정보"
|
||||
tableData={[]}
|
||||
headlist={headList}
|
||||
pageSize={20}
|
||||
total={0}
|
||||
cellClick={undefined}
|
||||
isEditable={true}
|
||||
onPageChange={function (page: number): void {
|
||||
throw new Error("Function not implemented.");
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default SwtrmtFclt;
|
||||
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* 화면명: 처리구역내 관로분석정보
|
||||
* 선택한 하수처리구역의 관로 분석 현황과 보수이력 연계 기능을 제공한다.
|
||||
*/
|
||||
"use client";
|
||||
|
||||
import React, {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
Button,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableRow,
|
||||
} from "@common/components";
|
||||
import { useGisContext } from "@common/business_components/ui/map/Gis";
|
||||
import Feature from "ol/Feature.js";
|
||||
import GeoJSON from "ol/format/GeoJSON.js";
|
||||
import VectorLayer from "ol/layer/Vector.js";
|
||||
import VectorSource from "ol/source/Vector.js";
|
||||
import Stroke from "ol/style/Stroke.js";
|
||||
import Style from "ol/style/Style.js";
|
||||
|
||||
import { openWindowPopup } from "@/features/window-popup/lib/open-window-popup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import {
|
||||
fetchSwtrmtPrcsZoneAnalysis,
|
||||
getSwtrmtPrcsZoneId,
|
||||
} from "@/features/facility-detail/api/treatment-zone-api";
|
||||
import type {
|
||||
RepairHistoryMapFeature,
|
||||
SwtrmtPrcsZoneAnalysisMetric,
|
||||
SwtrmtPrcsZoneAnalysisResponse,
|
||||
} from "@/features/facility-detail/api/treatment-zone-api";
|
||||
|
||||
const analysisRows: {
|
||||
key: keyof NonNullable<SwtrmtPrcsZoneAnalysisResponse["analysis"]>;
|
||||
title: string;
|
||||
}[] = [
|
||||
{ key: "total", title: "전체" },
|
||||
{ key: "combined", title: "합류관" },
|
||||
{ key: "rain", title: "우수관" },
|
||||
{ key: "sewage", title: "오수관" },
|
||||
];
|
||||
|
||||
const repairHistoryStyle = new Style({
|
||||
stroke: new Stroke({ color: "rgba(0, 229, 255, 0.95)", width: 5 }),
|
||||
zIndex: 10020,
|
||||
});
|
||||
|
||||
const selectedRepairHistoryStyle = new Style({
|
||||
stroke: new Stroke({ color: "rgba(255, 82, 82, 1)", width: 8 }),
|
||||
zIndex: 10021,
|
||||
});
|
||||
|
||||
const formatValue = (value: unknown, unit = "") => {
|
||||
if (value === null || value === undefined || value === "")
|
||||
return "데이터 없음";
|
||||
|
||||
const numberValue =
|
||||
typeof value === "number"
|
||||
? value
|
||||
: Number(String(value).replaceAll(",", ""));
|
||||
if (!Number.isNaN(numberValue) && Number.isFinite(numberValue)) {
|
||||
const formatted = numberValue.toLocaleString("ko-KR", {
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return unit ? `${formatted}${unit}` : formatted;
|
||||
}
|
||||
|
||||
return String(value);
|
||||
};
|
||||
|
||||
const getMetric = (
|
||||
analysis: SwtrmtPrcsZoneAnalysisResponse["analysis"] | undefined,
|
||||
key: keyof NonNullable<SwtrmtPrcsZoneAnalysisResponse["analysis"]>,
|
||||
): SwtrmtPrcsZoneAnalysisMetric => analysis?.[key] ?? {};
|
||||
|
||||
const metricGroups: {
|
||||
title: string;
|
||||
field: keyof SwtrmtPrcsZoneAnalysisMetric;
|
||||
}[] = [
|
||||
{ title: "평균경과년도(년)", field: "avgInstlYear" },
|
||||
{ title: "최장경과년도(년)", field: "oldestInstlYear" },
|
||||
{ title: "최신경과년도(년)", field: "latestInstlYear" },
|
||||
];
|
||||
|
||||
const MetricVerticalGrid = ({
|
||||
title,
|
||||
field,
|
||||
analysis,
|
||||
}: {
|
||||
title: string;
|
||||
field: keyof SwtrmtPrcsZoneAnalysisMetric;
|
||||
analysis: SwtrmtPrcsZoneAnalysisResponse["analysis"] | undefined;
|
||||
}) => (
|
||||
<div className="mb-4 last:mb-0">
|
||||
<div className="mx-3 mb-2 mt-1 text-xl font-medium text-label">{title}</div>
|
||||
<Table variant="secondary">
|
||||
<TableBody className="text-center">
|
||||
{analysisRows.map((row) => {
|
||||
const metric = getMetric(analysis, row.key);
|
||||
return (
|
||||
<TableRow key={`${title}-${row.key}`}>
|
||||
<TableCell className="w-[120px] whitespace-nowrap bg-secondary text-[13px] font-bold text-label">
|
||||
{row.title}
|
||||
</TableCell>
|
||||
<TableCell className="text-[13px]">
|
||||
{formatValue(metric[field])}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
|
||||
/** 처리구역 분석 패널과 보수이력 윈도우 팝업의 부모 지도 연계를 담당한다. */
|
||||
const SwtrmtPrcsZoneAnalysis = ({
|
||||
featureData,
|
||||
rawFeatureData,
|
||||
}: {
|
||||
featureData: any;
|
||||
rawFeatureData?: any;
|
||||
}) => {
|
||||
const alert = useAlertStore((state) => state.setMessage);
|
||||
const { gisMap } = useGisContext() as unknown as { gisMap: any };
|
||||
// 기존 처리구역 관로분석 정보의 조회 상태다.
|
||||
const [analysisData, setAnalysisData] =
|
||||
useState<SwtrmtPrcsZoneAnalysisResponse | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
// 보수이력 지도 레이어는 React 렌더링 대상이 아니므로 ref로 보관해 팝업 종료·구역 전환 때 제거한다.
|
||||
const repairLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
|
||||
const repairPopupRef = useRef<Window | null>(null);
|
||||
// 목록이 먼저 표시되어도 지도 도형 준비 후 마지막으로 클릭한 관로로 이동한다.
|
||||
const pendingRepairFidRef = useRef("");
|
||||
|
||||
const requestKey = useMemo(() => {
|
||||
const rawValues = rawFeatureData?.values_ ?? rawFeatureData ?? {};
|
||||
return [
|
||||
rawFeatureData?.getId?.(),
|
||||
rawFeatureData?.id_,
|
||||
rawFeatureData?.fid,
|
||||
rawValues?.fid,
|
||||
featureData?.fid,
|
||||
rawValues?.swtrmt_fclt_cd,
|
||||
rawValues?.swtrmtFcltCd,
|
||||
featureData?.swtrmt_fclt_cd,
|
||||
featureData?.swtrmtFcltCd,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("|");
|
||||
}, [featureData, rawFeatureData]);
|
||||
|
||||
const zoneId = useMemo(
|
||||
() => getSwtrmtPrcsZoneId(rawFeatureData, featureData),
|
||||
[featureData, rawFeatureData, requestKey],
|
||||
);
|
||||
|
||||
/** 이전 보수이력 조회에서 만든 임시 벡터 레이어를 제거한다. */
|
||||
const clearRepairLayer = useCallback(() => {
|
||||
const layer = repairLayerRef.current;
|
||||
if (layer && gisMap) gisMap.removeLayer(layer);
|
||||
layer?.getSource()?.clear();
|
||||
repairLayerRef.current = null;
|
||||
}, [gisMap]);
|
||||
|
||||
/** 윈도우 팝업 조회 결과 전체를 청록색 관로 레이어로 교체한다. */
|
||||
const replaceRepairLayer = useCallback(
|
||||
(rows: RepairHistoryMapFeature[]) => {
|
||||
if (!gisMap) return;
|
||||
clearRepairLayer();
|
||||
|
||||
const format = new GeoJSON();
|
||||
const projection = gisMap.getView()?.getProjection();
|
||||
const features = rows.flatMap((row) => {
|
||||
if (!row.geometryJson) return [];
|
||||
try {
|
||||
const geometry = format.readGeometry(JSON.parse(row.geometryJson), {
|
||||
dataProjection: "EPSG:3857",
|
||||
featureProjection: projection,
|
||||
});
|
||||
const feature = new Feature({ geometry, repairFid: row.fid });
|
||||
feature.setId(`repair-history-${row.fid}`);
|
||||
return [feature];
|
||||
} catch (error) {
|
||||
console.warn("보수이력 관로 도형을 읽지 못했습니다.", row.fid, error);
|
||||
return [];
|
||||
}
|
||||
});
|
||||
|
||||
if (features.length === 0) return;
|
||||
const layer = new VectorLayer({
|
||||
source: new VectorSource({ features }),
|
||||
style: (feature) =>
|
||||
feature.get("repairSelected")
|
||||
? selectedRepairHistoryStyle
|
||||
: repairHistoryStyle,
|
||||
});
|
||||
layer.set("repairHistoryLayer", true);
|
||||
layer.setZIndex(10020);
|
||||
gisMap.addLayer(layer);
|
||||
repairLayerRef.current = layer;
|
||||
},
|
||||
[clearRepairLayer, gisMap],
|
||||
);
|
||||
|
||||
/** 팝업에서 클릭한 관로를 붉게 선택하고 부모 지도를 해당 범위로 이동한다. */
|
||||
const focusRepairFeature = useCallback(
|
||||
(fid: string) => {
|
||||
const features = repairLayerRef.current?.getSource()?.getFeatures() ?? [];
|
||||
const selectedFeature = features.find(
|
||||
(feature) => String(feature.get("repairFid")) === String(fid),
|
||||
);
|
||||
if (!selectedFeature || !gisMap) return;
|
||||
|
||||
features.forEach((feature) =>
|
||||
feature.set("repairSelected", feature === selectedFeature),
|
||||
);
|
||||
repairLayerRef.current?.changed();
|
||||
const extent = selectedFeature.getGeometry()?.getExtent();
|
||||
if (extent) {
|
||||
gisMap.getView().fit(extent, {
|
||||
padding: [100, 100, 100, 460],
|
||||
duration: 350,
|
||||
maxZoom: 18,
|
||||
});
|
||||
}
|
||||
},
|
||||
[gisMap],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
setIsLoading(true);
|
||||
setErrorMessage("");
|
||||
|
||||
const loadAnalysis = async () => {
|
||||
try {
|
||||
const data = await fetchSwtrmtPrcsZoneAnalysis(
|
||||
rawFeatureData,
|
||||
featureData,
|
||||
);
|
||||
if (!isMounted) return;
|
||||
if (!data) {
|
||||
setAnalysisData(null);
|
||||
setErrorMessage(
|
||||
"처리구역 식별값이 없어 관로분석정보를 조회하지 못했습니다.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
setAnalysisData(data);
|
||||
} catch (error) {
|
||||
if (!isMounted) return;
|
||||
setAnalysisData(null);
|
||||
setErrorMessage(
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "관로분석정보를 불러오지 못했습니다.",
|
||||
);
|
||||
} finally {
|
||||
if (isMounted) setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
void loadAnalysis();
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [featureData, rawFeatureData, requestKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleRepairPopupMessage = (event: MessageEvent) => {
|
||||
if (event.origin !== window.location.origin) return;
|
||||
const data = event.data;
|
||||
const messageZoneId = String(data?.payload?.zoneId ?? "").trim();
|
||||
if (!messageZoneId || messageZoneId !== zoneId) return;
|
||||
|
||||
if (
|
||||
data?.type === WINDOW_POPUP_MESSAGE_TYPE.REPAIR_HISTORY_SHOW_RESULTS
|
||||
) {
|
||||
const features = Array.isArray(data.payload?.rows)
|
||||
? data.payload.rows
|
||||
: [];
|
||||
if (features.length === 0) pendingRepairFidRef.current = "";
|
||||
replaceRepairLayer(features);
|
||||
if (pendingRepairFidRef.current)
|
||||
focusRepairFeature(pendingRepairFidRef.current);
|
||||
return;
|
||||
}
|
||||
if (data?.type === WINDOW_POPUP_MESSAGE_TYPE.REPAIR_HISTORY_SELECT_PIPE) {
|
||||
pendingRepairFidRef.current = String(data.payload?.fid ?? "");
|
||||
focusRepairFeature(pendingRepairFidRef.current);
|
||||
return;
|
||||
}
|
||||
if (data?.type === WINDOW_POPUP_MESSAGE_TYPE.REPAIR_HISTORY_CLEAR) {
|
||||
pendingRepairFidRef.current = "";
|
||||
clearRepairLayer();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", handleRepairPopupMessage);
|
||||
return () =>
|
||||
window.removeEventListener("message", handleRepairPopupMessage);
|
||||
}, [clearRepairLayer, focusRepairFeature, replaceRepairLayer, zoneId]);
|
||||
|
||||
useEffect(() => {
|
||||
clearRepairLayer();
|
||||
}, [clearRepairLayer, requestKey]);
|
||||
|
||||
useEffect(() => () => clearRepairLayer(), [clearRepairLayer]);
|
||||
|
||||
useEffect(() => {
|
||||
const timerId = window.setInterval(() => {
|
||||
if (repairPopupRef.current?.closed) {
|
||||
repairPopupRef.current = null;
|
||||
clearRepairLayer();
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => window.clearInterval(timerId);
|
||||
}, [clearRepairLayer]);
|
||||
|
||||
/** 선택 처리구역을 고정한 기존 공통 윈도우 팝업을 연다. */
|
||||
const handleOpenRepairHistory = () => {
|
||||
if (!zoneId) {
|
||||
setErrorMessage("처리구역 식별값이 없어 보수이력을 열 수 없습니다.");
|
||||
return;
|
||||
}
|
||||
|
||||
clearRepairLayer();
|
||||
const popup = openWindowPopup("repairHistoryPopup", {
|
||||
zoneId,
|
||||
zoneName:
|
||||
analysisData?.zone?.swtrmtZoneNm ??
|
||||
featureData?.swtrmt_zone_nm ??
|
||||
featureData?.swtrmtZoneNm,
|
||||
});
|
||||
if (!popup) {
|
||||
alert("팝업이 차단되었습니다. 브라우저 팝업 허용 설정을 확인해주세요.");
|
||||
return;
|
||||
}
|
||||
repairPopupRef.current = popup;
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="card-header flex items-center justify-between">
|
||||
<h3 className="mx-3 text-2xl font-medium text-label">
|
||||
처리구역내 관로분석정보
|
||||
</h3>
|
||||
<Button
|
||||
type="button"
|
||||
className="hover:bg-primary/90 mr-3 bg-primary text-primary-foreground"
|
||||
onClick={handleOpenRepairHistory}
|
||||
data-testid="repair-history-open"
|
||||
>
|
||||
보수이력
|
||||
</Button>
|
||||
</div>
|
||||
<div className="card !mx-[1.2rem] !mb-[1.2rem] !mt-1 !p-0">
|
||||
<div className="px-3 pb-3 pt-1">
|
||||
{errorMessage ? (
|
||||
<div className="mb-3 rounded border border-red-200 bg-red-50 px-3 py-2 text-[13px] text-red-700">
|
||||
{errorMessage}
|
||||
</div>
|
||||
) : null}
|
||||
{isLoading ? (
|
||||
<div
|
||||
role="status"
|
||||
className="flex min-h-[12rem] items-center justify-center rounded-md border border-border bg-background text-[1.2rem] text-muted-foreground"
|
||||
>
|
||||
관로분석정보를 조회하고 있습니다.
|
||||
</div>
|
||||
) : (
|
||||
metricGroups.map((group) => (
|
||||
<MetricVerticalGrid
|
||||
key={group.title}
|
||||
title={group.title}
|
||||
field={group.field}
|
||||
analysis={analysisData?.analysis}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default SwtrmtPrcsZoneAnalysis;
|
||||
+8
-8
@@ -8,16 +8,16 @@ import {
|
||||
} from "@common/business_components";
|
||||
import { Button } from "@common/components";
|
||||
|
||||
import { getData, getRawJson } from "@/components/lib/api";
|
||||
import { getData, getRawJson } from "@/shared/api/sewerage-api";
|
||||
import { appendApiSearchParams } from "@/shared/util/util";
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { windowPopupDefinitions } from "@/features/windowPopup/model/popupDefinitions";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
import MapPopupDataTable from "@/features/windowPopup/ui/MapPopupDataTable";
|
||||
import PopupSearchPanel from "@/features/windowPopup/ui/PopupSearchPanel";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { windowPopupDefinitions } from "@/features/window-popup/model/popup-definitions";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import MapPopupDataTable from "@/features/window-popup/ui/map-popup-data-table";
|
||||
import PopupSearchPanel from "@/features/window-popup/ui/popup-search-panel";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import useStore from "@/store/useStore";
|
||||
import { createPredictionAnalysisTimeRange } from "../model/analysisTimeRange";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import { createPredictionAnalysisTimeRange } from "../model/analysis-time-range";
|
||||
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
|
||||
import { downloadFloodPredictionStatusExcel } from "../lib/fldng-predc-prst-excel";
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/windowPopup/model/types";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "@/features/window-popup/model/types";
|
||||
import type { GisUploadResponse } from "../model/upload-types";
|
||||
/** 성공한 GIS 업로드의 기존 refresh 메시지를 opener에 전달한다. */
|
||||
export const postRefreshMessageToOpener = (response: GisUploadResponse) => {
|
||||
@@ -0,0 +1,76 @@
|
||||
import {
|
||||
FLOW_DIRECTION_DEFAULT_COLOR,
|
||||
type FlowDirectionUsageStyle,
|
||||
withAlpha,
|
||||
} from "./flow-direction-styles";
|
||||
import {
|
||||
getLayerTypeName,
|
||||
isFlowDirectionLayerInfo,
|
||||
getFiniteNumber,
|
||||
} from "./layer-info";
|
||||
import { FLOW_DIRECTION_PIPE_LAYER_TYPE } from "../model/flow-direction-runtime";
|
||||
|
||||
/** 지도 체크 노드에서 유하방향 관종/스타일을 선택하는 순수 변환. */
|
||||
// 레이어 설정의 직접 코드와 filterSql 안의 usg_cd 조건을 모두 관종 코드 후보로 해석한다.
|
||||
export const extractUsageCodesFromLayerInfo = (layerInfo: any) => {
|
||||
const usageCodes = new Set<string>();
|
||||
const directCode = layerInfo?.usgCd ?? layerInfo?.usg_cd;
|
||||
if (directCode) usageCodes.add(String(directCode).trim());
|
||||
|
||||
const filterSql = String(layerInfo?.flterSql ?? layerInfo?.filterSql ?? "");
|
||||
const equalsMatches = filterSql.matchAll(/usg_cd\s*=\s*'([^']+)'/gi);
|
||||
for (const match of equalsMatches) {
|
||||
const code = match[1]?.trim();
|
||||
if (code) usageCodes.add(code);
|
||||
}
|
||||
|
||||
const inMatches = filterSql.matchAll(/usg_cd\s+in\s*\(([^)]+)\)/gi);
|
||||
for (const match of inMatches) {
|
||||
const codeList = match[1];
|
||||
if (!codeList) continue;
|
||||
|
||||
codeList
|
||||
.split(",")
|
||||
.map((item) => item.replace(/'/g, "").trim())
|
||||
.filter(Boolean)
|
||||
.forEach((code) => usageCodes.add(code));
|
||||
}
|
||||
|
||||
return Array.from(usageCodes);
|
||||
};
|
||||
|
||||
// 현재 줌에서 실제 표출 가능한 관로 레이어인지 확인해 숨겨진 관종의 유하방향 요청을 막는다.
|
||||
export const isLayerVisibleAtZoom = (layerInfo: any, zoom: number) => {
|
||||
const minZoom = getFiniteNumber(layerInfo?.minViewSize ?? layerInfo?.minZoom);
|
||||
return minZoom === null || zoom >= minZoom;
|
||||
};
|
||||
|
||||
// 현재 체크되어 화면에 보이는 관로 레이어의 관종 코드와 선 색상을 유하방향 조회/스타일 기준으로 변환한다.
|
||||
export const extractCheckedPipeUsageStyles = (
|
||||
checkedNodesData: any[],
|
||||
zoom: number,
|
||||
) => {
|
||||
const usageStyleMap: Record<string, FlowDirectionUsageStyle> = {};
|
||||
|
||||
checkedNodesData.forEach((node) => {
|
||||
const data = node?.data ?? node;
|
||||
if (!data || isFlowDirectionLayerInfo(data)) return;
|
||||
if (getLayerTypeName(data) !== FLOW_DIRECTION_PIPE_LAYER_TYPE) return;
|
||||
if (!isLayerVisibleAtZoom(data, zoom)) return;
|
||||
|
||||
const usageCodes = extractUsageCodesFromLayerInfo(data);
|
||||
if (usageCodes.length === 0) return;
|
||||
|
||||
const layerColor = String(
|
||||
data.lnColor ?? data.lineColor ?? FLOW_DIRECTION_DEFAULT_COLOR,
|
||||
).trim();
|
||||
usageCodes.forEach((code) => {
|
||||
usageStyleMap[code] = {
|
||||
color: layerColor,
|
||||
lineColor: withAlpha(layerColor, 0.28),
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
return usageStyleMap;
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
/** 지도 API의 래퍼/raw GeoJSON 응답을 같은 feature collection으로 읽는다. */
|
||||
// BE 응답이 FeatureCollection 그대로 오거나 공통 응답 wrapper의 data 안에 들어오는 두 계약을 모두 처리한다.
|
||||
export const getFeatureCollection = (payload: any) => {
|
||||
if (payload?.type === "FeatureCollection") return payload;
|
||||
if (payload?.data?.type === "FeatureCollection") return payload.data;
|
||||
return { type: "FeatureCollection", features: [] };
|
||||
};
|
||||
@@ -0,0 +1,518 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type MutableRefObject,
|
||||
} from "react";
|
||||
import GeoJSON from "ol/format/GeoJSON.js";
|
||||
import VectorLayer from "ol/layer/Vector.js";
|
||||
import VectorSource from "ol/source/Vector.js";
|
||||
import { unByKey } from "ol/Observable.js";
|
||||
import GisApp from "@common/business_components/ui/map/lib/gis.core";
|
||||
import { getRawJson } from "@/shared/api/sewerage-api";
|
||||
import {
|
||||
FLOW_DIRECTION_LAYER_TYPE,
|
||||
FLOW_DIRECTION_LAYER_NAME,
|
||||
getFlowDirectionMinZoom,
|
||||
getFlowDirectionZIndex,
|
||||
expandFlowDirectionExtent,
|
||||
formatFlowDirectionBbox,
|
||||
getFlowDirectionFeatureCacheKey,
|
||||
getFlowDirectionModeByPathname,
|
||||
} from "./layer-info";
|
||||
import { subscribeFlowDirectionMoveEnd } from "./flow-direction-listener";
|
||||
import {
|
||||
createFlowDirectionStyle,
|
||||
type FlowDirectionUsageStyle,
|
||||
} from "./flow-direction-styles";
|
||||
import { FLOW_DIRECTION_SRS } from "../model/flow-direction-runtime";
|
||||
import { getFeatureCollection } from "./geojson-response";
|
||||
import { extractCheckedPipeUsageStyles } from "./flow-direction-selection";
|
||||
import { isFlowDirectionLayerInfo } from "./layer-info";
|
||||
|
||||
type FlowDirectionOptions = {
|
||||
gisMaps: MutableRefObject<any>;
|
||||
checkedNodesDataRef: MutableRefObject<any[]>;
|
||||
mapReady: boolean;
|
||||
flowDirectionMode: ReturnType<typeof getFlowDirectionModeByPathname>;
|
||||
};
|
||||
|
||||
/** 유하방향의 요청·캐시·레이어·이벤트 수명을 소유한다. 외부에는 선택 명령과 표시 상태만 제공한다. */
|
||||
export function useFlowDirectionLayer({
|
||||
gisMaps,
|
||||
checkedNodesDataRef,
|
||||
mapReady,
|
||||
flowDirectionMode,
|
||||
}: FlowDirectionOptions) {
|
||||
// 유하방향 레이어 체크 여부를 React 렌더링 흐름에 반영하기 위한 state이다.
|
||||
const [isFlowDirectionChecked, setIsFlowDirectionChecked] = useState(false);
|
||||
|
||||
// 체크된 유하방향 트리 노드의 레이어 설정을 보관해 API 조회와 vector layer 스타일에 사용한다.
|
||||
const [flowDirectionLayerInfo, setFlowDirectionLayerInfo] = useState<
|
||||
any | null
|
||||
>(null);
|
||||
|
||||
// 관종 레이어 체크 변경도 유하방향 재조회 조건이므로 별도 버전 state로 effect를 다시 실행한다.
|
||||
const [flowDirectionSelectionVersion, setFlowDirectionSelectionVersion] =
|
||||
useState(0);
|
||||
|
||||
// moveend 이벤트 핸들러는 최신 state closure를 보장하지 않으므로 현재 체크 여부를 ref로 함께 보관한다.
|
||||
const flowDirectionCheckedRef = useRef(false);
|
||||
|
||||
// 지도 이동 후 재조회할 때 최신 유하방향 레이어 설정을 참조하기 위한 ref이다.
|
||||
const flowDirectionLayerInfoRef = useRef<any | null>(null);
|
||||
|
||||
// 유하방향 전용 vector layer/source를 유지해 지도 이동 시 기존 피처를 지우지 않고 새 BBOX 응답만 병합한다.
|
||||
const flowDirectionLayerRef = useRef<any | null>(null);
|
||||
|
||||
const flowDirectionSourceRef = useRef<VectorSource | null>(null);
|
||||
|
||||
// 같은 관로가 겹치는 BBOX에서 반복 조회될 수 있으므로 고유키와 삽입 순서를 캐시로 관리한다.
|
||||
const flowDirectionFeatureKeySetRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const flowDirectionFeatureKeyQueueRef = useRef<string[]>([]);
|
||||
|
||||
// 관종 체크 변경 시 다른 관종 유하방향을 유지하기 위해 현재 source에 남겨둘 관종 코드를 별도로 추적한다.
|
||||
const flowDirectionVisibleUsageCodesRef = useRef<Set<string>>(new Set());
|
||||
|
||||
// 관종 체크 변경으로 새로 켜진 usgCd만 다음 조회 대상으로 넘겨 기존 관종 재요청을 막는다.
|
||||
const flowDirectionSelectionRequestUsageCodesRef = useRef<string[] | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// 체크 해제나 재조회 중 늦게 도착한 이전 API 응답이 레이어를 다시 그리지 못하도록 요청 순번을 관리한다.
|
||||
const flowDirectionRequestSeqRef = useRef(0);
|
||||
|
||||
// 지도 이동이 연속으로 발생하면 이전 유하방향 요청을 중단해 늦은 응답과 불필요한 네트워크 대기를 줄인다.
|
||||
const flowDirectionAbortControllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
// 같은 장애 상황에서 alert가 반복 노출되지 않도록 실패 안내 여부를 기억한다.
|
||||
const flowDirectionFailureAlertedRef = useRef(false);
|
||||
|
||||
// 유하방향은 일반 Gis core 레이어 등록 흐름을 타지 않으므로 전용 layer/source/cache를 직접 정리한다.
|
||||
const removeFlowDirectionLayer = useCallback(() => {
|
||||
const core = GisApp.Module.core as any;
|
||||
core?.deleteLayer?.(FLOW_DIRECTION_LAYER_TYPE);
|
||||
flowDirectionLayerRef.current = null;
|
||||
flowDirectionSourceRef.current = null;
|
||||
flowDirectionFeatureKeySetRef.current.clear();
|
||||
flowDirectionFeatureKeyQueueRef.current = [];
|
||||
flowDirectionVisibleUsageCodesRef.current.clear();
|
||||
}, []);
|
||||
|
||||
// 유하방향 cache/source만 비워 관종 변경처럼 조건이 달라진 경우 이전 조건의 피처가 남지 않게 한다.
|
||||
const clearFlowDirectionFeatureCache = useCallback(() => {
|
||||
flowDirectionSourceRef.current?.clear();
|
||||
flowDirectionFeatureKeySetRef.current.clear();
|
||||
flowDirectionFeatureKeyQueueRef.current = [];
|
||||
flowDirectionVisibleUsageCodesRef.current.clear();
|
||||
}, []);
|
||||
|
||||
// 체크 해제된 관종의 유하방향 feature/cache만 제거하고, 새로 체크된 관종 코드만 다음 요청 대상으로 돌려준다.
|
||||
const retainFlowDirectionUsageCodes = useCallback((usageCodes: string[]) => {
|
||||
const nextUsageCodes = new Set(usageCodes);
|
||||
const addedUsageCodes = usageCodes.filter(
|
||||
(usageCode) => !flowDirectionVisibleUsageCodesRef.current.has(usageCode),
|
||||
);
|
||||
const source = flowDirectionSourceRef.current;
|
||||
if (source) {
|
||||
source.getFeatures().forEach((feature: any) => {
|
||||
const usageCode = String(
|
||||
feature.get("usgCd") ?? feature.get("usg_cd") ?? "",
|
||||
).trim();
|
||||
if (nextUsageCodes.has(usageCode)) return;
|
||||
|
||||
const featureKey = feature.get("flowDirectionCacheKey");
|
||||
if (featureKey) {
|
||||
flowDirectionFeatureKeySetRef.current.delete(String(featureKey));
|
||||
}
|
||||
source.removeFeature(feature);
|
||||
});
|
||||
flowDirectionFeatureKeyQueueRef.current =
|
||||
flowDirectionFeatureKeyQueueRef.current.filter((featureKey) =>
|
||||
flowDirectionFeatureKeySetRef.current.has(featureKey),
|
||||
);
|
||||
}
|
||||
flowDirectionVisibleUsageCodesRef.current = new Set(
|
||||
Array.from(flowDirectionVisibleUsageCodesRef.current).filter(
|
||||
(usageCode) => nextUsageCodes.has(usageCode),
|
||||
),
|
||||
);
|
||||
return addedUsageCodes;
|
||||
}, []);
|
||||
|
||||
// 유하방향 레이어는 하나만 유지하고 source에 피처를 누적한다.
|
||||
const ensureFlowDirectionLayer = useCallback((layerInfo: any) => {
|
||||
const map = gisMaps.current;
|
||||
if (!map) return null;
|
||||
|
||||
if (flowDirectionLayerRef.current && flowDirectionSourceRef.current) {
|
||||
flowDirectionLayerRef.current.setMinZoom?.(
|
||||
getFlowDirectionMinZoom(layerInfo),
|
||||
);
|
||||
flowDirectionLayerRef.current.setZIndex?.(
|
||||
getFlowDirectionZIndex(layerInfo),
|
||||
);
|
||||
return flowDirectionSourceRef.current;
|
||||
}
|
||||
|
||||
const source = new VectorSource();
|
||||
const layer = new VectorLayer({
|
||||
source,
|
||||
minZoom: getFlowDirectionMinZoom(layerInfo),
|
||||
zIndex: getFlowDirectionZIndex(layerInfo),
|
||||
updateWhileAnimating: false,
|
||||
updateWhileInteracting: false,
|
||||
});
|
||||
|
||||
layer.set("id", FLOW_DIRECTION_LAYER_TYPE);
|
||||
layer.set("lyrNm", FLOW_DIRECTION_LAYER_NAME);
|
||||
layer.set("lyrTyNm", FLOW_DIRECTION_LAYER_TYPE);
|
||||
layer.set("typeName", FLOW_DIRECTION_LAYER_TYPE);
|
||||
layer.set("clickPsblYn", "N");
|
||||
layer.set("chcYn", "N");
|
||||
|
||||
const core = GisApp.Module.core as any;
|
||||
core?.deleteLayer?.(FLOW_DIRECTION_LAYER_TYPE);
|
||||
map.addLayer(layer);
|
||||
flowDirectionLayerRef.current = layer;
|
||||
flowDirectionSourceRef.current = source;
|
||||
return source;
|
||||
}, []);
|
||||
|
||||
// BE에서 받은 보정 GeoJSON을 OpenLayers feature로 변환해 기존 유하방향 source에 중복 없이 병합한다.
|
||||
const renderFlowDirectionLayer = useCallback(
|
||||
(
|
||||
featureCollection: any,
|
||||
layerInfo: any,
|
||||
usageStyleMap: Record<string, FlowDirectionUsageStyle>,
|
||||
) => {
|
||||
const source = ensureFlowDirectionLayer(layerInfo);
|
||||
if (!source) return;
|
||||
|
||||
const features = new GeoJSON().readFeatures(featureCollection, {
|
||||
dataProjection: FLOW_DIRECTION_SRS,
|
||||
featureProjection: GisApp.TO_PROJ,
|
||||
});
|
||||
|
||||
const nextFeatures = features.filter((feature) => {
|
||||
const featureKey = getFlowDirectionFeatureCacheKey(feature);
|
||||
if (flowDirectionFeatureKeySetRef.current.has(featureKey)) return false;
|
||||
|
||||
feature.set("flowDirectionCacheKey", featureKey);
|
||||
feature.setId(featureKey);
|
||||
feature.setStyle(createFlowDirectionStyle(feature, usageStyleMap));
|
||||
flowDirectionFeatureKeySetRef.current.add(featureKey);
|
||||
flowDirectionFeatureKeyQueueRef.current.push(featureKey);
|
||||
return true;
|
||||
});
|
||||
|
||||
if (nextFeatures.length > 0) {
|
||||
source.addFeatures(nextFeatures);
|
||||
}
|
||||
},
|
||||
[ensureFlowDirectionLayer],
|
||||
);
|
||||
|
||||
// 현재 지도 BBOX와 체크된 관종별 필터로 유하방향 GeoJSON을 각각 조회하고, 최신 요청만 지도에 반영한다.
|
||||
const loadFlowDirectionLayer = useCallback(
|
||||
async (layerInfo: any, requestOnlyUsageCodes?: string[]) => {
|
||||
const map = gisMaps.current;
|
||||
if (!map) return;
|
||||
|
||||
const requestSeq = flowDirectionRequestSeqRef.current + 1;
|
||||
flowDirectionRequestSeqRef.current = requestSeq;
|
||||
flowDirectionAbortControllerRef.current?.abort();
|
||||
const abortController = new AbortController();
|
||||
flowDirectionAbortControllerRef.current = abortController;
|
||||
|
||||
const view = map.getView();
|
||||
const zoom = view.getZoom() ?? 0;
|
||||
const minZoom = getFlowDirectionMinZoom(layerInfo);
|
||||
|
||||
if (zoom < minZoom) {
|
||||
removeFlowDirectionLayer();
|
||||
return;
|
||||
}
|
||||
|
||||
const size = map.getSize();
|
||||
if (!size) return;
|
||||
|
||||
const usageStyleMap = extractCheckedPipeUsageStyles(
|
||||
checkedNodesDataRef.current,
|
||||
zoom,
|
||||
);
|
||||
const usageCodes = Object.keys(usageStyleMap);
|
||||
if (usageCodes.length === 0) {
|
||||
removeFlowDirectionLayer();
|
||||
return;
|
||||
}
|
||||
retainFlowDirectionUsageCodes(usageCodes);
|
||||
|
||||
const usageCodeSet = new Set(usageCodes);
|
||||
const requestUsageCodes = requestOnlyUsageCodes
|
||||
? requestOnlyUsageCodes.filter((usageCode) =>
|
||||
usageCodeSet.has(usageCode),
|
||||
)
|
||||
: usageCodes;
|
||||
const isPartialUsageRequest = Array.isArray(requestOnlyUsageCodes);
|
||||
if (requestUsageCodes.length === 0) {
|
||||
if (flowDirectionAbortControllerRef.current === abortController) {
|
||||
flowDirectionAbortControllerRef.current = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const screenExtent = view.calculateExtent(size);
|
||||
const requestExtent = expandFlowDirectionExtent(screenExtent);
|
||||
const screenBbox = formatFlowDirectionBbox(screenExtent);
|
||||
const requestBbox = formatFlowDirectionBbox(requestExtent);
|
||||
const baseParams = new URLSearchParams({
|
||||
srs: FLOW_DIRECTION_SRS,
|
||||
directionMode: flowDirectionMode,
|
||||
searchStrategy: "BBOX",
|
||||
bbox: requestBbox,
|
||||
});
|
||||
|
||||
try {
|
||||
const settledResponses = await Promise.allSettled(
|
||||
requestUsageCodes.map(async (usageCode) => {
|
||||
const params = new URLSearchParams(baseParams);
|
||||
params.set("usgCd", usageCode);
|
||||
const payload = await getRawJson(
|
||||
`/sewerage-service/api/v1/map/flowDirectionGeometry?${params.toString()}`,
|
||||
{ signal: abortController.signal },
|
||||
);
|
||||
return {
|
||||
usageCode,
|
||||
featureCollection: getFeatureCollection(payload),
|
||||
};
|
||||
}),
|
||||
);
|
||||
if (requestSeq !== flowDirectionRequestSeqRef.current) return;
|
||||
if (abortController.signal.aborted) return;
|
||||
|
||||
const responses = settledResponses
|
||||
.filter(
|
||||
(
|
||||
result,
|
||||
): result is PromiseFulfilledResult<{
|
||||
usageCode: string;
|
||||
featureCollection: any;
|
||||
}> => result.status === "fulfilled",
|
||||
)
|
||||
.map((result) => result.value);
|
||||
const failedResponses = settledResponses.filter(
|
||||
(result) => result.status === "rejected",
|
||||
);
|
||||
|
||||
if (responses.length === 0) {
|
||||
if (!isPartialUsageRequest) {
|
||||
removeFlowDirectionLayer();
|
||||
}
|
||||
throw (
|
||||
failedResponses[0]?.reason ??
|
||||
new Error("유하방향 관종별 조회 결과가 없습니다.")
|
||||
);
|
||||
}
|
||||
|
||||
if (failedResponses.length > 0) {
|
||||
console.error(
|
||||
"유하방향 일부 관종 조회 실패:",
|
||||
failedResponses.map((result) => result.reason),
|
||||
);
|
||||
if (!flowDirectionFailureAlertedRef.current) {
|
||||
flowDirectionFailureAlertedRef.current = true;
|
||||
}
|
||||
}
|
||||
|
||||
responses.forEach(({ usageCode, featureCollection }) => {
|
||||
renderFlowDirectionLayer(featureCollection, layerInfo, usageStyleMap);
|
||||
flowDirectionVisibleUsageCodesRef.current.add(usageCode);
|
||||
});
|
||||
const returnedFeaturesByUsage = responses.reduce<
|
||||
Record<string, number>
|
||||
>((acc, { usageCode, featureCollection }) => {
|
||||
acc[usageCode] = featureCollection.features?.length ?? 0;
|
||||
return acc;
|
||||
}, {});
|
||||
const networkCorrectedFeatures = responses.reduce(
|
||||
(count, { featureCollection }) => {
|
||||
const correctedCount =
|
||||
featureCollection.features?.filter(
|
||||
(feature: any) =>
|
||||
String(
|
||||
feature?.properties?.networkCorrectionYn ??
|
||||
feature?.properties?.network_correction_yn ??
|
||||
"",
|
||||
).toUpperCase() === "Y",
|
||||
).length ?? 0;
|
||||
return count + correctedCount;
|
||||
},
|
||||
0,
|
||||
);
|
||||
(window as any).__SN_FLOW_DIRECTION_DEBUG__ = {
|
||||
screenBbox,
|
||||
requestBbox,
|
||||
requestSeq,
|
||||
zoom,
|
||||
directionMode: flowDirectionMode,
|
||||
searchStrategy: "BBOX",
|
||||
usageCodes,
|
||||
requestUsageCodes,
|
||||
requestCount: responses.length,
|
||||
returnedFeaturesByUsage,
|
||||
returnedFeatures: Object.values(returnedFeaturesByUsage).reduce(
|
||||
(sum, count) => sum + count,
|
||||
0,
|
||||
),
|
||||
networkCorrectedFeatures,
|
||||
cachedFeatures:
|
||||
flowDirectionSourceRef.current?.getFeatures?.().length ?? 0,
|
||||
};
|
||||
if (failedResponses.length === 0) {
|
||||
flowDirectionFailureAlertedRef.current = false;
|
||||
}
|
||||
} catch (error) {
|
||||
if (requestSeq !== flowDirectionRequestSeqRef.current) return;
|
||||
if (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"name" in error &&
|
||||
error.name === "AbortError"
|
||||
)
|
||||
return;
|
||||
|
||||
console.error("유하방향 레이어 조회 실패:", error);
|
||||
if (!isPartialUsageRequest) {
|
||||
removeFlowDirectionLayer();
|
||||
}
|
||||
if (!flowDirectionFailureAlertedRef.current) {
|
||||
flowDirectionFailureAlertedRef.current = true;
|
||||
}
|
||||
} finally {
|
||||
if (flowDirectionAbortControllerRef.current === abortController) {
|
||||
flowDirectionAbortControllerRef.current = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
[
|
||||
flowDirectionMode,
|
||||
removeFlowDirectionLayer,
|
||||
renderFlowDirectionLayer,
|
||||
retainFlowDirectionUsageCodes,
|
||||
],
|
||||
);
|
||||
const updateSelection = useCallback(
|
||||
(checkedNodesData: any[]) => {
|
||||
// 유하방향은 일반 setLayerOnMap 대상이 아니므로 체크 노드 여부를 별도로 추적한다.
|
||||
const flowDirectionNode = checkedNodesData.find((node) =>
|
||||
isFlowDirectionLayerInfo(node?.data ?? node),
|
||||
);
|
||||
const nextFlowDirectionLayerInfo =
|
||||
flowDirectionNode?.data ?? flowDirectionNode ?? null;
|
||||
flowDirectionCheckedRef.current = Boolean(nextFlowDirectionLayerInfo);
|
||||
flowDirectionLayerInfoRef.current = nextFlowDirectionLayerInfo;
|
||||
setIsFlowDirectionChecked(Boolean(nextFlowDirectionLayerInfo));
|
||||
setFlowDirectionLayerInfo(nextFlowDirectionLayerInfo);
|
||||
if (nextFlowDirectionLayerInfo) {
|
||||
const map = gisMaps.current;
|
||||
const zoom = map?.getView?.()?.getZoom?.() ?? 0;
|
||||
const nextUsageStyleMap = extractCheckedPipeUsageStyles(
|
||||
checkedNodesData,
|
||||
zoom,
|
||||
);
|
||||
const requestUsageCodes = retainFlowDirectionUsageCodes(
|
||||
Object.keys(nextUsageStyleMap),
|
||||
);
|
||||
flowDirectionSelectionRequestUsageCodesRef.current = requestUsageCodes;
|
||||
if (requestUsageCodes.length === 0) {
|
||||
flowDirectionRequestSeqRef.current += 1;
|
||||
flowDirectionAbortControllerRef.current?.abort();
|
||||
flowDirectionAbortControllerRef.current = null;
|
||||
}
|
||||
setFlowDirectionSelectionVersion((version) => version + 1);
|
||||
}
|
||||
|
||||
if (!nextFlowDirectionLayerInfo) {
|
||||
// 해제 직후 pending API 응답이 늦게 도착해도 renderFlowDirectionLayer가 실행되지 않도록 순번을 무효화한다.
|
||||
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
||||
flowDirectionRequestSeqRef.current += 1;
|
||||
flowDirectionAbortControllerRef.current?.abort();
|
||||
flowDirectionAbortControllerRef.current = null;
|
||||
flowDirectionFailureAlertedRef.current = false;
|
||||
removeFlowDirectionLayer();
|
||||
}
|
||||
},
|
||||
[gisMaps, removeFlowDirectionLayer, retainFlowDirectionUsageCodes],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!flowDirectionCheckedRef.current) return;
|
||||
clearFlowDirectionFeatureCache();
|
||||
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
||||
setFlowDirectionSelectionVersion((version) => version + 1);
|
||||
}, [clearFlowDirectionFeatureCache, flowDirectionMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mapReady || !flowDirectionLayerInfo) return;
|
||||
|
||||
// 트리 체크 상태나 관종 레이어 선택이 바뀌면 유하방향 API vector layer를 추가/갱신/제거한다.
|
||||
if (isFlowDirectionChecked) {
|
||||
const requestUsageCodes =
|
||||
flowDirectionSelectionRequestUsageCodesRef.current;
|
||||
flowDirectionSelectionRequestUsageCodesRef.current = null;
|
||||
if (requestUsageCodes && requestUsageCodes.length === 0) return;
|
||||
loadFlowDirectionLayer(
|
||||
flowDirectionLayerInfo,
|
||||
requestUsageCodes ?? undefined,
|
||||
);
|
||||
} else {
|
||||
removeFlowDirectionLayer();
|
||||
}
|
||||
}, [
|
||||
flowDirectionLayerInfo,
|
||||
flowDirectionSelectionVersion,
|
||||
isFlowDirectionChecked,
|
||||
loadFlowDirectionLayer,
|
||||
mapReady,
|
||||
removeFlowDirectionLayer,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!mapReady || !gisMaps.current) return;
|
||||
|
||||
// 유하방향이 켜진 상태에서 지도 이동/확대축소가 끝나면 현재 BBOX 기준으로 다시 조회한다.
|
||||
return subscribeFlowDirectionMoveEnd(
|
||||
gisMaps.current,
|
||||
() => ({
|
||||
checked: flowDirectionCheckedRef.current,
|
||||
layerInfo: flowDirectionLayerInfoRef.current,
|
||||
}),
|
||||
loadFlowDirectionLayer,
|
||||
unByKey,
|
||||
);
|
||||
}, [loadFlowDirectionLayer, mapReady]);
|
||||
|
||||
// 화면 이탈 후 지연 응답이 제거된 지도에 레이어를 되살리지 않도록 무효화한다.
|
||||
useEffect(
|
||||
() => () => {
|
||||
flowDirectionRequestSeqRef.current += 1;
|
||||
flowDirectionAbortControllerRef.current?.abort();
|
||||
flowDirectionAbortControllerRef.current = null;
|
||||
const ownedLayer = flowDirectionLayerRef.current;
|
||||
if (ownedLayer) gisMaps.current?.removeLayer?.(ownedLayer);
|
||||
flowDirectionLayerRef.current = null;
|
||||
flowDirectionSourceRef.current = null;
|
||||
flowDirectionFeatureKeySetRef.current.clear();
|
||||
flowDirectionFeatureKeyQueueRef.current = [];
|
||||
flowDirectionVisibleUsageCodesRef.current.clear();
|
||||
},
|
||||
[gisMaps],
|
||||
);
|
||||
|
||||
return { isFlowDirectionChecked, flowDirectionLayerInfo, updateSelection };
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
/** 유하방향 원천 레이어와 API 좌표계 계약. 기존 값을 유지한다. */
|
||||
export const FLOW_DIRECTION_PIPE_LAYER_TYPE = "tb_ms_swage_ppl";
|
||||
export const FLOW_DIRECTION_SRS = "EPSG:5179";
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* 📄 useReportTabStore
|
||||
* 보고서 탭 Zustand 스토어
|
||||
*
|
||||
* - 보고서 탭 모달 열기/닫기 상태 관리
|
||||
* - 보고서 파일 목록 및 트리 구조 상태 관리
|
||||
* - DC 트리 데이터 조회 및 캐싱 기능
|
||||
* - DC 파일 목록 조회 및 상태 업데이트
|
||||
* - Zustand를 통한 중앙 집중식 상태 관리
|
||||
* - 데이터 변경 감지 및 불필요한 재렌더링 방지
|
||||
*
|
||||
* 🔗 사용 API
|
||||
* - DC 트리 데이터 조회: GET /dc-service//api/v1/dc/clsf
|
||||
* - DC 파일 목록 조회: GET /dc-service//api/v1/dc/file
|
||||
*/
|
||||
import { type Folder, type ReportDataFile } from "@/features/map-search/model/report-types";
|
||||
import { create } from 'zustand';
|
||||
import { getDcData } from "@/shared/api/external-service-api";
|
||||
|
||||
interface useReportTabStoreType {
|
||||
isOpen: boolean;
|
||||
files: ReportDataFile[];
|
||||
dcTree: Folder[];
|
||||
dcFiles: ReportDataFile[];
|
||||
setIsOpen: (open: boolean) => void;
|
||||
setFiles: (files: ReportDataFile[]) => void;
|
||||
fetchDcTree: (clsfSystmNm: string) => void;
|
||||
fetchDcFiles: (clsfSystmNm: string) => void;
|
||||
}
|
||||
export const useReportTabStore = create<useReportTabStoreType>((set, get) => ({
|
||||
isOpen: false,
|
||||
files: [],
|
||||
dcTree: [],
|
||||
dcFiles: [],
|
||||
setIsOpen: (open: boolean) => set({ isOpen: open }),
|
||||
setFiles: (files: ReportDataFile[]) => set({ files }),
|
||||
fetchDcTree: async (clsfSystmNm: string) => {
|
||||
const { dcTree } = get();
|
||||
try {
|
||||
const result = await getDcData("/api/v1/clsf?clsfSystmNm=" + clsfSystmNm);
|
||||
if (result && JSON.stringify(result) !== JSON.stringify(dcTree))
|
||||
set({ dcTree: result });
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch DC tree:', error);
|
||||
}
|
||||
},
|
||||
fetchDcFiles: async (clsfSystmNm: string) => {
|
||||
const getDcFiles = async (clsfSystmSn: string): Promise<ReportDataFile[]> => {
|
||||
if (!clsfSystmSn) {
|
||||
console.error("clsfSystmSn is required to get files.");
|
||||
return [];
|
||||
}
|
||||
const queryString = 'clsfSystmSn=' + clsfSystmSn;
|
||||
const result = await getDcData(`/api/v1/file${queryString ? `?${queryString}` : ''}`);
|
||||
return result;
|
||||
};
|
||||
|
||||
const { dcFiles } = get();
|
||||
try {
|
||||
const result = await getDcFiles(clsfSystmNm);
|
||||
if (result && JSON.stringify(result) !== JSON.stringify(dcFiles))
|
||||
set({ dcFiles: result });
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch DC files:', error);
|
||||
}
|
||||
}
|
||||
}));
|
||||
@@ -0,0 +1,25 @@
|
||||
/** 지도 보고서 조회에서 공유하는 도메인 타입. 화면 hook을 역참조하지 않는다. */
|
||||
export type Folder = {
|
||||
clsfSystmSn: string;
|
||||
upClsfSystmSn: string;
|
||||
clsfSystmNm: string;
|
||||
children: Folder[];
|
||||
};
|
||||
|
||||
export type FlattenedFolder = {
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
|
||||
export type SelectDataType = {
|
||||
text: string;
|
||||
val: string;
|
||||
sido?: string; // 시도 코드 (선택 사항)
|
||||
};
|
||||
|
||||
export type ReportDataFile = {
|
||||
no: number;
|
||||
fileTitle: string;
|
||||
regDt: string;
|
||||
fileSn: string;
|
||||
filePath: string;
|
||||
};
|
||||
@@ -0,0 +1,231 @@
|
||||
/**
|
||||
* 📄 useSearchModalStore
|
||||
* 검색 모달 Zustand 스토어
|
||||
*
|
||||
* - 검색 모달 열기/닫기 및 탭 전환 상태 관리
|
||||
* - 기본정보 및 유지관리 정보 탭 데이터 필터링 및 조회
|
||||
* - 테이블 데이터 및 페이지네이션 상태 관리
|
||||
* - 지역(시도/시군구) 및 날짜 범위 필터링 기능
|
||||
* - 로딩 상태 및 리셋 플래그 관리
|
||||
* - Zustand를 통한 중앙 집중식 상태 관리
|
||||
* - 데이터 변경 감지 및 불필요한 재렌더링 방지
|
||||
*/
|
||||
import { create } from "zustand";
|
||||
|
||||
export const SEARCH_MODAL_DEFAULT_BASIC_TYPE = "tb_ms_swage_ppl";
|
||||
export const SEARCH_MODAL_DEFAULT_WORK_TYPE = "['200', '201', '204']";
|
||||
|
||||
export type AppliedBasicQuery = {
|
||||
basicType: string;
|
||||
query: string;
|
||||
};
|
||||
|
||||
// 날짜 조합 함수
|
||||
const getDateString = (
|
||||
year: string,
|
||||
month: string,
|
||||
day: string,
|
||||
defaultDate: string,
|
||||
) => {
|
||||
if (!year && !month && !day) return defaultDate;
|
||||
const y = year || defaultDate.slice(0, 4);
|
||||
const m = month || defaultDate.slice(4, 6);
|
||||
const d = day || defaultDate.slice(6, 8);
|
||||
return `${y}${m}${d}`;
|
||||
};
|
||||
|
||||
// 오늘 날짜 계산
|
||||
const today = new Date();
|
||||
const todayYear = today.getFullYear().toString();
|
||||
const todayMonth = (today.getMonth() + 1).toString().padStart(2, "0");
|
||||
const todayDate = today.getDate().toString().padStart(2, "0");
|
||||
|
||||
export interface SearchModalState {
|
||||
// 모달 열림 상태
|
||||
isSearchModalOpen: boolean;
|
||||
// 탭 관련
|
||||
activeTab: string;
|
||||
basicType: string;
|
||||
workType: string;
|
||||
// 최초 렌더 방지 플래그
|
||||
showTable: boolean;
|
||||
// 테이블 데이터
|
||||
tableData: any[];
|
||||
detailTableData: any[];
|
||||
tableCount: number;
|
||||
detailTableCount: number;
|
||||
// 기본정보 화면을 마지막으로 만든 조회조건. 조회 훅과 다운로드 훅이 같은 값을 공유한다.
|
||||
appliedBasicQuery: AppliedBasicQuery | null;
|
||||
// 페이지네이션
|
||||
curPage: number;
|
||||
detailCurPage: number;
|
||||
// 로딩 상태
|
||||
isLoading: boolean;
|
||||
isDetailLoading: boolean;
|
||||
// 리셋 플래그
|
||||
isResetPage: boolean;
|
||||
isResetDetailPage: boolean;
|
||||
isResetSelection: boolean;
|
||||
isResetDetailSelection: boolean;
|
||||
// 사업 ID
|
||||
detailBizId: number;
|
||||
// 지역 필터
|
||||
ctpvCd: string;
|
||||
ctpvName: string;
|
||||
sggCd: string;
|
||||
sggName: string;
|
||||
// 범위 필터
|
||||
start1: string;
|
||||
start2: string;
|
||||
end1: string;
|
||||
end2: string;
|
||||
// 변수 필터
|
||||
var1: string;
|
||||
var2: string;
|
||||
// 연도 필터
|
||||
yearFilter: { start: string; end: string };
|
||||
// 날짜 관련
|
||||
today: Date;
|
||||
todayYear: string;
|
||||
todayMonth: string;
|
||||
todayDate: string;
|
||||
|
||||
// setters
|
||||
setIsSearchModalOpen: (open: boolean) => void;
|
||||
setActiveTab: (tab: string) => void;
|
||||
setBasicType: (type: string) => void;
|
||||
setWorkType: (type: string) => void;
|
||||
setShowTable: (show: boolean) => void;
|
||||
setTableData: (data: any[]) => void;
|
||||
setDetailTableData: (data: any[]) => void;
|
||||
setTableCount: (count: number) => void;
|
||||
setDetailTableCount: (count: number) => void;
|
||||
setAppliedBasicQuery: (query: AppliedBasicQuery | null) => void;
|
||||
setCurPage: (page: number) => void;
|
||||
setDetailCurPage: (page: number) => void;
|
||||
setIsLoading: (loading: boolean) => void;
|
||||
setIsDetailLoading: (loading: boolean) => void;
|
||||
setIsResetPage: (reset: boolean) => void;
|
||||
setIsResetDetailPage: (reset: boolean) => void;
|
||||
setIsResetSelection: (reset: boolean) => void;
|
||||
setIsResetDetailSelection: (reset: boolean) => void;
|
||||
setDetailBizId: (id: number) => void;
|
||||
setCtpvCd: (cd: string) => void;
|
||||
setCtpvName: (name: string) => void;
|
||||
setSggCd: (cd: string) => void;
|
||||
setSggName: (name: string) => void;
|
||||
setStart1: (val: string) => void;
|
||||
setStart2: (val: string) => void;
|
||||
setEnd1: (val: string) => void;
|
||||
setEnd2: (val: string) => void;
|
||||
setVar1: (val: string) => void;
|
||||
setVar2: (val: string) => void;
|
||||
setYearFilter: (filter: { start: string; end: string }) => void;
|
||||
|
||||
getDateString: (
|
||||
year: string,
|
||||
month: string,
|
||||
day: string,
|
||||
defaultDate: string,
|
||||
) => string;
|
||||
resetFilters: () => void; // 초기화 액션
|
||||
}
|
||||
|
||||
const useSearchModalStore = create<SearchModalState>((set) => ({
|
||||
isSearchModalOpen: false,
|
||||
activeTab: "basic",
|
||||
basicType: SEARCH_MODAL_DEFAULT_BASIC_TYPE,
|
||||
workType: SEARCH_MODAL_DEFAULT_WORK_TYPE,
|
||||
showTable: false,
|
||||
tableData: [],
|
||||
detailTableData: [],
|
||||
tableCount: 0,
|
||||
detailTableCount: 0,
|
||||
appliedBasicQuery: null,
|
||||
curPage: 1,
|
||||
detailCurPage: 1,
|
||||
isLoading: false,
|
||||
isDetailLoading: false,
|
||||
isResetPage: false,
|
||||
isResetDetailPage: false,
|
||||
isResetSelection: false,
|
||||
isResetDetailSelection: false,
|
||||
detailBizId: 0,
|
||||
ctpvCd: "0",
|
||||
ctpvName: "",
|
||||
sggCd: "0",
|
||||
sggName: "",
|
||||
start1: "",
|
||||
start2: "",
|
||||
end1: "",
|
||||
end2: "",
|
||||
var1: "",
|
||||
var2: "",
|
||||
yearFilter: { start: "", end: "" },
|
||||
today,
|
||||
todayYear,
|
||||
todayMonth,
|
||||
todayDate,
|
||||
setIsSearchModalOpen: (isSearchModalOpen) => set({ isSearchModalOpen }),
|
||||
setActiveTab: (tab) => set({ activeTab: tab }),
|
||||
setBasicType: (type) => set({ basicType: type }),
|
||||
setWorkType: (type) => set({ workType: type }),
|
||||
setShowTable: (show) => set({ showTable: show }),
|
||||
setTableData: (data) => set({ tableData: data }),
|
||||
setDetailTableData: (data) => set({ detailTableData: data }),
|
||||
setTableCount: (count) => set({ tableCount: count }),
|
||||
setDetailTableCount: (count) => set({ detailTableCount: count }),
|
||||
setAppliedBasicQuery: (appliedBasicQuery) => set({ appliedBasicQuery }),
|
||||
setCurPage: (page) => set({ curPage: page }),
|
||||
setDetailCurPage: (page) => set({ detailCurPage: page }),
|
||||
setIsLoading: (loading) => set({ isLoading: loading }),
|
||||
setIsDetailLoading: (loading) => set({ isDetailLoading: loading }),
|
||||
setIsResetPage: (reset) => set({ isResetPage: reset }),
|
||||
setIsResetDetailPage: (reset) => set({ isResetDetailPage: reset }),
|
||||
setIsResetSelection: (reset) => set({ isResetSelection: reset }),
|
||||
setIsResetDetailSelection: (reset) => set({ isResetDetailSelection: reset }),
|
||||
setDetailBizId: (id) => set({ detailBizId: id }),
|
||||
setCtpvCd: (cd) => set({ ctpvCd: cd }),
|
||||
setCtpvName: (name) => set({ ctpvName: name }),
|
||||
setSggCd: (cd) => set({ sggCd: cd }),
|
||||
setSggName: (name) => set({ sggName: name }),
|
||||
setStart1: (val) => set({ start1: val }),
|
||||
setStart2: (val) => set({ start2: val }),
|
||||
setEnd1: (val) => set({ end1: val }),
|
||||
setEnd2: (val) => set({ end2: val }),
|
||||
setVar1: (val) => set({ var1: val }),
|
||||
setVar2: (val) => set({ var2: val }),
|
||||
setYearFilter: (filter) => set({ yearFilter: filter }),
|
||||
|
||||
getDateString: getDateString,
|
||||
// 초기화 액션
|
||||
resetFilters: () =>
|
||||
set({
|
||||
showTable: false,
|
||||
start1: "",
|
||||
start2: "",
|
||||
end1: "",
|
||||
end2: "",
|
||||
var1: "",
|
||||
var2: "",
|
||||
ctpvCd: "0",
|
||||
ctpvName: "",
|
||||
sggCd: "0",
|
||||
sggName: "",
|
||||
yearFilter: { start: "", end: "" },
|
||||
tableData: [],
|
||||
detailTableData: [],
|
||||
tableCount: 0,
|
||||
detailTableCount: 0,
|
||||
appliedBasicQuery: null,
|
||||
curPage: 1,
|
||||
detailCurPage: 1,
|
||||
isResetPage: true,
|
||||
isResetDetailPage: true,
|
||||
isResetSelection: true,
|
||||
isResetDetailSelection: true,
|
||||
detailBizId: 0,
|
||||
}),
|
||||
}));
|
||||
|
||||
export default useSearchModalStore;
|
||||
+1
-6
@@ -5,12 +5,7 @@ import type {
|
||||
ObsltPplPage,
|
||||
} from "../model/obslt-ppl-types";
|
||||
|
||||
import {
|
||||
deleteData,
|
||||
getData,
|
||||
postRawJson,
|
||||
putData,
|
||||
} from "@/components/lib/api";
|
||||
import { deleteData, getData, postRawJson, putData } from "@/shared/api/sewerage-api";
|
||||
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
|
||||
|
||||
const API_PATH = "v1/obsltPplBiz";
|
||||
+3
-3
@@ -41,10 +41,10 @@ import type {
|
||||
ObsltPplBusinessSaveRequest,
|
||||
} from "../model/obslt-ppl-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { useAlertStore } from "@/shared/lib";
|
||||
import { useOperBusinessCommonCodes } from "@/shared/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/store/useStore";
|
||||
import { useOperBusinessCommonCodes } from "@/entities/business/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
|
||||
type FormKey = keyof ObsltPplBusinessSaveRequest;
|
||||
type FormState = Record<FormKey, string>;
|
||||
+5
-5
@@ -45,11 +45,11 @@ import {
|
||||
} from "../lib/obslt-ppl-region";
|
||||
import type { ObsltPplBusiness, ObsltPplPage } from "../model/obslt-ppl-types";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import { useOperBusinessCommonCodes } from "@/shared/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/store/useStore";
|
||||
import { openWindowPopup } from "../../windowPopup/lib/openWindowPopup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "../../windowPopup/model/types";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import { useOperBusinessCommonCodes } from "@/entities/business/lib/use-oper-business-common-codes";
|
||||
import useStore from "@/entities/reference-data/model/reference-data-store";
|
||||
import { openWindowPopup } from "../../window-popup/lib/open-window-popup";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "../../window-popup/model/types";
|
||||
|
||||
const DEFAULT_LIST_SIZE = 10;
|
||||
const ALL_REGION_OPTION = { text: "전체", val: "0" };
|
||||
+2
-2
@@ -1,9 +1,9 @@
|
||||
export { openWindowPopup } from "./lib/openWindowPopup";
|
||||
export { openWindowPopup } from "./lib/open-window-popup";
|
||||
export {
|
||||
isWindowPopupKey,
|
||||
windowPopupDefinitions,
|
||||
type WindowPopupKey,
|
||||
} from "./model/popupDefinitions";
|
||||
} from "./model/popup-definitions";
|
||||
export { windowPopupRegistry } from "./registry";
|
||||
export type {
|
||||
OpenWindowPopupParams,
|
||||
+2
-2
@@ -4,11 +4,11 @@ import {
|
||||
isWindowPopupKey,
|
||||
windowPopupDefinitions,
|
||||
type WindowPopupKey,
|
||||
} from "../model/popupDefinitions";
|
||||
} from "../model/popup-definitions";
|
||||
import {
|
||||
resolveWindowPopupTheme,
|
||||
WINDOW_POPUP_THEME_PARAM,
|
||||
} from "../model/popupTheme";
|
||||
} from "../model/popup-theme";
|
||||
import type {
|
||||
OpenWindowPopupOptions,
|
||||
OpenWindowPopupParams,
|
||||
+35
-35
@@ -1,18 +1,18 @@
|
||||
"use client";
|
||||
|
||||
import LoadingOverlay from "@/components/ui/LoadingBar";
|
||||
import LoadingOverlay from "@/components/ui/loading-bar";
|
||||
import dynamic from "next/dynamic";
|
||||
import type { ComponentType } from "react";
|
||||
|
||||
import {
|
||||
windowPopupDefinitions,
|
||||
type WindowPopupKey,
|
||||
} from "./model/popupDefinitions";
|
||||
} from "./model/popup-definitions";
|
||||
import type {
|
||||
WindowPopupContentProps,
|
||||
WindowPopupRegistryItem,
|
||||
} from "./model/types";
|
||||
import FeaturePlaceholderPopupContent from "./ui/FeaturePlaceholderPopupContent";
|
||||
import FeaturePlaceholderPopupContent from "./ui/feature-placeholder-popup-content";
|
||||
|
||||
type WindowPopupModule = {
|
||||
default: ComponentType<WindowPopupContentProps>;
|
||||
@@ -31,100 +31,100 @@ const loadPopupContent = (loader: () => Promise<WindowPopupModule>) =>
|
||||
});
|
||||
|
||||
const CfmtnBgtPopupContent = loadPopupContent(
|
||||
() => import("../cfmtnBgt/ui/CfmtnBgtPopupContent"),
|
||||
() => import("../cfmtn-bgt/ui/cfmtn-bgt-popup-content"),
|
||||
);
|
||||
const AgedPipePopupContent = loadPopupContent(
|
||||
() => import("./ui/AgedPipePopupContent"),
|
||||
() => import("./ui/aged-pipe-popup-content"),
|
||||
);
|
||||
const AgedPipeStatusByCtpvPopupContent = loadPopupContent(
|
||||
() => import("./ui/AgedPipeStatusByCtpvPopupContent"),
|
||||
() => import("./ui/aged-pipe-status-by-ctpv-popup-content"),
|
||||
);
|
||||
const DredgingRegisterPopupContent = loadPopupContent(
|
||||
() => import("./ui/DredgingRegisterPopupContent"),
|
||||
() => import("./ui/dredging-register-popup-content"),
|
||||
);
|
||||
const DredgingEditPopupContent = loadPopupContent(
|
||||
() => import("./ui/DredgingEditPopupContent"),
|
||||
() => import("./ui/dredging-edit-popup-content"),
|
||||
);
|
||||
const ExmnBusinessRegisterPopupContent = loadPopupContent(
|
||||
() => import("./ui/ExmnBusinessRegisterPopupContent"),
|
||||
() => import("./ui/exmn-business-register-popup-content"),
|
||||
);
|
||||
const ExmnPipeReportPopupContent = loadPopupContent(
|
||||
() => import("./ui/ExmnPipeReportPopupContent"),
|
||||
() => import("./ui/exmn-pipe-report-popup-content"),
|
||||
);
|
||||
const ExmnResultRegisterPopupContent = loadPopupContent(
|
||||
() => import("./ui/ExmnResultRegisterPopupContent"),
|
||||
() => import("./ui/exmn-result-register-popup-content"),
|
||||
);
|
||||
const ExmnSurveyDetailPopupContent = loadPopupContent(
|
||||
() => import("./ui/ExmnSurveyDetailPopupContent"),
|
||||
() => import("./ui/exmn-survey-detail-popup-content"),
|
||||
);
|
||||
const FloodPreTablePopupContent = loadPopupContent(
|
||||
() => import("./ui/FloodPreTablePopupContent"),
|
||||
() => import("./ui/flood-pre-table-popup-content"),
|
||||
);
|
||||
const FloodPreUploadPopupContent = loadPopupContent(
|
||||
() => import("./ui/FloodPreUploadPopupContent"),
|
||||
() => import("./ui/flood-pre-upload-popup-content"),
|
||||
);
|
||||
const InfilChartPopupContent = loadPopupContent(
|
||||
() => import("./ui/InfilChartPopupContent"),
|
||||
() => import("./ui/infil-chart-popup-content"),
|
||||
);
|
||||
const InftwtResultPopupContent = loadPopupContent(
|
||||
() => import("./ui/InftwtResultPopupContent"),
|
||||
() => import("./ui/inftwt-result-popup-content"),
|
||||
);
|
||||
const OldPpUploadPopupContent = loadPopupContent(
|
||||
() => import("./ui/OldPpUploadPopupContent"),
|
||||
() => import("./ui/old-pp-upload-popup-content"),
|
||||
);
|
||||
const OldPpTablePopupContent = loadPopupContent(
|
||||
() => import("./ui/OldPpTablePopupContent"),
|
||||
() => import("./ui/old-pp-table-popup-content"),
|
||||
);
|
||||
const RdiiChartPopupContent = loadPopupContent(
|
||||
() => import("./ui/RdiiChartPopupContent"),
|
||||
() => import("./ui/rdii-chart-popup-content"),
|
||||
);
|
||||
const RdiiResultPopupContent = loadPopupContent(
|
||||
() => import("./ui/RdiiResultPopupContent"),
|
||||
() => import("./ui/rdii-result-popup-content"),
|
||||
);
|
||||
const ReportFilesPopupContent = loadPopupContent(
|
||||
() => import("./ui/ReportFilesPopupContent"),
|
||||
() => import("./ui/report-files-popup-content"),
|
||||
);
|
||||
const ReportTabPopupContent = loadPopupContent(
|
||||
() => import("./ui/ReportTabPopupContent"),
|
||||
() => import("./ui/report-tab-popup-content"),
|
||||
);
|
||||
const SearchModalPopupContent = loadPopupContent(
|
||||
() => import("./ui/SearchModalPopupContent"),
|
||||
() => import("./ui/search-modal-popup-content"),
|
||||
);
|
||||
const SinkholePopupContent = loadPopupContent(
|
||||
() => import("./ui/SinkholePopupContent"),
|
||||
() => import("./ui/sinkhole-popup-content"),
|
||||
);
|
||||
const SbmrgDngrMapPopupContent = loadPopupContent(
|
||||
() => import("./ui/SbmrgDngrMapPopupContent"),
|
||||
() => import("./ui/sbmrg-dngr-map-popup-content"),
|
||||
);
|
||||
const FloodDngrMapPopupContent = loadPopupContent(
|
||||
() => import("./ui/FloodDngrMapPopupContent"),
|
||||
() => import("./ui/flood-dngr-map-popup-content"),
|
||||
);
|
||||
const SscDetailPopupContent = loadPopupContent(
|
||||
() => import("./ui/SscDetailPopupContent"),
|
||||
() => import("./ui/ssc-detail-popup-content"),
|
||||
);
|
||||
const FldngHstryPopupContent = loadPopupContent(
|
||||
() => import("./ui/FldngHstryPopupContent"),
|
||||
() => import("./ui/fldng-hstry-popup-content"),
|
||||
);
|
||||
const GisEditSessionPopupContent = loadPopupContent(
|
||||
() => import("./ui/GisEditSessionPopupContent"),
|
||||
() => import("./ui/gis-edit-session-popup-content"),
|
||||
);
|
||||
const GisManagementPopupContent = loadPopupContent(
|
||||
() => import("./ui/GisManagementPopupContent"),
|
||||
() => import("./ui/gis-management-popup-content"),
|
||||
);
|
||||
const PipeAnalysisPopupContent = loadPopupContent(
|
||||
() => import("./ui/PipeAnalysisPopupContent"),
|
||||
() => import("./ui/pipe-analysis-popup-content"),
|
||||
);
|
||||
const PipeAnalysisDetailPopupContent = loadPopupContent(
|
||||
() => import("./ui/PipeAnalysisDetailPopupContent"),
|
||||
() => import("./ui/pipe-analysis-detail-popup-content"),
|
||||
);
|
||||
const RepairHistoryPopupContent = loadPopupContent(
|
||||
() => import("./ui/RepairHistoryPopupContent"),
|
||||
() => import("./ui/repair-history-popup-content"),
|
||||
);
|
||||
const WaterRiskPopupContent = loadPopupContent(
|
||||
() => import("./ui/WaterRiskPopupContent"),
|
||||
() => import("./ui/water-risk-popup-content"),
|
||||
);
|
||||
const FldngPredcPrstPopupContent = loadPopupContent(
|
||||
() => import("../fldngPredcPrst/ui/FldngPredcPrstPopupContent"),
|
||||
() => import("../fldng-predc-prst/ui/fldng-predc-prst-popup-content"),
|
||||
);
|
||||
|
||||
const GisEditPopupContent = (_props: WindowPopupContentProps) => (
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { Suspense } from "react";
|
||||
import AgedPipePopupPage from "@/app/(map-layout)/map/components/agedPipe/AgedPipePopupPage";
|
||||
import AgedPipePopupPage from "@/app/(map-layout)/map/components/aged-pipe/aged-pipe-popup-page";
|
||||
|
||||
export default function AgedPipePopupContent() {
|
||||
return (
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { Suspense } from "react";
|
||||
import AgedPipeStatusByCtpvPopupPage from "@/app/(map-layout)/map/components/agedPipeStatusByCtpv/AgedPipeStatusByCtpvPopupPage";
|
||||
import AgedPipeStatusByCtpvPopupPage from "@/app/(map-layout)/map/components/aged-pipe-status-by-ctpv/aged-pipe-status-by-ctpv-popup-page";
|
||||
|
||||
export default function AgedPipeStatusByCtpvPopupContent() {
|
||||
return (
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import DredgingDetailPopupPage from "@/app/(with-base-layout)/oper/dredging/components/DredgingDetailPopupPage";
|
||||
import DredgingDetailPopupPage from "@/features/dredging/ui/dredging-detail-popup-page";
|
||||
|
||||
import { postPopupMessage } from "../lib/popupMessage";
|
||||
import { postPopupMessage } from "../lib/popup-message";
|
||||
import { WINDOW_POPUP_MESSAGE_TYPE } from "../model/types";
|
||||
import type { WindowPopupContentProps } from "../model/types";
|
||||
import { buildDredgingPopupRecord } from "./dredgingPopupRecord";
|
||||
import { buildDredgingPopupRecord } from "./dredging-popup-record";
|
||||
|
||||
/** 상세 화면과 같은 구조에서 선택 관로의 사진·위치·준설일자를 수정한다. */
|
||||
export default function DredgingEditPopupContent({
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user