Compare commits

...

32 Commits

Author SHA1 Message Date
e7688c127c 260226_01_ENH: dev prod api주소 변경 2026-02-26 11:01:26 +09:00
6b118dd7ec 260225_02_ENH: KART 사용 안하기 때문에 API 땜 2026-02-25 17:03:38 +09:00
357d9f2946 260225_01_ENH: 실제 Data 통계 API와 연결 및 일부 페이지 축소 2026-02-25 16:48:12 +09:00
d0e1352739 260210_01_ENH: Reverse StackBar legend 뒤집기 2026-02-10 15:01:31 +09:00
edfecfcea4 260209_04_ENH: 프로필 페이지에서 단위 텍스트 제거 2026-02-09 16:49:14 +09:00
49ae6ff37e 260209_03_ENH: 필터 영역 디자인 통일 2026-02-09 16:44:24 +09:00
0a81c1a748 260209_02_ENH: word break 모드 변경 및 전체파트 table 영역 조정 2026-02-09 16:37:23 +09:00
6e6120f205 260209_01_ENH: 테이블에 단위 텍스트 추가, 하단 설명 추가 2026-02-09 16:28:29 +09:00
b7282bd07d 260206_07_ENH: 필터 아이콘 추가 및 api통신에 캐시 기능 추가, LIFE_STAGE_COLUMNS에 미혼, 독립 시니어 rowspan 적용 2026-02-06 16:30:29 +09:00
17d75e3f3a 260206_06_ENH: LG 보급률 하위 테이블에 설명 영역 확보 2026-02-06 09:53:56 +09:00
6b5454aa59 260206_05_ENH: Chart 색상에서 hsl 함수 제거 2026-02-06 09:21:25 +09:00
b13f508065 260206_04_ENH: Chart 색상 유틸 수정 2026-02-06 09:15:38 +09:00
ea14a230a1 260206_03_BUG: import 버그 수정 2026-02-06 09:08:46 +09:00
0ff202afcc 260206_02_BLD: 로그인 API 롤백 2026-02-06 09:05:28 +09:00
bd9a95b87f 260206_01_ENH: 일부 차트색상 변경, 브랜드별 차트 부분 색상 변경 필요 2026-02-06 09:03:29 +09:00
21989aeeb7 260205_06_ENH: 보유 경로 차트 높이 수정 2026-02-05 16:56:14 +09:00
84675b77b3 260205_05_ENH: 1차 lg 수정 요청사항 반영 2026-02-05 16:54:55 +09:00
8c015bd443 260205_04_ENH: 빠진 아이콘 추가 2026-02-05 12:25:21 +09:00
8de707f8d1 260205_03_ENH: layout color gray + black으로 변경, excel버튼 아이콘으로 변경 2026-02-05 12:22:18 +09:00
5d3de68b05 260205_02_CLN: 안쓰는 import 정리 2026-02-05 10:05:19 +09:00
3e7c2a98df 260205_01_ENH: 페이지 별 엑셀 다운로드 적용 2026-02-05 09:24:19 +09:00
544f3010aa 260204_01_ENH: 카테고리 하위 페이지들 경로명 수정 2026-02-04 12:07:35 +09:00
0b693661f3 260202_04_ENH: Total 하위 페이지들에 useMemo 적용 및 LifeStyle 샘플 데이터 전체 값 조정 2026-02-02 15:21:53 +09:00
84560cef2d 260202_03_ENH: 페이지 깜빡임 최소화 및 카테고리에서 전체로 이동 시 페이지 렌더링 2회 되는 부분 수정 2026-02-02 15:05:11 +09:00
0950679874 260202_02_ENH: 구매 채널에 온/오프라인 네팅 데이터 추가 2026-02-02 12:30:48 +09:00
6f8e09bcf3 260202_01_ENH: route 구조 초창기 기획으로 다시 변경 및 Category 별 하위 페이지에 샘플 데이터 모두 적용 2026-02-02 11:32:50 +09:00
4b40c43962 260129_01_ENH: 카테고리 파트 layout 및 route 구조 변경 2026-01-29 13:42:42 +09:00
d48decab52 260128_04_ENH: 보급률 하단 카드 legend 크기 키우고 border 적용 2026-01-28 17:08:55 +09:00
d7cb9259cd 260128_03_ENH: 샘플데이터 랜덤 적용, lg 보급률 하단 카드 + 게이지 테이블 적용 2026-01-28 17:01:40 +09:00
4c00cfa946 260128_02_TST: 젠킨스 커밋 메시지 테스트 제거 2026-01-28 10:58:02 +09:00
14523e840d 260128_01_TST: 젠킨스 커밋 메시지 테스트 2026-01-28 10:53:37 +09:00
8bfa8fa7c4 260127_01_ENH: 커스텀 컴포넌트들 1차 완성 및 일부페이지에 SampleData 적용 2026-01-27 16:59:24 +09:00
80 changed files with 7899 additions and 355 deletions

View File

@@ -2,6 +2,4 @@ NEXT_PUBLIC_ENV=dev
NEXT_PUBLIC_API_BASE=https://test-lg-cxdash.kric.com/api
ENV=dev
API_BACK_SERVER=http://localhost:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
API_BACK_SERVER=http://127.0.0.1:6101/api/v1

View File

@@ -2,6 +2,4 @@ NEXT_PUBLIC_ENV=local
NEXT_PUBLIC_API_BASE=http://localhost:6100/api
ENV=local
API_BACK_SERVER=http://localhost:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
API_BACK_SERVER=http://localhost:6101/api/v1

View File

@@ -1,7 +1,5 @@
NEXT_PUBLIC_ENV=prod
NEXT_PUBLIC_API_BASE=http://localhost:6100/api
NEXT_PUBLIC_API_BASE=https://test-lg-cxdash.kric.com/api
ENV=prod
API_BACK_SERVER=http://localhost:6101/api/v1
API_KART_SERVER=https://rapi.kric.com/api/v1
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
API_BACK_SERVER=http://127.0.0.1:6101/api/v1

8
.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# 디폴트 무시된 파일
/shelf/
/workspace.xml
# 에디터 기반 HTTP 클라이언트 요청
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -16,7 +16,7 @@ bun dev
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
You can start editing the page by modifying `app/Profile.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.

1051
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -16,11 +16,13 @@
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@tanstack/react-query": "^5.90.21",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"crypto-js": "^4.2.0",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.5",
"exceljs": "^4.4.0",
"jotai": "^2.16.2",
"lodash": "^4.17.21",
"lucide-react": "^0.562.0",
@@ -33,6 +35,7 @@
},
"devDependencies": {
"@tailwindcss/postcss": "^4.0.7",
"@tanstack/react-query-devtools": "^5.91.3",
"@types/crypto-js": "^4.2.2",
"@types/lodash": "^4.17.23",
"@types/node": "^20",

BIN
public/icon-excel.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

BIN
public/logo_transparent.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

View File

@@ -1,7 +0,0 @@
const AirSolutionPage = () => {
return (
<div>AirSolutionPage</div>
);
}
export default AirSolutionPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
const ESPage = () => {
return <CategoryPage/>
}
export default ESPage;

View File

@@ -1,7 +0,0 @@
const HAKitchenPage = () => {
return (
<div>HAKitchenPage</div>
);
}
export default HAKitchenPage;

View File

@@ -1,7 +0,0 @@
const HALivingPage = () => {
return (
<div>HALivingPage</div>
);
}
export default HALivingPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
const KitchenPage = () => {
return <CategoryPage/>
}
export default KitchenPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
const LivingPage = () => {
return <CategoryPage/>
}
export default LivingPage;

View File

@@ -1,7 +0,0 @@
const MSDigitalPage = () => {
return (
<div>MSDigitalPage</div>
);
}
export default MSDigitalPage;

View File

@@ -0,0 +1,7 @@
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
const MSPage = () => {
return <CategoryPage/>
}
export default MSPage;

View File

@@ -1,7 +1,254 @@
"use client";
import {
BottomDescription,
GroupedOverlayBar,
type GroupedOverlayBarData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import {
CHART_COLOR_BY_YEAR,
CHART_FOCUS_COLOR_BY_YEAR,
LIFE_STAGE_COLUMNS,
LIFE_STAGE_GROUPS,
PRODUCT_KEY_MAP,
PRODUCT_KEYS,
SITE_TITLE,
YEARS
} from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import LifeStageDiv from "@/components/lge-dashboard/combo/LifeStageDiv";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow, calcTotalBaseRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow, withTotalBaseRow
} from "@/lib/lg-dashboard";
import {
buildHeader_LifeStageColumns,
buildHeader_ProductKeyMap,
exportDashboardExcel,
Section
} from "@/lib/lg-export-excel";
import {toNumOr0} from "@/lib/utils";
import {LifeStageGroup, LifeStageRow, ProductKey, StatisticsRequest} from "@/types/lg";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {useBannerStatisticsQuery, useProductStatisticsQuery} from "@/hooks/useLgStatisticsQuery";
const LGPenetrationPage = () => {
const {filterValue, registerExcelExporter} = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: {penetration: "KQA1", penetration_lg: "KQA3_3_LG"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: {useCache: true, lastYear: false, decimalPoint: 0},
};
}, [debouncedFilterValue]);
const req_lifestage = useMemo<StatisticsRequest>(() => {
const filter = {...debouncedFilterValue, "":""}
return {
variableIdMap: {lifestage_lg: "KQA3_3_LG"},
bannerIdList: ["product|lifeStage"],
filterCondition: normalizeFilterCondition(filter),
option: {useCache: true, lastYear: true, decimalPoint: 0},
};
}, [debouncedFilterValue]);
const {data, isError, error} = useProductStatisticsQuery(req);
const {
data: data_lifestage,
isError: isError_lifestage,
error: error_lifestage
} = useBannerStatisticsQuery(req_lifestage);
if(isError){
console.error(error);
}
if(isError_lifestage){
console.error(error_lifestage);
}
const penetrationRows =
data?.statisticsDataMap?.penetration
.filter((r) => r.rowLabel == `보유`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const penetrationLGRows =
data?.statisticsDataMap?.penetration_lg
.filter((row) => row.rowLabel === `보유`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const lifeStageRows =
data_lifestage?.statisticsDataMap?.lifestage_lg
.filter((r) => r.rowLabel == `보유`) ?? [];
const { includeProductKeys, productKeyMap, includeProducts } = useMemo(() => {
const included = new Set<ProductKey>();
for (const row of penetrationLGRows) {
for (const k of PRODUCT_KEYS) {
if (!included.has(k) && toNumOr0((row as any)[k]) !== 0) included.add(k);
}
}
const keys = PRODUCT_KEYS.filter((k) => included.has(k));
const map = Object.fromEntries(keys.map((k) => [k, PRODUCT_KEY_MAP[k]])) as Record<string, string>;
const products = keys.map((k) => PRODUCT_KEY_MAP[k]);
return { includeProductKeys: keys, productKeyMap: map, includeProducts: products };
}, [penetrationLGRows]);
const penetrationLGRowsWithGap = useMemo(() => {
const withGap = withGapRow(penetrationLGRows, calcGapProductRow);
return withTotalBaseRow("보급률",penetrationRows, withGap, calcTotalBaseRow);
}, [penetrationRows, penetrationLGRows]);
const productTableRows = useMemo<TopChartTableRow[]>(() => {
return penetrationLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, [penetrationLGRowsWithGap, includeProductKeys]);
const productChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
penetrationLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < includeProductKeys.length; ci++) {
const k = includeProductKeys[ci];
const t = (penetrationRows[ri] as any)[k];
const v = (r as any)[k];
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
return {
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, [penetrationRows, penetrationLGRows, includeProductKeys, includeProducts]);
const lifeStageRowsByGroup: LifeStageGroup[] = useMemo(() => {
if(lifeStageRows.length == 0){
return [];
}
const lifeStageData = lifeStageRows[0];
return LIFE_STAGE_GROUPS.map((g) => {
const rows: LifeStageRow[] = g.items.map((key) => {
const label = PRODUCT_KEY_MAP[key];
return {
item: label,
total: lifeStageData[`${key}`] ?? "",
"KLIFEstAGE#1": lifeStageData[`${key}|KLIFEstAGE#1`] ?? "",
"KLIFEstAGE#2": lifeStageData[`${key}|KLIFEstAGE#2`] ?? "",
"KLIFEstAGE#3": lifeStageData[`${key}|KLIFEstAGE#3`] ?? "",
"KLIFEstAGE#4": lifeStageData[`${key}|KLIFEstAGE#4`] ?? "",
"KLIFEstAGE#5": lifeStageData[`${key}|KLIFEstAGE#5`] ?? "",
"KLIFEstAGE#6": lifeStageData[`${key}|KLIFEstAGE#6`] ?? "",
};
});
return {title: g.title, rows};
});
}, [lifeStageRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(productKeyMap);
const lifeStageHeader = buildHeader_LifeStageColumns(LIFE_STAGE_COLUMNS);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{
title: "LG제품 보급률",
header: excelHeader,
rows: penetrationLGRowsWithGap as AnyRow[],
rowGap: 1,
},
...lifeStageRowsByGroup.map((lifeStageRow) => ({
title: lifeStageRow.title,
header: lifeStageHeader,
rows: lifeStageRow.rows as AnyRow[],
rowGap: 1,
})),
];
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 보급률).xlsx`,
sheetName: "LG제품 보급률",
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, penetrationLGRowsWithGap, lifeStageRowsByGroup, productKeyMap]);
return (
<div>LGPenetrationPage</div>
<div>
<TopChartTable
title={"LG제품 보급률"}
categories={[...includeProducts]}
rows={productTableRows}
chart={
<GroupedOverlayBar
data={productChartData}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup}/>
</div>
);
}
};
export default LGPenetrationPage;

View File

@@ -1,7 +1,179 @@
"use client";
import {useEffect, useMemo} from "react";
import {
CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR,
PRODUCT_KEY_MAP,
PRODUCT_KEYS,
SITE_TITLE,
YEARS
} from "@/const/lgConst";
import {
BottomDescription,
GroupedOverlayBar,
type GroupedOverlayBarData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow, calcTotalBaseRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow, withTotalBaseRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {ProductKey, StatisticsRequest} from "@/types/lg";
import {useProductStatisticsQuery} from "@/hooks/useLgStatisticsQuery";
import {toNumOr0} from "@/lib/utils";
const LGPurchasePage = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: {purchase: "KQA3_2", purchase_lg: "KQX3_3_LG"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: {useCache: false, lastYear: false, decimalPoint: 0},
};
}, [debouncedFilterValue]);
const {data, isError, error} = useProductStatisticsQuery(req);
if(isError){
console.error(error);
}
const purchaseRows =
data?.statisticsDataMap?.purchase
.filter((r) => r.rowLabel == `해당년도`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const purchaseLGRows =
data?.statisticsDataMap?.purchase_lg
.filter((row) => row.rowLabel === `구입`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const purchaseLGRowsWithGap = useMemo(() => {
const withGap = withGapRow(purchaseLGRows, calcGapProductRow);
return withTotalBaseRow("구입율",purchaseRows, withGap, calcTotalBaseRow);
}, [purchaseRows, purchaseLGRows]);
const { includeProductKeys, productKeyMap, includeProducts } = useMemo(() => {
const included = new Set<ProductKey>();
for (const row of purchaseLGRows) {
for (const k of PRODUCT_KEYS) {
if (!included.has(k) && toNumOr0((row as any)[k]) !== 0) included.add(k);
}
}
const keys = PRODUCT_KEYS.filter((k) => included.has(k));
const map = Object.fromEntries(keys.map((k) => [k, PRODUCT_KEY_MAP[k]])) as Record<string, string>;
const products = keys.map((k) => PRODUCT_KEY_MAP[k]);
return { includeProductKeys: keys, productKeyMap: map, includeProducts: products };
}, [purchaseLGRows]);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
return purchaseLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, [purchaseLGRowsWithGap, includeProductKeys]);
const purchaseChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(includeProductKeys.length).fill(0));
const yearIndexMap = new Map<string, number>(YEARS.map((y, i) => [y, i]));
purchaseLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < includeProductKeys.length; ci++) {
const k = includeProductKeys[ci];
const t = (purchaseRows[ri] as any)[k];
const v = (r as any)[k];
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
return {
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, [purchaseRows, purchaseLGRows, includeProducts, includeProductKeys]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>" +
"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(productKeyMap);
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 구매율).xlsx`,
sheetName: "LG제품 구매율",
sections: [
{ title: "LG제품 구매율", header: excelHeader, rows: purchaseLGRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, purchaseLGRowsWithGap]);
return (
<div>LGPurchasePage</div>
<div>
<TopChartTable
title={"LG제품 구매율"}
categories={[...includeProducts]}
rows={purchaseTableRows}
chart={
<GroupedOverlayBar
data={purchaseChartData}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
</div>
);
}
};
export default LGPurchasePage;

View File

@@ -1,7 +1,205 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import TopChartTable from "@/components/lge-dashboard/combo/TopChartTable";
import VerticalBar from "@/components/lge-dashboard/chart/VerticalBar";
import {
type ChartData,
GroupedStackBar,
signStyleGapRow,
type TopChartTableRow,
type GroupedStackBarData, BottomDescription,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { Button } from "@/components/ui/button";
import {
BRAND_LIST,
PRODUCT_KEYS,
PRODUCTS,
YEARS,
AXIS_HIDE_STYLE,
GRID_X_NOT_PADDING, PRODUCT_KEY_MAP, SITE_TITLE
} from "@/const/lgConst";
import {
calcCagrRow, calcGapProductRow,
formatRowLabel,
normalizeFilterCondition, withCagrRow, withGapRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
import {StatisticsRequest} from "@/types/lg";
import {useProductStatisticsQuery} from "@/hooks/useLgStatisticsQuery";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {toNumOr0} from "@/lib/utils";
import {SelectedMap} from "@/types/common";
const PenetrationPage = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
const [isBrandShare, setIsBrandShare] = useState(false);
const chartColorByYear = Object.fromEntries(
YEARS.map((year, i) => [
year,
[`--chart-cbrand-${i + 1}`,`--chart-samsung-${i + 1}`,`--chart-lg-${i + 1}`],
])
) as Record<(typeof YEARS)[number], string[]>;
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: { penetration: "KQA1", penetration_brand: "KQA3_3_NET" },
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: { useCache: true, lastYear: false, decimalPoint: 0 },
};
}, [debouncedFilterValue]);
const { data, isError, error } = useProductStatisticsQuery(req);
if(isError){
console.error(error);
}
const penetrationRows =
data?.statisticsDataMap?.penetration
.filter((r) => r.rowLabel == `보유`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const penetrationBrandRows =
data?.statisticsDataMap?.penetration_brand
.filter((row) => BRAND_LIST.includes(row.rowLabel)) ?? [];
const penetrationRowsWithGapCagr = useMemo(() => {
const withGap = withGapRow(penetrationRows, calcGapProductRow);
return withCagrRow(withGap, calcCagrRow);
}, [penetrationRows]);
const productTableRows = useMemo<TopChartTableRow[]>(() => {
return penetrationRowsWithGapCagr.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}))
}, [penetrationRowsWithGapCagr]);
const productChartData = useMemo<ChartData>(() => {
return {
categories: [...PRODUCTS],
series: penetrationRows
.map((row) => ({
name: row.year,
data: PRODUCT_KEYS.map((k) => toNumOr0((row as any)[k])),
})),
};
}, [penetrationRows]);
const brandShareChartData = useMemo<GroupedStackBarData>(() => {
const rowMap = new Map<string, (typeof penetrationBrandRows)[number]>();
for (const r of penetrationBrandRows) {
rowMap.set(`${r.year}__${r.rowLabel}`, r);
}
const values: number[][][] = YEARS.map(() =>
BRAND_LIST.map(() => new Array(PRODUCTS.length).fill(0))
);
YEARS.forEach((year, yi) => {
BRAND_LIST.forEach((brand, bi) => {
PRODUCT_KEYS.forEach((k, ci) => {
const row = rowMap.get(`${year}__${brand}`);
values[yi][bi][ci] = (row as any)?.[k];
});
});
});
return { categories: PRODUCTS, years: YEARS, brands: BRAND_LIST, values };
}, [penetrationBrandRows]);
const description = useMemo(() => {
if(isBrandShare){
return "Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.";
}, [isBrandShare]);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{ title: "전체 보급률", header: excelHeader, rows: penetrationRowsWithGapCagr, rowGap: 1 },
...YEARS.map((year) => (
{
title: `브랜드 별 점유율_${year}년`,
header: excelHeader,
rows: penetrationBrandRows.filter((row) => row.year === year),
rowGap: 1,
}
))
];
await exportDashboardExcel({
fileName: `${SITE_TITLE}(보급률).xlsx`,
sheetName: "전체 보급률",
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, penetrationRows, penetrationBrandRows]);
return (
<div>PenetrationPage</div>
<div>
<div className="flex py-4">
<Button
className="h-8 px-3 text-sm font-semibold content-text-sm"
variant={isBrandShare ? "default" : "secondary"}
onClick={() => setIsBrandShare((v) => !v)}
>
{"브랜드별 점유율"}
</Button>
</div>
<TopChartTable
title={isBrandShare ? "브랜드별 점유율" : "전체 보급률"}
categories={[...PRODUCTS]}
rows={productTableRows}
chart={
isBrandShare ? (
<GroupedStackBar
data={brandShareChartData}
grid={{ ...GRID_X_NOT_PADDING, top: 60 }}
xAxis={{ type: "category", data: PRODUCTS, ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"none"}
yearBrandPalette={chartColorByYear}
height={260}
/>
) : (
<VerticalBar
data={productChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
)
}
signStyle={signStyleGapRow}
fillCAGR={true}
/>
<BottomDescription description={description} />
</div>
);
}
};
export default PenetrationPage;

