Files
frontend/apps/sn/src/features/exmn/ui/PplSummaryModal.tsx
T

600 lines
20 KiB
TypeScript

"use client";
import LoadingOverlay from "@/components/ui/LoadingBar";
import {
Button,
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
Input,
} from "@common/components/ui";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
getExmnBusiness,
getPplFacilities,
getPplSummaries,
} from "../api/exmn-business-api";
import type {
ExmnBusiness,
ExmnBusinessDetail,
PplFacility,
PplSummaryRow,
} from "../model/exmn-business-types";
import { PplFacilityDetailModal } from "./PplFacilityDetailModal";
import { ExmnStandardDataTable } from "./ExmnStandardDataTable";
import { downloadExcelWithKoreanHeaders } from "@/shared/lib/download-excel";
import { fetchAllPages } from "@/shared/lib/fetch-all-pages";
import { useExmnCommonCodes } from "../lib/useExmnCommonCodes";
const SUMMARY_TABLE_HEAD = [
{ id: "trtdstNm", title: "처리분구", widthPercent: 20 },
{
id: "trgtPrlgText",
title: "대상연장(m)",
widthPercent: 13,
},
{
id: "drvngDstncText",
title: "주행거리(m)",
widthPercent: 13,
},
{
id: "pplExmnWholAnmlyArtclCnt",
title: "PPL 전체이상",
widthPercent: 14,
},
{
id: "pplExmnStrctDfcCnt",
title: "구조결함",
widthPercent: 13,
},
{
id: "pplExmnOperDfcCnt",
title: "운영결함",
widthPercent: 13,
},
{ id: "pplExmnEtcCnt", title: "기타", widthPercent: 14 },
];
const FACILITY_TABLE_HEAD = [
{ id: "trtdstNm", title: "처리분구", widthPercent: 13 },
{ id: "rptpNo", title: "보고서번호", widthPercent: 12 },
{
id: "exmnFcltyGisMngNo",
title: "GIS 관로관리번호",
widthPercent: 18,
},
{ id: "upstreamDownstream", title: "상류/하류 맨홀", widthPercent: 17 },
{ id: "pipeSpec", title: "관종/규격", widthPercent: 13 },
{
id: "prlgText",
title: "연장(m)",
widthPercent: 9,
},
{
id: "strctDfcGrdCdText",
title: "구조등급",
widthPercent: 9,
},
{
id: "operDfcGrdCdText",
title: "운영등급",
widthPercent: 9,
},
];
const SUMMARY_CLICKABLE_HEAD_IDS = [
"pplExmnWholAnmlyArtclCnt",
"pplExmnStrctDfcCnt",
"pplExmnOperDfcCnt",
"pplExmnEtcCnt",
];
type Notice = { type: "success" | "error"; text: string } | null;
type PplDefectType = "ALL" | "STRUCTURAL" | "OPERATIONAL" | "ETC";
type PplFacilityFilters = {
trtdstId: string;
sectionType: string;
gisManagementNo: string;
structuralGrade: string;
operationalGrade: string;
defectType: PplDefectType;
};
const DEFAULT_PPL_FACILITY_FILTERS: PplFacilityFilters = {
trtdstId: "",
sectionType: "",
gisManagementNo: "",
structuralGrade: "",
operationalGrade: "",
defectType: "ALL",
};
interface PplSummaryModalProps {
open: boolean;
business: ExmnBusiness | null;
onOpenChange: (open: boolean) => void;
}
/** 숫자 값을 목록에서 단위 없이 천단위 구분 형식으로 표시한다. */
const formatNumber = (value: number | null | undefined) =>
Number(value ?? 0).toLocaleString("ko-KR", { maximumFractionDigits: 3 });
/** 처리분구별 PPL 집계에서 결함 수를 따라 시설 목록과 단위 상세까지 탐색하는 모달이다. */
export function PplSummaryModal({
open,
business,
onOpenChange,
}: PplSummaryModalProps) {
// 조사시설 검색 코드값은 유지하고 등급·결함분류 표시명만 CMS 기준으로 사용한다.
const { defectGradeOptions, defectTypeLabels } = useExmnCommonCodes();
const [businessDetail, setBusinessDetail] =
useState<ExmnBusinessDetail | null>(null);
const [summaryRows, setSummaryRows] = useState<PplSummaryRow[]>([]);
const [summaryTotal, setSummaryTotal] = useState(0);
const [summaryPage, setSummaryPage] = useState(0);
const [facilityRows, setFacilityRows] = useState<PplFacility[]>([]);
const [facilityTotal, setFacilityTotal] = useState(0);
const [facilityPage, setFacilityPage] = useState(0);
// 집계 건수 클릭과 상세 조회조건이 공유하는 처리분구·결함유형 컨텍스트다.
const [trtdstId, setTrtdstId] = useState("");
const [sectionType, setSectionType] = useState("");
const [gisManagementNo, setGisManagementNo] = useState("");
const [structuralGrade, setStructuralGrade] = useState("");
const [operationalGrade, setOperationalGrade] = useState("");
const [defectType, setDefectType] = useState<PplDefectType>("ALL");
const [selectedFacility, setSelectedFacility] = useState<PplFacility | null>(
null,
);
const [isLoading, setIsLoading] = useState(false);
const [notice, setNotice] = useState<Notice>(null);
const displayedSummaryRows = useMemo(
() =>
summaryRows.map((row) => ({
...row,
trgtPrlgText: formatNumber(row.trgtPrlg),
drvngDstncText: formatNumber(row.drvngDstnc),
})),
[summaryRows],
);
const displayedFacilityRows = useMemo(
() =>
facilityRows.map((row) => ({
...row,
upstreamDownstream: `${row.upstmMnhlNo || "-"} / ${row.dnstmMnhlNo || "-"}`,
pipeSpec: `${row.pptyCd || "-"} / ${row.spcfctCd || "-"}`,
prlgText: row.prlg == null ? "-" : formatNumber(row.prlg),
strctDfcGrdCdText: row.strctDfcGrdCd || "-",
operDfcGrdCdText: row.operDfcGrdCd || "-",
})),
[facilityRows],
);
/** 현재 상세 필터로 PPL 시설 페이지를 요청한다. */
const fetchFacilities = useCallback(
async (
nextPage = facilityPage,
filters: PplFacilityFilters = {
trtdstId,
sectionType,
gisManagementNo,
structuralGrade,
operationalGrade,
defectType,
},
) => {
if (!business?.exmnBizId) return;
setIsLoading(true);
setNotice(null);
try {
const page = await getPplFacilities({
exmnBizId: business.exmnBizId,
trtdstId: filters.trtdstId || undefined,
sectionType: filters.sectionType || undefined,
gisManagementNo: filters.gisManagementNo || undefined,
structuralGrade: filters.structuralGrade || undefined,
operationalGrade: filters.operationalGrade || undefined,
defectType: filters.defectType,
page: nextPage,
size: 10,
});
setFacilityRows(page.content);
setFacilityTotal(page.totalElements);
setFacilityPage(page.number);
} catch (error) {
setFacilityRows([]);
setFacilityTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 시설 조회 중 오류가 발생했습니다.",
});
} finally {
setIsLoading(false);
}
},
[
business,
defectType,
facilityPage,
gisManagementNo,
operationalGrade,
sectionType,
structuralGrade,
trtdstId,
],
);
/** 모달 진입과 집계 정렬·페이지 변경 시 사업 상세와 PPL 집계를 읽는다. */
useEffect(() => {
if (!open || !business?.exmnBizId) return;
let active = true;
setIsLoading(true);
setNotice(null);
Promise.all([
getExmnBusiness(business.exmnBizId),
getPplSummaries(business.exmnBizId, {
trtdstId: trtdstId || undefined,
page: summaryPage,
size: 10,
}),
])
.then(([detail, page]) => {
if (!active) return;
setBusinessDetail(detail);
setSummaryRows(page.content);
setSummaryTotal(page.totalElements);
})
.catch((error: unknown) => {
if (!active) return;
setSummaryRows([]);
setSummaryTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 집계 조회 중 오류가 발생했습니다.",
});
})
.finally(() => {
if (active) setIsLoading(false);
});
return () => {
active = false;
};
}, [business, open, summaryPage, trtdstId]);
/** 새 사업을 열 때 상세 필터·페이지·선택 시설을 초기화한다. */
useEffect(() => {
if (!open) return;
setSummaryPage(0);
setFacilityRows([]);
setFacilityTotal(0);
setFacilityPage(0);
setTrtdstId("");
setSectionType("");
setGisManagementNo("");
setStructuralGrade("");
setOperationalGrade("");
setDefectType("ALL");
setSelectedFacility(null);
}, [business, open]);
/** 집계의 전체·구조·운영·기타 건수를 클릭하면 해당 처리분구 시설 조회로 연결한다. */
const handleSummaryCellClick = (
index: number | undefined,
headId: string,
) => {
if (index == null) return;
const row = summaryRows[index];
if (!row) return;
const nextDefectType: PplDefectType =
headId === "pplExmnStrctDfcCnt"
? "STRUCTURAL"
: headId === "pplExmnOperDfcCnt"
? "OPERATIONAL"
: headId === "pplExmnEtcCnt"
? "ETC"
: "ALL";
setTrtdstId(row.trtdstId);
setDefectType(nextDefectType);
setFacilityPage(0);
setNotice(null);
// React 상태 반영 전 값 대신 클릭 컨텍스트로 즉시 요청한다.
setIsLoading(true);
getPplFacilities({
exmnBizId: business?.exmnBizId ?? "",
trtdstId: row.trtdstId,
sectionType: sectionType || undefined,
gisManagementNo: gisManagementNo || undefined,
structuralGrade: structuralGrade || undefined,
operationalGrade: operationalGrade || undefined,
defectType: nextDefectType,
page: 0,
size: 10,
})
.then((page) => {
setFacilityRows(page.content);
setFacilityTotal(page.totalElements);
setFacilityPage(page.number);
})
.catch((error: unknown) => {
setFacilityRows([]);
setFacilityTotal(0);
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 시설 조회 중 오류가 발생했습니다.",
});
})
.finally(() => setIsLoading(false));
};
/** 현재 처리분구 조건의 PPL 집계 엑셀을 다운로드한다. */
const handleExport = async () => {
if (!business) return;
setIsLoading(true);
setNotice(null);
try {
const result = await fetchAllPages({
fetchPage: (page, size) =>
getPplSummaries(business.exmnBizId, {
trtdstId: trtdstId || undefined,
page,
size,
}),
getItems: (page) => page.content ?? [],
getTotal: (page) => Number(page.totalElements ?? 0),
});
const excelRows = result.items.map((row) => ({
trtdstNm: row.trtdstNm,
trgtPrlg: row.trgtPrlg,
drvngDstnc: row.drvngDstnc,
pplExmnWholAnmlyArtclCnt: row.pplExmnWholAnmlyArtclCnt,
pplExmnStrctDfcCnt: row.pplExmnStrctDfcCnt,
pplExmnOperDfcCnt: row.pplExmnOperDfcCnt,
pplExmnEtcCnt: row.pplExmnEtcCnt,
}));
await downloadExcelWithKoreanHeaders({
data: excelRows as unknown as JSON[],
fileName: `${business.bizNm}_PPL집계.xlsx`,
sheetNameArray: ["처리분구별 PPL 집계"],
headerRange: "A1:G1",
headerMapping: {
trtdstNm: "처리분구",
trgtPrlg: "대상연장(m)",
drvngDstnc: "주행거리(m)",
pplExmnWholAnmlyArtclCnt: "PPL 전체이상",
pplExmnStrctDfcCnt: "구조결함",
pplExmnOperDfcCnt: "운영결함",
pplExmnEtcCnt: "기타",
},
});
} catch (error) {
setNotice({
type: "error",
text:
error instanceof Error
? error.message
: "PPL 엑셀 다운로드 중 오류가 발생했습니다.",
});
} finally {
setIsLoading(false);
}
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[94vh] w-[96vw] !max-w-[96vw] flex-col overflow-hidden !p-0">
<DialogHeader className="card-header shrink-0 !space-y-0 px-5">
<DialogTitle className="text-[1.8rem] font-semibold text-label">
PPL 조사 집계·상세
</DialogTitle>
</DialogHeader>
<div className="relative min-h-0 flex-1 space-y-5 overflow-y-auto p-4">
<LoadingOverlay isLoading={isLoading} />
{notice && (
<div
role="alert"
className={`rounded border px-4 py-3 text-sm ${notice.type === "error" ? "border-red-200 bg-red-50 text-red-700" : "border-emerald-200 bg-emerald-50 text-emerald-700"}`}
>
{notice.text}
</div>
)}
<div className="rounded border bg-secondary px-4 py-3 text-sm text-label">
<strong>{business?.bizNm ?? "선택 사업"}</strong>
<span className="mx-3 text-muted-foreground">|</span>
{business?.bizYr}년 {business?.bizCycl ?? "-"}차
<span className="mx-3 text-muted-foreground">|</span>
{business?.ctpvNm} {business?.sggNm}
</div>
<section>
<ExmnStandardDataTable
rows={
displayedSummaryRows as Array<
(typeof displayedSummaryRows)[number] &
Record<string, unknown>
>
}
title="처리분구별 PPL 집계 목록"
headlist={SUMMARY_TABLE_HEAD}
total={summaryTotal}
pageSize={10}
page={summaryPage + 1}
clickableHeadIds={SUMMARY_CLICKABLE_HEAD_IDS}
onCellClick={(_row, index, headId) =>
handleSummaryCellClick(index, headId)
}
onPageChange={(page) => setSummaryPage(page - 1)}
actions={
<Button
disabled={isLoading}
onClick={() => void handleExport()}
>
엑셀다운로드
</Button>
}
/>
</section>
<section className="rounded border border-border p-4">
<div className="grid grid-cols-1 gap-3 md:grid-cols-3">
<label className="text-sm font-medium text-label">
처리분구
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={trtdstId}
onChange={(event) => setTrtdstId(event.target.value)}
>
<option value="">전체</option>
{(businessDetail?.districts ?? []).map((district) => (
<option key={district.trtdstId} value={district.trtdstId}>
{district.trtdstNm}
</option>
))}
</select>
</label>
<label className="text-sm font-medium text-label">
구간 구분
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={sectionType}
onChange={(event) => setSectionType(event.target.value)}
>
<option value="">전체</option>
<option value="PIPE">관로</option>
<option value="UNIT">단위구간</option>
</select>
</label>
<label className="col-span-2 text-sm font-medium text-label">
GIS 관로관리번호
<Input
className="mt-1 h-10 text-base"
value={gisManagementNo}
onChange={(event) => setGisManagementNo(event.target.value)}
/>
</label>
<label className="text-sm font-medium text-label">
구조등급
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={structuralGrade}
onChange={(event) => setStructuralGrade(event.target.value)}
>
<option value="">전체</option>
{defectGradeOptions.map((grade) => (
<option key={grade.value} value={grade.value}>
{grade.label}
</option>
))}
</select>
</label>
<label className="text-sm font-medium text-label">
운영등급
<select
className="mt-1 h-10 w-full rounded border bg-background px-2"
value={operationalGrade}
onChange={(event) =>
setOperationalGrade(event.target.value)
}
>
<option value="">전체</option>
{defectGradeOptions.map((grade) => (
<option key={grade.value} value={grade.value}>
{grade.label}
</option>
))}
</select>
</label>
</div>
<div className="mt-3 flex items-center justify-between">
<span className="text-sm text-muted-foreground">
결함 분류: {defectTypeLabels[defectType] || defectType}
</span>
<Button
disabled={isLoading}
onClick={() => void fetchFacilities(0)}
>
조회
</Button>
<Button
color="white"
disabled={isLoading}
onClick={() => {
setTrtdstId(DEFAULT_PPL_FACILITY_FILTERS.trtdstId);
setSectionType(DEFAULT_PPL_FACILITY_FILTERS.sectionType);
setGisManagementNo(
DEFAULT_PPL_FACILITY_FILTERS.gisManagementNo,
);
setStructuralGrade(
DEFAULT_PPL_FACILITY_FILTERS.structuralGrade,
);
setOperationalGrade(
DEFAULT_PPL_FACILITY_FILTERS.operationalGrade,
);
setDefectType(DEFAULT_PPL_FACILITY_FILTERS.defectType);
setFacilityPage(0);
setSelectedFacility(null);
void fetchFacilities(0, DEFAULT_PPL_FACILITY_FILTERS);
}}
>
초기화
</Button>
</div>
</section>
<section>
<ExmnStandardDataTable
rows={
displayedFacilityRows as Array<
(typeof displayedFacilityRows)[number] &
Record<string, unknown>
>
}
title="PPL 시설 목록"
headlist={FACILITY_TABLE_HEAD}
total={facilityTotal}
pageSize={10}
page={facilityPage + 1}
onRowClick={(_row, index) =>
setSelectedFacility(facilityRows[index] ?? null)
}
onPageChange={(page) => void fetchFacilities(page - 1)}
scrollMode="horizontal"
minTableWidth="120rem"
/>
<p className="mt-2 text-right text-sm text-muted-foreground">
시설 행을 선택하면 단위 구간과 상태·결함 상세가 열립니다.
</p>
</section>
</div>
<DialogFooter className="card-footer shrink-0">
<Button color="white" onClick={() => onOpenChange(false)}>
닫기
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<PplFacilityDetailModal
open={Boolean(selectedFacility)}
facility={selectedFacility}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSelectedFacility(null);
}}
/>
</>
);
}