/** * 成本中心总览与选项。 * * 口径(2026-10-23 重写): * 1. 商品来源统计按 canonical_sku 前缀分组,不再读 product_catalog.carrier_type; * 2. 成本项统计按 cost_model 分组,不再读 cost_items.carrier_type。 */ import { query } from '../../db/client.js' import { PROVIDERS, productSourceOf, toNumber } from './cost-center-shared.js' export type CostCenterScope = 'affiliate_dash' | 'work_order' | 'manual' /** * 成本中心总览。 * * scope 为空表示「全部来源」;传入具体来源时,商品/映射/成本项/版本/异常/未映射 * 六项统计都按该来源收敛,页面顶部数字才会和下面的列表对得上。 * * 来源与成本模型的对应关系: * affiliate_dash → affiliate_purchase * work_order → work_order_reward * manual → manual_actual */ export async function getAdminCostCenterOverview(params: { scope?: string } = {}) { const scope = normalizeScope(params.scope) const result = await query<{ product_count: number product_total_count: number mapping_count: number cost_item_count: number active_version_count: number open_exception_count: number unmapped_order_item_count: number }>( ` WITH scoped_products AS ( SELECT p.id FROM product_catalog p WHERE p.status = 'active' AND ( $1::text IS NULL OR ($1 = 'affiliate_dash' AND p.canonical_sku LIKE 'aff:%') OR ($1 = 'work_order' AND (p.canonical_sku LIKE 'tpl:%' OR p.canonical_sku LIKE 'wo:%')) OR ($1 = 'manual' AND p.canonical_sku LIKE 'man:%') ) ), scoped_cost_models AS ( SELECT CASE $1 WHEN 'affiliate_dash' THEN 'affiliate_purchase' WHEN 'work_order' THEN 'work_order_reward' WHEN 'manual' THEN 'manual_actual' END AS cost_model ) SELECT (SELECT COUNT(*)::int FROM scoped_products) AS product_count, (SELECT COUNT(*)::int FROM product_catalog WHERE status = 'active') AS product_total_count, ( SELECT COUNT(*)::int FROM channel_product_mappings m JOIN scoped_products p ON p.id = m.canonical_product_id WHERE m.enabled = TRUE ) AS mapping_count, ( SELECT COUNT(*)::int FROM cost_items ci WHERE ci.status = 'active' AND ($1::text IS NULL OR ci.cost_model = (SELECT cost_model FROM scoped_cost_models)) ) AS cost_item_count, ( SELECT COUNT(*)::int FROM cost_versions v JOIN cost_items ci ON ci.id = v.cost_item_id WHERE v.status = 'active' AND ($1::text IS NULL OR ci.cost_model = (SELECT cost_model FROM scoped_cost_models)) ) AS active_version_count, ( SELECT COUNT(*)::int FROM cost_exceptions ce WHERE ce.status = 'open' AND ( $1::text IS NULL OR ce.order_item_id IN ( SELECT oi.id FROM order_items oi WHERE COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $1 ) ) ) AS open_exception_count, ( SELECT COUNT(*)::int FROM order_items oi WHERE oi.canonical_product_id IS NULL AND oi.fulfillment_status <> 'archived' AND ($1::text IS NULL OR COALESCE(oi.fulfillment_channel, CASE WHEN oi.fulfillment_status = 'archived' THEN 'archived' ELSE 'pending' END) = $1) ) AS unmapped_order_item_count `, [scope], ) const row = result.rows[0] const [productSourceResult, costModelResult] = await Promise.all([ query<{ canonical_sku: string; total: number }>( `SELECT canonical_sku, COUNT(*)::int AS total FROM product_catalog WHERE status = 'active' GROUP BY canonical_sku`, ), query<{ cost_model: string; total: number }>( `SELECT cost_model, COUNT(*)::int AS total FROM cost_items WHERE status = 'active' GROUP BY cost_model`, ), ]) return { scope: scope ?? 'all', productCount: toNumber(row?.product_count), productTotalCount: toNumber(row?.product_total_count), mappingCount: toNumber(row?.mapping_count), costItemCount: toNumber(row?.cost_item_count), activeVersionCount: toNumber(row?.active_version_count), openExceptionCount: toNumber(row?.open_exception_count), unmappedOrderItemCount: toNumber(row?.unmapped_order_item_count), productSourceCounts: productSourceCountsOf(productSourceResult.rows), costModelCounts: costModelCountsOf(costModelResult.rows), } } const COST_CENTER_SCOPES = new Set([ 'affiliate_dash', 'work_order', 'third_party_voucher', 'manual', ]) function normalizeScope(raw: unknown): CostCenterScope | null { const value = String(raw ?? '').trim() return COST_CENTER_SCOPES.has(value) ? (value as CostCenterScope) : null } /** 商品来源计数:按 canonical_sku 前缀归类,未分类单独成桶。 */ function productSourceCountsOf(rows: Array<{ canonical_sku: string; total: number }>) { const counts: Record = { affiliate_dash: 0, work_order: 0, manual: 0, uncategorized: 0, } for (const row of rows) { const source = productSourceOf(row.canonical_sku) const key = source || 'uncategorized' counts[key] = (counts[key] || 0) + toNumber(row.total) } return counts } function costModelCountsOf(rows: Array<{ cost_model: string; total: number }>) { const counts: Record = {} for (const row of rows) { if (!row.cost_model) continue counts[row.cost_model] = toNumber(row.total) } return counts } export async function getAdminCostCenterOptions() { const [productsResult, costItemsResult, rulesResult] = await Promise.all([ query<{ id: number canonical_sku: string canonical_name: string unit_name: string }>( ` SELECT id, canonical_sku, canonical_name, unit_name FROM product_catalog WHERE status = 'active' ORDER BY canonical_name, id LIMIT 5000 `, ), query<{ id: number; code: string; name: string; pricing_mode: string; cost_model: string }>( ` SELECT id, code, name, pricing_mode, cost_model FROM cost_items WHERE status = 'active' ORDER BY name, id LIMIT 1000 `, ), query<{ id: number rule_key: string product_name: string sku_code: string provider: string }>( ` SELECT id, rule_key, product_name, sku_code, provider FROM work_product_rules WHERE enabled = TRUE ORDER BY sort_order, id LIMIT 1000 `, ), ]) return { providers: PROVIDERS, products: productsResult.rows.map((row) => ({ id: Number(row.id), canonicalSku: row.canonical_sku, canonicalName: row.canonical_name, unitName: row.unit_name, source: productSourceOf(row.canonical_sku), })), costItems: costItemsResult.rows.map((row) => ({ id: Number(row.id), code: row.code, name: row.name, pricingMode: row.pricing_mode, costModel: row.cost_model, })), rules: rulesResult.rows.map((row) => ({ id: Number(row.id), ruleKey: row.rule_key, productName: row.product_name, skuCode: row.sku_code, provider: row.provider, })), } }