import { getSupplierBindingCategoryDisplay, getSupplierBindingLookupCodes, type CategoryRow } from './categories'; /** 智能分配规则(可在分配页调整) */ export interface AllocationRules { /** 无 SKU(未匹配商品库)→ 流转自有采购员自采 */ noSkuToPurchaser: boolean; /** 无分类商品 → 自有采购员 */ uncategorizedToPurchaser: boolean; /** 有分类且存在分类供应商 → 分给该分类供应商 */ categoryMatchToSupplier: boolean; /** 有分类但无对应供应商 → 转自有采购员 */ noCategorySupplierToPurchaser: boolean; /** 同一分类多个供应商时优先 is_primary */ preferPrimarySupplier: boolean; /** P2-1:履约预测高风险时自动切换备选供应商 */ autoSwitchOnFulfillmentRisk: boolean; } export const DEFAULT_ALLOCATION_RULES: AllocationRules = { noSkuToPurchaser: true, uncategorizedToPurchaser: true, categoryMatchToSupplier: true, noCategorySupplierToPurchaser: true, preferPrimarySupplier: true, autoSwitchOnFulfillmentRisk: true, }; export type FulfillmentRiskLevel = 'low' | 'medium' | 'high'; export interface SupplierFulfillmentLite { supplier_code: string; supplier_name?: string; fulfillment_score: number; risk_level: FulfillmentRiskLevel; ontime_rate_pct?: number; current_load?: number; rating_grade?: string; suggest_backup: boolean; recommendation?: string; } export const INTERNAL_PURCHASER_CODE = 'INTERNAL'; export const INTERNAL_PURCHASER_NAME = '自有采购员'; /** * 订单行供应商的第三个取值:**库存抵扣**(2026-10-14,与后端 * `server/src/services/allocationRules.ts` 同名常量,口径见 * docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1)。 * 全额由仓库库存抵扣的行用它占位 —— 它**不是** `suppliers` 表里的厂商。 */ export const STOCK_COVER_SUPPLIER_CODE = 'STOCK_COVER'; export const STOCK_COVER_SUPPLIER_NAME = '库存抵扣'; /** 该编码是否就是「库存抵扣」(大小写不敏感) */ export function isStockCoverSupplierCode(supplierCode?: string | null): boolean { return String(supplierCode || '').trim().toUpperCase() === STOCK_COVER_SUPPLIER_CODE; } export type AllocationTarget = 'purchaser' | 'supplier'; export interface AllocationItemInput { id: string; sku_code: string; sku_name: string; category_code?: string; category_name?: string; quantity: number; price: number; unit: string; } export interface SupplierCategoryBinding { supplier_code: string; category_code: string; is_primary?: boolean; } export interface SupplierInfo { supplier_code: string; company_name: string; rating?: number | string | null; status?: number | null; } /** V9:不可用供应商状态(冻结、黑名单) */ const BLOCKED_SUPPLIER_STATUSES = new Set([30, 40]); export function isSupplierAvailableForAllocation(supplier: SupplierInfo): boolean { const status = Number(supplier.status ?? 10); if (BLOCKED_SUPPLIER_STATUSES.has(status)) return false; const grade = String(supplier.rating || '').trim().toUpperCase(); if (grade === 'D') return false; return true; } interface PickSupplierResult { supplier: SupplierInfo; usedBackup: boolean; unavailablePrimaryName?: string; fulfillmentSwitched?: boolean; previousSupplier?: SupplierInfo; fulfillmentScore?: number; fulfillmentRisk?: FulfillmentRiskLevel; fulfillmentRecommendation?: string; } export interface SkuSupplierPrice { sku_code: string; supplier_code: string; supply_price: number; is_preferred?: boolean; in_stock?: boolean; status?: number; quality_rating?: number; } export interface ResolvedAllocation { order_code: string; item_id: string; sku_code: string; sku_name: string; quantity: number; unit: string; category_code?: string; category_name?: string; target: AllocationTarget; supplier_code: string; supplier_name: string; supply_price: number; transport_cost: number; total_cost: number; confidence: number; reason: string; allocation_source: 'category' | 'sku_supplier' | 'purchaser'; /** V9:是否因正式供应商不可用而切换备选 */ usedBackupSupplier?: boolean; unavailablePrimaryName?: string; /** P2-1:AI 履约预测 */ fulfillment_score?: number; fulfillment_risk?: FulfillmentRiskLevel; fulfillment_recommendation?: string; /** 因履约风险切换备选(相对不可用切换) */ fulfillment_switched?: boolean; previous_supplier_code?: string; previous_supplier_name?: string; } function parseRating(value: unknown): number { const n = Number(value); return Number.isFinite(n) ? n : 3; } function fulfillmentScoreOf( supplierCode: string, fulfillmentBySupplier?: Record ): number { return fulfillmentBySupplier?.[supplierCode]?.fulfillment_score ?? 50; } function pickCategorySupplier( lookupCodes: string[], bindings: SupplierCategoryBinding[], suppliers: SupplierInfo[], preferPrimary: boolean, fulfillmentBySupplier?: Record, autoSwitchOnFulfillmentRisk = true ): PickSupplierResult | null { for (const code of lookupCodes) { const matched = bindings.filter((b) => b.category_code === code); if (!matched.length) continue; const primaryBindings = matched.filter((b) => b.is_primary); const backupBindings = matched.filter((b) => !b.is_primary); const orderedGroups = preferPrimary ? [primaryBindings, backupBindings] : [matched]; let unavailablePrimaryName: string | undefined; const groupPicks: Array<{ pick: PickSupplierResult; groupIndex: number }> = []; for (let groupIndex = 0; groupIndex < orderedGroups.length; groupIndex++) { const group = orderedGroups[groupIndex]; const isBackupGroup = preferPrimary && groupIndex > 0; const candidates: SupplierInfo[] = []; for (const binding of group) { const supplier = suppliers.find((s) => s.supplier_code === binding.supplier_code); if (!supplier) continue; if (isSupplierAvailableForAllocation(supplier)) { candidates.push(supplier); } else if (!isBackupGroup && binding.is_primary) { unavailablePrimaryName = supplier.company_name; } } if (!candidates.length) continue; const best = [...candidates].sort((a, b) => { const fs = fulfillmentScoreOf(b.supplier_code, fulfillmentBySupplier) - fulfillmentScoreOf(a.supplier_code, fulfillmentBySupplier); if (fs !== 0) return fs; return parseRating(b.rating) - parseRating(a.rating); })[0]; const pred = fulfillmentBySupplier?.[best.supplier_code]; groupPicks.push({ groupIndex, pick: { supplier: best, usedBackup: isBackupGroup, unavailablePrimaryName: isBackupGroup ? unavailablePrimaryName : undefined, fulfillmentScore: pred?.fulfillment_score, fulfillmentRisk: pred?.risk_level, fulfillmentRecommendation: pred?.recommendation, }, }); } if (!groupPicks.length) continue; groupPicks.sort((a, b) => a.groupIndex - b.groupIndex); let chosen = groupPicks[0].pick; if ( autoSwitchOnFulfillmentRisk && fulfillmentBySupplier && groupPicks.length > 1 && groupPicks[0].groupIndex === 0 ) { const primaryPred = fulfillmentBySupplier[chosen.supplier.supplier_code]; const backupPick = groupPicks.find((g) => g.groupIndex > 0)?.pick; if ( primaryPred?.suggest_backup && backupPick && fulfillmentScoreOf(backupPick.supplier.supplier_code, fulfillmentBySupplier) > fulfillmentScoreOf(chosen.supplier.supplier_code, fulfillmentBySupplier) + 2 ) { chosen = { ...backupPick, usedBackup: true, fulfillmentSwitched: true, previousSupplier: chosen.supplier, unavailablePrimaryName: chosen.supplier.company_name, }; } } return chosen; } return null; } function resolveSupplyPrice( skuCode: string, supplierCode: string, skuSuppliers: SkuSupplierPrice[] ): number { const row = skuSuppliers.find( (s) => s.sku_code === skuCode && s.supplier_code === supplierCode ); if (row && row.supply_price > 0) return row.supply_price; // 禁止用订单销售价兜底 return 0; } /** 分类未命中时:从 SKU 供货目录选可用供应商(优先 is_preferred) */ function pickSkuSupplierFallback( skuCode: string, skuSuppliers: SkuSupplierPrice[], suppliers: SupplierInfo[], fulfillmentBySupplier?: Record ): SupplierInfo | null { const rows = skuSuppliers.filter((row) => { if (row.sku_code !== skuCode) return false; if (row.status != null && Number(row.status) !== 1) return false; return true; }); if (!rows.length) return null; const candidates: Array<{ supplier: SupplierInfo; preferred: boolean; price: number }> = []; for (const row of rows) { const supplier = suppliers.find((s) => s.supplier_code === row.supplier_code); if (!supplier || !isSupplierAvailableForAllocation(supplier)) continue; candidates.push({ supplier, preferred: Boolean(row.is_preferred), price: Number(row.supply_price) || 0, }); } if (!candidates.length) return null; candidates.sort((a, b) => { if (a.preferred !== b.preferred) return a.preferred ? -1 : 1; const fs = fulfillmentScoreOf(b.supplier.supplier_code, fulfillmentBySupplier) - fulfillmentScoreOf(a.supplier.supplier_code, fulfillmentBySupplier); if (fs !== 0) return fs; if (a.price !== b.price) return a.price - b.price; return parseRating(b.supplier.rating) - parseRating(a.supplier.rating); }); return candidates[0].supplier; } export function resolveItemAllocation(params: { orderCode: string; item: AllocationItemInput; rules: AllocationRules; supplierCategories: SupplierCategoryBinding[]; suppliers: SupplierInfo[]; skuSuppliers: SkuSupplierPrice[]; categoryRows?: CategoryRow[]; /** 分类→采购员长期绑定:命中则强制自采,不走供应商备货 */ categoryPurchaserBindings?: Array<{ category_code: string }>; transportCost?: number; fulfillmentBySupplier?: Record; }): ResolvedAllocation | null { const { orderCode, item, rules, supplierCategories, suppliers, skuSuppliers } = params; const transportCost = params.transportCost ?? 0; const fulfillmentBySupplier = params.fulfillmentBySupplier; const categoryCode = item.category_code?.trim() || ''; const categoryName = item.category_name || ''; const bindingDisplay = params.categoryRows?.length ? getSupplierBindingCategoryDisplay(categoryCode, params.categoryRows) : { bindingCode: categoryCode || null, bindingName: categoryName || null, underContainer: false }; const allocationCategoryLabel = bindingDisplay.bindingName || bindingDisplay.bindingCode || categoryName || categoryCode; const allocationCategoryPrefix = bindingDisplay.underContainer ? '分类' : '一级分类'; const base = { order_code: orderCode, item_id: item.id, sku_code: item.sku_code, sku_name: item.sku_name, quantity: item.quantity, unit: item.unit, category_code: categoryCode || undefined, category_name: categoryName || undefined, transport_cost: transportCost, }; if (!item.sku_code?.trim()) { if (!rules.noSkuToPurchaser) { return null; } const supplyPrice = 0; const label = item.sku_name || '未命名商品'; return { ...base, target: 'purchaser', supplier_code: INTERNAL_PURCHASER_CODE, supplier_name: INTERNAL_PURCHASER_NAME, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: 100, reason: `未匹配商品「${label}」,流转至自有采购员自采`, allocation_source: 'purchaser', }; } if (!categoryCode) { if (!rules.uncategorizedToPurchaser) { return null; } const supplyPrice = 0; return { ...base, target: 'purchaser', supplier_code: INTERNAL_PURCHASER_CODE, supplier_name: INTERNAL_PURCHASER_NAME, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: 100, reason: '无商品分类,按规则流转至自有采购员', allocation_source: 'purchaser', }; } const categoryPurchaserBindings = params.categoryPurchaserBindings || []; if (categoryPurchaserBindings.length) { const purchaserHitCodes = params.categoryRows?.length ? getSupplierBindingLookupCodes( categoryCode, params.categoryRows, categoryPurchaserBindings ) : categoryPurchaserBindings.some((b) => b.category_code === categoryCode) ? [categoryCode] : []; if (purchaserHitCodes.length) { const supplyPrice = 0; return { ...base, target: 'purchaser', supplier_code: INTERNAL_PURCHASER_CODE, supplier_name: INTERNAL_PURCHASER_NAME, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: 100, reason: `${allocationCategoryPrefix}「${allocationCategoryLabel}」已指定采购员,强制自采(不走供应商备货)`, allocation_source: 'purchaser', }; } } if (rules.categoryMatchToSupplier) { const lookupCodes = params.categoryRows?.length && categoryCode ? getSupplierBindingLookupCodes(categoryCode, params.categoryRows, supplierCategories) : [categoryCode]; const pickResult = pickCategorySupplier( lookupCodes, supplierCategories, suppliers, rules.preferPrimarySupplier, fulfillmentBySupplier, rules.autoSwitchOnFulfillmentRisk ); if (pickResult) { const { supplier, usedBackup, unavailablePrimaryName, fulfillmentSwitched, previousSupplier, fulfillmentScore, fulfillmentRisk, fulfillmentRecommendation, } = pickResult; const supplyPrice = resolveSupplyPrice( item.sku_code, supplier.supplier_code, skuSuppliers ); let backupNote = ''; if (fulfillmentSwitched && previousSupplier) { backupNote = `(AI履约预测:${previousSupplier.company_name} 风险偏高,已切换备选 ${supplier.company_name})`; } else if (usedBackup) { backupNote = `(正式供应商「${unavailablePrimaryName || '不可用'}」不可用,已切换备选)`; } const pred = fulfillmentBySupplier?.[supplier.supplier_code]; return { ...base, target: 'supplier', supplier_code: supplier.supplier_code, supplier_name: supplier.company_name, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: fulfillmentSwitched ? 78 : usedBackup ? 82 : pred?.risk_level === 'low' ? 96 : 92, reason: `${allocationCategoryPrefix}「${allocationCategoryLabel}」匹配供应商 ${supplier.company_name}${backupNote}`, allocation_source: 'category', usedBackupSupplier: usedBackup || fulfillmentSwitched, unavailablePrimaryName, fulfillment_score: fulfillmentScore ?? pred?.fulfillment_score, fulfillment_risk: fulfillmentRisk ?? pred?.risk_level, fulfillment_recommendation: fulfillmentRecommendation ?? pred?.recommendation, fulfillment_switched: fulfillmentSwitched, previous_supplier_code: previousSupplier?.supplier_code, previous_supplier_name: previousSupplier?.company_name, }; } // 分类无绑定:先尝试 SKU 供货目录兜底,仍无再转自采 const skuSupplier = pickSkuSupplierFallback( item.sku_code, skuSuppliers, suppliers, fulfillmentBySupplier ); if (skuSupplier) { const supplyPrice = resolveSupplyPrice( item.sku_code, skuSupplier.supplier_code, skuSuppliers ); const pred = fulfillmentBySupplier?.[skuSupplier.supplier_code]; return { ...base, target: 'supplier', supplier_code: skuSupplier.supplier_code, supplier_name: skuSupplier.company_name, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: 80, reason: `${allocationCategoryPrefix}「${allocationCategoryLabel}」无分类绑定,按 SKU 供货目录匹配供应商 ${skuSupplier.company_name}`, allocation_source: 'sku_supplier', fulfillment_score: pred?.fulfillment_score, fulfillment_risk: pred?.risk_level, fulfillment_recommendation: pred?.recommendation, }; } } if (rules.noCategorySupplierToPurchaser) { const supplyPrice = 0; return { ...base, target: 'purchaser', supplier_code: INTERNAL_PURCHASER_CODE, supplier_name: INTERNAL_PURCHASER_NAME, supply_price: supplyPrice, total_cost: supplyPrice * item.quantity + transportCost, confidence: 85, reason: `${allocationCategoryPrefix}「${allocationCategoryLabel}」无绑定供应商,流转至自有采购员`, allocation_source: 'purchaser', }; } return null; } export function allocateOrderItems(params: { orderCode: string; items: AllocationItemInput[]; rules: AllocationRules; supplierCategories: SupplierCategoryBinding[]; suppliers: SupplierInfo[]; skuSuppliers: SkuSupplierPrice[]; categoryRows?: CategoryRow[]; categoryPurchaserBindings?: Array<{ category_code: string }>; /** 市场监控红灯 SKU,暂停分配 */ blockedSkuCodes?: Set | string[]; /** P2-1 履约预测(supplier_code → 预测) */ fulfillmentBySupplier?: Record; }): { results: ResolvedAllocation[]; skipped: AllocationItemInput[]; marketBlocked: AllocationItemInput[] } { const results: ResolvedAllocation[] = []; const skipped: AllocationItemInput[] = []; const marketBlocked: AllocationItemInput[] = []; const blockedSet = params.blockedSkuCodes instanceof Set ? params.blockedSkuCodes : new Set(params.blockedSkuCodes || []); for (const item of params.items) { if (item.sku_code && blockedSet.has(item.sku_code)) { marketBlocked.push(item); continue; } const resolved = resolveItemAllocation({ orderCode: params.orderCode, item, rules: params.rules, supplierCategories: params.supplierCategories, suppliers: params.suppliers, skuSuppliers: params.skuSuppliers, categoryRows: params.categoryRows, categoryPurchaserBindings: params.categoryPurchaserBindings, transportCost: 0, fulfillmentBySupplier: params.fulfillmentBySupplier, }); if (resolved) { results.push(resolved); } else { skipped.push(item); } } return { results, skipped, marketBlocked }; }