feat: spu 保持一致

This commit is contained in:
xingyu4j
2025-10-09 17:50:43 +08:00
parent 3d67a376a3
commit 2e4b788c5d
2 changed files with 408 additions and 159 deletions

View File

@@ -0,0 +1,262 @@
import type { VbenFormSchema } from '#/adapter/form';
import { DeliveryTypeEnum, DICT_TYPE } from '@vben/constants';
import { getDictOptions } from '@vben/hooks';
import { handleTree } from '@vben/utils';
import { z } from '#/adapter/form';
import { getSimpleBrandList } from '#/api/mall/product/brand';
import { getCategoryList } from '#/api/mall/product/category';
import { getSimpleTemplateList } from '#/api/mall/trade/delivery/expressTemplate';
/** 基础设置的表单 */
export function useInfoFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'name',
label: '商品名称',
component: 'Input',
componentProps: {
allowClear: true,
placeholder: '请输入商品名称',
},
rules: 'required',
},
{
fieldName: 'categoryId',
label: '分类名称',
// component: 'ApiCascader',
component: 'ApiTreeSelect',
componentProps: {
api: async () => {
const data = await getCategoryList({});
return handleTree(data);
},
fieldNames: { label: 'name', value: 'id', children: 'children' },
placeholder: '请选择商品分类',
},
rules: 'required',
},
{
fieldName: 'brandId',
label: '商品品牌',
component: 'ApiSelect',
componentProps: {
api: () => getSimpleBrandList(),
labelField: 'name',
valueField: 'id',
allowClear: true,
placeholder: '请选择商品品牌',
},
rules: 'required',
},
{
fieldName: 'keyword',
label: '商品关键字',
component: 'Input',
componentProps: {
placeholder: '请输入商品关键字',
},
rules: 'required',
},
{
fieldName: 'introduction',
label: '商品简介',
component: 'Textarea',
componentProps: {
placeholder: '请输入商品简介',
autoSize: { minRows: 2, maxRows: 2 },
showCount: true,
maxlength: 128,
allowClear: true,
},
rules: 'required',
},
{
fieldName: 'picUrl',
label: '商品封面图',
component: 'ImageUpload',
componentProps: {
maxSize: 30,
},
rules: 'required',
},
{
fieldName: 'sliderPicUrls',
label: '商品轮播图',
component: 'ImageUpload',
componentProps: {
maxNumber: 10,
multiple: true,
maxSize: 30,
},
rules: 'required',
},
];
}
/** 价格库存的表单 */
export function useSkuFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'subCommissionType',
label: '分销类型',
component: 'RadioGroup',
componentProps: {
allowClear: true,
options: [
{
label: '默认设置',
value: false,
},
{
label: '单独设置',
value: true,
},
],
},
rules: 'required',
},
{
fieldName: 'specType',
label: '商品规格',
component: 'RadioGroup',
componentProps: {
allowClear: true,
options: [
{
label: '单规格',
value: false,
},
{
label: '多规格',
value: true,
},
],
},
rules: 'required',
},
// TODO @xingyu待补充商品属性
];
}
/** 物流设置的表单 */
export function useDeliveryFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'deliveryTypes',
label: '配送方式',
component: 'CheckboxGroup',
componentProps: {
options: getDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE, 'number'),
},
rules: 'required',
},
{
fieldName: 'deliveryTemplateId',
label: '运费模板',
component: 'ApiSelect',
componentProps: {
api: getSimpleTemplateList,
labelField: 'name',
valueField: 'id',
},
dependencies: {
triggerFields: ['deliveryTypes'],
show: (values) =>
!!values.deliveryTypes &&
values.deliveryTypes.includes(DeliveryTypeEnum.EXPRESS.type),
},
rules: 'required',
},
];
}
/** 商品详情的表单 */
export function useDescriptionFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'description',
label: '商品详情',
component: 'RichTextarea',
componentProps: {
placeholder: '请输入商品详情',
height: 1000,
},
rules: 'required',
},
];
}
/** 其它设置的表单 */
export function useOtherFormSchema(): VbenFormSchema[] {
return [
{
fieldName: 'id',
component: 'Input',
dependencies: {
triggerFields: [''],
show: () => false,
},
},
{
fieldName: 'sort',
label: '商品排序',
component: 'InputNumber',
componentProps: {
min: 0,
},
rules: z.number().min(0).optional().default(0),
},
{
fieldName: 'giveIntegral',
label: '赠送积分',
component: 'InputNumber',
componentProps: {
min: 0,
},
rules: z.number().min(0).optional().default(0),
},
{
fieldName: 'virtualSalesCount',
label: '虚拟销量',
component: 'InputNumber',
componentProps: {
min: 0,
},
rules: z.number().min(0).optional().default(0),
},
];
}

