Files
ecom-dmb/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/store-overview/index.vue
T
小蟑螂andClaude Opus 4.7 7761667904 refactor: 统一字段命名从 *Comparisons 改为 *Summary
后端:
- CompanyOverviewVO: shopComparisons -> shopSummary, categoryComparisons -> categorySummary
- ShopOverviewStatisticsVO: ProductComparison/CategoryComparison -> ProductSummary/CategorySummary
- CompanyOverviewServiceImpl/ShopOverviewStatisticsServiceImpl: 方法和变量重命名
- CategoryExportExcelServiceImpl, ShopExportServiceImpl: 类型引用更新

前端:
- store-overview/types/types.vo.ts: 接口重命名 ShopSummary/CategorySummary
- shop/types/types.vo.ts: 接口重命名 ProductSummary/CategorySummary
- 组件 props 从 shopComparisons/categoryComparisons 改为 shopSummary/categorySummary
- 修复 ShopComparisonTable 导出类型引用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 02:10:21 +08:00

618 lines
19 KiB
Vue
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.
<script lang="ts" setup>
import type {
CompanyOverviewDTO,
CompanyOverviewVO,
} from '#/api/ecommerce/store-overview';
import {
onActivated,
onMounted,
onUnmounted,
ref,
watch,
} from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Button, DatePicker, InputNumber, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getCompanyOverviewApi } from '#/api/ecommerce/store-overview/apis';
import { exportByPost } from '#/utils/export';
import {
applyOverviewDateRangeFromUrl,
normalizeOverviewRangePickerChange,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
import ComparisonSwitcher from './components/ComparisonSwitcher.vue';
import KpiCards from './components/KpiCards.vue';
import ShopCharts from './components/ShopCharts.vue';
defineOptions({ name: 'CompanyOverview' });
// 路由
const router = useRouter();
// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const overviewData = ref<CompanyOverviewVO.Info | null>(null);
// 指定店铺导出模式
const shopExportMode = ref(false);
const selectedExportShopIds = ref<number[]>([]);
// 指定平台导出模式
const platformExportMode = ref(false);
const selectedExportPlatformIds = ref<number[]>([]);
// 日期范围(默认:本月至今日)
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().startOf('month'),
dayjs(),
]);
// 品类导出相关
const categoryExportMode = ref(false);
const selectedExportCategoryIds = ref<number[]>([]);
const handleCategoryExportToggle = (enabled: boolean) => {
categoryExportMode.value = enabled;
selectedExportCategoryIds.value = [];
};
const handleCategoryExport = async () => {
const params = {
dateRange: dateRange.value.map((d) => d.format('YYYY-MM-DD')),
taxRate: taxRate.value,
};
if (selectedExportCategoryIds.value.length > 0) {
Object.assign(params, { categoryIds: selectedExportCategoryIds.value });
}
const [cStart, cEnd] = dateRange.value;
await exportByPost(
'/ec/store-overview/export/by-category',
params,
`全店概览_按品类汇总_${cStart.format('YYYYMMDD')}-${cEnd.format('YYYYMMDD')}.xlsx`,
);
};
// 税率(公司/店铺概览共用持久化)
const TAX_RATE_KEY = 'overview-tax-rate';
const taxRate = ref<number>(0.04);
taxRate.value = Number(localStorage.getItem(TAX_RATE_KEY)) || 0.04;
watch(taxRate, (val) => {
localStorage.setItem(TAX_RATE_KEY, String(val));
loadOverviewData();
});
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${num * 100}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday'
>('thisMonth');
// 自定义日期范围
const customDateRange = ref<[dayjs.Dayjs, dayjs.Dayjs] | undefined>([
dateRange.value[0],
dateRange.value[1],
]);
const lastRequestKey = ref('');
const isRequesting = ref(false);
// 图表引用
const shopChartsRef = ref<{ renderShopBarChart: () => void; renderShopScatterChart: () => void }>();
// 切换时间范围
const switchTimeRange = async (
type: '7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday',
) => {
activeTimeRange.value = type;
let startDate: dayjs.Dayjs;
let endDate: dayjs.Dayjs = dayjs();
switch (type) {
case '7days': {
startDate = dayjs().subtract(7, 'day');
break;
}
case '30days': {
startDate = dayjs().subtract(30, 'day');
break;
}
case 'thisMonth': {
startDate = dayjs().startOf('month');
endDate = dayjs();
break;
}
case 'custom': {
if (customDateRange.value) {
dateRange.value = customDateRange.value;
}
return;
}
case 'today': {
startDate = dayjs();
endDate = dayjs();
break;
}
case 'yesterday': {
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
}
dateRange.value = [startDate, endDate];
customDateRange.value = [startDate, endDate];
// 手动切换时间时清除请求缓存,确保强制刷新
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
// 自定义日期范围变化(同一天点两次时,antd 可能只给出开始日、结束为 null,dayjs(undefined) 会变成「今天」)
const handleCustomDateRangeChange = async (
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
dateStrings?: [string, string],
) => {
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) {
return;
}
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
const setTimeRangeTypeByDates = (
startDate: dayjs.Dayjs,
endDate: dayjs.Dayjs,
) => {
const today = dayjs();
const daysDiff = endDate.diff(startDate, 'day');
const isEndDateToday = endDate.isSame(today, 'day');
const isStartDate7DaysAgo = startDate.isSame(
dayjs().subtract(7, 'day'),
'day',
);
const isStartDate30DaysAgo = startDate.isSame(
dayjs().subtract(30, 'day'),
'day',
);
if (
isEndDateToday &&
startDate.isSame(today.startOf('month'), 'day')
) {
activeTimeRange.value = 'thisMonth';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(today, 'day')) {
activeTimeRange.value = 'today';
customDateRange.value = [startDate, endDate];
return;
}
if (daysDiff === 0 && startDate.isSame(dayjs().subtract(1, 'day'), 'day')) {
activeTimeRange.value = 'yesterday';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate7DaysAgo) {
activeTimeRange.value = '7days';
customDateRange.value = [startDate, endDate];
return;
}
if (isEndDateToday && isStartDate30DaysAgo) {
activeTimeRange.value = '30days';
customDateRange.value = [startDate, endDate];
return;
}
activeTimeRange.value = 'custom';
customDateRange.value = [startDate, endDate];
};
const applyDateRangeFromRouteQuery = () =>
applyOverviewDateRangeFromUrl(dateRange, setTimeRangeTypeByDates);
const syncDateRangeToRouteQuery = () => {
syncOverviewDateRangeToUrl(dateRange.value);
};
// 加载概览数据
const loadOverviewData = async () => {
if (isRequesting.value) return;
isRequesting.value = true;
try {
loading.value = true;
const params: CompanyOverviewDTO.Query = {
dateRange: [
dateRange.value[0].format('YYYY-MM-DD'),
dateRange.value[1].format('YYYY-MM-DD'),
],
taxRate: taxRate.value,
};
const data = await getCompanyOverviewApi(params);
overviewData.value = data;
} catch (error) {
console.error('获取全店概览数据失败:', error);
} finally {
loading.value = false;
isRequesting.value = false;
}
};
const refreshOverviewByCurrentParams = async (force = false) => {
applyDateRangeFromRouteQuery();
const requestKey = `${dateRange.value[0].format('YYYY-MM-DD')}_${dateRange.value[1].format('YYYY-MM-DD')}`;
if (!force && lastRequestKey.value === requestKey) {
return;
}
lastRequestKey.value = requestKey;
await loadOverviewData();
};
// 监听数据变化,重新渲染图表
watch(
() => overviewData.value,
() => {
if (overviewData.value) {
setTimeout(() => {
shopChartsRef.value?.renderShopBarChart();
shopChartsRef.value?.renderShopScatterChart();
}, 100);
}
},
{ deep: true },
);
// 深色模式 class 变化时重绘图表
let darkThemeObserver: MutationObserver | null = null;
onMounted(async () => {
await refreshOverviewByCurrentParams(true);
darkThemeObserver = new MutationObserver(() => {
if (overviewData.value) {
shopChartsRef.value?.renderShopBarChart();
shopChartsRef.value?.renderShopScatterChart();
}
});
darkThemeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
});
onUnmounted(() => {
darkThemeObserver?.disconnect();
darkThemeObserver = null;
});
onActivated(async () => {
await refreshOverviewByCurrentParams(true);
});
// 全店概览-按店铺汇总导出
const handleExportCompanyOverview = async () => {
try {
exportLoading.value = true;
const [startDate, endDate] = dateRange.value;
let dataToExport: CompanyOverviewVO.ShopSummary[] = [];
if (overviewData.value?.shopSummary) {
const shops = overviewData.value.shopSummary.shops;
dataToExport =
selectedExportShopIds.value.length > 0
? shops.filter((s) =>
selectedExportShopIds.value.includes(s.shopId),
)
: shops;
}
let shopIds: number[] | undefined;
if (dataToExport.length === 0) {
shopIds =
selectedExportShopIds.value.length > 0
? selectedExportShopIds.value
: undefined;
}
const filename = `全店概览_按店铺汇总_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/store-overview/export/by-shop',
{
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
shopIds,
taxRate: taxRate.value,
},
filename,
);
shopExportMode.value = false;
} finally {
exportLoading.value = false;
}
};
// 切换行选择模式
const toggleShopExportMode = (enabled: boolean) => {
shopExportMode.value = enabled;
if (!enabled) {
selectedExportShopIds.value = [];
}
};
// 切换平台导出模式
const togglePlatformExportMode = (enabled: boolean) => {
platformExportMode.value = enabled;
if (!enabled) {
selectedExportPlatformIds.value = [];
}
};
// 全店概览-按平台汇总导出
const handlePlatformExport = async () => {
try {
exportLoading.value = true;
const [startDate, endDate] = dateRange.value;
const filename = `全店概览_按平台汇总_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/ec/store-overview/export/by-platform',
{
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
platformIds: selectedExportPlatformIds.value.length > 0
? selectedExportPlatformIds.value
: undefined,
taxRate: taxRate.value,
},
filename,
);
platformExportMode.value = false;
} finally {
exportLoading.value = false;
}
};
// 跳转到店铺详情页
const navigateToShopOverview = (shopId: number) => {
router.push({
path: `/ecom/shop/overview/${shopId}`,
query: {
startDate: dateRange.value[0].format('YYYY-MM-DD'),
endDate: dateRange.value[1].format('YYYY-MM-DD'),
},
});
};
</script>
<template>
<Page
auto-content-height
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
header-class="store-overview-page-header"
>
<template #title>
<div
class="text-xl font-black tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_98%)] sm:text-2xl md:text-3xl"
>
全店铺经营概览大盘
</div>
</template>
<template #extra>
<!-- 税率 + 时间选择器 -->
<div class="flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2">
<!-- 税率输入 -->
<div
class="flex min-h-[44px] w-full items-center gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 px-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)] sm:w-auto"
>
<span class="text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">税率</span>
<InputNumber
v-model:value="taxRate"
:min="0"
:max="1"
:step="0.01"
:precision="2"
size="small"
class="tax-rate-input !h-8 !w-20 !rounded-lg !border-none !bg-white/30 dark:!bg-[hsl(240deg_3.7%_22%/30%)] !text-sm !font-bold !text-center"
:formatter="formatTaxRate"
:parser="parseTaxRate"
/>
</div>
<!-- 时间选择器容器 -->
<div
class="flex w-full flex-col gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 p-1.5 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)] sm:w-auto sm:flex-row sm:items-center sm:gap-2"
>
<!-- 快速选择按钮组 -->
<div
class="flex w-full items-center gap-1 overflow-x-auto rounded-xl bg-white/30 p-1 dark:bg-[hsl(240deg_3.7%_22%/30%)]"
>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'today'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('today')"
>
今日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'yesterday'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('yesterday')"
>
昨日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === '7days'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('7days')"
>
近7日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === '30days'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('30days')"
>
近30日
</Button>
<Button
type="text"
size="small"
class="!h-auto !min-w-0 !rounded-xl !border-none !px-3 !py-2 !text-sm !font-bold !shadow-none !transition-colors sm:!px-5"
:class="
activeTimeRange === 'thisMonth'
? '!bg-white !text-blue-600 dark:!bg-blue-900/30 dark:!text-blue-400 !shadow-sm dark:!shadow-none'
: '!bg-transparent !text-slate-600 dark:!bg-[hsl(222.34deg_10.43%_12.27%/50%)] dark:!text-[hsl(240deg_5%_64.9%)] hover:!bg-[hsl(240deg_3.7%_22%)]'
"
@click="switchTimeRange('thisMonth')"
>
本月
</Button>
</div>
<!-- 日期选择器 -->
<div class="flex w-full items-center justify-between gap-2 sm:w-auto sm:justify-start">
<span class="hidden whitespace-nowrap text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)] sm:inline">
自定义日期
</span>
<DatePicker.RangePicker
v-model:value="customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始', '结束']"
class="!h-8 !w-full !border-none !bg-transparent !text-sm !font-bold dark:!text-[hsl(240deg_5%_64.9%)] sm:!w-[220px]"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</div>
</template>
<Spin :spinning="loading">
<div class="mx-auto w-full space-y-6">
<!-- 第一层:核心汇总指标 -->
<KpiCards :overview-data="overviewData" :tax-rate="taxRate" />
<!-- 第二层:深度分析图表 -->
<ShopCharts
ref="shopChartsRef"
:shop-sales-ratios="overviewData?.shopSalesRatios"
:shop-summary="overviewData?.shopSummary"
:sales-amount-trend="overviewData?.salesAmountTrend"
:order-count-trend="overviewData?.orderCountTrend"
/>
<!-- 第三层:平台/店铺/品类明细切换 -->
<ComparisonSwitcher
:tax-rate="taxRate"
:platform-summary="overviewData?.platformSummary"
:platform-export-mode="platformExportMode"
:selected-export-platform-ids="selectedExportPlatformIds"
:shop-summary="overviewData?.shopSummary"
:shop-export-mode="shopExportMode"
:selected-export-shop-ids="selectedExportShopIds"
:category-summary="overviewData?.categorySummary"
:category-export-mode="categoryExportMode"
:selected-export-category-ids="selectedExportCategoryIds"
@update:selected-export-platform-ids="(ids) => (selectedExportPlatformIds = ids)"
@toggle-platform-export-mode="togglePlatformExportMode"
@platform-export="handlePlatformExport"
@update:selected-export-shop-ids="(ids) => (selectedExportShopIds = ids)"
@toggle-shop-export-mode="toggleShopExportMode"
@shop-export="handleExportCompanyOverview"
@navigate="navigateToShopOverview"
@toggle-category-export-mode="handleCategoryExportToggle"
@update:selected-export-category-ids="selectedExportCategoryIds = $event"
@category-export="handleCategoryExport"
/>
</div>
</Spin>
</Page>
</template>
<style scoped>
:deep(.tax-rate-input .ant-input-number-input) {
height: 32px;
line-height: 32px;
padding-top: 0;
padding-bottom: 0;
}
:deep(.store-overview-page-header) {
align-items: center;
}
@media (max-width: 640px) {
:deep(.store-overview-page-header) {
flex-direction: column;
align-items: stretch;
gap: 10px;
}
:deep(.store-overview-page-header > div:first-child) {
width: 100%;
}
:deep(.store-overview-page-header > div:last-child) {
width: 100%;
}
}
</style>