Files
kfpa-cx-dash-front/src/components/kfpa/CustomerSatisfactionTotal.tsx
kric_jspark 5e53663b24 260609_01_ENH: 메인 페이지 안내문 /기준으로 앞뒤 띄어쓰기 1개씩 추가 및 안내문 1줄 추가
Comment 테이블에서 plan26 제거 및 label 수정, 테이블 width 조정, 안내문 추가
전체 현황 외 차트 테이블의 차트 시작 위치 수정
2026-06-09 16:48:19 +09:00

255 lines
8.6 KiB
TypeScript

"use client";
import { useCallback, useMemo } from "react";
import type { ChartData } from "@/components/chart/types";
import TopChartTable from "@/components/combo/TopChartTable";
import type { TopChartTableRow } from "@/components/combo/types";
import { cn } from "@/lib/utils";
import { useCsiDataQuery } from "@/query/statistics";
import type { DashboardMetricConfig, DashboardMetricGroup } from "@/types/kfpa";
import VerticalBar from "@/components/chart/VerticalBar";
import type { DataColumn } from "@/components/table/types";
import {
KFPA_GAP_SIGN_STYLE,
DASHBOARD_METRIC_GROUP_LABEL_MAP,
DASHBOARD_TOTAL_TITLE_BY_CATEGORY,
REGION_KEY_MAP,
getDashboardMetricConfigs,
getDashboardTotalColumnEntries,
getDashboardTotalTableLayout, GAP_WORDING, AVERAGE_GAP_WORDING, DIV_KEYS,
} from "@/config/kfpa.config";
import type { DashboardTotalTableLayout } from "@/config/kfpa.config";
import { useLayoutFilter } from "@/components/layout/LayoutCategoryContext";
import {
getAverageGapValue,
getCsiDataByWave,
getCsiMetricGapValue,
getCsiMetricValue, getSummaryDataKey,
getWaveLabel,
} from "@/lib/kfpa-util";
const getGroupMetricCount = (metrics: readonly DashboardMetricConfig[], group: DashboardMetricGroup) =>
metrics.filter((metric) => metric.group === group).length;
const isFirstMetricInGroup = (
metrics: readonly DashboardMetricConfig[],
metricIndex: number,
group: DashboardMetricGroup
) => metrics.findIndex((metric) => metric.group === group) === metricIndex;
const getPreAppendCells = (
metrics: readonly DashboardMetricConfig[],
metric: DashboardMetricConfig,
metricIndex: number,
waveIndex: number,
rowCountPerMetric: number,
tableLayout: DashboardTotalTableLayout
): TopChartTableRow["preAppendCells"] => {
if (waveIndex !== 0) return undefined;
if (metric.group === "csi") {
return [
{
content: DASHBOARD_METRIC_GROUP_LABEL_MAP.csi,
colSpan: 2,
rowSpan: rowCountPerMetric,
width: tableLayout.csiLabelWidth,
className: "bg-csi text-center align-middle font-bold content-text-base",
},
];
}
const cells: TopChartTableRow["preAppendCells"] = [];
if (isFirstMetricInGroup(metrics, metricIndex, metric.group)) {
cells.push({
content: DASHBOARD_METRIC_GROUP_LABEL_MAP[metric.group],
rowSpan: rowCountPerMetric * getGroupMetricCount(metrics, metric.group),
width: tableLayout.groupLabelWidth,
className: cn(`bg-${metric.group}`, "text-center align-middle font-bold content-text-base"),
});
}
cells.push({
content: metric.label,
rowSpan: rowCountPerMetric,
width: tableLayout.metricLabelWidth,
className: cn(`bg-${metric.group}`, "whitespace-pre-wrap text-left align-middle font-bold content-text-base"),
});
return cells;
};
const CustomerSatisfactionTotal = () => {
const { selectMenu, statisticsParams } = useLayoutFilter();
const categoryKey = statisticsParams.pkey;
const { data, isLoading, isError } = useCsiDataQuery(statisticsParams);
const metrics = useMemo(() => getDashboardMetricConfigs(categoryKey), [categoryKey]);
const tableLayout = useMemo(() => getDashboardTotalTableLayout(categoryKey), [categoryKey]);
const divisionColumns = useMemo(
() =>
getDashboardTotalColumnEntries(categoryKey).map(([key, label]) => ({
key,
label: key === "-1" ? label : REGION_KEY_MAP[key] ?? label,
})),
[categoryKey]
);
const addAverageGapRow = useMemo(() => categoryKey === "2601009_A", [categoryKey]);
const { categoryColumns, categories, rows, chartData } = useMemo(() => {
const waves = Array.from(
new Set(
Object.values(data ?? {})
.flat()
.map((item) => item.wave)
.filter((wave) => Number.isFinite(wave))
)
).sort((a, b) => a - b);
const latestWave = waves.at(-1);
const selectedWaves = latestWave == null ? [] : [latestWave - 1, latestWave];
const categoryColumns: DataColumn<Record<string, unknown>>[] = divisionColumns.map((div) => ({
key: div.key,
header: div.label,
headerClassName: div.key === "-1" && div.label ? "bg-summary" : undefined,
align: "center",
}));
const categories = divisionColumns.map((div) => div.label);
const rows: TopChartTableRow[] =
selectedWaves.length === 0 || latestWave == undefined
? []
: metrics.flatMap((metric, metricIndex) =>
[
{
label: GAP_WORDING,
values: divisionColumns.map((div) =>
getCsiMetricGapValue(data, div.key, selectedWaves[0], selectedWaves[1], metric.key)
),
},
...selectedWaves.map((wave) => ({
label: getWaveLabel(wave),
values: divisionColumns.map((div) => getCsiMetricValue(data, div.key, wave, metric.key)),
})),
...(addAverageGapRow && metric.group === "csi"
? [{
label: AVERAGE_GAP_WORDING,
values: divisionColumns.map((div) => getAverageGapValue(data, DIV_KEYS[0], div.key, latestWave)),
}]
: []
),
].map((row, rowIndex) => ({
...row,
preAppendCells: getPreAppendCells(
metrics,
metric,
metricIndex,
rowIndex,
selectedWaves.length + (addAverageGapRow && metric.group === "csi"? 2 : 1),
tableLayout
),
labelClassName: cn(`bg-${metric.group}`, "text-center", row.label !== GAP_WORDING && "font-bold"),
labelWidth: tableLayout.waveLabelWidth,
}))
);
const chartData: ChartData = {
categories,
series: selectedWaves.map((wave) => ({
name: getWaveLabel(wave),
data: divisionColumns.map((div) => getCsiDataByWave(data, div.key, wave)?.csi ?? 0),
})),
};
return {
categoryColumns,
categories,
rows,
chartData,
};
}, [data, divisionColumns, metrics, tableLayout]);
const handleChartClick = useCallback(
(params: unknown) => {
if (divisionColumns.length <= 1) return;
const dataIndex = typeof params === "object" && params !== null && "dataIndex" in params
? Number((params as { dataIndex?: unknown }).dataIndex)
: NaN;
const divKey = divisionColumns[dataIndex]?.key;
if (divKey && divKey !== "-1") {
selectMenu(divKey);
}
},
[divisionColumns, selectMenu]
);
if (isLoading) {
return <div className="content-text-sm text-muted-foreground">데이터를 불러오는 중입니다.</div>;
}
if (isError) {
return <div className="content-text-sm text-destructive">고객만족도 데이터를 불러오지 못했습니다.</div>;
}
if (rows.length === 0) {
return <div className="content-text-sm text-muted-foreground">표시할 고객만족도 데이터가 없습니다.</div>;
}
return (
<div className="w-full">
<TopChartTable
title={DASHBOARD_TOTAL_TITLE_BY_CATEGORY[categoryKey ?? ""] ?? "고객 만족도"}
columns={categoryColumns}
rows={rows}
sectionRows={[
{
afterRowIndex: addAverageGapRow? 3 : 2,
content: "고객만족지수 세부 항목",
className: "bg-gray-400 text-center font-bold",
bodyClassName: "bg-gray-400 text-center",
},
]}
signStyle={KFPA_GAP_SIGN_STYLE}
minWidth={divisionColumns.length > 1 ? 1120 : 900}
maxWidth={tableLayout.tableWidth}
chartHeight={200}
chart={
<VerticalBar
data={chartData}
height="100%"
paletteVarNames={["--chart-5", "--chart-7"]}
valueFormatter={(value) => value.toFixed(2)}
barMaxWidth={30}
showFocusLabel="all"
labelOptions={{ position: "top", distance: 4 }}
grid={{ left: 0, right: 0, top: 30, bottom: 5 }}
xAxis={{
type: "category",
data: categories,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
}}
yAxis={{
type: "value",
min: 3.95,
max: 5,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: false },
}}
onEvents={{ click: handleChartClick }}
/>
}
/>
</div>
);
};
export default CustomerSatisfactionTotal;