mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
fix: 导入时比较订单内容,变更才更新,未变更跳过
This commit is contained in:
+20
@@ -127,7 +127,12 @@ public class ImportRuntimeContext {
|
||||
public int successCount;
|
||||
public int failCount;
|
||||
public int insertCount;
|
||||
/** 实际执行了 UPDATE 的条数(与库中快照比较有变更) */
|
||||
public int updateCount;
|
||||
/** 已存在订单且内容一致,跳过 UPDATE 的条数 */
|
||||
public int existingUnchangedCount;
|
||||
/** 已存在订单但 UPDATE 失败的条数 */
|
||||
public int updateDbFailCount;
|
||||
public StringBuilder errorMessages = new StringBuilder();
|
||||
}
|
||||
|
||||
@@ -150,6 +155,8 @@ public class ImportRuntimeContext {
|
||||
// 已存在于 DB 的数据:预加载时填充(只写一次),后续只读
|
||||
final Set<String> existingPlatformOrderNos = ConcurrentHashMap.newKeySet();
|
||||
final Map<String, Long> existingOrderIdByPlatformNo = new ConcurrentHashMap<>();
|
||||
/** 平台订单号(规范化) → 库中订单业务字段快照;成功 UPDATE 后由主线程替换为新快照 */
|
||||
final ConcurrentHashMap<String, OrderPO> existingOrderSnapshotByPlatformNo = new ConcurrentHashMap<>();
|
||||
final Set<String> existingRelationKeys = ConcurrentHashMap.newKeySet();
|
||||
|
||||
// pendingOrders:由 workers 并发添加(CopyOnWriteArrayList 读多写少场景高效)
|
||||
@@ -169,6 +176,9 @@ public class ImportRuntimeContext {
|
||||
// 进度回调(主线程设置,workers 调用,线程安全包装)
|
||||
transient volatile BiConsumer<Integer, Integer> progressCallback;
|
||||
|
||||
/** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */
|
||||
private transient Map<String, MappingField> orderImportFieldMapping;
|
||||
|
||||
/** 线程安全的进度回调(防止多 worker 并发调用) */
|
||||
public void reportProgress(int total, int done) {
|
||||
BiConsumer<Integer, Integer> cb = this.progressCallback;
|
||||
@@ -192,6 +202,15 @@ public class ImportRuntimeContext {
|
||||
public Long getTaskId() { return taskId; }
|
||||
public DateTimeFormatPattern getDetectedDatePattern() { return detectedDatePattern; }
|
||||
public void setDetectedDatePattern(DateTimeFormatPattern detectedDatePattern) { this.detectedDatePattern = detectedDatePattern; }
|
||||
|
||||
public void setOrderImportFieldMapping(Map<String, MappingField> orderImportFieldMapping) {
|
||||
this.orderImportFieldMapping = orderImportFieldMapping;
|
||||
}
|
||||
|
||||
/** 无变更比较用;未设置时视为空映射(仅比较公司/店铺/状态) */
|
||||
public Map<String, MappingField> getOrderImportFieldMapping() {
|
||||
return orderImportFieldMapping != null ? orderImportFieldMapping : Collections.emptyMap();
|
||||
}
|
||||
public Map<String, ProductSpecPO> getSpecByCodeCache() { return specByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByCodeCache() { return productByCodeCache; }
|
||||
public Map<String, ProductPO> getProductByNameCache() { return productByNameCache; }
|
||||
@@ -199,6 +218,7 @@ public class ImportRuntimeContext {
|
||||
public Map<String, Long> getStatusIdByNameCache() { return statusIdByNameCache; }
|
||||
public Set<String> getExistingPlatformOrderNos() { return existingPlatformOrderNos; }
|
||||
public Map<String, Long> getExistingOrderIdByPlatformNo() { return existingOrderIdByPlatformNo; }
|
||||
public Map<String, OrderPO> getExistingOrderSnapshotByPlatformNo() { return existingOrderSnapshotByPlatformNo; }
|
||||
public Set<String> getExistingRelationKeys() { return existingRelationKeys; }
|
||||
public List<PendingOrderInsert> getPendingOrders() { return pendingOrders; }
|
||||
public Map<String, PendingOrderInsert> getPendingOrderByPlatformNo() { return pendingOrderByPlatformNo; }
|
||||
|
||||
+8
-1
@@ -181,7 +181,14 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
task, finalCsvFile, charset, fieldMapping, statusMapping, context, progressCallback);
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed");
|
||||
String summary = String.format("导入完成,新增 %d 条,更新 %d 条", result.insertCount, result.updateCount);
|
||||
int existingTotal = result.updateCount + result.existingUnchangedCount + result.updateDbFailCount;
|
||||
String summary = String.format(
|
||||
"导入完成,新增 %d 条,已存在订单 %d 条(实际更新 %d 条,无变更跳过 %d 条",
|
||||
result.insertCount, existingTotal, result.updateCount, result.existingUnchangedCount);
|
||||
if (result.updateDbFailCount > 0) {
|
||||
summary += String.format(",更新失败 %d 条", result.updateDbFailCount);
|
||||
}
|
||||
summary += ")";
|
||||
String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary;
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
|
||||
|
||||
+132
-8
@@ -23,6 +23,7 @@ import java.math.BigDecimal;
|
||||
import java.nio.charset.Charset;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.*;
|
||||
@@ -207,6 +208,7 @@ public class OrderImportProcessor {
|
||||
result.totalCount = records.size();
|
||||
context.totalCount = records.size();
|
||||
context.progressCallback = progressCallback;
|
||||
context.setOrderImportFieldMapping(fieldMapping);
|
||||
|
||||
// 预加载(主线程)
|
||||
specHelper.preloadProductSpecs(context, specCodes);
|
||||
@@ -265,7 +267,9 @@ public class OrderImportProcessor {
|
||||
flushedLast = doFlushPendingOrders(context, errorMessages);
|
||||
result.insertCount += flushedLast[0];
|
||||
result.updateCount += flushedLast[2];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2];
|
||||
result.existingUnchangedCount += flushedLast[4];
|
||||
result.updateDbFailCount += flushedLast[3];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4];
|
||||
if (progressCallback != null) {
|
||||
progressCallback.accept(result.totalCount, flushedTotal);
|
||||
}
|
||||
@@ -296,7 +300,9 @@ public class OrderImportProcessor {
|
||||
flushedLast = doFlushPendingOrders(context, errorMessages);
|
||||
result.insertCount += flushedLast[0];
|
||||
result.updateCount += flushedLast[2];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2];
|
||||
result.existingUnchangedCount += flushedLast[4];
|
||||
result.updateDbFailCount += flushedLast[3];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4];
|
||||
flushPendingRelations(context);
|
||||
|
||||
// 最终进度推送(flushedTotal 已是全部 DB 写入,<= totalCount)
|
||||
@@ -530,14 +536,19 @@ public class OrderImportProcessor {
|
||||
private int[] doFlushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) {
|
||||
synchronized (context.pendingOrders) {
|
||||
if (context.pendingOrders.isEmpty()) {
|
||||
return new int[] {0, 0, 0, 0};
|
||||
return new int[] {0, 0, 0, 0, 0};
|
||||
}
|
||||
return flushPendingOrdersInternal(context, errorMessages);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* flush 一批订单。
|
||||
*
|
||||
* @return [insertSuccess, insertFail, updateChanged, updateFail, updateSkippedUnchanged]
|
||||
*/
|
||||
private int[] flushPendingOrdersInternal(ImportRuntimeContext context, StringBuilder errorMessages) {
|
||||
int insertSuccess = 0, insertFail = 0, updateSuccess = 0, updateFail = 0;
|
||||
int insertSuccess = 0, insertFail = 0, updateChanged = 0, updateFail = 0, updateSkippedUnchanged = 0;
|
||||
|
||||
List<ImportRuntimeContext.PendingOrderInsert> batch =
|
||||
new ArrayList<>(context.pendingOrders);
|
||||
@@ -555,18 +566,29 @@ public class OrderImportProcessor {
|
||||
}
|
||||
|
||||
for (ImportRuntimeContext.PendingOrderInsert p : updates) {
|
||||
String normalized = p.platformOrderNo != null ? p.platformOrderNo.trim() : null;
|
||||
OrderPO dbSnap = normalized != null ? context.existingOrderSnapshotByPlatformNo.get(normalized) : null;
|
||||
boolean unchanged = dbSnap != null && isOrderImportContentUnchanged(dbSnap, p.order, context.getOrderImportFieldMapping());
|
||||
if (unchanged) {
|
||||
updateSkippedUnchanged++;
|
||||
if (p.platformOrderNo != null && !p.platformOrderNo.trim().isEmpty()) {
|
||||
context.pendingPlatformOrderNos.remove(normalized);
|
||||
context.existingPlatformOrderNos.add(normalized);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
orderMapper.updateById(p.order);
|
||||
updateSuccess++;
|
||||
updateChanged++;
|
||||
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();
|
||||
if (normalized != null) {
|
||||
context.pendingPlatformOrderNos.remove(normalized);
|
||||
context.existingPlatformOrderNos.add(normalized);
|
||||
context.existingOrderSnapshotByPlatformNo.put(normalized, copyOrderImportSnapshot(p.order));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
updateFail++;
|
||||
@@ -583,7 +605,109 @@ public class OrderImportProcessor {
|
||||
synchronized (context.pendingPlatformOrderNos) {
|
||||
context.pendingPlatformOrderNos.clear();
|
||||
}
|
||||
return new int[] {insertSuccess, insertFail, updateSuccess, updateFail};
|
||||
return new int[] {insertSuccess, insertFail, updateChanged, updateFail, updateSkippedUnchanged};
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断导入行与库中数据是否一致:始终比较公司、店铺、状态;其余仅比较本次映射中出现的业务字段,
|
||||
* 避免 import_task_id、confirm、审计时间等未映射列导致误判「有变更」。
|
||||
*/
|
||||
private static boolean isOrderImportContentUnchanged(OrderPO db, OrderPO incoming,
|
||||
Map<String, ImportRuntimeContext.MappingField> fieldMapping) {
|
||||
if (fieldMapping == null) {
|
||||
fieldMapping = Collections.emptyMap();
|
||||
}
|
||||
if (!Objects.equals(db.getCompanyId(), incoming.getCompanyId())) return false;
|
||||
if (!Objects.equals(db.getShopId(), incoming.getShopId())) return false;
|
||||
if (!Objects.equals(db.getStatusId(), incoming.getStatusId())) return false;
|
||||
|
||||
boolean compareProductBlock = fieldMapping.containsKey("spec_code")
|
||||
|| fieldMapping.containsKey("product_code")
|
||||
|| fieldMapping.containsKey("link_product_name")
|
||||
|| fieldMapping.containsKey("link_spec_name");
|
||||
if (compareProductBlock) {
|
||||
if (!Objects.equals(db.getProductId(), incoming.getProductId())) return false;
|
||||
if (!Objects.equals(db.getProductSpecId(), incoming.getProductSpecId())) return false;
|
||||
if (!normStrEq(db.getLinkProductName(), incoming.getLinkProductName())) return false;
|
||||
if (!normStrEq(db.getLinkSpecName(), incoming.getLinkSpecName())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("platform_order_no")) {
|
||||
if (!normStrEq(db.getPlatformOrderNo(), incoming.getPlatformOrderNo())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("quantity")) {
|
||||
if (!Objects.equals(db.getQuantity(), incoming.getQuantity())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("unit_price")) {
|
||||
if (!decimalEq(db.getUnitPrice(), incoming.getUnitPrice())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("product_cost")) {
|
||||
if (!decimalEq(db.getProductCost(), incoming.getProductCost())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("shipping_cost")) {
|
||||
if (!decimalEq(db.getShippingCost(), incoming.getShippingCost())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("other_cost")) {
|
||||
if (!decimalEq(db.getOtherCost(), incoming.getOtherCost())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("received_amount")) {
|
||||
if (!decimalEq(db.getReceivedAmount(), incoming.getReceivedAmount())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("order_time")) {
|
||||
if (!orderTimeEqualsForImport(db.getOrderTime(), incoming.getOrderTime())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("confirm")) {
|
||||
if (!Objects.equals(normalizeConfirm(db.getConfirm()), normalizeConfirm(incoming.getConfirm()))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 与库表 ec_order 常见 DATETIME(0) 精度一致,避免 JDBC 读出有纳秒/微秒而 CSV 解析为整秒导致误判有变更。
|
||||
*/
|
||||
private static boolean orderTimeEqualsForImport(LocalDateTime a, LocalDateTime b) {
|
||||
if (a == null && b == null) return true;
|
||||
if (a == null || b == null) return false;
|
||||
return a.truncatedTo(ChronoUnit.SECONDS).equals(b.truncatedTo(ChronoUnit.SECONDS));
|
||||
}
|
||||
|
||||
/** 与 {@link #buildOrderPO} 默认 confirm=1 对齐 */
|
||||
private static Integer normalizeConfirm(Integer c) {
|
||||
return c != null ? c : 1;
|
||||
}
|
||||
|
||||
private static boolean normStrEq(String a, String b) {
|
||||
String na = a == null || a.trim().isEmpty() ? null : a.trim();
|
||||
String nb = b == null || b.trim().isEmpty() ? null : b.trim();
|
||||
return Objects.equals(na, nb);
|
||||
}
|
||||
|
||||
private static boolean decimalEq(BigDecimal a, BigDecimal b) {
|
||||
BigDecimal x = a != null ? a : BigDecimal.ZERO;
|
||||
BigDecimal y = b != null ? b : BigDecimal.ZERO;
|
||||
return x.compareTo(y) == 0;
|
||||
}
|
||||
|
||||
/** 写入内存快照,避免后续同单号批次仍用旧快照比较 */
|
||||
private static OrderPO copyOrderImportSnapshot(OrderPO o) {
|
||||
OrderPO c = new OrderPO();
|
||||
c.setId(o.getId());
|
||||
c.setCompanyId(o.getCompanyId());
|
||||
c.setShopId(o.getShopId());
|
||||
c.setPlatformOrderNo(o.getPlatformOrderNo());
|
||||
c.setStatusId(o.getStatusId());
|
||||
c.setProductId(o.getProductId());
|
||||
c.setProductSpecId(o.getProductSpecId());
|
||||
c.setLinkProductName(o.getLinkProductName());
|
||||
c.setLinkSpecName(o.getLinkSpecName());
|
||||
c.setQuantity(o.getQuantity());
|
||||
c.setUnitPrice(o.getUnitPrice());
|
||||
c.setProductCost(o.getProductCost());
|
||||
c.setShippingCost(o.getShippingCost());
|
||||
c.setOtherCost(o.getOtherCost());
|
||||
c.setReceivedAmount(o.getReceivedAmount());
|
||||
c.setOrderTime(o.getOrderTime());
|
||||
c.setConfirm(o.getConfirm());
|
||||
return c;
|
||||
}
|
||||
|
||||
private int[] doBatchInsert(List<ImportRuntimeContext.PendingOrderInsert> inserts,
|
||||
|
||||
+5
-2
@@ -363,13 +363,16 @@ public class ProductSpecImportHelper {
|
||||
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);
|
||||
.in(OrderPO::getPlatformOrderNo, chunk);
|
||||
if (context.getShopId() != null) {
|
||||
wrapper.eq(OrderPO::getShopId, context.getShopId());
|
||||
}
|
||||
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());
|
||||
context.existingOrderSnapshotByPlatformNo.put(normalized, order);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user