feat(order-import): 重复订单改为更新而非报错

当CSV中遇到已存在的平台订单号时:
- 数据库中存在:直接更新该订单
- 同批次内重复:以最后一条数据为准更新

主要变更:
- CreateOrderDTO 新增 existingOrderId 字段用于标记更新操作
- PendingOrderInsert 改为可变,支持覆盖数据
- 新增 pendingOrderByPlatformNo Map 用于快速查找同批次重复
- flushPendingOrders 分离新增和更新操作,分别处理
- validatePlatformOrderNo 内存检查处理同批次重复
- parseOrderFromCSV DB检查找到已存在订单时设置 existingOrderId
This commit is contained in:
小蟑螂
2026-03-29 16:11:06 +08:00
parent 6cbbce5ded
commit 13de7bc55b
2 changed files with 136 additions and 19 deletions
@@ -169,14 +169,29 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private static final int IN_QUERY_BATCH_SIZE = 500;
private static class PendingOrderInsert {
private final int rowNumber;
private final String platformOrderNo;
private final OrderPO order;
private int rowNumber;
private String platformOrderNo;
private OrderPO order;
private Long existingOrderId; // 不为空表示是更新操作
private StringBuilder updateMessages; // 记录更新消息
private PendingOrderInsert(int rowNumber, String platformOrderNo, OrderPO order) {
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;
}
}
}
@@ -193,6 +208,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final Set<String> existingPlatformOrderNos = new HashSet<>();
private final Set<String> existingRelationKeys = new HashSet<>();
private final List<PendingOrderInsert> pendingOrders = new ArrayList<>();
private final Map<String, PendingOrderInsert> pendingOrderByPlatformNo = new HashMap<>(); // 按平台订单号索引,用于快速查找和更新
private final List<ShopProductRelationPO> pendingRelations = new ArrayList<>();
private final Set<String> pendingRelationKeys = new HashSet<>();
private final Set<String> pendingPlatformOrderNos = new HashSet<>();
@@ -381,10 +397,32 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 解析CSV行数据
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(),
defaultStatusId, companyId, task.getCreateBy(), context);
validatePlatformOrderNo(orderDTO.getPlatformOrderNo(), context);
queueShopProductRelation(orderDTO, context);
context.pendingOrders.add(new PendingOrderInsert(rowNumber, orderDTO.getPlatformOrderNo(),
buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId())));
OrderPO orderPO = buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId());
// 如果是更新操作,设置订单ID
if (orderDTO.getExistingOrderId() != null) {
orderPO.setId(orderDTO.getExistingOrderId());
}
StringBuilder updateMsg = new StringBuilder();
if (orderDTO.getExistingOrderId() != null) {
updateMsg.append(String.format("平台订单号 %s 已更新", orderDTO.getPlatformOrderNo()));
}
// 检查是否是同批次内重复(内存中的重复)
boolean isInMemoryDuplicate = validatePlatformOrderNo(
orderDTO.getPlatformOrderNo(), context, orderPO, rowNumber, orderDTO.getExistingOrderId(), updateMsg);
if (!isInMemoryDuplicate) {
// 非重复:新增到pending队列
PendingOrderInsert pendingInsert = new PendingOrderInsert(
rowNumber, orderDTO.getPlatformOrderNo(), orderPO, orderDTO.getExistingOrderId(), 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);
@@ -1184,13 +1222,16 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
// 验证平台订单号是否重复(如果提供了的话)
// 如果重复,则更新已存在的订单而不是报错
if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) {
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getPlatformOrderNo, createOrderDTO.getPlatformOrderNo())
.eq(OrderPO::getCompanyId, companyId);
if (orderMapper.selectCount(wrapper) > 0) {
throw new BusinessException("平台订单号已存在");
OrderPO existingOrder = orderMapper.selectOne(wrapper);
if (existingOrder != null) {
// 平台订单号已存在,记录existingOrderId用于更新
createOrderDTO.setExistingOrderId(existingOrder.getId());
}
}
@@ -1426,15 +1467,37 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
return product;
}
private void validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context) {
/**
* 验证平台订单号是否重复(内存检查)
* 如果同一批次内有重复,更新已存在的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;
return false;
}
String normalized = platformOrderNo.trim();
if (context.existingPlatformOrderNos.contains(normalized) || context.pendingPlatformOrderNos.contains(normalized)) {
throw new BusinessException("平台订单号已存在");
// 检查同一批次内是否已存在相同的平台订单号
if (context.pendingPlatformOrderNos.contains(normalized)) {
// 同批次内重复:更新已存在的pending订单数据
PendingOrderInsert existing = context.pendingOrderByPlatformNo.get(normalized);
if (existing != null) {
// 更新已存在订单的数据和行号
existing.updateData(newOrderPO, newExistingOrderId, newUpdateMsg, newRowNumber);
}
return true;
}
// 新增
context.pendingPlatformOrderNos.add(normalized);
return false;
}
private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) {
@@ -1493,15 +1556,64 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
int success = 0;
int fail = 0;
List<PendingOrderInsert> batch = new ArrayList<>(context.pendingOrders);
// 分离新增和更新
List<PendingOrderInsert> inserts = new ArrayList<>();
List<PendingOrderInsert> 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);
success += result[0];
fail += result[1];
}
// 处理更新
for (PendingOrderInsert pending : updates) {
try {
orderMapper.updateById(pending.order);
success++;
// 记录更新消息
if (pending.updateMessages != null && pending.updateMessages.length() > 0) {
errorMessages.append(String.format("第%d行:%s", pending.rowNumber, pending.updateMessages))
.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) {
fail++;
errorMessages.append(String.format("第%d行:更新失败 %s", pending.rowNumber, e.getMessage()))
.append(System.lineSeparator());
}
}
context.pendingOrders.clear();
return new int[] {success, fail};
}
private int[] doBatchInsert(List<PendingOrderInsert> 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 : batch) {
for (PendingOrderInsert pending : inserts) {
batchMapper.insert(pending.order);
}
session.flushStatements();
session.commit();
success += batch.size();
for (PendingOrderInsert pending : batch) {
success += inserts.size();
for (PendingOrderInsert pending : inserts) {
if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) {
String normalized = pending.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
@@ -1509,7 +1621,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
} catch (Exception e) {
for (PendingOrderInsert pending : batch) {
for (PendingOrderInsert pending : inserts) {
try {
orderMapper.insert(pending.order);
success++;
@@ -1527,8 +1639,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
.append(System.lineSeparator());
}
}
} finally {
context.pendingOrders.clear();
}
return new int[] {success, fail};
}
@@ -126,4 +126,11 @@ public class CreateOrderDTO {
*/
@Schema(description = "确认", example = "1")
private Integer confirm;
/**
* 已存在的订单ID(用于导入时更新重复订单)
* 不为空表示是更新操作
*/
@Schema(description = "已存在的订单ID(导入时用于更新)", example = "1")
private Long existingOrderId;
}