From 6f8e09bcf3734d84e388339cbae3382e781be025 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 2 Feb 2026 11:32:50 +0900 Subject: [PATCH] =?UTF-8?q?260202=5F01=5FENH:=20route=20=EA=B5=AC=EC=A1=B0?= =?UTF-8?q?=20=EC=B4=88=EC=B0=BD=EA=B8=B0=20=EA=B8=B0=ED=9A=8D=EC=9C=BC?= =?UTF-8?q?=EB=A1=9C=20=EB=8B=A4=EC=8B=9C=20=EB=B3=80=EA=B2=BD=20=EB=B0=8F?= =?UTF-8?q?=20Category=20=EB=B3=84=20=ED=95=98=EC=9C=84=20=ED=8E=98?= =?UTF-8?q?=EC=9D=B4=EC=A7=80=EC=97=90=20=EC=83=98=ED=94=8C=20=EB=8D=B0?= =?UTF-8?q?=EC=9D=B4=ED=84=B0=20=EB=AA=A8=EB=91=90=20=EC=A0=81=EC=9A=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- .../(main)/category/[category]/brand/page.tsx | 12 - .../[category]/ownership-path/page.tsx | 12 - .../[category]/penetration-change/page.tsx | 12 - .../category/[category]/profile/page.tsx | 12 - .../[category]/purchase-behavior/page.tsx | 12 - .../[category]/purchase-channel/page.tsx | 12 - .../[category]/purchase-format/page.tsx | 12 - .../category/[category]/type-spec/page.tsx | 12 - .../(main)/category/air-solution/page.tsx | 7 + .../(main)/category/ha-kitchen/page.tsx | 7 + .../(main)/category/ha-living/page.tsx | 7 + .../(main)/category/ms-digital/page.tsx | 7 + .../(main)/total/lg-penetration/page.tsx | 14 +- .../(pages)/(main)/total/lg-purchase/page.tsx | 12 +- .../(pages)/(main)/total/penetration/page.tsx | 12 +- .../(pages)/(main)/total/purchase/page.tsx | 12 +- src/app/globals.css | 18 +- src/components/layout/CategoryFilter.tsx | 1 - src/components/layout/LayoutFilterContext.tsx | 10 +- src/components/layout/MainLayout.tsx | 111 +++++--- .../lge-dashboard/BannerButtons.tsx | 14 +- src/components/lge-dashboard/BaseEChart.tsx | 3 +- .../lge-dashboard/chart/GroupedOverlayBar.tsx | 9 +- .../lge-dashboard/chart/GroupedStackBar.tsx | 21 +- .../lge-dashboard/chart/HorizontalBar.tsx | 31 +- .../lge-dashboard/chart/StackBar.tsx | 109 ++++--- .../lge-dashboard/chart/VerticalBar.tsx | 31 +- src/components/lge-dashboard/color.ts | 2 + .../lge-dashboard/combo/BannerSummary.tsx | 162 +++++++++++ .../lge-dashboard/combo/CategoryByData.tsx | 134 +++++++++ .../lge-dashboard/combo/LeftChartTable.tsx | 23 +- .../{sub-page => combo}/LifeStageDiv.tsx | 6 +- .../lge-dashboard/combo/TopChartTable.tsx | 23 +- src/components/lge-dashboard/index.ts | 2 +- .../lge-dashboard/sub-page/CategoryByData.tsx | 65 ----- .../lge-dashboard/sub-page/CategoryPage.tsx | 48 ++++ .../sub-page/category-page/Brand.tsx | 62 ++++ .../sub-page/category-page/OwnershipPath.tsx | 34 +++ .../sub-page/category-page/PaymentMethod.tsx | 33 +++ .../category-page/PenetrationChange.tsx | 24 ++ .../sub-page/category-page/Profile.tsx | 42 +++ .../category-page/PurchaseBehavior.tsx | 34 +++ .../category-page/PurchaseChannel.tsx | 38 +++ .../sub-page/category-page/TypeSpec.tsx | 37 +++ .../lge-dashboard/table/DataTable.tsx | 54 ++-- .../lge-dashboard/table/GaugeTable.tsx | 13 +- src/components/lge-dashboard/types.ts | 1 + src/config/filter.data.ts | 37 +-- src/config/filter.types.ts | 2 +- src/config/menu.data.ts | 2 +- src/config/sample.data.ts | 35 ++- src/const/chartConst.ts | 139 +++++++++ src/const/lgConst.ts | 59 +++- src/hooks/useStorage.ts | 6 +- src/lib/chart-options.ts | 232 +++++++++++++++ src/lib/lg-dashboard.ts | 269 ++++++++++++++++++ src/lib/utils.ts | 45 ++- src/store/storage/storage-keys.ts | 2 + src/types/lg.ts | 15 +- 60 files changed, 1750 insertions(+), 464 deletions(-) delete mode 100644 src/app/(pages)/(main)/category/[category]/brand/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/ownership-path/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/penetration-change/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/profile/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/purchase-behavior/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/purchase-channel/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/purchase-format/page.tsx delete mode 100644 src/app/(pages)/(main)/category/[category]/type-spec/page.tsx create mode 100644 src/app/(pages)/(main)/category/air-solution/page.tsx create mode 100644 src/app/(pages)/(main)/category/ha-kitchen/page.tsx create mode 100644 src/app/(pages)/(main)/category/ha-living/page.tsx create mode 100644 src/app/(pages)/(main)/category/ms-digital/page.tsx create mode 100644 src/components/lge-dashboard/combo/BannerSummary.tsx create mode 100644 src/components/lge-dashboard/combo/CategoryByData.tsx rename src/components/lge-dashboard/{sub-page => combo}/LifeStageDiv.tsx (93%) delete mode 100644 src/components/lge-dashboard/sub-page/CategoryByData.tsx create mode 100644 src/components/lge-dashboard/sub-page/CategoryPage.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/Brand.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/OwnershipPath.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/PaymentMethod.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/PenetrationChange.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/Profile.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/PurchaseBehavior.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/PurchaseChannel.tsx create mode 100644 src/components/lge-dashboard/sub-page/category-page/TypeSpec.tsx create mode 100644 src/const/chartConst.ts create mode 100644 src/lib/chart-options.ts create mode 100644 src/lib/lg-dashboard.ts diff --git a/README.md b/README.md index e215bc4..b63573d 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ bun dev Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. -You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. +You can start editing the page by modifying `app/Profile.tsx`. The page auto-updates as you edit the file. This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. diff --git a/src/app/(pages)/(main)/category/[category]/brand/page.tsx b/src/app/(pages)/(main)/category/[category]/brand/page.tsx deleted file mode 100644 index ce8859f..0000000 --- a/src/app/(pages)/(main)/category/[category]/brand/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const BrandPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
Brand
; -} - -export default BrandPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/ownership-path/page.tsx b/src/app/(pages)/(main)/category/[category]/ownership-path/page.tsx deleted file mode 100644 index a48bea3..0000000 --- a/src/app/(pages)/(main)/category/[category]/ownership-path/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const OwnershipPathPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
ownership path
; -}; - -export default OwnershipPathPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/penetration-change/page.tsx b/src/app/(pages)/(main)/category/[category]/penetration-change/page.tsx deleted file mode 100644 index 6dea644..0000000 --- a/src/app/(pages)/(main)/category/[category]/penetration-change/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const PenetrationChangePage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
PenetrationChange
-} - -export default PenetrationChangePage \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/profile/page.tsx b/src/app/(pages)/(main)/category/[category]/profile/page.tsx deleted file mode 100644 index 3e655a9..0000000 --- a/src/app/(pages)/(main)/category/[category]/profile/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const ProfilePage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
Profile
-} - -export default ProfilePage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/purchase-behavior/page.tsx b/src/app/(pages)/(main)/category/[category]/purchase-behavior/page.tsx deleted file mode 100644 index e5780d9..0000000 --- a/src/app/(pages)/(main)/category/[category]/purchase-behavior/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const PurchaseBehaviorPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
PurchaseBehavior
; -}; - -export default PurchaseBehaviorPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/purchase-channel/page.tsx b/src/app/(pages)/(main)/category/[category]/purchase-channel/page.tsx deleted file mode 100644 index 19290b8..0000000 --- a/src/app/(pages)/(main)/category/[category]/purchase-channel/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const PurchaseChannelPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
PurchaseChannel
; -}; - -export default PurchaseChannelPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/purchase-format/page.tsx b/src/app/(pages)/(main)/category/[category]/purchase-format/page.tsx deleted file mode 100644 index df262f5..0000000 --- a/src/app/(pages)/(main)/category/[category]/purchase-format/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const PurchaseFormatPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
PurchaseFormat
-} - -export default PurchaseFormatPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/[category]/type-spec/page.tsx b/src/app/(pages)/(main)/category/[category]/type-spec/page.tsx deleted file mode 100644 index 2997be4..0000000 --- a/src/app/(pages)/(main)/category/[category]/type-spec/page.tsx +++ /dev/null @@ -1,12 +0,0 @@ -'use client' - -import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; - -const TypeSpecPage = () => { - const { categoryValue } = useLayoutFilter(); - console.log(categoryValue); - - return
TypeSpec
-} - -export default TypeSpecPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/air-solution/page.tsx b/src/app/(pages)/(main)/category/air-solution/page.tsx new file mode 100644 index 0000000..e90a8c3 --- /dev/null +++ b/src/app/(pages)/(main)/category/air-solution/page.tsx @@ -0,0 +1,7 @@ +import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage"; + +const AirSolutionPage = () => { + return +} + +export default AirSolutionPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/ha-kitchen/page.tsx b/src/app/(pages)/(main)/category/ha-kitchen/page.tsx new file mode 100644 index 0000000..dd12a10 --- /dev/null +++ b/src/app/(pages)/(main)/category/ha-kitchen/page.tsx @@ -0,0 +1,7 @@ +import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage"; + +const HaKitchenPage = () => { + return +} + +export default HaKitchenPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/ha-living/page.tsx b/src/app/(pages)/(main)/category/ha-living/page.tsx new file mode 100644 index 0000000..95f1910 --- /dev/null +++ b/src/app/(pages)/(main)/category/ha-living/page.tsx @@ -0,0 +1,7 @@ +import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage"; + +const HaLivingPage = () => { + return +} + +export default HaLivingPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/category/ms-digital/page.tsx b/src/app/(pages)/(main)/category/ms-digital/page.tsx new file mode 100644 index 0000000..e736d99 --- /dev/null +++ b/src/app/(pages)/(main)/category/ms-digital/page.tsx @@ -0,0 +1,7 @@ +import CategoryPage from "@/components/lge-dashboard/sub-page/CategoryPage"; + +const MsDigitalPage = () => { + return +} + +export default MsDigitalPage; \ No newline at end of file diff --git a/src/app/(pages)/(main)/total/lg-penetration/page.tsx b/src/app/(pages)/(main)/total/lg-penetration/page.tsx index c0f007e..8bd8db7 100644 --- a/src/app/(pages)/(main)/total/lg-penetration/page.tsx +++ b/src/app/(pages)/(main)/total/lg-penetration/page.tsx @@ -10,20 +10,16 @@ import { apiOwnShareOfTotalPenetration, apiTrendCategories } from "@/config/sample.data"; -import LifeStageDiv from "@/components/lge-dashboard/sub-page/LifeStageDiv"; +import LifeStageDiv from "@/components/lge-dashboard/combo/LifeStageDiv"; import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {formatRowLabel} from "@/lib/lg-dashboard"; const LGPenetrationPage = () => { - const { totalValue } = useLayoutFilter(); - console.log(totalValue); - - const displayRowLabel = (i:number, rowLabel: string) => { - if (rowLabel === "gap") return "전년 대비 GAP(%)"; - return rowLabel; - }; + const { isTotal, filterValue } = useLayoutFilter(); + console.log(filterValue); const productTableRows: TopChartTableRow[] = apiOwnShareOfTotalPenetration.map((row, i) => ({ - label: displayRowLabel(i, row.rowLabel), + label: formatRowLabel(row.rowLabel), values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null), })); diff --git a/src/app/(pages)/(main)/total/lg-purchase/page.tsx b/src/app/(pages)/(main)/total/lg-purchase/page.tsx index 1c03dc8..0196d53 100644 --- a/src/app/(pages)/(main)/total/lg-purchase/page.tsx +++ b/src/app/(pages)/(main)/total/lg-purchase/page.tsx @@ -11,18 +11,14 @@ import { } from "@/components/lge-dashboard"; import { apiOwnShareOfTotalPurchase, apiTrendBuy} from "@/config/sample.data"; import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {formatRowLabel} from "@/lib/lg-dashboard"; const LGPurchasePage = () => { - const { totalValue } = useLayoutFilter(); - console.log(totalValue); - - const displayRowLabel = (i:number, rowLabel: string) => { - if (rowLabel === "gap") return "전년 대비 GAP(%)"; - return rowLabel; - }; + const { isTotal, filterValue } = useLayoutFilter(); + console.log(filterValue); const purchaseTableRows: TopChartTableRow[] = apiOwnShareOfTotalPurchase.map((row, i) => ({ - label: displayRowLabel(i, row.rowLabel), + label: formatRowLabel(row.rowLabel), values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null), })); diff --git a/src/app/(pages)/(main)/total/penetration/page.tsx b/src/app/(pages)/(main)/total/penetration/page.tsx index ee99f84..2c8f37c 100644 --- a/src/app/(pages)/(main)/total/penetration/page.tsx +++ b/src/app/(pages)/(main)/total/penetration/page.tsx @@ -11,21 +11,17 @@ import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; import {apiBrandByYearCategories, 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} from "@/const/lgConst"; +import {formatRowLabel} from "@/lib/lg-dashboard"; const PenetrationPage = () => { - const { totalValue, registerExcelExporter } = useLayoutFilter(); - console.log(totalValue); + const { isTotal, filterValue, registerExcelExporter } = useLayoutFilter(); + console.log(filterValue); const [isBrandShare, setIsBrandShare] = useState(false); - const displayRowLabel = (i:number, rowLabel: string) => { - if (rowLabel === "gap") return "전년 대비 GAP(%)"; - return rowLabel; - }; - const productTableRows: TopChartTableRow[] = apiTrendCategories.map((row, i) => ({ - label: displayRowLabel(i, row.rowLabel), + label: formatRowLabel(row.rowLabel), values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null), })); diff --git a/src/app/(pages)/(main)/total/purchase/page.tsx b/src/app/(pages)/(main)/total/purchase/page.tsx index 806015a..1993d1e 100644 --- a/src/app/(pages)/(main)/total/purchase/page.tsx +++ b/src/app/(pages)/(main)/total/purchase/page.tsx @@ -8,18 +8,14 @@ import { } from "@/components/lge-dashboard"; import {apiTrendBuy} from "@/config/sample.data"; import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {formatRowLabel} from "@/lib/lg-dashboard"; const PurchasePage = () => { - const { totalValue } = useLayoutFilter(); - console.log(totalValue); - - const displayRowLabel = (i:number, rowLabel: string) => { - if (rowLabel === "gap") return "전년 대비 GAP(%)"; - return rowLabel; - }; + const { isTotal, filterValue } = useLayoutFilter(); + console.log(filterValue); const purchaseTableRows: TopChartTableRow[] = apiTrendBuy.map((row, i) => ({ - label: displayRowLabel(i, row.rowLabel), + label: formatRowLabel(row.rowLabel), values: PRODUCT_KEYS.map((k) => (row as any)[k] ?? null), })); diff --git a/src/app/globals.css b/src/app/globals.css index 3da9c25..0144867 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -113,11 +113,17 @@ --lg-red-500: 341.1 95% 44.0%; /* #DB0649 */ --lg-red-400: 341.1 85% 56.0%; /* #EE2F6C */ --lg-red-300: 341.1 75% 68.0%; /* #EB7097 */ + --lg-red-200: 341.1 65% 82.0%; /* #EFB3C6 */ + --lg-red-100: 341.1 55% 90.0%; /* #F4D7E0 */ + --lg-red-50: 341.1 45% 96.0%; /* #F9F0F3 */ --lg-pink-600: 324.7 100% 46.3%; /* #EC008B */ --lg-pink-500: 324.7 95% 56.0%; /* #F924A2 */ --lg-pink-400: 324.7 85% 66.0%; /* #F25FB5 */ --lg-pink-300: 324.7 75% 76.0%; /* #F094CA */ + --lg-pink-200: 324.7 65% 86.0%; /* #F3C4DF */ + --lg-pink-100: 324.7 55% 92.0%; /* #F6DFED */ + --lg-pink-50: 324.7 45% 97.0%; /* #FBF4F8 */ --lg-purple-600: 263.0 65.9% 44.9%; /* #6127BE */ --lg-purple-500: 263.0 60.0% 56.0%; @@ -175,11 +181,11 @@ --chart-3: var(--lg-pink-300); --chart-4: var(--lg-pink-400); --chart-5: var(--lg-pink-600); - --chart-6: var(--lg-gray-900); - --chart-7: var(--lg-gray-800); + --chart-6: var(--lg-gray-500); + --chart-7: var(--lg-gray-600); --chart-8: var(--lg-gray-700); - --chart-9: var(--lg-gray-600); - --chart-10: var(--lg-gray-500); + --chart-9: var(--lg-gray-800); + --chart-10: var(--lg-gray-900); --chart-lg-1: var(--lg-pink-300); --chart-lg-2: var(--lg-red-300); @@ -326,11 +332,15 @@ .bg-red-500 { background-color: hsl(var(--lg-red-500)) !important; } .bg-red-400 { background-color: hsl(var(--lg-red-400)) !important; } .bg-red-300 { background-color: hsl(var(--lg-red-300)) !important; } +.bg-red-200 { background-color: hsl(var(--lg-red-200)) !important; } +.bg-red-100 { background-color: hsl(var(--lg-red-100)) !important; } .bg-pink-600 { background-color: hsl(var(--lg-pink-600)) !important; } .bg-pink-500 { background-color: hsl(var(--lg-pink-500)) !important; } .bg-pink-400 { background-color: hsl(var(--lg-pink-400)) !important; } .bg-pink-300 { background-color: hsl(var(--lg-pink-300)) !important; } +.bg-pink-200 { background-color: hsl(var(--lg-pink-200)) !important; } +.bg-pink-100 { background-color: hsl(var(--lg-pink-100)) !important; } .bg-purple-600 { background-color: hsl(var(--lg-purple-600)) !important; } .bg-purple-500 { background-color: hsl(var(--lg-purple-500)) !important; } diff --git a/src/components/layout/CategoryFilter.tsx b/src/components/layout/CategoryFilter.tsx index 41ec42f..a97cab7 100644 --- a/src/components/layout/CategoryFilter.tsx +++ b/src/components/layout/CategoryFilter.tsx @@ -36,7 +36,6 @@ const CategoryFilter = ({ filterItems, value, onChange, className }: CategoryFil v: string | CategoryTypeValue | CategoryTargetData ) => { if (value[key] === v) return; - const next: CategoryFilterValue = { ...value, [key]: v } as CategoryFilterValue; if (key === "type" && typeof v === "object" && v.value !== value.type.value) { diff --git a/src/components/layout/LayoutFilterContext.tsx b/src/components/layout/LayoutFilterContext.tsx index 3f8367d..859a81a 100644 --- a/src/components/layout/LayoutFilterContext.tsx +++ b/src/components/layout/LayoutFilterContext.tsx @@ -2,13 +2,11 @@ import React, { createContext, useCallback, useContext, useMemo, useRef } from "react"; import type { SelectedMap } from "@/types/common"; -import type { CategoryFilterValue } from "@/components/layout/CategoryFilter"; +import {CategoryFilterValue} from "@/components/layout/CategoryFilter"; -export type ExcelExportContext = { - isTotal: boolean; - totalValue: SelectedMap; - categoryValue: CategoryFilterValue; -}; +export type ExcelExportContext = + | { isTotal: true; filterValue: SelectedMap } + | { isTotal: false; filterValue: CategoryFilterValue }; type ExcelExporter = (ctx: ExcelExportContext) => void | Promise; diff --git a/src/components/layout/MainLayout.tsx b/src/components/layout/MainLayout.tsx index d3057d7..1f7a8e2 100644 --- a/src/components/layout/MainLayout.tsx +++ b/src/components/layout/MainLayout.tsx @@ -1,21 +1,22 @@ "use client"; -import {ReactNode, useEffect, useMemo, useState} from "react"; -import { usePathname, useRouter } from "next/navigation"; +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, TARGET_SLUG, totalFilters} from "@/config/filter.data"; +import {categoryTarget, totalFilters} from "@/config/filter.data"; import {CategoryTargetData, CategoryTargetType} from "@/config/filter.types"; import Header from "./Header"; import SubMenu from "./SubMenu"; import TotalFilter from "./TotalFilter"; import CategoryFilter, {CategoryFilterValue} from "./CategoryFilter"; import ExcelDownloadButton from "./ExcelDownloadButton"; -import {LayoutFilterProvider} from "./LayoutFilterContext"; +import {ExcelExportContext, LayoutFilterProvider} from "./LayoutFilterContext"; import {PRODUCTS_FILTER_ITEM} from "@/const/lgConst"; import {ProductsFilterItem} from "@/types/lg"; import {useLoading} from "@/hooks/useLoading"; +import {ArrowUp} from "lucide-react"; type MainLayoutProps = { children: ReactNode; @@ -49,6 +50,9 @@ const MainLayout = ({ children }: MainLayoutProps) => { const pathname = usePathname(); const { withLoadingAsync } = useLoading(); + const scrollRef = useRef(null); + const [showScrollTop, setShowScrollTop] = useState(false); + const isTotal = pathname.startsWith("/total"); const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0]; const subMenus = isTotal ? totalSubMenus : categorySubMenus; @@ -67,52 +71,45 @@ const MainLayout = ({ children }: MainLayoutProps) => { router.push(path); }; - const moveCategoryPage = (path: string) => { - const slug = TARGET_SLUG[categoryValue.target] ?? "profile"; - const nextPath = `${path}/${slug}`; - - if (pathname !== nextPath) { - router.push(nextPath); - } - } - const toggleFilter = () => { if (isTotal) setIsTotalFilterOpen((v) => !v); else setIsCategoryFilterOpen((v) => !v); }; - useEffect(() => { - /* - withLoadingAsync(async () => { - setCategoryValue(prev => ({...prev, product: categoryFilterItems.items[0]})) - }); - */ - setCategoryValue(prev => ({...prev, product: categoryFilterItems.items[0]})) - }, [categoryFilterItems]); + const onScrollContent = () => { + const el = scrollRef.current; + if (!el) return; + setShowScrollTop(el.scrollTop > 120); + }; + + const scrollToTop = () => { + scrollRef.current?.scrollTo({ top: 0, behavior: "smooth" }); + }; + + const ctx = useMemo(() => { + return isTotal + ? { isTotal: true, filterValue: totalValue } + : { isTotal: false, filterValue: categoryValue }; + }, [isTotal, totalValue, categoryValue]); useEffect(() => { - if (isTotal) return; - - const base = activeSub?.path; // "/category/ha-kitchen" - if (!base) return; - - const slug = TARGET_SLUG[categoryValue.target] ?? "profile"; - const nextPath = `${base}/${slug}`; - - if (pathname !== nextPath) { - router.replace(nextPath); + if (isTotal){ + console.log("istotal category", buildDefaultCategoryValue(PRODUCTS_FILTER_ITEM[0])); + setCategoryValue(buildDefaultCategoryValue(PRODUCTS_FILTER_ITEM[0])) + return; } - }, [isTotal, categoryValue.target, activeSub?.path, pathname, router]); + + if(categoryValue.product != categoryFilterItems.items[0]){ + setCategoryValue((prev) => { + return { ...prev, product: categoryFilterItems.items[0] }; + }); + } + + }, [isTotal, categoryFilterItems]); return ( -
- +
+
{
-
-
+
+
)} -
-
+
+
+
{children} -
+
+
+ + {showScrollTop && ( + + )}
diff --git a/src/components/lge-dashboard/BannerButtons.tsx b/src/components/lge-dashboard/BannerButtons.tsx index 7b25146..74362ca 100644 --- a/src/components/lge-dashboard/BannerButtons.tsx +++ b/src/components/lge-dashboard/BannerButtons.tsx @@ -20,13 +20,13 @@ const BannerButtons = ({ key={banner.variable} onClick={() => onSelectBanner(banner)} className={` - px-4 py-2 text-sm font-medium rounded-lg transition-colors - ${ - selectedBanner === banner - ? "bg-primary text-primary-foreground" - : "bg-gray-100 text-gray-700 hover:bg-gray-200" - } - `} + px-4 py-2 text-sm font-bold rounded-lg transition-colors cursor-pointer + ${ + selectedBanner === banner + ? "bg-primary text-primary-foreground" + : "bg-gray-100 text-gray-700 hover:bg-primary hover:text-primary-foreground" + } + `} > {banner.variableName} diff --git a/src/components/lge-dashboard/BaseEChart.tsx b/src/components/lge-dashboard/BaseEChart.tsx index 5c469d3..5743c42 100644 --- a/src/components/lge-dashboard/BaseEChart.tsx +++ b/src/components/lge-dashboard/BaseEChart.tsx @@ -3,6 +3,7 @@ import dynamic from "next/dynamic"; import { useMemo } from "react"; import type { EChartsOption } from "echarts"; +import { CHART_HEIGHTS } from "@/const/chartConst"; const ReactECharts = dynamic(() => import("echarts-for-react"), { ssr: false }); @@ -19,7 +20,7 @@ type BaseEChartProps = { const BaseEChart = ({ option, - height = 260, + height = CHART_HEIGHTS.DEFAULT, className, notMerge = true, lazyUpdate = true, diff --git a/src/components/lge-dashboard/chart/GroupedOverlayBar.tsx b/src/components/lge-dashboard/chart/GroupedOverlayBar.tsx index b759a81..ec4ffc6 100644 --- a/src/components/lge-dashboard/chart/GroupedOverlayBar.tsx +++ b/src/components/lge-dashboard/chart/GroupedOverlayBar.tsx @@ -14,6 +14,7 @@ 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"; type Props = { data: GroupedOverlayBarData; @@ -34,7 +35,7 @@ type Props = { const GroupedOverlayBar = ({ data, - height = 260, + height = CHART_HEIGHTS.DEFAULT, tooltip, grid, xAxis, @@ -170,9 +171,9 @@ const GroupedOverlayBar = ({ }); } - const YEAR_ITEM_W = 25; - const YEAR_ITEM_H = 14; - const YEAR_RADIUS = 4; + const YEAR_ITEM_W = LEGEND_ITEM_SIZE.WIDTH; + const YEAR_ITEM_H = LEGEND_ITEM_SIZE.HEIGHT; + const YEAR_RADIUS = LEGEND_ITEM_SIZE.RADIUS; let yearLegendOpt: LegendComponentOption | undefined = showYearLegend ? ({ diff --git a/src/components/lge-dashboard/chart/GroupedStackBar.tsx b/src/components/lge-dashboard/chart/GroupedStackBar.tsx index 2535258..ae71cb4 100644 --- a/src/components/lge-dashboard/chart/GroupedStackBar.tsx +++ b/src/components/lge-dashboard/chart/GroupedStackBar.tsx @@ -14,6 +14,7 @@ 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"; type Props = { data: GroupedStackBarData; @@ -33,7 +34,7 @@ type Props = { const GroupedStackBar = ({ data, - height = 260, + height = CHART_HEIGHTS.DEFAULT, tooltip, grid, xAxis, @@ -133,10 +134,6 @@ const GroupedStackBar = ({ } } - const YEAR_ITEM_W = 25; - const YEAR_ITEM_H = 14; - const YEAR_RADIUS = 4; - // 3) legend 2개: (좌)연도, (우)브랜드 let yearLegendOpt: LegendComponentOption | undefined = showYearLegend ? ({ @@ -145,9 +142,9 @@ const GroupedStackBar = ({ orient: "horizontal", data: yearLabels, // yearLegendSeries name과 일치 selected: yearSelected, - icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS), - itemWidth: YEAR_ITEM_W, - itemHeight: YEAR_ITEM_H, + icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS), + itemWidth: LEGEND_ITEM_SIZE.WIDTH, + itemHeight: LEGEND_ITEM_SIZE.HEIGHT, itemGap: 8, ...legend, } as LegendComponentOption) @@ -161,12 +158,12 @@ const GroupedStackBar = ({ top: 25, right: "center", orient: "horizontal", - data: brands, - icon: roundedRectIcon(YEAR_ITEM_W, YEAR_ITEM_H, YEAR_RADIUS), - itemWidth: YEAR_ITEM_W, - itemHeight: YEAR_ITEM_H, + icon: roundedRectIcon(LEGEND_ITEM_SIZE.WIDTH, LEGEND_ITEM_SIZE.HEIGHT, LEGEND_ITEM_SIZE.RADIUS), + itemWidth: LEGEND_ITEM_SIZE.WIDTH, + itemHeight: LEGEND_ITEM_SIZE.HEIGHT, itemGap: 8, ...legend, + data: [...brands].reverse(), } as LegendComponentOption); const legends = yearLegendOpt ? [yearLegendOpt, brandLegendOpt] : brandLegendOpt; diff --git a/src/components/lge-dashboard/chart/HorizontalBar.tsx b/src/components/lge-dashboard/chart/HorizontalBar.tsx index 53e277c..f3a4124 100644 --- a/src/components/lge-dashboard/chart/HorizontalBar.tsx +++ b/src/components/lge-dashboard/chart/HorizontalBar.tsx @@ -6,6 +6,14 @@ import BaseEChart from "../BaseEChart"; import {ChartData, ShowLabel, ValueFormatter} from "../types"; import { buildLgPalette } from "../color"; import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill"; +import { + createDefaultTooltip, + createDefaultLegend, + createDefaultGrid, + createCategoryAxis, + createValueAxis, +} from "@/lib/chart-options"; +import { BAR_WIDTHS } from "@/const/chartConst"; type Props = { data: ChartData; @@ -41,24 +49,13 @@ const HorizontalBar = ({ const option: EChartsOption = useMemo(() => { const fmt = valueFormatter ?? ((v: number) => String(v)); - const defaultTooltip: EChartsOption["tooltip"] = { - trigger: "axis", - axisPointer: { type: "shadow" }, - valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)), - }; - - const defaultLegend: EChartsOption["legend"] = { top: 0 }; - const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true }; - const defaultXAxis: EChartsOption["xAxis"] = { type: "value" }; - const defaultYAxis: EChartsOption["yAxis"] = { type: "category", data: data.categories }; - return { color: palette, - tooltip: tooltip ?? defaultTooltip, - legend: legend ?? defaultLegend, - grid: grid ?? defaultGrid, - xAxis: xAxis ?? defaultXAxis, - yAxis: yAxis ?? defaultYAxis, + tooltip: tooltip ?? createDefaultTooltip(fmt), + legend: legend ?? createDefaultLegend(), + grid: grid ?? createDefaultGrid(), + xAxis: xAxis ?? createValueAxis(), + yAxis: yAxis ?? createCategoryAxis(data.categories), series: data.series.map((s, index) => { const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length); @@ -67,7 +64,7 @@ const HorizontalBar = ({ type: "bar", data: s.data, emphasis: { disabled: true }, - barMaxWidth: barMaxWidth ?? 42, + barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT, label: showLabel ? { show: true, diff --git a/src/components/lge-dashboard/chart/StackBar.tsx b/src/components/lge-dashboard/chart/StackBar.tsx index 4d8092a..1e429a5 100644 --- a/src/components/lge-dashboard/chart/StackBar.tsx +++ b/src/components/lge-dashboard/chart/StackBar.tsx @@ -5,6 +5,16 @@ import type { EChartsOption } from "echarts"; import BaseEChart from "../BaseEChart"; import type { ChartData, ValueFormatter } from "../types"; import { buildLgPalette } from "../color"; +import { + createDefaultTooltip, + createDefaultLegend, + createDefaultGrid, + createCategoryAxis, + createValueAxis, + createBarSeries, + createReverseTooltip, + createReverseLegend, reverseSeries, +} from "@/lib/chart-options"; type Props = { data: ChartData; @@ -13,7 +23,6 @@ type Props = { paletteVarNames?: string[]; valueFormatter?: ValueFormatter; orientation?: "vertical" | "horizontal"; - /** series.stack이 없을 때 기본 stack key */ defaultStackKey?: string; tooltip?: EChartsOption["tooltip"]; legend?: EChartsOption["legend"]; @@ -21,58 +30,76 @@ type Props = { xAxis?: EChartsOption["xAxis"]; yAxis?: EChartsOption["yAxis"]; barMaxWidth?: number; + isReverse?: boolean; }; const StackBar = ({ - data, - height, - className, - paletteVarNames, - valueFormatter, - orientation = "vertical", - defaultStackKey = "total", - tooltip, - legend, - grid, - xAxis, - yAxis, - barMaxWidth, - }: Props) => { - const palette = useMemo(() => buildLgPalette(paletteVarNames), [paletteVarNames]); + data, + height, + className, + paletteVarNames, + valueFormatter, + orientation = "vertical", + defaultStackKey = "total", + tooltip, + legend, + grid, + xAxis, + yAxis, + barMaxWidth, + isReverse = false, + }: Props) => { + + // ✅ 렌더링용 데이터만 뒤집기 + const renderData = useMemo( + () => (isReverse ? reverseSeries(data) : data), + [data, isReverse] + ); + + // ✅ 팔레트도 뒤집어줘야 "시리즈 이름별" 색이 유지됨 + const palette = useMemo(() => { + const temp = buildLgPalette(paletteVarNames); + const n = data.series.length; // 원본 기준 + const base = temp.slice(0, n); + return isReverse ? [...base].reverse() : base; + }, [paletteVarNames, data.series.length, isReverse]); const option: EChartsOption = useMemo(() => { const fmt = valueFormatter ?? ((v: number) => String(v)); - const isV = orientation === "vertical"; - const defaultTooltip: EChartsOption["tooltip"] = { - trigger: "axis", - axisPointer: { type: "shadow" }, - valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)), - }; - const defaultLegend: EChartsOption["legend"] = { top: 0 }; - const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true }; - const defaultXAxis: EChartsOption["xAxis"] = isV ? { type: "category", data: data.categories } : { type: "value" }; - const defaultYAxis: EChartsOption["yAxis"] = isV ? { type: "value" } : { type: "category", data: data.categories }; return { color: palette, - tooltip: tooltip ?? defaultTooltip, - legend: legend ?? defaultLegend, - grid: grid ?? defaultGrid, - xAxis: xAxis ?? defaultXAxis, - yAxis: yAxis ?? defaultYAxis, - series: data.series.map((s) => ({ - name: s.name, - type: "bar", - stack: s.stack ?? defaultStackKey, - data: s.data, - emphasis: { disabled: true }, - barMaxWidth: barMaxWidth ?? 42, - })), + tooltip: tooltip ?? (isReverse ? createReverseTooltip(data, fmt) : createDefaultTooltip(fmt)), + legend: legend ?? (isReverse ? createReverseLegend(data) : createDefaultLegend()), + grid: grid ?? createDefaultGrid(), + xAxis: xAxis ?? (isV ? createCategoryAxis(renderData.categories) : createValueAxis()), + yAxis: yAxis ?? (isV ? createValueAxis() : createCategoryAxis(renderData.categories)), + + series: renderData.series.map((s) => + createBarSeries(s.name, s.data, { + stack: s.stack ?? defaultStackKey, + barMaxWidth, + }) + ), }; - }, [data, palette, valueFormatter, orientation, defaultStackKey, tooltip, legend, grid, xAxis, yAxis, barMaxWidth]); + }, [ + data, + renderData, + palette, + valueFormatter, + orientation, + defaultStackKey, + tooltip, + legend, + grid, + xAxis, + yAxis, + barMaxWidth, + isReverse, + ]); return ; -} +}; export default StackBar; \ No newline at end of file diff --git a/src/components/lge-dashboard/chart/VerticalBar.tsx b/src/components/lge-dashboard/chart/VerticalBar.tsx index 65529b1..f9ea382 100644 --- a/src/components/lge-dashboard/chart/VerticalBar.tsx +++ b/src/components/lge-dashboard/chart/VerticalBar.tsx @@ -6,6 +6,14 @@ import BaseEChart from "../BaseEChart"; import {ChartData, ShowLabel, ValueFormatter} from "../types"; import { buildLgPalette } from "../color"; import {getIsShowLabel} from "@/components/lge-dashboard/chart/utill"; +import { + createDefaultTooltip, + createDefaultLegend, + createDefaultGrid, + createCategoryAxis, + createValueAxis, +} from "@/lib/chart-options"; +import { BAR_WIDTHS } from "@/const/chartConst"; type Props = { data: ChartData; @@ -42,24 +50,13 @@ const VerticalBar = ({ const option: EChartsOption = useMemo(() => { const fmt = valueFormatter ?? ((v: number) => String(v)); - const defaultTooltip: EChartsOption["tooltip"] = { - trigger: "axis", - axisPointer: { type: "shadow" }, - valueFormatter: (v: unknown) => (typeof v === "number" ? fmt(v) : String(v)), - }; - - const defaultLegend: EChartsOption["legend"] = { top: 0 }; - const defaultGrid: EChartsOption["grid"] = { left: 16, right: 16, top: 36, bottom: 12, containLabel: true }; - const defaultXAxis: EChartsOption["xAxis"] = { type: "category", data: data.categories, axisTick: { alignWithLabel: true } }; - const defaultYAxis: EChartsOption["yAxis"] = { type: "value" }; - return { color: palette, - tooltip: tooltip ?? defaultTooltip, - legend: legend ?? defaultLegend, - grid: grid ?? defaultGrid, - xAxis: xAxis ?? defaultXAxis, - yAxis: yAxis ?? defaultYAxis, + tooltip: tooltip ?? createDefaultTooltip(fmt), + legend: legend ?? createDefaultLegend(), + grid: grid ?? createDefaultGrid(), + xAxis: xAxis ?? createCategoryAxis(data.categories, false, { axisTick: { alignWithLabel: true } }), + yAxis: yAxis ?? createValueAxis(), series: data.series.map((s, index) => { const showLabel = getIsShowLabel(showFocusLabel, index, data.series.length); @@ -68,7 +65,7 @@ const VerticalBar = ({ type: "bar", data: s.data, emphasis: { disabled: true }, - barMaxWidth: barMaxWidth ?? 42, + barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT, label: showLabel ? { show: true, diff --git a/src/components/lge-dashboard/color.ts b/src/components/lge-dashboard/color.ts index 0511359..dec77c9 100644 --- a/src/components/lge-dashboard/color.ts +++ b/src/components/lge-dashboard/color.ts @@ -1,5 +1,7 @@ type Hsl = { h: number; s: number; l: number }; + + const parseHslTriplet = (raw: string): Hsl | null => { // 예: "341.1 100% 32.4%" / "0 0% 85%" const m = raw.trim().match(/^(-?\d+(\.\d+)?)\s+(\d+(\.\d+)?)%\s+(\d+(\.\d+)?)%$/); diff --git a/src/components/lge-dashboard/combo/BannerSummary.tsx b/src/components/lge-dashboard/combo/BannerSummary.tsx new file mode 100644 index 0000000..7b9aaea --- /dev/null +++ b/src/components/lge-dashboard/combo/BannerSummary.tsx @@ -0,0 +1,162 @@ +import {ChartData, DataColumn, DataTable, HorizontalBar, LeftChartTable, SignStyle} from "@/components/lge-dashboard"; +import {BannerKey, ServerBannerRow} from "@/types/lg"; +import {formatRowLabel, isSampleRow} from "@/lib/lg-dashboard"; +import {useMemo} from "react"; +import {BANNER_GROUP, BANNER_KEY_MAP, GRID_Y_NOT_PADDING} from "@/const/lgConst"; +import {formatNumber, parseNumber} from "@/lib/utils"; + + +type SectionSpec = { + title: string; + groupKeys: Array; +}; + +/** 3개 섹션(테이블)도 여기서만 선언 */ +const SECTIONS: SectionSpec[] = [ + { title: "가구 형태", groupKeys: ["lifeStage", "household", "age"] }, + { title: "거주 형태", groupKeys: ["tenure", "housing", "pyeong"] }, + { title: "거주 지역 및 소득 수준", groupKeys: ["region", "income"] }, +]; + +const SEP_R = "lg-table__sep-r"; + +const getSectionBannerKeys = (spec: SectionSpec): BannerKey[] => + spec.groupKeys.flatMap((gk) => BANNER_GROUP[gk].keys); + +const buildColumns = (spec: SectionSpec): DataColumn[] => { + const columns: DataColumn[] = [ + { + key: "rowLabel", + header: "", + headRowSpan: 2, + rowHead: true, + cellClassName: "lg-table__rowhead", + width: 120, + }, + { + key: "total", + header: "전체", + numeric: true, + headerClassName: SEP_R, + cellClassName: SEP_R, + width: 80, + }, + ]; + + spec.groupKeys.forEach((groupKey) => { + const g = BANNER_GROUP[groupKey]; + g.keys.forEach((k, idx) => { + const isLast = idx === g.keys.length - 1; + columns.push({ + key: k as any, + header: BANNER_KEY_MAP[k] ?? String(k), + group: g.label, + numeric: true, + headerClassName: isLast ? SEP_R : undefined, + cellClassName: isLast ? SEP_R : undefined, + width: 90, + }); + }); + }); + + return columns; +}; + +type BannerSummaryProps = { + data: ServerBannerRow[]; + useChart: boolean; +}; + +const BannerSummary = ({ data, useChart }: BannerSummaryProps) => { + + const buildChartData = (rows: ServerBannerRow[], bannerKeys: BannerKey[]): ChartData => { + const categories = rows + .filter((r) => r.rowLabel !== "사례수") + .map((r) => formatRowLabel(r.rowLabel)); + + const series = [ + { + name:"전체", + data: rows + .filter((r) => r.rowLabel !== "사례수") + .map((r) => parseNumber(r.total) ?? null), + } + ]; + + return { categories, series }; + }; + + const rows = useMemo(() => { + const allKeys = Array.from( + new Set(Object.values(BANNER_GROUP).flatMap((g) => g.keys)) + ) as string[]; + + return data.map((r) => { + const out: any = { ...r }; + + if (isSampleRow(r.rowLabel)) { + // total + out.total = `(${formatNumber(Number(r.total ?? 0))})`; + // banner values + allKeys.forEach((k) => { + const v = (r as any)[k]; + if (typeof v === "number") out[k] = `(${formatNumber(v)})`; + }); + } + return out as ServerBannerRow; + }); + }, [data]); + + const signStyleGap: SignStyle = { + rowSelector: (row) => row.rowLabel === "gap", + display: "arrow", + arrowWithNumber: true, + paint: "text", + zeroText: "-", + }; + + return ( +
+ {SECTIONS.map((spec) => { + const bannerKeys = getSectionBannerKeys(spec); + + const columns = buildColumns(spec); + const chartData = buildChartData(rows, bannerKeys); + + return ( + useChart ? + + key={spec.title} + title={spec.title} + columns={columns} + rows={rows} + signStyle={signStyleGap} + chart={ + + } + chartCell={{ key: "total", startRowIndex: 1 }} + minWidthPx={1200} + /> + : + + key={spec.title} + title={spec.title} + columns={columns} + rows={rows} + signStyle={signStyleGap} + /> + ); + })} +
+ ); +} + +export default BannerSummary; \ No newline at end of file diff --git a/src/components/lge-dashboard/combo/CategoryByData.tsx b/src/components/lge-dashboard/combo/CategoryByData.tsx new file mode 100644 index 0000000..36fb68a --- /dev/null +++ b/src/components/lge-dashboard/combo/CategoryByData.tsx @@ -0,0 +1,134 @@ +import { + bannerType, + type DataColumn, + DataTable, + HorizontalBar, SectionTitle, SignStyle, + StackBar +} from "@/components/lge-dashboard"; +import BannerButtons from "@/components/lge-dashboard/BannerButtons"; +import {totalFilters} from "@/config/filter.data"; +import {useMemo, useState} from "react"; +import {BannerGroupKey, CategoryChartMode, ServerBannerRow} from "@/types/lg"; +import {buildRowLabelSeriesChartData, buildYearSeriesChartData, isBannerGroupKey} from "@/lib/lg-dashboard"; +import {BANNER_GROUP, BANNER_KEY_MAP, LAST_YEAR} from "@/const/lgConst"; +import {createDefaultGrid, createDefaultLegend, reverseCategories} from "@/lib/chart-options"; + +type CategoryByDataProps = { + title?: string; + chartMode: CategoryChartMode; + allTableData: ServerBannerRow[]; + fillGreaterThan5?: boolean; + chartHeight?: number; + chartWidth?: number; +} + +const banners: bannerType[] = totalFilters.map((filter) => { + return {variable: filter.variable, variableName: filter.variableName} +}) + +const signStyleGap: SignStyle = { + rowSelector: (row) => row.rowLabel === "gap", + display: "arrow", + arrowWithNumber: true, + paint: "text", + zeroText: "-", +}; + +const CategoryByData = ({ + title, + chartMode, + allTableData, + fillGreaterThan5, + chartHeight, + chartWidth, + }: CategoryByDataProps) => { + const [selectedBanner, setSelectedBanner] = useState(banners[0]); + + const buildColumns = (groupKey: BannerGroupKey): DataColumn[] => { + const columns: DataColumn[] = [ + { + key: "rowLabel", + header: "", + headRowSpan: 2, + rowHead: true, + cellClassName: "lg-table__rowhead", + width: 120, + }, + ]; + + const g = BANNER_GROUP[groupKey]; + g.keys.forEach((k) => { + columns.push({ + key: k as any, + header: BANNER_KEY_MAP[k] ?? String(k), + group: g.label, + numeric: true, + width: 90, + }); + }); + + return columns; + }; + + const chartData = useMemo(() => { + const excludeRowLabels =["사례수", "gap"]; + if(chartMode == "horizontal"){ + return reverseCategories(buildYearSeriesChartData(allTableData, {excludeRowLabels})); + } + + return buildRowLabelSeriesChartData(allTableData, {excludeRowLabels}); + + }, [allTableData, chartMode]); + + const tableColumns = useMemo(() => { + const v = selectedBanner.variable; + return isBannerGroupKey(v) ? buildColumns(v) : []; + }, [selectedBanner.variable]); + const tableData = useMemo(() => allTableData.filter((row) => row.year === LAST_YEAR), [allTableData, LAST_YEAR]) + + return ( +
+ {title && } +
+
+ { + chartMode === "stack" || chartMode === "reverseStack" ? + + : + + } +
+ +
+ +
+ +
+ +
+
+
+ ); +}; + +export default CategoryByData; \ No newline at end of file diff --git a/src/components/lge-dashboard/combo/LeftChartTable.tsx b/src/components/lge-dashboard/combo/LeftChartTable.tsx index 5f7e4db..51dd024 100644 --- a/src/components/lge-dashboard/combo/LeftChartTable.tsx +++ b/src/components/lge-dashboard/combo/LeftChartTable.tsx @@ -1,9 +1,10 @@ "use client"; import React, { useMemo } from "react"; -import { cn } from "@/lib/utils"; +import { cn, parseNumber } from "@/lib/utils"; import type { DataColumn, SignStyle } from "../types"; import SectionTitle from "../SectionTitle"; +import { TABLE_DIMENSIONS } from "@/const/chartConst"; type MergedChartCell = { /** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */ @@ -33,17 +34,7 @@ type Props> = { minWidthPx?: number; }; -function toNumber(v: unknown): number | null { - if (v === null || v === undefined) return null; - if (typeof v === "number") return Number.isFinite(v) ? v : null; - if (typeof v === "string") { - const s = v.trim(); - if (s === "" || s === "-") return null; - const n = Number(s.replaceAll(",", "")); - return Number.isFinite(n) ? n : null; - } - return null; -} +// toNumber는 utils.ts의 parseNumber로 통합됨 function renderSigned( n: number, @@ -73,7 +64,7 @@ export default function LeftChartTable>({ signStyle, wrapperClassName, tableClassName, - minWidthPx = 1200, + minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT, }: Props) { const hasGroupHeader = useMemo( () => columns.some((c) => c.group) || columns.some((c) => c.headRowSpan === 2), @@ -184,8 +175,8 @@ export default function LeftChartTable>({ {columns.map((c) => { // 머지-차트 셀 - if (c.key === chartCell.key) { - if (ri !== start) return null; + if (c.key === chartCell.key && ri >= start) { + if (ri > start) return null; return ( >({ ? raw : String(raw); - const n = isSignRow ? toNumber(raw) : null; + const n = isSignRow ? parseNumber(raw) : null; const shouldSign = isSignRow && (signStyle?.keys ? signStyle.keys.includes(c.key) : !!c.numeric); if (c.rowHead) { diff --git a/src/components/lge-dashboard/sub-page/LifeStageDiv.tsx b/src/components/lge-dashboard/combo/LifeStageDiv.tsx similarity index 93% rename from src/components/lge-dashboard/sub-page/LifeStageDiv.tsx rename to src/components/lge-dashboard/combo/LifeStageDiv.tsx index ded82dc..830419f 100644 --- a/src/components/lge-dashboard/sub-page/LifeStageDiv.tsx +++ b/src/components/lge-dashboard/combo/LifeStageDiv.tsx @@ -1,13 +1,11 @@ -import GaugeCardTable from "../combo/GaugeCardTable"; +import GaugeCardTable from "./GaugeCardTable"; import {GaugeColumn} from "@/components/lge-dashboard"; import {useMemo} from "react"; import {apiLifeStageByProduct} from "@/config/sample.data"; import {LifeStageRow} from "@/types/lg"; +import {asNum, norm} from "@/lib/utils"; const LifeStageDiv = () => { - const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase(); - const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null; - const LIFE_STAGE_COLUMNS: GaugeColumn[] = [ { key: "item", header: "", rowHead: true, renderLabel: (r) => r.item }, diff --git a/src/components/lge-dashboard/combo/TopChartTable.tsx b/src/components/lge-dashboard/combo/TopChartTable.tsx index cf5551f..b784018 100644 --- a/src/components/lge-dashboard/combo/TopChartTable.tsx +++ b/src/components/lge-dashboard/combo/TopChartTable.tsx @@ -1,9 +1,10 @@ "use client"; import React, { useMemo } from "react"; -import { cn } from "@/lib/utils"; +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"; type BaseProps = { title?: string; @@ -49,17 +50,7 @@ type ChartDataModeProps = BaseProps & { export type TopChartTableProps = HtmlModeProps | ChartDataModeProps; -function toNumber(v: unknown): number | null { - if (v === null || v === undefined) return null; - if (typeof v === "number") return Number.isFinite(v) ? v : null; - if (typeof v === "string") { - const s = v.trim(); - if (s === "" || s === "-") return null; - const n = Number(s.replaceAll(",", "")); - return Number.isFinite(n) ? n : null; - } - return null; -} +// toNumber는 utils.ts의 parseNumber로 통합됨 function formatSignedNumber(n: number, zeroText: string, showPlus: boolean) { if (n === 0) return zeroText; @@ -78,8 +69,8 @@ export default function TopChartTable(props: TopChartTableProps) { const { title, chart, - chartHeight = 260, - minWidthPx = 1600, + chartHeight = CHART_HEIGHTS.DEFAULT, + minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.STANDARD, tableClassName, wrapperClassName, signStyle, @@ -122,7 +113,7 @@ export default function TopChartTable(props: TopChartTableProps) { categories, series: rows.map((r) => ({ name: r.label, - data: r.values.map((v) => toNumber(v) ?? null), + data: r.values.map((v) => parseNumber(v) ?? null), })), }), [categories, rows] @@ -174,7 +165,7 @@ export default function TopChartTable(props: TopChartTableProps) { {categories.map((_, ci) => { const raw = r.values?.[ci]; - const n = toNumber(raw); + const n = parseNumber(raw); // 일반 행 if (!isSignRow) { diff --git a/src/components/lge-dashboard/index.ts b/src/components/lge-dashboard/index.ts index 9b4269d..7bfd2a3 100644 --- a/src/components/lge-dashboard/index.ts +++ b/src/components/lge-dashboard/index.ts @@ -14,7 +14,7 @@ export { default as GaugeTable } from "./table/GaugeTable"; export { default as TopChartTable } from "./combo/TopChartTable"; export { default as LeftChartTable } from "./combo/LeftChartTable"; export { default as GaugeCardTable } from "./combo/GaugeCardTable"; -export { default as CategoryByData } from "./sub-page/CategoryByData" +export { default as CategoryByData } from "./combo/CategoryByData" export { default as CardDefault } from "./card/Card"; diff --git a/src/components/lge-dashboard/sub-page/CategoryByData.tsx b/src/components/lge-dashboard/sub-page/CategoryByData.tsx deleted file mode 100644 index 612c1d8..0000000 --- a/src/components/lge-dashboard/sub-page/CategoryByData.tsx +++ /dev/null @@ -1,65 +0,0 @@ -import {bannerType, type ChartData, type DataColumn, DataTable, StackBar} from "@/components/lge-dashboard"; -import BannerButtons from "@/components/lge-dashboard/BannerButtons"; -import {totalFilters} from "@/config/filter.data"; -import {useEffect, useState} from "react"; - -type CategoryByDataProps> = { - chartData:ChartData; - tableColumns: DataColumn[]; - allTableData: T[]; -} - -const banners: bannerType[] = totalFilters.map((filter) => { - return {variable: filter.variable, variableName: filter.variableName} -}) - -const CategoryByData = >({ - chartData, - tableColumns, - allTableData, - }: CategoryByDataProps) => { - const [selectedBanner, setSelectedBanner] = useState(banners[0]); - const [tableData, setTableData] = useState([]); - - useEffect(() => { - const filteredTableData = allTableData.filter((row) => row[selectedBanner.variable] === selectedBanner.variableName); - setTableData(filteredTableData); - }, [selectedBanner, allTableData]); - - return ( -
- {/* 좌측: 차트 */} -
- -
- - {/* 중앙: 버튼 */} -
- -
- - {/* 우측: 테이블 */} -
- -
-
- ); -}; - -export default CategoryByData; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/CategoryPage.tsx b/src/components/lge-dashboard/sub-page/CategoryPage.tsx new file mode 100644 index 0000000..fea2fb1 --- /dev/null +++ b/src/components/lge-dashboard/sub-page/CategoryPage.tsx @@ -0,0 +1,48 @@ +'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 ; + case CategoryTargetData.PENETRATION_CHANGE: + return ; + case CategoryTargetData.BRAND: + return ; + case CategoryTargetData.TYPE_SPEC: + return ; + case CategoryTargetData.OWNERSHIP_PATH: + return ; + case CategoryTargetData.PURCHASE_BEHAVIOR: + return ; + case CategoryTargetData.PURCHASE_CHANNEL: + return ; + case CategoryTargetData.PAYMENT_METHOD: + return ; + default: + return null; + } + }; + + return renderPage(); +} + +export default CategoryPage; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/Brand.tsx b/src/components/lge-dashboard/sub-page/category-page/Brand.tsx new file mode 100644 index 0000000..031ca17 --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/Brand.tsx @@ -0,0 +1,62 @@ +'use client' + +import {useMemo} from "react"; +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {CategoryByData} from "@/components/lge-dashboard"; +import {apiBrandShareByYear, apiPaymentMethodByYear} from "@/config/sample.data"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import {buildGapRow} from "@/lib/lg-dashboard"; + +const Brand = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => { + const cleaned = apiBrandShareByYear.filter( + (r) => !(r.year === 26 && r.rowLabel === "gap") + ); + + const gapRow = buildGapRow(cleaned, 25, 26, "lg", "gap"); + + let finalData = cleaned; + + if (gapRow) { + const insertIdx = cleaned.findIndex( + (r) => r.year === 26 && r.rowLabel === "lg" + ); + + if (insertIdx >= 0) { + finalData = [ + ...cleaned.slice(0, insertIdx + 1), + gapRow, + ...cleaned.slice(insertIdx + 1), + ]; + } + } + + return [ + { + title: "구매 형식", + chartMode: "reverseStack", + data: finalData, + }, + ]; + }, []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +} + +export default Brand; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/OwnershipPath.tsx b/src/components/lge-dashboard/sub-page/category-page/OwnershipPath.tsx new file mode 100644 index 0000000..2caf38a --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/OwnershipPath.tsx @@ -0,0 +1,34 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {useMemo} from "react"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import {apiOwnershipPathByYear, apiOwnershipTriggerByYear} from "@/config/sample.data"; +import {CategoryByData} from "@/components/lge-dashboard"; + +const OwnershipPath = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => [ + {title: "보유 경로", chartMode:"reverseStack", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))}, + {title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))}, + ], []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +} + +export default OwnershipPath; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/PaymentMethod.tsx b/src/components/lge-dashboard/sub-page/category-page/PaymentMethod.tsx new file mode 100644 index 0000000..19c133a --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/PaymentMethod.tsx @@ -0,0 +1,33 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {apiOwnershipPathByYear, apiOwnershipTriggerByYear, apiPaymentMethodByYear} from "@/config/sample.data"; +import {useMemo} from "react"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import {CategoryByData} from "@/components/lge-dashboard"; + +const PaymentMethod = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => [ + {title: "구매 형식", chartMode:"reverseStack", data: apiPaymentMethodByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))}, + ], []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +} + +export default PaymentMethod; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/PenetrationChange.tsx b/src/components/lge-dashboard/sub-page/category-page/PenetrationChange.tsx new file mode 100644 index 0000000..44f064c --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/PenetrationChange.tsx @@ -0,0 +1,24 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary"; +import {useEffect, useState} from "react"; +import {ServerBannerRow} from "@/types/lg"; +import {apiYearIndex} from "@/config/sample.data"; + +const PenetrationChange = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const [penetrationChangeData, setPenetrationChangeData] = useState([]); + + useEffect(() => { + setPenetrationChangeData(apiYearIndex) + },[]) + + return( + + ); +} + +export default PenetrationChange \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/Profile.tsx b/src/components/lge-dashboard/sub-page/category-page/Profile.tsx new file mode 100644 index 0000000..fd8ef5b --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/Profile.tsx @@ -0,0 +1,42 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import BannerSummary from "@/components/lge-dashboard/combo/BannerSummary"; +import {useEffect, useMemo, useState} from "react"; +import {ServerBannerRow} from "@/types/lg"; +import {apiOwnershipSummary, apiPurchaseRateKpis} from "@/config/sample.data"; + +const Profile = () => { + const { isTotal, filterValue } = useLayoutFilter(); + const [profileData, setProfileData] = useState([]); + + const typeLabel = useMemo(() => { + if (isTotal) return null; // SelectedMap 경로 + return filterValue.type.label; // CategoryFilterValue 경로로 TS가 좁혀짐 + }, [isTotal, filterValue]); + + useEffect(() => { + if (!typeLabel) return; + + switch (typeLabel) { + case "보유": + setProfileData(apiOwnershipSummary); + break; + case "구매": + setProfileData(apiPurchaseRateKpis); + break; + case "향후 구매": + setProfileData(apiPurchaseRateKpis); + break; + default: + setProfileData([]); + break; + } + }, [typeLabel]); + + return ( + + ); +} + +export default Profile; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/PurchaseBehavior.tsx b/src/components/lge-dashboard/sub-page/category-page/PurchaseBehavior.tsx new file mode 100644 index 0000000..b553294 --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/PurchaseBehavior.tsx @@ -0,0 +1,34 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {useMemo} from "react"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import { apiOwnershipPathByYear, apiOwnershipTriggerByYear} from "@/config/sample.data"; +import {CategoryByData} from "@/components/lge-dashboard"; + +const PurchaseBehavior = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => [ + {title: "보유 경로", chartMode:"horizontal", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))}, + {title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))}, + ], []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +}; + +export default PurchaseBehavior; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/PurchaseChannel.tsx b/src/components/lge-dashboard/sub-page/category-page/PurchaseChannel.tsx new file mode 100644 index 0000000..321d91a --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/PurchaseChannel.tsx @@ -0,0 +1,38 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {apiOwnershipPathByYear, apiOwnershipTriggerByYear, apiPurchaseChannelByYear} from "@/config/sample.data"; +import {useMemo} from "react"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import {CategoryByData} from "@/components/lge-dashboard"; + +const PurchaseChannel = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => [ + { + title: "구매 채널", + chartMode: "horizontal", + data: apiPurchaseChannelByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")), + chartHeight: 550, + }, + ], []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +} + +export default PurchaseChannel; \ No newline at end of file diff --git a/src/components/lge-dashboard/sub-page/category-page/TypeSpec.tsx b/src/components/lge-dashboard/sub-page/category-page/TypeSpec.tsx new file mode 100644 index 0000000..d6ecaf8 --- /dev/null +++ b/src/components/lge-dashboard/sub-page/category-page/TypeSpec.tsx @@ -0,0 +1,37 @@ +'use client' + +import {useLayoutFilter} from "@/components/layout/LayoutFilterContext"; +import {useMemo} from "react"; +import {PageData, ServerBannerRow} from "@/types/lg"; +import {apiFridgeDoorTypeByYear} from "@/config/sample.data"; +import {CategoryByData} from "@/components/lge-dashboard"; + +const TypeSpec = () => { + const { filterValue } = useLayoutFilter(); + console.log(filterValue); + + const tableDataArray = useMemo[]>(() => [ + { + title: "타입", + chartMode: "horizontal", + data: apiFridgeDoorTypeByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")), + }, + ], []); + + return ( +
+ {tableDataArray.map((tableData) => ( + + ))} +
+ ); +} + +export default TypeSpec; \ No newline at end of file diff --git a/src/components/lge-dashboard/table/DataTable.tsx b/src/components/lge-dashboard/table/DataTable.tsx index a834872..e767f76 100644 --- a/src/components/lge-dashboard/table/DataTable.tsx +++ b/src/components/lge-dashboard/table/DataTable.tsx @@ -2,32 +2,21 @@ import { useMemo } from "react"; import type React from "react"; -import { cn } from "@/lib/utils"; +import { cn, parseNumber } from "@/lib/utils"; import type { DataColumn, SignDisplayMode, SignStyle } from "../types"; +import SectionTitle from "../SectionTitle"; type Props> = { columns: DataColumn[]; rows: T[]; + title?: string; className?: string; wrapperClassName?: string; signStyle?: SignStyle; + fillGreaterThan5?: boolean; }; -const parseSignedNumber = (raw: unknown): number | null => { - if (raw === null || raw === undefined) return null; - if (typeof raw === "number") return Number.isFinite(raw) ? raw : null; - if (typeof raw === "string") { - const s = raw - .trim() - .replaceAll(",", "") - .replaceAll("−", "-") // 유니코드 마이너스 - .replaceAll("%", ""); - if (s === "" || s === "-") return null; - const n = Number(s); - return Number.isFinite(n) ? n : null; - } - return null; -}; +// parseSignedNumber는 utils.ts의 parseNumber로 통합됨 const defaultFmt = (v: number) => Number.isInteger(v) ? String(v) : v.toLocaleString(); @@ -53,20 +42,22 @@ const signText = ( }; const DataTable = >({ - columns, - rows, - className, - wrapperClassName, - signStyle, - }: Props) => { + columns, + rows, + title, + className, + wrapperClassName, + signStyle, + fillGreaterThan5 = false, + }: Props) => { 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 }; + | { 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[]; @@ -148,6 +139,9 @@ const DataTable = >({ return (
+ {title && ( + + )} {hasGroup && ( @@ -178,6 +172,7 @@ const DataTable = >({ {rows.map((row, rIdx) => { const signRow = isSignRow(row, rIdx); + const total = parseNumber(row.total); return ( @@ -191,7 +186,7 @@ const DataTable = >({ const applySign = signRow && isTargetKey(c.key) && !c.rowHead; if (applySign) { - const n = parseSignedNumber(raw); + const n = parseNumber(raw); const displayText = n === null ? "-" : signText(n, display, showPlus, arrowWithNumber, fmt, zeroText); @@ -230,8 +225,13 @@ const DataTable = >({ ); } + + const numContent = c.numeric ? parseNumber(content) ?? 0 : 0; + const isFill = fillGreaterThan5 && total && numContent > total + 5; return ( - ); diff --git a/src/components/lge-dashboard/table/GaugeTable.tsx b/src/components/lge-dashboard/table/GaugeTable.tsx index d8252b1..faba734 100644 --- a/src/components/lge-dashboard/table/GaugeTable.tsx +++ b/src/components/lge-dashboard/table/GaugeTable.tsx @@ -1,7 +1,7 @@ "use client"; import { useMemo } from "react"; -import { cn } from "@/lib/utils"; +import { cn, parseNumber } from "@/lib/utils"; import {GaugeColumn} from "../types"; type Props> = { @@ -24,14 +24,7 @@ type Props> = { valueFormatter?: (v: number) => string; }; -const num = (v: unknown) => { - if (typeof v === "number" && Number.isFinite(v)) return v; - if (typeof v === "string") { - const n = Number(v.replaceAll(",", "").replaceAll("%", "").trim()); - return Number.isFinite(n) ? n : null; - } - return null; -}; +// num은 utils.ts의 parseNumber로 통합됨 const GaugeTable = >({ columns, @@ -130,7 +123,7 @@ const GaugeTable = >({ } const raw = row[c.key]; - const v = num(raw); + const v = parseNumber(raw); const max = c.max ?? 100; const ratio = v === null ? 0 : clamp01((v * scale) / max); const pct = ratio * 100; diff --git a/src/components/lge-dashboard/types.ts b/src/components/lge-dashboard/types.ts index 219c7a0..76e250f 100644 --- a/src/components/lge-dashboard/types.ts +++ b/src/components/lge-dashboard/types.ts @@ -124,6 +124,7 @@ export const signStyleGapRow: SignStyle = { arrowWithNumber: true, paint: "text", }; + /** ChartLabel 보여지는 옵션 */ export type ShowLabel = "none" | "all" | "last" | "first"; diff --git a/src/config/filter.data.ts b/src/config/filter.data.ts index 4129653..74aa1e1 100644 --- a/src/config/filter.data.ts +++ b/src/config/filter.data.ts @@ -8,7 +8,7 @@ import { export const totalFilters:TotalFilterItem[] = [ { - variable:"a1", + variable:"lifeStage", variableName:"라이프 스테이지", children:[ { value: "0", label: "전체"}, @@ -21,7 +21,7 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a2", + variable:"income", variableName:"월 소득 규모", children:[ { value: "0", label: "전체"}, @@ -32,8 +32,8 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a3", - variableName:"거주 형태", + variable:"tenure", + variableName:"입주 형태", children:[ { value: "0", label: "전체"}, { value: "1", label: "자가"}, @@ -44,7 +44,7 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a4", + variable:"pyeong", variableName:"거주 평형", children:[ { value: "0", label: "19평 이하"}, @@ -55,8 +55,8 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a5", - variableName:"주택 형태", + variable:"housing", + variableName:"주거 형태", children:[ { value: "0", label: "전체"}, { value: "1", label: "아파트"}, @@ -67,7 +67,7 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a6", + variable:"region", variableName:"지역", children:[ { value: "0", label: "전체"}, @@ -80,7 +80,7 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a7", + variable:"age", variableName:"연령대", children:[ { value: "0", label: "20대"}, @@ -91,7 +91,7 @@ export const totalFilters:TotalFilterItem[] = [ ] }, { - variable:"a8", + variable:"household", variableName:"가구원 수", children:[ { value: "0", label: "전체"}, @@ -127,7 +127,7 @@ export const categoryTarget: CategoryTargetItem[] = [ { target: CategoryTargetData.BRAND, label: "브랜드"}, { target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"}, { target: CategoryTargetData.OWNERSHIP_PATH, label: "보유 경로"}, - { target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"}, + { target: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"}, ] }, { @@ -138,18 +138,7 @@ export const categoryTarget: CategoryTargetItem[] = [ { target: CategoryTargetData.TYPE_SPEC, label: "타입/스펙"}, { target: CategoryTargetData.PURCHASE_BEHAVIOR, label: "구입 행태"}, { target: CategoryTargetData.PURCHASE_CHANNEL, label: "구매 채널"}, - { target: CategoryTargetData.PURCHASE_FORMAT, label: "구매 형식"}, + { target: CategoryTargetData.PAYMENT_METHOD, label: "구매 형식"}, ] }, -] - -export const TARGET_SLUG: Record = { - [CategoryTargetData.PROFILE]: "profile", - [CategoryTargetData.BRAND]: "brand", - [CategoryTargetData.TYPE_SPEC]: "type-spec", - [CategoryTargetData.PURCHASE_FORMAT]: "purchase-format", - [CategoryTargetData.PENETRATION_CHANGE]: "penetration-change", - [CategoryTargetData.OWNERSHIP_PATH]: "ownership-path", - [CategoryTargetData.PURCHASE_BEHAVIOR]: "purchase-behavior", - [CategoryTargetData.PURCHASE_CHANNEL]: "purchase-channel", -}; \ No newline at end of file +] \ No newline at end of file diff --git a/src/config/filter.types.ts b/src/config/filter.types.ts index 8e700d8..f3fb284 100644 --- a/src/config/filter.types.ts +++ b/src/config/filter.types.ts @@ -22,7 +22,7 @@ export enum CategoryTargetData { OWNERSHIP_PATH = 22, PURCHASE_BEHAVIOR = 31, PURCHASE_CHANNEL = 32, - PURCHASE_FORMAT = 14, + PAYMENT_METHOD = 14, } export type CategoryTargetTypeItem = { diff --git a/src/config/menu.data.ts b/src/config/menu.data.ts index 5b9e91c..d10eeb5 100644 --- a/src/config/menu.data.ts +++ b/src/config/menu.data.ts @@ -10,7 +10,7 @@ export const topMenus: TopMenuItem[] = [ { id: "category", label: "카테고리", - path: "/category/ha-kitchen/profile", + path: "/category/ha-kitchen", match: (pathname) => pathname.startsWith("/category"), }, ]; diff --git a/src/config/sample.data.ts b/src/config/sample.data.ts index d64455b..77cf207 100644 --- a/src/config/sample.data.ts +++ b/src/config/sample.data.ts @@ -154,7 +154,6 @@ const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number return out; }; -/** ✅ 그룹 키 정의(각 그룹 합 100) */ const BANNER_GROUPS: Record = { lifeStage: ["single", "noKids", "preschoolKids", "schoolKids", "adultKids", "independentSenior"], household: ["hh1", "hh2", "hh3", "hh4Plus"], @@ -202,7 +201,7 @@ export const bannerRow = ( year, rowLabel, total, - ...makeBannerDistDefault(`${year}|${rowLabel}`, range), // ✅ min/max 적용 + ...makeBannerDistDefault(`${year}|${rowLabel}`, range), ...(extra ?? {}), }); @@ -305,9 +304,9 @@ export const apiOwnershipSummary: ServerBannerRow[] = [ * -------------------------- */ export const apiYearIndex: ServerBannerRow[] = [ bannerRow(26, "사례수", 2000), - bannerRow(26, "26", 100), - bannerRow(25, "25", 100), - bannerRow(24, "24", 100), + bannerRow(26, "26", 15), + bannerRow(25, "25", 14), + bannerRow(24, "24", 13), ]; /** --------------------------- @@ -361,7 +360,7 @@ export const apiFridgeDoorTypeByYear: ServerBannerRow[] = [ * year rowLabel total banner * 25/26 사례수 + 보유 경로(구매 경로) * -------------------------- */ -export const apiPurchasePathByYear: ServerBannerRow[] = [ +export const apiOwnershipPathByYear: ServerBannerRow[] = [ bannerRow(25, "사례수", 520), bannerRow(25, "신규 구입", 8), bannerRow(25, "기존 제품 작동하나 신규 구입", 4), @@ -375,6 +374,30 @@ export const apiPurchasePathByYear: ServerBannerRow[] = [ bannerRow(26, "추가 구입", 48), ]; +export const apiOwnershipTriggerByYear: ServerBannerRow[] = [ + bannerRow(25, "사례수", 520), + bannerRow(25, "오래되어 새로운 제품 교체 필요", 23), + bannerRow(25, "이사로 인해 새로 구입", 22), + bannerRow(25, "이전 제품 고장으로 새로 구입", 17), + bannerRow(25, "새로운 기능/기술 사용하고 싶어서", 14), + bannerRow(25, "리모델링, 인테리어 계기로 새로 구입", 7), + bannerRow(25, "혼수로 장만", 7), + bannerRow(25, "(결혼 외) 가구 분가/독립하게 되어서", 6), + bannerRow(25, "가구 구성원이 늘어서", 3), + bannerRow(25, "가구 구성원이 줄어서", 2), + + bannerRow(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 diff --git a/src/const/chartConst.ts b/src/const/chartConst.ts new file mode 100644 index 0000000..86648cb --- /dev/null +++ b/src/const/chartConst.ts @@ -0,0 +1,139 @@ +/** + * 차트 관련 상수 정의 + * - 차트 높이, 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; diff --git a/src/const/lgConst.ts b/src/const/lgConst.ts index 6e5b4b4..99e3b2a 100644 --- a/src/const/lgConst.ts +++ b/src/const/lgConst.ts @@ -1,3 +1,5 @@ +import {BannerKey} from "@/types/lg"; + export const PRODUCT_KEY_MAP = { washingMachine: "세탁기", refrigerator: "냉장고", @@ -92,6 +94,7 @@ export const BANNER_KEY_MAP = { export const PRODUCT_KEYS = Object.keys(PRODUCT_KEY_MAP) as Array; export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array; export const YEARS = [24, 25, 26]; +export const LAST_YEAR = YEARS.at(-1); export const BRAND_LIST = ['Cbrand', 'Samsung', 'LG']; /** X 축 패딩 없앤 GridOption*/ @@ -151,4 +154,58 @@ export const PRODUCTS_FILTER_ITEM = [ PRODUCT_KEY_MAP.projector, // 빔프로젝터 ], }, -] as const; \ No newline at end of file +] 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; \ No newline at end of file diff --git a/src/hooks/useStorage.ts b/src/hooks/useStorage.ts index 977f591..b7852f9 100644 --- a/src/hooks/useStorage.ts +++ b/src/hooks/useStorage.ts @@ -14,10 +14,10 @@ import { StorageKey, StorageType } from "@/store/storage/storage-keys"; * 사용법: * const { set, get, remove } = useStorage(StorageKeys.SeatNumber); */ -export const useStorage = (key: StorageKey) => { +export const useStorage = (key: StorageKey) => { const storageType = StorageType[key]; // "local" | "session" - const set = (value: any): void => { + const set = (value: T): void => { if (storageType === "session") { setSessionStorage(key, value); } else { @@ -25,7 +25,7 @@ export const useStorage = (key: StorageKey) => { } }; - const get = (): any => { + const get = (): T => { if (storageType === "session") { return getSessionStorage(key); } else { diff --git a/src/lib/chart-options.ts b/src/lib/chart-options.ts new file mode 100644 index 0000000..56dadc7 --- /dev/null +++ b/src/lib/chart-options.ts @@ -0,0 +1,232 @@ +import { CHART_GRID_DEFAULTS, BAR_WIDTHS } from "@/const/chartConst"; +import {ChartData, NewNumber} from "@/components/lge-dashboard"; + +export function reverseCategories(data: T): T { + const categories = [...data.categories].reverse(); + + const series = data.series.map((s) => ({ + ...s, + data: [...s.data].reverse(), + })); + + return { ...data, categories, series }; +} + +export function reverseSeries(data: T): T { + return { + ...data, + series: [...data.series].reverse(), + }; +} + +/** + * 기본 Tooltip 옵션 생성 + * @param valueFormatter - 값 포맷터 함수 (기본값: 정수는 그대로, 소수는 toLocaleString) + * @param overrides - 추가/덮어쓸 옵션 + */ +export function createDefaultTooltip( + valueFormatter?: (v: number) => string, + overrides?: any +): any { + const defaultFmt = (v: number) => + Number.isInteger(v) ? String(v) : v.toLocaleString(); + + return { + trigger: "axis", + axisPointer: { type: "shadow" }, + valueFormatter: (v: unknown) => + typeof v === "number" ? (valueFormatter ?? defaultFmt)(v) : String(v), + ...overrides, + }; +} + +/** + * 기본 Legend 옵션 생성 + * @param overrides - 추가/덮어쓸 옵션 + */ +export function createDefaultLegend( + overrides?: any +): any { + return { + top: 0, + ...overrides, + }; +} + +export function createReverseLegend( + originalData: ChartData, + overrides?: any +): any { + const order = originalData.series.map((s) => s.name); + + return createDefaultLegend({ + data: order, // ✅ legend 표시 순서 고정(원본) + ...overrides, + }); +} + +export function createReverseTooltip( + originalData: ChartData, + valueFormatter?: (v: number) => string, + overrides?: any +): any { + const order = originalData.series.map((s) => s.name); + + // 기본 tooltip 생성(내부 defaultFmt 포함) + const base = createDefaultTooltip(valueFormatter, overrides); + const fmt = base.valueFormatter ?? ((v: unknown) => String(v)); + + const extractVal = (p: any): unknown => { + const v = p?.value; + if (typeof v === "number") return v; + if (Array.isArray(v)) return v[v.length - 1]; // dataset/encode 케이스 대비 + if (typeof p?.data === "number") return p.data; + if (p?.data && typeof p.data.value === "number") return p.data.value; + return v; + }; + + return { + ...base, + formatter: (params: any) => { + const arr = Array.isArray(params) ? params : [params]; + if (arr.length === 0) return ""; + + const title = arr[0]?.axisValueLabel ?? arr[0]?.name ?? ""; + + const byName = new Map(); + for (const p of arr) byName.set(p.seriesName, p); + + const lines = order + .map((name) => byName.get(name)) + .filter(Boolean) + .map((p) => { + const v = extractVal(p); + const printed = + typeof v === "number" ? fmt(v) : v == null ? "-" : String(v); + return `${p.marker ?? ""}${p.seriesName} ${printed}`; + }); + + return [title, ...lines].join("
"); + }, + }; +} + +/** + * 기본 Grid 옵션 생성 + * @param preset - 프리셋 타입 (default | compact) + * @param overrides - 추가/덮어쓸 옵션 + */ +export function createDefaultGrid( + preset: "default" | "compact" = "default", + overrides?: any +): any { + const base = + preset === "compact" + ? CHART_GRID_DEFAULTS.COMPACT + : CHART_GRID_DEFAULTS.DEFAULT; + + return { + ...base, + ...overrides, + }; +} + +/** + * Category Axis 옵션 생성 + * @param data - 카테고리 데이터 배열 + * @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등) + * @param overrides - 추가/덮어쓸 옵션 + */ +export function createCategoryAxis( + data: string[], + hideStyle?: boolean, + overrides?: any +): any { + const base: any = { + type: "category", + data, + }; + + if (hideStyle) { + return { + ...base, + axisLabel: { show: false }, + axisTick: { show: false }, + axisLine: { show: false }, + splitLine: { show: false }, + ...overrides, + }; + } + + return { + ...base, + ...overrides, + }; +} + +/** + * Value Axis 옵션 생성 + * @param hideStyle - 축 스타일 숨김 여부 (라벨, 틱, 라인 등) + * @param overrides - 추가/덮어쓸 옵션 + */ +export function createValueAxis( + hideStyle?: boolean, + overrides?: any +): any { + const base: any = { + type: "value", + }; + + if (hideStyle) { + return { + ...base, + axisLabel: { show: false }, + axisTick: { show: false }, + axisLine: { show: false }, + splitLine: { show: false }, + ...overrides, + }; + } + + return { + ...base, + ...overrides, + }; +} + +/** + * Bar 시리즈 기본 옵션 생성 + * @param name - 시리즈 이름 + * @param data - 데이터 배열 + * @param options - 추가 옵션 (stack, barMaxWidth 등) + */ +export function createBarSeries( + name: string, + data: NewNumber[], + options?: { + stack?: string; + barMaxWidth?: number; + emphasis?: boolean; + label?: object; + } +): { + name: string; + type: "bar"; + data: NewNumber[]; + stack?: string; + barMaxWidth?: number; + emphasis?: { disabled: boolean }; + label?: object; +} { + const { stack, barMaxWidth, emphasis = false, label } = options ?? {}; + + return { + name, + type: "bar", + data, + ...(stack && { stack }), + barMaxWidth: barMaxWidth ?? BAR_WIDTHS.DEFAULT, + emphasis: { disabled: !emphasis }, + ...(label && { label }), + }; +} diff --git a/src/lib/lg-dashboard.ts b/src/lib/lg-dashboard.ts new file mode 100644 index 0000000..4662cd1 --- /dev/null +++ b/src/lib/lg-dashboard.ts @@ -0,0 +1,269 @@ +import {BannerGroupKey, ServerBannerRow} from "@/types/lg"; +import {ChartData} from "@/components/lge-dashboard"; +import {BANNER_GROUP} from "@/const/lgConst"; + +export const isSampleRow = (raw: string) => raw.replace(/\s+/g, "") === "사례수"; + +/** + * Row Label을 표시용 텍스트로 포맷팅합니다. + * - "사례수" -> "(사례수)" + * - "gap" -> "전년 대비 GAP(%)" + * - "CAGR" -> "CAGR(%)" + * - "24" -> "24년" + * - "보급율" -> "보급율(%)" + * - 기타 -> 원본 그대로 + */ +export function formatRowLabel( + label: string, + options?: { + convertSample?: boolean; // "사례수" -> "(사례수)" (기본값: true) + convertGap?: boolean; // "gap" -> "전년 대비 GAP(%)" (기본값: true) + convertCagr?: boolean; // "CAGR" -> "CAGR(%)" (기본값: true) + convertYear?: boolean; // "24" -> "24년" (기본값: true) + convertRate?: boolean; // "~율" -> "~율(%)" (기본값: true) + convertCount?: boolean; // "~대수" -> "~대수(대)" (기본값: true) + } +): string { + const { + convertSample = true, + convertGap = true, + convertCagr = true, + convertYear = true, + convertRate = true, + convertCount = true, + } = options ?? {}; + + const t = label.trim(); + + if (convertSample && t === "사례수") return "(사례수)"; + if (convertGap && t.toLowerCase() === "gap") return "전년 대비 GAP(%)"; + if (convertCagr && t.toUpperCase() === "CAGR") return "CAGR(%)"; + if (convertYear && /^\d{2}$/.test(t)) return `${t}년`; + if (convertRate && t.endsWith("율")) return `${t}(%)`; + if (convertCount && t.includes("대수")) return `${t}(대)`; + + return t; +} + +/** + * 연도 배열로부터 연도 -> 인덱스 맵을 생성합니다. + * @param years - 연도 배열 (예: [2024, 2025, 2026]) + * @returns Map<연도, 인덱스> + */ +export function createYearIndexMap(years: number[]): Map { + return new Map(years.map((y, i) => [y, i])); +} + +/** + * 연도 필터링: 지정된 연도 배열에 포함되고 rowLabel이 "년"으로 끝나는 행만 반환 + * @param data - 필터링할 데이터 배열 + * @param years - 허용할 연도 배열 + * @returns 필터링된 데이터 배열 + */ +export function filterYearRows( + data: T[], + years: number[] +): T[] { + return data.filter((r) => years.includes(r.year) && r.rowLabel.endsWith("년")); +} + +/** + * GroupedOverlayBarData 구조를 생성합니다. + * @param params - 데이터 생성 파라미터 + * @returns GroupedOverlayBarData 구조 + */ +export function buildOverlayBarData(params: { + totalRows: T[]; + focusRows: T[]; + productKeys: string[]; + years: number[]; + totalName?: string; + focusName?: string; +}): { + years: number[]; + categories: string[]; + totalData: Array>; + focusData: Array>; + totalName: string; + focusName: string; +} { + const { + totalRows, + focusRows, + productKeys, + years, + totalName = "전체", + focusName = "LG", + } = params; + + const yearIndexMap = createYearIndexMap(years); + const total: Array> = years.map(() => Array(productKeys.length).fill(0)); + const focus: Array> = years.map(() => Array(productKeys.length).fill(0)); + + // totalRows에서 데이터 매핑 + const filteredTotal = filterYearRows(totalRows, years); + for (const row of filteredTotal) { + const yi = yearIndexMap.get(row.year); + if (yi === undefined) continue; + + for (let pi = 0; pi < productKeys.length; pi++) { + const key = productKeys[pi]; + const val = (row as any)[key]; + if (typeof val === "number") { + total[yi][pi] = val; + } + } + } + + // focusRows에서 데이터 매핑 + const filteredFocus = filterYearRows(focusRows, years); + for (const row of filteredFocus) { + const yi = yearIndexMap.get(row.year); + if (yi === undefined) continue; + + for (let pi = 0; pi < productKeys.length; pi++) { + const key = productKeys[pi]; + const val = (row as any)[key]; + if (typeof val === "number") { + focus[yi][pi] = val; + } + } + } + + return { + years, + categories: productKeys, + totalData: total, + focusData: focus, + totalName, + focusName, + }; +} + +type Opts = { + /** 기본: ["사례수", "gap"] 제외 */ + excludeRowLabels?: string[]; + /** 기본: (y) => `${y}년` */ + yearLabel?: (y: number) => string; + /** StackBar에 넣을 때 "스택 방지"용(연도별 stack 분리) */ + splitStackByYear?: boolean; +}; + +export function buildYearSeriesChartData(rows: ServerBannerRow[], opts: Opts = {}): ChartData { + const { + excludeRowLabels = ["사례수", "gap"], + yearLabel = (y) => `${y}년`, + splitStackByYear = false, + } = opts; + + const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b); + + // rowLabel 순서: 첫 연도 기준으로 고정(없으면 전체 unique) + const baseYear = years[0]; + const baseLabels = rows + .filter((r) => r.year === baseYear) + .map((r) => r.rowLabel) + .filter((l) => !excludeRowLabels.includes(l)); + + const labels = + baseLabels.length > 0 + ? baseLabels + : Array.from( + new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l))) + ); + + // 빠른 조회용: year -> (rowLabel -> total) + const map = new Map>(); + for (const y of years) map.set(y, new Map()); + for (const r of rows) { + if (excludeRowLabels.includes(r.rowLabel)) continue; + map.get(r.year)?.set(r.rowLabel, Number(r.total ?? 0)); + } + + return { + categories: labels, + series: years.map((y) => ({ + name: yearLabel(y), + data: labels.map((lbl) => map.get(y)?.get(lbl) ?? null), + ...(splitStackByYear ? { stack: String(y) } : {}), // 같은 stack이면 "연도끼리 스택"되어버리니 방지용 + })), + }; +} + +export function buildRowLabelSeriesChartData( + rows: ServerBannerRow[], + opts: Opts = {} +): ChartData { + const { + excludeRowLabels = ["사례수", "gap"], + yearLabel = (y) => `${y}년`, + } = opts; + + const years = Array.from(new Set(rows.map((r) => r.year))).sort((a, b) => a - b); + const categories = years.map(yearLabel); + + const baseYear = years[0]; + const baseRowLabels = rows + .filter((r) => r.year === baseYear) + .map((r) => r.rowLabel) + .filter((l) => !excludeRowLabels.includes(l)); + + const rowLabels = + baseRowLabels.length > 0 + ? baseRowLabels + : Array.from( + new Set(rows.map((r) => r.rowLabel).filter((l) => !excludeRowLabels.includes(l))) + ); + + // (year -> (rowLabel -> total)) 맵 + const valueMap = new Map>(); + for (const y of years) valueMap.set(y, new Map()); + + for (const r of rows) { + if (excludeRowLabels.includes(r.rowLabel)) continue; + valueMap.get(r.year)!.set(r.rowLabel, Number(r.total ?? 0)); + } + + return { + categories, + series: rowLabels.map((lbl) => ({ + name: lbl, + data: years.map((y) => valueMap.get(y)!.get(lbl) ?? null), + })), + }; +} + +export const buildGapRow = ( + rows: ServerBannerRow[], + prevYear: number, + curYear: number, + baseRowLabel: string, + gapRowLabel = "gap" +): ServerBannerRow | null => { + const prev = rows.find(r => r.year === prevYear && r.rowLabel === baseRowLabel); + const cur = rows.find(r => r.year === curYear && r.rowLabel === baseRowLabel); + if (!prev || !cur) return null; + + const gap: ServerBannerRow = { + year: curYear, + rowLabel: gapRowLabel, + total: (typeof cur.total === "number" ? cur.total : 0) - (typeof prev.total === "number" ? prev.total : 0), + }; + + // cur가 가진 모든 key를 돌면서 "숫자 필드"면 diff 계산 + (Object.keys(cur) as Array).forEach((k) => { + if (k === "year" || k === "rowLabel") return; + + const vCur = cur[k]; + const vPrev = prev[k]; + + const hasNumber = typeof vCur === "number" || typeof vPrev === "number"; + if (!hasNumber) return; + + (gap as any)[k] = (typeof vCur === "number" ? vCur : 0) - (typeof vPrev === "number" ? vPrev : 0); + }); + + return gap; +} + +export const isBannerGroupKey = (v: string): v is BannerGroupKey => v in BANNER_GROUP; \ No newline at end of file diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 5e38fb4..baa1b54 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -99,4 +99,47 @@ export const formatKst = ( return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`; }; -export const isBlank = (v?: string | null) => !v || v.trim().length === 0; \ No newline at end of file +export const isBlank = (v?: string | null) => !v || v.trim().length === 0; + +export const norm = (s: string) => s.replace(/\s+/g, "").toLowerCase(); +export const asNum = (v: unknown): number | null => typeof v === "number" && Number.isFinite(v) ? v : null; + +export const formatNumber = (v: number) => + Number.isInteger(v) ? v.toLocaleString() : v.toLocaleString(undefined, { maximumFractionDigits: 1 }); +/** + * 다양한 형식의 값을 숫자로 파싱합니다. + * - 쉼표, 퍼센트, 유니코드 마이너스 자동 처리 + * - null/undefined/빈문자열/"−" 등은 null 반환 + * - 유한하지 않은 숫자는 null 반환 + */ +export function parseNumber( + value: unknown, + options?: { + allowComma?: boolean; // 기본값: true + allowPercent?: boolean; // 기본값: true + allowMinus?: boolean; // 기본값: true (유니코드 마이너스 포함) + } +): number | null { + const { allowComma = true, allowPercent = true, allowMinus = true } = options ?? {}; + + if (value === null || value === undefined) return null; + + if (typeof value === "number") { + return Number.isFinite(value) ? value : null; + } + + if (typeof value === "string") { + let s = value.trim(); + + if (s === "" || s === "-" || s === "−") return null; + + if (allowComma) s = s.replaceAll(",", ""); + if (allowPercent) s = s.replaceAll("%", ""); + if (allowMinus) s = s.replaceAll("−", "-"); // 유니코드 마이너스 -> ASCII 마이너스 + + const n = Number(s); + return Number.isFinite(n) ? n : null; + } + + return null; +} \ No newline at end of file diff --git a/src/store/storage/storage-keys.ts b/src/store/storage/storage-keys.ts index 1bf1c0c..9f91443 100644 --- a/src/store/storage/storage-keys.ts +++ b/src/store/storage/storage-keys.ts @@ -1,11 +1,13 @@ export const StorageKeys = { AuthState: "kri:authState", + CategoriFilter: "kri:categoryFilter", //SidebarCollapsed: "kri:sidebarCollapsed", // 필요하면 여기 계속 추가 } as const; export const StorageType: Record = { [StorageKeys.AuthState]: "local", + [StorageKeys.CategoriFilter]: "local", }; export type StorageKey = (typeof StorageKeys)[keyof typeof StorageKeys]; \ No newline at end of file diff --git a/src/types/lg.ts b/src/types/lg.ts index f0a2cc1..65e1ef3 100644 --- a/src/types/lg.ts +++ b/src/types/lg.ts @@ -1,10 +1,9 @@ -import {BANNER_KEY_MAP, PRODUCT_KEY_MAP, PRODUCTS_FILTER_ITEM} from "@/const/lgConst"; +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: number; rowLabel: string; @@ -30,4 +29,16 @@ export type LifeStageRow = Record & { schoolKids: number | null; adultKids: number | null; independentSenior: number | null; +}; + +export type BannerGroupKey = keyof typeof BANNER_GROUP; + +export type CategoryChartMode = "stack" | "reverseStack" | "horizontal"; + +export type PageData = { + title: string; + chartMode: CategoryChartMode; + data: T[]; + chartHeight?: number; + chartWidth?: number; }; \ No newline at end of file
+ {content}