Files
lg-cxdash-front/src/app/(pages)/(main)/total/lg-penetration/page.tsx

272 lines
9.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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