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
@@ -0,0 +1,108 @@
/**
* 全店 / 店铺 / 商品概览共用:自定义日期范围解析与 URL 同步(与 history.replaceState 配合)。
*/
import type { Ref } from 'vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
/** 解析 RangePicker 单端;缺省或非法时返回 null(勿对缺省值调 dayjs(),undefined 会被当成「当前时刻」) */
export function parseOverviewRangePickerPart(
part: Dayjs | null | string | undefined,
dateStr?: string,
): Dayjs | null {
if (part != null && part !== '') {
const d = dayjs.isDayjs(part) ? part : dayjs(part);
return d.isValid() ? d.startOf('day') : null;
}
if (dateStr != null && String(dateStr).trim() !== '') {
const d = dayjs(dateStr);
return d.isValid() ? d.startOf('day') : null;
}
return null;
}
/**
* 规范化 RangePicker 的 change 结果(同一天点两次时 antd 可能只给出开始、结束为 null)。
*/
export function normalizeOverviewRangePickerChange(
value: [Dayjs, Dayjs] | [string, string] | null | undefined,
dateStrings?: [string, string],
): [Dayjs, Dayjs] | null {
if (!value || !Array.isArray(value) || value.length !== 2) {
return null;
}
const start = parseOverviewRangePickerPart(value[0], dateStrings?.[0]);
if (!start) {
return null;
}
let end = parseOverviewRangePickerPart(value[1], dateStrings?.[1]);
if (!end) {
end = start;
}
return [start, end];
}
const START_Q = 'startDate';
const END_Q = 'endDate';
/** 从当前地址栏读取概览日期 query(含 replaceState 写入、未反映到 Vue Router 的情况) */
export function getOverviewDateQueryFromLocation(): {
startDate: string;
endDate: string;
} | null {
const url = new URL(window.location.href);
const startDate = url.searchParams.get(START_Q);
const endDate = url.searchParams.get(END_Q);
if (startDate && endDate) {
return { startDate, endDate };
}
return null;
}
/** 将当前概览日期范围写入 URL query(replaceState,不触发 Vue Router 的 query 更新) */
export function syncOverviewDateRangeToUrl(dateRange: [Dayjs, Dayjs]): void {
const startDate = dateRange[0].format('YYYY-MM-DD');
const endDate = dateRange[1].format('YYYY-MM-DD');
const url = new URL(window.location.href);
const curStart = url.searchParams.get(START_Q);
const curEnd = url.searchParams.get(END_Q);
if (curStart === startDate && curEnd === endDate) {
return;
}
const newUrl = new URL(window.location.href);
newUrl.searchParams.set(START_Q, startDate);
newUrl.searchParams.set(END_Q, endDate);
window.history.replaceState({}, '', newUrl.toString());
}
/**
* 从当前 window.location 读取 startDate/endDate,写回 dateRange 并回调推断快捷项(本月/今日等)。
*/
export function applyOverviewDateRangeFromUrl(
dateRangeRef: Ref<[Dayjs, Dayjs]>,
onRangeFromUrl: (start: Dayjs, end: Dayjs) => void,
): boolean {
const url = new URL(window.location.href);
const startDate = url.searchParams.get(START_Q);
const endDate = url.searchParams.get(END_Q);
if (!startDate || !endDate) {
return false;
}
const parsedStartDate = dayjs(startDate);
const parsedEndDate = dayjs(endDate);
if (!parsedStartDate.isValid() || !parsedEndDate.isValid()) {
return false;
}
const isSameRange =
dateRangeRef.value[0].isSame(parsedStartDate, 'day') &&
dateRangeRef.value[1].isSame(parsedEndDate, 'day');
if (!isSameRange) {
dateRangeRef.value = [parsedStartDate, parsedEndDate];
}
onRangeFromUrl(parsedStartDate, parsedEndDate);
return true;
}
@@ -21,6 +21,11 @@ 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';
@@ -161,23 +166,21 @@ const switchTimeRange = async (
await refreshOverviewByCurrentParams();
};
// 自定义日期范围变化
// 自定义日期范围变化(同一天点两次时,antd 可能只给出开始日、结束为 null,dayjs(undefined) 会变成「今天」)
const handleCustomDateRangeChange = async (
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
_dateString?: [string, string],
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, dayjs.Dayjs];
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
const dates = normalizeOverviewRangePickerChange(value, dateStrings);
if (!dates) {
return;
}
customDateRange.value = dates;
activeTimeRange.value = 'custom';
dateRange.value = dates;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
const setTimeRangeTypeByDates = (
@@ -233,44 +236,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);
};
// 加载概览数据
@@ -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);
};
// 加载概览数据
@@ -1,5 +1,5 @@
<script lang="ts" setup>
import type { UserVO } from '#/api/system/user/types';
import type { UserDTO, UserVO } from '#/api/system/user/types';
import { computed, reactive, ref } from 'vue';
@@ -31,13 +31,12 @@ const avatarSrc = computed(() => {
return null;
});
// 表单数据
const formData = reactive({
// 表单数据(与更新接口 DTO 一致,头像 ID 用 undefined 表示未变更/未上传)
const formData = reactive<UserDTO.UpdateUserInfoDTO>({
loginCode: '',
realName: '',
phone: '',
remark: '',
avatarImageId: null as number | null,
});
const formRef = ref<any>(null);
@@ -100,6 +99,7 @@ async function handleSubmit() {
await updateUserInfoApi(formData);
message.success('保存成功');
formData.avatarImageId = undefined;
await fetchUserInfo();
} catch (error: any) {
if (error?.errorFields) {
@@ -119,6 +119,7 @@ function handleReset() {
formData.phone = userInfo.value.phone || '';
formData.remark = userInfo.value.remark || '';
}
formData.avatarImageId = undefined;
formRef.value?.resetFields();
pendingAvatarFile.value = null;
}
@@ -221,7 +222,7 @@ fetchUserInfo();
<Input
v-model:value="formData.phone"
placeholder="请输入手机号"
maxlength="11"
:maxlength="11"
/>
</Form.Item>