1413 lines
60 KiB
TypeScript
1413 lines
60 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from "react";
|
|
|
|
import { useConfirm } from "@frontend-opensource/use-react-hooks";
|
|
|
|
import { useAlertStore, useGlobalProgressStore, 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 { statisticsInputSewSupplyRateApi } from "@/entities/statistics/api/input/statistics-input-sew-supply-rate-service";
|
|
import { statisticsInputSewerageFinanceApi } from "@/entities/statistics/api/input/statistics-input-sewerage-finance-service";
|
|
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
|
|
import type {
|
|
CauserBurdenItem,
|
|
CauserBurdenSaveItem,
|
|
CauserBurdenSaveRequest,
|
|
CauserBurdenSubmitRequest,
|
|
SewerageChargeItem,
|
|
SewerageChargeSaveItem,
|
|
SewerageChargeSaveRequest,
|
|
SewerageChargeSubmitRequest,
|
|
SewerageFinanceRequestParams,
|
|
SewerageFinanceSettleItem,
|
|
SewerageFinanceSettleSaveItem,
|
|
SewerageFinanceSettleSaveRequest,
|
|
SewerageFinanceSettleSubmitRequest,
|
|
SewerageFinanceSubmitResponse,
|
|
SewerageFinanceVerificationResult,
|
|
SewerageUsageFeeItem,
|
|
SewerageUsageFeeSaveItem,
|
|
SewerageUsageFeeSaveRequest,
|
|
SewerageUsageFeeSubmitRequest,
|
|
} from "@/entities/statistics/model/input/statistics-input-sewerage-finance-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 {
|
|
cancelSubmitRequest,
|
|
ImrStatusResponse,
|
|
SewerageStatusInfo,
|
|
Sido,
|
|
} from "@/entities/statistics/model/statistics-interface";
|
|
import {
|
|
filterBySelectedAdmdstCd,
|
|
isGugunOkForToolbar,
|
|
isSubmitOkForToolbar,
|
|
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 CancelSubmitButton from "@/components/button/CancelSubmitButton";
|
|
import LastYearDataButton from "@/components/button/LastYearDataButton";
|
|
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 { ColumnConfig, ColumnInfo } from "@/components/type/DataGrid.type";
|
|
import type { SearchFormValues } from "@/components/type/SearchForm.type";
|
|
import { CauserBurdenInpColumn } from "@/components/util/column/input/sewerageFinance/CauserBurdenInpColumn";
|
|
import { SewerageChargeInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageChargeInpColumn";
|
|
import { SewerageFinanceSettleInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageFinanceSettleInpColumn";
|
|
import { SewerageUsageFeeInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageUsageFeeInpColumn";
|
|
import { fetchColumnGuidesRecord } from "@/components/util/grid/columnGuides";
|
|
import { toGridRows } from "@/components/util/grid/gridFunction";
|
|
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 { nullableTrimmedString } from "@/components/util/input/nullableString";
|
|
import { useAdminStore } from "@/store/admin-store";
|
|
import { useTabStore } from "@/store/tab-store";
|
|
|
|
const SewerageFinanceInpTabList = [
|
|
SewerageFinanceSettleInpColumn,
|
|
SewerageChargeInpColumn,
|
|
SewerageUsageFeeInpColumn,
|
|
CauserBurdenInpColumn,
|
|
] as const;
|
|
|
|
const firstTabKey = SewerageFinanceSettleInpColumn.tabKey;
|
|
|
|
type GridRowWithVerification = Record<string, string | number> & {
|
|
verificationResult?: SewerageFinanceVerificationResult;
|
|
};
|
|
|
|
type TabToolbarSnapshot = {
|
|
showSaveInToolbar: boolean;
|
|
showEnterableToolbarButtons: boolean;
|
|
showActionToolbarCard: boolean;
|
|
};
|
|
|
|
const toGridColumnInfo = (tab: (typeof SewerageFinanceInpTabList)[number]): ColumnInfo => ({
|
|
columns: tab.columns ?? [],
|
|
columnLayout: tab.columnLayout ?? [],
|
|
});
|
|
|
|
function buildSewerageFinanceSearchParam(
|
|
values: SearchFormValues,
|
|
overrides?: { mode?: string },
|
|
): SewerageFinanceRequestParams {
|
|
return {
|
|
statsYr: values.year,
|
|
ctpvNm: values.sido,
|
|
...toInputSearchRegion(sidoListRef.current, values),
|
|
...(overrides?.mode ? { mode: overrides.mode } : {}),
|
|
};
|
|
}
|
|
|
|
const computeTabEnterable = (
|
|
statusInfo: SewerageStatusInfo | null | undefined,
|
|
periodEnterable: boolean,
|
|
): boolean => {
|
|
if (statusInfo?.laeSbmsnSttsCd) {
|
|
if (["2", "3"].includes(statusInfo.laeSbmsnSttsCd)) {
|
|
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 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?.laeSbmsnSttsCd === "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 mapRegionalListToGridRows<
|
|
T extends { verificationResult?: SewerageFinanceVerificationResult },
|
|
>(list: T[], ctpvNm: string, values?: SearchFormValues | null): GridRowWithVerification[] {
|
|
return filterBySelectedAdmdstCd(list, sidoListRef.current, values).map((item) => {
|
|
const { verificationResult, ...rest } = item;
|
|
const row = toGridRows([{ ctpvNm, ...rest }])[0] as GridRowWithVerification;
|
|
if (verificationResult) row.verificationResult = verificationResult;
|
|
return row;
|
|
});
|
|
}
|
|
|
|
function buildColumnFormatNumber(columns: { fieldName?: string; dataFormat?: string }[]) {
|
|
const columnFormatMap = new Map<string, string>();
|
|
columns.forEach((col) => {
|
|
if (col.fieldName && col.dataFormat) {
|
|
columnFormatMap.set(col.fieldName, col.dataFormat);
|
|
}
|
|
});
|
|
|
|
return (value: string | number | null | undefined, fieldName: string): number => {
|
|
if (value === null || value === undefined || value === "") return 0;
|
|
const num =
|
|
typeof value === "string" ? parseFloat(value.replace(/,/g, "")) : value;
|
|
if (isNaN(num)) return 0;
|
|
const format = columnFormatMap.get(fieldName);
|
|
if (!format) return num;
|
|
const decimalPlaces = format.match(/\.(\d+)/)?.[1]?.length ?? 0;
|
|
return decimalPlaces > 0 ? parseFloat(num.toFixed(decimalPlaces)) : Math.round(num);
|
|
};
|
|
}
|
|
|
|
function resolveSewerageFinanceTab(tabKey: string) {
|
|
return {
|
|
isSettleTab: tabKey === SewerageFinanceSettleInpColumn.tabKey,
|
|
isChargeTab: tabKey === SewerageChargeInpColumn.tabKey,
|
|
isUsageFeeTab: tabKey === SewerageUsageFeeInpColumn.tabKey,
|
|
isCauserBurdenTab: tabKey === CauserBurdenInpColumn.tabKey,
|
|
};
|
|
}
|
|
|
|
function buildSewerageFinanceSettleSaveList(
|
|
currentData: Record<string, string | number>[],
|
|
): SewerageFinanceSettleSaveItem[] {
|
|
const formatNumber = buildColumnFormatNumber(SewerageFinanceSettleInpColumn.columns);
|
|
|
|
return currentData.map((d) => ({
|
|
admdstCd: nullableTrimmedString(d.admdstCd),
|
|
sggNm: nullableTrimmedString(d.sggNm),
|
|
admdstNm: nullableTrimmedString(d.admdstNm),
|
|
cnterGovSprtAmt: formatNumber(d.cnterGovSprtAmt, "cnterGovSprtAmt"),
|
|
mctpvLcexpAmt: formatNumber(d.mctpvLcexpAmt, "mctpvLcexpAmt"),
|
|
wareaSggLclAmt: formatNumber(d.wareaSggLclAmt, "wareaSggLclAmt"),
|
|
sewerUseAmt: formatNumber(d.sewerUseAmt, "sewerUseAmt"),
|
|
orgprBrdnAmt: formatNumber(d.orgprBrdnAmt, "orgprBrdnAmt"),
|
|
etcIncmAmt: formatNumber(d.etcIncmAmt, "etcIncmAmt"),
|
|
crfwAmt: formatNumber(d.crfwAmt, "crfwAmt"),
|
|
lbltAmt: formatNumber(d.lbltAmt, "lbltAmt"),
|
|
tmplntFcltAmt: formatNumber(d.tmplntFcltAmt, "tmplntFcltAmt"),
|
|
tmplntMendngAmt: formatNumber(d.tmplntMendngAmt, "tmplntMendngAmt"),
|
|
tmplntOperKeepAmt: formatNumber(d.tmplntOperKeepAmt, "tmplntOperKeepAmt"),
|
|
tmplntEtcAmt: formatNumber(d.tmplntEtcAmt, "tmplntEtcAmt"),
|
|
swagePplFcltAmt: formatNumber(d.swagePplFcltAmt, "swagePplFcltAmt"),
|
|
swagePplMendngAmt: formatNumber(d.swagePplMendngAmt, "swagePplMendngAmt"),
|
|
swagePplOperKeepAmt: formatNumber(d.swagePplOperKeepAmt, "swagePplOperKeepAmt"),
|
|
swagePplEtcAmt: formatNumber(d.swagePplEtcAmt, "swagePplEtcAmt"),
|
|
swageImpdFcltAmt: formatNumber(d.swageImpdFcltAmt, "swageImpdFcltAmt"),
|
|
swageImpdMendngAmt: formatNumber(d.swageImpdMendngAmt, "swageImpdMendngAmt"),
|
|
swageImpdOperKeepAmt: formatNumber(d.swageImpdOperKeepAmt, "swageImpdOperKeepAmt"),
|
|
swageImpdFcltEtcAmt: formatNumber(d.swageImpdFcltEtcAmt, "swageImpdFcltEtcAmt"),
|
|
etcAcdntCrfwAmt: formatNumber(d.etcAcdntCrfwAmt, "etcAcdntCrfwAmt"),
|
|
etcNrcpAmt: formatNumber(d.etcNrcpAmt, "etcNrcpAmt"),
|
|
etcAmt: formatNumber(d.etcAmt, "etcAmt"),
|
|
rmrk: nullableTrimmedString(d.rmrk),
|
|
fnnByWholPjtcoAmt: formatNumber(d.fnnByWholPjtcoAmt, "fnnByWholPjtcoAmt"),
|
|
usgByWholPjtcoAmt: formatNumber(d.usgByWholPjtcoAmt, "usgByWholPjtcoAmt"),
|
|
tmplntWholAmt: formatNumber(d.tmplntWholAmt, "tmplntWholAmt"),
|
|
wholSwagePplAmt: formatNumber(d.wholSwagePplAmt, "wholSwagePplAmt"),
|
|
wholSwageImpdFcltAmt: formatNumber(d.wholSwageImpdFcltAmt, "wholSwageImpdFcltAmt"),
|
|
etcWholAmt: formatNumber(d.etcWholAmt, "etcWholAmt"),
|
|
}));
|
|
}
|
|
|
|
function buildSewerageChargeSaveList(
|
|
currentData: Record<string, string | number>[],
|
|
): SewerageChargeSaveItem[] {
|
|
const formatNumber = buildColumnFormatNumber(SewerageChargeInpColumn.columns);
|
|
|
|
return currentData.map((d) => ({
|
|
admdstCd: nullableTrimmedString(d.admdstCd),
|
|
sggNm: nullableTrimmedString(d.sggNm),
|
|
admdstNm: nullableTrimmedString(d.admdstNm),
|
|
anlLevyQnt: formatNumber(d.anlLevyQnt, "anlLevyQnt"),
|
|
levyAmt: formatNumber(d.levyAmt, "levyAmt"),
|
|
grssPrmcoAmt: formatNumber(d.grssPrmcoAmt, "grssPrmcoAmt"),
|
|
rmrk: nullableTrimmedString(d.rmrk),
|
|
avgUntprcAmt: formatNumber(d.avgUntprcAmt, "avgUntprcAmt"),
|
|
grssUnitPrmcoAmt: formatNumber(d.grssUnitPrmcoAmt, "grssUnitPrmcoAmt"),
|
|
rlztnRt: formatNumber(d.rlztnRt, "rlztnRt"),
|
|
}));
|
|
}
|
|
|
|
function buildSewerageUsageFeeSaveList(
|
|
currentData: Record<string, string | number>[],
|
|
): SewerageUsageFeeSaveItem[] {
|
|
const formatNumber = buildColumnFormatNumber(SewerageUsageFeeInpColumn.columns);
|
|
|
|
return currentData.map((d) => ({
|
|
admdstCd: nullableTrimmedString(d.admdstCd),
|
|
sggNm: nullableTrimmedString(d.sggNm),
|
|
admdstNm: nullableTrimmedString(d.admdstNm),
|
|
hshusLevyAmt: formatNumber(d.hshusLevyAmt, "hshusLevyAmt"),
|
|
hshusLevyQnt: formatNumber(d.hshusLevyQnt, "hshusLevyQnt"),
|
|
hshusUntprcAmt: formatNumber(d.hshusUntprcAmt, "hshusUntprcAmt"),
|
|
taskFrLevyAmt: formatNumber(d.taskFrLevyAmt, "taskFrLevyAmt"),
|
|
taskFrLevyQnt: formatNumber(d.taskFrLevyQnt, "taskFrLevyQnt"),
|
|
taskFrUntprcAmt: formatNumber(d.taskFrUntprcAmt, "taskFrUntprcAmt"),
|
|
fbuLevyAmt: formatNumber(d.fbuLevyAmt, "fbuLevyAmt"),
|
|
fbuLevyQnt: formatNumber(d.fbuLevyQnt, "fbuLevyQnt"),
|
|
fbuUntprcAmt: formatNumber(d.fbuUntprcAmt, "fbuUntprcAmt"),
|
|
bthhsFrSpcs1LevyAmt: formatNumber(d.bthhsFrSpcs1LevyAmt, "bthhsFrSpcs1LevyAmt"),
|
|
bthhsFrSpcs1LevyQnt: formatNumber(d.bthhsFrSpcs1LevyQnt, "bthhsFrSpcs1LevyQnt"),
|
|
bthhsFrSpcs1UntprcAmt: formatNumber(d.bthhsFrSpcs1UntprcAmt, "bthhsFrSpcs1UntprcAmt"),
|
|
bthhsFrSpcs2LevyAmt: formatNumber(d.bthhsFrSpcs2LevyAmt, "bthhsFrSpcs2LevyAmt"),
|
|
bthhsFrSpcs2LevyQnt: formatNumber(d.bthhsFrSpcs2LevyQnt, "bthhsFrSpcs2LevyQnt"),
|
|
bthhsFrSpcs2UntprcAmt: formatNumber(d.bthhsFrSpcs2UntprcAmt, "bthhsFrSpcs2UntprcAmt"),
|
|
induLevyAmt: formatNumber(d.induLevyAmt, "induLevyAmt"),
|
|
induLevyQnt: formatNumber(d.induLevyQnt, "induLevyQnt"),
|
|
induUntprcAmt: formatNumber(d.induUntprcAmt, "induUntprcAmt"),
|
|
etcLevyAmt: formatNumber(d.etcLevyAmt, "etcLevyAmt"),
|
|
etcLevyQnt: formatNumber(d.etcLevyQnt, "etcLevyQnt"),
|
|
etcLevyUntprcAmt: formatNumber(d.etcLevyUntprcAmt, "etcLevyUntprcAmt"),
|
|
rmrk: nullableTrimmedString(d.rmrk),
|
|
levyAmt: formatNumber(d.levyAmt, "levyAmt"),
|
|
levyQnt: formatNumber(d.levyQnt, "levyQnt"),
|
|
}));
|
|
}
|
|
|
|
function buildCauserBurdenSaveList(
|
|
currentData: Record<string, string | number>[],
|
|
): CauserBurdenSaveItem[] {
|
|
const formatNumber = buildColumnFormatNumber(CauserBurdenInpColumn.columns);
|
|
|
|
return currentData.map((d) => ({
|
|
admdstCd: nullableTrimmedString(d.admdstCd),
|
|
sggNm: nullableTrimmedString(d.sggNm),
|
|
admdstNm: nullableTrimmedString(d.admdstNm),
|
|
levyEvntcsCnt: formatNumber(d.levyEvntcsCnt, "levyEvntcsCnt"),
|
|
levyAmt: formatNumber(d.levyAmt, "levyAmt"),
|
|
mltvEqpmEvntcsCnt: formatNumber(d.mltvEqpmEvntcsCnt, "mltvEqpmEvntcsCnt"),
|
|
mltvEqpmAmt: formatNumber(d.mltvEqpmAmt, "mltvEqpmAmt"),
|
|
othrCstrnOthrActrCnt: formatNumber(d.othrCstrnOthrActrCnt, "othrCstrnOthrActrCnt"),
|
|
othrCstrnOthrActrAmt: formatNumber(d.othrCstrnOthrActrAmt, "othrCstrnOthrActrAmt"),
|
|
rmrk: nullableTrimmedString(d.rmrk),
|
|
trgtByWholClctnAmt: formatNumber(d.trgtByWholClctnAmt, "trgtByWholClctnAmt"),
|
|
}));
|
|
}
|
|
|
|
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("시계열 검증 완료 대기 시간이 초과되었습니다.");
|
|
}
|
|
|
|
// 하수도 통계 관리 > 09. 하수도재정
|
|
const SewerageFinanceInp = () => {
|
|
const { sidoList } = useSearchConditionSidoList({ isInput: true });
|
|
sidoListRef.current = sidoList;
|
|
const { setMessage: alert } = useAlertStore((state) => state);
|
|
const { confirm } = useConfirm();
|
|
const { isAdminInfo } = useAdminStore();
|
|
const showGlobalProgress = useGlobalProgressStore((state) => state.show);
|
|
const hideGlobalProgress = useGlobalProgressStore((state) => state.hide);
|
|
const setGlobalProgress = useGlobalProgressStore((state) => state.setProgress);
|
|
const setGlobalProgressLabel = useGlobalProgressStore((state) => state.setLabel);
|
|
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [activeTab, setActiveTab] = useState<string>(firstTabKey);
|
|
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(
|
|
new Map(),
|
|
);
|
|
const [searchValues, setSearchValues] = useState<SearchFormValues | null>(null);
|
|
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(null);
|
|
const [hasSearched, setHasSearched] = useState(false);
|
|
const [inputPeriodEnterable, setInputPeriodEnterable] = useState(true);
|
|
const [tabStatusInfoMap, setTabStatusInfoMap] = useState<
|
|
Map<string, SewerageStatusInfo | null>
|
|
>(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 [_toolbarSnapshotByTab, setToolbarSnapshotByTab] = useState<
|
|
Map<string, TabToolbarSnapshot>
|
|
>(new Map());
|
|
const [searchContextByTab, setSearchContextByTab] = useState<Map<string, SearchFormValues>>(
|
|
() => new Map(),
|
|
);
|
|
const [columnGuidesByTab, setColumnGuidesByTab] = useState<
|
|
Record<string, Record<string, string>>
|
|
>({});
|
|
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
|
|
const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false);
|
|
const [showSubmitDialog, setShowSubmitDialog] = useState(false);
|
|
|
|
const searchParamRef = useRef<SewerageFinanceRequestParams | null>(null);
|
|
const searchDoneRef = useRef(false);
|
|
const periodEnterableRef = useRef(true);
|
|
const activeTabRef = useRef(activeTab);
|
|
const getGridDataRef = useRef<(() => Record<string, string | number>[]) | null>(null);
|
|
activeTabRef.current = activeTab;
|
|
|
|
const activeTabId = useTabStore((s) => s.activeTabId);
|
|
|
|
useEffect(() => {
|
|
if (activeTabId !== STATISTICS_INPUT_URL_PATH.SEWERAGE_FINANCE) 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 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,
|
|
param: SewerageFinanceRequestParams,
|
|
searchContext: SearchFormValues,
|
|
mergeIntoExistingMap: boolean,
|
|
updateLastSearchedValues: boolean,
|
|
overrides?: { mode?: string },
|
|
): Promise<boolean> => {
|
|
const requestParam = overrides?.mode ? { ...param, mode: overrides.mode } : param;
|
|
|
|
if (tabKey === SewerageFinanceSettleInpColumn.tabKey) {
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.getSewerageFinanceSettleList(requestParam);
|
|
if (response.status !== "success" || !response.data) {
|
|
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
|
|
return false;
|
|
}
|
|
const { commonInfo, statusInfo, sewerageFinanceSettleList } = response.data;
|
|
const gridRows = mapRegionalListToGridRows(
|
|
(sewerageFinanceSettleList ?? []) as SewerageFinanceSettleItem[],
|
|
commonInfo.ctpvNm,
|
|
searchContext,
|
|
);
|
|
|
|
applyRowMap(mergeIntoExistingMap, (m) => {
|
|
m.set(SewerageFinanceSettleInpColumn.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(searchContext);
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, gridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
if (tabKey === SewerageChargeInpColumn.tabKey) {
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.getSewerageChargeList(requestParam);
|
|
if (response.status !== "success" || !response.data) {
|
|
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
|
|
return false;
|
|
}
|
|
const { commonInfo, statusInfo, sewerageChargeList } = response.data;
|
|
const gridRows = mapRegionalListToGridRows(
|
|
(sewerageChargeList ?? []) as SewerageChargeItem[],
|
|
commonInfo.ctpvNm,
|
|
searchContext,
|
|
);
|
|
|
|
applyRowMap(mergeIntoExistingMap, (m) => {
|
|
m.set(SewerageChargeInpColumn.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(searchContext);
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, gridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
if (tabKey === SewerageUsageFeeInpColumn.tabKey) {
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.getSewerageUsageFeeList(requestParam);
|
|
if (response.status !== "success" || !response.data) {
|
|
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
|
|
return false;
|
|
}
|
|
const { commonInfo, statusInfo, sewerageUsageFeeList } = response.data;
|
|
const gridRows = mapRegionalListToGridRows(
|
|
(sewerageUsageFeeList ?? []) as SewerageUsageFeeItem[],
|
|
commonInfo.ctpvNm,
|
|
searchContext,
|
|
);
|
|
|
|
applyRowMap(mergeIntoExistingMap, (m) => {
|
|
m.set(SewerageUsageFeeInpColumn.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(searchContext);
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, gridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
if (tabKey === CauserBurdenInpColumn.tabKey) {
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.getCauserBurdenList(requestParam);
|
|
if (response.status !== "success" || !response.data) {
|
|
alert(response.message || "데이터 조회 중 오류가 발생했습니다.");
|
|
return false;
|
|
}
|
|
const { commonInfo, statusInfo, causerBurdenList } = response.data;
|
|
const gridRows = mapRegionalListToGridRows(
|
|
(causerBurdenList ?? []) as CauserBurdenItem[],
|
|
commonInfo.ctpvNm,
|
|
searchContext,
|
|
);
|
|
|
|
applyRowMap(mergeIntoExistingMap, (m) => {
|
|
m.set(CauserBurdenInpColumn.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(searchContext);
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, gridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
alert("해당 탭 조회 API가 없습니다.");
|
|
return false;
|
|
};
|
|
|
|
const getTabGridRows = (tabKey: string): Record<string, string | number>[] =>
|
|
getGridDataRef.current?.() ?? rowDataMap.get(tabKey) ?? [];
|
|
|
|
const handleReset = () => {
|
|
setRowDataMap(new Map());
|
|
setTabStatusInfoMap(new Map());
|
|
setTabStatsCdMap(new Map());
|
|
setIsVerificationFailedByTab(new Map());
|
|
setFooterVerificationByTab(new Map());
|
|
setToolbarSnapshotByTab(new Map());
|
|
setSearchContextByTab(new Map());
|
|
setActiveTab(firstTabKey);
|
|
activeTabRef.current = firstTabKey;
|
|
setLastSearchedValues(null);
|
|
setHasSearched(false);
|
|
setInputPeriodEnterable(true);
|
|
searchParamRef.current = null;
|
|
searchDoneRef.current = false;
|
|
periodEnterableRef.current = true;
|
|
};
|
|
|
|
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);
|
|
|
|
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());
|
|
activeTabRef.current = firstTabKey;
|
|
setActiveTab(firstTabKey);
|
|
}
|
|
|
|
if (opts?.forcedTabKey) {
|
|
activeTabRef.current = opts.forcedTabKey;
|
|
setActiveTab(opts.forcedTabKey);
|
|
}
|
|
|
|
setIsLoading(true);
|
|
searchDoneRef.current = true;
|
|
setHasSearched(true);
|
|
const searchParam = buildSewerageFinanceSearchParam(values);
|
|
searchParamRef.current = searchParam;
|
|
|
|
await loadActiveTabData(
|
|
opts?.forcedTabKey ?? activeTabRef.current,
|
|
searchParam,
|
|
values,
|
|
!yearChangedFromLastSearch,
|
|
true,
|
|
);
|
|
} catch {
|
|
alert("데이터 조회 중 오류가 발생했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleActiveTabChange = async (tabKey: string) => {
|
|
const prevTabKey = activeTabRef.current;
|
|
const latestRowsInPrevTab = getTabGridRows(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 || !searchParamRef.current) return;
|
|
if (tabRowDataExists(rowDataMap, tabKey)) return;
|
|
|
|
try {
|
|
setIsLoading(true);
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
} catch {
|
|
alert("데이터 조회 중 오류가 발생했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const lastYearDataFunc = async () => {
|
|
const values = lastSearchedValues ?? searchValues;
|
|
if (!values?.sido || values.sido === "ALL") {
|
|
alert("시도를 선택해주세요.");
|
|
return;
|
|
}
|
|
if (!hasSearched) {
|
|
alert("먼저 데이터를 조회해주세요.");
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setIsLoading(true);
|
|
const param = buildSewerageFinanceSearchParam(values, { mode: "PRE" });
|
|
await loadActiveTabData(
|
|
activeTabRef.current,
|
|
param,
|
|
values,
|
|
true,
|
|
false,
|
|
{ mode: "PRE" },
|
|
);
|
|
} catch {
|
|
alert("데이터 조회 중 오류가 발생했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const cnacelSubmitFunc = () => {
|
|
void (async () => {
|
|
try {
|
|
if (!(await confirm("제출된 내용을 취소하시겠습니까?"))) return;
|
|
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
|
|
const userInfo = await getUserInfo();
|
|
const tabKey = activeTabRef.current;
|
|
const statsCdForTab = tabStatsCdMap.get(tabKey);
|
|
if (!statsCdForTab) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
|
|
const requestData: cancelSubmitRequest = {
|
|
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
|
|
ctpvNm: lastSearchedValues.sido ?? "",
|
|
statsYr: lastSearchedValues.year ?? "",
|
|
mdfrId: userInfo.userUnqId,
|
|
statsCd: statsCdForTab,
|
|
};
|
|
|
|
const response = await statisticsApi.cancelSubmit(requestData);
|
|
|
|
if (response.status === "success") {
|
|
setIsLoading(true);
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
alert("제출 취소되었습니다.");
|
|
} else {
|
|
alert(response.message ?? "제출 취소 중 오류가 발생했습니다.");
|
|
}
|
|
} catch {
|
|
alert("제출 취소 중 오류가 발생했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
})();
|
|
};
|
|
|
|
const submitFunc = () => {
|
|
void (async () => {
|
|
const tabKey = activeTabRef.current;
|
|
const { isSettleTab, isChargeTab, isUsageFeeTab, isCauserBurdenTab } =
|
|
resolveSewerageFinanceTab(tabKey);
|
|
if (!isSettleTab && !isChargeTab && !isUsageFeeTab && !isCauserBurdenTab) {
|
|
alert("제출할 수 없는 탭입니다.");
|
|
return;
|
|
}
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
if (!buildGugunOkForToolbar(lastSearchedValues)) {
|
|
alert("시군구를 선택해주세요.");
|
|
return;
|
|
}
|
|
const currentData = getTabGridRows(tabKey);
|
|
if (!currentData.length) {
|
|
alert("제출할 데이터가 없습니다.");
|
|
return;
|
|
}
|
|
if (await confirm("제출 하시겠습니까?")) {
|
|
setShowSubmitDialog(true);
|
|
}
|
|
})();
|
|
};
|
|
|
|
const executeSubmit = async (submitInfo: StatisticsInputSubmitInfoFormData) => {
|
|
const tabKey = activeTabRef.current;
|
|
const { isSettleTab, isChargeTab, isUsageFeeTab, isCauserBurdenTab } =
|
|
resolveSewerageFinanceTab(tabKey);
|
|
if (!isSettleTab && !isChargeTab && !isUsageFeeTab && !isCauserBurdenTab) {
|
|
alert("제출할 수 없는 탭입니다.");
|
|
return;
|
|
}
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
|
|
const currentData = getTabGridRows(tabKey);
|
|
if (!currentData.length) {
|
|
alert("제출할 데이터가 없습니다.");
|
|
return;
|
|
}
|
|
|
|
const activeTabStatus = tabStatusInfoMap.get(tabKey) ?? null;
|
|
const statsCdForTab = tabStatsCdMap.get(tabKey) ?? tabKey;
|
|
const adminOpt = isAdminInfo ? { superAdmin: "superAdmin" as const } : {};
|
|
|
|
const submitInfoBase = {
|
|
statsYr: lastSearchedValues.year ?? "",
|
|
ctpvNm: lastSearchedValues.sido ?? "",
|
|
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
|
|
laePicNm: submitInfo.laePicNm,
|
|
laePicTelNo: submitInfo.laePicTelNo,
|
|
laeKbrdrDeptNm: submitInfo.laeKbrdrDeptNm,
|
|
laeKbrdrJbgdNm: submitInfo.laeKbrdrJbgdNm,
|
|
laeIdfrNm: submitInfo.laeIdfrNm,
|
|
laeIdfrTelNo: submitInfo.laeIdfrTelNo,
|
|
laeIdfrDeptNm: submitInfo.laeIdfrDeptNm,
|
|
laeIdfrJbgdNm: submitInfo.laeIdfrJbgdNm,
|
|
};
|
|
|
|
const verificationQuery = {
|
|
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
|
|
ctpvNm: lastSearchedValues.sido ?? "",
|
|
statsYr: lastSearchedValues.year ?? "",
|
|
statsCd: statsCdForTab,
|
|
};
|
|
|
|
const reloadSubmittedTab = async () => {
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current!,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
};
|
|
|
|
try {
|
|
showGlobalProgress({ label: "서버에 요청 중...", progress: 0 });
|
|
const userInfo = await getUserInfo();
|
|
setGlobalProgressLabel("일반 검증 진행 중...");
|
|
|
|
let response: SewerageFinanceSubmitResponse;
|
|
|
|
if (isSettleTab) {
|
|
const param: SewerageFinanceSettleSubmitRequest = {
|
|
...submitInfoBase,
|
|
userId: userInfo.userUnqId,
|
|
submitList: buildSewerageFinanceSettleSaveList(currentData),
|
|
...adminOpt,
|
|
};
|
|
response =
|
|
await statisticsInputSewerageFinanceApi.submitSewerageFinanceSettle(
|
|
param,
|
|
);
|
|
} else if (isChargeTab) {
|
|
const param: SewerageChargeSubmitRequest = {
|
|
...submitInfoBase,
|
|
userId: userInfo.userUnqId,
|
|
submitList: buildSewerageChargeSaveList(currentData),
|
|
...adminOpt,
|
|
};
|
|
response = await statisticsInputSewerageFinanceApi.submitSewerageCharge(param);
|
|
} else if (isUsageFeeTab) {
|
|
const param: SewerageUsageFeeSubmitRequest = {
|
|
...submitInfoBase,
|
|
userId: userInfo.userUnqId,
|
|
submitList: buildSewerageUsageFeeSaveList(currentData),
|
|
...adminOpt,
|
|
};
|
|
response =
|
|
await statisticsInputSewerageFinanceApi.submitSewerageUsageFee(param);
|
|
} else {
|
|
const param: CauserBurdenSubmitRequest = {
|
|
...submitInfoBase,
|
|
userId: userInfo.userUnqId,
|
|
submitList: buildCauserBurdenSaveList(currentData),
|
|
...adminOpt,
|
|
};
|
|
response = await statisticsInputSewerageFinanceApi.submitCauserBurden(param);
|
|
}
|
|
|
|
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?.laeSbmsnSttsCd === "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();
|
|
setShowSubmitDialog(false);
|
|
}
|
|
};
|
|
|
|
const saveFunc = () => {
|
|
void (async () => {
|
|
const tabKey = activeTabRef.current;
|
|
const { isSettleTab, isChargeTab, isUsageFeeTab, isCauserBurdenTab } =
|
|
resolveSewerageFinanceTab(tabKey);
|
|
if (!isSettleTab && !isChargeTab && !isUsageFeeTab && !isCauserBurdenTab) {
|
|
alert("저장할 수 없는 탭입니다.");
|
|
return;
|
|
}
|
|
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
|
|
if (!buildGugunOkForToolbar(lastSearchedValues)) {
|
|
alert("시군구를 선택해주세요.");
|
|
return;
|
|
}
|
|
|
|
if (!(await confirm("저장 하시겠습니까?"))) return;
|
|
|
|
const currentData = getTabGridRows(tabKey);
|
|
if (!currentData.length) {
|
|
alert("저장할 데이터가 없습니다.");
|
|
return;
|
|
}
|
|
|
|
const baseRequest = {
|
|
statsYr: lastSearchedValues.year ?? "",
|
|
ctpvNm: lastSearchedValues.sido ?? "",
|
|
...toInputSearchRegion(sidoListRef.current, lastSearchedValues),
|
|
};
|
|
|
|
try {
|
|
setIsLoading(true);
|
|
const userInfo = await getUserInfo();
|
|
|
|
if (isSettleTab) {
|
|
const param: SewerageFinanceSettleSaveRequest = {
|
|
...baseRequest,
|
|
userId: userInfo.userUnqId,
|
|
saveList: buildSewerageFinanceSettleSaveList(currentData),
|
|
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
|
|
};
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.saveSewerageFinanceSettle(param);
|
|
if (response.status === "success") {
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
alert("저장되었습니다.");
|
|
} else {
|
|
alert(response.message || "데이터 저장 중 오류가 발생했습니다.");
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (isChargeTab) {
|
|
const param: SewerageChargeSaveRequest = {
|
|
...baseRequest,
|
|
userId: userInfo.userUnqId,
|
|
saveList: buildSewerageChargeSaveList(currentData),
|
|
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
|
|
};
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.saveSewerageCharge(param);
|
|
if (response.status === "success") {
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
alert("저장되었습니다.");
|
|
} else {
|
|
alert(response.message || "데이터 저장 중 오류가 발생했습니다.");
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (isUsageFeeTab) {
|
|
const param: SewerageUsageFeeSaveRequest = {
|
|
...baseRequest,
|
|
userId: userInfo.userUnqId,
|
|
saveList: buildSewerageUsageFeeSaveList(currentData),
|
|
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
|
|
};
|
|
const response =
|
|
await statisticsInputSewerageFinanceApi.saveSewerageUsageFee(param);
|
|
if (response.status === "success") {
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
alert("저장되었습니다.");
|
|
} else {
|
|
alert(response.message || "데이터 저장 중 오류가 발생했습니다.");
|
|
}
|
|
return;
|
|
}
|
|
|
|
const param: CauserBurdenSaveRequest = {
|
|
...baseRequest,
|
|
userId: userInfo.userUnqId,
|
|
saveList: buildCauserBurdenSaveList(currentData),
|
|
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
|
|
};
|
|
const response = await statisticsInputSewerageFinanceApi.saveCauserBurden(param);
|
|
if (response.status === "success") {
|
|
await loadActiveTabData(
|
|
tabKey,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
true,
|
|
false,
|
|
);
|
|
alert("저장되었습니다.");
|
|
} else {
|
|
alert(response.message || "데이터 저장 중 오류가 발생했습니다.");
|
|
}
|
|
} catch {
|
|
alert("데이터 저장 중 오류가 발생했습니다.");
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
})();
|
|
};
|
|
|
|
const openVerificationHistoryDialog = () => {
|
|
const ctx = lastSearchedValues ?? searchValues;
|
|
const statsCd = tabStatsCdMap.get(activeTab);
|
|
if (!ctx?.year || !ctx?.sido || !ctx?.bsnmCd || !statsCd) {
|
|
alert("먼저 조회를 진행해주세요.");
|
|
return;
|
|
}
|
|
setVerificationHistoryOpen(true);
|
|
};
|
|
|
|
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 columnInfoByTab = useMemo(() => {
|
|
const map = new Map<string, ColumnInfo>();
|
|
for (const tab of SewerageFinanceInpTabList) {
|
|
const tabKey = tab.tabKey;
|
|
const canEdit =
|
|
(computeTabEnterable(
|
|
tabStatusInfoMap.get(tabKey) ?? null,
|
|
inputPeriodEnterable,
|
|
) || isAdminInfo) && inputPeriodEnterable;
|
|
const rawColumns = (tab.columns ?? []) as ColumnConfig[];
|
|
const base = canEdit
|
|
? rawColumns
|
|
: rawColumns.map((col) => ({ ...col, editable: false as const }));
|
|
const columns = base.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, columnGuidesByTab]);
|
|
|
|
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, showEnterableToolbarButtons, showActionToolbarCard } =
|
|
activeTabToolbar;
|
|
const submitOk = buildSubmitOkForToolbar(searchContextForToolbar);
|
|
|
|
const verificationCellStyle = ({
|
|
fieldName,
|
|
row,
|
|
}: {
|
|
fieldName: string;
|
|
row: Record<string, string | number>;
|
|
}): 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,
|
|
}: {
|
|
fieldName: string;
|
|
row: Record<string, string | number>;
|
|
}): 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.compVlCn} / 현재 입력값: ${e.nowVlCn})`;
|
|
})
|
|
.filter(Boolean)
|
|
.join("\n");
|
|
}
|
|
};
|
|
|
|
const { verificationSearchDefaults, searchFormRemountKey } =
|
|
useStatisticsInputPendingNavigation({
|
|
urlPath: STATISTICS_INPUT_URL_PATH.SEWERAGE_FINANCE,
|
|
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}
|
|
onSubmit={handleSearch}
|
|
onReset={handleReset}
|
|
onValuesChange={setSearchValues}
|
|
/>
|
|
{showActionToolbarCard && (
|
|
<div className="card !py-0">
|
|
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]">
|
|
<VerificationResultButton
|
|
VerificationResultButtonFunc={openVerificationHistoryDialog}
|
|
isVerificationFailed={
|
|
isVerificationFailedByTab.get(activeTab) === true
|
|
}
|
|
/>
|
|
{showEnterableToolbarButtons && (
|
|
<>
|
|
<LastYearDataButton
|
|
getLastYearDataFunc={() => void lastYearDataFunc()}
|
|
/>
|
|
{submitOk && <SubmitButton submitFunc={submitFunc} />}
|
|
</>
|
|
)}
|
|
{activeTabStatus?.laeSbmsnSttsCd === "2" && submitOk && (
|
|
<CancelSubmitButton cnacelSubmitFunc={cnacelSubmitFunc} />
|
|
)}
|
|
{showSaveInToolbar && <SaveButton saveFunc={saveFunc} />}
|
|
</div>
|
|
</div>
|
|
)}
|
|
{isLoading && (
|
|
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
|
|
<div className="relative size-[5rem]">
|
|
<LoadingWithAnimation color="primary" />
|
|
</div>
|
|
</div>
|
|
)}
|
|
<div className="flex flex-col gap-[0.6rem] mx-[0.6rem]">
|
|
<Tabs
|
|
value={activeTab}
|
|
onValueChange={(v) => void handleActiveTabChange(v)}
|
|
className="w-full"
|
|
variant="default"
|
|
>
|
|
<TabsList>
|
|
{SewerageFinanceInpTabList.map((info) => (
|
|
<TabsTrigger key={info.tabKey} value={info.tabKey}>
|
|
{info.tabLabel || info.tabKey}
|
|
</TabsTrigger>
|
|
))}
|
|
</TabsList>
|
|
{SewerageFinanceInpTabList.map((info) => {
|
|
const tabKey = info.tabKey;
|
|
const rowData = rowDataMap.get(tabKey) ?? [];
|
|
const tabEnterableForGrid =
|
|
(computeTabEnterable(
|
|
tabStatusInfoMap.get(tabKey) ?? null,
|
|
inputPeriodEnterable,
|
|
) || isAdminInfo) && inputPeriodEnterable;
|
|
const gugunOk = buildGugunOkForToolbar(searchContextForToolbar);
|
|
const tabStatusInfo = tabStatusInfoMap.get(tabKey) ?? null;
|
|
|
|
return (
|
|
<TabsContent key={tabKey} value={tabKey}>
|
|
<DataGrid
|
|
key={`${tabKey}-${tabEnterableForGrid ? "enterable" : "readonly"}`}
|
|
columnInfo={
|
|
columnInfoByTab.get(tabKey) ?? toGridColumnInfo(info)
|
|
}
|
|
rowStartNum={info.rowStartNum}
|
|
excelExportFileSuffix={info.tabLabel || tabKey}
|
|
rowData={rowData}
|
|
setRowData={(updater) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const cur = next.get(tabKey) ?? [];
|
|
const n =
|
|
typeof updater === "function"
|
|
? updater(cur)
|
|
: updater;
|
|
next.set(tabKey, n);
|
|
return next;
|
|
});
|
|
}}
|
|
showHeaderCheckbox={false}
|
|
fixedColumns={info.fixedColumns}
|
|
enableSort={false}
|
|
statusInfo={tabStatusInfo}
|
|
isExcelImport={
|
|
tabRowDataExists(rowDataMap, tabKey) &&
|
|
tabEnterableForGrid &&
|
|
gugunOk
|
|
}
|
|
excelImportSewerBzmnCd={(lastSearchedValues ?? searchValues)?.bsnmCd}
|
|
excelExportSearchContext={toExcelExportSearchContextFromSearchForm(lastSearchedValues ?? searchValues)}
|
|
isExcelExport
|
|
cellStyleCallback={verificationCellStyle}
|
|
footerVerificationResult={
|
|
footerVerificationByTab.get(tabKey) ?? null
|
|
}
|
|
cellTooltipCallback={verificationCellTooltip}
|
|
getGridDataRef={
|
|
activeTab === tabKey ? getGridDataRef : undefined
|
|
}
|
|
/>
|
|
</TabsContent>
|
|
);
|
|
})}
|
|
</Tabs>
|
|
</div>
|
|
</div>
|
|
<VerificationResultHistoryDialog
|
|
open={verificationHistoryOpen}
|
|
onOpenChange={setVerificationHistoryOpen}
|
|
queryContext={verificationQueryContext}
|
|
onExceptionResetSubmitted={async () => {
|
|
const values = lastSearchedValues ?? searchValues;
|
|
if (!values || !searchParamRef.current) return;
|
|
await loadActiveTabData(
|
|
activeTabRef.current,
|
|
searchParamRef.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 || !searchParamRef.current) return;
|
|
await loadActiveTabData(
|
|
activeTabRef.current,
|
|
searchParamRef.current,
|
|
values,
|
|
true,
|
|
false,
|
|
);
|
|
}}
|
|
/>
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default SewerageFinanceInp;
|