mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
fix(ecom-dmb): 修复CSV导入BOM问题,支持链接商品名称正确解析
- OrderImportProcessor.getValue() 增加BOM(\ufeff) fallback逻辑 - ImportRuntimeContext 优化统计信息(区分新增/已存在/无变更跳过)
This commit is contained in:
+4
@@ -131,6 +131,8 @@ public class ImportRuntimeContext {
|
||||
public int updateCount;
|
||||
/** 已存在订单且内容一致,跳过 UPDATE 的条数 */
|
||||
public int existingUnchangedCount;
|
||||
/** 同一导入文件内按平台订单号合并(后者覆盖前者)的条数 */
|
||||
public int mergedDuplicatePlatformNoCount;
|
||||
/** 已存在订单但 UPDATE 失败的条数 */
|
||||
public int updateDbFailCount;
|
||||
public StringBuilder errorMessages = new StringBuilder();
|
||||
@@ -171,6 +173,8 @@ public class ImportRuntimeContext {
|
||||
final Set<String> pendingRelationKeys = Collections.synchronizedSet(new HashSet<>());
|
||||
// 已处理的行数(workers 并发 +1,主线程读取用于推送进度)
|
||||
final AtomicInteger processedCount = new AtomicInteger(0);
|
||||
// 同一导入文件内重复平台订单号被合并的条数
|
||||
final AtomicInteger mergedDuplicatePlatformNoCount = new AtomicInteger(0);
|
||||
// 总行数(主线程设置,workers 读取用于回调)
|
||||
volatile int totalCount = 0;
|
||||
// 进度回调(主线程设置,workers 调用,线程安全包装)
|
||||
|
||||
+8
-4
@@ -181,14 +181,18 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
task, finalCsvFile, charset, fieldMapping, statusMapping, context, progressCallback);
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed");
|
||||
int existingTotal = result.updateCount + result.existingUnchangedCount + result.updateDbFailCount;
|
||||
String summary = String.format(
|
||||
"导入完成,新增 %d 条,已存在订单 %d 条(实际更新 %d 条,无变更跳过 %d 条",
|
||||
result.insertCount, existingTotal, result.updateCount, result.existingUnchangedCount);
|
||||
"导入完成,处理 %d 条,新增 %d 条,更新 %d 条",
|
||||
result.totalCount, result.insertCount, result.updateCount);
|
||||
if (result.existingUnchangedCount > 0) {
|
||||
summary += String.format(",无变更跳过 %d 条", result.existingUnchangedCount);
|
||||
}
|
||||
if (result.mergedDuplicatePlatformNoCount > 0) {
|
||||
summary += String.format(",同文件重复订单号合并 %d 条", result.mergedDuplicatePlatformNoCount);
|
||||
}
|
||||
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);
|
||||
|
||||
|
||||
+77
-11
@@ -262,10 +262,11 @@ public class OrderImportProcessor {
|
||||
|
||||
// 先将 worker 产出的结果并入 pending,再按阈值写入 DB。
|
||||
// 原先在 drain 之前判断 pendingOrders.size(),pending 永远不会在循环内增长,导致全部积压到最后一次 flush(进度却已由 worker 按解析数报到 100%)。
|
||||
drainResultsToPendingOrders(results, context);
|
||||
result.failCount += drainResultsToPendingOrders(results, context, errorMessages);
|
||||
if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) {
|
||||
flushedLast = doFlushPendingOrders(context, errorMessages);
|
||||
result.insertCount += flushedLast[0];
|
||||
result.failCount += flushedLast[1];
|
||||
result.updateCount += flushedLast[2];
|
||||
result.existingUnchangedCount += flushedLast[4];
|
||||
result.updateDbFailCount += flushedLast[3];
|
||||
@@ -294,11 +295,12 @@ public class OrderImportProcessor {
|
||||
}
|
||||
|
||||
// 合并 worker 结果到 pendingOrders(持有锁)
|
||||
drainResultsToPendingOrders(results, context);
|
||||
result.failCount += drainResultsToPendingOrders(results, context, errorMessages);
|
||||
|
||||
// 最终 flush
|
||||
flushedLast = doFlushPendingOrders(context, errorMessages);
|
||||
result.insertCount += flushedLast[0];
|
||||
result.failCount += flushedLast[1];
|
||||
result.updateCount += flushedLast[2];
|
||||
result.existingUnchangedCount += flushedLast[4];
|
||||
result.updateDbFailCount += flushedLast[3];
|
||||
@@ -309,7 +311,8 @@ public class OrderImportProcessor {
|
||||
if (progressCallback != null) {
|
||||
progressCallback.accept(result.totalCount, flushedTotal);
|
||||
}
|
||||
result.successCount = records.size() - result.failCount;
|
||||
result.successCount = result.insertCount + result.updateCount + result.existingUnchangedCount;
|
||||
result.mergedDuplicatePlatformNoCount = context.mergedDuplicatePlatformNoCount.get();
|
||||
result.errorMessages = errorMessages;
|
||||
|
||||
} catch (Exception e) {
|
||||
@@ -408,6 +411,17 @@ public class OrderImportProcessor {
|
||||
linkSpecName = linkSpecName.trim();
|
||||
if (linkSpecName.isEmpty()) linkSpecName = null;
|
||||
}
|
||||
// 二次从 CSV 读取失败时,回退到主线程 parseOrderFromCSV 已解析的 DTO 值。
|
||||
if ((linkProductName == null || linkProductName.isEmpty())
|
||||
&& dto.getLinkProductName() != null
|
||||
&& !dto.getLinkProductName().trim().isEmpty()) {
|
||||
linkProductName = dto.getLinkProductName().trim();
|
||||
}
|
||||
if ((linkSpecName == null || linkSpecName.isEmpty())
|
||||
&& dto.getLinkSpecName() != null
|
||||
&& !dto.getLinkSpecName().trim().isEmpty()) {
|
||||
linkSpecName = dto.getLinkSpecName().trim();
|
||||
}
|
||||
|
||||
if (specCodeRaw == null && productCode == null && linkProductName == null) {
|
||||
throw new BusinessException("商品信息为空");
|
||||
@@ -435,7 +449,10 @@ public class OrderImportProcessor {
|
||||
row.createBy, context);
|
||||
isNewSpecCreated = true;
|
||||
} else {
|
||||
String finalProductName = (linkProductName != null) ? linkProductName : "未知商品";
|
||||
String finalProductName =
|
||||
(linkProductName != null && !linkProductName.isEmpty()) ? linkProductName
|
||||
: (productCode != null && !productCode.isEmpty()) ? productCode
|
||||
: "未知商品";
|
||||
String finalSpecName = (linkSpecName != null) ? linkSpecName : "未知规格";
|
||||
productSpec = specHelper.createProductAndSpecIfNotExists(
|
||||
companyId, finalProductName, productCode,
|
||||
@@ -477,13 +494,15 @@ public class OrderImportProcessor {
|
||||
/**
|
||||
* 将 worker 的结果合并到 context.pendingOrders(主线程调用,持有锁)
|
||||
*/
|
||||
private void drainResultsToPendingOrders(List<OrderParseResult> results,
|
||||
ImportRuntimeContext context) {
|
||||
private int drainResultsToPendingOrders(List<OrderParseResult> results,
|
||||
ImportRuntimeContext context,
|
||||
StringBuilder errorMessages) {
|
||||
int workerFailCount = 0;
|
||||
// results 由 workers 并发写入,必须在同一锁内做快照再遍历,否则会 ConcurrentModificationException(getMessage() 为 null,外层显示「CSV解析失败: null」)
|
||||
final List<OrderParseResult> batch;
|
||||
synchronized (results) {
|
||||
if (results.isEmpty()) {
|
||||
return;
|
||||
return 0;
|
||||
}
|
||||
batch = new ArrayList<>(results);
|
||||
results.clear();
|
||||
@@ -491,7 +510,14 @@ public class OrderImportProcessor {
|
||||
synchronized (context.pendingOrders) {
|
||||
for (OrderParseResult r : batch) {
|
||||
if (r.parseException != null) {
|
||||
// 错误结果在主线程 parse 时已处理
|
||||
// Worker 线程异常必须计入失败,否则会出现 total > (insert+update) 且 fail=0 的假象
|
||||
workerFailCount++;
|
||||
errorMessages.append(String.format("第%d行:%s",
|
||||
r.rowNumber,
|
||||
r.parseException.getMessage() != null
|
||||
? r.parseException.getMessage()
|
||||
: r.parseException.toString()))
|
||||
.append(System.lineSeparator());
|
||||
continue;
|
||||
}
|
||||
StringBuilder updateMsg = new StringBuilder();
|
||||
@@ -499,6 +525,17 @@ public class OrderImportProcessor {
|
||||
if (isUpdate) {
|
||||
updateMsg.append(String.format("平台订单号 %s 已更新", r.platformOrderNo));
|
||||
}
|
||||
// 同一导入文件内若平台订单号重复,按“后者覆盖前者”合并到同一 pending,避免批量插入时唯一键冲突但任务统计不一致。
|
||||
if (validatePlatformOrderNo(
|
||||
r.platformOrderNo,
|
||||
context,
|
||||
r.order,
|
||||
r.rowNumber,
|
||||
r.order != null ? r.order.getId() : null,
|
||||
updateMsg)) {
|
||||
context.mergedDuplicatePlatformNoCount.incrementAndGet();
|
||||
continue;
|
||||
}
|
||||
|
||||
ImportRuntimeContext.PendingOrderInsert pending =
|
||||
new ImportRuntimeContext.PendingOrderInsert(
|
||||
@@ -515,6 +552,7 @@ public class OrderImportProcessor {
|
||||
}
|
||||
}
|
||||
}
|
||||
return workerFailCount;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -634,7 +672,7 @@ public class OrderImportProcessor {
|
||||
if (fieldMapping.containsKey("platform_order_no")) {
|
||||
if (!normStrEq(db.getPlatformOrderNo(), incoming.getPlatformOrderNo())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("quantity")) {
|
||||
if (fieldMapping.containsKey("product_quantity")) {
|
||||
if (!Objects.equals(db.getQuantity(), incoming.getQuantity())) return false;
|
||||
}
|
||||
if (fieldMapping.containsKey("unit_price")) {
|
||||
@@ -829,7 +867,7 @@ public class OrderImportProcessor {
|
||||
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 quantityField = fieldMapping.get("product_quantity");
|
||||
ImportRuntimeContext.MappingField unitPriceField = fieldMapping.get("unit_price");
|
||||
ImportRuntimeContext.MappingField productCostField = fieldMapping.get("product_cost");
|
||||
ImportRuntimeContext.MappingField shippingCostField = fieldMapping.get("shipping_cost");
|
||||
@@ -1042,6 +1080,7 @@ public class OrderImportProcessor {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// ==================== 关系队列 ====================
|
||||
|
||||
/**
|
||||
@@ -1133,10 +1172,27 @@ public class OrderImportProcessor {
|
||||
|| mappingField.getFileFieldName().trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String expectedHeader = mappingField.getFileFieldName().trim();
|
||||
try {
|
||||
String val = record.get(mappingField.getFileFieldName());
|
||||
String val = record.get(expectedHeader);
|
||||
return (val != null && !val.trim().isEmpty()) ? val.trim() : null;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// 某些 CSV 的表头会混入不可见字符/全角空格;做一次归一化匹配兜底。
|
||||
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
|
||||
if (headerMap != null && !headerMap.isEmpty()) {
|
||||
String normalizedExpected = normalizeHeader(expectedHeader);
|
||||
for (String actualHeader : headerMap.keySet()) {
|
||||
if (actualHeader != null
|
||||
&& normalizeHeader(actualHeader).equals(normalizedExpected)) {
|
||||
try {
|
||||
String val = record.get(actualHeader);
|
||||
return (val != null && !val.trim().isEmpty()) ? val.trim() : null;
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
// continue
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1150,4 +1206,14 @@ public class OrderImportProcessor {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeHeader(String header) {
|
||||
if (header == null) return "";
|
||||
return header.replace("\uFEFF", "")
|
||||
.replace("\u00A0", "")
|
||||
.replace("\u3000", "")
|
||||
.replaceAll("\\s+", "")
|
||||
.trim()
|
||||
.toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
|
||||
+6
-3
@@ -90,7 +90,9 @@ public class ProductSpecImportHelper {
|
||||
spec.setProductId(product.getId());
|
||||
spec.setCompanyId(companyId);
|
||||
spec.setSpecCode(trimmedCode);
|
||||
spec.setName(trimmedName != null ? trimmedName : (trimmedCode != null ? trimmedCode : "未知规格"));
|
||||
String finalSpecName = trimmedName != null ? trimmedName : (trimmedCode != null ? trimmedCode : "未知规格");
|
||||
spec.setName(finalSpecName);
|
||||
spec.setLinkName(finalSpecName);
|
||||
spec.setProductCost(productCost != null ? productCost : BigDecimal.ZERO);
|
||||
spec.setCreateBy(createBy);
|
||||
productSpecService.save(spec);
|
||||
@@ -180,8 +182,9 @@ public class ProductSpecImportHelper {
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
return createSpecForProductWithValidation(null, null, specCode, specName,
|
||||
null, companyId, createBy, context);
|
||||
// 已知 productId 时应直接基于该商品创建规格,不能再走“按商品编码/名称查商品”的路径,
|
||||
// 否则会在 productCode/productName 为空时误报“商品编码和商品名称不能同时为空”。
|
||||
return createSpecForProduct(product, specCode, specName, null, companyId, createBy, context);
|
||||
}
|
||||
|
||||
/** 旧签名(兼容旧版调用):参数顺序 companyId, productName, productCode, specName, specCode */
|
||||
|
||||
Reference in New Issue
Block a user