refactor: 提取概览日期范围工具函数,共享日期范围 URL 同步与异常处理逻辑

- 新增 utils/overview-date-range.ts:统一的概览日期范围处理(从 URL 应用、同步至 URL、normalize 日期选择器变化)
- store-overview / shop-overview / product-overview 的 TimeRangeBar 与 index.vue 均改用共享工具
- 修复同一天点击两次时日期范围 picker 值为空的异常处理
This commit is contained in:
小蟑螂
2026-05-07 15:31:53 +08:00
parent b695581377
commit a0e4fdb64d
9 changed files with 328 additions and 141 deletions
@@ -20,6 +20,7 @@ import ProductFormModal from './components/ProductFormModal.vue';
defineOptions({ name: 'ProductManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const RefreshCwIcon = createIconifyIcon('lucide:refresh-cw');
const productFormModalRef = ref();
@@ -123,6 +124,7 @@ async function handleSearchFormReset() {
}
const loading = ref(false);
const refreshLoading = ref(false);
const productList = ref<ProductVO.Info[]>([]);
const total = ref(0);
const current = ref(1);
@@ -196,7 +198,7 @@ async function handleDelete(record: ProductVO.Info) {
}
}
function refreshTable(updatedProduct?: ProductVO.Info) {
async function refreshTable(updatedProduct?: ProductVO.Info) {
if (updatedProduct) {
const index = productList.value.findIndex((p) => p.id === updatedProduct.id);
if (index !== -1) {
@@ -207,7 +209,16 @@ function refreshTable(updatedProduct?: ProductVO.Info) {
current.value = 1;
productList.value = [];
hasMore.value = true;
loadProductList(true);
await loadProductList(true);
}
async function handleRefresh() {
refreshLoading.value = true;
try {
await refreshTable();
} finally {
refreshLoading.value = false;
}
}
const handleEditingChange = async () => {
@@ -278,10 +289,23 @@ onUnmounted(() => {
<span class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
共 {{ total }} 个商品
</span>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
添加商品
</Button>
<div class="flex shrink-0 items-center gap-2">
<Button
shape="circle"
type="default"
title="刷新列表"
aria-label="刷新商品列表"
class="product-toolbar-refresh-btn"
:loading="refreshLoading"
@click="handleRefresh"
>
<RefreshCwIcon class="block h-4 w-4 shrink-0 leading-none" />
</Button>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
添加商品
</Button>
</div>
</div>
<!-- 仅列表区域滚动,用于瀑布流与触底加载 -->
<div
@@ -361,6 +385,18 @@ onUnmounted(() => {
background-color: transparent !important;
}
/* 圆形图标按钮:内容垂直水平居中(抵消 iconify 行高/基线偏移) */
.product-toolbar-refresh-btn.ant-btn {
display: inline-flex !important;
align-items: center;
justify-content: center;
padding: 0;
}
.product-toolbar-refresh-btn.ant-btn :deep(svg) {
display: block;
}
@media (max-width: 640px) {
:deep(.product-page-header) {
flex-direction: column;
@@ -1,7 +1,9 @@
<script lang="ts" setup>
import { Button, DatePicker, InputNumber } from 'ant-design-vue';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
interface Props {
modelValue: {
@@ -87,19 +89,16 @@ const switchTimeRange = (
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
dateStrings?: [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];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
}
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) return;
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
};
const handleTaxRateChange = (val: number | string | undefined) => {
@@ -1,7 +1,7 @@
<script lang="ts" setup>
import type { Dayjs } from 'dayjs';
import { computed, ref, watch } from 'vue';
import { computed, onActivated, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
@@ -15,6 +15,10 @@ import SalesTrendChart from './components/SalesTrendChart.vue';
import FinancialPanel from './components/FinancialPanel.vue';
import SpecSummaryTable from './components/SpecSummaryTable.vue';
import { getProductOverviewApi } from '#/api/ecommerce/product-overview';
import {
applyOverviewDateRangeFromUrl,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
defineOptions({ name: 'ProductOverview' });
@@ -78,15 +82,72 @@ const customDateRange = ref<[Dayjs, Dayjs] | undefined>([
dateRange.value[1],
]);
// 税率(持久化)
const lastRequestKey = ref('');
const isRequesting = ref(false);
// 税率(持久化,与全店/店铺概览共用 key)
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, () => {
fetchOverview();
loadOverviewData();
});
const setTimeRangeTypeByDates = (startDate: Dayjs, endDate: 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 timeRangeState = computed(() => ({
taxRate: taxRate.value,
@@ -95,21 +156,23 @@ const timeRangeState = computed(() => ({
dateRange: dateRange.value,
}));
// 监听子组件的时间范围变化
// 监听子组件的时间范围变化(与店铺概览一致:写 URL + 按条件刷新)
const handleTimeRangeChange = async (val: typeof timeRangeState.value) => {
taxRate.value = val.taxRate;
activeTimeRange.value = val.activeTimeRange;
customDateRange.value = val.customDateRange;
dateRange.value = val.dateRange;
await fetchOverview();
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
// 获取概览数据
async function fetchOverview() {
async function loadOverviewData() {
if (!isProductOverviewRoute() || !productId.value) return;
loading.value = true;
if (isRequesting.value) return;
isRequesting.value = true;
try {
loading.value = true;
const res = await getProductOverviewApi({
productId: productId.value,
startDate: dateRange.value[0].format('YYYY-MM-DD'),
@@ -121,19 +184,48 @@ async function fetchOverview() {
message.error(err?.message || '加载失败');
} finally {
loading.value = false;
isRequesting.value = false;
}
}
// 初始加载(依赖 route.path,避免 keep-alive 下切到店铺页仍用店铺 id 请求商品)
const refreshOverviewByCurrentParams = async (force = false) => {
if (!isProductOverviewRoute()) return;
applyDateRangeFromRouteQuery();
if (!productId.value) return;
const requestKey = `${productId.value}_${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();
};
// 监听路由(与店铺概览一致;日期 query 以 window.location 为准,见 applyOverviewDateRangeFromUrl)
watch(
() => [route.path, productId.value] as const,
([path, id]) => {
if (!/\/ecom\/product\/overview\/[^/]+\/?$/.test(path) || !id) return;
fetchOverview();
() => [
route.path,
route.params.id,
route.query.startDate,
route.query.endDate,
],
async () => {
if (!isProductOverviewRoute()) return;
await refreshOverviewByCurrentParams();
},
{ immediate: true },
);
onMounted(async () => {
if (!isProductOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
onActivated(async () => {
if (!isProductOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
// 计算 page title 用 productName
const pageTitle = computed(() => overviewData.value?.productName || '商品概览');
</script>
@@ -163,7 +255,7 @@ const pageTitle = computed(() => overviewData.value?.productName || '商品概
</template>
<Spin :spinning="loading">
<div v-if="overviewData" class="mx-auto w-full space-y-6 p-4 md:p-8">
<div v-if="overviewData" class="mx-auto w-full space-y-6">
<!-- 第一层:核心统计卡片 -->
<StatCards :data="overviewData" :loading="loading" />
@@ -4,6 +4,8 @@ import { useRouter } from 'vue-router';
import { Button } from 'ant-design-vue';
import { getOverviewDateQueryFromLocation } from '#/utils/overview-date-range';
interface Props {
data: ShopVO.OverviewStatistics | null;
taxRate: number;
@@ -18,6 +20,15 @@ const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const router = useRouter();
function goToProductOverview(productId: number) {
const q = getOverviewDateQueryFromLocation();
router.push(
q
? { path: `/ecom/product/overview/${productId}`, query: q }
: { path: `/ecom/product/overview/${productId}` },
);
}
const formatAmount = (amount: number) => `¥${amount.toLocaleString('zh-CN')}`;
const formatPercentPlain = (value: number | undefined) => {
@@ -134,7 +145,7 @@ const formatPercentPlain = (value: number | undefined) => {
<td
class="sticky-col border-r-2 border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white dark:bg-[hsl(222.34deg_10.43%_12.27%)] px-6 py-6 font-bold text-slate-900 dark:text-[hsl(0deg_0%_95%)] cursor-pointer hover:text-blue-600 dark:text-blue-400 hover:underline"
style="left: 0; position: sticky; z-index: 10;"
@click="router.push(`/ecom/product/overview/${product.productId}`)"
@click="goToProductOverview(product.productId)"
>
<div>{{ product.productName }}</div>
<div
@@ -1,7 +1,9 @@
<script lang="ts" setup>
import { Button, DatePicker, InputNumber } from 'ant-design-vue';
import dayjs from 'dayjs';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
interface Props {
modelValue: {
@@ -87,19 +89,16 @@ const switchTimeRange = (
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
dateStrings?: [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];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
}
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) return;
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: 'custom',
dateRange: dates,
customDateRange: dates,
});
};
const handleTaxRateChange = (val: number | string | undefined) => {
@@ -17,6 +17,10 @@ import dayjs from 'dayjs';
import { getShopOverviewStatisticsApi } from '#/api/ecommerce/shop';
import { exportByPost } from '#/utils/export';
import {
applyOverviewDateRangeFromUrl,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
import TimeRangeBar from './components/TimeRangeBar.vue';
import StatCards from './components/StatCards.vue';
@@ -150,44 +154,11 @@ const setTimeRangeTypeByDates = (
customDateRange.value = [startDate, endDate];
};
const applyDateRangeFromRouteQuery = () => {
// 用 window.location 而非 route.query,因为 syncDateRangeToRouteQuery 用的是 history.replaceState
const url = new URL(window.location.href);
const startDate = url.searchParams.get('startDate');
const endDate = url.searchParams.get('endDate');
if (!startDate || !endDate) return false;
const applyDateRangeFromRouteQuery = () =>
applyOverviewDateRangeFromUrl(dateRange, setTimeRangeTypeByDates);
const parsedStartDate = dayjs(startDate);
const parsedEndDate = dayjs(endDate);
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');
// 从 window.location 读取(history.replaceState 不会更新 route.query)
const url = new URL(window.location.href);
const curStart = url.searchParams.get('startDate');
const curEnd = url.searchParams.get('endDate');
if (curStart === startDate && curEnd === endDate) {
return;
}
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('startDate', startDate);
newUrl.searchParams.set('endDate', endDate);
window.history.replaceState({}, '', newUrl.toString());
const syncDateRangeToRouteQuery = () => {
syncOverviewDateRangeToUrl(dateRange.value);
};
// 加载概览数据