View File

@@ -1,7 +1,129 @@
"use client";
import {useEffect, useMemo} from "react";
import {
PRODUCT_KEYS,
PRODUCTS,
AXIS_HIDE_STYLE,
GRID_X_NOT_PADDING,
PRODUCT_KEY_MAP,
SITE_TITLE
} from "@/const/lgConst";
import {
BottomDescription,
type ChartData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
VerticalBar,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {calcGapProductRow, formatRowLabel, normalizeFilterCondition, withGapRow} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {StatisticsRequest} from "@/types/lg";
import {useProductStatisticsQuery} from "@/hooks/useLgStatisticsQuery";
const PurchasePage = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: { purchase: "KQA3_2"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: { useCache: true, lastYear: false, decimalPoint: 0 },
};
}, [debouncedFilterValue]);
const { data, isError, error } = useProductStatisticsQuery(req);
if(isError){
console.error(error);
}
const purchaseRows =
data?.statisticsDataMap?.purchase
.filter((r) => r.rowLabel == `해당년도`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}) ?? [];
const purchaseRowsWithGap = useMemo(() => {
return withGapRow(purchaseRows, calcGapProductRow);
}, [purchaseRows]);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
return purchaseRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
}));
}, [purchaseRowsWithGap]);
const purchaseChartData = useMemo<ChartData>(() => {
return {
categories: [...PRODUCTS],
series: purchaseRows
.map((r) => ({
name: r.rowLabel,
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
};
}, [purchaseRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>" +
"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
await exportDashboardExcel({
fileName: `${SITE_TITLE}(구매율).xlsx`,
sheetName: "구매율",
sections: [
{ title: "구매율", header: excelHeader, rows: purchaseRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, purchaseRowsWithGap]);
return (
<div>PurchasePage</div>
<div>
<TopChartTable
title={"전체 구매율"}
categories={[...PRODUCTS]}
rows={purchaseTableRows}
chart={
<VerticalBar
data={purchaseChartData}
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
grid={GRID_X_NOT_PADDING}
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description} />
</div>
);
}
};
export default PurchasePage;

View File

@@ -89,7 +89,7 @@ const LoginPage = () => {
};
return (
<div className="min-h-screen flex items-center justify-center p-4 bg-lg-login">
<div className="min-h-screen flex items-center justify-center p-4 bg-lg-login-body">
<Card className="w-full max-w-md shadow-xl">
<CardHeader className="space-y-4">
<div className="flex justify-center">

View File

@@ -14,17 +14,8 @@ export const POST = async (req: NextRequest) => {
const backApi = await createBackApi();
const body = (await req.json()) as LoginRequest;
//const result = await backApi.post<LoginResponse>("/auth/login", body);
const result:LoginResponse = {
accessToken: "abcdefghijklmnopqrstuvwxyz0123456789",
user: {
userId: "TEST_USER",
userName: "TEST_USER",
userCmpn: "TEST",
userTeam: "TEST",
userRole: 9999,
}
}
const result = await backApi.post<LoginResponse>("/auth/login", body);
const res = NextResponse.json(result.user, { status: 200 });
res.cookies.set("access_token", result.accessToken, {

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

@@ -0,0 +1,39 @@
import {NextRequest, NextResponse} from "next/server";
import {RouteContext} from "@/types/common";
import {errorToResponse} from "@/lib/http-util";
import {createBackApi} from "@/lib/server-api";
import {ProductResponse, BannerResponse} from "@/types/lg";
export async function POST(
req: NextRequest,
context: RouteContext
) {
try {
const {slug = []} = await context.params;
const backApi = await createBackApi();
const [action] = slug;
if(action === "product" || action === "banner"){
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json(
{ message: "요청 바디가 없습니다." },
{ status: 400 }
);
}
if (action === "product") {
const result = await backApi.post<ProductResponse>(`/statistics`, body);
return NextResponse.json(result, { status: 200 });
}
// action === "banner"
const result = await backApi.post<BannerResponse>(`/statistics`, body);
return NextResponse.json(result, { status: 200 });
}
return NextResponse.json({ message: "Not found" }, { status: 404 });
} catch (error: unknown) {
return errorToResponse(error);
}
}

View File

@@ -113,11 +113,17 @@
--lg-red-500: 341.1 95% 44.0%; /* #DB0649 */
--lg-red-400: 341.1 85% 56.0%; /* #EE2F6C */
--lg-red-300: 341.1 75% 68.0%; /* #EB7097 */
--lg-red-200: 341.1 65% 82.0%; /* #EFB3C6 */
--lg-red-100: 341.1 55% 90.0%; /* #F4D7E0 */
--lg-red-50: 341.1 45% 96.0%; /* #F9F0F3 */
--lg-pink-600: 324.7 100% 46.3%; /* #EC008B */
--lg-pink-500: 324.7 95% 56.0%; /* #F924A2 */
--lg-pink-400: 324.7 85% 66.0%; /* #F25FB5 */
--lg-pink-300: 324.7 75% 76.0%; /* #F094CA */
--lg-pink-200: 324.7 65% 86.0%; /* #F3C4DF */
--lg-pink-100: 324.7 55% 92.0%; /* #F6DFED */
--lg-pink-50: 324.7 45% 97.0%; /* #FBF4F8 */
--lg-purple-600: 263.0 65.9% 44.9%; /* #6127BE */
--lg-purple-500: 263.0 60.0% 56.0%;
@@ -129,6 +135,10 @@
--lg-orange-400: 29.6 85% 68.0%;
--lg-orange-300: 29.6 75% 78.0%;
--samsung-blue-600: 218.93 53.91% 52.35%; /* #4472C7 */
--samsung-blue-500: 218.93 48.0% 56.0%; /* #597FC5 */
--samsung-blue-400: 218.93 40.0% 66.0%; /* #869ECB */
--samsung-blue-300: 218.93 33.0% 76.0%; /* #AEBCD6 */
/* =============================
Brand Core
(semantic은 "실제 색"으로 정의)
@@ -166,16 +176,34 @@
/* =============================
Chart Colors
============================= */
--chart-1: hsl(var(--lg-red-600));
--chart-2: hsl(var(--lg-red-300));
--chart-3: hsl(var(--lg-pink-300));
--chart-4: hsl(var(--lg-pink-400));
--chart-5: hsl(var(--lg-pink-600));
--chart-6: hsl(var(--lg-gray-900));
--chart-7: hsl(var(--lg-gray-800));
--chart-8: hsl(var(--lg-gray-700));
--chart-9: hsl(var(--lg-gray-600));
--chart-10: hsl(var(--lg-gray-500));
--chart-1: 334 81% 41%;
--chart-2: 0 0% 49%;
--chart-3: 0 0% 74%;
--chart-1-t: 334 80% 90%;
--chart-2-t: 0 0% 70%;
--chart-3-t: 0 0% 88%;
--chart-4: var(--lg-pink-400);
--chart-5: var(--lg-pink-600);
--chart-6: var(--lg-gray-500);
--chart-7: var(--lg-gray-600);
--chart-8: var(--lg-gray-700);
--chart-9: var(--lg-gray-800);
--chart-10: var(--lg-gray-900);
--chart-lg-1: var(--lg-pink-300);
--chart-lg-2: var(--lg-red-300);
--chart-lg-3: var(--lg-red-600);
--chart-total-1: var(--lg-gray-300);
--chart-total-2: var(--lg-gray-400);
--chart-total-3: var(--lg-gray-700);
--chart-cbrand-1: var(--lg-gray-300);
--chart-cbrand-2: var(--lg-gray-400);
--chart-cbrand-3: var(--lg-gray-700);
--chart-samsung-1: var(--samsung-blue-400);
--chart-samsung-2: var(--samsung-blue-500);
--chart-samsung-3: var(--samsung-blue-600);
--chart-border: hsl(0 0% 95%);
/* =============================
@@ -285,6 +313,8 @@
.border-border { border-color: var(--border); }
/* LG gray scale (Tailwind gray override 의도 유지) */
.bg-black { background-color: #111111 !important; }
.bg-gray-900 { background-color: hsl(var(--lg-gray-900)) !important; }
.bg-gray-800 { background-color: hsl(var(--lg-gray-800)) !important; }
.bg-gray-700 { background-color: hsl(var(--lg-gray-700)) !important; }
@@ -308,11 +338,15 @@
.bg-red-500 { background-color: hsl(var(--lg-red-500)) !important; }
.bg-red-400 { background-color: hsl(var(--lg-red-400)) !important; }
.bg-red-300 { background-color: hsl(var(--lg-red-300)) !important; }
.bg-red-200 { background-color: hsl(var(--lg-red-200)) !important; }
.bg-red-100 { background-color: hsl(var(--lg-red-100)) !important; }
.bg-pink-600 { background-color: hsl(var(--lg-pink-600)) !important; }
.bg-pink-500 { background-color: hsl(var(--lg-pink-500)) !important; }
.bg-pink-400 { background-color: hsl(var(--lg-pink-400)) !important; }
.bg-pink-300 { background-color: hsl(var(--lg-pink-300)) !important; }
.bg-pink-200 { background-color: hsl(var(--lg-pink-200)) !important; }
.bg-pink-100 { background-color: hsl(var(--lg-pink-100)) !important; }
.bg-purple-600 { background-color: hsl(var(--lg-purple-600)) !important; }
.bg-purple-500 { background-color: hsl(var(--lg-purple-500)) !important; }
@@ -363,23 +397,57 @@
.placeholder-content-text-3xl::placeholder { font-size: calc(var(--content-font-size) * 1.875); }
.placeholder-content-text-4xl::placeholder { font-size: calc(var(--content-font-size) * 2.25); }
.bg-lg-login {
.bg-lg-login-body {
background-color: hsl(var(--background));
background-image: linear-gradient(
135deg,
hsl(var(--lg-red-600) / 0.16) 0%,
var(--background) 50%,
hsl(var(--lg-pink-600) / 0.14) 100%
hsl(var(--lg-gray-900) / 0.5) 0%,
var(--background) 30%,
var(--background) 70%,
hsl(var(--lg-gray-900) / 0.5) 100%
);
}
.text-header-color { color: #FFFFFF; }
.text-header-primary {
color: #FFFFFF;
font-weight: 600;
position: relative;
padding-bottom: 4px;
}
.text-header-primary::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
background: linear-gradient(90deg, #A50034 0%, #E6004C 100%);
border-radius: 2px 2px 0 0;
}
/* 비활성 메뉴 스타일 */
.text-header-secondary-hover {
color: #C0C0C0;
transition: all 0.3s ease;
cursor: pointer;
}
/* 호버 효과 */
.text-header-secondary-hover:hover {
color: rgba(255, 255, 255, 0.9) !important;
}
.bg-lg-main-body {
background-color: hsl(var(--background));
background-image: linear-gradient(
135deg,
hsl(var(--lg-red-500) / 0.12) 0%,
var(--background) 50%,
hsl(var(--lg-pink-500) / 0.10) 100%
hsl(var(--lg-gray-900) / 0.2) 0%,
var(--background) 30%,
var(--background) 70%,
hsl(var(--lg-gray-900) / 0.2) 100%
);
}
}
@@ -406,7 +474,7 @@
line-height: 1.15;
text-align: center;
word-wrap: break-word;
word-break: break-all;
word-break: auto-phrase;
}
.lg-table thead tr.lg-table__group th {
@@ -426,7 +494,7 @@
color: var(--foreground);
background: var(--background);
word-wrap: break-word;
word-break: break-all;
word-break: auto-phrase;
}
.lg-table .lg-table__sep-l { border-left: 3px solid hsl(var(--lg-gray-200)) !important; }

View File

@@ -2,6 +2,7 @@ import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import {Toaster} from "sonner";
import {AppProvider} from "@/components/providers/AppProvider";
const geistSans = Geist({
variable: "--font-geist-sans",
@@ -25,10 +26,10 @@ const RootLayout = ({
}>) => {
return (
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
{children}
<Toaster />
</body>
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<AppProvider>{children}</AppProvider>
<Toaster />
</body>
</html>
);
};

View File

@@ -0,0 +1,17 @@
"use client";
import { useAtomValue } from "jotai";
import { loadingAtom } from "@/store/jotai/loading";
export function LoadingOverlay({ force = false }: { force?: boolean }) {
const isLoading = useAtomValue(loadingAtom);
if (!force && !isLoading) return null;
return (
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
{/* 심플 로딩 인디케이터 */}
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
</div>
);
}

View File

@@ -0,0 +1,19 @@
"use client";
import {useIsFetching} from "@tanstack/react-query";
import {useLoading} from "@/hooks/useLoading";
import {useEffect} from "react";
const ReactQueryLoadingSync = () => {
const fetching = useIsFetching();
const { showLoading, hideLoading } = useLoading();
useEffect(() => {
if (fetching > 0) showLoading();
else hideLoading();
}, [fetching, showLoading, hideLoading]);
return null;
};
export default ReactQueryLoadingSync;

View File

@@ -1,19 +1,16 @@
"use client";
import { CategoryTargetData, CategoryTargetType } from "@/config/filter.types";
import {
CategoryTargetType,
TargetChild,
} from "@/config/filter.types";
import {categoryTarget, categoryTargetType} from "@/config/filter.data";
import { ChevronRight } from "lucide-react";
import { useMemo } from "react";
import {useCallback, useMemo} from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
const PRODUCTS = [
{ value: "냉장고", label: "냉장고" },
{ value: "세탁기", label: "세탁기" },
{ value: "식기세척기", label: "식기세척기" },
{ value: "건조기", label: "건조기" },
{ value: "에어컨", label: "에어컨" },
] as const;
import {ProductKey, ProductsFilterItem} from "@/types/lg";
import {PRODUCT_KEY_MAP, YEARS} from "@/const/lgConst";
export type CategoryTypeValue = {
label: string;
@@ -21,124 +18,191 @@ export type CategoryTypeValue = {
};
export type CategoryFilterValue = {
product: string;
product: ProductKey;
year: string;
type: CategoryTypeValue
target: CategoryTargetData;
target: TargetChild;
};
type CategoryFilterProps = {
filterItems: ProductsFilterItem,
value: CategoryFilterValue;
onChange: (next: CategoryFilterValue) => void;
className?: string;
};
const CategoryFilter = ({ value, onChange, className }: CategoryFilterProps) => {
type Option = { key: string; label: string; value: string | CategoryTypeValue | TargetChild };
type RowDef = {
id: "year" | "product" | "type" | "target";
title: string;
options: Option[];
isActive: (v: Option["value"]) => boolean;
onSelect: (v: Option["value"]) => void;
};
function FilterLine({ title, options, isActive, onSelect }: Omit<RowDef, "id">) {
return (
<div className="flex min-w-0">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">
{title}
</span>
</div>
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2">
{options.map((opt) => {
const active = isActive(opt.value);
return (
<Button
key={opt.key}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => onSelect(opt.value)}
className="h-8 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-base"
>
{opt.label}
</Button>
);
})}
</div>
</div>
);
}
const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFilterProps) => {
const currentTargetItem = useMemo(() => {
return categoryTarget.find((item) => item.type === value.type.value);
}, [value.type]);
return categoryTarget.find((item) => item.type.includes(value.type.value));
}, [value.type.value]);
const handlePick = (
key: keyof CategoryFilterValue,
v: string | CategoryTypeValue | CategoryTargetData
) => {
if (value[key] === v) return;
// type 비교는 객체참조가 아니라 value로 비교해야 함
const handlePick = useCallback(
<K extends keyof CategoryFilterValue>(key: K, v: CategoryFilterValue[K]) => {
// 1) type
if (key === "type") {
const nextType = v as CategoryTypeValue;
if (value.type.value === nextType.value) return;
const next: CategoryFilterValue = { ...value, [key]: v } as CategoryFilterValue;
const nextItem = categoryTarget.find((item) =>
item.type.includes(nextType.value)
);
const firstTarget = nextItem?.children?.[0];
onChange({
...value,
type: nextType,
target: firstTarget ?? value.target,
});
return;
}
if (key === "type") {
const nextItem = categoryTarget.find((item) => item.type === v);
const firstTarget = nextItem?.children?.[0]?.target;
if (firstTarget) next.target = firstTarget;
}
// 2) target (객체 비교는 value로)
if (key === "target") {
const nextTarget = v as TargetChild;
if (value.target.value === nextTarget.value) return;
onChange(next);
};
onChange({ ...value, target: nextTarget });
return;
}
// 3) year/product (primitive)
if (value[key] === v) return;
onChange({ ...value, [key]: v } as CategoryFilterValue);
},
[value, onChange]
);
const rowDefs = useMemo<RowDef[]>(() => {
const yearRow:RowDef = {
id:"year",
title: "연도",
options:(YEARS).map((y) => ({
key:y,
label:`${y}년`,
value:y,
})),
isActive: (v) => value.year === v,
onSelect: (v) => handlePick("year", v as string),
};
const productRow: RowDef = {
id: "product",
title: "제품",
options: (filterItems.items ?? []).map((p) => ({
key: p,
label: PRODUCT_KEY_MAP[p],
value: p,
})),
isActive: (v) => value.product === v,
onSelect: (v) => handlePick("product", v as ProductKey),
};
const typeRow: RowDef = {
id: "type",
title: "기준",
options: categoryTargetType.map((t) => ({
key: t.label,
label: t.label,
value: { label: t.label, value: t.value },
})),
isActive: (v) => value.type.value === (v as CategoryTypeValue).value,
onSelect: (v) => handlePick("type", v as CategoryTypeValue),
};
const targetRow: RowDef = {
id: "target",
title: "데이터",
options: (currentTargetItem?.children ?? []).map((c) => ({
key: String(c.value),
label: c.label,
value: { label: c.label, value: c.value },
})),
isActive: (v) => value.target.value === (v as TargetChild).value,
onSelect: (v) => handlePick("target", v as TargetChild),
};
// 여기 순서만 바꾸면 배치도 같이 바뀜 (left: 앞쪽 half, right: 뒤쪽 half)
return [yearRow, productRow, typeRow, targetRow];
}, [YEARS, filterItems.items, currentTargetItem, value, handlePick]);
const cells = useMemo(() => {
const half = Math.ceil(rowDefs.length / 2); // 3개면 2개(left) + 1개(right)
const maxRows = half;
return rowDefs.map((def, i) => {
const col = i < half ? 0 : 1; // 0:left, 1:right
const row = i < half ? i : i - half;
return { def, col, row, maxRows };
});
}, [rowDefs]);
return (
<div className={cn("w-full border border-gray-300 bg-white/70 backdrop-blur-sm", className)}>
{/* 제품 (1줄 나열) */}
<div className="flex min-w-0 border-b border-gray-200">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">제품</span>
</div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{PRODUCTS.map((p) => {
const active = value.product === p.value;
return (
<Button
key={p.value}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => handlePick("product", p.value)}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{p.label}
</Button>
);
})}
</div>
</div>
</div>
{/* 기준 (1줄 나열) */}
<div className="flex min-w-0 border-b border-gray-200">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">기준</span>
</div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{categoryTargetType.map((item) => {
const active = value.type.label === item.label;
return (
<Button
key={item.label}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => {
handlePick("type", {label:item.label, value:item.value});
}}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{item.label}
</Button>
);
})}
</div>
</div>
</div>
{/* 데이터 (1줄 나열) */}
<div className="flex min-w-0">
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">데이터</span>
</div>
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
<div className="flex w-max items-center gap-1 whitespace-nowrap">
{currentTargetItem?.children?.map((child) => {
const active = value.target === child.target;
return (
<Button
key={child.target}
type="button"
variant={active ? "default" : "secondary"}
onClick={() => handlePick("target", child.target)}
className="h-6 shrink-0 rounded-sm px-3 text-sm font-semibold content-text-sm"
>
{child.label}
</Button>
);
})}
</div>
</div>
<div className="grid grid-cols-2">
{cells.map(({ def, col, row, maxRows }) => {
const showRowDivider = row < maxRows - 1; // 같은 rowIndex 기준으로 좌/우 라인 맞춤
return (
<div
key={def.id}
style={{
gridColumnStart: col + 1,
gridRowStart: row + 1,
}}
className={cn(
"min-w-0",
showRowDivider && "border-b border-gray-200",
col === 1 && "border-l-4 border-gray-300"
)}
>
<FilterLine
title={def.title}
options={def.options}
isActive={def.isActive}
onSelect={def.onSelect}
/>
</div>
);
})}
</div>
</div>
);

View File

@@ -0,0 +1,26 @@
"use client";
import { Button } from "@/components/ui/button";
import { useLayoutFilter } from "./LayoutFilterContext";
import Image from "next/image";
const ExcelDownloadButton = () => {
const { requestExcelExport } = useLayoutFilter();
return (
<div className={"mr-2 pb-1 cursor-pointer"}>
<Image
src="/icon-excel.png"
alt="excel export"
width={27}
height={27}
className="object-contain"
onClick={requestExcelExport}
priority
/>
</div>
);
};
export default ExcelDownloadButton;

View File

@@ -5,8 +5,8 @@ import Image from "next/image";
import {topMenus} from "@/config/menu.data";
import {Button} from "@/components/ui/button";
import {LogOut} from "lucide-react";
import {DASHBOARD_YEAR} from "@/const/commonConst";
import {cn} from "@/lib/utils";
import {SITE_TITLE} from "@/const/lgConst";
interface HeaderProps {
activeTopId: string;
@@ -30,13 +30,13 @@ const Header = ({
}, [auth.user])
return (
<header className="bg-white border-b border-gray-200 sticky top-0 z-40">
<header className="bg-black border-b border-gray-200 sticky top-0 z-40">
<div className="flex items-center justify-between px-4 h-16">
<div className="flex items-center gap-4">
{/* 로고 */}
<div className="flex items-center gap-2 cursor-pointer w-30 h-15 justify-center">
<Image
src="/logo.png" // public/logo.png
src="/logo_transparent.png" // public/logo.png
alt="브랜드 로고"
width={200}
height={80}
@@ -56,32 +56,26 @@ const Header = ({
type="button"
onClick={() => onNavigate(m.path)}
className={cn(
"relative h-10 inline-flex items-center font-semibold transition-colors cursor-pointer",
"content-text-base bg-transparent px-1",
"relative h-8 inline-flex items-center font-bold transition-colors cursor-pointer",
"content-text-lg bg-transparent px-1",
active
? "text-primary"
: "text-secondary-hover"
? "text-header-primary"
: "text-header-secondary-hover"
)}
>
{m.label}
{/* 선택 표시(밑줄) */}
{active && (
<span className="absolute left-0 right-0 -bottom-[2px] h-[2px] bg-primary" />
)}
</button>
);
})}
</nav>
</div>
<div className="flex justify-between items-center">
<h1 className="font-bold content-text-2xl">{DASHBOARD_YEAR}년도 가전보급률 Dashboard</h1>
<h1 className="font-bold content-text-2xl text-header-color">{SITE_TITLE}</h1>
</div>
{/* 우측 컨트롤 */}
<div className="flex items-center gap-4">
<span className="text-sm text-gray-600 hidden sm:inline font-bold">{userInfo?.userName || ""}</span>
<span className="content-text-base text-header-color hidden sm:inline font-bold">{userInfo?.userName || ""}</span>
<Button
variant="ghost"
size="sm"
className="gap-2"
onClick={() => onNavigate("/logout")}

View File

@@ -0,0 +1,58 @@
"use client";
import React, { createContext, useCallback, useContext, useMemo, useRef } from "react";
import type { SelectedMap } from "@/types/common";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
export type ExcelExportContext =
| { isTotal: true; filterValue: SelectedMap }
| { isTotal: false; filterValue: CategoryFilterValue };
type ExcelExporter = (ctx: ExcelExportContext) => void | Promise<void>;
type LayoutFilterContextValue = ExcelExportContext & {
registerExcelExporter: (exporter: ExcelExporter | null) => void;
requestExcelExport: () => Promise<void>;
};
const LayoutFilterContext = createContext<LayoutFilterContextValue | null>(null);
export const LayoutFilterProvider = ({
value,
children,
}: {
value: ExcelExportContext;
children: React.ReactNode;
}) => {
const exporterRef = useRef<ExcelExporter | null>(null);
const registerExcelExporter = useCallback((exporter: ExcelExporter | null) => {
exporterRef.current = exporter;
}, []);
const requestExcelExport = useCallback(async () => {
const exporter = exporterRef.current;
if (!exporter) {
console.warn("Excel exporter is not registered.");
return;
}
await exporter(value);
}, [value]);
const ctxValue = useMemo<LayoutFilterContextValue>(
() => ({
...value,
registerExcelExporter,
requestExcelExport,
}),
[value, registerExcelExporter, requestExcelExport]
);
return <LayoutFilterContext.Provider value={ctxValue}>{children}</LayoutFilterContext.Provider>;
};
export const useLayoutFilter = () => {
const ctx = useContext(LayoutFilterContext);
if (!ctx) throw new Error("useLayoutFilter must be used within LayoutFilterProvider");
return ctx;
};

View File

@@ -1,17 +1,21 @@
"use client";
import {ReactNode, useState} from "react";
import { usePathname, useRouter } from "next/navigation";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
import Header from "./Header";
import SubMenu from "./SubMenu";
import TotalFilter from "@/components/layout/TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {ReactNode, useEffect, useRef, useState} from "react";
import {usePathname, useRouter} from "next/navigation";
import {cn} from "@/lib/utils";
import {Button} from "@/components/ui/button";
import {SelectedMap} from "@/types/common";
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
import {categoryTarget, totalFilters} from "@/config/filter.data";
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
import Header from "./Header";
import SubMenu from "./SubMenu";
import TotalFilter from "./TotalFilter";
import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
import ExcelDownloadButton from "./ExcelDownloadButton";
import {LayoutFilterProvider} from "./LayoutFilterContext";
import {LAST_YEAR, PRODUCTS_FILTER_ITEM} from "@/const/lgConst";
import {ProductsFilterItem} from "@/types/lg";
import {ArrowUp, Filter} from "lucide-react";
type MainLayoutProps = {
children: ReactNode;
@@ -27,33 +31,49 @@ const buildDefaultTotalValue = (): SelectedMap => {
return init;
};
export const buildDefaultCategoryValue = (): CategoryFilterValue => {
const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
const initProduct = categoryFilterItems.items[0];
const initType = {label:"보유", value:CategoryTargetType.PENETRATION}
const firstTarget = categoryTarget.find((x) => x.type === initType.value)?.children?.[0]?.target;
const firstTarget = categoryTarget.find((x) => x.type.includes(initType.value))?.children[0];
const initTarget = firstTarget ?? { value: CategoryTargetData.PROFILE, label: "Profile"};
return {
product: "냉장고",
year: LAST_YEAR,
product: initProduct,
type: initType,
target: firstTarget ?? CategoryTargetData.PROFILE,
target: initTarget,
};
};
const buildTotalPartDescription = (pathname:string) => {
return pathname.match("penetration")
? "■ 보급률: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>보유하고 있는 비율</strong>"
: "■ 구매율: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>구매한 비율</strong>";
}
const MainLayout = ({ children }: MainLayoutProps) => {
const router = useRouter();
const pathname = usePathname();
const scrollRef = useRef<HTMLDivElement | null>(null);
const [showScrollTop, setShowScrollTop] = useState(false);
const isTotal = pathname.startsWith("/total");
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
const subMenus = isTotal ? totalSubMenus : categorySubMenus;
const activeSub = subMenus.find((m) => m.path.startsWith(pathname)) ?? subMenus[0];
const activeSub = subMenus.find((m) => pathname.startsWith(m.path)) ?? subMenus[0];
const [isTotalFilterOpen, setIsTotalFilterOpen] = useState(true);
const [isCategoryFilterOpen, setIsCategoryFilterOpen] = useState(true);
const isFilterOpen = isTotal ? isTotalFilterOpen : isCategoryFilterOpen;
const categoryFilterItems = PRODUCTS_FILTER_ITEM.find((m) => pathname.match?.(m.path)) ?? PRODUCTS_FILTER_ITEM[0];
const totalPartDescription = buildTotalPartDescription(pathname);
const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue());
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue(categoryFilterItems));
const prevIsTotalRef = useRef<boolean>(isTotal);
const movePage = (path: string) => {
router.push(path);
@@ -64,62 +84,122 @@ const MainLayout = ({ children }: MainLayoutProps) => {
else setIsCategoryFilterOpen((v) => !v);
};
const handleExcelDownload = async () => {
// TODO: 다운로드 구현 필요
console.log("Excel download:", { pathname, top: activeTop.id, sub: activeSub.id });
const onScrollContent = () => {
const el = scrollRef.current;
if (!el) return;
setShowScrollTop(el.scrollTop > 120);
};
const scrollToTop = () => {
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
};
useEffect(() => {
const prevIsTotal = prevIsTotalRef.current;
// 1) category -> total : 아무것도 안 함 (여기서 setCategoryValue 하면 1번 더 렌더됨)
if (isTotal) {
prevIsTotalRef.current = isTotal;
return;
}
// 2) total -> category : 들어오는 순간에만 초기화
if (prevIsTotal) {
setCategoryValue(buildDefaultCategoryValue(categoryFilterItems));
prevIsTotalRef.current = isTotal;
return;
}
// 3) category 내부 이동(카테고리 path 바뀜 등) : product만 동기화
const nextProduct = categoryFilterItems.items[0];
setCategoryValue((prev) => {
if (prev.product === nextProduct) return prev;
return { ...prev, product: nextProduct };
});
prevIsTotalRef.current = isTotal;
}, [isTotal, categoryFilterItems]);
return (
<div className="min-h-screen flex flex-col bg-transparent">
<Header
activeTopId={activeTop.id}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col bg-lg-main-body p-1 pl-6">
<SubMenu
subMenu={subMenus}
activeSubId={activeSub.id}
<div className="h-screen flex flex-col bg-transparent overflow-hidden">
<LayoutFilterProvider
value={isTotal? { isTotal: true, filterValue: totalValue } : { isTotal: false, filterValue: categoryValue }}
>
<Header
activeTopId={activeTop.id}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0">
<div className="shrink-0 flex items-center justify-between px-2 py-1">
<button
type="button"
onClick={toggleFilter}
className={cn(
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm",
"select-none"
)}
>
필터 <span className="text-sm leading-none">{isFilterOpen ? "▲" : "▼"}</span>
</button>
<Button
variant="excel"
className="h-8 px-3 text-sm font-semibold content-text-sm"
onClick={handleExcelDownload}>
Excel 다운로드
</Button>
</div>
{isFilterOpen && (
<div className="shrink-0">
{isTotal ? (
<TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} />
) : (
<CategoryFilter value={categoryValue} onChange={setCategoryValue} />
<div className="flex-1 min-h-0 flex flex-col bg-lg-main-body p-1 pl-6">
<SubMenu
subMenu={subMenus}
activeSubId={activeSub.id}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="shrink-0 flex items-center justify-between px-2 py-1">
<div className="flex">
<button
type="button"
onClick={toggleFilter}
className={cn(
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm cursor-pointer",
"select-none"
)}
>
<Filter className="h-4 w-4 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
필터 <span className="text-sm leading-none mb-1">{isFilterOpen ? "▲" : "▼"}</span>
</button>
{isTotal && (
<div className={"ml-5 content-text-sm"} dangerouslySetInnerHTML={{__html: totalPartDescription}}>
</div>
)}
</div>
)}
<ExcelDownloadButton/>
</div>
{/* ✅ 실제 콘텐츠만 스크롤 */}
<div className="flex-1 min-h-0 overflow-auto">
<div className="p-3">{children}</div>
{isFilterOpen && (
<div className="shrink-0">
{isTotal ? (
<TotalFilter filters={totalFilters} value={totalValue} onChange={setTotalValue} />
) : (
<CategoryFilter filterItems={categoryFilterItems} value={categoryValue} onChange={setCategoryValue} />
)}
</div>
)}
<div className="relative flex-1 min-h-0">
<div
ref={scrollRef}
onScroll={onScrollContent}
className="h-full overflow-auto"
>
<div className="p-3 pb-8">
{children}
</div>
</div>
{showScrollTop && (
<button
type="button"
onClick={scrollToTop}
aria-label="위로 가기"
className={cn(
"absolute -bottom-2 right-4 z-20",
"h-8 w-8 rounded-full",
"bg-gray-900/80 text-white hover:bg-primary",
"flex items-center justify-center"
)}
>
<ArrowUp className="h-5 w-5" />
</button>
)}
</div>
</div>
</div>
</div>
</div>
</LayoutFilterProvider>
</div>
);
}

View File

@@ -29,7 +29,7 @@ const SubMenu = ({
"border border-gray-200",
"-ml-px first:ml-0 rounded-tl-lg rounded-tr-lg cursor-pointer", // 탭이 서로 '붙어' 보이게
active
? "bg-primary text-primary-foreground z-40"
? "bg-primary text-primary-foreground z-10"
: "bg-white-hover text-secondary"
)}
style={active ? {

View File

@@ -67,8 +67,8 @@ const TotalFilter = ({
<div className="flex w-[140px] shrink-0 items-center gap-2 px-3 py-2">
<ChevronRight className="h-4 w-4 text-gray-700" />
<span className="text-sm font-semibold text-gray-900 content-text-sm">
{row.variableName}
</span>
{row.variableName}
</span>
</div>
{/* 우측 옵션 */}

View File

@@ -0,0 +1,43 @@
"use client";
import {bannerType} from "@/components/lge-dashboard/types";
import {Filter} from "lucide-react";
type BannerButtonsProps = {
banners: bannerType[];
selectedBanner: bannerType;
onSelectBanner: (banner: bannerType) => void;
};
const BannerButtons = ({
banners,
selectedBanner,
onSelectBanner
}: BannerButtonsProps) => {
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-center font-bold p-1">
<Filter className="h-4 w-4 -ml-2 mr-1 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
구분 필터
</div>
{banners.map((banner) => (
<button
key={banner.variable}
onClick={() => onSelectBanner(banner)}
className={`
px-4 py-1.5 text-sm font-bold rounded-lg transition-colors cursor-pointer
${
selectedBanner === banner
? "bg-primary text-primary-foreground"
: "bg-gray-100 text-gray-700 hover:bg-primary hover:text-primary-foreground"
}
`}
>
{banner.variableName}
</button>
))}
</div>
);
}
export default BannerButtons;

View File

@@ -0,0 +1,52 @@
"use client";
import dynamic from "next/dynamic";
import type { EChartsOption } from "echarts";
import { CHART_HEIGHTS } from "@/const/chartConst";
import {useResizeKey} from "@/hooks/useResize";
const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false });
type BaseEChartProps = {
option: EChartsOption;
height?: number | string;
className?: string; // wrapper용
contentClassName?: string; // 안쪽 wrapper
chartClassName?: string; // ReactECharts용
/** echarts-for-react의 notMerge/lazyUpdate 옵션 필요 시 */
notMerge?: boolean;
lazyUpdate?: boolean;
/** echarts-for-react 이벤트 바인딩(예: legendselectchanged) */
onEvents?: Record<string, (params: unknown) => void>;
};
const BaseEChart = ({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
notMerge = true,
lazyUpdate = false, //이거 켜져있으면 오류남 Cannot read properties of undefined (reading 'getRawIndex')
onEvents,
}: BaseEChartProps) => {
const resizeKey = useResizeKey(150);
return (
<div className={className} style={{ display: "flex", flexDirection: "column", height: height }}>
<div className={contentClassName} style={{ flex: 1, minHeight: 0 }}>
<ReactECharts
key={resizeKey}
option={option}
className={chartClassName}
style={{ width: "100%", height: "100%" }}
notMerge={notMerge}
lazyUpdate={lazyUpdate}
onEvents={onEvents}
/>
</div>
</div>
);
}
export default BaseEChart;

View File

@@ -0,0 +1,8 @@
const BottomDescription = ({description}:{description:string}) => {
return (
<div className="content-text-sm mt-2" dangerouslySetInnerHTML={{__html: description}}>
</div>
);
}
export default BottomDescription;

View File

@@ -0,0 +1,10 @@
const SectionTitle = ({title}:{title:string}) => {
return (
<div className="font-semibold flex items-center gap-2">
<span className="w-3 h-3 bg-primary" />
{title}
</div>
);
}
export default SectionTitle;

View File

@@ -0,0 +1,37 @@
"use client";
import type React from "react";
import { cn } from "@/lib/utils";
type Props = {
label?: string;
title?: string;
rightSlot?: React.ReactNode;
className?: string;
children: React.ReactNode;
};
export const Card = ({
label,
title,
rightSlot,
className,
children }: Props) =>
{
return (
<div className={cn("lg-category-card", className)}>
{label && <div className="lg-category-card__label">{label}</div>}
{(title || rightSlot) && (
<div className="flex items-start justify-between gap-3 pt-2">
{title && <div className="content-text-base font-semibold">{title}</div>}
{rightSlot && <div className="shrink-0">{rightSlot}</div>}
</div>
)}
<div className="pt-3">{children}</div>
</div>
);
}
export default Card;

View File

@@ -0,0 +1,286 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import { buildLgPalette } from "../color";
import { GroupedOverlayBarData, ShowLabel} from "../types";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
import {AXIS_HIDE_STYLE} from "@/const/lgConst";
import { CHART_HEIGHTS, LEGEND_ITEM_SIZE } from "@/const/chartConst";
import {makeTotalBasePct} from "@/lib/lg-dashboard";
type Props = {
data: GroupedOverlayBarData;
height?: number | string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
// 연도 legend(좌측)
showYearLegend?: boolean;
yearTotalColor?: Record<string, string>;
yearFocusColor?: Record<string, string>;
};
const GroupedOverlayBar = ({
data,
height = CHART_HEIGHTS.DEFAULT,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend = true,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const years = data.years;
const totalName = data.totalName ?? "전체";
const focusName = data.focusName ?? "LG";
const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]);
const [yearSelected, setYearSelected] = useState<Record<string, boolean>>(() =>
Object.fromEntries(yearLabels.map((yl) => [yl, true]))
);
const option = useMemo(() => {
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 40, bottom: 10, containLabel: true};
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
const expandedCategories: string[] = [];
data.categories.forEach((cat, catIdx) => {
years.forEach(year => {
expandedCategories.push(`${year}년 ${cat}`);
});
// 카테고리 사이에 빈 공간 추가 (마지막 제외)
if (catIdx < data.categories.length - 1) {
expandedCategories.push(''); // 빈 항목
}
});
const defaultXAxis: EChartsOption["xAxis"] = {
type: "category",
data: expandedCategories,
...AXIS_HIDE_STYLE
};
// 연도별 색: 없으면 기본값(전체=회색, LG=빨강 계열)
const totalTokens = years.map((y, i) => {
const t = yearTotalColor?.[String(y)];
return t ?? (["--chart-1-t", "--chart-2-t", "--chart-3-t"][i] ?? "--lg-gray-300");
});
const focusTokens = years.map((y, i) => {
const t = yearFocusColor?.[String(y)];
return t ?? (["--chart-1", "--chart-2", "--chart-3"][i] ?? "--lg-red-500");
});
const totalColors = buildLgPalette(totalTokens);
const focusColors = buildLgPalette(focusTokens);
// 연도 legend가 실제로 렌더되려면 "name=24년" series가 있어야 함 (bar가 아닌 line으로)
const yearLegendSeries: SeriesOption[] = showYearLegend
? years.map((y, yi) => ({
id: `__year__|${y}`,
name: `${y}년`,
type: "line",
data: [],
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: focusColors[yi], width: 6 },
itemStyle: { color: focusColors[yi] },
}))
: [];
const series: SeriesOption[] = [];
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const isOn = yearSelected[yearLabel];
const totalRow = data.total?.[yi] ?? [];
const focusRow = data.focus?.[yi] ?? [];
// 각 카테고리별로 데이터 배치
const totalData: (number | null)[] = [];
const focusData: (number | null)[] = [];
data.categories.forEach((cat, ci) => {
years.forEach((y, yIdx) => {
if (yIdx === yi) {
totalData.push(isOn ? (totalRow[ci] ?? null) : null);
focusData.push(isOn ? (focusRow[ci] ?? null) : null);
} else {
totalData.push(null);
focusData.push(null);
}
});
// 카테고리 사이에 null 추가 (마지막 제외)
if (ci < data.categories.length - 1) {
totalData.push(null);
focusData.push(null);
}
});
// (1) 전체(회색)
series.push({
id: `total|${year}`,
name: `${year}년-${totalName}`,
type: "bar",
z: 1,
barMaxWidth: 42,
emphasis: { disabled: true },
itemStyle: { color: totalColors[yi] },
data: totalData,
});
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
// (2) LG(빨강) - 같은 위치에 겹침
series.push({
id: `focus|${year}`,
name: `${year}년-${focusName}`,
type: "bar",
z: 2,
barMaxWidth: 42,
barGap: "-100%",
emphasis: { disabled: true },
itemStyle: { color: focusColors[yi] },
label: showLabel
? ({
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
} as any)
: undefined,
data: focusData,
});
}
const YEAR_ITEM_W = LEGEND_ITEM_SIZE.WIDTH;
const YEAR_ITEM_H = LEGEND_ITEM_SIZE.HEIGHT;
const YEAR_RADIUS = LEGEND_ITEM_SIZE.RADIUS;
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels,
selected: yearSelected,
icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS),
itemWidth: YEAR_ITEM_W,
itemHeight: YEAR_ITEM_H,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
return {
tooltip:
tooltip ??
({
trigger: "axis",
axisPointer: { type: "shadow" },
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
const header = arr?.[0]?.axisValueLabel ?? "";
// bar만
const barItems = arr
.filter((p: any) => p?.seriesType === "bar")
.filter((p: any) => p?.value !== null && p?.value !== undefined);
// year -> {total, focus}
const map = new Map<number, { total?: number; focus?: number }>();
for (const p of barItems) {
const sid = String(p.seriesId ?? ""); // total|24, focus|24
const [kind, yStr] = sid.split("|");
const y = Number(yStr);
const e = map.get(y) ?? {};
if (kind === "total") e.total = Number(p.value);
if (kind === "focus") e.focus = Number(p.value);
map.set(y, e);
}
const lines = [...map.keys()]
.sort((a, b) => a - b)
.map((y) => {
const v = map.get(y)!;
const t = v.total ?? 0;
const f = v.focus ?? 0;
const pct = makeTotalBasePct(t, f);
const pctStr = pct > 0 ? ` (${pct}%)` : "";
return `${totalName} ${t} 중 ${focusName} ${f}${pctStr}`;
});
return [header, ...lines].join("<br/>");
},
} as TooltipComponentOption),
legend: yearLegendOpt ?? undefined,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: [...yearLegendSeries, ...series],
};
}, [
years,
data.categories,
data.total,
data.focus,
totalName,
focusName,
tooltip,
grid,
xAxis,
yAxis,
showYearLegend,
legend,
yearTotalColor,
yearFocusColor,
barMaxWidth,
showFocusLabel,
yearLabels,
yearSelected,
]);
const onEvents = useMemo(
() => ({
legendselectchanged: (e: any) => {
const name = String(e?.name ?? "");
if (!yearLabels.includes(name)) return;
const selected = e?.selected as Record<string, boolean>;
setYearSelected((prev) => ({
...prev,
[name]: selected?.[name] ?? true,
}));
},
}),
[yearLabels]
);
return <BaseEChart option={option} height={height} onEvents={onEvents} />;
}
export default GroupedOverlayBar;

View File

@@ -0,0 +1,258 @@
"use client";
import React, { useMemo, useState } from "react";
import type {
GridComponentOption,
LegendComponentOption,
TooltipComponentOption,
XAXisComponentOption,
YAXisComponentOption,
SeriesOption, EChartsOption,
} from "echarts";
import BaseEChart from "../BaseEChart";
import { GroupedStackBarData, ShowLabel} from "../types";
import { buildLgPalette } from "@/components/lge-dashboard/color";
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
import {AXIS_HIDE_STYLE} from "@/const/lgConst";
import { LEGEND_ITEM_SIZE } from "@/const/chartConst";
type Props = {
data: GroupedStackBarData;
height?: number | string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
xAxis?: XAXisComponentOption;
yAxis?: YAXisComponentOption;
legend?: LegendComponentOption;
barMaxWidth?: number;
showFocusLabel?: ShowLabel;
showYearLegend?: boolean;
yearBrandPalette?: Record<string, string[]>;
};
const GroupedStackBar = ({
data,
height,
tooltip,
grid,
xAxis,
yAxis,
legend,
barMaxWidth,
showFocusLabel = "all",
showYearLegend = true,
yearBrandPalette,
}: Props) => {
const years = data.years;
const brands = data.brands;
const yearLabels = useMemo(() => years.map((y) => `${y}년`), [years]);
const [yearSelected, setYearSelected] = useState<Record<string, boolean>>(() =>
Object.fromEntries(yearLabels.map((yl) => [yl, true]))
);
const option = useMemo(() => {
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 60, bottom: 10, containLabel: true};
const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, ...AXIS_HIDE_STYLE };
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
const latestYear = years.at(-1);
console.log(yearBrandPalette, String(latestYear), yearBrandPalette?.[String(latestYear)])
const latestPalette = buildLgPalette(yearBrandPalette?.[String(latestYear)]);
const yearLegendTokens = years.map((y) => {
const tokens = yearBrandPalette?.[String(y)];
const last = tokens?.[tokens.length - 1];
return last ?? "--lg-gray-500";
});
const yearLegendColors = buildLgPalette(yearLegendTokens);
const yearLegendSeries: SeriesOption[] = showYearLegend
? years.map((y, yi) => ({
id: `__year__|${y}`,
name: `${y}년`,
type: "line",
data: [], // 렌더링 없음(legend만)
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: yearLegendColors[yi], width: 6 },
itemStyle: { color: yearLegendColors[yi] },
}))
: [];
const brandLegendSeries: SeriesOption[] = brands.map((brand, bi) => ({
id: `__legend__|${brand}`,
name: brand,
type: "line",
data: [], // 렌더링 없음(legend만)
showSymbol: false,
silent: true,
tooltip: { show: false },
emphasis: { disabled: true },
lineStyle: { color: latestPalette[bi], width: 6 },
itemStyle: { color: latestPalette[bi] },
}));
// 2) 실제 bar series (연도 스택 3개) × (브랜드 N개)
const realSeries: SeriesOption[] = [];
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const palette = buildLgPalette(yearBrandPalette?.[String(year)]);
for (let bi = 0; bi < brands.length; bi++) {
const brand = brands[bi];
const row = data.values?.[yi]?.[bi] ?? [];
const isYearOn = yearSelected[yearLabel];
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
realSeries.push({
id: `${year}|${brand}`,
name: brand,
type: "bar",
stack: `Y${year}`,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? 42,
itemStyle: { color: palette?.[bi] },
label: showLabel
? ({
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
} as any)
: undefined,
data: data.categories.map((_, ci) => (isYearOn ? (row[ci] ?? null) : null)),
});
}
}
// 3) legend 2개: (좌)연도, (우)브랜드
let yearLegendOpt: LegendComponentOption | undefined = showYearLegend
? ({
top: 0,
left: "center",
orient: "horizontal",
data: yearLabels, // yearLegendSeries name과 일치
selected: yearSelected,
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
itemGap: 8,
...legend,
} as LegendComponentOption)
: undefined;
if(yearLegendOpt === undefined && legend !== undefined){
yearLegendOpt = legend;
}
const brandLegendOpt: LegendComponentOption = ({
top: 25,
right: "center",
orient: "horizontal",
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
itemWidth: LEGEND_ITEM_SIZE.WIDTH,
itemHeight: LEGEND_ITEM_SIZE.HEIGHT,
itemGap: 8,
...legend,
data: [...brands].reverse(),
} as LegendComponentOption);
const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt;
return {
tooltip:
tooltip ??
({
trigger: "axis",
axisPointer: { type: "shadow" },
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
const header = arr?.[0]?.axisValueLabel ?? "";
const yearMap = new Map<number, Array<{ brand: string; value: number }>>();
// bar series만 + 값 있는 것만
const barItems = arr
.filter((p: any) => p?.seriesType === "bar")
.filter((p: any) => p?.value !== null && p?.value !== undefined);
barItems.forEach((p: any) => {
const sid = String(p.seriesId ?? "");
const [y, brand] = sid.split("|");
const year = Number(y);
if (!yearMap.has(year)) {
yearMap.set(year, []);
}
yearMap.get(year)!.push({ brand, value: p.value });
});
const lines = Array.from(yearMap.entries())
.sort((a, b) => a[0] - b[0])
.map(([year, brands]) => {
const brandTexts = brands
.toReversed() // 브랜드 역순
.map(item => `${item.brand}: ${item.value}`)
.join(", ");
return `${year}년- ${brandTexts}`;
});
return [header, ...lines].join("<br/>");
},
} as TooltipComponentOption),
legend: legends,
grid: grid ?? defaultGrid,
xAxis: xAxis ?? defaultXAxis,
yAxis: yAxis ?? defaultYAxis,
series: [...yearLegendSeries, ...brandLegendSeries, ...realSeries],
};
}, [
years,
brands,
data.categories,
data.values,
tooltip,
grid,
xAxis,
yAxis,
legend,
showFocusLabel,
showYearLegend,
yearBrandPalette,
yearLabels,
yearSelected,
barMaxWidth,
]);
// 연도 legend 토글 이벤트만 가로채서 yearSelected에 반영
const onEvents = useMemo(
() => ({
legendselectchanged: (e: any) => {
const name = String(e?.name ?? "");
if (!yearLabels.includes(name)) return; // 브랜드 토글은 ECharts 기본 동작 사용
const selected = e?.selected as Record<string, boolean>;
setYearSelected((prev) => ({
...prev,
[name]: selected?.[name] ?? true,
}));
},
}),
[yearLabels]
);
return <BaseEChart option={option} height={height} onEvents={onEvents} />;
};
export default GroupedStackBar;

