Files
frontend/apps/st/src/components/statistics/verification/detail/ScatterChart.tsx
T

320 lines
9.4 KiB
TypeScript

import React, { useMemo } from "react";
import { Scatter } from "react-chartjs-2";
import {
Chart as ChartJS,
type ChartData,
type ChartOptions,
Legend,
LinearScale,
LineController,
LineElement,
PointElement,
ScatterController,
Tooltip,
type TooltipItem,
} from "chart.js";
import zoomPlugin from "chartjs-plugin-zoom";
import type { StAnlsRsltResponse } from "@/entities/statistics";
import {
useStAnlsChartData,
useStAnlsRsltList,
} from "@/entities/statistics/api/queries";
import { LoadingWithAnimation } from "@common/components";
import type { AppliedFilter } from "./HbVerificationDetail";
ChartJS.register(
LinearScale,
LineController,
LineElement,
PointElement,
ScatterController,
Legend,
Tooltip,
zoomPlugin,
);
interface ScatterChartProps {
anlsSn: number;
vrfcTrgtSn: string | null;
appliedFilter: AppliedFilter;
onPointClick?: (rsltSn: number | null) => void;
}
interface LinePoint {
x: number;
y: number;
}
interface DataPoint extends LinePoint {
item: StAnlsRsltResponse;
}
/** 모든 점의 x·y를 합쳐 두 축이 같은 [min, max] 구간을 쓰도록 할 때 사용 */
function getUnifiedLinearRange(data: ChartData<"scatter">): {
min: number;
max: number;
} | null {
const values: number[] = [];
for (const ds of data.datasets) {
for (const pt of ds.data) {
if (pt && typeof pt === "object" && "x" in pt && "y" in pt) {
const p = pt as LinePoint;
if (Number.isFinite(p.x)) values.push(p.x);
if (Number.isFinite(p.y)) values.push(p.y);
}
}
}
if (values.length === 0) return null;
const min = Math.min(...values);
const max = Math.max(...values);
if (min === max) {
const pad = Math.abs(min) * 0.05 || 1;
return { min: min - pad, max: max + pad };
}
const padding = (max - min) * 0.02;
return { min: min - padding, max: max + padding };
}
function matchesAdmdstFilter(
admdstCd: string,
sidoCd: string | null | undefined,
gugunCd: string | undefined,
): boolean {
const gugun = (gugunCd ?? "").trim();
if (gugun) {
return admdstCd === gugun;
}
const sido = (sidoCd ?? "").trim();
if (!sido) {
return true;
}
return admdstCd.startsWith(sido.slice(0, 2));
}
const ScatterChart: React.FC<ScatterChartProps> = ({
anlsSn,
vrfcTrgtSn,
appliedFilter,
onPointClick,
}) => {
const { data: resultData, isLoading: isLoadingGrid } = useStAnlsRsltList(
anlsSn,
vrfcTrgtSn,
);
const { data: chartData, isLoading: isLoadingChart } = useStAnlsChartData(
anlsSn,
vrfcTrgtSn,
);
const isLoading = isLoadingGrid || isLoadingChart;
const chartConfig = useMemo(() => {
if (!resultData || !chartData) return null;
const rawPoints = (resultData.content ?? []) as StAnlsRsltResponse[];
const boundaries = chartData.list ?? [];
const sortedBoundaries = [...boundaries].sort(
(a, b) => a.xprev - b.xprev,
);
const upperLineData: LinePoint[] = sortedBoundaries.map((b) => ({
x: b.yupper,
y: b.xprev,
}));
const lowerLineData: LinePoint[] = sortedBoundaries.map((b) => ({
x: b.xprev,
y: b.ylower,
}));
const normalPoints: DataPoint[] = [];
const outlierPoints: DataPoint[] = [];
rawPoints.forEach((item) => {
if (
!matchesAdmdstFilter(
item.admdstCd,
appliedFilter.sido,
appliedFilter.gugun,
)
) {
return;
}
if (
appliedFilter.status &&
item.otlrYnCd.toLowerCase() !== appliedFilter.status
) {
return;
}
const pt: DataPoint = {
x: Number(item.prvyrVl ?? 0),
y: Number(item.cryrVl ?? 0),
item,
};
if (item.otlrYnCd === "2") {
return;
} else if (item.otlrYnCd === "1") {
outlierPoints.push(pt);
} else {
normalPoints.push(pt);
}
});
const data: ChartData<"scatter"> = {
datasets: [
{
label: "상한선",
data: upperLineData,
showLine: true,
borderColor: "rgba(255, 99, 132, 0.8)",
pointRadius: 0,
},
{
label: "하한선",
data: lowerLineData,
showLine: true,
borderColor: "rgba(54, 162, 235, 0.8)",
pointRadius: 0,
},
{
label: "이상치",
data: outlierPoints,
backgroundColor: "rgba(255, 99, 132, 0.7)",
pointRadius: 4,
pointHoverRadius: 8,
},
{
label: "정상",
data: normalPoints,
backgroundColor: "rgba(75, 192, 192, 0.7)",
pointRadius: 4,
pointHoverRadius: 8,
},
],
};
const axisRange = getUnifiedLinearRange(data);
const options: ChartOptions<"scatter"> = {
responsive: true,
maintainAspectRatio: false,
onClick: (event, elements) => {
if (elements.length > 0) {
const element = elements[0];
if (!element) return;
const datasetIndex = element.datasetIndex;
const index = element.index;
const dataset = data.datasets[datasetIndex];
if (!dataset) return;
// 상한선/하한선 클릭 시 무시
if (dataset.showLine) return;
const pt = dataset.data[index] as DataPoint;
if (pt?.item?.rsltSn) {
onPointClick?.(pt.item.rsltSn);
}
} else {
onPointClick?.(null);
}
},
plugins: {
zoom: {
pan: {
enabled: true,
mode: "xy",
},
zoom: {
wheel: {
enabled: true,
},
pinch: {
enabled: true,
},
mode: "xy",
},
},
tooltip: {
callbacks: {
label: (context: TooltipItem<"scatter">) => {
const dataset = context.dataset;
if (dataset.showLine) {
return `${context.dataset.label}: (${context?.parsed?.x?.toFixed(2) ?? "-"}, ${context?.parsed?.y?.toFixed(2) ?? "-"})`;
}
const pt = (context.raw as DataPoint) ?? {};
return `${pt?.item?.sido ?? "시/도"} ${pt?.item?.gugun ?? "구/군"}: 이전(${pt?.x ?? "-"}), 당해(${pt?.y ?? "-"})`;
},
},
},
},
scales: {
x: {
type: "linear",
position: "bottom",
min: axisRange?.min,
max: axisRange?.max,
title: {
display: true,
text: "이전년도 값",
},
},
y: {
type: "linear",
min: axisRange?.min,
max: axisRange?.max,
title: {
display: true,
text: "당해년도 값",
},
},
},
};
return { data, options };
}, [
resultData,
chartData,
appliedFilter.sido,
appliedFilter.gugun,
appliedFilter.status,
]);
return (
<div className="relative flex-1 p-4">
{!vrfcTrgtSn ? (
<div className="flex h-full w-full items-center justify-center text-[1.4rem] text-muted-foreground">
항목을 선택해주세요
</div>
) : isLoading ? (
<div className="flex w-full items-center justify-center py-40">
<div className="relative size-[5rem]">
<LoadingWithAnimation color="primary" />
</div>
</div>
) : chartConfig ? (
<div className="size-[40rem]">
<Scatter
data={chartConfig.data}
options={chartConfig.options}
/>
</div>
) : (
<div className="flex h-full w-full items-center justify-center text-[1.4rem] text-muted-foreground">
표시할 데이터가 없습니다.
</div>
)}
</div>
);
};
export default ScatterChart;