refactor(shop-monthly-target): 重构为左侧店铺列表+右侧表格的两栏布局

This commit is contained in:
小蟑螂
2026-05-17 00:11:05 +08:00
parent b725107bc2
commit d766859a3e
2 changed files with 259 additions and 169 deletions
@@ -27,14 +27,12 @@ import {
defineOptions({ name: 'ShopMonthlyTargetFormModal' }); defineOptions({ name: 'ShopMonthlyTargetFormModal' });
const props = defineProps<Props>();
const emit = defineEmits<Emits>();
// Props // Props
interface Props { interface Props {
open: boolean; open: boolean;
shopMonthlyTargetData?: null | ShopMonthlyTargetVO.Info; shopMonthlyTargetData?: null | ShopMonthlyTargetVO.Info;
/** 新增时预填店铺(编辑时忽略) */
presetShopId?: number | null;
} }
// Emits // Emits
@@ -44,6 +42,12 @@ interface Emits {
(e: 'cancel'): void; (e: 'cancel'): void;
} }
const props = withDefaults(defineProps<Props>(), {
presetShopId: null,
});
const emit = defineEmits<Emits>();
// 创建 vben modal(与父组件 v-model:open 同步 isOpen,避免仅点遮罩关闭时父级仍为 true 导致无法二次打开) // 创建 vben modal(与父组件 v-model:open 同步 isOpen,避免仅点遮罩关闭时父级仍为 true 导致无法二次打开)
const [Modal, modalApi] = useVbenModal({ const [Modal, modalApi] = useVbenModal({
draggable: true, draggable: true,
@@ -131,6 +135,9 @@ watch(
} else { } else {
// 新增模式,重置表单数据 // 新增模式,重置表单数据
resetFormData(); resetFormData();
if (props.presetShopId != null && props.presetShopId !== undefined) {
formData.value.shopId = props.presetShopId;
}
} }
await nextTick(); await nextTick();
modalApi.open(); modalApi.open();
@@ -7,15 +7,25 @@ import type {
import type { ShopVO } from '#/api/ecommerce/shop/types'; import type { ShopVO } from '#/api/ecommerce/shop/types';
import type { PageQueryDTO } from '#/types/common'; import type { PageQueryDTO } from '#/types/common';
import { computed, ref } from 'vue'; import { computed, onMounted, ref, watch } from 'vue';
import { Page } from '@vben/common-ui'; import { Page } from '@vben/common-ui';
import { createIconifyIcon } from '@vben/icons'; import { createIconifyIcon } from '@vben/icons';
import { Button, message, Popconfirm, Space } from 'ant-design-vue'; import {
Button,
Card,
DatePicker,
Empty,
Flex,
message,
Popconfirm,
Space,
Spin,
} from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table'; import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getShopPageApi } from '#/api/ecommerce/shop'; import { getShopPageApi } from '#/api/ecommerce/shop/apis';
import { import {
deleteShopMonthlyTargetApi, deleteShopMonthlyTargetApi,
getShopMonthlyTargetPageApi, getShopMonthlyTargetPageApi,
@@ -25,74 +35,101 @@ import ShopMonthlyTargetFormModal from './components/ShopMonthlyTargetFormModal.
defineOptions({ name: 'ShopMonthlyTargetManagement' }); defineOptions({ name: 'ShopMonthlyTargetManagement' });
// 创建图标组件
const PlusIcon = createIconifyIcon('lucide:plus'); const PlusIcon = createIconifyIcon('lucide:plus');
const StoreIcon = createIconifyIcon('lucide:store');
// 响应式数据
const loading = ref(false); 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 formModalVisible = ref(false);
const currentShopMonthlyTargetData = ref<null | ShopMonthlyTargetVO.Info>(null); const currentShopMonthlyTargetData = ref<null | ShopMonthlyTargetVO.Info>(null);
const presetShopIdForModal = ref<number | null>(null);
// 搜索表单
const searchForm = ref({ const searchForm = ref({
shopId: undefined as number | undefined,
startTargetMonth: undefined as string | undefined, startTargetMonth: undefined as string | undefined,
endTargetMonth: undefined as string | undefined, endTargetMonth: undefined as string | undefined,
}); });
// 店铺选项(懒加载) async function loadShops() {
const shopOptions = ref<{ label: string; value: number }[]>([]); shopsLoading.value = true;
const shopLoading = ref(false); try {
const shopFetched = ref(false); const data = await getShopPageApi({ page: 1, pageSize: 500, filters: {} });
shops.value = data.records ?? [];
} catch {
message.error('获取店铺列表失败');
shops.value = [];
} finally {
shopsLoading.value = false;
}
}
// VbenVxeGrid 表格配置 const selectedShopLabel = computed(() => {
const gridOptions: VxeGridProps<any> = { 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: [ columns: [
{ {
type: 'seq' as const, type: 'seq' as const,
minWidth: 'auto', minWidth: 56,
title: '序号', title: '序号',
}, },
{ {
field: 'shopName', field: 'shopName',
title: '店铺名称', title: '店铺名称',
minWidth: 'auto', minWidth: 120,
showOverflow: 'tooltip' as const, showOverflow: 'tooltip' as const,
}, },
{ {
field: 'targetMonth', field: 'targetMonth',
title: '目标月份', title: '目标月份',
minWidth: 'auto', minWidth: 110,
}, },
{ {
title: '目标销售额', title: '目标销售额',
minWidth: 'auto', minWidth: 120,
slots: { default: 'targetAmount' }, slots: { default: 'targetAmount' },
}, },
{ {
field: 'targetOrderCount', field: 'targetOrderCount',
title: '目标订单数', title: '目标订单数',
minWidth: 'auto', minWidth: 100,
}, },
{ {
field: 'remark', field: 'remark',
title: '备注', title: '备注',
minWidth: 'auto', minWidth: 140,
showOverflow: 'tooltip' as const, showOverflow: 'tooltip' as const,
}, },
{ {
field: 'createTime', field: 'createTime',
title: '创建时间', title: '创建时间',
minWidth: 'auto', minWidth: 160,
}, },
{ {
title: '操作', title: '操作',
minWidth: 'auto', minWidth: 140,
fixed: 'right' as const, fixed: 'right' as const,
slots: { default: 'action' }, slots: { default: 'action' },
}, },
], ],
height: 'auto', height: '100%',
border: true, border: true,
stripe: true, stripe: true,
rowConfig: { isHover: true }, rowConfig: { isHover: true },
@@ -127,7 +164,6 @@ const gridOptions: VxeGridProps<any> = {
| 'Total' | 'Total'
)[], )[],
}, },
// 配置远程加载
proxyConfig: { proxyConfig: {
ajax: { ajax: {
query: async ({ page }) => { query: async ({ page }) => {
@@ -137,23 +173,16 @@ const gridOptions: VxeGridProps<any> = {
page: page.currentPage, page: page.currentPage,
pageSize: page.pageSize, pageSize: page.pageSize,
filters: { filters: {
shopId: searchForm.value.shopId, shopId: selectedShopId.value,
startTargetMonth: searchForm.value.startTargetMonth, startTargetMonth: searchForm.value.startTargetMonth || undefined,
endTargetMonth: searchForm.value.endTargetMonth, endTargetMonth: searchForm.value.endTargetMonth || undefined,
}, },
}; };
const data = await getShopMonthlyTargetPageApi(params); const data = await getShopMonthlyTargetPageApi(params);
return { return { items: data.records, total: data.total };
items: data.records, } catch {
total: data.total,
};
} catch (error) {
console.error('获取店铺月销量目标列表失败:', error);
message.error('获取店铺月销量目标列表失败'); message.error('获取店铺月销量目标列表失败');
return { return { items: [], total: 0 };
items: [],
total: 0,
};
} finally { } finally {
loading.value = false; loading.value = false;
} }
@@ -162,93 +191,48 @@ const gridOptions: VxeGridProps<any> = {
}, },
}; };
// 搜索表单配置
const gridReloadRef = ref<(() => void) | null>(null);
const formOptions = computed(() => ({
schema: [
{
component: 'Select',
componentProps: {
placeholder: '请选择店铺',
options: shopOptions,
allowClear: true,
showSearch: true,
filterOption: false,
loading: shopLoading,
onFocus: fetchShopOptions,
onChange: (val: any) => {
searchForm.value.shopId = val;
gridReloadRef.value?.();
},
},
fieldName: 'shopId',
label: '店铺',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '开始月份',
picker: 'month',
style: { width: '100%' },
onChange: (val: any) => {
searchForm.value.startTargetMonth = val ? val.format('YYYY-MM') : undefined;
gridReloadRef.value?.();
},
},
fieldName: 'startTargetMonth',
label: '目标月份',
},
{
component: 'DatePicker',
componentProps: {
placeholder: '结束月份',
picker: 'month',
style: { width: '100%' },
onChange: (val: any) => {
searchForm.value.endTargetMonth = val ? val.format('YYYY-MM') : undefined;
gridReloadRef.value?.();
},
},
fieldName: 'endTargetMonth',
label: '至',
},
],
showDefaultActions: true,
collapsed: true,
collapsedRows: 1,
}));
// 刷新表格数据
function refreshTable() { function refreshTable() {
if (gridApi) { gridApi?.reload();
gridApi.reload();
}
} }
// 创建 VbenVxeGrid 实例
const [Grid, gridApi] = useVbenVxeGrid({ const [Grid, gridApi] = useVbenVxeGrid({
gridOptions, gridOptions,
formOptions: formOptions.value, showSearchForm: false,
showSearchForm: true, tableTitle: '月销量目标',
tableTitle: '店铺月销量目标管理',
}); });
gridReloadRef.value = () => gridApi.reload();
// 处理新增 watch(selectedShopId, () => {
gridApi.reload();
});
onMounted(() => {
void loadShops();
});
function resetModalPreset() {
presetShopIdForModal.value = null;
}
const handleAdd = () => { const handleAdd = () => {
currentShopMonthlyTargetData.value = null; currentShopMonthlyTargetData.value = null;
resetModalPreset();
formModalVisible.value = true; formModalVisible.value = true;
}; };
// 处理编辑 function handleAddForShop(shopId: number) {
selectShop(shopId);
currentShopMonthlyTargetData.value = null;
presetShopIdForModal.value = shopId;
formModalVisible.value = true;
}
const handleEdit = (record: ShopMonthlyTargetVO.Info) => { const handleEdit = (record: ShopMonthlyTargetVO.Info) => {
resetModalPreset();
currentShopMonthlyTargetData.value = record; currentShopMonthlyTargetData.value = record;
formModalVisible.value = true; formModalVisible.value = true;
}; };
// 处理删除 async function handleDelete(id: number) {
const handleDelete = async (id: number) => {
try { try {
await deleteShopMonthlyTargetApi(id); await deleteShopMonthlyTargetApi(id);
message.success('删除成功'); message.success('删除成功');
@@ -256,48 +240,39 @@ const handleDelete = async (id: number) => {
} catch { } catch {
message.error('删除失败'); message.error('删除失败');
} }
}; }
// 处理表单成功
const handleFormSuccess = () => { const handleFormSuccess = () => {
resetModalPreset();
refreshTable(); refreshTable();
}; };
// 格式化金额 const handleFormCancel = () => {
const formatAmount = (amount: number) => { resetModalPreset();
return `¥${amount.toFixed(2)}`; formModalVisible.value = false;
}; };
// 获取店铺选项(首次触发时加载) const formatAmount = (amount: number) => `¥${amount.toFixed(2)}`;
async function fetchShopOptions() {
if (shopFetched.value || shopLoading.value) return;
shopLoading.value = true;
try {
const response = await getShopPageApi({
page: 1,
pageSize: 1000,
filters: {},
});
shopOptions.value = response.records.map((shop: ShopVO.Info) => ({
label: shop.name,
value: shop.id,
}));
shopFetched.value = true;
} catch (error) {
console.error('获取店铺列表失败:', error);
} finally {
shopLoading.value = false;
}
}
// 初始化 function shopRowClass(id: number | 'all') {
const active =
id === 'all'
? selectedShopId.value === undefined
: selectedShopId.value === id;
return [
'flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2.5 text-sm font-semibold transition-colors',
active
? 'border-primary bg-primary/8 text-primary'
: 'border-transparent bg-muted/30 text-foreground hover:bg-muted/60',
].join(' ');
}
</script> </script>
<template> <template>
<Page title="店铺月销量目标管理" auto-content-height> <Page title="店铺月销量目标管理" :auto-content-height="true">
<template #description> <template #description>
<div class="text-foreground/80 mt-2"> <div class="text-foreground/80 mt-2">
管理店铺月销量目标,支持按店铺、目标月份等维度查询和统计 左侧选择店铺筛选右侧月销量目标记录;未选店铺时展示全部记录。可在店铺行快捷新增该店铺月销量目标。
</div> </div>
</template> </template>
@@ -310,44 +285,152 @@ async function fetchShopOptions() {
</Space> </Space>
</template> </template>
<!-- 数据表格 --> <Flex gap="middle" class="h-full min-h-0">
<Grid :loading="loading"> <!-- 左:店铺 -->
<!-- 工具栏工具 --> <Card
<template #toolbar-tools> class="flex h-full w-[420px] shrink-0 flex-col"
<Space> :body-style="{
<span class="text-gray-500"> 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> </span>
</Space> </template>
</template> <Spin :spinning="shopsLoading" class="flex min-h-0 flex-1 flex-col">
<div class="flex min-h-0 flex-1 flex-col overflow-y-auto">
<button
type="button"
:class="shopRowClass('all')"
class="mb-1 w-full text-left"
@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>
<!-- 目标销售额列 --> <!-- 右:月销量目标 -->
<template #targetAmount="{ row }: { row: any }"> <Card
<span class="font-medium text-red-600"> class="flex h-full min-h-0 min-w-0 flex-1 flex-col"
{{ formatAmount(row.targetAmount) }} :body-style="{
</span> height: '100%',
</template> 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
<template #action="{ row }: { row: any }"> class="shrink-0 border-t border-border px-4 py-2 text-xs text-muted-foreground"
<Space> >
<Button size="small" @click="handleEdit(row)"> 编辑 </Button> 当前:{{ selectedShopLabel }}
<Popconfirm </div>
title="确定要删除这条月销量目标吗?"
@confirm="handleDelete(row.id)" <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">
<Button size="small" danger> 删除 </Button> <template #toolbar-tools>
</Popconfirm> <span class="text-xs text-muted-foreground">
</Space> 使用上方月份筛选;表格在区域内滚动
</template> </span>
</Grid> </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 <ShopMonthlyTargetFormModal
v-model:open="formModalVisible" v-model:open="formModalVisible"
:shop-monthly-target-data="currentShopMonthlyTargetData" :shop-monthly-target-data="currentShopMonthlyTargetData"
:preset-shop-id="presetShopIdForModal"
@success="handleFormSuccess" @success="handleFormSuccess"
@cancel="formModalVisible = false" @cancel="handleFormCancel"
/> />
</Page> </Page>
</template> </template>