refactor: 调整页面组件位置

This commit is contained in:
2026-08-14 14:37:54 +08:00
parent 5f824531ce
commit c51e13f4b4
82 changed files with 1 additions and 1 deletions
@@ -0,0 +1,480 @@
<script setup lang="ts">
import type { BrushOrderDTO, BrushOrderVO } from '#/api/ecommerce/brush-order';
import type {
ProductSkuDTO,
ProductSkuVO,
} from '#/api/ecommerce/product-sku/types';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
Spin,
} from 'ant-design-vue';
import type { SelectValue } from 'ant-design-vue/es/select';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import {
createBrushOrderApi,
updateBrushOrderApi,
} from '#/api/ecommerce/brush-order';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getProductSkuPageApi } from '#/api/ecommerce/product-sku';
import { getShopPageApi } from '#/api/ecommerce/shop';
defineOptions({ name: 'BrushOrderFormModal' });
interface Props {
open: boolean;
brushOrderData?: null | BrushOrderVO.Info;
/** 新增时预填店铺(编辑时忽略) */
presetShopId?: number | null;
}
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
const props = withDefaults(defineProps<Props>(), {
presetShopId: null,
});
const emit = defineEmits<Emits>();
// 与父组件 v-model:open 同步:遮罩/右上角关闭时也要 emit false,否则父级一直为 true 无法二次打开
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
destroyOnClose: false,
onCancel() {
handleCancel();
},
onConfirm() {
handleOk();
},
onOpenChange(isOpen: boolean) {
if (!isOpen) {
emit('update:open', false);
resetFormData();
}
},
});
// 响应式数据
const formRef = ref();
const isEdit = ref(false);
// 表单数据
const formData = ref<BrushOrderDTO.Create>({
shopId: undefined as any,
productId: undefined,
productSkuId: undefined,
brushAmount: undefined as any,
brushTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
quantity: 1,
remark: undefined,
});
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
brushAmount: [
{ required: true, message: '请输入刷单金额', trigger: 'blur' },
{ type: 'number', min: 0, message: '刷单金额必须大于等于0', trigger: 'blur' },
],
brushTime: [{ required: true, message: '请选择刷单时间', trigger: 'change' }],
} as any;
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 商品选项数据
const productOptions = ref<
{ label: string; product: ProductVO.Info; value: number }[]
>([]);
const productLoading = ref(false);
const productSearchKeyword = ref('');
// 规格选项数据
const productSkuOptions = ref<
{ label: string; sku: ProductSkuVO.Info; value: number }[]
>([]);
const productSkuLoading = ref(false);
const productSkuSearchKeyword = ref('');
// 处理日期选择器的双向绑定
const brushTimeValue = computed({
get(): Dayjs | undefined {
return formData.value.brushTime
? dayjs(formData.value.brushTime, 'YYYY-MM-DD HH:mm:ss')
: undefined;
},
set(value: Dayjs | null | undefined) {
formData.value.brushTime = value
? value.format('YYYY-MM-DD HH:mm:ss')
: '';
},
});
// 监听 props.open:先准备好表单再 open,关闭时同步 modalApi
watch(
() => props.open,
async (newVal) => {
if (!newVal) {
modalApi.close();
return;
}
isEdit.value = !!props.brushOrderData;
if (props.brushOrderData) {
// 编辑模式,填充表单数据
formData.value = {
shopId: props.brushOrderData.shopId,
productId: props.brushOrderData.productId,
productSkuId: props.brushOrderData.productSkuId,
brushAmount: props.brushOrderData.brushAmount,
brushTime: props.brushOrderData.brushTime
? dayjs(props.brushOrderData.brushTime).format('YYYY-MM-DD HH:mm:ss')
: dayjs().format('YYYY-MM-DD HH:mm:ss'),
quantity: props.brushOrderData.quantity || 1,
remark: props.brushOrderData.remark,
};
} else {
resetFormData();
if (props.presetShopId != null && props.presetShopId !== undefined) {
formData.value.shopId = props.presetShopId;
}
}
await nextTick();
modalApi.open();
await nextTick();
formRef.value?.clearValidate?.();
// 远程搜索 Select 仅 @search 不会在「只点开下拉」时请求,这里打开弹窗后预加载一页
void searchProducts('');
if (formData.value.productId) {
void searchProductSkus('');
}
},
{ immediate: true },
);
// 加载店铺列表
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
// 搜索商品
async function searchProducts(keyword: string) {
productSearchKeyword.value = keyword;
productLoading.value = true;
try {
const params: PageQueryDTO<ProductDTO.Filters> = {
page: 1,
pageSize: 50,
filters: {
name: keyword || undefined,
},
};
const data = await getProductPageApi(params);
productOptions.value = data.records.map((product: ProductVO.Info) => ({
label: `${product.name}${product.productCode ? ` (${product.productCode})` : ''}`,
value: product.id,
product,
}));
} catch (error) {
console.error('搜索商品失败:', error);
message.error('搜索商品失败');
} finally {
productLoading.value = false;
}
}
// 搜索规格
async function searchProductSkus(keyword: string) {
if (!formData.value.productId) {
productSkuOptions.value = [];
return;
}
productSkuSearchKeyword.value = keyword;
productSkuLoading.value = true;
try {
const params: PageQueryDTO<ProductSkuDTO.Filters> = {
page: 1,
pageSize: 50,
filters: {
productId: formData.value.productId,
name: keyword || undefined,
},
};
const data = await getProductSkuPageApi(params);
productSkuOptions.value = data.records.map((sku: ProductSkuVO.Info) => ({
label: `${sku.name}${sku.skuCode ? ` (${sku.skuCode})` : ''}`,
value: sku.id,
sku,
}));
} catch (error) {
console.error('搜索规格失败:', error);
message.error('搜索规格失败');
} finally {
productSkuLoading.value = false;
}
}
/** 点开/聚焦商品下拉时再拉一次(不输入关键词也能看到列表) */
function onProductSelectFocus() {
if (!productLoading.value) {
void searchProducts(productSearchKeyword.value || '');
}
}
/** 点开规格下拉时拉规格列表 */
function onProductSkuSelectFocus() {
if (!formData.value.productId || productSkuLoading.value) return;
void searchProductSkus(productSkuSearchKeyword.value || '');
}
function normalizeProductId(value: SelectValue): number | undefined {
if (value === null || value === undefined || value === '') {
return undefined;
}
if (typeof value === 'number') {
return Number.isFinite(value) ? value : undefined;
}
if (typeof value === 'string') {
const n = Number(value);
return Number.isFinite(n) ? n : undefined;
}
return undefined;
}
// 处理商品选择(Select @change 为 SelectValue,与 v-model 数字类型对齐)
function handleProductChange(value: SelectValue) {
const productId = normalizeProductId(value);
if (!productId) {
formData.value.productSkuId = undefined;
productSkuOptions.value = [];
} else {
void searchProductSkus('');
}
}
// 监听商品ID变化,加载规格列表
watch(
() => formData.value.productId,
(newProductId) => {
if (newProductId) {
searchProductSkus('');
} else {
productSkuOptions.value = [];
formData.value.productSkuId = undefined;
}
},
);
// 重置表单数据
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
productId: undefined,
productSkuId: undefined,
brushAmount: undefined as any,
brushTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
quantity: 1,
remark: undefined,
};
productOptions.value = [];
productSkuOptions.value = [];
};
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (isEdit.value && props.brushOrderData) {
// 更新刷单记录
await updateBrushOrderApi(props.brushOrderData.id, formData.value);
message.success('更新成功');
} else {
// 创建刷单记录
await createBrushOrderApi(formData.value);
message.success('创建成功');
}
emit('success');
modalApi.close();
} catch (error) {
if ((error as any)?.errorFields) {
// 表单验证错误
return;
}
console.error('操作失败:', error);
message.error(isEdit.value ? '更新失败' : '创建失败');
}
};
// 取消:关闭与重置由 onOpenChange 统一处理
const handleCancel = () => {
emit('cancel');
modalApi.close();
};
// 组件挂载时加载数据
onMounted(() => {
loadShopList();
});
</script>
<template>
<Modal :title="isEdit ? '编辑刷单记录' : '新增刷单记录'">
<Form
ref="formRef"
:model="formData"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="店铺" name="shopId">
<Select
v-model:value="formData.shopId"
placeholder="请选择店铺"
:loading="shopListLoading"
>
<Select.Option
v-for="shop in shopList"
:key="shop.id"
:value="shop.id"
>
{{ shop.name }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="商品" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选)"
show-search
:filter-option="false"
:loading="productLoading"
allow-clear
@search="searchProducts"
@focus="onProductSelectFocus"
@change="handleProductChange"
>
<template #notFoundContent>
<div v-if="productLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
请输入关键词搜索商品
</div>
</template>
<Select.Option
v-for="option in productOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="商品 SKU" name="productSkuId">
<Select
v-model:value="formData.productSkuId"
placeholder="请选择商品 SKU(可选)"
show-search
:filter-option="false"
:loading="productSkuLoading"
:disabled="!formData.productId"
allow-clear
@search="searchProductSkus"
@focus="onProductSkuSelectFocus"
>
<template #notFoundContent>
<div v-if="productSkuLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
{{ formData.productId ? '请输入关键词搜索规格' : '请先选择商品' }}
</div>
</template>
<Select.Option
v-for="option in productSkuOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="刷单金额" name="brushAmount">
<InputNumber
v-model:value="formData.brushAmount"
placeholder="请输入刷单金额"
:min="0"
:precision="2"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="刷单时间" name="brushTime">
<DatePicker
v-model:value="brushTimeValue"
placeholder="请选择刷单时间"
show-time
format="YYYY-MM-DD HH:mm:ss"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="刷单数量" name="quantity">
<InputNumber
v-model:value="formData.quantity"
placeholder="请输入刷单数量"
:min="1"
:precision="0"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注(可选)"
:rows="3"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,579 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { BrushOrderDTO, BrushOrderVO } from '#/api/ecommerce/brush-order';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
DatePicker,
Empty,
Flex,
InputNumber,
message,
Popconfirm,
Select,
Space,
Spin,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteBrushOrderApi,
getBrushOrderPageApi,
} from '#/api/ecommerce/brush-order';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import BrushOrderFormModal from './components/BrushOrderFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'BrushOrderManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const StoreIcon = createIconifyIcon('lucide:store');
const loading = ref(false);
const shopsLoading = ref(false);
const shops = ref<ShopVO.Info[]>([]);
/** 未选店铺:undefined 表示全部 */
const selectedShopId = ref<number | undefined>(undefined);
const formModalVisible = ref(false);
const currentBrushOrderData = ref<BrushOrderVO.Info | null>(null);
const presetShopIdForModal = ref<number | null>(null);
const searchForm = ref({
productId: undefined as number | undefined,
minBrushAmount: undefined as number | undefined,
maxBrushAmount: undefined as number | undefined,
startBrushTime: undefined as string | undefined,
endBrushTime: undefined as string | undefined,
});
const productOptions = ref<{ label: string; value: number }[]>([]);
const productPage = ref(1);
const productPageSize = 20;
const productTotal = ref(0);
const productLoading = ref(false);
const productSearchKeyword = ref('');
const productLoaded = ref(false);
let productSearchTimer: null | ReturnType<typeof setTimeout> = null;
function productOptionLabel(p: ProductVO.Info) {
const code = p.productCode ? ` · ${p.productCode}` : '';
return `${p.name}${code}`;
}
async function fetchProducts(page = 1, append = false) {
if (productLoading.value) return;
productLoading.value = true;
try {
const kw = productSearchKeyword.value.trim();
const params: PageQueryDTO<ProductDTO.Filters> = {
page,
pageSize: productPageSize,
filters: kw ? { keywords: kw } : {},
};
const data = await getProductPageApi(params);
const mapped = data.records.map((p: ProductVO.Info) => ({
label: productOptionLabel(p),
value: p.id,
}));
productOptions.value = append ? [...productOptions.value, ...mapped] : mapped;
productTotal.value = data.total;
productPage.value = page;
productLoaded.value = true;
} catch {
message.error('获取商品列表失败');
if (!append) productOptions.value = [];
} finally {
productLoading.value = false;
}
}
function handleProductSearch(value: string) {
if (productSearchTimer) clearTimeout(productSearchTimer);
productSearchTimer = setTimeout(() => {
productSearchKeyword.value = value;
productPage.value = 1;
void fetchProducts(1, false);
}, 300);
}
function handleProductPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = productPage.value * productPageSize < productTotal.value;
if (hasMore && !productLoading.value) {
void fetchProducts(productPage.value + 1, true);
}
}
}
async function loadShops() {
shopsLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 500,
filters: {},
});
shops.value = response.records ?? [];
} catch {
message.error('获取店铺列表失败');
shops.value = [];
} finally {
shopsLoading.value = false;
}
}
const selectedShopLabel = computed(() => {
if (selectedShopId.value == null) {
return '全部店铺';
}
const s = shops.value.find((x) => x.id === selectedShopId.value);
return s?.name ?? `店铺 #${selectedShopId.value}`;
});
function selectShopAll() {
selectedShopId.value = undefined;
}
function selectShop(id: number) {
selectedShopId.value = id;
}
const gridOptions: VxeGridProps<BrushOrderVO.Info> = {
columns: [
{
type: 'seq' as const,
width: 56,
title: '序号',
},
{
field: 'shopName',
title: '店铺名称',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
title: '商品信息',
minWidth: 160,
slots: { default: 'productInfo' },
},
{
field: 'quantity',
title: '刷单数量',
width: 100,
},
{
title: '刷单金额',
width: 120,
slots: { default: 'brushAmount' },
},
{
field: 'brushTime',
title: '刷单时间',
minWidth: 160,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
title: '操作',
width: 140,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: '100%',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<BrushOrderDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
shopId: selectedShopId.value,
productId: searchForm.value.productId || undefined,
minBrushAmount: searchForm.value.minBrushAmount,
maxBrushAmount: searchForm.value.maxBrushAmount,
startBrushTime: searchForm.value.startBrushTime || undefined,
endBrushTime: searchForm.value.endBrushTime || undefined,
},
};
const data = await getBrushOrderPageApi(params);
return { items: data.records, total: data.total };
} catch {
message.error('获取刷单记录列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
function refreshTable() {
gridApi?.reload();
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '刷单记录',
});
watch(selectedShopId, () => {
gridApi.reload();
});
onMounted(() => {
void loadShops();
});
function resetModalPreset() {
presetShopIdForModal.value = null;
}
function shopRowClass(id: number | 'all') {
const active =
id === 'all'
? selectedShopId.value === undefined
: selectedShopId.value === id;
const layout =
id === 'all'
? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
: 'group flex w-full cursor-pointer items-center gap-2';
return sidebarListRowClass(active, layout);
}
const handleAdd = () => {
currentBrushOrderData.value = null;
resetModalPreset();
formModalVisible.value = true;
};
function handleAddForShop(shopId: number) {
selectShop(shopId);
currentBrushOrderData.value = null;
presetShopIdForModal.value = shopId;
formModalVisible.value = true;
}
const handleEdit = (record: BrushOrderVO.Info) => {
resetModalPreset();
currentBrushOrderData.value = record;
formModalVisible.value = true;
};
const handleDelete = async (id: number) => {
try {
await deleteBrushOrderApi(id);
message.success('删除成功');
refreshTable();
} catch {
message.error('删除失败');
}
};
const handleFormSuccess = () => {
resetModalPreset();
refreshTable();
};
const handleFormCancel = () => {
resetModalPreset();
formModalVisible.value = false;
};
const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
</script>
<template>
<Page title="刷单记录管理" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择店铺筛选右侧记录;未选店铺时展示全部。可在店铺行快捷新增该店铺刷单记录。
</div>
</template>
<template #extra>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
新增刷单记录
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0">
<Card
class="flex h-full w-[420px] shrink-0 flex-col"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
padding: '12px',
}"
>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<StoreIcon class="h-4 w-4" />
店铺
</span>
</template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div :class="SIDEBAR_LIST_SHELL_CLASS">
<button
type="button"
:class="shopRowClass('all')"
@click="selectShopAll"
>
<span class="min-w-0 flex-1 truncate">全部店铺</span>
<span class="shrink-0 text-xs font-normal text-muted-foreground">
全部记录
</span>
</button>
<Empty
v-if="!shopsLoading && shops.length === 0"
class="py-8"
description="暂无店铺"
/>
<div v-else class="space-y-1">
<div
v-for="shop in shops"
:key="shop.id"
:class="shopRowClass(shop.id)"
class="group w-full"
>
<button
type="button"
class="min-w-0 flex-1 truncate text-left"
@click="selectShop(shop.id)"
>
{{ shop.name }}
</button>
<Button
type="link"
size="small"
class="!h-7 shrink-0 !px-1 !text-xs font-semibold opacity-80 group-hover:opacity-100"
@click.stop="handleAddForShop(shop.id)"
>
<PlusIcon class="mr-0.5 inline h-3.5 w-3.5" />
添加
</Button>
</div>
</div>
</div>
</Spin>
</Card>
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">刷单记录</span>
</template>
<div
class="shrink-0 space-y-2 border-t border-border px-4 py-3"
>
<div class="flex flex-wrap items-end gap-2">
<div class="flex min-w-0 flex-col gap-0.5">
<span class="text-xs text-muted-foreground">商品</span>
<Select
v-model:value="searchForm.productId"
allow-clear
show-search
:filter-option="false"
placeholder="名称/编码搜索"
class="min-w-[220px] max-w-[320px]"
:options="productOptions"
:loading="productLoading"
:dropdown-match-select-width="false"
:dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
@search="handleProductSearch"
@popup-scroll="handleProductPopupScroll"
@focus="
() => {
if (!productLoaded) void fetchProducts(1, false);
}
"
@change="() => refreshTable()"
/>
</div>
<div class="flex flex-col gap-0.5">
<span class="text-xs text-muted-foreground">金额 ≥</span>
<InputNumber
v-model:value="searchForm.minBrushAmount"
:min="0"
:precision="2"
placeholder="最小"
class="!w-[110px]"
allow-clear
@press-enter="refreshTable"
@blur="refreshTable"
/>
</div>
<div class="flex flex-col gap-0.5">
<span class="text-xs text-muted-foreground">金额 ≤</span>
<InputNumber
v-model:value="searchForm.maxBrushAmount"
:min="0"
:precision="2"
placeholder="最大"
class="!w-[110px]"
allow-clear
@press-enter="refreshTable"
@blur="refreshTable"
/>
</div>
<div class="flex flex-col gap-0.5">
<span class="text-xs text-muted-foreground">刷单时间起</span>
<DatePicker
v-model:value="searchForm.startBrushTime"
show-time
value-format="YYYY-MM-DD HH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
placeholder="开始"
class="w-[180px]"
allow-clear
@change="() => refreshTable()"
/>
</div>
<div class="flex flex-col gap-0.5">
<span class="text-xs text-muted-foreground">刷单时间止</span>
<DatePicker
v-model:value="searchForm.endBrushTime"
show-time
value-format="YYYY-MM-DD HH:mm:ss"
format="YYYY-MM-DD HH:mm:ss"
placeholder="结束"
class="w-[180px]"
allow-clear
@change="() => refreshTable()"
/>
</div>
<Button type="default" size="small" class="mb-0.5" @click="refreshTable">
查询
</Button>
</div>
<div class="text-xs text-muted-foreground">
当前:{{ selectedShopLabel }}
</div>
</div>
<div class="min-h-0 flex-1 overflow-hidden px-2 pb-2 pt-0 sm:px-3 sm:pb-3">
<Grid :loading="loading" class="h-full min-h-0">
<template #toolbar-tools>
<span class="text-xs text-muted-foreground">
修改筛选后点击「查询」或失焦/回车刷新;左侧切换店铺立即刷新
</span>
</template>
<template #productInfo="{ row }">
<div v-if="row.productName">
<div class="font-semibold">{{ row.productName }}</div>
<div
v-if="row.productSkuName"
class="text-xs text-muted-foreground"
>
{{ row.productSkuName }}
</div>
</div>
<span v-else class="text-muted-foreground">—</span>
</template>
<template #brushAmount="{ row }">
<span class="font-semibold text-green-600">
{{ formatAmount(row.brushAmount ?? 0) }}
</span>
</template>
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这条刷单记录吗?"
@confirm="handleDelete(row.id)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
</div>
</Card>
</Flex>
<BrushOrderFormModal
v-model:open="formModalVisible"
:brush-order-data="currentBrushOrderData"
:preset-shop-id="presetShopIdForModal"
@success="handleFormSuccess"
@cancel="handleFormCancel"
/>
</Page>
</template>
@@ -0,0 +1,172 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
// 创建图标组件
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
// Emits
interface Emits {
(e: 'fileSelected', file: File): void;
}
// 响应式数据
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
// 文件验证
const validateFile = (file: File): boolean => {
const ext = file.name.toLowerCase().split('.').pop() || '';
const allowedExts = ['csv', 'xlsx', 'xls'];
if (!allowedExts.includes(ext)) {
message.error('只能上传 CSV 或 Excel 格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
// 处理文件
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
// 拖拽处理
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
// 文件选择处理
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
// 清空input值,允许重复选择同一文件
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<div class="space-y-4">
<div class="relative mx-auto h-12 w-12">
<UploadIcon
v-if="!loading"
class="h-12 w-12 text-gray-400 dark:text-[hsl(240deg_5%_64.9%)]"
:class="{ 'text-blue-500': isDragOver }"
/>
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
</div>
<div>
<p
class="text-lg font-medium"
:class="loading ? 'text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
/* 拖拽区域样式 */
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
:deep(.border-dashed:hover) {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
html.dark .border-dashed:hover {
border-color: hsl(240deg 3.7% 40%) !important;
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
}
</style>
@@ -0,0 +1,518 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { useDebounceFn } from '@vueuse/core';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from './utils/fileParser';
defineOptions({ name: 'DataImport' });
// 响应式数据
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
/** 与向导中「SKU 编码」字段映射绑定的 CSV 表头,用于左侧表格该列可编辑 */
const skuCodeCsvHeader = ref<string | undefined>();
const skuMissingCount = ref(0);
/** SKU 编码为空的行在 csvData 中的全局下标(0-based) */
const skuMissingRowIndices = ref<Set<number>>(new Set());
/** 与表格分页条 pageSize 同步,用于计算空缺所在页 */
const tablePageSize = ref(50);
/** 「下一处空缺」循环游标,-1 表示尚未开始循环 */
const missingCycleCursor = ref(-1);
// 动态生成Grid列配置
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) {
return [];
}
const columns: VxeGridProps<any>['columns'] = [
{
type: 'seq' as const,
title: '序号',
width: 80,
fixed: 'left' as const,
},
];
csvHeaders.value.forEach((header) => {
const isSkuCol =
!!skuCodeCsvHeader.value && header === skuCodeCsvHeader.value;
columns.push({
field: header,
title: header,
minWidth: isSkuCol ? 180 : 150,
showOverflow: 'tooltip' as const,
...(isSkuCol ? { editRender: { name: 'input' as const } } : {}),
});
});
return columns;
});
const gridOptions: VxeGridProps<any> = {
columns: [],
height: tableHeight.value,
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
data: [],
editConfig: {
mode: 'cell',
trigger: 'click',
},
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
if (csvData.value.length === 0) {
return {
items: [],
total: 0,
};
}
const currentPage = page.currentPage || 1;
const pageSize = page.pageSize || 50;
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
// 供 rowClassName 识别全局行号(与 csvData 下标一致)
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
total: csvData.value.length,
};
},
},
},
};
const debouncedWizardSpecSync = useDebounceFn(() => {
importTaskWizardRef.value?.onPreviewSpecCodeCellSaved?.();
}, 400);
function rowClassNameForSpecMissing(params: { row?: Record<string, unknown> }) {
const idx = params.row?.__srcRowIndex;
if (typeof idx !== 'number') return '';
return skuMissingRowIndices.value.has(idx) ? 'order-import-row--sku-missing' : '';
}
const gridEvents = {
editClosed(params: { column?: { field?: string } }) {
const field = params.column?.field;
if (!field || !skuCodeCsvHeader.value) return;
if (field === skuCodeCsvHeader.value) {
debouncedWizardSpecSync();
}
},
pageChange(params: { pageSize?: number; currentPage?: number }) {
if (params.pageSize && params.pageSize > 0) {
tablePageSize.value = params.pageSize;
}
},
};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
rowClassName: rowClassNameForSpecMissing,
});
gridApi.reload();
};
watch(
tableHeight,
(newHeight) => {
gridApi.setGridOptions({
height: newHeight,
});
},
{ immediate: false },
);
const syncWizardOpen = () => {
if (csvData.value.length === 0 || csvHeaders.value.length === 0) {
return;
}
nextTick(() => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
);
});
};
function onSkuCodeColumnChange(header: string | undefined) {
skuCodeCsvHeader.value = header;
updateTable();
}
function onSkuMissingAfterPrecheck(payload: { count: number; indices: number[] }) {
skuMissingCount.value = payload.count;
skuMissingRowIndices.value = new Set(payload.indices);
missingCycleCursor.value = -1;
// 必须用 query 而非 reload:reload 会重置分页到第 1 页,用户在其它页补SKU 编码时会被突然拉回首页
if (csvData.value.length > 0) {
void gridApi.query({});
}
}
/** 取 VxeGrid 内部的 VxeTable 实例(用于 scrollToRow 等仅表格支持的方法) */
function getVxeInnerTable(grid: any) {
return grid?.$refs?.refTable ?? grid?.$refs?.xTable ?? null;
}
/** 等两帧再滚,避免 loadData 后 DOM 尚未稳定 */
function nextPaint() {
return new Promise<void>((resolve) => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
}
/**
* 滚动到指定数据行(scrollToRow 返回 Promise;第二参为列 field 时同时横向滚到「SKU 编码」列)
* 虚拟滚动场景 vxe 内部会延时二次校正,这里再补一次延迟滚动。
*/
async function scrollGridToDataRow(row: Record<string, unknown>) {
const grid = gridApi.grid as any;
const field = skuCodeCsvHeader.value;
const candidates = [grid, getVxeInnerTable(grid)].filter(Boolean);
for (const inst of candidates) {
if (inst && typeof inst.scrollToRow === 'function') {
try {
await inst.scrollToRow(row, field || undefined);
return;
} catch {
// 尝试下一个实例
}
}
}
}
/** 跳转到包含该全局行号的分页并滚动到该行 */
async function goToRowIndex(globalRowIndex: number) {
if (globalRowIndex < 0 || globalRowIndex >= csvData.value.length) return;
const ps = tablePageSize.value;
const targetPage = Math.floor(globalRowIndex / ps) + 1;
const grid = gridApi.grid as any;
if (!grid?.getProxyInfo || typeof grid.commitProxy !== 'function') {
message.warning('表格尚未就绪,请稍后重试');
return;
}
const row = csvData.value[globalRowIndex] as Record<string, unknown> | undefined;
if (!row) return;
try {
const proxy = grid.getProxyInfo();
if (proxy?.pager) {
proxy.pager.currentPage = targetPage;
proxy.pager.pageSize = ps;
}
await grid.commitProxy('query');
await nextTick();
await nextPaint();
await scrollGridToDataRow(row);
// 与 vxe 虚拟列表二次对齐时机接近,避免首屏未滚到位
window.setTimeout(() => {
void scrollGridToDataRow(row);
}, 400);
} catch (e) {
console.error('跳转表格分页失败:', e);
message.warning('跳转分页失败,请手动翻页查找');
}
}
function jumpToFirstSpecMissing() {
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的SKU 编码');
return;
}
missingCycleCursor.value = 0;
void goToRowIndex(sorted[0]!);
}
function jumpToNextSpecMissing() {
const sorted = [...skuMissingRowIndices.value].sort((a, b) => a - b);
if (sorted.length === 0) {
message.info('当前没有空缺的SKU 编码');
return;
}
missingCycleCursor.value = (missingCycleCursor.value + 1) % sorted.length;
void goToRowIndex(sorted[missingCycleCursor.value]!);
}
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseFileToRawData(file);
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('CSV文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
updateTable();
nextTick(() => {
calculateTableHeight();
});
syncWizardOpen();
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
skuCodeCsvHeader.value = undefined;
skuMissingCount.value = 0;
skuMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
};
const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
skuCodeCsvHeader.value = undefined;
skuMissingCount.value = 0;
skuMissingRowIndices.value = new Set();
missingCycleCursor.value = -1;
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
const toolbarReserve = 56;
const padding = 24;
const availableHeight = rect.height - padding - toolbarReserve;
tableHeight.value = Math.max(320, availableHeight);
}
});
};
watch(
() => csvData.value.length,
(len) => {
if (len > 0) {
nextTick(() => calculateTableHeight());
}
},
);
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
resizeObserver?.disconnect();
});
</script>
<template>
<Page
auto-content-height
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<!-- 未上传:居中上传 -->
<div
v-if="csvData.length === 0"
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
>
<div class="mb-10 shrink-0 text-center">
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
订单导入中心
</h1>
<p class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base">
请上传 CSV / Excel 格式的订单原始数据
</p>
</div>
<div
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
></div>
<div class="relative w-full">
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
</div>
<!-- 已上传:左表右配置(flex-1 + min-h-0 约束在布局内容高度内,避免撑开外层滚动) -->
<div
v-else
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
>
<section
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
>
<div
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
>
<div class="min-w-0">
<h2 class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
数据预览
</h2>
<p class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm">
共 {{ csvData.length }} 条 · 右侧配置导入任务
<template v-if="skuMissingCount > 0">
·
<span class="font-medium text-amber-600 dark:text-amber-400">
SKU 编码待补 {{ skuMissingCount }} 行(点击本表对应列表格填写)
</span>
</template>
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<template v-if="skuMissingCount > 0">
<Button size="small" type="primary" @click="jumpToFirstSpecMissing">
第一处空缺
</Button>
<Button size="small" @click="jumpToNextSpecMissing">下一处空缺</Button>
</template>
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
>
<Grid />
</div>
</section>
<aside
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
>
<!-- 单独一层 flex-1,避免多根子组件时侧栏被内容撑出视口 -->
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@sku-code-column-change="onSkuCodeColumnChange"
@sku-missing-after-precheck="onSkuMissingAfterPrecheck"
@success="handleWizardSuccess"
/>
</div>
</aside>
</div>
</Page>
</template>
<style scoped>
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
/* SKU 编码为空的行:整行高亮,便于分页中辨认 */
:deep(tr.order-import-row--sku-missing) {
background-color: rgb(254 243 199) !important;
}
:deep(tr.order-import-row--sku-missing:hover) {
background-color: rgb(253 230 138) !important;
}
.dark :deep(tr.order-import-row--sku-missing) {
background-color: rgb(120 53 15 / 0.45) !important;
}
.dark :deep(tr.order-import-row--sku-missing:hover) {
background-color: rgb(120 53 15 / 0.6) !important;
}
</style>
@@ -0,0 +1,84 @@
/**
* CSV数据解析工具
* 完全动态解析,不预设任何字段
*/
import Papa from 'papaparse';
export interface CSVParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持CSV文件中的顺序) */
headers: string[];
}
/**
* 解析CSV文件为原始数据(完全动态,保持字段顺序)
*/
export async function parseCSVToRawData(file: File): Promise<CSVParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: null | Papa.ParseResult<any> = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析CSV文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV文件为空或没有有效数据');
return { data, errors, headers };
}
// 获取表头(保持CSV文件中的顺序)
headers = result.meta.fields || [];
// 直接使用原始数据,完全保持CSV文件的字段顺序和数据顺序
data.push(...result.data);
return { data, errors, headers };
}
@@ -0,0 +1,214 @@
/**
* 文件数据解析工具(支持 CSV 和 Excel)
*/
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export interface FileParseOptions {
/** 为 true 时保留仅部分单元格为空的行(推广费导入需统计金额为空等失败行) */
preserveEmptyRows?: boolean;
}
export interface FileParseResult {
/** 解析成功的数据 */
data: any[];
/** 解析错误 */
errors: string[];
/** 表头(保持文件中的顺序) */
headers: string[];
}
function isExcelFile(filename: string): boolean {
const ext = filename.toLowerCase().split('.').pop() || '';
return ext === 'xlsx' || ext === 'xls';
}
/**
* 解析 CSV 文件为原始数据
*/
async function parseCSVFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
// 尝试多种编码格式
const encodings = ['GBK', 'utf8', 'GB2312'];
let result: Papa.ParseResult<any> | null = null;
for (const encoding of encodings) {
try {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: options?.preserveEmptyRows ? false : true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
},
error: (error) => {
reject(error);
},
});
});
// 检查是否成功解析出中文内容
if (result.data && result.data.length > 0) {
const firstRow = result.data[0];
const hasChineseContent = Object.values(firstRow).some(
(value) => typeof value === 'string' && /[\u4E00-\u9FA5]/.test(value),
);
if (hasChineseContent) {
break;
}
}
} catch {
continue;
}
}
if (!result) {
errors.push('无法解析 CSV 文件,请检查文件格式和编码');
return { data, errors, headers };
}
if (result.errors.length > 0) {
errors.push(
`CSV 解析错误: ${result.errors.map((e) => e.message).join(', ')}`,
);
}
if (!result.data || result.data.length === 0) {
errors.push('CSV 文件为空或没有有效数据');
return { data, errors, headers };
}
headers = result.meta.fields || [];
data.push(...result.data);
return { data, errors, headers };
}
/**
* 解析 Excel 文件为原始数据
*/
async function parseExcelFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const arrayBuffer = e.target?.result;
if (!arrayBuffer) {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
return;
}
const workbook = XLSX.read(arrayBuffer, { type: 'array', cellDates: true });
// 默认取第一个 sheet
const sheetName = workbook.SheetNames[0];
if (!sheetName) {
errors.push('Excel 文件中没有工作表');
resolve({ data, errors, headers });
return;
}
const sheet = workbook.Sheets[sheetName];
if (!sheet) {
errors.push('Excel 文件读取失败:未找到有效工作表');
resolve({ data, errors, headers });
return;
}
// 转换为 JSON(header: 1 表示第一行作为表头)
const jsonData = XLSX.utils.sheet_to_json(sheet, {
header: 1,
defval: '',
blankrows: false,
}) as any[][];
if (jsonData.length === 0) {
errors.push('Excel 文件为空或没有有效数据');
resolve({ data, errors, headers });
return;
}
// 第一行是表头
headers = (jsonData[0] || []).map((h) => String(h ?? '').trim());
// 其余行是数据
for (let i = 1; i < jsonData.length; i++) {
const row = jsonData[i];
if (!row) {
continue;
}
if (
!options?.preserveEmptyRows &&
row.every((cell) => cell === '' || cell == null)
) {
continue;
}
const rowData: Record<string, any> = {};
headers.forEach((header, idx) => {
let value = row[idx];
// XLSX 读取日期会返回 Date 对象,转成字符串
if (value instanceof Date) {
const y = value.getFullYear();
const m = String(value.getMonth() + 1).padStart(2, '0');
const d = String(value.getDate()).padStart(2, '0');
value = `${y}-${m}-${d}`;
}
rowData[header] = value != null ? String(value).trim() : '';
});
data.push(rowData);
}
resolve({ data, errors, headers });
} catch (err: any) {
errors.push(`Excel 解析失败: ${err?.message || '未知错误'}`);
resolve({ data, errors, headers });
}
};
reader.onerror = () => {
errors.push('Excel 文件读取失败');
resolve({ data, errors, headers });
};
reader.readAsArrayBuffer(file);
});
}
/**
* 解析文件为原始数据(自动根据扩展名选择解析器)
*/
export async function parseFileToRawData(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
if (isExcelFile(file.name)) {
return parseExcelFile(file, options);
}
return parseCSVFile(file, options);
}
/**
* @deprecated 请使用 parseFileToRawData
*/
export async function parseCSVToRawData(file: File): Promise<FileParseResult> {
return parseCSVFile(file);
}
@@ -0,0 +1,52 @@
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export function buildPatchedFileName(fileName: string) {
const dot = fileName.lastIndexOf('.');
if (dot < 0) return `${fileName}_patched`;
return `${fileName.slice(0, dot)}_patched${fileName.slice(dot)}`;
}
/**
* 根据 headers + rows 重建一个“补录后”的文件,并返回新的 File 对象
* - CSV:使用 papaparse 重新生成,并添加 BOM 保证中文兼容
* - Excel:使用 xlsx 生成新的 workbook(默认一个 sheet:Sheet1)
*/
export function createPatchedFile(
sourceFile: File,
headers: string[],
rows: any[],
): File {
const ext = sourceFile.name.toLowerCase().split('.').pop() || '';
const filename = buildPatchedFileName(sourceFile.name);
if (ext === 'csv') {
const csvText = Papa.unparse(rows, { columns: headers });
const blob = new Blob([`\uFEFF${csvText}`], {
type: 'text/csv;charset=utf-8',
});
return new File([blob], filename, { type: 'text/csv;charset=utf-8' });
}
const aoa = [
headers,
...rows.map((row) => headers.map((header) => row[header] ?? '')),
];
const workbook = XLSX.utils.book_new();
const worksheet = XLSX.utils.aoa_to_sheet(aoa);
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
const wbType = ext === 'xls' ? 'xls' : 'xlsx';
const buffer = XLSX.write(workbook, {
type: 'array',
bookType: wbType,
});
const blob = new Blob([buffer], {
type:
ext === 'xls'
? 'application/vnd.ms-excel'
: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
});
return new File([blob], filename, { type: blob.type });
}
@@ -0,0 +1,163 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'PromotionFeeFileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
interface Emits {
(e: 'fileSelected', file: File): void;
}
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
const validateFile = (file: File): boolean => {
const ext = file.name.toLowerCase().split('.').pop() || '';
const allowedExts = ['csv', 'xlsx', 'xls'];
if (!allowedExts.includes(ext)) {
message.error('只能上传 CSV 或 Excel 格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<div class="space-y-4">
<div class="relative mx-auto h-12 w-12">
<UploadIcon
v-if="!loading"
class="h-12 w-12 text-gray-400 dark:text-[hsl(240deg_5%_64.9%)]"
:class="{ 'text-blue-500': isDragOver }"
/>
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
</div>
<div>
<p
class="text-lg font-medium"
:class="loading ? 'text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
:deep(.border-dashed:hover) {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
html.dark .border-dashed:hover {
border-color: hsl(240deg 3.7% 40%) !important;
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
}
</style>
@@ -0,0 +1,843 @@
<script setup lang="ts">
import type { PromotionFeeFieldVO } from '#/api/ecommerce/promotion-fee/types';
import type { ImportMappingVO } from '#/api/ecommerce/import-mapping';
import type { ImportTaskDTO } from '#/api/ecommerce/import-task';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, DatePicker, Form, Input, message, Select, Spin, Steps } from 'ant-design-vue';
import {
createImportMappingApi,
getImportMappingPageApi,
ImportMappingType,
updateImportMappingApi,
} from '#/api/ecommerce/import-mapping';
import { getPromotionFeeFieldsApi } from '#/api/ecommerce/promotion-fee/apis';
import { getShopPageApi } from '#/api/ecommerce/shop';
import { createImportTaskApi } from '#/api/ecommerce/import-task';
import { useImportTaskStore } from '#/store';
import { uploadFileToOss } from '#/utils/oss-upload';
import dayjs from 'dayjs';
interface FieldMappingItem {
fieldName: string;
fieldLabel: string;
fileFieldName?: string;
required: boolean;
}
defineOptions({ name: 'PromotionFeeImportTaskWizard' });
const emit = defineEmits<{
success: [];
}>();
const currentStep = ref(0);
const fieldDefsLoading = ref(false);
const createTaskSubmitting = ref(false);
const csvHeaders = ref<string[]>([]);
const previewData = defineModel<any[]>('previewData', { default: () => [] });
const originalImportFile = ref<File | null>(null);
const selectedFile = ref<File | null>(null);
const shopList = ref<ShopVO.Info[]>([]);
const selectedShopId = ref<number | undefined>();
const shopLoading = ref(false);
const shopPage = ref(1);
const shopPageSize = ref(20);
const shopHasMore = ref(true);
const shopSearchValue = ref('');
const feeDate = ref<any>(undefined);
const fieldDefs = ref<PromotionFeeFieldVO.Info[]>([]);
const fieldMappings = ref<
Record<string, { fieldDef: PromotionFeeFieldVO.Info; mappedHeader?: string }>
>({});
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
const selectedTemplateId = ref<number | undefined>();
const selectedTemplateName = ref('');
const templateLoading = ref(false);
const savingTemplate = ref(false);
const templateName = ref('');
const savingFieldToTemplate = ref<null | string>(null);
const currentTemplateMappings = ref<FieldMappingItem[]>([]);
const [SaveTemplateModal, saveTemplateModalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
title: '保存映射模板',
showCancelButton: true,
showConfirmButton: true,
confirmText: '保存',
cancelText: '取消',
onConfirm: handleConfirmSaveTemplate,
onCancel() {
templateName.value = '';
saveTemplateModalApi.close();
},
});
const importTaskStore = useImportTaskStore();
const canGoToNextStep = computed(() => {
if (currentStep.value === 0) {
const requiredFields = fieldDefs.value.filter((f) => f.required);
return requiredFields.every((field) => {
const mapping = fieldMappings.value[field.fieldName];
return mapping && mapping.mappedHeader;
});
}
return false;
});
const isMappingFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
return currentMapping?.mappedHeader === templateItem.fileFieldName;
};
const isMappingChangedFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
if (templateItem.fileFieldName && currentMapping?.mappedHeader !== templateItem.fileFieldName) return true;
return false;
};
const initFieldMappings = () => {
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
let mappedHeader: string | undefined;
if (fieldDef.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === fieldDef.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
};
const fetchShopList = async (reset = false) => {
if (shopLoading.value) return;
try {
shopLoading.value = true;
if (reset) {
shopList.value = [];
shopPage.value = 1;
shopHasMore.value = true;
}
const result = await getShopPageApi({
page: shopPage.value,
pageSize: shopPageSize.value,
filters: { name: shopSearchValue.value || undefined },
});
if (reset) {
shopList.value = result.records || [];
} else {
shopList.value.push(...(result.records || []));
}
shopHasMore.value = (result.records?.length || 0) === shopPageSize.value;
if (shopHasMore.value) shopPage.value++;
} catch (error) {
console.error('获取店铺列表失败:', error);
message.error('获取店铺列表失败');
} finally {
shopLoading.value = false;
}
};
const handleShopSearch = (value: string) => {
shopSearchValue.value = value;
fetchShopList(true);
};
const handleShopScroll = (e: any) => {
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight && shopHasMore.value && !shopLoading.value) {
fetchShopList();
}
};
const fetchFieldDefs = async () => {
try {
fieldDefsLoading.value = true;
const result = await getPromotionFeeFieldsApi();
fieldDefs.value = (result || []) as unknown as PromotionFeeFieldVO.Info[];
initFieldMappings();
} catch (error) {
console.error('获取字段定义失败:', error);
message.error('获取字段定义失败');
} finally {
fieldDefsLoading.value = false;
}
};
const fetchMappingTemplates = async () => {
try {
templateLoading.value = true;
const result = await getImportMappingPageApi({
page: 1,
pageSize: 100,
filters: { type: ImportMappingType.PROMOTION_FEE },
});
mappingTemplates.value = result.records || [];
if (mappingTemplates.value.length > 0 && !selectedTemplateId.value) {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
} catch (error) {
console.error('获取映射模板列表失败:', error);
message.error('获取映射模板列表失败');
} finally {
templateLoading.value = false;
}
};
const handleSelectTemplate = async (value: any) => {
const templateId = typeof value === 'number' ? value : undefined;
if (!templateId) {
selectedTemplateName.value = '';
currentTemplateMappings.value = [];
if (fieldDefs.value.length > 0) initFieldMappings();
return;
}
if (fieldDefs.value.length === 0) return;
const template = mappingTemplates.value.find((t) => t.id === templateId);
if (!template) return;
try {
const mappingItems: FieldMappingItem[] = JSON.parse(template.mapping);
selectedTemplateName.value = template.name;
currentTemplateMappings.value = mappingItems;
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
const templateItem = mappingItems.find((item) => item.fieldName === fieldDef.fieldName);
let mappedHeader: string | undefined;
if (templateItem?.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === templateItem.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
message.success('已应用映射模板');
} catch (error) {
console.error('应用映射模板失败:', error);
message.error('应用映射模板失败,模板格式可能不正确');
}
};
const handleAddFieldToTemplate = async (fieldDefId: string) => {
if (!selectedTemplateId.value) {
message.warning('请先选择一个模板');
return;
}
const mapping = fieldMappings.value[fieldDefId];
if (!mapping || !mapping.mappedHeader) {
message.warning('请先完成该字段的映射');
return;
}
const fieldDef = mapping.fieldDef;
const fieldItem: FieldMappingItem = {
fieldName: fieldDef.fieldName,
fieldLabel: fieldDef.fieldLabel,
fileFieldName: mapping.mappedHeader,
required: fieldDef.required,
};
try {
savingFieldToTemplate.value = fieldDefId;
const template = mappingTemplates.value.find((t) => t.id === selectedTemplateId.value);
if (!template) {
message.error('模板不存在');
return;
}
let mappingItems: FieldMappingItem[] = [];
try {
mappingItems = JSON.parse(template.mapping);
} catch {
mappingItems = [];
}
const existingIdx = mappingItems.findIndex((item) => item.fieldName === fieldDef.fieldName);
if (existingIdx === -1) {
mappingItems.push(fieldItem);
} else {
mappingItems[existingIdx] = fieldItem;
}
const mappingJson = JSON.stringify(mappingItems);
await updateImportMappingApi(selectedTemplateId.value, {
name: template.name,
mapping: mappingJson,
});
template.mapping = mappingJson;
currentTemplateMappings.value = mappingItems;
message.success(`已将「${fieldDef.fieldLabel}」映射添加到模板`);
} catch (error: any) {
console.error('添加到模板失败:', error);
message.error(error?.message || '添加到模板失败');
} finally {
savingFieldToTemplate.value = null;
}
};
const handleSaveTemplate = () => {
if (selectedTemplateId.value) {
message.info('已有模板选中,请使用每行「添加到模板」按钮单独更新字段映射');
return;
}
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
if (mappingItems.length === 0) {
message.warning('请先完成字段映射');
return;
}
templateName.value = '';
saveTemplateModalApi.open();
};
async function handleConfirmSaveTemplate() {
if (!templateName.value.trim()) {
message.warning('请输入模板名称');
return;
}
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定所有必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
try {
savingTemplate.value = true;
saveTemplateModalApi.lock();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
await createImportMappingApi({
type: ImportMappingType.PROMOTION_FEE,
name: templateName.value.trim(),
mapping: JSON.stringify(mappingItems),
});
message.success('保存映射模板成功');
templateName.value = '';
saveTemplateModalApi.close();
await fetchMappingTemplates();
} catch (error: any) {
console.error('保存映射模板失败:', error);
message.error(error?.message || '保存映射模板失败');
} finally {
savingTemplate.value = false;
saveTemplateModalApi.unlock();
}
}
const handleNext = async () => {
if (currentStep.value !== 0) return;
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
await fetchShopList(true);
}
currentStep.value = 1;
};
const handlePrev = () => {
if (currentStep.value > 0) currentStep.value--;
};
const buildPatchedCsv = (): File => {
const headers = [...csvHeaders.value, 'feeTypeId', 'categoryId', 'productId'];
const rows = previewData.value.map((row: any) =>
headers.map((h: string) => {
if (h === 'feeTypeId') return row._feeTypeId ?? '';
if (h === 'categoryId') return row._categoryId ?? '';
if (h === 'productId') return row._productId ?? '';
return row[h] ?? '';
}),
);
const csvContent = `\uFEFF${[
headers.join(','),
...rows.map((r: any[]) => r.map((v: any) => `"${String(v).replace(/"/g, '""')}"`).join(',')),
].join('\n')}`;
return new File([csvContent], buildPatchedFileName(originalImportFile.value?.name || 'data.csv'), {
type: 'text/csv;charset=utf-8',
});
};
const buildPatchedFileName = (_original: string): string => {
return 'promotion_fee_import_patched.csv';
};
const handleCreateTask = async () => {
if (!selectedFile.value && !originalImportFile.value) {
message.error('文件信息丢失,请重新上传');
return;
}
if (selectedShopId.value === undefined) {
message.warning('请选择店铺');
return;
}
if (!feeDate.value) {
message.warning('请选择推广费发生日期');
return;
}
try {
createTaskSubmitting.value = true;
message.loading('正在上传文件...', 0);
const patchedFile = buildPatchedCsv();
const fileInfo = await uploadFileToOss(patchedFile, {
category: 'promotion-fee-import',
errorMessage: '文件上传失败,请重试',
});
message.destroy();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
const fullMapping = {
fieldMapping: mappingItems,
feeDate: dayjs(feeDate.value).format('YYYY-MM-DD'),
};
const createData: ImportTaskDTO.CreateImportTaskDTO = {
shopId: selectedShopId.value!,
type: 'promotion_record',
fileName: patchedFile.name,
fileId: fileInfo.id,
mapping: JSON.stringify(fullMapping),
};
const task = await createImportTaskApi(createData);
message.success('创建导入任务成功');
importTaskStore.updateTask(task);
await importTaskStore.fetchTasks(true);
importTaskStore.openDropdown();
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
emit('success');
} catch (error: any) {
message.destroy();
console.error('创建导入任务失败:', error);
message.error(error?.message || '创建导入任务失败');
} finally {
createTaskSubmitting.value = false;
}
};
async function open(headers: string[], file?: File) {
csvHeaders.value = headers;
originalImportFile.value = file ?? null;
selectedFile.value = file ?? null;
currentStep.value = 0;
fieldMappings.value = {};
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
void fetchShopList(true);
}
if (fieldDefs.value.length === 0) {
await fetchFieldDefs();
} else {
initFieldMappings();
}
if (mappingTemplates.value.length === 0) {
await fetchMappingTemplates();
} else if (selectedTemplateId.value) {
await handleSelectTemplate(selectedTemplateId.value);
} else {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
}
function reset() {
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
}
defineExpose({ open, reset });
const shopOptions = computed(() => {
return shopList.value.map((shop: ShopVO.Info) => ({
label: shop.platformName ? `${shop.name} (${shop.platformName})` : shop.name,
value: shop.id,
}));
});
</script>
<template>
<div
class="import-task-wizard flex h-full min-h-0 w-full flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div class="shrink-0 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]">
<div class="text-base font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
创建导入任务
</div>
<p
v-if="selectedFile"
class="mb-0 mt-1 truncate text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ selectedFile.name }} · {{ previewData.length }} 条
</p>
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<div
class="import-task-wizard-main grid min-h-0 min-w-0 w-full flex-1 grid-rows-[auto_minmax(0,1fr)] gap-3 overflow-hidden px-3 py-3"
>
<div class="min-w-0 shrink-0">
<Steps :current="currentStep">
<Steps.Step title="字段映射" />
<Steps.Step title="确认信息" />
</Steps>
</div>
<div class="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
<div
v-if="currentStep === 0"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-2"
>
<div class="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 gap-y-3">
<div class="text-sm text-gray-600 dark:text-gray-300">
请为每个推广费字段选择对应的CSV列,必填字段必须绑定
</div>
<div class="flex items-center space-x-2">
<Select
v-model:value="selectedTemplateId"
placeholder="选择已有模板"
class="w-[200px]"
:loading="templateLoading"
allow-clear
@change="handleSelectTemplate"
>
<template #notFoundContent>
<div v-if="templateLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无模板
</div>
</template>
<Select.Option
v-for="template in mappingTemplates"
:key="template.id"
:value="template.id"
>
{{ template.name }}
<span class="ml-2 text-xs text-gray-400 dark:text-gray-500">
({{ new Date(template.createTime).toLocaleDateString() }})
</span>
</Select.Option>
</Select>
<Button :disabled="selectedTemplateId !== undefined" @click="handleSaveTemplate">
保存为模板
</Button>
</div>
</div>
<template v-if="fieldDefsLoading">
<div class="flex min-h-[200px] flex-1 items-center justify-center text-gray-500 dark:text-gray-400">
<Spin size="large" />
<span class="ml-3 text-sm">加载字段定义中…</span>
</div>
</template>
<div
v-else
class="min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-y-contain pr-0.5"
>
<div
v-for="fieldDef in fieldDefs"
:key="fieldDef.fieldName"
class="flex min-w-0 flex-col overflow-hidden rounded-lg border p-0"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'border-red-300 dark:border-red-700'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'border-yellow-200 dark:border-yellow-700'
: isMappingFromTemplate(fieldDef.fieldName)
? 'border-blue-200 dark:border-blue-700'
: 'border-slate-200 dark:border-slate-600'
"
>
<div
class="border-b border-slate-200/90 bg-gradient-to-r to-transparent px-3 py-2.5 dark:border-slate-600"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'from-red-50/90 dark:from-red-950/35'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'from-amber-50/75 dark:from-amber-950/30'
: isMappingFromTemplate(fieldDef.fieldName)
? 'from-blue-50/90 dark:from-blue-950/40'
: 'from-blue-50/95 dark:from-blue-950/35'
"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-blue-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-blue-500"
>
系统
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
推广费字段
</span>
</div>
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
<span class="font-medium leading-snug text-slate-900 dark:text-slate-100">
{{ fieldDef.fieldLabel }}
</span>
<span v-if="fieldDef.required" class="text-xs text-red-500 dark:text-red-400">
必填
</span>
<span
v-if="selectedTemplateId && isMappingFromTemplate(fieldDef.fieldName)"
class="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
>
模板映射
</span>
<span
v-if="selectedTemplateId && isMappingChangedFromTemplate(fieldDef.fieldName)"
class="rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800 dark:bg-amber-900/40 dark:text-amber-200"
>
已变更
</span>
</div>
</div>
<div
class="bg-gradient-to-r from-amber-50/90 to-transparent px-3 py-2.5 dark:from-amber-950/25"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-amber-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-amber-600"
>
文件
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
CSV 列
</span>
</div>
<div class="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-2">
<Select
v-if="fieldMappings[fieldDef.fieldName]"
v-model:value="fieldMappings[fieldDef.fieldName]!.mappedHeader"
placeholder="选择该字段对应的 CSV 列"
class="w-full min-w-0 sm:flex-1"
show-search
allow-clear
:options="csvHeaders.map((h) => ({ label: h, value: h }))"
/>
<Button
v-if="selectedTemplateId && fieldMappings[fieldDef.fieldName]?.mappedHeader"
size="small"
type="link"
class="h-auto shrink-0 self-start px-0 py-0 sm:self-center"
:disabled="isMappingFromTemplate(fieldDef.fieldName)"
:loading="savingFieldToTemplate === fieldDef.fieldName"
@click="handleAddFieldToTemplate(fieldDef.fieldName)"
>
添加到模板
</Button>
</div>
</div>
</div>
</div>
</div>
<div
v-if="currentStep === 1"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto py-2"
>
<div class="space-y-4">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="选择店铺" required>
<Select
v-model:value="selectedShopId"
placeholder="请选择店铺"
show-search
:filter-option="false"
:loading="shopLoading"
@search="handleShopSearch"
@popup-scroll="handleShopScroll"
>
<template #notFoundContent>
<div v-if="shopLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无数据
</div>
</template>
<Select.Option
v-for="option in shopOptions"
:key="option.value"
:value="option.value"
:label="option.label"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="发生日期" required>
<DatePicker
v-model:value="feeDate"
placeholder="选择推广费发生日期"
style="width: 100%"
/>
</Form.Item>
</Form>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">字段映射</div>
<div class="space-y-2">
<div
v-for="mapping in Object.values(fieldMappings).filter((m) => m.mappedHeader)"
:key="mapping.fieldDef.fieldName"
class="flex justify-between text-sm"
>
<span class="text-gray-600 dark:text-gray-300">{{ mapping.fieldDef.fieldLabel }}:</span>
<span class="font-medium">{{ mapping.mappedHeader }}</span>
</div>
</div>
</div>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">导入配置摘要</div>
<div class="space-y-2">
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">数据行数</span>
<span class="font-medium">{{ previewData.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">已映射字段</span>
<span class="font-medium">{{ Object.values(fieldMappings).filter((m) => m.mappedHeader).length }}/{{ fieldDefs.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">推广费类型/类目/商品</span>
<span class="font-medium text-green-600">表格中逐行设置</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="flex shrink-0 flex-wrap justify-end gap-2 border-t border-slate-100 bg-slate-50/80 px-3 py-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/40%)]"
>
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
<Button
v-if="currentStep < 1"
type="primary"
:disabled="!canGoToNextStep"
@click="handleNext"
>
下一步
</Button>
<Button
v-if="currentStep === 1"
type="primary"
:loading="createTaskSubmitting"
@click="handleCreateTask"
>
创建导入任务
</Button>
</div>
</div>
<SaveTemplateModal :confirm-loading="savingTemplate">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="模板名称" required>
<Input
v-model:value="templateName"
placeholder="请输入模板名称"
:maxlength="50"
show-count
@press-enter="handleConfirmSaveTemplate"
/>
</Form.Item>
</Form>
</SaveTemplateModal>
</template>
<style scoped>
.import-task-wizard-main {
min-height: 0;
}
.import-task-wizard-main > :last-child {
min-height: 0;
align-self: stretch;
}
</style>
@@ -0,0 +1,399 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from '#/views/ec/import/order/utils/fileParser';
import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type/apis';
import { getCategoryTreeApi } from '#/api/ecommerce/category/apis';
import { getProductPageApi } from '#/api/ecommerce/product/apis';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/promotion-fee-type/types';
import type { CategoryVO } from '#/api/ecommerce/category/types';
import type { ProductVO } from '#/api/ecommerce/product/types';
defineOptions({ name: 'PromotionFeeImport' });
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
const feeTypeOptions = ref<PromotionFeeTypeVO.Info[]>([]);
const categoryTree = ref<CategoryVO.Info[]>([]);
const productList = ref<ProductVO.Info[]>([]);
const loadReferenceData = async () => {
try {
const [feeTypesRes, categoryRes, productRes] = await Promise.all([
getActivePromotionFeeTypeListApi(),
getCategoryTreeApi(),
getProductPageApi({ page: 1, pageSize: 9999, filters: {} }),
]);
feeTypeOptions.value = feeTypesRes as unknown as PromotionFeeTypeVO.Info[];
categoryTree.value = categoryRes as unknown as CategoryVO.Info[];
productList.value = ((productRes as any).records || []) as ProductVO.Info[];
} catch (e) {
console.error('加载参考数据失败', e);
}
};
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) return [];
const columns: VxeGridProps<any>['columns'] = [
{ type: 'seq' as const, title: '序号', width: 80, fixed: 'left' as const },
];
csvHeaders.value.forEach((header) => {
columns.push({
field: header,
title: header,
minWidth: 150,
showOverflow: 'tooltip' as const,
});
});
columns.push(
{
field: '_feeTypeId',
title: '推广费类型',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: feeTypeOptions.value.map((t) => ({
label: t.typeName,
value: t.id,
})),
allowClear: true,
placeholder: '请选择',
},
},
},
{
field: '_categoryId',
title: '类目',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellTreeSelect',
props: {
treeData: categoryTree.value,
fieldNames: { label: 'name', value: 'id', children: 'children' },
allowClear: true,
placeholder: '请选择',
treeDefaultExpandAll: false,
},
},
},
{
field: '_productId',
title: '商品',
width: 180,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: productList.value.map((p) => ({
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
value: p.id,
categoryId: (p as any).categoryId,
})),
filterByRowField: '_categoryId',
filterOptionKey: 'categoryId',
allowClear: true,
placeholder: '请选择商品',
showSearch: true,
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
},
},
},
);
return columns;
});
const gridOptions: VxeGridProps<any> = {
columns: [],
height: tableHeight.value,
border: true,
stripe: true,
rowConfig: { isHover: true, height: 44 },
showOverflow: true,
size: 'small',
data: [],
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
if (csvData.value.length === 0) {
return { items: [], total: 0 };
}
const currentPage = page.currentPage || 1;
const pageSize = page.pageSize || 50;
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
total: csvData.value.length,
};
},
},
},
};
const gridEvents = {};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
});
gridApi.reload();
};
const syncWizardOpen = () => {
if (csvData.value.length === 0 || csvHeaders.value.length === 0) return;
nextTick(() => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
);
});
};
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseFileToRawData(file, { preserveEmptyRows: true });
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
updateTable();
nextTick(() => {
calculateTableHeight();
});
syncWizardOpen();
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
// 加载参考数据用于表格行内下拉选择
await loadReferenceData();
updateTable();
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
};
const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
const toolbarReserve = 56;
const padding = 24;
const availableHeight = rect.height - padding - toolbarReserve;
tableHeight.value = Math.max(320, availableHeight);
}
});
};
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
resizeObserver?.disconnect();
});
</script>
<template>
<Page
auto-content-height
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div
v-if="csvData.length === 0"
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
>
<div class="mb-10 shrink-0 text-center">
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
推广费导入中心
</h1>
<p
class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base"
>
请上传 CSV / Excel 格式的推广费原始数据
</p>
</div>
<div
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
>
</div>
<div class="relative w-full">
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
</div>
<div
v-else
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
>
<section
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
>
<div
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
>
<div class="min-w-0">
<h2
class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
>
数据预览
</h2>
<p
class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm"
>
共 {{ csvData.length }} 条 · 右侧配置导入任务
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
>
<Grid />
</div>
</section>
<aside
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@success="handleWizardSuccess"
/>
</div>
</aside>
</div>
</Page>
</template>
<style scoped>
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
</style>
@@ -0,0 +1,263 @@
<script lang="ts" setup>
import type { OrderItemVO, OrderVO } from '#/api/ecommerce/order';
import { computed, ref } from 'vue';
import {
Descriptions,
DescriptionsItem,
Drawer,
Image,
Table,
Tag,
message,
} from 'ant-design-vue';
import { getOrderByIdApi } from '#/api/ecommerce/order';
import PlatformTag from '#/components/platform/PlatformTag.vue';
import {
getOrderPayAmount,
getOrderReceivedAmount,
getOrderServiceFee,
} from '#/utils/order-display';
defineOptions({ name: 'OrderDetailDrawer' });
const SOURCE_LABEL: Record<string, string> = {
import: '导入',
sync: '同步',
manual: '手动',
};
const openFlag = ref(false);
const loading = ref(false);
const detail = ref<null | OrderVO.Info>(null);
const itemColumns = [
{ title: '商品', key: 'goods', dataIndex: 'linkProductName' },
{
title: '规格',
dataIndex: 'linkSkuName',
key: 'linkSkuName',
ellipsis: true,
},
{ title: '数量', dataIndex: 'quantity', key: 'quantity', width: 70 },
{ title: '单价', key: 'unitPrice', width: 100 },
{ title: '行金额', key: 'lineAmount', width: 100 },
{ title: '商品成本', key: 'productCost', width: 100 },
{ title: '运费成本', key: 'shippingCost', width: 100 },
{ title: '其他成本', key: 'otherCost', width: 100 },
{
title: 'SKU编码',
dataIndex: 'skuCode',
key: 'skuCode',
ellipsis: true,
},
];
const moneyFields = computed(() => {
const d = detail.value;
if (!d) return [];
return [
{ label: '实付', value: getOrderPayAmount(d) },
{ label: '服务费', value: getOrderServiceFee(d) },
{ label: '商家实收', value: getOrderReceivedAmount(d) },
{ label: '商品金额', value: d.goodsAmount },
{ label: '折扣', value: d.discountAmount },
{ label: '邮费', value: d.postage },
{ label: '平台优惠', value: d.platformDiscount },
{ label: '商家优惠', value: d.sellerDiscount },
];
});
function money(v?: null | number) {
if (v == null || Number.isNaN(Number(v))) return '-';
return `¥${Number(v).toFixed(2)}`;
}
function sourceText(source?: string) {
if (!source) return '-';
return SOURCE_LABEL[source] ?? source;
}
function itemTitle(item: OrderItemVO.Info) {
return item.product?.name || item.linkProductName || '-';
}
function itemSpec(item: OrderItemVO.Info) {
return item.productSku?.name || item.linkSkuName || '-';
}
async function open(id: number) {
openFlag.value = true;
loading.value = true;
detail.value = null;
try {
detail.value = await getOrderByIdApi(id);
} catch (error) {
console.error(error);
message.error('加载订单详情失败');
openFlag.value = false;
} finally {
loading.value = false;
}
}
function close() {
openFlag.value = false;
}
defineExpose({ open, close });
</script>
<template>
<Drawer
v-model:open="openFlag"
title="订单详情"
width="780"
destroy-on-close
:loading="loading"
>
<template v-if="detail">
<Descriptions bordered :column="2" size="small" class="mb-4">
<DescriptionsItem label="平台订单号" :span="2">
{{ detail.platformOrderNo || '-' }}
</DescriptionsItem>
<DescriptionsItem label="店铺">
{{ detail.shopName || detail.shop?.name || `店铺#${detail.shopId}` }}
</DescriptionsItem>
<DescriptionsItem label="平台">
<PlatformTag
:code="detail.platformCode"
:label="detail.platformLabel"
show-empty
/>
</DescriptionsItem>
<DescriptionsItem label="订单状态">
<Tag :color="detail.statusColor || 'blue'">
{{ detail.statusLabel || detail.status || '-' }}
</Tag>
</DescriptionsItem>
<DescriptionsItem label="来源">
{{ sourceText(detail.source) }}
</DescriptionsItem>
<DescriptionsItem label="运单号">
{{ detail.trackingNumber || '-' }}
</DescriptionsItem>
<DescriptionsItem label="快递编码">
{{ detail.logisticsId || '-' }}
</DescriptionsItem>
<DescriptionsItem label="下单时间">
{{ detail.orderTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="支付时间">
{{ detail.payTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="成交时间">
{{ detail.confirmTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="发货时间">
{{ detail.shippingTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="签收时间">
{{ detail.receiveTime || '-' }}
</DescriptionsItem>
<DescriptionsItem label="最近转换">
{{ detail.lastMappedTime || '-' }}
</DescriptionsItem>
<DescriptionsItem
v-for="item in moneyFields"
:key="item.label"
:label="item.label"
>
{{ money(item.value) }}
</DescriptionsItem>
<DescriptionsItem label="收件人">
{{ detail.receiverNameMask || '-' }}
</DescriptionsItem>
<DescriptionsItem label="手机">
{{ detail.receiverPhoneMask || '-' }}
</DescriptionsItem>
<DescriptionsItem label="地区" :span="2">
{{
[detail.province, detail.city, detail.town]
.filter(Boolean)
.join(' / ') || '-'
}}
</DescriptionsItem>
<DescriptionsItem label="地址" :span="2">
{{ detail.receiverAddressMask || '-' }}
</DescriptionsItem>
<DescriptionsItem label="买家留言" :span="2">
{{ detail.buyerMemo || '-' }}
</DescriptionsItem>
<DescriptionsItem label="备注" :span="2">
{{ detail.remark || '-' }}
</DescriptionsItem>
</Descriptions>
<div class="mb-2 font-medium">商品明细</div>
<Table
:columns="itemColumns"
:data-source="detail.items || []"
:pagination="false"
:row-key="(r: OrderItemVO.Info) => r.id ?? r.lineNo"
size="small"
bordered
:scroll="{ x: 900 }"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'goods'">
<div class="goods-row">
<Image
v-if="record.goodsImg"
:src="record.goodsImg"
:width="36"
:height="36"
/>
<span>{{ itemTitle(record) }}</span>
</div>
</template>
<template v-else-if="column.key === 'linkSkuName'">
{{ itemSpec(record) }}
</template>
<template v-else-if="column.key === 'unitPrice'">
{{ money(record.unitPrice) }}
</template>
<template v-else-if="column.key === 'lineAmount'">
{{ money(record.lineAmount) }}
</template>
<template v-else-if="column.key === 'productCost'">
{{ money(record.productCost) }}
</template>
<template v-else-if="column.key === 'shippingCost'">
{{ money(record.shippingCost) }}
</template>
<template v-else-if="column.key === 'otherCost'">
{{ money(record.otherCost) }}
</template>
</template>
</Table>
</template>
</Drawer>
</template>
<style scoped>
.mb-4 {
margin-bottom: 16px;
}
.mb-2 {
margin-bottom: 8px;
}
.font-medium {
font-weight: 500;
}
.goods-row {
display: flex;
gap: 8px;
align-items: center;
}
</style>
@@ -0,0 +1,787 @@
<script lang="ts" setup>
import type { OrderDTO, OrderVO } from '#/api/ecommerce/order';
import type {
ProductSkuDTO,
ProductSkuVO,
} from '#/api/ecommerce/product-sku/types';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
Spin,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
createOrderApi,
updateOrderApi,
} from '#/api/ecommerce/order';
import { ORDER_STATUS_OPTIONS } from '#/api/ecommerce/order/types/types.enum';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getProductSkuPageApi } from '#/api/ecommerce/product-sku';
import { getShopPageApi } from '#/api/ecommerce/shop';
import {
getFirstOrderItem,
getOrderPayAmount,
getOrderReceivedAmount,
getOrderServiceFee,
} from '#/utils/order-display';
const emit = defineEmits<{
cancel: [];
success: [];
}>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[600px]',
onCancel() {
close();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<null | OrderVO.Info>(null);
// 表单数据
/** 表单含 UI 用 productId(选规格);提交组 items[0] + payAmount */
const formData = ref<
Partial<OrderDTO.Create> & { productId?: number; payAmount?: number }
>({
shopId: undefined,
platformOrderNo: '',
status: undefined as string | undefined,
payAmount: 0,
serviceFee: 0,
receivedAmount: undefined,
orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: undefined,
productSkuId: undefined,
skuCode: undefined,
linkProductName: '',
linkSkuName: '',
quantity: 1,
unitPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
});
// 下拉选项数据
const shopOptions = ref<{ label: string; value: number }[]>([]);
const shopLoading = ref(false);
const shopSearchKeyword = ref('');
const shopPage = ref(1);
const shopPageSize = 20;
const shopTotal = ref(0);
const shopLoaded = ref(false);
let shopSearchTimer: null | ReturnType<typeof setTimeout> = null;
/** 订单状态为后端软约定枚举,前端静态字典,不请求状态表 */
const orderStatusOptions = ORDER_STATUS_OPTIONS;
// 商品选项数据(支持分页)
const productOptions = ref<
{ label: string; product: ProductVO.Info; value: number }[]
>([]);
const productLoading = ref(false);
const productSearchKeyword = ref('');
const productPage = ref(1);
const productPageSize = 50;
const productTotal = ref(0);
const productLoaded = ref(false);
let productSearchTimer: null | ReturnType<typeof setTimeout> = null;
// 规格选项数据(支持分页)
const productSkuOptions = ref<
{ label: string; sku: ProductSkuVO.Info; value: number }[]
>([]);
const productSkuLoading = ref(false);
const productSkuSearchKeyword = ref('');
const skuPage = ref(1);
const skuPageSize = 50;
const skuTotal = ref(0);
const skuLoaded = ref(false);
let skuSearchTimer: null | ReturnType<typeof setTimeout> = null;
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
status: [{ required: true, message: '请选择订单状态', trigger: 'change' }],
payAmount: [
{ required: true, message: '请输入实付/商家实收金额', trigger: 'blur' },
],
orderTime: [{ required: true, message: '请选择下单时间', trigger: 'change' }],
productId: [{ required: true, message: '请选择商品', trigger: 'change' }],
productSkuId: [{ required: true, message: '请选择商品 SKU', trigger: 'change' }],
quantity: [{ required: true, message: '请输入数量', trigger: 'blur' }],
unitPrice: [{ required: true, message: '请输入销售单价', trigger: 'blur' }],
productCost: [{ required: true, message: '请输入商品成本', trigger: 'blur' }],
};
// 表单引用
const formRef = ref();
// 获取店铺选项(分页 + 搜索)
async function fetchShopOptions(page = 1, append = false) {
if (shopLoading.value) return;
shopLoading.value = true;
try {
const params: PageQueryDTO<ShopDTO.Filters> = {
page,
pageSize: shopPageSize,
filters: shopSearchKeyword.value
? { name: shopSearchKeyword.value }
: {},
};
const data = await getShopPageApi(params);
const mapped = data.records.map((shop: ShopVO.Info) => ({
label: shop.name,
value: shop.id,
}));
shopOptions.value = append ? [...shopOptions.value, ...mapped] : mapped;
shopTotal.value = data.total;
shopPage.value = page;
shopLoaded.value = true;
} catch (error) {
console.error('获取店铺列表失败:', error);
} finally {
shopLoading.value = false;
}
}
function handleShopSearch(value: string) {
if (shopSearchTimer) clearTimeout(shopSearchTimer);
shopSearchTimer = setTimeout(() => {
shopSearchKeyword.value = value;
shopPage.value = 1;
fetchShopOptions(1, false);
}, 300);
}
function handleShopPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = shopPage.value * shopPageSize < shopTotal.value;
if (hasMore && !shopLoading.value) {
fetchShopOptions(shopPage.value + 1, true);
}
}
}
/** 编辑回填:保证当前店铺出现在选项中 */
function ensureShopOption(record?: OrderVO.Info) {
if (!record?.shopId) return;
if (shopOptions.value.some((o) => o.value === record.shopId)) return;
shopOptions.value = [
{
label: record.shopName || record.shop?.name || `店铺#${record.shopId}`,
value: record.shopId,
},
...shopOptions.value,
];
}
// 分页加载商品列表
async function fetchProducts(page = 1, append = false) {
if (productLoading.value) return;
productLoading.value = true;
try {
const params: PageQueryDTO<ProductDTO.Filters> = {
page,
pageSize: productPageSize,
filters: {
keywords: productSearchKeyword.value || undefined,
},
};
const data = await getProductPageApi(params);
productOptions.value = append
? [
...productOptions.value,
...data.records.map((product: ProductVO.Info) => ({
label: `${product.name}${product.productCode ? ` (${product.productCode})` : ''}`,
value: product.id,
product,
})),
]
: data.records.map((product: ProductVO.Info) => ({
label: `${product.name}${product.productCode ? ` (${product.productCode})` : ''}`,
value: product.id,
product,
}));
productTotal.value = data.total;
productPage.value = page;
productLoaded.value = true;
} catch (error) {
console.error('获取商品列表失败:', error);
message.error('获取商品列表失败');
} finally {
productLoading.value = false;
}
}
// 搜索商品(防抖)
function handleProductSearch(value: string) {
if (productSearchTimer) clearTimeout(productSearchTimer);
productSearchTimer = setTimeout(() => {
productSearchKeyword.value = value;
productPage.value = 1;
fetchProducts(1, false);
}, 300);
}
// 滚动加载更多商品
function handleProductPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = productPage.value * productPageSize < productTotal.value;
if (hasMore && !productLoading.value) {
fetchProducts(productPage.value + 1, true);
}
}
}
// 分页加载规格列表
async function fetchProductSkus(page = 1, append = false) {
if (!formData.value.productId) {
productSkuOptions.value = [];
return;
}
if (productSkuLoading.value) return;
productSkuLoading.value = true;
try {
const params: PageQueryDTO<ProductSkuDTO.Filters> = {
page,
pageSize: skuPageSize,
filters: {
productId: formData.value.productId,
keywords: productSkuSearchKeyword.value || undefined,
},
};
const data = await getProductSkuPageApi(params);
productSkuOptions.value = append
? [
...productSkuOptions.value,
...data.records.map((sku: ProductSkuVO.Info) => ({
label: `${sku.name}${sku.skuCode ? ` (${sku.skuCode})` : ''}`,
value: sku.id,
sku,
})),
]
: data.records.map((sku: ProductSkuVO.Info) => ({
label: `${sku.name}${sku.skuCode ? ` (${sku.skuCode})` : ''}`,
value: sku.id,
sku,
}));
skuTotal.value = data.total;
skuPage.value = page;
skuLoaded.value = true;
} catch (error) {
console.error('获取 SKU 列表失败:', error);
message.error('获取 SKU 列表失败');
} finally {
productSkuLoading.value = false;
}
}
// 搜索规格(防抖)
function handleProductSkuSearch(value: string) {
if (skuSearchTimer) clearTimeout(skuSearchTimer);
skuSearchTimer = setTimeout(() => {
productSkuSearchKeyword.value = value;
skuPage.value = 1;
fetchProductSkus(1, false);
}, 300);
}
// 滚动加载更多规格
function handleSpecPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = skuPage.value * skuPageSize < skuTotal.value;
if (hasMore && !productSkuLoading.value) {
fetchProductSkus(skuPage.value + 1, true);
}
}
}
// 处理商品选择
function handleProductChange(productId: number | undefined) {
if (productId) {
const selectedProduct = productOptions.value.find(
(opt) => opt.value === productId,
);
if (selectedProduct) {
formData.value.linkProductName = selectedProduct.product.name;
}
// 重置规格状态,重新加载
skuLoaded.value = false;
skuPage.value = 1;
productSkuOptions.value = [];
formData.value.productSkuId = undefined;
formData.value.skuCode = undefined;
formData.value.linkSkuName = '';
formData.value.productCost = 0;
formData.value.shippingCost = 0;
formData.value.otherCost = 0;
fetchProductSkus(1, false);
} else {
formData.value.linkProductName = '';
formData.value.productSkuId = undefined;
formData.value.skuCode = undefined;
formData.value.linkSkuName = '';
formData.value.productCost = 0;
formData.value.shippingCost = 0;
formData.value.otherCost = 0;
productSkuOptions.value = [];
}
}
// 处理规格选择
function handleProductSkuChange(skuId: number | undefined) {
if (skuId) {
const selectedSku = productSkuOptions.value.find(
(opt) => opt.value === skuId,
);
if (selectedSku) {
formData.value.linkSkuName = selectedSku.sku.name;
formData.value.skuCode = selectedSku.sku.skuCode;
formData.value.productCost = selectedSku.sku.productCost;
formData.value.shippingCost = selectedSku.sku.shippingCost || 0;
formData.value.otherCost = selectedSku.sku.otherCost || 0;
}
} else {
formData.value.linkSkuName = '';
formData.value.skuCode = undefined;
formData.value.productCost = 0;
formData.value.shippingCost = 0;
formData.value.otherCost = 0;
}
}
// 打开模态框
async function open(edit: boolean, record?: OrderVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
// 加载下拉选项数据(状态用静态枚举,无需请求)
shopSearchKeyword.value = '';
shopLoaded.value = false;
await fetchShopOptions(1, false);
ensureShopOption(record);
modalApi.open();
const firstItem = record ? getFirstOrderItem(record) : undefined;
// 根据模式填充表单数据(编辑从 items[0] 回填)
formData.value =
edit && record
? {
shopId: record.shopId,
platformOrderNo: record.platformOrderNo || '',
status: record.status,
payAmount: getOrderPayAmount(record),
serviceFee: getOrderServiceFee(record),
receivedAmount: getOrderReceivedAmount(record),
orderTime: record.orderTime
? dayjs(record.orderTime).format('YYYY-MM-DD HH:mm:ss')
: dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: firstItem?.product?.id ?? firstItem?.productId,
productSkuId: firstItem?.productSkuId,
skuCode: firstItem?.skuCode,
linkProductName:
firstItem?.linkProductName ?? record.firstLinkProductName ?? '',
linkSkuName: firstItem?.linkSkuName,
quantity: firstItem?.quantity ?? 1,
unitPrice: firstItem?.unitPrice ?? 0,
productCost: firstItem?.productCost ?? 0,
shippingCost: firstItem?.shippingCost ?? 0,
otherCost: firstItem?.otherCost ?? 0,
remark: record.remark || firstItem?.remark || '',
}
: {
shopId: undefined,
platformOrderNo: '',
status: undefined,
payAmount: 0,
serviceFee: 0,
receivedAmount: undefined,
orderTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
productId: undefined,
productSkuId: undefined,
skuCode: undefined,
linkProductName: '',
linkSkuName: '',
quantity: 1,
unitPrice: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
remark: '',
};
// 如果是编辑模式且有商品/规格,加载商品和规格选项
if (edit && record && (firstItem?.product?.id ?? firstItem?.productSkuId)) {
await fetchProducts(1, false);
const pid = firstItem?.product?.id ?? firstItem?.productId;
const linkProductName =
firstItem?.linkProductName ?? record.firstLinkProductName ?? '';
if (pid && !productOptions.value.some((opt) => opt.value === pid)) {
productOptions.value.push({
label: linkProductName,
value: pid,
product: {
id: pid,
name: linkProductName,
} as ProductVO.Info,
});
}
if (firstItem?.productSkuId) {
await fetchProductSkus(1, false);
if (
!productSkuOptions.value.some(
(opt) => opt.value === firstItem.productSkuId,
)
) {
productSkuOptions.value.push({
label: firstItem.linkSkuName || '',
value: firstItem.productSkuId,
sku: {
id: firstItem.productSkuId,
name: firstItem.linkSkuName || '',
productCost: firstItem.productCost,
shippingCost: firstItem.shippingCost,
otherCost: firstItem.otherCost,
} as ProductSkuVO.Info,
});
}
}
}
}
// 关闭模态框
function close() {
modalApi.close();
formRef.value?.resetFields();
emit('cancel');
}
// 提交表单
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
const productOpt = productOptions.value.find(
(o) => o.value === formData.value.productId,
);
const skuOpt = productSkuOptions.value.find(
(o) => o.value === formData.value.productSkuId,
);
const linkProductName =
formData.value.linkProductName?.trim() ||
productOpt?.product.name ||
productOpt?.label ||
'未知商品';
const linkSkuName =
formData.value.linkSkuName?.trim() ||
skuOpt?.sku.name ||
undefined;
const itemPayload = {
productSkuId: formData.value.productSkuId,
skuCode: formData.value.skuCode,
linkProductName,
linkSkuName,
quantity: formData.value.quantity!,
unitPrice: formData.value.unitPrice,
productCost: formData.value.productCost,
shippingCost: formData.value.shippingCost,
otherCost: formData.value.otherCost,
remark: formData.value.remark,
};
if (isEdit.value && currentRecord.value) {
const updateData: OrderDTO.Update = {
shopId: formData.value.shopId!,
platformOrderNo: formData.value.platformOrderNo,
status: formData.value.status,
payAmount: formData.value.payAmount!,
serviceFee: formData.value.serviceFee,
receivedAmount: formData.value.receivedAmount,
orderTime: formData.value.orderTime!,
items: [itemPayload],
remark: formData.value.remark,
};
await updateOrderApi(currentRecord.value.id, updateData);
message.success('更新订单成功');
} else {
const createData: OrderDTO.Create = {
shopId: formData.value.shopId!,
platformOrderNo: formData.value.platformOrderNo,
status: formData.value.status!,
payAmount: formData.value.payAmount!,
serviceFee: formData.value.serviceFee,
receivedAmount: formData.value.receivedAmount,
orderTime: formData.value.orderTime!,
items: [itemPayload],
remark: formData.value.remark,
};
await createOrderApi(createData);
message.success('创建订单成功');
}
emit('success');
close();
} catch (error) {
console.error('提交订单失败:', error);
message.error('提交订单失败');
} finally {
loading.value = false;
}
}
// 暴露方法
defineExpose({
open,
close,
});
</script>
<template>
<Modal :title="isEdit ? '编辑订单' : '添加订单'" :confirm-loading="loading">
<Form
ref="formRef"
:model="formData"
:rules="rules as any"
layout="vertical"
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="店铺" name="shopId">
<Select
v-model:value="formData.shopId"
placeholder="请搜索并选择店铺"
show-search
:filter-option="false"
:loading="shopLoading"
:options="shopOptions"
@search="handleShopSearch"
@focus="
() => {
if (!shopLoaded) fetchShopOptions(1, false);
}
"
@popup-scroll="handleShopPopupScroll"
>
<template #notFoundContent>
<div v-if="shopLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
{{ shopSearchKeyword ? '未找到店铺' : '暂无店铺' }}
</div>
</template>
</Select>
</Form.Item>
<Form.Item label="订单状态" name="status">
<Select
v-model:value="formData.status"
placeholder="请选择订单状态"
:options="orderStatusOptions"
/>
</Form.Item>
</div>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="平台订单号" name="platformOrderNo">
<Input
v-model:value="formData.platformOrderNo"
placeholder="请输入平台订单号(可选)"
/>
</Form.Item>
<Form.Item label="下单时间" name="orderTime">
<DatePicker
v-model:value="formData.orderTime"
placeholder="请选择下单时间"
style="width: 100%"
show-time
format="YYYY-MM-DD HH:mm:ss"
value-format="YYYY-MM-DD HH:mm:ss"
/>
</Form.Item>
</div>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="商品" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请搜索并选择商品"
show-search
:filter-option="false"
:loading="productLoading"
:options="productOptions"
@search="handleProductSearch"
@focus="() => { if (!productLoaded) fetchProducts(1, false); }"
@popup-scroll="handleProductPopupScroll"
@change="(value) => handleProductChange(value as number)"
>
<template #notFoundContent>
<div v-if="productLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
{{ productSearchKeyword ? '未找到商品' : '请输入商品名称搜索' }}
</div>
</template>
</Select>
</Form.Item>
<Form.Item label="商品 SKU" name="productSkuId">
<Select
v-model:value="formData.productSkuId"
placeholder="请先选择商品,然后搜索规格"
show-search
:filter-option="false"
:loading="productSkuLoading"
:disabled="!formData.productId"
:options="productSkuOptions"
@search="handleProductSkuSearch"
@focus="() => { if (!skuLoaded && formData.productId) fetchProductSkus(1, false); }"
@popup-scroll="handleSpecPopupScroll"
@change="(value) => handleProductSkuChange(value as number)"
>
<template #notFoundContent>
<div v-if="productSkuLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400">
{{
formData.productId
? productSkuSearchKeyword
? '未找到规格'
: '请输入SKU 名称搜索'
: '请先选择商品'
}}
</div>
</template>
</Select>
</Form.Item>
</div>
<div class="grid grid-cols-3 gap-4">
<Form.Item label="数量" name="quantity">
<InputNumber
v-model:value="formData.quantity"
placeholder="请输入数量"
style="width: 100%"
:min="1"
/>
</Form.Item>
<Form.Item label="销售单价" name="unitPrice">
<InputNumber
v-model:value="formData.unitPrice"
placeholder="请输入销售单价"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="商品成本" name="productCost">
<InputNumber
v-model:value="formData.productCost"
placeholder="请输入商品成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</div>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="运费成本" name="shippingCost">
<InputNumber
v-model:value="formData.shippingCost"
placeholder="请输入运费成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="其他成本" name="otherCost">
<InputNumber
v-model:value="formData.otherCost"
placeholder="请输入其他成本"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</div>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注"
:rows="3"
/>
</Form.Item>
<Form.Item label="实付金额" name="payAmount">
<InputNumber
v-model:value="formData.payAmount"
placeholder="请输入买家实付金额"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="服务费" name="serviceFee">
<InputNumber
v-model:value="formData.serviceFee"
placeholder="平台服务费(可选)"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
<Form.Item label="商家实收" name="receivedAmount">
<InputNumber
v-model:value="formData.receivedAmount"
placeholder="不填则按 实付-服务费+平台优惠"
style="width: 100%"
:min="0"
:precision="2"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,839 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { OrderDTO, OrderVO } from '#/api/ecommerce/order';
import { ORDER_STATUS_OPTIONS } from '#/api/ecommerce/order/types/types.enum';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import dayjs from 'dayjs';
import {
Button,
Image,
message,
Popconfirm,
Space,
Tag,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
batchDeleteOrdersApi,
deleteOrderApi,
getOrderPageApi,
} from '#/api/ecommerce/order';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getPlatformListApi } from '#/api/ecommerce/platform';
import { getShopPageApi } from '#/api/ecommerce/shop';
import PlatformTag from '#/components/platform/PlatformTag.vue';
import {
getFirstOrderItem,
getOrderPayAmount,
getOrderProduct,
getOrderReceivedAmount,
} from '#/utils/order-display';
import OrderDetailDrawer from './components/OrderDetailDrawer.vue';
import OrderFormModal from './components/OrderFormModal.vue';
defineOptions({ name: 'OrderManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const router = useRouter();
const SOURCE_LABEL: Record<string, string> = {
import: '导入',
sync: '同步',
manual: '手动',
};
const loading = ref(false);
const batchDeleteLoading = ref(false);
/** vxe 勾选不触发 Vue 依赖,须用事件同步,勿用 computed 读 getCheckboxRecords */
const hasSelected = ref(false);
const orderFormModalRef = ref<InstanceType<typeof OrderFormModal>>();
const detailDrawerRef = ref<InstanceType<typeof OrderDetailDrawer>>();
const shopOptions = ref<{ label: string; value: number }[]>([]);
const shopPage = ref(1);
const shopPageSize = 20;
const shopTotal = ref(0);
const shopLoading = ref(false);
const shopSearchKeyword = ref('');
const shopLoaded = ref(false);
let shopSearchTimer: null | ReturnType<typeof setTimeout> = null;
const orderStatusOptions = ORDER_STATUS_OPTIONS;
const productOptions = ref<{ label: string; value: number }[]>([]);
const productPage = ref(1);
const productPageSize = 20;
const productTotal = ref(0);
const productLoading = ref(false);
const productSearchKeyword = ref('');
const productLoaded = ref(false);
let productSearchTimer: null | ReturnType<typeof setTimeout> = null;
/** 与后端 OrderPageQuerySupport 对齐 */
const DEFAULT_LIST_DAYS = 30;
const MAX_LIST_DAYS = 366;
function buildDefaultOrderTimeRange() {
const end = dayjs().endOf('day');
const start = dayjs()
.subtract(DEFAULT_LIST_DAYS - 1, 'day')
.startOf('day');
return {
start: start.format('YYYY-MM-DD HH:mm:ss'),
end: end.format('YYYY-MM-DD HH:mm:ss'),
range: [start, end] as [dayjs.Dayjs, dayjs.Dayjs],
};
}
const defaultOrderTime = buildDefaultOrderTimeRange();
const searchForm = ref({
platformOrderNo: '',
shopId: undefined as number | undefined,
platformCode: undefined as string | undefined,
status: undefined as string | undefined,
startOrderTime: defaultOrderTime.start as string | undefined,
endOrderTime: defaultOrderTime.end as string | undefined,
productId: undefined as number | undefined,
});
const platformOptions = ref<{ label: string; value: string }[]>([]);
const platformLoaded = ref(false);
const currentSort = ref<null | { field: string; order: 'asc' | 'desc' }>(null);
function money(v?: null | number) {
if (v == null || Number.isNaN(Number(v))) return '-';
return `¥${Number(v).toFixed(2)}`;
}
function sourceText(source?: string) {
if (!source) return '-';
return SOURCE_LABEL[source] ?? source;
}
function regionText(row: OrderVO.Info) {
return [row.province, row.city, row.town].filter(Boolean).join(' / ') || '-';
}
function goodsTitle(row: OrderVO.Info) {
return (
getOrderProduct(row)?.name ||
getFirstOrderItem(row)?.linkProductName ||
row.firstLinkProductName ||
'-'
);
}
function goodsSpec(row: OrderVO.Info) {
const item = getFirstOrderItem(row);
return item?.productSku?.name || item?.linkSkuName || '';
}
function goodsImg(row: OrderVO.Info) {
return getFirstOrderItem(row)?.goodsImg;
}
function ensureOrderTimeFilters(): boolean {
if (!searchForm.value.startOrderTime || !searchForm.value.endOrderTime) {
const d = buildDefaultOrderTimeRange();
searchForm.value.startOrderTime = d.start;
searchForm.value.endOrderTime = d.end;
}
const start = dayjs(searchForm.value.startOrderTime);
const end = dayjs(searchForm.value.endOrderTime);
if (!start.isValid() || !end.isValid()) {
message.warning('请选择有效的下单时间范围');
return false;
}
if (end.isBefore(start)) {
message.warning('下单结束时间不能早于开始时间');
return false;
}
if (end.diff(start, 'day') + 1 > MAX_LIST_DAYS) {
message.warning(`下单时间跨度不能超过 ${MAX_LIST_DAYS} 天,请缩小范围`);
return false;
}
return true;
}
async function fetchShops(page = 1, append = false) {
if (shopLoading.value) return;
shopLoading.value = true;
try {
const params: PageQueryDTO<ShopDTO.Filters> = {
page,
pageSize: shopPageSize,
filters: shopSearchKeyword.value ? { name: shopSearchKeyword.value } : {},
};
const data = await getShopPageApi(params);
const mapped = data.records.map((shop: ShopVO.Info) => ({
label: shop.name,
value: shop.id,
}));
shopOptions.value = append ? [...shopOptions.value, ...mapped] : mapped;
shopTotal.value = data.total;
shopPage.value = page;
shopLoaded.value = true;
} catch (error) {
console.error('获取店铺列表失败:', error);
} finally {
shopLoading.value = false;
}
}
function handleShopSearch(value: string) {
if (shopSearchTimer) clearTimeout(shopSearchTimer);
shopSearchTimer = setTimeout(() => {
shopSearchKeyword.value = value;
shopPage.value = 1;
fetchShops(1, false);
}, 300);
}
function handleShopPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = shopPage.value * shopPageSize < shopTotal.value;
if (hasMore && !shopLoading.value) {
fetchShops(shopPage.value + 1, true);
}
}
}
async function fetchProducts(page = 1, append = false) {
if (productLoading.value) return;
productLoading.value = true;
try {
const params: PageQueryDTO<ProductDTO.Filters> = {
page,
pageSize: productPageSize,
filters: productSearchKeyword.value
? { name: productSearchKeyword.value }
: {},
};
const data = await getProductPageApi(params);
const mapped = data.records.map((product: ProductVO.Info) => ({
label: product.name,
value: product.id,
}));
productOptions.value = append
? [...productOptions.value, ...mapped]
: mapped;
productTotal.value = data.total;
productPage.value = page;
productLoaded.value = true;
} catch (error) {
console.error('获取商品列表失败:', error);
} finally {
productLoading.value = false;
}
}
function handleProductSearch(value: string) {
if (productSearchTimer) clearTimeout(productSearchTimer);
productSearchTimer = setTimeout(() => {
productSearchKeyword.value = value;
productPage.value = 1;
fetchProducts(1, false);
}, 300);
}
function handleProductPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = productPage.value * productPageSize < productTotal.value;
if (hasMore && !productLoading.value) {
fetchProducts(productPage.value + 1, true);
}
}
}
async function fetchPlatformOptions() {
try {
const data = await getPlatformListApi();
platformOptions.value = (data ?? []).map((p) => ({
label: p.label,
value: p.code,
}));
platformLoaded.value = true;
} catch (error) {
console.error('获取平台字典失败:', error);
}
}
const gridOptions: VxeGridProps<OrderVO.Info> = {
checkboxConfig: {
highlight: true,
reserve: false,
},
columns: [
{ type: 'seq' as const, width: 56, title: '序号' },
{
type: 'checkbox' as const,
width: 48,
fixed: 'left' as const,
},
{
field: 'platformOrderNo',
title: '平台订单号',
minWidth: 180,
showOverflow: 'tooltip' as const,
sortable: true,
},
{
title: '平台',
width: 100,
slots: { default: 'platform' },
},
{
field: 'shopName',
title: '店铺',
minWidth: 120,
showOverflow: 'tooltip' as const,
sortable: true,
slots: { default: 'shopName' },
},
{
title: '商品',
minWidth: 240,
showOverflow: false,
slots: { default: 'goods' },
},
{
field: 'payAmount',
title: '实付',
width: 100,
sortable: true,
slots: { default: 'payAmount' },
},
{
field: 'receivedAmount',
title: '商家实收',
width: 110,
sortable: true,
slots: { default: 'receivedAmount' },
},
{
title: '订单状态',
width: 110,
slots: { default: 'orderStatus' },
},
{
title: '来源',
width: 80,
slots: { default: 'source' },
},
{
field: 'orderTime',
title: '下单时间',
minWidth: 160,
sortable: true,
},
{
title: '收件地区',
minWidth: 140,
showOverflow: 'tooltip' as const,
slots: { default: 'region' },
},
{
title: '操作',
width: 180,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true, height: 72 },
showOverflow: true,
size: 'small',
sortConfig: {
remote: true,
trigger: 'cell',
multiple: false,
orders: ['desc', 'asc'],
},
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page, form }) => {
try {
if (!ensureOrderTimeFilters()) {
return { items: [], total: 0 };
}
loading.value = true;
const searchParams = form || {};
const filters = {
platformOrderNo:
searchParams.platformOrderNo ||
searchForm.value.platformOrderNo ||
undefined,
shopId: searchParams.shopId ?? searchForm.value.shopId,
platformCode:
searchParams.platformCode ?? searchForm.value.platformCode,
status: searchParams.status ?? searchForm.value.status,
startOrderTime: searchForm.value.startOrderTime,
endOrderTime: searchForm.value.endOrderTime,
productId: searchParams.productId ?? searchForm.value.productId,
};
const params: PageQueryDTO<OrderDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters,
};
if (currentSort.value) {
params.sorts = [
{
field: currentSort.value.field,
order: currentSort.value.order,
},
];
}
const data = await getOrderPageApi(params);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取订单列表失败:', error);
message.error('获取订单列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '平台订单号(前缀匹配,回车搜索)',
onChange: (e: any) => {
searchForm.value.platformOrderNo = e.target.value;
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'platformOrderNo',
label: '平台订单号',
},
{
component: 'Select',
componentProps: {
placeholder: '全部平台',
options: platformOptions,
allowClear: true,
showSearch: true,
optionFilterProp: 'label',
onFocus: () => {
if (!platformLoaded.value) {
fetchPlatformOptions();
}
},
onChange: (val: string | undefined) => {
searchForm.value.platformCode = val;
gridReloadRef.value?.();
},
},
fieldName: 'platformCode',
label: '平台',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择店铺(支持搜索)',
options: shopOptions,
allowClear: true,
showSearch: true,
filterOption: false,
onSearch: handleShopSearch,
onFocus: () => {
if (!shopLoaded.value) {
fetchShops(1, false);
}
},
onPopupScroll: handleShopPopupScroll,
onChange: (val: any) => {
searchForm.value.shopId = val;
gridReloadRef.value?.();
},
loading: shopLoading,
dropdownMenuColumnStyle: { maxHeight: '300px', overflow: 'auto' },
},
fieldName: 'shopId',
label: '店铺',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择商品(支持搜索)',
options: productOptions,
allowClear: true,
showSearch: true,
filterOption: false,
onSearch: handleProductSearch,
onFocus: () => {
if (!productLoaded.value) {
fetchProducts(1, false);
}
},
onPopupScroll: handleProductPopupScroll,
onChange: (val: any) => {
searchForm.value.productId = val ?? undefined;
gridReloadRef.value?.();
},
loading: productLoading,
dropdownMenuColumnStyle: { maxHeight: '300px', overflow: 'auto' },
},
fieldName: 'productId',
label: '商品',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择状态',
options: orderStatusOptions,
allowClear: true,
onChange: (val: any) => {
searchForm.value.status = val;
gridReloadRef.value?.();
},
},
fieldName: 'status',
label: '订单状态',
},
{
component: 'RangePicker',
defaultValue: defaultOrderTime.range,
componentProps: {
placeholder: ['下单开始时间', '下单结束时间'],
allowClear: false,
showTime: { format: 'HH:mm:ss' },
format: 'YYYY-MM-DD HH:mm:ss',
style: { width: '100%' },
onChange: (val: any) => {
if (!val || !val[0] || !val[1]) {
const d = buildDefaultOrderTimeRange();
searchForm.value.startOrderTime = d.start;
searchForm.value.endOrderTime = d.end;
} else {
searchForm.value.startOrderTime = (val[0] as dayjs.Dayjs).format(
'YYYY-MM-DD HH:mm:ss',
);
searchForm.value.endOrderTime = (val[1] as dayjs.Dayjs).format(
'YYYY-MM-DD HH:mm:ss',
);
}
gridReloadRef.value?.();
},
},
fieldName: 'orderTimeRange',
label: '下单时间',
rules: 'required',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 2,
defaultValues: {
orderTimeRange: defaultOrderTime.range,
},
}));
function refreshTable() {
hasSelected.value = false;
gridApi.reload();
}
function handleSortChange({
field,
order,
}: {
field?: string;
order?: 'asc' | 'desc' | null;
}) {
currentSort.value = field ? { field, order: order || 'desc' } : null;
gridReloadRef.value?.();
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '订单管理',
gridEvents: {
checkboxChange() {
const vxeTable = (gridApi as any).grid;
const rows = vxeTable?.getCheckboxRecords?.() ?? [];
hasSelected.value = rows.length > 0;
},
checkboxAll() {
const vxeTable = (gridApi as any).grid;
const rows = vxeTable?.getCheckboxRecords?.() ?? [];
hasSelected.value = rows.length > 0;
},
},
});
gridReloadRef.value = () => gridApi.reload();
function goToShopDetail(shopId: number) {
router.push(`/ecom/shop/overview/${shopId}`);
}
function openDetail(row: OrderVO.Info) {
detailDrawerRef.value?.open(row.id);
}
function handleAdd() {
orderFormModalRef.value?.open(false);
}
function handleEdit(record: OrderVO.Info) {
orderFormModalRef.value?.open(true, record);
}
async function handleDelete(record: OrderVO.Info) {
try {
await deleteOrderApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除订单失败:', error);
message.error('删除订单失败');
}
}
async function handleBatchDelete() {
const vxeTable = (gridApi as any).grid;
const selectedRows: OrderVO.Info[] = vxeTable?.getCheckboxRecords?.() ?? [];
if (!selectedRows.length) {
message.warning('请选择要删除的订单');
return;
}
const orderIds = selectedRows.map((r) => r.id).filter((id) => id != null);
if (!orderIds.length) {
message.warning('所选行缺少订单ID');
return;
}
batchDeleteLoading.value = true;
try {
await batchDeleteOrdersApi({ orderIds });
message.success(`已删除 ${orderIds.length} 条订单`);
vxeTable?.clearCheckboxRow?.();
hasSelected.value = false;
await gridApi.reload();
} catch (error: any) {
console.error('批量删除订单失败:', error);
const msg =
error?.response?.data?.message || error?.message || '批量删除失败';
message.error(msg);
} finally {
batchDeleteLoading.value = false;
}
}
function handleModalSuccess() {
refreshTable();
}
onMounted(async () => {
ensureOrderTimeFilters();
await fetchPlatformOptions();
});
</script>
<template>
<Page auto-content-height>
<Grid
class="order-grid"
:loading="loading"
@sort-change="handleSortChange"
>
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加订单
</Button>
<Popconfirm
title="确定删除选中的订单吗?删除后不可恢复。"
ok-text="确定删除"
cancel-text="取消"
:ok-button-props="{ danger: true, loading: batchDeleteLoading }"
:disabled="!hasSelected"
@confirm="handleBatchDelete"
>
<Button
danger
:disabled="!hasSelected"
:loading="batchDeleteLoading"
>
批量删除
</Button>
</Popconfirm>
</Space>
</template>
<template #platform="{ row }: { row: OrderVO.Info }">
<PlatformTag :code="row.platformCode" :label="row.platformLabel" />
</template>
<template #shopName="{ row }: { row: OrderVO.Info }">
<a
style="color: #1890ff; cursor: pointer"
@click="goToShopDetail(row.shopId)"
>
{{ row.shopName || `店铺#${row.shopId}` }}
</a>
</template>
<template #goods="{ row }: { row: OrderVO.Info }">
<div class="goods-cell">
<Image
v-if="goodsImg(row)"
:src="goodsImg(row)"
:width="40"
:height="40"
class="goods-img"
/>
<div class="goods-meta">
<div class="goods-name" :title="goodsTitle(row)">
{{ goodsTitle(row) }}
</div>
<div class="goods-spec">
{{ goodsSpec(row) }}
<span v-if="(row.itemCount ?? 0) > 1">
等 {{ row.itemCount }} 件
</span>
</div>
</div>
</div>
</template>
<template #payAmount="{ row }: { row: OrderVO.Info }">
{{ money(getOrderPayAmount(row)) }}
</template>
<template #receivedAmount="{ row }: { row: OrderVO.Info }">
{{ money(getOrderReceivedAmount(row)) }}
</template>
<template #orderStatus="{ row }: { row: OrderVO.Info }">
<Tag :color="row.statusColor || 'blue'">
{{ row.statusLabel || '未知状态' }}
</Tag>
</template>
<template #source="{ row }: { row: OrderVO.Info }">
{{ sourceText(row.source) }}
</template>
<template #region="{ row }: { row: OrderVO.Info }">
{{ regionText(row) }}
</template>
<template #action="{ row }: { row: OrderVO.Info }">
<Space>
<Button type="link" size="small" @click="openDetail(row)">
详情
</Button>
<Button type="link" size="small" @click="handleEdit(row)">
编辑
</Button>
<Popconfirm
title="确定要删除这个订单吗?"
@confirm="handleDelete(row)"
>
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<OrderFormModal ref="orderFormModalRef" @success="handleModalSuccess" />
<OrderDetailDrawer ref="detailDrawerRef" />
</Page>
</template>
<style scoped>
.goods-cell {
display: flex;
gap: 8px;
align-items: center;
min-height: 48px;
}
.goods-img {
flex-shrink: 0;
overflow: hidden;
border-radius: 4px;
}
.goods-meta {
min-width: 0;
}
.goods-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.goods-spec {
color: #8c8c8c;
font-size: 12px;
}
:deep(.order-grid .vxe-body--column) {
vertical-align: middle;
}
</style>
@@ -0,0 +1,182 @@
<script lang="ts" setup>
import type { CategoryDTO, CategoryVO } from '#/api/ecommerce/category';
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Form, Input, InputNumber, Select, message } from 'ant-design-vue';
import {
createCategoryApi,
getCategoryListApi,
updateCategoryApi,
} from '#/api/ecommerce/category';
const emit = defineEmits<{
cancel: [];
success: [];
}>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
onCancel() {
close();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<null | CategoryVO.Info>(null);
// 类目选项列表(用于父级选择)
const categoryOptions = ref<CategoryVO.Info[]>([]);
// 表单数据
const formData = ref<Partial<CategoryDTO.Create>>({
parentId: undefined,
name: '',
sortOrder: 0,
});
// 表单验证规则
const rules = {
name: [{ required: true, message: '请输入类目名称', trigger: 'blur' }],
};
// 表单引用
const formRef = ref();
// 加载类目列表(扁平,用于父级选择)
async function loadCategoryOptions() {
try {
const list = await getCategoryListApi();
categoryOptions.value = list ?? [];
} catch (error) {
console.error('加载类目列表失败:', error);
}
}
// 打开模态框
async function open(edit: boolean, record?: CategoryVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
await loadCategoryOptions();
modalApi.open();
if (edit && record) {
formData.value = {
parentId: record.parentId ?? undefined,
name: record.name,
sortOrder: record.sortOrder ?? 0,
};
} else {
formData.value = {
parentId: undefined,
name: '',
sortOrder: 0,
};
}
}
// 关闭模态框
function close() {
modalApi.close();
formRef.value?.resetFields();
emit('cancel');
}
// 提交表单
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentRecord.value) {
const updateData: CategoryDTO.Update = {
parentId: formData.value.parentId ?? null,
name: formData.value.name!,
sortOrder: formData.value.sortOrder,
};
await updateCategoryApi(currentRecord.value.id, updateData);
message.success('更新类目成功');
} else {
const createData: CategoryDTO.Create = {
parentId: formData.value.parentId,
name: formData.value.name!,
sortOrder: formData.value.sortOrder,
};
await createCategoryApi(createData);
message.success('创建类目成功');
}
emit('success');
close();
} catch (error) {
console.error('提交失败:', error);
} finally {
loading.value = false;
}
}
// 监听模态框关闭状态
watch(
() => modalApi.useStore?.()?.value?.isOpen,
(newVal) => {
if (!newVal) {
formRef.value?.resetFields();
}
},
);
// 暴露方法
defineExpose({
open,
close,
});
</script>
<template>
<Modal
:title="isEdit ? '编辑类目' : '添加类目'"
:confirm-loading="loading"
>
<Form
ref="formRef"
:model="formData"
:rules="rules as any"
layout="vertical"
>
<Form.Item label="父级类目" name="parentId">
<Select
v-model:value="formData.parentId"
placeholder="请选择父级类目(留空则为顶级)"
:options="[{ label: '(顶级类目)', value: undefined }, ...categoryOptions.map(c => ({ label: c.name, value: c.id }))]"
allow-clear
/>
</Form.Item>
<Form.Item label="类目名称" name="name">
<Input
v-model:value="formData.name"
placeholder="请输入类目名称"
/>
</Form.Item>
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,221 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { CategoryVO } from '#/api/ecommerce/category';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deleteCategoryApi,
getCategoryTreeApi,
} from '#/api/ecommerce/category';
import CategoryFormModal from './components/CategoryFormModal.vue';
defineOptions({ name: 'CategoryConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const categoryFormModalRef = ref();
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
field: 'name',
title: '类目名称',
minWidth: 150,
slots: { default: 'name' },
},
{
field: 'parentName',
title: '上级类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
field: 'sortOrder',
title: '排序',
minWidth: 80,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 160,
},
{
title: '操作',
width: 160,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: false,
},
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const tree = await getCategoryTreeApi();
// 将树扁平化用于表格展示
const flatData = flattenTree(tree ?? []);
return {
items: flatData,
total: flatData.length,
};
} catch (error) {
console.error('获取类目列表失败:', error);
message.error('获取类目列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
// 将树形结构扁平化
function flattenTree(tree: CategoryVO.Info[], level = 0): any[] {
const result: any[] = [];
for (const item of tree) {
result.push({ ...item, _level: level });
if (item.children && item.children.length > 0) {
result.push(...flattenTree(item.children, level + 1));
}
}
return result;
}
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入类目名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'name',
label: '类目名称',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '商品类目配置',
});
gridReloadRef.value = () => gridApi.reload();
function refreshTable() {
gridApi?.reload();
}
function handleAdd() {
categoryFormModalRef.value?.open(false);
}
function handleEdit(record: CategoryVO.Info) {
categoryFormModalRef.value?.open(true, record);
}
async function handleDelete(record: CategoryVO.Info) {
try {
await deleteCategoryApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除类目失败:', error);
message.error((error as any)?.response?.data?.message || '删除类目失败');
}
}
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
<Page title="商品类目配置" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理商品类目,支持多级分类
</div>
</template>
<Grid :loading="loading">
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加类目
</Button>
</Space>
</template>
<!-- 类目名称列 -->
<template #name="{ row }: { row: CategoryVO.Info & { _level: number } }">
<span :style="{ paddingLeft: `${(row._level ?? 0) * 20}px` }">
<span v-if="(row._level ?? 0) > 0" class="mr-1 text-gray-400">└</span>
{{ row.name }}
</span>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这个类目吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<CategoryFormModal
ref="categoryFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
@@ -0,0 +1,471 @@
<script lang="ts" setup>
import type { ProductSkuVO } from '#/api/ecommerce/product-sku/types';
import { onUnmounted, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { DatePicker, message } from 'ant-design-vue';
import {
batchSyncCostsToOrdersApi,
countOrdersForCostSyncApi,
getProductSkusByIdsApi,
} from '#/api/ecommerce/product-sku/apis';
defineOptions({ name: 'ProductCostSyncToOrdersModal' });
type ProductCostSyncModalEntry = 'after-save' | 'manual';
interface ProductCostSyncOpenOptions {
/** 保存后提示 / 用户主动同步 */
entry?: ProductCostSyncModalEntry;
/** 打开时预填日期范围 `YYYY-MM-DD`;不传则清空由用户选择 */
initialDateRange?: [string, string];
}
/** 将选中的日期范围转为接口所需 LocalDateTime 字符串(起日 00:00:00,止日 23:59:59) */
function dateRangeToApiTimes(range: [string, string]): {
endTime: string;
startTime: string;
} {
const [startDate, endDate] = range;
return {
startTime: `${startDate} 00:00:00`,
endTime: `${endDate} 23:59:59`,
};
}
const [SyncModal, syncModalApi] = useVbenModal({
title: '成本变更同步确认',
class: 'w-[720px] max-w-[calc(100vw-2rem)]',
draggable: true,
contentClass: 'px-5 py-4 min-h-[480px]',
cancelText: '暂不同步',
confirmText: '立即同步',
onConfirm: handleSyncConfirm,
onCancel: () => {
syncModalApi.close();
},
});
const syncFormData = ref<[string, string] | undefined>(undefined);
const pendingCostChangedSkus = ref<ProductSkuVO.Info[]>([]);
const selectedSyncSkuIds = ref<number[]>([]);
const costSyncModalEntry = ref<ProductCostSyncModalEntry>('after-save');
const costSyncOrderCount = ref<null | number>(null);
const costSyncOrderCountLoading = ref(false);
let costSyncCountTimer: null | ReturnType<typeof setTimeout> = null;
function scheduleFetchCostSyncOrderCount() {
if (costSyncCountTimer) {
clearTimeout(costSyncCountTimer);
}
costSyncCountTimer = setTimeout(() => {
costSyncCountTimer = null;
void fetchCostSyncOrderCount();
}, 300);
}
async function fetchCostSyncOrderCount() {
const range = syncFormData.value;
if (!range?.[0] || !range[1]) {
costSyncOrderCount.value = null;
return;
}
if (selectedSyncSkuIds.value.length === 0) {
costSyncOrderCount.value = null;
return;
}
costSyncOrderCountLoading.value = true;
try {
const { startTime, endTime } = dateRangeToApiTimes(range);
costSyncOrderCount.value = await countOrdersForCostSyncApi({
skuIds: [...selectedSyncSkuIds.value],
startTime,
endTime,
});
} catch {
costSyncOrderCount.value = null;
} finally {
costSyncOrderCountLoading.value = false;
}
}
watch(
() => [...selectedSyncSkuIds.value],
() => {
scheduleFetchCostSyncOrderCount();
},
);
watch(
syncFormData,
() => {
scheduleFetchCostSyncOrderCount();
},
{ deep: true },
);
/**
* 打开成本同步弹窗(先拉取SKU详情再展示)
*/
async function open(skuIds: number[], options?: ProductCostSyncOpenOptions) {
const entry = options?.entry ?? 'after-save';
costSyncModalEntry.value = entry;
syncModalApi.setState?.({
title: entry === 'manual' ? '同步成本到订单' : '成本变更同步确认',
});
try {
const skus = await getProductSkusByIdsApi(skuIds);
pendingCostChangedSkus.value = skus ?? [];
selectedSyncSkuIds.value = [...skuIds];
syncFormData.value = options?.initialDateRange
? [options.initialDateRange[0], options.initialDateRange[1]]
: undefined;
costSyncOrderCount.value = null;
syncModalApi.open();
if (options?.initialDateRange) {
scheduleFetchCostSyncOrderCount();
}
} catch (error) {
console.error('获取SKU详情失败:', error);
message.error('获取SKU详情失败,无法进行成本同步');
}
}
function toggleSku(skuId: number) {
const idx = selectedSyncSkuIds.value.indexOf(skuId);
if (idx === -1) {
selectedSyncSkuIds.value.push(skuId);
} else {
selectedSyncSkuIds.value.splice(idx, 1);
}
}
async function handleSyncConfirm() {
if (selectedSyncSkuIds.value.length === 0) {
message.warning('请至少选择一个SKU');
return;
}
const range = syncFormData.value;
if (!range?.[0] || !range[1]) {
message.warning('请选择同步日期范围');
return;
}
try {
syncModalApi.setState?.({ confirmLoading: true });
const { startTime, endTime } = dateRangeToApiTimes(range);
const totalUpdated = await batchSyncCostsToOrdersApi({
skuIds: selectedSyncSkuIds.value,
startTime,
endTime,
});
message.success(`成本同步完成,共更新 ${totalUpdated ?? 0} 条订单`);
syncModalApi.close?.();
} catch (error) {
console.error('成本同步失败:', error);
message.error('成本同步失败');
} finally {
syncModalApi.setState?.({ confirmLoading: false });
}
}
onUnmounted(() => {
if (costSyncCountTimer) {
clearTimeout(costSyncCountTimer);
costSyncCountTimer = null;
}
});
defineExpose({ open });
</script>
<template>
<SyncModal>
<div class="product-cost-sync py-4">
<div class="sync-alert">
<svg
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
>
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<template v-if="costSyncModalEntry === 'after-save'">
检测到
<strong>{{ pendingCostChangedSkus.length }}</strong>
个SKU的成本已更新,请勾选需要同步的SKU:
</template>
<template v-else>
将所选SKU<strong>当前</strong>的商品成本、运费、其他成本写入订单(会覆盖该时间范围内订单上的对应成本字段)。请勾选需要同步的SKU,共
<strong>{{ pendingCostChangedSkus.length }}</strong> 个:
</template>
</div>
<div
class="sku-list mb-4 max-h-72 min-h-[200px] overflow-y-auto rounded-lg"
>
<div
v-for="sku in pendingCostChangedSkus"
:key="sku.id"
class="sku-item-card"
:class="{ active: selectedSyncSkuIds.includes(sku.id) }"
@click="toggleSku(sku.id)"
>
<div class="checkbox-wrapper">
<div class="custom-checkbox">
<span
v-if="selectedSyncSkuIds.includes(sku.id)"
class="check-icon"
>
✓
</span>
</div>
</div>
<div class="sku-info">
<div class="sku-title">{{ sku.name }}</div>
<div class="sku-code">{{ sku.skuCode || '无编码' }}</div>
</div>
<div class="cost-snapshot">
<div class="cost-tag changed">
<span>商品成本</span>
<span>¥{{ Number(sku.productCost || 0).toFixed(2) }}</span>
</div>
<div class="cost-tag">
<span>运费</span>
<span>¥{{ Number(sku.shippingCost || 0).toFixed(2) }}</span>
</div>
<div class="cost-tag">
<span>其他</span>
<span>¥{{ Number(sku.otherCost || 0).toFixed(2) }}</span>
</div>
</div>
</div>
</div>
<div class="time-range-section">
<label class="section-label">同步日期范围</label>
<DatePicker.RangePicker
v-model:value="syncFormData"
class="w-full"
format="YYYY-MM-DD"
value-format="YYYY-MM-DD"
/>
<div
class="sync-order-count mt-2 text-sm text-gray-600 dark:text-[hsl(240deg_5%_64.9%)]"
>
<template v-if="costSyncOrderCountLoading">正在统计订单数…</template>
<template
v-else-if="
costSyncOrderCount !== null &&
syncFormData &&
syncFormData[0] &&
syncFormData[1] &&
selectedSyncSkuIds.length > 0
"
>
当前日期范围内共
<strong class="text-gray-900 dark:text-[hsl(0deg_0%_95%)]">{{
costSyncOrderCount
}}</strong>
条订单将更新成本
</template>
</div>
</div>
</div>
</SyncModal>
</template>
<style scoped lang="scss">
.sync-alert {
display: flex;
align-items: center;
gap: 10px;
background: #fff8f1;
padding: 12px 16px;
border-radius: 8px;
border: 1px solid #ffe8d5;
margin-bottom: 24px;
color: #af6a2b;
font-size: 14px;
}
.sku-list {
display: flex;
flex-direction: column;
gap: 10px;
}
.sku-item-card {
display: flex;
align-items: center;
padding: 16px;
border: 2px solid #eef0f2;
border-radius: 10px;
transition: all 0.2s;
cursor: pointer;
background: #fff;
}
.sku-item-card:hover {
border-color: #d1d9ff;
background: #fafbff;
}
.sku-item-card.active {
border-color: #5b6df5;
background: #f0f2ff;
}
.checkbox-wrapper {
margin-right: 16px;
flex-shrink: 0;
}
.custom-checkbox {
width: 20px;
height: 20px;
border: 2px solid #cbd5e1;
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
background: #fff;
transition: all 0.2s;
}
.active .custom-checkbox {
background: #5b6df5;
border-color: #5b6df5;
}
.check-icon {
color: #fff;
font-size: 14px;
font-weight: bold;
line-height: 1;
}
.sku-info {
flex: 1;
min-width: 0;
}
.sku-title {
font-size: 14px;
font-weight: 500;
color: #2d3436;
margin-bottom: 4px;
display: -webkit-box;
-webkit-line-clamp: 1;
line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
.sku-code {
font-size: 12px;
color: #636e72;
font-family: monospace;
}
.cost-snapshot {
display: flex;
flex-direction: column;
gap: 4px;
padding-left: 20px;
border-left: 1px solid #e2e8f0;
margin-left: 15px;
min-width: 100px;
}
.cost-tag {
font-size: 12px;
color: #636e72;
display: flex;
justify-content: space-between;
gap: 10px;
}
.cost-tag span:last-child {
font-weight: 600;
color: #2d3436;
}
.cost-tag.changed span:last-child {
color: #f2994a;
}
.time-range-section {
margin-top: 24px;
}
.section-label {
font-size: 14px;
font-weight: 600;
color: #2d3436;
margin-bottom: 12px;
display: block;
}
</style>
<style lang="scss">
$card-text: hsl(var(--foreground));
$muted-text: hsl(var(--muted-foreground));
$accent-bg: hsl(var(--accent));
$border-base: hsl(var(--border));
$primary: hsl(var(--primary));
html.dark .product-cost-sync {
.section-label,
.sku-code,
.cost-tag {
color: $muted-text;
}
.sync-alert {
background: hsl(var(--warning) / 12%);
border-color: hsl(var(--warning) / 35%);
color: hsl(var(--warning));
}
.sku-item-card {
border-color: $border-base;
background: hsl(var(--muted));
&:hover {
border-color: hsl(var(--primary) / 50%);
background: $accent-bg;
}
&.active {
border-color: $primary;
background: hsl(var(--primary) / 10%);
}
}
.custom-checkbox {
background: hsl(var(--muted));
border-color: $border-base;
}
.sku-title {
color: $card-text;
}
.cost-snapshot {
border-left-color: $border-base;
}
.cost-tag span:last-child {
color: $card-text;
}
}
</style>
@@ -0,0 +1,217 @@
<script lang="ts" setup>
import type { ProductVO } from '#/api/ecommerce/product/types';
import { computed, h, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Image, Space, Table } from 'ant-design-vue';
defineOptions({ name: 'ProductDetailModal' });
const ChartIcon = createIconifyIcon('lucide:line-chart');
const EditIcon = createIconifyIcon('lucide:square-pen');
const ImageIcon = createIconifyIcon('lucide:image');
const product = ref<ProductVO.Info | null>(null);
const router = useRouter();
const emit = defineEmits<{
edit: [product: ProductVO.Info];
}>();
/** 金额展示 */
const formatCost = (val?: number) => `¥${(val ?? 0).toFixed(2)}`;
const skuDataSource = computed(() => product.value?.skus ?? []);
const skuColumns = [
{
title: '图片',
dataIndex: 'imageUrl',
key: 'imageUrl',
width: 72,
align: 'center' as const,
customRender: ({ record }: { record: ProductVO.SkuInfo }) => {
if (record.imageUrl) {
return h(Image, {
src: record.imageUrl,
width: 40,
height: 40,
class: 'object-cover',
preview: true,
});
}
return h(ImageIcon, {
class: 'mx-auto h-5 w-5 text-slate-300 dark:text-[hsl(240deg_5%_45%)]',
});
},
},
{
title: 'SKU 编码',
dataIndex: 'skuCode',
key: 'skuCode',
width: 140,
customRender: ({ text }: { text?: string }) => text || '-',
},
{
title: 'SKU 名称',
dataIndex: 'name',
key: 'name',
ellipsis: true,
},
{
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 110,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.productCost),
},
{
title: '运费成本',
dataIndex: 'shippingCost',
key: 'shippingCost',
width: 110,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.shippingCost),
},
{
title: '其他成本',
dataIndex: 'otherCost',
key: 'otherCost',
width: 110,
customRender: ({ record }: { record: ProductVO.SkuInfo }) =>
formatCost(record.otherCost),
},
{
title: '备注',
dataIndex: 'remark',
key: 'remark',
ellipsis: true,
customRender: ({ text }: { text?: string }) => text || '-',
},
];
const [Modal, modalApi] = useVbenModal({
title: '商品详情',
class: 'w-[920px] max-w-[calc(100vw-2rem)]',
draggable: true,
showConfirmButton: false,
showCancelButton: false,
footer: false,
});
/** 打开详情模态框 */
function open(record: ProductVO.Info) {
product.value = record;
modalApi.setState({
title: `商品详情 - ${record.name}`,
});
modalApi.open();
}
/** 跳转经营统计 */
function goOverview() {
if (!product.value) return;
router.push(`/ecom/product/overview/${product.value.id}`);
modalApi.close();
}
/** 编辑商品 */
function handleEdit() {
if (!product.value) return;
const current = product.value;
modalApi.close();
emit('edit', current);
}
defineExpose({
open,
});
</script>
<template>
<Modal>
<div v-if="product" class="space-y-5">
<!-- 商品基础信息 -->
<div
class="flex flex-col gap-4 rounded-xl border border-slate-200 bg-slate-50/80 p-4 sm:flex-row sm:items-start dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
>
<div
class="flex h-[120px] w-[120px] shrink-0 items-center justify-center overflow-hidden rounded-lg border border-slate-200 bg-white dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<Image
v-if="product.mainImage"
:src="product.mainImage"
:width="120"
:height="120"
class="object-cover"
:preview="true"
/>
<ImageIcon
v-else
class="h-10 w-10 text-slate-300 dark:text-[hsl(240deg_5%_45%)]"
/>
</div>
<div class="min-w-0 flex-1 space-y-2 text-sm">
<div class="text-lg font-semibold text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ product.name }}
</div>
<div class="grid gap-2 sm:grid-cols-2">
<div>
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">商品编码:</span>
<span>{{ product.productCode || '-' }}</span>
</div>
<div>
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">商品类目:</span>
<span>{{ product.categoryName || '-' }}</span>
</div>
<div>
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">SKU 数量:</span>
<span>{{ product.skus?.length ?? 0 }}</span>
</div>
<div>
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">创建时间:</span>
<span>{{ product.createTime || '-' }}</span>
</div>
</div>
</div>
</div>
<!-- SKU 明细表 -->
<div>
<div class="mb-3 text-base font-medium text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
SKU 明细
</div>
<Table
:columns="skuColumns"
:data-source="skuDataSource"
:pagination="false"
row-key="id"
size="small"
bordered
:scroll="{ x: 820 }"
/>
</div>
<div class="flex justify-end border-t border-slate-200 pt-4 dark:border-[hsl(240deg_3.7%_22%)]">
<Space>
<Button @click="modalApi.close()">关闭</Button>
<Button @click="goOverview">
<ChartIcon class="mr-1 h-4 w-4" />
经营统计
</Button>
<Button type="primary" @click="handleEdit">
<EditIcon class="mr-1 h-4 w-4" />
编辑商品
</Button>
</Space>
</div>
</div>
</Modal>
</template>
@@ -0,0 +1,429 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { ProductDTO, ProductVO } from '#/api/ecommerce/product/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Image, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteProductApi, getProductPageApi } from '#/api/ecommerce/product';
import ProductDetailModal from './components/ProductDetailModal.vue';
import ProductFormModal from './components/ProductFormModal.vue';
defineOptions({ name: 'ProductManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const ChartIcon = createIconifyIcon('lucide:line-chart');
const EditIcon = createIconifyIcon('lucide:square-pen');
const ImageIcon = createIconifyIcon('lucide:image');
const router = useRouter();
const loading = ref(false);
const productFormModalRef = ref<InstanceType<typeof ProductFormModal> | null>(
null,
);
const productDetailModalRef = ref<InstanceType<typeof ProductDetailModal> | null>(
null,
);
/** 列表行内最多展示的 SKU 编码标签数 */
const MAX_SKU_CODE_TAGS = 4;
// 搜索条件
const searchForm = ref({
name: '',
productCode: '',
skuCode: '',
skuName: '',
});
/** 提取 SKU 编码列表 */
function getSkuCodes(row: ProductVO.Info): string[] {
return (row.skus || [])
.map((sku) => sku.skuCode?.trim())
.filter((code): code is string => !!code);
}
/** 列表 SKU 编码预览 */
function getSkuCodePreview(row: ProductVO.Info) {
const codes = getSkuCodes(row);
return {
visible: codes.slice(0, MAX_SKU_CODE_TAGS),
rest: Math.max(codes.length - MAX_SKU_CODE_TAGS, 0),
empty: codes.length === 0,
};
}
// VbenVxeGrid 表格配置(行高高于订单表,便于展示商品图)
const gridOptions: VxeGridProps<ProductVO.Info> = {
columns: [
{
type: 'seq' as const,
minWidth: 'auto',
title: '序号',
},
{
title: '商品信息',
minWidth: 260,
showOverflow: false,
slots: { default: 'productInfo' },
},
{
field: 'productCode',
title: '商品编码',
minWidth: 140,
showOverflow: 'tooltip' as const,
},
{
field: 'categoryName',
title: '类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
title: 'SKU 编码',
minWidth: 200,
showOverflow: false,
slots: { default: 'skuCodes' },
},
{
title: 'SKU 数',
minWidth: 80,
slots: { default: 'skuCount' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 170,
showOverflow: 'tooltip' as const,
},
{
title: '操作',
minWidth: 200,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
// 商品行需要更高以容纳主图
rowConfig: {
isHover: true,
height: 88,
},
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSize: 20,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page, form }) => {
try {
loading.value = true;
const searchParams = form || {};
const filters: ProductDTO.Filters = {
name:
String(searchParams.name ?? searchForm.value.name ?? '').trim() ||
undefined,
productCode:
String(
searchParams.productCode ?? searchForm.value.productCode ?? '',
).trim() || undefined,
skuCode:
String(searchParams.skuCode ?? searchForm.value.skuCode ?? '').trim() ||
undefined,
skuName:
String(searchParams.skuName ?? searchForm.value.skuName ?? '').trim() ||
undefined,
};
const params: PageQueryDTO<ProductDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters,
};
const data = await getProductPageApi(params);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取商品列表失败:', error);
message.error('获取商品列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入商品名称(回车搜索)',
allowClear: true,
onChange: (e: Event) => {
searchForm.value.name = (e.target as HTMLInputElement).value;
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'name',
label: '商品名称',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入商品编码(回车搜索)',
allowClear: true,
onChange: (e: Event) => {
searchForm.value.productCode = (e.target as HTMLInputElement).value;
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'productCode',
label: '商品编码',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入 SKU 名称(回车搜索)',
allowClear: true,
onChange: (e: Event) => {
searchForm.value.skuName = (e.target as HTMLInputElement).value;
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'skuName',
label: 'SKU 名称',
},
{
component: 'Input',
componentProps: {
placeholder: '请输入 SKU 编码(回车搜索)',
allowClear: true,
onChange: (e: Event) => {
searchForm.value.skuCode = (e.target as HTMLInputElement).value;
},
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'skuCode',
label: 'SKU 编码',
},
],
showDefaultActions: true,
collapsed: false,
submitOnEnter: true,
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '商品管理',
});
gridReloadRef.value = () => gridApi.reload();
function refreshTable() {
gridApi.reload();
}
function handleAdd() {
productFormModalRef.value?.open(false);
}
function handleEdit(record: ProductVO.Info) {
productFormModalRef.value?.open(true, record);
}
/** 打开商品详情模态框 */
function openProductDetail(record: ProductVO.Info) {
productDetailModalRef.value?.open(record);
}
function goToOverview(record: ProductVO.Info) {
router.push(`/ecom/product/overview/${record.id}`);
}
async function handleDelete(record: ProductVO.Info) {
try {
await deleteProductApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除商品失败:', error);
message.error('删除商品失败');
}
}
function handleModalSuccess() {
refreshTable();
}
function handleDetailEdit(record: ProductVO.Info) {
handleEdit(record);
}
</script>
<template>
<Page auto-content-height>
<Grid :loading="loading" class="product-grid">
<template #toolbar-tools>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-1 h-4 w-4" />
添加商品
</Button>
</template>
<!-- 商品信息:主图 + 名称,点击打开详情 -->
<template #productInfo="{ row }: { row: ProductVO.Info }">
<div
class="product-info-cell flex cursor-pointer items-center gap-3"
@click="openProductDetail(row)"
>
<div
class="flex h-16 w-16 shrink-0 items-center justify-center overflow-hidden rounded-md border border-slate-200 bg-slate-50 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
>
<Image
v-if="row.mainImage"
:src="row.mainImage"
:width="64"
:height="64"
class="object-cover"
:preview="false"
/>
<ImageIcon
v-else
class="h-6 w-6 text-slate-300 dark:text-[hsl(240deg_5%_45%)]"
/>
</div>
<div class="min-w-0 flex-1">
<div
class="truncate text-sm font-medium text-[#1890ff] hover:underline"
>
{{ row.name }}
</div>
<div
class="mt-0.5 truncate text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
点击查看详情
</div>
</div>
</div>
</template>
<!-- SKU 编码预览,点击同样打开详情 -->
<template #skuCodes="{ row }: { row: ProductVO.Info }">
<div
class="sku-codes-cell flex cursor-pointer flex-wrap items-center gap-1"
@click="openProductDetail(row)"
>
<template v-if="!getSkuCodePreview(row).empty">
<Tag
v-for="code in getSkuCodePreview(row).visible"
:key="code"
class="m-0"
>
{{ code }}
</Tag>
<Tag v-if="getSkuCodePreview(row).rest > 0" class="m-0">
+{{ getSkuCodePreview(row).rest }}
</Tag>
</template>
<span v-else class="text-slate-400">-</span>
</div>
</template>
<template #skuCount="{ row }: { row: ProductVO.Info }">
{{ row.skus?.length ?? 0 }}
</template>
<template #action="{ row }: { row: ProductVO.Info }">
<Space :size="4">
<Button type="link" size="small" @click="openProductDetail(row)">
详情
</Button>
<Button type="link" size="small" @click="handleEdit(row)">
<EditIcon class="mr-0.5 h-3.5 w-3.5" />
编辑
</Button>
<Button type="link" size="small" @click="goToOverview(row)">
<ChartIcon class="mr-0.5 h-3.5 w-3.5" />
统计
</Button>
<Popconfirm
title="确定删除该商品吗?删除后不可恢复。"
ok-text="确定删除"
cancel-text="取消"
@confirm="handleDelete(row)"
>
<Button type="link" size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<ProductFormModal ref="productFormModalRef" @success="handleModalSuccess" />
<ProductDetailModal
ref="productDetailModalRef"
@edit="handleDetailEdit"
/>
</Page>
</template>
<style scoped>
/* 商品表行高与单元格垂直居中 */
:deep(.product-grid .vxe-body--column) {
vertical-align: middle;
}
.product-info-cell,
.sku-codes-cell {
min-height: 64px;
}
</style>
@@ -0,0 +1,216 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import dayjs from 'dayjs';
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
interface Props {
data: {
salesAmountTrend?: {
dailyDataList: { date: string; value: number }[];
};
orderCountTrend?: {
dailyDataList: { date: string; value: number }[];
};
} | null;
}
const props = defineProps<Props>();
const trendChartRef = ref<EchartsUIType>();
const { renderEcharts: renderTrendChart } = useEcharts(trendChartRef);
let isUnmounted = false;
let renderTimer: null | ReturnType<typeof setTimeout> = null;
let darkObserver: MutationObserver | null = null;
const renderChart = () => {
if (!trendChartRef.value || !props.data) return;
const salesTrend = props.data.salesAmountTrend;
const orderTrend = props.data.orderCountTrend;
if (!salesTrend || !orderTrend) return;
const salesList = Array.isArray(salesTrend.dailyDataList)
? salesTrend.dailyDataList
: [];
const orderList = Array.isArray(orderTrend.dailyDataList)
? orderTrend.dailyDataList
: [];
if (salesList.length === 0 && orderList.length === 0) {
return;
}
const dates = salesList.map((item) =>
dayjs(item.date).format('MM-DD'),
);
const salesData = salesList.map((item) => item.value);
const orderData = orderList.map((item) => item.value);
const isDark = document.documentElement.classList.contains('dark');
try {
renderTrendChart({
grid: {
left: '3%',
right: '3%',
bottom: '3%',
top: '5%',
containLabel: true,
},
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
textStyle: {
color: isDark ? 'hsl(0deg 0% 95%)' : '#000',
},
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dates,
axisLine: {
lineStyle: {
color: isDark ? 'hsl(240deg 3.7% 22%)' : '#e2e8f0',
},
},
},
yAxis: [
{
type: 'value',
name: '销售额',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: {
lineStyle: {
type: 'dashed',
color: isDark ? 'hsl(240deg 3.7% 22%)' : undefined,
},
},
},
{
type: 'value',
name: '单量',
position: 'right',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: { show: false },
},
],
series: [
{
name: '销售额',
type: 'line',
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#3b82f6' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(59, 130, 246, 0.4)' },
{ offset: 1, color: 'rgba(59, 130, 246, 0)' },
],
},
},
data: salesData,
},
{
name: '日单量',
type: 'line',
yAxisIndex: 1,
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#10b981' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
{ offset: 1, color: 'rgba(16, 185, 129, 0)' },
],
},
},
data: orderData,
},
],
});
} catch (error) {
console.error('渲染趋势图失败:', error);
}
};
const scheduleRender = async () => {
if (renderTimer) {
clearTimeout(renderTimer);
renderTimer = null;
}
await nextTick();
if (isUnmounted) return;
renderTimer = setTimeout(() => {
if (isUnmounted) return;
renderChart();
}, 16);
};
watch(
() => props.data,
() => {
if (props.data) {
scheduleRender();
}
},
{ deep: true, immediate: true },
);
onMounted(() => {
isUnmounted = false;
darkObserver = new MutationObserver(() => {
if (props.data) scheduleRender();
});
darkObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
});
onUnmounted(() => {
isUnmounted = true;
if (renderTimer) {
clearTimeout(renderTimer);
renderTimer = null;
}
darkObserver?.disconnect();
darkObserver = null;
});
defineExpose({ renderChart });
</script>
<template>
<div class="rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px] xl:col-span-2">
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
销售额与单量趋势分析
</h3>
<div class="h-[380px] w-full">
<EchartsUI ref="trendChartRef" />
</div>
</div>
</template>
@@ -0,0 +1,87 @@
<script lang="ts" setup>
interface SkuSalesRankItem {
skuId?: number;
skuName?: string;
skuCode?: string;
orderCount?: number;
salesAmount?: number;
}
interface Props {
data: SkuSalesRankItem[] | null;
}
defineProps<Props>();
const formatAmount = (amount: number | undefined) => {
if (amount === undefined || amount === null) return '-';
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
</script>
<template>
<div
class="flex flex-col rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<h3 class="mb-1 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
各 SKU 销量 Top10
</h3>
<p class="mb-5 text-xs font-medium text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
按单量排序,与上方时间范围一致
</p>
<div class="max-h-[380px] flex-1 space-y-2 overflow-y-auto pr-1">
<template v-if="data?.length">
<div
v-for="(row, idx) in data"
:key="row.skuId ?? `rank-${idx}`"
class="flex items-center gap-3 rounded-xl border border-slate-100/90 bg-slate-50/60 px-3 py-2.5 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/50%)]"
>
<span
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-sm font-black tabular-nums"
:class="
idx === 0
? 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200'
: idx === 1
? 'bg-slate-200 text-slate-700 dark:bg-slate-600 dark:text-slate-100'
: idx === 2
? 'bg-orange-100 text-orange-900 dark:bg-orange-900/30 dark:text-orange-200'
: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-300'
"
>
{{ idx + 1 }}
</span>
<div class="min-w-0 flex-1">
<div
class="truncate text-sm font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
:title="row.skuName"
>
{{ row.skuName || '-' }}
</div>
<div
v-if="row.skuCode"
class="truncate text-[11px] text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
{{ row.skuCode }}
</div>
</div>
<div class="shrink-0 text-right">
<div class="text-sm font-black tabular-nums text-indigo-600 dark:text-indigo-400">
{{ row.orderCount != null ? row.orderCount.toLocaleString('zh-CN') : '-' }}
<span class="text-[10px] font-semibold text-slate-400 dark:text-[hsl(240deg_5%_55%)]">单</span>
</div>
<div class="text-[11px] font-semibold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
{{ formatAmount(row.salesAmount) }}
</div>
</div>
</div>
</template>
<div
v-else
class="flex flex-1 items-center justify-center py-16 text-sm text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
暂无 SKU 数据
</div>
</div>
</div>
</template>
@@ -0,0 +1,316 @@
<script lang="ts" setup>
import type { ProductOverviewVO } from '#/api/ecommerce/product-overview';
import { computed } from 'vue';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import {
overviewTableHints,
salesTaxColumnHint,
} from '#/utils/overview-table-hints';
import { formatNumberCell } from '#/utils/overview-table-cells';
interface SkuData {
skuId: number;
skuName: string;
skuCode?: string;
salesAmount: number;
orderCount: number;
quantity: number;
averageOrderValue: number;
productCost: number;
shippingCost: number;
otherCost: number;
orderCost?: number;
refundAmount: number;
promotionFee: number;
feeRatio: number;
profitBeforeTax: number;
salesTaxAmount: number;
roi: number;
profitAfterTax: number;
}
interface Props {
data: SkuData[];
/** 后端合计行(含 orderCost),优先展示 */
footerTotal?: ProductOverviewVO.SkuSummaryTotal | null;
taxRate?: number;
}
const props = withDefaults(defineProps<Props>(), {
taxRate: 0.04,
footerTotal: null,
});
const formatAmount = (amount: number | undefined) => {
if (amount === undefined || amount === null) return '-';
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const cellMoney = (v: number | null | undefined) =>
formatNumberCell(v, (n) =>
`¥${n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`,
);
const cellRoi = (v: number | null | undefined) =>
formatNumberCell(v, (n) => n.toFixed(2));
const formatPercent = (value: number | undefined) => {
if (value === undefined || value === null) return '-';
return `${value.toFixed(1)}%`;
};
const formatCount = (value: number | undefined) => {
if (value === undefined || value === null) return '-';
return value.toLocaleString('zh-CN');
};
/** 无后端合计时由行数据汇总(兼容旧数据) */
const computedFooter = computed(() => {
if (!props.data || props.data.length === 0) return null;
const total: SkuData = {
skuId: 0,
skuName: '合计',
salesAmount: 0,
orderCount: 0,
quantity: 0,
averageOrderValue: 0,
productCost: 0,
shippingCost: 0,
otherCost: 0,
orderCost: 0,
refundAmount: 0,
promotionFee: 0,
feeRatio: 0,
profitBeforeTax: 0,
salesTaxAmount: 0,
roi: 0,
profitAfterTax: 0,
};
props.data.forEach((item) => {
total.salesAmount += item.salesAmount || 0;
total.orderCount += item.orderCount || 0;
total.quantity += item.quantity || 0;
total.productCost += item.productCost || 0;
total.shippingCost += item.shippingCost || 0;
total.otherCost += item.otherCost || 0;
const lineTotalCost =
item.orderCost ??
(item.productCost || 0) + (item.shippingCost || 0) + (item.otherCost || 0);
total.orderCost = (total.orderCost || 0) + lineTotalCost;
total.refundAmount += item.refundAmount || 0;
total.promotionFee += item.promotionFee || 0;
total.profitBeforeTax += item.profitBeforeTax || 0;
total.salesTaxAmount += item.salesTaxAmount || 0;
total.profitAfterTax += item.profitAfterTax || 0;
});
if (total.salesAmount > 0) {
total.averageOrderValue = total.salesAmount / total.orderCount;
total.feeRatio = (total.promotionFee / total.salesAmount) * 100;
const costBase = total.orderCost ?? total.productCost + total.shippingCost + total.otherCost;
total.roi =
costBase + total.promotionFee > 0
? (total.profitAfterTax / (costBase + total.promotionFee)) * 100
: 0;
}
return total;
});
const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
</script>
<template>
<div
class="overflow-hidden rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div
class="flex items-center justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white/40 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6"
>
<div>
<h3 class="text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">商品 SKU 销售汇总</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
各 SKU 经营明细:规模、成本及最终损益
</p>
</div>
</div>
<div class="table-container">
<table class="w-full whitespace-nowrap text-left text-sm">
<thead
class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-xs font-black uppercase text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
<tr>
<th
rowspan="2"
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%)] p-5 text-base font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)] shadow-sm dark:shadow-none"
>
SKU 名称
</th>
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-blue-50/50 dark:bg-[hsl(217.2deg_32.6%_17.5%/50%)] p-3 text-center text-blue-700 dark:text-blue-400"
>
经营规模
</th>
<th
colspan="7"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50%)] p-3 text-center text-orange-700 dark:text-orange-400"
>
成本费用
</th>
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-3 text-center text-emerald-700 dark:text-emerald-400"
>
盈利分析
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<!-- 规模 -->
<th class="border-b border-l px-5 py-3 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="overviewTableHints.salesAmountShort">
销售额
</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.orderCountSku">
订单量
</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<!-- 成本 -->
<th class="border-b border-l px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 font-bold text-rose-600 dark:text-rose-400">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3">
<OverviewColumnHint :title="overviewTableHints.promotionFeeSku">推广费</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="overviewTableHints.feeRatioSku">费比 %</OverviewColumnHint>
</th>
<!-- 盈利 -->
<th class="border-b border-l px-5 py-3 font-bold">
<OverviewColumnHint :title="overviewTableHints.profitBeforeTaxSku">税前盈亏</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="salesTaxColumnHint(taxRate)">
{{ (taxRate * 100).toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b px-5 py-3 font-black text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="overviewTableHints.roi">ROI</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 dark:bg-emerald-600 px-5 py-3 font-black text-white">
<OverviewColumnHint light :title="overviewTableHints.profitAfterTax">
税后盈亏
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="item in data"
:key="item.skuId"
class="transition-colors hover:bg-slate-50/50 dark:hover:bg-[hsl(240deg_3.7%_15.9%/30%)]"
>
<!-- SKU 名称 -->
<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%)] p-5 shadow-sm dark:shadow-none">
<span class="inline-block rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400">{{ item.skuName }}</span>
</td>
<!-- 规模 -->
<td class="p-5 font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">{{ formatAmount(item.salesAmount) }}</td>
<td class="p-5 font-medium">
<span>{{ formatCount(item.orderCount) }}</span>
<span class="ml-1 text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
<span class="ml-2 text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">({{ formatCount(item.quantity) }}件)</span>
</td>
<td class="p-5 font-medium">{{ formatAmount(item.averageOrderValue) }}</td>
<!-- 成本 -->
<td class="p-5">{{ cellMoney(item.productCost) }}</td>
<td class="p-5">{{ cellMoney(item.shippingCost) }}</td>
<td class="p-5">{{ cellMoney(item.otherCost) }}</td>
<td class="p-5 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoney(item.orderCost) }}
</td>
<td class="p-5 font-bold text-rose-600 dark:text-rose-400">
{{ cellMoney(item.refundAmount) }}
</td>
<td class="p-5">{{ cellMoney(item.promotionFee) }}</td>
<td class="p-5 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatPercent(item.feeRatio) }}</td>
<!-- 盈利 -->
<td class="p-5 font-bold" :class="item.profitBeforeTax >= 0 ? 'text-slate-800 dark:text-[hsl(0deg_0%_95%)]' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(item.profitBeforeTax) }}
</td>
<td class="p-5 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoney(item.salesTaxAmount) }}</td>
<td class="p-5 font-black text-indigo-700 dark:text-indigo-400">{{ cellRoi(item.roi) }}</td>
<td class="bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-5 text-base font-black" :class="item.profitAfterTax >= 0 ? 'text-emerald-600 dark:text-emerald-400' : 'text-rose-600 dark:text-rose-400'">
{{ formatAmount(item.profitAfterTax) }}
</td>
</tr>
<tr v-if="!data || data.length === 0">
<td colspan="16" class="p-8 text-center text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">暂无 SKU 数据</td>
</tr>
</tbody>
<tfoot v-if="footerRow" class="bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] p-5 text-base">合计</td>
<td class="p-5">{{ formatAmount(footerRow.salesAmount) }}</td>
<td class="p-5">
<span>{{ formatCount(footerRow.orderCount) }}</span>
<span class="ml-1 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
<span class="ml-2 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">({{ formatCount(footerRow.quantity) }}件)</span>
</td>
<td class="p-5">{{ formatAmount(footerRow.averageOrderValue) }}</td>
<td class="p-5">{{ formatAmount(footerRow.productCost) }}</td>
<td class="p-5">{{ formatAmount(footerRow.shippingCost) }}</td>
<td class="p-5">{{ formatAmount(footerRow.otherCost) }}</td>
<td class="p-5 font-bold text-orange-800 dark:text-orange-300">
{{ footerRow.orderCost != null ? formatAmount(footerRow.orderCost) : formatAmount((footerRow.productCost || 0) + (footerRow.shippingCost || 0) + (footerRow.otherCost || 0)) }}
</td>
<td class="p-5 text-rose-600 dark:text-rose-400">{{ formatAmount(footerRow.refundAmount) }}</td>
<td class="p-5">{{ formatAmount(footerRow.promotionFee) }}</td>
<td class="p-5 text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatPercent(footerRow.feeRatio) }}</td>
<td class="p-5">{{ formatAmount(footerRow.profitBeforeTax) }}</td>
<td class="p-5 italic text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">{{ formatAmount(footerRow.salesTaxAmount) }}</td>
<td class="p-5 text-indigo-700 dark:text-indigo-400">{{ cellRoi(footerRow.roi) }}</td>
<td class="bg-emerald-100 dark:bg-emerald-900/30 p-5 text-base text-emerald-600 dark:text-emerald-400">{{ formatAmount(footerRow.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
<style scoped>
.sticky-col {
position: sticky;
left: 0;
z-index: 10;
}
.table-container {
overflow-x: auto;
}
.table-container::-webkit-scrollbar {
height: 6px;
}
.table-container::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
</style>
@@ -0,0 +1,142 @@
<script lang="ts" setup>
interface Props {
data: {
productName?: string;
totalSalesAmount?: number;
totalOrderCount?: number;
monthOverMonthGrowth?: number;
salesAmountAchievementRate?: number;
orderCountAchievementRate?: number;
averageFeeRatio?: number;
totalROI?: number;
totalNetProfitAfterTax?: number;
totalTaxAmount?: number;
} | null;
loading?: boolean;
}
defineProps<Props>();
const formatAmount = (amount: number | undefined) => {
if (amount === undefined) return '-';
return `¥${amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
};
const toNumber = (value: unknown): number | undefined => {
if (value === undefined || value === null || value === '') return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
};
const formatPercentPlain = (value: number | undefined | null) => {
if (value == null) return '-';
return `${value.toFixed(1)}%`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
</script>
<template>
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-4">
<!-- 销售额 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 flex items-start justify-between">
<span class="text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
商品销售总额
</span>
<span
v-if="data?.monthOverMonthGrowth !== undefined"
class="rounded bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-2 py-1 text-xs font-bold text-emerald-600 dark:text-emerald-400"
>
增长率 {{ formatPercent(data.monthOverMonthGrowth) }}
</span>
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalSalesAmount ? formatAmount(data.totalSalesAmount) : '-' }}
</div>
<div
v-if="data?.salesAmountAchievementRate !== undefined"
class="mt-6 flex items-center justify-between border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-xs font-bold"
>
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">销售额目标达成</span>
<span class="font-black text-blue-600 dark:text-blue-400">
{{ formatPercentPlain(data.salesAmountAchievementRate) }}
</span>
</div>
</div>
<!-- 订单达成 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
订单总量与达成
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalOrderCount?.toLocaleString('zh-CN') || '-' }}
<span class="ml-1 text-sm font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
</div>
<div v-if="data?.orderCountAchievementRate !== undefined" class="mt-6">
<div class="mb-2 flex justify-between text-[10px] font-black text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<span>目标达成率</span>
<span>
{{ formatPercentPlain(data.orderCountAchievementRate) }}
</span>
</div>
<div class="h-2 w-full overflow-hidden rounded-full bg-slate-100">
<div
class="h-full bg-indigo-500 transition-all duration-1000"
:style="{ width: `${Math.min(data.orderCountAchievementRate || 0, 100)}%` }"
></div>
</div>
</div>
</div>
<!-- 推广效率 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
投资回报率 (ROI)
</div>
<div class="text-4xl font-black leading-none text-indigo-600 dark:text-indigo-400">
{{ toNumber(data?.totalROI)?.toFixed(2) || '-' }}
</div>
<div
v-if="data?.averageFeeRatio !== undefined"
class="mt-6 space-y-2 border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4"
>
<div class="flex justify-between text-xs font-bold">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">平均费比</span>
<span class="text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ formatPercentPlain(data.averageFeeRatio) }}
</span>
</div>
</div>
</div>
<!-- 利润汇总 -->
<div
class="flex flex-col justify-between rounded-[20px] border-l-4 border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] border-l-emerald-500 dark:border-l-emerald-500 bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-emerald-600 dark:text-emerald-400">
商品净利润 (税后)
</div>
<div class="text-4xl font-black leading-none text-emerald-600 dark:text-emerald-400">
{{ data?.totalNetProfitAfterTax ? formatAmount(data.totalNetProfitAfterTax) : '-' }}
</div>
<div
v-if="data?.totalTaxAmount !== undefined"
class="mt-6 flex justify-between border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-[11px] font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
<span>已扣除税额</span>
<span>{{ formatAmount(data.totalTaxAmount) }}</span>
</div>
</div>
</div>
</template>
@@ -0,0 +1,440 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { DatePicker, InputNumber, Popover, Select, Spin } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
import {
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState,
overviewToolbarPanelClass,
overviewToolbarShellClass,
} from '../../../styles/overview-toolbar-classes';
interface SelectOption {
label: string;
value: string;
}
interface Props {
modelValue: {
taxRate: number;
activeTimeRange:
| '7days'
| '30days'
| 'thisMonth'
| 'custom'
| 'today'
| 'yesterday';
customDateRange: [Dayjs, Dayjs] | undefined;
dateRange: [Dayjs, Dayjs];
};
/** 路由 query.shopId,未选店铺时为 undefined */
shopId?: number;
shopOptions?: SelectOption[];
shopListLoading?: boolean;
/** 当前商品 ID(与路由 params.id 一致) */
productId?: number;
productOptions?: SelectOption[];
productListLoading?: boolean;
}
interface Emits {
(e: 'update:modelValue', val: Props['modelValue']): void;
(e: 'shop-change', shopId: number | undefined): void;
(e: 'shop-search', keyword: string): void;
(e: 'shop-popup-scroll', event: Event): void;
(e: 'shop-dropdown-visible-change', open: boolean): void;
(e: 'product-change', productId: number): void;
(e: 'product-search', keyword: string): void;
(e: 'product-popup-scroll', event: Event): void;
(e: 'product-dropdown-visible-change', open: boolean): void;
}
const props = withDefaults(defineProps<Props>(), {
shopOptions: () => [],
shopListLoading: false,
productOptions: () => [],
productListLoading: false,
});
const emit = defineEmits<Emits>();
const openPopover = ref<string | null>(null);
function handlePopoverOpen(name: string, open: boolean) {
if (open) {
openPopover.value = name;
} else if (openPopover.value === name) {
openPopover.value = null;
}
}
const ReceiptIcon = createIconifyIcon('lucide:receipt');
const FilterIcon = createIconifyIcon('lucide:sliders-horizontal');
const CalendarIcon = createIconifyIcon('lucide:calendar');
const collapsedFilterLabel = computed(() => {
const shopName = props.shopId != null && props.shopId > 0
? (props.shopOptions?.find((o) => o.value === String(props.shopId))?.label ?? `店铺 #${props.shopId}`)
: '全部';
const productName = props.productId != null && props.productId > 0
? (props.productOptions?.find((o) => o.value === String(props.productId))?.label ?? `商品 #${props.productId}`)
: '选择商品';
return `${shopName}/${productName}`;
});
const timeRangeLabel = computed(() => {
const t = props.modelValue.activeTimeRange;
if (t === 'today') return '今日';
if (t === 'yesterday') return '昨日';
if (t === '7days') return '近7日';
if (t === '30days') return '近30日';
if (t === 'thisMonth') return '本月';
if (props.modelValue.customDateRange) {
return `${props.modelValue.customDateRange[0].format('M/D')}-${props.modelValue.customDateRange[1].format('M/D')}`;
}
return '日期';
});
const shopSelectValue = computed(() => {
if (props.shopId != null && props.shopId > 0) {
return String(props.shopId);
}
return undefined;
});
const handleShopSelectChange = (value: unknown) => {
if (value === '' || value == null) {
emit('shop-change', undefined);
return;
}
const id = Number(value);
if (!Number.isFinite(id) || id <= 0) return;
emit('shop-change', id);
};
const handleProductSelectChange = (value: unknown) => {
const id = Number(value);
if (!Number.isFinite(id) || id <= 0) return;
emit('product-change', id);
};
const TAX_RATE_KEY = 'overview-tax-rate';
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${Math.round(num * 100 * 1e10) / 1e10}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
const switchTimeRange = (
type: '7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday',
) => {
let startDate: Dayjs;
let endDate: 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 (props.modelValue.customDateRange) {
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: props.modelValue.customDateRange,
});
}
return;
case 'today':
startDate = dayjs();
endDate = dayjs();
break;
case 'yesterday':
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
const newRange: [Dayjs, Dayjs] = [startDate, endDate];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: newRange,
customDateRange: newRange,
});
};
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
dateStrings?: [string, string],
) => {
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) => {
const num = typeof val === 'string' ? parseTaxRate(val) : val ?? 0.04;
localStorage.setItem(TAX_RATE_KEY, String(num));
emit('update:modelValue', {
...props.modelValue,
taxRate: num,
});
};
</script>
<template>
<div
class="overview-header-extra flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2"
>
<!-- 税率 -->
<Popover
trigger="click"
:open="openPopover === 'taxRate'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('taxRate', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex items-center gap-2 whitespace-nowrap">
<span class="shrink-0 text-xs font-bold text-slate-700 dark:text-slate-300">
税率
</span>
<InputNumber
:value="props.modelValue.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-transparent !text-center !text-sm !font-bold !text-slate-800 !shadow-none dark:!text-slate-100"
:formatter="formatTaxRate"
:parser="parseTaxRate"
@change="handleTaxRateChange"
/>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<ReceiptIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">税率{{ formatTaxRate(props.modelValue.taxRate) }}</span>
</div>
</div>
</Popover>
<!-- 店铺/商品 -->
<Popover
trigger="click"
:open="openPopover === 'filter'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('filter', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-0">
<div
class="flex min-w-0 items-center gap-2 px-2 py-0.5 sm:w-[11.5rem] sm:flex-none sm:shrink-0 sm:py-0"
>
<span
class="w-9 shrink-0 text-right text-xs font-bold text-slate-700 dark:text-slate-300"
>
店铺
</span>
<Select
:value="shopSelectValue"
size="small"
show-search
allow-clear
:filter-option="false"
:loading="props.shopListLoading"
:options="props.shopOptions"
placeholder="全部店铺"
:dropdown-match-select-width="false"
class="overview-header-select overview-shop-select min-w-0 flex-1"
@change="handleShopSelectChange"
@search="(kw: string) => emit('shop-search', kw)"
@popup-scroll="(e: Event) => emit('shop-popup-scroll', e)"
@dropdown-visible-change="
(open: boolean) => emit('shop-dropdown-visible-change', open)
"
>
<template #notFoundContent>
<div v-if="props.shopListLoading" class="py-3 text-center">
<Spin size="small" />
<div class="mt-1 text-xs text-slate-600">加载中...</div>
</div>
<div v-else class="py-3 text-center text-xs text-slate-600">暂无店铺</div>
</template>
</Select>
</div>
<div
class="flex min-w-0 flex-1 items-center gap-2 border-t border-slate-200/80 px-2 pt-2 sm:min-w-[16rem] sm:border-t-0 sm:py-0 sm:pt-0 dark:border-[hsl(240deg_3.7%_22%)]"
>
<span
class="w-9 shrink-0 text-right text-xs font-bold text-slate-700 dark:text-slate-300"
>
商品
</span>
<Select
:value="
props.productId != null && props.productId > 0
? String(props.productId)
: undefined
"
size="small"
show-search
:filter-option="false"
:loading="props.productListLoading"
:options="props.productOptions"
placeholder="选择商品"
:dropdown-match-select-width="false"
class="overview-header-select overview-product-select min-w-0 flex-1"
@change="handleProductSelectChange"
@search="(kw: string) => emit('product-search', kw)"
@popup-scroll="(e: Event) => emit('product-popup-scroll', e)"
@dropdown-visible-change="
(open: boolean) => emit('product-dropdown-visible-change', open)
"
>
<template #notFoundContent>
<div v-if="props.productListLoading" class="py-3 text-center">
<Spin size="small" />
<div class="mt-1 text-xs text-slate-600">加载中...</div>
</div>
<div v-else class="py-3 text-center text-xs text-slate-600">暂无商品</div>
</template>
</Select>
</div>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<FilterIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">{{ collapsedFilterLabel }}</span>
</div>
</div>
</Popover>
<!-- 时间范围 -->
<Popover
trigger="click"
:open="openPopover === 'timeRange'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('timeRange', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex flex-col gap-2 px-1 py-0.5">
<div class="flex items-center gap-1 overflow-x-auto whitespace-nowrap">
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'today'),
]"
@click="switchTimeRange('today')"
>
今日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'yesterday'),
]"
@click="switchTimeRange('yesterday')"
>
昨日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === '7days'),
]"
@click="switchTimeRange('7days')"
>
近7日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === '30days'),
]"
@click="switchTimeRange('30days')"
>
近30日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'thisMonth'),
]"
@click="switchTimeRange('thisMonth')"
>
本月
</button>
</div>
<div class="flex items-center gap-2">
<span
class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300"
>
自定义日期
</span>
<DatePicker.RangePicker
:value="props.modelValue.customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始', '结束']"
class="overview-header-range-picker !h-8 !w-full !border-none !bg-transparent !text-sm !font-bold !text-slate-800 sm:!w-[220px] dark:!text-slate-200"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<CalendarIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">{{ timeRangeLabel }}</span>
</div>
</div>
</Popover>
</div>
</template>
<style src="../../../styles/overview-toolbar.css"></style>
<style src="../../../styles/overview-header-select.css"></style>
@@ -0,0 +1,554 @@
<script lang="ts" setup>
import type { Dayjs } from 'dayjs';
import { computed, onActivated, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Spin, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import TimeRangeBar from './components/TimeRangeBar.vue';
import StatCards from './components/StatCards.vue';
import SalesTrendChart from './components/SalesTrendChart.vue';
import SkuSalesTop10Panel from './components/SkuSalesTop10Panel.vue';
import SkuSummaryTable from './components/SkuSummaryTable.vue';
import { getProductPageApi } from '#/api/ecommerce/product/apis';
import type { ProductVO } from '#/api/ecommerce/product/types';
import { getProductOverviewApi } from '#/api/ecommerce/product-overview';
import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import {
applyOverviewDateRangeFromUrl,
buildOverviewRouteQuery,
parseOverviewShopIdFromQuery,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
defineOptions({ name: 'ProductOverview' });
const route = useRoute();
const router = useRouter();
const PRODUCT_PAGE_SIZE = 20;
const SHOP_PAGE_SIZE = 20;
/** 当前是否为商品概览路由(keep-alive 下勿用其它页的 params.id 请求商品接口) */
const isProductOverviewRoute = () =>
/\/ecom\/product\/overview\/[^/]+\/?$/.test(route.path);
// 商品ID(从路由参数获取)
const productId = computed(() => {
if (!isProductOverviewRoute()) return 0;
const id = route.params.id;
const parsed = id ? Number(id) : 0;
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
});
/** 路由 query.shopId:工作台筛选店铺跳转时带入 */
const contextShopId = computed(() => {
if (!isProductOverviewRoute()) return undefined;
return parseOverviewShopIdFromQuery(
route.query as Record<string, unknown>,
);
});
const shops = ref<ShopVO.Info[]>([]);
const shopsLoading = ref(false);
const shopPage = ref(1);
const shopTotal = ref(0);
const shopSearchKeyword = ref('');
const selectedShopLabelCache = ref('');
const products = ref<ProductVO.Info[]>([]);
const productsLoading = ref(false);
const productPage = ref(1);
const productTotal = ref(0);
const productSearchKeyword = ref('');
let productSearchTimer: ReturnType<typeof setTimeout> | undefined;
let shopSearchTimer: ReturnType<typeof setTimeout> | undefined;
const shopSelectOptions = computed(() => {
const opts = shops.value.map((s) => ({
label: s.name,
value: String(s.id),
}));
const id = contextShopId.value;
if (id != null && id > 0 && !opts.some((o) => o.value === String(id))) {
opts.unshift({
label: selectedShopLabelCache.value || `店铺 #${id}`,
value: String(id),
});
}
return opts;
});
// 响应式数据
const loading = ref(false);
const overviewData = ref<any>(null);
const productSelectOptions = computed(() => {
const opts = products.value.map((p) => ({
label: p.name,
value: String(p.id),
}));
const id = productId.value;
if (id > 0 && !opts.some((o) => o.value === String(id))) {
const name = overviewData.value?.productName ?? `商品 #${id}`;
return [{ label: name, value: String(id) }, ...opts];
}
return opts;
});
const normalizeOverview = (raw: any) => {
if (!raw || typeof raw !== 'object') return null;
return {
// 保留所有 KPI 字段
...raw,
// 防御性处理嵌套结构
salesAmountTrend: {
...(raw.salesAmountTrend || {}),
dailyDataList: Array.isArray(raw.salesAmountTrend?.dailyDataList)
? raw.salesAmountTrend.dailyDataList
: [],
},
orderCountTrend: {
...(raw.orderCountTrend || {}),
dailyDataList: Array.isArray(raw.orderCountTrend?.dailyDataList)
? raw.orderCountTrend.dailyDataList
: [],
},
specSummaries: {
...(raw.specSummaries || {}),
list: Array.isArray(raw.specSummaries?.list) ? raw.specSummaries.list : [],
},
};
};
// 日期范围(默认:本月至今日)
const dateRange = ref<[Dayjs, Dayjs]>([
dayjs().startOf('month'),
dayjs(),
]);
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday'
>('thisMonth');
// 自定义日期范围
const customDateRange = ref<[Dayjs, Dayjs] | undefined>([
dateRange.value[0],
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, () => {
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);
};
function buildProductOverviewQuery() {
return buildOverviewRouteQuery(
dateRange.value,
contextShopId.value != null && contextShopId.value > 0
? { shopId: contextShopId.value }
: undefined,
);
}
async function fetchShopList(page = 1, append = false) {
if (shopsLoading.value) return;
shopsLoading.value = true;
try {
const keyword = shopSearchKeyword.value.trim();
const data = await getShopPageApi({
page,
pageSize: SHOP_PAGE_SIZE,
filters: keyword ? { name: keyword } : {},
});
const records = data.records ?? [];
shops.value = append ? [...shops.value, ...records] : records;
shopTotal.value = data.total ?? 0;
shopPage.value = page;
const id = contextShopId.value;
if (id != null && id > 0) {
const hit = shops.value.find((s) => s.id === id);
if (hit) selectedShopLabelCache.value = hit.name;
}
} catch {
message.error('店铺列表加载失败');
} finally {
shopsLoading.value = false;
}
}
function handleShopSearch(keyword: string) {
if (shopSearchTimer) clearTimeout(shopSearchTimer);
shopSearchTimer = setTimeout(() => {
shopSearchKeyword.value = keyword;
void fetchShopList(1, false);
}, 300);
}
function handleShopPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = shopPage.value * SHOP_PAGE_SIZE < shopTotal.value;
if (hasMore && !shopsLoading.value) {
void fetchShopList(shopPage.value + 1, true);
}
}
}
function handleShopDropdownVisibleChange(open: boolean) {
if (!open) return;
shopSearchKeyword.value = '';
void fetchShopList(1, false);
}
function handleShopChange(nextShopId: number | undefined) {
products.value = [];
productSearchKeyword.value = '';
router.replace({
path: `/ecom/product/overview/${productId.value}`,
query: buildOverviewRouteQuery(
dateRange.value,
nextShopId != null && nextShopId > 0 ? { shopId: nextShopId } : undefined,
),
});
}
async function fetchProductList(page = 1, append = false) {
if (productsLoading.value) return;
productsLoading.value = true;
try {
const keyword = productSearchKeyword.value.trim();
const data = await getProductPageApi({
page,
pageSize: PRODUCT_PAGE_SIZE,
filters: keyword ? { keywords: keyword } : {},
});
const records = data.records ?? [];
products.value = append ? [...products.value, ...records] : records;
productTotal.value = data.total ?? 0;
productPage.value = page;
} catch {
message.error('商品列表加载失败');
} finally {
productsLoading.value = false;
}
}
function handleProductSearch(keyword: string) {
if (productSearchTimer) clearTimeout(productSearchTimer);
productSearchTimer = setTimeout(() => {
productSearchKeyword.value = keyword;
void fetchProductList(1, false);
}, 300);
}
function handleProductPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = productPage.value * PRODUCT_PAGE_SIZE < productTotal.value;
if (hasMore && !productsLoading.value) {
void fetchProductList(productPage.value + 1, true);
}
}
}
function handleProductDropdownVisibleChange(open: boolean) {
if (!open) return;
productSearchKeyword.value = '';
void fetchProductList(1, false);
}
function handleProductChange(nextProductId: number) {
if (!nextProductId || nextProductId === productId.value) return;
lastRequestKey.value = '';
router.push({
path: `/ecom/product/overview/${nextProductId}`,
query: buildProductOverviewQuery(),
});
}
// 时间范围状态(传递给子组件)
const timeRangeState = computed(() => ({
taxRate: taxRate.value,
activeTimeRange: activeTimeRange.value,
customDateRange: customDateRange.value,
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;
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
async function loadOverviewData() {
if (!isProductOverviewRoute() || !productId.value) return;
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'),
endDate: dateRange.value[1].format('YYYY-MM-DD'),
taxRate: taxRate.value,
...(contextShopId.value != null && contextShopId.value > 0
? { shopId: contextShopId.value }
: {}),
});
overviewData.value = normalizeOverview(res);
} catch (err: any) {
message.error(err?.message || '加载失败');
} finally {
loading.value = false;
isRequesting.value = false;
}
}
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')}_${contextShopId.value ?? ''}`;
if (!force && lastRequestKey.value === requestKey) {
return;
}
lastRequestKey.value = requestKey;
await loadOverviewData();
};
// 监听路由(与店铺概览一致;日期 query 以 window.location 为准,见 applyOverviewDateRangeFromUrl)
watch(
() => [
route.path,
route.params.id,
route.query.startDate,
route.query.endDate,
route.query.shopId,
],
async () => {
if (!isProductOverviewRoute()) return;
await refreshOverviewByCurrentParams();
},
);
watch(contextShopId, () => {
products.value = [];
lastRequestKey.value = '';
});
onMounted(async () => {
if (!isProductOverviewRoute()) return;
if (contextShopId.value != null && contextShopId.value > 0) {
void fetchShopList(1, false);
}
await refreshOverviewByCurrentParams(true);
});
onActivated(async () => {
if (!isProductOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
onUnmounted(() => {
if (productSearchTimer) clearTimeout(productSearchTimer);
if (shopSearchTimer) clearTimeout(shopSearchTimer);
});
</script>
<template>
<Page
auto-content-height
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
header-class="product-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="w-full max-w-full sm:w-auto">
<TimeRangeBar
:model-value="timeRangeState"
:shop-id="contextShopId"
:shop-options="shopSelectOptions"
:shop-list-loading="shopsLoading"
:product-id="productId"
:product-options="productSelectOptions"
:product-list-loading="productsLoading"
@update:model-value="handleTimeRangeChange"
@shop-change="handleShopChange"
@shop-search="handleShopSearch"
@shop-popup-scroll="handleShopPopupScroll"
@shop-dropdown-visible-change="handleShopDropdownVisibleChange"
@product-change="handleProductChange"
@product-search="handleProductSearch"
@product-popup-scroll="handleProductPopupScroll"
@product-dropdown-visible-change="handleProductDropdownVisibleChange"
/>
</div>
</template>
<Spin :spinning="loading">
<div v-if="overviewData" class="mx-auto w-full space-y-6">
<!-- 第一层:核心统计卡片 -->
<StatCards :data="overviewData" :loading="loading" />
<!-- 第二层:趋势与财务拆解 -->
<div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
<SalesTrendChart :data="overviewData" />
<SkuSalesTop10Panel :data="overviewData?.specSalesTop10 ?? []" />
</div>
<!-- 第三层:SKU 销售汇总 -->
<SkuSummaryTable
:data="overviewData?.specSummaries?.list ?? []"
:footer-total="overviewData?.specSummaries?.total"
:tax-rate="taxRate"
/>
</div>
<div v-else-if="!loading" class="flex items-center justify-center p-8 text-slate-400">
暂无数据
</div>
</Spin>
</Page>
</template>
<style scoped>
:deep(.product-overview-page-header) {
align-items: stretch;
flex-direction: column;
gap: 10px;
}
@media (min-width: 640px) {
:deep(.product-overview-page-header) {
flex-direction: row;
align-items: center;
}
}
:deep(.product-overview-page-header > div:first-child),
:deep(.product-overview-page-header > div:last-child) {
width: 100%;
}
@media (min-width: 640px) {
:deep(.product-overview-page-header > div:first-child),
:deep(.product-overview-page-header > div:last-child) {
width: auto;
}
}
/* 表格滚动条优化 */
.table-container::-webkit-scrollbar {
height: 6px;
}
.table-container::-webkit-scrollbar-thumb {
background: #e2e8f0;
border-radius: 10px;
}
</style>
<style>
html.dark .product-overview-thead table thead th {
background-color: hsl(240deg 3.7% 15.9% / 80%) !important;
}
html.dark .product-overview-thead table thead th {
border-color: hsl(240deg 3.7% 22%) !important;
}
html.dark .table-container table tbody tr:hover td {
background-color: hsl(217.2deg 32.6% 17.5% / 30%) !important;
}
html.dark .table-container::-webkit-scrollbar-thumb {
background: hsl(240deg 3.7% 22%);
}
html.dark .table-container::-webkit-scrollbar-track {
background: hsl(240deg 3.7% 15.9%);
}
</style>
@@ -0,0 +1,414 @@
<script setup lang="ts">
import type { PromotionFeeTypeVO } from '#/api/ecommerce/promotion-fee-type';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/ecommerce/promotion-fee/types';
import type { ProductVO } from '#/api/ecommerce/product/types';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
TreeSelect,
} from 'ant-design-vue';
import {
createPromotionFeeApi,
updatePromotionFeeApi,
} from '#/api/ecommerce/promotion-fee';
import { getCategoryTreeApi } from '#/api/ecommerce/category';
import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type';
import { getProductPageApi } from '#/api/ecommerce/product';
import { getShopPageApi } from '#/api/ecommerce/shop';
defineOptions({ name: 'PromotionFeeFormModal' });
interface Props {
open: boolean;
promotionFeeData?: null | PromotionFeeVO.Info;
/** 新增时预填店铺(编辑时忽略) */
presetShopId?: number | null;
}
const props = withDefaults(defineProps<Props>(), {
presetShopId: null,
});
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
const emit = defineEmits<Emits>();
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[800px]',
destroyOnClose: false,
onCancel() {
handleCancel();
},
onConfirm() {
handleOk();
},
onOpenChange(isOpen: boolean) {
if (!isOpen) {
emit('update:open', false);
resetFormData();
}
},
});
const formRef = ref();
const isEdit = ref(false);
/** 表单内用 Dayjs,提交时再格式化为 YYYY-MM-DD */
type PromotionFeeFormState = Omit<PromotionFeeDTO.Create, 'feeDate'> & {
feeDate?: Dayjs;
};
const formData = ref<PromotionFeeFormState>({
shopId: undefined as any,
feeTypeId: undefined as any,
categoryId: undefined,
productId: undefined,
campaignName: '',
feeAmount: undefined as any,
feeDate: undefined as any,
remark: '',
});
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
feeTypeId: [
{ required: true, message: '请选择推广费类型', trigger: 'change' },
],
feeAmount: [{ required: true, message: '请输入推广费金额', trigger: 'blur' }],
feeDate: [{ required: true, message: '请选择发生日期', trigger: 'change' }],
} as any;
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 推广费类型列表
const feeTypeList = ref<PromotionFeeTypeVO.Info[]>([]);
const feeTypeListLoading = ref(false);
// 类目树(与商品卡片 TreeSelect 一致:label=name, value=id)
const categoryOptions = ref<any[]>([]);
const categoryTreeLoading = ref(false);
// 商品列表
const productList = ref<ProductVO.Info[]>([]);
const productListLoading = ref(false);
const filteredProductList = computed(() => {
const cid = formData.value.categoryId;
if (cid == null) {
return productList.value;
}
return productList.value.filter((p) => p.categoryId === cid);
});
watch(
() => formData.value.categoryId,
(cid) => {
const pid = formData.value.productId;
if (pid == null || cid == null) {
return;
}
const p = productList.value.find((x) => x.id === pid);
if (p && p.categoryId !== cid) {
formData.value.productId = undefined;
}
},
);
watch(
() => props.open,
async (newVal) => {
if (!newVal) {
modalApi.close();
return;
}
isEdit.value = !!props.promotionFeeData;
if (props.promotionFeeData) {
formData.value = {
shopId: props.promotionFeeData.shopId,
feeTypeId: props.promotionFeeData.feeTypeId,
categoryId: props.promotionFeeData.categoryId,
productId: props.promotionFeeData.productId,
campaignName: props.promotionFeeData.campaignName || '',
feeAmount: props.promotionFeeData.feeAmount,
feeDate: props.promotionFeeData.feeDate
? dayjs(props.promotionFeeData.feeDate)
: undefined,
remark: props.promotionFeeData.remark || '',
};
} else {
resetFormData();
if (props.presetShopId != null && props.presetShopId !== undefined) {
formData.value.shopId = props.presetShopId;
}
}
await nextTick();
modalApi.open();
await nextTick();
formRef.value?.clearValidate?.();
if (props.promotionFeeData?.productId && productList.value.length > 0) {
const p = productList.value.find(
(x) => x.id === props.promotionFeeData!.productId,
);
if (
p?.categoryId != null &&
(formData.value.categoryId == null || formData.value.categoryId === undefined)
) {
formData.value.categoryId = p.categoryId;
}
}
},
);
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
const loadFeeTypeList = async () => {
feeTypeListLoading.value = true;
try {
const response = await getActivePromotionFeeTypeListApi();
feeTypeList.value = response;
} catch (error) {
console.error('加载推广费类型列表失败:', error);
} finally {
feeTypeListLoading.value = false;
}
};
const loadCategoryTree = async () => {
categoryTreeLoading.value = true;
try {
categoryOptions.value = (await getCategoryTreeApi()) ?? [];
} catch (error) {
console.error('加载类目树失败:', error);
categoryOptions.value = [];
} finally {
categoryTreeLoading.value = false;
}
};
const loadProductList = async () => {
productListLoading.value = true;
try {
const response = await getProductPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
productList.value = response.records;
} catch (error) {
console.error('加载商品列表失败:', error);
} finally {
productListLoading.value = false;
}
};
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
feeTypeId: undefined as any,
categoryId: undefined,
productId: undefined,
campaignName: '',
feeAmount: undefined as any,
feeDate: undefined as any,
remark: '',
};
};
/** 发生日期仅表示日历日,格式化为本地 YYYY-MM-DD,避免 JSON 序列化为 UTC ISO 后日期错位 */
const feeDateToApiString = (v: Dayjs) => dayjs(v).format('YYYY-MM-DD');
function productSelectFilterOption(input: string, option?: any) {
const o = filteredProductList.value.find((x) => x.id === option?.value);
return (o?.name ?? '').toLowerCase().includes(input.toLowerCase());
}
const handleOk = async () => {
try {
await formRef.value?.validate();
const feeDate = feeDateToApiString(formData.value.feeDate!);
if (isEdit.value && props.promotionFeeData) {
const updateData: PromotionFeeDTO.Update = {
id: props.promotionFeeData.id,
...formData.value,
feeDate,
};
await updatePromotionFeeApi(updateData);
message.success('更新成功');
} else {
await createPromotionFeeApi({
...formData.value,
feeDate,
});
message.success('创建成功');
}
emit('success');
modalApi.close();
} catch (error) {
console.error('操作失败:', error);
message.error(isEdit.value ? '更新失败' : '创建失败');
}
};
const handleCancel = () => {
emit('cancel');
modalApi.close();
};
onMounted(() => {
loadShopList();
loadFeeTypeList();
loadCategoryTree();
loadProductList();
});
</script>
<template>
<Modal :title="isEdit ? '编辑推广费记录' : '新增推广费记录'">
<Form
ref="formRef"
:model="formData"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="店铺" name="shopId">
<Select
v-model:value="formData.shopId"
placeholder="请选择店铺"
:loading="shopListLoading"
>
<Select.Option
v-for="shop in shopList"
:key="shop.id"
:value="shop.id"
>
{{ shop.name }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="推广费类型" name="feeTypeId">
<Select
v-model:value="formData.feeTypeId"
placeholder="请选择推广费类型"
:loading="feeTypeListLoading"
>
<Select.Option
v-for="feeType in feeTypeList"
:key="feeType.id"
:value="feeType.id"
>
{{ feeType.typeName }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="类目(可选)" name="categoryId">
<TreeSelect
v-model:value="formData.categoryId"
class="w-full"
placeholder="请选择类目(可选,用于类目级推广费或筛选商品)"
:tree-data="categoryOptions"
:field-names="{ label: 'name', value: 'id', children: 'children' }"
:loading="categoryTreeLoading"
allow-clear
tree-default-expand-all
/>
</Form.Item>
<Form.Item label="商品(可选)" name="productId">
<Select
v-model:value="formData.productId"
placeholder="请选择商品(可选;已选类目时仅显示该类目下商品)"
:loading="productListLoading"
allow-clear
show-search
:filter-option="productSelectFilterOption"
>
<Select.Option
v-for="product in filteredProductList"
:key="product.id"
:value="product.id"
>
{{ product.name }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="推广活动名称" name="campaignName">
<Input
v-model:value="formData.campaignName"
placeholder="请输入推广活动名称"
/>
</Form.Item>
<Form.Item label="推广费金额" name="feeAmount">
<InputNumber
v-model:value="formData.feeAmount"
placeholder="请输入推广费金额"
:min="0"
:precision="2"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="发生日期" name="feeDate">
<DatePicker
v-model:value="formData.feeDate"
placeholder="请选择推广费发生日期"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注"
:rows="3"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,502 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type {
PromotionFeeDTO,
PromotionFeeVO,
} from '#/api/ecommerce/promotion-fee/types';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
DatePicker,
Empty,
Flex,
message,
Popconfirm,
Select,
Space,
Spin,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePromotionFeeApi,
getPromotionFeePageApi,
} from '#/api/ecommerce/promotion-fee';
import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import { getAllPromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type/apis';
import PromotionFeeFormModal from './components/PromotionFeeFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'PromotionFeeManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const StoreIcon = createIconifyIcon('lucide:store');
const loading = ref(false);
const shopsLoading = ref(false);
const shops = ref<ShopVO.Info[]>([]);
/** 未选择具体店铺:undefined 表示全部店铺 */
const selectedShopId = ref<number | undefined>(undefined);
const formModalVisible = ref(false);
const currentPromotionFeeData = ref<null | PromotionFeeVO.Info>(null);
const presetShopIdForModal = ref<number | null>(null);
const feeTypeOptions = ref<{ label: string; value: number }[]>([]);
const feeTypeLoading = ref(false);
const feeTypeFetched = ref(false);
async function fetchFeeTypeOptions() {
if (feeTypeFetched.value || feeTypeLoading.value) return;
feeTypeLoading.value = true;
try {
const data = await getAllPromotionFeeTypeListApi();
feeTypeOptions.value = (data || []).map((type: { id: number; typeName: string }) => ({
label: type.typeName,
value: type.id,
}));
feeTypeFetched.value = true;
} catch {
message.error('获取推广费类型失败');
} finally {
feeTypeLoading.value = false;
}
}
const searchForm = ref({
feeTypeId: undefined as number | undefined,
feeDateStart: undefined as string | undefined,
feeDateEnd: undefined as string | undefined,
});
async function loadShops() {
shopsLoading.value = true;
try {
const data = await getShopPageApi({ page: 1, pageSize: 500, filters: {} });
shops.value = data.records ?? [];
} catch {
message.error('获取店铺列表失败');
shops.value = [];
} finally {
shopsLoading.value = false;
}
}
const selectedShopLabel = computed(() => {
if (selectedShopId.value == null) {
return '全部店铺';
}
const s = shops.value.find((x) => x.id === selectedShopId.value);
return s?.name ?? `店铺 #${selectedShopId.value}`;
});
function selectShopAll() {
selectedShopId.value = undefined;
}
function selectShop(id: number) {
selectedShopId.value = id;
}
const gridOptions: VxeGridProps<PromotionFeeVO.Info> = {
columns: [
{
type: 'seq' as const,
minWidth: 56,
title: '序号',
},
{
field: 'shopName',
title: '店铺',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
field: 'categoryName',
title: '类目',
minWidth: 120,
showOverflow: 'tooltip' as const,
slots: { default: 'category' },
},
{
field: 'productName',
title: '商品',
minWidth: 180,
showOverflow: 'tooltip' as const,
slots: { default: 'product' },
},
{
field: 'feeTypeName',
title: '推广费类型',
minWidth: 110,
showOverflow: 'tooltip' as const,
},
{
field: 'campaignName',
title: '推广活动',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
title: '推广费金额',
minWidth: 110,
slots: { default: 'feeAmount' },
},
{
field: 'feeDate',
title: '发生日期',
minWidth: 110,
},
{
title: '操作',
minWidth: 140,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: '100%',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<PromotionFeeDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
shopId: selectedShopId.value,
feeTypeId: searchForm.value.feeTypeId || undefined,
feeDateStart: searchForm.value.feeDateStart || undefined,
feeDateEnd: searchForm.value.feeDateEnd || undefined,
},
};
const data = await getPromotionFeePageApi(params);
return { items: data.records, total: data.total };
} catch {
message.error('获取推广费记录列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
function refreshTable() {
gridApi?.reload();
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '推广记录',
});
watch(selectedShopId, () => {
gridApi.reload();
});
onMounted(() => {
void loadShops();
void fetchFeeTypeOptions();
});
function resetModalPreset() {
presetShopIdForModal.value = null;
}
const handleAdd = () => {
currentPromotionFeeData.value = null;
resetModalPreset();
formModalVisible.value = true;
};
function handleAddForShop(shopId: number) {
selectShop(shopId);
currentPromotionFeeData.value = null;
presetShopIdForModal.value = shopId;
formModalVisible.value = true;
}
const handleEdit = (record: PromotionFeeVO.Info) => {
resetModalPreset();
currentPromotionFeeData.value = record;
formModalVisible.value = true;
};
async function handleDelete(id: number) {
try {
await deletePromotionFeeApi(id);
message.success('删除成功');
refreshTable();
} catch {
message.error('删除失败');
}
}
const handleFormSuccess = () => {
resetModalPreset();
refreshTable();
};
const handleFormCancel = () => {
resetModalPreset();
formModalVisible.value = false;
};
const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
function shopRowClass(id: number | 'all') {
const active =
id === 'all'
? selectedShopId.value === undefined
: selectedShopId.value === id;
const layout =
id === 'all'
? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
: 'group flex w-full cursor-pointer items-center gap-2';
return sidebarListRowClass(active, layout);
}
</script>
<template>
<Page title="推广费管理" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择店铺筛选右侧推广记录;未选店铺时展示全部记录。可在店铺行快捷新增该店铺推广费。
</div>
</template>
<template #extra>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
新增推广费
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0">
<!-- 左:店铺(与 company-menu-manage 一致:Card + h-full + 内部滚动) -->
<Card
class="flex h-full w-[420px] shrink-0 flex-col"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
padding: '12px',
}"
>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<StoreIcon class="h-4 w-4" />
店铺
</span>
</template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div :class="SIDEBAR_LIST_SHELL_CLASS">
<button
type="button"
:class="shopRowClass('all')"
@click="selectShopAll"
>
<span class="min-w-0 flex-1 truncate">全部店铺</span>
<span class="shrink-0 text-xs font-normal text-muted-foreground">
全部记录
</span>
</button>
<Empty
v-if="!shopsLoading && shops.length === 0"
class="py-8"
description="暂无店铺"
/>
<div v-else class="space-y-1">
<div
v-for="shop in shops"
:key="shop.id"
:class="shopRowClass(shop.id)"
class="group w-full"
>
<button
type="button"
class="min-w-0 flex-1 truncate text-left"
@click="selectShop(shop.id)"
>
{{ shop.name }}
</button>
<Button
type="link"
size="small"
class="!h-7 shrink-0 !px-1 !text-xs font-semibold opacity-80 group-hover:opacity-100"
@click.stop="handleAddForShop(shop.id)"
>
<PlusIcon class="mr-0.5 inline h-3.5 w-3.5" />
添加
</Button>
</div>
</div>
</div>
</Spin>
</Card>
<!-- 右:推广记录 -->
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">推广记录</span>
</template>
<template #extra>
<Space wrap size="small" class="max-w-[min(100%,42rem)]">
<Select
v-model:value="searchForm.feeTypeId"
allow-clear
show-search
:options="feeTypeOptions"
:loading="feeTypeLoading"
placeholder="类型"
class="min-w-[120px]"
option-filter-prop="label"
@dropdown-visible-change="
(open: boolean) => open && fetchFeeTypeOptions()
"
@change="() => refreshTable()"
/>
<DatePicker
v-model:value="searchForm.feeDateStart"
value-format="YYYY-MM-DD"
placeholder="开始"
class="w-[118px]"
allow-clear
@change="() => refreshTable()"
/>
<span class="text-muted-foreground">—</span>
<DatePicker
v-model:value="searchForm.feeDateEnd"
value-format="YYYY-MM-DD"
placeholder="结束"
class="w-[118px]"
allow-clear
@change="() => refreshTable()"
/>
</Space>
</template>
<div
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
>
当前:{{ selectedShopLabel }}
</div>
<div class="min-h-0 flex-1 overflow-hidden px-2 pb-2 pt-0 sm:px-3 sm:pb-3">
<Grid :loading="loading" class="h-full min-h-0">
<template #toolbar-tools>
<span class="text-xs text-muted-foreground">
使用上方类型与日期筛选;表格在区域内滚动
</span>
</template>
<template #category="{ row }">
<span>{{ row.categoryName || '—' }}</span>
</template>
<template #feeAmount="{ row }">
<span class="font-semibold text-red-600">
{{ formatAmount(row.feeAmount) }}
</span>
</template>
<template #product="{ row }">
<div>
<div>{{ row.productName || '—' }}</div>
<div
v-if="row.productCode"
class="text-xs text-muted-foreground"
>
{{ row.productCode }}
</div>
</div>
</template>
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这条推广费记录吗?"
@confirm="handleDelete(row.id)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
</div>
</Card>
</Flex>
<PromotionFeeFormModal
v-model:open="formModalVisible"
:promotion-fee-data="currentPromotionFeeData"
:preset-shop-id="presetShopIdForModal"
@success="handleFormSuccess"
@cancel="handleFormCancel"
/>
</Page>
</template>
@@ -0,0 +1,221 @@
<script lang="ts" setup>
import type {
PromotionFeeTypeDTO,
PromotionFeeTypeVO,
} from '#/api/ecommerce/promotion-fee-type';
import { ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
Form,
Input,
InputNumber,
message,
Select,
Switch,
} from 'ant-design-vue';
import {
createPromotionFeeTypeApi,
updatePromotionFeeTypeApi,
} from '#/api/ecommerce/promotion-fee-type';
const emit = defineEmits<{
cancel: [];
success: [];
}>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[600px]',
onCancel() {
close();
},
onConfirm() {
handleSubmit();
},
});
// 响应式数据
const loading = ref(false);
const isEdit = ref(false);
const currentRecord = ref<null | PromotionFeeTypeVO.Info>(null);
// 表单数据
const formData = ref<Partial<PromotionFeeTypeDTO.Create>>({
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
});
// 计算方式选项
const calculationMethodOptions = [
{ label: '固定金额', value: 1 },
{ label: '按比例', value: 2 },
{ label: '按点击', value: 3 },
{ label: '按展示', value: 4 },
];
// 表单验证规则
const rules = {
typeCode: [{ required: true, message: '请输入类型编码', trigger: 'blur' }],
typeName: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
sortOrder: [{ required: true, message: '请输入排序', trigger: 'blur' }],
};
// 表单引用
const formRef = ref();
// 打开模态框
function open(edit: boolean, record?: PromotionFeeTypeVO.Info) {
isEdit.value = edit;
currentRecord.value = record || null;
modalApi.open();
// 根据模式填充表单数据
formData.value =
edit && record
? {
typeName: record.typeName,
description: record.description || '',
calculationMethod: record.calculationMethod || 1,
sortOrder: record.sortOrder || 0,
isActive: record.isActive || 1,
}
: {
typeName: '',
description: '',
calculationMethod: 1,
sortOrder: 0,
isActive: 1,
};
}
// 关闭模态框
function close() {
modalApi.close();
formRef.value?.resetFields();
emit('cancel');
}
// 提交表单
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
if (isEdit.value && currentRecord.value) {
// 更新推广费类型
const updateData: PromotionFeeTypeDTO.Update = {
id: currentRecord.value.id,
typeName: formData.value.typeName!,
description: formData.value.description,
calculationMethod: formData.value.calculationMethod,
sortOrder: formData.value.sortOrder,
isActive: formData.value.isActive,
};
await updatePromotionFeeTypeApi(updateData);
message.success('更新推广费类型成功');
} else {
// 创建推广费类型
const createData: PromotionFeeTypeDTO.Create = {
typeName: formData.value.typeName!,
description: formData.value.description,
calculationMethod: formData.value.calculationMethod,
sortOrder: formData.value.sortOrder,
isActive: formData.value.isActive,
};
await createPromotionFeeTypeApi(createData);
message.success('创建推广费类型成功');
}
emit('success');
close();
} catch (error) {
console.error('提交推广费类型失败:', (error as any).message);
} finally {
loading.value = false;
}
}
// 监听 modal 关闭状态
watch(
() => modalApi.useStore()?.value?.isOpen,
(newVal) => {
if (!newVal) {
formRef.value?.resetFields();
}
},
);
// 暴露方法
defineExpose({
open,
close,
});
</script>
<template>
<Modal
:title="isEdit ? '编辑推广费类型' : '添加推广费类型'"
:confirm-loading="loading"
>
<Form
ref="formRef"
:model="formData"
:rules="rules as any"
layout="vertical"
>
<div class="grid grid-cols-2 gap-4">
<Form.Item label="类型名称" name="typeName">
<Input
v-model:value="formData.typeName"
placeholder="请输入类型名称"
/>
</Form.Item>
</div>
<Form.Item label="类型描述" name="description">
<Input.TextArea
v-model:value="formData.description"
placeholder="请输入类型描述(可选)"
:rows="3"
/>
</Form.Item>
<div class="grid grid-cols-3 gap-4">
<Form.Item label="计算方式" name="calculationMethod">
<Select
v-model:value="formData.calculationMethod"
placeholder="请选择计算方式"
:options="calculationMethodOptions"
/>
</Form.Item>
<Form.Item label="排序" name="sortOrder">
<InputNumber
v-model:value="formData.sortOrder"
placeholder="请输入排序"
style="width: 100%"
:min="0"
/>
</Form.Item>
<Form.Item label="启用状态" name="isActive">
<Switch
v-model:checked="formData.isActive"
:checked-value="1"
:un-checked-value="0"
checked-children="启用"
un-checked-children="禁用"
/>
</Form.Item>
</div>
</Form>
</Modal>
</template>
@@ -0,0 +1,265 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/promotion-fee-type';
import { computed, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
deletePromotionFeeTypeApi,
getAllPromotionFeeTypeListApi,
} from '#/api/ecommerce/promotion-fee-type';
import PromotionFeeTypeFormModal from './components/PromotionFeeTypeFormModal.vue';
defineOptions({ name: 'PromotionFeeTypeConfig' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus');
// 响应式数据
const loading = ref(false);
const promotionFeeTypeFormModalRef = ref();
// 计算方式选项
const calculationMethodOptions = [
{ label: '固定金额', value: 1 },
{ label: '按比例', value: 2 },
{ label: '按点击', value: 3 },
{ label: '按展示', value: 4 },
];
// VbenVxeGrid 表格配置
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
field: 'typeName',
title: '类型名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
field: 'description',
title: '类型描述',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
},
{
title: '计算方式',
minWidth: 'auto',
slots: { default: 'calculationMethod' },
},
{
field: 'sortOrder',
title: '排序',
minWidth: 'auto',
},
{
title: '状态',
minWidth: 'auto',
slots: { default: 'status' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 'auto',
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 'auto',
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: false,
},
// 配置远程加载
proxyConfig: {
ajax: {
query: async () => {
try {
loading.value = true;
const data = await getAllPromotionFeeTypeListApi();
return {
items: data,
total: data.length,
};
} catch (error) {
console.error('获取推广费类型列表失败:', error);
message.error('获取推广费类型列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入类型名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'typeName',
label: '类型名称',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择状态',
options: [
{ label: '启用', value: 1 },
{ label: '禁用', value: 0 },
],
allowClear: true,
onChange: () => gridReloadRef.value?.(),
},
fieldName: 'isActive',
label: '状态',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '推广费用类型配置',
});
gridReloadRef.value = () => gridApi.reload();
// 刷新表格数据
function refreshTable() {
if (gridApi) {
gridApi.reload();
}
}
// 处理添加推广费类型
function handleAdd() {
promotionFeeTypeFormModalRef.value?.open(false);
}
// 处理编辑推广费类型
function handleEdit(record: PromotionFeeTypeVO.Info) {
promotionFeeTypeFormModalRef.value?.open(true, record);
}
// 处理删除推广费类型
async function handleDelete(record: PromotionFeeTypeVO.Info) {
try {
await deletePromotionFeeTypeApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除推广费类型失败:', error);
message.error('删除推广费类型失败');
}
}
// 处理模态框成功
function handleModalSuccess() {
refreshTable();
}
</script>
<template>
<Page title="推广费用类型配置" auto-content-height>
<template #description>
<div class="text-foreground/80 mt-2">
管理推广费用类型,包括费用类型名称、描述、计算方式和启用状态
</div>
</template>
<!-- VbenVxeGrid 表格 -->
<Grid :loading="loading">
<!-- 工具栏工具 -->
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加类型
</Button>
</Space>
</template>
<!-- 计算方式列 -->
<template #calculationMethod="{ row }: { row: any }">
<Tag color="blue">
{{
calculationMethodOptions.find(
(opt) => opt.value === row.calculationMethod,
)?.label || '未设置'
}}
</Tag>
</template>
<!-- 状态列 -->
<template #status="{ row }: { row: any }">
<Tag :color="row.isActive === 1 ? 'green' : 'red'">
{{ row.isActive === 1 ? '启用' : '禁用' }}
</Tag>
</template>
<!-- 操作列 -->
<template #action="{ row }: { row: any }">
<Space>
<Button size="small" @click="handleEdit(row)"> 编辑 </Button>
<Popconfirm
title="确定要删除这个推广费类型吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger> 删除 </Button>
</Popconfirm>
</Space>
</template>
</Grid>
<!-- 推广费类型表单模态框 -->
<PromotionFeeTypeFormModal
ref="promotionFeeTypeFormModalRef"
@success="handleModalSuccess"
/>
</Page>
</template>
@@ -0,0 +1,136 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui';
import { Descriptions, Spin, Tag, message } from 'ant-design-vue';
import { getShopDetailApi } from '#/api/ecommerce/shop';
import {
getPlatformLabel,
getPlatformTagColor,
} from '#/utils/platform-display';
import PddShopDetailModal from '../list/components/PddShopDetailModal.vue';
defineOptions({ name: 'ShopDetails' });
const route = useRoute();
const loading = ref(false);
const shop = ref<null | ShopVO.Info>(null);
const pddShopDetailModalRef = ref<InstanceType<typeof PddShopDetailModal> | null>(
null,
);
const shopId = computed(() => {
const id = route.params.id;
return id ? Number(id) : 0;
});
async function loadDetail() {
if (!shopId.value) {
shop.value = null;
return;
}
try {
loading.value = true;
shop.value = await getShopDetailApi(shopId.value);
} catch (error) {
console.error('获取店铺详情失败:', error);
message.error('获取店铺详情失败');
shop.value = null;
} finally {
loading.value = false;
}
}
function openPddShopDetail() {
const pddShopId = shop.value?.pddShop?.id ?? shop.value?.externalShopId;
if (!pddShopId) {
message.warning('暂无平台店铺信息');
return;
}
pddShopDetailModalRef.value?.open(Number(pddShopId), shop.value?.name);
}
onMounted(loadDetail);
watch(shopId, loadDetail);
</script>
<template>
<Page
:title="shop ? shop.name : shopId ? `店铺详情(#${shopId})` : '店铺详情'"
auto-content-height
content-class="flex min-h-0 flex-1 flex-col bg-[#f8fafc] p-4 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<Spin :spinning="loading">
<div v-if="shop" class="space-y-4 rounded-lg bg-white p-5 dark:bg-[hsl(222.34deg_10.43%_14%)]">
<div class="flex items-start gap-4">
<img
v-if="shop.logo"
:src="shop.logo"
:alt="shop.name"
class="h-20 w-20 rounded-md border border-slate-200 object-cover"
/>
<div class="min-w-0 flex-1 space-y-2">
<div class="text-lg font-semibold">{{ shop.name }}</div>
<div class="flex flex-wrap items-center gap-2">
<Tag
v-if="shop.platformCode"
:color="getPlatformTagColor(shop.platformCode)"
>
{{ getPlatformLabel(shop.platformCode, shop.platformName) }}
</Tag>
<Tag v-else color="default">未设置平台</Tag>
</div>
</div>
</div>
<Descriptions :column="2" bordered size="small" title="基础信息">
<Descriptions.Item label="店铺ID">{{ shop.id }}</Descriptions.Item>
<Descriptions.Item label="平台店铺主键">
{{ shop.externalShopId ?? '-' }}
</Descriptions.Item>
<Descriptions.Item label="创建时间">
{{ shop.createTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="更新时间">
{{ shop.updateTime || '-' }}
</Descriptions.Item>
</Descriptions>
<div v-if="shop.platformCode === 'pdd'">
<Descriptions :column="2" bordered size="small" title="拼多多平台店铺">
<template v-if="shop.pddShop">
<Descriptions.Item label="店铺名称">
<a class="text-primary" @click="openPddShopDetail">
{{ shop.pddShop.mallName || '-' }}
</a>
</Descriptions.Item>
<Descriptions.Item label="mall_id">
{{ shop.pddShop.mallId }}
</Descriptions.Item>
<Descriptions.Item label="授权">
<Tag :color="shop.pddShop.pddAuthId ? 'success' : 'default'">
{{ shop.pddShop.pddAuthId ? '已绑定' : '未绑定' }}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="详情">
<a class="text-primary" @click="openPddShopDetail">查看完整信息</a>
</Descriptions.Item>
</template>
<Descriptions.Item v-else label="绑定状态" :span="2">
未绑定拼多多平台店铺
</Descriptions.Item>
</Descriptions>
</div>
</div>
<div v-else-if="!loading" class="text-slate-500">店铺不存在或暂无数据</div>
</Spin>
<PddShopDetailModal ref="pddShopDetailModalRef" />
</Page>
</template>
@@ -0,0 +1,629 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PddOrderSyncVO } from '#/api/ecommerce/pdd/order-sync';
import type { Dayjs } from 'dayjs';
import { computed, onBeforeUnmount, ref } from 'vue';
import {
Alert,
Button,
Card,
DatePicker,
Descriptions,
Drawer,
Empty,
Form,
List,
Modal,
Progress,
Radio,
Space,
Switch,
Tag,
Typography,
message,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import {
cancelPddFullSyncTaskApi,
createPddFullSyncTaskApi,
getPddFullSyncTaskApi,
getPddIncrementalSyncStatusApi,
listPddFullSyncTasksApi,
resumePddFullSyncTaskApi,
syncPddOrdersIncrementalApi,
togglePddIncrementalSyncApi,
} from '#/api/ecommerce/pdd/order-sync';
import { RealtimeSseEvent } from '#/api/notify/sse';
import { useRealtimeStore } from '#/store';
defineOptions({ name: 'PddOrderSyncDrawer' });
interface Emits {
(e: 'success'): void;
}
const emit = defineEmits<Emits>();
const FULL_SYNC_MAX_CALENDAR_DAYS = 90;
function fullSyncEarliest(): Dayjs {
return dayjs().startOf('day').subtract(FULL_SYNC_MAX_CALENDAR_DAYS - 1, 'day');
}
function fullSyncLatest(): Dayjs {
return dayjs().startOf('day');
}
function disabledFullSyncDate(current: Dayjs) {
if (!current) return false;
const d = current.startOf('day');
return d.isBefore(fullSyncEarliest()) || d.isAfter(fullSyncLatest());
}
const openFlag = ref(false);
const shop = ref<null | ShopVO.Info>(null);
const loading = ref(false);
const listLoading = ref(false);
const incSubmitting = ref(false);
const createSubmitting = ref(false);
const createModalOpen = ref(false);
const createMode = ref<'day' | 'range'>('range');
const confirmDate = ref<Dayjs>(dayjs().startOf('day'));
const range = ref<[Dayjs, Dayjs]>([fullSyncEarliest(), fullSyncLatest()]);
const incremental = ref<null | PddOrderSyncVO.IncrementalStatus>(null);
const fullTasks = ref<PddOrderSyncVO.FullTask[]>([]);
let pollTimer: null | ReturnType<typeof setInterval> = null;
let unsubProgress: (() => void) | null = null;
const terminalNotifiedTaskIds = new Set<number>();
const drawerTitle = computed(() =>
shop.value ? `同步拼多多订单 - ${shop.value.name}` : '同步拼多多订单',
);
const hasActiveFullTask = computed(() =>
fullTasks.value.some((t) => t.status === 'PENDING' || t.status === 'RUNNING'),
);
const incHealthLabel = computed(() => {
const health = incremental.value?.health;
const map: Record<string, string> = {
OFF: '已关闭',
OK: '正常',
LAGGING: '游标滞后',
PAUSED: '出错暂停',
};
return health ? map[health] || health : '-';
});
const incHealthColor = computed(() => {
const health = incremental.value?.health;
if (health === 'PAUSED') return 'error';
if (health === 'LAGGING') return 'warning';
if (health === 'OK') return 'success';
return 'default';
});
function formatTime(time?: null | string) {
if (!time) return '-';
const d = dayjs(time);
return d.isValid() ? d.format('YYYY-MM-DD HH:mm:ss') : '-';
}
function taskProgressPercent(task: PddOrderSyncVO.FullTask) {
if (!task.totalDays) return 0;
return Math.min(100, Math.round((task.doneDays / task.totalDays) * 100));
}
function statusTag(status: string) {
const map: Record<string, { color: string; text: string }> = {
PENDING: { color: 'default', text: '等待中' },
RUNNING: { color: 'processing', text: '执行中' },
SUCCESS: { color: 'success', text: '成功' },
FAILED: { color: 'error', text: '失败' },
CANCELLED: { color: 'warning', text: '已取消' },
};
return map[status] || { color: 'default', text: status };
}
function isTaskActive(task: PddOrderSyncVO.FullTask) {
return task.status === 'PENDING' || task.status === 'RUNNING';
}
function stopPoll() {
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
}
function unsubscribeProgress() {
unsubProgress?.();
unsubProgress = null;
}
function upsertTaskInList(task: PddOrderSyncVO.FullTask) {
const idx = fullTasks.value.findIndex((t) => t.id === task.id);
if (idx === -1) {
fullTasks.value.unshift(task);
} else {
fullTasks.value[idx] = task;
}
}
function applyFullTaskUpdate(task: PddOrderSyncVO.FullTask) {
if (!shop.value || task.shopId !== shop.value.id) {
return;
}
upsertTaskInList(task);
const terminal =
task.status === 'SUCCESS' ||
task.status === 'FAILED' ||
task.status === 'CANCELLED';
if (!terminal) {
return;
}
if (!hasActiveFullTask.value) {
stopPoll();
}
loading.value = false;
if (terminalNotifiedTaskIds.has(task.id)) {
return;
}
terminalNotifiedTaskIds.add(task.id);
if (task.status === 'SUCCESS') {
message.success(`全量任务 #${task.id} 完成:${task.doneDays}/${task.totalDays} 天`);
emit('success');
} else if (task.status === 'FAILED') {
message.error(task.lastError || `全量任务 #${task.id} 失败`);
emit('success');
} else {
message.info(`全量任务 #${task.id} 已取消`);
emit('success');
}
}
function subscribeProgress() {
unsubscribeProgress();
const realtime = useRealtimeStore();
unsubProgress = realtime.on(
RealtimeSseEvent.PDD_ORDER_FULL_SYNC_PROGRESS,
(event) => {
try {
const data = JSON.parse(event.data);
if (data.task) {
applyFullTaskUpdate(data.task as PddOrderSyncVO.FullTask);
}
} catch (error) {
console.error('解析全量同步进度失败:', error);
}
},
);
}
async function loadIncrementalStatus() {
if (!shop.value) return;
try {
incremental.value = await getPddIncrementalSyncStatusApi(shop.value.id);
} catch (error) {
console.error('加载增量状态失败:', error);
}
}
async function loadFullTasks() {
if (!shop.value) return;
try {
listLoading.value = true;
fullTasks.value = await listPddFullSyncTasksApi(shop.value.id, 30);
const active = fullTasks.value.find((t) => isTaskActive(t));
if (active) {
watchActiveTasks();
} else {
stopPoll();
}
} catch (error) {
console.error('加载全量任务列表失败:', error);
} finally {
listLoading.value = false;
}
}
async function handleToggleIncremental(checked: boolean | string | number) {
if (!shop.value) return;
const enabled = !!checked;
const prev = incremental.value;
try {
incremental.value = await togglePddIncrementalSyncApi({
shopId: shop.value.id,
enabled,
});
message.success(enabled ? '已开启增量同步' : '已关闭增量同步');
emit('success');
} catch (error) {
incremental.value = prev;
console.error('切换增量开关失败:', error);
message.error('切换增量开关失败');
}
}
async function handleManualIncremental() {
if (!shop.value) return;
try {
incSubmitting.value = true;
await syncPddOrdersIncrementalApi(shop.value.id);
message.success('已入队,后台增量同步中');
emit('success');
await loadIncrementalStatus();
} catch (error) {
console.error('手动增量失败:', error);
} finally {
incSubmitting.value = false;
}
}
/** SSE 为主,低频轮询活跃任务兜底 */
function watchActiveTasks() {
stopPoll();
subscribeProgress();
pollTimer = setInterval(async () => {
const actives = fullTasks.value.filter((t) => isTaskActive(t));
if (actives.length === 0) {
stopPoll();
return;
}
await Promise.all(
actives.map(async (t) => {
try {
applyFullTaskUpdate(await getPddFullSyncTaskApi(t.id));
} catch (error) {
console.error('轮询全量任务失败:', error);
}
}),
);
}, 10_000);
}
async function handleCancelFull(task: PddOrderSyncVO.FullTask) {
try {
loading.value = true;
applyFullTaskUpdate(await cancelPddFullSyncTaskApi(task.id));
message.success(`已取消全量任务 #${task.id}`);
emit('success');
} catch (error) {
console.error('取消全量任务失败:', error);
message.error('取消全量任务失败');
} finally {
loading.value = false;
}
}
async function handleResumeFull(task: PddOrderSyncVO.FullTask) {
try {
loading.value = true;
terminalNotifiedTaskIds.delete(task.id);
const updated = await resumePddFullSyncTaskApi(task.id);
upsertTaskInList(updated);
message.success(`全量任务 #${task.id} 已续跑入队`);
watchActiveTasks();
} catch (error) {
console.error('续跑全量任务失败:', error);
message.error('续跑全量任务失败');
} finally {
loading.value = false;
}
}
function openCreateModal() {
createMode.value = 'range';
confirmDate.value = fullSyncLatest();
range.value = [fullSyncEarliest(), fullSyncLatest()];
createModalOpen.value = true;
}
async function handleCreateTask() {
if (!shop.value) return;
if (createMode.value === 'day' && !confirmDate.value) {
message.warning('请选择成交日期');
return;
}
if (createMode.value === 'range' && (!range.value?.[0] || !range.value?.[1])) {
message.warning('请选择全量同步日期区间');
return;
}
const dateFromDayjs =
createMode.value === 'day' ? confirmDate.value : range.value[0];
const dateToDayjs =
createMode.value === 'day' ? confirmDate.value : range.value[1];
if (
disabledFullSyncDate(dateFromDayjs) ||
disabledFullSyncDate(dateToDayjs) ||
dateToDayjs.isBefore(dateFromDayjs, 'day')
) {
message.warning('日期须在近 90 天内(含今天),且结束不早于开始');
return;
}
if (hasActiveFullTask.value) {
message.warning('该店铺已有进行中的全量任务,请先等待或取消');
return;
}
try {
createSubmitting.value = true;
const dateFrom =
createMode.value === 'day'
? confirmDate.value.format('YYYY-MM-DD')
: range.value[0].format('YYYY-MM-DD');
const dateTo =
createMode.value === 'day'
? confirmDate.value.format('YYYY-MM-DD')
: range.value[1].format('YYYY-MM-DD');
const task = await createPddFullSyncTaskApi({
shopId: shop.value.id,
dateFrom,
dateTo,
});
terminalNotifiedTaskIds.delete(task.id);
upsertTaskInList(task);
createModalOpen.value = false;
message.success(
createMode.value === 'day'
? '单日全量任务已创建,正在后台执行'
: '全量同步任务已创建,正在后台执行',
);
watchActiveTasks();
emit('success');
} catch (error) {
console.error('创建全量任务失败:', error);
} finally {
createSubmitting.value = false;
}
}
function handleClose() {
stopPoll();
unsubscribeProgress();
createModalOpen.value = false;
openFlag.value = false;
}
async function open(record: ShopVO.Info) {
shop.value = record;
fullTasks.value = [];
incremental.value = null;
loading.value = false;
createSubmitting.value = false;
incSubmitting.value = false;
createModalOpen.value = false;
terminalNotifiedTaskIds.clear();
stopPoll();
subscribeProgress();
openFlag.value = true;
await Promise.all([loadIncrementalStatus(), loadFullTasks()]);
}
onBeforeUnmount(() => {
stopPoll();
unsubscribeProgress();
});
defineExpose({ open, close: handleClose });
</script>
<template>
<Drawer
v-model:open="openFlag"
:title="drawerTitle"
width="600"
destroy-on-close
:mask-closable="!hasActiveFullTask"
@close="handleClose"
>
<Space direction="vertical" :size="16" class="w-full">
<Card size="small">
<template #title>
<Space>
<span>增量同步</span>
<Tag :color="incHealthColor">{{ incHealthLabel }}</Tag>
</Space>
</template>
<Space direction="vertical" :size="12" class="w-full">
<Space wrap align="center">
<Switch
:checked="!!incremental?.enabled"
checked-children="开"
un-checked-children="关"
@change="handleToggleIncremental"
/>
<Typography.Text type="secondary">
开启后定时 Job 拉取增量并转换
</Typography.Text>
<Button
size="small"
type="primary"
ghost
:loading="incSubmitting"
@click="handleManualIncremental"
>
手动增量一次
</Button>
</Space>
<Descriptions bordered size="small" :column="1">
<Descriptions.Item label="游标">
{{ formatTime(incremental?.lastCursorAt) }}
</Descriptions.Item>
<Descriptions.Item label="上次成功">
{{ formatTime(incremental?.lastSuccessTime) }}
</Descriptions.Item>
</Descriptions>
<Alert
v-if="incremental?.lastError"
type="error"
show-icon
:message="incremental.lastError"
/>
<Alert
type="info"
show-icon
message="手动增量按订单更新时间拉取自上次游标以来的变更,用于发货/售后等状态同步。"
/>
</Space>
</Card>
<Card size="small" title="全量同步任务">
<template #extra>
<Space size="small">
<Button size="small" :loading="listLoading" @click="loadFullTasks">
刷新
</Button>
<Button
size="small"
type="primary"
:disabled="hasActiveFullTask"
@click="openCreateModal"
>
创建全量任务
</Button>
</Space>
</template>
<List
v-if="fullTasks.length > 0"
:data-source="fullTasks"
:loading="listLoading"
item-layout="vertical"
size="small"
class="max-h-[52vh] overflow-y-auto"
>
<template #renderItem="{ item: task }">
<List.Item>
<template #actions>
<Button
v-if="isTaskActive(task)"
size="small"
danger
:loading="loading"
@click="handleCancelFull(task)"
>
取消
</Button>
<Button
v-if="task.status === 'FAILED'"
size="small"
type="primary"
:loading="loading"
:disabled="hasActiveFullTask"
@click="handleResumeFull(task)"
>
续跑
</Button>
</template>
<List.Item.Meta>
<template #title>
<Space wrap>
<span>#{{ task.id }}</span>
<Tag :color="statusTag(task.status).color">
{{ statusTag(task.status).text }}
</Tag>
<Typography.Text type="secondary">
{{ task.doneDays }}/{{ task.totalDays }} 天
<template v-if="task.failedDays">
· 失败日 {{ task.failedDays }}
</template>
</Typography.Text>
</Space>
</template>
<template #description>
<div>
区间 {{ task.dateFrom }} ~ {{ task.dateTo }}
<template v-if="task.currentDate">
· 当前 {{ task.currentDate }}
</template>
</div>
<div>
创建 {{ formatTime(task.createTime) }}
<template v-if="task.finishTime">
· 结束 {{ formatTime(task.finishTime) }}
</template>
</div>
</template>
</List.Item.Meta>
<Progress
v-if="isTaskActive(task) || task.status === 'SUCCESS'"
:percent="taskProgressPercent(task)"
size="small"
:status="task.status === 'FAILED' ? 'exception' : undefined"
/>
<Alert
v-if="task.lastError"
class="mt-2"
type="error"
show-icon
:message="task.lastError"
/>
</List.Item>
</template>
</List>
<Empty
v-else
:image="Empty.PRESENTED_IMAGE_SIMPLE"
description="暂无全量任务"
/>
</Card>
</Space>
<template #footer>
<Space class="w-full justify-end">
<Button @click="handleClose">关闭</Button>
</Space>
</template>
</Drawer>
<Modal
v-model:open="createModalOpen"
title="创建全量同步任务"
:confirm-loading="createSubmitting"
ok-text="创建并开始"
destroy-on-close
@ok="handleCreateTask"
>
<Form layout="vertical" class="mt-2">
<Form.Item label="任务类型">
<Radio.Group v-model:value="createMode">
<Radio value="range">按成交日区间</Radio>
<Radio value="day">按成交日单日</Radio>
</Radio.Group>
</Form.Item>
<Form.Item
v-if="createMode === 'range'"
label="成交日期区间"
extra="仅近 90 天(含今天);选到今天时,当日按当前时刻拉取。每天成功后进入转换与 BI"
>
<DatePicker.RangePicker
v-model:value="range"
class="w-full"
:allow-clear="false"
:disabled-date="disabledFullSyncDate"
format="YYYY-MM-DD"
/>
</Form.Item>
<Form.Item
v-else
label="成交日期"
extra="仅近 90 天(含今天);选今天时按当前时刻拉取。若进行中任务已涵盖该日则不会重复创建"
>
<DatePicker
v-model:value="confirmDate"
class="w-full"
:allow-clear="false"
:disabled-date="disabledFullSyncDate"
format="YYYY-MM-DD"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,172 @@
<script lang="ts" setup>
import type { PddShopInfo } from '#/api/ecommerce/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Descriptions, Spin, Tag, message } from 'ant-design-vue';
import { getPddShopDetailApi } from '#/api/ecommerce/pdd/shop';
const MERCHANT_TYPE_MAP: Record<number, string> = {
1: '个人',
2: '企业',
3: '旗舰店',
4: '专卖店',
5: '专营店',
6: '普通店',
};
const MALL_CHARACTER_MAP: Record<number, string> = {
0: '厂商',
1: '分销商',
2: '都不是',
3: '都是',
};
const AUTH_STATUS_MAP: Record<number, { color: string; label: string }> = {
0: { color: 'error', label: '失效' },
1: { color: 'success', label: '正常' },
2: { color: 'default', label: '已撤销' },
};
const loading = ref(false);
const pddShop = ref<null | PddShopInfo>(null);
const internalShopName = ref('');
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[640px]',
showConfirmButton: false,
cancelText: '关闭',
});
const merchantTypeLabel = computed(() => {
const type = pddShop.value?.merchantType;
if (type == null) return '-';
return MERCHANT_TYPE_MAP[type] ?? String(type);
});
const mallCharacterLabel = computed(() => {
const character = pddShop.value?.mallCharacter;
if (character == null) return '-';
return MALL_CHARACTER_MAP[character] ?? String(character);
});
const authStatus = computed(() => {
const status = pddShop.value?.auth?.status;
if (status == null) {
return pddShop.value?.pddAuthId
? { color: 'success', label: '已绑定' }
: { color: 'default', label: '未绑定' };
}
return AUTH_STATUS_MAP[status] ?? { color: 'default', label: String(status) };
});
async function open(pddShopId: number, shopName?: string) {
if (!pddShopId) {
message.warning('暂无外部店铺详情,请先完成授权同步');
return;
}
internalShopName.value = shopName || '';
pddShop.value = null;
modalApi.open();
try {
loading.value = true;
pddShop.value = await getPddShopDetailApi(pddShopId);
} catch (error) {
console.error('获取拼多多店铺详情失败:', error);
message.error('获取拼多多店铺详情失败');
modalApi.close();
} finally {
loading.value = false;
}
}
defineExpose({ open });
</script>
<template>
<Modal title="拼多多外部店铺" content-class="px-5 py-4">
<Spin :spinning="loading">
<div v-if="pddShop" class="space-y-4">
<div class="flex items-center gap-3">
<img
v-if="pddShop.logo"
:src="pddShop.logo"
:alt="pddShop.mallName"
class="h-14 w-14 rounded-md border border-slate-200 object-cover"
/>
<div>
<div class="text-base font-medium">
{{ pddShop.mallName || '-' }}
</div>
<div v-if="internalShopName" class="mt-1 text-xs text-slate-500">
内部店铺:{{ internalShopName }}
</div>
</div>
</div>
<Descriptions :column="1" bordered size="small" title="店铺信息">
<Descriptions.Item label="平台店铺主键">
{{ pddShop.id }}
</Descriptions.Item>
<Descriptions.Item label="mall_id">
{{ pddShop.mallId }}
</Descriptions.Item>
<Descriptions.Item label="店铺类型">
{{ merchantTypeLabel }}
</Descriptions.Item>
<Descriptions.Item label="店铺身份">
{{ mallCharacterLabel }}
</Descriptions.Item>
<Descriptions.Item label="店铺描述">
{{ pddShop.mallDesc || '-' }}
</Descriptions.Item>
<Descriptions.Item label="最近同步">
{{ pddShop.lastSyncTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="创建时间">
{{ pddShop.createTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="更新时间">
{{ pddShop.updateTime || '-' }}
</Descriptions.Item>
</Descriptions>
<Descriptions :column="1" bordered size="small" title="授权信息">
<Descriptions.Item label="授权状态">
<Tag :color="authStatus.color">{{ authStatus.label }}</Tag>
</Descriptions.Item>
<template v-if="pddShop.auth">
<Descriptions.Item label="授权ID">
{{ pddShop.auth.id }}
</Descriptions.Item>
<Descriptions.Item label="owner_id">
{{ pddShop.auth.ownerId || '-' }}
</Descriptions.Item>
<Descriptions.Item label="Token 过期">
{{ pddShop.auth.expiresAt || '-' }}
</Descriptions.Item>
<Descriptions.Item label="Refresh 过期">
{{ pddShop.auth.refreshTokenExpiresAt || '-' }}
</Descriptions.Item>
<Descriptions.Item label="授权时间">
{{ pddShop.auth.createTime || '-' }}
</Descriptions.Item>
<Descriptions.Item label="更新时间">
{{ pddShop.auth.updateTime || '-' }}
</Descriptions.Item>
</template>
<Descriptions.Item v-else label="授权详情">
未绑定授权
</Descriptions.Item>
</Descriptions>
</div>
<div v-else-if="!loading" class="py-8 text-center text-slate-400">
暂无数据
</div>
</Spin>
</Modal>
</template>
@@ -0,0 +1,391 @@
<script lang="ts" setup>
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import { computed, onUnmounted, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, Form, Input, message, Select } from 'ant-design-vue';
import { createShopApi, updateShopApi } from '#/api/ecommerce/shop';
import { getPlatformListApi } from '#/api/ecommerce/platform';
import { uploadFileToOss } from '#/utils/oss-upload';
interface Emits {
(e: 'success'): void;
}
const emit = defineEmits<Emits>();
// 创建 vben modal
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[600px]',
onCancel() {
handleCancel();
},
onConfirm() {
handleSubmit();
},
});
// 创建相机图标组件
const CameraIcon = createIconifyIcon('mdi:camera');
// 内部状态管理
const isEdit = ref(false);
const currentShopData = ref<null | Partial<ShopVO.Info> | ShopVO.Info>(null);
// 响应式数据
const formRef = ref();
const loading = ref(false);
const newLogoFile = ref<File | null>(null); // 新选择的logo文件
const originalLogoUrl = ref(''); // 原始logo URL
const imageLoadError = ref(false); // 图片加载错误状态
// 表单数据
const formData = ref({
name: '',
platformCode: undefined as string | undefined,
logoImageId: undefined as number | undefined,
});
// 平台选项(静态字典)
const platformOptions = ref<{ label: string; value: string }[]>([]);
// 加载平台列表
async function fetchPlatformOptions() {
try {
const data = await getPlatformListApi();
platformOptions.value = data.map((p) => ({
label: p.label,
value: p.code,
}));
} catch (error) {
console.error('获取平台列表失败:', error);
}
}
// 模态框标题
const modalTitle = computed(() => (isEdit.value ? '编辑店铺' : '添加店铺'));
// 当前显示的logo URL(优先显示新选择的)
const currentLogoUrl = computed(() => {
if (newLogoFile.value) {
return URL.createObjectURL(newLogoFile.value);
}
return originalLogoUrl.value;
});
// 初始化表单数据
function initFormData() {
if (isEdit.value && currentShopData.value) {
// 编辑模式
formData.value = {
name: currentShopData.value.name || '',
platformCode: currentShopData.value.platformCode,
logoImageId: undefined,
};
// 设置原始Logo URL
originalLogoUrl.value = currentShopData.value.logo || '';
} else {
// 创建模式 - 如果有传入的shopData,则使用它来初始化表单
formData.value = {
name: currentShopData.value?.name || '',
platformCode: currentShopData.value?.platformCode,
logoImageId: undefined,
};
originalLogoUrl.value = currentShopData.value?.logo || '';
}
// 重置新选择的logo和图片加载状态
newLogoFile.value = null;
imageLoadError.value = false;
}
// 重置表单(在open方法中调用)
function resetForm() {
formRef.value?.resetFields();
newLogoFile.value = null;
originalLogoUrl.value = '';
imageLoadError.value = false;
// 加载平台选项
fetchPlatformOptions();
}
// 处理提交
async function handleSubmit() {
try {
await formRef.value?.validate();
loading.value = true;
// 准备提交数据
const submitData = { ...formData.value };
// 如果有新选择的logo,先上传获取ID
if (newLogoFile.value) {
const logoImageId = await uploadLogoAndGetId();
if (logoImageId) {
submitData.logoImageId = logoImageId;
}
} else if (!isEdit.value) {
// 创建模式且没有选择Logo,移除logoImageId字段
delete submitData.logoImageId;
}
// 调用API
if (
isEdit.value &&
currentShopData.value &&
'id' in currentShopData.value &&
currentShopData.value.id
) {
await updateShopApi(
currentShopData.value.id,
submitData as ShopDTO.Update,
);
message.success('更新成功');
} else {
await createShopApi(submitData as ShopDTO.Create);
message.success('创建成功');
}
emit('success');
modalApi.close();
} catch (error) {
console.error('保存店铺失败:', error);
message.error('保存店铺失败');
} finally {
loading.value = false;
}
}
// 处理取消
function handleCancel() {
modalApi.close();
}
// 暴露给父组件的方法
function open(
editMode: boolean = false,
shopData?: null | Partial<ShopVO.Info> | ShopVO.Info,
) {
isEdit.value = editMode;
currentShopData.value = shopData || null;
resetForm(); // 先重置表单
initFormData(); // 再初始化数据
modalApi.open();
}
// 暴露方法给父组件
defineExpose({
open,
});
// 选择logo文件
function selectLogoFile() {
const input = document.createElement('input');
input.type = 'file';
input.accept = 'image/*';
input.style.display = 'none';
document.body.append(input);
input.addEventListener('change', (e) => {
const file = (e.target as HTMLInputElement).files?.[0];
if (file) {
// 验证文件
const isImage = file.type.startsWith('image/');
if (!isImage) {
message.error('只能上传图片文件');
input.remove();
return;
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
message.error('图片大小不能超过 2MB');
input.remove();
return;
}
// 设置新选择的文件
newLogoFile.value = file;
imageLoadError.value = false; // 重置图片加载错误状态
message.success('Logo选择成功');
}
input.remove();
});
input.click();
}
// 重置新选择的logo
function removeNewLogo() {
newLogoFile.value = null;
imageLoadError.value = false; // 重置图片加载错误状态
message.success('已重置logo');
}
// 上传Logo并获取图片ID
async function uploadLogoAndGetId(): Promise<number | undefined> {
if (!newLogoFile.value) {
return undefined;
}
try {
const fileInfo = await uploadFileToOss(newLogoFile.value, {
category: 'shop-logo',
errorMessage: 'Logo上传失败',
});
return fileInfo.id;
} catch (error) {
console.error('Logo上传失败:', error);
throw error;
}
}
// 图片加载错误处理
function handleImageError(event: Event) {
console.error('图片加载失败:', event);
imageLoadError.value = true;
message.error('图片加载失败,请重新选择');
}
// 组件卸载时清理
onUnmounted(() => {
if (newLogoFile.value) {
const url = URL.createObjectURL(newLogoFile.value);
URL.revokeObjectURL(url);
}
});
</script>
<template>
<Modal
:title="modalTitle"
:confirm-loading="loading"
content-class="px-5 py-4"
>
<Form ref="formRef" :model="formData">
<Form.Item label="店铺Logo" name="logoImageId">
<div style="display: flex; align-items: center; gap: 16px">
<!-- Logo预览区域 -->
<div style="position: relative; display: inline-block">
<!-- 有图片时显示图片 -->
<img
v-if="currentLogoUrl && !imageLoadError"
:src="currentLogoUrl"
alt="店铺Logo"
style="
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 8px;
border: 1px solid #d9d9d9;
background-color: #f5f5f5;
"
@error="handleImageError"
/>
<!-- 无图片或加载失败时显示空状态 -->
<div
v-else
style="
width: 80px;
height: 80px;
border: 1px dashed #d9d9d9;
border-radius: 8px;
background-color: #fafafa;
display: flex;
align-items: center;
justify-content: center;
color: #999;
font-size: 12px;
text-align: center;
line-height: 1.2;
"
>
<div
style="
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div>上传Logo</div>
</div>
</div>
<!-- 点击更换遮罩 -->
<div
style="
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.6);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
"
@mouseenter="($event.target as HTMLElement).style.opacity = '1'"
@mouseleave="($event.target as HTMLElement).style.opacity = '0'"
@click="selectLogoFile"
>
<div
style="
color: white;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
"
>
<CameraIcon style="font-size: 16px; margin-bottom: 4px" />
<div style="font-size: 12px">
{{
currentLogoUrl && !imageLoadError ? '更换Logo' : '上传Logo'
}}
</div>
</div>
</div>
</div>
<!-- 重置按钮 -->
<div v-if="newLogoFile">
<Button size="small" @click="removeNewLogo">重置</Button>
</div>
</div>
</Form.Item>
<Form.Item
label="店铺名称"
name="name"
:rules="[{ required: true, message: '请输入店铺名称' }]"
>
<Input v-model:value="formData.name" placeholder="请输入店铺名称" />
</Form.Item>
<Form.Item label="平台" name="platformCode">
<Select
v-model:value="formData.platformCode"
placeholder="请选择平台"
:options="platformOptions"
allow-clear
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,553 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type { PlatformVO } from '#/api/ecommerce/platform/types';
import type { PddOrderSyncVO } from '#/api/ecommerce/pdd/order-sync';
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getPddAuthorizeUrlApi } from '#/api/ecommerce/pdd/auth';
import { batchPddOrderSyncStatusApi } from '#/api/ecommerce/pdd/order-sync';
import { getPlatformListApi } from '#/api/ecommerce/platform';
import { deleteShopApi, getShopPageApi } from '#/api/ecommerce/shop';
import {
getPlatformLabel,
getPlatformTagColor,
} from '#/utils/platform-display';
import PddOrderSyncDrawer from './components/PddOrderSyncDrawer.vue';
import PddShopDetailModal from './components/PddShopDetailModal.vue';
import ShopFormModal from './components/ShopFormModal.vue';
defineOptions({ name: 'ShopManagement' });
const PLATFORM_CODE_PDD = 'pdd';
const PlusIcon = createIconifyIcon('lucide:plus');
const loading = ref(false);
const authorizing = ref(false);
const shopFormModalRef = ref();
const pddShopDetailModalRef = ref();
const pddOrderSyncDrawerRef = ref();
/** shopId -> 同步摘要 */
const syncStatusMap = ref<Record<number, PddOrderSyncVO.ShopStatus>>({});
const searchForm = ref({
name: '',
platformCode: undefined as string | undefined,
});
const platformOptions = ref<{ label: string; value: string }[]>([]);
let authPollTimer: null | ReturnType<typeof setInterval> = null;
const gridOptions: VxeGridProps<any> = {
columns: [
{
type: 'seq' as const,
width: 80,
title: '序号',
},
{
title: 'Logo',
width: 120,
align: 'center' as const,
showOverflow: false,
slots: { default: 'logo' },
},
{
field: 'name',
title: '店铺名称',
minWidth: 'auto',
showOverflow: 'tooltip' as const,
slots: { default: 'name' },
},
{
field: 'platformName',
title: '平台',
minWidth: 120,
showOverflow: true,
},
{
title: '外部店铺',
minWidth: 180,
align: 'center' as const,
showOverflow: false,
slots: { default: 'externalShop' },
},
{
title: '订单同步',
minWidth: 200,
align: 'center' as const,
showOverflow: false,
slots: { default: 'orderSync' },
},
{
field: 'createTime',
title: '创建时间',
minWidth: 'auto',
},
{
field: 'updateTime',
title: '更新时间',
minWidth: 'auto',
},
{
title: '操作',
minWidth: 320,
fixed: 'right' as const,
showOverflow: false,
slots: { default: 'action' },
},
],
height: 'auto',
border: true,
stripe: true,
rowConfig: {
isHover: true,
height: 88,
},
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<ShopDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
name: searchForm.value.name || undefined,
platformCode: searchForm.value.platformCode,
},
};
const data = await getShopPageApi(params);
await loadSyncStatusForShops(data.records || []);
return {
items: data.records,
total: data.total,
};
} catch (error) {
console.error('获取店铺列表失败:', error);
message.error('获取店铺列表失败');
return {
items: [],
total: 0,
};
} finally {
loading.value = false;
}
},
},
},
};
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Input',
componentProps: {
placeholder: '请输入店铺名称(回车搜索)',
onPressEnter: () => gridReloadRef.value?.(),
},
fieldName: 'name',
label: '店铺名称',
},
{
component: 'Select',
componentProps: {
placeholder: '请选择平台',
options: platformOptions.value,
allowClear: true,
onChange: (val: any) => {
searchForm.value.platformCode = val;
gridReloadRef.value?.();
},
},
fieldName: 'platformCode',
label: '平台',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
formOptions: formOptions.value,
showSearchForm: true,
tableTitle: '店铺管理',
});
gridReloadRef.value = () => gridApi.reload();
async function fetchPlatformOptions() {
try {
const data = await getPlatformListApi();
platformOptions.value = data.map((p: PlatformVO.Meta) => ({
label: p.label,
value: p.code,
}));
await gridApi.formApi?.updateSchema([
{
fieldName: 'platformCode',
componentProps: {
options: platformOptions.value,
},
},
]);
} catch (error) {
console.error('获取平台列表失败:', error);
}
}
async function loadSyncStatusForShops(records: ShopVO.Info[]) {
const pddIds = records
.filter((r) => r.platformCode === PLATFORM_CODE_PDD && hasExternalShop(r))
.map((r) => r.id);
if (pddIds.length === 0) {
syncStatusMap.value = {};
return;
}
try {
const list = await batchPddOrderSyncStatusApi(pddIds);
const map: Record<number, PddOrderSyncVO.ShopStatus> = {};
for (const item of list || []) {
map[item.shopId] = item;
}
syncStatusMap.value = map;
} catch (error) {
console.error('加载订单同步状态失败:', error);
syncStatusMap.value = {};
}
}
function formatRelative(time?: null | string) {
if (!time) return '';
const d = dayjs(time);
if (!d.isValid()) return '';
const mins = dayjs().diff(d, 'minute');
if (mins < 1) return '刚刚';
if (mins < 60) return `${mins} 分钟前`;
const hours = dayjs().diff(d, 'hour');
if (hours < 24) return `${hours} 小时前`;
const days = dayjs().diff(d, 'day');
if (days < 30) return `${days} 天前`;
return d.format('MM-DD');
}
function fullSyncLabel(status?: PddOrderSyncVO.ShopStatus) {
const task = status?.fullTask;
if (!task) return '-';
if (task.status === 'PENDING' || task.status === 'RUNNING') {
return `进行中 ${task.doneDays ?? 0}/${task.totalDays ?? 0}`;
}
if (task.status === 'FAILED') return '失败';
if (task.status === 'CANCELLED') return '已取消';
if (task.status === 'SUCCESS') {
const rel = formatRelative(task.finishTime);
return rel ? `已完成(${rel})` : '已完成';
}
return task.status;
}
function fullSyncColor(status?: PddOrderSyncVO.ShopStatus) {
const s = status?.fullTask?.status;
if (s === 'RUNNING' || s === 'PENDING') return 'processing';
if (s === 'FAILED') return 'error';
if (s === 'SUCCESS') return 'success';
if (s === 'CANCELLED') return 'default';
return 'default';
}
function incSyncLabel(status?: PddOrderSyncVO.ShopStatus) {
const inc = status?.incremental;
if (!inc) return '关';
const health = inc.health || (inc.enabled ? 'OK' : 'OFF');
const map: Record<string, string> = {
OFF: '关',
OK: '开·正常',
LAGGING: '开·滞后',
PAUSED: '开·暂停',
};
const base = map[health] || (inc.enabled ? '开' : '关');
const anchor = inc.lastSuccessTime || inc.lastCursorAt;
const rel = formatRelative(anchor);
return rel ? `${base} · ${rel}` : base;
}
function incSyncColor(status?: PddOrderSyncVO.ShopStatus) {
const health = status?.incremental?.health;
if (health === 'PAUSED') return 'error';
if (health === 'LAGGING') return 'warning';
if (health === 'OK') return 'success';
return 'default';
}
function refreshTable() {
gridApi?.reload();
}
function isPddShop(row: ShopVO.Info) {
return row.platformCode === PLATFORM_CODE_PDD;
}
function hasExternalShop(row: ShopVO.Info) {
return Boolean(row.pddShop || row.externalShopId);
}
function handleAdd() {
shopFormModalRef.value?.open(false);
}
function handleEdit(record: ShopVO.Info) {
shopFormModalRef.value?.open(true, record);
}
async function handleDelete(record: ShopVO.Info) {
try {
await deleteShopApi(record.id);
message.success('删除成功');
refreshTable();
} catch (error) {
console.error('删除店铺失败:', error);
message.error('删除店铺失败');
}
}
function handleModalSuccess() {
refreshTable();
}
function handleViewExternalShop(record: ShopVO.Info) {
const pddShopId = record.pddShop?.id ?? record.externalShopId;
if (!pddShopId) {
message.warning('暂无外部店铺详情,请先完成授权同步');
return;
}
pddShopDetailModalRef.value?.open(Number(pddShopId), record.name);
}
function handleSyncPddOrders(record: ShopVO.Info) {
if (!hasExternalShop(record)) {
message.warning('请先完成拼多多授权绑定后再同步订单');
return;
}
pddOrderSyncDrawerRef.value?.open(record);
}
function clearAuthPoll() {
if (authPollTimer) {
clearInterval(authPollTimer);
authPollTimer = null;
}
}
async function handleAuthorizePdd(record: ShopVO.Info) {
if (authorizing.value) return;
try {
authorizing.value = true;
const data = await getPddAuthorizeUrlApi(record.id);
if (!data?.authorizeUrl) {
message.error('未获取到授权链接');
return;
}
const win = window.open(data.authorizeUrl, '_blank');
if (!win) {
message.warning('浏览器拦截了弹窗,请允许后重试');
return;
}
message.info('请在新窗口完成拼多多授权,完成后将自动刷新列表');
clearAuthPoll();
authPollTimer = setInterval(() => {
if (win.closed) {
clearAuthPoll();
refreshTable();
}
}, 1000);
} catch (error) {
console.error('获取拼多多授权链接失败:', error);
message.error('获取拼多多授权链接失败');
} finally {
authorizing.value = false;
}
}
onMounted(() => {
fetchPlatformOptions();
});
onUnmounted(() => {
clearAuthPoll();
});
</script>
<template>
<Page auto-content-height>
<Grid :loading="loading" class="shop-grid">
<template #toolbar-tools>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon />
添加店铺
</Button>
</Space>
</template>
<template #logo="{ row }: { row: ShopVO.Info }">
<div class="shop-logo-cell flex items-center justify-center">
<img
v-if="row.logo"
:src="row.logo"
:alt="row.name"
class="h-16 w-16 rounded-md border border-slate-200 object-cover dark:border-[hsl(240deg_3.7%_22%)]"
/>
<span
v-else
class="flex h-16 w-16 items-center justify-center rounded-md border border-dashed border-slate-200 text-xs text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)]"
>
暂无
</span>
</div>
</template>
<template #name="{ row }: { row: ShopVO.Info }">
<span>{{ row.name }}</span>
</template>
<template #externalShop="{ row }: { row: ShopVO.Info }">
<div v-if="isPddShop(row)" class="flex flex-col items-center gap-1">
<Tag
v-if="hasExternalShop(row)"
:color="getPlatformTagColor(row.platformCode)"
class="!mr-0 w-fit"
>
{{ getPlatformLabel(row.platformCode, row.platformName) }}
</Tag>
<Tag v-else color="default" class="!mr-0 w-fit">未授权</Tag>
<span
v-if="row.pddShop?.mallName"
class="text-primary cursor-pointer text-center text-xs hover:underline"
@click="handleViewExternalShop(row)"
>
{{ row.pddShop.mallName }}
</span>
<span
v-else-if="row.externalShopId"
class="text-center text-xs text-slate-500"
>
平台店#{{ row.externalShopId }}
</span>
</div>
<span v-else class="text-slate-400">-</span>
</template>
<template #orderSync="{ row }: { row: ShopVO.Info }">
<div
v-if="isPddShop(row) && hasExternalShop(row)"
class="inline-flex cursor-pointer flex-col items-center gap-1"
@click="handleSyncPddOrders(row)"
>
<div class="flex items-center gap-1 text-xs">
<span class="text-slate-500">全量</span>
<Tag :color="fullSyncColor(syncStatusMap[row.id])" class="!mr-0">
{{ fullSyncLabel(syncStatusMap[row.id]) }}
</Tag>
</div>
<div class="flex items-center gap-1 text-xs">
<span class="text-slate-500">增量</span>
<Tag :color="incSyncColor(syncStatusMap[row.id])" class="!mr-0">
{{ incSyncLabel(syncStatusMap[row.id]) }}
</Tag>
</div>
</div>
<span v-else class="text-slate-400">-</span>
</template>
<template #action="{ row }: { row: ShopVO.Info }">
<Space>
<Button
v-if="isPddShop(row) && hasExternalShop(row)"
size="small"
@click="handleSyncPddOrders(row)"
>
同步订单
</Button>
<Button
v-if="isPddShop(row)"
size="small"
type="primary"
ghost
:loading="authorizing"
@click="handleAuthorizePdd(row)"
>
{{ hasExternalShop(row) ? '重新授权' : '授权拼多多' }}
</Button>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这个店铺吗?"
@confirm="handleDelete(row)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
<ShopFormModal ref="shopFormModalRef" @success="handleModalSuccess" />
<PddShopDetailModal ref="pddShopDetailModalRef" />
<PddOrderSyncDrawer ref="pddOrderSyncDrawerRef" @success="handleModalSuccess" />
</Page>
</template>
<style scoped>
:deep(.shop-grid .vxe-body--column) {
vertical-align: middle;
}
.shop-logo-cell {
min-height: 64px;
}
</style>
@@ -0,0 +1,234 @@
<script lang="ts" setup>
import type { ShopDTO, ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { onMounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
Empty,
Input,
message,
Pagination,
Popconfirm,
Spin,
Tag,
} from 'ant-design-vue';
import { deleteShopApi, getShopPageApi } from '#/api/ecommerce/shop';
import { getPlatformListApi } from '#/api/ecommerce/platform/apis';
import type { PlatformVO } from '#/api/ecommerce/platform/types';
import ShopFormModal from '../list/components/ShopFormModal.vue';
defineOptions({ name: 'ShopManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const StoreIcon = createIconifyIcon('lucide:store');
const SearchIcon = createIconifyIcon('lucide:search');
const loading = ref(false);
const shops = ref<ShopVO.Info[]>([]);
const total = ref(0);
const page = ref(1);
const pageSize = ref(20);
const searchName = ref('');
const platformOptions = ref<{ label: string; value: string }[]>([]);
const shopFormModalRef = ref();
async function fetchShops() {
loading.value = true;
try {
const params: PageQueryDTO<ShopDTO.Filters> = {
page: page.value,
pageSize: pageSize.value,
filters: {
name: searchName.value || undefined,
},
};
const data = await getShopPageApi(params);
shops.value = data.records ?? [];
total.value = data.total ?? 0;
} catch {
message.error('获取店铺列表失败');
shops.value = [];
} finally {
loading.value = false;
}
}
function handleAdd() {
shopFormModalRef.value?.open(false);
}
function handleEdit(record: ShopVO.Info) {
shopFormModalRef.value?.open(true, record);
}
async function handleDelete(record: ShopVO.Info) {
try {
await deleteShopApi(record.id);
message.success('删除成功');
void fetchShops();
} catch {
message.error('删除失败');
}
}
function handleModalSuccess() {
void fetchShops();
}
function handleSearch() {
page.value = 1;
void fetchShops();
}
function handlePageChange(p: number) {
page.value = p;
void fetchShops();
}
function handlePageSizeChange(ps: number) {
pageSize.value = ps;
page.value = 1;
void fetchShops();
}
onMounted(async () => {
try {
const platforms = await getPlatformListApi();
platformOptions.value = (platforms ?? []).map((p: PlatformVO.Meta) => ({
label: p.label,
value: p.code,
}));
} catch {
platformOptions.value = [];
}
void fetchShops();
});
</script>
<template>
<Page title="店铺管理" :auto-content-height="true">
<template #extra>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-1 h-4 w-4" />
添加店铺
</Button>
</template>
<div class="flex flex-col gap-4">
<!-- 搜索栏 -->
<Card :body-style="{ padding: '16px' }">
<div class="flex flex-wrap items-center gap-3">
<Input
v-model:value="searchName"
placeholder="搜索店铺名称"
class="!w-[260px]"
allow-clear
@press-enter="handleSearch"
/>
<Button type="primary" ghost @click="handleSearch">
<SearchIcon class="mr-1 h-4 w-4" />
搜索
</Button>
</div>
</Card>
<!-- 卡片网格 -->
<Spin :spinning="loading">
<Empty v-if="!loading && shops.length === 0" description="暂无店铺" class="py-16" />
<div
v-else
class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
>
<Card
v-for="shop in shops"
:key="shop.id"
:body-style="{ padding: 0 }"
class="group overflow-hidden transition-shadow hover:shadow-md"
>
<div class="flex flex-col">
<!-- 顶部标识区 -->
<div class="flex items-center gap-3 bg-gradient-to-r from-blue-50 to-white px-4 py-4 dark:from-blue-950/30 dark:to-transparent">
<div
class="flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-xl bg-white shadow-sm"
>
<img
v-if="shop.logo"
:src="shop.logo"
:alt="shop.name"
class="h-full w-full object-cover"
/>
<StoreIcon v-else class="h-6 w-6 text-blue-500" />
</div>
<div class="min-w-0 flex-1">
<div class="truncate text-base font-bold text-slate-800 dark:text-slate-100">
{{ shop.name }}
</div>
<div class="mt-0.5 text-xs text-slate-500 dark:text-slate-400">
<Tag v-if="shop.platformName" color="blue" class="!mr-0 !text-xs">
{{ shop.platformName }}
</Tag>
<span v-else class="italic">未关联平台</span>
</div>
</div>
</div>
<!-- 信息行 -->
<div class="space-y-2 px-4 py-3">
<div class="flex justify-between text-xs">
<span class="text-slate-500 dark:text-slate-400">店铺ID</span>
<span class="font-mono text-slate-700 dark:text-slate-300">#{{ shop.id }}</span>
</div>
<div class="flex justify-between text-xs">
<span class="text-slate-500 dark:text-slate-400">创建时间</span>
<span class="text-slate-700 dark:text-slate-300">{{ shop.createTime }}</span>
</div>
</div>
<!-- 操作区 -->
<div class="flex items-center justify-end gap-2 border-t border-slate-100 px-4 py-2.5 dark:border-slate-700">
<Button size="small" type="link" @click="handleEdit(shop)">
编辑
</Button>
<Popconfirm
title="确定删除这个店铺?"
@confirm="handleDelete(shop)"
>
<Button size="small" type="link" danger>删除</Button>
</Popconfirm>
</div>
</div>
</Card>
</div>
<!-- 分页 -->
<div v-if="total > 0" class="mt-4 flex justify-center">
<Pagination
:current="page"
:page-size="pageSize"
:total="total"
show-size-changer
:page-size-options="['12', '20', '36', '60']"
@change="handlePageChange"
@show-size-change="
(_current: number, size: number) => {
handlePageSizeChange(size);
}
"
/>
</div>
</Spin>
</div>
<ShopFormModal ref="shopFormModalRef" @success="handleModalSuccess" />
</Page>
</template>
@@ -0,0 +1,283 @@
<script setup lang="ts">
import type {
ShopMonthlyTargetDTO,
ShopMonthlyTargetVO,
} from '#/api/ecommerce/shop-monthly-target';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
DatePicker,
Form,
Input,
InputNumber,
message,
Select,
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { getShopPageApi } from '#/api/ecommerce/shop';
import {
createShopMonthlyTargetApi,
updateShopMonthlyTargetApi,
} from '#/api/ecommerce/shop-monthly-target';
defineOptions({ name: 'ShopMonthlyTargetFormModal' });
// Props
interface Props {
open: boolean;
shopMonthlyTargetData?: null | ShopMonthlyTargetVO.Info;
/** 新增时预填店铺(编辑时忽略) */
presetShopId?: number | null;
}
// Emits
interface Emits {
(e: 'update:open', value: boolean): void;
(e: 'success'): void;
(e: 'cancel'): void;
}
const props = withDefaults(defineProps<Props>(), {
presetShopId: null,
});
const emit = defineEmits<Emits>();
// 创建 vben modal(与父组件 v-model:open 同步 isOpen,避免仅点遮罩关闭时父级仍为 true 导致无法二次打开)
const [Modal, modalApi] = useVbenModal({
draggable: true,
class: 'w-[700px]',
destroyOnClose: false,
onCancel() {
handleCancel();
},
onConfirm() {
handleOk();
},
onOpenChange(isOpen: boolean) {
if (!isOpen) {
emit('update:open', false);
resetFormData();
}
},
});
// 响应式数据
const formRef = ref();
const isEdit = ref(false);
// 表单数据
const formData = ref<ShopMonthlyTargetDTO.Create>({
shopId: undefined as any,
targetMonth: '',
targetAmount: undefined as any,
targetOrderCount: undefined as any,
remark: '',
});
// 目标月份展示值(只读 computed + @update:value 写回,避免与 Form 校验同一 tick 不同步)
const targetMonthForPicker = computed(() => {
if (!formData.value.targetMonth) return undefined;
return dayjs(formData.value.targetMonth);
});
function onTargetMonthChange(val: dayjs.Dayjs | string | undefined) {
if (val === undefined || val === null || val === '') {
formData.value.targetMonth = '';
} else {
const d = dayjs.isDayjs(val) ? val : dayjs(val);
formData.value.targetMonth = d.isValid() ? d.format('YYYY-MM-01') : '';
}
nextTick(() => formRef.value?.clearValidate?.(['targetMonth']));
}
// 表单验证规则
const rules = {
shopId: [{ required: true, message: '请选择店铺', trigger: 'change' }],
targetMonth: [
{ required: true, message: '请选择目标月份', trigger: 'change' },
],
targetAmount: [
{ required: true, message: '请输入目标销售额', trigger: 'blur' },
],
targetOrderCount: [
{ required: true, message: '请输入目标订单数', trigger: 'blur' },
],
} as any;
// 店铺列表
const shopList = ref<ShopVO.Info[]>([]);
const shopListLoading = ref(false);
// 监听props变化
watch(
() => props.open,
async (newVal) => {
if (!newVal) {
modalApi.close();
return;
}
isEdit.value = !!props.shopMonthlyTargetData;
if (props.shopMonthlyTargetData) {
// 编辑模式,填充表单数据
formData.value = {
shopId: props.shopMonthlyTargetData.shopId,
targetMonth: props.shopMonthlyTargetData.targetMonth,
targetAmount: props.shopMonthlyTargetData.targetAmount,
targetOrderCount: props.shopMonthlyTargetData.targetOrderCount,
remark: props.shopMonthlyTargetData.remark || '',
};
} else {
// 新增模式,重置表单数据
resetFormData();
if (props.presetShopId != null && props.presetShopId !== undefined) {
formData.value.shopId = props.presetShopId;
}
}
await nextTick();
modalApi.open();
await nextTick();
formRef.value?.clearValidate?.();
},
);
// 加载店铺列表
const loadShopList = async () => {
shopListLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopList.value = response.records;
} catch (error) {
console.error('加载店铺列表失败:', error);
} finally {
shopListLoading.value = false;
}
};
// 重置表单数据
const resetFormData = () => {
formData.value = {
shopId: undefined as any,
targetMonth: '',
targetAmount: undefined as any,
targetOrderCount: undefined as any,
remark: '',
};
};
// 确认操作
const handleOk = async () => {
try {
await formRef.value?.validate();
if (isEdit.value && props.shopMonthlyTargetData) {
// 更新店铺月销量目标
const updateData: ShopMonthlyTargetDTO.Update = {
targetMonth: formData.value.targetMonth,
targetAmount: formData.value.targetAmount,
targetOrderCount: formData.value.targetOrderCount,
remark: formData.value.remark,
};
await updateShopMonthlyTargetApi(
props.shopMonthlyTargetData.id,
updateData,
);
message.success('更新成功');
} else {
// 创建店铺月销量目标
await createShopMonthlyTargetApi(formData.value);
message.success('创建成功');
}
emit('success');
modalApi.close();
} catch (error) {
console.error('操作失败:', error);
}
};
// 取消操作(关闭与表单重置由 onOpenChange 统一处理,避免重复)
const handleCancel = () => {
emit('cancel');
modalApi.close();
};
// 组件挂载时加载数据
onMounted(() => {
loadShopList();
});
</script>
<template>
<Modal :title="isEdit ? '编辑月销量目标' : '新增月销量目标'">
<Form
ref="formRef"
:model="formData"
:rules="rules"
:label-col="{ span: 6 }"
:wrapper-col="{ span: 18 }"
>
<Form.Item label="店铺" name="shopId" required>
<Select
v-model:value="formData.shopId"
placeholder="请选择店铺"
:loading="shopListLoading"
:options="
shopList.map((shop) => ({
label: shop.name,
value: shop.id,
}))
"
/>
</Form.Item>
<Form.Item label="目标月份" name="targetMonth" required>
<DatePicker
:value="targetMonthForPicker"
placeholder="请选择目标月份"
picker="month"
format="YYYY-MM"
style="width: 100%"
@update:value="onTargetMonthChange"
/>
</Form.Item>
<Form.Item label="目标销售额" name="targetAmount" required>
<InputNumber
v-model:value="formData.targetAmount"
placeholder="请输入目标销售额"
:min="0"
:precision="2"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="目标订单数" name="targetOrderCount" required>
<InputNumber
v-model:value="formData.targetOrderCount"
placeholder="请输入目标订单数"
:min="0"
:precision="0"
style="width: 100%"
/>
</Form.Item>
<Form.Item label="备注" name="remark">
<Input.TextArea
v-model:value="formData.remark"
placeholder="请输入备注(可选)"
:rows="4"
/>
</Form.Item>
</Form>
</Modal>
</template>
@@ -0,0 +1,438 @@
<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';
import type {
ShopMonthlyTargetDTO,
ShopMonthlyTargetVO,
} from '#/api/ecommerce/shop-monthly-target';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common';
import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons';
import {
Button,
Card,
DatePicker,
Empty,
Flex,
message,
Popconfirm,
Space,
Spin,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import {
deleteShopMonthlyTargetApi,
getShopMonthlyTargetPageApi,
} from '#/api/ecommerce/shop-monthly-target';
import ShopMonthlyTargetFormModal from './components/ShopMonthlyTargetFormModal.vue';
import {
SIDEBAR_LIST_SHELL_CLASS,
sidebarListRowClass,
} from '#/utils/sidebar-list-styles';
defineOptions({ name: 'ShopMonthlyTargetManagement' });
const PlusIcon = createIconifyIcon('lucide:plus');
const StoreIcon = createIconifyIcon('lucide:store');
const loading = ref(false);
const shopsLoading = ref(false);
const shops = ref<ShopVO.Info[]>([]);
/** 未选择具体店铺:undefined 表示全部店铺 */
const selectedShopId = ref<number | undefined>(undefined);
const formModalVisible = ref(false);
const currentShopMonthlyTargetData = ref<null | ShopMonthlyTargetVO.Info>(null);
const presetShopIdForModal = ref<number | null>(null);
const searchForm = ref({
startTargetMonth: undefined as string | undefined,
endTargetMonth: undefined as string | undefined,
});
async function loadShops() {
shopsLoading.value = true;
try {
const data = await getShopPageApi({ page: 1, pageSize: 500, filters: {} });
shops.value = data.records ?? [];
} catch {
message.error('获取店铺列表失败');
shops.value = [];
} finally {
shopsLoading.value = false;
}
}
const selectedShopLabel = computed(() => {
if (selectedShopId.value == null) {
return '全部店铺';
}
const s = shops.value.find((x) => x.id === selectedShopId.value);
return s?.name ?? `店铺 #${selectedShopId.value}`;
});
function selectShopAll() {
selectedShopId.value = undefined;
}
function selectShop(id: number) {
selectedShopId.value = id;
}
const gridOptions: VxeGridProps<ShopMonthlyTargetVO.Info> = {
columns: [
{
type: 'seq' as const,
minWidth: 56,
title: '序号',
},
{
field: 'shopName',
title: '店铺名称',
minWidth: 120,
showOverflow: 'tooltip' as const,
},
{
field: 'targetMonth',
title: '目标月份',
minWidth: 110,
},
{
title: '目标销售额',
minWidth: 120,
slots: { default: 'targetAmount' },
},
{
field: 'targetOrderCount',
title: '目标订单数',
minWidth: 100,
},
{
field: 'remark',
title: '备注',
minWidth: 140,
showOverflow: 'tooltip' as const,
},
{
field: 'createTime',
title: '创建时间',
minWidth: 160,
},
{
title: '操作',
minWidth: 140,
fixed: 'right' as const,
slots: { default: 'action' },
},
],
height: '100%',
border: true,
stripe: true,
rowConfig: { isHover: true },
showOverflow: true,
size: 'small',
toolbarConfig: {
custom: true,
refresh: true,
zoom: true,
},
data: [],
pagerConfig: {
enabled: true,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
try {
loading.value = true;
const params: PageQueryDTO<ShopMonthlyTargetDTO.Filters> = {
page: page.currentPage,
pageSize: page.pageSize,
filters: {
shopId: selectedShopId.value,
startTargetMonth: searchForm.value.startTargetMonth || undefined,
endTargetMonth: searchForm.value.endTargetMonth || undefined,
},
};
const data = await getShopMonthlyTargetPageApi(params);
return { items: data.records, total: data.total };
} catch {
message.error('获取店铺月销量目标列表失败');
return { items: [], total: 0 };
} finally {
loading.value = false;
}
},
},
},
};
function refreshTable() {
gridApi?.reload();
}
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
showSearchForm: false,
tableTitle: '月销量目标',
});
watch(selectedShopId, () => {
gridApi.reload();
});
onMounted(() => {
void loadShops();
});
function resetModalPreset() {
presetShopIdForModal.value = null;
}
const handleAdd = () => {
currentShopMonthlyTargetData.value = null;
resetModalPreset();
formModalVisible.value = true;
};
function handleAddForShop(shopId: number) {
selectShop(shopId);
currentShopMonthlyTargetData.value = null;
presetShopIdForModal.value = shopId;
formModalVisible.value = true;
}
const handleEdit = (record: ShopMonthlyTargetVO.Info) => {
resetModalPreset();
currentShopMonthlyTargetData.value = record;
formModalVisible.value = true;
};
async function handleDelete(id: number) {
try {
await deleteShopMonthlyTargetApi(id);
message.success('删除成功');
refreshTable();
} catch {
message.error('删除失败');
}
}
const handleFormSuccess = () => {
resetModalPreset();
refreshTable();
};
const handleFormCancel = () => {
resetModalPreset();
formModalVisible.value = false;
};
const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
function shopRowClass(id: number | 'all') {
const active =
id === 'all'
? selectedShopId.value === undefined
: selectedShopId.value === id;
const layout =
id === 'all'
? 'mb-1.5 flex w-full cursor-pointer items-center gap-2 text-left'
: 'group flex w-full cursor-pointer items-center gap-2';
return sidebarListRowClass(active, layout);
}
</script>
<template>
<Page title="店铺月销量目标管理" :auto-content-height="true">
<template #description>
<div class="text-foreground/80 mt-2">
左侧选择店铺筛选右侧月销量目标记录;未选店铺时展示全部记录。可在店铺行快捷新增该店铺月销量目标。
</div>
</template>
<template #extra>
<Space>
<Button type="primary" @click="handleAdd">
<PlusIcon class="mr-2 h-4 w-4" />
新增月销量目标
</Button>
</Space>
</template>
<Flex gap="middle" class="h-full min-h-0">
<!-- 左:店铺 -->
<Card
class="flex h-full w-[420px] shrink-0 flex-col"
:body-style="{
height: '100%',
display: 'flex',
flexDirection: 'column',
gap: '8px',
minHeight: 0,
padding: '12px',
}"
>
<template #title>
<span class="flex items-center gap-2 text-base font-semibold">
<StoreIcon class="h-4 w-4" />
店铺
</span>
</template>
<Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div :class="SIDEBAR_LIST_SHELL_CLASS">
<button
type="button"
:class="shopRowClass('all')"
@click="selectShopAll"
>
<span class="min-w-0 flex-1 truncate">全部店铺</span>
<span class="shrink-0 text-xs font-normal text-muted-foreground">
全部记录
</span>
</button>
<Empty
v-if="!shopsLoading && shops.length === 0"
class="py-8"
description="暂无店铺"
/>
<div v-else class="space-y-1">
<div
v-for="shop in shops"
:key="shop.id"
:class="shopRowClass(shop.id)"
class="group w-full"
>
<button
type="button"
class="min-w-0 flex-1 truncate text-left"
@click="selectShop(shop.id)"
>
{{ shop.name }}
</button>
<Button
type="link"
size="small"
class="!h-7 shrink-0 !px-1 !text-xs font-semibold opacity-80 group-hover:opacity-100"
@click.stop="handleAddForShop(shop.id)"
>
<PlusIcon class="mr-0.5 inline h-3.5 w-3.5" />
添加
</Button>
</div>
</div>
</div>
</Spin>
</Card>
<!-- 右:月销量目标 -->
<Card
class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
:body-style="{
height: '100%',
minHeight: 0,
padding: 0,
display: 'flex',
flexDirection: 'column',
}"
>
<template #title>
<span class="text-base font-semibold">月销量目标</span>
</template>
<template #extra>
<Space wrap size="small" class="max-w-[min(100%,42rem)]">
<DatePicker
v-model:value="searchForm.startTargetMonth"
picker="month"
value-format="YYYY-MM"
placeholder="开始月份"
class="w-[120px]"
allow-clear
@change="() => refreshTable()"
/>
<span class="text-muted-foreground">—</span>
<DatePicker
v-model:value="searchForm.endTargetMonth"
picker="month"
value-format="YYYY-MM"
placeholder="结束月份"
class="w-[120px]"
allow-clear
@change="() => refreshTable()"
/>
</Space>
</template>
<div
class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
>
当前:{{ selectedShopLabel }}
</div>
<div class="min-h-0 flex-1 overflow-hidden px-2 pb-2 pt-0 sm:px-3 sm:pb-3">
<Grid :loading="loading" class="h-full min-h-0">
<template #toolbar-tools>
<span class="text-xs text-muted-foreground">
使用上方月份筛选;表格在区域内滚动
</span>
</template>
<template #targetAmount="{ row }">
<span class="font-semibold text-red-600">
{{ formatAmount(row.targetAmount) }}
</span>
</template>
<template #action="{ row }">
<Space>
<Button size="small" @click="handleEdit(row)">编辑</Button>
<Popconfirm
title="确定要删除这条月销量目标吗?"
@confirm="handleDelete(row.id)"
>
<Button size="small" danger>删除</Button>
</Popconfirm>
</Space>
</template>
</Grid>
</div>
</Card>
</Flex>
<ShopMonthlyTargetFormModal
v-model:open="formModalVisible"
:shop-monthly-target-data="currentShopMonthlyTargetData"
:preset-shop-id="presetShopIdForModal"
@success="handleFormSuccess"
@cancel="handleFormCancel"
/>
</Page>
</template>
@@ -0,0 +1,269 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import { formatIntCell, formatNumberCell } from '#/utils/overview-table-cells';
import {
formatCurrencyZhFromApi,
formatNumberZhFromApiOptional,
} from '#/utils/shop-overview-display';
import {
salesTaxColumnHint,
overviewTableHints,
} from '#/utils/overview-table-hints';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
interface Props {
data: ShopVO.OverviewStatistics | null;
taxRate: number;
categoryExportMode: boolean;
selectedExportCategoryIds: number[];
categoryExportLoading?: boolean;
}
interface Emits {
(e: 'export-all'): void;
(e: 'export-toggle', enabled: boolean): void;
(e: 'category-select-all', event: Event): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const cellMoneyApi = (v: number | null | undefined) =>
formatNumberCell(v, formatCurrencyZhFromApi);
</script>
<template>
<div
class="overflow-hidden rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div
class="flex flex-col items-start justify-between gap-4 border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white/40 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 md:flex-row md:items-center"
>
<div>
<h3 class="text-xl font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
品类多维度损益汇总
</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
当前时间范围内的品类经营数据汇总,支持按品类导出
</p>
</div>
<div class="flex items-center gap-3">
<template v-if="props.categoryExportMode">
<button
type="button"
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
:disabled="props.categoryExportLoading"
@click="emit('export-toggle', false)"
>
取消选择
</button>
<button
type="button"
class="rounded-2xl bg-blue-600 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 disabled:pointer-events-none disabled:opacity-60 dark:shadow-none"
:disabled="props.categoryExportLoading || props.selectedExportCategoryIds.length === 0"
@click="emit('export-all')"
>
导出已选品类 ({{ props.selectedExportCategoryIds.length }})
</button>
</template>
<template v-else>
<button
type="button"
class="rounded-2xl border border-slate-300 bg-white px-4 py-2 text-sm font-bold text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]"
:disabled="props.categoryExportLoading"
@click="emit('export-toggle', true)"
>
指定品类导出
</button>
<button
type="button"
class="rounded-2xl bg-slate-900 px-8 py-3 text-sm font-bold text-white shadow-xl shadow-slate-200 transition-all hover:scale-105 active:scale-95 disabled:pointer-events-none disabled:opacity-60 dark:shadow-none"
:disabled="props.categoryExportLoading"
@click="emit('export-all')"
>
导出全部
</button>
</template>
</div>
</div>
<div class="table-container max-h-[580px] overflow-x-auto overflow-y-auto">
<table class="w-full whitespace-nowrap text-left text-sm shop-overview-thead">
<thead
class="bg-slate-50 text-xs font-black uppercase tracking-tight text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
style="position: sticky; top: 0; z-index: 20;"
>
<tr>
<th
v-if="props.categoryExportMode"
rowspan="2"
class="border-b border-r border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-slate-50 dark:bg-[hsl(240deg_3.7%_22%/50%)] p-3 text-center"
>
<input
type="checkbox"
:checked="Boolean(props.data?.categoryOverview?.categories?.length) && props.selectedExportCategoryIds.length === (props.data?.categoryOverview?.categories?.length ?? 0)"
:indeterminate="props.selectedExportCategoryIds.length > 0 && props.selectedExportCategoryIds.length < (props.data?.categoryOverview?.categories?.length ?? 0)"
class="h-4 w-4 cursor-pointer accent-blue-600"
@change="emit('category-select-all', $event)"
/>
</th>
<th
rowspan="2"
class="sticky-col border-b px-6 py-6 text-base font-black text-slate-900 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_22%/50%)] dark:text-[hsl(0deg_0%_95%)] border-r-2 border-slate-100 bg-white shadow-sm dark:shadow-none"
:style="props.categoryExportMode ? 'left: 40px' : 'left: 0'"
>
品类名称
</th>
<th colspan="3" class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50)] p-3 text-center">
经营规模维度
</th>
<th colspan="8" class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50)] p-3 text-center italic text-orange-700 dark:text-orange-400">
成本费用维度
</th>
<th colspan="5" class="border-b border-l border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-l-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] p-3 text-center italic text-emerald-700 dark:text-emerald-400">
盈利分析维度
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<th class="border-b border-l dark:border-l-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:bg-[hsl(240deg_3.7%_22%/50%)] dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="overviewTableHints.salesAmount">
实际销售额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_22%/50%)]">
<OverviewColumnHint :title="overviewTableHints.orderCount">单量</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_22%/50%)]">
<OverviewColumnHint :title="overviewTableHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<th class="border-b border-l dark:border-l-[hsl(240deg_3.7%_22%)] px-6 py-4 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-rose-600 dark:bg-[hsl(24deg_9.8%_15%/50%)] dark:text-rose-400">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 dark:bg-[hsl(24deg_9.8%_15%/50%)]">
<OverviewColumnHint :title="overviewTableHints.totalPromotionFee">推广费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-orange-600 dark:bg-[hsl(24deg_9.8%_15%/50%)] dark:text-orange-400">
<OverviewColumnHint :title="overviewTableHints.brushFee">刷单费用</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<OverviewColumnHint :title="overviewTableHints.feeRatioShopCategoryRow">费比 %</OverviewColumnHint>
</th>
<th class="border-b border-l px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="overviewTableHints.totalProfitBeforeTax">
税前盈亏
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
<OverviewColumnHint :title="salesTaxColumnHint(props.taxRate)">
{{ (props.taxRate * 100).toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-black text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="overviewTableHints.roi">ROI</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 px-6 py-4 font-black text-white dark:bg-emerald-600">
<OverviewColumnHint light :title="overviewTableHints.profitAfterTax">
税后盈亏
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="cat in (props.data?.categoryOverview?.categories || [])"
:key="cat.categoryId ?? 'uncategorized'"
class="transition-colors hover:bg-blue-50/50 dark:hover:bg-[hsl(217.2deg_32.6%_17.5%/30%)]"
>
<td
v-if="props.categoryExportMode"
class="border-b border-r border-slate-100 dark:border-b-[hsl(240deg_3.7%_22%)] dark:border-r-[hsl(240deg_3.7%_22%)] bg-white p-3 text-center dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<input
v-model="props.selectedExportCategoryIds"
type="checkbox"
:value="cat.categoryId"
class="h-4 w-4 cursor-pointer accent-blue-600"
/>
</td>
<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%)] p-6 font-bold shadow-sm dark:shadow-none">
<span class="inline-block rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400 transition-colors hover:text-blue-300 hover:underline">
{{ cat.categoryName || '未分类' }}
</span>
</td>
<td class="p-6 font-black">{{ formatCurrencyZhFromApi(cat.salesAmount) }}</td>
<td class="p-6">{{ formatIntCell(cat.orderCount) }}</td>
<td class="p-6">{{ cellMoneyApi(cat.averageOrderValue) }}</td>
<td class="border-l dark:border-l-[hsl(240deg_3.7%_22%)] p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.productCost) }}</td>
<td class="p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.shippingCost) }}</td>
<td class="p-6 text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(cat.orderCost) }}</td>
<td class="border-l dark:border-l-[hsl(240deg_3.7%_22%)] p-6 font-bold text-rose-600 dark:text-rose-400">{{ cellMoneyApi(cat.refundAmount) }}</td>
<td class="p-6 text-amber-600 dark:text-amber-400">{{ cellMoneyApi(cat.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoneyApi(cat.brushFee) }}</td>
<td class="p-6 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ cat.feeRatio !== undefined ? formatFeeRatioPercent(cat.feeRatio) : '-' }}</td>
<td class="border-l border-slate-100 p-6 font-bold dark:border-l-[hsl(240deg_3.7%_22%)]">
{{ cellMoneyApi(cat.totalProfitBeforeTax) }}
</td>
<td class="p-6 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">{{ cellMoneyApi(cat.salesTaxAmount) }}</td>
<td class="p-6 font-black text-indigo-700 dark:text-indigo-400">{{
formatNumberZhFromApiOptional(cat.roi)
}}</td>
<td
class="bg-emerald-50 p-6 text-base font-black dark:bg-emerald-950"
:class="(cat.profitAfterTax ?? 0) < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-300'"
>
{{ cellMoneyApi(cat.profitAfterTax) }}
</td>
</tr>
<tr v-if="!props.data?.categoryOverview?.categories?.length">
<td :colspan="props.categoryExportMode ? 18 : 17" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
</tbody>
<tfoot v-if="props.data?.categoryOverview?.total" class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)]">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td v-if="props.categoryExportMode" class="sticky-col border-r border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] p-6 text-center" style="left: 40px; position: sticky; z-index: 10;"></td>
<td class="sticky-col border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4 text-base font-black" style="left: 0; position: sticky; z-index: 10;">合计</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.salesAmount) }}</td>
<td class="p-6">{{ formatIntCell(props.data.categoryOverview.total.orderCount) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.averageOrderValue) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.productCost) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.shippingCost) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.otherCost) }}</td>
<td class="p-6 font-bold text-orange-800 dark:text-orange-300">{{ cellMoneyApi(props.data.categoryOverview.total.orderCost) }}</td>
<td class="p-6 text-rose-600 dark:text-rose-400">{{ cellMoneyApi(props.data.categoryOverview.total.refundAmount) }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.totalPromotionFee) }}</td>
<td class="p-6 text-orange-600 dark:text-orange-400">{{ cellMoneyApi(props.data.categoryOverview.total.brushFee) }}</td>
<td class="p-6 text-slate-400">{{ props.data.categoryOverview.total.feeRatio !== undefined ? formatFeeRatioPercent(props.data.categoryOverview.total.feeRatio) : '-' }}</td>
<td class="p-6">{{ cellMoneyApi(props.data.categoryOverview.total.totalProfitBeforeTax) }}</td>
<td class="p-6 italic text-slate-400">{{ cellMoneyApi(props.data.categoryOverview.total.salesTaxAmount) }}</td>
<td class="p-6 text-indigo-700 dark:text-indigo-400">{{
formatNumberZhFromApiOptional(props.data.categoryOverview.total.roi)
}}</td>
<td
class="bg-emerald-100 p-6 text-base dark:bg-emerald-950"
:class="(props.data.categoryOverview.total.profitAfterTax ?? 0) < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-800 dark:text-emerald-300'"
>{{ cellMoneyApi(props.data.categoryOverview.total.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
@@ -0,0 +1,123 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { ref, watch } from 'vue';
import { Segmented } from 'ant-design-vue';
import CategoryComparisonTable from './CategoryComparisonTable.vue';
import ProductComparisonTable from './ProductComparisonTable.vue';
defineOptions({ name: 'ProductCategorySwitcher' });
interface Props {
data: ShopVO.OverviewStatistics | null;
taxRate: number;
categoryExportMode: boolean;
selectedExportCategoryIds: number[];
categoryExportLoading?: boolean;
exportLoading?: boolean;
}
interface Emits {
(e: 'export'): void;
(e: 'exportAll'): void;
(e: 'exportToggle', enabled: boolean): void;
(e: 'categorySelectAll', event: Event): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const STORAGE_KEY = 'shop-overview-tab';
const getDefaultMode = (): 'product' | 'category' => {
const stored = localStorage.getItem(STORAGE_KEY);
if (stored === 'product' || stored === 'category') return stored;
return 'product';
};
const activeMode = ref<'product' | 'category'>(getDefaultMode());
watch(activeMode, (val) => localStorage.setItem(STORAGE_KEY, val));
const modeOptions = [
{ label: '商品汇总', value: 'product' },
{ label: '品类汇总', value: 'category' },
];
</script>
<template>
<div class="space-y-4">
<div class="flex justify-end">
<Segmented
v-model:value="activeMode"
:options="modeOptions"
class="comparison-segmented"
/>
</div>
<ProductComparisonTable
v-if="activeMode === 'product'"
:data="props.data"
:tax-rate="props.taxRate"
:export-loading="props.exportLoading"
@export="emit('export')"
/>
<CategoryComparisonTable
v-if="activeMode === 'category'"
:data="props.data"
:tax-rate="props.taxRate"
:category-export-mode="props.categoryExportMode"
:selected-export-category-ids="props.selectedExportCategoryIds"
:category-export-loading="props.categoryExportLoading"
@export-all="emit('exportAll')"
@export-toggle="(enabled) => emit('exportToggle', enabled)"
@category-select-all="(event) => emit('categorySelectAll', event)"
/>
</div>
</template>
<style scoped>
:deep(.ant-segmented-thumb) {
border-radius: 999px !important;
}
:deep(.comparison-segmented) {
background: rgb(148 163 184 / 16%);
border-radius: 999px;
padding: 4px;
}
:deep(.comparison-segmented .ant-segmented-item) {
border-radius: 999px;
}
:deep(.comparison-segmented .ant-segmented-item-label) {
font-weight: 700;
padding: 6px 16px;
border-radius: 999px;
}
:deep(.comparison-segmented .ant-segmented-item-selected) {
background: white;
color: #1d4ed8;
box-shadow: 0 1px 3px rgb(0 0 0 / 10%);
}
:global(html.dark) :deep(.comparison-segmented) {
background: hsl(240deg 3.7% 22% / 70%);
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item) {
border-radius: 999px;
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item) {
color: hsl(240deg 5% 64.9%);
}
:global(html.dark) :deep(.comparison-segmented .ant-segmented-item-selected) {
background: hsl(220deg 13% 18%);
color: #60a5fa;
box-shadow: 0 1px 3px hsl(0 0 0% / 30%);
}
</style>
@@ -0,0 +1,300 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { createIconifyIcon } from '@vben/icons';
import { useRoute, useRouter } from 'vue-router';
import { Button } from 'ant-design-vue';
import dayjs from 'dayjs';
import {
buildOverviewRouteQuery,
getOverviewDateQueryFromLocation,
} from '#/utils/overview-date-range';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import { formatIntCell, formatNumberCell } from '#/utils/overview-table-cells';
import {
formatCurrencyZhFromApi,
formatNumberZhFromApiOptional,
} from '#/utils/shop-overview-display';
import {
salesTaxColumnHint,
overviewTableHints,
} from '#/utils/overview-table-hints';
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
const JumpIcon = createIconifyIcon('tdesign:jump');
interface Props {
data: ShopVO.OverviewStatistics | null;
taxRate: number;
exportLoading?: boolean;
}
interface Emits {
(e: 'export'): void;
}
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
const route = useRoute();
const router = useRouter();
const cellMoneyApi = (v: number | null | undefined) =>
formatNumberCell(v, formatCurrencyZhFromApi);
function currentShopIdFromRoute(): number | undefined {
const id = Number(route.params.id);
return Number.isFinite(id) && id > 0 ? id : undefined;
}
function goToProductOverview(productId: number) {
const dateQ = getOverviewDateQueryFromLocation();
const shopId = currentShopIdFromRoute();
if (dateQ) {
router.push({
path: `/ecom/product/overview/${productId}`,
query: buildOverviewRouteQuery(
[dayjs(dateQ.startDate), dayjs(dateQ.endDate)],
shopId != null ? { shopId } : undefined,
),
});
return;
}
if (shopId != null) {
router.push({
path: `/ecom/product/overview/${productId}`,
query: { shopId: String(shopId) },
});
return;
}
router.push({ path: `/ecom/product/overview/${productId}` });
}
</script>
<template>
<div
class="overflow-hidden rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div
class="flex items-center justify-between border-b border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] bg-white/40 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8"
>
<div>
<h3 class="text-xl font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
核心商品多维度损益汇总表
</h3>
<p class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
横向汇总各商品规模、成本及 ROI 效率
</p>
</div>
<Button
type="primary"
class="!h-auto !rounded-2xl !border-none !bg-slate-900 !px-8 !py-3 !text-sm !font-black !shadow-xl !shadow-slate-200 dark:!shadow-none !transition-all hover:!scale-105 active:!scale-95"
:loading="exportLoading"
@click="emit('export')"
>
导出汇总数据
</Button>
</div>
<div class="max-h-[580px] overflow-auto">
<table class="w-full whitespace-nowrap text-left text-sm shop-overview-thead">
<colgroup>
<col style="width: 220px; min-width: 220px;" />
<col style="width: 140px; min-width: 140px;" />
<col style="width: 100px; min-width: 100px;" />
<col style="width: 110px; min-width: 110px;" />
<col style="width: 130px; min-width: 130px;" />
<col style="width: 100px; min-width: 100px;" />
<col style="width: 110px; min-width: 110px;" />
<col style="width: 120px; min-width: 120px;" />
<col style="width: 120px; min-width: 120px;" />
<col style="width: 120px; min-width: 120px;" />
<col style="width: 110px; min-width: 110px;" />
<col style="width: 100px; min-width: 100px;" />
<col style="width: 110px; min-width: 110px;" />
<col style="width: 130px; min-width: 130px;" />
<col style="width: 120px; min-width: 120px;" />
<col style="width: 140px; min-width: 140px;" />
</colgroup>
<thead
class="bg-slate-50 text-xs font-black uppercase tracking-tight text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
style="position: sticky; top: 0; z-index: 20;"
>
<tr>
<th
rowspan="2"
class="sticky-col z-10 border-b px-6 py-6 text-base font-black text-slate-900 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/80%)] dark:text-[hsl(0deg_0%_95%)]"
style="left: 0"
>
商品
</th>
<th
colspan="3"
class="border-b border-l border-slate-200 dark:border-b dark:border-l dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100/50 dark:bg-[hsl(240deg_3.7%_22%/50)] px-3 py-3 text-center"
>
商品规模 (Scale)
</th>
<th
colspan="7"
class="border-b border-l border-slate-200 dark:border-b dark:border-l dark:border-[hsl(240deg_3.7%_22%)] bg-orange-50/50 dark:bg-[hsl(24deg_9.8%_15%/50)] px-3 py-3 text-center italic text-orange-700 dark:text-orange-400"
>
费用成本 (Costs)
</th>
<th
colspan="5"
class="border-b border-l border-slate-200 dark:border-b dark:border-l dark:border-[hsl(240deg_3.7%_22%)] bg-emerald-50/50 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-3 py-3 text-center italic text-emerald-700"
>
单品损益 (Profitability)
</th>
</tr>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_15.9%/80%)]">
<OverviewColumnHint :title="overviewTableHints.salesAmountShort">
销售额
</OverviewColumnHint>
</th>
<th class="border-b border-l dark:border-l dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.orderCount">单量</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.averageOrderValue">客单价</OverviewColumnHint>
</th>
<th class="border-b border-l dark:border-l dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.productCost">商品成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.shippingCost">运费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.otherCost">其他成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
<OverviewColumnHint :title="overviewTableHints.orderCost">订单成本</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-rose-600">
<OverviewColumnHint :title="overviewTableHints.refundAmount">退款金额</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.totalPromotionFee">推广费</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.brushFee">刷单费用</OverviewColumnHint>
</th>
<th class="border-b border-l dark:border-l dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.feeRatioShopRow">费比 %</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 text-indigo-700 dark:text-indigo-400">
<OverviewColumnHint :title="overviewTableHints.roi">单品 ROI</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4">
<OverviewColumnHint :title="overviewTableHints.totalProfitBeforeTax">税前盈亏</OverviewColumnHint>
</th>
<th class="border-b px-6 py-4 italic text-rose-500 dark:text-rose-400">
<OverviewColumnHint :title="salesTaxColumnHint(props.taxRate)">
{{ (props.taxRate * 100).toFixed(0) }}%税额
</OverviewColumnHint>
</th>
<th class="border-b bg-emerald-600 px-6 py-4 font-black text-white">
<OverviewColumnHint light :title="overviewTableHints.profitAfterTaxNet">
税后净利
</OverviewColumnHint>
</th>
</tr>
</thead>
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
<tr
v-for="product in (data?.productOverview?.products || [])"
:key="product.productId"
class="transition-colors hover:bg-blue-50/30"
>
<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="goToProductOverview(product.productId)"
>
<span class="inline-flex items-center gap-1 rounded-full bg-blue-50 dark:bg-blue-900/30 px-3 py-1 text-sm font-bold text-blue-600 dark:text-blue-400">
{{ product.productName }}
<JumpIcon class="text-xs" />
</span>
<div
v-if="product.productCode"
class="mt-0.5 font-mono text-xs text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
编码: {{ product.productCode }}
</div>
</td>
<td class="px-6 py-4 font-black">{{ formatCurrencyZhFromApi(product.salesAmount) }}</td>
<td class="px-6 py-4 font-medium">{{ formatIntCell(product.orderCount) }}</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.averageOrderValue) }}</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.productCost) }}</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.shippingCost) }}</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.otherCost) }}</td>
<td class="px-6 py-4 font-bold text-orange-800 dark:text-orange-300">
{{ cellMoneyApi(product.orderCost) }}
</td>
<td class="px-6 py-4 font-bold text-rose-500 dark:text-rose-400">
{{ cellMoneyApi(product.refundAmount) }}
</td>
<td class="px-6 py-4">{{ cellMoneyApi(product.totalPromotionFee) }}</td>
<td class="px-6 py-4 text-amber-500 dark:text-amber-400">
{{ cellMoneyApi(product.brushFee) }}
</td>
<td class="px-6 py-4 text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ product.feeRatio !== undefined ? formatFeeRatioPercent(product.feeRatio) : '-' }}
</td>
<td class="px-6 py-4 font-black text-indigo-700 dark:text-indigo-400">
{{ formatNumberZhFromApiOptional(product.roi) }}
</td>
<td class="px-6 py-4 font-bold text-slate-600 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cellMoneyApi(product.totalProfitBeforeTax) }}
</td>
<td class="px-6 py-4 italic text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
{{ cellMoneyApi(product.salesTaxAmount) }}
</td>
<td
class="bg-emerald-50/30 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-6 py-4 text-base font-black"
:class="(product.profitAfterTax ?? 0) < 0 ? 'text-rose-500 dark:text-rose-400' : 'text-emerald-600 dark:text-emerald-400'"
>
{{ cellMoneyApi(product.profitAfterTax) }}
</td>
</tr>
<tr v-if="!data?.productOverview?.products?.length">
<td colspan="16" class="p-8 text-center text-gray-400">
暂无数据
</td>
</tr>
</tbody>
<tfoot v-if="data?.productOverview?.total">
<tr class="font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<td class="sticky-col sticky bottom-0 border-r-2 border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4 text-base font-black" style="left: 0; z-index: 30;">合计</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.salesAmount) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ formatIntCell(data.productOverview.total.orderCount) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.averageOrderValue) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.productCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.shippingCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.otherCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 font-bold text-orange-800 dark:text-orange-300 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.orderCost) }}</td>
<td class="sticky bottom-0 bg-slate-100 text-rose-500 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-rose-400 px-6 py-4">{{ cellMoneyApi(data.productOverview.total.refundAmount) }}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.totalPromotionFee) }}</td>
<td class="sticky bottom-0 bg-slate-100 text-amber-500 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-amber-400 px-6 py-4">{{ cellMoneyApi(data.productOverview.total.brushFee) }}</td>
<td class="sticky bottom-0 bg-slate-100 text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)] px-6 py-4">{{ data.productOverview.total.feeRatio !== undefined ? formatFeeRatioPercent(data.productOverview.total.feeRatio) : '-' }}</td>
<td class="sticky bottom-0 bg-slate-100 text-indigo-700 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-indigo-400 px-6 py-4">{{
formatNumberZhFromApiOptional(data.productOverview.total.roi)
}}</td>
<td class="sticky bottom-0 bg-slate-100 dark:bg-[hsl(240deg_3.7%_22%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.totalProfitBeforeTax) }}</td>
<td class="sticky bottom-0 bg-slate-100 italic text-slate-400 dark:bg-[hsl(240deg_3.7%_22%)] dark:text-[hsl(240deg_5%_64.9%)] px-6 py-4">{{ cellMoneyApi(data.productOverview.total.salesTaxAmount) }}</td>
<td
class="sticky bottom-0 bg-emerald-100 px-6 py-4 text-base dark:bg-emerald-950"
:class="(data.productOverview.total.profitAfterTax ?? 0) < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-emerald-800 dark:text-emerald-300'"
>{{ cellMoneyApi(data.productOverview.total.profitAfterTax) }}</td>
</tr>
</tfoot>
</table>
</div>
</div>
</template>
@@ -0,0 +1,78 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { formatCurrencyZhFromApiOptional } from '#/utils/shop-overview-display';
interface Props {
data: ShopVO.OverviewStatistics | null;
}
defineProps<Props>();
</script>
<template>
<div
class="flex flex-col rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<h3 class="mb-1 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
各商品销量 Top10
</h3>
<p class="mb-5 text-xs font-medium text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
按单量排序,与上方时间范围一致
</p>
<div class="max-h-[380px] flex-1 space-y-2 overflow-y-auto pr-1">
<template v-if="data?.productSalesTop10?.length">
<div
v-for="(row, idx) in data.productSalesTop10"
:key="row.productId ?? `rank-${idx}`"
class="flex items-center gap-3 rounded-xl border border-slate-100/90 bg-slate-50/60 px-3 py-2.5 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/50%)]"
>
<span
class="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg text-sm font-black tabular-nums"
:class="
idx === 0
? 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-200'
: idx === 1
? 'bg-slate-200 text-slate-700 dark:bg-slate-600 dark:text-slate-100'
: idx === 2
? 'bg-orange-100 text-orange-900 dark:bg-orange-900/30 dark:text-orange-200'
: 'bg-slate-100 text-slate-500 dark:bg-slate-700 dark:text-slate-300'
"
>
{{ idx + 1 }}
</span>
<div class="min-w-0 flex-1">
<div
class="truncate text-sm font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
:title="row.productName"
>
{{ row.productName || '-' }}
</div>
<div
v-if="row.productCode"
class="truncate text-[11px] text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
{{ row.productCode }}
</div>
</div>
<div class="shrink-0 text-right">
<div class="text-sm font-black tabular-nums text-indigo-600 dark:text-indigo-400">
{{ row.orderCount != null ? row.orderCount.toLocaleString('zh-CN') : '-' }}
<span class="text-[10px] font-semibold text-slate-400 dark:text-[hsl(240deg_5%_55%)]">单</span>
</div>
<div class="text-[11px] font-semibold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
{{ formatCurrencyZhFromApiOptional(row.salesAmount) }}
</div>
</div>
</div>
</template>
<div
v-else
class="flex flex-1 items-center justify-center py-16 text-sm text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
暂无商品数据
</div>
</div>
</div>
</template>
@@ -0,0 +1,176 @@
<script lang="ts" setup>
import type { EchartsUIType } from '@vben/plugins/echarts';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
import dayjs from 'dayjs';
import { onMounted, onUnmounted, ref, watch } from 'vue';
interface Props {
data: {
salesAmountTrend?: {
dailyDataList: { date: string; value: number }[];
};
orderCountTrend?: {
dailyDataList: { date: string; value: number }[];
};
} | null;
}
const props = defineProps<Props>();
const trendChartRef = ref<EchartsUIType>();
const { renderEcharts: renderTrendChart } = useEcharts(trendChartRef);
const renderChart = () => {
if (!trendChartRef.value || !props.data) return;
const salesTrend = props.data.salesAmountTrend;
const orderTrend = props.data.orderCountTrend;
if (!salesTrend || !orderTrend) return;
const dates = salesTrend.dailyDataList.map((item) =>
dayjs(item.date).format('MM-DD'),
);
const salesData = salesTrend.dailyDataList.map((item) => item.value);
const orderData = orderTrend.dailyDataList.map((item) => item.value);
const isDark = document.documentElement.classList.contains('dark');
renderTrendChart({
grid: {
left: '3%',
right: '3%',
bottom: '3%',
top: '5%',
containLabel: true,
},
tooltip: {
trigger: 'axis',
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
textStyle: {
color: isDark ? 'hsl(0deg 0% 95%)' : '#000',
},
},
xAxis: {
type: 'category',
boundaryGap: false,
data: dates,
axisLine: {
lineStyle: {
color: isDark ? 'hsl(240deg 3.7% 22%)' : '#e2e8f0',
},
},
},
yAxis: [
{
type: 'value',
name: '销售额',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: {
lineStyle: {
type: 'dashed',
color: isDark ? 'hsl(240deg 3.7% 22%)' : undefined,
},
},
},
{
type: 'value',
name: '单量',
position: 'right',
nameTextStyle: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
axisLabel: {
color: isDark ? 'hsl(240deg 5% 64.9%)' : undefined,
},
splitLine: { show: false },
},
],
series: [
{
name: '销售额',
type: 'line',
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#3b82f6' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(59, 130, 246, 0.4)' },
{ offset: 1, color: 'rgba(59, 130, 246, 0)' },
],
},
},
data: salesData,
},
{
name: '日单量',
type: 'line',
yAxisIndex: 1,
smooth: true,
symbol: 'none',
lineStyle: { width: 3, color: '#10b981' },
areaStyle: {
color: {
type: 'linear',
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{ offset: 0, color: 'rgba(16, 185, 129, 0.2)' },
{ offset: 1, color: 'rgba(16, 185, 129, 0)' },
],
},
},
data: orderData,
},
],
});
};
watch(
() => props.data,
() => {
if (props.data) {
setTimeout(() => renderChart(), 100);
}
},
{ deep: true, immediate: true },
);
onMounted(() => {
const darkObserver = new MutationObserver(() => {
if (props.data) renderChart();
});
darkObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
onUnmounted(() => darkObserver.disconnect());
});
defineExpose({ renderChart });
</script>
<template>
<div class="rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-8 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px] xl:col-span-2">
<h3 class="mb-6 text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
销售额与单量趋势分析
</h3>
<div class="h-[380px] w-full">
<EchartsUI ref="trendChartRef" />
</div>
</div>
</template>
@@ -0,0 +1,164 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { formatFeeRatioPercent } from '#/utils/overview-fee-ratio';
import {
formatCurrencyZhFromApi,
formatNumberZhFromApiOptional,
} from '#/utils/shop-overview-display';
interface Props {
data: ShopVO.OverviewStatistics | null;
loading?: boolean;
}
defineProps<Props>();
const formatPercentPlain = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value.toFixed(1)}%`;
};
const formatPercent = (value: number | undefined) => {
if (value === undefined) return '-';
return `${value > 0 ? '+' : ''}${value.toFixed(1)}%`;
};
</script>
<template>
<div class="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-4">
<!-- 销售大盘 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 flex items-start justify-between">
<span class="text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
店铺销售总额
</span>
<span
v-if="data?.monthOverMonthGrowth !== undefined"
class="rounded bg-emerald-50 dark:bg-[hsl(142deg_71.8%_29%/20%)] px-2 py-1 text-xs font-bold text-emerald-600 dark:text-emerald-400"
>
增长率 {{ formatPercent(data.monthOverMonthGrowth) }}
</span>
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{
data?.totalSalesAmount != null
? formatCurrencyZhFromApi(data.totalSalesAmount)
: '-'
}}
</div>
<div
v-if="data?.salesAmountAchievementRate !== undefined"
class="mt-6 flex items-center justify-between border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-xs font-bold"
>
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">销售额目标达成</span>
<span class="font-black text-blue-600 dark:text-blue-400">
{{ formatPercentPlain(data.salesAmountAchievementRate) }}
</span>
</div>
</div>
<!-- 订单达成 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
订单总量与达成
</div>
<div class="text-4xl font-black leading-none text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
{{ data?.totalOrderCount?.toLocaleString('zh-CN') || '-' }}
<span class="ml-1 text-sm font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">单</span>
</div>
<div v-if="data?.orderCountAchievementRate !== undefined" class="mt-6">
<div class="mb-2 flex justify-between text-[10px] font-black text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
<span>
目标:
{{ data.totalTargetOrderCount?.toLocaleString('zh-CN') || '-' }} 单
</span>
<span>
达成率:
{{ formatPercentPlain(data.orderCountAchievementRate) }}
</span>
</div>
<div class="h-2 w-full overflow-hidden rounded-full bg-slate-100">
<div
class="h-full bg-indigo-500 transition-all duration-1000"
:style="{ width: `${Math.min(data.orderCountAchievementRate || 0, 100)}%` }"
></div>
</div>
</div>
</div>
<!-- 推广效率 -->
<div
class="flex flex-col justify-between rounded-[20px] border border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
投资回报率 (ROI)
</div>
<div class="text-4xl font-black leading-none text-indigo-600 dark:text-indigo-400">
{{ formatNumberZhFromApiOptional(data?.totalROI) }}
</div>
<div
v-if="data?.averageFeeRatio !== undefined"
class="mt-6 space-y-2 border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4"
>
<div class="flex justify-between text-xs font-bold">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">平均费比</span>
<span class="text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
{{ formatFeeRatioPercent(data.averageFeeRatio) }}
</span>
</div>
</div>
</div>
<!-- 利润汇总 -->
<div
class="flex flex-col justify-between rounded-[20px] border-l-4 border-slate-200/80 dark:border-[hsl(240deg_3.7%_22%)] border-l-emerald-500 dark:border-l-emerald-500 bg-white/85 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-6 shadow-[0_4px_20px_rgba(0,0,0,0.02)] dark:shadow-none backdrop-blur-[12px]"
>
<div class="mb-4 text-xs font-black uppercase tracking-widest text-emerald-600 dark:text-emerald-400">
店铺总净利润 (税后)
</div>
<div class="text-4xl font-black leading-none text-emerald-600 dark:text-emerald-400">
{{
data?.totalNetProfitAfterTax != null
? formatCurrencyZhFromApi(data.totalNetProfitAfterTax)
: '-'
}}
</div>
<div
v-if="data"
class="mt-6 flex justify-between gap-4 border-t border-slate-100 dark:border-[hsl(240deg_3.7%_22%)] pt-4 text-[11px] font-bold"
>
<div class="min-w-0 flex flex-col gap-0.5">
<span class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">税前总盈亏</span>
<span
:class="
(data.totalProfitBeforeTax ?? 0) >= 0
? 'text-emerald-600 dark:text-emerald-400'
: 'text-rose-600 dark:text-rose-400'
"
>
{{
data.totalProfitBeforeTax != null
? formatCurrencyZhFromApi(data.totalProfitBeforeTax)
: '-'
}}
</span>
</div>
<div class="shrink-0 text-right">
<div class="text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">税额</div>
<div class="text-rose-500 dark:text-rose-400">
{{
data.totalTaxAmount != null
? `-${formatCurrencyZhFromApi(data.totalTaxAmount)}`
: '-'
}}
</div>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,367 @@
<script lang="ts" setup>
import { computed, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { DatePicker, InputNumber, Popover, Select, Spin } from 'ant-design-vue';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
import {
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState,
overviewToolbarPanelClass,
overviewToolbarShellClass,
} from '../../../styles/overview-toolbar-classes';
interface ShopSelectOption {
label: string;
value: string;
}
interface Props {
modelValue: {
taxRate: number;
activeTimeRange:
| '7days'
| '30days'
| 'thisMonth'
| 'custom'
| 'today'
| 'yesterday';
customDateRange: [Dayjs, Dayjs] | undefined;
dateRange: [Dayjs, Dayjs];
};
/** 当前店铺 ID(与路由 params.id 一致) */
shopId?: number;
shopOptions?: ShopSelectOption[];
shopListLoading?: boolean;
}
interface Emits {
(e: 'update:modelValue', val: Props['modelValue']): void;
(e: 'shop-change', shopId: number): void;
(e: 'shop-search', keyword: string): void;
(e: 'shop-popup-scroll', event: Event): void;
(e: 'shop-dropdown-visible-change', open: boolean): void;
}
const props = withDefaults(defineProps<Props>(), {
shopOptions: () => [],
shopListLoading: false,
});
const emit = defineEmits<Emits>();
const openPopover = ref<string | null>(null);
function handlePopoverOpen(name: string, open: boolean) {
if (open) {
openPopover.value = name;
} else if (openPopover.value === name) {
openPopover.value = null;
}
}
const ReceiptIcon = createIconifyIcon('lucide:receipt');
const ShopIcon = createIconifyIcon('lucide:store');
const CalendarIcon = createIconifyIcon('lucide:calendar');
const selectedShopName = computed(() => {
const id = props.shopId;
if (id == null || id <= 0) return '选择店铺';
const opt = props.shopOptions?.find((o) => o.value === String(id));
return opt?.label ?? `店铺 #${id}`;
});
const timeRangeLabel = computed(() => {
const t = props.modelValue.activeTimeRange;
if (t === 'today') return '今日';
if (t === 'yesterday') return '昨日';
if (t === '7days') return '近7日';
if (t === '30days') return '近30日';
if (t === 'thisMonth') return '本月';
if (props.modelValue.customDateRange) {
return `${props.modelValue.customDateRange[0].format('M/D')}-${props.modelValue.customDateRange[1].format('M/D')}`;
}
return '日期';
});
const handleShopSelectChange = (value: unknown) => {
const id = Number(value);
if (!Number.isFinite(id) || id <= 0) return;
emit('shop-change', id);
};
const TAX_RATE_KEY = 'overview-tax-rate';
const formatTaxRate = (value: null | number | string | undefined) => {
if (value === null || value === undefined || value === '') return '';
const num = Number(value);
if (!Number.isFinite(num)) return '';
return `${Math.round(num * 100 * 1e10) / 1e10}%`;
};
const parseTaxRate = (value: string | undefined) => {
if (!value) return 0;
const num = Number(value.replace('%', '').trim());
return Number.isFinite(num) ? num / 100 : 0;
};
const switchTimeRange = (
type: '7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday',
) => {
let startDate: Dayjs;
let endDate: 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 (props.modelValue.customDateRange) {
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: props.modelValue.customDateRange,
});
}
return;
case 'today':
startDate = dayjs();
endDate = dayjs();
break;
case 'yesterday':
startDate = dayjs().subtract(1, 'day');
endDate = dayjs().subtract(1, 'day');
break;
}
const newRange: [Dayjs, Dayjs] = [startDate, endDate];
emit('update:modelValue', {
...props.modelValue,
activeTimeRange: type,
dateRange: newRange,
customDateRange: newRange,
});
};
const handleCustomDateRangeChange = (
value: [Dayjs, Dayjs] | [string, string] | null,
dateStrings?: [string, string],
) => {
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) => {
const num = typeof val === 'string' ? parseTaxRate(val) : val ?? 0.04;
localStorage.setItem(TAX_RATE_KEY, String(num));
emit('update:modelValue', {
...props.modelValue,
taxRate: num,
});
};
</script>
<template>
<div
class="overview-header-extra flex w-full max-w-full flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:gap-2"
>
<!-- 税率 -->
<Popover
trigger="click"
:open="openPopover === 'taxRate'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('taxRate', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex items-center gap-2 whitespace-nowrap">
<span class="shrink-0 text-xs font-bold text-slate-700 dark:text-slate-300">
税率
</span>
<InputNumber
:value="props.modelValue.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-transparent !text-center !text-sm !font-bold !text-slate-800 !shadow-none dark:!text-slate-100"
:formatter="formatTaxRate"
:parser="parseTaxRate"
@change="handleTaxRateChange"
/>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<ReceiptIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">税率{{ formatTaxRate(props.modelValue.taxRate) }}</span>
</div>
</div>
</Popover>
<!-- 店铺 -->
<Popover
trigger="click"
:open="openPopover === 'shop'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('shop', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex items-center gap-2 px-2 py-0.5" style="min-width: 200px;">
<span
class="w-9 shrink-0 text-right text-xs font-bold text-slate-700 dark:text-slate-300"
>
店铺
</span>
<Select
:value="props.shopId != null && props.shopId > 0 ? String(props.shopId) : undefined"
size="small"
show-search
:filter-option="false"
:loading="props.shopListLoading"
:options="props.shopOptions"
placeholder="选择店铺"
:dropdown-match-select-width="false"
class="overview-header-select overview-shop-select min-w-0 flex-1"
@change="handleShopSelectChange"
@search="(kw: string) => emit('shop-search', kw)"
@popup-scroll="(e: Event) => emit('shop-popup-scroll', e)"
@dropdown-visible-change="
(open: boolean) => emit('shop-dropdown-visible-change', open)
"
>
<template #notFoundContent>
<div v-if="props.shopListLoading" class="py-3 text-center">
<Spin size="small" />
<div class="mt-1 text-xs text-slate-600">加载中...</div>
</div>
<div v-else class="py-3 text-center text-xs text-slate-600">暂无店铺</div>
</template>
</Select>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<ShopIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">{{ selectedShopName }}</span>
</div>
</div>
</Popover>
<!-- 时间范围 -->
<Popover
trigger="click"
:open="openPopover === 'timeRange'"
placement="bottom"
@update:open="(val: boolean) => handlePopoverOpen('timeRange', val)"
overlay-class-name="workbench-toolbar-popover"
>
<template #content>
<div class="flex flex-col gap-2 px-1 py-0.5">
<div class="flex items-center gap-1 overflow-x-auto whitespace-nowrap">
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'today'),
]"
@click="switchTimeRange('today')"
>
今日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'yesterday'),
]"
@click="switchTimeRange('yesterday')"
>
昨日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === '7days'),
]"
@click="switchTimeRange('7days')"
>
近7日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === '30days'),
]"
@click="switchTimeRange('30days')"
>
近30日
</button>
<button
type="button"
:class="[
overviewTimeRangeBtnClass,
overviewTimeRangeBtnState(props.modelValue.activeTimeRange === 'thisMonth'),
]"
@click="switchTimeRange('thisMonth')"
>
本月
</button>
</div>
<div class="flex items-center gap-2">
<span
class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300"
>
自定义日期
</span>
<DatePicker.RangePicker
:value="props.modelValue.customDateRange"
size="small"
format="YYYY-MM-DD"
:allow-clear="false"
:placeholder="['开始', '结束']"
class="overview-header-range-picker !h-8 !w-full !border-none !bg-transparent !text-sm !font-bold !text-slate-800 sm:!w-[220px] dark:!text-slate-200"
@change="handleCustomDateRangeChange"
/>
</div>
</div>
</template>
<div :class="[overviewToolbarShellClass, 'cursor-pointer']">
<div
:class="[overviewToolbarPanelClass, 'flex items-center gap-1 px-2 py-1']"
>
<CalendarIcon class="h-4 w-4 shrink-0" />
<span class="whitespace-nowrap text-xs font-bold text-slate-700 dark:text-slate-300">{{ timeRangeLabel }}</span>
</div>
</div>
</Popover>
</div>
</template>
<style src="../../../styles/overview-toolbar.css"></style>
<style src="../../../styles/overview-header-select.css"></style>
@@ -0,0 +1,477 @@
<script lang="ts" setup>
import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { Dayjs } from 'dayjs';
import {
computed,
onActivated,
onMounted,
onUnmounted,
ref,
watch,
} from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Page } from '@vben/common-ui';
import { message, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getShopOverviewApi, getShopPageApi } from '#/api/ecommerce/shop/apis';
import { exportByPost } from '#/utils/export';
import {
applyOverviewDateRangeFromUrl,
buildOverviewRouteQuery,
syncOverviewDateRangeToUrl,
} from '#/utils/overview-date-range';
import TimeRangeBar from './components/TimeRangeBar.vue';
import StatCards from './components/StatCards.vue';
import SalesTrendChart from './components/SalesTrendChart.vue';
import ProductSalesTop10Panel from './components/ProductSalesTop10Panel.vue';
import ProductCategorySwitcher from './components/ProductCategorySwitcher.vue';
defineOptions({ name: 'ShopOverview' });
const route = useRoute();
const router = useRouter();
const SHOP_PAGE_SIZE = 20;
const shops = ref<ShopVO.Info[]>([]);
const shopsLoading = ref(false);
const shopPage = ref(1);
const shopTotal = ref(0);
const shopSearchKeyword = ref('');
let shopSearchTimer: ReturnType<typeof setTimeout> | undefined;
/** 当前是否为店铺概览路由(keep-alive 下 route.params.id 会随其它标签变化,不可仅凭 id 请求) */
const isShopOverviewRoute = () =>
/\/ecom\/shop\/overview\/[^/]+\/?$/.test(route.path);
// 店铺ID(从路由参数获取)
const shopId = computed(() => {
if (!isShopOverviewRoute()) return 0;
const id = route.params.id;
return id ? Number(id) : 0;
});
// 响应式数据
const loading = ref(false);
const exportLoading = ref(false);
const overviewData = ref<null | ShopVO.OverviewStatistics>(null);
const shopSelectOptions = computed(() => {
const opts = shops.value.map((s) => ({
label: s.name,
value: String(s.id),
}));
const id = shopId.value;
if (id > 0 && !opts.some((o) => o.value === String(id))) {
const name = overviewData.value?.shopName ?? `店铺 #${id}`;
return [{ label: name, value: String(id) }, ...opts];
}
return opts;
});
// 品类导出相关
const categoryExportMode = ref(false);
const selectedExportCategoryIds = ref<number[]>([]);
const categoryExportLoading = ref(false);
// 日期范围(默认:本月至今日)
const dateRange = ref<[Dayjs, Dayjs]>([
dayjs().startOf('month'),
dayjs(),
]);
// 当前选中的时间范围类型
const activeTimeRange = ref<
'7days' | '30days' | 'thisMonth' | 'custom' | 'today' | 'yesterday'
>('thisMonth');
// 自定义日期范围
const customDateRange = ref<[Dayjs, Dayjs] | undefined>([
dateRange.value[0],
dateRange.value[1],
]);
const lastRequestKey = ref('');
const isRequesting = ref(false);
// 税率(持久化)
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, () => {
loadOverviewData();
});
// 时间范围状态(传递给子组件)
const timeRangeState = computed(() => ({
taxRate: taxRate.value,
activeTimeRange: activeTimeRange.value,
customDateRange: customDateRange.value,
dateRange: dateRange.value,
}));
// 监听子组件的时间范围变化
const handleTimeRangeChange = async (val: typeof timeRangeState.value) => {
taxRate.value = val.taxRate;
activeTimeRange.value = val.activeTimeRange;
customDateRange.value = val.customDateRange;
dateRange.value = val.dateRange;
// 手动切换时间时清除请求缓存,确保强制刷新
lastRequestKey.value = '';
syncDateRangeToRouteQuery();
await refreshOverviewByCurrentParams();
};
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);
};
async function fetchShopList(page = 1, append = false) {
if (shopsLoading.value) return;
shopsLoading.value = true;
try {
const keyword = shopSearchKeyword.value.trim();
const data = await getShopPageApi({
page,
pageSize: SHOP_PAGE_SIZE,
filters: keyword ? { name: keyword } : {},
});
const records = data.records ?? [];
shops.value = append ? [...shops.value, ...records] : records;
shopTotal.value = data.total ?? 0;
shopPage.value = page;
} catch {
message.error('店铺列表加载失败');
} finally {
shopsLoading.value = false;
}
}
function handleShopSearch(keyword: string) {
if (shopSearchTimer) clearTimeout(shopSearchTimer);
shopSearchTimer = setTimeout(() => {
shopSearchKeyword.value = keyword;
void fetchShopList(1, false);
}, 300);
}
function handleShopPopupScroll(e: Event) {
const target = e.target as HTMLElement;
const { scrollTop, scrollHeight, clientHeight } = target;
if (scrollHeight - scrollTop - clientHeight < 50) {
const hasMore = shopPage.value * SHOP_PAGE_SIZE < shopTotal.value;
if (hasMore && !shopsLoading.value) {
void fetchShopList(shopPage.value + 1, true);
}
}
}
function handleShopDropdownVisibleChange(open: boolean) {
if (!open) return;
shopSearchKeyword.value = '';
void fetchShopList(1, false);
}
function handleShopChange(nextShopId: number) {
if (!nextShopId || nextShopId === shopId.value) return;
lastRequestKey.value = '';
router.push({
path: `/ecom/shop/overview/${nextShopId}`,
query: buildOverviewRouteQuery(dateRange.value),
});
}
// 加载概览数据
const loadOverviewData = async () => {
if (!isShopOverviewRoute() || !shopId.value) return;
if (isRequesting.value) return;
isRequesting.value = true;
try {
loading.value = true;
const [startDate, endDate] = dateRange.value;
overviewData.value = await getShopOverviewApi({
shopId: shopId.value,
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
taxRate: taxRate.value,
});
} catch (err: any) {
overviewData.value = null;
message.error(err?.message || '加载店铺概览失败');
} finally {
loading.value = false;
isRequesting.value = false;
}
};
// 导出汇总数据
const handleExportShopOverview = async () => {
if (!shopId.value) return;
try {
exportLoading.value = true;
const shopName = overviewData.value?.shopName || `店铺${shopId.value}`;
const [startDate, endDate] = dateRange.value;
const safeName = String(shopName).replace(/[/\\:*?"<>|]/g, '_');
const filename = `${safeName}_按商品汇总统计_${startDate.format('YYYYMMDD')}-${endDate.format('YYYYMMDD')}.xlsx`;
await exportByPost(
'/bi/shop/export/summary-by-product',
{
shopId: shopId.value,
dateRange: [
startDate.format('YYYY-MM-DD'),
endDate.format('YYYY-MM-DD'),
],
taxRate: taxRate.value,
},
filename,
);
} finally {
exportLoading.value = false;
}
};
// 品类导出相关
const handleCategoryExportToggle = (enabled: boolean) => {
categoryExportMode.value = enabled;
if (enabled) selectedExportCategoryIds.value = [];
};
const handleCategoryExport = async () => {
try {
categoryExportLoading.value = true;
const params: {
categoryIds?: number[];
dateRange: string[];
taxRate: number;
shopId: number;
} = {
dateRange: dateRange.value.map((d) => d.format('YYYY-MM-DD')),
taxRate: taxRate.value,
shopId: shopId.value,
};
if (selectedExportCategoryIds.value.length > 0) {
params.categoryIds = selectedExportCategoryIds.value;
}
const [catStart, catEnd] = dateRange.value;
const catShopName = overviewData.value?.shopName || `店铺${shopId.value}`;
const catSafeName = String(catShopName).replace(/[/\\:*?"<>|]/g, '_');
await exportByPost(
'/bi/shop/export/summary-by-category',
params,
`${catSafeName}_按品类汇总统计_${catStart.format('YYYYMMDD')}-${catEnd.format('YYYYMMDD')}.xlsx`,
);
} finally {
categoryExportLoading.value = false;
}
};
const handleCategorySelectAllChange = (event: Event) => {
const target = event.target as HTMLInputElement | null;
if (!target) return;
selectedExportCategoryIds.value = target.checked
? (overviewData.value?.categoryOverview?.categories?.map((c: ShopVO.CategorySummary) => c.categoryId) ?? [])
: [];
};
const refreshOverviewByCurrentParams = async (force = false) => {
if (!isShopOverviewRoute()) return;
applyDateRangeFromRouteQuery();
if (!shopId.value) return;
const requestKey = `${shopId.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();
};
// 监听路由变化(仅在本页路径下响应,避免切到商品概览等仍用当前 id 请求店铺接口)
watch(
() => [
route.path,
route.params.id,
route.query.startDate,
route.query.endDate,
],
async () => {
if (!isShopOverviewRoute()) return;
await refreshOverviewByCurrentParams();
},
);
// 初始化
onMounted(async () => {
if (!isShopOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
onUnmounted(() => {
if (shopSearchTimer) clearTimeout(shopSearchTimer);
});
onActivated(async () => {
if (!isShopOverviewRoute()) return;
await refreshOverviewByCurrentParams(true);
});
</script>
<template>
<Page
auto-content-height
class="bg-[#f8fafc] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
header-class="shop-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="w-full max-w-full sm:w-auto">
<TimeRangeBar
:model-value="timeRangeState"
:shop-id="shopId"
:shop-options="shopSelectOptions"
:shop-list-loading="shopsLoading"
@update:model-value="handleTimeRangeChange"
@shop-change="handleShopChange"
@shop-search="handleShopSearch"
@shop-popup-scroll="handleShopPopupScroll"
@shop-dropdown-visible-change="handleShopDropdownVisibleChange"
/>
</div>
</template>
<Spin :spinning="loading">
<div class="mx-auto w-full space-y-6">
<!-- 第一层:核心统计卡片 -->
<StatCards :data="overviewData" :loading="loading" />
<!-- 第二层:趋势与销量榜 -->
<div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
<SalesTrendChart :data="overviewData" />
<ProductSalesTop10Panel :data="overviewData" />
</div>
<!-- 第三层:商品/品类多维度损益汇总表 -->
<ProductCategorySwitcher
:data="overviewData"
:tax-rate="taxRate"
:category-export-mode="categoryExportMode"
:selected-export-category-ids="selectedExportCategoryIds"
:category-export-loading="categoryExportLoading"
:export-loading="exportLoading"
@export="handleExportShopOverview"
@export-all="handleCategoryExport"
@export-toggle="handleCategoryExportToggle"
@category-select-all="handleCategorySelectAllChange"
/>
</div>
</Spin>
</Page>
</template>
<style scoped>
:deep(.shop-overview-page-header) {
align-items: stretch;
flex-direction: column;
gap: 10px;
}
@media (min-width: 640px) {
:deep(.shop-overview-page-header) {
flex-direction: row;
align-items: center;
}
}
:deep(.shop-overview-page-header > div:first-child),
:deep(.shop-overview-page-header > div:last-child) {
width: 100%;
}
@media (min-width: 640px) {
:deep(.shop-overview-page-header > div:first-child),
:deep(.shop-overview-page-header > div:last-child) {
width: auto;
}
}
</style>
<style>
html.dark .shop-overview-thead table thead th {
background-color: hsl(240deg 3.7% 15.9% / 80%) !important;
}
html.dark .shop-overview-thead table thead th {
border-color: hsl(240deg 3.7% 22%) !important;
}
</style>
@@ -0,0 +1,113 @@
/* 概览页头部 Select:与工作台 workbench-header-select 样式、配色一致 */
.overview-header-select {
min-width: 0;
width: 100%;
}
.overview-header-select .ant-select-selector {
border-radius: 0.75rem !important;
border: none !important;
font-weight: 700;
font-size: 0.875rem !important;
line-height: 1.25rem !important;
min-height: 2.125rem !important;
display: flex !important;
align-items: center !important;
padding-inline: 10px 28px !important;
background-color: rgb(255 255 255 / 0.92) !important;
box-shadow: none !important;
}
.overview-header-select.ant-select-single
.ant-select-selector
.ant-select-selection-item,
.overview-header-select.ant-select-single
.ant-select-selector
.ant-select-selection-placeholder {
line-height: 1.25rem !important;
color: rgb(15 23 42) !important;
}
.overview-header-select .ant-select-selection-wrap {
position: relative !important;
display: flex !important;
align-items: center !important;
flex: 1 1 auto !important;
min-width: 0 !important;
min-height: 1.25rem;
align-self: center !important;
}
.overview-header-select .ant-select-selection-search {
position: absolute !important;
inset-inline-start: 10px !important;
inset-inline-end: 28px !important;
top: 50% !important;
bottom: auto !important;
transform: translateY(-50%) !important;
display: flex !important;
align-items: center !important;
height: 1.25rem !important;
margin-inline-start: 0 !important;
}
.overview-header-select .ant-select-selection-search-input {
height: 1.25rem !important;
line-height: 1.25rem !important;
padding: 0 !important;
margin: 0 !important;
vertical-align: middle !important;
color: rgb(15 23 42) !important;
}
.overview-header-select.overview-shop-select .ant-select-selector,
.overview-header-select.overview-product-select .ant-select-selector {
height: auto !important;
min-height: 2.125rem !important;
align-items: center !important;
padding-block: 6px !important;
padding-inline: 10px 28px !important;
}
.overview-header-select.overview-shop-select .ant-select-arrow,
.overview-header-select.overview-product-select .ant-select-arrow {
top: 50% !important;
margin-top: 0 !important;
transform: translateY(-50%) !important;
color: rgb(100 116 139) !important;
}
.overview-header-select.overview-shop-select.ant-select-single
.ant-select-selector
.ant-select-selection-item,
.overview-header-select.overview-shop-select.ant-select-single
.ant-select-selector
.ant-select-selection-placeholder,
.overview-header-select.overview-product-select.ant-select-single
.ant-select-selector
.ant-select-selection-item,
.overview-header-select.overview-product-select.ant-select-single
.ant-select-selector
.ant-select-selection-placeholder {
white-space: normal !important;
word-break: break-word !important;
overflow: visible !important;
text-overflow: clip !important;
line-height: 1.35 !important;
align-self: center !important;
}
html.dark .overview-header-select .ant-select-selector {
background-color: hsl(240deg 3.7% 18%) !important;
}
html.dark .overview-header-select.ant-select-single .ant-select-selector .ant-select-selection-item,
html.dark .overview-header-select.ant-select-single .ant-select-selector .ant-select-selection-placeholder,
html.dark .overview-header-select .ant-select-selection-search-input {
color: hsl(0deg 0% 95%) !important;
}
html.dark .overview-header-select .ant-select-arrow,
html.dark .overview-header-select .ant-select-clear {
color: hsl(240deg 5% 64.9%) !important;
}
@@ -0,0 +1,18 @@
/** 概览页顶部工具栏(与工作台 #extra 一致) */
export const overviewToolbarShellClass =
'flex w-full flex-col gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 p-1.5 sm:w-auto sm:flex-row sm:items-center sm:gap-2 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]';
export const overviewToolbarPanelClass =
'overview-toolbar-panel rounded-xl bg-white dark:bg-[hsl(222.34deg_10.43%_14%)]';
export const overviewToolbarLabelClass =
'text-xs font-bold text-slate-700 dark:text-slate-300';
export const overviewTimeRangeBtnClass =
'inline-flex min-w-0 cursor-pointer items-center justify-center rounded-xl border-0 px-3 py-2 text-sm font-bold transition-colors sm:px-5';
export function overviewTimeRangeBtnState(active: boolean) {
return active
? 'bg-slate-100 text-blue-600 shadow-sm dark:bg-blue-900/30 dark:text-blue-400'
: 'bg-transparent text-slate-800 hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-[hsl(240deg_3.7%_22%)]';
}
@@ -0,0 +1,62 @@
/* 概览页头部工具栏:税率、日期选择器等(与工作台 workbench-header-extra 一致) */
.overview-header-extra .tax-rate-input.ant-input-number {
background: transparent !important;
border: none !important;
box-shadow: none !important;
}
.overview-header-extra .tax-rate-input .ant-input-number-input {
height: 32px;
line-height: 32px;
padding-top: 0;
padding-bottom: 0;
color: rgb(15 23 42);
background: transparent !important;
}
.overview-header-extra .tax-rate-input:hover .ant-input-number-input {
background-color: rgb(241 245 249) !important;
}
.overview-header-extra .overview-header-range-picker .ant-picker-input > input {
color: rgb(15 23 42) !important;
font-weight: 700;
}
.overview-header-extra .overview-header-range-picker .ant-picker-separator,
.overview-header-extra .overview-header-range-picker .ant-picker-suffix {
color: rgb(71 85 105);
}
.overview-toolbar-panel .overview-header-select .ant-select-selector {
min-height: 2rem !important;
padding-inline: 8px 28px !important;
background-color: transparent !important;
box-shadow: none !important;
}
.overview-toolbar-panel .overview-header-select:hover .ant-select-selector {
background-color: rgb(241 245 249) !important;
}
html.dark .overview-header-extra .tax-rate-input .ant-input-number-input,
html.dark .overview-header-extra .overview-header-range-picker .ant-picker-input > input {
color: hsl(0deg 0% 95%) !important;
}
html.dark .overview-header-extra .overview-header-range-picker .ant-picker-separator,
html.dark .overview-header-extra .overview-header-range-picker .ant-picker-suffix {
color: hsl(240deg 5% 75%);
}
html.dark .overview-header-extra .tax-rate-input:hover .ant-input-number-input {
background-color: hsl(240deg 3.7% 22%) !important;
}
html.dark .overview-toolbar-panel .overview-header-select .ant-select-selector {
background-color: transparent !important;
}
html.dark .overview-toolbar-panel .overview-header-select:hover .ant-select-selector {
background-color: hsl(240deg 3.7% 22%) !important;
}