260825_04_ENH: 차트 색상을 t_survey 종속적으로 변경 및 후속처리

This commit is contained in:
2026-08-25 16:43:10 +09:00
parent fbd22a1471
commit bcf4b258b2
3 changed files with 85 additions and 37 deletions

View File

@@ -18,7 +18,7 @@ import {
SUBITEM_NEGATIVE_COLOR, SUBITEM_NEGATIVE_COLOR,
} from "@/const/epolicy-dash.const"; } from "@/const/epolicy-dash.const";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { getGapPoints, getHighlightedIndexes, toChartData } from "@/lib/chart-utils"; import { getGapPoints, getHighlightedIndexes, isNegativeCategory, toChartData } from "@/lib/chart-utils";
import { formatDecimal1, formatThousands, round1 } from "@/lib/format"; import { formatDecimal1, formatThousands, round1 } from "@/lib/format";
import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message"; import { isSessionInvalid, resolveApiErrorMessage } from "@/lib/api-error-message";
import { usePartDetailQuery } from "@/query/waves"; import { usePartDetailQuery } from "@/query/waves";
@@ -110,8 +110,11 @@ function wrapLabelByWord(value: string, maxWidth: number, charWidth: number) {
return lines.join("\n"); return lines.join("\n");
} }
function ResultGroupChart({ group }: { group: ResultGroup }) { function ResultGroupChart({ group, item }: { group: ResultGroup; item: Item }) {
const chartData = toChartData(group.categories, group.series); const chartData = toChartData(group.categories, group.series);
const visibleCategories = group.categories.filter((category) => category.chartVisible);
const negativeMode = group.subItem === null ? item.negativeMode : group.subItem.negativeMode;
const negativeOrder = group.subItem === null ? item.negativeOrder : group.subItem.negativeOrder;
const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0; const hasChartData = chartData.categories.length > 0 && chartData.series.length > 0;
const chartWrapperRef = useRef<HTMLDivElement>(null); const chartWrapperRef = useRef<HTMLDivElement>(null);
const [axisLabelWidth, setAxisLabelWidth] = useState<number>(); const [axisLabelWidth, setAxisLabelWidth] = useState<number>();
@@ -137,18 +140,29 @@ function ResultGroupChart({ group }: { group: ResultGroup }) {
<div ref={chartWrapperRef}> <div ref={chartWrapperRef}>
<KriBarChart <KriBarChart
categories={chartData.categories} categories={chartData.categories}
series={chartData.series.map((item) => { series={chartData.series.map((series) => {
const highlightedIndexes = item.chartHighlightMode ? getHighlightedIndexes(group.categories, item) : []; const highlightedIndexes = series.chartHighlightMode
const gapPoints = getGapPoints(group.categories, item); ? getHighlightedIndexes(group.categories, series)
: [];
const gapPoints = getGapPoints(group.categories, series);
return { return {
name: seriesLegendName(item.label, item.baseCount), name: seriesLegendName(series.label, series.baseCount),
data: item.values.map((value, index) => data: series.values.map((value, index) => {
highlightedIndexes.includes(index) && item.chartHighlightColor const category = visibleCategories[index];
? { value: round1(value), itemStyle: { color: item.chartHighlightColor } } const isNegative = category ? isNegativeCategory(negativeMode, negativeOrder, category) : false;
: round1(value), const isHighlighted = highlightedIndexes.includes(index);
), const color = isNegative
color: item.color, ? isHighlighted
? series.negativeHighlightColor
: series.negativeColor
: isHighlighted
? series.highlightColor
: series.color;
return { value: round1(value), itemStyle: { color } };
}),
color: negativeMode === "NEGATIVE" ? series.negativeColor : series.color,
option: { option: {
label: { label: {
show: true, show: true,
@@ -166,7 +180,7 @@ function ResultGroupChart({ group }: { group: ResultGroup }) {
show: true, show: true,
position: "top", position: "top",
// 막대 자체의 값 라벨(position:"top")과 겹치지 않도록 그 위로 띄운다. // 막대 자체의 값 라벨(position:"top")과 겹치지 않도록 그 위로 띄운다.
distance: 15, distance: 30,
color: CHART_GAP_MARKER_TEXT_COLOR, color: CHART_GAP_MARKER_TEXT_COLOR,
backgroundColor: CHART_GAP_MARKER_BG_COLOR, backgroundColor: CHART_GAP_MARKER_BG_COLOR,
borderRadius: 20, borderRadius: 20,
@@ -176,12 +190,9 @@ function ResultGroupChart({ group }: { group: ResultGroup }) {
formatter: ({ value }: { value: number }) => formatter: ({ value }: { value: number }) =>
`${value >= 0 ? "▲" : "▼"} ${formatDecimal1(Math.abs(value))}%p`, `${value >= 0 ? "▲" : "▼"} ${formatDecimal1(Math.abs(value))}%p`,
}, },
// ALL: 현재 막대 바로 위. LAST_VISIBLE: 직전 막대와의 중간 지점(두 막대 사이)에 표시한다. // ALL: 각 현재 막대 위치. LAST_VISIBLE: 마지막 표시 막대 위치에 표시한다.
data: gapPoints.map(({ index, previousIndex, value, previousValue, gap }) => ({ data: gapPoints.map(({ index, value, gap }) => ({
coord: coord: [index, value],
item.chartGapMode === "LAST_VISIBLE"
? [(index + previousIndex) / 2, Math.max(value, previousValue)]
: [index, value],
value: gap, value: gap,
})), })),
}, },
@@ -286,7 +297,7 @@ function ItemCard({ item }: { item: Item }) {
<div className="inline-flex shrink-0 rounded-md border p-1"> <div className="inline-flex shrink-0 rounded-md border p-1">
{item.resultGroups.map((group, index) => { {item.resultGroups.map((group, index) => {
const isActive = index === activeGroupIndex; const isActive = index === activeGroupIndex;
const isNegativeSubItem = group.subItem?.partItemSubCd === 2; const isNegativeSubItem = group.subItem?.negativeMode === "NEGATIVE";
return ( return (
<Button <Button
@@ -322,7 +333,7 @@ function ItemCard({ item }: { item: Item }) {
{activeGroup ? ( {activeGroup ? (
<div className="mt-4"> <div className="mt-4">
<ResultGroupChart group={activeGroup} /> <ResultGroupChart group={activeGroup} item={item} />
{hiddenCategoryNote ? <p className="mt-1 text-xs text-muted-foreground">{hiddenCategoryNote}</p> : null} {hiddenCategoryNote ? <p className="mt-1 text-xs text-muted-foreground">{hiddenCategoryNote}</p> : null}
{showTable ? ( {showTable ? (
<div className="mt-6"> <div className="mt-6">

View File

@@ -2,9 +2,7 @@ import { round1 } from "@/lib/format";
import type { Category, Series } from "@/types/wave"; import type { Category, Series } from "@/types/wave";
export function toChartData<T extends { values: number[] }>(categories: Category[], series: T[]) { export function toChartData<T extends { values: number[] }>(categories: Category[], series: T[]) {
const visibleIndexes = categories const visibleIndexes = getVisibleCategoryIndexes(categories);
.map((category, index) => (category.chartVisible ? index : -1))
.filter((index) => index >= 0);
return { return {
categories: visibleIndexes.map((index) => categories[index].label), categories: visibleIndexes.map((index) => categories[index].label),
@@ -15,6 +13,31 @@ export function toChartData<T extends { values: number[] }>(categories: Category
}; };
} }
export function getVisibleCategoryIndexes(categories: Category[]): number[] {
return categories
.map((category, index) => (category.chartVisible ? index : -1))
.filter((index) => index >= 0);
}
export function isNegativeCategory(
mode: "DEFAULT" | "NEGATIVE" | "SPECIFIED",
negativeOrder: string | null,
category: Category,
): boolean {
if (mode === "NEGATIVE") return true;
if (mode !== "SPECIFIED") return false;
return parseOrderSet(negativeOrder).has(category.order);
}
function parseOrderSet(value: string | null): Set<number> {
return new Set(
(value ?? "")
.split(",")
.map((order) => Number(order.trim()))
.filter((order) => Number.isFinite(order)),
);
}
// chartVisible=true인 카테고리만 대상으로, 강조할 데이터 포인트의 인덱스를 계산한다. // chartVisible=true인 카테고리만 대상으로, 강조할 데이터 포인트의 인덱스를 계산한다.
// 반환되는 인덱스는 toChartData가 만든 필터링된(visible) 카테고리/값 배열 기준이다. // 반환되는 인덱스는 toChartData가 만든 필터링된(visible) 카테고리/값 배열 기준이다.
export function getHighlightedIndexes( export function getHighlightedIndexes(
@@ -25,11 +48,10 @@ export function getHighlightedIndexes(
switch (series.chartHighlightMode) { switch (series.chartHighlightMode) {
case "MAX_VALUE": { case "MAX_VALUE": {
const visibleValues = toChartData(categories, [series]).series[0].values; const visibleValues = getVisibleCategoryIndexes(categories).map((index) => series.values[index]);
if (!visibleValues.length) return []; if (!visibleValues.length) return [];
const maxValue = Math.max(...visibleValues); const maxValue = Math.max(...visibleValues);
const index = visibleValues.indexOf(maxValue); return visibleValues.flatMap((value, index) => (value === maxValue ? [index] : []));
return index >= 0 ? [index] : [];
} }
case "LAST_VISIBLE": { case "LAST_VISIBLE": {
if (!visibleCategories.length) return []; if (!visibleCategories.length) return [];
@@ -38,13 +60,9 @@ export function getHighlightedIndexes(
return index >= 0 ? [index] : []; return index >= 0 ? [index] : [];
} }
case "SPECIFIED": { case "SPECIFIED": {
const orders = (series.chartHighlightValue ?? "") const orders = parseOrderSet(series.chartHighlightValue);
.split(",")
.map((value) => Number(value.trim()))
.filter((value) => !Number.isNaN(value));
if (!orders.length) return [];
return visibleCategories return visibleCategories
.map((category, index) => (orders.includes(category.order) ? index : -1)) .map((category, index) => (orders.has(category.order) ? index : -1))
.filter((index) => index >= 0); .filter((index) => index >= 0);
} }
default: default:
@@ -72,17 +90,26 @@ export function getGapPoints(
if (series.chartGapMode !== "ALL" && series.chartGapMode !== "LAST_VISIBLE") return []; if (series.chartGapMode !== "ALL" && series.chartGapMode !== "LAST_VISIBLE") return [];
const visiblePoints = categories const visiblePoints = categories
.map((category, index) => ({ category, value: round1(series.values[index]) })) .map((category, originalIndex) => ({ category, originalIndex, value: round1(series.values[originalIndex]) }))
.filter((point) => point.category.chartVisible) .filter((point) => point.category.chartVisible)
.sort((a, b) => a.category.order - b.category.order); .sort((a, b) => a.category.order - b.category.order);
if (visiblePoints.length < 2) return []; if (visiblePoints.length < 2) return [];
const displayIndexByOriginalIndex = new Map<number, number>();
let displayIndex = 0;
categories.forEach((category, originalIndex) => {
if (category.chartVisible) {
displayIndexByOriginalIndex.set(originalIndex, displayIndex);
displayIndex += 1;
}
});
const gapPoints = visiblePoints.slice(1).map((current, index) => { const gapPoints = visiblePoints.slice(1).map((current, index) => {
const previous = visiblePoints[index]; const previous = visiblePoints[index];
return { return {
index: index + 1, index: displayIndexByOriginalIndex.get(current.originalIndex) ?? index + 1,
previousIndex: index, previousIndex: displayIndexByOriginalIndex.get(previous.originalIndex) ?? index,
value: current.value, value: current.value,
previousValue: previous.value, previousValue: previous.value,
gap: round1(current.value - previous.value), gap: round1(current.value - previous.value),

View File

@@ -12,12 +12,15 @@ export interface Category {
} }
export interface SubItem { export interface SubItem {
negativeMode: NegativeMode;
negativeOrder: string | null;
partItemSubCd: number; partItemSubCd: number;
partItemSubComment: string | null; partItemSubComment: string | null;
title: string; title: string;
} }
export type ChartType = "BAR"; export type ChartType = "BAR";
export type NegativeMode = "DEFAULT" | "NEGATIVE" | "SPECIFIED";
export type ChartHighlightMode = "MAX_VALUE" | "LAST_VISIBLE" | "SPECIFIED"; export type ChartHighlightMode = "MAX_VALUE" | "LAST_VISIBLE" | "SPECIFIED";
@@ -29,13 +32,15 @@ export interface Series {
/** DB에 저장된 원문 그대로. baseCount와 조합해 생성되는 값이 아니다 (예: "전국 만 18세 이상 성인 남녀"). */ /** DB에 저장된 원문 그대로. baseCount와 조합해 생성되는 값이 아니다 (예: "전국 만 18세 이상 성인 남녀"). */
baseText: string | null; baseText: string | null;
chartGapMode: ChartGapMode; chartGapMode: ChartGapMode;
chartHighlightColor: string | null;
chartHighlightMode: ChartHighlightMode | null; chartHighlightMode: ChartHighlightMode | null;
/** chartHighlightMode가 "SPECIFIED"일 때 강조할 category.order 목록 (쉼표 구분 문자열, 예: "1,3,5"). */ /** chartHighlightMode가 "SPECIFIED"일 때 강조할 category.order 목록 (쉼표 구분 문자열, 예: "1,3,5"). */
chartHighlightValue: string | null; chartHighlightValue: string | null;
chartType: ChartType; chartType: ChartType;
color: string; color: string;
highlightColor: string;
label: string; label: string;
negativeColor: string;
negativeHighlightColor: string;
surveyCd: number; surveyCd: number;
values: number[]; values: number[];
} }
@@ -49,6 +54,8 @@ export interface ResultGroup {
export interface Item { export interface Item {
audience: Audience; audience: Audience;
comment: string; comment: string;
negativeMode: NegativeMode;
negativeOrder: string | null;
order: number; order: number;
partItemCd: number; partItemCd: number;
resultGroups: ResultGroup[]; resultGroups: ResultGroup[];
@@ -87,7 +94,10 @@ export interface SurveyItem {
export interface Survey { export interface Survey {
alias: string; alias: string;
color: string; color: string;
highlightColor: string;
items: SurveyItem[]; items: SurveyItem[];
negativeColor: string;
negativeHighlightColor: string;
surveyCd: number; surveyCd: number;
title: string; title: string;
} }