"use client"; import { useEffect, useMemo, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { getCoreRowModel, getPaginationRowModel, useReactTable, } from "@tanstack/react-table"; import type { AxiosError } from "axios"; import dayjs from "dayjs"; import { ENDPOINT } from "@/shared/config"; import { useAlertStore } from "@/shared/lib"; import type { ApiErrorResponse } from "@/shared/model"; import { CodeSelect } from "@/entities/code"; import { analysisApi } from "@/entities/statistics/api/analysis-api"; import { analysisHistoryApi } from "@/entities/statistics/api/analysis-history-api"; import { verificationTargetManagementApi } from "@/entities/statistics/api/verification-target-management-service"; import type { StAnlsMstResponse, StAnlsMstSearchParams, StAnlsOutlierListResponse, } from "@/entities/statistics/model/analysis-history-interface"; import type { AnalysisRequestPayload, AnalysisResponseDto, } from "@/entities/statistics/model/analysis-interface"; import { verificationHistoryColumns } from "@/entities/statistics/model/verification-history-columns"; import type { VerificationTargetCodeResponse } from "@/entities/statistics/model/verification-target-management-interface"; import { Button, Checkbox, DataTable, DateRangePicker, Dialog, DialogContent, DialogHeader, DialogTitle, Input, Label, LoadingWithAnimation, RadioGroup, RadioGroupItem, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, Table, TableBody, TableCell, TableHead, TableHeader, TableRow, } from "@common/components"; import HbVerificationDetail from "./detail/HbVerificationDetail"; type DateRangeValue = { from: Date; to?: Date; }; type VerifyType = "ALL" | "SELECT"; interface VerificationFormState { mu: string; percentile: string; a: string; c: string; verificationYear: string; } interface OutlierDialogState { open: boolean; anlsSn: number | null; } function getDefaultHistoryDateRange(): DateRangeValue { const to = dayjs().endOf("day").toDate(); const from = dayjs().subtract(7, "day").startOf("day").toDate(); return { from, to }; } function getVerificationYearOptions(): string[] { const currentYear = dayjs().year(); const startYear = 2017; const endYear = currentYear - 1; if (endYear < startYear) return []; return Array.from({ length: endYear - startYear + 1 }, (_, index) => String(startYear + index), ); } function toNumber(value: string): number { const parsed = Number(value); return Number.isNaN(parsed) ? 0 : parsed; } const HbStatisticsVerification = () => { const { setMessage: alert } = useAlertStore((state) => state); const queryClient = useQueryClient(); const yearOptions = useMemo(() => getVerificationYearOptions(), []); const defaultYear: string = yearOptions.length > 0 ? (yearOptions[yearOptions.length - 1] ?? "") : ""; const [verifyType, setVerifyType] = useState("ALL"); const [formState, setFormState] = useState({ mu: "0", percentile: "0", a: "0", c: "0", verificationYear: defaultYear, }); const [selectedTargets, setSelectedTargets] = useState([]); const [outlierDialog, setOutlierDialog] = useState({ open: false, anlsSn: null, }); const [selectedStatsCd, setSelectedStatsCd] = useState(""); const [selectedAnlsSn, setSelectedAnlsSn] = useState(null); const defaultHistoryDateRange = useMemo( () => getDefaultHistoryDateRange(), [], ); const [historyDateRange, setHistoryDateRange] = useState< DateRangeValue | undefined >(defaultHistoryDateRange); const [appliedHistoryDateRange, setAppliedHistoryDateRange] = useState< DateRangeValue | undefined >(defaultHistoryDateRange); const [historyPagination, setHistoryPagination] = useState({ pageIndex: 0, pageSize: 10, }); const { data: verificationTargetCodes } = useQuery< VerificationTargetCodeResponse[] >({ queryKey: [ENDPOINT.STATVERIFY_SERVICE.VRFCTGT_MNG, "codes"], queryFn: () => verificationTargetManagementApi.getVerificationTargetCodes(), }); const filteredVerificationTargetCodes = useMemo(() => { return verificationTargetCodes?.filter((item) => selectedStatsCd ? item.vrfcTrgtSn.startsWith(selectedStatsCd) : true, ); }, [verificationTargetCodes, selectedStatsCd]); const allVerificationTargetIds = useMemo( () => (filteredVerificationTargetCodes ?? []).map( (item) => item.vrfcTrgtSn, ), [filteredVerificationTargetCodes], ); useEffect(() => { if (!allVerificationTargetIds.length) return; setSelectedTargets(allVerificationTargetIds); }, [allVerificationTargetIds]); const { data: analysisHistory } = useQuery({ queryKey: [ ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, historyPagination, appliedHistoryDateRange, ], queryFn: () => { const params: StAnlsMstSearchParams = { page: historyPagination.pageIndex, size: historyPagination.pageSize, }; if (appliedHistoryDateRange?.from) { params.verifyDtStart = dayjs( appliedHistoryDateRange.from, ).format("YYYY-MM-DD"); } if (appliedHistoryDateRange?.to || appliedHistoryDateRange?.from) { const to = appliedHistoryDateRange.to ?? appliedHistoryDateRange.from!; params.verifyDtEnd = dayjs(to).format("YYYY-MM-DD"); } return analysisHistoryApi.getAnalysisHistoryList(params); }, refetchInterval: (query) => { const data = query.state.data; if (!data?.content?.length) return false; const hasProcessing = (data.content as StAnlsMstResponse[]).some( (item) => item.anlsSttsCd === "PROCESSING", ); return hasProcessing ? 3000 : false; }, }); const historyRowData: StAnlsMstResponse[] = (analysisHistory?.content ?? []) as StAnlsMstResponse[]; const table = useReactTable({ data: historyRowData, columns: verificationHistoryColumns, getCoreRowModel: getCoreRowModel(), getPaginationRowModel: getPaginationRowModel(), manualPagination: true, pageCount: analysisHistory?.totalPages ?? 0, state: { pagination: historyPagination, }, onPaginationChange: (updater) => { setHistoryPagination((prev) => typeof updater === "function" ? updater(prev) : updater, ); }, meta: { onOutlierCellClick: (row: StAnlsMstResponse) => { setOutlierDialog({ open: true, anlsSn: row.anlsSn }); }, }, }); const { data: outlierList, isLoading: isLoadingOutlier } = useQuery({ queryKey: [ ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST, "outlier", outlierDialog.anlsSn, ], queryFn: async () => { if (!outlierDialog.anlsSn) return []; const response = await analysisHistoryApi.getOutlierList( outlierDialog.anlsSn, ); return response; }, enabled: outlierDialog.open && !!outlierDialog.anlsSn, }); const analysisMutation = useMutation< AnalysisResponseDto, AxiosError, AnalysisRequestPayload >({ mutationFn: async (payload) => analysisApi.analyze(payload), onSuccess: () => { alert("검증을 요청했습니다."); queryClient.invalidateQueries({ queryKey: [ENDPOINT.STATVERIFY_SERVICE.ST_ANLS_MST], }); }, onError: (error) => { alert( error.response?.data?.message ?? "검증 실행 중 오류가 발생했습니다.", ); }, }); function handleFormChange( key: Key, value: string, ) { setFormState((prev) => ({ ...prev, [key]: value, })); } function handleTargetToggle(statsCd: string) { setSelectedTargets((prev) => prev.includes(statsCd) ? prev.filter((cd) => cd !== statsCd) : [...prev, statsCd], ); } async function handleSubmit() { if (!formState.verificationYear) { alert("검증년도를 선택해 주세요."); return; } if (verifyType === "SELECT" && selectedTargets.length === 0) { alert("검증 대상을 1개 이상 선택해 주세요."); return; } const yearNew = toNumber(formState.verificationYear); const payload: AnalysisRequestPayload = { dataset: verifyType === "ALL" ? allVerificationTargetIds.length > 0 ? allVerificationTargetIds.join(",") : undefined : selectedTargets.length > 0 ? selectedTargets.join(",") : undefined, yearNew, yearOld: yearNew - 1, mu: toNumber(formState.mu), percentile: toNumber(formState.percentile), a: toNumber(formState.a), c: toNumber(formState.c), vrfcMthdCd: "HB", allVerifyYn: verifyType === "ALL" ? "Y" : "N", }; analysisMutation.mutate(payload); } function handleReset() { setFormState({ mu: "0", percentile: "0", a: "0", c: "0", verificationYear: defaultYear, }); setSelectedTargets([]); } function handleHistoryRowClick(row: StAnlsMstResponse) { const anlsSn = Number(row.anlsSn ?? 0); if (!anlsSn) return; setSelectedAnlsSn(anlsSn); } function applyHistoryDateSearch(nextRange: DateRangeValue | undefined) { setAppliedHistoryDateRange(nextRange); setHistoryPagination((prev) => ({ ...prev, pageIndex: 0, })); } function handleHistoryDateSearch() { applyHistoryDateSearch(historyDateRange); } function handleHistoryDateReset() { const resetRange = getDefaultHistoryDateRange(); setHistoryDateRange(resetRange); applyHistoryDateSearch(resetRange); } function closeOutlierDialog() { setOutlierDialog({ open: false, anlsSn: null }); } return ( <> {selectedAnlsSn ? ( setSelectedAnlsSn(null)} /> ) : ( <>
{/* 검증 종류 선택 */}
setVerifyType(value as VerifyType) } className="flex items-center gap-4" >
{/* //검증 종류 선택 */} {verifyType === "SELECT" && (
{/* 검증 대상 */}

검증 대상

{verifyType === "SELECT" && filteredVerificationTargetCodes && filteredVerificationTargetCodes.length > 0 ? (
{filteredVerificationTargetCodes.map( (item) => (
handleTargetToggle( item.vrfcTrgtSn, ) } />
), )}
) : (

검증 대상이 없습니다.

)}
{/* //검증 대상 */} {/* 검증 변수 */}

검증 변수

handleFormChange( "mu", event.target.value, ) } className="flex-1" />
handleFormChange( "percentile", event.target.value, ) } className="flex-1" />
handleFormChange( "a", event.target.value, ) } className="flex-1" />
handleFormChange( "c", event.target.value, ) } className="flex-1" />
{/* //검증 변수 */}
)}

검증 이력

검증일시 setHistoryDateRange( value?.from ? (value as DateRangeValue) : undefined, ) } className="max-w-[26rem]" />
)} 이상건수 상세 {isLoadingOutlier && (
)} {!isLoadingOutlier && (outlierList?.length ?? 0) === 0 && (

표시할 이상치 데이터가 없습니다.

)} {!isLoadingOutlier && (outlierList?.length ?? 0) > 0 && (
{outlierList?.map( (item: StAnlsOutlierListResponse) => ( {item.vrfcTrgtNm} 시도 시군구 행정구역 시설명 입력값 {item.outlierDataList.map( (data) => ( {data.sido ?? "-"} {data.gugun ?? "-"} {data.adstDong ?? "-"} {/* 시설명: DTO에 해당 필드 없음 */} - {data.cryrVl != null ? String( data.cryrVl, ) : "-"} ), )}
), )}
)}
); }; export default HbStatisticsVerification;