diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/CreateImportMappingDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/CreateImportMappingDTO.java index 66cb79f2..739e94b8 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/CreateImportMappingDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/CreateImportMappingDTO.java @@ -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格式) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/ImportMappingFilterDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/ImportMappingFilterDTO.java index e3c38911..2ea693da 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/ImportMappingFilterDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/ImportMappingFilterDTO.java @@ -15,5 +15,11 @@ public class ImportMappingFilterDTO { */ @Schema(description = "导入类型", example = "product", allowableValues = {"product", "order"}) private String type; + + /** + * 映射名称(模糊查询) + */ + @Schema(description = "映射名称(模糊查询)", example = "商品导入") + private String name; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/UpdateImportMappingDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/UpdateImportMappingDTO.java index ce436909..f0ba16a4 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/UpdateImportMappingDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/importmapping/UpdateImportMappingDTO.java @@ -11,6 +11,12 @@ import lombok.Data; @Schema(description = "更新导入映射DTO") public class UpdateImportMappingDTO { + /** + * 映射名称 + */ + @Schema(description = "映射名称", example = "商品导入映射模板") + private String name; + /** * 字段映射(JSON格式) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/CreateProductDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/CreateProductDTO.java index ee3b0db3..502d0c8f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/CreateProductDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/CreateProductDTO.java @@ -23,6 +23,12 @@ public class CreateProductDTO { @NotBlank(message = "商品名称不能为空") private String name; + /** + * 商品编码 + */ + @Schema(description = "商品编码", example = "IPHONE15PRO001") + private String productCode; + /** * 主图图片ID */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/ProductFilterDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/ProductFilterDTO.java index 5c3fffb0..c780462f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/ProductFilterDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/ProductFilterDTO.java @@ -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; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/UpdateProductDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/UpdateProductDTO.java index 9d2f0e61..23971721 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/UpdateProductDTO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/dto/product/UpdateProductDTO.java @@ -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; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ImportMappingPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ImportMappingPO.java index ca3923aa..fdcfab8f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ImportMappingPO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ImportMappingPO.java @@ -32,6 +32,12 @@ public class ImportMappingPO { @TableField("type") private String type; + /** + * 映射模板名称 + */ + @TableField("name") + private String name; + /** * 字段映射(JSON格式) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ProductPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ProductPO.java index 34915586..f71a9187 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ProductPO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/po/ProductPO.java @@ -32,6 +32,12 @@ public class ProductPO { @TableField("name") private String name; + /** + * 商品编码 + */ + @TableField("product_code") + private String productCode; + /** * 主图URL(冗余字段) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ImportMappingVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ImportMappingVO.java index b7b1b01d..280adb3c 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ImportMappingVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ImportMappingVO.java @@ -30,6 +30,12 @@ public class ImportMappingVO { @Schema(description = "导入类型", example = "product") private String type; + /** + * 映射名称 + */ + @Schema(description = "映射名称", example = "商品导入映射模板") + private String name; + /** * 字段映射(JSON格式) */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ProductVO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ProductVO.java index 83631694..a3c50c8a 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ProductVO.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/model/vo/ProductVO.java @@ -31,6 +31,12 @@ public class ProductVO { @Schema(description = "商品名称", example = "iPhone 15 Pro") private String name; + /** + * 商品编码 + */ + @Schema(description = "商品编码", example = "IPHONE15PRO001") + private String productCode; + /** * 主图URL */ diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportMappingServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportMappingServiceImpl.java index 1d753361..c0496373 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportMappingServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportMappingServiceImpl.java @@ -47,12 +47,13 @@ public class ImportMappingServiceImpl extends ServiceImpl 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 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 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()); + } } // 按创建时间倒序 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskProcessorServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskProcessorServiceImpl.java index 8409bfe5..81b8c979 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskProcessorServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskProcessorServiceImpl.java @@ -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 mapping = parseMapping(task.getMapping()); + Map 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 parseMapping(String mappingJson) { + private Map parseMapping(String mappingJson) { try { if (mappingJson == null || mappingJson.trim().isEmpty()) { throw new BusinessException("字段映射不能为空"); } - // 解析JSON,格式:{"specCode": "商家编码-规格维度", "specName": "商品规格", ...} - Map mapping = objectMapper.readValue(mappingJson, new TypeReference>() {}); - return mapping; + // 解析JSON数组,格式:[{"required": false, "fieldName": "productName", "fieldLabel": "商品名称", "fileFieldName": "商品"}, ...] + List mappingFields = objectMapper.readValue(mappingJson, + new TypeReference>() {}); + + 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 mapping, + private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map 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 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 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 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 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 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 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 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); } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskQueueServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskQueueServiceImpl.java index 920a0ede..733b3dff 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskQueueServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskQueueServiceImpl.java @@ -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; } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskServiceImpl.java index 5bb4ba01..f0622945 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/service/impl/ImportTaskServiceImpl.java @@ -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 im throw new BusinessException("商品名称已存在"); } + // 验证商品编码是否重复(如果不为空) + if (createProductDTO.getProductCode() != null && !createProductDTO.getProductCode().trim().isEmpty()) { + LambdaQueryWrapper 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 im throw new BusinessException("商品名称已存在"); } + // 验证商品编码是否重复(如果不为空,排除当前商品) + if (updateProductDTO.getProductCode() != null && !updateProductDTO.getProductCode().trim().isEmpty()) { + LambdaQueryWrapper 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 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()); + } } // 排序 diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/add_name_to_import_mappings.sql b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/add_name_to_import_mappings.sql new file mode 100644 index 00000000..ccabd66f --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/add_name_to_import_mappings.sql @@ -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`); + diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/ec_design.sql b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/ec_design.sql index 99bebc57..b1ddf2d2 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/ec_design.sql +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/sql/ec_design.sql @@ -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 diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.dto.ts index 12914a41..8686b7f0 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.dto.ts @@ -7,12 +7,16 @@ export namespace ImportMappingDTO { export interface CreateImportMappingDTO { /** 导入类型(product-商品 order-订单) */ type: string; + /** 映射名称 */ + name: string; /** 字段映射(JSON格式) */ mapping: string; } /** 更新导入映射参数 */ export interface UpdateImportMappingDTO { + /** 映射名称 */ + name?: string; /** 字段映射(JSON格式) */ mapping: string; } @@ -21,5 +25,7 @@ export namespace ImportMappingDTO { export interface ImportMappingFilterDTO { /** 导入类型(product-商品 order-订单) */ type?: string; + /** 映射名称(模糊查询) */ + name?: string; } } diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.vo.ts index 0e63bd65..8e13a9be 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-mapping/types/types.vo.ts @@ -11,6 +11,8 @@ export namespace ImportMappingVO { companyId?: number; /** 导入类型(product-商品 order-订单) */ type: string; + /** 映射名称 */ + name: string; /** 字段映射(JSON格式) */ mapping: string; /** 创建时间 */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-task/apis.ts b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-task/apis.ts index 9a338c68..95224ec8 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-task/apis.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/ecommerce/import-task/apis.ts @@ -2,8 +2,13 @@ import type { ImportTaskDTO, ImportTaskVO } from './types'; import type { PageQueryDTO, PageResultVO } from '#/types/common'; +import { useAppConfig } from '@vben/hooks'; +import { useAccessStore } from '@vben/stores'; + import { requestClient } from '#/api/request'; +const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD); + /** * 导入任务管理API */ @@ -31,3 +36,191 @@ export async function getImportTaskPageApi( params, ); } + +/** + * SSE连接管理器(使用fetch API支持自定义请求头) + */ +class SseConnection { + private abortController: AbortController | null = null; + private accessStore: ReturnType; + private listeners: Map void>> = + new Map(); + private readyState: number = EventSource.CLOSED; + + constructor() { + this.accessStore = useAccessStore(); + } + + /** + * 添加事件监听器 + */ + addEventListener(eventType: string, handler: (event: MessageEvent) => void) { + if (!this.listeners.has(eventType)) { + this.listeners.set(eventType, new Set()); + } + this.listeners.get(eventType)!.add(handler); + } + + /** + * 建立SSE连接(使用fetch API) + */ + connect(): void { + if (this.abortController) { + this.disconnect(); + } + + const token = this.accessStore.accessToken; + if (!token) { + console.error('无法建立SSE连接:token不存在'); + return; + } + + const url = `${apiURL}/ec/import-task/sse/connect`; + this.abortController = new AbortController(); + this.readyState = EventSource.CONNECTING; + + fetch(url, { + method: 'GET', + headers: { + Authorization: `Bearer ${token}`, + Accept: 'text/event-stream', + }, + signal: this.abortController.signal, + }) + .then((response) => { + if (!response.ok) { + throw new Error(`SSE连接失败: ${response.status}`); + } + + this.readyState = EventSource.OPEN; + + const reader = response.body?.getReader(); + const decoder = new TextDecoder(); + + if (!reader) { + throw new Error('无法获取响应流'); + } + + // 读取流数据 + const readStream = () => { + reader + .read() + .then(({ done, value }) => { + if (done) { + this.readyState = EventSource.CLOSED; + return; + } + + const chunk = decoder.decode(value, { stream: true }); + this.parseSSE(chunk); + readStream(); + }) + .catch((error) => { + if (error.name !== 'AbortError') { + console.error('读取SSE流失败:', error); + this.readyState = EventSource.CLOSED; + this.dispatchEvent( + 'error', + new MessageEvent('error', { data: error }), + ); + } + }); + }; + + readStream(); + }) + .catch((error) => { + if (error.name !== 'AbortError') { + console.error('建立SSE连接失败:', error); + this.readyState = EventSource.CLOSED; + this.dispatchEvent( + 'error', + new MessageEvent('error', { data: error }), + ); + } + }); + } + + /** + * 断开连接 + */ + disconnect() { + if (this.abortController) { + this.abortController.abort(); + this.abortController = null; + this.readyState = EventSource.CLOSED; + } + } + + /** + * 获取连接状态 + */ + getReadyState(): number { + return this.readyState; + } + + /** + * 移除事件监听器 + */ + removeEventListener( + eventType: string, + handler: (event: MessageEvent) => void, + ) { + const handlers = this.listeners.get(eventType); + if (handlers) { + handlers.delete(handler); + } + } + + /** + * 分发事件 + */ + private dispatchEvent(eventType: string, event: MessageEvent) { + const handlers = this.listeners.get(eventType); + if (handlers) { + handlers.forEach((handler) => { + try { + handler(event); + } catch (error) { + console.error('事件处理器执行失败:', error); + } + }); + } + } + + /** + * 解析SSE数据 + */ + private parseSSE(chunk: string) { + const lines = chunk.split('\n'); + let eventType = 'message'; + let data = ''; + + for (const line of lines) { + if (line.startsWith('event:')) { + eventType = line.slice(6).trim(); + } else if (line.startsWith('data:')) { + data += `${line.slice(5).trim()}\n`; + } else if ( + line === '' && // 空行表示一个完整的消息 + data + ) { + const event = new MessageEvent(eventType, { + data: data.trim(), + }); + this.dispatchEvent(eventType, event); + this.dispatchEvent('message', event); + data = ''; + eventType = 'message'; + } + } + } +} + +/** + * 建立SSE连接 + * @returns SseConnection实例 + */ +export function createSseConnection(): SseConnection { + return new SseConnection(); +} diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.dto.ts b/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.dto.ts index 6e3f85e3..b6cd17f1 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.dto.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.dto.ts @@ -7,6 +7,8 @@ export namespace ProductDTO { export interface Create { /** 商品名称 */ name: string; + /** 商品编码 */ + productCode?: string; /** 主图图片ID */ mainImageId?: number; /** 商品规格列表(可选) */ @@ -18,6 +20,8 @@ export namespace ProductDTO { /** 商品名称 */ name: string; /** 商品编码 */ + productCode?: string; + /** 商品编码 */ specCode?: string; /** 商品SKU */ skuCode?: string; @@ -64,6 +68,8 @@ export namespace ProductDTO { /** 商品名称(模糊查询) */ name?: string; /** 商品编码(模糊查询) */ + productCode?: string; + /** 商品编码(模糊查询) */ specCode?: string; /** 商品SKU(模糊查询) */ skuCode?: string; diff --git a/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.vo.ts b/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.vo.ts index 0fe71b2f..77e3e861 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.vo.ts +++ b/ecom-dmb-frontend/apps/web-antd/src/api/shop/product/types/types.vo.ts @@ -11,6 +11,8 @@ export namespace ProductVO { companyId: number; /** 商品名称 */ name: string; + /** 商品编码 */ + productCode?: string; /** 主图URL(冗余字段) */ mainImage?: string; /** 主图图片ID */ diff --git a/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskButton.vue b/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskButton.vue new file mode 100644 index 00000000..168de089 --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskButton.vue @@ -0,0 +1,39 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskDropdown.vue b/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskDropdown.vue new file mode 100644 index 00000000..9dfab9bb --- /dev/null +++ b/ecom-dmb-frontend/apps/web-antd/src/components/ImportTaskDropdown.vue @@ -0,0 +1,234 @@ + + + diff --git a/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue b/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue index 44970ae2..0e4578f6 100644 --- a/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue +++ b/ecom-dmb-frontend/apps/web-antd/src/layouts/basic.vue @@ -1,7 +1,7 @@