260205_01_ENH: 페이지 별 엑셀 다운로드 적용

This commit is contained in:
2026-02-05 09:24:19 +09:00
parent 544f3010aa
commit 3e7c2a98df
25 changed files with 2500 additions and 336 deletions

View File

@@ -7,15 +7,31 @@ import {
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import { PRODUCT_KEYS, PRODUCTS, YEARS } from "@/const/lgConst";
import { useMemo } from "react";
import { apiOwnShareOfTotalPenetration, apiTrendCategories } from "@/config/sample.data";
import {
LAST_YEAR,
LIFE_STAGE_COLUMNS,
LIFE_STAGE_GROUPS,
PRODUCT_KEY_MAP,
PRODUCT_KEYS,
PRODUCTS,
YEARS
} from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import {apiLifeStageByProduct, apiOwnShareOfTotalPenetration, apiTrendCategories} from "@/config/sample.data";
import LifeStageDiv from "@/components/lge-dashboard/combo/LifeStageDiv";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
import {
buildHeader_LifeStageColumns,
buildHeader_ProductKeyMap,
exportDashboardExcel,
Section
} from "@/lib/lg-export-excel";
import {norm} from "@/lib/utils";
import {LifeStageGroup, LifeStageRow} from "@/types/lg";
const LGPenetrationPage = () => {
const { isTotal, filterValue } = useLayoutFilter();
const { isTotal, filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const productTableRows = useMemo<TopChartTableRow[]>(() => {
@@ -29,7 +45,7 @@ const LGPenetrationPage = () => {
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const yearIndexMap = new Map<number, number>(YEARS.map((y, i) => [y, i]));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
const totalRows = apiTrendCategories.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
@@ -47,8 +63,8 @@ const LGPenetrationPage = () => {
const t = (totalRows[ri] as any)[k];
const v = (r as any)[k];
total[yi][ci] = typeof t === "number" ? t : 0;
focus[yi][ci] = typeof v === "number" ? v : 0;
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
@@ -62,6 +78,61 @@ const LGPenetrationPage = () => {
};
}, []);
const lifeStageRowsByGroup:LifeStageGroup[] = useMemo(() => {
const pick = (label: string) => apiLifeStageByProduct.find((r) => norm(r.rowLabel) === norm(label));
return LIFE_STAGE_GROUPS.map((g) => {
const rows: LifeStageRow[] = g.items.map((label) => {
const r = pick(label);
return {
item: label,
total: r?.total ?? "",
single: r?.single ?? "",
noKids: r?.noKids ?? "",
preschoolKids: r?.preschoolKids ?? "",
schoolKids: r?.schoolKids ?? "",
adultKids: r?.adultKids ?? "",
independentSenior: r?.independentSenior ?? "",
};
});
return { title: g.title, rows };
});
}, []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
const lifeStageHeader = buildHeader_LifeStageColumns(LIFE_STAGE_COLUMNS);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{
title: "LG제품 보급률",
header: excelHeader,
rows: apiOwnShareOfTotalPenetration as AnyRow[],
rowGap: 1,
},
...lifeStageRowsByGroup.map((lifeStageRow) => ({
title: lifeStageRow.title,
header: lifeStageHeader,
rows: lifeStageRow.rows as AnyRow[],
rowGap: 1,
})),
];
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(LG제품 보급률).xlsx`,
sheetName: "LG제품 보급률",
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
<TopChartTable
@@ -79,7 +150,7 @@ const LGPenetrationPage = () => {
signStyle={signStyleGapRow}
/>
<LifeStageDiv />
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup} />
</div>
);
};

View File

@@ -1,7 +1,7 @@
"use client";
import { useMemo } from "react";
import { PRODUCT_KEYS, PRODUCTS, YEARS } from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import {LAST_YEAR, PRODUCT_KEY_MAP, PRODUCT_KEYS, PRODUCTS, YEARS} from "@/const/lgConst";
import {
GroupedOverlayBar,
type GroupedOverlayBarData,
@@ -12,9 +12,10 @@ import {
import { apiOwnShareOfTotalPurchase, apiTrendBuy } from "@/config/sample.data";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
const LGPurchasePage = () => {
const { isTotal, filterValue } = useLayoutFilter();
const { isTotal, filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
@@ -28,7 +29,7 @@ const LGPurchasePage = () => {
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const yearIndexMap = new Map<number, number>(YEARS.map((y, i) => [y, i]));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
const totalRows = apiTrendBuy.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
@@ -47,8 +48,8 @@ const LGPurchasePage = () => {
const v = (r as any)[k];
// total은 t 기준으로 체크해야 안전
total[yi][ci] = typeof t === "number" ? t : 0;
focus[yi][ci] = typeof v === "number" ? v : 0;
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
@@ -62,6 +63,21 @@ const LGPurchasePage = () => {
};
}, []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(LG제품 구매율).xlsx`,
sheetName: "LG제품 구매율",
sections: [
{ title: "LG제품 구매율", header: excelHeader, rows: apiOwnShareOfTotalPurchase, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
<TopChartTable

View File

@@ -19,9 +19,10 @@ import {
PRODUCTS,
YEARS,
AXIS_HIDE_STYLE,
GRID_X_NOT_PADDING,
GRID_X_NOT_PADDING, PRODUCT_KEY_MAP, LAST_YEAR,
} from "@/const/lgConst";
import { formatRowLabel } from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
const PenetrationPage = () => {
const { isTotal, filterValue, registerExcelExporter } = useLayoutFilter();
@@ -73,7 +74,15 @@ const PenetrationPage = () => {
useEffect(() => {
registerExcelExporter(async (payload) => {
// TODO: export
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(보급률).xlsx`,
sheetName: "전체 보급률",
sections: [
{ title: "전체 보급률", header: excelHeader, rows: apiTrendCategories, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);

View File

@@ -1,7 +1,7 @@
"use client";
import { useMemo } from "react";
import { PRODUCT_KEYS, PRODUCTS, AXIS_HIDE_STYLE, GRID_X_NOT_PADDING } from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import {PRODUCT_KEYS, PRODUCTS, AXIS_HIDE_STYLE, GRID_X_NOT_PADDING, LAST_YEAR, PRODUCT_KEY_MAP} from "@/const/lgConst";
import {
type ChartData,
signStyleGapRow,
@@ -12,9 +12,10 @@ import {
import { apiTrendBuy } from "@/config/sample.data";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
const PurchasePage = () => {
const { isTotal, filterValue } = useLayoutFilter();
const { isTotal, filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
@@ -36,6 +37,21 @@ const PurchasePage = () => {
};
}, []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(구매율).xlsx`,
sheetName: "구매율",
sections: [
{ title: "구매율", header: excelHeader, rows: apiTrendBuy, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
<TopChartTable

View File

@@ -14,11 +14,15 @@ export async function POST(
const [userId] = slug;
/*
서버 로그아웃 할 필요 없음
const url = userId
? `/auth/logout/${encodeURIComponent(userId)}`
: "/auth/logout/";
//await backApi.post<boolean>(url);
await backApi.post<boolean>(url);
*/
const res = NextResponse.json({ ok: true });
res.cookies.set("access_token", "", {

View File

@@ -23,11 +23,12 @@ const BaseEChart = ({
height = CHART_HEIGHTS.DEFAULT,
className,
notMerge = true,
lazyUpdate = true,
lazyUpdate = false, //이거 켜져있으면 오류남 Cannot read properties of undefined (reading 'getRawIndex')
onEvents,
}: BaseEChartProps) => {
const style = useMemo(() => ({ height }), [height]);
return (
<div className={className}>
<ReactECharts option={option} style={style} notMerge={notMerge} lazyUpdate={lazyUpdate} onEvents={onEvents} />

View File

@@ -1,9 +1,22 @@
import {ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, SignStyle} from "@/components/lge-dashboard";
import {BannerKey, ServerBannerRow} from "@/types/lg";
import {formatRowLabel, wrapSampleRow} from "@/lib/lg-dashboard";
import {useMemo} from "react";
import {BANNER_GROUP, BANNER_KEY_MAP, GRID_Y_NOT_PADDING} from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import {
BANNER_GROUP,
BANNER_KEY_MAP,
GRID_Y_NOT_PADDING,
LAST_YEAR,
} from "@/const/lgConst";
import {parseNumber} from "@/lib/utils";
import {
buildHeader_DataColumn,
exportDashboardExcel,
Section
} from "@/lib/lg-export-excel";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {CategoryTargetData} from "@/config/filter.types";
type SectionSpec = {
@@ -37,6 +50,7 @@ const buildColumns = (spec: SectionSpec): DataColumn<ServerBannerRow>[] => {
key: "total",
header: "전체",
numeric: true,
headRowSpan: 2,
headerClassName: SEP_R,
cellClassName: SEP_R,
width: 80,
@@ -68,25 +82,27 @@ type BannerSummaryProps = {
};
const BannerSummary = ({ data, useChart }: BannerSummaryProps) => {
const {filterValue, registerExcelExporter } = useLayoutFilter();
const buildChartData = (rows: ServerBannerRow[], bannerKeys: BannerKey[]): ChartData => {
const categories = rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => formatRowLabel(r.rowLabel));
.map((r) => formatRowLabel(r.rowLabel))
.reverse();
const series = [
{
name:"전체",
data: rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => parseNumber(r.total) ?? null),
.map((r) => parseNumber(r.total) ?? null)
.reverse(),
}
];
return { categories, series };
};
const rows = useMemo<ServerBannerRow[]>(() => wrapSampleRow(data), [data]);
const signStyleGap: SignStyle<ServerBannerRow> = {
rowSelector: (row) => row.rowLabel === "gap",
display: "arrow",
@@ -95,31 +111,73 @@ const BannerSummary = ({ data, useChart }: BannerSummaryProps) => {
zeroText: "-",
};
const sectionRows = useMemo(() => {
return SECTIONS.map((spec) => {
const specTitle = spec.title;
const bannerKeys = getSectionBannerKeys(spec);
const columns = buildColumns(spec);
// rows가 spec마다 다르면 여기서 가져오도록 구성
const rows = wrapSampleRow(data);
const chartData = buildChartData(rows, bannerKeys);
return {
spec,
specTitle,
bannerKeys,
columns,
rows,
chartData,
};
});
}, [data]);
useEffect(() => {
registerExcelExporter(async (payload) => {
const targetString =filterValue.target === CategoryTargetData.PROFILE? "Profile" : "보급률 변화"
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_${targetString}`
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] =
sectionRows.map((sectionRow) => ({
title: sectionRow.specTitle,
header: buildHeader_DataColumn(sectionRow.columns),
rows: sectionRow.rows as AnyRow[],
rowGap: 1,
}))
;
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div className="flex flex-col gap-6">
{SECTIONS.map((spec) => {
const bannerKeys = getSectionBannerKeys(spec);
const columns = buildColumns(spec);
const chartData = buildChartData(rows, bannerKeys);
{sectionRows.map((sectionRow) => {
return (
useChart ?
<LeftChartTable<ServerBannerRow>
key={spec.title}
title={spec.title}
columns={columns}
rows={rows}
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
signStyle={signStyleGap}
chart={
<HorizontalBar
data={chartData}
data={sectionRow.chartData}
height="100%"
showFocusLabel="none"
legend={{ show: false }}
grid={GRID_Y_NOT_PADDING}
xAxis={{ type: "value", show: false }}
yAxis={{ type: "category", data: chartData.categories, show: false }}
yAxis={{ type: "category", data: sectionRow.chartData.categories, show: false }}
/>
}
chartCell={{ key: "total", startRowIndex: 1 }}
@@ -127,10 +185,10 @@ const BannerSummary = ({ data, useChart }: BannerSummaryProps) => {
/>
:
<DataTable<ServerBannerRow>
key={spec.title}
title={spec.title}
columns={columns}
rows={rows}
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
signStyle={signStyleGap}
/>
);

View File

@@ -7,7 +7,7 @@ import {
} from "@/components/lge-dashboard";
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
import {totalFilters} from "@/config/filter.data";
import {useMemo, useState} from "react";
import {useEffect, useMemo, useState} from "react";
import {BannerGroupKey, CategoryChartMode, ServerBannerRow} from "@/types/lg";
import {
buildRowLabelSeriesChartData,
@@ -17,6 +17,8 @@ import {
} from "@/lib/lg-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR} from "@/const/lgConst";
import {createDefaultGrid, createDefaultLegend, reverseCategories} from "@/lib/chart-options";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
type CategoryByDataProps = {
title?: string;
@@ -90,7 +92,7 @@ const CategoryByData = ({
return isBannerGroupKey(v) ? buildColumns(v) : [];
}, [selectedBanner.variable]);
const tableData = useMemo(() => wrapSampleRow(allTableData).filter((row) => row.year === LAST_YEAR), [allTableData, LAST_YEAR])
const tableData = useMemo(() => wrapSampleRow(allTableData).filter((row) => row.year === LAST_YEAR), [allTableData, LAST_YEAR]);
return (
<div>

View File

@@ -1,54 +1,13 @@
import GaugeCardTable from "./GaugeCardTable";
import {GaugeColumn} from "@/components/lge-dashboard";
import {useMemo} from "react";
import {apiLifeStageByProduct} from "@/config/sample.data";
import {LifeStageRow} from "@/types/lg";
import {asNum, norm} from "@/lib/utils";
import {LIFE_STAGE_COLUMNS} from "@/const/lgConst";
import {LifeStageGroup} from "@/types/lg";
const LifeStageDiv = () => {
const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
{ key: "item", header: "", rowHead: true, renderLabel: (r) => r.item },
type lifeStageDivProps = {
lifeStageRowsByGroup:LifeStageGroup[];
}
{ key: "total", header: "전체", max: 100, align: "left", cellType:"number"},
{ key: "single", header: "미혼", max: 100 , align: "left"},
{ key: "noKids", header: "무자녀", group: "기혼", max: 100 , align: "left"},
{ key: "preschoolKids", header: "미취학", group: "기혼", max: 100 , align: "left"},
{ key: "schoolKids", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
{ key: "adultKids", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
{ key: "independentSenior", header: "독립\n시니어", max: 100 , align: "left"},
];
const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["냉장고", "세탁기", "건조기", "에어컨", "TV", "김치 냉장고", "식기세척기", "의류 관리기"] },
{ title: "소형가전 군", items: ["청소기", "공기 청정기", "정수기"] },
{ title: "신가전 군", items: ["로봇 청소기", "음식물처리기"] },
] as const;
const lifeStageRowsByGroup = useMemo(() => {
const pick = (label: string) => apiLifeStageByProduct.find((r) => norm(r.rowLabel) === norm(label));
return LIFE_STAGE_GROUPS.map((g) => {
const rows: LifeStageRow[] = g.items.map((label) => {
const r = pick(label);
return {
item: label,
total: asNum((r as any)?.total), // 서버에 all이 없으면 null로 남음
single: asNum((r as any)?.single),
noKids: asNum((r as any)?.noKids),
preschoolKids: asNum((r as any)?.preschoolKids),
schoolKids: asNum((r as any)?.schoolKids),
adultKids: asNum((r as any)?.adultKids),
independentSenior: asNum((r as any)?.independentSenior),
};
});
return { title: g.title, rows };
});
}, []);
const LifeStageDiv = ({lifeStageRowsByGroup}:lifeStageDivProps) => {
return (
<div className="mt-6">
<div className="flex justify-end gap-6 text-xs text-muted-foreground mb-2">

View File

@@ -1,18 +1,20 @@
'use client'
import {useMemo} from "react";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useEffect, useMemo} from "react";
import {CategoryByData} from "@/components/lge-dashboard";
import {apiBrandShareByYear} from "@/config/sample.data";
import {PageData, ServerBannerRow} from "@/types/lg";
import {buildGapRow} from "@/lib/lg-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const Brand = () => {
const { filterValue } = useLayoutFilter();
const {filterValue, registerExcelExporter} = useLayoutFilter();
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => {
const cleaned = apiBrandShareByYear.filter(
(r) => !(r.year === 26 && r.rowLabel === "gap")
(r) => !(r.year === LAST_YEAR && r.rowLabel === "gap")
);
const gapRow = buildGapRow(cleaned, 25, 26, "lg", "gap");
@@ -21,7 +23,7 @@ const Brand = () => {
if (gapRow) {
const insertIdx = cleaned.findIndex(
(r) => r.year === 26 && r.rowLabel === "lg"
(r) => r.year === LAST_YEAR && r.rowLabel === "lg"
);
if (insertIdx >= 0) {
@@ -42,6 +44,33 @@ const Brand = () => {
];
}, []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_브랜드`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -1,20 +1,50 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useMemo} from "react";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {apiOwnershipPathByYear, apiOwnershipTriggerByYear} from "@/config/sample.data";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const OwnershipPath = () => {
const { filterValue } = useLayoutFilter();
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{title: "보유 경로", chartMode:"reverseStack", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "보유 경로", chartMode:"reverseStack", data: apiOwnershipPathByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap"))},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_보유 경로`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -1,19 +1,49 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {apiOwnershipPathByYear, apiOwnershipTriggerByYear, apiPaymentMethodByYear} from "@/config/sample.data";
import {useMemo} from "react";
import {apiPaymentMethodByYear} from "@/config/sample.data";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const PaymentMethod = () => {
const { filterValue } = useLayoutFilter();
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{title: "구매 형식", chartMode:"reverseStack", data: apiPaymentMethodByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "구매 형식", chartMode:"reverseStack", data: apiPaymentMethodByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap"))},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_구매 형식`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -2,7 +2,7 @@
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import { useMemo } from "react";
import {useMemo} from "react";
import {ServerBannerRow} from "@/types/lg";
import {apiOwnershipSummary, apiPurchaseRateKpis} from "@/config/sample.data";

View File

@@ -1,20 +1,50 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useMemo} from "react";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import { apiOwnershipPathByYear, apiOwnershipTriggerByYear} from "@/config/sample.data";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const PurchaseBehavior = () => {
const { filterValue } = useLayoutFilter();
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{title: "보유 경로", chartMode:"horizontal", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "보유 경로", chartMode:"horizontal", data: apiOwnershipPathByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap"))},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_구입 행태`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -2,33 +2,61 @@
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {
apiOwnershipPathByYear,
apiOwnershipTriggerByYear,
apiPurchaseChannelByYear,
apiPurchaseChannelSummaryByYear
} from "@/config/sample.data";
import {useMemo} from "react";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const PurchaseChannel = () => {
const { filterValue } = useLayoutFilter();
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{
title: "구매 채널(온/오프라인)",
chartMode: "reverseStack",
data: apiPurchaseChannelSummaryByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")),
data: apiPurchaseChannelSummaryByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap")),
},
{
title: "구매 채널(상세)",
chartMode: "horizontal",
data: apiPurchaseChannelByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")),
data: apiPurchaseChannelByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap")),
chartHeight: 550,
},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_구매 채널`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -1,23 +1,53 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useMemo} from "react";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {apiFridgeDoorTypeByYear} from "@/config/sample.data";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const TypeSpec = () => {
const { filterValue } = useLayoutFilter();
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{
title: "타입",
chartMode: "horizontal",
data: apiFridgeDoorTypeByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")),
data: apiFridgeDoorTypeByYear.filter(r => !(r.year === LAST_YEAR && r.rowLabel === "gap")),
},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_타입/스펙`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `20${LAST_YEAR}년도 가전 보급률 Dashboard(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
return (
<div>
{tableDataArray.map((tableData) => (

View File

@@ -1,6 +1,6 @@
"use client";
import { useMemo } from "react";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import {GaugeColumn} from "../types";
@@ -37,23 +37,47 @@ const GaugeTable = <T extends Record<string, unknown>>({
cellHeight = 26,
valueFormatter,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group);
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
const groupCells = useMemo(() => {
if (!hasGroup) return [];
const res: { label: string; span: number }[] = [];
type GroupCell =
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
if (!hasGroup) return [] as GroupCell[];
const res: GroupCell[] = [];
let i = 0;
while (i < columns.length) {
const g = columns[i].group ?? "";
const c = columns[i];
if (c.headRowSpan === 2) {
res.push({ kind: "rowspan", label: c.header, colSpan: 1, rowSpan: 2 });
i++;
continue;
}
const g = c.group;
if (!g) {
// group 미지정: 1칸짜리 blank group 셀
res.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1 });
i++;
continue;
}
// 같은 group 연속 구간 colSpan
let span = 1;
let j = i + 1;
while (j < columns.length && (columns[j].group ?? "") === g) {
while (j < columns.length && columns[j].headRowSpan !== 2 && columns[j].group === g) {
span++;
j++;
}
res.push({ label: g, span });
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1 });
i = j;
}
return res;
}, [columns, hasGroup]);
@@ -80,14 +104,19 @@ const GaugeTable = <T extends Record<string, unknown>>({
{hasGroup && (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<th key={`${g.label}-${idx}`} colSpan={g.span}>
<th
key={`${g.kind}-${g.label}-${idx}`}
colSpan={g.colSpan}
rowSpan={g.rowSpan}
className={g.className}
>
{g.label}
</th>
))}
</tr>
)}
<tr className={hasGroup ? "lg-table__subhead" : undefined}>
{columns.map((c) => (
{columns.filter((c) => c.headRowSpan !== 2).map((c) => (
<th key={String(c.key)}>
{c.header}
</th>
@@ -104,8 +133,8 @@ const GaugeTable = <T extends Record<string, unknown>>({
if (c.rowHead) {
const raw = row[c.key];
const label = c.renderLabel
? c.renderLabel(row)
const label = c.render
? c.render(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"

View File

@@ -34,7 +34,7 @@ export type GroupedStackBarData = {
export type GroupedOverlayBarData = {
categories: string[]; // 제품
years: number[]; // 예: [24,25,26]
years: string[]; // 예: [24,25,26]
totalName?: string; // default: "전체"
focusName?: string; // default: "LG"
total: Array<Array<number | null>>; // [yearIndex][categoryIndex]
@@ -76,10 +76,13 @@ export type GaugeColumn<T> = {
width?: number | string;
align?: "left" | "center" | "right";
group?: string;
groupKey?:string;// 2단 헤더 그룹
headRowSpan?: 1 | 2;
rowHead?: boolean;
/** 게이지 최대값 기준(기본 100) */
max?: number;
renderLabel?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
render?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
cellType?: "gauge" | "number"; // default: "gauge"
};

View File

@@ -32,24 +32,24 @@ const randInt = (r: () => number, min: number, max: number) =>
type RandRange = { min: number | null; max: number | null };
const makeProductDist = (seedKey: string, range?: RandRange): Record<ProductKey, number> => {
const makeProductDist = (seedKey: string, range?: RandRange): Record<ProductKey, string> => {
const min = range?.min ?? 1;
const max = range?.max ?? 60;
const seed = (hash32(seedKey) ^ DUMMY_SEED) >>> 0;
const r = mulberry32(seed);
const out = {} as Record<ProductKey, number>;
for (const k of PRODUCT_KEYS) out[k] = randInt(r, min, max);
const out = {} as Record<ProductKey, string>;
for (const k of PRODUCT_KEYS) out[k] = String(randInt(r, min, max));
return out;
};
const productRow = (
year: number,
year: string,
rowLabel: string,
total: number,
total: string,
range: RandRange = { min: null, max: null },
extra?: Partial<Record<ProductKey, number>>,
extra?: Partial<Record<ProductKey, string>>,
): ServerProductRow => ({
year,
rowLabel,
@@ -64,33 +64,33 @@ const calcGapRow = (row26: ServerProductRow, row25: ServerProductRow): ServerPro
const out: ServerProductRow = {
year: row26.year,
rowLabel: "gap",
total: row26.total - row25.total,
total: String(Number(row26.total) - Number(row25.total)),
};
for (const k of PRODUCT_KEYS) {
const a = row26[k] ?? 0;
const b = row25[k] ?? 0;
out[k] = a - b;
const a = row26[k] ?? "0";
const b = row25[k] ?? "0";
out[k] = String(Number(a) - Number(b));
}
return out;
};
const calcCagrRow = (row24: ServerProductRow, row26: ServerProductRow): ServerProductRow => {
const years = 2; // 24 -> 26
const out: ServerProductRow = { year: row26.year, rowLabel: "CAGR", total: 0 };
const out: ServerProductRow = { year: row26.year, rowLabel: "CAGR", total: "0" };
// total은 참고용으로만: (26/24) CAGR %
out.total =
row24.total > 0 ? round1((Math.pow(row26.total / row24.total, 1 / years) - 1) * 100) : 0;
Number(row24.total) > 0 ? String(round1((Math.pow(Number(row26.total) / Number(row24.total), 1 / years) - 1) * 100)) : "0";
for (const k of PRODUCT_KEYS) {
const v24 = row24[k] ?? 0;
const v26 = row26[k] ?? 0;
out[k] = v24 > 0 ? round1((Math.pow(v26 / v24, 1 / years) - 1) * 100) : 0;
const v24 = row24[k] ?? "0";
const v26 = row26[k] ?? "0";
out[k] = Number(v24) > 0 ? String(round1((Math.pow(Number(v26) / Number(v24), 1 / years) - 1) * 100)) : "0";
}
return out;
};
const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number): number[] => {
const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number): string[] => {
// 불가능한 범위 방어
const minSum = n * minEach;
const maxSum = n * maxEach;
@@ -151,7 +151,7 @@ const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number
// 마지막 보정(이론상 거의 안 탐)
out[n - 1] += 100 - sum;
}
return out;
return out.map((o) => String(o));
};
const BANNER_GROUPS: Record<string, BannerKey[]> = {
@@ -173,14 +173,14 @@ const BANNER_GROUPS: Record<string, BannerKey[]> = {
};
/** ✅ 기존 상수 대신: 호출할 때마다 “결정적 랜덤” 분포 생성 */
export const makeBannerDistDefault = (seedKey: string, range?: RandRange): Record<BannerKey, number> => {
export const makeBannerDistDefault = (seedKey: string, range?: RandRange): Record<BannerKey, string> => {
const seed = (hash32(seedKey) ^ DUMMY_SEED) >>> 0;
const r = mulberry32(seed);
const minEach = range?.min ?? 1;
const maxEach = range?.max ?? 60;
const out = {} as Record<BannerKey, number>;
const out = {} as Record<BannerKey, string>;
(Object.keys(BANNER_GROUPS) as Array<keyof typeof BANNER_GROUPS>).forEach((groupName) => {
const keys = BANNER_GROUPS[groupName];
@@ -192,11 +192,11 @@ export const makeBannerDistDefault = (seedKey: string, range?: RandRange): Recor
};
export const bannerRow = (
year: number,
year: string,
rowLabel: string,
total: number,
total: string,
range: RandRange = { min: null, max: null },
extra?: Partial<Record<BannerKey, number>>,
extra?: Partial<Record<BannerKey, string>>,
): ServerBannerRow => ({
year,
rowLabel,
@@ -205,9 +205,9 @@ export const bannerRow = (
...(extra ?? {}),
});
const TREND_24: ServerProductRow = productRow(24, "24년", 45, {min:70, max:99});
const TREND_25: ServerProductRow = productRow(25, "25년", 46, {min:70, max:99});
const TREND_26: ServerProductRow = productRow(26, "26년", 48, {min:70, max:99});
const TREND_24: ServerProductRow = productRow("24", "24년", "45", {min:70, max:99});
const TREND_25: ServerProductRow = productRow("25", "25년", "46", {min:70, max:99});
const TREND_26: ServerProductRow = productRow("26", "26년", "48", {min:70, max:99});
export const apiTrendCategories: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
@@ -218,22 +218,22 @@ export const apiTrendCategories: ServerProductRow[] = [
];
export const apiBrandByYearCategories: ServerProductRow[] = [
productRow(24, "LG", 1200),
productRow(24, "Samsung", 1300),
productRow(24, "Cbrand", 600),
productRow("24", "LG", "1200"),
productRow("24", "Samsung", "1300"),
productRow("24", "Cbrand", "600"),
productRow(25, "LG", 1250),
productRow(25, "Samsung", 1320),
productRow(25, "Cbrand", 620),
productRow("25", "LG", "1250"),
productRow("25", "Samsung", "1320"),
productRow("25", "Cbrand", "620"),
productRow(26, "LG", 1280),
productRow(26, "Samsung", 1340),
productRow(26, "Cbrand", 640),
productRow("26", "LG", "1280"),
productRow("26", "Samsung", "1340"),
productRow("26", "Cbrand", "640"),
];
const OWN_PEN_24: ServerProductRow = productRow(24, "24년", 45);
const OWN_PEN_25: ServerProductRow = productRow(25, "25년", 46);
const OWN_PEN_26: ServerProductRow = productRow(26, "26년", 48);
const OWN_PEN_24: ServerProductRow = productRow("24", "24년", "45");
const OWN_PEN_25: ServerProductRow = productRow("25", "25년", "46");
const OWN_PEN_26: ServerProductRow = productRow("26", "26년", "48");
export const apiOwnShareOfTotalPenetration: ServerProductRow[] = [
calcGapRow(OWN_PEN_26, OWN_PEN_25),
@@ -242,9 +242,9 @@ export const apiOwnShareOfTotalPenetration: ServerProductRow[] = [
OWN_PEN_26,
];
const BUY_24: ServerProductRow = productRow(24, "24년", 45, {min:20, max:40});
const BUY_25: ServerProductRow = productRow(25, "25년", 46, {min:20, max:40});
const BUY_26: ServerProductRow = productRow(26, "26년", 48, {min:20, max:40});
const BUY_24: ServerProductRow = productRow("24", "24년", "45", {min:20, max:40});
const BUY_25: ServerProductRow = productRow("25", "25년", "46", {min:20, max:40});
const BUY_26: ServerProductRow = productRow("26", "26년", "48", {min:20, max:40});
export const apiTrendBuy: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
BUY_24,
@@ -252,34 +252,34 @@ export const apiTrendBuy: ServerProductRow[] = [
BUY_26,
];
const OWN_BUY_24: ServerProductRow = productRow(24, "24년", 41, {min:5, max:20});
const OWN_BUY_25: ServerProductRow = productRow(25, "25년", 42, {min:5, max:20});
const OWN_BUY_26: ServerProductRow = productRow(26, "26년", 43, {min:5, max:20});
const OWN_BUY_24: ServerProductRow = productRow("24", "24년", "41", {min:5, max:20});
const OWN_BUY_25: ServerProductRow = productRow("25", "25년", "42", {min:5, max:20});
const OWN_BUY_26: ServerProductRow = productRow("26", "26년", "43", {min:5, max:20});
export const apiOwnShareOfTotalPurchase: ServerProductRow[] = [
calcGapRow(OWN_BUY_26, OWN_BUY_25),
productRow(26, "전체 구입율 중 자사제품 비율", 46),
productRow("26", "전체 구입율 중 자사제품 비율", "46"),
OWN_BUY_24,
OWN_BUY_25,
OWN_BUY_26,
];
export const apiLifeStageByProduct: ServerBannerRow[] = [
bannerRow(26, "냉장고", 97, {min:10, max:99}),
bannerRow(26, "세탁기", 94, {min:10, max:99}),
bannerRow(26, "에어컨", 90, {min:10, max:99}),
bannerRow(26, "건조기", 38, {min:10, max:99}),
bannerRow(26, "TV", 86, {min:10, max:99}),
bannerRow(26, "김치 냉장고", 56, {min:10, max:99}),
bannerRow(26, "식기세척기", 18, {min:10, max:99}),
bannerRow(26, "의류 관리기", 13, {min:10, max:99}),
bannerRow("26", "냉장고", "97", {min:10, max:99}),
bannerRow("26", "세탁기", "94", {min:10, max:99}),
bannerRow("26", "에어컨", "90", {min:10, max:99}),
bannerRow("26", "건조기", "38", {min:10, max:99}),
bannerRow("26", "TV", "86", {min:10, max:99}),
bannerRow("26", "김치 냉장고", "56", {min:10, max:99}),
bannerRow("26", "식기세척기", "18", {min:10, max:99}),
bannerRow("26", "의류 관리기", "13", {min:10, max:99}),
bannerRow(26, "청소기", 78, {min:10, max:99}),
bannerRow(26, "공기 청정기", 52, {min:10, max:99}),
bannerRow(26, "정수기", 42, {min:10, max:99}),
bannerRow("26", "청소기", "78", {min:10, max:99}),
bannerRow("26", "공기 청정기", "52", {min:10, max:99}),
bannerRow("26", "정수기", "42", {min:10, max:99}),
bannerRow(26, "로봇 청소기", 22, {min:10, max:99}),
bannerRow(26, "음식물처리기", 26, {min:10, max:99}),
bannerRow("26", "로봇 청소기", "22", {min:10, max:99}),
bannerRow("26", "음식물처리기", "26", {min:10, max:99}),
];
/** ---------------------------
@@ -288,10 +288,10 @@ export const apiLifeStageByProduct: ServerBannerRow[] = [
* 26 사례수 / 보유율 / gap / 보유대수
* -------------------------- */
export const apiOwnershipSummary: ServerBannerRow[] = [
bannerRow(26, "사례수", 2000),
bannerRow(26, "보유율", 85),
bannerRow(26, "gap", 1), // 26-25
bannerRow(26, "보유대수", 1.2),
bannerRow("26", "사례수", "2000"),
bannerRow("26", "보유율", "85"),
bannerRow("26", "gap", "1"), // 26-25
bannerRow("26", "보유대수", "1.2"),
];
/** ---------------------------
@@ -303,10 +303,10 @@ export const apiOwnershipSummary: ServerBannerRow[] = [
* 24 24
* -------------------------- */
export const apiYearIndex: ServerBannerRow[] = [
bannerRow(26, "사례수", 2000),
bannerRow(26, "26", 15),
bannerRow(25, "25", 14),
bannerRow(24, "24", 13),
bannerRow("26", "사례수", "2000"),
bannerRow("26", "26", "15"),
bannerRow("25", "25", "14"),
bannerRow("24", "24", "13"),
];
/** ---------------------------
@@ -315,21 +315,21 @@ export const apiYearIndex: ServerBannerRow[] = [
* 25/26 사례수 + 브랜드
* -------------------------- */
export const apiBrandShareByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 500),
bannerRow(25, "lg", 48),
bannerRow(25, "삼성", 40),
bannerRow(25, "위니아", 4),
bannerRow(25, "캐리어", 3),
bannerRow(25, "하이얼", 1),
bannerRow(25, "기타", 4),
bannerRow("25", "사례수", "500"),
bannerRow("25", "lg", "48"),
bannerRow("25", "삼성", "40"),
bannerRow("25", "위니아", "4"),
bannerRow("25", "캐리어", "3"),
bannerRow("25", "하이얼", "1"),
bannerRow("25", "기타", "4"),
bannerRow(26, "사례수", 520),
bannerRow(26, "lg", 47),
bannerRow(26, "삼성", 40),
bannerRow(26, "위니아", 5),
bannerRow(26, "캐리어", 3),
bannerRow(26, "하이얼", 1),
bannerRow(26, "기타", 4),
bannerRow("26", "사례수", "520"),
bannerRow("26", "lg", "47"),
bannerRow("26", "삼성", "40"),
bannerRow("26", "위니아", "5"),
bannerRow("26", "캐리어", "3"),
bannerRow("26", "하이얼", "1"),
bannerRow("26", "기타", "4"),
];
/** ---------------------------
@@ -338,21 +338,21 @@ export const apiBrandShareByYear: ServerBannerRow[] = [
* 25/26 사례수 + 도어 타입
* -------------------------- */
export const apiFridgeDoorTypeByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 480),
bannerRow(25, "1도어", 5),
bannerRow(25, "2도어 상 냉동+하 냉장", 22),
bannerRow(25, "2도어 상 냉장+하 냉동", 8),
bannerRow(25, "2도어 양문형", 36),
bannerRow(25, "4도어", 28),
bannerRow(25, "기타", 1),
bannerRow("25", "사례수", "480"),
bannerRow("25", "1도어", "5"),
bannerRow("25", "2도어 상 냉동+하 냉장", "22"),
bannerRow("25", "2도어 상 냉장+하 냉동", "8"),
bannerRow("25", "2도어 양문형", "36"),
bannerRow("25", "4도어", "28"),
bannerRow("25", "기타", "1"),
bannerRow(26, "사례수", 500),
bannerRow(26, "1도어", 5),
bannerRow(26, "2도어 상 냉동+하 냉장", 23),
bannerRow(26, "2도어 상 냉장+하 냉동", 12),
bannerRow(26, "2도어 양문형", 35),
bannerRow(26, "4도어", 25),
bannerRow(26, "기타", 0),
bannerRow("26", "사례수", "500"),
bannerRow("26", "1도어", "5"),
bannerRow("26", "2도어 상 냉동+하 냉장", "23"),
bannerRow("26", "2도어 상 냉장+하 냉동", "12"),
bannerRow("26", "2도어 양문형", "35"),
bannerRow("26", "4도어", "25"),
bannerRow("26", "기타", "0"),
];
/** ---------------------------
@@ -361,41 +361,41 @@ export const apiFridgeDoorTypeByYear: ServerBannerRow[] = [
* 25/26 사례수 + 보유 경로(구매 경로)
* -------------------------- */
export const apiOwnershipPathByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 520),
bannerRow(25, "신규 구입", 8),
bannerRow(25, "기존 제품 작동하나 신규 구입", 4),
bannerRow(25, "기존 제품 고장으로 신규 구입", 40),
bannerRow(25, "추가 구입", 48),
bannerRow("25", "사례수", "520"),
bannerRow("25", "신규 구입", "8"),
bannerRow("25", "기존 제품 작동하나 신규 구입", "4"),
bannerRow("25", "기존 제품 고장으로 신규 구입", "40"),
bannerRow("25", "추가 구입", "48"),
bannerRow(26, "사례수", 540),
bannerRow(26, "신규 구입", 8),
bannerRow(26, "기존 제품 작동하나 신규 구입", 4),
bannerRow(26, "기존 제품 고장으로 신규 구입", 40),
bannerRow(26, "추가 구입", 48),
bannerRow("26", "사례수", "540"),
bannerRow("26", "신규 구입", "8"),
bannerRow("26", "기존 제품 작동하나 신규 구입", "4"),
bannerRow("26", "기존 제품 고장으로 신규 구입", "40"),
bannerRow("26", "추가 구입", "48"),
];
export const apiOwnershipTriggerByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 520),
bannerRow(25, "오래되어 새로운 제품 교체 필요", 23),
bannerRow(25, "이사로 인해 새로 구입", 22),
bannerRow(25, "이전 제품 고장으로 새로 구입", 17),
bannerRow(25, "새로운 기능/기술 사용하고 싶어서", 14),
bannerRow(25, "리모델링, 인테리어 계기로 새로 구입", 7),
bannerRow(25, "혼수로 장만", 7),
bannerRow(25, "(결혼 외) 가구 분가/독립하게 되어서", 6),
bannerRow(25, "가구 구성원이 늘어서", 3),
bannerRow(25, "가구 구성원이 줄어서", 2),
bannerRow("25", "사례수", "520"),
bannerRow("25", "오래되어 새로운 제품 교체 필요", "23"),
bannerRow("25", "이사로 인해 새로 구입", "22"),
bannerRow("25", "이전 제품 고장으로 새로 구입", "17"),
bannerRow("25", "새로운 기능/기술 사용하고 싶어서", "14"),
bannerRow("25", "리모델링, 인테리어 계기로 새로 구입", "7"),
bannerRow("25", "혼수로 장만", "7"),
bannerRow("25", "(결혼 외) 가구 분가/독립하게 되어서", "6"),
bannerRow("25", "가구 구성원이 늘어서", "3"),
bannerRow("25", "가구 구성원이 줄어서", '2'),
bannerRow(26, "사례수", 540),
bannerRow(26, "오래되어 새로운 제품 교체 필요", 23),
bannerRow(26, "이사로 인해 새로 구입", 22),
bannerRow(26, "이전 제품 고장으로 새로 구입", 17),
bannerRow(26, "새로운 기능/기술 사용하고 싶어서", 14),
bannerRow(26, "리모델링, 인테리어 계기로 새로 구입", 7),
bannerRow(26, "혼수로 장만", 7),
bannerRow(26, "(결혼 외) 가구 분가/독립하게 되어서", 6),
bannerRow(26, "가구 구성원이 늘어서", 3),
bannerRow(26, "가구 구성원이 줄어서", 2),
bannerRow("26", "사례수", "540"),
bannerRow("26", "오래되어 새로운 제품 교체 필요", "23"),
bannerRow("26", "이사로 인해 새로 구입", "22"),
bannerRow("26", "이전 제품 고장으로 새로 구입", "17"),
bannerRow("26", "새로운 기능/기술 사용하고 싶어서", "14"),
bannerRow("26", "리모델링, 인테리어 계기로 새로 구입", "7"),
bannerRow("26", "혼수로 장만", "7"),
bannerRow("26", "(결혼 외) 가구 분가/독립하게 되어서", "6"),
bannerRow("26", "가구 구성원이 늘어서", "3"),
bannerRow("26", "가구 구성원이 줄어서", "2"),
];
/** ---------------------------
@@ -404,15 +404,15 @@ export const apiOwnershipTriggerByYear: ServerBannerRow[] = [
* 25/26 결제수단
* -------------------------- */
export const apiPaymentMethodByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 650),
bannerRow(25, "일시불", 60),
bannerRow(25, "할부", 30),
bannerRow(25, "렌탈", 10),
bannerRow("25", "사례수", "650"),
bannerRow("25", "일시불", "60"),
bannerRow("25", "할부", "30"),
bannerRow("25", "렌탈", "10"),
bannerRow(26, "사례수", 650),
bannerRow(26, "일시불", 58),
bannerRow(26, "할부", 32),
bannerRow(26, "렌탈", 10),
bannerRow("26", "사례수", "650"),
bannerRow("26", "일시불", "58"),
bannerRow("26", "할부", "32"),
bannerRow("26", "렌탈", "10"),
];
/** ---------------------------
@@ -421,19 +421,19 @@ export const apiPaymentMethodByYear: ServerBannerRow[] = [
* 26 사례수 / 구매율 / gap
* -------------------------- */
export const apiPurchaseRateKpis: ServerBannerRow[] = [
bannerRow(26, "사례수", 700),
bannerRow(26, "구매율", 35),
bannerRow(26, "gap", 2), // 26-25
bannerRow("26", "사례수", "700"),
bannerRow("26", "구매율", "35"),
bannerRow("26", "gap", "2"), // 26-25
];
export const apiPurchaseChannelSummaryByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 650),
bannerRow(25, "오프라인", 60),
bannerRow(25, "온라인/홈쇼핑", 40),
bannerRow("25", "사례수", "650"),
bannerRow("25", "오프라인", "60"),
bannerRow("25", "온라인/홈쇼핑", "40"),
bannerRow(26, "사례수", 650),
bannerRow(26, "오프라인", 59),
bannerRow(26, "온라인/홈쇼핑", 41),
bannerRow("26", "사례수", "650"),
bannerRow("26", "오프라인", "59"),
bannerRow("26", "온라인/홈쇼핑", "41"),
]
/** ---------------------------
@@ -442,33 +442,33 @@ export const apiPurchaseChannelSummaryByYear: ServerBannerRow[] = [
* 25/26 사례수 + 유통채널
* -------------------------- */
export const apiPurchaseChannelByYear: ServerBannerRow[] = [
bannerRow(25, "사례수", 650),
bannerRow(25, "오프라인 단독 매장", 25),
bannerRow(25, "전자제품 양판점", 20),
bannerRow(25, "대형할인점", 10),
bannerRow(25, "백화점", 5),
bannerRow(25, "오픈마켓", 15),
bannerRow(25, "제조사 공식 홈페이지", 8),
bannerRow(25, "포털 쇼핑채널 입점몰", 4),
bannerRow(25, "백화점 기반 쇼핑몰", 2),
bannerRow(25, "TV 홈쇼핑", 3),
bannerRow(25, "유통사 온라인 쇼핑몰", 4),
bannerRow(25, "라이프스타일 쇼핑몰", 2),
bannerRow(25, "해외 직구/대행 사이트", 1),
bannerRow(25, "중고거래 사이트", 1),
bannerRow("25", "사례수", "650"),
bannerRow("25", "오프라인 단독 매장", "25"),
bannerRow("25", "전자제품 양판점", "20"),
bannerRow("25", "대형할인점", "10"),
bannerRow("25", "백화점", "5"),
bannerRow("25", "오픈마켓", "15"),
bannerRow("25", "제조사 공식 홈페이지", "8"),
bannerRow("25", "포털 쇼핑채널 입점몰", "4"),
bannerRow("25", "백화점 기반 쇼핑몰", "2"),
bannerRow("25", "TV 홈쇼핑", "3"),
bannerRow("25", "유통사 온라인 쇼핑몰", "4"),
bannerRow("25", "라이프스타일 쇼핑몰", "2"),
bannerRow("25", "해외 직구/대행 사이트", "1"),
bannerRow("25", "중고거래 사이트", "1"),
bannerRow(26, "사례수", 680),
bannerRow(26, "오프라인 단독 매장", 24),
bannerRow(26, "전자제품 양판점", 20),
bannerRow(26, "대형할인점", 10),
bannerRow(26, "백화점", 5),
bannerRow(26, "오픈마켓", 16),
bannerRow(26, "제조사 공식 홈페이지", 9),
bannerRow(26, "포털 쇼핑채널 입점몰", 4),
bannerRow(26, "백화점 기반 쇼핑몰", 2),
bannerRow(26, "TV 홈쇼핑", 3),
bannerRow(26, "유통사 온라인 쇼핑몰", 3),
bannerRow(26, "라이프스타일 쇼핑몰", 2),
bannerRow(26, "해외 직구/대행 사이트", 1),
bannerRow(26, "중고거래 사이트", 1),
bannerRow("26", "사례수", "680"),
bannerRow("26", "오프라인 단독 매장", "24"),
bannerRow("26", "전자제품 양판점", "20"),
bannerRow("26", "대형할인점", "10"),
bannerRow("26", "백화점", "5"),
bannerRow("26", "오픈마켓", "16"),
bannerRow("26", "제조사 공식 홈페이지", "9"),
bannerRow("26", "포털 쇼핑채널 입점몰", "4"),
bannerRow("26", "백화점 기반 쇼핑몰", "2"),
bannerRow("26", "TV 홈쇼핑", "3"),
bannerRow("26", "유통사 온라인 쇼핑몰", "3"),
bannerRow("26", "라이프스타일 쇼핑몰", "2"),
bannerRow("26", "해외 직구/대행 사이트", "1"),
bannerRow("26", "중고거래 사이트", "1"),
];

View File

@@ -1,4 +1,5 @@
import {BannerKey} from "@/types/lg";
import {BannerKey, LifeStageRow} from "@/types/lg";
import {GaugeColumn} from "@/components/lge-dashboard";
export const PRODUCT_KEY_MAP = {
washingMachine: "세탁기",
@@ -91,9 +92,29 @@ export const BANNER_KEY_MAP = {
income900Plus: "900만원 이상",
} as const;
export const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
{ key: "item", header: "", headRowSpan:2, rowHead: true, render: (r) => r.item },
{ key: "total", header: "전체", headRowSpan:2, max: 100, align: "left", cellType:"number"},
{ key: "single", header: "미혼", max: 100 , align: "left"},
{ key: "noKids", header: "무자녀", group: "기혼", max: 100 , align: "left"},
{ key: "preschoolKids", header: "미취학", group: "기혼", max: 100 , align: "left"},
{ key: "schoolKids", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
{ key: "adultKids", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
{ key: "independentSenior", header: "독립\n시니어", max: 100 , align: "left"},
];
export const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["냉장고", "세탁기", "건조기", "에어컨", "TV", "김치 냉장고", "식기세척기", "의류 관리기"] },
{ title: "소형가전 군", items: ["청소기", "공기 청정기", "정수기"] },
{ title: "신가전 군", items: ["로봇 청소기", "음식물처리기"] },
] as const;
export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array<keyof typeof PRODUCT_KEY_MAP>;
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
export const YEARS = [24, 25, 26];
export const YEARS = ["24", "25", "26"];
export const LAST_YEAR = YEARS.at(-1);
export const BRAND_LIST = ['Cbrand', 'Samsung', 'LG'];

View File

@@ -174,7 +174,7 @@ type Opts = {
/** 기본: ["사례수", "gap"] 제외 */
excludeRowLabels?: string[];
/** 기본: (y) => `${y}년` */
yearLabel?: (y: number) => string;
yearLabel?: (y: string) => string;
/** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */
splitStackByYear?: boolean;
};
@@ -186,7 +186,7 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
splitStackByYear = false,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
// rowLabel 순서: 첫 연도 기준으로 고정(없으면 전체 unique)
const baseYear = years[0];
@@ -203,7 +203,7 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
);
// 빠른 조회용: year -> (rowLabel -> total)
const map = new Map<number, Map<string, number>>();
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;
@@ -229,7 +229,7 @@ export function buildRowLabelSeriesChartData(
yearLabel = (y) => `${y}년`,
} = opts;
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b);
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];
@@ -246,7 +246,7 @@ export function buildRowLabelSeriesChartData(
);
// (year -> (rowLabel -> total)) 맵
const valueMap = new Map<number, Map<string, number>>();
const valueMap = new Map<string, Map<string, number>>();
for (const y of years) valueMap.set(y, new Map());
for (const r of rows) {
@@ -270,14 +270,14 @@ export const buildGapRow = (
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);
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: ServerBannerRow = {
year: curYear,
year: String(curYear),
rowLabel: gapRowLabel,
total: (typeof cur.total === "number" ? cur.total : 0) - (typeof prev.total === "number" ? prev.total : 0),
total: String(Number(cur.total) - Number(prev.total)),
};
// cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산
@@ -287,10 +287,7 @@ export const buildGapRow = (
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);
(gap as any)[k] = String(Number(vCur) - Number(vPrev));
});
return gap;

831
src/lib/lg-export-excel.ts Normal file
View File

@@ -0,0 +1,831 @@
// exportDashboardExcel.ts
"use client";
import {formatRowLabel, isSampleRow} from "@/lib/lg-dashboard";
import {DataColumn} from "@/components/lge-dashboard";
/**
* 요구사항:
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더(그룹 머지), (3) BANNER_GROUP 헤더(좌측 2칸 rowspan2 + 그룹 머지)
* - Excel export (한 시트, 섹션 간 1행 띄움)
* - 헤더 스타일:
* group: background = --lg-gray-400
* header: background = --lg-gray-600
* font: #fff, bold
*/
type HeaderStyleKey = "group" | "header";
type HeaderCell = {
text: string;
styleKey: HeaderStyleKey;
rowSpan?: number; // default 1
colSpan?: number; // default 1
align?: "left" | "center" | "right";
};
type HeaderBlock = {
headerRows: HeaderCell[][];
leafKeys: string[]; // 실제 데이터 컬럼 key 순서(좌->우)
totalCols: number;
};
export type Section<T extends Record<string, any>> = {
title?: string;
header: HeaderBlock;
rows: T[];
rowGap?: number; // default 1
// 옵션
colWidthByKey?: Record<string, number>;
numFmtByKey?: Record<string, string>; // 예: "#,##0", "0.0", "0%"
alignByKey?: Record<string, "left" | "center" | "right">;
valueGetter?: (row: T, key: string) => any;
};
type ExportOptions<T extends Record<string, any>> = {
fileName?: string;
sheetName?: string;
sections: Section<T>[];
// CSS 변수(없으면 기본값)
groupBgVar?: string; // default "--lg-gray-400"
headerBgVar?: string; // default "--lg-gray-600"
borderVar?: string; // default "--lg-gray-300"
};
/* =========================================================
* 0) Object.entries 타입 보존
* ========================================================= */
const typedEntries = <T extends Record<string, any>>(obj: T) =>
Object.entries(obj) as Array<[keyof T, T[keyof T]]>;
/* =========================================================
* 1) CSS var -> Excel ARGB (HSL 토큰 "H S% L%" 지원)
* ========================================================= */
type RGB = { r: number; g: number; b: number };
function clamp255(n: number) {
return Math.max(0, Math.min(255, Math.round(n)));
}
function hslTokenToRgb(token: string): RGB | null {
const m = token.trim().match(/^([\d.]+)\s+([\d.]+)%\s+([\d.]+)%$/);
if (!m) return null;
const h = parseFloat(m[1]) % 360;
const s = parseFloat(m[2]) / 100;
const l = parseFloat(m[3]) / 100;
const C = (1 - Math.abs(2 * l - 1)) * s;
const hh = h / 60;
const X = C * (1 - Math.abs((hh % 2) - 1));
let r1 = 0, g1 = 0, b1 = 0;
if (0 <= hh && hh < 1) [r1, g1, b1] = [C, X, 0];
else if (1 <= hh && hh < 2) [r1, g1, b1] = [X, C, 0];
else if (2 <= hh && hh < 3) [r1, g1, b1] = [0, C, X];
else if (3 <= hh && hh < 4) [r1, g1, b1] = [0, X, C];
else if (4 <= hh && hh < 5) [r1, g1, b1] = [X, 0, C];
else if (5 <= hh && hh < 6) [r1, g1, b1] = [C, 0, X];
const m2 = l - C / 2;
return {
r: clamp255((r1 + m2) * 255),
g: clamp255((g1 + m2) * 255),
b: clamp255((b1 + m2) * 255),
};
}
function hexToRgb(hex: string): RGB | null {
const v = hex.trim();
if (!v.startsWith("#")) return null;
const h = v.slice(1);
const full = h.length === 3 ? h.split("").map((c) => c + c).join("") : h;
if (full.length !== 6) return null;
return {
r: parseInt(full.slice(0, 2), 16),
g: parseInt(full.slice(2, 4), 16),
b: parseInt(full.slice(4, 6), 16),
};
}
function rgbToArgb(rgb: RGB) {
const toHex2 = (n: number) => n.toString(16).padStart(2, "0").toUpperCase();
return `FF${toHex2(rgb.r)}${toHex2(rgb.g)}${toHex2(rgb.b)}`;
}
function cssVarToExcelArgb(varName: string, fallbackHex = "#DDDDDD") {
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
const rgb = hslTokenToRgb(raw) ?? hexToRgb(raw) ?? hexToRgb(fallbackHex)!;
return rgbToArgb(rgb);
}
/* =========================================================
* 2) 헤더 렌더러 (row/col merge + 스타일)
* ========================================================= */
type StylePack = {
groupBg: string; // ARGB
headerBg: string; // ARGB
headerFont: string; // ARGB (white)
border: string; // ARGB
};
function writeMergedHeader(
ws: any, // ExcelJS.Worksheet
startRow: number,
headerRows: HeaderCell[][],
styles: StylePack
) {
const occupied = new Set<string>(); // "r,c" (0-based within header block)
const isOcc = (r: number, c: number) => occupied.has(`${r},${c}`);
const markOcc = (r: number, c: number) => occupied.add(`${r},${c}`);
const styleOf = (styleKey: HeaderStyleKey) => {
const bg = styleKey === "group" ? styles.groupBg : styles.headerBg;
return {
fill: { type: "pattern", pattern: "solid", fgColor: { argb: bg } },
font: { color: { argb: styles.headerFont }, bold: true },
alignment: { vertical: "middle", wrapText: true },
border: {
top: { style: "thin", color: { argb: styles.border } },
left: { style: "thin", color: { argb: styles.border } },
bottom: { style: "thin", color: { argb: styles.border } },
right: { style: "thin", color: { argb: styles.border } },
},
};
};
const applyStyleRange = (r1: number, c1: number, r2: number, c2: number, st: any) => {
for (let rr = r1; rr <= r2; rr++) {
const row = ws.getRow(rr);
for (let cc = c1; cc <= c2; cc++) {
const cell = row.getCell(cc);
cell.style = { ...(cell.style ?? {}), ...st };
}
}
};
for (let hr = 0; hr < headerRows.length; hr++) {
const rowCells = headerRows[hr];
let colCursor = 0;
for (const hc of rowCells) {
const rs = hc.rowSpan ?? 1;
const cs = hc.colSpan ?? 1;
while (isOcc(hr, colCursor)) colCursor++;
const topRow = startRow + hr;
const leftCol = colCursor + 1; // excel 1-based
const bottomRow = topRow + rs - 1;
const rightCol = leftCol + cs - 1;
const cell = ws.getRow(topRow).getCell(leftCol);
cell.value = hc.text;
const st = styleOf(hc.styleKey);
const horiz = hc.align ?? "center";
cell.alignment = { ...(st.alignment ?? {}), horizontal: horiz };
if (rs > 1 || cs > 1) ws.mergeCells(topRow, leftCol, bottomRow, rightCol);
applyStyleRange(topRow, leftCol, bottomRow, rightCol, {
...st,
alignment: { ...(st.alignment ?? {}), horizontal: horiz },
});
for (let r = hr; r < hr + rs; r++) {
for (let c = colCursor; c < colCursor + cs; c++) {
markOcc(r, c);
}
}
colCursor += cs;
}
ws.getRow(startRow + hr).height = 20;
}
return startRow + headerRows.length;
}
type AutoFitOpt = {
minColWidth?: number; // Excel column width units
maxColWidth?: number;
padding?: number; // width 여유(문자수 기준)
baseRowHeight?: number; // pt
maxRowHeight?: number; // pt
useCanvasMeasure?: boolean; // 브라우저에서 measureText로 더 정확하게
};
function autoFitApprox(ws: any, opt: AutoFitOpt = {}) {
const o: Required<AutoFitOpt> = {
minColWidth: opt.minColWidth ?? 8,
maxColWidth: opt.maxColWidth ?? 60,
padding: opt.padding ?? 2,
baseRowHeight: opt.baseRowHeight ?? 15,
maxRowHeight: opt.maxRowHeight ?? 120,
useCanvasMeasure: opt.useCanvasMeasure ?? true,
};
// 1) 머지 정보(내부 필드 사용: ExcelJS에서 공식 API가 없어서 근사 구현용)
const mergeMap = buildMergeMap(ws);
// 2) 컬럼 폭 먼저 계산
fitColumns(ws, mergeMap, o);
// 3) 그 다음 row height 계산 (wrapText/줄바꿈 고려)
fitRows(ws, mergeMap, o);
}
/* ---------------------------
* Column fit
* --------------------------- */
function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
const colCount = ws.columnCount ?? (ws.columns?.length ?? 0);
const widths = new Array<number>(colCount + 1).fill(o.minColWidth);
ws.eachRow({ includeEmpty: false }, (row: any) => {
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
const text = getCellText(cell);
if (!text) return;
// merged cell의 "master"만 처리 (중복 방지)
const masterAddr = getMasterAddress(cell);
const mi = mergeMap.get(masterAddr);
if (mi && cell.address !== masterAddr) return;
const w = estimateWidth(text, cell, o); // width in "excel-char-like units"
if (mi && mi.colSpan > 1) {
// 머지된 텍스트는 span만큼 나눠서 분배(머지 텍스트 때문에 한 컬럼이 과대해지는 현상 방지)
const perCol = w / mi.colSpan;
for (let c = mi.leftCol; c <= mi.rightCol; c++) {
widths[c] = Math.max(widths[c], perCol);
}
} else {
widths[colNumber] = Math.max(widths[colNumber], w);
}
});
});
for (let c = 1; c <= colCount; c++) {
const w = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
ws.getColumn(c).width = w;
}
}
/* ---------------------------
* Row fit
* --------------------------- */
function fitRows(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitOpt>) {
ws.eachRow({ includeEmpty: false }, (row: any) => {
let maxLines = 1;
row.eachCell({ includeEmpty: false }, (cell: any, colNumber: number) => {
const text = getCellText(cell);
if (!text) return;
const masterAddr = getMasterAddress(cell);
const mi = mergeMap.get(masterAddr);
if (mi && cell.address !== masterAddr) return;
const wrap = !!cell.alignment?.wrapText;
const explicitLines = text.split(/\r?\n/);
if (!wrap && explicitLines.length <= 1) return;
// 해당 셀의 사용 가능한 폭(머지면 합산)
const availableWidth = mi
? 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);
const needed = Math.max(1, Math.ceil(lineW / Math.max(1, availableWidth)));
cellLines += needed;
}
maxLines = Math.max(maxLines, cellLines);
});
const h = clamp(o.baseRowHeight * maxLines, o.baseRowHeight, o.maxRowHeight);
row.height = Math.max(row.height, h);
});
}
/* ---------------------------
* Width estimation
* --------------------------- */
function estimateWidth(text: string, cell: any, o: Required<AutoFitOpt>) {
// 줄바꿈이면 가장 긴 라인 기준(컬럼 폭은 max line)
const lines = text.split(/\r?\n/);
const maxLine = lines.reduce((m, s) => (s.length > m.length ? s : m), "");
if (o.useCanvasMeasure && typeof document !== "undefined") {
const px = measureTextPx(maxLine, cell);
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도가 근사치로 많이 씀
return px / 7;
}
// canvas 못 쓰는 환경(또는 성능 이유) -> 문자폭 가중치 근사
return estimateByCharWeight(maxLine);
}
function measureTextPx(text: string, cell: any) {
const canvas = getMeasureCanvas();
const ctx = canvas.getContext("2d")!;
const fontName = cell.font?.name ?? "Calibri";
const size = cell.font?.size ?? 11;
const bold = cell.font?.bold ? "bold " : "";
ctx.font = `${bold}${size}pt ${fontName}`;
return ctx.measureText(text).width;
}
let __canvas: HTMLCanvasElement | null = null;
function getMeasureCanvas() {
if (!__canvas) __canvas = document.createElement("canvas");
return __canvas;
}
// 한글/중국어/일본어 등 wide char 가중치 + 숫자/영문 가중치
function estimateByCharWeight(s: string) {
let w = 0;
for (const ch of s) {
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;
else w += 0.9;
}
return w;
}
function isWideChar(ch: string) {
const code = ch.codePointAt(0) ?? 0;
// 대략적인 CJK 범위
return (
(code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo
(code >= 0x2e80 && code <= 0x9fff) || // CJK, radicals
(code >= 0xac00 && code <= 0xd7af) || // Hangul syllables
(code >= 0x3040 && code <= 0x30ff) || // Hiragana/Katakana
(code >= 0xff00 && code <= 0xffef) // Fullwidth forms
);
}
/* ---------------------------
* Helpers: cell text
* --------------------------- */
function getCellText(cell: any): string {
const v = cell?.value;
if (v === null || v === undefined) return "";
if (typeof v === "string") return v;
if (typeof v === "number" || typeof v === "boolean") return String(v);
if (v instanceof Date) return v.toISOString().slice(0, 10);
// ExcelJS value object types
if (typeof v === "object") {
if (v.richText) return v.richText.map((t: any) => t.text).join("");
if (v.text) return String(v.text);
if (v.formula) return v.result != null ? String(v.result) : "";
if (v.hyperlink) return String(v.text ?? v.hyperlink);
}
return String(v);
}
function getMasterAddress(cell: any) {
// merged cell이면 master가 존재
if (cell?.isMerged && cell?.master?.address) return cell.master.address;
return cell.address;
}
/* ---------------------------
* Helpers: widths
* --------------------------- */
function getColumnWidth(ws: any, col: number, o: Required<AutoFitOpt>) {
const w = ws.getColumn(col)?.width;
return typeof w === "number" ? w : o.minColWidth;
}
function sumColumnWidth(ws: any, left: number, right: number, o: Required<AutoFitOpt>) {
let sum = 0;
for (let c = left; c <= right; c++) sum += getColumnWidth(ws, c, o);
return sum;
}
function clamp(v: number, min: number, max: number) {
return Math.max(min, Math.min(max, v));
}
/* ---------------------------
* Merge map (internal _merges parsing)
* --------------------------- */
type MergeInfo = {
leftCol: number;
rightCol: number;
topRow: number;
bottomRow: number;
colSpan: number;
};
function buildMergeMap(ws: any) {
const map = new Map<string, MergeInfo>();
const merges = ws?._merges;
if (!merges) return map;
// ws._merges: Map<string, any> 형태인 경우가 많음. key가 "A1:C1" 같은 range
const keys: string[] =
merges instanceof Map ? Array.from(merges.keys()) : Object.keys(merges);
for (const range of keys) {
const parsed = parseRange(range);
if (!parsed) continue;
const masterAddr = toA1(parsed.leftCol, parsed.topRow);
map.set(masterAddr, {
...parsed,
colSpan: parsed.rightCol - parsed.leftCol + 1,
});
}
return map;
}
// "A1:C3" -> 좌표
function parseRange(range: string): Omit<MergeInfo, "colSpan"> | null {
const parts = range.split(":");
if (parts.length !== 2) return null;
const a = parseA1(parts[0]);
const b = parseA1(parts[1]);
if (!a || !b) return null;
return {
leftCol: Math.min(a.col, b.col),
rightCol: Math.max(a.col, b.col),
topRow: Math.min(a.row, b.row),
bottomRow: Math.max(a.row, b.row),
};
}
function parseA1(a1: string): { col: number; row: number } | null {
const m = a1.match(/^([A-Z]+)(\d+)$/i);
if (!m) return null;
const col = lettersToCol(m[1].toUpperCase());
const row = parseInt(m[2], 10);
return { col, row };
}
function lettersToCol(letters: string) {
let n = 0;
for (const ch of letters) {
n = n * 26 + (ch.charCodeAt(0) - 64);
}
return n;
}
function toA1(col: number, row: number) {
return `${colToLetters(col)}${row}`;
}
function colToLetters(col: number) {
let n = col;
let s = "";
while (n > 0) {
const r = (n - 1) % 26;
s = String.fromCharCode(65 + r) + s;
n = Math.floor((n - 1) / 26);
}
return s;
}
/* =========================================================
* 3) 헤더 빌더 3종
* ========================================================= */
/**
* (1) PRODUCT_KEY_MAP:
* - 첫 칸 비움
* - 나머지는 일반 헤더
*/
export function buildHeader_ProductKeyMap(
productKeyMap: Record<string, string>,
rowHeadKey = "rowLabel"
): HeaderBlock {
const entries = typedEntries(productKeyMap);
const headerRow: HeaderCell[] = [
{ text: "", styleKey: "header", align: "center" },
...entries.map(([, label]) => ({
text: String(label),
styleKey: "header" as const,
align: "center" as const,
})),
];
const leafKeys = [rowHeadKey, ...entries.map(([k]) => String(k))];
return { headerRows: [headerRow], leafKeys, totalCols: headerRow.length };
}
/**
* (2) LIFE_STAGE_COLUMNS:
* - 1행: group 머지(같은 group 연속 구간)
* - 2행: header 텍스트
*
* group 없는 컬럼은 1행에 빈 셀(그룹 스타일) 1칸 채움
*/
export type GaugeColumn = {
key: string;
header: string;
rowHead?: boolean;
group?: string;
align?: "left" | "center" | "right";
};
export function buildHeader_LifeStageColumns(cols: GaugeColumn[]): HeaderBlock {
const row1: HeaderCell[] = [];
const row2: HeaderCell[] = [];
const leafKeys = cols.map((c) => c.key);
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_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,
};
}
/**
* (3) BANNER_GROUP + BANNER_KEY_MAP:
* - A1: "" (rowspan2)
* - B1: "전체" (rowspan2) key=total
* - C1~: group(label) (colSpan = keys.length)
* - 2행: 각 key의 라벨(BANNER_KEY_MAP[key])
*/
export function buildHeader_Banner<K extends string>(
bannerGroup: Record<string, { label: string; keys: readonly K[] }>,
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 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 };
}
/* =========================================================
* 4) Export (one sheet, 섹션 간 1행 띄움)
* ========================================================= */
export async function exportDashboardExcel<T extends Record<string, any>>(opts: ExportOptions<T>) {
const {
fileName = "export.xlsx",
sheetName = "Export",
sections,
groupBgVar = "--lg-gray-400",
headerBgVar = "--lg-gray-600",
borderVar = "--lg-gray-300",
} = opts;
// ExcelJS import (환경에 따라 min 빌드가 더 잘 먹는 경우가 있음)
const ExcelJS = await import("exceljs");
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet(sheetName);
const stylePack: StylePack = {
groupBg: cssVarToExcelArgb(groupBgVar, "#9CA3AF"),
headerBg: cssVarToExcelArgb(headerBgVar, "#4B5563"),
headerFont: "FFFFFFFF", // #fff
border: cssVarToExcelArgb(borderVar, "#D1D5DB"),
};
let rowCursor = 1;
for (const sec of sections) {
const gap = sec.rowGap ?? 1;
const { header, rows } = sec;
// (선택) 섹션 타이틀
if (sec.title) {
const r = ws.getRow(rowCursor);
const c = r.getCell(1);
c.value = sec.title;
c.font = { bold: true, size: 13 };
r.height = 22;
if (header.totalCols > 1) ws.mergeCells(rowCursor, 1, rowCursor, header.totalCols);
rowCursor += 1;
}
// 헤더
rowCursor = writeMergedHeader(ws, rowCursor, header.headerRows, stylePack);
// 컬럼 width
if (sec.colWidthByKey) {
header.leafKeys.forEach((k, idx) => {
const w = sec.colWidthByKey?.[k];
if (w) ws.getColumn(idx + 1).width = w;
});
} else {
// 기본: 첫 컬럼 넓게, 나머지 적당히
header.leafKeys.forEach((k, idx) => {
ws.getColumn(idx + 1).width = idx === 0 ? 22 : 14;
});
}
const valueGetter = sec.valueGetter ?? ((r: T, k: string) => (r as any)[k]);
// 데이터
for (const row of rows) {
const excelRow = ws.getRow(rowCursor);
const sampleRow = isSampleRow(valueGetter(row, header.leafKeys.at(0) ?? ""));
header.leafKeys.forEach((key, idx) => {
const cell = excelRow.getCell(idx + 1);
const v = valueGetter(row, key);
const isColHeader = idx === 0;
if (v === null || v === undefined || v === "") cell.value = null;
else if (typeof v === "number") cell.value = v;
else if (isColHeader) cell.value = formatRowLabel(String(v));
else if (sampleRow) cell.value = `(${String(v)})`;
else cell.value = String(v);
const align =
sec.alignByKey?.[key] ??
(typeof v === "number" ? "right" : "left");
cell.alignment = { vertical: "middle", horizontal: align, wrapText: true };
const numFmt = sec.numFmtByKey?.[key];
if (numFmt) cell.numFmt = numFmt;
cell.border = {
top: { style: "thin", color: { argb: stylePack.border } },
left: { style: "thin", color: { argb: stylePack.border } },
bottom: { style: "thin", color: { argb: stylePack.border } },
right: { style: "thin", color: { argb: stylePack.border } },
};
if(isColHeader){
cell.font = { bold: true };
}
});
excelRow.height = 18;
rowCursor += 1;
}
rowCursor += gap;
}
autoFitApprox(ws, {
minColWidth: 8,
maxColWidth: 55,
baseRowHeight: 15,
maxRowHeight: 120,
useCanvasMeasure: true,
});
// 다운로드
const buf = await wb.xlsx.writeBuffer();
const blob = new Blob([buf], {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = fileName;
a.click();
URL.revokeObjectURL(url);
}

View File

@@ -5,32 +5,37 @@ export type BannerKey = keyof typeof BANNER_KEY_MAP;
export type ProductsFilterItem = (typeof PRODUCTS_FILTER_ITEM)[number];
export type ServerBaseRow = {
year: number;
year: string;
rowLabel: string;
total: number;
total: string;
};
// { year, rowLabel, total, ...category }
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, number>>;
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, string>>;
// { year, rowLabel, total, ...banner }
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
export type ServerBannerRow = ServerBaseRow &
Partial<Record<BannerKey, number>> & {
[k: string]: number | string;
Partial<Record<BannerKey, string>> & {
[k: string]: string;
};
export type LifeStageRow = Record<string, unknown> & {
item: string;
total: number | null;
single: number | null;
noKids: number | null;
preschoolKids: number | null;
schoolKids: number | null;
adultKids: number | null;
independentSenior: number | null;
total: string;
single: string;
noKids: string;
preschoolKids: string;
schoolKids: string;
adultKids: string;
independentSenior: string;
};
export type LifeStageGroup = {
title: string;
rows: LifeStageRow[]
}
export type BannerGroupKey = keyof typeof BANNER_GROUP;
export type CategoryChartMode = "stack" | "reverseStack" | "horizontal";