Merge branch 'iipbs/sn/dev' of https://www.onasys.co.kr:3000/ONAANDALL/frontend into iipbs/sn/dev

# Conflicts:
#	apps/sn/src/features/windowPopup/model/popupDefinitions.ts
#	apps/sn/src/features/windowPopup/registry.tsx
This commit is contained in:
2026-08-05 16:24:52 +09:00
55 changed files with 4173 additions and 145 deletions
@@ -9,6 +9,7 @@ import type {
ExmnImportValidationResult,
ExmnJobType,
ExmnPage,
ExmnPipeReportAvailability,
ExmnSectionSummaryRow,
ExmnTemplateResult,
PplFacility,
@@ -285,7 +286,25 @@ export const downloadExmnReportTemplate = async (): Promise<Blob> =>
export const downloadExmnBusinessReport = async (attachmentId: string): Promise<Blob> =>
getBlobData(`/attach-service/api/v1/download/${encodeURIComponent(attachmentId)}`);
/** 저장된 페이지 범위를 이용해 선택 관로의 조사보고서 구간만 PDF로 조회한다. */
export const downloadExmnPipeReport = async (
exmnBizId: string,
pipeNumber: string,
): Promise<Blob> =>
getBlobData(
`${EXMN_BUSINESS_API_PATH}/${encodeURIComponent(exmnBizId)}/pipeReports/${encodeURIComponent(pipeNumber)}`,
);
/** 사업 파일별 첨부서비스 키 쌍을 조사사업에 연결한다. */
/** 팝업 생성 전에 선택 관로번호가 등록된 관로 PDF에 포함되는지 확인한다. */
export const getExmnPipeReportAvailability = async (
exmnBizId: string,
pipeNumber: string,
): Promise<ExmnPipeReportAvailability> =>
getData(
`${EXMN_BUSINESS_API_PATH}/${encodeURIComponent(exmnBizId)}/pipeReports/${encodeURIComponent(pipeNumber)}/availability`,
) as Promise<ExmnPipeReportAvailability>;
export const updateExmnAttachments = async (
exmnBizId: string,
attachments: Partial<Record<ExmnFileType, ExmnAttachmentKey>>,
@@ -8,7 +8,7 @@ export const EXMN_MAX_FILE_SIZE = 200 * 1024 * 1024;
/** 조사사업 파일별 화면 표시명과 허용 확장자다. */
export const EXMN_FILE_RULES: Record<ExmnFileType, { label: string; extensions: string[] }> = {
EXMN_EXCEL: { label: "조사 결과", extensions: ["xlsx", "xlsm"] },
EXMN_EXCEL: { label: "조사 결과", extensions: ["xlsx"] },
PPL_EXMN_PDF: { label: "CCTV 조사 결과(관로)", extensions: ["pdf"] },
MNHL_EXMN_PDF: { label: "CCTV 조사 결과(맨홀)", extensions: ["pdf"] },
BIZ_REPORT: { label: "사업보고서", extensions: ["pdf"] },
@@ -115,6 +115,12 @@ export interface ExmnImportCommitResult {
summaryCount: number;
}
/** 선택 관로의 조사보고서 팝업을 열 수 있는지 확인한 결과다. */
export interface ExmnPipeReportAvailability {
available: boolean;
message?: string | null;
}
/** 처리분구별 PPL 조사 집계 행이다. */
export interface PplSummaryRow {
trtdstId: string;
@@ -27,6 +27,10 @@ import type { TrtdstSettingDto } from "../model/trtdst-types";
const DOWNLOAD_BUTTON_CLASS =
"rounded-sm px-4 py-2 text-sm font-medium !text-white disabled:!text-white";
const FORM_LABEL_CLASS =
"shrink-0 whitespace-nowrap text-xl font-medium text-gray-600";
const FORM_INPUT_CLASS =
"h-[3.2rem] text-base text-label";
type Notice = { type: "success" | "error" | "info"; text: string } | null;
@@ -334,7 +338,7 @@ export function ExmnBusinessRegisterPopupPage({
<Button
type="button"
color="white"
size="xs"
size="sm"
className="sn-popup-header-button"
disabled={isLoading || formLocked}
onClick={() => void handleSave()}
@@ -362,11 +366,12 @@ export function ExmnBusinessRegisterPopupPage({
<div className="space-y-4 p-4">
<div className="flex flex-nowrap items-center gap-5">
<div className="flex items-center gap-2">
<Label className="shrink-0 whitespace-nowrap text-base">
<Label className={FORM_LABEL_CLASS}>
<span className="text-red-500">* </span>사업차수
</Label>
<Input
style={{ width: "3.5rem", flex: "none" }}
className={FORM_INPUT_CLASS}
style={{ width: "6rem", flex: "none" }}
type="text"
inputMode="numeric"
maxLength={3}
@@ -379,17 +384,17 @@ export function ExmnBusinessRegisterPopupPage({
</div>
<SelectBox
label="사업년도"
labelClass="shrink-0 whitespace-nowrap text-base"
labelClass={FORM_LABEL_CLASS}
className="flex items-center gap-2"
selectClass="w-[6.5rem] bg-white"
selectClass="h-[3.2rem] w-28 rounded-lg bg-white text-label"
selectArray={getStartYearArray({ placeholder: "선택" })}
value={bizYr}
readOnly={formLocked}
onSelectValue={(value) => setBizYr(String(value))}
/>
<CtpvSggPrcsFcltSelectBox
compact
className="!mr-0 !justify-start"
selectValueClassName="text-label"
sido={ctpvCd}
sigungu={sggCd}
onSidoChange={(nextCtpvCd) => {
@@ -409,8 +414,9 @@ export function ExmnBusinessRegisterPopupPage({
}}
/>
<div className="flex items-center gap-2">
<Label className="shrink-0 whitespace-nowrap text-base"><span className="text-red-500">* </span>정밀조사 연장</Label>
<Label className={FORM_LABEL_CLASS}><span className="text-red-500">* </span>정밀조사 연장</Label>
<Input
className={FORM_INPUT_CLASS}
style={{ width: "6rem", flex: "none" }}
type="text"
inputMode="decimal"
@@ -419,12 +425,12 @@ export function ExmnBusinessRegisterPopupPage({
disabled={formLocked}
onChange={(event) => setPrcisExmnPrlg(event.target.value)}
/>
<span className="text-sm text-gray-500">km</span>
<span className="text-base font-medium text-gray-600">km</span>
</div>
</div>
<div className="flex items-center gap-3">
<Label className="w-20 shrink-0 text-base"><span className="text-red-500">* </span>사업명</Label>
<Input style={{ maxWidth: "480px" }} value={bizNm} maxLength={200} disabled={formLocked} onChange={(event) => setBizNm(event.target.value)} />
<Label className={`w-20 ${FORM_LABEL_CLASS}`}><span className="text-red-500">* </span>사업명</Label>
<Input className={FORM_INPUT_CLASS} style={{ maxWidth: "480px" }} value={bizNm} maxLength={200} disabled={formLocked} onChange={(event) => setBizNm(event.target.value)} />
</div>
</div>
</section>
@@ -403,7 +403,7 @@ export function ExmnRegistrationPage() {
/>
<div className="mr-8 flex items-center gap-2">
<Label className="whitespace-nowrap text-xl font-medium text-gray-600">사업명</Label>
<Input className="h-[3.2rem] w-52 text-base" value={draftFilters.bizNm} onChange={(event) => setDraftFilters((current) => ({ ...current, bizNm: event.target.value }))} onKeyDown={(event) => { if (event.key === "Enter") void handleSearch(); }} />
<Input className="h-[3.2rem] w-[32rem] text-base" value={draftFilters.bizNm} onChange={(event) => setDraftFilters((current) => ({ ...current, bizNm: event.target.value }))} onKeyDown={(event) => { if (event.key === "Enter") void handleSearch(); }} />
</div>
<div className="ml-auto flex shrink-0 items-center gap-2">
<Button className={ACTION_BUTTON_CLASS} size="sm" disabled={isLoading} onClick={() => void handleSearch()}>조회</Button>
@@ -26,8 +26,12 @@ import type {
ExmnImportValidationResult,
} from "../model/exmn-business-types";
const ACTION_BUTTON_CLASS =
"rounded-sm bg-blue-600 px-3 py-1.5 text-sm font-medium !text-white hover:bg-blue-700 disabled:!text-white";
const POPUP_BUTTON_SIZE_CLASS =
"h-10 w-[9.6rem] rounded-sm px-4 !text-[1.2rem] font-medium";
const POPUP_ACTION_BUTTON_CLASS =
`${POPUP_BUTTON_SIZE_CLASS} !text-white disabled:!text-white`;
const FIND_BUTTON_CLASS =
"inline-flex h-10 cursor-pointer items-center justify-center rounded-sm bg-blue-600 px-3 !text-[1.2rem] font-medium !text-white hover:bg-blue-700";
const FILE_TYPES: ExmnFileType[] = [
"EXMN_EXCEL",
@@ -283,7 +287,7 @@ export function ExmnResultRegisterPopupPage({
...current,
[fileType]: [validationMessage],
}));
setNotice({ type: "error", text: validationMessage });
setNotice(null);
return;
}
@@ -303,16 +307,7 @@ export function ExmnResultRegisterPopupPage({
...current,
[fileType]: result.errors.map((item) => item.message),
}));
const visibleErrors = result.errors.slice(0, 5).map((item) => item.message);
if (result.errors.length > visibleErrors.length) {
visibleErrors.push(`외 ${result.errors.length - visibleErrors.length}건`);
}
setNotice(result.valid
? null
: {
type: "error",
text: `검토 오류 ${result.errors.length}건\n${visibleErrors.join("\n")}`,
});
setNotice(null);
} catch (error) {
const message = error instanceof Error ? error.message : "조사파일 검토 중 오류가 발생했습니다.";
setValidationResults((current) => {
@@ -325,10 +320,7 @@ export function ExmnResultRegisterPopupPage({
...current,
[fileType]: [message],
}));
setNotice({
type: "error",
text: message,
});
setNotice(null);
} finally {
setIsLoading(false);
}
@@ -375,8 +367,8 @@ export function ExmnResultRegisterPopupPage({
<Button
type="button"
color="white"
size="xs"
className="sn-popup-header-button"
size="sm"
className="sn-popup-header-button h-10 w-auto px-3 !text-[1.2rem]"
disabled={
isLoading
|| !excelValidation?.valid
@@ -392,7 +384,7 @@ export function ExmnResultRegisterPopupPage({
<section className="flex min-h-0 flex-1 flex-col gap-2 overflow-x-hidden overflow-y-auto px-4 pb-3 pt-3">
{notice && notice.type !== "success" && (
<div role="alert" className={`whitespace-pre-line rounded border px-4 py-3 text-sm ${
<div role="alert" className={`whitespace-pre-line rounded border px-4 py-3 text-[1.3rem] ${
notice.type === "error"
? "border-red-200 bg-red-50 text-red-700"
: notice.type === "success"
@@ -407,30 +399,30 @@ export function ExmnResultRegisterPopupPage({
>
<div className="flex min-w-0 flex-wrap items-center gap-x-7 gap-y-2">
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-[1.05rem] font-medium text-label">사업차수</span>
<span className="whitespace-nowrap text-[1.05rem] font-semibold text-foreground">
<span className="whitespace-nowrap text-xl font-medium text-gray-600">사업차수</span>
<span className="whitespace-nowrap text-[1.3rem] font-semibold text-black">
{detail?.bizCycl ?? businessSummary.bizCycl ?? "-"}차
</span>
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-[1.05rem] font-medium text-label">사업년도</span>
<span className="whitespace-nowrap text-[1.05rem] font-semibold text-foreground">
<span className="whitespace-nowrap text-xl font-medium text-gray-600">사업년도</span>
<span className="whitespace-nowrap text-[1.3rem] font-semibold text-black">
{detail?.bizYr ?? businessSummary.bizYr ?? "-"}
</span>
</div>
<div className="flex shrink-0 items-center gap-2">
<span className="whitespace-nowrap text-[1.05rem] font-medium text-label">행정구역</span>
<span className="whitespace-nowrap text-xl font-medium text-gray-600">행정구역</span>
<span
className="max-w-[22rem] truncate text-[1.05rem] font-semibold text-foreground"
className="max-w-[22rem] truncate text-[1.3rem] font-semibold text-black"
title={`${detail?.ctpvNm ?? businessSummary.ctpvNm} ${detail?.sggNm ?? businessSummary.sggNm}`}
>
{detail?.ctpvNm ?? businessSummary.ctpvNm} {detail?.sggNm ?? businessSummary.sggNm}
</span>
</div>
<div className="flex min-w-[24rem] flex-1 items-center gap-2">
<span className="shrink-0 whitespace-nowrap text-[1.05rem] font-medium text-label">사업명</span>
<span className="shrink-0 whitespace-nowrap text-xl font-medium text-gray-600">사업명</span>
<span
className="min-w-0 truncate text-[1.05rem] font-semibold text-foreground"
className="min-w-0 truncate text-[1.3rem] font-semibold text-black"
title={detail?.bizNm ?? businessSummary.bizNm}
>
{detail?.bizNm ?? businessSummary.bizNm ?? "-"}
@@ -441,7 +433,7 @@ export function ExmnResultRegisterPopupPage({
<section className="overflow-hidden border border-border">
<div
className="grid items-center gap-3 bg-[#eaf3fb] px-3 py-2.5 text-center text-sm font-semibold text-title"
className="grid items-center gap-3 bg-[#eaf3fb] px-3 py-2.5 text-center text-[1.3rem] font-medium text-label"
style={{ gridTemplateColumns: "180px minmax(0, 1fr) 80px 112px" }}
>
<span>파일 구분</span><span>선택 파일</span><span>찾기</span><span>데이터 검토</span>
@@ -455,15 +447,15 @@ export function ExmnResultRegisterPopupPage({
return (
<div
key={fileType}
className="grid items-center gap-3 border-t border-border px-3 py-3 text-sm"
className="grid items-center gap-3 border-t border-border px-3 py-3 text-[1.3rem] text-label"
style={{ gridTemplateColumns: "180px minmax(0, 1fr) 80px 112px" }}
>
<label htmlFor={inputId} className="font-medium text-gray-700">
{(fileType === "PPL_EXMN_PDF" || fileType === "MNHL_EXMN_PDF") && <span className="text-red-500">* </span>}
<label htmlFor={inputId} className="font-medium text-gray-600">
{(fileType === "EXMN_EXCEL" || fileType === "PPL_EXMN_PDF" || fileType === "MNHL_EXMN_PDF") && <span className="text-red-500">* </span>}
{rule.label}
</label>
<div
className={`flex min-w-0 items-center gap-2 border px-3 py-1.5 ${
className={`flex min-w-0 items-center gap-2 rounded-md border px-3 py-1.5 ${
validationStatus === "success"
? "border-emerald-300 bg-emerald-50 font-semibold text-emerald-700"
: validationStatus === "error"
@@ -492,11 +484,11 @@ export function ExmnResultRegisterPopupPage({
disabled={isLoading}
onChange={(event) => handleFileChange(fileType, event.target.files)}
/>
<label htmlFor={inputId} className="inline-flex cursor-pointer rounded-sm bg-blue-600 px-3 py-1.5 font-medium text-white hover:bg-blue-700">찾기</label>
<label htmlFor={inputId} className={FIND_BUTTON_CLASS}>찾기</label>
</div>
<div className="text-center">
{canValidate ? (
<Button className={ACTION_BUTTON_CLASS} size="sm" disabled={isLoading} onClick={() => void handleValidate(fileType)}>데이터 검토</Button>
<Button color="green" className={POPUP_ACTION_BUTTON_CLASS} size="sm" disabled={isLoading} onClick={() => void handleValidate(fileType)}>데이터 검토</Button>
) : <span className="text-gray-400">-</span>}
</div>
</div>
@@ -506,9 +498,8 @@ export function ExmnResultRegisterPopupPage({
{visibleValidationTypes.length > 0 && (
<section className="overflow-hidden border border-border" aria-label="데이터 검토 내역">
<div className="flex items-center justify-between bg-[#eaf3fb] px-3 py-2.5">
<h2 className="text-sm font-semibold text-title">데이터 검토 내역</h2>
<span className="text-xs text-label">파일별로 실제 확인한 항목입니다.</span>
<div className="flex items-center bg-[#eaf3fb] px-3 py-2.5">
<h2 className="text-[1.3rem] font-medium text-label">데이터 검토 내역</h2>
</div>
{visibleValidationTypes.map((fileType) => {
const status = fileValidationStatuses[fileType]!;
@@ -523,10 +514,10 @@ export function ExmnResultRegisterPopupPage({
return (
<div
key={fileType}
className="grid items-start gap-3 border-t border-border px-3 py-2.5 text-sm"
className="grid items-start gap-3 border-t border-border px-3 py-2.5 text-[1.3rem] text-label"
style={{ gridTemplateColumns: "180px 88px minmax(0, 1fr)" }}
>
<span className="font-medium text-gray-700">
<span className="font-medium text-gray-600">
{EXMN_FILE_RULES[fileType].label}
</span>
<span className={`inline-flex w-fit rounded-full px-2.5 py-1 text-xs font-semibold ${
@@ -538,9 +529,9 @@ export function ExmnResultRegisterPopupPage({
</span>
<div className="min-w-0">
{status === "success" && countText && (
<p className="mb-1 font-medium text-foreground">{countText}</p>
<p className="mb-1 font-medium text-label">{countText}</p>
)}
<p className="leading-5 text-gray-600">
<p className="leading-5 text-label">
{guide?.checkedItems.join(" · ")}
</p>
{guide?.pendingNote && (
@@ -560,7 +551,7 @@ export function ExmnResultRegisterPopupPage({
)}
{uploadStatus && (
<p className="text-right text-sm text-blue-700">{uploadStatus}</p>
<p className="text-right text-[1.3rem] text-blue-700">{uploadStatus}</p>
)}
</section>
</main>
@@ -241,8 +241,21 @@ export function ExmnStatusDetailPanel({ business }: ExmnStatusDetailPanelProps)
));
};
const showMapPendingNotice = () => {
setNotice({ type: "info", text: "지도보기는 현재 보류 기능이며 버튼 진입점만 표시합니다." });
/** 선택 사업의 행정구역·사업차수·현재 조사유형을 하수관망도 초기 조회 계약으로 전달한다. */
const openExmnMap = () => {
if (!business) return;
const query = new URLSearchParams({
exmnBizId: business.exmnBizId,
ctpvNm: business.ctpvNm,
sggNm: business.sggNm,
exmnJobType: jobType,
});
if (business.bizCycl != null) query.set("bizCycl", String(business.bizCycl));
if (selectedSummaryRow) {
query.set("trtdstId", selectedSummaryRow.trtdstId);
query.set("trtdstNm", selectedSummaryRow.trtdstNm);
}
window.location.assign(`/map?${query.toString()}`);
};
/** 현재 조사유형의 종합집계와 처리분구별 전체 상세 시트를 서버 XLSX로 내려받는다. */
@@ -359,7 +372,13 @@ export function ExmnStatusDetailPanel({ business }: ExmnStatusDetailPanelProps)
>
상세보기
</Button>
<Button className={ACTION_BUTTON_CLASS} size="sm" onClick={showMapPendingNotice}>지도보기</Button>
<Button
className={ACTION_BUTTON_CLASS}
size="sm"
onClick={openExmnMap}
>
지도보기
</Button>
<Button
color="green"
className={DOWNLOAD_BUTTON_CLASS}
@@ -66,7 +66,6 @@ const FIXED_COLUMNS = [
const REPORT_COLUMN_LEFT = 0;
const PIPE_COLUMN_LEFT = FIXED_COLUMNS[0].width;
const STICKY_COLUMN_COUNT = 2;
const PPL_FIXED_COLUMN_COUNT = 9;
const STICKY_DIVIDER_SHADOW = "2px 0 0 #b8c5d1";
const SEVERITY_COLUMN_WIDTH = 52;
type ExmnDetailFixedColumnId = (typeof FIXED_COLUMNS)[number]["id"];
@@ -183,13 +182,8 @@ export function ExmnSurveyDetailPopupPage({
);
const selectedTrtdstNm = selectedDistrict?.trtdstNm
?? (selectedTrtdstId === trtdstId ? trtdstNm : "");
/** 관로는 등급을 본단위구간에서 표시하고, 맨홀 전체표만 구조·운영 등급 열을 추가한다. */
const fixedColumns = useMemo(
() => jobType === "PPL"
? FIXED_COLUMNS.slice(0, PPL_FIXED_COLUMN_COUNT)
: FIXED_COLUMNS,
[jobType],
);
/** 관로·맨홀 모두 확정 계산된 구조·운영 내부결함 등급을 공통 고정 열로 표시한다. */
const fixedColumns = FIXED_COLUMNS;
const summaryLabelColumnCount = 7;
const fixedInfoScrollThreshold = useMemo(
() => fixedColumns
@@ -236,7 +230,7 @@ export function ExmnSurveyDetailPopupPage({
row.pipeNo.toLocaleLowerCase("ko-KR").includes(normalizedKeyword),
);
}, [appliedDetailNumberKeyword, scopedRows]);
/** 본단위구간 최초 진입은 전체를 표시하고, 관리번호가 있으면 부분 일치로 좁힌다. */
/** 본단위구간 최초 진입은 전체를 표시하고, 관로번호가 있으면 부분 일치로 좁힌다. */
const unitRows = useMemo(() => {
if (!isUnitMode) return [];
const normalizedKeyword = appliedDetailNumberKeyword.trim().toLocaleLowerCase("ko-KR");
@@ -399,7 +393,7 @@ export function ExmnSurveyDetailPopupPage({
setNotice(null);
};
/** 모드를 바꾸면 이전 표의 관리번호·정렬·안내 상태를 초기화한다. */
/** 모드를 바꾸면 이전 표의 관로번호·정렬·안내 상태를 초기화한다. */
const handleDetailModeChange = (nextMode: ExmnPplDetailMode) => {
if (nextMode === detailMode) return;
setDetailMode(nextMode);
@@ -454,16 +448,12 @@ export function ExmnSurveyDetailPopupPage({
[rows],
);
/** 고정 열의 합산값이며 구조·운영 등급 합계는 맨홀 전체표에만 표시한다. */
/** 고정 열의 합산값이며 관로·맨홀 모두 구조·운영 등급 합계를 표시한다. */
const fixedSummaryValues = [
{ key: "extensionM", value: formatNumber(totals.extensionM) },
{ key: "drivingDistanceM", value: formatNumber(totals.drivingDistanceM) },
...(jobType === "MNHL"
? [
{ key: "structuralGrade", value: formatNumber(totals.structuralGrade) },
{ key: "operationalGrade", value: formatNumber(totals.operationalGrade) },
]
: []),
{ key: "structuralGrade", value: formatNumber(totals.structuralGrade) },
{ key: "operationalGrade", value: formatNumber(totals.operationalGrade) },
];
/** 현재 보이는 구조·운영 결함 열만 기준으로 대·중·소 소계와 항목별 합계를 계산한다. */
@@ -582,12 +572,10 @@ export function ExmnSurveyDetailPopupPage({
extensionM: "연장(m)",
drivingDistanceM: "주행거리(m)",
};
if (jobType === "MNHL") {
Object.assign(detailHeaderMapping, {
structuralGrade: "구조적 내부결함",
operationalGrade: "운영적 내부결함",
});
}
Object.assign(detailHeaderMapping, {
structuralGrade: "구조적 내부결함",
operationalGrade: "운영적 내부결함",
});
Object.assign(detailHeaderMapping, {
anomalyL: "이상항목 합계-대",
anomalyM: "이상항목 합계-중",
@@ -613,12 +601,10 @@ export function ExmnSurveyDetailPopupPage({
extensionM: row.extensionM,
drivingDistanceM: row.drivingDistanceM,
};
if (jobType === "MNHL") {
Object.assign(result, {
structuralGrade: row.structuralGrade,
operationalGrade: row.operationalGrade,
});
}
Object.assign(result, {
structuralGrade: row.structuralGrade,
operationalGrade: row.operationalGrade,
});
Object.assign(result, {
anomalyL: anomalyTotals.L,
anomalyM: anomalyTotals.M,
@@ -654,16 +640,14 @@ export function ExmnSurveyDetailPopupPage({
extensionM: totals.extensionM,
drivingDistanceM: totals.drivingDistanceM,
};
if (jobType === "MNHL") {
Object.assign(subtotalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(totalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
}
Object.assign(subtotalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(totalRow, {
structuralGrade: totals.structuralGrade,
operationalGrade: totals.operationalGrade,
});
Object.assign(subtotalRow, {
anomalyL: defectSummary.anomalySubtotals.L,
anomalyM: defectSummary.anomalySubtotals.M,
@@ -797,11 +781,11 @@ export function ExmnSurveyDetailPopupPage({
</label>
<label className="sn-popup-field" style={{ width: "300px" }}>
<div className="sn-popup-field-label">관리번호</div>
<div className="sn-popup-field-label">관로번호</div>
<Input
className="sn-popup-input !text-[1.1rem]"
value={detailNumberKeyword}
placeholder="관리번호 입력"
placeholder="관로번호 입력"
onChange={(event) => setDetailNumberKeyword(event.target.value)}
onKeyDown={(event) => {
if (event.key === "Enter") handleSearch();
@@ -899,7 +883,7 @@ export function ExmnSurveyDetailPopupPage({
<div className="flex shrink-0 items-center gap-7 whitespace-nowrap text-[1.05rem] text-label">
{isUnitMode ? (
<>
<span><strong className="mr-2 text-foreground">관리번호</strong>{appliedDetailNumberKeyword || "전체"}</span>
<span><strong className="mr-2 text-foreground">관로번호</strong>{appliedDetailNumberKeyword || "전체"}</span>
<span><strong className="mr-2 text-foreground">단위구간</strong>{unitSectionCount.toLocaleString("ko-KR")}개</span>
</>
) : (
@@ -927,7 +911,7 @@ export function ExmnSurveyDetailPopupPage({
rows={unitRows}
emptyMessage={
appliedDetailNumberKeyword
? "입력한 관리번호에 해당하는 본단위구간이 없습니다."
? "입력한 관로번호에 해당하는 본단위구간이 없습니다."
: "조회된 본단위구간이 없습니다."
}
/>
@@ -0,0 +1,60 @@
import type {
ObsltPplBusiness,
ObsltPplBusinessSaveRequest,
ObsltPplImportResult,
ObsltPplPage,
} from "../model/obslt-ppl-types";
import {
deleteData,
getBlobData,
getData,
postRawJson,
putData,
} from "@/components/lib/api";
const API_PATH = "v1/obsltPplBiz";
/** 공통 응답 래퍼가 있는 JSON 응답에서 data를 안전하게 꺼낸다. */
const unwrapData = <T>(body: unknown): T => {
if (body && typeof body === "object" && "data" in body) {
return (body as { data: T }).data;
}
return body as T;
};
/** 목록 검색조건과 페이지 번호로 활성 사업 목록을 조회한다. */
export const getObsltPplBusinesses = async (params: URLSearchParams): Promise<ObsltPplPage> =>
getData(`${API_PATH}?${params.toString()}`) as Promise<ObsltPplPage>;
/** 수정 화면에서 사업 상세 한 건을 조회한다. */
export const getObsltPplBusiness = async (id: string): Promise<ObsltPplBusiness> =>
getData(`${API_PATH}/${encodeURIComponent(id)}`) as Promise<ObsltPplBusiness>;
/** 등록 화면의 입력값으로 사업 한 건을 생성한다. */
export const createObsltPplBusiness = async (
request: ObsltPplBusinessSaveRequest,
): Promise<ObsltPplBusiness> =>
unwrapData<ObsltPplBusiness>(await postRawJson(API_PATH, request));
/** 수정 화면의 입력값으로 사업 한 건을 갱신한다. */
export const updateObsltPplBusiness = async (
id: string,
request: ObsltPplBusinessSaveRequest,
): Promise<ObsltPplBusiness> =>
putData(`${API_PATH}/${encodeURIComponent(id)}`, request) as Promise<ObsltPplBusiness>;
/** 수정 화면에서 선택 사업을 논리삭제한다. */
export const deleteObsltPplBusiness = async (id: string): Promise<void> => {
await deleteData(`${API_PATH}/${encodeURIComponent(id)}`);
};
/** 브라우저에서 파싱한 두 시트 JSON을 활성 스냅샷으로 교체 저장한다. */
export const uploadObsltPplExcel = async (
rows: ObsltPplBusinessSaveRequest[],
): Promise<ObsltPplImportResult> =>
unwrapData<ObsltPplImportResult>(await postRawJson(`${API_PATH}/excel/upload`, rows));
/** 현재 활성 자료를 원본과 호환되는 xlsx로 내려받는다. */
export const downloadObsltPplExcel = async (): Promise<Blob> =>
getBlobData(`${API_PATH}/excel/download`);
@@ -0,0 +1,187 @@
import * as XLSX from "xlsx";
import type { ObsltPplBusinessSaveRequest } from "../model/obslt-ppl-types";
type BusinessType = ObsltPplBusinessSaveRequest["bizSe"];
type SheetContract = {
sheetName: BusinessType;
businessCodeHeader: string;
extensionHeader: string;
progressHeader: string;
startDateHeader: string;
};
const SHEET_CONTRACTS: SheetContract[] = [
{
sheetName: "정밀조사",
businessCodeHeader: "정밀조사사업코드",
extensionHeader: "조사연장(km)",
progressHeader: "정밀조사추진현황",
startDateHeader: "착수(예정)일자(yyyy.mm.dd)",
},
{
sheetName: "정비사업",
businessCodeHeader: "정비사업사업코드",
extensionHeader: "정비연장(km)",
progressHeader: "정비사업추진현황",
startDateHeader: "착공(예정)일자(yyyy.mm.dd)",
},
];
const DATA_START_ROW_INDEX = 7;
const FIRST_DATA_COLUMN_INDEX = 1;
const DATA_COLUMN_COUNT = 21;
/** 줄바꿈과 공백이 포함된 병합 헤더를 비교 가능한 문자열로 정규화한다. */
const normalizeHeader = (value: string) => value.replace(/\s+/g, "").trim();
/** SheetJS 셀의 화면 표시값을 원본 양식과 같은 문자열로 읽는다. */
const cellText = (sheet: XLSX.WorkSheet, rowIndex: number, columnIndex: number) => {
const cell = sheet[XLSX.utils.encode_cell({ r: rowIndex, c: columnIndex })];
return cell ? XLSX.utils.format_cell(cell).trim() : "";
};
/** 새 업로드 양식의 공통·업무별 핵심 헤더가 정확한 위치에 있는지 확인한다. */
const validateHeaders = (sheet: XLSX.WorkSheet, contract: SheetContract) => {
const expectedHeaders: Array<[number, number, string]> = [
[5, 1, "순번"], [5, 2, "정밀조사차수"], [5, 3, contract.businessCodeHeader],
[5, 4, "시도"], [5, 5, "시군"], [5, 6, "환경청"], [5, 7, "사업명"],
[5, 8, "추진현황"], [5, 9, "착수년도"], [5, 10, "준공(예정)년도"],
[5, 11, contract.extensionHeader], [6, 11, "계획연장(km)"],
[6, 12, "상반기(예상)연장(km)"], [6, 13, "잔여연장(km)"],
[6, 14, "증빙서류제출여부"], [5, 15, contract.progressHeader],
[6, 15, contract.startDateHeader], [6, 16, "준공(예정)일자(yyyy.mm.dd)"],
[5, 17, "사업추진부진사유"], [5, 18, "사업담당자(지자체)"],
[6, 18, "이름"], [6, 19, "연락처"], [5, 20, "비고"], [6, 21, "공단의견"],
];
for (const [rowIndex, columnIndex, expected] of expectedHeaders) {
const actual = normalizeHeader(cellText(sheet, rowIndex, columnIndex));
if (actual !== normalizeHeader(expected)) {
const address = XLSX.utils.encode_cell({ r: rowIndex, c: columnIndex });
throw new Error(
`${contract.sheetName} 시트 ${address} 헤더가 올바르지 않습니다. 기대값: '${expected}', 실제값: '${actual || "(빈 값)"}'`,
);
}
}
};
/** 빈 셀과 대시 표기를 API의 null 값으로 정규화한다. */
const optionalText = (value: string): string | null => {
const normalized = value.trim();
return !normalized || normalized === "-" ? null : normalized;
};
/** 필수 문자열을 검사하고 시트·행이 포함된 오류를 제공한다. */
const requiredText = (value: string, sheetName: string, rowNumber: number, fieldName: string) => {
const normalized = optionalText(value);
if (!normalized) throw new Error(`${sheetName} 시트 ${rowNumber}행의 ${fieldName} 값은 필수입니다.`);
return normalized;
};
/** 순번 셀을 안전한 정수로 변환한다. */
const optionalInteger = (value: string, sheetName: string, rowNumber: number): number | null => {
const normalized = optionalText(value)?.replace(/,/g, "");
if (!normalized) return null;
const parsed = Number(normalized);
if (!Number.isSafeInteger(parsed)) {
throw new Error(`${sheetName} 시트 ${rowNumber}행의 순번 값이 정수가 아닙니다.`);
}
return parsed;
};
/** 연장 셀의 콤마와 km 단위를 제거하고 유한한 숫자로 변환한다. */
const optionalDecimal = (value: string, sheetName: string, rowNumber: number, fieldName: string): number | null => {
const normalized = optionalText(value)?.replace(/,/g, "").replace(/km/gi, "").trim();
if (!normalized) return null;
const parsed = Number(normalized);
if (!Number.isFinite(parsed)) {
throw new Error(`${sheetName} 시트 ${rowNumber}행의 ${fieldName} 값이 숫자가 아닙니다.`);
}
return parsed;
};
/** 연도 셀은 DB 계약에 맞게 최초 4자리 연도를 보존한다. */
const yearText = (value: string): string | null => {
const normalized = optionalText(value);
if (!normalized) return null;
return normalized.match(/(19|20)\d{2}/)?.[0] ?? normalized.slice(0, 4);
};
/** 혼합 날짜 표기에서 숫자를 추출하고 DB 최대 길이 8자로 제한한다. */
const dateText = (value: string): string | null => {
const normalized = optionalText(value);
if (!normalized) return null;
const digits = normalized.replace(/[^0-9]/g, "");
return (digits || normalized).slice(0, 8);
};
/** B~V가 모두 비어 있는 행은 데이터가 아닌 양식 여백으로 판단한다. */
const isEmptyDataRow = (sheet: XLSX.WorkSheet, rowIndex: number) =>
Array.from({ length: DATA_COLUMN_COUNT }, (_, offset) =>
cellText(sheet, rowIndex, FIRST_DATA_COLUMN_INDEX + offset),
).every((value) => !value.trim());
/** 한 업무 시트의 데이터행을 JSON 저장 요청으로 변환한다. */
const parseSheet = (sheet: XLSX.WorkSheet, contract: SheetContract): ObsltPplBusinessSaveRequest[] => {
validateHeaders(sheet, contract);
const range = XLSX.utils.decode_range(sheet["!ref"] ?? "A1:A1");
const result: ObsltPplBusinessSaveRequest[] = [];
for (let rowIndex = DATA_START_ROW_INDEX; rowIndex <= range.e.r; rowIndex += 1) {
if (isEmptyDataRow(sheet, rowIndex)) continue;
const values = Array.from({ length: DATA_COLUMN_COUNT }, (_, offset) =>
cellText(sheet, rowIndex, FIRST_DATA_COLUMN_INDEX + offset),
);
const rowNumber = rowIndex + 1;
const bizSeq = optionalInteger(values[0], contract.sheetName, rowNumber);
const originalBizCd = optionalText(values[2]);
const fallbackType = contract.sheetName === "정밀조사" ? "S" : "M";
result.push({
bizSe: contract.sheetName,
bizSeq,
prcisExmnCycl: optionalText(values[1]),
bizCd: originalBizCd ?? `UNASSIGNED-${fallbackType}-${bizSeq ?? rowNumber}`,
sggCd: null,
ctpvNm: optionalText(values[3]),
sigunNm: optionalText(values[4]),
envoNm: optionalText(values[5]),
bizNm: requiredText(values[6], contract.sheetName, rowNumber, "사업명"),
prplPrst: optionalText(values[7]),
bgngYr: yearText(values[8]),
cmcnYr: yearText(values[9]),
planPrlg: optionalDecimal(values[10], contract.sheetName, rowNumber, "계획연장(km)"),
frhfyrExpcPrlg: optionalDecimal(values[11], contract.sheetName, rowNumber, "상반기(예상)연장(km)"),
rmndPrlg: optionalDecimal(values[12], contract.sheetName, rowNumber, "잔여연장(km)"),
evdncDcmntSbmsnStts: optionalText(values[13]),
bgngYmd: dateText(values[14]),
cmcnYmd: dateText(values[15]),
bizPrplDlyRsnCn: optionalText(values[16]),
bizPicNm: optionalText(values[17]),
bizPicCnpl: optionalText(values[18]),
rmrkCn: optionalText(values[19]),
pbcpOpnnCn: optionalText(values[20]),
});
}
return result;
};
/** ArrayBuffer workbook을 검증·파싱하여 두 시트의 JSON 저장 요청을 반환한다. */
export const parseObsltPplWorkbook = (workbookData: ArrayBuffer | Uint8Array): ObsltPplBusinessSaveRequest[] => {
const workbook = XLSX.read(workbookData, { type: "array", cellDates: false });
const rows = SHEET_CONTRACTS.flatMap((contract) => {
const sheet = workbook.Sheets[contract.sheetName];
if (!sheet) throw new Error(`필수 시트가 없습니다: ${contract.sheetName}`);
return parseSheet(sheet, contract);
});
if (rows.length === 0) throw new Error("업로드할 사업 자료가 없습니다.");
return rows;
};
/** 사용자가 선택한 xlsx 파일을 브라우저에서 읽고 JSON 요청 목록으로 변환한다. */
export const parseObsltPplExcel = async (file: File): Promise<ObsltPplBusinessSaveRequest[]> => {
if (!file.name.toLowerCase().endsWith(".xlsx")) throw new Error("xlsx 파일만 업로드할 수 있습니다.");
return parseObsltPplWorkbook(await file.arrayBuffer());
};
@@ -0,0 +1,80 @@
type RegionOption = {
text: string;
val: string | number;
};
const normalizeRegionText = (value?: string | null) => String(value ?? "").replace(/\s+/g, " ").trim();
/** 시군구명에서 상위 시만 대표명으로 추출한다. */
export const extractObsltPplRepresentativeSigunName = (value?: string | null) => {
const normalized = normalizeRegionText(value);
if (!normalized) return "";
const cityMatch = normalized.match(/^(.+?시)\s*(.+)$/);
return cityMatch?.[1] ?? normalized;
};
/** 목록과 상세 저장에 사용할 대표 시군구명을 정규화한다. */
export const normalizeObsltPplSigunName = (value?: string | null) => {
const representative = extractObsltPplRepresentativeSigunName(value);
return representative || normalizeRegionText(value);
};
/** 선택된 시도 기준으로 대표 시군구 한 건씩만 노출할 옵션 목록을 만든다. */
export const buildObsltPplRepresentativeSggOptions = (
sggOptions: RegionOption[],
ctpvCd: string,
) => {
const representativeMap = new Map<string, RegionOption>();
sggOptions
.filter((option) => {
const optionCode = String(option.val ?? "").trim();
return ctpvCd === "0" || optionCode.startsWith(ctpvCd.slice(0, 2));
})
.forEach((option) => {
const representativeName = normalizeObsltPplSigunName(option.text);
if (!representativeName) return;
const existing = representativeMap.get(representativeName);
if (!existing || String(option.val).localeCompare(String(existing.val), "ko") < 0) {
representativeMap.set(representativeName, {
text: representativeName,
val: String(option.val),
});
}
});
return [...representativeMap.values()].sort((left, right) => left.text.localeCompare(right.text, "ko"));
};
/** 저장된 시도명으로 공통 시도 코드값을 다시 찾는다. */
export const findObsltPplCtpvCodeByName = (ctpvOptions: RegionOption[], ctpvNm?: string | null) =>
String(
ctpvOptions.find((option) => normalizeRegionText(option.text) === normalizeRegionText(ctpvNm))?.val ?? "0",
);
/** 저장된 시군구명 또는 코드에 해당하는 대표 시군구 옵션을 찾는다. */
export const findObsltPplRepresentativeSggCode = (
sggOptions: RegionOption[],
ctpvCd: string,
sigunNm?: string | null,
sggCd?: string | null,
) => {
const normalizedSigunName = normalizeObsltPplSigunName(sigunNm);
const representativeOptions = buildObsltPplRepresentativeSggOptions(sggOptions, ctpvCd);
if (normalizedSigunName) {
const matchedByName = representativeOptions.find((option) => option.text === normalizedSigunName);
if (matchedByName) return String(matchedByName.val);
}
const normalizedSggCd = String(sggCd ?? "").trim();
if (!normalizedSggCd) return "0";
const matchedRawOption = sggOptions.find((option) => String(option.val).trim() === normalizedSggCd);
if (!matchedRawOption) return "0";
return String(
representativeOptions.find((option) => option.text === normalizeObsltPplSigunName(matchedRawOption.text))?.val ?? "0",
);
};
@@ -0,0 +1,51 @@
/** 노후하수관로 정밀조사·정비사업 한 건의 API 계약이다. */
export interface ObsltPplBusiness {
obsltSwagePplBizSn: number;
bizSe: "정밀조사" | "정비사업";
bizSeq?: number | null;
prcisExmnCycl?: string | null;
bizCd: string;
sggCd?: string | null;
ctpvNm?: string | null;
sigunNm?: string | null;
envoNm?: string | null;
bizNm: string;
prplPrst?: string | null;
bgngYr?: string | null;
cmcnYr?: string | null;
planPrlg?: number | null;
frhfyrExpcPrlg?: number | null;
rmndPrlg?: number | null;
evdncDcmntSbmsnStts?: string | null;
bgngYmd?: string | null;
cmcnYmd?: string | null;
bizPrplDlyRsnCn?: string | null;
bizPicNm?: string | null;
bizPicCnpl?: string | null;
rmrkCn?: string | null;
pbcpOpnnCn?: string | null;
regDt?: string | null;
mdfcnDt?: string | null;
}
/** 등록·수정 요청에서는 서버 생성 일련번호와 감사 컬럼을 제외한다. */
export type ObsltPplBusinessSaveRequest = Omit<
ObsltPplBusiness,
"obsltSwagePplBizSn" | "regDt" | "mdfcnDt"
>;
/** Spring Data 페이지 응답의 화면 사용 필드다. */
export interface ObsltPplPage {
content: ObsltPplBusiness[];
totalElements: number;
totalPages: number;
number: number;
size: number;
}
/** Excel 교체 업로드 결과 건수를 표시한다. */
export interface ObsltPplImportResult {
importedCount: number;
precisionSurveyCount: number;
maintenanceCount: number;
}
@@ -0,0 +1,211 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { SelectBox } from "@common/business_components/ui";
import { Button, Input, Table, TableBody, TableCell, TableHead, TableRow } from "@common/components/ui";
import {
createObsltPplBusiness,
deleteObsltPplBusiness,
getObsltPplBusiness,
updateObsltPplBusiness,
} from "../api/obslt-ppl-api";
import {
buildObsltPplRepresentativeSggOptions,
findObsltPplCtpvCodeByName,
findObsltPplRepresentativeSggCode,
normalizeObsltPplSigunName,
} from "../lib/obslt-ppl-region";
import type { ObsltPplBusiness, ObsltPplBusinessSaveRequest } from "../model/obslt-ppl-types";
import LoadingOverlay from "@/components/ui/LoadingBar";
import useStore from "@/store/useStore";
type FormKey = keyof ObsltPplBusinessSaveRequest;
type FormState = Record<FormKey, string>;
const REGION_FORM_KEYS: FormKey[] = ["sggCd", "ctpvNm", "sigunNm"];
/** 등록·수정 표에서 필드 순서, 라벨, 입력 종류와 필수 여부를 한 곳에서 관리한다. */
const FIELDS: Array<{ key: FormKey; label: string; type?: "number" | "textarea"; required?: boolean; placeholder?: string }> = [
{ key: "bizSe", label: "사업구분", required: true }, { key: "bizSeq", label: "순번", type: "number" },
{ key: "prcisExmnCycl", label: "정밀조사차수" }, { key: "bizCd", label: "사업코드", required: true },
{ key: "envoNm", label: "환경청" }, { key: "bizNm", label: "사업명", required: true },
{ key: "prplPrst", label: "추진현황" }, { key: "bgngYr", label: "착수년도", placeholder: "YYYY" },
{ key: "cmcnYr", label: "준공(예정)년도", placeholder: "YYYY" }, { key: "planPrlg", label: "계획연장(km)", type: "number" },
{ key: "frhfyrExpcPrlg", label: "상반기(예상)연장(km)", type: "number" }, { key: "rmndPrlg", label: "잔여연장(km)", type: "number" },
{ key: "evdncDcmntSbmsnStts", label: "증빙서류 제출여부" }, { key: "bgngYmd", label: "착수(착공) 예정일자", placeholder: "YYYYMMDD" },
{ key: "cmcnYmd", label: "준공(예정)일자", placeholder: "YYYYMMDD" }, { key: "bizPrplDlyRsnCn", label: "사업추진 부진사유", type: "textarea" },
{ key: "bizPicNm", label: "담당자 이름" }, { key: "bizPicCnpl", label: "담당자 연락처" },
{ key: "rmrkCn", label: "비고", type: "textarea" }, { key: "pbcpOpnnCn", label: "공단의견", type: "textarea" },
];
const NUMBER_KEYS = new Set<FormKey>(["bizSeq", "planPrlg", "frhfyrExpcPrlg", "rmndPrlg"]);
/** 모든 입력을 제어 컴포넌트로 유지하기 위한 빈 폼 값을 생성한다. */
const createEmptyForm = (): FormState => Object.fromEntries(
[...FIELDS.map(({ key }) => key), ...REGION_FORM_KEYS].map((key) => [key, key === "bizSe" ? "정밀조사" : ""]),
) as FormState;
/** API 상세값을 빈 문자열 기반 화면 폼 값으로 변환한다. */
const toForm = (business: ObsltPplBusiness): FormState => {
const form = createEmptyForm();
FIELDS.forEach(({ key }) => { form[key] = String(business[key] ?? ""); });
form.sggCd = String(business.sggCd ?? "");
form.ctpvNm = String(business.ctpvNm ?? "");
form.sigunNm = normalizeObsltPplSigunName(business.sigunNm);
return form;
};
/** 숫자 입력의 빈 문자열은 null로, 나머지는 trim 문자열로 저장 요청을 만든다. */
const toRequest = (form: FormState): ObsltPplBusinessSaveRequest => Object.fromEntries(
[...FIELDS.map(({ key }) => key), ...REGION_FORM_KEYS].map((key) => {
const value = form[key].trim();
return [key, NUMBER_KEYS.has(key) ? (value === "" ? null : Number(value)) : (value === "" ? null : value)];
}),
) as unknown as ObsltPplBusinessSaveRequest;
/** 배너 등록 화면의 표형 폼 패턴을 적용한 별도 등록·수정 화면이다. */
export function ObsltPplFormPage({ id }: { id?: string }) {
const router = useRouter();
const isModify = Boolean(id);
const { ctpv, sgg, fetchCtpv, fetchSgg } = useStore();
const [form, setForm] = useState<FormState>(createEmptyForm);
const [loading, setLoading] = useState(isModify);
const [notice, setNotice] = useState("");
const [ctpvCd, setCtpvCd] = useState("0");
const [sggCd, setSggCd] = useState("0");
const ctpvOptions = useMemo(() => [{ text: "전체", val: "0", hidden: true }, ...ctpv], [ctpv]);
const representativeSggOptions = useMemo(
() => [{ text: "전체", val: "0", hidden: true }, ...buildObsltPplRepresentativeSggOptions(sgg, ctpvCd)],
[ctpvCd, sgg],
);
useEffect(() => {
if (ctpv.length === 0) void fetchCtpv();
if (sgg.length === 0) void fetchSgg();
}, [ctpv.length, fetchCtpv, fetchSgg, sgg.length]);
useEffect(() => {
if (!ctpv.length || !sgg.length) return;
const resolvedCtpvCd = findObsltPplCtpvCodeByName(ctpv, form.ctpvNm);
const nextCtpvCd = resolvedCtpvCd !== "0" ? resolvedCtpvCd : ctpvCd;
const nextSggCd = findObsltPplRepresentativeSggCode(sgg, nextCtpvCd, form.sigunNm, form.sggCd);
if (nextCtpvCd !== ctpvCd) setCtpvCd(nextCtpvCd);
if (nextSggCd !== sggCd) setSggCd(nextSggCd);
}, [ctpv, ctpvCd, form.ctpvNm, form.sggCd, form.sigunNm, sgg, sggCd]);
useEffect(() => {
if (!id) return;
setLoading(true);
getObsltPplBusiness(id).then((data) => setForm(toForm(data)))
.catch((error) => setNotice(error instanceof Error ? error.message : "상세정보를 조회하지 못했습니다."))
.finally(() => setLoading(false));
}, [id]);
/** 필수값과 숫자 형식을 화면에서 먼저 확인한 뒤 등록 또는 수정 API를 호출한다. */
const handleSave = async () => {
if (!form.bizSe || !form.bizCd.trim() || !form.bizNm.trim()) { setNotice("사업구분, 사업코드, 사업명은 필수입니다."); return; }
if (ctpvCd === "0" || sggCd === "0" || !form.ctpvNm.trim() || !form.sigunNm.trim()) { setNotice("시도와 시군구를 선택해주세요."); return; }
if ([...NUMBER_KEYS].some((key) => form[key] && !Number.isFinite(Number(form[key])))) { setNotice("순번과 물량은 숫자로 입력해주세요."); return; }
setLoading(true);
try {
if (id) await updateObsltPplBusiness(id, toRequest(form));
else await createObsltPplBusiness(toRequest(form));
window.alert(isModify ? "수정되었습니다." : "등록되었습니다.");
router.push("/oper/obsltPplBiz");
} catch (error) { setNotice(error instanceof Error ? error.message : "저장하지 못했습니다."); }
finally { setLoading(false); }
};
/** 사용자 확인 후 현재 사업을 논리삭제하고 목록으로 이동한다. */
const handleDelete = async () => {
if (!id || !window.confirm("삭제하시겠습니까?")) return;
setLoading(true);
try { await deleteObsltPplBusiness(id); window.alert("삭제되었습니다."); router.push("/oper/obsltPplBiz"); }
catch (error) { setNotice(error instanceof Error ? error.message : "삭제하지 못했습니다."); }
finally { setLoading(false); }
};
return (
<div className="card card-border !mt-6">
<LoadingOverlay isLoading={loading} />
<div className="card-header"><h3 className="text-2xl font-medium text-label">노후하수관로 사업 {isModify ? "수정" : "등록"}</h3></div>
<div className="card">
<Table variant="secondary">
<colgroup><col width="18%" /><col width="82%" /></colgroup>
<TableBody>
<TableRow>
<TableHead data-required>시군구 선택</TableHead>
<TableCell className="border">
<div className="flex flex-wrap items-center gap-3">
<SelectBox
label="시도"
className=""
labelClass="w-16 whitespace-nowrap text-[1.3rem] text-gray-600"
selectClass="w-[180px] rounded-lg bg-white"
selectArray={ctpvOptions}
value={ctpvCd}
onSelectValue={(value) => {
const nextCtpvCd = String(value);
setCtpvCd(nextCtpvCd);
setSggCd("0");
setForm((current) => ({
...current,
ctpvNm: ctpv.find((option) => String(option.val) === nextCtpvCd)?.text ?? "",
sigunNm: "",
sggCd: "",
}));
}}
/>
<SelectBox
label="시군구"
className=""
labelClass="w-20 whitespace-nowrap text-[1.3rem] text-gray-600"
selectClass="w-[220px] rounded-lg bg-white"
selectArray={representativeSggOptions}
value={sggCd}
onSelectValue={(value) => {
const nextSggCd = String(value);
const selectedOption = representativeSggOptions.find((option) => String(option.val) === nextSggCd);
setSggCd(nextSggCd);
setForm((current) => ({
...current,
sigunNm: selectedOption?.text ?? "",
sggCd: nextSggCd === "0" ? "" : nextSggCd,
}));
}}
/>
</div>
</TableCell>
</TableRow>
{FIELDS.map((field) => (
<TableRow key={field.key}>
<TableHead data-required={field.required || undefined}>{field.label}</TableHead>
<TableCell className="border">
{field.key === "bizSe" ? (
<select className="h-11 w-full rounded border bg-white px-3 text-[1.3rem]" value={form.bizSe} onChange={(e) => setForm({ ...form, bizSe: e.target.value })}><option value="정밀조사">정밀조사</option><option value="정비사업">정비사업</option></select>
) : field.type === "textarea" ? (
<textarea className="min-h-24 w-full rounded border bg-white p-3 text-[1.3rem]" value={form[field.key]} placeholder={field.placeholder} onChange={(e) => setForm({ ...form, [field.key]: e.target.value })} />
) : (
<Input className="!text-[1.3rem]" type={field.type === "number" ? "number" : "text"} step={field.type === "number" ? "any" : undefined} value={form[field.key]} placeholder={field.placeholder} onChange={(e) => setForm({ ...form, [field.key]: e.target.value })} />
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{notice && <p className="mt-3 text-sm text-red-600" role="alert">{notice}</p>}
<div className="mt-5 flex justify-end gap-2">
<Button size="sm" onClick={() => router.push("/oper/obsltPplBiz")}>목록</Button>
<Button size="sm" className="rounded-sm bg-blue-600 px-4 py-2 !text-white hover:bg-blue-700" onClick={() => void handleSave()}>저장</Button>
{isModify && <Button size="sm" className="rounded-sm bg-red-600 px-4 py-2 !text-white hover:bg-red-700" onClick={() => void handleDelete()}>삭제</Button>}
</div>
</div>
</div>
);
}
@@ -0,0 +1,391 @@
"use client";
import moment from "moment";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { SearchDiv, SearchFormLeft, SearchFormRight, SelectBox, UiTable } from "@common/business_components/ui";
import ListDiv from "@common/business_components/ui/list_div";
import { Button, Input, Label } from "@common/components/ui";
import {
getObsltPplBusinesses,
uploadObsltPplExcel,
} from "../api/obslt-ppl-api";
import { parseObsltPplExcel } from "../lib/obslt-ppl-excel";
import { buildObsltPplRepresentativeSggOptions, normalizeObsltPplSigunName } from "../lib/obslt-ppl-region";
import type { ObsltPplBusiness, ObsltPplPage } from "../model/obslt-ppl-types";
import LoadingOverlay from "@/components/ui/LoadingBar";
import useStore from "@/store/useStore";
const DEFAULT_LIST_SIZE = 10;
const ACTION_BUTTON_CLASS =
"rounded-sm bg-blue-600 px-4 py-2 text-sm font-medium !text-white hover:bg-blue-700 disabled:!text-white";
const BIZ_SE_OPTIONS = [
{ text: "전체", val: "0" },
{ text: "정밀조사", val: "정밀조사" },
{ text: "정비사업", val: "정비사업" },
];
const ALL_REGION_OPTION = { text: "전체", val: "0" };
type ObsltPplTableRow = ObsltPplBusiness & {
rowNumber: number;
};
const TABLE_HEADLIST = [
{ id: "rowNumber", title: "NO", widthPercent: 4 },
{ id: "bizSe", title: "사업구분", widthPercent: 6 },
{ id: "bizSeq", title: "순번", widthPercent: 5 },
{ id: "prcisExmnCycl", title: "정밀조사차수", widthPercent: 6 },
{ id: "bizCd", title: "사업코드", widthPercent: 7 },
//{ id: "sggCd", title: "시군구코드", widthPercent: 6 },
{ id: "ctpvNm", title: "시도", widthPercent: 6 },
{ id: "sigunNm", title: "시군", widthPercent: 6 },
{ id: "envoNm", title: "환경청", widthPercent: 8 },
{ id: "bizNm", title: "사업명", widthPercent: 16 },
{ id: "prplPrst", title: "추진현황", widthPercent: 6 },
{ id: "bgngYr", title: "착수년도", widthPercent: 5 },
{ id: "cmcnYr", title: "준공(예정)년도", widthPercent: 6 },
{ id: "planPrlg", title: "계획연장(km)", widthPercent: 6 },
{ id: "frhfyrExpcPrlg", title: "상반기(예상)연장(km)", widthPercent: 8 },
{ id: "rmndPrlg", title: "잔여연장(km)", widthPercent: 6 },
{ id: "evdncDcmntSbmsnStts", title: "증빙서류\n제출여부", widthPercent: 6 },
{ id: "bgngYmd", title: "착수일자", widthPercent: 7 },
{ id: "cmcnYmd", title: "준공(예정)일자", widthPercent: 7 },
{ id: "bizPrplDlyRsnCn", title: "사업추진 부진사유", widthPercent: 26 },
{ id: "bizPicNm", title: "담당자 이름", widthPercent: 6 },
{ id: "bizPicCnpl", title: "담당자 연락처", widthPercent: 8 },
{ id: "rmrkCn", title: "비고", widthPercent: 10 },
{ id: "pbcpOpnnCn", title: "공단\n의견", widthPercent: 2 },
];
const EMPTY_PAGE: ObsltPplPage = {
content: [],
totalElements: 0,
totalPages: 0,
number: 0,
size: DEFAULT_LIST_SIZE,
};
const DATE_FIELD_SET = new Set<keyof ObsltPplBusiness>(["bgngYmd", "cmcnYmd"]);
/** 8자리 또는 구분자가 섞인 날짜 문자열을 화면·다운로드 공통 형식으로 정규화한다. */
const formatObsltPplDate = (value?: string | null) => {
if (!value) return "";
const normalized = String(value).trim();
if (!normalized) return "";
const digits = normalized.replace(/[^0-9]/g, "");
if (digits.length === 8) {
const parsedDate = moment(digits, "YYYYMMDD", true);
return parsedDate.isValid() ? parsedDate.format("YYYY-MM-DD") : normalized;
}
const parsedDate = moment(normalized);
return parsedDate.isValid() ? parsedDate.format("YYYY-MM-DD") : normalized;
};
/** 목록 표시값을 공통 포맷으로 정리한다. */
const formatBusinessForDisplay = (row: ObsltPplBusiness): ObsltPplBusiness => ({
...row,
sigunNm: normalizeObsltPplSigunName(row.sigunNm) || null,
bgngYmd: formatObsltPplDate(row.bgngYmd) || null,
cmcnYmd: formatObsltPplDate(row.cmcnYmd) || null,
});
/** 현재 조회조건 기준 전체 목록을 내려받기용 행으로 변환한다. */
const toExcelRow = (row: ObsltPplTableRow) => ({
NO: row.rowNumber,
사업구분: row.bizSe ?? "",
순번: row.bizSeq ?? "",
정밀조사차수: row.prcisExmnCycl ?? "",
사업코드: row.bizCd ?? "",
시도: row.ctpvNm ?? "",
시군: row.sigunNm ?? "",
환경청: row.envoNm ?? "",
사업명: row.bizNm ?? "",
추진현황: row.prplPrst ?? "",
착수년도: row.bgngYr ?? "",
"준공(예정)년도": row.cmcnYr ?? "",
"계획연장(km)": row.planPrlg ?? "",
"상반기(예상)연장(km)": row.frhfyrExpcPrlg ?? "",
"잔여연장(km)": row.rmndPrlg ?? "",
증빙서류제출여부: row.evdncDcmntSbmsnStts ?? "",
착수일자: formatObsltPplDate(row.bgngYmd),
"준공(예정)일자": formatObsltPplDate(row.cmcnYmd),
사업추진부진사유: row.bizPrplDlyRsnCn ?? "",
"담당자 이름": row.bizPicNm ?? "",
"담당자 연락처": row.bizPicCnpl ?? "",
비고: row.rmrkCn ?? "",
공단의견: row.pbcpOpnnCn ?? "",
});
/** 노후하수관로 사업 목록, 검색, xlsx 업로드·다운로드 진입점을 제공한다. */
export function ObsltPplListPage() {
const router = useRouter();
const { ctpv, sgg, fetchCtpv, fetchSgg } = useStore();
const fileInputRef = useRef<HTMLInputElement>(null);
const [page, setPage] = useState(1);
const [data, setData] = useState<ObsltPplPage>(EMPTY_PAGE);
const [rows, setRows] = useState<ObsltPplTableRow[]>([]);
const [loading, setLoading] = useState(false);
const [notice, setNotice] = useState("");
const [resetPageNo, setResetPageNo] = useState(false);
// 선택박스의 코드와 API 검색에 사용하는 행정구역명을 함께 관리한다.
const [ctpvCd, setCtpvCd] = useState("0");
const [sggCd, setSggCd] = useState("0");
const [search, setSearch] = useState({ bizSe: "", ctpvNm: "", sigunNm: "", bizNm: "" });
const [appliedSearch, setAppliedSearch] = useState(search);
/** 현재 선택한 시도에 속한 시군구만 선택 후보로 제공한다. */
const availableSgg = useMemo(() => {
return buildObsltPplRepresentativeSggOptions(sgg, ctpvCd);
}, [ctpvCd, sgg]);
/** 공통 레이아웃에서 아직 지역 데이터를 불러오지 못한 경우 공통 store 조회를 보완한다. */
useEffect(() => {
if (ctpv.length === 0) void fetchCtpv();
if (sgg.length === 0) void fetchSgg();
}, [ctpv.length, fetchCtpv, fetchSgg, sgg.length]);
/** 확정 검색조건과 페이지를 서버 요청 파라미터로 변환해 목록을 갱신한다. */
const load = useCallback(async (targetPage = page, targetSearch = appliedSearch) => {
const params = new URLSearchParams({
page: String(Math.max(targetPage - 1, 0)),
size: String(DEFAULT_LIST_SIZE),
sort: "obsltSwagePplBizSn,desc",
});
Object.entries(targetSearch).forEach(([key, value]) => {
if (value.trim()) params.set(key, value.trim());
});
setLoading(true);
try {
const result = await getObsltPplBusinesses(params);
setData(result);
setRows(result.content.map((row, index) => ({
...formatBusinessForDisplay(row),
rowNumber: result.totalElements - ((targetPage - 1) * DEFAULT_LIST_SIZE + index),
})));
} catch (error) {
setNotice(error instanceof Error ? error.message : "목록을 조회하지 못했습니다.");
setData(EMPTY_PAGE);
setRows([]);
} finally {
setLoading(false);
setResetPageNo(false);
}
}, [appliedSearch, page]);
useEffect(() => {
void load();
}, [load]);
/** 선택한 xlsx를 브라우저에서 검증·파싱한 뒤 JSON으로 교체 업로드한다. */
const handleUpload = async (file?: File) => {
if (!file) return;
if (!file.name.toLowerCase().endsWith(".xlsx")) {
setNotice("xlsx 파일만 업로드할 수 있습니다.");
return;
}
setLoading(true);
try {
const parsedRows = await parseObsltPplExcel(file);
const result = await uploadObsltPplExcel(parsedRows);
setNotice(
`총 ${result.importedCount.toLocaleString()}건을 저장했습니다. (정밀조사 ${result.precisionSurveyCount.toLocaleString()}건, 정비사업 ${result.maintenanceCount.toLocaleString()}건)`,
);
setResetPageNo(true);
setPage(1);
await load(1, appliedSearch);
} catch (error) {
setNotice(error instanceof Error ? error.message : "업로드하지 못했습니다.");
} finally {
setLoading(false);
if (fileInputRef.current) fileInputRef.current.value = "";
}
};
/** 현재 조회조건 기준 전체 목록을 화면 포맷 그대로 xlsx로 내려받는다. */
const handleDownload = async () => {
setLoading(true);
try {
const params = new URLSearchParams({
page: "0",
size: String(Math.max(data.totalElements, 1)),
sort: "obsltSwagePplBizSn,desc",
});
Object.entries(appliedSearch).forEach(([key, value]) => {
if (value.trim()) params.set(key, value.trim());
});
const result = await getObsltPplBusinesses(params);
const exportRows = result.content.map((row, index) => ({
...formatBusinessForDisplay(row),
rowNumber: result.totalElements - index,
}));
const { utils, writeFileXLSX } = await import("xlsx");
const worksheet = utils.json_to_sheet(exportRows.map(toExcelRow));
const workbook = utils.book_new();
utils.book_append_sheet(workbook, worksheet, "노후하수관로");
writeFileXLSX(workbook, "노후하수관로 정밀조사 및 정비사업 현황.xlsx");
} catch (error) {
setNotice(error instanceof Error ? error.message : "엑셀을 내려받지 못했습니다.");
} finally {
setLoading(false);
}
};
/** 입력 중 조건을 실제 조회조건으로 확정하고 첫 페이지를 다시 조회한다. */
const handleSearch = async () => {
const nextSearch = { ...search };
setNotice("");
setAppliedSearch(nextSearch);
setResetPageNo(true);
if (page === 1) {
await load(1, nextSearch);
return;
}
setPage(1);
};
return (
<>
<LoadingOverlay isLoading={loading} />
<SearchDiv>
<SearchFormLeft>
<div className="flex items-center gap-4">
<div className="flex items-center space-x-2">
<div className="flex items-center">
<SelectBox
label="사업구분"
className=""
labelClass="w-20 whitespace-nowrap text-xl text-gray-600"
selectClass="w-[120px] rounded-lg bg-white"
selectArray={BIZ_SE_OPTIONS}
value={search.bizSe}
onSelectValue={(value) => setSearch((current) => ({ ...current, bizSe: String(value) }))}
/>
</div>
<div className="flex items-center">
<SelectBox
label="시도"
className=""
labelClass="w-16 whitespace-nowrap text-xl text-gray-600"
selectClass="w-[140px] rounded-lg bg-white"
selectArray={[ALL_REGION_OPTION, ...ctpv]}
value={ctpvCd}
onSelectValue={(value) => {
const nextCtpvCd = String(value);
setCtpvCd(nextCtpvCd);
setSggCd("0");
setSearch((current) => ({
...current,
ctpvNm: ctpv.find((option) => String(option.val) === nextCtpvCd)?.text ?? "",
sigunNm: "",
}));
}}
/>
</div>
<div className="flex items-center">
<SelectBox
label="시군구"
className=""
labelClass="w-20 whitespace-nowrap text-xl text-gray-600"
selectClass="w-[140px] rounded-lg bg-white"
selectArray={[ALL_REGION_OPTION, ...availableSgg]}
value={sggCd}
onSelectValue={(value) => {
const nextSggCd = String(value);
setSggCd(nextSggCd);
const selectedOption = availableSgg.find((option) => String(option.val) === nextSggCd);
setSearch((current) => ({
...current,
sigunNm: selectedOption?.text ?? "",
}));
}}
/>
</div>
<div className="flex items-center">
<Label className="w-20 text-xl text-gray-600">사업명</Label>
<Input
className="w-[220px] !text-2xl"
value={search.bizNm}
onChange={(event) => setSearch((current) => ({ ...current, bizNm: event.target.value }))}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
void handleSearch();
}
}}
/>
</div>
</div>
</div>
</SearchFormLeft>
<SearchFormRight className="ml-auto flex shrink-0 items-center justify-end px-4">
<div className="flex items-center gap-2">
<Button className={ACTION_BUTTON_CLASS} size="sm" onClick={() => void handleSearch()}>
조회
</Button>
<Button className={ACTION_BUTTON_CLASS} size="sm" onClick={() => router.push("/oper/obsltPplBiz/register")}>
등록
</Button>
<input
ref={fileInputRef}
type="file"
accept=".xlsx"
className="hidden"
onChange={(event) => void handleUpload(event.target.files?.[0])}
/>
<Button className={ACTION_BUTTON_CLASS} size="sm" onClick={() => fileInputRef.current?.click()}>
업로드
</Button>
<Button
className="rounded-sm bg-green-600 px-4 py-2 text-sm font-medium !text-white hover:bg-green-700"
size="sm"
onClick={() => void handleDownload()}
>
엑셀다운로드
</Button>
</div>
</SearchFormRight>
</SearchDiv>
{notice && (
<div role="status" className="mx-[1.2rem] mt-4 rounded border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-700">
{notice}
</div>
)}
<ListDiv className="overflow-x-auto">
<div className="w-[100%]">
<div className="card-header flex items-center justify-between">
<h3 className="text-2xl font-medium">
노후하수관로 정밀조사 및 정비사업 현황{" "}
<span className="text-base text-gray-500">({data.totalElements.toLocaleString("ko-KR")}건)</span>
</h3>
</div>
<UiTable<ObsltPplTableRow>
headName=""
headlist={TABLE_HEADLIST}
tableData={rows}
pageSize={DEFAULT_LIST_SIZE}
total={data.totalElements}
curPage={page}
widthFixed
onPageChange={setPage}
resetPageNo={resetPageNo}
cellClick={(index) => {
if (typeof index !== "number" || !rows[index]) return;
router.push(`/oper/obsltPplBiz/register/${rows[index].obsltSwagePplBizSn}`);
}}
renderCell={(row, headId) => {
if (!DATE_FIELD_SET.has(headId as keyof ObsltPplBusiness)) return undefined;
return formatObsltPplDate(row[headId as keyof ObsltPplTableRow] as string | null | undefined);
}}
/>
</div>
</ListDiv>
</>
);
}
@@ -11,7 +11,7 @@ export const windowPopupDefinitions = {
key: "exmnResultRegister",
title: "조사 결과 업로드",
width: 1000,
height: 500,
height: 650,
requiredParams: ["exmnBizId"],
},
exmnSurveyDetail: {
@@ -27,6 +27,13 @@ export const windowPopupDefinitions = {
width: 1280,
height: 900,
},
exmnPipeReport: {
key: "exmnPipeReport",
title: "관로 조사보고서",
width: 1200,
height: 850,
requiredParams: ["exmnBizId", "pipeNumber"],
},
oldPpUpload: {
key: "oldPpUpload",
title: "노후 하수관로 정비사업 등록",
@@ -129,6 +136,18 @@ export const windowPopupDefinitions = {
width: 1380,
height: 820,
},
sbmrgDngrMapPopup: {
key: "sbmrgDngrMapPopup",
title: "침수위험지도 목록",
width: 1160,
height: 720,
},
floodDngrMapPopup: {
key: "floodDngrMapPopup",
title: "도시침수지도 목록",
width: 1160,
height: 720,
},
pipeAnalysisPopup: {
key: "pipeAnalysisPopup",
title: "관로분석",
@@ -44,6 +44,8 @@ export const WINDOW_POPUP_MESSAGE_TYPE = {
FLOOD_PRE_UPLOAD_COMPLETED: "sn:popup:floodPreUploadCompleted",
MAP_SEARCH_SELECT_FEATURE: "sn:popup:mapSearchSelectFeature",
MAP_SEARCH_SHOW_MULTIPLE: "sn:popup:mapSearchShowMultiple",
MAP_SEARCH_FIT_EXTENT: "sn:popup:mapSearchFitExtent",
MAP_SEARCH_SHOW_FLOOD_GROUP: "sn:popup:mapSearchShowFloodGroup",
GIS_EDIT_SESSION_READY: "sn:popup:gisEditSessionReady",
GIS_EDIT_SESSION_SYNC: "sn:popup:gisEditSessionSync",
GIS_EDIT_SESSION_SHOW_INLINE: "sn:popup:gisEditSessionShowInline",
@@ -4,6 +4,7 @@ import AgedPipePopupContent from "./ui/AgedPipePopupContent";
import AgedPipeStatusByCtpvPopupContent from "./ui/AgedPipeStatusByCtpvPopupContent";
import DredgingRegisterPopupContent from "./ui/DredgingRegisterPopupContent";
import ExmnBusinessRegisterPopupContent from "./ui/ExmnBusinessRegisterPopupContent";
import ExmnPipeReportPopupContent from "./ui/ExmnPipeReportPopupContent";
import ExmnResultRegisterPopupContent from "./ui/ExmnResultRegisterPopupContent";
import ExmnSurveyDetailPopupContent from "./ui/ExmnSurveyDetailPopupContent";
import FloodPreTablePopupContent from "./ui/FloodPreTablePopupContent";
@@ -18,6 +19,8 @@ import ReportFilesPopupContent from "./ui/ReportFilesPopupContent";
import ReportTabPopupContent from "./ui/ReportTabPopupContent";
import SearchModalPopupContent from "./ui/SearchModalPopupContent";
import SinkholePopupContent from "./ui/SinkholePopupContent";
import SbmrgDngrMapPopupContent from "./ui/SbmrgDngrMapPopupContent";
import FloodDngrMapPopupContent from "./ui/FloodDngrMapPopupContent";
import SscDetailPopupContent from "./ui/SscDetailPopupContent";
import type { WindowPopupContentProps } from "./model/types";
import FeaturePlaceholderPopupContent from "./ui/FeaturePlaceholderPopupContent";
@@ -55,6 +58,10 @@ export const windowPopupRegistry = {
...windowPopupDefinitions.dredgingRegister,
component: DredgingRegisterPopupContent,
},
exmnPipeReport: {
...windowPopupDefinitions.exmnPipeReport,
component: ExmnPipeReportPopupContent,
},
oldPpUpload: {
...windowPopupDefinitions.oldPpUpload,
component: OldPpUploadPopupContent,
@@ -111,6 +118,14 @@ export const windowPopupRegistry = {
...windowPopupDefinitions.sinkholePopup,
component: SinkholePopupContent,
},
sbmrgDngrMapPopup: {
...windowPopupDefinitions.sbmrgDngrMapPopup,
component: SbmrgDngrMapPopupContent,
},
floodDngrMapPopup: {
...windowPopupDefinitions.floodDngrMapPopup,
component: FloodDngrMapPopupContent,
},
pipeAnalysisPopup: {
...windowPopupDefinitions.pipeAnalysisPopup,
component: PipeAnalysisPopupContent,
@@ -0,0 +1,97 @@
"use client";
import { useEffect, useState } from "react";
import { downloadExmnPipeReport } from "@/features/exmn/api/exmn-business-api";
import type { WindowPopupContentProps } from "../model/types";
const getParam = (value: string | string[] | undefined) =>
Array.isArray(value) ? value[0] ?? "" : value ?? "";
/** 공통 Blob API 오류 문자열에서 백엔드의 사용자 안내 메시지만 추출한다. */
const getReportErrorMessage = (error: unknown) => {
if (!(error instanceof Error)) {
return "관로 조사보고서를 불러오지 못했습니다.";
}
const backendMessage = error.message.match(/"message":"((?:\\.|[^"\\])*)"/)?.[1];
if (!backendMessage) return error.message;
try {
return JSON.parse(`"${backendMessage}"`) as string;
} catch {
return backendMessage;
}
};
/** 저장된 관로별 PDF 구간을 공통 WindowPopup 안에서 표시한다. */
export default function ExmnPipeReportPopupContent({
searchParams,
}: WindowPopupContentProps) {
const exmnBizId = getParam(searchParams.exmnBizId);
const pipeNumber = getParam(searchParams.pipeNumber);
const reportNo = getParam(searchParams.reportNo);
const [reportUrl, setReportUrl] = useState("");
const [errorMessage, setErrorMessage] = useState("");
useEffect(() => {
let active = true;
let objectUrl = "";
setReportUrl("");
setErrorMessage("");
void downloadExmnPipeReport(exmnBizId, pipeNumber)
.then((blob) => {
if (!active) return;
const pdfBlob =
blob.type === "application/pdf"
? blob
: new Blob([blob], { type: "application/pdf" });
objectUrl = URL.createObjectURL(pdfBlob);
setReportUrl(objectUrl);
})
.catch((error) => {
if (!active) return;
console.warn("관로 조사보고서 조회 실패:", error);
setErrorMessage(getReportErrorMessage(error));
});
return () => {
active = false;
if (objectUrl) URL.revokeObjectURL(objectUrl);
};
}, [exmnBizId, pipeNumber]);
return (
<main className="sn-popup-page">
<header className="sn-popup-header">
<h1 className="sn-popup-title">관로 조사보고서</h1>
<span className="text-[1.05rem] text-white">
관로번호 {pipeNumber}
{reportNo ? ` · 보고서번호 ${reportNo}` : ""}
</span>
</header>
<section className="min-h-0 flex-1 bg-container p-3">
{errorMessage ? (
<div className="flex h-full items-center justify-center rounded-sm border border-red-200 bg-red-50 p-6 text-center text-[1.1rem] text-red-700">
{errorMessage}
</div>
) : reportUrl ? (
<iframe
title={`${pipeNumber} 관로 조사보고서`}
src={reportUrl}
className="h-full w-full border border-border bg-white"
/>
) : (
<div className="flex h-full items-center justify-center rounded-sm border border-border bg-white text-[1.1rem] text-muted-foreground">
조사보고서를 불러오는 중입니다.
</div>
)}
</section>
</main>
);
}
@@ -0,0 +1,7 @@
import FloodDngrMapPopupPage from "@/app/(map-layout)/map/components/floodDngrMap/FloodDngrMapPopupPage";
import type { WindowPopupContentProps } from "../model/types";
/** 도시침수지도 목록 WindowPopup을 실제 목록 화면에 연결한다. */
export default function FloodDngrMapPopupContent(_props: WindowPopupContentProps) {
return <FloodDngrMapPopupPage />;
}
@@ -0,0 +1,7 @@
import SbmrgDngrMapPopupPage from "@/app/(map-layout)/map/components/sbmrgDngrMap/SbmrgDngrMapPopupPage";
import type { WindowPopupContentProps } from "../model/types";
/** 침수위험지도 목록 WindowPopup을 실제 목록 화면에 연결한다. */
export default function SbmrgDngrMapPopupContent(_props: WindowPopupContentProps) {
return <SbmrgDngrMapPopupPage />;
}