260202_01_ENH: route 구조 초창기 기획으로 다시 변경 및 Category 별 하위 페이지에 샘플 데이터 모두 적용

This commit is contained in:
2026-02-02 11:32:50 +09:00
parent 4b40c43962
commit 6f8e09bcf3
60 changed files with 1750 additions and 464 deletions

View File

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

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const BrandPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>Brand</div>;
}
export default BrandPage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const OwnershipPathPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>ownership path</div>;
};
export default OwnershipPathPage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const PenetrationChangePage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>PenetrationChange</div>
}
export default PenetrationChangePage

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const ProfilePage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>Profile</div>
}
export default ProfilePage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const PurchaseBehaviorPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>PurchaseBehavior</div>;
};
export default PurchaseBehaviorPage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const PurchaseChannelPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>PurchaseChannel</div>;
};
export default PurchaseChannelPage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const PurchaseFormatPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>PurchaseFormat</div>
}
export default PurchaseFormatPage;

View File

@@ -1,12 +0,0 @@
'use client'
import {useLayoutFilter} from "@/components/layout/LayoutFilterContext";
const TypeSpecPage = () => {
const { categoryValue } = useLayoutFilter();
console.log(categoryValue);
return <div>TypeSpec</div>
}
export default TypeSpecPage;

View File

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

View File

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

View File

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

View File

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

View File

@@ -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),
}));

View File

@@ -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),
}));

View File

@@ -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<boolean>(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),
}));

View File

@@ -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),
}));

View File

@@ -113,11 +113,17 @@
--lg-red-500: 341.1 95% 44.0%; /* #DB0649 */
--lg-red-400: 341.1 85% 56.0%; /* #EE2F6C */
--lg-red-300: 341.1 75% 68.0%; /* #EB7097 */
--lg-red-200: 341.1 65% 82.0%; /* #EFB3C6 */
--lg-red-100: 341.1 55% 90.0%; /* #F4D7E0 */
--lg-red-50: 341.1 45% 96.0%; /* #F9F0F3 */
--lg-pink-600: 324.7 100% 46.3%; /* #EC008B */
--lg-pink-500: 324.7 95% 56.0%; /* #F924A2 */
--lg-pink-400: 324.7 85% 66.0%; /* #F25FB5 */
--lg-pink-300: 324.7 75% 76.0%; /* #F094CA */
--lg-pink-200: 324.7 65% 86.0%; /* #F3C4DF */
--lg-pink-100: 324.7 55% 92.0%; /* #F6DFED */
--lg-pink-50: 324.7 45% 97.0%; /* #FBF4F8 */
--lg-purple-600: 263.0 65.9% 44.9%; /* #6127BE */
--lg-purple-500: 263.0 60.0% 56.0%;
@@ -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; }

View File

@@ -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) {

View File

@@ -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<void>;

View File

@@ -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<HTMLDivElement | null>(null);
const [showScrollTop, setShowScrollTop] = useState(false);
const isTotal = pathname.startsWith("/total");
const activeTop = topMenus.find((m) => m.match?.(pathname)) ?? topMenus[0];
const subMenus = isTotal ? totalSubMenus : categorySubMenus;
@@ -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<ExcelExportContext>(() => {
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 (
<div className="min-h-screen flex flex-col bg-transparent">
<LayoutFilterProvider
value={{
isTotal,
totalValue,
categoryValue,
}}
>
<div className="h-screen flex flex-col bg-transparent overflow-hidden">
<LayoutFilterProvider value={ctx} >
<Header
activeTopId={activeTop.id}
onNavigate={movePage}
@@ -121,11 +118,11 @@ const MainLayout = ({ children }: MainLayoutProps) => {
<SubMenu
subMenu={subMenus}
activeSubId={activeSub.id}
onNavigate={isTotal? movePage : moveCategoryPage}
onNavigate={movePage}
/>
<div className="flex-1 min-h-0 flex flex-col pr-4">
<div className="bg-card lg-tab-content flex-1 min-h-0">
<div className="shrink-0 flex items-center justify-between px-2 py-1">
<div className="bg-card lg-tab-content flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="shrink-0 flex items-center justify-between px-2 py-1">
<button
type="button"
onClick={toggleFilter}
@@ -150,10 +147,32 @@ const MainLayout = ({ children }: MainLayoutProps) => {
</div>
)}
<div className="flex-1 min-h-0 overflow-auto">
<div className="p-3">
<div className="relative flex-1 min-h-0">
<div
ref={scrollRef}
onScroll={onScrollContent}
className="h-full overflow-auto"
>
<div className="p-3 pb-8">
{children}
</div>
</div>
</div>
{showScrollTop && (
<button
type="button"
onClick={scrollToTop}
aria-label="위로 가기"
className={cn(
"absolute -bottom-2 right-4 z-20",
"h-8 w-8 rounded-full",
"bg-gray-900/80 text-white hover:bg-primary",
"flex items-center justify-center"
)}
>
<ArrowUp className="h-5 w-5" />
</button>
)}
</div>
</div>
</div>

View File

@@ -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}
</button>

View File

@@ -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,

View File

@@ -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
? ({

View File

@@ -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;

View File

@@ -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,

View File

@@ -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 <BaseEChart option={option} height={height} className={className} />;
}
};
export default StackBar;

View File

@@ -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,

View File

@@ -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+)?)%$/);

