Files
lg-cxdash-front/src/lib/lg-dashboard.ts

544 lines
16 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {
BannerGroupKey,
BannerResponse,
BannerRow, BuildPageModeConfigResult,
ProductResponse, ProductRow,
StatisticsRequest
} from "@/types/lg.types";
import {ChartData} from "@/components/lge-dashboard";
import {API_DECIMAL_POINT, GAP_WORDING, VIEW_DECIMAL_POINT} from "@/const/lg-common.const";
import {BANNER_GROUP, BANNER_KEYS} from "@/const/lg-banner.const";
import {PRODUCT_KEYS} from "@/const/lg-product.const";
import {CATEGORY_PAGE_FIELDS} from "@/config/lg-page.config";
import {formatNumber} from "@/lib/utils";
import {nextApi} from "@/lib/http-client";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "").includes("사례수");
export const isCagrRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("CAGR");
export const isGapRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("GAP");
/**
* Row Label을 표시용 텍스트로 포맷팅합니다.
* - "사례수" -> "(사례수)"
* - "gap" -> "전년 대비 GAP(%p)"
* - "CAGR" -> "CAGR(%)"
* - "24" -> "24년"
* - "보급율" -> "보급율(%)"
* - 기타 -> 원본 그대로
*/
export function formatRowLabel(
label: string,
options?: {
convertSample?: boolean; // "사례수" -> "(사례수)" (기본값: true)
convertGap?: boolean; // "gap" -> "전년 대비 GAP(%p)" (기본값: 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_WORDING;
if (convertCagr && t.toUpperCase() === "CAGR") return "CAGR(%)";
if (convertYear && /^\d{4}$/.test(t)) return `${t.substring(2,4)}년`;
if (convertYear && /^\d{2}$/.test(t)) return `${t}년`;
if (convertRate && t.endsWith("율")) return `${t.replaceAll('(%)','')}(%)`;
if (convertCount && t.includes("대수")) return `${t.replaceAll('(대)','')}(대)`;
return t;
}
export const wrapSampleRow = <T extends Record<string, unknown> & { rowLabel: string }>(
rows: T[], replaceLabel: boolean = true
): T[] => {
return rows.map((r) => {
if (!isSampleRow(r.rowLabel)) return r;
const out: any = { ...r };
Object.entries(r).forEach(([k, v]) => {
if (k == "year" || v == null) return;
if (
typeof v === "number" ||
(typeof v === "string" && v.trim() !== "" && !Number.isNaN(Number(v)))
) {
out[k] = `(${formatNumber(Number(v))})`;
return;
}
if(replaceLabel){
if (typeof v === "string") {
// 이미 괄호면 그대로
out[k] = v.startsWith("(") && v.endsWith(")") ? v : `(${v})`;
return;
}
out[k] = `(${String(v)})`;
}
});
return out as 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: string) => string;
/** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */
splitStackByYear?: boolean;
};
export function buildYearSeriesChartData(rows: BannerRow[], 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) => Number(a) - Number(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<string, 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: BannerRow[],
opts: Opts = {}
): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(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<string, 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: BannerRow[],
prevYear: number,
curYear: number,
baseRowLabel: string,
gapRowLabel = "gap"
): BannerRow | null => {
const prev = rows.find(r => Number(r.year) === prevYear && r.rowLabel === baseRowLabel);
const cur = rows.find(r => Number(r.year) === curYear && r.rowLabel === baseRowLabel);
if (!prev || !cur) return null;
const gap: BannerRow = {
year: String(curYear),
rowLabel: gapRowLabel,
total: String(Number(cur.total) - Number(prev.total)),
};
// cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산
(Object.keys(cur) as Array<keyof BannerRow>).forEach((k) => {
if (k === "year" || k === "rowLabel") return;
const vCur = cur[k];
const vPrev = prev[k];
(gap as any)[k] = String(Number(vCur) - Number(vPrev));
});
return gap;
}
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;
export const fetchProductStatistics = (req: StatisticsRequest) =>
nextApi.post<ProductResponse>("/statistics/product", req);
export const fetchBannerStatistics = (req: StatisticsRequest) =>
nextApi.post<BannerResponse>("/statistics/banner", req);
type FilterInput =
| Record<string, unknown>
| Map<string, unknown>
| null
| undefined;
export function normalizeFilterCondition(
input: FilterInput,
upToZero: boolean = true
): Record<string, number[]> | undefined {
if (!input) return undefined;
const entries =
input instanceof Map ? Array.from(input.entries()) : Object.entries(input);
const out: Record<string, number[]> = {};
for (const [k, v] of entries) {
if (!k || v == null) continue;
const nums: number[] = [];
const pushNum = (x: unknown) => {
if (x == null) return;
const pushIfValid = (n: number) => {
if (!Number.isFinite(n)) return;
if (upToZero && n === 0) return; // upToZero=true일 때만 0 제외
nums.push(n);
};
if (typeof x === "number") {
pushIfValid(x);
return;
}
if (typeof x === "string") {
const parts = x
.split(/[,\|]/g)
.map((s) => s.trim())
.filter(Boolean);
for (const p of parts) {
pushIfValid(Number(p));
}
}
};
if (Array.isArray(v)) {
for (const item of v) pushNum(item);
} else {
pushNum(v);
}
if (nums.length > 0) out[k] = nums;
}
return Object.keys(out).length ? out : undefined;
}
export const buildCategoryFilter = (
filterValue:CategoryFilterValue
): Record<string, number[]> | undefined => {
const out: Record<string, number[]> = {};
const productCode = filterValue.product.split("#").at(-1);
if (productCode) {
out["product"] = [Number(productCode)];
}
return Object.keys(out).length ? out : undefined;
}
const fixedDecimalPoint = (n: number, decimalPoint?: number): string => {
decimalPoint ??= API_DECIMAL_POINT;
return n.toFixed(decimalPoint);
};
export const roundNumber = (num: number|null, decimalPoint?: number) => {
if(num == null) return null;
decimalPoint ??= VIEW_DECIMAL_POINT;
const factor = 10 ** decimalPoint;
return Math.round(num * factor) / factor;
};
export const calcGapProductRow = (after: ProductRow, before: ProductRow): ProductRow => {
const out: ProductRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
};
for (const k of PRODUCT_KEYS) {
const a = after? after[k] ?? "0" : "0";
const b = before? before[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(a) - Number(b));
}
return out;
};
export const calcGapBannerRow = (after: BannerRow, before: BannerRow): BannerRow => {
const out: BannerRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
};
for (const k of BANNER_KEYS) {
const a = after? after[k] ?? "0" : "0";
const b = before? before[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(a) - Number(b));
}
return out;
};
const calcCagr = (after: number, before: number, years:number): number => {
const power = Math.pow(after / before, 1 / years);
const cagr = power - 1;
const cagr100 = cagr * 100;
return cagr100;
};
export const calcCagrRow = (after: ProductRow, before: ProductRow): ProductRow => {
const years = 2; // 24 -> 26
const out: ProductRow = {
year: after?.year ?? "",
rowLabel: "CAGR",
total: "0"
};
// total은 참고용으로만: (26/24) CAGR %
out.total =
fixedDecimalPoint((before?.total ?? "0") > "0" ? calcCagr(Number(after?.total ?? "0"), Number(before?.total ?? "0"), years) : 0, 1);
for (const k of PRODUCT_KEYS) {
const vBefore = before? before[k] ?? "0" : "0";
const vAfter = after? after[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(Number(vBefore) > 0 ? calcCagr(Number(vAfter), Number(vBefore), years) : 0, 1);
}
return out;
};
export const makeTotalBasePct = (t:number|string, f:number|string):number => {
return Number(t) > 0 ? (Number(f) * 100) / Number(t) : 0;
}
export const calcTotalBaseRow = (label:string, totalRow: ProductRow, targetRow: ProductRow): ProductRow => {
const out: ProductRow = {
year: targetRow?.year ?? "",
rowLabel: `조사 년도 ${label} 중 자사제품 비율 (LG ${label} ÷ 전체 ${label}) × 100`,
total: fixedDecimalPoint(makeTotalBasePct(totalRow.total, targetRow.total))
};
for (const k of PRODUCT_KEYS) {
const t = totalRow? totalRow[k] ?? "0" : "0";
const f = targetRow? targetRow[k] ?? "0" : "0";
out[k] = fixedDecimalPoint(makeTotalBasePct(t, f));
}
return out;
}
export const withGapRow = <T>(
rows: T[],
calcGapRow: (last: T, secondLast: T) => T,
lastIndex: number,
secondLastIndex: number,
): T[] => {
const last = rows.at(lastIndex);
const secondLast = rows.at(secondLastIndex);
if (!last || !secondLast) return rows;
return [calcGapRow(last, secondLast), ...rows];
}
export const withCagrRow = <T>(
rows: T[],
calcCagrRow: (last: T, first: T) => T,
lastIndex: number,
firstIndex: number,
): T[] => {
const first = rows.at(firstIndex);
const last = rows.at(lastIndex);
if (!first || !last) return rows;
return [...rows, calcCagrRow(last, first)];
}
export const withTotalBaseRow = <T>(
label:string,
totalRows: T[],
targetRows: T[],
calcTotalBaseRow: (label:string, total: T, target: T) => T
): T[] => {
const totalRow = totalRows.at(-1);
const targetRow = targetRows.at(-1);
if (!totalRow || !targetRow) return targetRows;
const totalBaseRow = calcTotalBaseRow(label, totalRow, targetRow);
return targetRows.length === 0 ? [totalBaseRow] : [targetRows[0], totalBaseRow, ...targetRows.slice(1)];
}
const renderKey = (tpl: string, keyBase: string) => tpl.replaceAll("${keyBase}", keyBase.toLowerCase());
export const buildPageModeConfig = (
filterValue: CategoryFilterValue
):BuildPageModeConfigResult => {
const fields = (CATEGORY_PAGE_FIELDS[filterValue.target.value] ?? [])
.filter((f) => !!f.qidByMode[filterValue.type.value])
.map((f) => ({
...f,
requestKeyResolved: renderKey(f.requestKey, filterValue.type.value),
qid: f.qidByMode[filterValue.type.value]!,
}));
const variableIdMap = Object.fromEntries(fields.map((f) => [f.requestKeyResolved, f.qid])) as Record<string, string>;
return { fields, variableIdMap };
};