260225_01_ENH: 실제 Data 통계 API와 연결 및 일부 페이지 축소

This commit is contained in:
2026-02-25 16:48:12 +09:00
parent d0e1352739
commit 357d9f2946
38 changed files with 1593 additions and 1352 deletions

71
package-lock.json generated
View File

@@ -15,6 +15,7 @@
"@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",
@@ -33,6 +34,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",
@@ -86,7 +88,6 @@
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.6.tgz",
"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==",
"devOptional": true,
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.28.6",
"@babel/generator": "^7.28.6",
@@ -243,7 +244,6 @@
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz",
"integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==",
"devOptional": true,
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.28.6",
"@babel/parser": "^7.28.6",
@@ -2370,6 +2370,61 @@
"tailwindcss": "4.0.7"
}
},
"node_modules/@tanstack/query-core": {
"version": "5.90.20",
"resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",
"integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/query-devtools": {
"version": "5.93.0",
"resolved": "https://registry.npmjs.org/@tanstack/query-devtools/-/query-devtools-5.93.0.tgz",
"integrity": "sha512-+kpsx1NQnOFTZsw6HAFCW3HkKg0+2cepGtAWXjiiSOJJ1CtQpt72EE2nyZb+AjAbLRPoeRmPJ8MtQd8r8gsPdg==",
"dev": true,
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tanstack/react-query": {
"version": "5.90.21",
"resolved": "https://registry.npmjs.org/@tanstack/react-query/-/react-query-5.90.21.tgz",
"integrity": "sha512-0Lu6y5t+tvlTJMTO7oh5NSpJfpg/5D41LlThfepTixPYkJ0sE2Jj0m0f6yYqujBwIXlId87e234+MxG3D3g7kg==",
"license": "MIT",
"dependencies": {
"@tanstack/query-core": "5.90.20"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^18 || ^19"
}
},
"node_modules/@tanstack/react-query-devtools": {
"version": "5.91.3",
"resolved": "https://registry.npmjs.org/@tanstack/react-query-devtools/-/react-query-devtools-5.91.3.tgz",
"integrity": "sha512-nlahjMtd/J1h7IzOOfqeyDh5LNfG0eULwlltPEonYy0QL+nqrBB+nyzJfULV+moL7sZyxc2sHdNJki+vLA9BSA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@tanstack/query-devtools": "5.93.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"@tanstack/react-query": "^5.90.20",
"react": "^18 || ^19"
}
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.1",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz",
@@ -2426,7 +2481,6 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.8.tgz",
"integrity": "sha512-3MbSL37jEchWZz2p2mjntRZtPt837ij10ApxKfgmXCTuHWagYg7iA5bqPw6C8BMPfwidlvfPI/fxOc42HLhcyg==",
"devOptional": true,
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
@@ -2436,7 +2490,6 @@
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==",
"devOptional": true,
"peer": true,
"peerDependencies": {
"@types/react": "^19.2.0"
}
@@ -2483,7 +2536,6 @@
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.53.1.tgz",
"integrity": "sha512-nm3cvFN9SqZGXjmw5bZ6cGmvJSyJPn0wU9gHAZZHDnZl2wF9PhHv78Xf06E0MaNk4zLVHL8hb2/c32XvyJOLQg==",
"dev": true,
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.53.1",
"@typescript-eslint/types": "8.53.1",
@@ -2952,7 +3004,6 @@
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"dev": true,
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -3420,7 +3471,6 @@
"url": "https://github.com/sponsors/ai"
}
],
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -4181,7 +4231,6 @@
"resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.2.tgz",
"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==",
"dev": true,
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.8.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -4359,7 +4408,6 @@
"resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz",
"integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==",
"dev": true,
"peer": true,
"dependencies": {
"@rtsao/scc": "^1.1.0",
"array-includes": "^3.1.9",
@@ -6814,7 +6862,6 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -6823,7 +6870,6 @@
"version": "19.2.3",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"peer": true,
"dependencies": {
"scheduler": "^0.27.0"
},
@@ -7686,7 +7732,6 @@
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz",
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"peer": true,
"engines": {
"node": ">=12"
},
@@ -7866,7 +7911,6 @@
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -8286,7 +8330,6 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.5.tgz",
"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==",
"dev": true,
"peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}

View File

@@ -16,6 +16,7 @@
"@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",
@@ -34,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",

View File

@@ -9,62 +9,141 @@ import {
type TopChartTableRow,
} from "@/components/lge-dashboard";
import {
LAST_YEAR,
CHART_COLOR_BY_YEAR,
CHART_FOCUS_COLOR_BY_YEAR,
LIFE_STAGE_COLUMNS,
LIFE_STAGE_GROUPS,
PRODUCT_KEY_MAP,
PRODUCT_KEYS,
PRODUCTS, SITE_TITLE,
SITE_TITLE,
YEARS
} from "@/const/lgConst";
import {useEffect, useMemo} from "react";
import {apiLifeStageByProduct, apiOwnShareOfTotalPenetration, apiTrendCategories} from "@/config/sample.data";
import LifeStageDiv from "@/components/lge-dashboard/combo/LifeStageDiv";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
import {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 {norm} from "@/lib/utils";
import {LifeStageGroup, LifeStageRow} from "@/types/lg";
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();
console.log(filterValue);
const {filterValue, registerExcelExporter} = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
//TODO: LG가 0인 제품은 제외시키기
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 apiOwnShareOfTotalPenetration.map((row) => ({
return penetrationLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, []);
}, [penetrationLGRowsWithGap, includeProductKeys]);
const productChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const 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]));
const totalRows = apiTrendCategories.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
);
const lgRows = apiOwnShareOfTotalPenetration.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
);
lgRows.forEach((r, ri) => {
penetrationLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < PRODUCT_KEYS.length; ci++) {
const k = PRODUCT_KEYS[ci];
const t = (totalRows[ri] as any)[k];
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);
@@ -73,47 +152,51 @@ const LGPenetrationPage = () => {
});
return {
categories: PRODUCTS,
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, []);
}, [penetrationRows, penetrationLGRows, includeProductKeys, includeProducts]);
const lifeStageRowsByGroup:LifeStageGroup[] = useMemo(() => {
const pick = (label: string) => apiLifeStageByProduct.find((r) => norm(r.rowLabel) === norm(label));
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((label) => {
const r = pick(label);
const rows: LifeStageRow[] = g.items.map((key) => {
const label = PRODUCT_KEY_MAP[key];
return {
item: label,
total: r?.total ?? "",
single: r?.single ?? "",
noKids: r?.noKids ?? "",
preschoolKids: r?.preschoolKids ?? "",
schoolKids: r?.schoolKids ?? "",
adultKids: r?.adultKids ?? "",
independentSenior: r?.independentSenior ?? "",
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 };
return {title: g.title, rows};
});
}, []);
}, [lifeStageRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
const excelHeader = buildHeader_ProductKeyMap(productKeyMap);
const lifeStageHeader = buildHeader_LifeStageColumns(LIFE_STAGE_COLUMNS);
type AnyRow = Record<string, any>;
@@ -122,7 +205,7 @@ const LGPenetrationPage = () => {
{
title: "LG제품 보급률",
header: excelHeader,
rows: apiOwnShareOfTotalPenetration as AnyRow[],
rows: penetrationLGRowsWithGap as AnyRow[],
rowGap: 1,
},
@@ -141,28 +224,29 @@ const LGPenetrationPage = () => {
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, penetrationLGRowsWithGap, lifeStageRowsByGroup, productKeyMap]);
return (
<div>
<TopChartTable
title={"LG제품 보급률"}
categories={[...PRODUCTS]}
categories={[...includeProducts]}
rows={productTableRows}
chart={
<GroupedOverlayBar
data={productChartData}
yearTotalColor={{ "24": "--chart-3-t", "25": "--chart-2-t", "26": "--chart-1-t" }}
yearFocusColor={{ "24": "--chart-3", "25": "--chart-2", "26": "--chart-1" }}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description} />
<BottomDescription description={description}/>
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup} />
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup}/>
</div>
);
};

View File

