feat: 商品详情页功能完成

后端:
- ProductOverviewController POST /ec/product/overview
- ProductOverviewQueryDTO / ProductOverviewVO (productId + 7个统计字段)
- ProductOverviewServiceImpl

前端:
- ProductCard 添加统计入口,goToDetails 改用 path 导航
- /api/ecommerce/product-overview/ 接口定义
- views/ecommerce/product/details/ 商品详情页 + OverviewTab (7个ChartCard)

数据库:
- sys_menu id=43 parent_id 从 8 改为 6
This commit is contained in:
小蟑螂
2026-04-11 23:58:28 +08:00
parent bd9916fa99
commit 92a6175edb
18 changed files with 1059 additions and 157 deletions
@@ -38,13 +38,14 @@ export async function getImportTaskPageApi(
}
/**
* SSE连接管理器(使用fetch API支持自定义请求头)
* SSE连接管理器(使用原生EventSource,支持自动重连)
*/
class SseConnection {
private abortController: AbortController | null = null;
private eventSource: EventSource | null = null;
private accessStore: ReturnType<typeof useAccessStore>;
private listeners: Map<string, Set<(event: MessageEvent) => void>> =
new Map();
// EventSource 原生状态常量
private readyState: number = EventSource.CLOSED;
constructor() {
@@ -52,20 +53,38 @@ class SseConnection {
}
/**
* 添加事件监听器
* 添加事件监听器(需在 connect 之前调用)
*/
addEventListener(eventType: string, handler: (event: MessageEvent) => void) {
if (!this.listeners.has(eventType)) {
this.listeners.set(eventType, new Set());
}
this.listeners.get(eventType)!.add(handler);
// 如果 EventSource 已建立,额外绑定一次(防止在 connect 之后调用 listener 漏掉)
if (this.eventSource) {
this.eventSource.addEventListener(eventType, handler as EventListener);
}
}
/**
* 建立SSE连接(使用fetch API)
* 移除事件监听器
*/
removeEventListener(eventType: string, handler: (event: MessageEvent) => void) {
const handlers = this.listeners.get(eventType);
if (handlers) {
handlers.delete(handler);
}
if (this.eventSource) {
this.eventSource.removeEventListener(eventType, handler as EventListener);
}
}
/**
* 建立SSE连接
* EventSource 原生支持自动重连,无需手动实现
*/
connect(): void {
if (this.abortController) {
if (this.eventSource) {
this.disconnect();
}
@@ -75,79 +94,37 @@ class SseConnection {
return;
}
const url = `${apiURL}/ec/import-task/sse/connect`;
this.abortController = new AbortController();
const url = `${apiURL}/ec/import-task/sse/connect?token=${encodeURIComponent(token)}`;
this.readyState = EventSource.CONNECTING;
fetch(url, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'text/event-stream',
},
signal: this.abortController.signal,
})
.then((response) => {
if (!response.ok) {
throw new Error(`SSE连接失败: ${response.status}`);
}
const es = new EventSource(url);
this.eventSource = es;
this.readyState = EventSource.OPEN;
es.onopen = () => {
this.readyState = EventSource.OPEN;
};
const reader = response.body?.getReader();
const decoder = new TextDecoder();
es.onerror = (event) => {
this.readyState = EventSource.CLOSED;
this.dispatchEvent('error', new MessageEvent('error', { data: event }));
// EventSource 会自动重连,无需手动处理
};
if (!reader) {
throw new Error('无法获取响应流');
}
// 读取流数据
const readStream = () => {
reader
.read()
.then(({ done, value }) => {
if (done) {
this.readyState = EventSource.CLOSED;
return;
}
const chunk = decoder.decode(value, { stream: true });
this.parseSSE(chunk);
readStream();
})
.catch((error) => {
if (error.name !== 'AbortError') {
console.error('读取SSE流失败:', error);
this.readyState = EventSource.CLOSED;
this.dispatchEvent(
'error',
new MessageEvent('error', { data: error }),
);
}
});
};
readStream();
})
.catch((error) => {
if (error.name !== 'AbortError') {
console.error('建立SSE连接失败:', error);
this.readyState = EventSource.CLOSED;
this.dispatchEvent(
'error',
new MessageEvent('error', { data: error }),
);
}
// 将所有自定义事件类型的 listener 注册到 EventSource 上
this.listeners.forEach((handlers, eventType) => {
handlers.forEach((handler) => {
es.addEventListener(eventType, handler as EventListener);
});
});
}
/**
* 断开连接
* 断开连接(手动断开后不会自动重连)
*/
disconnect() {
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
if (this.eventSource) {
this.eventSource.close();
this.eventSource = null;
this.readyState = EventSource.CLOSED;
}
}
@@ -159,22 +136,6 @@ class SseConnection {
return this.readyState;
}
/**
* 移除事件监听器
*/
removeEventListener(
eventType: string,
handler: (event: MessageEvent) => void,
) {
const handlers = this.listeners.get(eventType);
if (handlers) {
handlers.delete(handler);
}
}
/**
* 分发事件
*/
private dispatchEvent(eventType: string, event: MessageEvent) {
const handlers = this.listeners.get(eventType);
if (handlers) {
@@ -187,34 +148,6 @@ class SseConnection {
});
}
}
/**
* 解析SSE数据
*/
private parseSSE(chunk: string) {
const lines = chunk.split('\n');
let eventType = 'message';
let data = '';
for (const line of lines) {
if (line.startsWith('event:')) {
eventType = line.slice(6).trim();
} else if (line.startsWith('data:')) {
data += `${line.slice(5).trim()}\n`;
} else if (
line === '' && // 空行表示一个完整的消息
data
) {
const event = new MessageEvent(eventType, {
data: data.trim(),
});
this.dispatchEvent(eventType, event);
this.dispatchEvent('message', event);
data = '';
eventType = 'message';
}
}
}
}
/**
@@ -0,0 +1,17 @@
import type { ProductOverviewDTO, ProductOverviewVO } from './types';
import { requestClient } from '#/api/request';
/**
* 商品概览管理API
*/
/**
* 获取商品总览统计数据
*/
export async function getProductOverviewApi(params: ProductOverviewDTO.Query) {
return requestClient.post<ProductOverviewVO.Overview>(
'/ec/product/overview',
params,
);
}
@@ -0,0 +1,2 @@
export * from './apis';
export * from './types';
@@ -0,0 +1,2 @@
export type { ProductOverviewDTO } from './types.dto';
export type { ProductOverviewVO } from './types.vo';
@@ -0,0 +1,11 @@
export namespace ProductOverviewDTO {
/** 商品概览查询参数 */
export interface Query {
/** 商品ID */
productId: number;
/** 开始日期 */
startDate: string;
/** 结束日期 */
endDate: string;
}
}
@@ -0,0 +1,39 @@
export namespace ProductOverviewVO {
/** 每日数据项 */
export interface DailyData {
/** 日期 */
date: string;
/** 对应的值 */
value: number;
}
/** 每日统计数据 */
export interface DailyStatistics {
/** 时间范围的总值 */
total: number;
/** 每日数据列表 */
dailyDataList: DailyData[];
}
/** 商品总览 */
export interface Overview {
/** 商品ID */
productId: number;
/** 商品名称 */
productName: string;
/** 销售额统计 */
salesAmount: DailyStatistics;
/** 订单数统计 */
orderCount: DailyStatistics;
/** 客单价统计 */
averageOrderValue: DailyStatistics;
/** 成本统计 */
costAmount: DailyStatistics;
/** 退款金额统计 */
refundAmount: DailyStatistics;
/** 推广费统计 */
promotionFee: DailyStatistics;
/** 费比统计 */
feeRatio: DailyStatistics;
}
}
@@ -141,8 +141,7 @@ watch(
:avatar
:menus
:text="userStore.userInfo?.realName"
description="ann.vben@gmail.com"
tag-text="Pro"
:description="userStore.userInfo?.phone || '-'"
@logout="handleLogout"
/>
</template>
@@ -37,9 +37,7 @@ async function generateAccess(options: GenerateMenuAndRoutesOptions) {
throw error;
}
},
// 可以指定没有权限跳转403页面
forbiddenComponent,
// 如果 route.meta.menuVisibleWithForbidden = true
layoutMap,
pageMap,
});
@@ -1,15 +1,20 @@
<script lang="ts" setup>
import type { ProductVO } from '#/api/ecommerce/product/types';
import { useRouter } from 'vue-router';
import { createIconifyIcon } from '@vben/icons';
import { Button, Card, Image, Popconfirm, Popover, Tag } from 'ant-design-vue';
defineProps<Props>();
const emit = defineEmits<Emits>();
const router = useRouter();
// 创建图标组件
const EditIcon = createIconifyIcon('lucide:edit');
const TrashIcon = createIconifyIcon('lucide:trash-2');
const ChartIcon = createIconifyIcon('lucide:bar-chart-2');
interface Props {
product: ProductVO.Info;
@@ -27,6 +32,10 @@ const handleEdit = (product: ProductVO.Info) => {
const handleDelete = (product: ProductVO.Info) => {
emit('delete', product);
};
const goToDetails = (product: ProductVO.Info) => {
router.push(`/ecom/product/details/${product.id}`);
};
</script>
<template>
@@ -35,9 +44,10 @@ const handleDelete = (product: ProductVO.Info) => {
:body-style="{ padding: 0 }"
class="group h-full border border-gray-200 transition-all duration-300 ease-out hover:-translate-y-1 hover:border-blue-500 hover:shadow-lg dark:border-gray-700"
>
<!-- 图片区域 -->
<!-- 图片区域(点击进入详情) -->
<div
class="relative aspect-square cursor-pointer overflow-hidden rounded-t-lg bg-gray-100 dark:bg-neutral-800"
@click="goToDetails(product)"
>
<Image
v-if="product.mainImage"
@@ -59,10 +69,11 @@ const handleDelete = (product: ProductVO.Info) => {
<!-- 信息区域 -->
<div class="p-3">
<!-- 商品名称 -->
<!-- 商品名称(点击进入详情) -->
<div
class="mb-2 line-clamp-2 text-sm font-medium text-gray-900 dark:text-gray-100"
class="mb-2 line-clamp-2 cursor-pointer text-sm font-medium text-gray-900 hover:text-blue-500 dark:text-gray-100"
:title="product.name"
@click="goToDetails(product)"
>
{{ product.name }}
</div>
@@ -142,6 +153,17 @@ const handleDelete = (product: ProductVO.Info) => {
<span class="hidden sm:inline">删除</span>
</Button>
</Popconfirm>
<Button
type="text"
size="small"
title="查看统计"
@click="goToDetails(product)"
>
<template #icon>
<ChartIcon class="h-4 w-4" />
</template>
<span class="hidden sm:inline">统计</span>
</Button>
</div>
</div>
</Card>
@@ -0,0 +1,37 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Tabs } from 'ant-design-vue';
import OverviewTab from './tabs/OverviewTab.vue';
defineOptions({ name: 'ProductDetails' });
const route = useRoute();
// 商品ID(从路由参数获取)
const productId = computed(() => {
const id = route.params.id;
return id ? Number(id) : 0;
});
// 当前激活的 tab
const activeKey = ref('overview');
</script>
<template>
<Page auto-content-height content-class="flex flex-col">
<Tabs
v-model:active-key="activeKey"
class="flex min-h-0 flex-1 flex-col"
:tab-bar-style="{ marginBottom: '16px' }"
>
<Tabs.TabPane key="overview" tab="总览">
<OverviewTab :product-id="productId" />
</Tabs.TabPane>
</Tabs>
</Page>
</template>
@@ -0,0 +1,185 @@
<script lang="ts" setup>
import type { ProductOverviewVO } from '#/api/ecommerce/product-overview/types';
import { onMounted, ref, watch } from 'vue';
import { Card, Col, DatePicker, message, Row, Space, Typography } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getProductOverviewApi } from '#/api/ecommerce/product-overview';
import ChartCard from '../../../shop/details/components/ChartCard.vue';
defineOptions({ name: 'ProductOverviewTab' });
const props = defineProps<Props>();
interface Props {
productId: number;
}
// 响应式数据
const loading = ref(false);
const overviewData = ref<null | ProductOverviewVO.Overview>(null);
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().subtract(30, 'day'),
dayjs(),
]);
// 格式化金额
function formatCurrency(value: number): string {
return `¥${value.toLocaleString('zh-CN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}`;
}
// 格式化百分比
function formatPercent(value: number): string {
return `${(value * 100).toFixed(2)}%`;
}
// 获取商品总览数据
async function fetchProductOverview() {
if (!props.productId || !dateRange.value) return;
try {
loading.value = true;
const data = await getProductOverviewApi({
productId: props.productId,
startDate: dateRange.value[0].format('YYYY-MM-DD'),
endDate: dateRange.value[1].format('YYYY-MM-DD'),
});
overviewData.value = data;
} catch (error) {
console.error('获取商品总览失败:', error);
message.error('获取商品总览失败');
} finally {
loading.value = false;
}
}
// 处理日期范围变化
function handleDateRangeChange() {
fetchProductOverview();
}
// 监听 productId 变化
watch(
() => props.productId,
(newProductId) => {
if (newProductId) {
fetchProductOverview();
}
},
);
// 初始化数据
onMounted(() => {
if (props.productId) {
fetchProductOverview();
}
});
</script>
<template>
<div class="flex h-full flex-col">
<!-- 日期选择器 -->
<Card :loading="loading" class="mb-4 flex-shrink-0">
<Space>
<span>选择日期范围:</span>
<DatePicker.RangePicker
v-model:value="dateRange"
format="YYYY-MM-DD"
@change="handleDateRangeChange"
/>
</Space>
</Card>
<!-- 商品名称标题 -->
<Card v-if="overviewData" :loading="loading" class="mb-4 flex-shrink-0">
<Typography.Title :level="4" style="margin: 0">
{{ overviewData.productName }}
</Typography.Title>
</Card>
<!-- 图表展示 -->
<div v-if="overviewData" class="min-h-0 flex-1 overflow-auto">
<Row :gutter="[16, 16]">
<!-- 销售额 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.salesAmount"
:formatter="formatCurrency"
title="销售额"
/>
</Col>
<!-- 订单数 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.orderCount"
:formatter="(v) => v.toLocaleString()"
chart-type="bar"
color="#019680"
title="订单数"
/>
</Col>
<!-- 客单价 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.averageOrderValue"
:formatter="formatCurrency"
color="#ff9800"
title="客单价"
/>
</Col>
<!-- 成本 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.costAmount"
:formatter="formatCurrency"
color="#f56c6c"
title="成本"
/>
</Col>
<!-- 退款金额 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.refundAmount"
:formatter="formatCurrency"
color="#e6a23c"
title="退款金额"
/>
</Col>
<!-- 推广费 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.promotionFee"
:formatter="formatCurrency"
color="#909399"
title="推广费"
/>
</Col>
<!-- 费比 -->
<Col :lg="12" :md="24" :sm="24" :xl="8" :xxl="8" :xs="24">
<ChartCard
:data="overviewData.feeRatio"
:formatter="formatPercent"
color="#67c23a"
title="费比"
/>
</Col>
</Row>
</div>
<!-- 空状态 -->
<div v-else class="flex flex-1 items-center justify-center">
<span class="text-gray-400">暂无数据</span>
</div>
</div>
</template>