Files
ai-platform/src/modules/baode-web/engine/rules.ts
T
2026-10-18 15:27:02 +08:00

263 lines
12 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { AgentResult, CustomerMaster, Demand, EvidenceRow, ProductCategory, Verdict } from "../types";
import { capacity, todayIso } from "../mock/capacity";
import { rndFiling } from "../mock/rndFiling";
import type { FilingValues } from "./filing";
import { newBomAssumption } from "../mock/bom";
import { demandAmount } from "../mock/demands";
import { pct, wan, yuan } from "./format";
/** 规格 4.3 规则与公式库 */
export interface MarginBreakdown {
revenue: number;
coilCostPerUnit: number;
coilCostTotal: number;
grossProfit: number;
grossMarginRate: number;
}
/** F-毛利:毛利额 = 数量×单价 − 新BOM钢卷用量×数量×钢卷单价 */
export function coilCostPerUnit(): number {
return newBomAssumption.coils.reduce((sum, c) => sum + c.kgPerUnit * c.unitPrice, 0);
}
export function computeMargin(demand: Demand): MarginBreakdown {
const revenue = demandAmount(demand);
const perUnit = coilCostPerUnit();
const coilCostTotal = perUnit * demand.parsed.quantity;
const grossProfit = revenue - coilCostTotal;
return { revenue, coilCostPerUnit: perUnit, coilCostTotal, grossProfit, grossMarginRate: grossProfit / revenue };
}
export interface FeasibilityResult extends AgentResult {
category: ProductCategory;
route: "rnd" | "parallel";
routeLabel: string;
}
/** R-可行-1 / R-可行-2 */
export function evaluateFeasibility(demand: Demand): FeasibilityResult {
const type = demand.parsed.productType;
const hitR1 = type.includes("可拆") || type.includes("钎焊式");
const category: ProductCategory = hitR1 ? "标品" : "非标品";
const evidence: EvidenceRow[] = [
{ label: "R-可行-1:类型含「可拆」或「钎焊式」→ 标品", value: `类型=${type}`, verdict: hitR1 ? "通过" : "不通过" },
{ label: "R-可行-2:否则 → 非标品", value: hitR1 ? "未进入" : "命中", verdict: hitR1 ? null : "通过" },
];
return {
agent: "feasibility",
category,
route: hitR1 ? "parallel" : "rnd",
routeLabel: hitR1 ? "标品 → 直接进入并行评审" : "非标品 → 新品研发评审",
conclusion: category,
verdict: "路由",
evidence,
suggestions: [],
};
}
export interface RndItem {
label: string;
standard: string;
actual: string | null;
pass: boolean;
waiting: boolean;
}
export interface RndResult extends AgentResult {
pass: boolean;
items: RndItem[];
margin: MarginBreakdown;
}
/** R-研发表:毛利率≥30%、模具≤3天、项目≤10天、回收期≤1年;四项全过才通过 */
export function evaluateRndReview(demand: Demand, filled: boolean, filing: FilingValues): RndResult {
const margin = computeMargin(demand);
const [mold, proj, payback] = rndFiling.items;
const items: RndItem[] = [
{ label: "毛利率", standard: "≥30%", actual: pct(margin.grossMarginRate), pass: margin.grossMarginRate >= 0.3, waiting: false },
{ label: mold.label, standard: mold.standard, actual: filled ? filing.values[0] : null, pass: filing.moldDays <= 3, waiting: !filled },
{ label: proj.label, standard: proj.standard, actual: filled ? filing.values[1] : null, pass: filing.projectDays <= 10, waiting: !filled },
{ label: payback.label, standard: payback.standard, actual: filled ? filing.values[2] : null, pass: filing.paybackPass, waiting: !filled },
];
const pass = filled && items.every((i) => i.pass);
const evidence: EvidenceRow[] = [
{
label: "毛利复算",
value: `收入 ${yuan(margin.revenue)} − 钢卷 ${yuan(margin.coilCostTotal)}(${margin.coilCostPerUnit} 元/台 × ${demand.parsed.quantity})= 毛利 ${yuan(margin.grossProfit)} → 毛利率 ${pct(margin.grossMarginRate)}`,
verdict: margin.grossMarginRate >= 0.3 ? "通过" : "不通过",
},
...items.slice(1).map((i) => ({ label: i.label, value: i.actual ?? "等待模具/项目/财务填报", verdict: i.waiting ? null : (i.pass ? "通过" as Verdict : "不通过" as Verdict) })),
];
return {
agent: "rnd",
pass,
items,
margin,
conclusion: filled ? (pass ? "通过" : "不通过") : "等待模具/项目/财务填报",
verdict: pass ? "通过" : "不通过",
evidence,
suggestions: [],
};
}
export interface DeliveryResult extends AgentResult {
pass: boolean;
daysToDelivery: number;
}
function daysBetween(fromIso: string, toIso: string): number {
return Math.round((Date.parse(toIso) - Date.parse(fromIso)) / 86_400_000);
}
/** 交期三维度:产能负荷 / 模具机台 / 物料采购交期 */
export function evaluateDelivery(demand: Demand): DeliveryResult {
const daysToDelivery = daysBetween(todayIso(), demand.parsed.deliveryDate);
const coilLead = capacity.purchase[0].leadDays;
const need = coilLead + capacity.productionCycleDays;
const dimensions: EvidenceRow[] = [
{ label: "产能负荷", value: `${capacity.pressLine.model}当前负荷 ${pct(capacity.pressLine.loadRate)},可吸收 ${demand.parsed.quantity} 台增量`, verdict: "通过" },
{ label: "模具/机台", value: `${capacity.mold.model}在库;钎焊炉排程有空档`, verdict: "通过" },
{ label: "物料采购交期", value: `316L 钢卷现货 ${coilLead} 天 + 生产 ${capacity.productionCycleDays} 天 = ${need} 天 ≤ 距交期 ${daysToDelivery} 天`, verdict: need <= daysToDelivery ? "通过" : "不通过" },
];
return {
agent: "delivery",
pass: dimensions.every((d) => d.verdict === "通过"),
daysToDelivery,
conclusion: "通过",
verdict: "通过",
evidence: dimensions,
suggestions: [capacity.tip],
};
}
export const INDUSTRY_MARGIN_TARGET: Record<string, number> = { CDU: 0.3, 储能: 0.2 };
export const SCORE_WEIGHT = { margin: 20, credit: 60, excess: 10, reconciliation: 10 } as const;
export const SCORE_PASS_LINE = 90;
export interface ScoreItem {
label: string;
weight: number;
score: number;
basis: string;
pass: boolean;
}
export interface RatingResult extends AgentResult {
pass: boolean;
total: number;
items: ScoreItem[];
creditAvailable: number;
marginChain: MarginChainStep[];
creditBreakdown: CreditBreakdown;
}
export interface MarginChainStep {
step: string;
label: string;
value: number;
target: number;
pass: boolean;
walked: boolean;
formula?: string;
}
export interface CreditBreakdown {
items: Array<{ label: string; amount: number; source: string }>;
available: number;
pass: boolean;
}
/** R-毛利达标链 ①②③④ + F-信用 + R-超额利润 + R-对账 + R-记分 */
export function evaluateRating(demand: Demand, customer: CustomerMaster, marginRate: number): RatingResult {
const amount = demandAmount(demand);
const industry = demand.parsed.industry ?? customer.industry;
const target = INDUSTRY_MARGIN_TARGET[industry];
const chainSteps = [
{ step: "①", label: "本单毛利率", value: marginRate },
{ step: "②", label: "客户近 12 月平均毛利率", value: customer.margin12mAvg },
{ step: "③", label: "集团近 12 月平均毛利率", value: customer.groupMargin12mAvg },
{ step: "④", label: `业务员 ${customer.salesRep.code} 近 12 月平均毛利率`, value: customer.salesRep.margin12mAvg },
];
const hitIndex = target === undefined ? -1 : chainSteps.findIndex((c) => c.value >= target);
const marginPass = hitIndex >= 0;
const walked = chainSteps.slice(0, hitIndex >= 0 ? hitIndex + 1 : chainSteps.length);
const marginBasis =
target === undefined
? `行业指标未命中(${industry})`
: marginPass
? walked
.map((c, i) =>
i === walked.length - 1
? `${c.step}${c.label} ${pct(c.value)} ≥ ${industry} 指标 ${pct(target)} → 达标`
: `${c.step}${c.label} ${pct(c.value)} < ${pct(target)}`,
)
.join(";")
: `达标链 ①②③④ 均未达 ${industry} 指标 ${pct(target)}`;
const creditAvailable = customer.creditLimit - customer.stockUnpickedAmount - customer.cancelledOrderAmount - amount;
const creditPass = creditAvailable > 0;
const creditBasis = `${wan(customer.creditLimit)} − ${wan(customer.stockUnpickedAmount)} − ${wan(customer.cancelledOrderAmount)} − ${wan(amount)} = ${wan(creditAvailable)} 万 ${creditAvailable > 0 ? "> 0" : "≤ 0"}`;
const excessProfit = amount * marginRate;
const overTarget = target !== undefined && marginRate > target;
const amountBig = amount >= 5_000_000;
const profitBig = excessProfit >= 2_000_000;
const excessPass = overTarget && amountBig && profitBig;
const excessBasis = excessPass
? `毛利率 ${pct(marginRate)} > 指标 ${pct(target ?? 0)},且金额 ${wan(amount)} 万 ≥ 500 万、毛利额 ${wan(excessProfit)} 万 ≥ 200 万`
: `超标准毛利(${pct(marginRate)} vs ${target !== undefined ? pct(target) : "无指标"})${overTarget ? "✓" : "✗"};金额 ≥ 500 万(${wan(amount)} 万)${amountBig ? "✓" : "✗"};毛利额 ≥ 200 万(${wan(excessProfit)} 万)${profitBig ? "✓" : "✗"}`;
const reconPass = customer.reconciliation.cyclesPerYear === 2 && customer.reconciliation.currentPeriodConfirmed;
const reconBasis = `${customer.reconciliation.system} 一年两次对账,本期${customer.reconciliation.currentPeriodConfirmed ? "已" : "未"}确认`;
const marginChain: MarginChainStep[] = chainSteps.map((c, i) => ({
step: c.step,
label: c.label,
value: c.value,
target: target ?? 0,
pass: target !== undefined && c.value >= target,
walked: hitIndex === -1 ? true : i <= hitIndex,
formula: i === 0 ? `1 − ${yuan(coilCostPerUnit())} ÷ ${yuan(demand.parsed.unitPrice)}` : undefined,
}));
const creditBreakdown: CreditBreakdown = {
items: [
{ label: "信用额度", amount: customer.creditLimit, source: "客户主数据 · 信用额度" },
{ label: "库存未提金额", amount: customer.stockUnpickedAmount, source: "ERP · 库存未提汇总" },
{ label: "客户取消订单金额", amount: customer.cancelledOrderAmount, source: "ERP · 取消订单汇总" },
{ label: "当期需求金额", amount, source: `需求文档 · 数量 ${demand.parsed.quantity} × 单价 ${yuan(demand.parsed.unitPrice)} 元` },
],
available: creditAvailable,
pass: creditPass,
};
const items: ScoreItem[] = [
{ label: "毛利达标", weight: SCORE_WEIGHT.margin, score: marginPass ? SCORE_WEIGHT.margin : 0, basis: marginBasis, pass: marginPass },
{ label: "信用达标", weight: SCORE_WEIGHT.credit, score: creditPass ? SCORE_WEIGHT.credit : 0, basis: creditBasis, pass: creditPass },
{ label: "超额利润", weight: SCORE_WEIGHT.excess, score: excessPass ? SCORE_WEIGHT.excess : 0, basis: excessBasis, pass: excessPass },
{ label: "对账单确认", weight: SCORE_WEIGHT.reconciliation, score: reconPass ? SCORE_WEIGHT.reconciliation : 0, basis: reconBasis, pass: reconPass },
];
const total = items.reduce((s, i) => s + i.score, 0);
const pass = total >= SCORE_PASS_LINE;
return {
agent: "rating",
pass,
total,
items,
creditAvailable,
marginChain,
creditBreakdown,
conclusion: pass ? `通过(${total} 分)` : `不通过(${total} 分 < ${SCORE_PASS_LINE})`,
verdict: pass ? "通过" : "不通过",
evidence: items.map((i) => ({ label: `${i.label}(${i.weight} 分)`, value: i.basis, verdict: i.pass ? "通过" as Verdict : "不通过" as Verdict })),
suggestions: [],
};
}
export interface CreditGap {
gap: number;
suggested: number;
bufferRatio: number;
path: string;
}
/** R-建议:授信缺口 = 当期需求金额 −(信用额度 − 库存未提 − 取消订单);建议值含 1.4 倍缓冲并向上取整到 10 万 */
export function computeCreditGap(demand: Demand, customer: CustomerMaster): CreditGap {
const base = customer.creditLimit - customer.stockUnpickedAmount - customer.cancelledOrderAmount;
const gap = demandAmount(demand) - base;
const bufferRatio = 1.4;
const suggested = Math.ceil((gap * bufferRatio) / 100_000) * 100_000;
return { gap, suggested, bufferRatio, path: "授信审批 → 评级复跑 → 重新汇总" };
}