来源:review-20261015/B §6-C/§6-D(真跑评审 P1)。D2 已于 2026-10-14 获批准修改, 但上一轮**只改了负毛利告警、漏了毛利分析列表**;开发者 2026-10-15「可以开始修复」⇒ 本次补完。 属 finance-freeze 面、在已批准范围内;口径变更成对落地(聚合 ↔ 文档 ↔ 契约测试 ↔ 改前改后数字)。 根因:queryMarginRows(毛利分析列表)的 order/customer/sku 三个维度仍引用旧常量 ORDER_ITEM_UNIT_COST_AMOUNT_SQL —— 它用 **KPI 版**去重判据,把(订单×SKU)的抵扣结转行 (cost_source='inventory_cover')当"正式采购行",从而把缺口自采的 unit_cost_sync 占位行整块剔除。 上一轮只把负毛利计数/告警换成了新常量 ORDER_ITEM_MARGIN_COST_AMOUNT_SQL。 改法: · 三个维度查询统一改用 ORDER_ITEM_MARGIN_COST_AMOUNT_SQL(与告警面同源); · 旧常量全仓已无调用方(唯一用户就是这三处)⇒ 删除,并把新常量注释重写为自述 + 记录本次补完; · 不动共享判据 excludePurchaseDupesForKpiSql(本文件其它账本聚合仍在用)、销售额口径、分页排序。 改前 → 改后(真库同一窗口 20261014_20261015 / delivery_date、同一脚本、只读样本单): · 面7b 毛利分析列表 Σtotal_cost:557.50 → 654.50 · 样本单 ORD_API_20261014_BR002_0001:241.50 → 338.50(差额精确 = ¥97.00) · 改后 面2 getCostAggregation = 面6 成本明细页 Σ = 面7b 列表 Σ = 654.50(三面逐值相等) · 第 7 面内部(告警 vs 列表)现共用同一常量 ⇒ 不再"告警判负、列表判正" 测试:partialCoverLedgerCaliber.test.ts 的 ③④ 重写 —— **原 ③ 把缺陷当契约钉住了** (断言 "const ORDER_ITEM_UNIT_COST_AMOUNT_SQL" 必须存在、该常量引用数 ≥4,而那三处引用 正是"列表用旧判据"这个漏点;上一轮把它误标成"账本窗口,作用域不得扩散")。 现 ③ 要求毛利面全部落点用新常量(≥6)且**旧常量不得再出现**(ratchet:谁把列表改回旧判据就红); ④ 改为校验新常量行匹配口径不变 + 去重判据是毛利版。①②(判据本身)不变。 验证:server tsc 0 error;vitest 25 failed / 3010 passed(445 文件)——失败文件数与基线 25、 失败用例数与基线 32 一致,无新增;设计门禁 8 通过 / 1 红(check-ai-cost) / 1 未执行,与改动前同基线。 设计:docs/design/20261015-毛利分析列表补完D2(订单行成本换用毛利面判据).md
3125 lines
135 KiB
TypeScript
3125 lines
135 KiB
TypeScript
import { pool } from '../db';
|
||
import { salesVisibleOrderSql } from './independentInbound';
|
||
import type { TenantContext } from './tenantScope';
|
||
import { customerStatementSharedFiltersSql } from './financeReconciliationService';
|
||
import { statementHasLiveOrderLinkSql } from './statementScopeSql';
|
||
import {
|
||
computeFinanceNetProfit,
|
||
NET_PROFIT_FORMULA_ID,
|
||
NET_PROFIT_FORMULA_LABEL,
|
||
PERIOD_FIXED_COST_SQL_PREDICATE,
|
||
} from './financeNetProfitFormula';
|
||
import {
|
||
excludeInventoryHoldingFromKpiSql,
|
||
excludePurchaseDupesForKpiSql,
|
||
excludePurchaseDupesForOrderMarginSql,
|
||
purchaseCostBucketExpr,
|
||
purchaseSelfAmountSql,
|
||
purchaseSupplierAmountSql,
|
||
purchaseStockCoverAmountSql,
|
||
costEffectiveAmountSql,
|
||
} from './purchaseCostBucketSql';
|
||
import {
|
||
ORDER_ITEM_REVENUE_SQL,
|
||
salesItemPredicateSql,
|
||
salesLinePredicateSql,
|
||
salesOrderPredicateSql,
|
||
} from './orderItemRevenueSql';
|
||
// 订单行供应商第三个取值「库存抵扣」(2026-10-14,见 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1)
|
||
import { STOCK_COVER_SUPPLIER_CODE } from './allocationRules';
|
||
// 入库日表达式 / JOIN 与过账扣点周期聚合共用同一份,勿各写一份
|
||
import { ORDER_DONE_DAY_SQL, ORDER_INBOUND_JOIN_SQL } from './orderInboundDateSql';
|
||
import type { RebateDateField } from './customerRebateService';
|
||
|
||
/** 直接成本:采购 + 加工 + 配送 + 损耗 */
|
||
export const DIRECT_COST_TYPES = new Set([
|
||
'purchase',
|
||
'purchase_applied',
|
||
'processing',
|
||
'delivery',
|
||
'loss',
|
||
]);
|
||
|
||
/** 间接-固定:仓储、管理等 */
|
||
export const FIXED_INDIRECT_TYPES = new Set(['overhead', 'warehouse']);
|
||
|
||
/** 间接-变动:人工、运输、包材等 */
|
||
export const VARIABLE_INDIRECT_TYPES = new Set([
|
||
'labor_sorting',
|
||
'labor_processing',
|
||
'labor',
|
||
'transport',
|
||
'packaging',
|
||
]);
|
||
|
||
export const FREE_COST_TYPE = 'free_overhead';
|
||
|
||
function branchFilter(ctx: TenantContext | null | undefined, alias: string, params: unknown[]) {
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
params.push(ctx.branchCode);
|
||
return `AND ${alias}.branch_code = $${params.length}`;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
function classifyCostBucket(costType: string): 'direct' | 'fixed' | 'variable' | 'free' | 'other' {
|
||
if (DIRECT_COST_TYPES.has(costType)) return 'direct';
|
||
if (costType === FREE_COST_TYPE) return 'free';
|
||
if (FIXED_INDIRECT_TYPES.has(costType)) return 'fixed';
|
||
if (VARIABLE_INDIRECT_TYPES.has(costType)) return 'variable';
|
||
if (costType === 'refund') return 'other';
|
||
return 'variable';
|
||
}
|
||
|
||
export interface CostAggregation {
|
||
cycle_code: string;
|
||
revenue: number;
|
||
direct_cost: number;
|
||
indirect_fixed: number;
|
||
indirect_variable: number;
|
||
free_cost: number;
|
||
other_cost: number;
|
||
total_cost: number;
|
||
gross_profit: number;
|
||
gross_margin_pct: number;
|
||
negative_margin_orders: number;
|
||
/** 采购成本来源拆分 */
|
||
purchase_self: number;
|
||
purchase_supplier: number;
|
||
}
|
||
|
||
export interface MarginRow {
|
||
key: string;
|
||
label: string;
|
||
revenue: number;
|
||
total_cost: number;
|
||
gross_profit: number;
|
||
gross_margin_pct: number;
|
||
order_count?: number;
|
||
/** 按商品:销量(结算/计价数量合计) */
|
||
quantity?: number;
|
||
/** 按商品:履约量(验收实收优先,否则备货量,再否则结算量) */
|
||
fulfilled_qty?: number;
|
||
/** 按商品:加权销售单价 = revenue / quantity */
|
||
sale_price?: number;
|
||
/** 按商品:加权成本单价 = total_cost / fulfilled_qty(过手对齐实采) */
|
||
cost_price?: number;
|
||
}
|
||
|
||
function round2(n: number) {
|
||
return Math.round(n * 100) / 100;
|
||
}
|
||
|
||
/**
|
||
* 解析周期/区间标识为日期范围。
|
||
* 支持:'YYYYMMDD_YYYYMMDD'(自定义区间)/ 'YYYYMMDD'(单日)/ 'YYYYMM'(整月,向后兼容)。
|
||
* 返回 { from, to }(YYYY-MM-DD);无法解析返回 null。
|
||
*/
|
||
export function parseCycleToDateRange(cycleCode: string): { from: string; to: string } | null {
|
||
const raw = String(cycleCode || '').trim();
|
||
const rangeMatch = /^(\d{4})(\d{2})(\d{2})_(\d{4})(\d{2})(\d{2})$/.exec(raw);
|
||
if (rangeMatch) {
|
||
return {
|
||
from: `${rangeMatch[1]}-${rangeMatch[2]}-${rangeMatch[3]}`,
|
||
to: `${rangeMatch[4]}-${rangeMatch[5]}-${rangeMatch[6]}`,
|
||
};
|
||
}
|
||
const dayMatch = /^(\d{4})(\d{2})(\d{2})$/.exec(raw);
|
||
if (dayMatch) {
|
||
const d = `${dayMatch[1]}-${dayMatch[2]}-${dayMatch[3]}`;
|
||
return { from: d, to: d };
|
||
}
|
||
const monthMatch = /^(\d{4})(\d{2})$/.exec(raw);
|
||
if (monthMatch) {
|
||
const from = `${monthMatch[1]}-${monthMatch[2]}-01`;
|
||
const y = Number(monthMatch[1]);
|
||
const m = Number(monthMatch[2]);
|
||
const last = new Date(Date.UTC(y, m, 0)).getUTCDate();
|
||
return { from, to: `${monthMatch[1]}-${monthMatch[2]}-${String(last).padStart(2, '0')}` };
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/** 是否为新日期区间格式(YYYYMMDD_YYYYMMDD 或 YYYYMMDD)。YYYYMM 走旧 cycle_code 精确匹配以保证零回归。 */
|
||
function isDateRangeCycle(cycleCode: string): boolean {
|
||
const raw = String(cycleCode || '').trim();
|
||
return /^\d{8}_\d{8}$/.test(raw) || /^\d{8}$/.test(raw);
|
||
}
|
||
|
||
|
||
/** 财务概览/成本管理日期维度(与结算页一致;默认配送日) */
|
||
export type FinanceDateField = 'delivery_date' | 'created_at' | 'inbound';
|
||
|
||
export function normalizeFinanceDateField(raw?: string | null): FinanceDateField {
|
||
const v = String(raw || '').trim().toLowerCase();
|
||
if (v === 'created_at' || v === 'order' || v === 'order_date') return 'created_at';
|
||
if (v === 'inbound' || v === 'posting' || v === '入库' || v === '入账') return 'inbound';
|
||
return 'delivery_date';
|
||
}
|
||
|
||
/** 订单日表达式(alias 固定 `o`;inbound 需附带 ORDER_INBOUND_JOIN_SQL) */
|
||
function orderFinanceDaySql(field: FinanceDateField): string {
|
||
if (field === 'created_at') return `(o.created_at AT TIME ZONE 'Asia/Shanghai')::date`;
|
||
if (field === 'delivery_date') return `o.delivery_date`;
|
||
return `(${ORDER_DONE_DAY_SQL})::date`;
|
||
}
|
||
|
||
export function orderFinanceJoinSql(field: FinanceDateField, useDateRange: boolean): string {
|
||
if (!useDateRange) return '';
|
||
return field === 'inbound' ? ORDER_INBOUND_JOIN_SQL : '';
|
||
}
|
||
|
||
/** 区间模式订单日条件(含首尾日历日) */
|
||
export function orderFinanceRangeCondSql(
|
||
field: FinanceDateField,
|
||
fromIdx: number,
|
||
toIdx: number
|
||
): string {
|
||
const day = orderFinanceDaySql(field);
|
||
if (field === 'delivery_date') {
|
||
return `${day} IS NOT NULL AND ${day} >= $${fromIdx}::date AND ${day} <= $${toIdx}::date`;
|
||
}
|
||
return `${day} >= $${fromIdx}::date AND ${day} <= $${toIdx}::date`;
|
||
}
|
||
|
||
/**
|
||
* 2A:有 order_code 的成本跟订单日;无订单号跟入账日。
|
||
* fromIdx/toIdx 为 params 中日历日起止下标。
|
||
*/
|
||
export function costDetailsLinkedOrPeriodCondSql(
|
||
field: FinanceDateField,
|
||
fromIdx: number,
|
||
toIdx: number
|
||
): string {
|
||
const join = field === 'inbound' ? ORDER_INBOUND_JOIN_SQL : '';
|
||
const orderCond = orderFinanceRangeCondSql(field, fromIdx, toIdx);
|
||
const posted = `(cd.created_at AT TIME ZONE 'Asia/Shanghai')::date >= $${fromIdx}::date AND (cd.created_at AT TIME ZONE 'Asia/Shanghai')::date <= $${toIdx}::date`;
|
||
return `(
|
||
(
|
||
(cd.order_code IS NULL OR TRIM(cd.order_code) = '')
|
||
AND ${posted}
|
||
)
|
||
OR (
|
||
cd.order_code IS NOT NULL AND TRIM(cd.order_code) <> ''
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o
|
||
${join}
|
||
WHERE o.order_code = cd.order_code
|
||
AND o.deleted_at IS NULL
|
||
AND ${orderCond}
|
||
)
|
||
)
|
||
)`;
|
||
}
|
||
|
||
/** 规范化客户筛选码;空 = 全部客户 */
|
||
export function normalizeCustomerCodeFilter(raw?: string | null): string | null {
|
||
const code = String(raw || '').trim();
|
||
return code || null;
|
||
}
|
||
|
||
/**
|
||
* 选客户时:仅保留挂到该客户订单的 cost_details(排除无单号期间固定/其他)。
|
||
* 会 push 到 params,返回 AND 片段(可能为空串)。
|
||
*/
|
||
export function costDetailsCustomerFilterSql(
|
||
customerCode: string | null | undefined,
|
||
params: unknown[],
|
||
cdAlias = 'cd'
|
||
): string {
|
||
const code = normalizeCustomerCodeFilter(customerCode);
|
||
if (!code) return '';
|
||
params.push(code);
|
||
const idx = params.length;
|
||
return ` AND ${cdAlias}.order_code IS NOT NULL AND TRIM(${cdAlias}.order_code) <> ''
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o_cf
|
||
WHERE o_cf.order_code = ${cdAlias}.order_code
|
||
AND o_cf.deleted_at IS NULL
|
||
AND o_cf.customer_code = $${idx}
|
||
)`;
|
||
}
|
||
|
||
/** 订单表客户筛选;会 push 到 params */
|
||
export function ordersCustomerFilterSql(
|
||
customerCode: string | null | undefined,
|
||
params: unknown[],
|
||
orderAlias = 'o'
|
||
): string {
|
||
const code = normalizeCustomerCodeFilter(customerCode);
|
||
if (!code) return '';
|
||
params.push(code);
|
||
return ` AND ${orderAlias}.customer_code = $${params.length}`;
|
||
}
|
||
|
||
/**
|
||
* 同一 params 数组内只 push 一次客户码,供订单侧与 cost_details 侧共用 $n。
|
||
* 空客户时两片段均为 ''(全部客户零回归)。
|
||
*/
|
||
export function bindSharedCustomerFilterSql(
|
||
customerCode: string | null | undefined,
|
||
params: unknown[],
|
||
opts?: { orderAlias?: string; cdAlias?: string }
|
||
): { ordersSql: string; costDetailsSql: string } {
|
||
const code = normalizeCustomerCodeFilter(customerCode);
|
||
if (!code) return { ordersSql: '', costDetailsSql: '' };
|
||
params.push(code);
|
||
const idx = params.length;
|
||
const orderAlias = opts?.orderAlias ?? 'o';
|
||
const cdAlias = opts?.cdAlias ?? 'cd';
|
||
return {
|
||
ordersSql: ` AND ${orderAlias}.customer_code = $${idx}`,
|
||
costDetailsSql: ` AND ${cdAlias}.order_code IS NOT NULL AND TRIM(${cdAlias}.order_code) <> ''
|
||
AND EXISTS (
|
||
SELECT 1 FROM orders o_cf
|
||
WHERE o_cf.order_code = ${cdAlias}.order_code
|
||
AND o_cf.deleted_at IS NULL
|
||
AND o_cf.customer_code = $${idx}
|
||
)`,
|
||
};
|
||
}
|
||
|
||
/** 周期成本归集:直接 / 间接(固定+变动)/ 自由 */
|
||
export async function getCostAggregation(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
): Promise<CostAggregation> {
|
||
// 新日期区间格式:订单侧按 date_field;无订单期间成本按入账日;YYYYMM 走旧 cycle_code 精确匹配(零回归)
|
||
const useDateRange = isDateRangeCycle(cycleCode);
|
||
const dateRange = useDateRange ? parseCycleToDateRange(cycleCode) : null;
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const customerFilter = normalizeCustomerCodeFilter(customerCode);
|
||
|
||
// 统一参数构造:区间模式 params=[from,to],条件用 $1/$2;YYYYMM params=[cycleCode],条件用 $1
|
||
const baseParams: unknown[] = useDateRange && dateRange ? [dateRange.from, dateRange.to] : [cycleCode];
|
||
const cdDateCond =
|
||
useDateRange && dateRange
|
||
? costDetailsLinkedOrPeriodCondSql(dateField, 1, 2)
|
||
: `cd.cycle_code = $1`;
|
||
// 孤儿成本排除:区间模式不再比对 o.cycle_code(订单周期是下单月,与入账区间无关),只排除已删除订单
|
||
const cdOrphanCond = useDateRange
|
||
? `(cd.order_code IS NULL OR EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code AND o.deleted_at IS NULL))`
|
||
: `(cd.order_code IS NULL OR EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code AND o.cycle_code = cd.cycle_code AND o.deleted_at IS NULL))`;
|
||
|
||
// 订单过滤条件(date_field vs cycle_code),同样用 $1/$2
|
||
const orderDateJoin = orderFinanceJoinSql(dateField, Boolean(useDateRange && dateRange));
|
||
const orderDateCond =
|
||
useDateRange && dateRange
|
||
? orderFinanceRangeCondSql(dateField, 1, 2)
|
||
: `o.cycle_code = $1`;
|
||
|
||
// 排除已删除订单的孤儿成本行,避免虚增高成本 / 假负毛利
|
||
const costParams = [...baseParams];
|
||
const costBranch = branchFilter(ctx, 'cd', costParams);
|
||
const costCustomer = costDetailsCustomerFilterSql(customerFilter, costParams);
|
||
const excludeSync = excludePurchaseDupesForKpiSql('cd');
|
||
const excludeHolding = excludeInventoryHoldingFromKpiSql('cd');
|
||
const costRows = await pool.query(
|
||
`SELECT COALESCE(cd.cost_type, 'overhead') AS cost_type,
|
||
COALESCE(cd.cost_source, '') AS cost_source,
|
||
SUM(${CD_EFFECTIVE_AMOUNT_SQL})::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE ${cdDateCond} ${costBranch}
|
||
AND ${cdOrphanCond}
|
||
AND ${excludeSync}
|
||
AND ${excludeHolding}
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
AND ${excludeInventoryHoldingFromKpiSql('cd')}
|
||
${costCustomer}
|
||
GROUP BY cd.cost_type, cd.cost_source`,
|
||
costParams
|
||
);
|
||
|
||
// 采购成本与商品成本页统一:订单行实时数量×成本价;仓内加工成品成本固定为 0。
|
||
// 独立自采入库无订单归属,单独叠加;其它费用仍从 cost_details 账本读取。
|
||
// purchaseCostBucketExpr 仅保留用于历史账本分桶兼容,实时采购不再依赖其金额。
|
||
const sourceParams = [...baseParams];
|
||
const sourceBranchIdx = resolveBranchParam(ctx, sourceParams);
|
||
const sourceBranchO = branchEq('o', sourceBranchIdx);
|
||
const sourceCustomer = ordersCustomerFilterSql(customerFilter, sourceParams);
|
||
const sourceOrderRows = await pool.query(
|
||
`SELECT CASE
|
||
WHEN LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料' THEN 'self'
|
||
WHEN NULLIF(TRIM(COALESCE(oi.supplier_code, '')), '') IS NULL THEN 'self'
|
||
WHEN UPPER(TRIM(oi.supplier_code)) IN ('INTERNAL', 'UNASSIGNED') THEN 'self'
|
||
ELSE 'supplier' END AS cost_bucket,
|
||
COALESCE(SUM(CASE
|
||
WHEN LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料' THEN 0
|
||
ELSE GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.stock_cover_qty, 0)) * COALESCE(oi.unit_cost, 0) END), 0)::numeric AS total
|
||
FROM orders o JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
WHERE ${orderDateCond} AND o.order_status >= 20 AND o.deleted_at IS NULL
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
|
||
/**
|
||
* **独立进货单自身的成本不进任何成本面**(开发者 2026-10-14):
|
||
* 它只是补库存(把货搬进仓库)——成本要在后续订单**抵扣**时才认(见上面的放行分支);
|
||
* 复用销售侧既有判据 salesVisibleOrderSql(与「订单商品成本」页同源,不新造口径)。
|
||
*/
|
||
AND ${salesVisibleOrderSql('o')}
|
||
${sourceBranchO} ${sourceCustomer}
|
||
GROUP BY 1`,
|
||
sourceParams
|
||
);
|
||
let purchaseSelf = 0;
|
||
let purchaseSupplier = 0;
|
||
for (const row of sourceOrderRows.rows) {
|
||
const amt = Number(row.total) || 0;
|
||
if (String(row.cost_bucket) === 'self') purchaseSelf += amt;
|
||
else purchaseSupplier += amt;
|
||
}
|
||
// 独立自采入库计入自采采购成本(客户筛选时不混入)。
|
||
if (!customerFilter) {
|
||
const independentParams: unknown[] = [...baseParams];
|
||
const independentBranch = ctx?.branchCode && !ctx.isSuperAdmin
|
||
? (independentParams.push(ctx.branchCode), `AND spi.branch_code = $${independentParams.length}`)
|
||
: '';
|
||
const independentDate = useDateRange && dateRange
|
||
? `spi.created_at IS NOT NULL AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date >= $1::date AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date <= $2::date`
|
||
: `TO_CHAR(spi.created_at AT TIME ZONE 'Asia/Shanghai', 'YYYYMM') = $1`;
|
||
const independentResult = await pool.query(
|
||
`SELECT COALESCE(SUM(COALESCE(spi.total_amount, COALESCE(spi.qty, 0) * COALESCE(spi.unit_cost, 0))), 0)::numeric AS total
|
||
FROM self_purchase_stock_inbounds spi
|
||
WHERE spi.voided_at IS NULL AND COALESCE(spi.qty, 0) > 0 AND COALESCE(spi.unit_cost, 0) > 0
|
||
AND ${independentDate} ${independentBranch}`,
|
||
independentParams
|
||
);
|
||
purchaseSelf += Number(independentResult.rows[0]?.total) || 0;
|
||
}
|
||
const purchaseTotal = purchaseSelf + purchaseSupplier;
|
||
|
||
let direct = 0;
|
||
let fixed = 0;
|
||
let variable = 0;
|
||
let free = 0;
|
||
let other = 0;
|
||
/** 账本里的**库存抵扣**金额(采购成本的第三部分,见下方 quoteProfit) */
|
||
let stockCoverCost = 0;
|
||
|
||
for (const row of costRows.rows) {
|
||
const type = String(row.cost_type);
|
||
const amt = Number(row.total) || 0;
|
||
/**
|
||
* **库存抵扣成本必须计入**(开发者 2026-10-14):
|
||
* 独立进货只是"把货搬进仓库"(其自身成本**不进任何成本**,见下一条实时采购排除),
|
||
* 这笔钱要在**后续订单把它抵扣掉**时才成为成本 ⇒ 抵扣账本行
|
||
* (`cost_type='purchase', cost_source='inventory_cover'`)**不能**跟着采购行一起跳过;
|
||
* 跳过它就等于"进货不认、消耗也不认",净利会虚高。
|
||
*/
|
||
const isInventoryCover = String(row.cost_source || '') === 'inventory_cover';
|
||
// 采购已按订单行实时口径计算,不能再把旧采购账本金额计入总成本(库存抵扣行除外)。
|
||
if (CD_PURCHASE_TYPES_SQL.includes(type) && !isInventoryCover) continue;
|
||
if (isInventoryCover) stockCoverCost += amt;
|
||
const bucket = classifyCostBucket(type);
|
||
if (bucket === 'direct') direct += amt;
|
||
else if (bucket === 'fixed') fixed += amt;
|
||
else if (bucket === 'free') free += amt;
|
||
else if (bucket === 'other') other += amt;
|
||
else variable += amt;
|
||
}
|
||
direct += purchaseTotal;
|
||
|
||
// 营收与财务概览「销售额」同口径:录单起(status≥20)明细售价合计;守卫见 salesLinePredicateSql
|
||
const revParams = [...baseParams];
|
||
const revBranch = branchFilter(ctx, 'o', revParams);
|
||
const revCustomer = ordersCustomerFilterSql(customerFilter, revParams);
|
||
const revenueResult = await pool.query(
|
||
`SELECT COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
WHERE ${orderDateCond} AND ${salesLinePredicateSql('o', 'oi')} ${revBranch}
|
||
${revCustomer}`,
|
||
revParams
|
||
);
|
||
const revenue = Number(revenueResult.rows[0]?.revenue) || 0;
|
||
const totalCost = direct + fixed + variable + free + other;
|
||
|
||
/**
|
||
* **毛利/毛利率的基数是「采购成本」= 自采 + 供应商 + 库存抵扣**(开发者 2026-10-14 口径定稿;
|
||
* 财务冻结条款:毛利率=(销售额 − 采购成本) ÷ 销售额,**禁止**写成 采购/销售)。
|
||
*
|
||
* 改前用 `purchaseTotal`(只有自采+供应商两支),而同一函数的「总成本」`direct` 已经把抵扣算进去
|
||
* ⇒ 卡片自己和自己对不上:实测 BR002 显示「总成本 ¥256 / 毛利 ¥385」(482−256=226 ≠ 385)。
|
||
* 改后毛利 226、毛利率 46.9%。
|
||
*/
|
||
const purchaseCostAll = round2(purchaseTotal + stockCoverCost);
|
||
const quoteProfit = revenue - purchaseCostAll;
|
||
const grossMarginPct = revenue > 0 ? round2((quoteProfit / revenue) * 100) : 0;
|
||
|
||
const negParams = [...baseParams];
|
||
const negBranchIdx = resolveBranchParam(ctx, negParams);
|
||
const negBranchO = branchEq('o', negBranchIdx);
|
||
const negCustomer = ordersCustomerFilterSql(customerFilter, negParams);
|
||
const negResult = await pool.query(
|
||
`SELECT COUNT(*)::int AS cnt
|
||
FROM (
|
||
SELECT o.order_code,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS order_revenue,
|
||
COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)::numeric AS order_cost
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
WHERE ${orderDateCond} AND ${salesLinePredicateSql('o', 'oi')} ${negBranchO}
|
||
${negCustomer}
|
||
GROUP BY o.order_code
|
||
HAVING COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) > 0
|
||
AND COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) < COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)
|
||
) neg`,
|
||
negParams
|
||
);
|
||
|
||
return {
|
||
cycle_code: cycleCode,
|
||
revenue: round2(revenue),
|
||
direct_cost: round2(direct),
|
||
indirect_fixed: round2(fixed),
|
||
indirect_variable: round2(variable),
|
||
free_cost: round2(free),
|
||
other_cost: round2(other),
|
||
total_cost: round2(totalCost),
|
||
gross_profit: round2(quoteProfit),
|
||
gross_margin_pct: grossMarginPct,
|
||
negative_margin_orders: Number(negResult.rows[0]?.cnt) || 0,
|
||
purchase_self: round2(purchaseSelf),
|
||
purchase_supplier: round2(purchaseSupplier),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 订单成本明细(**订单口径**):2A 窗内按订单商品现算 order_items.quantity × unit_cost,
|
||
* 并叠加非采购类账本行(损耗/加工/分摊等)与独立自采。
|
||
*
|
||
* ⚠️ 与 getPurchaseCostLedgerWindow 是**两套不同业务含义的口径,不是同一指标的两个算法**:
|
||
* 本函数 = 订单的成本;getPurchaseCostLedgerWindow = 当日采购的成本。
|
||
* 两者金额不同属正常,勿相互对齐、勿混用。
|
||
*/
|
||
export async function listOrderCostDetailsInWindow(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
dateFieldRaw?: string | null,
|
||
limit = 5000,
|
||
customerCode?: string | null
|
||
): Promise<
|
||
Array<{
|
||
id: string;
|
||
cycle_code: string | null;
|
||
order_code: string | null;
|
||
sku_code: string | null;
|
||
sku_name: string | null;
|
||
cost_type: string | null;
|
||
cost_subtype: string | null;
|
||
amount: number;
|
||
allocated_amount: number | null;
|
||
allocation_method: string | null;
|
||
reference_type: string | null;
|
||
cost_source: string | null;
|
||
remark: string | null;
|
||
status: number | null;
|
||
created_at: string | null;
|
||
order_item_id?: string | null;
|
||
}>
|
||
> {
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const useDateRange = isDateRangeCycle(cycleCode);
|
||
const dateRange = useDateRange ? parseCycleToDateRange(cycleCode) : null;
|
||
const safeLimit = Math.min(Math.max(Number(limit) || 5000, 1), 10000);
|
||
const params: unknown[] = useDateRange && dateRange ? [dateRange.from, dateRange.to] : [cycleCode];
|
||
const branch = branchFilter(ctx, 'cd', params);
|
||
const branchParamIdx = ctx?.branchCode && !ctx.isSuperAdmin ? params.length : null;
|
||
const customerSql = costDetailsCustomerFilterSql(customerCode, params);
|
||
const customerParamIdx = customerCode && String(customerCode).trim() ? params.length : null;
|
||
const independentBranch = ctx?.branchCode && !ctx.isSuperAdmin ? `AND spi.branch_code = $${branchParamIdx}` : '';
|
||
// 独立自采没有客户/订单归属;筛选某个客户时不混入该客户成本。
|
||
const independentCustomer = customerParamIdx ? 'AND FALSE' : '';
|
||
params.push(safeLimit);
|
||
const limitIdx = params.length;
|
||
|
||
const cdDateCond =
|
||
useDateRange && dateRange
|
||
? costDetailsLinkedOrPeriodCondSql(dateField, 1, 2)
|
||
: `cd.cycle_code = $1`;
|
||
const cdOrphanCond = useDateRange
|
||
? `(cd.order_code IS NULL OR EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code AND o.deleted_at IS NULL))`
|
||
: `(cd.order_code IS NULL OR EXISTS (SELECT 1 FROM orders o WHERE o.order_code = cd.order_code AND o.cycle_code = cd.cycle_code AND o.deleted_at IS NULL))`;
|
||
|
||
const runtimeOrderCond = useDateRange && dateRange
|
||
? orderFinanceRangeCondSql(dateField, 1, 2)
|
||
: 'o.cycle_code = $1';
|
||
const runtimeOrderJoin = useDateRange && dateField === 'inbound' ? ORDER_INBOUND_JOIN_SQL : '';
|
||
const runtimeBranch = branchParamIdx ? `AND o.branch_code = $${branchParamIdx}` : '';
|
||
const runtimeCustomer = customerParamIdx ? `AND o.customer_code = $${customerParamIdx}` : '';
|
||
const r = await pool.query(
|
||
`WITH runtime_order_costs AS (
|
||
SELECT oi.id::text AS id, o.cycle_code, o.order_code, oi.sku_code,
|
||
COALESCE(sk.sku_name, oi.item_name, oi.sku_code) AS sku_name,
|
||
'purchase'::text AS cost_type,
|
||
CASE WHEN LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料'
|
||
THEN 'processing_finished' ELSE 'order_goods' END AS cost_subtype,
|
||
CASE WHEN LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料'
|
||
THEN 0
|
||
ELSE GREATEST(0, COALESCE(oi.quantity, 0) - COALESCE(oi.stock_cover_qty, 0)) * COALESCE(oi.unit_cost, 0) END AS amount,
|
||
NULL::numeric AS allocated_amount, 'sku'::text AS allocation_method,
|
||
'order_item'::text AS reference_type, 'runtime_order_item'::text AS cost_source,
|
||
NULL::text AS remark, 20::int AS status, oi.created_at, oi.id::text AS order_item_id
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${runtimeOrderJoin}
|
||
LEFT JOIN skus sk ON sk.sku_code = oi.sku_code
|
||
WHERE ${runtimeOrderCond} AND o.deleted_at IS NULL
|
||
${runtimeBranch} ${runtimeCustomer}
|
||
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
|
||
AND COALESCE(oi.is_returned, false) = false
|
||
/**
|
||
* **独立进货单自身不进成本明细**(与成本页/商品成本页同一判据,2026-10-14):
|
||
* 它只是把货搬进仓库,成本要在后续订单**抵扣**时认(抵扣账本行由上面的账本分支给出)。
|
||
* 漏了这条 ⇒ 同一批货在明细里出现两次(独立进货行 + 抵扣账本行),
|
||
* 实测 BR002:明细 ¥415(97 缺口 + 159 抵扣 + 159 独立进货)而成本页是 ¥256。
|
||
*/
|
||
AND ${salesVisibleOrderSql('o')}
|
||
), independent_self_costs AS (
|
||
SELECT spi.id::text AS id,
|
||
CASE WHEN spi.created_at IS NOT NULL
|
||
THEN TO_CHAR(spi.created_at AT TIME ZONE 'Asia/Shanghai', 'YYYYMM')
|
||
ELSE TO_CHAR(CURRENT_DATE, 'YYYYMM') END AS cycle_code,
|
||
NULL::text AS order_code,
|
||
spi.sku_code,
|
||
COALESCE(NULLIF(TRIM(spi.sku_name), ''), spi.sku_code) AS sku_name,
|
||
'purchase'::text AS cost_type,
|
||
'self_purchase_inbound'::text AS cost_subtype,
|
||
COALESCE(spi.total_amount, COALESCE(spi.qty, 0) * COALESCE(spi.unit_cost, 0))::numeric AS amount,
|
||
NULL::numeric AS allocated_amount,
|
||
'self_purchase'::text AS allocation_method,
|
||
'self_purchase_stock_inbound'::text AS reference_type,
|
||
'self_purchase'::text AS cost_source,
|
||
COALESCE(NULLIF(TRIM(spi.remark), ''), '独立自采入库') AS remark,
|
||
20::int AS status,
|
||
spi.created_at,
|
||
NULL::text AS order_item_id
|
||
FROM self_purchase_stock_inbounds spi
|
||
WHERE spi.voided_at IS NULL
|
||
${independentBranch}
|
||
${independentCustomer}
|
||
AND COALESCE(spi.qty, 0) > 0
|
||
AND COALESCE(spi.unit_cost, 0) > 0
|
||
AND ${useDateRange && dateRange
|
||
? `spi.created_at IS NOT NULL AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date >= $1::date AND (spi.created_at AT TIME ZONE 'Asia/Shanghai')::date <= $2::date`
|
||
: `TO_CHAR(spi.created_at AT TIME ZONE 'Asia/Shanghai', 'YYYYMM') = $1`}
|
||
), combined AS (
|
||
SELECT cd.id::text, cd.cycle_code, cd.order_code, cd.sku_code, sk.sku_name,
|
||
cd.cost_type, cd.cost_subtype,
|
||
COALESCE(cd.amount, 0)::numeric AS amount,
|
||
cd.allocated_amount,
|
||
cd.allocation_method, cd.reference_type, cd.cost_source, cd.remark, cd.status,
|
||
cd.created_at, cd.order_item_id::text
|
||
FROM cost_details cd
|
||
LEFT JOIN skus sk ON sk.sku_code = cd.sku_code
|
||
WHERE ${cdDateCond}
|
||
AND ${cdOrphanCond}
|
||
AND ${excludePurchaseDupesForKpiSql('cd')}
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
-- unit_cost_sync 仅为旧占位:有对应订单商品时由 runtime_order_costs 实时生成,避免金额过期/重复
|
||
AND NOT (
|
||
COALESCE(cd.remark, '') = 'unit_cost_sync'
|
||
AND EXISTS (
|
||
SELECT 1 FROM order_items oi_rt
|
||
WHERE oi_rt.order_code = cd.order_code
|
||
AND oi_rt.sku_code IS NOT DISTINCT FROM cd.sku_code
|
||
AND COALESCE(oi_rt.is_returned, false) = false
|
||
)
|
||
)
|
||
-- 采购类金额统一由 cost_details 账本提供,去重规则负责排除
|
||
-- 旧验收入库和同步占位行,避免同一商品重复计算。
|
||
-- ⚠️ **库存抵扣行必须放行**(2026-10-14 开发者报障:「明细这块 为什么全是采购成本
|
||
-- 其中部分不是库存抵扣成本吗」):它的 cost_type 也是 'purchase',被这条整类丢掉的后果是
|
||
-- 明细里**看不到库存抵扣成本**(实测 BR002:抵扣 ¥159 一行都没有,只有缺口 ¥97);
|
||
-- 明细「类型」列按 cost_source 把它显示成「库存抵扣成本」。
|
||
AND (
|
||
cd.cost_type NOT IN ('purchase', 'purchase_applied')
|
||
OR COALESCE(cd.cost_source, '') = 'inventory_cover'
|
||
)
|
||
${branch}
|
||
${customerSql}
|
||
UNION ALL
|
||
SELECT id, cycle_code, order_code, sku_code, sku_name, cost_type, cost_subtype,
|
||
amount, allocated_amount, allocation_method, reference_type, cost_source,
|
||
remark, status, created_at, order_item_id
|
||
FROM runtime_order_costs
|
||
UNION ALL
|
||
SELECT id, cycle_code, order_code, sku_code, sku_name, cost_type, cost_subtype,
|
||
amount, allocated_amount, allocation_method, reference_type, cost_source,
|
||
remark, status, created_at, order_item_id
|
||
FROM independent_self_costs
|
||
)
|
||
SELECT * FROM combined
|
||
ORDER BY created_at DESC NULLS LAST
|
||
LIMIT $${limitIdx}`,
|
||
params
|
||
);
|
||
|
||
return r.rows.map((row) => ({
|
||
id: String(row.id),
|
||
cycle_code: row.cycle_code == null ? null : String(row.cycle_code),
|
||
order_code: row.order_code == null ? null : String(row.order_code),
|
||
sku_code: row.sku_code == null || String(row.sku_code).trim() === '' ? null : String(row.sku_code),
|
||
sku_name: row.sku_name == null || String(row.sku_name).trim() === '' ? null : String(row.sku_name),
|
||
cost_type: row.cost_type == null ? null : String(row.cost_type),
|
||
cost_subtype: row.cost_subtype == null ? null : String(row.cost_subtype),
|
||
amount: Number(row.amount) || 0,
|
||
allocated_amount: row.allocated_amount == null ? null : Number(row.allocated_amount),
|
||
allocation_method: row.allocation_method == null ? null : String(row.allocation_method),
|
||
reference_type: row.reference_type == null ? null : String(row.reference_type),
|
||
cost_source: row.cost_source == null ? null : String(row.cost_source),
|
||
remark: row.remark == null ? null : String(row.remark),
|
||
status: row.status == null ? null : Number(row.status),
|
||
created_at: row.created_at == null ? null : String(row.created_at),
|
||
order_item_id: row.order_item_id == null ? null : String(row.order_item_id),
|
||
}));
|
||
}
|
||
|
||
function branchEq(alias: string, paramIndex: number | null) {
|
||
if (!paramIndex) return '';
|
||
return `AND ${alias}.branch_code = $${paramIndex}`;
|
||
}
|
||
|
||
function resolveBranchParam(ctx: TenantContext | null | undefined, params: unknown[]) {
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
params.push(ctx.branchCode);
|
||
return params.length;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 账本有效金额:采购行只认 amount,其它类型分摊优先。
|
||
* 见 purchaseCostBucketSql.costEffectiveAmountSql / docs/design/20260911-cost-follow-picking-actual.md
|
||
*/
|
||
const CD_EFFECTIVE_AMOUNT_SQL = costEffectiveAmountSql('cd');
|
||
|
||
/** 采购类(含 applied 标记行) */
|
||
const CD_PURCHASE_TYPES_SQL = `cd.cost_type IN ('purchase', 'purchase_applied')`;
|
||
|
||
/**
|
||
* **订单行成本(账本关联)**:订单行成本统一从 `cost_details` 读取。
|
||
* 新账本按 `order_item_id` 精确关联;历史账本行没有明细 ID 时只挂到
|
||
* 同单同 SKU 的首条有效明细,避免同一笔历史成本在多条明细上重复计算。
|
||
*
|
||
* ⚠️ 去重判据用 `excludePurchaseDupesForOrderMarginSql`:抵扣结转行(`inventory_cover`)
|
||
* **不算**"取代占位行的正式采购行"。原因:部分抵扣的行,抵扣只覆盖被抵那部分量,
|
||
* 缺口自采的 `unit_cost_sync` 行是真的成本,不能被抵扣行整块剔掉。
|
||
*
|
||
* 历史(2026-10-14 审核整改 D2 只改了一半,2026-10-15 补完):
|
||
* 原有两个常量,旧版 `ORDER_ITEM_UNIT_COST_AMOUNT_SQL` 用 KPI 版去重判据,把缺口自采整块剔掉 ——
|
||
* 负毛利**告警**换成了新判据,而**毛利分析列表**(`queryMarginRows` 的 order/customer/sku 三个维度)
|
||
* 还在用旧常量 ⇒ 同一张单两个结论(告警判负、列表判正)。
|
||
* 真库样本 `ORD_API_20261014_BR002_0001`:列表 **241.50 → 338.50**(纠正 3 行 21+45+31 = ¥97.00),
|
||
* 毛利率 60.10% → 44.07%。现在全文件已无旧常量的调用方,故**删除**它(只保留这个新口径)。
|
||
* 共享判据 `excludePurchaseDupesForKpiSql` 本文件其它账本聚合仍在用,未动。
|
||
*/
|
||
const ORDER_ITEM_MARGIN_COST_AMOUNT_SQL = `(SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric
|
||
FROM cost_details cd
|
||
WHERE ${CD_PURCHASE_TYPES_SQL}
|
||
AND cd.order_code = oi.order_code
|
||
AND cd.sku_code IS NOT DISTINCT FROM oi.sku_code
|
||
AND (
|
||
cd.order_item_id = oi.id
|
||
OR (
|
||
cd.order_item_id IS NULL
|
||
AND oi.id = (
|
||
SELECT MIN(oi_first.id::text)::uuid
|
||
FROM order_items oi_first
|
||
WHERE oi_first.order_code = oi.order_code
|
||
AND oi_first.sku_code IS NOT DISTINCT FROM oi.sku_code
|
||
AND COALESCE(oi_first.is_returned, false) = false
|
||
)
|
||
)
|
||
)
|
||
AND ${excludePurchaseDupesForOrderMarginSql('cd')}
|
||
AND COALESCE(cd.status, 20) >= 20)`;
|
||
|
||
/**
|
||
* 商品成本口径(2026-10-14 定稿,见
|
||
* docs/design/20261014-订单成本排除独立进货与库存成本分类.md §5.1):
|
||
* **采购金额 = 缺口量 × unit_cost**,抵扣那部分由「库存成本」(账本 `inventory_cover` 结转额)承担。
|
||
*
|
||
* 原常量 `ORDER_ITEM_CACHED_COST_AMOUNT_SQL`(全量 `quantity × unit_cost`)随列表页与导出
|
||
* 一并**删除**——它正是"部分抵扣的行把已抵扣那部分也按缺口价算成采购成本"的入口(30 斤抵 20、
|
||
* 采 10、缺口价 ¥3 ⇒ 原式 ¥90,实际采购只有 ¥30)。
|
||
*/
|
||
|
||
/**
|
||
* 商品成本列表展示归桶(不改一套账 expr)。
|
||
* 只看本行供应商列:未分配(空/`UNASSIGNED`)与自采(`INTERNAL`)→ 自采;其余 → 供应。
|
||
* 不看分类名、加菜、账本、采购单。见 docs/design/20260831-sku-cost-bucket-internal-self.md
|
||
*/
|
||
/**
|
||
* 仓内加工订单行判定(成品行)。仓内加工不另计成本:原材料成本由
|
||
* 「独立自采入库」或「库存领用」承担,成品行再计一次会重复
|
||
* (见 docs/design/20260914-overview-cost-order-line-purchase.md)。
|
||
*/
|
||
const WAREHOUSE_PROCESSING_LINE_SQL = `(LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料')`;
|
||
|
||
|
||
function skuListDisplayCostBucketSql(opts?: { gapOnly?: boolean }): string {
|
||
return `CASE
|
||
-- 仓内加工属于内部处理,即使订单保留了供应商编码也进入自采表。
|
||
WHEN LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料' THEN 'self'
|
||
/**
|
||
* **库存抵扣(第三桶)**,2026-10-14 开发者立项(见
|
||
* docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1.2):
|
||
* ① 写入点(applyStockCoverForOrderItem)对**全额抵扣**的行打了
|
||
* supplier_code = 'STOCK_COVER' 标记;
|
||
* ② 或**全额抵扣这件事本身**(stock_cover_qty >= quantity)。
|
||
* 取「或」是为了让写入点之前已全额抵扣的历史行直接进第三桶(**无需回填**),
|
||
* 而 stock_cover_qty > 0 兜住"释放后残留的标记"(那种行走下面的兜底分支)。
|
||
* 部分抵扣(0 < 抵扣量 < 需求)**不进**本桶:货一部分来自库存、一部分仍要采购,
|
||
* 故留在原桶用「采购成本 / 库存成本」两列区分(§5.1)。
|
||
*/
|
||
${opts?.gapOnly ? '-- 缺口段专用:抵扣量在抵扣段已经单独成行 ⇒ 这里恒不返回库存抵扣桶' : ''}
|
||
${opts?.gapOnly ? '' : `WHEN COALESCE(oi.stock_cover_qty, 0) > 0
|
||
AND COALESCE(oi.quantity, 0) > 0
|
||
AND (UPPER(TRIM(COALESCE(oi.supplier_code, ''))) = '${STOCK_COVER_SUPPLIER_CODE}'
|
||
OR COALESCE(oi.stock_cover_qty, 0) >= COALESCE(oi.quantity, 0) - 1e-9) THEN 'stock_cover'`}
|
||
-- 残留标记(供应商写着库存抵扣、抵扣量已归零/未满)⇒ 按未分配处理,落自采表
|
||
WHEN UPPER(TRIM(COALESCE(oi.supplier_code, ''))) = '${STOCK_COVER_SUPPLIER_CODE}' THEN 'self'
|
||
WHEN NULLIF(TRIM(COALESCE(oi.supplier_code, '')), '') IS NULL THEN 'self'
|
||
WHEN UPPER(TRIM(oi.supplier_code)) IN ('INTERNAL', 'UNASSIGNED') THEN 'self'
|
||
ELSE 'supplier'
|
||
END`;
|
||
}
|
||
|
||
/**
|
||
* 账本已入账:其它类型 status=30 为已归档仍计入;
|
||
* 仅 free_overhead 的 30 是驳回,与待审 10 一样不进 KPI。
|
||
*/
|
||
export const CD_POSTED_STATUS_SQL = `(
|
||
(
|
||
cd.cost_type IS DISTINCT FROM 'free_overhead'
|
||
AND COALESCE(cd.status, 20) >= 20
|
||
)
|
||
OR (
|
||
cd.cost_type = 'free_overhead'
|
||
AND COALESCE(cd.status, 20) = 20
|
||
)
|
||
)`;
|
||
|
||
export interface UnifiedCostWindow {
|
||
date_from: string;
|
||
date_to: string;
|
||
date_field: FinanceDateField;
|
||
/** 2A 窗内全部有效金额合计 */
|
||
total: number;
|
||
/** 采购(含 purchase_applied) */
|
||
purchase: number;
|
||
purchase_self: number;
|
||
purchase_supplier: number;
|
||
/** 第三桶:库存抵扣(`cost_source='inventory_cover'`);`purchase = self + supplier + stock_cover` */
|
||
purchase_stock_cover: number;
|
||
/** 按类型;purchase_applied 已并入 purchase */
|
||
by_type: Array<{ cost_type: string; amount: number }>;
|
||
}
|
||
|
||
/**
|
||
* 采购成本账本读入口(**采购口径**):读 cost_details 的采购入账行,
|
||
* 日历日闭区间 + date_field(2A)+ 可选分公司。
|
||
* 概览 / 看板 / 后续 KPI 应优先调此函数,勿再抄 cost_details 聚合 SQL。
|
||
*
|
||
* ⚠️ 与 listOrderCostDetailsInWindow 是**两套不同业务含义的口径,不是同一指标的两个算法**:
|
||
* 本函数 = 当日采购的成本;listOrderCostDetailsInWindow = 订单的成本。
|
||
*/
|
||
export async function getPurchaseCostLedgerWindow(opts: {
|
||
dateFrom: string;
|
||
dateTo: string;
|
||
branchCode?: string | null;
|
||
dateField?: string | null;
|
||
/** 空 / 省略 = 全部客户;有值时排除无订单归属成本 */
|
||
customerCode?: string | null;
|
||
}): Promise<UnifiedCostWindow> {
|
||
const dateFrom = String(opts.dateFrom || '').trim();
|
||
const dateTo = String(opts.dateTo || '').trim();
|
||
const dateField = normalizeFinanceDateField(opts.dateField);
|
||
const params: unknown[] = [dateFrom, dateTo];
|
||
let branchSql = '';
|
||
if (opts.branchCode) {
|
||
params.push(opts.branchCode);
|
||
branchSql = `AND cd.branch_code = $${params.length}`;
|
||
}
|
||
const customerSql = costDetailsCustomerFilterSql(opts.customerCode, params);
|
||
const cdDateCond = costDetailsLinkedOrPeriodCondSql(dateField, 1, 2);
|
||
/** 排除已删订单孤儿成本(与 getCostAggregation / 成本管理对齐) */
|
||
const cdOrphanCond = `(cd.order_code IS NULL OR TRIM(cd.order_code) = '' OR EXISTS (
|
||
SELECT 1 FROM orders o WHERE o.order_code = cd.order_code AND o.deleted_at IS NULL
|
||
))`;
|
||
|
||
const excludeSync = excludePurchaseDupesForKpiSql('cd');
|
||
const excludeHolding = excludeInventoryHoldingFromKpiSql('cd');
|
||
const typeRows = await pool.query(
|
||
`SELECT bucket_type AS cost_type,
|
||
SUM(amt)::numeric AS total
|
||
FROM (
|
||
SELECT
|
||
CASE
|
||
WHEN cd.cost_type IN ('purchase', 'purchase_applied') THEN 'purchase'
|
||
ELSE COALESCE(NULLIF(TRIM(cd.cost_type), ''), 'overhead')
|
||
END AS bucket_type,
|
||
${CD_EFFECTIVE_AMOUNT_SQL} AS amt
|
||
FROM cost_details cd
|
||
WHERE ${cdDateCond}
|
||
AND ${cdOrphanCond}
|
||
AND ${excludeSync}
|
||
AND ${excludeHolding}
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
${branchSql}
|
||
${customerSql}
|
||
) x
|
||
GROUP BY bucket_type
|
||
HAVING SUM(amt) <> 0
|
||
ORDER BY total DESC`,
|
||
params
|
||
);
|
||
|
||
const by_type = typeRows.rows.map((r) => ({
|
||
cost_type: String(r.cost_type || 'overhead'),
|
||
amount: round2(Number(r.total) || 0),
|
||
}));
|
||
// 采购口径:本函数只读 cost_details 账本,不读 order_items.unit_cost。
|
||
// 账本是「当日采购成本」的唯一权威来源;order_items.unit_cost 属于另一口径
|
||
// (「订单成本」,见 listOrderCostDetailsInWindow)。两者业务含义不同,不在此处混算。
|
||
const purchase = round2(by_type.find((r) => r.cost_type === 'purchase')?.amount || 0);
|
||
const total = round2(by_type.reduce((sum, row) => sum + row.amount, 0));
|
||
|
||
const split = await pool.query(
|
||
`SELECT
|
||
COALESCE(SUM(${purchaseSelfAmountSql(CD_EFFECTIVE_AMOUNT_SQL)}), 0)::numeric AS self_total,
|
||
COALESCE(SUM(${purchaseSupplierAmountSql(CD_EFFECTIVE_AMOUNT_SQL)}), 0)::numeric AS supplier_total,
|
||
COALESCE(SUM(${purchaseStockCoverAmountSql(CD_EFFECTIVE_AMOUNT_SQL)}), 0)::numeric AS stock_cover_total
|
||
FROM cost_details cd
|
||
WHERE ${CD_PURCHASE_TYPES_SQL}
|
||
AND ${cdDateCond}
|
||
AND ${cdOrphanCond}
|
||
AND ${excludeSync}
|
||
AND ${excludeHolding}
|
||
${branchSql}
|
||
${customerSql}`,
|
||
params
|
||
);
|
||
|
||
return {
|
||
date_from: dateFrom,
|
||
date_to: dateTo,
|
||
date_field: dateField,
|
||
total,
|
||
purchase,
|
||
purchase_self: round2(Number(split.rows[0]?.self_total) || 0),
|
||
purchase_supplier: round2(Number(split.rows[0]?.supplier_total) || 0),
|
||
/** 第三桶:库存抵扣(与 `purchase` 同源账本;`purchase = self + supplier + stock_cover`) */
|
||
purchase_stock_cover: round2(Number(split.rows[0]?.stock_cover_total) || 0),
|
||
by_type,
|
||
};
|
||
}
|
||
|
||
function mapMarginRow(row: {
|
||
key: unknown;
|
||
label?: unknown;
|
||
revenue?: unknown;
|
||
total_cost?: unknown;
|
||
order_count?: unknown;
|
||
quantity?: unknown;
|
||
fulfilled_qty?: unknown;
|
||
}): MarginRow {
|
||
const revenue = Number(row.revenue) || 0;
|
||
const totalCost = Number(row.total_cost) || 0;
|
||
const grossProfit = revenue - totalCost;
|
||
const quantity = row.quantity == null ? undefined : Number(row.quantity) || 0;
|
||
const fulfilledRaw = row.fulfilled_qty == null ? undefined : Number(row.fulfilled_qty) || 0;
|
||
const fulfilledQty =
|
||
fulfilledRaw != null && fulfilledRaw > 0
|
||
? fulfilledRaw
|
||
: quantity != null && quantity > 0
|
||
? quantity
|
||
: fulfilledRaw;
|
||
const mapped: MarginRow = {
|
||
key: String(row.key || ''),
|
||
label: String(row.label || row.key || ''),
|
||
revenue: round2(revenue),
|
||
total_cost: round2(totalCost),
|
||
gross_profit: round2(grossProfit),
|
||
gross_margin_pct: revenue > 0 ? round2((grossProfit / revenue) * 100) : 0,
|
||
order_count: row.order_count == null ? undefined : Number(row.order_count) || 0,
|
||
};
|
||
if (quantity != null) {
|
||
mapped.quantity = round2(quantity);
|
||
mapped.sale_price = quantity > 0 ? round2(revenue / quantity) : 0;
|
||
}
|
||
// 成本价与销售价对称:订购量加权(unit_cost×qty / qty);履约量仅附带,不参与除法
|
||
if (quantity != null) {
|
||
mapped.cost_price = quantity > 0 ? round2(totalCost / quantity) : 0;
|
||
}
|
||
if (fulfilledQty != null) {
|
||
mapped.fulfilled_qty = round2(fulfilledQty);
|
||
}
|
||
return mapped;
|
||
}
|
||
|
||
/** 毛利明细分页排序:在 LIMIT 前对全量结果排序 */
|
||
function marginRowsOrderBySql(
|
||
groupBy: 'order' | 'customer' | 'sku',
|
||
sortField?: string | null,
|
||
sortOrder?: string | null
|
||
): string {
|
||
const dir = String(sortOrder || '').toLowerCase() === 'desc' ? 'DESC' : 'ASC';
|
||
const field = String(sortField || '').trim();
|
||
const defaultOrder = '(revenue - total_cost) ASC, key ASC';
|
||
const common: Record<string, string> = {
|
||
revenue: 'revenue',
|
||
total_cost: 'total_cost',
|
||
gross_profit: '(revenue - total_cost)',
|
||
gross_margin_pct: 'CASE WHEN revenue > 0 THEN (revenue - total_cost) / revenue ELSE 0 END',
|
||
};
|
||
if (groupBy === 'sku') {
|
||
const skuFields: Record<string, string> = {
|
||
...common,
|
||
sale_price: 'CASE WHEN quantity > 0 THEN revenue / quantity ELSE 0 END',
|
||
cost_price: 'CASE WHEN quantity > 0 THEN total_cost / quantity ELSE 0 END',
|
||
};
|
||
const expr = skuFields[field];
|
||
return expr ? `${expr} ${dir}, key ASC` : defaultOrder;
|
||
}
|
||
if (groupBy === 'customer' && field === 'order_count') {
|
||
return `order_count ${dir}, key ASC`;
|
||
}
|
||
const expr = common[field];
|
||
return expr ? `${expr} ${dir}, key ASC` : defaultOrder;
|
||
}
|
||
|
||
async function queryMarginRows(
|
||
cycleCode: string,
|
||
ctx: TenantContext | null | undefined,
|
||
groupBy: 'order' | 'customer' | 'sku',
|
||
limit: number,
|
||
offset = 0,
|
||
sortField?: string | null,
|
||
sortOrder?: string | null,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
): Promise<{ rows: MarginRow[]; total: number }> {
|
||
// 区间模式 params=[from,to],orderDateCond 用 $1/$2;YYYYMM params=[cycleCode],用 $1
|
||
const useDateRange = isDateRangeCycle(cycleCode);
|
||
const dateRange = useDateRange ? parseCycleToDateRange(cycleCode) : null;
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const params: unknown[] = useDateRange && dateRange ? [dateRange.from, dateRange.to] : [cycleCode];
|
||
const branchIdx = resolveBranchParam(ctx, params);
|
||
const branchO = branchEq('o', branchIdx);
|
||
const customerSql = ordersCustomerFilterSql(customerCode, params);
|
||
const safeLimit = Math.min(Math.max(limit, 1), 200);
|
||
const safeOffset = Math.max(0, offset);
|
||
params.push(safeLimit, safeOffset);
|
||
const limitIdx = params.length - 1;
|
||
const offsetIdx = params.length;
|
||
const orderBySql = marginRowsOrderBySql(groupBy, sortField, sortOrder);
|
||
|
||
const orderDateJoin = orderFinanceJoinSql(dateField, Boolean(useDateRange && dateRange));
|
||
const orderDateCond =
|
||
useDateRange && dateRange
|
||
? orderFinanceRangeCondSql(dateField, 1, 2)
|
||
: `o.cycle_code = $1`;
|
||
|
||
// 销售额=概览口径;成本=订单行 unit_cost×数量(供应商/自采填价)
|
||
// ORDER BY 表达式须引用 FROM 列(CTE 输出),不能直接用 SELECT 别名,否则 PG 报「字段 revenue 不存在」
|
||
if (groupBy === 'order') {
|
||
const r = await pool.query(
|
||
`WITH order_margin AS (
|
||
SELECT o.order_code AS key,
|
||
COALESCE(MAX(cu.company_name), MAX(o.customer_code)) AS label,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue,
|
||
COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)::numeric AS total_cost
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
LEFT JOIN customers cu ON cu.customer_code = o.customer_code
|
||
WHERE ${orderDateCond} AND ${salesLinePredicateSql('o', 'oi')} ${branchO}
|
||
${customerSql}
|
||
GROUP BY o.order_code
|
||
HAVING COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) > 0
|
||
)
|
||
SELECT key, label, revenue, total_cost,
|
||
COUNT(*) OVER()::int AS full_count
|
||
FROM order_margin
|
||
ORDER BY ${orderBySql}
|
||
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
||
params
|
||
);
|
||
const total = Number(r.rows[0]?.full_count) || 0;
|
||
return {
|
||
rows: r.rows.map((row) => mapMarginRow({ ...row, order_count: 1 })),
|
||
total,
|
||
};
|
||
}
|
||
|
||
if (groupBy === 'customer') {
|
||
const r = await pool.query(
|
||
`WITH order_sales AS (
|
||
SELECT o.order_code,
|
||
o.customer_code,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue,
|
||
COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)::numeric AS total_cost
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
WHERE ${orderDateCond} AND ${salesLinePredicateSql('o', 'oi')} ${branchO}
|
||
${customerSql}
|
||
GROUP BY o.order_code, o.customer_code
|
||
),
|
||
customer_margin AS (
|
||
SELECT s.customer_code AS key,
|
||
COALESCE(MAX(cu.company_name), s.customer_code) AS label,
|
||
COALESCE(SUM(s.revenue), 0)::numeric AS revenue,
|
||
COALESCE(SUM(s.total_cost), 0)::numeric AS total_cost,
|
||
COUNT(DISTINCT s.order_code)::int AS order_count
|
||
FROM order_sales s
|
||
LEFT JOIN customers cu ON cu.customer_code = s.customer_code
|
||
GROUP BY s.customer_code
|
||
)
|
||
SELECT key, label, revenue, total_cost, order_count,
|
||
COUNT(*) OVER()::int AS full_count
|
||
FROM customer_margin
|
||
WHERE revenue > 0
|
||
ORDER BY ${orderBySql}
|
||
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
||
params
|
||
);
|
||
const total = Number(r.rows[0]?.full_count) || 0;
|
||
return { rows: r.rows.map(mapMarginRow), total };
|
||
}
|
||
|
||
// 按商品:一订单×一SKU×是否加菜 一行;成本=SUM(qty×unit_cost),成本价=订购量加权
|
||
const r = await pool.query(
|
||
`WITH sku_margin AS (
|
||
SELECT o.order_code AS key,
|
||
CASE
|
||
WHEN COALESCE(oi.is_extra_dish, false)
|
||
THEN COALESCE(MAX(s.sku_name), oi.sku_code) || '(加菜)'
|
||
ELSE COALESCE(MAX(s.sku_name), oi.sku_code)
|
||
END AS label,
|
||
COALESCE(SUM(COALESCE(oi.quantity, 0)), 0)::numeric AS quantity,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue,
|
||
COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)::numeric AS total_cost
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
${orderDateJoin}
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
WHERE ${orderDateCond} AND ${salesLinePredicateSql('o', 'oi')}
|
||
${customerSql} ${branchO}
|
||
GROUP BY o.order_code, oi.sku_code, COALESCE(oi.is_extra_dish, false)
|
||
HAVING COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) > 0
|
||
)
|
||
SELECT key, label, quantity, revenue, total_cost,
|
||
COUNT(*) OVER()::int AS full_count
|
||
FROM sku_margin
|
||
ORDER BY ${orderBySql}
|
||
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
||
params
|
||
);
|
||
const total = Number(r.rows[0]?.full_count) || 0;
|
||
return { rows: r.rows.map(mapMarginRow), total };
|
||
}
|
||
|
||
/** 商品直接成本(采购+损耗):供成本排行 / 商品成本 Tab,间接成本不分摊到 SKU */
|
||
export interface SkuDirectCostRow {
|
||
sku_code: string;
|
||
sku_name: string;
|
||
category_name: string;
|
||
/** 订单明细加菜标记;前端用标签展示,不拼进 sku_name */
|
||
is_extra_dish?: boolean;
|
||
/** 仓内加工成品:成本固定为 0,仅作展示标记 */
|
||
is_warehouse_processing?: boolean;
|
||
/** 独立自采入库(无订单归属) */
|
||
is_independent_self_purchase?: boolean;
|
||
quantity: number;
|
||
/** SKU 主单位 */
|
||
unit?: string;
|
||
weight: number;
|
||
purchase_cost: number;
|
||
/**
|
||
* **库存成本** = 该 SKU 在本窗口内经库存抵扣拿到的那部分货的成本
|
||
* (账本 `cost_details.cost_source='inventory_cover'` 的结转额)。
|
||
* 与 `purchase_cost`(缺口量 × unit_cost)并列:**行真实成本 = purchase_cost + stock_cover_cost**,
|
||
* 真实成本价 = 两者相加 ÷ quantity(`unit_cost` 字段即为此值)。
|
||
* 见 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §5.1
|
||
*/
|
||
stock_cover_cost?: number;
|
||
/** 采购成本来源拆分:自采 / 供应商 */
|
||
purchase_self_cost?: number;
|
||
purchase_supplier_cost?: number;
|
||
/**
|
||
* 仓内加工行的加工结算成本(quantity × processing_settled_unit_cost)。
|
||
* 仅行展示与毛利率使用;**不计入** purchase_cost / 采购合计,
|
||
* 以免与原料自采重复计成本。
|
||
*/
|
||
settled_processing_cost?: number;
|
||
labor_sorting_cost: number;
|
||
labor_processing_cost: number;
|
||
packaging_cost: number;
|
||
transport_cost: number;
|
||
delivery_cost: number;
|
||
warehouse_cost: number;
|
||
loss_cost: number;
|
||
overhead_cost: number;
|
||
total_cost: number;
|
||
unit_cost: number;
|
||
gross_profit: number;
|
||
gross_margin: number;
|
||
sales_amount: number;
|
||
}
|
||
|
||
/** 商品成本排行列表(无分页);默认按毛利率降序 */
|
||
export async function getSkuDirectCosts(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
limit = 500,
|
||
dateFieldRaw?: string | null,
|
||
sortFieldRaw?: string | null,
|
||
sortOrderRaw?: string | null,
|
||
customerCode?: string | null
|
||
): Promise<SkuDirectCostRow[]> {
|
||
const paged = await getSkuDirectCostsPaged(
|
||
cycleCode,
|
||
ctx,
|
||
1,
|
||
Math.min(Math.max(limit, 1), 2000),
|
||
2000,
|
||
null,
|
||
dateFieldRaw,
|
||
sortFieldRaw ?? 'gross_margin',
|
||
sortOrderRaw ?? 'desc',
|
||
null,
|
||
null,
|
||
customerCode
|
||
);
|
||
return paged.data;
|
||
}
|
||
|
||
/**
|
||
* 商品成本的**来源桶**(列表页三张表 / 导出明细的「成本来源」列)。
|
||
* `stock_cover` = 库存抵扣(第三个取值,2026-10-14):全额由仓库库存抵扣的行。
|
||
*/
|
||
export type SkuCostSourceFilter = 'self' | 'supplier' | 'stock_cover';
|
||
export type SkuCostSortField = 'purchase' | 'gross_margin';
|
||
|
||
/**
|
||
* 订单行口径的采购合计(订单侧 quantity × unit_cost,按 SKU 归桶;含独立自采入库)。
|
||
* 供「所有成本」的采购项使用——账本 cost_details 在部分订单上只有验收同步的占位行、
|
||
* 或正式货值行按入账日落在窗口外,会系统性低估(实测某窗口账本 3,731.73 vs 订单行 8,726.85)。
|
||
* 参数与 getSkuDirectCostsPaged 一致;只取合计,故 page/pageSize 固定最小。
|
||
*/
|
||
export async function getOrderLinePurchaseTotal(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
): Promise<{
|
||
purchase: number;
|
||
purchase_self: number;
|
||
purchase_supplier: number;
|
||
purchase_stock_cover: number;
|
||
}> {
|
||
const paged = await getSkuDirectCostsPaged(
|
||
cycleCode, ctx, 1, 1, 1, null, dateFieldRaw, null, null, null, null, customerCode,
|
||
// 仓内加工成品行不另计成本(原料成本已由独立自采入库/库存领用承担),避免重复计
|
||
true
|
||
);
|
||
const purchaseSelf = round2(Number(paged.totals.purchase_self) || 0);
|
||
const purchaseSupplier = round2(Number(paged.totals.purchase_supplier) || 0);
|
||
/**
|
||
* **采购成本 = 自采 + 供应商 + 库存抵扣**(开发者 2026-10-14 口径定稿;本函数是看板「订单采购成本」卡、
|
||
* 财务概览「采购成本」与净利、以及看板毛利/净利率的**唯一采购来源**)。
|
||
*
|
||
* 为什么必须并入第三部分:被抵扣那部分成本是**早先买货时已经花掉的钱**,它在订单成本里同样是采购成本
|
||
* (商品成本表的「库存成本」列即此项)。漏掉它 ⇒ 采购成本少算、净利虚高。
|
||
* 实测 BR002(主系统分配单 `ORD_API_20261014_BR002_0001`,缺口 ¥97 / 抵扣 ¥159):
|
||
* 改前本函数返回 97 ⇒ 看板采购卡 97、看板净利 ¥385、财务概览净利 ¥385;
|
||
* 改后 256 ⇒ 采购卡 ¥256、净利 ¥226(销售额 ¥482)。
|
||
*/
|
||
const purchaseStockCover = round2(Number(paged.totals.stock_cover) || 0);
|
||
return {
|
||
purchase: round2(purchaseSelf + purchaseSupplier + purchaseStockCover),
|
||
purchase_self: purchaseSelf,
|
||
purchase_supplier: purchaseSupplier,
|
||
purchase_stock_cover: purchaseStockCover,
|
||
};
|
||
}
|
||
|
||
/** 商品成本列表:订单 quantity×unit_cost,并叠加独立自采入库;总览 KPI 仍读账本。 */
|
||
export async function getSkuDirectCostsPaged(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
page = 1,
|
||
pageSize = 20,
|
||
maxPageSize = 100,
|
||
costSource?: SkuCostSourceFilter | null,
|
||
dateFieldRaw?: string | null,
|
||
sortFieldRaw?: string | null,
|
||
sortOrderRaw?: string | null,
|
||
categoryCodes?: string[] | null,
|
||
nameQuery?: string | null,
|
||
customerCode?: string | null,
|
||
/** true 时从行来源排除仓内加工成品行(合计用;仓内加工不另计成本) */
|
||
excludeWarehouseProcessing?: boolean
|
||
): Promise<{
|
||
data: SkuDirectCostRow[];
|
||
total: number;
|
||
page: number;
|
||
page_size: number;
|
||
totals: {
|
||
sales_amount: number;
|
||
purchase_cost: number;
|
||
total_cost: number;
|
||
purchase_self?: number;
|
||
purchase_supplier?: number;
|
||
/** 库存成本合计(账本 inventory_cover);`total_cost = purchase_cost + stock_cover` */
|
||
stock_cover?: number;
|
||
};
|
||
}> {
|
||
const safePage = Math.max(1, Number(page) || 1);
|
||
const safeSize = Math.min(Math.max(Number(pageSize) || 20, 1), Math.max(1, maxPageSize));
|
||
const offset = (safePage - 1) * safeSize;
|
||
const sourceFilter: SkuCostSourceFilter | null =
|
||
costSource === 'self' || costSource === 'supplier' || costSource === 'stock_cover'
|
||
? costSource
|
||
: null;
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const customerFilter = normalizeCustomerCodeFilter(customerCode);
|
||
const categoryFilter = [
|
||
...new Set(
|
||
(Array.isArray(categoryCodes) ? categoryCodes : [])
|
||
.map((c) => String(c || '').trim())
|
||
.filter(Boolean)
|
||
),
|
||
];
|
||
const skuNameQuery = String(nameQuery || '').trim();
|
||
// 无来源过滤(总览排行)默认按毛利率;自采/供应表仍按采购额
|
||
const sortField: SkuCostSortField =
|
||
sortFieldRaw === 'purchase' || sortFieldRaw === 'gross_margin'
|
||
? sortFieldRaw
|
||
: sourceFilter
|
||
? 'purchase'
|
||
: 'gross_margin';
|
||
const sortDir = String(sortOrderRaw || '').toLowerCase() === 'asc' ? 'ASC' : 'DESC';
|
||
const marginExpr =
|
||
'CASE WHEN sales_amount > 0 THEN (sales_amount - purchase_cost) / sales_amount ELSE NULL END';
|
||
const orderBySql =
|
||
sourceFilter === 'self'
|
||
? `purchase_self_cost ${sortDir}, sales_amount DESC`
|
||
: sourceFilter === 'supplier'
|
||
? `purchase_supplier_cost ${sortDir}, sales_amount DESC`
|
||
: sortField === 'gross_margin'
|
||
? `${marginExpr} ${sortDir} NULLS LAST, purchase_cost DESC, sales_amount DESC`
|
||
: `purchase_cost ${sortDir}, sales_amount DESC`;
|
||
|
||
// 区间模式 params=[from,to],orderDateCond 用 $1/$2;YYYYMM params=[cycleCode],用 $1
|
||
const useDateRange = isDateRangeCycle(cycleCode);
|
||
const dateRange = useDateRange ? parseCycleToDateRange(cycleCode) : null;
|
||
const params: unknown[] = useDateRange && dateRange ? [dateRange.from, dateRange.to] : [cycleCode];
|
||
const branchIdx = resolveBranchParam(ctx, params);
|
||
const branchO = branchEq('o', branchIdx);
|
||
// 客户码只 push 一次;订单行成本与销量共用同一 $n
|
||
const { ordersSql: customerSqlO } = bindSharedCustomerFilterSql(customerFilter, params);
|
||
let categoryIdx: number | null = null;
|
||
let nameIdx: number | null = null;
|
||
if (categoryFilter.length) {
|
||
params.push(categoryFilter);
|
||
categoryIdx = params.length;
|
||
}
|
||
if (skuNameQuery) {
|
||
params.push(skuNameQuery);
|
||
nameIdx = params.length;
|
||
}
|
||
params.push(safeSize, offset);
|
||
const limitIdx = params.length - 1;
|
||
const offsetIdx = params.length;
|
||
// 分类筛选同样按「订单行分类」口径(取数量占比最大的那个),与展示一致,
|
||
// 否则按品类筛选会与列上显示的分类自相矛盾。
|
||
const skuCategoryCond = categoryIdx
|
||
? `AND rc.rep_category_code = ANY($${categoryIdx}::text[])`
|
||
: '';
|
||
const skuNameCond = nameIdx
|
||
? `AND COALESCE(s.sku_name, '') ILIKE ('%' || $${nameIdx}::text || '%')`
|
||
: '';
|
||
|
||
const orderDateJoin = orderFinanceJoinSql(dateField, Boolean(useDateRange && dateRange));
|
||
const orderDateCond =
|
||
useDateRange && dateRange
|
||
? orderFinanceRangeCondSql(dateField, 1, 2)
|
||
: `o.cycle_code = $1`;
|
||
|
||
// 列表金额直接读取订单行;展示归桶仍按本行供应商列区分自采/供应
|
||
const r = await pool.query(
|
||
`WITH cover_ledger AS (
|
||
-- 库存抵扣的**账本**结转额(按 订单×SKU):抵扣成本的唯一真相源
|
||
-- (行上不带 order_item_id,故只能按 订单×SKU 归属)
|
||
SELECT cd.order_code, cd.sku_code, SUM(cd.amount)::numeric AS cover_amount
|
||
FROM cost_details cd
|
||
WHERE cd.cost_source = 'inventory_cover'
|
||
GROUP BY cd.order_code, cd.sku_code
|
||
),
|
||
/**
|
||
* **一行一条订单行**(抵扣量、缺口、账本分摊都在这里算一次)。
|
||
* 之后按「成本来源」拆成**最多两段**(见 src_cost_lines):抵扣段 + 缺口段。
|
||
*/
|
||
src_line_base AS (
|
||
SELECT oi.order_code,
|
||
oi.sku_code,
|
||
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
|
||
${WAREHOUSE_PROCESSING_LINE_SQL} AS is_warehouse_processing,
|
||
${skuListDisplayCostBucketSql({ gapOnly: true })} AS gap_bucket,
|
||
COALESCE(oi.unit_cost, 0)::numeric AS unit_cost,
|
||
COALESCE(oi.quantity, 0)::numeric AS full_qty,
|
||
COALESCE(oi.stock_cover_qty, 0)::numeric AS cover_qty,
|
||
/**
|
||
* **库存成本(本行的账本分摊额)** = 账本 inventory_cover 结转额 × 本行抵扣量占比
|
||
* (同一订单同一 SKU 正常只有一行发生抵扣 ⇒ 拿到 100%)。
|
||
* 抵扣量为 0 却账本有行的脏数据 ⇒ 显式计 0。
|
||
*/
|
||
COALESCE(COALESCE(cov.cover_amount, 0) * COALESCE(oi.stock_cover_qty, 0)
|
||
/ NULLIF(SUM(COALESCE(oi.stock_cover_qty, 0))
|
||
OVER (PARTITION BY oi.order_code, oi.sku_code), 0), 0)::numeric
|
||
AS cover_share,
|
||
-- 仓内加工完工时 settleDemandSheetCostOnCompletion 会把分摊后的
|
||
-- 加工成本回写到 order_items.processing_settled_unit_cost(并同步 unit_cost)。
|
||
-- 排行/毛利率需要它,但订单采购成本合计不能用它(原料已按自采计价,避免重复计)。
|
||
COALESCE(oi.processing_settled_unit_cost, 0)::numeric AS settled_unit_cost,
|
||
(${ORDER_ITEM_REVENUE_SQL})::numeric AS line_sales,
|
||
-- 分类以「订单行分类」为基准(开发者 2026-09-22 决策):
|
||
-- 商品主数据 category_code 会被录单手动选分类回写,导致本页与订单详情不一致。
|
||
-- 见 docs/design/20260922-sku-cost-category-from-order-line.md
|
||
oi.category_code AS line_category_code
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
LEFT JOIN cover_ledger cov
|
||
ON cov.order_code = oi.order_code AND cov.sku_code = oi.sku_code
|
||
${orderDateJoin}
|
||
WHERE ${orderDateCond} AND o.order_status >= 20 AND o.deleted_at IS NULL
|
||
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
|
||
AND COALESCE(oi.is_returned, false) = false ${branchO}
|
||
${customerSqlO}
|
||
${excludeWarehouseProcessing ? `AND NOT ${WAREHOUSE_PROCESSING_LINE_SQL}` : ''}
|
||
/**
|
||
* **独立进货单不进「订单商品成本 / 订单采购成本」**(2026-10-14 开发者口径)。
|
||
*
|
||
* 独立进货是**进货/补库存**凭证(哨兵客户 __INDEPENDENT_INBOUND__),不是客户订单;
|
||
* 它的成本属于存货,算进「订单采购成本」会把供应表撑大。
|
||
* 真库实测(BR002 2026-10-14):ORD_WEB_20261014_BR002_0002 15 行 ¥1,449,
|
||
* 原本占「供应采购成本 ¥1,586」的主体。
|
||
*
|
||
* ⚠️ **与销售侧同口径**:直接复用既有判据 salesVisibleOrderSql(不新造口径);
|
||
* 本页销量/销售额出自同一份取数,因此也一并排除 —— 与全系统销售口径一致。
|
||
* (注意:本注释在模板字符串里,**不要**写反引号,会截断模板。)
|
||
*/
|
||
AND ${salesVisibleOrderSql('o')}
|
||
),
|
||
/**
|
||
* **按成本来源拆段**(2026-10-14 开发者真机裁定):
|
||
* 「库存里面已经被预留占用了,说明库存抵扣是生效了的 —— 为什么库存抵扣成本这块没有
|
||
* 抵扣数量的成本展示,反而全部都是给到了自采?」
|
||
* 根因:一行只归一个桶 ⇒ 部分抵扣的行整行落进自采表,抵扣段没有独立成行。
|
||
* 现在:有抵扣量就发**抵扣段**(销量=抵扣量、采购成本 0、库存成本=账本分摊额),
|
||
* 还有缺口就再发**缺口段**(销量=缺口量、采购成本=缺口×单价、库存成本 0)。
|
||
* 两段相加 = 整行真实成本;销售额只记一次(有缺口记在缺口段,全额抵扣记在抵扣段)。
|
||
*/
|
||
src_cost_lines AS (
|
||
SELECT sku_code,
|
||
is_extra_dish,
|
||
is_warehouse_processing,
|
||
'stock_cover' AS cost_bucket,
|
||
0::numeric AS amount,
|
||
cover_share AS stock_cover_cost,
|
||
settled_unit_cost,
|
||
cover_qty AS line_qty,
|
||
CASE WHEN full_qty - cover_qty > 1e-9 THEN 0 ELSE line_sales END AS line_sales,
|
||
line_category_code
|
||
FROM src_line_base
|
||
WHERE cover_qty > 1e-9
|
||
UNION ALL
|
||
SELECT sku_code,
|
||
is_extra_dish,
|
||
is_warehouse_processing,
|
||
gap_bucket AS cost_bucket,
|
||
(GREATEST(0, full_qty - cover_qty) * unit_cost)::numeric AS amount,
|
||
0::numeric AS stock_cover_cost,
|
||
settled_unit_cost,
|
||
GREATEST(0, full_qty - cover_qty) AS line_qty,
|
||
line_sales,
|
||
line_category_code
|
||
FROM src_line_base
|
||
WHERE full_qty - cover_qty > 1e-9
|
||
),
|
||
-- 每行(SKU×加菜×来源桶×加工)的展示分类:取本期**数量占比最大**的订单行分类;
|
||
-- 平手按 category_code 升序,保证结果确定。
|
||
cat_qty AS (
|
||
SELECT sku_code, is_extra_dish, cost_bucket, is_warehouse_processing,
|
||
line_category_code,
|
||
COALESCE(SUM(line_qty), 0)::numeric AS cat_qty
|
||
FROM src_cost_lines
|
||
GROUP BY sku_code, is_extra_dish, cost_bucket, is_warehouse_processing, line_category_code
|
||
),
|
||
rep_cat AS (
|
||
SELECT DISTINCT ON (sku_code, is_extra_dish, cost_bucket, is_warehouse_processing)
|
||
sku_code, is_extra_dish, cost_bucket, is_warehouse_processing,
|
||
line_category_code AS rep_category_code
|
||
FROM cat_qty
|
||
ORDER BY sku_code, is_extra_dish, cost_bucket, is_warehouse_processing,
|
||
cat_qty DESC, line_category_code
|
||
),
|
||
src_costs AS (
|
||
SELECT sku_code,
|
||
is_extra_dish,
|
||
BOOL_OR(is_warehouse_processing) AS is_warehouse_processing,
|
||
cost_bucket,
|
||
COALESCE(SUM(amount), 0)::numeric AS amount,
|
||
COALESCE(SUM(line_qty), 0)::numeric AS quantity,
|
||
COALESCE(SUM(line_sales), 0)::numeric AS sales_amount,
|
||
COALESCE(SUM(CASE WHEN cost_bucket = 'self' THEN amount ELSE 0 END), 0)::numeric AS self_cost,
|
||
COALESCE(SUM(CASE WHEN cost_bucket = 'supplier' THEN amount ELSE 0 END), 0)::numeric AS supplier_cost,
|
||
-- 库存成本(账本 inventory_cover 结转额):与采购成本并列的两项之一
|
||
COALESCE(SUM(stock_cover_cost), 0)::numeric AS stock_cover_cost,
|
||
COALESCE(SUM(line_qty * settled_unit_cost), 0)::numeric AS settled_amount
|
||
FROM src_cost_lines
|
||
-- 仓内加工单独成行:其成本恒为 0(原料成本由对应自采/独立入库体现),
|
||
-- 若与自采同桶合并,会把加工量并进自采数量而金额不增,导致单位成本与合计口径失真。
|
||
-- 见 docs/design/20260914-sku-cost-warehouse-processing-separate-row.md
|
||
GROUP BY sku_code, is_extra_dish, cost_bucket, is_warehouse_processing
|
||
),
|
||
filtered AS (
|
||
SELECT sc.sku_code,
|
||
sc.is_extra_dish,
|
||
sc.is_warehouse_processing,
|
||
COALESCE(s.sku_name, sc.sku_code) AS sku_name,
|
||
COALESCE(cat.category_name, '-') AS category_name,
|
||
COALESCE(NULLIF(TRIM(s.unit), ''), '') AS unit,
|
||
COALESCE(sc.quantity, 0)::numeric AS quantity,
|
||
COALESCE(sc.quantity, 0)::numeric AS fulfilled_qty,
|
||
COALESCE(sc.sales_amount, 0)::numeric AS sales_amount,
|
||
-- 仓内加工行:成本一律按 0 计(用户口径:仓内加工成本就是 0),
|
||
-- 避免历史行 unit_cost 未归零(如 4.00/3.80)被算进自采金额。
|
||
CASE WHEN sc.is_warehouse_processing THEN 0 ELSE sc.amount END::numeric AS purchase_cost,
|
||
-- 库存成本:仓内加工行同样按 0(其成本由加工线承担)
|
||
CASE WHEN sc.is_warehouse_processing THEN 0 ELSE COALESCE(sc.stock_cover_cost, 0) END::numeric
|
||
AS stock_cover_cost,
|
||
CASE WHEN sc.is_warehouse_processing THEN 0 ELSE sc.self_cost END AS purchase_self_cost,
|
||
CASE WHEN sc.is_warehouse_processing THEN 0 ELSE sc.supplier_cost END AS purchase_supplier_cost,
|
||
CASE WHEN sc.is_warehouse_processing THEN sc.settled_amount ELSE 0 END AS settled_processing_amount
|
||
FROM src_costs sc
|
||
LEFT JOIN skus s ON s.sku_code = sc.sku_code
|
||
-- 展示分类取订单行口径的代表分类(rep_cat),不再用商品主数据 s.category_code
|
||
LEFT JOIN rep_cat rc
|
||
ON rc.sku_code = sc.sku_code
|
||
AND rc.is_extra_dish = sc.is_extra_dish
|
||
AND rc.cost_bucket = sc.cost_bucket
|
||
AND rc.is_warehouse_processing = sc.is_warehouse_processing
|
||
LEFT JOIN LATERAL (
|
||
SELECT c.category_name
|
||
FROM categories c
|
||
WHERE c.category_code = rc.rep_category_code
|
||
ORDER BY CASE WHEN c.branch_code IS NOT DISTINCT FROM s.branch_code THEN 0 ELSE 1 END
|
||
LIMIT 1
|
||
) cat ON TRUE
|
||
WHERE TRUE
|
||
-- 0 成本也列出(docs/design/20260923-sku-cost-list-include-zero)
|
||
${sourceFilter === 'self' ? "AND sc.cost_bucket = 'self'" : ''}
|
||
${sourceFilter === 'supplier' ? "AND sc.cost_bucket = 'supplier'" : ''}
|
||
${sourceFilter === 'stock_cover' ? "AND sc.cost_bucket = 'stock_cover'" : ''}
|
||
${skuCategoryCond}
|
||
${skuNameCond}
|
||
),
|
||
-- 表头(供应/自采两张卡)的采购合计:保持原行为——**两个桶都按「窗口全集(分类/名称筛选后)」
|
||
-- 求和,不套来源过滤**。原因:前端 skuTotals 只有一个 state,两张表的表头都读同一次响应里的
|
||
-- purchase_self / purchase_supplier;若这里跟随来源过滤,其中一张表头会变成 0。
|
||
-- 仓内加工成品行不计入采购合计:其材料成本已由对应采购/独立入库体现,计入即重复
|
||
-- (用户 2026-09-14 口径)。与看板 getOrderLinePurchaseTotal 的 excludeWarehouseProcessing 一致。
|
||
-- 分类筛选同样按订单行口径(rep_cat),与列上展示一致。
|
||
ledger_totals AS (
|
||
SELECT
|
||
COALESCE(SUM(CASE WHEN t.cost_bucket = 'self' THEN t.amount ELSE 0 END), 0)::numeric AS self_total,
|
||
COALESCE(SUM(CASE WHEN t.cost_bucket = 'supplier' THEN t.amount ELSE 0 END), 0)::numeric AS supplier_total,
|
||
-- 库存成本合计(账本 inventory_cover):与采购合计并列的第三个数
|
||
COALESCE(SUM(t.stock_cover_cost), 0)::numeric AS stock_cover_total
|
||
FROM (
|
||
SELECT sc.cost_bucket, sc.amount, sc.stock_cover_cost
|
||
FROM src_costs sc
|
||
LEFT JOIN skus s ON s.sku_code = sc.sku_code
|
||
LEFT JOIN rep_cat rc
|
||
ON rc.sku_code = sc.sku_code
|
||
AND rc.is_extra_dish = sc.is_extra_dish
|
||
AND rc.cost_bucket = sc.cost_bucket
|
||
AND rc.is_warehouse_processing = sc.is_warehouse_processing
|
||
WHERE NOT sc.is_warehouse_processing
|
||
${skuCategoryCond}
|
||
${skuNameCond}
|
||
) t
|
||
),
|
||
ranked AS (
|
||
SELECT filtered.*,
|
||
COUNT(*) OVER()::int AS full_count,
|
||
SUM(filtered.sales_amount) OVER()::numeric AS sum_sales,
|
||
SUM(filtered.purchase_self_cost) OVER()::numeric AS sum_self_cost,
|
||
SUM(filtered.purchase_supplier_cost) OVER()::numeric AS sum_supplier_cost
|
||
FROM filtered
|
||
)
|
||
SELECT r.sku_code,
|
||
r.is_extra_dish,
|
||
r.is_warehouse_processing,
|
||
r.sku_name,
|
||
r.category_name,
|
||
r.unit,
|
||
r.quantity,
|
||
r.fulfilled_qty,
|
||
r.sales_amount,
|
||
r.purchase_cost,
|
||
r.stock_cover_cost,
|
||
r.purchase_self_cost,
|
||
r.purchase_supplier_cost,
|
||
r.settled_processing_amount,
|
||
r.full_count,
|
||
r.sum_sales,
|
||
lt.self_total AS ledger_self_total,
|
||
lt.supplier_total AS ledger_supplier_total,
|
||
lt.stock_cover_total AS ledger_stock_cover_total
|
||
FROM ledger_totals lt
|
||
LEFT JOIN (
|
||
SELECT *
|
||
FROM ranked
|
||
ORDER BY ${orderBySql}
|
||
LIMIT $${limitIdx} OFFSET $${offsetIdx}
|
||
) r ON TRUE`,
|
||
params
|
||
);
|
||
|
||
const total = Number(r.rows[0]?.full_count) || 0;
|
||
let purchaseSelfTotal = round2(Number(r.rows[0]?.ledger_self_total) || 0);
|
||
const purchaseSupplierTotal = round2(Number(r.rows[0]?.ledger_supplier_total) || 0);
|
||
let actualPurchaseTotal = round2(purchaseSelfTotal + purchaseSupplierTotal);
|
||
/** 库存成本合计(账本 inventory_cover):表头第三个数 */
|
||
const stockCoverTotal = round2(Number(r.rows[0]?.ledger_stock_cover_total) || 0);
|
||
|
||
const data = r.rows
|
||
.filter((row) => row.sku_code != null && String(row.sku_code).trim() !== '')
|
||
.map((row) => {
|
||
const quantity = Number(row.quantity) || 0;
|
||
const salesAmount = Number(row.sales_amount) || 0;
|
||
const purchaseSelfCost = round2(Number(row.purchase_self_cost) || 0);
|
||
const purchaseSupplierCost = round2(Number(row.purchase_supplier_cost) || 0);
|
||
// 仓内加工行:金额为 0(原料已按自采计价),但加工完工会把实际加工成本
|
||
// 回写到 order_items.processing_settled_unit_cost;单独带出供排行展示与毛利计算。
|
||
const settledProcessingCost = round2(Number(row.settled_processing_amount) || 0);
|
||
const purchaseCost = round2(purchaseSelfCost + purchaseSupplierCost);
|
||
/**
|
||
* **库存成本**(账本 `inventory_cover` 结转额):与采购成本并列的一项。
|
||
* 开发者 2026-10-14 定稿:**行真实成本 = 采购成本 + 库存成本**,
|
||
* 真实成本价 = `(采购金额 + 抵扣金额) ÷ 数量`(见 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §5.1)。
|
||
*/
|
||
const stockCoverCost = round2(Number(row.stock_cover_cost) || 0);
|
||
const lossCost = 0;
|
||
// 直接成本:来源过滤时仅计该来源;否则自采+供应商(缺口量×unit_cost)
|
||
// ⚠️ 再 **加上库存成本** —— 行真实成本 = 采购成本 + 库存成本(开发者 2026-10-14 定稿)
|
||
const totalCost = round2(
|
||
(sourceFilter === 'self'
|
||
? purchaseSelfCost
|
||
: sourceFilter === 'supplier'
|
||
? purchaseSupplierCost
|
||
: purchaseCost) + stockCoverCost
|
||
);
|
||
const grossProfit = round2(salesAmount - totalCost);
|
||
const isExtraDish = row.is_extra_dish === true || row.is_extra_dish === 't' || row.is_extra_dish === 1;
|
||
const isWarehouseProcessing = row.is_warehouse_processing === true || row.is_warehouse_processing === 't' || row.is_warehouse_processing === 'true' || row.is_warehouse_processing === 1;
|
||
const baseName = String(row.sku_name || row.sku_code).replace(/(加菜)\s*$/, '');
|
||
return {
|
||
sku_code: String(row.sku_code),
|
||
sku_name: baseName,
|
||
is_extra_dish: isExtraDish,
|
||
is_warehouse_processing: isWarehouseProcessing,
|
||
is_independent_self_purchase: false,
|
||
category_name: String(row.category_name || '-'),
|
||
quantity: round2(quantity),
|
||
unit: String(row.unit || '').trim() || undefined,
|
||
weight: round2(quantity),
|
||
purchase_cost: purchaseCost,
|
||
stock_cover_cost: stockCoverCost,
|
||
purchase_self_cost: purchaseSelfCost,
|
||
purchase_supplier_cost: purchaseSupplierCost,
|
||
settled_processing_cost: settledProcessingCost,
|
||
labor_sorting_cost: 0,
|
||
labor_processing_cost: 0,
|
||
packaging_cost: 0,
|
||
transport_cost: 0,
|
||
delivery_cost: 0,
|
||
warehouse_cost: 0,
|
||
loss_cost: lossCost,
|
||
overhead_cost: 0,
|
||
total_cost: totalCost,
|
||
unit_cost: quantity > 0 ? round2(totalCost / quantity) : 0,
|
||
gross_profit: grossProfit,
|
||
gross_margin: salesAmount > 0 ? round2((grossProfit / salesAmount) * 100) : 0,
|
||
sales_amount: round2(salesAmount),
|
||
};
|
||
});
|
||
|
||
// 独立入库(原「独立自采入库」)**不再单独补入商品成本页** —— 用户 2026-09-14 决策(方案 A)。
|
||
//
|
||
// 原因(已实测确认):
|
||
// 1) 独立入库是仓内加工的原材料仓,计入条件是「未作废 + 入库日期在窗口内」,
|
||
// **完全没有「是否已被加工领用」判断** → 未使用、纯留库存的部分也被算成期间成本
|
||
// (BR002 实测:40 笔 ¥1,343.95,其中未被领用的 7 笔 ¥280.66);
|
||
// 2) 加工单完工会把领料成本回写到订单行
|
||
// (`order_items.unit_cost` / `processing_settled_unit_cost`),成品行本身即真实成本;
|
||
// 20 个 SKU 同时出现在独立入库与订单行 → **两边都计就是重复**;
|
||
// 3) 本页语义是「订单商品成本」,成本应跟着**出货**走,而不是跟着**入库**走。
|
||
//
|
||
// 影响:本页不再显示独立入库行,`totals.purchase_self/purchase_cost/total_cost` 同步
|
||
// 不含该部分;已在库存中的料在被领用做出成品时,通过成品行进入成本(不会丢账,只是推迟)。
|
||
// 其它口径不受影响:`getCostAggregation`(总览账本)与 `listOrderCostDetailsInWindow`
|
||
// 的独立入库处理未改动。
|
||
//
|
||
// 见 docs/design/20260914-sku-cost-exclude-independent-inbound.md
|
||
|
||
// 合计与列表同源 src_cost_lines(当前数量×unit_cost,不加 cost_source)
|
||
return {
|
||
data,
|
||
total,
|
||
page: safePage,
|
||
page_size: safeSize,
|
||
totals: {
|
||
sales_amount: round2(Number(r.rows[0]?.sum_sales) || 0),
|
||
purchase_cost: actualPurchaseTotal,
|
||
// 行真实成本 = 采购成本 + 库存成本(开发者 2026-10-14 定稿,见设计文 §5.1)
|
||
total_cost: round2(actualPurchaseTotal + stockCoverTotal),
|
||
purchase_self: purchaseSelfTotal,
|
||
purchase_supplier: purchaseSupplierTotal,
|
||
stock_cover: stockCoverTotal,
|
||
},
|
||
};
|
||
}
|
||
|
||
/** 商品成本导出明细行:一单一商品一行(含客户/供应商) */
|
||
export interface SkuDirectCostLineRow {
|
||
order_code: string;
|
||
delivery_date: string | null;
|
||
customer_code: string | null;
|
||
customer_name: string | null;
|
||
supplier_code: string | null;
|
||
supplier_name: string | null;
|
||
cost_source: SkuCostSourceFilter;
|
||
sku_code: string;
|
||
sku_name: string;
|
||
category_name: string;
|
||
quantity: number;
|
||
unit: string | null;
|
||
unit_cost: number;
|
||
purchase_cost: number;
|
||
/**
|
||
* **库存成本** = 账本 `cost_details.cost_source='inventory_cover'` 的结转额
|
||
* (按 订单×SKU 分摊到行)。与 `purchase_cost` 相加 = 行真实成本。
|
||
* 见 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §5.1
|
||
*/
|
||
stock_cover_cost: number;
|
||
sales_amount: number;
|
||
is_extra_dish?: boolean;
|
||
is_warehouse_processing?: boolean;
|
||
}
|
||
|
||
/**
|
||
* 商品成本明细行分页(导出用)。
|
||
* 口径与 getSkuDirectCostsPaged 的 src_cost_lines 同源:当前数量×unit_cost + 展示归桶。
|
||
* 不含独立自采入库(无订单/客户)。
|
||
*/
|
||
export async function getSkuDirectCostLinesPaged(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
page = 1,
|
||
pageSize = 20,
|
||
maxPageSize = 100,
|
||
costSource?: SkuCostSourceFilter | null,
|
||
dateFieldRaw?: string | null,
|
||
categoryCodes?: string[] | null,
|
||
nameQuery?: string | null,
|
||
customerCode?: string | null
|
||
): Promise<{
|
||
data: SkuDirectCostLineRow[];
|
||
total: number;
|
||
page: number;
|
||
page_size: number;
|
||
}> {
|
||
const safePage = Math.max(1, Number(page) || 1);
|
||
const safeSize = Math.min(Math.max(Number(pageSize) || 20, 1), Math.max(1, maxPageSize));
|
||
const offset = (safePage - 1) * safeSize;
|
||
const sourceFilter: SkuCostSourceFilter | null =
|
||
costSource === 'self' || costSource === 'supplier' || costSource === 'stock_cover'
|
||
? costSource
|
||
: null;
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const customerFilter = normalizeCustomerCodeFilter(customerCode);
|
||
const categoryFilter = [
|
||
...new Set(
|
||
(Array.isArray(categoryCodes) ? categoryCodes : [])
|
||
.map((c) => String(c || '').trim())
|
||
.filter(Boolean)
|
||
),
|
||
];
|
||
const skuNameQuery = String(nameQuery || '').trim();
|
||
|
||
const useDateRange = isDateRangeCycle(cycleCode);
|
||
const dateRange = useDateRange ? parseCycleToDateRange(cycleCode) : null;
|
||
const params: unknown[] = useDateRange && dateRange ? [dateRange.from, dateRange.to] : [cycleCode];
|
||
const branchIdx = resolveBranchParam(ctx, params);
|
||
const branchO = branchEq('o', branchIdx);
|
||
const { ordersSql: customerSqlO } = bindSharedCustomerFilterSql(customerFilter, params);
|
||
let categoryIdx: number | null = null;
|
||
let nameIdx: number | null = null;
|
||
if (categoryFilter.length) {
|
||
params.push(categoryFilter);
|
||
categoryIdx = params.length;
|
||
}
|
||
if (skuNameQuery) {
|
||
params.push(skuNameQuery);
|
||
nameIdx = params.length;
|
||
}
|
||
params.push(safeSize, offset);
|
||
const limitIdx = params.length - 1;
|
||
const offsetIdx = params.length;
|
||
|
||
// 导出明细一行即一条订单行:分类直接用该行分类,与列表页口径一致
|
||
// (见 docs/design/20260922-sku-cost-category-from-order-line.md)
|
||
const skuCategoryCond = categoryIdx
|
||
? `AND oi.category_code = ANY($${categoryIdx}::text[])`
|
||
: '';
|
||
const skuNameCond = nameIdx
|
||
? `AND COALESCE(s.sku_name, oi.item_name, '') ILIKE ('%' || $${nameIdx}::text || '%')`
|
||
: '';
|
||
const orderDateJoin = orderFinanceJoinSql(dateField, Boolean(useDateRange && dateRange));
|
||
const orderDateCond =
|
||
useDateRange && dateRange
|
||
? orderFinanceRangeCondSql(dateField, 1, 2)
|
||
: `o.cycle_code = $1`;
|
||
const bucketSql = skuListDisplayCostBucketSql();
|
||
const warehouseFlagSql = `(LOWER(TRIM(COALESCE(oi.processing_owner, ''))) IN ('warehouse', 'warehouse_processing', '仓内加工')
|
||
AND COALESCE(NULLIF(TRIM(oi.processing_method), ''), '原材料') <> '原材料')`;
|
||
const sourceCond =
|
||
sourceFilter === 'self'
|
||
? `AND line.cost_bucket = 'self'`
|
||
: sourceFilter === 'supplier'
|
||
? `AND line.cost_bucket = 'supplier'`
|
||
: sourceFilter === 'stock_cover'
|
||
? `AND line.cost_bucket = 'stock_cover'`
|
||
: '';
|
||
|
||
const r = await pool.query(
|
||
`WITH cover_ledger AS (
|
||
-- 库存抵扣的**账本**结转额(按 订单×SKU):与列表页同一真相源
|
||
-- (成本行不带 order_item_id,故只能按 订单×SKU 归属)
|
||
SELECT cd.order_code, cd.sku_code, SUM(cd.amount)::numeric AS cover_amount
|
||
FROM cost_details cd
|
||
WHERE cd.cost_source = 'inventory_cover'
|
||
GROUP BY cd.order_code, cd.sku_code
|
||
),
|
||
/**
|
||
* 导出与列表页同源拆段(2026-10-14):一行先算全量/抵扣量/账本分摊,再拆成
|
||
* **抵扣段**(销量=抵扣量、采购成本 0、库存成本=账本分摊额)与**缺口段**
|
||
* (销量=缺口量、采购成本=缺口×单价、库存成本 0),与页面三张表逐项对账相等。
|
||
*/
|
||
src_line_base AS (
|
||
SELECT oi.order_code,
|
||
o.delivery_date::text AS delivery_date,
|
||
o.customer_code,
|
||
COALESCE(NULLIF(TRIM(cu.company_name), ''), o.customer_code) AS customer_name,
|
||
NULLIF(TRIM(oi.supplier_code), '') AS supplier_code,
|
||
COALESCE(NULLIF(TRIM(sup.company_name), ''), NULLIF(TRIM(oi.supplier_code), '')) AS supplier_name,
|
||
${skuListDisplayCostBucketSql({ gapOnly: true })} AS gap_bucket,
|
||
oi.sku_code,
|
||
COALESCE(NULLIF(TRIM(s.sku_name), ''), NULLIF(TRIM(oi.item_name), ''), oi.sku_code) AS sku_name,
|
||
COALESCE(cat.category_name, '-') AS category_name,
|
||
COALESCE(NULLIF(TRIM(s.unit), ''), NULLIF(TRIM(oi.unit), ''), '') AS unit,
|
||
COALESCE(oi.quantity, 0)::numeric AS full_qty,
|
||
COALESCE(oi.stock_cover_qty, 0)::numeric AS cover_qty,
|
||
COALESCE(oi.unit_cost, 0)::numeric AS unit_cost,
|
||
COALESCE(COALESCE(cov.cover_amount, 0) * COALESCE(oi.stock_cover_qty, 0)
|
||
/ NULLIF(SUM(COALESCE(oi.stock_cover_qty, 0))
|
||
OVER (PARTITION BY oi.order_code, oi.sku_code), 0), 0)::numeric
|
||
AS cover_share,
|
||
(${ORDER_ITEM_REVENUE_SQL})::numeric AS sales_amount,
|
||
COALESCE(oi.is_extra_dish, false) AS is_extra_dish,
|
||
${warehouseFlagSql} AS is_warehouse_processing
|
||
FROM order_items oi
|
||
JOIN orders o ON o.order_code = oi.order_code
|
||
${orderDateJoin}
|
||
LEFT JOIN cover_ledger cov
|
||
ON cov.order_code = oi.order_code AND cov.sku_code = oi.sku_code
|
||
LEFT JOIN customers cu ON cu.customer_code = o.customer_code
|
||
LEFT JOIN suppliers sup ON sup.supplier_code = oi.supplier_code
|
||
LEFT JOIN skus s ON s.sku_code = oi.sku_code
|
||
LEFT JOIN LATERAL (
|
||
SELECT c.category_name
|
||
FROM categories c
|
||
WHERE c.category_code = oi.category_code
|
||
ORDER BY CASE WHEN c.branch_code IS NOT DISTINCT FROM o.branch_code THEN 0 ELSE 1 END
|
||
LIMIT 1
|
||
) cat ON TRUE
|
||
WHERE ${orderDateCond} AND o.order_status >= 20 AND o.deleted_at IS NULL
|
||
AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> ''
|
||
AND COALESCE(oi.is_returned, false) = false ${branchO}
|
||
${customerSqlO}
|
||
${skuCategoryCond}
|
||
${skuNameCond}
|
||
/**
|
||
* **独立进货单不进「订单商品成本 / 订单采购成本」**(与列表页同一判据,含导出明细)。
|
||
*
|
||
* 独立进货是**进货/补库存**凭证(哨兵客户),不是客户订单;它的成本属存货。
|
||
* ⚠️ 复用销售侧既有判据 salesVisibleOrderSql(不新造口径)——导出若漏了这处,
|
||
* 页面已排除而导出仍在 ⇒ 同一页两个数(真库 BR002 该单 15 行 ¥1,449)。
|
||
* (注意:本注释在模板字符串里,**不要**写反引号,会截断模板。)
|
||
*/
|
||
AND ${salesVisibleOrderSql('o')}
|
||
),
|
||
line AS (
|
||
-- 抵扣段:货从仓库来 ⇒ 采购成本 0,成本全在库存成本列
|
||
SELECT order_code, delivery_date, customer_code, customer_name,
|
||
NULL::text AS supplier_code, NULL::text AS supplier_name,
|
||
'stock_cover' AS cost_bucket, sku_code, sku_name, category_name, unit,
|
||
cover_qty AS quantity, unit_cost,
|
||
0::numeric AS purchase_cost, cover_share AS stock_cover_cost,
|
||
CASE WHEN full_qty - cover_qty > 1e-9 THEN 0 ELSE sales_amount END AS sales_amount,
|
||
is_extra_dish, is_warehouse_processing
|
||
FROM src_line_base
|
||
WHERE cover_qty > 1e-9
|
||
UNION ALL
|
||
-- 缺口段:按供应商列归桶(自采/供应),采购成本 = 缺口 × 单价
|
||
SELECT order_code, delivery_date, customer_code, customer_name,
|
||
supplier_code, supplier_name,
|
||
gap_bucket AS cost_bucket, sku_code, sku_name, category_name, unit,
|
||
GREATEST(0, full_qty - cover_qty) AS quantity, unit_cost,
|
||
(GREATEST(0, full_qty - cover_qty) * unit_cost)::numeric AS purchase_cost,
|
||
0::numeric AS stock_cover_cost,
|
||
sales_amount,
|
||
is_extra_dish, is_warehouse_processing
|
||
FROM src_line_base
|
||
WHERE full_qty - cover_qty > 1e-9
|
||
)
|
||
SELECT line.*,
|
||
COUNT(*) OVER()::int AS full_count
|
||
FROM line
|
||
WHERE TRUE
|
||
${sourceCond}
|
||
ORDER BY line.delivery_date ASC NULLS LAST,
|
||
line.order_code ASC,
|
||
line.sku_code ASC
|
||
LIMIT $${limitIdx} OFFSET $${offsetIdx}`,
|
||
params
|
||
);
|
||
|
||
const total = Number(r.rows[0]?.full_count) || 0;
|
||
const data: SkuDirectCostLineRow[] = r.rows.map((row) => {
|
||
const bucket = String(row.cost_bucket || '');
|
||
const costSource: SkuCostSourceFilter =
|
||
bucket === 'supplier' ? 'supplier' : bucket === 'stock_cover' ? 'stock_cover' : 'self';
|
||
const qty = Number(row.quantity) || 0;
|
||
const purchase = round2(Number(row.purchase_cost) || 0);
|
||
// 库存成本:账本 inventory_cover 结转额(行真实成本 = 采购 + 库存,§5.1 定稿)
|
||
const stockCover = round2(Number(row.stock_cover_cost) || 0);
|
||
const realCost = round2(purchase + stockCover);
|
||
// 单位成本 = 行真实成本 ÷ 数量(与「订单商品成本」列表页同一口径)
|
||
const unitCost =
|
||
qty > 0 ? round2(realCost / qty) : round2(Number(row.unit_cost) || 0);
|
||
return {
|
||
order_code: String(row.order_code || ''),
|
||
delivery_date: row.delivery_date ? String(row.delivery_date).slice(0, 10) : null,
|
||
customer_code: row.customer_code ? String(row.customer_code) : null,
|
||
customer_name: row.customer_name ? String(row.customer_name) : null,
|
||
supplier_code:
|
||
costSource === 'supplier' ? (row.supplier_code ? String(row.supplier_code) : null) : null,
|
||
supplier_name:
|
||
costSource === 'supplier' ? (row.supplier_name ? String(row.supplier_name) : null) : null,
|
||
cost_source: costSource,
|
||
sku_code: String(row.sku_code || ''),
|
||
sku_name: String(row.sku_name || row.sku_code || '').replace(/(加菜)\s*$/, ''),
|
||
category_name: String(row.category_name || '-'),
|
||
quantity: round2(qty),
|
||
unit: String(row.unit || '').trim() || null,
|
||
unit_cost: unitCost,
|
||
purchase_cost: purchase,
|
||
stock_cover_cost: stockCover,
|
||
sales_amount: round2(Number(row.sales_amount) || 0),
|
||
is_extra_dish:
|
||
row.is_extra_dish === true || row.is_extra_dish === 't' || row.is_extra_dish === 1,
|
||
is_warehouse_processing:
|
||
row.is_warehouse_processing === true ||
|
||
row.is_warehouse_processing === 't' ||
|
||
row.is_warehouse_processing === 'true' ||
|
||
row.is_warehouse_processing === 1,
|
||
};
|
||
});
|
||
|
||
return {
|
||
data,
|
||
total,
|
||
page: safePage,
|
||
page_size: safeSize,
|
||
};
|
||
}
|
||
|
||
export async function getMarginByDimension(
|
||
cycleCode: string,
|
||
dimension: 'order' | 'customer' | 'sku',
|
||
ctx?: TenantContext | null,
|
||
limit = 50,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
) {
|
||
const result = await queryMarginRows(
|
||
cycleCode,
|
||
ctx,
|
||
dimension,
|
||
Math.min(limit, 200),
|
||
0,
|
||
null,
|
||
null,
|
||
dateFieldRaw,
|
||
customerCode
|
||
);
|
||
return result.rows;
|
||
}
|
||
|
||
export async function getMarginRowsPaged(
|
||
cycleCode: string,
|
||
dimension: 'order' | 'customer' | 'sku',
|
||
ctx?: TenantContext | null,
|
||
page = 1,
|
||
pageSize = 20,
|
||
sortField?: string | null,
|
||
sortOrder?: string | null,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
) {
|
||
const safePage = Math.max(1, Number(page) || 1);
|
||
const safeSize = Math.min(Math.max(Number(pageSize) || 20, 1), 100);
|
||
const offset = (safePage - 1) * safeSize;
|
||
const { rows, total } = await queryMarginRows(
|
||
cycleCode,
|
||
ctx,
|
||
dimension,
|
||
safeSize,
|
||
offset,
|
||
sortField,
|
||
sortOrder,
|
||
dateFieldRaw,
|
||
customerCode
|
||
);
|
||
return {
|
||
data: rows,
|
||
total,
|
||
page: safePage,
|
||
page_size: safeSize,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 负毛利告警:销售额 − SUM(qty×unit_cost) < 0(与毛利分维明细同口径)。
|
||
* 函数名保留 Ledger 以免大面积改引用;实现已不再读 cost_details。
|
||
* 见 docs/design/20260813-negative-margin-alert-unit-cost.md
|
||
*/
|
||
export async function listNegativeMarginFromLedger(
|
||
ctx?: TenantContext | null,
|
||
cycleCode?: string,
|
||
limit = 30,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
) {
|
||
const params: unknown[] = [];
|
||
const useDateRange = cycleCode ? isDateRangeCycle(cycleCode) : false;
|
||
const dateRange = useDateRange && cycleCode ? parseCycleToDateRange(cycleCode) : null;
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
let cycleIdx: number | null = null;
|
||
if (cycleCode && !useDateRange) {
|
||
params.push(cycleCode);
|
||
cycleIdx = params.length;
|
||
} else if (useDateRange && dateRange) {
|
||
params.push(dateRange.from, dateRange.to);
|
||
cycleIdx = params.length - 1; // from 的索引
|
||
}
|
||
const branchIdx = resolveBranchParam(ctx, params);
|
||
const branchO = branchEq('o', branchIdx);
|
||
const customerSql = ordersCustomerFilterSql(customerCode, params);
|
||
params.push(limit);
|
||
|
||
let cycleSql = '';
|
||
let orderDateJoin = '';
|
||
if (useDateRange && dateRange && cycleIdx != null) {
|
||
orderDateJoin = orderFinanceJoinSql(dateField, true);
|
||
cycleSql = `AND ${orderFinanceRangeCondSql(dateField, cycleIdx, cycleIdx + 1)}`;
|
||
} else if (cycleIdx) {
|
||
cycleSql = `AND o.cycle_code = $${cycleIdx}`;
|
||
}
|
||
|
||
const result = await pool.query(
|
||
`WITH order_margin AS (
|
||
SELECT o.order_code,
|
||
o.customer_code,
|
||
COALESCE(MAX(cu.company_name), o.customer_code) AS company_name,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS order_revenue,
|
||
COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)::numeric AS order_cost
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
${orderDateJoin}
|
||
LEFT JOIN customers cu ON cu.customer_code = o.customer_code
|
||
WHERE ${salesOrderPredicateSql('o')} ${cycleSql} ${branchO}
|
||
${customerSql}
|
||
AND ${salesItemPredicateSql('oi')}
|
||
GROUP BY o.order_code, o.customer_code
|
||
HAVING COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) > 0
|
||
AND COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0) < COALESCE(SUM(${ORDER_ITEM_MARGIN_COST_AMOUNT_SQL}), 0)
|
||
)
|
||
SELECT order_code, customer_code, company_name,
|
||
order_revenue, order_cost,
|
||
(order_revenue - order_cost)::numeric AS gross_profit
|
||
FROM order_margin
|
||
ORDER BY (order_revenue - order_cost) ASC
|
||
LIMIT $${params.length}`,
|
||
params
|
||
);
|
||
|
||
return result.rows.map((row) => ({
|
||
order_code: row.order_code,
|
||
customer_code: row.customer_code,
|
||
customer_name: row.company_name,
|
||
revenue: round2(Number(row.order_revenue) || 0),
|
||
total_cost: round2(Number(row.order_cost) || 0),
|
||
gross_profit: round2(Number(row.gross_profit) || 0),
|
||
gross_margin_pct:
|
||
Number(row.order_revenue) > 0
|
||
? round2((Number(row.gross_profit) / Number(row.order_revenue)) * 100)
|
||
: 0,
|
||
}));
|
||
}
|
||
|
||
export async function getMarginSummary(
|
||
cycleCode: string,
|
||
ctx?: TenantContext | null,
|
||
dateFieldRaw?: string | null,
|
||
customerCode?: string | null
|
||
) {
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const [aggregation, negativeAlerts] = await Promise.all([
|
||
getCostAggregation(cycleCode, ctx, dateField, customerCode),
|
||
listNegativeMarginFromLedger(ctx, cycleCode, 15, dateField, customerCode),
|
||
]);
|
||
|
||
return {
|
||
aggregation,
|
||
by_order: [],
|
||
by_customer: [],
|
||
by_sku: [],
|
||
negative_alerts: negativeAlerts,
|
||
date_field: dateField,
|
||
};
|
||
}
|
||
|
||
export interface FinanceOverviewStats {
|
||
week_revenue: number;
|
||
week_cost: number;
|
||
week_purchase_cost: number;
|
||
week_gross: number;
|
||
gross_margin_pct: number;
|
||
net_profit: number;
|
||
/** 净利润率 = 净利润 / 销售额 × 100;无销售额时为 0 */
|
||
net_profit_margin_pct: number;
|
||
/** 锁定公式 ID / 文案(见 financeNetProfitFormula.ts) */
|
||
net_profit_formula_id: typeof NET_PROFIT_FORMULA_ID;
|
||
net_profit_formula: string;
|
||
order_count: number;
|
||
receivable_total: number;
|
||
receivable_pending_count: number;
|
||
payable_total: number;
|
||
payable_pending_count: number;
|
||
/**
|
||
* 采购成本 = 自采 + 供应商 + 库存抵扣(开发者 2026-10-14 口径定稿)。
|
||
* 财务概览按订单入库日,成本管理商品成本排行按入账日。
|
||
*/
|
||
product_cost_total: number;
|
||
product_cost_self: number;
|
||
product_cost_supplier: number;
|
||
/** 第三桶:库存抵扣(账本 `inventory_cover` 结转额);`total = self + supplier + stock_cover` */
|
||
product_cost_stock_cover: number;
|
||
/** 期间均摊固定成本:非采购/非自由、未挂订单(order_code 为空),按入账日归集 */
|
||
period_fixed_cost: number;
|
||
/** 期间其他成本:free_overhead,按入账日归集 */
|
||
period_free_cost: number;
|
||
/** 区间所有成本:商品预估 + 非商品账本(2A:挂订单跟 date_field,无订单号跟入账日);**不含扣点** */
|
||
period_all_cost: number;
|
||
/** 客户「过账扣点」:不计入 period_all_cost / 构成,单独展示;但净利仍减去它 */
|
||
customer_rebate_cost: number;
|
||
/** 成本结构:名称 / 金额 / 占比;nav_tab 供前端跳转成本管理;cat_key 供改名 */
|
||
cost_buckets: Array<{
|
||
cat_key: string;
|
||
label: string;
|
||
amount: number;
|
||
value: number;
|
||
color: string;
|
||
nav_tab: 'sku' | 'fixed' | 'free' | 'records' | 'overview';
|
||
}>;
|
||
basis: 'settlement' | 'settlement_purchase' | 'settlement_sign_day' | 'quote_sheet' | 'order_estimate' | 'cost_details_ledger';
|
||
window_days: number;
|
||
date_from?: string | null;
|
||
date_to?: string | null;
|
||
/** 订单侧日期维度:配送日 / 下单日 / 入库日 */
|
||
date_field?: FinanceDateField;
|
||
}
|
||
|
||
const OVERVIEW_COST_COLORS: Record<string, string> = {
|
||
purchase: 'bg-gray-800',
|
||
delivery: 'bg-blue-600',
|
||
labor_processing: 'bg-amber-600',
|
||
labor: 'bg-amber-500',
|
||
loss: 'bg-red-500',
|
||
packaging: 'bg-emerald-600',
|
||
transport: 'bg-sky-600',
|
||
warehouse: 'bg-indigo-500',
|
||
overhead: 'bg-slate-500',
|
||
free_overhead: 'bg-violet-500',
|
||
rent: 'bg-stone-500',
|
||
utilities: 'bg-cyan-600',
|
||
adjustment: 'bg-orange-500',
|
||
refund: 'bg-rose-500',
|
||
};
|
||
|
||
/**
|
||
* 财务概览 KPI(一套账):
|
||
* - 销售额 = date_field 窗口内订单明细售价合计(week_revenue);默认配送日
|
||
* - 商品成本 = 同窗 cost_details 采购(含 purchase_applied;有效金额 allocated ?? amount)
|
||
* - 区间毛利 = 销售额 − 商品成本(订单 status≥20 录单即计)
|
||
* - 净利润 = 销售额 − 商品成本 − 期间固定 − 期间其他(期间仍按入账日 / 2A)
|
||
* - receivable_total 仍为结算单重叠应收(对照用,非销售额主卡)
|
||
* 见 docs/design/20260810-single-cost-ledger.md、20260810-margin-ledger-align.md
|
||
*/
|
||
export async function getFinanceOverviewStats(
|
||
ctx?: TenantContext | null,
|
||
opts: {
|
||
days?: number;
|
||
dateFrom?: string;
|
||
dateTo?: string;
|
||
dateField?: string | null;
|
||
customerCode?: string | null;
|
||
} = {}
|
||
): Promise<FinanceOverviewStats> {
|
||
const dateField = normalizeFinanceDateField(opts.dateField);
|
||
const customerFilter = normalizeCustomerCodeFilter(opts.customerCode);
|
||
// 解析窗口:优先自定义起止日期(YYYY-MM-DD 闭区间,中国时区),否则回退 days
|
||
let rangeStart: Date;
|
||
let rangeEnd: Date;
|
||
let usedDays: number;
|
||
let outDateFrom: string | null = null;
|
||
let outDateTo: string | null = null;
|
||
/** 自定义区间时用中国日闭区间;days 回退仍用 timestamptz 窗口 */
|
||
let useChinaDateBounds = false;
|
||
|
||
const df = String(opts.dateFrom || '').trim();
|
||
const dt = String(opts.dateTo || '').trim();
|
||
const isYmd = (s: string) => /^\d{4}-\d{2}-\d{2}$/.test(s);
|
||
|
||
if (df && dt && isYmd(df) && isYmd(dt)) {
|
||
rangeStart = new Date(`${df}T00:00:00+08:00`);
|
||
rangeEnd = new Date(`${dt}T23:59:59.999+08:00`);
|
||
if (rangeStart.getTime() > rangeEnd.getTime()) {
|
||
throw Object.assign(new Error('开始日期不能晚于结束日期'), { status: 400 });
|
||
}
|
||
const spanDays = (rangeEnd.getTime() - rangeStart.getTime()) / 86400000;
|
||
if (spanDays > 366) {
|
||
throw Object.assign(new Error('区间跨度不能超过 366 天'), { status: 400 });
|
||
}
|
||
usedDays = Math.max(1, Math.ceil(spanDays));
|
||
outDateFrom = df;
|
||
outDateTo = dt;
|
||
useChinaDateBounds = true;
|
||
} else {
|
||
const days = Math.min(Math.max(Number(opts.days) || 7, 1), 31);
|
||
rangeEnd = new Date();
|
||
rangeStart = new Date();
|
||
rangeStart.setDate(rangeStart.getDate() - days);
|
||
usedDays = days;
|
||
}
|
||
|
||
// 固定成本未录则沿用上月(仅当前分公司;惰性写入)
|
||
if (ctx?.branchCode) {
|
||
const { ensureFixedCostsCarriedForward } = await import('./fixedCostService');
|
||
const months: string[] = [];
|
||
if (useChinaDateBounds && outDateFrom && outDateTo) {
|
||
let y = Number(outDateFrom.slice(0, 4));
|
||
let m = Number(outDateFrom.slice(5, 7));
|
||
const ty = Number(outDateTo.slice(0, 4));
|
||
const tm = Number(outDateTo.slice(5, 7));
|
||
while (y < ty || (y === ty && m <= tm)) {
|
||
months.push(`${y}${String(m).padStart(2, '0')}`);
|
||
m += 1;
|
||
if (m > 12) {
|
||
m = 1;
|
||
y += 1;
|
||
}
|
||
}
|
||
} else {
|
||
const fmt = (d: Date) => {
|
||
const parts = new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
}).formatToParts(d);
|
||
const yy = parts.find((p) => p.type === 'year')?.value || '';
|
||
const mm = parts.find((p) => p.type === 'month')?.value || '';
|
||
return `${yy}${mm}`;
|
||
};
|
||
const a = fmt(rangeStart);
|
||
const b = fmt(rangeEnd);
|
||
months.push(a);
|
||
if (b !== a) months.push(b);
|
||
}
|
||
for (const ym of months) {
|
||
if (/^\d{6}$/.test(ym)) {
|
||
try {
|
||
await ensureFixedCostsCarriedForward({
|
||
cycleCode: ym,
|
||
branchCode: ctx.branchCode,
|
||
});
|
||
} catch (err) {
|
||
// 租户 schema / 缺表时不阻断概览主查询
|
||
console.warn(
|
||
'[finance-overview] ensureFixedCostsCarriedForward skipped:',
|
||
err instanceof Error ? err.message : err
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
const params: unknown[] = useChinaDateBounds
|
||
? [outDateFrom, outDateTo]
|
||
: [rangeStart.toISOString(), rangeEnd.toISOString()];
|
||
const branchIdx = resolveBranchParam(ctx, params);
|
||
const branchO = branchEq('o', branchIdx);
|
||
const customerSqlO = ordersCustomerFilterSql(customerFilter, params);
|
||
let orderDateJoin = '';
|
||
let orderInboundCond: string;
|
||
if (useChinaDateBounds) {
|
||
orderDateJoin = orderFinanceJoinSql(dateField, true);
|
||
orderInboundCond = orderFinanceRangeCondSql(dateField, 1, 2);
|
||
} else if (dateField === 'created_at') {
|
||
orderInboundCond = `o.created_at >= $1::timestamptz AND o.created_at <= $2::timestamptz`;
|
||
} else if (dateField === 'delivery_date') {
|
||
orderInboundCond = `o.delivery_date IS NOT NULL
|
||
AND o.delivery_date >= ($1::timestamptz AT TIME ZONE 'Asia/Shanghai')::date
|
||
AND o.delivery_date <= ($2::timestamptz AT TIME ZONE 'Asia/Shanghai')::date`;
|
||
} else {
|
||
orderDateJoin = ORDER_INBOUND_JOIN_SQL;
|
||
orderInboundCond = `COALESCE(ib.first_inbound_at, o.updated_at) >= $1::timestamptz
|
||
AND COALESCE(ib.first_inbound_at, o.updated_at) <= $2::timestamptz`;
|
||
}
|
||
|
||
const marginResult = await pool.query(
|
||
`WITH week_orders AS (
|
||
SELECT o.order_code
|
||
FROM orders o
|
||
${orderDateJoin}
|
||
WHERE ${salesOrderPredicateSql('o')}
|
||
AND ${orderInboundCond}
|
||
${branchO}
|
||
${customerSqlO}
|
||
),
|
||
rev AS (
|
||
SELECT
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue
|
||
FROM week_orders wo
|
||
JOIN order_items oi ON oi.order_code = wo.order_code
|
||
WHERE ${salesItemPredicateSql('oi')}
|
||
)
|
||
SELECT
|
||
(SELECT COUNT(*)::int FROM week_orders) AS order_count,
|
||
(SELECT revenue FROM rev) AS week_revenue`,
|
||
params
|
||
);
|
||
|
||
const weekRevenue = Number(marginResult.rows[0]?.week_revenue) || 0;
|
||
const orderCount = Number(marginResult.rows[0]?.order_count) || 0;
|
||
|
||
// 成本结构 / 所有成本 / 采购:统一账本窗
|
||
const shanghaiYmd = (d: Date) =>
|
||
new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
day: '2-digit',
|
||
}).format(d);
|
||
const structureDateFrom = outDateFrom || shanghaiYmd(rangeStart);
|
||
const structureDateTo = outDateTo || shanghaiYmd(rangeEnd);
|
||
const unified = await getPurchaseCostLedgerWindow({
|
||
dateFrom: structureDateFrom,
|
||
dateTo: structureDateTo,
|
||
branchCode: ctx?.branchCode && !ctx.isSuperAdmin ? ctx.branchCode : null,
|
||
dateField,
|
||
customerCode: customerFilter,
|
||
});
|
||
const structureParams: unknown[] = [structureDateFrom, structureDateTo];
|
||
let structureBranch = '';
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
structureParams.push(ctx.branchCode);
|
||
structureBranch = `AND cd.branch_code = $${structureParams.length}`;
|
||
}
|
||
const structureCustomer = costDetailsCustomerFilterSql(customerFilter, structureParams);
|
||
const structureDateCond = costDetailsLinkedOrPeriodCondSql(dateField, 1, 2);
|
||
// 客户「过账扣点」:2026-10-08 用户批准的过账扣点口径,在本函数自己的周期区间上多取一笔成本,
|
||
// 「所有成本」多一行、净利多减一笔;不改采购成本/毛利/期间其他成本。关闭态 ⇒ 0,逐位不变。
|
||
const customerRebateCost = await queryCustomerRebateCost(
|
||
structureDateFrom,
|
||
structureDateTo,
|
||
dateField,
|
||
ctx?.branchCode && !ctx.isSuperAdmin ? ctx.branchCode : null,
|
||
customerFilter
|
||
);
|
||
// 动态导入,避免与 freeCostService ↔ marginQueryService 循环依赖
|
||
const { loadCostLabelContext, resolveCostBucketLabelSync } = await import('./costDisplayNameService');
|
||
const labelCtx = await loadCostLabelContext(ctx?.branchCode || null);
|
||
const structureBucketResult = await pool.query(
|
||
`SELECT cat_key, SUM(amt)::numeric AS total
|
||
FROM (
|
||
SELECT
|
||
CASE
|
||
WHEN cd.cost_type IN ('purchase', 'purchase_applied') THEN 'product'
|
||
WHEN cd.reference_type = 'fixed_cost' THEN
|
||
'fixed:' || COALESCE(
|
||
NULLIF(TRIM(fc.cost_type), ''),
|
||
CASE
|
||
WHEN cd.cost_subtype LIKE 'day:%' THEN NULLIF(TRIM(cd.cost_type), '')
|
||
WHEN POSITION('|' IN COALESCE(cd.cost_subtype, '')) > 0
|
||
THEN NULLIF(TRIM(split_part(cd.cost_subtype, '|', 1)), '')
|
||
ELSE NULLIF(TRIM(cd.cost_subtype), '')
|
||
END,
|
||
NULLIF(TRIM(cd.cost_type), ''),
|
||
'other'
|
||
)
|
||
WHEN cd.cost_type = 'free_overhead' THEN
|
||
'free:' || COALESCE(NULLIF(TRIM(cd.cost_subtype), ''), 'misc')
|
||
ELSE 'type:' || COALESCE(NULLIF(TRIM(cd.cost_type), ''), 'overhead')
|
||
END AS cat_key,
|
||
${CD_EFFECTIVE_AMOUNT_SQL} AS amt
|
||
FROM cost_details cd
|
||
LEFT JOIN fixed_costs fc
|
||
ON cd.reference_type = 'fixed_cost'
|
||
AND fc.id::text = cd.reference_id
|
||
WHERE ${structureDateCond}
|
||
AND ${excludePurchaseDupesForKpiSql('cd')}
|
||
AND ${excludeInventoryHoldingFromKpiSql('cd')}
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
${structureBranch}
|
||
${structureCustomer}
|
||
) x
|
||
GROUP BY cat_key
|
||
HAVING SUM(amt) > 0
|
||
ORDER BY total DESC`,
|
||
structureParams
|
||
);
|
||
// 采购项改用「订单行口径」(quantity × unit_cost),与「订单采购成本」卡/商品成本表同源。
|
||
// 原因:账本 cost_details 在部分订单上只有验收入库同步的占位行、或正式货值行按入账日
|
||
// 落在所选窗口之外,会系统性低估采购成本(实测某窗口账本 3,731.73 vs 订单行 8,726.85),
|
||
// 导致「所有成本」与净利被压低。其它构成(人工/车辆/房租/其他)仍读账本。
|
||
// 用户 2026-09-14 确认方案 A。
|
||
const orderLinePurchase = await getOrderLinePurchaseTotal(
|
||
`${structureDateFrom.replace(/-/g, '')}_${structureDateTo.replace(/-/g, '')}`,
|
||
ctx,
|
||
dateField,
|
||
customerFilter
|
||
);
|
||
// 非采购构成继续读取账本;采购项用订单行口径
|
||
const structureRowsRaw = structureBucketResult.rows as Array<{ cat_key: string; total: number }>;
|
||
const structureRows = [
|
||
...(orderLinePurchase.purchase > 0
|
||
? [{ cat_key: 'product', total: orderLinePurchase.purchase }]
|
||
: []),
|
||
...structureRowsRaw.filter((row) => String(row.cat_key) !== 'product'),
|
||
// 客户「过账扣点」**不进构成**(用户 2026-10-08 裁决):所有成本 = 各构成项之和,不含扣点;
|
||
// 扣点单独由 `customer_rebate_cost` 返回,前端单独展示;净利仍减去它。
|
||
];
|
||
// 合计改为「各构成项之和」,保证「所有成本」与下方构成分析/占比口径一致
|
||
const structureSum = round2(
|
||
structureRows.reduce((sum, row) => sum + (Number(row.total) || 0), 0)
|
||
);
|
||
// 兼容字段:账本采购额(供对照/排查,不再用于卡片与构成)
|
||
const purchaseLedgerTotal = unified.purchase;
|
||
const cost_buckets =
|
||
structureRows.length > 0
|
||
? structureRows.map((b) => {
|
||
const amt = Number(b.total) || 0;
|
||
const catKey = String(b.cat_key || '');
|
||
let nav_tab: 'sku' | 'fixed' | 'free' | 'records' | 'overview' = 'records';
|
||
let colorKey = 'overhead';
|
||
if (catKey === 'product') {
|
||
nav_tab = 'sku';
|
||
colorKey = 'purchase';
|
||
} else if (catKey.startsWith('fixed:')) {
|
||
const fk = catKey.slice('fixed:'.length);
|
||
nav_tab = 'fixed';
|
||
colorKey = fk in OVERVIEW_COST_COLORS ? fk : 'rent';
|
||
} else if (catKey.startsWith('free:')) {
|
||
nav_tab = 'free';
|
||
colorKey = 'free_overhead';
|
||
} else if (catKey.startsWith('type:')) {
|
||
const tk = catKey.slice('type:'.length);
|
||
nav_tab = 'records';
|
||
colorKey = tk in OVERVIEW_COST_COLORS ? tk : 'overhead';
|
||
}
|
||
const label = resolveCostBucketLabelSync(catKey, {
|
||
displayNames: labelCtx.displayNames,
|
||
fixedTypes: labelCtx.fixedTypes,
|
||
freeTypes: labelCtx.freeTypes,
|
||
costTypeLabels: COST_TYPE_LABELS,
|
||
});
|
||
return {
|
||
cat_key: catKey,
|
||
label,
|
||
amount: round2(amt),
|
||
value: structureSum > 0 ? Math.round((amt / structureSum) * 1000) / 10 : 0,
|
||
color: OVERVIEW_COST_COLORS[colorKey] || 'bg-gray-500',
|
||
nav_tab,
|
||
};
|
||
})
|
||
: [];
|
||
|
||
// 应收/应付按「结算单账期与所选区间重叠」统计总额(含已结清,反映区间内产生的应收/应付)
|
||
// cycle_code:YYYYMMDD(按天)/ YYYYMM(整月)/ YYYYMMDD_YYYYMMDD(自定义区间)
|
||
const rangeFromDate = outDateFrom || rangeStart.toISOString().slice(0, 10);
|
||
const rangeToDate = outDateTo || rangeEnd.toISOString().slice(0, 10);
|
||
const cycleOverlapSql = `
|
||
(
|
||
CASE
|
||
WHEN %alias%.cycle_code ~ '^\\d{8}_\\d{8}$'
|
||
THEN to_date(substring(%alias%.cycle_code from 1 for 8), 'YYYYMMDD')
|
||
WHEN %alias%.cycle_code ~ '^\\d{8}$'
|
||
THEN to_date(%alias%.cycle_code, 'YYYYMMDD')
|
||
WHEN %alias%.cycle_code ~ '^\\d{6}$'
|
||
THEN to_date(%alias%.cycle_code || '01', 'YYYYMMDD')
|
||
END
|
||
) <= $1::date
|
||
AND
|
||
(
|
||
CASE
|
||
WHEN %alias%.cycle_code ~ '^\\d{8}_\\d{8}$'
|
||
THEN to_date(substring(%alias%.cycle_code from 10 for 8), 'YYYYMMDD')
|
||
WHEN %alias%.cycle_code ~ '^\\d{8}$'
|
||
THEN to_date(%alias%.cycle_code, 'YYYYMMDD')
|
||
WHEN %alias%.cycle_code ~ '^\\d{6}$'
|
||
THEN (to_date(%alias%.cycle_code || '01', 'YYYYMMDD') + interval '1 month - 1 day')::date
|
||
END
|
||
) >= $2::date`.replace(/%alias%/g, 'cs');
|
||
|
||
const recvParams: unknown[] = [rangeToDate, rangeFromDate];
|
||
let recvBranch = '';
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
recvParams.push(ctx.branchCode);
|
||
recvBranch = `AND cs.branch_code = $${recvParams.length}`;
|
||
}
|
||
let recvCustomer = '';
|
||
if (customerFilter) {
|
||
recvParams.push(customerFilter);
|
||
recvCustomer = `AND cs.customer_code = $${recvParams.length}`;
|
||
}
|
||
// 与客户结算列表同口径(账期重叠 + CS* 去重 + 隐藏零金额空壳)
|
||
const recvSharedFilters = customerStatementSharedFiltersSql('cs');
|
||
const receivables = await pool.query(
|
||
`SELECT
|
||
COALESCE(SUM(cs.total_amount), 0)::numeric AS range_total,
|
||
COALESCE(SUM(CASE WHEN COALESCE(cs.statement_status,0) < 30 THEN COALESCE(cs.unpaid_amount,0) ELSE 0 END), 0)::numeric AS open_total,
|
||
COALESCE(SUM(CASE WHEN COALESCE(cs.statement_status,0) < 30 AND COALESCE(cs.unpaid_amount,0) > 0 THEN 1 ELSE 0 END), 0)::int AS open_count
|
||
FROM customer_statements cs
|
||
WHERE ${cycleOverlapSql} ${recvBranch}
|
||
${recvCustomer}
|
||
${recvSharedFilters}
|
||
AND ${statementHasLiveOrderLinkSql('cs', 'customer')}`,
|
||
recvParams
|
||
);
|
||
const receivableTotal = Number(receivables.rows[0]?.range_total) || 0;
|
||
const openRecvCount = Number(receivables.rows[0]?.open_count) || 0;
|
||
|
||
const cycleOverlapSqlPay = cycleOverlapSql.replace(/cs\./g, 'ss.');
|
||
const payParams: unknown[] = [rangeToDate, rangeFromDate];
|
||
let payBranch = '';
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
payParams.push(ctx.branchCode);
|
||
payBranch = `AND ss.branch_code = $${payParams.length}`;
|
||
}
|
||
const payables = await pool.query(
|
||
`SELECT
|
||
COALESCE(SUM(ss.payable_amount), 0)::numeric AS range_total,
|
||
COALESCE(SUM(CASE WHEN COALESCE(ss.statement_status,0) < 30 AND COALESCE(ss.payable_amount,0) > 0 THEN 1 ELSE 0 END), 0)::int AS open_count
|
||
FROM supplier_statements ss
|
||
WHERE ${cycleOverlapSqlPay} ${payBranch}
|
||
AND ${statementHasLiveOrderLinkSql('ss', 'supplier')}`,
|
||
payParams
|
||
);
|
||
const payableTotal = Number(payables.rows[0]?.range_total) || 0;
|
||
const openPayCount = Number(payables.rows[0]?.open_count) || 0;
|
||
|
||
// 期间固定/其他:与构成同轴 2A(一套账)
|
||
// 选客户时:无单号期间成本按当窗客户数均摊;挂该客户订单的期间行仍归该客户
|
||
const periodSideParams: unknown[] = [structureDateFrom, structureDateTo];
|
||
let periodSideBranch = '';
|
||
if (ctx?.branchCode && !ctx.isSuperAdmin) {
|
||
periodSideParams.push(ctx.branchCode);
|
||
periodSideBranch = `AND cd.branch_code = $${periodSideParams.length}`;
|
||
}
|
||
const periodDateCond = costDetailsLinkedOrPeriodCondSql(dateField, 1, 2);
|
||
const orphanOrderSql = `(cd.order_code IS NULL OR TRIM(cd.order_code) = '')`;
|
||
|
||
let periodFixedCost = 0;
|
||
let freeCostTotal = 0;
|
||
/** 选客户时加回「所有成本」的无单号均摊额(挂单部分已在 structureSum) */
|
||
let allocatedOrphanIntoAll = 0;
|
||
|
||
if (customerFilter) {
|
||
const [orphanFixedResult, orphanFreeResult] = await Promise.all([
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE ${periodDateCond}
|
||
AND ${PERIOD_FIXED_COST_SQL_PREDICATE}
|
||
AND ${orphanOrderSql}
|
||
${periodSideBranch}`,
|
||
periodSideParams
|
||
),
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = 'free_overhead'
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
AND ${periodDateCond}
|
||
AND ${orphanOrderSql}
|
||
${periodSideBranch}`,
|
||
periodSideParams
|
||
),
|
||
]);
|
||
|
||
const linkedFixedParams = [...periodSideParams];
|
||
const linkedFixedCustomer = costDetailsCustomerFilterSql(customerFilter, linkedFixedParams);
|
||
const linkedFreeParams = [...periodSideParams];
|
||
const linkedFreeCustomer = costDetailsCustomerFilterSql(customerFilter, linkedFreeParams);
|
||
const [linkedFixedResult, linkedFreeResult] = await Promise.all([
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE ${periodDateCond}
|
||
AND ${PERIOD_FIXED_COST_SQL_PREDICATE}
|
||
AND NOT ${orphanOrderSql}
|
||
${periodSideBranch}
|
||
${linkedFixedCustomer}`,
|
||
linkedFixedParams
|
||
),
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = 'free_overhead'
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
AND ${periodDateCond}
|
||
AND NOT ${orphanOrderSql}
|
||
${periodSideBranch}
|
||
${linkedFreeCustomer}`,
|
||
linkedFreeParams
|
||
),
|
||
]);
|
||
|
||
// 与销售额同窗的有单客户数(录单起)
|
||
const custCountParams: unknown[] = useChinaDateBounds
|
||
? [outDateFrom, outDateTo]
|
||
: [rangeStart.toISOString(), rangeEnd.toISOString()];
|
||
const custCountBranchIdx = resolveBranchParam(ctx, custCountParams);
|
||
const custCountBranchO = branchEq('o', custCountBranchIdx);
|
||
let custCountDateJoin = '';
|
||
let custCountDateCond: string;
|
||
if (useChinaDateBounds) {
|
||
custCountDateJoin = orderFinanceJoinSql(dateField, true);
|
||
custCountDateCond = orderFinanceRangeCondSql(dateField, 1, 2);
|
||
} else if (dateField === 'created_at') {
|
||
custCountDateCond = `o.created_at >= $1::timestamptz AND o.created_at <= $2::timestamptz`;
|
||
} else if (dateField === 'delivery_date') {
|
||
custCountDateCond = `o.delivery_date IS NOT NULL
|
||
AND o.delivery_date >= ($1::timestamptz AT TIME ZONE 'Asia/Shanghai')::date
|
||
AND o.delivery_date <= ($2::timestamptz AT TIME ZONE 'Asia/Shanghai')::date`;
|
||
} else {
|
||
custCountDateJoin = ORDER_INBOUND_JOIN_SQL;
|
||
custCountDateCond = `COALESCE(ib.first_inbound_at, o.updated_at) >= $1::timestamptz
|
||
AND COALESCE(ib.first_inbound_at, o.updated_at) <= $2::timestamptz`;
|
||
}
|
||
const custCountResult = await pool.query(
|
||
`SELECT COUNT(DISTINCT NULLIF(TRIM(o.customer_code), ''))::int AS cnt
|
||
FROM orders o
|
||
${custCountDateJoin}
|
||
WHERE ${salesOrderPredicateSql('o')}
|
||
AND ${custCountDateCond}
|
||
${custCountBranchO}
|
||
AND o.customer_code IS NOT NULL AND TRIM(o.customer_code) <> ''`,
|
||
custCountParams
|
||
);
|
||
const customerCount = Math.max(0, Number(custCountResult.rows[0]?.cnt) || 0);
|
||
const orphanFixed = Number(orphanFixedResult.rows[0]?.total) || 0;
|
||
const orphanFree = Number(orphanFreeResult.rows[0]?.total) || 0;
|
||
const share = customerCount > 0 ? 1 / customerCount : 0;
|
||
const orphanFixedShare = orphanFixed * share;
|
||
const orphanFreeShare = orphanFree * share;
|
||
periodFixedCost =
|
||
(Number(linkedFixedResult.rows[0]?.total) || 0) + orphanFixedShare;
|
||
freeCostTotal =
|
||
(Number(linkedFreeResult.rows[0]?.total) || 0) + orphanFreeShare;
|
||
allocatedOrphanIntoAll = round2(orphanFixedShare + orphanFreeShare);
|
||
} else {
|
||
const periodFixedResult = await pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE ${periodDateCond}
|
||
AND ${PERIOD_FIXED_COST_SQL_PREDICATE}
|
||
${periodSideBranch}`,
|
||
periodSideParams
|
||
);
|
||
periodFixedCost = Number(periodFixedResult.rows[0]?.total) || 0;
|
||
const freeCostResult = await pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = 'free_overhead'
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
AND ${periodDateCond}
|
||
${periodSideBranch}`,
|
||
periodSideParams
|
||
);
|
||
freeCostTotal = Number(freeCostResult.rows[0]?.total) || 0;
|
||
}
|
||
|
||
// 商品侧采购成本:统一用「订单行口径」,与销售额同源、且与「所有成本」的采购项一致。
|
||
// 原实现优先读账本(purchaseLedgerTotal),会与订单口径的销售额混算,压低毛利/净利。
|
||
const productCostSelf = orderLinePurchase.purchase_self;
|
||
const productCostSupplier = orderLinePurchase.purchase_supplier;
|
||
const productCostTotal = orderLinePurchase.purchase;
|
||
|
||
const periodAllCost = customerFilter
|
||
? round2(structureSum + allocatedOrphanIntoAll)
|
||
: structureSum;
|
||
const weekCost = periodAllCost;
|
||
// 净利润:商品侧用订单行采购成本(与销售额同口径);固定/其他仍读账本
|
||
const profit = computeFinanceNetProfit({
|
||
revenue: weekRevenue,
|
||
productCost: productCostTotal,
|
||
periodFixedCost,
|
||
periodFreeCost: freeCostTotal,
|
||
});
|
||
const weekGross = profit.grossProfit;
|
||
const grossMarginPct = weekRevenue > 0 ? round2((weekGross / weekRevenue) * 100) : 0;
|
||
// 净利:2026-10-08 用户批准的过账扣点口径 —— 公式本身不动(computeFinanceNetProfit 是唯一实现),
|
||
// 只在这里多减一笔「客户过账扣点」,并同步重算净利率;关闭态扣点为 0 ⇒ 逐位不变。
|
||
const netProfit = round2(profit.netProfit - customerRebateCost);
|
||
const netProfitMarginPct =
|
||
weekRevenue > 0 ? round2((netProfit / weekRevenue) * 100) : profit.netProfitMarginPct;
|
||
|
||
return {
|
||
week_revenue: round2(weekRevenue),
|
||
week_cost: round2(weekCost),
|
||
week_purchase_cost: round2(productCostTotal),
|
||
week_gross: round2(weekGross),
|
||
gross_margin_pct: grossMarginPct,
|
||
net_profit: round2(netProfit),
|
||
net_profit_margin_pct: netProfitMarginPct,
|
||
net_profit_formula_id: profit.formulaId,
|
||
net_profit_formula: customerFilter
|
||
? `${profit.formulaLabel}(期间固定/其他按当窗客户数均摊)`
|
||
: profit.formulaLabel,
|
||
order_count: orderCount,
|
||
receivable_total: round2(receivableTotal),
|
||
receivable_pending_count: openRecvCount,
|
||
payable_total: round2(payableTotal),
|
||
payable_pending_count: openPayCount,
|
||
product_cost_total: round2(productCostTotal),
|
||
product_cost_self: round2(productCostSelf),
|
||
product_cost_supplier: round2(productCostSupplier),
|
||
product_cost_stock_cover: round2(orderLinePurchase.purchase_stock_cover),
|
||
period_fixed_cost: round2(periodFixedCost),
|
||
period_free_cost: round2(freeCostTotal),
|
||
period_all_cost: round2(periodAllCost),
|
||
customer_rebate_cost: round2(customerRebateCost),
|
||
cost_buckets,
|
||
basis: 'cost_details_ledger',
|
||
window_days: usedDays,
|
||
date_from: outDateFrom,
|
||
date_to: outDateTo,
|
||
date_field: dateField,
|
||
};
|
||
}
|
||
|
||
const COST_TYPE_LABELS: Record<string, string> = {
|
||
purchase: '采购成本',
|
||
purchase_applied: '采购成本',
|
||
inventory_holding: '库存持有',
|
||
processing: '加工成本',
|
||
labor: '人工成本',
|
||
labor_sorting: '分拣人工',
|
||
labor_processing: '加工人工',
|
||
delivery: '配送成本',
|
||
free_overhead: '其他成本',
|
||
rent: '房租物业',
|
||
utilities: '水电',
|
||
transport: '运输成本',
|
||
packaging: '包材成本',
|
||
warehouse: '仓储成本',
|
||
loss: '损耗成本',
|
||
depreciation: '折旧',
|
||
other: '其他成本',
|
||
overhead: '管理费用',
|
||
adjustment: '成本调整',
|
||
fixed_overhead: '固定费用',
|
||
refund: '退款回冲',
|
||
vehicle: '车辆相关',
|
||
salary: '人工工资',
|
||
equipment: '设备折旧',
|
||
/** 客户「过账扣点」(2026-10-08 用户批准的过账扣点口径;实时算、不落库) */
|
||
customer_rebate: '客户过账扣点',
|
||
};
|
||
|
||
/** 看板账本构成固定大类(与成本管理 COST_CATEGORIES 对齐;金额为 0 也展示) */
|
||
const DASHBOARD_LEDGER_FIXED_BUCKETS: Array<{ cost_type: string; label: string }> = [
|
||
{ cost_type: 'purchase', label: '采购成本' },
|
||
{ cost_type: 'labor_sorting', label: '分拣人工' },
|
||
{ cost_type: 'labor_processing', label: '加工人工' },
|
||
{ cost_type: 'packaging', label: '包材成本' },
|
||
{ cost_type: 'transport', label: '运输成本' },
|
||
{ cost_type: 'delivery', label: '配送成本' },
|
||
{ cost_type: 'warehouse', label: '仓储成本' },
|
||
{ cost_type: 'loss', label: '损耗成本' },
|
||
{ cost_type: 'overhead', label: '管理费用' },
|
||
];
|
||
|
||
function pctChange(current: number, previous: number): number | null {
|
||
if (!(previous > 0)) return null;
|
||
return Math.round(((current - previous) / previous) * 100);
|
||
}
|
||
|
||
function toShanghaiYmd(d: Date): string {
|
||
return new Intl.DateTimeFormat('en-CA', {
|
||
timeZone: 'Asia/Shanghai',
|
||
year: 'numeric',
|
||
month: '2-digit',
|
||
day: '2-digit',
|
||
}).format(d);
|
||
}
|
||
|
||
/**
|
||
* 取本窗口的客户「过账扣点」成本(2026-10-08 用户批准的过账扣点口径)。
|
||
*
|
||
* - 只读、实时算、不落库(客户未开启 ⇒ 全为 0,既有数字逐位不变);
|
||
* - `dateField` 必须与本次聚合的日期口径一致,取值的**唯一来源**是调用方的
|
||
* `normalizeFinanceDateField` 结果(三个口径 delivery_date / created_at / inbound 都支持,
|
||
* 其中 inbound 与财务概览同一表达式);遇到未知口径 ⇒ 跳过(按 0 计)并 warn,不抛错;
|
||
* - 整段取数 try/catch:任何异常一律降级为 0,绝不让看板/财务接口因这条新逻辑报错。
|
||
*/
|
||
async function queryCustomerRebateCost(
|
||
dateFrom: string,
|
||
dateTo: string,
|
||
dateField: FinanceDateField,
|
||
branchCode: string | null,
|
||
customerCode: string | null
|
||
): Promise<number> {
|
||
const supported: RebateDateField[] = ['delivery_date', 'created_at', 'inbound', 'cycle_code'];
|
||
if (!supported.includes(dateField as RebateDateField)) {
|
||
console.warn(
|
||
`[customer-rebate] 不支持日期口径 ${dateField},看板/财务概览按 0 计(跳过扣点成本)`
|
||
);
|
||
return 0;
|
||
}
|
||
try {
|
||
// 动态导入,避免与 customerRebateService 之间出现循环依赖
|
||
const { summarizeCustomerRebate } = await import('./customerRebateService');
|
||
const summary = await summarizeCustomerRebate({
|
||
from: dateFrom,
|
||
to: dateTo,
|
||
dateField: dateField as RebateDateField,
|
||
branchCode,
|
||
customerCode,
|
||
});
|
||
return round2(Number(summary.rebate_cost) || 0);
|
||
} catch (err) {
|
||
console.warn(
|
||
'[customer-rebate] 扣点成本取数失败,降级为 0:',
|
||
err instanceof Error ? err.message : err
|
||
);
|
||
return 0;
|
||
}
|
||
}
|
||
|
||
async function querySalesWindow(
|
||
start: Date,
|
||
end: Date,
|
||
branchCode: string | null,
|
||
dateField: FinanceDateField = 'delivery_date'
|
||
): Promise<{ revenue: number; orderCount: number }> {
|
||
const field = dateField === 'created_at' ? 'created_at' : 'delivery_date';
|
||
const params: unknown[] = [toShanghaiYmd(start), toShanghaiYmd(end)];
|
||
let branchIdx: number | null = null;
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
branchIdx = params.length;
|
||
}
|
||
const branchO = branchEq('o', branchIdx);
|
||
const orderDateCond = orderFinanceRangeCondSql(field, 1, 2);
|
||
|
||
// 销售额与财务概览同口径(locked_price ?? price);成本不在此算
|
||
const result = await pool.query(
|
||
`SELECT COUNT(DISTINCT o.order_code)::int AS order_count,
|
||
COALESCE(SUM(${ORDER_ITEM_REVENUE_SQL}), 0)::numeric AS revenue
|
||
FROM orders o
|
||
JOIN order_items oi ON oi.order_code = o.order_code
|
||
WHERE ${salesLinePredicateSql('o', 'oi')}
|
||
AND ${orderDateCond}
|
||
${branchO}`,
|
||
params
|
||
);
|
||
|
||
return {
|
||
revenue: Number(result.rows[0]?.revenue) || 0,
|
||
orderCount: Number(result.rows[0]?.order_count) || 0,
|
||
};
|
||
}
|
||
|
||
export interface DashboardCostOverview {
|
||
quote_revenue: number;
|
||
quote_cost: number;
|
||
quote_gross: number;
|
||
gross_margin_pct: number;
|
||
completed_orders: number;
|
||
prev_quote_revenue: number;
|
||
prev_quote_cost: number;
|
||
prev_quote_gross: number;
|
||
prev_gross_margin_pct: number;
|
||
revenue_change_pct: number | null;
|
||
cost_change_pct: number | null;
|
||
gross_change_pct: number | null;
|
||
margin_change_pp: number | null;
|
||
ledger_total: number;
|
||
ledger_buckets: Array<{ cost_type: string; label: string; amount: number; pct: number }>;
|
||
/**
|
||
* 客户「过账扣点」(用户 2026-10-08 裁决):**不计入「所有成本」构成**,单独一张卡展示;
|
||
* 但净利仍减去它(`net_profit` = 公式结果 − 本值)。
|
||
*/
|
||
customer_rebate_cost: number;
|
||
/** 与财务概览同口径:computeFinanceNetProfit */
|
||
net_profit: number;
|
||
net_profit_margin_pct: number;
|
||
prev_net_profit: number;
|
||
net_profit_change_pct: number | null;
|
||
net_profit_formula: typeof NET_PROFIT_FORMULA_LABEL;
|
||
basis: 'cost_details_ledger' | 'quote_sheet';
|
||
}
|
||
|
||
/** 期间固定 + 期间其他(净利润公式入参;与财务概览同轴 2A) */
|
||
async function queryPeriodFixedAndFree(
|
||
dateFrom: string,
|
||
dateTo: string,
|
||
branchCode: string | null,
|
||
dateField: FinanceDateField
|
||
): Promise<{ periodFixedCost: number; periodFreeCost: number }> {
|
||
const params: unknown[] = [dateFrom, dateTo];
|
||
let branchSql = '';
|
||
if (branchCode) {
|
||
params.push(branchCode);
|
||
branchSql = `AND cd.branch_code = $${params.length}`;
|
||
}
|
||
const periodDateCond = costDetailsLinkedOrPeriodCondSql(dateField, 1, 2);
|
||
const [fixedRes, freeRes] = await Promise.all([
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE ${periodDateCond}
|
||
AND ${PERIOD_FIXED_COST_SQL_PREDICATE}
|
||
${branchSql}`,
|
||
params
|
||
),
|
||
pool.query(
|
||
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
|
||
FROM cost_details cd
|
||
WHERE cd.cost_type = 'free_overhead'
|
||
AND ${CD_POSTED_STATUS_SQL}
|
||
AND ${periodDateCond}
|
||
${branchSql}`,
|
||
params
|
||
),
|
||
]);
|
||
return {
|
||
periodFixedCost: Number(fixedRes.rows[0]?.total) || 0,
|
||
periodFreeCost: Number(freeRes.rows[0]?.total) || 0,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 数据看板「成本与毛利」:
|
||
* - 销售额:与财务概览同口径(订单行售价)
|
||
* - 货品成本 / 账本合计:getPurchaseCostLedgerWindow(2A)
|
||
* - 净利润:锁定公式 computeFinanceNetProfit
|
||
*/
|
||
export async function getDashboardCostOverview(
|
||
start: Date,
|
||
end: Date,
|
||
previousStart: Date,
|
||
previousEnd: Date,
|
||
branchCode: string | null,
|
||
dateFieldRaw?: string | null
|
||
): Promise<DashboardCostOverview> {
|
||
const dateField = normalizeFinanceDateField(dateFieldRaw);
|
||
const dashField: FinanceDateField = dateField === 'created_at' ? 'created_at' : 'delivery_date';
|
||
const dateFrom = toShanghaiYmd(start);
|
||
const dateTo = toShanghaiYmd(end);
|
||
const prevFrom = toShanghaiYmd(previousStart);
|
||
const prevTo = toShanghaiYmd(previousEnd);
|
||
const [current, previous, unified, prevUnified, periodSides, prevPeriodSides] = await Promise.all([
|
||
querySalesWindow(start, end, branchCode, dashField),
|
||
querySalesWindow(previousStart, previousEnd, branchCode, dashField),
|
||
getPurchaseCostLedgerWindow({
|
||
dateFrom,
|
||
dateTo,
|
||
branchCode,
|
||
dateField: dashField,
|
||
}),
|
||
getPurchaseCostLedgerWindow({
|
||
dateFrom: prevFrom,
|
||
dateTo: prevTo,
|
||
branchCode,
|
||
dateField: dashField,
|
||
}),
|
||
queryPeriodFixedAndFree(dateFrom, dateTo, branchCode, dashField),
|
||
queryPeriodFixedAndFree(prevFrom, prevTo, branchCode, dashField),
|
||
]);
|
||
|
||
const amountByType = new Map<string, number>();
|
||
for (const row of unified.by_type) {
|
||
amountByType.set(row.cost_type, row.amount);
|
||
}
|
||
const fixedTypes = new Set(DASHBOARD_LEDGER_FIXED_BUCKETS.map((b) => b.cost_type));
|
||
const fixedLabel = new Map(DASHBOARD_LEDGER_FIXED_BUCKETS.map((b) => [b.cost_type, b.label]));
|
||
const ledgerBucketsRaw: Array<{ cost_type: string; label: string; amount: number }> = [
|
||
...DASHBOARD_LEDGER_FIXED_BUCKETS.map((b) => ({
|
||
cost_type: b.cost_type,
|
||
label: b.label,
|
||
amount: amountByType.get(b.cost_type) || 0,
|
||
})),
|
||
...[...amountByType.entries()]
|
||
.filter(([costType, amount]) => amount > 0 && !fixedTypes.has(costType))
|
||
.map(([costType, amount]) => ({
|
||
cost_type: costType,
|
||
label: COST_TYPE_LABELS[costType] || costType,
|
||
amount,
|
||
})),
|
||
];
|
||
// 构成排序:金额从高到低;金额相同按固定桶顺序,固定桶优先于非固定桶。
|
||
// ⚠️ 必须在「金额覆盖」(采购改用订单行口径)**之后**再排 —— 覆盖前排的是账本采购额、
|
||
// 显示的却是订单行采购额,两者不等时该行会排错位。
|
||
const compareLedgerBuckets = (
|
||
a: { cost_type: string; label: string; amount: number },
|
||
b: { cost_type: string; label: string; amount: number }
|
||
) => {
|
||
if (b.amount !== a.amount) return b.amount - a.amount;
|
||
const ai = DASHBOARD_LEDGER_FIXED_BUCKETS.findIndex((x) => x.cost_type === a.cost_type);
|
||
const bi = DASHBOARD_LEDGER_FIXED_BUCKETS.findIndex((x) => x.cost_type === b.cost_type);
|
||
if (ai >= 0 && bi >= 0) return ai - bi;
|
||
if (ai >= 0) return -1;
|
||
if (bi >= 0) return 1;
|
||
return (fixedLabel.get(a.cost_type) || a.label).localeCompare(
|
||
fixedLabel.get(b.cost_type) || b.label,
|
||
'zh'
|
||
);
|
||
};
|
||
// 采购成本改用「订单行口径」,与「销售收入」(订单口径)以及财务概览/订单采购成本卡同源。
|
||
// 账本 cost_details 在部分订单上只有验收入库同步的占位行、或正式行按入账日落在窗口外,
|
||
// 会系统性低估(实测配送日 09-14:账本 3,731.73 vs 订单行 8,726.85),
|
||
// 与订单口径的销售收入混算会把毛利/净利抬高。用户 2026-09-14 确认方案 A。
|
||
const [orderLinePurchase, prevOrderLinePurchase] = await Promise.all([
|
||
getOrderLinePurchaseTotal(`${dateFrom.replace(/-/g, '')}_${dateTo.replace(/-/g, '')}`, null, dashField),
|
||
getOrderLinePurchaseTotal(`${prevFrom.replace(/-/g, '')}_${prevTo.replace(/-/g, '')}`, null, dashField),
|
||
]);
|
||
const purchaseCost = orderLinePurchase.purchase;
|
||
const prevPurchaseCost = prevOrderLinePurchase.purchase;
|
||
// 客户「过账扣点」:用户 2026-10-08 裁决 —— **不进「所有成本」构成**,单独作为一张卡展示;
|
||
// 但**仍参与净利**(净利 = 公式结果 − 扣点)。取数与财务概览同一函数、同一日期口径;
|
||
// 关闭态 ⇒ 0(净利/毛利逐位不变)。
|
||
const [customerRebateCost, prevCustomerRebateCost] = await Promise.all([
|
||
queryCustomerRebateCost(dateFrom, dateTo, dashField, branchCode, null),
|
||
queryCustomerRebateCost(prevFrom, prevTo, dashField, branchCode, null),
|
||
]);
|
||
// 「所有成本」构成与合计:采购项用订单行口径替换账本采购项,其余构成仍读账本,
|
||
// 合计改为各构成项之和,保证卡片与构成分析/占比自洽(与财务概览同口径)。**不含扣点**。
|
||
const ledgerBucketsAdjusted = ledgerBucketsRaw
|
||
.map((b) => {
|
||
if (b.cost_type === 'purchase') return { ...b, amount: round2(purchaseCost) };
|
||
return b;
|
||
})
|
||
.sort(compareLedgerBuckets);
|
||
const ledgerTotal = round2(
|
||
ledgerBucketsAdjusted.reduce((sum, b) => sum + (Number(b.amount) || 0), 0)
|
||
);
|
||
const ledger_buckets = ledgerBucketsAdjusted.map((b) => ({
|
||
...b,
|
||
pct: ledgerTotal > 0 ? Math.round((b.amount / ledgerTotal) * 1000) / 10 : 0,
|
||
}));
|
||
const quoteGross = current.revenue - purchaseCost;
|
||
const prevGross = previous.revenue - prevPurchaseCost;
|
||
const grossMarginPct = current.revenue > 0 ? round2((quoteGross / current.revenue) * 100) : 0;
|
||
const prevGrossMarginPct = previous.revenue > 0 ? round2((prevGross / previous.revenue) * 100) : 0;
|
||
|
||
const profit = computeFinanceNetProfit({
|
||
revenue: current.revenue,
|
||
productCost: purchaseCost,
|
||
periodFixedCost: periodSides.periodFixedCost,
|
||
periodFreeCost: periodSides.periodFreeCost,
|
||
});
|
||
const prevProfit = computeFinanceNetProfit({
|
||
revenue: previous.revenue,
|
||
productCost: prevPurchaseCost,
|
||
periodFixedCost: prevPeriodSides.periodFixedCost,
|
||
periodFreeCost: prevPeriodSides.periodFreeCost,
|
||
});
|
||
// 净利:公式不动(computeFinanceNetProfit 是唯一实现),只多减一笔「客户过账扣点」,
|
||
// 净利率按同一销售额重算;关闭态扣点为 0 ⇒ 逐位不变。本期与上期同口径,环比才有意义。
|
||
const netProfit = round2(profit.netProfit - customerRebateCost);
|
||
const netProfitMarginPct =
|
||
current.revenue > 0 ? round2((netProfit / current.revenue) * 100) : profit.netProfitMarginPct;
|
||
const prevNetProfit = round2(prevProfit.netProfit - prevCustomerRebateCost);
|
||
|
||
return {
|
||
quote_revenue: round2(current.revenue),
|
||
quote_cost: purchaseCost,
|
||
quote_gross: round2(quoteGross),
|
||
gross_margin_pct: grossMarginPct,
|
||
completed_orders: current.orderCount,
|
||
prev_quote_revenue: round2(previous.revenue),
|
||
prev_quote_cost: prevPurchaseCost,
|
||
prev_quote_gross: round2(prevGross),
|
||
prev_gross_margin_pct: prevGrossMarginPct,
|
||
revenue_change_pct: pctChange(current.revenue, previous.revenue),
|
||
cost_change_pct: pctChange(purchaseCost, prevPurchaseCost),
|
||
gross_change_pct: pctChange(quoteGross, prevGross),
|
||
margin_change_pp:
|
||
previous.revenue > 0 || current.revenue > 0
|
||
? round2(grossMarginPct - prevGrossMarginPct)
|
||
: null,
|
||
ledger_total: ledgerTotal,
|
||
ledger_buckets,
|
||
customer_rebate_cost: round2(customerRebateCost),
|
||
net_profit: netProfit,
|
||
net_profit_margin_pct: netProfitMarginPct,
|
||
prev_net_profit: prevNetProfit,
|
||
net_profit_change_pct: pctChange(netProfit, prevNetProfit),
|
||
net_profit_formula: profit.formulaLabel,
|
||
basis: 'cost_details_ledger',
|
||
};
|
||
}
|