260331_02_ENH: 그룹 헤더 다단도 가능하게 수정

This commit is contained in:
2026-03-31 11:08:30 +09:00
parent e51c6ba810
commit d58c0b4dd4
13 changed files with 577 additions and 622 deletions

View File

@@ -6,8 +6,9 @@ import {
StatisticsRequest
} from "@/types/lg.types";
import {ChartData} from "@/components/lge-dashboard";
import type { DataColumn } from "@/components/lge-dashboard/types";
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 {BANNER_GROUP, BANNER_KEYS, type BannerGroupDefinition, type BannerGroupNode, flattenBannerGroupKeys} 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";
@@ -316,6 +317,47 @@ export const buildGapRow = (
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;
export function buildBannerGroupColumns<T extends Record<string, unknown>>(
group: BannerGroupDefinition,
keyLabelMap: Record<string, string>,
options: {
width?: number | string;
numeric?: boolean;
resolveLeafMeta?: (key: string, index: number, total: number) => {
headerClassName?: string;
cellClassName?: string;
};
} = {}
): DataColumn<T>[] {
const leafKeys = flattenBannerGroupKeys(group.children);
let leafIndex = 0;
const visit = (nodes: readonly BannerGroupNode[]): DataColumn<T>[] =>
nodes.map((node) => {
if (node.type === "leaf") {
const currentLeafIndex = leafIndex++;
const meta = options.resolveLeafMeta?.(node.key, currentLeafIndex, leafKeys.length);
return {
key: node.key as keyof T,
header: keyLabelMap[node.key] ?? String(node.key),
numeric: options.numeric,
width: options.width,
headerClassName: meta?.headerClassName,
cellClassName: meta?.cellClassName,
};
}
return {
id: node.id,
header: node.label,
children: visit(node.children),
};
});
return visit(group.children);
}
export const fetchProductStatistics = (req: StatisticsRequest) =>
nextApi.post<ProductResponse>("/statistics/product", req);

View File

@@ -1,15 +1,17 @@
// exportDashboardExcel.ts
// exportDashboardExcel.ts
"use client";
import {formatRowLabel} from "@/lib/lg-dashboard";
import {DataColumn} from "@/components/lge-dashboard";
import { buildBannerGroupColumns, formatRowLabel } from "@/lib/lg-dashboard";
import { DataColumn, GaugeColumn } from "@/components/lge-dashboard";
import { buildHeaderRows, getLeafColumns, type TableColumnNode } from "@/components/lge-dashboard/table/core/table-core.helpers";
import type { BannerGroupDefinition } from "@/const/lg-banner.const";
/**
* 요구사항:
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더(그룹 머지), (3) BANNER_GROUP 헤더(좌측 2칸 rowspan2 + 그룹 머지)
* - Excel export (한 시트, 섹션 간 1행 띄움)
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더, (3) BANNER_GROUP 헤더를 함께 지원
* - Excel export는 한 시트에 여러 섹션을 순서대로 기록
* - 헤더 스타일:
* group: background = --lg-gray-400
* group: background = --lg-gray-400
* header: background = --lg-gray-600
* font: #fff, bold
*/
@@ -47,9 +49,9 @@ type ExportOptions<T extends Record<string, any>> = {
sheetName?: string;
sections: Section<T>[];
// CSS 변수(없으면 기본값)
groupBgVar?: string; // default "--lg-gray-400"
groupBgVar?: string; // default "--lg-gray-400"
headerBgVar?: string; // default "--lg-gray-600"
borderVar?: string; // default "--lg-gray-300"
borderVar?: string; // default "--lg-gray-300"
};
/* =========================================================
@@ -208,11 +210,11 @@ function writeMergedHeader(
}
type AutoFitOpt = {
minColWidth?: number; // Excel column width units
minColWidth?: number; // Excel column width units
maxColWidth?: number;
padding?: number; // width 여유(문자수 기준)
padding?: number; // width 여유(문자수 기준)
baseRowHeight?: number; // pt
maxRowHeight?: number; // pt
maxRowHeight?: number; // pt
useCanvasMeasure?: boolean; // 브라우저에서 measureText로 더 정확하게
};
@@ -257,7 +259,7 @@ function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoF
const w = estimateWidth(text, cell, o); // width in "excel-char-like units"
if (mi && mi.colSpan > 1) {
// 머지된 텍스트는 span만큼 나눠서 분배(머지 텍스트 때문에 한 컬럼이 과대해지는 현상 방지)
// 머지된 텍스트는 span만큼 나눠서 분배(한 컬럼 폭이 과대해지는 현상 방지)
const perCol = w / mi.colSpan;
for (let c = mi.leftCol; c <= mi.rightCol; c++) {
widths[c] = Math.max(widths[c], perCol);
@@ -299,7 +301,7 @@ function fitRows(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitO
? sumColumnWidth(ws, mi.leftCol, mi.rightCol, o)
: getColumnWidth(ws, colNumber, o);
// 각 라인 별로 "줄바꿈이 몇 줄로 늘어나는지" 근사
// 각 라인별로 줄바꿈이 몇 줄로 늘어나는지 근사
let cellLines = 0;
for (const line of explicitLines) {
const lineW = estimateWidth(line, cell, o);
@@ -326,11 +328,11 @@ function estimateWidth(text: string, cell: any, o: Required<AutoFitOpt>) {
if (o.useCanvasMeasure && typeof document !== "undefined") {
const px = measureTextPx(maxLine, cell);
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도가 근사치로 많이 씀
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도를 사용
return px / 7;
}
// canvas 못 쓰는 환경(또는 성능 이유) -> 문자폭 가중치 근사
// canvas를 못 쓰는 환경이면 문자 폭 가중치로 근사
return estimateByCharWeight(maxLine);
}
@@ -350,11 +352,11 @@ function getMeasureCanvas() {
return __canvas;
}
// 한글/중국어/일본어 등 wide char 가중치 + 숫자/영문 가중치
// 한글/CJK wide char 가중치 + 숫자/영문 가중치
function estimateByCharWeight(s: string) {
let w = 0;
for (const ch of s) {
if (isWideChar(ch)) w += 1.7; // 한글/한자/가나 등
if (isWideChar(ch)) w += 1.7; // 한글/한자/가나 등
else if (ch === " ") w += 0.6;
else if (/[A-Z]/.test(ch)) w += 1.1;
else if (/[0-9]/.test(ch)) w += 1.0;
@@ -441,7 +443,7 @@ function buildMergeMap(ws: any) {
const merges = ws?._merges;
if (!merges) return map;
// ws._merges: Map<string, any> 형태인 경우가 많음. key가 "A1:C1" 같은 range
// ws._merges: Map<string, any> 형태인 경우가 많고 key는 "A1:C1" 같은 range
const keys: string[] =
merges instanceof Map ? Array.from(merges.keys()) : Object.keys(merges);
@@ -459,7 +461,7 @@ function buildMergeMap(ws: any) {
return map;
}
// "A1:C3" -> 좌표
// "A1:C3" -> 醫뚰몴
function parseRange(range: string): Omit<MergeInfo, "colSpan"> | null {
const parts = range.split(":");
if (parts.length !== 2) return null;
@@ -507,7 +509,7 @@ function colToLetters(col: number) {
}
/* =========================================================
* 3) 헤더 빌더 3종
* 3) 헤더 빌더
* ========================================================= */
/**
@@ -541,138 +543,31 @@ export function buildHeader_ProductKeyMap(
/**
* (2) LIFE_STAGE_COLUMNS:
* - 1행: group 머지(같은 group 연속 구간)
* - 2행: header 텍스트
*
* group 없는 컬럼은 1행에 빈 셀(그룹 스타일) 1칸 채움
* - 트리 기반 컬럼에서 header row를 계산
* - HTML 테이블과 동일한 merge 구조를 Excel에 적용
*/
export type GaugeColumn = {
key: string;
header: string;
rowHead?: boolean;
group?: string;
align?: "left" | "center" | "right";
};
function buildHeaderBlockFromColumns<T>(cols: TableColumnNode<T>[]): HeaderBlock {
const headerRows = buildHeaderRows(cols).map((row) =>
row.map((cell) => ({
text: cell.label,
styleKey: (cell.isLeaf ? "header" : "group") as HeaderStyleKey,
rowSpan: cell.rowSpan,
colSpan: cell.colSpan,
align: "center" as const,
}))
);
export function buildHeader_LifeStageColumns(cols: GaugeColumn[]): HeaderBlock {
const row1: HeaderCell[] = [];
const row2: HeaderCell[] = [];
const leafKeys = cols.map((c) => c.key);
const leafKeys = getLeafColumns(cols).map((column) => String(column.key));
return { headerRows, leafKeys, totalCols: leafKeys.length };
}
let i = 0;
while (i < cols.length) {
const c = cols[i];
const g = c.group;
if (!g) {
row1.push({ text: "", styleKey: "group", colSpan: 1, align: "center" });
i += 1;
continue;
}
let j = i + 1;
while (j < cols.length && cols[j].group === g) j += 1;
const span = j - i;
row1.push({ text: g, styleKey: "group", colSpan: span, align: "center" });
i = j;
}
for (const c of cols) {
row2.push({ text: c.header ?? "", styleKey: "header", colSpan: 1, align: "center" });
}
return { headerRows: [row1, row2], leafKeys, totalCols: cols.length };
export function buildHeader_LifeStageColumns<T>(cols: GaugeColumn<T>[]): HeaderBlock {
return buildHeaderBlockFromColumns(cols);
}
export function buildHeader_DataColumn<T>(cols: DataColumn<T>[]): HeaderBlock {
const row1: HeaderCell[] = [];
const row2: HeaderCell[] = [];
const leafKeys = cols.map((c) => String(c.key));
// 1행: 그룹 머지 / rowspan 처리
let i = 0;
while (i < cols.length) {
const c = cols[i];
const rs = c.headRowSpan ?? 1;
// (A) rowspan=2면: 1행에 header를 올리고(세로머지), 2행은 빈 칸(placeholder)
if (rs === 2) {
row1.push({
text: c.header ?? "",
styleKey: "header",
colSpan: 1,
rowSpan: 2,
align: c.align ?? "center",
});
i += 1;
continue;
}
// (B) 그룹 구간 처리
const gKey = c.groupKey ?? c.group;
if (gKey) {
let j = i + 1;
while (j < cols.length) {
const cj = cols[j];
const rsj = cj.headRowSpan ?? 1;
const gKeyJ = cj.groupKey ?? cj.group;
// rowspan=2가 섞이면 그룹 머지 끊음(안정성)
if (rsj === 2) break;
if (gKeyJ !== gKey) break;
j += 1;
}
const span = j - i;
row1.push({
text: c.group ?? "",
styleKey: "group",
colSpan: span,
align: "center",
});
// 2행: 그룹 구간의 각 컬럼 header
for (let k = i; k < j; k++) {
const ck = cols[k];
row2.push({
text: ck.header ?? "",
styleKey: "header",
colSpan: 1,
align: ck.align ?? "center",
});
}
i = j;
continue;
}
// (C) 그룹도 없고 rowspan도 아니면: 1행에 빈 group 셀 1개, 2행에 header
row1.push({
text: "",
styleKey: "group",
colSpan: 1,
align: "center",
});
row2.push({
text: c.header ?? "",
styleKey: "header",
colSpan: 1,
align: c.align ?? "center",
});
i += 1;
}
return {
headerRows: [row1, row2],
leafKeys,
totalCols: cols.length,
};
return buildHeaderBlockFromColumns(cols);
}
/**
* (3) BANNER_GROUP + BANNER_KEY_MAP:
* - A1: "" (rowspan2)
@@ -681,34 +576,23 @@ export function buildHeader_DataColumn<T>(cols: DataColumn<T>[]): HeaderBlock {
* - 2행: 각 key의 라벨(BANNER_KEY_MAP[key])
*/
export function buildHeader_Banner<K extends string>(
bannerGroup: Record<string, { label: string; keys: readonly K[] }>,
bannerGroup: Record<string, BannerGroupDefinition>,
bannerKeyMap: Record<K, string>,
rowHeadKey = "rowLabel",
totalKey = "total"
): HeaderBlock {
const groups = Object.values(bannerGroup);
const row1: HeaderCell[] = [
{ text: "", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
{ text: "전체", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
const columns: DataColumn<Record<string, unknown>>[] = [
{ key: rowHeadKey, header: "" },
{ key: totalKey, header: "전체" },
...Object.entries(bannerGroup).map(([groupKey, group]) => ({
id: `banner-${groupKey}`,
header: group.label,
children: buildBannerGroupColumns<Record<string, unknown>>(group, bannerKeyMap),
})),
];
const row2: HeaderCell[] = [];
const leafKeys: string[] = [rowHeadKey, totalKey];
for (const g of groups) {
row1.push({ text: g.label, styleKey: "group", colSpan: g.keys.length, align: "center" });
for (const k of g.keys) {
row2.push({ text: bannerKeyMap[k] ?? k, styleKey: "header", colSpan: 1, align: "center" });
leafKeys.push(k);
}
}
const totalCols = 2 + groups.reduce((acc, g) => acc + g.keys.length, 0);
return { headerRows: [row1, row2], leafKeys, totalCols };
return buildHeaderBlockFromColumns(columns);
}
/* =========================================================
* 4) Export (one sheet, 섹션 간 1행 띄움)
* ========================================================= */
@@ -722,7 +606,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
borderVar = "--lg-gray-300",
} = opts;
// ExcelJS import (환경에 따라 min 빌드가 더 잘 먹는 경우가 있음)
// ExcelJS import (환경에 따라 min 빌드가 더 잘 동작하는 경우가 있음)
const ExcelJS = await import("exceljs");
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet(sheetName);
@@ -740,7 +624,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
const gap = sec.rowGap ?? 1;
const { header, rows } = sec;
// (선택) 섹션 타이틀
// 섹션 타이틀
if (sec.title) {
const r = ws.getRow(rowCursor);
const c = r.getCell(1);
@@ -832,4 +716,6 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}
}