1305 lines
60 KiB
TypeScript
1305 lines
60 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
|
|
import { useConfirm } from '@frontend-opensource/use-react-hooks';
|
|
|
|
import { useAlertStore, useGlobalProgressStore, useStatisticsInputToolbarGroupGate } from '@/shared/lib';
|
|
import { statisticsInputSewSupplyRateApi } from '@/entities/statistics/api/input/statistics-input-sew-supply-rate-service';
|
|
import { statisticsInputPublicSewageFacilityApiService } from '@/entities/statistics/api/input/statistics-public-sewage-facility-input-service';
|
|
import { statisticsApi } from '@/entities/statistics/api/statistics-service';
|
|
import type {
|
|
PublicSewageFacilityRequestParams,
|
|
PublicSewageFacilitySaveItem,
|
|
PublicSewageFacilitySaveRequest,
|
|
PublicSewageMainFacilityMappingSaveItem,
|
|
PublicSewageMainFacilityMappingSaveRequest,
|
|
PublicSewageMappingTargetsRequestParams,
|
|
} from '@/entities/statistics/model/input/statistics-public-sewage-facility-input-interface';
|
|
import {
|
|
type CheckInputPeriodItem,
|
|
getVerificationPeriodActionBlockedMessage,
|
|
isInputPeriodCurrent,
|
|
type SewerageSupplyRateVerificationResult,
|
|
} 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 } from '@/entities/statistics/model/statistics-interface';
|
|
import { LoadingWithAnimation, Tabs, TabsContent, TabsList, TabsTrigger } from '@common/components';
|
|
|
|
import { getUserInfo } from '../../../../../../packages/common/components/src/api';
|
|
|
|
import { MainFacilityMappingSaveDialog, type MainFacilityMappingSaveDialogValues } from './MainFacilityMappingSaveDialog';
|
|
import SubmitDailog from './SubmitDailog';
|
|
|
|
import CancelSubmitButton from '@/components/button/CancelSubmitButton';
|
|
import NotApplicableCheckButton from '@/components/button/NotApplicableCheckButton';
|
|
import SaveButton from '@/components/button/SaveButton';
|
|
import SubmitButton from '@/components/button/SumitButton';
|
|
import UpdateOperateDataButton from '@/components/button/UpdateOperateDataButton';
|
|
import VerificationResultButton from '@/components/button/VerificationResultButton';
|
|
import DataGrid from '@/components/module/DataGrid';
|
|
import SearchForm from '@/components/module/SearchForm';
|
|
import SplitDataGrid from '@/components/module/SplitDataGrid';
|
|
import { openVerificationResultDialogIfNeeded } from '@/components/module/post-submit-verification-results';
|
|
import { VerificationResultDialog } from '@/components/module/VerificationResultDialog';
|
|
import { VerificationResultHistoryDialog } from '@/components/module/VerificationResultHistoryDialog';
|
|
import type { CellStyleCallbackParams, ColumnInfo, ColumnInfoList } from '@/components/type/DataGrid.type';
|
|
import type { SearchFormValues } from '@/components/type/SearchForm.type';
|
|
import { doList } from '@/components/util/column/input/DoList';
|
|
import { PublicSewageFactInpColumnList } from '@/components/util/column/input/PublicSewageFactInpColumn/PublicSewageFactInpColumn';
|
|
import { toGridRows } from '@/components/util/grid/gridFunction';
|
|
import { useAdminStore } from '@/store/admin-store';
|
|
|
|
type GridRowWithVerification = Record<string, string | number> & {
|
|
verificationResult?: SewerageSupplyRateVerificationResult;
|
|
};
|
|
|
|
type TabToolbarSnapshot = {
|
|
showSaveInToolbar: boolean;
|
|
showEnterableToolbarButtons: boolean;
|
|
showActionToolbarCard: boolean;
|
|
};
|
|
|
|
function buildGugunOkForToolbar(values: SearchFormValues | null): boolean {
|
|
return doList.includes(values?.bsnmCd || '')
|
|
? Boolean(values?.gugun && values.gugun !== 'ALL')
|
|
: true;
|
|
}
|
|
|
|
const computeTabEnterable = (
|
|
statusInfo: SewerageStatusInfo | null | undefined,
|
|
periodEnterable: boolean,
|
|
): boolean => {
|
|
if (statusInfo?.laeSbmsnSttsCd) {
|
|
if (['2', '3'].includes(statusInfo.laeSbmsnSttsCd)) {
|
|
return false;
|
|
}
|
|
return periodEnterable;
|
|
}
|
|
return periodEnterable;
|
|
};
|
|
|
|
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) && gugunOk;
|
|
const showEnterableToolbarButtons = enterable && gugunOk;
|
|
const showSubmittedInInputPeriodToolbar = isSubmitted && periodEnterable && gugunOk;
|
|
const showActionToolbarCard =
|
|
(hasRowData || treatAsSearched) &&
|
|
(showSaveInToolbar ||
|
|
showEnterableToolbarButtons ||
|
|
showSubmittedInInputPeriodToolbar ||
|
|
(isSubmitted && isAdminInfo));
|
|
return { showSaveInToolbar, showEnterableToolbarButtons, showActionToolbarCard };
|
|
}
|
|
|
|
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 || `IMR 검증이 ${res.status} 상태로 종료되었습니다.`);
|
|
}
|
|
await sleep(pollIntervalMs);
|
|
}
|
|
throw new Error('IMR 검증 완료 대기 시간이 초과되었습니다.');
|
|
}
|
|
|
|
type MainFacilityMappingSaveDraft = {
|
|
statsYr: string;
|
|
sewerBzmnCd: string;
|
|
admdstCd: string;
|
|
admdstNm: string;
|
|
mainFcltSn: string;
|
|
mainFcltNm: string;
|
|
initialCnsgnCstVl: number;
|
|
saveList: PublicSewageMainFacilityMappingSaveItem[];
|
|
deleteList: string[];
|
|
initialPrxyBzentyNmCn: string;
|
|
initialWholNope: number;
|
|
initialPrxyCtrtCn: string;
|
|
};
|
|
|
|
const PUBLIC_SEWAGE_FACILITY_COLUMN_GUIDE_TAB_KEYS = Array.from(
|
|
new Set(PublicSewageFactInpColumnList.map((tab) => tab.tabKey).filter(Boolean)),
|
|
);
|
|
|
|
// 하수도 통계 관리 > 06. 공공하수처리시설
|
|
const PublicSewageFacilityInp = () => {
|
|
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);
|
|
const globalProgressVisible = useGlobalProgressStore((state) => state.visible);
|
|
const [isLoading, setIsLoading] = useState<boolean>(false);
|
|
const [hasSearched, setHasSearched] = useState(false);
|
|
const [isNotApplicable, setIsNotApplicable] = useState(false);
|
|
const [showIsNotApplicable, setShowIsNotApplicable] = useState(false);
|
|
const [searchValues, setSearchValues] = useState<SearchFormValues | null>(null);
|
|
const [lastSearchedValues, setLastSearchedValues] = useState<SearchFormValues | null>(null);
|
|
const [tabStatusInfoMap, setTabStatusInfoMap] = useState<Map<string, SewerageStatusInfo | null>>(new Map());
|
|
const [tabStatsCdMap, setTabStatsCdMap] = useState<Map<string, string>>(new Map());
|
|
/** 탭키별 `engColNm -> columnGuide` 캐시 */
|
|
const [columnGuidesByTab, setColumnGuidesByTab] = useState<Record<string, Record<string, string>>>({});
|
|
const [toolbarSnapshotByTab, setToolbarSnapshotByTab] = useState<Map<string, TabToolbarSnapshot>>(() => new Map());
|
|
const [inputPeriodEnterable, setInputPeriodEnterable] = useState(true);
|
|
const [periodCheckList, setPeriodCheckList] = useState<CheckInputPeriodItem[]>([]);
|
|
const [showDailog, setShowDailog] = useState<boolean>(false);
|
|
const [selectedMainFacilitySn, setSelectedMainFacilitySn] = useState<string | null>(null);
|
|
const mainFacilityMappingSaveDraftRef = useRef<MainFacilityMappingSaveDraft | null>(null);
|
|
const [mainFacilityMappingSaveDialogOpen, setMainFacilityMappingSaveDialogOpen] = useState(false);
|
|
const [mainFacilityMappingSaveDialogKey, setMainFacilityMappingSaveDialogKey] = useState(0);
|
|
const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false);
|
|
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
|
|
|
|
const periodEnterableRef = useRef(true);
|
|
const searchDoneRef = useRef(false);
|
|
/** ST00060001만: RealGrid 편집값이 state에 없을 수 있어 저장/제출 시 그리드에서 직접 읽음 */
|
|
const st60001GridGetRowsRef = useRef<(() => Record<string, string | number>[]) | null>(null);
|
|
|
|
const submitFunc = () => {
|
|
void (async () => {
|
|
if (activeTab !== 'ST00060001') {
|
|
alert('ST00060002 제출 API 연동 전입니다.');
|
|
return;
|
|
}
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert('먼저 조회를 진행해주세요.');
|
|
return;
|
|
}
|
|
const currentData =
|
|
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
|
|
if (!currentData || currentData.length === 0) {
|
|
alert('제출할 데이터가 없습니다.');
|
|
return;
|
|
}
|
|
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
|
|
if (verificationBlocked) {
|
|
alert(verificationBlocked);
|
|
return;
|
|
}
|
|
if (await confirm('제출 하시겠습니까?')) {
|
|
setShowDailog(true);
|
|
}
|
|
})();
|
|
};
|
|
|
|
const buildFacilitySaveList = (currentData: Record<string, string | number>[]): PublicSewageFacilitySaveItem[] => {
|
|
const toNumber = (v: unknown): number => {
|
|
if (v === null || v === undefined) return 0;
|
|
if (v === '') return 0;
|
|
const num = typeof v === 'string' ? parseFloat(v.replace(/,/g, '')) : (v as number);
|
|
return Number.isFinite(num) ? num : 0;
|
|
};
|
|
|
|
const toNullableString = (v: unknown): string | null => {
|
|
if (v === null || v === undefined) return null;
|
|
const s = typeof v === 'string' ? v : String(v);
|
|
return s.trim() === '' ? null : s;
|
|
};
|
|
|
|
return currentData.map((d) => ({
|
|
admdstCd: String(d.admdstCd ?? ''),
|
|
admdstNm: String(d.admdstNm ?? ''),
|
|
swtrmtFcltCd: String(d.swtrmtFcltCd ?? ''),
|
|
swtrmtFcltNm: String(d.swtrmtFcltNm ?? ''),
|
|
fcltSn: String(d.fcltSn ?? ''),
|
|
fcltPstnCn: d.fcltPstnCn === '' ? null : toNullableString(d.fcltPstnCn),
|
|
inflwSwagePhysQnt: toNumber(d.inflwSwagePhysQnt),
|
|
inflwSwageBoilQnt: toNumber(d.inflwSwageBoilQnt),
|
|
inflwSwageAltdQnt: toNumber(d.inflwSwageAltdQnt),
|
|
prcsPhysCpct: toNumber(d.prcsPhysCpct),
|
|
prcsBoilCpct: toNumber(d.prcsBoilCpct),
|
|
prcsAltdCpct: toNumber(d.prcsAltdCpct),
|
|
prxyCtrtCn: d.prxyCtrtCn === '' ? null : toNullableString(d.prxyCtrtCn),
|
|
sftyAcdntEvntcsCnt: toNumber(d.sftyAcdntEvntcsCnt),
|
|
rmrk: toNullableString(d.rmrk),
|
|
}));
|
|
};
|
|
|
|
const getNoApplicableForRequest = (): boolean => {
|
|
const activeTabStatus = tabStatusInfoMap.get(activeTab) ?? null;
|
|
const searchContextForToolbar = lastSearchedValues ?? searchValues;
|
|
const gugunOk = buildGugunOkForToolbar(searchContextForToolbar);
|
|
const enterable = computeTabEnterable(activeTabStatus, inputPeriodEnterable);
|
|
const showEnterableToolbarButtons = enterable && gugunOk;
|
|
const noApplicableVisible = showEnterableToolbarButtons && showIsNotApplicable;
|
|
return noApplicableVisible ? Boolean(isNotApplicable) : 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 executeSubmit = async (submitInfo: StatisticsInputSubmitInfoFormData) => {
|
|
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
|
|
if (verificationBlocked) {
|
|
alert(verificationBlocked);
|
|
return;
|
|
}
|
|
if (activeTab !== 'ST00060001') {
|
|
alert('ST00060002 제출 API 연동 전입니다.');
|
|
return;
|
|
}
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert('먼저 조회를 진행해주세요.');
|
|
return;
|
|
}
|
|
const currentData =
|
|
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
|
|
if (!currentData || currentData.length === 0) {
|
|
alert('제출할 데이터가 없습니다.');
|
|
return;
|
|
}
|
|
|
|
try {
|
|
showGlobalProgress({ label: '서버에 요청 중...', progress: 0 });
|
|
const userInfo = await getUserInfo();
|
|
const submitList = buildFacilitySaveList(currentData);
|
|
const activeTabStatus = tabStatusInfoMap.get(activeTab) ?? null;
|
|
const statsCdForTab = tabStatsCdMap.get(activeTab) ?? activeTab;
|
|
const requestData = {
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
ctpvNm: lastSearchedValues.sido ?? '',
|
|
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : lastSearchedValues.gugun ?? '',
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
userId: userInfo.userUnqId,
|
|
noApplicable: getNoApplicableForRequest(),
|
|
laePicNm: submitInfo.laePicNm,
|
|
laeKbrdrJbgdNm: submitInfo.laeKbrdrJbgdNm,
|
|
laeKbrdrDeptNm: submitInfo.laeKbrdrDeptNm,
|
|
laePicTelNo: submitInfo.laePicTelNo,
|
|
laeIdfrNm: submitInfo.laeIdfrNm,
|
|
laeIdfrJbgdNm: submitInfo.laeIdfrJbgdNm,
|
|
laeIdfrDeptNm: submitInfo.laeIdfrDeptNm,
|
|
laeIdfrTelNo: submitInfo.laeIdfrTelNo,
|
|
submitList,
|
|
};
|
|
|
|
setGlobalProgressLabel('일반 검증 진행 중...');
|
|
const response =
|
|
await statisticsInputPublicSewageFacilityApiService.submitPublicSewageFacility(
|
|
requestData,
|
|
);
|
|
|
|
if (response.status !== 'success') {
|
|
alert(response.message || '데이터 제출 중 오류가 발생했습니다.');
|
|
return;
|
|
}
|
|
|
|
const finalStatus = response.data?.finalStatus;
|
|
const nvpassed = response.data?.nvpassed;
|
|
|
|
if (finalStatus === '5') {
|
|
setGlobalProgress(50);
|
|
setGlobalProgressLabel('IMR 검증 진행 중...');
|
|
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',
|
|
};
|
|
|
|
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 loadPublicSewageFacilityActiveTabData(
|
|
'ST00060001',
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
await openVerificationResultDialogIfNeeded(
|
|
{
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
ctpvNm: lastSearchedValues.sido ?? '',
|
|
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : (lastSearchedValues.gugun ?? ''),
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
statsCd: statsCdForTab,
|
|
},
|
|
setVerificationResultDialogOpen,
|
|
{ notify: alert },
|
|
);
|
|
} catch (e) {
|
|
await loadPublicSewageFacilityActiveTabData(
|
|
'ST00060001',
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
await openVerificationResultDialogIfNeeded(
|
|
{
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
ctpvNm: lastSearchedValues.sido ?? '',
|
|
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : (lastSearchedValues.gugun ?? ''),
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
statsCd: statsCdForTab,
|
|
},
|
|
setVerificationResultDialogOpen,
|
|
{ notify: alert, notifySubmitComplete: false },
|
|
);
|
|
const msg =
|
|
e instanceof Error && e.message
|
|
? e.message
|
|
: 'IMR 검증 중 오류가 발생했습니다.\n관리자에게 문의하세요.';
|
|
alert(msg);
|
|
}
|
|
} else {
|
|
setGlobalProgress(100);
|
|
await loadPublicSewageFacilityActiveTabData(
|
|
'ST00060001',
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
await openVerificationResultDialogIfNeeded(
|
|
{
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
ctpvNm: lastSearchedValues.sido ?? '',
|
|
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : (lastSearchedValues.gugun ?? ''),
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
statsCd: statsCdForTab,
|
|
},
|
|
setVerificationResultDialogOpen,
|
|
{ notify: alert },
|
|
);
|
|
}
|
|
} catch {
|
|
alert('데이터 제출 중 오류가 발생했습니다.');
|
|
} finally {
|
|
hideGlobalProgress();
|
|
}
|
|
};
|
|
|
|
const saveFunc = () => {
|
|
void (async () => {
|
|
if (!lastSearchedValues || !searchParamRef.current) {
|
|
alert('먼저 조회를 진행해주세요.');
|
|
return;
|
|
}
|
|
|
|
if (activeTab === 'ST00060002') {
|
|
const statusCodeResponse = await statisticsApi.CheckStatusCode({
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
statsCd: 'ST00060001',
|
|
statsYr: lastSearchedValues.year ?? ''
|
|
});
|
|
|
|
if (statusCodeResponse.status === 'success') {
|
|
if (!['0', '1', '4'].includes(statusCodeResponse.data)) {
|
|
const codeName = statusCodeResponse.data === '2' ? '제출' : (statusCodeResponse.data === '3' ? '승인' : '검증중');
|
|
alert(`공공 하수처리 시설 데이터가 ${codeName} 상태일 때는 중심 처리 시설 데이터를 변경할 수 없습니다.`);
|
|
return;
|
|
}
|
|
} else {
|
|
alert('오류가 발생했습니다.\n관리자에게 문의하세요')
|
|
}
|
|
|
|
if (!(await confirm('저장 하시겠습니까?'))) return;
|
|
|
|
const leftRows = rowDataMap.get('MainFacility') ?? [];
|
|
const rightRows = rowDataMap.get('MainFacilityTarget') ?? [];
|
|
if (!leftRows.length || !rightRows.length) {
|
|
alert('저장할 데이터가 없습니다.');
|
|
return;
|
|
}
|
|
if (!selectedMainFacilitySn) {
|
|
alert('좌측에서 중심 처리 시설을 먼저 선택해주세요.');
|
|
return;
|
|
}
|
|
|
|
const selectedMain = leftRows.find((r) => String(r.fcltSn ?? '') === selectedMainFacilitySn);
|
|
if (!selectedMain) {
|
|
alert('선택된 중심 처리 시설 정보를 찾을 수 없습니다.');
|
|
return;
|
|
}
|
|
|
|
const saveList: PublicSewageMainFacilityMappingSaveItem[] = rightRows
|
|
.filter((r) => isCheckedRow(r))
|
|
.map((r) => ({
|
|
fcltSn: String(r.fcltSn ?? ''),
|
|
admdstCd: String(r.admdstCd ?? ''),
|
|
admdstNm: String(r.admdstNm ?? ''),
|
|
swtrmtFcltCd: String(r.swtrmtFcltCd ?? ''),
|
|
swtrmtFcltNm: String(r.swtrmtFcltNm ?? ''),
|
|
isMainYn: String(r.isMainYn ?? ''),
|
|
}));
|
|
|
|
const deleteList = rightRows
|
|
.filter((r) => String(r.mappedYn ?? '') === 'Y' && !isCheckedRow(r))
|
|
.map((r) => String(r.fcltSn ?? ''))
|
|
.filter((sn) => sn !== '');
|
|
|
|
const wholNopeFromRow = Number(selectedMain.wholNope ?? 0);
|
|
const deleteOnly = saveList.length === 0 && deleteList.length > 0;
|
|
const nothingToPersist = saveList.length === 0 && deleteList.length === 0;
|
|
if (nothingToPersist) {
|
|
alert('저장할 변경 사항이 없습니다.');
|
|
return;
|
|
}
|
|
|
|
mainFacilityMappingSaveDraftRef.current = {
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
admdstCd: String(selectedMain.admdstCd ?? ''),
|
|
admdstNm: String(selectedMain.admdstNm ?? ''),
|
|
mainFcltSn: String(selectedMain.fcltSn ?? ''),
|
|
mainFcltNm: String(selectedMain.swtrmtFcltNm ?? ''),
|
|
initialCnsgnCstVl: Number(selectedMain.cnsgnCstVl ?? 0),
|
|
saveList,
|
|
deleteList,
|
|
initialPrxyBzentyNmCn: String(selectedMain.prxyBzentyNmCn ?? ''),
|
|
initialWholNope: Number.isFinite(wholNopeFromRow) ? wholNopeFromRow : 0,
|
|
initialPrxyCtrtCn: String(selectedMain.prxyCtrtCn ?? ''),
|
|
};
|
|
|
|
if (deleteOnly) {
|
|
const draft = mainFacilityMappingSaveDraftRef.current;
|
|
const ok = await runMainFacilityMappingSave(draft, null);
|
|
if (ok) {
|
|
mainFacilityMappingSaveDraftRef.current = null;
|
|
}
|
|
return;
|
|
}
|
|
|
|
setMainFacilityMappingSaveDialogKey((k) => k + 1);
|
|
setMainFacilityMappingSaveDialogOpen(true);
|
|
return;
|
|
}
|
|
|
|
if (!(await confirm('저장 하시겠습니까?'))) return;
|
|
|
|
if (activeTab === 'ST00060001') {
|
|
try {
|
|
showGlobalProgress({ label: '저장 진행 중...', progress: 0 });
|
|
const userInfo = await getUserInfo();
|
|
const currentData =
|
|
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
|
|
if (!currentData || currentData.length === 0) {
|
|
alert('저장할 데이터가 없습니다.');
|
|
return;
|
|
}
|
|
|
|
const saveList = buildFacilitySaveList(currentData);
|
|
const param: PublicSewageFacilitySaveRequest = {
|
|
statsYr: lastSearchedValues.year ?? '',
|
|
ctpvNm: lastSearchedValues.sido ?? '',
|
|
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : lastSearchedValues.gugun ?? '',
|
|
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
|
|
userId: userInfo.userUnqId,
|
|
// superAdmin: isAdminInfo ? 'superAdmin' : '',
|
|
noApplicable: getNoApplicableForRequest(),
|
|
saveList,
|
|
};
|
|
|
|
const response =
|
|
await statisticsInputPublicSewageFacilityApiService.savePublicSewageFacility(
|
|
param,
|
|
);
|
|
if (response.status === 'success') {
|
|
setGlobalProgress(50);
|
|
await loadPublicSewageFacilityActiveTabData(
|
|
'ST00060001',
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
setGlobalProgress(100);
|
|
alert('저장되었습니다.');
|
|
} else {
|
|
alert(response.message || '데이터 저장 중 오류가 발생했습니다.');
|
|
}
|
|
} catch {
|
|
alert('데이터 저장 중 오류가 발생했습니다.');
|
|
} finally {
|
|
hideGlobalProgress();
|
|
}
|
|
return;
|
|
}
|
|
|
|
alert('현재 탭 저장 API 연동 전입니다.');
|
|
})();
|
|
};
|
|
|
|
const updateOperateDataButtonFunc = () => {
|
|
console.log('updatedOperateData');
|
|
// 운영 데이터 업데이트 로직
|
|
};
|
|
|
|
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
|
|
const [activeTab, setActiveTab] = useState<string>(
|
|
PublicSewageFactInpColumnList[0]?.tabKey ?? 'ST00060001',
|
|
);
|
|
const activeTabRef = useRef<string>(PublicSewageFactInpColumnList[0]?.tabKey ?? 'ST00060001');
|
|
const firstTabKey = PublicSewageFactInpColumnList[0]?.tabKey ?? 'ST00060001';
|
|
const searchParamRef = useRef<PublicSewageFacilityRequestParams | null>(null);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
void (async () => {
|
|
const entries = await Promise.all(
|
|
PUBLIC_SEWAGE_FACILITY_COLUMN_GUIDE_TAB_KEYS.map(async (tabKey) => {
|
|
try {
|
|
const res = await statisticsApi.getColumnGuides(tabKey);
|
|
if (res.status !== 'success' || !Array.isArray(res.data)) {
|
|
return [tabKey, {}] as const;
|
|
}
|
|
const next: Record<string, string> = {};
|
|
for (const item of res.data) {
|
|
const key = item.engColNm?.trim();
|
|
const guide = item.columnGuide?.trim();
|
|
if (key && guide) next[key] = guide;
|
|
}
|
|
return [tabKey, next] as const;
|
|
} catch {
|
|
return [tabKey, {}] as const;
|
|
}
|
|
}),
|
|
);
|
|
if (cancelled) return;
|
|
setColumnGuidesByTab(Object.fromEntries(entries));
|
|
})();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, []);
|
|
|
|
const commitToolbarSnapshotForLoadedTab = (
|
|
tabKey: string,
|
|
statusInfo: SewerageStatusInfo | null,
|
|
hasRowData: boolean,
|
|
searchContext: SearchFormValues | null,
|
|
) => {
|
|
setToolbarSnapshotByTab((prev) => {
|
|
const next = new Map(prev);
|
|
next.set(
|
|
tabKey,
|
|
computeTabToolbarSnapshot(
|
|
statusInfo,
|
|
hasRowData,
|
|
searchDoneRef.current,
|
|
searchContext,
|
|
periodEnterableRef.current,
|
|
isAdminInfo,
|
|
),
|
|
);
|
|
return next;
|
|
});
|
|
};
|
|
|
|
const buildPublicSewageFacilityParams = (values: SearchFormValues): PublicSewageFacilityRequestParams => ({
|
|
ctpvNm: values.sido,
|
|
sggNm: values.gugun === 'ALL' ? '' : values.gugun,
|
|
sewerBzmnCd: values.bsnmCd,
|
|
fcltNm: values.fctName,
|
|
statsYr: values.year,
|
|
});
|
|
|
|
const tabRowDataExists = (tabKey: string): boolean => {
|
|
if (tabKey === 'ST00060002') {
|
|
const left = rowDataMap.get('MainFacility');
|
|
const right = rowDataMap.get('MainFacilityTarget');
|
|
return (left?.length ?? 0) > 0 || (right?.length ?? 0) > 0;
|
|
}
|
|
return (rowDataMap.get(tabKey)?.length ?? 0) > 0;
|
|
};
|
|
|
|
const loadPublicSewageFacilityActiveTabData = async (
|
|
tabKey: string,
|
|
param: PublicSewageFacilityRequestParams,
|
|
searchContext: SearchFormValues | null,
|
|
): Promise<boolean> => {
|
|
try {
|
|
if (tabKey === 'ST00060001') {
|
|
const response = await statisticsInputPublicSewageFacilityApiService.getPublicSewageFacility(param);
|
|
if (response.status !== 'success') {
|
|
alert(response.message || '데이터 조회 중 오류가 발생했습니다.');
|
|
return false;
|
|
}
|
|
setSelectedMainFacilitySn(null);
|
|
const statusInfo = response.data.statusInfo ?? null;
|
|
const statsCd = response.data.commonInfo.statsCd || tabKey;
|
|
const commonInfo = response.data.commonInfo;
|
|
const list = response.data.publicSewageFacilityList ?? [];
|
|
const convertedData = list.map((item) => ({
|
|
ctpvNm: commonInfo.ctpvNm,
|
|
...item,
|
|
rmrk: item.rmrk ?? null,
|
|
}));
|
|
|
|
if (list.length === 0) {
|
|
setShowIsNotApplicable(true);
|
|
} else {
|
|
setShowIsNotApplicable(false);
|
|
}
|
|
|
|
const gridRows = toGridRows(convertedData);
|
|
setTabStatusInfoMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set(tabKey, statusInfo);
|
|
return next;
|
|
});
|
|
setTabStatsCdMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set(tabKey, statsCd);
|
|
return next;
|
|
});
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set('ST00060001', gridRows);
|
|
return next;
|
|
});
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, gridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
if (tabKey === 'ST00060002') {
|
|
const response = await statisticsInputPublicSewageFacilityApiService.getPublicSewageMainFacility(param);
|
|
if (response.status !== 'success') {
|
|
alert(response.message || '데이터 조회 중 오류가 발생했습니다.');
|
|
return false;
|
|
}
|
|
setSelectedMainFacilitySn(null);
|
|
const statusInfo = response.data.statusInfo ?? null;
|
|
const statsCd = response.data.commonInfo.statsCd || tabKey;
|
|
const list = response.data.mainFacilityList ?? [];
|
|
const leftRows = list.map((item) => ({
|
|
swtrmtFcltNm: item.swtrmtFcltNm,
|
|
fcltPstnCn: item.fcltPstnCn,
|
|
prxyBzentyNmCn: item.prxyBzentyNmCn,
|
|
cnsgnCstVl: item.cnsgnCstVl,
|
|
prxyCtrtCn: item.prxyCtrtCn,
|
|
wholNope: item.wholNope,
|
|
isMainYn: item.isMainYn,
|
|
admdstCd: item.admdstCd,
|
|
fcltSn: item.fcltSn,
|
|
swtrmtFcltCd: item.swtrmtFcltCd,
|
|
sggNm: item.sggNm ?? '',
|
|
admdstNm: item.admdstNm,
|
|
}));
|
|
const leftGridRows = toGridRows(leftRows);
|
|
setTabStatusInfoMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set(tabKey, statusInfo);
|
|
return next;
|
|
});
|
|
setTabStatsCdMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set(tabKey, statsCd);
|
|
return next;
|
|
});
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set('MainFacility', leftGridRows);
|
|
next.set('MainFacilityTarget', []);
|
|
return next;
|
|
});
|
|
commitToolbarSnapshotForLoadedTab(tabKey, statusInfo, leftGridRows.length > 0, searchContext);
|
|
return true;
|
|
}
|
|
|
|
return true;
|
|
} catch {
|
|
alert('데이터 조회 중 오류가 발생했습니다.');
|
|
return false;
|
|
}
|
|
};
|
|
|
|
const runMainFacilityMappingSave = async (
|
|
draft: MainFacilityMappingSaveDraft,
|
|
dialogInput: MainFacilityMappingSaveDialogValues | null,
|
|
): Promise<boolean> => {
|
|
if (!searchParamRef.current || !lastSearchedValues) {
|
|
return false;
|
|
}
|
|
try {
|
|
showGlobalProgress({ label: '저장 진행 중...', progress: 0 });
|
|
const userInfo = await getUserInfo();
|
|
const base = {
|
|
statsYr: draft.statsYr,
|
|
sewerBzmnCd: draft.sewerBzmnCd,
|
|
admdstCd: draft.admdstCd,
|
|
admdstNm: draft.admdstNm,
|
|
mainFcltSn: draft.mainFcltSn,
|
|
mainFcltNm: draft.mainFcltNm,
|
|
userId: userInfo.userUnqId,
|
|
saveList: draft.saveList,
|
|
deleteList: draft.deleteList,
|
|
};
|
|
const param: PublicSewageMainFacilityMappingSaveRequest = dialogInput
|
|
? {
|
|
...base,
|
|
prxyBzentyNmCn: dialogInput.prxyBzentyNmCn,
|
|
cnsgnCstVl: dialogInput.cnsgnCstVl,
|
|
wholNope: dialogInput.wholNope,
|
|
prxyCtrtCn: dialogInput.prxyCtrtCn,
|
|
}
|
|
: { ...base };
|
|
const response =
|
|
await statisticsInputPublicSewageFacilityApiService.saveMainFacilityMapping(param);
|
|
if (response.status === 'success') {
|
|
setGlobalProgress(50);
|
|
await loadPublicSewageFacilityActiveTabData(
|
|
'ST00060002',
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
setGlobalProgress(100);
|
|
alert('저장되었습니다.');
|
|
return true;
|
|
}
|
|
alert(response.message || '데이터 저장 중 오류가 발생했습니다.');
|
|
return false;
|
|
} catch {
|
|
alert('데이터 저장 중 오류가 발생했습니다.');
|
|
return false;
|
|
} finally {
|
|
hideGlobalProgress();
|
|
}
|
|
};
|
|
|
|
const handleMainFacilityMappingSaveConfirm = async (input: MainFacilityMappingSaveDialogValues) => {
|
|
const draft = mainFacilityMappingSaveDraftRef.current;
|
|
if (!draft || !searchParamRef.current || !lastSearchedValues) {
|
|
setMainFacilityMappingSaveDialogOpen(false);
|
|
mainFacilityMappingSaveDraftRef.current = null;
|
|
return;
|
|
}
|
|
const ok = await runMainFacilityMappingSave(draft, input);
|
|
if (ok) {
|
|
setMainFacilityMappingSaveDialogOpen(false);
|
|
mainFacilityMappingSaveDraftRef.current = null;
|
|
}
|
|
};
|
|
|
|
const handleSearch = async (values: SearchFormValues) => {
|
|
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 : [];
|
|
setPeriodCheckList(periods);
|
|
const periodOk = isInputPeriodCurrent(periods);
|
|
periodEnterableRef.current = periodOk;
|
|
setInputPeriodEnterable(periodOk);
|
|
|
|
const yearChangedFromLastSearch =
|
|
lastSearchedValues != null &&
|
|
(lastSearchedValues.year ?? '') !== (values.year ?? '');
|
|
|
|
// 조회 시 이전 선택 로우 강조 초기화
|
|
setSelectedMainFacilitySn(null);
|
|
|
|
if (yearChangedFromLastSearch) {
|
|
setRowDataMap(new Map());
|
|
setTabStatusInfoMap(new Map());
|
|
setTabStatsCdMap(new Map());
|
|
setToolbarSnapshotByTab(new Map());
|
|
activeTabRef.current = firstTabKey;
|
|
setActiveTab(firstTabKey);
|
|
}
|
|
|
|
setLastSearchedValues(values);
|
|
searchDoneRef.current = true;
|
|
setHasSearched(true);
|
|
|
|
setIsLoading(true);
|
|
const param = buildPublicSewageFacilityParams(values);
|
|
searchParamRef.current = param;
|
|
const tabKeyToLoad = yearChangedFromLastSearch ? firstTabKey : activeTabRef.current;
|
|
await loadPublicSewageFacilityActiveTabData(tabKeyToLoad, param, values);
|
|
} catch {
|
|
alert('데이터 조회 중 오류가 발생했습니다.');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleActiveTabChange = async (tabKey: string) => {
|
|
activeTabRef.current = tabKey;
|
|
setActiveTab(tabKey);
|
|
|
|
if (!hasSearched || tabRowDataExists(tabKey) || !searchParamRef.current) return;
|
|
try {
|
|
setIsLoading(true);
|
|
await loadPublicSewageFacilityActiveTabData(tabKey, searchParamRef.current, lastSearchedValues);
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const handleReset = () => {
|
|
setIsLoading(false);
|
|
setHasSearched(false);
|
|
setIsNotApplicable(false);
|
|
setShowIsNotApplicable(false);
|
|
|
|
setRowDataMap(new Map());
|
|
setTabStatusInfoMap(new Map());
|
|
setTabStatsCdMap(new Map());
|
|
setToolbarSnapshotByTab(new Map());
|
|
|
|
setInputPeriodEnterable(true);
|
|
periodEnterableRef.current = true;
|
|
setPeriodCheckList([]);
|
|
|
|
searchParamRef.current = null;
|
|
searchDoneRef.current = false;
|
|
|
|
activeTabRef.current = firstTabKey;
|
|
setActiveTab(firstTabKey);
|
|
setLastSearchedValues(null);
|
|
setSelectedMainFacilitySn(null);
|
|
};
|
|
|
|
const cnacelSubmitFunc = async () => {
|
|
try {
|
|
if (await confirm('제출된 내용을 취소하시겠습니까?')) {
|
|
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
|
|
if (verificationBlocked) {
|
|
alert(verificationBlocked);
|
|
return;
|
|
}
|
|
|
|
const userInfo = await getUserInfo();
|
|
const statsCdForCancel = tabStatsCdMap.get(activeTab) ?? activeTab;
|
|
const requestData: cancelSubmitRequest = {
|
|
sewerBzmnCd: lastSearchedValues?.bsnmCd ?? '',
|
|
ctpvNm: lastSearchedValues?.sido ?? '',
|
|
sggNm: lastSearchedValues?.gugun === 'ALL' ? '' : lastSearchedValues?.gugun ?? '',
|
|
statsYr: lastSearchedValues?.year ?? '',
|
|
mdfrId: userInfo.userUnqId,
|
|
statsCd: statsCdForCancel,
|
|
};
|
|
|
|
const response = await statisticsApi.cancelSubmit(requestData);
|
|
|
|
if (response.status === 'success') {
|
|
if (searchParamRef.current) {
|
|
await loadPublicSewageFacilityActiveTabData(
|
|
activeTab,
|
|
searchParamRef.current,
|
|
lastSearchedValues,
|
|
);
|
|
}
|
|
alert('제출 취소되었습니다.');
|
|
} else {
|
|
alert(response.message ?? '제출 취소 중 오류가 발생했습니다.');
|
|
}
|
|
}
|
|
} catch {
|
|
alert('제출 취소 중 오류가 발생했습니다.');
|
|
}
|
|
};
|
|
|
|
const getGridColumnInfo = (
|
|
tab: ColumnInfoList,
|
|
guideTabKey?: string,
|
|
): ColumnInfo => ({
|
|
columns: (tab.columns ?? []).map((col) => {
|
|
const guide = columnGuidesByTab[guideTabKey ?? tab.tabKey]?.[col.fieldName]?.trim();
|
|
return {
|
|
...col,
|
|
tooltip: guide && guide.length > 0 ? guide : undefined,
|
|
};
|
|
}),
|
|
columnLayout: tab.columnLayout ?? [],
|
|
});
|
|
|
|
const handleMainFacilityRowClick = async (rowData: Record<string, string | number>) => {
|
|
if (!searchParamRef.current) {
|
|
alert('먼저 조회를 진행해주세요.');
|
|
return;
|
|
}
|
|
const fcltSn = String(rowData.fcltSn ?? '');
|
|
if (!fcltSn) {
|
|
alert('시설 일련번호가 없습니다.');
|
|
return;
|
|
}
|
|
setSelectedMainFacilitySn(fcltSn);
|
|
|
|
const param: PublicSewageMappingTargetsRequestParams = {
|
|
sewerBzmnCd: searchParamRef.current.sewerBzmnCd ?? '',
|
|
ctpvNm: searchParamRef.current.ctpvNm ?? '',
|
|
sggNm: searchParamRef.current.sggNm ?? '',
|
|
statsYr: searchParamRef.current.statsYr ?? '',
|
|
fcltSn,
|
|
};
|
|
|
|
try {
|
|
setIsLoading(true);
|
|
const response = await statisticsInputPublicSewageFacilityApiService.getMappingTargets(param);
|
|
if (response.status !== 'success') {
|
|
alert(response.message || '매핑 대상 조회 중 오류가 발생했습니다.');
|
|
return;
|
|
}
|
|
const rawList = response.data ?? [];
|
|
if (rawList.length === 0) {
|
|
alert('해당 시설은 중심처리시설의 위탁시설로 연결되어있습니다.');
|
|
}
|
|
const mappedTargetRows = rawList.map((item) => ({
|
|
...item,
|
|
__checked: item.mappedYn === 'Y' ? 'Y' : '',
|
|
}));
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
next.set('MainFacilityTarget', toGridRows(mappedTargetRows));
|
|
return next;
|
|
});
|
|
} catch {
|
|
alert('매핑 대상 조회 중 오류가 발생했습니다.');
|
|
} finally {
|
|
setIsLoading(false);
|
|
}
|
|
};
|
|
|
|
const leftMainFacilityCellStyleCallback = ({ row }: CellStyleCallbackParams) => {
|
|
if (!selectedMainFacilitySn) return;
|
|
return String(row.fcltSn ?? '') === selectedMainFacilitySn ? 'rg-cell-selected-row' : undefined;
|
|
};
|
|
|
|
const searchContextForToolbar = lastSearchedValues ?? searchValues;
|
|
const gugunOkOrNotDoList = buildGugunOkForToolbar(searchContextForToolbar);
|
|
const activeTabStatus = tabStatusInfoMap.get(activeTab) ?? null;
|
|
const activeTabToolbar = computeTabToolbarSnapshot(
|
|
activeTabStatus,
|
|
tabRowDataExists(activeTab),
|
|
hasSearched,
|
|
searchContextForToolbar,
|
|
inputPeriodEnterable,
|
|
isAdminInfo,
|
|
);
|
|
const {
|
|
showSaveInToolbar: baseShowSaveInToolbar,
|
|
showEnterableToolbarButtons: baseShowEnterableToolbarButtons,
|
|
showActionToolbarCard: baseShowActionToolbarCard,
|
|
} = activeTabToolbar;
|
|
const isMainFacilityTab = activeTab === 'ST00060002';
|
|
const showMainFacilitySaveInToolbar =
|
|
isMainFacilityTab &&
|
|
tabRowDataExists('ST00060002') &&
|
|
gugunOkOrNotDoList &&
|
|
(isAdminInfo || inputPeriodEnterable);
|
|
const showSaveInToolbar =
|
|
toolbarGroupAllowed && (baseShowSaveInToolbar || showMainFacilitySaveInToolbar);
|
|
const showEnterableToolbarButtons =
|
|
baseShowEnterableToolbarButtons && toolbarGroupAllowed;
|
|
const showActionToolbarCard =
|
|
toolbarGroupAllowed &&
|
|
(baseShowActionToolbarCard || showMainFacilitySaveInToolbar);
|
|
|
|
const openVerificationHistoryDialog = () => {
|
|
const ctx = lastSearchedValues ?? searchValues;
|
|
const activeTabStatsCd = tabStatsCdMap.get(activeTab) ?? activeTab;
|
|
if (!ctx?.year || !ctx?.sido || !ctx?.bsnmCd || !activeTabStatsCd) {
|
|
alert('먼저 조회를 진행해주세요.');
|
|
return;
|
|
}
|
|
setVerificationHistoryOpen(true);
|
|
};
|
|
|
|
const verificationQueryContext =
|
|
(() => {
|
|
const ctx = lastSearchedValues ?? searchValues;
|
|
const statsCd = tabStatsCdMap.get(activeTab) ?? activeTab;
|
|
if (!ctx?.year || !ctx?.sido || !ctx?.bsnmCd || !statsCd) return null;
|
|
return {
|
|
sewerBzmnCd: ctx.bsnmCd,
|
|
ctpvNm: ctx.sido,
|
|
sggNm: ctx.gugun === 'ALL' ? '' : (ctx.gugun ?? ''),
|
|
statsYr: ctx.year,
|
|
statsCd,
|
|
};
|
|
})();
|
|
|
|
return (
|
|
<>
|
|
<div className="relative">
|
|
<SearchForm
|
|
fctName={true}
|
|
onSubmit={handleSearch}
|
|
onReset={handleReset}
|
|
onValuesChange={setSearchValues}
|
|
/>
|
|
{showActionToolbarCard && (
|
|
<div className="card !py-0">
|
|
<div className="flex justify-end items-center gap-[0.6rem] mx-[0.6rem]">
|
|
{!isMainFacilityTab && (
|
|
<VerificationResultButton
|
|
VerificationResultButtonFunc={openVerificationHistoryDialog}
|
|
/>
|
|
)}
|
|
{showEnterableToolbarButtons && !isMainFacilityTab && (
|
|
<>
|
|
{showIsNotApplicable && <NotApplicableCheckButton isCheck={isNotApplicable} setIsCheck={setIsNotApplicable} />}
|
|
<UpdateOperateDataButton updateOperateDataButtonFunc={updateOperateDataButtonFunc} />
|
|
<SubmitButton submitFunc={submitFunc} />
|
|
</>
|
|
)}
|
|
{!isMainFacilityTab && activeTabStatus?.laeSbmsnSttsCd === '2' && (
|
|
<CancelSubmitButton cnacelSubmitFunc={cnacelSubmitFunc} />
|
|
)}
|
|
{showSaveInToolbar && <SaveButton saveFunc={saveFunc} />}
|
|
</div>
|
|
</div>
|
|
)}
|
|
{isLoading && !globalProgressVisible && (
|
|
<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>
|
|
)}
|
|
<Tabs value={activeTab} onValueChange={(v) => void handleActiveTabChange(v)}>
|
|
<TabsList>
|
|
{PublicSewageFactInpColumnList.map((tab) => (
|
|
<TabsTrigger key={tab.tabKey} value={tab.tabKey}>
|
|
{tab.tabLabel || tab.tabKey}
|
|
</TabsTrigger>
|
|
))}
|
|
</TabsList>
|
|
|
|
{PublicSewageFactInpColumnList.map((tab) => {
|
|
if (tab.isSplitGrid && tab.left && tab.right) {
|
|
const leftKey = tab.left.tabKey ?? `${tab.tabKey}_left`;
|
|
const rightKey = tab.right.tabKey ?? `${tab.tabKey}_right`;
|
|
return (
|
|
<TabsContent key={tab.tabKey} value={tab.tabKey}>
|
|
<SplitDataGrid
|
|
leftColumnInfo={getGridColumnInfo(tab.left, tab.tabKey)}
|
|
rightColumnInfo={getGridColumnInfo(tab.right, tab.tabKey)}
|
|
leftFixedColumns={tab.left.fixedColumns}
|
|
rightFixedColumns={tab.right.fixedColumns}
|
|
showHeaderCheckbox={true}
|
|
enableSort={false}
|
|
leftRowData={rowDataMap.get(leftKey) ?? []}
|
|
rightRowData={rowDataMap.get(rightKey) ?? []}
|
|
leftOnRowClick={
|
|
tab.tabKey === 'ST00060002'
|
|
? (row) => {
|
|
void handleMainFacilityRowClick(row);
|
|
}
|
|
: undefined
|
|
}
|
|
leftCellStyleCallback={
|
|
tab.tabKey === 'ST00060002'
|
|
? leftMainFacilityCellStyleCallback
|
|
: undefined
|
|
}
|
|
rightOnItemChecked={
|
|
tab.tabKey === 'ST00060002'
|
|
? (itemIndex, checked) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const rows = [...(next.get('MainFacilityTarget') ?? [])];
|
|
if (!rows[itemIndex]) return prev;
|
|
rows[itemIndex] = {
|
|
...rows[itemIndex],
|
|
__checked: checked ? 'Y' : '',
|
|
};
|
|
next.set('MainFacilityTarget', rows);
|
|
return next;
|
|
});
|
|
}
|
|
: undefined
|
|
}
|
|
rightOnItemAllChecked={
|
|
tab.tabKey === 'ST00060002'
|
|
? (checked) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const rows = [...(next.get('MainFacilityTarget') ?? [])].map((r) => ({
|
|
...r,
|
|
__checked: checked ? 'Y' : '',
|
|
}));
|
|
next.set('MainFacilityTarget', rows);
|
|
return next;
|
|
});
|
|
}
|
|
: undefined
|
|
}
|
|
setLeftRowData={(updater) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const cur = next.get(leftKey) ?? [];
|
|
const n =
|
|
typeof updater === 'function'
|
|
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
|
|
: updater;
|
|
next.set(leftKey, n);
|
|
return next;
|
|
});
|
|
}}
|
|
setRightRowData={(updater) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const cur = next.get(rightKey) ?? [];
|
|
const n =
|
|
typeof updater === 'function'
|
|
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
|
|
: updater;
|
|
next.set(rightKey, n);
|
|
return next;
|
|
});
|
|
}}
|
|
/>
|
|
</TabsContent>
|
|
);
|
|
}
|
|
|
|
const gridColumnInfo = getGridColumnInfo(tab);
|
|
const tabStatus = tabStatusInfoMap.get(tab.tabKey) ?? null;
|
|
const tabEnterableForGrid = computeTabEnterable(
|
|
tabStatus,
|
|
inputPeriodEnterable,
|
|
);
|
|
const excelToolbarEnabledForTab =
|
|
tabRowDataExists(tab.tabKey) &&
|
|
tabEnterableForGrid &&
|
|
gugunOkOrNotDoList;
|
|
|
|
return (
|
|
<TabsContent key={tab.tabKey} value={tab.tabKey}>
|
|
<DataGrid
|
|
key={(tabEnterableForGrid || isAdminInfo) ? 'enterable' : 'readonly'}
|
|
columnInfo={gridColumnInfo}
|
|
rowStartNum={tab.rowStartNum}
|
|
excelExportFileSuffix={tab.tabLabel || tab.tabKey}
|
|
fixedColumns={tab.fixedColumns}
|
|
statusInfo={tabStatus}
|
|
rowData={rowDataMap.get(tab.tabKey) ?? []}
|
|
setRowData={(updater) => {
|
|
setRowDataMap((prev) => {
|
|
const next = new Map(prev);
|
|
const cur = next.get(tab.tabKey) ?? [];
|
|
const n =
|
|
typeof updater === 'function'
|
|
? (updater as (p: Record<string, string | number>[]) => Record<string, string | number>[])(cur)
|
|
: updater;
|
|
next.set(tab.tabKey, n);
|
|
return next;
|
|
});
|
|
}}
|
|
getGridDataRef={
|
|
tab.tabKey === 'ST00060001' ? st60001GridGetRowsRef : undefined
|
|
}
|
|
isExcelImport={excelToolbarEnabledForTab}
|
|
isExcelExport
|
|
showHeaderCheckbox={false}
|
|
enableSort={false}
|
|
cellStyleCallback={({ row, fieldName }) => {
|
|
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";
|
|
}
|
|
}}
|
|
cellTooltipCallback={({ row, fieldName }) => {
|
|
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" ? "IMR검증 - " : (e.vrfcCd === "NV" ? "일반검증 - " : "HB검증 - ");
|
|
const comp = e.compVlCn ?? "";
|
|
const now = e.nowVlCn ?? "";
|
|
return `${prefix}${e.rsnExpln}
|
|
(검증 기준값: ${comp} / 현재 입력값: ${now})`;
|
|
})
|
|
.filter(Boolean)
|
|
.join("\n");
|
|
}
|
|
}}
|
|
/>
|
|
</TabsContent>
|
|
);
|
|
})}
|
|
</Tabs>
|
|
</div>
|
|
<VerificationResultHistoryDialog
|
|
open={verificationHistoryOpen}
|
|
onOpenChange={setVerificationHistoryOpen}
|
|
queryContext={verificationQueryContext}
|
|
/>
|
|
<SubmitDailog
|
|
open={showDailog}
|
|
onOpenChange={setShowDailog}
|
|
statusInfo={activeTabStatus}
|
|
onConfirm={executeSubmit}
|
|
submitMode="normal"
|
|
isLoading={isLoading}
|
|
/>
|
|
<VerificationResultDialog
|
|
open={verificationResultDialogOpen}
|
|
onOpenChange={setVerificationResultDialogOpen}
|
|
queryContext={verificationQueryContext}
|
|
onExceptionSubmitted={async () => {
|
|
const ctx = lastSearchedValues ?? searchValues;
|
|
if (!ctx || !searchParamRef.current) return;
|
|
await loadPublicSewageFacilityActiveTabData(activeTab, searchParamRef.current, ctx);
|
|
}}
|
|
/>
|
|
<MainFacilityMappingSaveDialog
|
|
key={`main-facility-mapping-save-${mainFacilityMappingSaveDialogKey}`}
|
|
open={mainFacilityMappingSaveDialogOpen}
|
|
onOpenChange={(open) => {
|
|
setMainFacilityMappingSaveDialogOpen(open);
|
|
if (!open) {
|
|
mainFacilityMappingSaveDraftRef.current = null;
|
|
}
|
|
}}
|
|
initialPrxyBzentyNmCn={mainFacilityMappingSaveDraftRef.current?.initialPrxyBzentyNmCn ?? ''}
|
|
initialCnsgnCstVl={mainFacilityMappingSaveDraftRef.current?.initialCnsgnCstVl ?? 0}
|
|
initialWholNope={mainFacilityMappingSaveDraftRef.current?.initialWholNope ?? 0}
|
|
initialPrxyCtrtCn={mainFacilityMappingSaveDraftRef.current?.initialPrxyCtrtCn ?? ''}
|
|
onConfirm={handleMainFacilityMappingSaveConfirm}
|
|
/>
|
|
</>
|
|
);
|
|
};
|
|
|
|
export default PublicSewageFacilityInp; |