feat(财务概览): 客户筛选支持多选,修复多码下游成本明细 500

- SearchableMultiSelect + customer_code 逗号串;单码 SQL 保持 =,多码 ANY
- 期间无单号成本按真实有单已选客户数分摊;净利公式未改
- 修复 bindShared/listOrderCostDetails 把数组当标量导致的 PG 42809
- 补 helper/契约测试
This commit is contained in:
Ubuntu
2026-10-25 15:53:22 +08:00
parent a1321571d2
commit d02c999069
4 changed files with 409 additions and 76 deletions
+281 -71
View File
@@ -215,73 +215,131 @@ export function costDetailsLinkedOrPeriodCondSql(
)`;
}
/** 规范化客户筛选码;空 = 全部客户 */
/** 规范化单客户筛选码;空 = 全部客户(保留原语义,别改)。 */
export function normalizeCustomerCodeFilter(raw?: string | null): string | null {
const code = String(raw || '').trim();
return code || null;
}
/**
* 选客户时:仅保留挂到该客户订单的 cost_details(排除无单号期间固定/其他)。
* 会 push 到 params,返回 AND 片段(可能为空串)。
* 规范化**多选**客户筛选码:兼容 单个码 / 逗号串 / 数组;去空去重;空数组 = 全部客户。
* 与 `normalizeCustomerCodeFilter`(单值)并存,不改后者语义 —— 既有单客户链路零改动。
*/
export function normalizeCustomerCodesFilter(raw?: string | string[] | null): string[] {
const parts = Array.isArray(raw) ? raw : String(raw || '').split(',');
const seen = new Set<string>();
const codes: string[] = [];
for (const part of parts) {
const code = String(part || '').trim();
if (!code || seen.has(code)) continue;
seen.add(code);
codes.push(code);
}
return codes;
}
/**
* 客户码 → SQL 谓词;会 push 到 params。
* 单码时与历史写法逐字相同(`= $n`);≥2 码才启用 `= ANY($n)`。
*/
export function pushCustomerCodePredicate(codes: string[], params: unknown[], column: string): string {
if (codes.length === 1) {
params.push(codes[0]);
return `${column} = $${params.length}`;
}
params.push(codes);
return `${column} = ANY($${params.length})`;
}
/** 选客户时:仅保留挂到该(些)客户订单的 cost_details(排除无单号期间固定/其他)。 */
export function costDetailsCustomerFilterSql(
customerCode: string | null | undefined,
customerCode: string | string[] | null | undefined,
params: unknown[],
cdAlias = 'cd'
): string {
const code = normalizeCustomerCodeFilter(customerCode);
if (!code) return '';
params.push(code);
const idx = params.length;
const codes = normalizeCustomerCodesFilter(customerCode);
if (!codes.length) return '';
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}
AND ${pushCustomerCodePredicate(codes, params, 'o_cf.customer_code')}
)`;
}
/** 订单表客户筛选;会 push 到 params */
export function ordersCustomerFilterSql(
customerCode: string | null | undefined,
customerCode: string | 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}`;
const codes = normalizeCustomerCodesFilter(customerCode);
if (!codes.length) return '';
return ` AND ${pushCustomerCodePredicate(codes, params, `${orderAlias}.customer_code`)}`;
}
/**
* 同一 params 数组内只 push 一次客户码,供订单侧与 cost_details 侧共用 $n。
* 空客户时两片段均为 ''(全部客户零回归)。
*/
/** 同一 params 数组内只 push 一次客户码,供订单侧与 cost_details 侧共用 $n。 */
export function bindSharedCustomerFilterSql(
customerCode: string | null | undefined,
customerCode: string | 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 codes = normalizeCustomerCodesFilter(customerCode);
if (!codes.length) return { ordersSql: '', costDetailsSql: '' };
const orderAlias = opts?.orderAlias ?? 'o';
const cdAlias = opts?.cdAlias ?? 'cd';
// 只 push 一次;订单侧与 cost_details 子查询共用同一个占位符。
// 多码必须 ANY,不能把数组参数拿去和标量列比较(否则 PG 42809)。
if (codes.length === 1) {
params.push(codes[0]);
} else {
params.push(codes);
}
const idx = params.length;
const rhs = codes.length === 1 ? `$${idx}` : `ANY($${idx})`;
return {
ordersSql: ` AND ${orderAlias}.customer_code = $${idx}`,
ordersSql: ` AND ${orderAlias}.customer_code = ${rhs}`,
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}
AND o_cf.customer_code = ${rhs}
)`,
};
}
/**
* 客户均摊后的金额表达式:挂所选客户订单的全额,无单号行按 share 比例。
* 单码沿用 `= $n`,多码 `= ANY($n)`;与 getPurchaseCostLedgerWindow 的 orphanShare 配套。
*/
export function customerAllocatedAmountSql(
amountSql: string,
codes: string[],
params: unknown[],
orphanShare: number
): string {
const share = Math.max(0, Math.min(1, Number(orphanShare) || 0));
params.push(share);
const shareIdx = params.length;
params.push(codes.length === 1 ? codes[0] : codes);
const codeIdx = params.length;
const codePred = codes.length === 1
? `o_cf.customer_code = $${codeIdx}`
: `o_cf.customer_code = ANY($${codeIdx})`;
return `${amountSql} * (CASE
WHEN cd.order_code IS NULL OR TRIM(cd.order_code) = '' THEN $${shareIdx}::numeric
WHEN EXISTS (
SELECT 1 FROM orders o_cf
WHERE o_cf.order_code = cd.order_code
AND o_cf.deleted_at IS NULL
AND ${codePred}
) THEN 1::numeric
ELSE 0::numeric
END)`;
}
/** 周期成本归集:直接 / 间接(固定+变动)/ 自由 */
export async function getCostAggregation(
cycleCode: string,
@@ -506,7 +564,7 @@ export async function listOrderCostDetailsInWindow(
ctx?: TenantContext | null,
dateFieldRaw?: string | null,
limit = 5000,
customerCode?: string | null
customerCode?: string | string[] | null
): Promise<
Array<{
id: string;
@@ -535,10 +593,10 @@ export async function listOrderCostDetailsInWindow(
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 hasCustomer = normalizeCustomerCodesFilter(customerCode).length > 0;
const independentBranch = ctx?.branchCode && !ctx.isSuperAdmin ? `AND spi.branch_code = $${branchParamIdx}` : '';
// 独立自采没有客户/订单归属;筛选某个客户时不混入该客户成本。
const independentCustomer = customerParamIdx ? 'AND FALSE' : '';
const independentCustomer = hasCustomer ? 'AND FALSE' : '';
params.push(safeLimit);
const limitIdx = params.length;
@@ -555,7 +613,7 @@ export async function listOrderCostDetailsInWindow(
: '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 runtimeCustomer = ordersCustomerFilterSql(customerCode, params, 'o');
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,
@@ -844,7 +902,9 @@ export async function getPurchaseCostLedgerWindow(opts: {
branchCode?: string | null;
dateField?: string | null;
/** 空 / 省略 = 全部客户;有值时排除无订单归属成本 */
customerCode?: string | null;
customerCode?: string | string[] | null;
/** 无单号期间成本计入比例(多选客户时按当窗客户数分摊) */
orphanShare?: number;
}): Promise<UnifiedCostWindow> {
const dateFrom = String(opts.dateFrom || '').trim();
const dateTo = String(opts.dateTo || '').trim();
@@ -855,7 +915,14 @@ export async function getPurchaseCostLedgerWindow(opts: {
params.push(opts.branchCode);
branchSql = `AND cd.branch_code = $${params.length}`;
}
const customerSql = costDetailsCustomerFilterSql(opts.customerCode, params);
const codes = normalizeCustomerCodesFilter(opts.customerCode);
let amtExpr = CD_EFFECTIVE_AMOUNT_SQL;
let customerSql = '';
if (codes.length && typeof opts.orphanShare === 'number') {
amtExpr = customerAllocatedAmountSql(CD_EFFECTIVE_AMOUNT_SQL, codes, params, opts.orphanShare);
} else {
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 (
@@ -873,7 +940,7 @@ export async function getPurchaseCostLedgerWindow(opts: {
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
${amtExpr} AS amt
FROM cost_details cd
WHERE ${cdDateCond}
AND ${cdOrphanCond}
@@ -901,9 +968,9 @@ export async function getPurchaseCostLedgerWindow(opts: {
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
COALESCE(SUM(${purchaseSelfAmountSql(amtExpr)}), 0)::numeric AS self_total,
COALESCE(SUM(${purchaseSupplierAmountSql(amtExpr)}), 0)::numeric AS supplier_total,
COALESCE(SUM(${purchaseStockCoverAmountSql(amtExpr)}), 0)::numeric AS stock_cover_total
FROM cost_details cd
WHERE ${CD_PURCHASE_TYPES_SQL}
AND ${cdDateCond}
@@ -1227,7 +1294,7 @@ export async function getOrderLinePurchaseTotal(
cycleCode: string,
ctx?: TenantContext | null,
dateFieldRaw?: string | null,
customerCode?: string | null
customerCode?: string | string[] | null
): Promise<{
purchase: number;
purchase_self: number;
@@ -1273,7 +1340,7 @@ export async function getSkuDirectCostsPaged(
sortOrderRaw?: string | null,
categoryCodes?: string[] | null,
nameQuery?: string | null,
customerCode?: string | null,
customerCode?: string | string[] | null,
/** true 时从行来源排除仓内加工成品行(合计用;仓内加工不另计成本) */
excludeWarehouseProcessing?: boolean
): Promise<{
@@ -1299,7 +1366,7 @@ export async function getSkuDirectCostsPaged(
? costSource
: null;
const dateField = normalizeFinanceDateField(dateFieldRaw);
const customerFilter = normalizeCustomerCodeFilter(customerCode);
const customerFilter = normalizeCustomerCodesFilter(customerCode);
const categoryFilter = [
...new Set(
(Array.isArray(categoryCodes) ? categoryCodes : [])
@@ -1767,7 +1834,7 @@ export async function getSkuDirectCostLinesPaged(
? costSource
: null;
const dateField = normalizeFinanceDateField(dateFieldRaw);
const customerFilter = normalizeCustomerCodeFilter(customerCode);
const customerFilter = normalizeCustomerCodesFilter(customerCode);
const categoryFilter = [
...new Set(
(Array.isArray(categoryCodes) ? categoryCodes : [])
@@ -2215,11 +2282,13 @@ export async function getFinanceOverviewStats(
dateFrom?: string;
dateTo?: string;
dateField?: string | null;
customerCode?: string | null;
/** 支持单码 / 逗号串 / 码数组(多选客户);空=全部客户 */
customerCode?: string | string[] | null;
} = {}
): Promise<FinanceOverviewStats> {
const dateField = normalizeFinanceDateField(opts.dateField);
const customerFilter = normalizeCustomerCodeFilter(opts.customerCode);
const customerFilterCodes = normalizeCustomerCodesFilter(opts.customerCode);
const customerFilter = customerFilterCodes.length ? customerFilterCodes : null;
// 解析窗口:优先自定义起止日期(YYYY-MM-DD 闭区间,中国时区),否则回退 days
let rangeStart: Date;
let rangeEnd: Date;
@@ -2533,7 +2602,7 @@ export async function getFinanceOverviewStats(
let recvCustomer = '';
if (customerFilter) {
recvParams.push(customerFilter);
recvCustomer = `AND cs.customer_code = $${recvParams.length}`;
recvCustomer = `AND cs.customer_code = ANY($${recvParams.length}::text[])`;
}
// 与客户结算列表同口径(账期重叠 + CS* 去重 + 隐藏零金额空壳)
const recvSharedFilters = customerStatementSharedFiltersSql('cs');
@@ -2665,8 +2734,14 @@ export async function getFinanceOverviewStats(
custCountDateCond = `COALESCE(ib.first_inbound_at, o.updated_at) >= $1::timestamptz
AND COALESCE(ib.first_inbound_at, o.updated_at) <= $2::timestamptz`;
}
// 分母=当窗全部有单客户;分子=已选客户中**真有单**的客户(避免勾选无单客户时多分)。
custCountParams.push(customerFilter);
const selectedCustomerIdx = custCountParams.length;
const custCountResult = await pool.query(
`SELECT COUNT(DISTINCT NULLIF(TRIM(o.customer_code), ''))::int AS cnt
`SELECT
COUNT(DISTINCT NULLIF(TRIM(o.customer_code), ''))::int AS cnt,
COUNT(DISTINCT NULLIF(TRIM(o.customer_code), ''))
FILTER (WHERE o.customer_code = ANY($${selectedCustomerIdx}::text[]))::int AS selected_cnt
FROM orders o
${custCountDateJoin}
WHERE ${salesOrderPredicateSql('o')}
@@ -2676,9 +2751,10 @@ export async function getFinanceOverviewStats(
custCountParams
);
const customerCount = Math.max(0, Number(custCountResult.rows[0]?.cnt) || 0);
const selectedCustomerCount = Math.max(0, Number(custCountResult.rows[0]?.selected_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 share = customerCount > 0 ? selectedCustomerCount / customerCount : 0;
const orphanFixedShare = orphanFixed * share;
const orphanFreeShare = orphanFree * share;
periodFixedCost =
@@ -2837,7 +2913,7 @@ async function queryCustomerRebateCost(
dateTo: string,
dateField: FinanceDateField,
branchCode: string | null,
customerCode: string | null
customerCode: string | string[] | null
): Promise<number> {
const supported: RebateDateField[] = ['delivery_date', 'created_at', 'inbound', 'cycle_code'];
if (!supported.includes(dateField as RebateDateField)) {
@@ -2849,14 +2925,28 @@ async function queryCustomerRebateCost(
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);
const codes = normalizeCustomerCodesFilter(customerCode);
if (!codes.length) {
const summary = await summarizeCustomerRebate({
from: dateFrom, to: dateTo, dateField: dateField as RebateDateField, branchCode, customerCode: null,
});
return round2(Number(summary.rebate_cost) || 0);
}
if (codes.length === 1) {
const summary = await summarizeCustomerRebate({
from: dateFrom, to: dateTo, dateField: dateField as RebateDateField, branchCode, customerCode: codes[0],
});
return round2(Number(summary.rebate_cost) || 0);
}
// 多选:扣点按客户维度计算,逐客户取数后求和(客户集合互斥 ⇒ 可加)
const summaries = await Promise.all(
codes.map((code) =>
summarizeCustomerRebate({
from: dateFrom, to: dateTo, dateField: dateField as RebateDateField, branchCode, customerCode: code,
})
)
);
return round2(summaries.reduce((sum, item) => sum + (Number(item.rebate_cost) || 0), 0));
} catch (err) {
console.warn(
'[customer-rebate] 扣点成本取数失败,降级为 0:',
@@ -2870,7 +2960,8 @@ async function querySalesWindow(
start: Date,
end: Date,
branchCode: string | null,
dateField: FinanceDateField = 'delivery_date'
dateField: FinanceDateField = 'delivery_date',
customerCodes?: string[] | null
): Promise<{ revenue: number; orderCount: number }> {
const field = dateField === 'created_at' ? 'created_at' : 'delivery_date';
const params: unknown[] = [toShanghaiYmd(start), toShanghaiYmd(end)];
@@ -2881,6 +2972,7 @@ async function querySalesWindow(
}
const branchO = branchEq('o', branchIdx);
const orderDateCond = orderFinanceRangeCondSql(field, 1, 2);
const customerSql = ordersCustomerFilterSql(customerCodes, params);
// 销售额与财务概览同口径(locked_price ?? price);成本不在此算
const result = await pool.query(
@@ -2890,7 +2982,8 @@ async function querySalesWindow(
JOIN order_items oi ON oi.order_code = o.order_code
WHERE ${salesLinePredicateSql('o', 'oi')}
AND ${orderDateCond}
${branchO}`,
${branchO}
${customerSql}`,
params
);
@@ -2900,6 +2993,45 @@ async function querySalesWindow(
};
}
async function countWindowCustomers(
dateFrom: string,
dateTo: string,
branchCode: string | null,
dateField: FinanceDateField
): Promise<number> {
const params: unknown[] = [dateFrom, dateTo];
let branchO = '';
if (branchCode) {
params.push(branchCode);
branchO = branchEq('o', params.length);
}
const join = orderFinanceJoinSql(dateField, true);
const cond = orderFinanceRangeCondSql(dateField, 1, 2);
const res = await pool.query(
`SELECT COUNT(DISTINCT NULLIF(TRIM(o.customer_code), ''))::int AS cnt
FROM orders o
${join}
WHERE ${salesOrderPredicateSql('o')}
AND ${cond}
${branchO}
AND o.customer_code IS NOT NULL AND TRIM(o.customer_code) <> ''`,
params
);
return Math.max(0, Number(res.rows[0]?.cnt) || 0);
}
async function computeCustomerShare(
dateFrom: string,
dateTo: string,
branchCode: string | null,
dateField: FinanceDateField,
selectedCount: number
): Promise<number> {
if (selectedCount <= 0) return 0;
const n = await countWindowCustomers(dateFrom, dateTo, branchCode, dateField);
return n > 0 ? selectedCount / n : 0;
}
export interface DashboardCostOverview {
quote_revenue: number;
quote_cost: number;
@@ -2930,13 +3062,16 @@ export interface DashboardCostOverview {
basis: 'cost_details_ledger' | 'quote_sheet';
}
/** 期间固定 + 期间其他(净利润公式入参;与财务概览同轴 2A) */
/** 期间固定 + 期间其他(净利润公式入参;与财务概览同轴 2A,支持多选客户分摊) */
async function queryPeriodFixedAndFree(
dateFrom: string,
dateTo: string,
branchCode: string | null,
dateField: FinanceDateField
dateField: FinanceDateField,
customerCodes?: string[] | null,
shareOverride?: number
): Promise<{ periodFixedCost: number; periodFreeCost: number }> {
const codes = normalizeCustomerCodesFilter(customerCodes);
const params: unknown[] = [dateFrom, dateTo];
let branchSql = '';
if (branchCode) {
@@ -2944,14 +3079,47 @@ async function queryPeriodFixedAndFree(
branchSql = `AND cd.branch_code = $${params.length}`;
}
const periodDateCond = costDetailsLinkedOrPeriodCondSql(dateField, 1, 2);
const [fixedRes, freeRes] = await Promise.all([
if (!codes.length) {
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,
};
}
const orphanOrderSql = `(cd.order_code IS NULL OR TRIM(cd.order_code) = '')`;
const orphanParams = [...params];
const linkedParams = [...params];
const linkedCustomerSql = costDetailsCustomerFilterSql(codes, linkedParams);
const [orphanFixedRes, orphanFreeRes, linkedFixedRes, linkedFreeRes] = 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}
${branchSql}`,
params
orphanParams
),
pool.query(
`SELECT COALESCE(SUM(${CD_EFFECTIVE_AMOUNT_SQL}), 0)::numeric AS total
@@ -2959,13 +3127,42 @@ async function queryPeriodFixedAndFree(
WHERE cd.cost_type = 'free_overhead'
AND ${CD_POSTED_STATUS_SQL}
AND ${periodDateCond}
AND ${orphanOrderSql}
${branchSql}`,
params
orphanParams
),
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}
${branchSql}
${linkedCustomerSql}`,
linkedParams
),
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}
${branchSql}
${linkedCustomerSql}`,
linkedParams
),
]);
const share =
typeof shareOverride === 'number'
? shareOverride
: await computeCustomerShare(dateFrom, dateTo, branchCode, dateField, codes.length);
return {
periodFixedCost: Number(fixedRes.rows[0]?.total) || 0,
periodFreeCost: Number(freeRes.rows[0]?.total) || 0,
periodFixedCost:
(Number(linkedFixedRes.rows[0]?.total) || 0) + (Number(orphanFixedRes.rows[0]?.total) || 0) * share,
periodFreeCost:
(Number(linkedFreeRes.rows[0]?.total) || 0) + (Number(orphanFreeRes.rows[0]?.total) || 0) * share,
};
}
@@ -2981,7 +3178,8 @@ export async function getDashboardCostOverview(
previousStart: Date,
previousEnd: Date,
branchCode: string | null,
dateFieldRaw?: string | null
dateFieldRaw?: string | null,
customerCodes?: string[] | null
): Promise<DashboardCostOverview> {
const dateField = normalizeFinanceDateField(dateFieldRaw);
const dashField: FinanceDateField = dateField === 'created_at' ? 'created_at' : 'delivery_date';
@@ -2989,23 +3187,35 @@ export async function getDashboardCostOverview(
const dateTo = toShanghaiYmd(end);
const prevFrom = toShanghaiYmd(previousStart);
const prevTo = toShanghaiYmd(previousEnd);
const codes = normalizeCustomerCodesFilter(customerCodes);
const customerArg = codes.length ? codes : null;
const [shareCurrent, sharePrev] = codes.length
? await Promise.all([
computeCustomerShare(dateFrom, dateTo, branchCode, dashField, codes.length),
computeCustomerShare(prevFrom, prevTo, branchCode, dashField, codes.length),
])
: [0, 0];
const [current, previous, unified, prevUnified, periodSides, prevPeriodSides] = await Promise.all([
querySalesWindow(start, end, branchCode, dashField),
querySalesWindow(previousStart, previousEnd, branchCode, dashField),
querySalesWindow(start, end, branchCode, dashField, customerArg),
querySalesWindow(previousStart, previousEnd, branchCode, dashField, customerArg),
getPurchaseCostLedgerWindow({
dateFrom,
dateTo,
branchCode,
dateField: dashField,
customerCode: customerArg,
...(codes.length ? { orphanShare: shareCurrent } : {}),
}),
getPurchaseCostLedgerWindow({
dateFrom: prevFrom,
dateTo: prevTo,
branchCode,
dateField: dashField,
customerCode: customerArg,
...(codes.length ? { orphanShare: sharePrev } : {}),
}),
queryPeriodFixedAndFree(dateFrom, dateTo, branchCode, dashField),
queryPeriodFixedAndFree(prevFrom, prevTo, branchCode, dashField),
queryPeriodFixedAndFree(dateFrom, dateTo, branchCode, dashField, customerArg, shareCurrent),
queryPeriodFixedAndFree(prevFrom, prevTo, branchCode, dashField, customerArg, sharePrev),
]);
const amountByType = new Map<string, number>();
@@ -3051,8 +3261,8 @@ export async function getDashboardCostOverview(
// 会系统性低估(实测配送日 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),
getOrderLinePurchaseTotal(`${dateFrom.replace(/-/g, '')}_${dateTo.replace(/-/g, '')}`, null, dashField, customerArg),
getOrderLinePurchaseTotal(`${prevFrom.replace(/-/g, '')}_${prevTo.replace(/-/g, '')}`, null, dashField, customerArg),
]);
const purchaseCost = orderLinePurchase.purchase;
const prevPurchaseCost = prevOrderLinePurchase.purchase;
@@ -3060,8 +3270,8 @@ export async function getDashboardCostOverview(
// 但**仍参与净利**(净利 = 公式结果 − 扣点)。取数与财务概览同一函数、同一日期口径;
// 关闭态 ⇒ 0(净利/毛利逐位不变)。
const [customerRebateCost, prevCustomerRebateCost] = await Promise.all([
queryCustomerRebateCost(dateFrom, dateTo, dashField, branchCode, null),
queryCustomerRebateCost(prevFrom, prevTo, dashField, branchCode, null),
queryCustomerRebateCost(dateFrom, dateTo, dashField, branchCode, customerArg),
queryCustomerRebateCost(prevFrom, prevTo, dashField, branchCode, customerArg),
]);
// 「所有成本」构成与合计:采购项用订单行口径替换账本采购项,其余构成仍读账本,
// 合计改为各构成项之和,保证卡片与构成分析/占比自洽(与财务概览同口径)。**不含扣点**。
@@ -0,0 +1,90 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import {
bindSharedCustomerFilterSql,
customerAllocatedAmountSql,
costDetailsCustomerFilterSql,
normalizeCustomerCodesFilter,
ordersCustomerFilterSql,
pushCustomerCodePredicate,
} from '../src/services/marginQueryService';
describe('财务客户多选 helper', () => {
it('normalize:单码/逗号/数组/去重/空=全部', () => {
expect(normalizeCustomerCodesFilter('C1')).toEqual(['C1']);
expect(normalizeCustomerCodesFilter('C1,C2, C1,, ')).toEqual(['C1', 'C2']);
expect(normalizeCustomerCodesFilter(['C2', ' C1 ', 'C2'])).toEqual(['C2', 'C1']);
expect(normalizeCustomerCodesFilter('')).toEqual([]);
expect(normalizeCustomerCodesFilter(null)).toEqual([]);
});
it('单码 SQL 与历史逐字一致;多码才 ANY', () => {
const single: unknown[] = [];
expect(pushCustomerCodePredicate(['C1'], single, 'o.customer_code')).toBe('o.customer_code = $1');
expect(single).toEqual(['C1']);
const multi: unknown[] = [];
expect(pushCustomerCodePredicate(['C1', 'C2'], multi, 'o.customer_code')).toBe(
'o.customer_code = ANY($1)'
);
expect(multi).toEqual([['C1', 'C2']]);
});
it('costDetails/orders/bindShared 单码保持 = $n,多码 ANY', () => {
const one: unknown[] = [];
expect(costDetailsCustomerFilterSql('C1', one)).toContain('o_cf.customer_code = $1');
expect(ordersCustomerFilterSql('C1', one)).toContain('o.customer_code = $2');
const oneShared = bindSharedCustomerFilterSql('C1', []);
expect(oneShared.ordersSql).toContain('o.customer_code = $1');
expect(oneShared.costDetailsSql).toContain('o_cf.customer_code = $1');
const many: unknown[] = [];
expect(costDetailsCustomerFilterSql(['C1', 'C2'], many)).toContain('o_cf.customer_code = ANY($1)');
expect(ordersCustomerFilterSql(['C1', 'C2'], many)).toContain('o.customer_code = ANY($2)');
const manyShared = bindSharedCustomerFilterSql(['C1', 'C2'], []);
expect(manyShared.ordersSql).toContain('= ANY($1)');
expect(manyShared.costDetailsSql).toContain('o_cf.customer_code = ANY($1)');
});
it('listOrderCostDetailsInWindow 多码订单侧也用 ANY,不能拿数组参数做标量比较', () => {
const src = readFileSync(new URL('../src/services/marginQueryService.ts', import.meta.url), 'utf8');
const fn = src.slice(
src.indexOf('export async function listOrderCostDetailsInWindow'),
src.indexOf('export async function getPurchaseCostLedgerWindow')
);
expect(fn).toContain('ordersCustomerFilterSql(customerCode, params, \'o\')');
expect(fn).not.toContain('o.customer_code = $${customerParamIdx}');
});
it('成本卡金额表达式:单码 = $n、多码 ANY;无单号按 share 分摊', () => {
const one: unknown[] = [];
const oneSql = customerAllocatedAmountSql('cd.amount', ['C1'], one, 0.5);
expect(oneSql).toContain('o_cf.customer_code = $2');
expect(one[0]).toBe(0.5);
expect(one[1]).toBe('C1');
const many: unknown[] = [];
const manySql = customerAllocatedAmountSql('cd.amount', ['C1', 'C2'], many, 0.25);
expect(manySql).toContain('o_cf.customer_code = ANY($2)');
expect(many[0]).toBe(0.25);
expect(many[1]).toEqual(['C1', 'C2']);
const src = readFileSync(new URL('../src/services/marginQueryService.ts', import.meta.url), 'utf8');
const cost = src.slice(src.indexOf('export async function getDashboardCostOverview'));
expect(cost).toContain('customerCodes?: string[] | null');
expect(cost).toContain('computeCustomerShare(');
expect(cost).toContain('orphanShare: shareCurrent');
expect(cost).toContain('getOrderLinePurchaseTotal');
expect(cost).toContain('queryCustomerRebateCost');
expect(cost).toContain('computeFinanceNetProfit(');
});
it('overview 的期间成本分摊按真实有单已选客户数,而非 filter.length', () => {
const src = readFileSync(new URL('../src/services/marginQueryService.ts', import.meta.url), 'utf8');
const overview = src.slice(src.indexOf('export async function getFinanceOverviewStats'));
expect(overview).toContain('selected_cnt');
expect(overview).toContain('FILTER (WHERE o.customer_code = ANY(');
expect(overview).toContain('selectedCustomerCount / customerCount');
expect(overview).not.toContain('customerFilter.length, customerCount');
});
});
+7 -5
View File
@@ -16,8 +16,9 @@ import { useAuth } from '../../hooks/useAuth';
import { useLegacyTabRedirect, useTabChildSegment } from '../../hooks/useModuleTabRoute';
import { MENU_CATALOG } from '../../config/menuCatalog';
import { PageFilterToolbar, StatusSummaryCard } from '../../components/ui/PagePrimitives';
import { SearchableSelect } from '../../components/ui/SearchableSelect';
import { SearchableMultiSelect } from '../../components/ui/SearchableMultiSelect';
import { buildFilterNavigateUrl } from '../../utils/filterNavigation';
import { parseCustomerCodes, serializeCustomerCodesParam } from '../../utils/customerCodes';
import { getFinanceOverviewStatsApi, renameCostBucketLabelApi } from '../../utils/workflowApi';
import { ListDateToolbar } from '../../components/ui/ListDateToolbar';
import type { OrderDatePreset } from '../../components/ui/OrderDateFilter';
@@ -622,17 +623,18 @@ export const FinanceOverview: React.FC = () => {
onRangeChange={applyToolbarRange}
after={
<div className="min-w-[200px] w-56">
<SearchableSelect
value={customerCode}
onChange={setCustomerCode}
<SearchableMultiSelect
values={parseCustomerCodes(customerCode)}
onChange={(codes) => setCustomerCode(serializeCustomerCodesParam(codes))}
options={customers.map((row) => ({
value: row.customer_code,
label: row.company_name,
searchText: row.customer_code,
}))}
allowEmpty
emptyLabel={t('finance.allCustomers')}
placeholder={t('finance.allCustomers')}
className="w-full"
zIndexClass="z-[100]"
/>
</div>
}
@@ -0,0 +1,31 @@
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
/**
* 财务概览 · 客户筛选多选(按主系统最终修复版移植):
* SearchableMultiSelect + customer_code 逗号串;服务端码数组 ANY;期间成本按真实有单已选客户数分摊。
*/
describe('财务概览客户多选', () => {
const page = read('./FinanceOverview.tsx');
const service = read('../../../server/src/services/marginQueryService.ts');
it('页面使用多选组件并序列化/反序列化 customer_code', () => {
expect(page).toContain('<SearchableMultiSelect');
expect(page).toContain('values={parseCustomerCodes(customerCode)}');
expect(page).toContain('serializeCustomerCodesParam(codes)');
expect(page).not.toContain('<SearchableSelect');
});
it('服务端 overview 客户过滤支持码数组,且不改净利公式', () => {
const overview = service.slice(service.indexOf('export async function getFinanceOverviewStats'));
expect(overview).toContain('normalizeCustomerCodesFilter(opts.customerCode)');
expect(overview).toContain('cs.customer_code = ANY(');
expect(overview).toContain('computeFinanceNetProfit(');
// 最终版:分子只算已选客户中真实有单的客户,避免勾选无单客户多分
expect(overview).toContain('FILTER (WHERE o.customer_code = ANY(');
expect(overview).toContain('selectedCustomerCount / customerCount');
expect(overview).not.toContain('Math.min(customerFilter.length, customerCount)');
});
});