317 lines
12 KiB
TypeScript
317 lines
12 KiB
TypeScript
"use client";
|
|
|
|
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 {
|
|
downloadObsltPplExcel,
|
|
getObsltPplBusinesses,
|
|
uploadObsltPplExcel,
|
|
} from "../api/obslt-ppl-api";
|
|
import type { ObsltPplBusiness, ObsltPplPage } from "../model/obslt-ppl-types";
|
|
|
|
import { fileDownload } from "@/components/lib/utils";
|
|
import LoadingOverlay from "@/components/ui/LoadingBar";
|
|
import useStore from "@/store/useStore";
|
|
|
|
const PAGE_SIZE = 20;
|
|
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", hidden: true },
|
|
{ text: "정밀조사", val: "정밀조사" },
|
|
{ text: "정비사업", val: "정비사업" },
|
|
];
|
|
const ALL_REGION_OPTION = { text: "전체", val: "0" };
|
|
|
|
type ObsltPplTableRow = ObsltPplBusiness & {
|
|
rowNumber: number;
|
|
};
|
|
|
|
const TABLE_HEADLIST = [
|
|
{ id: "rowNumber", title: "NO" },
|
|
{ id: "bizSe", title: "사업구분" },
|
|
{ id: "bizSeq", title: "순번" },
|
|
{ id: "prcisExmnCycl", title: "정밀조사차수" },
|
|
{ id: "bizCd", title: "사업코드" },
|
|
{ id: "sggCd", title: "시군구코드" },
|
|
{ id: "ctpvNm", title: "시도" },
|
|
{ id: "sigunNm", title: "시군" },
|
|
{ id: "envoNm", title: "환경청" },
|
|
{ id: "bizNm", title: "사업명" },
|
|
{ id: "prplPrst", title: "추진현황" },
|
|
{ id: "bgngYr", title: "착수년도" },
|
|
{ id: "cmcnYr", title: "준공(예정)년도" },
|
|
{ id: "planPrlg", title: "계획 연장(km)" },
|
|
{ id: "frhfyrExpcPrlg", title: "26.6월말 예상물량" },
|
|
{ id: "rmndPrlg", title: "잔여물량" },
|
|
{ id: "evdncDcmntSbmsnStts", title: "증빙서류 제출여부" },
|
|
{ id: "bgngYmd", title: "착수(착공) 예정일자" },
|
|
{ id: "cmcnYmd", title: "준공(예정)일자" },
|
|
{ id: "bizPrplDlyRsnCn", title: "추진 지연사업 대상" },
|
|
{ id: "bizPicNm", title: "담당자 이름" },
|
|
{ id: "bizPicCnpl", title: "담당자 연락처" },
|
|
{ id: "rmrkCn", title: "비고" },
|
|
{ id: "pbcpOpnnCn", title: "공단의견" },
|
|
];
|
|
|
|
const EMPTY_PAGE: ObsltPplPage = {
|
|
content: [],
|
|
totalElements: 0,
|
|
totalPages: 0,
|
|
number: 0,
|
|
size: PAGE_SIZE,
|
|
};
|
|
|
|
/** 노후하수관로 사업 목록, 검색, 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(() => {
|
|
if (ctpvCd === "0") return sgg;
|
|
return sgg.filter((option) => String(option.val).startsWith(ctpvCd.slice(0, 2)));
|
|
}, [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(PAGE_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) => ({
|
|
...row,
|
|
rowNumber: result.totalElements - ((targetPage - 1) * PAGE_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를 서버 교체 업로드하고 첫 페이지를 다시 조회한다. */
|
|
const handleUpload = async (file?: File) => {
|
|
if (!file) return;
|
|
if (!file.name.toLowerCase().endsWith(".xlsx")) {
|
|
setNotice("xlsx 파일만 업로드할 수 있습니다.");
|
|
return;
|
|
}
|
|
|
|
setLoading(true);
|
|
try {
|
|
const result = await uploadObsltPplExcel(file);
|
|
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 Blob을 사용자 PC에 고정 파일명으로 저장한다. */
|
|
const handleDownload = async () => {
|
|
setLoading(true);
|
|
try {
|
|
fileDownload(await downloadObsltPplExcel(), "노후하수관로 정밀조사 및 정비사업 현황.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);
|
|
setSearch((current) => ({
|
|
...current,
|
|
sigunNm: sgg.find((option) => String(option.val) === nextSggCd)?.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="mt-4">
|
|
<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={PAGE_SIZE}
|
|
total={data.totalElements}
|
|
curPage={page}
|
|
widthFixed
|
|
className="overflow-x-auto overflow-y-auto"
|
|
onPageChange={setPage}
|
|
resetPageNo={resetPageNo}
|
|
cellClick={(index) => {
|
|
if (typeof index !== "number" || !rows[index]) return;
|
|
router.push(`/oper/obsltPplBiz/register/${rows[index].obsltSwagePplBizSn}`);
|
|
}}
|
|
/>
|
|
</ListDiv>
|
|
</>
|
|
);
|
|
}
|