diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportRuntimeContext.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportRuntimeContext.java new file mode 100644 index 00000000..781ce7a6 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportRuntimeContext.java @@ -0,0 +1,194 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl; + +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; +import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO; + +import java.math.BigDecimal; +import java.util.*; + +/** + * 导入运行时上下文(贯穿整个导入过程) + *

+ * 所有共享类型(内部类/枚举)也定义在此文件,避免循环依赖。 + */ +public class ImportRuntimeContext { + + // ==================== 共享类型 ==================== + + /** + * 字段映射定义 + */ + public static class MappingField { + private Boolean required; + private String fieldName; + private String fieldLabel; + private String fileFieldName; + + public MappingField() {} + + 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; } + } + + /** + * 状态映射定义 + */ + public static class StatusMapping { + private String csvStatus; + private Long mappedStatusId; + + public StatusMapping() {} + + public String getCsvStatus() { return csvStatus; } + public void setCsvStatus(String csvStatus) { this.csvStatus = csvStatus; } + public Long getMappedStatusId() { return mappedStatusId; } + public void setMappedStatusId(Long mappedStatusId) { this.mappedStatusId = mappedStatusId; } + } + + /** + * 映射配置 + */ + public static class MappingConfig { + private List fieldMapping; + private List statusMapping; + + public MappingConfig() {} + + public List getFieldMapping() { return fieldMapping; } + public void setFieldMapping(List fieldMapping) { this.fieldMapping = fieldMapping; } + public List getStatusMapping() { return statusMapping; } + public void setStatusMapping(List statusMapping) { this.statusMapping = statusMapping; } + } + + /** + * 待插入订单包装器 + */ + public static class PendingOrderInsert { + public int rowNumber; + public String platformOrderNo; + public OrderPO order; + public Long existingOrderId; // 不为空表示是更新操作 + public StringBuilder updateMessages; + + public PendingOrderInsert(int rowNumber, String platformOrderNo, OrderPO order, + Long existingOrderId, StringBuilder updateMessages) { + this.rowNumber = rowNumber; + this.platformOrderNo = platformOrderNo; + this.order = order; + this.existingOrderId = existingOrderId; + this.updateMessages = updateMessages; + } + + public void updateData(OrderPO newOrder, Long newExistingOrderId, + StringBuilder newUpdateMsg, int newRowNumber) { + this.order = newOrder; + this.rowNumber = newRowNumber; + if (newExistingOrderId != null) this.existingOrderId = newExistingOrderId; + if (newUpdateMsg != null && newUpdateMsg.length() > 0) this.updateMessages = newUpdateMsg; + } + } + + /** + * 日期时间格式定义 + */ + public static class DateTimeFormatPattern { + public final String pattern; + public final java.time.format.DateTimeFormatter formatter; + public final boolean hasTime; + + public DateTimeFormatPattern(String pattern, boolean hasTime) { + this.pattern = pattern; + this.formatter = java.time.format.DateTimeFormatter.ofPattern(pattern); + this.hasTime = hasTime; + } + } + + /** + * 导入结果 + */ + public static class ImportResult { + public int totalCount; + public int successCount; + public int failCount; + public int insertCount; + public int updateCount; + public StringBuilder errorMessages = new StringBuilder(); + } + + // ==================== 上下文字段 ==================== + + private final Long companyId; + private final Long shopId; + private final Long createBy; + + private DateTimeFormatPattern detectedDatePattern; + + final Map specByCodeCache = new HashMap<>(); + final Map productByCodeCache = new HashMap<>(); + final Map productByNameCache = new HashMap<>(); + final Map productByIdCache = new HashMap<>(); + final Map statusIdByNameCache = new HashMap<>(); + final Set existingPlatformOrderNos = new HashSet<>(); + final Map existingOrderIdByPlatformNo = new HashMap<>(); + final Set existingRelationKeys = new HashSet<>(); + final List pendingOrders = new ArrayList<>(); + final Map pendingOrderByPlatformNo = new HashMap<>(); + final List pendingRelations = new ArrayList<>(); + final Set pendingRelationKeys = new HashSet<>(); + final Set pendingPlatformOrderNos = new HashSet<>(); + + public ImportRuntimeContext(Long companyId, Long shopId, Long createBy) { + this.companyId = companyId; + this.shopId = shopId; + this.createBy = createBy; + } + + public Long getCompanyId() { return companyId; } + public Long getShopId() { return shopId; } + public Long getCreateBy() { return createBy; } + public DateTimeFormatPattern getDetectedDatePattern() { return detectedDatePattern; } + public void setDetectedDatePattern(DateTimeFormatPattern detectedDatePattern) { this.detectedDatePattern = detectedDatePattern; } + public Map getSpecByCodeCache() { return specByCodeCache; } + public Map getProductByCodeCache() { return productByCodeCache; } + public Map getProductByNameCache() { return productByNameCache; } + public Map getProductByIdCache() { return productByIdCache; } + public Map getStatusIdByNameCache() { return statusIdByNameCache; } + public Set getExistingPlatformOrderNos() { return existingPlatformOrderNos; } + public Map getExistingOrderIdByPlatformNo() { return existingOrderIdByPlatformNo; } + public Set getExistingRelationKeys() { return existingRelationKeys; } + public List getPendingOrders() { return pendingOrders; } + public Map getPendingOrderByPlatformNo() { return pendingOrderByPlatformNo; } + public List getPendingRelations() { return pendingRelations; } + public Set getPendingRelationKeys() { return pendingRelationKeys; } + public Set getPendingPlatformOrderNos() { return pendingPlatformOrderNos; } + + // ==================== 工具方法 ==================== + + public void addNormalizedValue(Set target, String rawValue) { + if (rawValue == null) return; + String value = rawValue.trim(); + if (!value.isEmpty()) target.add(value); + } + + public String buildRelationKey(Long shopId, Long productId) { + return shopId + "#" + productId; + } + + public static List> splitToChunks(Set values, int chunkSize) { + if (values == null || values.isEmpty()) return Collections.emptyList(); + List all = new ArrayList<>(values); + List> chunks = new ArrayList<>(); + for (int i = 0; i < all.size(); i += chunkSize) { + chunks.add(all.subList(i, Math.min(i + chunkSize, all.size()))); + } + return chunks; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java index 07d0f320..55c6ab55 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java @@ -1,57 +1,34 @@ package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl; -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.ibatis.session.ExecutorType; -import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; -import org.apache.commons.csv.CSVFormat; -import org.apache.commons.csv.CSVParser; -import org.apache.commons.csv.CSVRecord; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper; -import org.springframework.beans.BeanUtils; -import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.CreateOrderDTO; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.vo.ImportTaskVO; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskProcessorService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.model.vo.OrderVO; import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService; +import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.service.OrderService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; +import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; -import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.sys.file.service.OssService; import top.xyquan.ecomdmbbackend.modules.sys.file.service.SysFileService; import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO; import java.io.File; -import java.io.InputStream; import java.io.IOException; -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; +import java.io.InputStream; +import java.nio.charset.Charset; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; /** @@ -60,170 +37,6 @@ import java.util.stream.Collectors; @Service public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService { - /** - * 映射字段定义 - */ - private static class MappingField { - private Boolean required; - private String fieldName; - private String fieldLabel; - private String fileFieldName; - - // 无参构造函数(Jackson需要) - public MappingField() { - } - - 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 class StatusMapping { - private String csvStatus; - private Long mappedStatusId; - - // 无参构造函数(Jackson需要) - public StatusMapping() { - } - - public String getCsvStatus() { - return csvStatus; - } - - public void setCsvStatus(String csvStatus) { - this.csvStatus = csvStatus; - } - - public Long getMappedStatusId() { - return mappedStatusId; - } - - public void setMappedStatusId(Long mappedStatusId) { - this.mappedStatusId = mappedStatusId; - } - } - - /** - * 映射配置(包含字段映射和状态映射) - */ - private static class MappingConfig { - private List fieldMapping; - private List statusMapping; - - // 无参构造函数(Jackson需要) - public MappingConfig() { - } - - public List getFieldMapping() { - return fieldMapping; - } - - public void setFieldMapping(List fieldMapping) { - this.fieldMapping = fieldMapping; - } - - public List getStatusMapping() { - return statusMapping; - } - - public void setStatusMapping(List statusMapping) { - this.statusMapping = statusMapping; - } - } - - private static final int ORDER_BATCH_SIZE = 1000; // 订单批量插入大小 - private static final int RELATION_BATCH_SIZE = 500; // 商品关系批量插入大小 - private static final int PROGRESS_UPDATE_INTERVAL_ROWS = 1000; // 进度更新间隔行数 - private static final long PROGRESS_NOTIFY_INTERVAL_MS = 1000L; // 进度通知间隔时间 - private static final int IN_QUERY_BATCH_SIZE = 1000; // 内查询批量大小 - - private static class PendingOrderInsert { - private int rowNumber; - private String platformOrderNo; - private OrderPO order; - private Long existingOrderId; // 不为空表示是更新操作 - private StringBuilder updateMessages; // 记录更新消息 - - private PendingOrderInsert(int rowNumber, String platformOrderNo, OrderPO order, Long existingOrderId, StringBuilder updateMessages) { - this.rowNumber = rowNumber; - this.platformOrderNo = platformOrderNo; - this.order = order; - this.existingOrderId = existingOrderId; - this.updateMessages = updateMessages; - } - - private void updateData(OrderPO newOrder, Long newExistingOrderId, StringBuilder newUpdateMsg, int newRowNumber) { - this.order = newOrder; - this.rowNumber = newRowNumber; - if (newExistingOrderId != null) { - this.existingOrderId = newExistingOrderId; - } - if (newUpdateMsg != null && newUpdateMsg.length() > 0) { - this.updateMessages = newUpdateMsg; - } - } - } - - private static class ImportRuntimeContext { - private final Long companyId; - private final Long shopId; - private final Long createBy; - - // 首行检测到的日期格式(null表示未检测) - private DateTimeFormatPattern detectedDatePattern = null; - - private final Map specByCodeCache = new HashMap<>(); - private final Map productByCodeCache = new HashMap<>(); - private final Map productByNameCache = new HashMap<>(); - private final Map productByIdCache = new HashMap<>(); - private final Map statusIdByNameCache = new HashMap<>(); - private final Set existingPlatformOrderNos = new HashSet<>(); - private final Map existingOrderIdByPlatformNo = new HashMap<>(); // platformOrderNo -> orderId - private final Set existingRelationKeys = new HashSet<>(); - private final List pendingOrders = new ArrayList<>(); - private final Map pendingOrderByPlatformNo = new HashMap<>(); // 按平台订单号索引,用于快速查找和更新 - private final List pendingRelations = new ArrayList<>(); - private final Set pendingRelationKeys = new HashSet<>(); - private final Set pendingPlatformOrderNos = new HashSet<>(); - - private ImportRuntimeContext(Long companyId, Long shopId, Long createBy) { - this.companyId = companyId; - this.shopId = shopId; - this.createBy = createBy; - } - } - private final ImportTaskService importTaskService; private final ProductSpecService productSpecService; private final OrderMapper orderMapper; @@ -237,6 +50,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic private final OssService ossService; private final SysFileService sysFileService; + // 提取出的处理器 + private final OrderImportProcessor orderImportProcessor; + private final ProductSpecImportHelper productSpecImportHelper; + public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService, OrderService orderService, ProductService productService, @@ -263,39 +80,33 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic this.sqlSessionFactory = sqlSessionFactory; this.ossService = ossService; this.sysFileService = sysFileService; + + // 初始化 helper 和 processor + this.productSpecImportHelper = new ProductSpecImportHelper( + productMapper, productSpecService, orderStatusService, shopProductRelationMapper); + this.orderImportProcessor = new OrderImportProcessor( + productSpecImportHelper, orderMapper, shopProductRelationMapper, sqlSessionFactory); } - /** - * 处理导入任务 - * - * @param taskId 任务ID - */ @Override - // 不使用事务:商品/规格创建均立即提交,避免事务回滚导致“商品不存在”等查询问题 public void processImportTask(Long taskId) { ImportTaskPO task = importTaskService.getById(taskId); - if (task == null) { - return; - } + if (task == null) return; - // 更新任务状态为处理中 updateTaskStatus(taskId, "processing", null, 0, 0, 0); try { - // 通知前端任务开始处理 ImportTaskPO updatedTask = importTaskService.getById(taskId); notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask)); if ("order".equals(task.getType())) { processOrderImport(task); } else if ("product".equals(task.getType())) { - // 商品导入逻辑待实现 updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0); } else { throw new BusinessException("不支持的导入类型: " + task.getType()); } - // 通知前端任务完成 ImportTaskPO completedTask = importTaskService.getById(taskId); notifyTaskProgress(task.getCreateBy(), convertToVO(completedTask)); @@ -313,1529 +124,172 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic } } - /** - * 处理订单导入 - * - * @param task 导入任务 - */ - private void processOrderImport(ImportTaskPO task) throws IOException { - // 解析映射配置(包含字段映射和状态映射) - MappingConfig mappingConfig = parseMappingConfig(task.getMapping()); - Map fieldMapping = mappingConfig.getFieldMapping().stream() - .collect(Collectors.toMap(MappingField::getFieldName, field -> field, (v1, v2) -> v1)); - Map statusMapping = mappingConfig.getStatusMapping() != null + private void processOrderImport(ImportTaskPO task) throws Exception { + ImportRuntimeContext.MappingConfig mappingConfig = parseMappingConfig(task.getMapping()); + Map fieldMapping = mappingConfig.getFieldMapping().stream() + .collect(Collectors.toMap( + ImportRuntimeContext.MappingField::getFieldName, + field -> field, (v1, v2) -> v1)); + Map statusMapping = mappingConfig.getStatusMapping() != null ? mappingConfig.getStatusMapping().stream() .filter(sm -> sm.getCsvStatus() != null && sm.getMappedStatusId() != null) .collect(Collectors.toMap( sm -> sm.getCsvStatus().trim(), - StatusMapping::getMappedStatusId, + ImportRuntimeContext.StatusMapping::getMappedStatusId, (v1, v2) -> v1)) : java.util.Collections.emptyMap(); - Long companyId = task.getCompanyId(); - // 读取CSV文件 - // 通过 fileId 从统一文件系统获取文件信息,根据存储类型读取文件 File csvFile = null; - File tempOssFile = null; // 仅当从OSS下载时使用,用于后续清理 - int totalCount = 0; - int successCount = 0; - int failCount = 0; - int insertCount = 0; - int updateCount = 0; - StringBuilder errorMessages = new StringBuilder(); - ImportRuntimeContext context = null; + File tempOssFile = null; try { - // 获取文件信息 SysFileVO fileInfo = sysFileService.getFileById(task.getFileId()); - if (fileInfo == null) { - throw new BusinessException("文件不存在,fileId: " + task.getFileId()); - } - + if (fileInfo == null) throw new BusinessException("文件不存在,fileId: " + task.getFileId()); + String storagePath = fileInfo.getStoragePath(); String storageType = fileInfo.getStorageType(); InputStream fileInputStream; - + if ("local".equals(storageType)) { - // 本地存储:使用 storagePath 作为本地文件路径 File localFile = new File(storagePath); - if (localFile.exists() && localFile.isFile()) { - fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile)); - csvFile = localFile; - } else { + if (!localFile.exists() || !localFile.isFile()) { throw new BusinessException("本地文件不存在: " + storagePath); } + fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile)); + csvFile = localFile; } else { - // 对象存储(oss/s3/qiniu/cos等):从 OSS 下载到临时文件 tempOssFile = java.io.File.createTempFile("import-csv-", ".csv"); - if (!ossService.downloadFile(storagePath, tempOssFile)) { throw new BusinessException("从对象存储下载文件失败,storagePath: " + storagePath); } - csvFile = tempOssFile; fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempOssFile)); } - long lastProgressNotifyAt = 0L; + Charset charset = detectFileEncoding(fileInputStream); + ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy()); - // 尝试多种编码读取CSV文件(常见的中文编码) - java.nio.charset.Charset charset = detectFileEncoding(fileInputStream); - - try (java.io.InputStreamReader reader = new java.io.InputStreamReader(fileInputStream, charset); - CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.builder() - .setHeader() - .setSkipHeaderRecord(true) - .setIgnoreHeaderCase(true) - .setTrim(true) // 自动去除表头和值的前后空格 - .build())) { + java.util.function.BiConsumer progressCallback = (total, done) -> { + updateTaskStatus(task.getId(), "processing", null, total, done, 0); + ImportTaskPO updatedTask = importTaskService.getById(task.getId()); + notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask)); + }; + // 将 csvFile 传给 task(临时方案:task 本身没有此字段,由 process 方法内部读取) + final File finalCsvFile = csvFile; + ImportRuntimeContext.ImportResult result = orderImportProcessor.process( + task, finalCsvFile, charset, fieldMapping, statusMapping, context, progressCallback); - // 验证店铺 - ShopPO shop = shopService.getById(task.getShopId()); - if (shop == null || !shop.getCompanyId().equals(companyId)) { - throw new BusinessException("店铺不存在"); - } + String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed"); + String summary = String.format("导入完成,新增 %d 条,更新 %d 条", result.insertCount, result.updateCount); + String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary; + updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); - // 第一 pass:边读 CSV 边收集预加载数据,同时构建 records 列表(合并原来第二次遍历) - MappingField specCodeField = fieldMapping.get("spec_code"); - MappingField productCodeField = fieldMapping.get("product_code"); - MappingField linkProductNameField = fieldMapping.get("link_product_name"); - MappingField orderStatusField = fieldMapping.get("status"); - MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); - MappingField orderDateField = fieldMapping.get("order_date"); - - Set specCodes = new HashSet<>(); - Set productCodes = new HashSet<>(); - Set productNames = new HashSet<>(); - Set platformOrderNos = new HashSet<>(); - Set statusNames = new HashSet<>(); - DateTimeFormatPattern detectedDatePattern = null; - List records = new ArrayList<>(); - - for (CSVRecord record : csvParser) { - records.add(record); - addNormalizedValue(specCodes, getValue(record, specCodeField)); - addNormalizedValue(productCodes, getValue(record, productCodeField)); - addNormalizedValue(productNames, getValue(record, linkProductNameField)); - addNormalizedValue(platformOrderNos, getValue(record, platformOrderNoField)); - addNormalizedValue(statusNames, getValue(record, orderStatusField)); - // 日期格式检测 - if (detectedDatePattern == null && orderDateField != null) { - String dateStr = getValue(record, orderDateField); - if (dateStr != null && !dateStr.trim().isEmpty()) { - detectedDatePattern = detectDateFormat(dateStr.trim()); - } - } - } - totalCount = records.size(); - updateTaskStatus(task.getId(), "processing", null, totalCount, 0, 0); - - context = new ImportRuntimeContext(companyId, task.getShopId(), task.getCreateBy()); - context.detectedDatePattern = detectedDatePattern; - - // 预加载(原来在 preloadImportContext 里,现在直接调用) - preloadProductSpecs(context, specCodes); - preloadProductsByCode(context, productCodes); - preloadProductsByName(context, productNames); - preloadPlatformOrderNos(context, platformOrderNos); - preloadStatuses(context, statusNames, statusMapping); - preloadShopProductRelations(context); - - for (int i = 0; i < records.size(); i++) { - CSVRecord record = records.get(i); - int rowNumber = i + 2; // 行号从2开始(第1行是表头) - - try { - // 解析CSV行数据 - CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(), - null, companyId, task.getCreateBy(), context); - queueShopProductRelation(orderDTO, context); - OrderPO orderPO = buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId(), context); - - StringBuilder updateMsg = new StringBuilder(); - if (orderDTO.getExistingOrderId() != null) { - updateMsg.append(String.format("平台订单号 %s 已更新", orderDTO.getPlatformOrderNo())); - } - - // 检查是否是同批次内重复(内存中的重复) - boolean isInMemoryDuplicate = validatePlatformOrderNo( - orderDTO.getPlatformOrderNo(), context, orderPO, rowNumber, orderPO.getId(), updateMsg); - - if (!isInMemoryDuplicate) { - // 非重复:新增到pending队列 - PendingOrderInsert pendingInsert = new PendingOrderInsert( - rowNumber, orderDTO.getPlatformOrderNo(), orderPO, orderPO.getId(), updateMsg); - context.pendingOrders.add(pendingInsert); - if (orderDTO.getPlatformOrderNo() != null && !orderDTO.getPlatformOrderNo().trim().isEmpty()) { - context.pendingOrderByPlatformNo.put(orderDTO.getPlatformOrderNo().trim(), pendingInsert); - } - } - - if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) { - flushPendingRelations(context); - } - if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) { - int[] result = flushPendingOrders(context, errorMessages); - successCount += result[0]; - failCount += result[1]; - insertCount += result[0]; - updateCount += result[2]; - } - - } catch (Exception e) { - failCount++; - String errorMsg = String.format("第%d行:%s", rowNumber, e.getMessage()); - errorMessages.append(errorMsg).append(System.lineSeparator()); - } - - if ((i + 1) % PROGRESS_UPDATE_INTERVAL_ROWS == 0 || (i + 1) == records.size()) { - updateTaskStatus(task.getId(), "processing", null, totalCount, successCount, failCount); - } - long now = System.currentTimeMillis(); - if (now - lastProgressNotifyAt >= PROGRESS_NOTIFY_INTERVAL_MS || (i + 1) == records.size()) { - ImportTaskPO updatedTask = importTaskService.getById(task.getId()); - notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask)); - lastProgressNotifyAt = now; - } - } - - flushPendingRelations(context); - int[] flushResult = flushPendingOrders(context, errorMessages); - successCount += flushResult[0]; - failCount += flushResult[1]; - insertCount += flushResult[0]; - updateCount += flushResult[2]; - } } finally { - // 清理:从OSS下载的临时文件需要手动删除 - if (tempOssFile != null && tempOssFile.exists()) { - tempOssFile.delete(); - } + if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); } - - // 更新最终状态 - String finalStatus = failCount == 0 ? "success" : (successCount > 0 ? "success" : "failed"); - String summaryMsg = String.format("导入完成,新增 %d 条,更新 %d 条", insertCount, updateCount); - String message = failCount > 0 ? summaryMsg + "\n" + errorMessages.toString() : summaryMsg; - updateTaskStatus(task.getId(), finalStatus, message, totalCount, successCount, failCount); } - /** - * 解析映射配置(包含字段映射和状态映射) - * - * @param mappingJson 映射JSON字符串 - * @return 映射配置对象 - */ - private MappingConfig parseMappingConfig(String mappingJson) { + private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) { try { if (mappingJson == null || mappingJson.trim().isEmpty()) { throw new BusinessException("映射配置不能为空"); } - - // 解析新的JSON结构,格式: - // { - // "fieldMapping": [...], - // "statusMapping": [...] - // } - // 使用JsonNode先解析,然后手动构建对象,避免内部类反序列化问题 com.fasterxml.jackson.databind.JsonNode rootNode; try { rootNode = objectMapper.readTree(mappingJson); } catch (com.fasterxml.jackson.core.JsonProcessingException e) { - throw new BusinessException("解析字段映射失败: JSON格式错误 - " + e.getMessage() + ",JSON内容: " + mappingJson); + throw new BusinessException("解析字段映射失败: JSON格式错误 - " + e.getMessage()); } - if (!rootNode.isObject()) { - throw new BusinessException("解析字段映射失败: 映射配置必须是JSON对象,当前类型: " + rootNode.getNodeType()); + throw new BusinessException("解析字段映射失败: 映射配置必须是JSON对象"); } - - MappingConfig config = new MappingConfig(); - - // 解析字段映射 + + ImportRuntimeContext.MappingConfig config = new ImportRuntimeContext.MappingConfig(); + com.fasterxml.jackson.databind.JsonNode fieldMappingNode = rootNode.get("fieldMapping"); - if (fieldMappingNode == null) { + if (fieldMappingNode == null || !fieldMappingNode.isArray()) { throw new BusinessException("解析字段映射失败: 缺少fieldMapping字段"); } - - if (!fieldMappingNode.isArray()) { - throw new BusinessException("解析字段映射失败: fieldMapping必须是数组类型,当前类型: " + fieldMappingNode.getNodeType()); + + java.util.List mappingFields = new java.util.ArrayList<>(); + for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) { + if (!fieldNode.isObject()) continue; + ImportRuntimeContext.MappingField field = new ImportRuntimeContext.MappingField(); + if (fieldNode.has("required")) field.setRequired(fieldNode.get("required").asBoolean()); + if (fieldNode.has("fieldName")) field.setFieldName(fieldNode.get("fieldName").asText()); + if (fieldNode.has("fieldLabel")) field.setFieldLabel(fieldNode.get("fieldLabel").asText()); + if (fieldNode.has("fileFieldName")) field.setFileFieldName(fieldNode.get("fileFieldName").asText()); + mappingFields.add(field); } - - List mappingFields = new java.util.ArrayList<>(); - for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) { - if (!fieldNode.isObject()) { - continue; - } - MappingField field = new MappingField(); - if (fieldNode.has("required")) { - field.setRequired(fieldNode.get("required").asBoolean()); - } - if (fieldNode.has("fieldName")) { - field.setFieldName(fieldNode.get("fieldName").asText()); - } - if (fieldNode.has("fieldLabel")) { - field.setFieldLabel(fieldNode.get("fieldLabel").asText()); - } - if (fieldNode.has("fileFieldName")) { - field.setFileFieldName(fieldNode.get("fileFieldName").asText()); - } - mappingFields.add(field); - } - config.setFieldMapping(mappingFields); - - // 解析状态映射(可选) + config.setFieldMapping(mappingFields); + com.fasterxml.jackson.databind.JsonNode statusMappingNode = rootNode.get("statusMapping"); - if (statusMappingNode != null) { - if (statusMappingNode.isArray()) { - List statusMappings = new java.util.ArrayList<>(); + if (statusMappingNode != null && statusMappingNode.isArray()) { + java.util.List statusMappings = new java.util.ArrayList<>(); for (com.fasterxml.jackson.databind.JsonNode statusNode : statusMappingNode) { - if (!statusNode.isObject()) { - continue; - } - StatusMapping statusMapping = new StatusMapping(); - if (statusNode.has("csvStatus")) { - statusMapping.setCsvStatus(statusNode.get("csvStatus").asText()); - } - if (statusNode.has("mappedStatusId")) { - statusMapping.setMappedStatusId(statusNode.get("mappedStatusId").asLong()); - } - statusMappings.add(statusMapping); + if (!statusNode.isObject()) continue; + ImportRuntimeContext.StatusMapping sm = new ImportRuntimeContext.StatusMapping(); + if (statusNode.has("csvStatus")) sm.setCsvStatus(statusNode.get("csvStatus").asText()); + if (statusNode.has("mappedStatusId")) sm.setMappedStatusId(statusNode.get("mappedStatusId").asLong()); + statusMappings.add(sm); } config.setStatusMapping(statusMappings); - } } - + if (config.getFieldMapping() == null || config.getFieldMapping().isEmpty()) { throw new BusinessException("解析字段映射失败: 字段映射不能为空"); } - return config; } catch (BusinessException e) { - // 业务异常直接抛出 throw e; } catch (Exception e) { - throw new BusinessException("解析字段映射失败: " + e.getMessage()); + throw new BusinessException("解析映射配置失败: " + e.getMessage()); } } - /** - * 从CSV记录解析订单数据 - * - * @param record CSV记录 - * @param fieldMapping 字段映射(fieldName -> MappingField) - * @param statusMapping 状态映射(CSV状态文本 -> 状态ID) - * @param shopId 店铺ID - * @param defaultStatusId 默认订单状态ID - * @param companyId 公司ID - * @param createBy 创建人ID - * @return 创建订单DTO - */ - private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map fieldMapping, - Map statusMapping, Long shopId, Long defaultStatusId, - Long companyId, Long createBy, ImportRuntimeContext context) { - CreateOrderDTO orderDTO = new CreateOrderDTO(); - orderDTO.setShopId(shopId); - orderDTO.setStatusId(defaultStatusId); - - // 获取映射字段定义(使用下划线命名) - MappingField specCodeField = fieldMapping.get("spec_code"); // 规格编码 - MappingField receivedAmountField = fieldMapping.get("received_amount"); // 商家实收金额 - MappingField productQuantityField = fieldMapping.get("product_quantity"); // 商品数量 - MappingField orderStatusField = fieldMapping.get("status"); // 订单状态 - MappingField linkProductNameField = fieldMapping.get("link_product_name"); // 链接商品名称 - MappingField productCodeField = fieldMapping.get("product_code"); // 商品编码(可选字段) - MappingField linkSpecNameField = fieldMapping.get("link_spec_name"); // 链接规格名称 - MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); // 平台订单号 - MappingField orderDateField = fieldMapping.get("order_time"); // 下单时间 - - // 必填字段验证 - String specCode = getValue(record, specCodeField); - if (specCode == null || specCode.trim().isEmpty()) { - // 检查是否为必填字段 - 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, receivedAmountField); - if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) && - receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) { - throw new BusinessException("商家实收金额不能为空"); - } - - String productQuantityStr = getValue(record, productQuantityField); - if ((productQuantityStr == null || productQuantityStr.trim().isEmpty()) && - productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) { - throw new BusinessException("商品数量不能为空"); - } - - // 解析必填字段 - 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("商家实收金额不能为空"); - } - - 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); - } - } else if (productQuantityField != null && productQuantityField.getRequired() != null && productQuantityField.getRequired()) { - throw new BusinessException("商品数量不能为空"); - } - - // 解析可选字段(优先使用链接商品名称和链接规格名称) - // 这些字段来自CSV中的 link_product_name 和 link_spec_name,用于创建商品和规格时的命名 - String linkProductName = getValue(record, linkProductNameField); - // trim并转换空字符串为null - if (linkProductName != null) { - linkProductName = linkProductName.trim(); - if (linkProductName.isEmpty()) { - linkProductName = null; - } - } - - String productCode = getValue(record, productCodeField); - if (productCode != null) { - productCode = productCode.trim(); - if (productCode.isEmpty()) { - productCode = null; - } - } - - String linkSpecName = getValue(record, linkSpecNameField); - if (linkSpecName != null) { - linkSpecName = linkSpecName.trim(); - if (linkSpecName.isEmpty()) { - linkSpecName = null; - } - } - - // 首先通过规格编码查找商品规格 - ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId, context); - boolean isNewSpecCreated = false; // 标记是否创建了新规格 - - // 如果找不到规格,则尝试通过商品编码或商品名称查找商品,然后创建规格 - if (productSpec == null) { - ProductPO product = null; - - // 优先使用商品编码查找商品 - if (productCode != null && !productCode.isEmpty()) { - product = findProductByProductCode(productCode, companyId, context); - } - - // 如果商品编码查找失败,使用链接商品名称精准查找商品 - if (product == null && linkProductName != null && !linkProductName.isEmpty()) { - product = findProductByName(linkProductName, companyId, context); - } - - // 如果找到了商品,创建规格 - if (product != null) { - // 优先使用链接规格名称,如果没有则使用"未知规格" - String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格"; - productSpec = createSpecForProduct(companyId, product.getId(), finalSpecName, specCode.trim(), createBy, context); - isNewSpecCreated = true; - } - // 如果没有找到商品,则自动创建商品和规格 - else { - // 优先使用链接商品名称,如果没有则使用"未知商品" - String finalProductName = (linkProductName != null && !linkProductName.isEmpty()) ? linkProductName : "未知商品"; - // 优先使用链接规格名称,如果没有则使用"未知规格" - String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格"; - productSpec = createProductAndSpecIfNotExists(companyId, finalProductName, productCode, finalSpecName, specCode.trim(), createBy, context); - isNewSpecCreated = true; - } - } - - orderDTO.setProductId(productSpec.getProductId()); - orderDTO.setProductSpecId(productSpec.getId()); - // 设置单件成本(从商品规格中获取,作为下单时快照) - orderDTO.setProductCost(productSpec.getProductCost() != null ? productSpec.getProductCost() : BigDecimal.ZERO); - orderDTO.setShippingCost(productSpec.getShippingCost() != null ? productSpec.getShippingCost() : BigDecimal.ZERO); - orderDTO.setOtherCost(productSpec.getOtherCost() != null ? productSpec.getOtherCost() : BigDecimal.ZERO); - - // 设置链接商品名称和链接规格名称 - // 优先使用CSV中的链接商品名称和链接规格名称,如果没有则使用创建的商品/规格名称 - if (linkProductName != null && !linkProductName.isEmpty()) { - orderDTO.setLinkProductName(linkProductName); - } else { - ProductPO product = getProductById(productSpec.getProductId(), context); - orderDTO.setLinkProductName(product != null ? product.getName() : "未知商品"); - } - - // 优先使用CSV中的链接规格名称,如果没有则使用规格的名称 - if (linkSpecName != null && !linkSpecName.isEmpty()) { - orderDTO.setLinkSpecName(linkSpecName); - } else { - orderDTO.setLinkSpecName(productSpec.getName()); - } - - // 如果创建了新规格,订单的确认状态设为0(需要用户手动确认) - if (isNewSpecCreated) { - orderDTO.setConfirm(0); - } else { - // 如果找到已存在的规格,订单的确认状态设为1(已确认) - orderDTO.setConfirm(1); - } - - String platformOrderNo = getValue(record, platformOrderNoField); - if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) { - orderDTO.setPlatformOrderNo(platformOrderNo.trim()); - } - - // 计算销售单价(商家实收金额 / 数量) - if (orderDTO.getReceivedAmount() != null && orderDTO.getQuantity() != null && orderDTO.getQuantity() > 0) { - orderDTO.setUnitPrice(orderDTO.getReceivedAmount() - .divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP)); - } - - // 解析订单状态(如果提供了映射) - String orderStatusName = getValue(record, orderStatusField); - if (orderStatusName != null && !orderStatusName.trim().isEmpty()) { - String trimmedStatus = orderStatusName.trim(); - Long statusId = null; - - // 首先尝试通过状态映射转换(statusMapping中存储的是状态ID) - if (statusMapping != null && !statusMapping.isEmpty()) { - statusId = statusMapping.get(trimmedStatus); - } - - // 如果状态映射没有找到,尝试直接通过状态名称查找 - if (statusId == null) { - statusId = findOrderStatusIdByName(companyId, trimmedStatus, context); - } - - // 如果找到了有效的状态,则使用;否则自动创建新状态 - if (statusId != null) { - orderDTO.setStatusId(statusId); - } else { - // 用户没有做映射,且数据库中该公司没有当前状态名称,自动创建新的订单状态 - statusId = createOrderStatusIfNotExists(companyId, trimmedStatus, createBy, context); - orderDTO.setStatusId(statusId); - } - } - - // 解析下单时间(支持多种格式) - String orderDateStr = getValue(record, orderDateField); - if (orderDateStr != null && !orderDateStr.trim().isEmpty()) { - LocalDateTime orderTime = parseDateTime(orderDateStr.trim(), context); - if (orderTime != null) { - orderDTO.setOrderTime(orderTime); - } else { - orderDTO.setOrderTime(LocalDateTime.now()); - } - } else { - // 如果没有提供下单时间,使用当前时间 - orderDTO.setOrderTime(LocalDateTime.now()); - } - - return orderDTO; - } - - /** - * 日期时间格式定义(内部类) - */ - private static class DateTimeFormatPattern { - String pattern; - DateTimeFormatter formatter; - boolean hasTime; - - DateTimeFormatPattern(String pattern, boolean hasTime) { - this.pattern = pattern; - this.formatter = DateTimeFormatter.ofPattern(pattern); - this.hasTime = hasTime; - } - } - - /** - * 解析日期时间字符串,支持多种常见格式 - * - * @param dateTimeStr 日期时间字符串 - * @return LocalDateTime对象,如果解析失败则返回null - */ - private LocalDateTime parseDateTime(String dateTimeStr, ImportRuntimeContext context) { - if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) { - return null; - } - String trimmed = dateTimeStr.trim(); - - // 优先尝试首行检测到的格式(无异常,开销极低) - if (context != null && context.detectedDatePattern != null) { - try { - DateTimeFormatPattern p = context.detectedDatePattern; - if (p.hasTime) { - return LocalDateTime.parse(trimmed, p.formatter); - } else { - return java.time.LocalDate.parse(trimmed, p.formatter).atStartOfDay(); - } - } catch (DateTimeParseException ignored) { - // 检测格式失败,继续尝试所有格式 - } - } - - // 常见的日期时间格式列表(按使用频率排序,提高解析效率) - DateTimeFormatPattern[] patterns = { - // 带时分秒的格式(最常用) - new DateTimeFormatPattern("yyyy/MM/dd HH:mm:ss", true), // 2025/12/15 16:21:19 - new DateTimeFormatPattern("yyyy-MM-dd HH:mm:ss", true), // 2025-12-15 16:21:19 - new DateTimeFormatPattern("yyyy/M/d H:m:s", true), // 2025/1/5 8:5:9 - new DateTimeFormatPattern("yyyy-M-d H:m:s", true), // 2025-1-5 8:5:9 - - // 带时分的格式(秒数默认为00) - new DateTimeFormatPattern("yyyy/MM/dd HH:mm", true), // 2025/12/15 16:21 - new DateTimeFormatPattern("yyyy-MM-dd HH:mm", true), // 2025-12-15 16:21 - new DateTimeFormatPattern("yyyy/M/d H:m", true), // 2025/1/5 8:5 - new DateTimeFormatPattern("yyyy-M-d H:m", true), // 2025-1-5 8:5 - - // 中文格式 - new DateTimeFormatPattern("yyyy年MM月dd日 HH:mm:ss", true), // 2025年12月15日 16:21:19 - new DateTimeFormatPattern("yyyy年MM月dd日 HH:mm", true), // 2025年12月15日 16:21 - new DateTimeFormatPattern("yyyy年M月d日 H:m:s", true), // 2025年1月5日 8:5:9 - new DateTimeFormatPattern("yyyy年M月d日 H:m", true), // 2025年1月5日 8:5 - - // 仅日期格式(时间默认为00:00:00) - new DateTimeFormatPattern("yyyy/MM/dd", false), // 2025/12/15 - new DateTimeFormatPattern("yyyy-MM-dd", false), // 2025-12-15 - new DateTimeFormatPattern("yyyy/M/d", false), // 2025/1/5 - new DateTimeFormatPattern("yyyy-M-d", false), // 2025-1-5 - new DateTimeFormatPattern("yyyy年MM月dd日", false), // 2025年12月15日 - new DateTimeFormatPattern("yyyy年M月d日", false) // 2025年1月5日 - }; - - // 尝试使用每种格式解析 - for (DateTimeFormatPattern pattern : patterns) { - try { - if (pattern.hasTime) { - // 包含时间部分,直接解析为LocalDateTime - return LocalDateTime.parse(dateTimeStr, pattern.formatter); - } else { - // 只有日期部分,解析为LocalDate后转换为LocalDateTime(时间为00:00:00) - return java.time.LocalDate.parse(dateTimeStr, pattern.formatter).atStartOfDay(); - } - } catch (DateTimeParseException e) { - // 当前格式不匹配,尝试下一个 - } - } - - // 所有格式都失败 - return null; - } - - /** - * 根据日期字符串特征快速判断格式(不抛异常) - */ - private DateTimeFormatPattern detectDateFormat(String dateStr) { - // 带时分秒的格式判断 - if (dateStr.contains("/")) { - if (dateStr.contains(":")) { - return new DateTimeFormatPattern("yyyy/MM/dd HH:mm:ss", true); - } - if (dateStr.contains("年")) { - return new DateTimeFormatPattern("yyyy年MM月dd日", false); - } - return new DateTimeFormatPattern("yyyy/MM/dd", false); - } - if (dateStr.contains("-")) { - if (dateStr.contains(":")) { - return new DateTimeFormatPattern("yyyy-MM-dd HH:mm:ss", true); - } - if (dateStr.contains("年")) { - return new DateTimeFormatPattern("yyyy年MM月dd日", false); - } - return new DateTimeFormatPattern("yyyy-MM-dd", false); - } - if (dateStr.contains("年")) { - return new DateTimeFormatPattern("yyyy年MM月dd日", false); - } - return null; - } - - /** - * 从CSV记录获取值 - * - * @param record CSV记录 - * @param mappingField 映射字段定义 - * @return 值 - */ - private String getValue(CSVRecord record, MappingField mappingField) { - if (mappingField == null || mappingField.getFileFieldName() == null || mappingField.getFileFieldName().trim().isEmpty()) { - return null; - } - return getValue(record, mappingField.getFileFieldName()); - } - - /** - * 从CSV记录获取值(重载方法,兼容旧代码) - * - * @param record CSV记录 - * @param header 表头名称 - * @return 值 - */ - private String getValue(CSVRecord record, String header) { - if (header == null || header.trim().isEmpty()) { - return null; - } - - String trimmedHeader = header.trim(); - Map headerMap = record.getParser().getHeaderMap(); - - // 首先尝试精确匹配(考虑CSV解析器已经设置了setTrim(true)) - try { - return record.get(trimmedHeader); - } catch (IllegalArgumentException e) { - // 精确匹配失败,尝试忽略大小写匹配 - String matchedHeader = headerMap.keySet().stream() - .filter(h -> h.trim().equalsIgnoreCase(trimmedHeader)) - .findFirst() - .orElse(null); - - if (matchedHeader != null) { - return record.get(matchedHeader); - } - - // 如果还是找不到,尝试包含匹配(处理可能的空格或特殊字符) - matchedHeader = headerMap.keySet().stream() - .filter(h -> h.trim().equalsIgnoreCase(trimmedHeader) || - h.trim().replaceAll("\\s+", "").equalsIgnoreCase(trimmedHeader.replaceAll("\\s+", ""))) - .findFirst() - .orElse(null); - - if (matchedHeader != null) { - return record.get(matchedHeader); - } - - // 处理BOM字符:尝试去除BOM后匹配(BOM字符是\uFEFF) - matchedHeader = headerMap.keySet().stream() - .filter(h -> removeBOM(h).trim().equalsIgnoreCase(trimmedHeader)) - .findFirst() - .orElse(null); - - if (matchedHeader != null) { - return record.get(matchedHeader); - } - - return null; - } - } - - /** - * 去除字符串开头的BOM字符 - * - * @param s 字符串 - * @return 去除BOM后的字符串 - */ - private String removeBOM(String s) { - if (s == null || s.isEmpty()) { - return s; - } - // BOM字符是 \uFEFF - if (s.charAt(0) == '\uFEFF') { - return s.substring(1); - } - return s; - } - - /** - * 通过规格编码查找商品规格 - * - * @param specCode 规格编码 - * @param companyId 公司ID - * @return 商品规格 - */ - private ProductSpecPO findProductSpecBySpecCode(String specCode, Long companyId, ImportRuntimeContext context) { - if (specCode == null) { - return null; - } - String normalized = specCode.trim(); - if (normalized.isEmpty()) { - return null; - } - ProductSpecPO cached = context.specByCodeCache.get(normalized); - if (cached != null) { - return cached; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductSpecPO::getSpecCode, normalized) - .eq(ProductSpecPO::getCompanyId, companyId); - ProductSpecPO productSpec = productSpecService.getOne(wrapper); - if (productSpec != null) { - context.specByCodeCache.put(normalized, productSpec); - } - return productSpec; - } - - /** - * 通过商品编码查找商品 - * - * @param productCode 商品编码 - * @param companyId 公司ID - * @return 商品 - */ - private ProductPO findProductByProductCode(String productCode, Long companyId, ImportRuntimeContext context) { - if (productCode == null) { - return null; - } - String normalized = productCode.trim(); - if (normalized.isEmpty()) { - return null; - } - ProductPO cached = context.productByCodeCache.get(normalized); - if (cached != null) { - return cached; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductPO::getProductCode, normalized) - .eq(ProductPO::getCompanyId, companyId); - ProductPO product = productMapper.selectOne(wrapper); - if (product != null) { - context.productByCodeCache.put(normalized, product); - context.productByIdCache.put(product.getId(), product); - if (product.getName() != null) { - context.productByNameCache.put(product.getName(), product); - } - } - return product; - } - - /** - * 通过商品名称查找商品(精准匹配) - * - * @param productName 商品名称 - * @param companyId 公司ID - * @return 商品 - */ - private ProductPO findProductByName(String productName, Long companyId, ImportRuntimeContext context) { - if (productName == null) { - return null; - } - String normalized = productName.trim(); - if (normalized.isEmpty()) { - return null; - } - ProductPO cached = context.productByNameCache.get(normalized); - if (cached != null) { - return cached; - } - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductPO::getName, normalized) - .eq(ProductPO::getCompanyId, companyId); - ProductPO product = productMapper.selectOne(wrapper); - if (product != null) { - context.productByNameCache.put(normalized, product); - context.productByIdCache.put(product.getId(), product); - if (product.getProductCode() != null) { - context.productByCodeCache.put(product.getProductCode(), product); - } - } - return product; - } - - /** - * 为已存在的商品创建规格 - * - * @param companyId 公司ID - * @param productId 商品ID - * @param specName 规格名称 - * @param specCode 规格编码 - * @param createBy 创建人ID - * @return 商品规格 - */ - /** - * 直接用已知的 ProductPO 创建规格(避免重复 selectById) - */ - private ProductSpecPO createSpecForProduct(ProductPO product, String specName, String specCode, Long createBy, - ImportRuntimeContext context) { - Long productId = product.getId(); - Long companyId = product.getCompanyId(); - return createSpecForProductWithValidation(productId, companyId, specName, specCode, createBy, context); - } - - /** - * 根据 productId 查库后创建规格(保留给其他调用方) - */ - private ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, String specCode, Long createBy, - ImportRuntimeContext context) { - ProductPO existingProduct = productMapper.selectById(productId); - if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) { - throw new BusinessException("商品不存在"); - } - return createSpecForProductWithValidation(productId, companyId, specName, specCode, createBy, context); - } - - private ProductSpecPO createSpecForProductWithValidation(Long productId, Long companyId, String specName, String specCode, Long createBy, - ImportRuntimeContext context) { - // 验证规格名称是否重复 - 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.setLinkName(specName); // 导入时链接名称默认等于规格名称 - productSpec.setSpecCode(specCode); - productSpec.setProductCost(BigDecimal.ZERO); - productSpec.setShippingCost(BigDecimal.ZERO); - productSpec.setOtherCost(BigDecimal.ZERO); - productSpec.setCreateBy(createBy); - productSpecService.save(productSpec); - context.specByCodeCache.put(specCode, productSpec); - 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 productCode, String specName, String specCode, Long createBy, - ImportRuntimeContext context) { - // 1. 通过商品名称查找商品(复用ProductService.getProductByName的逻辑) - com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper productWrapper = - new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); - productWrapper.eq(ProductPO::getName, productName) - .eq(ProductPO::getCompanyId, companyId); - ProductPO product = productMapper.selectOne(productWrapper); - - Long productId; - if (product == null) { - // 商品不存在,创建商品(复用ProductService.createProduct的逻辑:验证商品名称是否重复) - // 注意:createProduct需要CurrentUserContext,但我们在消费者线程中没有 - // 所以这里直接使用Mapper创建,保持与createProduct相同的验证逻辑 - // 由于上面已经查询过product为null,这里再次检查是为了避免并发问题 - com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper checkWrapper = - new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); - checkWrapper.eq(ProductPO::getName, productName) - .eq(ProductPO::getCompanyId, companyId); - if (productMapper.selectCount(checkWrapper) > 0) { - // 在检查期间商品被创建了,重新查询 - product = productMapper.selectOne(productWrapper); - productId = product.getId(); - } else { - // 创建新商品(复用ProductService.createProduct的逻辑) - product = new ProductPO(); - product.setCompanyId(companyId); - product.setName(productName); - product.setLinkName(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(); - } - } else { - productId = product.getId(); - } - - // 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑) - context.productByIdCache.put(productId, product); - if (product.getName() != null) { - context.productByNameCache.put(product.getName(), product); - } - if (product.getProductCode() != null) { - context.productByCodeCache.put(product.getProductCode(), product); - } - return createSpecForProduct(product, specName, specCode, createBy, context); - } - - /** - * 创建订单(不依赖CurrentUserContext,复用OrderService.createOrder的业务逻辑) - * - * @param createOrderDTO 创建订单DTO - * @param companyId 公司ID - * @param createBy 创建人ID - * @param importTaskId 导入任务ID(可选,如果为null则表示手动创建) - * @return 订单VO - */ - private OrderVO createOrderWithoutContext(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId) { - // 复用OrderService.createOrder的验证逻辑 - - // 验证店铺是否存在且属于当前公司 - top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO shop = shopService.getById(createOrderDTO.getShopId()); - if (shop == null || !shop.getCompanyId().equals(companyId)) { - throw new BusinessException("店铺不存在"); - } - - // 验证商品是否存在且属于当前公司 - ProductPO product = productMapper.selectById(createOrderDTO.getProductId()); - if (product == null || !product.getCompanyId().equals(companyId)) { - throw new BusinessException("商品不存在"); - } - - // 验证商品规格是否存在且属于当前公司(如果提供了规格ID) - ProductSpecPO productSpec = null; - if (createOrderDTO.getProductSpecId() != null) { - productSpec = productSpecService.getById(createOrderDTO.getProductSpecId()); - if (productSpec == null || !productSpec.getCompanyId().equals(companyId) || - !productSpec.getProductId().equals(createOrderDTO.getProductId())) { - throw new BusinessException("商品规格不存在或不属于该商品"); - } - } - - // 验证平台订单号是否重复(如果提供了的话) - // 如果重复,则更新已存在的订单而不是报错 - if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) { - com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper = - new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); - wrapper.eq(OrderPO::getPlatformOrderNo, createOrderDTO.getPlatformOrderNo()) - .eq(OrderPO::getCompanyId, companyId); - OrderPO existingOrder = orderMapper.selectOne(wrapper); - if (existingOrder != null) { - // 平台订单号已存在,记录existingOrderId用于更新 - createOrderDTO.setExistingOrderId(existingOrder.getId()); - } - } - - // 检查并创建店铺商品关联(如果不存在) - ensureShopProductRelation(createOrderDTO.getShopId(), createOrderDTO.getProductId(), companyId, createBy); - - // 创建订单(包含商品明细) - OrderPO order = new OrderPO(); - order.setCompanyId(companyId); - order.setShopId(createOrderDTO.getShopId()); - order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo()); - order.setStatusId(createOrderDTO.getStatusId()); - order.setProductId(createOrderDTO.getProductId()); - order.setProductSpecId(createOrderDTO.getProductSpecId()); - order.setLinkProductName(createOrderDTO.getLinkProductName()); - order.setLinkSpecName(createOrderDTO.getLinkSpecName()); - order.setQuantity(createOrderDTO.getQuantity()); - order.setUnitPrice(createOrderDTO.getUnitPrice()); - order.setProductCost(createOrderDTO.getProductCost()); - order.setShippingCost(createOrderDTO.getShippingCost()); - order.setOtherCost(createOrderDTO.getOtherCost()); - // 备注不复制,订单导入时不设置备注字段 - order.setReceivedAmount(createOrderDTO.getReceivedAmount()); - order.setOrderTime(createOrderDTO.getOrderTime()); - order.setCreateBy(createBy); - // 设置导入任务ID和确认状态 - order.setImportTaskId(importTaskId); - // 使用DTO中的确认状态(如果DTO中指定了值则使用指定值,否则默认为1) - order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1); - - // 保存订单 - orderMapper.insert(order); - - // 转换为VO并返回 - return convertOrderToVO(order); - } - - /** - * 转换订单PO为VO - * - * @param order 订单PO - * @return 订单VO - */ - private OrderVO convertOrderToVO(OrderPO order) { - OrderVO orderVO = new OrderVO(); - BeanUtils.copyProperties(order, orderVO); - return orderVO; - } - - /** - * 确保店铺商品关联存在,如果不存在则创建 - * - * @param shopId 店铺ID - * @param productId 商品ID - * @param companyId 公司ID - * @param createBy 创建人ID - */ - private void ensureShopProductRelation(Long shopId, Long productId, Long companyId, Long createBy) { - // 检查关联是否已存在 - com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper = - new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); - wrapper.eq(ShopProductRelationPO::getShopId, shopId) - .eq(ShopProductRelationPO::getProductId, productId) - .eq(ShopProductRelationPO::getCompanyId, companyId); - - ShopProductRelationPO existingRelation = shopProductRelationMapper.selectOne(wrapper); - - if (existingRelation == null) { - // 关联不存在,创建新关联 - ShopProductRelationPO relation = new ShopProductRelationPO(); - relation.setCompanyId(companyId); - relation.setShopId(shopId); - relation.setProductId(productId); - relation.setSortOrder(0); // 默认排序为0 - relation.setCreateBy(createBy); - shopProductRelationMapper.insert(relation); - } - } - - private void addNormalizedValue(Set target, String rawValue) { - if (rawValue == null) { - return; - } - String value = rawValue.trim(); - if (!value.isEmpty()) { - target.add(value); - } - } - - private void preloadProductSpecs(ImportRuntimeContext context, Set specCodes) { - for (List chunk : splitToChunks(specCodes, IN_QUERY_BATCH_SIZE)) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductSpecPO::getCompanyId, context.companyId) - .in(ProductSpecPO::getSpecCode, chunk); - List specs = productSpecService.list(wrapper); - for (ProductSpecPO spec : specs) { - context.specByCodeCache.put(spec.getSpecCode(), spec); - } - } - } - - private void preloadProductsByCode(ImportRuntimeContext context, Set productCodes) { - for (List chunk : splitToChunks(productCodes, IN_QUERY_BATCH_SIZE)) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductPO::getCompanyId, context.companyId) - .in(ProductPO::getProductCode, chunk); - List products = productMapper.selectList(wrapper); - for (ProductPO product : products) { - cacheProduct(context, product); - } - } - } - - private void preloadProductsByName(ImportRuntimeContext context, Set productNames) { - for (List chunk : splitToChunks(productNames, IN_QUERY_BATCH_SIZE)) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ProductPO::getCompanyId, context.companyId) - .in(ProductPO::getName, chunk); - List products = productMapper.selectList(wrapper); - for (ProductPO product : products) { - cacheProduct(context, product); - } - } - } - - private void preloadStatuses(ImportRuntimeContext context, Set statusNames, Map statusMapping) { - if (statusMapping != null) { - context.statusIdByNameCache.putAll(statusMapping); - } - for (List chunk : splitToChunks(statusNames, IN_QUERY_BATCH_SIZE)) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, context.companyId) - .in(OrderStatusPO::getStatusName, chunk); - List statusList = orderStatusService.list(wrapper); - for (OrderStatusPO status : statusList) { - context.statusIdByNameCache.put(status.getStatusName(), status.getId()); - } - } - } - - private void preloadPlatformOrderNos(ImportRuntimeContext context, Set platformOrderNos) { - for (List chunk : splitToChunks(platformOrderNos, IN_QUERY_BATCH_SIZE)) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(OrderPO::getCompanyId, context.companyId) - .in(OrderPO::getPlatformOrderNo, chunk) - .select(OrderPO::getId, OrderPO::getPlatformOrderNo); - List orders = orderMapper.selectList(wrapper); - for (OrderPO order : orders) { - if (order.getPlatformOrderNo() != null) { - String normalized = order.getPlatformOrderNo().trim(); - context.existingPlatformOrderNos.add(normalized); - context.existingOrderIdByPlatformNo.put(normalized, order.getId()); - } - } - } - } - - private void preloadShopProductRelations(ImportRuntimeContext context) { - LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); - wrapper.eq(ShopProductRelationPO::getCompanyId, context.companyId) - .eq(ShopProductRelationPO::getShopId, context.shopId) - .select(ShopProductRelationPO::getProductId); - List relations = shopProductRelationMapper.selectList(wrapper); - for (ShopProductRelationPO relation : relations) { - context.existingRelationKeys.add(buildRelationKey(context.shopId, relation.getProductId())); - } - } - - private List> splitToChunks(Set values, int chunkSize) { - if (values == null || values.isEmpty()) { - return Collections.emptyList(); - } - List all = new ArrayList<>(values); - List> chunks = new ArrayList<>(); - for (int i = 0; i < all.size(); i += chunkSize) { - chunks.add(all.subList(i, Math.min(i + chunkSize, all.size()))); - } - return chunks; - } - - private void cacheProduct(ImportRuntimeContext context, ProductPO product) { - context.productByIdCache.put(product.getId(), product); - if (product.getName() != null) { - context.productByNameCache.put(product.getName(), product); - } - if (product.getProductCode() != null) { - context.productByCodeCache.put(product.getProductCode(), product); - } - } - - private ProductPO getProductById(Long productId, ImportRuntimeContext context) { - ProductPO cached = context.productByIdCache.get(productId); - if (cached != null) { - return cached; - } - ProductPO product = productMapper.selectById(productId); - if (product != null) { - cacheProduct(context, product); - } - return product; - } - - /** - * 验证平台订单号是否重复(内存检查) - * 如果同一批次内有重复,更新已存在的pending订单数据 - * @param platformOrderNo 平台订单号 - * @param context 导入上下文 - * @param newOrderPO 新的订单数据(用于覆盖之前的) - * @param newRowNumber 新的行号 - * @param newExistingOrderId 新的existingOrderId(如果DB中有记录) - * @param newUpdateMsg 新的更新消息 - * @return 如果是重复返回true - */ - private boolean validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context, OrderPO newOrderPO, int newRowNumber, Long newExistingOrderId, StringBuilder newUpdateMsg) { - if (platformOrderNo == null || platformOrderNo.trim().isEmpty()) { - return false; - } - String normalized = platformOrderNo.trim(); - - // 检查同一批次内是否已存在相同的平台订单号 - // 优先使用 preload 中已知的最早 existingOrderId - Long existingId = newExistingOrderId; - if (existingId == null && context.existingOrderIdByPlatformNo.containsKey(normalized)) { - existingId = context.existingOrderIdByPlatformNo.get(normalized); - } - - if (context.pendingPlatformOrderNos.contains(normalized)) { - // 同批次内重复:更新已存在的pending订单数据 - PendingOrderInsert existing = context.pendingOrderByPlatformNo.get(normalized); - if (existing != null) { - // 更新已存在订单的数据和行号,同时保留/更新 existingOrderId - existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber); - } - return true; - } - - // 新增 - context.pendingPlatformOrderNos.add(normalized); - return false; - } - - private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) { - String relationKey = buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId()); - if (context.existingRelationKeys.contains(relationKey) || context.pendingRelationKeys.contains(relationKey)) { - return; - } - ShopProductRelationPO relation = new ShopProductRelationPO(); - relation.setCompanyId(context.companyId); - relation.setShopId(orderDTO.getShopId()); - relation.setProductId(orderDTO.getProductId()); - relation.setSortOrder(0); - relation.setCreateBy(context.createBy); - context.pendingRelations.add(relation); - context.pendingRelationKeys.add(relationKey); - } - - private String buildRelationKey(Long shopId, Long productId) { - return shopId + "#" + productId; - } - - private void flushPendingRelations(ImportRuntimeContext context) { - if (context.pendingRelations.isEmpty()) { - return; - } - List batch = new ArrayList<>(context.pendingRelations); - try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { - ShopProductRelationMapper batchMapper = session.getMapper(ShopProductRelationMapper.class); - for (ShopProductRelationPO relation : batch) { - batchMapper.insert(relation); - } - session.flushStatements(); - session.commit(); - for (ShopProductRelationPO relation : batch) { - context.existingRelationKeys.add(buildRelationKey(relation.getShopId(), relation.getProductId())); - } - } catch (Exception e) { - for (ShopProductRelationPO relation : batch) { - try { - shopProductRelationMapper.insert(relation); - context.existingRelationKeys.add(buildRelationKey(relation.getShopId(), relation.getProductId())); - } catch (Exception ignored) { - // 并发场景下唯一键冲突可忽略,关系存在即可 - } - } - } finally { - context.pendingRelations.clear(); - context.pendingRelationKeys.clear(); - } - } - - private int[] flushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) { - if (context.pendingOrders.isEmpty()) { - return new int[] {0, 0, 0, 0}; - } - int insertSuccess = 0; - int insertFail = 0; - int updateSuccess = 0; - int updateFail = 0; - List batch = new ArrayList<>(context.pendingOrders); - - // 分离新增和更新 - List inserts = new ArrayList<>(); - List updates = new ArrayList<>(); - for (PendingOrderInsert pending : batch) { - if (pending.existingOrderId != null) { - updates.add(pending); - } else { - inserts.add(pending); - } - } - - // 处理新增 - if (!inserts.isEmpty()) { - int[] result = doBatchInsert(inserts, context, errorMessages); - insertSuccess += result[0]; - insertFail += result[1]; - } - - // 处理更新 - for (PendingOrderInsert pending : updates) { - try { - orderMapper.updateById(pending.order); - updateSuccess++; - // 记录更新消息 - if (pending.updateMessages != null && pending.updateMessages.length() > 0) { - String updateInfo = pending.updateMessages.toString(); - errorMessages.append(String.format("[更新] 第%d行:%s", pending.rowNumber, updateInfo)) - .append(System.lineSeparator()); - } - // 更新内存状态 - if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) { - String normalized = pending.platformOrderNo.trim(); - context.pendingPlatformOrderNos.remove(normalized); - context.existingPlatformOrderNos.add(normalized); - } - } catch (Exception e) { - updateFail++; - errorMessages.append(String.format("[失败] 第%d行:更新失败 %s", pending.rowNumber, e.getMessage())) - .append(System.lineSeparator()); - } - } - - context.pendingOrders.clear(); - return new int[] {insertSuccess, insertFail, updateSuccess, updateFail}; - } - - private int[] doBatchInsert(List inserts, ImportRuntimeContext context, StringBuilder errorMessages) { - int success = 0; - int fail = 0; - try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { - OrderMapper batchMapper = session.getMapper(OrderMapper.class); - for (PendingOrderInsert pending : inserts) { - batchMapper.insert(pending.order); - } - session.flushStatements(); - session.commit(); - success += inserts.size(); - for (PendingOrderInsert pending : inserts) { - if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) { - String normalized = pending.platformOrderNo.trim(); - context.pendingPlatformOrderNos.remove(normalized); - context.existingPlatformOrderNos.add(normalized); - } - } - } catch (Exception e) { - for (PendingOrderInsert pending : inserts) { - try { - orderMapper.insert(pending.order); - success++; - if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) { - String normalized = pending.platformOrderNo.trim(); - context.pendingPlatformOrderNos.remove(normalized); - context.existingPlatformOrderNos.add(normalized); - } - } catch (Exception singleEx) { - fail++; - if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) { - context.pendingPlatformOrderNos.remove(pending.platformOrderNo.trim()); - } - errorMessages.append(String.format("第%d行:%s", pending.rowNumber, singleEx.getMessage())) - .append(System.lineSeparator()); - } - } - } - return new int[] {success, fail}; - } - - private OrderPO buildOrderPO(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId, ImportRuntimeContext context) { - OrderPO order = new OrderPO(); - order.setCompanyId(companyId); - order.setShopId(createOrderDTO.getShopId()); - order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo()); - order.setStatusId(createOrderDTO.getStatusId()); - order.setProductId(createOrderDTO.getProductId()); - order.setProductSpecId(createOrderDTO.getProductSpecId()); - order.setLinkProductName(createOrderDTO.getLinkProductName()); - order.setLinkSpecName(createOrderDTO.getLinkSpecName()); - order.setQuantity(createOrderDTO.getQuantity()); - order.setUnitPrice(createOrderDTO.getUnitPrice()); - order.setProductCost(createOrderDTO.getProductCost()); - order.setShippingCost(createOrderDTO.getShippingCost()); - order.setOtherCost(createOrderDTO.getOtherCost()); - order.setReceivedAmount(createOrderDTO.getReceivedAmount()); - order.setOrderTime(createOrderDTO.getOrderTime()); - order.setCreateBy(createBy); - order.setImportTaskId(importTaskId); - order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1); - // 从 preload 的订单号→ID 映射中查找已有订单ID,用于走 UPDATE 而非 INSERT - if (context != null && createOrderDTO.getPlatformOrderNo() != null) { - String normalized = createOrderDTO.getPlatformOrderNo().trim(); - if (context.existingOrderIdByPlatformNo.containsKey(normalized)) { - order.setId(context.existingOrderIdByPlatformNo.get(normalized)); - } - } - return order; - } - - - /** - * 更新任务状态 - * - * @param taskId 任务ID - * @param status 状态 - * @param message 消息 - * @param totalCount 总行数 - * @param successCount 成功行数 - * @param failCount 失败行数 - */ private void updateTaskStatus(Long taskId, String status, String message, Integer totalCount, Integer successCount, Integer failCount) { LambdaUpdateWrapper updateWrapper = new LambdaUpdateWrapper<>(); updateWrapper.eq(ImportTaskPO::getId, taskId); updateWrapper.set(ImportTaskPO::getStatus, status); if (message != null) { - // text 上限约 65535 字节,按字节长度截断(中文在UTF-8下占3字节) byte[] msgBytes = message.getBytes(java.nio.charset.StandardCharsets.UTF_8); String safeMsg = msgBytes.length > 60000 ? new String(msgBytes, 0, 60000, java.nio.charset.StandardCharsets.UTF_8) : message; updateWrapper.set(ImportTaskPO::getMessage, safeMsg); } - if (totalCount != null) { - updateWrapper.set(ImportTaskPO::getTotalCount, totalCount); - } - if (successCount != null) { - updateWrapper.set(ImportTaskPO::getSuccessCount, successCount); - } - if (failCount != null) { - updateWrapper.set(ImportTaskPO::getFailCount, failCount); - } + if (totalCount != null) updateWrapper.set(ImportTaskPO::getTotalCount, totalCount); + if (successCount != null) updateWrapper.set(ImportTaskPO::getSuccessCount, successCount); + if (failCount != null) updateWrapper.set(ImportTaskPO::getFailCount, failCount); importTaskService.update(updateWrapper); } - /** - * 通知任务进度 - * - * @param userId 用户ID - * @param taskVO 导入任务VO(完整信息) - */ private void notifyTaskProgress(Long userId, ImportTaskVO taskVO) { + if (userId == null || taskVO == null) return; try { sseNotificationService.sendTaskProgress(userId, taskVO); } catch (Exception e) { - // 静默处理通知失败 + // SSE 发送失败不影响主流程 } } - /** - * 转换为VO - * - * @param importTaskPO 导入任务PO - * @return 导入任务VO - */ private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) { - if (importTaskPO == null) { - return null; - } - ImportTaskVO importTaskVO = new ImportTaskVO(); - BeanUtils.copyProperties(importTaskPO, importTaskVO); - return importTaskVO; + if (importTaskPO == null) return null; + ImportTaskVO vo = new ImportTaskVO(); + org.springframework.beans.BeanUtils.copyProperties(importTaskPO, vo); + return vo; } - /** - * 检测文件编码 - * 尝试多种常见的中文编码 - * - * @param inputStream 文件输入流(需支持mark/reset,或使用BufferedInputStream包装) - * @return 检测到的编码 - */ - private java.nio.charset.Charset detectFileEncoding(InputStream inputStream) { - // 常见的编码列表,按优先级排序 - java.nio.charset.Charset[] charsets = { - java.nio.charset.Charset.forName("GBK"), // 优先尝试GBK,因为中文CSV文件常用GBK - java.nio.charset.Charset.forName("GB2312"), - java.nio.charset.StandardCharsets.UTF_8, - java.nio.charset.StandardCharsets.ISO_8859_1 + private Charset detectFileEncoding(InputStream inputStream) throws IOException { + Charset[] charsets = { + Charset.forName("GBK"), + Charset.forName("GB2312"), + Charset.forName("UTF-8"), + Charset.forName("ISO-8859-1") }; - - // 读取文件的前几行来检测编码 - for (java.nio.charset.Charset charset : charsets) { + for (Charset charset : charsets) { try { inputStream.mark(2048); char[] buffer = new char[2048]; @@ -1843,10 +297,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic if (read > 0) { String content = new String(buffer, 0, read); inputStream.reset(); - // 简单检测:如果包含常见的中文字符,可能是正确的编码 - if (content.contains("商家") || content.contains("编码") || - content.contains("商品") || content.contains("订单") || - content.contains("规格") || content.contains("金额")) { + if (content.contains("商家") || content.contains("编码") || + content.contains("商品") || content.contains("订单") || + content.contains("规格") || content.contains("金额")) { return charset; } } @@ -1855,70 +308,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic // 忽略编码检测错误 } } - - // 默认返回GBK(中文CSV文件最常用) - return java.nio.charset.Charset.forName("GBK"); - } - - /** - * 根据状态名称查找订单状态ID - * - * @param companyId 公司ID - * @param statusName 状态名称 - * @return 订单状态ID,如果不存在则返回null - */ - private Long findOrderStatusIdByName(Long companyId, String statusName) { - return findOrderStatusIdByName(companyId, statusName, null); - } - - private Long findOrderStatusIdByName(Long companyId, String statusName, ImportRuntimeContext context) { - if (statusName == null || statusName.trim().isEmpty()) { - return null; - } - String normalized = statusName.trim(); - if (context != null && context.statusIdByNameCache.containsKey(normalized)) { - return context.statusIdByNameCache.get(normalized); - } - com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper wrapper = - new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>(); - wrapper.eq(OrderStatusPO::getCompanyId, companyId) - .eq(OrderStatusPO::getStatusName, normalized); - OrderStatusPO status = orderStatusService.getOne(wrapper); - Long statusId = status != null ? status.getId() : null; - if (context != null) { - context.statusIdByNameCache.put(normalized, statusId); - } - return statusId; - } - - private Long createOrderStatusIfNotExists(Long companyId, String statusName, Long createBy, ImportRuntimeContext context) { - if (statusName == null || statusName.trim().isEmpty()) { - throw new BusinessException("订单状态名称不能为空"); - } - - String trimmedStatusName = statusName.trim(); - - // 再次检查状态是否已存在(避免并发创建) - Long existingStatusId = findOrderStatusIdByName(companyId, trimmedStatusName, context); - if (existingStatusId != null) { - return existingStatusId; - } - - // 创建新的订单状态 - OrderStatusPO orderStatus = new OrderStatusPO(); - orderStatus.setCompanyId(companyId); - orderStatus.setStatusName(trimmedStatusName); - orderStatus.setDescription("自动创建的状态"); - orderStatus.setSortOrder(0); - orderStatus.setAutoStatistics(1); // 自动参与统计字段设置为是(1) - orderStatus.setCreateBy(createBy); - - // 保存订单状态 - orderStatusService.save(orderStatus); - if (context != null) { - context.statusIdByNameCache.put(trimmedStatusName, orderStatus.getId()); - } - return orderStatus.getId(); + return Charset.forName("GBK"); } } - diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java new file mode 100644 index 00000000..8bb1f657 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/OrderImportProcessor.java @@ -0,0 +1,735 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import org.apache.ibatis.session.ExecutorType; +import org.apache.ibatis.session.SqlSession; +import org.apache.ibatis.session.SqlSessionFactory; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.CreateOrderDTO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStreamReader; +import java.math.BigDecimal; +import java.nio.charset.Charset; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.*; +import java.util.function.BiConsumer; + +/** + * 订单导入核心处理器 + *

+ * 职责:CSV 解析 → 商品/规格解析 → 订单构建 → 批量插入 + * 不涉及:任务状态管理、文件获取、SSE 通知(由调用方负责) + */ +public class OrderImportProcessor { + + private static final int ORDER_BATCH_SIZE = 1000; + private static final int RELATION_BATCH_SIZE = 500; + private static final int IN_QUERY_BATCH_SIZE = 1000; + + private final ProductSpecImportHelper specHelper; + private final OrderMapper orderMapper; + private final ShopProductRelationMapper shopProductRelationMapper; + private final SqlSessionFactory sqlSessionFactory; + + public OrderImportProcessor(ProductSpecImportHelper specHelper, + OrderMapper orderMapper, + ShopProductRelationMapper shopProductRelationMapper, + SqlSessionFactory sqlSessionFactory) { + this.specHelper = specHelper; + this.orderMapper = orderMapper; + this.shopProductRelationMapper = shopProductRelationMapper; + this.sqlSessionFactory = sqlSessionFactory; + } + + /** + * 处理订单导入(入口方法,由 ImportTaskProcessorServiceImpl.processOrderImport 调用) + */ + public ImportRuntimeContext.ImportResult process( + top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO task, + File csvFile, + Charset charset, + Map fieldMapping, + Map statusMapping, + ImportRuntimeContext context, + BiConsumer progressCallback) { + + ImportRuntimeContext.ImportResult result = new ImportRuntimeContext.ImportResult(); + + try (FileInputStream fis = new FileInputStream(csvFile); + InputStreamReader reader = new InputStreamReader(fis, charset); + CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.builder() + .setHeader() + .setSkipHeaderRecord(true) + .setIgnoreHeaderCase(true) + .setTrim(true) + .build())) { + + // 收集预加载数据 + ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code"); + ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code"); + ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name"); + ImportRuntimeContext.MappingField orderStatusField = fieldMapping.get("status"); + ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); + ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_date"); + + Set specCodes = new HashSet<>(); + Set productCodes = new HashSet<>(); + Set productNames = new HashSet<>(); + Set platformOrderNos = new HashSet<>(); + Set statusNames = new HashSet<>(); + List records = new ArrayList<>(); + + for (CSVRecord record : csvParser) { + records.add(record); + context.addNormalizedValue(specCodes, getValue(record, specCodeField)); + context.addNormalizedValue(productCodes, getValue(record, productCodeField)); + context.addNormalizedValue(productNames, getValue(record, linkProductNameField)); + context.addNormalizedValue(platformOrderNos, getValue(record, platformOrderNoField)); + context.addNormalizedValue(statusNames, getValue(record, orderStatusField)); + if (context.getDetectedDatePattern() == null && orderDateField != null) { + String dateStr = getValue(record, orderDateField); + if (dateStr != null && !dateStr.trim().isEmpty()) { + context.setDetectedDatePattern(detectDateFormat(dateStr.trim())); + } + } + } + result.totalCount = records.size(); + + // 预加载 + specHelper.preloadProductSpecs(context, specCodes); + specHelper.preloadProductsByCode(context, productCodes); + specHelper.preloadProductsByName(context, productNames); + specHelper.preloadPlatformOrderNos(context, platformOrderNos, orderMapper); + specHelper.preloadStatuses(context, statusNames, statusMapping); + specHelper.preloadShopProductRelations(context, shopProductRelationMapper); + + StringBuilder errorMessages = new StringBuilder(); + + for (int i = 0; i < records.size(); i++) { + CSVRecord record = records.get(i); + int rowNumber = i + 2; + + try { + CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, + task.getShopId(), context.getCompanyId(), context.getCreateBy(), context); + + queueShopProductRelation(orderDTO, context); + OrderPO orderPO = buildOrderPO(orderDTO, context.getCompanyId(), + context.getCreateBy(), task.getId(), context); + + StringBuilder updateMsg = new StringBuilder(); + if (orderDTO.getExistingOrderId() != null) { + updateMsg.append(String.format("平台订单号 %s 已更新", orderDTO.getPlatformOrderNo())); + } + + boolean isDuplicate = validatePlatformOrderNo( + orderDTO.getPlatformOrderNo(), context, orderPO, + rowNumber, orderPO.getId(), updateMsg); + + if (!isDuplicate) { + ImportRuntimeContext.PendingOrderInsert pending = + new ImportRuntimeContext.PendingOrderInsert( + rowNumber, orderDTO.getPlatformOrderNo(), orderPO, + orderPO.getId(), updateMsg); + context.pendingOrders.add(pending); + if (orderDTO.getPlatformOrderNo() != null + && !orderDTO.getPlatformOrderNo().trim().isEmpty()) { + context.pendingOrderByPlatformNo.put( + orderDTO.getPlatformOrderNo().trim(), pending); + } + } + + if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) { + flushPendingRelations(context); + } + if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) { + int[] r = flushPendingOrders(context, errorMessages); + result.successCount += r[0]; + result.failCount += r[1]; + result.insertCount += r[0]; + result.updateCount += r[2]; + } + + } catch (Exception e) { + result.failCount++; + errorMessages.append(String.format("第%d行:%s", rowNumber, e.getMessage())) + .append(System.lineSeparator()); + } + + if ((i + 1) % 1000 == 0 || (i + 1) == records.size()) { + result.successCount = i + 1 - result.failCount; + if (progressCallback != null) { + progressCallback.accept(result.totalCount, result.successCount); + } + } + } + + // 最终 flush + int[] r = flushPendingOrders(context, errorMessages); + result.successCount += r[0]; + result.failCount += r[1]; + result.insertCount += r[0]; + result.updateCount += r[2]; + flushPendingRelations(context); + + result.errorMessages = errorMessages; + + } catch (Exception e) { + throw new BusinessException("CSV解析失败: " + e.getMessage()); + } + + return result; + } + + // ==================== CSV 解析 ==================== + + private CreateOrderDTO parseOrderFromCSV(CSVRecord record, + Map fieldMapping, + Map statusMapping, + Long shopId, Long companyId, Long createBy, + ImportRuntimeContext context) { + CreateOrderDTO dto = new CreateOrderDTO(); + dto.setShopId(shopId); + + ImportRuntimeContext.MappingField platformOrderNoField = fieldMapping.get("platform_order_no"); + if (platformOrderNoField != null) { + String pon = getValue(record, platformOrderNoField); + if (pon != null && !pon.trim().isEmpty()) { + dto.setPlatformOrderNo(pon.trim()); + } + } + + ImportRuntimeContext.MappingField statusField = fieldMapping.get("status"); + if (statusField != null) { + String statusStr = getValue(record, statusField); + if (statusStr != null && !statusStr.trim().isEmpty()) { + Long statusId = statusMapping.get(statusStr.trim()); + if (statusId != null) { + dto.setStatusId(statusId); + } else { + Long id = specHelper.findOrderStatusIdByName( + context.getCompanyId(), statusStr, context); + if (id != null) { + dto.setStatusId(id); + } else { + id = specHelper.createOrderStatusIfNotExists( + context.getCompanyId(), statusStr, createBy, context); + dto.setStatusId(id); + } + } + } + } + + ImportRuntimeContext.MappingField specCodeField = fieldMapping.get("spec_code"); + ImportRuntimeContext.MappingField productCodeField = fieldMapping.get("product_code"); + ImportRuntimeContext.MappingField linkProductNameField = fieldMapping.get("link_product_name"); + ImportRuntimeContext.MappingField quantityField = fieldMapping.get("quantity"); + ImportRuntimeContext.MappingField unitPriceField = fieldMapping.get("unit_price"); + ImportRuntimeContext.MappingField productCostField = fieldMapping.get("product_cost"); + ImportRuntimeContext.MappingField shippingCostField = fieldMapping.get("shipping_cost"); + ImportRuntimeContext.MappingField otherCostField = fieldMapping.get("other_cost"); + ImportRuntimeContext.MappingField receivedAmountField = fieldMapping.get("received_amount"); + ImportRuntimeContext.MappingField orderDateField = fieldMapping.get("order_date"); + + String specCode = getValue(record, specCodeField); + if (specCode == null || specCode.trim().isEmpty()) { + 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, receivedAmountField); + if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) + && receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) { + throw new BusinessException("商家实收金额不能为空"); + } + + String productQuantityStr = getValue(record, quantityField); + if ((productQuantityStr == null || productQuantityStr.trim().isEmpty()) + && quantityField != null && quantityField.getRequired() != null && quantityField.getRequired()) { + throw new BusinessException("商品数量不能为空"); + } + + // 解析必填字段 + if (receivedAmountStr != null && !receivedAmountStr.trim().isEmpty()) { + try { + dto.setReceivedAmount(new BigDecimal(receivedAmountStr.trim())); + } catch (NumberFormatException e) { + throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr); + } + } else if (receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) { + throw new BusinessException("商家实收金额不能为空"); + } + + if (productQuantityStr != null && !productQuantityStr.trim().isEmpty()) { + try { + dto.setQuantity(Integer.parseInt(productQuantityStr.trim())); + if (dto.getQuantity() <= 0) { + throw new BusinessException("商品数量必须大于0"); + } + } catch (NumberFormatException e) { + throw new BusinessException("商品数量格式错误: " + productQuantityStr); + } + } else if (quantityField != null && quantityField.getRequired() != null && quantityField.getRequired()) { + throw new BusinessException("商品数量不能为空"); + } + + // 解析可选字段 + String productCode = getValue(record, productCodeField); + if (productCode != null && productCode.trim().isEmpty()) productCode = null; + String linkProductName = getValue(record, linkProductNameField); + if (linkProductName != null) { + linkProductName = linkProductName.trim(); + if (linkProductName.isEmpty()) linkProductName = null; + } + String linkSpecName = getValue(record, fieldMapping.get("link_spec_name")); + if (linkSpecName != null) { + linkSpecName = linkSpecName.trim(); + if (linkSpecName.isEmpty()) linkSpecName = null; + } + + // 商品/规格解析 + if (specCode == null && productCode == null && linkProductName == null) { + throw new BusinessException("商品信息为空(商品编码/规格编码/商品名称至少要填一个)"); + } + + ProductSpecPO productSpec = null; + boolean isNewSpecCreated = false; + if (specCode != null && !specCode.trim().isEmpty()) { + productSpec = specHelper.findProductSpecBySpecCode(specCode, companyId, context); + } + + if (productSpec == null) { + top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product = null; + if (productCode != null && !productCode.isEmpty()) { + product = specHelper.findProductByProductCode(productCode, companyId, context); + } + if (product == null && linkProductName != null && !linkProductName.isEmpty()) { + product = specHelper.findProductByName(linkProductName, companyId, context); + } + if (product != null) { + String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格"; + productSpec = specHelper.createSpecForProduct(companyId, product.getId(), finalSpecName, + specCode != null ? specCode.trim() : null, createBy, context); + isNewSpecCreated = true; + } else { + String finalProductName = (linkProductName != null && !linkProductName.isEmpty()) ? linkProductName : "未知商品"; + String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格"; + productSpec = specHelper.createProductAndSpecIfNotExists( + companyId, finalProductName, productCode, finalSpecName, + specCode != null ? specCode.trim() : null, + createBy, context); + isNewSpecCreated = true; + } + } + + if (productSpec == null) { + throw new BusinessException("无法创建商品规格"); + } + + dto.setProductId(productSpec.getProductId()); + dto.setProductSpecId(productSpec.getId()); + + // 设置单件成本(从商品规格中获取,作为下单时快照) + dto.setProductCost(productSpec.getProductCost() != null ? productSpec.getProductCost() : BigDecimal.ZERO); + dto.setShippingCost(productSpec.getShippingCost() != null ? productSpec.getShippingCost() : BigDecimal.ZERO); + dto.setOtherCost(productSpec.getOtherCost() != null ? productSpec.getOtherCost() : BigDecimal.ZERO); + + // 链接商品名称:优先使用CSV中的值,否则 fallback 到商品名称 + if (linkProductName != null && !linkProductName.isEmpty()) { + dto.setLinkProductName(linkProductName); + } else { + top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO product = + specHelper.getProductById(productSpec.getProductId(), context); + dto.setLinkProductName(product != null ? product.getName() : "未知商品"); + } + + // 链接规格名称:优先使用CSV中的值,否则 fallback 到规格名称 + if (linkSpecName != null && !linkSpecName.isEmpty()) { + dto.setLinkSpecName(linkSpecName); + } else { + dto.setLinkSpecName(productSpec.getName()); + } + + // 如果创建了新规格,订单的确认状态设为0;否则设为1 + dto.setConfirm(isNewSpecCreated ? 0 : 1); + + // 数量 + if (quantityField != null) { + String qtyStr = getValue(record, quantityField); + if (qtyStr != null && !qtyStr.trim().isEmpty()) { + try { + dto.setQuantity(Integer.parseInt(qtyStr.trim())); + } catch (NumberFormatException e) { + throw new BusinessException("数量格式错误: " + qtyStr); + } + } + } + + // 单价 + if (unitPriceField != null) { + String priceStr = getValue(record, unitPriceField); + if (priceStr != null && !priceStr.trim().isEmpty()) { + dto.setUnitPrice(new BigDecimal(priceStr.trim())); + } + } + + // 商品成本:优先使用 CSV 字段值,否则用规格中的快照值 + if (productCostField != null) { + String costStr = getValue(record, productCostField); + if (costStr != null && !costStr.trim().isEmpty()) { + dto.setProductCost(new BigDecimal(costStr.trim())); + } + } + + // 运费 + if (shippingCostField != null) { + String shippingStr = getValue(record, shippingCostField); + if (shippingStr != null && !shippingStr.trim().isEmpty()) { + dto.setShippingCost(new BigDecimal(shippingStr.trim())); + } + } + + // 其他成本 + if (otherCostField != null) { + String otherStr = getValue(record, otherCostField); + if (otherStr != null && !otherStr.trim().isEmpty()) { + dto.setOtherCost(new BigDecimal(otherStr.trim())); + } + } + + // 实收金额 + if (receivedAmountField != null) { + String receivedStr = getValue(record, receivedAmountField); + if (receivedStr != null && !receivedStr.trim().isEmpty()) { + dto.setReceivedAmount(new BigDecimal(receivedStr.trim())); + } + } + + // 订单日期 + if (orderDateField != null) { + String dateStr = getValue(record, orderDateField); + if (dateStr != null && !dateStr.trim().isEmpty()) { + LocalDateTime dateTime = parseDateTime(dateStr, context); + if (dateTime != null) { + dto.setOrderTime(dateTime); + } else { + dto.setOrderTime(LocalDateTime.now()); + } + } else { + dto.setOrderTime(LocalDateTime.now()); + } + } else { + dto.setOrderTime(LocalDateTime.now()); + } + + return dto; + } + + private LocalDateTime parseDateTime(String dateTimeStr, ImportRuntimeContext context) { + if (dateTimeStr == null || dateTimeStr.trim().isEmpty()) return null; + String trimmed = dateTimeStr.trim(); + + if (context != null && context.getDetectedDatePattern() != null) { + try { + ImportRuntimeContext.DateTimeFormatPattern p = context.getDetectedDatePattern(); + if (p.hasTime) { + return LocalDateTime.parse(trimmed, p.formatter); + } else { + return LocalDate.parse(trimmed, p.formatter).atStartOfDay(); + } + } catch (DateTimeParseException ignored) {} + } + + ImportRuntimeContext.DateTimeFormatPattern[] patterns = { + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/MM/dd HH:mm:ss", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-MM-dd HH:mm:ss", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/M/d H:m:s", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-M-d H:m:s", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/MM/dd HH:mm", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-MM-dd HH:mm", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/M/d H:m", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-M-d H:m", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日 HH:mm:ss", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日 HH:mm", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年M月d日 H:m:s", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年M月d日 H:m", true), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/MM/dd", false), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-MM-dd", false), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy/M/d", false), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy-M-d", false), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日", false), + new ImportRuntimeContext.DateTimeFormatPattern("yyyy年M月d日", false) + }; + + for (ImportRuntimeContext.DateTimeFormatPattern pattern : patterns) { + try { + if (pattern.hasTime) { + return LocalDateTime.parse(trimmed, pattern.formatter); + } else { + return LocalDate.parse(trimmed, pattern.formatter).atStartOfDay(); + } + } catch (DateTimeParseException ignored) {} + } + return null; + } + + private ImportRuntimeContext.DateTimeFormatPattern detectDateFormat(String dateStr) { + if (dateStr.contains("/")) { + if (dateStr.contains(":")) return new ImportRuntimeContext.DateTimeFormatPattern("yyyy/MM/dd HH:mm:ss", true); + if (dateStr.contains("年")) return new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日", false); + return new ImportRuntimeContext.DateTimeFormatPattern("yyyy/MM/dd", false); + } + if (dateStr.contains("-")) { + if (dateStr.contains(":")) return new ImportRuntimeContext.DateTimeFormatPattern("yyyy-MM-dd HH:mm:ss", true); + if (dateStr.contains("年")) return new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日", false); + return new ImportRuntimeContext.DateTimeFormatPattern("yyyy-MM-dd", false); + } + if (dateStr.contains("年")) return new ImportRuntimeContext.DateTimeFormatPattern("yyyy年MM月dd日", false); + return null; + } + + private String getValue(CSVRecord record, ImportRuntimeContext.MappingField mappingField) { + if (mappingField == null || mappingField.getFileFieldName() == null + || mappingField.getFileFieldName().trim().isEmpty()) { + return null; + } + try { + String val = record.get(mappingField.getFileFieldName()); + return (val != null && !val.trim().isEmpty()) ? val.trim() : null; + } catch (IllegalArgumentException e) { + return null; + } + } + + private String getValue(CSVRecord record, String header) { + if (header == null || header.trim().isEmpty()) return null; + try { + String val = record.get(header.trim()); + return (val != null && !val.trim().isEmpty()) ? val.trim() : null; + } catch (IllegalArgumentException e) { + return null; + } + } + + private String removeBOM(String s) { + if (s == null) return null; + if (s.startsWith("\uFEFF")) return s.substring(1); + return s; + } + + // ==================== 订单构建 ==================== + + private OrderPO buildOrderPO(CreateOrderDTO dto, Long companyId, Long createBy, + Long importTaskId, ImportRuntimeContext context) { + OrderPO order = new OrderPO(); + order.setCompanyId(companyId); + order.setShopId(dto.getShopId()); + order.setPlatformOrderNo(dto.getPlatformOrderNo()); + order.setStatusId(dto.getStatusId()); + order.setProductId(dto.getProductId()); + order.setProductSpecId(dto.getProductSpecId()); + order.setLinkProductName(dto.getLinkProductName()); + order.setLinkSpecName(dto.getLinkSpecName()); + order.setQuantity(dto.getQuantity()); + order.setUnitPrice(dto.getUnitPrice()); + order.setProductCost(dto.getProductCost()); + order.setShippingCost(dto.getShippingCost()); + order.setOtherCost(dto.getOtherCost()); + order.setReceivedAmount(dto.getReceivedAmount()); + order.setOrderTime(dto.getOrderTime()); + order.setCreateBy(createBy); + order.setImportTaskId(importTaskId); + order.setConfirm(dto.getConfirm() != null ? dto.getConfirm() : 1); + if (context != null && dto.getPlatformOrderNo() != null) { + String normalized = dto.getPlatformOrderNo().trim(); + if (context.existingOrderIdByPlatformNo.containsKey(normalized)) { + order.setId(context.existingOrderIdByPlatformNo.get(normalized)); + } + } + return order; + } + + // ==================== 平台订单号校验 ==================== + + private boolean validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context, + OrderPO newOrderPO, int newRowNumber, + Long newExistingOrderId, StringBuilder newUpdateMsg) { + if (platformOrderNo == null || platformOrderNo.trim().isEmpty()) return false; + String normalized = platformOrderNo.trim(); + + Long existingId = newExistingOrderId; + if (existingId == null && context.existingOrderIdByPlatformNo.containsKey(normalized)) { + existingId = context.existingOrderIdByPlatformNo.get(normalized); + } + + if (context.pendingPlatformOrderNos.contains(normalized)) { + ImportRuntimeContext.PendingOrderInsert existing = + context.pendingOrderByPlatformNo.get(normalized); + if (existing != null) { + existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber); + } + return true; + } + + context.pendingPlatformOrderNos.add(normalized); + return false; + } + + // ==================== 关系队列 ==================== + + private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) { + String relationKey = context.buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId()); + if (context.existingRelationKeys.contains(relationKey) + || context.pendingRelationKeys.contains(relationKey)) { + return; + } + ShopProductRelationPO relation = new ShopProductRelationPO(); + relation.setCompanyId(context.getCompanyId()); + relation.setShopId(orderDTO.getShopId()); + relation.setProductId(orderDTO.getProductId()); + relation.setSortOrder(0); + relation.setCreateBy(context.getCreateBy()); + context.pendingRelations.add(relation); + context.pendingRelationKeys.add(relationKey); + } + + // ==================== 批量 flush ==================== + + private int[] flushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) { + if (context.pendingOrders.isEmpty()) { + return new int[] {0, 0, 0, 0}; + } + int insertSuccess = 0, insertFail = 0, updateSuccess = 0, updateFail = 0; + List batch = + new ArrayList<>(context.pendingOrders); + + List inserts = new ArrayList<>(); + List updates = new ArrayList<>(); + for (ImportRuntimeContext.PendingOrderInsert p : batch) { + (p.existingOrderId != null ? updates : inserts).add(p); + } + + if (!inserts.isEmpty()) { + int[] r = doBatchInsert(inserts, context, errorMessages); + insertSuccess += r[0]; + insertFail += r[1]; + } + + for (ImportRuntimeContext.PendingOrderInsert p : updates) { + try { + orderMapper.updateById(p.order); + updateSuccess++; + if (p.updateMessages != null && p.updateMessages.length() > 0) { + errorMessages.append(String.format("[更新] 第%d行:%s", + p.rowNumber, p.updateMessages.toString())) + .append(System.lineSeparator()); + } + if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) { + String normalized = p.platformOrderNo.trim(); + context.pendingPlatformOrderNos.remove(normalized); + context.existingPlatformOrderNos.add(normalized); + } + } catch (Exception e) { + updateFail++; + errorMessages.append(String.format("[失败] 第%d行:更新失败 %s", + p.rowNumber, e.getMessage())) + .append(System.lineSeparator()); + } + } + + context.pendingOrders.clear(); + return new int[] {insertSuccess, insertFail, updateSuccess, updateFail}; + } + + private int[] doBatchInsert(List inserts, + ImportRuntimeContext context, StringBuilder errorMessages) { + int success = 0, fail = 0; + try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { + OrderMapper batchMapper = session.getMapper(OrderMapper.class); + for (ImportRuntimeContext.PendingOrderInsert p : inserts) { + batchMapper.insert(p.order); + } + session.flushStatements(); + session.commit(); + success += inserts.size(); + for (ImportRuntimeContext.PendingOrderInsert p : inserts) { + if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) { + String normalized = p.platformOrderNo.trim(); + context.pendingPlatformOrderNos.remove(normalized); + context.existingPlatformOrderNos.add(normalized); + } + } + } catch (Exception e) { + for (ImportRuntimeContext.PendingOrderInsert p : inserts) { + try { + orderMapper.insert(p.order); + success++; + if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) { + String normalized = p.platformOrderNo.trim(); + context.pendingPlatformOrderNos.remove(normalized); + context.existingPlatformOrderNos.add(normalized); + } + } catch (Exception singleEx) { + fail++; + if (p.platformOrderNo != null) { + context.pendingPlatformOrderNos.remove(p.platformOrderNo.trim()); + } + errorMessages.append(String.format("第%d行:%s", + p.rowNumber, singleEx.getMessage())) + .append(System.lineSeparator()); + } + } + } + return new int[] {success, fail}; + } + + private void flushPendingRelations(ImportRuntimeContext context) { + if (context.pendingRelations.isEmpty()) return; + List batch = new ArrayList<>(context.pendingRelations); + try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) { + ShopProductRelationMapper batchMapper = session.getMapper(ShopProductRelationMapper.class); + for (ShopProductRelationPO relation : batch) { + batchMapper.insert(relation); + } + session.flushStatements(); + session.commit(); + for (ShopProductRelationPO relation : batch) { + context.existingRelationKeys.add( + context.buildRelationKey(relation.getShopId(), relation.getProductId())); + } + } catch (Exception e) { + for (ShopProductRelationPO relation : batch) { + try { + shopProductRelationMapper.insert(relation); + context.existingRelationKeys.add( + context.buildRelationKey(relation.getShopId(), relation.getProductId())); + } catch (Exception ignored) {} + } + } finally { + context.pendingRelations.clear(); + context.pendingRelationKeys.clear(); + } + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java new file mode 100644 index 00000000..dd001c9c --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ProductSpecImportHelper.java @@ -0,0 +1,405 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import top.xyquan.ecomdmbbackend.common.exception.BusinessException; +import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; +import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService; +import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; +import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO; +import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO; + +import java.math.BigDecimal; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 商品/规格查找与创建辅助类 + *

+ * 职责: + * - 商品/规格/状态缓存查找 + * - 商品/规格/状态创建 + * - 预加载(填充 ImportRuntimeContext) + */ +public class ProductSpecImportHelper { + + private static final int IN_QUERY_BATCH_SIZE = 1000; + + private final ProductMapper productMapper; + private final ProductSpecService productSpecService; + private final OrderStatusService orderStatusService; + private final ShopProductRelationMapper shopProductRelationMapper; + + public ProductSpecImportHelper(ProductMapper productMapper, + ProductSpecService productSpecService, + OrderStatusService orderStatusService, + ShopProductRelationMapper shopProductRelationMapper) { + this.productMapper = productMapper; + this.productSpecService = productSpecService; + this.orderStatusService = orderStatusService; + this.shopProductRelationMapper = shopProductRelationMapper; + } + + // ==================== 缓存查找 ==================== + + public ProductSpecPO findProductSpecBySpecCode(String specCode, Long companyId, + ImportRuntimeContext context) { + if (specCode == null || specCode.trim().isEmpty()) return null; + return context.specByCodeCache.get(specCode.trim()); + } + + public ProductPO findProductByProductCode(String productCode, Long companyId, + ImportRuntimeContext context) { + if (productCode == null || productCode.trim().isEmpty()) return null; + return context.productByCodeCache.get(productCode.trim()); + } + + public ProductPO findProductByName(String productName, Long companyId, + ImportRuntimeContext context) { + if (productName == null || productName.trim().isEmpty()) return null; + return context.productByNameCache.get(productName.trim()); + } + + // ==================== 商品/规格创建 ==================== + + /** + * 根据已知商品创建规格(跳过 selectById) + */ + public ProductSpecPO createSpecForProduct(ProductPO product, String specCode, String specName, + BigDecimal productCost, Long companyId, + Long createBy, ImportRuntimeContext context) { + if (product == null) { + throw new BusinessException("商品不能为空"); + } + + String trimmedCode = specCode != null ? specCode.trim() : null; + String trimmedName = specName != null ? specName.trim() : null; + + // 检查缓存 + if (trimmedCode != null) { + ProductSpecPO existing = context.specByCodeCache.get(trimmedCode); + if (existing != null) return existing; + } + + // 创建规格 + ProductSpecPO spec = new ProductSpecPO(); + spec.setProductId(product.getId()); + spec.setCompanyId(companyId); + spec.setSpecCode(trimmedCode); + spec.setName(trimmedName != null ? trimmedName : (trimmedCode != null ? trimmedCode : "未知规格")); + spec.setProductCost(productCost != null ? productCost : BigDecimal.ZERO); + spec.setCreateBy(createBy); + productSpecService.save(spec); + + // 写入缓存 + if (trimmedCode != null) { + context.specByCodeCache.put(trimmedCode, spec); + } + return spec; + } + + /** + * 查找或创建商品,再查找或创建规格 + */ + public ProductSpecPO createProductAndSpecIfNotExists(String productCode, String productName, + String specCode, String specName, + BigDecimal productCost, Long companyId, + Long createBy, ImportRuntimeContext context) { + ProductPO product; + String trimmedCode = productCode != null ? productCode.trim() : null; + String trimmedName = productName != null ? productName.trim() : null; + + if (trimmedCode != null && !trimmedCode.isEmpty()) { + product = findProductByProductCode(trimmedCode, companyId, context); + } else if (trimmedName != null && !trimmedName.isEmpty()) { + product = findProductByName(trimmedName, companyId, context); + } else { + throw new BusinessException("商品编码和商品名称不能同时为空"); + } + + if (product == null) { + product = new ProductPO(); + product.setCompanyId(companyId); + product.setProductCode(trimmedCode); + product.setName(trimmedName != null ? trimmedName : (trimmedCode != null ? trimmedCode : "未知商品")); + product.setCreateBy(createBy); + productMapper.insert(product); + cacheProduct(context, product); + } + + return createSpecForProduct(product, specCode, specName, productCost, companyId, createBy, context); + } + + /** + * 根据规格编码查找规格,找不到则按"编码创建规格/无编码返回空"逻辑处理 + */ + public ProductSpecPO createSpecForProduct(String productCode, String productName, + String specCode, String specName, + BigDecimal productCost, Long companyId, + Long createBy, ImportRuntimeContext context) { + String trimmedSpecCode = specCode != null ? specCode.trim() : null; + if (trimmedSpecCode != null && !trimmedSpecCode.isEmpty()) { + ProductSpecPO existing = findProductSpecBySpecCode(trimmedSpecCode, companyId, context); + if (existing != null) return existing; + return createProductAndSpecIfNotExists(productCode, productName, specCode, specName, + productCost, companyId, createBy, context); + } + return null; + } + + public ProductSpecPO createSpecForProductWithValidation(String productCode, String productName, + String specCode, String specName, + BigDecimal productCost, Long companyId, + Long createBy, ImportRuntimeContext context) { + String trimmedSpecCode = specCode != null ? specCode.trim() : null; + String trimmedSpecName = specName != null ? specName.trim() : null; + + if (trimmedSpecCode == null || trimmedSpecCode.isEmpty()) { + throw new BusinessException("规格编码不能为空"); + } + if (trimmedSpecName == null || trimmedSpecName.isEmpty()) { + throw new BusinessException("规格名称不能为空"); + } + + ProductSpecPO existing = findProductSpecBySpecCode(trimmedSpecCode, companyId, context); + if (existing != null) return existing; + + return createProductAndSpecIfNotExists(productCode, productName, specCode, specName, + productCost, companyId, createBy, context); + } + + /** 旧签名(兼容旧版调用) */ + public ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, + String specCode, Long createBy, + ImportRuntimeContext context) { + ProductPO product = getProductById(productId, context); + if (product == null || !product.getCompanyId().equals(companyId)) { + throw new BusinessException("商品不存在"); + } + return createSpecForProductWithValidation(null, null, specCode, specName, + null, companyId, createBy, context); + } + + /** 旧签名(兼容旧版调用):参数顺序 companyId, productName, productCode, specName, specCode */ + public ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName, + String productCode, String specName, + String specCode, Long createBy, + ImportRuntimeContext context) { + // 1. 通过商品名称查找商品 + LambdaQueryWrapper productWrapper = + new LambdaQueryWrapper<>(); + productWrapper.eq(ProductPO::getName, productName) + .eq(ProductPO::getCompanyId, companyId); + ProductPO product = productMapper.selectOne(productWrapper); + + Long productId; + if (product == null) { + // 双重检查(避免并发问题) + LambdaQueryWrapper checkWrapper = new LambdaQueryWrapper<>(); + checkWrapper.eq(ProductPO::getName, productName) + .eq(ProductPO::getCompanyId, companyId); + if (productMapper.selectCount(checkWrapper) > 0) { + product = productMapper.selectOne(productWrapper); + productId = product.getId(); + } else { + product = new ProductPO(); + product.setCompanyId(companyId); + product.setName(productName); + product.setLinkName(productName); + String trimmedCode = productCode != null ? productCode.trim() : null; + if (trimmedCode != null && !trimmedCode.isEmpty()) { + LambdaQueryWrapper codeCheckWrapper = new LambdaQueryWrapper<>(); + codeCheckWrapper.eq(ProductPO::getProductCode, trimmedCode) + .eq(ProductPO::getCompanyId, companyId); + if (productMapper.selectCount(codeCheckWrapper) > 0) { + throw new BusinessException("商品编码已存在: " + trimmedCode); + } + product.setProductCode(trimmedCode); + } + product.setCreateBy(createBy); + productMapper.insert(product); + productId = product.getId(); + } + } else { + productId = product.getId(); + } + + // 写入缓存 + context.productByIdCache.put(productId, product); + if (product.getName() != null) { + context.productByNameCache.put(product.getName(), product); + } + if (product.getProductCode() != null) { + context.productByCodeCache.put(product.getProductCode(), product); + } + + // 2. 创建规格(使用原有 ProductPO 重载,保持逻辑一致) + return createSpecForProduct(product, specCode, specName, null, companyId, createBy, context); + } + + public ProductPO getProductById(Long productId, ImportRuntimeContext context) { + ProductPO cached = context.productByIdCache.get(productId); + if (cached != null) return cached; + ProductPO product = productMapper.selectById(productId); + if (product != null) cacheProduct(context, product); + return product; + } + + public void cacheProduct(ImportRuntimeContext context, ProductPO product) { + context.productByIdCache.put(product.getId(), product); + if (product.getName() != null) { + context.productByNameCache.put(product.getName(), product); + } + if (product.getProductCode() != null) { + context.productByCodeCache.put(product.getProductCode(), product); + } + } + + // ==================== 订单状态 ==================== + + public Long findOrderStatusIdByName(Long companyId, String statusName, + ImportRuntimeContext context) { + if (statusName == null || statusName.trim().isEmpty()) return null; + String trimmed = statusName.trim(); + if (context.statusIdByNameCache.containsKey(trimmed)) { + return context.statusIdByNameCache.get(trimmed); + } + LambdaQueryWrapper wrapper = + new LambdaQueryWrapper<>(); + wrapper.eq(top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO::getCompanyId, companyId) + .eq(top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO::getStatusName, trimmed); + top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO status = + orderStatusService.getOne(wrapper); + if (status != null) { + context.statusIdByNameCache.put(trimmed, status.getId()); + return status.getId(); + } + return null; + } + + public Long createOrderStatusIfNotExists(Long companyId, String statusName, + Long createBy, ImportRuntimeContext context) { + if (statusName == null || statusName.trim().isEmpty()) { + throw new BusinessException("订单状态名称不能为空"); + } + String trimmed = statusName.trim(); + + Long existingId = findOrderStatusIdByName(companyId, trimmed, context); + if (existingId != null) return existingId; + + top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO orderStatus = + new top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO(); + orderStatus.setCompanyId(companyId); + orderStatus.setStatusName(trimmed); + orderStatus.setDescription("自动创建的状态"); + orderStatus.setSortOrder(0); + orderStatus.setAutoStatistics(1); + orderStatus.setCreateBy(createBy); + orderStatusService.save(orderStatus); + + context.statusIdByNameCache.put(trimmed, orderStatus.getId()); + return orderStatus.getId(); + } + + // ==================== 预加载 ==================== + + public void preloadProductSpecs(ImportRuntimeContext context, Set specCodes) { + for (List chunk : ImportRuntimeContext.splitToChunks(specCodes, IN_QUERY_BATCH_SIZE)) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductSpecPO::getCompanyId, context.getCompanyId()) + .in(ProductSpecPO::getSpecCode, chunk); + for (ProductSpecPO spec : productSpecService.list(wrapper)) { + context.specByCodeCache.put(spec.getSpecCode(), spec); + } + } + } + + public void preloadProductsByCode(ImportRuntimeContext context, Set productCodes) { + for (List chunk : ImportRuntimeContext.splitToChunks(productCodes, IN_QUERY_BATCH_SIZE)) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductPO::getCompanyId, context.getCompanyId()) + .in(ProductPO::getProductCode, chunk); + for (ProductPO product : productMapper.selectList(wrapper)) { + cacheProduct(context, product); + } + } + } + + public void preloadProductsByName(ImportRuntimeContext context, Set productNames) { + for (List chunk : ImportRuntimeContext.splitToChunks(productNames, IN_QUERY_BATCH_SIZE)) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ProductPO::getCompanyId, context.getCompanyId()) + .in(ProductPO::getName, chunk); + for (ProductPO product : productMapper.selectList(wrapper)) { + cacheProduct(context, product); + } + } + } + + public void preloadStatuses(ImportRuntimeContext context, Set statusNames, + Map statusMapping) { + if (statusMapping != null) { + context.statusIdByNameCache.putAll(statusMapping); + } + for (List chunk : ImportRuntimeContext.splitToChunks(statusNames, IN_QUERY_BATCH_SIZE)) { + LambdaQueryWrapper wrapper = + new LambdaQueryWrapper<>(); + wrapper.eq(top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO::getCompanyId, + context.getCompanyId()) + .in(top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO::getStatusName, chunk); + for (top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO status : + orderStatusService.list(wrapper)) { + context.statusIdByNameCache.put(status.getStatusName(), status.getId()); + } + } + } + + public void preloadPlatformOrderNos(ImportRuntimeContext context, Set platformOrderNos, + OrderMapper orderMapper) { + for (List chunk : ImportRuntimeContext.splitToChunks(platformOrderNos, IN_QUERY_BATCH_SIZE)) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(OrderPO::getCompanyId, context.getCompanyId()) + .in(OrderPO::getPlatformOrderNo, chunk) + .select(OrderPO::getId, OrderPO::getPlatformOrderNo); + for (OrderPO order : orderMapper.selectList(wrapper)) { + if (order.getPlatformOrderNo() != null) { + String normalized = order.getPlatformOrderNo().trim(); + context.existingPlatformOrderNos.add(normalized); + context.existingOrderIdByPlatformNo.put(normalized, order.getId()); + } + } + } + } + + public void preloadShopProductRelations(ImportRuntimeContext context, + ShopProductRelationMapper shopProductRelationMapper) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ShopProductRelationPO::getCompanyId, context.getCompanyId()) + .eq(ShopProductRelationPO::getShopId, context.getShopId()) + .select(ShopProductRelationPO::getProductId); + for (ShopProductRelationPO relation : shopProductRelationMapper.selectList(wrapper)) { + context.existingRelationKeys.add(context.buildRelationKey(context.getShopId(), relation.getProductId())); + } + } + + public void ensureShopProductRelation(Long shopId, Long productId, Long companyId, Long createBy) { + LambdaQueryWrapper wrapper = new LambdaQueryWrapper<>(); + wrapper.eq(ShopProductRelationPO::getShopId, shopId) + .eq(ShopProductRelationPO::getProductId, productId) + .eq(ShopProductRelationPO::getCompanyId, companyId); + ShopProductRelationPO existing = shopProductRelationMapper.selectOne(wrapper); + if (existing == null) { + ShopProductRelationPO relation = new ShopProductRelationPO(); + relation.setCompanyId(companyId); + relation.setShopId(shopId); + relation.setProductId(productId); + relation.setSortOrder(0); + relation.setCreateBy(createBy); + shopProductRelationMapper.insert(relation); + } + } +}