Files
frontend/apps/st/src/components/statistics/input/SewageReservoirPumpInp.tsx
T

1734 lines
70 KiB
TypeScript

import {
type Dispatch,
type SetStateAction,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { ValueType } from "realgrid";
import type { RealGridReact } from "realgrid-react";
import { useAlertStore, useGlobalProgressStore, useStatisticsInputToolbarGroupGate, useSearchConditionSidoList } from "@/shared/lib";
import { STATISTICS_INPUT_URL_PATH } from "@/shared/lib/stats-cd-input-navigation";
import { useStatisticsInputPendingNavigation } from "@/shared/lib/use-statistics-input-pending-navigation";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { nullableTrimmedString } from "@/components/util/input/nullableString";
import { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service";
import { statisticsInputSewageReservoirPumpApi } from "@/entities/statistics/api/input/statistics-input-sewage-reservoir-pump-service";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import {
type RainfallPumpStationItem,
type RainfallPumpStationSaveItem,
SEWAGE_RESERVOIR_STATS_CD,
type SewageReservoirItem,
type SewageReservoirRequestParams,
type SewageReservoirSaveItem,
type SewageReservoirVerificationResult,
} from "@/entities/statistics/model/input/statistics-input-sewage-reservoir-pump-interface";
import { isInputPeriodCurrent } from "@/entities/statistics/model/input/statistics-sewage-supply-rate-input-interface";
import type { StatisticsInputSubmitInfoFormData } from "@/entities/statistics/model/statistics-input-submit-info-schema";
import type {
ApiResponse,
cancelSubmitRequest,
ImrStatusResponse,
SewerageStatusInfo,
Sgg,
Sido,
} from "@/entities/statistics/model/statistics-interface";
import {
filterBySelectedAdmdstCd,
isGugunOkForToolbar,
isSubmitOkForToolbar,
resolveNoApplicableForRequest,
toInputSearchRegion,
} from "@/entities/statistics";
import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "@common/components";
import { getUserInfo } from "../../../../../../packages/common/components/src/api";
import SubmitDailog from "./SubmitDailog";
import AddArticleButton from "@/components/button/AddArticleButton";
import CancelSubmitButton from "@/components/button/CancelSubmitButton";
import DeleteArticleButton from "@/components/button/DeleteArticleButton";
import LastYearDataButton from "@/components/button/LastYearDataButton";
import NotApplicableCheckButton from "@/components/button/NotApplicableCheckButton";
import SaveButton from "@/components/button/SaveButton";
import SubmitButton from "@/components/button/SumitButton";
import VerificationResultButton from "@/components/button/VerificationResultButton";
import DataGrid from "@/components/module/DataGrid";
import { openVerificationResultDialogIfNeeded } from "@/components/module/post-submit-verification-results";
import SearchForm from "@/components/module/SearchForm";
import { VerificationResultDialog } from "@/components/module/VerificationResultDialog";
import { VerificationResultHistoryDialog } from "@/components/module/VerificationResultHistoryDialog";
import type {
CellStyleCallbackParams,
CellTooltipCallbackParams,
ColumnConfig,
ColumnInfo,
ColumnInfoList,
} from "@/components/type/DataGrid.type";
import type { SearchFormValues } from "@/components/type/SearchForm.type";
import { RainfallPumpStationInpColumn } from "@/components/util/column/input/sewageReservoirPump/RainfallPumpStationInpColumn";
import { SewageReservoirInpColumn } from "@/components/util/column/input/sewageReservoirPump/SewageReservoirInpColumn";
import { fetchColumnGuidesRecord } from "@/components/util/grid/columnGuides";
import { toGridRows } from "@/components/util/grid/gridFunction";
import {
formatCompactYmdForGrid,
normalizeOxYnValue,
toCompactYmdOrNull,
} from "@/components/util/grid/ymdFormat";
import { toExcelExportSearchContextFromSearchForm } from "@/components/util/gridExcelExport";
import {
patchFooterVerificationByTab,
patchVerificationFailedByTab,
} from "@/components/util/input/verification-failed-flag";
import type { VerificationResultLikeMap } from "@/components/util/input/verification-result-display";
import { useAdminStore } from "@/store/admin-store";
import { useTabStore } from "@/store/tab-store";
const SewageReservoirPumpInpTabList = [
SewageReservoirInpColumn,
RainfallPumpStationInpColumn,
] as ColumnInfoList[];
const toGridColumnInfo = (tab: ColumnInfoList): ColumnInfo => ({
columns: tab.columns ?? [],
columnLayout: tab.columnLayout ?? [],
});
const firstTabKey = SewageReservoirPumpInpTabList[0]?.tabKey ?? SEWAGE_RESERVOIR_STATS_CD;
const rainfallPumpTabKey =
RainfallPumpStationInpColumn.tabKey ?? "rainfallPumpStationInp";
const SEWAGE_RESERVOIR_FACILITY_NAME_GUIDE_MESSAGE =
"하수저류시설 등록시 하수저류시설명이 동일할 경우 같은 데이터로 분류됩니다.\n\n" +
"하수저류시설명이 동일 할 경우 구분을 위해 하수저류시설 1, 하수저류시설 2 형태로 구분하여 주시길 바랍니다.";
type GridRowWithVerification = Record<string, string | number> & {
verificationResult?: SewageReservoirVerificationResult;
};
type TabToolbarSnapshot = {
showSaveInToolbar: boolean;
showEnterableToolbarButtons: boolean;
showActionToolbarCard: boolean;
};
const computeTabEnterable = (
statusInfo: SewerageStatusInfo | null | undefined,
periodEnterable: boolean,
): boolean => {
if (statusInfo?.lclgvSbmsnSttsCd) {
if (["2", "3"].includes(statusInfo.lclgvSbmsnSttsCd)) {
return false;
}
return periodEnterable;
}
return periodEnterable;
};
const sidoListRef: { current: Sido[] } = { current: [] };
function buildGugunOkForToolbar(values: SearchFormValues | null): boolean {
return isGugunOkForToolbar(sidoListRef.current, values);
}
function buildSubmitOkForToolbar(values: SearchFormValues | null): boolean {
return isSubmitOkForToolbar(sidoListRef.current, values);
}
function buildNoApplicableForRequest(
values: SearchFormValues | null,
checked: boolean,
isSaveListEmpty: boolean,
): boolean {
return resolveNoApplicableForRequest(sidoListRef.current, values, checked, isSaveListEmpty);
}
function computeTabToolbarSnapshot(
statusInfo: SewerageStatusInfo | null,
hasRowData: boolean,
treatAsSearched: boolean,
searchContext: SearchFormValues | null,
periodEnterable: boolean,
isAdminInfo: boolean,
): TabToolbarSnapshot {
const gugunOk = buildGugunOkForToolbar(searchContext);
const enterable = computeTabEnterable(statusInfo, periodEnterable);
const isSubmitted = statusInfo?.lclgvSbmsnSttsCd === "2";
const showSaveInToolbar = (enterable || isAdminInfo) && periodEnterable && gugunOk;
const showEnterableToolbarButtons = enterable && gugunOk;
const showSubmittedInInputPeriodToolbar =
isSubmitted && periodEnterable && gugunOk;
const showActionToolbarCard =
(hasRowData || treatAsSearched) &&
(showSaveInToolbar ||
showEnterableToolbarButtons ||
showSubmittedInInputPeriodToolbar ||
(isSubmitted && isAdminInfo));
return { showSaveInToolbar, showEnterableToolbarButtons, showActionToolbarCard };
}
function tabRowDataExists(
m: Map<string, Record<string, string | number>[]>,
tabKey: string,
): boolean {
const rows = m.get(tabKey);
return Array.isArray(rows) && rows.length > 0;
}
function buildSewageReservoirSearchParam(
values: SearchFormValues,
overrides?: { mode?: string },
): SewageReservoirRequestParams {
const fcltNm = values.fctName?.trim();
return {
statsYr: values.year,
ctpvNm: values.sido,
...toInputSearchRegion(sidoListRef.current, values),
...(fcltNm ? { fcltNm } : {}),
...(overrides?.mode ? { mode: overrides.mode } : {}),
};
}
/** 항목 추가 시 빈 행 (`ctpvNm` = 조회 시도명) */
function createEmptySewageReservoirRow(
ctpvNm: string,
sggNm = "",
): GridRowWithVerification {
const row: GridRowWithVerification = { ctpvNm, sggNm };
for (const col of SewageReservoirInpColumn.columns) {
const fieldName = col.fieldName;
if (fieldName === "ctpvNm" || fieldName === "sggNm") continue;
row[fieldName] = col.valueType === ValueType.NUMBER ? 0 : "";
}
return row;
}
/** 빗물펌프장 탭 항목 추가 시 빈 행 */
function createEmptyRainfallPumpStationRow(
ctpvNm: string,
sggNm = "",
): GridRowWithVerification {
const row: GridRowWithVerification = { ctpvNm, sggNm };
for (const col of RainfallPumpStationInpColumn.columns) {
const fieldName = col.fieldName;
if (!fieldName) continue;
if (fieldName === "ctpvNm" || fieldName === "sggNm") continue;
row[fieldName] = col.valueType === ValueType.NUMBER ? 0 : "";
}
return row;
}
function parseSggListFromResponse(res: ApiResponse<Sgg[]>): Sgg[] {
if (res.status !== "success" || res.data == null) return [];
return Array.isArray(res.data) ? res.data : [];
}
function buildSggNmColumn(
col: ColumnConfig,
canEdit: boolean,
sggOptions: Sgg[],
): ColumnConfig {
if (!canEdit) {
return { ...col, editable: false as const };
}
if (sggOptions.length === 0) {
return { ...col, editable: true };
}
const labels = sggOptions.map((s) => s.gugun);
return {
...col,
editable: true,
editor: {
type: "dropdown",
domainOnly: true,
textReadOnly: true,
commitOnSelect: true,
dropDownWhenClick: true,
values: labels,
labels,
},
values: labels,
labels,
lookupDisplay: true,
};
}
function mapSewageReservoirListToGridRows(
list: SewageReservoirItem[],
ctpvNm: string,
values?: SearchFormValues | null,
): GridRowWithVerification[] {
return filterBySelectedAdmdstCd(list, sidoListRef.current, values).map((item) => {
const row = toGridRows([
{
...item,
ctpvNm,
oprtngStrtYmd: formatCompactYmdForGrid(item.oprtngStrtYmd),
fldngPrvtnYn: normalizeOxYnValue(item.fldngPrvtnYn),
wtpltMtgtYn: normalizeOxYnValue(item.wtpltMtgtYn),
rtlztnUsgYn: normalizeOxYnValue(item.rtlztnUsgYn),
},
])[0] as GridRowWithVerification;
if (item.verificationResult) {
row.verificationResult = item.verificationResult;
}
return row;
});
}
function toGridNumber(value: string | number | null | undefined): number {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
}
/** 펌프 구경(mm) — 콤마 제거 후 숫자 변환, 소수점 버림 */
function toPumpDmtrExpln(value: string | number | null | undefined): number {
const raw = String(value ?? "").trim();
if (raw === "") return 0;
const normalized = raw.replace(/,/g, "");
const num = Number(normalized);
if (!Number.isFinite(num)) return 0;
return Math.floor(num);
}
/** 시군구명(`sggNm`) 기준 `admdstCd`(bsnmCd)·`admdstNm`(시군구명) */
function resolveSewageReservoirAdmdst(
sggNm: string,
sggOptions: Sgg[],
): { admdstCd: string | null; admdstNm: string | null } {
const trimmed = sggNm.trim();
const matched = sggOptions.find((s) => s.gugun === trimmed);
if (matched) {
return { admdstCd: matched.bsnmCd, admdstNm: matched.gugun };
}
return { admdstCd: null, admdstNm: nullableTrimmedString(trimmed) };
}
/** 그리드 행 → ST00040001 저장/삭제 API 항목 */
function buildSewageReservoirSaveItem(
row: Record<string, string | number>,
sggOptions: Sgg[] = [],
): SewageReservoirSaveItem {
const { admdstCd, admdstNm } = resolveSewageReservoirAdmdst(
String(row.sggNm ?? ""),
sggOptions,
);
return {
admdstCd,
admdstNm,
// 항목 추가 직후 저장(신규) — 그리드 fcltSn 없음 → API에는 "1"
fcltSn: nullableTrimmedString(row.fcltSn),
fcltNm: nullableTrimmedString(row.fcltNm),
fcltPstnCn: nullableTrimmedString(row.fcltPstnCn),
oprtngStrtYmd: toCompactYmdOrNull(row.oprtngStrtYmd),
planDesignFreqCnt: toGridNumber(row.planDesignFreqCnt),
fldngPrvtnYn: nullableTrimmedString(normalizeOxYnValue(row.fldngPrvtnYn)),
wtpltMtgtYn: nullableTrimmedString(normalizeOxYnValue(row.wtpltMtgtYn)),
rtlztnUsgYn: nullableTrimmedString(normalizeOxYnValue(row.rtlztnUsgYn)),
fcltStrctCn: nullableTrimmedString(row.fcltStrctCn),
wtrStrgZoneArea: toGridNumber(row.wtrStrgZoneArea),
impdFcltCpct: toGridNumber(row.impdFcltCpct),
wholPpqty: toGridNumber(row.wholPpqty),
pumpFcltN1DmtrExpln: toPumpDmtrExpln(row.pumpFcltN1DmtrExpln),
pumpFcltN1Ppqty: toGridNumber(row.pumpFcltN1Ppqty),
pumpFcltN1PumpCnt: toGridNumber(row.pumpFcltN1PumpCnt),
pumpFcltN1RsrvPumpCnt: toGridNumber(row.pumpFcltN1RsrvPumpCnt),
pumpFcltN2DmtrExpln: toPumpDmtrExpln(row.pumpFcltN2DmtrExpln),
pumpFcltN2Ppqty: toGridNumber(row.pumpFcltN2Ppqty),
pumpFcltN2PumpCnt: toGridNumber(row.pumpFcltN2PumpCnt),
pumpFcltN2RsrvPumpCnt: toGridNumber(row.pumpFcltN2RsrvPumpCnt),
pumpFcltN3DmtrExpln: toPumpDmtrExpln(row.pumpFcltN3DmtrExpln),
pumpFcltN3Ppqty: toGridNumber(row.pumpFcltN3Ppqty),
pumpFcltN3PumpCnt: toGridNumber(row.pumpFcltN3PumpCnt),
pumpFcltN3RsrvPumpCnt: toGridNumber(row.pumpFcltN3RsrvPumpCnt),
prcsgFcltYn: row.prcsgFcltYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
odorEqpmYn: row.odorEqpmYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
oslfEtgtYn: row.oslfEtgtYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
drgptnCn: nullableTrimmedString(row.drgptnCn),
impdMthCn: nullableTrimmedString(row.impdMthCn),
impdPrcsCn: nullableTrimmedString(row.impdPrcsCn),
dschgWtrsExpln: nullableTrimmedString(row.dschgWtrsExpln),
prpwLastDspsQnt: toGridNumber(row.prpwLastDspsQnt),
ctmnLastDspsQnt: toGridNumber(row.ctmnLastDspsQnt),
prpwLastDspsExpln: nullableTrimmedString(row.prpwLastDspsExpln),
ctmnLastDspsExpln: nullableTrimmedString(row.ctmnLastDspsExpln),
oprtngDayCnt: toGridNumber(row.oprtngDayCnt),
wholQnt: toGridNumber(row.wholQnt),
rmrk: nullableTrimmedString(row.rmrk),
};
}
/** 그리드 행 → ST00040002 저장/삭제 API 항목 */
function buildRainfallPumpStationSaveItem(
row: Record<string, string | number>,
sggOptions: Sgg[] = [],
): RainfallPumpStationSaveItem {
const { admdstCd, admdstNm } = resolveSewageReservoirAdmdst(
String(row.sggNm ?? ""),
sggOptions,
);
return {
admdstCd,
admdstNm,
fcltSn: nullableTrimmedString(row.fcltSn),
fcltNm: nullableTrimmedString(row.fcltNm),
fcltPstnCn: nullableTrimmedString(row.fcltPstnCn),
fcltyKndCn: nullableTrimmedString(row.fcltyKndCn),
oprtngStrtYmd: toCompactYmdOrNull(row.oprtngStrtYmd),
planDesignFreqCnt: toGridNumber(row.planDesignFreqCnt),
wtrStrgZoneArea: toGridNumber(row.wtrStrgZoneArea),
runwtrYn: row.runwtrYn ? (row.runwtrYn === "무" ? "N" : "Y") : null,
runwtrStrqty: toGridNumber(row.runwtrStrqty),
abstnRgnImpdQnt: toGridNumber(row.abstnRgnImpdQnt),
wholPpqty: toGridNumber(row.wholPpqty),
pumpFcltN1DmtrExpln: toPumpDmtrExpln(row.pumpFcltN1DmtrExpln),
pumpFcltN1UnitPpqty: toGridNumber(row.pumpFcltN1UnitPpqty),
pumpFcltN1PumpCnt: toGridNumber(row.pumpFcltN1PumpCnt),
pumpFcltN1RsrvPumpCnt: toGridNumber(row.pumpFcltN1RsrvPumpCnt),
pumpFcltN2DmtrExpln: toPumpDmtrExpln(row.pumpFcltN2DmtrExpln),
pumpFcltN2UnitPpqty: toGridNumber(row.pumpFcltN2UnitPpqty),
pumpFcltN2PumpCnt: toGridNumber(row.pumpFcltN2PumpCnt),
pumpFcltN2RsrvPumpCnt: toGridNumber(row.pumpFcltN2RsrvPumpCnt),
pumpFcltN3DmtrExpln: toPumpDmtrExpln(row.pumpFcltN3DmtrExpln),
pumpFcltN3UnitPpqty: toGridNumber(row.pumpFcltN3UnitPpqty),
pumpFcltN3PumpCnt: toGridNumber(row.pumpFcltN3PumpCnt),
pumpFcltN3RsrvPumpCnt: toGridNumber(row.pumpFcltN3RsrvPumpCnt),
prcsgFcltYn: row.prcsgFcltYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
odorEqpmYn: row.odorEqpmYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
oslfEtgtYn: row.oslfEtgtYn ? (row.prcsgFcltYn === "무" ? "N" : "Y") : null,
dschgWtrsExpln: nullableTrimmedString(row.dschgWtrsExpln),
prpwLastDspsQnt: toGridNumber(row.prpwLastDspsQnt),
ctmnLastDspsQnt: toGridNumber(row.ctmnLastDspsQnt),
prpwLastDspsExpln: nullableTrimmedString(row.prpwLastDspsExpln),
ctmnLastDspsExpln: nullableTrimmedString(row.ctmnLastDspsExpln),
oprtngDayCnt: toGridNumber(row.oprtngDayCnt),
wholQnt: toGridNumber(row.wholQnt),
rmrk: nullableTrimmedString(row.rmrk),
};
}
function mapRainfallPumpStationListToGridRows(
list: RainfallPumpStationItem[],
ctpvNm: string,
values?: SearchFormValues | null,
): GridRowWithVerification[] {
return filterBySelectedAdmdstCd(list, sidoListRef.current, values).map((item) => {
const row = toGridRows([
{
...item,
ctpvNm,
oprtngStrtYmd: formatCompactYmdForGrid(item.oprtngStrtYmd),
runwtrYn: normalizeOxYnValue(item.runwtrYn),
prcsgFcltYn: normalizeOxYnValue(item.prcsgFcltYn),
odorEqpmYn: normalizeOxYnValue(item.odorEqpmYn),
oslfEtgtYn: normalizeOxYnValue(item.oslfEtgtYn),
},
])[0] as GridRowWithVerification;
if (item.verificationResult) {
row.verificationResult = item.verificationResult;
}
return row;
});
}
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
async function waitForImrJobCompleted(
jobId: string,
getStatus: (id: string) => Promise<ImrStatusResponse>,
options?: {
pollIntervalMs?: number;
maxAttempts?: number;
onProgress?: (jobProgress: number) => void;
},
): Promise<void> {
const pollIntervalMs = options?.pollIntervalMs ?? 2000;
const maxAttempts = options?.maxAttempts ?? 150;
for (let i = 0; i < maxAttempts; i++) {
const res = await getStatus(jobId);
options?.onProgress?.(Math.max(0, Math.min(100, Number(res.job_prog) || 0)));
if (res.status === "COMPLETED" && Number(res.job_prog) === 100) return;
if (res.status === "FAILED" || res.status === "ERROR" || res.status === "CANCELLED") {
throw new Error(res.error_msg || `시계열 검증이 ${res.status} 상태로 종료되었습니다.`);
}
await sleep(pollIntervalMs);
}
throw new Error("시계열 검증 완료 대기 시간이 초과되었습니다.");
}
// 하수도 통계 관리 > 04. 하수저류 시설 및 빗물 펌프장
const SewageReservoirPumpInp = () => {
const { sidoList } = useSearchConditionSidoList({ isInput: true });
sidoListRef.current = sidoList;
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const { isAdminInfo } = useAdminStore();
const toolbarGroupAllowed = useStatisticsInputToolbarGroupGate();
const showGlobalProgress = useGlobalProgressStore((state) => state.show);
const setGlobalProgress = useGlobalProgressStore((state) => state.setProgress);
const setGlobalProgressLabel = useGlobalProgressStore((state) => state.setLabel);
const hideGlobalProgress = useGlobalProgressStore((state) => state.hide);
useEffect(() => {
alert(SEWAGE_RESERVOIR_FACILITY_NAME_GUIDE_MESSAGE);
}, [alert]);
const submitFunc = () => {
void (async () => {
const tabKey = activeTabRef.current;
if (
tabKey !== SEWAGE_RESERVOIR_STATS_CD &&
tabKey !== rainfallPumpTabKey
) {
alert("제출할 수 없는 탭입니다.");
return;
}
if (!lastSearchedValues) {
alert("먼저 조회를 진행해주세요.");
return;
}
if (!buildGugunOkForToolbar(lastSearchedValues)) {
alert("시군구를 선택해주세요.");
return;
}
const noApplicable = buildNoApplicableForRequest(searchContextByTab.get(tabKey) ?? lastSearchedValues, isNotApplicableByTab.get(tabKey) ?? false, getCurrentRowsForTab(tabKey).length === 0);
const currentData = getCurrentRowsForTab(tabKey);
if (!noApplicable && currentData.length === 0 && buildSubmitOkForToolbar(searchContextByTab.get(tabKey) ?? lastSearchedValues)) {
alert("해당사항 없음을 체크해주세요.");
return;
}
if (await confirm("제출 하시겠습니까?")) {
setShowSubmitDialog(true);
}
})();
};
const cnacelSubmitFunc = () => {
void (async () => {
try {
if (!(await confirm("제출된 내용을 취소하시겠습니까?"))) return;
if (!lastSearchedValues) {
alert("먼저 조회를 진행해주세요.");
return;
}
const tabKey = activeTabRef.current;
const statsCdForTab = tabStatsCdMap.get(tabKey) ?? tabKey;
const userInfo = await getUserInfo();
const requestData: cancelSubmitRequest = {
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
ctpvNm: lastSearchedValues.sido ?? "",
statsYr: lastSearchedValues.year ?? "",
mdfrUuid: userInfo.userUnqId,
statsCd: statsCdForTab,
};
const response = await statisticsApi.cancelSubmit(requestData);
if (response.status === "success") {
setIsLoading(true);
await loadActiveTabData(tabKey, lastSearchedValues, true, false);
alert("제출 취소되었습니다.");
} else {
alert(response.message ?? "제출 취소 중 오류가 발생했습니다.");
}
} catch {
alert("제출 취소 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
})();
};
const isCheckedRow = (row: Record<string, string | number>): boolean => {
const v = row.__checked;
return v === 1 || v === "1" || v === "Y" || v === "y" || v === "true";
};
const getCheckedItemIndexesFromGrid = (
tabKey: string,
rowCount: number,
): number[] => {
const gridRef =
tabKey === SEWAGE_RESERVOIR_STATS_CD
? reservoirGridRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridRef
: null;
if (!gridRef?.current?.gridView) return [];
const gridView = gridRef.current.gridView as {
getCheckedItems?: () => number[];
getCheckedRows?: () => number[];
};
const checked =
(typeof gridView.getCheckedItems === "function"
? gridView.getCheckedItems()
: typeof gridView.getCheckedRows === "function"
? gridView.getCheckedRows()
: []) ?? [];
return checked.filter(
(idx) => Number.isInteger(idx) && idx >= 0 && idx < rowCount,
);
};
const getCurrentRowsForTab = (
tabKey: string,
): Record<string, string | number>[] => {
if (tabKey === SEWAGE_RESERVOIR_STATS_CD) {
return reservoirGridGetRowsRef.current?.() ?? rowDataMap.get(tabKey) ?? [];
}
if (tabKey === rainfallPumpTabKey) {
return rainfallPumpGridGetRowsRef.current?.() ?? rowDataMap.get(tabKey) ?? [];
}
return rowDataMap.get(tabKey) ?? [];
};
const commitGridForTab = (tabKey: string) => {
const gridRef =
tabKey === SEWAGE_RESERVOIR_STATS_CD
? reservoirGridRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridRef
: null;
const gridView = gridRef?.current?.gridView as
| {
commit?: (force?: boolean) => void;
cancel?: () => void;
}
| undefined;
try {
gridView?.commit?.(true);
} catch {
gridView?.cancel?.();
}
};
const deleteArticleFunc = () => {
const tabKey = activeTabRef.current;
const currentRows = getCurrentRowsForTab(tabKey);
if (currentRows.length === 0) {
alert("삭제할 데이터가 없습니다.");
return;
}
const checkedIndexes = getCheckedItemIndexesFromGrid(
tabKey,
currentRows.length,
);
const checkedIndexSet =
checkedIndexes.length > 0
? new Set(checkedIndexes)
: new Set(
currentRows
.map((row, idx) => (isCheckedRow(row) ? idx : -1))
.filter((idx) => idx >= 0),
);
const removedRows = currentRows.filter((_, idx) =>
checkedIndexSet.has(idx),
);
const nextRows = currentRows.filter((_, idx) => !checkedIndexSet.has(idx));
if (removedRows.length === 0) {
alert("삭제할 항목을 선택해주세요.");
return;
}
if (tabKey === SEWAGE_RESERVOIR_STATS_CD) {
setSewageReservoirDeleteList((prev) => [...prev, ...removedRows]);
} else if (tabKey === rainfallPumpTabKey) {
setRainfallPumpStationDeleteList((prev) => [...prev, ...removedRows]);
}
setRowDataMap((prev) => {
const next = new Map(prev);
next.set(tabKey, nextRows);
return next;
});
};
const saveFunc = () => {
void (async () => {
const tabKey = activeTabRef.current;
if (
tabKey !== SEWAGE_RESERVOIR_STATS_CD &&
tabKey !== rainfallPumpTabKey
) {
alert("저장할 수 없는 탭입니다.");
return;
}
if (!lastSearchedValues) {
alert("먼저 조회를 진행해주세요.");
return;
}
if (!buildGugunOkForToolbar(lastSearchedValues)) {
alert("시군구를 선택해주세요.");
return;
}
if (!(await confirm("저장 하시겠습니까?"))) return;
commitGridForTab(tabKey);
const noApplicable = buildNoApplicableForRequest(searchContextByTab.get(tabKey) ?? lastSearchedValues, isNotApplicableByTab.get(tabKey) ?? false, getCurrentRowsForTab(tabKey).length === 0);
const currentData = getCurrentRowsForTab(tabKey);
const isReservoirTab = tabKey === SEWAGE_RESERVOIR_STATS_CD;
const saveList = noApplicable
? []
: isReservoirTab
? currentData.map((row) =>
buildSewageReservoirSaveItem(row, sggOptions),
)
: currentData.map((row) =>
buildRainfallPumpStationSaveItem(row, sggOptions),
);
const deleteList = isReservoirTab
? sewageReservoirDeleteList
.filter((row) => String(row.fcltSn ?? "").trim() !== "")
.map((row) => buildSewageReservoirSaveItem(row, sggOptions))
: rainfallPumpStationDeleteList
.filter((row) => String(row.fcltSn ?? "").trim() !== "")
.map((row) => buildRainfallPumpStationSaveItem(row, sggOptions));
if (!noApplicable && saveList.length === 0 && buildSubmitOkForToolbar(searchContextByTab.get(tabKey) ?? lastSearchedValues)) {
alert("해당사항 없음을 체크해주세요.");
return;
}
const requestBase = {
statsYr: lastSearchedValues.year ?? "",
ctpvNm: lastSearchedValues.sido ?? "",
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
...(noApplicable ? { noApplicable: true } : {}),
};
try {
setIsLoading(true);
const userInfo = await getUserInfo();
const response = isReservoirTab
? await statisticsInputSewageReservoirPumpApi.saveSewageReservoir({
...requestBase,
userUuid: userInfo.userUnqId,
saveList: saveList as SewageReservoirSaveItem[],
deleteList: deleteList as SewageReservoirSaveItem[],
})
: await statisticsInputSewageReservoirPumpApi.saveRainfallPumpStation({
...requestBase,
userUuid: userInfo.userUnqId,
saveList: saveList as RainfallPumpStationSaveItem[],
deleteList: deleteList as RainfallPumpStationSaveItem[],
});
if (response.status === "success") {
if (isReservoirTab) {
setSewageReservoirDeleteList([]);
} else {
setRainfallPumpStationDeleteList([]);
}
await loadActiveTabData(tabKey, lastSearchedValues, true, false);
alert("저장되었습니다.");
} else {
alert(response.message ?? "저장 중 오류가 발생했습니다.");
}
} catch {
alert("저장 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
})();
};
const executeSubmit = async (submitInfo: StatisticsInputSubmitInfoFormData) => {
const tabKey = activeTabRef.current;
if (
tabKey !== SEWAGE_RESERVOIR_STATS_CD &&
tabKey !== rainfallPumpTabKey
) {
alert("제출할 수 없는 탭입니다.");
return;
}
if (!lastSearchedValues) {
alert("먼저 조회를 진행해주세요.");
return;
}
if (!buildGugunOkForToolbar(lastSearchedValues)) {
alert("시군구를 선택해주세요.");
return;
}
commitGridForTab(tabKey);
const noApplicable = buildNoApplicableForRequest(searchContextByTab.get(tabKey) ?? lastSearchedValues, isNotApplicableByTab.get(tabKey) ?? false, getCurrentRowsForTab(tabKey).length === 0);
const currentData = getCurrentRowsForTab(tabKey);
const isReservoirTab = tabKey === SEWAGE_RESERVOIR_STATS_CD;
const submitList = noApplicable
? []
: isReservoirTab
? currentData.map((row) => buildSewageReservoirSaveItem(row, sggOptions))
: currentData.map((row) => buildRainfallPumpStationSaveItem(row, sggOptions));
const deleteList = isReservoirTab
? sewageReservoirDeleteList
.filter((row) => String(row.fcltSn ?? "").trim() !== "")
.map((row) => buildSewageReservoirSaveItem(row, sggOptions))
: rainfallPumpStationDeleteList
.filter((row) => String(row.fcltSn ?? "").trim() !== "")
.map((row) => buildRainfallPumpStationSaveItem(row, sggOptions));
const activeTabStatus = tabStatusInfoMap.get(tabKey) ?? null;
const statsCdForTab = tabStatsCdMap.get(tabKey) ?? tabKey;
const verificationQuery = {
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
ctpvNm: lastSearchedValues.sido ?? "",
statsYr: lastSearchedValues.year ?? "",
statsCd: statsCdForTab,
};
const reloadSubmittedTab = async () => {
if (isReservoirTab) {
setSewageReservoirDeleteList([]);
} else {
setRainfallPumpStationDeleteList([]);
}
await loadActiveTabData(tabKey, lastSearchedValues, true, false);
};
if (!noApplicable && submitList.length === 0 && buildSubmitOkForToolbar(searchContextByTab.get(tabKey) ?? lastSearchedValues)) {
alert("해당사항 없음을 체크해주세요.");
return;
}
const submitRequestBase = {
statsYr: lastSearchedValues.year ?? "",
ctpvNm: lastSearchedValues.sido ?? "",
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
...(noApplicable ? { noApplicable: true } : {}),
lclgvPicNm: submitInfo.lclgvPicNm,
lclgvKbrdrJbgdNm: submitInfo.lclgvKbrdrJbgdNm,
lclgvKbrdrDeptNm: submitInfo.lclgvKbrdrDeptNm,
lclgvPicTelnoCn: submitInfo.lclgvPicTelnoCn,
lclgvIdfrNm: submitInfo.lclgvIdfrNm,
lclgvIdfrJbgdNm: submitInfo.lclgvIdfrJbgdNm,
lclgvIdfrDeptNm: submitInfo.lclgvIdfrDeptNm,
lclgvIdfrTelnoCn: submitInfo.lclgvIdfrTelnoCn,
};
try {
showGlobalProgress({ label: "서버에 요청 중...", progress: 0 });
const userInfo = await getUserInfo();
setGlobalProgressLabel("일반 검증 진행 중...");
const response = isReservoirTab
? await statisticsInputSewageReservoirPumpApi.submitSewageReservoir({
...submitRequestBase,
userUuid: userInfo.userUnqId,
submitList: submitList as SewageReservoirSaveItem[],
deleteList: deleteList as SewageReservoirSaveItem[],
})
: await statisticsInputSewageReservoirPumpApi.submitRainfallPumpStation({
...submitRequestBase,
userUuid: userInfo.userUnqId,
submitList: submitList as RainfallPumpStationSaveItem[],
deleteList: deleteList as RainfallPumpStationSaveItem[],
});
if (response.status !== "success") {
alert(response.message ?? "데이터 제출 중 오류가 발생했습니다.");
return;
}
const finalStatus = response.data?.finalStatus;
const nvpassed = response.data?.nvpassed;
if (finalStatus === "5") {
setGlobalProgress(50);
setGlobalProgressLabel("시계열 검증 진행 중...");
const imrParam = {
user_id: userInfo.userUnqId,
sewer_bzmn_cd: lastSearchedValues?.bsnmCd ?? "",
stats_cd: statsCdForTab,
stats_yr: lastSearchedValues.year ?? "",
lae_sbmsn_stts_cd:
activeTabStatus?.lclgvSbmsnSttsCd === "4" ? "4" : "2",
gen_verify_stts_cd: nvpassed ? "1" : "2",
hb_pass_yn: response.data?.isHbPassed,
};
try {
const imrResponse = await statisticsApi.callImrService(imrParam);
if (imrResponse.job_id) {
await waitForImrJobCompleted(
imrResponse.job_id,
(id) => statisticsApi.getImrStatus(id),
{
onProgress: (jobProgress) => {
setGlobalProgress(50 + Math.round(jobProgress / 2));
},
},
);
}
setGlobalProgress(100);
await reloadSubmittedTab();
await openVerificationResultDialogIfNeeded(
verificationQuery,
setVerificationResultDialogOpen,
{ notify: alert },
);
} catch (e) {
await reloadSubmittedTab();
await openVerificationResultDialogIfNeeded(
verificationQuery,
setVerificationResultDialogOpen,
{ notify: alert, notifySubmitComplete: false },
);
const msg =
e instanceof Error && e.message
? e.message
: "IMR 검증 중 오류가 발생했습니다.\n관리자에게 문의하세요.";
alert(msg);
}
} else {
setGlobalProgress(100);
await reloadSubmittedTab();
await openVerificationResultDialogIfNeeded(
verificationQuery,
setVerificationResultDialogOpen,
{ notify: alert },
);
}
} catch {
alert("데이터 제출 중 오류가 발생했습니다.");
} finally {
hideGlobalProgress();
}
};
const [sewageReservoirDeleteList, setSewageReservoirDeleteList] = useState<
Record<string, string | number>[]
>([]);
const [rainfallPumpStationDeleteList, setRainfallPumpStationDeleteList] =
useState<Record<string, string | number>[]>([]);
const [activeTab, setActiveTab] = useState(firstTabKey);
const [rowDataMap, setRowDataMap] = useState<
Map<string, Record<string, string | number>[]>
>(new Map());
const [isNotApplicableByTab, setIsNotApplicableByTab] = useState<Map<string, boolean>>(
() => new Map(),
);
const [searchValues, setSearchValues] = useState<SearchFormValues | null>(null);
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(
null,
);
const [hasSearched, setHasSearched] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [inputPeriodEnterable, setInputPeriodEnterable] = useState(true);
const [tabStatusInfoMap, setTabStatusInfoMap] = useState<
Map<string, SewerageStatusInfo | null>
>(new Map());
const [_toolbarSnapshotByTab, setToolbarSnapshotByTab] = useState<
Map<string, TabToolbarSnapshot>
>(new Map());
const [searchContextByTab, setSearchContextByTab] = useState<Map<string, SearchFormValues>>(
() => new Map(),
);
const [tabStatsCdMap, setTabStatsCdMap] = useState<Map<string, string>>(new Map());
const [isVerificationFailedByTab, setIsVerificationFailedByTab] = useState<
Map<string, boolean>
>(new Map());
const [footerVerificationByTab, setFooterVerificationByTab] = useState<
Map<string, VerificationResultLikeMap | null>
>(new Map());
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
const [verificationResultDialogOpen, setVerificationResultDialogOpen] =
useState(false);
const [showSubmitDialog, setShowSubmitDialog] = useState(false);
const [sggOptions, setSggOptions] = useState<Sgg[]>([]);
const [columnGuidesByTab, setColumnGuidesByTab] = useState<
Record<string, Record<string, string>>
>({});
const reservoirGridRef = useRef<RealGridReact | null>(null);
const rainfallPumpGridRef = useRef<RealGridReact | null>(null);
const reservoirGridGetRowsRef =
useRef<(() => Record<string, string | number>[]) | null>(null);
const rainfallPumpGridGetRowsRef =
useRef<(() => Record<string, string | number>[]) | null>(null);
const sggOptionsSidoRef = useRef<string | null>(null);
const activeTabId = useTabStore((s) => s.activeTabId);
useEffect(() => {
if (activeTabId !== STATISTICS_INPUT_URL_PATH.SEWAGE_RESERVOIR_PUMP) return;
const tabKey = activeTab;
if (!tabKey) return;
if (Object.prototype.hasOwnProperty.call(columnGuidesByTab, tabKey)) return;
const statsCd = tabKey;
let cancelled = false;
void (async () => {
const next = await fetchColumnGuidesRecord(statsCd);
if (cancelled) return;
setColumnGuidesByTab((prev) =>
Object.prototype.hasOwnProperty.call(prev, tabKey)
? prev
: { ...prev, [tabKey]: next },
);
})();
return () => {
cancelled = true;
};
}, [activeTabId, activeTab, columnGuidesByTab]);
const searchDoneRef = useRef(false);
const periodEnterableRef = useRef(true);
const activeTabRef = useRef(activeTab);
const loadedTabKeysRef = useRef<Set<string>>(new Set());
activeTabRef.current = activeTab;
const shouldShowNotApplicable = (
tabKey: string,
hasRows: boolean,
statusInfo: SewerageStatusInfo | null | undefined,
): boolean =>
(tabKey === SEWAGE_RESERVOIR_STATS_CD || tabKey === rainfallPumpTabKey) &&
hasSearched &&
!hasRows &&
computeTabEnterable(statusInfo, inputPeriodEnterable);
const setIsNotApplicableForTab = useCallback(
(tabKey: string, nextValue: boolean) => {
setIsNotApplicableByTab((prev) => {
const next = new Map(prev);
next.set(tabKey, nextValue);
return next;
});
},
[],
);
const commitToolbarSnapshotForLoadedTab = (
tabKey: string,
statusInfo: SewerageStatusInfo | null,
hasRowData: boolean,
searchContext: SearchFormValues,
) => {
setToolbarSnapshotByTab((prev) => {
const next = new Map(prev);
next.set(
tabKey,
computeTabToolbarSnapshot(
statusInfo,
hasRowData,
searchDoneRef.current,
searchContext,
periodEnterableRef.current,
isAdminInfo,
),
);
return next;
});
if (searchContext) {
setSearchContextByTab((prev) => {
const next = new Map(prev);
next.set(tabKey, searchContext);
return next;
});
}
};
const applyRowMap = (
mergeIntoExistingMap: boolean,
apply: (m: Map<string, Record<string, string | number>[]>) => void,
) => {
if (mergeIntoExistingMap) {
setRowDataMap((prev) => {
const next = new Map(prev);
apply(next);
return next;
});
} else {
const next = new Map<string, Record<string, string | number>[]>();
apply(next);
setRowDataMap(next);
}
};
const loadActiveTabData = async (
tabKey: string,
values: SearchFormValues,
mergeIntoExistingMap: boolean,
updateLastSearchedValues: boolean,
overrides?: { mode?: string },
): Promise<boolean> => {
const fromPreYear = overrides?.mode === "PRE";
if (tabKey === SEWAGE_RESERVOIR_STATS_CD) {
const response =
await statisticsInputSewageReservoirPumpApi.getSewageReservoirList(
buildSewageReservoirSearchParam(values, overrides),
);
if (response.status !== "success" || !response.data) {
alert(response.message ?? "데이터 조회 중 오류가 발생했습니다.");
return false;
}
const { commonInfo, statusInfo, sewageReservoirList } = response.data;
const list = sewageReservoirList ?? [];
setSewageReservoirDeleteList([]);
const gridRows = mapSewageReservoirListToGridRows(
list,
commonInfo.ctpvNm,
values,
);
applyRowMap(mergeIntoExistingMap, (m) => {
m.set(tabKey, gridRows);
});
setTabStatusInfoMap((prev) => new Map(prev).set(tabKey, statusInfo));
setTabStatsCdMap((prev) => new Map(prev).set(tabKey, commonInfo.statsCd));
setIsVerificationFailedByTab((prev) =>
patchVerificationFailedByTab(prev, tabKey, commonInfo),
);
setFooterVerificationByTab((prev) =>
patchFooterVerificationByTab(prev, tabKey, commonInfo),
);
if (updateLastSearchedValues) {
setLastSearchedValues(values);
}
commitToolbarSnapshotForLoadedTab(
tabKey,
statusInfo,
gridRows.length > 0,
values,
);
if (!fromPreYear) {
setIsNotApplicableForTab(tabKey, gridRows.length === 0);
} else if (gridRows.length > 0) {
setIsNotApplicableForTab(tabKey, false);
}
loadedTabKeysRef.current.add(tabKey);
return true;
}
if (tabKey === rainfallPumpTabKey) {
const response =
await statisticsInputSewageReservoirPumpApi.getRainfallPumpStationList(
buildSewageReservoirSearchParam(values, overrides),
);
if (response.status !== "success" || !response.data) {
alert(response.message ?? "데이터 조회 중 오류가 발생했습니다.");
return false;
}
const { commonInfo, statusInfo, rainfallPumpStationList } = response.data;
const list = rainfallPumpStationList ?? [];
setRainfallPumpStationDeleteList([]);
const gridRows = mapRainfallPumpStationListToGridRows(
list,
commonInfo.ctpvNm,
values,
);
applyRowMap(mergeIntoExistingMap, (m) => {
m.set(tabKey, gridRows);
});
setTabStatusInfoMap((prev) => new Map(prev).set(tabKey, statusInfo));
setTabStatsCdMap((prev) => new Map(prev).set(tabKey, commonInfo.statsCd));
setIsVerificationFailedByTab((prev) =>
patchVerificationFailedByTab(prev, tabKey, commonInfo),
);
setFooterVerificationByTab((prev) =>
patchFooterVerificationByTab(prev, tabKey, commonInfo),
);
if (updateLastSearchedValues) {
setLastSearchedValues(values);
}
commitToolbarSnapshotForLoadedTab(
tabKey,
statusInfo,
gridRows.length > 0,
values,
);
if (!fromPreYear) {
setIsNotApplicableForTab(tabKey, gridRows.length === 0);
} else if (gridRows.length > 0) {
setIsNotApplicableForTab(tabKey, false);
}
loadedTabKeysRef.current.add(tabKey);
return true;
}
alert("해당 탭 조회 API가 없습니다.");
return false;
};
const getLastYearDataFunc = async () => {
const values = lastSearchedValues ?? searchValues;
if (!values?.sido || values.sido === "ALL") {
alert("시도를 선택해주세요.");
return;
}
if (!hasSearched) {
alert("먼저 데이터를 조회해주세요.");
return;
}
try {
setIsLoading(true);
await loadActiveTabData(activeTabRef.current, values, true, false, {
mode: "PRE",
});
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
const loadSggOptions = useCallback(async (sido: string): Promise<Sgg[]> => {
if (!sido || sido === "ALL") {
setSggOptions([]);
return [];
}
try {
const res = await statisticsApi.getSggAllList(sido);
const list = parseSggListFromResponse(res);
setSggOptions(list);
return list;
} catch {
setSggOptions([]);
return [];
}
}, []);
const handleReset = () => {
setSewageReservoirDeleteList([]);
setRainfallPumpStationDeleteList([]);
setRowDataMap(new Map());
setTabStatusInfoMap(new Map());
setTabStatsCdMap(new Map());
setIsVerificationFailedByTab(new Map());
setFooterVerificationByTab(new Map());
setToolbarSnapshotByTab(new Map());
setSearchContextByTab(new Map());
setLastSearchedValues(null);
setSggOptions([]);
sggOptionsSidoRef.current = null;
setHasSearched(false);
setInputPeriodEnterable(true);
setIsNotApplicableByTab(new Map());
searchDoneRef.current = false;
periodEnterableRef.current = true;
loadedTabKeysRef.current.clear();
setActiveTab(firstTabKey);
};
const handleSearch = async (
values: SearchFormValues,
opts?: { forcedTabKey?: string },
) => {
if (!values.sido || values.sido === "ALL") {
alert("시도를 선택해주세요.");
return;
}
try {
const periodResponse = await statisticsInputSewSupplyRateApi.checkInputPeriod(
values.year || "",
);
if (periodResponse.status !== "success") {
alert(periodResponse.message);
return;
}
const periods = Array.isArray(periodResponse.data)
? periodResponse.data
: [];
const periodOk = isInputPeriodCurrent(periods);
periodEnterableRef.current = periodOk;
setInputPeriodEnterable(periodOk);
} catch {
alert("입력 기간 확인 중 오류가 발생했습니다.");
return;
}
const yearChangedFromLastSearch =
lastSearchedValues != null &&
(lastSearchedValues.year ?? "") !== (values.year ?? "");
if (yearChangedFromLastSearch) {
setRowDataMap(new Map());
setTabStatusInfoMap(new Map());
setTabStatsCdMap(new Map());
setIsVerificationFailedByTab(new Map());
setFooterVerificationByTab(new Map());
setToolbarSnapshotByTab(new Map());
setSearchContextByTab(new Map());
loadedTabKeysRef.current.clear();
setActiveTab(firstTabKey);
}
try {
setIsLoading(true);
searchDoneRef.current = true;
setHasSearched(true);
setLastSearchedValues(values);
const loadedSgg = await loadSggOptions(values.sido);
sggOptionsSidoRef.current = values.sido;
if (loadedSgg.length === 0) {
alert("시군구 목록을 불러오지 못했습니다.");
return;
}
const tabKeyToLoad =
opts?.forcedTabKey ??
(yearChangedFromLastSearch ? firstTabKey : activeTabRef.current);
if (opts?.forcedTabKey) {
activeTabRef.current = opts.forcedTabKey;
setActiveTab(opts.forcedTabKey);
} else if (yearChangedFromLastSearch) {
activeTabRef.current = firstTabKey;
setActiveTab(firstTabKey);
}
const ok = await loadActiveTabData(
tabKeyToLoad,
values,
!yearChangedFromLastSearch,
true,
);
if (!ok) return;
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
const handleActiveTabChange = async (tabKey: string) => {
const prevTabKey = activeTabRef.current;
commitGridForTab(prevTabKey);
const latestRowsInPrevTab = getCurrentRowsForTab(prevTabKey);
if (latestRowsInPrevTab.length > 0 || rowDataMap.has(prevTabKey)) {
setRowDataMap((prev) => {
const next = new Map(prev);
next.set(prevTabKey, latestRowsInPrevTab);
return next;
});
}
activeTabRef.current = tabKey;
setActiveTab(tabKey);
if (!hasSearched || !lastSearchedValues) return;
if (loadedTabKeysRef.current.has(tabKey)) return;
if (tabRowDataExists(rowDataMap, tabKey)) return;
try {
setIsLoading(true);
await loadActiveTabData(tabKey, lastSearchedValues, true, false);
} catch {
alert("데이터 조회 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};
const searchContextForToolbar = searchContextByTab.get(activeTab) ?? lastSearchedValues;
const activeTabStatus = tabStatusInfoMap.get(activeTab) ?? null;
const activeTabToolbar =
computeTabToolbarSnapshot(
activeTabStatus,
tabRowDataExists(rowDataMap, activeTab),
hasSearched,
searchContextForToolbar,
inputPeriodEnterable,
isAdminInfo,
);
const {
showSaveInToolbar: baseShowSaveInToolbar,
showEnterableToolbarButtons: baseShowEnterableToolbarButtons,
showActionToolbarCard: baseShowActionToolbarCard,
} = activeTabToolbar;
const showSaveInToolbar = baseShowSaveInToolbar && toolbarGroupAllowed;
const showEnterableToolbarButtons =
baseShowEnterableToolbarButtons && toolbarGroupAllowed;
const showActionToolbarCard =
baseShowActionToolbarCard && toolbarGroupAllowed;
const submitOk = buildSubmitOkForToolbar(searchContextForToolbar);
const isReservoirOrRainfallTab =
activeTab === SEWAGE_RESERVOIR_STATS_CD || activeTab === rainfallPumpTabKey;
const showArticleToolbarCard =
hasSearched &&
isReservoirOrRainfallTab &&
toolbarGroupAllowed &&
(showSaveInToolbar || showEnterableToolbarButtons);
const isNotApplicableForActiveTab = isNotApplicableByTab.get(activeTab) ?? false;
const showNotApplicableForActiveTab =
loadedTabKeysRef.current.has(activeTab) &&
shouldShowNotApplicable(
activeTab,
tabRowDataExists(rowDataMap, activeTab),
tabStatusInfoMap.get(activeTab),
) &&
submitOk;
const setIsNotApplicableForActiveTab: Dispatch<SetStateAction<boolean>> = useCallback(
(next) => {
const tabKey = activeTabRef.current;
const current = isNotApplicableByTab.get(tabKey) ?? false;
const resolved =
typeof next === "function"
? (next as (prevState: boolean) => boolean)(current)
: next;
setIsNotApplicableForTab(tabKey, resolved);
},
[isNotApplicableByTab, setIsNotApplicableForTab],
);
const openVerificationHistoryDialog = () => {
const ctx = lastSearchedValues ?? searchValues;
const activeTabStatsCd = tabStatsCdMap.get(activeTab);
if (!ctx?.year || !ctx?.sido || !ctx?.bsnmCd || !activeTabStatsCd) {
alert("먼저 조회를 진행해주세요.");
return;
}
setVerificationHistoryOpen(true);
};
const addArticleFunc = async () => {
const ctx = lastSearchedValues ?? searchValues;
if (!hasSearched || !ctx?.sido || ctx.sido === "ALL") {
alert("먼저 조회를 진행해주세요.");
return;
}
const activeTabKey = activeTabRef.current;
const isReservoirTab = activeTabKey === SEWAGE_RESERVOIR_STATS_CD;
const isRainfallPumpTab = activeTabKey === rainfallPumpTabKey;
if (!isReservoirTab && !isRainfallPumpTab) {
alert("항목을 추가할 수 없는 탭입니다.");
return;
}
const sggNm =
ctx.gugun && ctx.gugun !== "ALL" ? ctx.gugun : "";
let list = sggOptions;
if (sggOptionsSidoRef.current !== ctx.sido || list.length === 0) {
list = await loadSggOptions(ctx.sido);
sggOptionsSidoRef.current = ctx.sido;
}
if (list.length === 0) {
alert("시군구 목록을 불러오지 못했습니다.");
return;
}
const tabKey = activeTabKey;
const newRow = isReservoirTab
? createEmptySewageReservoirRow(ctx.sido, sggNm)
: createEmptyRainfallPumpStationRow(ctx.sido, sggNm);
commitGridForTab(tabKey);
const currentRows = getCurrentRowsForTab(tabKey);
flushSync(() => {
setSggOptions(list);
setRowDataMap((prev) => {
const next = new Map(prev);
next.set(tabKey, [...currentRows, newRow]);
return next;
});
setIsNotApplicableForTab(tabKey, false);
});
const statusInfo = tabStatusInfoMap.get(tabKey) ?? null;
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, true, ctx);
};
const columnInfoByTab = useMemo(() => {
const map = new Map<string, ColumnInfo>();
for (const tab of SewageReservoirPumpInpTabList) {
const tabKey = tab.tabKey ?? "";
const canEdit =
(computeTabEnterable(
tabStatusInfoMap.get(tabKey) ?? null,
inputPeriodEnterable,
) || isAdminInfo) && inputPeriodEnterable;
const isReservoirTab = tabKey === SEWAGE_RESERVOIR_STATS_CD;
const isRainfallPumpTab = tabKey === rainfallPumpTabKey;
const rawColumns = tab.columns ?? [];
const base = canEdit
? rawColumns
: rawColumns.map((col) => ({ ...col, editable: false as const }));
const columns = base.map((col: ColumnConfig) => {
if (
(isReservoirTab || isRainfallPumpTab) &&
col.fieldName === "ctpvNm"
) {
return { ...col, editable: false as const };
}
if (
(isReservoirTab || isRainfallPumpTab) &&
col.fieldName === "sggNm" &&
canEdit
) {
return buildSggNmColumn(col, true, sggOptions);
}
return col;
}).map((col) => {
const guide = columnGuidesByTab[tabKey]?.[col.fieldName]?.trim();
return guide ? { ...col, tooltip: guide } : col;
});
map.set(tabKey, {
columns,
columnLayout: tab.columnLayout ?? [],
});
}
return map;
}, [tabStatusInfoMap, inputPeriodEnterable, isAdminInfo, sggOptions, columnGuidesByTab]);
const verificationCellStyle = ({
fieldName,
row,
}: CellStyleCallbackParams): string | undefined => {
const verification = (row as GridRowWithVerification).verificationResult;
if (!verification) return;
const errors = verification[fieldName];
if (Array.isArray(errors) && errors.length > 0) {
const hasImr = errors.some((e) => e.vrfcCd === "IMR" || e.vrfcCd === "HB");
return hasImr ? "rg-cell-verify-error-imr" : "rg-cell-verify-error";
}
};
const verificationCellTooltip = ({
fieldName,
row,
}: CellTooltipCallbackParams): string | undefined => {
const verification = (row as GridRowWithVerification).verificationResult;
if (!verification) return;
const errors = verification[fieldName];
if (Array.isArray(errors) && errors.length > 0) {
return errors
.map((e) => {
const prefix =
e.vrfcCd === "IMR"
? "시계열 검증 - "
: e.vrfcCd === "NV"
? "일반검증 - "
: "모집단 검증 -";
return `${prefix}${e.rsnExpln}
(검증 기준값: ${e.cmprCn} / 현재 입력값: ${e.nowCn})`;
})
.filter(Boolean)
.join("\n");
}
};
const verificationQueryContext = (() => {
const ctx = lastSearchedValues ?? searchValues;
const statsCd = tabStatsCdMap.get(activeTab);
if (!ctx?.year || !ctx?.sido || !ctx?.bsnmCd || !statsCd) return null;
return {
...toInputSearchRegion(sidoListRef.current, ctx),
ctpvNm: ctx.sido,
statsYr: ctx.year,
statsCd,
};
})();
const { verificationSearchDefaults, searchFormRemountKey } =
useStatisticsInputPendingNavigation({
urlPath: STATISTICS_INPUT_URL_PATH.SEWAGE_RESERVOIR_PUMP,
onPending: (pending) => {
activeTabRef.current = pending.tabKey;
setActiveTab(pending.tabKey);
},
onAutoSearch: (values, tabKey) =>
handleSearch(values, { forcedTabKey: tabKey }),
});
return (
<>
<div className="relative">
<SearchForm
isInput
key={searchFormRemountKey}
defaultValues={verificationSearchDefaults ?? undefined}
fctName={true}
onSubmit={handleSearch}
onReset={handleReset}
onValuesChange={setSearchValues}
/>
{showActionToolbarCard && (
<div className="card !py-0">
<div className="m-[0.6rem] flex items-center justify-end gap-[0.6rem]">
<VerificationResultButton
VerificationResultButtonFunc={openVerificationHistoryDialog}
isVerificationFailed={
isVerificationFailedByTab.get(activeTab) === true
}
/>
{showEnterableToolbarButtons && (
<>
<LastYearDataButton
getLastYearDataFunc={() => void getLastYearDataFunc()}
/>
{submitOk && <SubmitButton submitFunc={submitFunc} />}
</>
)}
{activeTabStatus?.lclgvSbmsnSttsCd === "2" && submitOk && (
<CancelSubmitButton cnacelSubmitFunc={cnacelSubmitFunc} />
)}
{showSaveInToolbar && <SaveButton saveFunc={saveFunc} />}
</div>
</div>
)}
{showArticleToolbarCard && (
<div className="card !py-0">
<div className="m-[0.6rem] flex items-center justify-end gap-[0.6rem]">
{showNotApplicableForActiveTab && (
<NotApplicableCheckButton
isCheck={isNotApplicableForActiveTab}
setIsCheck={setIsNotApplicableForActiveTab}
/>
)}
<AddArticleButton addArticleFunc={addArticleFunc} />
<DeleteArticleButton deleteArticleFunc={deleteArticleFunc} />
</div>
</div>
)}
{isLoading && (
<div className="absolute inset-0 z-50 flex items-center justify-center rounded-lg p-10 [data-theme='black']:bg-transparent">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
<Tabs
value={activeTab}
onValueChange={(v) => void handleActiveTabChange(v)}
>
<TabsList>
{SewageReservoirPumpInpTabList.map((tab) => (
<TabsTrigger key={tab.tabKey} value={tab.tabKey ?? ""}>
{tab.tabLabel || tab.tabKey}
</TabsTrigger>
))}
</TabsList>
{SewageReservoirPumpInpTabList.map((tab) => {
const tabKey = tab.tabKey ?? "";
const tabEnterableForGrid =
(computeTabEnterable(
tabStatusInfoMap.get(tabKey) ?? null,
inputPeriodEnterable,
) || isAdminInfo) && inputPeriodEnterable;
const gugunOk = buildGugunOkForToolbar(searchContextForToolbar);
const tabStatusInfo = tabStatusInfoMap.get(tabKey) ?? null;
const isReservoirTab = tabKey === SEWAGE_RESERVOIR_STATS_CD;
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
key={`${tabKey}-${tabEnterableForGrid ? "enterable" : "readonly"}`}
getGridRef={
isReservoirTab
? reservoirGridRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridRef
: undefined
}
columnInfo={
columnInfoByTab.get(tabKey) ??
toGridColumnInfo(tab)
}
rowStartNum={tab.rowStartNum}
fixedColumns={tab.fixedColumns}
rowData={rowDataMap.get(tabKey) ?? []}
setRowData={(updater) => {
setRowDataMap((prev) => {
const next = new Map(prev);
const cur = next.get(tabKey) ?? [];
const n =
typeof updater === "function"
? (updater as (
p: Record<
string,
string | number
>[],
) => Record<
string,
string | number
>[])(cur)
: updater;
next.set(tabKey, n);
return next;
});
}}
getGridDataRef={
tabKey === SEWAGE_RESERVOIR_STATS_CD
? reservoirGridGetRowsRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridGetRowsRef
: undefined
}
showHeaderCheckbox
statusInfo={tabStatusInfo}
isExcelImport={
loadedTabKeysRef.current.has(tabKey) &&
tabEnterableForGrid &&
gugunOk
}
excelImportSewerBzmnCd={(lastSearchedValues ?? searchValues)?.bsnmCd}
excelExportSearchContext={toExcelExportSearchContextFromSearchForm(lastSearchedValues ?? searchValues)}
cellStyleCallback={verificationCellStyle}
footerVerificationResult={
footerVerificationByTab.get(tabKey) ?? null
}
cellTooltipCallback={verificationCellTooltip}
/>
</TabsContent>
);
})}
</Tabs>
</div>
<VerificationResultHistoryDialog
open={verificationHistoryOpen}
onOpenChange={setVerificationHistoryOpen}
queryContext={verificationQueryContext}
onExceptionResetSubmitted={async () => {
const values = lastSearchedValues ?? searchValues;
if (!values) return;
await loadActiveTabData(activeTabRef.current, values, true, false);
}}
/>
<SubmitDailog
open={showSubmitDialog}
onOpenChange={setShowSubmitDialog}
statusInfo={activeTabStatus}
onConfirm={executeSubmit}
isLoading={isLoading}
/>
<VerificationResultDialog
open={verificationResultDialogOpen}
onOpenChange={setVerificationResultDialogOpen}
queryContext={verificationQueryContext}
onExceptionSubmitted={async () => {
const values = lastSearchedValues ?? searchValues;
if (!values) return;
await loadActiveTabData(activeTabRef.current, values, true, false);
}}
/>
<ConfirmDialog isOpen={false} />
</>
);
};
export default SewageReservoirPumpInp;