mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 14:29:19 +08:00
feat: 加入规格体系
This commit is contained in:
+6
@@ -4,6 +4,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
@@ -17,6 +18,7 @@ public class CreateProductDTO {
|
||||
@NotBlank(message = "商品名称不能为空")
|
||||
private String name;
|
||||
|
||||
@NotBlank(message = "商品编码不能为空")
|
||||
private String productCode;
|
||||
|
||||
private Long categoryId;
|
||||
@@ -26,6 +28,10 @@ public class CreateProductDTO {
|
||||
@Valid
|
||||
private List<ProductSkuDTO> skus;
|
||||
|
||||
/** 可选;与商品同事务写入规格维(id 空=新增)。 */
|
||||
@Valid
|
||||
private List<ReplaceProductSpecsDTO.SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class ProductSkuDTO {
|
||||
|
||||
|
||||
+9
-1
@@ -4,6 +4,7 @@ import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
@@ -17,6 +18,7 @@ public class UpdateProductDTO {
|
||||
@NotBlank(message = "商品名称不能为空")
|
||||
private String name;
|
||||
|
||||
@NotBlank(message = "商品编码不能为空")
|
||||
private String productCode;
|
||||
|
||||
private Long categoryId;
|
||||
@@ -24,11 +26,17 @@ public class UpdateProductDTO {
|
||||
private Long mainImageId;
|
||||
|
||||
/**
|
||||
* 传入则按全量同步:id>0 更新,id 为 null/0 新增,库中有但未出现的删除。
|
||||
* 传入则按全量同步:id>0 更新,id 为 null/0 新增,库中有但未出现的删除。
|
||||
*/
|
||||
@Valid
|
||||
private List<ProductSkuUpdateDTO> skus;
|
||||
|
||||
/**
|
||||
* 传入则全量同步规格维(有 id 更新,无 id 新增,未出现的删除)。
|
||||
*/
|
||||
@Valid
|
||||
private List<ReplaceProductSpecsDTO.SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class ProductSkuUpdateDTO {
|
||||
|
||||
|
||||
+5
@@ -67,6 +67,11 @@ public class ProductVO {
|
||||
*/
|
||||
private Long updateBy;
|
||||
|
||||
/**
|
||||
* 商品规格维(结构化)
|
||||
*/
|
||||
private List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO> specs;
|
||||
|
||||
/**
|
||||
* 商品 SKU 列表
|
||||
*/
|
||||
|
||||
+32
-8
@@ -30,6 +30,8 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.service.OrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.mapper.AdFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.adfee.model.po.AdFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.fakeordersfee.mapper.FakeOrdersFeeMapper;
|
||||
@@ -64,6 +66,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final SysFileMapper sysFileMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final CategoryService categoryService;
|
||||
private final OrderService orderService;
|
||||
private final BiOrderStatDirtyDayService biOrderStatDirtyDayService;
|
||||
@@ -72,7 +75,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
private final FakeOrdersFeeMapper fakeOrdersFeeMapper;
|
||||
|
||||
public ProductServiceImpl(CurrentUserContext currentUserContext, SysFileMapper sysFileMapper,
|
||||
@Lazy ProductSkuService productSkuService, @Lazy CategoryService categoryService,
|
||||
@Lazy ProductSkuService productSkuService,
|
||||
@Lazy ProductSpecService productSpecService,
|
||||
@Lazy CategoryService categoryService,
|
||||
@Lazy OrderService orderService,
|
||||
BiOrderStatDirtyDayService biOrderStatDirtyDayService,
|
||||
OrderItemMapper orderItemMapper,
|
||||
@@ -81,6 +86,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileMapper = sysFileMapper;
|
||||
this.productSkuService = productSkuService;
|
||||
this.productSpecService = productSpecService;
|
||||
this.categoryService = categoryService;
|
||||
this.orderService = orderService;
|
||||
this.biOrderStatDirtyDayService = biOrderStatDirtyDayService;
|
||||
@@ -144,8 +150,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
}
|
||||
}
|
||||
|
||||
if (createProductDTO.getSpecs() != null) {
|
||||
ReplaceProductSpecsDTO specsDto = new ReplaceProductSpecsDTO();
|
||||
specsDto.setSpecs(createProductDTO.getSpecs());
|
||||
productSpecService.replaceSpecs(product.getId(), specsDto);
|
||||
}
|
||||
|
||||
CreateProductResultDTO result = new CreateProductResultDTO();
|
||||
result.setProduct(convertToVO(product));
|
||||
result.setProduct(convertToVO(this.getById(product.getId())));
|
||||
result.setSkuIdsCostChangedWithLinkedOrders(new ArrayList<>(syncSkuIds));
|
||||
return result;
|
||||
}
|
||||
@@ -464,6 +476,12 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
rawCostChangedSkuIds, newSkuIdsFromCodeWithOrders);
|
||||
}
|
||||
|
||||
if (updateProductDTO.getSpecs() != null) {
|
||||
ReplaceProductSpecsDTO specsDto = new ReplaceProductSpecsDTO();
|
||||
specsDto.setSpecs(updateProductDTO.getSpecs());
|
||||
productSpecService.replaceSpecs(id, specsDto);
|
||||
}
|
||||
|
||||
// 返回结果:成本变更且有关联订单的规格 ∪ 新增规格(编码非空)且有关联订单的规格
|
||||
UpdateProductResultDTO result = new UpdateProductResultDTO();
|
||||
LinkedHashSet<Long> syncUnion = new LinkedHashSet<>();
|
||||
@@ -720,6 +738,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
.collect(Collectors.toList());
|
||||
|
||||
productVO.setSkus(skuVOs);
|
||||
productVO.setSpecs(productSpecService.listByProductId(product.getId()));
|
||||
if (!skuVOs.isEmpty()) {
|
||||
Map<Long, List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO>> bySku =
|
||||
productSpecService.listSkuSpecValues(
|
||||
skuVOs.stream().map(ProductSkuVO::getId).collect(Collectors.toList()));
|
||||
for (ProductSkuVO skuVo : skuVOs) {
|
||||
skuVo.setSpecValues(bySku.getOrDefault(skuVo.getId(), List.of()));
|
||||
}
|
||||
}
|
||||
return productVO;
|
||||
}
|
||||
|
||||
@@ -727,12 +754,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
return productSkuService.toVo(productSku);
|
||||
}
|
||||
|
||||
/** 公司内商品编码唯一;未填不校验。 */
|
||||
/** 公司内商品编码唯一;必填。 */
|
||||
private void assertProductCodeUnique(Long companyId, String productCode, Long excludeId) {
|
||||
String code = normalizeProductCode(productCode);
|
||||
if (code == null) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<ProductPO> uniqueWrapper = new LambdaQueryWrapper<>();
|
||||
uniqueWrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.eq(ProductPO::getProductCode, code);
|
||||
@@ -744,10 +768,10 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
|
||||
}
|
||||
}
|
||||
|
||||
/** 空白编码规范为 null,不参与唯一约束。 */
|
||||
/** 商品编码必填并 trim。 */
|
||||
private static String normalizeProductCode(String productCode) {
|
||||
if (productCode == null || productCode.isBlank()) {
|
||||
return null;
|
||||
throw new BusinessException("商品编码不能为空");
|
||||
}
|
||||
return productCode.trim();
|
||||
}
|
||||
|
||||
+4
@@ -35,6 +35,10 @@ public class ProductSkuPO {
|
||||
@TableField("attrs")
|
||||
private String attrs;
|
||||
|
||||
/** 空=遗留无结构;非空=结构化组合唯一键 */
|
||||
@TableField("spec_combination_key")
|
||||
private String specCombinationKey;
|
||||
|
||||
@TableField("image_id")
|
||||
private Long imageId;
|
||||
|
||||
|
||||
+7
@@ -5,6 +5,7 @@ import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品 SKU VO(含当前生效成本扁平字段)
|
||||
@@ -24,6 +25,12 @@ public class ProductSkuVO {
|
||||
|
||||
private String skuCode;
|
||||
|
||||
/** 空=遗留无结构 SKU */
|
||||
private String specCombinationKey;
|
||||
|
||||
/** 结构化规格值(未结构化则为空) */
|
||||
private List<top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO> specValues;
|
||||
|
||||
private String imageUrl;
|
||||
|
||||
private BigDecimal productCost;
|
||||
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 商品规格维 API(属商品;生成 SKU 可选)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/product/{productId}/specs")
|
||||
public class ProductSpecController {
|
||||
|
||||
private final ProductSpecService productSpecService;
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public ProductSpecController(ProductSpecService productSpecService,
|
||||
SpecTemplateService specTemplateService) {
|
||||
this.productSpecService = productSpecService;
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@RequirePermission(value = "ec:product:read", description = "查询商品规格", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> list(@PathVariable Long productId) {
|
||||
return ApiResponse.success("获取成功", productSpecService.listByProductId(productId));
|
||||
}
|
||||
|
||||
@PutMapping
|
||||
@RequirePermission(value = "ec:product:update", description = "保存商品规格", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> replace(@PathVariable Long productId,
|
||||
@Valid @RequestBody ReplaceProductSpecsDTO dto) {
|
||||
return ApiResponse.success("保存成功", productSpecService.replaceSpecs(productId, dto));
|
||||
}
|
||||
|
||||
@PostMapping("/generate-skus")
|
||||
@RequirePermission(value = "ec:product:update", description = "按规格生成SKU", allowSuper = true)
|
||||
public ApiResponse<List<ProductSkuVO>> generateSkus(@PathVariable Long productId,
|
||||
@RequestBody(required = false) GenerateProductSkusDTO dto) {
|
||||
List<ProductSkuVO> created = productSpecService.generateSkus(productId,
|
||||
dto != null ? dto : new GenerateProductSkusDTO());
|
||||
return ApiResponse.success("已生成 " + created.size() + " 个 SKU", created);
|
||||
}
|
||||
|
||||
@PostMapping("/skus")
|
||||
@RequirePermission(value = "ec:product:update", description = "按规格值创建SKU", allowSuper = true)
|
||||
public ApiResponse<ProductSkuVO> createSkuFromSpecs(@PathVariable Long productId,
|
||||
@Valid @RequestBody CreateSkuFromSpecsDTO dto) {
|
||||
return ApiResponse.success("创建成功", productSpecService.createSkuFromSpecs(productId, dto));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格值(不改 sku_code);body.specValueIds 空则解绑。
|
||||
*/
|
||||
@PutMapping("/skus/{skuId}")
|
||||
@RequirePermission(value = "ec:product:update", description = "SKU绑定规格", allowSuper = true)
|
||||
public ApiResponse<ProductSkuVO> bindSkuSpecs(@PathVariable Long productId,
|
||||
@PathVariable Long skuId,
|
||||
@RequestBody(required = false) BindSkuSpecsDTO dto) {
|
||||
return ApiResponse.success("绑定成功",
|
||||
productSpecService.bindSkuSpecs(productId, skuId, dto != null ? dto : new BindSkuSpecsDTO()));
|
||||
}
|
||||
|
||||
/** 套用规格模板到商品(合并维值,不生成 SKU)。 */
|
||||
@PostMapping("/apply-template")
|
||||
@RequirePermission(value = "ec:product:update", description = "套用规格模板", allowSuper = true)
|
||||
public ApiResponse<List<ProductSpecVO>> applyTemplate(@PathVariable Long productId,
|
||||
@Valid @RequestBody ApplySpecTemplateDTO dto) {
|
||||
return ApiResponse.success("套用成功", specTemplateService.applyToProduct(productId, dto));
|
||||
}
|
||||
|
||||
/** 将商品现有规格另存为公司模板。 */
|
||||
@PostMapping("/save-as-template")
|
||||
@RequirePermission(value = "ec:product:spec-template:create", description = "商品规格另存为模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> saveAsTemplate(@PathVariable Long productId,
|
||||
@Valid @RequestBody SaveProductAsTemplateDTO dto) {
|
||||
return ApiResponse.success("保存成功", specTemplateService.saveProductAsTemplate(productId, dto));
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.domain;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 规格组合键与 SKU 编码生成(纯函数,无 IO)。
|
||||
* combination_key 按 value_id 升序;sku_code 按规格 sort 拼接 value_code。
|
||||
*/
|
||||
public final class ProductSpecCodes {
|
||||
|
||||
public static final int MAX_GENERATED_SKUS = 200;
|
||||
|
||||
private ProductSpecCodes() {
|
||||
}
|
||||
|
||||
/** 组合唯一键:规格值 ID 升序,下划线拼接。 */
|
||||
public static String combinationKey(List<Long> specValueIds) {
|
||||
if (specValueIds == null || specValueIds.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
return specValueIds.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.map(String::valueOf)
|
||||
.collect(Collectors.joining("_"));
|
||||
}
|
||||
|
||||
/**
|
||||
* sku_code = productCode-valueCode…(规格 sort 升序,同 sort 再按 specId)。
|
||||
*/
|
||||
public static String buildSkuCode(String productCode,
|
||||
List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
String pc = productCode == null ? "" : productCode.trim();
|
||||
if (pc.isEmpty()) {
|
||||
throw new IllegalArgumentException("商品编码不能为空");
|
||||
}
|
||||
if (values == null || values.isEmpty()) {
|
||||
return pc;
|
||||
}
|
||||
List<ProductSpecValuePO> ordered = new ArrayList<>(values);
|
||||
ordered.sort(Comparator
|
||||
.comparing((ProductSpecValuePO v) -> {
|
||||
ProductSpecPO s = specById.get(v.getSpecId());
|
||||
return s != null && s.getSortOrder() != null ? s.getSortOrder() : 0;
|
||||
})
|
||||
.thenComparing(v -> v.getSpecId() != null ? v.getSpecId() : 0L)
|
||||
.thenComparing(v -> v.getSortOrder() != null ? v.getSortOrder() : 0)
|
||||
.thenComparing(v -> v.getId() != null ? v.getId() : 0L));
|
||||
StringBuilder sb = new StringBuilder(pc);
|
||||
for (ProductSpecValuePO v : ordered) {
|
||||
String code = v.getValueCode() == null ? "" : v.getValueCode().trim();
|
||||
if (code.isEmpty()) {
|
||||
throw new IllegalArgumentException("规格值编码不能为空");
|
||||
}
|
||||
sb.append('-').append(code);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/** 展示名:valueName 按规格 sort 用「/」拼接。 */
|
||||
public static String buildSkuDisplayName(List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return "默认";
|
||||
}
|
||||
List<ProductSpecValuePO> ordered = new ArrayList<>(values);
|
||||
ordered.sort(Comparator
|
||||
.comparing((ProductSpecValuePO v) -> {
|
||||
ProductSpecPO s = specById.get(v.getSpecId());
|
||||
return s != null && s.getSortOrder() != null ? s.getSortOrder() : 0;
|
||||
})
|
||||
.thenComparing(v -> v.getSpecId() != null ? v.getSpecId() : 0L));
|
||||
return ordered.stream()
|
||||
.map(v -> v.getValueName() != null ? v.getValueName() : "")
|
||||
.filter(s -> !s.isBlank())
|
||||
.collect(Collectors.joining("/"));
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSkuSpecValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSkuSpecValueMapper extends BaseMapper<ProductSkuSpecValuePO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSpecMapper extends BaseMapper<ProductSpecPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface ProductSpecValueMapper extends BaseMapper<ProductSpecValuePO> {
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定(或解绑)规格值。
|
||||
* 不修改 sku_code;specValueIds 空或 null 表示解绑回 legacy。
|
||||
*/
|
||||
@Data
|
||||
public class BindSkuSpecsDTO {
|
||||
|
||||
/** 规格值 ID;同一规格维最多一个;空=解绑 */
|
||||
private List<Long> specValueIds;
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 按所选规格值创建 SKU(允许缺维;编码可空则按商品编码+value_code 生成)。
|
||||
*/
|
||||
@Data
|
||||
public class CreateSkuFromSpecsDTO {
|
||||
|
||||
/** 规格值 ID 列表;同一规格维最多一个 */
|
||||
@NotEmpty(message = "请至少选择一个规格值")
|
||||
private List<Long> specValueIds;
|
||||
|
||||
/** 可选;空则自动生成 */
|
||||
private String skuCode;
|
||||
|
||||
/** 可选;空则用规格值名拼接 */
|
||||
private String name;
|
||||
|
||||
@NotNull(message = "商品成本不能为空")
|
||||
private BigDecimal productCost;
|
||||
|
||||
private BigDecimal shippingCost;
|
||||
|
||||
private BigDecimal otherCost;
|
||||
|
||||
private String remark;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 按当前规格维笛卡尔积生成缺失 SKU。
|
||||
* 成本缺省为 0,可随后在 SKU 成本中调整。
|
||||
*/
|
||||
@Data
|
||||
public class GenerateProductSkusDTO {
|
||||
|
||||
private BigDecimal productCost;
|
||||
|
||||
private BigDecimal shippingCost;
|
||||
|
||||
private BigDecimal otherCost;
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 全量覆盖保存商品规格维。specs 可空列表表示清空未引用规格。 */
|
||||
@Data
|
||||
public class ReplaceProductSpecsDTO {
|
||||
|
||||
@Valid
|
||||
private List<SpecItem> specs;
|
||||
|
||||
@Data
|
||||
public static class SpecItem {
|
||||
/** 已有规格维 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格名称不能为空")
|
||||
private String name;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ValueItem> values;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ValueItem {
|
||||
/** 已有规格值 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格值名称不能为空")
|
||||
private String valueName;
|
||||
|
||||
@NotBlank(message = "规格值编码不能为空")
|
||||
@Pattern(regexp = "^[A-Za-z0-9_-]+$", message = "规格值编码仅允许字母、数字、下划线、中划线")
|
||||
private String valueCode;
|
||||
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** SKU 与规格值多对多关系。 */
|
||||
@Data
|
||||
@TableName("ec_product_sku_spec_value")
|
||||
public class ProductSkuSpecValuePO {
|
||||
|
||||
@TableField("sku_id")
|
||||
private Long skuId;
|
||||
|
||||
@TableField("spec_value_id")
|
||||
private Long specValueId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 商品规格维(如颜色、尺码),属于单个商品。 */
|
||||
@Data
|
||||
@TableName("ec_product_spec")
|
||||
public class ProductSpecPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 商品规格值(含 value_code,用于拼 SKU 编码)。 */
|
||||
@Data
|
||||
@TableName("ec_product_spec_value")
|
||||
public class ProductSpecValuePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("spec_id")
|
||||
private Long specId;
|
||||
|
||||
@TableField("value_name")
|
||||
private String valueName;
|
||||
|
||||
@TableField("value_code")
|
||||
private String valueCode;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 商品规格维视图。 */
|
||||
@Data
|
||||
public class ProductSpecVO {
|
||||
|
||||
private Long id;
|
||||
private String name;
|
||||
private Integer sortOrder;
|
||||
private List<ProductSpecValueVO> values;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 商品规格值视图。 */
|
||||
@Data
|
||||
public class ProductSpecValueVO {
|
||||
|
||||
private Long id;
|
||||
private Long specId;
|
||||
private String valueName;
|
||||
private String valueCode;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** 商品规格维:查询、覆盖保存、按规格生成/绑定 SKU。 */
|
||||
public interface ProductSpecService {
|
||||
|
||||
List<ProductSpecVO> listByProductId(Long productId);
|
||||
|
||||
List<ProductSpecVO> replaceSpecs(Long productId, ReplaceProductSpecsDTO dto);
|
||||
|
||||
/** 笛卡尔积生成缺失结构化 SKU;sku_code 冲突则整批失败。 */
|
||||
List<ProductSkuVO> generateSkus(Long productId, GenerateProductSkusDTO dto);
|
||||
|
||||
/** 按所选规格值创建 SKU(允许缺维)。 */
|
||||
ProductSkuVO createSkuFromSpecs(Long productId, CreateSkuFromSpecsDTO dto);
|
||||
|
||||
/**
|
||||
* 为已有 SKU 绑定规格(可缺维);不改 sku_code。
|
||||
* specValueIds 空则解绑,回到 legacy(combination_key 空)。
|
||||
*/
|
||||
ProductSkuVO bindSkuSpecs(Long productId, Long skuId, BindSkuSpecsDTO dto);
|
||||
|
||||
/** 批量查询 SKU 已绑规格值(skuId → values)。 */
|
||||
Map<Long, List<ProductSpecValueVO>> listSkuSpecValues(Collection<Long> skuIds);
|
||||
}
|
||||
+604
@@ -0,0 +1,604 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.vo.ProductSkuVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.domain.ProductSpecCodes;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSkuSpecValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSpecMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.mapper.ProductSpecValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.BindSkuSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.CreateSkuFromSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.GenerateProductSkusDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSkuSpecValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.po.ProductSpecValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 商品规格维服务:覆盖保存规格树、按维笛卡尔生成结构化 SKU。
|
||||
*/
|
||||
@Service
|
||||
public class ProductSpecServiceImpl implements ProductSpecService {
|
||||
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSpecMapper specMapper;
|
||||
private final ProductSpecValueMapper valueMapper;
|
||||
private final ProductSkuSpecValueMapper skuSpecValueMapper;
|
||||
private final ProductSkuMapper skuMapper;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ProductSpecServiceImpl(ProductMapper productMapper,
|
||||
ProductSpecMapper specMapper,
|
||||
ProductSpecValueMapper valueMapper,
|
||||
ProductSkuSpecValueMapper skuSpecValueMapper,
|
||||
ProductSkuMapper skuMapper,
|
||||
ProductSkuService productSkuService,
|
||||
ProductSkuCostService productSkuCostService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.productMapper = productMapper;
|
||||
this.specMapper = specMapper;
|
||||
this.valueMapper = valueMapper;
|
||||
this.skuSpecValueMapper = skuSpecValueMapper;
|
||||
this.skuMapper = skuMapper;
|
||||
this.productSkuService = productSkuService;
|
||||
this.productSkuCostService = productSkuCostService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ProductSpecVO> listByProductId(Long productId) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
return loadSpecTree(product.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSpecVO> replaceSpecs(Long productId, ReplaceProductSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
List<ReplaceProductSpecsDTO.SpecItem> items =
|
||||
dto.getSpecs() == null ? List.of() : dto.getSpecs();
|
||||
|
||||
Set<Long> keepSpecIds = new HashSet<>();
|
||||
Set<Long> keepValueIds = new HashSet<>();
|
||||
int specOrder = 0;
|
||||
for (ReplaceProductSpecsDTO.SpecItem item : items) {
|
||||
if (item == null || !StringUtils.hasText(item.getName())) {
|
||||
throw new BusinessException("规格名称不能为空");
|
||||
}
|
||||
String specName = item.getName().trim();
|
||||
ProductSpecPO spec = resolveOrCreateSpec(product, item.getId(), specName,
|
||||
item.getSortOrder() != null ? item.getSortOrder() : specOrder++, userId);
|
||||
keepSpecIds.add(spec.getId());
|
||||
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values =
|
||||
item.getValues() == null ? List.of() : item.getValues();
|
||||
Set<String> nameSeen = new HashSet<>();
|
||||
Set<String> codeSeen = new HashSet<>();
|
||||
int valueOrder = 0;
|
||||
for (ReplaceProductSpecsDTO.ValueItem vi : values) {
|
||||
if (vi == null) {
|
||||
continue;
|
||||
}
|
||||
String vn = requireText(vi.getValueName(), "规格值名称不能为空");
|
||||
String vc = requireText(vi.getValueCode(), "规格值编码不能为空").toUpperCase();
|
||||
validateValueCode(vc);
|
||||
if (!nameSeen.add(vn)) {
|
||||
throw new BusinessException("同一规格下规格值名称重复: " + vn);
|
||||
}
|
||||
if (!codeSeen.add(vc)) {
|
||||
throw new BusinessException("同一规格下规格值编码重复: " + vc);
|
||||
}
|
||||
ProductSpecValuePO value = resolveOrCreateValue(product, spec, vi.getId(), vn, vc,
|
||||
vi.getSortOrder() != null ? vi.getSortOrder() : valueOrder++, userId);
|
||||
keepValueIds.add(value.getId());
|
||||
}
|
||||
}
|
||||
|
||||
// 删除未保留且未被 SKU 引用的规格值 / 规格维
|
||||
List<ProductSpecValuePO> existingValues = valueMapper.selectList(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getProductId, productId));
|
||||
for (ProductSpecValuePO v : existingValues) {
|
||||
if (keepValueIds.contains(v.getId())) {
|
||||
continue;
|
||||
}
|
||||
if (isValueReferenced(v.getId())) {
|
||||
throw new BusinessException("规格值「" + v.getValueName() + "」已被 SKU 使用,无法删除");
|
||||
}
|
||||
valueMapper.deleteById(v.getId());
|
||||
}
|
||||
List<ProductSpecPO> existingSpecs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId));
|
||||
for (ProductSpecPO s : existingSpecs) {
|
||||
if (keepSpecIds.contains(s.getId())) {
|
||||
continue;
|
||||
}
|
||||
long remain = valueMapper.selectCount(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getSpecId, s.getId()));
|
||||
if (remain > 0) {
|
||||
throw new BusinessException("规格「" + s.getName() + "」下仍有规格值,无法删除");
|
||||
}
|
||||
specMapper.deleteById(s.getId());
|
||||
}
|
||||
return loadSpecTree(productId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSkuVO> generateSkus(Long productId, GenerateProductSkusDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
if (!StringUtils.hasText(product.getProductCode())) {
|
||||
throw new BusinessException("请先填写商品编码后再生成 SKU");
|
||||
}
|
||||
String productCode = product.getProductCode().trim();
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
List<ProductSpecPO> specs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId)
|
||||
.orderByAsc(ProductSpecPO::getSortOrder)
|
||||
.orderByAsc(ProductSpecPO::getId));
|
||||
if (specs.isEmpty()) {
|
||||
throw new BusinessException("请先配置商品规格后再生成 SKU");
|
||||
}
|
||||
Map<Long, ProductSpecPO> specById = specs.stream()
|
||||
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
List<List<ProductSpecValuePO>> dimValues = new ArrayList<>();
|
||||
for (ProductSpecPO spec : specs) {
|
||||
List<ProductSpecValuePO> vals = valueMapper.selectList(new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.eq(ProductSpecValuePO::getSpecId, spec.getId())
|
||||
.orderByAsc(ProductSpecValuePO::getSortOrder)
|
||||
.orderByAsc(ProductSpecValuePO::getId));
|
||||
if (vals.isEmpty()) {
|
||||
throw new BusinessException("规格「" + spec.getName() + "」下没有规格值");
|
||||
}
|
||||
dimValues.add(vals);
|
||||
}
|
||||
|
||||
List<List<ProductSpecValuePO>> combos = cartesian(dimValues);
|
||||
if (combos.size() > ProductSpecCodes.MAX_GENERATED_SKUS) {
|
||||
throw new BusinessException("生成 SKU 数量超过上限 " + ProductSpecCodes.MAX_GENERATED_SKUS
|
||||
+ "(当前 " + combos.size() + "),请减少规格值");
|
||||
}
|
||||
|
||||
// 预检:组合键 / sku_code 冲突则整批失败
|
||||
Set<String> existingKeys = skuMapper.selectList(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getProductId, productId)
|
||||
.isNotNull(ProductSkuPO::getSpecCombinationKey))
|
||||
.stream()
|
||||
.map(ProductSkuPO::getSpecCombinationKey)
|
||||
.filter(StringUtils::hasText)
|
||||
.collect(Collectors.toSet());
|
||||
Set<String> existingCodes = skuMapper.selectList(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getCompanyId, companyId))
|
||||
.stream()
|
||||
.map(ProductSkuPO::getSkuCode)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(String::trim)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
List<PendingSku> toCreate = new ArrayList<>();
|
||||
for (List<ProductSpecValuePO> combo : combos) {
|
||||
List<Long> ids = combo.stream().map(ProductSpecValuePO::getId).toList();
|
||||
String key = ProductSpecCodes.combinationKey(ids);
|
||||
if (existingKeys.contains(key)) {
|
||||
continue;
|
||||
}
|
||||
String skuCode = ProductSpecCodes.buildSkuCode(productCode, combo, specById);
|
||||
if (existingCodes.contains(skuCode)) {
|
||||
throw new BusinessException("SKU 编码冲突,整批未生成: " + skuCode);
|
||||
}
|
||||
if (toCreate.stream().anyMatch(p -> p.skuCode.equals(skuCode) || p.combinationKey.equals(key))) {
|
||||
throw new BusinessException("生成结果内部出现重复 SKU 编码或组合: " + skuCode);
|
||||
}
|
||||
toCreate.add(new PendingSku(key, skuCode,
|
||||
ProductSpecCodes.buildSkuDisplayName(combo, specById), combo));
|
||||
existingCodes.add(skuCode);
|
||||
existingKeys.add(key);
|
||||
}
|
||||
|
||||
BigDecimal productCost = dto != null && dto.getProductCost() != null
|
||||
? dto.getProductCost() : BigDecimal.ZERO;
|
||||
BigDecimal shippingCost = dto != null && dto.getShippingCost() != null
|
||||
? dto.getShippingCost() : BigDecimal.ZERO;
|
||||
BigDecimal otherCost = dto != null && dto.getOtherCost() != null
|
||||
? dto.getOtherCost() : BigDecimal.ZERO;
|
||||
|
||||
List<ProductSkuVO> created = new ArrayList<>();
|
||||
for (PendingSku pending : toCreate) {
|
||||
ProductSkuPO sku = new ProductSkuPO();
|
||||
sku.setCompanyId(companyId);
|
||||
sku.setProductId(productId);
|
||||
sku.setName(pending.displayName);
|
||||
sku.setSkuCode(pending.skuCode);
|
||||
sku.setSpecCombinationKey(pending.combinationKey);
|
||||
sku.setStatus(1);
|
||||
sku.setSortOrder(0);
|
||||
sku.setCreateBy(userId);
|
||||
sku.setUpdateBy(userId);
|
||||
if (!productSkuService.save(sku)) {
|
||||
throw new BusinessException("创建 SKU 失败: " + pending.skuCode);
|
||||
}
|
||||
productSkuCostService.writeInitialCostIfPresent(sku.getId(), companyId,
|
||||
productCost, shippingCost, otherCost, userId);
|
||||
for (ProductSpecValuePO v : pending.values) {
|
||||
ProductSkuSpecValuePO rel = new ProductSkuSpecValuePO();
|
||||
rel.setSkuId(sku.getId());
|
||||
rel.setSpecValueId(v.getId());
|
||||
skuSpecValueMapper.insert(rel);
|
||||
}
|
||||
created.add(productSkuService.toVo(sku));
|
||||
}
|
||||
return created;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProductSkuVO createSkuFromSpecs(Long productId, CreateSkuFromSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
if (dto == null || dto.getSpecValueIds() == null || dto.getSpecValueIds().isEmpty()) {
|
||||
throw new BusinessException("请至少选择一个规格值");
|
||||
}
|
||||
if (!StringUtils.hasText(product.getProductCode())) {
|
||||
throw new BusinessException("请先填写商品编码");
|
||||
}
|
||||
Long companyId = product.getCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
ResolvedSpecValues resolved = resolveSpecValues(productId, dto.getSpecValueIds());
|
||||
String key = ProductSpecCodes.combinationKey(
|
||||
resolved.values().stream().map(ProductSpecValuePO::getId).toList());
|
||||
assertCombinationAvailable(productId, key, null);
|
||||
|
||||
String skuCode = StringUtils.hasText(dto.getSkuCode())
|
||||
? dto.getSkuCode().trim()
|
||||
: ProductSpecCodes.buildSkuCode(product.getProductCode(), resolved.values(), resolved.specById());
|
||||
if (skuMapper.selectCount(new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getSkuCode, skuCode)) > 0) {
|
||||
throw new BusinessException("SKU 编码已存在: " + skuCode);
|
||||
}
|
||||
|
||||
String name = StringUtils.hasText(dto.getName())
|
||||
? dto.getName().trim()
|
||||
: ProductSpecCodes.buildSkuDisplayName(resolved.values(), resolved.specById());
|
||||
|
||||
ProductSkuPO sku = new ProductSkuPO();
|
||||
sku.setCompanyId(companyId);
|
||||
sku.setProductId(productId);
|
||||
sku.setName(name);
|
||||
sku.setSkuCode(skuCode);
|
||||
sku.setSpecCombinationKey(key);
|
||||
sku.setRemark(dto.getRemark());
|
||||
sku.setStatus(1);
|
||||
sku.setSortOrder(0);
|
||||
sku.setCreateBy(userId);
|
||||
sku.setUpdateBy(userId);
|
||||
if (!productSkuService.save(sku)) {
|
||||
throw new BusinessException("创建 SKU 失败");
|
||||
}
|
||||
productSkuCostService.writeInitialCostIfPresent(sku.getId(), companyId,
|
||||
dto.getProductCost(),
|
||||
dto.getShippingCost() != null ? dto.getShippingCost() : BigDecimal.ZERO,
|
||||
dto.getOtherCost() != null ? dto.getOtherCost() : BigDecimal.ZERO,
|
||||
userId);
|
||||
replaceSkuSpecRels(sku.getId(), resolved.values());
|
||||
ProductSkuVO vo = productSkuService.toVo(sku);
|
||||
vo.setSpecValues(resolved.values().stream().map(this::toValueVo).toList());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public ProductSkuVO bindSkuSpecs(Long productId, Long skuId, BindSkuSpecsDTO dto) {
|
||||
ProductPO product = requireProduct(productId);
|
||||
ProductSkuPO sku = skuMapper.selectById(skuId);
|
||||
if (sku == null || !Objects.equals(sku.getProductId(), productId)
|
||||
|| !Objects.equals(sku.getCompanyId(), product.getCompanyId())) {
|
||||
throw new BusinessException("SKU 不存在或不属于当前商品");
|
||||
}
|
||||
|
||||
List<Long> rawIds = dto != null && dto.getSpecValueIds() != null
|
||||
? dto.getSpecValueIds() : List.of();
|
||||
List<Long> valueIds = rawIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
if (valueIds.isEmpty()) {
|
||||
// 解绑:回到 legacy,保留原 sku_code / name(须显式 set null,updateById 会忽略 null)
|
||||
skuSpecValueMapper.delete(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSkuId, skuId));
|
||||
skuMapper.update(null, new LambdaUpdateWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getId, skuId)
|
||||
.set(ProductSkuPO::getSpecCombinationKey, null)
|
||||
.set(ProductSkuPO::getUpdateBy, userId));
|
||||
ProductSkuVO vo = productSkuService.toVo(skuMapper.selectById(skuId));
|
||||
vo.setSpecValues(List.of());
|
||||
return vo;
|
||||
}
|
||||
|
||||
ResolvedSpecValues resolved = resolveSpecValues(productId, valueIds);
|
||||
String key = ProductSpecCodes.combinationKey(
|
||||
resolved.values().stream().map(ProductSpecValuePO::getId).toList());
|
||||
assertCombinationAvailable(productId, key, skuId);
|
||||
|
||||
replaceSkuSpecRels(skuId, resolved.values());
|
||||
sku.setSpecCombinationKey(key);
|
||||
sku.setUpdateBy(userId);
|
||||
// 刻意不改 sku_code / name:外部同步编码可保留
|
||||
skuMapper.updateById(sku);
|
||||
|
||||
ProductSkuVO vo = productSkuService.toVo(skuMapper.selectById(skuId));
|
||||
vo.setSpecValues(resolved.values().stream().map(this::toValueVo).toList());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 校验规格值归属与同维唯一,返回有序解析结果。 */
|
||||
private ResolvedSpecValues resolveSpecValues(Long productId, List<Long> rawValueIds) {
|
||||
List<Long> valueIds = rawValueIds.stream().filter(Objects::nonNull).distinct().toList();
|
||||
if (valueIds.isEmpty()) {
|
||||
throw new BusinessException("请至少选择一个规格值");
|
||||
}
|
||||
List<ProductSpecValuePO> values = valueMapper.selectBatchIds(valueIds);
|
||||
if (values.size() != valueIds.size()) {
|
||||
throw new BusinessException("存在无效的规格值");
|
||||
}
|
||||
for (ProductSpecValuePO v : values) {
|
||||
if (!Objects.equals(v.getProductId(), productId)) {
|
||||
throw new BusinessException("规格值不属于当前商品");
|
||||
}
|
||||
}
|
||||
Set<Long> specIds = new HashSet<>();
|
||||
for (ProductSpecValuePO v : values) {
|
||||
if (!specIds.add(v.getSpecId())) {
|
||||
throw new BusinessException("同一规格维只能选择一个规格值");
|
||||
}
|
||||
}
|
||||
Map<Long, ProductSpecPO> specById = specMapper.selectBatchIds(specIds).stream()
|
||||
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
|
||||
return new ResolvedSpecValues(values, specById);
|
||||
}
|
||||
|
||||
/** 同商品下组合键唯一(excludeSkuId 为当前绑定 SKU 时可排除自身)。 */
|
||||
private void assertCombinationAvailable(Long productId, String key, Long excludeSkuId) {
|
||||
if (!StringUtils.hasText(key)) {
|
||||
return;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSkuPO> w = new LambdaQueryWrapper<ProductSkuPO>()
|
||||
.eq(ProductSkuPO::getProductId, productId)
|
||||
.eq(ProductSkuPO::getSpecCombinationKey, key);
|
||||
if (excludeSkuId != null) {
|
||||
w.ne(ProductSkuPO::getId, excludeSkuId);
|
||||
}
|
||||
if (skuMapper.selectCount(w) > 0) {
|
||||
throw new BusinessException("该规格组合已被其他 SKU 占用");
|
||||
}
|
||||
}
|
||||
|
||||
/** 覆盖写 SKU-规格值关系。 */
|
||||
private void replaceSkuSpecRels(Long skuId, List<ProductSpecValuePO> values) {
|
||||
skuSpecValueMapper.delete(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSkuId, skuId));
|
||||
for (ProductSpecValuePO v : values) {
|
||||
ProductSkuSpecValuePO rel = new ProductSkuSpecValuePO();
|
||||
rel.setSkuId(skuId);
|
||||
rel.setSpecValueId(v.getId());
|
||||
skuSpecValueMapper.insert(rel);
|
||||
}
|
||||
}
|
||||
|
||||
private record ResolvedSpecValues(List<ProductSpecValuePO> values,
|
||||
Map<Long, ProductSpecPO> specById) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Long, List<ProductSpecValueVO>> listSkuSpecValues(Collection<Long> skuIds) {
|
||||
if (skuIds == null || skuIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
List<ProductSkuSpecValuePO> rels = skuSpecValueMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.in(ProductSkuSpecValuePO::getSkuId, skuIds));
|
||||
if (rels.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Set<Long> valueIds = rels.stream().map(ProductSkuSpecValuePO::getSpecValueId).collect(Collectors.toSet());
|
||||
Map<Long, ProductSpecValuePO> valueMap = valueMapper.selectBatchIds(valueIds).stream()
|
||||
.collect(Collectors.toMap(ProductSpecValuePO::getId, v -> v, (a, b) -> a));
|
||||
Map<Long, List<ProductSpecValueVO>> result = new HashMap<>();
|
||||
for (ProductSkuSpecValuePO rel : rels) {
|
||||
ProductSpecValuePO po = valueMap.get(rel.getSpecValueId());
|
||||
if (po == null) {
|
||||
continue;
|
||||
}
|
||||
result.computeIfAbsent(rel.getSkuId(), k -> new ArrayList<>()).add(toValueVo(po));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ProductSpecValueVO toValueVo(ProductSpecValuePO v) {
|
||||
ProductSpecValueVO vv = new ProductSpecValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setSpecId(v.getSpecId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
return vv;
|
||||
}
|
||||
|
||||
private ProductSpecPO resolveOrCreateSpec(ProductPO product, Long id, String name,
|
||||
int sortOrder, Long userId) {
|
||||
if (id != null && id > 0) {
|
||||
ProductSpecPO existing = specMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getProductId(), product.getId())) {
|
||||
throw new BusinessException("规格不存在或不属于当前商品");
|
||||
}
|
||||
existing.setName(name);
|
||||
existing.setSortOrder(sortOrder);
|
||||
existing.setUpdateBy(userId);
|
||||
specMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
ProductSpecPO po = new ProductSpecPO();
|
||||
po.setCompanyId(product.getCompanyId());
|
||||
po.setProductId(product.getId());
|
||||
po.setName(name);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
specMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
private ProductSpecValuePO resolveOrCreateValue(ProductPO product, ProductSpecPO spec, Long id,
|
||||
String valueName, String valueCode,
|
||||
int sortOrder, Long userId) {
|
||||
if (id != null && id > 0) {
|
||||
ProductSpecValuePO existing = valueMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getProductId(), product.getId())
|
||||
|| !Objects.equals(existing.getSpecId(), spec.getId())) {
|
||||
throw new BusinessException("规格值不存在或不属于当前规格");
|
||||
}
|
||||
if (isValueReferenced(existing.getId())) {
|
||||
if (!Objects.equals(existing.getValueName(), valueName)
|
||||
|| !Objects.equals(existing.getValueCode(), valueCode)) {
|
||||
throw new BusinessException("规格值「" + existing.getValueName()
|
||||
+ "」已被 SKU 使用,禁止修改名称或编码");
|
||||
}
|
||||
} else {
|
||||
existing.setValueName(valueName);
|
||||
existing.setValueCode(valueCode);
|
||||
}
|
||||
existing.setSortOrder(sortOrder);
|
||||
existing.setUpdateBy(userId);
|
||||
valueMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
ProductSpecValuePO po = new ProductSpecValuePO();
|
||||
po.setCompanyId(product.getCompanyId());
|
||||
po.setProductId(product.getId());
|
||||
po.setSpecId(spec.getId());
|
||||
po.setValueName(valueName);
|
||||
po.setValueCode(valueCode);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
valueMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
private boolean isValueReferenced(Long specValueId) {
|
||||
return skuSpecValueMapper.selectCount(new LambdaQueryWrapper<ProductSkuSpecValuePO>()
|
||||
.eq(ProductSkuSpecValuePO::getSpecValueId, specValueId)) > 0;
|
||||
}
|
||||
|
||||
private List<ProductSpecVO> loadSpecTree(Long productId) {
|
||||
List<ProductSpecPO> specs = specMapper.selectList(new LambdaQueryWrapper<ProductSpecPO>()
|
||||
.eq(ProductSpecPO::getProductId, productId)
|
||||
.orderByAsc(ProductSpecPO::getSortOrder)
|
||||
.orderByAsc(ProductSpecPO::getId));
|
||||
if (specs.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> specIds = specs.stream().map(ProductSpecPO::getId).toList();
|
||||
Map<Long, List<ProductSpecValuePO>> valuesBySpec = valueMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductSpecValuePO>()
|
||||
.in(ProductSpecValuePO::getSpecId, specIds)
|
||||
.orderByAsc(ProductSpecValuePO::getSortOrder)
|
||||
.orderByAsc(ProductSpecValuePO::getId))
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(ProductSpecValuePO::getSpecId));
|
||||
List<ProductSpecVO> result = new ArrayList<>();
|
||||
for (ProductSpecPO s : specs) {
|
||||
ProductSpecVO vo = new ProductSpecVO();
|
||||
vo.setId(s.getId());
|
||||
vo.setName(s.getName());
|
||||
vo.setSortOrder(s.getSortOrder());
|
||||
List<ProductSpecValueVO> vals = new ArrayList<>();
|
||||
for (ProductSpecValuePO v : valuesBySpec.getOrDefault(s.getId(), List.of())) {
|
||||
ProductSpecValueVO vv = new ProductSpecValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setSpecId(v.getSpecId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
vals.add(vv);
|
||||
}
|
||||
vo.setValues(vals);
|
||||
result.add(vo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ProductPO requireProduct(Long productId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ProductPO product = productMapper.selectById(productId);
|
||||
if (product == null || !Objects.equals(product.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
return product;
|
||||
}
|
||||
|
||||
private static String requireText(String s, String message) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static void validateValueCode(String code) {
|
||||
if (!code.matches("^[A-Za-z0-9_-]+$")) {
|
||||
throw new BusinessException("规格值编码仅允许字母、数字、下划线、中划线: " + code);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<List<ProductSpecValuePO>> cartesian(List<List<ProductSpecValuePO>> dims) {
|
||||
List<List<ProductSpecValuePO>> result = new ArrayList<>();
|
||||
result.add(new ArrayList<>());
|
||||
for (List<ProductSpecValuePO> dim : dims) {
|
||||
List<List<ProductSpecValuePO>> next = new ArrayList<>();
|
||||
for (List<ProductSpecValuePO> prefix : result) {
|
||||
for (ProductSpecValuePO v : dim) {
|
||||
List<ProductSpecValuePO> row = new ArrayList<>(prefix);
|
||||
row.add(v);
|
||||
next.add(row);
|
||||
}
|
||||
}
|
||||
result = next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private record PendingSku(String combinationKey, String skuCode, String displayName,
|
||||
List<ProductSpecValuePO> values) {
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 规格模板 API:公司级单维 CRUD。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/ec/product/spec-templates")
|
||||
public class SpecTemplateController {
|
||||
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public SpecTemplateController(SpecTemplateService specTemplateService) {
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@RequirePermission(value = "ec:product:spec-template:read", description = "查询规格模板列表", allowSuper = true)
|
||||
public ApiResponse<List<SpecTemplateVO>> list() {
|
||||
return ApiResponse.success("获取成功", specTemplateService.listForCompany());
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:read", description = "查询规格模板详情", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> get(@PathVariable Long id) {
|
||||
return ApiResponse.success("获取成功", specTemplateService.get(id));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@RequirePermission(value = "ec:product:spec-template:create", description = "创建规格模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> create(@Valid @RequestBody CreateSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("创建成功", specTemplateService.create(dto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:update", description = "更新规格模板", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> update(@PathVariable Long id,
|
||||
@Valid @RequestBody UpdateSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("更新成功", specTemplateService.update(id, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/{id}/content")
|
||||
@RequirePermission(value = "ec:product:spec-template:update", description = "覆盖规格模板值", allowSuper = true)
|
||||
public ApiResponse<SpecTemplateVO> replaceContent(@PathVariable Long id,
|
||||
@Valid @RequestBody ReplaceSpecTemplateDTO dto) {
|
||||
return ApiResponse.success("保存成功", specTemplateService.replaceContent(id, dto));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
@RequirePermission(value = "ec:product:spec-template:delete", description = "删除规格模板", allowSuper = true)
|
||||
public ApiResponse<Void> delete(@PathVariable Long id) {
|
||||
specTemplateService.delete(id);
|
||||
return ApiResponse.<Void>success("删除成功", null);
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplatePO;
|
||||
|
||||
@Mapper
|
||||
public interface SpecTemplateMapper extends BaseMapper<SpecTemplatePO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplateValuePO;
|
||||
|
||||
@Mapper
|
||||
public interface SpecTemplateValueMapper extends BaseMapper<SpecTemplateValuePO> {
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 将模板维值套用到商品规格(合并,不生成 SKU)。 */
|
||||
@Data
|
||||
public class ApplySpecTemplateDTO {
|
||||
|
||||
@NotNull(message = "模板ID不能为空")
|
||||
private Long templateId;
|
||||
|
||||
/** 可选;空表示模板下全部值 */
|
||||
private List<Long> templateValueIds;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 创建公司级规格模板(单维)。 */
|
||||
@Data
|
||||
public class CreateSpecTemplateDTO {
|
||||
|
||||
@NotBlank(message = "模板名称不能为空")
|
||||
private String name;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ReplaceSpecTemplateDTO.ValueItem> values;
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
@Data
|
||||
public class ReplaceSpecTemplateDTO {
|
||||
|
||||
@Valid
|
||||
private List<ValueItem> values;
|
||||
|
||||
@Data
|
||||
public static class ValueItem {
|
||||
|
||||
/** 已有值 ID;空表示新增 */
|
||||
private Long id;
|
||||
|
||||
@NotBlank(message = "规格值名称不能为空")
|
||||
private String valueName;
|
||||
|
||||
@NotBlank(message = "规格值编码不能为空")
|
||||
@Pattern(regexp = "^[A-Za-z0-9_-]+$", message = "规格值编码仅允许字母、数字、下划线、中划线")
|
||||
private String valueCode;
|
||||
|
||||
private Integer sortOrder;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
/** 将商品某一规格维另存为公司模板。 */
|
||||
@Data
|
||||
public class SaveProductAsTemplateDTO {
|
||||
|
||||
@NotNull(message = "商品规格ID不能为空")
|
||||
private Long productSpecId;
|
||||
|
||||
/** 可选;覆盖模板名,默认取规格维名称 */
|
||||
private String name;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 更新公司级模板;values 非空时全量覆盖规格值。 */
|
||||
@Data
|
||||
public class UpdateSpecTemplateDTO {
|
||||
|
||||
private String name;
|
||||
|
||||
private String remark;
|
||||
|
||||
private Integer sortOrder;
|
||||
|
||||
@Valid
|
||||
private List<ReplaceSpecTemplateDTO.ValueItem> values;
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 规格模板(单维);name 即规格维名称。 */
|
||||
@Data
|
||||
@TableName("ec_spec_template")
|
||||
public class SpecTemplatePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("name")
|
||||
private String name;
|
||||
|
||||
@TableField("remark")
|
||||
private String remark;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** 规格模板值。 */
|
||||
@Data
|
||||
@TableName("ec_spec_template_value")
|
||||
public class SpecTemplateValuePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("template_id")
|
||||
private Long templateId;
|
||||
|
||||
@TableField("value_name")
|
||||
private String valueName;
|
||||
|
||||
@TableField("value_code")
|
||||
private String valueCode;
|
||||
|
||||
@TableField("sort_order")
|
||||
private Integer sortOrder;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** 规格模板视图(单维 + 值列表)。 */
|
||||
@Data
|
||||
public class SpecTemplateVO {
|
||||
|
||||
private Long id;
|
||||
private Long companyId;
|
||||
/** 规格维名称,如颜色、尺码 */
|
||||
private String name;
|
||||
private String remark;
|
||||
private Integer sortOrder;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime updateTime;
|
||||
private List<SpecTemplateValueVO> values;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/** 规格模板值视图。 */
|
||||
@Data
|
||||
public class SpecTemplateValueVO {
|
||||
|
||||
private Long id;
|
||||
private String valueName;
|
||||
private String valueCode;
|
||||
private Integer sortOrder;
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 规格模板:公司级单维维护、套用与另存。 */
|
||||
public interface SpecTemplateService {
|
||||
|
||||
/** 本公司模板列表;无模板时先种子默认维。 */
|
||||
List<SpecTemplateVO> listForCompany();
|
||||
|
||||
/** 读取本公司模板详情。 */
|
||||
SpecTemplateVO get(Long id);
|
||||
|
||||
/** 创建本公司模板。 */
|
||||
SpecTemplateVO create(CreateSpecTemplateDTO dto);
|
||||
|
||||
/** 更新本公司模板;values 非空时全量覆盖规格值。 */
|
||||
SpecTemplateVO update(Long id, UpdateSpecTemplateDTO dto);
|
||||
|
||||
/** 删除本公司模板。 */
|
||||
void delete(Long id);
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
SpecTemplateVO replaceContent(Long id, ReplaceSpecTemplateDTO dto);
|
||||
|
||||
/** 按勾选值合并到商品规格,不生成 SKU。 */
|
||||
List<ProductSpecVO> applyToProduct(Long productId, ApplySpecTemplateDTO dto);
|
||||
|
||||
/** 从商品某一规格维拷贝创建本公司模板。 */
|
||||
SpecTemplateVO saveProductAsTemplate(Long productId, SaveProductAsTemplateDTO dto);
|
||||
|
||||
/** 为公司种子默认规格维(款式/颜色/尺码/容量),已存在则跳过。 */
|
||||
void seedDefaultTemplates(Long companyId, Long userId);
|
||||
}
|
||||
+551
@@ -0,0 +1,551 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.dto.ReplaceProductSpecsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.model.vo.ProductSpecValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper.SpecTemplateMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.mapper.SpecTemplateValueMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ApplySpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.CreateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.ReplaceSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.SaveProductAsTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.dto.UpdateSpecTemplateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplatePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.po.SpecTemplateValuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.model.vo.SpecTemplateValueVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 规格模板服务:公司级单维 CRUD、默认种子、套用与另存。
|
||||
*/
|
||||
@Service
|
||||
public class SpecTemplateServiceImpl implements SpecTemplateService {
|
||||
|
||||
private final SpecTemplateMapper templateMapper;
|
||||
private final SpecTemplateValueMapper valueMapper;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public SpecTemplateServiceImpl(SpecTemplateMapper templateMapper,
|
||||
SpecTemplateValueMapper valueMapper,
|
||||
ProductSpecService productSpecService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.templateMapper = templateMapper;
|
||||
this.valueMapper = valueMapper;
|
||||
this.productSpecService = productSpecService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<SpecTemplateVO> listForCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (countByCompany(companyId) == 0) {
|
||||
seedDefaultTemplates(companyId, currentUserContext.getCurrentUserId());
|
||||
}
|
||||
List<SpecTemplatePO> templates = templateMapper.selectList(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.orderByAsc(SpecTemplatePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplatePO::getId));
|
||||
return toVoList(templates);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SpecTemplateVO get(Long id) {
|
||||
SpecTemplatePO po = requireCompanyTemplate(id);
|
||||
return toVoWithValues(po);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO create(CreateSpecTemplateDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
String name = requireText(dto.getName(), "模板名称不能为空");
|
||||
assertCompanyNameAvailable(companyId, name, null);
|
||||
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setRemark(trimToNull(dto.getRemark()));
|
||||
po.setSortOrder(dto.getSortOrder() != null ? dto.getSortOrder() : 0);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
if (dto.getValues() != null && !dto.getValues().isEmpty()) {
|
||||
doReplaceContent(po.getId(), dto.getValues());
|
||||
}
|
||||
return get(po.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO update(Long id, UpdateSpecTemplateDTO dto) {
|
||||
SpecTemplatePO po = requireCompanyTemplate(id);
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
if (StringUtils.hasText(dto.getName())) {
|
||||
String name = dto.getName().trim();
|
||||
if (!Objects.equals(name, po.getName())) {
|
||||
assertCompanyNameAvailable(po.getCompanyId(), name, po.getId());
|
||||
}
|
||||
po.setName(name);
|
||||
}
|
||||
if (dto.getRemark() != null) {
|
||||
po.setRemark(trimToNull(dto.getRemark()));
|
||||
}
|
||||
if (dto.getSortOrder() != null) {
|
||||
po.setSortOrder(dto.getSortOrder());
|
||||
}
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.updateById(po);
|
||||
|
||||
if (dto.getValues() != null && !dto.getValues().isEmpty()) {
|
||||
doReplaceContent(id, dto.getValues());
|
||||
}
|
||||
return get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delete(Long id) {
|
||||
requireCompanyTemplate(id);
|
||||
templateMapper.deleteById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO replaceContent(Long id, ReplaceSpecTemplateDTO dto) {
|
||||
requireCompanyTemplate(id);
|
||||
List<ReplaceSpecTemplateDTO.ValueItem> items =
|
||||
dto.getValues() == null ? List.of() : dto.getValues();
|
||||
doReplaceContent(id, items);
|
||||
return get(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public List<ProductSpecVO> applyToProduct(Long productId, ApplySpecTemplateDTO dto) {
|
||||
SpecTemplatePO template = requireCompanyTemplate(dto.getTemplateId());
|
||||
List<SpecTemplateValueVO> selected = filterTemplateValues(template.getId(), dto);
|
||||
if (selected.isEmpty()) {
|
||||
throw new BusinessException("未选中任何模板规格值");
|
||||
}
|
||||
|
||||
List<ProductSpecVO> existing = productSpecService.listByProductId(productId);
|
||||
ReplaceProductSpecsDTO replaceDto = buildMergedReplaceDto(existing, template, selected);
|
||||
return productSpecService.replaceSpecs(productId, replaceDto);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public SpecTemplateVO saveProductAsTemplate(Long productId, SaveProductAsTemplateDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
|
||||
ProductSpecVO sourceSpec = productSpecService.listByProductId(productId).stream()
|
||||
.filter(s -> Objects.equals(s.getId(), dto.getProductSpecId()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException("商品规格不存在"));
|
||||
|
||||
String name = StringUtils.hasText(dto.getName())
|
||||
? dto.getName().trim() : sourceSpec.getName();
|
||||
assertCompanyNameAvailable(companyId, name, null);
|
||||
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setSortOrder(sourceSpec.getSortOrder() != null ? sourceSpec.getSortOrder() : 0);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
copyProductSpecValuesToTemplate(po.getId(), sourceSpec);
|
||||
return get(po.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void seedDefaultTemplates(Long companyId, Long userId) {
|
||||
seedOneIfAbsent(companyId, userId, "款式", 0,
|
||||
List.of(value("标准款", "STD", 0)));
|
||||
seedOneIfAbsent(companyId, userId, "颜色", 1,
|
||||
List.of(
|
||||
value("黑色", "BLK", 0),
|
||||
value("白色", "WHT", 1),
|
||||
value("灰色", "GRY", 2),
|
||||
value("红色", "RED", 3),
|
||||
value("蓝色", "BLU", 4)));
|
||||
seedOneIfAbsent(companyId, userId, "尺码", 2,
|
||||
List.of(
|
||||
value("S", "S", 0),
|
||||
value("M", "M", 1),
|
||||
value("L", "L", 2),
|
||||
value("XL", "XL", 3)));
|
||||
seedOneIfAbsent(companyId, userId, "容量", 3,
|
||||
List.of(
|
||||
value("100ML", "100ML", 0),
|
||||
value("250ML", "250ML", 1),
|
||||
value("500ML", "500ML", 2),
|
||||
value("1L", "1L", 3)));
|
||||
}
|
||||
|
||||
/** 全量覆盖模板规格值。 */
|
||||
private void doReplaceContent(Long templateId, List<ReplaceSpecTemplateDTO.ValueItem> items) {
|
||||
Set<Long> keepValueIds = new HashSet<>();
|
||||
Set<String> nameSeen = new HashSet<>();
|
||||
Set<String> codeSeen = new HashSet<>();
|
||||
int valueOrder = 0;
|
||||
|
||||
for (ReplaceSpecTemplateDTO.ValueItem vi : items) {
|
||||
if (vi == null) {
|
||||
continue;
|
||||
}
|
||||
String vn = requireText(vi.getValueName(), "规格值名称不能为空");
|
||||
String vc = requireText(vi.getValueCode(), "规格值编码不能为空").toUpperCase();
|
||||
validateValueCode(vc);
|
||||
if (!nameSeen.add(vn)) {
|
||||
throw new BusinessException("同一模板下规格值名称重复: " + vn);
|
||||
}
|
||||
if (!codeSeen.add(vc)) {
|
||||
throw new BusinessException("同一模板下规格值编码重复: " + vc);
|
||||
}
|
||||
SpecTemplateValuePO value = resolveOrCreateValue(templateId, vi.getId(), vn, vc,
|
||||
vi.getSortOrder() != null ? vi.getSortOrder() : valueOrder++);
|
||||
keepValueIds.add(value.getId());
|
||||
}
|
||||
|
||||
List<SpecTemplateValuePO> existing = valueMapper.selectList(new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.eq(SpecTemplateValuePO::getTemplateId, templateId));
|
||||
for (SpecTemplateValuePO v : existing) {
|
||||
if (!keepValueIds.contains(v.getId())) {
|
||||
valueMapper.deleteById(v.getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 按勾选过滤模板值;空表示全部值。 */
|
||||
private List<SpecTemplateValueVO> filterTemplateValues(Long templateId, ApplySpecTemplateDTO dto) {
|
||||
List<SpecTemplateValueVO> all = toValueVos(loadValues(templateId));
|
||||
if (dto.getTemplateValueIds() == null || dto.getTemplateValueIds().isEmpty()) {
|
||||
return all;
|
||||
}
|
||||
Set<Long> filter = dto.getTemplateValueIds().stream()
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
return all.stream()
|
||||
.filter(v -> filter.contains(v.getId()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
/** 合并模板维名与值到商品 ReplaceProductSpecsDTO。 */
|
||||
private ReplaceProductSpecsDTO buildMergedReplaceDto(List<ProductSpecVO> existing,
|
||||
SpecTemplatePO template,
|
||||
List<SpecTemplateValueVO> templateValues) {
|
||||
List<ReplaceProductSpecsDTO.SpecItem> items = new ArrayList<>();
|
||||
Map<String, ReplaceProductSpecsDTO.SpecItem> itemByName = new LinkedHashMap<>();
|
||||
|
||||
for (ProductSpecVO spec : existing) {
|
||||
ReplaceProductSpecsDTO.SpecItem item = toReplaceSpecItem(spec);
|
||||
items.add(item);
|
||||
itemByName.put(spec.getName(), item);
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO.SpecItem target = itemByName.get(template.getName());
|
||||
if (target != null) {
|
||||
mergeTemplateValuesIntoSpec(target, template.getName(), templateValues);
|
||||
} else {
|
||||
ReplaceProductSpecsDTO.SpecItem newItem = new ReplaceProductSpecsDTO.SpecItem();
|
||||
newItem.setName(template.getName());
|
||||
newItem.setSortOrder(template.getSortOrder() != null ? template.getSortOrder() : items.size());
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values = new ArrayList<>();
|
||||
for (SpecTemplateValueVO tv : templateValues) {
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setValueName(tv.getValueName());
|
||||
vi.setValueCode(tv.getValueCode().toUpperCase());
|
||||
vi.setSortOrder(tv.getSortOrder());
|
||||
values.add(vi);
|
||||
}
|
||||
newItem.setValues(values);
|
||||
items.add(newItem);
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO dto = new ReplaceProductSpecsDTO();
|
||||
dto.setSpecs(items);
|
||||
return dto;
|
||||
}
|
||||
|
||||
/** 同名维合并:只追加不存在的值,名称/编码冲突则整次失败。 */
|
||||
private void mergeTemplateValuesIntoSpec(ReplaceProductSpecsDTO.SpecItem item,
|
||||
String specName,
|
||||
List<SpecTemplateValueVO> templateValues) {
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values =
|
||||
item.getValues() == null ? new ArrayList<>() : new ArrayList<>(item.getValues());
|
||||
item.setValues(values);
|
||||
|
||||
Map<String, ReplaceProductSpecsDTO.ValueItem> byName = values.stream()
|
||||
.collect(Collectors.toMap(ReplaceProductSpecsDTO.ValueItem::getValueName, v -> v, (a, b) -> a));
|
||||
Map<String, ReplaceProductSpecsDTO.ValueItem> byCode = values.stream()
|
||||
.collect(Collectors.toMap(v -> v.getValueCode().toUpperCase(), v -> v, (a, b) -> a));
|
||||
|
||||
int nextOrder = values.stream()
|
||||
.map(ReplaceProductSpecsDTO.ValueItem::getSortOrder)
|
||||
.filter(Objects::nonNull)
|
||||
.mapToInt(Integer::intValue)
|
||||
.max().orElse(-1) + 1;
|
||||
|
||||
for (SpecTemplateValueVO tv : templateValues) {
|
||||
String name = tv.getValueName();
|
||||
String code = tv.getValueCode().toUpperCase();
|
||||
validateValueCode(code);
|
||||
|
||||
ReplaceProductSpecsDTO.ValueItem byNameMatch = byName.get(name);
|
||||
ReplaceProductSpecsDTO.ValueItem byCodeMatch = byCode.get(code);
|
||||
|
||||
if (byNameMatch != null && byCodeMatch != null) {
|
||||
if (!Objects.equals(byNameMatch.getId(), byCodeMatch.getId())) {
|
||||
throw new BusinessException("规格「" + specName + "」下名称与编码指向不同已有值,冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byNameMatch != null) {
|
||||
if (!Objects.equals(byNameMatch.getValueCode().toUpperCase(), code)) {
|
||||
throw new BusinessException("规格「" + specName + "」下规格值名称「"
|
||||
+ name + "」已存在但编码冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (byCodeMatch != null) {
|
||||
if (!Objects.equals(byCodeMatch.getValueName(), name)) {
|
||||
throw new BusinessException("规格「" + specName + "」下规格值编码「"
|
||||
+ code + "」已存在但名称冲突");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setValueName(name);
|
||||
vi.setValueCode(code);
|
||||
vi.setSortOrder(tv.getSortOrder() != null ? tv.getSortOrder() : nextOrder++);
|
||||
values.add(vi);
|
||||
byName.put(name, vi);
|
||||
byCode.put(code, vi);
|
||||
}
|
||||
}
|
||||
|
||||
private SpecTemplateValuePO resolveOrCreateValue(Long templateId, Long id,
|
||||
String valueName, String valueCode, int sortOrder) {
|
||||
if (id != null && id > 0) {
|
||||
SpecTemplateValuePO existing = valueMapper.selectById(id);
|
||||
if (existing == null || !Objects.equals(existing.getTemplateId(), templateId)) {
|
||||
throw new BusinessException("模板规格值不存在或不属于当前模板");
|
||||
}
|
||||
existing.setValueName(valueName);
|
||||
existing.setValueCode(valueCode);
|
||||
existing.setSortOrder(sortOrder);
|
||||
valueMapper.updateById(existing);
|
||||
return existing;
|
||||
}
|
||||
SpecTemplateValuePO po = new SpecTemplateValuePO();
|
||||
po.setTemplateId(templateId);
|
||||
po.setValueName(valueName);
|
||||
po.setValueCode(valueCode);
|
||||
po.setSortOrder(sortOrder);
|
||||
valueMapper.insert(po);
|
||||
return po;
|
||||
}
|
||||
|
||||
/** 从商品规格维拷贝值到新模板。 */
|
||||
private void copyProductSpecValuesToTemplate(Long templateId, ProductSpecVO spec) {
|
||||
List<ProductSpecValueVO> values = spec.getValues() == null ? List.of() : spec.getValues();
|
||||
int valueOrder = 0;
|
||||
for (ProductSpecValueVO val : values) {
|
||||
SpecTemplateValuePO valPo = new SpecTemplateValuePO();
|
||||
valPo.setTemplateId(templateId);
|
||||
valPo.setValueName(val.getValueName());
|
||||
valPo.setValueCode(val.getValueCode());
|
||||
valPo.setSortOrder(val.getSortOrder() != null ? val.getSortOrder() : valueOrder++);
|
||||
valueMapper.insert(valPo);
|
||||
}
|
||||
}
|
||||
|
||||
private void seedOneIfAbsent(Long companyId, Long userId, String name, int sortOrder,
|
||||
List<SeedValue> values) {
|
||||
if (existsByCompanyAndName(companyId, name)) {
|
||||
return;
|
||||
}
|
||||
SpecTemplatePO po = new SpecTemplatePO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setName(name);
|
||||
po.setSortOrder(sortOrder);
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
templateMapper.insert(po);
|
||||
|
||||
int order = 0;
|
||||
for (SeedValue sv : values) {
|
||||
SpecTemplateValuePO valPo = new SpecTemplateValuePO();
|
||||
valPo.setTemplateId(po.getId());
|
||||
valPo.setValueName(sv.name());
|
||||
valPo.setValueCode(sv.code());
|
||||
valPo.setSortOrder(sv.sortOrder() != null ? sv.sortOrder() : order++);
|
||||
valueMapper.insert(valPo);
|
||||
}
|
||||
}
|
||||
|
||||
private List<SpecTemplateVO> toVoList(List<SpecTemplatePO> templates) {
|
||||
if (templates.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Long> templateIds = templates.stream().map(SpecTemplatePO::getId).toList();
|
||||
Map<Long, List<SpecTemplateValuePO>> valuesByTemplate = valueMapper.selectList(
|
||||
new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.in(SpecTemplateValuePO::getTemplateId, templateIds)
|
||||
.orderByAsc(SpecTemplateValuePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplateValuePO::getId))
|
||||
.stream()
|
||||
.collect(Collectors.groupingBy(SpecTemplateValuePO::getTemplateId));
|
||||
|
||||
List<SpecTemplateVO> result = new ArrayList<>();
|
||||
for (SpecTemplatePO po : templates) {
|
||||
result.add(toVo(po, valuesByTemplate.getOrDefault(po.getId(), List.of())));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private SpecTemplateVO toVoWithValues(SpecTemplatePO po) {
|
||||
return toVo(po, loadValues(po.getId()));
|
||||
}
|
||||
|
||||
private SpecTemplateVO toVo(SpecTemplatePO po, List<SpecTemplateValuePO> values) {
|
||||
SpecTemplateVO vo = new SpecTemplateVO();
|
||||
vo.setId(po.getId());
|
||||
vo.setCompanyId(po.getCompanyId());
|
||||
vo.setName(po.getName());
|
||||
vo.setRemark(po.getRemark());
|
||||
vo.setSortOrder(po.getSortOrder());
|
||||
vo.setCreateTime(po.getCreateTime());
|
||||
vo.setUpdateTime(po.getUpdateTime());
|
||||
vo.setValues(toValueVos(values));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private List<SpecTemplateValuePO> loadValues(Long templateId) {
|
||||
return valueMapper.selectList(new LambdaQueryWrapper<SpecTemplateValuePO>()
|
||||
.eq(SpecTemplateValuePO::getTemplateId, templateId)
|
||||
.orderByAsc(SpecTemplateValuePO::getSortOrder)
|
||||
.orderByAsc(SpecTemplateValuePO::getId));
|
||||
}
|
||||
|
||||
private List<SpecTemplateValueVO> toValueVos(List<SpecTemplateValuePO> values) {
|
||||
List<SpecTemplateValueVO> result = new ArrayList<>();
|
||||
for (SpecTemplateValuePO v : values) {
|
||||
SpecTemplateValueVO vv = new SpecTemplateValueVO();
|
||||
vv.setId(v.getId());
|
||||
vv.setValueName(v.getValueName());
|
||||
vv.setValueCode(v.getValueCode());
|
||||
vv.setSortOrder(v.getSortOrder());
|
||||
result.add(vv);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ReplaceProductSpecsDTO.SpecItem toReplaceSpecItem(ProductSpecVO spec) {
|
||||
ReplaceProductSpecsDTO.SpecItem item = new ReplaceProductSpecsDTO.SpecItem();
|
||||
item.setId(spec.getId());
|
||||
item.setName(spec.getName());
|
||||
item.setSortOrder(spec.getSortOrder());
|
||||
List<ReplaceProductSpecsDTO.ValueItem> values = new ArrayList<>();
|
||||
if (spec.getValues() != null) {
|
||||
for (ProductSpecValueVO v : spec.getValues()) {
|
||||
ReplaceProductSpecsDTO.ValueItem vi = new ReplaceProductSpecsDTO.ValueItem();
|
||||
vi.setId(v.getId());
|
||||
vi.setValueName(v.getValueName());
|
||||
vi.setValueCode(v.getValueCode());
|
||||
vi.setSortOrder(v.getSortOrder());
|
||||
values.add(vi);
|
||||
}
|
||||
}
|
||||
item.setValues(values);
|
||||
return item;
|
||||
}
|
||||
|
||||
/** 可读写:仅本公司模板。 */
|
||||
private SpecTemplatePO requireCompanyTemplate(Long id) {
|
||||
SpecTemplatePO po = templateMapper.selectById(id);
|
||||
if (po == null) {
|
||||
throw new BusinessException("规格模板不存在");
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (!Objects.equals(po.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("规格模板不存在");
|
||||
}
|
||||
return po;
|
||||
}
|
||||
|
||||
private long countByCompany(Long companyId) {
|
||||
return templateMapper.selectCount(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId));
|
||||
}
|
||||
|
||||
private boolean existsByCompanyAndName(Long companyId, String name) {
|
||||
return templateMapper.selectCount(new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.eq(SpecTemplatePO::getName, name)) > 0;
|
||||
}
|
||||
|
||||
private void assertCompanyNameAvailable(Long companyId, String name, Long excludeId) {
|
||||
LambdaQueryWrapper<SpecTemplatePO> w = new LambdaQueryWrapper<SpecTemplatePO>()
|
||||
.eq(SpecTemplatePO::getCompanyId, companyId)
|
||||
.eq(SpecTemplatePO::getName, name);
|
||||
if (excludeId != null) {
|
||||
w.ne(SpecTemplatePO::getId, excludeId);
|
||||
}
|
||||
if (templateMapper.selectCount(w) > 0) {
|
||||
throw new BusinessException("模板名称已存在: " + name);
|
||||
}
|
||||
}
|
||||
|
||||
private static SeedValue value(String name, String code, int sortOrder) {
|
||||
return new SeedValue(name, code, sortOrder);
|
||||
}
|
||||
|
||||
private record SeedValue(String name, String code, Integer sortOrder) {}
|
||||
|
||||
private static String requireText(String s, String message) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
throw new BusinessException(message);
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static String trimToNull(String s) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
return null;
|
||||
}
|
||||
return s.trim();
|
||||
}
|
||||
|
||||
private static void validateValueCode(String code) {
|
||||
if (!code.matches("^[A-Za-z0-9_-]+$")) {
|
||||
throw new BusinessException("规格值编码仅允许字母、数字、下划线、中划线: " + code);
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-1
@@ -34,6 +34,7 @@ import top.xyquan.ecomdmbbackend.modules.org.company.member.enums.CompanyMemberR
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseEnforcement;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseInfo;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseValidator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.spec.template.service.SpecTemplateService;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
@@ -59,12 +60,14 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
private final CompanyMemberService companyMemberService;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final LicenseValidator licenseValidator;
|
||||
private final SpecTemplateService specTemplateService;
|
||||
|
||||
public CompanyServiceImpl(@Lazy CurrentUserContext currentUserContext, SysFileService sysFileService,
|
||||
CompanyMenuService companyMenuService, DepartmentService departmentService,
|
||||
PositionService positionService, MenuService menuService,
|
||||
@Lazy UserService userService, @Lazy CompanyMemberService companyMemberService,
|
||||
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator) {
|
||||
PasswordEncoder passwordEncoder, LicenseValidator licenseValidator,
|
||||
@Lazy SpecTemplateService specTemplateService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.sysFileService = sysFileService;
|
||||
this.companyMenuService = companyMenuService;
|
||||
@@ -75,6 +78,7 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
this.companyMemberService = companyMemberService;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.licenseValidator = licenseValidator;
|
||||
this.specTemplateService = specTemplateService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -166,6 +170,9 @@ public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> im
|
||||
// 初始化公司岗位
|
||||
initCompanyPositions(company.getId(), creatorId);
|
||||
|
||||
// 初始化默认规格模板
|
||||
specTemplateService.seedDefaultTemplates(company.getId(), creatorId);
|
||||
|
||||
// 转换为VO并返回
|
||||
return convertToVO(company);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user