mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
refactor: 移除工作台多维分析、销售额排行与区间对比
This commit is contained in:
-21
@@ -10,8 +10,6 @@ import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
|
||||
/**
|
||||
* BI 工作台查询:订单指标来自 Mongo 日汇聚,推广/刷单来自 MySQL。
|
||||
@@ -31,23 +29,4 @@ public class BiWorkbenchController {
|
||||
public ApiResponse<WorkbenchFinanceSliceVO> finance(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取经营概览成功", biWorkbenchService.financeSlice(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/multi-analysis")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台多维分析", allowSuper = true)
|
||||
public ApiResponse<WorkbenchMultiAnalysisPanelVO> multiAnalysis(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取多维分析成功", biWorkbenchService.multiAnalysis(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/sales-rank")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台销售额排行", allowSuper = true)
|
||||
public ApiResponse<WorkbenchMultiAnalysisPanelVO> salesRank(@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取销售额排行成功", biWorkbenchService.salesRank(queryDTO));
|
||||
}
|
||||
|
||||
@PostMapping("/period-compare/slice")
|
||||
@RequirePermission(value = "bi:workbench:read", description = "查询工作台区间对比", allowSuper = true)
|
||||
public ApiResponse<WorkbenchPeriodCompareSliceVO> periodCompareSlice(
|
||||
@Valid @RequestBody WorkbenchQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取区间对比数据成功", biWorkbenchService.periodCompareSlice(queryDTO));
|
||||
}
|
||||
}
|
||||
|
||||
-34
@@ -1,34 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 金额字段为「元」保留两位小数;前端可自行换算为「万」展示。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchDimRowVO {
|
||||
|
||||
private String key;
|
||||
|
||||
private String name;
|
||||
|
||||
private BigDecimal salesYuan;
|
||||
|
||||
private BigDecimal grossProfitYuan;
|
||||
|
||||
private BigDecimal netProfitYuan;
|
||||
|
||||
private BigDecimal refundYuan;
|
||||
|
||||
private BigDecimal grossMarginPct;
|
||||
|
||||
private BigDecimal netMarginPct;
|
||||
}
|
||||
-23
@@ -1,23 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchMultiAnalysisPanelVO {
|
||||
|
||||
private List<WorkbenchDimRowVO> platform;
|
||||
|
||||
private List<WorkbenchDimRowVO> shop;
|
||||
|
||||
private List<WorkbenchDimRowVO> category;
|
||||
|
||||
private List<WorkbenchDimRowVO> product;
|
||||
}
|
||||
-25
@@ -1,25 +0,0 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 工作台「区间对比」单段日期聚合:与底部店铺汇总表「合计」行同源({@link CompanyOverviewVO.ShopSummary})。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class WorkbenchPeriodCompareSliceVO {
|
||||
|
||||
private LocalDate startDate;
|
||||
|
||||
private LocalDate endDate;
|
||||
|
||||
private CompanyOverviewVO.ShopSummary total;
|
||||
}
|
||||
-8
@@ -4,8 +4,6 @@ import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
|
||||
/**
|
||||
* BI 工作台:读 Mongo 订单日汇聚 + MySQL 推广/刷单。
|
||||
@@ -14,12 +12,6 @@ public interface BiWorkbenchService {
|
||||
|
||||
WorkbenchFinanceSliceVO financeSlice(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchMultiAnalysisPanelVO multiAnalysis(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchMultiAnalysisPanelVO salesRank(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
WorkbenchPeriodCompareSliceVO periodCompareSlice(WorkbenchQueryDTO queryDTO);
|
||||
|
||||
/** 与 finance 四表同口径,供导出使用 */
|
||||
CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto);
|
||||
}
|
||||
|
||||
+5
-267
@@ -9,20 +9,13 @@ import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStat
|
||||
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.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchPeriodCompareSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchDimRowVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinancePanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchMultiAnalysisPanelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
@@ -38,11 +31,9 @@ import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
@@ -50,14 +41,11 @@ import java.util.stream.Collectors;
|
||||
* <p>
|
||||
* 口径约定:
|
||||
* <ul>
|
||||
* <li>「净销售额、成本、退款、多维行、趋势」等:Mongo 存成交/退款分桶,读侧净销售 = 成交 − 退款;
|
||||
* <li>「净销售额、成本、退款、趋势」等:Mongo 存成交/退款分桶,读侧净销售 = 成交 − 退款;
|
||||
* 成交不含已取消/未知;成本按状态开关计入。</li>
|
||||
* <li>「成交金额」为同店铺、同时间范围内<strong>全部订单状态</strong>的商家实收合计(由汇总表 KPI 提供)。</li>
|
||||
* <li>推广费、刷单费为区间汇总;多维行与趋势中的「净利润」按销售额占比将区间推广、刷单、税额<strong>分摊</strong>到各维度或各日,
|
||||
* 与 {@link #totalsFromOrderRows} 得到的区间总毛利润、总税额自洽。</li>
|
||||
* <li>「成交金额」为同店铺、同时间范围内成交状态商家实收合计。</li>
|
||||
* <li>推广费、刷单费为区间汇总;趋势中的「净利润」按销售额占比将区间推广、刷单、税额分摊到各日。</li>
|
||||
* </ul>
|
||||
* <p>
|
||||
* 分 Tab 输出:{@link #financeSlice}、{@link #multiAnalysis}、{@link #salesRank}。
|
||||
*/
|
||||
@Service
|
||||
public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
@@ -70,8 +58,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final ShopService shopService;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final ProductMapper productMapper;
|
||||
private final CategoryService categoryService;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
private final BiWorkbenchFeeLoader feeLoader;
|
||||
@@ -79,16 +65,12 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
public BiWorkbenchServiceImpl(CurrentUserContext currentUserContext,
|
||||
ShopService shopService,
|
||||
OrderStatusStatResolver orderStatusStatResolver,
|
||||
ProductMapper productMapper,
|
||||
CategoryService categoryService,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
BiOrderStatQueryService orderStatQueryService,
|
||||
BiWorkbenchFeeLoader feeLoader) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.shopService = shopService;
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
this.productMapper = productMapper;
|
||||
this.categoryService = categoryService;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.feeLoader = feeLoader;
|
||||
@@ -120,52 +102,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return WorkbenchFinanceSliceVO.builder().finance(finance).summaryTables(summaryTables).build();
|
||||
}
|
||||
|
||||
/** 多维分析 Tab:SQL 聚合 + 内存 rollup */
|
||||
@Override
|
||||
public WorkbenchMultiAnalysisPanelVO multiAnalysis(WorkbenchQueryDTO queryDTO) {
|
||||
ShopContext ctx = resolveShopContext(queryDTO);
|
||||
if (ctx.shops().isEmpty() || ctx.stat().isUnionEmpty()) {
|
||||
return emptyMultiPanel();
|
||||
}
|
||||
SqlAggBundle agg = loadSqlAgg(ctx);
|
||||
Totals cur = totalsFromOrderRows(agg.orderRows(), agg.promoTotal(), agg.brushTotal(), ctx.taxRate());
|
||||
return buildMultiPanel(aggregateDimensionsFromSql(agg.orderRows(), ctx), cur);
|
||||
}
|
||||
|
||||
/** 销售额排行 Tab:与多维同源,按销售额降序 */
|
||||
@Override
|
||||
public WorkbenchMultiAnalysisPanelVO salesRank(WorkbenchQueryDTO queryDTO) {
|
||||
return buildSalesRankPanel(multiAnalysis(queryDTO));
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间对比单段:只返回该段日期下店铺维表「合计」行,供前端与另一段日期并排对比;不组装完整工作台。
|
||||
*/
|
||||
@Override
|
||||
public WorkbenchPeriodCompareSliceVO periodCompareSlice(WorkbenchQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
DateRange range = parseDateRange(queryDTO);
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
if (stat.isUnionEmpty()) {
|
||||
return WorkbenchPeriodCompareSliceVO.builder()
|
||||
.startDate(range.startDate()).endDate(range.endDate())
|
||||
.total(new CompanyOverviewVO.ShopSummary()).build();
|
||||
}
|
||||
List<ShopPO> shops = loadFilteredShops(companyId, queryDTO.getPlatformCode(), queryDTO.getShopId());
|
||||
ShopContext ctx = new ShopContext(taxRate, companyId, range, stat, shops,
|
||||
shops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList(),
|
||||
shops.stream().collect(Collectors.toMap(ShopPO::getId, s -> s, (a, b) -> a)));
|
||||
SqlAggBundle agg = loadSqlAgg(ctx);
|
||||
CompanyOverviewVO.WorkbenchTableBundle bundle = companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, agg.orderRows(), agg.promotionRows(), agg.brushRows(),
|
||||
range.startDate(), range.endDate(), agg.skuRows());
|
||||
CompanyOverviewVO.ShopSummary total = bundle.getShopTable() != null && bundle.getShopTable().getTotal() != null
|
||||
? bundle.getShopTable().getTotal() : new CompanyOverviewVO.ShopSummary();
|
||||
return WorkbenchPeriodCompareSliceVO.builder()
|
||||
.startDate(range.startDate()).endDate(range.endDate()).total(total).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompanyOverviewVO.WorkbenchTableBundle loadSummaryTables(WorkbenchExportDTO dto) {
|
||||
WorkbenchQueryDTO query = new WorkbenchQueryDTO();
|
||||
@@ -209,15 +145,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO emptyMultiPanel() {
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(Collections.emptyList())
|
||||
.shop(Collections.emptyList())
|
||||
.category(Collections.emptyList())
|
||||
.product(Collections.emptyList())
|
||||
.build();
|
||||
}
|
||||
|
||||
/** 解析筛选上下文:公司、税率、日期、店铺列表等 */
|
||||
private ShopContext resolveShopContext(WorkbenchQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
@@ -292,63 +219,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
.build();
|
||||
}
|
||||
|
||||
private DimensionAggMaps aggregateDimensionsFromSql(List<OverviewAggRows.ShopProductRow> rows, ShopContext ctx) {
|
||||
Map<String, Agg> platformAgg = new HashMap<>();
|
||||
Map<String, Agg> shopAgg = new HashMap<>();
|
||||
Map<String, Agg> categoryAgg = new HashMap<>();
|
||||
Map<String, Agg> productAgg = new HashMap<>();
|
||||
Set<Long> productIds = new HashSet<>();
|
||||
Set<Long> categoryIds = new HashSet<>();
|
||||
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
String platformKey = blankPlatformKey(row.getPlatformCode());
|
||||
long shopKey = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
long categoryKey = productId <= 0 ? -1L
|
||||
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
|
||||
platformAgg.computeIfAbsent(platformKey, k -> new Agg()).addFromAggRow(row);
|
||||
shopAgg.computeIfAbsent(String.valueOf(shopKey), k -> new Agg()).addFromAggRow(row);
|
||||
categoryAgg.computeIfAbsent(String.valueOf(categoryKey), k -> new Agg()).addFromAggRow(row);
|
||||
productAgg.computeIfAbsent(String.valueOf(productId), k -> new Agg()).addFromAggRow(row);
|
||||
if (productId > 0) {
|
||||
productIds.add(productId);
|
||||
}
|
||||
if (categoryKey > 0) {
|
||||
categoryIds.add(categoryKey);
|
||||
}
|
||||
}
|
||||
Map<Long, ProductPO> productById = loadProducts(productIds);
|
||||
Map<Long, String> categoryNames = loadCategoryNamesByIds(categoryIds);
|
||||
return new DimensionAggMaps(platformAgg, shopAgg, categoryAgg, productAgg,
|
||||
loadPlatformNames(ctx.shops()), categoryNames, productById, ctx.shopById());
|
||||
}
|
||||
|
||||
private Totals totalsFromOrderRows(List<OverviewAggRows.ShopProductRow> rows,
|
||||
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate) {
|
||||
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO;
|
||||
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
|
||||
BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
int orderCount = 0;
|
||||
int salesQty = 0;
|
||||
int dealOrderCount = 0;
|
||||
int dealQuantitySum = 0;
|
||||
for (OverviewAggRows.ShopProductRow row : rows) {
|
||||
sales = sales.add(nz(row.getSalesAmount()));
|
||||
refund = refund.add(nz(row.getRefundAmount()));
|
||||
pc = pc.add(nz(row.getProductCost()));
|
||||
fc = fc.add(nz(row.getFreightCost()));
|
||||
oc = oc.add(nz(row.getOtherCost()));
|
||||
dealAmount = dealAmount.add(nz(row.getDealAmount()));
|
||||
orderCount += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
|
||||
salesQty += row.getSalesQuantitySum() != null ? row.getSalesQuantitySum().intValue() : 0;
|
||||
dealOrderCount += row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
|
||||
dealQuantitySum += row.getDealQuantitySum() != null ? row.getDealQuantitySum().intValue() : 0;
|
||||
}
|
||||
// 注意:商品粒度单量跨商品会重复计;多维/排行仅用销售额等金额字段,KPI 走店铺日文档
|
||||
return buildTotals(sales, refund, pc, fc, oc, promotion, brush, taxRate, orderCount, salesQty,
|
||||
dealAmount, dealOrderCount, dealQuantitySum);
|
||||
}
|
||||
|
||||
private Totals buildTotals(BigDecimal sales, BigDecimal refund, BigDecimal pc, BigDecimal fc, BigDecimal oc,
|
||||
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate,
|
||||
int orderCount, int salesQuantitySum,
|
||||
@@ -411,14 +281,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return list;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCategoryNamesByIds(Set<Long> categoryIds) {
|
||||
if (categoryIds.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().in(CategoryPO::getId, categoryIds))
|
||||
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
@@ -438,44 +300,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
}
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO buildMultiPanel(DimensionAggMaps aggs, Totals cur) {
|
||||
BigDecimal salesAllocBase = cur.totalSales();
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(buildDimRows(aggs.platformAgg(),
|
||||
k -> aggs.platformNames().getOrDefault(k, PlatformCode.labelOf(k)),
|
||||
salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.shop(buildDimRows(aggs.shopAgg(), k -> {
|
||||
ShopPO s = aggs.shopById().get(Long.parseLong(k));
|
||||
return s != null ? s.getName() : "未知店铺";
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.category(buildDimRows(aggs.categoryAgg(), k -> {
|
||||
if ("0".equals(k)) {
|
||||
return "未分类";
|
||||
}
|
||||
if ("-1".equals(k)) {
|
||||
return "其他品类";
|
||||
}
|
||||
return aggs.categoryNames().getOrDefault(Long.parseLong(k), "类目" + k);
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.product(buildDimRows(aggs.productAgg(), k -> {
|
||||
if (k.startsWith("-") || "0".equals(k)) {
|
||||
return "未匹配商品";
|
||||
}
|
||||
ProductPO p = aggs.productById().get(Long.parseLong(k));
|
||||
return p != null ? p.getName() : ("商品" + k);
|
||||
}, salesAllocBase, cur.promotion(), cur.brush(), cur.tax()))
|
||||
.build();
|
||||
}
|
||||
|
||||
private WorkbenchMultiAnalysisPanelVO buildSalesRankPanel(WorkbenchMultiAnalysisPanelVO multi) {
|
||||
return WorkbenchMultiAnalysisPanelVO.builder()
|
||||
.platform(sortByDealAmountDesc(multi.getPlatform()))
|
||||
.shop(sortByDealAmountDesc(multi.getShop()))
|
||||
.category(sortByDealAmountDesc(multi.getCategory()))
|
||||
.product(sortByDealAmountDesc(multi.getProduct()))
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按公司 + 可选平台/单店筛选店铺列表;指定 {@code shopId} 时校验归属与平台一致性。
|
||||
*/
|
||||
@@ -499,22 +323,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return shopService.list(w);
|
||||
}
|
||||
|
||||
/** 按商品 id 批量加载主数据,供类目解析与商品名称展示 */
|
||||
private Map<Long, ProductPO> loadProducts(Iterable<Long> productIds) {
|
||||
List<Long> ids = new ArrayList<>();
|
||||
for (Long id : productIds) {
|
||||
if (id != null && id > 0) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
ids = ids.stream().distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Collections.emptyMap();
|
||||
}
|
||||
List<ProductPO> list = productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, ids));
|
||||
return list.stream().collect(Collectors.toMap(ProductPO::getId, p -> p, (a, b) -> a));
|
||||
}
|
||||
|
||||
/** 从店铺收集平台 code,映射为展示名称 */
|
||||
private Map<String, String> loadPlatformNames(List<ShopPO> shops) {
|
||||
return shops.stream()
|
||||
@@ -528,65 +336,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
return platformCode != null && !platformCode.isBlank() ? platformCode : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 将「字符串 key → 聚合桶」转为多维表格行:每行毛利润 = 净销售额−成本;
|
||||
* 推广费、刷单费、税额均按该行净销售额占 {@code salesTotalCompany} 比例分摊;
|
||||
* 净利润 = 毛利润 − 分摊推广 − 分摊刷单 − 分摊税。
|
||||
*/
|
||||
private List<WorkbenchDimRowVO> buildDimRows(Map<String, Agg> aggs,
|
||||
java.util.function.Function<String, String> nameFn,
|
||||
BigDecimal salesTotalCompany,
|
||||
BigDecimal promoTotal,
|
||||
BigDecimal brushTotal,
|
||||
BigDecimal taxTotal) {
|
||||
List<WorkbenchDimRowVO> rows = new ArrayList<>();
|
||||
for (Map.Entry<String, Agg> e : aggs.entrySet()) {
|
||||
Agg a = e.getValue();
|
||||
if (a.sales.compareTo(BigDecimal.ZERO) <= 0 && a.refund.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal gross = a.sales.subtract(a.cost);
|
||||
BigDecimal promoB = allocShare(a.sales, salesTotalCompany, promoTotal);
|
||||
BigDecimal brushB = allocShare(a.sales, salesTotalCompany, brushTotal);
|
||||
BigDecimal taxB = allocShare(a.sales, salesTotalCompany.max(BigDecimal.ONE), taxTotal);
|
||||
if (salesTotalCompany.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
taxB = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal net = gross.subtract(promoB).subtract(brushB).subtract(taxB);
|
||||
|
||||
BigDecimal salesYuan = yuan2(a.sales);
|
||||
BigDecimal grossYuan = yuan2(gross);
|
||||
BigDecimal netYuan = yuan2(net);
|
||||
BigDecimal refundYuan = yuan2(a.refund);
|
||||
|
||||
BigDecimal grossMarginPct = safePct(gross, a.sales);
|
||||
BigDecimal netMarginPct = safePct(net, a.sales);
|
||||
|
||||
rows.add(WorkbenchDimRowVO.builder()
|
||||
.key(e.getKey())
|
||||
.name(nameFn.apply(e.getKey()))
|
||||
.salesYuan(salesYuan)
|
||||
.grossProfitYuan(grossYuan)
|
||||
.netProfitYuan(netYuan)
|
||||
.refundYuan(refundYuan)
|
||||
.grossMarginPct(grossMarginPct)
|
||||
.netMarginPct(netMarginPct)
|
||||
.build());
|
||||
}
|
||||
rows.sort(Comparator.comparing(WorkbenchDimRowVO::getSalesYuan, Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 按净销售额降序复制排序,用于销售额排行 */
|
||||
private List<WorkbenchDimRowVO> sortByDealAmountDesc(List<WorkbenchDimRowVO> in) {
|
||||
if (in == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return in.stream()
|
||||
.sorted(Comparator.comparing(WorkbenchDimRowVO::getSalesYuan, Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 比例分摊:{@code amount * part / total},四舍五入到 4 位小数;总额或金额为 0 时返回 0。
|
||||
* 用于将区间总推广、刷单、税额拆到各维度行或各日趋势点。
|
||||
@@ -602,7 +351,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
}
|
||||
|
||||
/**
|
||||
* 各平台净销售额占比:与多维分析「平台」维度同源订单聚合;分母为当前筛选下公司净销售额合计。
|
||||
* 各平台净销售额占比;分母为当前筛选下公司净销售额合计。
|
||||
*/
|
||||
private List<WorkbenchCostSliceVO> buildPlatformSalesSlices(Map<String, Agg> platformAgg,
|
||||
Map<String, String> platformNames,
|
||||
@@ -836,17 +585,6 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
private record ComparePeriodBundle(DateRange lastRange, DateRange yoyRange, Totals prev, Totals yoy) {
|
||||
}
|
||||
|
||||
/** 四维聚合桶 + 展示名称 */
|
||||
private record DimensionAggMaps(Map<String, Agg> platformAgg,
|
||||
Map<String, Agg> shopAgg,
|
||||
Map<String, Agg> categoryAgg,
|
||||
Map<String, Agg> productAgg,
|
||||
Map<String, String> platformNames,
|
||||
Map<Long, String> categoryNames,
|
||||
Map<Long, ProductPO> productById,
|
||||
Map<Long, ShopPO> shopById) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 单时间段店铺财务 KPI 总量(与汇总表 + 推广/刷单区间一致)。
|
||||
*/
|
||||
@@ -872,7 +610,7 @@ public class BiWorkbenchServiceImpl implements BiWorkbenchService {
|
||||
BigDecimal dealPiecePrice) {
|
||||
}
|
||||
|
||||
/** 多维或按日聚合用的累加桶:累计销售额、退款、成本 */
|
||||
/** 平台占比等聚合用的累加桶:累计销售额、退款、成本 */
|
||||
private static final class Agg {
|
||||
BigDecimal sales = BigDecimal.ZERO;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
|
||||
@@ -9,27 +9,3 @@ export async function getWorkbenchFinanceApi(data: WorkbenchDTO.Query) {
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** 多维分析 Tab */
|
||||
export async function getWorkbenchMultiAnalysisApi(data: WorkbenchDTO.Query) {
|
||||
return requestClient.post<WorkbenchVO.MultiPanel>(
|
||||
'/bi/workbench/multi-analysis',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** 销售额排行 Tab */
|
||||
export async function getWorkbenchSalesRankApi(data: WorkbenchDTO.Query) {
|
||||
return requestClient.post<WorkbenchVO.MultiPanel>(
|
||||
'/bi/workbench/sales-rank',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
/** 区间对比:单段日期,返回店铺汇总「合计」行(轻量) */
|
||||
export async function getWorkbenchPeriodCompareSliceApi(data: WorkbenchDTO.Query) {
|
||||
return requestClient.post<WorkbenchVO.PeriodCompareSlice>(
|
||||
'/bi/workbench/period-compare/slice',
|
||||
data,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,18 +4,6 @@
|
||||
import type { CompanyOverviewVO } from '#/api/bi/overview';
|
||||
|
||||
export namespace WorkbenchVO {
|
||||
export interface DimRow {
|
||||
key: string;
|
||||
name: string;
|
||||
/** 净销售额(元,两位小数):成交 − 退款 */
|
||||
salesYuan?: number;
|
||||
grossProfitYuan?: number;
|
||||
netProfitYuan?: number;
|
||||
refundYuan?: number;
|
||||
grossMarginPct?: number;
|
||||
netMarginPct?: number;
|
||||
}
|
||||
|
||||
export interface KpiItem {
|
||||
label: string;
|
||||
/** 主指标原始数值(金额为元;不含千分位) */
|
||||
@@ -46,7 +34,7 @@ export namespace WorkbenchVO {
|
||||
salesOrderCount?: number;
|
||||
/** 日毛利润(元)= 净销售额 − 订单成本 */
|
||||
profitYuan?: number;
|
||||
/** 日净利润(元),与 KPI「净利润」及多维分析分摊口径一致 */
|
||||
/** 日净利润(元),与 KPI「净利润」分摊口径一致 */
|
||||
netProfitYuan?: number;
|
||||
refundYuan?: number;
|
||||
}
|
||||
@@ -73,23 +61,9 @@ export namespace WorkbenchVO {
|
||||
yoyCompareDateEnd?: string | null;
|
||||
}
|
||||
|
||||
export interface MultiPanel {
|
||||
platform: DimRow[];
|
||||
shop: DimRow[];
|
||||
category: DimRow[];
|
||||
product: DimRow[];
|
||||
}
|
||||
|
||||
/** 经营概览 Tab 专用 */
|
||||
export interface FinanceSlice {
|
||||
finance: FinancePanel;
|
||||
summaryTables?: CompanyOverviewVO.WorkbenchTableBundle | null;
|
||||
}
|
||||
|
||||
/** 区间对比:单段日期对应的店铺汇总「合计」行(与 /period-compare/slice 对齐) */
|
||||
export interface PeriodCompareSlice {
|
||||
startDate: string;
|
||||
endDate: string;
|
||||
total: CompanyOverviewVO.ShopSummary;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,11 +31,7 @@ import type { PlatformVO } from '#/api/ec/platform/types';
|
||||
import { getShopPageApi } from '#/api/ec/shop/apis';
|
||||
import type { ShopDTO, ShopVO } from '#/api/ec/shop/types';
|
||||
import { getRegionOverviewApi } from '#/api/bi/region/apis';
|
||||
import {
|
||||
getWorkbenchFinanceApi,
|
||||
getWorkbenchMultiAnalysisApi,
|
||||
getWorkbenchSalesRankApi,
|
||||
} from '#/api/bi/workbench/apis';
|
||||
import { getWorkbenchFinanceApi } from '#/api/bi/workbench/apis';
|
||||
import type { WorkbenchDTO, WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
import type { RegionSalesPanel } from './tabs/region/types';
|
||||
import { $t } from '#/locales';
|
||||
@@ -46,9 +42,6 @@ import {
|
||||
|
||||
import WorkbenchFinanceTab from './tabs/finance/index.vue';
|
||||
import WorkbenchRegionTab from './tabs/region/index.vue';
|
||||
import WorkbenchMultiTab from './tabs/multi/index.vue';
|
||||
import WorkbenchPeriodCompareTab from './tabs/compare/index.vue';
|
||||
import WorkbenchSalesRankTab from './tabs/sales-rank/index.vue';
|
||||
import BiDataHealthToolbarButton from './components/BiDataHealthToolbarButton.vue';
|
||||
|
||||
defineOptions({ name: 'Workbench' });
|
||||
@@ -63,49 +56,30 @@ function handlePopoverOpen(name: string, open: boolean) {
|
||||
}
|
||||
}
|
||||
|
||||
const EMPTY_MULTI: WorkbenchVO.MultiPanel = {
|
||||
platform: [],
|
||||
shop: [],
|
||||
category: [],
|
||||
product: [],
|
||||
};
|
||||
|
||||
const EMPTY_FINANCE: WorkbenchVO.FinancePanel = {
|
||||
kpis: [],
|
||||
dealTrend: [],
|
||||
platformSalesShare: [],
|
||||
};
|
||||
|
||||
/** 需懒加载数据的 Tab(区间对比 Tab 自行请求) */
|
||||
type DataTabKey = 'finance' | 'region' | 'multi' | 'salesRank';
|
||||
/** 需懒加载数据的 Tab */
|
||||
type DataTabKey = 'finance' | 'region';
|
||||
|
||||
const financeSlice = ref<WorkbenchVO.FinanceSlice | null>(null);
|
||||
const regionPanel = ref<RegionSalesPanel | null>(null);
|
||||
const multiAnalysisData = ref<WorkbenchVO.MultiPanel | null>(null);
|
||||
const salesRankData = ref<WorkbenchVO.MultiPanel | null>(null);
|
||||
|
||||
const financeLoading = ref(false);
|
||||
const regionLoading = ref(false);
|
||||
const multiLoading = ref(false);
|
||||
const salesRankLoading = ref(false);
|
||||
|
||||
/** Tab 首次激活标记:筛选变更时重置,切换 Tab 时再按需拉数 */
|
||||
const tabLoaded: Record<DataTabKey, boolean> = {
|
||||
finance: false,
|
||||
region: false,
|
||||
multi: false,
|
||||
salesRank: false,
|
||||
};
|
||||
|
||||
const financePanel = computed(
|
||||
() => financeSlice.value?.finance ?? EMPTY_FINANCE,
|
||||
);
|
||||
const multiPanel = computed(
|
||||
() => multiAnalysisData.value ?? EMPTY_MULTI,
|
||||
);
|
||||
const salesRankPanel = computed(
|
||||
() => salesRankData.value ?? EMPTY_MULTI,
|
||||
);
|
||||
const summaryTablesPanel = computed(
|
||||
() => financeSlice.value?.summaryTables ?? null,
|
||||
);
|
||||
@@ -465,7 +439,7 @@ function buildWorkbenchQuery(): WorkbenchDTO.Query {
|
||||
return query;
|
||||
}
|
||||
|
||||
const DATA_TAB_KEYS: DataTabKey[] = ['finance', 'region', 'multi', 'salesRank'];
|
||||
const DATA_TAB_KEYS: DataTabKey[] = ['finance', 'region'];
|
||||
|
||||
function toRegionPanel(
|
||||
overview: Awaited<ReturnType<typeof getRegionOverviewApi>>,
|
||||
@@ -501,12 +475,6 @@ function hasTabData(tab: DataTabKey): boolean {
|
||||
case 'region': {
|
||||
return regionPanel.value != null;
|
||||
}
|
||||
case 'multi': {
|
||||
return multiAnalysisData.value != null;
|
||||
}
|
||||
case 'salesRank': {
|
||||
return salesRankData.value != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -534,18 +502,6 @@ async function loadTabData(tab: DataTabKey, opts?: { force?: boolean }) {
|
||||
tabLoaded.region = true;
|
||||
break;
|
||||
}
|
||||
case 'multi': {
|
||||
if (blocking) multiLoading.value = true;
|
||||
multiAnalysisData.value = await getWorkbenchMultiAnalysisApi(query);
|
||||
tabLoaded.multi = true;
|
||||
break;
|
||||
}
|
||||
case 'salesRank': {
|
||||
if (blocking) salesRankLoading.value = true;
|
||||
salesRankData.value = await getWorkbenchSalesRankApi(query);
|
||||
tabLoaded.salesRank = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : '工作台数据加载失败';
|
||||
@@ -566,30 +522,12 @@ async function loadTabData(tab: DataTabKey, opts?: { force?: boolean }) {
|
||||
tabLoaded.region = true;
|
||||
break;
|
||||
}
|
||||
case 'multi': {
|
||||
if (!multiAnalysisData.value) {
|
||||
multiAnalysisData.value = EMPTY_MULTI;
|
||||
}
|
||||
tabLoaded.multi = true;
|
||||
break;
|
||||
}
|
||||
case 'salesRank': {
|
||||
if (!salesRankData.value) {
|
||||
salesRankData.value = EMPTY_MULTI;
|
||||
}
|
||||
tabLoaded.salesRank = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (tab === 'finance') {
|
||||
financeLoading.value = false;
|
||||
} else if (tab === 'region') {
|
||||
regionLoading.value = false;
|
||||
} else if (tab === 'multi') {
|
||||
multiLoading.value = false;
|
||||
} else {
|
||||
salesRankLoading.value = false;
|
||||
regionLoading.value = false;
|
||||
}
|
||||
await nextTick();
|
||||
if (activeTab.value === tab) {
|
||||
@@ -600,18 +538,14 @@ async function loadTabData(tab: DataTabKey, opts?: { force?: boolean }) {
|
||||
|
||||
/** 强制刷新当前 Tab,并将其余数据 Tab 标脏;同步刷新 BI 健康度 */
|
||||
async function softRefreshActiveTab() {
|
||||
const dataPromise =
|
||||
activeTab.value === 'periodCompare'
|
||||
? (async () => {
|
||||
await periodCompareTabRef.value?.refresh?.({ silent: true });
|
||||
softInvalidateDataTabs();
|
||||
})()
|
||||
: (async () => {
|
||||
const tab = activeTab.value as DataTabKey;
|
||||
await loadTabData(tab, { force: true });
|
||||
softInvalidateDataTabs(tab);
|
||||
})();
|
||||
await Promise.all([dataPromise, refreshBiHealth()]);
|
||||
const tab = activeTab.value as DataTabKey;
|
||||
await Promise.all([
|
||||
(async () => {
|
||||
await loadTabData(tab, { force: true });
|
||||
softInvalidateDataTabs(tab);
|
||||
})(),
|
||||
refreshBiHealth(),
|
||||
]);
|
||||
}
|
||||
|
||||
const biHealthRef = ref<InstanceType<typeof BiDataHealthToolbarButton> | null>(
|
||||
@@ -624,11 +558,6 @@ async function refreshBiHealth() {
|
||||
}
|
||||
|
||||
async function refreshActiveDataTab(opts?: { force?: boolean }) {
|
||||
if (activeTab.value === 'periodCompare') {
|
||||
// 筛选变更等带 force:静默重拉,保留旧图
|
||||
await periodCompareTabRef.value?.refresh?.({ silent: !!opts?.force });
|
||||
return;
|
||||
}
|
||||
await loadTabData(activeTab.value as DataTabKey, opts);
|
||||
}
|
||||
|
||||
@@ -654,7 +583,7 @@ function flashRefreshDone() {
|
||||
}, REFRESH_DONE_MS);
|
||||
}
|
||||
|
||||
/** 手动刷新:强制重拉当前 Tab(含区间对比),其它 Tab 标脏;成功后按钮闪「已刷新」 */
|
||||
/** 手动刷新:强制重拉当前 Tab,其它 Tab 标脏;成功后按钮闪「已刷新」 */
|
||||
async function handleManualRefresh() {
|
||||
if (refreshing.value) {
|
||||
return;
|
||||
@@ -769,17 +698,6 @@ const financeTabRef = ref<InstanceType<typeof WorkbenchFinanceTab> | null>(
|
||||
null,
|
||||
);
|
||||
const regionTabRef = ref<InstanceType<typeof WorkbenchRegionTab> | null>(null);
|
||||
const multiTabRef = ref<InstanceType<typeof WorkbenchMultiTab> | null>(null);
|
||||
const salesRankTabRef = ref<InstanceType<typeof WorkbenchSalesRankTab> | null>(
|
||||
null,
|
||||
);
|
||||
const periodCompareTabRef = ref<
|
||||
| (InstanceType<typeof WorkbenchPeriodCompareTab> & {
|
||||
redraw: () => Promise<void>;
|
||||
refresh: (opts?: { silent?: boolean }) => Promise<void>;
|
||||
})
|
||||
| null
|
||||
>(null);
|
||||
|
||||
async function redrawActiveTabCharts() {
|
||||
await nextTick();
|
||||
@@ -792,26 +710,12 @@ async function redrawActiveTabCharts() {
|
||||
await regionTabRef.value?.redraw();
|
||||
break;
|
||||
}
|
||||
case 'multi': {
|
||||
await multiTabRef.value?.redraw();
|
||||
break;
|
||||
}
|
||||
case 'salesRank': {
|
||||
await salesRankTabRef.value?.redraw();
|
||||
break;
|
||||
}
|
||||
case 'periodCompare': {
|
||||
await periodCompareTabRef.value?.redraw();
|
||||
break;
|
||||
}
|
||||
// No default
|
||||
}
|
||||
}
|
||||
|
||||
watch(activeTab, (tab) => {
|
||||
if (tab !== 'periodCompare') {
|
||||
void loadTabData(tab as DataTabKey);
|
||||
}
|
||||
void loadTabData(tab as DataTabKey);
|
||||
void refreshBiHealth();
|
||||
setTimeout(() => {
|
||||
void redrawActiveTabCharts();
|
||||
@@ -1114,7 +1018,6 @@ onUnmounted(() => {
|
||||
:tax-rate="taxRate"
|
||||
:export-context="workbenchExportContext"
|
||||
:finance="financePanel"
|
||||
:multi-analysis="EMPTY_MULTI"
|
||||
:summary-tables="summaryTablesPanel"
|
||||
@navigate-product="handleProductNavigate"
|
||||
@navigate-shop="handleShopNavigate"
|
||||
@@ -1132,31 +1035,6 @@ onUnmounted(() => {
|
||||
/>
|
||||
</Spin>
|
||||
</Tabs.TabPane>
|
||||
<Tabs.TabPane key="multi" tab="多维分析">
|
||||
<Spin :spinning="multiLoading && !multiAnalysisData">
|
||||
<WorkbenchMultiTab
|
||||
ref="multiTabRef"
|
||||
:multi-analysis="multiPanel"
|
||||
/>
|
||||
</Spin>
|
||||
</Tabs.TabPane>
|
||||
<Tabs.TabPane key="salesRank" tab="销售额排行榜">
|
||||
<Spin :spinning="salesRankLoading && !salesRankData">
|
||||
<WorkbenchSalesRankTab
|
||||
ref="salesRankTabRef"
|
||||
:sales-rank="salesRankPanel"
|
||||
/>
|
||||
</Spin>
|
||||
</Tabs.TabPane>
|
||||
<Tabs.TabPane key="periodCompare" tab="区间对比">
|
||||
<WorkbenchPeriodCompareTab
|
||||
ref="periodCompareTabRef"
|
||||
:active-tab="activeTab"
|
||||
:tax-rate="taxRate"
|
||||
:platform-code="parseSelectedPlatformCode()"
|
||||
:shop-id="parseSelectedShopId()"
|
||||
/>
|
||||
</Tabs.TabPane>
|
||||
</Tabs>
|
||||
</div>
|
||||
</Page>
|
||||
|
||||
@@ -1,877 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { EchartsUIType } from '@vben/plugins/echarts';
|
||||
|
||||
import { DatePicker, message, Spin } from 'ant-design-vue';
|
||||
import dayjs from 'dayjs';
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { useDebounceFn } from '@vueuse/core';
|
||||
|
||||
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
|
||||
|
||||
import { getWorkbenchPeriodCompareSliceApi } from '#/api/bi/workbench/apis';
|
||||
import type { WorkbenchDTO, WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
import type { CompanyOverviewVO } from '#/api/bi/overview';
|
||||
import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
|
||||
import { normalizeOverviewRangePickerChange } from '#/utils/overview-date-range';
|
||||
import {
|
||||
overviewTableHints,
|
||||
salesTaxColumnHint,
|
||||
} from '#/utils/overview-table-hints';
|
||||
|
||||
import AnimatedNumberText from '../../components/AnimatedNumberText.vue';
|
||||
import { formatYuanDetail, yuanToWanNum } from '../../utils/money';
|
||||
|
||||
defineOptions({ name: 'WorkbenchPeriodCompareTab' });
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
/** 与父级 Tabs activeKey 同步;仅在本 Tab 激活时请求数据 */
|
||||
activeTab: string;
|
||||
/** 与页头税率一致 */
|
||||
taxRate: number;
|
||||
platformCode?: string;
|
||||
shopId?: number;
|
||||
}>(),
|
||||
{ activeTab: 'finance' },
|
||||
);
|
||||
|
||||
/**
|
||||
* 字段口径与「多维度经营明细汇总」店铺表合计行一致;区间 A/B 数据来自接口,差额与增幅由前端计算。
|
||||
*/
|
||||
type MetricFormat = 'int' | 'money' | 'percent' | 'ratio';
|
||||
|
||||
interface CompareMetric {
|
||||
key: string;
|
||||
label: string;
|
||||
hint: string;
|
||||
format: MetricFormat;
|
||||
/** 区间 A 数值 */
|
||||
valueA: number;
|
||||
/** 区间 B 数值 */
|
||||
valueB: number;
|
||||
}
|
||||
|
||||
function num(v: unknown): number {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : 0;
|
||||
}
|
||||
|
||||
/** 百分比展示统一保留的小数位 */
|
||||
const PCT_DECIMALS = 2;
|
||||
|
||||
function roundTo(n: number, digits = PCT_DECIMALS) {
|
||||
const f = 10 ** digits;
|
||||
return Math.round(n * f) / f;
|
||||
}
|
||||
|
||||
/** 如 12.35% */
|
||||
function formatPercentValue(n: number) {
|
||||
const v = roundTo(n, PCT_DECIMALS);
|
||||
return `${v.toFixed(PCT_DECIMALS)}%`;
|
||||
}
|
||||
|
||||
/** 如 +1.25%(增幅列) */
|
||||
function formatSignedPercent(n: number) {
|
||||
const v = roundTo(n, PCT_DECIMALS);
|
||||
if (v === 0) return `${v.toFixed(PCT_DECIMALS)}%`;
|
||||
const sign = v > 0 ? '+' : '';
|
||||
return `${sign}${v.toFixed(PCT_DECIMALS)}%`;
|
||||
}
|
||||
|
||||
/** 费比差额:百分点,如 +1.25 pts */
|
||||
function formatPercentDeltaPts(d: number) {
|
||||
const v = roundTo(d, PCT_DECIMALS);
|
||||
if (v === 0) return `${v.toFixed(PCT_DECIMALS)} pts`;
|
||||
const sign = v > 0 ? '+' : '';
|
||||
return `${sign}${v.toFixed(PCT_DECIMALS)} pts`;
|
||||
}
|
||||
|
||||
function feeRatioAsPercent(row: CompanyOverviewVO.ShopSummary | null | undefined) {
|
||||
if (!row || row.feeRatio == null) return 0;
|
||||
return roundTo(num(row.feeRatio) * 100, PCT_DECIMALS);
|
||||
}
|
||||
|
||||
function buildCompareMetrics(
|
||||
rowA: CompanyOverviewVO.ShopSummary | null | undefined,
|
||||
rowB: CompanyOverviewVO.ShopSummary | null | undefined,
|
||||
taxHint: string,
|
||||
): CompareMetric[] {
|
||||
const a = rowA ?? undefined;
|
||||
const b = rowB ?? undefined;
|
||||
const z = (r: CompanyOverviewVO.ShopSummary | undefined, fn: (x: CompanyOverviewVO.ShopSummary) => unknown) =>
|
||||
num(r ? fn(r) : undefined);
|
||||
return [
|
||||
{
|
||||
key: 'dealAmount',
|
||||
label: '成交金额',
|
||||
hint: overviewTableHints.dealAmount,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.dealAmount),
|
||||
valueB: z(b, (r) => r.dealAmount),
|
||||
},
|
||||
{
|
||||
key: 'salesAmount',
|
||||
label: '净销售额',
|
||||
hint: overviewTableHints.salesAmount,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.salesAmount),
|
||||
valueB: z(b, (r) => r.salesAmount),
|
||||
},
|
||||
{
|
||||
key: 'dealOrderCount',
|
||||
label: '成交单量',
|
||||
hint: overviewTableHints.dealOrderCount,
|
||||
format: 'int',
|
||||
valueA: z(a, (r) => r.dealOrderCount),
|
||||
valueB: z(b, (r) => r.dealOrderCount),
|
||||
},
|
||||
{
|
||||
key: 'salesOrderCount',
|
||||
label: '净销售单量',
|
||||
hint: overviewTableHints.salesOrderCount,
|
||||
format: 'int',
|
||||
valueA: z(a, (r) => r.salesOrderCount),
|
||||
valueB: z(b, (r) => r.salesOrderCount),
|
||||
},
|
||||
{
|
||||
key: 'dealAverageOrderValue',
|
||||
label: '成交客单价',
|
||||
hint: overviewTableHints.dealAverageOrderValue,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.dealAverageOrderValue),
|
||||
valueB: z(b, (r) => r.dealAverageOrderValue),
|
||||
},
|
||||
{
|
||||
key: 'salesAverageOrderValue',
|
||||
label: '净销售客单价',
|
||||
hint: overviewTableHints.salesAverageOrderValue,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.salesAverageOrderValue),
|
||||
valueB: z(b, (r) => r.salesAverageOrderValue),
|
||||
},
|
||||
{
|
||||
key: 'productCost',
|
||||
label: '商品成本',
|
||||
hint: overviewTableHints.productCost,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.productCost),
|
||||
valueB: z(b, (r) => r.productCost),
|
||||
},
|
||||
{
|
||||
key: 'shippingCost',
|
||||
label: '运费',
|
||||
hint: overviewTableHints.shippingCost,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.shippingCost),
|
||||
valueB: z(b, (r) => r.shippingCost),
|
||||
},
|
||||
{
|
||||
key: 'otherCost',
|
||||
label: '其他成本',
|
||||
hint: overviewTableHints.otherCost,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.otherCost),
|
||||
valueB: z(b, (r) => r.otherCost),
|
||||
},
|
||||
{
|
||||
key: 'orderCost',
|
||||
label: '订单成本',
|
||||
hint: overviewTableHints.orderCost,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.orderCost),
|
||||
valueB: z(b, (r) => r.orderCost),
|
||||
},
|
||||
{
|
||||
key: 'refundAmount',
|
||||
label: '退款金额',
|
||||
hint: overviewTableHints.refundAmount,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.refundAmount),
|
||||
valueB: z(b, (r) => r.refundAmount),
|
||||
},
|
||||
{
|
||||
key: 'totalPromotionFee',
|
||||
label: '推广费',
|
||||
hint: overviewTableHints.totalPromotionFee,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.totalPromotionFee),
|
||||
valueB: z(b, (r) => r.totalPromotionFee),
|
||||
},
|
||||
{
|
||||
key: 'brushFee',
|
||||
label: '刷单费用',
|
||||
hint: overviewTableHints.brushFee,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.brushFee),
|
||||
valueB: z(b, (r) => r.brushFee),
|
||||
},
|
||||
{
|
||||
key: 'feeRatio',
|
||||
label: '费比',
|
||||
hint: overviewTableHints.feeRatioShopRow,
|
||||
format: 'percent',
|
||||
valueA: feeRatioAsPercent(a),
|
||||
valueB: feeRatioAsPercent(b),
|
||||
},
|
||||
{
|
||||
key: 'grossProfit',
|
||||
label: '毛利',
|
||||
hint: overviewTableHints.grossProfit,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.grossProfit),
|
||||
valueB: z(b, (r) => r.grossProfit),
|
||||
},
|
||||
{
|
||||
key: 'totalProfitBeforeTax',
|
||||
label: '税前净利',
|
||||
hint: overviewTableHints.totalProfitBeforeTax,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.totalProfitBeforeTax),
|
||||
valueB: z(b, (r) => r.totalProfitBeforeTax),
|
||||
},
|
||||
{
|
||||
key: 'salesTaxAmount',
|
||||
label: '税额',
|
||||
hint: taxHint,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.salesTaxAmount),
|
||||
valueB: z(b, (r) => r.salesTaxAmount),
|
||||
},
|
||||
{
|
||||
key: 'roi',
|
||||
label: 'ROI',
|
||||
hint: overviewTableHints.roi,
|
||||
format: 'ratio',
|
||||
valueA: z(a, (r) => r.roi),
|
||||
valueB: z(b, (r) => r.roi),
|
||||
},
|
||||
{
|
||||
key: 'profitAfterTax',
|
||||
label: '税后净利',
|
||||
hint: overviewTableHints.profitAfterTax,
|
||||
format: 'money',
|
||||
valueA: z(a, (r) => r.profitAfterTax),
|
||||
valueB: z(b, (r) => r.profitAfterTax),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const sliceA = ref<WorkbenchVO.PeriodCompareSlice | null>(null);
|
||||
const sliceB = ref<WorkbenchVO.PeriodCompareSlice | null>(null);
|
||||
const loading = ref(false);
|
||||
|
||||
const periodA = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
|
||||
dayjs().subtract(1, 'month').startOf('month'),
|
||||
dayjs().subtract(1, 'month').endOf('month'),
|
||||
]);
|
||||
const periodB = ref<[dayjs.Dayjs, dayjs.Dayjs]>([
|
||||
dayjs().startOf('month'),
|
||||
dayjs(),
|
||||
]);
|
||||
|
||||
function onRangeAChange(
|
||||
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
|
||||
dateStrings?: [string, string],
|
||||
) {
|
||||
const d = normalizeOverviewRangePickerChange(value, dateStrings);
|
||||
if (d) periodA.value = d;
|
||||
}
|
||||
|
||||
function onRangeBChange(
|
||||
value: [dayjs.Dayjs, dayjs.Dayjs] | [string, string] | null,
|
||||
dateStrings?: [string, string],
|
||||
) {
|
||||
const d = normalizeOverviewRangePickerChange(value, dateStrings);
|
||||
if (d) periodB.value = d;
|
||||
}
|
||||
|
||||
const labelA = computed(
|
||||
() =>
|
||||
`${periodA.value[0].format('YYYY-MM-DD')} ~ ${periodA.value[1].format('YYYY-MM-DD')}`,
|
||||
);
|
||||
const labelB = computed(
|
||||
() =>
|
||||
`${periodB.value[0].format('YYYY-MM-DD')} ~ ${periodB.value[1].format('YYYY-MM-DD')}`,
|
||||
);
|
||||
|
||||
const metricsRows = computed(() =>
|
||||
buildCompareMetrics(
|
||||
sliceA.value?.total,
|
||||
sliceB.value?.total,
|
||||
salesTaxColumnHint(props.taxRate),
|
||||
),
|
||||
);
|
||||
|
||||
function buildWorkbenchQuery(range: [dayjs.Dayjs, dayjs.Dayjs]): WorkbenchDTO.Query {
|
||||
const q: WorkbenchDTO.Query = {
|
||||
dateRange: [range[0].format('YYYY-MM-DD'), range[1].format('YYYY-MM-DD')],
|
||||
taxRate: props.taxRate,
|
||||
};
|
||||
if (props.platformCode) {
|
||||
q.platformCode = props.platformCode;
|
||||
}
|
||||
if (props.shopId != null) {
|
||||
q.shopId = props.shopId;
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
async function fetchSlices(_opts?: { silent?: boolean }) {
|
||||
if (props.activeTab !== 'periodCompare') {
|
||||
return;
|
||||
}
|
||||
const hasExisting = sliceA.value != null || sliceB.value != null;
|
||||
// 已有数据时静默刷新,避免 Spin 盖住图表
|
||||
if (!hasExisting) {
|
||||
loading.value = true;
|
||||
}
|
||||
try {
|
||||
const [a, b] = await Promise.all([
|
||||
getWorkbenchPeriodCompareSliceApi(buildWorkbenchQuery(periodA.value)),
|
||||
getWorkbenchPeriodCompareSliceApi(buildWorkbenchQuery(periodB.value)),
|
||||
]);
|
||||
sliceA.value = a;
|
||||
sliceB.value = b;
|
||||
} catch (e: unknown) {
|
||||
const msg = e instanceof Error ? e.message : '区间对比数据加载失败';
|
||||
message.error(msg);
|
||||
if (!hasExisting) {
|
||||
sliceA.value = null;
|
||||
sliceB.value = null;
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const debouncedFetchSlices = useDebounceFn(fetchSlices, 280);
|
||||
|
||||
watch(
|
||||
() => ({
|
||||
tab: props.activeTab,
|
||||
tax: props.taxRate,
|
||||
plat: props.platformCode,
|
||||
shop: props.shopId,
|
||||
a0: periodA.value[0]?.valueOf(),
|
||||
a1: periodA.value[1]?.valueOf(),
|
||||
b0: periodB.value[0]?.valueOf(),
|
||||
b1: periodB.value[1]?.valueOf(),
|
||||
}),
|
||||
() => {
|
||||
void debouncedFetchSlices();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
function formatMoney(n: number) {
|
||||
return `¥${n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
||||
}
|
||||
|
||||
function formatMetricValue(m: CompareMetric, v: number) {
|
||||
switch (m.format) {
|
||||
case 'int': {
|
||||
return Math.round(v).toLocaleString('zh-CN');
|
||||
}
|
||||
case 'money': {
|
||||
return formatMoney(v);
|
||||
}
|
||||
case 'percent': {
|
||||
return formatPercentValue(v);
|
||||
}
|
||||
case 'ratio': {
|
||||
return `${v.toFixed(2)} : 1`;
|
||||
}
|
||||
default: {
|
||||
return String(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function formatCell(m: CompareMetric, side: 'a' | 'b') {
|
||||
const v = side === 'a' ? m.valueA : m.valueB;
|
||||
return formatMetricValue(m, v);
|
||||
}
|
||||
|
||||
function metricValueFormatter(m: CompareMetric) {
|
||||
return (n: number) => formatMetricValue(m, n);
|
||||
}
|
||||
|
||||
function delta(m: CompareMetric) {
|
||||
return m.valueB - m.valueA;
|
||||
}
|
||||
|
||||
function growthPct(m: CompareMetric): number | null {
|
||||
let raw: number | null;
|
||||
if (m.format === 'ratio') {
|
||||
if (m.valueA === 0) return null;
|
||||
raw = ((m.valueB - m.valueA) / m.valueA) * 100;
|
||||
} else if (m.valueA === 0) {
|
||||
raw = m.valueB === 0 ? 0 : null;
|
||||
} else {
|
||||
raw = ((m.valueB - m.valueA) / m.valueA) * 100;
|
||||
}
|
||||
if (raw === null || !Number.isFinite(raw)) return null;
|
||||
return roundTo(raw, PCT_DECIMALS);
|
||||
}
|
||||
|
||||
function formatDelta(m: CompareMetric) {
|
||||
const d = delta(m);
|
||||
if (m.format === 'int') {
|
||||
if (d > 0) return `+${d.toLocaleString('zh-CN')}`;
|
||||
return d.toLocaleString('zh-CN');
|
||||
}
|
||||
if (m.format === 'money') {
|
||||
const body = formatMoney(Math.abs(d));
|
||||
if (d > 0) return `+${body}`;
|
||||
if (d < 0) return `-${body}`;
|
||||
return body;
|
||||
}
|
||||
if (m.format === 'percent') {
|
||||
return formatPercentDeltaPts(d);
|
||||
}
|
||||
if (m.format === 'ratio') {
|
||||
const sign = d > 0 ? '+' : '';
|
||||
return `${sign}${d.toFixed(2)}`;
|
||||
}
|
||||
return String(d);
|
||||
}
|
||||
|
||||
function growthDisplay(m: CompareMetric) {
|
||||
const g = growthPct(m);
|
||||
if (g === null) return '—';
|
||||
return formatSignedPercent(g);
|
||||
}
|
||||
|
||||
/** 差额 / 增幅统一按数值正负着色:正=绿,负=红,零或无法计算=灰 */
|
||||
function signedChangeClass(value: number | null | undefined) {
|
||||
if (value === null || value === undefined || !Number.isFinite(value) || value === 0) {
|
||||
return 'font-bold text-slate-500 dark:text-slate-400';
|
||||
}
|
||||
return value > 0
|
||||
? 'font-black text-emerald-600 dark:text-emerald-400'
|
||||
: 'font-black text-rose-600 dark:text-rose-400';
|
||||
}
|
||||
|
||||
function deltaClass(m: CompareMetric) {
|
||||
return signedChangeClass(delta(m));
|
||||
}
|
||||
|
||||
function growthClass(m: CompareMetric) {
|
||||
return signedChangeClass(growthPct(m));
|
||||
}
|
||||
|
||||
const shellClass =
|
||||
'overflow-hidden rounded-2xl border border-slate-200 bg-white/90 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:shadow-none';
|
||||
|
||||
const moneyMetrics = computed(() => metricsRows.value.filter((m) => m.format === 'money'));
|
||||
|
||||
const moneyChartHeightPx = computed(
|
||||
() => Math.max(280, moneyMetrics.value.length * 30 + 100),
|
||||
);
|
||||
|
||||
const growthChartHeightPx = computed(
|
||||
() => Math.max(320, metricsRows.value.length * 26 + 100),
|
||||
);
|
||||
|
||||
function growthBarColor(_m: CompareMetric, g: number | null, dark: boolean) {
|
||||
if (g === null || !Number.isFinite(g) || g === 0) {
|
||||
return dark ? '#64748b' : '#94a3b8';
|
||||
}
|
||||
return g > 0
|
||||
? dark
|
||||
? '#34d399'
|
||||
: '#059669'
|
||||
: dark
|
||||
? '#fb7185'
|
||||
: '#e11d48';
|
||||
}
|
||||
|
||||
const moneyBarRef = ref<EchartsUIType>();
|
||||
const { renderEcharts: renderMoneyBar, resize: resizeMoneyBar } =
|
||||
useEcharts(moneyBarRef);
|
||||
const growthBarRef = ref<EchartsUIType>();
|
||||
const { renderEcharts: renderGrowthBar, resize: resizeGrowthBar } =
|
||||
useEcharts(growthBarRef);
|
||||
|
||||
function chartTheme() {
|
||||
const dark = document.documentElement.classList.contains('dark');
|
||||
return {
|
||||
dark,
|
||||
axis: dark ? 'hsl(240deg 5% 64.9%)' : '#64748b',
|
||||
split: dark ? 'hsl(240deg 3.7% 22%)' : '#f1f5f9',
|
||||
tipBg: dark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
|
||||
tipFg: dark ? 'hsl(0deg 0% 95%)' : '#0f172a',
|
||||
barA: dark ? '#60a5fa' : '#2563eb',
|
||||
barB: dark ? '#fbbf24' : '#d97706',
|
||||
};
|
||||
}
|
||||
|
||||
function drawMoneyCompareChart() {
|
||||
if (!moneyBarRef.value) return;
|
||||
const t = chartTheme();
|
||||
const rows = moneyMetrics.value;
|
||||
const names = rows.map((m) =>
|
||||
m.label.length > 11 ? `${m.label.slice(0, 10)}…` : m.label,
|
||||
);
|
||||
const legendA = `区间 A`;
|
||||
const legendB = `区间 B`;
|
||||
|
||||
void renderMoneyBar({
|
||||
animation: true,
|
||||
animationDuration: 500,
|
||||
animationDurationUpdate: 650,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
title: {
|
||||
text: '金额类指标对比(万元)',
|
||||
left: 0,
|
||||
top: 0,
|
||||
textStyle: { fontSize: 13, fontWeight: 800, color: t.tipFg },
|
||||
subtext: `${labelA.value}\n${labelB.value}`,
|
||||
subtextStyle: { fontSize: 10, fontWeight: 600, color: t.axis, lineHeight: 16 },
|
||||
},
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: { type: 'shadow' },
|
||||
backgroundColor: t.tipBg,
|
||||
borderColor: t.split,
|
||||
textStyle: { color: t.tipFg, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const params = raw as { axisValue?: string; dataIndex?: number }[];
|
||||
if (!Array.isArray(params) || params.length === 0) return '';
|
||||
const idx = params[0]?.dataIndex ?? 0;
|
||||
const m = rows[idx];
|
||||
if (!m) return '';
|
||||
const lines = [
|
||||
`${m.label}`,
|
||||
`${legendA}:${formatYuanDetail(m.valueA)}`,
|
||||
`${legendB}:${formatYuanDetail(m.valueB)}`,
|
||||
];
|
||||
return lines.join('<br/>');
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
top: 4,
|
||||
right: 0,
|
||||
data: [legendA, legendB],
|
||||
textStyle: { color: t.axis, fontWeight: 700, fontSize: 11 },
|
||||
},
|
||||
grid: { left: 4, right: 12, top: 72, bottom: 8, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
name: '万元',
|
||||
nameTextStyle: { color: t.axis, fontSize: 11, fontWeight: 700 },
|
||||
axisLabel: { color: t.axis, formatter: (v: number) => `${v}` },
|
||||
splitLine: { lineStyle: { type: 'dashed', color: t.split } },
|
||||
axisLine: { lineStyle: { color: t.split } },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'category',
|
||||
data: names,
|
||||
inverse: true,
|
||||
axisLabel: { color: t.axis, fontSize: 11, fontWeight: 600 },
|
||||
axisLine: { lineStyle: { color: t.split } },
|
||||
axisTick: { show: false },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: legendA,
|
||||
type: 'bar',
|
||||
data: rows.map((m) => Number(yuanToWanNum(m.valueA).toFixed(2))),
|
||||
barMaxWidth: 18,
|
||||
itemStyle: { color: t.barA, borderRadius: [0, 4, 4, 0] },
|
||||
},
|
||||
{
|
||||
name: legendB,
|
||||
type: 'bar',
|
||||
data: rows.map((m) => Number(yuanToWanNum(m.valueB).toFixed(2))),
|
||||
barMaxWidth: 18,
|
||||
itemStyle: { color: t.barB, borderRadius: [0, 4, 4, 0] },
|
||||
},
|
||||
],
|
||||
}, false);
|
||||
}
|
||||
|
||||
function drawGrowthCompareChart() {
|
||||
if (!growthBarRef.value) return;
|
||||
const t = chartTheme();
|
||||
const mr = metricsRows.value;
|
||||
const names = mr.map((m) =>
|
||||
m.label.length > 10 ? `${m.label.slice(0, 9)}…` : m.label,
|
||||
);
|
||||
|
||||
const numericGrowth = mr.map((m) => growthPct(m)).filter(
|
||||
(x): x is number => x != null && Number.isFinite(x),
|
||||
);
|
||||
let minV = 0;
|
||||
let maxV = 0;
|
||||
for (const v of numericGrowth) {
|
||||
minV = Math.min(minV, v);
|
||||
maxV = Math.max(maxV, v);
|
||||
}
|
||||
const pad = Math.max(8, (maxV - minV) * 0.08);
|
||||
minV = minV >= 0 ? Math.min(0, minV - pad) : minV - pad;
|
||||
maxV = maxV <= 0 ? Math.max(0, maxV + pad) : maxV + pad;
|
||||
|
||||
void renderGrowthBar({
|
||||
animation: true,
|
||||
animationDuration: 500,
|
||||
animationDurationUpdate: 650,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
title: {
|
||||
text: '相对区间 A 的增幅(%)',
|
||||
left: 0,
|
||||
top: 0,
|
||||
textStyle: { fontSize: 13, fontWeight: 800, color: t.tipFg },
|
||||
subtext: '与表格「增幅」列同口径;绿=正增幅、红=负增幅;区间 A 为 0 时无法计算。',
|
||||
subtextStyle: { fontSize: 10, fontWeight: 600, color: t.axis, lineHeight: 14 },
|
||||
},
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: { type: 'shadow' },
|
||||
backgroundColor: t.tipBg,
|
||||
borderColor: t.split,
|
||||
textStyle: { color: t.tipFg, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const params = raw as
|
||||
| { dataIndex?: number; data?: { realGrowth: number | null } }[]
|
||||
| undefined;
|
||||
if (!Array.isArray(params) || params.length === 0) return '';
|
||||
const p0 = params[0];
|
||||
const idx = p0?.dataIndex ?? 0;
|
||||
const m = mr[idx];
|
||||
if (!m) return '';
|
||||
const rg = p0?.data?.realGrowth;
|
||||
if (rg === null || rg === undefined || !Number.isFinite(rg)) {
|
||||
return `${m.label}<br/>增幅:—<br/>A:${formatCell(m, 'a')}<br/>B:${formatCell(m, 'b')}`;
|
||||
}
|
||||
return `${m.label}<br/>增幅:${formatSignedPercent(rg)}<br/>A:${formatCell(m, 'a')}<br/>B:${formatCell(m, 'b')}`;
|
||||
},
|
||||
},
|
||||
grid: { left: 4, right: 56, top: 64, bottom: 8, containLabel: true },
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
min: minV,
|
||||
max: maxV,
|
||||
name: '%',
|
||||
nameTextStyle: { color: t.axis, fontSize: 11, fontWeight: 700 },
|
||||
axisLabel: {
|
||||
color: t.axis,
|
||||
formatter: (v: number) => formatPercentValue(Number(v)),
|
||||
},
|
||||
splitLine: { lineStyle: { type: 'dashed', color: t.split } },
|
||||
axisLine: { lineStyle: { color: t.split } },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'category',
|
||||
data: names,
|
||||
inverse: true,
|
||||
axisLabel: { color: t.axis, fontSize: 11, fontWeight: 600 },
|
||||
axisLine: { lineStyle: { color: t.split } },
|
||||
axisTick: { show: false },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: 'bar',
|
||||
name: '增幅',
|
||||
data: mr.map((m) => {
|
||||
const g = growthPct(m);
|
||||
const ok = g !== null && Number.isFinite(g);
|
||||
return {
|
||||
value: ok ? g : 0,
|
||||
realGrowth: g,
|
||||
itemStyle: { color: growthBarColor(m, g, t.dark), borderRadius: [0, 4, 4, 0] },
|
||||
};
|
||||
}),
|
||||
barMaxWidth: 16,
|
||||
label: {
|
||||
show: true,
|
||||
position: (p: { value?: unknown }) =>
|
||||
typeof p.value === 'number' && p.value < 0 ? 'left' : 'right',
|
||||
color: t.axis,
|
||||
fontWeight: 700,
|
||||
fontSize: 10,
|
||||
formatter: (p: { data?: unknown }) => {
|
||||
const row = p.data as { realGrowth?: number | null } | undefined;
|
||||
const rg = row?.realGrowth;
|
||||
if (rg === null || rg === undefined || !Number.isFinite(rg)) return '';
|
||||
return formatSignedPercent(rg);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
} as never, false);
|
||||
}
|
||||
|
||||
async function redraw() {
|
||||
await nextTick();
|
||||
drawMoneyCompareChart();
|
||||
drawGrowthCompareChart();
|
||||
resizeMoneyBar();
|
||||
resizeGrowthBar();
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (props.activeTab === 'periodCompare') {
|
||||
void debouncedFetchSlices();
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [metricsRows.value, labelA.value, labelB.value],
|
||||
() => {
|
||||
void redraw();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
defineExpose({ redraw, refresh: fetchSlices });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-4 space-y-6">
|
||||
<div :class="shellClass">
|
||||
<div
|
||||
class="border-b border-slate-100 px-6 py-5 dark:border-[hsl(240deg_3.7%_22%)] md:px-8"
|
||||
>
|
||||
<h2
|
||||
class="text-lg font-black text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
区间对比
|
||||
</h2>
|
||||
<p
|
||||
class="mt-1 text-xs font-bold leading-relaxed text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
首次进入本 Tab 时按当前筛选与税率分别请求区间 A、区间 B;上方为<strong class="font-black text-slate-600 dark:text-slate-300">双柱对比(万元)</strong>与<strong class="font-black text-slate-600 dark:text-slate-300">相对 A 的增幅条形图</strong>,下方为明细表(与「多维度经营明细汇总」店铺表合计行同源)。差额、增幅及增幅图:<span class="text-emerald-600 dark:text-emerald-400">绿色=上升</span>,<span class="text-rose-600 dark:text-rose-400">红色=下降</span>(按 B−A 数值正负,与指标好坏无关)。
|
||||
</p>
|
||||
<div
|
||||
class="mt-4 flex flex-col gap-4 lg:flex-row lg:flex-wrap lg:items-end"
|
||||
>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="mb-1 text-xs font-bold text-slate-500 dark:text-slate-400">
|
||||
区间 A(基准)
|
||||
</div>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="periodA"
|
||||
format="YYYY-MM-DD"
|
||||
:allow-clear="false"
|
||||
class="w-full max-w-md"
|
||||
@change="onRangeAChange"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="mb-1 text-xs font-bold text-slate-500 dark:text-slate-400">
|
||||
区间 B(对比)
|
||||
</div>
|
||||
<DatePicker.RangePicker
|
||||
v-model:value="periodB"
|
||||
format="YYYY-MM-DD"
|
||||
:allow-clear="false"
|
||||
class="w-full max-w-md"
|
||||
@change="onRangeBChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Spin :spinning="loading && !sliceA && !sliceB">
|
||||
<div
|
||||
class="border-t border-slate-100 px-3 py-4 dark:border-[hsl(240deg_3.7%_22%)] md:px-6"
|
||||
>
|
||||
<div class="grid min-w-0 gap-4 xl:grid-cols-2">
|
||||
<div class="min-h-0 min-w-0 overflow-hidden rounded-xl bg-slate-50/80 p-3 dark:bg-[hsl(240deg_3.7%_15.9%/35%)]">
|
||||
<EchartsUI
|
||||
ref="moneyBarRef"
|
||||
:height="`${moneyChartHeightPx}px`"
|
||||
class="min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-h-0 min-w-0 overflow-hidden rounded-xl bg-slate-50/80 p-3 dark:bg-[hsl(240deg_3.7%_15.9%/35%)]">
|
||||
<EchartsUI
|
||||
ref="growthBarRef"
|
||||
:height="`${growthChartHeightPx}px`"
|
||||
class="min-w-0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="border-t border-slate-100 px-2 pb-4 pt-2 dark:border-[hsl(240deg_3.7%_22%)] md:px-4"
|
||||
>
|
||||
<table
|
||||
class="min-w-[880px] w-full border-collapse text-left text-sm md:min-w-0"
|
||||
>
|
||||
<thead>
|
||||
<tr
|
||||
class="border-b border-slate-200 bg-slate-50/90 text-slate-700 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_15.9%/80%)] dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
<th
|
||||
class="sticky left-0 z-10 border-r border-slate-200 bg-slate-50/95 px-4 py-3 text-xs font-black dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_14%)]"
|
||||
>
|
||||
指标
|
||||
</th>
|
||||
<th class="px-4 py-3 text-xs font-black">
|
||||
区间 A<br /><span
|
||||
class="font-bold text-slate-500 dark:text-slate-400"
|
||||
>{{ labelA }}</span
|
||||
>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-xs font-black">
|
||||
区间 B<br /><span
|
||||
class="font-bold text-slate-500 dark:text-slate-400"
|
||||
>{{ labelB }}</span
|
||||
>
|
||||
</th>
|
||||
<th
|
||||
class="border-l border-slate-200 px-4 py-3 text-xs font-black dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
差额<br /><span class="font-bold text-slate-500">B − A</span>
|
||||
</th>
|
||||
<th class="px-4 py-3 text-xs font-black">
|
||||
增幅<br /><span class="font-bold text-slate-500">相对 A</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-slate-100 dark:divide-[hsl(240deg_3.7%_22%)]">
|
||||
<tr
|
||||
v-for="m in metricsRows"
|
||||
:key="m.key"
|
||||
class="transition-colors hover:bg-blue-50/40 dark:hover:bg-[hsl(217.2deg_32.6%_17.5%/25%)]"
|
||||
>
|
||||
<td
|
||||
class="sticky left-0 z-10 border-r border-slate-100 bg-white/95 px-4 py-3 text-xs font-bold text-slate-800 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
<OverviewColumnHint :title="m.hint">
|
||||
{{ m.label }}
|
||||
</OverviewColumnHint>
|
||||
</td>
|
||||
<td class="px-4 py-3 font-mono text-xs font-bold tabular-nums text-slate-800 dark:text-slate-100">
|
||||
<AnimatedNumberText
|
||||
:value="m.valueA"
|
||||
:format="metricValueFormatter(m)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-4 py-3 font-mono text-xs font-bold tabular-nums text-slate-800 dark:text-slate-100">
|
||||
<AnimatedNumberText
|
||||
:value="m.valueB"
|
||||
:format="metricValueFormatter(m)"
|
||||
/>
|
||||
</td>
|
||||
<td
|
||||
class="border-l border-slate-100 px-4 py-3 font-mono text-xs tabular-nums dark:border-[hsl(240deg_3.7%_22%)]"
|
||||
:class="deltaClass(m)"
|
||||
>
|
||||
{{ formatDelta(m) }}
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs font-bold">
|
||||
<span :class="growthClass(m)">{{ growthDisplay(m) }}</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</Spin>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -16,12 +16,6 @@ import OverviewTables from './components/OverviewTables.vue';
|
||||
import { useFinanceKpiPreferences } from './composables/useFinanceKpiPreferences';
|
||||
import type { FinanceKpiCardId } from './constants/kpi-catalog';
|
||||
|
||||
import {
|
||||
buildCategoryOverviewFromDimRows,
|
||||
buildPlatformOverviewFromDimRows,
|
||||
buildShopOverviewFromDimRows,
|
||||
} from '../../utils/overview-bridge';
|
||||
|
||||
defineOptions({ name: 'WorkbenchFinanceTab' });
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -37,30 +31,13 @@ const props = defineProps<{
|
||||
/** 与当前工作台筛选、日期一致,用于底部四表导出 */
|
||||
exportContext?: WorkbenchDTO.ExportPayload | null;
|
||||
finance: WorkbenchVO.FinancePanel;
|
||||
multiAnalysis: WorkbenchVO.MultiPanel;
|
||||
summaryTables?: CompanyOverviewVO.WorkbenchTableBundle | null;
|
||||
}>();
|
||||
|
||||
const shopOverview = computed(
|
||||
() =>
|
||||
props.summaryTables?.shopTable ??
|
||||
buildShopOverviewFromDimRows(props.multiAnalysis.shop),
|
||||
);
|
||||
const platformOverview = computed(
|
||||
() =>
|
||||
props.summaryTables?.platformTable ??
|
||||
buildPlatformOverviewFromDimRows(props.multiAnalysis.platform),
|
||||
);
|
||||
const categoryOverview = computed(
|
||||
() =>
|
||||
props.summaryTables?.categoryTable ??
|
||||
buildCategoryOverviewFromDimRows(props.multiAnalysis.category),
|
||||
);
|
||||
const productOverview = computed(
|
||||
() =>
|
||||
props.summaryTables?.productTable ??
|
||||
buildCategoryOverviewFromDimRows(props.multiAnalysis.product),
|
||||
);
|
||||
const shopOverview = computed(() => props.summaryTables?.shopTable ?? null);
|
||||
const platformOverview = computed(() => props.summaryTables?.platformTable ?? null);
|
||||
const categoryOverview = computed(() => props.summaryTables?.categoryTable ?? null);
|
||||
const productOverview = computed(() => props.summaryTables?.productTable ?? null);
|
||||
const skuOverview = computed(() => props.summaryTables?.skuTable ?? null);
|
||||
|
||||
const IconSliders = createIconifyIcon('lucide:sliders-horizontal');
|
||||
|
||||
-438
@@ -1,438 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { EchartsUIType } from '@vben/plugins/echarts';
|
||||
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
import { computed, nextTick, onMounted, ref, watch } from 'vue';
|
||||
|
||||
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';
|
||||
|
||||
import {
|
||||
formatWanShort,
|
||||
formatYuanDetail,
|
||||
yuanToWanNum,
|
||||
} from '../../../utils/money';
|
||||
|
||||
defineOptions({ name: 'WorkbenchDimChartsCard' });
|
||||
|
||||
type WorkbenchDimKey = keyof WorkbenchVO.MultiPanel;
|
||||
|
||||
const props = defineProps<{
|
||||
dimension: WorkbenchDimKey;
|
||||
title: string;
|
||||
variant: 'analysis' | 'rank';
|
||||
/** 接口维度行;未传时使用本地演示数据 */
|
||||
rows?: WorkbenchVO.DimRow[];
|
||||
/** 为 true 时排行图不展示演示环比 */
|
||||
liveData?: boolean;
|
||||
}>();
|
||||
|
||||
/** 多维分析:不在卡片上 overflow-hidden,避免底部 X 轴类目名被裁掉 */
|
||||
const analysisCardClass =
|
||||
'min-w-0 rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-4 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px] sm:p-5';
|
||||
|
||||
/** 排行榜:保留 overflow-hidden,横向条形图不易在底部溢出 */
|
||||
const rankPanelClass =
|
||||
'min-w-0 overflow-hidden rounded-2xl border border-slate-200 dark:border-[hsl(240deg_3.7%_22%)] bg-white/90 dark:bg-[hsl(222.34deg_10.43%_12.27%)] p-4 shadow-[0_4px_12px_rgba(0,0,0,0.03)] dark:shadow-none backdrop-blur-[10px] sm:p-5';
|
||||
|
||||
/** 底部留白:旋转类目需要更高;横向「平台名」等也要留足一行高度 */
|
||||
function multiChartGridBottomPx(
|
||||
categoryCount: number,
|
||||
rotated: boolean,
|
||||
): number {
|
||||
if (rotated) {
|
||||
if (categoryCount > 5) return 92;
|
||||
return 76;
|
||||
}
|
||||
if (categoryCount > 4) return 52;
|
||||
return 44;
|
||||
}
|
||||
|
||||
const rows = computed(() => props.rows ?? []);
|
||||
|
||||
const rankMomDemo = [16.2, 11.4, 8.8, -2.1, 6.5, 4.2, 3.8, 2.4];
|
||||
|
||||
const rankRows = computed(() => {
|
||||
const raw = [...rows.value];
|
||||
const sorted = raw.sort(
|
||||
(a, b) => Number(b.salesYuan ?? 0) - Number(a.salesYuan ?? 0),
|
||||
);
|
||||
const total =
|
||||
sorted.reduce((s, r) => s + Number(r.salesYuan ?? 0), 0) || 1;
|
||||
return sorted.map((r, i) => ({
|
||||
rank: i + 1,
|
||||
key: r.key,
|
||||
name: r.name,
|
||||
salesYuan: Number(r.salesYuan ?? 0),
|
||||
sharePct: Number(((Number(r.salesYuan ?? 0) / total) * 100).toFixed(1)),
|
||||
momPct: props.liveData
|
||||
? 0
|
||||
: (rankMomDemo[i % rankMomDemo.length] ?? 0),
|
||||
}));
|
||||
});
|
||||
|
||||
function truncateLabel(s: string, max = 14) {
|
||||
if (s.length <= max) return s;
|
||||
return `${s.slice(0, max - 1)}…`;
|
||||
}
|
||||
|
||||
const multiBarChartRef = ref<EchartsUIType>();
|
||||
const { renderEcharts: renderMultiBar } = useEcharts(multiBarChartRef);
|
||||
const multiLineChartRef = ref<EchartsUIType>();
|
||||
const { renderEcharts: renderMultiLine } = useEcharts(multiLineChartRef);
|
||||
const rankBarChartRef = ref<EchartsUIType>();
|
||||
const { renderEcharts: renderRankBar } = useEcharts(rankBarChartRef);
|
||||
|
||||
const drawMultiBarChart = () => {
|
||||
if (!multiBarChartRef.value) return;
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
const axisLabel = isDark ? 'hsl(240deg 5% 64.9%)' : '#64748b';
|
||||
const split = isDark ? 'hsl(240deg 3.7% 22%)' : '#f1f5f9';
|
||||
const r = rows.value;
|
||||
const nameMax = props.dimension === 'product' ? 12 : 18;
|
||||
const names = r.map((row) => truncateLabel(row.name, nameMax));
|
||||
const rotateLabels = r.length > 4;
|
||||
const bottomPad = multiChartGridBottomPx(r.length, rotateLabels);
|
||||
|
||||
renderMultiBar({
|
||||
animation: true,
|
||||
animationDuration: 500,
|
||||
animationDurationUpdate: 650,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
|
||||
textStyle: { color: isDark ? 'hsl(0deg 0% 95%)' : '#0f172a' },
|
||||
formatter: (params: any) => {
|
||||
if (!Array.isArray(params) || params.length === 0) return '';
|
||||
const idx = params[0]?.dataIndex ?? 0;
|
||||
const row = r[idx];
|
||||
if (!row) return '';
|
||||
const lines = params.map((p: any) => {
|
||||
const wan = Number(p.value);
|
||||
const yuan = wan * 10_000;
|
||||
return `${p.marker ?? ''}${p.seriesName}: ${formatYuanDetail(yuan)}`;
|
||||
});
|
||||
return `${params[0]?.axisValueLabel ?? ''}<br/>${lines.join('<br/>')}`;
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
top: 2,
|
||||
itemWidth: 10,
|
||||
itemHeight: 8,
|
||||
itemGap: 4,
|
||||
textStyle: { color: axisLabel, fontWeight: 700, fontSize: 10 },
|
||||
data: ['净销售额(万)', '毛利额(万)', '净利额(万)', '退款金额(万)'],
|
||||
},
|
||||
grid: {
|
||||
left: '2%',
|
||||
right: '2%',
|
||||
bottom: bottomPad,
|
||||
top: 36,
|
||||
containLabel: true,
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: names,
|
||||
axisLine: { lineStyle: { color: split } },
|
||||
axisLabel: {
|
||||
color: axisLabel,
|
||||
fontSize: 11,
|
||||
rotate: rotateLabels ? 28 : 0,
|
||||
interval: 0,
|
||||
margin: 12,
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
name: '万元',
|
||||
nameTextStyle: { color: axisLabel, fontSize: 11, fontWeight: 700 },
|
||||
splitLine: { lineStyle: { type: 'dashed', color: split } },
|
||||
axisLabel: { color: axisLabel },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: '净销售额(万)',
|
||||
type: 'bar',
|
||||
data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))),
|
||||
barMaxWidth: 16,
|
||||
itemStyle: { color: isDark ? '#60a5fa' : '#2563eb' },
|
||||
},
|
||||
{
|
||||
name: '毛利额(万)',
|
||||
type: 'bar',
|
||||
data: r.map((row) => yuanToWanNum(Number(row.grossProfitYuan ?? 0))),
|
||||
barMaxWidth: 16,
|
||||
itemStyle: { color: isDark ? '#34d399' : '#059669' },
|
||||
},
|
||||
{
|
||||
name: '净利额(万)',
|
||||
type: 'bar',
|
||||
data: r.map((row) => yuanToWanNum(Number(row.netProfitYuan ?? 0))),
|
||||
barMaxWidth: 16,
|
||||
itemStyle: { color: isDark ? '#a78bfa' : '#7c3aed' },
|
||||
},
|
||||
{
|
||||
name: '退款金额(万)',
|
||||
type: 'bar',
|
||||
data: r.map((row) => yuanToWanNum(Number(row.refundYuan ?? 0))),
|
||||
barMaxWidth: 16,
|
||||
itemStyle: { color: isDark ? '#fb7185' : '#e11d48' },
|
||||
},
|
||||
],
|
||||
}, false);
|
||||
};
|
||||
|
||||
const drawMultiLineChart = () => {
|
||||
if (!multiLineChartRef.value) return;
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
const axisLabel = isDark ? 'hsl(240deg 5% 64.9%)' : '#64748b';
|
||||
const split = isDark ? 'hsl(240deg 3.7% 22%)' : '#f1f5f9';
|
||||
const r = rows.value;
|
||||
const nameMax = props.dimension === 'product' ? 12 : 18;
|
||||
const names = r.map((row) => truncateLabel(row.name, nameMax));
|
||||
const rotateLabels = r.length > 4;
|
||||
const bottomPad = multiChartGridBottomPx(r.length, rotateLabels);
|
||||
|
||||
renderMultiLine({
|
||||
animation: true,
|
||||
animationDuration: 500,
|
||||
animationDurationUpdate: 650,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
|
||||
textStyle: { color: isDark ? 'hsl(0deg 0% 95%)' : '#0f172a' },
|
||||
},
|
||||
legend: {
|
||||
top: 2,
|
||||
itemWidth: 10,
|
||||
itemHeight: 8,
|
||||
itemGap: 8,
|
||||
textStyle: { color: axisLabel, fontWeight: 700, fontSize: 10 },
|
||||
data: ['毛利率%', '净利率%'],
|
||||
},
|
||||
grid: {
|
||||
left: '2%',
|
||||
right: '3%',
|
||||
bottom: bottomPad,
|
||||
top: 32,
|
||||
containLabel: true,
|
||||
},
|
||||
xAxis: {
|
||||
type: 'category',
|
||||
data: names,
|
||||
axisLine: { lineStyle: { color: split } },
|
||||
axisLabel: {
|
||||
color: axisLabel,
|
||||
fontSize: 11,
|
||||
rotate: rotateLabels ? 28 : 0,
|
||||
interval: 0,
|
||||
margin: 12,
|
||||
},
|
||||
},
|
||||
yAxis: {
|
||||
type: 'value',
|
||||
name: '%',
|
||||
nameTextStyle: { color: axisLabel, fontSize: 11, fontWeight: 700 },
|
||||
splitLine: { lineStyle: { type: 'dashed', color: split } },
|
||||
axisLabel: { color: axisLabel },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: '毛利率%',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
symbolSize: 6,
|
||||
data: r.map((row) => Number(row.grossMarginPct ?? 0)),
|
||||
lineStyle: { width: 2.5, color: isDark ? '#34d399' : '#059669' },
|
||||
itemStyle: { color: isDark ? '#34d399' : '#059669' },
|
||||
},
|
||||
{
|
||||
name: '净利率%',
|
||||
type: 'line',
|
||||
smooth: true,
|
||||
symbolSize: 6,
|
||||
data: r.map((row) => Number(row.netMarginPct ?? 0)),
|
||||
lineStyle: { width: 2.5, color: isDark ? '#fbbf24' : '#d97706' },
|
||||
itemStyle: { color: isDark ? '#fbbf24' : '#d97706' },
|
||||
},
|
||||
],
|
||||
}, false);
|
||||
};
|
||||
|
||||
const drawRankBarChart = () => {
|
||||
if (!rankBarChartRef.value) return;
|
||||
const isDark = document.documentElement.classList.contains('dark');
|
||||
const axisLabel = isDark ? 'hsl(240deg 5% 64.9%)' : '#64748b';
|
||||
const split = isDark ? 'hsl(240deg 3.7% 22%)' : '#f1f5f9';
|
||||
const r = rankRows.value;
|
||||
const labelMax = props.dimension === 'product' ? 20 : 16;
|
||||
const yCats = r.map(
|
||||
(row) => `${row.rank}. ${truncateLabel(row.name, labelMax)}`,
|
||||
);
|
||||
|
||||
renderRankBar({
|
||||
animation: true,
|
||||
animationDuration: 500,
|
||||
animationDurationUpdate: 650,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
tooltip: {
|
||||
trigger: 'axis',
|
||||
axisPointer: { type: 'shadow' },
|
||||
backgroundColor: isDark ? 'hsl(222.34deg 10.43% 12.27%)' : '#fff',
|
||||
textStyle: { color: isDark ? 'hsl(0deg 0% 95%)' : '#0f172a' },
|
||||
formatter: (params: unknown) => {
|
||||
const arr = Array.isArray(params) ? params : [params];
|
||||
const p = arr[0] as {
|
||||
dataIndex?: number;
|
||||
marker?: string;
|
||||
value?: number;
|
||||
};
|
||||
const i = p?.dataIndex ?? 0;
|
||||
const row = r[i];
|
||||
if (!row) return '';
|
||||
const mom =
|
||||
row.momPct >= 0 ? `▲${row.momPct}` : `▼${Math.abs(row.momPct)}`;
|
||||
const momLine = props.liveData
|
||||
? ''
|
||||
: `<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}`;
|
||||
},
|
||||
},
|
||||
grid: {
|
||||
left: '2%',
|
||||
right: '6%',
|
||||
top: 8,
|
||||
bottom: 28,
|
||||
containLabel: true,
|
||||
},
|
||||
xAxis: {
|
||||
type: 'value',
|
||||
name: '净销售额(万)',
|
||||
nameTextStyle: { color: axisLabel, fontSize: 11, fontWeight: 700 },
|
||||
nameGap: 6,
|
||||
splitLine: { lineStyle: { type: 'dashed', color: split } },
|
||||
axisLabel: { color: axisLabel },
|
||||
},
|
||||
yAxis: {
|
||||
type: 'category',
|
||||
data: yCats,
|
||||
inverse: true,
|
||||
axisLine: { lineStyle: { color: split } },
|
||||
axisLabel: { color: axisLabel, fontSize: 11, fontWeight: 700 },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
name: '净销售额(万)',
|
||||
type: 'bar',
|
||||
data: r.map((row) => yuanToWanNum(Number(row.salesYuan ?? 0))),
|
||||
barMaxWidth: 22,
|
||||
itemStyle: {
|
||||
borderRadius: [0, 8, 8, 0],
|
||||
color: {
|
||||
type: 'linear',
|
||||
x: 0,
|
||||
y: 0,
|
||||
x2: 1,
|
||||
y2: 0,
|
||||
colorStops: [
|
||||
{ offset: 0, color: isDark ? '#1e3a8a' : '#bfdbfe' },
|
||||
{ offset: 1, color: isDark ? '#60a5fa' : '#2563eb' },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}, false);
|
||||
};
|
||||
|
||||
const redraw = async () => {
|
||||
await nextTick();
|
||||
if (props.variant === 'analysis') {
|
||||
drawMultiBarChart();
|
||||
drawMultiLineChart();
|
||||
} else {
|
||||
drawRankBarChart();
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
void redraw();
|
||||
});
|
||||
|
||||
watch(
|
||||
() => [props.rows, props.dimension, props.variant, props.liveData],
|
||||
() => {
|
||||
void redraw();
|
||||
},
|
||||
{ deep: true },
|
||||
);
|
||||
|
||||
defineExpose({ redraw });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="variant === 'analysis'" :class="analysisCardClass">
|
||||
<div
|
||||
class="border-b border-slate-100 pb-2 dark:border-b-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<h3
|
||||
class="text-base font-black text-slate-800 sm:text-lg dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
{{ title }}
|
||||
</h3>
|
||||
<p
|
||||
class="mt-0.5 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
销售/毛利/净利/退款(柱)与毛利率、净利率(线)·
|
||||
{{ liveData ? '接口数据(与工作台订单口径一致)' : '演示数据' }}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="mt-3 grid min-w-0 grid-cols-1 gap-4 lg:grid-cols-2 lg:gap-0 lg:divide-x lg:divide-slate-200 dark:lg:divide-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<div class="min-h-0 min-w-0 lg:pr-3">
|
||||
<p
|
||||
class="mb-1 text-xs font-black text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
金额对比(万)
|
||||
</p>
|
||||
<div class="h-[248px] min-h-0 w-full sm:h-[264px]">
|
||||
<EchartsUI ref="multiBarChartRef" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="min-h-0 min-w-0 lg:pl-3">
|
||||
<p
|
||||
class="mb-1 text-xs font-black text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
利率(%)
|
||||
</p>
|
||||
<div class="h-[248px] min-h-0 w-full sm:h-[264px]">
|
||||
<EchartsUI ref="multiLineChartRef" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else :class="rankPanelClass">
|
||||
<div
|
||||
class="border-b border-slate-100 pb-3 dark:border-b-[hsl(240deg_3.7%_22%)]"
|
||||
>
|
||||
<h3
|
||||
class="text-lg font-black text-slate-800 dark:text-[hsl(0deg_0%_95%)]"
|
||||
>
|
||||
{{ title }} · 净销售额排行(万)
|
||||
</h3>
|
||||
<p
|
||||
class="mt-1 text-xs font-bold text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
自上而下为第 1 名;悬浮查看占合计
|
||||
{{ liveData ? '(接口数据)' : '与环比(演示)' }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="mt-4 h-[320px] min-h-0 w-full overflow-hidden md:h-[360px]">
|
||||
<EchartsUI ref="rankBarChartRef" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
import WorkbenchDimChartsCard from './WorkbenchDimChartsCard.vue';
|
||||
|
||||
defineOptions({ name: 'WorkbenchMultiDimCardsGrid' });
|
||||
|
||||
const props = defineProps<{
|
||||
multiAnalysis: WorkbenchVO.MultiPanel;
|
||||
liveData?: boolean;
|
||||
}>();
|
||||
|
||||
const multiPlatformCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
const multiShopCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
const multiCategoryCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
const multiProductCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
|
||||
const cardRefs = [
|
||||
multiPlatformCardRef,
|
||||
multiShopCardRef,
|
||||
multiCategoryCardRef,
|
||||
multiProductCardRef,
|
||||
] as const;
|
||||
|
||||
async function redraw() {
|
||||
await nextTick();
|
||||
await Promise.all(
|
||||
cardRefs.map((r) => r.value?.redraw() ?? Promise.resolve()),
|
||||
);
|
||||
}
|
||||
|
||||
defineExpose({ redraw });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
|
||||
<WorkbenchDimChartsCard
|
||||
ref="multiPlatformCardRef"
|
||||
dimension="platform"
|
||||
variant="analysis"
|
||||
title="平台"
|
||||
:rows="props.multiAnalysis.platform"
|
||||
:live-data="props.liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="multiShopCardRef"
|
||||
dimension="shop"
|
||||
variant="analysis"
|
||||
title="店铺"
|
||||
:rows="props.multiAnalysis.shop"
|
||||
:live-data="props.liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="multiCategoryCardRef"
|
||||
dimension="category"
|
||||
variant="analysis"
|
||||
title="品类"
|
||||
:rows="props.multiAnalysis.category"
|
||||
:live-data="props.liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="multiProductCardRef"
|
||||
dimension="product"
|
||||
variant="analysis"
|
||||
title="商品"
|
||||
:rows="props.multiAnalysis.product"
|
||||
:live-data="props.liveData"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,39 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
import WorkbenchMultiDimCardsGrid from './components/WorkbenchMultiDimCardsGrid.vue';
|
||||
|
||||
defineOptions({ name: 'WorkbenchMultiTab' });
|
||||
|
||||
defineProps<{
|
||||
multiAnalysis: WorkbenchVO.MultiPanel;
|
||||
}>();
|
||||
|
||||
const gridRef = ref<InstanceType<typeof WorkbenchMultiDimCardsGrid> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
async function redraw() {
|
||||
await nextTick();
|
||||
await gridRef.value?.redraw();
|
||||
}
|
||||
|
||||
defineExpose({ redraw });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-4 space-y-3">
|
||||
<p
|
||||
class="text-xs font-bold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
按平台、店铺、品类、商品各一张卡;数据与工作台订单统计口径一致
|
||||
</p>
|
||||
<WorkbenchMultiDimCardsGrid
|
||||
ref="gridRef"
|
||||
:multi-analysis="multiAnalysis"
|
||||
live-data
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
-80
@@ -1,80 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
import WorkbenchDimChartsCard from '../../multi/components/WorkbenchDimChartsCard.vue';
|
||||
|
||||
defineOptions({ name: 'WorkbenchSalesRankCardsGrid' });
|
||||
|
||||
defineProps<{
|
||||
salesRank: WorkbenchVO.MultiPanel;
|
||||
liveData?: boolean;
|
||||
}>();
|
||||
|
||||
const rankPlatformCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
const rankShopCardRef = ref<InstanceType<typeof WorkbenchDimChartsCard> | null>(
|
||||
null,
|
||||
);
|
||||
const rankCategoryCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
const rankProductCardRef = ref<InstanceType<
|
||||
typeof WorkbenchDimChartsCard
|
||||
> | null>(null);
|
||||
|
||||
const cardRefs = [
|
||||
rankPlatformCardRef,
|
||||
rankShopCardRef,
|
||||
rankCategoryCardRef,
|
||||
rankProductCardRef,
|
||||
] as const;
|
||||
|
||||
async function redraw() {
|
||||
await nextTick();
|
||||
await Promise.all(
|
||||
cardRefs.map((r) => r.value?.redraw() ?? Promise.resolve()),
|
||||
);
|
||||
}
|
||||
|
||||
defineExpose({ redraw });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
|
||||
<WorkbenchDimChartsCard
|
||||
ref="rankPlatformCardRef"
|
||||
dimension="platform"
|
||||
variant="rank"
|
||||
title="平台"
|
||||
:rows="salesRank.platform"
|
||||
:live-data="liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="rankShopCardRef"
|
||||
dimension="shop"
|
||||
variant="rank"
|
||||
title="店铺"
|
||||
:rows="salesRank.shop"
|
||||
:live-data="liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="rankCategoryCardRef"
|
||||
dimension="category"
|
||||
variant="rank"
|
||||
title="品类"
|
||||
:rows="salesRank.category"
|
||||
:live-data="liveData"
|
||||
/>
|
||||
<WorkbenchDimChartsCard
|
||||
ref="rankProductCardRef"
|
||||
dimension="product"
|
||||
variant="rank"
|
||||
title="商品"
|
||||
:rows="salesRank.product"
|
||||
:live-data="liveData"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,35 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
import { nextTick, ref } from 'vue';
|
||||
|
||||
import WorkbenchSalesRankCardsGrid from './components/WorkbenchSalesRankCardsGrid.vue';
|
||||
|
||||
defineOptions({ name: 'WorkbenchSalesRankTab' });
|
||||
|
||||
defineProps<{
|
||||
salesRank: WorkbenchVO.MultiPanel;
|
||||
}>();
|
||||
|
||||
const gridRef = ref<InstanceType<typeof WorkbenchSalesRankCardsGrid> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
async function redraw() {
|
||||
await nextTick();
|
||||
await gridRef.value?.redraw();
|
||||
}
|
||||
|
||||
defineExpose({ redraw });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="mt-4 space-y-3">
|
||||
<p
|
||||
class="text-xs font-bold text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
|
||||
>
|
||||
各维度按销售额排序;接口未返回环比时仅展示占比
|
||||
</p>
|
||||
<WorkbenchSalesRankCardsGrid ref="gridRef" :sales-rank="salesRank" live-data />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,237 +0,0 @@
|
||||
import type { CompanyOverviewVO } from '#/api/bi/overview';
|
||||
import type { WorkbenchVO } from '#/api/bi/workbench/types';
|
||||
|
||||
function yuanField(v?: number | null): number {
|
||||
const n = Number(v);
|
||||
if (!Number.isFinite(n)) return 0;
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
function dimRowToShopSummary(row: WorkbenchVO.DimRow): CompanyOverviewVO.ShopSummary {
|
||||
const salesAmount = yuanField(row.salesYuan);
|
||||
const refundAmount = yuanField(row.refundYuan);
|
||||
const grossYuan = yuanField(row.grossProfitYuan);
|
||||
const profitAfterTax = yuanField(row.netProfitYuan);
|
||||
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
|
||||
const shopId = Number(row.key);
|
||||
return {
|
||||
shopId: Number.isFinite(shopId) ? shopId : 0,
|
||||
shopName: row.name,
|
||||
salesAmount,
|
||||
dealAmount: 0,
|
||||
refundAmount,
|
||||
orderCost,
|
||||
productCost: orderCost,
|
||||
shippingCost: 0,
|
||||
otherCost: 0,
|
||||
grossProfit: grossYuan,
|
||||
totalProfitBeforeTax: grossYuan,
|
||||
profitAfterTax,
|
||||
};
|
||||
}
|
||||
|
||||
function aggregateShopTotal(
|
||||
shops: CompanyOverviewVO.ShopSummary[],
|
||||
): CompanyOverviewVO.ShopSummary {
|
||||
const sum = (k: keyof CompanyOverviewVO.ShopSummary) =>
|
||||
shops.reduce((a, x) => a + (Number(x[k]) || 0), 0);
|
||||
const salesAmount = sum('salesAmount');
|
||||
const dealAmount = sum('dealAmount');
|
||||
const salesOrderCount = sum('salesOrderCount');
|
||||
const dealOrderCount = sum('dealOrderCount');
|
||||
const totalPromotionFee = sum('totalPromotionFee');
|
||||
const salesAverageOrderValue = salesOrderCount ? salesAmount / salesOrderCount : 0;
|
||||
const dealAverageOrderValue = dealOrderCount ? dealAmount / dealOrderCount : 0;
|
||||
const feeRatio = salesAmount ? totalPromotionFee / salesAmount : 0;
|
||||
return {
|
||||
shopId: 0,
|
||||
shopName: '合计',
|
||||
targetOrderCount: sum('targetOrderCount'),
|
||||
orderCountAchievementRate: sum('orderCountAchievementRate'),
|
||||
targetAmount: sum('targetAmount'),
|
||||
salesAmountAchievementRate: sum('salesAmountAchievementRate'),
|
||||
salesAmount,
|
||||
dealAmount,
|
||||
refundAmount: sum('refundAmount'),
|
||||
refundOrderCount: sum('refundOrderCount'),
|
||||
refundQuantitySum: sum('refundQuantitySum'),
|
||||
salesOrderCount,
|
||||
dealOrderCount,
|
||||
dealQuantitySum: sum('dealQuantitySum'),
|
||||
salesQuantitySum: sum('salesQuantitySum'),
|
||||
salesAverageOrderValue,
|
||||
dealAverageOrderValue,
|
||||
productCost: sum('productCost'),
|
||||
shippingCost: sum('shippingCost'),
|
||||
otherCost: sum('otherCost'),
|
||||
orderCost: sum('orderCost'),
|
||||
totalPromotionFee,
|
||||
brushFee: sum('brushFee'),
|
||||
feeRatio,
|
||||
grossProfit: sum('grossProfit'),
|
||||
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
|
||||
salesTaxAmount: sum('salesTaxAmount'),
|
||||
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
|
||||
profitAfterTax: sum('profitAfterTax'),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildShopOverviewFromDimRows(
|
||||
rows: WorkbenchVO.DimRow[],
|
||||
): CompanyOverviewVO.ShopOverview {
|
||||
const shops = rows.map(dimRowToShopSummary);
|
||||
return { total: aggregateShopTotal(shops), shops };
|
||||
}
|
||||
|
||||
function dimRowToCategorySummary(
|
||||
row: WorkbenchVO.DimRow,
|
||||
): CompanyOverviewVO.CategorySummary {
|
||||
const salesAmount = yuanField(row.salesYuan);
|
||||
const refundAmount = yuanField(row.refundYuan);
|
||||
const grossYuan = yuanField(row.grossProfitYuan);
|
||||
const profitAfterTax = yuanField(row.netProfitYuan);
|
||||
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
|
||||
const rawId = Number(row.key);
|
||||
const categoryId =
|
||||
row.key === '0' || !Number.isFinite(rawId) ? undefined : rawId;
|
||||
return {
|
||||
categoryId,
|
||||
categoryName: row.name,
|
||||
salesAmount,
|
||||
dealAmount: 0,
|
||||
refundAmount,
|
||||
orderCost,
|
||||
productCost: orderCost,
|
||||
shippingCost: 0,
|
||||
otherCost: 0,
|
||||
grossProfit: grossYuan,
|
||||
totalProfitBeforeTax: grossYuan,
|
||||
profitAfterTax,
|
||||
};
|
||||
}
|
||||
|
||||
function aggregateCategoryTotal(
|
||||
rows: CompanyOverviewVO.CategorySummary[],
|
||||
): CompanyOverviewVO.CategorySummary {
|
||||
const sum = (k: keyof CompanyOverviewVO.CategorySummary) =>
|
||||
rows.reduce((a, x) => a + (Number(x[k]) || 0), 0);
|
||||
const salesAmount = sum('salesAmount');
|
||||
const dealAmount = sum('dealAmount');
|
||||
const salesOrderCount = sum('salesOrderCount');
|
||||
const dealOrderCount = sum('dealOrderCount');
|
||||
const totalPromotionFee = sum('totalPromotionFee');
|
||||
const salesAverageOrderValue = salesOrderCount ? salesAmount / salesOrderCount : 0;
|
||||
const dealAverageOrderValue = dealOrderCount ? dealAmount / dealOrderCount : 0;
|
||||
const feeRatio = salesAmount ? totalPromotionFee / salesAmount : 0;
|
||||
return {
|
||||
categoryName: '合计',
|
||||
salesAmount,
|
||||
dealAmount,
|
||||
refundAmount: sum('refundAmount'),
|
||||
refundOrderCount: sum('refundOrderCount'),
|
||||
refundQuantitySum: sum('refundQuantitySum'),
|
||||
salesOrderCount,
|
||||
dealOrderCount,
|
||||
dealQuantitySum: sum('dealQuantitySum'),
|
||||
salesQuantitySum: sum('salesQuantitySum'),
|
||||
salesAverageOrderValue,
|
||||
dealAverageOrderValue,
|
||||
productCost: sum('productCost'),
|
||||
shippingCost: sum('shippingCost'),
|
||||
otherCost: sum('otherCost'),
|
||||
orderCost: sum('orderCost'),
|
||||
totalPromotionFee,
|
||||
brushFee: sum('brushFee'),
|
||||
feeRatio,
|
||||
grossProfit: sum('grossProfit'),
|
||||
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
|
||||
salesTaxAmount: sum('salesTaxAmount'),
|
||||
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
|
||||
profitAfterTax: sum('profitAfterTax'),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCategoryOverviewFromDimRows(
|
||||
rows: WorkbenchVO.DimRow[],
|
||||
): CompanyOverviewVO.CategoryOverview {
|
||||
const categories = rows.map(dimRowToCategorySummary);
|
||||
return { total: aggregateCategoryTotal(categories), categories };
|
||||
}
|
||||
|
||||
function dimRowToPlatformSummary(
|
||||
row: WorkbenchVO.DimRow,
|
||||
): CompanyOverviewVO.PlatformSummary {
|
||||
const salesAmount = yuanField(row.salesYuan);
|
||||
const refundAmount = yuanField(row.refundYuan);
|
||||
const grossYuan = yuanField(row.grossProfitYuan);
|
||||
const profitAfterTax = yuanField(row.netProfitYuan);
|
||||
const orderCost = Math.max(0, salesAmount - refundAmount - grossYuan);
|
||||
const platformCode = row.key?.trim() || '';
|
||||
return {
|
||||
platformCode,
|
||||
platformName: row.name,
|
||||
salesAmount,
|
||||
dealAmount: 0,
|
||||
refundAmount,
|
||||
orderCost,
|
||||
productCost: orderCost,
|
||||
shippingCost: 0,
|
||||
otherCost: 0,
|
||||
grossProfit: grossYuan,
|
||||
totalProfitBeforeTax: grossYuan,
|
||||
profitAfterTax,
|
||||
};
|
||||
}
|
||||
|
||||
function aggregatePlatformTotal(
|
||||
rows: CompanyOverviewVO.PlatformSummary[],
|
||||
): CompanyOverviewVO.PlatformSummary {
|
||||
const sum = (k: keyof CompanyOverviewVO.PlatformSummary) =>
|
||||
rows.reduce((a, x) => a + (Number(x[k]) || 0), 0);
|
||||
const salesAmount = sum('salesAmount');
|
||||
const dealAmount = sum('dealAmount');
|
||||
const salesOrderCount = sum('salesOrderCount');
|
||||
const dealOrderCount = sum('dealOrderCount');
|
||||
const totalPromotionFee = sum('totalPromotionFee');
|
||||
const salesAverageOrderValue = salesOrderCount ? salesAmount / salesOrderCount : 0;
|
||||
const dealAverageOrderValue = dealOrderCount ? dealAmount / dealOrderCount : 0;
|
||||
const feeRatio = salesAmount ? totalPromotionFee / salesAmount : 0;
|
||||
return {
|
||||
platformCode: '',
|
||||
platformName: '合计',
|
||||
targetOrderCount: sum('targetOrderCount'),
|
||||
orderCountAchievementRate: sum('orderCountAchievementRate'),
|
||||
targetAmount: sum('targetAmount'),
|
||||
salesAmountAchievementRate: sum('salesAmountAchievementRate'),
|
||||
salesAmount,
|
||||
dealAmount,
|
||||
refundAmount: sum('refundAmount'),
|
||||
refundOrderCount: sum('refundOrderCount'),
|
||||
refundQuantitySum: sum('refundQuantitySum'),
|
||||
salesOrderCount,
|
||||
dealOrderCount,
|
||||
dealQuantitySum: sum('dealQuantitySum'),
|
||||
salesQuantitySum: sum('salesQuantitySum'),
|
||||
salesAverageOrderValue,
|
||||
dealAverageOrderValue,
|
||||
productCost: sum('productCost'),
|
||||
shippingCost: sum('shippingCost'),
|
||||
otherCost: sum('otherCost'),
|
||||
orderCost: sum('orderCost'),
|
||||
totalPromotionFee,
|
||||
brushFee: sum('brushFee'),
|
||||
feeRatio,
|
||||
grossProfit: sum('grossProfit'),
|
||||
totalProfitBeforeTax: sum('totalProfitBeforeTax'),
|
||||
salesTaxAmount: sum('salesTaxAmount'),
|
||||
roi: totalPromotionFee ? salesAmount / totalPromotionFee : 0,
|
||||
profitAfterTax: sum('profitAfterTax'),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildPlatformOverviewFromDimRows(
|
||||
rows: WorkbenchVO.DimRow[],
|
||||
): CompanyOverviewVO.PlatformOverview {
|
||||
const platforms = rows.map(dimRowToPlatformSummary);
|
||||
return { total: aggregatePlatformTotal(platforms), platforms };
|
||||
}
|
||||
Reference in New Issue
Block a user