View File

@@ -1,104 +1,105 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { MallSpuApi } from '#/api/mall/product/spu'; import type { MallSpuApi } from '#/api/mall/product/spu';
import { onMounted, ref, unref } from 'vue'; import { onMounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router'; import { useRoute } from 'vue-router';
import { Page } from '@vben/common-ui'; import { ContentWrap, Page } from '@vben/common-ui';
import { cloneDeep, convertToInteger, formatToFraction } from '@vben/utils'; import { convertToInteger, formatToFraction } from '@vben/utils';
import { ElMessage } from 'element-plus'; import { ElButton, ElTabs } from 'element-plus';
import * as ProductSpuApi from '#/api/mall/product/spu'; import { useVbenForm } from '#/adapter/form';
import { createSpu, getSpu, updateSpu } from '#/api/mall/product/spu';
import DeliveryForm from '../components/delivery-form.vue'; import {
import DescriptionForm from '../components/description-form.vue'; useDeliveryFormSchema,
import InfoForm from '../components/info-form.vue'; useDescriptionFormSchema,
import OtherForm from '../components/other-form.vue'; useInfoFormSchema,
import SkuForm from '../components/sku-form.vue'; useOtherFormSchema,
useSkuFormSchema,
} from './form-data';
const spuId = ref<number>();
const { params } = useRoute();
const activeTab = ref('info'); const activeTab = ref('info');
const activeName = ref('info'); // Tag 激活的窗口
// SPU 表单数据 const [InfoForm, infoFormApi] = useVbenForm({
const formData = ref<MallSpuApi.Spu>({ commonConfig: {
name: '', // 商品名称 componentProps: {
categoryId: undefined, // 商品分类 class: 'w-full',
keyword: '', // 关键字
picUrl: '', // 商品封面图
sliderPicUrls: [], // 商品轮播图
introduction: '', // 商品简介
deliveryTypes: [], // 配送方式数组
deliveryTemplateId: undefined, // 运费模版
brandId: undefined, // 商品品牌
specType: false, // 商品规格
subCommissionType: false, // 分销类型
skus: [
{
price: 0, // 商品价格
marketPrice: 0, // 市场价
costPrice: 0, // 成本价
barCode: '', // 商品条码
picUrl: '', // 图片地址
stock: 0, // 库存
weight: 0, // 商品重量
volume: 0, // 商品体积
firstBrokeragePrice: 0, // 一级分销的佣金
secondBrokeragePrice: 0, // 二级分销的佣金
}, },
], formItemClass: 'col-span-2',
description: '', // 商品详情 labelWidth: 120,
sort: 0, // 商品排序 },
giveIntegral: 0, // 赠送积分 layout: 'horizontal',
virtualSalesCount: 0, // 虚拟销量 schema: useInfoFormSchema(),
showDefaultActions: false,
}); });
const formLoading = ref(false); // 表单的加载中1修改时的数据加载2提交的按钮禁用 const [SkuForm, skuFormApi] = useVbenForm({
const { push } = useRouter(); // 路由 commonConfig: {
const { params } = useRoute(); // 查询参数 componentProps: {
/** 获得详情 */ class: 'w-full',
const getDetail = async () => { },
const id = params.id as unknown as number; formItemClass: 'col-span-2',
if (id) { labelWidth: 120,
formLoading.value = true; },
try { layout: 'horizontal',
const res = (await ProductSpuApi.getSpu(id)) as MallSpuApi.Spu; schema: useSkuFormSchema(),
res.skus?.forEach((item: MallSpuApi.Sku) => { showDefaultActions: false,
// 回显价格分转元 });
item.price = formatToFraction(item.price);
item.marketPrice = formatToFraction(item.marketPrice);
item.costPrice = formatToFraction(item.costPrice);
item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice);
item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice);
});
formData.value = res;
} finally {
formLoading.value = false;
}
}
};
/** 提交按钮 */ const [DeliveryForm, deliveryFormApi] = useVbenForm({
const infoRef = ref<InstanceType<typeof InfoForm>>(); commonConfig: {
const skuRef = ref<InstanceType<typeof SkuForm>>(); componentProps: {
const deliveryRef = ref<InstanceType<typeof DeliveryForm>>(); class: 'w-full',
const descriptionRef = ref<InstanceType<typeof DescriptionForm>>(); },
const otherRef = ref<InstanceType<typeof OtherForm>>(); formItemClass: 'col-span-2',
const submitForm = async () => { labelWidth: 120,
// 提交请求 },
formLoading.value = true; layout: 'horizontal',
try { schema: useDeliveryFormSchema(),
// 校验各表单 showDefaultActions: false,
await unref(infoRef)?.validate(); });
await unref(skuRef)?.validate();
await unref(deliveryRef)?.validate(); const [DescriptionForm, descriptionFormApi] = useVbenForm({
await unref(descriptionRef)?.validate(); commonConfig: {
await unref(otherRef)?.validate(); componentProps: {
// 深拷贝一份, 这样最终 server 端不满足,不需要影响原始数据 class: 'w-full',
const deepCopyFormData = cloneDeep(unref(formData.value)) as MallSpuApi.Spu; },
deepCopyFormData.skus!.forEach((item) => { formItemClass: 'col-span-2',
// 给sku name赋值 labelWidth: 120,
item.name = deepCopyFormData.name; },
layout: 'vertical',
schema: useDescriptionFormSchema(),
showDefaultActions: false,
});
const [OtherForm, otherFormApi] = useVbenForm({
commonConfig: {
componentProps: {
class: 'w-full',
},
formItemClass: 'col-span-2',
labelWidth: 120,
},
layout: 'horizontal',
schema: useOtherFormSchema(),
showDefaultActions: false,
});
async function onSubmit() {
const values: MallSpuApi.Spu = await infoFormApi
.merge(skuFormApi)
.merge(deliveryFormApi)
.merge(descriptionFormApi)
.merge(otherFormApi)
.submitAllForm(true);
if (values.skus) {
values.skus.forEach((item) => {
// sku相关价格元转分 // sku相关价格元转分
item.price = convertToInteger(item.price); item.price = convertToInteger(item.price);
item.marketPrice = convertToInteger(item.marketPrice); item.marketPrice = convertToInteger(item.marketPrice);
@@ -106,85 +107,71 @@ const submitForm = async () => {
item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice); item.firstBrokeragePrice = convertToInteger(item.firstBrokeragePrice);
item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice); item.secondBrokeragePrice = convertToInteger(item.secondBrokeragePrice);
}); });
// 处理轮播图列表
const newSliderPicUrls: any[] = [];
deepCopyFormData.sliderPicUrls!.forEach((item: any) => {
// 如果是前端选的图
typeof item === 'object'
? newSliderPicUrls.push(item.url)
: newSliderPicUrls.push(item);
});
deepCopyFormData.sliderPicUrls = newSliderPicUrls;
// 校验都通过后提交表单
const data = deepCopyFormData as MallSpuApi.Spu;
const id = params.id as unknown as number;
if (id) {
await ProductSpuApi.updateSpu(data);
ElMessage.success('更新成功');
} else {
await ProductSpuApi.createSpu(data);
ElMessage.success('创建成功');
}
close();
} finally {
formLoading.value = false;
} }
}; // 处理轮播图列表
const newSliderPicUrls: any[] = [];
values.sliderPicUrls!.forEach((item: any) => {
// 如果是前端选的图
typeof item === 'object'
? newSliderPicUrls.push(item.url)
: newSliderPicUrls.push(item);
});
values.sliderPicUrls = newSliderPicUrls;
/** 关闭按钮 */ await (spuId.value ? updateSpu(values) : createSpu(values));
const close = () => { }
push({ name: 'ProductSpu' });
}; async function initDate() {
spuId.value = params.id as unknown as number;
if (!spuId.value) {
return;
}
const res = await getSpu(spuId.value);
if (res.skus) {
res.skus.forEach((item) => {
// 回显价格分转元
item.price = formatToFraction(item.price);
item.marketPrice = formatToFraction(item.marketPrice);
item.costPrice = formatToFraction(item.costPrice);
item.firstBrokeragePrice = formatToFraction(item.firstBrokeragePrice);
item.secondBrokeragePrice = formatToFraction(item.secondBrokeragePrice);
});
}
infoFormApi.setValues(res);
skuFormApi.setValues(res);
deliveryFormApi.setValues(res);
descriptionFormApi.setValues(res);
otherFormApi.setValues(res);
}
/** 初始化 */
onMounted(async () => { onMounted(async () => {
await getDetail(); await initDate();
}); });
</script> </script>
<template> <template>
<!-- TODO @样式有点丑要不照 vue3 + element-plus 在优化下 --> <Page auto-content-height>
<Page :auto-content-height="true"> <ContentWrap class="h-full w-full pb-8">
<ElTabs v-model="activeTab"> <template #extra>
<ElTabPane label="基础设置" name="info"> <ElButton type="primary" @click="onSubmit"> 保存 </ElButton>
<InfoForm </template>
:prop-form-data="formData" <ElTabs v-model="activeTab">
v-model:active-name="activeName" <ElTabs.TabPane label="基础设置" name="info">
ref="infoRef" <InfoForm class="w-3/5" />
/> </ElTabs.TabPane>
</ElTabPane> <ElTabs.TabPane label="价格库存" name="sku">
<ElTabPane label="价格库存" name="sku"> <SkuForm class="w-3/5" />
<SkuForm </ElTabs.TabPane>
:prop-form-data="formData" <ElTabs.TabPane label="物流设置" name="delivery">
v-model:active-name="activeName" <DeliveryForm class="w-3/5" />
ref="skuRef" </ElTabs.TabPane>
/> <ElTabs.TabPane label="商品详情" name="description">
</ElTabPane> <DescriptionForm class="w-3/5" />
<ElTabPane label="物流设置" name="delivery"> </ElTabs.TabPane>
<DeliveryForm <ElTabs.TabPane label="其它设置" name="other">
:prop-form-data="formData" <OtherForm class="w-3/5" />
v-model:active-name="activeName" </ElTabs.TabPane>
ref="deliveryRef" </ElTabs>
/> </ContentWrap>
</ElTabPane>
<ElTabPane label="商品详情" name="description">
<DescriptionForm
:prop-form-data="formData"
v-model:active-name="activeName"
ref="descriptionRef"
/>
</ElTabPane>
<ElTabPane label="其它设置" name="other">
<OtherForm
:prop-form-data="formData"
v-model:active-name="activeName"
ref="otherRef"
/>
</ElTabPane>
</ElTabs>
<ElButton type="primary" :loading="formLoading" @click="submitForm">
保存
</ElButton>
<ElButton @click="close">返回</ElButton>
</Page> </Page>
</template> </template>