mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
feat: 订单导入支持 Excel 格式(.xlsx/.xls)
- 前端:新增 fileParser.ts(XLSX 库解析 Excel),FileUploadArea 支持 csv/xlsx/xls - 后端:OrderImportProcessor.processExcel() 用 Apache POI 读取 Excel - ImportTaskProcessorServiceImpl 根据文件扩展名路由到 CSV 或 Excel 解析器 - 修复 Excel 空行检测 bug(isEmpty 逻辑写反)
This commit is contained in:
+15
-6
@@ -148,6 +148,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
|
||||
String storagePath = fileInfo.getStoragePath();
|
||||
String storageType = fileInfo.getStorageType();
|
||||
String filename = fileInfo.getFilename();
|
||||
boolean isExcel = filename != null && (filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".xls"));
|
||||
String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv";
|
||||
InputStream fileInputStream;
|
||||
|
||||
if ("local".equals(storageType)) {
|
||||
@@ -158,7 +161,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(localFile));
|
||||
csvFile = localFile;
|
||||
} else {
|
||||
tempOssFile = java.io.File.createTempFile("import-csv-", ".csv");
|
||||
tempOssFile = java.io.File.createTempFile("import-file-", fileExt);
|
||||
if (!ossService.downloadFile(storagePath, tempOssFile)) {
|
||||
throw new BusinessException("从对象存储下载文件失败,storagePath: " + storagePath);
|
||||
}
|
||||
@@ -166,7 +169,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
fileInputStream = new java.io.BufferedInputStream(new java.io.FileInputStream(tempOssFile));
|
||||
}
|
||||
|
||||
Charset charset = detectFileEncoding(fileInputStream);
|
||||
Charset charset = isExcel ? java.nio.charset.StandardCharsets.UTF_8 : detectFileEncoding(fileInputStream);
|
||||
ImportRuntimeContext context = new ImportRuntimeContext(task.getCompanyId(), task.getShopId(), task.getCreateBy(), task.getId());
|
||||
|
||||
java.util.function.BiConsumer<Integer, Integer> progressCallback = (total, done) -> {
|
||||
@@ -175,10 +178,16 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
|
||||
};
|
||||
|
||||
// 将 csvFile 传给 task(临时方案:task 本身没有此字段,由 process 方法内部读取)
|
||||
final File finalCsvFile = csvFile;
|
||||
ImportRuntimeContext.ImportResult result = orderImportProcessor.process(
|
||||
task, finalCsvFile, charset, fieldMapping, statusMapping, context, progressCallback);
|
||||
// 根据文件类型路由到对应解析器
|
||||
final File finalImportFile = csvFile;
|
||||
ImportRuntimeContext.ImportResult result;
|
||||
if (isExcel) {
|
||||
result = orderImportProcessor.processExcel(
|
||||
task, finalImportFile, fieldMapping, statusMapping, context, progressCallback);
|
||||
} else {
|
||||
result = orderImportProcessor.process(
|
||||
task, finalImportFile, charset, fieldMapping, statusMapping, context, progressCallback);
|
||||
}
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.insertCount > 0 ? "success" : "failed");
|
||||
String summary = String.format(
|
||||
|
||||
+551
-10
@@ -33,6 +33,10 @@ import java.util.concurrent.LinkedBlockingQueue;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BiConsumer;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 订单导入核心处理器(并行版本)
|
||||
@@ -70,10 +74,40 @@ public class OrderImportProcessor {
|
||||
/**
|
||||
* 队列元素:原始 CSV 行数据(由主线程解析出,传递给 workers)
|
||||
*/
|
||||
/** Excel 行数据包装器(用于替代 CSVRecord) */
|
||||
public static class ExcelRow {
|
||||
private final Map<String, String> rowData;
|
||||
private final List<String> orderedHeaders;
|
||||
|
||||
public ExcelRow(Map<String, String> rowData, List<String> orderedHeaders) {
|
||||
this.rowData = rowData;
|
||||
this.orderedHeaders = orderedHeaders;
|
||||
}
|
||||
|
||||
public String get(String header) {
|
||||
if (header == null) return null;
|
||||
String v = rowData.get(header);
|
||||
if (v != null) return v;
|
||||
String normalized = normalizeHeader(header);
|
||||
for (Map.Entry<String, String> e : rowData.entrySet()) {
|
||||
if (normalizeHeader(e.getKey()).equals(normalized)) {
|
||||
return e.getValue();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean isEmpty(String header) {
|
||||
String v = get(header);
|
||||
return v == null || v.trim().isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
public static class PendingRow {
|
||||
public final int rowNumber;
|
||||
public final CSVRecord record;
|
||||
public final CreateOrderDTO dto; // 主线程已解析好的 DTO
|
||||
/** 原始行数据(CSV → Map via csvRecordToMap;Excel → 直接为 Map) */
|
||||
public final Map<String, String> rowData;
|
||||
public final CreateOrderDTO dto;
|
||||
public final Map<String, ImportRuntimeContext.MappingField> fieldMapping;
|
||||
public final Map<String, Long> statusMapping;
|
||||
public final Long shopId;
|
||||
@@ -83,7 +117,7 @@ public class OrderImportProcessor {
|
||||
/** 无参构造器,用于毒丸(poison pill)信号 */
|
||||
public PendingRow() {
|
||||
this.rowNumber = -1;
|
||||
this.record = null;
|
||||
this.rowData = null;
|
||||
this.dto = null;
|
||||
this.fieldMapping = null;
|
||||
this.statusMapping = null;
|
||||
@@ -92,12 +126,12 @@ public class OrderImportProcessor {
|
||||
this.createBy = null;
|
||||
}
|
||||
|
||||
public PendingRow(int rowNumber, CSVRecord record, CreateOrderDTO dto,
|
||||
public PendingRow(int rowNumber, Map<String, String> rowData, CreateOrderDTO dto,
|
||||
Map<String, ImportRuntimeContext.MappingField> fieldMapping,
|
||||
Map<String, Long> statusMapping,
|
||||
Long shopId, Long companyId, Long createBy) {
|
||||
this.rowNumber = rowNumber;
|
||||
this.record = record;
|
||||
this.rowData = rowData;
|
||||
this.dto = dto;
|
||||
this.fieldMapping = fieldMapping;
|
||||
this.statusMapping = statusMapping;
|
||||
@@ -242,7 +276,8 @@ public class OrderImportProcessor {
|
||||
CreateOrderDTO dto = parseOrderFromCSV(record, fieldMapping, statusMapping,
|
||||
task.getShopId(), context.getCompanyId(), context.getCreateBy(), context);
|
||||
|
||||
PendingRow row = new PendingRow(rowNumber, record, dto, fieldMapping, statusMapping,
|
||||
Map<String, String> rowMap = csvRecordToMap(record);
|
||||
PendingRow row = new PendingRow(rowNumber, rowMap, dto, fieldMapping, statusMapping,
|
||||
task.getShopId(), context.getCompanyId(), context.getCreateBy());
|
||||
workQueue.offer(row);
|
||||
|
||||
@@ -322,6 +357,512 @@ public class OrderImportProcessor {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== Excel 解析入口 ====================
|
||||
|
||||
/**
|
||||
* 处理 Excel 订单导入(入口方法)
|
||||
*/
|
||||
public ImportRuntimeContext.ImportResult processExcel(
|
||||
top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO task,
|
||||
File excelFile,
|
||||
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(excelFile);
|
||||
Workbook workbook = WorkbookFactory.create(fis)) {
|
||||
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
if (sheet == null) {
|
||||
throw new BusinessException("Excel 文件中没有工作表");
|
||||
}
|
||||
|
||||
// 读取表头(第一行)
|
||||
Row headerRow = sheet.getRow(0);
|
||||
if (headerRow == null) {
|
||||
throw new BusinessException("Excel 文件表头行为空");
|
||||
}
|
||||
|
||||
List<String> orderedHeaders = new ArrayList<>();
|
||||
Map<String, Integer> headerIndexMap = new HashMap<>();
|
||||
for (int col = 0; col < headerRow.getLastCellNum(); col++) {
|
||||
Cell cell = headerRow.getCell(col);
|
||||
String header = getCellStringValue(cell);
|
||||
if (header != null && !header.trim().isEmpty()) {
|
||||
header = header.trim();
|
||||
orderedHeaders.add(header);
|
||||
headerIndexMap.put(header, col);
|
||||
}
|
||||
}
|
||||
|
||||
// 读取数据行
|
||||
List<Map<String, String>> rowDataList = new ArrayList<>();
|
||||
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
|
||||
Row dataRow = sheet.getRow(i);
|
||||
if (dataRow == null) continue;
|
||||
Map<String, String> rowMap = new LinkedHashMap<>();
|
||||
for (String header : orderedHeaders) {
|
||||
Integer colIdx = headerIndexMap.get(header);
|
||||
if (colIdx == null) {
|
||||
rowMap.put(header, "");
|
||||
continue;
|
||||
}
|
||||
Cell cell = dataRow.getCell(colIdx);
|
||||
String val = getCellStringValue(cell);
|
||||
rowMap.put(header, val != null ? val.trim() : "");
|
||||
}
|
||||
// 只要有一列有内容就认为是有效行
|
||||
boolean hasContent = rowMap.values().stream().anyMatch(v -> v != null && !v.isEmpty());
|
||||
if (hasContent) {
|
||||
rowDataList.add(rowMap);
|
||||
}
|
||||
}
|
||||
|
||||
result.totalCount = rowDataList.size();
|
||||
context.totalCount = rowDataList.size();
|
||||
context.progressCallback = progressCallback;
|
||||
context.setOrderImportFieldMapping(fieldMapping);
|
||||
|
||||
// 预加载数据
|
||||
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_time");
|
||||
|
||||
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<>();
|
||||
|
||||
for (Map<String, String> rowMap : rowDataList) {
|
||||
context.addNormalizedValue(specCodes, getValue(rowMap, specCodeField));
|
||||
context.addNormalizedValue(productCodes, getValue(rowMap, productCodeField));
|
||||
context.addNormalizedValue(productNames, getValue(rowMap, linkProductNameField));
|
||||
context.addNormalizedValue(platformOrderNos, getValue(rowMap, platformOrderNoField));
|
||||
context.addNormalizedValue(statusNames, getValue(rowMap, orderStatusField));
|
||||
if (context.getDetectedDatePattern() == null && orderDateField != null) {
|
||||
String dateStr = getValue(rowMap, orderDateField);
|
||||
if (dateStr != null && !dateStr.trim().isEmpty()) {
|
||||
context.setDetectedDatePattern(detectDateFormat(dateStr.trim()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
// ========== 并行处理(与 CSV 共用同一套 worker 机制)==========
|
||||
LinkedBlockingQueue<PendingRow> workQueue = new LinkedBlockingQueue<>();
|
||||
List<OrderParseResult> results = Collections.synchronizedList(new ArrayList<>());
|
||||
ExecutorService workerPool = Executors.newFixedThreadPool(PARALLELISM);
|
||||
for (int i = 0; i < PARALLELISM; i++) {
|
||||
workerPool.submit(() -> processWorkerLoopForMap(workQueue, results, context));
|
||||
}
|
||||
|
||||
StringBuilder errorMessages = new StringBuilder();
|
||||
int flushedTotal = 0;
|
||||
int[] flushedLast;
|
||||
|
||||
for (int i = 0; i < rowDataList.size(); i++) {
|
||||
Map<String, String> rowMap = rowDataList.get(i);
|
||||
int rowNumber = i + 2; // Excel 行号从 1 开始,减 1 是标题行,再 +1 是数据第 1 行
|
||||
|
||||
try {
|
||||
CreateOrderDTO dto = parseOrderFromMap(rowMap, fieldMapping, statusMapping,
|
||||
task.getShopId(), context.getCompanyId(), context.getCreateBy(), context);
|
||||
|
||||
PendingRow row = new PendingRow(rowNumber, rowMap, dto, fieldMapping, statusMapping,
|
||||
task.getShopId(), context.getCompanyId(), context.getCreateBy());
|
||||
workQueue.offer(row);
|
||||
|
||||
queueShopProductRelation(dto, context);
|
||||
if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) {
|
||||
flushPendingRelations(context);
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
result.failCount++;
|
||||
errorMessages.append(String.format("第%d行:%s", rowNumber, e.getMessage()))
|
||||
.append(System.lineSeparator());
|
||||
}
|
||||
|
||||
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];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4];
|
||||
if (progressCallback != null) {
|
||||
progressCallback.accept(result.totalCount, flushedTotal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 发送毒丸,停止 workers
|
||||
for (int i = 0; i < PARALLELISM; i++) {
|
||||
workQueue.offer(new PendingRow());
|
||||
}
|
||||
|
||||
workerPool.shutdown();
|
||||
try {
|
||||
if (!workerPool.awaitTermination(WORKER_TERMINATE_TIMEOUT_SEC, TimeUnit.SECONDS)) {
|
||||
workerPool.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
workerPool.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
|
||||
result.failCount += drainResultsToPendingOrders(results, context, errorMessages);
|
||||
flushedLast = doFlushPendingOrders(context, errorMessages);
|
||||
result.insertCount += flushedLast[0];
|
||||
result.failCount += flushedLast[1];
|
||||
result.updateCount += flushedLast[2];
|
||||
result.existingUnchangedCount += flushedLast[4];
|
||||
result.updateDbFailCount += flushedLast[3];
|
||||
flushedTotal += flushedLast[0] + flushedLast[2] + flushedLast[4];
|
||||
flushPendingRelations(context);
|
||||
|
||||
if (progressCallback != null) {
|
||||
progressCallback.accept(result.totalCount, flushedTotal);
|
||||
}
|
||||
result.successCount = result.insertCount + result.updateCount + result.existingUnchangedCount;
|
||||
result.mergedDuplicatePlatformNoCount = context.mergedDuplicatePlatformNoCount.get();
|
||||
result.errorMessages = errorMessages;
|
||||
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("Excel 解析失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// ==================== Worker 线程循环(Map 版本) ====================
|
||||
|
||||
private void processWorkerLoopForMap(LinkedBlockingQueue<PendingRow> workQueue,
|
||||
List<OrderParseResult> results,
|
||||
ImportRuntimeContext context) {
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
PendingRow row;
|
||||
try {
|
||||
row = workQueue.poll(100, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
if (row == null) continue;
|
||||
if (row.rowNumber < 0) break; // 毒丸
|
||||
|
||||
try {
|
||||
CreateOrderDTO dto = resolveProductAndSpec(row, context);
|
||||
OrderPO orderPO = buildOrderPO(dto, context.getCompanyId(),
|
||||
context.getCreateBy(), context.getTaskId(), context);
|
||||
|
||||
String platformOrderNo = dto.getPlatformOrderNo();
|
||||
boolean isUpdate = false;
|
||||
if (platformOrderNo != null && !platformOrderNo.trim().isEmpty()) {
|
||||
String normalized = platformOrderNo.trim();
|
||||
synchronized (context.pendingPlatformOrderNos) {
|
||||
if (context.pendingPlatformOrderNos.contains(normalized)) {
|
||||
isUpdate = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
synchronized (results) {
|
||||
results.add(OrderParseResult.success(row.rowNumber, dto, orderPO, platformOrderNo, isUpdate));
|
||||
}
|
||||
context.processedCount.incrementAndGet();
|
||||
|
||||
} catch (Exception e) {
|
||||
synchronized (results) {
|
||||
results.add(OrderParseResult.error(row.rowNumber, e));
|
||||
}
|
||||
context.processedCount.incrementAndGet();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== CSVRecord → Map 转换 ====================
|
||||
|
||||
/**
|
||||
* 将 CSVRecord 转换为 Map<String, String>(保持顺序)
|
||||
*/
|
||||
private Map<String, String> csvRecordToMap(CSVRecord record) {
|
||||
Map<String, String> map = new LinkedHashMap<>();
|
||||
if (record != null && record.getParser() != null) {
|
||||
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
|
||||
if (headerMap != null) {
|
||||
for (Map.Entry<String, Integer> entry : headerMap.entrySet()) {
|
||||
String header = entry.getKey();
|
||||
try {
|
||||
String val = record.get(header);
|
||||
map.put(header, val != null ? val.trim() : "");
|
||||
} catch (IllegalArgumentException e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
// ==================== Map 版本的 getValue ====================
|
||||
|
||||
private String getValue(Map<String, String> rowData, ImportRuntimeContext.MappingField mappingField) {
|
||||
if (mappingField == null || mappingField.getFileFieldName() == null
|
||||
|| mappingField.getFileFieldName().trim().isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
String expectedHeader = mappingField.getFileFieldName().trim();
|
||||
return getValue(rowData, expectedHeader);
|
||||
}
|
||||
|
||||
private String getValue(Map<String, String> rowData, String header) {
|
||||
if (header == null || header.trim().isEmpty()) return null;
|
||||
String val = rowData.get(header.trim());
|
||||
if (val != null && !val.trim().isEmpty()) return val.trim();
|
||||
// fallback: case-insensitive
|
||||
String normalized = normalizeHeader(header);
|
||||
for (Map.Entry<String, String> e : rowData.entrySet()) {
|
||||
if (normalizeHeader(e.getKey()).equals(normalized)) {
|
||||
String v = e.getValue();
|
||||
return (v != null && !v.trim().isEmpty()) ? v.trim() : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// ==================== Map 版本的订单解析 ====================
|
||||
|
||||
CreateOrderDTO parseOrderFromMap(Map<String, String> rowData,
|
||||
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(rowData, platformOrderNoField);
|
||||
if (pon != null && !pon.trim().isEmpty()) {
|
||||
dto.setPlatformOrderNo(pon.trim());
|
||||
}
|
||||
}
|
||||
|
||||
ImportRuntimeContext.MappingField statusField = fieldMapping.get("status");
|
||||
if (statusField != null) {
|
||||
String statusStr = getValue(rowData, 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("product_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_time");
|
||||
|
||||
String specCode = getValue(rowData, specCodeField);
|
||||
if (specCode == null || specCode.trim().isEmpty()) {
|
||||
if (specCodeField == null
|
||||
|| (specCodeField.getRequired() != null && specCodeField.getRequired())) {
|
||||
throw new BusinessException("规格编码不能为空");
|
||||
}
|
||||
}
|
||||
|
||||
String receivedAmountStr = getValue(rowData, receivedAmountField);
|
||||
if ((receivedAmountStr == null || receivedAmountStr.trim().isEmpty())
|
||||
&& receivedAmountField != null && receivedAmountField.getRequired() != null && receivedAmountField.getRequired()) {
|
||||
throw new BusinessException("商家实收金额不能为空");
|
||||
}
|
||||
|
||||
String productQuantityStr = getValue(rowData, 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(rowData, productCodeField);
|
||||
if (productCode != null && productCode.trim().isEmpty()) productCode = null;
|
||||
String linkProductName = getValue(rowData, linkProductNameField);
|
||||
if (linkProductName != null) {
|
||||
linkProductName = linkProductName.trim();
|
||||
if (linkProductName.isEmpty()) linkProductName = null;
|
||||
}
|
||||
String linkSpecName = getValue(rowData, fieldMapping.get("link_spec_name"));
|
||||
if (linkSpecName != null) {
|
||||
linkSpecName = linkSpecName.trim();
|
||||
if (linkSpecName.isEmpty()) linkSpecName = null;
|
||||
}
|
||||
|
||||
dto.setLinkProductName(linkProductName);
|
||||
dto.setLinkSpecName(linkSpecName);
|
||||
|
||||
if (quantityField != null) {
|
||||
String qtyStr = getValue(rowData, 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(rowData, unitPriceField);
|
||||
if (priceStr != null && !priceStr.trim().isEmpty()) {
|
||||
dto.setUnitPrice(new BigDecimal(priceStr.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
if (productCostField != null) {
|
||||
String costStr = getValue(rowData, productCostField);
|
||||
if (costStr != null && !costStr.trim().isEmpty()) {
|
||||
dto.setProductCost(new BigDecimal(costStr.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
if (shippingCostField != null) {
|
||||
String shippingStr = getValue(rowData, shippingCostField);
|
||||
if (shippingStr != null && !shippingStr.trim().isEmpty()) {
|
||||
dto.setShippingCost(new BigDecimal(shippingStr.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
if (otherCostField != null) {
|
||||
String otherStr = getValue(rowData, otherCostField);
|
||||
if (otherStr != null && !otherStr.trim().isEmpty()) {
|
||||
dto.setOtherCost(new BigDecimal(otherStr.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
if (receivedAmountField != null) {
|
||||
String receivedStr = getValue(rowData, receivedAmountField);
|
||||
if (receivedStr != null && !receivedStr.trim().isEmpty()) {
|
||||
dto.setReceivedAmount(new BigDecimal(receivedStr.trim()));
|
||||
}
|
||||
}
|
||||
|
||||
if (orderDateField != null) {
|
||||
String dateStr = getValue(rowData, 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;
|
||||
}
|
||||
|
||||
// ==================== Excel 单元格读取辅助 ====================
|
||||
|
||||
/**
|
||||
* 将 Cell 转换为字符串(处理日期、数值等类型)
|
||||
*/
|
||||
private String getCellStringValue(Cell cell) {
|
||||
if (cell == null) return "";
|
||||
switch (cell.getCellType()) {
|
||||
case STRING:
|
||||
return cell.getStringCellValue();
|
||||
case NUMERIC:
|
||||
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {
|
||||
java.util.Date date = cell.getDateCellValue();
|
||||
java.time.LocalDateTime ldt = java.time.LocalDateTime.ofInstant(
|
||||
date.toInstant(), java.time.ZoneId.systemDefault());
|
||||
return ldt.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
|
||||
}
|
||||
double dv = cell.getNumericCellValue();
|
||||
if (dv == Math.floor(dv)) {
|
||||
return String.valueOf((long) dv);
|
||||
}
|
||||
return String.valueOf(dv);
|
||||
case BOOLEAN:
|
||||
return String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA:
|
||||
try {
|
||||
return cell.getStringCellValue();
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
return String.valueOf(cell.getNumericCellValue());
|
||||
} catch (Exception ex) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
case BLANK:
|
||||
case _NONE:
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== Worker 线程循环 ====================
|
||||
|
||||
/**
|
||||
@@ -396,10 +937,10 @@ public class OrderImportProcessor {
|
||||
|
||||
if (dto.getProductSpecId() == null) {
|
||||
// 重新获取关键字段
|
||||
String specCodeRaw = getValue(row.record, row.fieldMapping.get("spec_code"));
|
||||
String productCode = getValue(row.record, row.fieldMapping.get("product_code"));
|
||||
String linkProductName = getValue(row.record, row.fieldMapping.get("link_product_name"));
|
||||
String linkSpecName = getValue(row.record, row.fieldMapping.get("link_spec_name"));
|
||||
String specCodeRaw = getValue(row.rowData, row.fieldMapping.get("spec_code"));
|
||||
String productCode = getValue(row.rowData, row.fieldMapping.get("product_code"));
|
||||
String linkProductName = getValue(row.rowData, row.fieldMapping.get("link_product_name"));
|
||||
String linkSpecName = getValue(row.rowData, row.fieldMapping.get("link_spec_name"));
|
||||
|
||||
if (specCodeRaw != null) specCodeRaw = specCodeRaw.trim();
|
||||
if (productCode != null) productCode = productCode.trim().isEmpty() ? null : productCode.trim();
|
||||
|
||||
Reference in New Issue
Block a user