View File

@@ -0,0 +1,83 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
} from "@/lib/chart-options";
import { BAR_WIDTHS } from "@/const/chartConst";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
};
const HorizontalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
return {
color: palette,
tooltip: tooltip ?? createDefaultTooltip(fmt),
legend: legend ?? createDefaultLegend(),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? createValueAxis(),
yAxis: yAxis ?? createCategoryAxis(data.categories),
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
label: showLabel
? {
show: true,
position: "right",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
};
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default HorizontalBar;

View File

@@ -0,0 +1,103 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import type { ChartData, ValueFormatter } from "../types";
import { buildLgPalette } from "../color";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
createBarSeries,
createReverseTooltip,
createReverseLegend, reverseSeries,
} from "@/lib/chart-options";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
orientation?: "vertical" | "horizontal";
defaultStackKey?: string;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
isReverse?: boolean;
};
const StackBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
orientation = "vertical",
defaultStackKey = "total",
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
isReverse = false,
}: Props) => {
const renderData = useMemo(
() => (isReverse ? reverseSeries(data) : data),
[data, isReverse]
);
const palette = useMemo(() => {
const temp = buildLgPalette(paletteVarNames);
const n = data.series.length; // 원본 기준
const base = temp.slice(0, n);
return isReverse ? [...base].reverse() : base;
}, [paletteVarNames, data.series.length, isReverse]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const isV = orientation === "vertical";
return {
color: palette,
tooltip: tooltip ?? (isReverse ? createReverseTooltip(data, fmt) : createDefaultTooltip(fmt)),
legend: legend ?? (isReverse ? createReverseLegend(data) : createDefaultLegend()),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? (isV ? createCategoryAxis(renderData.categories) : createValueAxis()),
yAxis: yAxis ?? (isV ? createValueAxis() : createCategoryAxis(renderData.categories)),
series: renderData.series.map((s) =>
createBarSeries(s.name, s.data, {
stack: s.stack ?? defaultStackKey,
barMaxWidth,
})
),
};
}, [
data,
renderData,
palette,
valueFormatter,
orientation,
defaultStackKey,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
isReverse,
]);
return <BaseEChart option={option} height={height} className={className} />;
};
export default StackBar;

