mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
refactor: 拆出 OrderImportProcessor/ProductSpecImportHelper/ImportRuntimeContext,修复导入逻辑bug
- ImportRuntimeContext: 抽取共享类型和上下文字段(内部类、缓存集合) - OrderImportProcessor: 拆出CSV解析、商品/规格查找、订单构建、批量flush逻辑 - ProductSpecImportHelper: 拆出商品/规格/状态查找与创建、预加载逻辑 - ImportTaskProcessorServiceImplImpl: 保留流程编排和任务状态管理 BUG修复: - link_product_name为空时fallback到商品名称 - link_spec_name为空时fallback到规格名称 - 新建规格时confirm设为0 - productCost/shippingCost/otherCost优先从CSV覆盖规格快照 - orderDate为空时fallback到当前时间 - 修复ProductSpecImportHelper中specName/specCode参数顺序错误 - 兼容旧签名createSpecForProduct/createProductAndSpecIfNotExists
This commit is contained in:
+194
@@ -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.*;
|
||||
|
||||
/**
|
||||
* 导入运行时上下文(贯穿整个导入过程)
|
||||
* <p>
|
||||
* 所有共享类型(内部类/枚举)也定义在此文件,避免循环依赖。
|
||||
*/
|
||||
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<MappingField> fieldMapping;
|
||||
private List<StatusMapping> statusMapping;
|
||||
|
||||
public MappingConfig() {}
|
||||
|
||||
public List<MappingField> getFieldMapping() { return fieldMapping; }
|
||||
public void setFieldMapping(List<MappingField> fieldMapping) { this.fieldMapping = fieldMapping; }
|
||||
public List<StatusMapping> getStatusMapping() { return statusMapping; }
|
||||
public void setStatusMapping(List<StatusMapping> 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<String, ProductSpecPO> specByCodeCache = new HashMap<>();
|
||||
final Map<String, ProductPO> productByCodeCache = new HashMap<>();
|
||||
final Map<String, ProductPO> productByNameCache = new HashMap<>();
|
||||
final Map<Long, ProductPO> productByIdCache = new HashMap<>();
|
||||
final Map<String, Long> statusIdByNameCache = new HashMap<>();
|
||||
final Set<String> existingPlatformOrderNos = new HashSet<>();
|
||||
final Map<String, Long> existingOrderIdByPlatformNo = new HashMap<>();
|
||||
final Set<String> existingRelationKeys = new HashSet<>();
|
||||
final List<PendingOrderInsert> pendingOrders = new ArrayList<>();
|
||||
final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = new HashMap<>();
|
||||
final List<ShopProductRelationPO> pendingRelations = new ArrayList<>();
|
||||
final Set<String> pendingRelationKeys = new HashSet<>();
|
||||
final Set<String> 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<String, ProductSpecPO> getSpecByCodeCache() { return specByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByCodeCache() { return productByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByNameCache() { return productByNameCache; }
|
||||
public Map<Long, ProductPO> getProductByIdCache() { return productByIdCache; }
|
||||
public Map<String, Long> getStatusIdByNameCache() { return statusIdByNameCache; }
|
||||
public Set<String> getExistingPlatformOrderNos() { return existingPlatformOrderNos; }
|
||||
public Map<String, Long> getExistingOrderIdByPlatformNo() { return existingOrderIdByPlatformNo; }
|
||||
public Set<String> getExistingRelationKeys() { return existingRelationKeys; }
|
||||
public List<PendingOrderInsert> getPendingOrders() { return pendingOrders; }
|
||||
public Map<String, PendingOrderInsert> getPendingOrderByPlatformNo() { return pendingOrderByPlatformNo; }
|
||||
public List<ShopProductRelationPO> getPendingRelations() { return pendingRelations; }
|
||||
public Set<String> getPendingRelationKeys() { return pendingRelationKeys; }
|
||||
public Set<String> getPendingPlatformOrderNos() { return pendingPlatformOrderNos; }
|
||||
|
||||
// ==================== 工具方法 ====================
|
||||
|
||||
public void addNormalizedValue(Set<String> 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 <T> List<List<T>> splitToChunks(Set<T> values, int chunkSize) {
|
||||
if (values == null || values.isEmpty()) return Collections.emptyList();
|
||||
List<T> all = new ArrayList<>(values);
|
||||
List<List<T>> 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;
|
||||
}
|
||||
}
|
||||
+98
-1709
File diff suppressed because it is too large
Load Diff
+735
@@ -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;
|
||||
|
||||
/**
|
||||
* 订单导入核心处理器
|
||||
* <p>
|
||||
* 职责: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<String, ImportRuntimeContext.MappingField> fieldMapping,
|
||||
Map<String, Long> statusMapping,
|
||||
ImportRuntimeContext context,
|
||||
BiConsumer<Integer, Integer> 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<String> specCodes = new HashSet<>();
|
||||
Set<String> productCodes = new HashSet<>();
|
||||
Set<String> productNames = new HashSet<>();
|
||||
Set<String> platformOrderNos = new HashSet<>();
|
||||
Set<String> statusNames = new HashSet<>();
|
||||
List<CSVRecord> 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<String, ImportRuntimeContext.MappingField> fieldMapping,
|
||||
Map<String, Long> 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<ImportRuntimeContext.PendingOrderInsert> batch =
|
||||
new ArrayList<>(context.pendingOrders);
|
||||
|
||||
List<ImportRuntimeContext.PendingOrderInsert> inserts = new ArrayList<>();
|
||||
List<ImportRuntimeContext.PendingOrderInsert> 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<ImportRuntimeContext.PendingOrderInsert> 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<ShopProductRelationPO> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
+405
@@ -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;
|
||||
|
||||
/**
|
||||
* 商品/规格查找与创建辅助类
|
||||
* <p>
|
||||
* 职责:
|
||||
* - 商品/规格/状态缓存查找
|
||||
* - 商品/规格/状态创建
|
||||
* - 预加载(填充 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<ProductPO> productWrapper =
|
||||
new LambdaQueryWrapper<>();
|
||||
productWrapper.eq(ProductPO::getName, productName)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
ProductPO product = productMapper.selectOne(productWrapper);
|
||||
|
||||
Long productId;
|
||||
if (product == null) {
|
||||
// 双重检查(避免并发问题)
|
||||
LambdaQueryWrapper<ProductPO> 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<ProductPO> 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<top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO> 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<String> specCodes) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(specCodes, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductSpecPO> 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<String> productCodes) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(productCodes, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductPO> 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<String> productNames) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(productNames, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<ProductPO> 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<String> statusNames,
|
||||
Map<String, Long> statusMapping) {
|
||||
if (statusMapping != null) {
|
||||
context.statusIdByNameCache.putAll(statusMapping);
|
||||
}
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(statusNames, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO> 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<String> platformOrderNos,
|
||||
OrderMapper orderMapper) {
|
||||
for (List<String> chunk : ImportRuntimeContext.splitToChunks(platformOrderNos, IN_QUERY_BATCH_SIZE)) {
|
||||
LambdaQueryWrapper<OrderPO> 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<ShopProductRelationPO> 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<ShopProductRelationPO> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user