mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-25 01:09:19 +08:00
feat: 优化商品编辑
This commit is contained in:
+7
@@ -42,6 +42,13 @@ public class ProductController {
|
|||||||
return ApiResponse.success("商品更新成功", result);
|
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}")
|
@DeleteMapping("/delete/{id}")
|
||||||
@RequirePermission(value = "ec:product:delete", description = "删除商品", allowSuper = true)
|
@RequirePermission(value = "ec:product:delete", description = "删除商品", allowSuper = true)
|
||||||
public ApiResponse<Void> deleteProduct(
|
public ApiResponse<Void> deleteProduct(
|
||||||
|
|||||||
+3
@@ -10,6 +10,9 @@ public class ProductSkuFilterDTO {
|
|||||||
|
|
||||||
private Long productId;
|
private Long productId;
|
||||||
|
|
||||||
|
/** 排除该商品下的 SKU(迁入搜索用) */
|
||||||
|
private Long excludeProductId;
|
||||||
|
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
private String name;
|
private String name;
|
||||||
|
|||||||
+4
-2
@@ -23,14 +23,16 @@ public class UpdateProductDTO {
|
|||||||
|
|
||||||
private Long mainImageId;
|
private Long mainImageId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 传入则按全量同步:id>0 更新,id 为 null/0 新增,库中有但未出现的删除。
|
||||||
|
*/
|
||||||
@Valid
|
@Valid
|
||||||
private List<ProductSkuUpdateDTO> skus;
|
private List<ProductSkuUpdateDTO> skus;
|
||||||
|
|
||||||
private List<Long> removedSkuIds;
|
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
public static class ProductSkuUpdateDTO {
|
public static class ProductSkuUpdateDTO {
|
||||||
|
|
||||||
|
/** 已有 SKU 的 ID;0 或空表示新增 */
|
||||||
private Long id;
|
private Long id;
|
||||||
|
|
||||||
@NotBlank(message = "SKU名称不能为空")
|
@NotBlank(message = "SKU名称不能为空")
|
||||||
|
|||||||
+5
@@ -34,6 +34,11 @@ public interface ProductService extends IService<ProductPO> {
|
|||||||
*/
|
*/
|
||||||
UpdateProductResultDTO updateProduct(UpdateProductDTO updateProductDTO, Long id);
|
UpdateProductResultDTO updateProduct(UpdateProductDTO updateProductDTO, Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将他品 SKU 迁入当前商品(同公司;编码已全局唯一,名称不得与目标商品冲突)。
|
||||||
|
*/
|
||||||
|
ProductVO migrateSkuToProduct(Long productId, Long skuId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 删除商品
|
* 删除商品
|
||||||
*
|
*
|
||||||
|
|||||||
+150
-115
@@ -35,9 +35,11 @@ import top.xyquan.ecomdmbbackend.utils.SysFileUtils;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.LinkedHashSet;
|
import java.util.HashMap;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.LinkedHashSet;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
@@ -231,27 +233,157 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
|||||||
throw new BusinessException("请求中规格编码重复: " + skuCode);
|
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) {
|
private void syncProductSkus(Long productId, Long companyId,
|
||||||
Set<String> inputSkuCodes = new HashSet<>();
|
List<UpdateProductDTO.ProductSkuUpdateDTO> incoming,
|
||||||
for (UpdateProductDTO.ProductSkuUpdateDTO specDTO : newSpecs) {
|
List<Long> rawCostChangedSkuIds, Collection<Long> newSkuIdsFromCodeWithOrders) {
|
||||||
if (specDTO.getSkuCode() == null) {
|
LambdaQueryWrapper<ProductSkuPO> existingW = new LambdaQueryWrapper<>();
|
||||||
continue;
|
existingW.eq(ProductSkuPO::getProductId, productId).eq(ProductSkuPO::getCompanyId, companyId);
|
||||||
}
|
List<ProductSkuPO> existing = productSkuService.list(existingW);
|
||||||
String skuCode = specDTO.getSkuCode().trim();
|
Map<Long, ProductSkuPO> existingById = new HashMap<>();
|
||||||
if (skuCode.isEmpty()) {
|
for (ProductSkuPO sku : existing) {
|
||||||
continue;
|
existingById.put(sku.getId(), sku);
|
||||||
}
|
}
|
||||||
if (!inputSkuCodes.add(skuCode)) {
|
|
||||||
throw new BusinessException("请求中规格编码重复: " + skuCode);
|
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);
|
this.updateById(product);
|
||||||
|
|
||||||
// 先删除规格(须属于本商品),再更新已有规格,最后新增规格
|
|
||||||
List<Long> rawCostChangedSkuIds = new ArrayList<>();
|
List<Long> rawCostChangedSkuIds = new ArrayList<>();
|
||||||
LinkedHashSet<Long> newSkuIdsFromCodeWithOrders = new LinkedHashSet<>();
|
LinkedHashSet<Long> newSkuIdsFromCodeWithOrders = new LinkedHashSet<>();
|
||||||
if (updateProductDTO.getRemovedSkuIds() != null && !updateProductDTO.getRemovedSkuIds().isEmpty()) {
|
if (updateProductDTO.getSkus() != null) {
|
||||||
for (Long skuId : updateProductDTO.getRemovedSkuIds()) {
|
syncProductSkus(id, companyId, updateProductDTO.getSkus(),
|
||||||
if (skuId == null) {
|
rawCostChangedSkuIds, newSkuIdsFromCodeWithOrders);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格
|
// 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格
|
||||||
|
|||||||
+61
-1
@@ -34,6 +34,7 @@ import java.util.Collection;
|
|||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.Set;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -87,7 +88,7 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
public ProductSkuVO createProductSku(CreateProductSkuDTO dto) {
|
public ProductSkuVO createProductSku(CreateProductSkuDTO dto) {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
Long createBy = currentUserContext.getCurrentUserId();
|
Long createBy = currentUserContext.getCurrentUserId();
|
||||||
return createOrMergeSkuByCompanyCode(dto, companyId, createBy);
|
return createSkuStrict(dto, companyId, createBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -108,6 +109,13 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
throw new BusinessException("SKU名称已存在");
|
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 基础字段
|
// 调价走独立成本接口;此处只更新 SKU 基础字段
|
||||||
ProductSkuPO sku = new ProductSkuPO();
|
ProductSkuPO sku = new ProductSkuPO();
|
||||||
sku.setId(id);
|
sku.setId(id);
|
||||||
@@ -151,6 +159,9 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
if (filter.getProductId() != null) {
|
if (filter.getProductId() != null) {
|
||||||
wrapper.eq(ProductSkuPO::getProductId, filter.getProductId());
|
wrapper.eq(ProductSkuPO::getProductId, filter.getProductId());
|
||||||
}
|
}
|
||||||
|
if (filter.getExcludeProductId() != null) {
|
||||||
|
wrapper.ne(ProductSkuPO::getProductId, filter.getExcludeProductId());
|
||||||
|
}
|
||||||
if (filter.getKeywords() != null && !filter.getKeywords().trim().isEmpty()) {
|
if (filter.getKeywords() != null && !filter.getKeywords().trim().isEmpty()) {
|
||||||
String keywords = filter.getKeywords().trim();
|
String keywords = filter.getKeywords().trim();
|
||||||
wrapper.and(w -> w
|
wrapper.and(w -> w
|
||||||
@@ -170,9 +181,29 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
wrapper.orderByDesc(ProductSkuPO::getCreateTime);
|
wrapper.orderByDesc(ProductSkuPO::getCreateTime);
|
||||||
IPage<ProductSkuPO> pageResult = this.page(page, wrapper);
|
IPage<ProductSkuPO> pageResult = this.page(page, wrapper);
|
||||||
List<ProductSkuVO> voList = toVoList(pageResult.getRecords());
|
List<ProductSkuVO> voList = toVoList(pageResult.getRecords());
|
||||||
|
fillProductNames(voList);
|
||||||
return PageResultVO.create(voList, pageResult.getTotal(), pageQueryDTO.getPage(), pageQueryDTO.getPageSize());
|
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
|
@Override
|
||||||
public ProductSkuVO getProductSkuByProductAndSku(String productName, String skuCode) {
|
public ProductSkuVO getProductSkuByProductAndSku(String productName, String skuCode) {
|
||||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||||
@@ -249,6 +280,31 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
return createOrMergeSkuByCompanyCode(dto, companyId, userId);
|
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) {
|
private ProductSkuVO createOrMergeSkuByCompanyCode(CreateProductSkuDTO dto, Long companyId, Long createByUserId) {
|
||||||
ProductPO product = productService.getById(dto.getProductId());
|
ProductPO product = productService.getById(dto.getProductId());
|
||||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||||
@@ -310,6 +366,10 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
|||||||
throw new BusinessException("SKU名称已存在");
|
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();
|
ProductSkuPO sku = new ProductSkuPO();
|
||||||
BeanCopyUtils.copyProperties(dto, sku);
|
BeanCopyUtils.copyProperties(dto, sku);
|
||||||
sku.setCompanyId(companyId);
|
sku.setCompanyId(companyId);
|
||||||
|
|||||||
@@ -43,3 +43,12 @@ export async function updateProductApi(id: number, data: ProductDTO.Update) {
|
|||||||
export async function deleteProductApi(id: number) {
|
export async function deleteProductApi(id: number) {
|
||||||
return requestClient.delete(`/ec/product/delete/${id}`);
|
return requestClient.delete(`/ec/product/delete/${id}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将他品 SKU 迁入当前商品
|
||||||
|
*/
|
||||||
|
export async function migrateSkuToProductApi(productId: number, skuId: number) {
|
||||||
|
return requestClient.post<ProductVO.Info>(
|
||||||
|
`/ec/product/${productId}/migrate-sku/${skuId}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -47,6 +47,8 @@ export namespace ProductSkuDTO {
|
|||||||
export interface Filters {
|
export interface Filters {
|
||||||
/** 商品 ID */
|
/** 商品 ID */
|
||||||
productId?: number;
|
productId?: number;
|
||||||
|
/** 排除该商品下的 SKU(迁入搜索) */
|
||||||
|
excludeProductId?: number;
|
||||||
/** SKU ID */
|
/** SKU ID */
|
||||||
id?: number;
|
id?: number;
|
||||||
/** SKU 名称 */
|
/** SKU 名称 */
|
||||||
|
|||||||
@@ -27,10 +27,8 @@ export namespace ProductDTO {
|
|||||||
categoryId?: number;
|
categoryId?: number;
|
||||||
/** 主图图片 ID */
|
/** 主图图片 ID */
|
||||||
mainImageId?: number;
|
mainImageId?: number;
|
||||||
/** 商品 SKU 列表:含 id 为更新,不含 id 为新增 */
|
/** 商品 SKU 列表:id>0 更新,id=0 新增;未出现的已有 SKU 视为删除 */
|
||||||
skus?: UpdateSku[];
|
skus?: UpdateSku[];
|
||||||
/** 编辑时从商品上移除的 SKU ID(须为打开表单时已有的 SKU) */
|
|
||||||
removedSkuIds?: number[];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 商品 SKU DTO(创建时) */
|
/** 商品 SKU DTO(创建时) */
|
||||||
@@ -73,7 +71,7 @@ export namespace ProductDTO {
|
|||||||
|
|
||||||
/** 更新商品 SKU 参数 */
|
/** 更新商品 SKU 参数 */
|
||||||
export interface UpdateSku {
|
export interface UpdateSku {
|
||||||
/** SKU ID:有值表示更新已有 SKU;不传或空表示新增一条 SKU */
|
/** SKU ID:>0 更新已有;0 表示新增 */
|
||||||
id?: number;
|
id?: number;
|
||||||
/** SKU 名称 */
|
/** SKU 名称 */
|
||||||
name: string;
|
name: string;
|
||||||
|
|||||||
@@ -425,6 +425,35 @@ const formOptions = computed(() => ({
|
|||||||
fieldName: 'platformOrderNo',
|
fieldName: 'platformOrderNo',
|
||||||
label: '平台订单号',
|
label: '平台订单号',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
component: 'RangePicker',
|
||||||
|
defaultValue: defaultOrderTime.range,
|
||||||
|
componentProps: {
|
||||||
|
placeholder: ['下单开始时间', '下单结束时间'],
|
||||||
|
allowClear: false,
|
||||||
|
showTime: { format: 'HH:mm:ss' },
|
||||||
|
format: 'YYYY-MM-DD HH:mm:ss',
|
||||||
|
style: { width: '100%' },
|
||||||
|
onChange: (val: any) => {
|
||||||
|
if (!val || !val[0] || !val[1]) {
|
||||||
|
const d = buildDefaultOrderTimeRange();
|
||||||
|
searchForm.value.startOrderTime = d.start;
|
||||||
|
searchForm.value.endOrderTime = d.end;
|
||||||
|
} else {
|
||||||
|
searchForm.value.startOrderTime = (val[0] as dayjs.Dayjs).format(
|
||||||
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
|
);
|
||||||
|
searchForm.value.endOrderTime = (val[1] as dayjs.Dayjs).format(
|
||||||
|
'YYYY-MM-DD HH:mm:ss',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
gridReloadRef.value?.();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
fieldName: 'orderTimeRange',
|
||||||
|
label: '下单时间',
|
||||||
|
rules: 'required',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
component: 'Select',
|
component: 'Select',
|
||||||
componentProps: {
|
componentProps: {
|
||||||
@@ -485,39 +514,11 @@ const formOptions = computed(() => ({
|
|||||||
fieldName: 'status',
|
fieldName: 'status',
|
||||||
label: '订单状态',
|
label: '订单状态',
|
||||||
},
|
},
|
||||||
{
|
|
||||||
component: 'RangePicker',
|
|
||||||
defaultValue: defaultOrderTime.range,
|
|
||||||
componentProps: {
|
|
||||||
placeholder: ['下单开始时间', '下单结束时间'],
|
|
||||||
allowClear: false,
|
|
||||||
showTime: { format: 'HH:mm:ss' },
|
|
||||||
format: 'YYYY-MM-DD HH:mm:ss',
|
|
||||||
style: { width: '100%' },
|
|
||||||
onChange: (val: any) => {
|
|
||||||
if (!val || !val[0] || !val[1]) {
|
|
||||||
const d = buildDefaultOrderTimeRange();
|
|
||||||
searchForm.value.startOrderTime = d.start;
|
|
||||||
searchForm.value.endOrderTime = d.end;
|
|
||||||
} else {
|
|
||||||
searchForm.value.startOrderTime = (val[0] as dayjs.Dayjs).format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
);
|
|
||||||
searchForm.value.endOrderTime = (val[1] as dayjs.Dayjs).format(
|
|
||||||
'YYYY-MM-DD HH:mm:ss',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
gridReloadRef.value?.();
|
|
||||||
},
|
|
||||||
},
|
|
||||||
fieldName: 'orderTimeRange',
|
|
||||||
label: '下单时间',
|
|
||||||
rules: 'required',
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
showDefaultActions: true,
|
showDefaultActions: true,
|
||||||
|
showCollapseButton: true,
|
||||||
collapsed: true,
|
collapsed: true,
|
||||||
collapsedRows: 2,
|
collapsedRows: 1,
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
orderTimeRange: defaultOrderTime.range,
|
orderTimeRange: defaultOrderTime.range,
|
||||||
},
|
},
|
||||||
|
|||||||
+178
-94
@@ -25,6 +25,7 @@ import { uploadFileToOss } from '#/utils/oss-upload';
|
|||||||
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
import CategoryFormModal from '#/views/ec/product/category/components/CategoryFormModal.vue';
|
||||||
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
|
import ProductCostSyncToOrdersModal from './ProductCostSyncToOrdersModal.vue';
|
||||||
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
import ProductSkuCostDrawer from './ProductSkuCostDrawer.vue';
|
||||||
|
import ProductSkuMigrateModal from './ProductSkuMigrateModal.vue';
|
||||||
|
|
||||||
interface Emits {
|
interface Emits {
|
||||||
(e: 'success'): void;
|
(e: 'success'): void;
|
||||||
@@ -64,6 +65,9 @@ const productCostSyncModalRef = ref<InstanceType<
|
|||||||
const productSkuCostDrawerRef = ref<InstanceType<
|
const productSkuCostDrawerRef = ref<InstanceType<
|
||||||
typeof ProductSkuCostDrawer
|
typeof ProductSkuCostDrawer
|
||||||
> | null>(null);
|
> | null>(null);
|
||||||
|
const productSkuMigrateModalRef = ref<InstanceType<
|
||||||
|
typeof ProductSkuMigrateModal
|
||||||
|
> | null>(null);
|
||||||
|
|
||||||
async function openSyncModal(skuIds: number[]) {
|
async function openSyncModal(skuIds: number[]) {
|
||||||
await productCostSyncModalRef.value?.open(skuIds, {
|
await productCostSyncModalRef.value?.open(skuIds, {
|
||||||
@@ -161,7 +165,7 @@ const categoryTreeDropdownRender: DropdownRender = (opt) => {
|
|||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 表格行:创建规格无 id,编辑已有规格带 id;_clientKey 用于行 key */
|
/** 表格行:已有 SKU 带 id;新增行 id=0。_clientKey 用于行 key */
|
||||||
type SkuFormRow = ProductDTO.Sku & {
|
type SkuFormRow = ProductDTO.Sku & {
|
||||||
_clientKey?: string;
|
_clientKey?: string;
|
||||||
id?: number;
|
id?: number;
|
||||||
@@ -174,13 +178,30 @@ type SkuFormRow = ProductDTO.Sku & {
|
|||||||
_previewUrl?: string;
|
_previewUrl?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
function isPersistedSkuId(id?: number) {
|
||||||
|
return id != null && id > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapSkuFields(spec: ProductVO.SkuInfo): ProductDTO.Sku & {
|
||||||
|
costEffectiveFrom?: string;
|
||||||
|
imageUrl?: string;
|
||||||
|
} {
|
||||||
|
return {
|
||||||
|
name: spec.name || spec.skuCode || '',
|
||||||
|
skuCode: spec.skuCode || '',
|
||||||
|
productCost: spec.productCost ?? 0,
|
||||||
|
shippingCost: spec.shippingCost ?? 0,
|
||||||
|
otherCost: spec.otherCost ?? 0,
|
||||||
|
costEffectiveFrom: spec.costEffectiveFrom,
|
||||||
|
remark: spec.remark || '',
|
||||||
|
imageUrl: spec.imageUrl || '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// 规格数据 - 支持创建和更新
|
// 规格数据 - 支持创建和更新
|
||||||
const skus = ref<SkuFormRow[]>([]);
|
const skus = ref<SkuFormRow[]>([]);
|
||||||
const showSkus = ref(false);
|
const showSkus = ref(false);
|
||||||
|
|
||||||
/** 编辑打开时已有的规格 ID,用于提交时计算 removedSkuIds */
|
|
||||||
const initialEditSkuIds = ref<Set<number>>(new Set());
|
|
||||||
|
|
||||||
let nextSkuClientKey = 0;
|
let nextSkuClientKey = 0;
|
||||||
|
|
||||||
// 当前显示的图片 URL(优先显示新选择的)
|
// 当前显示的图片 URL(优先显示新选择的)
|
||||||
@@ -225,41 +246,22 @@ function initFormData() {
|
|||||||
'skus' in currentProductData.value &&
|
'skus' in currentProductData.value &&
|
||||||
currentProductData.value.skus
|
currentProductData.value.skus
|
||||||
) {
|
) {
|
||||||
const mapSku = (spec: ProductVO.SkuInfo) => ({
|
|
||||||
name: spec.name || spec.skuCode || '',
|
|
||||||
skuCode: spec.skuCode || '',
|
|
||||||
productCost: spec.productCost ?? 0,
|
|
||||||
shippingCost: spec.shippingCost ?? 0,
|
|
||||||
otherCost: spec.otherCost ?? 0,
|
|
||||||
costEffectiveFrom: spec.costEffectiveFrom,
|
|
||||||
remark: spec.remark || '',
|
|
||||||
imageUrl: spec.imageUrl || '',
|
|
||||||
});
|
|
||||||
skus.value = isEdit.value
|
skus.value = isEdit.value
|
||||||
? currentProductData.value.skus.map((spec) => {
|
? currentProductData.value.skus.map((spec) => {
|
||||||
const s = spec as ProductVO.SkuInfo;
|
const s = spec as ProductVO.SkuInfo;
|
||||||
return {
|
return {
|
||||||
id: s.id,
|
id: s.id,
|
||||||
_clientKey: `exist-${s.id}`,
|
_clientKey: `exist-${s.id}`,
|
||||||
...mapSku(s),
|
...mapSkuFields(s),
|
||||||
} as SkuFormRow;
|
} as SkuFormRow;
|
||||||
})
|
})
|
||||||
: currentProductData.value.skus.map((spec) => ({
|
: currentProductData.value.skus.map((spec) => ({
|
||||||
_clientKey: `seed-${++nextSkuClientKey}`,
|
_clientKey: `seed-${++nextSkuClientKey}`,
|
||||||
...mapSku(spec as ProductVO.SkuInfo),
|
id: 0,
|
||||||
|
...mapSkuFields(spec as ProductVO.SkuInfo),
|
||||||
}));
|
}));
|
||||||
showSkus.value = skus.value.length > 0;
|
showSkus.value = skus.value.length > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isEdit.value) {
|
|
||||||
initialEditSkuIds.value = new Set(
|
|
||||||
skus.value
|
|
||||||
.map((s) => (s.id != null ? Number(s.id) : null))
|
|
||||||
.filter((x): x is number => x != null),
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
initialEditSkuIds.value = new Set();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 重置表单(在open方法中调用)
|
// 重置表单(在open方法中调用)
|
||||||
@@ -273,7 +275,6 @@ function resetForm() {
|
|||||||
}
|
}
|
||||||
skus.value = [];
|
skus.value = [];
|
||||||
showSkus.value = false;
|
showSkus.value = false;
|
||||||
initialEditSkuIds.value = new Set();
|
|
||||||
categoryOptions.value = [];
|
categoryOptions.value = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -281,6 +282,15 @@ function resetForm() {
|
|||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
try {
|
try {
|
||||||
await formRef.value?.validate();
|
await formRef.value?.validate();
|
||||||
|
if (hasDuplicateSkuField(skus.value, 'skuCode')) {
|
||||||
|
message.error('SKU 编码不能重复');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (hasDuplicateSkuField(skus.value, 'name')) {
|
||||||
|
message.error('SKU 名称不能重复');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
modalApi.setState({ confirmLoading: true });
|
modalApi.setState({ confirmLoading: true });
|
||||||
|
|
||||||
// 准备提交数据
|
// 准备提交数据
|
||||||
@@ -314,54 +324,16 @@ async function handleSubmit() {
|
|||||||
'id' in currentProductData.value &&
|
'id' in currentProductData.value &&
|
||||||
currentProductData.value.id
|
currentProductData.value.id
|
||||||
) {
|
) {
|
||||||
const keptSkuIds = new Set(
|
const skusPayload: ProductDTO.UpdateSku[] = skus.value.map((row) =>
|
||||||
skus.value
|
toSkuUpdatePayload(row),
|
||||||
.map((s) => (s.id != null ? Number(s.id) : null))
|
|
||||||
.filter((x): x is number => x != null),
|
|
||||||
);
|
);
|
||||||
const removedSkuIds = [...initialEditSkuIds.value].filter(
|
|
||||||
(sid) => !keptSkuIds.has(sid),
|
|
||||||
);
|
|
||||||
|
|
||||||
const skusPayload: ProductDTO.UpdateSku[] = skus.value.map((row) => {
|
|
||||||
const {
|
|
||||||
_clientKey: _c,
|
|
||||||
_previewUrl: _p,
|
|
||||||
newImageFile: _f,
|
|
||||||
imageUrl: _u,
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
skuCode,
|
|
||||||
productCost,
|
|
||||||
shippingCost,
|
|
||||||
otherCost,
|
|
||||||
remark,
|
|
||||||
imageId,
|
|
||||||
} = row;
|
|
||||||
const base: ProductDTO.UpdateSku = {
|
|
||||||
name,
|
|
||||||
skuCode: skuCode ?? '',
|
|
||||||
productCost: productCost ?? 0,
|
|
||||||
shippingCost: shippingCost ?? 0,
|
|
||||||
otherCost: otherCost ?? 0,
|
|
||||||
remark: remark ?? '',
|
|
||||||
};
|
|
||||||
if (imageId != null) {
|
|
||||||
base.imageId = imageId;
|
|
||||||
}
|
|
||||||
if (id != null && id !== undefined) {
|
|
||||||
return { ...base, id: Number(id) };
|
|
||||||
}
|
|
||||||
return { ...base };
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateData: ProductDTO.Update = {
|
const updateData: ProductDTO.Update = {
|
||||||
name: submitData.name,
|
name: submitData.name,
|
||||||
productCode: submitData.productCode || undefined,
|
productCode: submitData.productCode || undefined,
|
||||||
categoryId: submitData.categoryId,
|
categoryId: submitData.categoryId,
|
||||||
mainImageId: submitData.mainImageId,
|
mainImageId: submitData.mainImageId,
|
||||||
...(skus.value.length > 0 && { skus: skusPayload }),
|
skus: skusPayload,
|
||||||
...(removedSkuIds.length > 0 && { removedSkuIds }),
|
|
||||||
};
|
};
|
||||||
const result = await updateProductApi(currentProductData.value.id, updateData);
|
const result = await updateProductApi(currentProductData.value.id, updateData);
|
||||||
if (skus.value.length > 0 && result.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
if (skus.value.length > 0 && result.skuIdsCostChangedWithLinkedOrders?.length > 0) {
|
||||||
@@ -489,6 +461,7 @@ function removeNewImage() {
|
|||||||
|
|
||||||
const defaultSku = (): SkuFormRow => ({
|
const defaultSku = (): SkuFormRow => ({
|
||||||
_clientKey: `new-${++nextSkuClientKey}`,
|
_clientKey: `new-${++nextSkuClientKey}`,
|
||||||
|
id: 0,
|
||||||
name: '',
|
name: '',
|
||||||
skuCode: '',
|
skuCode: '',
|
||||||
productCost: 0,
|
productCost: 0,
|
||||||
@@ -499,6 +472,121 @@ const defaultSku = (): SkuFormRow => ({
|
|||||||
newImageFile: null,
|
newImageFile: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
function hasDuplicateSkuField(rows: SkuFormRow[], field: 'name' | 'skuCode') {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
for (const row of rows) {
|
||||||
|
const value = row[field]?.trim();
|
||||||
|
if (!value) continue;
|
||||||
|
if (seen.has(value)) return true;
|
||||||
|
seen.add(value);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function skuRowKey(row: SkuFormRow) {
|
||||||
|
return isPersistedSkuId(row.id) ? String(row.id) : (row._clientKey ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 与当前商品表单里其他行比较,空值不参与 */
|
||||||
|
function isDuplicateSkuField(row: SkuFormRow, field: 'name' | 'skuCode') {
|
||||||
|
const value = row[field]?.trim();
|
||||||
|
if (!value) return false;
|
||||||
|
const key = skuRowKey(row);
|
||||||
|
return skus.value.some(
|
||||||
|
(other) => skuRowKey(other) !== key && other[field]?.trim() === value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function touchSkuRows() {
|
||||||
|
skus.value = [...skus.value];
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderSkuTextInput(
|
||||||
|
record: SkuFormRow,
|
||||||
|
field: 'name' | 'skuCode',
|
||||||
|
placeholder: string,
|
||||||
|
duplicateHint: string,
|
||||||
|
) {
|
||||||
|
const duplicated = isDuplicateSkuField(record, field);
|
||||||
|
return h(
|
||||||
|
Form.Item,
|
||||||
|
{
|
||||||
|
validateStatus: duplicated ? 'error' : undefined,
|
||||||
|
help: duplicated ? duplicateHint : undefined,
|
||||||
|
class: '!mb-0',
|
||||||
|
style: { marginBottom: 0 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
default: () =>
|
||||||
|
h(Input, {
|
||||||
|
value: record[field],
|
||||||
|
placeholder,
|
||||||
|
status: duplicated ? 'error' : undefined,
|
||||||
|
'onUpdate:value': (value: string) => {
|
||||||
|
record[field] = value;
|
||||||
|
touchSkuRows();
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSkuUpdatePayload(row: SkuFormRow): ProductDTO.UpdateSku {
|
||||||
|
const payload: ProductDTO.UpdateSku = {
|
||||||
|
id: isPersistedSkuId(row.id) ? Number(row.id) : 0,
|
||||||
|
name: row.name,
|
||||||
|
skuCode: row.skuCode ?? '',
|
||||||
|
productCost: row.productCost ?? 0,
|
||||||
|
shippingCost: row.shippingCost ?? 0,
|
||||||
|
otherCost: row.otherCost ?? 0,
|
||||||
|
remark: row.remark ?? '',
|
||||||
|
};
|
||||||
|
if (row.imageId != null) {
|
||||||
|
payload.imageId = row.imageId;
|
||||||
|
}
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
|
||||||
|
function applySkusFromProduct(product: ProductVO.Info) {
|
||||||
|
const unsaved = skus.value.filter((row) => !isPersistedSkuId(row.id));
|
||||||
|
const unsavedKeys = new Set(unsaved.map((row) => row._clientKey));
|
||||||
|
for (const row of skus.value) {
|
||||||
|
if (!unsavedKeys.has(row._clientKey)) {
|
||||||
|
revokeSkuPreview(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
currentProductData.value = {
|
||||||
|
...(currentProductData.value ?? {}),
|
||||||
|
...product,
|
||||||
|
};
|
||||||
|
skus.value = [
|
||||||
|
...(product.skus ?? []).map((spec) => ({
|
||||||
|
id: spec.id,
|
||||||
|
_clientKey: `exist-${spec.id}`,
|
||||||
|
...mapSkuFields(spec),
|
||||||
|
})),
|
||||||
|
...unsaved,
|
||||||
|
];
|
||||||
|
showSkus.value = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function openMigrateModal() {
|
||||||
|
const productId = currentProductData.value?.id;
|
||||||
|
if (!isEdit.value || productId == null) {
|
||||||
|
message.warning('请先保存商品后再迁入 SKU');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
productSkuMigrateModalRef.value?.open(
|
||||||
|
productId,
|
||||||
|
formData.value.name || currentProductData.value?.name,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function onMigrateSuccess(product: ProductVO.Info) {
|
||||||
|
applySkusFromProduct(product);
|
||||||
|
emit('success');
|
||||||
|
}
|
||||||
|
|
||||||
// 添加 SKU
|
// 添加 SKU
|
||||||
function addSku() {
|
function addSku() {
|
||||||
skus.value.push(defaultSku());
|
skus.value.push(defaultSku());
|
||||||
@@ -690,34 +778,18 @@ const skuColumns = [
|
|||||||
record,
|
record,
|
||||||
}: {
|
}: {
|
||||||
record: SkuFormRow;
|
record: SkuFormRow;
|
||||||
}) => {
|
}) => renderSkuTextInput(record, 'name', '请输入SKU 名称', '与同品 SKU 名称重复'),
|
||||||
return h(Input, {
|
|
||||||
value: record.name,
|
|
||||||
placeholder: '请输入SKU 名称',
|
|
||||||
'onUpdate:value': (value: string) => {
|
|
||||||
record.name = value;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: 'SKU 编码',
|
title: 'SKU 编码',
|
||||||
dataIndex: 'skuCode',
|
dataIndex: 'skuCode',
|
||||||
key: 'skuCode',
|
key: 'skuCode',
|
||||||
width: 140,
|
width: 168,
|
||||||
customRender: ({
|
customRender: ({
|
||||||
record,
|
record,
|
||||||
}: {
|
}: {
|
||||||
record: SkuFormRow;
|
record: SkuFormRow;
|
||||||
}) => {
|
}) => renderSkuTextInput(record, 'skuCode', '请输入SKU 编码', '与同品 SKU 编码重复'),
|
||||||
return h(Input, {
|
|
||||||
value: record.skuCode,
|
|
||||||
placeholder: '请输入SKU 编码',
|
|
||||||
'onUpdate:value': (value: string) => {
|
|
||||||
record.skuCode = value;
|
|
||||||
},
|
|
||||||
});
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
title: '商品成本',
|
title: '商品成本',
|
||||||
@@ -994,12 +1066,20 @@ onUnmounted(() => {
|
|||||||
管理成本
|
管理成本
|
||||||
</Button>
|
</Button>
|
||||||
</Space>
|
</Space>
|
||||||
<Button v-if="showSkus" type="primary" @click="addSku">
|
<Space v-if="showSkus">
|
||||||
<template #icon>
|
<Button
|
||||||
<PlusIcon class="h-4 w-4" />
|
v-if="isEdit && currentProductData?.id"
|
||||||
</template>
|
@click="openMigrateModal"
|
||||||
添加 SKU
|
>
|
||||||
</Button>
|
迁入他品 SKU
|
||||||
|
</Button>
|
||||||
|
<Button type="primary" @click="addSku">
|
||||||
|
<template #icon>
|
||||||
|
<PlusIcon class="h-4 w-4" />
|
||||||
|
</template>
|
||||||
|
添加 SKU
|
||||||
|
</Button>
|
||||||
|
</Space>
|
||||||
</div>
|
</div>
|
||||||
<p
|
<p
|
||||||
v-if="isEdit && showSkus"
|
v-if="isEdit && showSkus"
|
||||||
@@ -1016,7 +1096,7 @@ onUnmounted(() => {
|
|||||||
:columns="skuColumns"
|
:columns="skuColumns"
|
||||||
:data-source="skus"
|
:data-source="skus"
|
||||||
:pagination="false"
|
:pagination="false"
|
||||||
:row-key="(r: SkuFormRow) => (r.id != null ? String(r.id) : r._clientKey ?? '')"
|
:row-key="(r: SkuFormRow) => (isPersistedSkuId(r.id) ? String(r.id) : r._clientKey ?? '')"
|
||||||
:scroll="{ x: 980 }"
|
:scroll="{ x: 980 }"
|
||||||
size="small"
|
size="small"
|
||||||
>
|
>
|
||||||
@@ -1038,5 +1118,9 @@ onUnmounted(() => {
|
|||||||
@success="emit('success')"
|
@success="emit('success')"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<ProductSkuMigrateModal
|
||||||
|
ref="productSkuMigrateModalRef"
|
||||||
|
@success="onMigrateSuccess"
|
||||||
|
/>
|
||||||
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
|
<CategoryFormModal ref="categoryFormModalRef" @success="reloadCategoryTree" />
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
+208
@@ -0,0 +1,208 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { ProductSkuVO } from '#/api/ec/product/sku/types';
|
||||||
|
import type { ProductVO } from '#/api/ec/product/types';
|
||||||
|
|
||||||
|
import { ref } from 'vue';
|
||||||
|
|
||||||
|
import { useVbenModal } from '@vben/common-ui';
|
||||||
|
|
||||||
|
import {
|
||||||
|
Button,
|
||||||
|
Input,
|
||||||
|
message,
|
||||||
|
Popconfirm,
|
||||||
|
Table,
|
||||||
|
} from 'ant-design-vue';
|
||||||
|
|
||||||
|
import { migrateSkuToProductApi } from '#/api/ec/product';
|
||||||
|
import { getProductSkuPageApi } from '#/api/ec/product/sku';
|
||||||
|
|
||||||
|
defineOptions({ name: 'ProductSkuMigrateModal' });
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
success: [product: ProductVO.Info];
|
||||||
|
}>();
|
||||||
|
|
||||||
|
/** 从他品搜索 SKU,二次确认后再迁入当前商品 */
|
||||||
|
const [Modal, modalApi] = useVbenModal({
|
||||||
|
title: '迁入他品 SKU',
|
||||||
|
class: 'w-[820px] max-w-[calc(100vw-2rem)]',
|
||||||
|
draggable: true,
|
||||||
|
contentClass: 'px-5 py-4',
|
||||||
|
showConfirmButton: false,
|
||||||
|
cancelText: '关闭',
|
||||||
|
onCancel() {
|
||||||
|
close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const targetProductId = ref<number>();
|
||||||
|
const targetProductName = ref('');
|
||||||
|
const keyword = ref('');
|
||||||
|
const records = ref<ProductSkuVO.Info[]>([]);
|
||||||
|
const loading = ref(false);
|
||||||
|
const migratingSkuId = ref<number | null>(null);
|
||||||
|
const pagination = ref({ current: 1, pageSize: 10, total: 0 });
|
||||||
|
|
||||||
|
function formatCost(val?: number) {
|
||||||
|
return `¥${Number(val ?? 0).toFixed(2)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function search(resetPage = false) {
|
||||||
|
if (targetProductId.value == null) return;
|
||||||
|
if (resetPage) {
|
||||||
|
pagination.value.current = 1;
|
||||||
|
}
|
||||||
|
loading.value = true;
|
||||||
|
try {
|
||||||
|
const data = await getProductSkuPageApi({
|
||||||
|
page: pagination.value.current,
|
||||||
|
pageSize: pagination.value.pageSize,
|
||||||
|
filters: {
|
||||||
|
excludeProductId: targetProductId.value,
|
||||||
|
keywords: keyword.value.trim() || undefined,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
records.value = data.records ?? [];
|
||||||
|
pagination.value.total = data.total ?? 0;
|
||||||
|
} catch {
|
||||||
|
records.value = [];
|
||||||
|
pagination.value.total = 0;
|
||||||
|
} finally {
|
||||||
|
loading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleTableChange(pager: { current?: number; pageSize?: number }) {
|
||||||
|
pagination.value.current = pager.current ?? 1;
|
||||||
|
pagination.value.pageSize = pager.pageSize ?? pagination.value.pageSize;
|
||||||
|
void search();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function confirmMigrate(sku: ProductSkuVO.Info) {
|
||||||
|
if (targetProductId.value == null) return;
|
||||||
|
migratingSkuId.value = sku.id;
|
||||||
|
try {
|
||||||
|
const product = await migrateSkuToProductApi(targetProductId.value, sku.id);
|
||||||
|
message.success('SKU 已迁入');
|
||||||
|
emit('success', product);
|
||||||
|
close();
|
||||||
|
} finally {
|
||||||
|
migratingSkuId.value = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
modalApi.close();
|
||||||
|
keyword.value = '';
|
||||||
|
records.value = [];
|
||||||
|
pagination.value = { current: 1, pageSize: 10, total: 0 };
|
||||||
|
targetProductId.value = undefined;
|
||||||
|
targetProductName.value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function open(productId: number, productName?: string) {
|
||||||
|
targetProductId.value = productId;
|
||||||
|
targetProductName.value = productName?.trim() || '';
|
||||||
|
keyword.value = '';
|
||||||
|
pagination.value = { current: 1, pageSize: 10, total: 0 };
|
||||||
|
modalApi.setState({
|
||||||
|
title: targetProductName.value
|
||||||
|
? `迁入他品 SKU(当前:${targetProductName.value})`
|
||||||
|
: '迁入他品 SKU',
|
||||||
|
});
|
||||||
|
modalApi.open();
|
||||||
|
await search(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{
|
||||||
|
title: '所属商品',
|
||||||
|
dataIndex: 'productName',
|
||||||
|
key: 'productName',
|
||||||
|
ellipsis: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'SKU 名称',
|
||||||
|
dataIndex: 'name',
|
||||||
|
key: 'name',
|
||||||
|
ellipsis: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'SKU 编码',
|
||||||
|
dataIndex: 'skuCode',
|
||||||
|
key: 'skuCode',
|
||||||
|
width: 140,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '商品成本',
|
||||||
|
dataIndex: 'productCost',
|
||||||
|
key: 'productCost',
|
||||||
|
width: 110,
|
||||||
|
customRender: ({ record }: { record: ProductSkuVO.Info }) =>
|
||||||
|
formatCost(record.productCost),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '操作',
|
||||||
|
key: 'action',
|
||||||
|
width: 100,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
defineExpose({ open });
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Modal>
|
||||||
|
<div class="mb-3 flex gap-2">
|
||||||
|
<Input
|
||||||
|
v-model:value="keyword"
|
||||||
|
allow-clear
|
||||||
|
placeholder="按 SKU 名称或编码搜索"
|
||||||
|
@press-enter="search(true)"
|
||||||
|
/>
|
||||||
|
<Button type="primary" :loading="loading" @click="search(true)">
|
||||||
|
查询
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Table
|
||||||
|
:columns="columns"
|
||||||
|
:data-source="records"
|
||||||
|
:loading="loading"
|
||||||
|
:pagination="{
|
||||||
|
current: pagination.current,
|
||||||
|
pageSize: pagination.pageSize,
|
||||||
|
total: pagination.total,
|
||||||
|
showSizeChanger: true,
|
||||||
|
showTotal: (total: number) => `共 ${total} 条`,
|
||||||
|
}"
|
||||||
|
:row-key="(row: ProductSkuVO.Info) => row.id"
|
||||||
|
size="small"
|
||||||
|
@change="handleTableChange"
|
||||||
|
>
|
||||||
|
<template #bodyCell="{ column, record }">
|
||||||
|
<template v-if="column.key === 'action'">
|
||||||
|
<Popconfirm
|
||||||
|
:title="`确认将「${record.name}」从「${record.productName || '其他商品'}」迁入当前商品?`"
|
||||||
|
ok-text="确认迁入"
|
||||||
|
cancel-text="取消"
|
||||||
|
:ok-button-props="{ loading: migratingSkuId === record.id }"
|
||||||
|
@confirm="confirmMigrate(record)"
|
||||||
|
>
|
||||||
|
<Button
|
||||||
|
type="link"
|
||||||
|
size="small"
|
||||||
|
:loading="migratingSkuId === record.id"
|
||||||
|
>
|
||||||
|
迁入
|
||||||
|
</Button>
|
||||||
|
</Popconfirm>
|
||||||
|
</template>
|
||||||
|
</template>
|
||||||
|
<template #emptyText>
|
||||||
|
<div class="py-6 text-center text-slate-400">暂无他品 SKU</div>
|
||||||
|
</template>
|
||||||
|
</Table>
|
||||||
|
</Modal>
|
||||||
|
</template>
|
||||||
Reference in New Issue
Block a user