View File

@@ -0,0 +1,84 @@
"use client";
import { useMemo } from "react";
import type { EChartsOption } from "echarts";
import BaseEChart from "../BaseEChart";
import {ChartData, ShowLabel, ValueFormatter} from "../types";
import { buildLgPalette } from "../color";
import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill";
import {
createDefaultTooltip,
createDefaultLegend,
createDefaultGrid,
createCategoryAxis,
createValueAxis,
} from "@/lib/chart-options";
import { BAR_WIDTHS } from "@/const/chartConst";
type Props = {
data: ChartData;
height?: number | string;
className?: string;
paletteVarNames?: string[];
valueFormatter?: ValueFormatter;
tooltip?: EChartsOption["tooltip"];
legend?: EChartsOption["legend"];
grid?: EChartsOption["grid"];
xAxis?: EChartsOption["xAxis"];
yAxis?: EChartsOption["yAxis"];
barMaxWidth?: number;
showFocusLabel?:ShowLabel;
};
const VerticalBar = ({
data,
height,
className,
paletteVarNames,
valueFormatter,
tooltip,
legend,
grid,
xAxis,
yAxis,
barMaxWidth,
showFocusLabel = "all",
}: Props) => {
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
return {
color: palette,
tooltip: tooltip ?? createDefaultTooltip(fmt),
legend: legend ?? createDefaultLegend(),
grid: grid ?? createDefaultGrid(),
xAxis: xAxis ?? createCategoryAxis(data.categories, false, { axisTick: { alignWithLabel: true } }),
yAxis: yAxis ?? createValueAxis(),
series: data.series.map((s, index) => {
const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length);
return {
name: s.name,
type: "bar",
data: s.data,
emphasis: { disabled: true },
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
label: showLabel
? {
show: true,
position: "top",
formatter: (p: any) => (p?.value ?? "") as any,
}
: undefined,
}
}),
};
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
return <BaseEChart option={option} height={height} className={className} />;
}
export default VerticalBar;

View File

@@ -0,0 +1,21 @@
import {ShowLabel} from "@/components/lge-dashboard";
export const roundedRectIcon = (w: number, h: number, r: number) => {
const rr = Math.max(0, Math.min(r, Math.min(w, h) / 2));
// ECharts legend icon은 'path://' 지원
return `path://M${rr},0 H${w - rr} Q${w},0 ${w},${rr} V${h - rr} Q${w},${h} ${w - rr},${h} H${rr} Q0,${h} 0,${h - rr} V${rr} Q0,0 ${rr},0 Z`;
};
export const getIsShowLabel = (showFocusLabel:ShowLabel, i:number, arrayLength: number ):boolean => {
let isShowLabel = false;
if (showFocusLabel === "all") {
isShowLabel = true;
} else if (showFocusLabel === "last") {
isShowLabel = i === arrayLength - 1;
} else if (showFocusLabel === "first") {
isShowLabel = i === 0;
}
return isShowLabel;
}

View File

@@ -0,0 +1,103 @@
type Hsl = { h: number; s: number; l: number };
const MAX_VAR_DEPTH = 10;
const getCssVarRaw = (varName: string) =>
getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
/** var(--a) / var(--a, fallback) 를 실제 값으로 재귀 해석 */
export const resolveCssVarValue = (varName: string, depth = 0): string | null => {
if (typeof window === "undefined") return null;
if (depth > MAX_VAR_DEPTH) return null;
const raw = getCssVarRaw(varName);
if (!raw) return null;
// "var(--x)" 또는 "var(--x, fallback)" 패턴
const m = raw.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+))?\s*\)$/);
if (m) {
const inner = m[1];
const fallback = m[2]?.trim() ?? null;
return resolveCssVarValue(inner, depth + 1) ?? fallback;
}
return raw;
};
const parseHue = (token: string): number | null => {
const t = token.trim().toLowerCase();
const num = parseFloat(t);
if (!Number.isFinite(num)) return null;
if (t.endsWith("turn")) return num * 360;
if (t.endsWith("rad")) return (num * 180) / Math.PI;
if (t.endsWith("grad")) return num * 0.9;
// deg 또는 단위 없음
return num;
};
const parsePercent = (token: string): number | null => {
const t = token.trim().toLowerCase();
const v = parseFloat(t.replace("%", ""));
if (!Number.isFinite(v)) return null;
// 혹시 "0.81" 같은 값이 들어오면(드물지만) 0~1 범위는 %로 보정
if (!t.includes("%") && v >= 0 && v <= 1) return v * 100;
return v;
};
const parseHslTriplet = (raw: string): Hsl | null => {
// 예: "341.1 100% 32.4%" / "0 0% 85%"
const m = raw.trim().match(/^(-?\d+(\.\d+)?)\s+(\d+(\.\d+)?)%\s+(\d+(\.\d+)?)%$/);
if (!m) return null;
return { h: Number(m[1]), s: Number(m[3]), l: Number(m[5]) };
};
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
export const resolveHslVar = (varName: string): Hsl | null => {
if (typeof window === "undefined") return null;
const raw = resolveCssVarValue(varName);
return raw ? parseHslTriplet(raw) : null;
};
export const hslCss = (hsl: Hsl, alpha = 1) =>
`hsl(${hsl.h} ${hsl.s}% ${hsl.l}% / ${alpha})`;
export const buildLgPalette = (varNames?: string[]): string[] => {
// globals.css에 정의된 스케일을 직접 참조(중첩 var(--chart-1) 회피)
const defaults = varNames ?? [
"--chart-1",
"--chart-2",
"--chart-3",
"--chart-4",
"--chart-5",
"--chart-6",
"--chart-7",
"--chart-8",
"--chart-9",
"--chart-10",
];
return defaults.map((v) => {
const hsl = resolveHslVar(v);
return hsl ? hslCss(hsl, 1) : v;
});
};
/** Row 기준 heatmap 배경색: 같은 row 안에서 min~max 상대비율로 칠함 */
export const rowHeatColor = (
value: number,
rowMin: number,
rowMax: number,
low: Hsl,
high: Hsl,
alpha = 0.18
) => {
const t = rowMax === rowMin ? 0.5 : (value - rowMin) / (rowMax - rowMin);
const h: Hsl = {
h: lerp(low.h, high.h, t),
s: lerp(low.s, high.s, t),
l: lerp(low.l, high.l, t),
};
return hslCss(h, alpha);
};

View File

