diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java index e28bbf8d..62e9478e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/brushorder/service/impl/BrushOrderServiceImpl.java @@ -20,7 +20,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSkuPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.vo.BrushOrderVO; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.service.BrushOrderService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; @@ -39,16 +38,13 @@ public class BrushOrderServiceImpl extends ServiceImpl progressCallback; - /** 本任务涉及、需 refresh 汇总表的自然日(order_time → Asia/Shanghai DATE) */ - private final Set dirtyStatDates = ConcurrentHashMap.newKeySet(); + /** 本任务涉及的自然日(订单统计已移除,保留空实现供导入流程调用) */ + public void markOrderStatDirty(LocalDateTime orderTime) { + // no-op + } - private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); + public void markOrderStatDirty(Long targetShopId, LocalDateTime orderTime) { + // no-op + } + + /** 更新订单时标记旧快照日期(订单统计已移除,空实现) */ + public void markOrderStatDirtyFromSnapshot(OrderPO before) { + // no-op + } /** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */ private transient Map orderImportFieldMapping; @@ -254,35 +261,6 @@ public class ImportRuntimeContext { public Set getPendingRelationKeys() { return pendingRelationKeys; } public Set getPendingPlatformOrderNos() { return pendingPlatformOrderNos; } - public Set getDirtyStatDates() { - return Collections.unmodifiableSet(dirtyStatDates); - } - - /** - * 标记订单所属自然日需重算汇总(导入/更新路径调用)。 - */ - public void markOrderStatDirty(LocalDateTime orderTime) { - markOrderStatDirty(shopId, orderTime); - } - - public void markOrderStatDirty(Long targetShopId, LocalDateTime orderTime) { - if (orderTime == null || targetShopId == null) { - return; - } - dirtyStatDates.add(orderTime.atZone(STAT_ZONE).toLocalDate()); - } - - /** 更新订单时:旧快照的 shop/date 也需 refresh */ - public void markOrderStatDirtyFromSnapshot(OrderPO before) { - if (before == null || before.getOrderTime() == null) { - return; - } - Long sid = before.getShopId() != null ? before.getShopId() : shopId; - markOrderStatDirty(sid, before.getOrderTime()); - } - - // ==================== 工具方法 ==================== - public void addNormalizedValue(Set target, String rawValue) { if (rawValue == null) return; String value = rawValue.trim(); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java index 4b6b2bf5..e28d9660 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/importtask/service/impl/ImportTaskProcessorServiceImpl.java @@ -15,9 +15,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskServi import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderItemMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatRefreshService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRefreshCoordinator; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuCostService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService; @@ -38,13 +35,8 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.nio.charset.StandardCharsets; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; /** @@ -65,8 +57,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic // 提取出的处理器(构造时组装,不单独持有 helper 的中间依赖) private final OrderImportProcessor orderImportProcessor; private final PromotionFeeImportProcessor promotionFeeImportProcessor; - private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; - private final FeeStatRefreshService feeStatRefreshService; private final LicenseFeatureGuard licenseFeatureGuard; public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService, @@ -82,8 +72,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic OssService ossService, SysFileService sysFileService, PromotionFeeImportProcessor promotionFeeImportProcessor, - OrderStatRefreshCoordinator orderStatRefreshCoordinator, - FeeStatRefreshService feeStatRefreshService, LicenseFeatureGuard licenseFeatureGuard) { this.importTaskService = importTaskService; this.licenseFeatureGuard = licenseFeatureGuard; @@ -93,8 +81,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic this.ossService = ossService; this.sysFileService = sysFileService; this.promotionFeeImportProcessor = promotionFeeImportProcessor; - this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; - this.feeStatRefreshService = feeStatRefreshService; ProductSkuImportHelper productSkuImportHelper = new ProductSkuImportHelper( productMapper, productSkuService, productSkuCostService, shopProductRelationMapper); @@ -222,42 +208,11 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary; updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); - // 明细写入成功后:异步排队 refresh 汇总表(不阻塞导入线程) - enqueueOrderStatRefreshAfterImport(task, context); - } finally { if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); } } - /** 合并内存脏日期 + DB 兜底,写入 refresh 队列 */ - private void enqueueOrderStatRefreshAfterImport(ImportTaskPO task, ImportRuntimeContext context) { - if (task.getCompanyId() == null || task.getShopId() == null) { - return; - } - Set dates = new HashSet<>(context.getDirtyStatDates()); - try { - List fromDb = orderMapper.selectDistinctOrderDatesByImportTaskId(task.getId()); - if (fromDb != null) { - dates.addAll(fromDb); - } - } catch (Exception e) { - // 兜底查询失败不影响导入成功态 - } - if (dates.isEmpty()) { - return; - } - int queued = orderStatRefreshCoordinator.enqueueRefresh( - task.getCompanyId(), task.getShopId(), dates, RefreshSource.IMPORT); - if (queued > 0) { - ImportTaskPO t = importTaskService.getById(task.getId()); - if (t != null && t.getMessage() != null) { - t.setMessage(t.getMessage() + String.format(";汇总刷新已排队 %d 个自然日", dates.size())); - importTaskService.updateById(t); - } - } - } - private void processPromotionFeeImport(ImportTaskPO task) throws Exception { com.fasterxml.jackson.databind.JsonNode rootNode; try { @@ -322,28 +277,12 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic message += "\n" + result.detailMessage; } updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount); - refreshFeeStatAfterPromotionImport(task, feeDateStr, result.successCount); } finally { if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete(); } } - /** 推广费导入成功后重算对应自然日的费汇总表 */ - private void refreshFeeStatAfterPromotionImport(ImportTaskPO task, String feeDateStr, int successCount) { - if (successCount <= 0 || task.getShopId() == null || feeDateStr == null || feeDateStr.isBlank()) { - return; - } - try { - LocalDate feeDate = LocalDate.parse(feeDateStr.trim(), DateTimeFormatter.ISO_LOCAL_DATE); - feeStatRefreshService.refreshShopDay(task.getCompanyId(), task.getShopId(), feeDate); - } catch (DateTimeParseException e) { - log.warn("推广费导入后 refresh 跳过:feeDate 格式无效 taskId={} feeDate={}", task.getId(), feeDateStr); - } catch (Exception e) { - log.warn("推广费导入后 refresh 失败 taskId={} shopId={} feeDate={}", task.getId(), task.getShopId(), feeDateStr, e); - } - } - private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) { try { if (mappingJson == null || mappingJson.trim().isEmpty()) { diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java index 5189e21e..4b0d745e 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderMapper.java @@ -7,10 +7,7 @@ import org.apache.ibatis.annotations.Update; import org.apache.ibatis.annotations.Select; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderListQueryParam; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow; - import java.math.BigDecimal; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; @@ -46,38 +43,6 @@ public interface OrderMapper extends BaseMapper { @Param("skuCode") String skuCode, @Param("productSkuId") Long productSkuId); - @Select("SELECT DISTINCT DATE(order_time) FROM ec_order WHERE import_task_id = #{importTaskId}") - List selectDistinctOrderDatesByImportTaskId(@Param("importTaskId") Long importTaskId); - - @Select(""" - SELECT DISTINCT DATE(order_time) AS statDate FROM ec_order - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND order_time >= #{startDate} AND order_time < DATE_ADD(#{endDate}, INTERVAL 1 DAY) - ORDER BY statDate - """) - List selectDistinctOrderDatesByCompanyShopRange( - @Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - @Select("SELECT MIN(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId}") - LocalDate selectMinOrderDateByCompany(@Param("companyId") Long companyId); - - @Select("SELECT MAX(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId}") - LocalDate selectMaxOrderDateByCompany(@Param("companyId") Long companyId); - - @Select(""" - SELECT i.shop_id AS shopId, DATE(o.order_time) AS statDate - FROM ec_order_item i - INNER JOIN ec_order o ON o.id = i.order_id - WHERE i.company_id = #{companyId} AND i.sku_code = #{skuCode} AND i.product_sku_id IS NULL - GROUP BY i.shop_id, DATE(o.order_time) - """) - List selectOrphanOrderStatDatesBySkuCode( - @Param("companyId") Long companyId, - @Param("skuCode") String skuCode); - long countOrderList(OrderListQueryParam param); List selectOrderListIds(OrderListQueryParam param); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderStatAggMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderStatAggMapper.java deleted file mode 100644 index 76f525c5..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/mapper/OrderStatAggMapper.java +++ /dev/null @@ -1,178 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.mapper; - -import lombok.Data; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; - -/** - * 订单/费用 SQL 聚合(SQL 均在 {@code mapper/order/OrderStatAggMapper.xml})。 - *

- * 行类型定义为内嵌类,避免单独拆多个 model 文件。 - */ -@Mapper -public interface OrderStatAggMapper { - - /** SQL-1:shop × product 粒度,四表 rollup 基础 */ - List aggregateByShopProduct( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("start") LocalDateTime start, - @Param("end") LocalDateTime end, - @Param("unionStatusCodes") List unionStatusCodes, - @Param("salesStatusCodes") List salesStatusCodes, - @Param("refundStatusCodes") List refundStatusCodes, - @Param("productCostStatusCodes") List productCostStatusCodes, - @Param("freightCostStatusCodes") List freightCostStatusCodes, - @Param("otherCostStatusCodes") List otherCostStatusCodes); - - /** SQL-2:日趋势 */ - List aggregateDaily( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("start") LocalDateTime start, - @Param("end") LocalDateTime end, - @Param("unionStatusCodes") List unionStatusCodes, - @Param("salesStatusCodes") List salesStatusCodes, - @Param("refundStatusCodes") List refundStatusCodes, - @Param("productCostStatusCodes") List productCostStatusCodes, - @Param("freightCostStatusCodes") List freightCostStatusCodes, - @Param("otherCostStatusCodes") List otherCostStatusCodes); - - /** SQL-3:三段时间 KPI(一次扫描) */ - PeriodKpiRow aggregatePeriodKpi( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("scanStart") LocalDateTime scanStart, - @Param("scanEnd") LocalDateTime scanEnd, - @Param("curStart") LocalDateTime curStart, - @Param("curEnd") LocalDateTime curEnd, - @Param("prevStart") LocalDateTime prevStart, - @Param("prevEnd") LocalDateTime prevEnd, - @Param("yoyStart") LocalDateTime yoyStart, - @Param("yoyEnd") LocalDateTime yoyEnd, - @Param("unionStatusCodes") List unionStatusCodes, - @Param("salesStatusCodes") List salesStatusCodes, - @Param("refundStatusCodes") List refundStatusCodes, - @Param("productCostStatusCodes") List productCostStatusCodes, - @Param("freightCostStatusCodes") List freightCostStatusCodes, - @Param("otherCostStatusCodes") List otherCostStatusCodes); - - /** 推广费三段时间 KPI */ - FeeKpiRow aggregatePromotionPeriodKpi( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("scanStart") LocalDate scanStart, - @Param("scanEnd") LocalDate scanEnd, - @Param("curStart") LocalDate curStart, - @Param("curEnd") LocalDate curEnd, - @Param("prevStart") LocalDate prevStart, - @Param("prevEnd") LocalDate prevEnd, - @Param("yoyStart") LocalDate yoyStart, - @Param("yoyEnd") LocalDate yoyEnd); - - /** 刷单费三段时间 KPI */ - FeeKpiRow aggregateBrushPeriodKpi( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("scanStart") LocalDateTime scanStart, - @Param("scanEnd") LocalDateTime scanEnd, - @Param("curStart") LocalDateTime curStart, - @Param("curEnd") LocalDateTime curEnd, - @Param("prevStart") LocalDateTime prevStart, - @Param("prevEnd") LocalDateTime prevEnd, - @Param("yoyStart") LocalDateTime yoyStart, - @Param("yoyEnd") LocalDateTime yoyEnd); - - /** SQL-4:推广费明细(四表分摊) */ - List aggregatePromotionFees( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - /** SQL-5:刷单费按店铺 */ - List aggregateBrushFees( - @Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("start") LocalDateTime start, - @Param("end") LocalDateTime end); - - @Data - class ShopProductRow { - private Long shopId; - private String platformCode; - private Long productId; - private Long categoryId; - private BigDecimal salesAmount; - private Long orderCount; - private Long salesQuantitySum; - private BigDecimal refundAmount; - private BigDecimal productCost; - private BigDecimal freightCost; - private BigDecimal otherCost; - private BigDecimal gmvAllStatus; - private Long gmvOrderCount; - private Long gmvQuantitySum; - } - - @Data - class DailyRow { - private LocalDate statDate; - private BigDecimal salesAmount; - private BigDecimal refundAmount; - private BigDecimal productCost; - private BigDecimal freightCost; - private BigDecimal otherCost; - } - - @Data - class PeriodKpiRow { - private BigDecimal curSalesAmount; - private Long curOrderCount; - private BigDecimal curRefundAmount; - private BigDecimal curProductCost; - private BigDecimal curFreightCost; - private BigDecimal curOtherCost; - private BigDecimal curGmvAllStatus; - private BigDecimal prevSalesAmount; - private Long prevOrderCount; - private BigDecimal prevRefundAmount; - private BigDecimal prevProductCost; - private BigDecimal prevFreightCost; - private BigDecimal prevOtherCost; - private BigDecimal prevGmvAllStatus; - private BigDecimal yoySalesAmount; - private Long yoyOrderCount; - private BigDecimal yoyRefundAmount; - private BigDecimal yoyProductCost; - private BigDecimal yoyFreightCost; - private BigDecimal yoyOtherCost; - private BigDecimal yoyGmvAllStatus; - } - - @Data - class FeeKpiRow { - private BigDecimal curAmount; - private BigDecimal prevAmount; - private BigDecimal yoyAmount; - } - - @Data - class PromotionRow { - private Long shopId; - private Long productId; - private Long categoryId; - private BigDecimal feeAmount; - } - - @Data - class BrushRow { - private Long shopId; - private BigDecimal brushAmount; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java index bef8e5af..01dfab8d 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/service/impl/OrderServiceImpl.java @@ -33,8 +33,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.enums.OrderStat import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo.ShopVO; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService; import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeature; import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeatureGuard; @@ -67,20 +65,17 @@ public class OrderServiceImpl extends ServiceImpl implemen private final ProductService productService; private final ProductSkuService productSkuService; private final OrderItemMapper orderItemMapper; - private final OrderStatCrudCoordinator orderStatCrudCoordinator; private final LicenseFeatureGuard licenseFeatureGuard; public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService, ProductService productService, ProductSkuService productSkuService, OrderItemMapper orderItemMapper, - OrderStatCrudCoordinator orderStatCrudCoordinator, LicenseFeatureGuard licenseFeatureGuard) { this.currentUserContext = currentUserContext; this.shopService = shopService; this.productService = productService; this.productSkuService = productSkuService; this.orderItemMapper = orderItemMapper; - this.orderStatCrudCoordinator = orderStatCrudCoordinator; this.licenseFeatureGuard = licenseFeatureGuard; } @@ -103,7 +98,6 @@ public class OrderServiceImpl extends ServiceImpl implemen order.setCreateBy(userId); this.save(order); saveItems(order, itemDtos, companyId, userId); - orderStatCrudCoordinator.afterOrderSaved(null, order); return convertToVO(order); } @@ -154,7 +148,6 @@ public class OrderServiceImpl extends ServiceImpl implemen } OrderPO after = this.getById(id); - orderStatCrudCoordinator.afterOrderSaved(existingOrder, after); return convertToVO(after != null ? after : order); } @@ -163,7 +156,6 @@ public class OrderServiceImpl extends ServiceImpl implemen public void deleteOrder(Long id) { Long companyId = currentUserContext.getCurrentCompanyId(); OrderPO existingOrder = requireOrder(id, companyId); - orderStatCrudCoordinator.afterOrderDeleted(existingOrder); orderItemMapper.delete(new LambdaQueryWrapper().eq(OrderItemPO::getOrderId, id)); this.removeById(id); } @@ -188,7 +180,6 @@ public class OrderServiceImpl extends ServiceImpl implemen if (toRemove.size() != uniqueIds.size()) { throw new BusinessException("存在无效订单或无权删除的订单"); } - orderStatCrudCoordinator.afterOrdersDeletedBatch(toRemove); orderItemMapper.delete(new LambdaQueryWrapper().in(OrderItemPO::getOrderId, uniqueIds)); this.remove(wrapper); } @@ -272,28 +263,6 @@ public class OrderServiceImpl extends ServiceImpl implemen try { ProductSkuPO sku = productSkuService.getById(skuId); int n = baseMapper.updateCostFields(productCost, shippingCost, otherCost, skuId, startTime, endTime); - if (n > 0 && sku != null && sku.getCompanyId() != null) { - List affected = orderItemMapper.selectList(new LambdaQueryWrapper() - .eq(OrderItemPO::getCompanyId, sku.getCompanyId()) - .eq(OrderItemPO::getProductSkuId, skuId)); - Set orderIds = affected.stream().map(OrderItemPO::getOrderId).filter(Objects::nonNull).collect(Collectors.toSet()); - if (!orderIds.isEmpty()) { - List orders = list(new LambdaQueryWrapper() - .in(OrderPO::getId, orderIds) - .ge(OrderPO::getOrderTime, startTime) - .le(OrderPO::getOrderTime, endTime) - .select(OrderPO::getCompanyId, OrderPO::getShopId, OrderPO::getOrderTime)); - Set keys = new HashSet<>(); - ZoneId zone = ZoneId.of("Asia/Shanghai"); - for (OrderPO o : orders) { - if (o.getShopId() != null && o.getOrderTime() != null) { - keys.add(new StatDirtyKey(o.getCompanyId(), o.getShopId(), - o.getOrderTime().atZone(zone).toLocalDate())); - } - } - orderStatCrudCoordinator.enqueueDirtyKeys(keys); - } - } return n; } catch (Exception ex) { log.warn("同步成本到订单跳过(订单表可能不存在): {}", ex.getMessage()); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java deleted file mode 100644 index ca4978ef..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/config/OrderStatProperties.java +++ /dev/null @@ -1,46 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -/** - * 订单统计读模型配置(写入 Worker、读路径开关、缓存 TTL)。 - */ -@Data -@Component -@ConfigurationProperties(prefix = "order-stat") -public class OrderStatProperties { - - /** daily=读汇总表;order=应急回退扫 ec_order */ - private String statSource = "daily"; - - /** 汇总行缺失时同步补算 */ - private boolean autoRefreshOnMiss = true; - - /** 是否启用夜间全公司 rebuild 定时任务 */ - private boolean nightlyRebuildEnabled = false; - - /** cron 表达式,见 {@code order-stat.nightly-rebuild-cron} */ - private String nightlyRebuildCron = "0 30 2 * * ?"; - - private RefreshWorker refreshWorker = new RefreshWorker(); - - private Cache cache = new Cache(); - - @Data - public static class RefreshWorker { - /** 是否启动异步 refresh 消费者 */ - private boolean enabled = true; - private int poolSize = 4; - /** 轮询 ec_order_stat_refresh_queue 间隔毫秒 */ - private long pollIntervalMs = 2000; - } - - @Data - public static class Cache { - private boolean enabled = true; - private long ttlHistorySeconds = 86400; - private long ttlTodaySeconds = 900; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java deleted file mode 100644 index 25d88bd1..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/controller/OrderStatAdminController.java +++ /dev/null @@ -1,61 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.controller; - -import io.swagger.v3.oas.annotations.Operation; -import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission; -import top.xyquan.ecomdmbbackend.common.response.ApiResponse; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatRebuildRequestDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatReconcileRequestDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReconcileService; - -@Tag(name = "电商-订单统计管理", description = "汇总表 backfill / rebuild") -@RestController -@RequestMapping("/ec/admin/order-stat") -public class OrderStatAdminController { - - private final OrderStatRebuildService orderStatRebuildService; - private final OrderStatReconcileService orderStatReconcileService; - - public OrderStatAdminController(OrderStatRebuildService orderStatRebuildService, - OrderStatReconcileService orderStatReconcileService) { - this.orderStatRebuildService = orderStatRebuildService; - this.orderStatReconcileService = orderStatReconcileService; - } - - @Operation(summary = "创建 rebuild 任务", description = "异步按 shop×date 重算日/月/年汇总表") - @PostMapping("/rebuild") - @RequirePermission(value = "ecom:shop:read", description = "订单统计 rebuild", allowSuper = true) - public ApiResponse rebuild(@Valid @RequestBody OrderStatRebuildRequestDTO dto) { - Long taskId = orderStatRebuildService.scheduleRebuild( - dto.getCompanyId(), dto.getShopId(), dto.getStartDate(), dto.getEndDate()); - return ApiResponse.success("rebuild 任务已创建", taskId); - } - - @Operation(summary = "查询 rebuild 进度") - @GetMapping("/rebuild/{taskId}") - @RequirePermission(value = "ecom:shop:read", description = "查询 rebuild 进度", allowSuper = true) - public ApiResponse rebuildStatus(@PathVariable Long taskId) { - OrderStatRebuildTaskPO task = orderStatRebuildService.getTask(taskId); - return ApiResponse.success("查询成功", task); - } - - @Operation(summary = "抽样对账", description = "汇总表 vs 明细聚合,默认 100 个 shop×date") - @PostMapping("/reconcile") - @RequirePermission(value = "ecom:shop:read", description = "订单统计对账", allowSuper = true) - public ApiResponse reconcile( - @Valid @RequestBody OrderStatReconcileRequestDTO dto) { - int sample = dto.getSampleSize() != null ? dto.getSampleSize() : 100; - OrderStatReconcileService.ReconcileReport report = orderStatReconcileService.reconcileCompany( - dto.getCompanyId(), dto.getStartDate(), dto.getEndDate(), sample); - return ApiResponse.success(report.isPassed() ? "对账通过" : "存在差异", report); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java deleted file mode 100644 index 430c99bf..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/job/OrderStatNightlyRebuildJob.java +++ /dev/null @@ -1,64 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.job; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Component; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService; -import top.xyquan.ecomdmbbackend.modules.org.company.model.po.CompanyPO; -import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService; - -import java.time.LocalDate; -import java.util.List; - -/** - * 夜间全公司汇总灌数:按公司订单日期范围创建 rebuild 任务。 - */ -@Component -public class OrderStatNightlyRebuildJob { - - private static final Logger log = LoggerFactory.getLogger(OrderStatNightlyRebuildJob.class); - - private final OrderStatProperties properties; - private final CompanyService companyService; - private final OrderMapper orderMapper; - private final OrderStatRebuildService orderStatRebuildService; - - public OrderStatNightlyRebuildJob(OrderStatProperties properties, - CompanyService companyService, - OrderMapper orderMapper, - OrderStatRebuildService orderStatRebuildService) { - this.properties = properties; - this.companyService = companyService; - this.orderMapper = orderMapper; - this.orderStatRebuildService = orderStatRebuildService; - } - - /** 默认每天 02:30 触发(可在 yml 覆盖 cron) */ - @Scheduled(cron = "${order-stat.nightly-rebuild-cron:0 30 2 * * ?}") - public void runNightlyRebuild() { - if (!properties.isNightlyRebuildEnabled()) { - return; - } - List companies = companyService.list(); - for (CompanyPO company : companies) { - try { - scheduleCompany(company.getId()); - } catch (Exception e) { - log.warn("nightly rebuild schedule failed company={}", company.getId(), e); - } - } - } - - private void scheduleCompany(Long companyId) { - LocalDate start = orderMapper.selectMinOrderDateByCompany(companyId); - LocalDate end = orderMapper.selectMaxOrderDateByCompany(companyId); - if (start == null || end == null) { - return; - } - Long taskId = orderStatRebuildService.scheduleRebuild(companyId, null, start, end); - log.info("nightly rebuild scheduled company={} taskId={} range {}~{}", companyId, taskId, start, end); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java deleted file mode 100644 index 8b5ad71a..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/FeeStatDailyMapper.java +++ /dev/null @@ -1,64 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import lombok.Data; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.List; - -@Mapper -public interface FeeStatDailyMapper extends BaseMapper { - - void deletePromotionDaily(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - void batchInsertPromotionDaily(@Param("list") List list); - - void rollupPromotionMonthly(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statMonth") LocalDate statMonth); - - void rollupPromotionYearly(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statYear") int statYear); - - void deleteBrushDaily(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - void upsertBrushDaily(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate, - @Param("brushAmount") BigDecimal brushAmount); - - void rollupBrushMonthly(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statMonth") LocalDate statMonth); - - void rollupBrushYearly(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statYear") int statYear); - - /** 从 ec_promotion_fee 聚合单日单店 */ - List aggregatePromotionByShopDay( - @Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - /** 从 ec_brush_order 聚合单日单店 */ - BigDecimal aggregateBrushByShopDay(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - @Data - class PromotionFeeAggRow { - private Long productId; - private Long categoryId; - private BigDecimal feeAmount; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java deleted file mode 100644 index 1ab785a2..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatDailyMapper.java +++ /dev/null @@ -1,55 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO; - -import java.time.LocalDate; -import java.util.List; - -@Mapper -public interface OrderStatDailyMapper extends BaseMapper { - - void upsertDailyShop(OrderStatDailyShopPO row); - - void deleteDailyProduct(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - void batchInsertDailyProduct(@Param("list") List list); - - void deleteDailySpec(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate); - - void batchInsertDailySpec(@Param("list") List list); - - /** 日表 → 月表(店铺) */ - void rollupMonthlyShop(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statMonth") LocalDate statMonth); - - /** 日表 → 年表(店铺) */ - void rollupYearlyShop(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statYear") int statYear); - - void rollupMonthlyProduct(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statMonth") LocalDate statMonth); - - void rollupYearlyProduct(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statYear") int statYear); - - void rollupMonthlySpec(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statMonth") LocalDate statMonth); - - void rollupYearlySpec(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statYear") int statYear); -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java deleted file mode 100644 index 6d34ca91..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatQueryMapper.java +++ /dev/null @@ -1,98 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; - -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; - -import java.time.LocalDate; -import java.util.List; - -/** 汇总表读路径 SQL(日/月/年表 SUM)。 */ -@Mapper -public interface OrderStatQueryMapper { - - OrderStatMetricsDTO sumDailyShop(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyShopByDay(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyShopByShop(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyProductByCategory(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyProductByProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyProductByShopProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - OrderStatMetricsDTO sumDailyProductForOneProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("productId") Long productId, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumDailyProductByDayForOneProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("productId") Long productId, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumMonthlyProductByCategory(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startMonth") LocalDate startMonth, - @Param("endMonth") LocalDate endMonth); - - List sumMonthlyProductByProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startMonth") LocalDate startMonth, - @Param("endMonth") LocalDate endMonth); - - List sumYearlyProductByCategory(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startYear") int startYear, - @Param("endYear") int endYear); - - List sumYearlyProductByProduct(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startYear") int startYear, - @Param("endYear") int endYear); - - List sumDailySpecBySpec(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("productId") Long productId, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); - - List sumMonthlySpecBySpec(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("productId") Long productId, - @Param("startMonth") LocalDate startMonth, - @Param("endMonth") LocalDate endMonth); - - List sumYearlySpecBySpec(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("productId") Long productId, - @Param("startYear") int startYear, - @Param("endYear") int endYear); - - int countDailyShopRows(@Param("companyId") Long companyId, - @Param("shopIds") List shopIds, - @Param("startDate") LocalDate startDate, - @Param("endDate") LocalDate endDate); -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java deleted file mode 100644 index 08cc35dc..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRebuildTaskMapper.java +++ /dev/null @@ -1,9 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import org.apache.ibatis.annotations.Mapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; - -@Mapper -public interface OrderStatRebuildTaskMapper extends BaseMapper { -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java deleted file mode 100644 index dfa2f63b..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/mapper/OrderStatRefreshMapper.java +++ /dev/null @@ -1,63 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper; - -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import lombok.Data; -import org.apache.ibatis.annotations.Mapper; -import org.apache.ibatis.annotations.Param; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.List; - -@Mapper -public interface OrderStatRefreshMapper extends BaseMapper { - - void markDone(@Param("id") Long id); - - void markFailed(@Param("id") Long id, @Param("retryCount") int retryCount); - - /** 入队:若已有 pending 同维度则忽略 */ - int insertPendingIgnore(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("statDate") LocalDate statDate, - @Param("source") String source); - - /** - * 单日单店规格维度聚合(口径与 OrderStatAggMapper 一致)。 - */ - /** 全状态 GMV 订单笔数(单日单店) */ - Integer countGmvOrdersByShopDay(@Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("start") java.time.LocalDateTime start, - @Param("end") java.time.LocalDateTime end); - - List aggregateSpecByShopDay( - @Param("companyId") Long companyId, - @Param("shopId") Long shopId, - @Param("start") LocalDateTime start, - @Param("end") LocalDateTime end, - @Param("unionStatusCodes") List unionStatusCodes, - @Param("salesStatusCodes") List salesStatusCodes, - @Param("refundStatusCodes") List refundStatusCodes, - @Param("productCostStatusCodes") List productCostStatusCodes, - @Param("freightCostStatusCodes") List freightCostStatusCodes, - @Param("otherCostStatusCodes") List otherCostStatusCodes); - - @Data - class SpecDayRow { - private Long productId; - private Long productSkuId; - private BigDecimal salesAmount; - private Long orderCount; - private BigDecimal refundAmount; - private Integer salesQuantitySum; - private BigDecimal gmvAmount; - private Long gmvOrderCount; - private Integer gmvQuantitySum; - private BigDecimal productCost; - private BigDecimal freightCost; - private BigDecimal otherCost; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java deleted file mode 100644 index b87c54ec..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/OrderShopStatDateRow.java +++ /dev/null @@ -1,12 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model; - -import lombok.Data; - -import java.time.LocalDate; - -/** 订单汇总 refresh 维度:店铺 + 自然日 */ -@Data -public class OrderShopStatDateRow { - private Long shopId; - private LocalDate statDate; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java deleted file mode 100644 index 237f2d8e..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatMetricsDTO.java +++ /dev/null @@ -1,42 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; - -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; - -/** - * 汇总表读侧统一指标 DTO(店铺/商品/规格维度共用字段集)。 - */ -@Data -public class OrderStatMetricsDTO { - - private LocalDate statDate; - private Long shopId; - private String platformCode; - private Long productId; - private Long categoryId; - private Long productSkuId; - - private BigDecimal salesAmount = BigDecimal.ZERO; - private BigDecimal refundAmount = BigDecimal.ZERO; - private Integer salesOrderCount = 0; - /** 实际销量件数(sales_quantity_sum) */ - private Integer salesQuantitySum = 0; - private BigDecimal productCost = BigDecimal.ZERO; - private BigDecimal freightCost = BigDecimal.ZERO; - private BigDecimal otherCost = BigDecimal.ZERO; - private BigDecimal gmvAmount = BigDecimal.ZERO; - private Integer gmvOrderCount = 0; - /** GMV 销量件数(gmv_quantity_sum) */ - private Integer gmvQuantitySum = 0; - - /** 订单成本合计 */ - public BigDecimal getOrderCost() { - return nz(productCost).add(nz(freightCost)).add(nz(otherCost)); - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java deleted file mode 100644 index b2e37767..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatRebuildRequestDTO.java +++ /dev/null @@ -1,27 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; -import lombok.Data; - -import java.time.LocalDate; - -@Data -@Schema(description = "订单统计 rebuild 请求") -public class OrderStatRebuildRequestDTO { - - @NotNull - @Schema(description = "公司ID") - private Long companyId; - - @Schema(description = "店铺ID,空=全店") - private Long shopId; - - @NotNull - @Schema(description = "起始自然日") - private LocalDate startDate; - - @NotNull - @Schema(description = "结束自然日") - private LocalDate endDate; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java deleted file mode 100644 index 54abf51e..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/dto/OrderStatReconcileRequestDTO.java +++ /dev/null @@ -1,24 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.NotNull; -import lombok.Data; - -import java.time.LocalDate; - -@Data -@Schema(description = "汇总表对账请求") -public class OrderStatReconcileRequestDTO { - - @NotNull - private Long companyId; - - @NotNull - private LocalDate startDate; - - @NotNull - private LocalDate endDate; - - @Schema(description = "抽样条数,默认 100") - private Integer sampleSize = 100; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java deleted file mode 100644 index 4879f948..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyProductPO.java +++ /dev/null @@ -1,74 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_order_stat_daily_product") -public class OrderStatDailyProductPO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("product_id") - private Long productId; - - @TableField("category_id") - private Long categoryId; - - @TableField("stat_date") - private LocalDate statDate; - - @TableField("sales_amount") - private BigDecimal salesAmount; - - @TableField("refund_amount") - private BigDecimal refundAmount; - - @TableField("sales_order_count") - private Integer salesOrderCount; - - @TableField("sales_quantity_sum") - private Integer salesQuantitySum; - - @TableField("gmv_amount") - private BigDecimal gmvAmount; - - @TableField("gmv_order_count") - private Integer gmvOrderCount; - - @TableField("gmv_quantity_sum") - private Integer gmvQuantitySum; - - @TableField("product_cost") - private BigDecimal productCost; - - @TableField("freight_cost") - private BigDecimal freightCost; - - @TableField("other_cost") - private BigDecimal otherCost; - - @TableField("stat_version") - private Integer statVersion; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java deleted file mode 100644 index 723edd6e..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailyShopPO.java +++ /dev/null @@ -1,71 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_order_stat_daily_shop") -public class OrderStatDailyShopPO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("platform_code") - private String platformCode; - - @TableField("stat_date") - private LocalDate statDate; - - @TableField("sales_amount") - private BigDecimal salesAmount; - - @TableField("refund_amount") - private BigDecimal refundAmount; - - @TableField("sales_order_count") - private Integer salesOrderCount; - - @TableField("sales_quantity_sum") - private Integer salesQuantitySum; - - @TableField("product_cost") - private BigDecimal productCost; - - @TableField("freight_cost") - private BigDecimal freightCost; - - @TableField("other_cost") - private BigDecimal otherCost; - - @TableField("gmv_amount") - private BigDecimal gmvAmount; - - @TableField("gmv_order_count") - private Integer gmvOrderCount; - - @TableField("gmv_quantity_sum") - private Integer gmvQuantitySum; - - @TableField("stat_version") - private Integer statVersion; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java deleted file mode 100644 index 7806a473..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatDailySpecPO.java +++ /dev/null @@ -1,74 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_order_stat_daily_spec") -public class OrderStatDailySpecPO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("product_id") - private Long productId; - - @TableField("product_sku_id") - private Long productSkuId; - - @TableField("stat_date") - private LocalDate statDate; - - @TableField("sales_amount") - private BigDecimal salesAmount; - - @TableField("refund_amount") - private BigDecimal refundAmount; - - @TableField("sales_order_count") - private Integer salesOrderCount; - - @TableField("sales_quantity_sum") - private Integer salesQuantitySum; - - @TableField("gmv_amount") - private BigDecimal gmvAmount; - - @TableField("gmv_order_count") - private Integer gmvOrderCount; - - @TableField("gmv_quantity_sum") - private Integer gmvQuantitySum; - - @TableField("product_cost") - private BigDecimal productCost; - - @TableField("freight_cost") - private BigDecimal freightCost; - - @TableField("other_cost") - private BigDecimal otherCost; - - @TableField("stat_version") - private Integer statVersion; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java deleted file mode 100644 index 00f1a6eb..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRebuildTaskPO.java +++ /dev/null @@ -1,49 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_order_stat_rebuild_task") -public class OrderStatRebuildTaskPO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("start_date") - private LocalDate startDate; - - @TableField("end_date") - private LocalDate endDate; - - @TableField("granularity") - private String granularity; - - @TableField("status") - private String status; - - @TableField("progress_date") - private LocalDate progressDate; - - @TableField("error_message") - private String errorMessage; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java deleted file mode 100644 index 4ed7dc38..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/OrderStatRefreshQueuePO.java +++ /dev/null @@ -1,43 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_order_stat_refresh_queue") -public class OrderStatRefreshQueuePO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("stat_date") - private LocalDate statDate; - - @TableField("source") - private String source; - - @TableField("status") - private String status; - - @TableField("retry_count") - private Integer retryCount; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java deleted file mode 100644 index 71bcad06..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/model/po/PromotionFeeStatDailyPO.java +++ /dev/null @@ -1,44 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.IdType; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; - -@Data -@TableName("ec_promotion_fee_stat_daily") -public class PromotionFeeStatDailyPO { - - @TableId(value = "id", type = IdType.AUTO) - private Long id; - - @TableField("company_id") - private Long companyId; - - @TableField("shop_id") - private Long shopId; - - @TableField("product_id") - private Long productId; - - @TableField("category_id") - private Long categoryId; - - @TableField("stat_date") - private LocalDate statDate; - - @TableField("fee_amount") - private BigDecimal feeAmount; - - @TableField(value = "create_time", fill = FieldFill.INSERT) - private LocalDateTime createTime; - - @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) - private LocalDateTime updateTime; -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java deleted file mode 100644 index 12e38126..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatCrudCoordinator.java +++ /dev/null @@ -1,102 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; - -import java.time.LocalDate; -import java.time.ZoneId; -import java.util.HashSet; -import java.util.Set; - -/** - * 推广费/刷单 CRUD 后刷新费汇总日表(事务提交后执行)。 - */ -@Service -public class FeeStatCrudCoordinator { - - private static final Logger log = LoggerFactory.getLogger(FeeStatCrudCoordinator.class); - private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); - - private final FeeStatRefreshService feeStatRefreshService; - private final OrderStatCacheService orderStatCacheService; - - public FeeStatCrudCoordinator(FeeStatRefreshService feeStatRefreshService, - OrderStatCacheService orderStatCacheService) { - this.feeStatRefreshService = feeStatRefreshService; - this.orderStatCacheService = orderStatCacheService; - } - - public void afterPromotionFeeSaved(PromotionFeePO before, PromotionFeePO after) { - Set keys = new HashSet<>(); - addPromotionKey(keys, before); - addPromotionKey(keys, after); - runAfterCommit(keys); - } - - public void afterPromotionFeeDeleted(PromotionFeePO before) { - Set keys = new HashSet<>(); - addPromotionKey(keys, before); - runAfterCommit(keys); - } - - public void afterBrushOrderSaved(BrushOrderPO before, BrushOrderPO after) { - Set keys = new HashSet<>(); - addBrushKey(keys, before); - addBrushKey(keys, after); - runAfterCommit(keys); - } - - public void afterBrushOrderDeleted(BrushOrderPO before) { - Set keys = new HashSet<>(); - addBrushKey(keys, before); - runAfterCommit(keys); - } - - private void runAfterCommit(Set keys) { - if (keys.isEmpty()) { - return; - } - Runnable task = () -> { - for (ShopDay k : keys) { - try { - feeStatRefreshService.refreshShopDay(k.companyId(), k.shopId(), k.statDate()); - orderStatCacheService.invalidateCompanyShopRange(k.companyId(), k.shopId(), k.statDate(), k.statDate()); - } catch (Exception e) { - log.warn("fee stat refresh failed: {}", k, e); - } - } - }; - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { - @Override - public void afterCommit() { - task.run(); - } - }); - } else { - task.run(); - } - } - - private static void addPromotionKey(Set keys, PromotionFeePO po) { - if (po == null || po.getCompanyId() == null || po.getShopId() == null || po.getFeeDate() == null) { - return; - } - keys.add(new ShopDay(po.getCompanyId(), po.getShopId(), po.getFeeDate())); - } - - private static void addBrushKey(Set keys, BrushOrderPO po) { - if (po == null || po.getCompanyId() == null || po.getShopId() == null || po.getBrushTime() == null) { - return; - } - LocalDate d = po.getBrushTime().atZone(STAT_ZONE).toLocalDate(); - keys.add(new ShopDay(po.getCompanyId(), po.getShopId(), d)); - } - - private record ShopDay(Long companyId, Long shopId, LocalDate statDate) {} -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java deleted file mode 100644 index dca79710..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/FeeStatRefreshService.java +++ /dev/null @@ -1,69 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.FeeStatDailyMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; - -/** 推广费/刷单费日表 refresh + 月年 rollup。 */ -@Service -public class FeeStatRefreshService { - - private final FeeStatDailyMapper feeStatDailyMapper; - - public FeeStatRefreshService(FeeStatDailyMapper feeStatDailyMapper) { - this.feeStatDailyMapper = feeStatDailyMapper; - } - - @Transactional(rollbackFor = Exception.class) - public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) { - refreshPromotionDay(companyId, shopId, statDate); - refreshBrushDay(companyId, shopId, statDate); - LocalDate statMonth = statDate.withDayOfMonth(1); - int statYear = statDate.getYear(); - feeStatDailyMapper.rollupPromotionMonthly(companyId, shopId, statMonth); - feeStatDailyMapper.rollupPromotionYearly(companyId, shopId, statYear); - feeStatDailyMapper.rollupBrushMonthly(companyId, shopId, statMonth); - feeStatDailyMapper.rollupBrushYearly(companyId, shopId, statYear); - } - - private void refreshPromotionDay(Long companyId, Long shopId, LocalDate statDate) { - feeStatDailyMapper.deletePromotionDaily(companyId, shopId, statDate); - List rows = - feeStatDailyMapper.aggregatePromotionByShopDay(companyId, shopId, statDate); - if (rows == null || rows.isEmpty()) { - return; - } - List list = new ArrayList<>(); - for (FeeStatDailyMapper.PromotionFeeAggRow r : rows) { - if (r.getFeeAmount() == null || r.getFeeAmount().signum() == 0) { - continue; - } - PromotionFeeStatDailyPO po = new PromotionFeeStatDailyPO(); - po.setCompanyId(companyId); - po.setShopId(shopId); - po.setProductId(r.getProductId() != null ? r.getProductId() : 0L); - po.setCategoryId(r.getCategoryId() != null ? r.getCategoryId() : 0L); - po.setStatDate(statDate); - po.setFeeAmount(r.getFeeAmount()); - list.add(po); - } - if (!list.isEmpty()) { - feeStatDailyMapper.batchInsertPromotionDaily(list); - } - } - - private void refreshBrushDay(Long companyId, Long shopId, LocalDate statDate) { - BigDecimal amt = feeStatDailyMapper.aggregateBrushByShopDay(companyId, shopId, statDate); - if (amt == null || amt.signum() == 0) { - feeStatDailyMapper.deleteBrushDaily(companyId, shopId, statDate); - return; - } - feeStatDailyMapper.upsertBrushDaily(companyId, shopId, statDate, amt); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java deleted file mode 100644 index 9442e7d4..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCacheService.java +++ /dev/null @@ -1,96 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.lang.NonNull; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; - -import java.time.LocalDate; -import java.util.Objects; -import java.util.concurrent.TimeUnit; - -/** - * 汇总读路径 Redis 缓存失效(按公司+店铺+日期区间)。 - */ -@Service -public class OrderStatCacheService { - - private static final Logger log = LoggerFactory.getLogger(OrderStatCacheService.class); - private static final String KEY_PREFIX = "order-stat:read:"; - - private final OrderStatProperties properties; - private final @NonNull RedisTemplate redisTemplate; - - public OrderStatCacheService(OrderStatProperties properties, - @NonNull RedisTemplate redisTemplate) { - this.properties = properties; - this.redisTemplate = redisTemplate; - } - - public boolean isEnabled() { - return properties.getCache().isEnabled(); - } - - /** 写入缓存(Query 层按需调用) */ - public void put(String cacheKey, Object value, long ttlSeconds) { - if (!isEnabled() || cacheKey == null || value == null) { - return; - } - try { - redisTemplate.opsForValue().set( - KEY_PREFIX + cacheKey, - Objects.requireNonNull(value), - ttlSeconds, - TimeUnit.SECONDS); - } catch (Exception e) { - log.debug("order-stat cache put skip: {}", cacheKey, e); - } - } - - public T get(String cacheKey, Class type) { - if (!isEnabled() || cacheKey == null) { - return null; - } - try { - Object v = redisTemplate.opsForValue().get(KEY_PREFIX + cacheKey); - if (v != null && type.isInstance(v)) { - return (T) v; - } - } catch (Exception e) { - log.debug("order-stat cache get skip: {}", cacheKey, e); - } - return null; - } - - /** 费用/订单变更后失效读缓存 */ - public void invalidateCompanyShopRange(Long companyId, Long shopId, LocalDate start, LocalDate end) { - if (!isEnabled() || companyId == null || shopId == null || start == null || end == null) { - return; - } - try { - for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { - String pattern = KEY_PREFIX + companyId + ":" + shopId + ":" + d + ":*"; - var keys = redisTemplate.keys(pattern); - if (keys != null && !keys.isEmpty()) { - redisTemplate.delete(keys); - } - } - } catch (Exception e) { - log.warn("order-stat cache invalidate failed company={} shop={}", companyId, shopId, e); - } - } - - public long resolveTtlSeconds(LocalDate endDate) { - LocalDate today = LocalDate.now(); - if (endDate != null && !endDate.isBefore(today)) { - return properties.getCache().getTtlTodaySeconds(); - } - return properties.getCache().getTtlHistorySeconds(); - } - - public static String buildKey(Long companyId, Long shopId, LocalDate start, LocalDate end, String suffix) { - return companyId + ":" + shopId + ":" + start + ":" + end + ":" + suffix; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java deleted file mode 100644 index ec4ecbae..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatCrudCoordinator.java +++ /dev/null @@ -1,128 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; - -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.time.ZoneId; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * 订单 CRUD 后触发汇总 refresh(事务提交后执行,避免读到未提交明细)。 - */ -@Service -public class OrderStatCrudCoordinator { - - private static final Logger log = LoggerFactory.getLogger(OrderStatCrudCoordinator.class); - private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai"); - - private final OrderStatRefreshService orderStatRefreshService; - private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; - - public OrderStatCrudCoordinator(OrderStatRefreshService orderStatRefreshService, - OrderStatRefreshCoordinator orderStatRefreshCoordinator) { - this.orderStatRefreshService = orderStatRefreshService; - this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; - } - - /** 单条创建/更新后:同步 refresh 涉及的自然日 */ - public void afterOrderSaved(OrderPO before, OrderPO after) { - Set keys = new HashSet<>(); - addKey(keys, before); - addKey(keys, after); - runAfterCommit(keys, true); - } - - /** 单条删除后 */ - public void afterOrderDeleted(OrderPO before) { - Set keys = new HashSet<>(); - addKey(keys, before); - runAfterCommit(keys, true); - } - - /** 批量删除:异步入队(避免一次 refresh 过多) */ - public void afterOrdersDeletedBatch(List removed) { - if (removed == null || removed.isEmpty()) { - return; - } - Set keys = new HashSet<>(); - for (OrderPO o : removed) { - addKey(keys, o); - } - runAfterCommit(keys, false); - } - - /** 规格补链等批量影响:异步入队 */ - public void enqueueDirtyKeys(Collection keys) { - if (keys == null || keys.isEmpty()) { - return; - } - runAfterCommit(new HashSet<>(keys), false); - } - - /** 成本同步等按时间范围影响:按 shop+日 enqueue */ - public void afterOrdersAffectedInRange(Long companyId, Long shopId, - LocalDateTime start, LocalDateTime end) { - if (companyId == null || shopId == null || start == null || end == null) { - return; - } - LocalDate d0 = start.atZone(STAT_ZONE).toLocalDate(); - LocalDate d1 = end.atZone(STAT_ZONE).toLocalDate(); - Set keys = new HashSet<>(); - for (LocalDate d = d0; !d.isAfter(d1); d = d.plusDays(1)) { - keys.add(new StatDirtyKey(companyId, shopId, d)); - } - runAfterCommit(keys, keys.size() <= 3); - } - - private void runAfterCommit(Set keys, boolean sync) { - if (keys.isEmpty()) { - return; - } - Runnable task = () -> executeRefresh(keys, sync); - if (TransactionSynchronizationManager.isSynchronizationActive()) { - TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { - @Override - public void afterCommit() { - task.run(); - } - }); - } else { - task.run(); - } - } - - private void executeRefresh(Set keys, boolean sync) { - if (sync) { - for (StatDirtyKey k : keys) { - try { - orderStatRefreshService.refreshShopDay(k.companyId(), k.shopId(), k.statDate()); - } catch (Exception e) { - log.warn("sync refresh failed, fallback enqueue: {}", k, e); - orderStatRefreshCoordinator.enqueueDirtyKeys(Set.of(k), RefreshSource.CRUD); - } - } - } else { - orderStatRefreshCoordinator.enqueueDirtyKeys(keys, RefreshSource.CRUD); - } - } - - private static void addKey(Set keys, OrderPO order) { - if (order == null || order.getCompanyId() == null || order.getShopId() == null - || order.getOrderTime() == null) { - return; - } - LocalDate d = order.getOrderTime().atZone(STAT_ZONE).toLocalDate(); - keys.add(new StatDirtyKey(order.getCompanyId(), order.getShopId(), d)); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java deleted file mode 100644 index ed4ba23d..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatOverviewAssembler.java +++ /dev/null @@ -1,195 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.springframework.context.annotation.Lazy; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; -import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -/** - * 基于汇总表的概览 VO 组装(公司/店铺/商品概览读路径切换共用)。 - */ -@Service -public class OrderStatOverviewAssembler { - - private final OrderStatReadFacade orderStatReadFacade; - private final CompanyOverviewService companyOverviewService; - - public OrderStatOverviewAssembler(OrderStatReadFacade orderStatReadFacade, - @Lazy CompanyOverviewService companyOverviewService) { - this.orderStatReadFacade = orderStatReadFacade; - this.companyOverviewService = companyOverviewService; - } - - /** 公司全店概览(汇总表读路径) */ - public CompanyOverviewVO buildCompanyOverview(Long companyId, List shops, - LocalDate startDate, LocalDate endDate, - BigDecimal taxRate, OrderStatusStatSets stat) { - List shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); - OrderStatMetricsDTO cur = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate); - LocalDate lastStart = startDate.minusMonths(1); - LocalDate lastEnd = endDate.minusMonths(1); - OrderStatMetricsDTO lastMonth = orderStatReadFacade.sumShopMetrics(companyId, shopIds, lastStart, lastEnd); - - BigDecimal totalSales = nz(cur.getSalesAmount()); - BigDecimal totalRefund = nz(cur.getRefundAmount()); - int totalOrderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; - BigDecimal lastMonthSales = nz(lastMonth.getSalesAmount()); - - List promoRows = orderStatReadFacade.loadPromotionRows( - companyId, shopIds, startDate, endDate); - List brushRows = orderStatReadFacade.loadBrushRows( - companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59)); - BigDecimal totalPromo = promoRows.stream().map(r -> nz(r.getFeeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalBrush = brushRows.stream().map(r -> nz(r.getBrushAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal orderCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); - BigDecimal profitBeforeTax = totalSales.subtract(orderCost).subtract(totalRefund).subtract(totalPromo).subtract(totalBrush); - BigDecimal tax = salesTaxOnNetSales(totalSales, totalRefund, taxRate); - BigDecimal profitAfterTax = profitBeforeTax.subtract(tax).setScale(2, RoundingMode.HALF_UP); - - CompanyOverviewVO vo = new CompanyOverviewVO(); - vo.setTotalSalesAmount(totalSales); - vo.setTotalOrderCount(totalOrderCount); - vo.setTotalPromotionFee(totalPromo); - vo.setTotalNetProfitAfterTax(profitAfterTax); - vo.setTotalTaxAmount(tax); - vo.setTotalProfitAfterTax(profitAfterTax); - vo.setMonthOverMonthGrowth(growthPct(totalSales, lastMonthSales)); - vo.setAverageFeeRatio(totalSales.signum() > 0 - ? totalPromo.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); - vo.setTotalROI(totalPromo.signum() > 0 - ? totalSales.subtract(totalRefund).divide(totalPromo, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); - - vo.setShopSalesRatios(buildShopSalesRatios(companyId, shopIds, shops, startDate, endDate, totalSales)); - vo.setSalesAmountTrend(buildSalesTrend(companyId, shopIds, startDate, endDate)); - vo.setOrderCountTrend(buildOrderTrend(companyId, shopIds, startDate, endDate)); - - List orderRows = orderStatReadFacade.loadShopProductRows( - companyId, shopIds, startDate, endDate, stat); - CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg( - taxRate, companyId, shops, orderRows, promoRows, brushRows, startDate, endDate); - vo.setShopSummary(bundle.getShopTable()); - vo.setCategorySummary(bundle.getCategoryTable()); - vo.setPlatformSummary(bundle.getPlatformTable()); - vo.setShopEfficiencyQuadrants(buildShopEfficiency(bundle.getShopTable())); - return vo; - } - - private List buildShopSalesRatios(Long companyId, List shopIds, - List shops, - LocalDate start, LocalDate end, - BigDecimal totalSales) { - List byShop = orderStatReadFacade.sumShopMetricsByShop(companyId, shopIds, start, end); - Map salesMap = new HashMap<>(); - for (OrderStatMetricsDTO m : byShop) { - if (m.getShopId() != null) { - salesMap.put(m.getShopId(), nz(m.getSalesAmount())); - } - } - List list = new ArrayList<>(); - for (ShopPO shop : shops) { - BigDecimal sales = salesMap.getOrDefault(shop.getId(), BigDecimal.ZERO); - CompanyOverviewVO.ShopSalesRatio r = new CompanyOverviewVO.ShopSalesRatio(); - r.setShopId(shop.getId()); - r.setShopName(shop.getName()); - r.setSalesAmount(sales); - r.setRatio(totalSales.signum() > 0 - ? sales.divide(totalSales, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) - : BigDecimal.ZERO); - list.add(r); - } - list.sort((a, b) -> nz(b.getSalesAmount()).compareTo(nz(a.getSalesAmount()))); - return list; - } - - private CompanyOverviewVO.TrendData buildSalesTrend(Long companyId, List shopIds, - LocalDate start, LocalDate end) { - List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end); - Map map = new HashMap<>(); - for (OrderStatMetricsDTO d : daily) { - if (d.getStatDate() != null) { - map.put(d.getStatDate(), nz(d.getSalesAmount())); - } - } - return fillTrend(start, end, map); - } - - private CompanyOverviewVO.TrendData buildOrderTrend(Long companyId, List shopIds, - LocalDate start, LocalDate end) { - List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end); - Map map = new HashMap<>(); - for (OrderStatMetricsDTO d : daily) { - if (d.getStatDate() != null) { - map.put(d.getStatDate(), BigDecimal.valueOf(d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0)); - } - } - return fillTrend(start, end, map); - } - - private static CompanyOverviewVO.TrendData fillTrend(LocalDate start, LocalDate end, Map map) { - List items = new ArrayList<>(); - BigDecimal total = BigDecimal.ZERO; - for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { - BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); - CompanyOverviewVO.TrendDataItem item = new CompanyOverviewVO.TrendDataItem(); - item.setDate(d); - item.setValue(v); - items.add(item); - total = total.add(v); - } - CompanyOverviewVO.TrendData trend = new CompanyOverviewVO.TrendData(); - trend.setDailyDataList(items); - trend.setTotal(total); - return trend; - } - - private static List buildShopEfficiency( - CompanyOverviewVO.ShopOverview shopOverview) { - if (shopOverview == null || shopOverview.getShops() == null) { - return List.of(); - } - List list = new ArrayList<>(); - for (CompanyOverviewVO.ShopSummary s : shopOverview.getShops()) { - CompanyOverviewVO.ShopEfficiencyQuadrant q = new CompanyOverviewVO.ShopEfficiencyQuadrant(); - q.setShopId(s.getShopId()); - q.setShopName(s.getShopName()); - q.setRoi(s.getRoi()); - q.setNetProfit(s.getProfitAfterTax()); - list.add(q); - } - return list; - } - - private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) { - if (prev.signum() > 0) { - return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)); - } - return cur.signum() > 0 ? BigDecimal.valueOf(100) : BigDecimal.ZERO; - } - - private static BigDecimal salesTaxOnNetSales(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { - BigDecimal base = sales.subtract(refund); - if (base.signum() < 0) { - base = BigDecimal.ZERO; - } - BigDecimal rate = taxRate != null ? taxRate : new BigDecimal("0.04"); - return base.multiply(rate).setScale(2, RoundingMode.HALF_UP); - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java deleted file mode 100644 index d31d67b4..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatQueryService.java +++ /dev/null @@ -1,192 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.temporal.ChronoUnit; -import java.util.Collections; -import java.util.List; - -/** - * 统一读服务:按区间粒度路由日/月/年汇总表;{@code stat-source=order} 时由上层继续走明细聚合(Phase G 切换)。 - */ -@Service -public class OrderStatQueryService { - - private static final Logger log = LoggerFactory.getLogger(OrderStatQueryService.class); - - /** ≤90 天走日表 */ - private static final int DAILY_THRESHOLD_DAYS = 90; - /** ≤1095 天(约 3 年)走月表 */ - private static final int MONTHLY_THRESHOLD_DAYS = 1095; - - private final OrderStatProperties properties; - private final OrderStatQueryMapper orderStatQueryMapper; - private final OrderStatRefreshCoordinator orderStatRefreshCoordinator; - private final OrderMapper orderMapper; - - public OrderStatQueryService(OrderStatProperties properties, - OrderStatQueryMapper orderStatQueryMapper, - OrderStatRefreshCoordinator orderStatRefreshCoordinator, - OrderMapper orderMapper) { - this.properties = properties; - this.orderStatQueryMapper = orderStatQueryMapper; - this.orderStatRefreshCoordinator = orderStatRefreshCoordinator; - this.orderMapper = orderMapper; - } - - public boolean usesDailyStatSource() { - return "daily".equalsIgnoreCase(properties.getStatSource()); - } - - /** 店铺 KPI 合计(始终读日表) */ - public OrderStatMetricsDTO sumShopMetrics(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - ensureStatReady(companyId, shopIds, startDate, endDate); - OrderStatMetricsDTO row = orderStatQueryMapper.sumDailyShop(companyId, shopIds, startDate, endDate); - return row != null ? row : emptyMetrics(); - } - - public List sumShopMetricsByDay(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - ensureStatReady(companyId, shopIds, startDate, endDate); - List rows = orderStatQueryMapper.sumDailyShopByDay(companyId, shopIds, startDate, endDate); - return rows != null ? rows : Collections.emptyList(); - } - - public List sumShopMetricsByShop(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - ensureStatReady(companyId, shopIds, startDate, endDate); - List rows = orderStatQueryMapper.sumDailyShopByShop(companyId, shopIds, startDate, endDate); - return rows != null ? rows : Collections.emptyList(); - } - - public List sumProductMetricsByCategory(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - ensureStatReady(companyId, shopIds, startDate, endDate); - ProductGranularity g = resolveProductGranularity(startDate, endDate); - return switch (g) { - case DAILY -> nullSafe(orderStatQueryMapper.sumDailyProductByCategory( - companyId, shopIds, startDate, endDate)); - case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlyProductByCategory( - companyId, shopIds, monthStart(startDate), monthStart(endDate))); - case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlyProductByCategory( - companyId, shopIds, startDate.getYear(), endDate.getYear())); - }; - } - - public List sumProductMetricsByProduct(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - ensureStatReady(companyId, shopIds, startDate, endDate); - ProductGranularity g = resolveProductGranularity(startDate, endDate); - return switch (g) { - case DAILY -> nullSafe(orderStatQueryMapper.sumDailyProductByProduct( - companyId, shopIds, startDate, endDate)); - case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlyProductByProduct( - companyId, shopIds, monthStart(startDate), monthStart(endDate))); - case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlyProductByProduct( - companyId, shopIds, startDate.getYear(), endDate.getYear())); - }; - } - - public List sumSpecMetricsBySpec(Long companyId, List shopIds, Long productId, - LocalDate startDate, LocalDate endDate) { - requireDailySource(); - if (productId == null) { - return Collections.emptyList(); - } - ensureStatReady(companyId, shopIds, startDate, endDate); - ProductGranularity g = resolveProductGranularity(startDate, endDate); - return switch (g) { - case DAILY -> nullSafe(orderStatQueryMapper.sumDailySpecBySpec( - companyId, shopIds, productId, startDate, endDate)); - case MONTHLY -> nullSafe(orderStatQueryMapper.sumMonthlySpecBySpec( - companyId, shopIds, productId, monthStart(startDate), monthStart(endDate))); - case YEARLY -> nullSafe(orderStatQueryMapper.sumYearlySpecBySpec( - companyId, shopIds, productId, startDate.getYear(), endDate.getYear())); - }; - } - - /** - * 汇总行缺失且区间内有订单时,异步 enqueue refresh(不阻塞读路径)。 - *

- * 若区间内无 ec_order 明细(如同比去年、未来日期),空汇总结果是正确口径,不应打日志或入队。 - */ - public void ensureStatReady(Long companyId, List shopIds, LocalDate startDate, LocalDate endDate) { - if (!properties.isAutoRefreshOnMiss() || shopIds == null || shopIds.isEmpty()) { - return; - } - if (orderStatQueryMapper.countDailyShopRows(companyId, shopIds, startDate, endDate) > 0) { - return; - } - int enqueuedShops = 0; - for (Long shopId : shopIds) { - List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( - companyId, shopId, startDate, endDate); - if (dates == null || dates.isEmpty()) { - continue; - } - orderStatRefreshCoordinator.enqueueRefresh(companyId, shopId, dates, RefreshSource.AUTO_MISS); - enqueuedShops++; - } - if (enqueuedShops > 0) { - log.info("汇总表缺失且区间内有订单,已异步 enqueue refresh company={} shops={} {}~{}", - companyId, shopIds, startDate, endDate); - } - } - - private void requireDailySource() { - if (!usesDailyStatSource()) { - throw new IllegalStateException("order-stat.stat-source=order 时读路径尚未切换,请由上层走 OrderStatAggMapper"); - } - } - - private static ProductGranularity resolveProductGranularity(LocalDate startDate, LocalDate endDate) { - long days = ChronoUnit.DAYS.between(startDate, endDate) + 1; - if (days <= DAILY_THRESHOLD_DAYS) { - return ProductGranularity.DAILY; - } - if (days <= MONTHLY_THRESHOLD_DAYS) { - return ProductGranularity.MONTHLY; - } - return ProductGranularity.YEARLY; - } - - private static LocalDate monthStart(LocalDate date) { - return date.withDayOfMonth(1); - } - - private static List nullSafe(List rows) { - return rows != null ? rows : Collections.emptyList(); - } - - private static OrderStatMetricsDTO emptyMetrics() { - OrderStatMetricsDTO dto = new OrderStatMetricsDTO(); - dto.setSalesAmount(BigDecimal.ZERO); - dto.setRefundAmount(BigDecimal.ZERO); - dto.setSalesOrderCount(0); - dto.setProductCost(BigDecimal.ZERO); - dto.setFreightCost(BigDecimal.ZERO); - dto.setOtherCost(BigDecimal.ZERO); - dto.setGmvAmount(BigDecimal.ZERO); - dto.setGmvOrderCount(0); - return dto; - } - - private enum ProductGranularity { - DAILY, MONTHLY, YEARLY - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java deleted file mode 100644 index 95ca3cfe..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReadFacade.java +++ /dev/null @@ -1,341 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** - * 读路径统一门面:{@code stat-source=daily} 走汇总表,否则回退 {@link OrderStatAggMapper} 扫明细。 - */ -@Service -public class OrderStatReadFacade { - - private final OrderStatProperties properties; - private final OrderStatQueryService orderStatQueryService; - private final OrderStatQueryMapper orderStatQueryMapper; - private final OrderStatAggMapper orderStatAggMapper; - private final OrderStatusStatResolver orderStatusStatResolver; - private final ShopService shopService; - - public OrderStatReadFacade(OrderStatProperties properties, - OrderStatQueryService orderStatQueryService, - OrderStatQueryMapper orderStatQueryMapper, - OrderStatAggMapper orderStatAggMapper, - OrderStatusStatResolver orderStatusStatResolver, - ShopService shopService) { - this.properties = properties; - this.orderStatQueryService = orderStatQueryService; - this.orderStatQueryMapper = orderStatQueryMapper; - this.orderStatAggMapper = orderStatAggMapper; - this.orderStatusStatResolver = orderStatusStatResolver; - this.shopService = shopService; - } - - public boolean usesDailyStatSource() { - return "daily".equalsIgnoreCase(properties.getStatSource()); - } - - /** 工作台/概览共用:shop×product 聚合行 */ - public List loadShopProductRows(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate, - OrderStatusStatSets stat) { - if (!usesDailyStatSource()) { - return orderStatAggMapper.aggregateByShopProduct( - companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59), - OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); - } - orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); - Map platformByShop = platformByShop(shopIds); - List rows = orderStatQueryMapper.sumDailyProductByShopProduct( - companyId, shopIds, startDate, endDate); - if (rows == null || rows.isEmpty()) { - return Collections.emptyList(); - } - List out = new ArrayList<>(rows.size()); - for (OrderStatMetricsDTO m : rows) { - OrderStatAggMapper.ShopProductRow r = new OrderStatAggMapper.ShopProductRow(); - r.setShopId(m.getShopId()); - r.setPlatformCode(platformByShop.get(m.getShopId())); - r.setProductId(m.getProductId()); - r.setCategoryId(m.getCategoryId()); - r.setSalesAmount(m.getSalesAmount()); - r.setRefundAmount(m.getRefundAmount()); - r.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); - r.setSalesQuantitySum(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum().longValue() : 0L); - r.setProductCost(m.getProductCost()); - r.setFreightCost(m.getFreightCost()); - r.setOtherCost(m.getOtherCost()); - r.setGmvAllStatus(nz(m.getGmvAmount())); - r.setGmvOrderCount(m.getGmvOrderCount() != null ? m.getGmvOrderCount().longValue() : 0L); - r.setGmvQuantitySum(m.getGmvQuantitySum() != null ? m.getGmvQuantitySum().longValue() : 0L); - out.add(r); - } - return out; - } - - public List loadDailyRows(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate, - OrderStatusStatSets stat) { - if (!usesDailyStatSource()) { - return orderStatAggMapper.aggregateDaily( - companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59), - OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); - } - orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); - List rows = orderStatQueryService.sumShopMetricsByDay( - companyId, shopIds, startDate, endDate); - List out = new ArrayList<>(); - for (OrderStatMetricsDTO m : rows) { - OrderStatAggMapper.DailyRow r = new OrderStatAggMapper.DailyRow(); - r.setStatDate(m.getStatDate()); - r.setSalesAmount(m.getSalesAmount()); - r.setRefundAmount(m.getRefundAmount()); - r.setProductCost(m.getProductCost()); - r.setFreightCost(m.getFreightCost()); - r.setOtherCost(m.getOtherCost()); - out.add(r); - } - return out; - } - - /** 三段时间 KPI(当前/环比/同比) */ - public OrderStatAggMapper.PeriodKpiRow loadPeriodKpi(Long companyId, List shopIds, - LocalDate curStart, LocalDate curEnd, - LocalDate prevStart, LocalDate prevEnd, - LocalDate yoyStart, LocalDate yoyEnd, - OrderStatusStatSets stat) { - if (!usesDailyStatSource()) { - LocalDateTime scanStart = minTime(prevStart, yoyStart, curStart); - LocalDateTime scanEnd = maxTime(prevEnd, yoyEnd, curEnd); - OrderStatAggMapper.PeriodKpiRow row = orderStatAggMapper.aggregatePeriodKpi( - companyId, shopIds, scanStart, scanEnd, - curStart.atStartOfDay(), curEnd.atTime(23, 59, 59), - prevStart.atStartOfDay(), prevEnd.atTime(23, 59, 59), - yoyStart.atStartOfDay(), yoyEnd.atTime(23, 59, 59), - OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); - return row != null ? row : new OrderStatAggMapper.PeriodKpiRow(); - } - OrderStatMetricsDTO cur = orderStatQueryService.sumShopMetrics(companyId, shopIds, curStart, curEnd); - OrderStatMetricsDTO prev = orderStatQueryService.sumShopMetrics(companyId, shopIds, prevStart, prevEnd); - OrderStatMetricsDTO yoy = orderStatQueryService.sumShopMetrics(companyId, shopIds, yoyStart, yoyEnd); - OrderStatAggMapper.PeriodKpiRow row = new OrderStatAggMapper.PeriodKpiRow(); - fillPeriodSlice(row, cur, Period.CUR); - fillPeriodSlice(row, prev, Period.PREV); - fillPeriodSlice(row, yoy, Period.YOY); - return row; - } - - public OrderStatMetricsDTO sumShopMetrics(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List rows = orderStatAggMapper.aggregateByShopProduct( - companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59), - OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); - OrderStatMetricsDTO dto = new OrderStatMetricsDTO(); - BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO, gmv = BigDecimal.ZERO; - BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO; - int cnt = 0, salesQty = 0, gmvCnt = 0, gmvQty = 0; - for (OrderStatAggMapper.ShopProductRow r : rows) { - sales = sales.add(nz(r.getSalesAmount())); - refund = refund.add(nz(r.getRefundAmount())); - gmv = gmv.add(nz(r.getGmvAllStatus())); - pc = pc.add(nz(r.getProductCost())); - fc = fc.add(nz(r.getFreightCost())); - oc = oc.add(nz(r.getOtherCost())); - cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; - salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0; - gmvCnt += r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0; - gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0; - } - dto.setSalesAmount(sales); - dto.setRefundAmount(refund); - dto.setSalesOrderCount(cnt); - dto.setSalesQuantitySum(salesQty); - dto.setGmvAmount(gmv); - dto.setGmvOrderCount(gmvCnt); - dto.setGmvQuantitySum(gmvQty); - dto.setProductCost(pc); - dto.setFreightCost(fc); - dto.setOtherCost(oc); - return dto; - } - return orderStatQueryService.sumShopMetrics(companyId, shopIds, startDate, endDate); - } - - public List sumShopMetricsByDay(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - return Collections.emptyList(); - } - return orderStatQueryService.sumShopMetricsByDay(companyId, shopIds, startDate, endDate); - } - - public List sumShopMetricsByShop(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - return Collections.emptyList(); - } - orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); - List rows = orderStatQueryMapper.sumDailyShopByShop( - companyId, shopIds, startDate, endDate); - return rows != null ? rows : Collections.emptyList(); - } - - public OrderStatMetricsDTO sumProductForOne(Long companyId, List shopIds, Long productId, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - return new OrderStatMetricsDTO(); - } - orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); - OrderStatMetricsDTO row = orderStatQueryMapper.sumDailyProductForOneProduct( - companyId, shopIds, productId, startDate, endDate); - return row != null ? row : new OrderStatMetricsDTO(); - } - - public List sumProductByDayForOne(Long companyId, List shopIds, Long productId, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - return Collections.emptyList(); - } - orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate); - List rows = orderStatQueryMapper.sumDailyProductByDayForOneProduct( - companyId, shopIds, productId, startDate, endDate); - return rows != null ? rows : Collections.emptyList(); - } - - public List sumSpecMetrics(Long companyId, List shopIds, Long productId, - LocalDate startDate, LocalDate endDate) { - if (!usesDailyStatSource()) { - return Collections.emptyList(); - } - return orderStatQueryService.sumSpecMetricsBySpec(companyId, shopIds, productId, startDate, endDate); - } - - /** 推广/刷单仍走明细表 SQL(数据量小) */ - public List loadPromotionRows(Long companyId, List shopIds, - LocalDate startDate, LocalDate endDate) { - List rows = orderStatAggMapper.aggregatePromotionFees( - companyId, shopIds, startDate, endDate); - return rows != null ? rows : Collections.emptyList(); - } - - public List loadBrushRows(Long companyId, List shopIds, - LocalDateTime start, LocalDateTime end) { - List rows = orderStatAggMapper.aggregateBrushFees( - companyId, shopIds, start, end); - return rows != null ? rows : Collections.emptyList(); - } - - public OrderStatAggMapper.FeeKpiRow loadPromotionPeriodKpi(Long companyId, List shopIds, - LocalDate scanStart, LocalDate scanEnd, - LocalDate curStart, LocalDate curEnd, - LocalDate prevStart, LocalDate prevEnd, - LocalDate yoyStart, LocalDate yoyEnd) { - OrderStatAggMapper.FeeKpiRow row = orderStatAggMapper.aggregatePromotionPeriodKpi( - companyId, shopIds, scanStart, scanEnd, curStart, curEnd, prevStart, prevEnd, yoyStart, yoyEnd); - return row != null ? row : new OrderStatAggMapper.FeeKpiRow(); - } - - public OrderStatAggMapper.FeeKpiRow loadBrushPeriodKpi(Long companyId, List shopIds, - LocalDateTime scanStart, LocalDateTime scanEnd, - LocalDateTime curStart, LocalDateTime curEnd, - LocalDateTime prevStart, LocalDateTime prevEnd, - LocalDateTime yoyStart, LocalDateTime yoyEnd) { - OrderStatAggMapper.FeeKpiRow row = orderStatAggMapper.aggregateBrushPeriodKpi( - companyId, shopIds, scanStart, scanEnd, curStart, curEnd, prevStart, prevEnd, yoyStart, yoyEnd); - return row != null ? row : new OrderStatAggMapper.FeeKpiRow(); - } - - private Map platformByShop(List shopIds) { - if (shopIds == null || shopIds.isEmpty()) { - return Map.of(); - } - return shopService.listByIds(shopIds).stream() - .collect(Collectors.toMap(ShopPO::getId, s -> s.getPlatformCode(), (a, b) -> a)); - } - - private enum Period { CUR, PREV, YOY } - - private static void fillPeriodSlice(OrderStatAggMapper.PeriodKpiRow row, OrderStatMetricsDTO m, Period p) { - switch (p) { - case CUR -> { - row.setCurSalesAmount(nz(m.getSalesAmount())); - row.setCurOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); - row.setCurRefundAmount(nz(m.getRefundAmount())); - row.setCurProductCost(nz(m.getProductCost())); - row.setCurFreightCost(nz(m.getFreightCost())); - row.setCurOtherCost(nz(m.getOtherCost())); - row.setCurGmvAllStatus(nz(m.getGmvAmount())); - } - case PREV -> { - row.setPrevSalesAmount(nz(m.getSalesAmount())); - row.setPrevOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); - row.setPrevRefundAmount(nz(m.getRefundAmount())); - row.setPrevProductCost(nz(m.getProductCost())); - row.setPrevFreightCost(nz(m.getFreightCost())); - row.setPrevOtherCost(nz(m.getOtherCost())); - row.setPrevGmvAllStatus(nz(m.getGmvAmount())); - } - case YOY -> { - row.setYoySalesAmount(nz(m.getSalesAmount())); - row.setYoyOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); - row.setYoyRefundAmount(nz(m.getRefundAmount())); - row.setYoyProductCost(nz(m.getProductCost())); - row.setYoyFreightCost(nz(m.getFreightCost())); - row.setYoyOtherCost(nz(m.getOtherCost())); - row.setYoyGmvAllStatus(nz(m.getGmvAmount())); - } - } - } - - private static LocalDateTime minTime(LocalDate... dates) { - LocalDateTime min = dates[0].atStartOfDay(); - for (int i = 1; i < dates.length; i++) { - LocalDateTime t = dates[i].atStartOfDay(); - if (t.isBefore(min)) { - min = t; - } - } - return min; - } - - private static LocalDateTime maxTime(LocalDate... dates) { - LocalDateTime max = dates[0].atTime(23, 59, 59); - for (int i = 1; i < dates.length; i++) { - LocalDateTime t = dates[i].atTime(23, 59, 59); - if (t.isAfter(max)) { - max = t; - } - } - return max; - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java deleted file mode 100644 index 1424a984..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRebuildService.java +++ /dev/null @@ -1,114 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRebuildTaskMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; - -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -/** - * 历史订单 backfill:按 shop × date 调用 {@link OrderStatRefreshService#refreshShopDay}。 - */ -@Service -public class OrderStatRebuildService extends ServiceImpl { - - private static final Logger log = LoggerFactory.getLogger(OrderStatRebuildService.class); - - private final ShopService shopService; - private final OrderMapper orderMapper; - private final OrderStatRefreshService orderStatRefreshService; - private final FeeStatRefreshService feeStatRefreshService; - private final ExecutorService executor = Executors.newSingleThreadExecutor(r -> { - Thread t = new Thread(r, "order-stat-rebuild"); - t.setDaemon(true); - return t; - }); - - public OrderStatRebuildService(ShopService shopService, - OrderMapper orderMapper, - OrderStatRefreshService orderStatRefreshService, - FeeStatRefreshService feeStatRefreshService) { - this.shopService = shopService; - this.orderMapper = orderMapper; - this.orderStatRefreshService = orderStatRefreshService; - this.feeStatRefreshService = feeStatRefreshService; - } - - /** 创建 rebuild 任务并异步执行 */ - public Long scheduleRebuild(Long companyId, Long shopId, LocalDate startDate, LocalDate endDate) { - OrderStatRebuildTaskPO task = new OrderStatRebuildTaskPO(); - task.setCompanyId(companyId); - task.setShopId(shopId); - task.setStartDate(startDate); - task.setEndDate(endDate); - task.setGranularity("all"); - task.setStatus("pending"); - save(task); - Long taskId = task.getId(); - executor.submit(() -> runRebuild(taskId)); - return taskId; - } - - public OrderStatRebuildTaskPO getTask(Long taskId) { - return getById(taskId); - } - - private void runRebuild(Long taskId) { - OrderStatRebuildTaskPO task = getById(taskId); - if (task == null) { - return; - } - task.setStatus("running"); - updateById(task); - try { - List shopIds = resolveShopIds(task.getCompanyId(), task.getShopId()); - LocalDate cursor = task.getProgressDate() != null ? task.getProgressDate() : task.getStartDate(); - if (cursor.isBefore(task.getStartDate())) { - cursor = task.getStartDate(); - } - for (Long shopId : shopIds) { - List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( - task.getCompanyId(), shopId, task.getStartDate(), task.getEndDate()); - if (dates == null) { - dates = new ArrayList<>(); - } - for (LocalDate d : dates) { - if (d.isBefore(cursor)) { - continue; - } - orderStatRefreshService.refreshShopDay(task.getCompanyId(), shopId, d); - feeStatRefreshService.refreshShopDay(task.getCompanyId(), shopId, d); - task.setProgressDate(d); - updateById(task); - } - } - task.setStatus("done"); - task.setProgressDate(task.getEndDate()); - updateById(task); - } catch (Exception e) { - log.error("rebuild task {} failed", taskId, e); - task.setStatus("failed"); - task.setErrorMessage(e.getMessage()); - updateById(task); - } - } - - private List resolveShopIds(Long companyId, Long shopId) { - if (shopId != null) { - return List.of(shopId); - } - return shopService.list(new LambdaQueryWrapper().eq(ShopPO::getCompanyId, companyId)) - .stream().map(ShopPO::getId).toList(); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java deleted file mode 100644 index ca3ac0b0..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatReconcileService.java +++ /dev/null @@ -1,175 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; - -import java.math.BigDecimal; -import java.math.RoundingMode; -import java.time.LocalDate; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Random; - -/** - * 汇总表 vs 明细聚合对账(抽样 shop×date)。 - */ -@Service -public class OrderStatReconcileService { - - private static final Logger log = LoggerFactory.getLogger(OrderStatReconcileService.class); - private static final BigDecimal TOLERANCE = new BigDecimal("0.01"); - - private final OrderStatReadFacade orderStatReadFacade; - private final OrderStatAggMapper orderStatAggMapper; - private final OrderStatusStatResolver orderStatusStatResolver; - private final OrderMapper orderMapper; - private final ShopService shopService; - - public OrderStatReconcileService(OrderStatReadFacade orderStatReadFacade, - OrderStatAggMapper orderStatAggMapper, - OrderStatusStatResolver orderStatusStatResolver, - OrderMapper orderMapper, - ShopService shopService) { - this.orderStatReadFacade = orderStatReadFacade; - this.orderStatAggMapper = orderStatAggMapper; - this.orderStatusStatResolver = orderStatusStatResolver; - this.orderMapper = orderMapper; - this.shopService = shopService; - } - - public ReconcileReport reconcileCompany(Long companyId, LocalDate startDate, LocalDate endDate, int sampleSize) { - ReconcileReport report = new ReconcileReport(); - report.setCompanyId(companyId); - report.setStartDate(startDate); - report.setEndDate(endDate); - if (!orderStatReadFacade.usesDailyStatSource()) { - report.setMessage("stat-source=order,跳过对账"); - return report; - } - List shops = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list(); - if (shops.isEmpty()) { - report.setMessage("无店铺"); - return report; - } - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - List samples = pickSamples(companyId, shops, startDate, endDate, sampleSize); - for (SampleKey s : samples) { - ReconcileItem item = reconcileOne(companyId, s.shopId(), s.statDate(), stat); - report.getItems().add(item); - if (!item.isMatch()) { - report.setMismatchCount(report.getMismatchCount() + 1); - } - } - report.setSampleCount(samples.size()); - report.setPassed(report.getMismatchCount() == 0); - log.info("reconcile company={} samples={} mismatch={}", companyId, samples.size(), report.getMismatchCount()); - return report; - } - - private ReconcileItem reconcileOne(Long companyId, Long shopId, LocalDate d, OrderStatusStatSets stat) { - OrderStatMetricsDTO daily = orderStatReadFacade.sumShopMetrics(companyId, List.of(shopId), d, d); - List rows = orderStatAggMapper.aggregateByShopProduct( - companyId, List.of(shopId), d.atStartOfDay(), d.atTime(23, 59, 59), - OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat)); - BigDecimal aggSales = BigDecimal.ZERO; - for (OrderStatAggMapper.ShopProductRow r : rows) { - aggSales = aggSales.add(nz(r.getSalesAmount())); - } - ReconcileItem item = new ReconcileItem(); - item.setShopId(shopId); - item.setStatDate(d); - item.setStatSales(nz(daily.getSalesAmount())); - item.setAggSales(aggSales); - item.setDiff(item.getStatSales().subtract(item.getAggSales()).abs()); - item.setMatch(item.getDiff().compareTo(TOLERANCE) <= 0); - return item; - } - - private List pickSamples(Long companyId, List shops, - LocalDate start, LocalDate end, int sampleSize) { - List pool = new ArrayList<>(); - for (ShopPO shop : shops) { - List dates = orderMapper.selectDistinctOrderDatesByCompanyShopRange( - companyId, shop.getId(), start, end); - if (dates == null) { - continue; - } - for (LocalDate d : dates) { - pool.add(new SampleKey(shop.getId(), d)); - } - } - if (pool.isEmpty()) { - return Collections.emptyList(); - } - Collections.shuffle(pool, new Random(42)); - return pool.subList(0, Math.min(sampleSize, pool.size())); - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } - - private record SampleKey(Long shopId, LocalDate statDate) {} - - public static class ReconcileReport { - private Long companyId; - private LocalDate startDate; - private LocalDate endDate; - private int sampleCount; - private int mismatchCount; - private boolean passed; - private String message; - private List items = new ArrayList<>(); - - public Long getCompanyId() { return companyId; } - public void setCompanyId(Long companyId) { this.companyId = companyId; } - public LocalDate getStartDate() { return startDate; } - public void setStartDate(LocalDate startDate) { this.startDate = startDate; } - public LocalDate getEndDate() { return endDate; } - public void setEndDate(LocalDate endDate) { this.endDate = endDate; } - public int getSampleCount() { return sampleCount; } - public void setSampleCount(int sampleCount) { this.sampleCount = sampleCount; } - public int getMismatchCount() { return mismatchCount; } - public void setMismatchCount(int mismatchCount) { this.mismatchCount = mismatchCount; } - public boolean isPassed() { return passed; } - public void setPassed(boolean passed) { this.passed = passed; } - public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } - public List getItems() { return items; } - public void setItems(List items) { this.items = items; } - } - - public static class ReconcileItem { - private Long shopId; - private LocalDate statDate; - private BigDecimal statSales; - private BigDecimal aggSales; - private BigDecimal diff; - private boolean match; - - public Long getShopId() { return shopId; } - public void setShopId(Long shopId) { this.shopId = shopId; } - public LocalDate getStatDate() { return statDate; } - public void setStatDate(LocalDate statDate) { this.statDate = statDate; } - public BigDecimal getStatSales() { return statSales; } - public void setStatSales(BigDecimal statSales) { this.statSales = statSales; } - public BigDecimal getAggSales() { return aggSales; } - public void setAggSales(BigDecimal aggSales) { this.aggSales = aggSales; } - public BigDecimal getDiff() { return diff; } - public void setDiff(BigDecimal diff) { this.diff = diff.setScale(2, RoundingMode.HALF_UP); } - public boolean isMatch() { return match; } - public void setMatch(boolean match) { this.match = match; } - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java deleted file mode 100644 index 4dc15806..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshCoordinator.java +++ /dev/null @@ -1,97 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -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.order.stat.mapper.OrderStatRefreshMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; - -import java.time.LocalDate; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * 汇总 refresh 入队与任务锁定(DB 队列,与导入消费者解耦)。 - */ -@Service -public class OrderStatRefreshCoordinator extends ServiceImpl { - - private static final Logger log = LoggerFactory.getLogger(OrderStatRefreshCoordinator.class); - private static final int MAX_RETRY = 3; - - private final OrderStatRefreshMapper orderStatRefreshMapper; - private final OrderStatRefreshService orderStatRefreshService; - - public OrderStatRefreshCoordinator(OrderStatRefreshMapper orderStatRefreshMapper, - OrderStatRefreshService orderStatRefreshService) { - this.orderStatRefreshMapper = orderStatRefreshMapper; - this.orderStatRefreshService = orderStatRefreshService; - } - - /** 批量入队(去重:同维度 pending 仅一条) */ - public int enqueueRefresh(Long companyId, Long shopId, Collection statDates, RefreshSource source) { - if (companyId == null || shopId == null || statDates == null || statDates.isEmpty()) { - return 0; - } - Set unique = new HashSet<>(statDates); - int n = 0; - for (LocalDate d : unique) { - n += orderStatRefreshMapper.insertPendingIgnore(companyId, shopId, d, source.name()); - } - log.info("order-stat enqueue company={} shop={} dates={} inserted={}", companyId, shopId, unique.size(), n); - return n; - } - - public int enqueueDirtyKeys(Collection keys, RefreshSource source) { - if (keys == null || keys.isEmpty()) { - return 0; - } - int n = 0; - for (StatDirtyKey k : keys) { - n += orderStatRefreshMapper.insertPendingIgnore(k.companyId(), k.shopId(), k.statDate(), source.name()); - } - return n; - } - - /** 取一条 pending 并置为 running */ - @Transactional(rollbackFor = Exception.class) - public OrderStatRefreshQueuePO fetchAndLockPending() { - LambdaQueryWrapper q = new LambdaQueryWrapper<>(); - q.eq(OrderStatRefreshQueuePO::getStatus, "pending") - .orderByAsc(OrderStatRefreshQueuePO::getId) - .last("LIMIT 1 FOR UPDATE SKIP LOCKED"); - OrderStatRefreshQueuePO row = getOne(q); - if (row == null) { - return null; - } - row.setStatus("running"); - updateById(row); - return row; - } - - /** 执行单条队列任务 */ - public void processQueueItem(OrderStatRefreshQueuePO item) { - try { - orderStatRefreshService.refreshShopDay(item.getCompanyId(), item.getShopId(), item.getStatDate()); - orderStatRefreshMapper.markDone(item.getId()); - } catch (Exception e) { - int retry = (item.getRetryCount() != null ? item.getRetryCount() : 0) + 1; - log.error("order-stat refresh failed id={} company={} shop={} date={} retry={}", - item.getId(), item.getCompanyId(), item.getShopId(), item.getStatDate(), retry, e); - if (retry < MAX_RETRY) { - // 重新入队 pending - item.setStatus("pending"); - item.setRetryCount(retry); - updateById(item); - } else { - orderStatRefreshMapper.markFailed(item.getId(), retry); - } - } - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java deleted file mode 100644 index de95c862..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshService.java +++ /dev/null @@ -1,252 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; - -import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.List; - -/** - * 单日单店重算:ec_order → 日汇总表,再触发月/年 rollup。 - */ -@Service -public class OrderStatRefreshService { - - private final OrderStatusStatResolver orderStatusStatResolver; - private final OrderStatAggMapper orderStatAggMapper; - private final OrderStatRefreshMapper orderStatRefreshMapper; - private final OrderStatDailyMapper orderStatDailyMapper; - private final OrderStatRollupService orderStatRollupService; - private final ShopMapper shopMapper; - - public OrderStatRefreshService(OrderStatusStatResolver orderStatusStatResolver, - OrderStatAggMapper orderStatAggMapper, - OrderStatRefreshMapper orderStatRefreshMapper, - OrderStatDailyMapper orderStatDailyMapper, - OrderStatRollupService orderStatRollupService, - ShopMapper shopMapper) { - this.orderStatusStatResolver = orderStatusStatResolver; - this.orderStatAggMapper = orderStatAggMapper; - this.orderStatRefreshMapper = orderStatRefreshMapper; - this.orderStatDailyMapper = orderStatDailyMapper; - this.orderStatRollupService = orderStatRollupService; - this.shopMapper = shopMapper; - } - - /** - * 重算指定自然日的店铺/商品/规格日表,并 rollup 对应月、年。 - */ - @Transactional(rollbackFor = Exception.class) - public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) { - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); - if (stat.isUnionEmpty()) { - writeEmptyShopDay(companyId, shopId, statDate); - orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate); - orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate); - orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate); - return; - } - - LocalDateTime start = statDate.atStartOfDay(); - LocalDateTime end = statDate.atTime(23, 59, 59); - List shopIds = List.of(shopId); - - List productRows = orderStatAggMapper.aggregateByShopProduct( - companyId, shopIds, start, end, - OrderStatParamHelper.unionList(stat), - OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), - OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), - OrderStatParamHelper.otherCostList(stat)); - - String platformCode = resolvePlatformCode(shopId); - Integer gmvOrderCount = orderStatRefreshMapper.countGmvOrdersByShopDay( - companyId, shopId, start, end); - OrderStatDailyShopPO shopRow = buildShopRow(companyId, shopId, platformCode, statDate, productRows, - gmvOrderCount != null ? gmvOrderCount : 0); - orderStatDailyMapper.upsertDailyShop(shopRow); - - orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate); - List dailyProducts = buildProductRows(companyId, shopId, statDate, productRows); - if (!dailyProducts.isEmpty()) { - orderStatDailyMapper.batchInsertDailyProduct(dailyProducts); - } - - orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate); - List skuRows = orderStatRefreshMapper.aggregateSpecByShopDay( - companyId, shopId, start, end, - OrderStatParamHelper.unionList(stat), - OrderStatParamHelper.salesList(stat), - OrderStatParamHelper.refundList(stat), - OrderStatParamHelper.productCostList(stat), - OrderStatParamHelper.freightCostList(stat), - OrderStatParamHelper.otherCostList(stat)); - List dailySpecs = buildSpecRows(companyId, shopId, statDate, skuRows); - if (!dailySpecs.isEmpty()) { - orderStatDailyMapper.batchInsertDailySpec(dailySpecs); - } - - orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate); - } - - private String resolvePlatformCode(Long shopId) { - ShopPO shop = shopMapper.selectById(shopId); - return shop != null ? shop.getPlatformCode() : null; - } - - private void writeEmptyShopDay(Long companyId, Long shopId, LocalDate statDate) { - OrderStatDailyShopPO row = new OrderStatDailyShopPO(); - row.setCompanyId(companyId); - row.setShopId(shopId); - row.setPlatformCode(resolvePlatformCode(shopId)); - row.setStatDate(statDate); - row.setSalesAmount(BigDecimal.ZERO); - row.setRefundAmount(BigDecimal.ZERO); - row.setSalesOrderCount(0); - row.setSalesQuantitySum(0); - row.setProductCost(BigDecimal.ZERO); - row.setFreightCost(BigDecimal.ZERO); - row.setOtherCost(BigDecimal.ZERO); - row.setGmvAmount(BigDecimal.ZERO); - row.setGmvOrderCount(0); - row.setGmvQuantitySum(0); - row.setStatVersion(0); - orderStatDailyMapper.upsertDailyShop(row); - } - - private static OrderStatDailyShopPO buildShopRow(Long companyId, Long shopId, String platformCode, - LocalDate statDate, - List rows, - int gmvOrderCount) { - BigDecimal sales = BigDecimal.ZERO; - BigDecimal refund = BigDecimal.ZERO; - BigDecimal pc = BigDecimal.ZERO; - BigDecimal fc = BigDecimal.ZERO; - BigDecimal oc = BigDecimal.ZERO; - BigDecimal gmv = BigDecimal.ZERO; - int orderCount = 0; - int salesQty = 0; - int gmvQty = 0; - for (OrderStatAggMapper.ShopProductRow r : rows) { - sales = sales.add(nz(r.getSalesAmount())); - refund = refund.add(nz(r.getRefundAmount())); - pc = pc.add(nz(r.getProductCost())); - fc = fc.add(nz(r.getFreightCost())); - oc = oc.add(nz(r.getOtherCost())); - gmv = gmv.add(nz(r.getGmvAllStatus())); - orderCount += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; - salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0; - gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0; - } - OrderStatDailyShopPO row = new OrderStatDailyShopPO(); - row.setCompanyId(companyId); - row.setShopId(shopId); - row.setPlatformCode(platformCode); - row.setStatDate(statDate); - row.setSalesAmount(sales); - row.setRefundAmount(refund); - row.setSalesOrderCount(orderCount); - row.setSalesQuantitySum(salesQty); - row.setProductCost(pc); - row.setFreightCost(fc); - row.setOtherCost(oc); - row.setGmvAmount(gmv); - row.setGmvOrderCount(gmvOrderCount); - row.setGmvQuantitySum(gmvQty); - row.setStatVersion(0); - return row; - } - - private static List buildProductRows(Long companyId, Long shopId, LocalDate statDate, - List rows) { - List list = new ArrayList<>(); - for (OrderStatAggMapper.ShopProductRow r : rows) { - if (isAllZeroProductRow(r)) { - continue; - } - OrderStatDailyProductPO p = new OrderStatDailyProductPO(); - p.setCompanyId(companyId); - p.setShopId(shopId); - p.setProductId(r.getProductId() != null ? r.getProductId() : 0L); - p.setCategoryId(r.getCategoryId() != null ? r.getCategoryId() : 0L); - p.setStatDate(statDate); - p.setSalesAmount(nz(r.getSalesAmount())); - p.setRefundAmount(nz(r.getRefundAmount())); - p.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); - p.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0); - p.setGmvAmount(nz(r.getGmvAllStatus())); - p.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0); - p.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0); - p.setProductCost(nz(r.getProductCost())); - p.setFreightCost(nz(r.getFreightCost())); - p.setOtherCost(nz(r.getOtherCost())); - p.setStatVersion(0); - list.add(p); - } - return list; - } - - private static List buildSpecRows(Long companyId, Long shopId, LocalDate statDate, - List rows) { - List list = new ArrayList<>(); - for (OrderStatRefreshMapper.SpecDayRow r : rows) { - if (isAllZeroSpecRow(r)) { - continue; - } - OrderStatDailySpecPO s = new OrderStatDailySpecPO(); - s.setCompanyId(companyId); - s.setShopId(shopId); - s.setProductId(r.getProductId() != null ? r.getProductId() : 0L); - s.setProductSkuId(r.getProductSkuId() != null ? r.getProductSkuId() : 0L); - s.setStatDate(statDate); - s.setSalesAmount(nz(r.getSalesAmount())); - s.setRefundAmount(nz(r.getRefundAmount())); - s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); - s.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum() : 0); - s.setGmvAmount(nz(r.getGmvAmount())); - s.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0); - s.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum() : 0); - s.setProductCost(nz(r.getProductCost())); - s.setFreightCost(nz(r.getFreightCost())); - s.setOtherCost(nz(r.getOtherCost())); - s.setStatVersion(0); - list.add(s); - } - return list; - } - - private static boolean isAllZeroProductRow(OrderStatAggMapper.ShopProductRow r) { - return nz(r.getSalesAmount()).signum() == 0 - && nz(r.getRefundAmount()).signum() == 0 - && nz(r.getGmvAllStatus()).signum() == 0 - && (r.getOrderCount() == null || r.getOrderCount() == 0) - && (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0); - } - - private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) { - return nz(r.getSalesAmount()).signum() == 0 - && nz(r.getRefundAmount()).signum() == 0 - && nz(r.getGmvAmount()).signum() == 0 - && (r.getOrderCount() == null || r.getOrderCount() == 0) - && (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0); - } - - private static BigDecimal nz(BigDecimal v) { - return v != null ? v : BigDecimal.ZERO; - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java deleted file mode 100644 index ce0d28a0..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRefreshWorker.java +++ /dev/null @@ -1,91 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import jakarta.annotation.PreDestroy; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * 异步消费 ec_order_stat_refresh_queue(独立线程池,不与导入消费者共用)。 - */ -@Service -public class OrderStatRefreshWorker { - - private static final Logger log = LoggerFactory.getLogger(OrderStatRefreshWorker.class); - - private final OrderStatProperties properties; - private final OrderStatRefreshCoordinator coordinator; - private final ExecutorService executorService; - private final AtomicBoolean running = new AtomicBoolean(false); - - public OrderStatRefreshWorker(OrderStatProperties properties, - OrderStatRefreshCoordinator coordinator) { - this.properties = properties; - this.coordinator = coordinator; - int pool = Math.max(1, properties.getRefreshWorker().getPoolSize()); - this.executorService = Executors.newFixedThreadPool(pool); - } - - @jakarta.annotation.PostConstruct - public void start() { - if (!properties.getRefreshWorker().isEnabled()) { - log.info("OrderStatRefreshWorker disabled by config"); - return; - } - if (running.compareAndSet(false, true)) { - int pool = properties.getRefreshWorker().getPoolSize(); - for (int i = 0; i < pool; i++) { - executorService.submit(this::pollLoop); - } - log.info("OrderStatRefreshWorker started, poolSize={}", pool); - } - } - - @PreDestroy - public void stop() { - if (running.compareAndSet(true, false)) { - executorService.shutdown(); - try { - if (!executorService.awaitTermination(15, TimeUnit.SECONDS)) { - executorService.shutdownNow(); - } - } catch (InterruptedException e) { - executorService.shutdownNow(); - Thread.currentThread().interrupt(); - } - log.info("OrderStatRefreshWorker stopped"); - } - } - - private void pollLoop() { - long interval = Math.max(500L, properties.getRefreshWorker().getPollIntervalMs()); - while (running.get()) { - try { - OrderStatRefreshQueuePO item = coordinator.fetchAndLockPending(); - if (item != null) { - coordinator.processQueueItem(item); - } else { - Thread.sleep(interval); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } catch (Exception e) { - log.error("OrderStatRefreshWorker poll error", e); - try { - Thread.sleep(interval); - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - break; - } - } - } - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java deleted file mode 100644 index a7a3e298..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/service/OrderStatRollupService.java +++ /dev/null @@ -1,30 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service; - -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper; - -import java.time.LocalDate; - -/** 日表变更后 rollup 月表、年表。 */ -@Service -public class OrderStatRollupService { - - private final OrderStatDailyMapper orderStatDailyMapper; - - public OrderStatRollupService(OrderStatDailyMapper orderStatDailyMapper) { - this.orderStatDailyMapper = orderStatDailyMapper; - } - - @Transactional(rollbackFor = Exception.class) - public void rollupAfterDailyChange(Long companyId, Long shopId, LocalDate statDate) { - LocalDate statMonth = statDate.withDayOfMonth(1); - int statYear = statDate.getYear(); - orderStatDailyMapper.rollupMonthlyShop(companyId, shopId, statMonth); - orderStatDailyMapper.rollupYearlyShop(companyId, shopId, statYear); - orderStatDailyMapper.rollupMonthlyProduct(companyId, shopId, statMonth); - orderStatDailyMapper.rollupYearlyProduct(companyId, shopId, statYear); - orderStatDailyMapper.rollupMonthlySpec(companyId, shopId, statMonth); - orderStatDailyMapper.rollupYearlySpec(companyId, shopId, statYear); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java deleted file mode 100644 index c649096d..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/OrderStatParamHelper.java +++ /dev/null @@ -1,47 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; - -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** 将 OrderStatusStatSets 转为 MyBatis IN 列表参数(状态码)。 */ -public final class OrderStatParamHelper { - - private OrderStatParamHelper() { - } - - public static List statusList(java.util.Collection codes) { - if (codes == null || codes.isEmpty()) { - return List.of("__NONE__"); - } - List list = new ArrayList<>(codes); - Collections.sort(list); - return list; - } - - public static List unionList(OrderStatusStatSets stat) { - return statusList(stat.getUnionStatusCodes()); - } - - public static List salesList(OrderStatusStatSets stat) { - return statusList(stat.getSalesCodes()); - } - - public static List refundList(OrderStatusStatSets stat) { - return statusList(stat.getRefundCodes()); - } - - public static List productCostList(OrderStatusStatSets stat) { - return statusList(stat.getProductCostCodes()); - } - - public static List freightCostList(OrderStatusStatSets stat) { - return statusList(stat.getFreightCostCodes()); - } - - public static List otherCostList(OrderStatusStatSets stat) { - return statusList(stat.getOtherCostCodes()); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java deleted file mode 100644 index 69c743e5..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/RefreshSource.java +++ /dev/null @@ -1,13 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; - -/** - * 汇总 refresh 触发来源。 - */ -public enum RefreshSource { - IMPORT, - CRUD, - STATUS_CHANGE, - MANUAL, - BACKFILL, - AUTO_MISS -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java deleted file mode 100644 index 8d5ff15d..00000000 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/order/stat/support/StatDirtyKey.java +++ /dev/null @@ -1,16 +0,0 @@ -package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support; - -import java.time.LocalDate; -import java.util.Objects; - -/** - * 待刷新维度:(公司, 店铺, 自然日)。 - */ -public record StatDirtyKey(Long companyId, Long shopId, LocalDate statDate) { - - public StatDirtyKey { - Objects.requireNonNull(companyId, "companyId"); - Objects.requireNonNull(shopId, "shopId"); - Objects.requireNonNull(statDate, "statDate"); - } -} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/model/agg/OverviewAggRows.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/model/agg/OverviewAggRows.java new file mode 100644 index 00000000..b9d47f45 --- /dev/null +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/model/agg/OverviewAggRows.java @@ -0,0 +1,64 @@ +package top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg; + +import lombok.Data; + +import java.math.BigDecimal; +import java.time.LocalDate; + +/** + * 概览/工作台 SQL 聚合行类型(原 OrderStatAggMapper 内嵌类,供 buildWorkbenchSummaryTablesFromAgg 等复用)。 + */ +public final class OverviewAggRows { + + private OverviewAggRows() { + } + + @Data + public static class ShopProductRow { + private Long shopId; + private String platformCode; + private Long productId; + private Long categoryId; + private BigDecimal salesAmount; + private Long orderCount; + private Long salesQuantitySum; + private BigDecimal refundAmount; + private BigDecimal productCost; + private BigDecimal freightCost; + private BigDecimal otherCost; + private BigDecimal gmvAllStatus; + private Long gmvOrderCount; + private Long gmvQuantitySum; + } + + @Data + public static class DailyRow { + private LocalDate statDate; + private BigDecimal salesAmount; + private BigDecimal refundAmount; + private BigDecimal productCost; + private BigDecimal freightCost; + private BigDecimal otherCost; + } + + @Data + public static class FeeKpiRow { + private BigDecimal curAmount; + private BigDecimal prevAmount; + private BigDecimal yoyAmount; + } + + @Data + public static class PromotionRow { + private Long shopId; + private Long productId; + private Long categoryId; + private BigDecimal feeAmount; + } + + @Data + public static class BrushRow { + private Long shopId; + private BigDecimal brushAmount; + } +} diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CompanyOverviewService.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CompanyOverviewService.java index e4f99970..a27cb2d8 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CompanyOverviewService.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/CompanyOverviewService.java @@ -1,7 +1,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.overview.service; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO; @@ -59,9 +59,9 @@ public interface CompanyOverviewService { BigDecimal taxRate, Long companyId, List shops, - List orderRows, - List promotionRows, - List brushRows, + List orderRows, + List promotionRows, + List brushRows, LocalDate startDate, LocalDate endDate); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java index 92de6221..0d674c1c 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/CompanyOverviewServiceImpl.java @@ -5,9 +5,7 @@ import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatOverviewAssembler; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.enums.PlatformCode; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO; @@ -68,8 +66,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { private final ProductMapper productMapper; private final ProductSkuMapper productSkuMapper; private final CategoryService categoryService; - private final OrderStatReadFacade orderStatReadFacade; - private final OrderStatOverviewAssembler orderStatOverviewAssembler; public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext, OrderMapper orderMapper, @@ -81,9 +77,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { OrderStatusStatResolver orderStatusStatResolver, ProductMapper productMapper, ProductSkuMapper productSkuMapper, - CategoryService categoryService, - OrderStatReadFacade orderStatReadFacade, - OrderStatOverviewAssembler orderStatOverviewAssembler) { + CategoryService categoryService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.orderItemMapper = orderItemMapper; @@ -95,8 +89,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { this.productMapper = productMapper; this.productSkuMapper = productSkuMapper; this.categoryService = categoryService; - this.orderStatReadFacade = orderStatReadFacade; - this.orderStatOverviewAssembler = orderStatOverviewAssembler; } /** @@ -160,15 +152,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { throw new BusinessException("当前公司没有店铺"); } - // 汇总表读路径 - if (orderStatReadFacade.usesDailyStatSource()) { - CompanyOverviewVO statVo = orderStatOverviewAssembler.buildCompanyOverview( - companyId, shops, startDate, endDate, taxRate, stat); - calculateTargetData(statVo, companyId, startDate, endDate, - statVo.getTotalSalesAmount(), statVo.getTotalOrderCount()); - return statVo; - } - // 查询订单数据(所有店铺) LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); orderWrapper.eq(OrderPO::getCompanyId, companyId) @@ -1814,9 +1797,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { BigDecimal taxRate, Long companyId, List shops, - List orderRows, - List promotionRows, - List brushRows, + List orderRows, + List promotionRows, + List brushRows, LocalDate startDate, LocalDate endDate) { synchronized (this) { @@ -1834,9 +1817,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal( Long companyId, List shops, - List orderRows, - List promotionRows, - List brushRows, + List orderRows, + List promotionRows, + List brushRows, LocalDate startDate, LocalDate endDate) { @@ -1847,7 +1830,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { Map> productSalesByShop = new HashMap<>(); Map productCategoryMap = new HashMap<>(); - for (OrderStatAggMapper.ShopProductRow row : orderRows) { + for (OverviewAggRows.ShopProductRow row : orderRows) { long shopId = row.getShopId() != null ? row.getShopId() : 0L; long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L; long categoryKey = productId <= 0 ? -1L @@ -1867,7 +1850,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { Map directPromoByProduct = new HashMap<>(); Map directPromoByCategory = new HashMap<>(); BigDecimal ratioPool = BigDecimal.ZERO; - for (OrderStatAggMapper.PromotionRow fee : promotionRows) { + for (OverviewAggRows.PromotionRow fee : promotionRows) { BigDecimal amt = nz(fee.getFeeAmount()); promoByShop.merge(fee.getShopId(), amt, BigDecimal::add); if (fee.getProductId() != null) { @@ -1879,7 +1862,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { } } Map brushByShop = new HashMap<>(); - for (OrderStatAggMapper.BrushRow b : brushRows) { + for (OverviewAggRows.BrushRow b : brushRows) { brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add); } BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); @@ -2120,7 +2103,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders))); } - private static void mergeAgg(Map map, long key, OrderStatAggMapper.ShopProductRow row) { + private static void mergeAgg(Map map, long key, OverviewAggRows.ShopProductRow row) { map.merge(key, AggMetrics.from(row), AggMetrics::merge); } @@ -2322,7 +2305,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService { return sales.subtract(orderCost()).subtract(refund); } - static AggMetrics from(OrderStatAggMapper.ShopProductRow row) { + static AggMetrics from(OverviewAggRows.ShopProductRow row) { AggMetrics a = new AggMetrics(); a.sales = nz(row.getSalesAmount()); a.gmv = nz(row.getGmvAllStatus()); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java index bcb23fcc..5d144b65 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/overview/service/impl/ShopOverviewStatisticsServiceImpl.java @@ -7,9 +7,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO; @@ -69,7 +66,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics private final ProductSkuMapper productSkuMapper; private final OrderStatusStatResolver orderStatusStatResolver; private final CategoryService categoryService; - private final OrderStatReadFacade orderStatReadFacade; private final CompanyOverviewService companyOverviewService; public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext, @@ -83,7 +79,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics ProductSkuMapper productSkuMapper, OrderStatusStatResolver orderStatusStatResolver, CategoryService categoryService, - OrderStatReadFacade orderStatReadFacade, CompanyOverviewService companyOverviewService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; @@ -96,7 +91,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics this.productSkuMapper = productSkuMapper; this.orderStatusStatResolver = orderStatusStatResolver; this.categoryService = categoryService; - this.orderStatReadFacade = orderStatReadFacade; this.companyOverviewService = companyOverviewService; } @@ -145,10 +139,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics throw new BusinessException("店铺不存在"); } - if (orderStatReadFacade.usesDailyStatSource()) { - return getShopOverviewFromStat(queryDTO, companyId, shop, startDate, endDate, stat); - } - // 查询订单数据(该店铺) LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); orderWrapper.eq(OrderPO::getCompanyId, companyId) @@ -1013,100 +1003,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics return total; } - /** 汇总表读路径:单店概览 */ - private ShopOverviewStatisticsVO getShopOverviewFromStat(ShopOverviewQueryDTO queryDTO, - Long companyId, ShopPO shop, - LocalDate startDate, LocalDate endDate, - OrderStatusStatSets stat) { - List shopIds = List.of(queryDTO.getShopId()); - OrderStatMetricsDTO cur = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate); - LocalDate lastStart = startDate.minusMonths(1); - LocalDate lastEnd = endDate.minusMonths(1); - OrderStatMetricsDTO lastMonth = orderStatReadFacade.sumShopMetrics(companyId, shopIds, lastStart, lastEnd); - - List promoRows = orderStatReadFacade.loadPromotionRows( - companyId, shopIds, startDate, endDate); - List brushRows = orderStatReadFacade.loadBrushRows( - companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59)); - BigDecimal totalPromo = promoRows.stream().map(r -> r.getFeeAmount() != null ? r.getFeeAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - BigDecimal totalBrush = brushRows.stream().map(r -> r.getBrushAmount() != null ? r.getBrushAmount() : BigDecimal.ZERO) - .reduce(BigDecimal.ZERO, BigDecimal::add); - - BigDecimal totalSales = cur.getSalesAmount() != null ? cur.getSalesAmount() : BigDecimal.ZERO; - BigDecimal refund = cur.getRefundAmount() != null ? cur.getRefundAmount() : BigDecimal.ZERO; - int orderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; - BigDecimal orderCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); - - ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO(); - vo.setShopId(shop.getId()); - vo.setShopName(shop.getName()); - vo.setTotalSalesAmount(totalSales); - vo.setTotalOrderCount(orderCount); - vo.setRefundAmount(refund); - vo.setAverageOrderValue(orderCount > 0 - ? totalSales.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO); - vo.setTotalPromotionFee(totalPromo); - vo.setAverageFeeRatio(totalSales.signum() > 0 ? totalPromo.divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); - BigDecimal profitBeforeTax = totalSales.subtract(orderCost).subtract(refund).subtract(totalPromo).subtract(totalBrush); - vo.setTotalProfitBeforeTax(profitBeforeTax); - BigDecimal tax = toSalesTaxAmount(totalSales, refund); - vo.setTotalTaxAmount(tax); - vo.setTotalNetProfitAfterTax(profitBeforeTax.subtract(tax).setScale(2, RoundingMode.HALF_UP)); - vo.setTotalROI(totalPromo.signum() > 0 - ? totalSales.subtract(refund).divide(totalPromo, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); - BigDecimal lastSales = lastMonth.getSalesAmount() != null ? lastMonth.getSalesAmount() : BigDecimal.ZERO; - if (lastSales.signum() > 0) { - vo.setMonthOverMonthGrowth(totalSales.subtract(lastSales).divide(lastSales, 4, RoundingMode.HALF_UP) - .multiply(new BigDecimal("100"))); - } else if (totalSales.signum() > 0) { - vo.setMonthOverMonthGrowth(new BigDecimal("100")); - } else { - vo.setMonthOverMonthGrowth(BigDecimal.ZERO); - } - - calculateTargetData(vo, companyId, queryDTO.getShopId(), startDate, endDate, totalSales, orderCount); - - List daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, startDate, endDate); - vo.setSalesAmountTrend(buildShopTrendFromStat(daily, startDate, endDate, OrderStatMetricsDTO::getSalesAmount)); - vo.setOrderCountTrend(buildShopTrendFromStat(daily, startDate, endDate, - m -> BigDecimal.valueOf(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0))); - - List orderRows = orderStatReadFacade.loadShopProductRows( - companyId, shopIds, startDate, endDate, stat); - CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg( - taxRate, companyId, List.of(shop), orderRows, promoRows, brushRows, startDate, endDate); - vo.setProductOverview(mapProductOverview(bundle.getProductTable())); - vo.setCategoryOverview(mapCategoryOverview(bundle.getCategoryTable())); - fillProductSalesTop10(vo); - return vo; - } - - private ShopOverviewStatisticsVO.TrendData buildShopTrendFromStat(List daily, - LocalDate start, LocalDate end, - java.util.function.Function fn) { - Map map = new HashMap<>(); - for (OrderStatMetricsDTO d : daily) { - if (d.getStatDate() != null) { - map.put(d.getStatDate(), fn.apply(d)); - } - } - List items = new ArrayList<>(); - BigDecimal total = BigDecimal.ZERO; - for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { - BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); - ShopOverviewStatisticsVO.TrendDataItem item = new ShopOverviewStatisticsVO.TrendDataItem(); - item.setDate(d); - item.setValue(v); - items.add(item); - total = total.add(v); - } - ShopOverviewStatisticsVO.TrendData trend = new ShopOverviewStatisticsVO.TrendData(); - trend.setDailyDataList(items); - trend.setTotal(total); - return trend; - } - private static ShopOverviewStatisticsVO.ProductOverview mapProductOverview(CompanyOverviewVO.CategoryOverview table) { if (table == null) { return new ShopOverviewStatisticsVO.ProductOverview(); diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java index bf4882be..1d8ee2f0 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/overview/service/impl/ProductOverviewServiceImpl.java @@ -8,8 +8,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderItemMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderItemPO; import top.xyquan.ecomdmbbackend.modules.ecom.order.support.OrderOverviewSupport; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO; @@ -50,7 +48,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { private final ProductSkuMapper productSkuMapper; private final ShopMonthlyTargetMapper shopMonthlyTargetMapper; private final ShopService shopService; - private final OrderStatReadFacade orderStatReadFacade; public ProductOverviewServiceImpl(CurrentUserContext currentUserContext, OrderMapper orderMapper, @@ -60,8 +57,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { ProductService productService, ProductSkuMapper productSkuMapper, ShopMonthlyTargetMapper shopMonthlyTargetMapper, - ShopService shopService, - OrderStatReadFacade orderStatReadFacade) { + ShopService shopService) { this.currentUserContext = currentUserContext; this.orderMapper = orderMapper; this.orderItemMapper = orderItemMapper; @@ -71,7 +67,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { this.productSkuMapper = productSkuMapper; this.shopMonthlyTargetMapper = shopMonthlyTargetMapper; this.shopService = shopService; - this.orderStatReadFacade = orderStatReadFacade; } private void applyProductOverviewOrderScope(LambdaQueryWrapper wrapper, @@ -144,11 +139,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); List unionStatusCodes = stat.getUnionStatusCodes(); - if (orderStatReadFacade.usesDailyStatSource()) { - return getProductOverviewFromStat(queryDTO, companyId, product, filterShopId, - startDate, endDate, taxRate, stat); - } - // 查询订单数据 LambdaQueryWrapper orderWrapper = new LambdaQueryWrapper<>(); applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId, @@ -830,208 +820,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService { .collect(Collectors.toList()); } - /** 汇总表读路径:商品概览 */ - private ProductOverviewVO getProductOverviewFromStat(ProductOverviewQueryDTO queryDTO, - Long companyId, ProductPO product, - Long filterShopId, - LocalDate startDate, LocalDate endDate, - BigDecimal taxRate, OrderStatusStatSets stat) { - List shopIds; - if (filterShopId != null) { - shopIds = List.of(filterShopId); - } else { - shopIds = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list() - .stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); - } - - OrderStatMetricsDTO cur = orderStatReadFacade.sumProductForOne( - companyId, shopIds, queryDTO.getProductId(), startDate, endDate); - long dayCount = ChronoUnit.DAYS.between(startDate, endDate) + 1; - LocalDate lastStart = startDate.minusDays(dayCount); - LocalDate lastEnd = startDate.minusDays(1); - OrderStatMetricsDTO last = orderStatReadFacade.sumProductForOne( - companyId, shopIds, queryDTO.getProductId(), lastStart, lastEnd); - - BigDecimal totalSales = nz(cur.getSalesAmount()); - BigDecimal totalRefund = nz(cur.getRefundAmount()); - int totalOrderCount = cur.getSalesOrderCount() != null ? cur.getSalesOrderCount() : 0; - BigDecimal totalCost = nz(cur.getProductCost()).add(nz(cur.getFreightCost())).add(nz(cur.getOtherCost())); - - List promotionFees = new ArrayList<>(); - if (!shopIds.isEmpty()) { - LambdaQueryWrapper promoWrapper = new LambdaQueryWrapper<>(); - promoWrapper.eq(PromotionFeePO::getCompanyId, companyId) - .in(PromotionFeePO::getShopId, shopIds) - .ge(PromotionFeePO::getFeeDate, startDate) - .le(PromotionFeePO::getFeeDate, endDate); - promotionFees = promotionFeeMapper.selectList(promoWrapper); - } - BigDecimal shopSalesDenominator = orderStatReadFacade.sumShopMetrics(companyId, shopIds, startDate, endDate) - .getSalesAmount(); - BigDecimal totalPromotionFee = computeAttributedPromotionFromStat( - queryDTO.getProductId(), product, shopSalesDenominator, promotionFees); - - ProductOverviewVO vo = new ProductOverviewVO(); - vo.setProductId(product.getId()); - vo.setProductName(product.getName()); - vo.setTotalSalesAmount(totalSales); - vo.setTotalOrderCount(totalOrderCount); - vo.setAverageFeeRatio(totalSales.signum() > 0 - ? totalPromotionFee.divide(totalSales, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) - .setScale(2, RoundingMode.HALF_UP) : BigDecimal.ZERO); - BigDecimal tax = salesTaxOnNetSales(totalSales, totalRefund, taxRate); - vo.setTotalTaxAmount(tax); - vo.setTotalNetProfitAfterTax(totalSales.subtract(totalCost).subtract(totalRefund) - .subtract(totalPromotionFee).subtract(tax).setScale(2, RoundingMode.HALF_UP)); - vo.setTotalROI(totalPromotionFee.signum() > 0 - ? totalSales.subtract(totalRefund).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) - : BigDecimal.ZERO); - vo.setMonthOverMonthGrowth(growthPct(totalSales, nz(last.getSalesAmount()))); - - vo.setSalesAmountTrend(buildTrendFromStatDaily( - orderStatReadFacade.sumProductByDayForOne(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), - startDate, endDate, OrderStatMetricsDTO::getSalesAmount)); - vo.setOrderCountTrend(buildTrendFromStatDaily( - orderStatReadFacade.sumProductByDayForOne(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), - startDate, endDate, m -> BigDecimal.valueOf(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0))); - - vo.setSpecSummaries(buildSpecSummaryFromStat( - orderStatReadFacade.sumSpecMetrics(companyId, shopIds, queryDTO.getProductId(), startDate, endDate), - taxRate, totalPromotionFee, totalSales)); - vo.setSpecSalesTop10(buildSpecTop10FromStat( - orderStatReadFacade.sumSpecMetrics(companyId, shopIds, queryDTO.getProductId(), startDate, endDate))); - return vo; - } - - private BigDecimal computeAttributedPromotionFromStat(Long productId, ProductPO product, - BigDecimal shopSalesTotal, - List promotionFees) { - if (promotionFees == null || promotionFees.isEmpty()) { - return BigDecimal.ZERO; - } - BigDecimal direct = BigDecimal.ZERO; - BigDecimal ratioPool = BigDecimal.ZERO; - for (PromotionFeePO fee : promotionFees) { - BigDecimal amt = fee.getFeeAmount() != null ? fee.getFeeAmount() : BigDecimal.ZERO; - if (fee.getProductId() != null && fee.getProductId().equals(productId)) { - direct = direct.add(amt); - } else if (fee.getCategoryId() != null && product.getCategoryId() != null - && fee.getCategoryId().equals(product.getCategoryId())) { - direct = direct.add(amt); - } else if (fee.getProductId() == null && fee.getCategoryId() == null) { - ratioPool = ratioPool.add(amt); - } - } - BigDecimal productSales = orderStatReadFacade.sumProductForOne( - product.getCompanyId(), List.of(), productId, - promotionFees.get(0).getFeeDate(), promotionFees.get(0).getFeeDate()).getSalesAmount(); - if (shopSalesTotal != null && shopSalesTotal.signum() > 0 && ratioPool.signum() > 0) { - direct = direct.add(ratioPool.multiply(productSales).divide(shopSalesTotal, 4, RoundingMode.HALF_UP)); - } - return direct; - } - - private ProductOverviewVO.TrendData buildTrendFromStatDaily(List daily, - LocalDate start, LocalDate end, - java.util.function.Function fn) { - Map map = new HashMap<>(); - for (OrderStatMetricsDTO d : daily) { - if (d.getStatDate() != null) { - map.put(d.getStatDate(), fn.apply(d)); - } - } - List items = new ArrayList<>(); - BigDecimal total = BigDecimal.ZERO; - for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) { - BigDecimal v = map.getOrDefault(d, BigDecimal.ZERO); - ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem(); - item.setDate(d); - item.setValue(v); - items.add(item); - total = total.add(v); - } - ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData(); - trend.setDailyDataList(items); - trend.setTotal(total); - return trend; - } - - private ProductOverviewVO.SpecSummary buildSpecSummaryFromStat(List skuRows, - BigDecimal taxRate, - BigDecimal totalPromo, - BigDecimal totalSales) { - if (skuRows == null || skuRows.isEmpty()) { - return buildEmptySpecSummary(); - } - Set skuIds = skuRows.stream().map(OrderStatMetricsDTO::getProductSkuId) - .filter(Objects::nonNull).collect(Collectors.toSet()); - Map skuMap = productSkuMapper.selectBatchIds(skuIds).stream() - .collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a)); - - List items = new ArrayList<>(); - for (OrderStatMetricsDTO m : skuRows) { - ProductSkuPO spec = skuMap.get(m.getProductSkuId()); - BigDecimal sales = nz(m.getSalesAmount()); - BigDecimal promoShare = totalSales.signum() > 0 - ? totalPromo.multiply(sales).divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO; - ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem(); - item.setSkuId(m.getProductSkuId()); - item.setSkuName(spec != null ? spec.getName() : "未知规格"); - item.setSkuCode(spec != null ? spec.getSkuCode() : null); - item.setSalesAmount(sales); - item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0); - item.setQuantity(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0); - item.setProductCost(nz(m.getProductCost())); - item.setShippingCost(nz(m.getFreightCost())); - item.setOtherCost(nz(m.getOtherCost())); - item.setOrderCost(item.getProductCost().add(item.getShippingCost()).add(item.getOtherCost())); - item.setRefundAmount(nz(m.getRefundAmount())); - item.setPromotionFee(promoShare); - item.setSalesTaxAmount(salesTaxOnNetSales(sales, item.getRefundAmount(), taxRate)); - item.setProfitAfterTax(sales.subtract(item.getOrderCost()).subtract(item.getRefundAmount()) - .subtract(promoShare).subtract(item.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP)); - items.add(item); - } - ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); - summary.setList(items); - summary.setTotal(buildSpecTotal(items)); - return summary; - } - - private static ProductOverviewVO.SpecSummaryTotal buildSpecTotal(List items) { - ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal(); - total.setSalesAmount(items.stream().map(ProductOverviewVO.SpecSummaryItem::getSalesAmount) - .reduce(BigDecimal.ZERO, BigDecimal::add)); - total.setOrderCount(items.stream().mapToInt(i -> i.getOrderCount() != null ? i.getOrderCount() : 0).sum()); - total.setQuantity(items.stream().mapToInt(i -> i.getQuantity() != null ? i.getQuantity() : 0).sum()); - return total; - } - - private List buildSpecTop10FromStat(List skuRows) { - if (skuRows == null) { - return List.of(); - } - Set skuIds = skuRows.stream().map(OrderStatMetricsDTO::getProductSkuId) - .filter(Objects::nonNull).collect(Collectors.toSet()); - Map skuMap = skuIds.isEmpty() ? Map.of() - : productSkuMapper.selectBatchIds(skuIds).stream() - .collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a)); - return skuRows.stream() - .sorted(Comparator.comparingInt((OrderStatMetricsDTO m) -> - m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0).reversed()) - .limit(10) - .map(m -> { - ProductSkuPO spec = skuMap.get(m.getProductSkuId()); - ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem(); - item.setSkuId(m.getProductSkuId()); - item.setSkuName(spec != null ? spec.getName() : "未知规格"); - item.setSkuCode(spec != null ? spec.getSkuCode() : null); - item.setOrderCount(m.getSalesOrderCount()); - item.setSalesAmount(nz(m.getSalesAmount())); - return item; - }).collect(Collectors.toList()); - } - private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) { if (prev.signum() > 0) { return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100)) diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSkuServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSkuServiceImpl.java index aad5b5fa..f9c9758d 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSkuServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/product/service/impl/ProductSkuServiceImpl.java @@ -13,9 +13,6 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO; import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey; import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSkuMapper; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductSkuDTO; import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductSkuFilterDTO; @@ -31,10 +28,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService; import top.xyquan.ecomdmbbackend.utils.CurrentUserContext; import java.math.BigDecimal; -import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Set; import java.util.stream.Collectors; /** @@ -49,17 +44,14 @@ public class ProductSkuServiceImpl extends ServiceImpl affected = - orderMapper.selectOrphanOrderStatDatesBySkuCode(companyId, code); orderMapper.linkOrdersBySkuCodeWhenSkuIdNull(companyId, code, productSkuId); - if (affected != null && !affected.isEmpty()) { - Set keys = new HashSet<>(); - for (OrderShopStatDateRow row : affected) { - if (row.getShopId() != null && row.getStatDate() != null) { - keys.add(new StatDirtyKey(companyId, row.getShopId(), row.getStatDate())); - } - } - orderStatCrudCoordinator.enqueueDirtyKeys(keys); - } } catch (Exception ex) { log.warn("挂 orphan 订单跳过(订单表可能不存在): {}", ex.getMessage()); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java index 071e9422..be0d212f 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/promotion/service/impl/PromotionFeeServiceImpl.java @@ -17,7 +17,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotio import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService; import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; @@ -43,22 +42,19 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { private final PromotionFeeTypeService promotionFeeTypeService; private final ProductService productService; private final CategoryService categoryService; - private final FeeStatCrudCoordinator feeStatCrudCoordinator; public PromotionFeeServiceImpl(PromotionFeeMapper promotionFeeMapper, CurrentUserContext currentUserContext, ShopService shopService, PromotionFeeTypeService promotionFeeTypeService, ProductService productService, - CategoryService categoryService, - FeeStatCrudCoordinator feeStatCrudCoordinator) { + CategoryService categoryService) { this.promotionFeeMapper = promotionFeeMapper; this.currentUserContext = currentUserContext; this.shopService = shopService; this.promotionFeeTypeService = promotionFeeTypeService; this.productService = productService; this.categoryService = categoryService; - this.feeStatCrudCoordinator = feeStatCrudCoordinator; } /** @@ -77,7 +73,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { po.setUpdateBy(currentUserContext.getCurrentUserId()); promotionFeeMapper.insert(po); - feeStatCrudCoordinator.afterPromotionFeeSaved(null, po); return po.getId(); } @@ -99,7 +94,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { po.setUpdateBy(currentUserContext.getCurrentUserId()); po.setCompanyId(companyId); promotionFeeMapper.updateById(po); - feeStatCrudCoordinator.afterPromotionFeeSaved(existing, po); } /** @@ -115,7 +109,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService { throw new BusinessException("推广费记录不存在"); } promotionFeeMapper.deleteById(id); - feeStatCrudCoordinator.afterPromotionFeeDeleted(existing); } /** diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java index 4475e24d..d2de270d 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchExportServiceImpl.java @@ -3,10 +3,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.workbench.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; -import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO; @@ -38,27 +35,21 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { private final CurrentUserContext currentUserContext; private final ShopService shopService; - private final OrderStatusStatResolver orderStatusStatResolver; private final CompanyOverviewService companyOverviewService; private final ExportService exportService; private final CategoryExportExcelService categoryExportExcelService; - private final OrderStatReadFacade orderStatReadFacade; public WorkbenchExportServiceImpl( CurrentUserContext currentUserContext, ShopService shopService, - OrderStatusStatResolver orderStatusStatResolver, CompanyOverviewService companyOverviewService, ExportService exportService, - CategoryExportExcelService categoryExportExcelService, - OrderStatReadFacade orderStatReadFacade) { + CategoryExportExcelService categoryExportExcelService) { this.currentUserContext = currentUserContext; this.shopService = shopService; - this.orderStatusStatResolver = orderStatusStatResolver; this.companyOverviewService = companyOverviewService; this.exportService = exportService; this.categoryExportExcelService = categoryExportExcelService; - this.orderStatReadFacade = orderStatReadFacade; } /** @@ -129,24 +120,18 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService { private CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) { Long companyId = currentUserContext.getCurrentCompanyId(); DateRange range = parseDateRange(toQuery(dto)); - OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId); List shops = loadFilteredShops(companyId, dto.getPlatformCode(), dto.getShopId()); if (shops.isEmpty()) { throw new BusinessException("没有可导出的店铺"); } - List shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(); - - List orderRows = orderStatReadFacade.loadShopProductRows( - companyId, shopIds, range.startDate(), range.endDate(), stat); - List promotionRows = orderStatReadFacade.loadPromotionRows( - companyId, shopIds, range.startDate(), range.endDate()); - List brushRows = orderStatReadFacade.loadBrushRows( - companyId, shopIds, range.startDateTime(), range.endDateTime()); BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE; return companyOverviewService.buildWorkbenchSummaryTablesFromAgg( - taxRate, companyId, shops, orderRows, promotionRows, brushRows, + taxRate, companyId, shops, + List.of(), + List.of(), + List.of(), range.startDate(), range.endDate()); } diff --git a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java index 9aba0eba..52a6cb5a 100644 --- a/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java +++ b/ecom-dmb-backend/src/main/java/top/xyquan/ecomdmbbackend/modules/ecom/workbench/service/impl/WorkbenchServiceImpl.java @@ -5,9 +5,7 @@ import org.springframework.stereotype.Service; import top.xyquan.ecomdmbbackend.common.exception.BusinessException; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; -import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; -import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; +import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO; @@ -75,7 +73,6 @@ public class WorkbenchServiceImpl implements WorkbenchService { private final OrderStatusStatResolver orderStatusStatResolver; private final ProductMapper productMapper; private final CategoryService categoryService; - private final OrderStatReadFacade orderStatReadFacade; private final CompanyOverviewService companyOverviewService; public WorkbenchServiceImpl(CurrentUserContext currentUserContext, @@ -83,14 +80,12 @@ public class WorkbenchServiceImpl implements WorkbenchService { OrderStatusStatResolver orderStatusStatResolver, ProductMapper productMapper, CategoryService categoryService, - OrderStatReadFacade orderStatReadFacade, CompanyOverviewService companyOverviewService) { this.currentUserContext = currentUserContext; this.shopService = shopService; this.orderStatusStatResolver = orderStatusStatResolver; this.productMapper = productMapper; this.categoryService = categoryService; - this.orderStatReadFacade = orderStatReadFacade; this.companyOverviewService = companyOverviewService; } @@ -203,65 +198,31 @@ public class WorkbenchServiceImpl implements WorkbenchService { return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById); } - /** 当前区间 SQL-1/2/4/5(汇总表或明细回退) */ + /** 订单统计读模型已移除:返回空聚合,KPI/趋势降级为 0 */ private SqlAggBundle loadSqlAgg(ShopContext ctx) { - LocalDate start = ctx.range().startDate(); - LocalDate end = ctx.range().endDate(); - List orderRows = orderStatReadFacade.loadShopProductRows( - ctx.companyId(), ctx.shopIds(), start, end, ctx.stat()); - List dailyRows = orderStatReadFacade.loadDailyRows( - ctx.companyId(), ctx.shopIds(), start, end, ctx.stat()); - List promotionRows = orderStatReadFacade.loadPromotionRows( - ctx.companyId(), ctx.shopIds(), start, end); - List brushRows = orderStatReadFacade.loadBrushRows( - ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime()); - return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows); + return new SqlAggBundle(Collections.emptyList(), Collections.emptyList(), + Collections.emptyList(), Collections.emptyList()); } - /** 环比/同比:店铺汇总表 + 各段推广/刷单 */ + /** 环比/同比:统计读模型移除后各段均为 0 */ private ComparePeriodBundle loadCompareFromSql(ShopContext ctx) { DateRange lastRange = lastMonthSameSpan(ctx.range()); DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1)); - - LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate()); - LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate()); - OrderStatAggMapper.FeeKpiRow promoKpi = orderStatReadFacade.loadPromotionPeriodKpi( - ctx.companyId(), ctx.shopIds(), feeScanStart, feeScanEnd, - ctx.range().startDate(), ctx.range().endDate(), - lastRange.startDate(), lastRange.endDate(), - yoyRange.startDate(), yoyRange.endDate()); - OrderStatAggMapper.FeeKpiRow brushKpi = orderStatReadFacade.loadBrushPeriodKpi( - ctx.companyId(), ctx.shopIds(), - minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime()), - maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime()), - ctx.range().startDateTime(), ctx.range().endDateTime(), - lastRange.startDateTime(), lastRange.endDateTime(), - yoyRange.startDateTime(), yoyRange.endDateTime()); - - Totals prev = buildShopPeriodTotals(ctx, lastRange, nz(promoKpi.getPrevAmount()), nz(brushKpi.getPrevAmount())); - Totals yoy = buildShopPeriodTotals(ctx, yoyRange, nz(promoKpi.getYoyAmount()), nz(brushKpi.getYoyAmount())); + Totals prev = buildShopPeriodTotals(ctx, lastRange, BigDecimal.ZERO, BigDecimal.ZERO); + Totals yoy = buildShopPeriodTotals(ctx, yoyRange, BigDecimal.ZERO, BigDecimal.ZERO); return new ComparePeriodBundle(lastRange, yoyRange, prev, yoy); } - /** 单时间段店铺 KPI:读 ec_order_stat_daily_shop 合计 */ + /** 单时间段店铺 KPI:统计读模型移除后返回 0 */ private Totals buildShopPeriodTotals(ShopContext ctx, DateRange range, BigDecimal promotion, BigDecimal brush) { - OrderStatMetricsDTO m = orderStatReadFacade.sumShopMetrics( - ctx.companyId(), ctx.shopIds(), range.startDate(), range.endDate()); - return buildTotals( - nz(m.getSalesAmount()), nz(m.getRefundAmount()), - nz(m.getProductCost()), nz(m.getFreightCost()), nz(m.getOtherCost()), - promotion, brush, ctx.taxRate(), - m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0, - m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0, - nz(m.getGmvAmount()), - m.getGmvOrderCount() != null ? m.getGmvOrderCount() : 0, - m.getGmvQuantitySum() != null ? m.getGmvQuantitySum() : 0); + return buildTotals(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, + promotion, brush, ctx.taxRate(), 0, 0, BigDecimal.ZERO, 0, 0); } private WorkbenchFinancePanelVO buildFinancePanelFromSql(ShopContext ctx, Totals cur, ComparePeriodBundle compare, SqlAggBundle agg) { Map platformAgg = new HashMap<>(); - for (OrderStatAggMapper.ShopProductRow row : agg.orderRows()) { + for (OverviewAggRows.ShopProductRow row : agg.orderRows()) { String pk = blankPlatformKey(row.getPlatformCode()); platformAgg.computeIfAbsent(pk, k -> new Agg()).addFromAggRow(row); } @@ -276,7 +237,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { .build(); } - private DimensionAggMaps aggregateDimensionsFromSql(List rows, ShopContext ctx) { + private DimensionAggMaps aggregateDimensionsFromSql(List rows, ShopContext ctx) { Map platformAgg = new HashMap<>(); Map shopAgg = new HashMap<>(); Map categoryAgg = new HashMap<>(); @@ -284,7 +245,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { Set productIds = new HashSet<>(); Set categoryIds = new HashSet<>(); - for (OrderStatAggMapper.ShopProductRow row : rows) { + for (OverviewAggRows.ShopProductRow row : rows) { String platformKey = blankPlatformKey(row.getPlatformCode()); long shopKey = row.getShopId() != null ? row.getShopId() : 0L; long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L; @@ -307,12 +268,12 @@ public class WorkbenchServiceImpl implements WorkbenchService { loadPlatformNames(ctx.shops()), categoryNames, productById, ctx.shopById()); } - private Totals totalsFromOrderRows(List rows, + private Totals totalsFromOrderRows(List rows, BigDecimal promotion, BigDecimal brush, BigDecimal taxRate) { BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO; BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO; int orderCount = 0; - for (OrderStatAggMapper.ShopProductRow row : rows) { + for (OverviewAggRows.ShopProductRow row : rows) { sales = sales.add(nz(row.getSalesAmount())); refund = refund.add(nz(row.getRefundAmount())); pc = pc.add(nz(row.getProductCost())); @@ -345,10 +306,10 @@ public class WorkbenchServiceImpl implements WorkbenchService { aov, gmvAov, salesPiecePrice, gmvPiecePrice); } - private List buildTrendFromDaily(List dailyRows, + private List buildTrendFromDaily(List dailyRows, DateRange range, Totals periodTotals) { - Map byDay = new HashMap<>(); - for (OrderStatAggMapper.DailyRow row : dailyRows) { + Map byDay = new HashMap<>(); + for (OverviewAggRows.DailyRow row : dailyRows) { if (row.getStatDate() != null) { byDay.put(row.getStatDate(), row); } @@ -360,7 +321,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { } List list = new ArrayList<>(); for (LocalDate d = range.startDate(); !d.isAfter(range.endDate()); d = d.plusDays(1)) { - OrderStatAggMapper.DailyRow row = byDay.get(d); + OverviewAggRows.DailyRow row = byDay.get(d); BigDecimal sales = row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO; BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO; BigDecimal cost = row != null @@ -391,7 +352,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { .stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a)); } - private static BigDecimal dayNetSales(OrderStatAggMapper.DailyRow row) { + private static BigDecimal dayNetSales(OverviewAggRows.DailyRow row) { if (row == null) { return BigDecimal.ZERO; } @@ -442,10 +403,10 @@ public class WorkbenchServiceImpl implements WorkbenchService { return v != null ? v : BigDecimal.ZERO; } - private record SqlAggBundle(List orderRows, - List dailyRows, - List promotionRows, - List brushRows) { + private record SqlAggBundle(List orderRows, + List dailyRows, + List promotionRows, + List brushRows) { BigDecimal promoTotal() { return promotionRows.stream().map(r -> nz(r.getFeeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); } @@ -936,7 +897,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { BigDecimal cost = BigDecimal.ZERO; /** 累加 SQL 聚合行 */ - void addFromAggRow(OrderStatAggMapper.ShopProductRow row) { + void addFromAggRow(OverviewAggRows.ShopProductRow row) { sales = sales.add(nz(row.getSalesAmount())); refund = refund.add(nz(row.getRefundAmount())); cost = cost.add(nz(row.getProductCost())).add(nz(row.getFreightCost())).add(nz(row.getOtherCost())); diff --git a/ecom-dmb-backend/src/main/resources/application-dev.yml b/ecom-dmb-backend/src/main/resources/application-dev.yml index 26ad51cc..b1157d6f 100644 --- a/ecom-dmb-backend/src/main/resources/application-dev.yml +++ b/ecom-dmb-backend/src/main/resources/application-dev.yml @@ -23,8 +23,6 @@ mybatis-plus: # 开发环境可按需打开 SQL 日志 # log-impl: org.apache.ibatis.logging.stdout.StdOutImpl -order-stat: - nightly-rebuild-enabled: false knife4j: enable: true diff --git a/ecom-dmb-backend/src/main/resources/application-pre.yml b/ecom-dmb-backend/src/main/resources/application-pre.yml index e83e875c..d4049ac5 100644 --- a/ecom-dmb-backend/src/main/resources/application-pre.yml +++ b/ecom-dmb-backend/src/main/resources/application-pre.yml @@ -20,8 +20,6 @@ spring: jwt: secret: staging-jwt-secret-key-must-be-at-least-64-bytes-long-for-hs512-algorithm -order-stat: - nightly-rebuild-enabled: false knife4j: enable: true diff --git a/ecom-dmb-backend/src/main/resources/application-prod.yml b/ecom-dmb-backend/src/main/resources/application-prod.yml index 7c26b5b9..9ad26ec4 100644 --- a/ecom-dmb-backend/src/main/resources/application-prod.yml +++ b/ecom-dmb-backend/src/main/resources/application-prod.yml @@ -21,8 +21,6 @@ spring: jwt: secret: prod-jwt-secret-key-must-be-at-least-64-bytes-long-for-hs512-algorithm-security -order-stat: - nightly-rebuild-enabled: false knife4j: enable: false diff --git a/ecom-dmb-backend/src/main/resources/application-test.yml b/ecom-dmb-backend/src/main/resources/application-test.yml index c1d8086d..134aaabd 100644 --- a/ecom-dmb-backend/src/main/resources/application-test.yml +++ b/ecom-dmb-backend/src/main/resources/application-test.yml @@ -18,10 +18,6 @@ spring: jwt: secret: test-jwt-secret-key-must-be-at-least-64-bytes-long-for-hs512-algorithm -order-stat: - nightly-rebuild-enabled: false - refresh-worker: - enabled: false knife4j: enable: true diff --git a/ecom-dmb-backend/src/main/resources/application.yml b/ecom-dmb-backend/src/main/resources/application.yml index 88897c70..7d6b6406 100644 --- a/ecom-dmb-backend/src/main/resources/application.yml +++ b/ecom-dmb-backend/src/main/resources/application.yml @@ -35,19 +35,6 @@ spring: max-wait: -1ms # 订单统计读模型(汇总表已删,待重构前关闭写入与 miss 补算) -order-stat: - stat-source: daily - auto-refresh-on-miss: false - refresh-worker: - enabled: false - pool-size: 4 - poll-interval-ms: 2000 - cache: - enabled: true - ttl-history-seconds: 86400 - ttl-today-seconds: 900 - nightly-rebuild-cron: "0 30 2 * * ?" - nightly-rebuild-enabled: false # 导入任务 Redis Stream 队列(DB 为真相源,Redis 负责调度) import-task: diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/OrderStatAggMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/OrderStatAggMapper.xml deleted file mode 100644 index c81cbb0e..00000000 --- a/ecom-dmb-backend/src/main/resources/mapper/order/OrderStatAggMapper.xml +++ /dev/null @@ -1,251 +0,0 @@ - - - - - - o.company_id = #{companyId} - - - AND o.shop_id IN - #{id} - - AND 1 = 0 - - AND o.order_time >= #{start} - AND o.order_time <= #{end} - - - - - - - AND o.status IN - #{id} - - AND 1 = 0 - - - - IFNULL(NULLIF(i.quantity, 0), 1) - - IFNULL(NULLIF(i.line_amount, 0), IFNULL(i.unit_price, 0) * ) - - - SUM(CASE WHEN o.status IN - #{id} - THEN ELSE 0 END) - - - COUNT(DISTINCT CASE WHEN o.status IN - #{id} - THEN o.id END) - - - SUM(CASE WHEN o.status IN - #{id} - THEN ELSE 0 END) - - - SUM() - - - SUM(CASE WHEN o.status IN - #{id} - THEN ELSE 0 END) - - - SUM(CASE WHEN o.status IN - #{id} - THEN IFNULL(i.product_cost, 0) * ELSE 0 END) - - - SUM(CASE WHEN o.status IN - #{id} - THEN IFNULL(i.shipping_cost, 0) * ELSE 0 END) - - - SUM(CASE WHEN o.status IN - #{id} - THEN IFNULL(i.other_cost, 0) * ELSE 0 END) - - - - - - - - - - - - - - - - diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml deleted file mode 100644 index 9868d0d6..00000000 --- a/ecom-dmb-backend/src/main/resources/mapper/order/stat/FeeStatDailyMapper.xml +++ /dev/null @@ -1,94 +0,0 @@ - - - - - - DELETE FROM ec_promotion_fee_stat_daily - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} - - - - INSERT INTO ec_promotion_fee_stat_daily ( - company_id, shop_id, product_id, category_id, stat_date, fee_amount - ) VALUES - - (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, #{r.feeAmount}) - - - - - INSERT INTO ec_promotion_fee_stat_monthly ( - company_id, shop_id, product_id, category_id, stat_month, fee_amount - ) - SELECT company_id, shop_id, product_id, category_id, #{statMonth}, SUM(fee_amount) - FROM ec_promotion_fee_stat_daily - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND stat_date >= #{statMonth} - AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) - GROUP BY company_id, shop_id, product_id, category_id - ON DUPLICATE KEY UPDATE fee_amount = VALUES(fee_amount), update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_promotion_fee_stat_yearly ( - company_id, shop_id, product_id, category_id, stat_year, fee_amount - ) - SELECT company_id, shop_id, product_id, category_id, #{statYear}, SUM(fee_amount) - FROM ec_promotion_fee_stat_monthly - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND YEAR(stat_month) = #{statYear} - GROUP BY company_id, shop_id, product_id, category_id - ON DUPLICATE KEY UPDATE fee_amount = VALUES(fee_amount), update_time = CURRENT_TIMESTAMP - - - - DELETE FROM ec_brush_fee_stat_daily - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} - - - - INSERT INTO ec_brush_fee_stat_daily (company_id, shop_id, stat_date, brush_amount) - VALUES (#{companyId}, #{shopId}, #{statDate}, #{brushAmount}) - ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_brush_fee_stat_monthly (company_id, shop_id, stat_month, brush_amount) - SELECT company_id, shop_id, #{statMonth}, SUM(brush_amount) - FROM ec_brush_fee_stat_daily - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND stat_date >= #{statMonth} - AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) - GROUP BY company_id, shop_id - ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_brush_fee_stat_yearly (company_id, shop_id, stat_year, brush_amount) - SELECT company_id, shop_id, #{statYear}, SUM(brush_amount) - FROM ec_brush_fee_stat_monthly - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND YEAR(stat_month) = #{statYear} - GROUP BY company_id, shop_id - ON DUPLICATE KEY UPDATE brush_amount = VALUES(brush_amount), update_time = CURRENT_TIMESTAMP - - - - - - diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml deleted file mode 100644 index 908a9523..00000000 --- a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatDailyMapper.xml +++ /dev/null @@ -1,272 +0,0 @@ - - - - - - INSERT INTO ec_order_stat_daily_shop ( - company_id, shop_id, platform_code, stat_date, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, - stat_version - ) VALUES ( - #{companyId}, #{shopId}, #{platformCode}, #{statDate}, - #{salesAmount}, #{salesOrderCount}, #{salesQuantitySum}, - #{gmvAmount}, #{gmvOrderCount}, #{gmvQuantitySum}, - #{refundAmount}, #{productCost}, #{freightCost}, #{otherCost}, - #{statVersion} - ) - ON DUPLICATE KEY UPDATE - platform_code = VALUES(platform_code), - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - DELETE FROM ec_order_stat_daily_product - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} - - - - INSERT INTO ec_order_stat_daily_product ( - company_id, shop_id, product_id, category_id, stat_date, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) VALUES - - (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, - #{r.salesAmount}, #{r.salesOrderCount}, #{r.salesQuantitySum}, - #{r.gmvAmount}, #{r.gmvOrderCount}, #{r.gmvQuantitySum}, - #{r.refundAmount}, #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) - - - - - DELETE FROM ec_order_stat_daily_spec - WHERE company_id = #{companyId} AND shop_id = #{shopId} AND stat_date = #{statDate} - - - - INSERT INTO ec_order_stat_daily_spec ( - company_id, shop_id, product_id, product_sku_id, stat_date, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) VALUES - - (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.productSkuId}, #{r.statDate}, - #{r.salesAmount}, #{r.salesOrderCount}, #{r.salesQuantitySum}, - #{r.gmvAmount}, #{r.gmvOrderCount}, #{r.gmvQuantitySum}, - #{r.refundAmount}, #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) - - - - - - INSERT INTO ec_order_stat_monthly_shop ( - company_id, shop_id, platform_code, stat_month, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, MAX(platform_code), - #{statMonth}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_daily_shop - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND stat_date >= #{statMonth} - AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) - GROUP BY company_id, shop_id - ON DUPLICATE KEY UPDATE - platform_code = VALUES(platform_code), - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_order_stat_yearly_shop ( - company_id, shop_id, platform_code, stat_year, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, MAX(platform_code), - #{statYear}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_monthly_shop - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND YEAR(stat_month) = #{statYear} - GROUP BY company_id, shop_id - ON DUPLICATE KEY UPDATE - platform_code = VALUES(platform_code), - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_order_stat_monthly_product ( - company_id, shop_id, product_id, category_id, stat_month, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, product_id, category_id, - #{statMonth}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_daily_product - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND stat_date >= #{statMonth} - AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) - GROUP BY company_id, shop_id, product_id, category_id - ON DUPLICATE KEY UPDATE - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_order_stat_yearly_product ( - company_id, shop_id, product_id, category_id, stat_year, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, product_id, category_id, - #{statYear}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_monthly_product - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND YEAR(stat_month) = #{statYear} - GROUP BY company_id, shop_id, product_id, category_id - ON DUPLICATE KEY UPDATE - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_order_stat_monthly_spec ( - company_id, shop_id, product_id, product_sku_id, stat_month, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, product_id, product_sku_id, - #{statMonth}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_daily_spec - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND stat_date >= #{statMonth} - AND stat_date < DATE_ADD(#{statMonth}, INTERVAL 1 MONTH) - GROUP BY company_id, shop_id, product_id, product_sku_id - ON DUPLICATE KEY UPDATE - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - - - INSERT INTO ec_order_stat_yearly_spec ( - company_id, shop_id, product_id, product_sku_id, stat_year, - sales_amount, sales_order_count, sales_quantity_sum, - gmv_amount, gmv_order_count, gmv_quantity_sum, - refund_amount, product_cost, freight_cost, other_cost, stat_version - ) - SELECT company_id, shop_id, product_id, product_sku_id, - #{statYear}, - SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum), - SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum), - SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost), - MAX(stat_version) - FROM ec_order_stat_monthly_spec - WHERE company_id = #{companyId} AND shop_id = #{shopId} - AND YEAR(stat_month) = #{statYear} - GROUP BY company_id, shop_id, product_id, product_sku_id - ON DUPLICATE KEY UPDATE - sales_amount = VALUES(sales_amount), - sales_order_count = VALUES(sales_order_count), - sales_quantity_sum = VALUES(sales_quantity_sum), - gmv_amount = VALUES(gmv_amount), - gmv_order_count = VALUES(gmv_order_count), - gmv_quantity_sum = VALUES(gmv_quantity_sum), - refund_amount = VALUES(refund_amount), - product_cost = VALUES(product_cost), - freight_cost = VALUES(freight_cost), - other_cost = VALUES(other_cost), - stat_version = VALUES(stat_version), - update_time = CURRENT_TIMESTAMP - - diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml deleted file mode 100644 index 93465728..00000000 --- a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatQueryMapper.xml +++ /dev/null @@ -1,245 +0,0 @@ - - - - - - company_id = #{companyId} - AND shop_id IN - #{sid} - - - - COALESCE(SUM(sales_amount), 0) AS salesAmount, - COALESCE(SUM(refund_amount), 0) AS refundAmount, - COALESCE(SUM(sales_order_count), 0) AS salesOrderCount, - COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum, - COALESCE(SUM(gmv_amount), 0) AS gmvAmount, - COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount, - COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum - - - - COALESCE(SUM(sales_amount), 0) AS salesAmount, - COALESCE(SUM(refund_amount), 0) AS refundAmount, - COALESCE(SUM(sales_order_count), 0) AS salesOrderCount, - COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum, - COALESCE(SUM(gmv_amount), 0) AS gmvAmount, - COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount, - COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum, - COALESCE(SUM(product_cost), 0) AS productCost, - COALESCE(SUM(freight_cost), 0) AS freightCost, - COALESCE(SUM(other_cost), 0) AS otherCost - - - - COALESCE(SUM(sales_amount), 0) AS salesAmount, - COALESCE(SUM(refund_amount), 0) AS refundAmount, - COALESCE(SUM(sales_order_count), 0) AS salesOrderCount, - COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum, - COALESCE(SUM(gmv_amount), 0) AS gmvAmount, - COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount, - COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum, - COALESCE(SUM(product_cost), 0) AS productCost, - COALESCE(SUM(freight_cost), 0) AS freightCost, - COALESCE(SUM(other_cost), 0) AS otherCost - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml b/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml deleted file mode 100644 index 3ac3f98b..00000000 --- a/ecom-dmb-backend/src/main/resources/mapper/order/stat/OrderStatRefreshMapper.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - IFNULL(NULLIF(i.quantity, 0), 1) - IFNULL(NULLIF(i.line_amount, 0), IFNULL(i.unit_price, 0) * ) - - - INSERT IGNORE INTO ec_order_stat_refresh_queue ( - company_id, shop_id, stat_date, source, status, retry_count - ) VALUES ( - #{companyId}, #{shopId}, #{statDate}, #{source}, 'pending', 0 - ) - - - - UPDATE ec_order_stat_refresh_queue SET status = 'done', update_time = CURRENT_TIMESTAMP - WHERE id = #{id} - - - - UPDATE ec_order_stat_refresh_queue - SET status = 'failed', retry_count = #{retryCount}, update_time = CURRENT_TIMESTAMP - WHERE id = #{id} - - - - - -