feat: 按经营概览风格重做商品概览并补齐 KPI 与趋势

This commit is contained in:
2026-09-05 11:08:30 +08:00
parent b2e0ee5da4
commit 5114abc986
14 changed files with 1070 additions and 1097 deletions
@@ -2,351 +2,123 @@ package top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/**
* 商品概览响应VO
* 商品概览响应:经营 KPI/趋势与工作台经营概览同口径,并附 SKU 明细。
*/
@Data
public class ProductOverviewVO {
/**
* 商品ID
*/
private Long productId;
/**
* 商品名称
*/
private String productName;
// ========== KPI 汇总指标 ==========
/** 与工作台经营概览同结构的 KPI 列表 */
private List<WorkbenchKpiItemVO> kpis;
/**
* 总销售额
*/
/** 成交/净销售/利润日趋势(与工作台 dealTrend 同形) */
private List<WorkbenchTrendPointVO> dealTrend;
/** 各 SKU 净销售额占比(饼图) */
private List<WorkbenchCostSliceVO> skuSalesShare;
private String momCompareDateStart;
private String momCompareDateEnd;
private String yoyCompareDateStart;
private String yoyCompareDateEnd;
/** 兼容 Agent/旧前端:扁平 KPI 摘要 */
private BigDecimal totalSalesAmount;
/**
* 较上月同期增长百分比
*/
private BigDecimal monthOverMonthGrowth;
/**
* 总订单量
*/
private Integer totalOrderCount;
/**
* 平均费比(推广费/销售额)
*/
private BigDecimal averageFeeRatio;
/**
* 总净利润(税后)
*/
private BigDecimal totalNetProfitAfterTax;
/**
* 扣除总税额
*/
private BigDecimal totalTaxAmount;
/**
* 销量目标达成率
*/
private BigDecimal orderCountAchievementRate;
/**
* 销售额目标达成率
*/
private BigDecimal salesAmountAchievementRate;
/**
* 汇总ROI
*/
private BigDecimal totalROI;
// ========== 各规格销量 Top10 ==========
/**
* 各规格销量 Top10(按单量降序,最多10条)
*/
private List<SpecSalesRankItem> specSalesTop10;
// ========== 趋势数据 ==========
/**
* 销售额趋势分析
*/
/** @deprecated 使用 dealTrend;保留以免旧客户端空指针 */
private TrendData salesAmountTrend;
/**
* 单量趋势分析
*/
/** @deprecated 使用 dealTrend */
private TrendData orderCountTrend;
// ========== 规格销售汇总 ==========
/**
* 规格销售汇总(含各规格明细列表和合计行)
*/
private SpecSummary specSummaries;
// ========== 内部类 ==========
/**
* 趋势数据
*/
@Data
public static class TrendData {
/**
* 时间范围的总值
*/
private BigDecimal total;
/**
* 每日数据列表
*/
private List<TrendDataItem> dailyDataList;
}
/**
* 趋势数据项
*/
@Data
public static class TrendDataItem {
/**
* 日期
*/
@JsonFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
/**
* 对应的值
*/
private BigDecimal value;
}
/**
* 规格销售汇总
*/
@Data
public static class SpecSummary {
/**
* 各规格明细列表
*/
private List<SpecSummaryItem> list;
/**
* 合计行
*/
private SpecSummaryTotal total;
}
/**
* 规格销售明细项
*/
@Data
public static class SpecSummaryItem {
/**
* 规格ID
*/
private Long skuId;
/**
* 规格名称
*/
private String skuName;
/**
* 规格编码
*/
private String skuCode;
/**
* 销售额
*/
private BigDecimal salesAmount;
/**
* 订单量(按平台订单号去重)
*/
private Integer orderCount;
/**
* 总件数
*/
private Integer quantity;
/**
* 客单价
*/
private BigDecimal averageOrderValue;
/**
* 商品成本
*/
private BigDecimal productCost;
/**
* 运费
*/
private BigDecimal shippingCost;
/**
* 其他成本
*/
private BigDecimal otherCost;
/**
* 订单成本(商品成本+运费+其他成本,不含推广费、刷单费)
*/
private BigDecimal orderCost;
/**
* 退款金额
*/
private BigDecimal refundAmount;
/**
* 推广费
*/
private BigDecimal promotionFee;
/**
* 费比(推广费/销售额)
*/
private BigDecimal feeRatio;
/**
* 税前盈亏
*/
private BigDecimal profitBeforeTax;
/**
* 销售额×税率的税额
*/
private BigDecimal salesTaxAmount;
/**
* ROI
*/
private BigDecimal roi;
/**
* 税后盈亏
*/
private BigDecimal profitAfterTax;
}
/**
* 规格销售汇总合计行
*/
@Data
public static class SpecSummaryTotal {
/**
* 销售额
*/
private BigDecimal salesAmount;
/**
* 订单量
*/
private Integer orderCount;
/**
* 总件数
*/
private Integer quantity;
/**
* 商品成本
*/
private BigDecimal productCost;
/**
* 运费
*/
private BigDecimal shippingCost;
/**
* 其他成本
*/
private BigDecimal otherCost;
/**
* 订单成本(商品成本+运费+其他成本,不含推广费、刷单费)
*/
private BigDecimal orderCost;
/**
* 退款金额
*/
private BigDecimal refundAmount;
/**
* 推广费
*/
private BigDecimal promotionFee;
/**
* 费比
*/
private BigDecimal feeRatio;
/**
* 税前盈亏
*/
private BigDecimal profitBeforeTax;
/**
* 税额
*/
private BigDecimal salesTaxAmount;
/**
* ROI
*/
private BigDecimal roi;
/**
* 税后盈亏
*/
private BigDecimal profitAfterTax;
}
/**
* 规格销量排名项
*/
@Data
public static class SpecSalesRankItem {
/**
* 规格ID
*/
private Long skuId;
/**
* 规格名称
*/
private String skuName;
/**
* 规格编码
*/
private String skuCode;
/**
* 订单量
*/
private Integer orderCount;
/**
* 销售额
*/
private BigDecimal salesAmount;
}
}
}
@@ -6,17 +6,20 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiFinanceKpiAssembler;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
import top.xyquan.ecomdmbbackend.modules.ec.product.service.ProductService;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
@@ -26,7 +29,6 @@ import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
@@ -38,8 +40,7 @@ import java.util.Set;
import java.util.stream.Collectors;
/**
* 商品概览:Mongo product/sku 日汇聚 + MySQL 推广/目标。
* 推广分摊复用工作台四表(按店全量商品行作分母),不再扫订单明细。
* 商品概览:Mongo product/sku 日汇聚 + 经营 KPI(与工作台同口径)。
*/
@Service
public class BiProductOverviewServiceImpl implements BiProductOverviewService {
@@ -87,7 +88,6 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
LocalDate start = queryDTO.getStartDate();
LocalDate end = queryDTO.getEndDate();
Long filterShopId = queryDTO.getShopId();
if (filterShopId != null) {
ShopPO shop = shopService.getById(filterShopId);
@@ -96,10 +96,53 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
}
}
// 先拉本商品日文档,确定涉及店铺
List<Long> shopIdFilter = filterShopId != null ? List.of(filterShopId) : null;
PeriodBundle cur = loadPeriod(companyId, product.getId(), shopIdFilter, filterShopId, start, end, taxRate);
LocalDate[] mom = BiFinanceKpiAssembler.lastMonthSameSpan(start, end);
LocalDate[] yoy = BiFinanceKpiAssembler.yoySameSpan(start, end);
PeriodBundle prev = loadPeriod(companyId, product.getId(), shopIdFilter, filterShopId, mom[0], mom[1], taxRate);
PeriodBundle yoyBundle = loadPeriod(companyId, product.getId(), shopIdFilter, filterShopId, yoy[0], yoy[1], taxRate);
BiFinanceKpiAssembler.Totals curT = cur.totals();
BiFinanceKpiAssembler.Totals prevT = prev.totals();
BiFinanceKpiAssembler.Totals yoyT = yoyBundle.totals();
List<WorkbenchTrendPointVO> dealTrend = BiFinanceKpiAssembler.buildTrendFromDaily(
cur.dailyRows(), start, end, curT);
List<BiOrderStatDailySkuDoc> skuDocs =
orderStatQueryService.listSkuDocs(companyId, product.getId(), shopIdFilter, start, end);
List<BiOrderStatQueryService.SkuPeriodMetrics> skuMetrics =
orderStatQueryService.sumSkuDocsBySku(skuDocs);
ProductOverviewVO.SpecSummary specSummaries =
buildSpecSummary(skuMetrics, taxRate, curT.promotion());
ProductOverviewVO vo = new ProductOverviewVO();
vo.setProductId(product.getId());
vo.setProductName(product.getName());
vo.setKpis(BiFinanceKpiAssembler.buildKpis(curT, prevT, yoyT, start, end, taxRate));
vo.setDealTrend(dealTrend);
vo.setSkuSalesShare(buildSkuSalesShare(specSummaries, curT.totalSales()));
vo.setMomCompareDateStart(mom[0].toString());
vo.setMomCompareDateEnd(mom[1].toString());
vo.setYoyCompareDateStart(yoy[0].toString());
vo.setYoyCompareDateEnd(yoy[1].toString());
vo.setSpecSummaries(specSummaries);
vo.setSpecSalesTop10(buildSpecTop10(specSummaries));
fillLegacyFlatFields(vo, curT, prevT);
fillTargets(vo, companyId, cur.shopIds(), start, end, curT.totalSales(), curT.orderCount());
fillLegacyTrends(vo, dealTrend);
return vo;
}
/**
* 加载单区间:店铺范围 + 商品分摊后的经营 Totals + 日趋势行。
*/
private PeriodBundle loadPeriod(Long companyId, Long productId, List<Long> shopIdFilter, Long filterShopId,
LocalDate start, LocalDate end, BigDecimal taxRate) {
List<BiOrderStatDailyProductDoc> thisProductDocs =
orderStatQueryService.listProductDocs(companyId, shopIdFilter, product.getId(), start, end);
orderStatQueryService.listProductDocs(companyId, shopIdFilter, productId, start, end);
List<Long> shopIds;
if (filterShopId != null) {
@@ -121,83 +164,74 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
s -> s.getPlatformCode() != null ? s.getPlatformCode() : "",
(a, b) -> a));
// 店内全量商品行:推广分摊分母(替代 allShopOrdersForPromo)
List<BiOrderStatDailyProductDoc> allProductDocs = shopIds.isEmpty()
? List.of()
: orderStatQueryService.listProductDocs(companyId, shopIds, start, end);
BiWorkbenchFeeLoader.FeeBundle fees = shopIds.isEmpty()
? new BiWorkbenchFeeLoader.FeeBundle(List.of(), List.of())
: feeLoader.load(companyId, shopIds, start, end);
List<OverviewAggRows.DailyRow> dailyRows =
orderStatQueryService.toDailyRowsFromProductDocs(thisProductDocs);
if (shops.isEmpty()) {
return new PeriodBundle(List.of(), BiFinanceKpiAssembler.Totals.empty(), dailyRows);
}
List<BiOrderStatDailyProductDoc> allProductDocs =
orderStatQueryService.listProductDocs(companyId, shopIds, start, end);
BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, start, end);
List<OverviewAggRows.ShopProductRow> orderRows =
orderStatQueryService.toShopProductRows(allProductDocs, platformByShopId);
CompanyOverviewVO.WorkbenchTableBundle tables = shops.isEmpty()
? emptyTables()
: companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
CompanyOverviewVO.WorkbenchTableBundle tables =
companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
taxRate, companyId, shops, orderRows,
fees.promotionRows(), fees.brushRows(), start, end);
CompanyOverviewVO.CategorySummary productRow = findProductRow(tables.getProductTable(), product.getId());
BigDecimal sales = productRow != null ? nz(productRow.getSalesAmount()) : sumSales(thisProductDocs);
int orderCount = productRow != null && productRow.getSalesOrderCount() != null
? productRow.getSalesOrderCount()
: sumOrders(thisProductDocs);
BigDecimal promo = productRow != null ? nz(productRow.getTotalPromotionFee()) : BigDecimal.ZERO;
BigDecimal orderCost = productRow != null ? nz(productRow.getOrderCost())
: sumCost(thisProductDocs);
BigDecimal tax = salesTaxOnNet(sales, taxRate);
BigDecimal net = sales.subtract(orderCost).subtract(promo).subtract(tax);
ProductOverviewVO vo = new ProductOverviewVO();
vo.setProductId(product.getId());
vo.setProductName(product.getName());
vo.setTotalSalesAmount(sales.setScale(2, RoundingMode.HALF_UP));
vo.setTotalOrderCount(orderCount);
vo.setAverageFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0
? promo.divide(sales, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
vo.setTotalTaxAmount(tax);
vo.setTotalNetProfitAfterTax(net.setScale(2, RoundingMode.HALF_UP));
vo.setTotalROI(roi(sales, promo));
vo.setMonthOverMonthGrowth(calcPrevPeriodGrowth(companyId, product.getId(), shopIdFilter,
start, end, sales));
fillTargets(vo, companyId, shopIds, start, end, sales, orderCount);
Map<LocalDate, OverviewAggRows.DailyRow> daily =
orderStatQueryService.toDailyRowsFromProductDocs(thisProductDocs).stream()
.filter(d -> d.getStatDate() != null)
.collect(Collectors.toMap(OverviewAggRows.DailyRow::getStatDate, d -> d, (a, b) -> a));
vo.setSalesAmountTrend(buildTrend(start, end, daily, true));
vo.setOrderCountTrend(buildTrend(start, end, daily, false));
List<BiOrderStatDailySkuDoc> skuDocs =
orderStatQueryService.listSkuDocs(companyId, product.getId(), shopIdFilter, start, end);
List<BiOrderStatQueryService.SkuPeriodMetrics> skuMetrics =
orderStatQueryService.sumSkuDocsBySku(skuDocs);
vo.setSpecSummaries(buildSpecSummary(skuMetrics, taxRate, promo));
vo.setSpecSalesTop10(buildSpecTop10(vo.getSpecSummaries()));
return vo;
CompanyOverviewVO.CategorySummary productRow = findProductRow(tables.getProductTable(), productId);
BiFinanceKpiAssembler.Totals totals = productRow != null
? BiFinanceKpiAssembler.fromCategorySummary(productRow, taxRate)
: BiFinanceKpiAssembler.Totals.empty();
return new PeriodBundle(shopIds, totals, dailyRows);
}
private BigDecimal calcPrevPeriodGrowth(Long companyId, Long productId, List<Long> shopIds,
LocalDate start, LocalDate end, BigDecimal curSales) {
long dayCount = ChronoUnit.DAYS.between(start, end) + 1;
LocalDate prevStart = start.minusDays(dayCount);
LocalDate prevEnd = start.minusDays(1);
List<BiOrderStatDailyProductDoc> prevDocs =
orderStatQueryService.listProductDocs(companyId, shopIds, productId, prevStart, prevEnd);
BigDecimal last = sumSales(prevDocs);
if (last.compareTo(BigDecimal.ZERO) > 0) {
return curSales.subtract(last)
.divide(last, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100"))
.setScale(2, RoundingMode.HALF_UP);
private void fillLegacyFlatFields(ProductOverviewVO vo,
BiFinanceKpiAssembler.Totals cur,
BiFinanceKpiAssembler.Totals prev) {
vo.setTotalSalesAmount(BiFinanceKpiAssembler.yuan2(cur.totalSales()));
vo.setTotalOrderCount(cur.orderCount());
vo.setAverageFeeRatio(cur.totalSales().compareTo(BigDecimal.ZERO) > 0
? cur.promotion().divide(cur.totalSales(), 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
vo.setTotalTaxAmount(BiFinanceKpiAssembler.yuan2(cur.tax()));
vo.setTotalNetProfitAfterTax(BiFinanceKpiAssembler.yuan2(cur.netProfit()));
vo.setTotalROI(cur.promotion().compareTo(BigDecimal.ZERO) > 0
? cur.totalSales().divide(cur.promotion(), 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
vo.setMonthOverMonthGrowth(BiFinanceKpiAssembler.pctChange(cur.totalSales(), prev.totalSales()));
}
private void fillLegacyTrends(ProductOverviewVO vo, List<WorkbenchTrendPointVO> dealTrend) {
ProductOverviewVO.TrendData sales = new ProductOverviewVO.TrendData();
ProductOverviewVO.TrendData orders = new ProductOverviewVO.TrendData();
List<ProductOverviewVO.TrendDataItem> salesItems = new ArrayList<>();
List<ProductOverviewVO.TrendDataItem> orderItems = new ArrayList<>();
BigDecimal salesTotal = BigDecimal.ZERO;
BigDecimal orderTotal = BigDecimal.ZERO;
if (dealTrend != null) {
for (WorkbenchTrendPointVO p : dealTrend) {
ProductOverviewVO.TrendDataItem s = new ProductOverviewVO.TrendDataItem();
s.setDate(LocalDate.parse(p.getDate()));
s.setValue(BiFinanceKpiAssembler.nz(p.getSalesYuan()));
salesItems.add(s);
salesTotal = salesTotal.add(s.getValue());
ProductOverviewVO.TrendDataItem o = new ProductOverviewVO.TrendDataItem();
o.setDate(s.getDate());
o.setValue(BigDecimal.valueOf(p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0));
orderItems.add(o);
orderTotal = orderTotal.add(o.getValue());
}
}
return curSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100.00") : BigDecimal.ZERO;
sales.setDailyDataList(salesItems);
sales.setTotal(salesTotal);
orders.setDailyDataList(orderItems);
orders.setTotal(orderTotal);
vo.setSalesAmountTrend(sales);
vo.setOrderCountTrend(orders);
}
private void fillTargets(ProductOverviewVO vo, Long companyId, List<Long> shopIds,
@@ -233,13 +267,39 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
}
}
private List<WorkbenchCostSliceVO> buildSkuSalesShare(ProductOverviewVO.SpecSummary summary,
BigDecimal salesTotal) {
if (summary == null || summary.getList() == null || summary.getList().isEmpty()) {
return List.of();
}
BigDecimal base = BiFinanceKpiAssembler.nz(salesTotal);
return summary.getList().stream()
.filter(i -> BiFinanceKpiAssembler.nz(i.getSalesAmount()).compareTo(BigDecimal.ZERO) > 0)
.sorted(Comparator.comparing(ProductOverviewVO.SpecSummaryItem::getSalesAmount,
Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
.limit(12)
.map(i -> {
BigDecimal amt = BiFinanceKpiAssembler.nz(i.getSalesAmount());
BigDecimal pct = base.compareTo(BigDecimal.ZERO) > 0
? amt.multiply(new BigDecimal("100")).divide(base, 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
String name = i.getSkuName() != null ? i.getSkuName() : "SKU";
return WorkbenchCostSliceVO.builder()
.name(name)
.value(BiFinanceKpiAssembler.yuan2(amt))
.pct(pct)
.build();
})
.collect(Collectors.toList());
}
private ProductOverviewVO.SpecSummary buildSpecSummary(
List<BiOrderStatQueryService.SkuPeriodMetrics> metrics,
BigDecimal taxRate,
BigDecimal totalPromo) {
BigDecimal salesPool = metrics.stream()
.map(BiOrderStatQueryService.SkuPeriodMetrics::salesAmount)
.map(BiProductOverviewServiceImpl::nz)
.map(BiFinanceKpiAssembler::nz)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Set<Long> skuIds = metrics.stream()
@@ -257,11 +317,12 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
List<ProductOverviewVO.SpecSummaryItem> list = new ArrayList<>();
for (BiOrderStatQueryService.SkuPeriodMetrics m : metrics) {
BigDecimal sales = nz(m.salesAmount());
BigDecimal sales = BiFinanceKpiAssembler.nz(m.salesAmount());
BigDecimal sharePromo = salesPool.compareTo(BigDecimal.ZERO) > 0
? nz(totalPromo).multiply(sales).divide(salesPool, 4, RoundingMode.HALF_UP)
? BiFinanceKpiAssembler.nz(totalPromo).multiply(sales)
.divide(salesPool, 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal refund = nz(m.refundAmount());
BigDecimal refund = BiFinanceKpiAssembler.nz(m.refundAmount());
BigDecimal cost = m.orderCost();
BigDecimal tax = salesTaxOnNet(sales, taxRate);
BigDecimal pbt = sales.subtract(cost).subtract(sharePromo);
@@ -279,9 +340,9 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
item.setAverageOrderValue(m.salesOrderCount() > 0
? sales.divide(BigDecimal.valueOf(m.salesOrderCount()), 2, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
item.setProductCost(nz(m.productCost()).setScale(2, RoundingMode.HALF_UP));
item.setShippingCost(nz(m.freightCost()).setScale(2, RoundingMode.HALF_UP));
item.setOtherCost(nz(m.otherCost()).setScale(2, RoundingMode.HALF_UP));
item.setProductCost(BiFinanceKpiAssembler.nz(m.productCost()).setScale(2, RoundingMode.HALF_UP));
item.setShippingCost(BiFinanceKpiAssembler.nz(m.freightCost()).setScale(2, RoundingMode.HALF_UP));
item.setOtherCost(BiFinanceKpiAssembler.nz(m.otherCost()).setScale(2, RoundingMode.HALF_UP));
item.setOrderCost(cost.setScale(2, RoundingMode.HALF_UP));
item.setRefundAmount(refund.setScale(2, RoundingMode.HALF_UP));
item.setPromotionFee(sharePromo.setScale(2, RoundingMode.HALF_UP));
@@ -297,22 +358,32 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
ProductOverviewVO.SpecSummaryTotal total = new ProductOverviewVO.SpecSummaryTotal();
total.setSalesAmount(list.stream().map(i -> nz(i.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setSalesAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getSalesAmount()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOrderCount(list.stream().mapToInt(i -> i.getOrderCount() != null ? i.getOrderCount() : 0).sum());
total.setQuantity(list.stream().mapToInt(i -> i.getQuantity() != null ? i.getQuantity() : 0).sum());
total.setProductCost(list.stream().map(i -> nz(i.getProductCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setShippingCost(list.stream().map(i -> nz(i.getShippingCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOtherCost(list.stream().map(i -> nz(i.getOtherCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOrderCost(list.stream().map(i -> nz(i.getOrderCost())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setRefundAmount(list.stream().map(i -> nz(i.getRefundAmount())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setPromotionFee(list.stream().map(i -> nz(i.getPromotionFee())).reduce(BigDecimal.ZERO, BigDecimal::add));
total.setProductCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getProductCost()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setShippingCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getShippingCost()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOtherCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getOtherCost()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setOrderCost(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getOrderCost()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setRefundAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getRefundAmount()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setPromotionFee(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getPromotionFee()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setFeeRatio(total.getSalesAmount().compareTo(BigDecimal.ZERO) > 0
? total.getPromotionFee().divide(total.getSalesAmount(), 4, RoundingMode.HALF_UP)
: BigDecimal.ZERO);
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.setProfitBeforeTax(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getProfitBeforeTax()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
total.setSalesTaxAmount(list.stream().map(i -> BiFinanceKpiAssembler.nz(i.getSalesTaxAmount()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
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 -> BiFinanceKpiAssembler.nz(i.getProfitAfterTax()))
.reduce(BigDecimal.ZERO, BigDecimal::add));
ProductOverviewVO.SpecSummary summary = new ProductOverviewVO.SpecSummary();
summary.setList(list);
@@ -343,29 +414,6 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
.collect(Collectors.toList());
}
private static ProductOverviewVO.TrendData buildTrend(
LocalDate start, LocalDate end,
Map<LocalDate, OverviewAggRows.DailyRow> daily,
boolean sales) {
List<ProductOverviewVO.TrendDataItem> items = new ArrayList<>();
BigDecimal total = BigDecimal.ZERO;
for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
OverviewAggRows.DailyRow row = daily.get(d);
BigDecimal value = sales
? (row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO)
: BigDecimal.valueOf(row != null && row.getOrderCount() != null ? row.getOrderCount() : 0L);
ProductOverviewVO.TrendDataItem item = new ProductOverviewVO.TrendDataItem();
item.setDate(d);
item.setValue(value);
items.add(item);
total = total.add(value);
}
ProductOverviewVO.TrendData trend = new ProductOverviewVO.TrendData();
trend.setTotal(total);
trend.setDailyDataList(items);
return trend;
}
private static CompanyOverviewVO.CategorySummary findProductRow(
CompanyOverviewVO.CategoryOverview table, Long productId) {
if (table == null || table.getCategories() == null || productId == null) {
@@ -377,53 +425,24 @@ public class BiProductOverviewServiceImpl implements BiProductOverviewService {
.orElse(null);
}
private static CompanyOverviewVO.WorkbenchTableBundle emptyTables() {
CompanyOverviewVO.WorkbenchTableBundle b = new CompanyOverviewVO.WorkbenchTableBundle();
CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview();
empty.setCategories(List.of());
b.setProductTable(empty);
b.setCategoryTable(empty);
return b;
}
private static BigDecimal sumSales(List<BiOrderStatDailyProductDoc> docs) {
return docs.stream()
.map(d -> nz(d.getDealAmount()).subtract(nz(d.getRefundAmount())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
private static BigDecimal sumCost(List<BiOrderStatDailyProductDoc> docs) {
return docs.stream()
.map(d -> nz(d.getProductCost()).add(nz(d.getFreightCost())).add(nz(d.getOtherCost())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
private static int sumOrders(List<BiOrderStatDailyProductDoc> docs) {
return docs.stream().mapToInt(d ->
nzInt(d.getDealOrderCount()) - nzInt(d.getRefundOrderCount())).sum();
}
/** 税额 = 净销售额 × 税率 */
private static BigDecimal salesTaxOnNet(BigDecimal sales, BigDecimal taxRate) {
BigDecimal base = nz(sales);
BigDecimal base = BiFinanceKpiAssembler.nz(sales);
if (base.compareTo(BigDecimal.ZERO) < 0) {
base = BigDecimal.ZERO;
}
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;
return base.multiply(taxRate != null ? taxRate : DEFAULT_TAX_RATE)
.setScale(2, RoundingMode.HALF_UP);
}
private static BigDecimal roi(BigDecimal netSales, BigDecimal promo) {
if (promo == null || promo.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
return nz(netSales).divide(promo, 4, RoundingMode.HALF_UP);
return BiFinanceKpiAssembler.nz(netSales).divide(promo, 4, RoundingMode.HALF_UP);
}
private static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
private record PeriodBundle(List<Long> shopIds,
BiFinanceKpiAssembler.Totals totals,
List<OverviewAggRows.DailyRow> dailyRows) {
}
}
@@ -0,0 +1,319 @@
package top.xyquan.ecomdmbbackend.modules.bi.workbench.support;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 经营财务 KPI / 趋势组装:工作台与商品概览共用,保证口径一致。
*/
public final class BiFinanceKpiAssembler {
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
private static final DateTimeFormatter TREND_DATE_FMT = DateTimeFormatter.ISO_LOCAL_DATE;
private BiFinanceKpiAssembler() {
}
/**
* 单时间段财务 KPI 总量。
*/
public record Totals(BigDecimal totalSales,
BigDecimal totalRefund,
BigDecimal totalCost,
BigDecimal productCost,
BigDecimal freightCost,
BigDecimal otherCost,
BigDecimal promotion,
BigDecimal brush,
BigDecimal tax,
BigDecimal grossOrder,
BigDecimal netProfit,
int orderCount,
int salesQuantitySum,
BigDecimal totalDealAmount,
int dealOrderCount,
int dealQuantitySum,
BigDecimal averageOrderValue,
BigDecimal dealAverageOrderValue,
BigDecimal salesPiecePrice,
BigDecimal dealPiecePrice) {
public static Totals empty() {
return buildTotals(BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO,
BigDecimal.ZERO, BigDecimal.ZERO, DEFAULT_TAX_RATE,
0, 0, BigDecimal.ZERO, 0, 0);
}
}
public static Totals buildTotals(BigDecimal sales, BigDecimal refund,
BigDecimal pc, BigDecimal fc, BigDecimal oc,
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate,
int orderCount, int salesQuantitySum,
BigDecimal totalDealAmount, int dealOrderCount, int dealQuantitySum) {
BigDecimal s = nz(sales);
BigDecimal cost = nz(pc).add(nz(fc)).add(nz(oc));
BigDecimal promo = nz(promotion);
BigDecimal brushFee = nz(brush);
BigDecimal deal = nz(totalDealAmount);
BigDecimal gross = s.subtract(cost);
BigDecimal pbt = gross.subtract(promo).subtract(brushFee);
BigDecimal tax = salesTaxOnSales(s, taxRate);
BigDecimal aov = orderCount > 0
? s.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal dealAov = dealOrderCount > 0
? deal.divide(BigDecimal.valueOf(dealOrderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal salesPiecePrice = salesQuantitySum > 0
? s.divide(BigDecimal.valueOf(salesQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal dealPiecePrice = dealQuantitySum > 0
? deal.divide(BigDecimal.valueOf(dealQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
return new Totals(s, nz(refund), cost, nz(pc), nz(fc), nz(oc), promo, brushFee, tax,
gross, pbt.subtract(tax),
orderCount, salesQuantitySum, deal, dealOrderCount, dealQuantitySum,
aov, dealAov, salesPiecePrice, dealPiecePrice);
}
/** 从经营汇总表商品/品类行构造 Totals(税按税率重算,与工作台一致)。 */
public static Totals fromCategorySummary(CompanyOverviewVO.CategorySummary row, BigDecimal taxRate) {
if (row == null) {
return Totals.empty();
}
return buildTotals(
nz(row.getSalesAmount()),
nz(row.getRefundAmount()),
nz(row.getProductCost()),
nz(row.getShippingCost()),
nz(row.getOtherCost()),
nz(row.getTotalPromotionFee()),
nz(row.getBrushFee()),
taxRate,
row.getSalesOrderCount() != null ? row.getSalesOrderCount() : 0,
row.getSalesQuantitySum() != null ? row.getSalesQuantitySum() : 0,
nz(row.getDealAmount()),
row.getDealOrderCount() != null ? row.getDealOrderCount() : 0,
row.getDealQuantitySum() != null ? row.getDealQuantitySum() : 0);
}
public static List<WorkbenchKpiItemVO> buildKpis(Totals cur, Totals prev, Totals yoy,
LocalDate start, LocalDate end, BigDecimal taxRate) {
int days = (int) (end.toEpochDay() - start.toEpochDay() + 1);
Totals c = cur != null ? cur : Totals.empty();
Totals p = prev != null ? prev : Totals.empty();
Totals y = yoy != null ? yoy : Totals.empty();
BigDecimal grossMarginPct = safePct(c.grossOrder(), c.totalSales());
BigDecimal netMarginPct = safePct(c.netProfit(), c.totalSales());
BigDecimal refundRate = safePct(c.totalRefund(), c.totalSales());
BigDecimal costRate = safePct(c.totalCost(), c.totalSales());
BigDecimal roi = c.promotion().compareTo(BigDecimal.ZERO) > 0
? c.totalSales().divide(c.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal yoyRoi = y.promotion().compareTo(BigDecimal.ZERO) > 0
? y.totalSales().divide(y.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal prevRoi = p.promotion().compareTo(BigDecimal.ZERO) > 0
? p.totalSales().divide(p.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal avgDailySalesOrders = days > 0
? BigDecimal.valueOf(c.orderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal avgDailyDealOrders = days > 0
? BigDecimal.valueOf(c.dealOrderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
List<WorkbenchKpiItemVO> list = new ArrayList<>();
list.add(kpi("成交金额", yuan2(c.totalDealAmount()), "元", c.totalDealAmount(), p.totalDealAmount(), y.totalDealAmount(),
"成交状态实收", c.totalDealAmount(), true));
list.add(kpiCount("成交单量", c.dealOrderCount(), p.dealOrderCount(), y.dealOrderCount(), "单",
"日均 " + avgDailyDealOrders.stripTrailingZeros().toPlainString() + " 单"));
list.add(kpiCount("成交销量", c.dealQuantitySum(), p.dealQuantitySum(), y.dealQuantitySum(), "件", "成交状态件数"));
list.add(kpi("成交客单价", yuan2(c.dealAverageOrderValue()), "元",
c.dealAverageOrderValue(), p.dealAverageOrderValue(), y.dealAverageOrderValue(),
"成交金额/成交单量", c.dealAverageOrderValue(), false));
list.add(kpi("净销售额", yuan2(c.totalSales()), "元", c.totalSales(), p.totalSales(), y.totalSales(),
"成交−退款", c.totalSales(), true));
list.add(kpiCount("净销售单量", c.orderCount(), p.orderCount(), y.orderCount(), "单",
"日均 " + avgDailySalesOrders.stripTrailingZeros().toPlainString() + " 单"));
list.add(kpiCount("净销量", c.salesQuantitySum(), p.salesQuantitySum(), y.salesQuantitySum(), "件",
"成交件数−退款件数"));
list.add(kpi("净销售客单价", yuan2(c.averageOrderValue()), "元",
c.averageOrderValue(), p.averageOrderValue(), y.averageOrderValue(),
"净销售额/净销售单量", c.averageOrderValue(), false));
list.add(kpi("退款额", yuan2(c.totalRefund()), "元", c.totalRefund(), p.totalRefund(), y.totalRefund(),
"计入退款状态", c.totalRefund(), true));
list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP), "%",
refundRate, safePct(p.totalRefund(), p.totalSales()), safePct(y.totalRefund(), y.totalSales()),
"退款/净销售额", null, null));
list.add(kpi("订单成本", yuan2(c.totalCost()), "元", c.totalCost(), p.totalCost(), y.totalCost(),
"成本率 " + costRate.stripTrailingZeros().toPlainString() + "%", c.totalCost(), true));
list.add(kpi("商品成本", yuan2(c.productCost()), "元", c.productCost(), p.productCost(), y.productCost(),
null, c.productCost(), true));
list.add(kpi("运费成本", yuan2(c.freightCost()), "元", c.freightCost(), p.freightCost(), y.freightCost(),
null, c.freightCost(), true));
list.add(kpi("其他成本", yuan2(c.otherCost()), "元", c.otherCost(), p.otherCost(), y.otherCost(),
null, c.otherCost(), true));
list.add(kpi("毛利润", yuan2(c.grossOrder()), "元", c.grossOrder(), p.grossOrder(), y.grossOrder(),
"毛利率 " + grossMarginPct.stripTrailingZeros().toPlainString() + "%", c.grossOrder(), true));
list.add(kpi("推广费", yuan2(c.promotion()), "元", c.promotion(), p.promotion(), y.promotion(),
null, c.promotion(), true));
list.add(kpi("刷单费", yuan2(c.brush()), "元", c.brush(), p.brush(), y.brush(),
null, c.brush(), true));
BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
list.add(kpi("税额", yuan2(c.tax()), "元", c.tax(), p.tax(), y.tax(),
"税率 " + rate.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%",
c.tax(), true));
list.add(kpi("净利润", yuan2(c.netProfit()), "元", c.netProfit(), p.netProfit(), y.netProfit(),
"净利率 " + netMarginPct.stripTrailingZeros().toPlainString() + "%",
c.netProfit(), true));
list.add(kpi("广告ROI", roi.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros(), ":1", roi, prevRoi, yoyRoi,
"净销售额/推广费", null, null));
return list;
}
public static List<WorkbenchTrendPointVO> buildTrendFromDaily(
List<OverviewAggRows.DailyRow> dailyRows,
LocalDate start, LocalDate end, Totals periodTotals) {
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
if (dailyRows != null) {
for (OverviewAggRows.DailyRow row : dailyRows) {
if (row.getStatDate() != null) {
byDay.put(row.getStatDate(), row);
}
}
}
Totals totals = periodTotals != null ? periodTotals : Totals.empty();
BigDecimal salesTotal = totals.totalSales();
List<WorkbenchTrendPointVO> list = new ArrayList<>();
for (LocalDate d = start; !d.isAfter(end); d = d.plusDays(1)) {
OverviewAggRows.DailyRow row = byDay.get(d);
BigDecimal sales = row != null ? nz(row.getSalesAmount()) : BigDecimal.ZERO;
BigDecimal deal = row != null ? nz(row.getDealAmount()) : BigDecimal.ZERO;
int salesOrders = row != null && row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
int dealOrders = row != null && row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
BigDecimal refund = row != null ? nz(row.getRefundAmount()) : BigDecimal.ZERO;
BigDecimal cost = row != null
? nz(row.getProductCost()).add(nz(row.getFreightCost())).add(nz(row.getOtherCost()))
: BigDecimal.ZERO;
BigDecimal gross = sales.subtract(cost);
BigDecimal promoB = allocShare(sales, salesTotal, totals.promotion());
BigDecimal brushB = allocShare(sales, salesTotal, totals.brush());
BigDecimal taxB = salesTotal.compareTo(BigDecimal.ZERO) <= 0
? BigDecimal.ZERO
: allocShare(sales, salesTotal.max(BigDecimal.ONE), totals.tax());
list.add(WorkbenchTrendPointVO.builder()
.date(d.format(TREND_DATE_FMT))
.dealYuan(yuan2(deal))
.dealOrderCount(dealOrders)
.salesYuan(yuan2(sales))
.salesOrderCount(salesOrders)
.profitYuan(yuan2(gross))
.netProfitYuan(yuan2(gross.subtract(promoB).subtract(brushB).subtract(taxB)))
.refundYuan(yuan2(refund))
.build());
}
return list;
}
public static LocalDate[] lastMonthSameSpan(LocalDate start, LocalDate end) {
return new LocalDate[]{start.minusMonths(1), end.minusMonths(1)};
}
public static LocalDate[] yoySameSpan(LocalDate start, LocalDate end) {
return new LocalDate[]{start.minusYears(1), end.minusYears(1)};
}
public static BigDecimal allocShare(BigDecimal part, BigDecimal total, BigDecimal amount) {
if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
if (total == null || total.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
return amount.multiply(part).divide(total, 4, RoundingMode.HALF_UP);
}
public static BigDecimal yuan2(BigDecimal yuan) {
if (yuan == null) {
return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
}
return yuan.setScale(2, RoundingMode.HALF_UP);
}
public static BigDecimal safePct(BigDecimal num, BigDecimal den) {
if (den == null || den.compareTo(BigDecimal.ZERO) <= 0) {
return BigDecimal.ZERO;
}
if (num == null) {
return BigDecimal.ZERO;
}
return num.multiply(new BigDecimal("100")).divide(den, 2, RoundingMode.HALF_UP);
}
public static BigDecimal pctChange(BigDecimal cur, BigDecimal prev) {
if (prev == null || prev.compareTo(BigDecimal.ZERO) == 0) {
if (cur != null && cur.compareTo(BigDecimal.ZERO) > 0) {
return new BigDecimal("100");
}
return BigDecimal.ZERO;
}
return cur.subtract(prev).divide(prev, 4, RoundingMode.HALF_UP)
.multiply(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
}
public static BigDecimal nz(BigDecimal v) {
return v != null ? v : BigDecimal.ZERO;
}
private static BigDecimal salesTaxOnSales(BigDecimal salesAmount, BigDecimal rate) {
BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO;
if (sales.compareTo(BigDecimal.ZERO) < 0) {
sales = BigDecimal.ZERO;
}
BigDecimal r = rate != null ? rate : DEFAULT_TAX_RATE;
return sales.multiply(r).setScale(2, RoundingMode.HALF_UP);
}
private static WorkbenchKpiItemVO kpiCount(String label, int cur, int prev, int yoy, String unit, String sub) {
return kpi(label, BigDecimal.valueOf(cur), unit,
BigDecimal.valueOf(cur), BigDecimal.valueOf(prev), BigDecimal.valueOf(yoy),
sub, null, null);
}
private static WorkbenchKpiItemVO kpi(String label, BigDecimal value, String unit,
BigDecimal curAmt, BigDecimal prevAmt, BigDecimal yoyAmt, String sub,
BigDecimal amountYuan, Boolean preferWanDisplay) {
BigDecimal change = pctChange(curAmt, prevAmt);
boolean up = curAmt.compareTo(prevAmt) >= 0;
BigDecimal yoyPct = pctChange(curAmt, yoyAmt);
boolean yoyUpFlag = curAmt.compareTo(yoyAmt) >= 0;
var b = WorkbenchKpiItemVO.builder()
.label(label)
.value(value)
.unit(unit)
.changePct(change)
.up(up)
.yoyChangePct(yoyPct)
.yoyUp(yoyUpFlag)
.sub(sub);
if (amountYuan != null) {
b.amountYuan(yuan2(amountYuan));
}
if (preferWanDisplay != null) {
b.preferWanDisplay(preferWanDisplay);
}
return b.build();
}
}