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

187 lines
6.6 KiB
TypeScript

"use client";
import {useEffect, useMemo} from "react";
import {
PRODUCT_KEYS,
} from "@/const/lg-product.const";
import { PRODUCT_KEY_MAP } from "@/const/lg-schema.const";
import {
API_DECIMAL_POINT,
SITE_TITLE,
USE_CACHE,
YEARS,
} from "@/const/lg-common.const";
import { CHART_COLOR_BY_YEAR, CHART_FOCUS_COLOR_BY_YEAR } from "@/components/lge-dashboard/chart/chart.config";
import {
BottomDescription,
GroupedOverlayBar,
type GroupedOverlayBarData,
signStyleGapRow,
TopChartTable,
type TopChartTableRow,
} from "@/components/lge-dashboard";
import { useLayoutFilter } from "@/components/layout/LayoutFilterContext";
import {
calcGapProductRow, calcTotalBaseRow,
formatRowLabel,
normalizeFilterCondition,
withGapRow, withTotalBaseRow, wrapSampleRow
} from "@/lib/lg-dashboard";
import {buildHeader_ProductKeyMap, exportDashboardExcel} from "@/lib/lg-export-excel";
import {useDebouncedValue} from "@/hooks/useDebouncedValue";
import {SelectedMap} from "@/types/common";
import {ProductKey, StatisticsRequest} from "@/types/lg.types";
import {useProductStatisticsQuery} from "@/query/statistics";
import {toNumOr0} from "@/lib/utils";
const LGPurchasePage = () => {
const { filterValue, registerExcelExporter } = useLayoutFilter();
const debouncedFilterValue = useDebouncedValue<SelectedMap>(filterValue as SelectedMap, 500);
const req = useMemo<StatisticsRequest>(() => {
return {
variableIdMap: {purchase: "KQB0", purchase_lg: "KQX3_3_LG"},
bannerIdList: ["product"],
filterCondition: normalizeFilterCondition(debouncedFilterValue),
option: {useCache: USE_CACHE, lastYear: false, decimalPoint: API_DECIMAL_POINT },
};
}, [debouncedFilterValue]);
const {data, isError, error} = useProductStatisticsQuery(req);
if(isError){
console.error(error);
}
const purchaseRows =
data?.statisticsDataMap?.purchase
.filter((r) => r.rowLabel == `구매` || r.rowLabel == `사례수`)
.map((row) => {
const rowLabel = row.rowLabel == `사례수`? `${formatRowLabel(row.year)} ${row.rowLabel}` : row.year;
return {
...row,
rowLabel: rowLabel,
}
}) ?? [];
const purchaseLGRows =
data?.statisticsDataMap?.purchase_lg
.filter((row) => row.rowLabel === `구입` || row.rowLabel == `사례수`)
.map((row) => {
const rowLabel = row.rowLabel == `사례수`? `${formatRowLabel(row.year)} ${row.rowLabel}` : row.year;
return {
...row,
rowLabel: rowLabel,
}
}) ?? [];
const purchaseLGRowsWithGap = useMemo(() => {
const withGap = withGapRow(wrapSampleRow(purchaseLGRows, false), calcGapProductRow, -1, -3);
return withTotalBaseRow("구입율",purchaseRows, withGap, calcTotalBaseRow);
}, [purchaseRows, purchaseLGRows]);
const { includeProductKeys, productKeyMap, includeProducts } = useMemo(() => {
const included = new Set<ProductKey>();
for (const row of purchaseLGRows) {
for (const k of PRODUCT_KEYS) {
if (!included.has(k) && toNumOr0((row as any)[k]) !== 0) included.add(k);
}
}
const keys = PRODUCT_KEYS.filter((k) => included.has(k));
const map = Object.fromEntries(keys.map((k) => [k, PRODUCT_KEY_MAP[k]])) as Record<string, string>;
const products = keys.map((k) => PRODUCT_KEY_MAP[k]);
return { includeProductKeys: keys, productKeyMap: map, includeProducts: products };
}, [purchaseLGRows]);
const purchaseTableRows = useMemo<TopChartTableRow[]>(() => {
return purchaseLGRowsWithGap.map((row) => ({
label: formatRowLabel(row.rowLabel),
total: row.total,
values: includeProductKeys.map((k) => (row as any)[k] ?? null),
}));
}, [purchaseLGRowsWithGap, includeProductKeys]);
const purchaseChartData = useMemo<GroupedOverlayBarData>(() => {
const total: Array<Array<number>> = YEARS.map(() => Array(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]));
purchaseLGRows.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 = (purchaseRows[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,
};
}, [purchaseRows, purchaseLGRows, includeProducts, includeProductKeys]);
const description = useMemo(() => {
return "Q. 다음 중 귀댁에서 보유하고 계신 가전/전자 제품은 무엇입니까? 모두 선택해주세요.<br/>" +
"* 구독/렌탈/선물/경품/아파트 내 빌트인 제품을 모두 포함하여 선택해주세요.<br/>" +
"Q. 보유하고 계신 (제품)을 언제 구입하셨습니까?<br/>" +
//"* 새 상품을 선물 받은 경우, 선물 받은 연도로 입력해주세요.<br/>" +
//"** 중고 제품인 경우, 중고 제품을 구입한 연도로 입력해주세요.<br/>" +
//"*** 신규 입주 시 빌트인되어 있던 제품은 입주한 연도를 입력해주세요.<br/>" +
"Q. 보유하고 계신 (제품)의 브랜드는 어떻게 되십니까?";
}, []);
useEffect(() => {
registerExcelExporter(async () => {
const excelHeader = buildHeader_ProductKeyMap(productKeyMap);
await exportDashboardExcel({
fileName: `${SITE_TITLE}(LG제품 구매율).xlsx`,
sheetName: "LG제품 구매율",
sections: [
{ title: "LG제품 구매율", header: excelHeader, rows: purchaseLGRowsWithGap, rowGap: 1 },
],
});
});
return () => registerExcelExporter(null);
}, [registerExcelExporter, purchaseLGRowsWithGap]);
return (
<div>
<TopChartTable
title={"LG제품 구매율"}
categories={[...includeProducts]}
rows={purchaseTableRows}
chart={
<GroupedOverlayBar
data={purchaseChartData}
questionText={"구매율"}
yearTotalColor={CHART_COLOR_BY_YEAR}
yearFocusColor={CHART_FOCUS_COLOR_BY_YEAR}
showFocusLabel={"last"}
height={260}
/>
}
signStyle={signStyleGapRow}
/>
<BottomDescription description={description}/>
</div>
);
};
export default LGPurchasePage;