mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 03:09:19 +08:00
feat: 加入规格体系
This commit is contained in:
@@ -17,6 +17,10 @@ export namespace ProductSkuVO {
|
||||
name: string;
|
||||
/** SKU 编码 */
|
||||
skuCode?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: import('#/api/ec/product/spec').ProductSpecVO.SpecValue[];
|
||||
/** 商品成本 */
|
||||
productCost: number;
|
||||
/** 运费成本 */
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 规格模板 API(单维:一个模板=一个规格维 + 若干值)
|
||||
*/
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
|
||||
export namespace SpecTemplateVO {
|
||||
export interface Info {
|
||||
id: number;
|
||||
companyId: number;
|
||||
name: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: Value[];
|
||||
createTime?: string;
|
||||
updateTime?: string;
|
||||
}
|
||||
|
||||
export interface Value {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace SpecTemplateDTO {
|
||||
export interface Create {
|
||||
name: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface Update {
|
||||
name?: string;
|
||||
remark?: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ReplaceContent {
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ValueItem {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export interface Apply {
|
||||
templateId: number;
|
||||
/** 空=该维全部值 */
|
||||
templateValueIds?: number[];
|
||||
}
|
||||
|
||||
export interface SaveAs {
|
||||
productSpecId: number;
|
||||
name?: string;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listSpecTemplatesApi() {
|
||||
return requestClient.get<SpecTemplateVO.Info[]>(
|
||||
'/ec/product/spec-templates',
|
||||
);
|
||||
}
|
||||
|
||||
export async function getSpecTemplateApi(id: number) {
|
||||
return requestClient.get<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createSpecTemplateApi(data: SpecTemplateDTO.Create) {
|
||||
return requestClient.post<SpecTemplateVO.Info>(
|
||||
'/ec/product/spec-templates',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateSpecTemplateApi(
|
||||
id: number,
|
||||
data: SpecTemplateDTO.Update,
|
||||
) {
|
||||
return requestClient.put<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function replaceSpecTemplateContentApi(
|
||||
id: number,
|
||||
data: SpecTemplateDTO.ReplaceContent,
|
||||
) {
|
||||
return requestClient.put<SpecTemplateVO.Info>(
|
||||
`/ec/product/spec-templates/${id}/content`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteSpecTemplateApi(id: number) {
|
||||
return requestClient.delete(`/ec/product/spec-templates/${id}`);
|
||||
}
|
||||
|
||||
export async function applySpecTemplateApi(
|
||||
productId: number,
|
||||
data: SpecTemplateDTO.Apply,
|
||||
) {
|
||||
return requestClient.post<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs/apply-template`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
export async function saveProductAsSpecTemplateApi(
|
||||
productId: number,
|
||||
data: SpecTemplateDTO.SaveAs,
|
||||
) {
|
||||
return requestClient.post<SpecTemplateVO.Info>(
|
||||
`/ec/product/${productId}/specs/save-as-template`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/**
|
||||
* 商品规格维 API / 类型
|
||||
*/
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
|
||||
|
||||
export namespace ProductSpecVO {
|
||||
export interface Spec {
|
||||
id?: number;
|
||||
name?: string;
|
||||
sortOrder?: number;
|
||||
values?: SpecValue[];
|
||||
}
|
||||
|
||||
export interface SpecValue {
|
||||
id?: number;
|
||||
specId?: number;
|
||||
valueName?: string;
|
||||
valueCode?: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
}
|
||||
|
||||
export namespace ProductSpecDTO {
|
||||
export interface Replace {
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
export interface SpecItem {
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder?: number;
|
||||
values?: ValueItem[];
|
||||
}
|
||||
|
||||
export interface ValueItem {
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export interface GenerateSkus {
|
||||
productCost?: number;
|
||||
shippingCost?: number;
|
||||
otherCost?: number;
|
||||
}
|
||||
|
||||
export interface CreateSkuFromSpecs {
|
||||
specValueIds: number[];
|
||||
skuCode?: string;
|
||||
name?: string;
|
||||
productCost: number;
|
||||
shippingCost?: number;
|
||||
otherCost?: number;
|
||||
remark?: string;
|
||||
}
|
||||
|
||||
/** 已有 SKU 绑定规格;空数组=解绑 */
|
||||
export interface BindSkuSpecs {
|
||||
specValueIds?: number[];
|
||||
}
|
||||
}
|
||||
|
||||
/** 查询商品规格维 */
|
||||
export async function listProductSpecsApi(productId: number) {
|
||||
return requestClient.get<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs`,
|
||||
);
|
||||
}
|
||||
|
||||
/** 覆盖保存商品规格维 */
|
||||
export async function replaceProductSpecsApi(
|
||||
productId: number,
|
||||
data: ProductSpecDTO.Replace,
|
||||
) {
|
||||
return requestClient.put<ProductSpecVO.Spec[]>(
|
||||
`/ec/product/${productId}/specs`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** 按规格笛卡尔积生成缺失 SKU */
|
||||
export async function generateProductSkusApi(
|
||||
productId: number,
|
||||
data?: ProductSpecDTO.GenerateSkus,
|
||||
) {
|
||||
return requestClient.post<ProductSkuVO.Info[]>(
|
||||
`/ec/product/${productId}/specs/generate-skus`,
|
||||
data ?? {},
|
||||
);
|
||||
}
|
||||
|
||||
/** 按所选规格值创建 SKU(可缺维;skuCode 可自定义) */
|
||||
export async function createSkuFromSpecsApi(
|
||||
productId: number,
|
||||
data: ProductSpecDTO.CreateSkuFromSpecs,
|
||||
) {
|
||||
return requestClient.post<ProductSkuVO.Info>(
|
||||
`/ec/product/${productId}/specs/skus`,
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格(不改 sku_code)。
|
||||
* specValueIds 空则解绑回 legacy。
|
||||
*/
|
||||
export async function bindSkuSpecsApi(
|
||||
productId: number,
|
||||
skuId: number,
|
||||
data?: ProductSpecDTO.BindSkuSpecs,
|
||||
) {
|
||||
return requestClient.put<ProductSkuVO.Info>(
|
||||
`/ec/product/${productId}/specs/skus/${skuId}`,
|
||||
data ?? { specValueIds: [] },
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ export namespace ProductDTO {
|
||||
mainImageId?: number;
|
||||
/** 商品 SKU 列表(可选) */
|
||||
skus?: Sku[];
|
||||
/** 规格维(与商品同事务;无 id=新增) */
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
/** 更新商品参数 */
|
||||
@@ -29,6 +31,25 @@ export namespace ProductDTO {
|
||||
mainImageId?: number;
|
||||
/** 商品 SKU 列表:id>0 更新,id=0 新增;未出现的已有 SKU 视为删除 */
|
||||
skus?: UpdateSku[];
|
||||
/** 规格维全量同步:有 id 更新,无 id 新增,未出现的删除 */
|
||||
specs?: SpecItem[];
|
||||
}
|
||||
|
||||
/** 商品规格维(创建/更新商品时一并提交) */
|
||||
export interface SpecItem {
|
||||
/** >0 更新已有;空/0 新增 */
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder?: number;
|
||||
values?: SpecValueItem[];
|
||||
}
|
||||
|
||||
export interface SpecValueItem {
|
||||
/** >0 更新已有;空/0 新增 */
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
/** 商品 SKU DTO(创建时) */
|
||||
|
||||
@@ -19,6 +19,8 @@ export namespace ProductVO {
|
||||
productCode?: string;
|
||||
/** 主图 URL */
|
||||
mainImage?: string;
|
||||
/** 结构化规格维 */
|
||||
specs?: import('#/api/ec/product/spec').ProductSpecVO.Spec[];
|
||||
/** 创建时间 */
|
||||
createTime: string;
|
||||
/** 更新时间 */
|
||||
@@ -80,6 +82,10 @@ export namespace ProductVO {
|
||||
name: string;
|
||||
/** SKU 编码 */
|
||||
skuCode?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: import('#/api/ec/product/spec').ProductSpecVO.SpecValue[];
|
||||
/** 商品成本 */
|
||||
productCost: number;
|
||||
/** 运费成本 */
|
||||
|
||||
+29
@@ -93,6 +93,19 @@ const skuColumns = [
|
||||
ellipsis: true,
|
||||
customRender: ({ text }: { text?: string }) => renderEllipsisText(text),
|
||||
},
|
||||
{
|
||||
title: '规格',
|
||||
key: 'specValues',
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
customRender: ({ record }: { record: ProductVO.SkuInfo }) => {
|
||||
const text = (record.specValues ?? [])
|
||||
.map((v) => v.valueName)
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
return renderEllipsisText(text || (record.specCombinationKey ? '结构化' : '-'));
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '商品成本',
|
||||
dataIndex: 'productCost',
|
||||
@@ -271,6 +284,22 @@ defineExpose({
|
||||
<span>{{ product.createTime || '-' }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="product.specs?.length"
|
||||
class="mt-2 border-t border-slate-200 pt-2 text-xs text-slate-600 dark:border-[hsl(240deg_3.7%_22%)] dark:text-slate-300"
|
||||
>
|
||||
<span class="text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">规格维:</span>
|
||||
<span
|
||||
v-for="(spec, i) in product.specs"
|
||||
:key="spec.id ?? i"
|
||||
>
|
||||
{{ i > 0 ? ';' : '' }}{{ spec.name }}({{
|
||||
(spec.values ?? [])
|
||||
.map((v) => `${v.valueName}/${v.valueCode}`)
|
||||
.join('、') || '无值'
|
||||
}})
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+180
-31
@@ -21,11 +21,14 @@ import {
|
||||
|
||||
import { getCategoryTreeApi } from '#/api/ec/product/category';
|
||||
import { createProductApi, updateProductApi } from '#/api/ec/product';
|
||||
import { getProductSkuPageApi } from '#/api/ec/product/sku';
|
||||
import { uploadFile } from '#/utils/upload-file';
|
||||
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
||||
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
||||
import ProductSkuDeleteConfirmModal from './ProductSkuDeleteConfirmModal.vue';
|
||||
import ProductSkuMigrateModal from './ProductSkuMigrateModal.vue';
|
||||
import ProductSkuBindSpecModal from './ProductSkuBindSpecModal.vue';
|
||||
import ProductSpecEditor from './ProductSpecEditor.vue';
|
||||
|
||||
interface Emits {
|
||||
(e: 'success'): void;
|
||||
@@ -35,6 +38,10 @@ defineOptions({ name: 'ProductFormModal' });
|
||||
|
||||
const emit = defineEmits<Emits>();
|
||||
|
||||
const productSpecEditorRef = ref<InstanceType<typeof ProductSpecEditor> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
// 创建Vben Modal实例:内容区不滚动,由 SKU 列表占满剩余高度并独立滚动
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '添加商品',
|
||||
@@ -69,6 +76,9 @@ const productSkuMigrateModalRef = ref<InstanceType<
|
||||
const productSkuDeleteModalRef = ref<InstanceType<
|
||||
typeof ProductSkuDeleteConfirmModal
|
||||
> | null>(null);
|
||||
const productSkuBindSpecModalRef = ref<InstanceType<
|
||||
typeof ProductSkuBindSpecModal
|
||||
> | null>(null);
|
||||
/** SKU 列表滚动容器:新增行后滚到底 */
|
||||
const skuListScrollRef = ref<HTMLElement | null>(null);
|
||||
|
||||
@@ -196,6 +206,10 @@ type SkuFormRow = ProductDTO.Sku & {
|
||||
_clientKey?: string;
|
||||
id?: number;
|
||||
costEffectiveFrom?: string;
|
||||
/** 规格组合键;空=未结构化 */
|
||||
specCombinationKey?: string;
|
||||
/** 已绑规格值 */
|
||||
specValues?: ProductVO.SkuInfo['specValues'];
|
||||
/** 已有图预览 URL(系统文件或渠道外链) */
|
||||
imageUrl?: string;
|
||||
/** 新选择待上传的文件 */
|
||||
@@ -211,6 +225,8 @@ function isPersistedSkuId(id?: number) {
|
||||
function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
|
||||
costEffectiveFrom?: string;
|
||||
imageUrl?: string;
|
||||
specCombinationKey?: string;
|
||||
specValues?: ProductVO.SkuInfo['specValues'];
|
||||
} {
|
||||
return {
|
||||
name: spec.name || spec.skuCode || '',
|
||||
@@ -221,6 +237,8 @@ function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
|
||||
costEffectiveFrom: spec.costEffectiveFrom,
|
||||
remark: spec.remark || '',
|
||||
imageUrl: spec.imageUrl || '',
|
||||
specCombinationKey: spec.specCombinationKey,
|
||||
specValues: spec.specValues,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -317,6 +335,14 @@ async function handleSubmit() {
|
||||
return;
|
||||
}
|
||||
|
||||
const specErr = productSpecEditorRef.value?.validateDraft?.();
|
||||
if (specErr) {
|
||||
message.error(specErr);
|
||||
return;
|
||||
}
|
||||
const specsPayload: ProductDTO.SpecItem[] =
|
||||
productSpecEditorRef.value?.getSpecsPayload?.() ?? [];
|
||||
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
|
||||
// 准备提交数据
|
||||
@@ -356,24 +382,25 @@ async function handleSubmit() {
|
||||
|
||||
const updateData: ProductDTO.Update = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
productCode: String(submitData.productCode || '').trim(),
|
||||
categoryId: submitData.categoryId,
|
||||
mainImageId: submitData.mainImageId,
|
||||
skus: skusPayload,
|
||||
specs: specsPayload,
|
||||
};
|
||||
const result = await updateProductApi(currentProductData.value.id, updateData);
|
||||
if (result.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品和 SKU 更新成功,已标记 BI 待重算(请在工作台查看)');
|
||||
message.success('商品、规格和 SKU 更新成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('商品和 SKU 更新成功');
|
||||
message.success('商品、规格和 SKU 更新成功');
|
||||
}
|
||||
} else {
|
||||
// 创建模式:统一使用创建接口,规格信息作为可选字段
|
||||
const createData: ProductDTO.Create = {
|
||||
name: submitData.name,
|
||||
productCode: submitData.productCode || undefined,
|
||||
productCode: String(submitData.productCode || '').trim(),
|
||||
categoryId: submitData.categoryId,
|
||||
mainImageId: submitData.mainImageId,
|
||||
specs: specsPayload,
|
||||
...(skus.value.length > 0 && {
|
||||
skus: skus.value.map(
|
||||
({
|
||||
@@ -388,14 +415,10 @@ async function handleSubmit() {
|
||||
}),
|
||||
};
|
||||
const createResult = await createProductApi(createData);
|
||||
if (skus.value.length > 0) {
|
||||
if (createResult.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品和 SKU 创建成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('商品和 SKU 创建成功');
|
||||
}
|
||||
if (createResult.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||
message.success('商品创建成功,已标记 BI 待重算(请在工作台查看)');
|
||||
} else {
|
||||
message.success('创建成功');
|
||||
message.success('商品创建成功');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,6 +431,27 @@ async function handleSubmit() {
|
||||
}
|
||||
}
|
||||
|
||||
/** 按规格生成/添加 SKU 后刷新表单 SKU 列表 */
|
||||
async function onSpecSkusChanged() {
|
||||
const productId = currentProductData.value?.id;
|
||||
if (productId == null) return;
|
||||
try {
|
||||
const data = await getProductSkuPageApi({
|
||||
page: 1,
|
||||
pageSize: 500,
|
||||
filters: { productId },
|
||||
});
|
||||
applySkusFromProduct({
|
||||
...(currentProductData.value as ProductVO.Info),
|
||||
id: productId,
|
||||
skus: (data.records ?? []) as unknown as ProductVO.SkuInfo[],
|
||||
});
|
||||
emit('success');
|
||||
} catch (error: any) {
|
||||
message.error(error?.message || '刷新 SKU 列表失败');
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭模态框
|
||||
function close() {
|
||||
modalApi.close();
|
||||
@@ -842,6 +886,20 @@ const skuColumns = [
|
||||
record: SkuFormRow;
|
||||
}) => renderSkuTextInput(record, 'skuCode', '请输入SKU 编码', '与同品 SKU 编码重复'),
|
||||
},
|
||||
{
|
||||
title: '规格',
|
||||
key: 'specValues',
|
||||
width: 120,
|
||||
ellipsis: true,
|
||||
customRender: ({ record }: { record: SkuFormRow }) => {
|
||||
const text = (record.specValues ?? [])
|
||||
.map((v) => v.valueName)
|
||||
.filter(Boolean)
|
||||
.join(' / ');
|
||||
if (text) return text;
|
||||
return record.specCombinationKey ? '已结构化' : '未绑定';
|
||||
},
|
||||
},
|
||||
{
|
||||
title: '商品成本',
|
||||
dataIndex: 'productCost',
|
||||
@@ -897,26 +955,99 @@ const skuColumns = [
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 48,
|
||||
width: 112,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) => {
|
||||
return h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
size: 'small',
|
||||
title: '删除',
|
||||
onClick: () => removeSku(index),
|
||||
},
|
||||
{
|
||||
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
|
||||
},
|
||||
customRender: ({
|
||||
record,
|
||||
index,
|
||||
}: {
|
||||
record: SkuFormRow;
|
||||
index: number;
|
||||
}) => {
|
||||
const children = [];
|
||||
if (isPersistedSkuId(record.id) && currentProductData.value?.id) {
|
||||
children.push(
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'link',
|
||||
title: '绑定规格',
|
||||
style: { padding: '0 4px' },
|
||||
onClick: () => openBindSpec(record),
|
||||
},
|
||||
{ default: () => '规格' },
|
||||
),
|
||||
);
|
||||
}
|
||||
children.push(
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
title: '删除',
|
||||
onClick: () => removeSku(index),
|
||||
},
|
||||
{
|
||||
icon: () => h(TrashIcon, { class: 'h-4 w-4' }),
|
||||
},
|
||||
),
|
||||
);
|
||||
return h(Space, { size: 0 }, { default: () => children });
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
function openBindSpec(record: SkuFormRow) {
|
||||
const pid = currentProductData.value?.id;
|
||||
if (pid == null || !isPersistedSkuId(record.id)) {
|
||||
message.warning('请先保存商品与该 SKU');
|
||||
return;
|
||||
}
|
||||
productSkuBindSpecModalRef.value?.open(pid, {
|
||||
id: Number(record.id),
|
||||
companyId: currentProductData.value?.companyId ?? 0,
|
||||
productId: pid,
|
||||
productName: formData.value.name || '',
|
||||
name: record.name,
|
||||
skuCode: record.skuCode,
|
||||
productCost: record.productCost ?? 0,
|
||||
shippingCost: record.shippingCost,
|
||||
otherCost: record.otherCost,
|
||||
costEffectiveFrom: record.costEffectiveFrom,
|
||||
remark: record.remark,
|
||||
imageUrl: record.imageUrl,
|
||||
specCombinationKey: record.specCombinationKey,
|
||||
specValues: record.specValues,
|
||||
createTime: '',
|
||||
updateTime: '',
|
||||
});
|
||||
}
|
||||
|
||||
function onBindSpecSuccess(vo: ProductVO.SkuInfo) {
|
||||
const idx = skus.value.findIndex((s) => s.id === vo.id);
|
||||
if (idx >= 0) {
|
||||
skus.value[idx] = {
|
||||
...skus.value[idx]!,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues ?? [],
|
||||
};
|
||||
skus.value = [...skus.value];
|
||||
}
|
||||
const productSkus = currentProductData.value?.skus;
|
||||
if (productSkus) {
|
||||
const pIdx = productSkus.findIndex((s) => s.id === vo.id);
|
||||
if (pIdx >= 0) {
|
||||
productSkus[pIdx] = {
|
||||
...productSkus[pIdx]!,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
emit('success');
|
||||
}
|
||||
|
||||
// 上传图片并获取图片ID
|
||||
async function uploadImageAndGetId(): Promise<number | undefined> {
|
||||
if (!newImageFile.value) {
|
||||
@@ -1082,10 +1213,14 @@ onUnmounted(() => {
|
||||
<Input v-model:value="formData.name" placeholder="请输入商品名称" />
|
||||
</Form.Item>
|
||||
|
||||
<Form.Item label="商品编码" name="productCode">
|
||||
<Form.Item
|
||||
label="商品编码"
|
||||
name="productCode"
|
||||
:rules="[{ required: true, message: '请输入商品编码' }]"
|
||||
>
|
||||
<Input
|
||||
v-model:value="formData.productCode"
|
||||
placeholder="请输入商品编码"
|
||||
placeholder="请输入商品编码(公司内唯一)"
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -1103,7 +1238,17 @@ onUnmounted(() => {
|
||||
</Form.Item>
|
||||
</div>
|
||||
|
||||
<!-- 规格管理:不用 Form.Item,避免栅格打断滚动高度链 -->
|
||||
<div class="mb-3 shrink-0">
|
||||
<ProductSpecEditor
|
||||
ref="productSpecEditorRef"
|
||||
:product-id="currentProductData?.id"
|
||||
:product-code="formData.productCode"
|
||||
:initial-specs="currentProductData?.specs"
|
||||
@skus-changed="onSpecSkusChanged"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- SKU:不用 Form.Item,避免栅格打断滚动高度链 -->
|
||||
<div class="flex min-h-0 flex-1 flex-col gap-3 overflow-hidden">
|
||||
<div class="flex shrink-0 items-center justify-between gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
@@ -1146,7 +1291,8 @@ onUnmounted(() => {
|
||||
v-if="isEdit && showSkus"
|
||||
class="shrink-0 text-xs text-slate-400"
|
||||
>
|
||||
已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。
|
||||
已有 SKU 的成本只读;调价请点「管理成本」。新增 SKU 仍可填初始成本。已落库
|
||||
SKU 可点「规格」绑定规格维(不改编码)。
|
||||
</p>
|
||||
|
||||
<div
|
||||
@@ -1160,7 +1306,6 @@ onUnmounted(() => {
|
||||
:pagination="false"
|
||||
:row-key="(r: SkuFormRow) => (isPersistedSkuId(r.id) ? String(r.id) : r._clientKey ?? '')"
|
||||
:scroll="{ x: 980 }"
|
||||
size="small"
|
||||
>
|
||||
<template #emptyText>
|
||||
<div class="py-4 text-center text-gray-400">
|
||||
@@ -1183,5 +1328,9 @@ onUnmounted(() => {
|
||||
@success="onMigrateSuccess"
|
||||
/>
|
||||
<ProductSkuDeleteConfirmModal ref="productSkuDeleteModalRef" />
|
||||
<ProductSkuBindSpecModal
|
||||
ref="productSkuBindSpecModalRef"
|
||||
@success="onBindSpecSuccess"
|
||||
/>
|
||||
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
|
||||
</template>
|
||||
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 已有 SKU 绑定规格:写组合键与关系表,不改 sku_code。
|
||||
*/
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
import type { ProductVO } from '#/api/ec/product/types';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
|
||||
import { Button, Select, Space, message } from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
bindSkuSpecsApi,
|
||||
listProductSpecsApi,
|
||||
} from '#/api/ec/product/spec';
|
||||
|
||||
defineOptions({ name: 'ProductSkuBindSpecModal' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [sku: ProductVO.SkuInfo];
|
||||
}>();
|
||||
|
||||
const productId = ref<number>();
|
||||
const sku = ref<ProductVO.SkuInfo | null>(null);
|
||||
const specs = ref<ProductSpecVO.Spec[]>([]);
|
||||
const selectedBySpecId = ref<Record<number, number | undefined>>({});
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
|
||||
const title = computed(() => {
|
||||
const code = sku.value?.skuCode || sku.value?.name || '';
|
||||
return code ? `绑定规格 - ${code}` : '绑定规格';
|
||||
});
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '绑定规格',
|
||||
class: 'w-[480px]',
|
||||
confirmText: '保存绑定',
|
||||
cancelText: '取消',
|
||||
onConfirm: handleSave,
|
||||
});
|
||||
|
||||
async function open(pid: number, row: ProductVO.SkuInfo) {
|
||||
if (!pid || !row?.id) {
|
||||
message.warning('请先保存商品与 SKU');
|
||||
return;
|
||||
}
|
||||
productId.value = pid;
|
||||
sku.value = row;
|
||||
selectedBySpecId.value = {};
|
||||
loading.value = true;
|
||||
modalApi.setState({ title: title.value, confirmLoading: false });
|
||||
modalApi.open();
|
||||
try {
|
||||
const list = await listProductSpecsApi(pid);
|
||||
specs.value = list ?? [];
|
||||
if (specs.value.length === 0) {
|
||||
message.warning('请先配置并保存规格维');
|
||||
}
|
||||
// 预填已绑规格值
|
||||
const bound = row.specValues ?? [];
|
||||
for (const s of specs.value) {
|
||||
if (s.id == null) continue;
|
||||
const hit = bound.find((v) => v.specId === s.id);
|
||||
selectedBySpecId.value[s.id] = hit?.id;
|
||||
}
|
||||
modalApi.setState({ title: title.value });
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载规格失败');
|
||||
modalApi.close();
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (productId.value == null || sku.value?.id == null) return;
|
||||
const ids: number[] = [];
|
||||
for (const s of specs.value) {
|
||||
if (s.id == null) continue;
|
||||
const vid = selectedBySpecId.value[s.id];
|
||||
if (vid != null) ids.push(vid);
|
||||
}
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const vo = await bindSkuSpecsApi(productId.value, sku.value.id, {
|
||||
specValueIds: ids,
|
||||
});
|
||||
message.success(ids.length === 0 ? '已解除规格绑定' : '规格已绑定(编码未改)');
|
||||
emit('success', {
|
||||
...sku.value,
|
||||
...vo,
|
||||
specCombinationKey: vo.specCombinationKey,
|
||||
specValues: vo.specValues,
|
||||
} as ProductVO.SkuInfo);
|
||||
modalApi.close();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '绑定失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUnbind() {
|
||||
if (productId.value == null || sku.value?.id == null) return;
|
||||
saving.value = true;
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const vo = await bindSkuSpecsApi(productId.value, sku.value.id, {
|
||||
specValueIds: [],
|
||||
});
|
||||
message.success('已解除规格绑定');
|
||||
emit('success', {
|
||||
...sku.value,
|
||||
...vo,
|
||||
specCombinationKey: undefined,
|
||||
specValues: [],
|
||||
} as ProductVO.SkuInfo);
|
||||
modalApi.close();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '解绑失败');
|
||||
} finally {
|
||||
saving.value = false;
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<p class="mb-3 text-xs text-slate-500">
|
||||
可为外部同步 SKU 绑定规格组合,<strong>不修改 SKU 编码</strong>。允许缺维;清空选择并保存,或点「解除绑定」回到无结构。
|
||||
</p>
|
||||
<div v-if="loading" class="py-6 text-center text-sm text-slate-400">加载中…</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="spec in specs.filter((s) => s.id)"
|
||||
:key="spec.id"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span class="w-20 shrink-0 text-sm">{{ spec.name }}</span>
|
||||
<Select
|
||||
v-model:value="selectedBySpecId[spec.id!]"
|
||||
class="flex-1"
|
||||
allow-clear
|
||||
placeholder="不选则缺该维"
|
||||
:options="
|
||||
(spec.values ?? [])
|
||||
.filter((v) => v.id)
|
||||
.map((v) => ({
|
||||
label: `${v.valueName} (${v.valueCode})`,
|
||||
value: v.id!,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<p v-if="specs.length === 0" class="text-sm text-amber-600">暂无规格维</p>
|
||||
<Space class="pt-1">
|
||||
<Button
|
||||
danger
|
||||
size="small"
|
||||
:disabled="saving || !sku?.specCombinationKey"
|
||||
@click="handleUnbind"
|
||||
>
|
||||
解除绑定
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</Modal>
|
||||
</template>
|
||||
+978
@@ -0,0 +1,978 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 商品规格维编辑:选择器套用模板;草稿随商品创建/更新一并提交。
|
||||
*/
|
||||
import type { ProductDTO } from '#/api/ec/product/types';
|
||||
import type { ProductSpecVO } from '#/api/ec/product/spec';
|
||||
import type { SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
import type { DropdownRender } from 'ant-design-vue/es/vc-select/BaseSelect';
|
||||
|
||||
import { computed, h, nextTick, ref, watch } from 'vue';
|
||||
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
InputNumber,
|
||||
Modal,
|
||||
Select,
|
||||
Space,
|
||||
Table,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createSkuFromSpecsApi,
|
||||
generateProductSkusApi,
|
||||
listProductSpecsApi,
|
||||
} from '#/api/ec/product/spec';
|
||||
import {
|
||||
listSpecTemplatesApi,
|
||||
saveProductAsSpecTemplateApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
import SpecTemplateFormModal from '#/views/ec/product/spec-template/components/SpecTemplateFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'ProductSpecEditor' });
|
||||
|
||||
const props = defineProps<{
|
||||
productId?: number | null;
|
||||
productCode?: string;
|
||||
/** 初始规格(编辑时从商品详情带入) */
|
||||
initialSpecs?: ProductSpecVO.Spec[];
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
skusChanged: [];
|
||||
}>();
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
const UpIcon = createIconifyIcon('lucide:chevron-up');
|
||||
const DownIcon = createIconifyIcon('lucide:chevron-down');
|
||||
const ArrowUpIcon = createIconifyIcon('lucide:arrow-up');
|
||||
const ArrowDownIcon = createIconifyIcon('lucide:arrow-down');
|
||||
|
||||
type DraftValue = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder: number;
|
||||
};
|
||||
|
||||
type DraftSpec = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
name: string;
|
||||
sortOrder: number;
|
||||
values: DraftValue[];
|
||||
};
|
||||
|
||||
const specs = ref<DraftSpec[]>([]);
|
||||
const showSpecs = ref(false);
|
||||
const dirty = ref(false);
|
||||
const generating = ref(false);
|
||||
const showAddSku = ref(false);
|
||||
const addSkuLoading = ref(false);
|
||||
const selectedBySpec = ref<Record<string, number | undefined>>({});
|
||||
const addSkuCost = ref({ productCost: 0, shippingCost: 0, otherCost: 0 });
|
||||
const addSkuCode = ref('');
|
||||
const addSkuName = ref('');
|
||||
const listScrollRef = ref<HTMLElement | null>(null);
|
||||
const templateFormModalRef = ref<InstanceType<
|
||||
typeof SpecTemplateFormModal
|
||||
> | null>(null);
|
||||
|
||||
/** 公司规格模板(选择器用) */
|
||||
const templates = ref<SpecTemplateVO.Info[]>([]);
|
||||
/** 规格名搜索词:spec._key → query */
|
||||
const specNameSearch = ref<Record<string, string>>({});
|
||||
/** 规格值名搜索词:specKey:valKey → query */
|
||||
const valueNameSearch = ref<Record<string, string>>({});
|
||||
/** 新建模板后回填到哪一行 */
|
||||
const pendingTemplateSpecKey = ref<string>();
|
||||
|
||||
let keySeq = 0;
|
||||
function nextKey(prefix: string) {
|
||||
return `${prefix}-${++keySeq}`;
|
||||
}
|
||||
|
||||
const canPersist = computed(
|
||||
() => props.productId != null && props.productId > 0,
|
||||
);
|
||||
|
||||
const savedSpecCount = computed(
|
||||
() => specs.value.filter((s) => s.id != null && s.id > 0).length,
|
||||
);
|
||||
|
||||
function toDraft(list?: ProductSpecVO.Spec[]): DraftSpec[] {
|
||||
return (list ?? []).map((s, si) => ({
|
||||
_key: nextKey('spec'),
|
||||
id: s.id,
|
||||
name: s.name || '',
|
||||
sortOrder: s.sortOrder ?? si,
|
||||
values: (s.values ?? []).map((v, vi) => ({
|
||||
_key: nextKey('val'),
|
||||
id: v.id,
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: v.sortOrder ?? vi,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
function resetFromProps() {
|
||||
specs.value = toDraft(props.initialSpecs);
|
||||
dirty.value = false;
|
||||
selectedBySpec.value = {};
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.productId,
|
||||
async (id) => {
|
||||
selectedBySpec.value = {};
|
||||
dirty.value = false;
|
||||
void loadTemplates();
|
||||
if (id != null && id > 0) {
|
||||
try {
|
||||
const list = await listProductSpecsApi(id);
|
||||
specs.value = toDraft(list);
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
return;
|
||||
} catch {
|
||||
// 接口失败时回退初始值
|
||||
}
|
||||
}
|
||||
specs.value = toDraft(props.initialSpecs);
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
watch(showSpecs, (open) => {
|
||||
if (open) void loadTemplates();
|
||||
});
|
||||
|
||||
async function loadTemplates() {
|
||||
try {
|
||||
templates.value = (await listSpecTemplatesApi()) ?? [];
|
||||
} catch {
|
||||
templates.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
function findTemplateByName(name?: string) {
|
||||
const n = name?.trim();
|
||||
if (!n) return undefined;
|
||||
return templates.value.find((t) => t.name === n);
|
||||
}
|
||||
|
||||
/** 选中模板:写入维名并用模板值覆盖当前行规格值 */
|
||||
function applyTemplateToSpec(spec: DraftSpec, tpl: SpecTemplateVO.Info) {
|
||||
spec.name = tpl.name;
|
||||
const vals = tpl.values ?? [];
|
||||
if (vals.length > 0) {
|
||||
spec.values = vals.map((v, i) => ({
|
||||
_key: nextKey('val'),
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: i,
|
||||
}));
|
||||
} else if (spec.values.length === 0) {
|
||||
spec.values = [
|
||||
{
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: 0,
|
||||
},
|
||||
];
|
||||
}
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function stripCustomPrefix(v: string) {
|
||||
return v.startsWith('__custom__:') ? v.slice('__custom__:'.length) : v;
|
||||
}
|
||||
|
||||
function onSpecNameSearch(spec: DraftSpec, q: string) {
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: q };
|
||||
}
|
||||
|
||||
function specNameOptions(spec: DraftSpec) {
|
||||
const q = (specNameSearch.value[spec._key] || '').trim();
|
||||
let list = templates.value.map((t) => ({
|
||||
label: `${t.name}(${t.values?.length ?? 0})`,
|
||||
value: t.name,
|
||||
}));
|
||||
if (q) {
|
||||
const lower = q.toLowerCase();
|
||||
list = list.filter(
|
||||
(o) =>
|
||||
o.value.toLowerCase().includes(lower) ||
|
||||
o.label.toLowerCase().includes(lower),
|
||||
);
|
||||
}
|
||||
if (q && !templates.value.some((t) => t.name === q)) {
|
||||
list = [{ label: `自定义「${q}」`, value: `__custom__:${q}` }, ...list];
|
||||
}
|
||||
if (
|
||||
spec.name &&
|
||||
!list.some(
|
||||
(o) => o.value === spec.name || o.value === `__custom__:${spec.name}`,
|
||||
)
|
||||
) {
|
||||
list.unshift({ label: spec.name, value: spec.name });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
function onSpecNameChange(spec: DraftSpec, raw?: string | null) {
|
||||
if (raw == null || raw === '') {
|
||||
spec.name = '';
|
||||
markDirty();
|
||||
return;
|
||||
}
|
||||
const name = stripCustomPrefix(String(raw)).trim();
|
||||
const tpl = findTemplateByName(name);
|
||||
if (tpl) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
} else {
|
||||
spec.name = name;
|
||||
markDirty();
|
||||
}
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: '' };
|
||||
}
|
||||
|
||||
function onSpecNameBlur(spec: DraftSpec) {
|
||||
const q = (specNameSearch.value[spec._key] || '').trim();
|
||||
if (!q) return;
|
||||
const tpl = findTemplateByName(q);
|
||||
if (tpl) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
} else if (spec.name !== q) {
|
||||
spec.name = q;
|
||||
markDirty();
|
||||
}
|
||||
specNameSearch.value = { ...specNameSearch.value, [spec._key]: '' };
|
||||
}
|
||||
|
||||
function openCreateTemplateForSpec(spec: DraftSpec) {
|
||||
pendingTemplateSpecKey.value = spec._key;
|
||||
const defaultName = (
|
||||
specNameSearch.value[spec._key] ||
|
||||
spec.name ||
|
||||
''
|
||||
).trim();
|
||||
templateFormModalRef.value?.open(false, undefined, { defaultName });
|
||||
}
|
||||
|
||||
async function onTemplateFormSuccess(tpl?: SpecTemplateVO.Info) {
|
||||
await loadTemplates();
|
||||
const key = pendingTemplateSpecKey.value;
|
||||
pendingTemplateSpecKey.value = undefined;
|
||||
if (!tpl || !key) return;
|
||||
const spec = specs.value.find((s) => s._key === key);
|
||||
if (spec) {
|
||||
applyTemplateToSpec(spec, tpl);
|
||||
}
|
||||
}
|
||||
|
||||
function specNameDropdownRender(spec: DraftSpec): DropdownRender {
|
||||
return (opt) =>
|
||||
h('div', {}, [
|
||||
opt?.menuNode,
|
||||
h(
|
||||
'div',
|
||||
{
|
||||
style: {
|
||||
borderTop: '1px solid #f1f5f9',
|
||||
padding: '6px 8px',
|
||||
background: '#f8fafc',
|
||||
},
|
||||
},
|
||||
[
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'link',
|
||||
size: 'small',
|
||||
block: true,
|
||||
style: {
|
||||
height: 'auto',
|
||||
padding: '4px 8px',
|
||||
textAlign: 'left' as const,
|
||||
},
|
||||
onMousedown: (e: MouseEvent) => e.preventDefault(),
|
||||
onClick: (e: MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openCreateTemplateForSpec(spec);
|
||||
},
|
||||
},
|
||||
{
|
||||
default: () => [
|
||||
h(PlusIcon, {
|
||||
class: 'mr-1 inline-block h-4 w-4 align-middle',
|
||||
}),
|
||||
h('span', null, '添加规格模板'),
|
||||
],
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
function valueSearchKey(spec: DraftSpec, val: DraftValue) {
|
||||
return `${spec._key}:${val._key}`;
|
||||
}
|
||||
|
||||
function valueNameOptions(spec: DraftSpec, val: DraftValue) {
|
||||
const q = (valueNameSearch.value[valueSearchKey(spec, val)] || '').trim();
|
||||
const tplVals = findTemplateByName(spec.name)?.values ?? [];
|
||||
let list = tplVals.map((v) => ({
|
||||
label: `${v.valueName}(${v.valueCode})`,
|
||||
value: v.valueName!,
|
||||
}));
|
||||
if (q) {
|
||||
const lower = q.toLowerCase();
|
||||
list = list.filter(
|
||||
(o) =>
|
||||
o.value.toLowerCase().includes(lower) ||
|
||||
o.label.toLowerCase().includes(lower),
|
||||
);
|
||||
}
|
||||
if (q && !tplVals.some((v) => v.valueName === q)) {
|
||||
list = [{ label: `自定义「${q}」`, value: `__custom__:${q}` }, ...list];
|
||||
}
|
||||
if (
|
||||
val.valueName &&
|
||||
!list.some(
|
||||
(o) =>
|
||||
o.value === val.valueName ||
|
||||
o.value === `__custom__:${val.valueName}`,
|
||||
)
|
||||
) {
|
||||
list.unshift({ label: val.valueName, value: val.valueName });
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
function onValueNameChange(
|
||||
spec: DraftSpec,
|
||||
val: DraftValue,
|
||||
raw?: string | null,
|
||||
) {
|
||||
if (raw == null || raw === '') {
|
||||
val.valueName = '';
|
||||
touchSpecs();
|
||||
return;
|
||||
}
|
||||
const name = stripCustomPrefix(String(raw)).trim();
|
||||
val.valueName = name;
|
||||
const hit = (findTemplateByName(spec.name)?.values ?? []).find(
|
||||
(v) => v.valueName === name,
|
||||
);
|
||||
if (hit?.valueCode) {
|
||||
val.valueCode = hit.valueCode;
|
||||
}
|
||||
valueNameSearch.value = {
|
||||
...valueNameSearch.value,
|
||||
[valueSearchKey(spec, val)]: '',
|
||||
};
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function onValueNameBlur(spec: DraftSpec, val: DraftValue) {
|
||||
const key = valueSearchKey(spec, val);
|
||||
const q = (valueNameSearch.value[key] || '').trim();
|
||||
if (!q) return;
|
||||
const hit = (findTemplateByName(spec.name)?.values ?? []).find(
|
||||
(v) => v.valueName === q,
|
||||
);
|
||||
if (hit) {
|
||||
val.valueName = hit.valueName || q;
|
||||
if (hit.valueCode) val.valueCode = hit.valueCode;
|
||||
} else if (val.valueName !== q) {
|
||||
val.valueName = q;
|
||||
}
|
||||
valueNameSearch.value = { ...valueNameSearch.value, [key]: '' };
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function markDirty() {
|
||||
dirty.value = true;
|
||||
}
|
||||
|
||||
function touchSpecs() {
|
||||
specs.value = [...specs.value];
|
||||
markDirty();
|
||||
}
|
||||
|
||||
async function addSpec() {
|
||||
showSpecs.value = true;
|
||||
specs.value.push({
|
||||
_key: nextKey('spec'),
|
||||
name: '',
|
||||
sortOrder: specs.value.length,
|
||||
values: [
|
||||
{
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
markDirty();
|
||||
await nextTick();
|
||||
const el = listScrollRef.value;
|
||||
if (el) {
|
||||
el.scrollTo({ top: el.scrollHeight, behavior: 'smooth' });
|
||||
}
|
||||
}
|
||||
|
||||
function removeSpec(index: number) {
|
||||
specs.value.splice(index, 1);
|
||||
reindexSort();
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function moveSpec(index: number, delta: number) {
|
||||
const target = index + delta;
|
||||
if (target < 0 || target >= specs.value.length) return;
|
||||
const list = [...specs.value];
|
||||
const [row] = list.splice(index, 1);
|
||||
if (!row) return;
|
||||
list.splice(target, 0, row);
|
||||
specs.value = list;
|
||||
reindexSort();
|
||||
markDirty();
|
||||
}
|
||||
|
||||
function reindexSort() {
|
||||
specs.value.forEach((s, i) => {
|
||||
s.sortOrder = i;
|
||||
s.values.forEach((v, vi) => {
|
||||
v.sortOrder = vi;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function addValue(spec: DraftSpec) {
|
||||
spec.values.push({
|
||||
_key: nextKey('val'),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: spec.values.length,
|
||||
});
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function removeValue(spec: DraftSpec, index: number) {
|
||||
spec.values.splice(index, 1);
|
||||
spec.values.forEach((v, i) => {
|
||||
v.sortOrder = i;
|
||||
});
|
||||
touchSpecs();
|
||||
}
|
||||
|
||||
function normalizeValueCode(val: DraftValue) {
|
||||
const next = val.valueCode.trim().toUpperCase();
|
||||
if (next !== val.valueCode) {
|
||||
val.valueCode = next;
|
||||
touchSpecs();
|
||||
}
|
||||
}
|
||||
|
||||
/** 供商品创建/更新一并提交(有 id 更新,无/0 新增;未出现的由后端删除) */
|
||||
function getSpecsPayload(): ProductDTO.SpecItem[] {
|
||||
reindexSort();
|
||||
return specs.value.map((s, si) => ({
|
||||
id: s.id != null && s.id > 0 ? s.id : 0,
|
||||
name: s.name.trim(),
|
||||
sortOrder: s.sortOrder ?? si,
|
||||
values: s.values.map((v, vi) => ({
|
||||
id: v.id != null && v.id > 0 ? v.id : 0,
|
||||
valueName: v.valueName.trim(),
|
||||
valueCode: v.valueCode.trim().toUpperCase(),
|
||||
sortOrder: v.sortOrder ?? vi,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
function validateDraft(): string | null {
|
||||
for (const s of specs.value) {
|
||||
if (!s.name.trim()) return '规格名称不能为空';
|
||||
if (s.values.length === 0) return `规格「${s.name}」至少需要一个规格值`;
|
||||
const names = new Set<string>();
|
||||
const codes = new Set<string>();
|
||||
for (const v of s.values) {
|
||||
if (!v.valueName.trim()) return `规格「${s.name}」存在空规格值名称`;
|
||||
if (!v.valueCode.trim()) return `规格「${s.name}」存在空规格值编码`;
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(v.valueCode.trim())) {
|
||||
return `规格值编码「${v.valueCode}」仅允许字母数字_-`;
|
||||
}
|
||||
const vn = v.valueName.trim();
|
||||
const vc = v.valueCode.trim().toUpperCase();
|
||||
if (names.has(vn)) return `规格「${s.name}」规格值名称重复`;
|
||||
if (codes.has(vc)) return `规格「${s.name}」规格值编码重复`;
|
||||
names.add(vn);
|
||||
codes.add(vc);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function reloadFromServer() {
|
||||
if (!canPersist.value) return;
|
||||
const list = await listProductSpecsApi(props.productId!);
|
||||
specs.value = toDraft(list);
|
||||
dirty.value = false;
|
||||
showSpecs.value = specs.value.length > 0;
|
||||
}
|
||||
|
||||
async function handleGenerate() {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (!props.productCode?.trim()) {
|
||||
message.warning('请先填写商品编码');
|
||||
return;
|
||||
}
|
||||
if (specs.value.length === 0) {
|
||||
message.warning('请先配置规格维并保存商品');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品后再生成 SKU');
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
title: '按规格生成 SKU?',
|
||||
content:
|
||||
'将按当前已保存规格做笛卡尔积,仅补缺失组合;编码为「商品编码-规格值编码…」。冲突则整批失败。',
|
||||
okText: '生成',
|
||||
cancelText: '取消',
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
generating.value = true;
|
||||
try {
|
||||
const created = await generateProductSkusApi(props.productId!, {
|
||||
productCost: 0,
|
||||
shippingCost: 0,
|
||||
otherCost: 0,
|
||||
});
|
||||
message.success(`已生成 ${created.length} 个 SKU`);
|
||||
emit('skusChanged');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '生成失败');
|
||||
throw e;
|
||||
} finally {
|
||||
generating.value = false;
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function openAddSkuPanel() {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (savedSpecCount.value === 0) {
|
||||
message.warning('请先保存商品以写入规格维');
|
||||
return;
|
||||
}
|
||||
selectedBySpec.value = {};
|
||||
addSkuCost.value = { productCost: 0, shippingCost: 0, otherCost: 0 };
|
||||
addSkuCode.value = '';
|
||||
addSkuName.value = '';
|
||||
showAddSku.value = true;
|
||||
}
|
||||
|
||||
async function handleCreateFromSpecs() {
|
||||
const ids: number[] = [];
|
||||
for (const s of specs.value) {
|
||||
if (!s.id) continue;
|
||||
const vid = selectedBySpec.value[s._key];
|
||||
if (vid != null) ids.push(vid);
|
||||
}
|
||||
if (ids.length === 0) {
|
||||
message.warning('请至少选择一个规格值(允许缺维)');
|
||||
return;
|
||||
}
|
||||
addSkuLoading.value = true;
|
||||
try {
|
||||
await createSkuFromSpecsApi(props.productId!, {
|
||||
specValueIds: ids,
|
||||
skuCode: addSkuCode.value.trim() || undefined,
|
||||
name: addSkuName.value.trim() || undefined,
|
||||
productCost: addSkuCost.value.productCost,
|
||||
shippingCost: addSkuCost.value.shippingCost,
|
||||
otherCost: addSkuCost.value.otherCost,
|
||||
});
|
||||
message.success('SKU 已创建');
|
||||
showAddSku.value = false;
|
||||
emit('skusChanged');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '创建失败');
|
||||
return Promise.reject(e);
|
||||
} finally {
|
||||
addSkuLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function valueColumns(spec: DraftSpec) {
|
||||
return [
|
||||
{
|
||||
title: '规格值',
|
||||
dataIndex: 'valueName',
|
||||
key: 'valueName',
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Select, {
|
||||
value: record.valueName || undefined,
|
||||
showSearch: true,
|
||||
allowClear: true,
|
||||
placeholder: '选择或输入',
|
||||
style: { width: '100%' },
|
||||
options: valueNameOptions(spec, record),
|
||||
filterOption: false,
|
||||
onSearch: (q: string) => {
|
||||
const k = valueSearchKey(spec, record);
|
||||
valueNameSearch.value = { ...valueNameSearch.value, [k]: q };
|
||||
},
|
||||
'onUpdate:value': (v: string | undefined) =>
|
||||
onValueNameChange(spec, record, v),
|
||||
onBlur: () => onValueNameBlur(spec, record),
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '编码',
|
||||
dataIndex: 'valueCode',
|
||||
key: 'valueCode',
|
||||
width: 160,
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueCode,
|
||||
placeholder: '如 BLK',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueCode = v;
|
||||
markDirty();
|
||||
},
|
||||
onBlur: () => normalizeValueCode(record),
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
key: 'action',
|
||||
width: 56,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) =>
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
title: '删除',
|
||||
onClick: () => removeValue(spec, index),
|
||||
},
|
||||
{ icon: () => h(TrashIcon, { class: 'h-4 w-4' }) },
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** 将当前规格行另存为公司模板(需已落库的规格 id) */
|
||||
function handleSaveAsTemplateForSpec(spec: DraftSpec) {
|
||||
if (!canPersist.value) {
|
||||
message.warning('请先保存商品');
|
||||
return;
|
||||
}
|
||||
if (!spec.id || spec.id <= 0) {
|
||||
message.warning('请先保存商品以写入该规格,再另存为模板');
|
||||
return;
|
||||
}
|
||||
if (dirty.value) {
|
||||
message.warning('规格有未提交修改,请先保存商品再另存');
|
||||
return;
|
||||
}
|
||||
let nameOverride = '';
|
||||
Modal.confirm({
|
||||
title: '另存为规格模板',
|
||||
content: h('div', { class: 'space-y-3' }, [
|
||||
h(
|
||||
'p',
|
||||
{ class: 'mb-0 text-sm text-slate-500' },
|
||||
`将规格「${spec.name}」拷贝为公司模板(一个模板=一个维)`,
|
||||
),
|
||||
h(Input, {
|
||||
placeholder: '模板名称(可选,默认用规格名)',
|
||||
defaultValue: spec.name,
|
||||
onChange: (e: any) => {
|
||||
nameOverride = e?.target?.value ?? '';
|
||||
},
|
||||
}),
|
||||
]),
|
||||
okText: '保存',
|
||||
cancelText: '取消',
|
||||
centered: true,
|
||||
onOk: async () => {
|
||||
try {
|
||||
await saveProductAsSpecTemplateApi(props.productId!, {
|
||||
productSpecId: spec.id!,
|
||||
name: nameOverride.trim() || undefined,
|
||||
});
|
||||
message.success('已另存为模板');
|
||||
await loadTemplates();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '另存失败');
|
||||
return Promise.reject(e);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
defineExpose({
|
||||
getSpecsPayload,
|
||||
validateDraft,
|
||||
reloadFromServer,
|
||||
resetFromProps,
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-0 flex-col gap-3 overflow-hidden">
|
||||
<div class="flex shrink-0 items-center justify-between gap-2">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<span class="shrink-0 text-sm text-foreground/80">商品规格</span>
|
||||
<Space>
|
||||
<Button type="dashed" @click="showSpecs = !showSpecs">
|
||||
<template #icon>
|
||||
<component :is="showSpecs ? UpIcon : DownIcon" class="h-4 w-4" />
|
||||
</template>
|
||||
{{ showSpecs ? '收起规格' : '展开规格' }}
|
||||
</Button>
|
||||
<span
|
||||
v-if="specs.length > 0"
|
||||
class="text-xs text-slate-400"
|
||||
>
|
||||
{{ specs.length }} 维
|
||||
<template v-if="dirty"> · 将随商品保存</template>
|
||||
</span>
|
||||
</Space>
|
||||
</div>
|
||||
<Space v-if="showSpecs" wrap>
|
||||
<Button
|
||||
:loading="generating"
|
||||
:disabled="!canPersist"
|
||||
@click="handleGenerate"
|
||||
>
|
||||
生成全部 SKU
|
||||
</Button>
|
||||
<Button :disabled="!canPersist" @click="openAddSkuPanel">
|
||||
按规格添加
|
||||
</Button>
|
||||
<Button type="primary" @click="addSpec">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
添加规格
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="showSpecs"
|
||||
class="mb-0 shrink-0 text-xs text-slate-400"
|
||||
>
|
||||
规格名从选择器选模板即可套用常用值;也可自定义。规格随商品一并保存(有 id
|
||||
更新,无 id 新增,删行即删除)。
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="showSpecs"
|
||||
ref="listScrollRef"
|
||||
class="max-h-[32vh] overflow-y-auto rounded-lg border border-gray-200 bg-white p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
|
||||
>
|
||||
<div
|
||||
v-if="specs.length === 0"
|
||||
class="py-4 text-center text-gray-400"
|
||||
>
|
||||
暂无规格,点击「添加规格」;规格名可从模板选择或自定义输入
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="(spec, si) in specs"
|
||||
:key="spec._key"
|
||||
class="mb-4 border-b border-slate-100 pb-4 last:mb-0 last:border-b-0 last:pb-0 dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span class="w-14 shrink-0 text-xs text-slate-400">规格名</span>
|
||||
<Select
|
||||
:value="spec.name || undefined"
|
||||
class="!w-52"
|
||||
show-search
|
||||
allow-clear
|
||||
placeholder="选择或输入规格"
|
||||
:options="specNameOptions(spec)"
|
||||
:filter-option="false"
|
||||
:dropdown-render="specNameDropdownRender(spec)"
|
||||
@search="(q: string) => onSpecNameSearch(spec, q)"
|
||||
@change="(v: any) => onSpecNameChange(spec, v as string)"
|
||||
@blur="onSpecNameBlur(spec)"
|
||||
/>
|
||||
<Space :size="4">
|
||||
<Button
|
||||
type="text"
|
||||
title="上移"
|
||||
:disabled="si === 0"
|
||||
@click="moveSpec(si, -1)"
|
||||
>
|
||||
<template #icon>
|
||||
<ArrowUpIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
<Button
|
||||
type="text"
|
||||
title="下移"
|
||||
:disabled="si === specs.length - 1"
|
||||
@click="moveSpec(si, 1)"
|
||||
>
|
||||
<template #icon>
|
||||
<ArrowDownIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
<Button type="link" @click="addValue(spec)">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
规格值
|
||||
</Button>
|
||||
<Button
|
||||
type="link"
|
||||
title="另存为模板"
|
||||
:disabled="!canPersist || !spec.id"
|
||||
@click="handleSaveAsTemplateForSpec(spec)"
|
||||
>
|
||||
另存为模板
|
||||
</Button>
|
||||
<Button
|
||||
type="text"
|
||||
danger
|
||||
title="删除规格"
|
||||
@click="removeSpec(si)"
|
||||
>
|
||||
<template #icon>
|
||||
<TrashIcon class="h-4 w-4" />
|
||||
</template>
|
||||
</Button>
|
||||
</Space>
|
||||
</div>
|
||||
<Table
|
||||
:columns="valueColumns(spec)"
|
||||
:data-source="spec.values"
|
||||
:pagination="false"
|
||||
:row-key="(r: DraftValue) => r._key"
|
||||
>
|
||||
<template #emptyText>
|
||||
<span class="text-xs text-slate-400">暂无规格值</span>
|
||||
</template>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
v-model:open="showAddSku"
|
||||
title="按规格值添加 SKU(可缺维)"
|
||||
:confirm-loading="addSkuLoading"
|
||||
ok-text="创建"
|
||||
destroy-on-close
|
||||
@ok="handleCreateFromSpecs"
|
||||
>
|
||||
<div class="space-y-3 py-2">
|
||||
<div
|
||||
v-for="spec in specs.filter((s) => s.id)"
|
||||
:key="spec._key"
|
||||
class="flex items-center gap-2"
|
||||
>
|
||||
<span class="w-20 shrink-0 text-sm">{{ spec.name }}</span>
|
||||
<Select
|
||||
v-model:value="selectedBySpec[spec._key]"
|
||||
class="flex-1"
|
||||
allow-clear
|
||||
placeholder="不选则缺该维"
|
||||
:options="
|
||||
spec.values
|
||||
.filter((v) => v.id)
|
||||
.map((v) => ({
|
||||
label: `${v.valueName} (${v.valueCode})`,
|
||||
value: v.id!,
|
||||
}))
|
||||
"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">
|
||||
SKU 编码(可选,空则按规则生成)
|
||||
</div>
|
||||
<Input
|
||||
v-model:value="addSkuCode"
|
||||
placeholder="自定义编码,如外部系统编码"
|
||||
allow-clear
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">SKU 名称(可选)</div>
|
||||
<Input
|
||||
v-model:value="addSkuName"
|
||||
placeholder="空则用规格值名拼接"
|
||||
allow-clear
|
||||
/>
|
||||
</div>
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">商品成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.productCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">运费成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.shippingCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="mb-1 text-xs text-slate-500">其他成本</div>
|
||||
<InputNumber
|
||||
v-model:value="addSkuCost.otherCost"
|
||||
class="w-full"
|
||||
:min="0"
|
||||
:precision="2"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
<SpecTemplateFormModal
|
||||
ref="templateFormModalRef"
|
||||
@success="onTemplateFormSuccess"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 规格模板创建/编辑:一个模板=一个规格维 + 规格值列表。
|
||||
*/
|
||||
import type { SpecTemplateDTO, SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
|
||||
import { h, ref } from 'vue';
|
||||
|
||||
import { useVbenModal } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Form,
|
||||
Input,
|
||||
InputNumber,
|
||||
Table,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createSpecTemplateApi,
|
||||
getSpecTemplateApi,
|
||||
updateSpecTemplateApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
|
||||
defineOptions({ name: 'SpecTemplateFormModal' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
success: [template?: SpecTemplateVO.Info];
|
||||
}>();
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const TrashIcon = createIconifyIcon('lucide:trash-2');
|
||||
|
||||
type DraftValue = {
|
||||
_key: string;
|
||||
id?: number;
|
||||
valueName: string;
|
||||
valueCode: string;
|
||||
sortOrder: number;
|
||||
};
|
||||
|
||||
const [Modal, modalApi] = useVbenModal({
|
||||
title: '规格模板',
|
||||
class: 'w-[640px]',
|
||||
draggable: true,
|
||||
contentClass: 'max-h-[70vh] overflow-y-auto',
|
||||
onConfirm: handleSubmit,
|
||||
});
|
||||
|
||||
const formRef = ref();
|
||||
const isEdit = ref(false);
|
||||
const templateId = ref<number>();
|
||||
const formData = ref({ name: '', remark: '', sortOrder: 0 });
|
||||
const values = ref<DraftValue[]>([]);
|
||||
|
||||
let keySeq = 0;
|
||||
function nextKey() {
|
||||
return `val-${++keySeq}`;
|
||||
}
|
||||
|
||||
function toDraft(list?: SpecTemplateVO.Value[]): DraftValue[] {
|
||||
return (list ?? []).map((v, i) => ({
|
||||
_key: nextKey(),
|
||||
id: v.id,
|
||||
valueName: v.valueName || '',
|
||||
valueCode: v.valueCode || '',
|
||||
sortOrder: v.sortOrder ?? i,
|
||||
}));
|
||||
}
|
||||
|
||||
function addValue() {
|
||||
values.value.push({
|
||||
_key: nextKey(),
|
||||
valueName: '',
|
||||
valueCode: '',
|
||||
sortOrder: values.value.length,
|
||||
});
|
||||
}
|
||||
|
||||
function removeValue(index: number) {
|
||||
values.value.splice(index, 1);
|
||||
}
|
||||
|
||||
function buildValuesPayload(): SpecTemplateDTO.ValueItem[] {
|
||||
return values.value.map((v, i) => ({
|
||||
id: v.id,
|
||||
valueName: v.valueName.trim(),
|
||||
valueCode: v.valueCode.trim().toUpperCase(),
|
||||
sortOrder: i,
|
||||
}));
|
||||
}
|
||||
|
||||
function validate(): string | null {
|
||||
if (!formData.value.name.trim()) return '请输入规格名称';
|
||||
if (values.value.length === 0) return '至少添加一个规格值';
|
||||
const names = new Set<string>();
|
||||
const codes = new Set<string>();
|
||||
for (const v of values.value) {
|
||||
if (!v.valueName.trim() || !v.valueCode.trim()) {
|
||||
return '规格值名称与编码不能为空';
|
||||
}
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(v.valueCode.trim())) {
|
||||
return `编码「${v.valueCode}」仅允许字母数字_-`;
|
||||
}
|
||||
const vn = v.valueName.trim();
|
||||
const vc = v.valueCode.trim().toUpperCase();
|
||||
if (names.has(vn) || codes.has(vc)) return '规格值名称或编码重复';
|
||||
names.add(vn);
|
||||
codes.add(vc);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function open(
|
||||
edit: boolean,
|
||||
record?: SpecTemplateVO.Info,
|
||||
options?: { defaultName?: string },
|
||||
) {
|
||||
isEdit.value = edit;
|
||||
templateId.value = record?.id;
|
||||
modalApi.setState({
|
||||
title: edit ? '编辑规格模板' : '新建规格模板',
|
||||
});
|
||||
if (edit && record?.id) {
|
||||
const detail = await getSpecTemplateApi(record.id);
|
||||
formData.value = {
|
||||
name: detail.name || '',
|
||||
remark: detail.remark || '',
|
||||
sortOrder: detail.sortOrder ?? 0,
|
||||
};
|
||||
values.value = toDraft(detail.values);
|
||||
} else {
|
||||
formData.value = {
|
||||
name: options?.defaultName?.trim() || '',
|
||||
remark: '',
|
||||
sortOrder: 0,
|
||||
};
|
||||
values.value = [
|
||||
{ _key: nextKey(), valueName: '', valueCode: '', sortOrder: 0 },
|
||||
];
|
||||
}
|
||||
modalApi.open();
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
await formRef.value?.validate?.();
|
||||
const err = validate();
|
||||
if (err) {
|
||||
message.error(err);
|
||||
return;
|
||||
}
|
||||
modalApi.setState({ confirmLoading: true });
|
||||
try {
|
||||
const payload = {
|
||||
name: formData.value.name.trim(),
|
||||
remark: formData.value.remark?.trim() || undefined,
|
||||
sortOrder: formData.value.sortOrder,
|
||||
values: buildValuesPayload(),
|
||||
};
|
||||
let saved: SpecTemplateVO.Info;
|
||||
if (isEdit.value && templateId.value != null) {
|
||||
saved = await updateSpecTemplateApi(templateId.value, payload);
|
||||
message.success('更新成功');
|
||||
} else {
|
||||
saved = await createSpecTemplateApi(payload);
|
||||
message.success('创建成功');
|
||||
}
|
||||
modalApi.close();
|
||||
emit('success', saved);
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
modalApi.setState({ confirmLoading: false });
|
||||
}
|
||||
}
|
||||
|
||||
const valueColumns = [
|
||||
{
|
||||
title: '规格值',
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueName,
|
||||
placeholder: '如黑色',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueName = v;
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '编码',
|
||||
width: 160,
|
||||
customRender: ({ record }: { record: DraftValue }) =>
|
||||
h(Input, {
|
||||
value: record.valueCode,
|
||||
placeholder: '如 BLK',
|
||||
'onUpdate:value': (v: string) => {
|
||||
record.valueCode = v;
|
||||
},
|
||||
onBlur: () => {
|
||||
record.valueCode = record.valueCode.trim().toUpperCase();
|
||||
},
|
||||
}),
|
||||
},
|
||||
{
|
||||
title: '',
|
||||
width: 56,
|
||||
align: 'center' as const,
|
||||
customRender: ({ index }: { index: number }) =>
|
||||
h(
|
||||
Button,
|
||||
{
|
||||
type: 'text',
|
||||
danger: true,
|
||||
onClick: () => removeValue(index),
|
||||
},
|
||||
{ icon: () => h(TrashIcon, { class: 'h-4 w-4' }) },
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
defineExpose({ open });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Modal>
|
||||
<Form ref="formRef" :model="formData" layout="vertical">
|
||||
<Form.Item
|
||||
label="规格名称"
|
||||
name="name"
|
||||
:rules="[{ required: true, message: '请输入规格名称,如颜色' }]"
|
||||
>
|
||||
<Input v-model:value="formData.name" placeholder="如颜色、尺码" />
|
||||
</Form.Item>
|
||||
<Form.Item label="备注" name="remark">
|
||||
<Input v-model:value="formData.remark" placeholder="可选" />
|
||||
</Form.Item>
|
||||
<Form.Item label="排序" name="sortOrder">
|
||||
<InputNumber v-model:value="formData.sortOrder" :min="0" class="w-32" />
|
||||
</Form.Item>
|
||||
</Form>
|
||||
|
||||
<div class="mb-2 flex items-center justify-between">
|
||||
<span class="text-sm text-foreground/80">规格值</span>
|
||||
<Button type="primary" @click="addValue">
|
||||
<template #icon>
|
||||
<PlusIcon class="h-4 w-4" />
|
||||
</template>
|
||||
添加规格值
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Table
|
||||
:columns="valueColumns"
|
||||
:data-source="values"
|
||||
:pagination="false"
|
||||
:row-key="(r: DraftValue) => r._key"
|
||||
/>
|
||||
</Modal>
|
||||
</template>
|
||||
@@ -0,0 +1,187 @@
|
||||
<script lang="ts" setup>
|
||||
/**
|
||||
* 规格模板列表:公司级单维模板(建公司或空列表时自动种子 款式/颜色/尺码/容量)。
|
||||
*/
|
||||
import type { VxeGridProps } from '#/adapter/vxe-table';
|
||||
import type { SpecTemplateVO } from '#/api/ec/product/spec-template';
|
||||
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
import { createIconifyIcon } from '@vben/icons';
|
||||
|
||||
import { Button, Popconfirm, Space, message } from 'ant-design-vue';
|
||||
|
||||
import { useVbenVxeGrid } from '#/adapter/vxe-table';
|
||||
import {
|
||||
deleteSpecTemplateApi,
|
||||
listSpecTemplatesApi,
|
||||
} from '#/api/ec/product/spec-template';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
|
||||
import SpecTemplateFormModal from './components/SpecTemplateFormModal.vue';
|
||||
|
||||
defineOptions({ name: 'SpecTemplate' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
|
||||
const loading = ref(false);
|
||||
const formModalRef = ref<InstanceType<typeof SpecTemplateFormModal> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const actionCodes = [
|
||||
'ec:product:spec-template:create',
|
||||
'ec:product:spec-template:update',
|
||||
'ec:product:spec-template:delete',
|
||||
];
|
||||
const showActionColumn = useActionColumnVisible(actionCodes);
|
||||
|
||||
function summarizeValues(row: SpecTemplateVO.Info) {
|
||||
const vals = row.values ?? [];
|
||||
if (vals.length === 0) return '-';
|
||||
return vals.map((v) => `${v.valueName}/${v.valueCode}`).join('、');
|
||||
}
|
||||
|
||||
const baseColumns: VxeGridProps<SpecTemplateVO.Info>['columns'] = [
|
||||
{ type: 'seq', width: 64, title: '序号' },
|
||||
{ field: 'name', title: '规格名称', minWidth: 120 },
|
||||
{
|
||||
field: 'values',
|
||||
title: '规格值',
|
||||
minWidth: 280,
|
||||
showOverflow: 'tooltip',
|
||||
formatter: ({ row }) => summarizeValues(row),
|
||||
},
|
||||
{
|
||||
field: 'sortOrder',
|
||||
title: '排序',
|
||||
width: 80,
|
||||
},
|
||||
{
|
||||
field: 'updateTime',
|
||||
title: '更新时间',
|
||||
minWidth: 160,
|
||||
},
|
||||
];
|
||||
|
||||
const actionColumn: NonNullable<
|
||||
VxeGridProps<SpecTemplateVO.Info>['columns']
|
||||
>[number] = {
|
||||
title: '操作',
|
||||
width: 160,
|
||||
fixed: 'right',
|
||||
slots: { default: 'action' },
|
||||
};
|
||||
|
||||
const tableColumns = computed(() =>
|
||||
showActionColumn.value
|
||||
? [...(baseColumns ?? []), actionColumn]
|
||||
: (baseColumns ?? []),
|
||||
);
|
||||
|
||||
const gridOptions: VxeGridProps<SpecTemplateVO.Info> = {
|
||||
columns: tableColumns.value,
|
||||
height: 'auto',
|
||||
border: true,
|
||||
stripe: true,
|
||||
rowConfig: { isHover: true },
|
||||
showOverflow: true,
|
||||
toolbarConfig: {
|
||||
custom: true,
|
||||
refresh: true,
|
||||
zoom: true,
|
||||
},
|
||||
data: [],
|
||||
pagerConfig: { enabled: false },
|
||||
proxyConfig: {
|
||||
ajax: {
|
||||
query: async () => {
|
||||
try {
|
||||
loading.value = true;
|
||||
const list = await listSpecTemplatesApi();
|
||||
return { items: list ?? [], total: list?.length ?? 0 };
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
message.error('加载规格模板失败');
|
||||
return { items: [], total: 0 };
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const [Grid, gridApi] = useVbenVxeGrid({
|
||||
gridOptions,
|
||||
showSearchForm: false,
|
||||
tableTitle: '规格模板',
|
||||
});
|
||||
syncVxeGridColumns(gridApi, tableColumns);
|
||||
|
||||
function refresh() {
|
||||
gridApi.reload();
|
||||
}
|
||||
|
||||
function handleAdd() {
|
||||
formModalRef.value?.open(false);
|
||||
}
|
||||
|
||||
function handleEdit(row: SpecTemplateVO.Info) {
|
||||
formModalRef.value?.open(true, row);
|
||||
}
|
||||
|
||||
async function handleDelete(row: SpecTemplateVO.Info) {
|
||||
try {
|
||||
await deleteSpecTemplateApi(row.id);
|
||||
message.success('删除成功');
|
||||
refresh();
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page title="规格模板" auto-content-height>
|
||||
<template #description>
|
||||
<div class="mt-2 text-foreground/80">
|
||||
每个模板对应一个规格维(如颜色)及其常用值。新建公司会预置款式/颜色/尺码/容量;建品时可套用。
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<PermissionGate code="ec:product:spec-template:create">
|
||||
<Button type="primary" @click="handleAdd">
|
||||
<PlusIcon class="mr-1 h-4 w-4" />
|
||||
新建模板
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</template>
|
||||
|
||||
<template
|
||||
v-if="showActionColumn"
|
||||
#action="{ row }: { row: SpecTemplateVO.Info }"
|
||||
>
|
||||
<Space>
|
||||
<PermissionGate code="ec:product:spec-template:update">
|
||||
<Button size="small" @click="handleEdit(row)">编辑</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="ec:product:spec-template:delete">
|
||||
<Popconfirm title="确定删除该模板?" @confirm="handleDelete(row)">
|
||||
<Button size="small" danger>删除</Button>
|
||||
</Popconfirm>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
</Grid>
|
||||
|
||||
<SpecTemplateFormModal ref="formModalRef" @success="refresh" />
|
||||
</Page>
|
||||
</template>
|
||||
Reference in New Issue
Block a user