mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 01:19:19 +08:00
remove: 移除统计相关后端代码
This commit is contained in:
+1
-8
@@ -20,7 +20,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.vo.BrushOrderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.service.BrushOrderService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
@@ -39,16 +38,13 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
|
||||
private final ShopService shopService;
|
||||
private final ProductService productService;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final FeeStatCrudCoordinator feeStatCrudCoordinator;
|
||||
|
||||
public BrushOrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
|
||||
ProductService productService, ProductSkuService productSkuService,
|
||||
FeeStatCrudCoordinator feeStatCrudCoordinator) {
|
||||
ProductService productService, ProductSkuService productSkuService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.productService = productService;
|
||||
this.productSkuService = productSkuService;
|
||||
this.feeStatCrudCoordinator = feeStatCrudCoordinator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -100,7 +96,6 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
|
||||
|
||||
// 保存刷单记录
|
||||
this.save(brushOrder);
|
||||
feeStatCrudCoordinator.afterBrushOrderSaved(null, brushOrder);
|
||||
|
||||
// 转换为VO并返回
|
||||
return convertToVO(brushOrder);
|
||||
@@ -164,7 +159,6 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
|
||||
|
||||
// 保存更新
|
||||
this.updateById(existingBrushOrder);
|
||||
feeStatCrudCoordinator.afterBrushOrderSaved(before, existingBrushOrder);
|
||||
|
||||
// 转换为VO并返回
|
||||
return convertToVO(existingBrushOrder);
|
||||
@@ -188,7 +182,6 @@ public class BrushOrderServiceImpl extends ServiceImpl<BrushOrderMapper, BrushOr
|
||||
}
|
||||
|
||||
// 硬删除刷单记录
|
||||
feeStatCrudCoordinator.afterBrushOrderDeleted(existingBrushOrder);
|
||||
this.removeById(id);
|
||||
}
|
||||
|
||||
|
||||
+12
-34
@@ -6,9 +6,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopProductRelationPO;
|
||||
|
||||
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;
|
||||
@@ -198,10 +196,19 @@ public class ImportRuntimeContext {
|
||||
// 进度回调(主线程设置,workers 调用,线程安全包装)
|
||||
transient volatile BiConsumer<Integer, Integer> progressCallback;
|
||||
|
||||
/** 本任务涉及、需 refresh 汇总表的自然日(order_time → Asia/Shanghai DATE) */
|
||||
private final Set<LocalDate> dirtyStatDates = ConcurrentHashMap.newKeySet();
|
||||
/** 本任务涉及的自然日(订单统计已移除,保留空实现供导入流程调用) */
|
||||
public void markOrderStatDirty(LocalDateTime orderTime) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
public void markOrderStatDirty(Long targetShopId, LocalDateTime orderTime) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/** 更新订单时标记旧快照日期(订单统计已移除,空实现) */
|
||||
public void markOrderStatDirtyFromSnapshot(OrderPO before) {
|
||||
// no-op
|
||||
}
|
||||
|
||||
/** 本次订单导入的字段映射(仅主线程在 process 入口设置,用于「有变更才更新」时按映射比较) */
|
||||
private transient Map<String, MappingField> orderImportFieldMapping;
|
||||
@@ -254,35 +261,6 @@ 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) {
|
||||
if (rawValue == null) return;
|
||||
String value = rawValue.trim();
|
||||
|
||||
-61
@@ -15,9 +15,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.ImportTaskServi
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.importtask.service.SseNotificationService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatRefreshService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRefreshCoordinator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuCostService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService;
|
||||
@@ -38,13 +35,8 @@ import java.nio.charset.Charset;
|
||||
import java.nio.charset.CharsetDecoder;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -65,8 +57,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
// 提取出的处理器(构造时组装,不单独持有 helper 的中间依赖)
|
||||
private final OrderImportProcessor orderImportProcessor;
|
||||
private final PromotionFeeImportProcessor promotionFeeImportProcessor;
|
||||
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
|
||||
private final FeeStatRefreshService feeStatRefreshService;
|
||||
private final LicenseFeatureGuard licenseFeatureGuard;
|
||||
|
||||
public ImportTaskProcessorServiceImpl(ImportTaskService importTaskService,
|
||||
@@ -82,8 +72,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
OssService ossService,
|
||||
SysFileService sysFileService,
|
||||
PromotionFeeImportProcessor promotionFeeImportProcessor,
|
||||
OrderStatRefreshCoordinator orderStatRefreshCoordinator,
|
||||
FeeStatRefreshService feeStatRefreshService,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
this.importTaskService = importTaskService;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
@@ -93,8 +81,6 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
this.ossService = ossService;
|
||||
this.sysFileService = sysFileService;
|
||||
this.promotionFeeImportProcessor = promotionFeeImportProcessor;
|
||||
this.orderStatRefreshCoordinator = orderStatRefreshCoordinator;
|
||||
this.feeStatRefreshService = feeStatRefreshService;
|
||||
|
||||
ProductSkuImportHelper productSkuImportHelper = new ProductSkuImportHelper(
|
||||
productMapper, productSkuService, productSkuCostService, shopProductRelationMapper);
|
||||
@@ -222,42 +208,11 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
String message = result.failCount > 0 ? summary + "\n" + result.errorMessages.toString() : summary;
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
|
||||
// 明细写入成功后:异步排队 refresh 汇总表(不阻塞导入线程)
|
||||
enqueueOrderStatRefreshAfterImport(task, context);
|
||||
|
||||
} finally {
|
||||
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** 合并内存脏日期 + DB 兜底,写入 refresh 队列 */
|
||||
private void enqueueOrderStatRefreshAfterImport(ImportTaskPO task, ImportRuntimeContext context) {
|
||||
if (task.getCompanyId() == null || task.getShopId() == null) {
|
||||
return;
|
||||
}
|
||||
Set<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 {
|
||||
@@ -322,28 +277,12 @@ public class ImportTaskProcessorServiceImpl implements ImportTaskProcessorServic
|
||||
message += "\n" + result.detailMessage;
|
||||
}
|
||||
updateTaskStatus(task.getId(), finalStatus, message, result.totalCount, result.successCount, result.failCount);
|
||||
refreshFeeStatAfterPromotionImport(task, feeDateStr, result.successCount);
|
||||
|
||||
} finally {
|
||||
if (tempOssFile != null && tempOssFile.exists()) tempOssFile.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** 推广费导入成功后重算对应自然日的费汇总表 */
|
||||
private void refreshFeeStatAfterPromotionImport(ImportTaskPO task, String feeDateStr, int successCount) {
|
||||
if (successCount <= 0 || task.getShopId() == null || feeDateStr == null || feeDateStr.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
LocalDate feeDate = LocalDate.parse(feeDateStr.trim(), DateTimeFormatter.ISO_LOCAL_DATE);
|
||||
feeStatRefreshService.refreshShopDay(task.getCompanyId(), task.getShopId(), feeDate);
|
||||
} catch (DateTimeParseException e) {
|
||||
log.warn("推广费导入后 refresh 跳过:feeDate 格式无效 taskId={} feeDate={}", task.getId(), feeDateStr);
|
||||
} catch (Exception e) {
|
||||
log.warn("推广费导入后 refresh 失败 taskId={} shopId={} feeDate={}", task.getId(), task.getShopId(), feeDateStr, e);
|
||||
}
|
||||
}
|
||||
|
||||
private ImportRuntimeContext.MappingConfig parseMappingConfig(String mappingJson) {
|
||||
try {
|
||||
if (mappingJson == null || mappingJson.trim().isEmpty()) {
|
||||
|
||||
-35
@@ -7,10 +7,7 @@ import org.apache.ibatis.annotations.Update;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.dto.OrderListQueryParam;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -46,38 +43,6 @@ public interface OrderMapper extends BaseMapper<OrderPO> {
|
||||
@Param("skuCode") String skuCode,
|
||||
@Param("productSkuId") Long productSkuId);
|
||||
|
||||
@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);
|
||||
|
||||
@Select("SELECT MIN(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId}")
|
||||
LocalDate selectMinOrderDateByCompany(@Param("companyId") Long companyId);
|
||||
|
||||
@Select("SELECT MAX(DATE(order_time)) FROM ec_order WHERE company_id = #{companyId}")
|
||||
LocalDate selectMaxOrderDateByCompany(@Param("companyId") Long companyId);
|
||||
|
||||
@Select("""
|
||||
SELECT i.shop_id AS shopId, DATE(o.order_time) AS statDate
|
||||
FROM ec_order_item i
|
||||
INNER JOIN ec_order o ON o.id = i.order_id
|
||||
WHERE i.company_id = #{companyId} AND i.sku_code = #{skuCode} AND i.product_sku_id IS NULL
|
||||
GROUP BY i.shop_id, DATE(o.order_time)
|
||||
""")
|
||||
List<OrderShopStatDateRow> selectOrphanOrderStatDatesBySkuCode(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("skuCode") String skuCode);
|
||||
|
||||
long countOrderList(OrderListQueryParam param);
|
||||
|
||||
List<Long> selectOrderListIds(OrderListQueryParam param);
|
||||
|
||||
-178
@@ -1,178 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.mapper;
|
||||
|
||||
import lombok.Data;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单/费用 SQL 聚合(SQL 均在 {@code mapper/order/OrderStatAggMapper.xml})。
|
||||
* <p>
|
||||
* 行类型定义为内嵌类,避免单独拆多个 model 文件。
|
||||
*/
|
||||
@Mapper
|
||||
public interface OrderStatAggMapper {
|
||||
|
||||
/** SQL-1:shop × product 粒度,四表 rollup 基础 */
|
||||
List<ShopProductRow> aggregateByShopProduct(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("start") LocalDateTime start,
|
||||
@Param("end") LocalDateTime end,
|
||||
@Param("unionStatusCodes") List<String> unionStatusCodes,
|
||||
@Param("salesStatusCodes") List<String> salesStatusCodes,
|
||||
@Param("refundStatusCodes") List<String> refundStatusCodes,
|
||||
@Param("productCostStatusCodes") List<String> productCostStatusCodes,
|
||||
@Param("freightCostStatusCodes") List<String> freightCostStatusCodes,
|
||||
@Param("otherCostStatusCodes") List<String> otherCostStatusCodes);
|
||||
|
||||
/** SQL-2:日趋势 */
|
||||
List<DailyRow> aggregateDaily(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("start") LocalDateTime start,
|
||||
@Param("end") LocalDateTime end,
|
||||
@Param("unionStatusCodes") List<String> unionStatusCodes,
|
||||
@Param("salesStatusCodes") List<String> salesStatusCodes,
|
||||
@Param("refundStatusCodes") List<String> refundStatusCodes,
|
||||
@Param("productCostStatusCodes") List<String> productCostStatusCodes,
|
||||
@Param("freightCostStatusCodes") List<String> freightCostStatusCodes,
|
||||
@Param("otherCostStatusCodes") List<String> otherCostStatusCodes);
|
||||
|
||||
/** SQL-3:三段时间 KPI(一次扫描) */
|
||||
PeriodKpiRow aggregatePeriodKpi(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("scanStart") LocalDateTime scanStart,
|
||||
@Param("scanEnd") LocalDateTime scanEnd,
|
||||
@Param("curStart") LocalDateTime curStart,
|
||||
@Param("curEnd") LocalDateTime curEnd,
|
||||
@Param("prevStart") LocalDateTime prevStart,
|
||||
@Param("prevEnd") LocalDateTime prevEnd,
|
||||
@Param("yoyStart") LocalDateTime yoyStart,
|
||||
@Param("yoyEnd") LocalDateTime yoyEnd,
|
||||
@Param("unionStatusCodes") List<String> unionStatusCodes,
|
||||
@Param("salesStatusCodes") List<String> salesStatusCodes,
|
||||
@Param("refundStatusCodes") List<String> refundStatusCodes,
|
||||
@Param("productCostStatusCodes") List<String> productCostStatusCodes,
|
||||
@Param("freightCostStatusCodes") List<String> freightCostStatusCodes,
|
||||
@Param("otherCostStatusCodes") List<String> otherCostStatusCodes);
|
||||
|
||||
/** 推广费三段时间 KPI */
|
||||
FeeKpiRow aggregatePromotionPeriodKpi(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("scanStart") LocalDate scanStart,
|
||||
@Param("scanEnd") LocalDate scanEnd,
|
||||
@Param("curStart") LocalDate curStart,
|
||||
@Param("curEnd") LocalDate curEnd,
|
||||
@Param("prevStart") LocalDate prevStart,
|
||||
@Param("prevEnd") LocalDate prevEnd,
|
||||
@Param("yoyStart") LocalDate yoyStart,
|
||||
@Param("yoyEnd") LocalDate yoyEnd);
|
||||
|
||||
/** 刷单费三段时间 KPI */
|
||||
FeeKpiRow aggregateBrushPeriodKpi(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("scanStart") LocalDateTime scanStart,
|
||||
@Param("scanEnd") LocalDateTime scanEnd,
|
||||
@Param("curStart") LocalDateTime curStart,
|
||||
@Param("curEnd") LocalDateTime curEnd,
|
||||
@Param("prevStart") LocalDateTime prevStart,
|
||||
@Param("prevEnd") LocalDateTime prevEnd,
|
||||
@Param("yoyStart") LocalDateTime yoyStart,
|
||||
@Param("yoyEnd") LocalDateTime yoyEnd);
|
||||
|
||||
/** SQL-4:推广费明细(四表分摊) */
|
||||
List<PromotionRow> aggregatePromotionFees(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("startDate") LocalDate startDate,
|
||||
@Param("endDate") LocalDate endDate);
|
||||
|
||||
/** SQL-5:刷单费按店铺 */
|
||||
List<BrushRow> aggregateBrushFees(
|
||||
@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<Long> shopIds,
|
||||
@Param("start") LocalDateTime start,
|
||||
@Param("end") LocalDateTime end);
|
||||
|
||||
@Data
|
||||
class ShopProductRow {
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BigDecimal salesAmount;
|
||||
private Long orderCount;
|
||||
private Long salesQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
private BigDecimal gmvAllStatus;
|
||||
private Long gmvOrderCount;
|
||||
private Long gmvQuantitySum;
|
||||
}
|
||||
|
||||
@Data
|
||||
class DailyRow {
|
||||
private LocalDate statDate;
|
||||
private BigDecimal salesAmount;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
}
|
||||
|
||||
@Data
|
||||
class PeriodKpiRow {
|
||||
private BigDecimal curSalesAmount;
|
||||
private Long curOrderCount;
|
||||
private BigDecimal curRefundAmount;
|
||||
private BigDecimal curProductCost;
|
||||
private BigDecimal curFreightCost;
|
||||
private BigDecimal curOtherCost;
|
||||
private BigDecimal curGmvAllStatus;
|
||||
private BigDecimal prevSalesAmount;
|
||||
private Long prevOrderCount;
|
||||
private BigDecimal prevRefundAmount;
|
||||
private BigDecimal prevProductCost;
|
||||
private BigDecimal prevFreightCost;
|
||||
private BigDecimal prevOtherCost;
|
||||
private BigDecimal prevGmvAllStatus;
|
||||
private BigDecimal yoySalesAmount;
|
||||
private Long yoyOrderCount;
|
||||
private BigDecimal yoyRefundAmount;
|
||||
private BigDecimal yoyProductCost;
|
||||
private BigDecimal yoyFreightCost;
|
||||
private BigDecimal yoyOtherCost;
|
||||
private BigDecimal yoyGmvAllStatus;
|
||||
}
|
||||
|
||||
@Data
|
||||
class FeeKpiRow {
|
||||
private BigDecimal curAmount;
|
||||
private BigDecimal prevAmount;
|
||||
private BigDecimal yoyAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
class PromotionRow {
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BigDecimal feeAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
class BrushRow {
|
||||
private Long shopId;
|
||||
private BigDecimal brushAmount;
|
||||
}
|
||||
}
|
||||
-31
@@ -33,8 +33,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.status.model.enums.OrderStat
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.vo.ShopVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeature;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseFeatureGuard;
|
||||
@@ -67,20 +65,17 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
private final ProductService productService;
|
||||
private final ProductSkuService productSkuService;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
|
||||
private final LicenseFeatureGuard licenseFeatureGuard;
|
||||
|
||||
public OrderServiceImpl(CurrentUserContext currentUserContext, ShopService shopService,
|
||||
ProductService productService, ProductSkuService productSkuService,
|
||||
OrderItemMapper orderItemMapper,
|
||||
OrderStatCrudCoordinator orderStatCrudCoordinator,
|
||||
LicenseFeatureGuard licenseFeatureGuard) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.productService = productService;
|
||||
this.productSkuService = productSkuService;
|
||||
this.orderItemMapper = orderItemMapper;
|
||||
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
|
||||
this.licenseFeatureGuard = licenseFeatureGuard;
|
||||
}
|
||||
|
||||
@@ -103,7 +98,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
order.setCreateBy(userId);
|
||||
this.save(order);
|
||||
saveItems(order, itemDtos, companyId, userId);
|
||||
orderStatCrudCoordinator.afterOrderSaved(null, order);
|
||||
return convertToVO(order);
|
||||
}
|
||||
|
||||
@@ -154,7 +148,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
}
|
||||
|
||||
OrderPO after = this.getById(id);
|
||||
orderStatCrudCoordinator.afterOrderSaved(existingOrder, after);
|
||||
return convertToVO(after != null ? after : order);
|
||||
}
|
||||
|
||||
@@ -163,7 +156,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
public void deleteOrder(Long id) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
OrderPO existingOrder = requireOrder(id, companyId);
|
||||
orderStatCrudCoordinator.afterOrderDeleted(existingOrder);
|
||||
orderItemMapper.delete(new LambdaQueryWrapper<OrderItemPO>().eq(OrderItemPO::getOrderId, id));
|
||||
this.removeById(id);
|
||||
}
|
||||
@@ -188,7 +180,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
if (toRemove.size() != uniqueIds.size()) {
|
||||
throw new BusinessException("存在无效订单或无权删除的订单");
|
||||
}
|
||||
orderStatCrudCoordinator.afterOrdersDeletedBatch(toRemove);
|
||||
orderItemMapper.delete(new LambdaQueryWrapper<OrderItemPO>().in(OrderItemPO::getOrderId, uniqueIds));
|
||||
this.remove(wrapper);
|
||||
}
|
||||
@@ -272,28 +263,6 @@ public class OrderServiceImpl extends ServiceImpl<OrderMapper, OrderPO> implemen
|
||||
try {
|
||||
ProductSkuPO sku = productSkuService.getById(skuId);
|
||||
int n = baseMapper.updateCostFields(productCost, shippingCost, otherCost, skuId, startTime, endTime);
|
||||
if (n > 0 && sku != null && sku.getCompanyId() != null) {
|
||||
List<OrderItemPO> affected = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.eq(OrderItemPO::getCompanyId, sku.getCompanyId())
|
||||
.eq(OrderItemPO::getProductSkuId, skuId));
|
||||
Set<Long> orderIds = affected.stream().map(OrderItemPO::getOrderId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
if (!orderIds.isEmpty()) {
|
||||
List<OrderPO> orders = list(new LambdaQueryWrapper<OrderPO>()
|
||||
.in(OrderPO::getId, orderIds)
|
||||
.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 : orders) {
|
||||
if (o.getShopId() != null && o.getOrderTime() != null) {
|
||||
keys.add(new StatDirtyKey(o.getCompanyId(), o.getShopId(),
|
||||
o.getOrderTime().atZone(zone).toLocalDate()));
|
||||
}
|
||||
}
|
||||
orderStatCrudCoordinator.enqueueDirtyKeys(keys);
|
||||
}
|
||||
}
|
||||
return n;
|
||||
} catch (Exception ex) {
|
||||
log.warn("同步成本到订单跳过(订单表可能不存在): {}", ex.getMessage());
|
||||
|
||||
-46
@@ -1,46 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 订单统计读模型配置(写入 Worker、读路径开关、缓存 TTL)。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "order-stat")
|
||||
public class OrderStatProperties {
|
||||
|
||||
/** daily=读汇总表;order=应急回退扫 ec_order */
|
||||
private String statSource = "daily";
|
||||
|
||||
/** 汇总行缺失时同步补算 */
|
||||
private boolean autoRefreshOnMiss = true;
|
||||
|
||||
/** 是否启用夜间全公司 rebuild 定时任务 */
|
||||
private boolean nightlyRebuildEnabled = false;
|
||||
|
||||
/** cron 表达式,见 {@code order-stat.nightly-rebuild-cron} */
|
||||
private String nightlyRebuildCron = "0 30 2 * * ?";
|
||||
|
||||
private RefreshWorker refreshWorker = new RefreshWorker();
|
||||
|
||||
private Cache cache = new Cache();
|
||||
|
||||
@Data
|
||||
public static class RefreshWorker {
|
||||
/** 是否启动异步 refresh 消费者 */
|
||||
private boolean enabled = true;
|
||||
private int poolSize = 4;
|
||||
/** 轮询 ec_order_stat_refresh_queue 间隔毫秒 */
|
||||
private long pollIntervalMs = 2000;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class Cache {
|
||||
private boolean enabled = true;
|
||||
private long ttlHistorySeconds = 86400;
|
||||
private long ttlTodaySeconds = 900;
|
||||
}
|
||||
}
|
||||
-61
@@ -1,61 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatRebuildRequestDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatReconcileRequestDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReconcileService;
|
||||
|
||||
@Tag(name = "电商-订单统计管理", description = "汇总表 backfill / rebuild")
|
||||
@RestController
|
||||
@RequestMapping("/ec/admin/order-stat")
|
||||
public class OrderStatAdminController {
|
||||
|
||||
private final OrderStatRebuildService orderStatRebuildService;
|
||||
private final OrderStatReconcileService orderStatReconcileService;
|
||||
|
||||
public OrderStatAdminController(OrderStatRebuildService orderStatRebuildService,
|
||||
OrderStatReconcileService orderStatReconcileService) {
|
||||
this.orderStatRebuildService = orderStatRebuildService;
|
||||
this.orderStatReconcileService = orderStatReconcileService;
|
||||
}
|
||||
|
||||
@Operation(summary = "创建 rebuild 任务", description = "异步按 shop×date 重算日/月/年汇总表")
|
||||
@PostMapping("/rebuild")
|
||||
@RequirePermission(value = "ecom:shop:read", description = "订单统计 rebuild", allowSuper = true)
|
||||
public ApiResponse<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);
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.job;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatRebuildService;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.model.po.CompanyPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.org.company.service.CompanyService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 夜间全公司汇总灌数:按公司订单日期范围创建 rebuild 任务。
|
||||
*/
|
||||
@Component
|
||||
public class OrderStatNightlyRebuildJob {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatNightlyRebuildJob.class);
|
||||
|
||||
private final OrderStatProperties properties;
|
||||
private final CompanyService companyService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderStatRebuildService orderStatRebuildService;
|
||||
|
||||
public OrderStatNightlyRebuildJob(OrderStatProperties properties,
|
||||
CompanyService companyService,
|
||||
OrderMapper orderMapper,
|
||||
OrderStatRebuildService orderStatRebuildService) {
|
||||
this.properties = properties;
|
||||
this.companyService = companyService;
|
||||
this.orderMapper = orderMapper;
|
||||
this.orderStatRebuildService = orderStatRebuildService;
|
||||
}
|
||||
|
||||
/** 默认每天 02:30 触发(可在 yml 覆盖 cron) */
|
||||
@Scheduled(cron = "${order-stat.nightly-rebuild-cron:0 30 2 * * ?}")
|
||||
public void runNightlyRebuild() {
|
||||
if (!properties.isNightlyRebuildEnabled()) {
|
||||
return;
|
||||
}
|
||||
List<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);
|
||||
}
|
||||
}
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import lombok.Data;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface FeeStatDailyMapper extends BaseMapper<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;
|
||||
}
|
||||
}
|
||||
-55
@@ -1,55 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface OrderStatDailyMapper extends BaseMapper<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);
|
||||
}
|
||||
-98
@@ -1,98 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/** 汇总表读路径 SQL(日/月/年表 SUM)。 */
|
||||
@Mapper
|
||||
public interface OrderStatQueryMapper {
|
||||
|
||||
OrderStatMetricsDTO sumDailyShop(@Param("companyId") Long companyId,
|
||||
@Param("shopIds") List<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);
|
||||
}
|
||||
-9
@@ -1,9 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO;
|
||||
|
||||
@Mapper
|
||||
public interface OrderStatRebuildTaskMapper extends BaseMapper<OrderStatRebuildTaskPO> {
|
||||
}
|
||||
-63
@@ -1,63 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import lombok.Data;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Mapper
|
||||
public interface OrderStatRefreshMapper extends BaseMapper<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("unionStatusCodes") List<String> unionStatusCodes,
|
||||
@Param("salesStatusCodes") List<String> salesStatusCodes,
|
||||
@Param("refundStatusCodes") List<String> refundStatusCodes,
|
||||
@Param("productCostStatusCodes") List<String> productCostStatusCodes,
|
||||
@Param("freightCostStatusCodes") List<String> freightCostStatusCodes,
|
||||
@Param("otherCostStatusCodes") List<String> otherCostStatusCodes);
|
||||
|
||||
@Data
|
||||
class SpecDayRow {
|
||||
private Long productId;
|
||||
private Long productSkuId;
|
||||
private BigDecimal salesAmount;
|
||||
private Long orderCount;
|
||||
private BigDecimal refundAmount;
|
||||
private Integer salesQuantitySum;
|
||||
private BigDecimal gmvAmount;
|
||||
private Long gmvOrderCount;
|
||||
private Integer gmvQuantitySum;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
}
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 订单汇总 refresh 维度:店铺 + 自然日 */
|
||||
@Data
|
||||
public class OrderShopStatDateRow {
|
||||
private Long shopId;
|
||||
private LocalDate statDate;
|
||||
}
|
||||
-42
@@ -1,42 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 汇总表读侧统一指标 DTO(店铺/商品/规格维度共用字段集)。
|
||||
*/
|
||||
@Data
|
||||
public class OrderStatMetricsDTO {
|
||||
|
||||
private LocalDate statDate;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private Long productSkuId;
|
||||
|
||||
private BigDecimal salesAmount = BigDecimal.ZERO;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private Integer salesOrderCount = 0;
|
||||
/** 实际销量件数(sales_quantity_sum) */
|
||||
private Integer salesQuantitySum = 0;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
private BigDecimal gmvAmount = BigDecimal.ZERO;
|
||||
private Integer gmvOrderCount = 0;
|
||||
/** GMV 销量件数(gmv_quantity_sum) */
|
||||
private Integer gmvQuantitySum = 0;
|
||||
|
||||
/** 订单成本合计 */
|
||||
public BigDecimal getOrderCost() {
|
||||
return nz(productCost).add(nz(freightCost)).add(nz(otherCost));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
-27
@@ -1,27 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Schema(description = "订单统计 rebuild 请求")
|
||||
public class OrderStatRebuildRequestDTO {
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "公司ID")
|
||||
private Long companyId;
|
||||
|
||||
@Schema(description = "店铺ID,空=全店")
|
||||
private Long shopId;
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "起始自然日")
|
||||
private LocalDate startDate;
|
||||
|
||||
@NotNull
|
||||
@Schema(description = "结束自然日")
|
||||
private LocalDate endDate;
|
||||
}
|
||||
-24
@@ -1,24 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
@Data
|
||||
@Schema(description = "汇总表对账请求")
|
||||
public class OrderStatReconcileRequestDTO {
|
||||
|
||||
@NotNull
|
||||
private Long companyId;
|
||||
|
||||
@NotNull
|
||||
private LocalDate startDate;
|
||||
|
||||
@NotNull
|
||||
private LocalDate endDate;
|
||||
|
||||
@Schema(description = "抽样条数,默认 100")
|
||||
private Integer sampleSize = 100;
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_order_stat_daily_product")
|
||||
public class OrderStatDailyProductPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("category_id")
|
||||
private Long categoryId;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
@TableField("sales_amount")
|
||||
private BigDecimal salesAmount;
|
||||
|
||||
@TableField("refund_amount")
|
||||
private BigDecimal refundAmount;
|
||||
|
||||
@TableField("sales_order_count")
|
||||
private Integer salesOrderCount;
|
||||
|
||||
@TableField("sales_quantity_sum")
|
||||
private Integer salesQuantitySum;
|
||||
|
||||
@TableField("gmv_amount")
|
||||
private BigDecimal gmvAmount;
|
||||
|
||||
@TableField("gmv_order_count")
|
||||
private Integer gmvOrderCount;
|
||||
|
||||
@TableField("gmv_quantity_sum")
|
||||
private Integer gmvQuantitySum;
|
||||
|
||||
@TableField("product_cost")
|
||||
private BigDecimal productCost;
|
||||
|
||||
@TableField("freight_cost")
|
||||
private BigDecimal freightCost;
|
||||
|
||||
@TableField("other_cost")
|
||||
private BigDecimal otherCost;
|
||||
|
||||
@TableField("stat_version")
|
||||
private Integer statVersion;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-71
@@ -1,71 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_order_stat_daily_shop")
|
||||
public class OrderStatDailyShopPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("platform_code")
|
||||
private String platformCode;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
@TableField("sales_amount")
|
||||
private BigDecimal salesAmount;
|
||||
|
||||
@TableField("refund_amount")
|
||||
private BigDecimal refundAmount;
|
||||
|
||||
@TableField("sales_order_count")
|
||||
private Integer salesOrderCount;
|
||||
|
||||
@TableField("sales_quantity_sum")
|
||||
private Integer salesQuantitySum;
|
||||
|
||||
@TableField("product_cost")
|
||||
private BigDecimal productCost;
|
||||
|
||||
@TableField("freight_cost")
|
||||
private BigDecimal freightCost;
|
||||
|
||||
@TableField("other_cost")
|
||||
private BigDecimal otherCost;
|
||||
|
||||
@TableField("gmv_amount")
|
||||
private BigDecimal gmvAmount;
|
||||
|
||||
@TableField("gmv_order_count")
|
||||
private Integer gmvOrderCount;
|
||||
|
||||
@TableField("gmv_quantity_sum")
|
||||
private Integer gmvQuantitySum;
|
||||
|
||||
@TableField("stat_version")
|
||||
private Integer statVersion;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-74
@@ -1,74 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_order_stat_daily_spec")
|
||||
public class OrderStatDailySpecPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("product_sku_id")
|
||||
private Long productSkuId;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
@TableField("sales_amount")
|
||||
private BigDecimal salesAmount;
|
||||
|
||||
@TableField("refund_amount")
|
||||
private BigDecimal refundAmount;
|
||||
|
||||
@TableField("sales_order_count")
|
||||
private Integer salesOrderCount;
|
||||
|
||||
@TableField("sales_quantity_sum")
|
||||
private Integer salesQuantitySum;
|
||||
|
||||
@TableField("gmv_amount")
|
||||
private BigDecimal gmvAmount;
|
||||
|
||||
@TableField("gmv_order_count")
|
||||
private Integer gmvOrderCount;
|
||||
|
||||
@TableField("gmv_quantity_sum")
|
||||
private Integer gmvQuantitySum;
|
||||
|
||||
@TableField("product_cost")
|
||||
private BigDecimal productCost;
|
||||
|
||||
@TableField("freight_cost")
|
||||
private BigDecimal freightCost;
|
||||
|
||||
@TableField("other_cost")
|
||||
private BigDecimal otherCost;
|
||||
|
||||
@TableField("stat_version")
|
||||
private Integer statVersion;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_order_stat_rebuild_task")
|
||||
public class OrderStatRebuildTaskPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("start_date")
|
||||
private LocalDate startDate;
|
||||
|
||||
@TableField("end_date")
|
||||
private LocalDate endDate;
|
||||
|
||||
@TableField("granularity")
|
||||
private String granularity;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("progress_date")
|
||||
private LocalDate progressDate;
|
||||
|
||||
@TableField("error_message")
|
||||
private String errorMessage;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-43
@@ -1,43 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_order_stat_refresh_queue")
|
||||
public class OrderStatRefreshQueuePO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
@TableField("source")
|
||||
private String source;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("retry_count")
|
||||
private Integer retryCount;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-44
@@ -1,44 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
@TableName("ec_promotion_fee_stat_daily")
|
||||
public class PromotionFeeStatDailyPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("product_id")
|
||||
private Long productId;
|
||||
|
||||
@TableField("category_id")
|
||||
private Long categoryId;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
@TableField("fee_amount")
|
||||
private BigDecimal feeAmount;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
-102
@@ -1,102 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 推广费/刷单 CRUD 后刷新费汇总日表(事务提交后执行)。
|
||||
*/
|
||||
@Service
|
||||
public class FeeStatCrudCoordinator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(FeeStatCrudCoordinator.class);
|
||||
private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final FeeStatRefreshService feeStatRefreshService;
|
||||
private final OrderStatCacheService orderStatCacheService;
|
||||
|
||||
public FeeStatCrudCoordinator(FeeStatRefreshService feeStatRefreshService,
|
||||
OrderStatCacheService orderStatCacheService) {
|
||||
this.feeStatRefreshService = feeStatRefreshService;
|
||||
this.orderStatCacheService = orderStatCacheService;
|
||||
}
|
||||
|
||||
public void afterPromotionFeeSaved(PromotionFeePO before, PromotionFeePO after) {
|
||||
Set<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) {}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.FeeStatDailyMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.PromotionFeeStatDailyPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** 推广费/刷单费日表 refresh + 月年 rollup。 */
|
||||
@Service
|
||||
public class FeeStatRefreshService {
|
||||
|
||||
private final FeeStatDailyMapper feeStatDailyMapper;
|
||||
|
||||
public FeeStatRefreshService(FeeStatDailyMapper feeStatDailyMapper) {
|
||||
this.feeStatDailyMapper = feeStatDailyMapper;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) {
|
||||
refreshPromotionDay(companyId, shopId, statDate);
|
||||
refreshBrushDay(companyId, shopId, statDate);
|
||||
LocalDate statMonth = statDate.withDayOfMonth(1);
|
||||
int statYear = statDate.getYear();
|
||||
feeStatDailyMapper.rollupPromotionMonthly(companyId, shopId, statMonth);
|
||||
feeStatDailyMapper.rollupPromotionYearly(companyId, shopId, statYear);
|
||||
feeStatDailyMapper.rollupBrushMonthly(companyId, shopId, statMonth);
|
||||
feeStatDailyMapper.rollupBrushYearly(companyId, shopId, statYear);
|
||||
}
|
||||
|
||||
private void refreshPromotionDay(Long companyId, Long shopId, LocalDate statDate) {
|
||||
feeStatDailyMapper.deletePromotionDaily(companyId, shopId, statDate);
|
||||
List<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);
|
||||
}
|
||||
}
|
||||
-96
@@ -1,96 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* 汇总读路径 Redis 缓存失效(按公司+店铺+日期区间)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatCacheService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatCacheService.class);
|
||||
private static final String KEY_PREFIX = "order-stat:read:";
|
||||
|
||||
private final OrderStatProperties properties;
|
||||
private final @NonNull RedisTemplate<String, Object> redisTemplate;
|
||||
|
||||
public OrderStatCacheService(OrderStatProperties properties,
|
||||
@NonNull 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 || value == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
redisTemplate.opsForValue().set(
|
||||
KEY_PREFIX + cacheKey,
|
||||
Objects.requireNonNull(value),
|
||||
ttlSeconds,
|
||||
TimeUnit.SECONDS);
|
||||
} catch (Exception e) {
|
||||
log.debug("order-stat cache put skip: {}", cacheKey, e);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> 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;
|
||||
}
|
||||
}
|
||||
-128
@@ -1,128 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 订单 CRUD 后触发汇总 refresh(事务提交后执行,避免读到未提交明细)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatCrudCoordinator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatCrudCoordinator.class);
|
||||
private static final ZoneId STAT_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final OrderStatRefreshService orderStatRefreshService;
|
||||
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
|
||||
|
||||
public OrderStatCrudCoordinator(OrderStatRefreshService orderStatRefreshService,
|
||||
OrderStatRefreshCoordinator orderStatRefreshCoordinator) {
|
||||
this.orderStatRefreshService = orderStatRefreshService;
|
||||
this.orderStatRefreshCoordinator = orderStatRefreshCoordinator;
|
||||
}
|
||||
|
||||
/** 单条创建/更新后:同步 refresh 涉及的自然日 */
|
||||
public void afterOrderSaved(OrderPO before, OrderPO after) {
|
||||
Set<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));
|
||||
}
|
||||
}
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 基于汇总表的概览 VO 组装(公司/店铺/商品概览读路径切换共用)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatOverviewAssembler {
|
||||
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
|
||||
public OrderStatOverviewAssembler(OrderStatReadFacade orderStatReadFacade,
|
||||
@Lazy CompanyOverviewService companyOverviewService) {
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
}
|
||||
|
||||
/** 公司全店概览(汇总表读路径) */
|
||||
public CompanyOverviewVO buildCompanyOverview(Long companyId, List<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;
|
||||
}
|
||||
}
|
||||
-192
@@ -1,192 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 统一读服务:按区间粒度路由日/月/年汇总表;{@code stat-source=order} 时由上层继续走明细聚合(Phase G 切换)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatQueryService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatQueryService.class);
|
||||
|
||||
/** ≤90 天走日表 */
|
||||
private static final int DAILY_THRESHOLD_DAYS = 90;
|
||||
/** ≤1095 天(约 3 年)走月表 */
|
||||
private static final int MONTHLY_THRESHOLD_DAYS = 1095;
|
||||
|
||||
private final OrderStatProperties properties;
|
||||
private final OrderStatQueryMapper orderStatQueryMapper;
|
||||
private final OrderStatRefreshCoordinator orderStatRefreshCoordinator;
|
||||
private final OrderMapper orderMapper;
|
||||
|
||||
public OrderStatQueryService(OrderStatProperties properties,
|
||||
OrderStatQueryMapper orderStatQueryMapper,
|
||||
OrderStatRefreshCoordinator orderStatRefreshCoordinator,
|
||||
OrderMapper orderMapper) {
|
||||
this.properties = properties;
|
||||
this.orderStatQueryMapper = orderStatQueryMapper;
|
||||
this.orderStatRefreshCoordinator = orderStatRefreshCoordinator;
|
||||
this.orderMapper = orderMapper;
|
||||
}
|
||||
|
||||
public boolean usesDailyStatSource() {
|
||||
return "daily".equalsIgnoreCase(properties.getStatSource());
|
||||
}
|
||||
|
||||
/** 店铺 KPI 合计(始终读日表) */
|
||||
public OrderStatMetricsDTO sumShopMetrics(Long companyId, List<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
|
||||
}
|
||||
}
|
||||
-341
@@ -1,341 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 读路径统一门面:{@code stat-source=daily} 走汇总表,否则回退 {@link OrderStatAggMapper} 扫明细。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatReadFacade {
|
||||
|
||||
private final OrderStatProperties properties;
|
||||
private final OrderStatQueryService orderStatQueryService;
|
||||
private final OrderStatQueryMapper orderStatQueryMapper;
|
||||
private final OrderStatAggMapper orderStatAggMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ShopService shopService;
|
||||
|
||||
public OrderStatReadFacade(OrderStatProperties properties,
|
||||
OrderStatQueryService orderStatQueryService,
|
||||
OrderStatQueryMapper orderStatQueryMapper,
|
||||
OrderStatAggMapper orderStatAggMapper,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ShopService shopService) {
|
||||
this.properties = properties;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.orderStatQueryMapper = orderStatQueryMapper;
|
||||
this.orderStatAggMapper = orderStatAggMapper;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.shopService = shopService;
|
||||
}
|
||||
|
||||
public boolean usesDailyStatSource() {
|
||||
return "daily".equalsIgnoreCase(properties.getStatSource());
|
||||
}
|
||||
|
||||
/** 工作台/概览共用:shop×product 聚合行 */
|
||||
public List<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, String> 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.setPlatformCode(platformByShop.get(m.getShopId()));
|
||||
r.setProductId(m.getProductId());
|
||||
r.setCategoryId(m.getCategoryId());
|
||||
r.setSalesAmount(m.getSalesAmount());
|
||||
r.setRefundAmount(m.getRefundAmount());
|
||||
r.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L);
|
||||
r.setSalesQuantitySum(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum().longValue() : 0L);
|
||||
r.setProductCost(m.getProductCost());
|
||||
r.setFreightCost(m.getFreightCost());
|
||||
r.setOtherCost(m.getOtherCost());
|
||||
r.setGmvAllStatus(nz(m.getGmvAmount()));
|
||||
r.setGmvOrderCount(m.getGmvOrderCount() != null ? m.getGmvOrderCount().longValue() : 0L);
|
||||
r.setGmvQuantitySum(m.getGmvQuantitySum() != null ? m.getGmvQuantitySum().longValue() : 0L);
|
||||
out.add(r);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public List<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 = orderStatusStatResolver.resolve(companyId);
|
||||
List<OrderStatAggMapper.ShopProductRow> rows = orderStatAggMapper.aggregateByShopProduct(
|
||||
companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59),
|
||||
OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat),
|
||||
OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat),
|
||||
OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat));
|
||||
OrderStatMetricsDTO dto = new OrderStatMetricsDTO();
|
||||
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO, gmv = BigDecimal.ZERO;
|
||||
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
|
||||
int cnt = 0, salesQty = 0, gmvCnt = 0, gmvQty = 0;
|
||||
for (OrderStatAggMapper.ShopProductRow r : rows) {
|
||||
sales = sales.add(nz(r.getSalesAmount()));
|
||||
refund = refund.add(nz(r.getRefundAmount()));
|
||||
gmv = gmv.add(nz(r.getGmvAllStatus()));
|
||||
pc = pc.add(nz(r.getProductCost()));
|
||||
fc = fc.add(nz(r.getFreightCost()));
|
||||
oc = oc.add(nz(r.getOtherCost()));
|
||||
cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0;
|
||||
salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0;
|
||||
gmvCnt += r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0;
|
||||
gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0;
|
||||
}
|
||||
dto.setSalesAmount(sales);
|
||||
dto.setRefundAmount(refund);
|
||||
dto.setSalesOrderCount(cnt);
|
||||
dto.setSalesQuantitySum(salesQty);
|
||||
dto.setGmvAmount(gmv);
|
||||
dto.setGmvOrderCount(gmvCnt);
|
||||
dto.setGmvQuantitySum(gmvQty);
|
||||
dto.setProductCost(pc);
|
||||
dto.setFreightCost(fc);
|
||||
dto.setOtherCost(oc);
|
||||
return dto;
|
||||
}
|
||||
return orderStatQueryService.sumShopMetrics(companyId, shopIds, startDate, endDate);
|
||||
}
|
||||
|
||||
public List<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, String> platformByShop(List<Long> shopIds) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return shopService.listByIds(shopIds).stream()
|
||||
.collect(Collectors.toMap(ShopPO::getId, s -> s.getPlatformCode(), (a, b) -> a));
|
||||
}
|
||||
|
||||
private enum Period { CUR, PREV, YOY }
|
||||
|
||||
private static void fillPeriodSlice(OrderStatAggMapper.PeriodKpiRow row, OrderStatMetricsDTO m, Period p) {
|
||||
switch (p) {
|
||||
case CUR -> {
|
||||
row.setCurSalesAmount(nz(m.getSalesAmount()));
|
||||
row.setCurOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L);
|
||||
row.setCurRefundAmount(nz(m.getRefundAmount()));
|
||||
row.setCurProductCost(nz(m.getProductCost()));
|
||||
row.setCurFreightCost(nz(m.getFreightCost()));
|
||||
row.setCurOtherCost(nz(m.getOtherCost()));
|
||||
row.setCurGmvAllStatus(nz(m.getGmvAmount()));
|
||||
}
|
||||
case PREV -> {
|
||||
row.setPrevSalesAmount(nz(m.getSalesAmount()));
|
||||
row.setPrevOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L);
|
||||
row.setPrevRefundAmount(nz(m.getRefundAmount()));
|
||||
row.setPrevProductCost(nz(m.getProductCost()));
|
||||
row.setPrevFreightCost(nz(m.getFreightCost()));
|
||||
row.setPrevOtherCost(nz(m.getOtherCost()));
|
||||
row.setPrevGmvAllStatus(nz(m.getGmvAmount()));
|
||||
}
|
||||
case YOY -> {
|
||||
row.setYoySalesAmount(nz(m.getSalesAmount()));
|
||||
row.setYoyOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L);
|
||||
row.setYoyRefundAmount(nz(m.getRefundAmount()));
|
||||
row.setYoyProductCost(nz(m.getProductCost()));
|
||||
row.setYoyFreightCost(nz(m.getFreightCost()));
|
||||
row.setYoyOtherCost(nz(m.getOtherCost()));
|
||||
row.setYoyGmvAllStatus(nz(m.getGmvAmount()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static LocalDateTime minTime(LocalDate... dates) {
|
||||
LocalDateTime min = dates[0].atStartOfDay();
|
||||
for (int i = 1; i < dates.length; i++) {
|
||||
LocalDateTime t = dates[i].atStartOfDay();
|
||||
if (t.isBefore(min)) {
|
||||
min = t;
|
||||
}
|
||||
}
|
||||
return min;
|
||||
}
|
||||
|
||||
private static LocalDateTime maxTime(LocalDate... dates) {
|
||||
LocalDateTime max = dates[0].atTime(23, 59, 59);
|
||||
for (int i = 1; i < dates.length; i++) {
|
||||
LocalDateTime t = dates[i].atTime(23, 59, 59);
|
||||
if (t.isAfter(max)) {
|
||||
max = t;
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
-114
@@ -1,114 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRebuildTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRebuildTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/**
|
||||
* 历史订单 backfill:按 shop × date 调用 {@link OrderStatRefreshService#refreshShopDay}。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatRebuildService extends ServiceImpl<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();
|
||||
}
|
||||
}
|
||||
-175
@@ -1,175 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* 汇总表 vs 明细聚合对账(抽样 shop×date)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatReconcileService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatReconcileService.class);
|
||||
private static final BigDecimal TOLERANCE = new BigDecimal("0.01");
|
||||
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
private final OrderStatAggMapper orderStatAggMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final OrderMapper orderMapper;
|
||||
private final ShopService shopService;
|
||||
|
||||
public OrderStatReconcileService(OrderStatReadFacade orderStatReadFacade,
|
||||
OrderStatAggMapper orderStatAggMapper,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
OrderMapper orderMapper,
|
||||
ShopService shopService) {
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
this.orderStatAggMapper = orderStatAggMapper;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.orderMapper = orderMapper;
|
||||
this.shopService = shopService;
|
||||
}
|
||||
|
||||
public ReconcileReport reconcileCompany(Long companyId, LocalDate startDate, LocalDate endDate, int sampleSize) {
|
||||
ReconcileReport report = new ReconcileReport();
|
||||
report.setCompanyId(companyId);
|
||||
report.setStartDate(startDate);
|
||||
report.setEndDate(endDate);
|
||||
if (!orderStatReadFacade.usesDailyStatSource()) {
|
||||
report.setMessage("stat-source=order,跳过对账");
|
||||
return report;
|
||||
}
|
||||
List<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),
|
||||
OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat),
|
||||
OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat),
|
||||
OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat));
|
||||
BigDecimal aggSales = BigDecimal.ZERO;
|
||||
for (OrderStatAggMapper.ShopProductRow r : rows) {
|
||||
aggSales = aggSales.add(nz(r.getSalesAmount()));
|
||||
}
|
||||
ReconcileItem item = new ReconcileItem();
|
||||
item.setShopId(shopId);
|
||||
item.setStatDate(d);
|
||||
item.setStatSales(nz(daily.getSalesAmount()));
|
||||
item.setAggSales(aggSales);
|
||||
item.setDiff(item.getStatSales().subtract(item.getAggSales()).abs());
|
||||
item.setMatch(item.getDiff().compareTo(TOLERANCE) <= 0);
|
||||
return item;
|
||||
}
|
||||
|
||||
private List<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 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; }
|
||||
}
|
||||
}
|
||||
-97
@@ -1,97 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.RefreshSource;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 汇总 refresh 入队与任务锁定(DB 队列,与导入消费者解耦)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatRefreshCoordinator extends ServiceImpl<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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-252
@@ -1,252 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatRefreshMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailyShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatDailySpecPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 单日单店重算:ec_order → 日汇总表,再触发月/年 rollup。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatRefreshService {
|
||||
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final OrderStatAggMapper orderStatAggMapper;
|
||||
private final OrderStatRefreshMapper orderStatRefreshMapper;
|
||||
private final OrderStatDailyMapper orderStatDailyMapper;
|
||||
private final OrderStatRollupService orderStatRollupService;
|
||||
private final ShopMapper shopMapper;
|
||||
|
||||
public OrderStatRefreshService(OrderStatusStatResolver orderStatusStatResolver,
|
||||
OrderStatAggMapper orderStatAggMapper,
|
||||
OrderStatRefreshMapper orderStatRefreshMapper,
|
||||
OrderStatDailyMapper orderStatDailyMapper,
|
||||
OrderStatRollupService orderStatRollupService,
|
||||
ShopMapper shopMapper) {
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.orderStatAggMapper = orderStatAggMapper;
|
||||
this.orderStatRefreshMapper = orderStatRefreshMapper;
|
||||
this.orderStatDailyMapper = orderStatDailyMapper;
|
||||
this.orderStatRollupService = orderStatRollupService;
|
||||
this.shopMapper = shopMapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 重算指定自然日的店铺/商品/规格日表,并 rollup 对应月、年。
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void refreshShopDay(Long companyId, Long shopId, LocalDate statDate) {
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
if (stat.isUnionEmpty()) {
|
||||
writeEmptyShopDay(companyId, shopId, statDate);
|
||||
orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate);
|
||||
orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate);
|
||||
orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate);
|
||||
return;
|
||||
}
|
||||
|
||||
LocalDateTime start = statDate.atStartOfDay();
|
||||
LocalDateTime end = statDate.atTime(23, 59, 59);
|
||||
List<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));
|
||||
|
||||
String platformCode = resolvePlatformCode(shopId);
|
||||
Integer gmvOrderCount = orderStatRefreshMapper.countGmvOrdersByShopDay(
|
||||
companyId, shopId, start, end);
|
||||
OrderStatDailyShopPO shopRow = buildShopRow(companyId, shopId, platformCode, statDate, productRows,
|
||||
gmvOrderCount != null ? gmvOrderCount : 0);
|
||||
orderStatDailyMapper.upsertDailyShop(shopRow);
|
||||
|
||||
orderStatDailyMapper.deleteDailyProduct(companyId, shopId, statDate);
|
||||
List<OrderStatDailyProductPO> dailyProducts = buildProductRows(companyId, shopId, statDate, productRows);
|
||||
if (!dailyProducts.isEmpty()) {
|
||||
orderStatDailyMapper.batchInsertDailyProduct(dailyProducts);
|
||||
}
|
||||
|
||||
orderStatDailyMapper.deleteDailySpec(companyId, shopId, statDate);
|
||||
List<OrderStatRefreshMapper.SpecDayRow> skuRows = orderStatRefreshMapper.aggregateSpecByShopDay(
|
||||
companyId, shopId, start, end,
|
||||
OrderStatParamHelper.unionList(stat),
|
||||
OrderStatParamHelper.salesList(stat),
|
||||
OrderStatParamHelper.refundList(stat),
|
||||
OrderStatParamHelper.productCostList(stat),
|
||||
OrderStatParamHelper.freightCostList(stat),
|
||||
OrderStatParamHelper.otherCostList(stat));
|
||||
List<OrderStatDailySpecPO> dailySpecs = buildSpecRows(companyId, shopId, statDate, skuRows);
|
||||
if (!dailySpecs.isEmpty()) {
|
||||
orderStatDailyMapper.batchInsertDailySpec(dailySpecs);
|
||||
}
|
||||
|
||||
orderStatRollupService.rollupAfterDailyChange(companyId, shopId, statDate);
|
||||
}
|
||||
|
||||
private String resolvePlatformCode(Long shopId) {
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
return shop != null ? shop.getPlatformCode() : null;
|
||||
}
|
||||
|
||||
private void writeEmptyShopDay(Long companyId, Long shopId, LocalDate statDate) {
|
||||
OrderStatDailyShopPO row = new OrderStatDailyShopPO();
|
||||
row.setCompanyId(companyId);
|
||||
row.setShopId(shopId);
|
||||
row.setPlatformCode(resolvePlatformCode(shopId));
|
||||
row.setStatDate(statDate);
|
||||
row.setSalesAmount(BigDecimal.ZERO);
|
||||
row.setRefundAmount(BigDecimal.ZERO);
|
||||
row.setSalesOrderCount(0);
|
||||
row.setSalesQuantitySum(0);
|
||||
row.setProductCost(BigDecimal.ZERO);
|
||||
row.setFreightCost(BigDecimal.ZERO);
|
||||
row.setOtherCost(BigDecimal.ZERO);
|
||||
row.setGmvAmount(BigDecimal.ZERO);
|
||||
row.setGmvOrderCount(0);
|
||||
row.setGmvQuantitySum(0);
|
||||
row.setStatVersion(0);
|
||||
orderStatDailyMapper.upsertDailyShop(row);
|
||||
}
|
||||
|
||||
private static OrderStatDailyShopPO buildShopRow(Long companyId, Long shopId, String platformCode,
|
||||
LocalDate statDate,
|
||||
List<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;
|
||||
int salesQty = 0;
|
||||
int gmvQty = 0;
|
||||
for (OrderStatAggMapper.ShopProductRow r : rows) {
|
||||
sales = sales.add(nz(r.getSalesAmount()));
|
||||
refund = refund.add(nz(r.getRefundAmount()));
|
||||
pc = pc.add(nz(r.getProductCost()));
|
||||
fc = fc.add(nz(r.getFreightCost()));
|
||||
oc = oc.add(nz(r.getOtherCost()));
|
||||
gmv = gmv.add(nz(r.getGmvAllStatus()));
|
||||
orderCount += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0;
|
||||
salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0;
|
||||
gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0;
|
||||
}
|
||||
OrderStatDailyShopPO row = new OrderStatDailyShopPO();
|
||||
row.setCompanyId(companyId);
|
||||
row.setShopId(shopId);
|
||||
row.setPlatformCode(platformCode);
|
||||
row.setStatDate(statDate);
|
||||
row.setSalesAmount(sales);
|
||||
row.setRefundAmount(refund);
|
||||
row.setSalesOrderCount(orderCount);
|
||||
row.setSalesQuantitySum(salesQty);
|
||||
row.setProductCost(pc);
|
||||
row.setFreightCost(fc);
|
||||
row.setOtherCost(oc);
|
||||
row.setGmvAmount(gmv);
|
||||
row.setGmvOrderCount(gmvOrderCount);
|
||||
row.setGmvQuantitySum(gmvQty);
|
||||
row.setStatVersion(0);
|
||||
return row;
|
||||
}
|
||||
|
||||
private static List<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.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0);
|
||||
p.setGmvAmount(nz(r.getGmvAllStatus()));
|
||||
p.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0);
|
||||
p.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0);
|
||||
p.setProductCost(nz(r.getProductCost()));
|
||||
p.setFreightCost(nz(r.getFreightCost()));
|
||||
p.setOtherCost(nz(r.getOtherCost()));
|
||||
p.setStatVersion(0);
|
||||
list.add(p);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static List<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.setProductSkuId(r.getProductSkuId() != null ? r.getProductSkuId() : 0L);
|
||||
s.setStatDate(statDate);
|
||||
s.setSalesAmount(nz(r.getSalesAmount()));
|
||||
s.setRefundAmount(nz(r.getRefundAmount()));
|
||||
s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0);
|
||||
s.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum() : 0);
|
||||
s.setGmvAmount(nz(r.getGmvAmount()));
|
||||
s.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0);
|
||||
s.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum() : 0);
|
||||
s.setProductCost(nz(r.getProductCost()));
|
||||
s.setFreightCost(nz(r.getFreightCost()));
|
||||
s.setOtherCost(nz(r.getOtherCost()));
|
||||
s.setStatVersion(0);
|
||||
list.add(s);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
private static boolean isAllZeroProductRow(OrderStatAggMapper.ShopProductRow r) {
|
||||
return nz(r.getSalesAmount()).signum() == 0
|
||||
&& nz(r.getRefundAmount()).signum() == 0
|
||||
&& nz(r.getGmvAllStatus()).signum() == 0
|
||||
&& (r.getOrderCount() == null || r.getOrderCount() == 0)
|
||||
&& (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0);
|
||||
}
|
||||
|
||||
private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) {
|
||||
return nz(r.getSalesAmount()).signum() == 0
|
||||
&& nz(r.getRefundAmount()).signum() == 0
|
||||
&& nz(r.getGmvAmount()).signum() == 0
|
||||
&& (r.getOrderCount() == null || r.getOrderCount() == 0)
|
||||
&& (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
-91
@@ -1,91 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.po.OrderStatRefreshQueuePO;
|
||||
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* 异步消费 ec_order_stat_refresh_queue(独立线程池,不与导入消费者共用)。
|
||||
*/
|
||||
@Service
|
||||
public class OrderStatRefreshWorker {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(OrderStatRefreshWorker.class);
|
||||
|
||||
private final OrderStatProperties properties;
|
||||
private final OrderStatRefreshCoordinator coordinator;
|
||||
private final ExecutorService executorService;
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
public OrderStatRefreshWorker(OrderStatProperties properties,
|
||||
OrderStatRefreshCoordinator coordinator) {
|
||||
this.properties = properties;
|
||||
this.coordinator = coordinator;
|
||||
int pool = Math.max(1, properties.getRefreshWorker().getPoolSize());
|
||||
this.executorService = Executors.newFixedThreadPool(pool);
|
||||
}
|
||||
|
||||
@jakarta.annotation.PostConstruct
|
||||
public void start() {
|
||||
if (!properties.getRefreshWorker().isEnabled()) {
|
||||
log.info("OrderStatRefreshWorker disabled by config");
|
||||
return;
|
||||
}
|
||||
if (running.compareAndSet(false, true)) {
|
||||
int pool = properties.getRefreshWorker().getPoolSize();
|
||||
for (int i = 0; i < pool; i++) {
|
||||
executorService.submit(this::pollLoop);
|
||||
}
|
||||
log.info("OrderStatRefreshWorker started, poolSize={}", pool);
|
||||
}
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
public void stop() {
|
||||
if (running.compareAndSet(true, false)) {
|
||||
executorService.shutdown();
|
||||
try {
|
||||
if (!executorService.awaitTermination(15, TimeUnit.SECONDS)) {
|
||||
executorService.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
executorService.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
log.info("OrderStatRefreshWorker stopped");
|
||||
}
|
||||
}
|
||||
|
||||
private void pollLoop() {
|
||||
long interval = Math.max(500L, properties.getRefreshWorker().getPollIntervalMs());
|
||||
while (running.get()) {
|
||||
try {
|
||||
OrderStatRefreshQueuePO item = coordinator.fetchAndLockPending();
|
||||
if (item != null) {
|
||||
coordinator.processQueueItem(item);
|
||||
} else {
|
||||
Thread.sleep(interval);
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("OrderStatRefreshWorker poll error", e);
|
||||
try {
|
||||
Thread.sleep(interval);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
-30
@@ -1,30 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatDailyMapper;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 日表变更后 rollup 月表、年表。 */
|
||||
@Service
|
||||
public class OrderStatRollupService {
|
||||
|
||||
private final OrderStatDailyMapper orderStatDailyMapper;
|
||||
|
||||
public OrderStatRollupService(OrderStatDailyMapper orderStatDailyMapper) {
|
||||
this.orderStatDailyMapper = orderStatDailyMapper;
|
||||
}
|
||||
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void rollupAfterDailyChange(Long companyId, Long shopId, LocalDate statDate) {
|
||||
LocalDate statMonth = statDate.withDayOfMonth(1);
|
||||
int statYear = statDate.getYear();
|
||||
orderStatDailyMapper.rollupMonthlyShop(companyId, shopId, statMonth);
|
||||
orderStatDailyMapper.rollupYearlyShop(companyId, shopId, statYear);
|
||||
orderStatDailyMapper.rollupMonthlyProduct(companyId, shopId, statMonth);
|
||||
orderStatDailyMapper.rollupYearlyProduct(companyId, shopId, statYear);
|
||||
orderStatDailyMapper.rollupMonthlySpec(companyId, shopId, statMonth);
|
||||
orderStatDailyMapper.rollupYearlySpec(companyId, shopId, statYear);
|
||||
}
|
||||
}
|
||||
-47
@@ -1,47 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/** 将 OrderStatusStatSets 转为 MyBatis IN 列表参数(状态码)。 */
|
||||
public final class OrderStatParamHelper {
|
||||
|
||||
private OrderStatParamHelper() {
|
||||
}
|
||||
|
||||
public static List<String> statusList(java.util.Collection<String> codes) {
|
||||
if (codes == null || codes.isEmpty()) {
|
||||
return List.of("__NONE__");
|
||||
}
|
||||
List<String> list = new ArrayList<>(codes);
|
||||
Collections.sort(list);
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<String> unionList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getUnionStatusCodes());
|
||||
}
|
||||
|
||||
public static List<String> salesList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getSalesCodes());
|
||||
}
|
||||
|
||||
public static List<String> refundList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getRefundCodes());
|
||||
}
|
||||
|
||||
public static List<String> productCostList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getProductCostCodes());
|
||||
}
|
||||
|
||||
public static List<String> freightCostList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getFreightCostCodes());
|
||||
}
|
||||
|
||||
public static List<String> otherCostList(OrderStatusStatSets stat) {
|
||||
return statusList(stat.getOtherCostCodes());
|
||||
}
|
||||
}
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support;
|
||||
|
||||
/**
|
||||
* 汇总 refresh 触发来源。
|
||||
*/
|
||||
public enum RefreshSource {
|
||||
IMPORT,
|
||||
CRUD,
|
||||
STATUS_CHANGE,
|
||||
MANUAL,
|
||||
BACKFILL,
|
||||
AUTO_MISS
|
||||
}
|
||||
-16
@@ -1,16 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 待刷新维度:(公司, 店铺, 自然日)。
|
||||
*/
|
||||
public record StatDirtyKey(Long companyId, Long shopId, LocalDate statDate) {
|
||||
|
||||
public StatDirtyKey {
|
||||
Objects.requireNonNull(companyId, "companyId");
|
||||
Objects.requireNonNull(shopId, "shopId");
|
||||
Objects.requireNonNull(statDate, "statDate");
|
||||
}
|
||||
}
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 概览/工作台 SQL 聚合行类型(原 OrderStatAggMapper 内嵌类,供 buildWorkbenchSummaryTablesFromAgg 等复用)。
|
||||
*/
|
||||
public final class OverviewAggRows {
|
||||
|
||||
private OverviewAggRows() {
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ShopProductRow {
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BigDecimal salesAmount;
|
||||
private Long orderCount;
|
||||
private Long salesQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
private BigDecimal gmvAllStatus;
|
||||
private Long gmvOrderCount;
|
||||
private Long gmvQuantitySum;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class DailyRow {
|
||||
private LocalDate statDate;
|
||||
private BigDecimal salesAmount;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class FeeKpiRow {
|
||||
private BigDecimal curAmount;
|
||||
private BigDecimal prevAmount;
|
||||
private BigDecimal yoyAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PromotionRow {
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BigDecimal feeAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BrushRow {
|
||||
private Long shopId;
|
||||
private BigDecimal brushAmount;
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.ecom.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.model.po.BrushOrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO;
|
||||
@@ -59,9 +59,9 @@ public interface CompanyOverviewService {
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OrderStatAggMapper.ShopProductRow> orderRows,
|
||||
List<OrderStatAggMapper.PromotionRow> promotionRows,
|
||||
List<OrderStatAggMapper.BrushRow> brushRows,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate);
|
||||
}
|
||||
|
||||
+13
-30
@@ -5,9 +5,7 @@ import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatOverviewAssembler;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyOverviewQueryDTO;
|
||||
@@ -68,8 +66,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final CategoryService categoryService;
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
private final OrderStatOverviewAssembler orderStatOverviewAssembler;
|
||||
|
||||
public CompanyOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
OrderMapper orderMapper,
|
||||
@@ -81,9 +77,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ProductMapper productMapper,
|
||||
ProductSkuMapper productSkuMapper,
|
||||
CategoryService categoryService,
|
||||
OrderStatReadFacade orderStatReadFacade,
|
||||
OrderStatOverviewAssembler orderStatOverviewAssembler) {
|
||||
CategoryService categoryService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.orderMapper = orderMapper;
|
||||
this.orderItemMapper = orderItemMapper;
|
||||
@@ -95,8 +89,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
this.productMapper = productMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.categoryService = categoryService;
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
this.orderStatOverviewAssembler = orderStatOverviewAssembler;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -160,15 +152,6 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
throw new BusinessException("当前公司没有店铺");
|
||||
}
|
||||
|
||||
// 汇总表读路径
|
||||
if (orderStatReadFacade.usesDailyStatSource()) {
|
||||
CompanyOverviewVO statVo = orderStatOverviewAssembler.buildCompanyOverview(
|
||||
companyId, shops, startDate, endDate, taxRate, stat);
|
||||
calculateTargetData(statVo, companyId, startDate, endDate,
|
||||
statVo.getTotalSalesAmount(), statVo.getTotalOrderCount());
|
||||
return statVo;
|
||||
}
|
||||
|
||||
// 查询订单数据(所有店铺)
|
||||
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
|
||||
orderWrapper.eq(OrderPO::getCompanyId, companyId)
|
||||
@@ -1814,9 +1797,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OrderStatAggMapper.ShopProductRow> orderRows,
|
||||
List<OrderStatAggMapper.PromotionRow> promotionRows,
|
||||
List<OrderStatAggMapper.BrushRow> brushRows,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate) {
|
||||
synchronized (this) {
|
||||
@@ -1834,9 +1817,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal(
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OrderStatAggMapper.ShopProductRow> orderRows,
|
||||
List<OrderStatAggMapper.PromotionRow> promotionRows,
|
||||
List<OrderStatAggMapper.BrushRow> brushRows,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate) {
|
||||
|
||||
@@ -1847,7 +1830,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
Map<Long, Map<Long, BigDecimal>> productSalesByShop = new HashMap<>();
|
||||
Map<Long, Long> productCategoryMap = new HashMap<>();
|
||||
|
||||
for (OrderStatAggMapper.ShopProductRow row : orderRows) {
|
||||
for (OverviewAggRows.ShopProductRow row : orderRows) {
|
||||
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
long categoryKey = productId <= 0 ? -1L
|
||||
@@ -1867,7 +1850,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
Map<Long, BigDecimal> directPromoByProduct = new HashMap<>();
|
||||
Map<Long, BigDecimal> directPromoByCategory = new HashMap<>();
|
||||
BigDecimal ratioPool = BigDecimal.ZERO;
|
||||
for (OrderStatAggMapper.PromotionRow fee : promotionRows) {
|
||||
for (OverviewAggRows.PromotionRow fee : promotionRows) {
|
||||
BigDecimal amt = nz(fee.getFeeAmount());
|
||||
promoByShop.merge(fee.getShopId(), amt, BigDecimal::add);
|
||||
if (fee.getProductId() != null) {
|
||||
@@ -1879,7 +1862,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
}
|
||||
}
|
||||
Map<Long, BigDecimal> brushByShop = new HashMap<>();
|
||||
for (OrderStatAggMapper.BrushRow b : brushRows) {
|
||||
for (OverviewAggRows.BrushRow b : brushRows) {
|
||||
brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add);
|
||||
}
|
||||
BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
@@ -2120,7 +2103,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.orderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
private static void mergeAgg(Map<Long, AggMetrics> map, long key, OrderStatAggMapper.ShopProductRow row) {
|
||||
private static void mergeAgg(Map<Long, AggMetrics> map, long key, OverviewAggRows.ShopProductRow row) {
|
||||
map.merge(key, AggMetrics.from(row), AggMetrics::merge);
|
||||
}
|
||||
|
||||
@@ -2322,7 +2305,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
return sales.subtract(orderCost()).subtract(refund);
|
||||
}
|
||||
|
||||
static AggMetrics from(OrderStatAggMapper.ShopProductRow row) {
|
||||
static AggMetrics from(OverviewAggRows.ShopProductRow row) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = nz(row.getSalesAmount());
|
||||
a.gmv = nz(row.getGmvAllStatus());
|
||||
|
||||
-104
@@ -7,9 +7,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.brushorder.mapper.BrushOrderMapper
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.mapper.PromotionFeeMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.ShopOverviewQueryDTO;
|
||||
@@ -69,7 +66,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final CategoryService categoryService;
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
|
||||
public ShopOverviewStatisticsServiceImpl(CurrentUserContext currentUserContext,
|
||||
@@ -83,7 +79,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
|
||||
ProductSkuMapper productSkuMapper,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
CategoryService categoryService,
|
||||
OrderStatReadFacade orderStatReadFacade,
|
||||
CompanyOverviewService companyOverviewService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.orderMapper = orderMapper;
|
||||
@@ -96,7 +91,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.categoryService = categoryService;
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
}
|
||||
|
||||
@@ -145,10 +139,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
|
||||
throw new BusinessException("店铺不存在");
|
||||
}
|
||||
|
||||
if (orderStatReadFacade.usesDailyStatSource()) {
|
||||
return getShopOverviewFromStat(queryDTO, companyId, shop, startDate, endDate, stat);
|
||||
}
|
||||
|
||||
// 查询订单数据(该店铺)
|
||||
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
|
||||
orderWrapper.eq(OrderPO::getCompanyId, companyId)
|
||||
@@ -1013,100 +1003,6 @@ public class ShopOverviewStatisticsServiceImpl implements ShopOverviewStatistics
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 汇总表读路径:单店概览 */
|
||||
private ShopOverviewStatisticsVO getShopOverviewFromStat(ShopOverviewQueryDTO queryDTO,
|
||||
Long companyId, ShopPO shop,
|
||||
LocalDate startDate, LocalDate endDate,
|
||||
OrderStatusStatSets stat) {
|
||||
List<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();
|
||||
|
||||
+1
-213
@@ -8,8 +8,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.support.OrderOverviewSupport;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.po.ProductPO;
|
||||
@@ -50,7 +48,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ShopService shopService;
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
|
||||
public ProductOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
OrderMapper orderMapper,
|
||||
@@ -60,8 +57,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
ProductService productService,
|
||||
ProductSkuMapper productSkuMapper,
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ShopService shopService,
|
||||
OrderStatReadFacade orderStatReadFacade) {
|
||||
ShopService shopService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.orderMapper = orderMapper;
|
||||
this.orderItemMapper = orderItemMapper;
|
||||
@@ -71,7 +67,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.shopService = shopService;
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
}
|
||||
|
||||
private void applyProductOverviewOrderScope(LambdaQueryWrapper<OrderPO> wrapper,
|
||||
@@ -144,11 +139,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
List<String> unionStatusCodes = stat.getUnionStatusCodes();
|
||||
|
||||
if (orderStatReadFacade.usesDailyStatSource()) {
|
||||
return getProductOverviewFromStat(queryDTO, companyId, product, filterShopId,
|
||||
startDate, endDate, taxRate, stat);
|
||||
}
|
||||
|
||||
// 查询订单数据
|
||||
LambdaQueryWrapper<OrderPO> orderWrapper = new LambdaQueryWrapper<>();
|
||||
applyProductOverviewOrderScope(orderWrapper, companyId, queryDTO.getProductId(), filterShopId,
|
||||
@@ -830,208 +820,6 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/** 汇总表读路径:商品概览 */
|
||||
private ProductOverviewVO getProductOverviewFromStat(ProductOverviewQueryDTO queryDTO,
|
||||
Long companyId, ProductPO product,
|
||||
Long filterShopId,
|
||||
LocalDate startDate, LocalDate endDate,
|
||||
BigDecimal taxRate, OrderStatusStatSets stat) {
|
||||
List<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> skuRows,
|
||||
BigDecimal taxRate,
|
||||
BigDecimal totalPromo,
|
||||
BigDecimal totalSales) {
|
||||
if (skuRows == null || skuRows.isEmpty()) {
|
||||
return buildEmptySpecSummary();
|
||||
}
|
||||
Set<Long> skuIds = skuRows.stream().map(OrderStatMetricsDTO::getProductSkuId)
|
||||
.filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
Map<Long, ProductSkuPO> skuMap = productSkuMapper.selectBatchIds(skuIds).stream()
|
||||
.collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a));
|
||||
|
||||
List<ProductOverviewVO.SpecSummaryItem> items = new ArrayList<>();
|
||||
for (OrderStatMetricsDTO m : skuRows) {
|
||||
ProductSkuPO spec = skuMap.get(m.getProductSkuId());
|
||||
BigDecimal sales = nz(m.getSalesAmount());
|
||||
BigDecimal promoShare = totalSales.signum() > 0
|
||||
? totalPromo.multiply(sales).divide(totalSales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
|
||||
ProductOverviewVO.SpecSummaryItem item = new ProductOverviewVO.SpecSummaryItem();
|
||||
item.setSkuId(m.getProductSkuId());
|
||||
item.setSkuName(spec != null ? spec.getName() : "未知规格");
|
||||
item.setSkuCode(spec != null ? spec.getSkuCode() : null);
|
||||
item.setSalesAmount(sales);
|
||||
item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0);
|
||||
item.setQuantity(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0);
|
||||
item.setProductCost(nz(m.getProductCost()));
|
||||
item.setShippingCost(nz(m.getFreightCost()));
|
||||
item.setOtherCost(nz(m.getOtherCost()));
|
||||
item.setOrderCost(item.getProductCost().add(item.getShippingCost()).add(item.getOtherCost()));
|
||||
item.setRefundAmount(nz(m.getRefundAmount()));
|
||||
item.setPromotionFee(promoShare);
|
||||
item.setSalesTaxAmount(salesTaxOnNetSales(sales, item.getRefundAmount(), taxRate));
|
||||
item.setProfitAfterTax(sales.subtract(item.getOrderCost()).subtract(item.getRefundAmount())
|
||||
.subtract(promoShare).subtract(item.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
items.add(item);
|
||||
}
|
||||
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
|
||||
summary.setList(items);
|
||||
summary.setTotal(buildSpecTotal(items));
|
||||
return summary;
|
||||
}
|
||||
|
||||
private static ProductOverviewVO.SpecSummaryTotal buildSpecTotal(List<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> skuRows) {
|
||||
if (skuRows == null) {
|
||||
return List.of();
|
||||
}
|
||||
Set<Long> skuIds = skuRows.stream().map(OrderStatMetricsDTO::getProductSkuId)
|
||||
.filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
Map<Long, ProductSkuPO> skuMap = skuIds.isEmpty() ? Map.of()
|
||||
: productSkuMapper.selectBatchIds(skuIds).stream()
|
||||
.collect(Collectors.toMap(ProductSkuPO::getId, s -> s, (a, b) -> a));
|
||||
return skuRows.stream()
|
||||
.sorted(Comparator.comparingInt((OrderStatMetricsDTO m) ->
|
||||
m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0).reversed())
|
||||
.limit(10)
|
||||
.map(m -> {
|
||||
ProductSkuPO spec = skuMap.get(m.getProductSkuId());
|
||||
ProductOverviewVO.SpecSalesRankItem item = new ProductOverviewVO.SpecSalesRankItem();
|
||||
item.setSkuId(m.getProductSkuId());
|
||||
item.setSkuName(spec != null ? spec.getName() : "未知规格");
|
||||
item.setSkuCode(spec != null ? spec.getSkuCode() : null);
|
||||
item.setOrderCount(m.getSalesOrderCount());
|
||||
item.setSalesAmount(nz(m.getSalesAmount()));
|
||||
return item;
|
||||
}).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static BigDecimal growthPct(BigDecimal cur, BigDecimal prev) {
|
||||
if (prev.signum() > 0) {
|
||||
return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100))
|
||||
|
||||
+1
-20
@@ -13,9 +13,6 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.PageQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.common.model.vo.PageResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.OrderShopStatDateRow;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatCrudCoordinator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.StatDirtyKey;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.CreateProductSkuDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.product.model.dto.ProductSkuFilterDTO;
|
||||
@@ -31,10 +28,8 @@ import top.xyquan.ecomdmbbackend.modules.ecom.product.service.ProductSkuService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -49,17 +44,14 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
||||
private final ProductService productService;
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderStatCrudCoordinator orderStatCrudCoordinator;
|
||||
|
||||
public ProductSkuServiceImpl(CurrentUserContext currentUserContext, ProductService productService,
|
||||
ProductSkuCostService productSkuCostService,
|
||||
OrderMapper orderMapper,
|
||||
OrderStatCrudCoordinator orderStatCrudCoordinator) {
|
||||
OrderMapper orderMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.productService = productService;
|
||||
this.productSkuCostService = productSkuCostService;
|
||||
this.orderMapper = orderMapper;
|
||||
this.orderStatCrudCoordinator = orderStatCrudCoordinator;
|
||||
}
|
||||
|
||||
/** SKU 落库后尝试挂 orphan 订单;订单表不存在时跳过 */
|
||||
@@ -78,18 +70,7 @@ public class ProductSkuServiceImpl extends ServiceImpl<ProductSkuMapper, Product
|
||||
}
|
||||
try {
|
||||
String code = skuCode.trim();
|
||||
List<OrderShopStatDateRow> affected =
|
||||
orderMapper.selectOrphanOrderStatDatesBySkuCode(companyId, code);
|
||||
orderMapper.linkOrdersBySkuCodeWhenSkuIdNull(companyId, code, productSkuId);
|
||||
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);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.warn("挂 orphan 订单跳过(订单表可能不存在): {}", ex.getMessage());
|
||||
}
|
||||
|
||||
+1
-8
@@ -17,7 +17,6 @@ import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.dto.UpdatePromotio
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.po.PromotionFeePO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.BatchImportPromotionFeeResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.model.vo.PromotionFeeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.FeeStatCrudCoordinator;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.promotion.service.PromotionFeeTypeService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
@@ -43,22 +42,19 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
|
||||
private final PromotionFeeTypeService promotionFeeTypeService;
|
||||
private final ProductService productService;
|
||||
private final CategoryService categoryService;
|
||||
private final FeeStatCrudCoordinator feeStatCrudCoordinator;
|
||||
|
||||
public PromotionFeeServiceImpl(PromotionFeeMapper promotionFeeMapper,
|
||||
CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
PromotionFeeTypeService promotionFeeTypeService,
|
||||
ProductService productService,
|
||||
CategoryService categoryService,
|
||||
FeeStatCrudCoordinator feeStatCrudCoordinator) {
|
||||
CategoryService categoryService) {
|
||||
this.promotionFeeMapper = promotionFeeMapper;
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.promotionFeeTypeService = promotionFeeTypeService;
|
||||
this.productService = productService;
|
||||
this.categoryService = categoryService;
|
||||
this.feeStatCrudCoordinator = feeStatCrudCoordinator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -77,7 +73,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
|
||||
po.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
|
||||
promotionFeeMapper.insert(po);
|
||||
feeStatCrudCoordinator.afterPromotionFeeSaved(null, po);
|
||||
return po.getId();
|
||||
}
|
||||
|
||||
@@ -99,7 +94,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
|
||||
po.setUpdateBy(currentUserContext.getCurrentUserId());
|
||||
po.setCompanyId(companyId);
|
||||
promotionFeeMapper.updateById(po);
|
||||
feeStatCrudCoordinator.afterPromotionFeeSaved(existing, po);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -115,7 +109,6 @@ public class PromotionFeeServiceImpl implements PromotionFeeService {
|
||||
throw new BusinessException("推广费记录不存在");
|
||||
}
|
||||
promotionFeeMapper.deleteById(id);
|
||||
feeStatCrudCoordinator.afterPromotionFeeDeleted(existing);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+6
-21
@@ -3,10 +3,7 @@ package top.xyquan.ecomdmbbackend.modules.ecom.workbench.service.impl;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.dto.PlatformExportDTO;
|
||||
@@ -38,27 +35,21 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopService shopService;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final ExportService exportService;
|
||||
private final CategoryExportExcelService categoryExportExcelService;
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
|
||||
public WorkbenchExportServiceImpl(
|
||||
CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
ExportService exportService,
|
||||
CategoryExportExcelService categoryExportExcelService,
|
||||
OrderStatReadFacade orderStatReadFacade) {
|
||||
CategoryExportExcelService categoryExportExcelService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.exportService = exportService;
|
||||
this.categoryExportExcelService = categoryExportExcelService;
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,24 +120,18 @@ public class WorkbenchExportServiceImpl implements WorkbenchExportService {
|
||||
private CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
DateRange range = parseDateRange(toQuery(dto));
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
|
||||
List<ShopPO> shops = loadFilteredShops(companyId, dto.getPlatformCode(), dto.getShopId());
|
||||
if (shops.isEmpty()) {
|
||||
throw new BusinessException("没有可导出的店铺");
|
||||
}
|
||||
List<Long> shopIds = shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
|
||||
|
||||
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.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, orderRows, promotionRows, brushRows,
|
||||
taxRate, companyId, shops,
|
||||
List.<OverviewAggRows.ShopProductRow>of(),
|
||||
List.<OverviewAggRows.PromotionRow>of(),
|
||||
List.<OverviewAggRows.BrushRow>of(),
|
||||
range.startDate(), range.endDate());
|
||||
}
|
||||
|
||||
|
||||
+25
-64
@@ -5,9 +5,7 @@ import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ecom.overview.model.vo.CompanyOverviewVO;
|
||||
@@ -75,7 +73,6 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ProductMapper productMapper;
|
||||
private final CategoryService categoryService;
|
||||
private final OrderStatReadFacade orderStatReadFacade;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
|
||||
public WorkbenchServiceImpl(CurrentUserContext currentUserContext,
|
||||
@@ -83,14 +80,12 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ProductMapper productMapper,
|
||||
CategoryService categoryService,
|
||||
OrderStatReadFacade orderStatReadFacade,
|
||||
CompanyOverviewService companyOverviewService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.productMapper = productMapper;
|
||||
this.categoryService = categoryService;
|
||||
this.orderStatReadFacade = orderStatReadFacade;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
}
|
||||
|
||||
@@ -203,65 +198,31 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
return new ShopContext(taxRate, companyId, range, stat, shops, shopIds, shopById);
|
||||
}
|
||||
|
||||
/** 当前区间 SQL-1/2/4/5(汇总表或明细回退) */
|
||||
/** 订单统计读模型已移除:返回空聚合,KPI/趋势降级为 0 */
|
||||
private SqlAggBundle loadSqlAgg(ShopContext ctx) {
|
||||
LocalDate start = ctx.range().startDate();
|
||||
LocalDate end = ctx.range().endDate();
|
||||
List<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);
|
||||
return new SqlAggBundle(Collections.emptyList(), Collections.emptyList(),
|
||||
Collections.emptyList(), Collections.emptyList());
|
||||
}
|
||||
|
||||
/** 环比/同比:店铺汇总表 + 各段推广/刷单 */
|
||||
/** 环比/同比:统计读模型移除后各段均为 0 */
|
||||
private ComparePeriodBundle loadCompareFromSql(ShopContext ctx) {
|
||||
DateRange lastRange = lastMonthSameSpan(ctx.range());
|
||||
DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1));
|
||||
|
||||
LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate());
|
||||
LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate());
|
||||
OrderStatAggMapper.FeeKpiRow promoKpi = orderStatReadFacade.loadPromotionPeriodKpi(
|
||||
ctx.companyId(), ctx.shopIds(), feeScanStart, feeScanEnd,
|
||||
ctx.range().startDate(), ctx.range().endDate(),
|
||||
lastRange.startDate(), lastRange.endDate(),
|
||||
yoyRange.startDate(), yoyRange.endDate());
|
||||
OrderStatAggMapper.FeeKpiRow brushKpi = orderStatReadFacade.loadBrushPeriodKpi(
|
||||
ctx.companyId(), ctx.shopIds(),
|
||||
minTime(lastRange.startDateTime(), yoyRange.startDateTime(), ctx.range().startDateTime()),
|
||||
maxTime(lastRange.endDateTime(), yoyRange.endDateTime(), ctx.range().endDateTime()),
|
||||
ctx.range().startDateTime(), ctx.range().endDateTime(),
|
||||
lastRange.startDateTime(), lastRange.endDateTime(),
|
||||
yoyRange.startDateTime(), yoyRange.endDateTime());
|
||||
|
||||
Totals prev = buildShopPeriodTotals(ctx, lastRange, nz(promoKpi.getPrevAmount()), nz(brushKpi.getPrevAmount()));
|
||||
Totals yoy = buildShopPeriodTotals(ctx, yoyRange, nz(promoKpi.getYoyAmount()), nz(brushKpi.getYoyAmount()));
|
||||
Totals prev = buildShopPeriodTotals(ctx, lastRange, BigDecimal.ZERO, BigDecimal.ZERO);
|
||||
Totals yoy = buildShopPeriodTotals(ctx, yoyRange, BigDecimal.ZERO, BigDecimal.ZERO);
|
||||
return new ComparePeriodBundle(lastRange, yoyRange, prev, yoy);
|
||||
}
|
||||
|
||||
/** 单时间段店铺 KPI:读 ec_order_stat_daily_shop 合计 */
|
||||
/** 单时间段店铺 KPI:统计读模型移除后返回 0 */
|
||||
private Totals buildShopPeriodTotals(ShopContext ctx, DateRange range, BigDecimal promotion, BigDecimal brush) {
|
||||
OrderStatMetricsDTO m = orderStatReadFacade.sumShopMetrics(
|
||||
ctx.companyId(), ctx.shopIds(), range.startDate(), range.endDate());
|
||||
return buildTotals(
|
||||
nz(m.getSalesAmount()), nz(m.getRefundAmount()),
|
||||
nz(m.getProductCost()), nz(m.getFreightCost()), nz(m.getOtherCost()),
|
||||
promotion, brush, ctx.taxRate(),
|
||||
m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0,
|
||||
m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0,
|
||||
nz(m.getGmvAmount()),
|
||||
m.getGmvOrderCount() != null ? m.getGmvOrderCount() : 0,
|
||||
m.getGmvQuantitySum() != null ? m.getGmvQuantitySum() : 0);
|
||||
return buildTotals(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
|
||||
promotion, brush, ctx.taxRate(), 0, 0, BigDecimal.ZERO, 0, 0);
|
||||
}
|
||||
|
||||
private WorkbenchFinancePanelVO buildFinancePanelFromSql(ShopContext ctx, Totals cur,
|
||||
ComparePeriodBundle compare, SqlAggBundle agg) {
|
||||
Map<String, Agg> platformAgg = new HashMap<>();
|
||||
for (OrderStatAggMapper.ShopProductRow row : agg.orderRows()) {
|
||||
for (OverviewAggRows.ShopProductRow row : agg.orderRows()) {
|
||||
String pk = blankPlatformKey(row.getPlatformCode());
|
||||
platformAgg.computeIfAbsent(pk, k -> new Agg()).addFromAggRow(row);
|
||||
}
|
||||
@@ -276,7 +237,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private DimensionAggMaps aggregateDimensionsFromSql(List<OrderStatAggMapper.ShopProductRow> rows, ShopContext ctx) {
|
||||
private DimensionAggMaps aggregateDimensionsFromSql(List<OverviewAggRows.ShopProductRow> rows, ShopContext ctx) {
|
||||
Map<String, Agg> platformAgg = new HashMap<>();
|
||||
Map<String, Agg> shopAgg = new HashMap<>();
|
||||
Map<String, Agg> categoryAgg = new HashMap<>();
|
||||
@@ -284,7 +245,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
Set<Long> productIds = new HashSet<>();
|
||||
Set<Long> categoryIds = new HashSet<>();
|
||||
|
||||
for (OrderStatAggMapper.ShopProductRow row : rows) {
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
String platformKey = blankPlatformKey(row.getPlatformCode());
|
||||
long shopKey = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
@@ -307,12 +268,12 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
loadPlatformNames(ctx.shops()), categoryNames, productById, ctx.shopById());
|
||||
}
|
||||
|
||||
private Totals totalsFromOrderRows(List<OrderStatAggMapper.ShopProductRow> rows,
|
||||
private Totals totalsFromOrderRows(List<OverviewAggRows.ShopProductRow> rows,
|
||||
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate) {
|
||||
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO;
|
||||
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
|
||||
int orderCount = 0;
|
||||
for (OrderStatAggMapper.ShopProductRow row : rows) {
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
sales = sales.add(nz(row.getSalesAmount()));
|
||||
refund = refund.add(nz(row.getRefundAmount()));
|
||||
pc = pc.add(nz(row.getProductCost()));
|
||||
@@ -345,10 +306,10 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
aov, gmvAov, salesPiecePrice, gmvPiecePrice);
|
||||
}
|
||||
|
||||
private List<WorkbenchTrendPointVO> buildTrendFromDaily(List<OrderStatAggMapper.DailyRow> dailyRows,
|
||||
private List<WorkbenchTrendPointVO> buildTrendFromDaily(List<OverviewAggRows.DailyRow> dailyRows,
|
||||
DateRange range, Totals periodTotals) {
|
||||
Map<LocalDate, OrderStatAggMapper.DailyRow> byDay = new HashMap<>();
|
||||
for (OrderStatAggMapper.DailyRow row : dailyRows) {
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
|
||||
for (OverviewAggRows.DailyRow row : dailyRows) {
|
||||
if (row.getStatDate() != null) {
|
||||
byDay.put(row.getStatDate(), row);
|
||||
}
|
||||
@@ -360,7 +321,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
}
|
||||
List<WorkbenchTrendPointVO> list = new ArrayList<>();
|
||||
for (LocalDate d = range.startDate(); !d.isAfter(range.endDate()); d = d.plusDays(1)) {
|
||||
OrderStatAggMapper.DailyRow row = byDay.get(d);
|
||||
OverviewAggRows.DailyRow row = byDay.get(d);
|
||||
BigDecimal sales = row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO;
|
||||
BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO;
|
||||
BigDecimal cost = row != null
|
||||
@@ -391,7 +352,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private static BigDecimal dayNetSales(OrderStatAggMapper.DailyRow row) {
|
||||
private static BigDecimal dayNetSales(OverviewAggRows.DailyRow row) {
|
||||
if (row == null) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
@@ -442,10 +403,10 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private record SqlAggBundle(List<OrderStatAggMapper.ShopProductRow> orderRows,
|
||||
List<OrderStatAggMapper.DailyRow> dailyRows,
|
||||
List<OrderStatAggMapper.PromotionRow> promotionRows,
|
||||
List<OrderStatAggMapper.BrushRow> brushRows) {
|
||||
private record SqlAggBundle(List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.DailyRow> dailyRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows) {
|
||||
BigDecimal promoTotal() {
|
||||
return promotionRows.stream().map(r -> nz(r.getFeeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
}
|
||||
@@ -936,7 +897,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
|
||||
BigDecimal cost = BigDecimal.ZERO;
|
||||
|
||||
/** 累加 SQL 聚合行 */
|
||||
void addFromAggRow(OrderStatAggMapper.ShopProductRow row) {
|
||||
void addFromAggRow(OverviewAggRows.ShopProductRow row) {
|
||||
sales = sales.add(nz(row.getSalesAmount()));
|
||||
refund = refund.add(nz(row.getRefundAmount()));
|
||||
cost = cost.add(nz(row.getProductCost())).add(nz(row.getFreightCost())).add(nz(row.getOtherCost()));
|
||||
|
||||
Reference in New Issue
Block a user