Compare commits
67 Commits
21989aeeb7
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 1da20a1fb6 | |||
| 50e1ea19cc | |||
| fc43eab6fc | |||
| 7474d4d3d4 | |||
| 01208b5b24 | |||
| d6f4bca06f | |||
| 563f98c6f2 | |||
| 20b8547701 | |||
| b740cc27fa | |||
| 9b3a21ea39 | |||
| f4f487ca10 | |||
| 3c7865ef60 | |||
| 849245818c | |||
| 26848901cf | |||
| 3a42ac867c | |||
| ebc72e57c2 | |||
| f6b5b21cb2 | |||
| 59943b2e45 | |||
| c67971f803 | |||
| 882a5f046a | |||
| 8540df7274 | |||
| dc9b2baeb1 | |||
| d58c0b4dd4 | |||
| 5b2811fd86 | |||
| e51c6ba810 | |||
| 3dc735722d | |||
| a0ee062899 | |||
| 8fff3ec908 | |||
| 7f9465e96f | |||
| ee8bb13209 | |||
| 8133ab1ee4 | |||
| 2052c84371 | |||
| 8a6216ef02 | |||
| ffeee5bef2 | |||
| 836f756a42 | |||
| b2cf1b846f | |||
| c66b51ca53 | |||
| 72e18adb03 | |||
| b39c3e8ef9 | |||
| 1751a5071a | |||
| 41a8e2abb2 | |||
| 75153ff02e | |||
| 497301e102 | |||
| eee25ea68f | |||
| 1159993c62 | |||
| 1c2dcb6fd5 | |||
| 4bdb705720 | |||
| 9df181e6dc | |||
| 11321c483b | |||
| 011c727cd6 | |||
| 40b6ddb553 | |||
| 404e5f7351 | |||
| e7688c127c | |||
| 6b118dd7ec | |||
| 357d9f2946 | |||
| d0e1352739 | |||
| edfecfcea4 | |||
| 49ae6ff37e | |||
| 0a81c1a748 | |||
| 6e6120f205 | |||
| b7282bd07d | |||
| 17d75e3f3a | |||
| 6b5454aa59 | |||
| b13f508065 | |||
| ea14a230a1 | |||
| 0ff202afcc | |||
| bd9a95b87f |
@@ -2,6 +2,4 @@ NEXT_PUBLIC_ENV=dev
|
||||
NEXT_PUBLIC_API_BASE=https://test-lg-cxdash.kric.com/api
|
||||
|
||||
ENV=dev
|
||||
API_BACK_SERVER=http://localhost:6101/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
API_BACK_SERVER=http://127.0.0.1:6101/api/v1
|
||||
@@ -3,5 +3,3 @@ NEXT_PUBLIC_API_BASE=http://localhost:6100/api
|
||||
|
||||
ENV=local
|
||||
API_BACK_SERVER=http://localhost:6101/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
@@ -1,7 +1,5 @@
|
||||
NEXT_PUBLIC_ENV=prod
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:6100/api
|
||||
NEXT_PUBLIC_API_BASE=https://lg-cxdash.kric.com/api
|
||||
|
||||
ENV=prod
|
||||
API_BACK_SERVER=http://localhost:6101/api/v1
|
||||
API_KART_SERVER=https://rapi.kric.com/api/v1
|
||||
KART_API_KEY=4B726963-436F6E74616374-46726F6E74-402531213230
|
||||
API_BACK_SERVER=http://127.0.0.1:6101/api/v1
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,5 +1,7 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
.idea
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
|
||||
71
package-lock.json
generated
71
package-lock.json
generated
@@ -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"
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
|
||||
import CategoryPage from "../sub-page/CategoryPage";
|
||||
|
||||
const ESPage = () => {
|
||||
return <CategoryPage/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
|
||||
import CategoryPage from "../sub-page/CategoryPage";
|
||||
|
||||
const KitchenPage = () => {
|
||||
return <CategoryPage/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
|
||||
import CategoryPage from "../sub-page/CategoryPage";
|
||||
|
||||
const LivingPage = () => {
|
||||
return <CategoryPage/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage";
|
||||
import CategoryPage from "../sub-page/CategoryPage";
|
||||
|
||||
const MSPage = () => {
|
||||
return <CategoryPage/>
|
||||
|
||||
120
src/app/(pages)/(main)/category/sub-page/CategoryPage.tsx
Normal file
120
src/app/(pages)/(main)/category/sub-page/CategoryPage.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
'use client'
|
||||
|
||||
import {useMemo} from "react";
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import {CategoryTargetData} from "@/types/filter.types";
|
||||
import {BannerRow, CategoryResolvedField, StatisticsRequest} from "@/types/lg.types";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
|
||||
import {buildCategoryFilter, buildGapRow, buildPageModeConfig} from "@/lib/lg-dashboard";
|
||||
import {BANNER_GROUP_KEY} from "@/const/lg-banner.const";
|
||||
import {API_DECIMAL_POINT, USE_CACHE} from "@/const/lg-common.const";
|
||||
import Profile from "./category-page/Profile";
|
||||
import PenetrationChange from "./category-page/PenetrationChange";
|
||||
import CategoryDetail from "./category-page/CategoryDetail";
|
||||
import {useBannerStatisticsQuery} from "@/query/statistics";
|
||||
|
||||
export type CategoryPageProps = {
|
||||
fields: CategoryResolvedField[];
|
||||
variableIdMap: Record<string, string>;
|
||||
dataMap:Record<string, BannerRow[]> | undefined;
|
||||
fillGreaterThan5?: boolean;
|
||||
isProfileAll?: boolean;
|
||||
}
|
||||
|
||||
const PAGE_COMPONENTS: Partial<Record<CategoryTargetData, React.ComponentType<CategoryPageProps>>> = {
|
||||
[CategoryTargetData.PROFILE]: Profile,
|
||||
[CategoryTargetData.PROFILE_ALL]: Profile,
|
||||
[CategoryTargetData.PENETRATION_CHANGE]: PenetrationChange,
|
||||
[CategoryTargetData.BRAND]: CategoryDetail,
|
||||
[CategoryTargetData.TYPE_SPEC]: CategoryDetail,
|
||||
[CategoryTargetData.BEHAVIOR]: CategoryDetail,
|
||||
[CategoryTargetData.PURCHASE_CHANNEL]: CategoryDetail,
|
||||
[CategoryTargetData.PAYMENT_METHOD]: CategoryDetail,
|
||||
};
|
||||
|
||||
const CategoryPage = () => {
|
||||
const { isTotal, filterValue } = useLayoutFilter();
|
||||
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
|
||||
|
||||
const { fields, variableIdMap } = useMemo(() => {
|
||||
return buildPageModeConfig(debouncedFilterValue);
|
||||
}, [debouncedFilterValue]);
|
||||
|
||||
const req = useMemo<StatisticsRequest>(() => {
|
||||
return {
|
||||
variableIdMap,
|
||||
bannerIdList: BANNER_GROUP_KEY,
|
||||
filterCondition: buildCategoryFilter(debouncedFilterValue),
|
||||
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: 2 },
|
||||
};
|
||||
}, [variableIdMap, debouncedFilterValue]);
|
||||
const { data } = useBannerStatisticsQuery(req);
|
||||
const dataMap = data?.statisticsDataMap;
|
||||
const target = debouncedFilterValue.target;
|
||||
const Comp = PAGE_COMPONENTS[target.value];
|
||||
const isProfileAll = target.value === CategoryTargetData.PROFILE_ALL;
|
||||
const fillGreaterThan5 = Comp === CategoryDetail && !!dataMap;
|
||||
|
||||
const processedDataMap = useMemo(() => {
|
||||
if (!dataMap || target.value !== CategoryTargetData.BRAND) {
|
||||
return dataMap;
|
||||
}
|
||||
|
||||
const nextMap: Record<string, BannerRow[]> = { ...dataMap };
|
||||
|
||||
fields.forEach((f) => {
|
||||
const rows = dataMap[f.requestKeyResolved];
|
||||
if (!rows?.length) return;
|
||||
|
||||
const years = Array.from(new Set(rows.map((row) => Number(row.year))))
|
||||
.filter((year) => Number.isFinite(year))
|
||||
.sort((a, b) => b - a)
|
||||
.slice(0, -1);
|
||||
|
||||
if(years.length === 0) {
|
||||
nextMap[f.requestKeyResolved] = rows;
|
||||
return;
|
||||
}
|
||||
|
||||
const gapRowsByYear = new Map<number, BannerRow>();
|
||||
|
||||
years.forEach((year) => {
|
||||
const currentYear = year;
|
||||
const prevYear = year - 1;
|
||||
const gapRow = buildGapRow(rows, prevYear, currentYear, "LG");
|
||||
|
||||
if(gapRow !== null){
|
||||
gapRowsByYear.set(currentYear, gapRow);
|
||||
}
|
||||
});
|
||||
|
||||
const nextRows: BannerRow[] = [];
|
||||
rows.forEach((row) => {
|
||||
nextRows.push(row);
|
||||
|
||||
const gapRow = gapRowsByYear.get(Number(row.year));
|
||||
if (row.rowLabel === "LG" && gapRow) {
|
||||
nextRows.push(gapRow);
|
||||
}
|
||||
});
|
||||
|
||||
nextMap[f.requestKeyResolved] = nextRows;
|
||||
});
|
||||
|
||||
return nextMap;
|
||||
}, [dataMap, fields, target.value]);
|
||||
|
||||
if(isTotal) return null;
|
||||
return Comp ?
|
||||
<Comp
|
||||
fields={fields}
|
||||
variableIdMap={variableIdMap}
|
||||
dataMap={processedDataMap}
|
||||
fillGreaterThan5={fillGreaterThan5}
|
||||
isProfileAll={isProfileAll}
|
||||
/>
|
||||
: null;
|
||||
}
|
||||
|
||||
export default CategoryPage;
|
||||
@@ -0,0 +1,100 @@
|
||||
import {CategoryPageProps} from "../../sub-page/CategoryPage";
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
|
||||
import {useEffect, useMemo} from "react";
|
||||
import {BannerRow, PageData} from "@/types/lg.types";
|
||||
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
|
||||
import {BANNER_GROUP} from "@/const/lg-banner.const";
|
||||
import {BANNER_KEY_MAP, PRODUCT_KEY_MAP} from "@/const/lg-schema.const";
|
||||
import {QID_SURVEY_TITLE} from "@/const/lg-survey.const";
|
||||
import {SITE_TITLE, YEARS} from "@/const/lg-common.const";
|
||||
import {CategoryByData} from "@/components/lge-dashboard";
|
||||
import {wrapSampleRow} from "@/lib/lg-dashboard";
|
||||
|
||||
const CategoryDetail = ({
|
||||
fields,
|
||||
dataMap,
|
||||
fillGreaterThan5
|
||||
}:CategoryPageProps) => {
|
||||
const {filterValue, registerExcelExporter} = useLayoutFilter();
|
||||
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
|
||||
|
||||
const tableDataArray = useMemo<PageData<BannerRow>[]>(() => {
|
||||
const tempTableDataArray = fields.map((f) :PageData<BannerRow> => {
|
||||
const dataLength = dataMap?.[f.requestKeyResolved].filter((row) => row.rowLabel !=`사례수`).length;
|
||||
const qid = f.qidByMode[debouncedFilterValue.type.value];
|
||||
|
||||
let surveyTitle = qid? QID_SURVEY_TITLE[qid] ?? "" : "";
|
||||
surveyTitle = surveyTitle.replaceAll("[#YEAR#]", debouncedFilterValue.year);
|
||||
surveyTitle = surveyTitle.replaceAll("[#NEXT_YEAR#]", String(Number(debouncedFilterValue.year) + 1));
|
||||
|
||||
return {
|
||||
title: typeof f.title === "string"? f.title : f.title[debouncedFilterValue.type.value],
|
||||
surveyTitle: surveyTitle,
|
||||
chartMode:f.chartMode,
|
||||
chartLegend:f.chartLegend,
|
||||
chartTopMargin:f.chartTopMargin,
|
||||
data: dataLength && dataLength > 0 ? wrapSampleRow(dataMap[f.requestKeyResolved]) : []
|
||||
};
|
||||
});
|
||||
|
||||
//사례수만 있는 테이블은 아예 제외
|
||||
return tempTableDataArray.filter((tableData) => tableData.data.length > 0);
|
||||
}, [debouncedFilterValue, fields, dataMap]);
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
registerExcelExporter(async () => {
|
||||
const product = PRODUCT_KEY_MAP[debouncedFilterValue.product];
|
||||
const type = debouncedFilterValue.type.label;
|
||||
const target = debouncedFilterValue.target.label.replaceAll('/', '_');
|
||||
|
||||
const sheetName = `${product}_${type}_${target}`
|
||||
const h3 = buildHeader_Banner(BANNER_GROUP, BANNER_KEY_MAP);
|
||||
const years = [
|
||||
debouncedFilterValue.year,
|
||||
String(Number(debouncedFilterValue.year) - 1),
|
||||
].filter((year) => YEARS.includes(year));
|
||||
|
||||
type AnyRow = Record<string, any>;
|
||||
const sections: Section<AnyRow>[] = tableDataArray.flatMap((tableData) => {
|
||||
return years.map((year) => ({
|
||||
title: `${tableData.title}_${year}년`,
|
||||
header: h3,
|
||||
rows: tableData.data.filter((d) => d.year === year) as AnyRow[],
|
||||
rowGap: 1,
|
||||
}));
|
||||
});
|
||||
|
||||
await exportDashboardExcel({
|
||||
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
|
||||
sheetName: sheetName,
|
||||
sections: sections,
|
||||
});
|
||||
});
|
||||
return () => registerExcelExporter(null);
|
||||
}, [registerExcelExporter, debouncedFilterValue, tableDataArray]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{tableDataArray.map((tableData) => (
|
||||
<CategoryByData
|
||||
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
|
||||
selectedYear={debouncedFilterValue.year}
|
||||
title={tableData.title}
|
||||
surveyTitle={tableData.surveyTitle}
|
||||
chartMode={tableData.chartMode}
|
||||
chartLegend={tableData.chartLegend}
|
||||
chartTopMargin={tableData.chartTopMargin}
|
||||
allTableData={tableData.data}
|
||||
chartHeight={tableData.chartHeight}
|
||||
chartWidth={tableData.chartWidth}
|
||||
fillGreaterThan5={fillGreaterThan5}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default CategoryDetail;
|
||||
@@ -0,0 +1,72 @@
|
||||
'use client'
|
||||
|
||||
import {DataColumn} from "@/components/lge-dashboard";
|
||||
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
|
||||
import {useMemo} from "react";
|
||||
import {parseNumber} from "@/lib/utils";
|
||||
import {BannerRow} from "@/types/lg.types";
|
||||
import {CategoryPageProps} from "../../sub-page/CategoryPage";
|
||||
import {LAST_YEAR} from "@/const/lg-common.const";
|
||||
|
||||
const PenetrationChange = ({
|
||||
dataMap
|
||||
}:CategoryPageProps) => {
|
||||
|
||||
const penetrationChangeData = useMemo<BannerRow[]>(() => {
|
||||
if (dataMap === undefined) return [];
|
||||
|
||||
const tempProfileData: BannerRow[] = [];
|
||||
Object.keys(dataMap).forEach(requestKey => {
|
||||
const data = dataMap[requestKey];
|
||||
tempProfileData.push(
|
||||
...data.filter((r) => r.rowLabel === `사례수` && r.year === LAST_YEAR),
|
||||
...data.filter((r) => r.rowLabel === `보유`)
|
||||
.map((row) => {
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
}
|
||||
}));
|
||||
});
|
||||
|
||||
return tempProfileData;
|
||||
}, [dataMap]);
|
||||
|
||||
const getCellClassName = (row: BannerRow, column: DataColumn<BannerRow>, rowIndex: number) => {
|
||||
if (!("key" in column) || column.key === undefined) return undefined;
|
||||
|
||||
const currentYear = Number(row.year);
|
||||
if (currentYear !== 2024 && currentYear !== 2025) return undefined;
|
||||
if (column.key === "rowLabel" || column.key === "total") return undefined;
|
||||
|
||||
const prevRow = penetrationChangeData[rowIndex - 1];
|
||||
if (!prevRow || Number(prevRow.year) !== currentYear - 1) return undefined;
|
||||
|
||||
const currentValue = parseNumber(row[column.key]);
|
||||
const prevValue = parseNumber(prevRow[column.key]);
|
||||
if (currentValue === null || prevValue === null) return undefined;
|
||||
|
||||
const gap = currentValue - prevValue;
|
||||
|
||||
if (gap >= 3) return "lg-num-pos";
|
||||
if (gap <= -3) return "lg-num-neg";
|
||||
|
||||
return undefined;
|
||||
};
|
||||
|
||||
return(
|
||||
<>
|
||||
<BannerSummary
|
||||
data={penetrationChangeData}
|
||||
useChart={true}
|
||||
useYear={false}
|
||||
getCellClassName={getCellClassName}
|
||||
/>
|
||||
<div className="content-text-base font-bold mt-2">
|
||||
전년 대비 GAP ±3%p 이상 수치 강조 : <span className="lg-num-pos"> 상승</span> / <span className="lg-num-neg">하락</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default PenetrationChange
|
||||
@@ -0,0 +1,88 @@
|
||||
'use client'
|
||||
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary";
|
||||
import {useMemo} from "react";
|
||||
import {BannerRow} from "@/types/lg.types";
|
||||
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import { calcGapBannerRow } from "@/lib/lg-dashboard";
|
||||
import {YEARS} from "@/const/lg-common.const";
|
||||
import {CategoryTargetType} from "@/types/filter.types";
|
||||
import {CategoryPageProps} from "../../sub-page/CategoryPage";
|
||||
|
||||
const Profile = ({
|
||||
dataMap,
|
||||
isProfileAll,
|
||||
}:CategoryPageProps) => {
|
||||
const { filterValue } = useLayoutFilter();
|
||||
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
|
||||
|
||||
const profileData = useMemo<BannerRow[]>(() => {
|
||||
if (dataMap === undefined) return [];
|
||||
|
||||
const targetMap = {
|
||||
[CategoryTargetType.PENETRATION]: "보유",
|
||||
[CategoryTargetType.PURCHASE]: "구매",
|
||||
[CategoryTargetType.INTENDED]: "향후구매",
|
||||
}
|
||||
|
||||
const tempProfileData: BannerRow[] = [];
|
||||
Object.keys(dataMap).forEach(requestKey => {
|
||||
const data = dataMap[requestKey];
|
||||
|
||||
if(requestKey.toLowerCase().endsWith("count")){
|
||||
tempProfileData.push(
|
||||
...data.filter((r) => r.rowLabel == `MEAN`)
|
||||
.map((row) => {
|
||||
return {
|
||||
...row,
|
||||
rowLabel: "보유대수",
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
else{
|
||||
const target = debouncedFilterValue.type.value;
|
||||
|
||||
tempProfileData.push(...data.filter((r) => r.rowLabel == `사례수`));
|
||||
|
||||
const targetData =
|
||||
data.filter((r) => r.rowLabel == targetMap[target])
|
||||
.map((row) => {
|
||||
return {
|
||||
...row,
|
||||
rowLabel: isProfileAll ? `${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));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
tempProfileData.sort((a, b) => Number(a.rowLabel === "보유대수") - Number(b.rowLabel === "보유대수"));
|
||||
tempProfileData.sort((a, b) => Number(a.year) - Number(b.year));
|
||||
|
||||
return tempProfileData;
|
||||
}, [debouncedFilterValue, dataMap, isProfileAll]);
|
||||
|
||||
return (
|
||||
<BannerSummary
|
||||
data={profileData}
|
||||
useChart={false}
|
||||
useYear={!isProfileAll}
|
||||
isProfileAll={isProfileAll}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default Profile;
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
BottomDescription,
|
||||
GroupedOverlayBar,
|
||||
type GroupedOverlayBarData,
|
||||
signStyleGapRow,
|
||||
@@ -8,61 +9,154 @@ import {
|
||||
type TopChartTableRow,
|
||||
} from "@/components/lge-dashboard";
|
||||
import {
|
||||
LAST_YEAR,
|
||||
LIFE_STAGE_COLUMNS,
|
||||
LIFE_STAGE_GROUPS,
|
||||
PRODUCT_KEY_MAP,
|
||||
PRODUCT_KEYS,
|
||||
PRODUCTS, SITE_TITLE,
|
||||
YEARS
|
||||
} from "@/const/lgConst";
|
||||
} from "@/const/lg-product.const";
|
||||
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import {
|
||||
API_DECIMAL_POINT,
|
||||
SITE_TITLE,
|
||||
USE_CACHE,
|
||||
YEARS,
|
||||
} from "@/const/lg-common.const";
|
||||
import { CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR } from "@/components/lge-dashboard/chart/chart.config";
|
||||
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, wrapSampleRow
|
||||
} 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.types";
|
||||
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
|
||||
import {SelectedMap} from "@/types/common";
|
||||
import {useBannerStatisticsQuery, useProductStatisticsQuery} from "@/query/statistics";
|
||||
|
||||
const LGPenetrationPage = () => {
|
||||
const { filterValue, registerExcelExporter } = useLayoutFilter();
|
||||
console.log(filterValue);
|
||||
const {filterValue, registerExcelExporter} = useLayoutFilter();
|
||||
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
|
||||
|
||||
//TODO: LG가 0인 제품은 제외시키기
|
||||
const req = useMemo<StatisticsRequest>(() => {
|
||||
return {
|
||||
variableIdMap: {penetration: "KQA1", penetration_lg: "KQA3_3_LG"},
|
||||
bannerIdList: ["product"],
|
||||
filterCondition: normalizeFilterCondition(debouncedFilterValue),
|
||||
option: {useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
|
||||
};
|
||||
}, [debouncedFilterValue]);
|
||||
|
||||
const req_lifestage = useMemo<StatisticsRequest>(() => {
|
||||
const filter = {...debouncedFilterValue, "":""}
|
||||
|
||||
return {
|
||||
variableIdMap: {lifestage_lg: "KQA3_3_LG"},
|
||||
bannerIdList: ["product|lifeStage"],
|
||||
filterCondition: normalizeFilterCondition(filter),
|
||||
option: {useCache: USE_CACHE, lastYear: true, decimalPoint: API_DECIMAL_POINT },
|
||||
};
|
||||
}, [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) => {
|
||||
const rowSample = data?.statisticsDataMap?.penetration
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
const penetrationLGRows =
|
||||
data?.statisticsDataMap?.penetration_lg
|
||||
.filter((r) => r.rowLabel == `보유`)
|
||||
.map((row) => {
|
||||
const rowSample = data?.statisticsDataMap?.penetration_lg
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
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, -1, -2);
|
||||
|
||||
return withTotalBaseRow("보급률",penetrationRows, wrapSampleRow(withGap, false), calcTotalBaseRow);
|
||||
}, [penetrationRows, penetrationLGRows]);
|
||||
|
||||
const productTableRows = useMemo<TopChartTableRow[]>(() => {
|
||||
return apiOwnShareOfTotalPenetration.map((row) => ({
|
||||
return penetrationLGRowsWithGap.map((row) => ({
|
||||
label: formatRowLabel(row.rowLabel),
|
||||
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
|
||||
sample: row.sample,
|
||||
total: row.total,
|
||||
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
|
||||
}));
|
||||
}, []);
|
||||
}, [penetrationLGRowsWithGap, includeProductKeys]);
|
||||
|
||||
const productChartData = useMemo<GroupedOverlayBarData>(() => {
|
||||
const total: Array<Array<number>> = YEARS.map(() => Array(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);
|
||||
@@ -71,41 +165,54 @@ 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`] ?? "",
|
||||
"KLIFEstAGE#7": lifeStageData[`${key}|KLIFEstAGE#7`] ?? "",
|
||||
"KLIFEstAGE#8": lifeStageData[`${key}|KLIFEstAGE#8`] ?? "",
|
||||
};
|
||||
});
|
||||
|
||||
return { title: g.title, rows };
|
||||
return {title: g.title, rows};
|
||||
});
|
||||
}, [lifeStageRows]);
|
||||
|
||||
const description = useMemo(() => {
|
||||
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
|
||||
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
|
||||
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?<br/>" +
|
||||
"** 조사 년도 보급률 중 자사제품 비율 = (LG 보급률 ÷ 전체 보급률) × 100";
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
registerExcelExporter(async () => {
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
|
||||
const excelHeader = buildHeader_ProductKeyMap(productKeyMap, "sample");
|
||||
const lifeStageHeader = buildHeader_LifeStageColumns(LIFE_STAGE_COLUMNS);
|
||||
|
||||
type AnyRow = Record<string, any>;
|
||||
@@ -114,7 +221,7 @@ const LGPenetrationPage = () => {
|
||||
{
|
||||
title: "LG제품 보급률",
|
||||
header: excelHeader,
|
||||
rows: apiOwnShareOfTotalPenetration as AnyRow[],
|
||||
rows: penetrationLGRowsWithGap as AnyRow[],
|
||||
rowGap: 1,
|
||||
},
|
||||
|
||||
@@ -133,26 +240,30 @@ 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-total-1", "25": "--chart-total-2", "26": "--chart-total-3" }}
|
||||
yearFocusColor={{ "24": "--chart-lg-1", "25": "--chart-lg-2", "26": "--chart-lg-3" }}
|
||||
questionText={"보급률"}
|
||||
yearTotalColor={CHART_COLOR_BY_YEAR}
|
||||
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
|
||||
showFocusLabel={"last"}
|
||||
height={260}
|
||||
/>
|
||||
}
|
||||
signStyle={signStyleGapRow}
|
||||
/>
|
||||
|
||||
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup} />
|
||||
<BottomDescription description={description}/>
|
||||
|
||||
<LifeStageDiv lifeStageRowsByGroup={lifeStageRowsByGroup}/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,101 +1,192 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo} from "react";
|
||||
import {LAST_YEAR, PRODUCT_KEY_MAP, PRODUCT_KEYS, PRODUCTS, SITE_TITLE, YEARS} from "@/const/lgConst";
|
||||
import {
|
||||
PRODUCT_KEYS,
|
||||
} from "@/const/lg-product.const";
|
||||
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import {
|
||||
API_DECIMAL_POINT,
|
||||
SITE_TITLE,
|
||||
USE_CACHE,
|
||||
YEARS,
|
||||
} from "@/const/lg-common.const";
|
||||
import { CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR } from "@/components/lge-dashboard/chart/chart.config";
|
||||
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, wrapSampleRow
|
||||
} 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.types";
|
||||
import {useProductStatisticsQuery} from "@/query/statistics";
|
||||
import {toNumOr0} from "@/lib/utils";
|
||||
|
||||
const LGPurchasePage = () => {
|
||||
const { filterValue, registerExcelExporter } = useLayoutFilter();
|
||||
console.log(filterValue);
|
||||
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
|
||||
|
||||
//TODO: LG가 0인 제품은 제외시키기
|
||||
const req = useMemo<StatisticsRequest>(() => {
|
||||
return {
|
||||
variableIdMap: {purchase: "KQB0", purchase_lg: "KQX3_3_LG"},
|
||||
bannerIdList: ["product"],
|
||||
filterCondition: normalizeFilterCondition(debouncedFilterValue),
|
||||
option: {useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
|
||||
};
|
||||
}, [debouncedFilterValue]);
|
||||
|
||||
const {data, isError, error} = useProductStatisticsQuery(req);
|
||||
|
||||
if(isError){
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
const purchaseRows =
|
||||
data?.statisticsDataMap?.purchase
|
||||
.filter((r) => r.rowLabel == `구매`)
|
||||
.map((row) => {
|
||||
const rowSample = data?.statisticsDataMap?.purchase
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
const purchaseLGRows =
|
||||
data?.statisticsDataMap?.purchase_lg
|
||||
.filter((row) => row.rowLabel === `구입`)
|
||||
.map((row) => {
|
||||
const rowSample = data?.statisticsDataMap?.purchase_lg
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
const purchaseLGRowsWithGap = useMemo(() => {
|
||||
const withGap = withGapRow(wrapSampleRow(purchaseLGRows, false), calcGapProductRow, -1, -2);
|
||||
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),
|
||||
values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null),
|
||||
sample: row.sample,
|
||||
total: row.total,
|
||||
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
|
||||
}));
|
||||
}, []);
|
||||
}, [purchaseLGRowsWithGap, includeProductKeys]);
|
||||
|
||||
const purchaseChartData = useMemo<GroupedOverlayBarData>(() => {
|
||||
const total: Array<Array<number>> = YEARS.map(() => Array(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];
|
||||
const v = (r 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/>" +
|
||||
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
|
||||
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>" +
|
||||
//"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
|
||||
//"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
|
||||
//"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.<br/>" +
|
||||
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?<br/>" +
|
||||
"** 조사 년도 구매율 중 자사제품 비율 = (LG 구매율 ÷ 전체 구매율) × 100";
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
registerExcelExporter(async () => {
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
|
||||
const excelHeader = buildHeader_ProductKeyMap(productKeyMap, "sample");
|
||||
|
||||
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-total-1", "25": "--chart-total-2", "26": "--chart-total-3" }}
|
||||
yearFocusColor={{ "24": "--chart-lg-1", "25": "--chart-lg-2", "26": "--chart-lg-3" }}
|
||||
questionText={"구매율"}
|
||||
yearTotalColor={CHART_COLOR_BY_YEAR}
|
||||
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
|
||||
showFocusLabel={"last"}
|
||||
height={260}
|
||||
/>
|
||||
}
|
||||
signStyle={signStyleGapRow}
|
||||
/>
|
||||
|
||||
<BottomDescription description={description}/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -8,50 +8,116 @@ import {
|
||||
GroupedStackBar,
|
||||
signStyleGapRow,
|
||||
type TopChartTableRow,
|
||||
type GroupedStackBarData,
|
||||
type GroupedStackBarData, BottomDescription,
|
||||
} from "@/components/lge-dashboard";
|
||||
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
|
||||
import {apiBrandByYearCategories, apiOwnShareOfTotalPenetration, apiTrendCategories} from "@/config/sample.data";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
BRAND_LIST,
|
||||
PRODUCT_KEYS,
|
||||
PRODUCTS,
|
||||
YEARS,
|
||||
AXIS_HIDE_STYLE,
|
||||
GRID_X_NOT_PADDING, PRODUCT_KEY_MAP, LAST_YEAR, SITE_TITLE,
|
||||
} from "@/const/lgConst";
|
||||
import { formatRowLabel } from "@/lib/lg-dashboard";
|
||||
SITE_TITLE,
|
||||
USE_CACHE,
|
||||
API_DECIMAL_POINT,
|
||||
} from "@/const/lg-common.const";
|
||||
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import { PRODUCT_KEYS, PRODUCTS } from "@/const/lg-product.const";
|
||||
import { AXIS_HIDE_STYLE, GRID_X_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import {
|
||||
calcCagrRow, calcGapProductRow,
|
||||
formatRowLabel,
|
||||
normalizeFilterCondition, withCagrRow, withGapRow, wrapSampleRow
|
||||
} from "@/lib/lg-dashboard";
|
||||
import {buildHeader_ProductKeyMap, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
|
||||
import {StatisticsRequest} from "@/types/lg.types";
|
||||
import {useProductStatisticsQuery} from "@/query/statistics";
|
||||
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);
|
||||
const [isBrandShare, setIsBrandShare] = useState(false);
|
||||
|
||||
const req = useMemo<StatisticsRequest>(() => {
|
||||
return {
|
||||
variableIdMap: { penetration: "KQA1", penetration_brand: "KQA3_3_NET" },
|
||||
bannerIdList: ["product"],
|
||||
filterCondition: normalizeFilterCondition(debouncedFilterValue),
|
||||
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
|
||||
};
|
||||
}, [debouncedFilterValue]);
|
||||
|
||||
const { data, isError, error } = useProductStatisticsQuery(req);
|
||||
|
||||
if(isError){
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
const penetrationRows =
|
||||
data?.statisticsDataMap?.penetration
|
||||
.filter((r) => r.rowLabel == `보유`)
|
||||
.map((row) => {
|
||||
const rowSample = data?.statisticsDataMap?.penetration
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
const penetrationBrandRows = (
|
||||
data?.statisticsDataMap?.penetration_brand
|
||||
?.filter((row) => BRAND_LIST.includes(row.rowLabel)) ?? []
|
||||
).map((row) => {
|
||||
PRODUCT_KEYS.forEach((k) => {
|
||||
(row as any)[k] = Number((row as any)[k]).toFixed(0);
|
||||
});
|
||||
|
||||
return row;
|
||||
});
|
||||
|
||||
const penetrationRowsWithGapCagr = useMemo(() => {
|
||||
const withGap = withGapRow(penetrationRows, calcGapProductRow, -1, -2);
|
||||
const withCagr = withCagrRow(withGap, calcCagrRow, -1, 1);
|
||||
|
||||
withCagr.forEach((row) => {
|
||||
if (row.rowLabel !== "CAGR") {
|
||||
PRODUCT_KEYS.forEach((k) => {
|
||||
(row as any)[k] = Number((row as any)[k]).toFixed(0);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return wrapSampleRow(withCagr, false);
|
||||
}, [penetrationRows]);
|
||||
|
||||
const productTableRows = useMemo<TopChartTableRow[]>(() => {
|
||||
return apiTrendCategories.map((row) => ({
|
||||
return penetrationRowsWithGapCagr.map((row) => ({
|
||||
label: formatRowLabel(row.rowLabel),
|
||||
sample: row.sample,
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -69,20 +135,30 @@ const PenetrationPage = () => {
|
||||
});
|
||||
|
||||
return { categories: PRODUCTS, years: YEARS, brands: BRAND_LIST, values };
|
||||
}, []);
|
||||
}, [penetrationBrandRows]);
|
||||
|
||||
const description = useMemo(() => {
|
||||
if(isBrandShare){
|
||||
return "Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
|
||||
}
|
||||
|
||||
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
|
||||
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.";
|
||||
}, [isBrandShare]);
|
||||
|
||||
useEffect(() => {
|
||||
registerExcelExporter(async () => {
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP, "sample");
|
||||
const brandHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
|
||||
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[],
|
||||
header: brandHeader,
|
||||
rows: penetrationBrandRows.filter((row) => row.year === year),
|
||||
rowGap: 1,
|
||||
}
|
||||
))
|
||||
@@ -95,7 +171,7 @@ const PenetrationPage = () => {
|
||||
});
|
||||
});
|
||||
return () => registerExcelExporter(null);
|
||||
}, [registerExcelExporter]);
|
||||
}, [registerExcelExporter, penetrationRowsWithGapCagr, penetrationBrandRows]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -105,27 +181,24 @@ const PenetrationPage = () => {
|
||||
variant={isBrandShare ? "default" : "secondary"}
|
||||
onClick={() => setIsBrandShare((v) => !v)}
|
||||
>
|
||||
{"브랜드별 점유율"}
|
||||
{"브랜드 점유율 변화"}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<TopChartTable
|
||||
title={isBrandShare ? "브랜드별 점유율" : "전체 보급률"}
|
||||
title={isBrandShare ? "브랜드 점유율 변화" : "전체 보급률"}
|
||||
categories={[...PRODUCTS]}
|
||||
rows={productTableRows}
|
||||
chart={
|
||||
isBrandShare ? (
|
||||
<GroupedStackBar
|
||||
data={brandShareChartData}
|
||||
grid={{ ...GRID_X_NOT_PADDING, top: 60 }}
|
||||
grid={{...GRID_X_NOT_PADDING, bottom: 20}}
|
||||
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={[ "--chart-etc", "--chart-cbrand","--chart-samsung","--chart-lg"]}
|
||||
height={260}
|
||||
/>
|
||||
) : (
|
||||
<VerticalBar
|
||||
@@ -140,7 +213,10 @@ const PenetrationPage = () => {
|
||||
)
|
||||
}
|
||||
signStyle={signStyleGapRow}
|
||||
fillCAGR={true}
|
||||
/>
|
||||
<BottomDescription description={"CAGR(%) 5%p 이상 품목에 대해 음영 표시"} />
|
||||
<BottomDescription description={description} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,56 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import {useEffect, useMemo} from "react";
|
||||
import {PRODUCT_KEYS, PRODUCTS, AXIS_HIDE_STYLE, GRID_X_NOT_PADDING, LAST_YEAR, PRODUCT_KEY_MAP} from "@/const/lgConst";
|
||||
import {
|
||||
PRODUCT_KEYS,
|
||||
PRODUCTS,
|
||||
} from "@/const/lg-product.const";
|
||||
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import {
|
||||
SITE_TITLE,
|
||||
USE_CACHE,
|
||||
API_DECIMAL_POINT,
|
||||
} from "@/const/lg-common.const";
|
||||
import { AXIS_HIDE_STYLE, GRID_X_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import {
|
||||
BottomDescription,
|
||||
type ChartData,
|
||||
signStyleGapRow,
|
||||
TopChartTable,
|
||||
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,
|
||||
wrapSampleRow
|
||||
} 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.types";
|
||||
import {useProductStatisticsQuery} from "@/query/statistics";
|
||||
|
||||
const PurchasePage = () => {
|
||||
const { filterValue, registerExcelExporter } = useLayoutFilter();
|
||||
console.log(filterValue);
|
||||
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap);
|
||||
|
||||
const req = useMemo<StatisticsRequest>(() => {
|
||||
return {
|
||||
variableIdMap: { purchase: "KQB0"},
|
||||
bannerIdList: ["product"],
|
||||
filterCondition: normalizeFilterCondition(debouncedFilterValue),
|
||||
option: { useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
|
||||
};
|
||||
}, [debouncedFilterValue]);
|
||||
|
||||
const { data, isError, error } = useProductStatisticsQuery(req);
|
||||
|
||||
if(isError){
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
const purchaseRows =
|
||||
data?.statisticsDataMap?.purchase
|
||||
.filter((r) => r.rowLabel == `구매`)
|
||||
.map((row) => {
|
||||
const rowSample = data?.statisticsDataMap?.purchase
|
||||
.find(r => r.rowLabel == '사례수' && r.year == row.year)?.total ?? 0;
|
||||
|
||||
return {
|
||||
...row,
|
||||
rowLabel: row.year,
|
||||
sample: `(${rowSample})`,
|
||||
}
|
||||
}) ?? [];
|
||||
|
||||
const purchaseRowsWithGap = useMemo(() => {
|
||||
return withGapRow(wrapSampleRow(purchaseRows, false), calcGapProductRow, -1, -2);
|
||||
}, [purchaseRows]);
|
||||
|
||||
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
|
||||
return apiTrendBuy.map((row) => ({
|
||||
return purchaseRowsWithGap.map((row) => ({
|
||||
label: formatRowLabel(row.rowLabel),
|
||||
sample: row.sample,
|
||||
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.filter((r) => !r.rowLabel.includes("사례수"))
|
||||
.map((r) => ({
|
||||
name: r.rowLabel,
|
||||
data: PRODUCT_KEYS.map((k) => (r as any)[k] ?? null),
|
||||
})),
|
||||
};
|
||||
}, [purchaseRows]);
|
||||
|
||||
const description = useMemo(() => {
|
||||
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
|
||||
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
|
||||
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>";
|
||||
/*
|
||||
"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
|
||||
"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
|
||||
"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.";
|
||||
*/
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
registerExcelExporter(async () => {
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP);
|
||||
const excelHeader = buildHeader_ProductKeyMap(PRODUCT_KEY_MAP, "sample");
|
||||
|
||||
await exportDashboardExcel({
|
||||
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>
|
||||
@@ -64,13 +129,15 @@ const PurchasePage = () => {
|
||||
paletteVarNames={["--chart-3", "--chart-2", "--chart-1"]}
|
||||
grid={GRID_X_NOT_PADDING}
|
||||
xAxis={{ type: "category", data: [...PRODUCTS], ...AXIS_HIDE_STYLE }}
|
||||
yAxis={{ type: "value", ...AXIS_HIDE_STYLE }}
|
||||
yAxis={{ type: "value", min:0, max:100, ...AXIS_HIDE_STYLE }}
|
||||
showFocusLabel={"last"}
|
||||
height={260}
|
||||
/>
|
||||
}
|
||||
signStyle={signStyleGapRow}
|
||||
/>
|
||||
|
||||
<BottomDescription description={description} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,30 +1,16 @@
|
||||
import {createBackApi} from "@/lib/server-api";
|
||||
import {LoginRequest, LoginUser} from "@/types/auth";
|
||||
import {LoginRequest, LoginResponse, LoginUser} from "@/types/auth";
|
||||
import {NextRequest, NextResponse} from "next/server";
|
||||
import {serverEnv} from "@/lib/env.server";
|
||||
import {errorToResponse} from "@/lib/http-util";
|
||||
|
||||
type LoginResponse = {
|
||||
accessToken: string;
|
||||
user: LoginUser;
|
||||
};
|
||||
|
||||
export const POST = async (req: NextRequest) => {
|
||||
try {
|
||||
const backApi = await createBackApi();
|
||||
|
||||
const body = (await req.json()) as LoginRequest;
|
||||
//const result = await backApi.post<LoginResponse>("/auth/login", body);
|
||||
const result:LoginResponse = {
|
||||
accessToken: "abcdefghijklmnopqrstuvwxyz0123456789",
|
||||
user: {
|
||||
userId: "TEST_USER",
|
||||
userName: "TEST_USER",
|
||||
userCmpn: "TEST",
|
||||
userTeam: "TEST",
|
||||
userRole: 9999,
|
||||
}
|
||||
}
|
||||
|
||||
const result = await backApi.post<LoginResponse>("/auth/login", body);
|
||||
|
||||
const res = NextResponse.json(result.user, { status: 200 });
|
||||
res.cookies.set("access_token", result.accessToken, {
|
||||
|
||||
39
src/app/api/statistics/[[...slug]]/route.ts
Normal file
39
src/app/api/statistics/[[...slug]]/route.ts
Normal 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.types";
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -54,17 +54,6 @@
|
||||
--color-warning: var(--warning);
|
||||
--color-info: var(--info);
|
||||
|
||||
/* Chart */
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-chart-6: var(--chart-6);
|
||||
--color-chart-7: var(--chart-7);
|
||||
--color-chart-8: var(--chart-8);
|
||||
--color-chart-9: var(--chart-9);
|
||||
--color-chart-10: var(--chart-10);
|
||||
--color-chart-border: var(--chart-border);
|
||||
|
||||
/* Sidebar (shadcn sidebar 토큰) */
|
||||
@@ -108,6 +97,8 @@
|
||||
--lg-gray-400: 0 0% 50%; /* #7F7F7F */
|
||||
--lg-gray-300: 0 0% 75%; /* #BFBFBF */
|
||||
--lg-gray-200: 0 0% 85%; /* #D9D9D9 */
|
||||
--lg-gray-100: 0 0% 92%; /* #EBEBEB */
|
||||
--lg-gray-50: 0 0% 96%; /* #F5F5F5 */
|
||||
|
||||
--lg-red-600: 341.1 100% 32.4%; /* #A50034 */
|
||||
--lg-red-500: 341.1 95% 44.0%; /* #DB0649 */
|
||||
@@ -134,11 +125,6 @@
|
||||
--lg-orange-500: 29.6 95% 56.0%;
|
||||
--lg-orange-400: 29.6 85% 68.0%;
|
||||
--lg-orange-300: 29.6 75% 78.0%;
|
||||
|
||||
--samsung-blue-600: 218.93 53.91% 52.35%; /* #4472C7 */
|
||||
--samsung-blue-500: 218.93 48.0% 56.0%; /* #597FC5 */
|
||||
--samsung-blue-400: 218.93 40.0% 66.0%; /* #869ECB */
|
||||
--samsung-blue-300: 218.93 33.0% 76.0%; /* #AEBCD6 */
|
||||
/* =============================
|
||||
Brand Core
|
||||
(semantic은 "실제 색"으로 정의)
|
||||
@@ -176,29 +162,32 @@
|
||||
/* =============================
|
||||
Chart Colors
|
||||
============================= */
|
||||
--chart-1: var(--lg-red-600);
|
||||
--chart-2: var(--lg-red-300);
|
||||
--chart-3: var(--lg-pink-300);
|
||||
--chart-4: var(--lg-pink-400);
|
||||
--chart-5: var(--lg-pink-600);
|
||||
--chart-6: var(--lg-gray-500);
|
||||
--chart-7: var(--lg-gray-600);
|
||||
--chart-8: var(--lg-gray-700);
|
||||
--chart-9: var(--lg-gray-800);
|
||||
--chart-10: var(--lg-gray-900);
|
||||
--chart-1: 334 81% 41%;
|
||||
--chart-2: 0 0% 49%;
|
||||
--chart-3: 0 0% 74%;
|
||||
--chart-1-t: 334 80% 90%;
|
||||
--chart-2-t: 0 0% 70%;
|
||||
--chart-3-t: 0 0% 88%;
|
||||
|
||||
--chart-lg-1: var(--lg-pink-300);
|
||||
--chart-lg-2: var(--lg-red-300);
|
||||
--chart-lg-3: var(--lg-red-600);
|
||||
--chart-total-1: var(--lg-gray-300);
|
||||
--chart-total-2: var(--lg-gray-400);
|
||||
--chart-total-3: var(--lg-gray-700);
|
||||
--chart-cbrand-1: var(--lg-gray-300);
|
||||
--chart-cbrand-2: var(--lg-gray-400);
|
||||
--chart-cbrand-3: var(--lg-gray-700);
|
||||
--chart-samsung-1: var(--samsung-blue-400);
|
||||
--chart-samsung-2: var(--samsung-blue-500);
|
||||
--chart-samsung-3: var(--samsung-blue-600);
|
||||
--chart-stack-1: 335 64% 34%;
|
||||
--chart-stack-2: 332 65% 57%;
|
||||
--chart-stack-3: 334 66% 73%;
|
||||
--chart-stack-4: 334 28% 49%;
|
||||
--chart-stack-5: 340 25% 58%;
|
||||
--chart-stack-6: 0 28% 69%;
|
||||
--chart-stack-7: 26 37% 70%;
|
||||
--chart-stack-8: 27 38% 83%;
|
||||
--chart-stack-9: 30 45% 91%;
|
||||
--chart-stack-10: 0 0% 50%;
|
||||
--chart-stack-11: 0 0% 60%;
|
||||
--chart-stack-12: 0 0% 71%;
|
||||
--chart-stack-13: 0 0% 82%;
|
||||
--chart-stack-14: 0 0% 91%;
|
||||
|
||||
--chart-lg: var(--chart-1);
|
||||
--chart-samsung: 218 48% 58%;
|
||||
--chart-cbrand: var(--chart-2);
|
||||
--chart-etc: 0 0% 74%;
|
||||
|
||||
--chart-border: hsl(0 0% 95%);
|
||||
|
||||
@@ -319,6 +308,8 @@
|
||||
.bg-gray-400 { background-color: hsl(var(--lg-gray-400)) !important; }
|
||||
.bg-gray-300 { background-color: hsl(var(--lg-gray-300)) !important; }
|
||||
.bg-gray-200 { background-color: hsl(var(--lg-gray-200)) !important; }
|
||||
.bg-gray-100 { background-color: hsl(var(--lg-gray-100)) !important; }
|
||||
.bg-gray-50 { background-color: hsl(var(--lg-gray-50)) !important; }
|
||||
|
||||
.border-gray-900 { border-color: hsl(var(--lg-gray-900)) !important; }
|
||||
.border-gray-800 { border-color: hsl(var(--lg-gray-800)) !important; }
|
||||
@@ -328,6 +319,8 @@
|
||||
.border-gray-400 { border-color: hsl(var(--lg-gray-400)) !important; }
|
||||
.border-gray-300 { border-color: hsl(var(--lg-gray-300)) !important; }
|
||||
.border-gray-200 { border-color: hsl(var(--lg-gray-200)) !important; }
|
||||
.border-gray-100 { border-color: hsl(var(--lg-gray-100)) !important; }
|
||||
.border-gray-50 { border-color: hsl(var(--lg-gray-50)) !important; }
|
||||
|
||||
/* LG Red/Pink/Purple/Orange scale overrides */
|
||||
.bg-red-600 { background-color: hsl(var(--lg-red-600)) !important; }
|
||||
@@ -470,16 +463,28 @@
|
||||
line-height: 1.15;
|
||||
text-align: center;
|
||||
word-wrap: break-word;
|
||||
word-break: break-all;
|
||||
word-break: auto-phrase;
|
||||
}
|
||||
|
||||
.lg-table th.lg-table__no-border-r,
|
||||
.lg-table td.lg-table__no-border-r {
|
||||
border-right: 0 !important;
|
||||
}
|
||||
|
||||
.lg-table th.lg-table__no-border-l,
|
||||
.lg-table td.lg-table__no-border-l {
|
||||
border-left: 0 !important;
|
||||
}
|
||||
|
||||
.lg-table thead tr.lg-table__group th {
|
||||
background: hsl(var(--lg-gray-400));
|
||||
white-space: pre-wrap;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
.lg-table thead tr.lg-table__subhead th {
|
||||
background: hsl(var(--lg-gray-600));
|
||||
white-space: pre-wrap;
|
||||
color: #fff;
|
||||
font-weight: 700;
|
||||
}
|
||||
@@ -490,7 +495,7 @@
|
||||
color: var(--foreground);
|
||||
background: var(--background);
|
||||
word-wrap: break-word;
|
||||
word-break: break-all;
|
||||
word-break: auto-phrase;
|
||||
}
|
||||
|
||||
.lg-table .lg-table__sep-l { border-left: 3px solid hsl(var(--lg-gray-200)) !important; }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useAtomValue } from "jotai";
|
||||
import { Loader2Icon } from "lucide-react";
|
||||
import { loadingAtom } from "@/store/jotai/loading";
|
||||
|
||||
export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
@@ -9,9 +10,11 @@ export function LoadingOverlay({ force = false }: { force?: boolean }) {
|
||||
if (!force && !isLoading) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[9999] bg-black/70 flex items-center justify-center">
|
||||
{/* 심플 로딩 인디케이터 */}
|
||||
<div className="h-12 w-12 rounded-full border-4 border-gray-400 border-t-white animate-spin" />
|
||||
<div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/65">
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<Loader2Icon className="size-20 animate-spin text-white" style={{ animationDuration: "0.7s" }} />
|
||||
<div className="text-sm font-medium tracking-[0.18em] text-white/90">Loading</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
19
src/components/common/ReactQueryLoadingSync.tsx
Normal file
19
src/components/common/ReactQueryLoadingSync.tsx
Normal 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;
|
||||
@@ -1,13 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import {CategoryTargetData, CategoryTargetType, TotalFilterItem} from "@/config/filter.types";
|
||||
import {categoryTarget, categoryTargetType} from "@/config/filter.data";
|
||||
import {
|
||||
CategoryTargetType,
|
||||
TargetChild,
|
||||
} from "@/types/filter.types";
|
||||
import {categoryTarget, categoryTargetType} from "@/const/filter.const";
|
||||
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.types";
|
||||
import {PRODUCT_KEY_MAP} from "@/const/lg-schema.const";
|
||||
import {YEARS} from "@/const/lg-common.const";
|
||||
|
||||
export type CategoryTypeValue = {
|
||||
label: string;
|
||||
@@ -15,10 +19,10 @@ export type CategoryTypeValue = {
|
||||
};
|
||||
|
||||
export type CategoryFilterValue = {
|
||||
product: string;
|
||||
product: ProductKey;
|
||||
year: string;
|
||||
type: CategoryTypeValue
|
||||
target: CategoryTargetData;
|
||||
target: TargetChild;
|
||||
};
|
||||
|
||||
type CategoryFilterProps = {
|
||||
@@ -28,7 +32,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";
|
||||
@@ -48,8 +52,7 @@ function FilterLine({ title, options, isActive, onSelect }: Omit<RowDef, "id">)
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0 flex-1 overflow-x-auto px-2 py-2">
|
||||
<div className="flex w-max items-center gap-1 whitespace-nowrap">
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2">
|
||||
{options.map((opt) => {
|
||||
const active = isActive(opt.value);
|
||||
return (
|
||||
@@ -66,7 +69,6 @@ function FilterLine({ title, options, isActive, onSelect }: Omit<RowDef, "id">)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -77,27 +79,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]
|
||||
);
|
||||
@@ -108,7 +119,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,
|
||||
@@ -120,11 +131,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 = {
|
||||
@@ -135,10 +146,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),
|
||||
};
|
||||
|
||||
@@ -146,14 +154,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]);
|
||||
|
||||
@@ -2,11 +2,11 @@ import {useAuth} from "@/hooks/useAuth";
|
||||
import {useEffect, useState} from "react";
|
||||
import {LoginUser} from "@/types/auth";
|
||||
import Image from "next/image";
|
||||
import {topMenus} from "@/config/menu.data";
|
||||
import {topMenus} from "@/const/menu.const";
|
||||
import {Button} from "@/components/ui/button";
|
||||
import {LogOut} from "lucide-react";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {SITE_TITLE} from "@/const/lgConst";
|
||||
import {SITE_TITLE} from "@/const/lg-common.const";
|
||||
|
||||
interface HeaderProps {
|
||||
activeTopId: string;
|
||||
|
||||
@@ -1,21 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import {ReactNode, useEffect, useRef, useState} from "react";
|
||||
import {ReactNode, useEffect, useMemo, useRef, useState} from "react";
|
||||
import {usePathname, useRouter} from "next/navigation";
|
||||
import {cn} from "@/lib/utils";
|
||||
import {SelectedMap} from "@/types/common";
|
||||
import {topMenus, totalSubMenus, categorySubMenus} from "@/config/menu.data";
|
||||
import {categoryTarget, totalFilters} from "@/config/filter.data";
|
||||
import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types";
|
||||
import {topMenus, totalSubMenus, categorySubMenus} from "@/const/menu.const";
|
||||
import {categoryTarget, totalFilters} from "@/const/filter.const";
|
||||
import {CategoryTargetData, CategoryTargetType} from "@/types/filter.types";
|
||||
import Header from "./Header";
|
||||
import SubMenu from "./SubMenu";
|
||||
import TotalFilter from "./TotalFilter";
|
||||
import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter";
|
||||
import ExcelDownloadButton from "./ExcelDownloadButton";
|
||||
import {LayoutFilterProvider} from "./LayoutFilterContext";
|
||||
import {LAST_YEAR, PRODUCTS_FILTER_ITEM} from "@/const/lgConst";
|
||||
import {ProductsFilterItem} from "@/types/lg";
|
||||
import {ArrowUp} from "lucide-react";
|
||||
import {LAST_YEAR} from "@/const/lg-common.const";
|
||||
import {PRODUCTS_FILTER_ITEM} from "@/const/lg-product.const";
|
||||
import {ProductsFilterItem} from "@/types/lg.types";
|
||||
import {ArrowUp, Filter} from "lucide-react";
|
||||
import {Button} from "@/components/ui/button";
|
||||
|
||||
type MainLayoutProps = {
|
||||
children: ReactNode;
|
||||
@@ -26,16 +28,18 @@ const buildDefaultTotalValue = (): SelectedMap => {
|
||||
totalFilters.forEach((f) => {
|
||||
// "전체"가 있으면 그 value, 없으면 첫 번째 값
|
||||
const all = f.children.find((c) => c.label === "전체");
|
||||
init[f.variable] = all?.value ?? f.children[0]?.value ?? "";
|
||||
const initValue = all?.value ?? f.children[0]?.value ?? "";
|
||||
|
||||
init[f.variable] = [initValue];
|
||||
});
|
||||
return init;
|
||||
};
|
||||
|
||||
export const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterItem): CategoryFilterValue => {
|
||||
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,
|
||||
@@ -45,6 +49,21 @@ export const buildDefaultCategoryValue = (categoryFilterItems: ProductsFilterIte
|
||||
};
|
||||
};
|
||||
|
||||
const buildTotalPartDescription = (pathname:string) => {
|
||||
switch(pathname) {
|
||||
case "/total/penetration":
|
||||
return "■ 보급률: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>보유하고 있는 비율</strong>";
|
||||
case "/total/lg-penetration":
|
||||
return "■ 보급률: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>보유하고 있는 비율</strong>";
|
||||
case "/total/purchase":
|
||||
return "■ 구매율: 전체 소비자 중, 조사 년도에 해당 제품을 <strong>구매한 비율</strong>";
|
||||
case "/total/lg-purchase":
|
||||
return "■ 구매율: 전체 소비자 중, 조사 년도에 LG 제품을 <strong>구매한 비율</strong>";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
@@ -62,6 +81,7 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
const isFilterOpen = isTotal ? isTotalFilterOpen : isCategoryFilterOpen;
|
||||
|
||||
const categoryFilterItems = PRODUCTS_FILTER_ITEM.find((m) => pathname.match?.(m.path)) ?? PRODUCTS_FILTER_ITEM[0];
|
||||
const totalPartDescription = buildTotalPartDescription(pathname);
|
||||
|
||||
const [totalValue, setTotalValue] = useState<SelectedMap>(() => buildDefaultTotalValue());
|
||||
const [categoryValue, setCategoryValue] = useState<CategoryFilterValue>(() => buildDefaultCategoryValue(categoryFilterItems));
|
||||
@@ -87,6 +107,21 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" });
|
||||
};
|
||||
|
||||
const isDefaultTotalFilter = useMemo(() => {
|
||||
if(!isTotal) return false;
|
||||
|
||||
return Object.values(totalValue).every(value => value.length === 1 && value[0] === "0");
|
||||
},[isTotal, totalValue])
|
||||
|
||||
const setDefaultTotalFilter = () => {
|
||||
if(isTotal && !isDefaultTotalFilter){
|
||||
setTotalValue(prev =>
|
||||
Object.fromEntries(
|
||||
Object.keys(prev).map(key => [key, ["0"]])
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const prevIsTotal = prevIsTotalRef.current;
|
||||
@@ -137,16 +172,25 @@ const MainLayout = ({ children }: MainLayoutProps) => {
|
||||
type="button"
|
||||
onClick={toggleFilter}
|
||||
className={cn(
|
||||
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm",
|
||||
"inline-flex items-center gap-2 font-semibold text-gray-900 content-text-sm cursor-pointer",
|
||||
"select-none"
|
||||
)}
|
||||
>
|
||||
필터 <span className="text-sm leading-none">{isFilterOpen ? "▲" : "▼"}</span>
|
||||
<Filter className="h-4 w-4 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
|
||||
필터 <span className="text-sm leading-none mb-1">{isFilterOpen ? "▲" : "▼"}</span>
|
||||
</button>
|
||||
{isTotal && (
|
||||
<div className={"ml-5 content-text-sm"}>
|
||||
페이지에 대한 설명
|
||||
<>
|
||||
<Button
|
||||
variant={isDefaultTotalFilter ? "secondary" : "default"}
|
||||
onClick={setDefaultTotalFilter}
|
||||
className="h-6 rounded-sm px-3 ml-3 text-sm font-semibold content-text-sm"
|
||||
>
|
||||
초기화
|
||||
</Button>
|
||||
<div className={"ml-5 content-text-sm"} dangerouslySetInnerHTML={{__html: totalPartDescription}}>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<ExcelDownloadButton/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {SubMenuItem} from "@/config/menu.types";
|
||||
import {SubMenuItem} from "@/types/menu.types";
|
||||
import {cn} from "@/lib/utils";
|
||||
|
||||
interface SubMenuProps {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {TotalFilterItem} from "@/config/filter.types";
|
||||
import {TotalFilterItem} from "@/types/filter.types";
|
||||
import {SelectedMap} from "@/types/common";
|
||||
import {useMemo} from "react";
|
||||
import {cn} from "@/lib/utils";
|
||||
@@ -20,9 +20,32 @@ const TotalFilter = ({
|
||||
className
|
||||
}: TotalFilterProps) => {
|
||||
|
||||
const handlePick = (variable: string, v: string) => {
|
||||
if (value[variable] === v) return;
|
||||
onChange({ ...value, [variable]: v });
|
||||
const getSelectableCount = (variable: string) =>
|
||||
filters.find((filter) => filter.variable === variable)?.children
|
||||
.filter((child) => child.value !== "0").length ?? 0;
|
||||
|
||||
const handlePick = (variable: string, selectedValue: string) => {
|
||||
if (selectedValue === "0") {
|
||||
onChange({ ...value, [variable]: ["0"] });
|
||||
return;
|
||||
}
|
||||
|
||||
const currentValues = value[variable] ?? ["0"];
|
||||
const normalizedValues = currentValues.filter((item) => item !== "0");
|
||||
const selectableCount = getSelectableCount(variable);
|
||||
|
||||
const isAlreadySelected = normalizedValues.includes(selectedValue);
|
||||
|
||||
const nextValues = isAlreadySelected
|
||||
? normalizedValues.filter((item) => item !== selectedValue)
|
||||
: [...normalizedValues, selectedValue].sort((a, b) => Number(a) - Number(b));
|
||||
|
||||
if (nextValues.length === 0 || nextValues.length === selectableCount) {
|
||||
onChange({ ...value, [variable]: ["0"] });
|
||||
return;
|
||||
}
|
||||
|
||||
onChange({ ...value, [variable]: nextValues });
|
||||
};
|
||||
|
||||
const arranged = useMemo(() => {
|
||||
@@ -74,7 +97,7 @@ const TotalFilter = ({
|
||||
{/* 우측 옵션 */}
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-1 px-2 py-2">
|
||||
{row.children.map((c) => {
|
||||
const active = current === c.value;
|
||||
const active = current.includes(c.value);
|
||||
|
||||
return (
|
||||
<Button
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import {bannerType} from "@/components/lge-dashboard/types";
|
||||
import {Filter} from "lucide-react";
|
||||
|
||||
type BannerButtonsProps = {
|
||||
banners: bannerType[];
|
||||
@@ -15,7 +16,10 @@ const BannerButtons = ({
|
||||
}: BannerButtonsProps) => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="text-center font-bold p-1">구분 필터</div>
|
||||
<div className="flex items-center justify-center font-bold p-1">
|
||||
<Filter className="h-4 w-4 -ml-2 mr-1 fill-[hsl(var(--lg-gray-500))] stroke-[hsl(var(--lg-gray-500))]" />
|
||||
구분 필터
|
||||
</div>
|
||||
{banners.map((banner) => (
|
||||
<button
|
||||
key={banner.variable}
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import dynamic from "next/dynamic";
|
||||
import { useMemo } from "react";
|
||||
import type { EChartsOption } from "echarts";
|
||||
import { CHART_HEIGHTS } from "@/const/chartConst";
|
||||
import { CHART_HEIGHTS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import {useResizeKey} from "@/hooks/useResize";
|
||||
import { VIEW_DECIMAL_POINT } from "@/const/lg-common.const";
|
||||
import { useMemo } from "react";
|
||||
import {roundNumber} from "@/lib/lg-dashboard";
|
||||
|
||||
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;
|
||||
@@ -18,20 +23,74 @@ type BaseEChartProps = {
|
||||
onEvents?: Record<string, (params: unknown) => void>;
|
||||
};
|
||||
|
||||
const normalizeDataValue = (value: unknown): unknown => {
|
||||
if (typeof value === "number") {
|
||||
return roundNumber(value);
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map(normalizeDataValue);
|
||||
}
|
||||
|
||||
if (value && typeof value === "object" && "value" in value) {
|
||||
const item = value as { value: unknown };
|
||||
return {
|
||||
...(value as Record<string, unknown>),
|
||||
value: normalizeDataValue(item.value),
|
||||
};
|
||||
}
|
||||
|
||||
return value;
|
||||
};
|
||||
|
||||
const normalizeSeries = (series?: EChartsOption["series"]): EChartsOption["series"] => {
|
||||
if (!series) return series;
|
||||
|
||||
const normalizeOne = (s: any) => {
|
||||
if (!s || !("data" in s) || !Array.isArray(s.data)) {
|
||||
return s;
|
||||
}
|
||||
|
||||
return {
|
||||
...s,
|
||||
data: s.data.map(normalizeDataValue),
|
||||
};
|
||||
};
|
||||
|
||||
return Array.isArray(series) ? series.map(normalizeOne) : normalizeOne(series);
|
||||
};
|
||||
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);
|
||||
|
||||
const normalizedOption = useMemo<EChartsOption>(() => {
|
||||
return {
|
||||
...option,
|
||||
series: normalizeSeries(option.series),
|
||||
};
|
||||
}, [option]);
|
||||
|
||||
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={normalizedOption}
|
||||
className={chartClassName}
|
||||
style={{ width: "100%", height: "100%" }}
|
||||
notMerge={notMerge}
|
||||
lazyUpdate={lazyUpdate}
|
||||
onEvents={onEvents}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
8
src/components/lge-dashboard/BottomDescription.tsx
Normal file
8
src/components/lge-dashboard/BottomDescription.tsx
Normal file
@@ -0,0 +1,8 @@
|
||||
const BottomDescription = ({description}:{description:string}) => {
|
||||
return (
|
||||
<div className="content-text-sm mt-2" dangerouslySetInnerHTML={{__html: description}}>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default BottomDescription;
|
||||
@@ -1,6 +1,6 @@
|
||||
const SectionTitle = ({title}:{title:string}) => {
|
||||
return (
|
||||
<div className="mb-2 font-semibold flex items-center gap-2">
|
||||
<div className="font-semibold flex items-center gap-2">
|
||||
<span className="w-3 h-3 bg-primary" />
|
||||
{title}
|
||||
</div>
|
||||
|
||||
@@ -13,13 +13,13 @@ import BaseEChart from "../BaseEChart";
|
||||
import { buildLgPalette } from "../color";
|
||||
import { GroupedOverlayBarData, ShowLabel} from "../types";
|
||||
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
|
||||
import {AXIS_HIDE_STYLE} from "@/const/lgConst";
|
||||
import { CHART_HEIGHTS, LEGEND_ITEM_SIZE } from "@/const/chartConst";
|
||||
import {AXIS_HIDE_STYLE, AXIS_HIDE_Y_STYLE, CHART_HEIGHTS, LEGEND_ITEM_SIZE} from "@/components/lge-dashboard/chart/chart.config";
|
||||
import {makeTotalBasePct} from "@/lib/lg-dashboard";
|
||||
|
||||
type Props = {
|
||||
data: GroupedOverlayBarData;
|
||||
height?: number;
|
||||
|
||||
height?: number | string;
|
||||
questionText: string;
|
||||
tooltip?: TooltipComponentOption;
|
||||
grid?: GridComponentOption;
|
||||
xAxis?: XAXisComponentOption;
|
||||
@@ -35,6 +35,7 @@ type Props = {
|
||||
|
||||
const GroupedOverlayBar = ({
|
||||
data,
|
||||
questionText,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
tooltip,
|
||||
grid,
|
||||
@@ -59,7 +60,7 @@ const GroupedOverlayBar = ({
|
||||
|
||||
const option = useMemo(() => {
|
||||
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 40, bottom: 10, containLabel: true};
|
||||
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
|
||||
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_Y_STYLE };
|
||||
const expandedCategories: string[] = [];
|
||||
data.categories.forEach((cat, catIdx) => {
|
||||
years.forEach(year => {
|
||||
@@ -80,11 +81,11 @@ const GroupedOverlayBar = ({
|
||||
// 연도별 색: 없으면 기본값(전체=회색, LG=빨강 계열)
|
||||
const totalTokens = years.map((y, i) => {
|
||||
const t = yearTotalColor?.[String(y)];
|
||||
return t ?? (["--lg-gray-200", "--lg-gray-300", "--lg-gray-400", "--lg-gray-500"][i] ?? "--lg-gray-300");
|
||||
return t ?? (["--chart-1-t", "--chart-2-t", "--chart-3-t"][i] ?? "--lg-gray-300");
|
||||
});
|
||||
const focusTokens = years.map((y, i) => {
|
||||
const t = yearFocusColor?.[String(y)];
|
||||
return t ?? (["--lg-red-300", "--lg-red-400", "--lg-red-500", "--lg-red-600"][i] ?? "--lg-red-500");
|
||||
return t ?? (["--chart-1", "--chart-2", "--chart-3"][i] ?? "--lg-red-500");
|
||||
});
|
||||
|
||||
const totalColors = buildLgPalette(totalTokens);
|
||||
@@ -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] ?? [];
|
||||
@@ -203,6 +204,7 @@ const GroupedOverlayBar = ({
|
||||
formatter: (params: any) => {
|
||||
const arr = Array.isArray(params) ? params : [params];
|
||||
const header = arr?.[0]?.axisValueLabel ?? "";
|
||||
//header += ` ${questionText}`;
|
||||
|
||||
// bar만
|
||||
const barItems = arr
|
||||
@@ -227,8 +229,11 @@ 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 `${totalName} ${t} 중 ${focusName} ${f}`;
|
||||
return `${questionText} ${totalName} ${t} 중 ${focusName} ${f}`;
|
||||
});
|
||||
|
||||
return [header, ...lines].join("<br/>");
|
||||
|
||||
@@ -13,12 +13,11 @@ import BaseEChart from "../BaseEChart";
|
||||
import { GroupedStackBarData, ShowLabel} from "../types";
|
||||
import { buildLgPalette } from "@/components/lge-dashboard/color";
|
||||
import {getIsShowLabel, roundedRectIcon} from "@/components/lge-dashboard/chart/utill";
|
||||
import {AXIS_HIDE_STYLE} from "@/const/lgConst";
|
||||
import { CHART_HEIGHTS, LEGEND_ITEM_SIZE } from "@/const/chartConst";
|
||||
import {AXIS_HIDE_STYLE, AXIS_HIDE_Y_STYLE, LEGEND_ITEM_SIZE} from "@/components/lge-dashboard/chart/chart.config";
|
||||
|
||||
type Props = {
|
||||
data: GroupedStackBarData;
|
||||
height?: number;
|
||||
height?: number | string;
|
||||
|
||||
tooltip?: TooltipComponentOption;
|
||||
grid?: GridComponentOption;
|
||||
@@ -29,12 +28,12 @@ type Props = {
|
||||
showFocusLabel?: ShowLabel;
|
||||
|
||||
showYearLegend?: boolean;
|
||||
yearBrandPalette?: Record<string, string[]>;
|
||||
yearBrandPalette?: string[];
|
||||
};
|
||||
|
||||
const GroupedStackBar = ({
|
||||
data,
|
||||
height = CHART_HEIGHTS.DEFAULT,
|
||||
height,
|
||||
tooltip,
|
||||
grid,
|
||||
xAxis,
|
||||
@@ -58,13 +57,12 @@ const GroupedStackBar = ({
|
||||
const option = useMemo(() => {
|
||||
const defaultGrid: EChartsOption["grid"] = {left: 10, right: 10, top: 60, bottom: 10, containLabel: true};
|
||||
const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, ...AXIS_HIDE_STYLE };
|
||||
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_STYLE };
|
||||
const defaultYAxis: EChartsOption["yAxis"] = { type: "value", ...AXIS_HIDE_Y_STYLE };
|
||||
|
||||
const latestYear = years.at(-1);
|
||||
const latestPalette = buildLgPalette(yearBrandPalette?.[String(latestYear)]);
|
||||
const latestPalette = buildLgPalette(yearBrandPalette);
|
||||
|
||||
const yearLegendTokens = years.map((y) => {
|
||||
const tokens = yearBrandPalette?.[String(y)];
|
||||
const tokens = yearBrandPalette;
|
||||
const last = tokens?.[tokens.length - 1];
|
||||
return last ?? "--lg-gray-500";
|
||||
});
|
||||
@@ -104,16 +102,19 @@ const GroupedStackBar = ({
|
||||
for (let yi = 0; yi < years.length; yi++) {
|
||||
const year = years[yi];
|
||||
const yearLabel = `${year}년`;
|
||||
const viewYearLabel = `'${Number(year)-2000}`;
|
||||
|
||||
const palette = buildLgPalette(yearBrandPalette?.[String(year)]);
|
||||
const palette = buildLgPalette(yearBrandPalette);
|
||||
|
||||
for (let bi = 0; bi < brands.length; bi++) {
|
||||
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);
|
||||
|
||||
const isFirstBrand = bi === 0;
|
||||
|
||||
realSeries.push({
|
||||
id: `${year}|${brand}`,
|
||||
name: brand,
|
||||
@@ -122,12 +123,20 @@ const GroupedStackBar = ({
|
||||
emphasis: { disabled: true },
|
||||
barMaxWidth: barMaxWidth ?? 42,
|
||||
itemStyle: { color: palette?.[bi] },
|
||||
label: showLabel
|
||||
? ({
|
||||
label: isFirstBrand
|
||||
? {
|
||||
show: true,
|
||||
position: "bottom",
|
||||
formatter: () => viewYearLabel,
|
||||
color: "#666",
|
||||
fontSize: 12,
|
||||
}
|
||||
: showLabel
|
||||
? {
|
||||
show: true,
|
||||
position: "top",
|
||||
formatter: (p: any) => (p?.value ?? "") as any,
|
||||
} as any)
|
||||
}
|
||||
: undefined,
|
||||
data: data.categories.map((_, ci) => (isYearOn ? (row[ci] ?? null) : null)),
|
||||
});
|
||||
@@ -155,7 +164,7 @@ const GroupedStackBar = ({
|
||||
}
|
||||
|
||||
const brandLegendOpt: LegendComponentOption = ({
|
||||
top: 25,
|
||||
top: 0, //25,
|
||||
right: "center",
|
||||
orient: "horizontal",
|
||||
icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS),
|
||||
@@ -166,7 +175,8 @@ const GroupedStackBar = ({
|
||||
data: [...brands].reverse(),
|
||||
} as LegendComponentOption);
|
||||
|
||||
const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt;
|
||||
//const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt;
|
||||
const legends = brandLegendOpt;
|
||||
|
||||
return {
|
||||
tooltip:
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
createCategoryAxis,
|
||||
createValueAxis,
|
||||
} from "@/lib/chart-options";
|
||||
import { BAR_WIDTHS } from "@/const/chartConst";
|
||||
import { BAR_WIDTHS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
|
||||
type Props = {
|
||||
data: ChartData;
|
||||
@@ -28,6 +28,11 @@ type Props = {
|
||||
yAxis?: EChartsOption["yAxis"];
|
||||
barMaxWidth?: number;
|
||||
showFocusLabel?:ShowLabel;
|
||||
labelOptions?: {
|
||||
position?: "right" | "insideRight";
|
||||
color?: string;
|
||||
distance?: number;
|
||||
};
|
||||
};
|
||||
|
||||
const HorizontalBar = ({
|
||||
@@ -43,6 +48,7 @@ const HorizontalBar = ({
|
||||
yAxis,
|
||||
barMaxWidth,
|
||||
showFocusLabel = "all",
|
||||
labelOptions,
|
||||
}: Props) => {
|
||||
const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]);
|
||||
|
||||
@@ -68,14 +74,16 @@ const HorizontalBar = ({
|
||||
label: showLabel
|
||||
? {
|
||||
show: true,
|
||||
position: "right",
|
||||
position: labelOptions?.position ?? "right",
|
||||
color: labelOptions?.color,
|
||||
distance: labelOptions?.distance,
|
||||
formatter: (p: any) => (p?.value ?? "") as any,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel]);
|
||||
}, [data, palette, valueFormatter, tooltip, legend, grid, xAxis, yAxis, barMaxWidth, showFocusLabel, labelOptions]);
|
||||
|
||||
return <BaseEChart option={option} height={height} className={className} />;
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { useMemo } from "react";
|
||||
import type { EChartsOption } from "echarts";
|
||||
import BaseEChart from "../BaseEChart";
|
||||
import type { ChartData, ValueFormatter } from "../types";
|
||||
import { buildLgPalette } from "../color";
|
||||
import {buildLgPalette, buildLgStackPalette} from "../color";
|
||||
import {
|
||||
createDefaultTooltip,
|
||||
createDefaultLegend,
|
||||
@@ -50,15 +50,13 @@ const StackBar = ({
|
||||
isReverse = false,
|
||||
}: Props) => {
|
||||
|
||||
// ✅ 렌더링용 데이터만 뒤집기
|
||||
const renderData = useMemo(
|
||||
() => (isReverse ? reverseSeries(data) : data),
|
||||
[data, isReverse]
|
||||
);
|
||||
|
||||
// ✅ 팔레트도 뒤집어줘야 "시리즈 이름별" 색이 유지됨
|
||||
const palette = useMemo(() => {
|
||||
const temp = buildLgPalette(paletteVarNames);
|
||||
const temp = buildLgStackPalette(paletteVarNames);
|
||||
const n = data.series.length; // 원본 기준
|
||||
const base = temp.slice(0, n);
|
||||
return isReverse ? [...base].reverse() : base;
|
||||
@@ -68,13 +66,26 @@ const StackBar = ({
|
||||
const fmt = valueFormatter ?? ((v: number) => String(v));
|
||||
const isV = orientation === "vertical";
|
||||
|
||||
const seriseSum: number[] = new Array(renderData.categories.length).fill(0);
|
||||
renderData.categories.forEach((c, i) => {
|
||||
renderData.series.forEach((s) => {
|
||||
seriseSum[i] += Number(s.data[i]);
|
||||
})
|
||||
});
|
||||
|
||||
const seriesSumMax = Math.max(...seriseSum);
|
||||
const valueAxis: { min: number; max?: number } = { min: 0 };
|
||||
if (seriesSumMax > 100) {
|
||||
valueAxis.max = Math.ceil(seriesSumMax / 5) * 5;
|
||||
}
|
||||
|
||||
return {
|
||||
color: palette,
|
||||
tooltip: tooltip ?? (isReverse ? createReverseTooltip(data, fmt) : createDefaultTooltip(fmt)),
|
||||
legend: legend ?? (isReverse ? createReverseLegend(data) : createDefaultLegend()),
|
||||
grid: grid ?? createDefaultGrid(),
|
||||
xAxis: xAxis ?? (isV ? createCategoryAxis(renderData.categories) : createValueAxis()),
|
||||
yAxis: yAxis ?? (isV ? createValueAxis() : createCategoryAxis(renderData.categories)),
|
||||
xAxis: xAxis ?? (isV ? createCategoryAxis(renderData.categories) : createValueAxis(false, valueAxis)),
|
||||
yAxis: yAxis ?? (isV ? createValueAxis(false, valueAxis) : createCategoryAxis(renderData.categories)),
|
||||
|
||||
series: renderData.series.map((s) =>
|
||||
createBarSeries(s.name, s.data, {
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
createCategoryAxis,
|
||||
createValueAxis,
|
||||
} from "@/lib/chart-options";
|
||||
import { BAR_WIDTHS } from "@/const/chartConst";
|
||||
import { BAR_WIDTHS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
|
||||
type Props = {
|
||||
data: ChartData;
|
||||
|
||||
86
src/components/lge-dashboard/chart/chart.config.ts
Normal file
86
src/components/lge-dashboard/chart/chart.config.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* 차트 기본 높이 설정
|
||||
*/
|
||||
export const CHART_HEIGHTS = {
|
||||
DEFAULT: "100%",
|
||||
COMPACT: 200,
|
||||
EXPANDED: 320,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Bar 차트의 Bar 너비 설정
|
||||
*/
|
||||
export const BAR_WIDTHS = {
|
||||
DEFAULT: 42,
|
||||
NARROW: 30,
|
||||
WIDE: 60,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 차트 Grid 기본 패딩 설정
|
||||
*/
|
||||
export const CHART_GRID_DEFAULTS = {
|
||||
DEFAULT: {
|
||||
left: 16,
|
||||
right: 16,
|
||||
top: 36,
|
||||
bottom: 12,
|
||||
containLabel: true,
|
||||
},
|
||||
COMPACT: {
|
||||
left: 10,
|
||||
right: 10,
|
||||
top: 20,
|
||||
bottom: 8,
|
||||
containLabel: true,
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Legend 아이템 크기 설정 (GroupedOverlayBar, GroupedStackBar에서 사용)
|
||||
*/
|
||||
export const LEGEND_ITEM_SIZE = {
|
||||
WIDTH: 25,
|
||||
HEIGHT: 14,
|
||||
RADIUS: 4,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 테이블 크기 설정
|
||||
*/
|
||||
export const TABLE_DIMENSIONS = {
|
||||
CELL_HEIGHT: {
|
||||
DEFAULT: 26,
|
||||
COMPACT: 20,
|
||||
EXPANDED: 32,
|
||||
},
|
||||
MIN_WIDTH: {
|
||||
STANDARD: 1600,
|
||||
COMPACT: 1200,
|
||||
WIDE: 2000,
|
||||
},
|
||||
} as const;
|
||||
|
||||
import {YEARS} from "@/const/lg-common.const";
|
||||
|
||||
/** 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 AXIS_HIDE_Y_STYLE = { min:0, max:100, 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>;
|
||||
@@ -1,6 +1,49 @@
|
||||
type Hsl = { h: number; s: number; l: number };
|
||||
const MAX_VAR_DEPTH = 10;
|
||||
|
||||
const getCssVarRaw = (varName: string) =>
|
||||
getComputedStyle(document.documentElement).getPropertyValue(varName).trim();
|
||||
|
||||
/** var(--a) / var(--a, fallback) 를 실제 값으로 재귀 해석 */
|
||||
export const resolveCssVarValue = (varName: string, depth = 0): string | null => {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (depth > MAX_VAR_DEPTH) return null;
|
||||
|
||||
const raw = getCssVarRaw(varName);
|
||||
if (!raw) return null;
|
||||
|
||||
// "var(--x)" 또는 "var(--x, fallback)" 패턴
|
||||
const m = raw.match(/^var\(\s*(--[^,\s)]+)\s*(?:,\s*([^)]+))?\s*\)$/);
|
||||
if (m) {
|
||||
const inner = m[1];
|
||||
const fallback = m[2]?.trim() ?? null;
|
||||
return resolveCssVarValue(inner, depth + 1) ?? fallback;
|
||||
}
|
||||
|
||||
return raw;
|
||||
};
|
||||
|
||||
const parseHue = (token: string): number | null => {
|
||||
const t = token.trim().toLowerCase();
|
||||
const num = parseFloat(t);
|
||||
if (!Number.isFinite(num)) return null;
|
||||
|
||||
if (t.endsWith("turn")) return num * 360;
|
||||
if (t.endsWith("rad")) return (num * 180) / Math.PI;
|
||||
if (t.endsWith("grad")) return num * 0.9;
|
||||
// deg 또는 단위 없음
|
||||
return num;
|
||||
};
|
||||
|
||||
const parsePercent = (token: string): number | null => {
|
||||
const t = token.trim().toLowerCase();
|
||||
const v = parseFloat(t.replace("%", ""));
|
||||
if (!Number.isFinite(v)) return null;
|
||||
|
||||
// 혹시 "0.81" 같은 값이 들어오면(드물지만) 0~1 범위는 %로 보정
|
||||
if (!t.includes("%") && v >= 0 && v <= 1) return v * 100;
|
||||
return v;
|
||||
};
|
||||
|
||||
const parseHslTriplet = (raw: string): Hsl | null => {
|
||||
// 예: "341.1 100% 32.4%" / "0 0% 85%"
|
||||
@@ -13,8 +56,8 @@ const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
|
||||
|
||||
export const resolveHslVar = (varName: string): Hsl | null => {
|
||||
if (typeof window === "undefined") return null;
|
||||
const raw = getComputedStyle(document.documentElement).getPropertyValue(varName);
|
||||
return parseHslTriplet(raw);
|
||||
const raw = resolveCssVarValue(varName);
|
||||
return raw ? parseHslTriplet(raw) : null;
|
||||
};
|
||||
|
||||
export const hslCss = (hsl: Hsl, alpha = 1) =>
|
||||
@@ -26,13 +69,30 @@ export const buildLgPalette = (varNames?: string[]): string[] => {
|
||||
"--chart-1",
|
||||
"--chart-2",
|
||||
"--chart-3",
|
||||
"--chart-4",
|
||||
"--chart-5",
|
||||
"--chart-6",
|
||||
"--chart-7",
|
||||
"--chart-8",
|
||||
"--chart-9",
|
||||
"--chart-10",
|
||||
];
|
||||
|
||||
return defaults.map((v) => {
|
||||
const hsl = resolveHslVar(v);
|
||||
return hsl ? hslCss(hsl, 1) : v;
|
||||
});
|
||||
};
|
||||
|
||||
export const buildLgStackPalette = (varNames?: string[]): string[] => {
|
||||
// globals.css에 정의된 스케일을 직접 참조(중첩 var(--chart-1) 회피)
|
||||
const defaults = varNames ?? [
|
||||
"--chart-stack-1",
|
||||
"--chart-stack-2",
|
||||
"--chart-stack-3",
|
||||
"--chart-stack-4",
|
||||
"--chart-stack-5",
|
||||
"--chart-stack-6",
|
||||
"--chart-stack-7",
|
||||
"--chart-stack-8",
|
||||
"--chart-stack-9",
|
||||
"--chart-stack-10",
|
||||
"--chart-stack-11",
|
||||
"--chart-stack-12",
|
||||
"--chart-stack-13",
|
||||
];
|
||||
|
||||
return defaults.map((v) => {
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
import {ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, SignStyle} from "@/components/lge-dashboard";
|
||||
import {BannerKey, ServerBannerRow} from "@/types/lg";
|
||||
import {formatRowLabel, wrapSampleRow} from "@/lib/lg-dashboard";
|
||||
import {useEffect, useMemo} from "react";
|
||||
import {
|
||||
BANNER_GROUP,
|
||||
BANNER_KEY_MAP,
|
||||
GRID_Y_NOT_PADDING,
|
||||
SAMPLE_SIZE_NOTICE, SITE_TITLE,
|
||||
} from "@/const/lgConst";
|
||||
import {parseNumber} from "@/lib/utils";
|
||||
import {
|
||||
buildHeader_DataColumn,
|
||||
exportDashboardExcel,
|
||||
Section
|
||||
} from "@/lib/lg-export-excel";
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
|
||||
import {CategoryTargetData} from "@/config/filter.types";
|
||||
|
||||
import { ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, MergedTableCell, SignStyle } from "@/components/lge-dashboard";
|
||||
import { BannerKey, BannerRow } from "@/types/lg.types";
|
||||
import { buildBannerGroupColumns, formatRowLabel, isGapRow, wrapSampleRow } from "@/lib/lg-dashboard";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { BANNER_GROUP, flattenBannerGroupKeys } from "@/const/lg-banner.const";
|
||||
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import { SITE_TITLE } from "@/const/lg-common.const";
|
||||
import { GRID_Y_NOT_PADDING } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import { parseNumber } from "@/lib/utils";
|
||||
import { buildHeader_DataColumn, exportDashboardExcel, Section } from "@/lib/lg-export-excel";
|
||||
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
|
||||
import { CategoryFilterValue } from "@/components/layout/CategoryFilter";
|
||||
import { CategoryTargetData } from "@/types/filter.types";
|
||||
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
|
||||
|
||||
type SectionSpec = {
|
||||
title: string;
|
||||
@@ -27,30 +21,39 @@ type SectionSpec = {
|
||||
/** 3개 섹션(테이블)도 여기서만 선언 */
|
||||
const SECTIONS: SectionSpec[] = [
|
||||
{ title: "가구 형태", groupKeys: ["lifeStage", "household", "age"] },
|
||||
{ title: "거주 형태", groupKeys: ["tenure", "housing", "pyeong"] },
|
||||
{ title: "거주 형태", groupKeys: ["occupancy", "housing", "houseSize"] },
|
||||
{ title: "거주 지역 및 소득 수준", groupKeys: ["region", "income"] },
|
||||
];
|
||||
|
||||
const SEP_R = "lg-table__sep-r";
|
||||
|
||||
const getSectionBannerKeys = (spec: SectionSpec): BannerKey[] =>
|
||||
spec.groupKeys.flatMap((gk) => BANNER_GROUP[gk].keys);
|
||||
spec.groupKeys.flatMap((gk) => flattenBannerGroupKeys(BANNER_GROUP[gk].children));
|
||||
|
||||
const buildColumns = (spec: SectionSpec, selectedYear:string): DataColumn<ServerBannerRow>[] => {
|
||||
const columns: DataColumn<ServerBannerRow>[] = [
|
||||
const buildColumns = (spec: SectionSpec, selectedYear: string, isProfileAll:boolean): DataColumn<BannerRow>[] => {
|
||||
const columns: DataColumn<BannerRow>[] = [
|
||||
...(isProfileAll
|
||||
? [
|
||||
{
|
||||
key: "year" as const,
|
||||
header: "",
|
||||
rowHead: true,
|
||||
headerClassName: "lg-table__no-border-r",
|
||||
width: 60,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
key: "rowLabel",
|
||||
header: `20${selectedYear}년`,
|
||||
headRowSpan: 2,
|
||||
header: selectedYear ? `${selectedYear}년` : "",
|
||||
headerClassName: "lg-table__no-border-l",
|
||||
rowHead: true,
|
||||
cellClassName: "lg-table__rowhead",
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
key: "total",
|
||||
header: "전체",
|
||||
numeric: true,
|
||||
headRowSpan: 2,
|
||||
headerClassName: SEP_R,
|
||||
cellClassName: SEP_R,
|
||||
width: 80,
|
||||
@@ -59,33 +62,71 @@ const buildColumns = (spec: SectionSpec, selectedYear:string): DataColumn<Server
|
||||
|
||||
spec.groupKeys.forEach((groupKey) => {
|
||||
const g = BANNER_GROUP[groupKey];
|
||||
g.keys.forEach((k, idx) => {
|
||||
const isLast = idx === g.keys.length - 1;
|
||||
columns.push({
|
||||
key: k as any,
|
||||
header: BANNER_KEY_MAP[k] ?? String(k),
|
||||
group: g.label,
|
||||
id: `banner-group-${groupKey}`,
|
||||
header: g.label,
|
||||
children: buildBannerGroupColumns<BannerRow>(g, BANNER_KEY_MAP, {
|
||||
numeric: true,
|
||||
width: 90,
|
||||
resolveLeafMeta: (_key, idx, total) => {
|
||||
const isLast = idx === total - 1;
|
||||
return {
|
||||
headerClassName: isLast ? SEP_R : undefined,
|
||||
cellClassName: isLast ? SEP_R : undefined,
|
||||
width: 90,
|
||||
});
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
return columns;
|
||||
};
|
||||
|
||||
type BannerSummaryProps = {
|
||||
data: ServerBannerRow[];
|
||||
useChart: boolean;
|
||||
useYear: boolean;
|
||||
const buildYearMergedCells = (rows: BannerRow[]): MergedTableCell<BannerRow>[] => {
|
||||
const mergedCells: MergedTableCell<BannerRow>[] = [];
|
||||
let startRowIndex = 0;
|
||||
|
||||
while (startRowIndex < rows.length) {
|
||||
const year = rows[startRowIndex].year;
|
||||
let endRowIndex = startRowIndex + 1;
|
||||
|
||||
while (endRowIndex < rows.length && rows[endRowIndex].year === year) {
|
||||
endRowIndex += 1;
|
||||
}
|
||||
|
||||
mergedCells.push({
|
||||
key: "year",
|
||||
content: formatRowLabel(year),
|
||||
startRowIndex,
|
||||
rowSpan: endRowIndex - startRowIndex,
|
||||
className: "font-bold text-center",
|
||||
});
|
||||
|
||||
startRowIndex = endRowIndex;
|
||||
}
|
||||
|
||||
return mergedCells;
|
||||
};
|
||||
|
||||
const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
|
||||
const {filterValue, registerExcelExporter } = useLayoutFilter();
|
||||
type BannerSummaryProps = {
|
||||
data: BannerRow[];
|
||||
useChart: boolean;
|
||||
useYear: boolean;
|
||||
isProfileAll?: boolean;
|
||||
getCellClassName?: (row: BannerRow, column: DataColumn<BannerRow>, rowIndex: number) => string | undefined;
|
||||
};
|
||||
|
||||
const buildChartData = (rows: ServerBannerRow[], bannerKeys: BannerKey[]): ChartData => {
|
||||
const BannerSummary = ({
|
||||
data,
|
||||
useChart,
|
||||
useYear,
|
||||
isProfileAll = false,
|
||||
getCellClassName
|
||||
}: BannerSummaryProps) => {
|
||||
const { filterValue, registerExcelExporter } = useLayoutFilter();
|
||||
const debouncedFilterValue = useDebouncedValue<CategoryFilterValue>(filterValue as CategoryFilterValue);
|
||||
|
||||
const buildChartData = (rows: BannerRow[]): ChartData => {
|
||||
const categories = rows
|
||||
.filter((r) => !r.rowLabel.includes("사례수"))
|
||||
.map((r) => formatRowLabel(r.rowLabel))
|
||||
@@ -93,36 +134,38 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
|
||||
|
||||
const series = [
|
||||
{
|
||||
name:"전체",
|
||||
name: "전체",
|
||||
data: rows
|
||||
.filter((r) => !r.rowLabel.includes("사례수"))
|
||||
.map((r) => parseNumber(r.total) ?? null)
|
||||
.reverse(),
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
return { categories, series };
|
||||
};
|
||||
|
||||
const signStyleGap: SignStyle<ServerBannerRow> = {
|
||||
rowSelector: (row) => row.rowLabel === "gap",
|
||||
const signStyleGap: SignStyle<BannerRow> = {
|
||||
rowSelector: (row) => isGapRow(row.rowLabel),
|
||||
display: "arrow",
|
||||
arrowWithNumber: true,
|
||||
paint: "text",
|
||||
zeroText: "-",
|
||||
};
|
||||
|
||||
|
||||
const sectionRows = useMemo(() => {
|
||||
return SECTIONS.map((spec) => {
|
||||
const specTitle = spec.title;
|
||||
|
||||
const bannerKeys = getSectionBannerKeys(spec);
|
||||
const columns = buildColumns(spec, useYear? filterValue.year : "");
|
||||
const columns = buildColumns(spec, useYear ? debouncedFilterValue.year : "", isProfileAll);
|
||||
|
||||
// rows가 spec마다 다르면 여기서 가져오도록 구성
|
||||
const rows = wrapSampleRow(useYear? data.filter((d) => d.year === filterValue.year) : data);
|
||||
const chartData = buildChartData(rows, bannerKeys);
|
||||
const rows = wrapSampleRow(useYear ? data.filter((d) => d.year === debouncedFilterValue.year) : data).map((row) => {
|
||||
row.rowLabel = formatRowLabel(row.rowLabel);
|
||||
return row;
|
||||
});
|
||||
const chartData = buildChartData(rows);
|
||||
const mergedCells = isProfileAll ? buildYearMergedCells(rows) : undefined;
|
||||
|
||||
return {
|
||||
spec,
|
||||
@@ -131,52 +174,66 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
|
||||
columns,
|
||||
rows,
|
||||
chartData,
|
||||
mergedCells,
|
||||
};
|
||||
});
|
||||
}, [data, useYear, filterValue.year]);
|
||||
}, [data, useYear, debouncedFilterValue.year, isProfileAll]);
|
||||
|
||||
const getTargetString = (target: CategoryTargetData): string => {
|
||||
switch (target) {
|
||||
case CategoryTargetData.PROFILE_ALL:
|
||||
return "Profile (전체)";
|
||||
case CategoryTargetData.PROFILE:
|
||||
return "Profile";
|
||||
default:
|
||||
return "보급률 변화"
|
||||
}
|
||||
}
|
||||
|
||||
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 = getTargetString(debouncedFilterValue.target.value);
|
||||
const sheetName = `${product}_${type}_${target}`;
|
||||
|
||||
type AnyRow = Record<string, any>;
|
||||
const sections: Section<AnyRow>[] =
|
||||
sectionRows.map((sectionRow) => ({
|
||||
const sections: Section<AnyRow>[] = sectionRows.map((sectionRow) => ({
|
||||
title: sectionRow.specTitle,
|
||||
header: buildHeader_DataColumn(sectionRow.columns),
|
||||
rows: sectionRow.rows as AnyRow[],
|
||||
rowGap: 1,
|
||||
}))
|
||||
;
|
||||
}));
|
||||
|
||||
await exportDashboardExcel({
|
||||
fileName: `${SITE_TITLE}(${sheetName}).xlsx`,
|
||||
sheetName: sheetName,
|
||||
sections: sections,
|
||||
sheetName,
|
||||
sections,
|
||||
});
|
||||
});
|
||||
return () => registerExcelExporter(null);
|
||||
}, [registerExcelExporter]);
|
||||
}, [registerExcelExporter, debouncedFilterValue, sectionRows]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
{sectionRows.map((sectionRow) => {
|
||||
return (
|
||||
<div key={`div_${sectionRow.specTitle}`}>
|
||||
{
|
||||
useChart ?
|
||||
<LeftChartTable<ServerBannerRow>
|
||||
{useChart ? (
|
||||
<LeftChartTable<BannerRow>
|
||||
key={sectionRow.specTitle}
|
||||
title={sectionRow.specTitle}
|
||||
columns={sectionRow.columns}
|
||||
rows={sectionRow.rows}
|
||||
getCellClassName={getCellClassName}
|
||||
signStyle={signStyleGap}
|
||||
chart={
|
||||
<HorizontalBar
|
||||
data={sectionRow.chartData}
|
||||
height="100%"
|
||||
showFocusLabel="none"
|
||||
showFocusLabel="all"
|
||||
labelOptions={{ position: "insideRight", color: "#fff", distance: 4 }}
|
||||
legend={{ show: false }}
|
||||
grid={GRID_Y_NOT_PADDING}
|
||||
xAxis={{ type: "value", show: false }}
|
||||
@@ -187,22 +244,23 @@ const BannerSummary = ({ data, useChart, useYear }: BannerSummaryProps) => {
|
||||
minWidthPx={1200}
|
||||
starUnder30Sample={true}
|
||||
/>
|
||||
:
|
||||
<DataTable<ServerBannerRow>
|
||||
) : (
|
||||
<DataTable<BannerRow>
|
||||
key={sectionRow.specTitle}
|
||||
title={sectionRow.specTitle}
|
||||
columns={sectionRow.columns}
|
||||
rows={sectionRow.rows}
|
||||
signStyle={signStyleGap}
|
||||
unitText={""}
|
||||
starUnder30Sample={true}
|
||||
mergedCells={sectionRow.mergedCells}
|
||||
/>
|
||||
}
|
||||
<div className="float-right content-text-sm">{SAMPLE_SIZE_NOTICE}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default BannerSummary;
|
||||
@@ -1,39 +1,35 @@
|
||||
import {
|
||||
bannerType,
|
||||
type DataColumn,
|
||||
DataTable,
|
||||
HorizontalBar, SectionTitle, SignStyle,
|
||||
StackBar
|
||||
BottomDescription, type DataColumn, DataTable, HorizontalBar, SectionTitle, SignStyle, StackBar
|
||||
} from "@/components/lge-dashboard";
|
||||
import BannerButtons from "@/components/lge-dashboard/BannerButtons";
|
||||
import {totalFilters} from "@/config/filter.data";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {BannerGroupKey, CategoryChartMode, ServerBannerRow} from "@/types/lg";
|
||||
import {
|
||||
buildRowLabelSeriesChartData,
|
||||
buildYearSeriesChartData,
|
||||
isBannerGroupKey,
|
||||
wrapSampleRow
|
||||
} from "@/lib/lg-dashboard";
|
||||
import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR, SAMPLE_SIZE_NOTICE} from "@/const/lgConst";
|
||||
import {createDefaultGrid, createDefaultLegend, reverseCategories} from "@/lib/chart-options";
|
||||
import { categoryByDataBanner } from "@/const/filter.const";
|
||||
import React, { useMemo, useState } from "react";
|
||||
import { BannerGroupKey, CategoryChartMode, BannerRow, LegendOption } from "@/types/lg.types";
|
||||
import { buildBannerGroupColumns, buildRowLabelSeriesChartData, buildYearSeriesChartData, formatRowLabel, isBannerGroupKey, isGapRow, wrapSampleRow } from "@/lib/lg-dashboard";
|
||||
import { BANNER_GROUP } from "@/const/lg-banner.const";
|
||||
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import { createDefaultGrid, reverseCategories } from "@/lib/chart-options";
|
||||
|
||||
type CategoryByDataProps = {
|
||||
selectedYear: string;
|
||||
title?: string;
|
||||
surveyTitle?: string;
|
||||
chartMode: CategoryChartMode;
|
||||
allTableData: ServerBannerRow[];
|
||||
chartLegend?: LegendOption;
|
||||
chartTopMargin?: number;
|
||||
allTableData: BannerRow[];
|
||||
fillGreaterThan5?: boolean;
|
||||
chartHeight?: number;
|
||||
chartHeight?: number | string;
|
||||
chartWidth?: number;
|
||||
}
|
||||
};
|
||||
|
||||
const banners: bannerType[] = totalFilters.map((filter) => {
|
||||
return {variable: filter.variable, variableName: filter.variableName}
|
||||
})
|
||||
const banners: bannerType[] = categoryByDataBanner.map((filter) => {
|
||||
return { variable: filter.variable, variableName: filter.variableName };
|
||||
});
|
||||
|
||||
const signStyleGap: SignStyle<ServerBannerRow> = {
|
||||
rowSelector: (row) => row.rowLabel === "gap",
|
||||
const signStyleGap: SignStyle<BannerRow> = {
|
||||
rowSelector: (row) => isGapRow(row.rowLabel),
|
||||
display: "arrow",
|
||||
arrowWithNumber: true,
|
||||
paint: "text",
|
||||
@@ -43,49 +39,54 @@ const signStyleGap: SignStyle<ServerBannerRow> = {
|
||||
const CategoryByData = ({
|
||||
selectedYear,
|
||||
title,
|
||||
surveyTitle,
|
||||
chartMode,
|
||||
chartLegend,
|
||||
chartTopMargin,
|
||||
allTableData,
|
||||
fillGreaterThan5,
|
||||
chartHeight,
|
||||
chartWidth,
|
||||
}: CategoryByDataProps) => {
|
||||
}: CategoryByDataProps) => {
|
||||
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
|
||||
|
||||
const buildColumns = (groupKey: BannerGroupKey, selectedYear:string): DataColumn<ServerBannerRow>[] => {
|
||||
const columns: DataColumn<ServerBannerRow>[] = [
|
||||
const buildColumns = (groupKey: BannerGroupKey, year: string): DataColumn<BannerRow>[] => {
|
||||
const g = BANNER_GROUP[groupKey];
|
||||
|
||||
return [
|
||||
{
|
||||
key: "rowLabel",
|
||||
header: `20${selectedYear}년`,
|
||||
headRowSpan: 2,
|
||||
header: `${year}년`,
|
||||
rowHead: true,
|
||||
cellClassName: "lg-table__rowhead",
|
||||
width: 120,
|
||||
},
|
||||
];
|
||||
|
||||
const g = BANNER_GROUP[groupKey];
|
||||
g.keys.forEach((k) => {
|
||||
columns.push({
|
||||
key: k as any,
|
||||
header: BANNER_KEY_MAP[k] ?? String(k),
|
||||
group: g.label,
|
||||
{
|
||||
key: "total",
|
||||
header: "전체",
|
||||
numeric: true,
|
||||
cellClassName: "lg-table__rowhead",
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
id: `category-banner-${groupKey}`,
|
||||
header: g.label,
|
||||
children: buildBannerGroupColumns<BannerRow>(g, BANNER_KEY_MAP, {
|
||||
numeric: true,
|
||||
width: 90,
|
||||
});
|
||||
});
|
||||
|
||||
return columns;
|
||||
}),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const chartData = useMemo(() => {
|
||||
const excludeRowLabels =["사례수", "gap"];
|
||||
const excludeRowLabels = ["사례수", "gap"];
|
||||
const chartTargetData = allTableData.filter((row) => row.year === selectedYear || Number(row.year) === Number(selectedYear) - 1);
|
||||
if(chartMode == "horizontal"){
|
||||
return reverseCategories(buildYearSeriesChartData(chartTargetData, {excludeRowLabels}));
|
||||
if (chartMode === "horizontal") {
|
||||
return reverseCategories(buildYearSeriesChartData(chartTargetData, { excludeRowLabels }));
|
||||
}
|
||||
|
||||
return buildRowLabelSeriesChartData(chartTargetData, {excludeRowLabels});
|
||||
|
||||
return buildRowLabelSeriesChartData(chartTargetData, { excludeRowLabels });
|
||||
}, [allTableData, selectedYear, chartMode]);
|
||||
|
||||
const tableColumns = useMemo(() => {
|
||||
@@ -93,38 +94,56 @@ const CategoryByData = ({
|
||||
return isBannerGroupKey(v) ? buildColumns(v, selectedYear) : [];
|
||||
}, [selectedBanner.variable, selectedYear]);
|
||||
|
||||
const tableData = useMemo(() => wrapSampleRow(allTableData).filter((row) => row.year === selectedYear), [allTableData, selectedYear]);
|
||||
const tableData = useMemo(
|
||||
() =>
|
||||
wrapSampleRow(allTableData)
|
||||
.filter((row) => row.year === selectedYear)
|
||||
.map((row) => {
|
||||
row.rowLabel = formatRowLabel(row.rowLabel);
|
||||
return row;
|
||||
}),
|
||||
[allTableData, selectedYear]
|
||||
);
|
||||
|
||||
return (
|
||||
<div>
|
||||
{title && <SectionTitle title={title} />}
|
||||
<div className="mb-2 flex items-center pr-6">
|
||||
{title ? <SectionTitle title={title} /> : <div />}
|
||||
</div>
|
||||
<div className="flex gap-6 p-3">
|
||||
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px`}}>
|
||||
{
|
||||
chartMode === "stack" || chartMode === "reverseStack" ?
|
||||
<StackBar
|
||||
data={chartData}
|
||||
height={`${chartHeight ?? 340}px`}
|
||||
legend={createDefaultLegend({ top: 0 })}
|
||||
grid={createDefaultGrid("default", { top: 52 })}
|
||||
isReverse={chartMode === "reverseStack"}
|
||||
/>
|
||||
:
|
||||
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px` }}>
|
||||
{(() => {
|
||||
switch (chartMode) {
|
||||
case "horizontal":
|
||||
return (
|
||||
<HorizontalBar
|
||||
data={chartData}
|
||||
height={`${chartHeight ?? 340}px`}
|
||||
legend={chartLegend}
|
||||
grid={chartTopMargin ? createDefaultGrid("default", { top: chartTopMargin }) : undefined}
|
||||
height={chartHeight}
|
||||
showFocusLabel="none"
|
||||
paletteVarNames={chartData.series.length === 1? ["--chart-1"]: ["--chart-2","--chart-1"]}
|
||||
paletteVarNames={chartData.series.length === 1 ? ["--chart-1"] : ["--chart-2", "--chart-1"]}
|
||||
/>
|
||||
);
|
||||
case "stack":
|
||||
case "reverseStack":
|
||||
return (
|
||||
<StackBar
|
||||
data={chartData}
|
||||
legend={chartLegend}
|
||||
height={chartHeight}
|
||||
grid={createDefaultGrid("default", { top: chartTopMargin ? chartTopMargin : 52 })}
|
||||
isReverse={chartMode === "reverseStack"}
|
||||
/>
|
||||
);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center">
|
||||
<BannerButtons
|
||||
banners={banners}
|
||||
selectedBanner={selectedBanner}
|
||||
onSelectBanner={setSelectedBanner}
|
||||
/>
|
||||
<BannerButtons banners={banners} selectedBanner={selectedBanner} onSelectBanner={setSelectedBanner} />
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
@@ -132,13 +151,14 @@ const CategoryByData = ({
|
||||
columns={tableColumns}
|
||||
rows={tableData}
|
||||
signStyle={signStyleGap}
|
||||
wrapperClassName="border rounded-lg"
|
||||
fillGreaterThan5={fillGreaterThan5}
|
||||
fillGapRow={true}
|
||||
starUnder30Sample={true}
|
||||
/>
|
||||
<BottomDescription description={"전체 대비 5%p 이상 품목에 대해 음영 표시"} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="float-right content-text-sm">{SAMPLE_SIZE_NOTICE}</div>
|
||||
<div className="ml-5 mb-5 -mt-3 flex content-text-sm">{surveyTitle}</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo } from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import type React from "react";
|
||||
import { TABLE_DIMENSIONS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import { UNIT_TEXT } from "@/const/lg-common.const";
|
||||
import type { DataColumn, SignStyle } from "../types";
|
||||
import SectionTitle from "../SectionTitle";
|
||||
import { TABLE_DIMENSIONS } from "@/const/chartConst";
|
||||
import {isSampleRow} from "@/lib/lg-dashboard";
|
||||
import BaseDataTable from "../table/BaseDataTable";
|
||||
|
||||
type MergedChartCell<T> = {
|
||||
/** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */
|
||||
key: keyof T;
|
||||
/** rowSpan 시작 row index (기본 0) */
|
||||
startRowIndex?: number;
|
||||
/** rowSpan 수 (기본: rows.length - startRowIndex) */
|
||||
rowSpan?: number;
|
||||
/** chart td 클래스 (예: lg-table__sep-r) */
|
||||
className?: string;
|
||||
};
|
||||
|
||||
@@ -22,41 +17,18 @@ type Props<T extends Record<string, unknown>> = {
|
||||
title?: string;
|
||||
columns: DataColumn<T>[];
|
||||
rows: T[];
|
||||
/** 머지된 셀 안에 렌더할 차트 */
|
||||
chart: React.ReactNode;
|
||||
/** 어떤 컬럼을 머지-차트 셀로 교체할지 */
|
||||
chartCell: MergedChartCell<T>;
|
||||
|
||||
/** +/-/0 표기/색상 옵션(선택) */
|
||||
signStyle?: SignStyle<T>;
|
||||
|
||||
wrapperClassName?: string;
|
||||
tableClassName?: string;
|
||||
minWidthPx?: number;
|
||||
minWidth?: number;
|
||||
starUnder30Sample?: boolean;
|
||||
unitText?: string;
|
||||
getCellClassName?: (row: T, column: DataColumn<T>, rowIndex: number) => string | undefined;
|
||||
};
|
||||
|
||||
// toNumber는 utils.ts의 parseNumber로 통합됨
|
||||
|
||||
function renderSigned(
|
||||
n: number,
|
||||
opts: {
|
||||
display: "number" | "arrow";
|
||||
showPlus: boolean;
|
||||
arrowWithNumber: boolean;
|
||||
zeroText: string;
|
||||
}
|
||||
) {
|
||||
if (n === 0) return opts.zeroText;
|
||||
if (opts.display === "arrow") {
|
||||
const arrow = n > 0 ? "▲" : "▼";
|
||||
const num = Math.abs(n);
|
||||
return opts.arrowWithNumber ? `${arrow} ${num}` : arrow;
|
||||
}
|
||||
if (n > 0) return opts.showPlus ? `+${n}` : `${n}`;
|
||||
return `${n}`;
|
||||
}
|
||||
|
||||
export default function LeftChartTable<T extends Record<string, unknown>>({
|
||||
title,
|
||||
columns,
|
||||
@@ -67,198 +39,38 @@ export default function LeftChartTable<T extends Record<string, unknown>>({
|
||||
wrapperClassName,
|
||||
tableClassName,
|
||||
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT,
|
||||
starUnder30Sample = true
|
||||
}: Props<T>) {
|
||||
const hasGroupHeader = useMemo(
|
||||
() => columns.some((c) => c.group) || columns.some((c) => c.headRowSpan === 2),
|
||||
[columns]
|
||||
);
|
||||
|
||||
const groupCells = useMemo(() => {
|
||||
if (!hasGroupHeader) return [] as Array<
|
||||
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
|
||||
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
|
||||
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string }
|
||||
>;
|
||||
|
||||
type Cell =
|
||||
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
|
||||
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
|
||||
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
|
||||
|
||||
const out: Cell[] = [];
|
||||
let i = 0;
|
||||
while (i < columns.length) {
|
||||
const c = columns[i];
|
||||
if (c.headRowSpan === 2) {
|
||||
out.push({
|
||||
kind: "rowspan",
|
||||
label: c.header,
|
||||
colSpan: 1,
|
||||
rowSpan: 2,
|
||||
className: c.headerClassName,
|
||||
});
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const g = c.group ?? "";
|
||||
if (!g) {
|
||||
out.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let span = 1;
|
||||
while (
|
||||
i + span < columns.length &&
|
||||
(columns[i + span].headRowSpan ?? 1) !== 2 &&
|
||||
(columns[i + span].group ?? "") === g
|
||||
) {
|
||||
span += 1;
|
||||
}
|
||||
|
||||
out.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: columns[i + span -1].headerClassName });
|
||||
i += span;
|
||||
}
|
||||
return out;
|
||||
}, [columns, hasGroupHeader]);
|
||||
|
||||
const display = signStyle?.display ?? "number";
|
||||
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
|
||||
const showPlus = signStyle?.showPlus ?? true;
|
||||
const zeroText = signStyle?.zeroText ?? "-";
|
||||
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
|
||||
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
|
||||
const zeroCls = signStyle?.zeroTextClassName ?? "";
|
||||
|
||||
const start = chartCell.startRowIndex ?? 0;
|
||||
const rowSpan = chartCell.rowSpan ?? Math.max(0, rows.length - start);
|
||||
|
||||
minWidth,
|
||||
starUnder30Sample = true,
|
||||
unitText = UNIT_TEXT,
|
||||
getCellClassName,
|
||||
}: Readonly<Props<T>>) {
|
||||
return (
|
||||
<div className={cn("w-full", wrapperClassName)}>
|
||||
{title && (
|
||||
<SectionTitle title={title} />
|
||||
)}
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table className={cn("lg-table", tableClassName)} style={{ minWidth: `${minWidthPx}px` }}>
|
||||
<thead>
|
||||
{hasGroupHeader ? (
|
||||
<tr className="lg-table__group">
|
||||
{groupCells.map((g, idx) => (
|
||||
<th
|
||||
key={`${g.kind}-${idx}`}
|
||||
className={cn(g.className)}
|
||||
colSpan={g.colSpan}
|
||||
rowSpan={g.rowSpan}
|
||||
>
|
||||
{g.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
) : null}
|
||||
|
||||
<tr className={hasGroupHeader ? "lg-table__subhead" : undefined}>
|
||||
{columns
|
||||
.filter((c) => (c.headRowSpan ?? 1) !== 2)
|
||||
.map((c) => (
|
||||
<th key={String(c.key)} className={cn(c.headerClassName)} style={c.width ? { width: c.width } : undefined}>
|
||||
{c.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row, ri) => {
|
||||
const sampleRow = isSampleRow(row.rowLabel as string ?? "");
|
||||
const isSignRow = signStyle?.rowSelector ? signStyle.rowSelector(row, ri) : false;
|
||||
|
||||
return (
|
||||
<tr key={ri}>
|
||||
{columns.map((c) => {
|
||||
// 머지-차트 셀
|
||||
if (c.key === chartCell.key && ri >= start) {
|
||||
if (ri > start) return null;
|
||||
return (
|
||||
<td
|
||||
key={String(c.key)}
|
||||
rowSpan={rowSpan}
|
||||
className={cn(c.cellClassName, chartCell.className)}
|
||||
style={{ padding: 0, verticalAlign: "middle" }}
|
||||
>
|
||||
{chart}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
// 일반 셀
|
||||
const raw = c.key in row ? row[c.key] : undefined;
|
||||
const content = c.render
|
||||
? c.render(row)
|
||||
: raw === null || raw === undefined
|
||||
? ""
|
||||
: typeof raw === "string" || typeof raw === "number"
|
||||
? raw
|
||||
: String(raw);
|
||||
|
||||
const n = c.numeric ? parseNumber(raw) : null;
|
||||
const shouldSign = isSignRow && (signStyle?.keys ? signStyle.keys.includes(c.key) : !!c.numeric);
|
||||
|
||||
if (c.rowHead) {
|
||||
return (
|
||||
<th
|
||||
key={String(c.key)}
|
||||
scope="row"
|
||||
className={cn("lg-table__rowhead", c.cellClassName)}
|
||||
style={c.width ? { width: c.width } : undefined}
|
||||
>
|
||||
{content}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
if (!shouldSign) {
|
||||
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
|
||||
const isStar = starUnder30Sample && sampleRow && numContent < 30;
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(c.key)}
|
||||
className={cn(c.cellClassName)}
|
||||
style={c.width ? { width: c.width } : undefined}
|
||||
>
|
||||
{isStar?`${content}*`:content}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
// sign row: 값이 없으면 "-" 유지
|
||||
if (n === null) {
|
||||
return (
|
||||
<td key={String(c.key)} className={cn(c.cellClassName)}>
|
||||
-
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
const cls = n > 0 ? posCls : n < 0 ? negCls : zeroCls;
|
||||
const txt = renderSigned(n, { display, showPlus, arrowWithNumber, zeroText });
|
||||
|
||||
return (
|
||||
<td key={String(c.key)} className={cn(c.cellClassName, cls)}>
|
||||
{txt}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<BaseDataTable
|
||||
columns={columns}
|
||||
rows={rows}
|
||||
title={title}
|
||||
wrapperClassName={wrapperClassName}
|
||||
tableClassName={tableClassName}
|
||||
minWidth={minWidth ?? minWidthPx}
|
||||
signStyle={signStyle}
|
||||
signStyleFallback={{
|
||||
positiveTextClassName: "lg-num-pos",
|
||||
negativeTextClassName: "lg-num-neg",
|
||||
zeroTextClassName: "",
|
||||
arrowWithNumber: true,
|
||||
}}
|
||||
starUnder30Sample={starUnder30Sample}
|
||||
unitText={unitText}
|
||||
getCellClassName={getCellClassName}
|
||||
mergedCells={[
|
||||
{
|
||||
key: chartCell.key,
|
||||
content: chart,
|
||||
startRowIndex: chartCell.startRowIndex,
|
||||
rowSpan: chartCell.rowSpan,
|
||||
className: chartCell.className,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import GaugeCardTable from "./GaugeCardTable";
|
||||
import {LIFE_STAGE_COLUMNS} from "@/const/lgConst";
|
||||
import {LifeStageGroup} from "@/types/lg";
|
||||
import {LIFE_STAGE_COLUMNS} from "@/const/lg-product.const";
|
||||
import {UNIT_TEXT} from "@/const/lg-common.const";
|
||||
import {LifeStageGroup} from "@/types/lg.types";
|
||||
import SectionTitle from "../SectionTitle";
|
||||
import React from "react";
|
||||
|
||||
type lifeStageDivProps = {
|
||||
lifeStageRowsByGroup:LifeStageGroup[];
|
||||
@@ -10,7 +13,10 @@ type lifeStageDivProps = {
|
||||
const LifeStageDiv = ({lifeStageRowsByGroup}:lifeStageDivProps) => {
|
||||
return (
|
||||
<div className="mt-6">
|
||||
<div className="flex justify-end gap-6 text-xs text-muted-foreground mb-2">
|
||||
<SectionTitle title={"LG 가전 보급률 기준 라이프스테이지별 기회 영역"} />
|
||||
|
||||
<div className="flex justify-end text-muted-foreground mb-5">
|
||||
<div className="flex justify-end gap-4 content-text-xs">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="inline-block h-4 w-8 border bg-gray-200 border-gray-300"/>
|
||||
<span>제품 보유율</span>
|
||||
@@ -23,6 +29,10 @@ const LifeStageDiv = ({lifeStageRowsByGroup}:lifeStageDivProps) => {
|
||||
/>
|
||||
<span>시장 기회공간</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{UNIT_TEXT}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
|
||||
@@ -3,197 +3,136 @@
|
||||
import React, { useMemo } from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import type { ChartData, SignStyle, TopChartTableRow } from "../types";
|
||||
import SectionTitle from "../SectionTitle";
|
||||
import { CHART_HEIGHTS, TABLE_DIMENSIONS } from "@/const/chartConst";
|
||||
import { CHART_HEIGHTS, TABLE_DIMENSIONS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import { UNIT_TEXT } from "@/const/lg-common.const";
|
||||
import {isCagrRow, isSampleRow} from "@/lib/lg-dashboard";
|
||||
import BaseTableHeader from "../table/core/BaseTableHeader";
|
||||
import { formatSignedValue, getSignTextClass, resolveSignStyle, toRoundedNumber } from "../table/core/table-core.helpers";
|
||||
|
||||
type BaseProps = {
|
||||
export type TopChartTableProps = {
|
||||
title?: string;
|
||||
/** 테이블 상단(헤더 1행) 콜스팬 셀 내부에 렌더될 차트 */
|
||||
categories: string[];
|
||||
rows: TopChartTableRow[];
|
||||
chart?:
|
||||
| React.ReactNode
|
||||
| ((ctx: {
|
||||
/** 테이블 컬럼(=x축) 기준으로 구성된 ChartData */
|
||||
chartData: ChartData;
|
||||
tableCategories: string[];
|
||||
tableRows: TopChartTableRow[];
|
||||
}) => React.ReactNode);
|
||||
/** chart 셀 높이(px) */
|
||||
chartHeight?: number;
|
||||
/** 가로 스크롤 min-width */
|
||||
chartHeight?: number | string;
|
||||
minWidthPx?: number;
|
||||
minWidth?: number;
|
||||
tableClassName?: string;
|
||||
wrapperClassName?: string;
|
||||
/** +/-/0 색상/표기 옵션(선택) */
|
||||
signStyle?: SignStyle<TopChartTableRow>;
|
||||
fillCAGR?: boolean;
|
||||
unitText?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* 1) (신규) HTML 형태: columns=categories, rows=TopChartTableRow
|
||||
*/
|
||||
type HtmlModeProps = BaseProps & {
|
||||
categories: string[];
|
||||
rows: TopChartTableRow[];
|
||||
};
|
||||
|
||||
/**
|
||||
* 2) (호환) 기존 형태: ChartData 기반으로 rows/columns 자동 생성
|
||||
* - rows = data.categories
|
||||
* - cols = data.series.name
|
||||
*/
|
||||
type ChartDataModeProps = BaseProps & {
|
||||
data: ChartData;
|
||||
/** 좌측 rowhead 컬럼 헤더 */
|
||||
categoryHeader?: string;
|
||||
/** 값 표기 포맷터 */
|
||||
valueFormatter?: (v: number) => string;
|
||||
};
|
||||
|
||||
export type TopChartTableProps = HtmlModeProps | ChartDataModeProps;
|
||||
|
||||
// toNumber는 utils.ts의 parseNumber로 통합됨
|
||||
|
||||
function formatSignedNumber(n: number, zeroText: string, showPlus: boolean) {
|
||||
if (n === 0) return zeroText;
|
||||
if (n > 0) return showPlus ? `+${n}` : `${n}`;
|
||||
return `${n}`;
|
||||
}
|
||||
|
||||
type CellValue = TopChartTableRow["values"][number];
|
||||
function toCellValue(v: unknown): CellValue {
|
||||
if (v === null || v === undefined) return v;
|
||||
if (typeof v === "number" || typeof v === "string") return v;
|
||||
return String(v);
|
||||
}
|
||||
|
||||
export default function TopChartTable(props: TopChartTableProps) {
|
||||
const {
|
||||
export default function TopChartTable({
|
||||
title,
|
||||
rows,
|
||||
categories,
|
||||
chart,
|
||||
chartHeight = CHART_HEIGHTS.DEFAULT,
|
||||
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD,
|
||||
minWidth,
|
||||
tableClassName,
|
||||
wrapperClassName,
|
||||
signStyle,
|
||||
} = props;
|
||||
fillCAGR = false,
|
||||
unitText = UNIT_TEXT,
|
||||
}: Readonly<TopChartTableProps>) {
|
||||
const resolvedSignStyle = resolveSignStyle(signStyle, {
|
||||
positiveTextClassName: "lg-num-pos",
|
||||
negativeTextClassName: "lg-num-neg",
|
||||
zeroTextClassName: "",
|
||||
arrowWithNumber: true,
|
||||
});
|
||||
|
||||
const display = signStyle?.display ?? "number";
|
||||
const arrowWithNumber = signStyle?.arrowWithNumber ?? true;
|
||||
const showPlus = signStyle?.showPlus ?? true;
|
||||
const posCls = signStyle?.positiveTextClassName ?? "lg-num-pos";
|
||||
const negCls = signStyle?.negativeTextClassName ?? "lg-num-neg";
|
||||
const zeroText = signStyle?.zeroText ?? "-";
|
||||
|
||||
const { categories, rows, rowHeadHeader, valueFormatter } = useMemo(() => {
|
||||
if ("data" in props) {
|
||||
const d = props.data;
|
||||
const tableRows: TopChartTableRow[] = d.categories.map((cat, i) => ({
|
||||
label: String(cat ?? ""),
|
||||
values: d.series.map((s) => toCellValue(s.data[i] ?? null)),
|
||||
}));
|
||||
|
||||
return {
|
||||
categories: d.series.map((s) => s.name),
|
||||
rows: tableRows,
|
||||
rowHeadHeader: props.categoryHeader ?? "",
|
||||
valueFormatter: props.valueFormatter,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
categories: props.categories,
|
||||
rows: props.rows,
|
||||
rowHeadHeader: "",
|
||||
valueFormatter: undefined,
|
||||
};
|
||||
}, [props]);
|
||||
|
||||
// 테이블 컬럼(=categories)을 x축으로 사용하는 chartData를 항상 제공
|
||||
const chartData: ChartData = useMemo(
|
||||
() => ({
|
||||
categories,
|
||||
series: rows.map((r) => ({
|
||||
name: r.label,
|
||||
data: r.values.map((v) => parseNumber(v) ?? null),
|
||||
series: rows.map((row) => ({
|
||||
name: row.label,
|
||||
data: row.values.map((value) => parseNumber(value) ?? null),
|
||||
})),
|
||||
}),
|
||||
[categories, rows]
|
||||
);
|
||||
|
||||
const chartNode = useMemo(() => {
|
||||
if (!chart) return null;
|
||||
return typeof chart === "function" ? chart({ chartData, tableCategories: categories, tableRows: rows }) : chart;
|
||||
}, [chart, chartData, categories, rows]);
|
||||
if (!chart) {
|
||||
return null;
|
||||
}
|
||||
return typeof chart === "function" ? chart({ chartData }) : chart;
|
||||
}, [chart, chartData]);
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", wrapperClassName)}>
|
||||
{title && (
|
||||
<SectionTitle title={title} />
|
||||
)}
|
||||
<BaseTableHeader title={title} unitText={unitText} />
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table
|
||||
className={cn("lg-table", tableClassName)}
|
||||
style={{ minWidth: `${minWidthPx}px` }}
|
||||
>
|
||||
<table className={cn("lg-table", tableClassName)} style={{ minWidth: `${minWidth ?? minWidthPx}px` }}>
|
||||
<thead>
|
||||
<tr>
|
||||
{/* 좌상단: rowhead 헤더(필요 시 표시). HTML과 동일하게 2행 rowspan */}
|
||||
<th rowSpan={2} className="lg-table__sep-r w-15" style={{ whiteSpace: "nowrap" }}>
|
||||
{rowHeadHeader}
|
||||
</th>
|
||||
<th colSpan={2} className="w-44" style={{ whiteSpace: "nowrap" }} />
|
||||
<td colSpan={categories.length} style={{ padding: 0, height: chartNode ? chartHeight : 0 }}>
|
||||
{chartNode ? <div style={{ width: "100%", height: "100%" }}>{chartNode}</div> : null}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr className="lg-table__subhead">
|
||||
{categories.map((c) => (
|
||||
<th key={c} className={"content-text-xs"}>{c}</th>
|
||||
<th className="lg-table__sep-r"></th>
|
||||
<th className="content-text-xs">사례수</th>
|
||||
{categories.map((category) => (
|
||||
<th key={category} className="content-text-xs">
|
||||
{category}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((r, ri) => {
|
||||
const isSignRow = !!(signStyle?.rowSelector && signStyle.rowSelector(r, ri));
|
||||
{rows.map((row, rowIndex) => {
|
||||
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
|
||||
const sampleRow = isSampleRow(row.label ?? "");
|
||||
const cagrRow = isCagrRow(row.label ?? "");
|
||||
const rowTotal = parseNumber(row.total);
|
||||
|
||||
return (
|
||||
<tr key={`${r.label}-${ri}`}>
|
||||
<tr key={`${row.label}-${rowIndex}`}>
|
||||
<th scope="row" className="lg-table__rowhead lg-table__sep-r content-text-sm">
|
||||
{r.label}
|
||||
{row.label}
|
||||
</th>
|
||||
|
||||
{categories.map((_, ci) => {
|
||||
const raw = r.values?.[ci];
|
||||
const n = parseNumber(raw);
|
||||
|
||||
// 일반 행
|
||||
if (!isSignRow) {
|
||||
if (n === null) return <td key={ci}>-</td>;
|
||||
const txt = valueFormatter ? valueFormatter(n) : n.toLocaleString();
|
||||
return <td key={ci}>{txt}</td>;
|
||||
}
|
||||
|
||||
// sign row
|
||||
if (n === null) return <td key={ci}>-</td>;
|
||||
if (n === 0) return <td key={ci}>{zeroText}</td>;
|
||||
|
||||
const cls = n > 0 ? posCls : negCls;
|
||||
|
||||
if (display === "arrow") {
|
||||
const arrow = n > 0 ? "▲" : "▼";
|
||||
const num = Math.abs(n);
|
||||
return (
|
||||
<td key={ci} className={cls}>
|
||||
{arrow}
|
||||
{arrowWithNumber ? ` ${num}` : ""}
|
||||
<td>
|
||||
{row.sample}
|
||||
</td>
|
||||
);
|
||||
|
||||
{categories.map((_, categoryIndex) => {
|
||||
const rawValue = row.values?.[categoryIndex];
|
||||
|
||||
if(sampleRow){
|
||||
return <td key={categoryIndex}>{rawValue}</td>;
|
||||
}
|
||||
|
||||
const roundedValue = toRoundedNumber(rawValue, cagrRow? 1 : 0);
|
||||
|
||||
if (!signRow) {
|
||||
if (roundedValue === null) {
|
||||
return <td key={categoryIndex}>-</td>;
|
||||
}
|
||||
|
||||
const shouldFillCell = fillCAGR && cagrRow && rowTotal !== null && roundedValue >= rowTotal + 5;
|
||||
return <td key={categoryIndex} className={cn(shouldFillCell ? "bg-red-200" : "")}>{roundedValue.toLocaleString()}</td>;
|
||||
}
|
||||
|
||||
if (roundedValue === null) {
|
||||
return <td key={categoryIndex}>-</td>;
|
||||
}
|
||||
|
||||
return (
|
||||
<td key={ci} className={cls}>
|
||||
{formatSignedNumber(n, zeroText, showPlus)}
|
||||
<td key={categoryIndex} className={getSignTextClass(roundedValue, resolvedSignStyle)}>
|
||||
{formatSignedValue(roundedValue, resolvedSignStyle)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -9,6 +9,8 @@ export { default as GroupedStackBar} from "./chart/GroupedStackBar";
|
||||
export { default as GroupedOverlayBar} from "./chart/GroupedOverlayBar";
|
||||
|
||||
export { default as DataTable } from "./table/DataTable";
|
||||
export type { DataTableProps } from "./table/DataTable";
|
||||
export type { MergedTableCell } from "./table/BaseDataTable";
|
||||
export { default as GaugeTable } from "./table/GaugeTable";
|
||||
|
||||
export { default as TopChartTable } from "./combo/TopChartTable";
|
||||
@@ -19,3 +21,4 @@ export { default as CategoryByData } from "./combo/CategoryByData"
|
||||
export { default as CardDefault } from "./card/Card";
|
||||
|
||||
export { default as SectionTitle } from "./SectionTitle";
|
||||
export { default as BottomDescription } from "./BottomDescription";
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
'use client'
|
||||
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import {CategoryTargetData} from "@/config/filter.types";
|
||||
import Profile from "./category-page/Profile";
|
||||
import PenetrationChange from "./category-page/PenetrationChange";
|
||||
import 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";
|
||||
|
||||
|
||||
const CategoryPage = () => {
|
||||
const { isTotal, filterValue } = useLayoutFilter();
|
||||
console.log(filterValue);
|
||||
|
||||
const renderPage = () => {
|
||||
if (isTotal) return null;
|
||||
|
||||
const target = filterValue.target;
|
||||
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
return renderPage();
|
||||
}
|
||||
|
||||
export default CategoryPage;
|
||||
@@ -1,64 +0,0 @@
|
||||
'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 {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
|
||||
import {CategoryTypeValue} from "@/components/layout/CategoryFilter";
|
||||
import {buildHeader_Banner, exportDashboardExcel, Section} from "@/lib/lg-export-excel";
|
||||
|
||||
const Brand = () => {
|
||||
const {filterValue, registerExcelExporter} = useLayoutFilter();
|
||||
|
||||
const tableDataArray = useMemo<PageData<ServerBannerRow>[]>(() => [
|
||||
{title: "브랜드", chartMode:"reverseStack", data: apiBrandShareByYear},
|
||||
], []);
|
||||
|
||||
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 Brand;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -1,20 +0,0 @@
|
||||
'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";
|
||||
|
||||
const PenetrationChange = () => {
|
||||
const { filterValue } = useLayoutFilter();
|
||||
console.log(filterValue);
|
||||
|
||||
const penetrationChangeData = useMemo<ServerBannerRow[]>(() => apiYearIndex, []);
|
||||
|
||||
return(
|
||||
<BannerSummary data={penetrationChangeData} useChart={true} useYear={false} />
|
||||
);
|
||||
}
|
||||
|
||||
export default PenetrationChange
|
||||
@@ -1,34 +0,0 @@
|
||||
'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 {apiOwnershipSummary, apiPurchaseRateKpis} from "@/config/sample.data";
|
||||
|
||||
const Profile = () => {
|
||||
const { isTotal, filterValue } = useLayoutFilter();
|
||||
|
||||
const profileData = useMemo<ServerBannerRow[]>(() => {
|
||||
if (isTotal) return [];
|
||||
|
||||
const typeLabel = filterValue.type.label;
|
||||
|
||||
switch (typeLabel) {
|
||||
case "보유":
|
||||
return apiOwnershipSummary;
|
||||
case "구매":
|
||||
return apiPurchaseRateKpis;
|
||||
case "향후 구매":
|
||||
return apiPurchaseRateKpis;
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}, [isTotal, filterValue]);
|
||||
|
||||
return (
|
||||
<BannerSummary data={profileData} useChart={false} useYear={true} />
|
||||
);
|
||||
}
|
||||
|
||||
export default Profile;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
176
src/components/lge-dashboard/table/BaseDataTable.tsx
Normal file
176
src/components/lge-dashboard/table/BaseDataTable.tsx
Normal file
@@ -0,0 +1,176 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import {isGapRow, isHasCountRow, isSampleRow} from "@/lib/lg-dashboard";
|
||||
import type { DataColumn, SignStyle } from "../types";
|
||||
import BaseTableRenderer from "./core/BaseTableRenderer";
|
||||
import {
|
||||
appendCellMarker,
|
||||
formatSignedValue,
|
||||
getColumnAlign,
|
||||
getLeafColumns,
|
||||
getSignCellBackground,
|
||||
getSignTextClass,
|
||||
resolveSignStyle,
|
||||
shouldApplySignToColumn,
|
||||
toRoundedNumber,
|
||||
toTableCellContent,
|
||||
type ResolvedSignStyle,
|
||||
} from "./core/table-core.helpers";
|
||||
import {VIEW_DECIMAL_POINT} from "@/const/lg-common.const";
|
||||
|
||||
export type MergedTableCell<T> = {
|
||||
key: keyof T;
|
||||
content: React.ReactNode;
|
||||
startRowIndex?: number;
|
||||
rowSpan?: number;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
type Props<T extends Record<string, unknown>> = {
|
||||
columns: DataColumn<T>[];
|
||||
rows: T[];
|
||||
title?: string;
|
||||
wrapperClassName?: string;
|
||||
tableClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
minWidth?: number;
|
||||
signStyle?: SignStyle<T>;
|
||||
signStyleFallback?: Partial<ResolvedSignStyle>;
|
||||
fillGreaterThan5?: boolean;
|
||||
fillGapRow?: boolean;
|
||||
starUnder30Sample?: boolean;
|
||||
unitText?: string;
|
||||
mergedCells?: MergedTableCell<T>[];
|
||||
getCellClassName?: (row: T, column: DataColumn<T>, rowIndex: number) => string | undefined;
|
||||
};
|
||||
|
||||
export default function BaseDataTable<T extends Record<string, unknown>>({
|
||||
columns,
|
||||
rows,
|
||||
title,
|
||||
wrapperClassName,
|
||||
tableClassName,
|
||||
subheadRowClassName,
|
||||
minWidth,
|
||||
signStyle,
|
||||
signStyleFallback,
|
||||
fillGreaterThan5 = false,
|
||||
fillGapRow = false,
|
||||
starUnder30Sample = false,
|
||||
unitText,
|
||||
mergedCells,
|
||||
getCellClassName,
|
||||
}: Readonly<Props<T>>) {
|
||||
const resolvedSignStyle = resolveSignStyle(signStyle, signStyleFallback);
|
||||
const leafColumns = getLeafColumns(columns);
|
||||
|
||||
return (
|
||||
<BaseTableRenderer
|
||||
columns={columns}
|
||||
title={title}
|
||||
unitText={unitText}
|
||||
showSampleNotice={starUnder30Sample}
|
||||
wrapperClassName={wrapperClassName}
|
||||
tableClassName={tableClassName}
|
||||
subheadRowClassName={subheadRowClassName}
|
||||
minWidth={minWidth}
|
||||
>
|
||||
{rows.map((row, rowIndex) => {
|
||||
const rowLabel = (row.rowLabel as string) ?? "";
|
||||
const sampleRow = isSampleRow(rowLabel);
|
||||
const hasCountRow = isHasCountRow(rowLabel);
|
||||
const signRow = !!signStyle?.rowSelector?.(row, rowIndex);
|
||||
const rowTotal = parseNumber(row.total);
|
||||
const isFillGapRow = fillGapRow && isGapRow(rowLabel)
|
||||
const fillGapClass = isFillGapRow ? "bg-gray-100" : "";
|
||||
|
||||
return (
|
||||
<tr key={rowIndex}>
|
||||
{leafColumns.map((column) => {
|
||||
const dynamicCellClassName = getCellClassName?.(row, column, rowIndex);
|
||||
const mergedCell = mergedCells?.find((cell) => {
|
||||
const startRowIndex = cell.startRowIndex ?? 0;
|
||||
const rowSpan = cell.rowSpan ?? Math.max(0, rows.length - startRowIndex);
|
||||
|
||||
return column.key === cell.key && rowIndex >= startRowIndex && rowIndex < startRowIndex + rowSpan;
|
||||
});
|
||||
|
||||
if (mergedCell) {
|
||||
const mergedCellStart = mergedCell.startRowIndex ?? 0;
|
||||
const mergedCellSpan = mergedCell.rowSpan ?? Math.max(0, rows.length - mergedCellStart);
|
||||
|
||||
if (rowIndex > mergedCellStart) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(column.key)}
|
||||
rowSpan={mergedCellSpan}
|
||||
className={cn(column.cellClassName, mergedCell.className)}
|
||||
style={{ padding: 0, verticalAlign: "middle" }}
|
||||
>
|
||||
{mergedCell.content}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
const rawValue = row[column.key];
|
||||
const align = getColumnAlign(column);
|
||||
const viewDecimalPoint = hasCountRow ? 2 : VIEW_DECIMAL_POINT;
|
||||
const defaultContent = column.render ? column.render(row) : toTableCellContent(rawValue, viewDecimalPoint);
|
||||
const numericValue = "numeric" in column && column.numeric ? parseNumber(rawValue ?? defaultContent) ?? 0 : 0;
|
||||
const applySign = signRow && shouldApplySignToColumn(column, signStyle);
|
||||
|
||||
if (column.rowHead) {
|
||||
return (
|
||||
<th
|
||||
key={String(column.key)}
|
||||
scope="row"
|
||||
className={cn("lg-table__rowhead", column.cellClassName, dynamicCellClassName, fillGapClass)}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{defaultContent}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
if (applySign) {
|
||||
const roundedValue = toRoundedNumber(rawValue);
|
||||
const displayText = roundedValue === null ? "-" : formatSignedValue(roundedValue, resolvedSignStyle);
|
||||
const cellStyle: React.CSSProperties =
|
||||
resolvedSignStyle.paint === "cell"
|
||||
? { textAlign: align, background: getSignCellBackground(roundedValue ?? 0, resolvedSignStyle) }
|
||||
: { textAlign: align };
|
||||
|
||||
return (
|
||||
<td key={String(column.key)} className={cn(column.cellClassName, dynamicCellClassName, fillGapClass)} style={cellStyle}>
|
||||
<span className={cn(roundedValue === null ? "text-gray-500" : getSignTextClass(roundedValue, resolvedSignStyle))}>
|
||||
{displayText}
|
||||
</span>
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
const shouldFillCell = fillGreaterThan5 && rowTotal !== null && numericValue >= rowTotal + 5;
|
||||
const shouldMarkSample = starUnder30Sample && sampleRow && numericValue < 30;
|
||||
const displayContent = shouldMarkSample ? appendCellMarker(defaultContent, "*") : defaultContent;
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(column.key)}
|
||||
className={cn(column.cellClassName, dynamicCellClassName, fillGapClass, shouldFillCell ? "bg-red-200" : "")}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{displayContent}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</BaseTableRenderer>
|
||||
);
|
||||
}
|
||||
@@ -1,52 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import type React from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import type { DataColumn, SignDisplayMode, SignStyle } from "../types";
|
||||
import SectionTitle from "../SectionTitle";
|
||||
import {isSampleRow} from "@/lib/lg-dashboard";
|
||||
import type { DataColumn, SignStyle } from "../types";
|
||||
import { UNIT_TEXT } from "@/const/lg-common.const";
|
||||
import BaseDataTable, { type MergedTableCell } from "./BaseDataTable";
|
||||
|
||||
type Props<T extends Record<string, unknown>> = {
|
||||
export type DataTableProps<T extends Record<string, unknown>> = {
|
||||
columns: DataColumn<T>[];
|
||||
rows: T[];
|
||||
title?: string;
|
||||
className?: string;
|
||||
tableClassName?: string;
|
||||
wrapperClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
signStyle?: SignStyle<T>;
|
||||
fillGreaterThan5?: boolean;
|
||||
fillGapRow?: boolean;
|
||||
starUnder30Sample?: boolean;
|
||||
};
|
||||
|
||||
// parseSignedNumber는 utils.ts의 parseNumber로 통합됨
|
||||
|
||||
const defaultFmt = (v: number) =>
|
||||
Number.isInteger(v) ? String(v) : v.toLocaleString();
|
||||
|
||||
const signText = (
|
||||
v: number,
|
||||
display: SignDisplayMode,
|
||||
showPlus: boolean,
|
||||
arrowWithNumber: boolean,
|
||||
fmt: (n: number) => string,
|
||||
zeroText: string
|
||||
) => {
|
||||
if (display === "arrow") {
|
||||
if (v > 0) return arrowWithNumber ? `▲ ${fmt(Math.abs(v))}` : "▲";
|
||||
if (v < 0) return arrowWithNumber ? `▼ ${fmt(Math.abs(v))}` : "▼";
|
||||
return zeroText;
|
||||
}
|
||||
|
||||
// number
|
||||
if (v > 0) return showPlus ? `+${fmt(v)}` : fmt(v);
|
||||
if (v < 0) return fmt(v); // 음수는 기본적으로 - 포함
|
||||
return zeroText;
|
||||
};
|
||||
|
||||
const toCellContent = (raw: unknown): React.ReactNode => {
|
||||
if (raw == null) return "";
|
||||
if (typeof raw === "string" || typeof raw === "number") return raw;
|
||||
return String(raw);
|
||||
unitText?: string;
|
||||
mergedCells?: MergedTableCell<T>[];
|
||||
};
|
||||
|
||||
const DataTable = <T extends Record<string, unknown>>({
|
||||
@@ -54,202 +25,32 @@ const DataTable = <T extends Record<string, unknown>>({
|
||||
rows,
|
||||
title,
|
||||
className,
|
||||
tableClassName,
|
||||
wrapperClassName,
|
||||
subheadRowClassName,
|
||||
signStyle,
|
||||
fillGreaterThan5 = false,
|
||||
fillGapRow = false,
|
||||
starUnder30Sample = false,
|
||||
}: Props<T>) => {
|
||||
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
|
||||
|
||||
// group header(1행): rowspan=2 컬럼(th) + group label(colspan)
|
||||
const groupCells = useMemo(() => {
|
||||
type GroupCell =
|
||||
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
|
||||
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
|
||||
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
|
||||
|
||||
if (!hasGroup) return [] as GroupCell[];
|
||||
|
||||
const res: GroupCell[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < columns.length) {
|
||||
const c = columns[i];
|
||||
|
||||
if (c.headRowSpan === 2) {
|
||||
res.push({ kind: "rowspan", label: c.header, colSpan: 1, rowSpan: 2, className: c.headerClassName });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const g = c.group;
|
||||
if (!g) {
|
||||
// group 미지정: 1칸짜리 blank group 셀
|
||||
res.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1, className: c.headerClassName });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 같은 group 연속 구간 colSpan
|
||||
let span = 1;
|
||||
let j = i + 1;
|
||||
while (j < columns.length && columns[j].headRowSpan !== 2 && columns[j].group === g) {
|
||||
span++;
|
||||
j++;
|
||||
}
|
||||
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1, className: c.headerClassName });
|
||||
i = j;
|
||||
}
|
||||
|
||||
return res;
|
||||
}, [columns, hasGroup]);
|
||||
|
||||
const {
|
||||
rowSelector,
|
||||
keys,
|
||||
paint = "text",
|
||||
display = "number",
|
||||
showPlus = true,
|
||||
arrowWithNumber = false,
|
||||
zeroText = "-",
|
||||
valueFormatter,
|
||||
positiveTextClassName = "text-primary font-semibold",
|
||||
negativeTextClassName = "text-info font-semibold",
|
||||
zeroTextClassName = "text-gray-600",
|
||||
positiveCellBg = "hsl(var(--primary) / 0.08)",
|
||||
negativeCellBg = "hsl(var(--info) / 0.08)",
|
||||
zeroCellBg = "hsl(var(--lg-gray-200) / 0.6)",
|
||||
} = signStyle ?? ({} as SignStyle<T>);
|
||||
|
||||
const fmt = valueFormatter ?? defaultFmt;
|
||||
|
||||
const isSignRow = (row: T, rowIndex: number) =>
|
||||
!!signStyle && !!rowSelector?.(row, rowIndex);
|
||||
|
||||
const isTargetKey = (k: keyof T) => {
|
||||
if (!signStyle) return false;
|
||||
if (keys && keys.length) return keys.includes(k);
|
||||
// keys 미지정이면 numeric 컬럼 전체
|
||||
const col = columns.find((c) => c.key === k);
|
||||
return !!col?.numeric;
|
||||
};
|
||||
|
||||
const signClass = (v: number) => {
|
||||
if (v > 0) return positiveTextClassName;
|
||||
if (v < 0) return negativeTextClassName;
|
||||
return zeroTextClassName;
|
||||
};
|
||||
|
||||
const signBg = (v: number) => {
|
||||
if (v > 0) return positiveCellBg;
|
||||
if (v < 0) return negativeCellBg;
|
||||
return zeroCellBg;
|
||||
};
|
||||
|
||||
unitText = UNIT_TEXT,
|
||||
mergedCells,
|
||||
}: DataTableProps<T>) => {
|
||||
return (
|
||||
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
|
||||
{title && (
|
||||
<SectionTitle title={title} />
|
||||
)}
|
||||
<table className={cn("lg-table", className)}>
|
||||
<thead>
|
||||
{hasGroup && (
|
||||
<tr className="lg-table__group">
|
||||
{groupCells.map((g, idx) => (
|
||||
<th
|
||||
key={`${g.kind}-${g.label}-${idx}`}
|
||||
colSpan={g.colSpan}
|
||||
rowSpan={g.rowSpan}
|
||||
className={g.className}
|
||||
>
|
||||
{g.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
)}
|
||||
<tr className={hasGroup ? "lg-table__subhead" : undefined}>
|
||||
{columns
|
||||
.filter((c) => c.headRowSpan !== 2)
|
||||
.map((c) => (
|
||||
<th key={String(c.key)} style={{ width: c.width }} className={c.headerClassName}>
|
||||
{c.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row, rIdx) => {
|
||||
const sampleRow = isSampleRow(row.rowLabel as string ?? "");
|
||||
const signRow = isSignRow(row, rIdx);
|
||||
const total = parseNumber(row.total);
|
||||
|
||||
return (
|
||||
<tr key={rIdx}>
|
||||
{columns.map((c) => {
|
||||
const raw: unknown = c.key ? (row[c.key] as unknown) : undefined;
|
||||
const align = c.align ?? (c.numeric ? "right" : "center");
|
||||
|
||||
// headRowSpan=2 컬럼은 thead 2행에서 제외되므로, tbody는 항상 렌더
|
||||
|
||||
// sign row + target column이면 색상/표기 적용
|
||||
const applySign = signRow && isTargetKey(c.key) && !c.rowHead;
|
||||
|
||||
if (applySign) {
|
||||
const n = parseNumber(raw);
|
||||
const displayText =
|
||||
n === null ? "-" : signText(n, display, showPlus, arrowWithNumber, fmt, zeroText);
|
||||
|
||||
const style: React.CSSProperties =
|
||||
paint === "cell"
|
||||
? { textAlign: align, background: signBg(n ?? 0) }
|
||||
: { textAlign: align };
|
||||
|
||||
return (
|
||||
<td key={String(c.key)} style={style} className={c.cellClassName}>
|
||||
<span className={cn(n === null ? "text-gray-500" : signClass(n))}>
|
||||
{displayText}
|
||||
</span>
|
||||
</td>
|
||||
<BaseDataTable
|
||||
columns={columns}
|
||||
rows={rows}
|
||||
title={title}
|
||||
tableClassName={tableClassName ?? className}
|
||||
wrapperClassName={wrapperClassName}
|
||||
subheadRowClassName={subheadRowClassName}
|
||||
signStyle={signStyle}
|
||||
fillGreaterThan5={fillGreaterThan5}
|
||||
fillGapRow={fillGapRow}
|
||||
starUnder30Sample={starUnder30Sample}
|
||||
unitText={unitText}
|
||||
mergedCells={mergedCells}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// 일반 셀
|
||||
const content: React.ReactNode = c.render
|
||||
? c.render(row)
|
||||
: toCellContent(raw);
|
||||
|
||||
if (c.rowHead) {
|
||||
return (
|
||||
<th
|
||||
key={String(c.key)}
|
||||
className={cn("lg-table__rowhead", c.cellClassName)}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{content}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
|
||||
const isFill = fillGreaterThan5 && total && numContent > total + 5;
|
||||
const isStar = starUnder30Sample && sampleRow && numContent < 30;
|
||||
|
||||
return (
|
||||
<td key={String(c.key)} style={{ textAlign: align }} className={
|
||||
cn(c.cellClassName, isFill? "bg-red-200" :"")
|
||||
}>
|
||||
{isStar?`${content}*`:content}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default DataTable;
|
||||
@@ -1,204 +1,114 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo } from "react";
|
||||
import { cn, parseNumber } from "@/lib/utils";
|
||||
import {GaugeColumn} from "../types";
|
||||
import { roundNumber } from "@/lib/lg-dashboard";
|
||||
import type { GaugeColumn } from "../types";
|
||||
import BaseTableRenderer from "./core/BaseTableRenderer";
|
||||
import { getColumnAlign, getLeafColumns, toTableCellContent } from "./core/table-core.helpers";
|
||||
|
||||
type Props<T extends Record<string, unknown>> = {
|
||||
columns: GaugeColumn<T>[];
|
||||
rows: T[];
|
||||
className?: string;
|
||||
tableClassName?: string;
|
||||
wrapperClassName?: string;
|
||||
|
||||
/** value가 0~100이 아니라 0~1이면 scale=100 */
|
||||
scale?: number; // 기본 1
|
||||
|
||||
/** 색상(기본: primary 채움 + gray 트랙) */
|
||||
fillColor?: string; // ex) "hsl(var(--primary) / 0.9)"
|
||||
trackColor?: string; // ex) "hsl(var(--lg-gray-200) / 0.9)"
|
||||
|
||||
/** 셀 높이 */
|
||||
cellHeight?: number; // 기본 26
|
||||
|
||||
/** 숫자 표시 여부/포맷 */
|
||||
valueFormatter?: (v: number) => string;
|
||||
scale?: number;
|
||||
fillColor?: string;
|
||||
trackColor?: string;
|
||||
cellHeight?: number;
|
||||
valueFormatter?: (value: number) => string;
|
||||
};
|
||||
|
||||
// num은 utils.ts의 parseNumber로 통합됨
|
||||
|
||||
const GaugeTable = <T extends Record<string, unknown>>({
|
||||
columns,
|
||||
rows,
|
||||
className,
|
||||
tableClassName,
|
||||
wrapperClassName,
|
||||
scale = 1,
|
||||
fillColor = "hsl(var(--lg-gray-200) / 0.85)",
|
||||
trackColor = "hsl(var(--lg-pink-300) / 0.2)",
|
||||
cellHeight = 26,
|
||||
valueFormatter,
|
||||
}: Props<T>) => {
|
||||
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
|
||||
|
||||
const groupCells = useMemo(() => {
|
||||
type GroupCell =
|
||||
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
|
||||
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
|
||||
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
|
||||
|
||||
if (!hasGroup) return [] as GroupCell[];
|
||||
|
||||
const res: GroupCell[] = [];
|
||||
let i = 0;
|
||||
|
||||
while (i < columns.length) {
|
||||
const c = columns[i];
|
||||
|
||||
if (c.headRowSpan === 2) {
|
||||
res.push({ kind: "rowspan", label: c.header, colSpan: 1, rowSpan: 2 });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const g = c.group;
|
||||
if (!g) {
|
||||
// group 미지정: 1칸짜리 blank group 셀
|
||||
res.push({ kind: "blank", label: "", colSpan: 1, rowSpan: 1 });
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
// 같은 group 연속 구간 colSpan
|
||||
let span = 1;
|
||||
let j = i + 1;
|
||||
while (j < columns.length && columns[j].headRowSpan !== 2 && columns[j].group === g) {
|
||||
span++;
|
||||
j++;
|
||||
}
|
||||
res.push({ kind: "group", label: g, colSpan: span, rowSpan: 1 });
|
||||
i = j;
|
||||
}
|
||||
|
||||
return res;
|
||||
}, [columns, hasGroup]);
|
||||
|
||||
const fmt = valueFormatter ?? ((v: number) => String(Math.round(v)));
|
||||
|
||||
const clamp01 = (n: number) => Math.max(0, Math.min(1, n));
|
||||
}: Props<T>) => {
|
||||
const formatValue = valueFormatter ?? ((value: number) => String(roundNumber(value)));
|
||||
const clampRatio = (value: number) => Math.max(0, Math.min(1, value));
|
||||
const leafColumns = getLeafColumns(columns);
|
||||
|
||||
return (
|
||||
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
|
||||
<table className={cn("lg-table", className)} style={{minWidth:"100%"}}>
|
||||
<BaseTableRenderer
|
||||
columns={columns}
|
||||
wrapperClassName={wrapperClassName}
|
||||
tableClassName={tableClassName ?? className}
|
||||
minWidth="100%"
|
||||
colgroup={
|
||||
<colgroup>
|
||||
{columns.map((c, i) => (
|
||||
{leafColumns.map((column, index) => (
|
||||
<col
|
||||
key={`${String(c.key)}-${i}`}
|
||||
key={`${String(column.key)}-${index}`}
|
||||
style={{
|
||||
width:
|
||||
c.width ??
|
||||
(c.rowHead ? 50 : 40), // 기본 폭(필요시 숫자 조절)
|
||||
width: column.width ?? (column.rowHead ? 50 : 40),
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</colgroup>
|
||||
<thead>
|
||||
{hasGroup && (
|
||||
<tr className="lg-table__group">
|
||||
{groupCells.map((g, idx) => (
|
||||
<th
|
||||
key={`${g.kind}-${g.label}-${idx}`}
|
||||
colSpan={g.colSpan}
|
||||
rowSpan={g.rowSpan}
|
||||
className={g.className}
|
||||
}
|
||||
>
|
||||
{g.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
)}
|
||||
<tr className={hasGroup ? "lg-table__subhead" : undefined}>
|
||||
{columns.filter((c) => c.headRowSpan !== 2).map((c) => (
|
||||
<th key={String(c.key)}>
|
||||
{c.header}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
{rows.map((row, rowIndex) => (
|
||||
<tr key={rowIndex}>
|
||||
{leafColumns.map((column) => {
|
||||
const align = getColumnAlign(column);
|
||||
|
||||
<tbody>
|
||||
{rows.map((row, rIdx) => (
|
||||
<tr key={rIdx}>
|
||||
{columns.map((c) => {
|
||||
const align = c.align ?? (c.rowHead ? "left" : "center");
|
||||
const cellType = c.cellType ?? "gauge";
|
||||
|
||||
if (c.rowHead) {
|
||||
const raw = row[c.key];
|
||||
const label = c.render
|
||||
? c.render(row)
|
||||
: raw === null || raw === undefined
|
||||
? ""
|
||||
: typeof raw === "string" || typeof raw === "number"
|
||||
? raw
|
||||
: String(raw);
|
||||
if (column.rowHead) {
|
||||
const content = column.render ? column.render(row) : toTableCellContent(row[column.key]);
|
||||
return (
|
||||
<th
|
||||
key={String(c.key)}
|
||||
className="lg-table__rowhead"
|
||||
key={String(column.key)}
|
||||
scope="row"
|
||||
className={cn("lg-table__rowhead", column.cellClassName)}
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{label}
|
||||
{content}
|
||||
</th>
|
||||
);
|
||||
}
|
||||
|
||||
const raw = row[c.key];
|
||||
const v = parseNumber(raw);
|
||||
const max = c.max ?? 100;
|
||||
const ratio = v === null ? 0 : clamp01((v * scale) / max);
|
||||
const pct = ratio * 100;
|
||||
const rawValue = row[column.key];
|
||||
const numericValue = parseNumber(rawValue);
|
||||
const max = "max" in column ? column.max ?? 100 : 100;
|
||||
const ratio = numericValue === null ? 0 : clampRatio((numericValue * scale) / max);
|
||||
const percentage = ratio * 100;
|
||||
const background =
|
||||
numericValue === null ? undefined : `linear-gradient(to right, ${fillColor} ${percentage}%, ${trackColor} 0%)`;
|
||||
|
||||
const fill = fillColor;
|
||||
const track = trackColor;
|
||||
|
||||
const cellBg =
|
||||
v === null
|
||||
? undefined
|
||||
: `linear-gradient(to right, ${fill} ${pct}%, ${track} 0%)`;
|
||||
|
||||
if (cellType === "number") {
|
||||
if (("cellType" in column ? column.cellType : "gauge") === "number") {
|
||||
return (
|
||||
<td
|
||||
key={String(c.key)}
|
||||
className="px-2 content-text-sm"
|
||||
style={{ textAlign: align }}
|
||||
>
|
||||
{v === null ? "-" : fmt(v)}
|
||||
<td key={String(column.key)} className={cn("px-2 content-text-sm", column.cellClassName)} style={{ textAlign: align }}>
|
||||
{numericValue === null ? "-" : formatValue(numericValue)}
|
||||
</td>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<td
|
||||
key={String(c.key)}
|
||||
className="px-2 content-text-sm"
|
||||
key={String(column.key)}
|
||||
className={cn("px-2 content-text-sm", column.cellClassName)}
|
||||
style={{
|
||||
textAlign: "left",
|
||||
height: cellHeight,
|
||||
whiteSpace: "nowrap",
|
||||
background: cellBg,
|
||||
background,
|
||||
backgroundClip: "padding-box",
|
||||
}}
|
||||
>
|
||||
{v === null ? "-" : fmt(v)}
|
||||
{numericValue === null ? "-" : formatValue(numericValue)}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</BaseTableRenderer>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default GaugeTable;
|
||||
31
src/components/lge-dashboard/table/core/BaseTableHeader.tsx
Normal file
31
src/components/lge-dashboard/table/core/BaseTableHeader.tsx
Normal file
@@ -0,0 +1,31 @@
|
||||
import SectionTitle from "../../SectionTitle";
|
||||
import { SAMPLE_SIZE_NOTICE } from "@/const/lg-common.const";
|
||||
|
||||
type Props = {
|
||||
title?: string;
|
||||
unitText?: string;
|
||||
showSampleNotice?: boolean;
|
||||
};
|
||||
|
||||
export default function BaseTableHeader({ title, unitText, showSampleNotice = false }: Props) {
|
||||
if (!title && !unitText && !showSampleNotice) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
{title ? <SectionTitle title={title} /> : <div />}
|
||||
{unitText || showSampleNotice ? (
|
||||
<div className="ml-auto text-right text-gray-500 content-text-xs font-semibold">
|
||||
{unitText}
|
||||
{showSampleNotice ? (
|
||||
<>
|
||||
<br />
|
||||
{SAMPLE_SIZE_NOTICE}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
"use client";
|
||||
|
||||
import type React from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { DataColumn, GaugeColumn } from "../../types";
|
||||
import BaseTableHeader from "./BaseTableHeader";
|
||||
import { buildHeaderRows } from "./table-core.helpers";
|
||||
|
||||
type BaseColumn<T> = DataColumn<T> | GaugeColumn<T>;
|
||||
|
||||
type Props<T> = {
|
||||
columns: BaseColumn<T>[];
|
||||
title?: string;
|
||||
unitText?: string;
|
||||
showSampleNotice?: boolean;
|
||||
wrapperClassName?: string;
|
||||
tableClassName?: string;
|
||||
subheadRowClassName?: string;
|
||||
minWidth?: number | string;
|
||||
colgroup?: React.ReactNode;
|
||||
renderHeaderPrefix?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
export default function BaseTableRenderer<T>({
|
||||
columns,
|
||||
title,
|
||||
unitText,
|
||||
showSampleNotice = false,
|
||||
wrapperClassName,
|
||||
tableClassName,
|
||||
subheadRowClassName,
|
||||
minWidth,
|
||||
colgroup,
|
||||
renderHeaderPrefix,
|
||||
children,
|
||||
}: Readonly<Props<T>>) {
|
||||
const headerRows = buildHeaderRows(columns);
|
||||
const lastHeaderRowIndex = headerRows.length - 1;
|
||||
|
||||
return (
|
||||
<div className={cn("w-full", wrapperClassName)}>
|
||||
<BaseTableHeader title={title} unitText={unitText} showSampleNotice={showSampleNotice} />
|
||||
|
||||
<div className="overflow-x-auto">
|
||||
<table
|
||||
className={cn("lg-table", tableClassName)}
|
||||
style={minWidth === undefined ? undefined : { minWidth: typeof minWidth === "number" ? `${minWidth}px` : minWidth }}
|
||||
>
|
||||
{colgroup}
|
||||
<thead>
|
||||
{renderHeaderPrefix}
|
||||
{headerRows.map((row, rowIndex) => (
|
||||
<tr
|
||||
key={`header-row-${rowIndex}`}
|
||||
className={cn(rowIndex === lastHeaderRowIndex ? "lg-table__subhead" : "lg-table__group", rowIndex === lastHeaderRowIndex ? subheadRowClassName : undefined)}
|
||||
>
|
||||
{row.map((cell) => (
|
||||
<th key={cell.id} colSpan={cell.colSpan} rowSpan={cell.rowSpan} className={cell.className}>
|
||||
{cell.label}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>{children}</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
277
src/components/lge-dashboard/table/core/table-core.helpers.tsx
Normal file
277
src/components/lge-dashboard/table/core/table-core.helpers.tsx
Normal file
@@ -0,0 +1,277 @@
|
||||
import type React from "react";
|
||||
import { parseNumber } from "@/lib/utils";
|
||||
import { roundNumber } from "@/lib/lg-dashboard";
|
||||
import type {
|
||||
DataColumn,
|
||||
DataColumnLeaf,
|
||||
GaugeColumn,
|
||||
GaugeColumnLeaf,
|
||||
SignDisplayMode,
|
||||
SignStyle,
|
||||
ValueFormatter,
|
||||
} from "../../types";
|
||||
|
||||
export type TableColumnNode<T> = DataColumn<T> | GaugeColumn<T>;
|
||||
export type TableColumnLeaf<T> = DataColumnLeaf<T> | GaugeColumnLeaf<T>;
|
||||
|
||||
export type GroupHeaderCell = {
|
||||
id: string;
|
||||
label: string;
|
||||
colSpan: number;
|
||||
rowSpan: number;
|
||||
className?: string;
|
||||
isLeaf: boolean;
|
||||
};
|
||||
|
||||
export type ResolvedSignStyle = {
|
||||
paint: "text" | "cell";
|
||||
display: SignDisplayMode;
|
||||
showPlus: boolean;
|
||||
arrowWithNumber: boolean;
|
||||
zeroText: string;
|
||||
valueFormatter: ValueFormatter;
|
||||
positiveTextClassName: string;
|
||||
negativeTextClassName: string;
|
||||
zeroTextClassName: string;
|
||||
positiveCellBg: string;
|
||||
negativeCellBg: string;
|
||||
zeroCellBg: string;
|
||||
};
|
||||
|
||||
const defaultValueFormatter: ValueFormatter = (value) =>
|
||||
Number.isInteger(value) ? String(roundNumber(value)) : value.toLocaleString();
|
||||
|
||||
const defaultSignStyle: ResolvedSignStyle = {
|
||||
paint: "text",
|
||||
display: "number",
|
||||
showPlus: true,
|
||||
arrowWithNumber: false,
|
||||
zeroText: "-",
|
||||
valueFormatter: defaultValueFormatter,
|
||||
positiveTextClassName: "text-primary font-semibold",
|
||||
negativeTextClassName: "text-info font-semibold",
|
||||
zeroTextClassName: "text-gray-600",
|
||||
positiveCellBg: "hsl(var(--primary) / 0.08)",
|
||||
negativeCellBg: "hsl(var(--info) / 0.08)",
|
||||
zeroCellBg: "hsl(var(--lg-gray-200) / 0.6)",
|
||||
};
|
||||
|
||||
function isColumnLeaf<T>(column: TableColumnNode<T>): column is TableColumnLeaf<T> {
|
||||
return !("children" in column) || !column.children?.length;
|
||||
}
|
||||
|
||||
export function getLeafColumns<T>(columns: TableColumnNode<T>[]) {
|
||||
const leaves: TableColumnLeaf<T>[] = [];
|
||||
|
||||
const visit = (nodes: TableColumnNode<T>[]) => {
|
||||
nodes.forEach((node) => {
|
||||
if (isColumnLeaf(node)) {
|
||||
leaves.push(node);
|
||||
return;
|
||||
}
|
||||
|
||||
visit(node.children);
|
||||
});
|
||||
};
|
||||
|
||||
visit(columns);
|
||||
return leaves;
|
||||
}
|
||||
|
||||
function getHeaderDepth<T>(columns: TableColumnNode<T>[]) {
|
||||
const visit = (nodes: TableColumnNode<T>[], depth: number): number =>
|
||||
nodes.reduce((maxDepth, node) => {
|
||||
if (isColumnLeaf(node)) {
|
||||
return Math.max(maxDepth, depth);
|
||||
}
|
||||
|
||||
return Math.max(maxDepth, visit(node.children, depth + 1));
|
||||
}, depth);
|
||||
|
||||
return columns.length ? visit(columns, 1) : 0;
|
||||
}
|
||||
|
||||
function getLeafCount<T>(column: TableColumnNode<T>): number {
|
||||
if (isColumnLeaf(column)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
return column.children.reduce((sum, child) => sum + getLeafCount(child), 0);
|
||||
}
|
||||
|
||||
function getColSpan<T>(isLeaf: boolean, node: TableColumnNode<T>) {
|
||||
if(node.colSpan){
|
||||
return node.colSpan;
|
||||
}
|
||||
|
||||
return isLeaf ? 1 : getLeafCount(node);
|
||||
}
|
||||
|
||||
export function buildHeaderRows<T>(columns: TableColumnNode<T>[]) {
|
||||
const depth = getHeaderDepth(columns);
|
||||
|
||||
if (!depth) {
|
||||
return [] as GroupHeaderCell[][];
|
||||
}
|
||||
|
||||
const rows = Array.from({ length: depth }, () => [] as GroupHeaderCell[]);
|
||||
|
||||
const visit = (nodes: TableColumnNode<T>[], level: number, path: string[]) => {
|
||||
nodes.forEach((node, index) => {
|
||||
const nodeId = node.id ?? (isColumnLeaf(node) ? String(node.key) : `${path.join(".") || "root"}:${index}:${node.header}`);
|
||||
const nextPath = [...path, nodeId];
|
||||
const isLeaf = isColumnLeaf(node);
|
||||
const colSpan = getColSpan(isLeaf, node);
|
||||
|
||||
rows[level].push({
|
||||
id: nextPath.join("/"),
|
||||
label: node.header,
|
||||
colSpan,
|
||||
rowSpan: isLeaf ? depth - level : 1,
|
||||
className: node.headerClassName,
|
||||
isLeaf,
|
||||
});
|
||||
|
||||
if (!isLeaf) {
|
||||
visit(node.children, level + 1, nextPath);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
visit(columns, 0, []);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function hasGroupedHeader<T>(columns: TableColumnNode<T>[]) {
|
||||
return getHeaderDepth(columns) > 1;
|
||||
}
|
||||
|
||||
export function getColumnAlign<T>(column: TableColumnLeaf<T>, fallback: "left" | "center" | "right" = "center") {
|
||||
if (column.align) {
|
||||
return column.align;
|
||||
}
|
||||
|
||||
if ("numeric" in column && column.numeric) {
|
||||
return "right";
|
||||
}
|
||||
|
||||
if (column.rowHead) {
|
||||
return "left";
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
export function toTableCellContent(raw: unknown, decimalPoint?: number): React.ReactNode {
|
||||
if (raw == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (typeof raw === "string") {
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) {
|
||||
return raw;
|
||||
}
|
||||
|
||||
const parsed = Number(trimmed);
|
||||
return Number.isNaN(parsed) ? raw : roundNumber(parsed, decimalPoint);
|
||||
}
|
||||
|
||||
if (typeof raw === "number") {
|
||||
return String(roundNumber(raw));
|
||||
}
|
||||
|
||||
return String(raw);
|
||||
}
|
||||
|
||||
export function toRoundedNumber(raw: unknown, decimalPoint?: number) {
|
||||
const parsed = parseNumber(raw);
|
||||
return parsed === null ? null : roundNumber(parsed, decimalPoint);
|
||||
}
|
||||
|
||||
export function appendCellMarker(content: React.ReactNode, marker: string) {
|
||||
if (!marker) {
|
||||
return content;
|
||||
}
|
||||
|
||||
if (typeof content === "string" || typeof content === "number") {
|
||||
return `${content}${marker}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{content}
|
||||
{marker}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveSignStyle<T>(signStyle?: SignStyle<T>, fallback?: Partial<ResolvedSignStyle>) {
|
||||
return {
|
||||
...defaultSignStyle,
|
||||
...fallback,
|
||||
...signStyle,
|
||||
valueFormatter: signStyle?.valueFormatter ?? fallback?.valueFormatter ?? defaultSignStyle.valueFormatter,
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldApplySignToColumn<T>(column: TableColumnLeaf<T>, signStyle?: SignStyle<T>) {
|
||||
if (!signStyle || column.rowHead) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (signStyle.keys?.length) {
|
||||
return signStyle.keys.includes(column.key);
|
||||
}
|
||||
|
||||
return "numeric" in column ? !!column.numeric : false;
|
||||
}
|
||||
|
||||
export function formatSignedValue(
|
||||
value: number,
|
||||
options: Pick<ResolvedSignStyle, "arrowWithNumber" | "display" | "showPlus" | "valueFormatter" | "zeroText">
|
||||
) {
|
||||
if (options.display === "arrow") {
|
||||
if (value > 0) {
|
||||
return options.arrowWithNumber ? `▲${options.valueFormatter(Math.abs(value))}` : "▲";
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.arrowWithNumber ? `▼${options.valueFormatter(Math.abs(value))}` : "▼";
|
||||
}
|
||||
return options.zeroText;
|
||||
}
|
||||
|
||||
if (value > 0) {
|
||||
return options.showPlus ? `+${options.valueFormatter(value)}` : options.valueFormatter(value);
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.valueFormatter(value);
|
||||
}
|
||||
return options.zeroText;
|
||||
}
|
||||
|
||||
export function getSignTextClass(
|
||||
value: number,
|
||||
options: Pick<ResolvedSignStyle, "negativeTextClassName" | "positiveTextClassName" | "zeroTextClassName">
|
||||
) {
|
||||
if (value > 0) {
|
||||
return options.positiveTextClassName;
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.negativeTextClassName;
|
||||
}
|
||||
return options.zeroTextClassName;
|
||||
}
|
||||
|
||||
export function getSignCellBackground(
|
||||
value: number,
|
||||
options: Pick<ResolvedSignStyle, "negativeCellBg" | "positiveCellBg" | "zeroCellBg">
|
||||
) {
|
||||
if (value > 0) {
|
||||
return options.positiveCellBg;
|
||||
}
|
||||
if (value < 0) {
|
||||
return options.negativeCellBg;
|
||||
}
|
||||
return options.zeroCellBg;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type React from "react";
|
||||
import { GAP_WORDING } from "@/const/lg-common.const";
|
||||
|
||||
export type NewNumber = number | null | undefined;
|
||||
|
||||
@@ -45,47 +46,63 @@ export type GroupedOverlayBarData = {
|
||||
export type TopChartTableRow = {
|
||||
/** 좌측 rowhead 라벨 */
|
||||
label: string;
|
||||
total: number | string | null | undefined;
|
||||
sample: number | string | null | undefined;
|
||||
/** categories 순서대로 값 */
|
||||
values: Array<number | string | null | undefined>;
|
||||
};
|
||||
|
||||
export type ValueFormatter = (v: number) => string;
|
||||
|
||||
export type DataColumn<T> = {
|
||||
key: keyof T;
|
||||
export type TableColumnAlign = "left" | "center" | "right";
|
||||
|
||||
type TableColumnShared<T> = {
|
||||
id?: string;
|
||||
header: string;
|
||||
width?: number | string;
|
||||
align?: "left" | "center" | "right";
|
||||
group?: string; // 2단 헤더 그룹
|
||||
groupKey?:string;// 2단 헤더 그룹
|
||||
|
||||
/** group header에서 해당 컬럼 헤더를 rowspan=2로 올릴 때 사용(HTML 테이블과 동일한 구조 지원) */
|
||||
headRowSpan?: 1 | 2;
|
||||
rowHead?: boolean; // 첫 컬럼 등 row header
|
||||
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
|
||||
/** th 클래스(필요 시 lg-table__sep-r 등 주입) */
|
||||
align?: TableColumnAlign;
|
||||
headerClassName?: string;
|
||||
/** td 클래스(필요 시 lg-table__sep-l, lg-table__sep-r 등 주입) */
|
||||
cellClassName?: string;
|
||||
render?: (row: T) => React.ReactNode;
|
||||
colSpan?: number;
|
||||
};
|
||||
|
||||
export type GaugeColumn<T> = {
|
||||
export type DataColumnLeaf<T> = TableColumnShared<T> & {
|
||||
key: keyof T;
|
||||
header: string;
|
||||
width?: number | string;
|
||||
align?: "left" | "center" | "right";
|
||||
group?: string;
|
||||
groupKey?:string;// 2단 헤더 그룹
|
||||
rowHead?: boolean; // 첫 컬럼 등 row header
|
||||
numeric?: boolean; // 숫자열(정렬 기본값/색상 타겟 기본값에 사용)
|
||||
children?: undefined;
|
||||
};
|
||||
|
||||
headRowSpan?: 1 | 2;
|
||||
export type DataColumnGroup<T> = TableColumnShared<T> & {
|
||||
children: DataColumn<T>[];
|
||||
key?: undefined;
|
||||
rowHead?: undefined;
|
||||
numeric?: undefined;
|
||||
};
|
||||
|
||||
export type DataColumn<T> = DataColumnLeaf<T> | DataColumnGroup<T>;
|
||||
|
||||
export type GaugeColumnLeaf<T> = TableColumnShared<T> & {
|
||||
key: keyof T;
|
||||
rowHead?: boolean;
|
||||
/** 게이지 최대값 기준(기본 100) */
|
||||
max?: number;
|
||||
render?: (row: T) => React.ReactNode; // rowHead에 쓰기 좋음
|
||||
cellType?: "gauge" | "number"; // default: "gauge"
|
||||
children?: undefined;
|
||||
};
|
||||
|
||||
export type GaugeColumnGroup<T> = TableColumnShared<T> & {
|
||||
children: GaugeColumn<T>[];
|
||||
key?: undefined;
|
||||
rowHead?: undefined;
|
||||
max?: undefined;
|
||||
cellType?: undefined;
|
||||
};
|
||||
|
||||
export type GaugeColumn<T> = GaugeColumnLeaf<T> | GaugeColumnGroup<T>;
|
||||
|
||||
export type SignDisplayMode = "number" | "arrow";
|
||||
|
||||
export type SignStyle<T> = {
|
||||
@@ -122,7 +139,7 @@ export type SignStyle<T> = {
|
||||
};
|
||||
|
||||
export const signStyleGapRow: SignStyle<TopChartTableRow> = {
|
||||
rowSelector: (row) => row.label === "전년 대비 GAP(%)",
|
||||
rowSelector: (row) => row.label === GAP_WORDING,
|
||||
display: "arrow",
|
||||
arrowWithNumber: true,
|
||||
paint: "text",
|
||||
@@ -132,6 +149,6 @@ export const signStyleGapRow: SignStyle<TopChartTableRow> = {
|
||||
export type ShowLabel = "none" | "all" | "last" | "first";
|
||||
|
||||
export type bannerType = {
|
||||
variable:string;
|
||||
variableName:string;
|
||||
}
|
||||
variable: string;
|
||||
variableName: string;
|
||||
};
|
||||
|
||||
@@ -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>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ReactQueryLoadingSync />
|
||||
<LoadingOverlay />
|
||||
{children}
|
||||
</QueryClientProvider>
|
||||
</JotaiProvider>
|
||||
);
|
||||
}
|
||||
266
src/config/lg-page.config.ts
Normal file
266
src/config/lg-page.config.ts
Normal file
@@ -0,0 +1,266 @@
|
||||
import {CategoryFieldSpec} from "@/types/lg.types";
|
||||
import {CategoryTargetData, CategoryTargetType} from "@/types/filter.types";
|
||||
|
||||
const profileFieldSpec: CategoryFieldSpec[] = [
|
||||
{
|
||||
title: {
|
||||
[CategoryTargetType.PENETRATION]: "보유율"
|
||||
, [CategoryTargetType.PURCHASE]: "구매율"
|
||||
, [CategoryTargetType.INTENDED]: "향후 구매율"
|
||||
},
|
||||
requestKey: "category_${keyBase}",
|
||||
chartMode:"none",
|
||||
qidByMode: {
|
||||
[CategoryTargetType.PENETRATION]: "KQA1"
|
||||
, [CategoryTargetType.PURCHASE]: "KQB0"
|
||||
, [CategoryTargetType.INTENDED]: "KQC1"
|
||||
},
|
||||
},
|
||||
{
|
||||
title: "보유대수",
|
||||
requestKey: "category_penetration_count",
|
||||
chartMode:"none",
|
||||
qidByMode: {
|
||||
[CategoryTargetType.PENETRATION]: "KQA2"
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const CATEGORY_PAGE_FIELDS: Record<CategoryTargetData, CategoryFieldSpec[]> = {
|
||||
[CategoryTargetData.PROFILE_ALL]: profileFieldSpec,
|
||||
[CategoryTargetData.PROFILE]: profileFieldSpec,
|
||||
|
||||
[CategoryTargetData.PENETRATION_CHANGE]: [
|
||||
{
|
||||
title: "보급률 변화",
|
||||
requestKey: "category_${keyBase}",
|
||||
chartMode:"none",
|
||||
qidByMode: {
|
||||
[CategoryTargetType.PENETRATION]: "KQA1"
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
[CategoryTargetData.BRAND]: [
|
||||
{
|
||||
title: "브랜드",
|
||||
requestKey: "category_${keyBase}_brand",
|
||||
chartMode:"reverseStack",
|
||||
chartTopMargin: 80,
|
||||
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"
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "음식물처리기 구동 방식",
|
||||
requestKey: "category_${keyBase}_driveMethod",
|
||||
chartMode: "horizontal",
|
||||
qidByMode: {
|
||||
[CategoryTargetType.PENETRATION]: "KQA3_13",
|
||||
[CategoryTargetType.PURCHASE]: "KQX3_13"
|
||||
}
|
||||
},
|
||||
{
|
||||
title: "전기레인지 화구 수",
|
||||
requestKey: "category_${keyBase}_burnerCount",
|
||||
chartMode: "horizontal",
|
||||
qidByMode: {
|
||||
[CategoryTargetType.PENETRATION]: "KQA3_14",
|
||||
[CategoryTargetType.PURCHASE]: "KQX3_14"
|
||||
}
|
||||
},
|
||||
],
|
||||
|
||||
[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"
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -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"],
|
||||
tenure: ["ownerOccupied", "jeonse", "depositAndMonthly", "monthlyNoDeposit", "otherTenure"],
|
||||
housing: ["apartment", "house", "officetel", "villa", "studio", "otherHousingType"],
|
||||
pyeong: ["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"),
|
||||
];
|
||||
@@ -1,139 +0,0 @@
|
||||
/**
|
||||
* 차트 관련 상수 정의
|
||||
* - 차트 높이, Bar 너비, Grid 설정 등
|
||||
*/
|
||||
|
||||
/**
|
||||
* 차트 기본 높이 설정
|
||||
*/
|
||||
export const CHART_HEIGHTS = {
|
||||
DEFAULT: 260,
|
||||
COMPACT: 200,
|
||||
EXPANDED: 320,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Bar 차트의 Bar 너비 설정
|
||||
*/
|
||||
export const BAR_WIDTHS = {
|
||||
DEFAULT: 42,
|
||||
NARROW: 30,
|
||||
WIDE: 60,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 차트 Grid 기본 패딩 설정
|
||||
*/
|
||||
export const CHART_GRID_DEFAULTS = {
|
||||
DEFAULT: {
|
||||
left: 16,
|
||||
right: 16,
|
||||
top: 36,
|
||||
bottom: 12,
|
||||
containLabel: true,
|
||||
},
|
||||
COMPACT: {
|
||||
left: 10,
|
||||
right: 10,
|
||||
top: 20,
|
||||
bottom: 8,
|
||||
containLabel: true,
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* Legend 아이템 크기 설정 (GroupedOverlayBar, GroupedStackBar에서 사용)
|
||||
*/
|
||||
export const LEGEND_ITEM_SIZE = {
|
||||
WIDTH: 25,
|
||||
HEIGHT: 14,
|
||||
RADIUS: 4,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 색상 팔레트 설정
|
||||
*/
|
||||
export const CHART_COLOR_PALETTES = {
|
||||
/** 연도별 트렌드 역순 (최신->과거) */
|
||||
YEAR_TREND_REVERSE: ["--chart-3", "--chart-2", "--chart-1"],
|
||||
|
||||
/** LG Red 계열 */
|
||||
LG_RED_SCALE: ["--lg-red-300", "--lg-red-400", "--lg-red-500"],
|
||||
|
||||
/** 연도별 전체 색상 */
|
||||
YEAR_TOTAL: {
|
||||
"24": "--chart-total-1",
|
||||
"25": "--chart-total-2",
|
||||
"26": "--chart-total-3",
|
||||
} as const,
|
||||
|
||||
/** 연도별 LG 색상 */
|
||||
YEAR_LG: {
|
||||
"24": "--chart-lg-1",
|
||||
"25": "--chart-lg-2",
|
||||
"26": "--chart-lg-3",
|
||||
} as const,
|
||||
|
||||
/** 연도별 브랜드 색상 (CBrand, Samsung, LG) */
|
||||
YEAR_BRAND: {
|
||||
"24": ["--chart-cbrand-1", "--chart-samsung-1", "--chart-lg-1"],
|
||||
"25": ["--chart-cbrand-2", "--chart-samsung-2", "--chart-lg-2"],
|
||||
"26": ["--chart-cbrand-3", "--chart-samsung-3", "--chart-lg-3"],
|
||||
} as const,
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 테이블 색상 설정
|
||||
*/
|
||||
export const TABLE_COLORS = {
|
||||
/** 게이지 테이블 색상 */
|
||||
GAUGE: {
|
||||
FILL: "hsl(var(--lg-gray-200) / 0.85)",
|
||||
TRACK: "hsl(var(--lg-pink-300) / 0.2)",
|
||||
},
|
||||
|
||||
/** Sign 표기 셀 배경색 */
|
||||
SIGN_CELL: {
|
||||
POSITIVE: "hsl(var(--primary) / 0.08)",
|
||||
NEGATIVE: "hsl(var(--info) / 0.08)",
|
||||
ZERO: "hsl(var(--lg-gray-200) / 0.6)",
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 테이블 크기 설정
|
||||
*/
|
||||
export const TABLE_DIMENSIONS = {
|
||||
CELL_HEIGHT: {
|
||||
DEFAULT: 26,
|
||||
COMPACT: 20,
|
||||
EXPANDED: 32,
|
||||
},
|
||||
MIN_WIDTH: {
|
||||
STANDARD: 1600,
|
||||
COMPACT: 1200,
|
||||
WIDE: 2000,
|
||||
},
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 차트/테이블 라벨 텍스트
|
||||
*/
|
||||
export const CHART_LABELS = {
|
||||
TOTAL: "전체",
|
||||
LG: "LG",
|
||||
GAP: "전년 대비 GAP(%)",
|
||||
CAGR: "CAGR(%)",
|
||||
SAMPLE_COUNT: "(사례수)",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 차트 제목 텍스트
|
||||
*/
|
||||
export const CHART_TITLES = {
|
||||
LG_PENETRATION: "LG제품 보급률",
|
||||
TOTAL_PENETRATION: "전체 보급률",
|
||||
LG_PURCHASE: "LG제품 구매율",
|
||||
TOTAL_PURCHASE: "전체 구매율",
|
||||
BRAND_SHARE: "브랜드별 점유율",
|
||||
} as const;
|
||||
@@ -2,9 +2,9 @@ import {
|
||||
CategoryTargetData,
|
||||
CategoryTargetItem,
|
||||
CategoryTargetType,
|
||||
CategoryTargetTypeItem,
|
||||
CategoryTargetTypeItem, FilterItem,
|
||||
TotalFilterItem
|
||||
} from "./filter.types";
|
||||
} from "@/types/filter.types";
|
||||
|
||||
export const totalFilters:TotalFilterItem[] = [
|
||||
{
|
||||
@@ -18,6 +18,8 @@ export const totalFilters:TotalFilterItem[] = [
|
||||
{ value: "4", label: "기혼 학령기"},
|
||||
{ value: "5", label: "기혼 성인자녀"},
|
||||
{ value: "6", label: "독립 시니어"},
|
||||
{ value: "7", label: "비혼 중년"},
|
||||
{ value: "8", label: "기타"},
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -32,7 +34,7 @@ export const totalFilters:TotalFilterItem[] = [
|
||||
]
|
||||
},
|
||||
{
|
||||
variable:"tenure",
|
||||
variable:"occupancy",
|
||||
variableName:"입주 형태",
|
||||
children:[
|
||||
{ value: "0", label: "전체"},
|
||||
@@ -44,7 +46,7 @@ export const totalFilters:TotalFilterItem[] = [
|
||||
]
|
||||
},
|
||||
{
|
||||
variable:"pyeong",
|
||||
variable:"houseSize",
|
||||
variableName:"거주 평형",
|
||||
children:[
|
||||
{ value: "0", label: "전체"},
|
||||
@@ -64,7 +66,8 @@ export const totalFilters:TotalFilterItem[] = [
|
||||
{ value: "2", label: "주택"},
|
||||
{ value: "3", label: "오피스텔"},
|
||||
{ value: "4", label: "(연립)빌라"},
|
||||
{ value: "5", label: "기타"},
|
||||
{ value: "5", label: "원룸"},
|
||||
{ value: "6", label: "기타"},
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -85,11 +88,11 @@ export const totalFilters:TotalFilterItem[] = [
|
||||
variableName:"연령대",
|
||||
children:[
|
||||
{ value: "0", label: "전체"},
|
||||
{ value: "2", label: "20대"},
|
||||
{ value: "3", label: "30대"},
|
||||
{ value: "4", label: "40대"},
|
||||
{ value: "5", label: "50대"},
|
||||
{ value: "6", label: "60대"},
|
||||
{ value: "1", label: "20대"},
|
||||
{ value: "2", label: "30대"},
|
||||
{ value: "3", label: "40대"},
|
||||
{ value: "4", label: "50대"},
|
||||
{ value: "5", label: "60대"},
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -124,23 +127,60 @@ 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.PROFILE_ALL, 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.PROFILE_ALL, 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: "구매 형식"},
|
||||
]
|
||||
},
|
||||
]
|
||||
|
||||
export const categoryByDataBanner:FilterItem[] = [
|
||||
{
|
||||
variable:"lifeStage",
|
||||
variableName:"라이프 스테이지",
|
||||
},
|
||||
{
|
||||
variable:"age",
|
||||
variableName:"연령대",
|
||||
},
|
||||
{
|
||||
variable:"household",
|
||||
variableName:"가구원 수",
|
||||
},
|
||||
{
|
||||
variable:"occupancy",
|
||||
variableName:"입주 형태",
|
||||
},
|
||||
{
|
||||
variable:"housing",
|
||||
variableName:"주거 형태",
|
||||
},
|
||||
{
|
||||
variable:"houseSize",
|
||||
variableName:"거주 평형",
|
||||
},
|
||||
{
|
||||
variable:"income",
|
||||
variableName:"월 소득 규모",
|
||||
},
|
||||
{
|
||||
variable:"region",
|
||||
variableName:"지역",
|
||||
},
|
||||
]
|
||||
137
src/const/lg-banner.const.ts
Normal file
137
src/const/lg-banner.const.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import type { BannerKey } from "@/types/lg.types";
|
||||
import { BANNER_KEY_MAP } from "@/const/lg-schema.const";
|
||||
|
||||
export type BannerGroupLeafNode = {
|
||||
type: "leaf";
|
||||
key: BannerKey;
|
||||
};
|
||||
|
||||
export type BannerGroupBranchNode = {
|
||||
type: "group";
|
||||
id: string;
|
||||
label: string;
|
||||
children: readonly BannerGroupNode[];
|
||||
};
|
||||
|
||||
export type BannerGroupNode = BannerGroupLeafNode | BannerGroupBranchNode;
|
||||
|
||||
export type BannerGroupDefinition = {
|
||||
label: string;
|
||||
children: readonly BannerGroupNode[];
|
||||
};
|
||||
|
||||
export const BANNER_KEYS = Object.keys(BANNER_KEY_MAP) as Array<keyof typeof BANNER_KEY_MAP>;
|
||||
export const BANNER_KEY = Object.keys(BANNER_KEY_MAP).reduce((acc, k) => {
|
||||
(acc as any)[k] = k;
|
||||
return acc;
|
||||
}, {} as { [K in BannerKey]: K });
|
||||
|
||||
const leaf = (key: BannerKey): BannerGroupLeafNode => ({
|
||||
type: "leaf",
|
||||
key,
|
||||
});
|
||||
|
||||
const group = (id: string, label: string, children: readonly BannerGroupNode[]): BannerGroupBranchNode => ({
|
||||
type: "group",
|
||||
id,
|
||||
label,
|
||||
children,
|
||||
});
|
||||
|
||||
export const BANNER_GROUP = {
|
||||
lifeStage: {
|
||||
label: "라이프스테이지 별",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KLIFEstAGE#1"]),
|
||||
group("life-stage-married", "기혼", [
|
||||
leaf(BANNER_KEY["KLIFEstAGE#2"]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#3"]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#4"]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#5"]),
|
||||
]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#6"]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#7"]),
|
||||
leaf(BANNER_KEY["KLIFEstAGE#8"]),
|
||||
],
|
||||
},
|
||||
household: {
|
||||
label: "가구원수 별",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KSQ8_R_DB#1"]),
|
||||
leaf(BANNER_KEY["KSQ8_R_DB#2"]),
|
||||
leaf(BANNER_KEY["KSQ8_R_DB#3"]),
|
||||
leaf(BANNER_KEY["KSQ8_R_DB#4"]),
|
||||
],
|
||||
},
|
||||
age: {
|
||||
label: "연령",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KSQ2_R_R#1"]),
|
||||
leaf(BANNER_KEY["KSQ2_R_R#2"]),
|
||||
leaf(BANNER_KEY["KSQ2_R_R#3"]),
|
||||
leaf(BANNER_KEY["KSQ2_R_R#4"]),
|
||||
leaf(BANNER_KEY["KSQ2_R_R#5"]),
|
||||
],
|
||||
},
|
||||
occupancy: {
|
||||
label: "입주 형태",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KDQ6#1"]),
|
||||
leaf(BANNER_KEY["KDQ6#2"]),
|
||||
leaf(BANNER_KEY["KDQ6#3"]),
|
||||
leaf(BANNER_KEY["KDQ6#4"]),
|
||||
leaf(BANNER_KEY["KDQ6#5"]),
|
||||
],
|
||||
},
|
||||
housing: {
|
||||
label: "주거 형태",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KDQ4#1"]),
|
||||
leaf(BANNER_KEY["KDQ4#2"]),
|
||||
leaf(BANNER_KEY["KDQ4#3"]),
|
||||
leaf(BANNER_KEY["KDQ4#4"]),
|
||||
leaf(BANNER_KEY["KDQ4#5"]),
|
||||
leaf(BANNER_KEY["KDQ4#6"]),
|
||||
],
|
||||
},
|
||||
houseSize: {
|
||||
label: "거주 평형",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KDQ5#1"]),
|
||||
leaf(BANNER_KEY["KDQ5#2"]),
|
||||
leaf(BANNER_KEY["KDQ5#3"]),
|
||||
leaf(BANNER_KEY["KDQ5#4"]),
|
||||
leaf(BANNER_KEY["KDQ5#5"]),
|
||||
],
|
||||
},
|
||||
region: {
|
||||
label: "거주 지역",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KSQ4_R_R#1"]),
|
||||
leaf(BANNER_KEY["KSQ4_R_R#2"]),
|
||||
leaf(BANNER_KEY["KSQ4_R_R#3"]),
|
||||
leaf(BANNER_KEY["KSQ4_R_R#4"]),
|
||||
leaf(BANNER_KEY["KSQ4_R_R#5"]),
|
||||
leaf(BANNER_KEY["KSQ4_R_R#6"]),
|
||||
],
|
||||
},
|
||||
income: {
|
||||
label: "소득수준",
|
||||
children: [
|
||||
leaf(BANNER_KEY["KDQ3_DB#1"]),
|
||||
leaf(BANNER_KEY["KDQ3_DB#2"]),
|
||||
leaf(BANNER_KEY["KDQ3_DB#3"]),
|
||||
leaf(BANNER_KEY["KDQ3_DB#4"]),
|
||||
],
|
||||
},
|
||||
} as const satisfies Record<string, BannerGroupDefinition>;
|
||||
|
||||
export const isBannerGroupBranchNode = (node: BannerGroupNode): node is BannerGroupBranchNode => {
|
||||
return node.type === "group";
|
||||
}
|
||||
|
||||
export const flattenBannerGroupKeys = (nodes: readonly BannerGroupNode[]): BannerKey[] => {
|
||||
return nodes.flatMap((node) => (node.type === "leaf" ? [node.key] : flattenBannerGroupKeys(node.children)));
|
||||
}
|
||||
|
||||
export const BANNER_GROUP_KEY = Object.keys(BANNER_GROUP) as string[];
|
||||
15
src/const/lg-common.const.ts
Normal file
15
src/const/lg-common.const.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
export const DEBOUNCE_TIME = 500;
|
||||
export const USE_CACHE = true;
|
||||
export const API_DECIMAL_POINT = 0;
|
||||
export const VIEW_DECIMAL_POINT = 0;
|
||||
|
||||
export const SITE_TITLE = 'LGE CX Dashboard';
|
||||
|
||||
export const YEARS = ["2023", "2024", "2025"];
|
||||
export const LAST_YEAR = YEARS.at(-1)!;
|
||||
|
||||
export const GAP_WORDING = "전년 대비 GAP(%p)";
|
||||
export const UNIT_TEXT = "(단위 %)"
|
||||
export const SAMPLE_SIZE_NOTICE = "* 30표본 미만 해석에 주의";
|
||||
|
||||
export const BRAND_LIST = ['기타', 'C Brand', '삼성', 'LG'];
|
||||
70
src/const/lg-product.const.ts
Normal file
70
src/const/lg-product.const.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { GaugeColumn } from "@/components/lge-dashboard";
|
||||
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
|
||||
import type { LifeStageRow } from "@/types/lg.types";
|
||||
|
||||
export const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
|
||||
{ key: "item", header: "", rowHead: true, render: (r) => r.item },
|
||||
{ key: "total", header: "전체", max: 100, align: "left", cellType: "number" },
|
||||
{ key: "KLIFEstAGE#1", header: "미혼", max: 100, align: "left" },
|
||||
{
|
||||
id: "life-stage-married",
|
||||
header: "기혼",
|
||||
children: [
|
||||
{ key: "KLIFEstAGE#2", header: "무자녀", max: 100, align: "left" },
|
||||
{ key: "KLIFEstAGE#3", header: "미취학", max: 100, align: "left" },
|
||||
{ key: "KLIFEstAGE#4", header: "취학자녀", max: 100, align: "left" },
|
||||
{ key: "KLIFEstAGE#5", header: "성인자녀", max: 100, align: "left" },
|
||||
],
|
||||
},
|
||||
{ key: "KLIFEstAGE#6", header: "독립\n시니어", max: 100, align: "left" },
|
||||
{ key: "KLIFEstAGE#7", header: "비혼 중년", max: 100, align: "left" },
|
||||
{ key: "KLIFEstAGE#8", header: "기타", max: 100, align: "left" },
|
||||
];
|
||||
|
||||
export const LIFE_STAGE_GROUPS = [
|
||||
{ title: "대형가전 군", items: ["KPRODUCT#1", "KPRODUCT#7", "KPRODUCT#8", "KPRODUCT#12", "KPRODUCT#14", "KPRODUCT#2", "KPRODUCT#3", "KPRODUCT#11"] },
|
||||
{ title: "소형가전 군", items: ["KPRODUCT#9", "KPRODUCT#13", "KPRODUCT#4"] },
|
||||
{ title: "신가전 군", items: ["KPRODUCT#10", "KPRODUCT#6"] },
|
||||
] as const;
|
||||
|
||||
export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array<keyof typeof PRODUCT_KEY_MAP>;
|
||||
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
|
||||
|
||||
export const PRODUCTS_FILTER_ITEM = [
|
||||
{
|
||||
path: "kitchen",
|
||||
items: [
|
||||
"KPRODUCT#1", // 냉장고
|
||||
"KPRODUCT#2", // 김치 냉장고
|
||||
"KPRODUCT#3", // 정수기
|
||||
"KPRODUCT#4", // 전기 레인지
|
||||
"KPRODUCT#5", // 식기 세척기
|
||||
"KPRODUCT#6", // 음식물처리기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "living",
|
||||
items: [
|
||||
"KPRODUCT#7", // 세탁기
|
||||
"KPRODUCT#9", // 건조기
|
||||
"KPRODUCT#8", // 청소기
|
||||
"KPRODUCT#10", // 로봇 청소기
|
||||
"KPRODUCT#11", // 의류 관리기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "es",
|
||||
items: [
|
||||
"KPRODUCT#12", // 에어컨
|
||||
"KPRODUCT#13", // 공기 청정기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "ms",
|
||||
items: [
|
||||
"KPRODUCT#14", // TV
|
||||
"KPRODUCT#15", // 노트북
|
||||
"KPRODUCT#16", // 모니터
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
82
src/const/lg-schema.const.ts
Normal file
82
src/const/lg-schema.const.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
export const PRODUCT_KEY_MAP = {
|
||||
"KPRODUCT#1": "냉장고",
|
||||
"KPRODUCT#2": "김치 냉장고",
|
||||
"KPRODUCT#3": "정수기",
|
||||
"KPRODUCT#4": "전기 레인지",
|
||||
"KPRODUCT#5": "식기 세척기",
|
||||
"KPRODUCT#6": "음식물처리기",
|
||||
|
||||
"KPRODUCT#7": "세탁기",
|
||||
"KPRODUCT#9": "건조기",
|
||||
"KPRODUCT#8": "청소기",
|
||||
"KPRODUCT#10": "로봇 청소기",
|
||||
"KPRODUCT#11": "의류 관리기",
|
||||
|
||||
"KPRODUCT#12": "에어컨",
|
||||
"KPRODUCT#13": "공기 청정기",
|
||||
|
||||
"KPRODUCT#14": "TV",
|
||||
"KPRODUCT#15": "노트북",
|
||||
"KPRODUCT#16": "모니터",
|
||||
} as const;
|
||||
|
||||
export const BANNER_KEY_MAP = {
|
||||
// 라이프 스테이지
|
||||
"KLIFEstAGE#1": "미혼",
|
||||
"KLIFEstAGE#2": "무자녀",
|
||||
"KLIFEstAGE#3": "미취학",
|
||||
"KLIFEstAGE#4": "취학자녀",
|
||||
"KLIFEstAGE#5": "성인자녀",
|
||||
"KLIFEstAGE#6": "독립\n시니어",
|
||||
"KLIFEstAGE#7": "비혼 중년",
|
||||
"KLIFEstAGE#8": "기타",
|
||||
|
||||
// 가구원수
|
||||
"KSQ8_R_DB#1": "1인 가구",
|
||||
"KSQ8_R_DB#2": "2인 가구",
|
||||
"KSQ8_R_DB#3": "3인 가구",
|
||||
"KSQ8_R_DB#4": "4인 이상 가구",
|
||||
|
||||
// 연령
|
||||
"KSQ2_R_R#1": "20대",
|
||||
"KSQ2_R_R#2": "30대",
|
||||
"KSQ2_R_R#3": "40대",
|
||||
"KSQ2_R_R#4": "50대",
|
||||
"KSQ2_R_R#5": "60대",
|
||||
|
||||
// 점유형태
|
||||
"KDQ6#1": "자가",
|
||||
"KDQ6#2": "전세",
|
||||
"KDQ6#3": "전+월세\n(보증금有)",
|
||||
"KDQ6#4": "월세\n(보증금無)",
|
||||
"KDQ6#5": "기타",
|
||||
|
||||
// 주거형태
|
||||
"KDQ4#1": "아파트",
|
||||
"KDQ4#2": "주택",
|
||||
"KDQ4#3": "오피스텔",
|
||||
"KDQ4#4": "(연립)빌라",
|
||||
"KDQ4#5": "원룸",
|
||||
"KDQ4#6": "기타",
|
||||
|
||||
// 평형
|
||||
"KDQ5#1": "19평 이하",
|
||||
"KDQ5#2": "20평형 대",
|
||||
"KDQ5#3": "30평형 대",
|
||||
"KDQ5#4": "40평형 대",
|
||||
"KDQ5#5": "50평형 대 이상",
|
||||
|
||||
// 권역
|
||||
"KSQ4_R_R#1": "서울, 인천, 경기도",
|
||||
"KSQ4_R_R#2": "경남, 부산, 울산",
|
||||
"KSQ4_R_R#3": "경북, 대구",
|
||||
"KSQ4_R_R#4": "전라도, 광주",
|
||||
"KSQ4_R_R#5": "충청, 대전, 세종",
|
||||
"KSQ4_R_R#6": "강원, 제주",
|
||||
|
||||
// 소득
|
||||
"KDQ3_DB#1": "299만원 이하",
|
||||
"KDQ3_DB#2": "300~599만원 이하",
|
||||
"KDQ3_DB#3": "600~899만원 이하",
|
||||
"KDQ3_DB#4": "900만원 이상",
|
||||
} as const;
|
||||
49
src/const/lg-survey.const.ts
Normal file
49
src/const/lg-survey.const.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export const QID_SURVEY_TITLE: Record<string, string> = {
|
||||
"KQA3_3": "Q. 보유하고 계신 제품의 브랜드는 어떻게 되십니까?",
|
||||
"KQA3_4": "Q. 보유하고 계신 제품의 타입은 어떻게 되십니까?",
|
||||
"KQA3_5": "Q. 보유하고 계신 제품의 깊이 타입은 어떻게 되십니까?",
|
||||
"KQA3_6": "Q. 보유하고 계신 제품의 용량은 어떻게 되십니까?",
|
||||
"KQA3_7": "Q. 보유하고 계신 제품의 설치 형태는 어떻게 되십니까?",
|
||||
"KQA3_8": "Q. 보유하고 계신 제품은 메인 가구와 어떻게 배치되어 있습니까?",
|
||||
"KQA3_9": "Q. 보유하고 계신 제품에 포함되어 있는 기능이 있으십니까? 모두 선택해 주세요.",
|
||||
"KQA3_10": "Q. 보유하고 계신 제품의 스크린 사이즈는 어떻게 되십니까?",
|
||||
"KQA3_11": "Q. 보유하고 계신 제품의 가장 주된 용도는 무엇입니까?",
|
||||
"KQA3_12": "Q. 보유하고 계신 제품은 스마트 모니터(자체적으로 OS를 가지고 있어, 기타 기기 연결 없이 작동이 가능한 모니터) 입니까?",
|
||||
"KQA3_13": "Q. 보유하고 계신 제품의 구동 방식은 어떻게 되십니까?",
|
||||
"KQA3_14": "Q. 보유하고 계신 제품의 화구 수는 어떻게 되십니까?",
|
||||
"KQA3_1": "Q. 보유하고 계신 제품을 구매 또는 보유하게 된 경로가 어떻게 되십니까? ",
|
||||
"KQA3_2_1": "Q. 귀하께서는 제품을 어떤 방식으로 구입하셨습니까? ",
|
||||
|
||||
"KQX3_3": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 브랜드는 어떻게 되십니까?",
|
||||
"KQB1": "Q. 귀하께서 [#YEAR#]년에 제품을 구매하실 때 구매를 고려하셨던 브랜드는 무엇입니까? 모두 선택하여 주시기 바랍니다",
|
||||
"KQX3_4": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 타입은 어떻게 되십니까?",
|
||||
"KQX3_5": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 깊이 타입은 어떻게 되십니까?",
|
||||
"KQX3_6": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 용량은 어떻게 되십니까?",
|
||||
"KQX3_7": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 설치 형태는 어떻게 되십니까?",
|
||||
"KQX3_8": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품은 메인 가구와 어떻게 배치되어 있습니까?",
|
||||
"KQX3_9": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품에 포함되어 있는 기능이 있으십니까? 모두 선택해 주세요.",
|
||||
"KQX3_10": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 스크린 사이즈는 어떻게 되십니까?",
|
||||
"KQX3_11": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 가장 주된 용도는 무엇입니까?",
|
||||
"KQX3_12": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품은 스마트 모니터(자체적으로 OS를 가지고 있어, 기타 기기 연결 없이 작동이 가능한 모니터) 입니까?",
|
||||
"KQX3_13": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 구동 방식은 어떻게 되십니까?",
|
||||
"KQX3_14": "Q. 귀하께서 [#YEAR#]년에 구매하신 제품의 화구 수는 어떻게 되십니까?",
|
||||
"KQB2": "Q. 귀하께서는 [#YEAR#]년에 제품을 신규로 구입하신 건가요? 교체/추가 구입하신 건가요? 한 가지만 선택해주세요",
|
||||
"KQB3": "Q. 귀하께서 [#YEAR#]년에 제품을 구입하신 이유/계기(상황)는 무엇입니까? 가장 주요한 이유/계기를 한 가지만 선택해주세요",
|
||||
"KQB4_NET": "Q. 최종적으로 제품을 구매하신 곳은 어디십니까? 한 가지만 선택해주세요",
|
||||
"KQB4": "Q. 최종적으로 제품을 구매하신 곳은 어디십니까? 한 가지만 선택해주세요",
|
||||
"KQX3_2_1": "Q. 귀하께서는 제품을 어떤 방식으로 구입하셨습니까? 한가지만 선택해주세요",
|
||||
|
||||
"KQC2": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 브랜드로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
|
||||
"KQC3_1": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 타입으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
|
||||
"KQC3_2": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 깊이 타입으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
|
||||
"KQC3_3": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 설치 형태로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
|
||||
"KQC3_4": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 설치 방식을 실제 공간에 구현하기 위해서 다음 중 어떤 방식의 시공이 필요하다고 생각하십니까?",
|
||||
"KQC3_5": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 <냉장고와 김치냉장고>를 어떤 형태로 설치하실 계획이십니까?",
|
||||
"KQC3_6": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품은 어디에 설치하실 계획이십니까?",
|
||||
"KQC3_7": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품은 어떤 환경에 설치하실 계획이십니까?",
|
||||
"KQC3_8": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품의 특징으로 고려하고 계신 것은 무엇입니까? 모두 선택해주세요",
|
||||
"KQC5": "Q. 귀하께서 [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 신규로 구입하실 건가요? 교체/추가 구입하실 건가요? 한 가지만 선택해주세요",
|
||||
"KQC6_NET": "Q. [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 구매하고 싶으신 곳은 어디십니까? 한 가지만 선택해주세요",
|
||||
"KQC6": "Q. [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 구매하고 싶으신 곳은 어디십니까? 한 가지만 선택해주세요",
|
||||
"KQC7": "Q. 그렇다면, [#NEXT_YEAR#]년 이내 구입을 고려하시는 제품을 어떤 방식으로 구입하길 원하십니까? 한가지만 선택해주세요",
|
||||
}
|
||||
@@ -1,213 +0,0 @@
|
||||
import {BannerKey, LifeStageRow} from "@/types/lg";
|
||||
import {GaugeColumn} from "@/components/lge-dashboard";
|
||||
|
||||
export const SITE_TITLE = 'LGE CX Dashboard';
|
||||
|
||||
export const PRODUCT_KEY_MAP = {
|
||||
refrigerator: "냉장고",
|
||||
kimchiRefrigerator: "김치 냉장고",
|
||||
dishwasher: "식기 세척기",
|
||||
waterPurifier: "정수기",
|
||||
electricRange: "전기 레인지",
|
||||
foodWasteDisposer: "음식물처리기",
|
||||
|
||||
washingMachine: "세탁기",
|
||||
dryer: "건조기",
|
||||
vacuumCleaner: "청소기",
|
||||
robotVacuum: "로봇 청소기",
|
||||
clothingCareSystem: "의류 관리기",
|
||||
|
||||
airConditioner: "에어컨",
|
||||
airPurifier: "공기 청정기",
|
||||
|
||||
tv: "TV",
|
||||
monitor: "모니터",
|
||||
laptop: "노트북",
|
||||
} as const;
|
||||
|
||||
export const BANNER_KEY_MAP = {
|
||||
// 라이프 스테이지
|
||||
single: "미혼",
|
||||
noKids: "무자녀",
|
||||
preschoolKids: "미취학",
|
||||
schoolKids: "취학자녀",
|
||||
adultKids: "성인자녀",
|
||||
independentSenior: "독립시니어",
|
||||
|
||||
// 가구원수
|
||||
hh1: "1인 가구",
|
||||
hh2: "2인 가구",
|
||||
hh3: "3인 가구",
|
||||
hh4Plus: "4인 이상 가구",
|
||||
|
||||
// 연령
|
||||
age20s: "20대",
|
||||
age30s: "30대",
|
||||
age40s: "40대",
|
||||
age50s: "50대",
|
||||
age60s: "60대",
|
||||
|
||||
// 점유형태
|
||||
ownerOccupied: "자가",
|
||||
jeonse: "전세",
|
||||
depositAndMonthly: "전+월세 (보증금有)",
|
||||
monthlyNoDeposit: "월세 (보증금無)",
|
||||
otherTenure: "기타",
|
||||
|
||||
// 주거형태
|
||||
apartment: "아파트",
|
||||
house: "주택",
|
||||
officetel: "오피스텔",
|
||||
villa: "(연립)빌라",
|
||||
studio: "원룸",
|
||||
otherHousingType: "기타",
|
||||
|
||||
// 평형
|
||||
under19Pyeong: "19평 이하",
|
||||
pyeong20s: "20평형 대",
|
||||
pyeong30s: "30평형 대",
|
||||
pyeong40s: "40평형 대",
|
||||
pyeong50Plus: "50평형 대 이상",
|
||||
|
||||
// 권역
|
||||
regionCapital: "서울, 인천, 경기도",
|
||||
regionGyeongnamBusanUlsan: "경남, 부산, 울산",
|
||||
regionGyeongbukDaegu: "경북, 대구",
|
||||
regionJeollaGwangju: "전라도, 광주",
|
||||
regionChungcheongDaejeonSejong: "충청, 대전, 세종",
|
||||
regionGangwonJeju: "강원, 제주",
|
||||
|
||||
// 소득
|
||||
incomeUnder299: "299만원 이하",
|
||||
income300to599: "300~599만원 이하",
|
||||
income600to899: "600~899만원 이하",
|
||||
income900Plus: "900만원 이상",
|
||||
} as const;
|
||||
|
||||
export const LIFE_STAGE_COLUMNS: GaugeColumn<LifeStageRow>[] = [
|
||||
{ key: "item", header: "", headRowSpan:2, rowHead: true, render: (r) => r.item },
|
||||
|
||||
{ key: "total", header: "전체", headRowSpan:2, max: 100, align: "left", cellType:"number"},
|
||||
{ key: "single", header: "미혼", max: 100 , align: "left"},
|
||||
|
||||
{ key: "noKids", header: "무자녀", group: "기혼", max: 100 , align: "left"},
|
||||
{ key: "preschoolKids", header: "미취학", group: "기혼", max: 100 , align: "left"},
|
||||
{ key: "schoolKids", header: "취학자녀", group: "기혼", max: 100 , align: "left"},
|
||||
{ key: "adultKids", header: "성인자녀", group: "기혼", max: 100 , align: "left"},
|
||||
|
||||
{ key: "independentSenior", header: "독립\n시니어", max: 100 , align: "left"},
|
||||
];
|
||||
|
||||
export const LIFE_STAGE_GROUPS = [
|
||||
{ title: "대형가전 군", items: ["냉장고", "세탁기", "건조기", "에어컨", "TV", "김치 냉장고", "식기세척기", "의류 관리기"] },
|
||||
{ title: "소형가전 군", items: ["청소기", "공기 청정기", "정수기"] },
|
||||
{ title: "신가전 군", items: ["로봇 청소기", "음식물처리기"] },
|
||||
] as const;
|
||||
|
||||
export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array<keyof typeof PRODUCT_KEY_MAP>;
|
||||
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
|
||||
export const YEARS = ["24", "25", "26"];
|
||||
export const 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, // 음식물처리기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "living",
|
||||
items: [
|
||||
PRODUCT_KEY_MAP.washingMachine, // 세탁기
|
||||
PRODUCT_KEY_MAP.dryer, // 건조기
|
||||
PRODUCT_KEY_MAP.vacuumCleaner, // 청소기
|
||||
PRODUCT_KEY_MAP.robotVacuum, // 로봇 청소기
|
||||
PRODUCT_KEY_MAP.clothingCareSystem, // 의류 관리기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "es",
|
||||
items: [
|
||||
PRODUCT_KEY_MAP.airConditioner, // 에어컨
|
||||
PRODUCT_KEY_MAP.airPurifier, // 공기 청정기
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "ms",
|
||||
items: [
|
||||
PRODUCT_KEY_MAP.tv, // TV
|
||||
PRODUCT_KEY_MAP.monitor, // 모니터
|
||||
PRODUCT_KEY_MAP.laptop, // 노트북
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const BANNER_KEY = Object.keys(BANNER_KEY_MAP).reduce((acc, k) => {
|
||||
(acc as any)[k] = k;
|
||||
return acc;
|
||||
}, {} as { [K in BannerKey]: K });
|
||||
|
||||
export const BANNER_GROUP = {
|
||||
lifeStage: {
|
||||
label: "라이프스테이지 별",
|
||||
keys: [
|
||||
BANNER_KEY.single,
|
||||
BANNER_KEY.noKids,
|
||||
BANNER_KEY.preschoolKids,
|
||||
BANNER_KEY.schoolKids,
|
||||
BANNER_KEY.adultKids,
|
||||
BANNER_KEY.independentSenior,
|
||||
],
|
||||
},
|
||||
household: {
|
||||
label: "가구원수 별",
|
||||
keys: [BANNER_KEY.hh1, BANNER_KEY.hh2, BANNER_KEY.hh3, BANNER_KEY.hh4Plus],
|
||||
},
|
||||
age: {
|
||||
label: "연령",
|
||||
keys: [BANNER_KEY.age20s, BANNER_KEY.age30s, BANNER_KEY.age40s, BANNER_KEY.age50s, BANNER_KEY.age60s],
|
||||
},
|
||||
tenure: {
|
||||
label: "입주 형태",
|
||||
keys: [BANNER_KEY.ownerOccupied, BANNER_KEY.jeonse, BANNER_KEY.depositAndMonthly, BANNER_KEY.monthlyNoDeposit, BANNER_KEY.otherTenure],
|
||||
},
|
||||
housing: {
|
||||
label: "주거 형태",
|
||||
keys: [BANNER_KEY.apartment, BANNER_KEY.house, BANNER_KEY.officetel, BANNER_KEY.villa, BANNER_KEY.studio, BANNER_KEY.otherHousingType],
|
||||
},
|
||||
pyeong: {
|
||||
label: "거주 평형",
|
||||
keys: [BANNER_KEY.under19Pyeong, BANNER_KEY.pyeong20s, BANNER_KEY.pyeong30s, BANNER_KEY.pyeong40s, BANNER_KEY.pyeong50Plus],
|
||||
},
|
||||
region: {
|
||||
label: "거주 지역",
|
||||
keys: [
|
||||
BANNER_KEY.regionCapital,
|
||||
BANNER_KEY.regionGyeongnamBusanUlsan,
|
||||
BANNER_KEY.regionGyeongbukDaegu,
|
||||
BANNER_KEY.regionJeollaGwangju,
|
||||
BANNER_KEY.regionChungcheongDaejeonSejong,
|
||||
BANNER_KEY.regionGangwonJeju,
|
||||
],
|
||||
},
|
||||
income: {
|
||||
label: "소득수준",
|
||||
keys: [BANNER_KEY.incomeUnder299, BANNER_KEY.income300to599, BANNER_KEY.income600to899, BANNER_KEY.income900Plus],
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const SAMPLE_SIZE_NOTICE = "* 30 미만 샘플에 대한 설명";
|
||||
@@ -1,4 +1,4 @@
|
||||
import {SubMenuItem, TopMenuItem} from "@/config/menu.types";
|
||||
import {SubMenuItem, TopMenuItem} from "@/types/menu.types";
|
||||
|
||||
export const topMenus: TopMenuItem[] = [
|
||||
{
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {DEBOUNCE_TIME} from "@/const/lg-common.const";
|
||||
|
||||
export function useDebouncedValue<T>(value: T, delayMs = 1200) {
|
||||
export function useDebouncedValue<T>(value: T, delayMs = DEBOUNCE_TIME) {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
22
src/hooks/useResize.ts
Normal file
22
src/hooks/useResize.ts
Normal 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;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CHART_GRID_DEFAULTS, BAR_WIDTHS } from "@/const/chartConst";
|
||||
import { AXIS_HIDE_Y_STYLE, BAR_WIDTHS, CHART_GRID_DEFAULTS } from "@/components/lge-dashboard/chart/chart.config";
|
||||
import {ChartData, NewNumber} from "@/components/lge-dashboard";
|
||||
|
||||
export function reverseCategories<T extends ChartData>(data: T): T {
|
||||
@@ -48,8 +48,8 @@ export function createDefaultLegend(
|
||||
overrides?: any
|
||||
): any {
|
||||
return {
|
||||
top: 0,
|
||||
...overrides,
|
||||
top: 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,8 +60,8 @@ export function createReverseLegend(
|
||||
const order = originalData.series.map((s) => s.name);
|
||||
|
||||
return createDefaultLegend({
|
||||
data: order, // ✅ legend 표시 순서 고정(원본)
|
||||
...overrides,
|
||||
data: order,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -180,9 +180,7 @@ export function createValueAxis(
|
||||
if (hideStyle) {
|
||||
return {
|
||||
...base,
|
||||
axisLabel: { show: false },
|
||||
axisTick: { show: false },
|
||||
axisLine: { show: false },
|
||||
...AXIS_HIDE_Y_STYLE,
|
||||
splitLine: { show: false },
|
||||
...overrides,
|
||||
};
|
||||
|
||||
@@ -7,6 +7,4 @@ const required = (name: string) => {
|
||||
export const serverEnv = {
|
||||
ENV: required("ENV"),
|
||||
API_BACK_SERVER: required("API_BACK_SERVER"),
|
||||
API_KART_SERVER: required("API_KART_SERVER"),
|
||||
KART_API_KEY: required("KART_API_KEY"),
|
||||
};
|
||||
@@ -33,6 +33,11 @@ export type QueryValue = string | string[] | undefined;
|
||||
export type Query = Record<string, QueryValue>;
|
||||
export type PathParams = Record<string, string | number | boolean>;
|
||||
|
||||
export type NextFetchOptions = {
|
||||
revalidate?: number;
|
||||
tags?: string[];
|
||||
};
|
||||
|
||||
export type RequestOptions = {
|
||||
method?: HttpMethod;
|
||||
pathParams?: PathParams;
|
||||
@@ -47,6 +52,8 @@ export type RequestOptions = {
|
||||
autoLogoutOnAuthError?: boolean;
|
||||
expectText?: boolean;
|
||||
expectBinary?: boolean;
|
||||
cache?: RequestCache; // "force-cache" | "no-store" | ...
|
||||
next?: NextFetchOptions; // Next 서버 fetch 확장 옵션
|
||||
};
|
||||
|
||||
export type HttpClientOptions = {
|
||||
@@ -140,12 +147,17 @@ export const createHttpClient = (baseURL: string, opts: HttpClientOptions = {})
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? defaultTimeoutMs);
|
||||
|
||||
const isServer = typeof window === "undefined";
|
||||
const cacheMode: RequestCache = options.cache ?? (isServer && options.next ? "force-cache" : "no-store");
|
||||
const nextOpt = isServer ? options.next : undefined;
|
||||
|
||||
try {
|
||||
const res = await fetch(url.toString(), {
|
||||
method: options.method ?? (body ? "POST" : "GET"),
|
||||
headers,
|
||||
body,
|
||||
cache: "no-store",
|
||||
cache: cacheMode,
|
||||
...(nextOpt ? ({ next: nextOpt } as any) : {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,14 +1,32 @@
|
||||
import {BannerGroupKey, ServerBannerRow} from "@/types/lg";
|
||||
import {
|
||||
BannerGroupKey,
|
||||
BannerResponse,
|
||||
BannerRow, BuildPageModeConfigResult,
|
||||
ProductResponse, ProductRow,
|
||||
StatisticsRequest
|
||||
} from "@/types/lg.types";
|
||||
import {ChartData} from "@/components/lge-dashboard";
|
||||
import {BANNER_GROUP} from "@/const/lgConst";
|
||||
import type { DataColumn } from "@/components/lge-dashboard/types";
|
||||
import {API_DECIMAL_POINT, GAP_WORDING, VIEW_DECIMAL_POINT} from "@/const/lg-common.const";
|
||||
import {BANNER_GROUP, BANNER_KEYS, type BannerGroupDefinition, type BannerGroupNode, flattenBannerGroupKeys} from "@/const/lg-banner.const";
|
||||
import {PRODUCT_KEYS} from "@/const/lg-product.const";
|
||||
import {CATEGORY_PAGE_FIELDS} from "@/config/lg-page.config";
|
||||
import {formatNumber} from "@/lib/utils";
|
||||
import {nextApi} from "@/lib/http-client";
|
||||
import {CategoryFilterValue} from "@/components/layout/CategoryFilter";
|
||||
|
||||
export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "").includes("사례수");
|
||||
|
||||
export const isHasCountRow = (raw: string) => raw.replace(/\s+/g, "").includes("보유대수");
|
||||
|
||||
export const isCagrRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("CAGR");
|
||||
|
||||
export const isGapRow = (raw: string) => raw.replace(/\s+/g, "").toUpperCase().includes("GAP");
|
||||
|
||||
/**
|
||||
* Row Label을 표시용 텍스트로 포맷팅합니다.
|
||||
* - "사례수" -> "(사례수)"
|
||||
* - "gap" -> "전년 대비 GAP(%)"
|
||||
* - "gap" -> "전년 대비 GAP(%p)"
|
||||
* - "CAGR" -> "CAGR(%)"
|
||||
* - "24" -> "24년"
|
||||
* - "보급율" -> "보급율(%)"
|
||||
@@ -18,7 +36,7 @@ export function formatRowLabel(
|
||||
label: string,
|
||||
options?: {
|
||||
convertSample?: boolean; // "사례수" -> "(사례수)" (기본값: true)
|
||||
convertGap?: boolean; // "gap" -> "전년 대비 GAP(%)" (기본값: true)
|
||||
convertGap?: boolean; // "gap" -> "전년 대비 GAP(%p)" (기본값: true)
|
||||
convertCagr?: boolean; // "CAGR" -> "CAGR(%)" (기본값: true)
|
||||
convertYear?: boolean; // "24" -> "24년" (기본값: true)
|
||||
convertRate?: boolean; // "~율" -> "~율(%)" (기본값: true)
|
||||
@@ -37,17 +55,18 @@ export function formatRowLabel(
|
||||
const t = label.trim();
|
||||
|
||||
if (convertSample && t === "사례수") return "(사례수)";
|
||||
if (convertGap && t.toLowerCase() === "gap") return "전년 대비 GAP(%)";
|
||||
if (convertGap && t.toLowerCase() === "gap") return GAP_WORDING;
|
||||
if (convertCagr && t.toUpperCase() === "CAGR") return "CAGR(%)";
|
||||
if (convertYear && /^\d{4}$/.test(t)) return `${t.substring(2,4)}년`;
|
||||
if (convertYear && /^\d{2}$/.test(t)) return `${t}년`;
|
||||
if (convertRate && t.endsWith("율")) return `${t}(%)`;
|
||||
if (convertCount && t.includes("대수")) return `${t}(대)`;
|
||||
if (convertRate && t.endsWith("율")) return `${t.replaceAll('(%)','')}(%)`;
|
||||
if (convertCount && t.includes("대수")) return `${t.replaceAll('(대)','')}(대)`;
|
||||
|
||||
return t;
|
||||
}
|
||||
|
||||
export const wrapSampleRow = <T extends Record<string, unknown> & { rowLabel: string }>(
|
||||
rows: T[]
|
||||
rows: T[], replaceLabel: boolean = true
|
||||
): T[] => {
|
||||
return rows.map((r) => {
|
||||
if (!isSampleRow(r.rowLabel)) return r;
|
||||
@@ -57,11 +76,15 @@ export const wrapSampleRow = <T extends Record<string, unknown> & { rowLabel: st
|
||||
Object.entries(r).forEach(([k, v]) => {
|
||||
if (k == "year" || v == null) return;
|
||||
|
||||
if (typeof v === "number") {
|
||||
out[k] = `(${formatNumber(v)})`;
|
||||
if (
|
||||
typeof v === "number" ||
|
||||
(typeof v === "string" && v.trim() !== "" && !Number.isNaN(Number(v)))
|
||||
) {
|
||||
out[k] = `(${formatNumber(Number(v))})`;
|
||||
return;
|
||||
}
|
||||
|
||||
if(replaceLabel){
|
||||
if (typeof v === "string") {
|
||||
// 이미 괄호면 그대로
|
||||
out[k] = v.startsWith("(") && v.endsWith(")") ? v : `(${v})`;
|
||||
@@ -69,6 +92,7 @@ export const wrapSampleRow = <T extends Record<string, unknown> & { rowLabel: st
|
||||
}
|
||||
|
||||
out[k] = `(${String(v)})`;
|
||||
}
|
||||
});
|
||||
|
||||
return out as T;
|
||||
@@ -170,6 +194,9 @@ export function buildOverlayBarData<T extends { year: number; rowLabel: string }
|
||||
};
|
||||
}
|
||||
|
||||
const shouldExcludeLabel = (excludeRowLabels: string[], label: string) =>
|
||||
excludeRowLabels.some((el) => label.includes(el));
|
||||
|
||||
type Opts = {
|
||||
/** 기본: ["사례수", "gap"] 제외 */
|
||||
excludeRowLabels?: string[];
|
||||
@@ -179,7 +206,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}년`,
|
||||
@@ -188,25 +215,22 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
|
||||
|
||||
const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => Number(a) - Number(b));
|
||||
|
||||
// rowLabel 순서: 첫 연도 기준으로 고정(없으면 전체 unique)
|
||||
const baseYear = years[0];
|
||||
const baseLabels = rows
|
||||
.filter((r) => r.year === baseYear)
|
||||
.map((r) => r.rowLabel)
|
||||
.filter((l) => !excludeRowLabels.includes(l));
|
||||
.filter((l) => !shouldExcludeLabel(excludeRowLabels, l));
|
||||
|
||||
const labels =
|
||||
baseLabels.length > 0
|
||||
? baseLabels
|
||||
: Array.from(
|
||||
new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l)))
|
||||
);
|
||||
: Array.from(new Set(rows.map((r) => r.rowLabel).filter((l) => !shouldExcludeLabel(excludeRowLabels, l))));
|
||||
|
||||
// 빠른 조회용: year -> (rowLabel -> total)
|
||||
const map = new Map<string, Map<string, number>>();
|
||||
for (const y of years) map.set(y, new Map());
|
||||
|
||||
for (const r of rows) {
|
||||
if (excludeRowLabels.includes(r.rowLabel)) continue;
|
||||
if (shouldExcludeLabel(excludeRowLabels, r.rowLabel)) continue;
|
||||
map.get(r.year)?.set(r.rowLabel, Number(r.total ?? 0));
|
||||
}
|
||||
|
||||
@@ -215,13 +239,13 @@ export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {
|
||||
series: years.map((y) => ({
|
||||
name: yearLabel(y),
|
||||
data: labels.map((lbl) => map.get(y)?.get(lbl) ?? null),
|
||||
...(splitStackByYear ? { stack: String(y) } : {}), // 같은 stack이면 "연도끼리 스택"되어버리니 방지용
|
||||
...(splitStackByYear ? { stack: String(y) } : {}),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildRowLabelSeriesChartData(
|
||||
rows: ServerBannerRow[],
|
||||
rows: BannerRow[],
|
||||
opts: Opts = {}
|
||||
): ChartData {
|
||||
const {
|
||||
@@ -236,13 +260,13 @@ export function buildRowLabelSeriesChartData(
|
||||
const baseRowLabels = rows
|
||||
.filter((r) => r.year === baseYear)
|
||||
.map((r) => r.rowLabel)
|
||||
.filter((l) => !excludeRowLabels.includes(l));
|
||||
.filter((l) => !shouldExcludeLabel(excludeRowLabels, l));
|
||||
|
||||
const rowLabels =
|
||||
baseRowLabels.length > 0
|
||||
? baseRowLabels
|
||||
: Array.from(
|
||||
new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l)))
|
||||
new Set(rows.map((r) => r.rowLabel).filter((l) => !shouldExcludeLabel(excludeRowLabels, l)))
|
||||
);
|
||||
|
||||
// (year -> (rowLabel -> total)) 맵
|
||||
@@ -250,7 +274,7 @@ export function buildRowLabelSeriesChartData(
|
||||
for (const y of years) valueMap.set(y, new Map());
|
||||
|
||||
for (const r of rows) {
|
||||
if (excludeRowLabels.includes(r.rowLabel)) continue;
|
||||
if (shouldExcludeLabel(excludeRowLabels, r.rowLabel)) continue;
|
||||
valueMap.get(r.year)!.set(r.rowLabel, Number(r.total ?? 0));
|
||||
}
|
||||
|
||||
@@ -264,24 +288,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];
|
||||
@@ -294,3 +318,271 @@ export const buildGapRow = (
|
||||
}
|
||||
|
||||
export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP;
|
||||
|
||||
export function buildBannerGroupColumns<T extends Record<string, unknown>>(
|
||||
group: BannerGroupDefinition,
|
||||
keyLabelMap: Record<string, string>,
|
||||
options: {
|
||||
width?: number | string;
|
||||
numeric?: boolean;
|
||||
resolveLeafMeta?: (key: string, index: number, total: number) => {
|
||||
headerClassName?: string;
|
||||
cellClassName?: string;
|
||||
};
|
||||
} = {}
|
||||
): DataColumn<T>[] {
|
||||
const leafKeys = flattenBannerGroupKeys(group.children);
|
||||
let leafIndex = 0;
|
||||
|
||||
const visit = (nodes: readonly BannerGroupNode[]): DataColumn<T>[] =>
|
||||
nodes.map((node) => {
|
||||
if (node.type === "leaf") {
|
||||
const currentLeafIndex = leafIndex++;
|
||||
const meta = options.resolveLeafMeta?.(node.key, currentLeafIndex, leafKeys.length);
|
||||
|
||||
return {
|
||||
key: node.key as keyof T,
|
||||
header: keyLabelMap[node.key] ?? String(node.key),
|
||||
numeric: options.numeric,
|
||||
width: options.width,
|
||||
headerClassName: meta?.headerClassName,
|
||||
cellClassName: meta?.cellClassName,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
id: node.id,
|
||||
header: node.label,
|
||||
children: visit(node.children),
|
||||
};
|
||||
});
|
||||
|
||||
return visit(group.children);
|
||||
}
|
||||
|
||||
export const fetchProductStatistics = (req: StatisticsRequest) =>
|
||||
nextApi.post<ProductResponse>("/statistics/product", req);
|
||||
|
||||
export const fetchBannerStatistics = (req: StatisticsRequest) =>
|
||||
nextApi.post<BannerResponse>("/statistics/banner", req);
|
||||
|
||||
type FilterInput =
|
||||
| Record<string, unknown>
|
||||
| Map<string, unknown>
|
||||
| null
|
||||
| undefined;
|
||||
|
||||
export function normalizeFilterCondition(
|
||||
input: FilterInput,
|
||||
upToZero: boolean = true
|
||||
): Record<string, number[]> | undefined {
|
||||
if (!input) return undefined;
|
||||
|
||||
const entries =
|
||||
input instanceof Map ? Array.from(input.entries()) : Object.entries(input);
|
||||
|
||||
const out: Record<string, number[]> = {};
|
||||
|
||||
for (const [k, v] of entries) {
|
||||
if (!k || v == null) continue;
|
||||
|
||||
const nums: number[] = [];
|
||||
|
||||
const pushNum = (x: unknown) => {
|
||||
if (x == null) return;
|
||||
|
||||
const pushIfValid = (n: number) => {
|
||||
if (!Number.isFinite(n)) return;
|
||||
if (upToZero && n === 0) return; // upToZero=true일 때만 0 제외
|
||||
nums.push(n);
|
||||
};
|
||||
|
||||
if (typeof x === "number") {
|
||||
pushIfValid(x);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof x === "string") {
|
||||
const parts = x
|
||||
.split(/[,\|]/g)
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
for (const p of parts) {
|
||||
pushIfValid(Number(p));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (Array.isArray(v)) {
|
||||
for (const item of v) pushNum(item);
|
||||
} else {
|
||||
pushNum(v);
|
||||
}
|
||||
|
||||
if (nums.length > 0) out[k] = nums;
|
||||
}
|
||||
|
||||
return Object.keys(out).length ? out : undefined;
|
||||
}
|
||||
|
||||
export const buildCategoryFilter = (
|
||||
filterValue:CategoryFilterValue
|
||||
): Record<string, number[]> | undefined => {
|
||||
const out: Record<string, number[]> = {};
|
||||
const productCode = filterValue.product.split("#").at(-1);
|
||||
|
||||
if (productCode) {
|
||||
out["product"] = [Number(productCode)];
|
||||
}
|
||||
|
||||
return Object.keys(out).length ? out : undefined;
|
||||
}
|
||||
|
||||
const fixedDecimalPoint = (n: number, decimalPoint?: number): string => {
|
||||
decimalPoint ??= API_DECIMAL_POINT;
|
||||
return n.toFixed(decimalPoint);
|
||||
};
|
||||
|
||||
export const roundNumber = (num: number|null, decimalPoint?: number) => {
|
||||
if(num == null) return null;
|
||||
|
||||
decimalPoint ??= VIEW_DECIMAL_POINT;
|
||||
const factor = 10 ** decimalPoint;
|
||||
return Math.round(num * factor) / factor;
|
||||
};
|
||||
|
||||
export const calcGapProductRow = (after: ProductRow, before: ProductRow): ProductRow => {
|
||||
const out: ProductRow = {
|
||||
year: after?.year ?? "",
|
||||
rowLabel: "gap",
|
||||
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
|
||||
};
|
||||
for (const k of PRODUCT_KEYS) {
|
||||
const a = after? after[k] ?? "0" : "0";
|
||||
const b = before? before[k] ?? "0" : "0";
|
||||
out[k] = fixedDecimalPoint(Number(a) - Number(b));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
export const calcGapBannerRow = (after: BannerRow, before: BannerRow): BannerRow => {
|
||||
const out: BannerRow = {
|
||||
year: after?.year ?? "",
|
||||
rowLabel: "gap",
|
||||
total: fixedDecimalPoint(Number(after?.total ?? "0") - Number(before?.total ?? "0")),
|
||||
};
|
||||
for (const k of BANNER_KEYS) {
|
||||
const a = after? after[k] ?? "0" : "0";
|
||||
const b = before? before[k] ?? "0" : "0";
|
||||
out[k] = fixedDecimalPoint(Number(a) - Number(b));
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
const calcCagr = (after: number, before: number, years:number): number => {
|
||||
const power = Math.pow(after / before, 1 / years);
|
||||
const cagr = power - 1;
|
||||
const cagr100 = cagr * 100;
|
||||
|
||||
return cagr100;
|
||||
};
|
||||
|
||||
export const calcCagrRow = (after: ProductRow, before: ProductRow): ProductRow => {
|
||||
const years = 2; // 24 -> 26
|
||||
const out: ProductRow = {
|
||||
year: after?.year ?? "",
|
||||
rowLabel: "CAGR",
|
||||
total: "0"
|
||||
};
|
||||
|
||||
// total은 참고용으로만: (26/24) CAGR %
|
||||
out.total =
|
||||
fixedDecimalPoint((before?.total ?? "0") > "0" ? calcCagr(Number(after?.total ?? "0"), Number(before?.total ?? "0"), years) : 0, 1);
|
||||
|
||||
for (const k of PRODUCT_KEYS) {
|
||||
const vBefore = before? before[k] ?? "0" : "0";
|
||||
const vAfter = after? after[k] ?? "0" : "0";
|
||||
out[k] = fixedDecimalPoint(Number(vBefore) > 0 ? calcCagr(Number(vAfter), Number(vBefore), years) : 0, 1);
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
|
||||
export const makeTotalBasePct = (t:number|string, f:number|string):number => {
|
||||
return Number(t) > 0 ? (Number(f) * 100) / Number(t) : 0;
|
||||
}
|
||||
|
||||
export const calcTotalBaseRow = (label:string, totalRow: ProductRow, targetRow: ProductRow): ProductRow => {
|
||||
const out: ProductRow = {
|
||||
year: targetRow?.year ?? "",
|
||||
//rowLabel: `**조사 년도 ${label} 중 자사제품 비율`,
|
||||
rowLabel: `**자사제품 비율`,
|
||||
total: fixedDecimalPoint(makeTotalBasePct(totalRow.total, targetRow.total))
|
||||
};
|
||||
|
||||
for (const k of PRODUCT_KEYS) {
|
||||
const t = totalRow? totalRow[k] ?? "0" : "0";
|
||||
const f = targetRow? targetRow[k] ?? "0" : "0";
|
||||
out[k] = fixedDecimalPoint(makeTotalBasePct(t, f));
|
||||
}
|
||||
return out;
|
||||
|
||||
}
|
||||
|
||||
export const withGapRow = <T>(
|
||||
rows: T[],
|
||||
calcGapRow: (last: T, secondLast: T) => T,
|
||||
lastIndex: number,
|
||||
secondLastIndex: number,
|
||||
): T[] => {
|
||||
const last = rows.at(lastIndex);
|
||||
const secondLast = rows.at(secondLastIndex);
|
||||
if (!last || !secondLast) return rows;
|
||||
return [calcGapRow(last, secondLast), ...rows];
|
||||
}
|
||||
|
||||
export const withCagrRow = <T>(
|
||||
rows: T[],
|
||||
calcCagrRow: (last: T, first: T) => T,
|
||||
lastIndex: number,
|
||||
firstIndex: number,
|
||||
): T[] => {
|
||||
const first = rows.at(firstIndex);
|
||||
const last = rows.at(lastIndex);
|
||||
if (!first || !last) return rows;
|
||||
return [...rows, calcCagrRow(last, first)];
|
||||
}
|
||||
|
||||
export const withTotalBaseRow = <T>(
|
||||
label:string,
|
||||
totalRows: T[],
|
||||
targetRows: T[],
|
||||
calcTotalBaseRow: (label:string, total: T, target: T) => T
|
||||
): T[] => {
|
||||
const totalRow = totalRows.at(-1);
|
||||
const targetRow = targetRows.at(-1);
|
||||
|
||||
if (!totalRow || !targetRow) return targetRows;
|
||||
|
||||
const totalBaseRow = calcTotalBaseRow(label, totalRow, targetRow);
|
||||
return targetRows.length === 0 ? [totalBaseRow] : [targetRows[0], totalBaseRow, ...targetRows.slice(1)];
|
||||
}
|
||||
|
||||
const renderKey = (tpl: string, keyBase: string) => tpl.replaceAll("${keyBase}", keyBase.toLowerCase());
|
||||
|
||||
export const buildPageModeConfig = (
|
||||
filterValue: CategoryFilterValue
|
||||
):BuildPageModeConfigResult => {
|
||||
const fields = (CATEGORY_PAGE_FIELDS[filterValue.target.value] ?? [])
|
||||
.filter((f) => !!f.qidByMode[filterValue.type.value])
|
||||
.map((f) => ({
|
||||
...f,
|
||||
requestKeyResolved: renderKey(f.requestKey, filterValue.type.value),
|
||||
qid: f.qidByMode[filterValue.type.value]!,
|
||||
}));
|
||||
|
||||
const variableIdMap = Object.fromEntries(fields.map((f) => [f.requestKeyResolved, f.qid])) as Record<string, string>;
|
||||
|
||||
return { fields, variableIdMap };
|
||||
};
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
// exportDashboardExcel.ts
|
||||
// exportDashboardExcel.ts
|
||||
"use client";
|
||||
|
||||
import {formatRowLabel, isSampleRow} from "@/lib/lg-dashboard";
|
||||
import {DataColumn} from "@/components/lge-dashboard";
|
||||
import { buildBannerGroupColumns, formatRowLabel } from "@/lib/lg-dashboard";
|
||||
import { DataColumn, GaugeColumn } from "@/components/lge-dashboard";
|
||||
import { buildHeaderRows, getLeafColumns, type TableColumnNode } from "@/components/lge-dashboard/table/core/table-core.helpers";
|
||||
import type { BannerGroupDefinition } from "@/const/lg-banner.const";
|
||||
|
||||
/**
|
||||
* 요구사항:
|
||||
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더(그룹 머지), (3) BANNER_GROUP 헤더(좌측 2칸 rowspan2 + 그룹 머지)
|
||||
* - Excel export (한 시트, 섹션 간 1행 띄움)
|
||||
* - 한 파일에 (1) PRODUCT_KEY_MAP 헤더, (2) LIFE_STAGE_COLUMNS 헤더, (3) BANNER_GROUP 헤더를 함께 지원
|
||||
* - Excel export는 한 시트에 여러 섹션을 순서대로 기록
|
||||
* - 헤더 스타일:
|
||||
* group: background = --lg-gray-400
|
||||
* header: background = --lg-gray-600
|
||||
@@ -257,7 +259,7 @@ function fitColumns(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoF
|
||||
const w = estimateWidth(text, cell, o); // width in "excel-char-like units"
|
||||
|
||||
if (mi && mi.colSpan > 1) {
|
||||
// 머지된 텍스트는 span만큼 나눠서 분배(머지 텍스트 때문에 한 컬럼이 과대해지는 현상 방지)
|
||||
// 머지된 텍스트는 span만큼 나눠서 분배(한 컬럼 폭이 과대해지는 현상 방지)
|
||||
const perCol = w / mi.colSpan;
|
||||
for (let c = mi.leftCol; c <= mi.rightCol; c++) {
|
||||
widths[c] = Math.max(widths[c], perCol);
|
||||
@@ -269,8 +271,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -300,7 +301,7 @@ function fitRows(ws: any, mergeMap: Map<string, MergeInfo>, o: Required<AutoFitO
|
||||
? sumColumnWidth(ws, mi.leftCol, mi.rightCol, o)
|
||||
: getColumnWidth(ws, colNumber, o);
|
||||
|
||||
// 각 라인 별로 "줄바꿈이 몇 줄로 늘어나는지" 근사
|
||||
// 각 라인별로 줄바꿈이 몇 줄로 늘어나는지 근사
|
||||
let cellLines = 0;
|
||||
for (const line of explicitLines) {
|
||||
const lineW = estimateWidth(line, cell, o);
|
||||
@@ -327,11 +328,11 @@ function estimateWidth(text: string, cell: any, o: Required<AutoFitOpt>) {
|
||||
|
||||
if (o.useCanvasMeasure && typeof document !== "undefined") {
|
||||
const px = measureTextPx(maxLine, cell);
|
||||
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도가 근사치로 많이 씀
|
||||
// Excel column width 단위는 폰트마다 다르지만 Calibri 11 기준으로 px/7 정도를 사용
|
||||
return px / 7;
|
||||
}
|
||||
|
||||
// canvas 못 쓰는 환경(또는 성능 이유) -> 문자폭 가중치 근사
|
||||
// canvas를 못 쓰는 환경이면 문자 폭 가중치로 근사
|
||||
return estimateByCharWeight(maxLine);
|
||||
}
|
||||
|
||||
@@ -351,7 +352,7 @@ function getMeasureCanvas() {
|
||||
return __canvas;
|
||||
}
|
||||
|
||||
// 한글/중국어/일본어 등 wide char 가중치 + 숫자/영문 가중치
|
||||
// 한글/CJK wide char 가중치 + 숫자/영문 가중치
|
||||
function estimateByCharWeight(s: string) {
|
||||
let w = 0;
|
||||
for (const ch of s) {
|
||||
@@ -442,7 +443,7 @@ function buildMergeMap(ws: any) {
|
||||
const merges = ws?._merges;
|
||||
if (!merges) return map;
|
||||
|
||||
// ws._merges: Map<string, any> 형태인 경우가 많음. key가 "A1:C1" 같은 range
|
||||
// ws._merges: Map<string, any> 형태인 경우가 많고 key는 "A1:C1" 같은 range
|
||||
const keys: string[] =
|
||||
merges instanceof Map ? Array.from(merges.keys()) : Object.keys(merges);
|
||||
|
||||
@@ -460,7 +461,7 @@ function buildMergeMap(ws: any) {
|
||||
return map;
|
||||
}
|
||||
|
||||
// "A1:C3" -> 좌표
|
||||
// "A1:C3" -> 醫뚰몴
|
||||
function parseRange(range: string): Omit<MergeInfo, "colSpan"> | null {
|
||||
const parts = range.split(":");
|
||||
if (parts.length !== 2) return null;
|
||||
@@ -508,7 +509,7 @@ function colToLetters(col: number) {
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 3) 헤더 빌더 3종
|
||||
* 3) 헤더 빌더
|
||||
* ========================================================= */
|
||||
|
||||
/**
|
||||
@@ -518,12 +519,16 @@ function colToLetters(col: number) {
|
||||
*/
|
||||
export function buildHeader_ProductKeyMap(
|
||||
productKeyMap: Record<string, string>,
|
||||
sampleHeadKey? :string,
|
||||
rowHeadKey = "rowLabel"
|
||||
): HeaderBlock {
|
||||
const entries = typedEntries(productKeyMap);
|
||||
|
||||
const headerRow: HeaderCell[] = [
|
||||
{ text: "", styleKey: "header", align: "center" },
|
||||
...(sampleHeadKey
|
||||
? [{ text: "사례수", styleKey: "header", align: "center" } as const]
|
||||
: []),
|
||||
...entries.map(([, label]) => ({
|
||||
text: String(label),
|
||||
styleKey: "header" as const,
|
||||
@@ -531,180 +536,63 @@ export function buildHeader_ProductKeyMap(
|
||||
})),
|
||||
];
|
||||
|
||||
const leafKeys = [rowHeadKey, ...entries.map(([k]) => String(k))];
|
||||
|
||||
const leafKeys = [rowHeadKey, ...(sampleHeadKey? [sampleHeadKey]: []), ...entries.map(([k]) => String(k))];
|
||||
return { headerRows: [headerRow], leafKeys, totalCols: headerRow.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* (2) LIFE_STAGE_COLUMNS:
|
||||
* - 1행: group 머지(같은 group 연속 구간)
|
||||
* - 2행: header 텍스트
|
||||
*
|
||||
* group 없는 컬럼은 1행에 빈 셀(그룹 스타일) 1칸 채움
|
||||
* - 트리 기반 컬럼에서 header row를 계산
|
||||
* - HTML 테이블과 동일한 merge 구조를 Excel에 적용
|
||||
*/
|
||||
export type GaugeColumn = {
|
||||
key: string;
|
||||
header: string;
|
||||
rowHead?: boolean;
|
||||
group?: string;
|
||||
align?: "left" | "center" | "right";
|
||||
};
|
||||
function buildHeaderBlockFromColumns<T>(cols: TableColumnNode<T>[]): HeaderBlock {
|
||||
const headerRows = buildHeaderRows(cols).map((row) =>
|
||||
row.map((cell) => ({
|
||||
text: cell.label,
|
||||
styleKey: (cell.isLeaf ? "header" : "group") as HeaderStyleKey,
|
||||
rowSpan: cell.rowSpan,
|
||||
colSpan: cell.colSpan,
|
||||
align: "center" as const,
|
||||
}))
|
||||
);
|
||||
|
||||
export function buildHeader_LifeStageColumns(cols: GaugeColumn[]): HeaderBlock {
|
||||
const row1: HeaderCell[] = [];
|
||||
const row2: HeaderCell[] = [];
|
||||
const leafKeys = cols.map((c) => c.key);
|
||||
const leafKeys = getLeafColumns(cols).map((column) => String(column.key));
|
||||
return { headerRows, leafKeys, totalCols: leafKeys.length };
|
||||
}
|
||||
|
||||
let i = 0;
|
||||
while (i < cols.length) {
|
||||
const c = cols[i];
|
||||
const g = c.group;
|
||||
|
||||
if (!g) {
|
||||
row1.push({ text: "", styleKey: "group", colSpan: 1, align: "center" });
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
let j = i + 1;
|
||||
while (j < cols.length && cols[j].group === g) j += 1;
|
||||
const span = j - i;
|
||||
|
||||
row1.push({ text: g, styleKey: "group", colSpan: span, align: "center" });
|
||||
i = j;
|
||||
}
|
||||
|
||||
for (const c of cols) {
|
||||
row2.push({ text: c.header ?? "", styleKey: "header", colSpan: 1, align: "center" });
|
||||
}
|
||||
|
||||
return { headerRows: [row1, row2], leafKeys, totalCols: cols.length };
|
||||
export function buildHeader_LifeStageColumns<T>(cols: GaugeColumn<T>[]): HeaderBlock {
|
||||
return buildHeaderBlockFromColumns(cols);
|
||||
}
|
||||
|
||||
export function buildHeader_DataColumn<T>(cols: DataColumn<T>[]): HeaderBlock {
|
||||
const row1: HeaderCell[] = [];
|
||||
const row2: HeaderCell[] = [];
|
||||
|
||||
const leafKeys = cols.map((c) => String(c.key));
|
||||
|
||||
// 1행: 그룹 머지 / rowspan 처리
|
||||
let i = 0;
|
||||
while (i < cols.length) {
|
||||
const c = cols[i];
|
||||
const rs = c.headRowSpan ?? 1;
|
||||
|
||||
// (A) rowspan=2면: 1행에 header를 올리고(세로머지), 2행은 빈 칸(placeholder)
|
||||
if (rs === 2) {
|
||||
row1.push({
|
||||
text: c.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
rowSpan: 2,
|
||||
align: c.align ?? "center",
|
||||
});
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// (B) 그룹 구간 처리
|
||||
const gKey = c.groupKey ?? c.group;
|
||||
if (gKey) {
|
||||
let j = i + 1;
|
||||
while (j < cols.length) {
|
||||
const cj = cols[j];
|
||||
const rsj = cj.headRowSpan ?? 1;
|
||||
const gKeyJ = cj.groupKey ?? cj.group;
|
||||
|
||||
// rowspan=2가 섞이면 그룹 머지 끊음(안정성)
|
||||
if (rsj === 2) break;
|
||||
if (gKeyJ !== gKey) break;
|
||||
|
||||
j += 1;
|
||||
}
|
||||
|
||||
const span = j - i;
|
||||
|
||||
row1.push({
|
||||
text: c.group ?? "",
|
||||
styleKey: "group",
|
||||
colSpan: span,
|
||||
align: "center",
|
||||
});
|
||||
|
||||
// 2행: 그룹 구간의 각 컬럼 header
|
||||
for (let k = i; k < j; k++) {
|
||||
const ck = cols[k];
|
||||
row2.push({
|
||||
text: ck.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
align: ck.align ?? "center",
|
||||
});
|
||||
}
|
||||
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
|
||||
// (C) 그룹도 없고 rowspan도 아니면: 1행에 빈 group 셀 1개, 2행에 header
|
||||
row1.push({
|
||||
text: "",
|
||||
styleKey: "group",
|
||||
colSpan: 1,
|
||||
align: "center",
|
||||
});
|
||||
row2.push({
|
||||
text: c.header ?? "",
|
||||
styleKey: "header",
|
||||
colSpan: 1,
|
||||
align: c.align ?? "center",
|
||||
});
|
||||
i += 1;
|
||||
}
|
||||
|
||||
return {
|
||||
headerRows: [row1, row2],
|
||||
leafKeys,
|
||||
totalCols: cols.length,
|
||||
};
|
||||
return buildHeaderBlockFromColumns(cols);
|
||||
}
|
||||
|
||||
/**
|
||||
* (3) BANNER_GROUP + BANNER_KEY_MAP:
|
||||
* - A1: "" (rowspan2)
|
||||
* - B1: "전체" (rowspan2) key=total
|
||||
* - C1~: group(label) (colSpan = keys.length)
|
||||
* - C1~: group(label) (colSpan = keys.ts.length)
|
||||
* - 2행: 각 key의 라벨(BANNER_KEY_MAP[key])
|
||||
*/
|
||||
export function buildHeader_Banner<K extends string>(
|
||||
bannerGroup: Record<string, { label: string; keys: readonly K[] }>,
|
||||
bannerGroup: Record<string, BannerGroupDefinition>,
|
||||
bannerKeyMap: Record<K, string>,
|
||||
rowHeadKey = "rowLabel",
|
||||
totalKey = "total"
|
||||
): HeaderBlock {
|
||||
const groups = Object.values(bannerGroup);
|
||||
|
||||
const row1: HeaderCell[] = [
|
||||
{ text: "", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
|
||||
{ text: "전체", styleKey: "header", rowSpan: 2, colSpan: 1, align: "center" },
|
||||
const columns: DataColumn<Record<string, unknown>>[] = [
|
||||
{ key: rowHeadKey, header: "" },
|
||||
{ key: totalKey, header: "전체" },
|
||||
...Object.entries(bannerGroup).map(([groupKey, group]) => ({
|
||||
id: `banner-${groupKey}`,
|
||||
header: group.label,
|
||||
children: buildBannerGroupColumns<Record<string, unknown>>(group, bannerKeyMap),
|
||||
})),
|
||||
];
|
||||
|
||||
const row2: HeaderCell[] = [];
|
||||
const leafKeys: string[] = [rowHeadKey, totalKey];
|
||||
|
||||
for (const g of groups) {
|
||||
row1.push({ text: g.label, styleKey: "group", colSpan: g.keys.length, align: "center" });
|
||||
|
||||
for (const k of g.keys) {
|
||||
row2.push({ text: bannerKeyMap[k] ?? k, styleKey: "header", colSpan: 1, align: "center" });
|
||||
leafKeys.push(k);
|
||||
}
|
||||
}
|
||||
|
||||
const totalCols = 2 + groups.reduce((acc, g) => acc + g.keys.length, 0);
|
||||
return { headerRows: [row1, row2], leafKeys, totalCols };
|
||||
return buildHeaderBlockFromColumns(columns);
|
||||
}
|
||||
|
||||
/* =========================================================
|
||||
* 4) Export (one sheet, 섹션 간 1행 띄움)
|
||||
* ========================================================= */
|
||||
@@ -718,7 +606,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
|
||||
borderVar = "--lg-gray-300",
|
||||
} = opts;
|
||||
|
||||
// ExcelJS import (환경에 따라 min 빌드가 더 잘 먹는 경우가 있음)
|
||||
// ExcelJS import (환경에 따라 min 빌드가 더 잘 동작하는 경우가 있음)
|
||||
const ExcelJS = await import("exceljs");
|
||||
const wb = new ExcelJS.Workbook();
|
||||
const ws = wb.addWorksheet(sheetName);
|
||||
@@ -736,7 +624,7 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
|
||||
const gap = sec.rowGap ?? 1;
|
||||
const { header, rows } = sec;
|
||||
|
||||
// (선택) 섹션 타이틀
|
||||
// 섹션 타이틀
|
||||
if (sec.title) {
|
||||
const r = ws.getRow(rowCursor);
|
||||
const c = r.getCell(1);
|
||||
@@ -768,7 +656,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 +666,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 =
|
||||
@@ -829,3 +717,5 @@ export async function exportDashboardExcel<T extends Record<string, any>>(opts:
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -18,9 +18,3 @@ const createServerApi = async (rootUrl: string, defaultHeaders?: Record<string,
|
||||
export const createBackApi = () => {
|
||||
return createServerApi(serverEnv.API_BACK_SERVER);
|
||||
}
|
||||
|
||||
export const createKartApi = () => {
|
||||
return createServerApi(serverEnv.API_KART_SERVER, {
|
||||
"X-API-Key": serverEnv.KART_API_KEY,
|
||||
});
|
||||
};
|
||||
@@ -146,3 +146,15 @@ 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;
|
||||
};
|
||||
32
src/query/keys.ts
Normal file
32
src/query/keys.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import type {StatisticsRequest} from "@/types/lg.types";
|
||||
|
||||
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)])
|
||||
);
|
||||
};
|
||||
|
||||
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;
|
||||
28
src/query/statistics.ts
Normal file
28
src/query/statistics.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import {BannerResponse, ProductResponse, StatisticsRequest} from "@/types/lg.types";
|
||||
import {useQuery} from "@tanstack/react-query";
|
||||
import {bannerStatisticsKey, productStatisticsKey} from "@/query/keys";
|
||||
import {fetchBannerStatistics, fetchProductStatistics} from "@/lib/lg-dashboard";
|
||||
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,11 @@ export type LoginRequest = {
|
||||
userPw: string;
|
||||
};
|
||||
|
||||
export type LoginResponse = {
|
||||
accessToken: string;
|
||||
user: LoginUser;
|
||||
};
|
||||
|
||||
export type LoginUser = {
|
||||
userId: string;
|
||||
userName: string;
|
||||
|
||||
@@ -25,4 +25,4 @@ export type PageResponse<T> = {
|
||||
empty: boolean;
|
||||
}
|
||||
|
||||
export type SelectedMap = Record<string, string>;
|
||||
export type SelectedMap = Record<string, string[]>;
|
||||
@@ -3,9 +3,12 @@ export type FilterChild = {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export type TotalFilterItem = {
|
||||
export type FilterItem = {
|
||||
variable: string;
|
||||
variableName: string;
|
||||
};
|
||||
|
||||
export type TotalFilterItem = FilterItem & {
|
||||
children: FilterChild[];
|
||||
};
|
||||
|
||||
@@ -17,13 +20,13 @@ export enum CategoryTargetType {
|
||||
|
||||
export enum CategoryTargetData {
|
||||
PROFILE = 11,
|
||||
PROFILE_ALL = 10,
|
||||
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 +35,8 @@ export type CategoryTargetTypeItem = {
|
||||
}
|
||||
|
||||
export type TargetChild = {
|
||||
target: CategoryTargetData;
|
||||
label: string;
|
||||
value: CategoryTargetData;
|
||||
}
|
||||
|
||||
export type CategoryTargetItem = {
|
||||
@@ -1,49 +0,0 @@
|
||||
import {BANNER_GROUP, BANNER_KEY_MAP, PRODUCT_KEY_MAP, PRODUCTS_FILTER_ITEM} from "@/const/lgConst";
|
||||
|
||||
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 = {
|
||||
year: string;
|
||||
rowLabel: string;
|
||||
total: string;
|
||||
};
|
||||
|
||||
// { year, rowLabel, total, ...category }
|
||||
export type ServerProductRow = ServerBaseRow & Partial<Record<ProductKey, string>>;
|
||||
|
||||
// { year, rowLabel, total, ...banner }
|
||||
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
|
||||
export type ServerBannerRow = ServerBaseRow &
|
||||
Partial<Record<BannerKey, string>> & {
|
||||
[k: string]: string;
|
||||
};
|
||||
|
||||
export type LifeStageRow = Record<string, unknown> & {
|
||||
item: string;
|
||||
total: string;
|
||||
single: string;
|
||||
noKids: string;
|
||||
preschoolKids: string;
|
||||
schoolKids: string;
|
||||
adultKids: string;
|
||||
independentSenior: string;
|
||||
};
|
||||
|
||||
export type LifeStageGroup = {
|
||||
title: string;
|
||||
rows: LifeStageRow[]
|
||||
}
|
||||
|
||||
export type BannerGroupKey = keyof typeof BANNER_GROUP;
|
||||
|
||||
export type CategoryChartMode = "stack" | "reverseStack" | "horizontal";
|
||||
|
||||
export type PageData<T> = {
|
||||
title: string;
|
||||
chartMode: CategoryChartMode;
|
||||
data: T[];
|
||||
chartHeight?: number;
|
||||
chartWidth?: number;
|
||||
};
|
||||
112
src/types/lg.types.ts
Normal file
112
src/types/lg.types.ts
Normal file
@@ -0,0 +1,112 @@
|
||||
import {BANNER_GROUP} from "@/const/lg-banner.const";
|
||||
import {BANNER_KEY_MAP, PRODUCT_KEY_MAP} from "@/const/lg-schema.const";
|
||||
import {PRODUCTS_FILTER_ITEM} from "@/const/lg-product.const";
|
||||
import {CategoryTargetType} from "@/types/filter.types";
|
||||
import {EChartsOption} from "echarts";
|
||||
|
||||
export type ProductKey = keyof typeof PRODUCT_KEY_MAP;
|
||||
export type BannerKey = keyof typeof BANNER_KEY_MAP;
|
||||
export type ProductsFilterItem = (typeof PRODUCTS_FILTER_ITEM)[number];
|
||||
|
||||
export type BaseRow = {
|
||||
year: string;
|
||||
rowLabel: string;
|
||||
total: string;
|
||||
};
|
||||
|
||||
// { year, rowLabel, total, ...category }
|
||||
export type ProductRow = BaseRow & Partial<{sample: string;}> & Partial<Record<ProductKey, string>>;
|
||||
|
||||
// { year, rowLabel, total, ...banner }
|
||||
// (배너는 기본 41개 키 + 차트별 추가 키가 생길 수 있으니 확장 허용)
|
||||
export type BannerRow = BaseRow &
|
||||
Partial<Record<BannerKey, string>> &
|
||||
Record<Exclude<string, keyof BaseRow>, string>;
|
||||
|
||||
export type ProductResponse = {
|
||||
statisticsDataMap : Record<string, Array<ProductRow>>;
|
||||
};
|
||||
|
||||
export type BannerResponse = {
|
||||
statisticsDataMap : Record<string, Array<BannerRow>>;
|
||||
};
|
||||
|
||||
export type StatisticsRequestOption = {
|
||||
// 캐시 사용 여부
|
||||
useCache?: boolean; // default: true
|
||||
|
||||
// 마지막 연도만 조회
|
||||
lastYear?: boolean; // default: false
|
||||
|
||||
// 소수점 자리수
|
||||
decimalPoint?: number; // default: LgePenetrationConst.DECIMAL_POINT
|
||||
};
|
||||
|
||||
export type StatisticsRequest = {
|
||||
// 변수 ID 맵 (Key: 요청 Key, Value: 변수 ID)
|
||||
variableIdMap: Record<string, string>;
|
||||
|
||||
// 배너 ID 배열 (1단 배너, 옆으로 붙이기)
|
||||
bannerIdList?: string[];
|
||||
|
||||
// 필터 정보
|
||||
// Key: 필터 키, Value: 필터 값 목록
|
||||
filterCondition?: Record<string, number[]>;
|
||||
|
||||
// 요청 옵션
|
||||
option?: StatisticsRequestOption; // default: { useCache: true, lastYear: false, decimalPoint: ... }
|
||||
};
|
||||
|
||||
export type LifeStageRow = Record<string, unknown> & {
|
||||
item: string;
|
||||
total: string;
|
||||
"KLIFEstAGE#1": string;
|
||||
"KLIFEstAGE#2": string;
|
||||
"KLIFEstAGE#3": string;
|
||||
"KLIFEstAGE#4": string;
|
||||
"KLIFEstAGE#5": string;
|
||||
"KLIFEstAGE#6": string;
|
||||
"KLIFEstAGE#7": string;
|
||||
"KLIFEstAGE#8": string;
|
||||
};
|
||||
|
||||
export type LifeStageGroup = {
|
||||
title: string;
|
||||
rows: LifeStageRow[]
|
||||
}
|
||||
|
||||
export type BannerGroupKey = keyof typeof BANNER_GROUP;
|
||||
|
||||
export type CategoryChartMode = "none" | "stack" | "reverseStack" | "horizontal";
|
||||
|
||||
export type PageData<T> = {
|
||||
title: string;
|
||||
surveyTitle: string;
|
||||
chartMode: CategoryChartMode;
|
||||
chartLegend?: LegendOption;
|
||||
chartTopMargin?:number;
|
||||
chartHeight?: number | string;
|
||||
chartWidth?: number;
|
||||
data: T[];
|
||||
};
|
||||
|
||||
export type LegendOption = EChartsOption["legend"];
|
||||
|
||||
export type CategoryFieldSpec = {
|
||||
title: string | Record<CategoryTargetType, string>;
|
||||
requestKey: string;
|
||||
chartMode:CategoryChartMode;
|
||||
chartLegend?: LegendOption;
|
||||
chartTopMargin?:number;
|
||||
qidByMode: Partial<Record<CategoryTargetType, string>>; // mode별 qid (없으면 숨김/요청 제외)
|
||||
};
|
||||
|
||||
export type CategoryResolvedField = CategoryFieldSpec & {
|
||||
requestKeyResolved: string;
|
||||
qid: string;
|
||||
};
|
||||
|
||||
export type BuildPageModeConfigResult = {
|
||||
fields: CategoryResolvedField[];
|
||||
variableIdMap: Record<string, string>;
|
||||
};
|
||||
Reference in New Issue
Block a user