@@ -0,0 +1,218 @@
import {ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, SignStyle} from "@/components/lge-dashboard";
import {BannerKey, BannerRow} from "@/types/lg";
import {formatRowLabel, isGapRow, wrapSampleRow} from "@/lib/lg-dashboard";
import {useEffect, useMemo} from "react";
import {
BANNER_GROUP,
BANNER_KEY_MAP,
GRID_Y_NOT_PADDING,
SITE_TITLE,
} 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 {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {CategoryTargetData} from "@/config/filter.types";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
type SectionSpec = {
title: string;
groupKeys: Array<keyof typeof BANNER_GROUP>;
};
/** 3개 섹션(테이블)도 여기서만 선언 */
const SECTIONS: SectionSpec[] = [
{ title: "가구 형태", groupKeys: ["lifeStage", "household", "age"] },
{ title: "거주 형태", groupKeys: ["occupancy", "housing", "houseSize"] },
{ title: "거주 지역 및 소득 수준", groupKeys: ["region", "income"] },
];
const SEP_R = "lg-table__sep-r";
const getSectionBannerKeys = (spec: SectionSpec): BannerKey[] =>
spec.groupKeys.flatMap((gk) => BANNER_GROUP[gk].keys);
const buildColumns = (spec: SectionSpec, selectedYear:string): DataColumn<BannerRow>[] => {
const columns: DataColumn<BannerRow>[] = [
{
key: "rowLabel",
header: `${selectedYear}년`,
headRowSpan: 2,
rowHead: true,
cellClassName: "lg-table__rowhead",
width: 120,
},
{
key: "total",
header: "전체",
numeric: true,
headRowSpan: 2,
headerClassName: SEP_R,
cellClassName: SEP_R,
width: 80,
},
];
spec.groupKeys.forEach((groupKey) => {
const g = BANNER_GROUP[groupKey];
g.keys.forEach((k, idx) => {
const isLast = idx === g.keys.length - 1;
columns.push({
key: k as any,
header: BANNER_KEY_MAP[k] ?? String(k),
group: g.label,
numeric: true,
headerClassName: isLast ? SEP_R : undefined,
cellClassName: isLast ? SEP_R : undefined,
width: 90,
});
});
});
return columns;
};
type BannerSummaryProps = {
data: BannerRow[];
useChart: boolean;
useYear: boolean;
};
const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
const {filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const buildChartData = (rows: BannerRow[]): ChartData => {
const categories = rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => formatRowLabel(r.rowLabel))
.reverse();
const series = [
{
name:"전체",
data: rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => parseNumber(r.total) ?? null)
.reverse(),
}
];
return { categories, series };
};
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
paint: "text",
zeroText: "-",
};
const sectionRows = useMemo(() => {
return SECTIONS.map((spec) => {
const specTitle = spec.title;
const bannerKeys = getSectionBannerKeys(spec);
const columns = buildColumns(spec, useYear? filterValue.year : "");
// rows가 spec마다 다르면 여기서 가져오도록 구성
const rows =
wrapSampleRow(useYear? data.filter((d) => d.year === filterValue.year) : data)
.map((row) => {
row.rowLabel = formatRowLabel(row.rowLabel);
return row
})
const chartData = buildChartData(rows);
return {
spec,
specTitle,
bannerKeys,
columns,
rows,
chartData,
};
});
}, [data, useYear, filterValue.year]);
useEffect(() => {
registerExcelExporter(async () => {
const product = debouncedFilterValue.product;
const type = debouncedFilterValue.type.label;
const target = debouncedFilterValue.target.value === CategoryTargetData.PROFILE? "Profile" : "보급률 변화"
const sheetName = `${product}_${type}_${target}`
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: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, debouncedFilterValue, sectionRows]);
return (
<div className="flex flex-col gap-6">
{sectionRows.map((sectionRow) => {
return (
<div key={`div_${sectionRow.specTitle}`}>
{
useChart ?
<LeftChartTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
signStyle={signStyleGap}
chart={
<HorizontalBar
data={sectionRow.chartData}
height="100%"
showFocusLabel="none"
legend={{ show: false }}
grid={GRID_Y_NOT_PADDING}
xAxis={{ type: "value", show: false }}
yAxis={{ type: "category", data: sectionRow.chartData.categories, show: false }}
/>
}
chartCell={{ key: "total", startRowIndex: 1 }}
minWidthPx={1200}
starUnder30Sample={true}
/>
:
<DataTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
rows={sectionRow.rows}
signStyle={signStyleGap}
unitText={""}
starUnder30Sample={true}
/>
}
</div>
);
})}
</div>
);
}
export default BannerSummary;

View File

@@ -0,0 +1,164 @@
import {
bannerType,
type DataColumn,
DataTable,
HorizontalBar, SectionTitle, SignStyle,
StackBar
} from "@/components/lge-dashboard";
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
import {totalFilters} from "@/config/filter.data";
import React, {useMemo, useState} from "react";
import {BannerGroupKey, CategoryChartMode, BannerRow} from "@/types/lg";
import {
buildRowLabelSeriesChartData,
buildYearSeriesChartData, formatRowLabel,
isBannerGroupKey, isGapRow,
wrapSampleRow
} from "@/lib/lg-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP} from "@/const/lgConst";
import {createDefaultGrid, reverseCategories} from "@/lib/chart-options";
type CategoryByDataProps = {
selectedYear: string;
title?: string;
chartMode: CategoryChartMode;
allTableData: BannerRow[];
fillGreaterThan5?: boolean;
chartHeight?: number | string;
chartWidth?: number;
}
const banners: bannerType[] = totalFilters.map((filter) => {
return {variable: filter.variable, variableName: filter.variableName}
})
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
paint: "text",
zeroText: "-",
};
const CategoryByData = ({
selectedYear,
title,
chartMode,
allTableData,
fillGreaterThan5,
chartHeight,
chartWidth,
}: CategoryByDataProps) => {
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
const buildColumns = (groupKey: BannerGroupKey, selectedYear:string): DataColumn<BannerRow>[] => {
const columns: DataColumn<BannerRow>[] = [
{
key: "rowLabel",
header: `${selectedYear}년`,
headRowSpan: 2,
rowHead: true,
cellClassName: "lg-table__rowhead",
width: 120,
},
];
const g = BANNER_GROUP[groupKey];
g.keys.forEach((k) => {
columns.push({
key: k as any,
header: BANNER_KEY_MAP[k] ?? String(k),
group: g.label,
numeric: true,
width: 90,
});
});
return columns;
};
const chartData = useMemo(() => {
const excludeRowLabels =["사례수", "gap"];
const chartTargetData = allTableData.filter((row) => row.year === selectedYear || Number(row.year) === Number(selectedYear) - 1);
if(chartMode == "horizontal"){
return reverseCategories(buildYearSeriesChartData(chartTargetData, {excludeRowLabels}));
}
return buildRowLabelSeriesChartData(chartTargetData, {excludeRowLabels});
}, [allTableData, selectedYear, chartMode]);
const tableColumns = useMemo(() => {
const v = selectedBanner.variable;
return isBannerGroupKey(v) ? buildColumns(v, selectedYear) : [];
}, [selectedBanner.variable, selectedYear]);
const tableData = useMemo(() =>
wrapSampleRow(allTableData)
.filter((row) => row.year === selectedYear)
.map((row) => {
row.rowLabel = formatRowLabel(row.rowLabel);
return row
})
, [allTableData, selectedYear]);
return (
<div>
<div className="mb-2 flex items-center pr-6">
{title ? <SectionTitle title={title} /> : <div />}
</div>
<div className="flex gap-6 p-3">
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px`}}>
{(() => {
switch (chartMode) {
case "horizontal":
return (
<HorizontalBar
data={chartData}
height={chartHeight}
showFocusLabel="none"
paletteVarNames={
chartData.series.length === 1 ? ["--chart-1"] : ["--chart-2", "--chart-1"]
}
/>
);
case "stack":
case "reverseStack":
return (
<StackBar
data={chartData}
height={chartHeight}
grid={createDefaultGrid("default", { top: 52 })}
isReverse={chartMode === "reverseStack"}
/>
);
default:
return null;
}
})()}
</div>
<div className="flex items-center">
<BannerButtons
banners={banners}
selectedBanner={selectedBanner}
onSelectBanner={setSelectedBanner}
/>
</div>
<div className="flex-1">
<DataTable
columns={tableColumns}
rows={tableData}
signStyle={signStyleGap}
fillGreaterThan5={fillGreaterThan5}
starUnder30Sample={true}
/>
</div>
</div>
</div>
);
};
export default CategoryByData;

View File

@@ -0,0 +1,58 @@
"use client";
import React from "react";
import { cn } from "@/lib/utils";
import {GaugeColumn, GaugeTable} from "@/components/lge-dashboard";
import Card from "@/components/lge-dashboard/card/Card";
export type GaugeCardTableProps<T> = {
/** 카드 제목 */
title: string;
/** GaugeTable columns */
columns: GaugeColumn<T>[];
/** GaugeTable rows */
rows: T[];
/** GaugeTable 옵션들 (필요한 것만 노출) */
cellHeight?: number;
fillColor?: string;
trackColor?: string;
className?: string;
cardClassName?: string;
tableClassName?: string;
};
const GaugeCardTable = <T extends Record<string, unknown>>(
props: GaugeCardTableProps<T>
) => {
const {
title,
columns,
rows,
cellHeight = 26,
fillColor,
trackColor,
className,
cardClassName,
tableClassName,
} = props;
return (
<div className={cn("w-full", className)}>
<Card label={title} className={cardClassName}>
<div className={cn("w-full", tableClassName)}>
<GaugeTable
columns={columns}
rows={rows}
cellHeight={cellHeight}
fillColor={fillColor}
trackColor={trackColor}
/>
</div>
</Card>
</div>
);
};
export default GaugeCardTable;

View File

@@ -0,0 +1,274 @@
"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import type { DataColumn, SignStyle } from "../types";
import SectionTitle from "../SectionTitle";
import { TABLE_DIMENSIONS } from "@/const/chartConst";
import {isSampleRow} from "@/lib/lg-dashboard";
import {SAMPLE_SIZE_NOTICE, UNIT_TEXT} from "@/const/lgConst";
type MergedChartCell<T> = {
/** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */
key: keyof T;
/** rowSpan 시작 row index (기본 0) */
startRowIndex?: number;
/** rowSpan 수 (기본: rows.length - startRowIndex) */
rowSpan?: number;
/** chart td 클래스 (예: lg-table__sep-r) */
className?: string;
};
type Props<T extends Record<string, unknown>> = {
title?: string;
columns: DataColumn<T>[];
rows: T[];
/** 머지된 셀 안에 렌더할 차트 */
chart: React.ReactNode;
/** 어떤 컬럼을 머지-차트 셀로 교체할지 */
chartCell: MergedChartCell<T>;
/** +/-/0 표기/색상 옵션(선택) */
signStyle?: SignStyle<T>;
wrapperClassName?: string;
tableClassName?: string;
minWidthPx?: number;
starUnder30Sample?: boolean;
unitText?: string;
};
// toNumber는 utils.ts의 parseNumber로 통합됨
function renderSigned(
n: number,
opts: {
display: "number" | "arrow";
showPlus: boolean;
arrowWithNumber: boolean;
zeroText: string;
}
) {
if (n === 0) return opts.zeroText;
if (opts.display === "arrow") {
const arrow = n > 0 ? "▲" : "▼";
const num = Math.abs(n);
return opts.arrowWithNumber ? `${arrow} ${num}` : arrow;
}
if (n > 0) return opts.showPlus ? `+${n}` : `${n}`;
return `${n}`;
}
export default function LeftChartTable<T extends Record<string, unknown>>({
title,
columns,
rows,
chart,
chartCell,
signStyle,
wrapperClassName,
tableClassName,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT,
starUnder30Sample = true,
unitText = UNIT_TEXT,
}: Props<T>) {
const hasGroupHeader = useMemo(
() => columns.some((c) => c.group) || columns.some((c) => c.headRowSpan === 2),
[columns]
);
const groupCells = useMemo(() => {
if (!hasGroupHeader) return [] as Array<
| { 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 }
>;
type Cell =
| { 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 };
const out: Cell[] = [];
let i = 0;
while (i < columns.length) {
const c = columns[i];
if (c.headRowSpan === 2) {
out.push({
kind: "rowspan",
label: c.header,
colSpan: 1,
rowSpan: 2,
className: c.headerClassName,
});
i += 1;
continue;
}
const g = c.group ?? "";
if (!g) {
out.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
i += 1;
continue;
}
let span = 1;
while (
i + span < columns.length &&
(columns[i + span].headRowSpan ?? 1) !== 2 &&
(columns[i + span].group ?? "") === g
) {
span += 1;
}
out.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: columns[i + span -1].headerClassName });
i += span;
}
return out;
}, [columns, hasGroupHeader]);
const display = signStyle?.display ?? "number";
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
const showPlus = signStyle?.showPlus ?? true;
const zeroText = signStyle?.zeroText ?? "-";
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
const zeroCls = signStyle?.zeroTextClassName ?? "";
const start = chartCell.startRowIndex ?? 0;
const rowSpan = chartCell.rowSpan ?? Math.max(0, rows.length - start);
return (
<div className={cn("w-full", wrapperClassName)}>
<div className="mb-2 flex items-center justify-between">
{ title && <SectionTitle title={title} />}
{
(unitText || starUnder30Sample) &&
<div className="ml-auto text-gray-500 content-text-xs font-semibold text-right">
{unitText}
{starUnder30Sample && <><br/>{SAMPLE_SIZE_NOTICE}</>}
</div>
}
</div>
<div className="overflow-x-auto">
<table className={cn("lg-table", tableClassName)} style={{ minWidth: `${minWidthPx}px` }}>
<thead>
{hasGroupHeader ? (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<th
key={`${g.kind}-${idx}`}
className={cn(g.className)}
colSpan={g.colSpan}
rowSpan={g.rowSpan}
>
{g.label}
</th>
))}
</tr>
) : null}
<tr className={hasGroupHeader ? "lg-table__subhead" : undefined}>
{columns
.filter((c) => (c.headRowSpan ?? 1) !== 2)
.map((c) => (
<th key={String(c.key)} className={cn(c.headerClassName)} style={c.width ? { width: c.width } : undefined}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, ri) => {
const sampleRow = isSampleRow(row.rowLabel as string ?? "");
const isSignRow = signStyle?.rowSelector ? signStyle.rowSelector(row, ri) : false;
return (
<tr key={ri}>
{columns.map((c) => {
// 머지-차트 셀
if (c.key === chartCell.key && ri >= start) {
if (ri > start) return null;
return (
<td
key={String(c.key)}
rowSpan={rowSpan}
className={cn(c.cellClassName, chartCell.className)}
style={{ padding: 0, verticalAlign: "middle" }}
>
{chart}
</td>
);
}
// 일반 셀
const raw = c.key in row ? row[c.key] : undefined;
const content = c.render
? c.render(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"
? raw
: String(raw);
const n = c.numeric ? parseNumber(raw) : null;
const shouldSign = isSignRow && (signStyle?.keys ? signStyle.keys.includes(c.key) : !!c.numeric);
if (c.rowHead) {
return (
<th
key={String(c.key)}
scope="row"
className={cn("lg-table__rowhead", c.cellClassName)}
style={c.width ? { width: c.width } : undefined}
>
{content}
</th>
);
}
if (!shouldSign) {
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
const isStar = starUnder30Sample && sampleRow && numContent < 30;
return (
<td
key={String(c.key)}
className={cn(c.cellClassName)}
style={c.width ? { width: c.width } : undefined}
>
{isStar?`${content}*`:content}
</td>
);
}
// sign row: 값이 없으면 "-" 유지
if (n === null) {
return (
<td key={String(c.key)} className={cn(c.cellClassName)}>
-
</td>
);
}
const cls = n > 0 ? posCls : n < 0 ? negCls : zeroCls;
const txt = renderSigned(n, { display, showPlus, arrowWithNumber, zeroText });
return (
<td key={String(c.key)} className={cn(c.cellClassName, cls)}>
{txt}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,51 @@
import GaugeCardTable from "./GaugeCardTable";
import {LIFE_STAGE_COLUMNS, UNIT_TEXT} from "@/const/lgConst";
import {LifeStageGroup} from "@/types/lg";
import SectionTitle from "../SectionTitle";
import React from "react";
type lifeStageDivProps = {
lifeStageRowsByGroup:LifeStageGroup[];
}
const LifeStageDiv = ({lifeStageRowsByGroup}:lifeStageDivProps) => {
return (
<div className="mt-6">
<SectionTitle title={"LG 가전 보급률 기준 라이프스테이지별 기회 영역"} />
<div className="flex justify-end text-muted-foreground mb-5">
<div className="flex justify-end gap-4 content-text-xs">
<div className="flex items-center gap-2">
<span className="inline-block h-4 w-8 border bg-gray-200 border-gray-300"/>
<span>제품 보유율</span>
</div>
<div className="flex items-center gap-2">
<span
className="inline-block h-4 w-8 border border-gray-300"
style={{ backgroundColor: "hsl(var(--lg-pink-300) / 0.4)" }}
/>
<span>시장 기회공간</span>
</div>
<div className="flex items-center gap-2">
{UNIT_TEXT}
</div>
</div>
</div>
<div className="grid grid-cols-2 gap-4">
{lifeStageRowsByGroup.map((g) => (
<GaugeCardTable
key={g.title}
title={g.title}
columns={LIFE_STAGE_COLUMNS}
rows={g.rows}
/>
))}
</div>
</div>
);
}
export default LifeStageDiv;

View File

@@ -0,0 +1,173 @@
"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import type { ChartData, SignStyle, TopChartTableRow } from "../types";
import SectionTitle from "../SectionTitle";
import { CHART_HEIGHTS, TABLE_DIMENSIONS } from "@/const/chartConst";
import {UNIT_TEXT} from "@/const/lgConst";
import {isCagrRow} from "@/lib/lg-dashboard";
export type TopChartTableProps = {
title?: string;
categories: string[];
rows: TopChartTableRow[];
/** 테이블 상단(헤더 1행) 콜스팬 셀 내부에 렌더될 차트 */
chart?:
| React.ReactNode
| ((ctx: {
/** 테이블 컬럼(=x축) 기준으로 구성된 ChartData */
chartData: ChartData;
}) => React.ReactNode);
/** chart 셀 높이(px) */
chartHeight?: number;
/** 가로 스크롤 min-width */
minWidthPx?: number;
tableClassName?: string;
wrapperClassName?: string;
/** +/-/0 색상/표기 옵션(선택) */
signStyle?: SignStyle<TopChartTableRow>;
fillCAGR?: boolean;
unitText?: string;
};
// toNumber는 utils.ts의 parseNumber로 통합됨
function formatSignedNumber(n: number, zeroText: string, showPlus: boolean) {
if (n === 0) return zeroText;
if (n > 0) return showPlus ? `+${n}` : `${n}`;
return `${n}`;
}
type CellValue = TopChartTableRow["values"][number];
function toCellValue(v: unknown): CellValue {
if (v === null || v === undefined) return v;
if (typeof v === "number" || typeof v === "string") return v;
return String(v);
}
export default function TopChartTable(props: TopChartTableProps) {
const {
title,
rows,
categories,
chart,
chartHeight = CHART_HEIGHTS.DEFAULT,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD,
tableClassName,
wrapperClassName,
signStyle,
fillCAGR = false,
unitText = UNIT_TEXT
} = props;
const display = signStyle?.display ?? "number";
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
const showPlus = signStyle?.showPlus ?? true;
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
const zeroText = signStyle?.zeroText ?? "-";
// 테이블 컬럼(=categories)을 x축으로 사용하는 chartData를 항상 제공
const chartData: ChartData = useMemo(
() => ({
categories,
series: rows.map((r) => ({
name: r.label,
data: r.values.map((v) => parseNumber(v) ?? null),
})),
}),
[categories, rows]
);
const chartNode = useMemo(() => {
if (!chart) return null;
return typeof chart === "function" ? chart({ chartData }) : chart;
}, [chart, chartData, categories, rows]);
return (
<div className={cn("w-full", wrapperClassName)}>
<div className="mb-2 flex items-center justify-between">
{title ? <SectionTitle title={title} /> : <div />}
{unitText ? <div className="text-gray-500 text-xs font-semibold">{unitText}</div> : null}
</div>
<div className="overflow-x-auto">
<table
className={cn("lg-table", tableClassName)}
style={{ minWidth: `${minWidthPx}px` }}
>
<thead>
<tr>
{/* 좌상단: rowhead 헤더(필요 시 표시). HTML과 동일하게 2행 rowspan */}
<th rowSpan={2} className="lg-table__sep-r w-31" style={{ whiteSpace: "nowrap" }}>
</th>
<td colSpan={categories.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
</td>
</tr>
<tr className="lg-table__subhead">
{categories.map((c) => (
<th key={c} className={"content-text-xs"}>{c}</th>
))}
</tr>
</thead>
<tbody>
{rows.map((r, ri) => {
const isSignRow = !!(signStyle?.rowSelector && signStyle.rowSelector(r, ri));
const cagrRow = isCagrRow(r.label as string ?? "");
const total = parseNumber(r.total);
return (
<tr key={`${r.label}-${ri}`}>
<th scope="row" className="lg-table__rowhead lg-table__sep-r content-text-sm">
{r.label}
</th>
{categories.map((_, ci) => {
const raw = r.values?.[ci];
const n = parseNumber(raw);
// 일반 행
if (!isSignRow) {
if (n === null) return <td key={ci}>-</td>;
const isFill = fillCAGR && cagrRow && total && n > total + 5;
const txt = n.toLocaleString();
return <td key={ci} className={cn(isFill? "bg-red-200" :"")}>{txt}</td>;
}
// sign row
if (n === null) return <td key={ci}>-</td>;
if (n === 0) return <td key={ci}>{zeroText}</td>;
const cls = n > 0 ? posCls : negCls;
if (display === "arrow") {
const arrow = n > 0 ? "▲" : "▼";
const num = Math.abs(n);
return (
<td key={ci} className={cls}>
{arrow}
{arrowWithNumber ? ` ${num}` : ""}
</td>
);
}
return (
<td key={ci} className={cls}>
{formatSignedNumber(n, zeroText, showPlus)}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -0,0 +1,22 @@
export * from "./types";
export { default as BaseEChart } from "./BaseEChart";
export { default as VerticalBar } from "./chart/VerticalBar";
export { default as HorizontalBar } from "./chart/HorizontalBar";
export { default as StackBar } from "./chart/StackBar";
export { default as GroupedStackBar} from "./chart/GroupedStackBar";
export { default as GroupedOverlayBar} from "./chart/GroupedOverlayBar";
export { default as DataTable } from "./table/DataTable";
export { default as GaugeTable } from "./table/GaugeTable";
export { default as TopChartTable } from "./combo/TopChartTable";
export { default as LeftChartTable } from "./combo/LeftChartTable";
export { default as GaugeCardTable } from "./combo/GaugeCardTable";
export { default as CategoryByData } from "./combo/CategoryByData"
export { default as CardDefault } from "./card/Card";
export { default as SectionTitle } from "./SectionTitle";
export { default as BottomDescription } from "./BottomDescription";

View File

@@ -0,0 +1,57 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTargetData} from "@/config/filter.types";
import Profile from "./category-page/Profile";
import PenetrationChange from "./category-page/PenetrationChange";
import {BannerRow, CategoryResolvedField, StatisticsRequest} from "@/types/lg";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {useMemo} from "react";
import {buildCategoryFilter, buildPageModeConfig} from "@/lib/lg-dashboard";
import {BANNER_GROUP_KEY} from "@/const/lgConst";
import {useBannerStatisticsQuery} from "@/hooks/useLgStatisticsQuery";
import CategoryDetail from "@/components/lge-dashboard/sub-page/category-page/CategoryDetail";
export type CategoryPageProps = {
fields: CategoryResolvedField[];
variableIdMap: Record<string, string>;
dataMap:Record<string, BannerRow[]> | undefined;
}
const PAGE_COMPONENTS: Partial<Record<CategoryTargetData, React.ComponentType<CategoryPageProps>>> = {
[CategoryTargetData.PROFILE]: Profile,
[CategoryTargetData.PENETRATION_CHANGE]: PenetrationChange,
[CategoryTargetData.BRAND]: CategoryDetail,
[CategoryTargetData.TYPE_SPEC]: CategoryDetail,
[CategoryTargetData.BEHAVIOR]: CategoryDetail,
[CategoryTargetData.PURCHASE_CHANNEL]: CategoryDetail,
[CategoryTargetData.PAYMENT_METHOD]: CategoryDetail,
};
const CategoryPage = () => {
const { isTotal, filterValue } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const { fields, variableIdMap } = useMemo(() => {
return buildPageModeConfig(debouncedFilterValue);
}, [debouncedFilterValue]);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap,
bannerIdList: BANNER_GROUP_KEY,
filterCondition: buildCategoryFilter(debouncedFilterValue),
option: { useCache: false, lastYear: false, decimalPoint: 0 },
};
}, [variableIdMap, debouncedFilterValue]);
const { data } = useBannerStatisticsQuery(req);
const dataMap = data?.statisticsDataMap;
const target = debouncedFilterValue.target;
const Comp = PAGE_COMPONENTS[target.value]
if(isTotal) return null;
return Comp ? <Comp fields={fields} variableIdMap={variableIdMap} dataMap={dataMap} /> : null;
}
export default CategoryPage;

View File

@@ -0,0 +1,81 @@
import {CategoryPageProps} from "@/components/lge-dashboard/sub-page/CategoryPage";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {useEffect, useMemo} from "react";
import {BannerRow, PageData} from "@/types/lg";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
import {BANNER_GROUP, BANNER_KEY_MAP, SITE_TITLE, YEARS} from "@/const/lgConst";
import {CategoryByData} from "@/components/lge-dashboard";
const CategoryDetail = ({
fields,
dataMap
}:CategoryPageProps) => {
const {filterValue, registerExcelExporter} = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const tableDataArray = useMemo<PageData<BannerRow>[]>(() => {
const tempTableDataArray = fields.map((f) => {
const dataLength = dataMap?.[f.requestKeyResolved].filter((row) => row.rowLabel !=`사례수`).length;
return {
title: typeof f.title === "string"? f.title : f.title[debouncedFilterValue.type.value],
chartMode:f.chartMode,
data: dataLength && dataLength > 0 ? dataMap[f.requestKeyResolved] : []
};
});
//사례수만 있는 테이블은 아예 제외
return tempTableDataArray.filter((tableData) => tableData.data.length > 0);
}, [debouncedFilterValue, fields, dataMap]);
useEffect(() => {
registerExcelExporter(async () => {
const product = debouncedFilterValue.product;
const type = debouncedFilterValue.type.label;
const target = debouncedFilterValue.target.label.replaceAll('/', '_');
const sheetName = `${product}_${type}_${target}`
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: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, debouncedFilterValue, tableDataArray]);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
selectedYear={filterValue.year}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default CategoryDetail;

View File

@@ -0,0 +1,40 @@
'use client'
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {BannerRow} from "@/types/lg";
import {CategoryPageProps} from "@/components/lge-dashboard/sub-page/CategoryPage";
import {LAST_YEAR} from "@/const/lgConst";
const PenetrationChange = ({
dataMap
}:CategoryPageProps) => {
const penetrationChangeData = useMemo<BannerRow[]>(() => {
if (dataMap === undefined) return [];
const tempProfileData: BannerRow[] = [];
Object.keys(dataMap).forEach(requestKey => {
const data = dataMap[requestKey];
tempProfileData.push(
...data.filter((r) => r.rowLabel === `사례수` && r.year === LAST_YEAR),
...data.filter((r) => r.rowLabel === `보유`)
.map((row) => {
return {
...row,
rowLabel: row.year,
}
}));
});
console.log(tempProfileData)
return tempProfileData;
}, [dataMap]);
return(
<BannerSummary data={penetrationChangeData} useChart={true} useYear={false} />
);
}
export default PenetrationChange

View File

@@ -0,0 +1,79 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {BannerRow} from "@/types/lg";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import { calcGapBannerRow } from "@/lib/lg-dashboard";
import {YEARS} from "@/const/lgConst";
import {CategoryTargetType} from "@/config/filter.types";
import {CategoryPageProps} from "@/components/lge-dashboard/sub-page/CategoryPage";
const Profile = ({
dataMap
}:CategoryPageProps) => {
const { filterValue } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const profileData = useMemo<BannerRow[]>(() => {
if (dataMap === undefined) return [];
const targetMap = {
[CategoryTargetType.PENETRATION]: "보유",
[CategoryTargetType.PURCHASE]: "해당년도",
[CategoryTargetType.INTENDED]: "향후구매",
}
const tempProfileData: BannerRow[] = [];
Object.keys(dataMap).forEach(requestKey => {
const data = dataMap[requestKey];
if(requestKey.toLowerCase().endsWith("count")){
tempProfileData.push(
...data.filter((r) => r.rowLabel == `MEAN`)
.map((row) => {
return {
...row,
rowLabel: "보유대수",
}
})
);
}
else{
const target = debouncedFilterValue.type.value;
tempProfileData.push(...data.filter((r) => r.rowLabel == `사례수`));
const targetData =
data.filter((r) => r.rowLabel == targetMap[target])
.map((row) => {
return {
...row,
rowLabel: row.year,
}
})
tempProfileData.push(...targetData);
YEARS.forEach((year, idx) => {
const after = targetData.find((r) => r.year == year)
const before = idx == 0? undefined : targetData.find((r) => r.year == YEARS[idx-1]);
if (after && before) {
tempProfileData.push(calcGapBannerRow(after, before));
}
});
}
});
return tempProfileData.sort((a, b) => Number(a.rowLabel === "보유대수") - Number(b.rowLabel === "보유대수"));
}, [debouncedFilterValue, dataMap]);
return (
<BannerSummary data={profileData} useChart={false} useYear={true} />
);
}
export default Profile;

View File

@@ -0,0 +1,267 @@
"use client";
import { useMemo } from "react";
import type React from "react";
import { cn, parseNumber } from "@/lib/utils";
import type { DataColumn, SignDisplayMode, SignStyle } from "../types";
import SectionTitle from "../SectionTitle";
import {isCagrRow, isSampleRow} from "@/lib/lg-dashboard";
import {SAMPLE_SIZE_NOTICE, UNIT_TEXT} from "@/const/lgConst";
type Props<T extends Record<string, unknown>> = {
columns: DataColumn<T>[];
rows: T[];
title?: string;
className?: string;
wrapperClassName?: string;
signStyle?: SignStyle<T>;
fillGreaterThan5?: boolean;
fillCAGR?: boolean;
starUnder30Sample?: boolean;
unitText?: string;
};
// parseSignedNumber는 utils.ts의 parseNumber로 통합됨
const defaultFmt = (v: number) =>
Number.isInteger(v) ? String(v) : v.toLocaleString();
const signText = (
v: number,
display: SignDisplayMode,
showPlus: boolean,
arrowWithNumber: boolean,
fmt: (n: number) => string,
zeroText: string
) => {
if (display === "arrow") {
if (v > 0) return arrowWithNumber ? `▲ ${fmt(Math.abs(v))}` : "▲";
if (v < 0) return arrowWithNumber ? `▼ ${fmt(Math.abs(v))}` : "▼";
return zeroText;
}
// number
if (v > 0) return showPlus ? `+${fmt(v)}` : fmt(v);
if (v < 0) return fmt(v); // 음수는 기본적으로 - 포함
return zeroText;
};
const toCellContent = (raw: unknown): React.ReactNode => {
if (raw == null) return "";
if (typeof raw === "string" || typeof raw === "number") return raw;
return String(raw);
};
const DataTable = <T extends Record<string, unknown>>({
columns,
rows,
title,
className,
wrapperClassName,
signStyle,
fillGreaterThan5 = false,
fillCAGR = false,
starUnder30Sample = false,
unitText = UNIT_TEXT,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
// group header(1행): rowspan=2 컬럼(th) + group label(colspan)
const groupCells = useMemo(() => {
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 c = columns[i];
if (c.headRowSpan === 2) {
res.push({ kind: "rowspan", label: c.header, colSpan: 1, rowSpan: 2, className: c.headerClassName });
i++;
continue;
}
const g = c.group;
if (!g) {
// group 미지정: 1칸짜리 blank group 셀
res.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
i++;
continue;
}
// 같은 group 연속 구간 colSpan
let span = 1;
let j = i + 1;
while (j < columns.length && columns[j].headRowSpan !== 2 && columns[j].group === g) {
span++;
j++;
}
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: c.headerClassName });
i = j;
}
return res;
}, [columns, hasGroup]);
const {
rowSelector,
keys,
paint = "text",
display = "number",
showPlus = true,
arrowWithNumber = false,
zeroText = "-",
valueFormatter,
positiveTextClassName = "text-primary font-semibold",
negativeTextClassName = "text-info font-semibold",
zeroTextClassName = "text-gray-600",
positiveCellBg = "hsl(var(--primary) / 0.08)",
negativeCellBg = "hsl(var(--info) / 0.08)",
zeroCellBg = "hsl(var(--lg-gray-200) / 0.6)",
} = signStyle ?? ({} as SignStyle<T>);
const fmt = valueFormatter ?? defaultFmt;
const isSignRow = (row: T, rowIndex: number) =>
!!signStyle && !!rowSelector?.(row, rowIndex);
const isTargetKey = (k: keyof T) => {
if (!signStyle) return false;
if (keys && keys.length) return keys.includes(k);
// keys 미지정이면 numeric 컬럼 전체
const col = columns.find((c) => c.key === k);
return !!col?.numeric;
};
const signClass = (v: number) => {
if (v > 0) return positiveTextClassName;
if (v < 0) return negativeTextClassName;
return zeroTextClassName;
};
const signBg = (v: number) => {
if (v > 0) return positiveCellBg;
if (v < 0) return negativeCellBg;
return zeroCellBg;
};
return (
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
<div className="mb-2 flex items-center justify-between">
{ title && <SectionTitle title={title} />}
{
(unitText || starUnder30Sample) &&
<div className="ml-auto text-gray-500 content-text-xs font-semibold text-right">
{unitText}
{starUnder30Sample && <><br/>{SAMPLE_SIZE_NOTICE}</>}
</div>
}
</div>
<table className={cn("lg-table", className)}>
<thead>
{hasGroup && (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<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
.filter((c) => c.headRowSpan !== 2)
.map((c) => (
<th key={String(c.key)} style={{ width: c.width }} className={c.headerClassName}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rIdx) => {
const sampleRow = isSampleRow(row.rowLabel as string ?? "");
const signRow = isSignRow(row, rIdx);
const total = parseNumber(row.total);
return (
<tr key={rIdx}>
{columns.map((c) => {
const raw: unknown = c.key ? (row[c.key] as unknown) : undefined;
const align = c.align ?? (c.numeric ? "right" : "center");
// headRowSpan=2 컬럼은 thead 2행에서 제외되므로, tbody는 항상 렌더
// sign row + target column이면 색상/표기 적용
const applySign = signRow && isTargetKey(c.key) && !c.rowHead;
if (applySign) {
const n = parseNumber(raw);
const displayText =
n === null ? "-" : signText(n, display, showPlus, arrowWithNumber, fmt, zeroText);
const style: React.CSSProperties =
paint === "cell"
? { textAlign: align, background: signBg(n ?? 0) }
: { textAlign: align };
return (
<td key={String(c.key)} style={style} className={c.cellClassName}>
<span className={cn(n === null ? "text-gray-500" : signClass(n))}>
{displayText}
</span>
</td>
);
}
// 일반 셀
const content: React.ReactNode = c.render
? c.render(row)
: toCellContent(raw);
if (c.rowHead) {
return (
<th
key={String(c.key)}
className={cn("lg-table__rowhead", c.cellClassName)}
style={{ textAlign: align }}
>
{content}
</th>
);
}
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
const isFill = fillGreaterThan5 && total && numContent > total + 5;
const isStar = starUnder30Sample && sampleRow && numContent < 30;
return (
<td key={String(c.key)} style={{ textAlign: align }} className={
cn(c.cellClassName, isFill? "bg-red-200" :"")
}>
{isStar?`${content}*`:content}
</td>
);
})}
</tr>
);
})}
</tbody>
</table>
</div>
);
}
export default DataTable;

View File

@@ -0,0 +1,204 @@
"use client";
import React, { useMemo } from "react";
import { cn, parseNumber } from "@/lib/utils";
import {GaugeColumn} from "../types";
type Props<T extends Record<string, unknown>> = {
columns: GaugeColumn<T>[];
rows: T[];
className?: string;
wrapperClassName?: string;
/** value가 0~100이 아니라 0~1이면 scale=100 */
scale?: number; // 기본 1
/** 색상(기본: primary 채움 + gray 트랙) */
fillColor?: string; // ex) "hsl(var(--primary) / 0.9)"
trackColor?: string; // ex) "hsl(var(--lg-gray-200) / 0.9)"
/** 셀 높이 */
cellHeight?: number; // 기본 26
/** 숫자 표시 여부/포맷 */
valueFormatter?: (v: number) => string;
};
// num은 utils.ts의 parseNumber로 통합됨
const GaugeTable = <T extends Record<string, unknown>>({
columns,
rows,
className,
wrapperClassName,
scale = 1,
fillColor = "hsl(var(--lg-gray-200) / 0.85)",
trackColor = "hsl(var(--lg-pink-300) / 0.2)",
cellHeight = 26,
valueFormatter,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
const groupCells = useMemo(() => {
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 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].headRowSpan !== 2 && columns[j].group === g) {
span++;
j++;
}
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1 });
i = j;
}
return res;
}, [columns, hasGroup]);
const fmt = valueFormatter ?? ((v: number) => String(Math.round(v)));
const clamp01 = (n: number) => Math.max(0, Math.min(1, n));
return (
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
<table className={cn("lg-table", className)} style={{minWidth:"100%"}}>
<colgroup>
{columns.map((c, i) => (
<col
key={`${String(c.key)}-${i}`}
style={{
width:
c.width ??
(c.rowHead ? 50 : 40), // 기본 폭(필요시 숫자 조절)
}}
/>
))}
</colgroup>
<thead>
{hasGroup && (
<tr className="lg-table__group">
{groupCells.map((g, idx) => (
<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.filter((c) => c.headRowSpan !== 2).map((c) => (
<th key={String(c.key)}>
{c.header}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, rIdx) => (
<tr key={rIdx}>
{columns.map((c) => {
const align = c.align ?? (c.rowHead ? "left" : "center");
const cellType = c.cellType ?? "gauge";
if (c.rowHead) {
const raw = row[c.key];
const label = c.render
? c.render(row)
: raw === null || raw === undefined
? ""
: typeof raw === "string" || typeof raw === "number"
? raw
: String(raw);
return (
<th
key={String(c.key)}
className="lg-table__rowhead"
style={{ textAlign: align }}
>
{label}
</th>
);
}
const raw = row[c.key];
const v = parseNumber(raw);
const max = c.max ?? 100;
const ratio = v === null ? 0 : clamp01((v * scale) / max);
const pct = ratio * 100;
const fill = fillColor;
const track = trackColor;
const cellBg =
v === null
? undefined
: `linear-gradient(to right, ${fill} ${pct}%, ${track} 0%)`;
if (cellType === "number") {
return (
<td
key={String(c.key)}
className="px-2 content-text-sm"
style={{ textAlign: align }}
>
{v === null ? "-" : fmt(v)}
</td>
);
}
return (
<td
key={String(c.key)}
className="px-2 content-text-sm"
style={{
textAlign: "left",
height: cellHeight,
whiteSpace: "nowrap",
background: cellBg,
backgroundClip: "padding-box",
}}
>
{v === null ? "-" : fmt(v)}
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
);
}
export default GaugeTable;

View File

@@ -0,0 +1,139 @@
import type React from "react";
import {GAP_WORDING} from "@/const/lgConst";
export type NewNumber = number | null | undefined;
export type ChartSeries = {
/** legend에 노출될 이름 */
name: string;
/** categories와 동일 길이 */
data: NewNumber[];
/** stacked bar 용 */
stack?: string; // 같은 stack 값끼리 누적
};
export type ChartData = {
/** x(세로바)/y(가로바) 카테고리 */
categories: string[];
/** 시리즈(막대/스택 등) */
series: ChartSeries[];
};
/**
* (GroupedStackBar)
* - categories: x축 카테고리(예: 제품)
* - years: 그룹(예: 24/25/26)
* - brands: 스택 구성요소(예: LG/SS/C브랜드)
* - values: [yearIndex][brandIndex][categoryIndex]
*/
export type GroupedStackBarData = {
categories: string[];
years: Array<string | number>;
brands: string[];
values: Array<Array<Array<number | null | undefined>>>;
};
export type GroupedOverlayBarData = {
categories: string[]; // 제품
years: string[]; // 예: [24,25,26]
totalName?: string; // default: "전체"
focusName?: string; // default: "LG"
total: Array<Array<number | null>>; // [yearIndex][categoryIndex]
focus: Array<Array<number | null>>; // [yearIndex][categoryIndex]
};
/** (TopChartTable) HTML 테이블용 row (columns=categories) */
export type TopChartTableRow = {
/** 좌측 rowhead 라벨 */
label: string;
total: number | string | null | undefined;
/** categories 순서대로 값 */
values: Array<number | string | null | undefined>;
};
export type ValueFormatter = (v: number) => string;
export type DataColumn<T> = {
key: keyof T;
header: string;
width?: number | string;
align?: "left" | "center" | "right";
group?: string; // 2단 헤더 그룹
groupKey?:string;// 2단 헤더 그룹
/** group header에서 해당 컬럼 헤더를 rowspan=2로 올릴 때 사용(HTML 테이블과 동일한 구조 지원) */
headRowSpan?: 1 | 2;
rowHead?: boolean; // 첫 컬럼 등 row header
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
/** th 클래스(필요 시 lg-table__sep-r 등 주입) */
headerClassName?: string;
/** td 클래스(필요 시 lg-table__sep-l, lg-table__sep-r 등 주입) */
cellClassName?: string;
render?: (row: T) => React.ReactNode;
};
export type GaugeColumn<T> = {
key: keyof T;
header: string;
width?: number | string;
align?: "left" | "center" | "right";
group?: string;
groupKey?:string;// 2단 헤더 그룹
headRowSpan?: 1 | 2;
rowHead?: boolean;
/** 게이지 최대값 기준(기본 100) */
max?: number;
render?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
cellType?: "gauge" | "number"; // default: "gauge"
};
export type SignDisplayMode = "number" | "arrow";
export type SignStyle<T> = {
/** 어떤 row에 +/ -/ 0 색상표기를 적용할지 선택 */
rowSelector: (row: T, rowIndex: number) => boolean;
/** 어떤 컬럼에 적용할지(미지정 시 numeric 컬럼 전체) */
keys?: (keyof T)[];
/** 색상 적용 방식 */
paint?: "text" | "cell"; // 기본 text
/** 표기 방식 */
display?: SignDisplayMode; // 기본 number
showPlus?: boolean; // number 모드에서 + 표시(기본 true)
/** 0 값 표기(기본 "-") */
zeroText?: string;
/** arrow 모드 옵션 */
arrowWithNumber?: boolean; // ▲ 2 처럼 (기본 false)
/** 값 포맷(기본: 정수면 그대로/그 외 toLocaleString) */
valueFormatter?: (v: number) => string;
/** 색상 커스터마이즈(기본: + primary, - info, 0 gray) */
positiveTextClassName?: string; // 기본 "text-primary font-semibold"
negativeTextClassName?: string; // 기본 "text-info font-semibold"
zeroTextClassName?: string; // 기본 "text-gray-600"
positiveCellBg?: string; // ex) "hsl(var(--primary) / 0.08)"
negativeCellBg?: string; // ex) "hsl(var(--info) / 0.08)"
zeroCellBg?: string; // ex) "hsl(var(--lg-gray-200) / 0.6)"
};
export const signStyleGapRow: SignStyle<TopChartTableRow> = {
rowSelector: (row) => row.label === GAP_WORDING,
display: "arrow",
arrowWithNumber: true,
paint: "text",
};
/** ChartLabel 보여지는 옵션 */
export type ShowLabel = "none" | "all" | "last" | "first";
export type bannerType = {
variable:string;
variableName:string;
}

View File

@@ -0,0 +1,33 @@
'use client'
import { Provider as JotaiProvider } from "jotai";
import {LoadingOverlay} from "@/components/common/LoadingOverlay";
import ReactQueryLoadingSync from "@/components/common/ReactQueryLoadingSync";
import {useState} from "react";
import {QueryClient} from "@tanstack/query-core";
import { QueryClientProvider } from "@tanstack/react-query";
export function AppProvider({ children }: { children: React.ReactNode }) {
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
},
},
})
);
return (
<JotaiProvider>
<QueryClientProvider client={queryClient}>
<ReactQueryLoadingSync />
<LoadingOverlay />
{children}
</QueryClientProvider>
</JotaiProvider>
);
}

View File

@@ -8,7 +8,7 @@ import {
export const totalFilters:TotalFilterItem[] = [
{
variable:"a1",
variable:"lifeStage",
variableName:"라이프 스테이지",
children:[
{ value: "0", label: "전체"},
@@ -21,7 +21,7 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a2",
variable:"income",
variableName:"월 소득 규모",
children:[
{ value: "0", label: "전체"},
@@ -32,8 +32,8 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a3",
variableName:"거주 형태",
variable:"occupancy",
variableName:"입주 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "자가"},
@@ -44,19 +44,20 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a4",
variable:"houseSize",
variableName:"거주 평형",
children:[
{ value: "0", label: "19평 이하"},
{ value: "1", label: "20평형 대"},
{ value: "2", label: "30평형 대"},
{ value: "3", label: "40평형 대"},
{ value: "4", label: "50평형 이상"},
{ value: "0", label: "전체"},
{ value: "1", label: "19평 이하"},
{ value: "2", label: "20평형 대"},
{ value: "3", label: "30평형 대"},
{ value: "4", label: "40평형 대"},
{ value: "5", label: "50평형 이상"},
]
},
{
variable:"a5",
variableName:"주택 형태",
variable:"housing",
variableName:"주거 형태",
children:[
{ value: "0", label: "전체"},
{ value: "1", label: "아파트"},
@@ -67,7 +68,7 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a6",
variable:"region",
variableName:"지역",
children:[
{ value: "0", label: "전체"},
@@ -80,18 +81,19 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a7",
variable:"age",
variableName:"연령대",
children:[
{ value: "0", label: "20대"},
{ value: "1", label: "30대"},
{ value: "2", label: "40대"},
{ value: "3", label: "50대"},
{ value: "4", label: "60대"},
{ value: "0", label: "전체"},
{ value: "2", label: "20대"},
{ value: "3", label: "30대"},
{ value: "4", label: "40대"},
{ value: "5", label: "50대"},
{ value: "6", label: "60대"},
]
},
{
variable:"a8",
variable:"household",
variableName:"가구원 수",
children:[
{ value: "0", label: "전체"},
@@ -114,31 +116,31 @@ export const categoryTargetType: CategoryTargetTypeItem[] = [
},
{
label:"향후 구매",
value: CategoryTargetType.PURCHASE,
value: CategoryTargetType.INTENDED,
},
]
export const categoryTarget: CategoryTargetItem[] = [
{
type: CategoryTargetType.PENETRATION,
type: [CategoryTargetType.PENETRATION],
children:[
{ target: CategoryTargetData.PROFILE, label: "Profile"},
{ target: CategoryTargetData.PENETRATION_CHANGE, label: "보급률 변화"},
{ target: CategoryTargetData.BRAND, label: "브랜드"},
{ target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ target: CategoryTargetData.OWNERSHIP_PATH, label: "보유 경로"},
{ target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"},
{ value: CategoryTargetData.PROFILE, label: "Profile"},
{ value: CategoryTargetData.PENETRATION_CHANGE, label: "보급률 변화"},
{ value: CategoryTargetData.BRAND, label: "브랜드"},
{ value: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ value: CategoryTargetData.BEHAVIOR, label: "보유 경로"},
{ value: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"},
]
},
{
type: CategoryTargetType.PURCHASE,
type: [CategoryTargetType.PURCHASE, CategoryTargetType.INTENDED],
children:[
{ target: CategoryTargetData.PROFILE, label: "Profile"},
{ target: CategoryTargetData.BRAND, label: "브랜드"},
{ target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ target: CategoryTargetData.PURCHASE_BEHAVIOR, label: "구입 행태"},
{ target: CategoryTargetData.PURCHASE_CHANNEL, label: "구매 채널"},
{ target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"},
{ value: CategoryTargetData.PROFILE, label: "Profile"},
{ value: CategoryTargetData.BRAND, label: "브랜드"},
{ value: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"},
{ value: CategoryTargetData.BEHAVIOR, label: "구입 행태"},
{ value: CategoryTargetData.PURCHASE_CHANNEL, label: "구매 채널"},
{ value: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"},
]
},
]

View File

@@ -12,6 +12,7 @@ export type TotalFilterItem = {
export enum CategoryTargetType {
PENETRATION = "PENETRATION",
PURCHASE = "PURCHASE",
INTENDED = "INTENDED"
}
export enum CategoryTargetData {
@@ -19,10 +20,9 @@ export enum CategoryTargetData {
PENETRATION_CHANGE = 21,
BRAND = 12,
TYPE_SPEC = 13,
OWNERSHIP_PATH = 22,
PURCHASE_BEHAVIOR = 31,
BEHAVIOR = 14,
PURCHASE_CHANNEL = 32,
PURCHASE_FORMAT = 14,
PAYMENT_METHOD = 15,
}
export type CategoryTargetTypeItem = {
@@ -31,11 +31,11 @@ export type CategoryTargetTypeItem = {
}
export type TargetChild = {
target: CategoryTargetData;
label: string;
value: CategoryTargetData;
}
export type CategoryTargetItem = {
type: CategoryTargetType;
type: CategoryTargetType[];
children: TargetChild[];
}

View File

@@ -10,7 +10,7 @@ export const topMenus: TopMenuItem[] = [
{
id: "category",
label: "카테고리",
path: "/category/ha-kitchen",
path: "/category/kitchen",
match: (pathname) => pathname.startsWith("/category"),
},
];
@@ -40,23 +40,23 @@ export const totalSubMenus: SubMenuItem[] = [
export const categorySubMenus: SubMenuItem[] = [
{
id: "ha-kitchen",
label: "H&A 주방가전(키친)",
path: "/category/ha-kitchen",
id: "kitchen",
label: "키친솔루션",
path: "/category/kitchen",
},
{
id: "ha-living",
label: "H&A 리빙가전",
path: "/category/ha-living",
id: "living",
label: "리빙솔루션",
path: "/category/living",
},
{
id: "air-solution",
label: "에어솔루션",
path: "/category/air-solution",
id: "es",
label: "ES",
path: "/category/es",
},
{
id: "ms-digital",
label: "MS 디지털가전",
path: "/category/ms-digital",
id: "ms",
label: "MS",
path: "/category/ms",
},
]

141
src/const/chartConst.ts Normal file
View File

@@ -0,0 +1,141 @@
/**
* 차트 관련 상수 정의
* - 차트 높이, Bar 너비, Grid 설정 등
*/
import {GAP_WORDING} from "@/const/lgConst";
/**
* 차트 기본 높이 설정
*/
export const CHART_HEIGHTS = {
DEFAULT: "100%",
COMPACT: 200,
EXPANDED: 320,
} as const;
/**
* Bar 차트의 Bar 너비 설정
*/
export const BAR_WIDTHS = {
DEFAULT: 42,
NARROW: 30,
WIDE: 60,
} as const;
/**
* 차트 Grid 기본 패딩 설정
*/
export const CHART_GRID_DEFAULTS = {
DEFAULT: {
left: 16,
right: 16,
top: 36,
bottom: 12,
containLabel: true,
},
COMPACT: {
left: 10,
right: 10,
top: 20,
bottom: 8,
containLabel: true,
},
} as const;
/**
* Legend 아이템 크기 설정 (GroupedOverlayBar, GroupedStackBar에서 사용)
*/
export const LEGEND_ITEM_SIZE = {
WIDTH: 25,
HEIGHT: 14,
RADIUS: 4,
} as const;
/**
* 색상 팔레트 설정
*/
export const CHART_COLOR_PALETTES = {
/** 연도별 트렌드 역순 (최신->과거) */
YEAR_TREND_REVERSE: ["--chart-3", "--chart-2", "--chart-1"],
/** LG Red 계열 */
LG_RED_SCALE: ["--lg-red-300", "--lg-red-400", "--lg-red-500"],
/** 연도별 전체 색상 */
YEAR_TOTAL: {
"24": "--chart-total-1",
"25": "--chart-total-2",
"26": "--chart-total-3",
} as const,
/** 연도별 LG 색상 */
YEAR_LG: {
"24": "--chart-lg-1",
"25": "--chart-lg-2",
"26": "--chart-lg-3",
} as const,
/** 연도별 브랜드 색상 (CBrand, Samsung, LG) */
YEAR_BRAND: {
"24": ["--chart-cbrand-1", "--chart-samsung-1", "--chart-lg-1"],
"25": ["--chart-cbrand-2", "--chart-samsung-2", "--chart-lg-2"],
"26": ["--chart-cbrand-3", "--chart-samsung-3", "--chart-lg-3"],
} as const,
} as const;
/**
* 테이블 색상 설정
*/
export const TABLE_COLORS = {
/** 게이지 테이블 색상 */
GAUGE: {
FILL: "hsl(var(--lg-gray-200) / 0.85)",
TRACK: "hsl(var(--lg-pink-300) / 0.2)",
},
/** Sign 표기 셀 배경색 */
SIGN_CELL: {
POSITIVE: "hsl(var(--primary) / 0.08)",
NEGATIVE: "hsl(var(--info) / 0.08)",
ZERO: "hsl(var(--lg-gray-200) / 0.6)",
},
} as const;
/**
* 테이블 크기 설정
*/
export const TABLE_DIMENSIONS = {
CELL_HEIGHT: {
DEFAULT: 26,
COMPACT: 20,
EXPANDED: 32,
},
MIN_WIDTH: {
STANDARD: 1600,
COMPACT: 1200,
WIDE: 2000,
},
} as const;
/**
* 차트/테이블 라벨 텍스트
*/
export const CHART_LABELS = {
TOTAL: "전체",
LG: "LG",
GAP: GAP_WORDING,
CAGR: "CAGR(%p)",
SAMPLE_COUNT: "(사례수)",
} as const;
/**
* 차트 제목 텍스트
*/
export const CHART_TITLES = {
LG_PENETRATION: "LG제품 보급률",
TOTAL_PENETRATION: "전체 보급률",
LG_PURCHASE: "LG제품 구매율",
TOTAL_PURCHASE: "전체 구매율",
BRAND_SHARE: "브랜드별 점유율",
} as const;

View File

@@ -1,3 +1,2 @@
export const UNKNOWN_HTTP_ERROR = 'UNKNOWN_HTTP_ERROR';
export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR';
export const DASHBOARD_YEAR = 2026;
export const NONE_HTTP_ERROR = 'NONE_HTTP_ERROR';

511
src/const/lgConst.ts Normal file
View File

@@ -0,0 +1,511 @@
import {BannerKey, CategoryFieldSpec, LifeStageRow} from "@/types/lg";
import {GaugeColumn} from "@/components/lge-dashboard";
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
export const SITE_TITLE = 'LGE CX Dashboard';
export const YEARS = ["2023", "2024", "2025"];
export const LAST_YEAR = YEARS.at(-1)!;
export const GAP_WORDING = "전년 대비 GAP(%p)";
export const UNIT_TEXT = "(단위 %)"
export const SAMPLE_SIZE_NOTICE = "* 30표본 미만 해석에 주의";
export const BRAND_LIST = ['Cbrand', '삼성', 'LG'];
export const PRODUCT_KEY_MAP = {
"KPRODUCT#1": "냉장고",
"KPRODUCT#2": "김치 냉장고",
"KPRODUCT#3": "식기 세척기",
"KPRODUCT#4": "정수기",
"KPRODUCT#5": "전기 레인지",
"KPRODUCT#6": "음식물처리기",
"KPRODUCT#7": "세탁기",
"KPRODUCT#8": "건조기",
"KPRODUCT#9": "청소기",
"KPRODUCT#10": "로봇 청소기",
"KPRODUCT#11": "의류 관리기",
"KPRODUCT#12": "에어컨",
"KPRODUCT#13": "공기 청정기",
"KPRODUCT#14": "TV",
"KPRODUCT#15": "모니터",
"KPRODUCT#16": "노트북",
} as const;
export const BANNER_KEY_MAP = {
// 라이프 스테이지
"KLIFEstAGE#1": "미혼",
"KLIFEstAGE#2": "무자녀",
"KLIFEstAGE#3": "미취학",
"KLIFEstAGE#4": "취학자녀",
"KLIFEstAGE#5": "성인자녀",
"KLIFEstAGE#6": "독립시니어",
// 가구원수
"KSQ8_R_DB#1": "1인 가구",
"KSQ8_R_DB#2": "2인 가구",
"KSQ8_R_DB#3": "3인 가구",
"KSQ8_R_DB#4": "4인 이상 가구",
// 연령
"KSQ2_R_R#1": "20대",
"KSQ2_R_R#2": "30대",
"KSQ2_R_R#3": "40대",
"KSQ2_R_R#4": "50대",
"KSQ2_R_R#5": "60대",
// 점유형태
"KDQ6#1": "자가",
"KDQ6#2": "전세",
"KDQ6#3": "전+월세 (보증금有)",
"KDQ6#4": "월세 (보증금無)",
"KDQ6#5": "기타",
// 주거형태
"KDQ4#1": "아파트",
"KDQ4#2": "주택",
"KDQ4#3": "오피스텔",
"KDQ4#4": "(연립)빌라",
"KDQ4#5": "원룸",
"KDQ4#6": "기타",
// 평형
"KDQ5#1": "19평 이하",
"KDQ5#2": "20평형 대",
"KDQ5#3": "30평형 대",
"KDQ5#4": "40평형 대",
"KDQ5#5": "50평형 대 이상",
// 권역
"KSQ4_R_R#1": "서울, 인천, 경기도",
"KSQ4_R_R#2": "경남, 부산, 울산",
"KSQ4_R_R#3": "경북, 대구",
"KSQ4_R_R#4": "전라도, 광주",
"KSQ4_R_R#5": "충청, 대전, 세종",
"KSQ4_R_R#6": "강원, 제주",
// 소득
"KDQ3_DB#1": "299만원 이하",
"KDQ3_DB#2": "300~599만원 이하",
"KDQ3_DB#3": "600~899만원 이하",
"KDQ3_DB#4": "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: "KLIFEstAGE#1", header: "미혼" , headRowSpan:2, max: 100 , align: "left"},
{ key: "KLIFEstAGE#2", header: "무자녀", group: "기혼", max: 100 , align: "left"},
{ key: "KLIFEstAGE#3", header: "미취학", group: "기혼", max: 100 , align: "left"},
{ key: "KLIFEstAGE#4", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
{ key: "KLIFEstAGE#5", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
{ key: "KLIFEstAGE#6", header: "독립\n시니어", headRowSpan:2, max: 100 , align: "left"},
];
export const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["KPRODUCT#1", "KPRODUCT#7", "KPRODUCT#8", "KPRODUCT#12", "KPRODUCT#14", "KPRODUCT#2", "KPRODUCT#3", "KPRODUCT#11"] },
{ title: "소형가전 군", items: ["KPRODUCT#9", "KPRODUCT#13", "KPRODUCT#4"] },
{ title: "신가전 군", items: ["KPRODUCT#10", "KPRODUCT#6"] },
] 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 PRODUCTS_FILTER_ITEM = [
{
path: "kitchen",
items: [
"KPRODUCT#1", // 냉장고
"KPRODUCT#2", // 김치 냉장고
"KPRODUCT#3", // 식기 세척기
"KPRODUCT#4", // 정수기
"KPRODUCT#5", // 전기 레인지
"KPRODUCT#6", // 음식물처리기
],
},
{
path: "living",
items: [
"KPRODUCT#7", // 세탁기
"KPRODUCT#8", // 건조기
"KPRODUCT#9", // 청소기
"KPRODUCT#10", // 로봇 청소기
"KPRODUCT#11", // 의류 관리기
],
},
{
path: "es",
items: [
"KPRODUCT#12", // 에어컨
"KPRODUCT#13", // 공기 청정기
],
},
{
path: "ms",
items: [
"KPRODUCT#14", // TV
"KPRODUCT#15", // 모니터
"KPRODUCT#16", // 노트북
],
},
] as const;
export const BANNER_KEYS = Object.keys(BANNER_KEY_MAP) as Array<keyof typeof BANNER_KEY_MAP>;
export const BANNER_KEY = Object.keys(BANNER_KEY_MAP).reduce((acc, k) => {
(acc as any)[k] = k;
return acc;
}, {} as { [K in BannerKey]: K });
export const BANNER_GROUP = {
lifeStage: {
label: "라이프스테이지 별",
keys: [
BANNER_KEY["KLIFEstAGE#1"],
BANNER_KEY["KLIFEstAGE#2"],
BANNER_KEY["KLIFEstAGE#3"],
BANNER_KEY["KLIFEstAGE#4"],
BANNER_KEY["KLIFEstAGE#5"],
BANNER_KEY["KLIFEstAGE#6"],
],
},
household: {
label: "가구원수 별",
keys: [
BANNER_KEY["KSQ8_R_DB#1"],
BANNER_KEY["KSQ8_R_DB#2"],
BANNER_KEY["KSQ8_R_DB#3"],
BANNER_KEY["KSQ8_R_DB#4"],
],
},
age: {
label: "연령",
keys: [
BANNER_KEY["KSQ2_R_R#1"],
BANNER_KEY["KSQ2_R_R#2"],
BANNER_KEY["KSQ2_R_R#3"],
BANNER_KEY["KSQ2_R_R#4"],
BANNER_KEY["KSQ2_R_R#5"],
],
},
occupancy: {
label: "입주 형태",
keys: [
BANNER_KEY["KDQ6#1"],
BANNER_KEY["KDQ6#2"],
BANNER_KEY["KDQ6#3"],
BANNER_KEY["KDQ6#4"],
BANNER_KEY["KDQ6#5"],
],
},
housing: {
label: "주거 형태",
keys: [
BANNER_KEY["KDQ4#1"],
BANNER_KEY["KDQ4#2"],
BANNER_KEY["KDQ4#3"],
BANNER_KEY["KDQ4#4"],
BANNER_KEY["KDQ4#5"],
BANNER_KEY["KDQ4#6"],
],
},
houseSize: {
label: "거주 평형",
keys: [
BANNER_KEY["KDQ5#1"],
BANNER_KEY["KDQ5#2"],
BANNER_KEY["KDQ5#3"],
BANNER_KEY["KDQ5#4"],
BANNER_KEY["KDQ5#5"],
],
},
region: {
label: "거주 지역",
keys: [
BANNER_KEY["KSQ4_R_R#1"],
BANNER_KEY["KSQ4_R_R#2"],
BANNER_KEY["KSQ4_R_R#3"],
BANNER_KEY["KSQ4_R_R#4"],
BANNER_KEY["KSQ4_R_R#5"],
BANNER_KEY["KSQ4_R_R#6"],
],
},
income: {
label: "소득수준",
keys: [
BANNER_KEY["KDQ3_DB#1"],
BANNER_KEY["KDQ3_DB#2"],
BANNER_KEY["KDQ3_DB#3"],
BANNER_KEY["KDQ3_DB#4"],
],
},
} as const;
export const BANNER_GROUP_KEY = Object.keys(BANNER_GROUP) as string[];
export const CATEGORY_PAGE_FIELDS: Record<CategoryTargetData, CategoryFieldSpec[]> = {
[CategoryTargetData.PROFILE]: [
{
title: {
[CategoryTargetType.PENETRATION]: "보유율"
, [CategoryTargetType.PURCHASE]: "구매율"
, [CategoryTargetType.INTENDED]: "향후 구매율"
},
requestKey: "category_${keyBase}",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA1"
, [CategoryTargetType.PURCHASE]: "KQA3_2"
, [CategoryTargetType.INTENDED]: "KQC1"
},
},
{
title: "보유대수",
requestKey: "category_penetration_count",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA2"
},
},
],
[CategoryTargetData.PENETRATION_CHANGE]: [
{
title: "보급률 변화",
requestKey: "category_${keyBase}",
chartMode:"none",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA1"
},
},
],
[CategoryTargetData.BRAND]: [
{
title: "브랜드",
requestKey: "category_${keyBase}_brand",
chartMode:"reverseStack",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_3",
[CategoryTargetType.PURCHASE]: "KQX3_3",
},
},
{
title: {
[CategoryTargetType.PENETRATION]: "",
[CategoryTargetType.PURCHASE]: "구매 고려 브랜드",
[CategoryTargetType.INTENDED]: "브랜드",
},
requestKey: "category_${keyBase}_consider_brand",
chartMode:"horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB1",
[CategoryTargetType.INTENDED]: "KQC2",
},
},
],
[CategoryTargetData.TYPE_SPEC]: [
{
title: "타입",
requestKey: "category_${keyBase}_type",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_4",
[CategoryTargetType.PURCHASE]: "KQX3_4",
[CategoryTargetType.INTENDED]: "KQC3_1" }
},
{
title: "깊이 타입",
requestKey: "category_${keyBase}_depthType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_5",
[CategoryTargetType.PURCHASE]: "KQX3_5",
[CategoryTargetType.INTENDED]: "KQC3_2"
}
},
{
title: "용량",
requestKey: "category_${keyBase}_capacity",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_6",
[CategoryTargetType.PURCHASE]: "KQX3_6"
}
},
{
title: "설치 형태",
requestKey: "category_${keyBase}_installType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_7",
[CategoryTargetType.PURCHASE]: "KQX3_7",
[CategoryTargetType.INTENDED]: "KQC3_3"
}
},
{
title: "시공 방식",
requestKey: "category_${keyBase}_installMethod",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_4"
}
},
{
title: "냉장고 & 김치냉장고 설치 형태",
requestKey: "category_${keyBase}_fridgeInstallType",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_5"
}
},
{
title: "설치 위치",
requestKey: "category_${keyBase}_installLocation",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_6"
}
},
{
title: "배치/설치환경",
requestKey: "category_${keyBase}_installEnv",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_8",
[CategoryTargetType.PURCHASE]: "KQX3_8",
[CategoryTargetType.INTENDED]: "KQC3_7"
}
},
{
title: "구입 고려 특징",
requestKey: "category_${keyBase}_buyConsiderations",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.INTENDED]: "KQC3_8"
}
},
{
title: "기능",
requestKey: "category_${keyBase}_features",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_9",
[CategoryTargetType.PURCHASE]: "KQX3_9"
}
},
{
title: "스크린 사이즈",
requestKey: "category_${keyBase}_screenSize",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_10",
[CategoryTargetType.PURCHASE]: "KQX3_10"
}
},
{
title: "용도",
requestKey: "category_${keyBase}_usage",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_11",
[CategoryTargetType.PURCHASE]: "KQX3_11"
}
},
{
title: "스마트 모니터 여부",
requestKey: "category_${keyBase}_isSmartMonitor",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_12",
[CategoryTargetType.PURCHASE]: "KQX3_12"
}
},
],
[CategoryTargetData.BEHAVIOR]: [
{
title: {
[CategoryTargetType.PENETRATION]: "보유 경로"
, [CategoryTargetType.PURCHASE]: "구입 행태"
, [CategoryTargetType.INTENDED]: "구입 행태"
},
requestKey: "category_${keyBase}_behavior",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_1",
[CategoryTargetType.PURCHASE]: "KQB2",
[CategoryTargetType.INTENDED]: "KQC5"
},
},
{
title: "구입 계기",
requestKey: "category_${keyBase}_chance",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB3"
},
},
],
[CategoryTargetData.PURCHASE_CHANNEL]: [
{
title: "구매 채널(온/오프라인)",
requestKey: "category_${keyBase}_channel",
chartMode: "reverseStack",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB4_NET",
[CategoryTargetType.INTENDED]: "KQC6_NET"
},
},
{
title: "구매 채널(상세)",
requestKey: "category_${keyBase}_channel_detail",
chartMode: "horizontal",
qidByMode: {
[CategoryTargetType.PURCHASE]: "KQB4",
[CategoryTargetType.INTENDED]: "KQC6"
},
},
],
[CategoryTargetData.PAYMENT_METHOD]: [
{
title: "구매형식",
requestKey: "category_${keyBase}_method",
chartMode:"reverseStack",
qidByMode: {
[CategoryTargetType.PENETRATION]: "KQA3_2_1",
[CategoryTargetType.PURCHASE]: "KQX3_2_1",
[CategoryTargetType.INTENDED]: "KQC7"
},
},
],
};
/** X 축 패딩 없앤 GridOption*/
export const GRID_X_NOT_PADDING = { left: 0, right: 0, top: 50, bottom: 10, containLabel: false } as const;
/** T 축 패딩 없앤 GridOption*/
export const GRID_Y_NOT_PADDING = { left: 10, right: 10, top: 0, bottom: 0, containLabel: false } as const;
/** 축 스타일 감춤 */
export const AXIS_HIDE_STYLE = { axisLabel: { show: false }, axisTick: { show: false }, axisLine: { show: false }} as const;
export const CHART_COLOR_BY_YEAR = Object.fromEntries(
YEARS.map((year, i) => [
year,
`--chart-${YEARS.length-i}-t`,
])
) as Record<(typeof YEARS)[number], string>;
export const CHART_FOCUS_COLOR_BY_YEAR = Object.fromEntries(
YEARS.map((year, i) => [
year,
`--chart-${YEARS.length-i}`,
])
) as Record<(typeof YEARS)[number], string>;

View File

@@ -0,0 +1,59 @@
import { useQuery } from "@tanstack/react-query";
import type { StatisticsRequest, ProductResponse, BannerResponse } from "@/types/lg";
import {fetchBannerStatistics, fetchProductStatistics} from "@/lib/lg-dashboard";
const sortRecord = <T,>(obj?: Record<string, T> | null): Record<string, T> => {
if (!obj) return {};
return Object.fromEntries(
Object.keys(obj)
.sort()
.map((k) => [k, obj[k]])
);
};
const sortNumberArrayRecord = (obj?: Record<string, number[]> | null): Record<string, number[]> => {
if (!obj) return {};
return Object.fromEntries(
Object.keys(obj)
.sort()
.map((k) => [k, [...(obj[k] ?? [])].sort((a, b) => a - b)])
);
};
// queryKey에 넣을 “안정적인 req”
const normalizeReqForKey = (req: StatisticsRequest) => ({
variableIdMap: sortRecord(req.variableIdMap),
bannerIdList: [...(req.bannerIdList ?? [])].sort(),
filterCondition: sortNumberArrayRecord(req.filterCondition as any), // normalizeFilterCondition 결과면 Record<string, number[]>
option: req.option ?? null,
});
export const productStatisticsKey = (req: StatisticsRequest) =>
["statistics", "product", normalizeReqForKey(req)] as const;
export const bannerStatisticsKey = (req: StatisticsRequest) =>
["statistics", "banner", normalizeReqForKey(req)] as const;
export function useProductStatisticsQuery(req: StatisticsRequest, enabled = true) {
return useQuery<ProductResponse>({
queryKey: productStatisticsKey(req),
queryFn: () => fetchProductStatistics(req),
enabled,
staleTime: 60_000,
gcTime: 10 * 60_000,
});
}
export function useBannerStatisticsQuery(req: StatisticsRequest, enabled = true) {
return useQuery<BannerResponse>({
queryKey: bannerStatisticsKey(req),
queryFn: () => fetchBannerStatistics(req),
enabled,
/*
refetchOnMount: "always",
staleTime: 0,
*/
staleTime: 60_000,
gcTime: 10 * 60_000,
});
}

22
src/hooks/useResize.ts Normal file
View File

@@ -0,0 +1,22 @@
import { useEffect, useState } from "react";
export const useResizeKey = (debounceMs = 150) => {
const [key, setKey] = useState(0);
useEffect(() => {
let t: number | undefined;
const onResize = () => {
window.clearTimeout(t);
t = window.setTimeout(() => setKey((k) => k + 1), debounceMs);
};
window.addEventListener("resize", onResize);
return () => {
window.removeEventListener("resize", onResize);
window.clearTimeout(t);
};
}, [debounceMs]);
return key;
}

View File

@@ -14,10 +14,10 @@ import { StorageKey, StorageType } from "@/store/storage/storage-keys";
* 사용법:
* const { set, get, remove } = useStorage(StorageKeys.SeatNumber);
*/
export const useStorage = (key: StorageKey) => {
export const useStorage = <T>(key: StorageKey) => {
const storageType = StorageType[key]; // "local" | "session"
const set = (value: any): void => {
const set = (value: T): void => {
if (storageType === "session") {
setSessionStorage(key, value);
} else {
@@ -25,7 +25,7 @@ export const useStorage = (key: StorageKey) => {
}
};
const get = (): any => {
const get = (): T => {
if (storageType === "session") {
return getSessionStorage(key);
} else {

232
src/lib/chart-options.ts Normal file
View File

@@ -0,0 +1,232 @@
import { CHART_GRID_DEFAULTS, BAR_WIDTHS } from "@/const/chartConst";
import {ChartData, NewNumber} from "@/components/lge-dashboard";
export function reverseCategories<T extends ChartData>(data: T): T {
const categories = [...data.categories].reverse();
const series = data.series.map((s) => ({
...s,
data: [...s.data].reverse(),
}));
return { ...data, categories, series };
}
export function reverseSeries<T extends ChartData>(data: T): T {
return {
...data,
series: [...data.series].reverse(),
};
}
/**
* 기본 Tooltip 옵션 생성
* @param valueFormatter - 값 포맷터 함수 (기본값: 정수는 그대로, 소수는 toLocaleString)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultTooltip(
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const defaultFmt = (v: number) =>
Number.isInteger(v) ? String(v) : v.toLocaleString();
return {
trigger: "axis",
axisPointer: { type: "shadow" },
valueFormatter: (v: unknown) =>
typeof v === "number" ? (valueFormatter ?? defaultFmt)(v) : String(v),
...overrides,
};
}
/**
* 기본 Legend 옵션 생성
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultLegend(
overrides?: any
): any {
return {
...overrides,
top: 0,
};
}
export function createReverseLegend(
originalData: ChartData,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
return createDefaultLegend({
...overrides,
data: order,
});
}
export function createReverseTooltip(
originalData: ChartData,
valueFormatter?: (v: number) => string,
overrides?: any
): any {
const order = originalData.series.map((s) => s.name);
// 기본 tooltip 생성(내부 defaultFmt 포함)
const base = createDefaultTooltip(valueFormatter, overrides);
const fmt = base.valueFormatter ?? ((v: unknown) => String(v));
const extractVal = (p: any): unknown => {
const v = p?.value;
if (typeof v === "number") return v;
if (Array.isArray(v)) return v[v.length - 1]; // dataset/encode 케이스 대비
if (typeof p?.data === "number") return p.data;
if (p?.data && typeof p.data.value === "number") return p.data.value;
return v;
};
return {
...base,
formatter: (params: any) => {
const arr = Array.isArray(params) ? params : [params];
if (arr.length === 0) return "";
const title = arr[0]?.axisValueLabel ?? arr[0]?.name ?? "";
const byName = new Map<string, any>();
for (const p of arr) byName.set(p.seriesName, p);
const lines = order
.map((name) => byName.get(name))
.filter(Boolean)
.map((p) => {
const v = extractVal(p);
const printed =
typeof v === "number" ? fmt(v) : v == null ? "-" : String(v);
return `${p.marker ?? ""}${p.seriesName} ${printed}`;
});
return [title, ...lines].join("<br/>");
},
};
}
/**
* 기본 Grid 옵션 생성
* @param preset - 프리셋 타입 (default | compact)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createDefaultGrid(
preset: "default" | "compact" = "default",
overrides?: any
): any {
const base =
preset === "compact"
? CHART_GRID_DEFAULTS.COMPACT
: CHART_GRID_DEFAULTS.DEFAULT;
return {
...base,
...overrides,
};
}
/**
* Category Axis 옵션 생성
* @param data - 카테고리 데이터 배열
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createCategoryAxis(
data: string[],
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "category",
data,
};
if (hideStyle) {
return {
...base,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Value Axis 옵션 생성
* @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등)
* @param overrides - 추가/덮어쓸 옵션
*/
export function createValueAxis(
hideStyle?: boolean,
overrides?: any
): any {
const base: any = {
type: "value",
};
if (hideStyle) {
return {
...base,
axisLabel: { show: false },
axisTick: { show: false },
axisLine: { show: false },
splitLine: { show: false },
...overrides,
};
}
return {
...base,
...overrides,
};
}
/**
* Bar 시리즈 기본 옵션 생성
* @param name - 시리즈 이름
* @param data - 데이터 배열
* @param options - 추가 옵션 (stack, barMaxWidth 등)
*/
export function createBarSeries(
name: string,
data: NewNumber[],
options?: {
stack?: string;
barMaxWidth?: number;
emphasis?: boolean;
label?: object;
}
): {
name: string;
type: "bar";
data: NewNumber[];
stack?: string;
barMaxWidth?: number;
emphasis?: { disabled: boolean };
label?: object;
} {
const { stack, barMaxWidth, emphasis = false, label } = options ?? {};
return {
name,
type: "bar",
data,
...(stack && { stack }),
barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT,
emphasis: { disabled: !emphasis },
...(label && { label }),
};
}

View File

@@ -7,6 +7,4 @@ const required = (name: string) => {
export const serverEnv = {
ENV: required("ENV"),
API_BACK_SERVER: required("API_BACK_SERVER"),
API_KART_SERVER: required("API_KART_SERVER"),
KART_API_KEY: required("KART_API_KEY"),
};

View File

@@ -33,6 +33,11 @@ export type QueryValue = string | string[] | undefined;
export type Query = Record<string, QueryValue>;
export type PathParams = Record<string, string | number | boolean>;
export type NextFetchOptions = {
revalidate?: number;
tags?: string[];
};
export type RequestOptions = {
method?: HttpMethod;
pathParams?: PathParams;
@@ -47,6 +52,8 @@ export type RequestOptions = {
autoLogoutOnAuthError?: boolean;
expectText?: boolean;
expectBinary?: boolean;
cache?: RequestCache; // "force-cache" | "no-store" | ...
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
};
export type HttpClientOptions = {
@@ -140,12 +147,17 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
const isServer = typeof window === "undefined";
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
const nextOpt = isServer ? options.next : undefined;
try {
const res = await fetch(url.toString(), {
method: options.method ?? (body ? "POST" : "GET"),
headers,
body,
cache: "no-store",
cache: cacheMode,
...(nextOpt ? ({ next: nextOpt } as any) : {}),
signal: controller.signal,
});
@@ -292,4 +304,4 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
return { request, get, post, put, patch, del, postForm, putForm };
};
export const nextApi = createHttpClient(clientEnv.API_BASE);
export const nextApi = createHttpClient(clientEnv.API_BASE);

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

@@ -0,0 +1,518 @@
import {
BannerGroupKey,
BannerResponse,
BannerRow, BuildPageModeConfigResult,
ProductResponse, ProductRow,
StatisticsRequest
} from "@/types/lg";
import {ChartData} from "@/components/lge-dashboard";
import {
BANNER_GROUP,
BANNER_KEYS,
CATEGORY_PAGE_FIELDS,
GAP_WORDING,
PRODUCT_KEYS
} from "@/const/lgConst";
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(%p)";
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[]
): 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") {
out[k] = `(${formatNumber(v)})`;
return;
}
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;
}
export const calcGapProductRow = (after: ProductRow, before: ProductRow): ProductRow => {
const out: ProductRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: String(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] = String(Number(a) - Number(b));
}
return out;
};
export const calcGapBannerRow = (after: BannerRow, before: BannerRow): BannerRow => {
const out: BannerRow = {
year: after?.year ?? "",
rowLabel: "gap",
total: String(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] = String(Number(a) - Number(b));
}
return out;
};
const round1 = (n: number) => Math.round(n * 10) / 10;
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 =
Number(before?.total ?? "0") > 0 ? String(round1((Math.pow(Number(after?.total ?? "0") / Number(before?.total ?? "0"), 1 / years) - 1) * 100)) : "0";
for (const k of PRODUCT_KEYS) {
const vBefore = before? before[k] ?? "0" : "0";
const vAfter = after? after[k] ?? "0" : "0";
out[k] = Number(vBefore) > 0 ? String(round1((Math.pow(Number(vAfter) / Number(vBefore), 1 / years) - 1) * 100)) : "0";
}
return out;
};
export const makeTotalBasePct = (t:number|string, f:number|string):number => {
return Number(t) > 0 ? Math.round((Number(f) / Number(t)) * 100) : 0;
}
export const calcTotalBaseRow = (label:string, totalRow: ProductRow, targetRow: ProductRow): ProductRow => {
const out: ProductRow = {
year: targetRow?.year ?? "",
rowLabel: `전체 ${label} 중 자사제품 비율`,
total: String(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] = String(makeTotalBasePct(t, f));
}
return out;
}
export const withGapRow = <T>(
rows: T[],
calcGapRow: (last: T, secondLast: T) => T
): T[] => {
const last = rows.at(-1);
const secondLast = rows.at(-2);
if (!last || !secondLast) return rows;
return [calcGapRow(last, secondLast), ...rows];
}
export const withCagrRow = <T>(
rows: T[],
calcCagrRow: (last: T, first: T) => T
): T[] => {
const first = rows.at(0);
const last = rows.at(-1);
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 };
};

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

@@ -0,0 +1,830 @@
// exportDashboardExcel.ts
"use client";
import {formatRowLabel} 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++) {
ws.getColumn(c).width = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
}
}
/* ---------------------------
* 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

@@ -99,4 +99,62 @@ export const formatKst = (
return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`;
};
export const isBlank = (v?: string | null) => !v || v.trim().length === 0;
export const isBlank = (v?: string | null) => !v || v.trim().length === 0;
export const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase();
export const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null;
export const formatNumber = (v: number) =>
Number.isInteger(v) ? v.toLocaleString() : v.toLocaleString(undefined, { maximumFractionDigits: 1 });
/**
* 다양한 형식의 값을 숫자로 파싱합니다.
* - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리
* - null/undefined/빈문자열/"−" 등은 null 반환
* - 유한하지 않은 숫자는 null 반환
*/
export function parseNumber(
value: unknown,
options?: {
allowComma?: boolean; // 기본값: true
allowPercent?: boolean; // 기본값: true
allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함)
}
): number | null {
const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {};
if (value === null || value === undefined) return null;
if (typeof value === "number") {
return Number.isFinite(value) ? value : null;
}
if (typeof value === "string") {
let s = value.trim();
if (s === "" || s === "-" || s === "−") return null;
s = s.replaceAll("(", "");
s = s.replaceAll(")", "");
if (allowComma) s = s.replaceAll(",", "");
if (allowPercent) s = s.replaceAll("%", "");
if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
return null;
}
export const toNumOrNull = (v: unknown) => {
if (v == null) return null;
if (v === "-" || v === "") return null;
const n = Number(v);
return Number.isFinite(n) ? n : null;
};
export const toNumOr0 = (v: unknown) => {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
};

View File

@@ -1,11 +1,13 @@
export const StorageKeys = {
AuthState: "kri:authState",
CategoriFilter: "kri:categoryFilter",
//SidebarCollapsed: "kri:sidebarCollapsed",
// 필요하면 여기 계속 추가
} as const;
export const StorageType: Record<StorageKey, "local" | "session"> = {
[StorageKeys.AuthState]: "local",
[StorageKeys.CategoriFilter]: "local",
};
export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys];

