260202_01_ENH: route 구조 초창기 기획으로 다시 변경 및 Category 별 하위 페이지에 샘플 데이터 모두 적용

This commit is contained in:
2026-02-02 11:32:50 +09:00
parent 4b40c43962
commit 6f8e09bcf3
60 changed files with 1750 additions and 464 deletions

269
src/lib/lg-dashboard.ts Normal file
View File

@@ -0,0 +1,269 @@
import {BannerGroupKey, ServerBannerRow} from "@/types/lg";
import {ChartData} from "@/components/lge-dashboard";
import {BANNER_GROUP} from "@/const/lgConst";
export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "") === "사례수";
/**
* Row Label을 표시용 텍스트로 포맷팅합니다.
* - "사례수" -> "(사례수)"
* - "gap" -> "전년 대비 GAP(%)"
* - "CAGR" -> "CAGR(%)"
* - "24" -> "24년"
* - "보급율" -> "보급율(%)"
* - 기타 -> 원본 그대로
*/
export function formatRowLabel(
label: string,
options?: {
convertSample?: boolean; // "사례수" -> "(사례수)" (기본값: true)
convertGap?: boolean; // "gap" -> "전년 대비 GAP(%)" (기본값: true)
convertCagr?: boolean; // "CAGR" -> "CAGR(%)" (기본값: true)
convertYear?: boolean; // "24" -> "24년" (기본값: true)
convertRate?: boolean; // "~율" -> "~율(%)" (기본값: true)
convertCount?: boolean; // "~대수" -> "~대수(대)" (기본값: true)
}
): string {
const {
convertSample = true,
convertGap = true,
convertCagr = true,
convertYear = true,
convertRate = true,
convertCount = true,
} = options ?? {};
const t = label.trim();
if (convertSample && t === "사례수") return "(사례수)";
if (convertGap && t.toLowerCase() === "gap") return "전년 대비 GAP(%)";
if (convertCagr && t.toUpperCase() === "CAGR") return "CAGR(%)";
if (convertYear && /^\d{2}$/.test(t)) return `${t}년`;
if (convertRate && t.endsWith("율")) return `${t}(%)`;
if (convertCount && t.includes("대수")) return `${t}(대)`;
return t;
}
/**
* 연도 배열로부터 연도 -> 인덱스 맵을 생성합니다.
* @param years - 연도 배열 (예: [2024, 2025, 2026])
* @returns Map<연도, 인덱스>
*/
export function createYearIndexMap(years: number[]): Map<number, number> {
return new Map<number, number>(years.map((y, i) => [y, i]));
}
/**
* 연도 필터링: 지정된 연도 배열에 포함되고 rowLabel이 "년"으로 끝나는 행만 반환
* @param data - 필터링할 데이터 배열
* @param years - 허용할 연도 배열
* @returns 필터링된 데이터 배열
*/
export function filterYearRows<T extends { year: number; rowLabel: string }>(
data: T[],
years: number[]
): T[] {
return data.filter((r) => years.includes(r.year) && r.rowLabel.endsWith("년"));
}
/**
* GroupedOverlayBarData 구조를 생성합니다.
* @param params - 데이터 생성 파라미터
* @returns GroupedOverlayBarData 구조
*/
export function buildOverlayBarData<T extends { year: number; rowLabel: string }>(params: {
totalRows: T[];
focusRows: T[];
productKeys: string[];
years: number[];
totalName?: string;
focusName?: string;
}): {
years: number[];
categories: string[];
totalData: Array<Array<number>>;
focusData: Array<Array<number>>;
totalName: string;
focusName: string;
} {
const {
totalRows,
focusRows,
productKeys,
years,
totalName = "전체",
focusName = "LG",
} = params;
const yearIndexMap = createYearIndexMap(years);
const total: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
const focus: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
// totalRows에서 데이터 매핑
const filteredTotal = filterYearRows(totalRows, years);
for (const row of filteredTotal) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
total[yi][pi] = val;
}
}
}
// focusRows에서 데이터 매핑
const filteredFocus = filterYearRows(focusRows, years);
for (const row of filteredFocus) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
focus[yi][pi] = val;
}
}
}
return {
years,
categories: productKeys,
totalData: total,
focusData: focus,
totalName,
focusName,
};
}
type Opts = {
/** 기본: ["사례수", "gap"] 제외 */
excludeRowLabels?: string[];
/** 기본: (y) => `${y}년` */
yearLabel?: (y: number) => string;
/** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */
splitStackByYear?: boolean;
};
export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {}): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
splitStackByYear = false,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
// rowLabel 순서: 첫 연도 기준으로 고정(없으면 전체 unique)
const baseYear = years[0];
const baseLabels = rows
.filter((r) => r.year === baseYear)
.map((r) => r.rowLabel)
.filter((l) => !excludeRowLabels.includes(l));
const labels =
baseLabels.length > 0
? baseLabels
: Array.from(
new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l)))
);
// 빠른 조회용: year -> (rowLabel -> total)
const map = new Map<number, Map<string, number>>();
for (const y of years) map.set(y, new Map());
for (const r of rows) {
if (excludeRowLabels.includes(r.rowLabel)) continue;
map.get(r.year)?.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories: labels,
series: years.map((y) => ({
name: yearLabel(y),
data: labels.map((lbl) => map.get(y)?.get(lbl) ?? null),
...(splitStackByYear ? { stack: String(y) } : {}), // 같은 stack이면 "연도끼리 스택"되어버리니 방지용
})),
};
}
export function buildRowLabelSeriesChartData(
rows: ServerBannerRow[],
opts: Opts = {}
): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
const categories = years.map(yearLabel);
const baseYear = years[0];
const baseRowLabels = rows
.filter((r) => r.year === baseYear)
.map((r) => r.rowLabel)
.filter((l) => !excludeRowLabels.includes(l));
const rowLabels =
baseRowLabels.length > 0
? baseRowLabels
: Array.from(
new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l)))
);
// (year -> (rowLabel -> total)) 맵
const valueMap = new Map<number, Map<string, number>>();
for (const y of years) valueMap.set(y, new Map());
for (const r of rows) {
if (excludeRowLabels.includes(r.rowLabel)) continue;
valueMap.get(r.year)!.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories,
series: rowLabels.map((lbl) => ({
name: lbl,
data: years.map((y) => valueMap.get(y)!.get(lbl) ?? null),
})),
};
}
export const buildGapRow = (
rows: ServerBannerRow[],
prevYear: number,
curYear: number,
baseRowLabel: string,
gapRowLabel = "gap"
): ServerBannerRow | null => {
const prev = rows.find(r => r.year === prevYear && r.rowLabel === baseRowLabel);
const cur = rows.find(r => r.year === curYear && r.rowLabel === baseRowLabel);
if (!prev || !cur) return null;
const gap: ServerBannerRow = {
year: curYear,
rowLabel: gapRowLabel,
total: (typeof cur.total === "number" ? cur.total : 0) - (typeof prev.total === "number" ? prev.total : 0),
};
// cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산
(Object.keys(cur) as Array<keyof ServerBannerRow>).forEach((k) => {
if (k === "year" || k === "rowLabel") return;
const vCur = cur[k];
const vPrev = prev[k];
const hasNumber = typeof vCur === "number" || typeof vPrev === "number";
if (!hasNumber) return;
(gap as any)[k] = (typeof vCur === "number" ? vCur : 0) - (typeof vPrev === "number" ? vPrev : 0);
});
return gap;
}
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;