refactor: 重构bi计算侧口径,移除原有销售口径补齐退款口径

This commit is contained in:
2026-08-25 14:47:47 +08:00
parent 53bb8a32fd
commit ea86cab0a9
38 changed files with 498 additions and 365 deletions
@@ -0,0 +1,60 @@
// Navicat MongoDB 查询窗口可直接执行(连到正确库后,三段可依次或一起执行)
// 去掉 sales* 三字段(净销售改为读侧 deal − refund 推导)
// 执行后请在前端对相关店铺触发一次 BI 全量重算,以补齐 refundOrderCount / refundQuantitySum
// 并按新成交口径(不含已取消/未知)重建日文档
db.bi_order_stat_daily_shop.updateMany(
{
$or: [
{ salesAmount: { $exists: true } },
{ salesOrderCount: { $exists: true } },
{ salesQuantitySum: { $exists: true } }
]
},
{
$unset: {
salesAmount: "",
salesOrderCount: "",
salesQuantitySum: ""
}
}
);
db.bi_order_stat_daily_product.updateMany(
{
$or: [
{ salesAmount: { $exists: true } },
{ salesOrderCount: { $exists: true } },
{ salesQuantitySum: { $exists: true } }
]
},
{
$unset: {
salesAmount: "",
salesOrderCount: "",
salesQuantitySum: ""
}
}
);
db.bi_order_stat_daily_sku.updateMany(
{
$or: [
{ salesAmount: { $exists: true } },
{ salesOrderCount: { $exists: true } },
{ salesQuantitySum: { $exists: true } }
]
},
{
$unset: {
salesAmount: "",
salesOrderCount: "",
salesQuantitySum: ""
}
}
);
// 可选校验(期望均为 0)
// db.bi_order_stat_daily_shop.countDocuments({ salesAmount: { $exists: true } })
// db.bi_order_stat_daily_product.countDocuments({ salesAmount: { $exists: true } })
// db.bi_order_stat_daily_sku.countDocuments({ salesAmount: { $exists: true } })
@@ -8,16 +8,13 @@ import lombok.NoArgsConstructor;
import java.math.BigDecimal; import java.math.BigDecimal;
/** 单维度指标增量(可正可负) */ /** 单维度指标增量(可正可负);净销售由读侧「成交 − 退款」推导,不存 sales*。 */
@Data @Data
@Builder @Builder
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor @AllArgsConstructor
public class BiStatMetricDelta { public class BiStatMetricDelta {
private BigDecimal salesAmount;
private Integer salesOrderCount;
private Integer salesQuantitySum;
/** JsonAlias:兼容迁移前队列中仍带 gmv* 的旧消息 */ /** JsonAlias:兼容迁移前队列中仍带 gmv* 的旧消息 */
@JsonAlias("gmvAmount") @JsonAlias("gmvAmount")
private BigDecimal dealAmount; private BigDecimal dealAmount;
@@ -26,6 +23,8 @@ public class BiStatMetricDelta {
@JsonAlias("gmvQuantitySum") @JsonAlias("gmvQuantitySum")
private Integer dealQuantitySum; private Integer dealQuantitySum;
private BigDecimal refundAmount; private BigDecimal refundAmount;
private Integer refundOrderCount;
private Integer refundQuantitySum;
private BigDecimal serviceFee; private BigDecimal serviceFee;
private BigDecimal productCost; private BigDecimal productCost;
private BigDecimal freightCost; private BigDecimal freightCost;
@@ -33,13 +32,12 @@ public class BiStatMetricDelta {
public static BiStatMetricDelta zeros() { public static BiStatMetricDelta zeros() {
return BiStatMetricDelta.builder() return BiStatMetricDelta.builder()
.salesAmount(BigDecimal.ZERO)
.salesOrderCount(0)
.salesQuantitySum(0)
.dealAmount(BigDecimal.ZERO) .dealAmount(BigDecimal.ZERO)
.dealOrderCount(0) .dealOrderCount(0)
.dealQuantitySum(0) .dealQuantitySum(0)
.refundAmount(BigDecimal.ZERO) .refundAmount(BigDecimal.ZERO)
.refundOrderCount(0)
.refundQuantitySum(0)
.serviceFee(BigDecimal.ZERO) .serviceFee(BigDecimal.ZERO)
.productCost(BigDecimal.ZERO) .productCost(BigDecimal.ZERO)
.freightCost(BigDecimal.ZERO) .freightCost(BigDecimal.ZERO)
@@ -49,13 +47,12 @@ public class BiStatMetricDelta {
public BiStatMetricDelta negate() { public BiStatMetricDelta negate() {
return BiStatMetricDelta.builder() return BiStatMetricDelta.builder()
.salesAmount(nz(salesAmount).negate())
.salesOrderCount(-(salesOrderCount == null ? 0 : salesOrderCount))
.salesQuantitySum(-(salesQuantitySum == null ? 0 : salesQuantitySum))
.dealAmount(nz(dealAmount).negate()) .dealAmount(nz(dealAmount).negate())
.dealOrderCount(-(dealOrderCount == null ? 0 : dealOrderCount)) .dealOrderCount(-(dealOrderCount == null ? 0 : dealOrderCount))
.dealQuantitySum(-(dealQuantitySum == null ? 0 : dealQuantitySum)) .dealQuantitySum(-(dealQuantitySum == null ? 0 : dealQuantitySum))
.refundAmount(nz(refundAmount).negate()) .refundAmount(nz(refundAmount).negate())
.refundOrderCount(-(refundOrderCount == null ? 0 : refundOrderCount))
.refundQuantitySum(-(refundQuantitySum == null ? 0 : refundQuantitySum))
.serviceFee(nz(serviceFee).negate()) .serviceFee(nz(serviceFee).negate())
.productCost(nz(productCost).negate()) .productCost(nz(productCost).negate())
.freightCost(nz(freightCost).negate()) .freightCost(nz(freightCost).negate())
@@ -68,13 +65,12 @@ public class BiStatMetricDelta {
return this; return this;
} }
return BiStatMetricDelta.builder() return BiStatMetricDelta.builder()
.salesAmount(nz(salesAmount).add(nz(o.salesAmount)))
.salesOrderCount(nzi(salesOrderCount) + nzi(o.salesOrderCount))
.salesQuantitySum(nzi(salesQuantitySum) + nzi(o.salesQuantitySum))
.dealAmount(nz(dealAmount).add(nz(o.dealAmount))) .dealAmount(nz(dealAmount).add(nz(o.dealAmount)))
.dealOrderCount(nzi(dealOrderCount) + nzi(o.dealOrderCount)) .dealOrderCount(nzi(dealOrderCount) + nzi(o.dealOrderCount))
.dealQuantitySum(nzi(dealQuantitySum) + nzi(o.dealQuantitySum)) .dealQuantitySum(nzi(dealQuantitySum) + nzi(o.dealQuantitySum))
.refundAmount(nz(refundAmount).add(nz(o.refundAmount))) .refundAmount(nz(refundAmount).add(nz(o.refundAmount)))
.refundOrderCount(nzi(refundOrderCount) + nzi(o.refundOrderCount))
.refundQuantitySum(nzi(refundQuantitySum) + nzi(o.refundQuantitySum))
.serviceFee(nz(serviceFee).add(nz(o.serviceFee))) .serviceFee(nz(serviceFee).add(nz(o.serviceFee)))
.productCost(nz(productCost).add(nz(o.productCost))) .productCost(nz(productCost).add(nz(o.productCost)))
.freightCost(nz(freightCost).add(nz(o.freightCost))) .freightCost(nz(freightCost).add(nz(o.freightCost)))
@@ -87,13 +83,12 @@ public class BiStatMetricDelta {
} }
public boolean isAllZero() { public boolean isAllZero() {
return nz(salesAmount).signum() == 0 return nz(dealAmount).signum() == 0
&& nzi(salesOrderCount) == 0
&& nzi(salesQuantitySum) == 0
&& nz(dealAmount).signum() == 0
&& nzi(dealOrderCount) == 0 && nzi(dealOrderCount) == 0
&& nzi(dealQuantitySum) == 0 && nzi(dealQuantitySum) == 0
&& nz(refundAmount).signum() == 0 && nz(refundAmount).signum() == 0
&& nzi(refundOrderCount) == 0
&& nzi(refundQuantitySum) == 0
&& nz(serviceFee).signum() == 0 && nz(serviceFee).signum() == 0
&& nz(productCost).signum() == 0 && nz(productCost).signum() == 0
&& nz(freightCost).signum() == 0 && nz(freightCost).signum() == 0
@@ -10,6 +10,7 @@ import java.math.BigDecimal;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
/** 商品日汇聚。净销售由读侧 deal − refund 推导。 */
@Data @Data
@Document(collection = "bi_order_stat_daily_product") @Document(collection = "bi_order_stat_daily_product")
@CompoundIndexes({ @CompoundIndexes({
@@ -29,13 +30,12 @@ public class BiOrderStatDailyProductDoc {
private Long categoryId; private Long categoryId;
private LocalDate statDate; private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal dealAmount = BigDecimal.ZERO; private BigDecimal dealAmount = BigDecimal.ZERO;
private Integer dealOrderCount = 0; private Integer dealOrderCount = 0;
private Integer dealQuantitySum = 0; private Integer dealQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO; private BigDecimal refundAmount = BigDecimal.ZERO;
private Integer refundOrderCount = 0;
private Integer refundQuantitySum = 0;
private BigDecimal serviceFee = BigDecimal.ZERO; private BigDecimal serviceFee = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO; private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO; private BigDecimal freightCost = BigDecimal.ZERO;
@@ -10,6 +10,9 @@ import java.math.BigDecimal;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
/**
* 店铺日汇聚。净销售由读侧 deal − refund 推导,不存 sales*。
*/
@Data @Data
@Document(collection = "bi_order_stat_daily_shop") @Document(collection = "bi_order_stat_daily_shop")
@CompoundIndexes({ @CompoundIndexes({
@@ -26,13 +29,12 @@ public class BiOrderStatDailyShopDoc {
private String platformCode; private String platformCode;
private LocalDate statDate; private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal dealAmount = BigDecimal.ZERO; private BigDecimal dealAmount = BigDecimal.ZERO;
private Integer dealOrderCount = 0; private Integer dealOrderCount = 0;
private Integer dealQuantitySum = 0; private Integer dealQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO; private BigDecimal refundAmount = BigDecimal.ZERO;
private Integer refundOrderCount = 0;
private Integer refundQuantitySum = 0;
private BigDecimal serviceFee = BigDecimal.ZERO; private BigDecimal serviceFee = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO; private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO; private BigDecimal freightCost = BigDecimal.ZERO;
@@ -10,6 +10,7 @@ import java.math.BigDecimal;
import java.time.Instant; import java.time.Instant;
import java.time.LocalDate; import java.time.LocalDate;
/** SKU 日汇聚。净销售由读侧 deal − refund 推导。 */
@Data @Data
@Document(collection = "bi_order_stat_daily_sku") @Document(collection = "bi_order_stat_daily_sku")
@CompoundIndexes({ @CompoundIndexes({
@@ -30,13 +31,12 @@ public class BiOrderStatDailySkuDoc {
private Long productSkuId; private Long productSkuId;
private LocalDate statDate; private LocalDate statDate;
private BigDecimal salesAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0;
private Integer salesQuantitySum = 0;
private BigDecimal dealAmount = BigDecimal.ZERO; private BigDecimal dealAmount = BigDecimal.ZERO;
private Integer dealOrderCount = 0; private Integer dealOrderCount = 0;
private Integer dealQuantitySum = 0; private Integer dealQuantitySum = 0;
private BigDecimal refundAmount = BigDecimal.ZERO; private BigDecimal refundAmount = BigDecimal.ZERO;
private Integer refundOrderCount = 0;
private Integer refundQuantitySum = 0;
private BigDecimal serviceFee = BigDecimal.ZERO; private BigDecimal serviceFee = BigDecimal.ZERO;
private BigDecimal productCost = BigDecimal.ZERO; private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO; private BigDecimal freightCost = BigDecimal.ZERO;
@@ -17,6 +17,8 @@ import java.util.Map;
/** /**
* BI 订单日汇聚读查询:Mongo → 工作台/概览沿用的 {@link OverviewAggRows} 行形态。 * BI 订单日汇聚读查询:Mongo → 工作台/概览沿用的 {@link OverviewAggRows} 行形态。
* <p>
* 净销售三件套由读侧推导:{@code deal* − refund*},不再读 Mongo sales* 字段。
*/ */
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
@@ -54,27 +56,11 @@ public class BiOrderStatQueryService {
if (doc == null || doc.getStatDate() == null) { if (doc == null || doc.getStatDate() == null) {
continue; continue;
} }
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> { OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow(); addDealRefundCost(row,
r.setStatDate(d); doc.getDealAmount(), doc.getDealOrderCount(),
r.setSalesAmount(BigDecimal.ZERO); doc.getRefundAmount(), doc.getRefundOrderCount(),
r.setDealAmount(BigDecimal.ZERO); doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
r.setRefundAmount(BigDecimal.ZERO);
r.setProductCost(BigDecimal.ZERO);
r.setFreightCost(BigDecimal.ZERO);
r.setOtherCost(BigDecimal.ZERO);
r.setOrderCount(0L);
r.setDealOrderCount(0L);
return r;
});
row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount())));
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount()));
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
} }
return new ArrayList<>(byDay.values()); return new ArrayList<>(byDay.values());
} }
@@ -88,31 +74,50 @@ public class BiOrderStatQueryService {
} }
long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L; long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L;
SkuPeriodMetrics cur = merged.get(skuId); SkuPeriodMetrics cur = merged.get(skuId);
BigDecimal deal = nz(doc.getDealAmount());
BigDecimal refund = nz(doc.getRefundAmount());
int dealOrders = nzInt(doc.getDealOrderCount());
int refundOrders = nzInt(doc.getRefundOrderCount());
int dealQty = nzInt(doc.getDealQuantitySum());
int refundQty = nzInt(doc.getRefundQuantitySum());
if (cur == null) { if (cur == null) {
merged.put(skuId, new SkuPeriodMetrics( merged.put(skuId, new SkuPeriodMetrics(
skuId, skuId,
nz(doc.getSalesAmount()), netAmount(deal, refund),
nz(doc.getRefundAmount()), refund,
nz(doc.getProductCost()), nz(doc.getProductCost()),
nz(doc.getFreightCost()), nz(doc.getFreightCost()),
nz(doc.getOtherCost()), nz(doc.getOtherCost()),
nzInt(doc.getSalesOrderCount()), netCount(dealOrders, refundOrders),
nzInt(doc.getSalesQuantitySum()))); netCount(dealQty, refundQty),
deal, dealOrders, dealQty,
refundOrders, refundQty));
} else { } else {
BigDecimal nextDeal = cur.dealAmount().add(deal);
BigDecimal nextRefund = cur.refundAmount().add(refund);
int nextDealOrders = cur.dealOrderCount() + dealOrders;
int nextRefundOrders = cur.refundOrderCount() + refundOrders;
int nextDealQty = cur.dealQuantitySum() + dealQty;
int nextRefundQty = cur.refundQuantitySum() + refundQty;
merged.put(skuId, new SkuPeriodMetrics( merged.put(skuId, new SkuPeriodMetrics(
skuId, skuId,
cur.salesAmount().add(nz(doc.getSalesAmount())), netAmount(nextDeal, nextRefund),
cur.refundAmount().add(nz(doc.getRefundAmount())), nextRefund,
cur.productCost().add(nz(doc.getProductCost())), cur.productCost().add(nz(doc.getProductCost())),
cur.freightCost().add(nz(doc.getFreightCost())), cur.freightCost().add(nz(doc.getFreightCost())),
cur.otherCost().add(nz(doc.getOtherCost())), cur.otherCost().add(nz(doc.getOtherCost())),
cur.salesOrderCount() + nzInt(doc.getSalesOrderCount()), netCount(nextDealOrders, nextRefundOrders),
cur.salesQuantitySum() + nzInt(doc.getSalesQuantitySum()))); netCount(nextDealQty, nextRefundQty),
nextDeal, nextDealOrders, nextDealQty,
nextRefundOrders, nextRefundQty));
} }
} }
return new ArrayList<>(merged.values()); return new ArrayList<>(merged.values());
} }
/**
* SKU 区间指标。{@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套(成交−退款)。
*/
public record SkuPeriodMetrics( public record SkuPeriodMetrics(
long productSkuId, long productSkuId,
BigDecimal salesAmount, BigDecimal salesAmount,
@@ -121,7 +126,12 @@ public class BiOrderStatQueryService {
BigDecimal freightCost, BigDecimal freightCost,
BigDecimal otherCost, BigDecimal otherCost,
int salesOrderCount, int salesOrderCount,
int salesQuantitySum int salesQuantitySum,
BigDecimal dealAmount,
int dealOrderCount,
int dealQuantitySum,
int refundOrderCount,
int refundQuantitySum
) { ) {
public BigDecimal orderCost() { public BigDecimal orderCost() {
return nz(productCost).add(nz(freightCost)).add(nz(otherCost)); return nz(productCost).add(nz(freightCost)).add(nz(otherCost));
@@ -131,6 +141,7 @@ public class BiOrderStatQueryService {
/** /**
* 商品日文档按 (shopId, productId, categoryId) 合并区间后,转为工作台多维/四表所需行。 * 商品日文档按 (shopId, productId, categoryId) 合并区间后,转为工作台多维/四表所需行。
* platformCode 由店铺主数据补齐(商品日文档无平台字段)。 * platformCode 由店铺主数据补齐(商品日文档无平台字段)。
* 行上 salesAmount/orderCount/salesQuantitySum 为净销售三件套。
*/ */
public List<OverviewAggRows.ShopProductRow> toShopProductRows( public List<OverviewAggRows.ShopProductRow> toShopProductRows(
List<BiOrderStatDailyProductDoc> docs, Map<Long, String> platformByShopId) { List<BiOrderStatDailyProductDoc> docs, Map<Long, String> platformByShopId) {
@@ -152,6 +163,8 @@ public class BiOrderStatQueryService {
r.setOrderCount(0L); r.setOrderCount(0L);
r.setSalesQuantitySum(0L); r.setSalesQuantitySum(0L);
r.setRefundAmount(BigDecimal.ZERO); r.setRefundAmount(BigDecimal.ZERO);
r.setRefundOrderCount(0L);
r.setRefundQuantitySum(0L);
r.setProductCost(BigDecimal.ZERO); r.setProductCost(BigDecimal.ZERO);
r.setFreightCost(BigDecimal.ZERO); r.setFreightCost(BigDecimal.ZERO);
r.setOtherCost(BigDecimal.ZERO); r.setOtherCost(BigDecimal.ZERO);
@@ -160,16 +173,16 @@ public class BiOrderStatQueryService {
r.setDealQuantitySum(0L); r.setDealQuantitySum(0L);
return r; return r;
}); });
row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount())));
row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount()));
row.setSalesQuantitySum(nzLong(row.getSalesQuantitySum()) + nzInt(doc.getSalesQuantitySum()));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount()))); row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount())); row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
row.setDealQuantitySum(nzLong(row.getDealQuantitySum()) + nzInt(doc.getDealQuantitySum())); row.setDealQuantitySum(nzLong(row.getDealQuantitySum()) + nzInt(doc.getDealQuantitySum()));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(doc.getRefundOrderCount()));
row.setRefundQuantitySum(nzLong(row.getRefundQuantitySum()) + nzInt(doc.getRefundQuantitySum()));
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
fillNetSales(row);
} }
return new ArrayList<>(merged.values()); return new ArrayList<>(merged.values());
} }
@@ -181,60 +194,52 @@ public class BiOrderStatQueryService {
if (doc == null || doc.getStatDate() == null) { if (doc == null || doc.getStatDate() == null) {
continue; continue;
} }
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> { OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow(); addDealRefundCost(row,
r.setStatDate(d); doc.getDealAmount(), doc.getDealOrderCount(),
r.setSalesAmount(BigDecimal.ZERO); doc.getRefundAmount(), doc.getRefundOrderCount(),
r.setDealAmount(BigDecimal.ZERO); doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
r.setRefundAmount(BigDecimal.ZERO);
r.setProductCost(BigDecimal.ZERO);
r.setFreightCost(BigDecimal.ZERO);
r.setOtherCost(BigDecimal.ZERO);
r.setOrderCount(0L);
r.setDealOrderCount(0L);
return r;
});
row.setSalesAmount(nz(row.getSalesAmount()).add(nz(doc.getSalesAmount())));
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
row.setOrderCount(nzLong(row.getOrderCount()) + nzInt(doc.getSalesOrderCount()));
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
} }
return new ArrayList<>(byDay.values()); return new ArrayList<>(byDay.values());
} }
/** 店铺日文档区间合计(KPI 用:单量不跨商品重复计)。 */ /**
* 店铺日文档区间合计(KPI 用:单量不跨商品重复计)。
* {@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套。
*/
public ShopPeriodMetrics sumShopDocs(List<BiOrderStatDailyShopDoc> shopDocs) { public ShopPeriodMetrics sumShopDocs(List<BiOrderStatDailyShopDoc> shopDocs) {
BigDecimal sales = BigDecimal.ZERO; BigDecimal dealAmount = BigDecimal.ZERO;
BigDecimal refund = BigDecimal.ZERO; BigDecimal refund = BigDecimal.ZERO;
BigDecimal pc = BigDecimal.ZERO; BigDecimal pc = BigDecimal.ZERO;
BigDecimal fc = BigDecimal.ZERO; BigDecimal fc = BigDecimal.ZERO;
BigDecimal oc = BigDecimal.ZERO; BigDecimal oc = BigDecimal.ZERO;
BigDecimal dealAmount = BigDecimal.ZERO;
int salesOrderCount = 0;
int salesQuantitySum = 0;
int dealOrderCount = 0; int dealOrderCount = 0;
int dealQuantitySum = 0; int dealQuantitySum = 0;
int refundOrderCount = 0;
int refundQuantitySum = 0;
for (BiOrderStatDailyShopDoc doc : shopDocs) { for (BiOrderStatDailyShopDoc doc : shopDocs) {
if (doc == null) { if (doc == null) {
continue; continue;
} }
sales = sales.add(nz(doc.getSalesAmount())); dealAmount = dealAmount.add(nz(doc.getDealAmount()));
refund = refund.add(nz(doc.getRefundAmount())); refund = refund.add(nz(doc.getRefundAmount()));
pc = pc.add(nz(doc.getProductCost())); pc = pc.add(nz(doc.getProductCost()));
fc = fc.add(nz(doc.getFreightCost())); fc = fc.add(nz(doc.getFreightCost()));
oc = oc.add(nz(doc.getOtherCost())); oc = oc.add(nz(doc.getOtherCost()));
dealAmount = dealAmount.add(nz(doc.getDealAmount()));
salesOrderCount += nzInt(doc.getSalesOrderCount());
salesQuantitySum += nzInt(doc.getSalesQuantitySum());
dealOrderCount += nzInt(doc.getDealOrderCount()); dealOrderCount += nzInt(doc.getDealOrderCount());
dealQuantitySum += nzInt(doc.getDealQuantitySum()); dealQuantitySum += nzInt(doc.getDealQuantitySum());
refundOrderCount += nzInt(doc.getRefundOrderCount());
refundQuantitySum += nzInt(doc.getRefundQuantitySum());
} }
return new ShopPeriodMetrics(sales, refund, pc, fc, oc, dealAmount, return new ShopPeriodMetrics(
salesOrderCount, salesQuantitySum, dealOrderCount, dealQuantitySum); netAmount(dealAmount, refund),
refund,
pc, fc, oc,
dealAmount,
netCount(dealOrderCount, refundOrderCount),
netCount(dealQuantitySum, refundQuantitySum),
dealOrderCount, dealQuantitySum,
refundOrderCount, refundQuantitySum);
} }
public record ShopPeriodMetrics( public record ShopPeriodMetrics(
@@ -247,10 +252,66 @@ public class BiOrderStatQueryService {
int salesOrderCount, int salesOrderCount,
int salesQuantitySum, int salesQuantitySum,
int dealOrderCount, int dealOrderCount,
int dealQuantitySum int dealQuantitySum,
int refundOrderCount,
int refundQuantitySum
) { ) {
} }
private static OverviewAggRows.DailyRow emptyDaily(LocalDate d) {
OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow();
r.setStatDate(d);
r.setSalesAmount(BigDecimal.ZERO);
r.setDealAmount(BigDecimal.ZERO);
r.setRefundAmount(BigDecimal.ZERO);
r.setProductCost(BigDecimal.ZERO);
r.setFreightCost(BigDecimal.ZERO);
r.setOtherCost(BigDecimal.ZERO);
r.setOrderCount(0L);
r.setDealOrderCount(0L);
r.setRefundOrderCount(0L);
return r;
}
private static void addDealRefundCost(OverviewAggRows.DailyRow row,
BigDecimal dealAmount, Integer dealOrderCount,
BigDecimal refundAmount, Integer refundOrderCount,
BigDecimal productCost, BigDecimal freightCost, BigDecimal otherCost) {
row.setDealAmount(nz(row.getDealAmount()).add(nz(dealAmount)));
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(dealOrderCount));
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(refundAmount)));
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(refundOrderCount));
row.setProductCost(nz(row.getProductCost()).add(nz(productCost)));
row.setFreightCost(nz(row.getFreightCost()).add(nz(freightCost)));
row.setOtherCost(nz(row.getOtherCost()).add(nz(otherCost)));
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
row.setOrderCount(netCountLong(
nzLong(row.getDealOrderCount()),
nzLong(row.getRefundOrderCount())));
}
private static void fillNetSales(OverviewAggRows.ShopProductRow row) {
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
row.setOrderCount(netCountLong(
nzLong(row.getDealOrderCount()),
nzLong(row.getRefundOrderCount())));
row.setSalesQuantitySum(netCountLong(
nzLong(row.getDealQuantitySum()),
nzLong(row.getRefundQuantitySum())));
}
private static BigDecimal netAmount(BigDecimal deal, BigDecimal refund) {
return nz(deal).subtract(nz(refund));
}
private static int netCount(int deal, int refund) {
return deal - refund;
}
private static long netCountLong(long deal, long refund) {
return deal - refund;
}
private static BigDecimal nz(BigDecimal v) { private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO; return v != null ? v : BigDecimal.ZERO;
} }
@@ -217,13 +217,12 @@ public class BiOrderStatDailyRepository {
if (d == null) { if (d == null) {
return u; return u;
} }
inc(u, "salesAmount", d.getSalesAmount());
inc(u, "salesOrderCount", d.getSalesOrderCount());
inc(u, "salesQuantitySum", d.getSalesQuantitySum());
inc(u, "dealAmount", d.getDealAmount()); inc(u, "dealAmount", d.getDealAmount());
inc(u, "dealOrderCount", d.getDealOrderCount()); inc(u, "dealOrderCount", d.getDealOrderCount());
inc(u, "dealQuantitySum", d.getDealQuantitySum()); inc(u, "dealQuantitySum", d.getDealQuantitySum());
inc(u, "refundAmount", d.getRefundAmount()); inc(u, "refundAmount", d.getRefundAmount());
inc(u, "refundOrderCount", d.getRefundOrderCount());
inc(u, "refundQuantitySum", d.getRefundQuantitySum());
inc(u, "serviceFee", d.getServiceFee()); inc(u, "serviceFee", d.getServiceFee());
inc(u, "productCost", d.getProductCost()); inc(u, "productCost", d.getProductCost());
inc(u, "freightCost", d.getFreightCost()); inc(u, "freightCost", d.getFreightCost());
@@ -252,13 +251,12 @@ public class BiOrderStatDailyRepository {
if (d == null) { if (d == null) {
return; return;
} }
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setDealAmount(nz(d.getDealAmount())); doc.setDealAmount(nz(d.getDealAmount()));
doc.setDealOrderCount(nzi(d.getDealOrderCount())); doc.setDealOrderCount(nzi(d.getDealOrderCount()));
doc.setDealQuantitySum(nzi(d.getDealQuantitySum())); doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount())); doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
doc.setServiceFee(nz(d.getServiceFee())); doc.setServiceFee(nz(d.getServiceFee()));
doc.setProductCost(nz(d.getProductCost())); doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost())); doc.setFreightCost(nz(d.getFreightCost()));
@@ -269,13 +267,12 @@ public class BiOrderStatDailyRepository {
if (d == null) { if (d == null) {
return; return;
} }
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setDealAmount(nz(d.getDealAmount())); doc.setDealAmount(nz(d.getDealAmount()));
doc.setDealOrderCount(nzi(d.getDealOrderCount())); doc.setDealOrderCount(nzi(d.getDealOrderCount()));
doc.setDealQuantitySum(nzi(d.getDealQuantitySum())); doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount())); doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
doc.setServiceFee(nz(d.getServiceFee())); doc.setServiceFee(nz(d.getServiceFee()));
doc.setProductCost(nz(d.getProductCost())); doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost())); doc.setFreightCost(nz(d.getFreightCost()));
@@ -286,13 +283,12 @@ public class BiOrderStatDailyRepository {
if (d == null) { if (d == null) {
return; return;
} }
doc.setSalesAmount(nz(d.getSalesAmount()));
doc.setSalesOrderCount(nzi(d.getSalesOrderCount()));
doc.setSalesQuantitySum(nzi(d.getSalesQuantitySum()));
doc.setDealAmount(nz(d.getDealAmount())); doc.setDealAmount(nz(d.getDealAmount()));
doc.setDealOrderCount(nzi(d.getDealOrderCount())); doc.setDealOrderCount(nzi(d.getDealOrderCount()));
doc.setDealQuantitySum(nzi(d.getDealQuantitySum())); doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
doc.setRefundAmount(nz(d.getRefundAmount())); doc.setRefundAmount(nz(d.getRefundAmount()));
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
doc.setServiceFee(nz(d.getServiceFee())); doc.setServiceFee(nz(d.getServiceFee()));
doc.setProductCost(nz(d.getProductCost())); doc.setProductCost(nz(d.getProductCost()));
doc.setFreightCost(nz(d.getFreightCost())); doc.setFreightCost(nz(d.getFreightCost()));
@@ -152,33 +152,36 @@ public class OrderDailyStatComputeService {
Map<String, DimKey> skuKeys = new HashMap<>(); Map<String, DimKey> skuKeys = new HashMap<>();
for (OrderPO order : orders) { for (OrderPO order : orders) {
boolean deal = stat.includesDeal(order.getStatus());
boolean refund = stat.includesRefund(order.getStatus());
// 已取消/未知:不进成交、退款、服务费与成本
if (!deal && !refund) {
continue;
}
List<OrderItemPO> items = itemsByOrder.getOrDefault(order.getId(), List.of()); List<OrderItemPO> items = itemsByOrder.getOrDefault(order.getId(), List.of());
int qtySum = OrderStatusStatSets.totalQuantity(items); int qtySum = OrderStatusStatSets.totalQuantity(items);
if (qtySum <= 0 && items.isEmpty()) { if (qtySum <= 0 && items.isEmpty()) {
qtySum = 1; qtySum = 1;
} }
BigDecimal received = OrderStatusStatSets.receivedAmount(order); BigDecimal received = OrderStatusStatSets.receivedAmount(order);
BigDecimal fee = nz(order.getServiceFee()); BigDecimal fee = deal ? nz(order.getServiceFee()) : BigDecimal.ZERO;
boolean sales = stat.includesSales(order.getStatus());
boolean refund = stat.includesRefund(order.getStatus());
shop.dealAmount = shop.dealAmount.add(received); if (deal) {
shop.dealOrderCount++; shop.dealAmount = shop.dealAmount.add(received);
shop.dealQuantitySum += qtySum; shop.dealOrderCount++;
shop.serviceFee = shop.serviceFee.add(fee); shop.dealQuantitySum += qtySum;
if (sales) { shop.serviceFee = shop.serviceFee.add(fee);
shop.salesAmount = shop.salesAmount.add(received);
shop.salesOrderCount++;
shop.salesQuantitySum += qtySum;
} }
if (refund) { if (refund) {
shop.refundAmount = shop.refundAmount.add(received); shop.refundAmount = shop.refundAmount.add(received);
shop.refundOrderCount++;
shop.refundQuantitySum += qtySum;
} }
Set<String> countedProductSales = new HashSet<>();
Set<String> countedProductDeal = new HashSet<>(); Set<String> countedProductDeal = new HashSet<>();
Set<String> countedSkuSales = new HashSet<>(); Set<String> countedProductRefund = new HashSet<>();
Set<String> countedSkuDeal = new HashSet<>(); Set<String> countedSkuDeal = new HashSet<>();
Set<String> countedSkuRefund = new HashSet<>();
if (items.isEmpty()) { if (items.isEmpty()) {
continue; continue;
@@ -189,26 +192,25 @@ public class OrderDailyStatComputeService {
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L; long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
int qty = OrderStatusStatSets.quantity(item); int qty = OrderStatusStatSets.quantity(item);
BigDecimal lineReceived = allocateLine(received, item, items); BigDecimal lineReceived = allocateLine(received, item, items);
BigDecimal lineFee = allocateLine(fee, item, items); BigDecimal lineFee = deal ? allocateLine(fee, item, items) : BigDecimal.ZERO;
String pk = companyId + ":" + shopId + ":" + productId + ":" + categoryId; String pk = companyId + ":" + shopId + ":" + productId + ":" + categoryId;
Metric pm = productMap.computeIfAbsent(pk, k -> new Metric()); Metric pm = productMap.computeIfAbsent(pk, k -> new Metric());
productKeys.putIfAbsent(pk, new DimKey(productId, categoryId, 0L)); productKeys.putIfAbsent(pk, new DimKey(productId, categoryId, 0L));
pm.dealAmount = pm.dealAmount.add(lineReceived); if (deal) {
pm.dealQuantitySum += qty; pm.dealAmount = pm.dealAmount.add(lineReceived);
pm.serviceFee = pm.serviceFee.add(lineFee); pm.dealQuantitySum += qty;
if (countedProductDeal.add(pk)) { pm.serviceFee = pm.serviceFee.add(lineFee);
pm.dealOrderCount++; if (countedProductDeal.add(pk)) {
} pm.dealOrderCount++;
if (sales) {
pm.salesAmount = pm.salesAmount.add(lineReceived);
pm.salesQuantitySum += qty;
if (countedProductSales.add(pk)) {
pm.salesOrderCount++;
} }
} }
if (refund) { if (refund) {
pm.refundAmount = pm.refundAmount.add(lineReceived); pm.refundAmount = pm.refundAmount.add(lineReceived);
pm.refundQuantitySum += qty;
if (countedProductRefund.add(pk)) {
pm.refundOrderCount++;
}
} }
pm.productCost = pm.productCost.add(stat.productCostForStats(order, item)); pm.productCost = pm.productCost.add(stat.productCostForStats(order, item));
pm.freightCost = pm.freightCost.add(stat.freightCostForStats(order, item)); pm.freightCost = pm.freightCost.add(stat.freightCostForStats(order, item));
@@ -217,21 +219,20 @@ public class OrderDailyStatComputeService {
String sk = companyId + ":" + shopId + ":" + skuId; String sk = companyId + ":" + shopId + ":" + skuId;
Metric sm = skuMap.computeIfAbsent(sk, k -> new Metric()); Metric sm = skuMap.computeIfAbsent(sk, k -> new Metric());
skuKeys.putIfAbsent(sk, new DimKey(productId, 0L, skuId)); skuKeys.putIfAbsent(sk, new DimKey(productId, 0L, skuId));
sm.dealAmount = sm.dealAmount.add(lineReceived); if (deal) {
sm.dealQuantitySum += qty; sm.dealAmount = sm.dealAmount.add(lineReceived);
sm.serviceFee = sm.serviceFee.add(lineFee); sm.dealQuantitySum += qty;
if (countedSkuDeal.add(sk)) { sm.serviceFee = sm.serviceFee.add(lineFee);
sm.dealOrderCount++; if (countedSkuDeal.add(sk)) {
} sm.dealOrderCount++;
if (sales) {
sm.salesAmount = sm.salesAmount.add(lineReceived);
sm.salesQuantitySum += qty;
if (countedSkuSales.add(sk)) {
sm.salesOrderCount++;
} }
} }
if (refund) { if (refund) {
sm.refundAmount = sm.refundAmount.add(lineReceived); sm.refundAmount = sm.refundAmount.add(lineReceived);
sm.refundQuantitySum += qty;
if (countedSkuRefund.add(sk)) {
sm.refundOrderCount++;
}
} }
sm.productCost = sm.productCost.add(stat.productCostForStats(order, item)); sm.productCost = sm.productCost.add(stat.productCostForStats(order, item));
sm.freightCost = sm.freightCost.add(stat.freightCostForStats(order, item)); sm.freightCost = sm.freightCost.add(stat.freightCostForStats(order, item));
@@ -301,13 +302,12 @@ public class OrderDailyStatComputeService {
} }
private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) { private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setDealAmount(m.dealAmount); doc.setDealAmount(m.dealAmount);
doc.setDealOrderCount(m.dealOrderCount); doc.setDealOrderCount(m.dealOrderCount);
doc.setDealQuantitySum(m.dealQuantitySum); doc.setDealQuantitySum(m.dealQuantitySum);
doc.setRefundAmount(m.refundAmount); doc.setRefundAmount(m.refundAmount);
doc.setRefundOrderCount(m.refundOrderCount);
doc.setRefundQuantitySum(m.refundQuantitySum);
doc.setServiceFee(m.serviceFee); doc.setServiceFee(m.serviceFee);
doc.setProductCost(m.productCost); doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost); doc.setFreightCost(m.freightCost);
@@ -315,13 +315,12 @@ public class OrderDailyStatComputeService {
} }
private static void applyMetric(BiOrderStatDailyProductDoc doc, Metric m) { private static void applyMetric(BiOrderStatDailyProductDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setDealAmount(m.dealAmount); doc.setDealAmount(m.dealAmount);
doc.setDealOrderCount(m.dealOrderCount); doc.setDealOrderCount(m.dealOrderCount);
doc.setDealQuantitySum(m.dealQuantitySum); doc.setDealQuantitySum(m.dealQuantitySum);
doc.setRefundAmount(m.refundAmount); doc.setRefundAmount(m.refundAmount);
doc.setRefundOrderCount(m.refundOrderCount);
doc.setRefundQuantitySum(m.refundQuantitySum);
doc.setServiceFee(m.serviceFee); doc.setServiceFee(m.serviceFee);
doc.setProductCost(m.productCost); doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost); doc.setFreightCost(m.freightCost);
@@ -329,13 +328,12 @@ public class OrderDailyStatComputeService {
} }
private static void applyMetric(BiOrderStatDailySkuDoc doc, Metric m) { private static void applyMetric(BiOrderStatDailySkuDoc doc, Metric m) {
doc.setSalesAmount(m.salesAmount);
doc.setSalesOrderCount(m.salesOrderCount);
doc.setSalesQuantitySum(m.salesQuantitySum);
doc.setDealAmount(m.dealAmount); doc.setDealAmount(m.dealAmount);
doc.setDealOrderCount(m.dealOrderCount); doc.setDealOrderCount(m.dealOrderCount);
doc.setDealQuantitySum(m.dealQuantitySum); doc.setDealQuantitySum(m.dealQuantitySum);
doc.setRefundAmount(m.refundAmount); doc.setRefundAmount(m.refundAmount);
doc.setRefundOrderCount(m.refundOrderCount);
doc.setRefundQuantitySum(m.refundQuantitySum);
doc.setServiceFee(m.serviceFee); doc.setServiceFee(m.serviceFee);
doc.setProductCost(m.productCost); doc.setProductCost(m.productCost);
doc.setFreightCost(m.freightCost); doc.setFreightCost(m.freightCost);
@@ -362,13 +360,12 @@ public class OrderDailyStatComputeService {
} }
private static final class Metric { private static final class Metric {
BigDecimal salesAmount = BigDecimal.ZERO;
int salesOrderCount;
int salesQuantitySum;
BigDecimal dealAmount = BigDecimal.ZERO; BigDecimal dealAmount = BigDecimal.ZERO;
int dealOrderCount; int dealOrderCount;
int dealQuantitySum; int dealQuantitySum;
BigDecimal refundAmount = BigDecimal.ZERO; BigDecimal refundAmount = BigDecimal.ZERO;
int refundOrderCount;
int refundQuantitySum;
BigDecimal serviceFee = BigDecimal.ZERO; BigDecimal serviceFee = BigDecimal.ZERO;
BigDecimal productCost = BigDecimal.ZERO; BigDecimal productCost = BigDecimal.ZERO;
BigDecimal freightCost = BigDecimal.ZERO; BigDecimal freightCost = BigDecimal.ZERO;
@@ -44,22 +44,24 @@ public class OrderStatContributionCalculator {
qtySum = 1; qtySum = 1;
} }
BigDecimal received = OrderStatusStatSets.receivedAmount(order); BigDecimal received = OrderStatusStatSets.receivedAmount(order);
BigDecimal fee = nz(order.getServiceFee()); boolean deal = stat.includesDeal(order.getStatus());
boolean sales = stat.includesSales(order.getStatus());
boolean refund = stat.includesRefund(order.getStatus()); boolean refund = stat.includesRefund(order.getStatus());
if (!deal && !refund) {
return null;
}
BigDecimal fee = deal ? nz(order.getServiceFee()) : BigDecimal.ZERO;
BiStatMetricDelta shop = BiStatMetricDelta.zeros(); BiStatMetricDelta shop = BiStatMetricDelta.zeros();
shop.setDealAmount(received); if (deal) {
shop.setDealOrderCount(1); shop.setDealAmount(received);
shop.setDealQuantitySum(qtySum); shop.setDealOrderCount(1);
shop.setServiceFee(fee); shop.setDealQuantitySum(qtySum);
if (sales) { shop.setServiceFee(fee);
shop.setSalesAmount(received);
shop.setSalesOrderCount(1);
shop.setSalesQuantitySum(qtySum);
} }
if (refund) { if (refund) {
shop.setRefundAmount(received); shop.setRefundAmount(received);
shop.setRefundOrderCount(1);
shop.setRefundQuantitySum(qtySum);
} }
Map<String, BiStatMetricDelta> productMap = new HashMap<>(); Map<String, BiStatMetricDelta> productMap = new HashMap<>();
@@ -75,20 +77,19 @@ public class OrderStatContributionCalculator {
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L; long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
int qty = OrderStatusStatSets.quantity(item); int qty = OrderStatusStatSets.quantity(item);
BigDecimal lineReceived = allocateLine(received, item, safeItems); BigDecimal lineReceived = allocateLine(received, item, safeItems);
BigDecimal lineFee = allocateLine(fee, item, safeItems); BigDecimal lineFee = deal ? allocateLine(fee, item, safeItems) : BigDecimal.ZERO;
String pk = productId + ":" + categoryId; String pk = productId + ":" + categoryId;
BiStatMetricDelta pm = productMap.computeIfAbsent(pk, k -> BiStatMetricDelta.zeros()); BiStatMetricDelta pm = productMap.computeIfAbsent(pk, k -> BiStatMetricDelta.zeros());
productKeys.putIfAbsent(pk, new long[]{productId, categoryId}); productKeys.putIfAbsent(pk, new long[]{productId, categoryId});
pm.setDealAmount(nz(pm.getDealAmount()).add(lineReceived)); if (deal) {
pm.setDealQuantitySum(nzi(pm.getDealQuantitySum()) + qty); pm.setDealAmount(nz(pm.getDealAmount()).add(lineReceived));
pm.setServiceFee(nz(pm.getServiceFee()).add(lineFee)); pm.setDealQuantitySum(nzi(pm.getDealQuantitySum()) + qty);
if (sales) { pm.setServiceFee(nz(pm.getServiceFee()).add(lineFee));
pm.setSalesAmount(nz(pm.getSalesAmount()).add(lineReceived));
pm.setSalesQuantitySum(nzi(pm.getSalesQuantitySum()) + qty);
} }
if (refund) { if (refund) {
pm.setRefundAmount(nz(pm.getRefundAmount()).add(lineReceived)); pm.setRefundAmount(nz(pm.getRefundAmount()).add(lineReceived));
pm.setRefundQuantitySum(nzi(pm.getRefundQuantitySum()) + qty);
} }
BigDecimal pc = stat.productCostForStats(order, item); BigDecimal pc = stat.productCostForStats(order, item);
BigDecimal fc = stat.freightCostForStats(order, item); BigDecimal fc = stat.freightCostForStats(order, item);
@@ -100,15 +101,14 @@ public class OrderStatContributionCalculator {
String sk = String.valueOf(skuId); String sk = String.valueOf(skuId);
BiStatMetricDelta sm = skuMap.computeIfAbsent(sk, k -> BiStatMetricDelta.zeros()); BiStatMetricDelta sm = skuMap.computeIfAbsent(sk, k -> BiStatMetricDelta.zeros());
skuKeys.putIfAbsent(sk, new long[]{productId, skuId}); skuKeys.putIfAbsent(sk, new long[]{productId, skuId});
sm.setDealAmount(nz(sm.getDealAmount()).add(lineReceived)); if (deal) {
sm.setDealQuantitySum(nzi(sm.getDealQuantitySum()) + qty); sm.setDealAmount(nz(sm.getDealAmount()).add(lineReceived));
sm.setServiceFee(nz(sm.getServiceFee()).add(lineFee)); sm.setDealQuantitySum(nzi(sm.getDealQuantitySum()) + qty);
if (sales) { sm.setServiceFee(nz(sm.getServiceFee()).add(lineFee));
sm.setSalesAmount(nz(sm.getSalesAmount()).add(lineReceived));
sm.setSalesQuantitySum(nzi(sm.getSalesQuantitySum()) + qty);
} }
if (refund) { if (refund) {
sm.setRefundAmount(nz(sm.getRefundAmount()).add(lineReceived)); sm.setRefundAmount(nz(sm.getRefundAmount()).add(lineReceived));
sm.setRefundQuantitySum(nzi(sm.getRefundQuantitySum()) + qty);
} }
sm.setProductCost(nz(sm.getProductCost()).add(pc)); sm.setProductCost(nz(sm.getProductCost()).add(pc));
sm.setFreightCost(nz(sm.getFreightCost()).add(fc)); sm.setFreightCost(nz(sm.getFreightCost()).add(fc));
@@ -122,15 +122,19 @@ public class OrderStatContributionCalculator {
// 订单计数:商品/SKU 维度每单计 1 次(有明细时) // 订单计数:商品/SKU 维度每单计 1 次(有明细时)
if (!safeItems.isEmpty()) { if (!safeItems.isEmpty()) {
for (BiStatMetricDelta pm : productMap.values()) { for (BiStatMetricDelta pm : productMap.values()) {
pm.setDealOrderCount(1); if (deal) {
if (sales) { pm.setDealOrderCount(1);
pm.setSalesOrderCount(1); }
if (refund) {
pm.setRefundOrderCount(1);
} }
} }
for (BiStatMetricDelta sm : skuMap.values()) { for (BiStatMetricDelta sm : skuMap.values()) {
sm.setDealOrderCount(1); if (deal) {
if (sales) { sm.setDealOrderCount(1);
sm.setSalesOrderCount(1); }
if (refund) {
sm.setRefundOrderCount(1);
} }
} }
} }
@@ -19,10 +19,15 @@ public final class OverviewAggRows {
private String platformCode; private String platformCode;
private Long productId; private Long productId;
private Long categoryId; private Long categoryId;
/** 净销售额 = dealAmount − refundAmount(读侧推导) */
private BigDecimal salesAmount; private BigDecimal salesAmount;
/** 净销售单量 = dealOrderCount − refundOrderCount */
private Long orderCount; private Long orderCount;
/** 净销量 = dealQuantitySum − refundQuantitySum */
private Long salesQuantitySum; private Long salesQuantitySum;
private BigDecimal refundAmount; private BigDecimal refundAmount;
private Long refundOrderCount;
private Long refundQuantitySum;
private BigDecimal productCost; private BigDecimal productCost;
private BigDecimal freightCost; private BigDecimal freightCost;
private BigDecimal otherCost; private BigDecimal otherCost;
@@ -34,16 +39,17 @@ public final class OverviewAggRows {
@Data @Data
public static class DailyRow { public static class DailyRow {
private LocalDate statDate; private LocalDate statDate;
/** 净销售额 = dealAmount − refundAmount */
private BigDecimal salesAmount; private BigDecimal salesAmount;
private BigDecimal dealAmount; private BigDecimal dealAmount;
private BigDecimal refundAmount; private BigDecimal refundAmount;
private BigDecimal productCost; private BigDecimal productCost;
private BigDecimal freightCost; private BigDecimal freightCost;
private BigDecimal otherCost; private BigDecimal otherCost;
/** 当日销售单量合计(店铺/商品日汇聚 salesOrderCount,与「实际销售额」同口径) */ /** 净销售单量 = dealOrderCount − refundOrderCount */
private Long orderCount; private Long orderCount;
/** 当日成交单量合计(店铺/商品日汇聚 dealOrderCount) */
private Long dealOrderCount; private Long dealOrderCount;
private Long refundOrderCount;
} }
@Data @Data
@@ -150,7 +150,7 @@ public class CompanyOverviewVO {
private BigDecimal orderCountAchievementRate; private BigDecimal orderCountAchievementRate;
/** /**
* 销售额目标达成率(实际销售额/目标销售额) * 销售额目标达成率(净销售额/目标销售额)
*/ */
private BigDecimal salesAmountAchievementRate; private BigDecimal salesAmountAchievementRate;
@@ -31,14 +31,11 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static BigDecimal salesTaxOnNetForCategoryExport(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { /** 税额 = 净销售额 × 税率 */
private static BigDecimal salesTaxOnNetForCategoryExport(BigDecimal sales, BigDecimal taxRate) {
BigDecimal s = sales != null ? sales : BigDecimal.ZERO; BigDecimal s = sales != null ? sales : BigDecimal.ZERO;
BigDecimal rfd = refund != null ? refund : BigDecimal.ZERO;
BigDecimal r = taxRate != null ? taxRate : DEFAULT_TAX_RATE; BigDecimal r = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
BigDecimal base = s.subtract(rfd); BigDecimal base = s.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : s;
if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO;
}
return base.multiply(r).setScale(2, RoundingMode.HALF_UP); return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
} }
@@ -279,12 +276,12 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
.subtract(totalPromoFee).subtract(totalBrushFee); .subtract(totalPromoFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnNetForCategoryExport(totalSales, totalRefund, taxRate); BigDecimal salesTax = salesTaxOnNetForCategoryExport(totalSales, taxRate);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) ? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
@@ -331,7 +328,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
String taxHeader = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString() String taxHeader = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString()
+ "%税额"; + "%税额";
String[] headers = { String[] headers = {
dimensionColumnHeader, "实际销售额", "单量", "客单价", dimensionColumnHeader, "净销售额", "单量", "客单价",
"商品成本", "运费", "其他成本", "订单成本", "退款金额", taxHeader, "推广费", "刷单费", "商品成本", "运费", "其他成本", "订单成本", "退款金额", taxHeader, "推广费", "刷单费",
"税前盈亏", "费比 %", "ROI", "税后盈亏" "税前盈亏", "费比 %", "ROI", "税后盈亏"
}; };
@@ -375,7 +372,7 @@ public class CategoryExportExcelServiceImpl implements CategoryExportExcelServic
setCell(row, 5, bd2Money(d.getShippingCost()), style); setCell(row, 5, bd2Money(d.getShippingCost()), style);
setCell(row, 6, bd2Money(d.getOtherCost()), style); setCell(row, 6, bd2Money(d.getOtherCost()), style);
setCell(row, 7, bd2Money(d.getOrderCost()), style); setCell(row, 7, bd2Money(d.getOrderCost()), style);
BigDecimal salesTax = salesTaxOnNetForCategoryExport(d.getSalesAmount(), d.getRefundAmount(), taxRate); BigDecimal salesTax = salesTaxOnNetForCategoryExport(d.getSalesAmount(), taxRate);
BigDecimal profitAfterTax = (d.getTotalProfitBeforeTax() != null ? d.getTotalProfitBeforeTax() : BigDecimal.ZERO) BigDecimal profitAfterTax = (d.getTotalProfitBeforeTax() != null ? d.getTotalProfitBeforeTax() : BigDecimal.ZERO)
.subtract(salesTax) .subtract(salesTax)
.setScale(2, RoundingMode.HALF_UP); .setScale(2, RoundingMode.HALF_UP);
@@ -56,7 +56,7 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
return sales.multiply(rate).setScale(2, RoundingMode.HALF_UP); return sales.multiply(rate).setScale(2, RoundingMode.HALF_UP);
} }
/** 计算ROI:实际销售额 / 推广费用 */ /** 计算ROI:净销售额 / 推广费用 */
private BigDecimal calculateSalesROI(BigDecimal salesAmount, BigDecimal promotionFee) { private BigDecimal calculateSalesROI(BigDecimal salesAmount, BigDecimal promotionFee) {
if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) { if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO; return BigDecimal.ZERO;
@@ -98,12 +98,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
.subtract(totalPromoFee).subtract(totalBrushFee); .subtract(totalPromoFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnSales(totalSales); BigDecimal salesTax = salesTaxOnSales(totalSales);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) ? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
@@ -173,12 +173,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
.subtract(totalPromoFee).subtract(totalBrushFee); .subtract(totalPromoFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnSales(totalSales); BigDecimal salesTax = salesTaxOnSales(totalSales);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) ? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
@@ -241,12 +241,12 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP) ? totalSalesAmount.divide(new BigDecimal(totalOrderCount), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost).subtract(totalRefundAmount) BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost)
.subtract(totalPromotionFee).subtract(totalBrushFee); .subtract(totalPromotionFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnSales(totalSalesAmount); BigDecimal salesTax = salesTaxOnSales(totalSalesAmount);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
? totalSalesAmount.subtract(totalRefundAmount).divide(totalPromotionFee, 4, RoundingMode.HALF_UP) ? totalSalesAmount.divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP) ? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
@@ -741,9 +741,9 @@ public class CompanyOverviewServiceImpl implements CompanyOverviewService {
return productCost.add(freightCost).add(otherCost); return productCost.add(freightCost).add(otherCost);
} }
/** 订单维度毛利:未扣推广/刷单/税 */ /** 订单维度毛利:净销售额 − 订单成本(净销售额已含成交−退款,不再二次减退款) */
BigDecimal grossProfit() { BigDecimal grossProfit() {
return sales.subtract(orderCost()).subtract(refund); return sales.subtract(orderCost());
} }
static AggMetrics from(OverviewAggRows.ShopProductRow row) { static AggMetrics from(OverviewAggRows.ShopProductRow row) {
@@ -131,7 +131,7 @@ public class ExportServiceImpl implements ExportService {
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额"; String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
String[] headers = { String[] headers = {
firstColumnHeader, "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)", firstColumnHeader, "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)",
"实际销售额", "成交金额", "单量", "客单价", "净销售额", "成交金额", "单量", "客单价",
"商品成本", "运费", "其他成本", "订单成本", "退款金额", taxLabel, "推广费", "刷单费", "商品成本", "运费", "其他成本", "订单成本", "退款金额", taxLabel, "推广费", "刷单费",
"毛利", "税前净利", "费比", "ROI", "税后净利" "毛利", "税前净利", "费比", "ROI", "税后净利"
}; };
@@ -179,7 +179,6 @@ public class ExportServiceImpl implements ExportService {
setCell(row, 12, objToDouble(data.get("orderCost")), style); setCell(row, 12, objToDouble(data.get("orderCost")), style);
BigDecimal salesTax = salesTaxOnNetForExport( BigDecimal salesTax = salesTaxOnNetForExport(
mapToBigDecimal(data.get("salesAmount")), mapToBigDecimal(data.get("salesAmount")),
mapToBigDecimal(data.get("refundAmount")),
taxRate); taxRate);
BigDecimal profitAfterTax = mapToBigDecimal(data.get("totalProfitBeforeTax")) BigDecimal profitAfterTax = mapToBigDecimal(data.get("totalProfitBeforeTax"))
.subtract(salesTax) .subtract(salesTax)
@@ -238,14 +237,13 @@ public class ExportServiceImpl implements ExportService {
return data; return data;
} }
private static BigDecimal salesTaxOnNetForExport(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { /** 税额 = 净销售额 × 税率 */
BigDecimal s = sales != null ? sales : BigDecimal.ZERO; private static BigDecimal salesTaxOnNetForExport(BigDecimal sales, BigDecimal taxRate) {
BigDecimal rfd = refund != null ? refund : BigDecimal.ZERO; BigDecimal base = sales != null ? sales : BigDecimal.ZERO;
BigDecimal r = taxRate != null ? taxRate : new BigDecimal("0.04");
BigDecimal base = s.subtract(rfd);
if (base.compareTo(BigDecimal.ZERO) < 0) { if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO; base = BigDecimal.ZERO;
} }
BigDecimal r = taxRate != null ? taxRate : BigDecimal.ZERO;
return base.multiply(r).setScale(2, RoundingMode.HALF_UP); return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
} }
@@ -279,12 +277,12 @@ public class ExportServiceImpl implements ExportService {
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
.subtract(totalPromoFee).subtract(totalBrushFee); .subtract(totalPromoFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnNetForExport(totalSales, totalRefund, taxRate); BigDecimal salesTax = salesTaxOnNetForExport(totalSales, taxRate);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) ? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
@@ -379,12 +377,12 @@ public class ExportServiceImpl implements ExportService {
? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP) ? totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost); BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
BigDecimal profitBeforeTax = totalSales.subtract(totalCost).subtract(totalRefund) BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
.subtract(totalPromoFee).subtract(totalBrushFee); .subtract(totalPromoFee).subtract(totalBrushFee);
BigDecimal salesTax = salesTaxOnNetForExport(totalSales, totalRefund, taxRate); BigDecimal salesTax = salesTaxOnNetForExport(totalSales, taxRate);
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax); BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
? totalSales.subtract(totalRefund).divide(totalPromoFee, 4, RoundingMode.HALF_UP) ? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0 BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP) ? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
@@ -147,8 +147,8 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO; BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO;
BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost()) BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost())
: sumCost(thisProductDocs); : sumCost(thisProductDocs);
BigDecimal tax = salesTax(sales, refund, taxRate); BigDecimal tax = salesTaxOnNet(sales, taxRate);
BigDecimal net = sales.subtract(orderCost).subtract(refund).subtract(promo).subtract(tax); BigDecimal net = sales.subtract(orderCost).subtract(promo).subtract(tax);
ProductOverviewVO vo = new ProductOverviewVO(); ProductOverviewVO vo = new ProductOverviewVO();
vo.setProductId(product.getId()); vo.setProductId(product.getId());
@@ -161,7 +161,7 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
: BigDecimal.ZERO); : BigDecimal.ZERO);
vo.setTotalTaxAmount(tax); vo.setTotalTaxAmount(tax);
vo.setTotalNetProfitAfterTax(net.setScale(2, RoundingMode.HALF_UP)); vo.setTotalNetProfitAfterTax(net.setScale(2, RoundingMode.HALF_UP));
vo.setTotalROI(roi(sales.subtract(refund), promo)); vo.setTotalROI(roi(sales, promo));
vo.setMonthOverMonthGrowth(calcPrevPeriodGrowth(companyId, product.getId(), shopIdFilter, vo.setMonthOverMonthGrowth(calcPrevPeriodGrowth(companyId, product.getId(), shopIdFilter,
start, end, sales)); start, end, sales));
@@ -264,8 +264,8 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal refund = nz(m.refundAmount()); BigDecimal refund = nz(m.refundAmount());
BigDecimal cost = m.orderCost(); BigDecimal cost = m.orderCost();
BigDecimal tax = salesTax(sales, refund, taxRate); BigDecimal tax = salesTaxOnNet(sales, taxRate);
BigDecimal pbt = sales.subtract(cost).subtract(refund).subtract(sharePromo); BigDecimal pbt = sales.subtract(cost).subtract(sharePromo);
BigDecimal pat = pbt.subtract(tax); BigDecimal pat = pbt.subtract(tax);
ProductSkuPO sku = m.productSkuId() > 0 ? skuMap.get(m.productSkuId()) : null; ProductSkuPO sku = m.productSkuId() > 0 ? skuMap.get(m.productSkuId()) : null;
@@ -290,7 +290,7 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
? sharePromo.divide(sales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO); ? sharePromo.divide(sales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO);
item.setProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP)); item.setProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP));
item.setSalesTaxAmount(tax); item.setSalesTaxAmount(tax);
item.setRoi(roi(sales.subtract(refund), sharePromo)); item.setRoi(roi(sales, sharePromo));
item.setProfitAfterTax(pat.setScale(2, RoundingMode.HALF_UP)); item.setProfitAfterTax(pat.setScale(2, RoundingMode.HALF_UP));
list.add(item); list.add(item);
} }
@@ -312,7 +312,7 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
: BigDecimal.ZERO); : BigDecimal.ZERO);
total.setProfitBeforeTax(list.stream().map(i -> nz(i.getProfitBeforeTax())).reduce(BigDecimal.ZERO, BigDecimal::add)); total.setProfitBeforeTax(list.stream().map(i -> nz(i.getProfitBeforeTax())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setSalesTaxAmount(list.stream().map(i -> nz(i.getSalesTaxAmount())).reduce(BigDecimal.ZERO, BigDecimal::add)); total.setSalesTaxAmount(list.stream().map(i -> nz(i.getSalesTaxAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setRoi(roi(total.getSalesAmount().subtract(total.getRefundAmount()), total.getPromotionFee())); total.setRoi(roi(total.getSalesAmount(), total.getPromotionFee()));
total.setProfitAfterTax(list.stream().map(i -> nz(i.getProfitAfterTax())).reduce(BigDecimal.ZERO, BigDecimal::add)); total.setProfitAfterTax(list.stream().map(i -> nz(i.getProfitAfterTax())).reduce(BigDecimal.ZERO, BigDecimal::add));
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary(); ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
@@ -388,7 +388,9 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
} }
private static BigDecimal sumSales(List<BiOrderStatDailyProductDoc> docs) { private static BigDecimal sumSales(List<BiOrderStatDailyProductDoc> docs) {
return docs.stream().map(d -> nz(d.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add); return docs.stream()
.map(d -> nz(d.getDealAmount()).subtract(nz(d.getRefundAmount())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
} }
private static BigDecimal sumRefund(List<BiOrderStatDailyProductDoc> docs) { private static BigDecimal sumRefund(List<BiOrderStatDailyProductDoc> docs) {
@@ -402,17 +404,23 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
} }
private static int sumOrders(List<BiOrderStatDailyProductDoc> docs) { private static int sumOrders(List<BiOrderStatDailyProductDoc> docs) {
return docs.stream().mapToInt(d -> d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0).sum(); return docs.stream().mapToInt(d ->
nzInt(d.getDealOrderCount()) - nzInt(d.getRefundOrderCount())).sum();
} }
private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { /** 税额 = 净销售额 × 税率 */
BigDecimal base = nz(sales).subtract(nz(refund)); private static BigDecimal salesTaxOnNet(BigDecimal sales, BigDecimal taxRate) {
BigDecimal base = nz(sales);
if (base.compareTo(BigDecimal.ZERO) < 0) { if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO; base = BigDecimal.ZERO;
} }
return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP); return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE).setScale(2, RoundingMode.HALF_UP);
} }
private static int nzInt(Integer v) {
return v != null ? v : 0;
}
private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) { private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) {
if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) { if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO; return BigDecimal.ZERO;
@@ -29,15 +29,11 @@ public class BiShopExportServiceImpl implements BiShopExportService {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04"); private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/** 与店铺概览一致:税额 = max(0, 销售额 − 退款) × 税率,两位小数。 */ /** 税额 = 净销售额 × 税率 */
private static BigDecimal salesTaxOnNetForShopExport(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { private static BigDecimal salesTaxOnNetForShopExport(BigDecimal sales, BigDecimal taxRate) {
BigDecimal s = sales != null ? sales : BigDecimal.ZERO; BigDecimal s = sales != null ? sales : BigDecimal.ZERO;
BigDecimal rfd = refund != null ? refund : BigDecimal.ZERO;
BigDecimal r = taxRate != null ? taxRate : DEFAULT_TAX_RATE; BigDecimal r = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
BigDecimal base = s.subtract(rfd); BigDecimal base = s.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : s;
if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO;
}
return base.multiply(r).setScale(2, RoundingMode.HALF_UP); return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
} }
@@ -187,7 +183,7 @@ public class BiShopExportServiceImpl implements BiShopExportService {
setCell(row, 11, feePct, style); setCell(row, 11, feePct, style);
setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), style); setCell(row, 12, nvl(p.getRoi(), BigDecimal.ZERO).setScale(4, RoundingMode.HALF_UP).doubleValue(), style);
setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style); setCell(row, 13, nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO).setScale(2, RoundingMode.HALF_UP).doubleValue(), style);
BigDecimal salesTax = salesTaxOnNetForShopExport(p.getSalesAmount(), p.getRefundAmount(), taxRate); BigDecimal salesTax = salesTaxOnNetForShopExport(p.getSalesAmount(), taxRate);
BigDecimal profitAfterTax = nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO) BigDecimal profitAfterTax = nvl(p.getTotalProfitBeforeTax(), BigDecimal.ZERO)
.subtract(salesTax) .subtract(salesTax)
.setScale(2, RoundingMode.HALF_UP); .setScale(2, RoundingMode.HALF_UP);
@@ -111,9 +111,9 @@ public class BiShopOverviewServiceImpl implements BiShopOverviewService {
BigDecimal promo = fees.promoTotal(); BigDecimal promo = fees.promoTotal();
BigDecimal brush = fees.brushTotal(); BigDecimal brush = fees.brushTotal();
BigDecimal orderCost = nz(m.productCost()).add(nz(m.freightCost())).add(nz(m.otherCost())); BigDecimal orderCost = nz(m.productCost()).add(nz(m.freightCost())).add(nz(m.otherCost()));
BigDecimal gross = nz(m.salesAmount()).subtract(orderCost).subtract(nz(m.refundAmount())); BigDecimal gross = nz(m.salesAmount()).subtract(orderCost);
BigDecimal pbt = gross.subtract(promo).subtract(brush); BigDecimal pbt = gross.subtract(promo).subtract(brush);
BigDecimal tax = salesTax(m.salesAmount(), m.refundAmount(), taxRate); BigDecimal tax = salesTaxOnNet(m.salesAmount(), taxRate);
ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO(); ShopOverviewStatisticsVO vo = new ShopOverviewStatisticsVO();
vo.setShopId(shop.getId()); vo.setShopId(shop.getId());
@@ -131,7 +131,7 @@ public class BiShopOverviewServiceImpl implements BiShopOverviewService {
vo.setTotalProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP)); vo.setTotalProfitBeforeTax(pbt.setScale(2, RoundingMode.HALF_UP));
vo.setTotalTaxAmount(tax); vo.setTotalTaxAmount(tax);
vo.setTotalNetProfitAfterTax(pbt.subtract(tax).setScale(2, RoundingMode.HALF_UP)); vo.setTotalNetProfitAfterTax(pbt.subtract(tax).setScale(2, RoundingMode.HALF_UP));
vo.setTotalROI(roi(nz(m.salesAmount()).subtract(nz(m.refundAmount())), promo)); vo.setTotalROI(roi(nz(m.salesAmount()), promo));
vo.setMonthOverMonthGrowth(calcMomGrowth(companyId, shopIds, startDate, endDate, m.salesAmount())); vo.setMonthOverMonthGrowth(calcMomGrowth(companyId, shopIds, startDate, endDate, m.salesAmount()));
fillTargets(vo, companyId, shop.getId(), startDate, endDate, m.salesAmount(), m.salesOrderCount()); fillTargets(vo, companyId, shop.getId(), startDate, endDate, m.salesAmount(), m.salesOrderCount());
@@ -366,8 +366,9 @@ public class BiShopOverviewServiceImpl implements BiShopOverviewService {
.collect(Collectors.toList())); .collect(Collectors.toList()));
} }
private static BigDecimal salesTax(BigDecimal sales, BigDecimal refund, BigDecimal taxRate) { /** 税额 = 净销售额 × 税率 */
BigDecimal base = nz(sales).subtract(nz(refund)); private static BigDecimal salesTaxOnNet(BigDecimal sales, BigDecimal taxRate) {
BigDecimal base = nz(sales);
if (base.compareTo(BigDecimal.ZERO) < 0) { if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO; base = BigDecimal.ZERO;
} }
@@ -53,8 +53,8 @@ import java.util.stream.Collectors;
* <p> * <p>
* 口径约定: * 口径约定:
* <ul> * <ul>
* <li>「实际销售额、成本、退款、多维行、趋势」等与 {@link OrderStatusStatSets} 一致:仅统计配置为「计入销售额」的订单状态, * <li>「净销售额、成本、退款、多维行、趋势」等:Mongo 存成交/退款分桶,读侧净销售 = 成交 − 退款;
* 金额字段由 {@code stat} 解析商家实收、成本、退款等。</li> * 成交不含已取消/未知;成本按状态开关计入。</li>
* <li>「成交金额」为同店铺、同时间范围内<strong>全部订单状态</strong>的商家实收合计(由汇总表 KPI 提供)。</li> * <li>「成交金额」为同店铺、同时间范围内<strong>全部订单状态</strong>的商家实收合计(由汇总表 KPI 提供)。</li>
* <li>推广费、刷单费为区间汇总;多维行与趋势中的「净利润」按销售额占比将区间推广、刷单、税额<strong>分摊</strong>到各维度或各日, * <li>推广费、刷单费为区间汇总;多维行与趋势中的「净利润」按销售额占比将区间推广、刷单、税额<strong>分摊</strong>到各维度或各日,
* 与 {@link #totalsFromOrderRows} 得到的区间总毛利润、总税额自洽。</li> * 与 {@link #totalsFromOrderRows} 得到的区间总毛利润、总税额自洽。</li>
@@ -354,7 +354,8 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
int orderCount, int salesQuantitySum, int orderCount, int salesQuantitySum,
BigDecimal totalDealAmount, int dealOrderCount, int dealQuantitySum) { BigDecimal totalDealAmount, int dealOrderCount, int dealQuantitySum) {
BigDecimal cost = pc.add(fc).add(oc); BigDecimal cost = pc.add(fc).add(oc);
BigDecimal gross = sales.subtract(cost).subtract(refund); // 入参 sales 已是净销售额(成交−退款),毛利不再二次减退款
BigDecimal gross = sales.subtract(cost);
BigDecimal pbt = gross.subtract(promotion).subtract(brush); BigDecimal pbt = gross.subtract(promotion).subtract(brush);
BigDecimal tax = salesTaxOnSales(sales, taxRate); BigDecimal tax = salesTaxOnSales(sales, taxRate);
BigDecimal aov = orderCount > 0 BigDecimal aov = orderCount > 0
@@ -389,7 +390,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO; BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO;
BigDecimal cost = row != null BigDecimal cost = row != null
? nz(row.getProductCost()).add(nz(row.getFreightCost())).add(nz(row.getOtherCost())) : BigDecimal.ZERO; ? nz(row.getProductCost()).add(nz(row.getFreightCost())).add(nz(row.getOtherCost())) : BigDecimal.ZERO;
BigDecimal gross = sales.subtract(cost).subtract(refund); BigDecimal gross = sales.subtract(cost);
BigDecimal promoB = allocShare(sales, salesTotal, periodTotals.promotion()); BigDecimal promoB = allocShare(sales, salesTotal, periodTotals.promotion());
BigDecimal brushB = allocShare(sales, salesTotal, periodTotals.brush()); BigDecimal brushB = allocShare(sales, salesTotal, periodTotals.brush());
BigDecimal taxB = allocShare(sales, salesTotal.max(BigDecimal.ONE), periodTotals.tax()); BigDecimal taxB = allocShare(sales, salesTotal.max(BigDecimal.ONE), periodTotals.tax());
@@ -527,8 +528,8 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
} }
/** /**
* 将「字符串 key → 聚合桶」转为多维表格行:每行毛利润 = 销售−成本−退款; * 将「字符串 key → 聚合桶」转为多维表格行:每行毛利润 = 净销售额−成本;
* 推广费、刷单费、税额均按该行销售额占 {@code salesTotalCompany} 比例分摊; * 推广费、刷单费、税额均按该行净销售额占 {@code salesTotalCompany} 比例分摊;
* 净利润 = 毛利润 − 分摊推广 − 分摊刷单 − 分摊税。 * 净利润 = 毛利润 − 分摊推广 − 分摊刷单 − 分摊税。
*/ */
private List<WorkbenchDimRowVO> buildDimRows(Map<String, Agg> aggs, private List<WorkbenchDimRowVO> buildDimRows(Map<String, Agg> aggs,
@@ -543,7 +544,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
if (a.sales.compareTo(BigDecimal.ZERO) <= 0 && a.refund.compareTo(BigDecimal.ZERO) <= 0) { if (a.sales.compareTo(BigDecimal.ZERO) <= 0 && a.refund.compareTo(BigDecimal.ZERO) <= 0) {
continue; continue;
} }
BigDecimal gross = a.sales.subtract(a.cost).subtract(a.refund); BigDecimal gross = a.sales.subtract(a.cost);
BigDecimal promoB = allocShare(a.sales, salesTotalCompany, promoTotal); BigDecimal promoB = allocShare(a.sales, salesTotalCompany, promoTotal);
BigDecimal brushB = allocShare(a.sales, salesTotalCompany, brushTotal); BigDecimal brushB = allocShare(a.sales, salesTotalCompany, brushTotal);
BigDecimal taxB = allocShare(a.sales, salesTotalCompany.max(BigDecimal.ONE), taxTotal); BigDecimal taxB = allocShare(a.sales, salesTotalCompany.max(BigDecimal.ONE), taxTotal);
@@ -575,7 +576,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
return rows; return rows;
} }
/** 按实际销售额降序复制排序,用于销售额排行 */ /** 按净销售额降序复制排序,用于销售额排行 */
private List<WorkbenchDimRowVO> sortByDealAmountDesc(List<WorkbenchDimRowVO> in) { private List<WorkbenchDimRowVO> sortByDealAmountDesc(List<WorkbenchDimRowVO> in) {
if (in == null) { if (in == null) {
return Collections.emptyList(); return Collections.emptyList();
@@ -600,7 +601,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
} }
/** /**
* 各平台实际销售额占比:与多维分析「平台」维度同源订单聚合;分母为当前筛选下公司实际销售额合计。 * 各平台净销售额占比:与多维分析「平台」维度同源订单聚合;分母为当前筛选下公司净销售额合计。
*/ */
private List<WorkbenchCostSliceVO> buildPlatformSalesSlices(Map<String, Agg> platformAgg, private List<WorkbenchCostSliceVO> buildPlatformSalesSlices(Map<String, Agg> platformAgg,
Map<String, String> platformNames, Map<String, String> platformNames,
@@ -630,7 +631,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
} }
/** /**
* 经营概览 KPI 卡片:成交三角、实际销售三角、净收/退款、成本分项、利润费用、运营效率等。 * 经营概览 KPI 卡片:成交三角、净销售三角、净收/退款、成本分项、利润费用、运营效率等。
*/ */
private List<WorkbenchKpiItemVO> buildKpis(Totals cur, Totals prev, Totals yoy, DateRange range, BigDecimal taxRate) { private List<WorkbenchKpiItemVO> buildKpis(Totals cur, Totals prev, Totals yoy, DateRange range, BigDecimal taxRate) {
int days = (int) (range.endDate().toEpochDay() - range.startDate().toEpochDay() + 1); int days = (int) (range.endDate().toEpochDay() - range.startDate().toEpochDay() + 1);
@@ -655,33 +656,33 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
List<WorkbenchKpiItemVO> list = new ArrayList<>(); List<WorkbenchKpiItemVO> list = new ArrayList<>();
// —— 成交口径(全状态)—— // —— 成交口径(不含已取消/未知)——
list.add(kpi("成交金额", formatYuanComma(cur.totalDealAmount()), "元", cur.totalDealAmount(), prev.totalDealAmount(), yoy.totalDealAmount(), list.add(kpi("成交金额", formatYuanComma(cur.totalDealAmount()), "元", cur.totalDealAmount(), prev.totalDealAmount(), yoy.totalDealAmount(),
"全状态实收", cur.totalDealAmount(), true)); "成交状态实收", cur.totalDealAmount(), true));
list.add(kpiCount("成交单量", cur.dealOrderCount(), prev.dealOrderCount(), yoy.dealOrderCount(), "单", list.add(kpiCount("成交单量", cur.dealOrderCount(), prev.dealOrderCount(), yoy.dealOrderCount(), "单",
"日均 " + avgDailyDealOrders.stripTrailingZeros().toPlainString() + " 单")); "日均 " + avgDailyDealOrders.stripTrailingZeros().toPlainString() + " 单"));
list.add(kpiCount("成交销量", cur.dealQuantitySum(), prev.dealQuantitySum(), yoy.dealQuantitySum(), "件", "全状态件数")); list.add(kpiCount("成交销量", cur.dealQuantitySum(), prev.dealQuantitySum(), yoy.dealQuantitySum(), "件", "成交状态件数"));
list.add(kpi("成交客单价", formatYuanComma(cur.dealAverageOrderValue()), "元", list.add(kpi("成交客单价", formatYuanComma(cur.dealAverageOrderValue()), "元",
cur.dealAverageOrderValue(), prev.dealAverageOrderValue(), yoy.dealAverageOrderValue(), cur.dealAverageOrderValue(), prev.dealAverageOrderValue(), yoy.dealAverageOrderValue(),
"成交金额/成交单量", cur.dealAverageOrderValue(), false)); "成交金额/成交单量", cur.dealAverageOrderValue(), false));
// —— 实际销售口径(计入销售额状态)—— // —— 净销售口径(成交 − 退款)——
list.add(kpi("实际销售额", formatYuanComma(cur.totalSales()), "元", cur.totalSales(), prev.totalSales(), yoy.totalSales(), list.add(kpi("净销售额", formatYuanComma(cur.totalSales()), "元", cur.totalSales(), prev.totalSales(), yoy.totalSales(),
"计入销售状态", cur.totalSales(), true)); "成交−退款", cur.totalSales(), true));
list.add(kpiCount("销售单量", cur.orderCount(), prev.orderCount(), yoy.orderCount(), "单", list.add(kpiCount("净销售单量", cur.orderCount(), prev.orderCount(), yoy.orderCount(), "单",
"日均 " + avgDailySalesOrders.stripTrailingZeros().toPlainString() + " 单")); "日均 " + avgDailySalesOrders.stripTrailingZeros().toPlainString() + " 单"));
list.add(kpiCount("实际销量", cur.salesQuantitySum(), prev.salesQuantitySum(), yoy.salesQuantitySum(), "件", list.add(kpiCount("净销量", cur.salesQuantitySum(), prev.salesQuantitySum(), yoy.salesQuantitySum(), "件",
"计入销售件数")); "成交件数−退款件数"));
list.add(kpi("销售客单价", formatYuanComma(cur.averageOrderValue()), "元", list.add(kpi("净销售客单价", formatYuanComma(cur.averageOrderValue()), "元",
cur.averageOrderValue(), prev.averageOrderValue(), yoy.averageOrderValue(), cur.averageOrderValue(), prev.averageOrderValue(), yoy.averageOrderValue(),
"销售额/销售单量", cur.averageOrderValue(), false)); "净销售额/净销售单量", cur.averageOrderValue(), false));
// —— 净收与退款 —— // —— 退款 ——
list.add(kpi("退款额", formatYuanComma(cur.totalRefund()), "元", cur.totalRefund(), prev.totalRefund(), yoy.totalRefund(), list.add(kpi("退款额", formatYuanComma(cur.totalRefund()), "元", cur.totalRefund(), prev.totalRefund(), yoy.totalRefund(),
"计入退款状态", cur.totalRefund(), true)); "计入退款状态", cur.totalRefund(), true));
list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP).toPlainString(), "%", list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP).toPlainString(), "%",
refundRate, safePct(prev.totalRefund(), prev.totalSales()), safePct(yoy.totalRefund(), yoy.totalSales()), refundRate, safePct(prev.totalRefund(), prev.totalSales()), safePct(yoy.totalRefund(), yoy.totalSales()),
"退款/实际销售额", null, null)); "退款/净销售额", null, null));
// —— 成本 —— // —— 成本 ——
list.add(kpi("订单成本", formatYuanComma(cur.totalCost()), "元", cur.totalCost(), prev.totalCost(), yoy.totalCost(), list.add(kpi("订单成本", formatYuanComma(cur.totalCost()), "元", cur.totalCost(), prev.totalCost(), yoy.totalCost(),
@@ -709,7 +710,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
// —— 运营效率 —— // —— 运营效率 ——
list.add(kpi("广告ROI", roi.stripTrailingZeros().toPlainString(), ":1", roi, prevRoi, yoyRoi, list.add(kpi("广告ROI", roi.stripTrailingZeros().toPlainString(), ":1", roi, prevRoi, yoyRoi,
"实际销售额/推广费", null, null)); "净销售额/推广费", null, null));
return list; return list;
} }
@@ -764,7 +765,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
} }
/** /**
* 税额 = 实际销售额 * 税率(实际销售额已按状态剔除退款单,不再二次扣退款)。 * 税额 = 净销售额 * 税率(净销售额 = 成交 − 退款,不再二次扣退款)。
*/ */
private BigDecimal salesTaxOnSales(BigDecimal salesAmount, BigDecimal rate) { private BigDecimal salesTaxOnSales(BigDecimal salesAmount, BigDecimal rate) {
BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO; BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO;
@@ -8,7 +8,8 @@ import java.util.Optional;
/** /**
* 内部订单状态(软约定,无状态表)。 * 内部订单状态(软约定,无状态表)。
* 统计五维开关写死在枚举元数据上。 * 统计四维开关写死在枚举元数据上:成交 / 商品成本 / 运费 / 其他成本 / 退款。
* 净销售由读侧「成交 − 退款」推导,不再单独存销售额桶。
*/ */
@Getter @Getter
public enum OrderStatus { public enum OrderStatus {
@@ -23,29 +24,30 @@ public enum OrderStatus {
CANCELLED("CANCELLED", "已取消", "#bfbfbf", 40, CANCELLED("CANCELLED", "已取消", "#bfbfbf", 40,
false, false, false, false, false), false, false, false, false, false),
REFUNDING("REFUNDING", "退款中", "#fa8c16", 50, REFUNDING("REFUNDING", "退款中", "#fa8c16", 50,
false, false, false, false, true), true, false, false, false, true),
REFUNDED("REFUNDED", "已退款", "#f5222d", 60, REFUNDED("REFUNDED", "已退款", "#f5222d", 60,
false, false, false, false, true); true, false, false, false, true);
private final String code; private final String code;
private final String label; private final String label;
private final String color; private final String color;
private final int sortOrder; private final int sortOrder;
private final boolean includeSalesAmount; /** 计入成交金额/单量/件数(不含已取消、未知) */
private final boolean includeDeal;
private final boolean includeProductCost; private final boolean includeProductCost;
private final boolean includeFreightCost; private final boolean includeFreightCost;
private final boolean includeOtherCost; private final boolean includeOtherCost;
private final boolean includeRefund; private final boolean includeRefund;
OrderStatus(String code, String label, String color, int sortOrder, OrderStatus(String code, String label, String color, int sortOrder,
boolean includeSalesAmount, boolean includeProductCost, boolean includeDeal, boolean includeProductCost,
boolean includeFreightCost, boolean includeOtherCost, boolean includeFreightCost, boolean includeOtherCost,
boolean includeRefund) { boolean includeRefund) {
this.code = code; this.code = code;
this.label = label; this.label = label;
this.color = color; this.color = color;
this.sortOrder = sortOrder; this.sortOrder = sortOrder;
this.includeSalesAmount = includeSalesAmount; this.includeDeal = includeDeal;
this.includeProductCost = includeProductCost; this.includeProductCost = includeProductCost;
this.includeFreightCost = includeFreightCost; this.includeFreightCost = includeFreightCost;
this.includeOtherCost = includeOtherCost; this.includeOtherCost = includeOtherCost;
@@ -16,7 +16,8 @@ public class OrderStatusMetaVO {
private Integer sortOrder; private Integer sortOrder;
private boolean includeSalesAmount; /** 计入成交金额/单量/件数 */
private boolean includeDeal;
private boolean includeProductCost; private boolean includeProductCost;
@@ -25,7 +25,7 @@ public final class OrderStatusMetaSupport {
vo.setLabel(status.getLabel()); vo.setLabel(status.getLabel());
vo.setColor(status.getColor()); vo.setColor(status.getColor());
vo.setSortOrder(status.getSortOrder()); vo.setSortOrder(status.getSortOrder());
vo.setIncludeSalesAmount(status.isIncludeSalesAmount()); vo.setIncludeDeal(status.isIncludeDeal());
vo.setIncludeProductCost(status.isIncludeProductCost()); vo.setIncludeProductCost(status.isIncludeProductCost());
vo.setIncludeFreightCost(status.isIncludeFreightCost()); vo.setIncludeFreightCost(status.isIncludeFreightCost());
vo.setIncludeOtherCost(status.isIncludeOtherCost()); vo.setIncludeOtherCost(status.isIncludeOtherCost());
@@ -15,6 +15,7 @@ import java.util.stream.Collectors;
/** /**
* 订单状态各统计维度的生效集合(由 {@link OrderStatus} 枚举元数据解析,全局固定)。 * 订单状态各统计维度的生效集合(由 {@link OrderStatus} 枚举元数据解析,全局固定)。
* 净销售不在此处分桶,由读侧「成交 − 退款」推导。
*/ */
@Getter @Getter
public final class OrderStatusStatSets { public final class OrderStatusStatSets {
@@ -22,20 +23,20 @@ public final class OrderStatusStatSets {
private static final OrderStatusStatSets GLOBAL = fromEnum(); private static final OrderStatusStatSets GLOBAL = fromEnum();
private final List<String> unionStatusCodes; private final List<String> unionStatusCodes;
private final Set<String> salesCodes; private final Set<String> dealCodes;
private final Set<String> productCostCodes; private final Set<String> productCostCodes;
private final Set<String> freightCostCodes; private final Set<String> freightCostCodes;
private final Set<String> otherCostCodes; private final Set<String> otherCostCodes;
private final Set<String> refundCodes; private final Set<String> refundCodes;
private OrderStatusStatSets(List<String> unionStatusCodes, private OrderStatusStatSets(List<String> unionStatusCodes,
Set<String> salesCodes, Set<String> dealCodes,
Set<String> productCostCodes, Set<String> productCostCodes,
Set<String> freightCostCodes, Set<String> freightCostCodes,
Set<String> otherCostCodes, Set<String> otherCostCodes,
Set<String> refundCodes) { Set<String> refundCodes) {
this.unionStatusCodes = unionStatusCodes; this.unionStatusCodes = unionStatusCodes;
this.salesCodes = salesCodes; this.dealCodes = dealCodes;
this.productCostCodes = productCostCodes; this.productCostCodes = productCostCodes;
this.freightCostCodes = freightCostCodes; this.freightCostCodes = freightCostCodes;
this.otherCostCodes = otherCostCodes; this.otherCostCodes = otherCostCodes;
@@ -47,7 +48,7 @@ public final class OrderStatusStatSets {
} }
private static OrderStatusStatSets fromEnum() { private static OrderStatusStatSets fromEnum() {
Set<String> sales = new HashSet<>(); Set<String> deal = new HashSet<>();
Set<String> productCost = new HashSet<>(); Set<String> productCost = new HashSet<>();
Set<String> freightCost = new HashSet<>(); Set<String> freightCost = new HashSet<>();
Set<String> otherCost = new HashSet<>(); Set<String> otherCost = new HashSet<>();
@@ -55,7 +56,7 @@ public final class OrderStatusStatSets {
Set<String> union = new HashSet<>(); Set<String> union = new HashSet<>();
for (OrderStatus s : OrderStatus.values()) { for (OrderStatus s : OrderStatus.values()) {
boolean any = false; boolean any = false;
if (s.isIncludeSalesAmount()) { sales.add(s.getCode()); any = true; } if (s.isIncludeDeal()) { deal.add(s.getCode()); any = true; }
if (s.isIncludeProductCost()) { productCost.add(s.getCode()); any = true; } if (s.isIncludeProductCost()) { productCost.add(s.getCode()); any = true; }
if (s.isIncludeFreightCost()) { freightCost.add(s.getCode()); any = true; } if (s.isIncludeFreightCost()) { freightCost.add(s.getCode()); any = true; }
if (s.isIncludeOtherCost()) { otherCost.add(s.getCode()); any = true; } if (s.isIncludeOtherCost()) { otherCost.add(s.getCode()); any = true; }
@@ -66,7 +67,7 @@ public final class OrderStatusStatSets {
Collections.sort(unionList); Collections.sort(unionList);
return new OrderStatusStatSets( return new OrderStatusStatSets(
Collections.unmodifiableList(unionList), Collections.unmodifiableList(unionList),
Collections.unmodifiableSet(sales), Collections.unmodifiableSet(deal),
Collections.unmodifiableSet(productCost), Collections.unmodifiableSet(productCost),
Collections.unmodifiableSet(freightCost), Collections.unmodifiableSet(freightCost),
Collections.unmodifiableSet(otherCost), Collections.unmodifiableSet(otherCost),
@@ -77,8 +78,8 @@ public final class OrderStatusStatSets {
return unionStatusCodes.isEmpty(); return unionStatusCodes.isEmpty();
} }
public boolean includesSales(String status) { public boolean includesDeal(String status) {
return status != null && salesCodes.contains(status); return status != null && dealCodes.contains(status);
} }
public boolean includesProductCost(String status) { public boolean includesProductCost(String status) {
@@ -116,8 +117,8 @@ public final class OrderStatusStatSets {
return sum; return sum;
} }
public BigDecimal receivedForSales(OrderPO order) { public BigDecimal receivedForDeal(OrderPO order) {
return includesSales(order.getStatus()) ? receivedAmount(order) : BigDecimal.ZERO; return includesDeal(order.getStatus()) ? receivedAmount(order) : BigDecimal.ZERO;
} }
public BigDecimal productCostForStats(OrderPO order, OrderItemPO item) { public BigDecimal productCostForStats(OrderPO order, OrderItemPO item) {
@@ -7,7 +7,7 @@ export namespace WorkbenchVO {
export interface DimRow { export interface DimRow {
key: string; key: string;
name: string; name: string;
/** 实际销售额(元,两位小数):计入「销售额」的订单状态配置下的商家实收合计 */ /** 净销售额(元,两位小数):成交 − 退款 */
salesYuan?: number; salesYuan?: number;
grossProfitYuan?: number; grossProfitYuan?: number;
netProfitYuan?: number; netProfitYuan?: number;
@@ -35,15 +35,15 @@ export namespace WorkbenchVO {
export interface TrendPoint { export interface TrendPoint {
date: string; date: string;
/** 日成交金额(元):全部订单状态商家实收 */ /** 日成交金额(元):计入成交状态商家实收(不含已取消、未知) */
dealYuan?: number; dealYuan?: number;
/** 日成交单量:与 KPI「成交单量」同口径 */ /** 日成交单量:与 KPI「成交单量」同口径 */
dealOrderCount?: number; dealOrderCount?: number;
/** 日实际销售额(元),与 KPI「实际销售额」同口径 */ /** 日净销售额(元),与 KPI「净销售额」同口径 */
salesYuan?: number; salesYuan?: number;
/** 日实际销售单量:与 KPI「销售单量」同口径 */ /** 日净销售单量:与 KPI「净销售单量」同口径 */
salesOrderCount?: number; salesOrderCount?: number;
/** 日毛利润(元)= 销售额−成本−退款 */ /** 日毛利润(元)= 净销售额 − 订单成本 */
profitYuan?: number; profitYuan?: number;
/** 日净利润(元),与 KPI「净利润」及多维分析分摊口径一致 */ /** 日净利润(元),与 KPI「净利润」及多维分析分摊口径一致 */
netProfitYuan?: number; netProfitYuan?: number;
@@ -55,14 +55,14 @@ export namespace WorkbenchVO {
name: string; name: string;
/** 金额(元,两位小数) */ /** 金额(元,两位小数) */
value?: number; value?: number;
/** 占实际销售额合计的比例 % */ /** 占净销售额合计的比例 % */
pct?: number; pct?: number;
} }
export interface FinancePanel { export interface FinancePanel {
kpis: KpiItem[]; kpis: KpiItem[];
dealTrend: TrendPoint[]; dealTrend: TrendPoint[];
/** 各平台实际销售额占比 */ /** 各平台净销售额占比 */
platformSalesShare: PieSlice[]; platformSalesShare: PieSlice[];
/** 环比对比期起(yyyy-MM-dd) */ /** 环比对比期起(yyyy-MM-dd) */
momCompareDateStart?: string | null; momCompareDateStart?: string | null;
@@ -9,7 +9,7 @@ export namespace OrderStatusVO {
label: string; label: string;
color?: string; color?: string;
sortOrder?: number; sortOrder?: number;
includeSalesAmount: boolean; includeDeal: boolean;
includeProductCost: boolean; includeProductCost: boolean;
includeFreightCost: boolean; includeFreightCost: boolean;
includeOtherCost: boolean; includeOtherCost: boolean;
@@ -6,17 +6,17 @@ export const overviewTableHints = {
targetOrderCount: '区间内各店铺月度目标单量之和。', targetOrderCount: '区间内各店铺月度目标单量之和。',
orderCountAchievementRate: '实际单量 / 目标单量 * 100%。', orderCountAchievementRate: '实际单量 / 目标单量 * 100%。',
targetAmount: '区间内各店铺月度目标销售额之和。', targetAmount: '区间内各店铺月度目标销售额之和。',
salesAmountAchievementRate: '实际销售额 / 目标额 * 100%。', salesAmountAchievementRate: '净销售额 / 目标额 * 100%。',
salesAmount: '商家实收合计(排除退款)。', salesAmount: '成交金额 − 退款额(不含已取消、未知订单)。',
dealAmount: '全部订单状态的商家实收合计。', dealAmount: '计入成交状态的商家实收合计(不含已取消、未知)。',
grossProfit: '实际销售额 − 订单成本 − 退款额。', grossProfit: '净销售额 − 订单成本。',
/** 与 salesAmount 同口径,表头文案为「销售额」时使用 */ /** 与 salesAmount 同口径,表头文案为「销售额」时使用 */
salesAmountShort: '商家实收合计(排除退款)。', salesAmountShort: '成交金额 − 退款额(不含已取消、未知订单)。',
orderCount: '计入销售额状态的订单笔数。', orderCount: '净销售单量 = 成交单量 − 退款单量。',
orderCountSku: '该 SKU 计入统计的订单笔数;括号内为件数。', orderCountSku: '该 SKU 净销售单量;括号内为净销量件数。',
/** @deprecated 使用 orderCountSku */ /** @deprecated 使用 orderCountSku */
orderCountSpec: '该 SKU 计入统计的订单笔数;括号内为件数。', orderCountSpec: '该 SKU 净销售单量;括号内为净销量件数。',
averageOrderValue: '销售额 / 单量。', averageOrderValue: '净销售额 / 净销售单量。',
productCost: '商品成本合计。', productCost: '商品成本合计。',
shippingCost: '运费成本合计。', shippingCost: '运费成本合计。',
otherCost: '其他成本合计。', otherCost: '其他成本合计。',
@@ -27,18 +27,18 @@ export const overviewTableHints = {
/** @deprecated 使用 promotionFeeSku */ /** @deprecated 使用 promotionFeeSku */
promotionFeeSpec: '店铺推广费 *(该 SKU 订单数 / 区间总订单数)。', promotionFeeSpec: '店铺推广费 *(该 SKU 订单数 / 区间总订单数)。',
brushFee: '刷单费合计。', brushFee: '刷单费合计。',
feeRatioShopRow: '推广费 / 实际销售额;合计行含刷单费。', feeRatioShopRow: '推广费 / 净销售额;合计行含刷单费。',
feeRatioShopCategoryRow: '推广费 / 实际销售额;合计行含刷单费。', feeRatioShopCategoryRow: '推广费 / 净销售额;合计行含刷单费。',
feeRatioCategoryRow: '推广费 / 实际销售额;合计行含刷单费。', feeRatioCategoryRow: '推广费 / 净销售额;合计行含刷单费。',
feeRatioPlatform: '(推广费 + 刷单费)/ 实际销售额。', feeRatioPlatform: '(推广费 + 刷单费)/ 净销售额。',
feeRatioSku: '推广费 / 销售额(百分数 0–100)。', feeRatioSku: '推广费 / 净销售额(百分数 0–100)。',
/** @deprecated 使用 feeRatioSku */ /** @deprecated 使用 feeRatioSku */
feeRatioSpec: '推广费 / 销售额(百分数 0–100)。', feeRatioSpec: '推广费 / 净销售额(百分数 0–100)。',
totalProfitBeforeTax: '毛利 − 推广费 − 刷单费。', totalProfitBeforeTax: '毛利 − 推广费 − 刷单费。',
profitBeforeTaxSku: '销售额 − 订单成本 − 退款额 − 推广费。', profitBeforeTaxSku: '净销售额 − 订单成本 − 推广费。',
/** @deprecated 使用 profitBeforeTaxSku */ /** @deprecated 使用 profitBeforeTaxSku */
profitBeforeTaxSpec: '销售额 − 订单成本 − 退款额 − 推广费。', profitBeforeTaxSpec: '净销售额 − 订单成本 − 推广费。',
roi: '实际销售额 / 推广费。', roi: '净销售额 / 推广费。',
profitAfterTax: '税前净利 − 税额。', profitAfterTax: '税前净利 − 税额。',
profitAfterTaxNet: '税前净利 − 税额。', profitAfterTaxNet: '税前净利 − 税额。',
} as const; } as const;
@@ -48,5 +48,5 @@ export const storeOverviewHints = overviewTableHints;
export function salesTaxColumnHint(taxRate: number): string { export function salesTaxColumnHint(taxRate: number): string {
const pct = (taxRate * 100).toFixed(0); const pct = (taxRate * 100).toFixed(0);
return `实际销售额 * ${pct}%。`; return `净销售额 * ${pct}%。`;
} }
@@ -103,7 +103,7 @@ function buildCompareMetrics(
return [ return [
{ {
key: 'salesAmount', key: 'salesAmount',
label: '实际销售额', label: '净销售额',
hint: overviewTableHints.salesAmount, hint: overviewTableHints.salesAmount,
format: 'money', format: 'money',
valueA: z(a, (r) => r.salesAmount), valueA: z(a, (r) => r.salesAmount),
@@ -169,7 +169,7 @@ const cellRoi = (v: number | null | undefined) =>
<tr class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-sm"> <tr class="bg-slate-50 dark:bg-[hsl(240deg_3.7%_15.9%)] text-sm">
<th class="border-b border-l px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]"> <th class="border-b border-l px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount"> <OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400"> <th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400">
@@ -63,7 +63,7 @@ function drawPie() {
const val = Number(params.value ?? 0); const val = Number(params.value ?? 0);
const row = props.platformSalesShare.find((r) => r.name === name); const row = props.platformSalesShare.find((r) => r.name === name);
const pctText = const pctText =
row?.pct != null ? `${row.pct}%(占实际销售额)` : ''; row?.pct != null ? `${row.pct}%(占净销售额)` : '';
return `${name}<br/>约 ${formatWanShort(val)}<br/>${formatYuanDetail(val)}<br/>${pctText}`; return `${name}<br/>约 ${formatWanShort(val)}<br/>${formatYuanDetail(val)}<br/>${pctText}`;
}, },
}, },
@@ -167,10 +167,10 @@ defineExpose({ redraw });
<h3 <h3
class="text-base font-semibold text-slate-800 dark:text-[hsl(0deg_0%_95%)]" class="text-base font-semibold text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
> >
各平台实际销售额分布 各平台净销售额分布
</h3> </h3>
<p class="mt-1 text-xs font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"> <p class="mt-1 text-xs font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
占当前筛选条件下实际销售额合计的比例 占当前筛选条件下净销售额合计的比例
</p> </p>
</div> </div>
<div class="px-5 py-4 md:px-6 md:py-5"> <div class="px-5 py-4 md:px-6 md:py-5">
@@ -125,8 +125,8 @@ function drawFinanceTrend() {
`<div style="font-weight:800;margin-bottom:6px">${title}</div>`, `<div style="font-weight:800;margin-bottom:6px">${title}</div>`,
`<span style="color:${isDark ? '#fbbf24' : '#d97706'}">●</span> 成交金额:${formatWanWithYuanDetail(deal)}`, `<span style="color:${isDark ? '#fbbf24' : '#d97706'}">●</span> 成交金额:${formatWanWithYuanDetail(deal)}`,
`<span style="color:${isDark ? '#f59e0b' : '#b45309'}">●</span> 成交单量:${dealOrder} 单`, `<span style="color:${isDark ? '#f59e0b' : '#b45309'}">●</span> 成交单量:${dealOrder} 单`,
`<span style="color:${isDark ? '#60a5fa' : '#1d4ed8'}">●</span> 实际销售额:${formatWanWithYuanDetail(sales)}`, `<span style="color:${isDark ? '#60a5fa' : '#1d4ed8'}">●</span> 净销售额:${formatWanWithYuanDetail(sales)}`,
`<span style="color:${isDark ? '#38bdf8' : '#0369a1'}">●</span> 实际销售单量:${salesOrder} 单`, `<span style="color:${isDark ? '#38bdf8' : '#0369a1'}">●</span> 净销售单量:${salesOrder} 单`,
`<span style="color:${isDark ? '#34d399' : '#059669'}">●</span> 毛利:${formatWanWithYuanDetail(gross)} <span style="opacity:0.75">(毛利率 ${pctOfSales(gross, sales)})</span>`, `<span style="color:${isDark ? '#34d399' : '#059669'}">●</span> 毛利:${formatWanWithYuanDetail(gross)} <span style="opacity:0.75">(毛利率 ${pctOfSales(gross, sales)})</span>`,
`<span style="color:${isDark ? '#c4b5fd' : '#6d28d9'}">●</span> 净利:${formatWanWithYuanDetail(net)} <span style="opacity:0.75">(净利率 ${pctOfSales(net, sales)})</span>`, `<span style="color:${isDark ? '#c4b5fd' : '#6d28d9'}">●</span> 净利:${formatWanWithYuanDetail(net)} <span style="opacity:0.75">(净利率 ${pctOfSales(net, sales)})</span>`,
]; ];
@@ -145,9 +145,9 @@ function drawFinanceTrend() {
textStyle: { color: axisLabel, fontWeight: 700, fontSize: 11 }, textStyle: { color: axisLabel, fontWeight: 700, fontSize: 11 },
data: [ data: [
'成交金额', '成交金额',
'实际销售额', '净销售额',
'成交单量', '成交单量',
'实际销售单量', '净销售单量',
'毛利', '毛利',
'净利', '净利',
'退款', '退款',
@@ -246,7 +246,7 @@ function drawFinanceTrend() {
z: 1, z: 1,
}, },
{ {
name: '实际销售额', name: '净销售额',
type: 'bar', type: 'bar',
barMaxWidth: 22, barMaxWidth: 22,
itemStyle: { itemStyle: {
@@ -283,7 +283,7 @@ function drawFinanceTrend() {
z: 5, z: 5,
}, },
{ {
name: '实际销售单量', name: '净销售单量',
type: 'line', type: 'line',
yAxisIndex: 1, yAxisIndex: 1,
smooth: 0.35, smooth: 0.35,
@@ -433,7 +433,7 @@ defineExpose({ redraw });
经营趋势 经营趋势
</h3> </h3>
<p class="mt-1 text-xs font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"> <p class="mt-1 text-xs font-normal text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]">
柱状为成交金额 / 实际销售额,折线含成交单量 / 实际销售单量与毛利 / 净利 柱状为成交金额 / 净销售额,折线含成交单量 / 净销售单量与毛利 / 净利
</p> </p>
</div> </div>
<div <div
@@ -247,7 +247,7 @@ const sortedData = computed(() => {
<!-- 规模子列 --> <!-- 规模子列 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]"> <th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount"> <OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-amber-700 dark:text-amber-400"> <th class="border-b border-slate-200 dark:border-b-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-amber-700 dark:text-amber-400">
@@ -193,7 +193,7 @@ const cellRoi = (v: number | null | undefined) =>
<!-- 规模 --> <!-- 规模 -->
<th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]"> <th class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="storeOverviewHints.salesAmount"> <OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400"> <th class="border-b px-6 py-4 font-black text-amber-700 dark:text-amber-400">
@@ -3,15 +3,15 @@ import { overviewTableHints, salesTaxColumnHint } from '#/utils/overview-table-h
/** 工作台经营 KPI 问号说明 */ /** 工作台经营 KPI 问号说明 */
const FINANCE_KPI_HINTS: Record<string, string> = { const FINANCE_KPI_HINTS: Record<string, string> = {
成交金额: overviewTableHints.dealAmount, 成交金额: overviewTableHints.dealAmount,
成交单量: '全部订单状态的订单笔数。', 成交单量: '计入成交状态的订单笔数(不含已取消、未知)。',
成交销量: '全部订单状态的销售件数。', 成交销量: '计入成交状态的销售件数(不含已取消、未知)。',
成交客单价: '成交金额 / 成交单量。', 成交客单价: '成交金额 / 成交单量。',
实际销售额: overviewTableHints.salesAmount, 净销售额: overviewTableHints.salesAmount,
销售单量: '计入销售额状态的订单笔数。', 净销售单量: overviewTableHints.orderCount,
实际销量: '计入销售额状态的销售件数。', 净销量: '成交销量 − 退款件数。',
销售客单价: '实际销售额 / 销售单量。', 净销售客单价: '净销售额 / 净销售单量。',
退款额: overviewTableHints.refundAmount, 退款额: overviewTableHints.refundAmount,
退款率: '退款额 / 实际销售额 * 100%。', 退款率: '退款额 / 净销售额 * 100%。',
订单成本: overviewTableHints.orderCost, 订单成本: overviewTableHints.orderCost,
商品成本: overviewTableHints.productCost, 商品成本: overviewTableHints.productCost,
运费成本: overviewTableHints.shippingCost, 运费成本: overviewTableHints.shippingCost,
@@ -61,10 +61,10 @@ export const FINANCE_KPI_METRIC_META: Record<string, FinanceKpiMetricMeta> = {
成交单量: { label: '成交单量', upIsGood: true, icon: IconOrders }, 成交单量: { label: '成交单量', upIsGood: true, icon: IconOrders },
成交销量: { label: '成交销量', upIsGood: true, icon: IconPackage }, 成交销量: { label: '成交销量', upIsGood: true, icon: IconPackage },
成交客单价: { label: '成交客单价', upIsGood: true, icon: IconAov }, 成交客单价: { label: '成交客单价', upIsGood: true, icon: IconAov },
实际销售额: { label: '实际销售额', upIsGood: true, icon: IconSales }, 净销售额: { label: '净销售额', upIsGood: true, icon: IconSales },
销售单量: { label: '销售单量', upIsGood: true, icon: IconOrders }, 净销售单量: { label: '净销售单量', upIsGood: true, icon: IconOrders },
实际销量: { label: '实际销量', upIsGood: true, icon: IconPackage }, 净销量: { label: '净销量', upIsGood: true, icon: IconPackage },
销售客单价: { label: '销售客单价', upIsGood: true, icon: IconAov }, 净销售客单价: { label: '净销售客单价', upIsGood: true, icon: IconAov },
退款额: { label: '退款额', upIsGood: false, icon: IconRefund }, 退款额: { label: '退款额', upIsGood: false, icon: IconRefund },
退款率: { label: '退款率', upIsGood: false, icon: IconPercent }, 退款率: { label: '退款率', upIsGood: false, icon: IconPercent },
订单成本: { label: '订单成本', upIsGood: false, icon: IconCost }, 订单成本: { label: '订单成本', upIsGood: false, icon: IconCost },
@@ -97,32 +97,32 @@ export const FINANCE_KPI_CARDS: FinanceKpiCardDef[] = [
{ {
id: 'revenue', id: 'revenue',
title: '销售额', title: '销售额',
metrics: ['实际销售额', '成交金额'], metrics: ['净销售额', '成交金额'],
defaultPrimary: '实际销售额', defaultPrimary: '净销售额',
icon: IconSales, icon: IconSales,
tone: 'blue', tone: 'blue',
}, },
{ {
id: 'orders', id: 'orders',
title: '单量', title: '单量',
metrics: ['销售单量', '成交单量'], metrics: ['净销售单量', '成交单量'],
defaultPrimary: '销售单量', defaultPrimary: '净销售单量',
icon: IconOrders, icon: IconOrders,
tone: 'blue', tone: 'blue',
}, },
{ {
id: 'qty', id: 'qty',
title: '销量', title: '销量',
metrics: ['实际销量', '成交销量'], metrics: ['净销量', '成交销量'],
defaultPrimary: '实际销量', defaultPrimary: '净销量',
icon: IconPackage, icon: IconPackage,
tone: 'cyan', tone: 'cyan',
}, },
{ {
id: 'aov', id: 'aov',
title: '客单价', title: '客单价',
metrics: ['销售客单价', '成交客单价'], metrics: ['净销售客单价', '成交客单价'],
defaultPrimary: '销售客单价', defaultPrimary: '净销售客单价',
icon: IconAov, icon: IconAov,
tone: 'purple', tone: 'purple',
}, },
@@ -192,7 +192,10 @@ export function normalizePrimary(
primary: string | undefined | null, primary: string | undefined | null,
): string { ): string {
let p = primary ?? undefined; let p = primary ?? undefined;
if (p === '客单价') p = '销售客单价'; if (p === '客单价' || p === '销售客单价') p = '净销售客单价';
if (p === '实际销售额') p = '净销售额';
if (p === '销售单量' || p === '订单量') p = '净销售单量';
if (p === '实际销量') p = '净销量';
if (p && card.metrics.includes(p)) return p; if (p && card.metrics.includes(p)) return p;
return card.defaultPrimary; return card.defaultPrimary;
} }
@@ -210,8 +213,10 @@ export function migrateV1LabelsToCardIds(labels: string[]): FinanceKpiCardId[] {
const mapped = new Set<FinanceKpiCardId>(); const mapped = new Set<FinanceKpiCardId>();
const labelSet = new Set( const labelSet = new Set(
labels.map((l) => { labels.map((l) => {
if (l === '订单量') return '销售单量'; if (l === '订单量' || l === '销售单量') return '净销售单量';
if (l === '客单价') return '销售客单价'; if (l === '客单价' || l === '销售客单价') return '净销售客单价';
if (l === '实际销售额') return '净销售额';
if (l === '实际销量') return '净销量';
return l; return l;
}), }),
); );
@@ -226,14 +231,16 @@ export function migrateV1LabelsToCardIds(labels: string[]): FinanceKpiCardId[] {
return sortCardIdsByCatalog([...mapped]); return sortCardIdsByCatalog([...mapped]);
} }
/** 旧 v1:若勾选了某卡下多个指标,优先用「实际销售额」等默认偏好,否则取第一个命中的成员 */ /** 旧 v1:若勾选了某卡下多个指标,优先用默认偏好,否则取第一个命中的成员 */
export function migrateV1PrimaryByCard( export function migrateV1PrimaryByCard(
labels: string[], labels: string[],
): Partial<Record<FinanceKpiCardId, string>> { ): Partial<Record<FinanceKpiCardId, string>> {
const labelSet = new Set( const labelSet = new Set(
labels.map((l) => { labels.map((l) => {
if (l === '订单量') return '销售单量'; if (l === '订单量' || l === '销售单量') return '净销售单量';
if (l === '客单价') return '销售客单价'; if (l === '客单价' || l === '销售客单价') return '净销售客单价';
if (l === '实际销售额') return '净销售额';
if (l === '实际销量') return '净销量';
return l; return l;
}), }),
); );
@@ -118,7 +118,7 @@ const drawMultiBarChart = () => {
itemHeight: 8, itemHeight: 8,
itemGap: 4, itemGap: 4,
textStyle: { color: axisLabel, fontWeight: 700, fontSize: 10 }, textStyle: { color: axisLabel, fontWeight: 700, fontSize: 10 },
data: ['实际销售额(万)', '毛利额(万)', '净利额(万)', '退款金额(万)'], data: ['净销售额(万)', '毛利额(万)', '净利额(万)', '退款金额(万)'],
}, },
grid: { grid: {
left: '2%', left: '2%',
@@ -148,7 +148,7 @@ const drawMultiBarChart = () => {
}, },
series: [ series: [
{ {
name: '实际销售额(万)', name: '净销售额(万)',
type: 'bar', type: 'bar',
data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))), data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))),
barMaxWidth: 16, barMaxWidth: 16,
@@ -285,7 +285,7 @@ const drawRankBarChart = () => {
const momLine = props.liveData const momLine = props.liveData
? '' ? ''
: `<br/>环比 <b>${mom}%</b>(演示)`; : `<br/>环比 <b>${mom}%</b>(演示)`;
return `${row.name}<br/>${p?.marker ?? ''} 实际销售额 <b>${formatWanShort(row.salesYuan)}</b>(约)<br/>精确 ${formatYuanDetail(row.salesYuan)}<br/>占合计 <b>${row.sharePct}%</b>${momLine}`; return `${row.name}<br/>${p?.marker ?? ''} 净销售额 <b>${formatWanShort(row.salesYuan)}</b>(约)<br/>精确 ${formatYuanDetail(row.salesYuan)}<br/>占合计 <b>${row.sharePct}%</b>${momLine}`;
}, },
}, },
grid: { grid: {
@@ -297,7 +297,7 @@ const drawRankBarChart = () => {
}, },
xAxis: { xAxis: {
type: 'value', type: 'value',
name: '实际销售额(万)', name: '净销售额(万)',
nameTextStyle: { color: axisLabel, fontSize: 11, fontWeight: 700 }, nameTextStyle: { color: axisLabel, fontSize: 11, fontWeight: 700 },
nameGap: 6, nameGap: 6,
splitLine: { lineStyle: { type: 'dashed', color: split } }, splitLine: { lineStyle: { type: 'dashed', color: split } },
@@ -312,7 +312,7 @@ const drawRankBarChart = () => {
}, },
series: [ series: [
{ {
name: '实际销售额(万)', name: '净销售额(万)',
type: 'bar', type: 'bar',
data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))), data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))),
barMaxWidth: 22, barMaxWidth: 22,
@@ -410,7 +410,7 @@ defineExpose({ redraw });
<h3 <h3
class="text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]" class="text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
> >
{{ title }} · 实际销售额排行(万) {{ title }} · 净销售额排行(万)
</h3> </h3>
<p <p
class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]" class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
@@ -167,7 +167,7 @@ const footerRow = computed(() => props.footerTotal ?? computedFooter.value);
class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]" class="border-b border-l border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
> >
<OverviewColumnHint :title="storeOverviewHints.salesAmount"> <OverviewColumnHint :title="storeOverviewHints.salesAmount">
实际销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b px-6 py-4"> <th class="border-b px-6 py-4">
@@ -33,13 +33,13 @@ defineProps<Props>();
const cards = [ const cards = [
{ {
key: 'sales', key: 'sales',
label: '实际销售额', label: '净销售额',
tone: 'blue' as const, tone: 'blue' as const,
icon: IconSales, icon: IconSales,
}, },
{ {
key: 'orders', key: 'orders',
label: '销售单量', label: '净销售单量',
tone: 'blue' as const, tone: 'blue' as const,
icon: IconOrders, icon: IconOrders,
}, },
@@ -130,7 +130,7 @@ const cellMoneyApi = (v: number | null | undefined) =>
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm"> <tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<th class="border-b border-l dark:border-l-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:bg-[hsl(240deg_3.7%_22%/50%)] dark:text-[hsl(0deg_0%_95%)]"> <th class="border-b border-l dark:border-l-[hsl(240deg_3.7%_22%)] px-6 py-4 font-black text-slate-900 dark:bg-[hsl(240deg_3.7%_22%/50%)] dark:text-[hsl(0deg_0%_95%)]">
<OverviewColumnHint :title="overviewTableHints.salesAmount"> <OverviewColumnHint :title="overviewTableHints.salesAmount">
实际销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_22%/50%)]"> <th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_22%/50%)]">
@@ -154,7 +154,7 @@ function goToProductOverview(productId: number) {
<tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm"> <tr class="bg-slate-50/80 dark:bg-[hsl(240deg_3.7%_15.9%/80)] text-sm">
<th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_15.9%/80%)]"> <th class="border-b px-6 py-4 dark:bg-[hsl(240deg_3.7%_15.9%/80%)]">
<OverviewColumnHint :title="overviewTableHints.salesAmountShort"> <OverviewColumnHint :title="overviewTableHints.salesAmountShort">
销售额 净销售额
</OverviewColumnHint> </OverviewColumnHint>
</th> </th>
<th class="border-b border-l dark:border-l dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4"> <th class="border-b border-l dark:border-l dark:border-[hsl(240deg_3.7%_22%)] px-6 py-4">