mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 02:39:19 +08:00
wip: 基本完成完成订单导入功能
This commit is contained in:
+39
@@ -0,0 +1,39 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
/**
|
||||
* 导入任务SSE控制器
|
||||
*/
|
||||
@Tag(name = "电商-导入任务SSE", description = "导入任务实时进度推送接口")
|
||||
@RestController
|
||||
@RequestMapping("/ec/import-task/sse")
|
||||
public class ImportTaskSseController {
|
||||
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public ImportTaskSseController(SseNotificationService sseNotificationService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Operation(summary = "建立SSE连接", description = "前端在创建任务前建立SSE连接,用于接收任务进度推送")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
@RequireRole(description = "建立SSE连接", allowUser = true)
|
||||
public SseEmitter connect() {
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
return sseNotificationService.createConnection(userId);
|
||||
}
|
||||
}
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service;
|
||||
|
||||
/**
|
||||
* 导入任务消费者服务接口
|
||||
*/
|
||||
public interface ImportTaskConsumerService {
|
||||
|
||||
/**
|
||||
* 启动消费者
|
||||
*/
|
||||
void startConsumers();
|
||||
|
||||
/**
|
||||
* 停止消费者
|
||||
*/
|
||||
void stopConsumers();
|
||||
}
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service;
|
||||
|
||||
/**
|
||||
* 导入任务处理器服务接口
|
||||
*/
|
||||
public interface ImportTaskProcessorService {
|
||||
|
||||
/**
|
||||
* 处理导入任务
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
void processImportTask(Long taskId);
|
||||
}
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service;
|
||||
|
||||
/**
|
||||
* 导入任务队列服务接口
|
||||
*/
|
||||
public interface ImportTaskQueueService {
|
||||
|
||||
/**
|
||||
* 发布导入任务到队列
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
void publishImportTask(Long taskId);
|
||||
}
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service;
|
||||
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
|
||||
|
||||
/**
|
||||
* SSE通知服务接口
|
||||
*/
|
||||
public interface SseNotificationService {
|
||||
|
||||
/**
|
||||
* 创建SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
*/
|
||||
SseEmitter createConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
void sendTaskProgress(Long userId, ImportTaskVO taskVO);
|
||||
|
||||
/**
|
||||
* 关闭用户的SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void closeConnection(Long userId);
|
||||
|
||||
/**
|
||||
* 检查用户是否有活跃的任务
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 是否有活跃任务
|
||||
*/
|
||||
boolean hasActiveTasks(Long userId);
|
||||
|
||||
/**
|
||||
* 通知所有任务已完成,可以关闭连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
void notifyAllTasksCompleted(Long userId);
|
||||
}
|
||||
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.config.ImportTaskQueueConfig;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskConsumerService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskProcessorService;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 导入任务消费者服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskConsumerServiceImpl implements ImportTaskConsumerService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskConsumerServiceImpl.class);
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
private final ImportTaskProcessorService importTaskProcessorService;
|
||||
|
||||
private final ExecutorService executorService;
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
public ImportTaskConsumerServiceImpl(RedisTemplate<String, Object> redisTemplate,
|
||||
ImportTaskProcessorService importTaskProcessorService) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.importTaskProcessorService = importTaskProcessorService;
|
||||
this.executorService = Executors.newFixedThreadPool(2); // 商品和订单各一个消费者线程
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
// 延迟启动,避免Redis连接失败时阻止应用启动
|
||||
new Thread(() -> {
|
||||
try {
|
||||
// 等待3秒,确保Redis连接已建立
|
||||
Thread.sleep(3000);
|
||||
startConsumers();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
logger.warn("消费者启动线程被中断", e);
|
||||
} catch (Exception e) {
|
||||
logger.error("启动导入任务消费者失败,Redis可能不可用", e);
|
||||
}
|
||||
}, "ImportTaskConsumerStarter").start();
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void destroy() {
|
||||
stopConsumers();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void startConsumers() {
|
||||
if (running.compareAndSet(false, true)) {
|
||||
logger.info("启动导入任务消费者...");
|
||||
|
||||
// 启动商品导入任务消费者
|
||||
executorService.submit(() -> consumeTasks(ImportTaskQueueConfig.IMPORT_TASK_QUEUE_PRODUCT, "product"));
|
||||
|
||||
// 启动订单导入任务消费者
|
||||
executorService.submit(() -> consumeTasks(ImportTaskQueueConfig.IMPORT_TASK_QUEUE_ORDER, "order"));
|
||||
|
||||
logger.info("导入任务消费者已启动");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stopConsumers() {
|
||||
if (running.compareAndSet(true, false)) {
|
||||
logger.info("停止导入任务消费者...");
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
logger.info("导入任务消费者已停止");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费任务
|
||||
*
|
||||
* @param queueName 队列名称
|
||||
* @param type 任务类型
|
||||
*/
|
||||
private void consumeTasks(String queueName, String type) {
|
||||
logger.info("开始消费{}导入任务,队列: {}", type, queueName);
|
||||
|
||||
// 先测试Redis连接
|
||||
try {
|
||||
redisTemplate.getConnectionFactory().getConnection().ping();
|
||||
logger.info("Redis连接正常,开始消费{}导入任务", type);
|
||||
} catch (Exception e) {
|
||||
logger.error("Redis连接失败,无法启动{}导入任务消费者。请检查Redis服务是否运行: {}", type, e.getMessage());
|
||||
return; // Redis不可用时,不启动消费者
|
||||
}
|
||||
|
||||
while (running.get()) {
|
||||
try {
|
||||
// 从队列左侧弹出任务(阻塞式,超时时间5秒)
|
||||
Object taskIdObj = redisTemplate.opsForList().leftPop(queueName, 5, TimeUnit.SECONDS);
|
||||
|
||||
if (taskIdObj != null) {
|
||||
Long taskId = Long.valueOf(taskIdObj.toString());
|
||||
logger.info("从队列获取到{}导入任务,taskId: {}", type, taskId);
|
||||
|
||||
try {
|
||||
// 处理任务
|
||||
importTaskProcessorService.processImportTask(taskId);
|
||||
} catch (Exception e) {
|
||||
logger.error("处理{}导入任务失败,taskId: {}", type, taskId, e);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
if (running.get()) {
|
||||
// 如果是超时异常,这是正常的(队列为空时的等待),只记录debug日志
|
||||
if (e instanceof org.springframework.dao.QueryTimeoutException ||
|
||||
(e.getCause() != null && e.getCause() instanceof io.lettuce.core.RedisCommandTimeoutException)) {
|
||||
logger.debug("{}导入任务队列为空,等待中...", type);
|
||||
} else {
|
||||
// 其他异常才记录为错误
|
||||
logger.error("消费{}导入任务时发生异常", type, e);
|
||||
}
|
||||
// 如果是连接异常,等待更长时间后重试
|
||||
long waitTime = (e.getMessage() != null && e.getMessage().contains("Connection")) ? 5000 : 1000;
|
||||
try {
|
||||
Thread.sleep(waitTime);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("{}导入任务消费者已停止", type);
|
||||
}
|
||||
}
|
||||
|
||||
+735
@@ -0,0 +1,735 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
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.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderStatusMapper;
|
||||
import org.springframework.beans.BeanUtils;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.order.CreateOrderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderStatusPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductSpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskProcessorService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.OrderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.OrderStatusService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ProductSpecService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.SseNotificationService;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 导入任务处理器服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
|
||||
|
||||
private final ImportTaskService importTaskService;
|
||||
private final OrderService orderService;
|
||||
private final ProductService productService;
|
||||
private final ProductSpecService productSpecService;
|
||||
private final OrderStatusService orderStatusService;
|
||||
private final OrderStatusMapper orderStatusMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final ShopService shopService;
|
||||
private final SseNotificationService sseNotificationService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
|
||||
OrderService orderService,
|
||||
ProductService productService,
|
||||
ProductSpecService productSpecService,
|
||||
OrderStatusService orderStatusService,
|
||||
OrderStatusMapper orderStatusMapper,
|
||||
OrderMapper orderMapper,
|
||||
ProductMapper productMapper,
|
||||
ShopService shopService,
|
||||
SseNotificationService sseNotificationService,
|
||||
ObjectMapper objectMapper) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.orderService = orderService;
|
||||
this.productService = productService;
|
||||
this.productSpecService = productSpecService;
|
||||
this.orderStatusService = orderStatusService;
|
||||
this.orderStatusMapper = orderStatusMapper;
|
||||
this.orderMapper = orderMapper;
|
||||
this.productMapper = productMapper;
|
||||
this.shopService = shopService;
|
||||
this.sseNotificationService = sseNotificationService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理导入任务
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
@Override
|
||||
@Transactional
|
||||
public void processImportTask(Long taskId) {
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
logger.error("导入任务不存在,taskId: {}", taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 更新任务状态为处理中
|
||||
updateTaskStatus(taskId, "processing", null, 0, 0, 0);
|
||||
|
||||
try {
|
||||
// 通知前端任务开始处理
|
||||
ImportTaskPO updatedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
|
||||
|
||||
if ("order".equals(task.getType())) {
|
||||
processOrderImport(task);
|
||||
} else if ("product".equals(task.getType())) {
|
||||
// 商品导入逻辑待实现
|
||||
logger.warn("商品导入功能暂未实现,taskId: {}", taskId);
|
||||
updateTaskStatus(taskId, "failed", "商品导入功能暂未实现", 0, 0, 0);
|
||||
} else {
|
||||
throw new BusinessException("不支持的导入类型: " + task.getType());
|
||||
}
|
||||
|
||||
// 通知前端任务完成
|
||||
ImportTaskPO completedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(completedTask));
|
||||
|
||||
} catch (Exception e) {
|
||||
logger.error("处理导入任务失败,taskId: {}", taskId, e);
|
||||
updateTaskStatus(taskId, "failed", "处理失败: " + e.getMessage(), 0, 0, 0);
|
||||
ImportTaskPO failedTask = importTaskService.getById(taskId);
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(failedTask));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理订单导入
|
||||
*
|
||||
* @param task 导入任务
|
||||
*/
|
||||
private void processOrderImport(ImportTaskPO task) throws IOException {
|
||||
// 解析字段映射
|
||||
Map<String, String> mapping = parseMapping(task.getMapping());
|
||||
Long companyId = task.getCompanyId();
|
||||
|
||||
// 读取CSV文件
|
||||
// 处理文件路径:统一转换为实际文件系统路径
|
||||
String filePath = task.getFilePath();
|
||||
File csvFile;
|
||||
|
||||
if (filePath.startsWith("/")) {
|
||||
// 以/开头的路径,去掉开头的/,转换为相对于项目根目录的路径
|
||||
csvFile = new File(System.getProperty("user.dir"), filePath.substring(1));
|
||||
} else if (filePath.contains(":")) {
|
||||
// 包含:的路径,认为是绝对路径(Windows路径如 C:\...)
|
||||
csvFile = new File(filePath);
|
||||
} else {
|
||||
// 相对路径,相对于项目根目录
|
||||
csvFile = new File(System.getProperty("user.dir"), filePath);
|
||||
}
|
||||
|
||||
if (!csvFile.exists() || !csvFile.isFile()) {
|
||||
throw new BusinessException("CSV文件不存在: " + task.getFilePath() + " (实际查找路径: " + csvFile.getAbsolutePath() + ")");
|
||||
}
|
||||
|
||||
// 获取默认订单状态(使用第一个启用的状态)
|
||||
// 注意:在消费者线程中,不能使用CurrentUserContext,所以直接使用Mapper查询
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> statusWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
statusWrapper.eq(OrderStatusPO::getCompanyId, companyId)
|
||||
.eq(OrderStatusPO::getIsActive, 1)
|
||||
.orderByAsc(OrderStatusPO::getSortOrder)
|
||||
.last("LIMIT 1");
|
||||
OrderStatusPO defaultStatus = orderStatusMapper.selectOne(statusWrapper);
|
||||
if (defaultStatus == null) {
|
||||
throw new BusinessException("没有可用的订单状态,请先创建订单状态");
|
||||
}
|
||||
Long defaultStatusId = defaultStatus.getId();
|
||||
|
||||
int totalCount = 0;
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
StringBuilder errorMessages = new StringBuilder();
|
||||
|
||||
// 尝试多种编码读取CSV文件(常见的中文编码)
|
||||
java.nio.charset.Charset charset = detectFileEncoding(csvFile);
|
||||
logger.info("检测到CSV文件编码: {}", charset);
|
||||
|
||||
try (java.io.InputStreamReader reader = new java.io.InputStreamReader(
|
||||
new java.io.FileInputStream(csvFile), charset);
|
||||
CSVParser csvParser = new CSVParser(reader, CSVFormat.DEFAULT.builder()
|
||||
.setHeader()
|
||||
.setSkipHeaderRecord(true)
|
||||
.setIgnoreHeaderCase(true)
|
||||
.setTrim(true) // 自动去除表头和值的前后空格
|
||||
.build())) {
|
||||
|
||||
// 记录CSV表头,用于调试
|
||||
Map<String, Integer> headerMap = csvParser.getHeaderMap();
|
||||
logger.info("CSV表头信息: {}", headerMap);
|
||||
logger.info("字段映射信息: {}", mapping);
|
||||
|
||||
List<CSVRecord> records = csvParser.getRecords();
|
||||
totalCount = records.size();
|
||||
|
||||
// 更新总行数
|
||||
updateTaskStatus(task.getId(), "processing", null, totalCount, 0, 0);
|
||||
|
||||
for (int i = 0; i < records.size(); i++) {
|
||||
CSVRecord record = records.get(i);
|
||||
int rowNumber = i + 2; // 行号从2开始(第1行是表头)
|
||||
|
||||
try {
|
||||
// 解析CSV行数据
|
||||
CreateOrderDTO orderDTO = parseOrderFromCSV(record, mapping, task.getShopId(), defaultStatusId, companyId, task.getCreateBy());
|
||||
|
||||
// 创建订单(复用OrderService.createOrder的业务逻辑,但不依赖CurrentUserContext)
|
||||
createOrderWithoutContext(orderDTO, companyId, task.getCreateBy());
|
||||
successCount++;
|
||||
|
||||
// 每处理10条记录通知一次进度
|
||||
if ((i + 1) % 10 == 0 || (i + 1) == records.size()) {
|
||||
updateTaskStatus(task.getId(), "processing", null, totalCount, successCount, failCount);
|
||||
ImportTaskPO updatedTask = importTaskService.getById(task.getId());
|
||||
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
failCount++;
|
||||
String errorMsg = String.format("第%d行处理失败: %s", rowNumber, e.getMessage());
|
||||
errorMessages.append(errorMsg).append("; ");
|
||||
logger.error("处理订单导入第{}行失败", rowNumber, e);
|
||||
|
||||
// 更新失败计数
|
||||
updateTaskStatus(task.getId(), "processing", null, totalCount, successCount, failCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 更新最终状态
|
||||
String finalStatus = failCount == 0 ? "success" : (successCount > 0 ? "success" : "failed");
|
||||
String message = failCount > 0 ? errorMessages.toString() : "导入完成";
|
||||
updateTaskStatus(task.getId(), finalStatus, message, totalCount, successCount, failCount);
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析字段映射
|
||||
*
|
||||
* @param mappingJson 映射JSON字符串
|
||||
* @return 字段映射Map(实体字段名 -> CSV表头名)
|
||||
*/
|
||||
private Map<String, String> parseMapping(String mappingJson) {
|
||||
try {
|
||||
if (mappingJson == null || mappingJson.trim().isEmpty()) {
|
||||
throw new BusinessException("字段映射不能为空");
|
||||
}
|
||||
// 解析JSON,格式:{"specCode": "商家编码-规格维度", "specName": "商品规格", ...}
|
||||
Map<String, String> mapping = objectMapper.readValue(mappingJson, new TypeReference<Map<String, String>>() {});
|
||||
return mapping;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解析字段映射失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从CSV记录解析订单数据
|
||||
*
|
||||
* @param record CSV记录
|
||||
* @param mapping 字段映射
|
||||
* @param shopId 店铺ID
|
||||
* @param defaultStatusId 默认订单状态ID
|
||||
* @param companyId 公司ID
|
||||
* @param createBy 创建人ID
|
||||
* @return 创建订单DTO
|
||||
*/
|
||||
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, String> mapping,
|
||||
Long shopId, Long defaultStatusId, Long companyId, Long createBy) {
|
||||
CreateOrderDTO orderDTO = new CreateOrderDTO();
|
||||
orderDTO.setShopId(shopId);
|
||||
orderDTO.setStatusId(defaultStatusId);
|
||||
|
||||
// 获取映射的CSV表头名
|
||||
String specCodeHeader = mapping.get("specCode");
|
||||
String receivedAmountHeader = mapping.get("receivedAmount");
|
||||
String orderQuantityHeader = mapping.get("orderQuantity");
|
||||
String orderStatusHeader = mapping.get("orderStatus");
|
||||
String productNameHeader = mapping.get("productName");
|
||||
String specNameHeader = mapping.get("specName");
|
||||
String platformOrderNoHeader = mapping.get("platformOrderNo");
|
||||
|
||||
// 调试日志:记录字段映射
|
||||
if (logger.isDebugEnabled()) {
|
||||
logger.debug("字段映射 - specCodeHeader: {}, receivedAmountHeader: {}, orderQuantityHeader: {}",
|
||||
specCodeHeader, receivedAmountHeader, orderQuantityHeader);
|
||||
}
|
||||
|
||||
// 必填字段验证
|
||||
String specCode = getValue(record, specCodeHeader);
|
||||
if (specCode == null || specCode.trim().isEmpty()) {
|
||||
// 提供更详细的错误信息
|
||||
String availableHeaders = String.join(", ", record.getParser().getHeaderMap().keySet());
|
||||
throw new BusinessException(String.format("规格编码不能为空。映射的表头名: '%s',可用的表头: [%s],当前行的所有值: %s",
|
||||
specCodeHeader, availableHeaders, record.toMap()));
|
||||
}
|
||||
|
||||
String receivedAmountStr = getValue(record, receivedAmountHeader);
|
||||
if (receivedAmountStr == null || receivedAmountStr.trim().isEmpty()) {
|
||||
throw new BusinessException("商家实收金额不能为空");
|
||||
}
|
||||
|
||||
String orderQuantityStr = getValue(record, orderQuantityHeader);
|
||||
if (orderQuantityStr == null || orderQuantityStr.trim().isEmpty()) {
|
||||
throw new BusinessException("订单数量不能为空");
|
||||
}
|
||||
|
||||
// 解析必填字段
|
||||
try {
|
||||
orderDTO.setReceivedAmount(new BigDecimal(receivedAmountStr.trim()));
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("商家实收金额格式错误: " + receivedAmountStr);
|
||||
}
|
||||
|
||||
try {
|
||||
orderDTO.setQuantity(Integer.parseInt(orderQuantityStr.trim()));
|
||||
if (orderDTO.getQuantity() <= 0) {
|
||||
throw new BusinessException("订单数量必须大于0");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
throw new BusinessException("订单数量格式错误: " + orderQuantityStr);
|
||||
}
|
||||
|
||||
// 解析可选字段(先解析,用于后续创建商品和规格)
|
||||
String productName = null;
|
||||
if (productNameHeader != null) {
|
||||
productName = getValue(record, productNameHeader);
|
||||
productName = productName != null ? productName.trim() : null;
|
||||
}
|
||||
|
||||
String specName = null;
|
||||
if (specNameHeader != null) {
|
||||
specName = getValue(record, specNameHeader);
|
||||
specName = specName != null ? specName.trim() : null;
|
||||
}
|
||||
|
||||
// 通过规格编码查找商品规格
|
||||
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId);
|
||||
|
||||
// 如果找不到规格,但有商品名称和规格名称,则自动创建商品和规格
|
||||
if (productSpec == null) {
|
||||
if (productName != null && !productName.isEmpty() &&
|
||||
specName != null && !specName.isEmpty()) {
|
||||
logger.info("未找到规格编码 '{}',但提供了商品名称 '{}' 和规格名称 '{}',将自动创建商品和规格",
|
||||
specCode, productName, specName);
|
||||
productSpec = createProductAndSpecIfNotExists(companyId, productName, specName, specCode.trim(), createBy);
|
||||
} else {
|
||||
throw new BusinessException("未找到规格编码对应的商品规格: " + specCode +
|
||||
(productName == null || productName.isEmpty() ? ",且未提供商品名称" : "") +
|
||||
(specName == null || specName.isEmpty() ? ",且未提供规格名称" : ""));
|
||||
}
|
||||
}
|
||||
|
||||
orderDTO.setProductId(productSpec.getProductId());
|
||||
orderDTO.setProductSpecId(productSpec.getId());
|
||||
orderDTO.setCostPrice(productSpec.getCostPrice());
|
||||
|
||||
// 设置商品名称和规格名称
|
||||
if (productName != null && !productName.isEmpty()) {
|
||||
orderDTO.setProductName(productName);
|
||||
} else {
|
||||
// 如果CSV中没有商品名称,从商品规格关联的商品中获取
|
||||
ProductPO product = productMapper.selectById(productSpec.getProductId());
|
||||
orderDTO.setProductName(product != null ? product.getName() : "");
|
||||
}
|
||||
|
||||
if (specName != null && !specName.isEmpty()) {
|
||||
orderDTO.setSpecName(specName);
|
||||
} else {
|
||||
orderDTO.setSpecName(productSpec.getName());
|
||||
}
|
||||
|
||||
if (platformOrderNoHeader != null) {
|
||||
String platformOrderNo = getValue(record, platformOrderNoHeader);
|
||||
orderDTO.setPlatformOrderNo(platformOrderNo != null ? platformOrderNo.trim() : null);
|
||||
}
|
||||
|
||||
// 计算销售单价(商家实收金额 / 数量)
|
||||
orderDTO.setUnitPrice(orderDTO.getReceivedAmount()
|
||||
.divide(new BigDecimal(orderDTO.getQuantity()), 2, RoundingMode.HALF_UP));
|
||||
|
||||
// 解析订单状态(如果提供了映射)
|
||||
if (orderStatusHeader != null) {
|
||||
String orderStatusName = getValue(record, orderStatusHeader);
|
||||
if (orderStatusName != null && !orderStatusName.trim().isEmpty()) {
|
||||
Long statusId = findOrderStatusByName(orderStatusName.trim(), companyId);
|
||||
if (statusId != null) {
|
||||
orderDTO.setStatusId(statusId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 解析下单时间(如果有映射,这里简化处理,使用当前时间)
|
||||
orderDTO.setOrderDate(LocalDateTime.now());
|
||||
|
||||
return orderDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从CSV记录获取值
|
||||
*
|
||||
* @param record CSV记录
|
||||
* @param header 表头名称
|
||||
* @return 值
|
||||
*/
|
||||
private String getValue(CSVRecord record, String header) {
|
||||
if (header == null || header.trim().isEmpty()) {
|
||||
logger.debug("表头名称为空,无法获取值");
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
String trimmedHeader = header.trim();
|
||||
String value = record.get(trimmedHeader);
|
||||
logger.debug("从表头 '{}' 获取值: '{}'", trimmedHeader, value);
|
||||
return value;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// 表头不存在,尝试忽略大小写匹配
|
||||
Map<String, Integer> headerMap = record.getParser().getHeaderMap();
|
||||
String matchedHeader = headerMap.keySet().stream()
|
||||
.filter(h -> h.trim().equalsIgnoreCase(header.trim()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (matchedHeader != null) {
|
||||
logger.debug("表头 '{}' 不存在,但找到忽略大小写的匹配: '{}'", header, matchedHeader);
|
||||
return record.get(matchedHeader);
|
||||
}
|
||||
|
||||
logger.warn("表头 '{}' 不存在,可用的表头: {}", header, headerMap.keySet());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过规格编码查找商品规格
|
||||
*
|
||||
* @param specCode 规格编码
|
||||
* @param companyId 公司ID
|
||||
* @return 商品规格
|
||||
*/
|
||||
private ProductSpecPO findProductSpecBySpecCode(String specCode, Long companyId) {
|
||||
// 根据公司ID和规格编码查询,规格编码在公司内应该是唯一的
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSpecPO::getSpecCode, specCode)
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
return productSpecService.getOne(wrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果商品和规格不存在,则创建它们
|
||||
* 通过规格编码查找无果则确定为规格不存在,再通过商品名称来判断有没有该商品
|
||||
* 复用ProductService.createProduct和ProductSpecService.createProductSpec的业务逻辑
|
||||
*
|
||||
* @param companyId 公司ID
|
||||
* @param productName 商品名称
|
||||
* @param specName 规格名称
|
||||
* @param specCode 规格编码
|
||||
* @param createBy 创建人ID
|
||||
* @return 商品规格
|
||||
*/
|
||||
private ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName,
|
||||
String specName, String specCode, Long createBy) {
|
||||
// 1. 通过商品名称查找商品(复用ProductService.getProductByName的逻辑)
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> productWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
productWrapper.eq(ProductPO::getName, productName)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
ProductPO product = productMapper.selectOne(productWrapper);
|
||||
|
||||
Long productId;
|
||||
if (product == null) {
|
||||
// 商品不存在,创建商品(复用ProductService.createProduct的逻辑:验证商品名称是否重复)
|
||||
// 注意:createProduct需要CurrentUserContext,但我们在消费者线程中没有
|
||||
// 所以这里直接使用Mapper创建,保持与createProduct相同的验证逻辑
|
||||
// 由于上面已经查询过product为null,这里再次检查是为了避免并发问题
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> checkWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
checkWrapper.eq(ProductPO::getName, productName)
|
||||
.eq(ProductPO::getCompanyId, companyId);
|
||||
if (productMapper.selectCount(checkWrapper) > 0) {
|
||||
// 在检查期间商品被创建了,重新查询
|
||||
product = productMapper.selectOne(productWrapper);
|
||||
productId = product.getId();
|
||||
logger.debug("商品在检查期间被创建: {} (ID: {})", productName, productId);
|
||||
} else {
|
||||
// 创建新商品(复用ProductService.createProduct的逻辑)
|
||||
product = new ProductPO();
|
||||
product.setCompanyId(companyId);
|
||||
product.setName(productName);
|
||||
product.setCreateBy(createBy);
|
||||
productMapper.insert(product);
|
||||
productId = product.getId();
|
||||
logger.info("自动创建商品: {} (ID: {})", productName, productId);
|
||||
}
|
||||
} else {
|
||||
productId = product.getId();
|
||||
logger.debug("商品已存在: {} (ID: {})", productName, productId);
|
||||
}
|
||||
|
||||
// 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑)
|
||||
// 注意:规格编码查找无果,所以这里直接创建
|
||||
// 验证商品是否存在(复用createProductSpec的逻辑)
|
||||
ProductPO existingProduct = productMapper.selectById(productId);
|
||||
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
|
||||
// 验证规格名称是否重复(复用createProductSpec的逻辑)
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductSpecPO> specCheckWrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
specCheckWrapper.eq(ProductSpecPO::getProductId, productId)
|
||||
.eq(ProductSpecPO::getName, specName)
|
||||
.eq(ProductSpecPO::getCompanyId, companyId);
|
||||
if (productSpecService.count(specCheckWrapper) > 0) {
|
||||
throw new BusinessException("规格名称已存在");
|
||||
}
|
||||
|
||||
// 创建商品规格(复用createProductSpec的逻辑)
|
||||
ProductSpecPO productSpec = new ProductSpecPO();
|
||||
productSpec.setCompanyId(companyId);
|
||||
productSpec.setProductId(productId);
|
||||
productSpec.setName(specName);
|
||||
productSpec.setSpecCode(specCode);
|
||||
productSpec.setCostPrice(BigDecimal.ZERO); // 默认成本价为0,后续可以手动更新
|
||||
productSpec.setCreateBy(createBy);
|
||||
productSpecService.save(productSpec);
|
||||
logger.info("自动创建商品规格: {} (编码: {}, ID: {})", specName, specCode, productSpec.getId());
|
||||
|
||||
return productSpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单(不依赖CurrentUserContext,复用OrderService.createOrder的业务逻辑)
|
||||
*
|
||||
* @param createOrderDTO 创建订单DTO
|
||||
* @param companyId 公司ID
|
||||
* @param createBy 创建人ID
|
||||
* @return 订单VO
|
||||
*/
|
||||
private OrderVO createOrderWithoutContext(CreateOrderDTO createOrderDTO, Long companyId, Long createBy) {
|
||||
// 复用OrderService.createOrder的验证逻辑
|
||||
|
||||
// 验证店铺是否存在且属于当前公司
|
||||
top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopPO shop = shopService.getById(createOrderDTO.getShopId());
|
||||
if (shop == null || !shop.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
|
||||
// 验证商品是否存在且属于当前公司
|
||||
ProductPO product = productMapper.selectById(createOrderDTO.getProductId());
|
||||
if (product == null || !product.getCompanyId().equals(companyId)) {
|
||||
throw new BusinessException("商品不存在");
|
||||
}
|
||||
|
||||
// 验证商品规格是否存在且属于当前公司(如果提供了规格ID)
|
||||
ProductSpecPO productSpec = null;
|
||||
if (createOrderDTO.getProductSpecId() != null) {
|
||||
productSpec = productSpecService.getById(createOrderDTO.getProductSpecId());
|
||||
if (productSpec == null || !productSpec.getCompanyId().equals(companyId) ||
|
||||
!productSpec.getProductId().equals(createOrderDTO.getProductId())) {
|
||||
throw new BusinessException("商品规格不存在或不属于该商品");
|
||||
}
|
||||
}
|
||||
|
||||
// 验证平台订单号是否重复(如果提供了的话)
|
||||
if (createOrderDTO.getPlatformOrderNo() != null && !createOrderDTO.getPlatformOrderNo().trim().isEmpty()) {
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(OrderPO::getPlatformOrderNo, createOrderDTO.getPlatformOrderNo())
|
||||
.eq(OrderPO::getCompanyId, companyId);
|
||||
if (orderMapper.selectCount(wrapper) > 0) {
|
||||
throw new BusinessException("平台订单号已存在");
|
||||
}
|
||||
}
|
||||
|
||||
// 创建订单(包含商品明细)
|
||||
OrderPO order = new OrderPO();
|
||||
order.setCompanyId(companyId);
|
||||
order.setShopId(createOrderDTO.getShopId());
|
||||
order.setPlatformOrderNo(createOrderDTO.getPlatformOrderNo());
|
||||
order.setStatusId(createOrderDTO.getStatusId());
|
||||
order.setProductId(createOrderDTO.getProductId());
|
||||
order.setProductSpecId(createOrderDTO.getProductSpecId());
|
||||
order.setProductName(createOrderDTO.getProductName());
|
||||
order.setSpecName(createOrderDTO.getSpecName());
|
||||
order.setQuantity(createOrderDTO.getQuantity());
|
||||
order.setUnitPrice(createOrderDTO.getUnitPrice());
|
||||
order.setCostPrice(createOrderDTO.getCostPrice());
|
||||
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
|
||||
order.setOrderDate(createOrderDTO.getOrderDate());
|
||||
order.setCreateBy(createBy);
|
||||
|
||||
// 保存订单
|
||||
orderMapper.insert(order);
|
||||
|
||||
// 转换为VO并返回
|
||||
return convertOrderToVO(order);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换订单PO为VO
|
||||
*
|
||||
* @param order 订单PO
|
||||
* @return 订单VO
|
||||
*/
|
||||
private OrderVO convertOrderToVO(OrderPO order) {
|
||||
OrderVO orderVO = new OrderVO();
|
||||
BeanUtils.copyProperties(order, orderVO);
|
||||
return orderVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过订单状态名称查找订单状态ID
|
||||
*
|
||||
* @param statusName 状态名称
|
||||
* @param companyId 公司ID
|
||||
* @return 状态ID
|
||||
*/
|
||||
private Long findOrderStatusByName(String statusName, Long companyId) {
|
||||
// 根据公司ID和状态名称查询订单状态
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<OrderStatusPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
|
||||
.eq(OrderStatusPO::getStatusName, statusName)
|
||||
.eq(OrderStatusPO::getIsActive, 1);
|
||||
OrderStatusPO status = orderStatusMapper.selectOne(wrapper);
|
||||
return status != null ? status.getId() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新任务状态
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
* @param status 状态
|
||||
* @param message 消息
|
||||
* @param totalCount 总行数
|
||||
* @param successCount 成功行数
|
||||
* @param failCount 失败行数
|
||||
*/
|
||||
private void updateTaskStatus(Long taskId, String status, String message,
|
||||
Integer totalCount, Integer successCount, Integer failCount) {
|
||||
LambdaUpdateWrapper<ImportTaskPO> updateWrapper = new LambdaUpdateWrapper<>();
|
||||
updateWrapper.eq(ImportTaskPO::getId, taskId);
|
||||
updateWrapper.set(ImportTaskPO::getStatus, status);
|
||||
if (message != null) {
|
||||
updateWrapper.set(ImportTaskPO::getMessage, message);
|
||||
}
|
||||
if (totalCount != null) {
|
||||
updateWrapper.set(ImportTaskPO::getTotalCount, totalCount);
|
||||
}
|
||||
if (successCount != null) {
|
||||
updateWrapper.set(ImportTaskPO::getSuccessCount, successCount);
|
||||
}
|
||||
if (failCount != null) {
|
||||
updateWrapper.set(ImportTaskPO::getFailCount, failCount);
|
||||
}
|
||||
importTaskService.update(updateWrapper);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知任务进度
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
private void notifyTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
try {
|
||||
sseNotificationService.sendTaskProgress(userId, taskVO);
|
||||
} catch (Exception e) {
|
||||
logger.warn("发送任务进度通知失败,userId: {}, taskId: {}", userId, taskVO != null ? taskVO.getId() : null, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为VO
|
||||
*
|
||||
* @param importTaskPO 导入任务PO
|
||||
* @return 导入任务VO
|
||||
*/
|
||||
private ImportTaskVO convertToVO(ImportTaskPO importTaskPO) {
|
||||
if (importTaskPO == null) {
|
||||
return null;
|
||||
}
|
||||
ImportTaskVO importTaskVO = new ImportTaskVO();
|
||||
BeanUtils.copyProperties(importTaskPO, importTaskVO);
|
||||
return importTaskVO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检测文件编码
|
||||
* 尝试多种常见的中文编码
|
||||
*
|
||||
* @param file 文件
|
||||
* @return 检测到的编码
|
||||
*/
|
||||
private java.nio.charset.Charset detectFileEncoding(File file) {
|
||||
// 常见的编码列表,按优先级排序
|
||||
java.nio.charset.Charset[] charsets = {
|
||||
java.nio.charset.Charset.forName("GBK"), // 优先尝试GBK,因为中文CSV文件常用GBK
|
||||
java.nio.charset.Charset.forName("GB2312"),
|
||||
java.nio.charset.StandardCharsets.UTF_8,
|
||||
java.nio.charset.StandardCharsets.ISO_8859_1
|
||||
};
|
||||
|
||||
// 读取文件的前几行来检测编码
|
||||
for (java.nio.charset.Charset charset : charsets) {
|
||||
try (java.io.InputStreamReader reader = new java.io.InputStreamReader(
|
||||
new java.io.FileInputStream(file), charset)) {
|
||||
char[] buffer = new char[2048];
|
||||
int read = reader.read(buffer);
|
||||
if (read > 0) {
|
||||
String content = new String(buffer, 0, read);
|
||||
// 简单检测:如果包含常见的中文字符,可能是正确的编码
|
||||
if (content.contains("商家") || content.contains("编码") ||
|
||||
content.contains("商品") || content.contains("订单") ||
|
||||
content.contains("规格") || content.contains("金额")) {
|
||||
logger.debug("检测到编码 {} 可能正确,内容预览: {}", charset, content.substring(0, Math.min(100, content.length())));
|
||||
return charset;
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.debug("尝试编码 {} 失败: {}", charset, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 默认返回GBK(中文CSV文件最常用)
|
||||
logger.warn("无法确定文件编码,使用默认GBK");
|
||||
return java.nio.charset.Charset.forName("GBK");
|
||||
}
|
||||
}
|
||||
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.config.ImportTaskQueueConfig;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
|
||||
|
||||
/**
|
||||
* 导入任务队列服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class ImportTaskQueueServiceImpl implements ImportTaskQueueService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(ImportTaskQueueServiceImpl.class);
|
||||
|
||||
private final RedisTemplate<String, Object> redisTemplate;
|
||||
private final ImportTaskService importTaskService;
|
||||
|
||||
public ImportTaskQueueServiceImpl(RedisTemplate<String, Object> redisTemplate,
|
||||
@Lazy ImportTaskService importTaskService) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.importTaskService = importTaskService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发布导入任务到队列
|
||||
*
|
||||
* @param taskId 任务ID
|
||||
*/
|
||||
@Override
|
||||
public void publishImportTask(Long taskId) {
|
||||
try {
|
||||
// 获取任务信息
|
||||
ImportTaskPO task = importTaskService.getById(taskId);
|
||||
if (task == null) {
|
||||
logger.error("导入任务不存在,taskId: {}", taskId);
|
||||
return;
|
||||
}
|
||||
|
||||
// 根据任务类型获取队列名称
|
||||
String queueName = ImportTaskQueueConfig.getQueueName(task.getType());
|
||||
|
||||
// 发布任务到Redis队列
|
||||
redisTemplate.opsForList().rightPush(queueName, taskId);
|
||||
|
||||
logger.info("导入任务已发布到队列,taskId: {}, queueName: {}", taskId, queueName);
|
||||
} catch (Exception e) {
|
||||
logger.error("发布导入任务到队列失败,taskId: {}", taskId, e);
|
||||
throw new RuntimeException("发布导入任务到队列失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-1
@@ -15,6 +15,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask.CreateImportT
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.dto.importtask.ImportTaskFilterDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskQueueService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
@@ -28,9 +29,12 @@ import java.util.stream.Collectors;
|
||||
public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportTaskPO> implements ImportTaskService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ImportTaskQueueService importTaskQueueService;
|
||||
|
||||
public ImportTaskServiceImpl(CurrentUserContext currentUserContext) {
|
||||
public ImportTaskServiceImpl(CurrentUserContext currentUserContext,
|
||||
ImportTaskQueueService importTaskQueueService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.importTaskQueueService = importTaskQueueService;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,6 +61,9 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
|
||||
|
||||
this.save(importTaskPO);
|
||||
|
||||
// 发布任务到Redis队列
|
||||
importTaskQueueService.publishImportTask(importTaskPO.getId());
|
||||
|
||||
// 转换为VO返回
|
||||
return convertToVO(importTaskPO);
|
||||
}
|
||||
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ImportTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.service.SseNotificationService;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* SSE通知服务实现类
|
||||
*/
|
||||
@Service
|
||||
public class SseNotificationServiceImpl implements SseNotificationService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(SseNotificationServiceImpl.class);
|
||||
|
||||
private final Map<Long, SseEmitter> userConnections = new ConcurrentHashMap<>();
|
||||
private final ImportTaskService importTaskService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public SseNotificationServiceImpl(ImportTaskService importTaskService, ObjectMapper objectMapper) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return SSE发射器
|
||||
*/
|
||||
@Override
|
||||
public SseEmitter createConnection(Long userId) {
|
||||
// 如果已存在连接,先关闭
|
||||
SseEmitter existingEmitter = userConnections.get(userId);
|
||||
if (existingEmitter != null) {
|
||||
try {
|
||||
existingEmitter.complete();
|
||||
} catch (Exception e) {
|
||||
logger.warn("关闭已存在的SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新的SSE连接,超时时间30分钟
|
||||
SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);
|
||||
userConnections.put(userId, emitter);
|
||||
|
||||
// 设置完成和超时回调
|
||||
emitter.onCompletion(() -> {
|
||||
logger.info("SSE连接完成,userId: {}", userId);
|
||||
userConnections.remove(userId);
|
||||
});
|
||||
|
||||
emitter.onTimeout(() -> {
|
||||
logger.info("SSE连接超时,userId: {}", userId);
|
||||
userConnections.remove(userId);
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception e) {
|
||||
logger.warn("完成超时的SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
});
|
||||
|
||||
emitter.onError((ex) -> {
|
||||
logger.error("SSE连接错误,userId: {}", userId, ex);
|
||||
userConnections.remove(userId);
|
||||
try {
|
||||
emitter.completeWithError(ex);
|
||||
} catch (Exception e) {
|
||||
logger.warn("完成错误的SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
});
|
||||
|
||||
// 发送初始连接成功消息
|
||||
try {
|
||||
Map<String, Object> initialMessage = new java.util.HashMap<>();
|
||||
initialMessage.put("type", "connected");
|
||||
initialMessage.put("message", "SSE连接已建立");
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("message")
|
||||
.data(objectMapper.writeValueAsString(initialMessage)));
|
||||
} catch (IOException e) {
|
||||
logger.error("发送初始SSE消息失败,userId: {}", userId, e);
|
||||
userConnections.remove(userId);
|
||||
emitter.completeWithError(e);
|
||||
}
|
||||
|
||||
logger.info("创建SSE连接成功,userId: {}", userId);
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送任务进度通知
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @param taskVO 导入任务VO(完整信息)
|
||||
*/
|
||||
@Override
|
||||
public void sendTaskProgress(Long userId, ImportTaskVO taskVO) {
|
||||
SseEmitter emitter = userConnections.get(userId);
|
||||
if (emitter == null) {
|
||||
logger.debug("用户没有SSE连接,userId: {}", userId);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> progressMessage = new java.util.HashMap<>();
|
||||
progressMessage.put("type", "task_progress");
|
||||
progressMessage.put("task", taskVO); // 发送完整的ImportTaskVO
|
||||
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("task_progress")
|
||||
.data(objectMapper.writeValueAsString(progressMessage)));
|
||||
|
||||
logger.debug("发送任务进度通知成功,userId: {}, taskId: {}, status: {}", userId, taskVO.getId(), taskVO.getStatus());
|
||||
|
||||
// 如果任务已完成(success或failed),检查是否所有任务都已完成
|
||||
if ("success".equals(taskVO.getStatus()) || "failed".equals(taskVO.getStatus())) {
|
||||
checkAndNotifyAllTasksCompleted(userId);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("发送任务进度通知失败,userId: {}, taskId: {}", userId, taskVO != null ? taskVO.getId() : null, e);
|
||||
userConnections.remove(userId);
|
||||
try {
|
||||
emitter.completeWithError(e);
|
||||
} catch (Exception ex) {
|
||||
logger.warn("完成错误的SSE连接失败,userId: {}", userId, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 关闭用户的SSE连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
@Override
|
||||
public void closeConnection(Long userId) {
|
||||
SseEmitter emitter = userConnections.remove(userId);
|
||||
if (emitter != null) {
|
||||
try {
|
||||
emitter.complete();
|
||||
logger.info("关闭SSE连接成功,userId: {}", userId);
|
||||
} catch (Exception e) {
|
||||
logger.warn("关闭SSE连接失败,userId: {}", userId, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否有活跃的任务
|
||||
*
|
||||
* @param userId 用户ID
|
||||
* @return 是否有活跃任务
|
||||
*/
|
||||
@Override
|
||||
public boolean hasActiveTasks(Long userId) {
|
||||
// 查询用户是否有pending或processing状态的任务
|
||||
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ImportTaskPO> wrapper =
|
||||
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
|
||||
wrapper.eq(ImportTaskPO::getCreateBy, userId)
|
||||
.in(ImportTaskPO::getStatus, "pending", "processing");
|
||||
long count = importTaskService.count(wrapper);
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 通知所有任务已完成,可以关闭连接
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
@Override
|
||||
public void notifyAllTasksCompleted(Long userId) {
|
||||
SseEmitter emitter = userConnections.get(userId);
|
||||
if (emitter == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Map<String, Object> completeMessage = new java.util.HashMap<>();
|
||||
completeMessage.put("type", "all_tasks_completed");
|
||||
completeMessage.put("message", "所有任务已完成,可以关闭连接");
|
||||
|
||||
emitter.send(SseEmitter.event()
|
||||
.name("all_tasks_completed")
|
||||
.data(objectMapper.writeValueAsString(completeMessage)));
|
||||
|
||||
logger.info("通知所有任务已完成,userId: {}", userId);
|
||||
|
||||
// 延迟关闭连接,给前端时间处理
|
||||
new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(1000); // 等待1秒
|
||||
closeConnection(userId);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}).start();
|
||||
|
||||
} catch (IOException e) {
|
||||
logger.error("通知所有任务完成失败,userId: {}", userId, e);
|
||||
closeConnection(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查并通知所有任务已完成
|
||||
*
|
||||
* @param userId 用户ID
|
||||
*/
|
||||
private void checkAndNotifyAllTasksCompleted(Long userId) {
|
||||
if (!hasActiveTasks(userId)) {
|
||||
notifyAllTasksCompleted(userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user