[st] - feat: 입력 04 작업 중 & 수정 요청 사항 적용

This commit is contained in:
2026-06-05 10:35:31 +09:00
parent d58b2db786
commit 7b9081a125
27 changed files with 1293 additions and 280 deletions
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from 'react';
import { useEffect, useRef, useState, type Dispatch, type SetStateAction } from 'react';
import { useConfirm } from '@frontend-opensource/use-react-hooks';
@@ -157,7 +157,9 @@ const PublicSewageFacilityInp = () => {
const globalProgressVisible = useGlobalProgressStore((state) => state.visible);
const [isLoading, setIsLoading] = useState<boolean>(false);
const [hasSearched, setHasSearched] = useState(false);
const [isNotApplicable, setIsNotApplicable] = useState(false);
const [isNotApplicableByTab, setIsNotApplicableByTab] = useState<Map<string, boolean>>(
() => new Map(),
);
const [showIsNotApplicable, setShowIsNotApplicable] = useState(false);
const [searchValues, setSearchValues] = useState<SearchFormValues | null>(null);
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(null);
@@ -175,6 +177,19 @@ const PublicSewageFacilityInp = () => {
const [mainFacilityMappingSaveDialogKey, setMainFacilityMappingSaveDialogKey] = useState(0);
const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false);
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
const isNotApplicable = isNotApplicableByTab.get('ST00060001') ?? false;
const setIsNotApplicable: Dispatch<SetStateAction<boolean>> = (next) => {
setIsNotApplicableByTab((prev) => {
const current = prev.get('ST00060001') ?? false;
const resolved =
typeof next === 'function'
? (next as (prevState: boolean) => boolean)(current)
: next;
const nextMap = new Map(prev);
nextMap.set('ST00060001', resolved);
return nextMap;
});
};
const periodEnterableRef = useRef(true);
const searchDoneRef = useRef(false);
@@ -655,8 +670,6 @@ const PublicSewageFacilityInp = () => {
param: PublicSewageFacilityRequestParams,
searchContext: SearchFormValues | null,
): Promise<boolean> => {
// 서버 데이터로 새로 불러오는 시점이므로 "해당없음" 체크는 항상 초기화
setIsNotApplicable(false);
try {
if (tabKey === 'ST00060001') {
const response = await statisticsInputPublicSewageFacilityApiService.getPublicSewageFacility(param);
@@ -856,6 +869,11 @@ const PublicSewageFacilityInp = () => {
setLastSearchedValues(values);
searchDoneRef.current = true;
setHasSearched(true);
setIsNotApplicableByTab((prev) => {
const next = new Map(prev);
next.set('ST00060001', false);
return next;
});
setIsLoading(true);
const param = buildPublicSewageFacilityParams(values);
@@ -870,6 +888,19 @@ const PublicSewageFacilityInp = () => {
};
const handleActiveTabChange = async (tabKey: string) => {
const prevTabKey = activeTabRef.current;
if (prevTabKey === 'ST00060001') {
const latestRowsInPrevTab =
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
if (latestRowsInPrevTab.length > 0 || rowDataMap.has('ST00060001')) {
setRowDataMap((prev) => {
const next = new Map(prev);
next.set('ST00060001', latestRowsInPrevTab);
return next;
});
}
}
activeTabRef.current = tabKey;
setActiveTab(tabKey);
@@ -885,7 +916,7 @@ const PublicSewageFacilityInp = () => {
const handleReset = () => {
setIsLoading(false);
setHasSearched(false);
setIsNotApplicable(false);
setIsNotApplicableByTab(new Map());
setShowIsNotApplicable(false);
setRowDataMap(new Map());
@@ -1215,7 +1246,7 @@ const PublicSewageFacilityInp = () => {
return (
<TabsContent key={tab.tabKey} value={tab.tabKey}>
<DataGrid
key={(tabEnterableForGrid || isAdminInfo) ? 'enterable' : 'readonly'}
key={tab.tabKey}
columnInfo={gridColumnInfo}
rowStartNum={tab.rowStartNum}
excelExportFileSuffix={tab.tabLabel || tab.tabKey}
@@ -5,7 +5,6 @@ import DataGrid from "@/components/module/DataGrid";
import SubmitButton from "@/components/button/SumitButton";
import SaveButton from "@/components/button/SaveButton";
import LastYearDataButton from "@/components/button/LastYearDataButton";
import SubmitExceptionButton from "@/components/button/SubmitExceptionButton";
import AddArticleButton from "@/components/button/AddArticleButton";
import DeleteArticleButton from "@/components/button/DeleteArticleButton";
import NotApplicableCheckButton from "@/components/button/NotApplicableCheckButton";
@@ -15,11 +14,6 @@ import { PumpingStationInpColumn } from "@/components/util/column/input/PumpingS
// 하수도 통계 관리 > 05. 펌프장
const PumpingStationInp = () => {
const SubmitExceptionFunc = () => {
console.log('submit exception');
// 예외 제출 로직
};
const getLastYearDataFunc = () => {
console.log('get last year data');
// 지난연도 데이터 가져오기 로직
@@ -53,7 +47,6 @@ const PumpingStationInp = () => {
<SearchForm fctName={true} />
<div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]">
<SubmitExceptionButton SubmitExceptionFunc={SubmitExceptionFunc} />
<LastYearDataButton getLastYearDataFunc={getLastYearDataFunc} />
<SubmitButton submitFunc={submitFunc} />
<SaveButton saveFunc={saveFunc} />
@@ -67,7 +60,7 @@ const PumpingStationInp = () => {
</div>
</div>
<DataGrid
columnInfo={ PumpingStationInpColumn }
columnInfo={PumpingStationInpColumn}
rowStartNum={3}
fixedColumns={3}
rowData={rowData}
@@ -396,6 +396,8 @@ const SewagePipeInp = () => {
values: SearchFormValues;
tabKey: string;
} | null>(null);
/** ST00020002 무데이터 안내/자동이동은 동일 조회조건에서 1회만 수행 */
const factInstallNoDataHandledKeyRef = useRef<string | null>(null);
const [verificationSearchDefaults, setVerificationSearchDefaults] =
useState<SearchFormValues | null>(null);
@@ -549,6 +551,12 @@ const SewagePipeInp = () => {
mergeIntoExistingMap: boolean,
updateLastSearchedValues: boolean,
): Promise<boolean> => {
const searchConditionKey = JSON.stringify({
statsYr: searchParam.statsYr ?? "",
ctpvNm: searchParam.ctpvNm ?? "",
sggNm: searchParam.sggNm ?? "",
sewerBzmnCd: searchParam.sewerBzmnCd ?? "",
});
const applyRowMap = (apply: (m: Map<string, Record<string, string | number>[]>) => void) => {
if (mergeIntoExistingMap) {
setRowDataMap((prev) => {
@@ -595,6 +603,23 @@ const SewagePipeInp = () => {
ctpvNm: commonInfo.ctpvNm,
...d,
}));
if (convertedData.length === 0) {
const alreadyHandledForSameSearch =
factInstallNoDataHandledKeyRef.current === searchConditionKey;
if (!alreadyHandledForSameSearch) {
factInstallNoDataHandledKeyRef.current = searchConditionKey;
alert("시설별 설치 현황에 조회된 데이터가 없습니다.\n시설별 현황 관리에서 설정해주세요");
activeTabRef.current = "ST00020006";
setActiveTab("ST00020006");
return await loadSewagePipeActiveTabData(
"ST00020006",
searchParam,
values,
true,
updateLastSearchedValues,
);
}
}
applyRowMap((m) => m.set('ST00020002', toGridRows(convertedData)));
setTabStatusInfoMap((prev) => new Map(prev).set(tabKey, response.data.statusInfo));
setTabStatsCdMap((prev) => new Map(prev).set(tabKey, commonInfo.statsCd));
@@ -795,7 +820,39 @@ const SewagePipeInp = () => {
}, [searchFormRemountKey]);
const getCurrentRowsForTab = (tabKey: string): Record<string, string | number>[] => {
switch (tabKey) {
case REGIONAL_FACT_TAB_KEY:
return getGridDataRef.current?.() ?? [];
case "ST00020002":
return getFactInstallGridDataRef.current?.() ?? [];
case "ST00020003":
return getPipeTypeGridDataRef.current?.() ?? [];
case "ST00020004":
return getPipeDiameterGridDataRef.current?.() ?? [];
case "ST00020005":
return getManholeGridDataRef.current?.() ?? [];
case "ST00020006":
return [
...(rowDataMap.get("treatmentPlantConnectionInp") ?? []),
...(rowDataMap.get("adminAreaConnectionInp") ?? []),
];
default:
return rowDataMap.get(tabKey) ?? [];
}
};
const handleActiveTabChange = async (tabKey: string) => {
const prevTabKey = activeTabRef.current;
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);
setStatsCd(tabStatsCdMap.get(tabKey) ?? "");
@@ -1735,7 +1792,7 @@ const SewagePipeInp = () => {
const maxYy = getManholeLastDataYear() % 100;
const saveList = currentData.map((d) => {
const yearlyStats = [];
const yearlyStats: SeweragePipeInputManholeStatusSaveYearlyStatItem[] = [];
for (let yy = minYy; yy <= maxYy; yy++) {
const year = 2000 + yy;
const wholKey = `yy${yy}WholMnhlCnt`;
@@ -1978,7 +2035,7 @@ const SewagePipeInp = () => {
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
key={(tabEnterableForGrid || isAdminInfo) ? "enterable" : "readonly"}
key={tabKey}
columnInfo={gridColumnInfo}
rowStartNum={info.rowStartNum}
excelExportFileSuffix={info.tabLabel || tabKey}
@@ -912,6 +912,16 @@ const SewagePipeMaintainInp = () => {
}, [searchFormRemountKey]);
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;
@@ -1110,11 +1120,7 @@ const SewagePipeMaintainInp = () => {
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
key={
tabEnterableForGrid || isAdminInfo
? `${tabKey}-enterable`
: `${tabKey}-readonly`
}
key={tabKey}
columnInfo={
columnInfoByTab.get(tabKey) ??
toGridColumnInfo(info)
@@ -4,10 +4,14 @@ import {
useRef,
useState,
type RefObject,
type Dispatch,
type SetStateAction,
} 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 { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from "@common/components";
@@ -25,7 +29,6 @@ import SearchForm from "@/components/module/SearchForm";
import { VerificationResultHistoryDialog } from "@/components/module/VerificationResultHistoryDialog";
import type { SearchFormValues } from "@/components/type/SearchForm.type";
import type {
CellEditedCallbackParams,
CellStyleCallbackParams,
CellTooltipCallbackParams,
ColumnConfig,
@@ -36,24 +39,33 @@ import { doList } from "@/components/util/column/input/DoList";
import { RainfallPumpStationInpColumn } from "@/components/util/column/input/sewageReservoirPump/RainfallPumpStationInpColumn";
import { SewageReservoirInpColumn } from "@/components/util/column/input/sewageReservoirPump/SewageReservoirInpColumn";
import { toGridRows } from "@/components/util/grid/gridFunction";
import { formatCompactYmdForGrid, normalizeOxYnValue } from "@/components/util/grid/ymdFormat";
import {
formatCompactYmdForGrid,
normalizeOxYnValue,
toCompactYmd,
} from "@/components/util/grid/ymdFormat";
import { statisticsInputSewageReservoirPumpApi } from "@/entities/statistics/api/input/statistics-input-sewage-reservoir-pump-service";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import {
SEWAGE_RESERVOIR_STATS_CD,
type SewageReservoirItem,
type SewageReservoirRequestParams,
type SewageReservoirSaveItem,
type RainfallPumpStationItem,
type SewageReservoirVerificationResult,
} from "@/entities/statistics/model/input/statistics-input-sewage-reservoir-pump-interface";
import type {
ApiResponse,
cancelSubmitRequest,
Sgg,
SewerageStatusInfo,
} from "@/entities/statistics/model/statistics-interface";
import { useAlertStore, useStatisticsInputToolbarGroupGate } from "@/shared/lib";
import { ConfirmDialog } from "@/shared/ui/confirm-dialog";
import { useAdminStore } from "@/store/admin-store";
import { getUserInfo } from "../../../../../../packages/common/components/src/api";
const SewageReservoirPumpInpTabList = [
SewageReservoirInpColumn,
RainfallPumpStationInpColumn,
@@ -144,7 +156,7 @@ function buildSewageReservoirSearchParam(
};
}
/** 항목 추가 시 빈 행 (시도는 조회 시 선택한 시도명) */
/** 항목 추가 시 빈 행 (`ctpvNm` = 조회 시도명) */
function createEmptySewageReservoirRow(
ctpvNm: string,
sggNm = "",
@@ -248,6 +260,108 @@ function mapSewageReservoirListToGridRows(
});
}
function nullableTrimmedString(
value: string | number | null | undefined,
): string | null {
const s = String(value ?? "").trim();
return s === "" ? null : s;
}
function toGridNumber(value: string | number | null | undefined): number {
const n = Number(value);
return Number.isFinite(n) ? n : 0;
}
/** API 조회 항목 → 저장/삭제 API 형식 (조회 직후 스냅샷용) */
function buildSewageReservoirSaveItemFromApiItem(
item: SewageReservoirItem,
): SewageReservoirSaveItem {
return buildSewageReservoirSaveItem(
item as unknown as Record<string, string | number>,
);
}
function buildSewageReservoirDeleteList(
loadedSnapshot: SewageReservoirSaveItem[],
currentRows: Record<string, string | number>[],
): SewageReservoirSaveItem[] {
const currentFcltSnSet = new Set(
currentRows
.map((row) => String(row.fcltSn ?? "").trim())
.filter((sn) => sn !== ""),
);
return loadedSnapshot.filter((item) => {
const sn = String(item.fcltSn ?? "").trim();
return sn !== "" && !currentFcltSnSet.has(sn);
});
}
/** 시군구명(`sggNm`) 기준 행정구역 코드·명 */
function resolveSewageReservoirAdmdst(
sggNm: string,
sggOptions: Sgg[],
): { admdstCd: string; admdstNm: string } {
const trimmed = sggNm.trim();
const matched = sggOptions.find((s) => s.gugun === trimmed);
if (matched) {
return { admdstCd: matched.adstDstrCd, admdstNm: matched.gugun };
}
return { admdstCd: "", admdstNm: 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: String(row.fcltSn ?? ""),
fcltNm: String(row.fcltNm ?? ""),
fcltPstnCn: String(row.fcltPstnCn ?? ""),
oprtngStrtYmd: toCompactYmd(row.oprtngStrtYmd),
planDesignFreqCnt: toGridNumber(row.planDesignFreqCnt),
fldngPrvtnYn: normalizeOxYnValue(row.fldngPrvtnYn),
wqPlltnMtgtYn: normalizeOxYnValue(row.wqPlltnMtgtYn),
rtlztnUsgYn: normalizeOxYnValue(row.rtlztnUsgYn),
fcltStrctCn: nullableTrimmedString(row.fcltStrctCn),
wtrStrgZoneArea: toGridNumber(row.wtrStrgZoneArea),
impdFcltCpct: toGridNumber(row.impdFcltCpct),
grssPpqty: toGridNumber(row.grssPpqty),
pumpFcltN1DmtrExpln: String(row.pumpFcltN1DmtrExpln ?? ""),
pumpFcltN1PerPpqty: toGridNumber(row.pumpFcltN1PerPpqty),
pumpFcltN1PumpCnt: toGridNumber(row.pumpFcltN1PumpCnt),
pumpFcltN1RsrvPumpCnt: toGridNumber(row.pumpFcltN1RsrvPumpCnt),
pumpFcltN2DmtrExpln: String(row.pumpFcltN2DmtrExpln ?? ""),
pumpFcltN2PerPpqty: toGridNumber(row.pumpFcltN2PerPpqty),
pumpFcltN2PumpCnt: toGridNumber(row.pumpFcltN2PumpCnt),
pumpFcltN2RsrvPumpCnt: toGridNumber(row.pumpFcltN2RsrvPumpCnt),
pumpFcltN3DmtrExpln: String(row.pumpFcltN3DmtrExpln ?? ""),
pumpFcltN3PerPpqty: toGridNumber(row.pumpFcltN3PerPpqty),
pumpFcltN3PumpCnt: toGridNumber(row.pumpFcltN3PumpCnt),
pumpFcltN3RsrvPumpCnt: toGridNumber(row.pumpFcltN3RsrvPumpCnt),
prcsgFcltYn: String(row.prcsgFcltYn ?? ""),
ddrztnEqpmYn: String(row.ddrztnEqpmYn ?? ""),
oslfEtgtYn: String(row.oslfEtgtYn ?? ""),
mltvMthCn: nullableTrimmedString(row.mltvMthCn),
impdMthCn: nullableTrimmedString(row.impdMthCn),
impdPrcsMthdCn: nullableTrimmedString(row.impdPrcsMthdCn),
dschgWtrsExpln: String(row.dschgWtrsExpln ?? ""),
prcptnLastDspsQnt: toGridNumber(row.prcptnLastDspsQnt),
ctmnLastDspsQnt: toGridNumber(row.ctmnLastDspsQnt),
prcptnLastDspsMthdExpln: String(row.prcptnLastDspsMthdExpln ?? ""),
ctmnLastDspsMthdExpln: String(row.ctmnLastDspsMthdExpln ?? ""),
oprtngDayCnt: toGridNumber(row.oprtngDayCnt),
grssMltvQnt: toGridNumber(row.grssMltvQnt),
rmrk: nullableTrimmedString(row.rmrk),
};
}
function mapRainfallPumpStationListToGridRows(
list: RainfallPumpStationItem[],
ctpvNm: string,
@@ -275,6 +389,7 @@ function mapRainfallPumpStationListToGridRows(
// 하수도 통계 관리 > 04. 하수저류 시설 및 빗물 펌프장
const SewageReservoirPumpInp = () => {
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const { isAdminInfo } = useAdminStore();
const toolbarGroupAllowed = useStatisticsInputToolbarGroupGate();
@@ -282,24 +397,228 @@ const SewageReservoirPumpInp = () => {
console.log("submit");
};
const saveFunc = () => {
console.log("save");
};
/** 마지막 조회 시 서버에 있던 하수저류시설 목록 (deleteList 비교 기준) */
const loadedSewageReservoirSnapshotRef = useRef<SewageReservoirSaveItem[]>([]);
const cnacelSubmitFunc = () => {
console.log("cancel submit");
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 = {
sewerBzmnCd: lastSearchedValues.bsnmCd ?? "",
ctpvNm: lastSearchedValues.sido ?? "",
sggNm:
lastSearchedValues.gugun === "ALL"
? ""
: (lastSearchedValues.gugun ?? ""),
statsYr: lastSearchedValues.year ?? "",
mdfrId: userInfo.userUnqId,
statsCd: statsCdForTab,
};
const response = await statisticsApi.cancelSubmit(requestData);
if (response.status === "success") {
setIsLoading(true);
await loadActiveTabData(tabKey, lastSearchedValues, false, 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 = () => {
console.log("delete article");
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 nextRows = currentRows.filter((_, idx) => !checkedIndexSet.has(idx));
if (nextRows.length === currentRows.length) {
alert("삭제할 항목을 선택해주세요.");
return;
}
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) {
alert("저장할 수 없는 탭입니다.");
return;
}
if (!lastSearchedValues) {
alert("먼저 조회를 진행해주세요.");
return;
}
if (!buildGugunOkForToolbar(lastSearchedValues)) {
alert("시군구를 선택해주세요.");
return;
}
if (!(await confirm("저장 하시겠습니까?"))) return;
commitGridForTab(tabKey);
const noApplicable = isNotApplicableByTab.get(tabKey) ?? false;
const currentData = getCurrentRowsForTab(tabKey);
const saveList = noApplicable
? []
: currentData.map((row) =>
buildSewageReservoirSaveItem(row, sggOptions),
);
const deleteList = buildSewageReservoirDeleteList(
loadedSewageReservoirSnapshotRef.current,
currentData,
);
if (!noApplicable && saveList.length === 0 && deleteList.length === 0) {
alert("저장할 변경 사항이 없습니다.");
return;
}
try {
setIsLoading(true);
const userInfo = await getUserInfo();
const response =
await statisticsInputSewageReservoirPumpApi.saveSewageReservoir({
statsYr: lastSearchedValues.year ?? "",
ctpvNm: lastSearchedValues.sido ?? "",
sggNm:
lastSearchedValues.gugun === "ALL"
? ""
: (lastSearchedValues.gugun ?? ""),
sewerBzmnCd: lastSearchedValues.bsnmCd ?? "",
userId: userInfo.userUnqId,
...(isAdminInfo ? { superAdmin: "superAdmin" } : {}),
...(noApplicable ? { noApplicable: true } : {}),
saveList,
deleteList,
});
if (response.status === "success") {
await loadActiveTabData(tabKey, lastSearchedValues, false, false);
alert("저장되었습니다.");
} else {
alert(response.message ?? "저장 중 오류가 발생했습니다.");
}
} catch {
alert("저장 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
})();
};
const [activeTab, setActiveTab] = useState(firstTabKey);
const [rowDataMap, setRowDataMap] = useState<
Map<string, Record<string, string | number>[]>
>(new Map());
const [isNotApplicable, setIsNotApplicable] = useState(false);
const [showIsNotApplicable, setShowIsNotApplicable] = useState(false);
const [isNotApplicableByTab, setIsNotApplicableByTab] = useState<Map<string, boolean>>(
() => new Map(),
);
const [searchValues, setSearchValues] = useState<SearchFormValues | null>(null);
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(
null,
@@ -317,13 +636,40 @@ const SewageReservoirPumpInp = () => {
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
const [sggOptions, setSggOptions] = useState<Sgg[]>([]);
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 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,
@@ -371,8 +717,8 @@ const SewageReservoirPumpInp = () => {
updateLastSearchedValues: boolean,
overrides?: { mode?: string },
): Promise<boolean> => {
// 서버 데이터로 새로 불러오는 시점이므로 "해당없음" 체크는 항상 초기화
setIsNotApplicable(false);
// 서버 데이터로 새로 불러오는 시점이므로 현재 탭의 "해당없음" 체크는 초기화
setIsNotApplicableForTab(tabKey, false);
if (tabKey === SEWAGE_RESERVOIR_STATS_CD) {
const response =
await statisticsInputSewageReservoirPumpApi.getSewageReservoirList(
@@ -386,15 +732,14 @@ const SewageReservoirPumpInp = () => {
const { commonInfo, statusInfo, sewageReservoirList } = response.data;
const list = sewageReservoirList ?? [];
loadedSewageReservoirSnapshotRef.current = list
.filter((item) => String(item.fcltSn ?? "").trim() !== "")
.map(buildSewageReservoirSaveItemFromApiItem);
const gridRows = mapSewageReservoirListToGridRows(
list,
commonInfo.ctpvNm,
);
if (activeTabRef.current === tabKey) {
setShowIsNotApplicable(list.length === 0);
}
applyRowMap(mergeIntoExistingMap, (m) => {
m.set(tabKey, gridRows);
});
@@ -409,6 +754,7 @@ const SewageReservoirPumpInp = () => {
gridRows.length > 0,
values,
);
loadedTabKeysRef.current.add(tabKey);
return true;
}
@@ -444,6 +790,7 @@ const SewageReservoirPumpInp = () => {
gridRows.length > 0,
values,
);
loadedTabKeysRef.current.add(tabKey);
return true;
}
@@ -490,6 +837,7 @@ const SewageReservoirPumpInp = () => {
}, []);
const handleReset = () => {
loadedSewageReservoirSnapshotRef.current = [];
setRowDataMap(new Map());
setTabStatusInfoMap(new Map());
setTabStatsCdMap(new Map());
@@ -499,10 +847,10 @@ const SewageReservoirPumpInp = () => {
sggOptionsSidoRef.current = null;
setHasSearched(false);
setInputPeriodEnterable(true);
setIsNotApplicable(false);
setShowIsNotApplicable(false);
setIsNotApplicableByTab(new Map());
searchDoneRef.current = false;
periodEnterableRef.current = true;
loadedTabKeysRef.current.clear();
setActiveTab(firstTabKey);
};
@@ -521,6 +869,7 @@ const SewageReservoirPumpInp = () => {
setTabStatusInfoMap(new Map());
setTabStatsCdMap(new Map());
setToolbarSnapshotByTab(new Map());
loadedTabKeysRef.current.clear();
setActiveTab(firstTabKey);
}
@@ -529,6 +878,12 @@ const SewageReservoirPumpInp = () => {
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 = yearChangedFromLastSearch ? firstTabKey : activeTabRef.current;
if (yearChangedFromLastSearch) {
@@ -551,15 +906,21 @@ const SewageReservoirPumpInp = () => {
};
const handleActiveTabChange = async (tabKey: string) => {
setActiveTab(tabKey);
if (tabKey === SEWAGE_RESERVOIR_STATS_CD) {
setShowIsNotApplicable(
hasSearched && !tabRowDataExists(rowDataMap, tabKey),
);
} else {
setShowIsNotApplicable(false);
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 {
@@ -602,6 +963,26 @@ const SewageReservoirPumpInp = () => {
activeTab === SEWAGE_RESERVOIR_STATS_CD || activeTab === rainfallPumpTabKey;
const showArticleToolbarCard =
hasSearched && isReservoirOrRainfallTab && toolbarGroupAllowed;
const isNotApplicableForActiveTab = isNotApplicableByTab.get(activeTab) ?? false;
const showNotApplicableForActiveTab =
loadedTabKeysRef.current.has(activeTab) &&
shouldShowNotApplicable(
activeTab,
tabRowDataExists(rowDataMap, activeTab),
tabStatusInfoMap.get(activeTab),
);
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;
@@ -673,8 +1054,6 @@ const SewageReservoirPumpInp = () => {
// 행 추가 직후 setColumnProperty를 강제 재적용하면 타이밍 이슈로
// `fieldIndex is out of bounds`가 발생할 수 있어 제거한다.
setShowIsNotApplicable(false);
const statusInfo = tabStatusInfoMap.get(tabKey) ?? null;
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, true, ctx);
};
@@ -690,6 +1069,13 @@ const SewageReservoirPumpInp = () => {
) || isAdminInfo;
const isReservoirTab = tabKey === SEWAGE_RESERVOIR_STATS_CD;
const columns = (tab.columns ?? []).map((col: ColumnConfig) => {
if (isReservoirTab && col.fieldName === "ctpvNm") {
return {
...col,
editable: false as const,
styleName: col.styleName ?? "rg-cell-readonly",
};
}
if (isReservoirTab && col.fieldName === "sggNm") {
return buildSggNmColumn(col, canEdit, sggOptions);
}
@@ -709,31 +1095,6 @@ const SewageReservoirPumpInp = () => {
return map;
}, [tabStatusInfoMap, inputPeriodEnterable, isAdminInfo, sggOptions]);
const handleSewageReservoirCellEdited = useCallback(
(params: CellEditedCallbackParams) => {
if (params.fieldName !== "sggNm") return;
const selected = sggOptions.find((s) => s.gugun === params.newValue);
if (!selected) return;
const tabKey = SEWAGE_RESERVOIR_STATS_CD;
setRowDataMap((prev) => {
const next = new Map(prev);
const rows = [...(next.get(tabKey) ?? [])];
const row = rows[params.itemIndex];
if (!row) return prev;
rows[params.itemIndex] = {
...row,
sggNm: selected.gugun,
admdstCd: selected.adstDstrCd,
admdstNm: selected.gugun,
};
next.set(tabKey, rows);
return next;
});
},
[sggOptions],
);
const verificationCellStyle = ({
fieldName,
row,
@@ -817,10 +1178,10 @@ const SewageReservoirPumpInp = () => {
{showArticleToolbarCard && (
<div className="card !py-0">
<div className="m-[0.6rem] flex items-center justify-end gap-[0.6rem]">
{showIsNotApplicable && (
{showNotApplicableForActiveTab && (
<NotApplicableCheckButton
isCheck={isNotApplicable}
setIsCheck={setIsNotApplicable}
isCheck={isNotApplicableForActiveTab}
setIsCheck={setIsNotApplicableForActiveTab}
/>
)}
<AddArticleButton addArticleFunc={addArticleFunc} />
@@ -859,13 +1220,13 @@ const SewageReservoirPumpInp = () => {
return (
<TabsContent key={tabKey} value={tabKey}>
<DataGrid
key={
tabEnterableForGrid || isAdminInfo
? `${tabKey}-enterable`
: `${tabKey}-readonly`
}
key={tabKey}
getGridRef={
isReservoirTab ? reservoirGridRef : undefined
isReservoirTab
? reservoirGridRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridRef
: undefined
}
columnInfo={
columnInfoByTab.get(tabKey) ??
@@ -894,6 +1255,13 @@ const SewageReservoirPumpInp = () => {
return next;
});
}}
getGridDataRef={
tabKey === SEWAGE_RESERVOIR_STATS_CD
? reservoirGridGetRowsRef
: tabKey === rainfallPumpTabKey
? rainfallPumpGridGetRowsRef
: undefined
}
showHeaderCheckbox
statusInfo={tabStatusInfo}
isExcelImport={
@@ -903,13 +1271,6 @@ const SewageReservoirPumpInp = () => {
}
cellStyleCallback={verificationCellStyle}
cellTooltipCallback={verificationCellTooltip}
onCellEdited={
isReservoirTab &&
tabEnterableForGrid &&
sggOptions.length > 0
? handleSewageReservoirCellEdited
: undefined
}
/>
</TabsContent>
);
@@ -921,6 +1282,7 @@ const SewageReservoirPumpInp = () => {
onOpenChange={setVerificationHistoryOpen}
queryContext={verificationQueryContext}
/>
<ConfirmDialog isOpen={false} />
</>
);
};