feat: 忘了

This commit is contained in:
ah--desktop
2026-03-12 21:24:15 +08:00
parent 43e01a1617
commit dbf9a8d1b4
8 changed files with 553 additions and 48 deletions
@@ -38,6 +38,12 @@ public class ImportTaskPO {
@TableField("type")
private String type;
/**
* 任务名称
*/
@TableField("task_name")
private String taskName;
/**
* 原始文件名
*/
@@ -36,6 +36,12 @@ public class ImportTaskVO {
@Schema(description = "导入类型", example = "product")
private String type;
/**
* 任务名称
*/
@Schema(description = "任务名称", example = "T-1001-20260311123059")
private String taskName;
/**
* 原始文件名
*/
@@ -83,6 +83,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
List<Long> autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId);
// 查询所有店铺
LambdaQueryWrapper<ShopPO> shopWrapper = new LambdaQueryWrapper<>();
@@ -97,6 +98,11 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
if (!autoStatisticsStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds);
} else {
orderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(所有店铺)
@@ -126,6 +132,11 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
lastMonthOrderWrapper.eq(OrderPO::getCompanyId, companyId)
.ge(OrderPO::getOrderTime, lastMonthStartDateTime)
.le(OrderPO::getOrderTime, lastMonthEndDateTime);
if (!autoStatisticsStatusIds.isEmpty()) {
lastMonthOrderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds);
} else {
lastMonthOrderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper);
// 构建返回对象
@@ -635,5 +646,16 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
private List<Long> getAutoStatisticsStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
}
}
@@ -1,7 +1,11 @@
package top.xyquan.ecomdmbbackend.modules.ecom.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
@@ -11,6 +15,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.mapper.ShopProductRelationMapper;
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.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.po.ShopProductRelationPO;
import top.xyquan.ecomdmbbackend.modules.ecom.model.vo.ImportTaskVO;
@@ -36,8 +41,13 @@ import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -148,6 +158,48 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
private static final int ORDER_BATCH_SIZE = 200;
private static final int RELATION_BATCH_SIZE = 200;
private static final int PROGRESS_UPDATE_INTERVAL_ROWS = 50;
private static final long PROGRESS_NOTIFY_INTERVAL_MS = 2000L;
private static final int IN_QUERY_BATCH_SIZE = 500;
private static class PendingOrderInsert {
private final int rowNumber;
private final String platformOrderNo;
private final OrderPO order;
private PendingOrderInsert(int rowNumber, String platformOrderNo, OrderPO order) {
this.rowNumber = rowNumber;
this.platformOrderNo = platformOrderNo;
this.order = order;
}
}
private static class ImportRuntimeContext {
private final Long companyId;
private final Long shopId;
private final Long createBy;
private final Map<String, ProductSpecPO> specByCodeCache = new HashMap<>();
private final Map<String, ProductPO> productByCodeCache = new HashMap<>();
private final Map<String, ProductPO> productByNameCache = new HashMap<>();
private final Map<Long, ProductPO> productByIdCache = new HashMap<>();
private final Map<String, Long> statusIdByNameCache = new HashMap<>();
private final Set<String> existingPlatformOrderNos = new HashSet<>();
private final Set<String> existingRelationKeys = new HashSet<>();
private final List<PendingOrderInsert> pendingOrders = new ArrayList<>();
private final List<ShopProductRelationPO> pendingRelations = new ArrayList<>();
private final Set<String> pendingRelationKeys = new HashSet<>();
private final Set<String> pendingPlatformOrderNos = new HashSet<>();
private ImportRuntimeContext(Long companyId, Long shopId, Long createBy) {
this.companyId = companyId;
this.shopId = shopId;
this.createBy = createBy;
}
}
private final ImportTaskService importTaskService;
private final ProductSpecService productSpecService;
private final OrderMapper orderMapper;
@@ -157,6 +209,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final SseNotificationService sseNotificationService;
private final ObjectMapper objectMapper;
private final OrderStatusService orderStatusService;
private final SqlSessionFactory sqlSessionFactory;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
OrderService orderService,
@@ -168,7 +221,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
ShopProductRelationMapper shopProductRelationMapper,
SseNotificationService sseNotificationService,
ObjectMapper objectMapper,
OrderStatusService orderStatusService) {
OrderStatusService orderStatusService,
SqlSessionFactory sqlSessionFactory) {
this.importTaskService = importTaskService;
this.productSpecService = productSpecService;
this.orderMapper = orderMapper;
@@ -178,6 +232,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
this.sseNotificationService = sseNotificationService;
this.objectMapper = objectMapper;
this.orderStatusService = orderStatusService;
this.sqlSessionFactory = sqlSessionFactory;
}
/**
@@ -269,6 +324,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
int successCount = 0;
int failCount = 0;
StringBuilder errorMessages = new StringBuilder();
long lastProgressNotifyAt = 0L;
// 尝试多种编码读取CSV文件(常见的中文编码)
java.nio.charset.Charset charset = detectFileEncoding(csvFile);
@@ -289,34 +345,52 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 更新总行数
updateTaskStatus(task.getId(), "processing", null, totalCount, 0, 0);
ImportRuntimeContext context = new ImportRuntimeContext(companyId, task.getShopId(), task.getCreateBy());
preloadImportContext(context, records, fieldMapping, statusMapping);
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, fieldMapping, statusMapping, task.getShopId(), defaultStatusId, companyId, task.getCreateBy());
CreateOrderDTO orderDTO = parseOrderFromCSV(record, fieldMapping, statusMapping, task.getShopId(),
defaultStatusId, companyId, task.getCreateBy(), context);
validatePlatformOrderNo(orderDTO.getPlatformOrderNo(), context);
queueShopProductRelation(orderDTO, context);
context.pendingOrders.add(new PendingOrderInsert(rowNumber, orderDTO.getPlatformOrderNo(),
buildOrderPO(orderDTO, companyId, task.getCreateBy(), task.getId())));
// 创建订单(复用OrderService.createOrder的业务逻辑,但不依赖CurrentUserContext)
createOrderWithoutContext(orderDTO, companyId, task.getCreateBy(), task.getId());
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));
if (context.pendingRelations.size() >= RELATION_BATCH_SIZE) {
flushPendingRelations(context);
}
if (context.pendingOrders.size() >= ORDER_BATCH_SIZE) {
int[] result = flushPendingOrders(context, errorMessages);
successCount += result[0];
failCount += result[1];
}
} catch (Exception e) {
failCount++;
String errorMsg = String.format("第%d行:%s", rowNumber, e.getMessage());
errorMessages.append(errorMsg).append(System.lineSeparator());
}
// 更新失败计数
if ((i + 1) % PROGRESS_UPDATE_INTERVAL_ROWS == 0 || (i + 1) == records.size()) {
updateTaskStatus(task.getId(), "processing", null, totalCount, successCount, failCount);
}
long now = System.currentTimeMillis();
if (now - lastProgressNotifyAt >= PROGRESS_NOTIFY_INTERVAL_MS || (i + 1) == records.size()) {
ImportTaskPO updatedTask = importTaskService.getById(task.getId());
notifyTaskProgress(task.getCreateBy(), convertToVO(updatedTask));
lastProgressNotifyAt = now;
}
}
flushPendingRelations(context);
int[] flushResult = flushPendingOrders(context, errorMessages);
successCount += flushResult[0];
failCount += flushResult[1];
}
// 更新最终状态
@@ -436,8 +510,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @return 创建订单DTO
*/
private CreateOrderDTO parseOrderFromCSV(CSVRecord record, Map<String, MappingField> fieldMapping,
Map<String, Long> statusMapping, Long shopId, Long defaultStatusId,
Long companyId, Long createBy) {
Map<String, Long> statusMapping, Long shopId, Long defaultStatusId,
Long companyId, Long createBy, ImportRuntimeContext context) {
CreateOrderDTO orderDTO = new CreateOrderDTO();
orderDTO.setShopId(shopId);
orderDTO.setStatusId(defaultStatusId);
@@ -535,7 +609,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
// 首先通过规格编码查找商品规格
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId);
ProductSpecPO productSpec = findProductSpecBySpecCode(specCode.trim(), companyId, context);
boolean isNewSpecCreated = false; // 标记是否创建了新规格
// 如果找不到规格,则尝试通过商品编码或商品名称查找商品,然后创建规格
@@ -544,19 +618,19 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 优先使用商品编码查找商品
if (productCode != null && !productCode.isEmpty()) {
product = findProductByProductCode(productCode, companyId);
product = findProductByProductCode(productCode, companyId, context);
}
// 如果商品编码查找失败,使用链接商品名称精准查找商品
if (product == null && linkProductName != null && !linkProductName.isEmpty()) {
product = findProductByName(linkProductName, companyId);
product = findProductByName(linkProductName, companyId, context);
}
// 如果找到了商品,创建规格
if (product != null) {
// 优先使用链接规格名称,如果没有则使用"未知规格"
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = createSpecForProduct(companyId, product.getId(), finalSpecName, specCode.trim(), createBy);
productSpec = createSpecForProduct(companyId, product.getId(), finalSpecName, specCode.trim(), createBy, context);
isNewSpecCreated = true;
}
// 如果没有找到商品,则自动创建商品和规格
@@ -565,7 +639,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
String finalProductName = (linkProductName != null && !linkProductName.isEmpty()) ? linkProductName : "未知商品";
// 优先使用链接规格名称,如果没有则使用"未知规格"
String finalSpecName = (linkSpecName != null && !linkSpecName.isEmpty()) ? linkSpecName : "未知规格";
productSpec = createProductAndSpecIfNotExists(companyId, finalProductName, productCode, finalSpecName, specCode.trim(), createBy);
productSpec = createProductAndSpecIfNotExists(companyId, finalProductName, productCode, finalSpecName, specCode.trim(), createBy, context);
isNewSpecCreated = true;
}
}
@@ -582,7 +656,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
if (linkProductName != null && !linkProductName.isEmpty()) {
orderDTO.setLinkProductName(linkProductName);
} else {
ProductPO product = productMapper.selectById(productSpec.getProductId());
ProductPO product = getProductById(productSpec.getProductId(), context);
orderDTO.setLinkProductName(product != null ? product.getName() : "未知商品");
}
@@ -625,7 +699,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 如果状态映射没有找到,尝试直接通过状态名称查找
if (statusId == null) {
statusId = findOrderStatusIdByName(companyId, trimmedStatus);
statusId = findOrderStatusIdByName(companyId, trimmedStatus, context);
}
// 如果找到了有效的状态,则使用;否则自动创建新状态
@@ -633,7 +707,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
orderDTO.setStatusId(statusId);
} else {
// 用户没有做映射,且数据库中该公司没有当前状态名称,自动创建新的订单状态
statusId = createOrderStatusIfNotExists(companyId, trimmedStatus, createBy);
statusId = createOrderStatusIfNotExists(companyId, trimmedStatus, createBy, context);
orderDTO.setStatusId(statusId);
}
}
@@ -821,13 +895,26 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @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)
private ProductSpecPO findProductSpecBySpecCode(String specCode, Long companyId, ImportRuntimeContext context) {
if (specCode == null) {
return null;
}
String normalized = specCode.trim();
if (normalized.isEmpty()) {
return null;
}
ProductSpecPO cached = context.specByCodeCache.get(normalized);
if (cached != null) {
return cached;
}
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getSpecCode, normalized)
.eq(ProductSpecPO::getCompanyId, companyId);
return productSpecService.getOne(wrapper);
ProductSpecPO productSpec = productSpecService.getOne(wrapper);
if (productSpec != null) {
context.specByCodeCache.put(normalized, productSpec);
}
return productSpec;
}
/**
@@ -837,12 +924,30 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param companyId 公司ID
* @return 商品
*/
private ProductPO findProductByProductCode(String productCode, Long companyId) {
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getProductCode, productCode)
private ProductPO findProductByProductCode(String productCode, Long companyId, ImportRuntimeContext context) {
if (productCode == null) {
return null;
}
String normalized = productCode.trim();
if (normalized.isEmpty()) {
return null;
}
ProductPO cached = context.productByCodeCache.get(normalized);
if (cached != null) {
return cached;
}
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getProductCode, normalized)
.eq(ProductPO::getCompanyId, companyId);
return productMapper.selectOne(wrapper);
ProductPO product = productMapper.selectOne(wrapper);
if (product != null) {
context.productByCodeCache.put(normalized, product);
context.productByIdCache.put(product.getId(), product);
if (product.getName() != null) {
context.productByNameCache.put(product.getName(), product);
}
}
return product;
}
/**
@@ -852,12 +957,30 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param companyId 公司ID
* @return 商品
*/
private ProductPO findProductByName(String productName, Long companyId) {
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> wrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getName, productName)
private ProductPO findProductByName(String productName, Long companyId, ImportRuntimeContext context) {
if (productName == null) {
return null;
}
String normalized = productName.trim();
if (normalized.isEmpty()) {
return null;
}
ProductPO cached = context.productByNameCache.get(normalized);
if (cached != null) {
return cached;
}
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getName, normalized)
.eq(ProductPO::getCompanyId, companyId);
return productMapper.selectOne(wrapper);
ProductPO product = productMapper.selectOne(wrapper);
if (product != null) {
context.productByNameCache.put(normalized, product);
context.productByIdCache.put(product.getId(), product);
if (product.getProductCode() != null) {
context.productByCodeCache.put(product.getProductCode(), product);
}
}
return product;
}
/**
@@ -870,7 +993,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param createBy 创建人ID
* @return 商品规格
*/
private ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, String specCode, Long createBy) {
private ProductSpecPO createSpecForProduct(Long companyId, Long productId, String specName, String specCode, Long createBy,
ImportRuntimeContext context) {
// 验证商品是否存在
ProductPO existingProduct = productMapper.selectById(productId);
if (existingProduct == null || !existingProduct.getCompanyId().equals(companyId)) {
@@ -907,7 +1031,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
productSpec.setOtherCost(BigDecimal.ZERO); // 默认其他成本为0
productSpec.setCreateBy(createBy);
productSpecService.save(productSpec);
context.specByCodeCache.put(specCode, productSpec);
return productSpec;
}
@@ -924,8 +1048,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @param createBy 创建人ID
* @return 商品规格
*/
private ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName,
String productCode, String specName, String specCode, Long createBy) {
private ProductSpecPO createProductAndSpecIfNotExists(Long companyId, String productName,
String productCode, String specName, String specCode, Long createBy,
ImportRuntimeContext context) {
// 1. 通过商品名称查找商品(复用ProductService.getProductByName的逻辑)
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<ProductPO> productWrapper =
new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<>();
@@ -983,7 +1108,14 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
// 2. 创建商品规格(复用ProductSpecService.createProductSpec的逻辑)
return createSpecForProduct(companyId, productId, specName, specCode, createBy);
context.productByIdCache.put(productId, product);
if (product.getName() != null) {
context.productByNameCache.put(product.getName(), product);
}
if (product.getProductCode() != null) {
context.productByCodeCache.put(product.getProductCode(), product);
}
return createSpecForProduct(companyId, productId, specName, specCode, createBy, context);
}
/**
@@ -1107,6 +1239,292 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
}
}
private void preloadImportContext(ImportRuntimeContext context, List<CSVRecord> records, Map<String, MappingField> fieldMapping,
Map<String, Long> statusMapping) {
ShopPO shop = shopService.getById(context.shopId);
if (shop == null || !shop.getCompanyId().equals(context.companyId)) {
throw new BusinessException("店铺不存在");
}
MappingField specCodeField = fieldMapping.get("spec_code");
MappingField productCodeField = fieldMapping.get("product_code");
MappingField linkProductNameField = fieldMapping.get("link_product_name");
MappingField orderStatusField = fieldMapping.get("status");
MappingField platformOrderNoField = fieldMapping.get("platform_order_no");
Set<String> specCodes = new HashSet<>();
Set<String> productCodes = new HashSet<>();
Set<String> productNames = new HashSet<>();
Set<String> platformOrderNos = new HashSet<>();
Set<String> statusNames = new HashSet<>();
for (CSVRecord record : records) {
addNormalizedValue(specCodes, getValue(record, specCodeField));
addNormalizedValue(productCodes, getValue(record, productCodeField));
addNormalizedValue(productNames, getValue(record, linkProductNameField));
addNormalizedValue(platformOrderNos, getValue(record, platformOrderNoField));
addNormalizedValue(statusNames, getValue(record, orderStatusField));
}
preloadProductSpecs(context, specCodes);
preloadProductsByCode(context, productCodes);
preloadProductsByName(context, productNames);
preloadPlatformOrderNos(context, platformOrderNos);
preloadStatuses(context, statusNames, statusMapping);
preloadShopProductRelations(context);
}
private void addNormalizedValue(Set<String> target, String rawValue) {
if (rawValue == null) {
return;
}
String value = rawValue.trim();
if (!value.isEmpty()) {
target.add(value);
}
}
private void preloadProductSpecs(ImportRuntimeContext context, Set<String> specCodes) {
for (List<String> chunk : splitToChunks(specCodes, IN_QUERY_BATCH_SIZE)) {
LambdaQueryWrapper<ProductSpecPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductSpecPO::getCompanyId, context.companyId)
.in(ProductSpecPO::getSpecCode, chunk);
List<ProductSpecPO> specs = productSpecService.list(wrapper);
for (ProductSpecPO spec : specs) {
context.specByCodeCache.put(spec.getSpecCode(), spec);
}
}
}
private void preloadProductsByCode(ImportRuntimeContext context, Set<String> productCodes) {
for (List<String> chunk : splitToChunks(productCodes, IN_QUERY_BATCH_SIZE)) {
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getCompanyId, context.companyId)
.in(ProductPO::getProductCode, chunk);
List<ProductPO> products = productMapper.selectList(wrapper);
for (ProductPO product : products) {
cacheProduct(context, product);
}
}
}
private void preloadProductsByName(ImportRuntimeContext context, Set<String> productNames) {
for (List<String> chunk : splitToChunks(productNames, IN_QUERY_BATCH_SIZE)) {
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ProductPO::getCompanyId, context.companyId)
.in(ProductPO::getName, chunk);
List<ProductPO> products = productMapper.selectList(wrapper);
for (ProductPO product : products) {
cacheProduct(context, product);
}
}
}
private void preloadStatuses(ImportRuntimeContext context, Set<String> statusNames, Map<String, Long> statusMapping) {
if (statusMapping != null) {
context.statusIdByNameCache.putAll(statusMapping);
}
for (List<String> chunk : splitToChunks(statusNames, IN_QUERY_BATCH_SIZE)) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, context.companyId)
.in(OrderStatusPO::getStatusName, chunk);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
for (OrderStatusPO status : statusList) {
context.statusIdByNameCache.put(status.getStatusName(), status.getId());
}
}
}
private void preloadPlatformOrderNos(ImportRuntimeContext context, Set<String> platformOrderNos) {
for (List<String> chunk : splitToChunks(platformOrderNos, IN_QUERY_BATCH_SIZE)) {
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, context.companyId)
.in(OrderPO::getPlatformOrderNo, chunk)
.select(OrderPO::getPlatformOrderNo);
List<OrderPO> orders = orderMapper.selectList(wrapper);
for (OrderPO order : orders) {
if (order.getPlatformOrderNo() != null) {
context.existingPlatformOrderNos.add(order.getPlatformOrderNo().trim());
}
}
}
}
private void preloadShopProductRelations(ImportRuntimeContext context) {
LambdaQueryWrapper<ShopProductRelationPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(ShopProductRelationPO::getCompanyId, context.companyId)
.eq(ShopProductRelationPO::getShopId, context.shopId)
.select(ShopProductRelationPO::getProductId);
List<ShopProductRelationPO> relations = shopProductRelationMapper.selectList(wrapper);
for (ShopProductRelationPO relation : relations) {
context.existingRelationKeys.add(buildRelationKey(context.shopId, relation.getProductId()));
}
}
private <T> List<List<T>> splitToChunks(Set<T> values, int chunkSize) {
if (values == null || values.isEmpty()) {
return Collections.emptyList();
}
List<T> all = new ArrayList<>(values);
List<List<T>> chunks = new ArrayList<>();
for (int i = 0; i < all.size(); i += chunkSize) {
chunks.add(all.subList(i, Math.min(i + chunkSize, all.size())));
}
return chunks;
}
private void cacheProduct(ImportRuntimeContext context, ProductPO product) {
context.productByIdCache.put(product.getId(), product);
if (product.getName() != null) {
context.productByNameCache.put(product.getName(), product);
}
if (product.getProductCode() != null) {
context.productByCodeCache.put(product.getProductCode(), product);
}
}
private ProductPO getProductById(Long productId, ImportRuntimeContext context) {
ProductPO cached = context.productByIdCache.get(productId);
if (cached != null) {
return cached;
}
ProductPO product = productMapper.selectById(productId);
if (product != null) {
cacheProduct(context, product);
}
return product;
}
private void validatePlatformOrderNo(String platformOrderNo, ImportRuntimeContext context) {
if (platformOrderNo == null || platformOrderNo.trim().isEmpty()) {
return;
}
String normalized = platformOrderNo.trim();
if (context.existingPlatformOrderNos.contains(normalized) || context.pendingPlatformOrderNos.contains(normalized)) {
throw new BusinessException("平台订单号已存在");
}
context.pendingPlatformOrderNos.add(normalized);
}
private void queueShopProductRelation(CreateOrderDTO orderDTO, ImportRuntimeContext context) {
String relationKey = buildRelationKey(orderDTO.getShopId(), orderDTO.getProductId());
if (context.existingRelationKeys.contains(relationKey) || context.pendingRelationKeys.contains(relationKey)) {
return;
}
ShopProductRelationPO relation = new ShopProductRelationPO();
relation.setCompanyId(context.companyId);
relation.setShopId(orderDTO.getShopId());
relation.setProductId(orderDTO.getProductId());
relation.setSortOrder(0);
relation.setCreateBy(context.createBy);
context.pendingRelations.add(relation);
context.pendingRelationKeys.add(relationKey);
}
private String buildRelationKey(Long shopId, Long productId) {
return shopId + "#" + productId;
}
private void flushPendingRelations(ImportRuntimeContext context) {
if (context.pendingRelations.isEmpty()) {
return;
}
List<ShopProductRelationPO> batch = new ArrayList<>(context.pendingRelations);
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
ShopProductRelationMapper batchMapper = session.getMapper(ShopProductRelationMapper.class);
for (ShopProductRelationPO relation : batch) {
batchMapper.insert(relation);
}
session.flushStatements();
session.commit();
for (ShopProductRelationPO relation : batch) {
context.existingRelationKeys.add(buildRelationKey(relation.getShopId(), relation.getProductId()));
}
} catch (Exception e) {
for (ShopProductRelationPO relation : batch) {
try {
shopProductRelationMapper.insert(relation);
context.existingRelationKeys.add(buildRelationKey(relation.getShopId(), relation.getProductId()));
} catch (Exception ignored) {
// 并发场景下唯一键冲突可忽略,关系存在即可
}
}
} finally {
context.pendingRelations.clear();
context.pendingRelationKeys.clear();
}
}
private int[] flushPendingOrders(ImportRuntimeContext context, StringBuilder errorMessages) {
if (context.pendingOrders.isEmpty()) {
return new int[] {0, 0};
}
int success = 0;
int fail = 0;
List<PendingOrderInsert> batch = new ArrayList<>(context.pendingOrders);
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH, false)) {
OrderMapper batchMapper = session.getMapper(OrderMapper.class);
for (PendingOrderInsert pending : batch) {
batchMapper.insert(pending.order);
}
session.flushStatements();
session.commit();
success += batch.size();
for (PendingOrderInsert pending : batch) {
if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) {
String normalized = pending.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
}
} catch (Exception e) {
for (PendingOrderInsert pending : batch) {
try {
orderMapper.insert(pending.order);
success++;
if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) {
String normalized = pending.platformOrderNo.trim();
context.pendingPlatformOrderNos.remove(normalized);
context.existingPlatformOrderNos.add(normalized);
}
} catch (Exception singleEx) {
fail++;
if (pending.platformOrderNo != null && !pending.platformOrderNo.trim().isEmpty()) {
context.pendingPlatformOrderNos.remove(pending.platformOrderNo.trim());
}
errorMessages.append(String.format("第%d行:%s", pending.rowNumber, singleEx.getMessage()))
.append(System.lineSeparator());
}
}
} finally {
context.pendingOrders.clear();
}
return new int[] {success, fail};
}
private OrderPO buildOrderPO(CreateOrderDTO createOrderDTO, Long companyId, Long createBy, Long importTaskId) {
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.setLinkProductName(createOrderDTO.getLinkProductName());
order.setLinkSpecName(createOrderDTO.getLinkSpecName());
order.setQuantity(createOrderDTO.getQuantity());
order.setUnitPrice(createOrderDTO.getUnitPrice());
order.setProductCost(createOrderDTO.getProductCost());
order.setShippingCost(createOrderDTO.getShippingCost());
order.setOtherCost(createOrderDTO.getOtherCost());
order.setReceivedAmount(createOrderDTO.getReceivedAmount());
order.setOrderTime(createOrderDTO.getOrderTime());
order.setCreateBy(createBy);
order.setImportTaskId(importTaskId);
order.setConfirm(createOrderDTO.getConfirm() != null ? createOrderDTO.getConfirm() : 1);
return order;
}
/**
* 更新任务状态
@@ -1243,15 +1661,27 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @return 订单状态ID,如果不存在则返回null
*/
private Long findOrderStatusIdByName(Long companyId, String statusName) {
return findOrderStatusIdByName(companyId, statusName, null);
}
private Long findOrderStatusIdByName(Long companyId, String statusName, ImportRuntimeContext context) {
if (statusName == null || statusName.trim().isEmpty()) {
return null;
}
String normalized = statusName.trim();
if (context != null && context.statusIdByNameCache.containsKey(normalized)) {
return context.statusIdByNameCache.get(normalized);
}
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.trim());
.eq(OrderStatusPO::getStatusName, normalized);
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
Long statusId = status != null ? status.getId() : null;
if (context != null) {
context.statusIdByNameCache.put(normalized, statusId);
}
return statusId;
}
/**
@@ -1263,6 +1693,10 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
* @return 订单状态ID
*/
private Long createOrderStatusIfNotExists(Long companyId, String statusName, Long createBy) {
return createOrderStatusIfNotExists(companyId, statusName, createBy, null);
}
private Long createOrderStatusIfNotExists(Long companyId, String statusName, Long createBy, ImportRuntimeContext context) {
if (statusName == null || statusName.trim().isEmpty()) {
throw new BusinessException("订单状态名称不能为空");
}
@@ -1270,7 +1704,7 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
String trimmedStatusName = statusName.trim();
// 再次检查状态是否已存在(避免并发创建)
Long existingStatusId = findOrderStatusIdByName(companyId, trimmedStatusName);
Long existingStatusId = findOrderStatusIdByName(companyId, trimmedStatusName, context);
if (existingStatusId != null) {
return existingStatusId;
}
@@ -1286,7 +1720,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
// 保存订单状态
orderStatusService.save(orderStatus);
if (context != null) {
context.statusIdByNameCache.put(trimmedStatusName, orderStatus.getId());
}
return orderStatus.getId();
}
}
@@ -20,6 +20,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskQueueService;
import top.xyquan.ecomdmbbackend.modules.ecom.service.ImportTaskService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
@@ -29,6 +31,8 @@ import java.util.stream.Collectors;
@Service
public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportTaskPO> implements ImportTaskService {
private static final DateTimeFormatter TASK_NAME_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private final CurrentUserContext currentUserContext;
private final ImportTaskQueueService importTaskQueueService;
@@ -49,16 +53,18 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
public ImportTaskVO createImportTask(CreateImportTaskDTO createImportTaskDTO) {
// 从token中获取公司ID
Long companyId = currentUserContext.getCurrentCompanyId();
Long currentUserId = currentUserContext.getCurrentUserId();
// 创建导入任务
ImportTaskPO importTaskPO = new ImportTaskPO();
BeanUtils.copyProperties(createImportTaskDTO, importTaskPO);
importTaskPO.setCompanyId(companyId);
importTaskPO.setTaskName(generateTaskName(currentUserId));
importTaskPO.setStatus("pending"); // 初始状态为待处理
importTaskPO.setTotalCount(0);
importTaskPO.setSuccessCount(0);
importTaskPO.setFailCount(0);
importTaskPO.setCreateBy(currentUserContext.getCurrentUserId());
importTaskPO.setCreateBy(currentUserId);
this.save(importTaskPO);
@@ -130,5 +136,9 @@ public class ImportTaskServiceImpl extends ServiceImpl<ImportTaskMapper, ImportT
BeanUtils.copyProperties(importTaskPO, importTaskVO);
return importTaskVO;
}
private String generateTaskName(Long userId) {
return "T-" + userId + "-" + LocalDateTime.now().format(TASK_NAME_TIME_FORMATTER);
}
}
@@ -87,6 +87,7 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
LocalDateTime startDateTime = startDate.atStartOfDay();
LocalDateTime endDateTime = endDate.atTime(23, 59, 59);
List<Long> autoStatisticsStatusIds = getAutoStatisticsStatusIds(companyId);
// 验证店铺是否存在
ShopPO shop = shopService.getById(queryDTO.getShopId());
@@ -100,6 +101,11 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
.eq(OrderPO::getShopId, queryDTO.getShopId())
.ge(OrderPO::getOrderTime, startDateTime)
.le(OrderPO::getOrderTime, endDateTime);
if (!autoStatisticsStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds);
} else {
orderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> orders = orderMapper.selectList(orderWrapper);
// 查询推广费数据(该店铺)
@@ -132,6 +138,11 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
.eq(OrderPO::getShopId, queryDTO.getShopId())
.ge(OrderPO::getOrderTime, lastMonthStartDateTime)
.le(OrderPO::getOrderTime, lastMonthEndDateTime);
if (!autoStatisticsStatusIds.isEmpty()) {
lastMonthOrderWrapper.in(OrderPO::getStatusId, autoStatisticsStatusIds);
} else {
lastMonthOrderWrapper.isNull(OrderPO::getId);
}
List<OrderPO> lastMonthOrders = orderMapper.selectList(lastMonthOrderWrapper);
// 构建返回对象
@@ -523,5 +534,16 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
OrderStatusPO status = orderStatusService.getOne(wrapper);
return status != null ? status.getId() : null;
}
private List<Long> getAutoStatisticsStatusIds(Long companyId) {
LambdaQueryWrapper<OrderStatusPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderStatusPO::getCompanyId, companyId)
.eq(OrderStatusPO::getAutoStatistics, 1)
.select(OrderStatusPO::getId);
List<OrderStatusPO> statusList = orderStatusService.list(wrapper);
return statusList.stream()
.map(OrderStatusPO::getId)
.collect(Collectors.toList());
}
}
@@ -208,6 +208,7 @@ CREATE TABLE `ec_import_tasks` (
`company_id` bigint unsigned NOT NULL COMMENT '所属公司ID',
`shop_id` bigint unsigned NOT NULL COMMENT '所属店铺ID',
`type` enum('product','order') NOT NULL COMMENT '导入类型(product-商品 order-订单)',
`task_name` varchar(100) DEFAULT NULL COMMENT '任务名称',
`file_name` varchar(255) NOT NULL COMMENT '原始文件名',
`file_path` varchar(500) NOT NULL COMMENT '存储路径',
`status` enum('pending','processing','success','failed') DEFAULT 'pending' NOT NULL COMMENT '任务状态(pending-待处理 processing-处理中 success-成功 failed-失败)',
@@ -0,0 +1,2 @@
ALTER TABLE `ec_import_tasks`
ADD COLUMN `task_name` VARCHAR(100) DEFAULT NULL COMMENT '任务名称' AFTER `type`;