开发者 2026-10-14:「开始做 C 块;文案你自己编写;布局自行调整」,并确认
「独立进货就是一个客户、这个客户就是他自己、相当于补充库存」、
「订单管理列表就可以不用隐藏独立进货单了」(后者本轮未动)。
设计文 docs/design/20261014-订单成本排除独立进货与库存成本分类.md §6.1(本轮新增)。
## 取值与写入
- 新增 `STOCK_COVER_SUPPLIER_CODE='STOCK_COVER'` / 名称「库存抵扣」(服务端 + 前端 allocationRules 同名常量)。
- `applyStockCoverForOrderItem`(唯一把 stock_cover_qty 写大的入口)在**同一条 UPDATE**里维护标记:
全额抵扣 ⇒ `supplier_code='STOCK_COVER'`;部分抵扣 ⇒ **不动**(缺口仍要厂商/自采,§5.1);
释放/归零且原标记是 STOCK_COVER ⇒ 回退 `UNASSIGNED`。片段 `STOCK_COVER_SUPPLIER_SQL` 与
**8 处归零点**共用(本文件 7 处 + inventoryReservationReplenishService 1 处),漏一处即留脏标记。
## 商品成本第三张表(页面 + 导出)
- 分桶取「或」:写入点打的标记 **或** 全额抵扣事实(`stock_cover_qty >= quantity`),且要求 `stock_cover_qty > 0`
⇒ **历史全额抵扣行无需回填**即进第三桶;释放后残留标记落自采表。
- `SkuCostSourceFilter` / 路由 / 列表与导出两个接口都放行 `stock_cover`;第三张表 `xl:grid-cols-3`、
标题「库存抵扣」、表头「库存成本合计 ¥x · n 个商品」(该表采购成本恒 0)。
- 订单详情供应商下拉新增第三项「库存抵扣」;订单列表/订单导出/打印供货清单都不再出现裸码或空白。
## 全域「非厂商」守卫(R1 排查,新增 hasRealSupplierCode + NON_VENDOR_SUPPLIER_SQL_LIST)
- 会**静默造脏数据/抹掉标记**的三处最要命:`orderAllocationService` 结果落库安全网与 pending 过滤、
`purchaseSupplierAssignService` 转供应商黑名单(原本不传 supplier_code 会静默建 STOCK_COVER 备货)、
`orderManageItemsService` 加菜裸 INSERT 备货与 `isAssignedExternalSupplier`(否则保存会取消在途自采+删分拣行)。
- 其余 A 清单:竞价 `isRealBidSupplier` + 回写额外再挡一次、结算/应付×3、成本来源标签、退货红冲、
验收单/再归属、备货成本回填、待备货/采购列表、商品指定供应商(后端拒 + 前端候选滤)。
- **B 类一行不动**(`isUnassignedSupplier` 系列):对"是否还要再分配"而言「已有供应商」就是对的。
## 实测(真库 BR002/BR003,服务函数直调,见 §6.1.5)
| 分支/周期 | 供应采购 | 自采采购 | 库存抵扣 |
| BR002 202610 | 0 行 ¥0 | 0 行 ¥0 | **3 行 / ¥137** |
| BR002 MOBILE | 0 行 ¥0 | 6 行 / ¥187 | **3 行 / ¥54** |
| BR003 MOBILE | 0 行 ¥0 | 4 行 / ¥61.8 | **8 行 / ¥942.2** |
三张表行数 = 表头合计,逐项对账相等;导出按来源筛同样落第三桶。
标记 SQL 语义在真库事务内验证并 ROLLBACK:全额→STOCK_COVER;部分(原标记)→UNASSIGNED;
部分(原厂商)→不动;释放归零→UNASSIGNED。
## 回归
- 后端 25 failed / 407 passed(干净 HEAD 890c055 为 27/396)⇒ **无新增失败**,另 2 个文件转好;
- 前端 2 failed / 163 passed(与基线同集合:SystemConfig.allowZeroCost、PickingManagement.outboundPhotoPreview);
- `tsc --noEmit`(前端)与 `tsc --noEmit -p server/tsconfig.json --module esnext` 均 0 错;
- 门禁 8 通过 / 1 已知红(check-ai-cost) / 1 未执行(verify-facts)。
## 未做(需裁决,见 §8 D 组)
D1 实时采购成本分桶(财务冻结)、D2 发车/入库照 skip_inbound(配送冻结)、
D3 改派真厂商的取消在途(分拣冻结)、D4 退货改派批次对齐、D5 小程序订单详情同改。
562 lines
19 KiB
TypeScript
562 lines
19 KiB
TypeScript
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<string, SupplierFulfillmentLite>
|
||
): number {
|
||
return fulfillmentBySupplier?.[supplierCode]?.fulfillment_score ?? 50;
|
||
}
|
||
|
||
function pickCategorySupplier(
|
||
lookupCodes: string[],
|
||
bindings: SupplierCategoryBinding[],
|
||
suppliers: SupplierInfo[],
|
||
preferPrimary: boolean,
|
||
fulfillmentBySupplier?: Record<string, SupplierFulfillmentLite>,
|
||
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<string, SupplierFulfillmentLite>
|
||
): 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<string, SupplierFulfillmentLite>;
|
||
}): 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> | string[];
|
||
/** P2-1 履约预测(supplier_code → 预测) */
|
||
fulfillmentBySupplier?: Record<string, SupplierFulfillmentLite>;
|
||
}): { 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 };
|
||
}
|