Files
epolicy-dash-front/src/app/(pages)/(main)/dashboard/[waveCd]/[partCd]/page.tsx

262 lines
9.9 KiB
TypeScript

"use client";
import { ChevronDown } from "lucide-react";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { KriBarChart } from "@/components/chart";
import { AppPageTitle } from "@/components/app-shell/AppPageTitle";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { CHART_BAR_MAX_WIDTH, CHART_FONT_SIZE, CHART_HEIGHT } from "@/const/epolicy-dash.const";
import { cn } from "@/lib/utils";
import { toChartData } from "@/lib/chart-utils";
import { formatDecimal1, formatThousands, round1 } from "@/lib/format";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { usePartDetailQuery } from "@/query/waves";
import type { Item, ResultGroup } from "@/types/wave";
// audience.type이 SURVEY인 문항의 대표 색상은 실제 응답에 포함된 series[].color를 그대로 사용한다.
// surveyCd/label 기준으로 색상을 별도 매핑하지 않는다.
function findAudienceColor(item: Item): string | undefined {
for (const group of item.resultGroups) {
const withColor = group.series.find((series) => series.color);
if (withColor) return withColor.color;
}
return undefined;
}
function seriesLegendName(label: string, baseCount: number | null) {
return baseCount === null ? label : `${label} (N=${formatThousands(baseCount)})`;
}
// 차트에서 숨겨진(chartVisible=false) 카테고리를 각주로 만든다. 값이 0인 항목은 무시한다.
// 시리즈(설문)가 하나뿐이면 "※ 기타 0.9%, 모름·무응답 2.3%"처럼 시리즈명을 생략하고,
// 여러 개면 "※ 기타 : 일반국민 0.9%, 전문가 3.8% | 모름·무응답 : 일반국민 2.5%"처럼 구분해서 표기한다.
function buildHiddenCategoryNote(group: ResultGroup): string | null {
const isSingleSeries = group.series.length === 1;
const parts = group.categories
.map((category, index) => {
if (category.chartVisible) return null;
const entries = group.series
.map((series) => ({ label: series.label, value: series.values[index] }))
.filter((entry) => entry.value !== 0);
if (!entries.length) return null;
if (isSingleSeries) {
return `${category.label} ${formatDecimal1(entries[0].value)}%`;
}
const valueText = entries.map((entry) => `${entry.label} ${formatDecimal1(entry.value)}%`).join(", ");
return `${category.label} : ${valueText}`;
})
.filter((part): part is string => part !== null);
if (!parts.length) return null;
return `※ ${parts.join(isSingleSeries ? ", " : " | ")}`;
}
// x축 카테고리 라벨 폭을 컨테이너 실측 폭 기준으로 계산한다(카테고리당 슬롯 폭에 여유를 둔 값).
// 고정값을 쓰면 화면이 넓을 때는 불필요하게 줄바꿈되고, 좁을 때는 라벨이 겹치는 문제가 생긴다.
const MIN_AXIS_LABEL_WIDTH = 48;
function ResultGroupChart({ group }: { group: ResultGroup }) {
const chartData = toChartData(group.categories, group.series);
const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0;
const chartWrapperRef = useRef<HTMLDivElement>(null);
const [axisLabelWidth, setAxisLabelWidth] = useState<number>();
useEffect(() => {
const el = chartWrapperRef.current;
if (!el || chartData.categories.length === 0) return;
const updateAxisLabelWidth = () => {
const width = (el.clientWidth / chartData.categories.length) * 0.85;
setAxisLabelWidth(Math.max(MIN_AXIS_LABEL_WIDTH, width));
};
updateAxisLabelWidth();
const observer = new ResizeObserver(updateAxisLabelWidth);
observer.observe(el);
return () => observer.disconnect();
}, [chartData.categories.length]);
if (!hasChartData) return null;
return (
<div ref={chartWrapperRef}>
<KriBarChart
categories={chartData.categories}
series={chartData.series.map((item) => ({
name: seriesLegendName(item.label, item.baseCount),
data: item.values.map(round1),
color: item.color,
option: {
label: {
show: true,
position: "top",
fontSize: CHART_FONT_SIZE,
formatter: (params: { value: number }) => formatDecimal1(params.value),
},
},
}))}
legend={{ left: 0, top: 0, textStyle: { fontSize: CHART_FONT_SIZE } }}
grid={{ top: 55, right: 25, bottom: 5, left: 0, containLabel: true }}
xAxis={{
axisLabel: {
fontSize: CHART_FONT_SIZE,
interval: 0,
...(axisLabelWidth ? { width: axisLabelWidth, overflow: "break" as const } : {}),
},
}}
yAxis={{ min: 0, max: 100, interval: 25, axisLabel: { fontSize: CHART_FONT_SIZE } }}
barMaxWidth={CHART_BAR_MAX_WIDTH}
height={CHART_HEIGHT}
/>
</div>
);
}
function ResultGroupTable({ group }: { group: ResultGroup }) {
if (!group.categories.length) {
return <p className="text-sm text-muted-foreground">데이터가 없습니다.</p>;
}
return (
<div className="overflow-x-auto rounded-md border">
<Table>
<TableHeader>
<TableRow>
<TableHead className="border">{`BASE: ${group.series[0].baseText}`}</TableHead>
<TableHead className="border">사례수</TableHead>
{group.categories.map((category) => (
<TableHead key={category.label} className="text-center border">
{category.label}
</TableHead>
))}
</TableRow>
</TableHeader>
<TableBody>
{group.series.map((series) => (
<TableRow key={series.surveyCd}>
<TableCell className="font-medium whitespace-normal border">{series.label}</TableCell>
<TableCell className="border">
{series.baseCount !== null ? `(${formatThousands(series.baseCount)})` : "-"}
</TableCell>
{series.values.map((value, index) => (
<TableCell key={group.categories[index]?.label ?? index} className="text-right border">
{value === 0 ? "-" : formatDecimal1(value)}
</TableCell>
))}
</TableRow>
))}
</TableBody>
</Table>
</div>
);
}
function ItemCard({ item }: { item: Item }) {
const [showTable, setShowTable] = useState(false);
const [activeGroupIndex, setActiveGroupIndex] = useState(0);
const hasSubItems = item.resultGroups.some((group) => group.subItem !== null);
const activeGroup = item.resultGroups[activeGroupIndex] ?? item.resultGroups[0];
const hiddenCategoryNote = activeGroup ? buildHiddenCategoryNote(activeGroup) : null;
return (
<div id={`item-${item.partItemCd}`} className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="font-medium">{item.title}</p>
<div className="flex items-center gap-2">
<Badge
className={cn(
"rounded-md px-3 py-1.5 text-sm font-semibold text-white",
item.audience.type === "COMMON" && "bg-slate-500",
)}
style={item.audience.type === "COMMON" ? undefined : { backgroundColor: findAudienceColor(item) }}
>
{item.audience.label}
</Badge>
<Button type="button" variant="outline" size="sm" onClick={() => setShowTable((current) => !current)}>
통계표 보기
<ChevronDown className={cn("size-4 transition-transform", showTable && "rotate-180")} />
</Button>
</div>
</div>
{hasSubItems ? (
<div className="mt-4 flex justify-end">
<div className="inline-flex rounded-md border p-1">
{item.resultGroups.map((group, index) => (
<Button
key={group.subItem?.partItemSubCd ?? index}
type="button"
size="sm"
variant={index === activeGroupIndex ? "default" : "ghost"}
className="rounded-sm"
onClick={() => setActiveGroupIndex(index)}
>
{group.subItem?.title}
</Button>
))}
</div>
</div>
) : null}
{activeGroup ? (
<div className="mt-4">
<ResultGroupChart group={activeGroup} />
{hiddenCategoryNote ? <p className="mt-1 text-xs text-muted-foreground">{hiddenCategoryNote}</p> : null}
{showTable ? (
<div className="mt-6">
<ResultGroupTable group={activeGroup} />
</div>
) : null}
</div>
) : null}
{item.comment ? <p className="mt-4 text-xs text-muted-foreground">{item.comment}</p> : null}
</div>
);
}
export default function PartDetailPage() {
const params = useParams<{ waveCd: string; partCd: string }>();
const router = useRouter();
const waveCd = Number(params.waveCd);
const partCd = Number(params.partCd);
const { data, isPending, isError, error } = usePartDetailQuery(waveCd, partCd);
useEffect(() => {
if (isError && isSessionInvalid(error)) router.replace("/logout");
}, [isError, error, router]);
if (isPending) {
return <p className="text-sm text-muted-foreground">불러오는 중입니다...</p>;
}
if (isError) {
if (isSessionInvalid(error)) return null;
return (
<div className="space-y-6">
<AppPageTitle title="문항" />
<div className="rounded-lg border bg-card p-6 text-card-foreground shadow-sm">
<p className="text-sm text-destructive">{resolveApiErrorMessage(error)}</p>
</div>
</div>
);
}
return (
<div className="space-y-6">
<AppPageTitle title={data.title} />
{data.items.map((item) => (
<ItemCard key={item.partItemCd} item={item} />
))}
</div>
);
}