mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:59:20 +08:00
fix: 修复导入文件编码检测及上传区域样式
This commit is contained in:
+3
-3
@@ -13,11 +13,11 @@ import lombok.Data;
|
||||
public class CreateImportMappingDTO {
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)
|
||||
*/
|
||||
@Schema(description = "导入类型", example = "PRODUCT", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS"})
|
||||
@Schema(description = "导入类型", example = "PRODUCT", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS", "PROMOTION_FEE"})
|
||||
@NotBlank(message = "导入类型不能为空")
|
||||
@Pattern(regexp = "^(PRODUCT|ORDER|ORDER_STATUS)$", message = "导入类型只能是PRODUCT、ORDER或ORDER_STATUS")
|
||||
@Pattern(regexp = "^(PRODUCT|ORDER|ORDER_STATUS|PROMOTION_FEE)$", message = "导入类型只能是PRODUCT、ORDER、ORDER_STATUS或PROMOTION_FEE")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -11,9 +11,9 @@ import lombok.Data;
|
||||
public class ImportMappingFilterDTO {
|
||||
|
||||
/**
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)
|
||||
* 导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)
|
||||
*/
|
||||
@Schema(description = "导入类型", example = "PRODUCT", allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS"})
|
||||
@Schema(description = "导入类型", example = "PRODUCT", allowableValues = {"PRODUCT", "ORDER", "ORDER_STATUS", "PROMOTION_FEE"})
|
||||
private String type;
|
||||
|
||||
/**
|
||||
|
||||
+3
-3
@@ -21,11 +21,11 @@ public class CreateImportTaskDTO {
|
||||
private Long shopId;
|
||||
|
||||
/**
|
||||
* 导入类型(product-商品 order-订单)
|
||||
* 导入类型(product-商品 order-订单 promotion_record-推广记录)
|
||||
*/
|
||||
@Schema(description = "导入类型", example = "product", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"product", "order"})
|
||||
@Schema(description = "导入类型", example = "product", requiredMode = Schema.RequiredMode.REQUIRED, allowableValues = {"product", "order", "promotion_record"})
|
||||
@NotBlank(message = "导入类型不能为空")
|
||||
@Pattern(regexp = "^(product|order)$", message = "导入类型只能是product或order")
|
||||
@Pattern(regexp = "^(product|order|promotion_record)$", message = "导入类型只能是product、order或promotion_record")
|
||||
private String type;
|
||||
|
||||
/**
|
||||
|
||||
+3
-2
@@ -45,7 +45,7 @@ public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService
|
||||
ImportTaskProcessorService importTaskProcessorService) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.importTaskProcessorService = importTaskProcessorService;
|
||||
this.executorService = Executors.newFixedThreadPool(2);
|
||||
this.executorService = Executors.newFixedThreadPool(3);
|
||||
}
|
||||
|
||||
@jakarta.annotation.PostConstruct
|
||||
@@ -67,9 +67,10 @@ public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService
|
||||
public void startConsumers() {
|
||||
if (running.compareAndSet(false, true)) {
|
||||
logger.info("启动导入任务消费者...");
|
||||
// 启动两个消费者线程(一个处理订单,一个处理商品)
|
||||
// 启动三个消费者线程(订单、商品、推广费)
|
||||
executorService.submit(() -> consumeLoop("order"));
|
||||
executorService.submit(() -> consumeLoop("product"));
|
||||
executorService.submit(() -> consumeLoop("promotion_record"));
|
||||
logger.info("导入任务消费者已启动");
|
||||
}
|
||||
}
|
||||
|
||||
+130
-18
@@ -16,6 +16,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusSe
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.impl.PromotionFeeImportProcessor;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopProductRelationMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
@@ -26,7 +27,12 @@ import top.xyquan.ecomdmbbackend.modules.sys.file.model.vo.SysFileVO;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -53,6 +59,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
// 提取出的处理器
|
||||
private final OrderImportProcessor orderImportProcessor;
|
||||
private final ProductSpecImportHelper productSpecImportHelper;
|
||||
private final PromotionFeeImportProcessor promotionFeeImportProcessor;
|
||||
|
||||
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
|
||||
OrderService orderService,
|
||||
@@ -67,7 +74,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
OrderStatusService orderStatusService,
|
||||
SqlSessionFactory sqlSessionFactory,
|
||||
OssService ossService,
|
||||
SysFileService sysFileService) {
|
||||
SysFileService sysFileService,
|
||||
PromotionFeeImportProcessor promotionFeeImportProcessor) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.productSpecService = productSpecService;
|
||||
this.orderMapper = orderMapper;
|
||||
@@ -80,6 +88,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
this.sqlSessionFactory = sqlSessionFactory;
|
||||
this.ossService = ossService;
|
||||
this.sysFileService = sysFileService;
|
||||
this.promotionFeeImportProcessor = promotionFeeImportProcessor;
|
||||
|
||||
// 初始化 helper 和 processor
|
||||
this.productSpecImportHelper = new ProductSpecImportHelper(
|
||||
@@ -103,6 +112,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
processOrderImport(task);
|
||||
} else if ("product".equals(task.getType())) {
|
||||
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
|
||||
} else if ("promotion_record".equals(task.getType())) {
|
||||
processPromotionFeeImport(task);
|
||||
} else {
|
||||
throw new BusinessException("不支持的导入类型: " + task.getType());
|
||||
}
|
||||
@@ -210,6 +221,76 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
}
|
||||
}
|
||||
|
||||
private void processPromotionFeeImport(ImportTaskPO task) throws Exception {
|
||||
com.fasterxml.jackson.databind.JsonNode rootNode;
|
||||
try {
|
||||
rootNode = objectMapper.readTree(task.getMapping());
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析映射配置失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
Map<String, String> fieldMapping = new java.util.HashMap<>();
|
||||
com.fasterxml.jackson.databind.JsonNode fieldMappingNode = rootNode.get("fieldMapping");
|
||||
if (fieldMappingNode != null && fieldMappingNode.isArray()) {
|
||||
for (com.fasterxml.jackson.databind.JsonNode fieldNode : fieldMappingNode) {
|
||||
String fieldName = fieldNode.has("fieldName") ? fieldNode.get("fieldName").asText() : null;
|
||||
String fileFieldName = fieldNode.has("fileFieldName") ? fieldNode.get("fileFieldName").asText() : null;
|
||||
if (fieldName != null && fileFieldName != null) {
|
||||
fieldMapping.put(fieldName, fileFieldName);
|
||||
}
|
||||
}
|
||||
}
|
||||
String feeDateStr = rootNode.has("feeDate") ? rootNode.get("feeDate").asText() : null;
|
||||
|
||||
File csvFile = null;
|
||||
File tempOssFile = null;
|
||||
|
||||
try {
|
||||
SysFileVO fileInfo = sysFileService.getFileById(task.getFileId());
|
||||
if (fileInfo == null) throw new BusinessException("文件不存在,fileId: " + task.getFileId());
|
||||
|
||||
String storagePath = fileInfo.getStoragePath();
|
||||
String storageType = fileInfo.getStorageType();
|
||||
String filename = fileInfo.getFilename();
|
||||
boolean isExcel = filename != null && (filename.toLowerCase().endsWith(".xlsx") || filename.toLowerCase().endsWith(".xls"));
|
||||
|
||||
if ("local".equals(storageType)) {
|
||||
File localFile = new File(storagePath);
|
||||
if (!localFile.exists() || !localFile.isFile()) {
|
||||
throw new BusinessException("本地文件不存在: " + storagePath);
|
||||
}
|
||||
csvFile = localFile;
|
||||
} else {
|
||||
String fileExt = isExcel ? (filename.toLowerCase().endsWith(".xlsx") ? ".xlsx" : ".xls") : ".csv";
|
||||
tempOssFile = java.io.File.createTempFile("import-promotion-fee-", fileExt);
|
||||
if (!ossService.downloadFile(storagePath, tempOssFile)) {
|
||||
throw new BusinessException("从对象存储下载文件失败");
|
||||
}
|
||||
csvFile = tempOssFile;
|
||||
}
|
||||
|
||||
// 前端 wizard 生成的 patched CSV 固定为 UTF-8,避免被误判为 GBK 导致表头乱码
|
||||
boolean isPatchedPromotionCsv = filename != null
|
||||
&& filename.toLowerCase().contains("promotion_fee_import_patched");
|
||||
Charset charset = isExcel || isPatchedPromotionCsv ? StandardCharsets.UTF_8
|
||||
: detectFileEncoding(new java.io.BufferedInputStream(new java.io.FileInputStream(csvFile)));
|
||||
PromotionFeeImportProcessor.ImportResult result = promotionFeeImportProcessor.processImport(
|
||||
task, csvFile, charset, fieldMapping, feeDateStr);
|
||||
|
||||
String finalStatus = result.failCount == 0 ? "success" : (result.successCount > 0 ? "success" : "failed");
|
||||
String summary = String.format("导入完成,处理 %d 条,成功 %d 条,失败 %d 条",
|
||||
result.totalCount, result.successCount, result.failCount);
|
||||
String message = summary;
|
||||
if (result.detailMessage != null && !result.detailMessage.isBlank()) {
|
||||
message += "\n" + result.detailMessage;
|
||||
}
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
|
||||
} finally {
|
||||
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) {
|
||||
try {
|
||||
if (mappingJson == null || mappingJson.trim().isEmpty()) {
|
||||
@@ -303,31 +384,62 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
}
|
||||
|
||||
private Charset detectFileEncoding(InputStream inputStream) throws IOException {
|
||||
inputStream.mark(8196);
|
||||
byte[] bom = new byte[3];
|
||||
int bomRead = inputStream.read(bom);
|
||||
boolean hasUtf8Bom = bomRead >= 3 && bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF;
|
||||
inputStream.reset();
|
||||
if (hasUtf8Bom) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
byte[] sample = inputStream.readNBytes(8192);
|
||||
inputStream.reset();
|
||||
if (sample.length > 0 && isStrictValidUtf8(sample)) {
|
||||
return StandardCharsets.UTF_8;
|
||||
}
|
||||
|
||||
Charset[] charsets = {
|
||||
Charset.forName("GBK"),
|
||||
Charset.forName("GB2312"),
|
||||
Charset.forName("UTF-8"),
|
||||
Charset.forName("ISO-8859-1")
|
||||
};
|
||||
for (Charset charset : charsets) {
|
||||
try {
|
||||
inputStream.mark(2048);
|
||||
char[] buffer = new char[2048];
|
||||
int read = new java.io.InputStreamReader(inputStream, charset).read(buffer);
|
||||
if (read > 0) {
|
||||
String content = new String(buffer, 0, read);
|
||||
inputStream.reset();
|
||||
if (content.contains("商家") || content.contains("编码") ||
|
||||
content.contains("商品") || content.contains("订单") ||
|
||||
content.contains("规格") || content.contains("金额")) {
|
||||
return charset;
|
||||
}
|
||||
}
|
||||
inputStream.reset();
|
||||
} catch (Exception e) {
|
||||
// 忽略编码检测错误
|
||||
String content = decodeSample(sample, charset);
|
||||
if (content != null && containsChineseImportKeywords(content)) {
|
||||
return charset;
|
||||
}
|
||||
}
|
||||
return Charset.forName("GBK");
|
||||
}
|
||||
|
||||
private static boolean isStrictValidUtf8(byte[] bytes) {
|
||||
CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
|
||||
.onMalformedInput(CodingErrorAction.REPORT)
|
||||
.onUnmappableCharacter(CodingErrorAction.REPORT);
|
||||
try {
|
||||
decoder.decode(ByteBuffer.wrap(bytes));
|
||||
return true;
|
||||
} catch (CharacterCodingException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String decodeSample(byte[] sample, Charset charset) {
|
||||
if (sample.length == 0) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return charset.decode(ByteBuffer.wrap(sample)).toString();
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean containsChineseImportKeywords(String content) {
|
||||
return content.contains("商家") || content.contains("编码")
|
||||
|| content.contains("商品") || content.contains("订单")
|
||||
|| content.contains("规格") || content.contains("金额")
|
||||
|| content.contains("推广") || content.contains("花费");
|
||||
}
|
||||
}
|
||||
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.importtask.util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* 导入任务明细消息拼接器,限制明细条数与 UTF-8 字节长度,避免写入任务表时溢出。
|
||||
*/
|
||||
public class ImportTaskMessageAppender {
|
||||
|
||||
/** 预留摘要等文案空间,略小于 {@code ImportTaskProcessorServiceImpl} 的 60000 字节上限 */
|
||||
private static final int MAX_MESSAGE_BYTES = 55_000;
|
||||
private static final int MAX_DETAIL_LINES = 100;
|
||||
|
||||
private final StringBuilder buffer = new StringBuilder();
|
||||
private int detailLineCount;
|
||||
private int suppressedLineCount;
|
||||
|
||||
/**
|
||||
* 追加一行明细;超出条数或字节上限时仅累计抑制条数,不再写入。
|
||||
*
|
||||
* @return 是否已写入 buffer
|
||||
*/
|
||||
public boolean appendDetailLine(String line) {
|
||||
if (line == null || line.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
if (detailLineCount >= MAX_DETAIL_LINES) {
|
||||
suppressedLineCount++;
|
||||
return false;
|
||||
}
|
||||
String entry = line.strip() + System.lineSeparator();
|
||||
if (currentUtf8Length() + entry.getBytes(StandardCharsets.UTF_8).length > MAX_MESSAGE_BYTES) {
|
||||
suppressedLineCount++;
|
||||
return false;
|
||||
}
|
||||
buffer.append(entry);
|
||||
detailLineCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
public int getSuppressedLineCount() {
|
||||
return suppressedLineCount;
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return buffer.length() == 0 && suppressedLineCount == 0;
|
||||
}
|
||||
|
||||
public String build() {
|
||||
if (suppressedLineCount > 0) {
|
||||
String suffix = String.format("(另有 %d 条明细未展示)%n", suppressedLineCount);
|
||||
if (currentUtf8Length() + suffix.getBytes(StandardCharsets.UTF_8).length <= MAX_MESSAGE_BYTES) {
|
||||
buffer.append(suffix);
|
||||
}
|
||||
}
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
private int currentUtf8Length() {
|
||||
return buffer.toString().getBytes(StandardCharsets.UTF_8).length;
|
||||
}
|
||||
}
|
||||
+11
@@ -13,9 +13,13 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.CreatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.PromotionFeeFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotionFeeDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeFieldVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeFieldConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 推广费记录控制器
|
||||
*/
|
||||
@@ -69,4 +73,11 @@ public class PromotionFeeController {
|
||||
PageResultVO<PromotionFeeVO> result = promotionFeeService.getPromotionFeePage(pageQueryDTO);
|
||||
return ApiResponse.success("获取推广费记录列表成功", result);
|
||||
}
|
||||
|
||||
@GetMapping("/fields")
|
||||
@Operation(summary = "获取推广费导入字段定义", description = "获取推广费导入时可映射的系统字段列表")
|
||||
@RequirePermission(value = "ecom:order:read", description = "查询导入字段", allowSuper = true)
|
||||
public ApiResponse<List<PromotionFeeFieldVO>> getPromotionFeeFields() {
|
||||
return ApiResponse.success("获取推广费导入字段成功", PromotionFeeFieldConstants.FIELDS);
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class PromotionFeeFieldConstants {
|
||||
|
||||
public static final List<PromotionFeeFieldVO> FIELDS = Arrays.asList(
|
||||
create("campaignName", "推广活动名称", "推广活动名称", true, 1, "string"),
|
||||
create("feeAmount", "推广费金额", "推广费金额(元)", true, 2, "number")
|
||||
);
|
||||
|
||||
private static PromotionFeeFieldVO create(String fieldName, String fieldLabel, String fileFieldName,
|
||||
boolean required, int sort, String dataType) {
|
||||
PromotionFeeFieldVO vo = new PromotionFeeFieldVO();
|
||||
vo.setFieldName(fieldName);
|
||||
vo.setFieldLabel(fieldLabel);
|
||||
vo.setFileFieldName(fileFieldName);
|
||||
vo.setRequired(required);
|
||||
vo.setSort(sort);
|
||||
vo.setDataType(dataType);
|
||||
return vo;
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "推广费导入字段信息VO")
|
||||
public class PromotionFeeFieldVO {
|
||||
|
||||
@Schema(description = "数据库字段名", example = "campaign_name")
|
||||
private String fieldName;
|
||||
|
||||
@Schema(description = "中文字段名", example = "推广活动名称")
|
||||
private String fieldLabel;
|
||||
|
||||
@Schema(description = "建议的文件字段名", example = "活动名称")
|
||||
private String fileFieldName;
|
||||
|
||||
@Schema(description = "是否必填", example = "true")
|
||||
private Boolean required;
|
||||
|
||||
@Schema(description = "排序", example = "1")
|
||||
private Integer sort;
|
||||
|
||||
@Schema(description = "数据类型", example = "string")
|
||||
private String dataType;
|
||||
}
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.apache.commons.csv.CSVFormat;
|
||||
import org.apache.commons.csv.CSVParser;
|
||||
import org.apache.commons.csv.CSVRecord;
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.util.ImportTaskMessageAppender;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
|
||||
|
||||
import java.io.*;
|
||||
import java.math.BigDecimal;
|
||||
import java.nio.charset.Charset;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* 推广费导入处理器
|
||||
* 负责解析 CSV/Excel 文件中的推广费数据,按字段映射提取 campaignName/feeAmount,
|
||||
* 从文件列中直接读取 feeTypeId/categoryId/productId,批量写入 ec_promotion_fee 表。
|
||||
*/
|
||||
@Service
|
||||
public class PromotionFeeImportProcessor extends ServiceImpl<PromotionFeeMapper, PromotionFeePO> {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(PromotionFeeImportProcessor.class);
|
||||
/** 每批插入条数 */
|
||||
private static final int BATCH_SIZE = 500;
|
||||
/** 推广费金额不合规时的统一失败原因 */
|
||||
private static final String INVALID_FEE_AMOUNT_REASON = "推广费金额为空或须大于0";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public PromotionFeeImportProcessor(ObjectMapper objectMapper) {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行导入
|
||||
*/
|
||||
public ImportResult processImport(ImportTaskPO task, File file, Charset charset,
|
||||
Map<String, String> fieldMapping, String feeDateStr) throws Exception {
|
||||
boolean isExcel = file.getName().toLowerCase().endsWith(".xlsx")
|
||||
|| file.getName().toLowerCase().endsWith(".xls");
|
||||
ParseResult parseResult = isExcel
|
||||
? parseExcel(file, fieldMapping, feeDateStr, task)
|
||||
: parseCsv(file, charset, fieldMapping, feeDateStr, task);
|
||||
|
||||
if (parseResult.totalCount == 0) {
|
||||
return new ImportResult(0, 0, 0, "文件中没有有效数据");
|
||||
}
|
||||
|
||||
int success = 0;
|
||||
int insertFailCount = 0;
|
||||
ImportTaskMessageAppender detailMessages = parseResult.detailMessages;
|
||||
|
||||
for (int i = 0; i < parseResult.records.size(); i += BATCH_SIZE) {
|
||||
int end = Math.min(i + BATCH_SIZE, parseResult.records.size());
|
||||
List<PromotionFeePO> batch = parseResult.records.subList(i, end);
|
||||
try {
|
||||
saveBatch(batch);
|
||||
success += batch.size();
|
||||
} catch (Exception e) {
|
||||
insertFailCount += batch.size();
|
||||
int startRow = parseResult.recordStartRows.get(i);
|
||||
int endRow = parseResult.recordStartRows.get(end - 1);
|
||||
detailMessages.appendDetailLine(String.format("第%d~%d行:批量插入失败,%s",
|
||||
startRow, endRow, e.getMessage()));
|
||||
log.error("批量插入推广费记录失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
return new ImportResult(
|
||||
parseResult.totalCount,
|
||||
success,
|
||||
parseResult.failCount + insertFailCount,
|
||||
detailMessages.build());
|
||||
}
|
||||
|
||||
private ParseResult parseCsv(File file, Charset charset,
|
||||
Map<String, String> fieldMapping, String feeDateStr,
|
||||
ImportTaskPO task) throws IOException {
|
||||
ParseResult result = new ParseResult();
|
||||
try (Reader reader = new InputStreamReader(new FileInputStream(file), charset);
|
||||
CSVParser parser = CSVFormat.DEFAULT.builder()
|
||||
.setHeader()
|
||||
.setSkipHeaderRecord(true)
|
||||
.setTrim(true)
|
||||
.build()
|
||||
.parse(reader)) {
|
||||
|
||||
LocalDate feeDate = parseFeeDate(feeDateStr);
|
||||
Map<String, Integer> headerMap = parser.getHeaderMap();
|
||||
for (CSVRecord record : parser) {
|
||||
int rowNumber = (int) record.getRecordNumber();
|
||||
Function<String, String> cellGetter = colName -> getCsvColumnValue(record, headerMap, colName);
|
||||
collectRow(result, rowNumber, cellGetter, fieldMapping, feeDate, task);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private ParseResult parseExcel(File file, Map<String, String> fieldMapping,
|
||||
String feeDateStr, ImportTaskPO task) throws IOException {
|
||||
ParseResult result = new ParseResult();
|
||||
Workbook workbook = null;
|
||||
try {
|
||||
workbook = file.getName().toLowerCase().endsWith(".xlsx")
|
||||
? createXssfWorkbook(file) : new HSSFWorkbook(new FileInputStream(file));
|
||||
Sheet sheet = workbook.getSheetAt(0);
|
||||
if (sheet == null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Row headerRow = sheet.getRow(0);
|
||||
if (headerRow == null) {
|
||||
return result;
|
||||
}
|
||||
|
||||
Map<String, Integer> headerIndex = new HashMap<>();
|
||||
for (int i = 0; i < headerRow.getLastCellNum(); i++) {
|
||||
Cell cell = headerRow.getCell(i);
|
||||
if (cell != null) {
|
||||
headerIndex.put(normalizeColumnName(getCellStringValue(cell)), i);
|
||||
}
|
||||
}
|
||||
|
||||
LocalDate feeDate = parseFeeDate(feeDateStr);
|
||||
for (int rowIdx = 1; rowIdx <= sheet.getLastRowNum(); rowIdx++) {
|
||||
Row row = sheet.getRow(rowIdx);
|
||||
if (row == null) {
|
||||
continue;
|
||||
}
|
||||
int rowNumber = rowIdx + 1;
|
||||
Function<String, String> cellGetter = colName -> {
|
||||
Integer idx = headerIndex.get(normalizeColumnName(colName));
|
||||
if (idx == null) {
|
||||
return null;
|
||||
}
|
||||
Cell cell = row.getCell(idx);
|
||||
return cell == null ? null : getCellStringValue(cell);
|
||||
};
|
||||
collectRow(result, rowNumber, cellGetter, fieldMapping, feeDate, task);
|
||||
}
|
||||
} finally {
|
||||
if (workbook != null) {
|
||||
try {
|
||||
workbook.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private void collectRow(ParseResult result, int rowNumber, Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, LocalDate feeDate, ImportTaskPO task) {
|
||||
result.totalCount++;
|
||||
RowBuildResult buildResult = buildPo(cellGetter, fieldMapping, feeDate, task);
|
||||
if (buildResult.po != null) {
|
||||
result.records.add(buildResult.po);
|
||||
result.recordStartRows.add(rowNumber);
|
||||
return;
|
||||
}
|
||||
if (buildResult.failReason != null) {
|
||||
result.failCount++;
|
||||
result.detailMessages.appendDetailLine(formatFailLine(rowNumber, buildResult.failReason,
|
||||
buildResult.campaignName));
|
||||
}
|
||||
}
|
||||
|
||||
private static String formatFailLine(int rowNumber, String reason, String campaignName) {
|
||||
if (campaignName != null && !campaignName.isBlank()) {
|
||||
return String.format("第%d行:%s(%s)", rowNumber, reason, campaignName.trim());
|
||||
}
|
||||
return String.format("第%d行:%s", rowNumber, reason);
|
||||
}
|
||||
|
||||
private RowBuildResult buildPo(Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, LocalDate feeDate,
|
||||
ImportTaskPO task) {
|
||||
String campaignName = getMappedValue(cellGetter, fieldMapping, "campaignName");
|
||||
String feeAmountStr = getMappedValue(cellGetter, fieldMapping, "feeAmount");
|
||||
|
||||
if (!isValidFeeAmount(feeAmountStr)) {
|
||||
return RowBuildResult.invalid(INVALID_FEE_AMOUNT_REASON, campaignName);
|
||||
}
|
||||
|
||||
BigDecimal feeAmount = new BigDecimal(normalizeFeeAmount(feeAmountStr));
|
||||
|
||||
PromotionFeePO po = new PromotionFeePO();
|
||||
po.setCompanyId(task.getCompanyId());
|
||||
po.setShopId(task.getShopId());
|
||||
po.setFeeDate(feeDate);
|
||||
po.setFeeTypeId(parseLong(cellGetter.apply("feeTypeId")));
|
||||
po.setCategoryId(parseLong(cellGetter.apply("categoryId")));
|
||||
po.setProductId(parseLong(cellGetter.apply("productId")));
|
||||
po.setCampaignName(campaignName);
|
||||
po.setFeeAmount(feeAmount);
|
||||
po.setCreateBy(task.getCreateBy());
|
||||
po.setUpdateBy(task.getCreateBy());
|
||||
return RowBuildResult.ok(po);
|
||||
}
|
||||
|
||||
private String getCsvColumnValue(CSVRecord record, Map<String, Integer> headerMap, String colName) {
|
||||
String headerKey = resolveHeaderKey(headerMap, colName);
|
||||
if (headerKey == null) {
|
||||
return null;
|
||||
}
|
||||
return record.get(headerKey);
|
||||
}
|
||||
|
||||
private static String resolveHeaderKey(Map<String, Integer> headerMap, String colName) {
|
||||
if (colName == null || colName.isBlank() || headerMap == null) {
|
||||
return null;
|
||||
}
|
||||
String normalized = normalizeColumnName(colName);
|
||||
if (headerMap.containsKey(normalized)) {
|
||||
return normalized;
|
||||
}
|
||||
for (String header : headerMap.keySet()) {
|
||||
if (normalizeColumnName(header).equals(normalized)) {
|
||||
return header;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String normalizeColumnName(String name) {
|
||||
if (name == null) {
|
||||
return "";
|
||||
}
|
||||
return name.replace("\uFEFF", "").trim();
|
||||
}
|
||||
|
||||
private String getMappedValue(Function<String, String> cellGetter,
|
||||
Map<String, String> fieldMapping, String fieldName) {
|
||||
String fileColumn = fieldMapping.get(fieldName);
|
||||
if (fileColumn == null) {
|
||||
return null;
|
||||
}
|
||||
return cellGetter.apply(fileColumn);
|
||||
}
|
||||
|
||||
private static boolean isValidFeeAmount(String feeAmountStr) {
|
||||
if (feeAmountStr == null || feeAmountStr.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
String normalized = normalizeFeeAmount(feeAmountStr);
|
||||
if (normalized.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return new BigDecimal(normalized).compareTo(BigDecimal.ZERO) > 0;
|
||||
} catch (NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeFeeAmount(String feeAmountStr) {
|
||||
return feeAmountStr.trim().replace(",", "");
|
||||
}
|
||||
|
||||
private Long parseLong(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Long.parseLong(value.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate parseFeeDate(String feeDateStr) {
|
||||
if (feeDateStr == null || feeDateStr.isBlank()) {
|
||||
return LocalDate.now();
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(feeDateStr.trim(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
} catch (Exception e) {
|
||||
return LocalDate.now();
|
||||
}
|
||||
}
|
||||
|
||||
private String getCellStringValue(Cell cell) {
|
||||
if (cell == null) {
|
||||
return "";
|
||||
}
|
||||
return switch (cell.getCellType()) {
|
||||
case STRING -> cell.getStringCellValue();
|
||||
case NUMERIC -> {
|
||||
double val = cell.getNumericCellValue();
|
||||
if (val == Math.floor(val) && !Double.isInfinite(val)) {
|
||||
yield String.valueOf((long) val);
|
||||
}
|
||||
yield String.valueOf(val);
|
||||
}
|
||||
case BOOLEAN -> String.valueOf(cell.getBooleanCellValue());
|
||||
case FORMULA -> {
|
||||
try {
|
||||
yield String.valueOf(cell.getNumericCellValue());
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
yield cell.getStringCellValue();
|
||||
} catch (Exception e2) {
|
||||
yield "";
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> "";
|
||||
};
|
||||
}
|
||||
|
||||
private static XSSFWorkbook createXssfWorkbook(File file) throws IOException {
|
||||
try {
|
||||
return new XSSFWorkbook(file);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new IOException("无法打开Excel文件: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static class ParseResult {
|
||||
final List<PromotionFeePO> records = new ArrayList<>();
|
||||
/** 与 records 一一对应,用于插入失败时标注行号 */
|
||||
final List<Integer> recordStartRows = new ArrayList<>();
|
||||
final ImportTaskMessageAppender detailMessages = new ImportTaskMessageAppender();
|
||||
int totalCount;
|
||||
int failCount;
|
||||
}
|
||||
|
||||
private static class RowBuildResult {
|
||||
final PromotionFeePO po;
|
||||
final String failReason;
|
||||
final String campaignName;
|
||||
|
||||
private RowBuildResult(PromotionFeePO po, String failReason, String campaignName) {
|
||||
this.po = po;
|
||||
this.failReason = failReason;
|
||||
this.campaignName = campaignName;
|
||||
}
|
||||
|
||||
static RowBuildResult ok(PromotionFeePO po) {
|
||||
return new RowBuildResult(po, null, null);
|
||||
}
|
||||
|
||||
static RowBuildResult invalid(String reason, String campaignName) {
|
||||
return new RowBuildResult(null, reason, campaignName);
|
||||
}
|
||||
}
|
||||
|
||||
public static class ImportResult {
|
||||
public final int totalCount;
|
||||
public final int successCount;
|
||||
public final int failCount;
|
||||
/** 失败明细(已限制条数与长度) */
|
||||
public final String detailMessage;
|
||||
|
||||
public ImportResult(int totalCount, int successCount, int failCount, String detailMessage) {
|
||||
this.totalCount = totalCount;
|
||||
this.successCount = successCount;
|
||||
this.failCount = failCount;
|
||||
this.detailMessage = detailMessage == null ? "" : detailMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user