fix: 修复导入文件编码检测及上传区域样式

This commit is contained in:
小蟑螂
2026-05-21 20:32:56 +08:00
parent 263b7793a6
commit 047fd866bb
22 changed files with 2288 additions and 64 deletions
+2 -2
View File
@@ -64,7 +64,7 @@ DROP TABLE IF EXISTS `ec_import_mappings`;
CREATE TABLE `ec_import_mappings` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '映射ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`type` enum('PRODUCT','ORDER','ORDER_STATUS') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态)',
`type` enum('PRODUCT','ORDER','ORDER_STATUS', 'PROMOTION_FEE') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(PRODUCT-商品 ORDER-订单 ORDER_STATUS-订单状态 PROMOTION_FEE-推广费)',
`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '映射名称',
`mapping` json NOT NULL COMMENT '映射JSON',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -88,7 +88,7 @@ CREATE TABLE `ec_import_tasks` (
`id` bigint UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`company_id` bigint UNSIGNED NOT NULL COMMENT '所属公司ID',
`shop_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '所属店铺ID',
`type` enum('product','order') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(product-商品 order-订单)',
`type` enum('product','order', 'promotion_record') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '导入类型(product-商品 order-订单 promotion_record-推广记录)',
`task_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '任务名称',
`file_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '原始文件名',
`file_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '关联文件ID',
@@ -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;
/**
@@ -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;
/**
@@ -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;
/**
@@ -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("导入任务消费者已启动");
}
}
@@ -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("花费");
}
}
@@ -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;
}
}
@@ -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);
}
}
@@ -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;
}
}
@@ -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;
}
@@ -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;
}
}
}
@@ -4,10 +4,64 @@ import { h } from 'vue';
import { setupVbenVxeTable, useVbenVxeGrid } from '@vben/plugins/vxe-table';
import { Button, Image } from 'ant-design-vue';
import { Button, Image, Select, TreeSelect } from 'ant-design-vue';
import { CaretUpOutlined, CaretDownOutlined } from '@ant-design/icons-vue';
import { useVbenForm } from './form';
function createArrowHandlers(
getData: () => any[],
getIdx: (data: any[]) => number,
colField: string,
sourceRow: any,
) {
let timer: ReturnType<typeof setTimeout> | null = null;
const copyTo = (targetRow: any) => {
if (targetRow) targetRow[colField] = sourceRow[colField];
};
const copyRange = (from: number, to: number, data: any[]) => {
for (let i = from; i < to; i++) {
copyTo(data[i]);
}
};
const withData = (fn: (data: any[], idx: number) => void) => {
const data = getData();
const idx = getIdx(data);
fn(data, idx);
};
const singleUp = () => {
if (timer) { clearTimeout(timer); timer = null; }
timer = setTimeout(() => {
withData((data, idx) => { if (idx > 0) copyTo(data[idx - 1]); });
timer = null;
}, 200);
};
const dblUp = () => {
if (timer) { clearTimeout(timer); timer = null; }
withData((data, idx) => { if (idx > 0) copyRange(0, idx, data); });
};
const singleDown = () => {
if (timer) { clearTimeout(timer); timer = null; }
timer = setTimeout(() => {
withData((data, idx) => { if (idx >= 0 && idx < data.length - 1) copyTo(data[idx + 1]); });
timer = null;
}, 200);
};
const dblDown = () => {
if (timer) { clearTimeout(timer); timer = null; }
withData((data, idx) => { if (idx < data.length - 1) copyRange(idx + 1, data.length, data); });
};
return { singleUp, dblUp, singleDown, dblDown };
}
setupVbenVxeTable({
configVxeTable: (vxeUI) => {
vxeUI.setConfig({
@@ -19,7 +73,6 @@ setupVbenVxeTable({
},
minHeight: 180,
formConfig: {
// 全局禁用vxe-table的表单配置,使用formOptions
enabled: false,
},
proxyConfig: {
@@ -38,7 +91,6 @@ setupVbenVxeTable({
} as VxeTableGridOptions,
});
// 表格配置项可以用 cellRender: { name: 'CellImage' },
vxeUI.renderer.add('CellImage', {
renderTableDefault(_renderOpts, params) {
const { column, row } = params;
@@ -46,20 +98,107 @@ setupVbenVxeTable({
},
});
// 表格配置项可以用 cellRender: { name: 'CellLink' },
vxeUI.renderer.add('CellLink', {
renderTableDefault(renderOpts) {
const { props } = renderOpts;
return h(
Button,
{ size: 'small', type: 'link' },
{ default: () => props?.text },
);
return h(Button, { size: 'small', type: 'link' }, { default: () => props?.text });
},
});
// 这里可以自行扩展 vxe-table 的全局配置,比如自定义格式化
// vxeUI.formats.add
function sharedGetData($table: any, $grid: any): any[] {
return ($grid as any)?.getTableData?.()?.fullData
|| ($table as any)?.getTableData?.()?.fullData
|| ($table as any)?.tableData
|| [];
}
function sharedGetIdx(data: any[], row: any): number {
const srcIdx = (row as any).__srcRowIndex;
return typeof srcIdx === 'number'
? data.findIndex((r: any) => r.__srcRowIndex === srcIdx)
: data.indexOf(row);
}
vxeUI.renderer.add('CellSelect', {
renderTableDefault(renderOpts, params) {
const { props } = renderOpts;
const { row, column, $table, $grid } = params;
const getData = () => sharedGetData($table, $grid);
const getIdx = (data: any[]) => sharedGetIdx(data, row);
const { singleUp, dblUp, singleDown, dblDown } = createArrowHandlers(getData, getIdx, column.field, row);
const allOptions: any[] = props?.options || [];
const filterField = props?.filterByRowField as string | undefined;
const filterKey = props?.filterOptionKey as string | undefined;
const rowFilterVal = filterField ? row[filterField] : undefined;
const displayOptions = filterField && rowFilterVal && filterKey
? allOptions.filter((opt: any) => String(opt[filterKey]) === String(rowFilterVal))
: allOptions;
return h('div', { style: 'display: flex; align-items: center; gap: 2px;' }, [
h(Select, {
value: row[column.field] ?? undefined,
'onUpdate:value': (val: any) => { row[column.field] = val; },
options: displayOptions,
allowClear: props?.allowClear ?? true,
placeholder: props?.placeholder || '',
showSearch: props?.showSearch ?? false,
filterOption: props?.filterOption,
style: 'flex: 1; min-width: 0;',
size: 'small',
}),
h('div', { style: 'display: flex; flex-direction: column; gap: 0; flex-shrink: 0; width: 18px;' }, [
h(Button, {
size: 'small', type: 'text',
onClick: singleUp, onDblclick: dblUp,
title: '单击复制上一行,双击复制上面全部',
style: 'padding: 0; height: 11px; width: 18px; line-height: 11px; font-size: 8px; border-radius: 2px 2px 0 0; min-width: 0;',
}, { default: () => h(CaretUpOutlined) }),
h(Button, {
size: 'small', type: 'text',
onClick: singleDown, onDblclick: dblDown,
title: '单击复制下一行,双击复制下面全部',
style: 'padding: 0; height: 11px; width: 18px; line-height: 11px; font-size: 8px; border-radius: 0 0 2px 2px; min-width: 0;',
}, { default: () => h(CaretDownOutlined) }),
]),
]);
},
});
vxeUI.renderer.add('CellTreeSelect', {
renderTableDefault(renderOpts, params) {
const { props } = renderOpts;
const { row, column, $table, $grid } = params;
const getData = () => sharedGetData($table, $grid);
const getIdx = (data: any[]) => sharedGetIdx(data, row);
const { singleUp, dblUp, singleDown, dblDown } = createArrowHandlers(getData, getIdx, column.field, row);
return h('div', { style: 'display: flex; align-items: center; gap: 2px;' }, [
h(TreeSelect, {
value: row[column.field] ?? undefined,
'onUpdate:value': (val: any) => { row[column.field] = val; },
treeData: props?.treeData || [],
fieldNames: props?.fieldNames || { label: 'name', value: 'id', children: 'children' },
allowClear: props?.allowClear ?? true,
placeholder: props?.placeholder || '',
treeDefaultExpandAll: props?.treeDefaultExpandAll ?? false,
style: 'flex: 1; min-width: 0;',
size: 'small',
}),
h('div', { style: 'display: flex; flex-direction: column; gap: 0; flex-shrink: 0; width: 18px;' }, [
h(Button, {
size: 'small', type: 'text',
onClick: singleUp, onDblclick: dblUp,
title: '单击复制上一行,双击复制上面全部',
style: 'padding: 0; height: 11px; width: 18px; line-height: 11px; font-size: 8px; border-radius: 2px 2px 0 0; min-width: 0;',
}, { default: () => h(CaretUpOutlined) }),
h(Button, {
size: 'small', type: 'text',
onClick: singleDown, onDblclick: dblDown,
title: '单击复制下一行,双击复制下面全部',
style: 'padding: 0; height: 11px; width: 18px; line-height: 11px; font-size: 8px; border-radius: 0 0 2px 2px; min-width: 0;',
}, { default: () => h(CaretDownOutlined) }),
]),
]);
},
});
},
useVbenForm,
});
@@ -8,6 +8,8 @@ export enum ImportMappingType {
ORDER = 'ORDER',
/** 订单状态 */
ORDER_STATUS = 'ORDER_STATUS',
/** 推广费 */
PROMOTION_FEE = 'PROMOTION_FEE',
}
/**
@@ -17,6 +19,7 @@ export const IMPORT_MAPPING_TYPE_OPTIONS = [
{ label: '商品', value: ImportMappingType.PRODUCT },
{ label: '订单', value: ImportMappingType.ORDER },
{ label: '订单状态', value: ImportMappingType.ORDER_STATUS },
{ label: '推广费', value: ImportMappingType.PROMOTION_FEE },
];
/**
@@ -1,7 +1,7 @@
import { requestClient } from '#/api/request';
import type { PageQueryDTO, PageResultVO } from '#/types/common';
import type { PromotionFeeDTO, PromotionFeeVO } from './types';
import type { PromotionFeeDTO, PromotionFeeVO, PromotionFeeFieldVO } from './types';
/**
* 推广费管理API
@@ -41,3 +41,10 @@ export async function deletePromotionFeeApi(id: number) {
export async function getPromotionFeeByIdApi(id: number) {
return requestClient.get<PromotionFeeVO.Info>(`/ec/promotion-fee/${id}`);
}
/**
* 获取推广费导入字段定义
*/
export async function getPromotionFeeFieldsApi() {
return requestClient.get<PromotionFeeFieldVO.Info[]>('/ec/promotion-fee/fields');
}
@@ -45,3 +45,15 @@ export namespace PromotionFeeVO {
updateBy?: number;
}
}
export namespace PromotionFeeFieldVO {
/** 推广费导入字段信息 */
export interface Info {
fieldName: string;
fieldLabel: string;
fileFieldName?: string;
required: boolean;
sort?: number;
dataType?: string;
}
}
@@ -13,13 +13,30 @@ const routes: RouteRecordRaw[] = [
{
name: 'DataImport',
path: '/data/import',
/** 与 `router.push('/import')` 等同页,地址栏可保持为 `/import` */
alias: '/import',
component: () => import('#/views/ecommerce/order-import/index.vue'),
redirect: '/data/import/order',
meta: {
icon: 'lucide:upload',
title: '数据导入',
},
children: [
{
name: 'DataImportOrder',
path: 'order',
alias: '/import/order',
component: () => import('#/views/ecommerce/import/order/index.vue'),
meta: {
title: '订单导入',
},
},
{
name: 'DataImportPromotionFee',
path: 'promotion-fee',
component: () => import('#/views/ecommerce/import/promotion-fee/index.vue'),
meta: {
title: '推广费导入',
},
},
],
},
{
name: 'PlatformManagement',
@@ -39,11 +39,16 @@ const EMPTY_WORKBENCH: WorkbenchVO.Info = {
const router = useRouter();
const ImportOrderIcon = createIconifyIcon('lucide:upload');
const PromotionFeeIcon = createIconifyIcon('lucide:dollar-sign');
function goToImportOrder() {
void router.push('/import/order');
}
function goToImportPromotionFee() {
void router.push('/data/import/promotion-fee');
}
/** 与全店概览一致:快捷区间 + 自定义 RangePicker */
const dateRange = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
dayjs().startOf('month'),
@@ -353,6 +358,15 @@ onUnmounted(() => {
<ImportOrderIcon class="mr-1.5 h-4 w-4 shrink-0" />
导入订单
</Button>
<Button
type="default"
size="small"
class="!inline-flex !h-9 shrink-0 !items-center !rounded-xl !border-slate-200 !px-4 !text-sm !font-bold !shadow-sm dark:!border-[hsl(240deg_3.7%_22%)]"
@click="goToImportPromotionFee"
>
<PromotionFeeIcon class="mr-1.5 h-4 w-4 shrink-0" />
导入推广费
</Button>
<div
class="flex min-h-[44px] w-full items-center gap-2 rounded-2xl border border-slate-200 bg-slate-200/50 px-3 sm:w-auto dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/30%)]"
>
@@ -3,7 +3,7 @@ import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message, Spin } from 'ant-design-vue';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'FileUploadArea' });
@@ -102,7 +102,7 @@ const handleFileSelect = (e: Event) => {
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors"
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
@@ -110,6 +110,7 @@ const handleFileSelect = (e: Event) => {
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<div class="space-y-4">
<div class="relative mx-auto h-12 w-12">
@@ -135,15 +136,6 @@ const handleFileSelect = (e: Event) => {
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
<Button
@click="triggerFileInput"
type="primary"
ghost
:disabled="loading"
:loading="loading"
>
选择文件
</Button>
</div>
<input
ref="fileInputRef"
@@ -5,6 +5,11 @@
import Papa from 'papaparse';
import * as XLSX from 'xlsx';
export interface FileParseOptions {
/** 为 true 时保留仅部分单元格为空的行(推广费导入需统计金额为空等失败行) */
preserveEmptyRows?: boolean;
}
export interface FileParseResult {
/** 解析成功的数据 */
data: any[];
@@ -22,7 +27,10 @@ function isExcelFile(filename: string): boolean {
/**
* 解析 CSV 文件为原始数据
*/
async function parseCSVFile(file: File): Promise<FileParseResult> {
async function parseCSVFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
@@ -36,7 +44,7 @@ async function parseCSVFile(file: File): Promise<FileParseResult> {
result = await new Promise<Papa.ParseResult<any>>((resolve, reject) => {
Papa.parse(file, {
header: true,
skipEmptyLines: true,
skipEmptyLines: options?.preserveEmptyRows ? false : true,
encoding: encoding as any,
complete: (results) => {
resolve(results);
@@ -88,7 +96,10 @@ async function parseCSVFile(file: File): Promise<FileParseResult> {
/**
* 解析 Excel 文件为原始数据
*/
async function parseExcelFile(file: File): Promise<FileParseResult> {
async function parseExcelFile(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
const errors: string[] = [];
const data: any[] = [];
let headers: string[] = [];
@@ -142,8 +153,14 @@ async function parseExcelFile(file: File): Promise<FileParseResult> {
// 其余行是数据
for (let i = 1; i < jsonData.length; i++) {
const row = jsonData[i];
if (!row || row.every((cell) => cell === '' || cell == null)) {
continue; // 跳过空行
if (!row) {
continue;
}
if (
!options?.preserveEmptyRows &&
row.every((cell) => cell === '' || cell == null)
) {
continue;
}
const rowData: Record<string, any> = {};
headers.forEach((header, idx) => {
@@ -179,11 +196,14 @@ async function parseExcelFile(file: File): Promise<FileParseResult> {
/**
* 解析文件为原始数据(自动根据扩展名选择解析器)
*/
export async function parseFileToRawData(file: File): Promise<FileParseResult> {
export async function parseFileToRawData(
file: File,
options?: FileParseOptions,
): Promise<FileParseResult> {
if (isExcelFile(file.name)) {
return parseExcelFile(file);
return parseExcelFile(file, options);
}
return parseCSVFile(file);
return parseCSVFile(file, options);
}
/**
@@ -0,0 +1,163 @@
<script setup lang="ts">
import { ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { message, Spin } from 'ant-design-vue';
defineOptions({ name: 'PromotionFeeFileUploadArea' });
const props = withDefaults(
defineProps<{
loading?: boolean;
}>(),
{
loading: false,
},
);
const emit = defineEmits<Emits>();
const UploadIcon = createIconifyIcon('lucide:upload');
const LoaderIcon = createIconifyIcon('lucide:loader-2');
interface Emits {
(e: 'fileSelected', file: File): void;
}
const isDragOver = ref(false);
const fileInputRef = ref<HTMLInputElement>();
const validateFile = (file: File): boolean => {
const ext = file.name.toLowerCase().split('.').pop() || '';
const allowedExts = ['csv', 'xlsx', 'xls'];
if (!allowedExts.includes(ext)) {
message.error('只能上传 CSV 或 Excel 格式的文件!');
return false;
}
const isLt10M = file.size / 1024 / 1024 < 10;
if (!isLt10M) {
message.error('文件大小不能超过10MB!');
return false;
}
return true;
};
const processFile = (file: File) => {
if (props.loading) return;
if (!validateFile(file)) return;
emit('fileSelected', file);
};
const handleDragOver = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = true;
};
const handleDragLeave = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
};
const handleDrop = (e: DragEvent) => {
e.preventDefault();
isDragOver.value = false;
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
};
const triggerFileInput = () => {
fileInputRef.value?.click();
};
const handleFileSelect = (e: Event) => {
const target = e.target as HTMLInputElement;
const files = target.files;
if (files && files.length > 0) {
const file = files[0];
if (file) {
processFile(file);
}
}
target.value = '';
};
</script>
<template>
<Spin :spinning="loading" tip="正在解析文件...">
<div
class="rounded-lg border-2 border-dashed border-gray-300 dark:border-[hsl(240deg_3.7%_22%)] p-8 text-center transition-colors cursor-pointer"
:class="{
'border-blue-500 bg-blue-50 dark:bg-[hsl(240deg_3.7%_15.9%/20%)]': isDragOver && !loading,
'cursor-not-allowed opacity-60': loading,
}"
@dragover.prevent="!loading && handleDragOver($event)"
@dragleave.prevent="!loading && handleDragLeave($event)"
@drop.prevent="!loading && handleDrop($event)"
@click="!loading && triggerFileInput()"
>
<div class="space-y-4">
<div class="relative mx-auto h-12 w-12">
<UploadIcon
v-if="!loading"
class="h-12 w-12 text-gray-400 dark:text-[hsl(240deg_5%_64.9%)]"
:class="{ 'text-blue-500': isDragOver }"
/>
<LoaderIcon v-else class="h-12 w-12 animate-spin text-blue-500" />
</div>
<div>
<p
class="text-lg font-medium"
:class="loading ? 'text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]' : 'text-gray-700 dark:text-[hsl(0deg_0%_95%)]'"
>
{{
loading
? '正在解析文件,请稍候...'
: '拖拽 CSV 或 Excel 文件到此处或点击上传'
}}
</p>
<p v-if="!loading" class="text-sm text-gray-500 dark:text-[hsl(240deg_5%_64.9%)]">
支持 .csv / .xlsx / .xls 格式,最大 10MB
</p>
</div>
</div>
<input
ref="fileInputRef"
type="file"
accept=".csv,.xlsx,.xls"
style="display: none"
:disabled="loading"
@change="handleFileSelect"
/>
</div>
</Spin>
</template>
<style scoped>
.border-dashed {
transition: all 0.3s ease;
}
.border-dashed:hover {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
:deep(.border-dashed:hover) {
border-color: #1890ff !important;
background-color: #f0f8ff !important;
}
html.dark .border-dashed:hover {
border-color: hsl(240deg 3.7% 40%) !important;
background-color: hsl(240deg 3.7% 15.9% / 15%) !important;
}
</style>
@@ -0,0 +1,843 @@
<script setup lang="ts">
import type { PromotionFeeFieldVO } from '#/api/ecommerce/promotion-fee/types';
import type { ImportMappingVO } from '#/api/ecommerce/import-mapping';
import type { ImportTaskDTO } from '#/api/ecommerce/import-task';
import type { ShopVO } from '#/api/ecommerce/shop/types';
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { Button, DatePicker, Form, Input, message, Select, Spin, Steps } from 'ant-design-vue';
import {
createImportMappingApi,
getImportMappingPageApi,
ImportMappingType,
updateImportMappingApi,
} from '#/api/ecommerce/import-mapping';
import { getPromotionFeeFieldsApi } from '#/api/ecommerce/promotion-fee/apis';
import { getShopPageApi } from '#/api/ecommerce/shop';
import { createImportTaskApi } from '#/api/ecommerce/import-task';
import { useImportTaskStore } from '#/store';
import { uploadFileToOss } from '#/utils/oss-upload';
import dayjs from 'dayjs';
interface FieldMappingItem {
fieldName: string;
fieldLabel: string;
fileFieldName?: string;
required: boolean;
}
defineOptions({ name: 'PromotionFeeImportTaskWizard' });
const emit = defineEmits<{
success: [];
}>();
const currentStep = ref(0);
const fieldDefsLoading = ref(false);
const createTaskSubmitting = ref(false);
const csvHeaders = ref<string[]>([]);
const previewData = defineModel<any[]>('previewData', { default: () => [] });
const originalImportFile = ref<File | null>(null);
const selectedFile = ref<File | null>(null);
const shopList = ref<ShopVO.Info[]>([]);
const selectedShopId = ref<number | undefined>();
const shopLoading = ref(false);
const shopPage = ref(1);
const shopPageSize = ref(20);
const shopHasMore = ref(true);
const shopSearchValue = ref('');
const feeDate = ref<any>(undefined);
const fieldDefs = ref<PromotionFeeFieldVO.Info[]>([]);
const fieldMappings = ref<
Record<string, { fieldDef: PromotionFeeFieldVO.Info; mappedHeader?: string }>
>({});
const mappingTemplates = ref<ImportMappingVO.ImportMappingInfoVO[]>([]);
const selectedTemplateId = ref<number | undefined>();
const selectedTemplateName = ref('');
const templateLoading = ref(false);
const savingTemplate = ref(false);
const templateName = ref('');
const savingFieldToTemplate = ref<null | string>(null);
const currentTemplateMappings = ref<FieldMappingItem[]>([]);
const [SaveTemplateModal, saveTemplateModalApi] = useVbenModal({
draggable: true,
class: 'w-[500px]',
title: '保存映射模板',
showCancelButton: true,
showConfirmButton: true,
confirmText: '保存',
cancelText: '取消',
onConfirm: handleConfirmSaveTemplate,
onCancel() {
templateName.value = '';
saveTemplateModalApi.close();
},
});
const importTaskStore = useImportTaskStore();
const canGoToNextStep = computed(() => {
if (currentStep.value === 0) {
const requiredFields = fieldDefs.value.filter((f) => f.required);
return requiredFields.every((field) => {
const mapping = fieldMappings.value[field.fieldName];
return mapping && mapping.mappedHeader;
});
}
return false;
});
const isMappingFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
return currentMapping?.mappedHeader === templateItem.fileFieldName;
};
const isMappingChangedFromTemplate = (fieldDefId: string): boolean => {
if (!selectedTemplateId.value || currentTemplateMappings.value.length === 0) return false;
const fieldDef = fieldDefs.value.find((f) => f.fieldName === fieldDefId);
if (!fieldDef) return false;
const templateItem = currentTemplateMappings.value.find(
(item) => item.fieldName === fieldDef.fieldName,
);
if (!templateItem) return false;
const currentMapping = fieldMappings.value[fieldDef.fieldName];
if (templateItem.fileFieldName && currentMapping?.mappedHeader !== templateItem.fileFieldName) return true;
return false;
};
const initFieldMappings = () => {
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
let mappedHeader: string | undefined;
if (fieldDef.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === fieldDef.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
};
const fetchShopList = async (reset = false) => {
if (shopLoading.value) return;
try {
shopLoading.value = true;
if (reset) {
shopList.value = [];
shopPage.value = 1;
shopHasMore.value = true;
}
const result = await getShopPageApi({
page: shopPage.value,
pageSize: shopPageSize.value,
filters: { name: shopSearchValue.value || undefined },
});
if (reset) {
shopList.value = result.records || [];
} else {
shopList.value.push(...(result.records || []));
}
shopHasMore.value = (result.records?.length || 0) === shopPageSize.value;
if (shopHasMore.value) shopPage.value++;
} catch (error) {
console.error('获取店铺列表失败:', error);
message.error('获取店铺列表失败');
} finally {
shopLoading.value = false;
}
};
const handleShopSearch = (value: string) => {
shopSearchValue.value = value;
fetchShopList(true);
};
const handleShopScroll = (e: any) => {
const { target } = e;
if (target.scrollTop + target.offsetHeight === target.scrollHeight && shopHasMore.value && !shopLoading.value) {
fetchShopList();
}
};
const fetchFieldDefs = async () => {
try {
fieldDefsLoading.value = true;
const result = await getPromotionFeeFieldsApi();
fieldDefs.value = (result || []) as unknown as PromotionFeeFieldVO.Info[];
initFieldMappings();
} catch (error) {
console.error('获取字段定义失败:', error);
message.error('获取字段定义失败');
} finally {
fieldDefsLoading.value = false;
}
};
const fetchMappingTemplates = async () => {
try {
templateLoading.value = true;
const result = await getImportMappingPageApi({
page: 1,
pageSize: 100,
filters: { type: ImportMappingType.PROMOTION_FEE },
});
mappingTemplates.value = result.records || [];
if (mappingTemplates.value.length > 0 && !selectedTemplateId.value) {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
} catch (error) {
console.error('获取映射模板列表失败:', error);
message.error('获取映射模板列表失败');
} finally {
templateLoading.value = false;
}
};
const handleSelectTemplate = async (value: any) => {
const templateId = typeof value === 'number' ? value : undefined;
if (!templateId) {
selectedTemplateName.value = '';
currentTemplateMappings.value = [];
if (fieldDefs.value.length > 0) initFieldMappings();
return;
}
if (fieldDefs.value.length === 0) return;
const template = mappingTemplates.value.find((t) => t.id === templateId);
if (!template) return;
try {
const mappingItems: FieldMappingItem[] = JSON.parse(template.mapping);
selectedTemplateName.value = template.name;
currentTemplateMappings.value = mappingItems;
const mappings: typeof fieldMappings.value = {};
fieldDefs.value.forEach((fieldDef) => {
const templateItem = mappingItems.find((item) => item.fieldName === fieldDef.fieldName);
let mappedHeader: string | undefined;
if (templateItem?.fileFieldName) {
const matched = csvHeaders.value.find((h) => h === templateItem.fileFieldName);
if (matched) mappedHeader = matched;
}
mappings[fieldDef.fieldName] = { fieldDef, mappedHeader };
});
fieldMappings.value = mappings;
message.success('已应用映射模板');
} catch (error) {
console.error('应用映射模板失败:', error);
message.error('应用映射模板失败,模板格式可能不正确');
}
};
const handleAddFieldToTemplate = async (fieldDefId: string) => {
if (!selectedTemplateId.value) {
message.warning('请先选择一个模板');
return;
}
const mapping = fieldMappings.value[fieldDefId];
if (!mapping || !mapping.mappedHeader) {
message.warning('请先完成该字段的映射');
return;
}
const fieldDef = mapping.fieldDef;
const fieldItem: FieldMappingItem = {
fieldName: fieldDef.fieldName,
fieldLabel: fieldDef.fieldLabel,
fileFieldName: mapping.mappedHeader,
required: fieldDef.required,
};
try {
savingFieldToTemplate.value = fieldDefId;
const template = mappingTemplates.value.find((t) => t.id === selectedTemplateId.value);
if (!template) {
message.error('模板不存在');
return;
}
let mappingItems: FieldMappingItem[] = [];
try {
mappingItems = JSON.parse(template.mapping);
} catch {
mappingItems = [];
}
const existingIdx = mappingItems.findIndex((item) => item.fieldName === fieldDef.fieldName);
if (existingIdx === -1) {
mappingItems.push(fieldItem);
} else {
mappingItems[existingIdx] = fieldItem;
}
const mappingJson = JSON.stringify(mappingItems);
await updateImportMappingApi(selectedTemplateId.value, {
name: template.name,
mapping: mappingJson,
});
template.mapping = mappingJson;
currentTemplateMappings.value = mappingItems;
message.success(`已将「${fieldDef.fieldLabel}」映射添加到模板`);
} catch (error: any) {
console.error('添加到模板失败:', error);
message.error(error?.message || '添加到模板失败');
} finally {
savingFieldToTemplate.value = null;
}
};
const handleSaveTemplate = () => {
if (selectedTemplateId.value) {
message.info('已有模板选中,请使用每行「添加到模板」按钮单独更新字段映射');
return;
}
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
if (mappingItems.length === 0) {
message.warning('请先完成字段映射');
return;
}
templateName.value = '';
saveTemplateModalApi.open();
};
async function handleConfirmSaveTemplate() {
if (!templateName.value.trim()) {
message.warning('请输入模板名称');
return;
}
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定所有必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
try {
savingTemplate.value = true;
saveTemplateModalApi.lock();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
await createImportMappingApi({
type: ImportMappingType.PROMOTION_FEE,
name: templateName.value.trim(),
mapping: JSON.stringify(mappingItems),
});
message.success('保存映射模板成功');
templateName.value = '';
saveTemplateModalApi.close();
await fetchMappingTemplates();
} catch (error: any) {
console.error('保存映射模板失败:', error);
message.error(error?.message || '保存映射模板失败');
} finally {
savingTemplate.value = false;
saveTemplateModalApi.unlock();
}
}
const handleNext = async () => {
if (currentStep.value !== 0) return;
const requiredFields = fieldDefs.value.filter((f) => f.required);
const unMappedFields = requiredFields.filter((field) => {
const mapping = fieldMappings.value[field.fieldName];
return !mapping || !mapping.mappedHeader;
});
if (unMappedFields.length > 0) {
message.warning(`请先绑定必填字段:${unMappedFields.map((f) => f.fieldLabel).join('、')}`);
return;
}
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
await fetchShopList(true);
}
currentStep.value = 1;
};
const handlePrev = () => {
if (currentStep.value > 0) currentStep.value--;
};
const buildPatchedCsv = (): File => {
const headers = [...csvHeaders.value, 'feeTypeId', 'categoryId', 'productId'];
const rows = previewData.value.map((row: any) =>
headers.map((h: string) => {
if (h === 'feeTypeId') return row._feeTypeId ?? '';
if (h === 'categoryId') return row._categoryId ?? '';
if (h === 'productId') return row._productId ?? '';
return row[h] ?? '';
}),
);
const csvContent = `\uFEFF${[
headers.join(','),
...rows.map((r: any[]) => r.map((v: any) => `"${String(v).replace(/"/g, '""')}"`).join(',')),
].join('\n')}`;
return new File([csvContent], buildPatchedFileName(originalImportFile.value?.name || 'data.csv'), {
type: 'text/csv;charset=utf-8',
});
};
const buildPatchedFileName = (_original: string): string => {
return 'promotion_fee_import_patched.csv';
};
const handleCreateTask = async () => {
if (!selectedFile.value && !originalImportFile.value) {
message.error('文件信息丢失,请重新上传');
return;
}
if (selectedShopId.value === undefined) {
message.warning('请选择店铺');
return;
}
if (!feeDate.value) {
message.warning('请选择推广费发生日期');
return;
}
try {
createTaskSubmitting.value = true;
message.loading('正在上传文件...', 0);
const patchedFile = buildPatchedCsv();
const fileInfo = await uploadFileToOss(patchedFile, {
category: 'promotion-fee-import',
errorMessage: '文件上传失败,请重试',
});
message.destroy();
const mappingItems: FieldMappingItem[] = Object.values(fieldMappings.value)
.filter((m) => m.mappedHeader)
.map((m) => ({
fieldName: m.fieldDef.fieldName,
fieldLabel: m.fieldDef.fieldLabel,
fileFieldName: m.mappedHeader,
required: m.fieldDef.required,
}));
const fullMapping = {
fieldMapping: mappingItems,
feeDate: dayjs(feeDate.value).format('YYYY-MM-DD'),
};
const createData: ImportTaskDTO.CreateImportTaskDTO = {
shopId: selectedShopId.value!,
type: 'promotion_record',
fileName: patchedFile.name,
fileId: fileInfo.id,
mapping: JSON.stringify(fullMapping),
};
const task = await createImportTaskApi(createData);
message.success('创建导入任务成功');
importTaskStore.updateTask(task);
await importTaskStore.fetchTasks(true);
importTaskStore.openDropdown();
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
emit('success');
} catch (error: any) {
message.destroy();
console.error('创建导入任务失败:', error);
message.error(error?.message || '创建导入任务失败');
} finally {
createTaskSubmitting.value = false;
}
};
async function open(headers: string[], file?: File) {
csvHeaders.value = headers;
originalImportFile.value = file ?? null;
selectedFile.value = file ?? null;
currentStep.value = 0;
fieldMappings.value = {};
if (shopList.value.length === 0) {
shopSearchValue.value = '';
shopPage.value = 1;
shopHasMore.value = true;
void fetchShopList(true);
}
if (fieldDefs.value.length === 0) {
await fetchFieldDefs();
} else {
initFieldMappings();
}
if (mappingTemplates.value.length === 0) {
await fetchMappingTemplates();
} else if (selectedTemplateId.value) {
await handleSelectTemplate(selectedTemplateId.value);
} else {
const firstTemplate = mappingTemplates.value[0];
if (firstTemplate?.id) {
selectedTemplateId.value = firstTemplate.id;
await handleSelectTemplate(firstTemplate.id);
}
}
}
function reset() {
currentStep.value = 0;
selectedShopId.value = undefined;
feeDate.value = undefined;
fieldMappings.value = {};
csvHeaders.value = [];
previewData.value = [];
selectedFile.value = null;
originalImportFile.value = null;
selectedTemplateId.value = undefined;
}
defineExpose({ open, reset });
const shopOptions = computed(() => {
return shopList.value.map((shop: ShopVO.Info) => ({
label: shop.platformName ? `${shop.name} (${shop.platformName})` : shop.name,
value: shop.id,
}));
});
</script>
<template>
<div
class="import-task-wizard flex h-full min-h-0 w-full flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div class="shrink-0 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]">
<div class="text-base font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]">
创建导入任务
</div>
<p
v-if="selectedFile"
class="mb-0 mt-1 truncate text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ selectedFile.name }} · {{ previewData.length }} 条
</p>
</div>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<div
class="import-task-wizard-main grid min-h-0 min-w-0 w-full flex-1 grid-rows-[auto_minmax(0,1fr)] gap-3 overflow-hidden px-3 py-3"
>
<div class="min-w-0 shrink-0">
<Steps :current="currentStep">
<Steps.Step title="字段映射" />
<Steps.Step title="确认信息" />
</Steps>
</div>
<div class="flex h-full min-h-0 min-w-0 flex-col overflow-hidden">
<div
v-if="currentStep === 0"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden py-2"
>
<div class="mb-3 flex shrink-0 flex-wrap items-center justify-between gap-2 gap-y-3">
<div class="text-sm text-gray-600 dark:text-gray-300">
请为每个推广费字段选择对应的CSV列,必填字段必须绑定
</div>
<div class="flex items-center space-x-2">
<Select
v-model:value="selectedTemplateId"
placeholder="选择已有模板"
class="w-[200px]"
:loading="templateLoading"
allow-clear
@change="handleSelectTemplate"
>
<template #notFoundContent>
<div v-if="templateLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无模板
</div>
</template>
<Select.Option
v-for="template in mappingTemplates"
:key="template.id"
:value="template.id"
>
{{ template.name }}
<span class="ml-2 text-xs text-gray-400 dark:text-gray-500">
({{ new Date(template.createTime).toLocaleDateString() }})
</span>
</Select.Option>
</Select>
<Button :disabled="selectedTemplateId !== undefined" @click="handleSaveTemplate">
保存为模板
</Button>
</div>
</div>
<template v-if="fieldDefsLoading">
<div class="flex min-h-[200px] flex-1 items-center justify-center text-gray-500 dark:text-gray-400">
<Spin size="large" />
<span class="ml-3 text-sm">加载字段定义中…</span>
</div>
</template>
<div
v-else
class="min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-y-contain pr-0.5"
>
<div
v-for="fieldDef in fieldDefs"
:key="fieldDef.fieldName"
class="flex min-w-0 flex-col overflow-hidden rounded-lg border p-0"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'border-red-300 dark:border-red-700'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'border-yellow-200 dark:border-yellow-700'
: isMappingFromTemplate(fieldDef.fieldName)
? 'border-blue-200 dark:border-blue-700'
: 'border-slate-200 dark:border-slate-600'
"
>
<div
class="border-b border-slate-200/90 bg-gradient-to-r to-transparent px-3 py-2.5 dark:border-slate-600"
:class="
fieldDef.required && !fieldMappings[fieldDef.fieldName]?.mappedHeader
? 'from-red-50/90 dark:from-red-950/35'
: isMappingChangedFromTemplate(fieldDef.fieldName)
? 'from-amber-50/75 dark:from-amber-950/30'
: isMappingFromTemplate(fieldDef.fieldName)
? 'from-blue-50/90 dark:from-blue-950/40'
: 'from-blue-50/95 dark:from-blue-950/35'
"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-blue-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-blue-500"
>
系统
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
推广费字段
</span>
</div>
<div class="flex flex-wrap items-center gap-x-2 gap-y-1">
<span class="font-medium leading-snug text-slate-900 dark:text-slate-100">
{{ fieldDef.fieldLabel }}
</span>
<span v-if="fieldDef.required" class="text-xs text-red-500 dark:text-red-400">
必填
</span>
<span
v-if="selectedTemplateId && isMappingFromTemplate(fieldDef.fieldName)"
class="rounded bg-blue-100 px-1.5 py-0.5 text-xs text-blue-700 dark:bg-blue-900/50 dark:text-blue-300"
>
模板映射
</span>
<span
v-if="selectedTemplateId && isMappingChangedFromTemplate(fieldDef.fieldName)"
class="rounded bg-amber-100 px-1.5 py-0.5 text-xs text-amber-800 dark:bg-amber-900/40 dark:text-amber-200"
>
已变更
</span>
</div>
</div>
<div
class="bg-gradient-to-r from-amber-50/90 to-transparent px-3 py-2.5 dark:from-amber-950/25"
>
<div class="mb-2 flex flex-wrap items-center gap-2">
<span
class="shrink-0 rounded bg-amber-600 px-2 py-0.5 text-[11px] font-semibold text-white shadow-sm dark:bg-amber-600"
>
文件
</span>
<span class="text-xs font-medium text-slate-600 dark:text-slate-300">
CSV 列
</span>
</div>
<div class="flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:gap-2">
<Select
v-if="fieldMappings[fieldDef.fieldName]"
v-model:value="fieldMappings[fieldDef.fieldName]!.mappedHeader"
placeholder="选择该字段对应的 CSV 列"
class="w-full min-w-0 sm:flex-1"
show-search
allow-clear
:options="csvHeaders.map((h) => ({ label: h, value: h }))"
/>
<Button
v-if="selectedTemplateId && fieldMappings[fieldDef.fieldName]?.mappedHeader"
size="small"
type="link"
class="h-auto shrink-0 self-start px-0 py-0 sm:self-center"
:disabled="isMappingFromTemplate(fieldDef.fieldName)"
:loading="savingFieldToTemplate === fieldDef.fieldName"
@click="handleAddFieldToTemplate(fieldDef.fieldName)"
>
添加到模板
</Button>
</div>
</div>
</div>
</div>
</div>
<div
v-if="currentStep === 1"
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto py-2"
>
<div class="space-y-4">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="选择店铺" required>
<Select
v-model:value="selectedShopId"
placeholder="请选择店铺"
show-search
:filter-option="false"
:loading="shopLoading"
@search="handleShopSearch"
@popup-scroll="handleShopScroll"
>
<template #notFoundContent>
<div v-if="shopLoading" class="py-4 text-center">
<Spin size="small" />
<div class="mt-2">加载中...</div>
</div>
<div v-else class="py-4 text-center text-gray-400 dark:text-gray-500">
暂无数据
</div>
</template>
<Select.Option
v-for="option in shopOptions"
:key="option.value"
:value="option.value"
:label="option.label"
>
{{ option.label }}
</Select.Option>
</Select>
</Form.Item>
<Form.Item label="发生日期" required>
<DatePicker
v-model:value="feeDate"
placeholder="选择推广费发生日期"
style="width: 100%"
/>
</Form.Item>
</Form>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">字段映射</div>
<div class="space-y-2">
<div
v-for="mapping in Object.values(fieldMappings).filter((m) => m.mappedHeader)"
:key="mapping.fieldDef.fieldName"
class="flex justify-between text-sm"
>
<span class="text-gray-600 dark:text-gray-300">{{ mapping.fieldDef.fieldLabel }}:</span>
<span class="font-medium">{{ mapping.mappedHeader }}</span>
</div>
</div>
</div>
<div class="rounded bg-gray-50 p-4 dark:bg-gray-800">
<div class="mb-2 font-medium">导入配置摘要</div>
<div class="space-y-2">
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">数据行数</span>
<span class="font-medium">{{ previewData.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">已映射字段</span>
<span class="font-medium">{{ Object.values(fieldMappings).filter((m) => m.mappedHeader).length }}/{{ fieldDefs.length }}</span>
</div>
<div class="flex justify-between text-sm">
<span class="text-gray-600 dark:text-gray-300">推广费类型/类目/商品</span>
<span class="font-medium text-green-600">表格中逐行设置</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div
class="flex shrink-0 flex-wrap justify-end gap-2 border-t border-slate-100 bg-slate-50/80 px-3 py-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/40%)]"
>
<Button v-if="currentStep > 0" @click="handlePrev">上一步</Button>
<Button
v-if="currentStep < 1"
type="primary"
:disabled="!canGoToNextStep"
@click="handleNext"
>
下一步
</Button>
<Button
v-if="currentStep === 1"
type="primary"
:loading="createTaskSubmitting"
@click="handleCreateTask"
>
创建导入任务
</Button>
</div>
</div>
<SaveTemplateModal :confirm-loading="savingTemplate">
<Form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<Form.Item label="模板名称" required>
<Input
v-model:value="templateName"
placeholder="请输入模板名称"
:maxlength="50"
show-count
@press-enter="handleConfirmSaveTemplate"
/>
</Form.Item>
</Form>
</SaveTemplateModal>
</template>
<style scoped>
.import-task-wizard-main {
min-height: 0;
}
.import-task-wizard-main > :last-child {
min-height: 0;
align-self: stretch;
}
</style>
@@ -0,0 +1,399 @@
<script setup lang="ts">
import type { VxeGridProps } from '#/adapter/vxe-table';
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue';
import { Page } from '@vben/common-ui';
import { Button, message } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ImportTaskWizard from './components/ImportTaskWizard.vue';
import FileUploadArea from './components/FileUploadArea.vue';
import { parseFileToRawData } from '#/views/ecommerce/import/order/utils/fileParser';
import { getActivePromotionFeeTypeListApi } from '#/api/ecommerce/promotion-fee-type/apis';
import { getCategoryTreeApi } from '#/api/ecommerce/category/apis';
import { getProductPageApi } from '#/api/ecommerce/product/apis';
import type { PromotionFeeTypeVO } from '#/api/ecommerce/promotion-fee-type/types';
import type { CategoryVO } from '#/api/ecommerce/category/types';
import type { ProductVO } from '#/api/ecommerce/product/types';
defineOptions({ name: 'PromotionFeeImport' });
const csvData = ref<any[]>([]);
const csvHeaders = ref<string[]>([]);
const importLoading = ref(false);
const currentFile = ref<File | null>(null);
const tableContainerRef = ref<HTMLElement>();
const tableHeight = ref<number>(600);
const importTaskWizardRef = ref<InstanceType<typeof ImportTaskWizard>>();
const feeTypeOptions = ref<PromotionFeeTypeVO.Info[]>([]);
const categoryTree = ref<CategoryVO.Info[]>([]);
const productList = ref<ProductVO.Info[]>([]);
const loadReferenceData = async () => {
try {
const [feeTypesRes, categoryRes, productRes] = await Promise.all([
getActivePromotionFeeTypeListApi(),
getCategoryTreeApi(),
getProductPageApi({ page: 1, pageSize: 9999, filters: {} }),
]);
feeTypeOptions.value = feeTypesRes as unknown as PromotionFeeTypeVO.Info[];
categoryTree.value = categoryRes as unknown as CategoryVO.Info[];
productList.value = ((productRes as any).records || []) as ProductVO.Info[];
} catch (e) {
console.error('加载参考数据失败', e);
}
};
const gridColumns = computed(() => {
if (csvHeaders.value.length === 0) return [];
const columns: VxeGridProps<any>['columns'] = [
{ type: 'seq' as const, title: '序号', width: 80, fixed: 'left' as const },
];
csvHeaders.value.forEach((header) => {
columns.push({
field: header,
title: header,
minWidth: 150,
showOverflow: 'tooltip' as const,
});
});
columns.push(
{
field: '_feeTypeId',
title: '推广费类型',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: feeTypeOptions.value.map((t) => ({
label: t.typeName,
value: t.id,
})),
allowClear: true,
placeholder: '请选择',
},
},
},
{
field: '_categoryId',
title: '类目',
width: 160,
fixed: 'right' as const,
cellRender: {
name: 'CellTreeSelect',
props: {
treeData: categoryTree.value,
fieldNames: { label: 'name', value: 'id', children: 'children' },
allowClear: true,
placeholder: '请选择',
treeDefaultExpandAll: false,
},
},
},
{
field: '_productId',
title: '商品',
width: 180,
fixed: 'right' as const,
cellRender: {
name: 'CellSelect',
props: {
options: productList.value.map((p) => ({
label: `${p.name}${p.productCode ? ` (${p.productCode})` : ''}`,
value: p.id,
categoryId: (p as any).categoryId,
})),
filterByRowField: '_categoryId',
filterOptionKey: 'categoryId',
allowClear: true,
placeholder: '请选择商品',
showSearch: true,
filterOption: (input: string, option: any) =>
option.label.toLowerCase().includes(input.toLowerCase()),
},
},
},
);
return columns;
});
const gridOptions: VxeGridProps<any> = {
columns: [],
height: tableHeight.value,
border: true,
stripe: true,
rowConfig: { isHover: true, height: 44 },
showOverflow: true,
size: 'small',
data: [],
pagerConfig: {
enabled: true,
pageSize: 50,
pageSizes: [10, 20, 50, 100],
layouts: [
'PrevJump',
'PrevPage',
'Number',
'NextPage',
'NextJump',
'Sizes',
'FullJump',
'Total',
] as (
| 'FullJump'
| 'NextJump'
| 'NextPage'
| 'Number'
| 'PrevJump'
| 'PrevPage'
| 'Sizes'
| 'Total'
)[],
},
proxyConfig: {
ajax: {
query: async ({ page }) => {
if (csvData.value.length === 0) {
return { items: [], total: 0 };
}
const currentPage = page.currentPage || 1;
const pageSize = page.pageSize || 50;
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pageData = csvData.value.slice(startIndex, endIndex);
pageData.forEach((row, i) => {
(row as Record<string, unknown>).__srcRowIndex = startIndex + i;
});
return {
items: pageData,
total: csvData.value.length,
};
},
},
},
};
const gridEvents = {};
const [Grid, gridApi] = useVbenVxeGrid({
gridOptions,
gridEvents,
});
const updateTable = () => {
gridApi.setGridOptions({
columns: gridColumns.value,
height: tableHeight.value,
});
gridApi.reload();
};
const syncWizardOpen = () => {
if (csvData.value.length === 0 || csvHeaders.value.length === 0) return;
nextTick(() => {
importTaskWizardRef.value?.open(
[...csvHeaders.value],
currentFile.value ?? undefined,
);
});
};
const handleFileUpload = async (file: File) => {
importLoading.value = true;
try {
const result = await parseFileToRawData(file, { preserveEmptyRows: true });
if (result.errors.length > 0) {
message.warning(result.errors.join('; '));
}
if (result.data.length === 0) {
message.error('文件没有有效数据');
return;
}
csvData.value = result.data;
csvHeaders.value = result.headers;
currentFile.value = file;
updateTable();
nextTick(() => {
calculateTableHeight();
});
syncWizardOpen();
const fileExt = file.name.toLowerCase().split('.').pop() || '';
const format = ['xlsx', 'xls'].includes(fileExt) ? 'Excel' : 'CSV';
message.success(`成功解析 ${result.data.length} 条数据(${format} 格式)`);
// 加载参考数据用于表格行内下拉选择
await loadReferenceData();
updateTable();
} catch (error: any) {
message.error(`文件读取失败: ${error.message}`);
} finally {
importLoading.value = false;
}
};
const handleClearData = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已清空数据');
};
const handleWizardSuccess = () => {
csvData.value = [];
csvHeaders.value = [];
currentFile.value = null;
importTaskWizardRef.value?.reset();
updateTable();
message.success('已创建导入任务,可继续上传新文件');
};
const calculateTableHeight = () => {
nextTick(() => {
if (tableContainerRef.value) {
const rect = tableContainerRef.value.getBoundingClientRect();
const toolbarReserve = 56;
const padding = 24;
const availableHeight = rect.height - padding - toolbarReserve;
tableHeight.value = Math.max(320, availableHeight);
}
});
};
let resizeObserver: null | ResizeObserver = null;
onMounted(() => {
calculateTableHeight();
if (tableContainerRef.value) {
resizeObserver = new ResizeObserver(() => {
calculateTableHeight();
});
resizeObserver.observe(tableContainerRef.value);
}
});
onUnmounted(() => {
resizeObserver?.disconnect();
});
</script>
<template>
<Page
auto-content-height
:content-padding-class="csvData.length === 0 ? 'p-4 sm:p-6' : 'p-2 sm:p-3'"
content-class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-slate-100 dark:bg-[hsl(222.34deg_10.43%_12.27%)]"
>
<div
v-if="csvData.length === 0"
class="mx-auto flex min-h-0 w-full max-w-3xl flex-1 flex-col items-center justify-center py-8"
>
<div class="mb-10 shrink-0 text-center">
<h1
class="mb-2 text-3xl font-black tracking-tight text-slate-800 dark:text-[hsl(0deg_0%_95%)] sm:text-4xl"
>
推广费导入中心
</h1>
<p
class="text-sm font-medium text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-base"
>
请上传 CSV / Excel 格式的推广费原始数据
</p>
</div>
<div
class="relative w-full overflow-hidden rounded-[2rem] border border-white/50 bg-white/45 p-6 dark:border-[hsl(240deg_3.7%_22%/50%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/80%)] shadow-[0_25px_50px_-12px_rgba(0,0,0,0.1)] dark:shadow-none backdrop-blur-2xl sm:p-8"
>
<div
class="absolute -right-10 -top-10 h-32 w-32 rounded-full bg-indigo-400 opacity-10 blur-3xl"
>
</div>
<div class="relative w-full">
<FileUploadArea
:loading="importLoading"
@file-selected="handleFileUpload"
/>
</div>
</div>
</div>
<div
v-else
class="flex min-h-0 w-full min-w-0 flex-1 flex-row gap-3 overflow-hidden sm:gap-4"
>
<section
class="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-2xl border border-slate-200/80 bg-white/90 shadow-sm dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%/90%)]"
>
<div
class="flex shrink-0 flex-wrap items-center justify-between gap-3 border-b border-slate-100 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)]"
>
<div class="min-w-0">
<h2
class="mb-0.5 text-lg font-bold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
>
数据预览
</h2>
<p
class="m-0 text-xs text-slate-500 dark:text-[hsl(240deg_5%_64.9%)] sm:text-sm"
>
共 {{ csvData.length }} 条 · 右侧配置导入任务
</p>
</div>
<div class="flex shrink-0 flex-wrap items-center justify-end gap-2">
<Button size="small" @click="handleClearData">清空数据</Button>
</div>
</div>
<div
ref="tableContainerRef"
class="flex min-h-0 flex-1 flex-col overflow-hidden p-3 sm:p-4"
>
<Grid />
</div>
</section>
<aside
class="flex min-h-0 w-[min(100%,440px)] shrink-0 flex-col self-stretch overflow-hidden sm:w-[400px] lg:w-[440px]"
>
<div class="flex min-h-0 flex-1 flex-col overflow-hidden">
<ImportTaskWizard
ref="importTaskWizardRef"
v-model:preview-data="csvData"
@success="handleWizardSuccess"
/>
</div>
</aside>
</div>
</Page>
</template>
<style scoped>
:deep(.vxe-grid) {
flex: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
:deep(.vxe-grid--body-wrapper) {
flex: 1;
overflow: auto;
}
</style>