feat: 优化商品编辑

This commit is contained in:
2026-08-18 23:05:53 +08:00
parent 9dd4977e09
commit 12bb03a43f
12 changed files with 660 additions and 246 deletions
@@ -42,6 +42,13 @@ public class ProductController {
return ApiResponse.success("商品更新成功", result);
}
@PostMapping("/{id}/migrate-sku/{skuId}")
@RequirePermission(value = "ec:product:update", description = "迁入他品SKU", allowSuper = true)
public ApiResponse<ProductVO> migrateSkuToProduct(@PathVariable Long id, @PathVariable Long skuId) {
ProductVO product = productService.migrateSkuToProduct(id, skuId);
return ApiResponse.success("SKU 迁入成功", product);
}
@DeleteMapping("/delete/{id}")
@RequirePermission(value = "ec:product:delete", description = "删除商品", allowSuper = true)
public ApiResponse<Void> deleteProduct(
@@ -10,6 +10,9 @@ public class ProductSkuFilterDTO {
private Long productId;
/** 排除该商品下的 SKU(迁入搜索用) */
private Long excludeProductId;
private Long id;
private String name;
@@ -23,14 +23,16 @@ public class UpdateProductDTO {
private Long mainImageId;
/**
* 传入则按全量同步:id&gt;0 更新,id 为 null/0 新增,库中有但未出现的删除。
*/
@Valid
private List<ProductSkuUpdateDTO> skus;
private List<Long> removedSkuIds;
@Data
public static class ProductSkuUpdateDTO {
/** 已有 SKU 的 ID;0 或空表示新增 */
private Long id;
@NotBlank(message = "SKU名称不能为空")
@@ -34,6 +34,11 @@ public interface ProductService extends IService<ProductPO> {
*/
UpdateProductResultDTO updateProduct(UpdateProductDTO updateProductDTO, Long id);
/**
* 将他品 SKU 迁入当前商品(同公司;编码已全局唯一,名称不得与目标商品冲突)。
*/
ProductVO migrateSkuToProduct(Long productId, Long skuId);
/**
* 删除商品
*
@@ -35,9 +35,11 @@ import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@@ -231,27 +233,157 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
throw new BusinessException("请求中规格编码重复: " + skuCode);
}
// 2) 与数据库同公司已有规格编码冲突时由落库逻辑合并到已有行,此处不再校验
// 2) 公司内已占用
ProductSkuPO existed = productSkuService.getByCompanyIdAndSkuCode(companyId, skuCode);
if (existed != null) {
throw new BusinessException("规格编码已存在: " + skuCode);
}
}
}
/**
* 更新商品时,本次请求内多条「新增规格」之间的规格编码不得重复(非空编码参与)。
* 有 id 更新,id 为 0/空 新增,库中有但请求未带的删除。编码/名称重复则失败。
*/
private void validateNewSkuCodesUniqueWithinRequest(List<UpdateProductDTO.ProductSkuUpdateDTO> newSpecs) {
Set<String> inputSkuCodes = new HashSet<>();
for (UpdateProductDTO.ProductSkuUpdateDTO specDTO : newSpecs) {
if (specDTO.getSkuCode() == null) {
continue;
}
String skuCode = specDTO.getSkuCode().trim();
if (skuCode.isEmpty()) {
continue;
}
if (!inputSkuCodes.add(skuCode)) {
throw new BusinessException("请求中规格编码重复: " + skuCode);
private void syncProductSkus(Long productId, Long companyId,
List<UpdateProductDTO.ProductSkuUpdateDTO> incoming,
List<Long> rawCostChangedSkuIds, Collection<Long> newSkuIdsFromCodeWithOrders) {
LambdaQueryWrapper<ProductSkuPO> existingW = new LambdaQueryWrapper<>();
existingW.eq(ProductSkuPO::getProductId, productId).eq(ProductSkuPO::getCompanyId, companyId);
List<ProductSkuPO> existing = productSkuService.list(existingW);
Map<Long, ProductSkuPO> existingById = new HashMap<>();
for (ProductSkuPO sku : existing) {
existingById.put(sku.getId(), sku);
}
List<UpdateProductDTO.ProductSkuUpdateDTO> toUpdate = new ArrayList<>();
List<UpdateProductDTO.ProductSkuUpdateDTO> toCreate = new ArrayList<>();
Set<Long> incomingIds = new HashSet<>();
for (UpdateProductDTO.ProductSkuUpdateDTO row : incoming) {
if (isPersistedSkuId(row.getId())) {
toUpdate.add(row);
incomingIds.add(row.getId());
} else {
toCreate.add(row);
}
}
for (UpdateProductDTO.ProductSkuUpdateDTO row : toUpdate) {
ProductSkuPO found = existingById.get(row.getId());
if (found == null) {
throw new BusinessException("规格不存在,规格ID: " + row.getId());
}
}
validateIncomingSkuUniqueness(companyId, incoming, existingById.keySet(), incomingIds);
for (ProductSkuPO sku : existing) {
if (!incomingIds.contains(sku.getId())) {
productSkuService.deleteProductSku(sku.getId());
}
}
for (UpdateProductDTO.ProductSkuUpdateDTO row : toUpdate) {
UpdateProductSkuDTO updateDto = new UpdateProductSkuDTO();
updateDto.setName(row.getName());
updateDto.setSkuCode(row.getSkuCode());
updateDto.setRemark(row.getRemark());
updateDto.setImageId(row.getImageId());
productSkuService.updateProductSku(updateDto, row.getId());
}
for (UpdateProductDTO.ProductSkuUpdateDTO row : toCreate) {
CreateProductSkuDTO createDto = new CreateProductSkuDTO();
createDto.setProductId(productId);
createDto.setName(row.getName());
createDto.setSkuCode(row.getSkuCode());
createDto.setProductCost(row.getProductCost());
createDto.setShippingCost(row.getShippingCost());
createDto.setOtherCost(row.getOtherCost());
createDto.setRemark(row.getRemark());
createDto.setImageId(row.getImageId());
ProductSkuVO createdVo = productSkuService.createProductSku(createDto);
if (Boolean.TRUE.equals(createdVo.getCostChanged()) && createdVo.getId() != null) {
rawCostChangedSkuIds.add(createdVo.getId());
}
appendSpecIdIfSkuCodeHasLinkedOrders(companyId, createdVo.getId(), row.getSkuCode(),
row.getProductCost(), row.getShippingCost(), row.getOtherCost(),
newSkuIdsFromCodeWithOrders);
}
}
/** 请求内名称/编码不得重复;公司内编码不得占用(排除本次保留的 id 与即将删除的 id)。 */
private void validateIncomingSkuUniqueness(Long companyId,
List<UpdateProductDTO.ProductSkuUpdateDTO> incoming,
Set<Long> existingIds, Set<Long> keepIds) {
Set<String> names = new HashSet<>();
Set<String> codes = new HashSet<>();
Set<Long> reusableIds = new HashSet<>(keepIds);
for (Long existingId : existingIds) {
if (!keepIds.contains(existingId)) {
reusableIds.add(existingId);
}
}
for (UpdateProductDTO.ProductSkuUpdateDTO row : incoming) {
String name = row.getName() == null ? "" : row.getName().trim();
if (!names.add(name)) {
throw new BusinessException("规格名称已存在: " + name);
}
String code = row.getSkuCode() == null ? "" : row.getSkuCode().trim();
if (code.isEmpty()) {
throw new BusinessException("SKU编码不能为空");
}
if (!codes.add(code)) {
throw new BusinessException("请求中规格编码重复: " + code);
}
}
for (UpdateProductDTO.ProductSkuUpdateDTO row : incoming) {
String code = row.getSkuCode().trim();
ProductSkuPO byCode = productSkuService.getByCompanyIdAndSkuCode(companyId, code);
if (byCode == null) {
continue;
}
boolean self = isPersistedSkuId(row.getId()) && byCode.getId().equals(row.getId());
boolean willDelete = reusableIds.contains(byCode.getId()) && !keepIds.contains(byCode.getId());
if (!self && !willDelete) {
throw new BusinessException("规格编码已存在: " + code);
}
}
}
private static boolean isPersistedSkuId(Long id) {
return id != null && id > 0;
}
@Override
@Transactional
public ProductVO migrateSkuToProduct(Long productId, Long skuId) {
Long companyId = currentUserContext.getCurrentCompanyId();
ProductPO target = this.getById(productId);
if (target == null || !target.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
ProductSkuPO sku = productSkuService.getById(skuId);
if (sku == null || !sku.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在");
}
if (sku.getProductId().equals(productId)) {
throw new BusinessException("该 SKU 已属于当前商品");
}
LambdaQueryWrapper<ProductSkuPO> nameW = new LambdaQueryWrapper<>();
nameW.eq(ProductSkuPO::getProductId, productId)
.eq(ProductSkuPO::getCompanyId, companyId)
.eq(ProductSkuPO::getName, sku.getName());
if (productSkuService.count(nameW) > 0) {
throw new BusinessException("规格名称已存在: " + sku.getName());
}
sku.setProductId(productId);
sku.setUpdateBy(currentUserContext.getCurrentUserId());
productSkuService.updateById(sku);
return convertToVO(target);
}
/**
@@ -300,108 +432,11 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
// 更新商品
this.updateById(product);
// 先删除规格(须属于本商品),再更新已有规格,最后新增规格
List<Long> rawCostChangedSkuIds = new ArrayList<>();
LinkedHashSet<Long> newSkuIdsFromCodeWithOrders = new LinkedHashSet<>();
if (updateProductDTO.getRemovedSkuIds() != null && !updateProductDTO.getRemovedSkuIds().isEmpty()) {
for (Long skuId : updateProductDTO.getRemovedSkuIds()) {
if (skuId == null) {
continue;
}
ProductSkuPO toRemove = productSkuService.getById(skuId);
if (toRemove == null || !toRemove.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在,规格ID: " + skuId);
}
if (!toRemove.getProductId().equals(id)) {
throw new BusinessException("规格不属于该商品,规格ID: " + skuId);
}
productSkuService.deleteProductSku(skuId);
}
}
if (updateProductDTO.getSkus() != null && !updateProductDTO.getSkus().isEmpty()) {
List<UpdateProductDTO.ProductSkuUpdateDTO> specDTOs = updateProductDTO.getSkus();
List<UpdateProductDTO.ProductSkuUpdateDTO> newSpecs = specDTOs.stream()
.filter(s -> s.getId() == null)
.collect(Collectors.toList());
validateNewSkuCodesUniqueWithinRequest(newSpecs);
List<UpdateProductDTO.ProductSkuUpdateDTO> existingSkus = specDTOs.stream()
.filter(s -> s.getId() != null)
.collect(Collectors.toList());
for (UpdateProductDTO.ProductSkuUpdateDTO specDTO : existingSkus) {
// 验证规格是否存在且属于该商品
ProductSkuPO existingSku = productSkuService.getById(specDTO.getId());
if (existingSku == null || !existingSku.getCompanyId().equals(companyId)) {
throw new BusinessException("规格不存在,规格ID: " + specDTO.getId());
}
if (!existingSku.getProductId().equals(id)) {
throw new BusinessException("规格不属于该商品,规格ID: " + specDTO.getId());
}
// 验证规格名称是否重复(排除当前规格)
LambdaQueryWrapper<ProductSkuPO> skuNameWrapper = new LambdaQueryWrapper<>();
skuNameWrapper.eq(ProductSkuPO::getProductId, id)
.eq(ProductSkuPO::getName, specDTO.getName())
.eq(ProductSkuPO::getCompanyId, companyId)
.ne(ProductSkuPO::getId, specDTO.getId());
if (productSkuService.count(skuNameWrapper) > 0) {
throw new BusinessException("规格名称已存在: " + specDTO.getName());
}
// 验证规格编码是否重复(如果不为空,排除当前规格)
if (specDTO.getSkuCode() != null && !specDTO.getSkuCode().trim().isEmpty()) {
LambdaQueryWrapper<ProductSkuPO> skuCodeWrapper = new LambdaQueryWrapper<>();
skuCodeWrapper.eq(ProductSkuPO::getSkuCode, specDTO.getSkuCode().trim())
.eq(ProductSkuPO::getCompanyId, companyId)
.ne(ProductSkuPO::getId, specDTO.getId());
if (productSkuService.count(skuCodeWrapper) > 0) {
throw new BusinessException("规格编码已存在: " + specDTO.getSkuCode());
}
}
// 更新规格(成本变更请走独立调价接口)
UpdateProductSkuDTO updateSpecDto = new UpdateProductSkuDTO();
updateSpecDto.setName(specDTO.getName());
updateSpecDto.setSkuCode(specDTO.getSkuCode());
updateSpecDto.setRemark(specDTO.getRemark());
updateSpecDto.setImageId(specDTO.getImageId());
productSkuService.updateProductSku(updateSpecDto, specDTO.getId());
}
for (UpdateProductDTO.ProductSkuUpdateDTO specDTO : newSpecs) {
ProductSkuPO mergeByCode = null;
if (specDTO.getSkuCode() != null && !specDTO.getSkuCode().trim().isEmpty()) {
mergeByCode = productSkuService.getByCompanyIdAndSkuCode(companyId, specDTO.getSkuCode().trim());
}
LambdaQueryWrapper<ProductSkuPO> nameW = new LambdaQueryWrapper<>();
nameW.eq(ProductSkuPO::getProductId, id)
.eq(ProductSkuPO::getName, specDTO.getName())
.eq(ProductSkuPO::getCompanyId, companyId);
if (mergeByCode != null) {
nameW.ne(ProductSkuPO::getId, mergeByCode.getId());
}
if (productSkuService.count(nameW) > 0) {
throw new BusinessException("规格名称已存在: " + specDTO.getName());
}
CreateProductSkuDTO createDto = new CreateProductSkuDTO();
createDto.setProductId(id);
createDto.setName(specDTO.getName());
createDto.setSkuCode(specDTO.getSkuCode());
createDto.setProductCost(specDTO.getProductCost());
createDto.setShippingCost(specDTO.getShippingCost());
createDto.setOtherCost(specDTO.getOtherCost());
createDto.setRemark(specDTO.getRemark());
createDto.setImageId(specDTO.getImageId());
ProductSkuVO createdVo = productSkuService.createProductSku(createDto);
if (Boolean.TRUE.equals(createdVo.getCostChanged()) && createdVo.getId() != null) {
rawCostChangedSkuIds.add(createdVo.getId());
}
appendSpecIdIfSkuCodeHasLinkedOrders(companyId, createdVo.getId(), specDTO.getSkuCode(),
specDTO.getProductCost(), specDTO.getShippingCost(), specDTO.getOtherCost(),
newSkuIdsFromCodeWithOrders);
}
if (updateProductDTO.getSkus() != null) {
syncProductSkus(id, companyId, updateProductDTO.getSkus(),
rawCostChangedSkuIds, newSkuIdsFromCodeWithOrders);
}
// 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格
@@ -34,6 +34,7 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -87,7 +88,7 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
public ProductSkuVO createProductSku(CreateProductSkuDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
Long createBy = currentUserContext.getCurrentUserId();
return createOrMergeSkuByCompanyCode(dto, companyId, createBy);
return createSkuStrict(dto, companyId, createBy);
}
@Override
@@ -108,6 +109,13 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
throw new BusinessException("SKU名称已存在");
}
if (dto.getSkuCode() != null && !dto.getSkuCode().trim().isEmpty()) {
ProductSkuPO byCode = getByCompanyIdAndSkuCode(companyId, dto.getSkuCode().trim());
if (byCode != null && !byCode.getId().equals(id)) {
throw new BusinessException("规格编码已存在: " + dto.getSkuCode().trim());
}
}
// 调价走独立成本接口;此处只更新 SKU 基础字段
ProductSkuPO sku = new ProductSkuPO();
sku.setId(id);
@@ -151,6 +159,9 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
if (filter.getProductId() != null) {
wrapper.eq(ProductSkuPO::getProductId, filter.getProductId());
}
if (filter.getExcludeProductId() != null) {
wrapper.ne(ProductSkuPO::getProductId, filter.getExcludeProductId());
}
if (filter.getKeywords() != null && !filter.getKeywords().trim().isEmpty()) {
String keywords = filter.getKeywords().trim();
wrapper.and(w -> w
@@ -170,9 +181,29 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
wrapper.orderByDesc(ProductSkuPO::getCreateTime);
IPage<ProductSkuPO> pageResult = this.page(page, wrapper);
List<ProductSkuVO> voList = toVoList(pageResult.getRecords());
fillProductNames(voList);
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
}
/** 列表展示所属商品名称 */
private void fillProductNames(List<ProductSkuVO> vos) {
if (vos == null || vos.isEmpty()) {
return;
}
Set<Long> productIds = vos.stream()
.map(ProductSkuVO::getProductId)
.filter(id -> id != null)
.collect(Collectors.toSet());
if (productIds.isEmpty()) {
return;
}
Map<Long, String> names = productService.listByIds(productIds).stream()
.collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a));
for (ProductSkuVO vo : vos) {
vo.setProductName(names.get(vo.getProductId()));
}
}
@Override
public ProductSkuVO getProductSkuByProductAndSku(String productName, String skuCode) {
Long companyId = currentUserContext.getCurrentCompanyId();
@@ -249,6 +280,31 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
return createOrMergeSkuByCompanyCode(dto, companyId, userId);
}
private ProductSkuVO createSkuStrict(CreateProductSkuDTO dto, Long companyId, Long createByUserId) {
ProductPO product = productService.getById(dto.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
String trimmedCode = dto.getSkuCode() != null ? dto.getSkuCode().trim() : "";
if (!trimmedCode.isEmpty()) {
ProductSkuPO byCode = getByCompanyIdAndSkuCode(companyId, trimmedCode);
if (byCode != null) {
throw new BusinessException("规格编码已存在: " + trimmedCode);
}
}
LambdaQueryWrapper<ProductSkuPO> nameOnly = new LambdaQueryWrapper<>();
nameOnly.eq(ProductSkuPO::getProductId, dto.getProductId())
.eq(ProductSkuPO::getName, dto.getName())
.eq(ProductSkuPO::getCompanyId, companyId);
if (this.count(nameOnly) > 0) {
throw new BusinessException("SKU名称已存在");
}
return insertNewSku(dto, companyId, createByUserId, trimmedCode);
}
private ProductSkuVO createOrMergeSkuByCompanyCode(CreateProductSkuDTO dto, Long companyId, Long createByUserId) {
ProductPO product = productService.getById(dto.getProductId());
if (product == null || !product.getCompanyId().equals(companyId)) {
@@ -310,6 +366,10 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
throw new BusinessException("SKU名称已存在");
}
return insertNewSku(dto, companyId, createByUserId, trimmedCode);
}
private ProductSkuVO insertNewSku(CreateProductSkuDTO dto, Long companyId, Long createByUserId, String trimmedCode) {
ProductSkuPO sku = new ProductSkuPO();
BeanCopyUtils.copyProperties(dto, sku);
sku.setCompanyId(companyId);