100
src/types/lg.ts Normal file
View File

@@ -0,0 +1,100 @@
import {BANNER_GROUP, BANNER_KEY_MAP, PRODUCT_KEY_MAP, PRODUCTS_FILTER_ITEM} from "@/const/lgConst";
import {CategoryTargetType} from "@/config/filter.types";
export type ProductKey = keyof typeof PRODUCT_KEY_MAP;
export type BannerKey = keyof typeof BANNER_KEY_MAP;
export type ProductsFilterItem = (typeof PRODUCTS_FILTER_ITEM)[number];
export type BaseRow = {
year: string;
rowLabel: string;
total: string;
};
// { year, rowLabel, total, ...category }
export type ProductRow = BaseRow & Partial<Record<ProductKey, string>>;
// { year, rowLabel, total, ...banner }
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
export type BannerRow = BaseRow &
Partial<Record<BannerKey, string>> &
Record<Exclude<string, keyof BaseRow>, string>;
export type ProductResponse = {
statisticsDataMap : Record<string, Array<ProductRow>>;
};
export type BannerResponse = {
statisticsDataMap : Record<string, Array<BannerRow>>;
};
export type StatisticsRequestOption = {
// 캐시 사용 여부
useCache?: boolean; // default: true
// 마지막 연도만 조회
lastYear?: boolean; // default: false
// 소수점 자리수
decimalPoint?: number; // default: LgePenetrationConst.DECIMAL_POINT
};
export type StatisticsRequest = {
// 변수 ID 맵 (Key: 요청 Key, Value: 변수 ID)
variableIdMap: Record<string, string>;
// 배너 ID 배열 (1단 배너, 옆으로 붙이기)
bannerIdList?: string[];
// 필터 정보
// Key: 필터 키, Value: 필터 값 목록
filterCondition?: Record<string, number[]>;
// 요청 옵션
option?: StatisticsRequestOption; // default: { useCache: true, lastYear: false, decimalPoint: ... }
};
export type LifeStageRow = Record<string, unknown> & {
item: string;
total: string;
"KLIFEstAGE#1": string;
"KLIFEstAGE#2": string;
"KLIFEstAGE#3": string;
"KLIFEstAGE#4": string;
"KLIFEstAGE#5": string;
"KLIFEstAGE#6": string;
};
export type LifeStageGroup = {
title: string;
rows: LifeStageRow[]
}
export type BannerGroupKey = keyof typeof BANNER_GROUP;
export type CategoryChartMode = "none" | "stack" | "reverseStack" | "horizontal";
export type PageData<T> = {
title: string;
chartMode: CategoryChartMode;
data: T[];
chartHeight?: number | string;
chartWidth?: number;
};
export type CategoryFieldSpec = {
title: string | Record<CategoryTargetType, string>;
requestKey: string;
chartMode:CategoryChartMode;
qidByMode: Partial<Record<CategoryTargetType, string>>; // mode별 qid (없으면 숨김/요청 제외)
};
export type CategoryResolvedField = CategoryFieldSpec & {
requestKeyResolved: string;
qid: string;
};
export type BuildPageModeConfigResult = {
fields: CategoryResolvedField[];
variableIdMap: Record<string, string>;
};