新增模块

This commit is contained in:
2026-10-18 15:27:02 +08:00
parent 5b7d1e8f64
commit f2e6d2b3f1
228 changed files with 46089 additions and 11 deletions
+131
View File
@@ -0,0 +1,131 @@
import type { Demand, IndustryCode } from "../types";
import { customer } from "../mock/customer";
/** 上传文档解析:.docx 解包正文 / .txt 直读;字段口径对齐规格 5.2 */
export async function extractDocumentText(file: File): Promise<string> {
const name = file.name.toLowerCase();
if (name.endsWith(".txt") || name.endsWith(".md")) return file.text();
if (name.endsWith(".docx")) return extractDocxText(await file.arrayBuffer());
if (name.endsWith(".doc")) throw new Error("旧版 .doc 格式无法在线解析,请在 Word 中另存为 .docx 后重新上传。");
if (name.endsWith(".pdf")) throw new Error("PDF 解析通道暂未接入,请上传同一需求的 Word(.docx)或文本版本。");
throw new Error(`不支持的文件格式(${file.name}),当前支持 .docx / .txt。`);
}
async function extractDocxText(buffer: ArrayBuffer): Promise<string> {
const view = new DataView(buffer);
let eocd = -1;
for (let i = buffer.byteLength - 22; i >= 0; i--) {
if (view.getUint32(i, true) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd < 0) throw new Error("需求文档已损坏或不是有效的 .docx 文件,请重新导出后上传。");
const entries = view.getUint16(eocd + 10, true);
let offset = view.getUint32(eocd + 16, true);
for (let n = 0; n < entries; n++) {
if (view.getUint32(offset, true) !== 0x02014b50) break;
const method = view.getUint16(offset + 10, true);
const compSize = view.getUint32(offset + 20, true);
const nameLen = view.getUint16(offset + 28, true);
const extraLen = view.getUint16(offset + 30, true);
const commentLen = view.getUint16(offset + 32, true);
const localOffset = view.getUint32(offset + 42, true);
const entryName = new TextDecoder().decode(new Uint8Array(buffer, offset + 46, nameLen));
if (entryName === "word/document.xml") {
const lNameLen = view.getUint16(localOffset + 26, true);
const lExtraLen = view.getUint16(localOffset + 28, true);
const start = localOffset + 30 + lNameLen + lExtraLen;
const raw = new Uint8Array(buffer, start, compSize);
const xml = new TextDecoder().decode(method === 0 ? raw : await inflateRaw(raw));
return xmlToText(xml);
}
offset += 46 + nameLen + extraLen + commentLen;
}
throw new Error("未能从需求文档中读取正文,请确认其为 Word .docx 文件。");
}
async function inflateRaw(raw: Uint8Array): Promise<Uint8Array> {
const copy = new Uint8Array(raw);
const stream = new Blob([copy]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
function xmlToText(xml: string): string {
return xml
.replace(/<\/w:p>/g, "\n")
.replace(/<w:tab[^>]*>/g, "\t")
.replace(/<w:br[^>]*>/g, "\n")
.replace(/<[^>]+>/g, "")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.trim();
}
export type ParseResult = { ok: true; demand: Demand } | { ok: false; reasons: string[] };
const INDUSTRIES: IndustryCode[] = ["CDU", "储能", "其他"];
function pick(text: string, re: RegExp): string | null {
const m = text.match(re);
return m ? m[1].trim() : null;
}
export function parseDemandDocument(text: string, fileName: string): ParseResult {
const reasons: string[] = [];
const code = pick(text, /客户(?:代码|编号)[::]\s*([A-Za-z0-9-]+)/);
if (!code) reasons.push("缺少「客户代码」");
else if (code !== customer.code) reasons.push(`客户 ${code} 不在客户主数据中(当前仅支持 ${customer.code})`);
const productType = pick(text, /产品(?:类型|名称)[::]\s*([^\n,,;;]+)/);
if (!productType) reasons.push("缺少「产品类型」");
const quantityRaw = pick(text, /(?:需求)?数量[::]\s*([0-9,]+)/);
const quantity = quantityRaw ? Number(quantityRaw.replace(/,/g, "")) : NaN;
if (!quantityRaw || !Number.isFinite(quantity) || quantity <= 0) reasons.push("缺少有效的「数量」");
const priceRaw = pick(text, /单价[::]\s*([0-9,]+)/);
const unitPrice = priceRaw ? Number(priceRaw.replace(/,/g, "")) : NaN;
if (!priceRaw || !Number.isFinite(unitPrice) || unitPrice <= 0) reasons.push("缺少有效的「单价」");
const coilMaterial = pick(text, /钢卷(?:材质)?[::]\s*([A-Za-z0-9]+)/);
if (!coilMaterial) reasons.push("缺少「钢卷材质」");
const dateMatch = text.match(/(?:交期|交付日期|交货日期)[::]\s*(\d{4})\s*[-年/.]\s*(\d{1,2})\s*[-月/.]\s*(\d{1,2})/);
if (!dateMatch) reasons.push("缺少有效的「交期」");
const deliveryDate = dateMatch
? `${dateMatch[1]}-${dateMatch[2].padStart(2, "0")}-${dateMatch[3].padStart(2, "0")}`
: "";
if (reasons.length > 0 || !productType || !coilMaterial) return { ok: false, reasons };
const industryRaw = pick(text, new RegExp(`行业[::]\\s*(${INDUSTRIES.join("|")})`));
const industry = (industryRaw as IndustryCode | null) ?? null;
return {
ok: true,
demand: {
id: fileName,
label: `${productType} · ${quantity} 个`,
customerCode: code as string,
document: { fileName, fileType: fileName.toLowerCase().endsWith(".txt") ? "txt" : "docx" },
parsed: {
industry,
productType,
quantity,
unitPrice,
deliveryDate,
coilMaterial,
},
missingFields: industry ? [] : ["industry"],
followUp: industry
? null
: { field: "industry", prompt: "需求文档缺少「行业」字段,请补全:", options: INDUSTRIES },
provenance: "上传文档解析",
},
};
}
+76
View File
@@ -0,0 +1,76 @@
import { yuan } from "./format";
/** 研发填报动态推导(规格 V1.3):模具/项目周期按数量,回收期按本单毛利额(假设年 1 单) */
export const RND_INVEST_TOTAL = 112_000;
export const RND_INVEST_ITEMS = [
{ name: "模具投入", amount: 80_000 },
{ name: "工装投入", amount: 20_000 },
{ name: "试产费用", amount: 12_000 },
];
export interface FilingValues {
moldDays: number;
projectDays: number;
paybackMonths: number;
paybackLabel: string;
paybackPass: boolean;
moldSteps: Array<{ name: string; days: number }>;
projectSteps: Array<{ name: string; days: number }>;
investCalc: string;
values: [string, string, string];
}
export function deriveFiling(quantity: number, grossProfit: number): FilingValues {
const moldDays = quantity <= 200 ? 2 : 3;
const projectDays = quantity <= 200 ? 8 : 10;
const moldSteps =
moldDays === 2
? [
{ name: "模具设计", days: 0.5 },
{ name: "CNC 加工", days: 1 },
{ name: "试模确认", days: 0.5 },
]
: [
{ name: "模具设计", days: 0.5 },
{ name: "CNC 加工", days: 1.5 },
{ name: "试模确认", days: 1 },
];
const projectSteps =
projectDays === 8
? [
{ name: "工艺与工装准备", days: 2 },
{ name: "316L 钢卷采购", days: 2 },
{ name: "冲压 + 铜钎焊生产", days: 3 },
{ name: "检验入库", days: 1 },
]
: [
{ name: "工艺与工装准备", days: 2 },
{ name: "316L 钢卷采购", days: 2 },
{ name: "冲压 + 铜钎焊生产(批量排产)", days: 5 },
{ name: "检验入库", days: 1 },
];
const paybackMonths = (RND_INVEST_TOTAL / grossProfit) * 12;
const paybackPass = paybackMonths <= 12;
const paybackLabel = !paybackPass
? `${(paybackMonths / 12).toFixed(1)} 年`
: paybackMonths < 1
? "约 1 个月"
: Math.abs(paybackMonths - 6) < 0.05
? "半年"
: `${Math.round(paybackMonths)} 个月`;
const profitWan = (grossProfit / 10_000).toLocaleString("zh-CN", { maximumFractionDigits: 1 });
const investCalc = paybackPass
? `投入 ${yuan(RND_INVEST_TOTAL)} 元 < 本单毛利 ${profitWan} 万,本单周期内全额回收(假设年 1 单)→ 投资回收期 ${paybackLabel}`
: `投入 ${yuan(RND_INVEST_TOTAL)} 元 > 本单毛利 ${profitWan} 万,一年内无法回收 → 投资回收期 ${paybackLabel}(不满足 ≤1 年)`;
return {
moldDays,
projectDays,
paybackMonths,
paybackLabel,
paybackPass,
moldSteps,
projectSteps,
investCalc,
values: [`${moldDays} 天`, `${projectDays} 天`, paybackLabel],
};
}
+10
View File
@@ -0,0 +1,10 @@
/** 展示格式化:金额统一存元,展示时转千分位 / 万 */
export function yuan(n: number): string {
return n.toLocaleString("zh-CN");
}
export function wan(n: number): string {
return (n / 10_000).toLocaleString("zh-CN", { maximumFractionDigits: 2 });
}
export function pct(rate: number, digits = 0): string {
return `${(rate * 100).toFixed(digits)}%`;
}
+154
View File
@@ -0,0 +1,154 @@
import type { EvidenceRow } from "../types";
import type { Scenario } from "../mock/scenarios";
import { pct, wan, yuan } from "./format";
/** 流程收尾自动出具的《需求评估报告》:自包含 HTML 网页,新标签页打开 */
export type ReviewOutcome = "order" | "credit";
const pad = (n: number) => `${n}`.padStart(2, "0");
export function reportFileName(s: Scenario, when: Date = new Date()): string {
const p = s.demand.parsed;
const stamp = `${when.getFullYear()}${pad(when.getMonth() + 1)}${pad(when.getDate())}-${pad(when.getHours())}${pad(when.getMinutes())}`;
return `需求评估报告-${p.productType}-${p.quantity}个-${stamp}.html`;
}
function esc(t: string): string {
return t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function evidenceRows(rows: EvidenceRow[]): string {
return rows
.map(
(r) =>
`<tr><td class="k">${esc(r.label)}</td><td>${esc(r.value)}</td><td class="v ${r.verdict === "通过" ? "pass" : r.verdict === "不通过" ? "fail" : ""}">${r.verdict ? esc(r.verdict) : ""}</td></tr>`,
)
.join("");
}
const CSS = `
* { box-sizing: border-box; }
body { margin: 0; background: #f4f6fb; color: #1e293b; font: 14px/1.65 -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif; }
.wrap { max-width: 980px; margin: 0 auto; padding: 32px 20px 64px; }
.hero { background: linear-gradient(135deg, #0b2a6b 0%, #2563eb 62%, #3b82f6 100%); color: #fff; border-radius: 16px; padding: 28px 30px; box-shadow: 0 12px 32px rgba(37, 99, 235, .25); }
.hero .eyebrow { letter-spacing: .18em; font-size: 11px; opacity: .82; }
.hero h1 { margin: 6px 0 10px; font-size: 26px; letter-spacing: .02em; }
.hero .meta { display: flex; flex-wrap: wrap; gap: 8px 18px; font-size: 12px; opacity: .92; }
.banner { margin: 18px 0 0; border-radius: 12px; padding: 14px 18px; font-size: 15px; font-weight: 700; }
.banner.ok { background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; }
.banner.fail { background: #fef2f2; color: #b91c1c; border: 1px solid #fecaca; }
.card { background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 18px 20px; margin-top: 16px; box-shadow: 0 1px 2px rgba(15, 23, 42, .05), 0 8px 24px rgba(15, 23, 42, .06); }
.card h2 { margin: 0 0 10px; font-size: 15px; color: #0b2a6b; border-left: 4px solid #2563eb; padding-left: 10px; }
.lead { margin: 4px 0 10px; font-size: 13px; color: #475569; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px 18px; margin: 0; font-size: 13px; }
.grid dt { color: #64748b; font-size: 12px; }
.grid dd { margin: 2px 0 0; font-weight: 600; font-variant-numeric: tabular-nums; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
td, th { padding: 8px 10px; border-bottom: 1px solid #eef2f7; text-align: left; vertical-align: top; }
tr:last-child td { border-bottom: 0; }
td.k { color: #64748b; width: 34%; }
td.v { width: 64px; text-align: right; font-weight: 700; white-space: nowrap; }
td.v.pass { color: #15803d; }
td.v.fail { color: #b91c1c; }
.note { margin: 10px 0 0; padding: 10px 12px; background: #eff6ff; border-radius: 10px; color: #1d4ed8; font-size: 12.5px; }
.score { display: flex; align-items: baseline; gap: 10px; margin: 4px 0 8px; }
.score b { font-size: 30px; color: #0b2a6b; font-variant-numeric: tabular-nums; }
.score span { color: #64748b; font-size: 12px; }
.bar { height: 10px; border-radius: 999px; background: #e2e8f0; overflow: hidden; position: relative; }
.bar i { display: block; height: 100%; border-radius: 999px; background: linear-gradient(90deg, #2563eb, #60a5fa); }
.bar u { position: absolute; left: 90%; top: -3px; width: 2px; height: 16px; background: #b91c1c; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.tag { font-size: 12px; padding: 4px 10px; border-radius: 999px; background: #f1f5f9; color: #475569; }
.tag.ok { background: #f0fdf4; color: #15803d; }
.tag.fail { background: #fef2f2; color: #b91c1c; }
ul.sug { margin: 8px 0 0; padding-left: 20px; font-size: 13px; color: #475569; }
footer { margin-top: 22px; color: #94a3b8; font-size: 12px; text-align: center; }
b.ok { color: #15803d; } b.fail { color: #b91c1c; }
@media print { body { background: #fff; } .card, .hero { box-shadow: none; } }
`;
export function buildReportHtml(s: Scenario, outcome: ReviewOutcome): string {
const d = s.demand;
const p = d.parsed;
const order = s.summary.order;
const now = new Date().toLocaleString("zh-CN", { hour12: false });
const rndSection =
s.feasibility.route === "rnd"
? `<section class="card"><h2>新品研发评审</h2>
<p class="lead">结论:<b class="${s.rnd.pass ? "ok" : "fail"}">${s.rnd.pass ? "通过" : "不通过"}</b>(4 项评审全过才通过)</p>
<table><tbody>${s.rnd.items
.map(
(i) =>
`<tr><td class="k">${esc(i.label)}</td><td>标准 ${esc(i.standard)}</td><td>实际 ${esc(i.actual ?? "—")}</td><td class="v ${i.pass ? "pass" : "fail"}">${i.pass ? "通过" : "不通过"}</td></tr>`,
)
.join("")}</tbody></table>
<p class="note">毛利复算:收入 ${yuan(s.margin.revenue)} − 钢卷 ${yuan(s.margin.coilCostTotal)} = ${yuan(s.margin.grossProfit)} 元(毛利率 ${pct(s.margin.grossMarginRate)})</p></section>`
: "";
const ratingTags = s.rating.items
.map((i) => `<span class="tag ${i.pass ? "ok" : "fail"}">${esc(i.label)} ${i.score}/${i.weight}</span>`)
.join("");
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>需求评估报告 · ${esc(p.productType)} ${p.quantity} 个</title>
<style>${CSS}</style>
</head>
<body>
<div class="wrap">
<header class="hero">
<div class="eyebrow">BAODE · INTELLIGENT REVIEW</div>
<h1>需求评估报告</h1>
<div class="meta">
<span>来源文档:${esc(d.document.fileName)}</span>
<span>生成时间:${esc(now)}</span>
<span>出具:需求评审多智能体系统</span>
</div>
</header>
<div class="banner ${order ? "ok" : "fail"}">整体结论:${esc(s.summary.overall)}${order ? ` · 订单 ${esc(order.orderNo)}` : ""}</div>
<section class="card"><h2>需求概要</h2>
<dl class="grid">
<div><dt>客户</dt><dd>${esc(d.customerCode)}</dd></div>
<div><dt>行业</dt><dd>${esc(p.industry ?? "—")}</dd></div>
<div><dt>产品类型</dt><dd>${esc(p.productType)}</dd></div>
<div><dt>数量 / 单价</dt><dd>${p.quantity} 个 / ${yuan(p.unitPrice)} 元</dd></div>
<div><dt>当期需求金额</dt><dd>${wan(p.quantity * p.unitPrice)} 万</dd></div>
<div><dt>交期</dt><dd>${esc(p.deliveryDate)}</dd></div>
<div><dt>钢卷材质</dt><dd>${esc(p.coilMaterial)}</dd></div>
</dl>
</section>
<section class="card"><h2>可行性判定</h2>
<p class="lead">结论:<b>${esc(s.feasibility.category)}</b>(${esc(s.feasibility.routeLabel)})</p>
<table><tbody>${evidenceRows(s.feasibility.evidence)}</tbody></table>
</section>
${rndSection}
<section class="card"><h2>交期评审</h2>
<p class="lead">结论:<b class="${s.delivery.pass ? "ok" : "fail"}">${s.delivery.pass ? "通过" : "不通过"}</b> · 距交期 ${s.delivery.daysToDelivery} 天</p>
<table><tbody>${evidenceRows(s.delivery.evidence)}</tbody></table>
${s.delivery.suggestions.length ? `<ul class="sug">${s.delivery.suggestions.map((t) => `<li>${esc(t)}</li>`).join("")}</ul>` : ""}
</section>
<section class="card"><h2>客户评级</h2>
<div class="score"><b>${s.rating.total}</b><span>/ 100 分 · ≥90 合格 · 红线为合格线</span></div>
<div class="bar"><i style="width:${Math.min(100, s.rating.total)}%"></i><u></u></div>
<div class="tags">${ratingTags}</div>
<table><tbody>${s.rating.items
.map((i) => `<tr><td class="k">${esc(i.label)}(权重 ${i.weight})</td><td>${esc(i.basis)}</td><td class="v ${i.pass ? "pass" : "fail"}">${i.score} 分</td></tr>`)
.join("")}</tbody></table>
</section>
<section class="card"><h2>综合结论与处理</h2>
<p class="lead">整体结论:<b class="${order ? "ok" : "fail"}">${esc(s.summary.overall)}</b></p>
${order ? `<p class="note">订单:${esc(order.orderNo)}|金额 ${yuan(order.amount)} 元|交期 ${esc(order.deliveryDate)}</p>` : ""}
${s.summary.suggestions.length ? `<ul class="sug">${s.summary.suggestions.map((t) => `<li>${esc(t)}</li>`).join("")}</ul>` : ""}
<p class="lead">${outcome === "order" ? "处理结果:用户已确认评审结论并发起订单生成。" : "处理结果:用户已发起客户临时授信流程(授信审批 → 评级复跑 → 重新汇总)。"}</p>
</section>
<footer>需求评审多智能体系统 自动出具 · ${esc(now)}</footer>
</div>
</body>
</html>`;
return html;
}
+262
View File
@@ -0,0 +1,262 @@
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: "授信审批 → 评级复跑 → 重新汇总" };
}
+57
View File
@@ -0,0 +1,57 @@
import type { AgentResult, CustomerMaster, Demand } from "../types";
import type { DeliveryResult, FeasibilityResult, RatingResult, RndResult } from "./rules";
import { computeCreditGap } from "./rules";
import { customer } from "../mock/customer";
import { wan } from "./format";
export interface OrderMock {
orderNo: string;
itemSummary: string;
amount: number;
deliveryDate: string;
}
export interface SummaryResult {
overall: "评审通过" | "评审不通过";
rows: Array<{ agent: string; conclusion: string; keyEvidence: string }>;
suggestions: string[];
creditGap: ReturnType<typeof computeCreditGap> | null;
order: OrderMock | null;
}
/** 第四幕:主智能体汇总 + 订单 / 建议(规格 2.4) */
export function summarize(
demand: Demand,
feasibility: FeasibilityResult,
rnd: RndResult | null,
delivery: DeliveryResult,
rating: RatingResult,
customerOverride?: CustomerMaster,
): SummaryResult {
const rows = [
{ agent: "可行性", conclusion: feasibility.category, keyEvidence: `${demand.parsed.productType}命中 ${feasibility.category === "非标品" ? "R-可行-2" : "R-可行-1"}` },
...(rnd ? [{ agent: "新品研发评审", conclusion: rnd.pass ? "通过" : "不通过", keyEvidence: rnd.items.map((i) => i.actual ?? "—").join(" / ") }] : []),
{ agent: "交期评审", conclusion: delivery.pass ? "通过" : "不通过", keyEvidence: `负荷 78%;采购+生产 ${delivery.daysToDelivery} 天内可覆盖` },
{ agent: "客户评级", conclusion: rating.pass ? "通过" : "不通过", keyEvidence: `记分 ${rating.total} ${rating.pass ? "≥" : "<"} 90` },
];
const allPass = feasibility !== null && (rnd ? rnd.pass : true) && delivery.pass && rating.pass;
const suggestions: string[] = [...delivery.suggestions];
let creditGap: ReturnType<typeof computeCreditGap> | null = null;
if (!rating.pass && rating.items[1].score === 0) {
creditGap = computeCreditGap(demand, customerOverride ?? customer);
suggestions.push(
`建议发起客户临时授信:精确缺口 ${wan(creditGap.gap)} 万,建议授信 ≥ ${wan(creditGap.suggested)} 万(含缓冲)`,
`处理路径:${creditGap.path}`,
);
}
const order: OrderMock | null = allPass
? {
orderNo: "SO-2610-0001",
itemSummary: `${demand.parsed.productType} ${demand.parsed.quantity} 个 @ ${demand.parsed.unitPrice.toLocaleString("zh-CN")} 元`,
amount: demand.parsed.quantity * demand.parsed.unitPrice,
deliveryDate: demand.parsed.deliveryDate,
}
: null;
return { overall: allPass ? "评审通过" : "评审不通过", rows, suggestions, creditGap, order };
}
export type { AgentResult };