@@ -1,70 +1,132 @@
"use client";
import {useEffect, useMemo} from "react";
import {LAST_YEAR, PRODUCT_KEY_MAP, PRODUCT_KEYS, PRODUCTS, SITE_TITLE, YEARS} from "@/const/lgConst";
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 { apiOwnShareOfTotalPurchase, apiTrendBuy } from "@/config/sample.data";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
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();
console.log(filterValue);
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
//TODO: LG가 0인 제품은 제외시키기
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 apiOwnShareOfTotalPurchase.map((row) => ({
return purchaseLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, []);
}, [purchaseLGRowsWithGap, includeProductKeys]);
const purchaseChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const focus: Array<Array<number>> = YEARS.map(() => Array(PRODUCT_KEYS.length).fill(0));
const 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]));
const totalRows = apiTrendBuy.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
);
const lgRows = apiOwnShareOfTotalPurchase.filter(
(r) => YEARS.includes(r.year as any) && r.rowLabel.endsWith("년")
);
lgRows.forEach((r, ri) => {
purchaseLGRows.forEach((r, ri) => {
const yi = yearIndexMap.get(r.year);
if (yi == null) return;
for (let ci = 0; ci < PRODUCT_KEYS.length; ci++) {
const k = PRODUCT_KEYS[ci];
const t = (totalRows[ri] as any)[k];
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은 t 기준으로 체크해야 안전
total[yi][ci] = Number(t);
focus[yi][ci] = Number(v);
}
});
return {
categories: PRODUCTS,
categories: includeProducts,
years: YEARS,
totalName: "전체",
focusName: "LG",
total,
focus,
};
}, []);
}, [purchaseRows, purchaseLGRows, includeProducts, includeProductKeys]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
@@ -78,35 +140,38 @@ const LGPurchasePage = () => {
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
const excelHeader = buildHeader_ProductKeyMap(productKeyMap);
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 구매율).xlsx`,
sheetName: "LG제품 구매율",
sections: [
{ title: "LG제품 구매율", header: excelHeader, rows: apiOwnShareOfTotalPurchase, rowGap: 1 },
{ title: "LG제품 구매율", header: excelHeader, rows: purchaseLGRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, purchaseLGRowsWithGap]);
return (
<div>
<TopChartTable
title={"LG제품 구매율"}
categories={[...PRODUCTS]}
categories={[...includeProducts]}
rows={purchaseTableRows}
chart={
<GroupedOverlayBar
data={purchaseChartData}
yearTotalColor={{ "24": "--chart-3-t", "25": "--chart-2-t", "26": "--chart-1-t" }}
yearFocusColor={{ "24": "--chart-3", "25": "--chart-2", "26": "--chart-1" }}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
</div>
);
};

View File

@@ -11,7 +11,6 @@ import {
type GroupedStackBarData, BottomDescription,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {apiBrandByYearCategories, apiTrendCategories} from "@/config/sample.data";
import { Button } from "@/components/ui/button";
import {
BRAND_LIST,
@@ -19,40 +18,89 @@ import {
PRODUCTS,
YEARS,
AXIS_HIDE_STYLE,
GRID_X_NOT_PADDING, PRODUCT_KEY_MAP, LAST_YEAR, SITE_TITLE,
GRID_X_NOT_PADDING, PRODUCT_KEY_MAP, SITE_TITLE
} from "@/const/lgConst";
import { formatRowLabel } from "@/lib/lg-dashboard";
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();
console.log(filterValue);
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 apiTrendCategories.map((row) => ({
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: apiTrendCategories
.filter((r) => r.rowLabel.endsWith("년"))
.map((r) => ({
name: r.rowLabel,
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
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 apiBrandByYearCategories)[number]>();
for (const r of apiBrandByYearCategories) {
const rowMap = new Map<string, (typeof penetrationBrandRows)[number]>();
for (const r of penetrationBrandRows) {
rowMap.set(`${r.year}__${r.rowLabel}`, r);
}
@@ -70,7 +118,7 @@ const PenetrationPage = () => {
});
return { categories: PRODUCTS, years: YEARS, brands: BRAND_LIST, values };
}, []);
}, [penetrationBrandRows]);
const description = useMemo(() => {
if(isBrandShare){
@@ -78,7 +126,7 @@ const PenetrationPage = () => {
}
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.";
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.";
}, [isBrandShare]);
useEffect(() => {
@@ -87,12 +135,12 @@ const PenetrationPage = () => {
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = [
{ title: "전체 보급률", header: excelHeader, rows: apiTrendCategories, rowGap: 1 },
{ title: "전체 보급률", header: excelHeader, rows: penetrationRowsWithGapCagr, rowGap: 1 },
...YEARS.map((year) => (
{
title: `브랜드 별 점유율_${year}년`,
header: excelHeader,
rows: apiBrandByYearCategories.filter((row) => row.year === year) as AnyRow[],
rows: penetrationBrandRows.filter((row) => row.year === year),
rowGap: 1,
}
))
@@ -105,7 +153,7 @@ const PenetrationPage = () => {
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, penetrationRows, penetrationBrandRows]);
return (
<div>
@@ -131,11 +179,8 @@ const PenetrationPage = () => {
xAxis={{ type: "category", data: PRODUCTS, ...AXIS_HIDE_STYLE }}
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
showFocusLabel={"none"}
yearBrandPalette={{
"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"],
}}
yearBrandPalette={chartColorByYear}
height={260}
/>
) : (
<VerticalBar

View File

@@ -17,34 +17,65 @@ import {
type TopChartTableRow,
VerticalBar,
} from "@/components/lge-dashboard";
import { apiTrendBuy } from "@/config/sample.data";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import { formatRowLabel } from "@/lib/lg-dashboard";
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();
console.log(filterValue);
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 apiTrendBuy.map((row) => ({
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: apiTrendBuy
.filter((r) => r.rowLabel.endsWith("년"))
series: purchaseRows
.map((r) => ({
name: r.rowLabel,
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
})),
};
}, []);
}, [purchaseRows]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
@@ -63,12 +94,12 @@ const PurchasePage = () => {
fileName: `${SITE_TITLE}(구매율).xlsx`,
sheetName: "구매율",
sections: [
{ title: "구매율", header: excelHeader, rows: apiTrendBuy, rowGap: 1 },
{ title: "구매율", header: excelHeader, rows: purchaseRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, purchaseRowsWithGap]);
return (
<div>

View File

@@ -15,17 +15,8 @@ export const POST = async (req: NextRequest) => {
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, {
httpOnly: true,

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

@@ -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,13 +1,16 @@
"use client";
import {CategoryTargetData, CategoryTargetType, TotalFilterItem} from "@/config/filter.types";
import {
CategoryTargetType,
TargetChild,
} from "@/config/filter.types";
import {categoryTarget, categoryTargetType} from "@/config/filter.data";
import { ChevronRight } from "lucide-react";
import {useCallback, useMemo} from "react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {ProductsFilterItem} from "@/types/lg";
import {YEARS} from "@/const/lgConst";
import {ProductKey, ProductsFilterItem} from "@/types/lg";
import {PRODUCT_KEY_MAP, YEARS} from "@/const/lgConst";
export type CategoryTypeValue = {
label: string;
@@ -15,10 +18,10 @@ export type CategoryTypeValue = {
};
export type CategoryFilterValue = {
product: string;
product: ProductKey;
year: string;
type: CategoryTypeValue
target: CategoryTargetData;
target: TargetChild;
};
type CategoryFilterProps = {
@@ -28,7 +31,7 @@ type CategoryFilterProps = {
className?: string;
};
type Option = { key: string; label: string; value: string | CategoryTypeValue | CategoryTargetData };
type Option = { key: string; label: string; value: string | CategoryTypeValue | TargetChild };
type RowDef = {
id: "year" | "product" | "type" | "target";
@@ -75,27 +78,36 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil
// type 비교는 객체참조가 아니라 value로 비교해야 함
const handlePick = useCallback(
(key: keyof CategoryFilterValue, v: string | CategoryTypeValue | CategoryTargetData) => {
// same check
if (key === "type" && typeof v === "object" && "value" in v) {
if (value.type.value === v.value) return;
const nextItem = categoryTarget.find((item) => item.type.includes(v.value));
const firstTarget = nextItem?.children?.[0]?.target;
<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 nextItem = categoryTarget.find((item) =>
item.type.includes(nextType.value)
);
const firstTarget = nextItem?.children?.[0];
onChange({
...value,
type: v,
target: (firstTarget ?? value.target) as CategoryTargetData,
type: nextType,
target: firstTarget ?? value.target,
});
return;
}
if (key !== "type") {
// string/primitive 비교
if ((value as any)[key] === v) return;
onChange({ ...value, [key]: v } as CategoryFilterValue);
// 2) target (객체 비교는 value로)
if (key === "target") {
const nextTarget = v as TargetChild;
if (value.target.value === nextTarget.value) return;
onChange({ ...value, target: nextTarget });
return;
}
// 3) year/product (primitive)
if (value[key] === v) return;
onChange({ ...value, [key]: v } as CategoryFilterValue);
},
[value, onChange]
);
@@ -106,7 +118,7 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil
title: "연도",
options:(YEARS).map((y) => ({
key:y,
label:`20${y}년`,
label:`${y}년`,
value:y,
})),
isActive: (v) => value.year === v,
@@ -118,11 +130,11 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil
title: "제품",
options: (filterItems.items ?? []).map((p) => ({
key: p,
label: p,
label: PRODUCT_KEY_MAP[p],
value: p,
})),
isActive: (v) => value.product === v,
onSelect: (v) => handlePick("product", v as string),
onSelect: (v) => handlePick("product", v as ProductKey),
};
const typeRow: RowDef = {
@@ -133,10 +145,7 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil
label: t.label,
value: { label: t.label, value: t.value },
})),
isActive: (v) => {
const vv = v as CategoryTypeValue;
return value.type.value === vv.value;
},
isActive: (v) => value.type.value === (v as CategoryTypeValue).value,
onSelect: (v) => handlePick("type", v as CategoryTypeValue),
};
@@ -144,14 +153,13 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil
id: "target",
title: "데이터",
options: (currentTargetItem?.children ?? []).map((c) => ({
key: String(c.target),
key: String(c.value),
label: c.label,
value: c.target,
value: { label: c.label, value: c.value },
})),
isActive: (v) => value.target === v,
onSelect: (v) => handlePick("target", v as CategoryTargetData),
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]);

View File

@@ -34,8 +34,8 @@ const buildDefaultTotalValue = (): SelectedMap => {
const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
const initProduct = categoryFilterItems.items[0];
const initType = {label:"보유", value:CategoryTargetType.PENETRATION}
const firstTarget = categoryTarget.find((x) => x.type.includes(initType.value))?.children?.[0]?.target;
const initTarget = firstTarget ?? CategoryTargetData.PROFILE;
const firstTarget = categoryTarget.find((x) => x.type.includes(initType.value))?.children[0];
const initTarget = firstTarget ?? { value: CategoryTargetData.PROFILE, label: "Profile"};
return {
year: LAST_YEAR,

View File

@@ -1,16 +1,18 @@
"use client";
import dynamic from "next/dynamic";
import { useMemo } from "react";
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;
className?: string; // wrapper용
contentClassName?: string; // 안쪽 wrapper
chartClassName?: string; // ReactECharts용
/** echarts-for-react의 notMerge/lazyUpdate 옵션 필요 시 */
notMerge?: boolean;
lazyUpdate?: boolean;
@@ -22,16 +24,27 @@ const BaseEChart = ({
option,
height = CHART_HEIGHTS.DEFAULT,
className,
contentClassName,
chartClassName,
notMerge = true,
lazyUpdate = false, //이거 켜져있으면 오류남 Cannot read properties of undefined (reading 'getRawIndex')
onEvents,
}: BaseEChartProps) => {
const style = useMemo(() => ({ height }), [height]);
const resizeKey = useResizeKey(150);
return (
<div className={className}>
<ReactECharts option={option} style={style} notMerge={notMerge} lazyUpdate={lazyUpdate} onEvents={onEvents} />
<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>
);
}

View File

@@ -15,10 +15,11 @@ 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;
height?: number | string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
@@ -111,7 +112,7 @@ const GroupedOverlayBar = ({
for (let yi = 0; yi < years.length; yi++) {
const year = years[yi];
const yearLabel = `${year}년`;
const isOn = yearSelected[yearLabel] !== false;
const isOn = yearSelected[yearLabel];
const totalRow = data.total?.[yi] ?? [];
const focusRow = data.focus?.[yi] ?? [];
@@ -227,8 +228,9 @@ const GroupedOverlayBar = ({
const v = map.get(y)!;
const t = v.total ?? 0;
const f = v.focus ?? 0;
const pct = t > 0 ? ` (${Math.round((f / t) * 100)}%)` : "";
return `${totalName} ${t} 중 ${focusName} ${f}${pct}`;
const pct = makeTotalBasePct(t, f);
const pctStr = pct > 0 ? ` (${pct}%)` : "";
return `${totalName} ${t} 중 ${focusName} ${f}${pctStr}`;
});
return [header, ...lines].join("<br/>");

View File

@@ -14,11 +14,11 @@ 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 { CHART_HEIGHTS, LEGEND_ITEM_SIZE } from "@/const/chartConst";
import { LEGEND_ITEM_SIZE } from "@/const/chartConst";
type Props = {
data: GroupedStackBarData;
height?: number;
height?: number | string;
tooltip?: TooltipComponentOption;
grid?: GridComponentOption;
@@ -34,7 +34,7 @@ type Props = {
const GroupedStackBar = ({
data,
height = CHART_HEIGHTS.DEFAULT,
height,
tooltip,
grid,
xAxis,
@@ -61,6 +61,7 @@ const GroupedStackBar = ({
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) => {
@@ -111,7 +112,7 @@ const GroupedStackBar = ({
const brand = brands[bi];
const row = data.values?.[yi]?.[bi] ?? [];
const isYearOn = yearSelected[yearLabel] !== false;
const isYearOn = yearSelected[yearLabel];
const showLabel = getIsShowLabel(showFocusLabel, yi, years.length);
realSeries.push({

View File

@@ -50,13 +50,11 @@ const StackBar = ({
isReverse = false,
}: Props) => {
// ✅ 렌더링용 데이터만 뒤집기
const renderData = useMemo(
() => (isReverse ? reverseSeries(data) : data),
[data, isReverse]
);
// ✅ 팔레트도 뒤집어줘야 "시리즈 이름별" 색이 유지됨
const palette = useMemo(() => {
const temp = buildLgPalette(paletteVarNames);
const n = data.series.length; // 원본 기준
@@ -67,7 +65,7 @@ const StackBar = ({
const option: EChartsOption = useMemo(() => {
const fmt = valueFormatter ?? ((v: number) => String(v));
const isV = orientation === "vertical";
console.log(isReverse)
return {
color: palette,
tooltip: tooltip ?? (isReverse ? createReverseTooltip(data, fmt) : createDefaultTooltip(fmt)),

View File

@@ -1,5 +1,5 @@
import {ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, SignStyle} from "@/components/lge-dashboard";
import {BannerKey, ServerBannerRow} from "@/types/lg";
import {BannerKey, BannerRow} from "@/types/lg";
import {formatRowLabel, isGapRow, wrapSampleRow} from "@/lib/lg-dashboard";
import {useEffect, useMemo} from "react";
import {
@@ -15,8 +15,9 @@ import {
Section
} from "@/lib/lg-export-excel";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
import {CategoryTargetData} from "@/config/filter.types";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
type SectionSpec = {
@@ -36,11 +37,11 @@ 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<ServerBannerRow>[] => {
const columns: DataColumn<ServerBannerRow>[] = [
const buildColumns = (spec: SectionSpec, selectedYear:string): DataColumn<BannerRow>[] => {
const columns: DataColumn<BannerRow>[] = [
{
key: "rowLabel",
header: `20${selectedYear}년`,
header: `${selectedYear}년`,
headRowSpan: 2,
rowHead: true,
cellClassName: "lg-table__rowhead",
@@ -77,15 +78,16 @@ const buildColumns = (spec: SectionSpec, selectedYear:string): DataColumn<Server
};
type BannerSummaryProps = {
data: ServerBannerRow[];
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: ServerBannerRow[], bannerKeys: BannerKey[]): ChartData => {
const buildChartData = (rows: BannerRow[]): ChartData => {
const categories = rows
.filter((r) => !r.rowLabel.includes("사례수"))
.map((r) => formatRowLabel(r.rowLabel))
@@ -104,7 +106,7 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
return { categories, series };
};
const signStyleGap: SignStyle<ServerBannerRow> = {
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
@@ -127,7 +129,7 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
row.rowLabel = formatRowLabel(row.rowLabel);
return row
})
const chartData = buildChartData(rows, bannerKeys);
const chartData = buildChartData(rows);
return {
spec,
@@ -141,9 +143,12 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
}, [data, useYear, filterValue.year]);
useEffect(() => {
registerExcelExporter(async (payload) => {
const targetString =filterValue.target === CategoryTargetData.PROFILE? "Profile" : "보급률 변화"
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_${targetString}`
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>[] =
@@ -162,7 +167,7 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, debouncedFilterValue, sectionRows]);
return (
<div className="flex flex-col gap-6">
@@ -171,7 +176,7 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
<div key={`div_${sectionRow.specTitle}`}>
{
useChart ?
<LeftChartTable<ServerBannerRow>
<LeftChartTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}
@@ -193,7 +198,7 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
starUnder30Sample={true}
/>
:
<DataTable<ServerBannerRow>
<DataTable<BannerRow>
key={sectionRow.specTitle}
title={sectionRow.specTitle}
columns={sectionRow.columns}

View File

@@ -8,32 +8,31 @@ import {
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
import {totalFilters} from "@/config/filter.data";
import React, {useMemo, useState} from "react";
import {BannerGroupKey, CategoryChartMode, ServerBannerRow} from "@/types/lg";
import {BannerGroupKey, CategoryChartMode, BannerRow} from "@/types/lg";
import {
buildRowLabelSeriesChartData,
buildYearSeriesChartData, formatRowLabel,
isBannerGroupKey, isGapRow,
wrapSampleRow
} from "@/lib/lg-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, GAP_WORDING, SAMPLE_SIZE_NOTICE, UNIT_TEXT} from "@/const/lgConst";
import {createDefaultGrid, createDefaultLegend, reverseCategories} from "@/lib/chart-options";
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: ServerBannerRow[];
allTableData: BannerRow[];
fillGreaterThan5?: boolean;
chartHeight?: number;
chartHeight?: number | string;
chartWidth?: number;
unitText?: string;
}
const banners: bannerType[] = totalFilters.map((filter) => {
return {variable: filter.variable, variableName: filter.variableName}
})
const signStyleGap: SignStyle<ServerBannerRow> = {
const signStyleGap: SignStyle<BannerRow> = {
rowSelector: (row) => isGapRow(row.rowLabel),
display: "arrow",
arrowWithNumber: true,
@@ -49,15 +48,14 @@ const CategoryByData = ({
fillGreaterThan5,
chartHeight,
chartWidth,
unitText = UNIT_TEXT,
}: CategoryByDataProps) => {
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
const buildColumns = (groupKey: BannerGroupKey, selectedYear:string): DataColumn<ServerBannerRow>[] => {
const columns: DataColumn<ServerBannerRow>[] = [
const buildColumns = (groupKey: BannerGroupKey, selectedYear:string): DataColumn<BannerRow>[] => {
const columns: DataColumn<BannerRow>[] = [
{
key: "rowLabel",
header: `20${selectedYear}년`,
header: `${selectedYear}년`,
headRowSpan: 2,
rowHead: true,
cellClassName: "lg-table__rowhead",
@@ -111,22 +109,34 @@ const CategoryByData = ({
</div>
<div className="flex gap-6 p-3">
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px`}}>
{
chartMode === "stack" || chartMode === "reverseStack" ?
<StackBar
data={chartData}
height={`${chartHeight ?? 340}px`}
grid={createDefaultGrid("default", { top: 52 })}
isReverse={chartMode === "reverseStack"}
/>
:
<HorizontalBar
data={chartData}
height={`${chartHeight ?? 340}px`}
showFocusLabel="none"
paletteVarNames={chartData.series.length === 1? ["--chart-1"]: ["--chart-2","--chart-1"]}
/>
}
{(() => {
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">

View File

@@ -3,46 +3,55 @@ 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 Brand from "./category-page/Brand";
import TypeSpec from "./category-page/TypeSpec";
import OwnershipPath from "./category-page/OwnershipPath";
import PurchaseBehavior from "./category-page/PurchaseBehavior";
import PurchaseChannel from "./category-page/PurchaseChannel";
import PaymentMethod from "./category-page/PaymentMethod";
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();
console.log(filterValue);
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const renderPage = () => {
if (isTotal) return null;
const { fields, variableIdMap } = useMemo(() => {
return buildPageModeConfig(debouncedFilterValue);
}, [debouncedFilterValue]);
const target = filterValue.target;
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap,
bannerIdList: BANNER_GROUP_KEY,
filterCondition: buildCategoryFilter(debouncedFilterValue),
option: { useCache: false, lastYear: false, decimalPoint: 0 },
};
}, [variableIdMap, debouncedFilterValue]);
switch (target) {
case CategoryTargetData.PROFILE:
return <Profile />;
case CategoryTargetData.PENETRATION_CHANGE:
return <PenetrationChange />;
case CategoryTargetData.BRAND:
return <Brand />;
case CategoryTargetData.TYPE_SPEC:
return <TypeSpec />;
case CategoryTargetData.OWNERSHIP_PATH:
return <OwnershipPath />;
case CategoryTargetData.PURCHASE_BEHAVIOR:
return <PurchaseBehavior />;
case CategoryTargetData.PURCHASE_CHANNEL:
return <PurchaseChannel />;
case CategoryTargetData.PAYMENT_METHOD:
return <PaymentMethod />;
default:
return null;
}
};
const { data } = useBannerStatisticsQuery(req);
const dataMap = data?.statisticsDataMap;
const target = debouncedFilterValue.target;
const Comp = PAGE_COMPONENTS[target.value]
return renderPage();
if(isTotal) return null;
return Comp ? <Comp fields={fields} variableIdMap={variableIdMap} dataMap={dataMap} /> : null;
}
export default CategoryPage;

View File

@@ -1,26 +1,43 @@
'use client'
import {useEffect, useMemo} from "react";
import {CategoryByData} from "@/components/lge-dashboard";
import {apiBrandShareByYear} from "@/config/sample.data";
import {PageData, ServerBannerRow} from "@/types/lg";
import {buildGapRow} from "@/lib/lg-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, SITE_TITLE, YEARS} from "@/const/lgConst";
import {CategoryPageProps} from "@/components/lge-dashboard/sub-page/CategoryPage";
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
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 Brand = () => {
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]);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{title: "브랜드", chartMode:"reverseStack", data: apiBrandShareByYear, chartHeight:400},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
registerExcelExporter(async () => {
const product = debouncedFilterValue.product;
const type = debouncedFilterValue.type.label;
const target = debouncedFilterValue.target.label.replaceAll('/', '_');
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_브랜드`
const sheetName = `${product}_${type}_${target}`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
@@ -42,7 +59,7 @@ const Brand = () => {
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
}, [registerExcelExporter, debouncedFilterValue, tableDataArray]);
return (
<div>
@@ -61,4 +78,4 @@ const Brand = () => {
);
}
export default Brand;
export default CategoryDetail;

View File

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

View File

@@ -1,64 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {apiPaymentMethodByYear} from "@/config/sample.data";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, SITE_TITLE, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const PaymentMethod = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{title: "구매 형식", chartMode:"reverseStack", data: apiPaymentMethodByYear},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_구매 형식`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
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 PaymentMethod;

View File

@@ -1,16 +1,36 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {ServerBannerRow} from "@/types/lg";
import {apiYearIndex} from "@/config/sample.data";
import {BannerRow} from "@/types/lg";
import {CategoryPageProps} from "@/components/lge-dashboard/sub-page/CategoryPage";
import {LAST_YEAR} from "@/const/lgConst";
const PenetrationChange = () => {
const { filterValue } = useLayoutFilter();
console.log(filterValue);
const PenetrationChange = ({
dataMap
}:CategoryPageProps) => {
const penetrationChangeData = useMemo<ServerBannerRow[]>(() => apiYearIndex, []);
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} />

View File

@@ -3,28 +3,73 @@
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
import {useMemo} from "react";
import {ServerBannerRow} from "@/types/lg";
import {apiOwnershipSummary, apiPurchaseRateKpis} from "@/config/sample.data";
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 = () => {
const { isTotal, filterValue } = useLayoutFilter();
const Profile = ({
dataMap
}:CategoryPageProps) => {
const { filterValue } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue, 500);
const profileData = useMemo<ServerBannerRow[]>(() => {
if (isTotal) return [];
const profileData = useMemo<BannerRow[]>(() => {
if (dataMap === undefined) return [];
const typeLabel = filterValue.type.label;
switch (typeLabel) {
case "보유":
return apiOwnershipSummary;
case "구매":
return apiPurchaseRateKpis;
case "향후 구매":
return apiPurchaseRateKpis;
default:
return [];
const targetMap = {
[CategoryTargetType.PENETRATION]: "보유",
[CategoryTargetType.PURCHASE]: "해당년도",
[CategoryTargetType.INTENDED]: "향후구매",
}
}, [isTotal, filterValue]);
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} />

View File

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

View File

@@ -1,77 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {
apiPurchaseChannelByYear,
apiPurchaseChannelSummaryByYear
} from "@/config/sample.data";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, SITE_TITLE, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const PurchaseChannel = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{
title: "구매 채널(온/오프라인)",
chartMode: "reverseStack",
data: apiPurchaseChannelSummaryByYear,
},
{
title: "구매 채널(상세)",
chartMode: "horizontal",
data: apiPurchaseChannelByYear,
chartHeight: 550,
},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_구매 채널`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
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 PurchaseChannel;

View File

@@ -1,68 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
import {useEffect, useMemo} from "react";
import {PageData, ServerBannerRow} from "@/types/lg";
import {apiFridgeDoorTypeByYear} from "@/config/sample.data";
import {CategoryByData} from "@/components/lge-dashboard";
import {BANNER_GROUP, BANNER_KEY_MAP, SITE_TITLE, YEARS} from "@/const/lgConst";
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
const TypeSpec = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
console.log(filterValue);
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
{
title: "타입",
chartMode: "horizontal",
data: apiFridgeDoorTypeByYear,
},
], []);
useEffect(() => {
registerExcelExporter(async (payload) => {
const sheetName = `${filterValue.product}_${(filterValue.type as CategoryTypeValue).label}_타입/스펙`
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
type AnyRow = Record<string, any>;
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
const years = [YEARS.at(-1), YEARS.at(-2)];
return years.map((year) => ({
title: `${tableData.title}_${year}년`,
header: h3,
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
rowGap: 1,
}));
});
await exportDashboardExcel({
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
sheetName: sheetName,
sections: sections,
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter]);
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 TypeSpec;

View File

@@ -1,11 +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>
<LoadingOverlay />
{children}
<QueryClientProvider client={queryClient}>
<ReactQueryLoadingSync />
<LoadingOverlay />
{children}
</QueryClientProvider>
</JotaiProvider>
);
}

View File

@@ -124,23 +124,23 @@ export const categoryTarget: CategoryTargetItem[] = [
{
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.PAYMENT_METHOD, 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, 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.PAYMENT_METHOD, 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

@@ -20,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,
PAYMENT_METHOD = 14,
PAYMENT_METHOD = 15,
}
export type CategoryTargetTypeItem = {
@@ -32,8 +31,8 @@ export type CategoryTargetTypeItem = {
}
export type TargetChild = {
target: CategoryTargetData;
label: string;
value: CategoryTargetData;
}
export type CategoryTargetItem = {

View File

@@ -1,544 +0,0 @@
// sample.data.ts
import {PRODUCT_KEY_MAP} from "@/const/lgConst";
import {BannerKey, ProductKey, ServerBannerRow, ServerProductRow} from "@/types/lg";
const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as ProductKey[];
const DUMMY_SEED = Number(process.env.NEXT_PUBLIC_DUMMY_SEED ?? 12345);
// 문자열 → 32bit 해시
const hash32 = (s: string) => {
let h = 2166136261;
for (let i = 0; i < s.length; i++) {
h ^= s.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
};
// 결정적 PRNG
const mulberry32 = (a: number) => {
return () => {
let t = (a += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
};
const randInt = (r: () => number, min: number, max: number) =>
Math.floor(r() * (max - min + 1)) + min;
type RandRange = { min: number | null; max: number | null };
const makeProductDist = (seedKey: string, range?: RandRange): Record<ProductKey, string> => {
const min = range?.min ?? 1;
const max = range?.max ?? 60;
const seed = (hash32(seedKey) ^ DUMMY_SEED) >>> 0;
const r = mulberry32(seed);
const out = {} as Record<ProductKey, string>;
for (const k of PRODUCT_KEYS) out[k] = String(randInt(r, min, max));
return out;
};
const productRow = (
year: string,
rowLabel: string,
total: string,
range: RandRange = { min: null, max: null },
extra?: Partial<Record<ProductKey, string>>,
): ServerProductRow => ({
year,
rowLabel,
total,
...makeProductDist(`${year}|${rowLabel}|${range.min ?? ""}|${range.max ?? ""}`, range),
...(extra ?? {}),
});
const round1 = (n: number) => Math.round(n * 10) / 10;
const calcGapRow = (row26: ServerProductRow, row25: ServerProductRow): ServerProductRow => {
const out: ServerProductRow = {
year: row26.year,
rowLabel: "gap",
total: String(Number(row26.total) - Number(row25.total)),
};
for (const k of PRODUCT_KEYS) {
const a = row26[k] ?? "0";
const b = row25[k] ?? "0";
out[k] = String(Number(a) - Number(b));
}
return out;
};
const calcCagrRow = (row24: ServerProductRow, row26: ServerProductRow): ServerProductRow => {
const years = 2; // 24 -> 26
const out: ServerProductRow = { year: row26.year, rowLabel: "CAGR", total: "0" };
// total은 참고용으로만: (26/24) CAGR %
out.total =
Number(row24.total) > 0 ? String(round1((Math.pow(Number(row26.total) / Number(row24.total), 1 / years) - 1) * 100)) : "0";
for (const k of PRODUCT_KEYS) {
const v24 = row24[k] ?? "0";
const v26 = row26[k] ?? "0";
out[k] = Number(v24) > 0 ? String(round1((Math.pow(Number(v26) / Number(v24), 1 / years) - 1) * 100)) : "0";
}
return out;
};
const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number): string[] => {
// 불가능한 범위 방어
const minSum = n * minEach;
const maxSum = n * maxEach;
if (minSum > 100) throw new Error(`splitTo100 invalid: minEach too large (n=${n}, minEach=${minEach})`);
if (maxSum < 100) throw new Error(`splitTo100 invalid: maxEach too small (n=${n}, maxEach=${maxEach})`);
// 1) 최소값으로 깔기
const out = Array(n).fill(minEach);
const remain = 100 - minSum;
// 2) 각 슬롯이 추가로 받을 수 있는 상한
const caps = Array(n).fill(maxEach - minEach);
// 3) remain을 cap 내에서 랜덤 분배
// (가중치 기반으로 일단 분배 → cap 초과를 다시 재분배)
const w = Array.from({ length: n }, () => randInt(r, 1, 100));
const wSum = w.reduce((a, b) => a + b, 0);
const add = w.map((wi) => Math.floor((wi / wSum) * remain));
const used = add.reduce((a, b) => a + b, 0);
const left = remain - used;
// 남은 left를 가중치 큰 순으로 1씩
const order = w
.map((wi, i) => ({ wi, i }))
.sort((a, b) => b.wi - a.wi)
.map((x) => x.i);
for (let k = 0; k < left; k++) add[order[k % n]] += 1;
// cap 적용(초과분 회수)
let overflow = 0;
for (let i = 0; i < n; i++) {
if (add[i] > caps[i]) {
overflow += add[i] - caps[i];
add[i] = caps[i];
}
}
// 회수한 overflow를 cap 남은 곳에 다시 채우기(랜덤)
while (overflow > 0) {
const candidates = [];
for (let i = 0; i < n; i++) {
const room = caps[i] - add[i];
if (room > 0) candidates.push({ i, room });
}
if (candidates.length === 0) break;
const pick = candidates[randInt(r, 0, candidates.length - 1)];
add[pick.i] += 1;
overflow -= 1;
}
// 최종 합 100 보장
for (let i = 0; i < n; i++) out[i] += add[i];
const sum = out.reduce((a, b) => a + b, 0);
if (sum !== 100) {
// 마지막 보정(이론상 거의 안 탐)
out[n - 1] += 100 - sum;
}
return out.map((o) => String(o));
};
const BANNER_GROUPS: Record<string, BannerKey[]> = {
lifeStage: ["single", "noKids", "preschoolKids", "schoolKids", "adultKids", "independentSenior"],
household: ["hh1", "hh2", "hh3", "hh4Plus"],
age: ["age20s", "age30s", "age40s", "age50s", "age60s"],
occupancy: ["ownerOccupied", "jeonse", "depositAndMonthly", "monthlyNoDeposit", "otherOccupancyType"],
housing: ["apartment", "house", "officetel", "villa", "studio", "otherHousingType"],
houseSize: ["under19Pyeong", "pyeong20s", "pyeong30s", "pyeong40s", "pyeong50Plus"],
region: [
"regionCapital",
"regionGyeongnamBusanUlsan",
"regionGyeongbukDaegu",
"regionJeollaGwangju",
"regionChungcheongDaejeonSejong",
"regionGangwonJeju",
],
income: ["incomeUnder299", "income300to599", "income600to899", "income900Plus"],
};
/** ✅ 기존 상수 대신: 호출할 때마다 “결정적 랜덤” 분포 생성 */
export const makeBannerDistDefault = (seedKey: string, range?: RandRange): Record<BannerKey, string> => {
const seed = (hash32(seedKey) ^ DUMMY_SEED) >>> 0;
const r = mulberry32(seed);
const minEach = range?.min ?? 1;
const maxEach = range?.max ?? 60;
const out = {} as Record<BannerKey, string>;
(Object.keys(BANNER_GROUPS) as Array<keyof typeof BANNER_GROUPS>).forEach((groupName) => {
const keys = BANNER_GROUPS[groupName];
const parts = splitTo100(r, keys.length, minEach, maxEach); // ✅ min/max 적용
for (let i = 0; i < keys.length; i++) out[keys[i]] = parts[i];
});
return out;
};
export const bannerRow = (
year: string,
rowLabel: string,
total: string,
range: RandRange = { min: null, max: null },
extra?: Partial<Record<BannerKey, string>>,
): ServerBannerRow => ({
year,
rowLabel,
total,
...makeBannerDistDefault(`${year}|${rowLabel}`, range),
...(extra ?? {}),
});
const TREND_24: ServerProductRow = productRow("24", "24년", "45", {min:70, max:99});
const TREND_25: ServerProductRow = productRow("25", "25년", "46", {min:70, max:99});
const TREND_26: ServerProductRow = productRow("26", "26년", "48", {min:70, max:99});
export const apiTrendCategories: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
TREND_24,
TREND_25,
TREND_26,
calcCagrRow(TREND_24, TREND_26),
];
export const apiBrandByYearCategories: ServerProductRow[] = [
productRow("24", "LG", "1200"),
productRow("24", "Samsung", "1300"),
productRow("24", "Cbrand", "600"),
productRow("25", "LG", "1250"),
productRow("25", "Samsung", "1320"),
productRow("25", "Cbrand", "620"),
productRow("26", "LG", "1280"),
productRow("26", "Samsung", "1340"),
productRow("26", "Cbrand", "640"),
];
const OWN_PEN_24: ServerProductRow = productRow("24", "24년", "45");
const OWN_PEN_25: ServerProductRow = productRow("25", "25년", "46");
const OWN_PEN_26: ServerProductRow = productRow("26", "26년", "48");
export const apiOwnShareOfTotalPenetration: ServerProductRow[] = [
calcGapRow(OWN_PEN_26, OWN_PEN_25),
OWN_PEN_24,
OWN_PEN_25,
OWN_PEN_26,
];
const BUY_24: ServerProductRow = productRow("24", "24년", "45", {min:20, max:40});
const BUY_25: ServerProductRow = productRow("25", "25년", "46", {min:20, max:40});
const BUY_26: ServerProductRow = productRow("26", "26년", "48", {min:20, max:40});
export const apiTrendBuy: ServerProductRow[] = [
calcGapRow(TREND_26, TREND_25),
BUY_24,
BUY_25,
BUY_26,
];
const OWN_BUY_24: ServerProductRow = productRow("24", "24년", "41", {min:5, max:20});
const OWN_BUY_25: ServerProductRow = productRow("25", "25년", "42", {min:5, max:20});
const OWN_BUY_26: ServerProductRow = productRow("26", "26년", "43", {min:5, max:20});
export const apiOwnShareOfTotalPurchase: ServerProductRow[] = [
calcGapRow(OWN_BUY_26, OWN_BUY_25),
productRow("26", "전체 구입율 중 자사제품 비율", "46"),
OWN_BUY_24,
OWN_BUY_25,
OWN_BUY_26,
];
export const apiLifeStageByProduct: ServerBannerRow[] = [
bannerRow("26", "냉장고", "97", {min:10, max:99}),
bannerRow("26", "세탁기", "94", {min:10, max:99}),
bannerRow("26", "에어컨", "90", {min:10, max:99}),
bannerRow("26", "건조기", "38", {min:10, max:99}),
bannerRow("26", "TV", "86", {min:10, max:99}),
bannerRow("26", "김치 냉장고", "56", {min:10, max:99}),
bannerRow("26", "식기세척기", "18", {min:10, max:99}),
bannerRow("26", "의류 관리기", "13", {min:10, max:99}),
bannerRow("26", "청소기", "78", {min:10, max:99}),
bannerRow("26", "공기 청정기", "52", {min:10, max:99}),
bannerRow("26", "정수기", "42", {min:10, max:99}),
bannerRow("26", "로봇 청소기", "22", {min:10, max:99}),
bannerRow("26", "음식물처리기", "26", {min:10, max:99}),
];
/** ---------------------------
* API #6
* year rowLabel total banner
* 26 사례수 / 보유율 / gap / 보유대수
* -------------------------- */
export const apiOwnershipSummary: ServerBannerRow[] = [
bannerRow("26", "사례수", "2000"),
bannerRow("26", "보유율", "85"),
bannerRow("26", "gap", "5"), // 26-25
bannerRow("26", "보유대수", "1.3"),
bannerRow("25", "사례수", "2000"),
bannerRow("25", "보유율", "80"),
bannerRow("25", "gap", "4"), // 26-25
bannerRow("25", "보유대수", "1.2"),
bannerRow("24", "사례수", "2000"),
bannerRow("24", "보유율", "76"),
bannerRow("24", "gap", "-", ), // 26-25
bannerRow("24", "보유대수", "1.0"),
];
/** ---------------------------
* API #7
* year rowLabel total banner
* 26 사례수
* 26 26
* 25 25
* 24 24
* -------------------------- */
export const apiYearIndex: ServerBannerRow[] = [
bannerRow("26", "사례수", "2000"),
bannerRow("26", "26", "15"),
bannerRow("25", "25", "14"),
bannerRow("24", "24", "13"),
];
/** ---------------------------
* API #8
* year rowLabel total banner
* 25/26 사례수 + 브랜드
* -------------------------- */
export const apiBrandShareByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "500"),
bannerRow("24", "lg", "46"),
bannerRow("24", "gap", "-"),
bannerRow("24", "삼성", "41"),
bannerRow("24", "위니아", "4"),
bannerRow("24", "캐리어", "4"),
bannerRow("24", "하이얼", "1"),
bannerRow("24", "기타", "4"),
bannerRow("25", "사례수", "500"),
bannerRow("25", "lg", "48"),
bannerRow("25", "gap", "2"),
bannerRow("25", "삼성", "40"),
bannerRow("25", "위니아", "4"),
bannerRow("25", "캐리어", "3"),
bannerRow("25", "하이얼", "1"),
bannerRow("25", "기타", "4"),
bannerRow("26", "사례수", "520"),
bannerRow("26", "lg", "47"),
bannerRow("26", "gap", "-1"),
bannerRow("26", "삼성", "40"),
bannerRow("26", "위니아", "5"),
bannerRow("26", "캐리어", "3"),
bannerRow("26", "하이얼", "1"),
bannerRow("26", "기타", "4"),
];
/** ---------------------------
* API #9
* year rowLabel total banner
* 25/26 사례수 + 도어 타입
* -------------------------- */
export const apiFridgeDoorTypeByYear: ServerBannerRow[] = [
bannerRow("25", "사례수", "480"),
bannerRow("25", "1도어", "5"),
bannerRow("25", "2도어 상 냉동+하 냉장", "22"),
bannerRow("25", "2도어 상 냉장+하 냉동", "8"),
bannerRow("25", "2도어 양문형", "36"),
bannerRow("25", "4도어", "28"),
bannerRow("25", "기타", "1"),
bannerRow("26", "사례수", "500"),
bannerRow("26", "1도어", "5"),
bannerRow("26", "2도어 상 냉동+하 냉장", "23"),
bannerRow("26", "2도어 상 냉장+하 냉동", "12"),
bannerRow("26", "2도어 양문형", "35"),
bannerRow("26", "4도어", "25"),
bannerRow("26", "기타", "0"),
];
/** ---------------------------
* API #10
* year rowLabel total banner
* 25/26 사례수 + 보유 경로(구매 경로)
* -------------------------- */
export const apiOwnershipPathByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "520"),
bannerRow("24", "신규 구입", "7"),
bannerRow("24", "기존 제품 작동하나 신규 구입", "5"),
bannerRow("24", "기존 제품 고장으로 신규 구입", "30"),
bannerRow("24", "추가 구입", "58"),
bannerRow("25", "사례수", "520"),
bannerRow("25", "신규 구입", "8"),
bannerRow("25", "기존 제품 작동하나 신규 구입", "4"),
bannerRow("25", "기존 제품 고장으로 신규 구입", "40"),
bannerRow("25", "추가 구입", "48"),
bannerRow("26", "사례수", "540"),
bannerRow("26", "신규 구입", "8"),
bannerRow("26", "기존 제품 작동하나 신규 구입", "4"),
bannerRow("26", "기존 제품 고장으로 신규 구입", "40"),
bannerRow("26", "추가 구입", "48"),
];
export const apiOwnershipTriggerByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "520"),
bannerRow("24", "오래되어 새로운 제품 교체 필요", "23"),
bannerRow("24", "이사로 인해 새로 구입", "22"),
bannerRow("24", "이전 제품 고장으로 새로 구입", "17"),
bannerRow("24", "새로운 기능/기술 사용하고 싶어서", "14"),
bannerRow("24", "리모델링, 인테리어 계기로 새로 구입", "7"),
bannerRow("24", "혼수로 장만", "7"),
bannerRow("24", "(결혼 외) 가구 분가/독립하게 되어서", "6"),
bannerRow("24", "가구 구성원이 늘어서", "3"),
bannerRow("24", "가구 구성원이 줄어서", '2'),
bannerRow("25", "사례수", "520"),
bannerRow("25", "오래되어 새로운 제품 교체 필요", "23"),
bannerRow("25", "이사로 인해 새로 구입", "22"),
bannerRow("25", "이전 제품 고장으로 새로 구입", "17"),
bannerRow("25", "새로운 기능/기술 사용하고 싶어서", "14"),
bannerRow("25", "리모델링, 인테리어 계기로 새로 구입", "7"),
bannerRow("25", "혼수로 장만", "7"),
bannerRow("25", "(결혼 외) 가구 분가/독립하게 되어서", "6"),
bannerRow("25", "가구 구성원이 늘어서", "3"),
bannerRow("25", "가구 구성원이 줄어서", '2'),
bannerRow("26", "사례수", "540"),
bannerRow("26", "오래되어 새로운 제품 교체 필요", "23"),
bannerRow("26", "이사로 인해 새로 구입", "22"),
bannerRow("26", "이전 제품 고장으로 새로 구입", "17"),
bannerRow("26", "새로운 기능/기술 사용하고 싶어서", "14"),
bannerRow("26", "리모델링, 인테리어 계기로 새로 구입", "7"),
bannerRow("26", "혼수로 장만", "7"),
bannerRow("26", "(결혼 외) 가구 분가/독립하게 되어서", "6"),
bannerRow("26", "가구 구성원이 늘어서", "3"),
bannerRow("26", "가구 구성원이 줄어서", "2"),
];
/** ---------------------------
* API #11
* year rowLabel total banner
* 25/26 결제수단
* -------------------------- */
export const apiPaymentMethodByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "650"),
bannerRow("24", "일시불", "60"),
bannerRow("24", "할부", "30"),
bannerRow("24", "렌탈", "10"),
bannerRow("25", "사례수", "650"),
bannerRow("25", "일시불", "60"),
bannerRow("25", "할부", "30"),
bannerRow("25", "렌탈", "10"),
bannerRow("26", "사례수", "650"),
bannerRow("26", "일시불", "58"),
bannerRow("26", "할부", "32"),
bannerRow("26", "렌탈", "10"),
];
/** ---------------------------
* API #12
* year rowLabel total banner
* 26 사례수 / 구매율 / gap
* -------------------------- */
export const apiPurchaseRateKpis: ServerBannerRow[] = [
bannerRow("26", "사례수", "700"),
bannerRow("26", "구매율", "35"),
bannerRow("26", "gap", "2"), // 26-25
bannerRow("25", "사례수", "700"),
bannerRow("25", "구매율", "33"),
bannerRow("25", "gap", "5"), // 26-25
bannerRow("24", "사례수", "700"),
bannerRow("24", "구매율", "28"),
bannerRow("24", "gap", "-"), // 26-25
];
export const apiPurchaseChannelSummaryByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "650"),
bannerRow("24", "오프라인", "65"),
bannerRow("24", "온라인/홈쇼핑", "35"),
bannerRow("25", "사례수", "650"),
bannerRow("25", "오프라인", "60"),
bannerRow("25", "온라인/홈쇼핑", "40"),
bannerRow("26", "사례수", "650"),
bannerRow("26", "오프라인", "59"),
bannerRow("26", "온라인/홈쇼핑", "41"),
]
/** ---------------------------
* API #13
* year rowLabel total banner
* 25/26 사례수 + 유통채널
* -------------------------- */
export const apiPurchaseChannelByYear: ServerBannerRow[] = [
bannerRow("24", "사례수", "650"),
bannerRow("24", "오프라인 단독 매장", "25"),
bannerRow("24", "전자제품 양판점", "20"),
bannerRow("24", "대형할인점", "10"),
bannerRow("24", "백화점", "5"),
bannerRow("24", "오픈마켓", "15"),
bannerRow("24", "제조사 공식 홈페이지", "8"),
bannerRow("24", "포털 쇼핑채널 입점몰", "4"),
bannerRow("24", "백화점 기반 쇼핑몰", "2"),
bannerRow("24", "TV 홈쇼핑", "3"),
bannerRow("24", "유통사 온라인 쇼핑몰", "4"),
bannerRow("24", "라이프스타일 쇼핑몰", "2"),
bannerRow("24", "해외 직구/대행 사이트", "1"),
bannerRow("24", "중고거래 사이트", "1"),
bannerRow("25", "사례수", "650"),
bannerRow("25", "오프라인 단독 매장", "25"),
bannerRow("25", "전자제품 양판점", "20"),
bannerRow("25", "대형할인점", "10"),
bannerRow("25", "백화점", "5"),
bannerRow("25", "오픈마켓", "15"),
bannerRow("25", "제조사 공식 홈페이지", "8"),
bannerRow("25", "포털 쇼핑채널 입점몰", "4"),
bannerRow("25", "백화점 기반 쇼핑몰", "2"),
bannerRow("25", "TV 홈쇼핑", "3"),
bannerRow("25", "유통사 온라인 쇼핑몰", "4"),
bannerRow("25", "라이프스타일 쇼핑몰", "2"),
bannerRow("25", "해외 직구/대행 사이트", "1"),
bannerRow("25", "중고거래 사이트", "1"),
bannerRow("26", "사례수", "680"),
bannerRow("26", "오프라인 단독 매장", "24"),
bannerRow("26", "전자제품 양판점", "20"),
bannerRow("26", "대형할인점", "10"),
bannerRow("26", "백화점", "5"),
bannerRow("26", "오픈마켓", "16"),
bannerRow("26", "제조사 공식 홈페이지", "9"),
bannerRow("26", "포털 쇼핑채널 입점몰", "4"),
bannerRow("26", "백화점 기반 쇼핑몰", "2"),
bannerRow("26", "TV 홈쇼핑", "3"),
bannerRow("26", "유통사 온라인 쇼핑몰", "3"),
bannerRow("26", "라이프스타일 쇼핑몰", "2"),
bannerRow("26", "해외 직구/대행 사이트", "1"),
bannerRow("26", "중고거래 사이트", "1"),
];

View File

@@ -9,7 +9,7 @@ import {GAP_WORDING} from "@/const/lgConst";
* 차트 기본 높이 설정
*/
export const CHART_HEIGHTS = {
DEFAULT: 260,
DEFAULT: "100%",
COMPACT: 200,
EXPANDED: 320,
} as const;

View File

@@ -1,166 +1,162 @@
import {BannerKey, LifeStageRow} from "@/types/lg";
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 GAP_WORDING = "전년 대비 GAP(%p)";
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 = {
refrigerator: "냉장고",
kimchiRefrigerator: "김치 냉장고",
dishwasher: "식기 세척기",
waterPurifier: "정수기",
electricRange: "전기 레인지",
foodWasteDisposer: "음식물처리기",
"KPRODUCT#1": "냉장고",
"KPRODUCT#2": "김치 냉장고",
"KPRODUCT#3": "식기 세척기",
"KPRODUCT#4": "정수기",
"KPRODUCT#5": "전기 레인지",
"KPRODUCT#6": "음식물처리기",
washingMachine: "세탁기",
dryer: "건조기",
vacuumCleaner: "청소기",
robotVacuum: "로봇 청소기",
clothingCareSystem: "의류 관리기",
"KPRODUCT#7": "세탁기",
"KPRODUCT#8": "건조기",
"KPRODUCT#9": "청소기",
"KPRODUCT#10": "로봇 청소기",
"KPRODUCT#11": "의류 관리기",
airConditioner: "에어컨",
airPurifier: "공기 청정기",
"KPRODUCT#12": "에어컨",
"KPRODUCT#13": "공기 청정기",
tv: "TV",
monitor: "모니터",
laptop: "노트북",
"KPRODUCT#14": "TV",
"KPRODUCT#15": "모니터",
"KPRODUCT#16": "노트북",
} as const;
export const BANNER_KEY_MAP = {
// 라이프 스테이지
single: "미혼",
noKids: "무자녀",
preschoolKids: "미취학",
schoolKids: "취학자녀",
adultKids: "성인자녀",
independentSenior: "독립시니어",
"KLIFEstAGE#1": "미혼",
"KLIFEstAGE#2": "무자녀",
"KLIFEstAGE#3": "미취학",
"KLIFEstAGE#4": "취학자녀",
"KLIFEstAGE#5": "성인자녀",
"KLIFEstAGE#6": "독립시니어",
// 가구원수
hh1: "1인 가구",
hh2: "2인 가구",
hh3: "3인 가구",
hh4Plus: "4인 이상 가구",
"KSQ8_R_DB#1": "1인 가구",
"KSQ8_R_DB#2": "2인 가구",
"KSQ8_R_DB#3": "3인 가구",
"KSQ8_R_DB#4": "4인 이상 가구",
// 연령
age20s: "20대",
age30s: "30대",
age40s: "40대",
age50s: "50대",
age60s: "60대",
"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대",
// 점유형태
ownerOccupied: "자가",
jeonse: "전세",
depositAndMonthly: "전+월세 (보증금有)",
monthlyNoDeposit: "월세 (보증금無)",
otherOccupancyType: "기타",
"KDQ6#1": "자가",
"KDQ6#2": "전세",
"KDQ6#3": "전+월세 (보증금有)",
"KDQ6#4": "월세 (보증금無)",
"KDQ6#5": "기타",
// 주거형태
apartment: "아파트",
house: "주택",
officetel: "오피스텔",
villa: "(연립)빌라",
studio: "원룸",
otherHousingType: "기타",
"KDQ4#1": "아파트",
"KDQ4#2": "주택",
"KDQ4#3": "오피스텔",
"KDQ4#4": "(연립)빌라",
"KDQ4#5": "원룸",
"KDQ4#6": "기타",
// 평형
under19Pyeong: "19평 이하",
pyeong20s: "20평형 대",
pyeong30s: "30평형 대",
pyeong40s: "40평형 대",
pyeong50Plus: "50평형 대 이상",
"KDQ5#1": "19평 이하",
"KDQ5#2": "20평형 대",
"KDQ5#3": "30평형 대",
"KDQ5#4": "40평형 대",
"KDQ5#5": "50평형 대 이상",
// 권역
regionCapital: "서울, 인천, 경기도",
regionGyeongnamBusanUlsan: "경남, 부산, 울산",
regionGyeongbukDaegu: "경북, 대구",
regionJeollaGwangju: "전라도, 광주",
regionChungcheongDaejeonSejong: "충청, 대전, 세종",
regionGangwonJeju: "강원, 제주",
"KSQ4_R_R#1": "서울, 인천, 경기도",
"KSQ4_R_R#2": "경남, 부산, 울산",
"KSQ4_R_R#3": "경북, 대구",
"KSQ4_R_R#4": "전라도, 광주",
"KSQ4_R_R#5": "충청, 대전, 세종",
"KSQ4_R_R#6": "강원, 제주",
// 소득
incomeUnder299: "299만원 이하",
income300to599: "300~599만원 이하",
income600to899: "600~899만원 이하",
income900Plus: "900만원 이상",
"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: "single", header: "미혼" , headRowSpan:2, max: 100 , align: "left"},
{ key: "KLIFEstAGE#1", header: "미혼" , headRowSpan:2, max: 100 , align: "left"},
{ key: "noKids", header: "무자녀", group: "기혼", max: 100 , align: "left"},
{ key: "preschoolKids", header: "미취학", group: "기혼", max: 100 , align: "left"},
{ key: "schoolKids", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
{ key: "adultKids", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
{ key: "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: "independentSenior", header: "독립\n시니어", headRowSpan:2, max: 100 , align: "left"},
{ key: "KLIFEstAGE#6", header: "독립\n시니어", headRowSpan:2, max: 100 , align: "left"},
];
export const LIFE_STAGE_GROUPS = [
{ title: "대형가전 군", items: ["냉장고", "세탁기", "건조기", "에어컨", "TV", "김치 냉장고", "식기세척기", "의류 관리기"] },
{ title: "소형가전 군", items: ["청소기", "공기 청정기", "정수기"] },
{ title: "신가전 군", items: ["로봇 청소기", "음식물처리기"] },
{ 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 YEARS = ["24", "25", "26"];
export const LAST_YEAR = YEARS.at(-1)!;
export const BRAND_LIST = ['Cbrand', 'Samsung', 'LG'];
/** 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 PRODUCTS_FILTER_ITEM = [
{
path: "kitchen",
items: [
PRODUCT_KEY_MAP.refrigerator, // 냉장고
PRODUCT_KEY_MAP.kimchiRefrigerator, // 김치 냉장고
PRODUCT_KEY_MAP.dishwasher, // 식기 세척기
PRODUCT_KEY_MAP.waterPurifier, // 정수기
PRODUCT_KEY_MAP.electricRange, // 전기 레인지
PRODUCT_KEY_MAP.foodWasteDisposer, // 음식물처리기
"KPRODUCT#1", // 냉장고
"KPRODUCT#2", // 김치 냉장고
"KPRODUCT#3", // 식기 세척기
"KPRODUCT#4", // 정수기
"KPRODUCT#5", // 전기 레인지
"KPRODUCT#6", // 음식물처리기
],
},
{
path: "living",
items: [
PRODUCT_KEY_MAP.washingMachine, // 세탁기
PRODUCT_KEY_MAP.dryer, // 건조기
PRODUCT_KEY_MAP.vacuumCleaner, // 청소기
PRODUCT_KEY_MAP.robotVacuum, // 로봇 청소기
PRODUCT_KEY_MAP.clothingCareSystem, // 의류 관리기
"KPRODUCT#7", // 세탁기
"KPRODUCT#8", // 건조기
"KPRODUCT#9", // 청소기
"KPRODUCT#10", // 로봇 청소기
"KPRODUCT#11", // 의류 관리기
],
},
{
path: "es",
items: [
PRODUCT_KEY_MAP.airConditioner, // 에어컨
PRODUCT_KEY_MAP.airPurifier, // 공기 청정기
"KPRODUCT#12", // 에어컨
"KPRODUCT#13", // 공기 청정기
],
},
{
path: "ms",
items: [
PRODUCT_KEY_MAP.tv, // TV
PRODUCT_KEY_MAP.monitor, // 모니터
PRODUCT_KEY_MAP.laptop, // 노트북
"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;
@@ -170,47 +166,346 @@ export const BANNER_GROUP = {
lifeStage: {
label: "라이프스테이지 별",
keys: [
BANNER_KEY.single,
BANNER_KEY.noKids,
BANNER_KEY.preschoolKids,
BANNER_KEY.schoolKids,
BANNER_KEY.adultKids,
BANNER_KEY.independentSenior,
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.hh1, BANNER_KEY.hh2, BANNER_KEY.hh3, BANNER_KEY.hh4Plus],
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.age20s, BANNER_KEY.age30s, BANNER_KEY.age40s, BANNER_KEY.age50s, BANNER_KEY.age60s],
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.ownerOccupied, BANNER_KEY.jeonse, BANNER_KEY.depositAndMonthly, BANNER_KEY.monthlyNoDeposit, BANNER_KEY.otherOccupancyType],
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.apartment, BANNER_KEY.house, BANNER_KEY.officetel, BANNER_KEY.villa, BANNER_KEY.studio, BANNER_KEY.otherHousingType],
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.under19Pyeong, BANNER_KEY.pyeong20s, BANNER_KEY.pyeong30s, BANNER_KEY.pyeong40s, BANNER_KEY.pyeong50Plus],
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.regionCapital,
BANNER_KEY.regionGyeongnamBusanUlsan,
BANNER_KEY.regionGyeongbukDaegu,
BANNER_KEY.regionJeollaGwangju,
BANNER_KEY.regionChungcheongDaejeonSejong,
BANNER_KEY.regionGangwonJeju,
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.incomeUnder299, BANNER_KEY.income300to599, BANNER_KEY.income600to899, BANNER_KEY.income900Plus],
keys: [
BANNER_KEY["KDQ3_DB#1"],
BANNER_KEY["KDQ3_DB#2"],
BANNER_KEY["KDQ3_DB#3"],
BANNER_KEY["KDQ3_DB#4"],
],
},
} as const;
} 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

@@ -1,7 +1,21 @@
import {BannerGroupKey, ServerBannerRow} from "@/types/lg";
import {
BannerGroupKey,
BannerResponse,
BannerRow, BuildPageModeConfigResult,
ProductResponse, ProductRow,
StatisticsRequest
} from "@/types/lg";
import {ChartData} from "@/components/lge-dashboard";
import {BANNER_GROUP, GAP_WORDING} from "@/const/lgConst";
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("사례수");
@@ -43,6 +57,7 @@ export function formatRowLabel(
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('(대)','')}(대)`;
@@ -183,7 +198,7 @@ type Opts = {
splitStackByYear?: boolean;
};
export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {}): ChartData {
export function buildYearSeriesChartData(rows: BannerRow[], opts: Opts = {}): ChartData {
const {
excludeRowLabels = ["사례수", "gap"],
yearLabel = (y) => `${y}년`,
@@ -225,7 +240,7 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
}
export function buildRowLabelSeriesChartData(
rows: ServerBannerRow[],
rows: BannerRow[],
opts: Opts = {}
): ChartData {
const {
@@ -268,24 +283,24 @@ export function buildRowLabelSeriesChartData(
}
export const buildGapRow = (
rows: ServerBannerRow[],
rows: BannerRow[],
prevYear: number,
curYear: number,
baseRowLabel: string,
gapRowLabel = "gap"
): ServerBannerRow | null => {
): 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: ServerBannerRow = {
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 ServerBannerRow>).forEach((k) => {
(Object.keys(cur) as Array<keyof BannerRow>).forEach((k) => {
if (k === "year" || k === "rowLabel") return;
const vCur = cur[k];
@@ -297,4 +312,207 @@ export const buildGapRow = (
return gap;
}
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;
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 };
};

View File

@@ -1,7 +1,7 @@
// exportDashboardExcel.ts
"use client";
import {formatRowLabel, isSampleRow} from "@/lib/lg-dashboard";
import {formatRowLabel} from "@/lib/lg-dashboard";
import {DataColumn} from "@/components/lge-dashboard";
/**
@@ -269,8 +269,7 @@ function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoF
});
for (let c = 1; c <= colCount; c++) {
const w = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
ws.getColumn(c).width = w;
ws.getColumn(c).width = clamp(widths[c] + o.padding, o.minColWidth, o.maxColWidth);
}
}
@@ -768,7 +767,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
// 데이터
for (const row of rows) {
const excelRow = ws.getRow(rowCursor);
const sampleRow = isSampleRow(valueGetter(row, header.leafKeys.at(0) ?? ""));
//const sampleRow = isSampleRow(valueGetter(row, header.leafKeys.at(0) ?? ""));
header.leafKeys.forEach((key, idx) => {
const cell = excelRow.getCell(idx + 1);
@@ -778,7 +777,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
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 if (sampleRow) cell.value = `(${String(v)})`;
else cell.value = String(v);
const align =

View File

@@ -145,4 +145,16 @@ export function parseNumber(
}
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,34 +1,68 @@
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 ServerBaseRow = {
export type BaseRow = {
year: string;
rowLabel: string;
total: string;
};
// { year, rowLabel, total, ...category }
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, string>>;
export type ProductRow = BaseRow & Partial<Record<ProductKey, string>>;
// { year, rowLabel, total, ...banner }
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
export type ServerBannerRow = ServerBaseRow &
Partial<Record<BannerKey, string>> & {
[k: string]: string;
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;
single: string;
noKids: string;
preschoolKids: string;
schoolKids: string;
adultKids: string;
independentSenior: string;
"KLIFEstAGE#1": string;
"KLIFEstAGE#2": string;
"KLIFEstAGE#3": string;
"KLIFEstAGE#4": string;
"KLIFEstAGE#5": string;
"KLIFEstAGE#6": string;
};
export type LifeStageGroup = {
@@ -38,12 +72,29 @@ export type LifeStageGroup = {
export type BannerGroupKey = keyof typeof BANNER_GROUP;
export type CategoryChartMode = "stack" | "reverseStack" | "horizontal";
export type CategoryChartMode = "none" | "stack" | "reverseStack" | "horizontal";
export type PageData<T> = {
title: string;
chartMode: CategoryChartMode;
data: T[];
chartHeight?: number;
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>;
};