product: 规格新增关联平台店铺字段,ProductSpec 支持绑定店铺列表

- ProductServiceImpl / ProductSpecServiceImpl: 规格关联平台店铺逻辑
- UpdateProductDTO: 增加 platform_shop_ids 字段
- OrderMapper: 关联查询优化
- 前端: ProductFormModal / ProductCard 适配多店铺绑定
This commit is contained in:
小蟑螂
2026-05-03 23:50:03 +08:00
parent 63e54279c0
commit 74eb45b76c
7 changed files with 279 additions and 54 deletions
@@ -34,4 +34,13 @@ public interface OrderMapper extends BaseMapper<OrderPO> {
@Param("productSpecId") Long productSpecId,
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
/**
* 新建规格后:将同公司、规格编码一致且未绑定规格的订单挂到该规格。
*/
@Update("UPDATE ec_order SET product_spec_id = #{productSpecId}, update_time = NOW() " +
"WHERE company_id = #{companyId} AND spec_code = #{specCode} AND product_spec_id IS NULL")
int linkOrdersBySpecCodeWhenSpecIdNull(@Param("companyId") Long companyId,
@Param("specCode") String specCode,
@Param("productSpecId") Long productSpecId);
}
@@ -48,12 +48,18 @@ public class UpdateProductDTO {
private Long mainImageId;
/**
* 商品规格列表(可选,仅更新提供的规格)
* 商品规格列表(可选):有 id 的项为更新,无 id 的项为在该商品下新增规格。
*/
@Schema(description = "商品规格列表(如果提供,则更新这些规格)")
@Schema(description = "商品规格列表:含 id 为更新,不含 id 为新增")
@Valid
private List<ProductSpecUpdateDTO> specs;
/**
* 编辑商品时需删除的规格 ID(与 specs 组合使用:先删再改后增)。
*/
@Schema(description = "本次需删除的规格 ID 列表(须属于当前商品)")
private List<Long> removedSpecIds;
/**
* 商品规格更新DTO(内部类)
*/
@@ -62,10 +68,9 @@ public class UpdateProductDTO {
public static class ProductSpecUpdateDTO {
/**
* 规格ID(必填,用于确定更新哪个规格)
* 规格ID(更新时必填;为空表示在该商品下新增一条规格)
*/
@Schema(description = "规格ID(必填)", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
@NotNull(message = "规格ID不能为空")
@Schema(description = "规格ID:有值则更新该规格,为空则新增", example = "1")
private Long id;
/**
@@ -13,6 +13,7 @@ import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductFilterDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.UpdateProductResultDTO;
@@ -199,6 +200,47 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
}
}
/**
* 更新商品时,本次请求内多条「新增规格」之间的规格编码不得重复(非空编码参与)。
*/
private void validateNewSpecCodesUniqueWithinRequest(List<UpdateProductDTO.ProductSpecUpdateDTO> newSpecs) {
Set<String> inputSpecCodes = new HashSet<>();
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : newSpecs) {
if (specDTO.getSpecCode() == null) {
continue;
}
String specCode = specDTO.getSpecCode().trim();
if (specCode.isEmpty()) {
continue;
}
if (!inputSpecCodes.add(specCode)) {
throw new BusinessException("请求中规格编码重复: " + specCode);
}
}
}
/**
* 更新商品时,新增规格的编码不得与公司内已有规格冲突(在删除、旧规格更新之后校验)。
*/
private void validateNewSpecCodesAgainstDatabase(List<UpdateProductDTO.ProductSpecUpdateDTO> newSpecs,
Long companyId) {
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : newSpecs) {
if (specDTO.getSpecCode() == null) {
continue;
}
String specCode = specDTO.getSpecCode().trim();
if (specCode.isEmpty()) {
continue;
}
LambdaQueryWrapper<ProductSpecPO> specCodeWrapper = new LambdaQueryWrapper<>();
specCodeWrapper.eq(ProductSpecPO::getCompanyId, companyId)
.eq(ProductSpecPO::getSpecCode, specCode);
if (productSpecService.count(specCodeWrapper) > 0) {
throw new BusinessException("规格编码已存在: " + specCode);
}
}
}
/**
* 更新商品
* @param updateProductDTO 更新商品DTO
@@ -245,11 +287,36 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
// 更新商品
this.updateById(product);
// 如果提供了规格列表,则更新对应的规格
// 先删除规格(须属于本商品),再更新已有规格,最后新增规格
List<Long> costChangedSpecIds = new ArrayList<>();
if (updateProductDTO.getRemovedSpecIds() != null && !updateProductDTO.getRemovedSpecIds().isEmpty()) {
for (Long specId : updateProductDTO.getRemovedSpecIds()) {
if (specId == null) {
continue;
}
ProductSpecPO toRemove = productSpecService.getById(specId);
if (toRemove == null || !toRemove.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在,规格ID: " + specId);
}
if (!toRemove.getProductId().equals(id)) {
throw new BusinessException("规格不属于该商品,规格ID: " + specId);
}
productSpecService.deleteProductSpec(specId);
}
}
if (updateProductDTO.getSpecs() != null && !updateProductDTO.getSpecs().isEmpty()) {
List<UpdateProductDTO.ProductSpecUpdateDTO> specDTOs = updateProductDTO.getSpecs();
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : specDTOs) {
List<UpdateProductDTO.ProductSpecUpdateDTO> newSpecs = specDTOs.stream()
.filter(s -> s.getId() == null)
.collect(Collectors.toList());
validateNewSpecCodesUniqueWithinRequest(newSpecs);
List<UpdateProductDTO.ProductSpecUpdateDTO> existingSpecs = specDTOs.stream()
.filter(s -> s.getId() != null)
.collect(Collectors.toList());
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : existingSpecs) {
// 验证规格是否存在且属于该商品
ProductSpecPO existingSpec = productSpecService.getById(specDTO.getId());
if (existingSpec == null || !existingSpec.getCompanyId().equals(companyId)) {
@@ -293,6 +360,34 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
costChangedSpecIds.add(specDTO.getId());
}
}
// 全部更新落库后再校验新增规格编码与库内冲突(避免与本次更新后的编码冲突)
validateNewSpecCodesAgainstDatabase(newSpecs, companyId);
for (UpdateProductDTO.ProductSpecUpdateDTO specDTO : newSpecs) {
LambdaQueryWrapper<ProductSpecPO> nameW = new LambdaQueryWrapper<>();
nameW.eq(ProductSpecPO::getProductId, id)
.eq(ProductSpecPO::getName, specDTO.getName())
.eq(ProductSpecPO::getCompanyId, companyId);
if (productSpecService.count(nameW) > 0) {
throw new BusinessException("规格名称已存在: " + specDTO.getName());
}
CreateProductSpecDTO createDto = new CreateProductSpecDTO();
createDto.setProductId(id);
createDto.setName(specDTO.getName());
createDto.setSpecCode(specDTO.getSpecCode());
createDto.setProductCost(specDTO.getProductCost());
createDto.setShippingCost(specDTO.getShippingCost());
createDto.setOtherCost(specDTO.getOtherCost());
createDto.setRemark(specDTO.getRemark());
ProductSpecVO createdVo = productSpecService.createProductSpec(createDto);
if (specDTO.getLinkName() != null && !specDTO.getLinkName().isBlank()) {
ProductSpecPO patch = new ProductSpecPO();
patch.setId(createdVo.getId());
patch.setLinkName(specDTO.getLinkName().trim());
productSpecService.updateById(patch);
}
}
}
// 返回结果
@@ -10,6 +10,7 @@ import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSpecMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductSpecDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductSpecFilterDTO;
@@ -33,10 +34,35 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
private final CurrentUserContext currentUserContext;
private final ProductService productService;
private final OrderMapper orderMapper;
public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService) {
public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService,
OrderMapper orderMapper) {
this.currentUserContext = currentUserContext;
this.productService = productService;
this.orderMapper = orderMapper;
}
/**
* 规格落库后(含新建):把订单表里同公司、同规格编码且 product_spec_id 为空的订单挂到本规格。
*/
@Override
public boolean save(ProductSpecPO entity) {
boolean ok = super.save(entity);
if (ok) {
relinkOrphanOrdersBySpecCode(entity.getCompanyId(), entity.getSpecCode(), entity.getId());
}
return ok;
}
private void relinkOrphanOrdersBySpecCode(Long companyId, String specCode, Long productSpecId) {
if (companyId == null || productSpecId == null) {
return;
}
if (specCode == null || specCode.isBlank()) {
return;
}
orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, specCode.trim(), productSpecId);
}
/**
@@ -27,14 +27,18 @@ export namespace ProductDTO {
categoryId?: number;
/** 主图图片ID */
mainImageId?: number;
/** 商品规格列表(如果提供,则更新这些规格) */
/** 商品规格列表:含 id 为更新,不含 id 为新增 */
specs?: UpdateSpec[];
/** 编辑时从商品上移除的规格 ID(须为打开表单时已有的规格) */
removedSpecIds?: number[];
}
/** 商品规格DTO(创建时) */
export interface Spec {
/** 规格名称 */
name: string;
/** 链接规格名称 */
linkName?: string;
/** 规格编码 */
specCode?: string;
/** 商品成本 */
@@ -67,10 +71,12 @@ export namespace ProductDTO {
/** 更新商品规格参数 */
export interface UpdateSpec {
/** 规格ID(必填,用于确定更新哪个规格) */
id: number;
/** 规格ID:有值表示更新已有规格;不传或空表示新增一条规格 */
id?: number;
/** 规格名称 */
name: string;
/** 链接规格名称 */
linkName?: string;
/** 规格编码 */
specCode?: string;
/** 商品成本 */
@@ -188,8 +188,10 @@ const goToDetails = (product: ProductVO.Info) => {
const MAX_VISIBLE_SPECS = 4;
const visibleSpecs = computed(() => (props.product.specs || []).slice(0, MAX_VISIBLE_SPECS));
/** id 仅来自后端的已有规格;新增行不传 id,用 _clientKey 做列表 key */
type EditableSpec = {
id: number;
id?: number;
_clientKey?: string;
name: string;
otherCost?: number;
productCost: number;
@@ -198,6 +200,11 @@ type EditableSpec = {
specCode?: string;
};
let nextSpecRowKey = 0;
/** 进入编辑时商品上已有的规格 ID,用于提交时生成 removedSpecIds */
const initialEditSpecIds = ref<Set<number>>(new Set());
const isEditing = ref(false);
const isSaving = ref(false);
const originalSnapshot = ref('');
@@ -232,6 +239,7 @@ const normalizeDraft = () => ({
remark: (spec.remark || '').trim(),
shippingCost: Number(spec.shippingCost || 0),
specCode: (spec.specCode || '').trim(),
...(spec._clientKey ? { _cid: spec._clientKey } : {}),
})),
});
@@ -260,6 +268,9 @@ const initDraftFromProps = () => {
specCode: spec.specCode || '',
})),
};
initialEditSpecIds.value = new Set(
(props.product.specs || []).map((s) => s.id).filter((id) => id != null),
);
newImageFile.value = null;
originalImageUrl.value = props.product.mainImage || '';
imageLoadError.value = false;
@@ -292,7 +303,7 @@ const formatCost = (val?: number) => `¥${(val ?? 0).toFixed(2)}`;
function addSpec() {
draft.value.specs.push({
id: -Date.now(),
_clientKey: `new-${++nextSpecRowKey}`,
name: '',
otherCost: 0,
productCost: 0,
@@ -391,23 +402,37 @@ const saveEdit = async () => {
if (newImageFile.value) {
mainImageId = await uploadImageAndGetId();
}
const keptSpecIds = new Set(
draft.value.specs
.map((s) => s.id)
.filter((id): id is number => id != null && id > 0),
);
const removedSpecIds = [...initialEditSpecIds.value].filter(
(sid) => !keptSpecIds.has(sid),
);
const specsPayload = draft.value.specs.map((spec) => {
const base = {
name: spec.name.trim(),
otherCost: Number(spec.otherCost || 0),
productCost: Number(spec.productCost || 0),
remark: (spec.remark || '').trim(),
shippingCost: Number(spec.shippingCost || 0),
specCode: spec.specCode?.trim() || undefined,
};
if (spec.id != null && spec.id > 0) {
return { id: spec.id, ...base } as ProductDTO.UpdateSpec;
}
return { ...base } as ProductDTO.UpdateSpec;
});
const payload: ProductDTO.Update = {
name: draft.value.name.trim(),
productCode: draft.value.productCode.trim() || undefined,
categoryId: draft.value.categoryId,
mainImageId,
specs: draft.value.specs.map((spec) => {
const base = {
name: spec.name.trim(),
otherCost: Number(spec.otherCost || 0),
productCost: Number(spec.productCost || 0),
remark: (spec.remark || '').trim(),
shippingCost: Number(spec.shippingCost || 0),
specCode: spec.specCode?.trim() || undefined,
};
if (spec.id < 0) return base as ProductDTO.UpdateSpec;
return { id: spec.id, ...base } as ProductDTO.UpdateSpec;
}),
...(draft.value.specs.length > 0 && { specs: specsPayload }),
...(removedSpecIds.length > 0 && { removedSpecIds }),
};
const result = await updateProductApi(props.product.id, payload);
message.success('商品保存成功');
@@ -537,7 +562,7 @@ const saveEdit = async () => {
</div>
<div
v-for="(spec, index) in displaySpecs"
:key="spec.id"
:key="isEditing ? spec.id ?? spec._clientKey ?? `idx-${index}` : spec.id"
class="spec-row"
:class="{ 'editing-row': isEditing }"
>
@@ -197,10 +197,20 @@ const formData = ref({
// 类目选项列表
const categoryOptions = ref<any[]>([]);
/** 表格行稳定 key(新增行无 id) */
type SpecFormRow = (ProductDTO.Spec | ProductDTO.UpdateSpec) & {
_clientKey?: string;
};
// 规格数据 - 支持创建和更新
const specs = ref<Array<ProductDTO.Spec | ProductDTO.UpdateSpec>>([]);
const specs = ref<SpecFormRow[]>([]);
const showSpecs = ref(false);
/** 编辑打开时已有的规格 ID,用于提交时计算 removedSpecIds */
const initialEditSpecIds = ref<Set<number>>(new Set());
let nextSpecClientKey = 0;
// 当前显示的图片 URL(优先显示新选择的)
const currentImageUrl = computed(() => {
if (newImageFile.value) {
@@ -245,6 +255,7 @@ function initFormData() {
) {
const mapSpec = (spec: ProductVO.SpecInfo) => ({
name: spec.name || spec.specCode || '',
linkName: spec.linkName || '',
specCode: spec.specCode || '',
productCost: spec.productCost ?? 0,
shippingCost: spec.shippingCost ?? 0,
@@ -252,18 +263,30 @@ function initFormData() {
remark: spec.remark || '',
});
specs.value = isEdit.value
? currentProductData.value.specs.map(
(spec) =>
({
id: (spec as ProductVO.SpecInfo).id,
...mapSpec(spec as ProductVO.SpecInfo),
}) as ProductDTO.UpdateSpec,
)
: currentProductData.value.specs.map((spec) =>
mapSpec(spec as ProductVO.SpecInfo),
);
? currentProductData.value.specs.map((spec) => {
const s = spec as ProductVO.SpecInfo;
return {
id: s.id,
_clientKey: `exist-${s.id}`,
...mapSpec(s),
} as SpecFormRow;
})
: currentProductData.value.specs.map((spec) => ({
_clientKey: `seed-${++nextSpecClientKey}`,
...mapSpec(spec as ProductVO.SpecInfo),
}));
showSpecs.value = specs.value.length > 0;
}
if (isEdit.value) {
initialEditSpecIds.value = new Set(
specs.value
.map((s) => (s.id != null ? Number(s.id) : null))
.filter((x): x is number => x != null),
);
} else {
initialEditSpecIds.value = new Set();
}
}
// 重置表单(在open方法中调用)
@@ -274,6 +297,7 @@ function resetForm() {
imageLoadError.value = false;
specs.value = [];
showSpecs.value = false;
initialEditSpecIds.value = new Set();
categoryOptions.value = [];
}
@@ -304,14 +328,49 @@ async function handleSubmit() {
'id' in currentProductData.value &&
currentProductData.value.id
) {
const keptSpecIds = new Set(
specs.value
.map((s) => (s.id != null ? Number(s.id) : null))
.filter((x): x is number => x != null),
);
const removedSpecIds = [...initialEditSpecIds.value].filter(
(sid) => !keptSpecIds.has(sid),
);
const specsPayload: ProductDTO.UpdateSpec[] = specs.value.map((row) => {
const {
_clientKey: _c,
id,
name,
linkName,
specCode,
productCost,
shippingCost,
otherCost,
remark,
} = row;
const base = {
name,
linkName: linkName || undefined,
specCode: specCode ?? '',
productCost: productCost ?? 0,
shippingCost: shippingCost ?? 0,
otherCost: otherCost ?? 0,
remark: remark ?? '',
};
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,
...(specs.value.length > 0 && {
specs: specs.value as ProductDTO.UpdateSpec[],
}),
...(specs.value.length > 0 && { specs: specsPayload }),
...(removedSpecIds.length > 0 && { removedSpecIds }),
};
const result = await updateProductApi(currentProductData.value.id, updateData);
if (specs.value.length > 0 && result.costChangedSpecIds?.length > 0) {
@@ -327,7 +386,9 @@ async function handleSubmit() {
productCode: submitData.productCode || undefined,
categoryId: submitData.categoryId,
mainImageId: submitData.mainImageId,
...(specs.value.length > 0 && { specs: specs.value }),
...(specs.value.length > 0 && {
specs: specs.value.map(({ _clientKey: _c, id: _id, ...rest }) => rest),
}),
};
await createProductApi(createData);
if (specs.value.length > 0) {
@@ -429,8 +490,10 @@ function removeNewImage() {
message.success('已重置图片');
}
const defaultSpec = (): ProductDTO.Spec => ({
const defaultSpec = (): SpecFormRow => ({
_clientKey: `new-${++nextSpecClientKey}`,
name: '',
linkName: '',
specCode: '',
productCost: 0,
shippingCost: 0,
@@ -440,11 +503,7 @@ const defaultSpec = (): ProductDTO.Spec => ({
// 添加规格
function addSpec() {
if (isEdit.value) {
specs.value.push(defaultSpec() as ProductDTO.Spec);
} else {
specs.value.push(defaultSpec());
}
specs.value.push(defaultSpec());
}
// 删除规格
@@ -462,7 +521,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(Input, {
value: record.name,
@@ -481,7 +540,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(Input, {
value: record.specCode,
@@ -500,7 +559,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(InputNumber, {
value: record.productCost,
@@ -522,7 +581,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(InputNumber, {
value: record.shippingCost ?? 0,
@@ -544,7 +603,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(InputNumber, {
value: record.otherCost ?? 0,
@@ -566,7 +625,7 @@ const specColumns = [
customRender: ({
record,
}: {
record: ProductDTO.Spec | ProductDTO.UpdateSpec;
record: SpecFormRow;
}) => {
return h(Input, {
value: record.remark ?? '',
@@ -792,7 +851,7 @@ onUnmounted(() => {
:columns="specColumns"
:data-source="specs"
:pagination="false"
row-key="index"
:row-key="(r: SpecFormRow) => (r.id != null ? String(r.id) : r._clientKey ?? '')"
size="small"
>
<template #emptyText>