522 lines
19 KiB
TypeScript
522 lines
19 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
import { useRouter, useSearchParams } 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 {
|
|
getAllObsltPplBusinesses,
|
|
getObsltPplBusinesses,
|
|
uploadObsltPplExcel,
|
|
} from "../api/obslt-ppl-api";
|
|
import { formatDate } from "../../common/util";
|
|
import {
|
|
downloadObsltPplExcel,
|
|
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";
|
|
import { openWindowPopup } from "../../windowPopup/lib/openWindowPopup";
|
|
import { WINDOW_POPUP_MESSAGE_TYPE } from "../../windowPopup/model/types";
|
|
|
|
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;
|
|
};
|
|
type ObsltPplSearch = {
|
|
bizSe: string;
|
|
ctpvNm: string;
|
|
sigunNm: string;
|
|
bizNm: string;
|
|
};
|
|
|
|
/** 조회조건·지역 선택 코드·페이지를 목록 복귀에 사용할 URL query로 만든다. */
|
|
const createListQueryString = (
|
|
page: number,
|
|
search: ObsltPplSearch,
|
|
ctpvCd: string,
|
|
sggCd: string,
|
|
) => {
|
|
const params = new URLSearchParams();
|
|
if (page > 1) params.set("page", String(page));
|
|
Object.entries(search).forEach(([key, value]) => {
|
|
if (value.trim()) params.set(key, value.trim());
|
|
});
|
|
if (ctpvCd !== "0") params.set("ctpvCd", ctpvCd);
|
|
if (sggCd !== "0") params.set("sggCd", sggCd);
|
|
return params.toString();
|
|
};
|
|
|
|
const TABLE_HEADLIST = [
|
|
{ id: "rowNumber", title: "NO", widthPercent: 4 },
|
|
{ id: "bizSe", title: "사업구분", widthPercent: 6 },
|
|
{ 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"]);
|
|
|
|
/** 목록 표시값을 공통 포맷으로 정리한다. */
|
|
const formatBusinessForDisplay = (row: ObsltPplBusiness): ObsltPplBusiness => ({
|
|
...row,
|
|
sigunNm: normalizeObsltPplSigunName(row.sigunNm) || null,
|
|
bgngYmd: formatDate(row.bgngYmd) || null,
|
|
cmcnYmd: formatDate(row.cmcnYmd) || null,
|
|
});
|
|
|
|
/** 노후하수관로 사업 목록, 검색, xlsx 업로드·다운로드 진입점을 제공한다. */
|
|
export function ObsltPplListPage() {
|
|
const router = useRouter();
|
|
const searchParams = useSearchParams();
|
|
const { ctpv, sgg, fetchCtpv, fetchSgg } = useStore();
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
const initialSearch = useMemo<ObsltPplSearch>(
|
|
() => ({
|
|
bizSe: searchParams.get("bizSe") ?? "",
|
|
ctpvNm: searchParams.get("ctpvNm") ?? "",
|
|
sigunNm: searchParams.get("sigunNm") ?? "",
|
|
bizNm: searchParams.get("bizNm") ?? "",
|
|
}),
|
|
[searchParams],
|
|
);
|
|
const [page, setPage] = useState(() =>
|
|
Math.max(Number(searchParams.get("page")) || 1, 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(() => searchParams.get("ctpvCd") ?? "0");
|
|
const [sggCd, setSggCd] = useState(() => searchParams.get("sggCd") ?? "0");
|
|
const [appliedCtpvCd, setAppliedCtpvCd] = useState(
|
|
() => searchParams.get("ctpvCd") ?? "0",
|
|
);
|
|
const [appliedSggCd, setAppliedSggCd] = useState(
|
|
() => searchParams.get("sggCd") ?? "0",
|
|
);
|
|
const [search, setSearch] = useState<ObsltPplSearch>(initialSearch);
|
|
const [appliedSearch, setAppliedSearch] =
|
|
useState<ObsltPplSearch>(initialSearch);
|
|
|
|
/** 현재 선택한 시도에 속한 시군구만 선택 후보로 제공한다. */
|
|
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]);
|
|
|
|
/** 팝업 등록 완료 메시지를 받으면 기존 적용 조회조건을 유지한 채 첫 페이지를 재조회한다. */
|
|
useEffect(() => {
|
|
const receivePopupMessage = (event: MessageEvent) => {
|
|
if (event.origin !== window.location.origin) return;
|
|
if (event.data?.type !== WINDOW_POPUP_MESSAGE_TYPE.CFMTN_BGT_REGISTERED)
|
|
return;
|
|
const inserted = Number(event.data?.payload?.insertedCount ?? 0);
|
|
const skipped = Number(event.data?.payload?.skippedCount ?? 0);
|
|
setNotice(
|
|
`최종확정예산사업 ${inserted.toLocaleString()}건을 등록했습니다.${skipped ? ` 이미 등록된 ${skipped.toLocaleString()}건은 제외했습니다.` : ""}`,
|
|
);
|
|
setPage(1);
|
|
setResetPageNo(true);
|
|
void load(1, appliedSearch);
|
|
};
|
|
window.addEventListener("message", receivePopupMessage);
|
|
return () => window.removeEventListener("message", receivePopupMessage);
|
|
}, [appliedSearch, load]);
|
|
|
|
/** 부모 화면의 필수 사업구분을 전달하여 최종확정예산사업 선택 팝업을 연다. */
|
|
const handleOpenCfmtnBgt = () => {
|
|
if (search.bizSe !== "정밀조사" && search.bizSe !== "정비사업") {
|
|
setNotice("사업구분에서 정밀조사 또는 정비사업을 먼저 선택해 주세요.");
|
|
return;
|
|
}
|
|
const popup = openWindowPopup("cfmtnBgt", { bizSe: search.bizSe });
|
|
if (!popup)
|
|
setNotice(
|
|
"팝업이 차단되었습니다. 브라우저의 팝업 허용 설정을 확인해 주세요.",
|
|
);
|
|
};
|
|
|
|
/** 선택한 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 = "";
|
|
}
|
|
};
|
|
|
|
/** 적용된 조회조건 전체를 두 업무 시트의 업로드 호환 위치로 내려받는다. */
|
|
const handleDownload = async () => {
|
|
setLoading(true);
|
|
try {
|
|
const params = new URLSearchParams();
|
|
Object.entries(appliedSearch).forEach(([key, value]) => {
|
|
if (value.trim()) params.set(key, value.trim());
|
|
});
|
|
const exportRows = await getAllObsltPplBusinesses(params);
|
|
downloadObsltPplExcel(exportRows);
|
|
} catch (error) {
|
|
setNotice(
|
|
error instanceof Error ? error.message : "엑셀을 내려받지 못했습니다.",
|
|
);
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
/** 입력 중 조건을 실제 조회조건으로 확정하고 첫 페이지를 다시 조회한다. */
|
|
const handleSearch = async () => {
|
|
const nextSearch = { ...search };
|
|
setNotice("");
|
|
setAppliedSearch(nextSearch);
|
|
setAppliedCtpvCd(ctpvCd);
|
|
setAppliedSggCd(sggCd);
|
|
setResetPageNo(true);
|
|
const queryString = createListQueryString(1, nextSearch, ctpvCd, sggCd);
|
|
router.replace(`/oper/obsltPplBiz${queryString ? `?${queryString}` : ""}`, {
|
|
scroll: false,
|
|
});
|
|
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={() => {
|
|
const queryString = createListQueryString(
|
|
page,
|
|
appliedSearch,
|
|
appliedCtpvCd,
|
|
appliedSggCd,
|
|
);
|
|
router.push(
|
|
`/oper/obsltPplBiz/register${queryString ? `?${queryString}` : ""}`,
|
|
);
|
|
}}
|
|
>
|
|
등록
|
|
</Button>
|
|
<Button
|
|
className={ACTION_BUTTON_CLASS}
|
|
size="sm"
|
|
onClick={handleOpenCfmtnBgt}
|
|
>
|
|
최종확정예산사업
|
|
</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-[130%]">
|
|
<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={(nextPage) => {
|
|
setPage(nextPage);
|
|
const queryString = createListQueryString(
|
|
nextPage,
|
|
appliedSearch,
|
|
appliedCtpvCd,
|
|
appliedSggCd,
|
|
);
|
|
router.replace(
|
|
`/oper/obsltPplBiz${queryString ? `?${queryString}` : ""}`,
|
|
{ scroll: false },
|
|
);
|
|
}}
|
|
resetPageNo={resetPageNo}
|
|
cellClick={(index) => {
|
|
if (typeof index !== "number" || !rows[index]) return;
|
|
const queryString = createListQueryString(
|
|
page,
|
|
appliedSearch,
|
|
appliedCtpvCd,
|
|
appliedSggCd,
|
|
);
|
|
router.push(
|
|
`/oper/obsltPplBiz/register/${rows[index].obsltSwagePplBizSn}${queryString ? `?${queryString}` : ""}`,
|
|
);
|
|
}}
|
|
renderCell={(row, headId) => {
|
|
if (!DATE_FIELD_SET.has(headId as keyof ObsltPplBusiness))
|
|
return undefined;
|
|
return formatDate(
|
|
row[headId as keyof ObsltPplTableRow] as
|
|
| string
|
|
| null
|
|
| undefined,
|
|
);
|
|
}}
|
|
/>
|
|
</div>
|
|
</ListDiv>
|
|
</>
|
|
);
|
|
}
|