feat: 优化商品编辑

This commit is contained in:
2026-08-18 23:05:53 +08:00
parent 9dd4977e09
commit 12bb03a43f
12 changed files with 660 additions and 246 deletions
@@ -43,3 +43,12 @@ export async function updateProductApi(id: number, data: ProductDTO.Update) {
export async function deleteProductApi(id: number) {
return requestClient.delete(`/ec/product/delete/${id}`);
}
/**
* 将他品 SKU 迁入当前商品
*/
export async function migrateSkuToProductApi(productId: number, skuId: number) {
return requestClient.post<ProductVO.Info>(
`/ec/product/${productId}/migrate-sku/${skuId}`,
);
}
@@ -47,6 +47,8 @@ export namespace ProductSkuDTO {
export interface Filters {
/** 商品 ID */
productId?: number;
/** 排除该商品下的 SKU(迁入搜索) */
excludeProductId?: number;
/** SKU ID */
id?: number;
/** SKU 名称 */
@@ -27,10 +27,8 @@ export namespace ProductDTO {
categoryId?: number;
/** 主图图片 ID */
mainImageId?: number;
/** 商品 SKU 列表:含 id 为更新,不含 id 为新增 */
/** 商品 SKU 列表:id>0 更新,id=0 新增;未出现的已有 SKU 视为删除 */
skus?: UpdateSku[];
/** 编辑时从商品上移除的 SKU ID(须为打开表单时已有的 SKU) */
removedSkuIds?: number[];
}
/** 商品 SKU DTO(创建时) */
@@ -73,7 +71,7 @@ export namespace ProductDTO {
/** 更新商品 SKU 参数 */
export interface UpdateSku {
/** SKU ID:有值表示更新已有 SKU;不传或空表示新增一条 SKU */
/** SKU ID:>0 更新已有;0 表示新增 */
id?: number;
/** SKU 名称 */
name: string;
@@ -425,6 +425,35 @@ const formOptions = computed(() => ({
fieldName: 'platformOrderNo',
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',
},
{
component: 'Select',
componentProps: {
@@ -485,39 +514,11 @@ const formOptions = computed(() => ({
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,
showCollapseButton: true,
collapsed: true,
collapsedRows: 2,
collapsedRows: 1,
defaultValues: {
orderTimeRange: defaultOrderTime.range,
},
@@ -25,6 +25,7 @@ import { uploadFileToOss } from '#/utils/oss-upload';
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
import ProductSkuMigrateModal from './ProductSkuMigrateModal.vue';
interface Emits {
(e: 'success'): void;
@@ -64,6 +65,9 @@ const productCostSyncModalRef = ref<InstanceType<
const productSkuCostDrawerRef = ref<InstanceType<
typeof ProductSkuCostDrawer
> | null>(null);
const productSkuMigrateModalRef = ref<InstanceType<
typeof ProductSkuMigrateModal
> | null>(null);
async function openSyncModal(skuIds: number[]) {
await productCostSyncModalRef.value?.open(skuIds, {
@@ -161,7 +165,7 @@ const categoryTreeDropdownRender: DropdownRender = (opt) => {
]);
};
/** 表格行:创建规格无 id,编辑已有规格带 id;_clientKey 用于行 key */
/** 表格行:已有 SKU 带 id;新增行 id=0。_clientKey 用于行 key */
type SkuFormRow = ProductDTO.Sku & {
_clientKey?: string;
id?: number;
@@ -174,13 +178,30 @@ type SkuFormRow = ProductDTO.Sku & {
_previewUrl?: string;
};
function isPersistedSkuId(id?: number) {
return id != null && id > 0;
}
function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
costEffectiveFrom?: string;
imageUrl?: string;
} {
return {
name: spec.name || spec.skuCode || '',
skuCode: spec.skuCode || '',
productCost: spec.productCost ?? 0,
shippingCost: spec.shippingCost ?? 0,
otherCost: spec.otherCost ?? 0,
costEffectiveFrom: spec.costEffectiveFrom,
remark: spec.remark || '',
imageUrl: spec.imageUrl || '',
};
}
// 规格数据 - 支持创建和更新
const skus = ref<SkuFormRow[]>([]);
const showSkus = ref(false);
/** 编辑打开时已有的规格 ID,用于提交时计算 removedSkuIds */
const initialEditSkuIds = ref<Set<number>>(new Set());
let nextSkuClientKey = 0;
// 当前显示的图片 URL(优先显示新选择的)
@@ -225,41 +246,22 @@ function initFormData() {
'skus' in currentProductData.value &&
currentProductData.value.skus
) {
const mapSku = (spec: ProductVO.SkuInfo) => ({
name: spec.name || spec.skuCode || '',
skuCode: spec.skuCode || '',
productCost: spec.productCost ?? 0,
shippingCost: spec.shippingCost ?? 0,
otherCost: spec.otherCost ?? 0,
costEffectiveFrom: spec.costEffectiveFrom,
remark: spec.remark || '',
imageUrl: spec.imageUrl || '',
});
skus.value = isEdit.value
? currentProductData.value.skus.map((spec) => {
const s = spec as ProductVO.SkuInfo;
return {
id: s.id,
_clientKey: `exist-${s.id}`,
...mapSku(s),
...mapSkuFields(s),
} as SkuFormRow;
})
: currentProductData.value.skus.map((spec) => ({
_clientKey: `seed-${++nextSkuClientKey}`,
...mapSku(spec as ProductVO.SkuInfo),
id: 0,
...mapSkuFields(spec as ProductVO.SkuInfo),
}));
showSkus.value = skus.value.length > 0;
}
if (isEdit.value) {
initialEditSkuIds.value = new Set(
skus.value
.map((s) => (s.id != null ? Number(s.id) : null))
.filter((x): x is number => x != null),
);
} else {
initialEditSkuIds.value = new Set();
}
}
// 重置表单(在open方法中调用)
@@ -273,7 +275,6 @@ function resetForm() {
}
skus.value = [];
showSkus.value = false;
initialEditSkuIds.value = new Set();
categoryOptions.value = [];
}
@@ -281,6 +282,15 @@ function resetForm() {
async function handleSubmit() {
try {
await formRef.value?.validate();
if (hasDuplicateSkuField(skus.value, 'skuCode')) {
message.error('SKU 编码不能重复');
return;
}
if (hasDuplicateSkuField(skus.value, 'name')) {
message.error('SKU 名称不能重复');
return;
}
modalApi.setState({ confirmLoading: true });
// 准备提交数据
@@ -314,54 +324,16 @@ async function handleSubmit() {
'id' in currentProductData.value &&
currentProductData.value.id
) {
const keptSkuIds = new Set(
skus.value
.map((s) => (s.id != null ? Number(s.id) : null))
.filter((x): x is number => x != null),
const skusPayload: ProductDTO.UpdateSku[] = skus.value.map((row) =>
toSkuUpdatePayload(row),
);
const removedSkuIds = [...initialEditSkuIds.value].filter(
(sid) => !keptSkuIds.has(sid),
);
const skusPayload: ProductDTO.UpdateSku[] = skus.value.map((row) => {
const {
_clientKey: _c,
_previewUrl: _p,
newImageFile: _f,
imageUrl: _u,
id,
name,
skuCode,
productCost,
shippingCost,
otherCost,
remark,
imageId,
} = row;
const base: ProductDTO.UpdateSku = {
name,
skuCode: skuCode ?? '',
productCost: productCost ?? 0,
shippingCost: shippingCost ?? 0,
otherCost: otherCost ?? 0,
remark: remark ?? '',
};
if (imageId != null) {
base.imageId = imageId;
}
if (id != null && id !== undefined) {
return { ...base, id: Number(id) };
}
return { ...base };
});
const updateData: ProductDTO.Update = {
name: submitData.name,
productCode: submitData.productCode || undefined,
categoryId: submitData.categoryId,
mainImageId: submitData.mainImageId,
...(skus.value.length > 0 && { skus: skusPayload }),
...(removedSkuIds.length > 0 && { removedSkuIds }),
skus: skusPayload,
};
const result = await updateProductApi(currentProductData.value.id, updateData);
if (skus.value.length > 0 && result.skuIdsCostChangedWithLinkedOrders?.length > 0) {
@@ -489,6 +461,7 @@ function removeNewImage() {
const defaultSku = (): SkuFormRow => ({
_clientKey: `new-${++nextSkuClientKey}`,
id: 0,
name: '',
skuCode: '',
productCost: 0,
@@ -499,6 +472,121 @@ const defaultSku = (): SkuFormRow => ({
newImageFile: null,
});
function hasDuplicateSkuField(rows: SkuFormRow[], field: 'name' | 'skuCode') {
const seen = new Set<string>();
for (const row of rows) {
const value = row[field]?.trim();
if (!value) continue;
if (seen.has(value)) return true;
seen.add(value);
}
return false;
}
function skuRowKey(row: SkuFormRow) {
return isPersistedSkuId(row.id) ? String(row.id) : (row._clientKey ?? '');
}
/** 与当前商品表单里其他行比较,空值不参与 */
function isDuplicateSkuField(row: SkuFormRow, field: 'name' | 'skuCode') {
const value = row[field]?.trim();
if (!value) return false;
const key = skuRowKey(row);
return skus.value.some(
(other) => skuRowKey(other) !== key && other[field]?.trim() === value,
);
}
function touchSkuRows() {
skus.value = [...skus.value];
}
function renderSkuTextInput(
record: SkuFormRow,
field: 'name' | 'skuCode',
placeholder: string,
duplicateHint: string,
) {
const duplicated = isDuplicateSkuField(record, field);
return h(
Form.Item,
{
validateStatus: duplicated ? 'error' : undefined,
help: duplicated ? duplicateHint : undefined,
class: '!mb-0',
style: { marginBottom: 0 },
},
{
default: () =>
h(Input, {
value: record[field],
placeholder,
status: duplicated ? 'error' : undefined,
'onUpdate:value': (value: string) => {
record[field] = value;
touchSkuRows();
},
}),
},
);
}
function toSkuUpdatePayload(row: SkuFormRow): ProductDTO.UpdateSku {
const payload: ProductDTO.UpdateSku = {
id: isPersistedSkuId(row.id) ? Number(row.id) : 0,
name: row.name,
skuCode: row.skuCode ?? '',
productCost: row.productCost ?? 0,
shippingCost: row.shippingCost ?? 0,
otherCost: row.otherCost ?? 0,
remark: row.remark ?? '',
};
if (row.imageId != null) {
payload.imageId = row.imageId;
}
return payload;
}
function applySkusFromProduct(product: ProductVO.Info) {
const unsaved = skus.value.filter((row) => !isPersistedSkuId(row.id));
const unsavedKeys = new Set(unsaved.map((row) => row._clientKey));
for (const row of skus.value) {
if (!unsavedKeys.has(row._clientKey)) {
revokeSkuPreview(row);
}
}
currentProductData.value = {
...(currentProductData.value ?? {}),
...product,
};
skus.value = [
...(product.skus ?? []).map((spec) => ({
id: spec.id,
_clientKey: `exist-${spec.id}`,
...mapSkuFields(spec),
})),
...unsaved,
];
showSkus.value = true;
}
function openMigrateModal() {
const productId = currentProductData.value?.id;
if (!isEdit.value || productId == null) {
message.warning('请先保存商品后再迁入 SKU');
return;
}
productSkuMigrateModalRef.value?.open(
productId,
formData.value.name || currentProductData.value?.name,
);
}
function onMigrateSuccess(product: ProductVO.Info) {
applySkusFromProduct(product);
emit('success');
}
// 添加 SKU
function addSku() {
skus.value.push(defaultSku());
@@ -690,34 +778,18 @@ const skuColumns = [
record,
}: {
record: SkuFormRow;
}) => {
return h(Input, {
value: record.name,
placeholder: '请输入SKU 名称',
'onUpdate:value': (value: string) => {
record.name = value;
},
});
},
}) => renderSkuTextInput(record, 'name', '请输入SKU 名称', '与同品 SKU 名称重复'),
},
{
title: 'SKU 编码',
dataIndex: 'skuCode',
key: 'skuCode',
width: 140,
width: 168,
customRender: ({
record,
}: {
record: SkuFormRow;
}) => {
return h(Input, {
value: record.skuCode,
placeholder: '请输入SKU 编码',
'onUpdate:value': (value: string) => {
record.skuCode = value;
},
});
},
}) => renderSkuTextInput(record, 'skuCode', '请输入SKU 编码', '与同品 SKU 编码重复'),
},
{
title: '商品成本',
@@ -994,12 +1066,20 @@ onUnmounted(() => {
管理成本
</Button>
</Space>
<Button v-if="showSkus" type="primary" @click="addSku">
<template #icon>
<PlusIcon class="h-4 w-4" />
</template>
添加 SKU
</Button>
<Space v-if="showSkus">
<Button
v-if="isEdit && currentProductData?.id"
@click="openMigrateModal"
>
迁入他品 SKU
</Button>
<Button type="primary" @click="addSku">
<template #icon>
<PlusIcon class="h-4 w-4" />
</template>
添加 SKU
</Button>
</Space>
</div>
<p
v-if="isEdit && showSkus"
@@ -1016,7 +1096,7 @@ onUnmounted(() => {
:columns="skuColumns"
:data-source="skus"
:pagination="false"
:row-key="(r: SkuFormRow) => (r.id != null ? String(r.id) : r._clientKey ?? '')"
:row-key="(r: SkuFormRow) => (isPersistedSkuId(r.id) ? String(r.id) : r._clientKey ?? '')"
:scroll="{ x: 980 }"
size="small"
>
@@ -1038,5 +1118,9 @@ onUnmounted(() => {
@success="emit('success')"
/>
<ProductSkuMigrateModal
ref="productSkuMigrateModalRef"
@success="onMigrateSuccess"
/>
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
</template>
@@ -0,0 +1,208 @@
<script setup lang="ts">
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
import type { ProductVO } from '#/api/ec/product/types';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import {
Button,
Input,
message,
Popconfirm,
Table,
} from 'ant-design-vue';
import { migrateSkuToProductApi } from '#/api/ec/product';
import { getProductSkuPageApi } from '#/api/ec/product/sku';
defineOptions({ name: 'ProductSkuMigrateModal' });
const emit = defineEmits<{
success: [product: ProductVO.Info];
}>();
/** 从他品搜索 SKU,二次确认后再迁入当前商品 */
const [Modal, modalApi] = useVbenModal({
title: '迁入他品 SKU',
class: 'w-[820px] max-w-[calc(100vw-2rem)]',
draggable: true,
contentClass: 'px-5 py-4',
showConfirmButton: false,
cancelText: '关闭',
onCancel() {
close();
},
});
const targetProductId = ref<number>();
const targetProductName = ref('');
const keyword = ref('');
const records = ref<ProductSkuVO.Info[]>([]);
const loading = ref(false);
const migratingSkuId = ref<number | null>(null);
const pagination = ref({ current: 1, pageSize: 10, total: 0 });
function formatCost(val?: number) {
return `¥${Number(val ?? 0).toFixed(2)}`;
}
async function search(resetPage = false) {
if (targetProductId.value == null) return;
if (resetPage) {
pagination.value.current = 1;
}
loading.value = true;
try {
const data = await getProductSkuPageApi({
page: pagination.value.current,
pageSize: pagination.value.pageSize,
filters: {
excludeProductId: targetProductId.value,
keywords: keyword.value.trim() || undefined,
},
});
records.value = data.records ?? [];
pagination.value.total = data.total ?? 0;
} catch {
records.value = [];
pagination.value.total = 0;
} finally {
loading.value = false;
}
}
function handleTableChange(pager: { current?: number; pageSize?: number }) {
pagination.value.current = pager.current ?? 1;
pagination.value.pageSize = pager.pageSize ?? pagination.value.pageSize;
void search();
}
async function confirmMigrate(sku: ProductSkuVO.Info) {
if (targetProductId.value == null) return;
migratingSkuId.value = sku.id;
try {
const product = await migrateSkuToProductApi(targetProductId.value, sku.id);
message.success('SKU 已迁入');
emit('success', product);
close();
} finally {
migratingSkuId.value = null;
}
}
function close() {
modalApi.close();
keyword.value = '';
records.value = [];
pagination.value = { current: 1, pageSize: 10, total: 0 };
targetProductId.value = undefined;
targetProductName.value = '';
}
async function open(productId: number, productName?: string) {
targetProductId.value = productId;
targetProductName.value = productName?.trim() || '';
keyword.value = '';
pagination.value = { current: 1, pageSize: 10, total: 0 };
modalApi.setState({
title: targetProductName.value
? `迁入他品 SKU(当前:${targetProductName.value})`
: '迁入他品 SKU',
});
modalApi.open();
await search(true);
}
const columns = [
{
title: '所属商品',
dataIndex: 'productName',
key: 'productName',
ellipsis: true,
},
{
title: 'SKU 名称',
dataIndex: 'name',
key: 'name',
ellipsis: true,
},
{
title: 'SKU 编码',
dataIndex: 'skuCode',
key: 'skuCode',
width: 140,
},
{
title: '商品成本',
dataIndex: 'productCost',
key: 'productCost',
width: 110,
customRender: ({ record }: { record: ProductSkuVO.Info }) =>
formatCost(record.productCost),
},
{
title: '操作',
key: 'action',
width: 100,
},
];
defineExpose({ open });
</script>
<template>
<Modal>
<div class="mb-3 flex gap-2">
<Input
v-model:value="keyword"
allow-clear
placeholder="按 SKU 名称或编码搜索"
@press-enter="search(true)"
/>
<Button type="primary" :loading="loading" @click="search(true)">
查询
</Button>
</div>
<Table
:columns="columns"
:data-source="records"
:loading="loading"
:pagination="{
current: pagination.current,
pageSize: pagination.pageSize,
total: pagination.total,
showSizeChanger: true,
showTotal: (total: number) => `共 ${total} 条`,
}"
:row-key="(row: ProductSkuVO.Info) => row.id"
size="small"
@change="handleTableChange"
>
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'action'">
<Popconfirm
:title="`确认将「${record.name}」从「${record.productName || '其他商品'}」迁入当前商品?`"
ok-text="确认迁入"
cancel-text="取消"
:ok-button-props="{ loading: migratingSkuId === record.id }"
@confirm="confirmMigrate(record)"
>
<Button
type="link"
size="small"
:loading="migratingSkuId === record.id"
>
迁入
</Button>
</Popconfirm>
</template>
</template>
<template #emptyText>
<div class="py-6 text-center text-slate-400">暂无他品 SKU</div>
</template>
</Table>
</Modal>
</template>