feat(order-stat,workbench): 订单统计日表扩展 GMV/销售单量件数并贯通刷新读写,工作台经营 KPI 扩至 22 项及前端展示配置

This commit is contained in:
小蟑螂
2026-06-03 20:51:26 +08:00
parent 28fba73928
commit b2a25a236f
23 changed files with 1192 additions and 455 deletions
+82 -40
View File
@@ -2,7 +2,7 @@
-- 订单统计读模型:日 / 月 / 年 聚合表设计 -- 订单统计读模型:日 / 月 / 年 聚合表设计
-- ============================================================================= -- =============================================================================
-- 目标:支撑 1 天~5 年(1825 天)区间查询与导出,避免在线扫 ec_order 明细。 -- 目标:支撑 1 天~5 年(1825 天)区间查询与导出,避免在线扫 ec_order 明细。
-- 口径:与 OrderStatusStatSets + OrderStatAggMapper 一致(五维度 + GMV + 件数)。 -- 口径:与 OrderStatusStatSets + OrderStatAggMapper 一致(成本/退款五维度 + KPI 双三角)。
-- 写入:ec_order 变更 / 导入完成后,按 (company, shop, stat_date) 重算日表,再 rollup 月/年。 -- 写入:ec_order 变更 / 导入完成后,按 (company, shop, stat_date) 重算日表,再 rollup 月/年。
-- 详细方案见:docs/订单统计读模型方案.md -- 详细方案见:docs/订单统计读模型方案.md
-- --
@@ -22,18 +22,31 @@
-- ----------------------------------------------------------------------------- -- -----------------------------------------------------------------------------
-- 一、公共指标列说明(日 / 月 / 年 三张同维度表字段一致,仅时间键不同) -- 一、公共指标列说明(日 / 月 / 年 同维度表字段一致,仅时间键 stat_date/stat_month/stat_year 不同)
-- ----------------------------------------------------------------------------- -- -----------------------------------------------------------------------------
-- sales_amount 计入销售额的 received_amount 合计(salesStatusIds) -- 【KPI · 实际销售口径】salesStatusIds(订单状态 includeSalesAmount=1)
-- refund_amount 计入退款的 received_amount 合计(refundStatusIds) -- sales_amount 实际销售额:SUM(received_amount)
-- sales_order_count 计入销售额的订单笔数 -- sales_order_count 实际销售单量:符合条件的订单笔数
-- product_cost 商品成本 × qty(productCostStatusIds) -- sales_quantity_sum 实际销量件数:SUM(qty),qty=IFNULL(NULLIF(quantity,0),1)
-- freight_cost 运费成本 × qty(freightCostStatusIds) --
-- other_cost 其他成本 × qty(otherCostStatusIds) -- 【KPI · GMV 口径】全订单状态(不按 status_id 过滤)
-- gmv_amount 全状态 received_amount 合计(仅 shop / spec 层需要 GMV 时保留) -- gmv_amount 总 GMV:SUM(received_amount)
-- gmv_order_count 全状态订单笔数(仅 shop 层) -- gmv_order_count GMV 单量:COUNT(*) 订单笔数
-- quantity_sum 销量件数合计(spec 层;qty = IFNULL(NULLIF(quantity,0),1)) -- gmv_quantity_sum GMV 销量件数:SUM(qty) 全状态
-- stat_version 重算批次号,状态配置 rebuild 时递增,便于排查 --
-- 【利润相关】仍按 OrderStatusStatSets 分维度
-- refund_amount 计入退款的 received_amount(refundStatusIds)
-- product_cost 商品成本 × qty(productCostStatusIds)
-- freight_cost 运费成本 × qty(freightCostStatusIds)
-- other_cost 其他成本 × qty(otherCostStatusIds)
--
-- 【各层落表范围】
-- 店铺 shop :KPI 双三角(6 列)+ 利润相关 → 工作台 KPI / 趋势主读
-- 商品 product:KPI 双三角(6 列)+ 利润相关 → 多维排行 / 品类商品表
-- 规格 spec :KPI 双三角(6 列)+ 利润相关 → 商品概览 spec 块
--
-- stat_version 重算批次号,状态配置 rebuild 时递增
-- 存量库升级见:migration/V20260607__ec_order_stat_kpi_quantity_columns.sql
-- ----------------------------------------------------------------------------- -- -----------------------------------------------------------------------------
@@ -49,14 +62,16 @@ CREATE TABLE `ec_order_stat_daily_shop` (
`platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(写入时快照 ec_shop.platform_id)', `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(写入时快照 ec_shop.platform_id)',
`stat_date` date NOT NULL COMMENT '自然日(Asia/Shanghai,与 order_time 的 DATE 一致)', `stat_date` date NOT NULL COMMENT '自然日(Asia/Shanghai,与 order_time 的 DATE 一致)',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV(全状态商家实收)',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV(全状态商家实收)',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数',
`stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -80,14 +95,16 @@ CREATE TABLE `ec_order_stat_monthly_shop` (
`platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(月 rollup 时取当月最后写入快照)', `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID(月 rollup 时取当月最后写入快照)',
`stat_month` date NOT NULL COMMENT '自然月首日,如 2024-03-01', `stat_month` date NOT NULL COMMENT '自然月首日,如 2024-03-01',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数',
`stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -110,14 +127,16 @@ CREATE TABLE `ec_order_stat_yearly_shop` (
`platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID', `platform_id` bigint UNSIGNED NULL DEFAULT NULL COMMENT '平台ID',
`stat_year` smallint NOT NULL COMMENT '自然年,如 2024', `stat_year` smallint NOT NULL COMMENT '自然年,如 2024',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT 'GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV 订单笔数',
`stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号', `stat_version` int NOT NULL DEFAULT 0 COMMENT '重算版本号',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
@@ -146,9 +165,13 @@ CREATE TABLE `ec_order_stat_daily_product` (
`category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID,0=未分类', `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID,0=未分类',
`stat_date` date NOT NULL COMMENT '自然日', `stat_date` date NOT NULL COMMENT '自然日',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -177,9 +200,13 @@ CREATE TABLE `ec_order_stat_monthly_product` (
`category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID',
`stat_month` date NOT NULL COMMENT '自然月首日', `stat_month` date NOT NULL COMMENT '自然月首日',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -207,9 +234,13 @@ CREATE TABLE `ec_order_stat_yearly_product` (
`category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID', `category_id` bigint NOT NULL DEFAULT 0 COMMENT '品类ID',
`stat_year` smallint NOT NULL COMMENT '自然年', `stat_year` smallint NOT NULL COMMENT '自然年',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -241,10 +272,13 @@ CREATE TABLE `ec_order_stat_daily_spec` (
`product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID,0=未绑定', `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID,0=未绑定',
`stat_date` date NOT NULL COMMENT '自然日', `stat_date` date NOT NULL COMMENT '自然日',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -271,10 +305,13 @@ CREATE TABLE `ec_order_stat_monthly_spec` (
`product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID',
`stat_month` date NOT NULL COMMENT '自然月首日', `stat_month` date NOT NULL COMMENT '自然月首日',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -300,10 +337,13 @@ CREATE TABLE `ec_order_stat_yearly_spec` (
`product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID', `product_spec_id` bigint UNSIGNED NOT NULL DEFAULT 0 COMMENT '规格ID',
`stat_year` smallint NOT NULL COMMENT '自然年', `stat_year` smallint NOT NULL COMMENT '自然年',
`sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '销售额', `sales_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '实际销售额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '实际销售单量',
`sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
`gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV',
`gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量',
`gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数',
`refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额', `refund_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '退款金额',
`sales_order_count` int NOT NULL DEFAULT 0 COMMENT '销售单量',
`quantity_sum` int NOT NULL DEFAULT 0 COMMENT '销量件数合计',
`product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本', `product_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '商品成本',
`freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本', `freight_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '运费成本',
`other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本', `other_cost` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '其他成本',
@@ -503,7 +543,9 @@ CREATE TABLE `ec_order_stat_refresh_queue` (
-- INSERT INTO ec_order_stat_monthly_shop (...) -- INSERT INTO ec_order_stat_monthly_shop (...)
-- SELECT company_id, shop_id, MAX(platform_id), -- SELECT company_id, shop_id, MAX(platform_id),
-- DATE_FORMAT(stat_date, '%Y-%m-01'), -- DATE_FORMAT(stat_date, '%Y-%m-01'),
-- SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), ... -- SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
-- SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
-- SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost)
-- FROM ec_order_stat_daily_shop -- FROM ec_order_stat_daily_shop
-- WHERE company_id=? AND shop_id=? AND stat_date BETWEEN ? AND ? -- WHERE company_id=? AND shop_id=? AND stat_date BETWEEN ? AND ?
-- GROUP BY company_id, shop_id, DATE_FORMAT(stat_date, '%Y-%m-01') -- GROUP BY company_id, shop_id, DATE_FORMAT(stat_date, '%Y-%m-01')
@@ -0,0 +1,57 @@
-- ================================================
-- 订单统计读模型:KPI 双三角指标列(实际销售 + GMV × 金额/单量/件数)
-- 设计说明见 sql/ec_order_stat_design.sql
-- 适用:已执行 V20260606 的存量库;新库若 V20260606 已含下列字段可跳过本脚本
-- 升级后需对受影响区间触发 rebuild / refresh 回填数据
-- ================================================
-- ---------- 店铺:补实际销量、GMV 销量 ----------
ALTER TABLE `ec_order_stat_daily_shop`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_monthly_shop`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_yearly_shop`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
-- ---------- 商品:补 KPI 双三角 ----------
ALTER TABLE `ec_order_stat_daily_product`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_monthly_product`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_yearly_product`
ADD COLUMN `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数' AFTER `sales_order_count`,
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
-- ---------- 规格:quantity_sum 更名为 sales_quantity_sum,并补 GMV 三角 ----------
ALTER TABLE `ec_order_stat_daily_spec`
CHANGE COLUMN `quantity_sum` `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_monthly_spec`
CHANGE COLUMN `quantity_sum` `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
ALTER TABLE `ec_order_stat_yearly_spec`
CHANGE COLUMN `quantity_sum` `sales_quantity_sum` int NOT NULL DEFAULT 0 COMMENT '实际销量件数',
ADD COLUMN `gmv_amount` decimal(16, 2) NOT NULL DEFAULT 0.00 COMMENT '总GMV' AFTER `sales_quantity_sum`,
ADD COLUMN `gmv_order_count` int NOT NULL DEFAULT 0 COMMENT 'GMV单量' AFTER `gmv_amount`,
ADD COLUMN `gmv_quantity_sum` int NOT NULL DEFAULT 0 COMMENT 'GMV销量件数' AFTER `gmv_order_count`;
@@ -110,11 +110,14 @@ public interface OrderStatAggMapper {
private Long categoryId; private Long categoryId;
private BigDecimal salesAmount; private BigDecimal salesAmount;
private Long orderCount; private Long orderCount;
private Long salesQuantitySum;
private BigDecimal refundAmount; private BigDecimal refundAmount;
private BigDecimal productCost; private BigDecimal productCost;
private BigDecimal freightCost; private BigDecimal freightCost;
private BigDecimal otherCost; private BigDecimal otherCost;
private BigDecimal gmvAllStatus; private BigDecimal gmvAllStatus;
private Long gmvOrderCount;
private Long gmvQuantitySum;
} }
@Data @Data
@@ -52,7 +52,10 @@ public interface OrderStatRefreshMapper extends BaseMapper<OrderStatRefreshQueue
private BigDecimal salesAmount; private BigDecimal salesAmount;
private Long orderCount; private Long orderCount;
private BigDecimal refundAmount; private BigDecimal refundAmount;
private Integer quantitySum; private Integer salesQuantitySum;
private BigDecimal gmvAmount;
private Long gmvOrderCount;
private Integer gmvQuantitySum;
private BigDecimal productCost; private BigDecimal productCost;
private BigDecimal freightCost; private BigDecimal freightCost;
private BigDecimal otherCost; private BigDecimal otherCost;
@@ -21,12 +21,15 @@ public class OrderStatMetricsDTO {
private BigDecimal salesAmount = BigDecimal.ZERO; private BigDecimal salesAmount = BigDecimal.ZERO;
private BigDecimal refundAmount = BigDecimal.ZERO; private BigDecimal refundAmount = BigDecimal.ZERO;
private Integer salesOrderCount = 0; private Integer salesOrderCount = 0;
/** 实际销量件数(sales_quantity_sum) */
private Integer salesQuantitySum = 0;
private BigDecimal productCost = BigDecimal.ZERO; private BigDecimal productCost = BigDecimal.ZERO;
private BigDecimal freightCost = BigDecimal.ZERO; private BigDecimal freightCost = BigDecimal.ZERO;
private BigDecimal otherCost = BigDecimal.ZERO; private BigDecimal otherCost = BigDecimal.ZERO;
private BigDecimal gmvAmount = BigDecimal.ZERO; private BigDecimal gmvAmount = BigDecimal.ZERO;
private Integer gmvOrderCount = 0; private Integer gmvOrderCount = 0;
private Integer quantitySum = 0; /** GMV 销量件数(gmv_quantity_sum) */
private Integer gmvQuantitySum = 0;
/** 订单成本合计 */ /** 订单成本合计 */
public BigDecimal getOrderCost() { public BigDecimal getOrderCost() {
@@ -42,6 +42,18 @@ public class OrderStatDailyProductPO {
@TableField("sales_order_count") @TableField("sales_order_count")
private Integer salesOrderCount; private Integer salesOrderCount;
@TableField("sales_quantity_sum")
private Integer salesQuantitySum;
@TableField("gmv_amount")
private BigDecimal gmvAmount;
@TableField("gmv_order_count")
private Integer gmvOrderCount;
@TableField("gmv_quantity_sum")
private Integer gmvQuantitySum;
@TableField("product_cost") @TableField("product_cost")
private BigDecimal productCost; private BigDecimal productCost;
@@ -39,6 +39,9 @@ public class OrderStatDailyShopPO {
@TableField("sales_order_count") @TableField("sales_order_count")
private Integer salesOrderCount; private Integer salesOrderCount;
@TableField("sales_quantity_sum")
private Integer salesQuantitySum;
@TableField("product_cost") @TableField("product_cost")
private BigDecimal productCost; private BigDecimal productCost;
@@ -54,6 +57,9 @@ public class OrderStatDailyShopPO {
@TableField("gmv_order_count") @TableField("gmv_order_count")
private Integer gmvOrderCount; private Integer gmvOrderCount;
@TableField("gmv_quantity_sum")
private Integer gmvQuantitySum;
@TableField("stat_version") @TableField("stat_version")
private Integer statVersion; private Integer statVersion;
@@ -42,8 +42,17 @@ public class OrderStatDailySpecPO {
@TableField("sales_order_count") @TableField("sales_order_count")
private Integer salesOrderCount; private Integer salesOrderCount;
@TableField("quantity_sum") @TableField("sales_quantity_sum")
private Integer quantitySum; private Integer salesQuantitySum;
@TableField("gmv_amount")
private BigDecimal gmvAmount;
@TableField("gmv_order_count")
private Integer gmvOrderCount;
@TableField("gmv_quantity_sum")
private Integer gmvQuantitySum;
@TableField("product_cost") @TableField("product_cost")
private BigDecimal productCost; private BigDecimal productCost;
@@ -6,6 +6,7 @@ import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.config.OrderStatPropert
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.mapper.OrderStatQueryMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO; import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper; import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.support.OrderStatParamHelper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO; import top.xyquan.ecomdmbbackend.modules.ecom.shop.model.po.ShopPO;
import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService; import top.xyquan.ecomdmbbackend.modules.ecom.shop.service.ShopService;
@@ -29,17 +30,20 @@ public class OrderStatReadFacade {
private final OrderStatQueryService orderStatQueryService; private final OrderStatQueryService orderStatQueryService;
private final OrderStatQueryMapper orderStatQueryMapper; private final OrderStatQueryMapper orderStatQueryMapper;
private final OrderStatAggMapper orderStatAggMapper; private final OrderStatAggMapper orderStatAggMapper;
private final OrderStatusStatResolver orderStatusStatResolver;
private final ShopService shopService; private final ShopService shopService;
public OrderStatReadFacade(OrderStatProperties properties, public OrderStatReadFacade(OrderStatProperties properties,
OrderStatQueryService orderStatQueryService, OrderStatQueryService orderStatQueryService,
OrderStatQueryMapper orderStatQueryMapper, OrderStatQueryMapper orderStatQueryMapper,
OrderStatAggMapper orderStatAggMapper, OrderStatAggMapper orderStatAggMapper,
OrderStatusStatResolver orderStatusStatResolver,
ShopService shopService) { ShopService shopService) {
this.properties = properties; this.properties = properties;
this.orderStatQueryService = orderStatQueryService; this.orderStatQueryService = orderStatQueryService;
this.orderStatQueryMapper = orderStatQueryMapper; this.orderStatQueryMapper = orderStatQueryMapper;
this.orderStatAggMapper = orderStatAggMapper; this.orderStatAggMapper = orderStatAggMapper;
this.orderStatusStatResolver = orderStatusStatResolver;
this.shopService = shopService; this.shopService = shopService;
} }
@@ -75,10 +79,13 @@ public class OrderStatReadFacade {
r.setSalesAmount(m.getSalesAmount()); r.setSalesAmount(m.getSalesAmount());
r.setRefundAmount(m.getRefundAmount()); r.setRefundAmount(m.getRefundAmount());
r.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L); r.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount().longValue() : 0L);
r.setSalesQuantitySum(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum().longValue() : 0L);
r.setProductCost(m.getProductCost()); r.setProductCost(m.getProductCost());
r.setFreightCost(m.getFreightCost()); r.setFreightCost(m.getFreightCost());
r.setOtherCost(m.getOtherCost()); r.setOtherCost(m.getOtherCost());
r.setGmvAllStatus(BigDecimal.ZERO); r.setGmvAllStatus(nz(m.getGmvAmount()));
r.setGmvOrderCount(m.getGmvOrderCount() != null ? m.getGmvOrderCount().longValue() : 0L);
r.setGmvQuantitySum(m.getGmvQuantitySum() != null ? m.getGmvQuantitySum().longValue() : 0L);
out.add(r); out.add(r);
} }
return out; return out;
@@ -143,23 +150,35 @@ public class OrderStatReadFacade {
public OrderStatMetricsDTO sumShopMetrics(Long companyId, List<Long> shopIds, public OrderStatMetricsDTO sumShopMetrics(Long companyId, List<Long> shopIds,
LocalDate startDate, LocalDate endDate) { LocalDate startDate, LocalDate endDate) {
if (!usesDailyStatSource()) { if (!usesDailyStatSource()) {
OrderStatusStatSets stat = OrderStatusStatSets.from(List.of()); OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
List<OrderStatAggMapper.ShopProductRow> rows = loadShopProductRows(companyId, shopIds, startDate, endDate, stat); List<OrderStatAggMapper.ShopProductRow> rows = orderStatAggMapper.aggregateByShopProduct(
companyId, shopIds, startDate.atStartOfDay(), endDate.atTime(23, 59, 59),
OrderStatParamHelper.unionList(stat), OrderStatParamHelper.salesList(stat),
OrderStatParamHelper.refundList(stat), OrderStatParamHelper.productCostList(stat),
OrderStatParamHelper.freightCostList(stat), OrderStatParamHelper.otherCostList(stat));
OrderStatMetricsDTO dto = new OrderStatMetricsDTO(); OrderStatMetricsDTO dto = new OrderStatMetricsDTO();
BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO; BigDecimal sales = BigDecimal.ZERO, refund = BigDecimal.ZERO, gmv = BigDecimal.ZERO;
BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO; BigDecimal pc = BigDecimal.ZERO, fc = BigDecimal.ZERO, oc = BigDecimal.ZERO;
int cnt = 0; int cnt = 0, salesQty = 0, gmvCnt = 0, gmvQty = 0;
for (OrderStatAggMapper.ShopProductRow r : rows) { for (OrderStatAggMapper.ShopProductRow r : rows) {
sales = sales.add(nz(r.getSalesAmount())); sales = sales.add(nz(r.getSalesAmount()));
refund = refund.add(nz(r.getRefundAmount())); refund = refund.add(nz(r.getRefundAmount()));
gmv = gmv.add(nz(r.getGmvAllStatus()));
pc = pc.add(nz(r.getProductCost())); pc = pc.add(nz(r.getProductCost()));
fc = fc.add(nz(r.getFreightCost())); fc = fc.add(nz(r.getFreightCost()));
oc = oc.add(nz(r.getOtherCost())); oc = oc.add(nz(r.getOtherCost()));
cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; cnt += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0;
salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0;
gmvCnt += r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0;
gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0;
} }
dto.setSalesAmount(sales); dto.setSalesAmount(sales);
dto.setRefundAmount(refund); dto.setRefundAmount(refund);
dto.setSalesOrderCount(cnt); dto.setSalesOrderCount(cnt);
dto.setSalesQuantitySum(salesQty);
dto.setGmvAmount(gmv);
dto.setGmvOrderCount(gmvCnt);
dto.setGmvQuantitySum(gmvQty);
dto.setProductCost(pc); dto.setProductCost(pc);
dto.setFreightCost(fc); dto.setFreightCost(fc);
dto.setOtherCost(oc); dto.setOtherCost(oc);
@@ -118,11 +118,13 @@ public class OrderStatRefreshService {
row.setSalesAmount(BigDecimal.ZERO); row.setSalesAmount(BigDecimal.ZERO);
row.setRefundAmount(BigDecimal.ZERO); row.setRefundAmount(BigDecimal.ZERO);
row.setSalesOrderCount(0); row.setSalesOrderCount(0);
row.setSalesQuantitySum(0);
row.setProductCost(BigDecimal.ZERO); row.setProductCost(BigDecimal.ZERO);
row.setFreightCost(BigDecimal.ZERO); row.setFreightCost(BigDecimal.ZERO);
row.setOtherCost(BigDecimal.ZERO); row.setOtherCost(BigDecimal.ZERO);
row.setGmvAmount(BigDecimal.ZERO); row.setGmvAmount(BigDecimal.ZERO);
row.setGmvOrderCount(0); row.setGmvOrderCount(0);
row.setGmvQuantitySum(0);
row.setStatVersion(0); row.setStatVersion(0);
orderStatDailyMapper.upsertDailyShop(row); orderStatDailyMapper.upsertDailyShop(row);
} }
@@ -138,6 +140,8 @@ public class OrderStatRefreshService {
BigDecimal oc = BigDecimal.ZERO; BigDecimal oc = BigDecimal.ZERO;
BigDecimal gmv = BigDecimal.ZERO; BigDecimal gmv = BigDecimal.ZERO;
int orderCount = 0; int orderCount = 0;
int salesQty = 0;
int gmvQty = 0;
for (OrderStatAggMapper.ShopProductRow r : rows) { for (OrderStatAggMapper.ShopProductRow r : rows) {
sales = sales.add(nz(r.getSalesAmount())); sales = sales.add(nz(r.getSalesAmount()));
refund = refund.add(nz(r.getRefundAmount())); refund = refund.add(nz(r.getRefundAmount()));
@@ -146,6 +150,8 @@ public class OrderStatRefreshService {
oc = oc.add(nz(r.getOtherCost())); oc = oc.add(nz(r.getOtherCost()));
gmv = gmv.add(nz(r.getGmvAllStatus())); gmv = gmv.add(nz(r.getGmvAllStatus()));
orderCount += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0; orderCount += r.getOrderCount() != null ? r.getOrderCount().intValue() : 0;
salesQty += r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0;
gmvQty += r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0;
} }
OrderStatDailyShopPO row = new OrderStatDailyShopPO(); OrderStatDailyShopPO row = new OrderStatDailyShopPO();
row.setCompanyId(companyId); row.setCompanyId(companyId);
@@ -155,11 +161,13 @@ public class OrderStatRefreshService {
row.setSalesAmount(sales); row.setSalesAmount(sales);
row.setRefundAmount(refund); row.setRefundAmount(refund);
row.setSalesOrderCount(orderCount); row.setSalesOrderCount(orderCount);
row.setSalesQuantitySum(salesQty);
row.setProductCost(pc); row.setProductCost(pc);
row.setFreightCost(fc); row.setFreightCost(fc);
row.setOtherCost(oc); row.setOtherCost(oc);
row.setGmvAmount(gmv); row.setGmvAmount(gmv);
row.setGmvOrderCount(gmvOrderCount); row.setGmvOrderCount(gmvOrderCount);
row.setGmvQuantitySum(gmvQty);
row.setStatVersion(0); row.setStatVersion(0);
return row; return row;
} }
@@ -180,6 +188,10 @@ public class OrderStatRefreshService {
p.setSalesAmount(nz(r.getSalesAmount())); p.setSalesAmount(nz(r.getSalesAmount()));
p.setRefundAmount(nz(r.getRefundAmount())); p.setRefundAmount(nz(r.getRefundAmount()));
p.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); p.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0);
p.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum().intValue() : 0);
p.setGmvAmount(nz(r.getGmvAllStatus()));
p.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0);
p.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum().intValue() : 0);
p.setProductCost(nz(r.getProductCost())); p.setProductCost(nz(r.getProductCost()));
p.setFreightCost(nz(r.getFreightCost())); p.setFreightCost(nz(r.getFreightCost()));
p.setOtherCost(nz(r.getOtherCost())); p.setOtherCost(nz(r.getOtherCost()));
@@ -205,7 +217,10 @@ public class OrderStatRefreshService {
s.setSalesAmount(nz(r.getSalesAmount())); s.setSalesAmount(nz(r.getSalesAmount()));
s.setRefundAmount(nz(r.getRefundAmount())); s.setRefundAmount(nz(r.getRefundAmount()));
s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0); s.setSalesOrderCount(r.getOrderCount() != null ? r.getOrderCount().intValue() : 0);
s.setQuantitySum(r.getQuantitySum() != null ? r.getQuantitySum() : 0); s.setSalesQuantitySum(r.getSalesQuantitySum() != null ? r.getSalesQuantitySum() : 0);
s.setGmvAmount(nz(r.getGmvAmount()));
s.setGmvOrderCount(r.getGmvOrderCount() != null ? r.getGmvOrderCount().intValue() : 0);
s.setGmvQuantitySum(r.getGmvQuantitySum() != null ? r.getGmvQuantitySum() : 0);
s.setProductCost(nz(r.getProductCost())); s.setProductCost(nz(r.getProductCost()));
s.setFreightCost(nz(r.getFreightCost())); s.setFreightCost(nz(r.getFreightCost()));
s.setOtherCost(nz(r.getOtherCost())); s.setOtherCost(nz(r.getOtherCost()));
@@ -218,13 +233,17 @@ public class OrderStatRefreshService {
private static boolean isAllZeroProductRow(OrderStatAggMapper.ShopProductRow r) { private static boolean isAllZeroProductRow(OrderStatAggMapper.ShopProductRow r) {
return nz(r.getSalesAmount()).signum() == 0 return nz(r.getSalesAmount()).signum() == 0
&& nz(r.getRefundAmount()).signum() == 0 && nz(r.getRefundAmount()).signum() == 0
&& (r.getOrderCount() == null || r.getOrderCount() == 0); && nz(r.getGmvAllStatus()).signum() == 0
&& (r.getOrderCount() == null || r.getOrderCount() == 0)
&& (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0);
} }
private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) { private static boolean isAllZeroSpecRow(OrderStatRefreshMapper.SpecDayRow r) {
return nz(r.getSalesAmount()).signum() == 0 return nz(r.getSalesAmount()).signum() == 0
&& nz(r.getRefundAmount()).signum() == 0 && nz(r.getRefundAmount()).signum() == 0
&& (r.getOrderCount() == null || r.getOrderCount() == 0); && nz(r.getGmvAmount()).signum() == 0
&& (r.getOrderCount() == null || r.getOrderCount() == 0)
&& (r.getGmvOrderCount() == null || r.getGmvOrderCount() == 0);
} }
private static BigDecimal nz(BigDecimal v) { private static BigDecimal nz(BigDecimal v) {
@@ -981,7 +981,7 @@ public class ProductOverviewServiceImpl implements ProductOverviewService {
item.setSpecCode(spec != null ? spec.getSpecCode() : null); item.setSpecCode(spec != null ? spec.getSpecCode() : null);
item.setSalesAmount(sales); item.setSalesAmount(sales);
item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0); item.setOrderCount(m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0);
item.setQuantity(m.getQuantitySum() != null ? m.getQuantitySum() : 0); item.setQuantity(m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0);
item.setProductCost(nz(m.getProductCost())); item.setProductCost(nz(m.getProductCost()));
item.setShippingCost(nz(m.getFreightCost())); item.setShippingCost(nz(m.getFreightCost()));
item.setOtherCost(nz(m.getOtherCost())); item.setOtherCost(nz(m.getOtherCost()));
@@ -6,6 +6,7 @@ import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO; import top.xyquan.ecomdmbbackend.modules.ecom.category.model.po.CategoryPO;
import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService; import top.xyquan.ecomdmbbackend.modules.ecom.category.service.CategoryService;
import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper; import top.xyquan.ecomdmbbackend.modules.ecom.order.mapper.OrderStatAggMapper;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO;
import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade; import top.xyquan.ecomdmbbackend.modules.ecom.order.stat.service.OrderStatReadFacade;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatResolver;
import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets; import top.xyquan.ecomdmbbackend.modules.ecom.order.status.support.OrderStatusStatSets;
@@ -107,7 +108,8 @@ public class WorkbenchServiceImpl implements WorkbenchService {
SqlAggBundle agg = loadSqlAgg(ctx); SqlAggBundle agg = loadSqlAgg(ctx);
ComparePeriodBundle compare = loadCompareFromSql(ctx); ComparePeriodBundle compare = loadCompareFromSql(ctx);
Totals cur = totalsFromOrderRows(agg.orderRows(), agg.promoTotal(), agg.brushTotal(), ctx.taxRate()); // 店铺日汇总表口径:含 GMV/销售双三角 + 成本;推广/刷单仍用区间聚合
Totals cur = buildShopPeriodTotals(ctx, ctx.range(), agg.promoTotal(), agg.brushTotal());
WorkbenchFinancePanelVO finance = buildFinancePanelFromSql(ctx, cur, compare, agg); WorkbenchFinancePanelVO finance = buildFinancePanelFromSql(ctx, cur, compare, agg);
@@ -220,18 +222,11 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows); return new SqlAggBundle(orderRows, dailyRows, promotionRows, brushRows);
} }
/** SQL-3 + 推广/刷单三段时间 KPI */ /** 环比/同比:店铺汇总表 + 各段推广/刷单 */
private ComparePeriodBundle loadCompareFromSql(ShopContext ctx) { private ComparePeriodBundle loadCompareFromSql(ShopContext ctx) {
OrderStatusStatSets stat = ctx.stat();
DateRange lastRange = lastMonthSameSpan(ctx.range()); DateRange lastRange = lastMonthSameSpan(ctx.range());
DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1)); DateRange yoyRange = new DateRange(ctx.range().startDate().minusYears(1), ctx.range().endDate().minusYears(1));
OrderStatAggMapper.PeriodKpiRow orderKpi = orderStatReadFacade.loadPeriodKpi(
ctx.companyId(), ctx.shopIds(),
ctx.range().startDate(), ctx.range().endDate(),
lastRange.startDate(), lastRange.endDate(),
yoyRange.startDate(), yoyRange.endDate(), stat);
LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate()); LocalDate feeScanStart = minDate(lastRange.startDate(), yoyRange.startDate(), ctx.range().startDate());
LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate()); LocalDate feeScanEnd = maxDate(lastRange.endDate(), yoyRange.endDate(), ctx.range().endDate());
OrderStatAggMapper.FeeKpiRow promoKpi = orderStatReadFacade.loadPromotionPeriodKpi( OrderStatAggMapper.FeeKpiRow promoKpi = orderStatReadFacade.loadPromotionPeriodKpi(
@@ -247,10 +242,24 @@ public class WorkbenchServiceImpl implements WorkbenchService {
lastRange.startDateTime(), lastRange.endDateTime(), lastRange.startDateTime(), lastRange.endDateTime(),
yoyRange.startDateTime(), yoyRange.endDateTime()); yoyRange.startDateTime(), yoyRange.endDateTime());
return new ComparePeriodBundle(lastRange, yoyRange, Totals prev = buildShopPeriodTotals(ctx, lastRange, nz(promoKpi.getPrevAmount()), nz(brushKpi.getPrevAmount()));
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.PREV, ctx.taxRate()), Totals yoy = buildShopPeriodTotals(ctx, yoyRange, nz(promoKpi.getYoyAmount()), nz(brushKpi.getYoyAmount()));
totalsFromPeriodKpi(orderKpi, promoKpi, brushKpi, PeriodSlice.YOY, ctx.taxRate()), return new ComparePeriodBundle(lastRange, yoyRange, prev, yoy);
nz(orderKpi.getCurGmvAllStatus()), nz(orderKpi.getPrevGmvAllStatus()), nz(orderKpi.getYoyGmvAllStatus())); }
/** 单时间段店铺 KPI:读 ec_order_stat_daily_shop 合计 */
private Totals buildShopPeriodTotals(ShopContext ctx, DateRange range, BigDecimal promotion, BigDecimal brush) {
OrderStatMetricsDTO m = orderStatReadFacade.sumShopMetrics(
ctx.companyId(), ctx.shopIds(), range.startDate(), range.endDate());
return buildTotals(
nz(m.getSalesAmount()), nz(m.getRefundAmount()),
nz(m.getProductCost()), nz(m.getFreightCost()), nz(m.getOtherCost()),
promotion, brush, ctx.taxRate(),
m.getSalesOrderCount() != null ? m.getSalesOrderCount() : 0,
m.getSalesQuantitySum() != null ? m.getSalesQuantitySum() : 0,
nz(m.getGmvAmount()),
m.getGmvOrderCount() != null ? m.getGmvOrderCount() : 0,
m.getGmvQuantitySum() != null ? m.getGmvQuantitySum() : 0);
} }
private WorkbenchFinancePanelVO buildFinancePanelFromSql(ShopContext ctx, Totals cur, private WorkbenchFinancePanelVO buildFinancePanelFromSql(ShopContext ctx, Totals cur,
@@ -261,8 +270,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
platformAgg.computeIfAbsent(String.valueOf(pk), k -> new Agg()).addFromAggRow(row); platformAgg.computeIfAbsent(String.valueOf(pk), k -> new Agg()).addFromAggRow(row);
} }
return WorkbenchFinancePanelVO.builder() return WorkbenchFinancePanelVO.builder()
.kpis(buildKpis(cur, compare.prev(), compare.yoy(), ctx.range(), ctx.taxRate(), .kpis(buildKpis(cur, compare.prev(), compare.yoy(), ctx.range(), ctx.taxRate()))
compare.totalGmvCur(), compare.totalGmvPrev(), compare.totalGmvYoy()))
.gmvTrend(buildTrendFromDaily(agg.dailyRows(), ctx.range(), cur)) .gmvTrend(buildTrendFromDaily(agg.dailyRows(), ctx.range(), cur))
.platformSalesShare(buildPlatformSalesSlices(platformAgg, loadPlatformNames(ctx.shops()), cur.totalSales())) .platformSalesShare(buildPlatformSalesSlices(platformAgg, loadPlatformNames(ctx.shops()), cur.totalSales()))
.momCompareDateStart(compare.lastRange().startDate().toString()) .momCompareDateStart(compare.lastRange().startDate().toString())
@@ -316,35 +324,29 @@ public class WorkbenchServiceImpl implements WorkbenchService {
oc = oc.add(nz(row.getOtherCost())); oc = oc.add(nz(row.getOtherCost()));
orderCount += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0; orderCount += row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
} }
return buildTotals(sales, refund, pc, fc, oc, promotion, brush, taxRate, orderCount); return buildTotals(sales, refund, pc, fc, oc, promotion, brush, taxRate, orderCount, 0,
} BigDecimal.ZERO, 0, 0);
private Totals totalsFromPeriodKpi(OrderStatAggMapper.PeriodKpiRow o, OrderStatAggMapper.FeeKpiRow promo,
OrderStatAggMapper.FeeKpiRow brush, PeriodSlice slice, BigDecimal taxRate) {
return switch (slice) {
case CUR -> buildTotals(nz(o.getCurSalesAmount()), nz(o.getCurRefundAmount()),
nz(o.getCurProductCost()), nz(o.getCurFreightCost()), nz(o.getCurOtherCost()),
nz(promo.getCurAmount()), nz(brush.getCurAmount()), taxRate,
o.getCurOrderCount() != null ? o.getCurOrderCount().intValue() : 0);
case PREV -> buildTotals(nz(o.getPrevSalesAmount()), nz(o.getPrevRefundAmount()),
nz(o.getPrevProductCost()), nz(o.getPrevFreightCost()), nz(o.getPrevOtherCost()),
nz(promo.getPrevAmount()), nz(brush.getPrevAmount()), taxRate,
o.getPrevOrderCount() != null ? o.getPrevOrderCount().intValue() : 0);
case YOY -> buildTotals(nz(o.getYoySalesAmount()), nz(o.getYoyRefundAmount()),
nz(o.getYoyProductCost()), nz(o.getYoyFreightCost()), nz(o.getYoyOtherCost()),
nz(promo.getYoyAmount()), nz(brush.getYoyAmount()), taxRate,
o.getYoyOrderCount() != null ? o.getYoyOrderCount().intValue() : 0);
};
} }
private Totals buildTotals(BigDecimal sales, BigDecimal refund, BigDecimal pc, BigDecimal fc, BigDecimal oc, private Totals buildTotals(BigDecimal sales, BigDecimal refund, BigDecimal pc, BigDecimal fc, BigDecimal oc,
BigDecimal promotion, BigDecimal brush, BigDecimal taxRate, int orderCount) { BigDecimal promotion, BigDecimal brush, BigDecimal taxRate,
int orderCount, int salesQuantitySum,
BigDecimal totalGmv, int gmvOrderCount, int gmvQuantitySum) {
BigDecimal cost = pc.add(fc).add(oc); BigDecimal cost = pc.add(fc).add(oc);
BigDecimal gross = sales.subtract(cost).subtract(refund); BigDecimal gross = sales.subtract(cost).subtract(refund);
BigDecimal pbt = gross.subtract(promotion).subtract(brush); BigDecimal pbt = gross.subtract(promotion).subtract(brush);
BigDecimal tax = salesTaxOnNetSales(sales, refund, taxRate); BigDecimal tax = salesTaxOnNetSales(sales, refund, taxRate);
BigDecimal aov = orderCount > 0 ? sales.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO; BigDecimal aov = orderCount > 0
return new Totals(sales, refund, cost, pc, fc, oc, promotion, brush, tax, gross, pbt.subtract(tax), orderCount, aov); ? sales.divide(BigDecimal.valueOf(orderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal gmvAov = gmvOrderCount > 0
? totalGmv.divide(BigDecimal.valueOf(gmvOrderCount), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal salesPiecePrice = salesQuantitySum > 0
? sales.divide(BigDecimal.valueOf(salesQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal gmvPiecePrice = gmvQuantitySum > 0
? totalGmv.divide(BigDecimal.valueOf(gmvQuantitySum), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
return new Totals(sales, refund, cost, pc, fc, oc, promotion, brush, tax, gross, pbt.subtract(tax),
orderCount, salesQuantitySum, totalGmv, gmvOrderCount, gmvQuantitySum,
aov, gmvAov, salesPiecePrice, gmvPiecePrice);
} }
private List<WorkbenchTrendPointVO> buildTrendFromDaily(List<OrderStatAggMapper.DailyRow> dailyRows, private List<WorkbenchTrendPointVO> buildTrendFromDaily(List<OrderStatAggMapper.DailyRow> dailyRows,
@@ -444,8 +446,6 @@ public class WorkbenchServiceImpl implements WorkbenchService {
return v != null ? v : BigDecimal.ZERO; return v != null ? v : BigDecimal.ZERO;
} }
private enum PeriodSlice { CUR, PREV, YOY }
private record SqlAggBundle(List<OrderStatAggMapper.ShopProductRow> orderRows, private record SqlAggBundle(List<OrderStatAggMapper.ShopProductRow> orderRows,
List<OrderStatAggMapper.DailyRow> dailyRows, List<OrderStatAggMapper.DailyRow> dailyRows,
List<OrderStatAggMapper.PromotionRow> promotionRows, List<OrderStatAggMapper.PromotionRow> promotionRows,
@@ -661,67 +661,112 @@ public class WorkbenchServiceImpl implements WorkbenchService {
} }
/** /**
* 组装财务区 KPI 卡片:总 GMV(全状态)、实际销售额、毛利、净利、订单量、客单价、退款率、广告 ROI; * 经营概览 KPI 卡片:GMV 三角、实际销售三角、净收/退款、成本分项、利润费用、运营效率等。
* 环比用 {@code prev},同比用 {@code yoy};副文案中带毛利率、净利率、税率等说明。
*/ */
private List<WorkbenchKpiItemVO> buildKpis(Totals cur, Totals prev, Totals yoy, DateRange range, BigDecimal taxRate, private List<WorkbenchKpiItemVO> buildKpis(Totals cur, Totals prev, Totals yoy, DateRange range, BigDecimal taxRate) {
BigDecimal totalGmvCur, BigDecimal totalGmvPrev, BigDecimal totalGmvYoy) {
int days = (int) (range.endDate().toEpochDay() - range.startDate().toEpochDay() + 1); int days = (int) (range.endDate().toEpochDay() - range.startDate().toEpochDay() + 1);
DecimalFormat df = new DecimalFormat("#,###", DecimalFormatSymbols.getInstance(Locale.CHINA)); DecimalFormat df = new DecimalFormat("#,###", DecimalFormatSymbols.getInstance(Locale.CHINA));
BigDecimal netRecv = cur.totalSales().subtract(cur.totalRefund()); BigDecimal netRecv = cur.netSales();
BigDecimal grossMarginPct = safePct(cur.grossOrder(), cur.totalSales()); BigDecimal grossMarginPct = safePct(cur.grossOrder(), cur.totalSales());
BigDecimal netMarginPct = safePct(cur.netProfit(), cur.totalSales()); BigDecimal netMarginPct = safePct(cur.netProfit(), cur.totalSales());
BigDecimal refundRate = safePct(cur.totalRefund(), cur.totalSales()); BigDecimal refundRate = safePct(cur.totalRefund(), cur.totalSales());
BigDecimal costRate = safePct(cur.totalCost(), cur.totalSales());
BigDecimal roi = cur.promotion().compareTo(BigDecimal.ZERO) > 0 BigDecimal roi = cur.promotion().compareTo(BigDecimal.ZERO) > 0
? netRecv.divide(cur.promotion(), 2, RoundingMode.HALF_UP) ? netRecv.divide(cur.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
: BigDecimal.ZERO;
BigDecimal yoyNetRecv = yoy.totalSales().subtract(yoy.totalRefund());
BigDecimal yoyRoi = yoy.promotion().compareTo(BigDecimal.ZERO) > 0 BigDecimal yoyRoi = yoy.promotion().compareTo(BigDecimal.ZERO) > 0
? yoyNetRecv.divide(yoy.promotion(), 2, RoundingMode.HALF_UP) ? yoy.netSales().divide(yoy.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
: BigDecimal.ZERO; BigDecimal prevRoi = prev.promotion().compareTo(BigDecimal.ZERO) > 0
? prev.netSales().divide(prev.promotion(), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
BigDecimal avgDaily = days > 0 BigDecimal avgDailySalesOrders = days > 0
? BigDecimal.valueOf(cur.orderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP) ? BigDecimal.valueOf(cur.orderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP)
: BigDecimal.ZERO; : BigDecimal.ZERO;
BigDecimal avgDailyGmvOrders = days > 0
BigDecimal yoyRefundRate = safePct(yoy.totalRefund(), yoy.totalSales()); ? BigDecimal.valueOf(cur.gmvOrderCount()).divide(BigDecimal.valueOf(days), 1, RoundingMode.HALF_UP)
: BigDecimal.ZERO;
BigDecimal gmvSalesGap = cur.totalGmv().subtract(cur.totalSales());
List<WorkbenchKpiItemVO> list = new ArrayList<>(); List<WorkbenchKpiItemVO> list = new ArrayList<>();
list.add(kpi("总GMV", formatYuanComma(totalGmvCur), "元", totalGmvCur, totalGmvPrev, totalGmvYoy,
"全部订单状态商家实收合计", // —— GMV 口径(全状态)——
totalGmvCur, true)); list.add(kpi("总GMV", formatYuanComma(cur.totalGmv()), "元", cur.totalGmv(), prev.totalGmv(), yoy.totalGmv(),
"全状态商家实收", cur.totalGmv(), true));
list.add(kpiCount("GMV单量", cur.gmvOrderCount(), prev.gmvOrderCount(), yoy.gmvOrderCount(), "单",
"日均约 " + avgDailyGmvOrders.stripTrailingZeros().toPlainString() + " 单"));
list.add(kpiCount("GMV销量", cur.gmvQuantitySum(), prev.gmvQuantitySum(), yoy.gmvQuantitySum(), "件", "全状态件数合计"));
list.add(kpi("GMV客单价", formatYuanComma(cur.gmvAverageOrderValue()), "元",
cur.gmvAverageOrderValue(), prev.gmvAverageOrderValue(), yoy.gmvAverageOrderValue(),
"GMV÷GMV单量", cur.gmvAverageOrderValue(), false));
list.add(kpi("GMV件单价", formatYuanComma(cur.gmvPiecePrice()), "元",
cur.gmvPiecePrice(), prev.gmvPiecePrice(), yoy.gmvPiecePrice(),
"GMV÷GMV销量", cur.gmvPiecePrice(), false));
// —— 实际销售口径(计入销售额状态)——
list.add(kpi("实际销售额", formatYuanComma(cur.totalSales()), "元", cur.totalSales(), prev.totalSales(), yoy.totalSales(), list.add(kpi("实际销售额", formatYuanComma(cur.totalSales()), "元", cur.totalSales(), prev.totalSales(), yoy.totalSales(),
"退款 " + formatYuanComma(cur.totalRefund()) + " 元 · 计入销售额的订单状态口径", "计入销售额的订单状态", cur.totalSales(), true));
cur.totalSales(), true)); list.add(kpiCount("销售单量", cur.orderCount(), prev.orderCount(), yoy.orderCount(), "单",
list.add(kpi("毛利润", formatYuanComma(cur.grossOrder()), "元", cur.grossOrder(), prev.grossOrder(), yoy.grossOrder(), "日均约 " + avgDailySalesOrders.stripTrailingZeros().toPlainString() + " 单"));
"毛利率 " + grossMarginPct.stripTrailingZeros().toPlainString() + "%", list.add(kpiCount("实际销量", cur.salesQuantitySum(), prev.salesQuantitySum(), yoy.salesQuantitySum(), "件",
cur.grossOrder(), true)); "计入销售额状态件数"));
list.add(kpi("净利润", formatYuanComma(cur.netProfit()), "元", cur.netProfit(), prev.netProfit(), yoy.netProfit(),
"净利率 " + netMarginPct.stripTrailingZeros().toPlainString() + "% · 税额口径税率 "
+ taxRate.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%",
cur.netProfit(), true));
list.add(kpi("订单量", df.format(cur.orderCount()), "单",
BigDecimal.valueOf(cur.orderCount()), BigDecimal.valueOf(prev.orderCount()), BigDecimal.valueOf(yoy.orderCount()),
"日均约 " + avgDaily.stripTrailingZeros().toPlainString() + " 单",
null, null));
list.add(kpi("客单价", formatYuanComma(cur.averageOrderValue()), "元", list.add(kpi("客单价", formatYuanComma(cur.averageOrderValue()), "元",
cur.averageOrderValue(), prev.averageOrderValue(), yoy.averageOrderValue(), "按计入销售额单量", cur.averageOrderValue(), prev.averageOrderValue(), yoy.averageOrderValue(),
cur.averageOrderValue(), false)); "销售额÷销售单量", cur.averageOrderValue(), false));
list.add(kpi("销售件单价", formatYuanComma(cur.salesPiecePrice()), "元",
cur.salesPiecePrice(), prev.salesPiecePrice(), yoy.salesPiecePrice(),
"销售额÷实际销量", cur.salesPiecePrice(), false));
// —— 净收与退款 ——
list.add(kpi("净销售额", formatYuanComma(netRecv), "元", netRecv, prev.netSales(), yoy.netSales(),
"实际销售额−退款", netRecv, true));
list.add(kpi("退款额", formatYuanComma(cur.totalRefund()), "元", cur.totalRefund(), prev.totalRefund(), yoy.totalRefund(),
"计入退款状态口径", cur.totalRefund(), true));
list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP).toPlainString(), "%", list.add(kpi("退款率", refundRate.setScale(2, RoundingMode.HALF_UP).toPlainString(), "%",
refundRate, safePct(prev.totalRefund(), prev.totalSales()), yoyRefundRate, "销售额口径", refundRate, safePct(prev.totalRefund(), prev.totalSales()), safePct(yoy.totalRefund(), yoy.totalSales()),
null, null)); "退款÷实际销售额", null, null));
list.add(kpi("广告ROI", roi.stripTrailingZeros().toPlainString(), ":1", roi, list.add(kpi("GMV与销售差额", formatYuanComma(gmvSalesGap), "元", gmvSalesGap,
prev.promotion().compareTo(BigDecimal.ZERO) > 0 prev.totalGmv().subtract(prev.totalSales()), yoy.totalGmv().subtract(yoy.totalSales()),
? prev.totalSales().subtract(prev.totalRefund()).divide(prev.promotion(), 2, RoundingMode.HALF_UP) "总GMV−实际销售额", gmvSalesGap, true));
: BigDecimal.ZERO,
yoyRoi, // —— 成本 ——
"推广花费 " + formatYuanComma(cur.promotion()) + " 元", list.add(kpi("订单成本", formatYuanComma(cur.totalCost()), "元", cur.totalCost(), prev.totalCost(), yoy.totalCost(),
null, null)); "成本率 " + costRate.stripTrailingZeros().toPlainString() + "%", cur.totalCost(), true));
list.add(kpi("商品成本", formatYuanComma(cur.productCost()), "元", cur.productCost(), prev.productCost(), yoy.productCost(),
"按状态配置计入", cur.productCost(), true));
list.add(kpi("运费成本", formatYuanComma(cur.freightCost()), "元", cur.freightCost(), prev.freightCost(), yoy.freightCost(),
null, cur.freightCost(), true));
list.add(kpi("其他成本", formatYuanComma(cur.otherCost()), "元", cur.otherCost(), prev.otherCost(), yoy.otherCost(),
null, cur.otherCost(), true));
// —— 利润与费用 ——
list.add(kpi("毛利润", formatYuanComma(cur.grossOrder()), "元", cur.grossOrder(), prev.grossOrder(), yoy.grossOrder(),
"毛利率 " + grossMarginPct.stripTrailingZeros().toPlainString() + "%", cur.grossOrder(), true));
list.add(kpi("推广费", formatYuanComma(cur.promotion()), "元", cur.promotion(), prev.promotion(), yoy.promotion(),
"区间推广费合计", cur.promotion(), true));
list.add(kpi("刷单费", formatYuanComma(cur.brush()), "元", cur.brush(), prev.brush(), yoy.brush(),
"区间刷单费合计", cur.brush(), true));
list.add(kpi("税额", formatYuanComma(cur.tax()), "元", cur.tax(), prev.tax(), yoy.tax(),
"税率 " + taxRate.multiply(new BigDecimal("100")).stripTrailingZeros().toPlainString() + "%(净销售额口径)",
cur.tax(), true));
list.add(kpi("净利润", formatYuanComma(cur.netProfit()), "元", cur.netProfit(), prev.netProfit(), yoy.netProfit(),
"净利率 " + netMarginPct.stripTrailingZeros().toPlainString() + "%",
cur.netProfit(), true));
// —— 运营效率 ——
list.add(kpi("广告ROI", roi.stripTrailingZeros().toPlainString(), ":1", roi, prevRoi, yoyRoi,
"净销售额÷推广费", null, null));
return list; return list;
} }
/** 非金额类 KPI(单量、件数等) */
private WorkbenchKpiItemVO kpiCount(String label, int cur, int prev, int yoy, String unit, String sub) {
DecimalFormat df = new DecimalFormat("#,###", DecimalFormatSymbols.getInstance(Locale.CHINA));
return kpi(label, df.format(cur), unit,
BigDecimal.valueOf(cur), BigDecimal.valueOf(prev), BigDecimal.valueOf(yoy),
sub, null, null);
}
/** /**
* 单张 KPI:展示格式化主值 + 环比/同比变化率;{@code amountYuan} 供前端换算「万」; * 单张 KPI:展示格式化主值 + 环比/同比变化率;{@code amountYuan} 供前端换算「万」;
* {@code preferWanDisplay} 为 true 时建议主数字用万展示。 * {@code preferWanDisplay} 为 true 时建议主数字用万展示。
@@ -850,13 +895,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
} }
/** 环比/同比汇总 */ /** 环比/同比汇总 */
private record ComparePeriodBundle(DateRange lastRange, private record ComparePeriodBundle(DateRange lastRange, DateRange yoyRange, Totals prev, Totals yoy) {
DateRange yoyRange,
Totals prev,
Totals yoy,
BigDecimal totalGmvCur,
BigDecimal totalGmvPrev,
BigDecimal totalGmvYoy) {
} }
/** 四维聚合桶 + 展示名称 */ /** 四维聚合桶 + 展示名称 */
@@ -871,21 +910,7 @@ public class WorkbenchServiceImpl implements WorkbenchService {
} }
/** /**
* 某一时间段、在「计入销售额」口径下聚合后的财务总量。 * 单时间段店铺财务 KPI 总量(与汇总表 + 推广/刷单区间一致)。
*
* @param totalSales 计入销售额的商家实收合计
* @param totalRefund 退款侧实收合计(与 stat 一致)
* @param totalCost 订单成本合计(商品+物流+其他)
* @param productCost 商品成本分项
* @param freightCost 物流成本分项
* @param otherCost 其他成本分项
* @param promotion 区间内推广费合计
* @param brush 区间内刷单金额合计
* @param tax 按净销售额与税率计算的税额
* @param grossOrder 毛利润 = 销售 − 成本 − 退款
* @param netProfit 净利润 = 毛利润 − 推广 − 刷单 − 税
* @param orderCount 计入销售额状态的订单笔数
* @param averageOrderValue 客单价 = 销售额 / 笔数
*/ */
private record Totals(BigDecimal totalSales, private record Totals(BigDecimal totalSales,
BigDecimal totalRefund, BigDecimal totalRefund,
@@ -899,7 +924,18 @@ public class WorkbenchServiceImpl implements WorkbenchService {
BigDecimal grossOrder, BigDecimal grossOrder,
BigDecimal netProfit, BigDecimal netProfit,
int orderCount, int orderCount,
BigDecimal averageOrderValue) { int salesQuantitySum,
BigDecimal totalGmv,
int gmvOrderCount,
int gmvQuantitySum,
BigDecimal averageOrderValue,
BigDecimal gmvAverageOrderValue,
BigDecimal salesPiecePrice,
BigDecimal gmvPiecePrice) {
BigDecimal netSales() {
return totalSales.subtract(totalRefund);
}
} }
/** 多维或按日聚合用的累加桶:累计销售额、退款、成本 */ /** 多维或按日聚合用的累加桶:累计销售额、退款、成本 */
@@ -40,6 +40,14 @@
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach> <foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN 1 ELSE 0 END) THEN 1 ELSE 0 END)
</sql> </sql>
<sql id="sumSalesQuantity">
SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN <include refid="qty"/> ELSE 0 END)
</sql>
<sql id="sumGmvQuantity">
SUM(<include refid="qty"/>)
</sql>
<sql id="sumRefund"> <sql id="sumRefund">
SUM(CASE WHEN o.status_id IN SUM(CASE WHEN o.status_id IN
<foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach> <foreach collection="refundStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
@@ -67,11 +75,14 @@
IFNULL(ps.product_id, -1) AS productId, IFNULL(p.category_id, 0) AS categoryId, IFNULL(ps.product_id, -1) AS productId, IFNULL(p.category_id, 0) AS categoryId,
<include refid="sumSales"/> AS salesAmount, <include refid="sumSales"/> AS salesAmount,
<include refid="sumOrderCount"/> AS orderCount, <include refid="sumOrderCount"/> AS orderCount,
<include refid="sumSalesQuantity"/> AS salesQuantitySum,
<include refid="sumRefund"/> AS refundAmount, <include refid="sumRefund"/> AS refundAmount,
<include refid="sumProductCost"/> AS productCost, <include refid="sumProductCost"/> AS productCost,
<include refid="sumFreightCost"/> AS freightCost, <include refid="sumFreightCost"/> AS freightCost,
<include refid="sumOtherCost"/> AS otherCost, <include refid="sumOtherCost"/> AS otherCost,
SUM(o.received_amount) AS gmvAllStatus SUM(o.received_amount) AS gmvAllStatus,
COUNT(*) AS gmvOrderCount,
<include refid="sumGmvQuantity"/> AS gmvQuantitySum
FROM ec_order o FROM ec_order o
INNER JOIN ec_shop s ON s.id = o.shop_id INNER JOIN ec_shop s ON s.id = o.shop_id
LEFT JOIN ec_product_spec ps ON ps.id = o.product_spec_id LEFT JOIN ec_product_spec ps ON ps.id = o.product_spec_id
@@ -5,25 +5,29 @@
<insert id="upsertDailyShop"> <insert id="upsertDailyShop">
INSERT INTO ec_order_stat_daily_shop ( INSERT INTO ec_order_stat_daily_shop (
company_id, shop_id, platform_id, stat_date, company_id, shop_id, platform_id, stat_date,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, gmv_amount, gmv_order_count, gmv_quantity_sum,
gmv_amount, gmv_order_count, stat_version refund_amount, product_cost, freight_cost, other_cost,
stat_version
) VALUES ( ) VALUES (
#{companyId}, #{shopId}, #{platformId}, #{statDate}, #{companyId}, #{shopId}, #{platformId}, #{statDate},
#{salesAmount}, #{refundAmount}, #{salesOrderCount}, #{salesAmount}, #{salesOrderCount}, #{salesQuantitySum},
#{productCost}, #{freightCost}, #{otherCost}, #{gmvAmount}, #{gmvOrderCount}, #{gmvQuantitySum},
#{gmvAmount}, #{gmvOrderCount}, #{statVersion} #{refundAmount}, #{productCost}, #{freightCost}, #{otherCost},
#{statVersion}
) )
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
platform_id = VALUES(platform_id), platform_id = VALUES(platform_id),
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
stat_version = VALUES(stat_version), stat_version = VALUES(stat_version),
update_time = CURRENT_TIMESTAMP update_time = CURRENT_TIMESTAMP
</insert> </insert>
@@ -36,13 +40,15 @@
<insert id="batchInsertDailyProduct"> <insert id="batchInsertDailyProduct">
INSERT INTO ec_order_stat_daily_product ( INSERT INTO ec_order_stat_daily_product (
company_id, shop_id, product_id, category_id, stat_date, company_id, shop_id, product_id, category_id, stat_date,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) VALUES ) VALUES
<foreach collection="list" item="r" separator=","> <foreach collection="list" item="r" separator=",">
(#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate}, (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.categoryId}, #{r.statDate},
#{r.salesAmount}, #{r.refundAmount}, #{r.salesOrderCount}, #{r.salesAmount}, #{r.salesOrderCount}, #{r.salesQuantitySum},
#{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) #{r.gmvAmount}, #{r.gmvOrderCount}, #{r.gmvQuantitySum},
#{r.refundAmount}, #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion})
</foreach> </foreach>
</insert> </insert>
@@ -54,13 +60,15 @@
<insert id="batchInsertDailySpec"> <insert id="batchInsertDailySpec">
INSERT INTO ec_order_stat_daily_spec ( INSERT INTO ec_order_stat_daily_spec (
company_id, shop_id, product_id, product_spec_id, stat_date, company_id, shop_id, product_id, product_spec_id, stat_date,
sales_amount, refund_amount, sales_order_count, quantity_sum, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) VALUES ) VALUES
<foreach collection="list" item="r" separator=","> <foreach collection="list" item="r" separator=",">
(#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.productSpecId}, #{r.statDate}, (#{r.companyId}, #{r.shopId}, #{r.productId}, #{r.productSpecId}, #{r.statDate},
#{r.salesAmount}, #{r.refundAmount}, #{r.salesOrderCount}, #{r.quantitySum}, #{r.salesAmount}, #{r.salesOrderCount}, #{r.salesQuantitySum},
#{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion}) #{r.gmvAmount}, #{r.gmvOrderCount}, #{r.gmvQuantitySum},
#{r.refundAmount}, #{r.productCost}, #{r.freightCost}, #{r.otherCost}, #{r.statVersion})
</foreach> </foreach>
</insert> </insert>
@@ -68,14 +76,16 @@
<insert id="rollupMonthlyShop"> <insert id="rollupMonthlyShop">
INSERT INTO ec_order_stat_monthly_shop ( INSERT INTO ec_order_stat_monthly_shop (
company_id, shop_id, platform_id, stat_month, company_id, shop_id, platform_id, stat_month,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, gmv_amount, gmv_order_count, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, MAX(platform_id), SELECT company_id, shop_id, MAX(platform_id),
#{statMonth}, #{statMonth},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(gmv_amount), SUM(gmv_order_count), MAX(stat_version) SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_daily_shop FROM ec_order_stat_daily_shop
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND stat_date &gt;= #{statMonth} AND stat_date &gt;= #{statMonth}
@@ -84,13 +94,15 @@
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
platform_id = VALUES(platform_id), platform_id = VALUES(platform_id),
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
stat_version = VALUES(stat_version), stat_version = VALUES(stat_version),
update_time = CURRENT_TIMESTAMP update_time = CURRENT_TIMESTAMP
</insert> </insert>
@@ -98,14 +110,16 @@
<insert id="rollupYearlyShop"> <insert id="rollupYearlyShop">
INSERT INTO ec_order_stat_yearly_shop ( INSERT INTO ec_order_stat_yearly_shop (
company_id, shop_id, platform_id, stat_year, company_id, shop_id, platform_id, stat_year,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, gmv_amount, gmv_order_count, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, MAX(platform_id), SELECT company_id, shop_id, MAX(platform_id),
#{statYear}, #{statYear},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(gmv_amount), SUM(gmv_order_count), MAX(stat_version) SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_monthly_shop FROM ec_order_stat_monthly_shop
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND YEAR(stat_month) = #{statYear} AND YEAR(stat_month) = #{statYear}
@@ -113,13 +127,15 @@
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
platform_id = VALUES(platform_id), platform_id = VALUES(platform_id),
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
stat_version = VALUES(stat_version), stat_version = VALUES(stat_version),
update_time = CURRENT_TIMESTAMP update_time = CURRENT_TIMESTAMP
</insert> </insert>
@@ -127,13 +143,16 @@
<insert id="rollupMonthlyProduct"> <insert id="rollupMonthlyProduct">
INSERT INTO ec_order_stat_monthly_product ( INSERT INTO ec_order_stat_monthly_product (
company_id, shop_id, product_id, category_id, stat_month, company_id, shop_id, product_id, category_id, stat_month,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, product_id, category_id, SELECT company_id, shop_id, product_id, category_id,
#{statMonth}, #{statMonth},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND stat_date &gt;= #{statMonth} AND stat_date &gt;= #{statMonth}
@@ -141,8 +160,12 @@
GROUP BY company_id, shop_id, product_id, category_id GROUP BY company_id, shop_id, product_id, category_id
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
@@ -153,21 +176,28 @@
<insert id="rollupYearlyProduct"> <insert id="rollupYearlyProduct">
INSERT INTO ec_order_stat_yearly_product ( INSERT INTO ec_order_stat_yearly_product (
company_id, shop_id, product_id, category_id, stat_year, company_id, shop_id, product_id, category_id, stat_year,
sales_amount, refund_amount, sales_order_count, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, product_id, category_id, SELECT company_id, shop_id, product_id, category_id,
#{statYear}, #{statYear},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_monthly_product FROM ec_order_stat_monthly_product
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND YEAR(stat_month) = #{statYear} AND YEAR(stat_month) = #{statYear}
GROUP BY company_id, shop_id, product_id, category_id GROUP BY company_id, shop_id, product_id, category_id
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
@@ -178,13 +208,16 @@
<insert id="rollupMonthlySpec"> <insert id="rollupMonthlySpec">
INSERT INTO ec_order_stat_monthly_spec ( INSERT INTO ec_order_stat_monthly_spec (
company_id, shop_id, product_id, product_spec_id, stat_month, company_id, shop_id, product_id, product_spec_id, stat_month,
sales_amount, refund_amount, sales_order_count, quantity_sum, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, product_id, product_spec_id, SELECT company_id, shop_id, product_id, product_spec_id,
#{statMonth}, #{statMonth},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(quantity_sum), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_daily_spec FROM ec_order_stat_daily_spec
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND stat_date &gt;= #{statMonth} AND stat_date &gt;= #{statMonth}
@@ -192,9 +225,12 @@
GROUP BY company_id, shop_id, product_id, product_spec_id GROUP BY company_id, shop_id, product_id, product_spec_id
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
quantity_sum = VALUES(quantity_sum), sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
@@ -205,22 +241,28 @@
<insert id="rollupYearlySpec"> <insert id="rollupYearlySpec">
INSERT INTO ec_order_stat_yearly_spec ( INSERT INTO ec_order_stat_yearly_spec (
company_id, shop_id, product_id, product_spec_id, stat_year, company_id, shop_id, product_id, product_spec_id, stat_year,
sales_amount, refund_amount, sales_order_count, quantity_sum, sales_amount, sales_order_count, sales_quantity_sum,
product_cost, freight_cost, other_cost, stat_version gmv_amount, gmv_order_count, gmv_quantity_sum,
refund_amount, product_cost, freight_cost, other_cost, stat_version
) )
SELECT company_id, shop_id, product_id, product_spec_id, SELECT company_id, shop_id, product_id, product_spec_id,
#{statYear}, #{statYear},
SUM(sales_amount), SUM(refund_amount), SUM(sales_order_count), SUM(quantity_sum), SUM(sales_amount), SUM(sales_order_count), SUM(sales_quantity_sum),
SUM(product_cost), SUM(freight_cost), SUM(other_cost), MAX(stat_version) SUM(gmv_amount), SUM(gmv_order_count), SUM(gmv_quantity_sum),
SUM(refund_amount), SUM(product_cost), SUM(freight_cost), SUM(other_cost),
MAX(stat_version)
FROM ec_order_stat_monthly_spec FROM ec_order_stat_monthly_spec
WHERE company_id = #{companyId} AND shop_id = #{shopId} WHERE company_id = #{companyId} AND shop_id = #{shopId}
AND YEAR(stat_month) = #{statYear} AND YEAR(stat_month) = #{statYear}
GROUP BY company_id, shop_id, product_id, product_spec_id GROUP BY company_id, shop_id, product_id, product_spec_id
ON DUPLICATE KEY UPDATE ON DUPLICATE KEY UPDATE
sales_amount = VALUES(sales_amount), sales_amount = VALUES(sales_amount),
refund_amount = VALUES(refund_amount),
sales_order_count = VALUES(sales_order_count), sales_order_count = VALUES(sales_order_count),
quantity_sum = VALUES(quantity_sum), sales_quantity_sum = VALUES(sales_quantity_sum),
gmv_amount = VALUES(gmv_amount),
gmv_order_count = VALUES(gmv_order_count),
gmv_quantity_sum = VALUES(gmv_quantity_sum),
refund_amount = VALUES(refund_amount),
product_cost = VALUES(product_cost), product_cost = VALUES(product_cost),
freight_cost = VALUES(freight_cost), freight_cost = VALUES(freight_cost),
other_cost = VALUES(other_cost), other_cost = VALUES(other_cost),
@@ -8,16 +8,48 @@
<foreach collection="shopIds" item="sid" open="(" separator="," close=")">#{sid}</foreach> <foreach collection="shopIds" item="sid" open="(" separator="," close=")">#{sid}</foreach>
</sql> </sql>
<sql id="kpiSumShop">
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount,
COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum
</sql>
<sql id="kpiSumProduct">
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount,
COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
</sql>
<sql id="kpiSumSpec">
COALESCE(SUM(sales_amount), 0) AS salesAmount,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(sales_quantity_sum), 0) AS salesQuantitySum,
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount,
COALESCE(SUM(gmv_quantity_sum), 0) AS gmvQuantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
</sql>
<select id="sumDailyShop" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailyShop" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumShop"/>,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost, COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost, COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost, COALESCE(SUM(other_cost), 0) AS otherCost
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -27,14 +59,10 @@
<select id="sumDailyShopByDay" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailyShopByDay" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
stat_date AS statDate, stat_date AS statDate,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumShop"/>,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost, COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost, COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost, COALESCE(SUM(other_cost), 0) AS otherCost
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -47,14 +75,10 @@
SELECT SELECT
shop_id AS shopId, shop_id AS shopId,
MAX(platform_id) AS platformId, MAX(platform_id) AS platformId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumShop"/>,
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost, COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost, COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost, COALESCE(SUM(other_cost), 0) AS otherCost
COALESCE(SUM(gmv_amount), 0) AS gmvAmount,
COALESCE(SUM(gmv_order_count), 0) AS gmvOrderCount
FROM ec_order_stat_daily_shop FROM ec_order_stat_daily_shop
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -65,12 +89,7 @@
<select id="sumDailyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
category_id AS categoryId, category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -82,12 +101,7 @@
SELECT SELECT
product_id AS productId, product_id AS productId,
MAX(category_id) AS categoryId, MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -100,12 +114,7 @@
shop_id AS shopId, shop_id AS shopId,
product_id AS productId, product_id AS productId,
MAX(category_id) AS categoryId, MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_date &gt;= #{startDate} AND stat_date &gt;= #{startDate}
@@ -115,12 +124,7 @@
<select id="sumDailyProductForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailyProductForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE company_id = #{companyId} WHERE company_id = #{companyId}
AND product_id = #{productId} AND product_id = #{productId}
@@ -135,12 +139,7 @@
<select id="sumDailyProductByDayForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailyProductByDayForOneProduct" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
stat_date AS statDate, stat_date AS statDate,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_product FROM ec_order_stat_daily_product
WHERE company_id = #{companyId} WHERE company_id = #{companyId}
AND product_id = #{productId} AND product_id = #{productId}
@@ -157,12 +156,7 @@
<select id="sumMonthlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumMonthlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
category_id AS categoryId, category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_product FROM ec_order_stat_monthly_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_month &gt;= #{startMonth} AND stat_month &gt;= #{startMonth}
@@ -174,12 +168,7 @@
SELECT SELECT
product_id AS productId, product_id AS productId,
MAX(category_id) AS categoryId, MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_product FROM ec_order_stat_monthly_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_month &gt;= #{startMonth} AND stat_month &gt;= #{startMonth}
@@ -190,12 +179,7 @@
<select id="sumYearlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumYearlyProductByCategory" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
category_id AS categoryId, category_id AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_product FROM ec_order_stat_yearly_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_year &gt;= #{startYear} AND stat_year &gt;= #{startYear}
@@ -207,12 +191,7 @@
SELECT SELECT
product_id AS productId, product_id AS productId,
MAX(category_id) AS categoryId, MAX(category_id) AS categoryId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumProduct"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_product FROM ec_order_stat_yearly_product
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND stat_year &gt;= #{startYear} AND stat_year &gt;= #{startYear}
@@ -223,13 +202,7 @@
<select id="sumDailySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumDailySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
product_spec_id AS productSpecId, product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumSpec"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_daily_spec FROM ec_order_stat_daily_spec
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND product_id = #{productId} AND product_id = #{productId}
@@ -241,13 +214,7 @@
<select id="sumMonthlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumMonthlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
product_spec_id AS productSpecId, product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumSpec"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_monthly_spec FROM ec_order_stat_monthly_spec
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND product_id = #{productId} AND product_id = #{productId}
@@ -259,13 +226,7 @@
<select id="sumYearlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO"> <select id="sumYearlySpecBySpec" resultType="top.xyquan.ecomdmbbackend.modules.ecom.order.stat.model.dto.OrderStatMetricsDTO">
SELECT SELECT
product_spec_id AS productSpecId, product_spec_id AS productSpecId,
COALESCE(SUM(sales_amount), 0) AS salesAmount, <include refid="kpiSumSpec"/>
COALESCE(SUM(refund_amount), 0) AS refundAmount,
COALESCE(SUM(sales_order_count), 0) AS salesOrderCount,
COALESCE(SUM(quantity_sum), 0) AS quantitySum,
COALESCE(SUM(product_cost), 0) AS productCost,
COALESCE(SUM(freight_cost), 0) AS freightCost,
COALESCE(SUM(other_cost), 0) AS otherCost
FROM ec_order_stat_yearly_spec FROM ec_order_stat_yearly_spec
WHERE <include refid="shopFilter"/> WHERE <include refid="shopFilter"/>
AND product_id = #{productId} AND product_id = #{productId}
@@ -50,7 +50,10 @@
THEN o.received_amount ELSE 0 END) AS refundAmount, THEN o.received_amount ELSE 0 END) AS refundAmount,
SUM(CASE WHEN o.status_id IN SUM(CASE WHEN o.status_id IN
<foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach> <foreach collection="salesStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN <include refid="qty"/> ELSE 0 END) AS quantitySum, THEN <include refid="qty"/> ELSE 0 END) AS salesQuantitySum,
SUM(o.received_amount) AS gmvAmount,
COUNT(*) AS gmvOrderCount,
SUM(<include refid="qty"/>) AS gmvQuantitySum,
SUM(CASE WHEN o.status_id IN SUM(CASE WHEN o.status_id IN
<foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach> <foreach collection="productCostStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS productCost, THEN o.product_cost * <include refid="qty"/> ELSE 0 END) AS productCost,
@@ -66,13 +69,6 @@
AND o.shop_id = #{shopId} AND o.shop_id = #{shopId}
AND o.order_time &gt;= #{start} AND o.order_time &gt;= #{start}
AND o.order_time &lt;= #{end} AND o.order_time &lt;= #{end}
<choose>
<when test="unionStatusIds != null and unionStatusIds.size() > 0">
AND o.status_id IN
<foreach collection="unionStatusIds" item="id" open="(" separator="," close=")">#{id}</foreach>
</when>
<otherwise>AND 1 = 0</otherwise>
</choose>
GROUP BY IFNULL(o.product_spec_id, 0), IFNULL(ps.product_id, 0) GROUP BY IFNULL(o.product_spec_id, 0), IFNULL(ps.product_id, 0)
</select> </select>
</mapper> </mapper>
@@ -1,115 +1,109 @@
<script lang="ts" setup> <script lang="ts" setup>
import type { Component } from 'vue';
import type { WorkbenchVO } from '#/api/ecommerce/workbench/types'; import type { WorkbenchVO } from '#/api/ecommerce/workbench/types';
import { computed } from 'vue'; import { computed } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Tooltip } from 'ant-design-vue'; import { Tooltip } from 'ant-design-vue';
import { formatWanShort, formatYuanDetail } from '../../../utils/money'; import OverviewColumnHint from '#/components/overview/OverviewColumnHint.vue';
import { formatYuanDetail, yuanToWanNum } from '../../../utils/money';
import {
catalogLabels,
clampFinanceKpiColsPerRow,
kpiMetaByLabel,
sortLabelsByCatalog,
} from '../kpi-catalog';
import { getFinanceKpiHint } from '../finance-kpi-hints';
defineOptions({ name: 'WorkbenchFinanceKpiGrid' }); defineOptions({ name: 'WorkbenchFinanceKpiGrid' });
const props = defineProps<{ const props = defineProps<{
kpis: WorkbenchVO.KpiItem[]; kpis: WorkbenchVO.KpiItem[];
/** 用户勾选的 KPI label 列表 */
visibleLabels: string[];
/** 与汇总表一致,用于「税额」列说明 */
taxRate?: number;
/** 每行卡片数(来自用户设置) */
colsPerRow?: number;
momCompareDateStart?: string | null; momCompareDateStart?: string | null;
momCompareDateEnd?: string | null; momCompareDateEnd?: string | null;
yoyCompareDateStart?: string | null; yoyCompareDateStart?: string | null;
yoyCompareDateEnd?: string | null; yoyCompareDateEnd?: string | null;
}>(); }>();
const COLS_PER_ROW = 4; const displayOrder = computed(() => {
const fromPrefs = sortLabelsByCatalog(props.visibleLabels);
const IconGmv = createIconifyIcon('lucide:layers'); if (fromPrefs.length > 0) return fromPrefs;
const IconSales = createIconifyIcon('lucide:wallet'); return catalogLabels();
const IconGross = createIconifyIcon('lucide:trending-up'); });
const IconNet = createIconifyIcon('lucide:badge-dollar-sign');
const IconOrders = createIconifyIcon('lucide:shopping-bag');
const IconAov = createIconifyIcon('lucide:receipt');
const IconRefund = createIconifyIcon('lucide:undo-2');
const IconRoi = createIconifyIcon('lucide:target');
const IconDefault = createIconifyIcon('lucide:bar-chart-3');
type KpiMeta = {
icon: Component;
upIsGood: boolean;
};
const KPI_DISPLAY_ORDER = [
'总GMV',
'实际销售额',
'毛利润',
'净利润',
'订单量',
'客单价',
'退款率',
'广告ROI',
] as const;
const KPI_META: Record<string, KpiMeta> = {
总GMV: { icon: IconGmv, upIsGood: true },
实际销售额: { icon: IconSales, upIsGood: true },
毛利润: { icon: IconGross, upIsGood: true },
净利润: { icon: IconNet, upIsGood: true },
订单量: { icon: IconOrders, upIsGood: true },
客单价: { icon: IconAov, upIsGood: true },
退款率: { icon: IconRefund, upIsGood: false },
广告ROI: { icon: IconRoi, upIsGood: true },
};
const DEFAULT_META: KpiMeta = {
icon: IconDefault,
upIsGood: true,
};
const orderedKpiRows = computed(() => { const orderedKpiRows = computed(() => {
const byLabel = new Map(props.kpis.map((k) => [k.label, k])); const byLabel = new Map(props.kpis.map((k) => [k.label, k]));
const visibleSet = new Set(displayOrder.value);
const ordered: WorkbenchVO.KpiItem[] = []; const ordered: WorkbenchVO.KpiItem[] = [];
for (const label of KPI_DISPLAY_ORDER) { for (const label of displayOrder.value) {
const k = byLabel.get(label); const k = byLabel.get(label);
if (k) ordered.push(k); if (k) ordered.push(k);
} }
for (const k of props.kpis) { for (const k of props.kpis) {
if (!KPI_DISPLAY_ORDER.includes(k.label as (typeof KPI_DISPLAY_ORDER)[number])) { if (!visibleSet.has(k.label)) continue;
ordered.push(k); if (!ordered.some((o) => o.label === k.label)) ordered.push(k);
}
} }
const total = ordered.length; return ordered.map((kpi) => ({
const remainder = total % COLS_PER_ROW;
const lastRowFillSpan = remainder === 0 ? 0 : COLS_PER_ROW - remainder + 1;
return ordered.map((kpi, index) => ({
kpi, kpi,
meta: KPI_META[kpi.label] ?? DEFAULT_META, meta: kpiMetaByLabel(kpi.label),
fillSpan: index === total - 1 && lastRowFillSpan > 1 ? lastRowFillSpan : 0,
})); }));
}); });
const showEmptyPrefsHint = computed(
() => props.kpis.length > 0 && props.visibleLabels.length === 0,
);
const gridColumnCount = computed(() =>
clampFinanceKpiColsPerRow(props.colsPerRow),
);
const gridStyle = computed(() => ({
gridTemplateColumns: `repeat(${gridColumnCount.value}, minmax(0, 1fr))`,
}));
function compareRangeHint(start?: string | null, end?: string | null): string { function compareRangeHint(start?: string | null, end?: string | null): string {
if (start && end) return `对比区间:${start} 至 ${end}`; if (start && end) return `对比区间:${start} 至 ${end}`;
return '对比区间未返回'; return '对比区间未返回';
} }
function labelTooltip(kpi: WorkbenchVO.KpiItem): string | undefined { /** 主数字与单位分开展示,便于单位、环比胶囊紧跟数字 */
const sub = kpi.sub?.trim(); function primaryLine(kpi: WorkbenchVO.KpiItem): {
return sub || undefined; display: string;
} unitText: string;
hover: string;
function primaryLine(kpi: WorkbenchVO.KpiItem): { display: string; hover: string } { } {
const ay = kpi.amountYuan; const ay = kpi.amountYuan;
if (ay == null || !Number.isFinite(ay)) { if (ay == null || !Number.isFinite(ay)) {
return { display: String(kpi.value ?? ''), hover: '' }; return {
display: String(kpi.value ?? ''),
unitText: kpi.unit?.trim() ?? '',
hover: '',
};
} }
const hover = formatYuanDetail(ay); const hover = formatYuanDetail(ay);
if (kpi.preferWanDisplay === true) { if (kpi.preferWanDisplay === true) {
return { display: formatWanShort(ay), hover }; return {
display: yuanToWanNum(ay).toFixed(2),
unitText: '万',
hover,
};
} }
return { display: String(kpi.value ?? ''), hover }; return {
display: String(kpi.value ?? ''),
unitText: kpi.unit?.trim() ?? '',
hover,
};
} }
function trendIsGood(kpi: WorkbenchVO.KpiItem, up: boolean): boolean { function trendIsGood(kpi: WorkbenchVO.KpiItem, up: boolean): boolean {
const meta = KPI_META[kpi.label] ?? DEFAULT_META; const meta = kpiMetaByLabel(kpi.label);
return meta.upIsGood ? up : !up; return meta.upIsGood ? up : !up;
} }
@@ -127,63 +121,65 @@ function deltaTextClass(good: boolean): string {
: 'text-rose-600 dark:text-rose-400'; : 'text-rose-600 dark:text-rose-400';
} }
/** 末行未满时,最后一张卡跨列铺满 */
function gridSpanClass(fillSpan: number): string {
if (fillSpan <= 1) return '';
return `lg:col-span-${fillSpan}`;
}
const cardShellClass = const cardShellClass =
'group flex min-h-[8.5rem] min-w-0 flex-col justify-between rounded-2xl border border-slate-200 bg-white/90 p-5 shadow-[0_4px_12px_rgba(0,0,0,0.03)] transition-all duration-200 hover:border-slate-300 hover:shadow-md dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:shadow-none dark:hover:border-[hsl(240deg_3.7%_35%)] backdrop-blur-[10px] sm:min-h-[9rem] sm:p-6'; 'group flex min-h-[6.75rem] min-w-0 flex-col rounded-xl border border-slate-200/90 bg-gradient-to-b from-white to-slate-50/80 p-3.5 shadow-sm transition-[border-color,box-shadow] duration-200 hover:border-slate-300 hover:shadow-md dark:border-[hsl(240deg_3.7%_22%)] dark:from-[hsl(222.34deg_10.43%_12.27%)] dark:to-[hsl(222.34deg_10.43%_10%)] dark:shadow-none dark:hover:border-[hsl(240deg_3.7%_32%)]';
const iconShellClass = const labelClass =
'flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-slate-50 text-slate-500 transition-colors group-hover:bg-slate-100 dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)] dark:group-hover:bg-[hsl(240deg_3.7%_22%)]'; 'truncate text-xs font-semibold leading-none text-slate-600 dark:text-[hsl(240deg_5%_72%)]';
const trendBadgeShellClass = const valueUnitClass =
'inline-flex cursor-default items-center rounded-lg bg-slate-50 px-2 py-1 text-[11px] font-bold leading-none text-slate-500 dark:bg-[hsl(240deg_3.7%_15.9%)] dark:text-[hsl(240deg_5%_64.9%)]'; 'text-sm font-semibold leading-none text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]';
const trendChipClass =
'inline-flex cursor-default items-baseline gap-px rounded-full border border-slate-200/80 bg-white/80 px-1.5 py-0.5 text-[11px] font-medium leading-none text-slate-500 dark:border-[hsl(240deg_3.7%_26%)] dark:bg-[hsl(240deg_3.7%_14%)] dark:text-[hsl(240deg_5%_64.9%)]';
</script> </script>
<template> <template>
<div <div
v-if="kpis.length === 0" v-if="kpis.length === 0"
class="rounded-2xl border border-dashed border-slate-200 bg-white/60 px-4 py-12 text-center text-sm text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(240deg_5%_64.9%)]" class="rounded-xl border border-dashed border-slate-200 bg-white/60 px-4 py-8 text-center text-sm text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(240deg_5%_64.9%)]"
> >
暂无 KPI 数据 暂无 KPI 数据
</div> </div>
<div
v-else-if="showEmptyPrefsHint"
class="rounded-xl border border-dashed border-amber-200 bg-amber-50/60 px-4 py-8 text-center text-sm text-amber-700 dark:border-amber-900/40 dark:bg-amber-950/20 dark:text-amber-300"
>
未选择任何 KPI,请点击上方「KPI 显示设置」勾选要展示的指标。
</div>
<div
v-else-if="orderedKpiRows.length === 0"
class="rounded-xl border border-dashed border-slate-200 bg-white/60 px-4 py-8 text-center text-sm text-slate-400 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(222.34deg_10.43%_12.27%)] dark:text-[hsl(240deg_5%_64.9%)]"
>
当前筛选下暂无已选 KPI 数据
</div>
<div <div
v-else v-else
class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4" class="grid gap-3"
:style="gridStyle"
> >
<div <div
v-for="{ kpi, meta, fillSpan } in orderedKpiRows" v-for="{ kpi, meta } in orderedKpiRows"
:key="kpi.label" :key="kpi.label"
:class="[cardShellClass, gridSpanClass(fillSpan)]" :class="cardShellClass"
> >
<div class="mb-4 flex items-start justify-between gap-3"> <!-- 顶栏:左标题 / 右上角环比同比 -->
<div class="flex min-w-0 items-center gap-3"> <div class="mb-2 flex items-start justify-between gap-2">
<span :class="iconShellClass"> <div class="flex min-w-0 flex-1 items-center gap-1.5">
<component :is="meta.icon" class="text-xl" /> <component
</span> :is="meta.icon"
<div class="flex flex-col min-w-0"> class="size-4 shrink-0 text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
<Tooltip v-if="labelTooltip(kpi)" :title="labelTooltip(kpi)"> />
<span <OverviewColumnHint
class="cursor-default truncate text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]" class="min-w-0"
> :title="getFinanceKpiHint(kpi.label, taxRate ?? 0.04)"
{{ kpi.label }} >
</span> <span :class="labelClass">{{ kpi.label }}</span>
</Tooltip> </OverviewColumnHint>
<span
v-else
class="truncate text-xs font-bold uppercase tracking-wider text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ kpi.label }}
</span>
</div>
</div> </div>
<div class="flex shrink-0 flex-col items-end gap-1.5"> <div class="flex shrink-0 items-center gap-1">
<Tooltip <Tooltip
:title="compareRangeHint(momCompareDateStart, momCompareDateEnd)" :title="compareRangeHint(momCompareDateStart, momCompareDateEnd)"
> >
<span :class="trendBadgeShellClass"> <span :class="trendChipClass">
<span class="mr-1 opacity-60">环</span> <span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">环</span>
<span :class="deltaTextClass(trendIsGood(kpi, kpi.up === true))"> <span :class="deltaTextClass(trendIsGood(kpi, kpi.up === true))">
{{ formatDelta(kpi, kpi.changePct) }} {{ formatDelta(kpi, kpi.changePct) }}
</span> </span>
@@ -193,9 +189,11 @@ const trendBadgeShellClass =
v-if="kpi.yoyChangePct != null && kpi.yoyUp != null" v-if="kpi.yoyChangePct != null && kpi.yoyUp != null"
:title="compareRangeHint(yoyCompareDateStart, yoyCompareDateEnd)" :title="compareRangeHint(yoyCompareDateStart, yoyCompareDateEnd)"
> >
<span :class="trendBadgeShellClass"> <span :class="trendChipClass">
<span class="mr-1 opacity-60">同</span> <span class="text-slate-400 dark:text-[hsl(240deg_5%_55%)]">同</span>
<span :class="deltaTextClass(trendIsGood(kpi, kpi.yoyUp === true))"> <span
:class="deltaTextClass(trendIsGood(kpi, kpi.yoyUp === true))"
>
{{ formatDelta(kpi, kpi.yoyChangePct) }} {{ formatDelta(kpi, kpi.yoyChangePct) }}
</span> </span>
</span> </span>
@@ -203,38 +201,32 @@ const trendBadgeShellClass =
</div> </div>
</div> </div>
<div class="flex flex-col"> <!-- 主数字 + 单位紧跟 -->
<div <span class="inline-flex max-w-full items-baseline whitespace-nowrap">
class="min-w-0 truncate text-2xl font-bold leading-tight tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)] sm:text-3xl" <Tooltip v-if="primaryLine(kpi).hover" :title="primaryLine(kpi).hover">
> <span
<Tooltip v-if="primaryLine(kpi).hover" :title="primaryLine(kpi).hover"> class="cursor-default tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
<span class="cursor-default"> >
{{ primaryLine(kpi).display }}
<span
v-if="kpi.preferWanDisplay !== true && kpi.unit"
class="ml-1 text-base font-medium text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
>
{{ kpi.unit }}
</span>
</span>
</Tooltip>
<template v-else>
{{ primaryLine(kpi).display }} {{ primaryLine(kpi).display }}
<span </span>
v-if="kpi.unit" </Tooltip>
class="ml-1 text-base font-medium text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]" <span
> v-else
{{ kpi.unit }} class="tabular-nums text-2xl font-bold leading-none tracking-tight text-slate-900 dark:text-[hsl(0deg_0%_95%)]"
</span>
</template>
</div>
<div
v-if="kpi.sub"
class="mt-1 truncate text-[11px] font-medium text-slate-400 dark:text-[hsl(240deg_5%_64.9%)]"
> >
{{ kpi.sub }} {{ primaryLine(kpi).display }}
</div> </span>
</div> <span v-if="primaryLine(kpi).unitText" :class="valueUnitClass">
{{ primaryLine(kpi).unitText }}
</span>
</span>
<p
v-if="kpi.sub"
class="mt-1.5 w-full truncate text-right text-[11px] leading-snug text-slate-400 dark:text-[hsl(240deg_5%_55%)]"
>
{{ kpi.sub }}
</p>
</div> </div>
</div> </div>
</template> </template>
@@ -0,0 +1,200 @@
<script lang="ts" setup>
import type { FinanceKpiGroupId } from '../kpi-catalog';
import { computed, ref, watch } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, Checkbox, message, Modal, Radio } from 'ant-design-vue';
import {
clampFinanceKpiColsPerRow,
FINANCE_KPI_CATALOG,
FINANCE_KPI_COLS_PER_ROW_OPTIONS,
FINANCE_KPI_DEFAULT_COLS_PER_ROW,
FINANCE_KPI_DEFAULT_VISIBLE,
FINANCE_KPI_GROUP_ORDER,
type FinanceKpiColsPerRow,
} from '../kpi-catalog';
defineOptions({ name: 'WorkbenchFinanceKpiSettingsModal' });
const props = defineProps<{
open: boolean;
visibleLabels: string[];
colsPerRow: number;
}>();
const emit = defineEmits<{
(e: 'update:open', v: boolean): void;
(e: 'save', payload: { labels: string[]; colsPerRow: number }): void;
}>();
const IconSettings = createIconifyIcon('lucide:settings-2');
const draft = ref<string[]>([]);
const draftColsPerRow = ref<FinanceKpiColsPerRow>(FINANCE_KPI_DEFAULT_COLS_PER_ROW);
watch(
() => props.open,
(isOpen) => {
if (isOpen) {
draft.value = [...props.visibleLabels];
draftColsPerRow.value = clampFinanceKpiColsPerRow(props.colsPerRow);
}
},
{ immediate: true },
);
const grouped = computed(() => {
const map = new Map<FinanceKpiGroupId, { title: string; labels: string[] }>();
for (const g of FINANCE_KPI_GROUP_ORDER) {
map.set(g, { title: '', labels: [] });
}
for (const item of FINANCE_KPI_CATALOG) {
const bucket = map.get(item.group)!;
if (!bucket.title) bucket.title = item.groupTitle;
bucket.labels.push(item.label);
}
return FINANCE_KPI_GROUP_ORDER.map((id) => ({
id,
title: map.get(id)!.title,
labels: map.get(id)!.labels,
})).filter((g) => g.labels.length > 0);
});
function isGroupAllChecked(labels: string[]): boolean {
return labels.every((l) => draft.value.includes(l));
}
function isGroupIndeterminate(labels: string[]): boolean {
const n = labels.filter((l) => draft.value.includes(l)).length;
return n > 0 && n < labels.length;
}
function toggleGroup(labels: string[], checked: boolean) {
const set = new Set(draft.value);
for (const l of labels) {
if (checked) set.add(l);
else set.delete(l);
}
draft.value = [...set];
}
function onCheckboxChange(label: string, checked: boolean) {
const set = new Set(draft.value);
if (checked) set.add(label);
else set.delete(label);
draft.value = [...set];
}
function onGroupCheckboxChange(labels: string[], e: { target: { checked: boolean } }) {
toggleGroup(labels, e.target.checked);
}
function onItemCheckboxChange(label: string, e: { target: { checked: boolean } }) {
onCheckboxChange(label, e.target.checked);
}
function applyDefaultCore() {
draft.value = [...FINANCE_KPI_DEFAULT_VISIBLE];
draftColsPerRow.value = FINANCE_KPI_DEFAULT_COLS_PER_ROW;
}
function applySelectAll() {
draft.value = FINANCE_KPI_CATALOG.map((c) => c.label);
}
function handleOk() {
if (draft.value.length === 0) {
message.warning('请至少选择一项 KPI');
return;
}
emit('save', { labels: draft.value, colsPerRow: draftColsPerRow.value });
emit('update:open', false);
}
function handleCancel() {
emit('update:open', false);
}
</script>
<template>
<Modal
:open="open"
title="KPI 显示设置"
width="640px"
:destroy-on-close="false"
@cancel="handleCancel"
@ok="handleOk"
>
<template #title>
<span class="inline-flex flex-nowrap items-center gap-2 whitespace-nowrap">
<component :is="IconSettings" class="size-[1.125rem] shrink-0 text-slate-500" />
<span class="shrink-0">KPI 显示设置</span>
</span>
</template>
<p class="mb-4 text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
勾选要在经营概览中展示的指标,并可调整每行卡片数量;设置保存在本浏览器。
</p>
<div
class="mb-4 rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_12%)]"
>
<div class="mb-2 text-sm font-semibold text-slate-700 dark:text-[hsl(0deg_0%_90%)]">
每行显示卡片数
</div>
<Radio.Group v-model:value="draftColsPerRow" class="flex flex-wrap gap-2">
<Radio
v-for="n in FINANCE_KPI_COLS_PER_ROW_OPTIONS"
:key="n"
:value="n"
>
{{ n }} 张
</Radio>
</Radio.Group>
</div>
<div class="mb-4 flex flex-wrap gap-2">
<Button size="small" @click="applySelectAll">全选</Button>
<Button size="small" @click="applyDefaultCore">恢复默认(8 项)</Button>
</div>
<div class="max-h-[min(60vh,28rem)] space-y-5 overflow-y-auto pr-1">
<section
v-for="group in grouped"
:key="group.id"
class="rounded-xl border border-slate-100 bg-slate-50/80 p-4 dark:border-[hsl(240deg_3.7%_22%)] dark:bg-[hsl(240deg_3.7%_12%)]"
>
<div class="mb-3 flex items-center gap-2">
<Checkbox
:checked="isGroupAllChecked(group.labels)"
:indeterminate="isGroupIndeterminate(group.labels)"
@change="(e) => onGroupCheckboxChange(group.labels, e)"
>
<span class="font-semibold text-slate-700 dark:text-[hsl(0deg_0%_90%)]">
{{ group.title }}
</span>
</Checkbox>
</div>
<div class="grid grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-3">
<Checkbox
v-for="label in group.labels"
:key="label"
:checked="draft.includes(label)"
@change="(e) => onItemCheckboxChange(label, e)"
>
<span class="text-sm">{{ label }}</span>
</Checkbox>
</div>
</section>
</div>
<p
v-if="draft.length === 0"
class="mt-3 text-sm text-amber-600 dark:text-amber-400"
>
请至少选择一项指标,否则概览区将无 KPI 卡片。
</p>
</Modal>
</template>
@@ -0,0 +1,45 @@
import { overviewTableHints, salesTaxColumnHint } from '#/utils/overview-table-hints';
/** 工作台经营 KPI 计算说明(与汇总表、后端 WorkbenchServiceImpl 口径一致) */
const FINANCE_KPI_HINTS: Record<string, string> = {
总GMV: overviewTableHints.gmv,
GMV单量:
'所选时间范围内,全部订单状态的订单笔数合计(不按是否计入销售额过滤)。环比/同比为笔数变化率。',
GMV销量:
'所选时间范围内,全部订单状态的销售件数合计(订单行件数汇总)。',
GMV客单价: 'GMV ÷ GMV单量;GMV单量为 0 时为 0。',
GMV件单价: 'GMV ÷ GMV销量;GMV销量为 0 时为 0。',
实际销售额: overviewTableHints.salesAmount,
销售单量:
'统计口径下,计入销售额的有效订单笔数(与下方汇总表「单量」列一致)。环比/同比为笔数变化率。',
实际销量: '计入销售额的订单状态件数合计。',
客单价: '实际销售额 ÷ 销售单量;销售单量为 0 时为 0。',
销售件单价: '实际销售额 ÷ 实际销量;实际销量为 0 时为 0。',
净销售额: '实际销售额 − 退款额(与广告 ROI 分子、税额计税基数同口径)。',
退款额: overviewTableHints.refundAmount,
退款率: '退款额 ÷ 实际销售额 × 100%;实际销售额为 0 时为 0。',
'GMV与销售差额': '总GMV − 实际销售额,反映未计入销售口径的订单实收差额。',
订单成本: overviewTableHints.orderCost,
商品成本: overviewTableHints.productCost,
运费成本: overviewTableHints.shippingCost,
其他成本: overviewTableHints.otherCost,
毛利润: overviewTableHints.grossProfit,
推广费: overviewTableHints.totalPromotionFee,
刷单费: overviewTableHints.brushFee,
净利润:
'净利润 = 毛利润 − 推广费 − 刷单费 − 税额(与汇总表损益链路一致)。卡片副文案中的净利率 = 净利润 ÷ 实际销售额。',
广告ROI: overviewTableHints.roi,
};
/**
* 获取 KPI 标题旁问号 Tooltip 文案;税额随页面税率变化。
*/
export function getFinanceKpiHint(label: string, taxRate = 0.04): string {
if (label === '税额') {
return `${salesTaxColumnHint(taxRate)} 工作台按净销售额计税基数汇总。`;
}
return (
FINANCE_KPI_HINTS[label] ??
'该指标说明暂未配置,请以汇总表同名列或系统配置口径为准。'
);
}
@@ -4,11 +4,18 @@ import type { CompanyOverviewVO } from '#/api/ecommerce/store-overview';
import { computed, nextTick, ref } from 'vue'; import { computed, nextTick, ref } from 'vue';
import { createIconifyIcon } from '@vben/icons';
import { Button, message } from 'ant-design-vue';
import FinanceCostPieChart from './components/FinanceCostPieChart.vue'; import FinanceCostPieChart from './components/FinanceCostPieChart.vue';
import FinanceKpiGrid from './components/FinanceKpiGrid.vue'; import FinanceKpiGrid from './components/FinanceKpiGrid.vue';
import FinanceKpiSettingsModal from './components/FinanceKpiSettingsModal.vue';
import FinanceTrendChart from './components/FinanceTrendChart.vue'; import FinanceTrendChart from './components/FinanceTrendChart.vue';
import OverviewTables from './components/OverviewTables.vue'; import OverviewTables from './components/OverviewTables.vue';
import { sortLabelsByCatalog } from './kpi-catalog';
import { useFinanceKpiPreferences } from './useFinanceKpiPreferences';
import { import {
buildCategoryOverviewFromDimRows, buildCategoryOverviewFromDimRows,
buildPlatformOverviewFromDimRows, buildPlatformOverviewFromDimRows,
@@ -52,6 +59,23 @@ const productOverview = computed(
buildCategoryOverviewFromDimRows(props.multiAnalysis.product), buildCategoryOverviewFromDimRows(props.multiAnalysis.product),
); );
const IconSliders = createIconifyIcon('lucide:sliders-horizontal');
const { visibleLabels, colsPerRow, applySettings } = useFinanceKpiPreferences();
const kpiSettingsOpen = ref(false);
const visibleKpiCount = computed(() => visibleLabels.value.length);
function onKpiSettingsSave(payload: { labels: string[]; colsPerRow: number }) {
const normalized = sortLabelsByCatalog(payload.labels);
if (normalized.length === 0) {
message.warning('请至少选择一项 KPI');
return;
}
applySettings(normalized, payload.colsPerRow);
message.success('KPI 显示已更新');
}
const trendChartRef = ref<InstanceType< const trendChartRef = ref<InstanceType<
typeof FinanceTrendChart typeof FinanceTrendChart
> | null>(null); > | null>(null);
@@ -69,9 +93,36 @@ defineExpose({ redraw });
</script> </script>
<template> <template>
<div class="mt-4 space-y-6"> <div class="mt-4 space-y-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<span class="text-sm text-slate-500 dark:text-[hsl(240deg_5%_64.9%)]">
经营 KPI
<span v-if="visibleKpiCount > 0" class="ml-1 text-slate-400">
(已选 {{ visibleKpiCount }} 项 · 每行 {{ colsPerRow }} 张)
</span>
</span>
<Button
type="default"
class="shrink-0 whitespace-nowrap"
@click="kpiSettingsOpen = true"
>
<template #icon>
<component :is="IconSliders" class="size-4 shrink-0" />
</template>
KPI 显示设置
</Button>
</div>
<FinanceKpiSettingsModal
v-model:open="kpiSettingsOpen"
:cols-per-row="colsPerRow"
:visible-labels="visibleLabels"
@save="onKpiSettingsSave"
/>
<FinanceKpiGrid <FinanceKpiGrid
:kpis="finance.kpis" :kpis="finance.kpis"
:cols-per-row="colsPerRow"
:tax-rate="taxRate"
:visible-labels="visibleLabels"
:mom-compare-date-start="finance.momCompareDateStart" :mom-compare-date-start="finance.momCompareDateStart"
:mom-compare-date-end="finance.momCompareDateEnd" :mom-compare-date-end="finance.momCompareDateEnd"
:yoy-compare-date-start="finance.yoyCompareDateStart" :yoy-compare-date-start="finance.yoyCompareDateStart"
@@ -0,0 +1,134 @@
import type { Component } from 'vue';
import { createIconifyIcon } from '@vben/icons';
/** localStorage 键(本机浏览器) */
export const FINANCE_KPI_PREFS_KEY = 'workbench-finance-kpi-visible-v1';
/** 每行 KPI 卡片数默认值 */
export const FINANCE_KPI_DEFAULT_COLS_PER_ROW = 5;
/** 设置里可选的每行卡片数 */
export const FINANCE_KPI_COLS_PER_ROW_OPTIONS = [3, 4, 5, 6] as const;
export type FinanceKpiColsPerRow = (typeof FINANCE_KPI_COLS_PER_ROW_OPTIONS)[number];
export function clampFinanceKpiColsPerRow(value: unknown): FinanceKpiColsPerRow {
const n = typeof value === 'number' ? value : Number(value);
if (FINANCE_KPI_COLS_PER_ROW_OPTIONS.includes(n as FinanceKpiColsPerRow)) {
return n as FinanceKpiColsPerRow;
}
return FINANCE_KPI_DEFAULT_COLS_PER_ROW;
}
export type FinanceKpiGroupId =
| 'gmv'
| 'sales'
| 'net'
| 'cost'
| 'profit'
| 'ops';
export type FinanceKpiCatalogItem = {
label: string;
group: FinanceKpiGroupId;
groupTitle: string;
/** 涨跌颜色:true=涨绿跌红,false=涨红跌绿(如退款率) */
upIsGood: boolean;
icon: Component;
};
const IconGmv = createIconifyIcon('lucide:layers');
const IconSales = createIconifyIcon('lucide:wallet');
const IconGross = createIconifyIcon('lucide:trending-up');
const IconNet = createIconifyIcon('lucide:badge-dollar-sign');
const IconOrders = createIconifyIcon('lucide:shopping-bag');
const IconAov = createIconifyIcon('lucide:receipt');
const IconRefund = createIconifyIcon('lucide:undo-2');
const IconRoi = createIconifyIcon('lucide:target');
const IconCost = createIconifyIcon('lucide:coins');
const IconPercent = createIconifyIcon('lucide:percent');
const IconPackage = createIconifyIcon('lucide:package');
const IconTruck = createIconifyIcon('lucide:truck');
const IconMegaphone = createIconifyIcon('lucide:megaphone');
const IconBrush = createIconifyIcon('lucide:brush');
const IconTax = createIconifyIcon('lucide:landmark');
const IconScale = createIconifyIcon('lucide:scale');
const IconReceipt = createIconifyIcon('lucide:receipt');
const IconDefault = createIconifyIcon('lucide:bar-chart-3');
const G = {
gmv: 'GMV 口径',
sales: '实际销售',
net: '净收与退款',
cost: '成本',
profit: '利润与费用',
ops: '运营效率',
} as const;
/** 与后端 buildKpis 顺序一致,用于默认排序 */
export const FINANCE_KPI_CATALOG: FinanceKpiCatalogItem[] = [
{ label: '总GMV', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconGmv },
{ label: 'GMV单量', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconOrders },
{ label: 'GMV销量', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconPackage },
{ label: 'GMV客单价', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconAov },
{ label: 'GMV件单价', group: 'gmv', groupTitle: G.gmv, upIsGood: true, icon: IconReceipt },
{ label: '实际销售额', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconSales },
{ label: '销售单量', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconOrders },
{ label: '实际销量', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconPackage },
{ label: '客单价', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconAov },
{ label: '销售件单价', group: 'sales', groupTitle: G.sales, upIsGood: true, icon: IconReceipt },
{ label: '净销售额', group: 'net', groupTitle: G.net, upIsGood: true, icon: IconNet },
{ label: '退款额', group: 'net', groupTitle: G.net, upIsGood: false, icon: IconRefund },
{ label: '退款率', group: 'net', groupTitle: G.net, upIsGood: false, icon: IconPercent },
{ label: 'GMV与销售差额', group: 'net', groupTitle: G.net, upIsGood: true, icon: IconScale },
{ label: '订单成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconCost },
{ label: '商品成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconPackage },
{ label: '运费成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconTruck },
{ label: '其他成本', group: 'cost', groupTitle: G.cost, upIsGood: false, icon: IconCost },
{ label: '毛利润', group: 'profit', groupTitle: G.profit, upIsGood: true, icon: IconGross },
{ label: '推广费', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconMegaphone },
{ label: '刷单费', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconBrush },
{ label: '税额', group: 'profit', groupTitle: G.profit, upIsGood: false, icon: IconTax },
{ label: '净利润', group: 'profit', groupTitle: G.profit, upIsGood: true, icon: IconNet },
{ label: '广告ROI', group: 'ops', groupTitle: G.ops, upIsGood: true, icon: IconRoi },
];
/** 首次进入默认展示(与改版前 8 卡接近,订单量→销售单量) */
export const FINANCE_KPI_DEFAULT_VISIBLE: string[] = [
'总GMV',
'实际销售额',
'毛利润',
'净利润',
'销售单量',
'客单价',
'退款率',
'广告ROI',
];
export const FINANCE_KPI_GROUP_ORDER: FinanceKpiGroupId[] = [
'gmv',
'sales',
'net',
'cost',
'profit',
'ops',
];
export function kpiMetaByLabel(label: string): Pick<
FinanceKpiCatalogItem,
'icon' | 'upIsGood'
> {
const item = FINANCE_KPI_CATALOG.find((c) => c.label === label);
return item ?? { icon: IconDefault, upIsGood: true };
}
export function catalogLabels(): string[] {
return FINANCE_KPI_CATALOG.map((c) => c.label);
}
/** 按目录顺序排列可见 label */
export function sortLabelsByCatalog(visible: string[]): string[] {
const set = new Set(visible);
return FINANCE_KPI_CATALOG.map((c) => c.label).filter((l) => set.has(l));
}
@@ -0,0 +1,96 @@
import { ref } from 'vue';
import {
catalogLabels,
clampFinanceKpiColsPerRow,
FINANCE_KPI_DEFAULT_COLS_PER_ROW,
FINANCE_KPI_DEFAULT_VISIBLE,
FINANCE_KPI_PREFS_KEY,
sortLabelsByCatalog,
} from './kpi-catalog';
type PrefsPayload = {
visibleLabels: string[];
colsPerRow?: number;
};
function parseStored(): PrefsPayload | null {
try {
const raw = localStorage.getItem(FINANCE_KPI_PREFS_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as PrefsPayload;
if (!Array.isArray(parsed.visibleLabels)) return null;
return {
visibleLabels: parsed.visibleLabels
.filter((x) => typeof x === 'string')
.map((l) => (l === '订单量' ? '销售单量' : l)),
colsPerRow: parsed.colsPerRow,
};
} catch {
return null;
}
}
function normalizeVisible(labels: string[]): string[] {
const catalog = new Set(catalogLabels());
const seen = new Set<string>();
const out: string[] = [];
for (const label of labels) {
if (!catalog.has(label) || seen.has(label)) continue;
seen.add(label);
out.push(label);
}
return out;
}
export function useFinanceKpiPreferences() {
const stored = parseStored();
const visibleLabels = ref<string[]>(
normalizeVisible(stored?.visibleLabels ?? [...FINANCE_KPI_DEFAULT_VISIBLE]),
);
const colsPerRow = ref(
clampFinanceKpiColsPerRow(stored?.colsPerRow ?? FINANCE_KPI_DEFAULT_COLS_PER_ROW),
);
function persist() {
const payload: PrefsPayload = {
visibleLabels: visibleLabels.value,
colsPerRow: colsPerRow.value,
};
localStorage.setItem(FINANCE_KPI_PREFS_KEY, JSON.stringify(payload));
}
function setVisibleLabels(labels: string[]) {
visibleLabels.value = sortLabelsByCatalog(normalizeVisible(labels));
persist();
}
function setColsPerRow(cols: number) {
colsPerRow.value = clampFinanceKpiColsPerRow(cols);
persist();
}
function applySettings(labels: string[], cols: number) {
visibleLabels.value = sortLabelsByCatalog(normalizeVisible(labels));
colsPerRow.value = clampFinanceKpiColsPerRow(cols);
persist();
}
function resetToDefault() {
applySettings([...FINANCE_KPI_DEFAULT_VISIBLE], FINANCE_KPI_DEFAULT_COLS_PER_ROW);
}
function selectAll() {
setVisibleLabels(catalogLabels());
}
return {
visibleLabels,
colsPerRow,
setVisibleLabels,
setColsPerRow,
applySettings,
resetToDefault,
selectAll,
};
}
@@ -16,7 +16,7 @@ export function formatYuanDetail(yuan: number | null | undefined): string {
/** 主展示:万,两位小数 */ /** 主展示:万,两位小数 */
export function formatWanShort(yuan: number | null | undefined, digits = 2): string { export function formatWanShort(yuan: number | null | undefined, digits = 2): string {
if (yuan == null || !Number.isFinite(yuan)) return '—'; if (yuan == null || !Number.isFinite(yuan)) return '—';
return `${yuanToWanNum(yuan).toFixed(digits)} 万`; return `${yuanToWanNum(yuan).toFixed(digits)}万`;
} }
/** Tooltip 等:主数字为万,括号内为精确元(与图例「万」口径一致) */ /** Tooltip 等:主数字为万,括号内为精确元(与图例「万」口径一致) */
@@ -30,5 +30,5 @@ export function formatWanWithYuanDetail(
minimumFractionDigits: 2, minimumFractionDigits: 2,
maximumFractionDigits: 2, maximumFractionDigits: 2,
}).format(yuan); }).format(yuan);
return `${wanStr} 万(${yuanStr} 元)`; return `${wanStr}万(${yuanStr} 元)`;
} }