Merge remote-tracking branch 'origin/iipbs/st/dev' into feature/sein

This commit is contained in:
yangsein
2026-06-15 14:53:01 +09:00
346 changed files with 39428 additions and 8615 deletions
@@ -1,11 +1,20 @@
"use client";
import { useCallback, useState } from "react";
import { useQueries } from "@tanstack/react-query";
import { useCallback, useEffect, useState } from "react";
import {
type InfiniteData,
keepPreviousData,
useInfiniteQuery,
useQueryClient,
} from "@tanstack/react-query";
import { useTabStore as useGridTabStore } from "@rsone/components";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import type { VerificationResultReportItem } from "@/entities/statistics/model/statistics-interface";
import { verificationInputReportApi } from "@/entities/statistics/api/verification-input-report-service";
import type {
VerificationInputReportItem,
VerificationInputReportResponse,
VerificationInputReportTypeCountingInfo,
} from "@/entities/statistics/model/verification-input-report-interface";
import { useAlertStore, useMenuStore } from "@/shared/lib";
import {
findMenuItemByUrlPath,
@@ -23,7 +32,9 @@ import {
TabsContent,
TabsList,
TabsTrigger,
Label,
} from "@common/components";
import { CodeSelectWithAll } from "@/entities/code";
type VerificationReportTabKey = "NV" | "IMR" | "HB";
@@ -45,6 +56,77 @@ const TYPE_CODE_NAME_MAP: Record<string, string> = {
HB: "HB",
};
const PAGE_SIZE = 100;
const SCROLL_LOAD_THRESHOLD_PX = 120;
function getNextVerificationInputReportPage(
lastPage: VerificationInputReportResponse,
): number | undefined {
const pageInfo = lastPage?.data?.pageInfo;
if (!pageInfo) return undefined;
const { currentPage, totalPages } = pageInfo;
if (currentPage + 1 <= totalPages) return currentPage + 1;
return undefined;
}
function flattenVerificationInputReportResults(
data: InfiniteData<VerificationInputReportResponse> | undefined,
): VerificationInputReportItem[] {
return (
data?.pages.flatMap((page) => page?.data?.verifyResultList ?? []) ?? []
);
}
function getVerifyTypeCountingInfo(
data: InfiniteData<VerificationInputReportResponse> | undefined,
): VerificationInputReportTypeCountingInfo | null {
return data?.pages[0]?.data?.verifyTypeCountingInfo ?? null;
}
function formatReportItemTitle(item: VerificationInputReportItem): string {
return item.statsNm?.trim() || item.vrfcTrgtNm?.trim() || item.statsCd;
}
function formatReportItemRegion(item: VerificationInputReportItem): string {
const parts = [item.ctpvNm, item.sggNm].filter(
(v): v is string => Boolean(v?.trim()),
);
return parts.length > 0 ? parts.join(" ") : "-";
}
function useVerificationReportList(
statsYr: string,
statsCdQueryKey: string,
vrfcMthdCd: VerificationReportTabKey,
statsCd: string,
enabled: boolean,
) {
return useInfiniteQuery({
queryKey: [
"verificationInputReport",
statsYr,
vrfcMthdCd,
statsCdQueryKey,
],
initialPageParam: 1,
queryFn: ({ pageParam }) =>
verificationInputReportApi.getVerificationInputReport({
statsYr,
vrfcMthdCd,
page: pageParam,
size: PAGE_SIZE,
...(!(statsCd === "" || statsCd === "ALL") && { statsCd }),
}),
getNextPageParam: getNextVerificationInputReportPage,
placeholderData: keepPreviousData,
refetchOnWindowFocus: false,
// 탭 전환만으로는 재조회하지 않음(명시적 새로고침/조건 변경 시만 조회)
staleTime: Infinity,
refetchOnMount: false,
enabled,
});
}
type VerificationSelectionReportProps = {
onClose?: () => void;
};
@@ -52,6 +134,7 @@ type VerificationSelectionReportProps = {
const VerificationSelectionReport = ({
onClose,
}: VerificationSelectionReportProps) => {
const queryClient = useQueryClient();
const menuList = useTabStore((s) => s.menuList);
const addTab = useTabStore((s) => s.addTab);
const setCurrentMenuInfo = useMenuStore((s) => s.setCurrentMenuInfo);
@@ -61,82 +144,100 @@ const VerificationSelectionReport = ({
);
const alert = useAlertStore((s) => s.setMessage);
const [activeTab, setActiveTab] = useState<VerificationReportTabKey>("NV");
const [statsCd, setStatsCd] = useState<string>("ALL");
const [isFullReloading, setIsFullReloading] = useState(false);
const statsYr = String(dayjs().year() - 1);
const statsCdQueryKey =
statsCd === "" || statsCd === "ALL" ? "" : statsCd;
const baseRequest = {
const handleStatsCdChange = useCallback(
(nextStatsCd: string) => {
setStatsCd(nextStatsCd);
setActiveTab("NV");
setIsFullReloading(true);
// 통계항목 변경 시 모든 탭 캐시 제거 후 NV부터 다시 조회
void queryClient.removeQueries({
queryKey: ["verificationInputReport", statsYr],
});
},
[queryClient, statsYr],
);
const nvQuery = useVerificationReportList(
statsYr,
pbcpAprvYn: "N" as const,
page: 1,
size: 10000,
prcsYnList: "0",
statsCdQueryKey,
"NV",
statsCd,
activeTab === "NV",
);
const imrQuery = useVerificationReportList(
statsYr,
statsCdQueryKey,
"IMR",
statsCd,
activeTab === "IMR",
);
const hbQuery = useVerificationReportList(
statsYr,
statsCdQueryKey,
"HB",
statsCd,
activeTab === "HB",
);
const queryByTab = {
NV: nvQuery,
IMR: imrQuery,
HB: hbQuery,
} as const;
const activeQuery = queryByTab[activeTab];
const isRefreshing = activeQuery.isFetching && !activeQuery.isPending;
const error = activeQuery.error;
/** 통계항목 변경·최초 진입: 탭 영역 숨기고 카드 전체 로딩만 표시 */
const hideTabsSection =
isFullReloading ||
(activeTab === "NV" && !nvQuery.data && (nvQuery.isPending || nvQuery.isFetching));
useEffect(() => {
if (!isFullReloading) return;
if (nvQuery.isFetching) return;
if (nvQuery.isSuccess || nvQuery.isError) {
setIsFullReloading(false);
}
}, [isFullReloading, nvQuery.isFetching, nvQuery.isSuccess, nvQuery.isError]);
const handleRefresh = useCallback(() => {
setStatsCd("ALL");
setActiveTab("NV");
setIsFullReloading(true);
void queryClient.removeQueries({
queryKey: ["verificationInputReport", statsYr],
});
}, [queryClient, statsYr]);
const listsByTab: Record<VerificationReportTabKey, VerificationInputReportItem[]> = {
NV: flattenVerificationInputReportResults(nvQuery.data),
IMR: flattenVerificationInputReportResults(imrQuery.data),
HB: flattenVerificationInputReportResults(hbQuery.data),
};
const [nvQuery, imrQuery, hbQuery] = useQueries({
queries: [
{
queryKey: [
"verificationResultList",
statsYr,
"NV",
baseRequest.pbcpAprvYn,
baseRequest.page,
baseRequest.size,
baseRequest.prcsYnList,
],
queryFn: () =>
statisticsApi.getVerificationResultList({
...baseRequest,
vrfcMthdCd: "NV",
}),
},
{
queryKey: [
"verificationResultList",
statsYr,
"IMR",
baseRequest.pbcpAprvYn,
baseRequest.page,
baseRequest.size,
baseRequest.prcsYnList,
],
queryFn: () =>
statisticsApi.getVerificationResultList({
...baseRequest,
vrfcMthdCd: "IMR",
}),
},
{
queryKey: [
"verificationResultList",
statsYr,
"HB",
baseRequest.pbcpAprvYn,
baseRequest.page,
baseRequest.size,
baseRequest.prcsYnList,
],
queryFn: () =>
statisticsApi.getVerificationResultList({
...baseRequest,
vrfcMthdCd: "HB",
}),
},
],
});
const typeCountingInfo =
getVerifyTypeCountingInfo(nvQuery.data) ??
getVerifyTypeCountingInfo(imrQuery.data) ??
getVerifyTypeCountingInfo(hbQuery.data);
const isLoading =
nvQuery.isLoading || imrQuery.isLoading || hbQuery.isLoading;
const error = nvQuery.error ?? imrQuery.error ?? hbQuery.error;
const listsByTab: Record<VerificationReportTabKey, VerificationResultReportItem[]> = {
NV: nvQuery.data?.data?.verifyResultList ?? [],
IMR: imrQuery.data?.data?.verifyResultList ?? [],
HB: hbQuery.data?.data?.verifyResultList ?? [],
const totalCountByTab: Record<VerificationReportTabKey, number> = {
NV: typeCountingInfo?.nvCount ?? listsByTab.NV.length,
IMR: typeCountingInfo?.imrCount ?? listsByTab.IMR.length,
HB: typeCountingInfo?.hbCount ?? listsByTab.HB.length,
};
const openInputFromStatsCd = useCallback(
(item: VerificationResultReportItem) => {
(item: VerificationInputReportItem) => {
const nav = resolveInputPageNavigationFromStatsCd(item.statsCd);
if (!nav) {
alert(
@@ -182,12 +283,61 @@ const VerificationSelectionReport = ({
],
);
const handleListScroll = useCallback(
(
e: React.UIEvent<HTMLDivElement>,
hasNextPage: boolean,
isFetchingNextPage: boolean,
fetchNextPage: () => void,
) => {
const el = e.currentTarget;
const remaining =
el.scrollHeight - el.scrollTop - el.clientHeight;
if (remaining > SCROLL_LOAD_THRESHOLD_PX) return;
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
},
[],
);
const isTabContentLoading = (tab: VerificationReportTabKey) => {
const query = queryByTab[tab];
return (
activeTab === tab &&
!hideTabsSection &&
(query.isPending ||
(query.isFetching && !query.isFetchingNextPage) ||
(!query.data && !query.error))
);
};
const renderResultList = (
typeCode: VerificationReportTabKey,
items: VerificationResultReportItem[],
items: VerificationInputReportItem[],
isTabLoading: boolean,
hasNextPage: boolean,
isFetchingNextPage: boolean,
fetchNextPage: () => void,
) => (
<div className="min-h-0 flex-1 overflow-y-auto p-2">
{items.length === 0 ? (
<div
className="min-h-0 flex-1 overflow-y-auto p-2"
onScroll={(e) =>
handleListScroll(
e,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
)
}
>
{isTabLoading ? (
<div className="flex h-full min-h-[8rem] items-center justify-center">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
) : items.length === 0 && !isFetchingNextPage ? (
<div className="flex h-full min-h-[8rem] items-center justify-center text-lg text-muted-foreground">
항목이 없습니다.
</div>
@@ -209,7 +359,7 @@ const VerificationSelectionReport = ({
>
<div className="mb-2 flex items-center justify-between">
<span className="font-medium">
{item.statsNm}
{formatReportItemTitle(item)}
</span>
<Badge
color={
@@ -226,7 +376,7 @@ const VerificationSelectionReport = ({
{item.rsnExpln}
</p>
<div className="flex justify-between text-lg text-muted-foreground">
<span>{item.admdstNm}</span>
<span>{formatReportItemRegion(item)}</span>
<span>
현재: {item.nowVlCn ?? "-"} / 비교:{" "}
{item.compVlCn ?? "-"}
@@ -234,6 +384,13 @@ const VerificationSelectionReport = ({
</div>
</div>
))}
{isFetchingNextPage && (
<div className="flex justify-center py-3">
<div className="relative size-[3rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
</div>
)}
</div>
@@ -241,9 +398,26 @@ const VerificationSelectionReport = ({
return (
<div className="w-1/5 bg-container p-4 !pb-2 flex border-r border-border">
<div className="card card-border flex-1 bg-background !px-0">
<div className="card card-border flex-1 bg-background !px-0 max-h-[1000px] flex flex-col">
<div className="border-b border-border flex justify-between">
<h2 className="text-[2.4rem] font-semibold text-title p-4 ">이상치 선별 보고서</h2>
<div className="flex justify-center items-center text-[2.4rem] ">
<h2 className="font-semibold text-title p-4 pr-1">이상치 선별 보고서</h2>
<span
role="button"
tabIndex={0}
aria-label="새로고침"
className={`text-gray-400 cursor-pointer hover:text-[#2094fa] ${isRefreshing ? "pointer-events-none opacity-50" : ""}`}
onClick={handleRefresh}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
handleRefresh();
}
}}
>
<i className="diveicon di-arrow-reflash" />
</span>
</div>
<span
role="button"
tabIndex={0}
@@ -260,37 +434,47 @@ const VerificationSelectionReport = ({
<i className="ri-close-line" />
</span>
</div>
<div className="card-body max-h-[calc(100%-3.25rem)] p-2.5">
{isLoading && (
<div className="flex items-center gap-2 pt-2.5 px-4">
<Label className="text-label shrink-0">통계항목</Label>
<CodeSelectWithAll
upCd="STITEM"
value={statsCd}
onValueChange={handleStatsCdChange}
placeholder="전체"
className="w-full"
/>
</div>
<div className="card-body p-2.5 flex-1 flex flex-col overflow-hidden relative min-h-0">
{hideTabsSection && (
<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>
)}
{error && (
{!hideTabsSection && error && (
<div className="absolute inset-0 z-50 [data-theme='black']:bg-transparent rounded-lg p-10 flex justify-center items-center">
데이터를 불러올 수 없습니다.
</div>
)}
{!isLoading && !error && (
<section className="flex min-h-0 flex-1 flex-col h-[85rem]">
{!hideTabsSection && !error && (
<section className="flex min-h-0 flex-1 flex-col">
<Tabs
value={activeTab}
onValueChange={(value) =>
setActiveTab(value as VerificationReportTabKey)
}
className="flex min-h-0 flex-1 flex-col h-full"
className="flex min-h-0 flex-1 flex-col"
variant="default"
>
<TabsList className="grid w-full grid-cols-3 p-1">
<TabsList className="grid w-full grid-cols-3 p-1 shrink-0">
{VERIFICATION_REPORT_TABS.map((tab) => (
<TabsTrigger
key={tab.value}
value={tab.value}
className="!px-2 !py-2 text-[1.3rem] whitespace-normal"
>
{tab.label} ({listsByTab[tab.value].length})
{tab.label} ({totalCountByTab[tab.value]})
</TabsTrigger>
))}
</TabsList>
@@ -300,12 +484,14 @@ const VerificationSelectionReport = ({
value={tab.value}
className="mt-0 flex min-h-0 flex-1 flex-col p-0 data-[state=inactive]:hidden"
>
{activeTab === tab.value
? renderResultList(
tab.value,
listsByTab[tab.value],
)
: null}
{renderResultList(
tab.value,
listsByTab[tab.value],
isTabContentLoading(tab.value),
queryByTab[tab.value].hasNextPage ?? false,
queryByTab[tab.value].isFetchingNextPage,
queryByTab[tab.value].fetchNextPage,
)}
</TabsContent>
))}
</Tabs>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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);
@@ -165,7 +167,7 @@ const PublicSewageFacilityInp = () => {
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 [_toolbarSnapshotByTab, setToolbarSnapshotByTab] = useState<Map<string, TabToolbarSnapshot>>(() => new Map());
const [inputPeriodEnterable, setInputPeriodEnterable] = useState(true);
const [periodCheckList, setPeriodCheckList] = useState<CheckInputPeriodItem[]>([]);
const [showDailog, setShowDailog] = useState<boolean>(false);
@@ -175,12 +177,25 @@ 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);
/** ST00060001만: RealGrid 편집값이 state에 없을 수 있어 저장/제출 시 그리드에서 직접 읽음 */
const st60001GridGetRowsRef = useRef<(() => Record<string, string | number>[]) | null>(null);
const submitFunc = () => {
void (async () => {
if (activeTab !== 'ST00060001') {
@@ -191,10 +206,11 @@ const PublicSewageFacilityInp = () => {
alert('먼저 조회를 진행해주세요.');
return;
}
const treatAsNoApplicable = getNoApplicableForRequest() || isNotApplicable;
const currentData =
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
if (!currentData || currentData.length === 0) {
alert('제출할 데이터가 없습니다.');
if (!treatAsNoApplicable && (!currentData || currentData.length === 0)) {
alert('해당사항 없음을 체크해주세요.');
return;
}
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
@@ -270,17 +286,20 @@ const PublicSewageFacilityInp = () => {
alert('먼저 조회를 진행해주세요.');
return;
}
const noApplicable = getNoApplicableForRequest();
const treatAsNoApplicable = noApplicable || isNotApplicable;
const currentData =
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
if (!currentData || currentData.length === 0) {
alert('제출할 데이터가 없습니다.');
const submitList = treatAsNoApplicable ? [] : buildFacilitySaveList(currentData);
if (!treatAsNoApplicable && submitList.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 = {
@@ -289,7 +308,7 @@ const PublicSewageFacilityInp = () => {
sggNm: lastSearchedValues.gugun === 'ALL' ? '' : lastSearchedValues.gugun ?? '',
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
userId: userInfo.userUnqId,
noApplicable: getNoApplicableForRequest(),
noApplicable,
laePicNm: submitInfo.laePicNm,
laeKbrdrJbgdNm: submitInfo.laeKbrdrJbgdNm,
laeKbrdrDeptNm: submitInfo.laeKbrdrDeptNm,
@@ -408,6 +427,12 @@ const PublicSewageFacilityInp = () => {
const saveFunc = () => {
void (async () => {
const verificationBlocked = getVerificationPeriodActionBlockedMessage(periodCheckList);
if (verificationBlocked) {
alert(verificationBlocked);
return;
}
if (!lastSearchedValues || !searchParamRef.current) {
alert('먼저 조회를 진행해주세요.');
return;
@@ -419,13 +444,13 @@ const PublicSewageFacilityInp = () => {
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관리자에게 문의하세요')
}
@@ -505,17 +530,19 @@ const PublicSewageFacilityInp = () => {
if (!(await confirm('저장 하시겠습니까?'))) return;
if (activeTab === 'ST00060001') {
const noApplicable = getNoApplicableForRequest();
const treatAsNoApplicable = noApplicable || isNotApplicable;
const currentData =
st60001GridGetRowsRef.current?.() ?? rowDataMap.get('ST00060001') ?? [];
const saveList = treatAsNoApplicable ? [] : buildFacilitySaveList(currentData);
if (!treatAsNoApplicable && saveList.length === 0) {
alert('해당사항 없음을 체크해주세요.');
return;
}
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 ?? '',
@@ -523,7 +550,7 @@ const PublicSewageFacilityInp = () => {
sewerBzmnCd: lastSearchedValues.bsnmCd ?? '',
userId: userInfo.userUnqId,
// superAdmin: isAdminInfo ? 'superAdmin' : '',
noApplicable: getNoApplicableForRequest(),
noApplicable,
saveList,
};
@@ -842,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);
@@ -856,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);
@@ -871,7 +916,7 @@ const PublicSewageFacilityInp = () => {
const handleReset = () => {
setIsLoading(false);
setHasSearched(false);
setIsNotApplicable(false);
setIsNotApplicableByTab(new Map());
setShowIsNotApplicable(false);
setRowDataMap(new Map());
@@ -1062,7 +1107,7 @@ const PublicSewageFacilityInp = () => {
onValuesChange={setSearchValues}
/>
{showActionToolbarCard && (
<div className="card !py-0">
<div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] mx-[0.6rem]">
{!isMainFacilityTab && (
<VerificationResultButton
@@ -1072,8 +1117,8 @@ const PublicSewageFacilityInp = () => {
{showEnterableToolbarButtons && !isMainFacilityTab && (
<>
{showIsNotApplicable && <NotApplicableCheckButton isCheck={isNotApplicable} setIsCheck={setIsNotApplicable} />}
<UpdateOperateDataButton updateOperateDataButtonFunc={updateOperateDataButtonFunc} />
<SubmitButton submitFunc={submitFunc} />
<UpdateOperateDataButton updateOperateDataButtonFunc={updateOperateDataButtonFunc} />
<SubmitButton submitFunc={submitFunc} />
</>
)}
{!isMainFacilityTab && activeTabStatus?.laeSbmsnSttsCd === '2' && (
@@ -1088,7 +1133,7 @@ const PublicSewageFacilityInp = () => {
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
</div>
)}
<Tabs value={activeTab} onValueChange={(v) => void handleActiveTabChange(v)}>
<TabsList>
@@ -1099,171 +1144,176 @@ const PublicSewageFacilityInp = () => {
))}
</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`;
{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}>
<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) => {
<DataGrid
key={tab.tabKey}
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(leftKey) ?? [];
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(leftKey, n);
next.set(tab.tabKey, 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;
});
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>
);
}
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}
onExceptionResetSubmitted={async () => {
const ctx = lastSearchedValues ?? searchValues;
if (!ctx || !searchParamRef.current) return;
await loadPublicSewageFacilityActiveTabData(activeTab, searchParamRef.current, ctx);
}}
/>
<SubmitDailog
open={showDailog}
File diff suppressed because it is too large Load Diff
@@ -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}
@@ -2062,6 +2119,12 @@ const SewagePipeInp = () => {
}
: null
}
onExceptionResetSubmitted={async () => {
const values = lastSearchedValues ?? searchValues;
if (!values?.year || !values?.sido || !values?.bsnmCd) return;
const refreshedParam = buildSewagePipeSearchParam(values);
await loadSewagePipeActiveTabData(activeTab, refreshedParam, values, true, false);
}}
/>
<SubmitDailog
open={showDailog}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,34 +1,539 @@
import { useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import SearchForm from "@/components/module/SearchForm";
import TabDataGrid from "@/components/module/TabDataGrid";
import SubmitButton from "@/components/button/SumitButton";
import SaveButton from "@/components/button/SaveButton";
import SubmitExceptionButton from "@/components/button/SubmitExceptionButton";
import { useConfirm } from "@frontend-opensource/use-react-hooks";
import { useAlertStore } from "@/shared/lib";
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,
SewerageChargeItem,
SewerageFinanceRequestParams,
SewerageFinanceSettleItem,
SewerageFinanceVerificationResult,
SewerageUsageFeeItem,
} 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 { cancelSubmitRequest, 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 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 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 { doList } from "@/components/util/column/input/DoList";
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 { toGridRows } from "@/components/util/grid/gridFunction";
import { useAdminStore } from "@/store/admin-store";
import { SewerageFinanceSettleInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageFinanceSettleInpColumn"
import { SewerageChargeInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageChargeInpColumn"
import { SewerageUsageFeeInpColumn } from "@/components/util/column/input/sewerageFinance/SewerageUsageFeeInpColumn"
import { CauserBurdenInpColumn } from "@/components/util/column/input/sewerageFinance/CauserBurdenInpColumn"
const SewerageFinanceInpTabList = [
SewerageFinanceSettleInpColumn,
SewerageChargeInpColumn,
SewerageUsageFeeInpColumn,
CauserBurdenInpColumn,
] as const;
const firstTabKey = SewerageFinanceSettleInpColumn.tabKey;
const SEWERAGE_FINANCE_COLUMN_GUIDE_TAB_KEYS = Array.from(
new Set(SewerageFinanceInpTabList.map((tab) => tab.tabKey).filter(Boolean)),
);
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,
sewerBzmnCd: values.bsnmCd,
ctpvNm: values.sido,
sggNm: values.gugun === "ALL" ? "" : values.gugun,
...(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;
};
function buildGugunOkForToolbar(values: SearchFormValues | null): boolean {
return doList.includes(values?.bsnmCd || "")
? Boolean(values?.gugun && values.gugun !== "ALL")
: true;
}
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 };
}
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): GridRowWithVerification[] {
return list.map((item) => {
const { verificationResult, ...rest } = item;
const row = toGridRows([{ ctpvNm, ...rest }])[0] as GridRowWithVerification;
if (verificationResult) row.verificationResult = verificationResult;
return row;
});
}
// 하수도 통계 관리 > 09. 하수도재정
const SewerageFinanceInp = () => {
const { setMessage: alert } = useAlertStore((state) => state);
const { confirm } = useConfirm();
const { isAdminInfo } = useAdminStore();
// tab list
const SewerageFinanceInpTabList = [
SewerageFinanceSettleInpColumn,
SewerageChargeInpColumn,
SewerageUsageFeeInpColumn,
CauserBurdenInpColumn
];
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 [toolbarSnapshotByTab, setToolbarSnapshotByTab] = useState<
Map<string, TabToolbarSnapshot>
>(new Map());
const [columnGuidesByTab, setColumnGuidesByTab] = useState<
Record<string, Record<string, string>>
>({});
const [verificationHistoryOpen, setVerificationHistoryOpen] = useState(false);
const [verificationResultDialogOpen, setVerificationResultDialogOpen] = useState(false);
const submitExceptionFunc = () => {
// 예외 제출 로직
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;
useEffect(() => {
let cancelled = false;
void (async () => {
const entries = await Promise.all(
SEWERAGE_FINANCE_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,
) => {
setToolbarSnapshotByTab((prev) => {
const next = new Map(prev);
next.set(
tabKey,
computeTabToolbarSnapshot(
statusInfo,
hasRowData,
searchDoneRef.current,
searchContext,
periodEnterableRef.current,
isAdminInfo,
),
);
return next;
});
};
const lastYearDataFunc = () => {
// 지난연도 데이터 가져오기 로직
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,
);
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));
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,
);
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));
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,
);
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));
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,
);
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));
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());
setToolbarSnapshotByTab(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) => {
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());
setToolbarSnapshotByTab(new Map());
activeTabRef.current = firstTabKey;
setActiveTab(firstTabKey);
}
setIsLoading(true);
searchDoneRef.current = true;
setHasSearched(true);
const searchParam = buildSewerageFinanceSearchParam(values);
searchParamRef.current = searchParam;
await loadActiveTabData(
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 = {
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,
searchParamRef.current,
lastSearchedValues,
false,
false,
);
alert("제출 취소되었습니다.");
} else {
alert(response.message ?? "제출 취소 중 오류가 발생했습니다.");
}
} catch {
alert("제출 취소 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
})();
};
const submitFunc = () => {
@@ -39,26 +544,249 @@ const SewerageFinanceInp = () => {
// 저장 로직
};
const [rowDataMap, setRowDataMap] = useState<Map<string, Record<string, string | number>[]>>(new Map());
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 {
sewerBzmnCd: ctx.bsnmCd,
ctpvNm: ctx.sido,
sggNm: ctx.gugun === "ALL" ? "" : (ctx.gugun ?? ""),
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;
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 activeTabStatus = tabStatusInfoMap.get(activeTab) ?? null;
const activeTabToolbar =
toolbarSnapshotByTab.get(activeTab) ??
computeTabToolbarSnapshot(
activeTabStatus,
tabRowDataExists(rowDataMap, activeTab),
hasSearched,
lastSearchedValues,
inputPeriodEnterable,
isAdminInfo,
);
const { showSaveInToolbar, showEnterableToolbarButtons, showActionToolbarCard } =
activeTabToolbar;
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"
? "IMR검증 - "
: e.vrfcCd === "NV"
? "일반검증 - "
: "HB검증 - ";
return `${prefix}${e.rsnExpln}(검증 기준값: ${e.compVlCn} / 현재 입력값: ${e.nowVlCn})`;
})
.filter(Boolean)
.join("\n");
}
};
return (
<>
<SearchForm />
<div className="card !py-0">
<div className="flex justify-end items-center gap-[0.6rem] m-[0.6rem]">
<SubmitExceptionButton SubmitExceptionFunc={submitExceptionFunc} />
<LastYearDataButton getLastYearDataFunc={lastYearDataFunc} />
<SubmitButton submitFunc={submitFunc} />
<SaveButton saveFunc={saveFunc} />
<div className="relative">
<SearchForm
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}
/>
{showEnterableToolbarButtons && (
<>
<LastYearDataButton
getLastYearDataFunc={() => void lastYearDataFunc()}
/>
<SubmitButton submitFunc={submitFunc} />
</>
)}
{activeTabStatus?.laeSbmsnSttsCd === "2" && (
<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;
const gugunOk = buildGugunOkForToolbar(lastSearchedValues);
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
}
isExcelExport
cellStyleCallback={verificationCellStyle}
cellTooltipCallback={verificationCellTooltip}
getGridDataRef={
activeTab === tabKey ? getGridDataRef : undefined
}
/>
</TabsContent>
);
})}
</Tabs>
</div>
</div>
<TabDataGrid
columnInfo={SewerageFinanceInpTabList}
rowDataMap={rowDataMap}
setRowDataMap={setRowDataMap}
<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,
);
}}
/>
<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;
export default SewerageFinanceInp;
@@ -254,7 +254,6 @@ const SeweragePenetrationRateInp = () => {
...d,
ctpvNm: commonInfo.ctpvNm,
spcCtpnRgnCn: d.spcCtpnRgnCn === '' || d.spcCtpnRgnCn === null ? '해당없음' : d.spcCtpnRgnCn,
swagePplPsplyRt: commonInfo.swagePplPsplyRt,
}));
setRowData(
convertedData.map((d) => {
@@ -289,7 +288,8 @@ const SeweragePenetrationRateInp = () => {
} else {
alert(response.message);
}
} catch {
} catch (error) {
console.log(error);
alert('데이터 조회 중 오류가 발생했습니다.');
setRowData([]);
setStatusInfo(null);
@@ -791,11 +791,13 @@ const SeweragePenetrationRateInp = () => {
</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" />
{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>
</div>}
}
<DataGrid
key={(isEnterable || isAdminInfo) ? 'enterable' : 'readonly'}
columnInfo={columnInfo}
@@ -823,7 +825,7 @@ const SeweragePenetrationRateInp = () => {
if (Array.isArray(errors) && errors.length > 0) {
return errors
.map((e) => {
const prefix = e.vrfcCd === 'IMR' ? 'IMR검증 - ' : (e.vrfcCd === 'NM' ? '일반검증 - ' : 'HB검증 -');
const prefix = e.vrfcCd === 'IMR' ? 'IMR검증 - ' : (e.vrfcCd === 'NV' ? '일반검증 - ' : 'HB검증 -');
return `${prefix}${e.rsnExpln}
(검증 기준값: ${e.compVlCn} / 현재 입력값: ${e.nowVlCn})`;
})
@@ -860,6 +862,11 @@ const SeweragePenetrationRateInp = () => {
}
: null
}
onExceptionResetSubmitted={async () => {
const values = lastSearchedValues ?? searchValues;
if (!values) return;
await handleSearch(values);
}}
/>
<VerificationResultDialog
open={verificationResultDialogOpen}
@@ -196,6 +196,20 @@ const LogHistory = () => {
const handleSearch = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (startDate && endDate) {
const start = dayjs(startDate);
const end = dayjs(endDate);
if (start.isAfter(end, "day")) {
alert("시작일은 종료일보다 늦을 수 없습니다.");
return;
}
if (end.isBefore(start, "day")) {
alert("종료일은 시작일보다 빠를 수 없습니다.");
return;
}
}
await loadLogs(1);
};
@@ -1,6 +1,7 @@
"use client";
import { useEffect } from "react";
import { useEffect, useMemo, useState } from "react";
import { GridFitStyle } from "realgrid";
import {
Button,
@@ -10,9 +11,20 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
LoadingWithAnimation,
} from "@common/components";
import DataGrid from "@/components/module/DataGrid";
import type { ColumnInfo } from "@/components/type/DataGrid.type";
import {
alignLogDetailRowsToColumns,
buildLogHistoryDetailColumnInfo,
emptyLogHistoryDetailColumnInfo,
} from "@/components/util/column/management/LogHistoryDetailColumn";
import { toGridRows } from "@/components/util/grid/gridFunction";
import { statisticsApi } from "@/entities/statistics/api/statistics-service";
import type { StatisticsLogDetailRow } from "@/entities/statistics/model/statistics-interface";
import { useAlertStore } from "@/shared/lib";
export interface LogHistoryDetailDialogProps {
open: boolean;
@@ -25,24 +37,115 @@ export function LogHistoryDetailDialog({
onOpenChange,
row,
}: LogHistoryDetailDialogProps) {
const { setMessage: alert } = useAlertStore((state) => state);
const [isLoading, setIsLoading] = useState(false);
const [rowData, setRowData] = useState<Record<string, string | number>[]>(
[],
);
const [columnInfo, setColumnInfo] = useState<ColumnInfo>(
emptyLogHistoryDetailColumnInfo,
);
useEffect(() => {
if (!open || !row) return;
if (!open) {
setRowData([]);
setColumnInfo(emptyLogHistoryDetailColumnInfo);
setIsLoading(false);
return;
}
if (!row) return;
const sn = row.statsLogSn;
let cancelled = false;
void (async () => {
const response = await statisticsApi.getLogDetail(
sn !== undefined && sn !== null ? String(sn) : "",
);
console.log(response.data);
setIsLoading(true);
setRowData([]);
try {
const response = await statisticsApi.getLogDetail(
sn !== undefined && sn !== null ? String(sn) : "",
);
if (cancelled) return;
if (response.status !== "success") {
alert(
response.message ??
"로그 상세 정보를 불러오는데 실패했습니다.",
);
return;
}
const list = Array.isArray(response.data)
? response.data
: [];
const nextColumnInfo = buildLogHistoryDetailColumnInfo(list);
const nextRows = alignLogDetailRowsToColumns(
toGridRows(list as StatisticsLogDetailRow[]),
nextColumnInfo,
);
setColumnInfo(nextColumnInfo);
setRowData(nextRows);
} catch {
if (!cancelled) {
alert("로그 상세 정보를 불러오는데 실패했습니다.");
}
} finally {
if (!cancelled) setIsLoading(false);
}
})();
}, [open, row]);
return () => {
cancelled = true;
};
}, [open, row, alert]);
const gridRemountKey = useMemo(
() => columnInfo.columns.map((c) => c.fieldName).join("\u0001"),
[columnInfo],
);
const showGrid = !isLoading && rowData.length > 0;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[60rem]" aria-describedby={undefined}>
<DialogContent
className="max-w-[80%]"
aria-describedby={undefined}
>
<DialogHeader>
<DialogTitle />
<DialogTitle>로그 상세 정보</DialogTitle>
</DialogHeader>
<div className="relative min-h-[32rem]">
{isLoading && (
<div className="absolute inset-0 z-10 flex items-center justify-center rounded-lg bg-background/80">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
)}
{showGrid ? (
<DataGrid
key={gridRemountKey}
columnInfo={columnInfo}
rowData={rowData}
setRowData={setRowData}
isExcelImport={false}
isExcelExport={false}
enableSort={false}
gridHeight={55}
fitStyle={GridFitStyle.NONE}
/>
) : (
!isLoading && (
<p className="flex h-full items-center justify-center text-[1.3rem] text-muted-foreground">
표시할 상세 데이터가 없습니다.
</p>
)
)}
</div>
<DialogFooter>
<DialogClose asChild>
<Button size="lg" color="white" type="button">
@@ -213,6 +213,7 @@ function buildRowsFromStatusList(
statKeys: string[],
): Record<string, string | number>[] {
const rowMap = new Map<string, Record<string, string | number>>();
const rowOrder: string[] = [];
for (const item of statusList) {
const { sido, sgg } = splitSidoSggNm(item.sidoSggNm);
@@ -228,6 +229,7 @@ function buildRowsFromStatusList(
row[key] = "";
}
rowMap.set(rowKey, row);
rowOrder.push(rowKey);
}
const row = rowMap.get(rowKey)!;
@@ -236,11 +238,7 @@ function buildRowsFromStatusList(
}
}
return Array.from(rowMap.values()).sort((a, b) => {
const sidoCmp = String(a[SIDO_FIELD]).localeCompare(String(b[SIDO_FIELD]), "ko");
if (sidoCmp !== 0) return sidoCmp;
return String(a[SGG_FIELD]).localeCompare(String(b[SGG_FIELD]), "ko");
});
return rowOrder.map((key) => rowMap.get(key)!);
}
function buildUnSubmitDataRequest(
@@ -4,8 +4,6 @@ import { useEffect, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Search } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@common/components";
import { CodeSelect } from "@/entities/code/ui/code-select";
import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service";
@@ -17,6 +15,14 @@ import {
type VerificationTargetManagementFormData,
verificationTargetManagementSchema,
} from "@/entities/statistics/model/verification-target-management-schema";
import {
Label,
RadioGroup,
RadioGroupItem,
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@common/components";
import {
Button,
Dialog,
@@ -321,16 +327,27 @@ export function VerificationTargetDialog({
{tabValue !== "IMR" && (
<TableRow>
<TableHead className="bg-muted font-medium">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1">
중요도 계수(μ)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
<span className="inline-flex cursor-help items-center gap-1">
중요도 계수(μ)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
</TooltipTrigger>
<TooltipContent>
<p>통계청(Statistics Canada) 등에서 기업 단위의 주기적 조사 데이터(수익, 매출, 생산량 등)에서 이상치(Outlier)를 탐지할 때, 데이터의 크기(규모)에 따라 이상치 판별 기준을 다르게 적용하기 위해 도입된 가중치 요인</p>
<p>
통계청(Statistics
Canada) 등에서 기업
단위의 주기적 조사
데이터(수익, 매출,
생산량 등)에서
이상치(Outlier)를 탐지할
때, 데이터의
크기(규모)에 따라 이상치
판별 기준을 다르게
적용하기 위해 도입된
가중치 요인
</p>
</TooltipContent>
</Tooltip>
</TableHead>
@@ -370,13 +387,19 @@ export function VerificationTargetDialog({
<TableHead className="bg-muted font-medium">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1">
백분위수 기준값(pct)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
<span className="inline-flex cursor-help items-center gap-1">
백분위수 기준값(pct)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
</TooltipTrigger>
<TooltipContent>
<p>데이터가 정규분포를 따르지 않아도, 데이터의 하위/상위 몇 % 위치를 기준으로 이상치 범위를 정할지 결정</p>
<p>
데이터가 정규분포를
따르지 않아도, 데이터의
하위/상위 몇 % 위치를
기준으로 이상치 범위를
정할지 결정
</p>
</TooltipContent>
</Tooltip>
</TableHead>
@@ -419,16 +442,23 @@ export function VerificationTargetDialog({
{tabValue !== "IMR" && (
<TableRow>
<TableHead className="bg-muted font-medium">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1">
스케일 조정 계수(A)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
<span className="inline-flex cursor-help items-center gap-1">
스케일 조정 계수(A)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
</TooltipTrigger>
<TooltipContent>
<p>데이터의 크기가 다른 경우, 특히 규모가 작은 업체가 이상치로 잘못 탐지되는 것을 막기 위해 변환된 비율(Symmetric Ratios)에 규모(size)의 영향을 보정하는 역할</p>
<p>
데이터의 크기가 다른
경우, 특히 규모가 작은
업체가 이상치로 잘못
탐지되는 것을 막기 위해
변환된 비율(Symmetric
Ratios)에 규모(size)의
영향을 보정하는 역할
</p>
</TooltipContent>
</Tooltip>
</TableHead>
@@ -465,16 +495,22 @@ export function VerificationTargetDialog({
)}
/>
</TableCell>
<TableHead className="bg-muted font-medium" >
<TableHead className="bg-muted font-medium">
<Tooltip>
<TooltipTrigger asChild>
<span className="inline-flex cursor-help items-center gap-1">
임계 계수(c)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
<span className="inline-flex cursor-help items-center gap-1">
임계 계수(c)
<i className="diveicon di-info-circle text-muted-foreground" />
</span>
</TooltipTrigger>
<TooltipContent>
<p>데이터의 분포가 중앙값(median)을 중심으로 얼마나 흩어져 있는지를 바탕으로 이상치 범위를 결정</p>
<p>
데이터의 분포가
중앙값(median)을
중심으로 얼마나 흩어져
있는지를 바탕으로 이상치
범위를 결정
</p>
</TooltipContent>
</Tooltip>
</TableHead>
@@ -513,6 +549,48 @@ export function VerificationTargetDialog({
</TableCell>
</TableRow>
)}
<TableRow>
<TableHead className="bg-muted font-medium">
사용 여부
</TableHead>
<TableCell colSpan={3}>
<Controller
name="useYn"
control={control}
render={({ field }) => (
<div className="space-y-1">
<RadioGroup
className="flex items-center"
{...field}
onValueChange={
field.onChange
}
>
<div className="flex items-center gap-1">
<RadioGroupItem
value="Y"
id="useY"
/>
<Label htmlFor="useY">
예
</Label>
</div>
<div className="flex items-center gap-1">
<RadioGroupItem
value="N"
id="useN"
/>
<Label htmlFor="useN">
아니오
</Label>
</div>
</RadioGroup>
</div>
)}
/>
</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -612,4 +690,3 @@ export function VerificationTargetDialog({
</>
);
}