Files
ecom-dmb/ecom-dmb-frontend/apps/web-antd/src/views/dashboard/company-overview/index.vue
T

597 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/company-overview';
import {
onActivated,
onMounted,
onUnmounted,
ref,
watch,
} from 'vue';
import { useRoute, 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/company-overview/apis';
import { getShopPageApi } from '#/api/ecommerce/shop';
import { exportByPost } from '#/utils/export';
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 route = useRoute();
// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const overviewData = ref<CompanyOverviewVO.Info | null>(null);
const shopCount = ref(0);
// 指定店铺导出模式
const shopExportMode = ref(false);
const selectedExportShopIds = ref<number[]>([]);
// 指定平台导出模式
const platformExportMode = ref(false);
const selectedExportPlatformIds = ref<number[]>([]);
// 日期范围
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().subtract(30, 'day'),
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 });
}
await exportByPost('/ec/category-overview/export', params, '品类多维度经营明细.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' | 'custom' | 'today' | 'yesterday'
>('30days');
// 自定义日期范围
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' | '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 '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];
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
// 自定义日期范围变化
const handleCustomDateRangeChange = async (
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
_dateString?: [string, string],
) => {
if (value && Array.isArray(value) && value.length === 2) {
const dates = [
dayjs.isDayjs(value[0]) ? value[0] : dayjs(value[0]),
dayjs.isDayjs(value[1]) ? value[1] : dayjs(value[1]),
] as [dayjs.Dayjs, dayjs.Dayjs];
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
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 (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 = () => {
const { endDate, startDate } = route.query;
if (!startDate || !endDate) return false;
const parsedStartDate = dayjs(startDate as string);
const parsedEndDate = dayjs(endDate as string);
if (!parsedStartDate.isValid() || !parsedEndDate.isValid()) return false;
const isSameRange =
dateRange.value[0].isSame(parsedStartDate, 'day') &&
dateRange.value[1].isSame(parsedEndDate, 'day');
if (!isSameRange) {
dateRange.value = [parsedStartDate, parsedEndDate];
}
setTimeRangeTypeByDates(parsedStartDate, parsedEndDate);
return true;
};
const syncDateRangeToRouteQuery = async () => {
const startDate = dateRange.value[0].format('YYYY-MM-DD');
const endDate = dateRange.value[1].format('YYYY-MM-DD');
if (route.query.startDate === startDate && route.query.endDate === endDate) {
return;
}
// 用 history.replaceState 直接改 URL,避免触发 Vue Router 导航和 Vben tab 重复创建
const url = new URL(window.location.href);
url.searchParams.set('startDate', startDate);
url.searchParams.set('endDate', endDate);
window.history.replaceState({}, '', url.toString());
};
// 加载店铺数量
const loadShopCount = async () => {
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1,
filters: {},
});
shopCount.value = response.total || 0;
} catch (error) {
console.error('获取店铺数量失败:', error);
}
};
// 加载概览数据
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 loadShopCount();
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.ShopComparison[] = [];
if (overviewData.value?.shopComparisons) {
dataToExport =
selectedExportShopIds.value.length > 0
? overviewData.value.shopComparisons.filter((s) =>
selectedExportShopIds.value.includes(s.shopId),
)
: overviewData.value.shopComparisons;
}
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/company-overview/export',
{
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/platform-overview/export',
{
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 title="全店铺经营概览大盘" auto-content-height class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]">
<template #description>
<div class="mt-1 text-sm font-bold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
数据范围:公司旗下所有店铺汇总统计 · 共 {{ shopCount }} 家在营店铺
</div>
</template>
<template #extra>
<!-- 税率 + 时间选择器 -->
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-2">
<!-- 税率输入 -->
<div
class="flex h-[42px] items-center gap-2 rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-200/50 dark:bg-[hsl(240deg_3.7%_15.9%/30%)] px-3"
>
<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 h-[42px] flex-col gap-2 rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-200/50 dark:bg-[hsl(240deg_3.7%_15.9%/30%)] p-1.5 sm:flex-row sm:items-center sm:gap-2"
>
<!-- 快速选择按钮组 -->
<div
class="flex items-center gap-1 overflow-x-auto rounded-xl bg-white/30 dark:bg-[hsl(240deg_3.7%_22%/30%)] p-1"
>
<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>
</div>
<!-- 日期选择器 -->
<div class="flex items-center gap-2">
<span class="hidden 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 !border-none !bg-transparent !text-sm !font-bold dark:!text-[hsl(240deg_5%_64.9%)]"
@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-comparisons="overviewData?.shopComparisons"
:shop-efficiency-quadrants="overviewData?.shopEfficiencyQuadrants"
/>
<!-- 第三层:平台/店铺/品类明细切换 -->
<ComparisonSwitcher
:tax-rate="taxRate"
:platform-summary="overviewData?.platformSummary"
:platform-export-mode="platformExportMode"
:selected-export-platform-ids="selectedExportPlatformIds"
:shop-comparisons="overviewData?.shopComparisons"
:shop-export-mode="shopExportMode"
:selected-export-shop-ids="selectedExportShopIds"
:category-comparisons="overviewData?.categoryComparisons"
: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;
}
</style>