feat: 新增导入功能

This commit is contained in:
ah--desktop
2025-12-04 23:22:02 +08:00
parent e2caac2965
commit d3d9fd47d8
33 changed files with 1585 additions and 176 deletions
@@ -20,6 +20,13 @@ public class CreateImportMappingDTO {
@Pattern(regexp = "^(product|order)$", message = "导入类型只能是product或order")
private String type;
/**
* 映射名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板", required = true)
@NotBlank(message = "映射名称不能为空")
private String name;
/**
* 字段映射(JSON格式)
*/
@@ -15,5 +15,11 @@ public class ImportMappingFilterDTO {
*/
@Schema(description = "导入类型", example = "product", allowableValues = {"product", "order"})
private String type;
/**
* 映射名称(模糊查询)
*/
@Schema(description = "映射名称(模糊查询)", example = "商品导入")
private String name;
}
@@ -11,6 +11,12 @@ import lombok.Data;
@Schema(description = "更新导入映射DTO")
public class UpdateImportMappingDTO {
/**
* 映射名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板")
private String name;
/**
* 字段映射(JSON格式)
*/
@@ -23,6 +23,12 @@ public class CreateProductDTO {
@NotBlank(message = "商品名称不能为空")
private String name;
/**
* 商品编码
*/
@Schema(description = "商品编码", example = "IPHONE15PRO001")
private String productCode;
/**
* 主图图片ID
*/
@@ -3,8 +3,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.model.dto.product;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
/**
* 商品分页查询过滤DTO
*/
@@ -21,24 +19,6 @@ public class ProductFilterDTO {
/**
* 商品编码(模糊查询)
*/
@Schema(description = "商品编码(模糊查询)", example = "IPHONE")
private String specCode;
/**
* 商品SKU(模糊查询)
*/
@Schema(description = "商品SKU(模糊查询)", example = "IPHONE15")
private String skuCode;
/**
* 成本价范围-最小值
*/
@Schema(description = "成本价范围-最小值", example = "1000.00")
private BigDecimal minCostPrice;
/**
* 成本价范围-最大值
*/
@Schema(description = "成本价范围-最大值", example = "10000.00")
private BigDecimal maxCostPrice;
@Schema(description = "商品编码(模糊查询)", example = "IPHONE15PRO001")
private String productCode;
}
@@ -25,24 +25,11 @@ public class UpdateProductDTO {
* 商品编码
*/
@Schema(description = "商品编码", example = "IPHONE15PRO001")
private String specCode;
/**
* 商品SKU
*/
@Schema(description = "商品SKU", example = "IPHONE15PRO-128G-BLUE")
private String skuCode;
private String productCode;
/**
* 主图图片ID
*/
@Schema(description = "主图图片ID", example = "1")
private Long mainImageId;
/**
* 成本价
*/
@Schema(description = "成本价", example = "8000.00", required = true)
@NotNull(message = "成本价不能为空")
private BigDecimal costPrice;
}
@@ -32,6 +32,12 @@ public class ImportMappingPO {
@TableField("type")
private String type;
/**
* 映射模板名称
*/
@TableField("name")
private String name;
/**
* 字段映射(JSON格式)
*/
@@ -32,6 +32,12 @@ public class ProductPO {
@TableField("name")
private String name;
/**
* 商品编码
*/
@TableField("product_code")
private String productCode;
/**
* 主图URL(冗余字段)
*/
@@ -30,6 +30,12 @@ public class ImportMappingVO {
@Schema(description = "导入类型", example = "product")
private String type;
/**
* 映射名称
*/
@Schema(description = "映射名称", example = "商品导入映射模板")
private String name;
/**
* 字段映射(JSON格式)
*/
@@ -31,6 +31,12 @@ public class ProductVO {
@Schema(description = "商品名称", example = "iPhone 15 Pro")
private String name;
/**
* 商品编码
*/
@Schema(description = "商品编码", example = "IPHONE15PRO001")
private String productCode;
/**
* 主图URL
*/
@@ -47,12 +47,13 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
// 验证同一公司、同一类型是否已存在映射(根据唯一索引)
// 验证同一公司、同一类型、同一名称是否已存在映射(根据唯一索引)
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ImportMappingPO::getCompanyId, companyId)
.eq(ImportMappingPO::getType, createImportMappingDTO.getType());
.eq(ImportMappingPO::getType, createImportMappingDTO.getType())
.eq(ImportMappingPO::getName, createImportMappingDTO.getName());
if (this.count(wrapper) > 0) {
throw new BusinessException("该类型的导入映射已存在,请使用更新接口");
throw new BusinessException("该类型的导入映射名称已存在,请使用其他名称或更新接口");
}
// 创建导入映射
@@ -89,6 +90,19 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
throw new BusinessException("无权限操作此映射");
}
// 如果更新了名称,验证新名称是否与同一公司、同一类型的其他映射冲突
if (updateImportMappingDTO.getName() != null &&
!updateImportMappingDTO.getName().equals(existingMapping.getName())) {
LambdaQueryWrapper<ImportMappingPO> nameCheckWrapper = new LambdaQueryWrapper<>();
nameCheckWrapper.eq(ImportMappingPO::getCompanyId, companyId)
.eq(ImportMappingPO::getType, existingMapping.getType())
.eq(ImportMappingPO::getName, updateImportMappingDTO.getName())
.ne(ImportMappingPO::getId, id);
if (this.count(nameCheckWrapper) > 0) {
throw new BusinessException("该类型的导入映射名称已存在,请使用其他名称");
}
}
// 更新映射
ImportMappingPO importMappingPO = new ImportMappingPO();
BeanUtils.copyProperties(updateImportMappingDTO, importMappingPO);
@@ -140,8 +154,13 @@ public class ImportMappingServiceImpl extends ServiceImpl<ImportMappingMapper, I
LambdaQueryWrapper<ImportMappingPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ImportMappingPO::getCompanyId, companyId);
if (filter != null && StringUtils.hasText(filter.getType())) {
wrapper.eq(ImportMappingPO::getType, filter.getType());
if (filter != null) {
if (StringUtils.hasText(filter.getType())) {
wrapper.eq(ImportMappingPO::getType, filter.getType());
}
if (StringUtils.hasText(filter.getName())) {
wrapper.like(ImportMappingPO::getName, filter.getName());
}
}
// 按创建时间倒序
@@ -39,6 +39,7 @@ import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 导入任务处理器服务实现类
@@ -46,13 +47,52 @@ import java.util.Map;
@Service
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
/**
* 映射字段定义
*/
private static class MappingField {
private Boolean required;
private String fieldName;
private String fieldLabel;
private String fileFieldName;
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public String getFieldLabel() {
return fieldLabel;
}
public void setFieldLabel(String fieldLabel) {
this.fieldLabel = fieldLabel;
}
public String getFileFieldName() {
return fileFieldName;
}
public void setFileFieldName(String fileFieldName) {
this.fileFieldName = fileFieldName;
}
}
private static final Logger logger = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
private final ImportTaskService importTaskService;
private final OrderService orderService;
private final ProductService productService;
private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService;
private final OrderStatusMapper orderStatusMapper;
private final OrderMapper orderMapper;
private final ProductMapper productMapper;
@@ -72,10 +112,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
SseNotificationService sseNotificationService,
ObjectMapper objectMapper) {
this.importTaskService = importTaskService;
this.orderService = orderService;
this.productService = productService;
this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService;
this.orderStatusMapper = orderStatusMapper;
this.orderMapper = orderMapper;
this.productMapper = productMapper;
@@ -135,7 +172,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
*/
private void processOrderImport(ImportTaskPO task) throws IOException {
// 解析字段映射
Map<String, String> mapping = parseMapping(task.getMapping());
Map<String, MappingField> mapping = parseMapping(task.getMapping());
Long companyId = task.getCompanyId();
// 读取CSV文件
@@ -242,16 +279,24 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* 解析字段映射
*
* @param mappingJson 映射JSON字符串
* @return 字段映射Map(实体字段名 -> CSV表头名)
* @return 字段映射Map(实体字段名 -> 映射字段定义)
*/
private Map<String, String> parseMapping(String mappingJson) {
private Map<String, MappingField> parseMapping(String mappingJson) {
try {
if (mappingJson == null || mappingJson.trim().isEmpty()) {
throw new BusinessException("字段映射不能为空");
}
// 解析JSON,格式:{"specCode": "商家编码-规格维度", "specName": "商品规格", ...}
Map<String, String> mapping = objectMapper.readValue(mappingJson, new TypeReference<Map<String, String>>() {});
return mapping;
// 解析JSON数组,格式:[{"required": false, "fieldName": "productName", "fieldLabel": "商品名称", "fileFieldName": "商品"}, ...]
List<MappingField> mappingFields = objectMapper.readValue(mappingJson,
new TypeReference<List<MappingField>>() {});
if (mappingFields == null || mappingFields.isEmpty()) {
throw new BusinessException("字段映射不能为空");
}
// 转换为Map,key为fieldName,value为MappingField对象
return mappingFields.stream()
.collect(Collectors.toMap(MappingField::getFieldName, field -> field, (v1, v2) -> v1));
} catch (Exception e) {
throw new BusinessException("解析字段映射失败: " + e.getMessage());
}
@@ -261,94 +306,145 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* 从CSV记录解析订单数据
*
* @param record CSV记录
* @param mapping 字段映射
* @param mapping 字段映射(fieldName -> MappingField)
* @param shopId 店铺ID
* @param defaultStatusId 默认订单状态ID
* @param companyId 公司ID
* @param createBy 创建人ID
* @return 创建订单DTO
*/
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, String> mapping,
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, MappingField> mapping,
Long shopId, Long defaultStatusId, Long companyId, Long createBy) {
CreateOrderDTO orderDTO = new CreateOrderDTO();
orderDTO.setShopId(shopId);
orderDTO.setStatusId(defaultStatusId);
// 获取映射的CSV表头名
String specCodeHeader = mapping.get("specCode");
String receivedAmountHeader = mapping.get("receivedAmount");
String orderQuantityHeader = mapping.get("orderQuantity");
String orderStatusHeader = mapping.get("orderStatus");
String productNameHeader = mapping.get("productName");
String specNameHeader = mapping.get("specName");
String platformOrderNoHeader = mapping.get("platformOrderNo");
// 获取映射字段定义
MappingField specCodeField = mapping.get("specCode"); // 规格编码
MappingField receivedAmountField = mapping.get("receivedAmount"); // 商家实收金额
MappingField productQuantityField = mapping.get("productQuantity"); // 商品数量
MappingField orderStatusField = mapping.get("orderStatus"); // 订单状态
MappingField productNameField = mapping.get("productName"); // 商品名称
MappingField productCodeField = mapping.get("productCode"); // 商品编码
MappingField specNameField = mapping.get("specName"); // 规格名称
MappingField platformOrderNoField = mapping.get("platformOrderNo"); // 平台订单号
// 调试日志:记录字段映射
if (logger.isDebugEnabled()) {
logger.debug("字段映射 - specCodeHeader: {}, receivedAmountHeader: {}, orderQuantityHeader: {}",
specCodeHeader, receivedAmountHeader, orderQuantityHeader);
logger.debug("字段映射 - specCode: {}, receivedAmount: {}, productQuantity: {}",
specCodeField != null ? specCodeField.getFileFieldName() : null,
receivedAmountField != null ? receivedAmountField.getFileFieldName() : null,
productQuantityField != null ? productQuantityField.getFileFieldName() : null);
}
// 必填字段验证
String specCode = getValue(record, specCodeHeader);
String specCode = getValue(record, specCodeField);
if (specCode == null || specCode.trim().isEmpty()) {
// 提供更详细的错误信息
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
throw new BusinessException(String.format("规格编码不能为空。映射的表头名: '%s',可用的表头: [%s],当前行的所有值: %s",
specCodeHeader, availableHeaders, record.toMap()));
// 检查是否为必填字段
if (specCodeField != null && specCodeField.getRequired() != null && specCodeField.getRequired()) {
// 提供更详细的错误信息
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
String fileFieldName = specCodeField.getFileFieldName();
throw new BusinessException(String.format("规格编码不能为空。映射的表头名: '%s',可用的表头: [%s],当前行的所有值: %s",
fileFieldName, availableHeaders, record.toMap()));
} else if (specCodeField == null) {
// 如果映射中没有定义该字段,但规格编码是必需的,抛出异常
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
throw new BusinessException(String.format("规格编码不能为空。映射中未定义该字段,可用的表头: [%s],当前行的所有值: %s",
availableHeaders, record.toMap()));
}
}
String receivedAmountStr = getValue(record, receivedAmountHeader);
if (receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) {
String receivedAmountStr = getValue(record, receivedAmountField);
if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) &&
receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) {
throw new BusinessException("商家实收金额不能为空");
}
String orderQuantityStr = getValue(record, orderQuantityHeader);
if (orderQuantityStr == null || orderQuantityStr.trim().isEmpty()) {
throw new BusinessException("订单数量不能为空");
String productQuantityStr = getValue(record, productQuantityField);
if ((productQuantityStr == null || productQuantityStr.trim().isEmpty()) &&
productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) {
throw new BusinessException("商品数量不能为空");
}
// 解析必填字段
try {
orderDTO.setReceivedAmount(new BigDecimal(receivedAmountStr.trim()));
} catch (NumberFormatException e) {
throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr);
if (receivedAmountStr != null && !receivedAmountStr.trim().isEmpty()) {
try {
orderDTO.setReceivedAmount(new BigDecimal(receivedAmountStr.trim()));
} catch (NumberFormatException e) {
throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr);
}
} else if (receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) {
throw new BusinessException("商家实收金额不能为空");
}
try {
orderDTO.setQuantity(Integer.parseInt(orderQuantityStr.trim()));
if (orderDTO.getQuantity() <= 0) {
throw new BusinessException("订单数量必须大于0");
if (productQuantityStr != null && !productQuantityStr.trim().isEmpty()) {
try {
orderDTO.setQuantity(Integer.parseInt(productQuantityStr.trim()));
if (orderDTO.getQuantity() <= 0) {
throw new BusinessException("商品数量必须大于0");
}
} catch (NumberFormatException e) {
throw new BusinessException("商品数量格式错误: " + productQuantityStr);
}
} catch (NumberFormatException e) {
throw new BusinessException("订单数量格式错误: " + orderQuantityStr);
} else if (productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) {
throw new BusinessException("商品数量不能为空");
}
// 解析可选字段(先解析,用于后续创建商品和规格)
String productName = null;
if (productNameHeader != null) {
productName = getValue(record, productNameHeader);
productName = productName != null ? productName.trim() : null;
}
String productName = getValue(record, productNameField);
productName = productName != null ? productName.trim() : null;
String specName = null;
if (specNameHeader != null) {
specName = getValue(record, specNameHeader);
specName = specName != null ? specName.trim() : null;
}
String productCode = getValue(record, productCodeField);
productCode = productCode != null ? productCode.trim() : null;
String specName = getValue(record, specNameField);
specName = specName != null ? specName.trim() : null;
// 通过规格编码查找商品规格
// 首先通过规格编码查找商品规格
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId);
// 如果找不到规格,但有商品名称和规格名称,则自动创建商品和规格
// 如果找不到规格,则尝试通过商品编码或商品名称查找商品,然后创建规格
if (productSpec == null) {
if (productName != null && !productName.isEmpty() &&
specName != null && !specName.isEmpty()) {
logger.info("未找到规格编码 '{}',但提供了商品名称 '{}' 和规格名称 '{}',将自动创建商品和规格",
ProductPO product = null;
// 优先使用商品编码查找商品
if (productCode != null && !productCode.isEmpty()) {
product = findProductByProductCode(productCode, companyId);
if (product != null) {
logger.info("未找到规格编码 '{}',但通过商品编码 '{}' 找到了商品 '{}' (ID: {})",
specCode, productCode, product.getName(), product.getId());
}
}
// 如果商品编码查找失败,使用商品名称精准查找商品
if (product == null && productName != null && !productName.isEmpty()) {
product = findProductByName(productName, companyId);
if (product != null) {
logger.info("未找到规格编码 '{}',但通过商品名称 '{}' 找到了商品 (ID: {})",
specCode, productName, product.getId());
}
}
// 如果找到了商品,创建规格
if (product != null) {
if (specName == null || specName.isEmpty()) {
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
",且未提供规格名称,无法创建规格");
}
logger.info("为商品 '{}' (ID: {}) 创建规格 '{}' (编码: {})",
product.getName(), product.getId(), specName, specCode);
productSpec = createSpecForProduct(companyId, product.getId(), specName, specCode.trim(), createBy);
}
// 如果没有找到商品,但有商品名称和规格名称,则自动创建商品和规格
else if (productName != null && !productName.isEmpty() &&
specName != null && !specName.isEmpty()) {
logger.info("未找到规格编码 '{}',也未找到商品,将自动创建商品 '{}' 和规格 '{}'",
specCode, productName, specName);
productSpec = createProductAndSpecIfNotExists(companyId, productName, specName, specCode.trim(), createBy);
productSpec = createProductAndSpecIfNotExists(companyId, productName, productCode, specName, specCode.trim(), createBy);
} else {
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
(productCode == null || productCode.isEmpty() ? "" : ",商品编码 '" + productCode + "' 未找到商品") +
(productName == null || productName.isEmpty() ? ",且未提供商品名称" : "") +
(specName == null || specName.isEmpty() ? ",且未提供规格名称" : ""));
}
@@ -373,23 +469,23 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
orderDTO.setSpecName(productSpec.getName());
}
if (platformOrderNoHeader != null) {
String platformOrderNo = getValue(record, platformOrderNoHeader);
orderDTO.setPlatformOrderNo(platformOrderNo != null ? platformOrderNo.trim() : null);
String platformOrderNo = getValue(record, platformOrderNoField);
if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) {
orderDTO.setPlatformOrderNo(platformOrderNo.trim());
}
// 计算销售单价(商家实收金额 / 数量)
orderDTO.setUnitPrice(orderDTO.getReceivedAmount()
.divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP));
if (orderDTO.getReceivedAmount() != null && orderDTO.getQuantity() != null && orderDTO.getQuantity() > 0) {
orderDTO.setUnitPrice(orderDTO.getReceivedAmount()
.divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP));
}
// 解析订单状态(如果提供了映射)
if (orderStatusHeader != null) {
String orderStatusName = getValue(record, orderStatusHeader);
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
if (statusId != null) {
orderDTO.setStatusId(statusId);
}
String orderStatusName = getValue(record, orderStatusField);
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
if (statusId != null) {
orderDTO.setStatusId(statusId);
}
}
@@ -403,6 +499,21 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* 从CSV记录获取值
*
* @param record CSV记录
* @param mappingField 映射字段定义
* @return 值
*/
private String getValue(CSVRecord record, MappingField mappingField) {
if (mappingField == null || mappingField.getFileFieldName() == null || mappingField.getFileFieldName().trim().isEmpty()) {
logger.debug("映射字段为空或文件字段名为空,无法获取值");
return null;
}
return getValue(record, mappingField.getFileFieldName());
}
/**
* 从CSV记录获取值(重载方法,兼容旧代码)
*
* @param record CSV记录
* @param header 表头名称
* @return 值
*/
@@ -451,19 +562,100 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
/**
* 如果商品和规格不存在,则创建它们
* 通过规格编码查找无果则确定为规格不存在,再通过商品名称来判断有没有该商品
* 复用ProductService.createProduct和ProductSpecService.createProductSpec的业务逻辑
* 通过商品编码查找商品
*
* @param productCode 商品编码
* @param companyId 公司ID
* @return 商品
*/
private ProductPO findProductByProductCode(String productCode, Long companyId) {
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getProductCode, productCode)
.eq(ProductPO::getCompanyId, companyId);
return productMapper.selectOne(wrapper);
}
/**
* 通过商品名称查找商品(精准匹配)
*
* @param productName 商品名称
* @param companyId 公司ID
* @return 商品
*/
private ProductPO findProductByName(String productName, Long companyId) {
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getName, productName)
.eq(ProductPO::getCompanyId, companyId);
return productMapper.selectOne(wrapper);
}
/**
* 为已存在的商品创建规格
*
* @param companyId 公司ID
* @param productId 商品ID
* @param specName 规格名称
* @param specCode 规格编码
* @param createBy 创建人ID
* @return 商品规格
*/
private ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, String specCode, Long createBy) {
// 验证商品是否存在
ProductPO existingProduct = productMapper.selectById(productId);
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证规格名称是否重复
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCheckWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
specCheckWrapper.eq(ProductSpecPO::getProductId, productId)
.eq(ProductSpecPO::getName, specName)
.eq(ProductSpecPO::getCompanyId, companyId);
if (productSpecService.count(specCheckWrapper) > 0) {
throw new BusinessException("规格名称已存在");
}
// 验证规格编码是否重复
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCodeCheckWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
specCodeCheckWrapper.eq(ProductSpecPO::getSpecCode, specCode)
.eq(ProductSpecPO::getCompanyId, companyId);
if (productSpecService.count(specCodeCheckWrapper) > 0) {
throw new BusinessException("规格编码已存在");
}
// 创建商品规格
ProductSpecPO productSpec = new ProductSpecPO();
productSpec.setCompanyId(companyId);
productSpec.setProductId(productId);
productSpec.setName(specName);
productSpec.setSpecCode(specCode);
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
productSpec.setCreateBy(createBy);
productSpecService.save(productSpec);
logger.info("为商品 (ID: {}) 创建规格: {} (编码: {}, ID: {})", productId, specName, specCode, productSpec.getId());
return productSpec;
}
/**
* 如果商品和规格不存在,则创建它们
* 通过规格编码查找无果则确定为规格不存在,再通过商品编码或商品名称来判断有没有该商品
* 复用ProductService.createProduct和ProductSpecService.createProductSpec的业务逻辑
*
* @param companyId 公司ID
* @param productName 商品名称
* @param productCode 商品编码(可选)
* @param specName 规格名称
* @param specCode 规格编码
* @param createBy 创建人ID
* @return 商品规格
*/
private ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName,
String specName, String specCode, Long createBy) {
String productCode, String specName, String specCode, Long createBy) {
// 1. 通过商品名称查找商品(复用ProductService.getProductByName的逻辑)
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> productWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
@@ -491,10 +683,22 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
product = new ProductPO();
product.setCompanyId(companyId);
product.setName(productName);
if (productCode != null && !productCode.isEmpty()) {
// 验证商品编码是否重复
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> codeCheckWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
codeCheckWrapper.eq(ProductPO::getProductCode, productCode)
.eq(ProductPO::getCompanyId, companyId);
if (productMapper.selectCount(codeCheckWrapper) > 0) {
throw new BusinessException("商品编码已存在: " + productCode);
}
product.setProductCode(productCode);
}
product.setCreateBy(createBy);
productMapper.insert(product);
productId = product.getId();
logger.info("自动创建商品: {} (ID: {})", productName, productId);
logger.info("自动创建商品: {} (ID: {})" + (productCode != null && !productCode.isEmpty() ? ", 商品编码: " + productCode : ""),
productName, productId);
}
} else {
productId = product.getId();
@@ -502,35 +706,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
// 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑)
// 注意:规格编码查找无果,所以这里直接创建
// 验证商品是否存在(复用createProductSpec的逻辑)
ProductPO existingProduct = productMapper.selectById(productId);
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
throw new BusinessException("商品不存在");
}
// 验证规格名称是否重复(复用createProductSpec的逻辑)
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCheckWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
specCheckWrapper.eq(ProductSpecPO::getProductId, productId)
.eq(ProductSpecPO::getName, specName)
.eq(ProductSpecPO::getCompanyId, companyId);
if (productSpecService.count(specCheckWrapper) > 0) {
throw new BusinessException("规格名称已存在");
}
// 创建商品规格(复用createProductSpec的逻辑)
ProductSpecPO productSpec = new ProductSpecPO();
productSpec.setCompanyId(companyId);
productSpec.setProductId(productId);
productSpec.setName(specName);
productSpec.setSpecCode(specCode);
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
productSpec.setCreateBy(createBy);
productSpecService.save(productSpec);
logger.info("自动创建商品规格: {} (编码: {}, ID: {})", specName, specCode, productSpec.getId());
return productSpec;
return createSpecForProduct(companyId, productId, specName, specCode, createBy);
}
/**
@@ -35,10 +35,30 @@ public class ImportTaskQueueServiceImpl implements ImportTaskQueueService {
@Override
public void publishImportTask(Long taskId) {
try {
// 获取任务信息
ImportTaskPO task = importTaskService.getById(taskId);
// 获取任务信息,由于是在事务提交后调用,可能需要短暂等待
ImportTaskPO task = null;
int retryCount = 0;
int maxRetries = 5;
while (task == null && retryCount < maxRetries) {
task = importTaskService.getById(taskId);
if (task == null) {
retryCount++;
if (retryCount < maxRetries) {
// 等待一小段时间后重试(事务可能刚提交,数据库可能还没完全同步)
try {
Thread.sleep(50); // 等待50毫秒
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logger.warn("等待任务查询时被中断", e);
break;
}
}
}
}
if (task == null) {
logger.error("导入任务不存在,taskId: {}", taskId);
logger.error("导入任务不存在,taskId: {},已重试{}次", taskId, maxRetries);
return;
}
@@ -7,6 +7,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
@@ -61,8 +62,16 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
this.save(importTaskPO);
// 发布任务到Redis队列
importTaskQueueService.publishImportTask(importTaskPO.getId());
// 在事务提交后再发布任务到Redis队列,确保数据已提交到数据库
Long taskId = importTaskPO.getId();
TransactionSynchronizationManager.registerSynchronization(
new org.springframework.transaction.support.TransactionSynchronization() {
@Override
public void afterCommit() {
importTaskQueueService.publishImportTask(taskId);
}
}
);
// 转换为VO返回
return convertToVO(importTaskPO);
@@ -63,6 +63,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
throw new BusinessException("商品名称已存在");
}
// 验证商品编码是否重复(如果不为空)
if (createProductDTO.getProductCode() != null && !createProductDTO.getProductCode().trim().isEmpty()) {
LambdaQueryWrapper<ProductPO> codeWrapper = new LambdaQueryWrapper<>();
codeWrapper.eq(ProductPO::getProductCode, createProductDTO.getProductCode().trim());
if (this.count(codeWrapper) > 0) {
throw new BusinessException("商品编码已存在");
}
}
// 创建商品
ProductPO product = new ProductPO();
@@ -133,6 +141,15 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
throw new BusinessException("商品名称已存在");
}
// 验证商品编码是否重复(如果不为空,排除当前商品)
if (updateProductDTO.getProductCode() != null && !updateProductDTO.getProductCode().trim().isEmpty()) {
LambdaQueryWrapper<ProductPO> codeWrapper = new LambdaQueryWrapper<>();
codeWrapper.eq(ProductPO::getProductCode, updateProductDTO.getProductCode().trim())
.ne(ProductPO::getId, id);
if (this.count(codeWrapper) > 0) {
throw new BusinessException("商品编码已存在");
}
}
// 更新商品
ProductPO product = new ProductPO();
@@ -202,6 +219,9 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductPO> im
if (filter.getName() != null && !filter.getName().trim().isEmpty()) {
wrapper.like(ProductPO::getName, filter.getName());
}
if (filter.getProductCode() != null && !filter.getProductCode().trim().isEmpty()) {
wrapper.like(ProductPO::getProductCode, filter.getProductCode());
}
}
// 排序
@@ -0,0 +1,18 @@
-- 为导入映射表添加名称字段并修改唯一约束
-- 执行时间:2025-12-03
-- 1. 添加名称字段
ALTER TABLE `ec_import_mappings`
ADD COLUMN `name` varchar(20) NOT NULL COMMENT '映射名称' AFTER `type`;
-- 2. 为现有数据设置默认名称(根据类型设置,确保唯一性)
UPDATE `ec_import_mappings` SET `name` = CONCAT('商品导入映射-', DATE_FORMAT(create_time, '%Y%m%d')) WHERE `type` = 'product';
UPDATE `ec_import_mappings` SET `name` = CONCAT('订单导入映射-', DATE_FORMAT(create_time, '%Y%m%d')) WHERE `type` = 'order';
-- 3. 删除旧的唯一约束(如果存在)
ALTER TABLE `ec_import_mappings` DROP INDEX IF EXISTS `uniq_company_type`;
-- 4. 添加新的唯一约束(公司ID、导入类型、名称)
ALTER TABLE `ec_import_mappings`
ADD UNIQUE KEY `uniq_company_type_name` (`company_id`, `type`, `name`);
@@ -26,6 +26,7 @@ CREATE TABLE `ec_product` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '商品ID',
`company_id` BIGINT UNSIGNED NOT NULL COMMENT '公司ID',
`name` VARCHAR(255) NOT NULL COMMENT '商品名称',
`product_code` VARCHAR(100) DEFAULT NULL COMMENT '商品编码',
`main_image` VARCHAR(500) DEFAULT NULL COMMENT '主图URL(冗余字段)',
`main_image_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '主图图片ID',
`create_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -34,6 +35,7 @@ CREATE TABLE `ec_product` (
`update_by` BIGINT UNSIGNED DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`),
KEY `idx_company_id` (`company_id`),
UNIQUE KEY `uk_product_code` (`product_code`),
KEY `fk_ec_product_main_image` (`main_image_id`),
KEY `fk_ec_product_creator` (`create_by`),
KEY `fk_ec_product_updater` (`update_by`),
@@ -225,14 +227,15 @@ CREATE TABLE `ec_import_mappings` (
`id` bigint unsigned NOT NULL AUTO_INCREMENT COMMENT '映射ID',
`company_id` bigint unsigned NOT NULL COMMENT '所属公司ID',
`type` enum('product','order') NOT NULL COMMENT '导入类型(product-商品 order-订单)',
`mapping` json NOT NULL COMMENT '{"商品名称":"name","价格(元)":"price"}',
`name` varchar(20) NOT NULL COMMENT '映射模板名称',
`mapping` json NOT NULL COMMENT '映射模板JSON',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
`create_by` bigint unsigned DEFAULT NULL COMMENT '创建人ID',
`update_by` bigint unsigned DEFAULT NULL COMMENT '更新人ID',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_company_type` (`company_id`, `type`),
UNIQUE KEY `uniq_company_type_name` (`company_id`, `type`, `name`),
CONSTRAINT `fk_import_mapping_company` FOREIGN KEY (`company_id`) REFERENCES `org_company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `fk_import_mapping_creator` FOREIGN KEY (`create_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT `fk_import_mapping_updater` FOREIGN KEY (`update_by`) REFERENCES `sys_user` (`id`) ON DELETE SET NULL ON UPDATE CASCADE