feat(订单统计): 落地读模型汇总表与 refresh 写入链路,工作台/概览/导出切读 daily 汇总并补充 Admin rebuild 与对账

This commit is contained in:
小蟑螂
2026-06-01 15:45:31 +08:00
parent e1d90ccba3
commit b19f6d60f9
58 changed files with 5332 additions and 131 deletions
@@ -5,9 +5,11 @@ import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableAsync
@EnableScheduling
@MapperScan(
basePackages = "top.xyquan.ecomdmbbackend.modules",
annotationClass = Mapper.class
@@ -20,6 +20,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
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.ProductSpecService;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
@@ -38,13 +39,16 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
private final ShopService shopService;
private final ProductService productService;
private final ProductSpecService productSpecService;
private final FeeStatCrudCoordinator feeStatCrudCoordinator;
public BrushOrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService) {
ProductService productService, ProductSpecService productSpecService,
FeeStatCrudCoordinator feeStatCrudCoordinator) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
this.feeStatCrudCoordinator = feeStatCrudCoordinator;
}
/**
@@ -96,6 +100,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
// 保存刷单记录
this.save(brushOrder);
feeStatCrudCoordinator.afterBrushOrderSaved(null, brushOrder);
// 转换为VO并返回
return convertToVO(brushOrder);
@@ -144,6 +149,8 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
}
// 更新刷单记录
BrushOrderPO before = new BrushOrderPO();
BeanUtils.copyProperties(existingBrushOrder, before);
existingBrushOrder.setShopId(updateBrushOrderDTO.getShopId());
existingBrushOrder.setProductId(updateBrushOrderDTO.getProductId());
existingBrushOrder.setProductSpecId(updateBrushOrderDTO.getProductSpecId());
@@ -157,6 +164,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
// 保存更新
this.updateById(existingBrushOrder);
feeStatCrudCoordinator.afterBrushOrderSaved(before, existingBrushOrder);
// 转换为VO并返回
return convertToVO(existingBrushOrder);
@@ -180,6 +188,7 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
}
// 硬删除刷单记录
feeStatCrudCoordinator.afterBrushOrderDeleted(existingBrushOrder);
this.removeById(id);
}
@@ -6,6 +6,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSpecPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@@ -192,6 +195,11 @@ public class ImportRuntimeContext {
// 进度回调(主线程设置,workers 调用,线程安全包装)
transient volatile BiConsumer<Integer, Integer> progressCallback;
/** 本任务涉及、需 refresh 汇总表的自然日(order_time → Asia/Shanghai DATE) */
private final Set<LocalDate> dirtyStatDates = ConcurrentHashMap.newKeySet();
private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai");
/** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */
private transient Map<String, MappingField> orderImportFieldMapping;
@@ -243,6 +251,33 @@ public class ImportRuntimeContext {
public Set<String> getPendingRelationKeys() { return pendingRelationKeys; }
public Set<String> getPendingPlatformOrderNos() { return pendingPlatformOrderNos; }
public Set<LocalDate> 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<String> target, String rawValue) {
@@ -3,6 +3,8 @@ package top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.impl;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.model.po.ImportTaskPO;
@@ -11,6 +13,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskProce
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskService;
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
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.order.service.OrderService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
@@ -33,8 +38,13 @@ 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;
/**
@@ -43,6 +53,8 @@ import java.util.stream.Collectors;
@Service
public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorService {
private static final Logger log = LoggerFactory.getLogger(ImportTaskProcessorServiceImpl.class);
private final ImportTaskService importTaskService;
private final ProductSpecService productSpecService;
private final OrderMapper orderMapper;
@@ -60,6 +72,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
private final OrderImportProcessor orderImportProcessor;
private final ProductSpecImportHelper productSpecImportHelper;
private final PromotionFeeImportProcessor promotionFeeImportProcessor;
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
private final FeeStatRefreshService feeStatRefreshService;
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
OrderService orderService,
@@ -75,7 +89,9 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
SqlSessionFactory sqlSessionFactory,
OssService ossService,
SysFileService sysFileService,
PromotionFeeImportProcessor promotionFeeImportProcessor) {
PromotionFeeImportProcessor promotionFeeImportProcessor,
OrderStatRefreshCoordinator orderStatRefreshCoordinator,
FeeStatRefreshService feeStatRefreshService) {
this.importTaskService = importTaskService;
this.productSpecService = productSpecService;
this.orderMapper = orderMapper;
@@ -89,6 +105,8 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
this.ossService = ossService;
this.sysFileService = sysFileService;
this.promotionFeeImportProcessor = promotionFeeImportProcessor;
this.orderStatRefreshCoordinator = orderStatRefreshCoordinator;
this.feeStatRefreshService = feeStatRefreshService;
// 初始化 helper 和 processor
this.productSpecImportHelper = new ProductSpecImportHelper(
@@ -216,11 +234,42 @@ 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<LocalDate> dates = new HashSet<>(context.getDirtyStatDates());
try {
List<LocalDate> 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 {
@@ -285,12 +334,28 @@ 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()) {
@@ -1080,6 +1080,13 @@ public class OrderImportProcessor {
r.rowNumber, r.platformOrderNo, r.order,
r.order.getId(), updateMsg,
r.dto != null && Boolean.TRUE.equals(r.dto.getOrderTimeEmptyInInput()));
if (r.order != null && r.order.getOrderTime() != null) {
context.markOrderStatDirty(r.order.getShopId(), r.order.getOrderTime());
}
if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) {
OrderPO snap = context.existingOrderSnapshotByPlatformNo.get(r.platformOrderNo.trim());
context.markOrderStatDirtyFromSnapshot(snap);
}
context.pendingOrders.add(pending);
if (r.platformOrderNo != null && !r.platformOrderNo.trim().isEmpty()) {
synchronized (context.pendingOrderByPlatformNo) {
@@ -1612,6 +1619,11 @@ public class OrderImportProcessor {
if (existing != null) {
existing.updateData(newOrderPO, existingId, newUpdateMsg, newRowNumber,
newOrderTimeEmptyInInput);
if (newOrderPO != null && newOrderPO.getOrderTime() != null) {
context.markOrderStatDirty(newOrderPO.getShopId(), newOrderPO.getOrderTime());
}
OrderPO snap = context.existingOrderSnapshotByPlatformNo.get(normalized);
context.markOrderStatDirtyFromSnapshot(snap);
}
}
return true;
@@ -4,10 +4,15 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
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;
/**
* 订单Mapper接口
@@ -43,4 +48,40 @@ public interface OrderMapper extends BaseMapper<OrderPO> {
int linkOrdersBySpecCodeWhenSpecIdNull(@Param("companyId") Long companyId,
@Param("specCode") String specCode,
@Param("productSpecId") Long productSpecId);
/** 导入任务完成后兜底:该任务写入订单涉及的自然日 */
@Select("SELECT DISTINCT DATE(order_time) FROM ec_order WHERE import_task_id = #{importTaskId}")
List<LocalDate> 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<LocalDate> selectDistinctOrderDatesByCompanyShopRange(
@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
/** 公司订单日期范围(rebuild 用) */
@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 shop_id AS shopId, DATE(order_time) AS statDate FROM ec_order
WHERE company_id = #{companyId} AND spec_code = #{specCode} AND product_spec_id IS NULL
GROUP BY shop_id, DATE(order_time)
""")
List<OrderShopStatDateRow> selectOrphanOrderStatDatesBySpecCode(
@Param("companyId") Long companyId,
@Param("specCode") String specCode);
}
@@ -32,12 +32,17 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusSe
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.ProductSpecService;
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.utils.CurrentUserContext;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -51,15 +56,18 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
private final ProductService productService;
private final ProductSpecService productSpecService;
private final OrderStatusService orderStatusService;
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
ProductService productService, ProductSpecService productSpecService,
OrderStatusService orderStatusService) {
OrderStatusService orderStatusService,
OrderStatCrudCoordinator orderStatCrudCoordinator) {
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.productService = productService;
this.productSpecService = productSpecService;
this.orderStatusService = orderStatusService;
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
}
/**
@@ -131,6 +139,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
// 保存订单
this.save(order);
orderStatCrudCoordinator.afterOrderSaved(null, order);
// 转换为VO并返回
return convertToVO(order);
@@ -236,8 +245,11 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
// 更新订单
this.updateById(order);
OrderPO after = this.getById(id);
orderStatCrudCoordinator.afterOrderSaved(existingOrder, after);
// 转换为VO并返回
return convertToVO(order);
return convertToVO(after != null ? after : order);
}
/**
@@ -257,6 +269,7 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
}
// 硬删除订单(外键约束会自动处理相关数据)
orderStatCrudCoordinator.afterOrderDeleted(existingOrder);
this.removeById(id);
}
@@ -283,10 +296,12 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
LambdaQueryWrapper<OrderPO> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OrderPO::getCompanyId, companyId)
.in(OrderPO::getId, uniqueIds);
long matched = this.count(wrapper);
List<OrderPO> toRemove = this.list(wrapper);
long matched = toRemove.size();
if (matched != uniqueIds.size()) {
throw new BusinessException("存在无效订单或无权删除的订单");
}
orderStatCrudCoordinator.afterOrdersDeletedBatch(toRemove);
this.remove(wrapper);
}
@@ -485,7 +500,26 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
public int syncCostsToOrders(Long specId, java.math.BigDecimal productCost,
java.math.BigDecimal shippingCost, java.math.BigDecimal otherCost,
java.time.LocalDateTime startTime, java.time.LocalDateTime endTime) {
return baseMapper.updateCostFields(productCost, shippingCost, otherCost, specId, startTime, endTime);
ProductSpecPO spec = productSpecService.getById(specId);
int n = baseMapper.updateCostFields(productCost, shippingCost, otherCost, specId, startTime, endTime);
if (n > 0 && spec != null && spec.getCompanyId() != null) {
List<OrderPO> affected = list(new LambdaQueryWrapper<OrderPO>()
.eq(OrderPO::getCompanyId, spec.getCompanyId())
.eq(OrderPO::getProductSpecId, specId)
.ge(OrderPO::getOrderTime, startTime)
.le(OrderPO::getOrderTime, endTime)
.select(OrderPO::getCompanyId, OrderPO::getShopId, OrderPO::getOrderTime));
Set<StatDirtyKey> keys = new HashSet<>();
ZoneId zone = ZoneId.of("Asia/Shanghai");
for (OrderPO o : affected) {
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;
}
@Override
@@ -0,0 +1,46 @@
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;
}
}
@@ -0,0 +1,61 @@
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<Long> 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<OrderStatRebuildTaskPO> 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<OrderStatReconcileService.ReconcileReport> 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);
}
}
@@ -0,0 +1,64 @@
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<CompanyPO> 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);
}
}
@@ -0,0 +1,64 @@
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<PromotionFeeStatDailyPO> {
void deletePromotionDaily(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertPromotionDaily(@Param("list") List<PromotionFeeStatDailyPO> 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<PromotionFeeAggRow> 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;
}
}
@@ -0,0 +1,55 @@
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<OrderStatDailyShopPO> {
void upsertDailyShop(OrderStatDailyShopPO row);
void deleteDailyProduct(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertDailyProduct(@Param("list") List<OrderStatDailyProductPO> list);
void deleteDailySpec(@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("statDate") LocalDate statDate);
void batchInsertDailySpec(@Param("list") List<OrderStatDailySpecPO> 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);
}
@@ -0,0 +1,98 @@
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<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyShopByDay(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyShopByShop(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByShopProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
OrderStatMetricsDTO sumDailyProductForOneProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumDailyProductByDayForOneProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumMonthlyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumMonthlyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumYearlyProductByCategory(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
List<OrderStatMetricsDTO> sumYearlyProductByProduct(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
List<OrderStatMetricsDTO> sumDailySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
List<OrderStatMetricsDTO> sumMonthlySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startMonth") LocalDate startMonth,
@Param("endMonth") LocalDate endMonth);
List<OrderStatMetricsDTO> sumYearlySpecBySpec(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("productId") Long productId,
@Param("startYear") int startYear,
@Param("endYear") int endYear);
int countDailyShopRows(@Param("companyId") Long companyId,
@Param("shopIds") List<Long> shopIds,
@Param("startDate") LocalDate startDate,
@Param("endDate") LocalDate endDate);
}
@@ -0,0 +1,9 @@
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<OrderStatRebuildTaskPO> {
}
@@ -0,0 +1,60 @@
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<OrderStatRefreshQueuePO> {
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<SpecDayRow> aggregateSpecByShopDay(
@Param("companyId") Long companyId,
@Param("shopId") Long shopId,
@Param("start") LocalDateTime start,
@Param("end") LocalDateTime end,
@Param("unionStatusIds") List<Long> unionStatusIds,
@Param("salesStatusIds") List<Long> salesStatusIds,
@Param("refundStatusIds") List<Long> refundStatusIds,
@Param("productCostStatusIds") List<Long> productCostStatusIds,
@Param("freightCostStatusIds") List<Long> freightCostStatusIds,
@Param("otherCostStatusIds") List<Long> otherCostStatusIds);
@Data
class SpecDayRow {
private Long productId;
private Long productSpecId;
private BigDecimal salesAmount;
private Long orderCount;
private BigDecimal refundAmount;
private Integer quantitySum;
private BigDecimal productCost;
private BigDecimal freightCost;
private BigDecimal otherCost;
}
}
@@ -0,0 +1,12 @@
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;
}
@@ -0,0 +1,39 @@
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 Long platformId;
private Long productId;
private Long categoryId;
private Long productSpecId;
private BigDecimal salesAmount = BigDecimal.ZERO;
private BigDecimal refundAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 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;
private Integer quantitySum = 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;
}
}
@@ -0,0 +1,27 @@
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;
}
@@ -0,0 +1,24 @@
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;
}
@@ -0,0 +1,62 @@
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("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;
}
@@ -0,0 +1,65 @@
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_id")
private Long platformId;
@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("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("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;
}
@@ -0,0 +1,65 @@
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_spec_id")
private Long productSpecId;
@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("quantity_sum")
private Integer quantitySum;
@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;
}
@@ -0,0 +1,49 @@
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;
}
@@ -0,0 +1,43 @@
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;
}
@@ -0,0 +1,44 @@
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;
}
@@ -0,0 +1,102 @@
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<ShopDay> keys = new HashSet<>();
addPromotionKey(keys, before);
addPromotionKey(keys, after);
runAfterCommit(keys);
}
public void afterPromotionFeeDeleted(PromotionFeePO before) {
Set<ShopDay> keys = new HashSet<>();
addPromotionKey(keys, before);
runAfterCommit(keys);
}
public void afterBrushOrderSaved(BrushOrderPO before, BrushOrderPO after) {
Set<ShopDay> keys = new HashSet<>();
addBrushKey(keys, before);
addBrushKey(keys, after);
runAfterCommit(keys);
}
public void afterBrushOrderDeleted(BrushOrderPO before) {
Set<ShopDay> keys = new HashSet<>();
addBrushKey(keys, before);
runAfterCommit(keys);
}
private void runAfterCommit(Set<ShopDay> 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<ShopDay> 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<ShopDay> 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) {}
}
@@ -0,0 +1,69 @@
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<FeeStatDailyMapper.PromotionFeeAggRow> rows =
feeStatDailyMapper.aggregatePromotionByShopDay(companyId, shopId, statDate);
if (rows == null || rows.isEmpty()) {
return;
}
List<PromotionFeeStatDailyPO> 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);
}
}
@@ -0,0 +1,91 @@
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.stereotype.Service;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
import java.time.LocalDate;
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 RedisTemplate<String, Object> redisTemplate;
public OrderStatCacheService(OrderStatProperties properties,
RedisTemplate<String, Object> 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) {
return;
}
try {
redisTemplate.opsForValue().set(KEY_PREFIX + cacheKey, value, ttlSeconds, TimeUnit.SECONDS);
} catch (Exception e) {
log.debug("order-stat cache put skip: {}", cacheKey, e);
}
}
@SuppressWarnings("unchecked")
public <T> T get(String cacheKey, Class<T> 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;
}
}
@@ -0,0 +1,128 @@
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<StatDirtyKey> keys = new HashSet<>();
addKey(keys, before);
addKey(keys, after);
runAfterCommit(keys, true);
}
/** 单条删除后 */
public void afterOrderDeleted(OrderPO before) {
Set<StatDirtyKey> keys = new HashSet<>();
addKey(keys, before);
runAfterCommit(keys, true);
}
/** 批量删除:异步入队(避免一次 refresh 过多) */
public void afterOrdersDeletedBatch(List<OrderPO> removed) {
if (removed == null || removed.isEmpty()) {
return;
}
Set<StatDirtyKey> keys = new HashSet<>();
for (OrderPO o : removed) {
addKey(keys, o);
}
runAfterCommit(keys, false);
}
/** 规格补链等批量影响:异步入队 */
public void enqueueDirtyKeys(Collection<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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<StatDirtyKey> 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));
}
}
@@ -0,0 +1,195 @@
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<ShopPO> shops,
LocalDate startDate, LocalDate endDate,
BigDecimal taxRate, OrderStatusStatSets stat) {
List<Long> 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<OrderStatAggMapper.PromotionRow> promoRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.BrushRow> 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<OrderStatAggMapper.ShopProductRow> 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<CompanyOverviewVO.ShopSalesRatio> buildShopSalesRatios(Long companyId, List<Long> shopIds,
List<ShopPO> shops,
LocalDate start, LocalDate end,
BigDecimal totalSales) {
List<OrderStatMetricsDTO> byShop = orderStatReadFacade.sumShopMetricsByShop(companyId, shopIds, start, end);
Map<Long, BigDecimal> salesMap = new HashMap<>();
for (OrderStatMetricsDTO m : byShop) {
if (m.getShopId() != null) {
salesMap.put(m.getShopId(), nz(m.getSalesAmount()));
}
}
List<CompanyOverviewVO.ShopSalesRatio> 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<Long> shopIds,
LocalDate start, LocalDate end) {
List<OrderStatMetricsDTO> daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end);
Map<LocalDate, BigDecimal> 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<Long> shopIds,
LocalDate start, LocalDate end) {
List<OrderStatMetricsDTO> daily = orderStatReadFacade.sumShopMetricsByDay(companyId, shopIds, start, end);
Map<LocalDate, BigDecimal> 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<LocalDate, BigDecimal> map) {
List<CompanyOverviewVO.TrendDataItem> 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<CompanyOverviewVO.ShopEfficiencyQuadrant> buildShopEfficiency(
CompanyOverviewVO.ShopOverview shopOverview) {
if (shopOverview == null || shopOverview.getShops() == null) {
return List.of();
}
List<CompanyOverviewVO.ShopEfficiencyQuadrant> 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;
}
}
@@ -0,0 +1,192 @@
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<Long> 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<OrderStatMetricsDTO> sumShopMetricsByDay(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
requireDailySource();
ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByDay(companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumShopMetricsByShop(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
requireDailySource();
ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByShop(companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumProductMetricsByCategory(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumProductMetricsByProduct(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumSpecMetricsBySpec(Long companyId, List<Long> 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(不阻塞读路径)。
* <p>
* 若区间内无 ec_order 明细(如同比去年、未来日期),空汇总结果是正确口径,不应打日志或入队。
*/
public void ensureStatReady(Long companyId, List<Long> 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<LocalDate> 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<OrderStatMetricsDTO> nullSafe(List<OrderStatMetricsDTO> 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
}
}
@@ -0,0 +1,322 @@
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.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 ShopService shopService;
public OrderStatReadFacade(OrderStatProperties properties,
OrderStatQueryService orderStatQueryService,
OrderStatQueryMapper orderStatQueryMapper,
OrderStatAggMapper orderStatAggMapper,
ShopService shopService) {
this.properties = properties;
this.orderStatQueryService = orderStatQueryService;
this.orderStatQueryMapper = orderStatQueryMapper;
this.orderStatAggMapper = orderStatAggMapper;
this.shopService = shopService;
}
public boolean usesDailyStatSource() {
return "daily".equalsIgnoreCase(properties.getStatSource());
}
/** 工作台/概览共用:shop×product 聚合行 */
public List<OrderStatAggMapper.ShopProductRow> loadShopProductRows(Long companyId, List<Long> 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<Long, Long> platformByShop = platformByShop(shopIds);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyProductByShopProduct(
companyId, shopIds, startDate, endDate);
if (rows == null || rows.isEmpty()) {
return Collections.emptyList();
}
List<OrderStatAggMapper.ShopProductRow> out = new ArrayList<>(rows.size());
for (OrderStatMetricsDTO m : rows) {
OrderStatAggMapper.ShopProductRow r = new OrderStatAggMapper.ShopProductRow();
r.setShopId(m.getShopId());
r.setPlatformId(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.setProductCost(m.getProductCost());
r.setFreightCost(m.getFreightCost());
r.setOtherCost(m.getOtherCost());
r.setGmvAllStatus(BigDecimal.ZERO);
out.add(r);
}
return out;
}
public List<OrderStatAggMapper.DailyRow> loadDailyRows(Long companyId, List<Long> 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<OrderStatMetricsDTO> rows = orderStatQueryService.sumShopMetricsByDay(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.DailyRow> 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<Long> 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<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
OrderStatusStatSets stat = OrderStatusStatSets.from(List.of());
List<OrderStatAggMapper.ShopProductRow> rows = loadShopProductRows(companyId, shopIds, startDate, endDate, stat);
OrderStatMetricsDTO dto = new OrderStatMetricsDTO();
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO;
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
int cnt = 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()));
cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0;
}
dto.setSalesAmount(sales);
dto.setRefundAmount(refund);
dto.setSalesOrderCount(cnt);
dto.setProductCost(pc);
dto.setFreightCost(fc);
dto.setOtherCost(oc);
return dto;
}
return orderStatQueryService.sumShopMetrics(companyId, shopIds, startDate, endDate);
}
public List<OrderStatMetricsDTO> sumShopMetricsByDay(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
return orderStatQueryService.sumShopMetricsByDay(companyId, shopIds, startDate, endDate);
}
public List<OrderStatMetricsDTO> sumShopMetricsByShop(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyShopByShop(
companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public OrderStatMetricsDTO sumProductForOne(Long companyId, List<Long> 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<OrderStatMetricsDTO> sumProductByDayForOne(Long companyId, List<Long> shopIds, Long productId,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
orderStatQueryService.ensureStatReady(companyId, shopIds, startDate, endDate);
List<OrderStatMetricsDTO> rows = orderStatQueryMapper.sumDailyProductByDayForOneProduct(
companyId, shopIds, productId, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatMetricsDTO> sumSpecMetrics(Long companyId, List<Long> shopIds, Long productId,
LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) {
return Collections.emptyList();
}
return orderStatQueryService.sumSpecMetricsBySpec(companyId, shopIds, productId, startDate, endDate);
}
/** 推广/刷单仍走明细表 SQL(数据量小) */
public List<OrderStatAggMapper.PromotionRow> loadPromotionRows(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) {
List<OrderStatAggMapper.PromotionRow> rows = orderStatAggMapper.aggregatePromotionFees(
companyId, shopIds, startDate, endDate);
return rows != null ? rows : Collections.emptyList();
}
public List<OrderStatAggMapper.BrushRow> loadBrushRows(Long companyId, List<Long> shopIds,
LocalDateTime start, LocalDateTime end) {
List<OrderStatAggMapper.BrushRow> rows = orderStatAggMapper.aggregateBrushFees(
companyId, shopIds, start, end);
return rows != null ? rows : Collections.emptyList();
}
public OrderStatAggMapper.FeeKpiRow loadPromotionPeriodKpi(Long companyId, List<Long> 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<Long> 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<Long, Long> platformByShop(List<Long> shopIds) {
if (shopIds == null || shopIds.isEmpty()) {
return Map.of();
}
return shopService.listByIds(shopIds).stream()
.collect(Collectors.toMap(ShopPO::getId, s -> s.getPlatformId() != null ? s.getPlatformId() : 0L, (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;
}
}
@@ -0,0 +1,114 @@
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<OrderStatRebuildTaskMapper, OrderStatRebuildTaskPO> {
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<Long> 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<LocalDate> 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<Long> resolveShopIds(Long companyId, Long shopId) {
if (shopId != null) {
return List.of(shopId);
}
return shopService.list(new LambdaQueryWrapper<ShopPO>().eq(ShopPO::getCompanyId, companyId))
.stream().map(ShopPO::getId).toList();
}
}
@@ -0,0 +1,177 @@
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.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<ShopPO> shops = shopService.lambdaQuery().eq(ShopPO::getCompanyId, companyId).list();
if (shops.isEmpty()) {
report.setMessage("无店铺");
return report;
}
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<SampleKey> 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<OrderStatAggMapper.ShopProductRow> rows = orderStatAggMapper.aggregateByShopProduct(
companyId, List.of(shopId), d.atStartOfDay(), d.atTime(23, 59, 59),
stat.getUnionStatusIds(), list(stat.getSalesIds()), list(stat.getRefundIds()),
list(stat.getProductCostIds()), list(stat.getFreightCostIds()), list(stat.getOtherCostIds()));
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<SampleKey> pickSamples(Long companyId, List<ShopPO> shops,
LocalDate start, LocalDate end, int sampleSize) {
List<SampleKey> pool = new ArrayList<>();
for (ShopPO shop : shops) {
List<LocalDate> 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 List<Long> list(java.util.Set<Long> ids) {
return ids == null ? List.of() : new ArrayList<>(ids);
}
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<ReconcileItem> 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<ReconcileItem> getItems() { return items; }
public void setItems(List<ReconcileItem> 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; }
}
}
@@ -0,0 +1,97 @@
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<OrderStatRefreshMapper, OrderStatRefreshQueuePO> {
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<LocalDate> statDates, RefreshSource source) {
if (companyId == null || shopId == null || statDates == null || statDates.isEmpty()) {
return 0;
}
Set<LocalDate> 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<StatDirtyKey> 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<OrderStatRefreshQueuePO> 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);
}
}
}
}
@@ -0,0 +1,233 @@
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<Long> shopIds = List.of(shopId);
List<OrderStatAggMapper.ShopProductRow> 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));
Long platformId = resolvePlatformId(shopId);
Integer gmvOrderCount = orderStatRefreshMapper.countGmvOrdersByShopDay(
companyId, shopId, start, end);
OrderStatDailyShopPO shopRow = buildShopRow(companyId, shopId, platformId, statDate, productRows,
gmvOrderCount != null ? gmvOrderCount : 0);
orderStatDailyMapper.upsertDailyShop(shopRow);
orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate);
List<OrderStatDailyProductPO> dailyProducts = buildProductRows(companyId, shopId, statDate, productRows);
if (!dailyProducts.isEmpty()) {
orderStatDailyMapper.batchInsertDailyProduct(dailyProducts);
}
orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate);
List<OrderStatRefreshMapper.SpecDayRow> specRows = 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<OrderStatDailySpecPO> dailySpecs = buildSpecRows(companyId, shopId, statDate, specRows);
if (!dailySpecs.isEmpty()) {
orderStatDailyMapper.batchInsertDailySpec(dailySpecs);
}
orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate);
}
private Long resolvePlatformId(Long shopId) {
ShopPO shop = shopMapper.selectById(shopId);
return shop != null ? shop.getPlatformId() : null;
}
private void writeEmptyShopDay(Long companyId, Long shopId, LocalDate statDate) {
OrderStatDailyShopPO row = new OrderStatDailyShopPO();
row.setCompanyId(companyId);
row.setShopId(shopId);
row.setPlatformId(resolvePlatformId(shopId));
row.setStatDate(statDate);
row.setSalesAmount(BigDecimal.ZERO);
row.setRefundAmount(BigDecimal.ZERO);
row.setSalesOrderCount(0);
row.setProductCost(BigDecimal.ZERO);
row.setFreightCost(BigDecimal.ZERO);
row.setOtherCost(BigDecimal.ZERO);
row.setGmvAmount(BigDecimal.ZERO);
row.setGmvOrderCount(0);
row.setStatVersion(0);
orderStatDailyMapper.upsertDailyShop(row);
}
private static OrderStatDailyShopPO buildShopRow(Long companyId, Long shopId, Long platformId,
LocalDate statDate,
List<OrderStatAggMapper.ShopProductRow> 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;
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;
}
OrderStatDailyShopPO row = new OrderStatDailyShopPO();
row.setCompanyId(companyId);
row.setShopId(shopId);
row.setPlatformId(platformId);
row.setStatDate(statDate);
row.setSalesAmount(sales);
row.setRefundAmount(refund);
row.setSalesOrderCount(orderCount);
row.setProductCost(pc);
row.setFreightCost(fc);
row.setOtherCost(oc);
row.setGmvAmount(gmv);
row.setGmvOrderCount(gmvOrderCount);
row.setStatVersion(0);
return row;
}
private static List<OrderStatDailyProductPO> buildProductRows(Long companyId, Long shopId, LocalDate statDate,
List<OrderStatAggMapper.ShopProductRow> rows) {
List<OrderStatDailyProductPO> 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.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<OrderStatDailySpecPO> buildSpecRows(Long companyId, Long shopId, LocalDate statDate,
List<OrderStatRefreshMapper.SpecDayRow> rows) {
List<OrderStatDailySpecPO> 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.setProductSpecId(r.getProductSpecId() != null ? r.getProductSpecId() : 0L);
s.setStatDate(statDate);
s.setSalesAmount(nz(r.getSalesAmount()));
s.setRefundAmount(nz(r.getRefundAmount()));
s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0);
s.setQuantitySum(r.getQuantitySum() != null ? r.getQuantitySum() : 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
&& (r.getOrderCount() == null || r.getOrderCount() == 0);
}
private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) {
return nz(r.getSalesAmount()).signum() == 0
&& nz(r.getRefundAmount()).signum() == 0
&& (r.getOrderCount() == null || r.getOrderCount() == 0);
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
}
@@ -0,0 +1,91 @@
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;
}
}
}
}
}
@@ -0,0 +1,30 @@
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);
}
}
@@ -0,0 +1,48 @@
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;
import java.util.Set;
/** 将 OrderStatusStatSets 转为 MyBatis IN 列表参数。 */
public final class OrderStatParamHelper {
private OrderStatParamHelper() {
}
public static List<Long> statusList(java.util.Collection<Long> ids) {
if (ids == null || ids.isEmpty()) {
return List.of(-1L);
}
List<Long> list = new ArrayList<>(ids);
Collections.sort(list);
return list;
}
public static List<Long> unionList(OrderStatusStatSets stat) {
return statusList(stat.getUnionStatusIds());
}
public static List<Long> salesList(OrderStatusStatSets stat) {
return statusList(stat.getSalesIds());
}
public static List<Long> refundList(OrderStatusStatSets stat) {
return statusList(stat.getRefundIds());
}
public static List<Long> productCostList(OrderStatusStatSets stat) {
return statusList(stat.getProductCostIds());
}
public static List<Long> freightCostList(OrderStatusStatSets stat) {
return statusList(stat.getFreightCostIds());
}
public static List<Long> otherCostList(OrderStatusStatSets stat) {
return statusList(stat.getOtherCostIds());
}
}
@@ -0,0 +1,13 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support;
/**
* 汇总 refresh 触发来源。
*/
public enum RefreshSource {
IMPORT,
CRUD,
STATUS_CHANGE,
MANUAL,
BACKFILL,
AUTO_MISS
}
@@ -0,0 +1,16 @@
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");
}
}
@@ -3,9 +3,12 @@ package top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.mapper.OrderStatusMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.CreateOrderStatusDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.dto.PatchOrderStatusDTO;
@@ -15,7 +18,9 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.vo.OrderStatusV
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
@@ -25,9 +30,15 @@ import java.util.stream.Collectors;
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusPO> implements OrderStatusService {
private final CurrentUserContext currentUserContext;
private final OrderStatRebuildService orderStatRebuildService;
private final OrderMapper orderMapper;
public OrderStatusServiceImpl(CurrentUserContext currentUserContext) {
public OrderStatusServiceImpl(CurrentUserContext currentUserContext,
@Lazy OrderStatRebuildService orderStatRebuildService,
OrderMapper orderMapper) {
this.currentUserContext = currentUserContext;
this.orderStatRebuildService = orderStatRebuildService;
this.orderMapper = orderMapper;
}
/**
@@ -99,6 +110,9 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
throw new BusinessException("状态名称已存在");
}
// 更新前快照五维开关,用于检测是否需全公司 rebuild
OrderStatusPO beforeStat = snapshotStatDimensions(existingStatus);
// 更新订单状态
OrderStatusPO orderStatus = new OrderStatusPO();
BeanUtils.copyProperties(updateOrderStatusDTO, orderStatus);
@@ -111,6 +125,8 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
// 更新订单状态
this.updateById(orderStatus);
maybeScheduleCompanyRebuild(companyId, beforeStat, snapshotStatDimensions(orderStatus));
// 转换为VO并返回
return convertToVO(orderStatus);
}
@@ -133,6 +149,8 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
throw new BusinessException("订单状态不存在");
}
OrderStatusPO beforeStat = snapshotStatDimensions(existingStatus);
if (patchDTO.getIncludeSalesAmount() != null) {
existingStatus.setIncludeSalesAmount(patchDTO.getIncludeSalesAmount());
}
@@ -151,6 +169,7 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
existingStatus.setUpdateBy(currentUserContext.getCurrentUserId());
this.updateById(existingStatus);
maybeScheduleCompanyRebuild(companyId, beforeStat, snapshotStatDimensions(existingStatus));
return convertToVO(existingStatus);
}
@@ -174,6 +193,9 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
// 检查是否有订单使用此状态
// TODO: 这里可以添加检查逻辑,如果有订单使用此状态,可以阻止删除或提示
// 删除后统计口径集合变化,需全公司 rebuild
scheduleCompanyRebuild(companyId);
// 删除订单状态
this.removeById(id);
}
@@ -232,6 +254,45 @@ public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, Order
return vo;
}
/** 五维统计开关是否变化(影响历史汇总列含义) */
private static boolean statDimensionsChanged(OrderStatusPO before, OrderStatusPO after) {
if (before == null || after == null) {
return false;
}
return !Objects.equals(before.getIncludeSalesAmount(), after.getIncludeSalesAmount())
|| !Objects.equals(before.getIncludeProductCost(), after.getIncludeProductCost())
|| !Objects.equals(before.getIncludeFreightCost(), after.getIncludeFreightCost())
|| !Objects.equals(before.getIncludeOtherCost(), after.getIncludeOtherCost())
|| !Objects.equals(before.getIncludeRefund(), after.getIncludeRefund());
}
private static OrderStatusPO snapshotStatDimensions(OrderStatusPO src) {
OrderStatusPO copy = new OrderStatusPO();
copy.setIncludeSalesAmount(src.getIncludeSalesAmount());
copy.setIncludeProductCost(src.getIncludeProductCost());
copy.setIncludeFreightCost(src.getIncludeFreightCost());
copy.setIncludeOtherCost(src.getIncludeOtherCost());
copy.setIncludeRefund(src.getIncludeRefund());
return copy;
}
private void maybeScheduleCompanyRebuild(Long companyId, OrderStatusPO before, OrderStatusPO after) {
if (!statDimensionsChanged(before, after)) {
return;
}
scheduleCompanyRebuild(companyId);
}
/** 状态配置变更后异步全公司 backfill */
private void scheduleCompanyRebuild(Long companyId) {
LocalDate start = orderMapper.selectMinOrderDateByCompany(companyId);
LocalDate end = orderMapper.selectMaxOrderDateByCompany(companyId);
if (start == null || end == null) {
return;
}
orderStatRebuildService.scheduleRebuild(companyId, null, start, end);
}
/** 创建时未传的统计开关默认:前四项参与(等同原 auto_statistics=1),退款不参与 */
private void applyStatDefaultsForCreate(OrderStatusPO p) {
if (p.getIncludeSalesAmount() == null) {
@@ -1,6 +1,7 @@
package top.xyquan.ecomdmbbackend.modules.ecom.order.status.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.po.OrderStatusPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.service.OrderStatusService;
@@ -15,7 +16,7 @@ public class OrderStatusStatResolver {
private final OrderStatusService orderStatusService;
public OrderStatusStatResolver(OrderStatusService orderStatusService) {
public OrderStatusStatResolver(@Lazy OrderStatusService orderStatusService) {
this.orderStatusService = orderStatusService;
}
@@ -4,8 +4,10 @@ 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.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
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.platform.mapper.PlatformMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.po.PlatformPO;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
@@ -64,6 +66,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
private final ProductSpecMapper productSpecMapper;
private final CategoryService categoryService;
private final PlatformMapper platformMapper;
private final OrderStatReadFacade orderStatReadFacade;
private final OrderStatOverviewAssembler orderStatOverviewAssembler;
public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
@@ -75,7 +79,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
ProductMapper productMapper,
ProductSpecMapper productSpecMapper,
CategoryService categoryService,
PlatformMapper platformMapper) {
PlatformMapper platformMapper,
OrderStatReadFacade orderStatReadFacade,
OrderStatOverviewAssembler orderStatOverviewAssembler) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
@@ -87,6 +93,8 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
this.productSpecMapper = productSpecMapper;
this.categoryService = categoryService;
this.platformMapper = platformMapper;
this.orderStatReadFacade = orderStatReadFacade;
this.orderStatOverviewAssembler = orderStatOverviewAssembler;
}
/**
@@ -150,6 +158,15 @@ 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<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
@@ -7,6 +7,10 @@ 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;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
@@ -20,6 +24,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.ShopOverviewStatisticsVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ShopOverviewStatisticsService;
@@ -60,6 +65,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
private final ProductSpecMapper productSpecMapper;
private final OrderStatusStatResolver orderStatusStatResolver;
private final CategoryService categoryService;
private final OrderStatReadFacade orderStatReadFacade;
private final CompanyOverviewService companyOverviewService;
public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
@@ -70,7 +77,9 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
ProductService productService,
ProductSpecMapper productSpecMapper,
OrderStatusStatResolver orderStatusStatResolver,
CategoryService categoryService) {
CategoryService categoryService,
OrderStatReadFacade orderStatReadFacade,
CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
@@ -81,6 +90,8 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
this.productSpecMapper = productSpecMapper;
this.orderStatusStatResolver = orderStatusStatResolver;
this.categoryService = categoryService;
this.orderStatReadFacade = orderStatReadFacade;
this.companyOverviewService = companyOverviewService;
}
/**
@@ -128,6 +139,10 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
throw new BusinessException("店铺不存在");
}
if (orderStatReadFacade.usesDailyStatSource()) {
return getShopOverviewFromStat(queryDTO, companyId, shop, startDate, endDate, stat);
}
// 查询订单数据(该店铺)
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
@@ -1013,5 +1028,165 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
return total;
}
/** 汇总表读路径:单店概览 */
private ShopOverviewStatisticsVO getShopOverviewFromStat(ShopOverviewQueryDTO queryDTO,
Long companyId, ShopPO shop,
LocalDate startDate, LocalDate endDate,
OrderStatusStatSets stat) {
List<Long> 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<OrderStatAggMapper.PromotionRow> promoRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, startDate, endDate);
List<OrderStatAggMapper.BrushRow> 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<OrderStatMetricsDTO> 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<OrderStatAggMapper.ShopProductRow> 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<OrderStatMetricsDTO> daily,
LocalDate start, LocalDate end,
java.util.function.Function<OrderStatMetricsDTO, BigDecimal> fn) {
Map<LocalDate, BigDecimal> map = new HashMap<>();
for (OrderStatMetricsDTO d : daily) {
if (d.getStatDate() != null) {
map.put(d.getStatDate(), fn.apply(d));
}
}
List<ShopOverviewStatisticsVO.TrendDataItem> 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();
}
ShopOverviewStatisticsVO.ProductOverview po = new ShopOverviewStatisticsVO.ProductOverview();
po.setTotal(mapCategorySummaryToProductTotal(table.getTotal()));
if (table.getCategories() != null) {
po.setProducts(table.getCategories().stream().map(c -> {
ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary();
p.setProductId(c.getCategoryId());
p.setProductName(c.getCategoryName());
p.setSalesAmount(c.getSalesAmount());
p.setOrderCount(c.getOrderCount());
p.setProfitAfterTax(c.getProfitAfterTax());
return p;
}).collect(Collectors.toList()));
}
return po;
}
private static ShopOverviewStatisticsVO.CategoryOverview mapCategoryOverview(CompanyOverviewVO.CategoryOverview table) {
if (table == null) {
return new ShopOverviewStatisticsVO.CategoryOverview();
}
ShopOverviewStatisticsVO.CategoryOverview co = new ShopOverviewStatisticsVO.CategoryOverview();
co.setTotal(mapCategorySummaryToShopCategoryTotal(table.getTotal()));
if (table.getCategories() != null) {
co.setCategories(table.getCategories().stream().map(c -> {
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
s.setCategoryId(c.getCategoryId());
s.setCategoryName(c.getCategoryName());
s.setSalesAmount(c.getSalesAmount());
s.setOrderCount(c.getOrderCount());
s.setProfitAfterTax(c.getProfitAfterTax());
return s;
}).collect(Collectors.toList()));
}
return co;
}
private static ShopOverviewStatisticsVO.ProductSummary mapCategorySummaryToProductTotal(CompanyOverviewVO.CategorySummary t) {
ShopOverviewStatisticsVO.ProductSummary p = new ShopOverviewStatisticsVO.ProductSummary();
if (t == null) {
return p;
}
p.setSalesAmount(t.getSalesAmount());
p.setOrderCount(t.getOrderCount());
p.setProfitAfterTax(t.getProfitAfterTax());
return p;
}
private static ShopOverviewStatisticsVO.CategorySummary mapCategorySummaryToShopCategoryTotal(CompanyOverviewVO.CategorySummary t) {
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
if (t == null) {
return s;
}
s.setSalesAmount(t.getSalesAmount());
s.setOrderCount(t.getOrderCount());
s.setProfitAfterTax(t.getProfitAfterTax());
return s;
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
}
@@ -3,8 +3,10 @@ package top.xyquan.ecomdmbbackend.modules.ecom.product.overview.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.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
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;
@@ -44,6 +46,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
private final ProductSpecMapper productSpecMapper;
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
private final ShopService shopService;
private final OrderStatReadFacade orderStatReadFacade;
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
OrderMapper orderMapper,
@@ -52,7 +55,8 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
ProductService productService,
ProductSpecMapper productSpecMapper,
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
ShopService shopService) {
ShopService shopService,
OrderStatReadFacade orderStatReadFacade) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.promotionFeeMapper = promotionFeeMapper;
@@ -61,6 +65,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
this.productSpecMapper = productSpecMapper;
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
this.shopService = shopService;
this.orderStatReadFacade = orderStatReadFacade;
}
private void applyProductOverviewOrderScope(LambdaQueryWrapper<OrderPO> wrapper,
@@ -133,6 +138,11 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds();
if (orderStatReadFacade.usesDailyStatSource()) {
return getProductOverviewFromStat(queryDTO, companyId, product, filterShopId,
startDate, endDate, taxRate, stat);
}
// 查询订单数据
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId,
@@ -819,4 +829,218 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
.limit(10)
.collect(Collectors.toList());
}
/** 汇总表读路径:商品概览 */
private ProductOverviewVO getProductOverviewFromStat(ProductOverviewQueryDTO queryDTO,
Long companyId, ProductPO product,
Long filterShopId,
LocalDate startDate, LocalDate endDate,
BigDecimal taxRate, OrderStatusStatSets stat) {
List<Long> 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<PromotionFeePO> promotionFees = new ArrayList<>();
if (!shopIds.isEmpty()) {
LambdaQueryWrapper<PromotionFeePO> 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<PromotionFeePO> 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<OrderStatMetricsDTO> daily,
LocalDate start, LocalDate end,
java.util.function.Function<OrderStatMetricsDTO, BigDecimal> fn) {
Map<LocalDate, BigDecimal> map = new HashMap<>();
for (OrderStatMetricsDTO d : daily) {
if (d.getStatDate() != null) {
map.put(d.getStatDate(), fn.apply(d));
}
}
List<ProductOverviewVO.TrendDataItem> 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<OrderStatMetricsDTO> specRows,
BigDecimal taxRate,
BigDecimal totalPromo,
BigDecimal totalSales) {
if (specRows == null || specRows.isEmpty()) {
return buildEmptySpecSummary();
}
Set<Long> specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId)
.filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, ProductSpecPO> specMap = productSpecMapper.selectBatchIds(specIds).stream()
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
List<ProductOverviewVO.SpecSummaryItem> items = new ArrayList<>();
for (OrderStatMetricsDTO m : specRows) {
ProductSpecPO spec = specMap.get(m.getProductSpecId());
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.setSpecId(m.getProductSpecId());
item.setSpecName(spec != null ? spec.getName() : "未知规格");
item.setSpecCode(spec != null ? spec.getSpecCode() : null);
item.setSalesAmount(sales);
item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0);
item.setQuantity(m.getQuantitySum() != null ? m.getQuantitySum() : 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<ProductOverviewVO.SpecSummaryItem> 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<ProductOverviewVO.SpecSalesRankItem> buildSpecTop10FromStat(List<OrderStatMetricsDTO> specRows) {
if (specRows == null) {
return List.of();
}
Set<Long> specIds = specRows.stream().map(OrderStatMetricsDTO::getProductSpecId)
.filter(Objects::nonNull).collect(Collectors.toSet());
Map<Long, ProductSpecPO> specMap = specIds.isEmpty() ? Map.of()
: productSpecMapper.selectBatchIds(specIds).stream()
.collect(Collectors.toMap(ProductSpecPO::getId, s -> s, (a, b) -> a));
return specRows.stream()
.sorted(Comparator.comparingInt((OrderStatMetricsDTO m) ->
m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0).reversed())
.limit(10)
.map(m -> {
ProductSpecPO spec = specMap.get(m.getProductSpecId());
ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem();
item.setSpecId(m.getProductSpecId());
item.setSpecName(spec != null ? spec.getName() : "未知规格");
item.setSpecCode(spec != null ? spec.getSpecCode() : 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))
.setScale(2, RoundingMode.HALF_UP);
}
return cur.signum() > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO;
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
}
@@ -21,10 +21,15 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductSpecVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.vo.ProductVO;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSpecService;
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.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
@@ -36,12 +41,15 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
private final CurrentUserContext currentUserContext;
private final ProductService productService;
private final OrderMapper orderMapper;
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
public ProductSpecServiceImpl(CurrentUserContext currentUserContext, ProductService productService,
OrderMapper orderMapper) {
OrderMapper orderMapper,
OrderStatCrudCoordinator orderStatCrudCoordinator) {
this.currentUserContext = currentUserContext;
this.productService = productService;
this.orderMapper = orderMapper;
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
}
/**
@@ -63,7 +71,19 @@ public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, Produ
if (specCode == null || specCode.isBlank()) {
return;
}
orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, specCode.trim(), productSpecId);
String code = specCode.trim();
List<OrderShopStatDateRow> affected =
orderMapper.selectOrphanOrderStatDatesBySpecCode(companyId, code);
orderMapper.linkOrdersBySpecCodeWhenSpecIdNull(companyId, code, productSpecId);
if (affected != null && !affected.isEmpty()) {
Set<StatDirtyKey> 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);
}
}
/**
@@ -3,7 +3,6 @@ package top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -18,6 +17,7 @@ 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;
@@ -35,7 +35,6 @@ import java.util.stream.Collectors;
* 推广费记录服务实现类
*/
@Service
@RequiredArgsConstructor
public class PromotionFeeServiceImpl implements PromotionFeeService {
private final PromotionFeeMapper promotionFeeMapper;
@@ -44,7 +43,23 @@ 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) {
this.promotionFeeMapper = promotionFeeMapper;
this.currentUserContext = currentUserContext;
this.shopService = shopService;
this.promotionFeeTypeService = promotionFeeTypeService;
this.productService = productService;
this.categoryService = categoryService;
this.feeStatCrudCoordinator = feeStatCrudCoordinator;
}
/**
* 创建推广费记录
@@ -62,6 +77,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
po.setUpdateBy(currentUserContext.getCurrentUserId());
promotionFeeMapper.insert(po);
feeStatCrudCoordinator.afterPromotionFeeSaved(null, po);
return po.getId();
}
@@ -83,6 +99,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
po.setUpdateBy(currentUserContext.getCurrentUserId());
po.setCompanyId(companyId);
promotionFeeMapper.updateById(po);
feeStatCrudCoordinator.afterPromotionFeeSaved(existing, po);
}
/**
@@ -98,6 +115,7 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
throw new BusinessException("推广费记录不存在");
}
promotionFeeMapper.deleteById(id);
feeStatCrudCoordinator.afterPromotionFeeDeleted(existing);
}
/**
@@ -3,10 +3,8 @@ 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.brushorder.mapper.BrushOrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
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.dto.CategoryExportDTO;
@@ -16,8 +14,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewV
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CategoryExportExcelService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService;
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.ExportService;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
import top.xyquan.ecomdmbbackend.modules.ecom.workbench.model.dto.WorkbenchExportDTO;
@@ -28,7 +24,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
@@ -42,34 +37,28 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private final CurrentUserContext currentUserContext;
private final OrderMapper orderMapper;
private final ShopService shopService;
private final OrderStatusStatResolver orderStatusStatResolver;
private final PromotionFeeMapper promotionFeeMapper;
private final BrushOrderMapper brushOrderMapper;
private final CompanyOverviewService companyOverviewService;
private final ExportService exportService;
private final CategoryExportExcelService categoryExportExcelService;
private final OrderStatReadFacade orderStatReadFacade;
public WorkbenchExportServiceImpl(
CurrentUserContext currentUserContext,
OrderMapper orderMapper,
ShopService shopService,
OrderStatusStatResolver orderStatusStatResolver,
PromotionFeeMapper promotionFeeMapper,
BrushOrderMapper brushOrderMapper,
CompanyOverviewService companyOverviewService,
ExportService exportService,
CategoryExportExcelService categoryExportExcelService) {
CategoryExportExcelService categoryExportExcelService,
OrderStatReadFacade orderStatReadFacade) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
this.shopService = shopService;
this.orderStatusStatResolver = orderStatusStatResolver;
this.promotionFeeMapper = promotionFeeMapper;
this.brushOrderMapper = brushOrderMapper;
this.companyOverviewService = companyOverviewService;
this.exportService = exportService;
this.categoryExportExcelService = categoryExportExcelService;
this.orderStatReadFacade = orderStatReadFacade;
}
/**
@@ -136,12 +125,11 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
"商品名称");
}
/** 拉取订单/推广/刷单后调用 {@link CompanyOverviewService#buildWorkbenchSummaryTables},各 export 共用 */
/** 拉取汇总表/明细聚合后构建四表,与 {@link WorkbenchServiceImpl#financeSlice} 口径一致 */
private CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) {
Long companyId = currentUserContext.getCurrentCompanyId();
DateRange range = parseDateRange(toQuery(dto));
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<Long> unionStatusIds = stat.getUnionStatusIds();
List<ShopPO> shops = loadFilteredShops(companyId, dto.getPlatformId(), dto.getShopId());
if (shops.isEmpty()) {
@@ -149,21 +137,17 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
}
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
List<OrderPO> orders = loadOrders(companyId, shopIds, range.startDateTime(), range.endDateTime(), unionStatusIds);
List<PromotionFeePO> promotionFees = loadPromotionFees(companyId, shopIds, range.startDate(), range.endDate());
List<BrushOrderPO> brushOrders = loadBrushOrders(companyId, shopIds, range.startDateTime(), range.endDateTime());
List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatReadFacade.loadShopProductRows(
companyId, shopIds, range.startDate(), range.endDate(), stat);
List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatReadFacade.loadPromotionRows(
companyId, shopIds, range.startDate(), range.endDate());
List<OrderStatAggMapper.BrushRow> brushRows = orderStatReadFacade.loadBrushRows(
companyId, shopIds, range.startDateTime(), range.endDateTime());
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
return companyOverviewService.buildWorkbenchSummaryTables(
taxRate,
companyId,
shops,
orders,
promotionFees,
brushOrders,
stat,
range.startDate(),
range.endDate());
return companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, orderRows, promotionRows, brushRows,
range.startDate(), range.endDate());
}
/** 导出 DTO 与查询 DTO 字段对齐,仅用于复用 {@link #parseDateRange} */
@@ -214,51 +198,6 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
return shopService.list(w);
}
/** 计入销售额状态的订单列表,与 {@link WorkbenchServiceImpl#loadOrders} 一致 */
private List<OrderPO> loadOrders(Long companyId, List<Long> shopIds,
LocalDateTime start, LocalDateTime end, List<Long> unionStatusIds) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
orderWrapper.eq(OrderPO::getCompanyId, companyId)
.in(OrderPO::getShopId, shopIds)
.ge(OrderPO::getOrderTime, start)
.le(OrderPO::getOrderTime, end);
if (!unionStatusIds.isEmpty()) {
orderWrapper.in(OrderPO::getStatusId, unionStatusIds);
} else {
orderWrapper.isNull(OrderPO::getId);
}
return orderMapper.selectList(orderWrapper);
}
/** 区间内推广费(按费用日) */
private List<PromotionFeePO> loadPromotionFees(Long companyId, List<Long> shopIds, LocalDate start, LocalDate end) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<PromotionFeePO> w = new LambdaQueryWrapper<>();
w.eq(PromotionFeePO::getCompanyId, companyId)
.in(PromotionFeePO::getShopId, shopIds)
.ge(PromotionFeePO::getFeeDate, start)
.le(PromotionFeePO::getFeeDate, end);
return promotionFeeMapper.selectList(w);
}
/** 区间内刷单(按刷单时间) */
private List<BrushOrderPO> loadBrushOrders(Long companyId, List<Long> shopIds, LocalDateTime start, LocalDateTime end) {
if (shopIds.isEmpty()) {
return Collections.emptyList();
}
LambdaQueryWrapper<BrushOrderPO> w = new LambdaQueryWrapper<>();
w.eq(BrushOrderPO::getCompanyId, companyId)
.in(BrushOrderPO::getShopId, shopIds)
.ge(BrushOrderPO::getBrushTime, start)
.le(BrushOrderPO::getBrushTime, end);
return brushOrderMapper.selectList(w);
}
/** 查询时间闭区间辅助 record */
private record DateRange(LocalDate startDate, LocalDate endDate) {
LocalDateTime startDateTime() {
@@ -9,6 +9,7 @@ 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.service.OrderStatReadFacade;
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
@@ -87,7 +88,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
private final ProductMapper productMapper;
private final CategoryService categoryService;
private final PlatformMapper platformMapper;
private final OrderStatAggMapper orderStatAggMapper;
private final OrderStatReadFacade orderStatReadFacade;
private final CompanyOverviewService companyOverviewService;
public WorkbenchServiceImpl(CurrentUserContext currentUserContext,
@@ -100,7 +101,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
ProductMapper productMapper,
CategoryService categoryService,
PlatformMapper platformMapper,
OrderStatAggMapper orderStatAggMapper,
OrderStatReadFacade orderStatReadFacade,
CompanyOverviewService companyOverviewService) {
this.currentUserContext = currentUserContext;
this.orderMapper = orderMapper;
@@ -112,7 +113,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
this.productMapper = productMapper;
this.categoryService = categoryService;
this.platformMapper = platformMapper;
this.orderStatAggMapper = orderStatAggMapper;
this.orderStatReadFacade = orderStatReadFacade;
this.companyOverviewService = companyOverviewService;
}
@@ -224,20 +225,17 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById);
}
/** 当前区间 SQL-1/2/4/5 */
/** 当前区间 SQL-1/2/4/5(汇总表或明细回退) */
private SqlAggBundle loadSqlAgg(ShopContext ctx) {
OrderStatusStatSets stat = ctx.stat();
List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatAggMapper.aggregateByShopProduct(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
List<OrderStatAggMapper.DailyRow> dailyRows = orderStatAggMapper.aggregateDaily(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatAggMapper.aggregatePromotionFees(
ctx.companyId(), ctx.shopIds(), ctx.range().startDate(), ctx.range().endDate());
List<OrderStatAggMapper.BrushRow> brushRows = orderStatAggMapper.aggregateBrushFees(
LocalDate start = ctx.range().startDate();
LocalDate end = ctx.range().endDate();
List<OrderStatAggMapper.ShopProductRow> orderRows = orderStatReadFacade.loadShopProductRows(
ctx.companyId(), ctx.shopIds(), start, end, ctx.stat());
List<OrderStatAggMapper.DailyRow> dailyRows = orderStatReadFacade.loadDailyRows(
ctx.companyId(), ctx.shopIds(), start, end, ctx.stat());
List<OrderStatAggMapper.PromotionRow> promotionRows = orderStatReadFacade.loadPromotionRows(
ctx.companyId(), ctx.shopIds(), start, end);
List<OrderStatAggMapper.BrushRow> brushRows = orderStatReadFacade.loadBrushRows(
ctx.companyId(), ctx.shopIds(), ctx.range().startDateTime(), ctx.range().endDateTime());
return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows);
}
@@ -247,38 +245,27 @@ public class WorkbenchServiceImpl implements WorkbenchService {
OrderStatusStatSets stat = ctx.stat();
DateRange lastRange = lastMonthSameSpan(ctx.range());
DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1));
LocalDateTime scanStart = minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime());
LocalDateTime scanEnd = maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime());
OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatAggMapper.aggregatePeriodKpi(
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd,
ctx.range().startDateTime(), ctx.range().endDateTime(),
lastRange.startDateTime(), lastRange.endDateTime(),
yoyRange.startDateTime(), yoyRange.endDateTime(),
stat.getUnionStatusIds(), statusList(stat.getSalesIds()), statusList(stat.getRefundIds()),
statusList(stat.getProductCostIds()), statusList(stat.getFreightCostIds()), statusList(stat.getOtherCostIds()));
if (orderKpi == null) {
orderKpi = new OrderStatAggMapper.PeriodKpiRow();
}
OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatReadFacade.loadPeriodKpi(
ctx.companyId(), ctx.shopIds(),
ctx.range().startDate(), ctx.range().endDate(),
lastRange.startDate(), lastRange.endDate(),
yoyRange.startDate(), yoyRange.endDate(), stat);
LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate());
LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate());
OrderStatAggMapper.FeeKpiRow promoKpi = orderStatAggMapper.aggregatePromotionPeriodKpi(
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());
if (promoKpi == null) {
promoKpi = new OrderStatAggMapper.FeeKpiRow();
}
OrderStatAggMapper.FeeKpiRow brushKpi = orderStatAggMapper.aggregateBrushPeriodKpi(
ctx.companyId(), ctx.shopIds(), scanStart, scanEnd,
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());
if (brushKpi == null) {
brushKpi = new OrderStatAggMapper.FeeKpiRow();
}
return new ComparePeriodBundle(lastRange, yoyRange,
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()),