View File

@@ -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<keyof typeof BANNER_GROUP>;
};
/** 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<ServerBannerRow>[] => {
const columns: DataColumn<ServerBannerRow>[] = [
{
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<ServerBannerRow[]>(() => {
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<ServerBannerRow> = {
rowSelector: (row) => row.rowLabel === "gap",
display: "arrow",
arrowWithNumber: true,
paint: "text",
zeroText: "-",
};
return (
<div className="flex flex-col gap-6">
{SECTIONS.map((spec) => {
const bannerKeys = getSectionBannerKeys(spec);
const columns = buildColumns(spec);
const chartData = buildChartData(rows, bannerKeys);
return (
useChart ?
<LeftChartTable<ServerBannerRow>
key={spec.title}
title={spec.title}
columns={columns}
rows={rows}
signStyle={signStyleGap}
chart={
<HorizontalBar
data={chartData}
height="100%"
showFocusLabel="none"
legend={{ show: false }}
grid={GRID_Y_NOT_PADDING}
xAxis={{ type: "value", show: false }}
yAxis={{ type: "category", data: chartData.categories, show: false }}
/>
}
chartCell={{ key: "total", startRowIndex: 1 }}
minWidthPx={1200}
/>
:
<DataTable<ServerBannerRow>
key={spec.title}
title={spec.title}
columns={columns}
rows={rows}
signStyle={signStyleGap}
/>
);
})}
</div>
);
}
export default BannerSummary;

View File

@@ -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<ServerBannerRow> = {
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<bannerType>(banners[0]);
const buildColumns = (groupKey: BannerGroupKey): DataColumn<ServerBannerRow>[] => {
const columns: DataColumn<ServerBannerRow>[] = [
{
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 (
<div>
{title && <SectionTitle title={title} />}
<div className="flex gap-6 p-3">
<div className="flex-shrink-0" style={{ width: `${chartWidth ?? 400}px`}}>
{
chartMode === "stack" || chartMode === "reverseStack" ?
<StackBar
data={chartData}
height={`${chartHeight ?? 340}px`}
legend={createDefaultLegend({ top: 0 })}
grid={createDefaultGrid("default", { top: 52 })}
isReverse={chartMode === "reverseStack"}
/>
:
<HorizontalBar
data={chartData}
height={`${chartHeight ?? 340}px`}
showFocusLabel="none"
/>
}
</div>
<div className="flex items-center">
<BannerButtons
banners={banners}
selectedBanner={selectedBanner}
onSelectBanner={setSelectedBanner}
/>
</div>
<div className="flex-1">
<DataTable
columns={tableColumns}
rows={tableData}
signStyle={signStyleGap}
wrapperClassName="border rounded-lg"
fillGreaterThan5={fillGreaterThan5}
/>
</div>
</div>
</div>
);
};
export default CategoryByData;

View File

@@ -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<T> = {
/** 차트를 삽입할 컬럼 key(해당 컬럼 td는 startRow에서만 렌더되고 rowSpan 적용) */
@@ -33,17 +34,7 @@ type Props<T extends Record<string, unknown>> = {
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<T extends Record<string, unknown>>({
signStyle,
wrapperClassName,
tableClassName,
minWidthPx = 1200,
minWidthPx = TABLE_DIMENSIONS.MIN_WIDTH.COMPACT,
}: Props<T>) {
const hasGroupHeader = useMemo(
() => columns.some((c) => c.group) || columns.some((c) => c.headRowSpan === 2),
@@ -184,8 +175,8 @@ export default function LeftChartTable<T extends Record<string, unknown>>({
<tr key={ri}>
{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 (
<td
key={String(c.key)}
@@ -208,7 +199,7 @@ export default function LeftChartTable<T extends Record<string, unknown>>({
? 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) {

View File

@@ -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<LifeStageRow>[] = [
{ key: "item", header: "", rowHead: true, renderLabel: (r) => r.item },

View File

@@ -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) {

View File

@@ -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";

View File

@@ -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<T extends Record<string, unknown>> = {
chartData:ChartData;
tableColumns: DataColumn<T>[];
allTableData: T[];
}
const banners: bannerType[] = totalFilters.map((filter) => {
return {variable: filter.variable, variableName: filter.variableName}
})
const CategoryByData = <T extends Record<string, unknown>>({
chartData,
tableColumns,
allTableData,
}: CategoryByDataProps<T>) => {
const [selectedBanner, setSelectedBanner] = useState<bannerType>(banners[0]);
const [tableData, setTableData] = useState<T[]>([]);
useEffect(() => {
const filteredTableData = allTableData.filter((row) => row[selectedBanner.variable] === selectedBanner.variableName);
setTableData(filteredTableData);
}, [selectedBanner, allTableData]);
return (
<div className="flex gap-6 p-6">
{/* 좌측: 차트 */}
<div className="flex-shrink-0" style={{ width: "300px" }}>
<StackBar
data={chartData}
height={300}
paletteVarNames={[
"--lg-red-300",
"--lg-red-400",
"--lg-red-500",
]}
/>
</div>
{/* 중앙: 버튼 */}
<div className="flex items-center">
<BannerButtons
banners={banners}
selectedBanner={selectedBanner}
onSelectBanner={setSelectedBanner}
/>
</div>
{/* 우측: 테이블 */}
<div className="flex-1">
<DataTable
columns={tableColumns}
rows={tableData}
wrapperClassName="border rounded-lg"
/>
</div>
</div>
);
};
export default CategoryByData;

View File

@@ -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 <Profile />;
case CategoryTargetData.PENETRATION_CHANGE:
return <PenetrationChange />;
case CategoryTargetData.BRAND:
return <Brand />;
case CategoryTargetData.TYPE_SPEC:
return <TypeSpec />;
case CategoryTargetData.OWNERSHIP_PATH:
return <OwnershipPath />;
case CategoryTargetData.PURCHASE_BEHAVIOR:
return <PurchaseBehavior />;
case CategoryTargetData.PURCHASE_CHANNEL:
return <PurchaseChannel />;
case CategoryTargetData.PAYMENT_METHOD:
return <PaymentMethod />;
default:
return null;
}
};
return renderPage();
}
export default CategoryPage;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => {
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 (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default Brand;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => [
{title: "보유 경로", chartMode:"reverseStack", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
], []);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default OwnershipPath;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => [
{title: "구매 형식", chartMode:"reverseStack", data: apiPaymentMethodByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
], []);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default PaymentMethod;

View File

@@ -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<ServerBannerRow[]>([]);
useEffect(() => {
setPenetrationChangeData(apiYearIndex)
},[])
return(
<BannerSummary data={penetrationChangeData} useChart={true} />
);
}
export default PenetrationChange

View File

@@ -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<ServerBannerRow[]>([]);
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 (
<BannerSummary data={profileData} useChart={false} />
);
}
export default Profile;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => [
{title: "보유 경로", chartMode:"horizontal", data: apiOwnershipPathByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
{title: "구입 계기", chartMode:"horizontal", data: apiOwnershipTriggerByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap"))},
], []);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
};
export default PurchaseBehavior;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => [
{
title: "구매 채널",
chartMode: "horizontal",
data: apiPurchaseChannelByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")),
chartHeight: 550,
},
], []);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default PurchaseChannel;

View File

@@ -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<PageData<ServerBannerRow>[]>(() => [
{
title: "타입",
chartMode: "horizontal",
data: apiFridgeDoorTypeByYear.filter(r => !(r.year === 26 && r.rowLabel === "gap")),
},
], []);
return (
<div>
{tableDataArray.map((tableData) => (
<CategoryByData
key={`cbd-${tableData.title.replaceAll(/\s+/g, "_")}`}
title={tableData.title}
chartMode={tableData.chartMode}
allTableData={tableData.data}
chartHeight={tableData.chartHeight}
chartWidth={tableData.chartWidth}
/>
))}
</div>
);
}
export default TypeSpec;

View File

@@ -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<T extends Record<string, unknown>> = {
columns: DataColumn<T>[];
rows: T[];
title?: string;
className?: string;
wrapperClassName?: string;
signStyle?: SignStyle<T>;
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 = <T extends Record<string, unknown>>({
columns,
rows,
className,
wrapperClassName,
signStyle,
}: Props<T>) => {
columns,
rows,
title,
className,
wrapperClassName,
signStyle,
fillGreaterThan5 = false,
}: Props<T>) => {
const hasGroup = columns.some((c) => !!c.group) || columns.some((c) => c.headRowSpan === 2);
// group header(1행): rowspan=2 컬럼(th) + group label(colspan)
const groupCells = useMemo(() => {
type GroupCell =
| { kind: "rowspan"; label: string; colSpan: 1; rowSpan: 2; className?: string }
| { kind: "group"; label: string; colSpan: number; rowSpan: 1; className?: string }
| { kind: "blank"; label: string; colSpan: 1; rowSpan: 1; className?: string };
| { 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 = <T extends Record<string, unknown>>({
return (
<div className={cn("w-full overflow-x-auto", wrapperClassName)}>
{title && (
<SectionTitle title={title} />
)}
<table className={cn("lg-table", className)}>
<thead>
{hasGroup && (
@@ -178,6 +172,7 @@ const DataTable = <T extends Record<string, unknown>>({
<tbody>
{rows.map((row, rIdx) => {
const signRow = isSignRow(row, rIdx);
const total = parseNumber(row.total);
return (
<tr key={rIdx}>
@@ -191,7 +186,7 @@ const DataTable = <T extends Record<string, unknown>>({
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 = <T extends Record<string, unknown>>({
);
}
const numContent = c.numeric ? parseNumber(content) ?? 0 : 0;
const isFill = fillGreaterThan5 && total && numContent > total + 5;
return (
<td key={String(c.key)} style={{ textAlign: align }} className={c.cellClassName}>
<td key={String(c.key)} style={{ textAlign: align }} className={
cn(c.cellClassName, isFill? "bg-red-200" :"")
}>
{content}
</td>
);

View File

@@ -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<T extends Record<string, unknown>> = {
@@ -24,14 +24,7 @@ type Props<T extends Record<string, unknown>> = {
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 = <T extends Record<string, unknown>>({
columns,
@@ -130,7 +123,7 @@ const GaugeTable = <T extends Record<string, unknown>>({
}
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;

View File

@@ -124,6 +124,7 @@ export const signStyleGapRow: SignStyle<TopChartTableRow> = {
arrowWithNumber: true,
paint: "text",
};
/** ChartLabel 보여지는 옵션 */
export type ShowLabel = "none" | "all" | "last" | "first";

View File

@@ -8,7 +8,7 @@ import {
export const totalFilters:TotalFilterItem[] = [
{
variable:"a1",
variable:"lifeStage",
variableName:"라이프 스테이지",
children:[
{ value: "0", label: "전체"},
@@ -21,7 +21,7 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a2",
variable:"income",
variableName:"월 소득 규모",
children:[
{ value: "0", label: "전체"},
@@ -32,8 +32,8 @@ export const totalFilters:TotalFilterItem[] = [
]
},
{
variable:"a3",
variableName:"거주 형태",
variable:"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, string> = {
[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",
};
]

View File

@@ -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 = {

View File

@@ -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"),
},
];

View File

@@ -154,7 +154,6 @@ const splitTo100 = (r: () => number, n: number, minEach: number, maxEach: number
return out;
};
/** ✅ 그룹 키 정의(각 그룹 합 100) */
const BANNER_GROUPS: Record<string, BannerKey[]> = {
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

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

@@ -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;

View File

@@ -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<keyof typeof PRODUCT_KEY_MAP>;
export const PRODUCTS = Object.values(PRODUCT_KEY_MAP) as Array<string>;
export const YEARS = [24, 25, 26];
export const LAST_YEAR = YEARS.at(-1);
export const BRAND_LIST = ['Cbrand', 'Samsung', 'LG'];
/** X 축 패딩 없앤 GridOption*/
@@ -151,4 +154,58 @@ export const PRODUCTS_FILTER_ITEM = [
PRODUCT_KEY_MAP.projector, // 빔프로젝터
],
},
] as const;
] 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;

View File

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

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

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

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

@@ -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<number, number> {
return new Map<number, number>(years.map((y, i) => [y, i]));
}
/**
* 연도 필터링: 지정된 연도 배열에 포함되고 rowLabel이 "년"으로 끝나는 행만 반환
* @param data - 필터링할 데이터 배열
* @param years - 허용할 연도 배열
* @returns 필터링된 데이터 배열
*/
export function filterYearRows<T extends { year: number; rowLabel: string }>(
data: T[],
years: number[]
): T[] {
return data.filter((r) => years.includes(r.year) && r.rowLabel.endsWith("년"));
}
/**
* GroupedOverlayBarData 구조를 생성합니다.
* @param params - 데이터 생성 파라미터
* @returns GroupedOverlayBarData 구조
*/
export function buildOverlayBarData<T extends { year: number; rowLabel: string }>(params: {
totalRows: T[];
focusRows: T[];
productKeys: string[];
years: number[];
totalName?: string;
focusName?: string;
}): {
years: number[];
categories: string[];
totalData: Array<Array<number>>;
focusData: Array<Array<number>>;
totalName: string;
focusName: string;
} {
const {
totalRows,
focusRows,
productKeys,
years,
totalName = "전체",
focusName = "LG",
} = params;
const yearIndexMap = createYearIndexMap(years);
const total: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
const focus: Array<Array<number>> = years.map(() => Array(productKeys.length).fill(0));
// totalRows에서 데이터 매핑
const filteredTotal = filterYearRows(totalRows, years);
for (const row of filteredTotal) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
total[yi][pi] = val;
}
}
}
// focusRows에서 데이터 매핑
const filteredFocus = filterYearRows(focusRows, years);
for (const row of filteredFocus) {
const yi = yearIndexMap.get(row.year);
if (yi === undefined) continue;
for (let pi = 0; pi < productKeys.length; pi++) {
const key = productKeys[pi];
const val = (row as any)[key];
if (typeof val === "number") {
focus[yi][pi] = val;
}
}
}
return {
years,
categories: productKeys,
totalData: total,
focusData: focus,
totalName,
focusName,
};
}
type Opts = {
/** 기본: ["사례수", "gap"] 제외 */
excludeRowLabels?: string[];
/** 기본: (y) => `${y}년` */
yearLabel?: (y: 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<number, Map<string, number>>();
for (const y of years) map.set(y, new Map());
for (const r of rows) {
if (excludeRowLabels.includes(r.rowLabel)) continue;
map.get(r.year)?.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories: labels,
series: years.map((y) => ({
name: yearLabel(y),
data: labels.map((lbl) => map.get(y)?.get(lbl) ?? null),
...(splitStackByYear ? { stack: String(y) } : {}), // 같은 stack이면 "연도끼리 스택"되어버리니 방지용
})),
};
}
export function buildRowLabelSeriesChartData(
rows: 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<number, Map<string, number>>();
for (const y of years) valueMap.set(y, new Map());
for (const r of rows) {
if (excludeRowLabels.includes(r.rowLabel)) continue;
valueMap.get(r.year)!.set(r.rowLabel, Number(r.total ?? 0));
}
return {
categories,
series: rowLabels.map((lbl) => ({
name: lbl,
data: years.map((y) => valueMap.get(y)!.get(lbl) ?? null),
})),
};
}
export const buildGapRow = (
rows: 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<keyof ServerBannerRow>).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;

View File

@@ -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;
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;
}

View File

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

View File

@@ -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<string, unknown> & {
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<T> = {
title: string;
chartMode: CategoryChartMode;
data: T[];
chartHeight?: number;
chartWidth?: number;
};