/** * ============================================================================ * 财务概览 · 净利润公式(锁定) * ============================================================================ * * 本文件是净利润计算的**唯一权威**。修改口径只允许改这里,并同步: * - docs/design/20260809-lock-net-profit-formula.md * - docs/design/20260809-net-profit-fixed-cost-day-alloc.md * - server/tests/financeNetProfitFormula.test.ts * * 禁止在 marginQueryService / 前端 / 其他服务内联另一套净利润算术。 * * 公式: * 净利润 = 销售额 − 商品成本 − 期间固定 − 期间其他 * 期间固定:含 reference_type=fixed_cost 的按天分摊(含挂订单),按入账日入区间。 */ /** 公式版本 ID:契约测试与文档引用;改公式必须改 ID 与测试 */ export const NET_PROFIT_FORMULA_ID = 'finance_overview_net_profit_v20260810' as const; /** 对人展示的固定文案(勿在各页面各自改写);商品侧=账本采购(一套账定稿) */ export const NET_PROFIT_FORMULA_LABEL = '销售额 − 采购成本 − 期间固定 − 期间其他' as const; /** * cost_details 上「期间固定」谓词(别名必须为 cd)。 * 含 fixed_cost 挂单分摊;排除 free_overhead(走期间其他)。 */ export const PERIOD_FIXED_COST_SQL_PREDICATE = `( cd.reference_type = 'fixed_cost' OR ( (cd.order_code IS NULL OR TRIM(cd.order_code) = '') AND cd.cost_type IS DISTINCT FROM 'purchase' AND cd.cost_type IS DISTINCT FROM 'free_overhead' AND cd.cost_type IS DISTINCT FROM 'adjustment' AND cd.cost_type IS DISTINCT FROM 'refund' AND (cd.reference_type IS NULL OR cd.reference_type IS DISTINCT FROM 'fixed_cost') ) )` as const; export type FinanceNetProfitInput = { /** 销售额(订单当前预估) */ revenue: number; /** 采购成本(cost_details 账本,一套账权威) */ productCost: number; /** 期间固定(见 PERIOD_FIXED_COST_SQL_PREDICATE) */ periodFixedCost: number; /** 期间其他(free_overhead) */ periodFreeCost: number; }; export type FinanceNetProfitResult = { formulaId: typeof NET_PROFIT_FORMULA_ID; formulaLabel: typeof NET_PROFIT_FORMULA_LABEL; grossProfit: number; netProfit: number; netProfitMarginPct: number; }; function n(value: unknown): number { const x = Number(value); return Number.isFinite(x) ? x : 0; } function round2(value: number): number { return Math.round((value + Number.EPSILON) * 100) / 100; } /** * 计算商品毛利与净利润。算术只允许出现在本函数内。 */ export function computeFinanceNetProfit(input: FinanceNetProfitInput): FinanceNetProfitResult { const revenue = n(input.revenue); const productCost = n(input.productCost); const periodFixedCost = n(input.periodFixedCost); const periodFreeCost = n(input.periodFreeCost); const grossProfit = revenue - productCost; const netProfit = revenue - productCost - periodFixedCost - periodFreeCost; const netProfitMarginPct = revenue > 0 ? round2((netProfit / revenue) * 100) : 0; return { formulaId: NET_PROFIT_FORMULA_ID, formulaLabel: NET_PROFIT_FORMULA_LABEL, grossProfit: round2(grossProfit), netProfit: round2(netProfit), netProfitMarginPct, }; } /** 冻结导出,降低运行时被挂属性篡改的风险 */ Object.freeze(computeFinanceNetProfit);