新增模块
@@ -19,6 +19,7 @@
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^7.1.1",
|
||||
"sql.js": "^1.14.2",
|
||||
"tailwind-merge": "^2.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -3151,6 +3152,12 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/sql.js": {
|
||||
"version": "1.14.2",
|
||||
"resolved": "https://registry.npmmirror.com/sql.js/-/sql.js-1.14.2.tgz",
|
||||
"integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/string-convert": {
|
||||
"version": "0.2.1",
|
||||
"resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz",
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-router-dom": "^7.1.1",
|
||||
"sql.js": "^1.14.2",
|
||||
"tailwind-merge": "^2.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 90 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 18 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 19 KiB |
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 16 KiB |
@@ -3,6 +3,7 @@ import HomePage from '@/pages/HomePage';
|
||||
import SSOLogin from '@/pages/SSOLogin';
|
||||
import LoginPage from '@/pages/LoginPage';
|
||||
import RequireAuth from '@/shared/components/RequireAuth';
|
||||
import ModuleTitle from '@/shared/components/ModuleTitle';
|
||||
import AIMCockpit from '@/modules/ai-matching/pages/AIMCockpit';
|
||||
import CostCockpit from '@/modules/cost-analysis/pages/CostCockpit';
|
||||
import KnowledgeGraphHome from '@/modules/knowledge-graph/pages/KnowledgeGraphHome';
|
||||
@@ -12,6 +13,10 @@ import CostCockpitFull from '@/modules/order-cost-analysis/pages/CostCockpitFull
|
||||
import AIMCockpitFull from '@/modules/order-cost-analysis/pages/AIMCockpitFull';
|
||||
import BexellSchedulingApp from '@/modules/bexell-scheduling-ai/App';
|
||||
import SanruiAIDesignHome from '@/modules/sanrui-ai-design/pages/SanruiAIDesignHome';
|
||||
import JieyaIbpApp from '@/modules/jieya-ibp/App';
|
||||
import WelltrustQapApp from '@/modules/welltrust-qap/App';
|
||||
import BaodeWebApp from '@/modules/baode-web/App';
|
||||
import SupplierPlatformApp from '@/modules/supplier-platform/App';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
@@ -19,15 +24,19 @@ export default function App() {
|
||||
<Route path="/login" element={<LoginPage />} />
|
||||
<Route path="/sso-login" element={<SSOLogin />} />
|
||||
<Route path="/" element={<RequireAuth><HomePage /></RequireAuth>} />
|
||||
<Route path="/ai-matching" element={<RequireAuth><AIMCockpit /></RequireAuth>} />
|
||||
<Route path="/cost-analysis" element={<RequireAuth><CostCockpit /></RequireAuth>} />
|
||||
<Route path="/knowledge-graph" element={<RequireAuth><KnowledgeGraphHome /></RequireAuth>} />
|
||||
<Route path="/knowledge-graph/space" element={<RequireAuth><SpaceCockpit /></RequireAuth>} />
|
||||
<Route path="/bomx-reuse-analyzer" element={<RequireAuth><BomxReuseHome /></RequireAuth>} />
|
||||
<Route path="/order-cost-analysis" element={<RequireAuth><CostCockpitFull /></RequireAuth>} />
|
||||
<Route path="/order-cost-analysis/aim" element={<RequireAuth><AIMCockpitFull /></RequireAuth>} />
|
||||
<Route path="/bexell-scheduling-ai/*" element={<RequireAuth><BexellSchedulingApp /></RequireAuth>} />
|
||||
<Route path="/sanrui-ai-design" element={<RequireAuth><SanruiAIDesignHome /></RequireAuth>} />
|
||||
<Route path="/ai-matching" element={<RequireAuth><ModuleTitle title="AI+制造 智创空间"><AIMCockpit /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/cost-analysis" element={<RequireAuth><ModuleTitle title="AI订单成本分析"><CostCockpit /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/knowledge-graph" element={<RequireAuth><ModuleTitle title="采购域知识图谱"><KnowledgeGraphHome /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/knowledge-graph/space" element={<RequireAuth><ModuleTitle title="采购域知识图谱"><SpaceCockpit /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/bomx-reuse-analyzer" element={<RequireAuth><ModuleTitle title="企业级BOM标准化治理"><BomxReuseHome /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/order-cost-analysis" element={<RequireAuth><ModuleTitle title="AI+成本智能分析平台"><CostCockpitFull /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/order-cost-analysis/aim" element={<RequireAuth><ModuleTitle title="AI+成本智能分析平台"><AIMCockpitFull /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/bexell-scheduling-ai/*" element={<RequireAuth><ModuleTitle title="试产排程评估及优化"><BexellSchedulingApp /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/sanrui-ai-design" element={<RequireAuth><ModuleTitle title="AI设计标准化智能体"><SanruiAIDesignHome /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/jieya-ibp" element={<RequireAuth><ModuleTitle title="销售订单履约控制塔"><JieyaIbpApp /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/welltrust-qap" element={<RequireAuth><ModuleTitle title="品质异常预防工作台"><WelltrustQapApp /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/baode-web" element={<RequireAuth><ModuleTitle title="需求评审多智能体"><BaodeWebApp /></ModuleTitle></RequireAuth>} />
|
||||
<Route path="/supplier-platform" element={<RequireAuth><ModuleTitle title="供应商智能管控平台"><SupplierPlatformApp /></ModuleTitle></RequireAuth>} />
|
||||
</Routes>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import "./styles.css";
|
||||
import { useState } from "react";
|
||||
import { Header } from "./components/Header";
|
||||
import { HistoryPanel } from "./components/HistoryPanel";
|
||||
import { OrchestrationCanvas } from "./components/OrchestrationCanvas";
|
||||
import { RightPanel } from "./components/RightPanel";
|
||||
import { SelfCheck } from "./components/SelfCheck";
|
||||
import { useReviewRunner } from "./state/useReviewRunner";
|
||||
|
||||
const showCheck = typeof window !== "undefined" && window.location.search.includes("check=1");
|
||||
|
||||
function Cockpit() {
|
||||
const runner = useReviewRunner();
|
||||
const [historyOpen, setHistoryOpen] = useState(false);
|
||||
return (
|
||||
<div className="cockpit-root">
|
||||
<Header onOpenHistory={() => setHistoryOpen(true)} />
|
||||
<main className="cockpit">
|
||||
<OrchestrationCanvas
|
||||
nodes={runner.nodes}
|
||||
floats={runner.floats}
|
||||
floatFocus={runner.floatFocus}
|
||||
scenario={runner.scenario}
|
||||
ratingRevealed={runner.ratingRevealed}
|
||||
/>
|
||||
<RightPanel runner={runner} />
|
||||
</main>
|
||||
<HistoryPanel open={historyOpen} onClose={() => setHistoryOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
// baode-root:模块样式命名空间根容器,避免通用类名(logo/btn/modal 等)污染其他模块
|
||||
return <div className="baode-root">{showCheck ? <SelfCheck /> : <Cockpit />}</div>;
|
||||
}
|
||||
|
After Width: | Height: | Size: 7.4 KiB |
@@ -0,0 +1,77 @@
|
||||
import { useEffect } from "react";
|
||||
import { bomLines, newBomAssumption, productMaster, steelCoils } from "../mock/bom";
|
||||
import { yuan } from "../engine/format";
|
||||
|
||||
/** 新品 BOM 详细弹窗:展示 BL95A-58 多层 BOM(含下展层与失效件标识) */
|
||||
export function BomModal({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [open, onClose]);
|
||||
if (!open) return null;
|
||||
const coilCost = steelCoils.reduce((s, c) => s + c.kgPerUnit * c.unitPrice, 0);
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose} role="presentation">
|
||||
<div
|
||||
className="modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="新品 BOM 详细"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<span>新品 BOM 详细 · {productMaster.itemName}</span>
|
||||
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<dl className="kv-grid modal-kv">
|
||||
<dt>品号</dt><dd>{productMaster.itemCode}</dd>
|
||||
<dt>品名</dt><dd>{productMaster.itemName}</dd>
|
||||
<dt>规格</dt><dd>{productMaster.spec}</dd>
|
||||
<dt>品号类型</dt><dd>{productMaster.makeType}</dd>
|
||||
<dt>工厂</dt><dd>{productMaster.plant}</dd>
|
||||
<dt>图号</dt><dd>{productMaster.drawingNo}</dd>
|
||||
<dt>BOM 日期</dt><dd>{productMaster.bomDate}</dd>
|
||||
<dt>版次</dt><dd>{productMaster.revision}</dd>
|
||||
</dl>
|
||||
<table className="bom-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>序号</th>
|
||||
<th>元件品号 / 品名</th>
|
||||
<th>规格</th>
|
||||
<th>用量</th>
|
||||
<th>单价</th>
|
||||
<th>总价</th>
|
||||
<th>状态</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{bomLines.map((l) => (
|
||||
<tr key={l.seq} className={l.level === 2 ? "lvl2" : l.status === "失效" ? "invalid" : ""}>
|
||||
<td>{l.level === 2 ? "└" : l.seq}</td>
|
||||
<td>
|
||||
{l.itemName} <span className="sub">{l.itemCode}</span>
|
||||
</td>
|
||||
<td>{l.spec}</td>
|
||||
<td>{l.level === 2 ? l.qtyDisplay : l.qtyPerUnit}</td>
|
||||
<td>{l.unitPrice ? l.unitPrice.toFixed(2) : "—"}</td>
|
||||
<td>{l.totalPrice ? l.totalPrice.toFixed(2) : "—"}</td>
|
||||
<td>{l.status}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<p className="modal-note">
|
||||
钢卷用量汇总(复算口径):{steelCoils.map((c) => `${c.material} ${c.kgPerUnit} kg/台 × ${c.unitPrice} 元`).join(" + ")} ={" "}
|
||||
<b>{yuan(coilCost)} 元/台</b>;{newBomAssumption.basis}。失效件 2220160034 仅做状态识别展示,不计用量与金额。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { EvidenceRow } from "../types";
|
||||
|
||||
/** 依据表(H7:每个结论都带依据表) */
|
||||
export function EvidenceTable({ rows }: { rows: EvidenceRow[] }) {
|
||||
return (
|
||||
<table className="ev">
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={i}>
|
||||
<td className="ev-label">{r.label}</td>
|
||||
<td className="ev-value">{r.value}</td>
|
||||
{r.verdict ? (
|
||||
<td className={r.verdict === "通过" ? "ev-v pass" : "ev-v fail"}>{r.verdict}</td>
|
||||
) : (
|
||||
<td className="ev-v" />
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { currentUser } from "../mock/user";
|
||||
import logoUrl from "../assets/logo.png";
|
||||
|
||||
export function Header({ onOpenHistory }: { onOpenHistory: () => void }) {
|
||||
return (
|
||||
<header className="topbar">
|
||||
<img className="logo" src={logoUrl} alt="宝得换热" width={212} height={40} />
|
||||
<div className="topbar-title">
|
||||
<strong>订单需求评审智能体</strong>
|
||||
</div>
|
||||
<div className="topbar-right">
|
||||
<button type="button" className="btn" onClick={onOpenHistory}>
|
||||
评审历史
|
||||
</button>
|
||||
<span className="user-chip">
|
||||
{currentUser.name} · {currentUser.code}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { ReviewRecord } from "../state/history";
|
||||
import { getReviewRecord, listReviewRecords } from "../state/history";
|
||||
import { EvidenceTable } from "./EvidenceTable";
|
||||
|
||||
/** 评审历史:已完成评审的清单与当次执行轨迹回看 */
|
||||
|
||||
function fmt(iso: string): string {
|
||||
return new Date(iso).toLocaleString("zh-CN", { hour12: false });
|
||||
}
|
||||
|
||||
function openReportHtml(html: string): void {
|
||||
const url = URL.createObjectURL(new Blob([html], { type: "text/html;charset=utf-8" }));
|
||||
window.open(url, "_blank");
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
}
|
||||
|
||||
export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () => void }) {
|
||||
const [records, setRecords] = useState<ReviewRecord[]>([]);
|
||||
const [selected, setSelected] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setRecords(listReviewRecords());
|
||||
setSelected(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
if (!open) return null;
|
||||
const detail = selected ? getReviewRecord(selected) : null;
|
||||
|
||||
return (
|
||||
<div className="hist-mask" role="dialog" aria-label="评审历史">
|
||||
<div className="hist">
|
||||
<div className="hist-head">
|
||||
<span>{detail ? "执行详情" : "评审历史"}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
onClick={detail ? () => setSelected(null) : onClose}
|
||||
aria-label={detail ? "返回列表" : "关闭"}
|
||||
>
|
||||
{detail ? "←" : "✕"}
|
||||
</button>
|
||||
</div>
|
||||
<div className="hist-body">
|
||||
{detail ? (
|
||||
<>
|
||||
<dl className="kv-grid">
|
||||
<dt>记录编号</dt><dd>{detail.id}</dd>
|
||||
<dt>发起人</dt><dd>{detail.operator.name} · {detail.operator.code}</dd>
|
||||
<dt>开始时间</dt><dd>{fmt(detail.startedAt)}</dd>
|
||||
<dt>结束时间</dt><dd>{fmt(detail.finishedAt)}</dd>
|
||||
<dt>来源文档</dt><dd>{detail.fileName}</dd>
|
||||
<dt>需求</dt><dd>{detail.productType} {detail.quantity} 个 @ {detail.unitPrice} 元</dd>
|
||||
<dt>可行性判定</dt><dd>{detail.feasibilityCategory}</dd>
|
||||
<dt>评级记分</dt><dd>{detail.ratingTotal} 分</dd>
|
||||
<dt>整体结论</dt><dd>{detail.overall}</dd>
|
||||
<dt>订单 / 授信</dt><dd>{detail.orderNo ?? (detail.creditStarted ? "已发起临时授信" : "—")}</dd>
|
||||
</dl>
|
||||
<div className="todo-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => openReportHtml(detail.reportHtml)}>
|
||||
打开当次评估报告
|
||||
</button>
|
||||
</div>
|
||||
<h3 className="hist-sub">执行轨迹</h3>
|
||||
<ol className="trace">
|
||||
{detail.trace.map((t, i) => (
|
||||
<li key={i}>
|
||||
<div className="trace-head">
|
||||
<span className="trace-time">{t.time}</span>
|
||||
<span className="trace-agent">{t.agent}</span>
|
||||
<strong>{t.title}</strong>
|
||||
</div>
|
||||
{t.note ? <p className="trace-note">{t.note}</p> : null}
|
||||
{t.rows?.length ? <EvidenceTable rows={t.rows} /> : null}
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</>
|
||||
) : records.length === 0 ? (
|
||||
<p className="chat-empty">暂无评审记录。上传需求文档发起评审后,完成的评审会自动归档在此。</p>
|
||||
) : (
|
||||
<table className="hist-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>记录编号</th>
|
||||
<th>发起时间</th>
|
||||
<th>发起人</th>
|
||||
<th>需求</th>
|
||||
<th>结论</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{records.map((r) => (
|
||||
<tr key={r.id}>
|
||||
<td>{r.id}</td>
|
||||
<td>{fmt(r.startedAt)}</td>
|
||||
<td>{r.operator.name}</td>
|
||||
<td>{r.productType} {r.quantity} 个</td>
|
||||
<td>
|
||||
<span className={`badge ${r.orderNo ? "badge-ok" : "badge-fail"}`}>{r.overall}</span>
|
||||
</td>
|
||||
<td>
|
||||
<button type="button" className="btn" onClick={() => setSelected(r.id)}>
|
||||
查看
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
import { pct, yuan } from "../engine/format";
|
||||
|
||||
/** 订单毛利复算表:收入 / 钢卷成本 / 毛利 / 毛利率(无标题,直接可读) */
|
||||
export function MarginCalcTable({ scenario }: { scenario: Scenario }) {
|
||||
const m = scenario.margin;
|
||||
const q = scenario.demand.parsed.quantity;
|
||||
const p = scenario.demand.parsed.unitPrice;
|
||||
return (
|
||||
<table className="bom-table float-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>收入</td>
|
||||
<td>{q} × {yuan(p)} = {yuan(m.revenue)} 元</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>钢卷成本</td>
|
||||
<td>{yuan(m.coilCostPerUnit)} 元/台 × {q} = {yuan(m.coilCostTotal)} 元</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>订单毛利</td>
|
||||
<td>{yuan(m.revenue)} − {yuan(m.coilCostTotal)} = {yuan(m.grossProfit)} 元</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>订单毛利率</td>
|
||||
<td>{yuan(m.grossProfit)} ÷ {yuan(m.revenue)} = {pct(m.grossMarginRate)}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import type { FloatCard, NodeId, NodeState } from "../state/types";
|
||||
import { EvidenceTable } from "./EvidenceTable";
|
||||
import { BomModal } from "./BomModal";
|
||||
import { RndDetailModal } from "./RndDetailModal";
|
||||
import { RatingDetailModal } from "./RatingDetailModal";
|
||||
import { RatingScorePanels } from "./RatingScorePanels";
|
||||
import { agentIntros } from "../mock/agents";
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
|
||||
const LINK_LABELS: Record<"bom" | "cycle" | "invest", string> = {
|
||||
bom: "查看新品 BOM 详细 →",
|
||||
cycle: "周期详细 →",
|
||||
invest: "投资详细 →",
|
||||
};
|
||||
const ICON_PATHS: Record<NodeId, string> = {
|
||||
parse: "M14 3v4a1 1 0 0 0 1 1h4M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM9 13h6M9 17h6",
|
||||
feasibility: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6l7-3zM9.5 12l2 2 3.5-4",
|
||||
judge: "M12 4l6 8-6 8-6-8 6-8z",
|
||||
rnd: "M9 3h6M10 3v5l-5 9a2 2 0 0 0 2 3h10a2 2 0 0 0 2-3l-5-9V3",
|
||||
delivery: "M3 7h11v8H3zM14 10h4l3 3v2h-7M7 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM17 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z",
|
||||
rating: "M12 4l2.4 4.9 5.4.8-3.9 3.8.9 5.4-4.8-2.5-4.8 2.5.9-5.4L4.2 9.7l5.4-.8L12 4z",
|
||||
summary: "M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2M9 5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2M9 5h6M9.5 14l2 2 3.5-4",
|
||||
};
|
||||
|
||||
function NodeIcon({ id, onIntro, label }: { id: NodeId; onIntro: (id: NodeId) => void; label: string }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="node-icon"
|
||||
title={`介绍:${label}`}
|
||||
aria-label={`介绍:${label}`}
|
||||
onClick={() => onIntro(id)}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
|
||||
<path d={ICON_PATHS[id]} />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_ICON: Record<NodeState["status"], string> = {
|
||||
排队: "○",
|
||||
执行中: "◌",
|
||||
等待填报: "◔",
|
||||
待补全: "!",
|
||||
已完成: "✓",
|
||||
不通过: "✕",
|
||||
跳过: "→",
|
||||
};
|
||||
|
||||
const AGENT_IDS: NodeId[] = ["feasibility", "rnd", "delivery", "rating"];
|
||||
|
||||
function NodeCard(props: {
|
||||
id: NodeId;
|
||||
label: string;
|
||||
note?: string;
|
||||
state: NodeState;
|
||||
kind?: "agent" | "control" | "decision";
|
||||
onIntro: (id: NodeId) => void;
|
||||
started: boolean;
|
||||
}) {
|
||||
const { id, label, note, state, kind = "agent", onIntro, started } = props;
|
||||
const showStatus = state.status !== "排队" || (started && AGENT_IDS.includes(id));
|
||||
return (
|
||||
<div className={`fnode kind-${kind} s-${state.status}`} data-node={id}>
|
||||
<div className="fnode-card">
|
||||
<div className="fnode-top">
|
||||
<NodeIcon id={id} label={label} onIntro={onIntro} />
|
||||
<span className="fnode-dot" aria-hidden>{STATUS_ICON[state.status]}</span>
|
||||
{showStatus ? <span className="fnode-status">{state.status}</span> : null}
|
||||
</div>
|
||||
<span className="fnode-label">
|
||||
<span className="fnode-label-row">
|
||||
{label}
|
||||
{state.metric ? <span className="fnode-metric">{state.metric}</span> : null}
|
||||
</span>
|
||||
{kind === "agent" || note ? (
|
||||
<em className="fnode-note">
|
||||
{kind === "agent" ? <span className="agent-tag">智能体</span> : null}
|
||||
{note ? <span>{note}</span> : null}
|
||||
</em>
|
||||
) : null}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface BypassGeom {
|
||||
left: number;
|
||||
width: number;
|
||||
leftDrop: number;
|
||||
rightDrop: number;
|
||||
}
|
||||
|
||||
function DecisionNode(props: { state: NodeState; onIntro: (id: NodeId) => void }) {
|
||||
const { state, onIntro } = props;
|
||||
const showStatus = state.status !== "排队";
|
||||
return (
|
||||
<div className={`fnode kind-decision s-${state.status}`} data-node="judge">
|
||||
<button
|
||||
type="button"
|
||||
className="diamond"
|
||||
title="介绍:标品判断"
|
||||
aria-label="介绍:标品判断"
|
||||
onClick={() => onIntro("judge")}
|
||||
>
|
||||
<div className="diamond-in">
|
||||
<span className="diamond-label">标品判断</span>
|
||||
<span className={state.metric ? "fnode-metric" : "fnode-metric muted"}>
|
||||
{state.metric ?? "待判定"}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
<div className="decision-status">
|
||||
{showStatus ? <span className="fnode-status">{state.status}</span> : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function OrchestrationCanvas(props: {
|
||||
nodes: Record<NodeId, NodeState>;
|
||||
floats: Partial<Record<NodeId, FloatCard>>;
|
||||
floatFocus: NodeId | null;
|
||||
scenario: Scenario | null;
|
||||
ratingRevealed: number;
|
||||
}) {
|
||||
const { nodes, floats, floatFocus, scenario, ratingRevealed } = props;
|
||||
const canvasRef = useRef<HTMLDivElement>(null);
|
||||
const stageRefs = useRef<Partial<Record<string, HTMLDivElement | null>>>({});
|
||||
const [bypass, setBypass] = useState<BypassGeom | null>(null);
|
||||
const [mode, setMode] = useState<Partial<Record<NodeId, "open" | "closed">>>({});
|
||||
const [bomOpen, setBomOpen] = useState(false);
|
||||
const [rndDetail, setRndDetail] = useState<"cycle" | "invest" | null>(null);
|
||||
const [ratingDetail, setRatingDetail] = useState<"margin" | null>(null);
|
||||
const [panels, setPanels] = useState({ margin: false, credit: false });
|
||||
const [intro, setIntro] = useState<NodeId | null>(null);
|
||||
const toggleIntro = (id: NodeId) => setIntro((p) => (p === id ? null : id));
|
||||
const allIds: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
|
||||
|
||||
const isFull = (id: NodeId) => {
|
||||
if (!floats[id]) return false;
|
||||
if (mode[id] === "open") return true;
|
||||
if (mode[id] === "closed") return false;
|
||||
const st = nodes[id].status;
|
||||
return id === floatFocus || (st !== "排队" && st !== "跳过");
|
||||
};
|
||||
const spread = allIds.some((id) => floats[id] && isFull(id));
|
||||
const started = allIds.some((id) => nodes[id].status !== "排队");
|
||||
const active =
|
||||
spread || intro !== null || allIds.some((id) => nodes[id].status !== "排队");
|
||||
|
||||
const measure = () => {
|
||||
const j = stageRefs.current.judge;
|
||||
const p = stageRefs.current.parallel;
|
||||
if (!j || !p) return;
|
||||
const jc = j.offsetLeft + j.offsetWidth / 2;
|
||||
const pc = p.offsetLeft + p.offsetWidth / 2;
|
||||
const next = {
|
||||
left: jc,
|
||||
width: Math.max(0, pc - jc),
|
||||
leftDrop: Math.max(0, j.offsetTop - 18),
|
||||
rightDrop: Math.max(0, p.offsetTop - 18),
|
||||
};
|
||||
setBypass((prev) =>
|
||||
prev &&
|
||||
prev.left === next.left &&
|
||||
prev.width === next.width &&
|
||||
prev.leftDrop === next.leftDrop &&
|
||||
prev.rightDrop === next.rightDrop
|
||||
? prev
|
||||
: next,
|
||||
);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
measure();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const onResize = () => measure();
|
||||
window.addEventListener("resize", onResize);
|
||||
return () => window.removeEventListener("resize", onResize);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const ORDER: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
|
||||
const active =
|
||||
ORDER.find((id) => nodes[id].status === "执行中" || nodes[id].status === "等待填报") ??
|
||||
[...ORDER]
|
||||
.reverse()
|
||||
.find((id) =>
|
||||
["已完成", "不通过", "待补全"].includes(nodes[id].status),
|
||||
);
|
||||
const stageKey = (id: NodeId) => (id === "delivery" || id === "rating" ? "parallel" : id);
|
||||
const el = active ? stageRefs.current[stageKey(active)] : null;
|
||||
const canvas = canvasRef.current;
|
||||
if (!el || !canvas) return;
|
||||
if (canvas.scrollWidth <= canvas.clientWidth + 4) {
|
||||
if (canvas.scrollLeft !== 0) canvas.scrollTo({ left: 0, behavior: "smooth" });
|
||||
return;
|
||||
}
|
||||
el.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
|
||||
}, [nodes]);
|
||||
|
||||
const renderStage = (key: string, inner: ReactNode, floatIds: NodeId[]) => {
|
||||
const chips = floatIds.filter((id) => floats[id] && !isFull(id));
|
||||
const fulls = floatIds.filter((id) => floats[id] && isFull(id));
|
||||
const introId = floatIds.find((id) => id === intro);
|
||||
const introData = introId ? agentIntros[introId] : null;
|
||||
return (
|
||||
<div
|
||||
className="stage"
|
||||
key={key}
|
||||
ref={(el) => {
|
||||
stageRefs.current[key] = el;
|
||||
}}
|
||||
>
|
||||
{inner}
|
||||
<div className="chips">
|
||||
{chips.map((id) => (
|
||||
<button
|
||||
key={id}
|
||||
type="button"
|
||||
className="chip-f"
|
||||
title="展开依据卡"
|
||||
onClick={() => setMode((p) => ({ ...p, [id]: "open" }))}
|
||||
>
|
||||
{floats[id]?.title}
|
||||
{floats[id]?.verdict ? ` · ${floats[id]?.verdict}` : ""}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{introData || fulls.length > 0 ? (
|
||||
<div
|
||||
className={`floats-col ${key === "parse" ? "align-left" : key === "summary" ? "align-right" : ""} ${fulls.includes("rating") || fulls.includes("delivery") ? "wide" : fulls.includes("rnd") ? "mid" : ""}`}
|
||||
>
|
||||
{introData ? (
|
||||
<div className="float tone-info" role="dialog" aria-label={`${introData.title} 介绍`}>
|
||||
<div className="float-head">
|
||||
<span>{introData.title}</span>
|
||||
<span className="float-verdict">介绍</span>
|
||||
</div>
|
||||
<p className="intro-desc">{introData.desc}</p>
|
||||
<ul className="intro-points">
|
||||
{introData.points.map((p, i) => (
|
||||
<li key={i}>{p}</li>
|
||||
))}
|
||||
</ul>
|
||||
<button type="button" className="chip-f float-close" onClick={() => setIntro(null)}>
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{fulls.map((id) => {
|
||||
const f = floats[id];
|
||||
if (!f) return null;
|
||||
return (
|
||||
<div className={`float tone-${f.tone}`} key={id} role="status">
|
||||
<div className="float-head">
|
||||
<span>{f.title}</span>
|
||||
{f.verdict ? <span className="float-verdict">{f.verdict}</span> : null}
|
||||
</div>
|
||||
{id === "rating" && scenario ? (
|
||||
<RatingScorePanels
|
||||
scenario={scenario}
|
||||
marginOpen={panels.margin}
|
||||
creditOpen={panels.credit}
|
||||
onToggleMargin={() => setPanels((p) => ({ ...p, margin: !p.margin }))}
|
||||
onToggleCredit={() => setPanels((p) => ({ ...p, credit: !p.credit }))}
|
||||
onMarginClick={() => setRatingDetail("margin")}
|
||||
revealed={ratingRevealed}
|
||||
/>
|
||||
) : id === "rnd" && scenario && (f.links ?? []).includes("cycle") ? (
|
||||
<>
|
||||
<table className="bom-table float-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>评审项</th>
|
||||
<th>标准</th>
|
||||
<th>实际</th>
|
||||
<th>判定</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{scenario.rnd.items.map((i) => (
|
||||
<tr key={i.label}>
|
||||
<td>{i.label}</td>
|
||||
<td>{i.standard}</td>
|
||||
<td>
|
||||
{i.label === "毛利率" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="link-btn inline-link"
|
||||
title="查看订单毛利计算逻辑"
|
||||
onClick={() => setRatingDetail("margin")}
|
||||
>
|
||||
{i.actual}
|
||||
</button>
|
||||
) : (
|
||||
i.actual
|
||||
)}
|
||||
</td>
|
||||
<td className={i.pass ? "pass-cell" : "fail-cell"}>{i.pass ? "通过" : "不通过"}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{f.note ? <p className="float-note">{f.note}</p> : null}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<EvidenceTable rows={f.rows} />
|
||||
{f.note ? <p className="float-note">{f.note}</p> : null}
|
||||
</>
|
||||
)}
|
||||
{(f.links ?? []).length > 0 ? (
|
||||
<div className="link-row">
|
||||
{(f.links ?? []).map((lk) => (
|
||||
<button
|
||||
key={lk}
|
||||
type="button"
|
||||
className="link-btn"
|
||||
onClick={() => {
|
||||
if (lk === "bom") setBomOpen(true);
|
||||
else setRndDetail(lk);
|
||||
}}
|
||||
>
|
||||
{LINK_LABELS[lk]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
<button
|
||||
type="button"
|
||||
className="chip-f float-close"
|
||||
onClick={() => setMode((p) => ({ ...p, [id]: "closed" }))}
|
||||
>
|
||||
收起
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="canvas-panel" aria-label="智能体编排与执行流程">
|
||||
<div className="panel-head">
|
||||
<h2>智能体编排与执行流程</h2>
|
||||
<div className="legend" aria-hidden>
|
||||
<span><i className="lg lg-run" />执行中</span>
|
||||
<span><i className="lg lg-wait" />等待填报</span>
|
||||
<span><i className="lg lg-todo" />待补全</span>
|
||||
<span><i className="lg lg-ok" />已完成</span>
|
||||
<span><i className="lg lg-fail" />不通过</span>
|
||||
<span><i className="lg lg-skip" />跳过</span>
|
||||
<span><i className="lg lg-agent" />智能体节点</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="canvas" ref={canvasRef}>
|
||||
<div
|
||||
className="flow"
|
||||
data-spread={spread ? "true" : "false"}
|
||||
data-active={active ? "true" : "false"}
|
||||
data-wide={
|
||||
(floats.rating && isFull("rating")) ||
|
||||
(floats.rnd && isFull("rnd")) ||
|
||||
(floats.delivery && isFull("delivery"))
|
||||
? "true"
|
||||
: "false"
|
||||
}
|
||||
>
|
||||
{bypass ? (
|
||||
<div className="bypass-h" style={{ left: bypass.left, width: bypass.width }} aria-hidden>
|
||||
<i className="stub stub-l" style={{ height: bypass.leftDrop }} />
|
||||
<i className="stub stub-r" style={{ height: bypass.rightDrop }} />
|
||||
<span>标品:跳过研发评审</span>
|
||||
</div>
|
||||
) : null}
|
||||
{renderStage("parse", <NodeCard id="parse" kind="control" label="需求解析" note="总控" state={nodes.parse} onIntro={toggleIntro} started={started} />, ["parse"])}
|
||||
<div className="conn-h" aria-hidden />
|
||||
{renderStage("feasibility", <NodeCard id="feasibility" label="可行性智能体" state={nodes.feasibility} onIntro={toggleIntro} started={started} />, ["feasibility"])}
|
||||
<div className="conn-h" aria-hidden />
|
||||
{renderStage("judge", <DecisionNode state={nodes.judge} onIntro={toggleIntro} />, ["judge"])}
|
||||
<div className="conn-h" aria-hidden>
|
||||
<span>非标</span>
|
||||
</div>
|
||||
{renderStage("rnd", <NodeCard id="rnd" label="新品研发评估" note="仅非标进入" state={nodes.rnd} onIntro={toggleIntro} started={started} />, ["rnd"])}
|
||||
<div className="conn-h" aria-hidden />
|
||||
{renderStage(
|
||||
"parallel",
|
||||
<div
|
||||
className={`pgroup ${nodes.delivery.status !== "排队" || nodes.rating.status !== "排队" ? "pg-active" : ""}`}
|
||||
>
|
||||
<span className="pgroup-badge">∥ 并行评审</span>
|
||||
<NodeCard id="delivery" label="交期评审" state={nodes.delivery} onIntro={toggleIntro} started={started} />
|
||||
<NodeCard id="rating" label="客户评级" state={nodes.rating} onIntro={toggleIntro} started={started} />
|
||||
</div>,
|
||||
["delivery", "rating"],
|
||||
)}
|
||||
<div className="conn-h" aria-hidden />
|
||||
{renderStage("summary", <NodeCard id="summary" kind="control" label="汇总·订单" note="总控" state={nodes.summary} onIntro={toggleIntro} started={started} />, ["summary"])}
|
||||
</div>
|
||||
</div>
|
||||
<BomModal open={bomOpen} onClose={() => setBomOpen(false)} />
|
||||
<RndDetailModal section={rndDetail} scenario={scenario} onClose={() => setRndDetail(null)} />
|
||||
<RatingDetailModal section={ratingDetail} scenario={scenario} onClose={() => setRatingDetail(null)} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { useEffect } from "react";
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
import { MarginCalcTable } from "./MarginCalcTable";
|
||||
|
||||
/** 评级明细弹窗:毛利达标四级链复算 / 信用达标数据拆解 */
|
||||
export function RatingDetailModal(props: { section: "margin" | null; scenario: Scenario | null; onClose: () => void }) {
|
||||
const { section, scenario, onClose } = props;
|
||||
useEffect(() => {
|
||||
if (!section) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [section, onClose]);
|
||||
if (!section || !scenario) return null;
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose} role="presentation">
|
||||
<div
|
||||
className="modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label="订单毛利计算逻辑"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<span>订单毛利计算逻辑</span>
|
||||
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<MarginCalcTable scenario={scenario} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
import { pct, wan } from "../engine/format";
|
||||
|
||||
/** 信用达标拆解表(面板展开内容) */
|
||||
function CreditBreakdownTable({ scenario }: { scenario: Scenario }) {
|
||||
const cb = scenario.rating.creditBreakdown;
|
||||
return (
|
||||
<table className="bom-table float-table">
|
||||
<tbody>
|
||||
{cb.items.map((it, i) => (
|
||||
<tr key={it.label}>
|
||||
<td>{it.label}</td>
|
||||
<td>{i === 0 ? wan(it.amount) : `− ${wan(it.amount)}`}</td>
|
||||
<td>{it.source}</td>
|
||||
</tr>
|
||||
))}
|
||||
<tr>
|
||||
<td>信用可用余额</td>
|
||||
<td>{wan(cb.available)}</td>
|
||||
<td>{cb.pass ? "> 0 → 达标" : "≤ 0 → 不达标"}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
}
|
||||
|
||||
/** 客户评级记分卡:毛利达标 / 信用达标为可展开面板(默认收起),其余记分项直接显示 */
|
||||
export function RatingScorePanels(props: {
|
||||
scenario: Scenario;
|
||||
marginOpen: boolean;
|
||||
creditOpen: boolean;
|
||||
onToggleMargin: () => void;
|
||||
onToggleCredit: () => void;
|
||||
onMarginClick: () => void;
|
||||
revealed: number;
|
||||
}) {
|
||||
const { scenario, marginOpen, creditOpen, onToggleMargin, onToggleCredit, onMarginClick, revealed } = props;
|
||||
const r = scenario.rating;
|
||||
const walked = r.marginChain.filter((c) => c.walked);
|
||||
const hit = walked.find((c) => c.pass);
|
||||
const marginItem = r.items[0];
|
||||
const creditItem = r.items[1];
|
||||
const THRESH = [1, 2, 4, 3];
|
||||
const shown = (i: number) => revealed >= THRESH[i];
|
||||
return (
|
||||
<div className="score-panels">
|
||||
<div className="score-panel">
|
||||
<button type="button" className="score-panel-head" aria-expanded={marginOpen} onClick={onToggleMargin}>
|
||||
<span className="sp-label">{marginItem.label}({marginItem.weight} 分)</span>
|
||||
<span className="sp-value">
|
||||
{shown(0)
|
||||
? `本单毛利 ${pct(scenario.margin.grossMarginRate)}${hit && walked.length > 1 ? ` · 经 ${hit.step} 达标` : ""}`
|
||||
: "计算中…"}
|
||||
</span>
|
||||
{shown(0) ? (
|
||||
<span className={marginItem.pass ? "pass-cell" : "fail-cell"}>
|
||||
{marginItem.pass ? "通过" : "不通过"} · {marginItem.score} 分
|
||||
</span>
|
||||
) : (
|
||||
<span className="sp-muted">—</span>
|
||||
)}
|
||||
<span className="sp-caret" aria-hidden>{marginOpen ? "▲" : "▼"}</span>
|
||||
</button>
|
||||
{marginOpen ? (
|
||||
<div className="score-panel-body">
|
||||
<table className="bom-table float-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>层级</th>
|
||||
<th>复算</th>
|
||||
<th>对比行业指标 {walked[0] ? pct(walked[0].target) : ""}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{walked.map((c) => (
|
||||
<tr key={c.step}>
|
||||
<td>{c.step} {c.label}</td>
|
||||
<td>
|
||||
{c.step === "①" ? (
|
||||
<button type="button" className="link-btn inline-link" onClick={onMarginClick} title="查看订单毛利计算逻辑">
|
||||
{pct(c.value)}
|
||||
</button>
|
||||
) : (
|
||||
pct(c.value)
|
||||
)}
|
||||
</td>
|
||||
<td className={c.pass ? "pass-cell" : "fail-cell"}>
|
||||
{pct(c.value)} {c.pass ? "≥" : "<"} {pct(c.target)} → {c.pass ? "达标" : "不达标"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="score-panel">
|
||||
<button type="button" className="score-panel-head" aria-expanded={creditOpen} onClick={onToggleCredit}>
|
||||
<span className="sp-label">{creditItem.label}({creditItem.weight} 分)</span>
|
||||
<span className="sp-value">
|
||||
{shown(1)
|
||||
? `可用余额 ${wan(r.creditBreakdown.available)} 万 ${r.creditBreakdown.pass ? "> 0" : "≤ 0"}`
|
||||
: "计算中…"}
|
||||
</span>
|
||||
{shown(1) ? (
|
||||
<span className={creditItem.pass ? "pass-cell" : "fail-cell"}>
|
||||
{creditItem.pass ? "通过" : "不通过"} · {creditItem.score} 分
|
||||
</span>
|
||||
) : (
|
||||
<span className="sp-muted">—</span>
|
||||
)}
|
||||
<span className="sp-caret" aria-hidden>{creditOpen ? "▲" : "▼"}</span>
|
||||
</button>
|
||||
{creditOpen ? (
|
||||
<div className="score-panel-body">
|
||||
<CreditBreakdownTable scenario={scenario} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<table className="ev">
|
||||
<tbody>
|
||||
{r.items.slice(2).map((i, idx) => (
|
||||
<tr key={i.label}>
|
||||
<td className="ev-label">{i.label}({i.weight} 分)</td>
|
||||
<td className="ev-value">{shown(idx + 2) ? i.basis : "计算中…"}</td>
|
||||
{shown(idx + 2) ? (
|
||||
<td className={i.pass ? "ev-v pass" : "ev-v fail"}>{i.pass ? "通过" : "不通过"} · {i.score} 分</td>
|
||||
) : (
|
||||
<td className="ev-v sp-muted">—</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{revealed >= 4 ? (
|
||||
<p className="float-note">合计 {r.total} 分 · {r.pass ? "≥90 合格" : "<90 不合格"}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { ChangeEvent, FormEvent } from "react";
|
||||
import type { ReviewRunner } from "../state/useReviewRunner";
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
import type { ChatMsg, Todo } from "../state/types";
|
||||
import { wan, yuan } from "../engine/format";
|
||||
import { EvidenceTable } from "./EvidenceTable";
|
||||
|
||||
interface ChatCardViewProps {
|
||||
msg: ChatMsg;
|
||||
scenario: Scenario | null;
|
||||
report: { fileName: string; html: string } | null;
|
||||
onOpenReport: () => void;
|
||||
}
|
||||
|
||||
function ChatCardView({ msg, scenario, report, onOpenReport }: ChatCardViewProps) {
|
||||
if (msg.card.kind === "text") {
|
||||
return <div className={msg.role === "user" ? "bubble user" : "bubble master"}>{msg.card.text}</div>;
|
||||
}
|
||||
if (!scenario) return null;
|
||||
if (msg.card.kind === "summary") {
|
||||
const s = scenario.summary;
|
||||
return (
|
||||
<div className="card master-card">
|
||||
<div className="card-head">
|
||||
<span>汇总结论</span>
|
||||
<span className={s.order ? "badge badge-ok" : "badge badge-fail"}>{s.overall}</span>
|
||||
</div>
|
||||
<EvidenceTable rows={s.rows.map((r) => ({ label: r.agent, value: `${r.conclusion} · ${r.keyEvidence}` }))} />
|
||||
{s.suggestions.length > 0 ? (
|
||||
<ul className="card-list">
|
||||
{s.suggestions.map((t, i) => (
|
||||
<li key={i}>{t}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (msg.card.kind === "order") {
|
||||
const o = scenario.summary.order;
|
||||
if (!o) return null;
|
||||
return (
|
||||
<div className="card master-card">
|
||||
<div className="card-head">
|
||||
<span>订单已生成</span>
|
||||
<span className="badge badge-ok">{o.orderNo}</span>
|
||||
</div>
|
||||
<EvidenceTable
|
||||
rows={[
|
||||
{ label: "品项", value: o.itemSummary },
|
||||
{ label: "金额", value: `${yuan(o.amount)} 元(${wan(o.amount)} 万)` },
|
||||
{ label: "交期", value: o.deliveryDate },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (msg.card.kind === "suggest") {
|
||||
const g = scenario.summary.creditGap;
|
||||
return (
|
||||
<div className="card master-card tone-fail">
|
||||
<div className="card-head">
|
||||
<span>评审不通过 · 处理建议</span>
|
||||
<span className="badge badge-fail">信用达标 0 分</span>
|
||||
</div>
|
||||
{g ? (
|
||||
<EvidenceTable
|
||||
rows={[
|
||||
{ label: "精确缺口", value: `${wan(g.gap)} 万` },
|
||||
{ label: "建议动作", value: `发起客户临时授信 ≥ ${wan(g.suggested)} 万(含缓冲)` },
|
||||
{ label: "处理路径", value: g.path },
|
||||
]}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (msg.card.kind === "report") {
|
||||
return (
|
||||
<div className="card master-card">
|
||||
<div className="card-head">
|
||||
<span>需求评估报告已生成</span>
|
||||
<span className="badge badge-ok">网页</span>
|
||||
</div>
|
||||
<p className="todo-prompt">{msg.card.fileName}</p>
|
||||
<div className="todo-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={onOpenReport} disabled={!report}>
|
||||
打开报告
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <div className="bubble master">临时授信流程已发起:授信审批 → 评级复跑 → 重新汇总。</div>;
|
||||
}
|
||||
|
||||
function TodoCard({ todo, onResolve }: { todo: Todo; onResolve: (v: string | null) => void }) {
|
||||
if (todo.kind === "followup") {
|
||||
return (
|
||||
<div className="card todo-card">
|
||||
<div className="card-head">
|
||||
<span>待办 · 补全追问</span>
|
||||
<span className="badge badge-wait">等待响应</span>
|
||||
</div>
|
||||
<p className="todo-prompt">{todo.prompt}</p>
|
||||
<div className="todo-actions">
|
||||
{todo.options.map((o) => (
|
||||
<button key={o} type="button" className="btn btn-opt" onClick={() => onResolve(o)}>
|
||||
{o}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (todo.kind === "confirm") {
|
||||
return (
|
||||
<div className="card todo-card">
|
||||
<div className="card-head">
|
||||
<span>待办 · 确认评审结论</span>
|
||||
<span className="badge badge-ok">评审通过</span>
|
||||
</div>
|
||||
<p className="todo-prompt">三个智能体结论齐备且依据透明,是否发起订单生成?</p>
|
||||
<div className="todo-actions">
|
||||
<button type="button" className="btn btn-primary" onClick={() => onResolve(null)}>
|
||||
确认并发起订单
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (todo.kind === "next") {
|
||||
return (
|
||||
<div className="card todo-card">
|
||||
<div className="card-head">
|
||||
<span>待办 · 下一步</span>
|
||||
<span className="badge badge-ok">评审收尾</span>
|
||||
</div>
|
||||
<p className="todo-prompt">本次评审已收尾并生成报告,接下来:</p>
|
||||
<div className="todo-actions">
|
||||
{todo.allowCreditRerun ? (
|
||||
<button type="button" className="btn btn-primary" onClick={() => onResolve("credit-approved")}>
|
||||
模拟授信审批通过 · 复跑评级
|
||||
</button>
|
||||
) : null}
|
||||
<button type="button" className="btn btn-opt" onClick={() => onResolve("new-review")}>
|
||||
发起新评审
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="card todo-card tone-fail">
|
||||
<div className="card-head">
|
||||
<span>待办 · 异常处理</span>
|
||||
<span className="badge badge-fail">评级不通过</span>
|
||||
</div>
|
||||
<p className="todo-prompt">信用项不达标,是否发起客户临时授信?</p>
|
||||
<div className="todo-actions">
|
||||
<button type="button" className="btn btn-danger" onClick={() => onResolve(null)}>
|
||||
发起临时授信
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RightPanel({ runner }: { runner: ReviewRunner }) {
|
||||
const { demand, scenario, chat, todo, running } = runner;
|
||||
const [text, setText] = useState("");
|
||||
const chatRef = useRef<HTMLDivElement>(null);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
chatRef.current?.scrollTo({ top: chatRef.current.scrollHeight });
|
||||
}, [chat.length, todo]);
|
||||
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
runner.sendText(text);
|
||||
setText("");
|
||||
};
|
||||
|
||||
const onFile = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
e.target.value = "";
|
||||
if (file) void runner.uploadFile(file);
|
||||
};
|
||||
|
||||
const openReport = () => {
|
||||
const r = runner.report;
|
||||
if (!r) return;
|
||||
const url = URL.createObjectURL(new Blob([r.html], { type: "text/html;charset=utf-8" }));
|
||||
window.open(url, "_blank");
|
||||
setTimeout(() => URL.revokeObjectURL(url), 60_000);
|
||||
};
|
||||
|
||||
return (
|
||||
<aside className="right" aria-label="需求评审">
|
||||
<div className="panel-head">
|
||||
<h2>需求评审</h2>
|
||||
</div>
|
||||
{demand ? (
|
||||
<div className="demand-card">
|
||||
<div className="card-head">
|
||||
<span>当前需求卡</span>
|
||||
<span className={demand.missingFields.length === 0 ? "badge badge-ok" : "badge badge-wait"}>
|
||||
{demand.missingFields.length > 0 ? "待补全" : "检查通过"}
|
||||
</span>
|
||||
</div>
|
||||
<dl className="kv-grid">
|
||||
<dt>客户</dt><dd>{demand.customerCode}</dd>
|
||||
<dt>行业</dt><dd>{demand.parsed.industry ?? "缺失"}</dd>
|
||||
<dt>产品类型</dt><dd>{demand.parsed.productType}</dd>
|
||||
<dt>数量 / 单价</dt><dd>{demand.parsed.quantity} 个 / {yuan(demand.parsed.unitPrice)} 元</dd>
|
||||
<dt>交期</dt><dd>{demand.parsed.deliveryDate}</dd>
|
||||
<dt>钢卷材质</dt><dd>{demand.parsed.coilMaterial}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
) : (
|
||||
<div className="demand-card demand-empty">
|
||||
{running ? (
|
||||
<>
|
||||
<strong>正在解析需求文档…</strong>
|
||||
<span>提取字段并做完整性检查,完成后在此显示需求卡</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<strong>尚未载入客户需求</strong>
|
||||
<span>上传 Word / 文本需求文档开始评审</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="chat" ref={chatRef} aria-live="polite">
|
||||
{chat.length === 0 ? (
|
||||
<p className="chat-empty">上传需求文档或输入客户需求,主智能体将在此给出解析、追问、汇总与订单等关键反馈。</p>
|
||||
) : (
|
||||
chat.map((m) => (
|
||||
<ChatCardView key={m.id} msg={m} scenario={scenario} report={runner.report} onOpenReport={openReport} />
|
||||
))
|
||||
)}
|
||||
{todo ? <TodoCard todo={todo} onResolve={runner.resolveTodo} /> : null}
|
||||
</div>
|
||||
<form className="composer" onSubmit={submit}>
|
||||
<input ref={fileRef} type="file" accept=".docx,.txt,.doc,.pdf" hidden onChange={onFile} />
|
||||
<button
|
||||
type="button"
|
||||
className="icon-btn"
|
||||
aria-label="上传需求文档并启动评审"
|
||||
onClick={() => fileRef.current?.click()}
|
||||
disabled={running}
|
||||
>
|
||||
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
|
||||
<path d="M12 16V4m0 0 4 4m-4-4-4 4" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" strokeLinecap="round" />
|
||||
</svg>
|
||||
</button>
|
||||
<input
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="输入客户需求,或点击左侧图标上传需求文档…"
|
||||
aria-label="输入客户需求"
|
||||
/>
|
||||
<button type="submit" className="btn btn-primary" disabled={!text.trim()}>
|
||||
发送
|
||||
</button>
|
||||
</form>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useEffect } from "react";
|
||||
import type { Scenario } from "../mock/scenarios";
|
||||
import { RND_INVEST_ITEMS, RND_INVEST_TOTAL } from "../engine/filing";
|
||||
import { yuan } from "../engine/format";
|
||||
|
||||
/** 研发评审详细弹窗:周期拆解 / 投资与回收期复算(按场景动态推导) */
|
||||
export function RndDetailModal(props: {
|
||||
section: "cycle" | "invest" | null;
|
||||
scenario: Scenario | null;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const { section, scenario, onClose } = props;
|
||||
useEffect(() => {
|
||||
if (!section) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onClose();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [section, onClose]);
|
||||
if (!section || !scenario) return null;
|
||||
const f = scenario.filing;
|
||||
return (
|
||||
<div className="modal-backdrop" onClick={onClose} role="presentation">
|
||||
<div
|
||||
className="modal"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={section === "cycle" ? "周期详细" : "投资详细"}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div className="modal-head">
|
||||
<span>{section === "cycle" ? "周期详细 · 模具 / 项目周期拆解" : "投资详细 · 投资回收期复算"}</span>
|
||||
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
{section === "cycle" ? (
|
||||
<>
|
||||
<h4 className="detail-title">模具周期 · 标准 ≤3 天 · 实际 {f.values[0]}</h4>
|
||||
<table className="bom-table">
|
||||
<thead>
|
||||
<tr><th>阶段</th><th>天数</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{f.moldSteps.map((s) => (
|
||||
<tr key={s.name}><td>{s.name}</td><td>{s.days} 天</td></tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
<h4 className="detail-title">项目周期 · 标准 ≤10 天 · 实际 {f.values[1]}</h4>
|
||||
<table className="bom-table">
|
||||
<thead>
|
||||
<tr><th>阶段</th><th>天数</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{f.projectSteps.map((s) => (
|
||||
<tr key={s.name}><td>{s.name}</td><td>{s.days} 天</td></tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<h4 className="detail-title">投入构成 · 合计 {yuan(RND_INVEST_TOTAL)} 元</h4>
|
||||
<table className="bom-table">
|
||||
<thead>
|
||||
<tr><th>项目</th><th>金额(元)</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{RND_INVEST_ITEMS.map((s) => (
|
||||
<tr key={s.name}><td>{s.name}</td><td>{yuan(s.amount)}</td></tr>
|
||||
))}
|
||||
<tr><td>合计</td><td>{yuan(RND_INVEST_TOTAL)}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<h4 className="detail-title">回收期复算 · 标准 ≤1 年 · 实际 {f.paybackLabel}</h4>
|
||||
<table className="bom-table">
|
||||
<tbody>
|
||||
<tr><td>本单毛利</td><td>{yuan(scenario.margin.grossProfit)} 元</td></tr>
|
||||
<tr><td>复算口径</td><td>{f.investCalc}</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { scenarios } from "../mock/scenarios";
|
||||
import { yuan, wan } from "../engine/format";
|
||||
|
||||
/** 数据自检页(?check=1):核对 mock 复算关键数字 */
|
||||
export function SelfCheck() {
|
||||
return (
|
||||
<div className="checkpage">
|
||||
<h1>订单需求评审智能体 · Mock 数据自检</h1>
|
||||
<p className="sub">数据字典对齐规格第 5 章;关键数字由规则引擎实时复算。</p>
|
||||
{scenarios.map((s) => (
|
||||
<section key={s.demand.id}>
|
||||
<h2>需求 {s.demand.id} · {s.demand.label}</h2>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr><th>当期需求金额</th><td className="num">{yuan(s.margin.revenue)} 元({wan(s.margin.revenue)} 万)</td></tr>
|
||||
<tr><th>可行性判定</th><td>{s.feasibility.category}({s.feasibility.routeLabel})</td></tr>
|
||||
<tr><th>单台钢卷成本</th><td className="num">{yuan(s.coilCostPerUnit)} 元</td></tr>
|
||||
<tr><th>毛利率</th><td className="num">{(s.margin.grossMarginRate * 100).toFixed(0)}%</td></tr>
|
||||
<tr><th>研发评审</th><td className={s.rnd.pass ? "pass" : "fail"}>{s.rnd.pass ? "通过" : "不通过"}</td></tr>
|
||||
<tr><th>客户评级记分</th><td className={s.rating.pass ? "pass" : "fail"}>{s.rating.total} 分</td></tr>
|
||||
<tr><th>主智能体结论</th><td>{s.summary.overall}{s.summary.order ? ` · ${s.summary.order.orderNo}` : ""}</td></tr>
|
||||
{s.creditGap ? (
|
||||
<tr><th>临时授信建议</th><td className="num">缺口 {wan(s.creditGap.gap)} 万 · 建议 ≥ {wan(s.creditGap.suggested)} 万</td></tr>
|
||||
) : null}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/&/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: "上传文档解析",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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],
|
||||
};
|
||||
}
|
||||
@@ -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)}%`;
|
||||
}
|
||||
@@ -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, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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: "授信审批 → 评级复跑 → 重新汇总" };
|
||||
}
|
||||
@@ -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 };
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ModuleConfig } from '../registry';
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'baode-web',
|
||||
name: '需求评审多智能体',
|
||||
description: '江苏宝得需求评审 Cockpit:多智能体编排评审、毛利测算、研发加计与负荷校验',
|
||||
icon: 'ClipboardCheck',
|
||||
path: '/baode-web',
|
||||
accentColor: '#2563eb',
|
||||
accentColorLight: '#1d4ed8',
|
||||
gradient: 'linear-gradient(135deg, #0c1a3a, #16307a, #1d4ed8)',
|
||||
gradientLight: 'linear-gradient(135deg, #eef4ff, #dce8ff, #c8dcff)',
|
||||
tags: ['需求评审', '多智能体', '规则引擎'],
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { NodeId } from "../state/types";
|
||||
|
||||
/** 演示讲解用:每个节点的功能介绍(点击节点 icon 弹出) */
|
||||
export interface AgentIntro {
|
||||
title: string;
|
||||
desc: string;
|
||||
points: string[];
|
||||
}
|
||||
|
||||
export const agentIntros: Record<NodeId, AgentIntro> = {
|
||||
parse: {
|
||||
title: "总控 · 需求解析",
|
||||
desc: "主智能体:多模态解析上传的 Word / 文本需求文档,结构化关键字段,缺关键信息主动追问。",
|
||||
points: ["解析字段:客户 / 行业 / 产品类型 / 数量 / 单价 / 交期 / 钢卷材质", "完整性检查,缺失字段生成追问卡,补全后刷新需求卡"],
|
||||
},
|
||||
feasibility: {
|
||||
title: "可行性智能体",
|
||||
desc: "规则引擎自动判定标品 / 非标品,规则命中过程透明可见。",
|
||||
points: ["R-可行-1:类型含「可拆」或「钎焊式」→ 标品", "R-可行-2:否则 → 非标品,路由至新品研发评审"],
|
||||
},
|
||||
judge: {
|
||||
title: "标品判断(if 决策)",
|
||||
desc: "编排决策节点:按可行性判定结果路由到不同评审路径。",
|
||||
points: ["非标 → 实线进入新品研发评审", "标品 → 虚线跳过研发,直达并行评审"],
|
||||
},
|
||||
rnd: {
|
||||
title: "新品研发评审智能体",
|
||||
desc: "非标专属:多层 BOM 展开至钢卷层并复算毛利;模具 / 项目 / 财务三人协同填报。",
|
||||
points: ["评审表:毛利率 ≥30%、模具 ≤3 天、项目 ≤10 天、回收期 ≤1 年", "BOM 展开 + 单台钢卷成本 4,760 元复算闭环"],
|
||||
},
|
||||
delivery: {
|
||||
title: "交期评审智能体",
|
||||
desc: "三维度评审交期可行性,与客户评级并行执行。",
|
||||
points: ["产能负荷 78%,可吸收增量", "采购 5 天 + 生产 7 天 ≤ 距交期天数", "提示:316L 钢卷建议立即发起采购"],
|
||||
},
|
||||
rating: {
|
||||
title: "客户评级智能体",
|
||||
desc: "记分卡评级,与交期评审并行执行;不通过时给出处理路径。",
|
||||
points: ["毛利达标 20 + 信用达标 60 + 超额利润 10 + 对账 10,≥90 合格", "信用 = 额度 − 库存未提 − 取消订单 − 当期需求", "不通过 → 建议临时授信并测算缺口"],
|
||||
},
|
||||
summary: {
|
||||
title: "总控 · 汇总·订单",
|
||||
desc: "主智能体汇总三个智能体结论与依据;通过后一键生成订单,不通过输出处理建议。",
|
||||
points: ["评审通过 → 订单 SO-2610-0001", "评级不通过 → 临时授信建议 + 精确缺口"],
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { BomLine, SteelCoil } from "../types";
|
||||
|
||||
/** 规格 5.3 主件表头 + 客户 ERP 截图(维护BOM信息画面,版本 6.3.0.0.50.14) */
|
||||
export const productMaster = {
|
||||
itemCode: "310250000339",
|
||||
itemName: "BL95A-58",
|
||||
spec: "S31603-(R520-D1-D2, H2116-B3, H4152-D4)",
|
||||
makeType: "自制件",
|
||||
unit: "PCS",
|
||||
plant: "江苏宝得",
|
||||
refPlant: "江苏宝得",
|
||||
drawingNo: "I-BL95A-000370",
|
||||
bomDate: "2026-10-16",
|
||||
revision: "0000",
|
||||
standardLot: 1,
|
||||
expandMode: "多阶",
|
||||
expandStages: 20,
|
||||
bomStatusFilter: "全部",
|
||||
erpScreen: "维护BOM信息",
|
||||
erpVersion: "6.3.0.0.50.14",
|
||||
treeRoot: "310250000339[BL95A-58]-StandardBom",
|
||||
provenance: "规格 5.3 + ERP 截图",
|
||||
};
|
||||
|
||||
/**
|
||||
* BOM 用量信息(一层 14 行 + 下展层)。
|
||||
* 单价/总价取自客户 ERP 截图原值,仅做展示,不参与金额复算;
|
||||
* 金额复算口径统一走 steelCoils 汇总(规格 5.3 / 5.7)。
|
||||
*/
|
||||
export const bomLines: BomLine[] = [
|
||||
{ seq: 10, itemCode: "2020020184", itemName: "外螺纹接管", spec: "304-R520-3.1", qtyPerUnit: 2, unitPrice: 17.1, totalPrice: 34.19, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 20, itemCode: "2020010083", itemName: "焊接管", spec: "304-H2116 系", qtyPerUnit: 1, unitPrice: 5.75, totalPrice: 5.75, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 30, itemCode: "2020010148", itemName: "焊接管", spec: "304-H4152 系", qtyPerUnit: 1, unitPrice: 11.54, totalPrice: 11.54, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 40, itemCode: "2010010019", itemName: "板片铜箔", spec: "BL95A 铜箔", qtyPerUnit: 64, unitPrice: 4.88, totalPrice: 312.4, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 50, itemCode: "2220160011", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 14, unitPrice: 10.79, totalPrice: 151.05, category: "固定元件", status: "生效", level: 1, material: "316L" },
|
||||
{ seq: 60, itemCode: "2220160012", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 15, unitPrice: 10.79, totalPrice: 161.84, category: "固定元件", status: "生效", level: 1, material: "316L" },
|
||||
{ seq: 70, itemCode: "2220160013", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 29, unitPrice: 10.79, totalPrice: 312.88, category: "固定元件", status: "生效", level: 1, material: "316L" },
|
||||
{ seq: 80, itemCode: "2220160034", itemName: "BL95 板片(失效示例)", spec: "304-BL95A 系", qtyPerUnit: 0, unitPrice: 15.84, totalPrice: 15.84, category: "固定元件", status: "失效", level: 1, material: "304", note: "失效件仅做状态识别展示,不计用量与金额" },
|
||||
{ seq: 90, itemCode: "2030160108", itemName: "BL95 前端板", spec: "304-F95A 系", qtyPerUnit: 1, unitPrice: 35.62, totalPrice: 35.62, category: "固定元件", status: "生效", level: 1, material: "304" },
|
||||
{ seq: 100, itemCode: "2040160003", itemName: "BL95 后端板", spec: "304-R95A 系", qtyPerUnit: 1, unitPrice: 35.62, totalPrice: 35.62, category: "固定元件", status: "生效", level: 1, material: "304" },
|
||||
{ seq: 110, itemCode: "2150020010", itemName: "垫圈", spec: "304-BL95A 系", qtyPerUnit: 2, unitPrice: 1.91, totalPrice: 3.82, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 120, itemCode: "2010030003", itemName: "铜垫圈", spec: "2系-D35xd", qtyPerUnit: 1, unitPrice: 0.1, totalPrice: 0.1, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 130, itemCode: "2010030005", itemName: "铜垫圈", spec: "4系-D48xd", qtyPerUnit: 1, unitPrice: 0.12, totalPrice: 0.12, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 140, itemCode: "2010030006", itemName: "铜垫圈", spec: "5系-D61xd", qtyPerUnit: 2, unitPrice: 0.14, totalPrice: 0.28, category: "固定元件", status: "生效", level: 1 },
|
||||
{ seq: 51, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 50, material: "316L", kind: "plate", qtyDisplay: "—" },
|
||||
{ seq: 52, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 50, material: "316L", kind: "coil", qtyDisplay: "展阶" },
|
||||
{ seq: 61, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 60, material: "316L", kind: "plate", qtyDisplay: "—" },
|
||||
{ seq: 62, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 60, material: "316L", kind: "coil", qtyDisplay: "展阶" },
|
||||
{ seq: 71, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 70, material: "316L", kind: "plate", qtyDisplay: "—" },
|
||||
{ seq: 72, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 70, material: "316L", kind: "coil", qtyDisplay: "展阶" },
|
||||
{ seq: 81, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "失效", level: 2, parentSeq: 80, material: "304", kind: "coil", qtyDisplay: "展阶", note: "截图树中失效件下展 304 钢卷;失效不计用量" },
|
||||
{ seq: 91, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 90, material: "304", kind: "coil", qtyDisplay: "展阶" },
|
||||
{ seq: 101, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 100, material: "304", kind: "coil", qtyDisplay: "展阶" },
|
||||
];
|
||||
|
||||
/** 钢卷用量汇总(mock 汇总口径,金额复算唯一入口):316L 250kg/台 · 304 20kg/台 */
|
||||
export const steelCoils: SteelCoil[] = [
|
||||
{ material: "316L", itemCode: "1010020011", kgPerUnit: 250, unitPrice: 18 },
|
||||
{ material: "304", itemCode: "1010010007", kgPerUnit: 20, unitPrice: 13 },
|
||||
];
|
||||
|
||||
/** 新 BOM 假设:研发设计新 BOM 单台钢卷用量与现 BOM 汇总一致,保证毛利复算闭环 */
|
||||
export const newBomAssumption = {
|
||||
basis: "研发设计新 BOM 的单台钢卷用量取与现 BOM 汇总一致",
|
||||
coils: steelCoils,
|
||||
provenance: "规格 5.3",
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
/** 规格 5.5 产能与采购 mock */
|
||||
export const capacity = {
|
||||
pressLine: { model: "BL95 冲压机组", loadRate: 0.78, absorbableIncrementUnits: 500 },
|
||||
mold: { model: "BL95 冲压模具", inStock: true },
|
||||
brazingFurnace: { scheduleHasSlot: true },
|
||||
purchase: [
|
||||
{ material: "316L 钢卷", itemCode: "1010020011", source: "供应商确认现货", leadDays: 5 },
|
||||
{ material: "304 钢卷", itemCode: "1010010007", source: "库存充足", leadDays: 0 },
|
||||
],
|
||||
productionCycleDays: 7,
|
||||
tip: "316L 钢卷建议立即发起采购以保留缓冲",
|
||||
provenance: "规格 5.5",
|
||||
};
|
||||
|
||||
/** 系统当前日期:距交期天数等按此实时复算 */
|
||||
export function todayIso(): string {
|
||||
return formatIso(new Date());
|
||||
}
|
||||
|
||||
/** 自今日起 n 天后的 ISO 日期(内置需求样本的交期按此生成,保证样本口径稳定) */
|
||||
export function isoAfterDays(days: number): string {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() + days);
|
||||
return formatIso(d);
|
||||
}
|
||||
|
||||
function formatIso(d: Date): string {
|
||||
const mm = `${d.getMonth() + 1}`.padStart(2, "0");
|
||||
const dd = `${d.getDate()}`.padStart(2, "0");
|
||||
return `${d.getFullYear()}-${mm}-${dd}`;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { CustomerMaster } from "../types";
|
||||
|
||||
/** 规格 5.1 客户主数据;金额单位统一为元(500 万 = 5,000,000) */
|
||||
export const customer: CustomerMaster = {
|
||||
code: "C-BD-001",
|
||||
name: "江苏宝得换热设备有限公司",
|
||||
shortName: "江苏宝得",
|
||||
industry: "CDU",
|
||||
creditLimit: 5_000_000,
|
||||
stockUnpickedAmount: 2_800_000,
|
||||
cancelledOrderAmount: 200_000,
|
||||
margin12mAvg: 0.12,
|
||||
groupMargin12mAvg: 0.16,
|
||||
salesRep: { code: "E-001", margin12mAvg: 0.21 },
|
||||
reconciliation: { system: "OA", cyclesPerYear: 2, currentPeriodConfirmed: true },
|
||||
provenance: "规格 5.1(V1.2:库存未提金额上调至 280 万,演示库存积压挤占信用额度)",
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { Demand, DemandPresetId } from "../types";
|
||||
import { isoAfterDays } from "./capacity";
|
||||
|
||||
/**
|
||||
* 规格 5.2 需求样本(V1.2 演示三场景 + 一个备用):
|
||||
* A 场景1 标品主线(字段齐备直通 → 全通过 → 订单 → 评审历史可查)
|
||||
* B 场景2 非标信用超额(库存 280 万 + 本单 350 万 → 评级 30 分 → 临时授信)
|
||||
* C 场景3 标品毛利达标链(储能 15% → ①②③ 不达标、④ 业务员 21% 兜底 → 90 分通过)
|
||||
* D 备用 非标毛利硬不达标(单价 6000 → 研发 30% 门槛不过 → 授信无法扭转)
|
||||
*/
|
||||
export const demands: Record<DemandPresetId, Demand> = {
|
||||
A: {
|
||||
id: "A",
|
||||
label: "场景1 · 钎焊式换热器 100 个(标品主线 · 全通过)",
|
||||
customerCode: "C-BD-001",
|
||||
document: { fileName: "客户需求评审申请-钎焊式换热器-100个-标品主线.docx", fileType: "docx" },
|
||||
parsed: {
|
||||
industry: "CDU",
|
||||
productType: "钎焊式换热器",
|
||||
quantity: 100,
|
||||
unitPrice: 7000,
|
||||
deliveryDate: isoAfterDays(14),
|
||||
coilMaterial: "316L",
|
||||
},
|
||||
missingFields: [],
|
||||
followUp: null,
|
||||
provenance: "规格 5.2 需求 A(V1.2 场景1 标品主线)",
|
||||
},
|
||||
B: {
|
||||
id: "B",
|
||||
label: "场景2 · 半焊式换热器 500 个(非标 · 信用超额)",
|
||||
customerCode: "C-BD-001",
|
||||
document: { fileName: "客户需求评审申请-半焊式换热器-500个-信用超额.docx", fileType: "docx" },
|
||||
parsed: {
|
||||
industry: "CDU",
|
||||
productType: "半焊式换热器",
|
||||
quantity: 500,
|
||||
unitPrice: 7000,
|
||||
deliveryDate: isoAfterDays(44),
|
||||
coilMaterial: "316L",
|
||||
},
|
||||
missingFields: [],
|
||||
followUp: null,
|
||||
provenance: "规格 5.2 需求 B(V1.2 场景2 信用超额)",
|
||||
},
|
||||
C: {
|
||||
id: "C",
|
||||
label: "场景3 · 钎焊式换热器 100 个(储能 · 毛利达标链)",
|
||||
customerCode: "C-BD-001",
|
||||
document: { fileName: "客户需求评审申请-钎焊式换热器-100个-储能-毛利达标链.docx", fileType: "docx" },
|
||||
parsed: {
|
||||
industry: "储能",
|
||||
productType: "钎焊式换热器",
|
||||
quantity: 100,
|
||||
unitPrice: 5600,
|
||||
deliveryDate: isoAfterDays(14),
|
||||
coilMaterial: "316L",
|
||||
},
|
||||
missingFields: [],
|
||||
followUp: null,
|
||||
provenance: "规格 5.2 需求 C(V1.2 场景3 毛利达标链)",
|
||||
},
|
||||
D: {
|
||||
id: "D",
|
||||
label: "备用 · 半焊式换热器 100 个 @6000(毛利硬不达标)",
|
||||
customerCode: "C-BD-001",
|
||||
document: { fileName: "客户需求评审申请-半焊式换热器-100个-单价6000-毛利不达标.docx", fileType: "docx" },
|
||||
parsed: {
|
||||
industry: "CDU",
|
||||
productType: "半焊式换热器",
|
||||
quantity: 100,
|
||||
unitPrice: 6000,
|
||||
deliveryDate: isoAfterDays(14),
|
||||
coilMaterial: "316L",
|
||||
},
|
||||
missingFields: [],
|
||||
followUp: null,
|
||||
provenance: "规格 5.2 需求 D(V1.2 备用:毛利不达标且授信无法扭转)",
|
||||
},
|
||||
};
|
||||
|
||||
/** 当期需求金额 = 数量 × 单价(元) */
|
||||
export function demandAmount(demand: Demand): number {
|
||||
return demand.parsed.quantity * demand.parsed.unitPrice;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/** 研发填报协同 meta(演示 mock):责任方 / 填报人 / 到达间隔;填报值由 engine/filing 按场景动态推导 */
|
||||
export interface FilingMeta {
|
||||
key: "mold" | "project" | "payback";
|
||||
label: string;
|
||||
standard: string;
|
||||
waiter: string;
|
||||
filler: string;
|
||||
delayMs: number;
|
||||
}
|
||||
|
||||
export const rndFiling: { items: FilingMeta[] } = {
|
||||
items: [
|
||||
{ key: "mold", label: "模具周期", standard: "≤3 天", waiter: "模具组", filler: "模具组 · 王工", delayMs: 4000 },
|
||||
{ key: "project", label: "项目周期", standard: "≤10 天", waiter: "项目部", filler: "项目部 · 李经理", delayMs: 5000 },
|
||||
{ key: "payback", label: "投资回收期", standard: "≤1 年", waiter: "财务", filler: "财务 · 赵经理", delayMs: 6000 },
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { CustomerMaster, Demand, DemandPresetId } from "../types";
|
||||
import { demands } from "./demands";
|
||||
import { customer } from "./customer";
|
||||
import { coilCostPerUnit, computeMargin, evaluateDelivery, evaluateFeasibility, evaluateRating, evaluateRndReview, computeCreditGap } from "../engine/rules";
|
||||
import { deriveFiling } from "../engine/filing";
|
||||
import type { FilingValues } from "../engine/filing";
|
||||
import { summarize } from "../engine/summary";
|
||||
|
||||
export interface Scenario {
|
||||
demand: Demand;
|
||||
coilCostPerUnit: number;
|
||||
margin: ReturnType<typeof computeMargin>;
|
||||
feasibility: ReturnType<typeof evaluateFeasibility>;
|
||||
rnd: ReturnType<typeof evaluateRndReview>;
|
||||
filing: FilingValues;
|
||||
delivery: ReturnType<typeof evaluateDelivery>;
|
||||
rating: ReturnType<typeof evaluateRating>;
|
||||
summary: ReturnType<typeof summarize>;
|
||||
creditGap: ReturnType<typeof computeCreditGap> | null;
|
||||
}
|
||||
|
||||
/** 场景快照:全部结论由规则引擎实时复算,保证口径自洽(规格 5.7) */
|
||||
export function buildScenario(demand: Demand, customerOverride?: CustomerMaster): Scenario {
|
||||
const c = customerOverride ?? customer;
|
||||
const margin = computeMargin(demand);
|
||||
const filing = deriveFiling(demand.parsed.quantity, margin.grossProfit);
|
||||
const feasibility = evaluateFeasibility(demand);
|
||||
const isStandard = feasibility.category === "标品";
|
||||
const rnd = evaluateRndReview(demand, true, filing);
|
||||
const delivery = evaluateDelivery(demand);
|
||||
const rating = evaluateRating(demand, c, margin.grossMarginRate);
|
||||
const summary = summarize(demand, feasibility, isStandard ? null : rnd, delivery, rating, c);
|
||||
return {
|
||||
demand,
|
||||
coilCostPerUnit: coilCostPerUnit(),
|
||||
margin,
|
||||
feasibility,
|
||||
rnd,
|
||||
filing,
|
||||
delivery,
|
||||
rating,
|
||||
summary,
|
||||
creditGap: summary.creditGap,
|
||||
};
|
||||
}
|
||||
|
||||
export const scenarios: Scenario[] = (["A", "B", "C", "D"] as DemandPresetId[]).map((id) => buildScenario(demands[id]));
|
||||
@@ -0,0 +1,17 @@
|
||||
/** 演示讲解节奏表(ms):按各节点内容多寡设计「过程时长」与「结果停留」 */
|
||||
export const pacing = {
|
||||
/** 需求解析:需求卡在右栏常驻,画布间隔离短 */
|
||||
parse: { process: 2000, cardDwell: 2500 },
|
||||
/** 可行性:2 条规则行 */
|
||||
feasibility: { steps: [1200, 1200], dwell: 4000 },
|
||||
/** 标品判断:菱形翻转 + 路由讲解 */
|
||||
judge: { flip: 400, dwell: 2500 },
|
||||
/** 研发:6 行 BOM/毛利卡 + 4 行结论表 */
|
||||
rnd: { bomSteps: [1500, 1200], bomDwell: 6000, conclusionDwell: 6000 },
|
||||
/** 交期:3 维度 */
|
||||
delivery: { steps: [1500, 1500, 1500], dwell: 5000 },
|
||||
/** 评级:4 记分项 + 可展开面板,内容最多 */
|
||||
rating: { steps: [1200, 1500, 1200, 1000], dwell: 8000 },
|
||||
/** 汇总/订单/授信/报告 */
|
||||
summary: { process: 1500, order: 1500, credit: 600, report: 3200 },
|
||||
} as const;
|
||||
@@ -0,0 +1,2 @@
|
||||
/** 当前登录用户(mock 认证态):评审发起人身份 */
|
||||
export const currentUser = { code: "E-001", name: "周销售" } as const;
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { EvidenceRow, IndustryCode } from "../types";
|
||||
|
||||
/** 评审历史归档:浏览器优先 localStorage,非浏览器环境回退内存 */
|
||||
|
||||
export interface TraceEntry {
|
||||
time: string;
|
||||
agent: string;
|
||||
title: string;
|
||||
rows?: EvidenceRow[];
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface ReviewRecordInput {
|
||||
fileName: string;
|
||||
customerCode: string;
|
||||
productType: string;
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
industry: IndustryCode | null;
|
||||
deliveryDate: string;
|
||||
operator: { code: string; name: string };
|
||||
startedAt: string;
|
||||
overall: "评审通过" | "评审不通过";
|
||||
orderNo: string | null;
|
||||
creditStarted: boolean;
|
||||
ratingTotal: number;
|
||||
feasibilityCategory: string;
|
||||
reportFileName: string;
|
||||
reportHtml: string;
|
||||
trace: TraceEntry[];
|
||||
}
|
||||
|
||||
export interface ReviewRecord extends ReviewRecordInput {
|
||||
id: string;
|
||||
finishedAt: string;
|
||||
}
|
||||
|
||||
const KEY = "bd-review-records-v1";
|
||||
const memory = new Map<string, string>();
|
||||
|
||||
function readAll(): ReviewRecord[] {
|
||||
try {
|
||||
const raw = typeof localStorage !== "undefined" ? localStorage.getItem(KEY) : (memory.get(KEY) ?? null);
|
||||
return raw ? (JSON.parse(raw) as ReviewRecord[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeAll(list: ReviewRecord[]): void {
|
||||
const raw = JSON.stringify(list);
|
||||
try {
|
||||
if (typeof localStorage !== "undefined") localStorage.setItem(KEY, raw);
|
||||
else memory.set(KEY, raw);
|
||||
} catch {
|
||||
memory.set(KEY, raw);
|
||||
}
|
||||
}
|
||||
|
||||
export function listReviewRecords(): ReviewRecord[] {
|
||||
return readAll();
|
||||
}
|
||||
|
||||
export function getReviewRecord(id: string): ReviewRecord | null {
|
||||
return readAll().find((r) => r.id === id) ?? null;
|
||||
}
|
||||
|
||||
export function saveReviewRecord(input: ReviewRecordInput): ReviewRecord {
|
||||
const list = readAll();
|
||||
const d = new Date();
|
||||
const pad = (n: number) => `${n}`.padStart(2, "0");
|
||||
const record: ReviewRecord = {
|
||||
...input,
|
||||
id: `RV-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${`${list.length + 1}`.padStart(3, "0")}`,
|
||||
finishedAt: d.toISOString(),
|
||||
};
|
||||
writeAll([record, ...list].slice(0, 50));
|
||||
return record;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { EvidenceRow } from "../types";
|
||||
|
||||
export type NodeId = "parse" | "feasibility" | "judge" | "rnd" | "delivery" | "rating" | "summary";
|
||||
export type NodeStatus = "排队" | "执行中" | "等待填报" | "待补全" | "已完成" | "不通过" | "跳过";
|
||||
|
||||
export interface NodeState {
|
||||
status: NodeStatus;
|
||||
metric?: string;
|
||||
}
|
||||
|
||||
/** 智能体旁悬浮卡:判断结果 + 判断依据(H7) */
|
||||
export interface FloatCard {
|
||||
title: string;
|
||||
verdict?: string;
|
||||
tone: "pass" | "fail" | "wait" | "info";
|
||||
rows: EvidenceRow[];
|
||||
note?: string;
|
||||
links?: Array<"bom" | "cycle" | "invest">;
|
||||
}
|
||||
|
||||
export type ChatCard =
|
||||
| { kind: "text"; text: string }
|
||||
| { kind: "summary" }
|
||||
| { kind: "order" }
|
||||
| { kind: "suggest" }
|
||||
| { kind: "credit-started" }
|
||||
| { kind: "report"; fileName: string };
|
||||
|
||||
export interface ChatMsg {
|
||||
id: number;
|
||||
role: "user" | "master";
|
||||
card: ChatCard;
|
||||
}
|
||||
|
||||
export type Todo =
|
||||
| { kind: "followup"; prompt: string; options: string[] }
|
||||
| { kind: "confirm" }
|
||||
| { kind: "credit" }
|
||||
| { kind: "next"; allowCreditRerun: boolean };
|
||||
@@ -0,0 +1,549 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { CustomerMaster, Demand, EvidenceRow, IndustryCode } from "../types";
|
||||
import { customer } from "../mock/customer";
|
||||
import { buildScenario } from "../mock/scenarios";
|
||||
import { currentUser } from "../mock/user";
|
||||
import { rndFiling } from "../mock/rndFiling";
|
||||
import { productMaster } from "../mock/bom";
|
||||
import { steelCoils } from "../mock/bom";
|
||||
import { pacing } from "../mock/timing";
|
||||
import { extractDocumentText, parseDemandDocument } from "../engine/docParse";
|
||||
import { buildReportHtml, reportFileName } from "../engine/report";
|
||||
import { computeCreditGap } from "../engine/rules";
|
||||
import { pct, wan, yuan } from "../engine/format";
|
||||
import { saveReviewRecord } from "./history";
|
||||
import type { TraceEntry } from "./history";
|
||||
import type { ChatCard, ChatMsg, FloatCard, NodeId, NodeState, NodeStatus, Todo } from "./types";
|
||||
|
||||
const NODE_IDS: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
|
||||
const initialNodes = (): Record<NodeId, NodeState> =>
|
||||
Object.fromEntries(NODE_IDS.map((id) => [id, { status: "排队" as NodeStatus }])) as Record<NodeId, NodeState>;
|
||||
|
||||
let seq = 1;
|
||||
const now = () => new Date().toLocaleTimeString("zh-CN", { hour12: false });
|
||||
/** 评审运行器:上传需求文档后按「解析 → 路由 → 并行评审 → 汇总」推进编排状态、悬浮依据卡与右侧对话流 */
|
||||
export function useReviewRunner() {
|
||||
const [demand, setDemand] = useState<Demand | null>(null);
|
||||
const [nodes, setNodes] = useState<Record<NodeId, NodeState>>(initialNodes);
|
||||
const [floats, setFloats] = useState<Partial<Record<NodeId, FloatCard>>>({});
|
||||
const [chat, setChat] = useState<ChatMsg[]>([]);
|
||||
const [todo, setTodo] = useState<Todo | null>(null);
|
||||
const [running, setRunning] = useState(false);
|
||||
const [report, setReport] = useState<{ fileName: string; html: string } | null>(null);
|
||||
const [customerOverride, setCustomerOverride] = useState<CustomerMaster | null>(null);
|
||||
const [ratingRevealed, setRatingRevealed] = useState(0);
|
||||
const [floatFocus, setFloatFocus] = useState<NodeId | null>(null);
|
||||
|
||||
const runIdRef = useRef(0);
|
||||
const todoRef = useRef<Todo | null>(null);
|
||||
const todoResolverRef = useRef<((v: string | null) => void) | null>(null);
|
||||
const filingResolverRef = useRef<(() => void) | null>(null);
|
||||
const traceRef = useRef<TraceEntry[]>([]);
|
||||
const demandRef = useRef<Demand | null>(null);
|
||||
|
||||
const scenario = useMemo(() => (demand ? buildScenario(demand, customerOverride ?? undefined) : null), [demand, customerOverride]);
|
||||
|
||||
useEffect(() => {
|
||||
demandRef.current = demand;
|
||||
}, [demand]);
|
||||
|
||||
useEffect(() => {
|
||||
demandRef.current = demand;
|
||||
}, [demand]);
|
||||
|
||||
const alive = (id: number) => runIdRef.current === id;
|
||||
const sleep = (ms: number, id: number) =>
|
||||
new Promise<boolean>((res) => setTimeout(() => res(alive(id)), ms));
|
||||
|
||||
const setNode = (node: NodeId, status: NodeStatus, metric?: string) =>
|
||||
setNodes((p) => ({ ...p, [node]: { status, metric } }));
|
||||
const setFloat = (node: NodeId, card: FloatCard | null) => {
|
||||
setFloats((p) => {
|
||||
const next = { ...p };
|
||||
if (card) next[node] = card;
|
||||
else delete next[node];
|
||||
return next;
|
||||
});
|
||||
if (card) setFloatFocus(node);
|
||||
};
|
||||
const pushChat = (role: "user" | "master", card: ChatCard) =>
|
||||
setChat((p) => [...p, { id: seq++, role, card }]);
|
||||
const pushTrace = (agent: string, title: string, rows?: EvidenceRow[], note?: string) => {
|
||||
traceRef.current = [...traceRef.current, { time: now(), agent, title, rows, note }];
|
||||
};
|
||||
|
||||
const clearAll = () => {
|
||||
setNodes(initialNodes());
|
||||
setFloats({});
|
||||
setFloatFocus(null);
|
||||
setRatingRevealed(0);
|
||||
setChat([]);
|
||||
setTodo(null);
|
||||
todoRef.current = null;
|
||||
setRunning(false);
|
||||
setDemand(null);
|
||||
setReport(null);
|
||||
setCustomerOverride(null);
|
||||
};
|
||||
|
||||
const askTodo = (t: Todo) => {
|
||||
setTodo(t);
|
||||
todoRef.current = t;
|
||||
return new Promise<string | null>((res) => {
|
||||
todoResolverRef.current = res;
|
||||
});
|
||||
};
|
||||
|
||||
const resolveTodo = (value: string | null) => {
|
||||
const t = todoRef.current;
|
||||
if (!t) return;
|
||||
if (t.kind === "next") {
|
||||
setTodo(null);
|
||||
todoRef.current = null;
|
||||
if (value === "new-review") {
|
||||
pushChat("user", { kind: "text", text: "发起新评审" });
|
||||
runIdRef.current++;
|
||||
filingResolverRef.current = null;
|
||||
clearAll();
|
||||
setDemand(null);
|
||||
setReport(null);
|
||||
setCustomerOverride(null);
|
||||
} else {
|
||||
pushChat("user", { kind: "text", text: "模拟授信审批通过,复跑评级" });
|
||||
void rerunAfterCredit();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (t.kind === "followup") {
|
||||
pushChat("user", { kind: "text", text: `补充行业:${value}` });
|
||||
} else if (t.kind === "confirm") {
|
||||
pushChat("user", { kind: "text", text: "确认评审结论,发起订单生成" });
|
||||
} else {
|
||||
pushChat("user", { kind: "text", text: "发起客户临时授信" });
|
||||
}
|
||||
setTodo(null);
|
||||
todoRef.current = null;
|
||||
todoResolverRef.current?.(value);
|
||||
todoResolverRef.current = null;
|
||||
};
|
||||
|
||||
async function runFlow(initialDemand: Demand) {
|
||||
const id = ++runIdRef.current;
|
||||
setRunning(true);
|
||||
let current = initialDemand;
|
||||
let s = buildScenario(current);
|
||||
const delay = (ms: number) => sleep(ms, id);
|
||||
traceRef.current = [];
|
||||
const startedAt = new Date();
|
||||
pushTrace("主智能体", `接收需求文档《${current.document.fileName}》,发起评审`);
|
||||
|
||||
pushChat("user", { kind: "text", text: `上传《${current.document.fileName}》` });
|
||||
setNode("parse", "执行中", "解析文档…");
|
||||
if (!(await delay(pacing.parse.process))) return finish(id);
|
||||
const missingNow = current.missingFields.length > 0;
|
||||
setNode("parse", missingNow ? "待补全" : "已完成", missingNow ? "等待补全行业" : "解析完成");
|
||||
setDemand(current);
|
||||
pushTrace("主智能体", "需求解析完成", [
|
||||
{ label: "客户", value: current.customerCode },
|
||||
{ label: "行业", value: current.parsed.industry ?? "缺失(待补全)" },
|
||||
{ label: "产品类型", value: current.parsed.productType },
|
||||
{ label: "数量 / 单价", value: `${current.parsed.quantity} 个 / ${yuan(current.parsed.unitPrice)} 元` },
|
||||
{ label: "交期", value: current.parsed.deliveryDate },
|
||||
{ label: "钢卷材质", value: current.parsed.coilMaterial },
|
||||
]);
|
||||
if (!missingNow) {
|
||||
pushChat("master", { kind: "text", text: "解析完成,完整性检查通过,进入可行性判定。" });
|
||||
}
|
||||
if (missingNow && current.followUp) {
|
||||
pushTrace("主智能体", "完整性检查:缺「行业」字段,发出补全追问");
|
||||
const v = await askTodo({ kind: "followup", prompt: current.followUp.prompt, options: current.followUp.options });
|
||||
if (!alive(id)) return;
|
||||
current = {
|
||||
...current,
|
||||
parsed: { ...current.parsed, industry: (v as IndustryCode) ?? current.parsed.industry },
|
||||
missingFields: [],
|
||||
followUp: null,
|
||||
};
|
||||
setDemand(current);
|
||||
s = buildScenario(current);
|
||||
pushTrace("用户", `补充行业:${v}`);
|
||||
setNode("parse", "已完成", "解析完成");
|
||||
pushChat("master", { kind: "text", text: "完整性检查通过,进入可行性判定。" });
|
||||
}
|
||||
|
||||
if (!(await delay(pacing.parse.cardDwell))) return finish(id);
|
||||
const feasRows = (stage: number) =>
|
||||
s.feasibility.evidence.map((row, i) =>
|
||||
stage > i ? row : { ...row, value: i === 0 ? "匹配中…" : "等待上一条规则结果", verdict: null },
|
||||
);
|
||||
setFloat("feasibility", {
|
||||
title: "可行性判定",
|
||||
tone: "info",
|
||||
rows: feasRows(0),
|
||||
note: "规则引擎匹配中…",
|
||||
});
|
||||
setNode("feasibility", "执行中", "加载规则库…");
|
||||
if (!(await delay(pacing.feasibility.steps[0]))) return finish(id);
|
||||
setFloat("feasibility", {
|
||||
title: "可行性判定",
|
||||
tone: "info",
|
||||
rows: feasRows(1),
|
||||
note: "R-可行-1 已出,匹配 R-可行-2…",
|
||||
});
|
||||
setNode("feasibility", "执行中", "匹配产品类型…");
|
||||
if (!(await delay(pacing.feasibility.steps[1]))) return finish(id);
|
||||
setNode("feasibility", "已完成", s.feasibility.category);
|
||||
setFloat("feasibility", {
|
||||
title: "可行性判定",
|
||||
verdict: s.feasibility.category,
|
||||
tone: "info",
|
||||
rows: s.feasibility.evidence,
|
||||
note: s.feasibility.routeLabel,
|
||||
});
|
||||
pushTrace("可行性智能体", `判定:${s.feasibility.category}`, s.feasibility.evidence, s.feasibility.routeLabel);
|
||||
pushChat("master", { kind: "text", text: `可行性判定:${s.feasibility.category},${s.feasibility.route === "rnd" ? "进入新品研发评审。" : "标品路径,跳过研发评审直达并行评审。"}` });
|
||||
if (!(await delay(pacing.feasibility.dwell))) return finish(id);
|
||||
if (s.feasibility.route !== "rnd") {
|
||||
setNode("rnd", "跳过", "标品跳过");
|
||||
}
|
||||
setNode("judge", "执行中", "读取判定结果…");
|
||||
if (!(await delay(pacing.judge.flip))) return finish(id);
|
||||
setNode("judge", "已完成", s.feasibility.category);
|
||||
if (!(await delay(pacing.judge.dwell))) return finish(id);
|
||||
|
||||
if (s.feasibility.route === "rnd") {
|
||||
const bomRowsFinal = [
|
||||
{ label: "单台钢卷成本", value: `${yuan(s.coilCostPerUnit)} 元/台` },
|
||||
{ label: "其中 316L", value: `${steelCoils[0].kgPerUnit} kg × ${steelCoils[0].unitPrice} 元 = ${yuan(steelCoils[0].kgPerUnit * steelCoils[0].unitPrice)} 元` },
|
||||
{ label: "其中 304", value: `${steelCoils[1].kgPerUnit} kg × ${steelCoils[1].unitPrice} 元 = ${yuan(steelCoils[1].kgPerUnit * steelCoils[1].unitPrice)} 元` },
|
||||
{ label: "收入", value: `${s.demand.parsed.quantity} × ${yuan(s.demand.parsed.unitPrice)} = ${yuan(s.margin.revenue)} 元` },
|
||||
{ label: "钢卷成本", value: `${yuan(s.coilCostPerUnit)} × ${s.demand.parsed.quantity} = ${yuan(s.margin.coilCostTotal)} 元` },
|
||||
{ label: "毛利 / 毛利率", value: `${yuan(s.margin.grossProfit)} 元 / ${pct(s.margin.grossMarginRate)}` },
|
||||
];
|
||||
const bomRows = (stage: number) =>
|
||||
bomRowsFinal.map((row, i) => {
|
||||
const need = i < 3 ? 1 : 2;
|
||||
return stage >= need
|
||||
? row
|
||||
: { ...row, value: stage === 0 ? (i < 3 ? "展开 BOM…" : "—") : "计算中…", verdict: null };
|
||||
});
|
||||
setFloat("rnd", {
|
||||
title: "BOM 展开 · 毛利复算",
|
||||
tone: "info",
|
||||
rows: bomRows(0),
|
||||
note: "展开多层 BOM 中…",
|
||||
});
|
||||
setNode("rnd", "执行中", "展开多层 BOM…");
|
||||
if (!(await delay(pacing.rnd.bomSteps[0]))) return finish(id);
|
||||
setFloat("rnd", {
|
||||
title: "BOM 展开 · 毛利复算",
|
||||
tone: "info",
|
||||
rows: bomRows(1),
|
||||
note: "钢卷用量已出,获取钢卷价格中…",
|
||||
});
|
||||
setNode("rnd", "执行中", "获取钢卷价格…");
|
||||
if (!(await delay(pacing.rnd.bomSteps[1]))) return finish(id);
|
||||
setFloat("rnd", {
|
||||
title: "BOM 展开 · 毛利复算",
|
||||
tone: "info",
|
||||
rows: bomRowsFinal,
|
||||
note: `${productMaster.itemName} 多层 BOM 已展至钢卷层`,
|
||||
links: ["bom"],
|
||||
});
|
||||
pushTrace("研发智能体", "BOM 展开与毛利复算完成", [
|
||||
{ label: "单台钢卷成本", value: `${yuan(s.coilCostPerUnit)} 元` },
|
||||
{ label: "毛利率", value: pct(s.margin.grossMarginRate) },
|
||||
]);
|
||||
if (!(await delay(pacing.rnd.bomDwell))) return finish(id);
|
||||
const arrived: Array<{ label: string; text: string }> = [];
|
||||
const waitRows = () =>
|
||||
rndFiling.items.map((it) => {
|
||||
const a = arrived.find((x) => x.label === it.label);
|
||||
return { label: it.label, value: a ? a.text : `等待${it.waiter}填报`, verdict: null };
|
||||
});
|
||||
setNode("rnd", "等待填报", "等待填报 0/3");
|
||||
setFloat("rnd", {
|
||||
title: "等待模具/项目/财务填报",
|
||||
tone: "wait",
|
||||
rows: waitRows(),
|
||||
note: "三项填报由模具 / 项目 / 财务分别提交,逐条到达",
|
||||
});
|
||||
for (const [idx, it] of rndFiling.items.entries()) {
|
||||
const manual = new Promise<void>((res) => {
|
||||
filingResolverRef.current = res;
|
||||
});
|
||||
await Promise.race([manual, delay(it.delayMs)]);
|
||||
filingResolverRef.current = null;
|
||||
if (!alive(id)) return;
|
||||
arrived.push({ label: it.label, text: `${s.filing.values[idx]} · ${it.filler} ${now()}` });
|
||||
pushTrace(it.filler, `${it.label}填报到达:${s.filing.values[idx]}`);
|
||||
setNode("rnd", "等待填报", `等待填报 ${arrived.length}/3`);
|
||||
setFloat("rnd", {
|
||||
title: "等待模具/项目/财务填报",
|
||||
tone: "wait",
|
||||
rows: waitRows(),
|
||||
note: `${it.label} 已到达(${arrived.length}/3)· ${it.filler}`,
|
||||
});
|
||||
}
|
||||
setNode("rnd", s.rnd.pass ? "已完成" : "不通过", `毛利率 ${pct(s.margin.grossMarginRate)}`);
|
||||
setFloat("rnd", {
|
||||
title: "研发评审结论",
|
||||
verdict: s.rnd.pass ? "通过" : "不通过",
|
||||
tone: s.rnd.pass ? "pass" : "fail",
|
||||
rows: s.rnd.items.map((i) => ({ label: i.label, value: `${i.standard} · 实际 ${i.actual}`, verdict: i.pass ? ("通过" as const) : ("不通过" as const) })),
|
||||
note: `毛利复算:${yuan(s.margin.revenue)} − ${yuan(s.margin.coilCostTotal)} = ${yuan(s.margin.grossProfit)} → ${pct(s.margin.grossMarginRate)}`,
|
||||
links: ["bom", "cycle", "invest"],
|
||||
});
|
||||
pushTrace("研发智能体", `研发评审结论:${s.rnd.pass ? "通过(4/4 项)" : "不通过"}`, s.rnd.evidence);
|
||||
pushChat("master", { kind: "text", text: `新品研发评审:${s.rnd.pass ? "通过(4/4 项)。" : `不通过(毛利率 ${pct(s.margin.grossMarginRate)} < 30%)。`}` });
|
||||
if (!(await delay(pacing.rnd.conclusionDwell))) return finish(id);
|
||||
} else {
|
||||
setNode("rnd", "跳过", "标品跳过");
|
||||
}
|
||||
|
||||
setNode("delivery", "执行中");
|
||||
setNode("rating", "执行中");
|
||||
pushChat("master", { kind: "text", text: "并行评审启动:交期评审 ∥ 客户评级。" });
|
||||
const tDelivery = (async () => {
|
||||
const dims = s.delivery.evidence;
|
||||
const rowsAt = (done: number) =>
|
||||
dims.map((r, i) => (i < done ? r : { label: r.label, value: "计算中…", verdict: null }));
|
||||
setFloat("delivery", {
|
||||
title: "交期依据",
|
||||
tone: "info",
|
||||
rows: rowsAt(0),
|
||||
note: "三个维度依次计算中…",
|
||||
});
|
||||
setNode("delivery", "执行中", "拉取冲压机组负荷…");
|
||||
if (!(await delay(pacing.delivery.steps[0])) || !alive(id)) return;
|
||||
setFloat("delivery", { title: "交期依据", tone: "info", rows: rowsAt(1), note: "产能负荷已出(1/3)" });
|
||||
setNode("delivery", "执行中", "核对模具/钎焊炉排程…");
|
||||
if (!(await delay(pacing.delivery.steps[1])) || !alive(id)) return;
|
||||
setFloat("delivery", { title: "交期依据", tone: "info", rows: rowsAt(2), note: "模具/机台已出(2/3)" });
|
||||
setNode("delivery", "执行中", "确认钢卷采购交期…");
|
||||
if (!(await delay(pacing.delivery.steps[2])) || !alive(id)) return;
|
||||
setNode("delivery", "已完成", `${s.delivery.daysToDelivery} 天可覆盖`);
|
||||
setFloat("delivery", {
|
||||
title: "交期依据",
|
||||
verdict: s.delivery.pass ? "通过" : "不通过",
|
||||
tone: s.delivery.pass ? "pass" : "fail",
|
||||
rows: dims,
|
||||
note: s.delivery.suggestions[0],
|
||||
});
|
||||
pushTrace("交期智能体", s.delivery.pass ? "交期评审通过" : "交期评审不通过", s.delivery.evidence, s.delivery.suggestions[0]);
|
||||
pushChat("master", { kind: "text", text: `交期评审:${s.delivery.pass ? "通过。" : "不通过。"}` });
|
||||
if (!(await delay(pacing.delivery.dwell)) || !alive(id)) return;
|
||||
})();
|
||||
const tRating = (async () => {
|
||||
setFloat("rating", {
|
||||
title: "客户评级记分卡",
|
||||
tone: "info",
|
||||
rows: [],
|
||||
note: "四个记分项依次计算中…",
|
||||
});
|
||||
setNode("rating", "执行中", "读取客户主数据 / ERP 信用数据…");
|
||||
if (!(await delay(pacing.rating.steps[0])) || !alive(id)) return;
|
||||
setRatingRevealed(1);
|
||||
setNode("rating", "执行中", "计算信用敞口…");
|
||||
if (!(await delay(pacing.rating.steps[1])) || !alive(id)) return;
|
||||
setRatingRevealed(2);
|
||||
setNode("rating", "执行中", "拉取 OA 对账状态…");
|
||||
if (!(await delay(pacing.rating.steps[2])) || !alive(id)) return;
|
||||
setRatingRevealed(3);
|
||||
setNode("rating", "执行中", "按记分规则打分…");
|
||||
if (!(await delay(pacing.rating.steps[3])) || !alive(id)) return;
|
||||
setRatingRevealed(4);
|
||||
setNode("rating", s.rating.pass ? "已完成" : "不通过", `${s.rating.total} 分`);
|
||||
setFloat("rating", {
|
||||
title: "客户评级记分卡",
|
||||
verdict: `${s.rating.total} 分 · ${s.rating.pass ? "合格" : "不合格"}`,
|
||||
tone: s.rating.pass ? "pass" : "fail",
|
||||
rows: s.rating.evidence,
|
||||
note: `合计 ${s.rating.total} 分 · ${s.rating.pass ? "≥90 合格" : "<90 不合格"}`,
|
||||
});
|
||||
pushTrace("评级智能体", s.rating.conclusion, s.rating.evidence);
|
||||
pushChat("master", { kind: "text", text: `客户评级:${s.rating.total} 分,${s.rating.pass ? "合格。" : "不合格。"}` });
|
||||
if (!(await delay(pacing.rating.dwell)) || !alive(id)) return;
|
||||
})();
|
||||
await Promise.all([tDelivery, tRating]);
|
||||
if (!alive(id)) return;
|
||||
|
||||
setNode("summary", "执行中", "汇总三个智能体结论…");
|
||||
if (!(await delay(pacing.summary.process))) return finish(id);
|
||||
setNode("summary", s.summary.order ? "已完成" : "不通过", s.summary.overall);
|
||||
pushChat("master", { kind: "summary" });
|
||||
pushTrace("主智能体", s.summary.overall, s.summary.rows.map((r) => ({ label: r.agent, value: `${r.conclusion} · ${r.keyEvidence}` })));
|
||||
|
||||
if (s.summary.order) {
|
||||
await askTodo({ kind: "confirm" });
|
||||
if (!alive(id)) return;
|
||||
setNode("summary", "执行中", "生成订单号…");
|
||||
if (!(await delay(pacing.summary.order))) return finish(id);
|
||||
pushChat("master", { kind: "order" });
|
||||
setNode("summary", "已完成", s.summary.order.orderNo);
|
||||
pushTrace("主智能体", `订单已生成 ${s.summary.order.orderNo}`);
|
||||
} else if (s.summary.creditGap) {
|
||||
pushChat("master", { kind: "suggest" });
|
||||
await askTodo({ kind: "credit" });
|
||||
if (!alive(id)) return;
|
||||
if (!(await delay(pacing.summary.credit))) return finish(id);
|
||||
pushChat("master", { kind: "credit-started" });
|
||||
pushTrace("主智能体", "客户临时授信流程已发起");
|
||||
} else {
|
||||
const failedAgents = s.summary.rows
|
||||
.filter((r) => r.conclusion.includes("不通过"))
|
||||
.map((r) => r.agent)
|
||||
.join("、");
|
||||
pushChat("master", {
|
||||
kind: "text",
|
||||
text: `评审不通过:${failedAgents} 未达标。该结论与信用额度无关,临时授信无法扭转;请调整单价、交期或工艺方案后重新发起评审。`,
|
||||
});
|
||||
pushTrace("主智能体", `评审不通过(${failedAgents}),不适用临时授信`);
|
||||
}
|
||||
pushChat("master", { kind: "text", text: "评审已收尾,正在生成《需求评估报告》…" });
|
||||
setNode("summary", "执行中", "生成评估报告…");
|
||||
if (!(await delay(pacing.summary.report))) return finish(id);
|
||||
const fileName = reportFileName(s);
|
||||
const html = buildReportHtml(s, s.summary.order ? "order" : "credit");
|
||||
if (!alive(id)) return;
|
||||
setReport({ fileName, html });
|
||||
pushTrace("主智能体", `需求评估报告已生成《${fileName}》`);
|
||||
saveReviewRecord({
|
||||
fileName: current.document.fileName,
|
||||
customerCode: current.customerCode,
|
||||
productType: current.parsed.productType,
|
||||
quantity: current.parsed.quantity,
|
||||
unitPrice: current.parsed.unitPrice,
|
||||
industry: current.parsed.industry,
|
||||
deliveryDate: current.parsed.deliveryDate,
|
||||
operator: currentUser,
|
||||
startedAt: startedAt.toISOString(),
|
||||
overall: s.summary.overall,
|
||||
orderNo: s.summary.order?.orderNo ?? null,
|
||||
creditStarted: !s.summary.order,
|
||||
ratingTotal: s.rating.total,
|
||||
feasibilityCategory: s.feasibility.category,
|
||||
reportFileName: fileName,
|
||||
reportHtml: html,
|
||||
trace: traceRef.current,
|
||||
});
|
||||
setNode("summary", s.summary.order ? "已完成" : "不通过", s.summary.order ? s.summary.order.orderNo : s.summary.overall);
|
||||
pushChat("master", { kind: "report", fileName });
|
||||
const nextTodo: Todo = { kind: "next", allowCreditRerun: !s.summary.order };
|
||||
setTodo(nextTodo);
|
||||
todoRef.current = nextTodo;
|
||||
finish(id);
|
||||
}
|
||||
|
||||
function finish(id: number) {
|
||||
if (alive(id)) setRunning(false);
|
||||
}
|
||||
|
||||
async function rerunAfterCredit() {
|
||||
const id = ++runIdRef.current;
|
||||
setRunning(true);
|
||||
const d = demandRef.current;
|
||||
if (!d) return finish(id);
|
||||
const granted = computeCreditGap(d, customer).suggested;
|
||||
const override: CustomerMaster = { ...customer, creditLimit: customer.creditLimit + granted };
|
||||
setCustomerOverride(override);
|
||||
pushChat("master", { kind: "text", text: `授信审批通过:临时授信 ${wan(granted)} 万已生效,复跑客户评级与汇总…` });
|
||||
const s2 = buildScenario(d, override);
|
||||
setRatingRevealed(0);
|
||||
setFloat("rating", {
|
||||
title: "客户评级记分卡",
|
||||
tone: "info",
|
||||
rows: [],
|
||||
note: "复跑:四个记分项依次计算中…",
|
||||
});
|
||||
setNode("rating", "执行中", "复跑评级(含临时授信)…");
|
||||
if (!(await sleep(1800, id))) return finish(id);
|
||||
setRatingRevealed(4);
|
||||
setNode("rating", "已完成", `${s2.rating.total} 分`);
|
||||
setFloat("rating", {
|
||||
title: "客户评级记分卡(复跑)",
|
||||
verdict: `${s2.rating.total} 分 · ${s2.rating.pass ? "合格" : "不合格"}`,
|
||||
tone: s2.rating.pass ? "pass" : "fail",
|
||||
rows: s2.rating.evidence,
|
||||
note: `临时授信 ${wan(granted)} 万生效,信用项转通过`,
|
||||
});
|
||||
setNode("summary", "执行中", "重新汇总…");
|
||||
if (!(await sleep(1500, id))) return finish(id);
|
||||
setNode("summary", "已完成", s2.summary.overall);
|
||||
pushChat("master", { kind: "summary" });
|
||||
await askTodo({ kind: "confirm" });
|
||||
if (!alive(id)) return;
|
||||
setNode("summary", "执行中", "生成订单号…");
|
||||
if (!(await sleep(1500, id))) return finish(id);
|
||||
pushChat("master", { kind: "order" });
|
||||
setNode("summary", "已完成", s2.summary.order?.orderNo ?? s2.summary.overall);
|
||||
pushChat("master", { kind: "text", text: "评审已收尾,正在生成《需求评估报告》…" });
|
||||
setNode("summary", "执行中", "生成评估报告…");
|
||||
if (!(await sleep(3200, id))) return finish(id);
|
||||
const fileName = reportFileName(s2);
|
||||
const html = buildReportHtml(s2, "order");
|
||||
if (!alive(id)) return;
|
||||
setReport({ fileName, html });
|
||||
setNode("summary", "已完成", s2.summary.order?.orderNo ?? s2.summary.overall);
|
||||
pushChat("master", { kind: "report", fileName });
|
||||
const t: Todo = { kind: "next", allowCreditRerun: false };
|
||||
setTodo(t);
|
||||
todoRef.current = t;
|
||||
finish(id);
|
||||
}
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
if (running) return;
|
||||
let text: string;
|
||||
try {
|
||||
text = await extractDocumentText(file);
|
||||
} catch (err) {
|
||||
pushChat("master", { kind: "text", text: err instanceof Error ? err.message : "文档解析失败,请重新上传。" });
|
||||
return;
|
||||
}
|
||||
const result = parseDemandDocument(text, file.name);
|
||||
if (!result.ok) {
|
||||
pushChat("master", {
|
||||
kind: "text",
|
||||
text: `《${file.name}》无法发起评审:${result.reasons.join(";")}。请补全后重新上传。`,
|
||||
});
|
||||
return;
|
||||
}
|
||||
runIdRef.current++;
|
||||
filingResolverRef.current = null;
|
||||
clearAll();
|
||||
setCustomerOverride(null);
|
||||
void runFlow(result.demand);
|
||||
};
|
||||
|
||||
const sendText = (text: string) => {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) return;
|
||||
pushChat("user", { kind: "text", text: trimmed });
|
||||
pushChat("master", {
|
||||
kind: "text",
|
||||
text: running
|
||||
? "评审正在进行中,进度见左侧编排画布;待办事项会出现在此处。"
|
||||
: "已收到。请通过下方附件按钮上传需求文档(Word / 文本)以启动评审。",
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
demand,
|
||||
scenario,
|
||||
nodes,
|
||||
floats,
|
||||
floatFocus,
|
||||
chat,
|
||||
todo,
|
||||
running,
|
||||
report,
|
||||
ratingRevealed,
|
||||
activeCustomer: customerOverride ?? customer,
|
||||
uploadFile,
|
||||
sendText,
|
||||
resolveTodo,
|
||||
};
|
||||
}
|
||||
|
||||
export type ReviewRunner = ReturnType<typeof useReviewRunner>;
|
||||
@@ -0,0 +1,394 @@
|
||||
/* 设计令牌:ui-ux-pro-max 推荐(enterprise B2B · Trust & Authority),离线包不引外部字体 */
|
||||
/* 变量挂在模块根容器 .cockpit-root 上,避免与平台全局 :root 变量冲突 */
|
||||
.cockpit-root {
|
||||
--brand: #2563eb;
|
||||
--brand-600: #1d4ed8;
|
||||
--brand-soft: #eff6ff;
|
||||
--cta: #f97316;
|
||||
--cta-soft: #fff7ed;
|
||||
--bg: #f8fafc;
|
||||
--surface: #ffffff;
|
||||
--ink: #1e293b;
|
||||
--muted: #64748b;
|
||||
--line: #e2e8f0;
|
||||
--pass: #15803d;
|
||||
--pass-bg: #f0fdf4;
|
||||
--fail: #b91c1c;
|
||||
--fail-bg: #fef2f2;
|
||||
--wait: #b45309;
|
||||
--wait-bg: #fffbeb;
|
||||
--radius: 10px;
|
||||
--shadow-1: 0 1px 2px rgba(15, 23, 42, 0.06), 0 4px 12px rgba(15, 23, 42, 0.08);
|
||||
--shadow-2: 0 12px 32px rgba(15, 23, 42, 0.16);
|
||||
--font: "Plus Jakarta Sans", -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;
|
||||
--label-col: 150px;
|
||||
/* 原 body 全局样式收敛到模块根容器 */
|
||||
height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: var(--font);
|
||||
font-size: 14px;
|
||||
line-height: 1.55;
|
||||
color: var(--ink);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* ---------- 顶栏 ---------- */
|
||||
.topbar {
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 8px 20px; background: var(--surface); border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.baode-root .logo { height: 30px; width: auto; }
|
||||
.topbar-title { display: flex; align-items: center; line-height: 1.2; padding-left: 14px; border-left: 1px solid var(--line); }
|
||||
.topbar-title strong { font-size: 16px; font-weight: 600; letter-spacing: .01em; }
|
||||
/* ---------- 主布局 ---------- */
|
||||
.topbar-right { margin-left: auto; display: flex; gap: 10px; align-items: center; }
|
||||
.user-chip { font-size: 12px; color: var(--muted); background: #f1f5f9; border-radius: 999px; padding: 4px 12px; }
|
||||
|
||||
/* ---------- 评审历史 ---------- */
|
||||
.hist-mask { position: fixed; inset: 0; background: rgba(15, 23, 42, .45); z-index: 70; display: flex; justify-content: center; padding: 40px 16px; }
|
||||
.hist { width: min(880px, 100%); max-height: calc(100dvh - 80px); display: flex; flex-direction: column; background: #fff; border-radius: 14px; overflow: hidden; box-shadow: var(--shadow-2); }
|
||||
.hist-head { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; border-bottom: 1px solid var(--line); font-weight: 700; }
|
||||
.hist-body { overflow: auto; padding: 14px 16px; }
|
||||
.hist-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||
.hist-table th, .hist-table td { padding: 8px 10px; border-bottom: 1px solid var(--line); text-align: left; }
|
||||
.hist-table th { color: var(--muted); font-weight: 600; font-size: 12px; }
|
||||
.hist-sub { margin: 18px 0 8px; font-size: 13px; }
|
||||
.trace { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.trace li { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }
|
||||
.trace-head { display: flex; gap: 10px; align-items: baseline; font-size: 13px; flex-wrap: wrap; }
|
||||
.trace-time { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 12px; }
|
||||
.trace-agent { background: var(--brand-soft); color: var(--brand-600); border-radius: 999px; padding: 1px 8px; font-size: 11px; font-weight: 600; }
|
||||
.trace-note { margin: 6px 0 0; color: var(--muted); font-size: 12px; }
|
||||
|
||||
.cockpit {
|
||||
flex: 1; min-height: 0;
|
||||
display: grid; grid-template-columns: minmax(0, 1fr) clamp(320px, 28vw, 400px);
|
||||
gap: 14px; padding: 14px 16px;
|
||||
}
|
||||
@media (max-width: 1100px) {
|
||||
.cockpit { grid-template-columns: 1fr; grid-template-rows: minmax(430px, 1fr) minmax(400px, 1fr); }
|
||||
}
|
||||
.canvas-panel, .right {
|
||||
display: flex; flex-direction: column; min-height: 0;
|
||||
background: var(--surface); border: 1px solid var(--line);
|
||||
border-radius: var(--radius); box-shadow: var(--shadow-1); overflow: hidden;
|
||||
}
|
||||
.baode-root .panel-head {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
padding: 10px 14px; border-bottom: 1px solid var(--line);
|
||||
}
|
||||
.baode-root .panel-head h2 { margin: 0; font-size: 14px; }
|
||||
.legend { display: flex; gap: 12px; font-size: 12px; color: var(--muted); flex-wrap: wrap; }
|
||||
.lg { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 4px; }
|
||||
.lg-run { background: var(--brand); }
|
||||
.lg-wait { background: var(--wait); }
|
||||
.lg-todo { background: var(--cta); }
|
||||
.lg-ok { background: var(--pass); }
|
||||
.lg-fail { background: var(--fail); }
|
||||
.lg-skip { background: #cbd5e1; }
|
||||
.lg-agent { background: #6366f1; border-radius: 2px; }
|
||||
|
||||
/* ---------- 编排画布 ---------- */
|
||||
.canvas {
|
||||
flex: 1; min-height: 0; overflow: auto; display: flex;
|
||||
background-image: radial-gradient(circle, #e2e8f0 1px, transparent 1px);
|
||||
background-size: 22px 22px;
|
||||
}
|
||||
.flow { position: relative; display: flex; flex-direction: row; align-items: flex-start; width: max-content; margin: auto; padding: 52px 20px 40px; transition: padding-bottom 0.25s ease; }
|
||||
.flow[data-active="true"] { margin: 0 auto; padding-bottom: 480px; }
|
||||
.stage { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; }
|
||||
.chips { display: flex; flex-direction: column; align-items: center; gap: 4px; }
|
||||
.chip-f {
|
||||
max-width: 118px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
font-size: 11px; padding: 2px 8px; border: 1px solid var(--line); border-radius: 999px;
|
||||
background: #fff; color: var(--muted); cursor: pointer; transition: color 0.18s, border-color 0.18s;
|
||||
}
|
||||
.chip-f:hover { border-color: var(--brand); color: var(--brand-600); }
|
||||
.fnode { position: relative; }
|
||||
.fnode-card {
|
||||
display: flex; flex-direction: column; gap: 6px; width: 118px; min-height: 92px;
|
||||
background: #fff; border: 1px solid var(--line); border-top: 3px solid #cbd5e1;
|
||||
border-radius: var(--radius); padding: 10px 12px; box-shadow: var(--shadow-1);
|
||||
transition: border-color 0.2s, box-shadow 0.2s;
|
||||
}
|
||||
.kind-control .fnode-card { background: var(--brand-soft); }
|
||||
.kind-agent .fnode-card {
|
||||
background: linear-gradient(180deg, #eef2ff 0%, #ffffff 60%);
|
||||
border-color: #c7d2fe; border-top-color: #6366f1;
|
||||
}
|
||||
.agent-tag {
|
||||
font-style: normal; font-size: 10px; font-weight: 700;
|
||||
color: #4338ca; background: #e0e7ff; border-radius: 999px; padding: 1px 6px;
|
||||
}
|
||||
.s-执行中 .fnode-card { border-top-color: var(--brand); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12); }
|
||||
.s-执行中 .fnode-card { position: relative; }
|
||||
.s-执行中 .fnode-card::after {
|
||||
content: ""; position: absolute; inset: -5px; border-radius: 14px; pointer-events: none;
|
||||
background:
|
||||
repeating-linear-gradient(90deg, var(--brand) 0 6px, transparent 6px 12px) 0 0 / 100% 2px no-repeat,
|
||||
repeating-linear-gradient(90deg, var(--brand) 0 6px, transparent 6px 12px) 0 100% / 100% 2px no-repeat,
|
||||
repeating-linear-gradient(0deg, var(--brand) 0 6px, transparent 6px 12px) 0 0 / 2px 100% no-repeat,
|
||||
repeating-linear-gradient(0deg, var(--brand) 0 6px, transparent 6px 12px) 100% 0 / 2px 100% no-repeat;
|
||||
animation: ants 1s linear infinite;
|
||||
}
|
||||
@keyframes ants {
|
||||
to { background-position: 12px 0, -12px 100%, 0 -12px, 100% 12px; }
|
||||
}
|
||||
.s-等待填报 .fnode-card { border-top-color: var(--wait); }
|
||||
.s-待补全 .fnode-card { border-top-color: var(--cta); box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.12); }
|
||||
.s-已完成 .fnode-card { border-top-color: var(--pass); }
|
||||
.s-不通过 .fnode-card { border-top-color: var(--fail); }
|
||||
.fnode-top { display: flex; align-items: center; gap: 6px; }
|
||||
.fnode-top .fnode-status { margin-left: auto; }
|
||||
.node-icon {
|
||||
width: 22px; height: 22px; flex: none; display: grid; place-items: center;
|
||||
border: none; border-radius: 6px; padding: 0; cursor: pointer;
|
||||
background: var(--brand-soft); color: var(--brand-600);
|
||||
transition: background 0.18s, color 0.18s;
|
||||
}
|
||||
.node-icon:hover { background: #dbeafe; color: var(--brand); }
|
||||
.node-icon:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
|
||||
.diamond {
|
||||
position: relative; width: 150px; height: 84px; margin-top: 4px;
|
||||
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
|
||||
background: #cbd5e1; display: grid; place-items: center;
|
||||
border: none; padding: 0; cursor: pointer;
|
||||
}
|
||||
.diamond:focus-visible { outline: 2px solid var(--brand); outline-offset: 3px; }
|
||||
.diamond-in {
|
||||
position: absolute; inset: 2px;
|
||||
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
|
||||
background: var(--cta-soft);
|
||||
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px;
|
||||
}
|
||||
.diamond-label { font-size: 12px; font-weight: 700; }
|
||||
.fnode-metric.muted { color: var(--muted); font-weight: 500; }
|
||||
.s-执行中 .diamond { background: var(--brand); animation: diamondPulse 1.2s ease-in-out infinite; }
|
||||
.s-已完成 .diamond { background: var(--pass); }
|
||||
.s-不通过 .diamond { background: var(--fail); }
|
||||
@keyframes diamondPulse { 50% { filter: brightness(1.18); } }
|
||||
.decision-status { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 6px; }
|
||||
.kind-decision .node-icon { background: var(--cta-soft); color: var(--cta); }
|
||||
.intro-desc { margin: 0; font-size: 12px; color: var(--ink); }
|
||||
.intro-points { margin: 6px 0 0; padding-left: 16px; font-size: 12px; }
|
||||
.intro-points li { margin: 2px 0; }
|
||||
.fnode-dot {
|
||||
flex: none; width: 18px; height: 18px; border-radius: 50%;
|
||||
display: grid; place-items: center; font-size: 11px; color: #fff; background: #cbd5e1;
|
||||
}
|
||||
.s-执行中 .fnode-dot { background: var(--brand); animation: pulse 1.6s ease-in-out infinite; }
|
||||
.s-等待填报 .fnode-dot { background: var(--wait); }
|
||||
.s-待补全 .fnode-dot { background: var(--cta); }
|
||||
.s-已完成 .fnode-dot { background: var(--pass); }
|
||||
.s-不通过 .fnode-dot { background: var(--fail); }
|
||||
.fnode-label { display: flex; flex-direction: column; font-size: 13px; font-weight: 600; }
|
||||
.fnode-label-row { display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap; }
|
||||
.fnode-note { font-style: normal; font-weight: 400; font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
|
||||
.fnode-status { font-size: 10px; color: var(--muted); white-space: nowrap; }
|
||||
.s-执行中 .fnode-status { color: var(--brand-600); font-weight: 600; }
|
||||
.s-不通过 .fnode-status { color: var(--fail); font-weight: 600; }
|
||||
.s-待补全 .fnode-status { color: var(--cta); font-weight: 600; }
|
||||
.fnode-metric { font-size: 12px; font-weight: 700; color: var(--brand-600); font-variant-numeric: tabular-nums; }
|
||||
|
||||
.conn-h { flex: none; position: relative; width: 20px; height: 2px; margin-top: 45px; background: #cbd5e1; }
|
||||
.flow[data-spread="true"] .conn-h { width: 210px; }
|
||||
.flow[data-wide="true"] .conn-h { width: 380px; }
|
||||
.conn-h::after {
|
||||
content: ""; position: absolute; right: -2px; top: -3px;
|
||||
border: 4px solid transparent; border-left-color: #cbd5e1;
|
||||
}
|
||||
.conn-h span {
|
||||
position: absolute; bottom: 4px; left: 50%; transform: translateX(-50%); z-index: 6;
|
||||
font-size: 11px; color: var(--muted); white-space: nowrap;
|
||||
background: var(--bg); padding: 0 4px; border-radius: 4px;
|
||||
}
|
||||
.bypass-h { position: absolute; top: 18px; height: 0; border-top: 2px dashed #fdba74; }
|
||||
.stub { position: absolute; top: 0; width: 0; border-left: 2px dashed #fdba74; }
|
||||
.stub-l { left: -1px; }
|
||||
.stub-l::after {
|
||||
content: ""; position: absolute; bottom: -4px; left: -4px;
|
||||
width: 6px; height: 6px; border-radius: 50%; background: #fdba74;
|
||||
}
|
||||
.stub-r { right: -1px; }
|
||||
.stub-r::after {
|
||||
content: ""; position: absolute; bottom: -6px; left: -5px;
|
||||
border: 4px solid transparent; border-top-color: #fdba74;
|
||||
}
|
||||
.bypass-h span {
|
||||
position: absolute; top: -18px; left: 50%; transform: translateX(-50%);
|
||||
font-size: 11px; color: var(--cta); white-space: nowrap;
|
||||
}
|
||||
|
||||
.pgroup {
|
||||
position: relative; display: flex; flex-direction: column; gap: 8px; width: 136px;
|
||||
padding: 16px 10px 10px;
|
||||
border: 1.5px dashed var(--brand); border-radius: 12px; background: rgba(37, 99, 235, 0.03);
|
||||
}
|
||||
.pgroup-badge {
|
||||
position: absolute; top: -10px; left: 12px;
|
||||
background: var(--brand); color: #fff; font-size: 11px; font-weight: 600;
|
||||
padding: 2px 10px; border-radius: 999px;
|
||||
}
|
||||
.pgroup .fnode-card { width: 100%; min-height: 76px; }
|
||||
.pgroup.pg-active { width: 210px; }
|
||||
|
||||
/* ---------- 悬浮依据卡 ---------- */
|
||||
.float {
|
||||
background: #fff; border: 1px solid var(--line); border-left: 3px solid var(--brand);
|
||||
border-radius: 8px; box-shadow: var(--shadow-2); padding: 10px 12px;
|
||||
animation: floatIn 0.24s ease-out; z-index: 5;
|
||||
}
|
||||
.floats-col {
|
||||
position: absolute; top: calc(100% + 8px); left: 50%; transform: translateX(-50%);
|
||||
display: flex; flex-direction: column; gap: 10px; z-index: 10; width: 320px;
|
||||
}
|
||||
.floats-col.align-left { left: 0; transform: none; }
|
||||
.floats-col.align-right { left: auto; right: 0; transform: none; }
|
||||
.floats-col.wide { width: 560px; }
|
||||
.floats-col.mid { width: 420px; }
|
||||
.float-table { margin: 2px 0 6px; }
|
||||
.float-table th, .float-table td { padding: 4px 6px; }
|
||||
.floats-col .float { width: 100%; display: flex; flex-direction: column; }
|
||||
.float-close { align-self: flex-end; margin-top: 6px; }
|
||||
.link-btn {
|
||||
align-self: flex-start; margin-top: 6px; padding: 0;
|
||||
background: none; border: none; color: var(--brand-600);
|
||||
font-size: 12px; cursor: pointer; text-decoration: underline;
|
||||
}
|
||||
.link-btn:hover { color: var(--brand); }
|
||||
.link-row { display: flex; gap: 14px; flex-wrap: wrap; margin-top: 6px; }
|
||||
.link-row .link-btn { margin-top: 0; }
|
||||
.baode-root .modal-backdrop {
|
||||
position: fixed; inset: 0; z-index: 100;
|
||||
background: rgba(15, 23, 42, 0.45);
|
||||
display: grid; place-items: center; padding: 24px;
|
||||
}
|
||||
.baode-root .modal {
|
||||
background: #fff; border-radius: 12px; box-shadow: var(--shadow-2);
|
||||
width: min(780px, 100%); max-height: 84vh; overflow: auto; padding: 16px 18px;
|
||||
}
|
||||
.baode-root .modal-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 14px; font-weight: 700; margin-bottom: 10px; }
|
||||
.baode-root .modal-kv { margin: 0 0 12px; }
|
||||
.bom-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||
.bom-table th, .bom-table td { border: 1px solid var(--line); padding: 5px 8px; text-align: left; }
|
||||
.bom-table th { background: #f3f4f6; }
|
||||
.bom-table .lvl2 td:nth-child(2) { padding-left: 22px; color: var(--muted); }
|
||||
.bom-table .invalid td:nth-child(2) { text-decoration: line-through; }
|
||||
.bom-table .invalid td:last-child { color: var(--fail); }
|
||||
.baode-root .sub { color: var(--muted); font-size: 11px; }
|
||||
.baode-root .modal-note { margin: 10px 0 0; font-size: 12px; color: var(--muted); }
|
||||
.detail-title { margin: 12px 0 6px; font-size: 13px; font-weight: 700; }
|
||||
.pass-cell { color: var(--pass); font-weight: 600; }
|
||||
.fail-cell { color: var(--fail); font-weight: 600; }
|
||||
.score-panels { display: flex; flex-direction: column; }
|
||||
.score-panel { border-top: 1px dashed var(--line); }
|
||||
.score-panel:first-child { border-top: none; }
|
||||
.score-panel-head {
|
||||
display: flex; align-items: center; gap: 8px; width: 100%;
|
||||
padding: 6px 0; background: none; border: none; cursor: pointer;
|
||||
font: inherit; font-size: 12px; text-align: left;
|
||||
}
|
||||
.score-panel-head:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
|
||||
.sp-label { font-weight: 600; color: var(--muted); white-space: nowrap; width: var(--label-col); flex: none; }
|
||||
.sp-value { flex: 1; color: var(--ink); }
|
||||
.sp-caret { color: var(--muted); font-size: 10px; width: 14px; flex: none; text-align: center; }
|
||||
.sp-muted { color: var(--muted); }
|
||||
.score-panel-head .pass-cell, .score-panel-head .fail-cell { flex: none; width: 96px; text-align: right; }
|
||||
.score-panel-body { padding: 2px 0 8px; }
|
||||
.inline-link { display: inline; padding: 0; margin: 0; }
|
||||
.score-panels .ev-v { width: 96px; padding-right: 22px; white-space: nowrap; text-align: right; }
|
||||
.tone-pass { border-left-color: var(--pass); }
|
||||
.tone-fail { border-left-color: var(--fail); }
|
||||
.tone-wait { border-left-color: var(--wait); }
|
||||
.float-head { display: flex; justify-content: space-between; gap: 8px; font-size: 12px; font-weight: 700; margin-bottom: 6px; }
|
||||
.float-verdict { font-weight: 700; }
|
||||
.tone-pass .float-verdict { color: var(--pass); }
|
||||
.tone-fail .float-verdict { color: var(--fail); }
|
||||
.tone-wait .float-verdict { color: var(--wait); }
|
||||
.float-note { margin: 6px 0 0; font-size: 11px; color: var(--muted); }
|
||||
|
||||
.ev { width: 100%; border-collapse: collapse; }
|
||||
.ev td { padding: 3px 6px 3px 0; font-size: 12px; vertical-align: top; border: 0; text-align: left; }
|
||||
.ev tr + tr td { border-top: 1px dashed var(--line); }
|
||||
.ev-label { color: var(--muted); width: calc(var(--label-col) + 8px); padding-right: 8px; }
|
||||
.ev-value { color: var(--ink); }
|
||||
.ev-v { width: 46px; text-align: right; font-weight: 600; }
|
||||
.ev-v.pass { color: var(--pass); }
|
||||
.ev-v.fail { color: var(--fail); }
|
||||
|
||||
/* ---------- 执行日志 ---------- */
|
||||
.chat-empty { color: var(--muted); font-size: 12px; padding: 8px 2px; margin: 0; }
|
||||
|
||||
/* ---------- 右栏 ---------- */
|
||||
.demand-card { padding: 10px 14px; border-bottom: 1px solid var(--line); background: #fbfcfe; }
|
||||
.demand-empty { display: flex; flex-direction: column; gap: 4px; padding: 14px; color: var(--muted); font-size: 12px; }
|
||||
.demand-empty strong { color: var(--ink); font-size: 13px; }
|
||||
.kv-grid { display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 4px 10px; margin: 8px 0 0; font-size: 12px; }
|
||||
.kv-grid dt { color: var(--muted); }
|
||||
.kv-grid dd { margin: 0; font-variant-numeric: tabular-nums; }
|
||||
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 12px; font-weight: 700; }
|
||||
.badge { font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 999px; white-space: nowrap; }
|
||||
.badge-ok { background: var(--pass-bg); color: var(--pass); }
|
||||
.badge-wait { background: var(--wait-bg); color: var(--wait); }
|
||||
.badge-fail { background: var(--fail-bg); color: var(--fail); }
|
||||
.chat { flex: 1; min-height: 0; overflow: auto; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
|
||||
.bubble { max-width: 88%; padding: 8px 12px; border-radius: 12px; font-size: 13px; }
|
||||
.bubble.user { align-self: flex-end; background: var(--brand); color: #fff; border-bottom-right-radius: 4px; }
|
||||
.bubble.master { align-self: flex-start; background: #f1f5f9; color: var(--ink); border-bottom-left-radius: 4px; }
|
||||
.card { align-self: stretch; background: #fff; border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; box-shadow: var(--shadow-1); }
|
||||
.master-card { border-left: 3px solid var(--brand); }
|
||||
.master-card.tone-fail, .todo-card.tone-fail { border-left-color: var(--fail); }
|
||||
.card-list { margin: 8px 0 0; padding-left: 18px; font-size: 12px; }
|
||||
.card-list li { margin: 2px 0; }
|
||||
.todo-card { border-left: 3px solid var(--cta); }
|
||||
.todo-prompt { margin: 8px 0; font-size: 12px; }
|
||||
.todo-actions { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||
|
||||
.baode-root .btn {
|
||||
font-size: 13px; padding: 7px 14px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--line); background: #fff; color: var(--ink);
|
||||
transition: background 0.18s, border-color 0.18s, color 0.18s;
|
||||
}
|
||||
.baode-root .btn:hover { border-color: var(--brand); color: var(--brand-600); }
|
||||
.baode-root .btn-primary { background: var(--brand); border-color: var(--brand); color: #fff; font-weight: 600; }
|
||||
.baode-root .btn-primary:hover { background: var(--brand-600); border-color: var(--brand-600); color: #fff; }
|
||||
.baode-root .btn-danger { background: var(--fail); border-color: var(--fail); color: #fff; font-weight: 600; }
|
||||
.baode-root .btn-danger:hover { background: #991b1b; border-color: #991b1b; color: #fff; }
|
||||
.baode-root .btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.baode-root .icon-btn {
|
||||
width: 38px; height: 38px; display: grid; place-items: center; flex: none;
|
||||
border: 1px solid var(--line); border-radius: 8px; background: #fff;
|
||||
color: var(--brand-600); cursor: pointer; transition: border-color 0.18s;
|
||||
}
|
||||
.baode-root .icon-btn:hover { border-color: var(--brand); }
|
||||
.baode-root .icon-btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.composer { display: flex; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--line); background: #fbfcfe; }
|
||||
.composer input {
|
||||
flex: 1; min-width: 0; height: 38px; padding: 0 12px;
|
||||
border: 1px solid var(--line); border-radius: 8px; background: #fff; font: inherit; font-size: 13px;
|
||||
}
|
||||
.baode-root .btn:focus-visible, .baode-root .icon-btn:focus-visible, .composer input:focus-visible {
|
||||
outline: 2px solid var(--brand); outline-offset: 2px;
|
||||
}
|
||||
|
||||
/* ---------- 数据自检页(类名用 checkpage,避免与 supplier-platform 的 .page 冲突) ---------- */
|
||||
.checkpage { max-width: 1080px; margin: 0 auto; padding: 32px 24px 64px; }
|
||||
.checkpage h1 { font-size: 22px; margin: 0 0 4px; }
|
||||
.checkpage h2 { font-size: 16px; margin: 28px 0 10px; }
|
||||
.checkpage .sub { color: var(--muted); font-size: 13px; margin: 0 0 20px; }
|
||||
.checkpage table { width: 100%; border-collapse: collapse; background: #fff; font-size: 13px; }
|
||||
.checkpage th, .checkpage td { border: 1px solid var(--line); padding: 7px 10px; text-align: left; }
|
||||
.checkpage th { background: #f3f4f6; }
|
||||
.checkpage td.num { font-variant-numeric: tabular-nums; }
|
||||
.checkpage .pass { color: var(--pass); font-weight: 600; }
|
||||
.checkpage .fail { color: var(--fail); font-weight: 600; }
|
||||
|
||||
@keyframes floatIn { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } }
|
||||
@keyframes pulse {
|
||||
0%, 100% { box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.35); }
|
||||
50% { box-shadow: 0 0 0 6px rgba(37, 99, 235, 0); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
* { animation: none !important; transition: none !important; }
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/** 江苏宝得需求评审多智能体 cockpit · 业务域类型 */
|
||||
|
||||
export type IndustryCode = "CDU" | "储能" | "其他";
|
||||
/** 内置需求样本编号(数据自检页使用);上传解析的需求以文件名为 id */
|
||||
export type DemandPresetId = "A" | "B" | "C" | "D";
|
||||
export type ProductCategory = "标品" | "非标品";
|
||||
export type AgentKey = "feasibility" | "rnd" | "delivery" | "rating";
|
||||
export type Verdict = "通过" | "不通过";
|
||||
|
||||
/** 依据表行(H7:每个结论都带依据表) */
|
||||
export interface EvidenceRow {
|
||||
label: string;
|
||||
value: string;
|
||||
verdict?: Verdict | null;
|
||||
}
|
||||
|
||||
/** 智能体统一返回结构(规格 4.2):{结论, 依据[], 建议[], 时间戳} */
|
||||
export interface AgentResult {
|
||||
agent: AgentKey | "master";
|
||||
conclusion: string;
|
||||
verdict: Verdict | "路由";
|
||||
evidence: EvidenceRow[];
|
||||
suggestions: string[];
|
||||
}
|
||||
|
||||
/** 客户主数据(规格 5.1,金额单位:元) */
|
||||
export interface CustomerMaster {
|
||||
code: string;
|
||||
name: string;
|
||||
shortName: string;
|
||||
industry: IndustryCode;
|
||||
creditLimit: number;
|
||||
stockUnpickedAmount: number;
|
||||
cancelledOrderAmount: number;
|
||||
margin12mAvg: number;
|
||||
groupMargin12mAvg: number;
|
||||
salesRep: { code: string; margin12mAvg: number };
|
||||
reconciliation: { system: string; cyclesPerYear: number; currentPeriodConfirmed: boolean };
|
||||
provenance: string;
|
||||
}
|
||||
|
||||
/** 上传文档解析后的结构化需求(规格 5.2) */
|
||||
export interface Demand {
|
||||
id: string;
|
||||
label: string;
|
||||
customerCode: string;
|
||||
document: { fileName: string; fileType: "docx" | "txt" };
|
||||
parsed: {
|
||||
industry: IndustryCode | null;
|
||||
productType: string;
|
||||
quantity: number;
|
||||
unitPrice: number;
|
||||
deliveryDate: string;
|
||||
coilMaterial: string;
|
||||
};
|
||||
missingFields: Array<"industry">;
|
||||
followUp: { field: "industry"; prompt: string; options: IndustryCode[] } | null;
|
||||
provenance: string;
|
||||
}
|
||||
|
||||
/** BOM 行(规格 5.3 + 客户 ERP 截图:维护BOM信息画面) */
|
||||
export interface BomLine {
|
||||
seq: number;
|
||||
itemCode: string;
|
||||
itemName: string;
|
||||
spec: string;
|
||||
qtyPerUnit: number;
|
||||
unitPrice: number;
|
||||
totalPrice: number;
|
||||
category: string;
|
||||
status: "生效" | "失效";
|
||||
level: 1 | 2;
|
||||
parentSeq?: number;
|
||||
material?: "304" | "316L";
|
||||
kind?: "coil" | "plate";
|
||||
qtyDisplay?: string;
|
||||
note?: string;
|
||||
}
|
||||
|
||||
export interface SteelCoil {
|
||||
material: "304" | "316L";
|
||||
itemCode: string;
|
||||
kgPerUnit: number;
|
||||
unitPrice: number;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,172 @@
|
||||
import './index.css';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { ThemeProvider, useTheme } from './context/ThemeContext';
|
||||
import { useText } from './i18n/useText';
|
||||
import { initDatabase } from './data/sqlite';
|
||||
import { useMecData } from './hooks/useMecData';
|
||||
import { CURRENT_PERIOD, projectAt, projectTree } from './lib/time';
|
||||
import MecHeader from './components/MecHeader';
|
||||
import StarBackground from './components/StarBackground';
|
||||
import DemandPanel from './components/DemandPanel';
|
||||
import MetricWorkspace from './components/MetricWorkspace';
|
||||
import SupplyPanel from './components/SupplyPanel';
|
||||
import type { ViewProps } from './components/workspace/views';
|
||||
import type { ExpertTeam } from './lib/teams';
|
||||
|
||||
const GAP = 36;
|
||||
|
||||
function AppInner() {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
|
||||
const [dbReady, setDbReady] = useState(false);
|
||||
const [dbError, setDbError] = useState<string | null>(null);
|
||||
const [dbTimedOut, setDbTimedOut] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let settled = false;
|
||||
// 看门狗:WASM 请求挂起时不再无限转圈
|
||||
const watchdog = setTimeout(() => { if (!settled) setDbTimedOut(true); }, 20000);
|
||||
initDatabase()
|
||||
.then(() => { settled = true; clearTimeout(watchdog); setDbReady(true); })
|
||||
.catch((e: unknown) => { settled = true; clearTimeout(watchdog); setDbError((e as Error).message); });
|
||||
return () => { settled = true; clearTimeout(watchdog); };
|
||||
}, []);
|
||||
|
||||
const data = useMecData(dbReady);
|
||||
|
||||
const [selected, setSelected] = useState('OV');
|
||||
/* 左栏=销售订单 / 客户资料两个页签,右栏=采购单 / 生产工单 / 供应商资料三个页签;点选订单后两侧联动过滤 */
|
||||
const [selectedSO, setSelectedSO] = useState<string | null>(null);
|
||||
/* 缺省两侧收起:首屏中间内容区更平衡,用户需要时再展开 */
|
||||
const [leftOpen, setLeftOpen] = useState(false);
|
||||
const [rightOpen, setRightOpen] = useState(false);
|
||||
const [netStage, setNetStage] = useState(false);
|
||||
const [team, setTeam] = useState<ExpertTeam | null>(null);
|
||||
/* 全局时间游标(0-11):知识图谱与因果看板按此时点重算取值与状态 */
|
||||
const [period, setPeriod] = useState(CURRENT_PERIOD);
|
||||
|
||||
const onSelect = useCallback((code: string) => {
|
||||
if (code) setSelected(code);
|
||||
}, []);
|
||||
|
||||
/* 时间滑块拖动 / 回放:单一游标源,图谱与看板同一时点读数 */
|
||||
const onPeriod = useCallback((p: number) => setPeriod(p), []);
|
||||
|
||||
// 指标网络全景舞台:ESC 退出(捕获阶段注册,子组件阻断冒泡也生效)
|
||||
useEffect(() => {
|
||||
if (!netStage) return;
|
||||
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setNetStage(false); };
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [netStage]);
|
||||
|
||||
// 专家团会诊状态:中央对话区仍消费 team / onDismissTeam
|
||||
const onDismissTeam = useCallback(() => setTeam(null), []);
|
||||
|
||||
/* 游标投影:一处把时点值与定级贴回节点,下游(指标树 / 明细 / 趋势 / 结构 / 驾驶舱 /
|
||||
图谱 / 因果看板 / 对话区)的当期口径自动变成“数据期口径”,避免逐点改造遗漏。
|
||||
trend 不投影,回看历史与预测仍拿得到完整 12 期。 */
|
||||
const view = useMemo(() => {
|
||||
if (period === CURRENT_PERIOD) return { tree: data.tree, flat: data.flat, byCode: data.byCode };
|
||||
const tree = projectTree(data.tree, period);
|
||||
const flat = data.flat.map(n => projectAt(n, period));
|
||||
return { tree, flat, byCode: new Map(flat.map(n => [n.code, n] as const)) };
|
||||
}, [data, period]);
|
||||
|
||||
const viewProps = useMemo<ViewProps>(
|
||||
() => ({ selected, byCode: view.byCode, flat: view.flat, links: data.links, onSelect, period }),
|
||||
[selected, view.byCode, view.flat, data.links, onSelect, period],
|
||||
);
|
||||
|
||||
if (!dbReady) {
|
||||
const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null);
|
||||
return (
|
||||
<div style={{
|
||||
width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14,
|
||||
}}>
|
||||
<style>{`@keyframes mec-spin { to { transform: rotate(360deg); } }`}</style>
|
||||
{!errMsg ? (
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<div style={{
|
||||
width: 40, height: 40, border: `3px solid ${tokens.border}`, borderTopColor: tokens.accent,
|
||||
borderRadius: '50%', margin: '0 auto 16px', animation: 'mec-spin 1s linear infinite',
|
||||
}} />
|
||||
{t.common.initializing}
|
||||
</div>
|
||||
) : (
|
||||
<div style={{ maxWidth: 560, textAlign: 'center' }}>
|
||||
<div style={{ color: tokens.danger, marginBottom: 6, fontWeight: 600 }}>{t.common.initFailed}</div>
|
||||
<div style={{ fontSize: 12, color: tokens.textSub, wordBreak: 'break-all', marginBottom: 10 }}>{errMsg}</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, marginBottom: 14, fontFamily: 'monospace' }}>{location.host}</div>
|
||||
<button
|
||||
onClick={() => window.location.reload()}
|
||||
style={{
|
||||
padding: '6px 20px', fontSize: 13, cursor: 'pointer', borderRadius: 6,
|
||||
background: tokens.accentBg, color: tokens.accent, border: `1px solid ${tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{t.common.retry}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column',
|
||||
background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden',
|
||||
position: 'relative',
|
||||
}}>
|
||||
{/* 流动透明球体科技感背景层 */}
|
||||
<StarBackground />
|
||||
|
||||
{/* 内容层:置于背景球体之上 */}
|
||||
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
|
||||
<MecHeader period={period} />
|
||||
|
||||
{/* 三栏:左=销售订单 / 客户资料,中=指标工作区(底部内嵌对话区),右=采购单 / 生产工单 / 供应商资料 */}
|
||||
<div style={{
|
||||
flex: 1, display: 'flex', minHeight: 0, alignItems: 'stretch', padding: '28px 0 20px',
|
||||
}}>
|
||||
<DemandPanel
|
||||
expanded={leftOpen}
|
||||
onToggle={() => setLeftOpen(v => !v)}
|
||||
selectedSO={selectedSO}
|
||||
onSelectSO={setSelectedSO}
|
||||
/>
|
||||
|
||||
<div style={{ width: GAP, flexShrink: 0 }} />
|
||||
|
||||
<MetricWorkspace
|
||||
selected={selected} staff={data.staff} viewProps={viewProps}
|
||||
period={period} onPeriod={onPeriod}
|
||||
netStage={netStage} onExitNetStage={() => setNetStage(false)}
|
||||
team={team} onDismissTeam={onDismissTeam}
|
||||
onLocateSO={so => { setSelectedSO(so); setLeftOpen(true); setRightOpen(true); }}
|
||||
/>
|
||||
|
||||
<div style={{ width: GAP, flexShrink: 0 }} />
|
||||
|
||||
<SupplyPanel
|
||||
expanded={rightOpen}
|
||||
onToggle={() => setRightOpen(v => !v)}
|
||||
selectedSO={selectedSO}
|
||||
onSelectSO={setSelectedSO}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<ThemeProvider>
|
||||
<AppInner />
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { ArrowRight, Ban, Bot, ChevronDown, ChevronsDown, ChevronUp, ChevronsUp, Layers, Radio, Send, Sparkles, User, Users } from 'lucide-react';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import type { ThemeTokens } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import type { I18n } from '../i18n/locales';
|
||||
import type { DigitalStaff } from '../data/sqlite';
|
||||
import { SUGGESTED } from '../lib/ibpAsk';
|
||||
import { alertColor, fmt } from '../lib/metric';
|
||||
import type { ConsultTurn, ExpertTeam, MetricSnap } from '../lib/teams';
|
||||
import type { AgentChat } from '../hooks/useAgentChat';
|
||||
import AskAnswerCard, { StepTrace } from './agent/AskAnswerCard';
|
||||
|
||||
interface AgentDockProps {
|
||||
/** 在岗数字员工:头部状态点 */
|
||||
staff: DigitalStaff[];
|
||||
/** 会话状态机由父级持有:本体舞台换掉内容区时对话历史不丢 */
|
||||
chat: AgentChat;
|
||||
/** 专家团:非空时对话区切换为多智能体轮流会诊 */
|
||||
team: ExpertTeam | null;
|
||||
onDismissTeam: () => void;
|
||||
/** 建议动作「定位到订单」:在左栏选中该销售订单 */
|
||||
onLocateSO?: (so: string) => void;
|
||||
/** 建议动作「打开业务本体总览」:切到本体页 */
|
||||
onOpenOntology?: () => void;
|
||||
/** 高度由父级持有,全屏切换时不丢失展开状态 */
|
||||
height: number;
|
||||
onToggle: () => void;
|
||||
/** 拉高态:对话区进一步往上拉高(第三高度档) */
|
||||
tall: boolean;
|
||||
onToggleTall: () => void;
|
||||
}
|
||||
|
||||
const levelColor = (lv: MetricSnap['level'], tk: ThemeTokens) =>
|
||||
lv === 'good' ? tk.success : lv === 'warn' ? tk.warning : tk.danger;
|
||||
|
||||
/** 成员卡内的一行:小标签 + 文本 */
|
||||
function SecRow({ label, text, tk, color }: { label: string; text?: string; tk: ThemeTokens; color?: string }) {
|
||||
if (!text) return null;
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{
|
||||
flex: '0 0 auto', fontSize: 10.5, fontWeight: 700, marginTop: 1, padding: '1px 6px', borderRadius: 6,
|
||||
color: color ?? tk.textMuted,
|
||||
background: color ? `${color}1a` : tk.panelBgAlt,
|
||||
border: `1px solid ${color ? `${color}33` : tk.border}`,
|
||||
}}>{label}</span>
|
||||
<span style={{ fontSize: 12.5, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>{text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 专家成员发言卡:指标数据条 + 现状/观点/建议 + 移交衔接 */
|
||||
function MemberCard({ turn, tk, t, time }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string }) {
|
||||
const m = turn.metric;
|
||||
const lc = m ? levelColor(m.level, tk) : tk.accent;
|
||||
return (
|
||||
<div className="content-reveal" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
|
||||
<div style={{ maxWidth: '92%', minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
|
||||
<span style={{ width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0, background: tk.cardBg, border: `1px solid ${tk.border}` }}>
|
||||
<User size={11} color={tk.accent} />
|
||||
</span>
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tk.text, flexShrink: 0 }}>{turn.name}</span>
|
||||
{turn.tag && <span style={{ fontSize: 10.5, color: tk.textMuted, padding: '0 6px', borderRadius: 7, border: `1px solid ${tk.border}`, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160 }}>{turn.tag}</span>}
|
||||
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums' }}>{time}</span>
|
||||
</div>
|
||||
<div style={{ background: tk.cardBg, border: `1px solid ${tk.border}`, borderLeft: `3px solid ${lc}`, borderRadius: '4px 10px 10px 10px', padding: '9px 11px', display: 'flex', flexDirection: 'column', gap: 7 }}>
|
||||
{m && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 9px', borderRadius: 8, background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}` }}>
|
||||
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: tk.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.label}</span>
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: tk.text, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{m.value}</span>
|
||||
<span style={{ fontSize: 11, fontWeight: 700, color: lc, background: `${lc}1a`, border: `1px solid ${lc}33`, borderRadius: 6, padding: '0 6px', fontVariantNumeric: 'tabular-nums' }}>{fmt(m.rate, 0)}%</span>
|
||||
<span style={{ fontSize: 11.5, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{m.gap}</span>
|
||||
</div>
|
||||
)}
|
||||
<SecRow label={t.agent.secStatus} text={turn.status} tk={tk} />
|
||||
<SecRow label={t.agent.secStance} text={turn.stance} tk={tk} color={lc} />
|
||||
<SecRow label={t.agent.secProposal} text={turn.proposal} tk={tk} color={tk.accent} />
|
||||
{turn.handoff && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: tk.textMuted }}>
|
||||
<ArrowRight size={11} color={tk.accent} style={{ flexShrink: 0 }} />
|
||||
{t.agent.handoff} →
|
||||
<span style={{ color: tk.accent, fontWeight: 700 }}>{turn.handoff}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 牵头结论卡:结论 headline + 成员要点 + 研判数据条 + 联合行动清单 */
|
||||
function LeadCard({ turn, tk, t, time }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string }) {
|
||||
const j = turn.judge;
|
||||
const lc = j ? levelColor(j.level, tk) : tk.accent;
|
||||
const marks = ['①', '②', '③'];
|
||||
return (
|
||||
<div className="content-reveal" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
|
||||
<div style={{ maxWidth: '94%', minWidth: 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
|
||||
<span style={{ width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0, background: `linear-gradient(135deg, ${tk.accent}, ${tk.info})` }}>
|
||||
<Sparkles size={11} color={tk.onAccent} />
|
||||
</span>
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tk.accent, flexShrink: 0 }}>{turn.name}</span>
|
||||
{turn.tag && <span style={{ fontSize: 10.5, color: tk.accent, padding: '0 6px', borderRadius: 7, border: `1px solid ${tk.borderAccent}`, background: tk.accentBg, whiteSpace: 'nowrap' }}>{turn.tag}</span>}
|
||||
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums' }}>{time}</span>
|
||||
</div>
|
||||
<div style={{ background: tk.accentBg, border: `1px solid ${tk.borderAccent}`, borderRadius: '4px 12px 12px 12px', padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 9, boxShadow: `0 0 0 1px ${tk.accent}1f` }}>
|
||||
{turn.conclusion && (
|
||||
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{ flex: '0 0 auto', fontSize: 10.5, fontWeight: 700, color: tk.accent, background: `${tk.accent}1a`, border: `1px solid ${tk.borderAccent}`, borderRadius: 6, padding: '1px 6px', marginTop: 1 }}>{t.agent.concl}</span>
|
||||
<span style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.6, color: tk.text, minWidth: 0 }}>{turn.conclusion}</span>
|
||||
</div>
|
||||
)}
|
||||
{!!turn.summary?.length && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.keypoints}</span>
|
||||
{turn.summary.map((srow, i) => (
|
||||
<div key={i} style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{ width: 5, height: 5, borderRadius: 5, background: tk.accent, flex: '0 0 5px', marginTop: 6 }} />
|
||||
<span style={{ fontSize: 12, color: tk.text, fontWeight: 600, flexShrink: 0 }}>{srow.name}</span>
|
||||
<span style={{ fontSize: 12, color: tk.textSub, minWidth: 0 }}>{srow.point}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{j && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.judgeLabel}</span>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '6px 10px', borderRadius: 8, background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}` }}>
|
||||
<span style={{ fontSize: 20, fontWeight: 800, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', lineHeight: 1 }}>{fmt(j.rate, 0)}%</span>
|
||||
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: tk.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{j.label}{j.gap ? ` · ${j.gap}` : ''}</span>
|
||||
<span style={{ fontSize: 11, fontWeight: 700, color: lc, background: `${lc}1a`, border: `1px solid ${lc}33`, borderRadius: 6, padding: '1px 7px', whiteSpace: 'nowrap' }}>{j.verdict}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!!turn.actions?.length && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.actionsLabel}</span>
|
||||
{turn.actions.map((a, i) => (
|
||||
<div key={i} style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{ flex: '0 0 auto', fontSize: 12, color: tk.accent, fontWeight: 700, lineHeight: 1.5 }}>{marks[i] ?? '·'}</span>
|
||||
<span style={{ fontSize: 12, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>
|
||||
<span style={{ color: tk.text, fontWeight: 600 }}>{a.owner}</span>
|
||||
<span style={{ color: tk.textMuted }}>({a.role})</span> {a.action}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AgentDock({ staff, chat, team, onDismissTeam, onLocateSO, onOpenOntology, height, onToggle, tall, onToggleTall }: AgentDockProps) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
/* 会话状态机在父级:本组件只管渲染与滚动,进出本体舞台都不会丢掉对话历史 */
|
||||
const { msgs, pending, thinking, busy, draft, setDraft, ask, reset } = chat;
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const onDuty = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
|
||||
const nameOf = (s: DigitalStaff) => (s.name_zh);
|
||||
|
||||
/* 新消息、思考步骤逐条揭示、高度变化都要贴底:对话区高度有限,
|
||||
用户不该往下翻找刚出现的回答卡 */
|
||||
useEffect(() => {
|
||||
const el = listRef.current;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}, [msgs, pending, thinking, height]);
|
||||
|
||||
const expanded = height > 120;
|
||||
const dotColor = (s: DigitalStaff) => alertColor(s.status === 'alert' ? 'red' : 'green', tokens);
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
flexShrink: 0, position: 'relative', zIndex: 2,
|
||||
background: tokens.panelBgAlt, borderRadius: '0 0 16px 16px',
|
||||
display: 'flex', flexDirection: 'column', overflow: 'hidden', height,
|
||||
transition: 'height 0.28s cubic-bezier(0.22,1,0.36,1)',
|
||||
}}>
|
||||
{/* 与上方工作区的分隔饰条:中央亮渐变主线 + 下溢光晕 + 菱形饰点,比 1px 实线更清晰且有仪式感 */}
|
||||
<div style={{ flexShrink: 0, position: 'relative', height: 9 }}>
|
||||
<div style={{
|
||||
position: 'absolute', left: 0, right: 0, top: 3, height: 2,
|
||||
background: `linear-gradient(90deg, transparent, ${tokens.accent}55 15%, ${tokens.accent}b3 50%, ${tokens.accent}55 85%, transparent)`,
|
||||
}} />
|
||||
<div style={{
|
||||
position: 'absolute', left: 0, right: 0, top: 5, height: 4,
|
||||
background: `linear-gradient(to bottom, ${tokens.accentGlow}, transparent)`,
|
||||
}} />
|
||||
<div style={{
|
||||
position: 'absolute', left: '50%', top: 4, width: 7, height: 7,
|
||||
transform: 'translate(-50%, -50%) rotate(45deg)',
|
||||
background: tokens.accent, boxShadow: `0 0 8px ${tokens.accentGlow}`,
|
||||
}} />
|
||||
<div style={{ position: 'absolute', left: '12%', top: 4, width: 3, height: 3, transform: 'translate(-50%, -50%) rotate(45deg)', background: `${tokens.accent}88` }} />
|
||||
<div style={{ position: 'absolute', left: '88%', top: 4, width: 3, height: 3, transform: 'translate(-50%, -50%) rotate(45deg)', background: `${tokens.accent}88` }} />
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', flexShrink: 0 }}>
|
||||
<span style={{
|
||||
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
|
||||
background: `linear-gradient(135deg, ${tokens.accent}, ${tokens.info})`,
|
||||
}}>
|
||||
<Bot size={13} color={tokens.onAccent} strokeWidth={2.2} />
|
||||
</span>
|
||||
<span style={{ color: tokens.text, fontSize: 14.5, fontWeight: 700, letterSpacing: '0.03em' }}>{t.agent.title}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||
{onDuty.slice(0, 4).map(s => (
|
||||
<span key={s.code} title={nameOf(s)} style={{
|
||||
width: 7, height: 7, borderRadius: '50%', background: dotColor(s),
|
||||
boxShadow: `0 0 6px ${dotColor(s)}`,
|
||||
}} />
|
||||
))}
|
||||
</span>
|
||||
<button
|
||||
onClick={reset}
|
||||
title={t.agent.clear}
|
||||
className="ghost-btn"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 4, color: tokens.textMuted, fontSize: 12, border: 'none', background: 'transparent', cursor: 'pointer', padding: '2px 6px' }}
|
||||
>
|
||||
<Ban size={12} />{t.agent.clear}
|
||||
</button>
|
||||
<button
|
||||
onClick={onToggleTall}
|
||||
title={tall ? t.agent.tallOff : t.agent.tall}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'grid', placeItems: 'center', width: 24, height: 24, borderRadius: 8, cursor: 'pointer', flexShrink: 0,
|
||||
color: tall ? tokens.onAccent : tokens.accent,
|
||||
background: tall ? tokens.accent : tokens.accentBg,
|
||||
border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
{tall ? <ChevronsDown size={13} /> : <ChevronsUp size={13} />}
|
||||
</button>
|
||||
<button
|
||||
onClick={onToggle}
|
||||
title={expanded ? t.agent.collapse : t.agent.expand}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 3, color: tokens.accent, fontSize: 12, fontWeight: 600,
|
||||
border: `1px solid ${tokens.borderAccent}`, background: tokens.accentBg, borderRadius: 12, padding: '2px 9px', cursor: 'pointer', flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{expanded ? <ChevronDown size={12} /> : <ChevronUp size={12} />}
|
||||
{expanded ? t.agent.collapse : t.agent.expand}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{team && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, margin: '0 14px 6px', padding: '5px 10px',
|
||||
borderRadius: 9, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`, flexShrink: 0,
|
||||
}}>
|
||||
<Users size={13} color={tokens.accent} style={{ flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.accent, flexShrink: 0 }}>{team.nameZh}</span>
|
||||
<span style={{ fontSize: 11.5, color: tokens.textMuted, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
· {team.memberCodes.length} 位专家 · {team.topicZh}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button
|
||||
onClick={onDismissTeam}
|
||||
title={t.team.dismiss}
|
||||
className="ghost-btn"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: tokens.textMuted, border: 'none', background: 'transparent', cursor: 'pointer', padding: '2px 5px', flexShrink: 0 }}
|
||||
>
|
||||
<Ban size={11} />{t.team.dismiss}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{expanded && (
|
||||
<>
|
||||
<div ref={listRef} className="space-scroll" style={{ flex: 1, overflowY: 'auto', padding: '2px 14px 0', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
|
||||
{/* 消息贴底:对话从输入框往上长,不留中段空洞(内容满时该占位自动压为 0,不影响滚动) */}
|
||||
<div style={{ flex: '1 0 0px', minHeight: 0 }} />
|
||||
{msgs.map(m => {
|
||||
/* 专家团就位播报:居中虚线卡,区别于专家发言 */
|
||||
if (m.kind === 'system') {
|
||||
return (
|
||||
<div key={m.id} className="content-reveal" style={{ display: 'flex', justifyContent: 'center', marginBottom: 8 }}>
|
||||
<div style={{
|
||||
maxWidth: '94%', padding: '7px 12px', borderRadius: 10, whiteSpace: 'pre-wrap', textAlign: 'center',
|
||||
background: tokens.accentBg, border: `1px dashed ${tokens.borderAccent}`,
|
||||
color: tokens.textSub, fontSize: 12.5, lineHeight: 1.6,
|
||||
}}>
|
||||
<span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5, color: tokens.accent, fontWeight: 700, marginBottom: 3 }}>
|
||||
<Radio size={11} />{m.name} · {m.tag}
|
||||
</span>
|
||||
{m.text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if ((m.kind === 'member' || m.kind === 'lead') && m.turn) {
|
||||
return m.kind === 'member'
|
||||
? <MemberCard key={m.id} turn={m.turn} tk={tokens} t={t} time={m.time} />
|
||||
: <LeadCard key={m.id} turn={m.turn} tk={tokens} t={t} time={m.time} />;
|
||||
}
|
||||
/* 单轮问答:折叠的思考过程条 + 规范回答卡(结论/关键数字/明细/依据/行动/来源) */
|
||||
if (m.role === 'ai' && m.answer) {
|
||||
return (
|
||||
<AskAnswerCard
|
||||
key={m.id} answer={m.answer} elapsed={m.elapsed ?? 0} tk={tokens} t={t} time={m.time} staff={m.staff}
|
||||
onLocate={so => onLocateSO?.(so)}
|
||||
onAsk={q => ask(q)}
|
||||
onOntology={() => onOpenOntology?.()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
const consult = m.kind === 'member' || m.kind === 'lead';
|
||||
const isLead = m.kind === 'lead';
|
||||
return (
|
||||
<div key={m.id} className={consult ? 'content-reveal' : undefined} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start', marginBottom: 8 }}>
|
||||
<div style={{ maxWidth: consult ? '90%' : '76%', minWidth: 0 }}>
|
||||
{consult && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
|
||||
<span style={{
|
||||
width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0,
|
||||
background: isLead ? `linear-gradient(135deg, ${tokens.accent}, ${tokens.info})` : tokens.cardBg,
|
||||
border: `1px solid ${isLead ? 'transparent' : tokens.border}`,
|
||||
}}>
|
||||
<User size={11} color={isLead ? tokens.onAccent : tokens.accent} />
|
||||
</span>
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: isLead ? tokens.accent : tokens.text, flexShrink: 0 }}>{m.name}</span>
|
||||
{m.tag && (
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, padding: '0 6px', borderRadius: 7, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160 }}>{m.tag}</span>
|
||||
)}
|
||||
{isLead && <Sparkles size={11} color={tokens.accent} style={{ flexShrink: 0 }} />}
|
||||
</div>
|
||||
)}
|
||||
<div style={{
|
||||
padding: '8px 12px', fontSize: 13.5, lineHeight: 1.65, whiteSpace: 'pre-wrap',
|
||||
borderRadius: m.role === 'user' ? '10px 10px 3px 10px' : '10px 10px 10px 3px',
|
||||
background: m.role === 'user' ? `${tokens.accent}22` : isLead ? tokens.accentBg : tokens.cardBg,
|
||||
border: `1px solid ${m.role === 'user' ? `${tokens.accent}44` : isLead ? tokens.borderAccent : tokens.border}`,
|
||||
color: m.role === 'user' ? tokens.text : tokens.textSub,
|
||||
boxShadow: isLead ? `0 0 0 1px ${tokens.accent}1f` : 'none',
|
||||
}}>{m.text}</div>
|
||||
<div style={{ display: 'flex', gap: 6, marginTop: 3, justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
|
||||
{m.staff && (
|
||||
<span style={{ color: m.role === 'user' ? tokens.textMuted : tokens.accent, fontSize: 11, display: 'flex', alignItems: 'center', gap: 3 }}>
|
||||
{m.role === 'ai' && <Sparkles size={10} />}{m.staff}
|
||||
</span>
|
||||
)}
|
||||
<span style={{ color: tokens.textMuted, fontSize: 11, fontVariantNumeric: 'tabular-nums' }}>{m.time}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{/* 思考中:已揭示的步骤逐条出现,未揭示的只显示当前这步在做什么 */}
|
||||
{pending && (
|
||||
<div style={{ marginBottom: 8 }}>
|
||||
<StepTrace steps={pending.answer.steps} revealed={pending.revealed} running tk={tokens} t={t} />
|
||||
</div>
|
||||
)}
|
||||
{thinking && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '6px 10px', background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 10, width: 'fit-content' }}>
|
||||
<span style={{ display: 'flex', gap: 3 }}>
|
||||
{[0, 1, 2].map(i => <i key={i} className="typing-dot" style={{ animationDelay: `${i * 0.16}s` }} />)}
|
||||
</span>
|
||||
<span style={{ color: tokens.textMuted, fontSize: 12 }}>{t.agent.thinking}…</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: 6, padding: '0 14px 6px', flexWrap: 'wrap', flexShrink: 0 }}>
|
||||
{SUGGESTED.map(q => (
|
||||
<button key={q} onClick={() => ask(q)} disabled={busy} className="ghost-btn" style={{
|
||||
color: busy ? tokens.textMuted : tokens.textSub, fontSize: 12, border: `1px solid ${tokens.border}`, background: tokens.cardBg,
|
||||
borderRadius: 20, padding: '4px 11px', cursor: busy ? 'default' : 'pointer', whiteSpace: 'nowrap',
|
||||
opacity: busy ? 0.55 : 1,
|
||||
}}>{q}</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px 10px', flexShrink: 0 }}>
|
||||
<Layers size={14} color={tokens.textMuted} style={{ flexShrink: 0 }} />
|
||||
<input
|
||||
value={draft}
|
||||
onChange={e => setDraft(e.target.value)}
|
||||
onKeyDown={e => { if (e.key === 'Enter') ask(draft); }}
|
||||
onFocus={() => { if (!expanded) onToggle(); }}
|
||||
placeholder={t.agent.placeholder}
|
||||
style={{
|
||||
flex: 1, minWidth: 0, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
|
||||
borderRadius: 10, padding: '8px 12px', color: tokens.text, fontSize: 13.5, outline: 'none',
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
onClick={() => ask(draft)}
|
||||
disabled={!draft.trim() || busy}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, padding: '7px 14px', borderRadius: 10, border: 'none',
|
||||
background: !draft.trim() || busy ? tokens.border : tokens.accent,
|
||||
color: tokens.onAccent, fontSize: 13, fontWeight: 700,
|
||||
cursor: !draft.trim() || busy ? 'default' : 'pointer', transition: 'background 0.18s ease', flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
<Send size={13} />{t.agent.send}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Building2, Search, ShoppingCart, X } from 'lucide-react';
|
||||
import PanelShell, { CountBadge } from './layout/PanelShell';
|
||||
import { AutoScrollProvider, AutoScrollToggle } from './layout/AutoScroll';
|
||||
import { LEFT_MOTION } from '../hooks/useAutoScroll';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import SalesOrderList, { filterSalesOrders } from './demand/SalesOrderList';
|
||||
import CustomerList, { buildCustomers, filterCustomers } from './demand/CustomerList';
|
||||
import { salesOrders } from '../data/ibp';
|
||||
|
||||
type TabKey = 'so' | 'cus';
|
||||
|
||||
interface Props {
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
/** 当前选中的销售订单号:本页两个页签与右侧供应栏共用同一联动游标 */
|
||||
selectedSO: string | null;
|
||||
onSelectSO: (so: string | null) => void;
|
||||
}
|
||||
|
||||
const TABS: { key: TabKey; label: string; short: string; icon: typeof ShoppingCart; placeholder: string }[] = [
|
||||
{ key: 'so', label: '销售订单', short: '订单', icon: ShoppingCart, placeholder: '搜索订单号 / 客户 / 产品编码' },
|
||||
{ key: 'cus', label: '客户资料', short: '客户', icon: Building2, placeholder: '搜索客户编码 / 简称 / 分类 / 部门' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 左侧需求栏:销售订单与客户资料两个页签共用一块弧板,
|
||||
* 搜索关键词、展开态与选中订单联动在两者之间保持同一份状态。
|
||||
*/
|
||||
export default function DemandPanel({ expanded, onToggle, selectedSO, onSelectSO }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const [tab, setTab] = useState<TabKey>('so');
|
||||
/* 外部定位(对话卡的「定位到订单」/ 本体页明细行)把订单选中时切回销售订单页签,
|
||||
否则停在客户资料页签会让用户以为点了没反应 */
|
||||
const prevSO = useRef(selectedSO);
|
||||
useEffect(() => {
|
||||
if (selectedSO && selectedSO !== prevSO.current) setTab('so');
|
||||
prevSO.current = selectedSO;
|
||||
}, [selectedSO]);
|
||||
const [query, setQuery] = useState('');
|
||||
/* 卡片多到一屏装不下时自动缓慢下滚;标题栏按钮可关闭,页签之间共用这一个开关 */
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
/* 徽标数与页签内容走同一组纯函数,标题数字不会和列表条数打架 */
|
||||
const count = useMemo(() => {
|
||||
const q = query.trim();
|
||||
if (tab === 'so') return filterSalesOrders(salesOrders, q).length;
|
||||
return filterCustomers(buildCustomers(selectedSO), q).length;
|
||||
}, [tab, query, selectedSO]);
|
||||
|
||||
const segBtn = (active: boolean) => ({
|
||||
display: 'flex' as const, alignItems: 'center' as const, justifyContent: 'center' as const,
|
||||
gap: 5, flex: 1, minWidth: 0, padding: '5px 8px', borderRadius: 7,
|
||||
fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const,
|
||||
background: active ? tokens.accent : 'transparent',
|
||||
color: active ? tokens.onAccent : tokens.textMuted,
|
||||
border: `1px solid ${active ? tokens.accent : tokens.border}`,
|
||||
});
|
||||
|
||||
const current = TABS.find(x => x.key === tab)!;
|
||||
const Icon = current.icon;
|
||||
|
||||
return (
|
||||
<PanelShell
|
||||
side="left" expanded={expanded} onToggle={onToggle}
|
||||
widthCollapsed={268} widthExpanded={468}
|
||||
icon={<Icon size={16} />}
|
||||
title={current.label}
|
||||
badge={<CountBadge n={count} />}
|
||||
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll(v => !v)} expanded={expanded} />}
|
||||
animClass="space-animate-left"
|
||||
tabs={
|
||||
<>
|
||||
{TABS.map(x => (
|
||||
/* 收起态宽度只够两个字:页签用短标签,避免挤成一列竖排 */
|
||||
<button key={x.key} style={segBtn(tab === x.key)} onClick={() => setTab(x.key)}>
|
||||
{expanded ? x.label : x.short}
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{/* 搜索:两个页签共用,占位提示随页签切换 */}
|
||||
<div style={{ position: 'relative', marginBottom: 10, flex: '0 0 auto' }}>
|
||||
<Search size={14} style={{ position: 'absolute', left: 10, top: 10, color: tokens.textMuted }} />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={current.placeholder}
|
||||
style={{
|
||||
width: '100%', padding: '8px 30px 8px 31px', fontSize: 13.5, borderRadius: 9,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, color: tokens.text,
|
||||
outline: 'none',
|
||||
}}
|
||||
/>
|
||||
{query && (
|
||||
<button onClick={() => setQuery('')} style={{ position: 'absolute', right: 9, top: 11, color: tokens.textMuted, cursor: 'pointer', background: 'none', border: 'none' }}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AutoScrollProvider value={{ enabled: autoScroll, cfg: LEFT_MOTION }}>
|
||||
{tab === 'so' && (
|
||||
<SalesOrderList
|
||||
query={query}
|
||||
expanded={expanded}
|
||||
selectedSO={selectedSO}
|
||||
onSelectSO={onSelectSO}
|
||||
/>
|
||||
)}
|
||||
{tab === 'cus' && (
|
||||
<CustomerList
|
||||
query={query}
|
||||
filterSO={selectedSO}
|
||||
onClearFilter={() => onSelectSO(null)}
|
||||
/* 点客户=带着它的编码切到销售订单页签,只看这家下的单 */
|
||||
onPickCustomer={code => { setQuery(code); setTab('so'); }}
|
||||
/>
|
||||
)}
|
||||
</AutoScrollProvider>
|
||||
</PanelShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { ArrowLeft, Bot, Check, ChevronDown, MessagesSquare, Radar, Target, Users } from 'lucide-react';
|
||||
import PanelShell, { PanelBody, CountBadge } from './layout/PanelShell';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import type { DigitalStaff, MetricNode } from '../data/sqlite';
|
||||
import { customTeam, presetTeams } from '../lib/teams';
|
||||
import type { ExpertTeam } from '../lib/teams';
|
||||
|
||||
interface Props {
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
staff: DigitalStaff[];
|
||||
byCode: Map<string, MetricNode>;
|
||||
selected: string;
|
||||
onViewMetric: (code: string) => void;
|
||||
onWake: (s: DigitalStaff) => void;
|
||||
/** 专家团:当前已就位的团队 + 组建回调 */
|
||||
activeTeam: ExpertTeam | null;
|
||||
onConvene: (t: ExpertTeam) => void;
|
||||
}
|
||||
|
||||
type Status = DigitalStaff['status'];
|
||||
|
||||
export default function DigitalStaffPanel({
|
||||
expanded, onToggle, staff, byCode, selected, onViewMetric, onWake, activeTeam, onConvene,
|
||||
}: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
const [filter, setFilter] = useState<Status | 'all'>('all');
|
||||
const [open, setOpen] = useState<string | null>('METRIX');
|
||||
const [view, setView] = useState<'staff' | 'team'>('staff'); // 数字员工列表 / 专家团组建
|
||||
const [selCodes, setSelCodes] = useState<string[]>([]); // 自由勾选的成员(首位为牵头)
|
||||
const [presetKey, setPresetKey] = useState<string | null>(null); // 当前选中的预设团
|
||||
const [tick, setTick] = useState(0);
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const hoverRef = useRef(false); // 鼠标进入列表即暂停,方便点卡
|
||||
const coolRef = useRef(0); // 滚轮手动滚动后的冷却截止时刻
|
||||
|
||||
const statusMeta = (s: Status) => ({
|
||||
working: { label: t.staff.busy, color: tokens.accent },
|
||||
idle: { label: t.staff.idle, color: tokens.textMuted },
|
||||
alert: { label: t.staff.alert, color: tokens.danger },
|
||||
offline: { label: t.staff.offline, color: tokens.warning },
|
||||
}[s]);
|
||||
|
||||
const list = useMemo(() => (filter === 'all' ? staff : staff.filter(s => s.status === filter)), [staff, filter]);
|
||||
const online = staff.filter(s => s.status !== 'offline').length;
|
||||
const totalTasks = staff.reduce((a, s) => a + s.tasks_today, 0);
|
||||
const avgConf = staff.filter(s => s.confidence > 0).reduce((a, s, _i, arr) => a + s.confidence / arr.length, 0);
|
||||
const escalations = staff.filter(s => s.status === 'alert').length;
|
||||
|
||||
// 动作轮播:只轮播在岗员工,避免"停用"卡片抢镜
|
||||
const feed = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
|
||||
useEffect(() => {
|
||||
if (feed.length < 2) return;
|
||||
const id = setInterval(() => setTick(v => (v + 1) % feed.length), 3400);
|
||||
return () => clearInterval(id);
|
||||
}, [feed.length]);
|
||||
const active = feed.length ? feed[tick % feed.length] : null;
|
||||
|
||||
// 鼠标进入 / 滚轮手动滚动时暂停自动滚动,避免和用户抢滚动条
|
||||
useEffect(() => {
|
||||
const el = scrollRef.current;
|
||||
if (!el) return;
|
||||
const onWheel = () => { coolRef.current = performance.now() + 2200; };
|
||||
const onEnter = () => { hoverRef.current = true; };
|
||||
const onLeave = () => { hoverRef.current = false; };
|
||||
el.addEventListener('wheel', onWheel, { passive: true });
|
||||
el.addEventListener('pointerenter', onEnter);
|
||||
el.addEventListener('pointerleave', onLeave);
|
||||
return () => {
|
||||
el.removeEventListener('wheel', onWheel);
|
||||
el.removeEventListener('pointerenter', onEnter);
|
||||
el.removeEventListener('pointerleave', onLeave);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 自动滚动:营造"员工一个个在干活"的现场感;到底停留 1.4s 后回顶循环。
|
||||
// pos 是浮点累加器:26px/s 摊到 120Hz 每帧只有 0.22px,直接读改写 scrollTop 会被量化舍入吞掉而停摆
|
||||
useEffect(() => {
|
||||
let raf = 0;
|
||||
let last = performance.now();
|
||||
let pos = scrollRef.current ? scrollRef.current.scrollTop : 0;
|
||||
let phase: 'down' | 'holdB' | 'up' | 'holdT' = 'down';
|
||||
let until = 0;
|
||||
const step = (now: number) => {
|
||||
raf = requestAnimationFrame(step);
|
||||
const el = scrollRef.current;
|
||||
const dt = Math.min(0.05, (now - last) / 1000);
|
||||
last = now;
|
||||
if (!el || el.scrollHeight <= el.clientHeight + 4) return;
|
||||
// 被门控暂停期间以真实 scrollTop 为准(用户可能滚轮动过),恢复时从那里续跑
|
||||
if (hoverRef.current || now < coolRef.current) { pos = el.scrollTop; return; }
|
||||
if (phase === 'down') {
|
||||
if (pos + el.clientHeight >= el.scrollHeight - 2) { phase = 'holdB'; until = now + 1400; pos = el.scrollTop; }
|
||||
else { pos += 26 * dt; el.scrollTop = pos; }
|
||||
} else if (phase === 'holdB') {
|
||||
pos = el.scrollTop;
|
||||
if (now >= until) phase = 'up';
|
||||
} else if (phase === 'up') {
|
||||
pos -= pos * Math.min(1, dt * 5);
|
||||
el.scrollTop = pos;
|
||||
if (pos <= 0.5) { el.scrollTop = 0; pos = 0; phase = 'holdT'; until = now + 500; }
|
||||
} else {
|
||||
pos = el.scrollTop;
|
||||
if (now >= until) phase = 'down';
|
||||
}
|
||||
};
|
||||
raf = requestAnimationFrame(step);
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, []);
|
||||
|
||||
const chip = (key: Status | 'all', label: string, color?: string) => {
|
||||
const on = filter === key;
|
||||
return (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setFilter(key)}
|
||||
style={{
|
||||
fontSize: 11.5, padding: '2px 7px', borderRadius: 9, cursor: 'pointer', lineHeight: '17px', whiteSpace: 'nowrap' as const,
|
||||
background: on ? `${color ?? tokens.accent}22` : 'transparent',
|
||||
color: on ? (color ?? tokens.accent) : tokens.textMuted,
|
||||
border: `1px solid ${on ? `${color ?? tokens.accent}55` : tokens.border}`,
|
||||
}}
|
||||
>{label}</button>
|
||||
);
|
||||
};
|
||||
|
||||
const presets = useMemo(() => presetTeams(), []);
|
||||
// 预设团语义色 → 主题 token,让五张卡片有各自的色彩识别(不硬编码色值)
|
||||
const toneColor = (tone: ExpertTeam['tone']) =>
|
||||
({ success: tokens.success, danger: tokens.danger, info: tokens.info, warning: tokens.warning, accent: tokens.accent }[tone] ?? tokens.accent);
|
||||
const nameOfStaff = (x: DigitalStaff) => (x.name_zh);
|
||||
|
||||
// 选中一个预设团:填充成员并停留在组建视图,便于直接发起或再微调
|
||||
const pickPreset = (tm: ExpertTeam) => { setPresetKey(tm.id); setSelCodes(tm.memberCodes); };
|
||||
// 勾选/取消一个智能体:脱离预设,转为自定义团
|
||||
const toggleCode = (code: string) => {
|
||||
setPresetKey(null);
|
||||
setSelCodes(prev => (prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]));
|
||||
};
|
||||
const convene = () => {
|
||||
if (selCodes.length < 2) return;
|
||||
const preset = presetKey ? presets.find(x => x.id === presetKey) : null;
|
||||
const tm = preset ?? customTeam(selCodes);
|
||||
if (tm) onConvene(tm);
|
||||
};
|
||||
const openTeamView = () => { if (!expanded) onToggle(); setView('team'); };
|
||||
|
||||
return (
|
||||
<PanelShell
|
||||
side="right" expanded={expanded} onToggle={onToggle}
|
||||
widthCollapsed={268} widthExpanded={468}
|
||||
icon={expanded ? (view === 'team' ? <Users size={15} /> : <Bot size={15} />) : undefined}
|
||||
title={view === 'team' ? t.team.panel : t.staff.title}
|
||||
badge={view === 'team' ? <CountBadge n={selCodes.length} /> : <CountBadge n={`${online}/${staff.length}`} />}
|
||||
extra={
|
||||
<>
|
||||
<button
|
||||
onClick={() => (view === 'team' ? setView('staff') : openTeamView())}
|
||||
title={t.team.entry}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
|
||||
width: 22, height: 22, borderRadius: 5, cursor: 'pointer',
|
||||
color: view === 'team' ? tokens.onAccent : tokens.accent,
|
||||
background: view === 'team' ? tokens.accent : `${tokens.accent}1f`,
|
||||
border: `1px solid ${view === 'team' ? tokens.accent : `${tokens.accent}55`}`,
|
||||
}}
|
||||
>
|
||||
<Users size={12} />
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
animClass="space-animate-right"
|
||||
>
|
||||
{view === 'staff' && (
|
||||
<>
|
||||
<div style={{ display: 'flex', gap: 3, flexWrap: 'wrap', marginBottom: 8, flex: '0 0 auto' }}>
|
||||
{chip('all', t.staff.filterAll)}
|
||||
{chip('working', t.staff.busy, tokens.accent)}
|
||||
{chip('idle', t.staff.idle)}
|
||||
{chip('alert', t.staff.alert, tokens.danger)}
|
||||
{chip('offline', t.staff.offline, tokens.warning)}
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, marginBottom: 8, flex: '0 0 auto',
|
||||
background: tokens.border, border: `1px solid ${tokens.border}`, borderRadius: 8, overflow: 'hidden',
|
||||
}}>
|
||||
{[
|
||||
{ k: t.staff.online, v: String(online) },
|
||||
{ k: t.staff.tasks, v: String(totalTasks) },
|
||||
{ k: t.staff.confidence, v: `${avgConf.toFixed(0)}%` },
|
||||
{ k: t.staff.alert, v: String(escalations), warn: escalations > 0 },
|
||||
].map(c => (
|
||||
<div key={c.k} style={{ background: tokens.panelBgAlt, padding: '5px 4px', textAlign: 'center' }}>
|
||||
<div style={{ fontSize: 17, fontWeight: 800, color: c.warn ? tokens.danger : tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.15 }}>{c.v}</div>
|
||||
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 1 }}>{c.k}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<PanelBody ref={scrollRef}>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>{t.staff.emptyFilter}</div>
|
||||
)}
|
||||
{list.map((s, i) => {
|
||||
const meta = statusMeta(s.status);
|
||||
const isOpen = open === s.code;
|
||||
const bound = byCode.get(s.bound_metric);
|
||||
const nm = (n: MetricNode | undefined) => (n ? (n.name_zh) : s.bound_metric);
|
||||
return (
|
||||
<div
|
||||
key={s.code}
|
||||
className="card-in"
|
||||
style={{
|
||||
animationDelay: `${i * 45}ms`,
|
||||
border: `1px solid ${s.status === 'alert' ? `${tokens.danger}66` : isOpen ? tokens.borderAccent : tokens.border}`,
|
||||
background: isOpen ? tokens.cardBg : tokens.panelBgAlt,
|
||||
borderRadius: 10, marginBottom: 7, overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 9px', cursor: 'pointer' }}
|
||||
onClick={() => {
|
||||
// 收起态没有详情空间:先展开面板再开详情,避免"点了没反应"
|
||||
if (!expanded) { onToggle(); setOpen(s.code); }
|
||||
else setOpen(isOpen ? null : s.code);
|
||||
}}
|
||||
>
|
||||
<span
|
||||
className={s.status === 'working' || s.status === 'alert' ? 'dot-blink' : undefined}
|
||||
style={{ width: 7, height: 7, borderRadius: 7, background: meta.color, flex: '0 0 7px', boxShadow: `0 0 7px ${meta.color}88` }}
|
||||
/>
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
|
||||
<span
|
||||
title={s.name_zh}
|
||||
style={{ fontSize: 14.5, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}
|
||||
>
|
||||
{s.name_zh}
|
||||
</span>
|
||||
{/* 收起态 268px 放不下「9 字名 + code」,code 只在展开态显示 */}
|
||||
{expanded && (
|
||||
<span style={{ fontSize: 10, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace' }}>{s.code}</span>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: 11.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{s.role_zh}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'right', flex: '0 0 auto' }}>
|
||||
<div style={{ fontSize: 11.5, color: meta.color, fontWeight: 600 }}>{meta.label}</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.tasks_today} {t.staff.tasks}</div>
|
||||
</div>
|
||||
<ChevronDown size={13} style={{ color: tokens.textMuted, transform: `rotate(${isOpen ? 180 : 0}deg)`, transition: 'transform 0.2s', flex: '0 0 13px' }} />
|
||||
</div>
|
||||
|
||||
<div style={{ padding: '0 9px 6px' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
|
||||
<div style={{ flex: 1, height: 3, borderRadius: 3, background: `${tokens.border}`, overflow: 'hidden' }}>
|
||||
<div style={{ width: `${s.load_pct}%`, height: '100%', background: meta.color, transition: 'width 0.4s ease' }} />
|
||||
</div>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', width: 34, textAlign: 'right' }}>{s.load_pct}%</span>
|
||||
</div>
|
||||
{expanded && (
|
||||
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
<Radar size={9} style={{ verticalAlign: -1, marginRight: 3, color: meta.color }} />
|
||||
{s.cur_zh}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isOpen && expanded && (
|
||||
<div style={{ padding: '2px 9px 9px', borderTop: `1px dashed ${tokens.border}`, marginTop: 2 }}>
|
||||
<Row label={t.staff.skills} value={s.skill_zh} tokens={tokens} text={tokens.textSub} />
|
||||
<Row label={t.staff.success} value={`${s.success_rate}%`} tokens={tokens} text={tokens.text} mono />
|
||||
<Row label={t.staff.confidence} value={`${s.confidence}%`} tokens={tokens} text={tokens.text} mono />
|
||||
<Row label={t.staff.lastRun} value={s.last_run} tokens={tokens} text={tokens.textMuted} />
|
||||
<Row label={t.staff.current} value={s.cur_zh} tokens={tokens} text={tokens.textSub} />
|
||||
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
|
||||
<button
|
||||
onClick={() => onViewMetric(s.bound_metric)}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
|
||||
padding: '4px 6px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
|
||||
border: `1px solid ${selected === s.bound_metric ? tokens.accent : tokens.border}`,
|
||||
color: tokens.accent, background: tokens.accentBg,
|
||||
}}
|
||||
>
|
||||
<Target size={11} />{nm(bound)}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => onWake(s)}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
|
||||
padding: '4px 10px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
|
||||
border: `1px solid ${tokens.accent}`, color: tokens.onAccent, background: tokens.accent,
|
||||
opacity: s.status === 'offline' ? 0.45 : 1,
|
||||
}}
|
||||
>
|
||||
<MessagesSquare size={11} />{t.staff.wake}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</PanelBody>
|
||||
|
||||
{active && (
|
||||
<div style={{
|
||||
flex: '0 0 auto', marginTop: 6, padding: '6px 9px', borderRadius: 9,
|
||||
background: tokens.accentBg, border: `1px solid ${tokens.border}`,
|
||||
display: 'flex', alignItems: 'center', gap: 7, minWidth: 0,
|
||||
}}>
|
||||
<Radar size={13} style={{ color: tokens.accent, flex: '0 0 13px' }} className="dot-blink" />
|
||||
<div key={active.code} className="content-reveal" style={{ minWidth: 0 }}>
|
||||
<div style={{ fontSize: 11.5, color: tokens.accent, fontWeight: 700 }}>
|
||||
{active.name_zh} · {active.last_run}
|
||||
</div>
|
||||
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{active.cur_zh}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{view === 'team' && (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1, gap: 7 }}>
|
||||
<button
|
||||
onClick={() => setView('staff')}
|
||||
className="ghost-btn"
|
||||
style={{ display: 'flex', alignItems: 'center', gap: 5, alignSelf: 'flex-start', fontSize: 12, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '2px 4px', flex: '0 0 auto' }}
|
||||
>
|
||||
<ArrowLeft size={13} />{t.team.back}
|
||||
</button>
|
||||
|
||||
<div style={{ flex: '0 0 auto' }}>
|
||||
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub, letterSpacing: '0.02em' }}>{t.team.presetTitle}</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{t.team.presetHint}</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: '0 0 auto' }}>
|
||||
{presets.map(tm => {
|
||||
const on = presetKey === tm.id;
|
||||
const isActive = activeTeam?.id === tm.id;
|
||||
const c = toneColor(tm.tone);
|
||||
return (
|
||||
<button
|
||||
key={tm.id} onClick={() => pickPreset(tm)} className="ghost-btn"
|
||||
style={{
|
||||
textAlign: 'left', padding: '8px 10px', borderRadius: 10, cursor: 'pointer',
|
||||
background: on ? `${c}17` : `linear-gradient(135deg, ${c}0f, ${tokens.panelBgAlt} 60%)`,
|
||||
border: `1px solid ${on ? `${c}88` : `${c}30`}`,
|
||||
boxShadow: on ? `0 0 0 1px ${c}33, 0 2px 12px ${c}22` : 'none',
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
|
||||
<span style={{
|
||||
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
|
||||
background: `${c}1f`, border: `1px solid ${c}44`, color: c,
|
||||
}}>
|
||||
<Users size={12} />
|
||||
</span>
|
||||
<span style={{ fontSize: 13.5, fontWeight: 700, color: on ? c : tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tm.nameZh}</span>
|
||||
<span style={{ fontSize: 10.5, color: c, marginLeft: 'auto', flexShrink: 0, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{tm.memberCodes.length} 位</span>
|
||||
{isActive && <Check size={13} color={c} style={{ flexShrink: 0 }} />}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 4, lineHeight: 1.45, paddingLeft: 29 }}>{tm.topicZh}</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginTop: 2 }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub }}>{t.team.customTitle}</span>
|
||||
{selCodes.length > 0 && (
|
||||
<button
|
||||
onClick={() => { setSelCodes([]); setPresetKey(null); }}
|
||||
className="ghost-btn"
|
||||
style={{ marginLeft: 'auto', fontSize: 11, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '1px 4px' }}
|
||||
>{t.team.clearSel}</button>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, lineHeight: 1.5, flex: '0 0 auto' }}>{t.team.customHint}</div>
|
||||
|
||||
<PanelBody>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
|
||||
{feed.map(x => {
|
||||
const idx = selCodes.indexOf(x.code);
|
||||
const on = idx >= 0;
|
||||
return (
|
||||
<button
|
||||
key={x.code} onClick={() => toggleCode(x.code)}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11.5, padding: '3px 8px', borderRadius: 16, cursor: 'pointer',
|
||||
background: on ? `${tokens.accent}22` : 'transparent',
|
||||
color: on ? tokens.accent : tokens.textSub,
|
||||
border: `1px solid ${on ? `${tokens.accent}66` : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{on && (
|
||||
<span style={{ width: 14, height: 14, borderRadius: 4, background: tokens.accent, color: tokens.onAccent, display: 'grid', placeItems: 'center', fontSize: 9, fontWeight: 800, flexShrink: 0 }}>{idx + 1}</span>
|
||||
)}
|
||||
{nameOfStaff(x)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</PanelBody>
|
||||
|
||||
<button
|
||||
onClick={convene} disabled={selCodes.length < 2}
|
||||
style={{
|
||||
flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
|
||||
padding: '9px 12px', borderRadius: 10, border: 'none', fontSize: 13, fontWeight: 700,
|
||||
cursor: selCodes.length < 2 ? 'default' : 'pointer',
|
||||
background: selCodes.length < 2 ? tokens.border : tokens.accent,
|
||||
color: selCodes.length < 2 ? tokens.textMuted : tokens.onAccent,
|
||||
boxShadow: selCodes.length >= 2 ? `0 2px 10px ${tokens.accent}40` : 'none',
|
||||
}}
|
||||
>
|
||||
<Users size={14} />
|
||||
{selCodes.length < 2 ? t.team.needTwo : t.team.conveneN.replace('{n}', String(selCodes.length))}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</PanelShell>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, value, tokens, text, mono }: {
|
||||
label: string; value: string; tokens: { textMuted: string }; text: string; mono?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<div style={{ display: 'flex', gap: 8, fontSize: 11.5, lineHeight: '19px', minWidth: 0 }}>
|
||||
<span style={{ color: tokens.textMuted, flex: '0 0 64px' }}>{label}</span>
|
||||
<span style={{
|
||||
color: text, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
|
||||
...(mono ? { fontFamily: 'ui-monospace, monospace', fontVariantNumeric: 'tabular-nums' } : {}),
|
||||
}}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { AlarmClock, AlertOctagon, ClipboardList, ShoppingCart, TrendingUp, Moon, Sun, FileWarning } from 'lucide-react';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import { materialBalance, purchaseOrders, salesOrders } from '../data/ibp';
|
||||
import { CURRENT_PERIOD, periodLabel } from '../lib/time';
|
||||
import { wan } from '../lib/money';
|
||||
|
||||
interface HeaderProps {
|
||||
/** 全局时间游标:仅用于右上角「数据期」标注,KPI 取自内置业务单据快照 */
|
||||
period: number;
|
||||
}
|
||||
|
||||
/** 单据金额合计(元);先按 2 位小数收敛浮点误差,展示口径交给 lib/money */
|
||||
const sum = <T,>(rows: T[], pick: (r: T) => number) =>
|
||||
+rows.reduce((acc, r) => acc + (pick(r) || 0), 0).toFixed(2);
|
||||
|
||||
export default function MecHeader({ period }: HeaderProps) {
|
||||
const { tokens, theme, toggleTheme } = useTheme();
|
||||
const { t } = useText();
|
||||
const [time, setTime] = useState(() => new Date());
|
||||
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setTime(new Date()), 1000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
const timeStr = `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}`;
|
||||
const dateStr = `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())} ${time.toLocaleDateString('zh-CN', { weekday: 'short' })}`;
|
||||
|
||||
const isLight = theme === 'light';
|
||||
|
||||
/* KPI 全部取自内置单据快照:履约看订单与交期,异常看物料缺口与未审采购 */
|
||||
const kpi = useMemo(() => {
|
||||
const d = new Date();
|
||||
const today = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
|
||||
const gap = materialBalance().filter(m => m.缺口 > 0);
|
||||
return {
|
||||
soCount: salesOrders.length,
|
||||
soAmount: sum(salesOrders, s => s.含税金额),
|
||||
poCount: new Set(purchaseOrders.map(p => p.采购订单号)).size,
|
||||
gapCount: gap.length,
|
||||
overdue: salesOrders.filter(s => s.预计发货日期 < today).length,
|
||||
draftPo: new Set(purchaseOrders.filter(p => p.订单状态 !== '生效').map(p => p.采购订单号)).size,
|
||||
};
|
||||
}, []);
|
||||
|
||||
const stats = [
|
||||
{ label: '销售订单', value: String(kpi.soCount), unit: '张', color: tokens.accent, Icon: ClipboardList },
|
||||
{ label: '订单金额', value: wan(kpi.soAmount), unit: '万元', color: tokens.accent, Icon: TrendingUp },
|
||||
{ label: '采购订单', value: String(kpi.poCount), unit: '张', color: tokens.accent, Icon: ShoppingCart },
|
||||
{ label: '物料缺口', value: String(kpi.gapCount), unit: '种', color: kpi.gapCount ? tokens.danger : tokens.success, Icon: AlertOctagon },
|
||||
{ label: '交期逾期', value: String(kpi.overdue), unit: '单', color: kpi.overdue ? tokens.warning : tokens.success, Icon: AlarmClock },
|
||||
{ label: '待审采购单', value: String(kpi.draftPo), unit: '张', color: kpi.draftPo ? tokens.warning : tokens.success, Icon: FileWarning },
|
||||
];
|
||||
|
||||
return (
|
||||
<header style={{
|
||||
height: 88, flexShrink: 0, display: 'flex', alignItems: 'center', padding: '0 24px',
|
||||
position: 'relative', zIndex: 10, overflow: 'visible',
|
||||
}}>
|
||||
<div style={{
|
||||
position: 'absolute', top: 0, left: 0, right: 0, height: 1,
|
||||
background: tokens.headerScanLine, boxShadow: `0 0 12px ${tokens.accentGlow}`, zIndex: 2,
|
||||
}} />
|
||||
<svg style={{
|
||||
position: 'absolute', bottom: -26, left: 0, width: '100%', height: 28,
|
||||
pointerEvents: 'none', zIndex: 0, overflow: 'visible',
|
||||
}} viewBox="0 0 1000 28" preserveAspectRatio="none">
|
||||
<path d="M 0,0 C 250,28 750,28 1000,0" fill="none" stroke={tokens.svgStroke} strokeWidth="1" vectorEffect="non-scaling-stroke" />
|
||||
<path d="M 0,0 C 250,28 750,28 1000,0" fill="none" stroke={tokens.accent} strokeWidth="6" opacity="0.10" vectorEffect="non-scaling-stroke" />
|
||||
<circle cx="0" cy="0" r="2.5" fill={tokens.svgDot} />
|
||||
<circle cx="1000" cy="0" r="2.5" fill={tokens.svgDot} />
|
||||
</svg>
|
||||
|
||||
{/* 品牌 + 标题 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 14, flex: 1, position: 'relative', zIndex: 1 }}>
|
||||
{/* 品牌 logo:白底反预乘抠成透明,深浅主题各用一版——
|
||||
浅色版保留原墨色,深色版把中性色(深蓝/灰)换成近白、品红方块原样保留 */}
|
||||
<img
|
||||
src={isLight ? '/jieya-ibp/jieya-logo-on-light.png' : '/jieya-ibp/jieya-logo-on-dark.png'}
|
||||
alt="JIEYA 洁雅家居"
|
||||
width={172}
|
||||
height={48}
|
||||
style={{ display: 'block', width: 172, height: 'auto', flexShrink: 0 }}
|
||||
/>
|
||||
<div style={{ minWidth: 0 }}>
|
||||
<h1 style={{
|
||||
color: tokens.text, fontSize: 21, fontWeight: 800, letterSpacing: '0.04em',
|
||||
margin: 0, textShadow: tokens.titleGlow, whiteSpace: 'nowrap',
|
||||
}}>{t.appTitle}</h1>
|
||||
<div style={{
|
||||
color: tokens.textSub, fontSize: 12.5, marginTop: 3, letterSpacing: '0.04em',
|
||||
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>{t.appSubTitle}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ width: 1, height: 44, background: `linear-gradient(to bottom, transparent, ${tokens.accent}33, transparent)`, flexShrink: 0, margin: '0 22px', position: 'relative', zIndex: 1 }} />
|
||||
|
||||
{/* KPI 胶囊带 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flex: 2.1, justifyContent: 'center', position: 'relative', zIndex: 1, marginTop: 22 }}>
|
||||
{stats.map((item, idx) => {
|
||||
const { Icon } = item;
|
||||
return (
|
||||
<div key={item.label} style={{ display: 'flex', alignItems: 'center', flex: 1, minWidth: 0 }}>
|
||||
<div style={{
|
||||
textAlign: 'center', padding: '6px 10px', borderRadius: 10, width: '100%',
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
|
||||
backdropFilter: 'blur(8px)', whiteSpace: 'nowrap',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5 }}>
|
||||
<Icon size={15} color={item.color} strokeWidth={2} />
|
||||
<span style={{
|
||||
color: item.color, fontSize: 23, fontWeight: 800, lineHeight: 1,
|
||||
textShadow: isLight ? 'none' : `0 0 10px ${item.color}80`,
|
||||
}}>{item.value}</span>
|
||||
<span style={{ color: tokens.textSub, fontSize: 11.5, fontWeight: 500 }}>{item.unit}</span>
|
||||
</div>
|
||||
<div style={{ color: tokens.textSub, fontSize: 11.5, marginTop: 3, letterSpacing: '0.03em', fontWeight: 600 }}>
|
||||
{item.label}
|
||||
</div>
|
||||
</div>
|
||||
{idx < stats.length - 1 && (
|
||||
<div style={{ width: 1, height: 36, background: `${tokens.accent}18`, margin: '0 3px', flexShrink: 0 }} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div style={{ width: 1, height: 44, background: `linear-gradient(to bottom, transparent, ${tokens.accent}33, transparent)`, flexShrink: 0, margin: '0 22px', position: 'relative', zIndex: 1 }} />
|
||||
|
||||
{/* 时钟 + 语言 / 主题 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1, justifyContent: 'flex-end', position: 'relative', zIndex: 1 }}>
|
||||
<div style={{ textAlign: 'right' }}>
|
||||
<div style={{
|
||||
color: period === CURRENT_PERIOD ? tokens.textMuted : tokens.warning, fontSize: 11.5, marginTop: 2,
|
||||
letterSpacing: '0.04em', fontVariantNumeric: 'tabular-nums', fontWeight: 700,
|
||||
}}>{t.header.dataAt} {periodLabel(period)}</div>
|
||||
<div style={{
|
||||
color: tokens.accent, fontSize: 16, fontWeight: 700, fontVariantNumeric: 'tabular-nums',
|
||||
lineHeight: 1, letterSpacing: '0.05em', textShadow: isLight ? 'none' : `0 0 16px ${tokens.accentGlow}`,
|
||||
}}>{timeStr}</div>
|
||||
<div style={{ color: tokens.textMuted, fontSize: 11.5, marginTop: 2, letterSpacing: '0.04em' }}>{dateStr}</div>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, padding: '4px 11px', borderRadius: 20,
|
||||
border: `1px solid ${tokens.border}`, background: tokens.panelBgAlt,
|
||||
color: tokens.textSub, fontSize: 11.5, fontWeight: 600, cursor: 'pointer', flexShrink: 0,
|
||||
}}
|
||||
>
|
||||
{theme === 'dark' ? <Sun size={12} /> : <Moon size={12} />}
|
||||
{theme === 'dark' ? t.common.light : t.common.dark}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
import { useEffect, useMemo, useRef, useState, type CSSProperties, type PointerEvent as RPointerEvent } from 'react';
|
||||
import { Activity, Crosshair, Layers, Maximize2, Minimize2, Network, RotateCcw } from 'lucide-react';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import type { MetricNode, MetricLink } from '../data/sqlite';
|
||||
import { alertColor, descendantsOf, execColor, fmt, fmtSigned } from '../lib/metric';
|
||||
import { achieveAt, CURRENT_PERIOD, gapAt, levelAt, periodLabel, valueAt } from '../lib/time';
|
||||
import DeepSpaceBackdrop from './network/DeepSpaceBackdrop';
|
||||
import { arcPath, DEEP, DEEP_BG } from './network/deepTheme';
|
||||
|
||||
interface Props {
|
||||
selected: string;
|
||||
byCode: Map<string, MetricNode>;
|
||||
flat: MetricNode[];
|
||||
links: MetricLink[];
|
||||
onSelect: (code: string) => void;
|
||||
expanded: boolean;
|
||||
/** 全局时间游标(0-11):节点取值 / 配色 / 声呐均随时点重算 */
|
||||
period: number;
|
||||
/** 舞台态:中央工作区渲染知识图谱全景,详情交给右侧因果看板 */
|
||||
stage?: boolean;
|
||||
onMaximize?: () => void;
|
||||
onExitStage?: () => void;
|
||||
}
|
||||
|
||||
/** 屏幕空间标签项:恒定字号,脱离世界缩放,保证任何缩放下都清晰可读 */
|
||||
interface LabelItem {
|
||||
code: string; text: string;
|
||||
/** 世界坐标(随相机层变换,与节点严格同步) */
|
||||
wx: number; wy: number; fsw: number;
|
||||
anchor: 'start' | 'end' | 'middle';
|
||||
fill: string; weight: number; halo: string; op: number;
|
||||
/** 屏幕空间碰撞盒 */
|
||||
bx: number; by: number; bw: number; bh: number;
|
||||
prio: number; ego: boolean;
|
||||
/** 值行(数字上环:Bloomberg 式密度) */
|
||||
sub?: string; subFill?: string;
|
||||
}
|
||||
|
||||
/** 估算文本渲染宽度:CJK/假名约 1 字宽,拉丁/数字约 0.56 */
|
||||
function textWidth(s: string, fs: number): number {
|
||||
let w = 0;
|
||||
for (const ch of s) w += ch.charCodeAt(0) > 0x2e7f ? fs : fs * 0.56;
|
||||
return w;
|
||||
}
|
||||
|
||||
export default function MetricNetwork({
|
||||
selected, byCode, flat, links, onSelect, expanded, period, stage = false, onMaximize, onExitStage,
|
||||
}: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
/* 深空主题:舞台态强制覆盖,面板态跟随用户主题 */
|
||||
const tk = stage ? { ...tokens, ...DEEP } : tokens;
|
||||
const [scope, setScope] = useState<'full' | 'ego'>('full');
|
||||
/** M4 影响传播:沿链路逐跳染亮(能量涟漪) */
|
||||
const [propagate, setPropagate] = useState(false);
|
||||
/** 降密:末级驱动因子默认折叠,只在悬停/选中其父级时上下文展开 */
|
||||
const [leaves, setLeaves] = useState(false);
|
||||
/** 电影感相机:统一位置+缩放,CSS transition 驱动平滑 fly-to */
|
||||
const [cam, setCam] = useState({ x: 0, y: 0, k: 1 });
|
||||
const [camAnim, setCamAnim] = useState(true);
|
||||
const [hover, setHover] = useState<string | null>(null);
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const dragRef = useRef<{ x: number; y: number } | null>(null);
|
||||
const movedRef = useRef(false);
|
||||
const [size, setSize] = useState({ w: 420, h: 620 });
|
||||
|
||||
useEffect(() => {
|
||||
const el = hostRef.current;
|
||||
if (!el) return;
|
||||
const ro = new ResizeObserver(([e]) => {
|
||||
const { width, height } = e.contentRect;
|
||||
if (width <= 40 || height <= 40) return;
|
||||
const w = Math.round(width), h = Math.round(height);
|
||||
/* 小于 2px 的扰动(滚动条出现/消失、子元素换行的一两px)直接丢弃:
|
||||
返回同一对象 → 不触发重渲染 → 也就不会重放取景,杜绝「尺寸微抖 → 图谱跟着抖」。 */
|
||||
setSize(prev => (Math.abs(prev.w - w) < 2 && Math.abs(prev.h - h) < 2 ? prev : { w, h }));
|
||||
});
|
||||
ro.observe(el);
|
||||
return () => ro.disconnect();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const el = hostRef.current;
|
||||
if (!el) return;
|
||||
const onWheel = (e: WheelEvent) => {
|
||||
e.preventDefault();
|
||||
setCamAnim(false);
|
||||
setCam(c => ({ ...c, k: Math.max(0.3, Math.min(3.6, c.k * (1 - e.deltaY * 0.0013))) }));
|
||||
};
|
||||
el.addEventListener('wheel', onWheel, { passive: false });
|
||||
return () => el.removeEventListener('wheel', onWheel);
|
||||
}, []);
|
||||
|
||||
const nameOf = (code: string) => {
|
||||
const n = byCode.get(code);
|
||||
return !n ? code : n.name_zh;
|
||||
};
|
||||
const unitOf = (u: string) => (u);
|
||||
|
||||
/* 每个节点归属的 L1 维度(面板态枢纽聚合用) */
|
||||
const dimAnc = useMemo(() => {
|
||||
const m = new Map<string, string>();
|
||||
flat.forEach(n => {
|
||||
let cur: MetricNode | undefined = n;
|
||||
while (cur && cur.level > 1) cur = flat.find(p => p.code === cur!.parent_code);
|
||||
if (cur) m.set(n.code, cur.code);
|
||||
});
|
||||
return m;
|
||||
}, [flat]);
|
||||
|
||||
/* ---------------- 舞台态:知识图谱径向层级布局 ----------------
|
||||
OV 居中 → 八维成环 → L2 指标绕维度扇出 → L3 驱动因子绕指标扇出。
|
||||
纵向压扁成椭圆,贴合宽而矮的中央舞台视口;末级折叠时半径外扩换呼吸感。 */
|
||||
const layout = useMemo(() => {
|
||||
const pos = new Map<string, { x: number; y: number }>();
|
||||
pos.set('OV', { x: 0, y: 0 });
|
||||
const dims = flat.filter(n => n.level === 1);
|
||||
const R1 = leaves ? 240 : 292, R2 = leaves ? 132 : 158, R3 = 78, YO = 0.86;
|
||||
dims.forEach((d, i) => {
|
||||
const a = -Math.PI / 2 + (i / Math.max(1, dims.length)) * Math.PI * 2;
|
||||
const dp = { x: R1 * Math.cos(a), y: R1 * Math.sin(a) * YO };
|
||||
pos.set(d.code, dp);
|
||||
const kids = flat.filter(n => n.parent_code === d.code);
|
||||
kids.forEach((kd, j) => {
|
||||
const off = kids.length === 1 ? 0 : (j / (kids.length - 1) - 0.5) * Math.PI * 0.92;
|
||||
const aa = a + off;
|
||||
const kp = { x: dp.x + R2 * Math.cos(aa), y: dp.y + R2 * Math.sin(aa) * YO };
|
||||
pos.set(kd.code, kp);
|
||||
const gk = flat.filter(n => n.parent_code === kd.code);
|
||||
gk.forEach((g, m) => {
|
||||
const goff = gk.length === 1 ? 0 : (m / (gk.length - 1) - 0.5) * Math.PI * 0.82;
|
||||
const ga = aa + goff;
|
||||
pos.set(g.code, { x: kp.x + R3 * Math.cos(ga), y: kp.y + R3 * Math.sin(ga) * YO });
|
||||
});
|
||||
});
|
||||
});
|
||||
let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9;
|
||||
/* 宽幅舞台:横向拉伸布局,消除左右大片空白。
|
||||
必须是连续函数——旧写法在 ratio=1.5 处从 1 跳到 1.25,容器高度只要有一两px
|
||||
波动跨过这个临界点,整张图就瞬间左右拉伸一次(表现为持续抖动)。 */
|
||||
const ratio = size.h > 40 ? size.w / size.h : 1;
|
||||
const xs = Math.max(1, Math.min(1.5, ratio / 1.2));
|
||||
pos.forEach(p => { p.x *= xs; });
|
||||
/* 适配边界只算常驻层级(L3 仅上下文展开,不应反复重新推镜头) */
|
||||
pos.forEach((p, code) => {
|
||||
const lv = byCode.get(code)?.level ?? 0;
|
||||
if (lv >= 3 && !leaves) return;
|
||||
minX = Math.min(minX, p.x); maxX = Math.max(maxX, p.x);
|
||||
minY = Math.min(minY, p.y); maxY = Math.max(maxY, p.y);
|
||||
});
|
||||
const cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;
|
||||
return { pos, cx, cy, w: maxX - minX + 210, h: maxY - minY + 150 };
|
||||
}, [flat, byCode, leaves, size.w, size.h]);
|
||||
|
||||
/* 实体可见集:降密的核心——末级平时隐藏,只在全景选中某维度或悬停探索时露面。
|
||||
注意:默认选中 OV(L0)不能展开全部子孙,否则降密失效。 */
|
||||
const visible = useMemo(() => {
|
||||
const s = new Set<string>();
|
||||
const anchors = new Set<string>();
|
||||
[hover, selected].forEach(cd => {
|
||||
const n = cd ? byCode.get(cd) : undefined;
|
||||
if (!n) return;
|
||||
anchors.add(n.code);
|
||||
if (n.level === 1) descendantsOf(n.code, flat).forEach(d => anchors.add(d.code));
|
||||
if (n.level === 3 && n.parent_code) anchors.add(n.parent_code);
|
||||
});
|
||||
flat.forEach(n => {
|
||||
if (n.level <= 2 || leaves || anchors.has(n.code) || anchors.has(n.parent_code)) s.add(n.code);
|
||||
});
|
||||
return s;
|
||||
}, [flat, byCode, hover, selected, leaves]);
|
||||
|
||||
const relEdges = useMemo(
|
||||
() => links.filter(l => visible.has(l.from_code) && visible.has(l.to_code)),
|
||||
[links, visible],
|
||||
);
|
||||
const hierEdges = useMemo(
|
||||
() => flat.filter(n => n.parent_code && visible.has(n.parent_code) && visible.has(n.code))
|
||||
.map(n => ({ from: n.parent_code, to: n.code })),
|
||||
[flat, visible],
|
||||
);
|
||||
|
||||
/* ---------------- 面板态:OV + 维度枢纽椭圆环 + 跨维关系束 ---------------- */
|
||||
const hubs = useMemo(() => {
|
||||
const dims = flat.filter(n => n.level === 1);
|
||||
const rx = Math.min(size.w * 0.36, 190), ry = rx * 0.52;
|
||||
const cx = size.w / 2, cy = size.h / 2 + 4;
|
||||
const place = new Map<string, { x: number; y: number }>();
|
||||
place.set('OV', { x: cx, y: cy });
|
||||
dims.forEach((d, i) => {
|
||||
const a = -Math.PI / 2 + (i / dims.length) * Math.PI * 2;
|
||||
place.set(d.code, { x: cx + rx * Math.cos(a), y: cy + ry * Math.sin(a) });
|
||||
});
|
||||
const anc = (c: string) => (c === 'OV' ? 'OV' : dimAnc.get(c) ?? 'OV');
|
||||
const agg = new Map<string, { w: number; rel: MetricLink['relation'] }>();
|
||||
links.forEach(l => {
|
||||
const a = anc(l.from_code), b = anc(l.to_code);
|
||||
if (a === b) return;
|
||||
const key = a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
const cur = agg.get(key) ?? { w: 0, rel: l.relation };
|
||||
cur.w += Math.abs(l.strength);
|
||||
agg.set(key, cur);
|
||||
});
|
||||
return { place, dims, agg: [...agg.entries()].map(([key, v]) => ({ a: key.split('|')[0], b: key.split('|')[1], ...v })) };
|
||||
}, [flat, links, dimAnc, size]);
|
||||
|
||||
const neighbors = useMemo(() => {
|
||||
const s = new Set<string>();
|
||||
links.forEach(l => {
|
||||
if (l.from_code === selected) s.add(l.to_code);
|
||||
if (l.to_code === selected) s.add(l.from_code);
|
||||
});
|
||||
return s;
|
||||
}, [links, selected]);
|
||||
|
||||
/* 当前活跃节点(悬停 > 选中)及其关联集:
|
||||
悬停或选中维度/总览时纳入全部子孙点亮扇区;
|
||||
默认仅选中 OV 时不展开(否则全图边误判 focus 造成毛线球) */
|
||||
const active = hover ?? selected;
|
||||
const selNode = byCode.get(selected);
|
||||
const fanCenter = hover ?? (selNode && selNode.level === 1 ? selected : null);
|
||||
const activeSet = useMemo(() => {
|
||||
const s = new Set<string>();
|
||||
const src = fanCenter ?? active;
|
||||
if (!src) return s;
|
||||
s.add(src);
|
||||
const an = byCode.get(src);
|
||||
if (an && an.level <= 1 && fanCenter) {
|
||||
descendantsOf(src, flat).forEach(d => s.add(d.code));
|
||||
} else {
|
||||
links.forEach(l => {
|
||||
if (l.from_code === src) s.add(l.to_code);
|
||||
if (l.to_code === src) s.add(l.from_code);
|
||||
});
|
||||
}
|
||||
return s;
|
||||
}, [fanCenter, active, byCode, flat, links]);
|
||||
|
||||
const relColor = (r: string) => (r === 'drive' ? tk.success : r === 'conflict' ? tk.danger : tk.info);
|
||||
|
||||
/** M4 影响传播:从 active 沿链路 BFS 3 跳,hop/累计强度决定染亮层级 */
|
||||
const reach = useMemo(() => {
|
||||
if (!propagate || !active) return null;
|
||||
const m = new Map<string, { hop: number; power: number }>();
|
||||
m.set(active, { hop: 0, power: 1 });
|
||||
let frontier = [active];
|
||||
for (let hop = 1; hop <= 3 && frontier.length; hop++) {
|
||||
const next: string[] = [];
|
||||
for (const c of frontier) {
|
||||
links.forEach(l => {
|
||||
const other = l.from_code === c ? l.to_code : l.to_code === c ? l.from_code : null;
|
||||
if (!other || m.has(other) || !visible.has(other)) return;
|
||||
m.set(other, { hop, power: +((Math.abs(l.strength) + 0.32) ** hop).toFixed(3) });
|
||||
next.push(other);
|
||||
});
|
||||
}
|
||||
frontier = next;
|
||||
}
|
||||
return m;
|
||||
}, [propagate, active, links, visible]);
|
||||
|
||||
const onDown = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
dragRef.current = { x: e.clientX, y: e.clientY };
|
||||
movedRef.current = false;
|
||||
setCamAnim(false);
|
||||
/* 不能在 pointerdown 就捕获指针:一旦捕获,浏览器会把后续 click 重定向到宿主元素,
|
||||
节点 <g onClick> 永远收不到事件——表现就是“点实体后右侧看板不联动”。
|
||||
指针捕获改到确实拖拽起来的那一刻(onMove 里)。 */
|
||||
};
|
||||
const onMove = (e: RPointerEvent<HTMLDivElement>) => {
|
||||
const d = dragRef.current;
|
||||
if (!d) return;
|
||||
const dx = e.clientX - d.x, dy = e.clientY - d.y;
|
||||
if (!movedRef.current) {
|
||||
if (Math.abs(dx) + Math.abs(dy) < 4) return;
|
||||
movedRef.current = true;
|
||||
// 合成指针(自动化测试、触控中断)下 setPointerCapture 会抛 NotFoundError,不能让它抖动交互
|
||||
try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* 忽略:降级为无捕获拖拽 */ }
|
||||
}
|
||||
d.x = e.clientX; d.y = e.clientY;
|
||||
setCam(p => ({ ...p, x: p.x + dx, y: p.y + dy }));
|
||||
};
|
||||
/* movedRef 只在 pointerdown 复位、供紧随其后的 click 判断“这次按下是不是拖拽”,
|
||||
拖拽结束后残留的 true 不该影响悬停,所以悬停用 dragRef(按压期间)作为闸门。 */
|
||||
const onUp = () => { dragRef.current = null; };
|
||||
|
||||
const modeBtn = (on: boolean) => ({
|
||||
display: 'flex' as const, alignItems: 'center' as const, gap: 4,
|
||||
padding: '3px 9px', borderRadius: 6, fontSize: 12, cursor: 'pointer',
|
||||
whiteSpace: 'nowrap' as const, flexShrink: 0,
|
||||
background: on ? tk.accentBg : 'transparent',
|
||||
color: on ? tk.accent : tk.textMuted,
|
||||
border: `1px solid ${on ? tk.borderAccent : tk.border}`,
|
||||
});
|
||||
|
||||
const fit = stage ? Math.max(0.45, Math.min(1.5, Math.min(size.w / layout.w, size.h / layout.h))) : 1;
|
||||
/* fit 只由容器尺寸与密度档位决定(适配边界刻意排除 L3,悬停展开不改取景);
|
||||
用 ref 取最新值而不进依赖数组,否则“平移视角 → 点一个节点”就会被重新取景拽回原点,
|
||||
看着像点击没生效。 */
|
||||
const fitRef = useRef(fit);
|
||||
fitRef.current = fit;
|
||||
|
||||
/* 相机取景单一入口:
|
||||
· 进入舞台 / 切密度档位 → 播一次入场推进(0.62 → 1 缓出)
|
||||
· 容器尺寸变化 → 静默重取景,不重放推进(否则与工具条宽度形成自激抖动)
|
||||
两个 effect 分开写会互相抢相机(尺寸一变就把推进抹平),所以统一收在这里。 */
|
||||
const introKeyRef = useRef('');
|
||||
/** 上次真正取景时的容器尺寸:小于此幅度的变化不再惊动相机 */
|
||||
const fittedRef = useRef({ w: -1, h: -1 });
|
||||
/** 入场推进是否还在空中(被尺寸变化打断时需要补完,不能砸成瞬间跳变) */
|
||||
const introPendingRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!stage) {
|
||||
introKeyRef.current = '';
|
||||
fittedRef.current = { w: -1, h: -1 };
|
||||
introPendingRef.current = false;
|
||||
setCam({ x: 0, y: 0, k: 1 });
|
||||
return;
|
||||
}
|
||||
const key = `stage|${leaves ? 'leaves' : 'fold'}`;
|
||||
const isIntro = introKeyRef.current !== key;
|
||||
const resized = Math.abs(size.w - fittedRef.current.w) >= 3 || Math.abs(size.h - fittedRef.current.h) >= 3;
|
||||
if (!isIntro && !resized) return;
|
||||
fittedRef.current = { w: size.w, h: size.h };
|
||||
if (isIntro) {
|
||||
introKeyRef.current = key;
|
||||
introPendingRef.current = true;
|
||||
setCamAnim(false);
|
||||
setCam({ x: 0, y: 0, k: fitRef.current * 0.62 });
|
||||
const id = requestAnimationFrame(() => requestAnimationFrame(() => {
|
||||
introPendingRef.current = false;
|
||||
setCamAnim(true);
|
||||
setCam({ x: 0, y: 0, k: fitRef.current });
|
||||
}));
|
||||
return () => cancelAnimationFrame(id);
|
||||
}
|
||||
/* 容器尺寸变化 → 静默重取景(不挂 transition)。动画化重取景会与工具条换行互相追,
|
||||
每追一次就是一次 0.9s 推拉,视觉上正是「一直在抖」;只有入场被打断时才补一次动画。 */
|
||||
const animate = introPendingRef.current;
|
||||
introPendingRef.current = false;
|
||||
setCamAnim(animate);
|
||||
setCam({ x: 0, y: 0, k: fitRef.current });
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [stage, leaves, size.w, size.h]);
|
||||
|
||||
/** M6 电影感相机:平滑推近到指定节点 */
|
||||
const flyTo = (code: string, mult = 1.3) => {
|
||||
const p = layout.pos.get(code);
|
||||
if (!p) return;
|
||||
setCamAnim(true);
|
||||
setCam(c => {
|
||||
const k = Math.min(fit * 2.4, Math.max(c.k, fit * mult));
|
||||
return { x: (layout.cx - p.x) * k, y: (layout.cy - p.y) * k, k };
|
||||
});
|
||||
};
|
||||
|
||||
/* ego 聚焦模式:切换或换选中节点时相机自动跟进 */
|
||||
useEffect(() => {
|
||||
if (stage && scope === 'ego' && selected) {
|
||||
const p = layout.pos.get(selected);
|
||||
if (p) { flyTo(selected, 1.25); }
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [scope, selected, stage]);
|
||||
|
||||
/** 相机过渡期:标签短暂降透,避免逆缩放字号与插值 scale 不一致造成的瞬时重叠 */
|
||||
const [camMoving, setCamMoving] = useState(false);
|
||||
useEffect(() => {
|
||||
if (!camAnim) return;
|
||||
setCamMoving(true);
|
||||
const id = window.setTimeout(() => setCamMoving(false), 950);
|
||||
return () => window.clearTimeout(id);
|
||||
}, [cam, camAnim]);
|
||||
|
||||
/** 世界层统一相机变换:节点与标签共用,保证 fly-to 期间严格同步 */
|
||||
const camStyle: CSSProperties = {
|
||||
transform: `translate(${size.w / 2 + cam.x}px, ${size.h / 2 + cam.y}px) scale(${cam.k}) translate(${-layout.cx}px, ${-layout.cy}px)`,
|
||||
transition: camAnim ? 'transform 0.9s cubic-bezier(0.22,1,0.36,1)' : 'none',
|
||||
};
|
||||
const toScreen = (wx: number, wy: number) => ({
|
||||
x: size.w / 2 + cam.x + (wx - layout.cx) * cam.k,
|
||||
y: size.h / 2 + cam.y + (wy - layout.cy) * cam.k,
|
||||
});
|
||||
|
||||
const nodeR = (code: string) => {
|
||||
const n = byCode.get(code);
|
||||
if (!n) return 6;
|
||||
if (code === 'OV') return 16;
|
||||
return n.level === 1 ? 11.5 : n.level === 2 ? 8.5 : 6.5;
|
||||
};
|
||||
const labelFs = (code: string) => {
|
||||
const n = byCode.get(code);
|
||||
if (code === 'OV') return 15;
|
||||
if (!n) return 11;
|
||||
return n.level === 1 ? 13.5 : n.level === 2 ? 12 : 11;
|
||||
};
|
||||
const isEgo = (code: string) =>
|
||||
code === active || code === selected || activeSet.has(code);
|
||||
/* 悬停即凸显:不论 scope,只要用户悬停探索某节点,就压暗其非关联节点,
|
||||
让「指标间连接关系」随手可见;切到聚焦模式则常驻凸显选中节点。 */
|
||||
const focusing = scope === 'ego' || hover !== null || propagate;
|
||||
const dimFactor = (code: string) => {
|
||||
if (!stage) return 1;
|
||||
/* 传播模式:涟漪覆盖的节点染亮,其余压到背景 */
|
||||
if (reach) return reach.has(code) ? 1 : 0.08;
|
||||
return !focusing || !active ? 1 : (isEgo(code) ? 1 : 0.12);
|
||||
};
|
||||
|
||||
/* 关系边:垂直弓形 + 两端按半径收口,箭头落在目标节点外沿 */
|
||||
const edgePath = (ax: number, ay: number, bx: number, by: number, ra: number, rb: number) => {
|
||||
const dx = bx - ax, dy = by - ay;
|
||||
const len = Math.hypot(dx, dy) || 1;
|
||||
const nx = -dy / len, ny = dx / len;
|
||||
const bow = Math.min(48, len * 0.16);
|
||||
const cxp = (ax + bx) / 2 + nx * bow, cyp = (ay + by) / 2 + ny * bow;
|
||||
const va = { x: ax - cxp, y: ay - cyp }, la = Math.hypot(va.x, va.y) || 1;
|
||||
const vb = { x: bx - cxp, y: by - cyp }, lb = Math.hypot(vb.x, vb.y) || 1;
|
||||
const a2 = { x: ax + (va.x / la) * (ra + 2), y: ay + (va.y / la) * (ra + 2) };
|
||||
const b2 = { x: bx + (vb.x / lb) * (rb + 5), y: by + (vb.y / lb) * (rb + 5) };
|
||||
return `M ${a2.x.toFixed(1)},${a2.y.toFixed(1)} Q ${cxp.toFixed(1)},${cyp.toFixed(1)} ${b2.x.toFixed(1)},${b2.y.toFixed(1)}`;
|
||||
};
|
||||
|
||||
/* -------- 屏幕空间标签层:恒定字号 + 优先级碰撞抑制(缩小时自动只留高优先级) --------
|
||||
碰撞检测在屏幕空间算,渲染坐标用世界系:fly-to 动画期间与节点层零偏差 */
|
||||
const haloCol = stage ? '#0a1022' : tokens.panelBgAlt;
|
||||
const labelPlan = (): LabelItem[] => {
|
||||
if (!stage) return [];
|
||||
const items: LabelItem[] = [];
|
||||
layout.pos.forEach((p, code) => {
|
||||
if (!visible.has(code)) return;
|
||||
const n = byCode.get(code);
|
||||
if (!n) return;
|
||||
const s = toScreen(p.x, p.y);
|
||||
const fs = labelFs(code);
|
||||
const fsw = fs / cam.k;
|
||||
const rW = nodeR(code);
|
||||
const text = nameOf(code);
|
||||
const tw = textWidth(text, fs);
|
||||
const isOV = code === 'OV';
|
||||
const right = p.x >= layout.cx;
|
||||
const ego = isEgo(code);
|
||||
const gapW = (isOV ? 9 : 6) / cam.k;
|
||||
const wx = isOV ? p.x : right ? p.x + rW + gapW : p.x - rW - gapW;
|
||||
const wy = isOV ? p.y - rW - gapW : p.y + fsw * 0.34;
|
||||
const anchor: 'start' | 'end' | 'middle' = isOV ? 'middle' : right ? 'start' : 'end';
|
||||
/* 屏幕碰撞盒 */
|
||||
const bw = tw + 6, bh = fs * 1.3;
|
||||
const sx = isOV ? s.x : right ? s.x + rW * cam.k + 6 : s.x - rW * cam.k - 6;
|
||||
const sy = isOV ? s.y - rW * cam.k - 9 : s.y + fs * 0.34;
|
||||
const bx = anchor === 'start' ? sx - 3 : anchor === 'end' ? sx - bw + 3 : sx - bw / 2;
|
||||
const by = sy - fs * 0.92;
|
||||
const hot = code === hover || code === selected;
|
||||
const fill = hot ? tk.accent : isOV || n.level === 1 ? tk.text : n.level === 2 ? tk.textSub : tk.textMuted;
|
||||
const weight = hot || isOV || n.level === 1 ? 700 : 500;
|
||||
const lv = levelAt(n, period);
|
||||
let prio = ego ? 0 : isOV ? 1 : n.level === 1 ? 2 : n.level === 2 ? 3 : 4;
|
||||
if (!ego) prio += lv === 'red' ? -0.4 : lv === 'yellow' ? -0.2 : 0;
|
||||
/* 数字副行:L1/L2 带游标时点达成率,一眼可读该月健康度 */
|
||||
let sub: string | undefined, subFill: string | undefined;
|
||||
const ach = achieveAt(n, period);
|
||||
if (isOV) {
|
||||
sub = `${fmt(valueAt(n, period))} / ${fmt(n.target)}`;
|
||||
subFill = execColor(ach, tk);
|
||||
} else if (n.level === 1) {
|
||||
sub = `${fmt(ach, 0)}%`;
|
||||
subFill = execColor(ach, tk);
|
||||
}
|
||||
items.push({ code, text, wx, wy, fsw, anchor, fill, weight, halo: haloCol, op: dimFactor(code), bx, by, bw, bh, prio, ego, sub, subFill });
|
||||
});
|
||||
items.sort((a, b) => a.prio - b.prio || b.fsw - a.fsw);
|
||||
const placed: { bx: number; by: number; bw: number; bh: number }[] = [];
|
||||
const out: LabelItem[] = [];
|
||||
for (const it of items) {
|
||||
/* 碰撞盒覆盖数字副行,密集扇区不再与邻居主标签相碰 */
|
||||
const hit = placed.some(b => it.bx < b.bx + b.bw && it.bx + it.bw > b.bx && it.by < b.by + b.bh && it.by + it.bh > b.by);
|
||||
/* 仅焦点二节点强制显示,其余(含邻居)参与碰撞避让,叶层不再叠字 */
|
||||
const force = it.code === active || it.code === selected;
|
||||
if (force || !hit) {
|
||||
placed.push({ bx: it.bx, by: it.by, bw: it.bw, bh: it.bh + (it.sub ? it.fsw * 1.35 * cam.k : 0) });
|
||||
out.push(it);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
|
||||
/* 实体详情已迁移到右侧因果看板(CausalPanel),图谱只负责关系与空间叙事 */
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', minHeight: 0, minWidth: 0, flex: 1, gap: 6,
|
||||
...(stage ? { background: DEEP_BG, borderRadius: 12, padding: 2 } : null),
|
||||
}}>
|
||||
{/* 工具条可换行 + 上层 minWidth:0:不让按钮的 min-content 反过来决定图谱宽度;
|
||||
minHeight 兜住一行高度,避免子项瞬时空高把工具条塌下去(塌一次 = 图谱重取景一次)。 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', flexWrap: 'wrap', minHeight: 30, padding: stage ? '4px 6px 0' : 0 }}>
|
||||
{stage && (
|
||||
<>
|
||||
<button style={modeBtn(scope === 'full')} onClick={() => setScope('full')}>
|
||||
<Layers size={12} />{t.net.allNodes}
|
||||
</button>
|
||||
<button style={modeBtn(scope === 'ego')} onClick={() => setScope(scope === 'ego' ? 'full' : 'ego')}>
|
||||
<Crosshair size={12} />{t.net.focusSel}
|
||||
</button>
|
||||
{/* M4 影响传播:沿链路 BFS 涟漪 */}
|
||||
<button style={modeBtn(propagate)} onClick={() => { setPropagate(v => !v); setScope('full'); }}>
|
||||
<Activity size={12} />{t.net.propagate}
|
||||
</button>
|
||||
{/* 降密开关:末级驱动因子平时收起,避免图“密麻” */}
|
||||
<button style={modeBtn(leaves)} onClick={() => setLeaves(v => !v)}>
|
||||
<Network size={12} />{t.net.leaves}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
<span style={{ flex: 1 }} />
|
||||
{/* 游标chip:提醒全图取值已锁定在该时点。
|
||||
“回放中”后缀恒定占位(只切 visibility):条件挂/卸会改工具条宽度 → 换行行数变
|
||||
→ 图谱容器高度变 → 重取景,与悬停展开是同一条自激链。 */}
|
||||
{stage && (
|
||||
<span style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 6,
|
||||
color: period === CURRENT_PERIOD ? tk.textMuted : tk.warning,
|
||||
background: period === CURRENT_PERIOD ? 'transparent' : `${tk.warning}14`,
|
||||
border: `1px solid ${period === CURRENT_PERIOD ? tk.border : `${tk.warning}44`}`,
|
||||
fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap',
|
||||
}}>
|
||||
{periodLabel(period)}
|
||||
<span style={{ visibility: period === CURRENT_PERIOD ? 'hidden' : 'visible' }}> 回放中</span>
|
||||
</span>
|
||||
)}
|
||||
<button style={modeBtn(false)} title={t.net.resetView} onClick={() => { setCamAnim(true); setCam({ x: 0, y: 0, k: fit }); }}>
|
||||
<RotateCcw size={12} />
|
||||
</button>
|
||||
{/* 缩放徽标恒定占位:条件挂/卸会改变工具条 min-content → 容器宽度变 → 重放推镜 → 无限拖动 */}
|
||||
{stage && (
|
||||
<span style={{
|
||||
width: 38, textAlign: 'right', fontSize: 11.5, color: tk.accent, fontVariantNumeric: 'tabular-nums',
|
||||
opacity: Math.abs(cam.k / fit - 1) > 0.01 ? 1 : 0,
|
||||
}}>{Math.round((cam.k / fit) * 100)}%</span>
|
||||
)}
|
||||
{/* 计数文本恒定宽:visible.size 会从 9 变到 59(悬停维度时),
|
||||
不定宽就会改变工具条 min-content → 换行/塌陷 → 图谱容器高变 → 重取景,
|
||||
节点从光标下移开 → 悬停失效 → 换行回去……就是“鼠标停在图上时一直抖”。 */}
|
||||
<span style={{
|
||||
fontSize: 12, color: tk.textMuted, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
|
||||
...(stage ? { width: 78, flex: '0 0 78px' } : null),
|
||||
}}>
|
||||
{stage ? `${visible.size}/${flat.length}` : flat.length} · {links.length}
|
||||
</span>
|
||||
{stage ? (
|
||||
<button style={modeBtn(false)} onClick={onExitStage}>
|
||||
<Minimize2 size={12} />{t.net.exitStage}
|
||||
</button>
|
||||
) : (
|
||||
<button style={modeBtn(true)} onClick={onMaximize}>
|
||||
<Maximize2 size={12} />{t.net.toStage}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={hostRef}
|
||||
onPointerDown={onDown} onPointerMove={onMove} onPointerUp={onUp} onPointerCancel={onUp}
|
||||
style={{
|
||||
position: 'relative', flex: '1 1 auto', minWidth: 0, minHeight: 260, borderRadius: 10, overflow: 'hidden',
|
||||
background: stage ? 'transparent' : tokens.panelBgAlt,
|
||||
border: `1px solid ${stage ? 'rgba(129,140,248,0.14)' : tokens.border}`,
|
||||
cursor: dragRef.current ? 'grabbing' : 'grab', touchAction: 'none', userSelect: 'none',
|
||||
}}
|
||||
>
|
||||
{/* M5 深空氛围:星云/星点/雷达扫描/暗角 */}
|
||||
<DeepSpaceBackdrop w={size.w} h={size.h} deep={stage} radar={stage} />
|
||||
<svg width="100%" height="100%" style={{ display: 'block', position: 'relative' }}>
|
||||
<defs>
|
||||
{(['drive', 'conflict', 'monitor'] as const).map(r => (
|
||||
<marker key={r} id={`mk-${r}`} viewBox="0 0 10 10" refX="8" refY="5"
|
||||
markerWidth="6.5" markerHeight="6.5" orient="auto-start-reverse">
|
||||
<path d="M 0 0 L 10 5 L 0 10 z" fill={relColor(r)} />
|
||||
</marker>
|
||||
))}
|
||||
{/* M1 星体渐变:亮心→本色→暗边,节点自带体积光 */}
|
||||
<radialGradient id="net-core" cx="42%" cy="36%">
|
||||
<stop offset="0%" stopColor="#ffffff" stopOpacity={0.95} />
|
||||
<stop offset="42%" stopColor={tk.accent} />
|
||||
<stop offset="100%" stopColor="#312e81" />
|
||||
</radialGradient>
|
||||
{(['green', 'yellow', 'red'] as const).map(lv => (
|
||||
<radialGradient key={lv} id={`net-${lv}`} cx="40%" cy="34%">
|
||||
<stop offset="0%" stopColor="#ffffff" stopOpacity={0.82} />
|
||||
<stop offset="46%" stopColor={alertColor(lv, tk)} />
|
||||
<stop offset="100%" stopColor={alertColor(lv, tk)} stopOpacity={0.62} />
|
||||
</radialGradient>
|
||||
))}
|
||||
</defs>
|
||||
|
||||
{!stage ? (
|
||||
/* ---------- 面板态:枢纽星座总览 ---------- */
|
||||
<g>
|
||||
{[-1, 0, 1].map(kk => (
|
||||
<ellipse key={kk} cx={size.w / 2} cy={size.h / 2 + 4}
|
||||
rx={Math.min(size.w * 0.36, 190) * (1 + kk * 0.28)} ry={Math.min(size.w * 0.36, 190) * 0.52 * (1 + kk * 0.28)}
|
||||
fill="none" stroke={tokens.border} strokeWidth={0.7} strokeDasharray="2 6" opacity={0.5} />
|
||||
))}
|
||||
{hubs.agg.map((e, i) => {
|
||||
const a = hubs.place.get(e.a)!, b = hubs.place.get(e.b)!;
|
||||
const focus = e.a === selected || e.b === selected || neighbors.has(e.a) || neighbors.has(e.b);
|
||||
return (
|
||||
<path key={i}
|
||||
d={`M ${a.x},${a.y} Q ${(a.x + b.x) / 2},${(a.y + b.y) / 2 - 26} ${b.x},${b.y}`}
|
||||
fill="none" stroke={relColor(e.rel)}
|
||||
strokeWidth={Math.min(3.4, 0.8 + e.w * 0.5)} opacity={focus ? 0.85 : 0.28}
|
||||
className={focus ? 'dash-flow' : undefined}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{['OV', ...hubs.dims.map(d => d.code)].map(code => {
|
||||
const p = hubs.place.get(code)!;
|
||||
const n = byCode.get(code);
|
||||
if (!n) return null;
|
||||
const isSel = code === selected, isHot = hover === code;
|
||||
const lv = levelAt(n, period);
|
||||
const c = alertColor(lv, tk);
|
||||
const count = flat.filter(x => dimAnc.get(x.code) === code || x.code === code).length;
|
||||
const left = p.x < size.w / 2;
|
||||
const isOv = code === 'OV';
|
||||
const rBase = isOv ? 9 : 7.5;
|
||||
const ar = Math.min(1, Math.max(0, achieveAt(n, period) / 100));
|
||||
const sonar = lv === 'red' || (lv === 'yellow' && gapAt(n, period) < 0);
|
||||
return (
|
||||
<g key={code} style={{ cursor: 'pointer' }}
|
||||
onPointerEnter={() => { if (!dragRef.current) setHover(code); }}
|
||||
onPointerLeave={() => { if (hover === code) setHover(null); }}
|
||||
onClick={e => { if (!movedRef.current) { e.stopPropagation(); onSelect(code); } }}
|
||||
>
|
||||
{(isSel || isHot) && (
|
||||
<circle cx={p.x} cy={p.y} r={15} fill={tk.accent} opacity={isSel ? 0.16 : 0.1}
|
||||
className={isSel ? 'space-pulse' : undefined} />
|
||||
)}
|
||||
{/* M3 声呐:枢纽偏离也自主扩散 */}
|
||||
{sonar && !isOv && (
|
||||
<circle cx={p.x} cy={p.y} r={rBase + 3} fill="none" stroke={c} strokeWidth={1}
|
||||
className="net-sonar" />
|
||||
)}
|
||||
{/* L1 行星达成率环 + 中心恒星呼吸光晕 */}
|
||||
{isOv && <circle cx={p.x} cy={p.y} r={13.5} fill={tk.accent} opacity={0.18} className="net-breathe" />}
|
||||
{!isOv && <circle cx={p.x} cy={p.y} r={rBase + 3.4} fill="none" stroke={tk.border} strokeWidth={1.8} />}
|
||||
{!isOv && <path d={arcPath(p.x, p.y, rBase + 3.4, ar)} fill="none" stroke={c} strokeWidth={2} strokeLinecap="round" />}
|
||||
<circle cx={p.x} cy={p.y} r={rBase} fill={isOv ? 'url(#net-core)' : `url(#net-${lv})`}
|
||||
stroke={isSel ? tk.accent : tk.panelBgAlt} strokeWidth={isSel ? 2.5 : 2}
|
||||
style={{ filter: `drop-shadow(0 0 ${isOv ? 7 : 3.5}px ${c})` }} />
|
||||
<text
|
||||
x={left ? p.x - 13 : p.x + 13} y={p.y + 4.5}
|
||||
textAnchor={left ? 'end' : 'start'}
|
||||
fontSize={expanded ? 13.5 : 12} fontWeight={800}
|
||||
fill={isSel || isHot ? tk.accent : tk.text}
|
||||
stroke={tk.panelBgAlt} strokeWidth={3} paintOrder="stroke" strokeLinejoin="round"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>{nameOf(code)}</text>
|
||||
<text
|
||||
x={left ? p.x - 13 : p.x + 13} y={p.y + (expanded ? 19 : 17.5)}
|
||||
textAnchor={left ? 'end' : 'start'}
|
||||
fontSize={10.5} fill={tk.textMuted}
|
||||
stroke={tk.panelBgAlt} strokeWidth={2.4} paintOrder="stroke" strokeLinejoin="round"
|
||||
style={{ pointerEvents: 'none' }}
|
||||
>{count} {t.net.nodes}</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
) : (
|
||||
/* ---------- 舞台态:指标知识图谱全景(深空叙事) ---------- */
|
||||
<>
|
||||
<g style={camStyle}>
|
||||
{/* 星系轨道环:呼吸的层级星环,强化径向布局的天体秩序 */}
|
||||
{[300, 420, 545].map((rr, i) => (
|
||||
<ellipse key={rr} cx={layout.cx} cy={layout.cy} rx={rr} ry={rr * 0.86}
|
||||
fill="none" stroke={tk.accent} strokeWidth={0.6} strokeDasharray="3 10"
|
||||
opacity={0.09 - i * 0.02} className="net-breathe"
|
||||
style={{ animationDelay: `${i * 1.5}s`, animationDuration: '8s', pointerEvents: 'none' }} />
|
||||
))}
|
||||
|
||||
{/* 层级父子边(极淡底衬;悬停维度/总览时点亮整个扇区) */}
|
||||
{hierEdges.map((e, i) => {
|
||||
const a = layout.pos.get(e.from)!, b = layout.pos.get(e.to)!;
|
||||
const dim = Math.min(dimFactor(e.from), dimFactor(e.to));
|
||||
const hFoc = activeSet.has(e.from) && activeSet.has(e.to);
|
||||
return (
|
||||
<line key={`h${i}`} x1={a.x} y1={a.y} x2={b.x} y2={b.y}
|
||||
stroke={hFoc ? tk.accent : tk.border} strokeWidth={hFoc ? 1.3 : 0.8}
|
||||
opacity={(hFoc ? 0.4 : 0.15) * dim} />
|
||||
);
|
||||
})}
|
||||
|
||||
{/* M2 能量流边:focus 边霓虹三层 + 因果方向粒子;非 focus 压入背景 */}
|
||||
{relEdges.map(l => {
|
||||
const a = layout.pos.get(l.from_code)!, b = layout.pos.get(l.to_code)!;
|
||||
const d = edgePath(a.x, a.y, b.x, b.y, nodeR(l.from_code), nodeR(l.to_code));
|
||||
const inTree = !!reach
|
||||
&& reach.has(l.from_code) && reach.has(l.to_code)
|
||||
&& Math.abs(reach.get(l.from_code)!.hop - reach.get(l.to_code)!.hop) <= 1;
|
||||
const focus = inTree
|
||||
|| (activeSet.has(l.from_code) && activeSet.has(l.to_code))
|
||||
|| l.from_code === active || l.to_code === active
|
||||
|| l.from_code === selected || l.to_code === selected;
|
||||
const dim = Math.min(dimFactor(l.from_code), dimFactor(l.to_code));
|
||||
const c = relColor(l.relation);
|
||||
const wBase = 0.6 + Math.abs(l.strength) * 1.3;
|
||||
if (!focus) {
|
||||
return (
|
||||
<path key={l.id} d={d} fill="none" stroke={c} strokeWidth={wBase}
|
||||
opacity={0.3 * dim}
|
||||
strokeDasharray={l.relation === 'monitor' ? '4 4' : undefined} />
|
||||
);
|
||||
}
|
||||
return (
|
||||
<g key={l.id} opacity={dim}>
|
||||
{/* 光晕底 / 主线 / 白亮芯 */}
|
||||
<path d={d} fill="none" stroke={c} strokeWidth={wBase + 3.6} opacity={0.13} strokeLinecap="round" />
|
||||
<path d={d} fill="none" stroke={c} strokeWidth={wBase + 1.5} opacity={0.9}
|
||||
strokeDasharray={l.relation === 'monitor' ? '5 4' : undefined}
|
||||
markerEnd={`url(#mk-${l.relation})`} className="dash-flow" />
|
||||
<path d={d} fill="none" stroke="#fff" strokeWidth={0.55} opacity={0.38} />
|
||||
{/* 能量粒子:速度∝强度;conflict 额外逆向对撞 */}
|
||||
<circle r={l.relation === 'monitor' ? 1.6 : 2.3} fill={c}
|
||||
style={{ filter: `drop-shadow(0 0 3.5px ${c})` }}>
|
||||
<animateMotion dur={`${(3.6 - Math.min(2, Math.abs(l.strength) * 2.6)).toFixed(2)}s`} repeatCount="indefinite" path={d} />
|
||||
</circle>
|
||||
{l.relation === 'conflict' && (
|
||||
<circle r={1.6} fill={c} opacity={0.75}>
|
||||
<animateMotion dur="3.6s" repeatCount="indefinite" path={d} keyPoints="1;0" keyTimes="0;1" calcMode="linear" />
|
||||
</circle>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* M1 恒星层级节点:OV=核心恒星 / L1=行星(达成率环) / L2=卫星 / L3=尘埃 */}
|
||||
{[...layout.pos.entries()].filter(([code]) => visible.has(code)).map(([code, p], idx) => {
|
||||
const n = byCode.get(code);
|
||||
if (!n) return null;
|
||||
const isSel = code === selected, isHot = hover === code;
|
||||
const lv = levelAt(n, period);
|
||||
const c = alertColor(lv, tk);
|
||||
const r = nodeR(code);
|
||||
const ar = Math.min(1, Math.max(0, achieveAt(n, period) / 100));
|
||||
const rp = reach?.get(code);
|
||||
/* M3 声呐:游标时点偏离的指标自主扩散涟漪,问题自己跳出来 */
|
||||
const sonar = n.level >= 2 && (lv === 'red' || (lv === 'yellow' && gapAt(n, period) < 0));
|
||||
const glow = code === 'OV' || n.level === 1 || lv === 'red' || isHot || isSel;
|
||||
return (
|
||||
<g key={code}
|
||||
className={rp && propagate ? 'net-ripple' : undefined}
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
opacity: dimFactor(code),
|
||||
animationDelay: rp && propagate ? `${(rp.hop * 0.24).toFixed(2)}s` : undefined,
|
||||
filter: glow ? `drop-shadow(0 0 ${code === 'OV' ? 9 : 4.5}px ${c})` : undefined,
|
||||
}}
|
||||
onPointerEnter={() => { if (!dragRef.current) setHover(code); }}
|
||||
onPointerLeave={() => { if (hover === code) setHover(null); }}
|
||||
onDoubleClick={e => { e.stopPropagation(); flyTo(code, 1.5); }}
|
||||
onPointerUp={e => {
|
||||
/* 兼容路径:拖拽期间指针被宿主捕获时 click 不会落到节点,
|
||||
未发生拖拽时在此直接选中,保证“点哪个看板就换哪个” */
|
||||
if (movedRef.current || dragRef.current === null) return;
|
||||
e.stopPropagation();
|
||||
onSelect(code);
|
||||
}}
|
||||
onClick={e => { if (movedRef.current) return; e.stopPropagation(); onSelect(code); }}
|
||||
>
|
||||
<circle cx={p.x} cy={p.y} r={r + 9} fill="transparent" style={{ pointerEvents: 'all' }} />
|
||||
{/* M3 声呐环(red 双波错峰 / yellow 单波慢速) */}
|
||||
{sonar && (
|
||||
<circle cx={p.x} cy={p.y} r={r + 2.5} fill="none" stroke={c} strokeWidth={1.1}
|
||||
className={`net-sonar${lv === 'yellow' ? ' net-sonar-slow' : ''}`}
|
||||
style={{ animationDelay: `${((idx * 437) % 2400) / 1000}s` }} />
|
||||
)}
|
||||
{sonar && lv === 'red' && (
|
||||
<circle cx={p.x} cy={p.y} r={r + 2.5} fill="none" stroke={c} strokeWidth={1.1}
|
||||
className="net-sonar" style={{ animationDelay: '1.8s' }} />
|
||||
)}
|
||||
{(isSel || isHot) && (
|
||||
<circle cx={p.x} cy={p.y} r={r + 7} fill={tk.accent} opacity={isSel ? 0.18 : 0.12}
|
||||
className={isSel ? 'space-pulse' : undefined} />
|
||||
)}
|
||||
{/* L0 中心恒星:双层反转刻度环 + 呼吸光晕 */}
|
||||
{code === 'OV' && (
|
||||
<>
|
||||
<g className="net-orbit">
|
||||
{Array.from({ length: 24 }, (_, i) => {
|
||||
const ang = (i / 24) * Math.PI * 2;
|
||||
const r0 = r + 10, r1 = i % 6 === 0 ? r + 17 : r + 13.5;
|
||||
return (
|
||||
<line key={i}
|
||||
x1={p.x + r0 * Math.cos(ang)} y1={p.y + r0 * Math.sin(ang)}
|
||||
x2={p.x + r1 * Math.cos(ang)} y2={p.y + r1 * Math.sin(ang)}
|
||||
stroke={tk.accent} strokeWidth={i % 6 === 0 ? 1.3 : 0.7}
|
||||
opacity={i % 6 === 0 ? 0.9 : 0.4} />
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
<circle cx={p.x} cy={p.y} r={r + 22} fill="none" stroke={tk.accent} strokeWidth={0.6}
|
||||
strokeDasharray="2 9" opacity={0.45} className="net-orbit net-orbit-rev" />
|
||||
<circle cx={p.x} cy={p.y} r={r + 5} fill={tk.accent} opacity={0.2} className="net-breathe" />
|
||||
<circle cx={p.x} cy={p.y} r={r} fill="url(#net-core)" stroke={tk.accent} strokeWidth={1.5} />
|
||||
</>
|
||||
)}
|
||||
{/* L1 行星:体积光球体 + 达成率环 */}
|
||||
{n.level === 1 && (
|
||||
<>
|
||||
<circle cx={p.x} cy={p.y} r={r + 5} fill={c} opacity={0.13} className="net-breathe" />
|
||||
<circle cx={p.x} cy={p.y} r={r + 3.6} fill="none" stroke={tk.borderSub} strokeWidth={2.2} />
|
||||
<path d={arcPath(p.x, p.y, r + 3.6, ar)} fill="none" stroke={c} strokeWidth={2.2} strokeLinecap="round" />
|
||||
<circle cx={p.x} cy={p.y} r={r} fill={`url(#net-${lv})`}
|
||||
stroke={isSel ? tk.accent : 'rgba(255,255,255,0.3)'} strokeWidth={isSel ? 1.7 : 0.9} />
|
||||
</>
|
||||
)}
|
||||
{/* L2 KPI:达成率细弧卫星 */}
|
||||
{n.level === 2 && (
|
||||
<>
|
||||
<circle cx={p.x} cy={p.y} r={r + 2.8} fill="none" stroke={tk.border} strokeWidth={1.2} opacity={0.6} />
|
||||
<path d={arcPath(p.x, p.y, r + 2.8, ar)} fill="none" stroke={c} strokeWidth={1.5} strokeLinecap="round" opacity={0.95} />
|
||||
<circle cx={p.x} cy={p.y} r={r} fill={c}
|
||||
stroke={isSel ? tk.accent : isHot ? tk.text : tk.panelBgAlt}
|
||||
strokeWidth={isSel ? 1.8 : isHot ? 1.4 : 0.8} />
|
||||
</>
|
||||
)}
|
||||
{/* L3 驱动因子:尘埃光点 */}
|
||||
{n.level === 3 && (
|
||||
<circle cx={p.x} cy={p.y} r={isHot || isSel ? r + 1 : r} fill={c}
|
||||
opacity={isHot ? 1 : 0.85}
|
||||
stroke={isSel ? tk.accent : 'transparent'} strokeWidth={1.4} />
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</g>
|
||||
|
||||
{/* 标签层:世界坐标随相机同步 fly-to,字号逆缩放保持恒定可读;过渡期降透避让瞬时重叠 */}
|
||||
<g style={{ ...camStyle, pointerEvents: 'none', opacity: camMoving ? 0.25 : 1, transition: `${camStyle.transition}, opacity 0.35s ease` } as CSSProperties}>
|
||||
{labelPlan().map(l => (
|
||||
<g key={l.code} opacity={l.op}>
|
||||
<text x={l.wx} y={l.wy} textAnchor={l.anchor} fontSize={l.fsw}
|
||||
fontWeight={l.weight} fill={l.fill}
|
||||
stroke={l.halo} strokeWidth={3 / cam.k} paintOrder="stroke" strokeLinejoin="round"
|
||||
>{l.text}</text>
|
||||
{l.sub && (
|
||||
<text x={l.wx} y={l.wy + l.fsw * 1.22} textAnchor={l.anchor} fontSize={l.fsw * 0.74}
|
||||
fontWeight={800} fill={l.subFill ?? l.fill}
|
||||
stroke={l.halo} strokeWidth={2.4 / cam.k} paintOrder="stroke" strokeLinejoin="round"
|
||||
>{l.sub}</text>
|
||||
)}
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
</>
|
||||
)}
|
||||
</svg>
|
||||
|
||||
{/* M6 hover 数据签:不点击即可读数(深空玻璃浮签) */}
|
||||
{stage && hover && !dragRef.current && (() => {
|
||||
const hn = byCode.get(hover);
|
||||
const hp = hover ? layout.pos.get(hover) : undefined;
|
||||
if (!hn || !hp) return null;
|
||||
const s = toScreen(hp.x, hp.y);
|
||||
if (s.x < -60 || s.y < -40 || s.x > size.w + 60 || s.y > size.h + 40) return null;
|
||||
const TIPW = 196;
|
||||
const left = s.x < size.w - TIPW - 30;
|
||||
return (
|
||||
<div style={{
|
||||
position: 'absolute', left: left ? s.x + 18 : s.x - TIPW - 18, top: s.y + 12, width: TIPW,
|
||||
pointerEvents: 'none', zIndex: 7,
|
||||
background: 'rgba(6,10,22,0.92)', border: `1px solid ${tk.borderAccent}`, borderRadius: 10,
|
||||
padding: '7px 10px', boxShadow: '0 10px 28px rgba(0,0,0,0.55), 0 0 0 1px rgba(129,140,248,0.1)',
|
||||
backdropFilter: 'blur(8px)',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ width: 7, height: 7, borderRadius: '50%', background: alertColor(levelAt(hn, period), tk), boxShadow: `0 0 6px ${alertColor(levelAt(hn, period), tk)}` }} />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 800, color: tk.text, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{nameOf(hover)}</span>
|
||||
<span style={{ fontSize: 9.5, color: tk.textMuted, fontFamily: 'ui-monospace, monospace' }}>{hn.code}</span>
|
||||
</div>
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 4, marginTop: 5 }}>
|
||||
{([[t.detail.current, `${fmt(valueAt(hn, period))}${unitOf(hn.unit)}`, tk.text],
|
||||
[t.detail.gap, fmtSigned(gapAt(hn, period)) + (hn.unit === '%' ? 'pt' : unitOf(hn.unit)), gapAt(hn, period) >= 0 ? tk.success : tk.danger],
|
||||
[t.detail.achieve, `${fmt(achieveAt(hn, period), 0)}%`, execColor(achieveAt(hn, period), tk)] ] as const).map(([lab, val, col]) => (
|
||||
<div key={lab}>
|
||||
<div style={{ fontSize: 9, color: tk.textMuted }}>{lab}</div>
|
||||
<div style={{ fontSize: 12.5, fontWeight: 800, color: col, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{val}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={{ fontSize: 9.5, color: tk.textMuted, marginTop: 4, display: 'flex', justifyContent: 'space-between', gap: 6 }}>
|
||||
<span>{hn.owner}</span>
|
||||
<span style={{ opacity: 0.75 }}>{t.net.tipToPanel}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{/* 图例与操作提示:深空下加玻璃胶囊衬底,不与标签打架 */}
|
||||
<div style={{
|
||||
position: 'absolute', left: 12, bottom: 10, display: 'flex', gap: 13, flexWrap: 'wrap',
|
||||
fontSize: 12, color: tk.textSub, pointerEvents: 'none',
|
||||
...(stage ? { background: 'rgba(6,10,22,0.55)', border: `1px solid ${tk.border}`, borderRadius: 9, padding: '3px 9px', backdropFilter: 'blur(4px)' } : null),
|
||||
}}>
|
||||
{(['drive', 'conflict', 'monitor'] as const).map(r => (
|
||||
<span key={r} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||
<span style={{ width: 16, height: 2.5, background: relColor(r), borderRadius: 2, boxShadow: `0 0 6px ${relColor(r)}66` }} />{t.net[r]}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<div style={{
|
||||
position: 'absolute', right: 12, bottom: 10, fontSize: 12, color: tk.textMuted, pointerEvents: 'none', maxWidth: '52%', textAlign: 'right',
|
||||
...(stage ? { background: 'rgba(6,10,22,0.55)', border: `1px solid ${tk.border}`, borderRadius: 9, padding: '3px 9px', backdropFilter: 'blur(4px)' } : null),
|
||||
}}>
|
||||
{stage ? t.net.stageHint : t.net.hubHint}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { useEffect, useMemo, useState, type MouseEvent } from 'react';
|
||||
import { ChevronRight, ListTree, Maximize2, Network, Search, Workflow, X } from 'lucide-react';
|
||||
import PanelShell, { PanelBody, CountBadge } from './layout/PanelShell';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import type { MetricNode } from '../data/sqlite';
|
||||
import { alertColor, chainOf, execColor, EXEC_RED_LINE, fmt } from '../lib/metric';
|
||||
import { achieveAt, levelAt, valueAt } from '../lib/time';
|
||||
import { STAGES } from '../lib/process';
|
||||
import ProcessFlowPanel from './process/ProcessFlowPanel';
|
||||
|
||||
const TreeIcon = ListTree;
|
||||
|
||||
interface Props {
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
tree: MetricNode[];
|
||||
flat: MetricNode[];
|
||||
byCode: Map<string, MetricNode>;
|
||||
selected: string;
|
||||
onSelect: (code: string) => void;
|
||||
/** 左栏两种口径:指标树=结果指标,流程效能=过程指标 */
|
||||
mode: 'tree' | 'process';
|
||||
onModeChange: (m: 'tree' | 'process') => void;
|
||||
/** 指标网络全景:把图谱推到中央工作区 */
|
||||
onMaximize?: () => void;
|
||||
/** 全局时间游标:列表里的取值与达成率随时点重算 */
|
||||
period: number;
|
||||
}
|
||||
|
||||
interface Flat { node: MetricNode; depth: number; hasKids: boolean }
|
||||
|
||||
/** 三档视觉权重对应的字号:指标卡(L2)最突出,驱动因子(L3)从属,维度行只作分组标题 */
|
||||
function typo(level: number) {
|
||||
if (level === 0) return { name: 16, nameW: 800, val: 20, valW: 800, unit: 11.5, meta: 11.5, gap: 12.5, dot: 8 };
|
||||
if (level === 1) return { name: 14.5, nameW: 800, val: 15, valW: 800, unit: 10.5, meta: 11.5, gap: 12, dot: 8 };
|
||||
if (level === 2) return { name: 14.5, nameW: 600, val: 17, valW: 800, unit: 11, meta: 11.5, gap: 12.5, dot: 7 };
|
||||
return { name: 13, nameW: 500, val: 14.5, valW: 700, unit: 10, meta: 11, gap: 11.5, dot: 6 };
|
||||
}
|
||||
|
||||
export default function MetricTreePanel({
|
||||
expanded, onToggle, tree, flat, byCode, selected, onSelect, mode, onModeChange, onMaximize, period,
|
||||
}: Props) {
|
||||
const { tokens, theme } = useTheme();
|
||||
const { t } = useText();
|
||||
const isLight = theme === 'light';
|
||||
const [query, setQuery] = useState('');
|
||||
const [collapsed, setCollapsed] = useState<Set<string>>(() => new Set(['D-G', 'D-M', 'D-P', 'D-D', 'D-K']));
|
||||
|
||||
// 外部(数字员工 / 中央看板)改变选中项时,自动展开归属链
|
||||
useEffect(() => {
|
||||
const chain = chainOf(selected, byCode);
|
||||
setCollapsed(prev => {
|
||||
const next = new Set(prev);
|
||||
chain.forEach(c => next.delete(c));
|
||||
return next;
|
||||
});
|
||||
}, [selected, byCode]);
|
||||
|
||||
const name = (n: MetricNode) => (n.name_zh);
|
||||
|
||||
const rows = useMemo<Flat[]>(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
const match = (n: MetricNode) =>
|
||||
name(n).toLowerCase().includes(q)
|
||||
|| n.code.toLowerCase().includes(q)
|
||||
|| n.owner.toLowerCase().includes(q);
|
||||
|
||||
// 搜索态:命中的节点连同其父链一起保留,keepDepth 记录该节点应处的缩进层级
|
||||
const keepDepth = new Map<string, number>();
|
||||
if (q) {
|
||||
flat.forEach(n => {
|
||||
if (!match(n)) return;
|
||||
chainOf(n.code, byCode).forEach((c, i) => {
|
||||
if (!keepDepth.has(c) || keepDepth.get(c)! > i) keepDepth.set(c, i);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const out: Flat[] = [];
|
||||
const walk = (nodes: MetricNode[], depth: number) => {
|
||||
nodes.forEach(n => {
|
||||
const kids = n.children ?? [];
|
||||
if (!q) {
|
||||
out.push({ node: n, depth, hasKids: kids.length > 0 });
|
||||
if (kids.length && !collapsed.has(n.code)) walk(kids, depth + 1);
|
||||
} else if (keepDepth.has(n.code)) {
|
||||
out.push({ node: n, depth: keepDepth.get(n.code)!, hasKids: false });
|
||||
walk(kids, depth + 1);
|
||||
}
|
||||
});
|
||||
};
|
||||
walk(tree, 0);
|
||||
return out.slice(0, 160);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tree, flat, byCode, collapsed, query]);
|
||||
|
||||
const toggleNode = (code: string) => {
|
||||
setCollapsed(prev => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(code)) next.delete(code); else next.add(code);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const segBtn = (active: boolean) => ({
|
||||
display: 'flex' as const, alignItems: 'center' as const, justifyContent: 'center' as const,
|
||||
gap: 5, flex: 1, minWidth: 0, padding: '5px 8px', borderRadius: 7,
|
||||
fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const,
|
||||
background: active ? tokens.accent : 'transparent',
|
||||
color: active ? tokens.onAccent : tokens.textMuted,
|
||||
border: `1px solid ${active ? tokens.accent : tokens.border}`,
|
||||
});
|
||||
|
||||
const isTree = mode === 'tree';
|
||||
|
||||
return (
|
||||
<PanelShell
|
||||
side="left" expanded={expanded} onToggle={onToggle}
|
||||
widthCollapsed={268} widthExpanded={468}
|
||||
icon={isTree ? <TreeIcon size={16} /> : <Workflow size={16} />}
|
||||
title={isTree ? t.panel.metricTree : t.flow.title}
|
||||
badge={<CountBadge n={isTree ? flat.length : STAGES.length} />}
|
||||
animClass="space-animate-left"
|
||||
/* 指标网络不再占一个页签,改为标题行上的一颗按钮:点了就把图谱送到中央工作区。
|
||||
两种页签下都保留这颗钮,不让人从流程效能绕路才能回图谱。 */
|
||||
extra={onMaximize ? (
|
||||
<button
|
||||
onClick={onMaximize}
|
||||
className="ghost-btn"
|
||||
title={t.net.toStage}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0, cursor: 'pointer',
|
||||
padding: '3px 8px', borderRadius: 7, fontSize: 12.5, fontWeight: 700,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
<Network size={13} />{/* 收起态只留图标:标题不被挤成一个字 */}
|
||||
{expanded && t.panel.metricNetwork}
|
||||
{expanded && <Maximize2 size={11} style={{ opacity: 0.75 }} />}
|
||||
</button>
|
||||
) : undefined}
|
||||
tabs={
|
||||
<>
|
||||
<button style={segBtn(isTree)} onClick={() => onModeChange('tree')}>{t.panel.metricTree}</button>
|
||||
<button style={segBtn(!isTree)} onClick={() => onModeChange('process')}>{t.flow.title}</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{isTree ? (
|
||||
<>
|
||||
<div style={{ position: 'relative', marginBottom: 10, flex: '0 0 auto' }}>
|
||||
<Search size={14} style={{ position: 'absolute', left: 10, top: 10, color: tokens.textMuted }} />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={t.tree.search}
|
||||
style={{
|
||||
width: '100%', padding: '8px 30px 8px 31px', fontSize: 13.5, borderRadius: 9,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, color: tokens.text,
|
||||
outline: 'none',
|
||||
}}
|
||||
/>
|
||||
{query && (
|
||||
<button onClick={() => setQuery('')} style={{ position: 'absolute', right: 9, top: 11, color: tokens.textMuted, cursor: 'pointer' }}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 色条语义图例:三档与 execColor / EXEC_RED_LINE 同源,改阈值不会漏改 */}
|
||||
{expanded && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', flexWrap: 'wrap', gap: '4px 11px',
|
||||
marginBottom: 10, flex: '0 0 auto', fontSize: 11.5, color: tokens.textMuted,
|
||||
}}>
|
||||
<span style={{ fontWeight: 700, color: tokens.textSub }}>{t.panel.legendExec}</span>
|
||||
{[
|
||||
{ c: tokens.success, k: t.panel.legendOk },
|
||||
{ c: tokens.warning, k: t.panel.legendWarn },
|
||||
{ c: tokens.danger, k: t.panel.legendBad.replace('{n}', String(EXEC_RED_LINE)) },
|
||||
].map(x => (
|
||||
<span key={x.k} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, whiteSpace: 'nowrap' }}>
|
||||
<i style={{ display: 'inline-block', width: 14, height: 5, borderRadius: 99, background: x.c }} />{x.k}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<PanelBody>
|
||||
{rows.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>{t.tree.noResult}</div>
|
||||
)}
|
||||
{rows.map(({ node: n, depth, hasKids }) => {
|
||||
const active = selected === n.code;
|
||||
const c = alertColor(levelAt(n, period), tokens);
|
||||
const unit = n.unit;
|
||||
const ty = typo(n.level);
|
||||
const kind: 'head' | 'card' | 'drive' = n.level <= 1 ? 'head' : n.level === 2 ? 'card' : 'drive';
|
||||
const rate = achieveAt(n, period); // 游标时点的预算执行率,超额时会大于 100
|
||||
const rateW = Math.max(0, Math.min(rate, 100)); // 条宽封顶:满格即达标
|
||||
const ec = execColor(rate, tokens); // 色条与右侧数字同色,成对引导视线
|
||||
const surface = isLight ? '#ffffff' : tokens.cardBg;
|
||||
const base = active ? tokens.accentBg
|
||||
: kind === 'drive' ? tokens.panelBgAlt
|
||||
: (kind === 'card' || n.level === 0) ? surface
|
||||
: 'transparent';
|
||||
const lift = isLight ? '0 1px 3px rgba(30,60,130,0.09), 0 1px 2px rgba(30,60,130,0.05)' : 'none';
|
||||
const enter = (e: MouseEvent<HTMLDivElement>) => { if (!active) e.currentTarget.style.background = tokens.tableRowHover; };
|
||||
const leave = (e: MouseEvent<HTMLDivElement>) => { if (!active) e.currentTarget.style.background = base; };
|
||||
|
||||
const dot = <span style={{ width: ty.dot, height: ty.dot, borderRadius: 99, background: c, flex: '0 0 auto', boxShadow: `0 0 7px ${c}66` }} />;
|
||||
|
||||
const label = (
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{
|
||||
fontSize: ty.name, fontWeight: ty.nameW, letterSpacing: '0.01em',
|
||||
color: active ? tokens.accent : kind === 'drive' ? tokens.textSub : tokens.text,
|
||||
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>{name(n)}</div>
|
||||
{expanded && n.level >= 2 && (
|
||||
<div style={{
|
||||
fontSize: ty.meta, color: tokens.textMuted, marginTop: 2,
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
|
||||
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>{n.code} · {n.owner}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
const nums = (
|
||||
<div style={{ textAlign: 'right', flex: '0 0 auto', minWidth: 66, whiteSpace: 'nowrap' }}>
|
||||
<div style={{
|
||||
fontSize: ty.val, fontWeight: ty.valW, color: tokens.text, lineHeight: 1.12,
|
||||
fontVariantNumeric: 'tabular-nums', letterSpacing: '0.01em',
|
||||
}}>
|
||||
{fmt(valueAt(n, period))}
|
||||
<span style={{ fontSize: ty.unit, fontWeight: 500, color: tokens.textMuted, marginLeft: 3 }}>{unit}</span>
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: ty.gap, fontWeight: kind === 'drive' ? 600 : 700, color: ec,
|
||||
fontVariantNumeric: 'tabular-nums', marginTop: 1, letterSpacing: '0.01em',
|
||||
}}>
|
||||
{t.detail.reach} {fmt(rate)}%
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
/* L2 指标 → 独立指标卡:卡内留白撑开名称与数值,底边一条达成度进度条 */
|
||||
if (kind === 'card') {
|
||||
return (
|
||||
<div
|
||||
key={n.code} onClick={() => onSelect(n.code)} className="notice-in"
|
||||
onMouseEnter={enter} onMouseLeave={leave}
|
||||
style={{
|
||||
cursor: 'pointer', marginBottom: 5, marginLeft: depth * 11,
|
||||
padding: '8px 10px 7px', borderRadius: 10, background: base,
|
||||
border: `1px solid ${active ? tokens.borderAccent : tokens.border}`,
|
||||
boxShadow: active ? `0 0 0 1px ${tokens.accent}2e, 0 3px 14px rgba(0,0,0,0.2)` : lift,
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{hasKids && (
|
||||
<span
|
||||
onClick={e => { e.stopPropagation(); toggleNode(n.code); }}
|
||||
style={{ width: 16, flex: '0 0 16px', display: 'flex', alignItems: 'center', color: tokens.textMuted, cursor: 'pointer' }}
|
||||
>
|
||||
<ChevronRight size={14} style={{ transform: `rotate(${collapsed.has(n.code) ? 0 : 90}deg)`, transition: 'transform 0.18s' }} />
|
||||
</span>
|
||||
)}
|
||||
{dot}
|
||||
{label}
|
||||
{nums}
|
||||
</div>
|
||||
<div style={{ marginTop: 8, height: 6, borderRadius: 99, background: tokens.border, overflow: 'hidden' }}>
|
||||
<div style={{ width: `${rateW}%`, height: '100%', borderRadius: 99, background: ec, boxShadow: `0 0 8px ${ec}59` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* L3 驱动因子 → 从属子条目:左侧一道状态色连接线,挂在上方指标卡之下 */
|
||||
if (kind === 'drive') {
|
||||
return (
|
||||
<div
|
||||
key={n.code} onClick={() => onSelect(n.code)} className="notice-in"
|
||||
onMouseEnter={enter} onMouseLeave={leave}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer',
|
||||
marginLeft: depth * 11 + 10, marginBottom: 4, padding: '5px 8px',
|
||||
borderRadius: 8, background: base,
|
||||
border: `1px solid ${active ? tokens.borderAccent : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{dot}
|
||||
{label}
|
||||
{nums}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* L0 / L1 → 分组标题行,不参与卡片化,避免 54 行同质方框 */
|
||||
return (
|
||||
<div
|
||||
key={n.code} onClick={() => onSelect(n.code)} className="notice-in"
|
||||
onMouseEnter={enter} onMouseLeave={leave}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 7, cursor: 'pointer',
|
||||
marginLeft: depth * 11, marginBottom: n.level === 0 ? 9 : 4,
|
||||
padding: n.level === 0 ? '8px 10px' : '5px 7px', borderRadius: 9,
|
||||
background: base,
|
||||
border: `1px solid ${active ? tokens.borderAccent : n.level === 0 ? tokens.border : 'transparent'}`,
|
||||
}}
|
||||
>
|
||||
<span
|
||||
onClick={e => { e.stopPropagation(); if (hasKids) toggleNode(n.code); }}
|
||||
style={{
|
||||
width: 16, flex: '0 0 16px', display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
color: tokens.textMuted, cursor: hasKids ? 'pointer' : 'default',
|
||||
}}
|
||||
>
|
||||
{hasKids && <ChevronRight size={14} style={{ transform: `rotate(${collapsed.has(n.code) ? 0 : 90}deg)`, transition: 'transform 0.18s' }} />}
|
||||
</span>
|
||||
{dot}
|
||||
{label}
|
||||
{nums}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</PanelBody>
|
||||
</>
|
||||
) : (
|
||||
<ProcessFlowPanel byCode={byCode} selected={selected} onSelect={onSelect} period={period} />
|
||||
)}
|
||||
</PanelShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
import { Boxes, ChevronLeft, Maximize2, Minimize2 } from 'lucide-react';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import { useText } from '../i18n/useText';
|
||||
import type { DigitalStaff } from '../data/sqlite';
|
||||
import AgentDock from './AgentDock';
|
||||
import { useAgentChat } from '../hooks/useAgentChat';
|
||||
import OntologyView from './ontology/OntologyView';
|
||||
import MetricNetwork from './MetricNetwork';
|
||||
import CausalPanel from './network/CausalPanel';
|
||||
import MetricTimeline from './network/MetricTimeline';
|
||||
import { DEEP } from './network/deepTheme';
|
||||
import type { ExpertTeam } from '../lib/teams';
|
||||
import { CockpitView, DetailView, RegionView, RiskView, StructureView, TrendView } from './workspace/views';
|
||||
import type { ViewProps } from './workspace/views';
|
||||
|
||||
type TabKey = 'detail' | 'trend' | 'structure' | 'region' | 'risk' | 'cockpit';
|
||||
|
||||
/** 左组=全局驾驶舱优先,右组=明细分析收尾 */
|
||||
const PRIMARY: TabKey[] = ['cockpit', 'trend', 'structure'];
|
||||
const SECONDARY: TabKey[] = ['region', 'risk', 'detail'];
|
||||
|
||||
/* 展开高 244:头部 + 一条问候气泡 + 快捷问句 + 输入框刚好占满,
|
||||
不再把图谱挤小半屏换成一段空对话(需要长对话时另有“拉高”档) */
|
||||
const AGENT_EXPANDED = 244;
|
||||
const AGENT_COLLAPSED = 80;
|
||||
|
||||
interface WorkspaceProps {
|
||||
selected: string;
|
||||
staff: DigitalStaff[];
|
||||
viewProps: ViewProps;
|
||||
/** 全局时间游标(0-11):舞台底部滑块拖动,图谱与因果看板同步重算 */
|
||||
period: number;
|
||||
onPeriod: (p: number) => void;
|
||||
/** 指标网络全景舞台:占用整个内容区并自动全屏 */
|
||||
netStage: boolean;
|
||||
onExitNetStage: () => void;
|
||||
/** 专家团多智能体协作:交给底部对话区做轮流会诊 */
|
||||
team: ExpertTeam | null;
|
||||
onDismissTeam: () => void;
|
||||
/** 本体页「定位到订单」:退出本体舞台并在左栏选中该销售订单 */
|
||||
onLocateSO: (so: string) => void;
|
||||
}
|
||||
|
||||
export default function MetricWorkspace({ selected, staff, viewProps, period, onPeriod, netStage, onExitNetStage, team, onDismissTeam, onLocateSO }: WorkspaceProps) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
const [tab, setTab] = useState<TabKey>('cockpit');
|
||||
const [fullscreen, setFullscreen] = useState(false);
|
||||
/* 业务本体总览舞台:与指标网络舞台互斥,同样占用整屏,但用本组件自己的状态管——
|
||||
它不进 App 的全局 netStage,避免两个全景互相踩 */
|
||||
const [ontStage, setOntStage] = useState(false);
|
||||
const [agentOpen, setAgentOpen] = useState(true);
|
||||
const [agentTall, setAgentTall] = useState(false);
|
||||
/* 舞台右栏因果看板:默认展开,收起时只留一条把手,不抢图谱空间 */
|
||||
const [causalOpen, setCausalOpen] = useState(true);
|
||||
// 拉高态高度随视口自适应:约占视口 58%,且不低于常规展开+120,避免小屏把内容区挤没
|
||||
const [vh, setVh] = useState(() => window.innerHeight);
|
||||
useEffect(() => {
|
||||
const onR = () => setVh(window.innerHeight);
|
||||
window.addEventListener('resize', onR);
|
||||
return () => window.removeEventListener('resize', onR);
|
||||
}, []);
|
||||
const agentTallH = Math.max(AGENT_EXPANDED + 120, Math.round(vh * 0.58));
|
||||
|
||||
const node = viewProps.byCode.get(selected);
|
||||
|
||||
/* 会话状态机放在这一层:本体舞台会替换整块内容区(对话区随之卸载),
|
||||
状态上提后「从回答卡跳进本体页再退回」会话历史与进行中的推演都不丢 */
|
||||
const chat = useAgentChat({ staff, byCode: viewProps.byCode, selected: node, team, t });
|
||||
|
||||
// 进入任一全景舞台即全屏,退出舞台还原(把图从窄栏解放到整屏)
|
||||
useEffect(() => { setFullscreen(netStage || ontStage); }, [netStage, ontStage]);
|
||||
|
||||
// 专家团就位即展开对话区,让轮流会诊立即可见
|
||||
useEffect(() => { if (team) setAgentOpen(true); }, [team]);
|
||||
|
||||
// 左侧换节点时回到全景驾驶舱,避免用户以为"点了没反应"
|
||||
useEffect(() => { if (selected) setTab('cockpit'); }, [selected]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!fullscreen) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
setOntStage(false);
|
||||
setFullscreen(false);
|
||||
};
|
||||
// 捕获阶段注册:页签 / 对话区里的子组件即使阻断冒泡,ESC 仍然能退出
|
||||
window.addEventListener('keydown', onKey, true);
|
||||
return () => window.removeEventListener('keydown', onKey, true);
|
||||
}, [fullscreen]);
|
||||
|
||||
const activeColor = tokens.accent;
|
||||
|
||||
const corners = useMemo(
|
||||
() =>
|
||||
(['top-left', 'top-right', 'bottom-left', 'bottom-right'] as const).map(pos => {
|
||||
const [v, h] = pos.split('-');
|
||||
return {
|
||||
key: pos,
|
||||
style: {
|
||||
position: 'absolute', top: v === 'top' ? 7 : undefined, bottom: v === 'bottom' ? 7 : undefined,
|
||||
left: h === 'left' ? 7 : undefined, right: h === 'right' ? 7 : undefined,
|
||||
width: 16, height: 16, pointerEvents: 'none', zIndex: 3, opacity: 0.55,
|
||||
borderTop: v === 'top' ? `2px solid ${tokens.accent}` : undefined,
|
||||
borderBottom: v === 'bottom' ? `2px solid ${tokens.accent}` : undefined,
|
||||
borderLeft: h === 'left' ? `2px solid ${tokens.accent}` : undefined,
|
||||
borderRight: h === 'right' ? `2px solid ${tokens.accent}` : undefined,
|
||||
} as CSSProperties,
|
||||
};
|
||||
}),
|
||||
[tokens.accent],
|
||||
);
|
||||
|
||||
const renderView = () => {
|
||||
if (tab === 'trend') return <TrendView {...viewProps} />;
|
||||
if (tab === 'structure') return <StructureView {...viewProps} />;
|
||||
if (tab === 'region') return <RegionView {...viewProps} />;
|
||||
if (tab === 'risk') return <RiskView {...viewProps} />;
|
||||
if (tab === 'cockpit') return <CockpitView {...viewProps} />;
|
||||
return <DetailView {...viewProps} />;
|
||||
};
|
||||
|
||||
/* 对话区实例:舞台态嵌进左列(与图谱同宽),让右栏看板能贯通到底;
|
||||
非舞台态仍满宽占据工作区底部 */
|
||||
const agentDock = (
|
||||
<AgentDock
|
||||
staff={staff}
|
||||
chat={chat}
|
||||
team={team}
|
||||
onDismissTeam={onDismissTeam}
|
||||
onLocateSO={onLocateSO}
|
||||
onOpenOntology={() => setOntStage(true)}
|
||||
height={!agentOpen ? AGENT_COLLAPSED : agentTall ? agentTallH : AGENT_EXPANDED}
|
||||
onToggle={() => { setAgentOpen(v => !v); setAgentTall(false); }}
|
||||
tall={agentTall}
|
||||
onToggleTall={() => { setAgentOpen(true); setAgentTall(v => !v); }}
|
||||
/>
|
||||
);
|
||||
|
||||
const tabBtn = (k: TabKey) => {
|
||||
const on = tab === k;
|
||||
return (
|
||||
<button
|
||||
key={k}
|
||||
onClick={() => setTab(k)}
|
||||
style={{
|
||||
padding: '6px 16px', borderRadius: 9, fontSize: 13, cursor: 'pointer',
|
||||
fontWeight: on ? 700 : 500,
|
||||
border: `1px solid ${on ? 'transparent' : tokens.border}`,
|
||||
background: on ? activeColor : 'transparent',
|
||||
color: on ? tokens.onAccent : tokens.textSub,
|
||||
boxShadow: on ? `0 2px 8px ${activeColor}40` : 'none',
|
||||
transition: 'background 0.18s ease, color 0.18s ease',
|
||||
whiteSpace: 'nowrap', letterSpacing: '0.02em',
|
||||
}}
|
||||
>
|
||||
{t.tab[k]}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className="card-in"
|
||||
style={{
|
||||
position: fullscreen ? 'fixed' : 'relative',
|
||||
inset: fullscreen ? 0 : undefined,
|
||||
zIndex: fullscreen ? 60 : 1,
|
||||
flex: '1 1 auto', minWidth: 0, height: '100%',
|
||||
display: 'flex', flexDirection: 'column', overflow: 'hidden',
|
||||
borderRadius: fullscreen ? 0 : 16,
|
||||
border: `1px solid ${tokens.borderAccent}`,
|
||||
background: tokens.centerBg,
|
||||
boxShadow: tokens.centerShadow,
|
||||
backdropFilter: 'blur(10px) saturate(1.3)',
|
||||
}}
|
||||
>
|
||||
{corners.map(c => <div key={c.key} style={c.style} />)}
|
||||
|
||||
{/* 标题栏 */}
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center',
|
||||
gap: 12, padding: '14px 22px 10px', flexShrink: 0,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
|
||||
<button
|
||||
onClick={() => {
|
||||
// 本体舞台里的手柄只负责退出,不让它退成"半屏本体"
|
||||
if (ontStage) { setOntStage(false); setFullscreen(false); return; }
|
||||
setFullscreen(f => !f);
|
||||
}}
|
||||
title={fullscreen ? `${t.tab.clickToRestore} (ESC)` : t.panel.workspace}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
width: 28, height: 28, borderRadius: 8, flexShrink: 0, cursor: 'pointer',
|
||||
display: 'grid', placeItems: 'center',
|
||||
border: `1px solid ${tokens.borderAccent}`, background: tokens.accentBg, color: tokens.accent,
|
||||
}}
|
||||
>
|
||||
{fullscreen ? <Minimize2 size={14} /> : <Maximize2 size={14} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<h2 style={{
|
||||
margin: 0, textAlign: 'center', whiteSpace: 'nowrap',
|
||||
color: tokens.text, fontSize: 24, fontWeight: 800, letterSpacing: '0.05em', textShadow: tokens.titleGlow,
|
||||
}}>
|
||||
{ontStage ? '业务本体总览' : netStage ? t.panel.metricNetwork : t.panel.workspace}
|
||||
</h2>
|
||||
|
||||
<div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', gap: 8, minWidth: 0 }}>
|
||||
{fullscreen && <span style={{ color: tokens.textMuted, fontSize: 11, whiteSpace: 'nowrap' }}>{t.tab.clickToRestore} / ESC</span>}
|
||||
{/* 原「当前指标名」药签改为业务本体入口:整屏舞台看四层结构,选中指标不再占用标题栏 */}
|
||||
<button
|
||||
onClick={() => {
|
||||
if (ontStage) { setOntStage(false); setFullscreen(false); return; }
|
||||
if (netStage) onExitNetStage();
|
||||
setOntStage(true);
|
||||
}}
|
||||
title="查看业务对象、关系、规则与动作(实时统计)"
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flexShrink: 0, cursor: 'pointer',
|
||||
fontSize: 12.5, fontWeight: 700, padding: '3px 11px', borderRadius: 20, whiteSpace: 'nowrap',
|
||||
color: ontStage ? tokens.onAccent : tokens.accent,
|
||||
background: ontStage ? tokens.accent : tokens.accentBg,
|
||||
border: `1px solid ${ontStage ? tokens.accent : tokens.borderAccent}`,
|
||||
boxShadow: ontStage ? `0 2px 10px ${tokens.accent}55` : 'none',
|
||||
transition: 'background .18s ease, color .18s ease',
|
||||
}}
|
||||
>
|
||||
<Boxes size={13} />
|
||||
业务本体总览
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 页签栏(全景舞台与本体舞台时让位给主内容) */}
|
||||
<div style={{ display: netStage || ontStage ? 'none' : 'flex', alignItems: 'center', gap: 6, padding: '0 22px 12px', flexShrink: 0, flexWrap: 'wrap' }}>
|
||||
{PRIMARY.map(tabBtn)}
|
||||
<span style={{ color: tokens.textMuted, fontSize: 14, margin: '0 2px', opacity: 0.6 }}>›</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ width: 1, height: 18, background: tokens.borderAccent, margin: '0 6px' }} />
|
||||
{SECONDARY.map(tabBtn)}
|
||||
</div>
|
||||
|
||||
{/* 内容区:舞台与非舞台共用同一棵子树——时间轴与对话区固定是左列的第 2 / 3 个子节点,
|
||||
进出全景只会重建第 1 个子节点(图谱 ⇄ 明细视图),对话历史因此不会被抹掉。
|
||||
舞台 7:3:左=图谱 + 时间轴 + 对话(70%)· 右=因果看板贯通到底(30%)
|
||||
本体舞台独占整块内容区:四层结构本身要占满宽度,时间轴与对话区在此让位。 */}
|
||||
<div style={{
|
||||
flex: 1, minHeight: 0, display: 'flex', gap: 9,
|
||||
padding: ontStage ? '0 18px 14px' : netStage ? '0 14px 12px' : '0 22px 12px',
|
||||
}}>
|
||||
{ontStage ? (
|
||||
<OntologyView
|
||||
onExit={() => { setOntStage(false); setFullscreen(false); }}
|
||||
onLocateSO={so => { setOntStage(false); setFullscreen(false); onLocateSO(so); }}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<div style={{
|
||||
flex: netStage ? '7 1 0' : '1 1 auto', minWidth: 0,
|
||||
display: 'flex', flexDirection: 'column', gap: 8,
|
||||
}}>
|
||||
{netStage ? (
|
||||
<div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
|
||||
<MetricNetwork
|
||||
stage selected={selected} byCode={viewProps.byCode} flat={viewProps.flat}
|
||||
links={viewProps.links} onSelect={viewProps.onSelect} expanded onExitStage={onExitNetStage}
|
||||
period={period}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
/* key=tab 触发入场动画,让切换有落点感 */
|
||||
<div key={tab} className="content-reveal space-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>
|
||||
{renderView()}
|
||||
</div>
|
||||
)}
|
||||
{/* 全局时间游标:两种形态都常驻——时间轴是全局口径开关,不该只活在全景里 */}
|
||||
<MetricTimeline
|
||||
period={period} onPeriod={onPeriod} ov={viewProps.byCode.get('OV')}
|
||||
tokens={netStage ? { ...tokens, ...DEEP } : tokens} t={t}
|
||||
/>
|
||||
<div style={{
|
||||
flex: '0 0 auto', borderRadius: netStage ? 12 : 0, overflow: 'hidden',
|
||||
border: netStage ? `1px solid ${tokens.borderAccent}` : 'none',
|
||||
}}>
|
||||
{agentDock}
|
||||
</div>
|
||||
</div>
|
||||
{/* 地板降到 240:非全屏的小窗口下也不至多把图谱压成几十px */}
|
||||
{netStage && (causalOpen ? (
|
||||
<div style={{ flex: '3 1 0', minWidth: 240, maxWidth: 660, display: 'flex' }}>
|
||||
<CausalPanel
|
||||
code={selected} byCode={viewProps.byCode} flat={viewProps.flat}
|
||||
links={viewProps.links} staff={staff} period={period}
|
||||
deep onSelect={viewProps.onSelect} onClose={() => setCausalOpen(false)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => setCausalOpen(true)}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
width: 26, flexShrink: 0, cursor: 'pointer', display: 'flex', flexDirection: 'column',
|
||||
alignItems: 'center', justifyContent: 'center', gap: 8, borderRadius: 12,
|
||||
writingMode: 'vertical-rl' as const, letterSpacing: '0.08em',
|
||||
fontSize: 11.5, fontWeight: 700, color: tokens.accent,
|
||||
background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
<ChevronLeft size={13} style={{ transform: 'rotate(90deg)' }} />
|
||||
{t.net.causalOpen}
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
|
||||
/**
|
||||
* 流动透明球体背景(科技感氛围层)。
|
||||
* 参考同级看板项目的 StarBackground 实现,改为透明底:不覆盖 mec 自身的 bodyBgImage 渐变,
|
||||
* 只在其上叠加漂浮光球 / 星点 / 深空云雾,固定定位 zIndex 0,内容层以 zIndex 1 覆盖其上。
|
||||
*/
|
||||
interface Orb {
|
||||
x: number; y: number; r: number;
|
||||
vx: number; vy: number;
|
||||
color: string;
|
||||
glowAlpha: number;
|
||||
pulsePhase: number;
|
||||
pulseSpeed: number;
|
||||
}
|
||||
|
||||
export default function StarBackground() {
|
||||
const { theme } = useTheme();
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const canvas = canvasRef.current;
|
||||
if (!canvas) return;
|
||||
const ctx = canvas.getContext('2d');
|
||||
if (!ctx) return;
|
||||
|
||||
const resize = () => {
|
||||
canvas.width = window.innerWidth;
|
||||
canvas.height = window.innerHeight;
|
||||
};
|
||||
resize();
|
||||
window.addEventListener('resize', resize);
|
||||
|
||||
// 星点
|
||||
const stars = Array.from({ length: 160 }, () => ({
|
||||
x: Math.random() * canvas.width,
|
||||
y: Math.random() * canvas.height,
|
||||
r: Math.random() * 1.2 + 0.2,
|
||||
opacity: Math.random() * 0.6 + 0.2,
|
||||
speed: Math.random() * 0.015 + 0.005,
|
||||
phase: Math.random() * Math.PI * 2,
|
||||
}));
|
||||
|
||||
// 深空云雾
|
||||
const nebula = Array.from({ length: 6 }, (_, i) => ({
|
||||
x: (i / 6) * canvas.width + Math.random() * 200 - 100,
|
||||
y: Math.random() * canvas.height,
|
||||
r: Math.random() * 180 + 120,
|
||||
color: ['rgba(99,102,241,', 'rgba(56,189,248,', 'rgba(40,0,120,', 'rgba(0,80,160,', 'rgba(0,229,153,', 'rgba(120,100,255,'][i],
|
||||
}));
|
||||
|
||||
// 流动透明球体:大球 + 小球混合
|
||||
const darkOrbColors = [
|
||||
'rgba(220,240,255,', 'rgba(200,230,255,', 'rgba(255,255,255,', 'rgba(230,240,255,',
|
||||
'rgba(56,189,248,', 'rgba(129,140,248,', 'rgba(52,211,153,', 'rgba(0,212,255,',
|
||||
];
|
||||
const lightOrbColors = [
|
||||
'rgba(160,185,230,', 'rgba(180,200,240,', 'rgba(200,215,245,', 'rgba(140,170,220,',
|
||||
'rgba(100,140,210,', 'rgba(129,140,248,', 'rgba(120,160,220,', 'rgba(190,210,245,',
|
||||
];
|
||||
const orbColors = theme === 'dark' ? darkOrbColors : lightOrbColors;
|
||||
const orbGlowBase = theme === 'dark' ? 0.025 : 0.07;
|
||||
const orbs: Orb[] = Array.from({ length: 110 }, (_, i) => ({
|
||||
x: Math.random() * canvas.width,
|
||||
y: Math.random() * canvas.height,
|
||||
r: i < 40 ? (Math.random() * 30 + 35) : (Math.random() * 12 + 10),
|
||||
vx: (Math.random() - 0.5) * 2.2,
|
||||
vy: (Math.random() - 0.5) * 1.6,
|
||||
color: orbColors[i % orbColors.length],
|
||||
glowAlpha: Math.random() * orbGlowBase + orbGlowBase * 0.4,
|
||||
pulsePhase: Math.random() * Math.PI * 2,
|
||||
pulseSpeed: Math.random() * 0.012 + 0.006,
|
||||
}));
|
||||
|
||||
let frame = 0;
|
||||
let animId: number;
|
||||
|
||||
const draw = () => {
|
||||
frame++;
|
||||
const W = canvas.width;
|
||||
const H = canvas.height;
|
||||
// 透明底:只清空,不填充不透明背景,保留 mec 自身 bodyBgImage 渐变
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
|
||||
// 星云雾
|
||||
nebula.forEach(n => {
|
||||
const g = ctx.createRadialGradient(n.x, n.y, 0, n.x, n.y, n.r);
|
||||
const nebulaAlpha = theme === 'dark' ? '0.05' : '0.035';
|
||||
g.addColorStop(0, n.color + nebulaAlpha + ')');
|
||||
g.addColorStop(1, n.color + '0)');
|
||||
ctx.fillStyle = g;
|
||||
ctx.beginPath();
|
||||
ctx.arc(n.x, n.y, n.r, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
|
||||
// 流动球体
|
||||
orbs.forEach(orb => {
|
||||
orb.x += orb.vx;
|
||||
orb.y += orb.vy;
|
||||
if (orb.x < -orb.r) orb.x = W + orb.r;
|
||||
if (orb.x > W + orb.r) orb.x = -orb.r;
|
||||
if (orb.y < -orb.r) orb.y = H + orb.r;
|
||||
if (orb.y > H + orb.r) orb.y = -orb.r;
|
||||
|
||||
const pulse = 0.7 + 0.3 * Math.sin(frame * orb.pulseSpeed + orb.pulsePhase);
|
||||
const alpha = orb.glowAlpha * pulse;
|
||||
|
||||
// 外层光晕
|
||||
const outerR = orb.r * 1.5;
|
||||
const outerGrad = ctx.createRadialGradient(orb.x, orb.y, 0, orb.x, orb.y, outerR);
|
||||
outerGrad.addColorStop(0, orb.color + (alpha * 0.9).toFixed(3) + ')');
|
||||
outerGrad.addColorStop(0.5, orb.color + (alpha * 0.3).toFixed(3) + ')');
|
||||
outerGrad.addColorStop(1, orb.color + '0)');
|
||||
ctx.fillStyle = outerGrad;
|
||||
ctx.beginPath();
|
||||
ctx.arc(orb.x, orb.y, outerR, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
// 内层球体
|
||||
const innerGrad = ctx.createRadialGradient(
|
||||
orb.x - orb.r * 0.2, orb.y - orb.r * 0.2, 0,
|
||||
orb.x, orb.y, orb.r,
|
||||
);
|
||||
innerGrad.addColorStop(0, orb.color + (alpha * 2.0).toFixed(3) + ')');
|
||||
innerGrad.addColorStop(0.6, orb.color + (alpha * 0.8).toFixed(3) + ')');
|
||||
innerGrad.addColorStop(1, orb.color + '0)');
|
||||
ctx.fillStyle = innerGrad;
|
||||
ctx.beginPath();
|
||||
ctx.arc(orb.x, orb.y, orb.r, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
|
||||
// 高光点
|
||||
const hlR = orb.r * 0.25;
|
||||
const hlGrad = ctx.createRadialGradient(
|
||||
orb.x - orb.r * 0.25, orb.y - orb.r * 0.25, 0,
|
||||
orb.x - orb.r * 0.25, orb.y - orb.r * 0.25, hlR,
|
||||
);
|
||||
hlGrad.addColorStop(0, 'rgba(255,255,255,' + (alpha * 4).toFixed(3) + ')');
|
||||
hlGrad.addColorStop(1, 'rgba(255,255,255,0)');
|
||||
ctx.fillStyle = hlGrad;
|
||||
ctx.beginPath();
|
||||
ctx.arc(orb.x - orb.r * 0.25, orb.y - orb.r * 0.25, hlR, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
});
|
||||
|
||||
// 星点闪烁
|
||||
stars.forEach(s => {
|
||||
const twinkle = 0.3 + 0.7 * (0.5 + 0.5 * Math.sin(frame * s.speed + s.phase));
|
||||
ctx.beginPath();
|
||||
ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
|
||||
ctx.fillStyle = theme === 'dark'
|
||||
? `rgba(180,220,255,${s.opacity * twinkle})`
|
||||
: `rgba(100,140,200,${s.opacity * twinkle * 0.5})`;
|
||||
ctx.fill();
|
||||
if (s.r > 1.0) {
|
||||
const halo = ctx.createRadialGradient(s.x, s.y, 0, s.x, s.y, s.r * 4);
|
||||
halo.addColorStop(0, theme === 'dark'
|
||||
? `rgba(100,200,255,${0.2 * twinkle})`
|
||||
: `rgba(80,130,220,${0.08 * twinkle})`);
|
||||
halo.addColorStop(1, 'rgba(0,0,0,0)');
|
||||
ctx.fillStyle = halo;
|
||||
ctx.beginPath();
|
||||
ctx.arc(s.x, s.y, s.r * 4, 0, Math.PI * 2);
|
||||
ctx.fill();
|
||||
}
|
||||
});
|
||||
|
||||
animId = requestAnimationFrame(draw);
|
||||
};
|
||||
|
||||
draw();
|
||||
return () => {
|
||||
cancelAnimationFrame(animId);
|
||||
window.removeEventListener('resize', resize);
|
||||
};
|
||||
}, [theme]);
|
||||
|
||||
return (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
position: 'fixed', top: 0, left: 0,
|
||||
width: '100%', height: '100%',
|
||||
zIndex: 0, pointerEvents: 'none',
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Boxes, Search, Truck, Users, X } from 'lucide-react';
|
||||
import PanelShell, { CountBadge } from './layout/PanelShell';
|
||||
import { AutoScrollProvider, AutoScrollToggle } from './layout/AutoScroll';
|
||||
import { RIGHT_MOTION } from '../hooks/useAutoScroll';
|
||||
import { useTheme } from '../context/ThemeContext';
|
||||
import PurchaseOrderList, { buildPurchaseGroups, filterPurchaseGroups } from './supply/PurchaseOrderList';
|
||||
import ProductionOrderList, { buildWorkOrders, filterWorkOrders } from './supply/ProductionOrderList';
|
||||
import SupplierList, { buildSuppliers, filterSuppliers } from './supply/SupplierList';
|
||||
|
||||
type TabKey = 'po' | 'wo' | 'sup';
|
||||
|
||||
interface Props {
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
/** 左栏选中的销售订单号:三个页签各自反查关联单据 */
|
||||
selectedSO: string | null;
|
||||
onSelectSO: (so: string | null) => void;
|
||||
}
|
||||
|
||||
const TABS: { key: TabKey; label: string; short: string; icon: typeof Truck; placeholder: string }[] = [
|
||||
{ key: 'po', label: '采购单', short: '采购', icon: Truck, placeholder: '搜索采购单号 / 供应商 / 材料' },
|
||||
{ key: 'wo', label: '生产工单', short: '工单', icon: Boxes, placeholder: '搜索工单号 / 来源订单 / 产品编码 / 车间' },
|
||||
{ key: 'sup', label: '供应商资料', short: '供方', icon: Users, placeholder: '搜索供应商编码 / 简称 / 类别 / 部门' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 右侧供应与生产执行栏:采购单、生产工单、供应商资料三个页签共用一块弧板,
|
||||
* 搜索关键词、展开态与左栏订单联动在三者之间保持同一份状态。
|
||||
*/
|
||||
export default function SupplyPanel({ expanded, onToggle, selectedSO, onSelectSO }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const [tab, setTab] = useState<TabKey>('po');
|
||||
/* 外部把订单选中时切回采购单页签:与左栏同一联动理由 */
|
||||
const prevSO = useRef(selectedSO);
|
||||
useEffect(() => {
|
||||
if (selectedSO && selectedSO !== prevSO.current) setTab('po');
|
||||
prevSO.current = selectedSO;
|
||||
}, [selectedSO]);
|
||||
const [query, setQuery] = useState('');
|
||||
/* 卡片多到一屏装不下时自动缓慢下滚;标题栏按钮可关闭,三个页签共用这一个开关 */
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
|
||||
/* 徽标数与页签内容走同一组纯函数,标题数字不会和列表条数打架 */
|
||||
const count = useMemo(() => {
|
||||
const q = query.trim();
|
||||
if (tab === 'po') return filterPurchaseGroups(buildPurchaseGroups(selectedSO), q).length;
|
||||
if (tab === 'wo') return filterWorkOrders(buildWorkOrders(selectedSO), q).length;
|
||||
return filterSuppliers(buildSuppliers(selectedSO), q).length;
|
||||
}, [tab, query, selectedSO]);
|
||||
|
||||
const segBtn = (active: boolean) => ({
|
||||
display: 'flex' as const, alignItems: 'center' as const, justifyContent: 'center' as const,
|
||||
gap: 5, flex: 1, minWidth: 0, padding: '5px 8px', borderRadius: 7,
|
||||
fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const,
|
||||
background: active ? tokens.accent : 'transparent',
|
||||
color: active ? tokens.onAccent : tokens.textMuted,
|
||||
border: `1px solid ${active ? tokens.accent : tokens.border}`,
|
||||
});
|
||||
|
||||
const current = TABS.find(x => x.key === tab)!;
|
||||
const Icon = current.icon;
|
||||
|
||||
return (
|
||||
<PanelShell
|
||||
side="right" expanded={expanded} onToggle={onToggle}
|
||||
widthCollapsed={268} widthExpanded={468}
|
||||
icon={<Icon size={16} />}
|
||||
title={current.label}
|
||||
badge={<CountBadge n={count} />}
|
||||
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll(v => !v)} expanded={expanded} />}
|
||||
animClass="space-animate-right"
|
||||
tabs={
|
||||
<>
|
||||
{TABS.map(x => (
|
||||
/* 收起态宽度只够两个字:页签用短标签,避免挤成一列竖排 */
|
||||
<button key={x.key} style={segBtn(tab === x.key)} onClick={() => setTab(x.key)}>
|
||||
{expanded ? x.label : x.short}
|
||||
</button>
|
||||
))}
|
||||
</>
|
||||
}
|
||||
>
|
||||
{/* 搜索:三个页签共用,占位提示随页签切换 */}
|
||||
<div style={{ position: 'relative', marginBottom: 10, flex: '0 0 auto' }}>
|
||||
<Search size={14} style={{ position: 'absolute', left: 10, top: 10, color: tokens.textMuted }} />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder={current.placeholder}
|
||||
style={{
|
||||
width: '100%', padding: '8px 30px 8px 31px', fontSize: 13.5, borderRadius: 9,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, color: tokens.text,
|
||||
outline: 'none',
|
||||
}}
|
||||
/>
|
||||
{query && (
|
||||
<button onClick={() => setQuery('')} style={{ position: 'absolute', right: 9, top: 11, color: tokens.textMuted, cursor: 'pointer', background: 'none', border: 'none' }}>
|
||||
<X size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<AutoScrollProvider value={{ enabled: autoScroll, cfg: RIGHT_MOTION }}>
|
||||
{tab === 'po' && (
|
||||
<PurchaseOrderList
|
||||
query={query}
|
||||
filterSO={selectedSO}
|
||||
onClearFilter={() => onSelectSO(null)}
|
||||
/>
|
||||
)}
|
||||
{tab === 'wo' && (
|
||||
<ProductionOrderList
|
||||
query={query}
|
||||
filterSO={selectedSO}
|
||||
onClearFilter={() => onSelectSO(null)}
|
||||
selectedSO={selectedSO}
|
||||
onSelectSO={onSelectSO}
|
||||
/>
|
||||
)}
|
||||
{tab === 'sup' && (
|
||||
<SupplierList
|
||||
query={query}
|
||||
filterSO={selectedSO}
|
||||
onClearFilter={() => onSelectSO(null)}
|
||||
/* 点供应商=带着它的编码跳到采购单页签,只看这家下的单 */
|
||||
onPickSupplier={code => { setQuery(code); setTab('po'); }}
|
||||
/>
|
||||
)}
|
||||
</AutoScrollProvider>
|
||||
</PanelShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { ArrowRight, BrainCircuit, ChevronRight, CircleAlert, Database, Layers, Lightbulb, ListChecks, Sparkles, Table2 } from 'lucide-react';
|
||||
import type { ThemeTokens } from '../../context/ThemeContext';
|
||||
import type { I18n } from '../../i18n/locales';
|
||||
import type { AskAnswer, AskStep, AskTone } from '../../lib/ibpAsk';
|
||||
|
||||
/**
|
||||
* 履约风险回答卡:思考过程(逐条揭示,揭示完折叠成一行)+ 规范六段式正文
|
||||
* 结论 / 关键数字 / 风险明细 / 依据与口径 / 建议动作 / 数据来源。
|
||||
* 只负责渲染,所有数字与文案由 lib/ibpAsk.ts 从业务本体层现算。
|
||||
*/
|
||||
|
||||
const toneColor = (tone: AskTone | undefined, tk: ThemeTokens) =>
|
||||
tone === 'danger' ? tk.danger
|
||||
: tone === 'warning' ? tk.warning
|
||||
: tone === 'success' ? tk.success
|
||||
: tone === 'info' ? tk.info
|
||||
: tk.accent;
|
||||
|
||||
/** 小节标题:细线 + 图标 + 文案,让六段结构一眼可辨 */
|
||||
function SecHead({ icon, text, tk, hint }: { icon: ReactNode; text: string; tk: ThemeTokens; hint?: string }) {
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 1 }}>
|
||||
{icon}
|
||||
<span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: '0.06em', color: tk.textMuted }}>{text}</span>
|
||||
{hint && <span style={{ fontSize: 10.5, color: tk.textMuted, opacity: 0.8 }}>· {hint}</span>}
|
||||
<span style={{ flex: 1, height: 1, background: tk.borderSub }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 打字点:思考进行中用,揭示一条停一条 */
|
||||
function Dots({ tk }: { tk: ThemeTokens }) {
|
||||
return (
|
||||
<span style={{ display: 'flex', gap: 3, alignItems: 'center' }}>
|
||||
{[0, 1, 2].map(i => (
|
||||
<i key={i} className="typing-dot" style={{ animationDelay: `${i * 0.16}s`, background: tk.accent }} />
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** 小节思考提示:斜体 + info 色,让各区块的生成有呼吸感 */
|
||||
function BlockThink({ text, tk }: { text: string; tk: ThemeTokens }) {
|
||||
return (
|
||||
<div className="content-reveal" style={{ display: 'flex', alignItems: 'center', gap: 6, padding: '2px 0' }}>
|
||||
<Dots tk={tk} />
|
||||
<span style={{ fontSize: 11.5, fontStyle: 'italic', color: tk.info, lineHeight: 1.55 }}>{text}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type BlockKey = 'metrics' | 'table' | 'points' | 'actions' | 'source';
|
||||
const BLOCKS: BlockKey[] = ['metrics', 'table', 'points', 'actions', 'source'];
|
||||
type Phase = 'hidden' | 'thinking' | 'ready';
|
||||
|
||||
const THINK_MS = 1600;
|
||||
const GAP_MS = 600;
|
||||
const PRE_CONCLUSION_MS = 900;
|
||||
const CHAR_MS = 65;
|
||||
const TICK_MS = 80;
|
||||
|
||||
function blockHasContent(answer: AskAnswer, key: BlockKey) {
|
||||
switch (key) {
|
||||
case 'metrics': return answer.metrics.length > 0;
|
||||
case 'table': return !!answer.table;
|
||||
case 'points': return answer.points.length > 0;
|
||||
case 'actions': return answer.actions.length > 0;
|
||||
case 'source': return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** 每个正文块的揭示时间点:用于按 elapsed-time 推进,避免后台 tab 的 setTimeout 被节流后卡住 */
|
||||
interface BlockSchedule { key: BlockKey; thinkAt: number; readyAt: number }
|
||||
|
||||
/**
|
||||
* 思考过程轨:running 时逐条出现(由父级推进 revealed),出答案后折叠成
|
||||
* 「思考过程 · 6 步 · 耗时 2.8s」一行,点开可复查每一步做了什么、依据哪张表。
|
||||
*/
|
||||
export function StepTrace({
|
||||
steps, revealed, running, elapsed, tk, t,
|
||||
}: {
|
||||
steps: AskStep[]; revealed: number; running: boolean; elapsed?: number; tk: ThemeTokens; t: I18n;
|
||||
}) {
|
||||
const [open, setOpen] = useState(running);
|
||||
const shown = steps.slice(0, Math.max(0, revealed));
|
||||
const label = t.agent.thinkSteps.replace('{n}', String(steps.length));
|
||||
const time = elapsed !== undefined ? t.agent.thinkElapsed.replace('{s}', elapsed.toFixed(1)) : t.agent.thinkHint;
|
||||
return (
|
||||
<div style={{
|
||||
border: `1px ${running ? 'solid' : 'dashed'} ${tk.borderAccent}`, borderRadius: 10,
|
||||
background: running ? tk.accentBg : tk.cardBg, overflow: 'hidden',
|
||||
}}>
|
||||
<button
|
||||
onClick={() => setOpen(v => !v)}
|
||||
aria-expanded={open}
|
||||
data-role="think-toggle"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, width: '100%', cursor: 'pointer',
|
||||
padding: '5px 9px', border: 'none', background: 'transparent', textAlign: 'left',
|
||||
}}
|
||||
>
|
||||
<BrainCircuit size={12} color={tk.accent} style={{ flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 11.5, fontWeight: 700, color: tk.accent, flexShrink: 0 }}>{t.agent.thinkTitle}</span>
|
||||
<span style={{ fontSize: 11, color: tk.textMuted, fontVariantNumeric: 'tabular-nums' }}>{label} · {time}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{running && <Dots tk={tk} />}
|
||||
<ChevronRight size={12} color={tk.textMuted} style={{ flexShrink: 0, transform: open ? 'rotate(90deg)' : undefined, transition: 'transform 0.18s ease' }} />
|
||||
</button>
|
||||
{open && (
|
||||
<div style={{ padding: '2px 9px 8px', display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
{shown.map((s, i) => (
|
||||
<div key={i} className="content-reveal" style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{
|
||||
flex: '0 0 15px', width: 15, height: 15, borderRadius: 5, display: 'grid', placeItems: 'center', marginTop: 1,
|
||||
fontSize: 10, fontWeight: 700, fontVariantNumeric: 'tabular-nums',
|
||||
color: tk.onAccent, background: tk.accent,
|
||||
}}>{i + 1}</span>
|
||||
<span style={{ minWidth: 0, fontSize: 11.5, lineHeight: 1.55 }}>
|
||||
<span style={{ color: tk.text, fontWeight: 700 }}>{s.act}</span>
|
||||
<span style={{ color: tk.textMuted }}> · {s.detail}</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
{running && revealed < steps.length && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11.5, color: tk.textMuted }}>
|
||||
<Dots tk={tk} />
|
||||
{steps[revealed]?.act ?? t.agent.thinkHint}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface CardProps {
|
||||
answer: AskAnswer;
|
||||
elapsed: number;
|
||||
tk: ThemeTokens;
|
||||
t: I18n;
|
||||
time: string;
|
||||
/** 派发给哪位数字员工(回答卡头部标注,保留数字员工协同设定) */
|
||||
staff?: string;
|
||||
onLocate: (so: string) => void;
|
||||
onAsk: (q: string) => void;
|
||||
onOntology: () => void;
|
||||
}
|
||||
|
||||
export default function AskAnswerCard({ answer, elapsed, tk, t, time, staff, onLocate, onAsk, onOntology }: CardProps) {
|
||||
const sev = toneColor(answer.severity, tk);
|
||||
const tone = (x?: AskTone) => toneColor(x, tk);
|
||||
const iconOf = (a: AskAnswer['actions'][number]) =>
|
||||
a.locateSO ? <ArrowRight size={11} /> : a.ontology ? <Layers size={11} /> : <ChevronRight size={11} />;
|
||||
const run = (a: AskAnswer['actions'][number]) => {
|
||||
if (a.locateSO) onLocate(a.locateSO);
|
||||
else if (a.ontology) onOntology();
|
||||
else if (a.ask) onAsk(a.ask);
|
||||
};
|
||||
|
||||
/* 结论生成节奏:先停顿「整理结论中」→ 逐字流式输出 → 每个正文区块先显示
|
||||
「思考中」提示再揭示内容,整体明显慢于「瞬间甩结果」,让推理过程可感知。
|
||||
用 elapsed-time 调度:即使页面在后台 tab 被节流,回到前台后也会按真实
|
||||
耗时一次性追赶到对应进度,不会无限卡住。 */
|
||||
const [streamed, setStreamed] = useState('');
|
||||
const [preparing, setPreparing] = useState(true);
|
||||
const [phases, setPhases] = useState<Record<BlockKey, Phase>>(() =>
|
||||
Object.fromEntries(BLOCKS.map(k => [k, 'hidden'])) as Record<BlockKey, Phase>
|
||||
);
|
||||
const scheduleRef = useRef<BlockSchedule[]>([]);
|
||||
const startRef = useRef<number>(0);
|
||||
const streamStartRef = useRef<number>(0);
|
||||
const preparingRef = useRef<boolean>(true);
|
||||
const conclusionDone = answer.conclusion.length === 0 || streamed.length === answer.conclusion.length;
|
||||
|
||||
useEffect(() => {
|
||||
setStreamed('');
|
||||
setPreparing(true);
|
||||
preparingRef.current = true;
|
||||
streamStartRef.current = 0;
|
||||
setPhases(Object.fromEntries(BLOCKS.map(k => [k, 'hidden'])) as Record<BlockKey, Phase>);
|
||||
startRef.current = Date.now();
|
||||
|
||||
// 预排各正文块的 thinking / ready 时间点,按相对结论输出完成后的绝对时间推进
|
||||
let offset = 80;
|
||||
scheduleRef.current = BLOCKS.reduce<BlockSchedule[]>((acc, key, idx) => {
|
||||
if (!blockHasContent(answer, key)) return acc;
|
||||
const thinkAt = offset;
|
||||
const readyAt = thinkAt + THINK_MS + idx * 80;
|
||||
acc.push({ key, thinkAt, readyAt });
|
||||
offset = readyAt + GAP_MS;
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const chars = answer.conclusion.split('');
|
||||
const totalChars = chars.length;
|
||||
|
||||
const updateBlocks = (blockElapsed: number) => {
|
||||
scheduleRef.current.forEach(({ key, thinkAt, readyAt }) => {
|
||||
if (blockElapsed >= readyAt) {
|
||||
setPhases(p => (p[key] === 'ready' ? p : { ...p, [key]: 'ready' }));
|
||||
} else if (blockElapsed >= thinkAt) {
|
||||
setPhases(p => (p[key] === 'thinking' || p[key] === 'ready' ? p : { ...p, [key]: 'thinking' }));
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const tick = () => {
|
||||
const now = Date.now();
|
||||
const elapsed = now - startRef.current;
|
||||
|
||||
if (preparingRef.current) {
|
||||
if (elapsed >= PRE_CONCLUSION_MS) {
|
||||
preparingRef.current = false;
|
||||
streamStartRef.current = now;
|
||||
setPreparing(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (totalChars === 0) {
|
||||
// 无结论时直接揭示区块
|
||||
updateBlocks(elapsed - PRE_CONCLUSION_MS);
|
||||
return;
|
||||
}
|
||||
|
||||
const streamElapsed = now - streamStartRef.current;
|
||||
const idx = Math.min(totalChars, Math.floor(streamElapsed / CHAR_MS));
|
||||
setStreamed(chars.slice(0, idx).join(''));
|
||||
|
||||
if (idx >= totalChars) {
|
||||
// 结论已流完,按结论完成后时间点推进区块
|
||||
updateBlocks(streamElapsed - totalChars * CHAR_MS);
|
||||
}
|
||||
};
|
||||
|
||||
const id = window.setInterval(tick, TICK_MS);
|
||||
return () => window.clearInterval(id);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [answer.conclusion]);
|
||||
|
||||
return (
|
||||
<div className="content-reveal" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
|
||||
<div style={{ maxWidth: '96%', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||
{/* 卡头:智能体名 + 识别到的意图 + 派发员工 + 时间 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{
|
||||
width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0,
|
||||
background: `linear-gradient(135deg, ${tk.accent}, ${tk.info})`,
|
||||
}}>
|
||||
<Sparkles size={11} color={tk.onAccent} />
|
||||
</span>
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tk.accent, flexShrink: 0 }}>{t.agent.aiName}</span>
|
||||
<span style={{
|
||||
fontSize: 10.5, color: tk.textMuted, padding: '0 6px', borderRadius: 7,
|
||||
border: `1px solid ${tk.border}`, background: tk.cardBg, whiteSpace: 'nowrap',
|
||||
}}>{t.agent.secIntent}:{answer.intent}</span>
|
||||
{staff && (
|
||||
<span style={{ fontSize: 10.5, color: tk.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', minWidth: 0 }}>{staff}</span>
|
||||
)}
|
||||
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{time}</span>
|
||||
</div>
|
||||
|
||||
<StepTrace steps={answer.steps} revealed={answer.steps.length} elapsed={elapsed} running={false} tk={tk} t={t} />
|
||||
|
||||
{/* 正文卡 */}
|
||||
<div style={{
|
||||
background: tk.cardBg, border: `1px solid ${tk.border}`, borderLeft: `3px solid ${sev}`,
|
||||
borderRadius: '4px 12px 12px 12px', padding: '9px 12px',
|
||||
display: 'flex', flexDirection: 'column', gap: 9, minWidth: 0,
|
||||
}}>
|
||||
{/* ① 结论:先「整理结论中」停顿,再逐字流出 */}
|
||||
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<CircleAlert size={13} color={sev} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<span style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.65, color: tk.text, minWidth: 0 }}>
|
||||
{preparing ? (
|
||||
<span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<Dots tk={tk} />
|
||||
<span style={{ fontStyle: 'italic', color: tk.info }}>正在整合关键数字与规则口径,生成结论…</span>
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{streamed}
|
||||
{!conclusionDone && <span className="stream-cursor" style={{ marginLeft: 2, display: 'inline-block', width: 2, height: 14, background: tk.accent, verticalAlign: 'middle' }} />}
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* ② 关键数字 */}
|
||||
{phases.metrics === 'thinking' && <BlockThink text={t.agent.thinkNumbers} tk={tk} />}
|
||||
{phases.metrics === 'ready' && !!answer.metrics.length && (
|
||||
<div className="content-reveal" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
|
||||
<SecHead icon={<ListChecks size={11} color={tk.textMuted} />} text={t.agent.secNumbers} tk={tk} />
|
||||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
|
||||
{answer.metrics.map((m, i) => {
|
||||
const c = tone(m.tone);
|
||||
return (
|
||||
<span key={i} style={{
|
||||
display: 'flex', alignItems: 'baseline', gap: 5, padding: '3px 9px', borderRadius: 8,
|
||||
background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}`,
|
||||
}}>
|
||||
<span style={{ fontSize: 11, color: tk.textMuted, whiteSpace: 'nowrap' }}>{m.label}</span>
|
||||
<span style={{ fontSize: 13, fontWeight: 800, color: c, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{m.value}</span>
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ③ 风险明细表 */}
|
||||
{phases.table === 'thinking' && <BlockThink text={t.agent.thinkTable} tk={tk} />}
|
||||
{phases.table === 'ready' && answer.table && (
|
||||
<div className="content-reveal" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
|
||||
<SecHead
|
||||
icon={<Table2 size={11} color={tk.textMuted} />} text={t.agent.secTable} tk={tk}
|
||||
hint={`${answer.table.rows.length} 行`}
|
||||
/>
|
||||
<div style={{ marginTop: 4, overflowX: 'auto', border: `1px solid ${tk.borderSub}`, borderRadius: 9 }}>
|
||||
<table style={{ borderCollapse: 'collapse', width: '100%', fontSize: 11.5, whiteSpace: 'nowrap' }}>
|
||||
<thead>
|
||||
<tr style={{ background: tk.panelBgAlt }}>
|
||||
{answer.table.cols.map((c, i) => (
|
||||
<th key={i} style={{
|
||||
textAlign: 'left', fontWeight: 700, color: tk.textMuted, padding: '5px 8px',
|
||||
borderBottom: `1px solid ${tk.border}`, fontSize: 10.5, letterSpacing: '0.04em',
|
||||
}}>{c}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{answer.table.rows.map((r, ri) => {
|
||||
const c = tone(r.tone);
|
||||
return (
|
||||
<tr key={ri} style={{ background: r.tone ? `${c}0d` : undefined, borderBottom: ri < answer.table!.rows.length - 1 ? `1px solid ${tk.borderSub}` : undefined }}>
|
||||
{r.cells.map((cell, ci) => (
|
||||
<td key={ci} style={{
|
||||
padding: '4px 8px',
|
||||
color: ci === 0 ? (r.tone ? c : tk.text) : tk.textSub,
|
||||
fontWeight: ci === 0 ? 700 : 400,
|
||||
fontVariantNumeric: 'tabular-nums',
|
||||
fontFamily: ci === 0 ? undefined : 'ui-monospace, monospace',
|
||||
}}>{cell}</td>
|
||||
))}
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ④ 依据与口径 */}
|
||||
{phases.points === 'thinking' && <BlockThink text={t.agent.thinkBasis} tk={tk} />}
|
||||
{phases.points === 'ready' && !!answer.points.length && (
|
||||
<div className="content-reveal" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
|
||||
<SecHead icon={<BrainCircuit size={11} color={tk.textMuted} />} text={t.agent.secBasis} tk={tk} />
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 4 }}>
|
||||
{answer.points.map((p, i) => {
|
||||
const c = tone(p.tone);
|
||||
return (
|
||||
<div key={i} style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
|
||||
<span style={{
|
||||
flex: '0 0 auto', fontSize: 10.5, fontWeight: 700, marginTop: 1, padding: '1px 6px', borderRadius: 6,
|
||||
color: p.tone ? c : tk.textMuted,
|
||||
background: p.tone ? `${c}14` : tk.panelBgAlt,
|
||||
border: `1px solid ${p.tone ? `${c}33` : tk.border}`,
|
||||
whiteSpace: 'nowrap', maxWidth: 130, overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>{p.label}</span>
|
||||
<span style={{ fontSize: 12, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>{p.text}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ⑤ 建议动作 */}
|
||||
{phases.actions === 'thinking' && <BlockThink text={t.agent.thinkActions} tk={tk} />}
|
||||
{phases.actions === 'ready' && !!answer.actions.length && (
|
||||
<div className="content-reveal" style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
|
||||
<SecHead icon={<Lightbulb size={11} color={tk.textMuted} />} text={t.agent.secActions} tk={tk} />
|
||||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
|
||||
{answer.actions.map((a, i) => (
|
||||
<button
|
||||
key={i}
|
||||
onClick={() => run(a)}
|
||||
data-role={a.locateSO ? `locate-${a.locateSO}` : a.ontology ? 'open-ontology' : 'ask-more'}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11.5, fontWeight: 600, cursor: 'pointer',
|
||||
color: tk.accent, background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
|
||||
borderRadius: 8, padding: '3px 10px', whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{iconOf(a)}{a.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ⑥ 数据来源 */}
|
||||
{phases.source === 'thinking' && <BlockThink text={t.agent.thinkSource} tk={tk} />}
|
||||
{phases.source === 'ready' && (
|
||||
<div className="content-reveal" style={{ display: 'flex', alignItems: 'flex-start', gap: 5, paddingTop: 3, borderTop: `1px dashed ${tk.borderSub}` }}>
|
||||
<Database size={10} color={tk.textMuted} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<span style={{ fontSize: 10.5, color: tk.textMuted, minWidth: 0, lineHeight: 1.55 }}>
|
||||
<span style={{ fontWeight: 700 }}>{t.agent.secSource}:</span>{answer.source}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Building2, Link2, X } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import { customers, salesOrders, type Customer } from '../../data/ibp';
|
||||
import { ScrollList } from '../supply/PurchaseOrderList';
|
||||
import { money } from '../../lib/money';
|
||||
|
||||
/**
|
||||
* 客户资料页签:Excel「客户资料」的 9 个字段全量展示(订单笔数 / 订单金额沿用表内汇总口径)。
|
||||
* 左栏选中销售订单时,只列出该订单的客户——关联关系由销售订单行反推,不另外造数据。
|
||||
*/
|
||||
|
||||
/** 按订单金额从大到小:贡献多的客户先看 */
|
||||
export function sortCustomers(rows: Customer[]): Customer[] {
|
||||
return [...rows].sort((a, b) => b.订单金额 - a.订单金额);
|
||||
}
|
||||
|
||||
/** filterSO 非空时用销售订单行反查该订单的客户编码 */
|
||||
export function buildCustomers(filterSO: string | null): Customer[] {
|
||||
if (!filterSO) return sortCustomers(customers);
|
||||
const codes = new Set(salesOrders.filter(s => s.销售订单号 === filterSO).map(s => s.客户编码));
|
||||
return sortCustomers(customers.filter(c => codes.has(c.客户编码)));
|
||||
}
|
||||
|
||||
/** 编码 / 简称 / 客户分类 / 所属类别 / 分管部门 五向模糊匹配 */
|
||||
export function filterCustomers(rows: Customer[], query: string): Customer[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter(c =>
|
||||
c.客户编码.toLowerCase().includes(q)
|
||||
|| c.客户简称.toLowerCase().includes(q)
|
||||
|| c.客户分类.toLowerCase().includes(q)
|
||||
|| c.所属类别.toLowerCase().includes(q)
|
||||
|| (c.分管部门 ?? '').toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
/** 客商一体(性质=客户/供应商)是治理关注项,单独给色 */
|
||||
const natureColor = (nature: string, tk: ThemeTokens) =>
|
||||
nature === '客户/供应商' ? { c: tk.warning, bg: tk.warningBg } : { c: tk.info, bg: tk.infoBg };
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
filterSO: string | null;
|
||||
onClearFilter: () => void;
|
||||
/** 点击客户:把客户编码填进搜索框并切回销售订单页签 */
|
||||
onPickCustomer: (code: string) => void;
|
||||
}
|
||||
|
||||
export default function CustomerList({ query, filterSO, onClearFilter, onPickCustomer }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const list = useMemo(() => filterCustomers(buildCustomers(filterSO), query), [filterSO, query]);
|
||||
const total = useMemo(() => list.reduce((a, c) => a + c.订单金额, 0), [list]);
|
||||
const totalOrders = useMemo(() => list.reduce((a, c) => a + c.订单笔数, 0), [list]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{filterSO && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
|
||||
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
<Link2 size={12} style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO} · 仅该单涉及的客户</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button onClick={onClearFilter} title="显示全部客户" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 汇总条 */}
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
|
||||
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
|
||||
}}>
|
||||
<span>{list.length} 家客户 · {totalOrders} 笔订单</span>
|
||||
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{money(total)}</span>
|
||||
</div>
|
||||
|
||||
<ScrollList>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
|
||||
{filterSO ? '该销售订单暂无匹配客户' : '无匹配客户'}
|
||||
</div>
|
||||
)}
|
||||
{list.map(c => {
|
||||
const nc = natureColor(c.性质, tokens);
|
||||
return (
|
||||
<div
|
||||
key={c.客户编码}
|
||||
onClick={() => onPickCustomer(c.客户编码)}
|
||||
title="点击只看这家客户的销售订单"
|
||||
style={{
|
||||
marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
|
||||
transition: 'background .15s, border-color .15s',
|
||||
}}
|
||||
>
|
||||
{/* 行1:简称 + 编码 + 性质 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<Building2 size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{c.客户简称}
|
||||
</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{c.客户编码}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{
|
||||
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
|
||||
color: nc.c, background: nc.bg, border: `1px solid ${nc.c}44`, whiteSpace: 'nowrap',
|
||||
}}>{c.性质}</span>
|
||||
</div>
|
||||
{/* 行2:客户分类 + 所属类别 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textSub, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{c.客户分类}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textSub, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{c.所属类别}</span>
|
||||
</div>
|
||||
{/* 行3:分管部门 + 序号 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{c.分管部门 || '分管部门未填'}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>序 {c.序号}</span>
|
||||
</div>
|
||||
{/* 行4:金额 + 笔数 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{money(c.订单金额)}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{c.订单笔数} 笔订单</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ScrollList>
|
||||
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, flex: '0 0 auto', paddingTop: 6,
|
||||
fontSize: 10.5, color: tokens.textMuted, borderTop: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<span style={{ flex: 1 }}>笔数与金额为该客户在本批销售订单中的合计,与销售订单页签同源可核对</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Package } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import { salesOrders, type SalesOrder } from '../../data/ibp';
|
||||
import { ScrollList } from '../supply/PurchaseOrderList';
|
||||
import { money } from '../../lib/money';
|
||||
|
||||
/**
|
||||
* 销售订单页签内容:Excel「销售订单」全量卡片列表。
|
||||
* 列表口径交给纯函数,DemandPanel 用同一函数算页签徽标数,标题数字与条数不会各说各话。
|
||||
*/
|
||||
|
||||
/** 订单号 / 客户简称 / 客户编码 / 产品编码 四向模糊匹配 */
|
||||
export function filterSalesOrders(rows: SalesOrder[], query: string): SalesOrder[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter((s: SalesOrder) =>
|
||||
s.销售订单号.toLowerCase().includes(q)
|
||||
|| s.客户简称.toLowerCase().includes(q)
|
||||
|| s.客户编码.toLowerCase().includes(q)
|
||||
|| s.产品编码.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const statusColor = (s: string, tk: ThemeTokens) =>
|
||||
s === '生效' || s === '已下达' ? { c: tk.success, bg: tk.successBg } : { c: tk.warning, bg: tk.warningBg };
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
expanded: boolean;
|
||||
/** 当前选中的销售订单号(联动右侧采购单 / 生产工单 / 供应商与本页客户资料过滤) */
|
||||
selectedSO: string | null;
|
||||
onSelectSO: (so: string | null) => void;
|
||||
}
|
||||
|
||||
export default function SalesOrderList({ query, expanded, selectedSO, onSelectSO }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const list = useMemo(() => filterSalesOrders(salesOrders, query), [query]);
|
||||
const total = useMemo(() => list.reduce((a, s) => a + s.含税金额, 0), [list]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 汇总条 */}
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
|
||||
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
|
||||
}}>
|
||||
<span>{list.length} 张订单 · {new Set(list.map(s => s.客户编码)).size} 家客户</span>
|
||||
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{money(total)}</span>
|
||||
</div>
|
||||
|
||||
<ScrollList>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>无匹配订单</div>
|
||||
)}
|
||||
{list.map(s => {
|
||||
const active = selectedSO === s.销售订单号;
|
||||
const sc = statusColor(s.单据状态, tokens);
|
||||
return (
|
||||
<div
|
||||
key={s.销售订单号}
|
||||
onClick={() => onSelectSO(active ? null : s.销售订单号)}
|
||||
style={{
|
||||
position: 'relative', marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
|
||||
background: active ? tokens.accentBg : tokens.panelBgAlt,
|
||||
border: `1px solid ${active ? tokens.accent : tokens.border}`,
|
||||
transition: 'background .15s, border-color .15s',
|
||||
}}
|
||||
>
|
||||
{active && <span style={{ position: 'absolute', left: -1, top: 10, bottom: 10, width: 3, borderRadius: 2, background: tokens.accent }} />}
|
||||
{/* 行1:单号 + 状态 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 13.5, fontWeight: 700, color: active ? tokens.accent : tokens.text, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
|
||||
{s.销售订单号}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{
|
||||
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
|
||||
color: sc.c, background: sc.bg, border: `1px solid ${sc.c}44`, whiteSpace: 'nowrap',
|
||||
}}>{s.单据状态}</span>
|
||||
</div>
|
||||
{/* 行2:客户 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
|
||||
<span style={{ fontSize: 12, color: tokens.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.客户简称}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{s.客户分类}</span>
|
||||
</div>
|
||||
{/* 行3:产品 + 数量 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5 }}>
|
||||
<Package size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 12.5, color: tokens.text, fontFamily: 'ui-monospace, monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.产品编码}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 12, color: tokens.textSub, fontVariantNumeric: 'tabular-nums' }}>{s.数量.toLocaleString()} PCS</span>
|
||||
</div>
|
||||
{/* 行4:金额 + 交期 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 14.5, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{money(s.含税金额)}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted }}>发货 {s.预计发货日期}</span>
|
||||
</div>
|
||||
{expanded && (
|
||||
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 4 }}>{s.仓库名称} · {s.制单人} · 下单 {s.单据日期}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ScrollList>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
import { Pause, Play } from 'lucide-react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import { DEFAULT_MOTION, type MotionCfg } from '../../hooks/useAutoScroll';
|
||||
|
||||
/**
|
||||
* 左右工作区列表的自动滚动配置。
|
||||
* 用 context 下发而不是逐层传 prop:一份弧板里挂着好几个页签
|
||||
* (左:销售订单 / 客户资料;右:采购单 / 生产工单 / 供应商资料),
|
||||
* 开关与滚动节奏属于「这块面板」而不是某个列表,页签组件本身不该关心它。
|
||||
* 左右两侧使用不同速度,形成差异性效果。
|
||||
*/
|
||||
interface ScrollCfg { enabled: boolean; cfg: MotionCfg }
|
||||
const AutoScrollCtx = createContext<ScrollCfg>({ enabled: false, cfg: DEFAULT_MOTION });
|
||||
|
||||
export const AutoScrollProvider = AutoScrollCtx.Provider;
|
||||
|
||||
/** 当前面板的自动滚动开关 + 滚动节奏;ScrollList 用它决定是否挂滚动循环及速度 */
|
||||
export const useAutoScrollEnabled = () => useContext(AutoScrollCtx);
|
||||
|
||||
interface ToggleProps {
|
||||
on: boolean;
|
||||
onToggle: () => void;
|
||||
/** 收起态宽度只够一个图标,文字标签在展开态才出现 */
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
/** 面板标题栏的自动滚动开关按钮:开=可点击关闭,关=可点击开启 */
|
||||
export function AutoScrollToggle({ on, onToggle, expanded = true }: ToggleProps) {
|
||||
const { tokens } = useTheme();
|
||||
const c = on ? tokens.accent : tokens.textMuted;
|
||||
return (
|
||||
<button
|
||||
onClick={onToggle}
|
||||
aria-pressed={on}
|
||||
title={on ? '列表自动滚动中,点击关闭' : '自动滚动已关闭,点击开启'}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0,
|
||||
height: 22, padding: expanded ? '0 7px 0 5px' : '0 5px', borderRadius: 6, cursor: 'pointer',
|
||||
fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap',
|
||||
color: c, background: on ? tokens.accentBg : 'transparent',
|
||||
border: `1px solid ${on ? tokens.borderAccent : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{on ? <Pause size={12} /> : <Play size={12} />}
|
||||
{expanded && <span>{on ? '自动滚动' : '已暂停'}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { forwardRef, type ReactNode } from 'react';
|
||||
import { ChevronsLeft, ChevronsRight } from 'lucide-react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
|
||||
/** 侧板外凸弧线的水平位移(与参考实现一致的"太空舱"侧板语法) */
|
||||
const BULGE = 28;
|
||||
|
||||
interface PanelShellProps {
|
||||
side: 'left' | 'right';
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
widthCollapsed?: number;
|
||||
widthExpanded?: number;
|
||||
icon?: ReactNode;
|
||||
title: string;
|
||||
badge?: ReactNode;
|
||||
extra?: ReactNode;
|
||||
/** 独占一行的分段切换,避免与标题争抢标题行宽度 */
|
||||
tabs?: ReactNode;
|
||||
hint?: string;
|
||||
children: ReactNode;
|
||||
animClass?: string;
|
||||
}
|
||||
|
||||
export default function PanelShell({
|
||||
side, expanded, onToggle, widthCollapsed = 268, widthExpanded = 452,
|
||||
icon, title, badge, extra, tabs, hint, children, animClass,
|
||||
}: PanelShellProps) {
|
||||
const { tokens } = useTheme();
|
||||
const W = expanded ? widthExpanded : widthCollapsed;
|
||||
const totalW = W + BULGE;
|
||||
const gid = `mec-pnl-${side}`;
|
||||
const left = side === 'left';
|
||||
|
||||
const path = left
|
||||
? `M 0,0 L ${W - 70},0 Q ${W},0 ${W},80 C ${W + BULGE},2000 ${W + BULGE},8000 ${W},9920 L 0,10000 Z`
|
||||
: `M ${totalW},0 L ${BULGE + 70},0 Q ${BULGE},0 ${BULGE},80 C 0,2000 0,8000 ${BULGE},9920 L ${totalW},10000 Z`;
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`panel-shell ${animClass ?? ''}`}
|
||||
style={{
|
||||
position: 'relative', width: totalW, height: '100%', flex: '0 0 auto',
|
||||
transition: 'width 0.3s cubic-bezier(0.4,0,0.2,1)',
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
viewBox={`0 0 ${totalW} 10000`}
|
||||
preserveAspectRatio="none"
|
||||
style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', overflow: 'visible' }}
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id={gid} x1={left ? '0' : '1'} y1="0" x2={left ? '1' : '0'} y2="1">
|
||||
<stop offset="0%" stopColor={tokens.svgPanelFrom} />
|
||||
<stop offset="100%" stopColor={tokens.svgPanelTo} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<path d={path} fill={`url(#${gid})`} />
|
||||
<path d={path} fill="none" stroke={tokens.svgStroke} strokeWidth={6} opacity={0.18} />
|
||||
<path d={path} fill="none" stroke={tokens.svgStroke} strokeWidth={1} />
|
||||
<circle cx={left ? W : BULGE} cy={80} r={3.5} fill={tokens.svgDot} />
|
||||
<circle cx={left ? W : BULGE} cy={9920} r={3.5} fill={tokens.svgDot} />
|
||||
</svg>
|
||||
|
||||
{/* 内容层压在弧板之上,宽度不超过直边区域 */}
|
||||
<div
|
||||
style={{
|
||||
position: 'absolute', top: 0, bottom: 0,
|
||||
[left ? 'left' : 'right']: 0,
|
||||
width: W,
|
||||
display: 'flex', flexDirection: 'column', minHeight: 0,
|
||||
padding: left ? '10px 24px 8px 14px' : '10px 14px 8px 24px',
|
||||
backdropFilter: 'blur(14px)', WebkitBackdropFilter: 'blur(14px)',
|
||||
} as React.CSSProperties}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, height: 30, flex: '0 0 auto' }}>
|
||||
<span style={{ width: 3, height: 16, borderRadius: 2, background: tokens.accent, flex: '0 0 auto' }} />
|
||||
{icon && <span style={{ display: 'flex', color: tokens.accent }}>{icon}</span>}
|
||||
<span style={{
|
||||
fontSize: 15, fontWeight: 700, color: tokens.text, letterSpacing: '0.02em',
|
||||
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
flex: '0 1 auto', minWidth: 0,
|
||||
}}>{title}</span>
|
||||
{badge}
|
||||
<span style={{ flex: 1 }} />
|
||||
{extra}
|
||||
<button
|
||||
onClick={onToggle}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center',
|
||||
width: 22, height: 22, borderRadius: 5, cursor: 'pointer', flexShrink: 0,
|
||||
color: tokens.textMuted, border: `1px solid ${tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{expanded
|
||||
? (left ? <ChevronsLeft size={13} /> : <ChevronsRight size={13} />)
|
||||
: (left ? <ChevronsRight size={13} /> : <ChevronsLeft size={13} />)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{tabs && (
|
||||
<div style={{ display: 'flex', gap: 4, flex: '0 0 auto', marginBottom: 8 }}>{tabs}</div>
|
||||
)}
|
||||
|
||||
{hint && (
|
||||
<div style={{ fontSize: 12.5, color: tokens.textMuted, marginBottom: 7, lineHeight: 1.45 }}>
|
||||
{hint}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 面板内统一的滚动容器;ref 外放,供调用方实现自动滚动等滚动控制 */
|
||||
export const PanelBody = forwardRef<HTMLDivElement, { children: ReactNode; pad?: string }>(
|
||||
function PanelBody({ children, pad = '0 0 10px 0' }, ref) {
|
||||
return (
|
||||
<div ref={ref} className="space-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: pad }}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/** 标题栏数量徽标 */
|
||||
export function CountBadge({ n, color }: { n: number | string; color?: string }) {
|
||||
const { tokens } = useTheme();
|
||||
return (
|
||||
<span style={{
|
||||
fontSize: 12, fontWeight: 700, padding: '1px 8px', borderRadius: 10,
|
||||
background: `${color ?? tokens.accent}22`, color: color ?? tokens.accent,
|
||||
border: `1px solid ${color ?? tokens.accent}33`, lineHeight: '16px',
|
||||
}}>{n}</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { useMemo } from 'react';
|
||||
import { ArrowLeft, ArrowRight, X } from 'lucide-react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import { useText } from '../../i18n/useText';
|
||||
import type { DigitalStaff, MetricLink, MetricNode } from '../../data/sqlite';
|
||||
import { alertColor, descendantsOf, execColor, fmt, fmtSigned } from '../../lib/metric';
|
||||
import { achieveAt, gapAt, levelAt, momAt, periodLabel, seriesOf, valueAt } from '../../lib/time';
|
||||
import { DEEP } from './deepTheme';
|
||||
|
||||
/**
|
||||
* 因果看板:图谱选中实体的「右栏一览」。
|
||||
* 把散在浮层卡里的信息升级为纵向叙事——游标读数 → 12 期趋势 → 前因 → 后果 → 下级回应 → AI 研判 → 汇报口径,
|
||||
* 全部数值随底部时间滑块重算,拖动即可看同一指标在不同时点的因果表现。
|
||||
*/
|
||||
interface Props {
|
||||
code: string | null;
|
||||
byCode: Map<string, MetricNode>;
|
||||
flat: MetricNode[];
|
||||
links: MetricLink[];
|
||||
staff: DigitalStaff[];
|
||||
period: number;
|
||||
/** 舞台态跟随深空主题,面板态跟随用户主题 */
|
||||
deep: boolean;
|
||||
onSelect: (code: string) => void;
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
export default function CausalPanel({ code, byCode, flat, links, staff, period, deep, onSelect, onClose }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
const tk = deep ? { ...tokens, ...DEEP } : tokens;
|
||||
|
||||
const node = code ? byCode.get(code) : undefined;
|
||||
|
||||
/* 子树集合:维度/总览看辖域对外语义关联;L0 无从切分 → 回退全图最强因果链 */
|
||||
const isRoot = node?.level === 0;
|
||||
const set = useMemo(() => {
|
||||
if (!node) return null;
|
||||
const s = new Set<string>([node.code]);
|
||||
if (node.level <= 1) descendantsOf(node.code, flat).forEach(d => s.add(d.code));
|
||||
return s;
|
||||
}, [node, flat]);
|
||||
|
||||
const { incoming, outgoing } = useMemo(() => {
|
||||
if (!set) return { incoming: [], outgoing: [] as MetricLink[] };
|
||||
if (isRoot) {
|
||||
return { incoming: [] as MetricLink[], outgoing: [...links].sort((a, b) => Math.abs(b.strength) - Math.abs(a.strength)).slice(0, 6) };
|
||||
}
|
||||
return {
|
||||
incoming: links.filter(l => set.has(l.to_code) && !set.has(l.from_code)),
|
||||
outgoing: links.filter(l => set.has(l.from_code) && !set.has(l.to_code)),
|
||||
};
|
||||
}, [set, links, isRoot]);
|
||||
|
||||
const kids = useMemo(
|
||||
() => (node ? flat.filter(n => n.parent_code === node.code) : []),
|
||||
[node, flat],
|
||||
);
|
||||
|
||||
/* 同层对标:末级没有“下级回应”可看,就拿同父兄弟作参照,看板不至于空一块 */
|
||||
const sibs = useMemo(
|
||||
() => (node && node.parent_code && kids.length === 0)
|
||||
? flat.filter(n => n.parent_code === node.parent_code && n.code !== node.code)
|
||||
: [],
|
||||
[node, flat, kids.length],
|
||||
);
|
||||
|
||||
if (!node) {
|
||||
return (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', justifyContent: 'center', flex: '1 1 auto', minWidth: 0, height: '100%',
|
||||
padding: 18, textAlign: 'center', fontSize: 12.5, lineHeight: 1.8, color: tk.textMuted,
|
||||
background: tk.panelBgAlt, border: `1px solid ${tk.border}`, borderRadius: 12,
|
||||
}}>
|
||||
点击图谱中的任意节点,这里将展开它的前因、后果与下级回应。
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const name = node.name_zh;
|
||||
const lv = levelAt(node, period);
|
||||
const c = alertColor(lv, tk);
|
||||
const val = valueAt(node, period);
|
||||
const gap = gapAt(node, period);
|
||||
const ach = achieveAt(node, period);
|
||||
const mom = momAt(node, period);
|
||||
const gapU = node.unit === '%' ? 'pt' : (node.unit);
|
||||
const valU = node.unit;
|
||||
/** 子指标偏差单位:% 类走 pt,其余按语言取单位(不在中文句里漏出日文汉字) */
|
||||
const kidGapU = (n: MetricNode) => (n.unit === '%' ? 'pt' : (n.unit));
|
||||
const series = seriesOf(node);
|
||||
const maxStrength = links.reduce((m, l) => Math.max(m, Math.abs(l.strength)), 0.001);
|
||||
const nameOf = (cd: string) => {
|
||||
const n = byCode.get(cd);
|
||||
return !n ? cd : n.name_zh;
|
||||
};
|
||||
|
||||
/* ---- AI 研判:游标读数 + 近 4 期斜率 + 最弱子项 / 最强前因 ---- */
|
||||
const win = series.slice(Math.max(0, period - 3), period + 1);
|
||||
const slope = win.length >= 2 ? +((win[win.length - 1] - win[0]) / Math.max(1, win.length - 1)).toFixed(2) : 0;
|
||||
const improving = node.polarity === 'down' ? slope < 0 : slope > 0;
|
||||
const weakening = node.polarity === 'down' ? slope > 0 : slope < 0;
|
||||
const kidGaps = kids.map(k => ({ k, g: gapAt(k, period) })).sort((a, b) => a.g - b.g);
|
||||
const worstKid = kidGaps.find(x => x.g < 0)?.k;
|
||||
const topCause = incoming.length
|
||||
? [...incoming].sort((a, b) => Math.abs(b.strength) - Math.abs(a.strength))[0]
|
||||
: null;
|
||||
const verdicts: { text: string; tone: string }[] = [
|
||||
{
|
||||
text: `${periodLabel(period)} 当期:${name} ${fmt(val)}${valU},较目标 ${fmtSigned(gap)}${gapU}(达成 ${fmt(ach, 0)}%)。`,
|
||||
tone: lv === 'red' ? tk.danger : lv === 'yellow' ? tk.warning : tk.success,
|
||||
},
|
||||
{
|
||||
text: mom === null
|
||||
? ('首期无上期,暂无环比。')
|
||||
: `环比上期 ${mom > 0 ? '+' : ''}${fmt(mom)}${valU},近 4 期呈${improving ? '改善' : weakening ? '走弱' : '平稳'}走势。`,
|
||||
tone: improving ? tk.success : weakening ? tk.danger : tk.textSub,
|
||||
},
|
||||
worstKid
|
||||
? {
|
||||
text: `下级「${nameOf(worstKid.code)}」偏差 ${fmtSigned(gapAt(worstKid, period))}${kidGapU(worstKid)},是回升支点。`,
|
||||
tone: tk.warning,
|
||||
}
|
||||
: topCause
|
||||
? {
|
||||
text: `最大驱动源:${nameOf(topCause.from_code)}(强度 ${fmt(topCause.strength, 2)}),稳住传播路径即可。`,
|
||||
tone: tk.info,
|
||||
}
|
||||
: {
|
||||
text: '已是末级驱动因子,无更深层拆解,关注口径稳定性。',
|
||||
tone: tk.textSub,
|
||||
},
|
||||
];
|
||||
|
||||
const secTitle = (label: string, n?: number) => (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
|
||||
<span style={{ width: 3, height: 12, borderRadius: 2, background: tk.accent, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 11.5, fontWeight: 800, color: tk.text, letterSpacing: '0.03em', flexShrink: 0 }}>{label}</span>
|
||||
{n !== undefined && <span style={{ fontSize: 10.5, color: tk.textMuted, fontVariantNumeric: 'tabular-nums' }}>{n}</span>}
|
||||
<span style={{ flex: 1, height: 1, background: tk.border }} />
|
||||
</div>
|
||||
);
|
||||
|
||||
const relColor = (r: string) => (r === 'drive' ? tk.success : r === 'conflict' ? tk.danger : tk.info);
|
||||
|
||||
/* 因果行:方向 + 关系徽章 + 实体 + 游标值 + 强度条 */
|
||||
const linkRow = (l: MetricLink, out: boolean) => {
|
||||
const other = out ? l.to_code : l.from_code;
|
||||
const on = byCode.get(other);
|
||||
const rc = relColor(l.relation);
|
||||
const oc = on ? alertColor(levelAt(on, period), tk) : tk.textMuted;
|
||||
return (
|
||||
<button key={`${l.id}-${out}`} onClick={() => onSelect(other)} className="ghost-btn" style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, width: '100%', textAlign: 'left', cursor: 'pointer',
|
||||
padding: '5px 7px', borderRadius: 8, background: tk.cardBg, border: `1px solid ${tk.border}`,
|
||||
}}>
|
||||
{out ? <ArrowRight size={11} color={rc} style={{ flexShrink: 0 }} /> : <ArrowLeft size={11} color={rc} style={{ flexShrink: 0 }} />}
|
||||
<span style={{ fontSize: 9.5, color: rc, background: `${rc}1a`, border: `1px solid ${rc}33`, borderRadius: 5, padding: '0 4px', flexShrink: 0 }}>{t.net[l.relation]}</span>
|
||||
<span style={{ fontSize: 12, color: tk.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{nameOf(other)}</span>
|
||||
{on && <span style={{ fontSize: 11, color: oc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>{fmt(valueAt(on, period))}</span>}
|
||||
<span style={{ width: 30, height: 3.5, borderRadius: 99, background: tk.border, overflow: 'hidden', flexShrink: 0 }}>
|
||||
<span style={{ display: 'block', width: `${Math.min(100, (Math.abs(l.strength) / maxStrength) * 100)}%`, height: '100%', background: rc }} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
/* 下级回应条:子指标在该期的达成率,一眼看出谁在拖、谁在扛 */
|
||||
const kidRow = (k: MetricNode) => {
|
||||
const ka = achieveAt(k, period);
|
||||
const kc = alertColor(levelAt(k, period), tk);
|
||||
const kg = gapAt(k, period);
|
||||
return (
|
||||
<button key={k.code} onClick={() => onSelect(k.code)} className="ghost-btn" style={{
|
||||
display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer', padding: '5px 7px',
|
||||
borderRadius: 8, background: tk.cardBg, border: `1px solid ${tk.border}`,
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ width: 6, height: 6, borderRadius: '50%', background: kc, boxShadow: `0 0 5px ${kc}`, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 12, color: tk.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{k.name_zh}</span>
|
||||
<span style={{ fontSize: 11, fontWeight: 800, color: kc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>{fmt(ka, 0)}%</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
|
||||
<span style={{ flex: 1, height: 3, borderRadius: 99, background: tk.border, overflow: 'hidden' }}>
|
||||
<span style={{ display: 'block', width: `${Math.min(100, ka)}%`, height: '100%', background: kc, transition: 'width 0.4s ease' }} />
|
||||
</span>
|
||||
<span style={{ fontSize: 10, color: kg >= 0 ? tk.success : tk.danger, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>
|
||||
{fmtSigned(kg)}{kidGapU(k)}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
/* 12 期趋势柱:游标柱高亮发光,目标线横贯 */
|
||||
const trendBars = () => {
|
||||
const mn = Math.min(...series, node.target);
|
||||
const mx = Math.max(...series, node.target);
|
||||
const span = mx - mn || 1;
|
||||
const H = 56;
|
||||
const ty = H - 4 - ((node.target - mn) / span) * (H - 10);
|
||||
return (
|
||||
<div style={{ position: 'relative', height: H, display: 'flex', alignItems: 'flex-end', gap: 3 }}>
|
||||
{series.map((v, i) => {
|
||||
const h = 6 + ((v - mn) / span) * (H - 12);
|
||||
const on = i === period;
|
||||
const col = alertColor(levelAt(node, i), tk);
|
||||
return (
|
||||
<div key={i} style={{
|
||||
flex: 1, height: h, borderRadius: 2.5, background: col,
|
||||
opacity: on ? 1 : i < period ? 0.4 : 0.16,
|
||||
boxShadow: on ? `0 0 9px ${col}99` : 'none',
|
||||
transition: 'opacity 0.25s ease, box-shadow 0.25s ease',
|
||||
}} />
|
||||
);
|
||||
})}
|
||||
<div style={{
|
||||
position: 'absolute', left: 0, right: 0, top: ty, borderTop: `1px dashed ${tk.textMuted}`, opacity: 0.65,
|
||||
}} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
const guards = staff.filter(s => s.bound_metric === node.code);
|
||||
|
||||
return (
|
||||
<div className="space-scroll" style={{
|
||||
display: 'flex', flexDirection: 'column', gap: 12, flex: '1 1 auto', minWidth: 0, height: '100%', overflowY: 'auto',
|
||||
padding: '12px 13px', borderRadius: 12, background: tk.panelBgAlt,
|
||||
border: `1px solid ${tk.borderAccent}`, backdropFilter: 'blur(9px) saturate(1.15)',
|
||||
boxShadow: deep ? '0 10px 30px rgba(0,0,0,0.35)' : 'none',
|
||||
}}>
|
||||
{/* 实体抬头 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
|
||||
<span className={lv === 'red' ? 'net-breathe' : undefined} style={{
|
||||
display: 'block', width: 10, height: 10, borderRadius: '50%', flexShrink: 0, background: c,
|
||||
boxShadow: `0 0 9px ${c}`,
|
||||
}} />
|
||||
<span style={{ fontSize: 15, fontWeight: 800, color: tk.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{name}</span>
|
||||
<span style={{ fontSize: 10, color: tk.textMuted, border: `1px solid ${tk.border}`, borderRadius: 5, padding: '0 4px', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>{node.code}</span>
|
||||
{onClose && (
|
||||
<button onClick={onClose} className="ghost-btn" style={{
|
||||
display: 'grid', placeItems: 'center', width: 20, height: 20, borderRadius: 5, cursor: 'pointer', flexShrink: 0,
|
||||
color: tk.textMuted, border: `1px solid ${tk.border}`, background: 'transparent',
|
||||
}}><X size={12} /></button>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', fontSize: 10.5, color: tk.textMuted, marginTop: -8 }}>
|
||||
<span>L{node.level}</span><span>·</span><span>{node.owner}</span><span>·</span>
|
||||
<span>{node.frequency}</span><span>·</span>
|
||||
<span>{node.parent_code && node.parent_code !== 'OV' ? `上级 ${nameOf(node.parent_code)}` : 'OV'}</span>
|
||||
</div>
|
||||
|
||||
{/* 看板现已贯通到底(整屏高),纵向叙事优先填满高度;只有超宽屏才自动分双列 */}
|
||||
<div style={{
|
||||
display: 'grid', gap: 12, alignItems: 'start',
|
||||
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
|
||||
}}>
|
||||
|
||||
{/* 游标读数 */}
|
||||
<div>
|
||||
{secTitle(`${t.net.causalCursor} · ${periodLabel(period)}`)}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
|
||||
{([
|
||||
[t.detail.current, `${fmt(val)}${valU}`, tk.text],
|
||||
[t.detail.targetVal, `${fmt(node.target)}${valU}`, tk.textSub],
|
||||
[t.detail.gap, `${fmtSigned(gap)}${gapU}`, gap >= 0 ? tk.success : tk.danger],
|
||||
[t.detail.achieve, `${fmt(ach, 0)}%`, execColor(ach, tk)],
|
||||
] as const).map(([lab, v, col]) => (
|
||||
<div key={lab} style={{ background: tk.cardBg, border: `1px solid ${tk.border}`, borderRadius: 8, padding: '5px 8px' }}>
|
||||
<div style={{ fontSize: 10, color: tk.textMuted }}>{lab}</div>
|
||||
<div style={{ fontSize: 15.5, fontWeight: 800, color: col, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', lineHeight: 1.3 }}>{v}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 趋势柱 */}
|
||||
<div>
|
||||
{secTitle(t.net.causalTrend)}
|
||||
{trendBars()}
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 9.5, color: tk.textMuted, marginTop: 3 }}>
|
||||
<span>2025-01</span><span>虚线=目标</span><span>2025-12</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 前因 */}
|
||||
<div>
|
||||
{secTitle(t.net.causalIn, incoming.length)}
|
||||
{incoming.length
|
||||
? <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{incoming.map(l => linkRow(l, false))}</div>
|
||||
: <div style={{ fontSize: 11.5, color: tk.textMuted }}>{isRoot ? t.net.noConn : t.net.causalNoIn}</div>}
|
||||
</div>
|
||||
|
||||
{/* 后果 */}
|
||||
<div>
|
||||
{secTitle(isRoot ? t.net.topChains : t.net.causalOut, outgoing.length)}
|
||||
{outgoing.length
|
||||
? <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{outgoing.map(l => linkRow(l, true))}</div>
|
||||
: <div style={{ fontSize: 11.5, color: tk.textMuted }}>{t.net.causalNoOut}</div>}
|
||||
</div>
|
||||
|
||||
{/* 下级回应 */}
|
||||
<div>
|
||||
{secTitle(t.net.causalKids, kids.length)}
|
||||
{kids.length
|
||||
? <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>{[...kidGaps].map(x => kidRow(x.k))}</div>
|
||||
: <div style={{ fontSize: 11.5, color: tk.textMuted }}>{t.net.causalNoKid}</div>}
|
||||
</div>
|
||||
|
||||
{/* 同层对标(仅末级:没有下级可拆时,用兄弟指标补齐这块高度) */}
|
||||
{!kids.length && sibs.length > 0 && (
|
||||
<div>
|
||||
{secTitle(t.net.causalSibs, sibs.length)}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
{[...sibs].sort((a, b) => gapAt(a, period) - gapAt(b, period)).slice(0, 6).map(k => kidRow(k))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI 研判:整行占位,长句不拆栏 */}
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
{secTitle(t.net.causalAi)}
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
|
||||
{verdicts.map(v => (
|
||||
<div key={v.text} style={{
|
||||
display: 'flex', gap: 6, fontSize: 11.5, lineHeight: 1.65, color: tk.textSub,
|
||||
background: tk.cardBg, border: `1px solid ${tk.border}`, borderLeft: `2px solid ${v.tone}`,
|
||||
borderRadius: 8, padding: '5px 8px',
|
||||
}}>{v.text}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 汇报口径 */}
|
||||
<div style={{ gridColumn: '1 / -1' }}>
|
||||
{secTitle(t.net.causalReport)}
|
||||
<div style={{ background: tk.cardBg, border: `1px solid ${tk.border}`, borderRadius: 8, padding: '6px 8px' }}>
|
||||
<div style={{ fontSize: 10, color: tk.textMuted }}>{t.common.formula}</div>
|
||||
<div style={{ fontSize: 11.5, color: tk.textSub, marginBottom: 5 }}>{node.formula}</div>
|
||||
<div style={{ fontSize: 10, color: tk.textMuted }}>{t.detail.desc}</div>
|
||||
<div style={{ fontSize: 11.5, color: tk.textSub, lineHeight: 1.6 }}>{(node.desc_zh) || t.detail.noDesc}</div>
|
||||
</div>
|
||||
<div style={{ marginTop: 5, display: 'flex', flexDirection: 'column', gap: 4 }}>
|
||||
{guards.length ? guards.map(s => (
|
||||
<div key={s.code} style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, padding: '4px 8px', borderRadius: 8,
|
||||
background: tk.cardBg, border: `1px solid ${tk.border}`, color: tk.textSub,
|
||||
}}>
|
||||
<span style={{ width: 5, height: 5, borderRadius: '50%', flexShrink: 0, background: s.status === 'alert' ? tk.danger : s.status === 'working' ? tk.success : tk.textMuted }} />
|
||||
<span style={{ color: tk.text, fontWeight: 700, flexShrink: 0 }}>{s.name_zh}</span>
|
||||
<span style={{ minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{s.cur_zh}</span>
|
||||
</div>
|
||||
)) : <div style={{ fontSize: 11.5, color: tk.textMuted }}>{t.net.causalNoStaff}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useMemo } from 'react';
|
||||
import type { CSSProperties } from 'react';
|
||||
|
||||
/**
|
||||
* 知识图谱氛围层(M5 深空叙事):星云漂移 + 闪烁星点 + 雷达扫描 + 中心辉光 + 边缘暗角。
|
||||
* 全部用 CSS 动画驱动(无 JS 帧循环,不抢占主线程),纯装饰层 pointerEvents: none。
|
||||
* deep 模式(全景舞台,强制深空)拉满;面板模式收敛为极淡星云底。
|
||||
*/
|
||||
|
||||
interface Props {
|
||||
w: number;
|
||||
h: number;
|
||||
/** 深空模式:舞台态强制深色底 */
|
||||
deep: boolean;
|
||||
/** 雷达扫描(仅舞台态开) */
|
||||
radar?: boolean;
|
||||
}
|
||||
|
||||
/** 与数据无关的固定分布:每次挂载只算一次 */
|
||||
function mulberry(seed: number) {
|
||||
let t = seed >>> 0;
|
||||
return () => {
|
||||
t += 0x6d2b79f5;
|
||||
let r = Math.imul(t ^ (t >>> 15), 1 | t);
|
||||
r ^= r + Math.imul(r ^ (r >>> 7), 61 | r);
|
||||
return ((r ^ (r >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
export default function DeepSpaceBackdrop({ w, h, deep, radar = false }: Props) {
|
||||
const stars = useMemo(() => {
|
||||
const rnd = mulberry(20250911);
|
||||
return Array.from({ length: 46 }, () => ({
|
||||
left: `${(rnd() * 100).toFixed(2)}%`,
|
||||
top: `${(rnd() * 100).toFixed(2)}%`,
|
||||
size: rnd() < 0.82 ? 1.2 : 2,
|
||||
o: 0.18 + rnd() * 0.5,
|
||||
d: `${(2.6 + rnd() * 4.2).toFixed(1)}s`,
|
||||
delay: `${(rnd() * 5).toFixed(1)}s`,
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const layer = (style: CSSProperties): CSSProperties => ({
|
||||
position: 'absolute', inset: 0, pointerEvents: 'none', ...style,
|
||||
});
|
||||
|
||||
return (
|
||||
<div style={layer({ overflow: 'hidden' })}>
|
||||
{/* 星云光斑:双色呼吸漂移 */}
|
||||
<div
|
||||
className="net-nebula"
|
||||
style={layer({
|
||||
background: deep
|
||||
? 'radial-gradient(52% 60% at 26% 22%, rgba(99,102,241,0.17), transparent 68%), radial-gradient(46% 54% at 78% 76%, rgba(56,189,248,0.11), transparent 66%)'
|
||||
: 'radial-gradient(52% 60% at 26% 22%, rgba(99,102,241,0.05), transparent 68%)',
|
||||
['--nb-d' as string]: '52s',
|
||||
})}
|
||||
/>
|
||||
<div
|
||||
className="net-nebula"
|
||||
style={layer({
|
||||
background: deep
|
||||
? 'radial-gradient(38% 44% at 64% 30%, rgba(129,140,248,0.10), transparent 64%)'
|
||||
: 'none',
|
||||
['--nb-d' as string]: '38s',
|
||||
})}
|
||||
/>
|
||||
|
||||
{/* 中心恒星辉光 + 雷达扫描(两者只在深空模式出现) */}
|
||||
{deep && (
|
||||
<>
|
||||
<div style={layer({
|
||||
background: 'radial-gradient(circle at 50% 50%, rgba(99,102,241,0.16), rgba(56,189,248,0.05) 30%, transparent 46%)',
|
||||
})} />
|
||||
{radar && (
|
||||
<div style={layer({
|
||||
display: 'grid', placeItems: 'center',
|
||||
})}>
|
||||
<div style={{
|
||||
width: Math.max(w, h) * 1.15, height: Math.max(w, h) * 1.15,
|
||||
borderRadius: '50%', mixBlendMode: 'screen',
|
||||
background: 'conic-gradient(from 0deg, transparent 0deg 292deg, rgba(129,140,248,0.05) 322deg, rgba(129,140,248,0.20) 355deg, transparent 360deg)',
|
||||
animation: 'net-radar 56s linear infinite',
|
||||
opacity: 0.75,
|
||||
}} />
|
||||
</div>
|
||||
)}
|
||||
{/* 星点闪烁 */}
|
||||
{stars.map((s, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className="net-twinkle"
|
||||
style={{
|
||||
position: 'absolute', left: s.left, top: s.top,
|
||||
width: s.size, height: s.size, borderRadius: '50%',
|
||||
background: i % 7 === 0 ? '#93c5fd' : '#dbeafe',
|
||||
['--tw-o' as string]: s.o,
|
||||
['--tw-d' as string]: s.d,
|
||||
['--tw-delay' as string]: s.delay,
|
||||
animationDelay: s.delay,
|
||||
opacity: s.o,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 边缘暗角:收束视线,制造纵深 */}
|
||||
{deep && (
|
||||
<div style={layer({
|
||||
background: 'radial-gradient(ellipse 78% 78% at 50% 50%, transparent 52%, rgba(2,6,18,0.55) 100%)',
|
||||
})} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { ChevronLeft, ChevronRight, Play, Radio, Square } from 'lucide-react';
|
||||
import type { ThemeTokens } from '../../context/ThemeContext';
|
||||
import type { I18n } from '../../i18n/locales';
|
||||
import type { MetricNode } from '../../data/sqlite';
|
||||
import { achieveAt, PERIOD_MONTHS, periodLabel, CURRENT_PERIOD, PERIOD_COUNT } from '../../lib/time';
|
||||
import { execColor } from '../../lib/metric';
|
||||
|
||||
/**
|
||||
* BI 式时间轴滑块:拖动 / 点击刻度 / 自动回放,全图按游标时点重取值与状态。
|
||||
* 柱体高度与颜色取自整体健康度在各期的达成率,时间进度感与数据同轴呈现。
|
||||
*/
|
||||
interface Props {
|
||||
period: number;
|
||||
onPeriod: (p: number) => void;
|
||||
/** 整体健康度节点:驱动 12 根背景柱 */
|
||||
ov?: MetricNode;
|
||||
tokens: ThemeTokens;
|
||||
t: I18n;
|
||||
}
|
||||
|
||||
export default function MetricTimeline({ period, onPeriod, ov, tokens, t }: Props) {
|
||||
const [playing, setPlaying] = useState(false);
|
||||
const trackRef = useRef<HTMLDivElement>(null);
|
||||
const draggingRef = useRef(false);
|
||||
const periodRef = useRef(period); periodRef.current = period;
|
||||
const onPeriodRef = useRef(onPeriod); onPeriodRef.current = onPeriod;
|
||||
|
||||
useEffect(() => {
|
||||
if (!playing) return;
|
||||
const id = window.setInterval(() => {
|
||||
onPeriodRef.current((periodRef.current + 1) % PERIOD_COUNT);
|
||||
}, 850);
|
||||
return () => window.clearInterval(id);
|
||||
}, [playing]);
|
||||
|
||||
const posToPeriod = (clientX: number) => {
|
||||
const el = trackRef.current;
|
||||
if (!el) return periodRef.current;
|
||||
const r = el.getBoundingClientRect();
|
||||
const f = (clientX - r.left) / Math.max(1, r.width);
|
||||
return Math.max(0, Math.min(PERIOD_COUNT - 1, Math.floor(f * PERIOD_COUNT)));
|
||||
};
|
||||
|
||||
const months = PERIOD_MONTHS.map(m => `${Number(m.slice(5, 7))}月`);
|
||||
const cur = periodLabel(period);
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 12,
|
||||
margin: '0 6px 6px', padding: '9px 14px', borderRadius: 12,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
|
||||
backdropFilter: 'blur(8px)', userSelect: 'none',
|
||||
}}>
|
||||
{/* 回放控制 */}
|
||||
<button
|
||||
onClick={() => setPlaying(p => !p)}
|
||||
className="ghost-btn"
|
||||
title={playing ? t.net.tlPause : t.net.tlPlay}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0, cursor: 'pointer',
|
||||
padding: '4px 10px', borderRadius: 8, fontSize: 12, fontWeight: 700,
|
||||
color: playing ? tokens.onAccent : tokens.accent,
|
||||
background: playing ? tokens.accent : tokens.accentBg,
|
||||
border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
{playing ? <Square size={11} /> : <Play size={11} />}
|
||||
{playing ? t.net.tlPause : t.net.tlPlay}
|
||||
</button>
|
||||
|
||||
{/* 轨道:12 根健康度柱 + 游标 */}
|
||||
<div
|
||||
ref={trackRef}
|
||||
style={{ position: 'relative', flex: 1, height: 42, cursor: 'ew-resize', touchAction: 'none', minWidth: 0 }}
|
||||
onPointerDown={e => {
|
||||
draggingRef.current = true;
|
||||
setPlaying(false);
|
||||
try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* 合成指针下降级为无捕获拖动 */ }
|
||||
onPeriod(posToPeriod(e.clientX));
|
||||
}}
|
||||
onPointerMove={e => { if (draggingRef.current) onPeriod(posToPeriod(e.clientX)); }}
|
||||
onPointerUp={() => { draggingRef.current = false; }}
|
||||
onPointerCancel={() => { draggingRef.current = false; }}
|
||||
>
|
||||
{/* 柱阵列 */}
|
||||
<div style={{ position: 'absolute', inset: '0 0 12px', display: 'flex', gap: 3 }}>
|
||||
{Array.from({ length: PERIOD_COUNT }, (_, i) => {
|
||||
const rate = ov ? achieveAt(ov, i) : 100;
|
||||
const passed = i <= period;
|
||||
const h = 12 + Math.min(1.4, Math.max(0.25, rate / 100)) * 18;
|
||||
const col = execColor(rate, tokens);
|
||||
return (
|
||||
<div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'stretch' }}>
|
||||
<div style={{
|
||||
height: h, borderRadius: 3,
|
||||
background: col,
|
||||
opacity: i === period ? 0.95 : passed ? 0.42 : 0.16,
|
||||
boxShadow: i === period ? `0 0 10px ${col}88` : 'none',
|
||||
transition: 'opacity 0.25s ease, height 0.4s ease, box-shadow 0.25s ease',
|
||||
}} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
{/* 游标发光线 */}
|
||||
<div style={{
|
||||
position: 'absolute', top: 0, bottom: 10, width: 2, borderRadius: 2,
|
||||
left: `calc(${((period + 0.5) / PERIOD_COUNT) * 100}% - 1px)`,
|
||||
background: `linear-gradient(180deg, ${tokens.accent}, ${tokens.info})`,
|
||||
boxShadow: `0 0 10px ${tokens.accentGlow}`,
|
||||
transition: 'left 0.28s cubic-bezier(0.22,1,0.36,1)', pointerEvents: 'none',
|
||||
}}>
|
||||
<span style={{
|
||||
position: 'absolute', top: -3, left: '50%', transform: 'translateX(-50%)',
|
||||
width: 9, height: 9, borderRadius: '50%', background: tokens.accent,
|
||||
boxShadow: `0 0 8px ${tokens.accentGlow}`, border: `2px solid ${tokens.panelBgAlt}`,
|
||||
}} />
|
||||
</div>
|
||||
{/* 月刻度 */}
|
||||
<div style={{ position: 'absolute', left: 0, right: 0, bottom: -2, display: 'flex' }}>
|
||||
{months.map((m, i) => (
|
||||
<span key={`${m}-${i}`} title={PERIOD_MONTHS[i]} style={{
|
||||
flex: 1, textAlign: 'center', fontSize: 9.5,
|
||||
fontVariantNumeric: 'tabular-nums',
|
||||
color: i === period ? tokens.accent : tokens.textMuted,
|
||||
opacity: i === period ? 1 : 0.55, fontWeight: i === period ? 800 : 400,
|
||||
}}>{m}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 当前期读数 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0 }}>
|
||||
<button
|
||||
onClick={() => onPeriod(Math.max(0, period - 1))}
|
||||
className="ghost-btn"
|
||||
style={{ display: 'grid', placeItems: 'center', width: 22, height: 22, borderRadius: 6, cursor: 'pointer', color: tokens.textSub, border: `1px solid ${tokens.border}`, background: 'transparent' }}
|
||||
><ChevronLeft size={13} /></button>
|
||||
<span style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, fontSize: 13.5, fontWeight: 800,
|
||||
color: tokens.accent, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace',
|
||||
minWidth: 86, justifyContent: 'center',
|
||||
}}>
|
||||
<Radio size={11} />{cur}
|
||||
</span>
|
||||
<button
|
||||
onClick={() => onPeriod(Math.min(PERIOD_COUNT - 1, period + 1))}
|
||||
className="ghost-btn"
|
||||
style={{ display: 'grid', placeItems: 'center', width: 22, height: 22, borderRadius: 6, cursor: 'pointer', color: tokens.textSub, border: `1px solid ${tokens.border}`, background: 'transparent' }}
|
||||
><ChevronRight size={13} /></button>
|
||||
<button
|
||||
onClick={() => { setPlaying(false); onPeriod(CURRENT_PERIOD); }}
|
||||
className="ghost-btn"
|
||||
disabled={period === CURRENT_PERIOD}
|
||||
style={{
|
||||
padding: '3px 10px', borderRadius: 8, fontSize: 11.5, fontWeight: 700, cursor: period === CURRENT_PERIOD ? 'default' : 'pointer',
|
||||
color: period === CURRENT_PERIOD ? tokens.textMuted : tokens.accent,
|
||||
border: `1px solid ${period === CURRENT_PERIOD ? tokens.border : tokens.borderAccent}`,
|
||||
background: period === CURRENT_PERIOD ? 'transparent' : tokens.accentBg,
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>{t.net.tlBack}</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { ThemeTokens } from '../../context/ThemeContext';
|
||||
|
||||
/** 舞台态强制深空(Bloomberg 黑屏模式):图谱与看板共用同一套语义色,不随用户主题漂移 */
|
||||
export const DEEP: Partial<ThemeTokens> = {
|
||||
text: '#e8eefc', textSub: '#a9b8d0', textMuted: 'rgba(154,172,199,0.82)',
|
||||
accent: '#818cf8', accentGlow: 'rgba(129,140,248,0.75)', accentBg: 'rgba(129,140,248,0.10)',
|
||||
border: 'rgba(129,140,248,0.16)', borderSub: 'rgba(129,140,248,0.08)', borderAccent: 'rgba(129,140,248,0.34)',
|
||||
panelBg: 'rgba(8,13,28,0.92)', panelBgAlt: 'rgba(10,16,32,0.72)', cardBg: 'rgba(20,29,54,0.66)',
|
||||
success: '#34d399', warning: '#fbbf24', danger: '#f87171', info: '#38bdf8',
|
||||
};
|
||||
|
||||
export const DEEP_BG = 'radial-gradient(120% 95% at 50% 40%, #0a1022 0%, #060a16 52%, #03060e 100%)';
|
||||
|
||||
/** 达成率弧:从 12 点顺时针的 donut 弧(节点形态即数据:环弧长度=达成率) */
|
||||
export function arcPath(cx: number, cy: number, r: number, frac: number): string {
|
||||
const f = Math.min(0.9999, Math.max(0.0001, frac));
|
||||
const a0 = -Math.PI / 2, a1 = a0 + f * Math.PI * 2;
|
||||
const x0 = cx + r * Math.cos(a0), y0 = cy + r * Math.sin(a0);
|
||||
const x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
|
||||
return `M ${x0.toFixed(2)},${y0.toFixed(2)} A ${r},${r} 0 ${f > 0.5 ? 1 : 0} 1 ${x1.toFixed(2)},${y1.toFixed(2)}`;
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
import { useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import { type Tone } from '../../data/ontology';
|
||||
|
||||
/**
|
||||
* 业务本体图谱:8 个对象节点 + 10 条关系边。
|
||||
* 力导向布局移植自智能体开发平台的本体管理页(纯手写 SVG,不引 d3):
|
||||
* 环形初始化 → 斥力 6000/d² → 弹簧 (d−160)×0.008 → 向心 0.004 → 阻尼 0.88,跑满 120 帧收敛。
|
||||
* 配色改用本应用主题 token,深浅两套主题都保证边线与文字有足够对比度。
|
||||
*/
|
||||
|
||||
export interface GNode { id: string; label: string; count: number; color: string }
|
||||
export interface GEdge { id: string; source: string; target: string; label: string }
|
||||
|
||||
interface SimNode extends GNode { x: number; y: number; vx: number; vy: number; deg: number }
|
||||
|
||||
export interface ChainOverlay {
|
||||
nodeIds: Set<string>;
|
||||
edgeIds: Set<string>;
|
||||
tones: Record<string, Tone>;
|
||||
metrics: Record<string, Record<string, string>>;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
nodes: GNode[];
|
||||
edges: GEdge[];
|
||||
selectedNodeId: string | null;
|
||||
selectedEdgeId: string | null;
|
||||
onNodeClick?: (id: string) => void;
|
||||
onEdgeClick?: (id: string) => void;
|
||||
chain?: ChainOverlay | null;
|
||||
}
|
||||
|
||||
/** 节点内只放清洗后的短名,全称留给节点下方那行 */
|
||||
const shortName = (s: string) => s.replace(/([^)]*)/g, '').trim();
|
||||
|
||||
export default function OntologyGraph({ nodes: rawNodes, edges, selectedNodeId, selectedEdgeId, onNodeClick, onEdgeClick, chain }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const svgRef = useRef<SVGSVGElement>(null);
|
||||
const [nodes, setNodes] = useState<SimNode[]>([]);
|
||||
const [dims, setDims] = useState({ w: 720, h: 420 });
|
||||
const [hovered, setHovered] = useState<string | null>(null);
|
||||
const [tooltipPos, setTooltipPos] = useState({ x: 0, y: 0 });
|
||||
const idPrefix = useId().replace(/:/g, '');
|
||||
|
||||
const inChainNode = (n: SimNode) => !!chain?.nodeIds.has(n.id);
|
||||
const inChainEdge = (e: GEdge) => !!chain?.edgeIds.has(e.id);
|
||||
const chainTone = (n: SimNode) => chain?.tones[n.id] ?? 'info';
|
||||
const toneColor = (t: Tone) => {
|
||||
switch (t) {
|
||||
case 'success': return tokens.success;
|
||||
case 'warning': return tokens.warning;
|
||||
case 'danger': return tokens.danger;
|
||||
case 'info': return tokens.info;
|
||||
}
|
||||
};
|
||||
|
||||
const handleSvgMouseMove = (e: React.MouseEvent<SVGSVGElement>) => {
|
||||
const rect = e.currentTarget.getBoundingClientRect();
|
||||
const scaleX = dims.w / rect.width;
|
||||
const scaleY = dims.h / rect.height;
|
||||
setTooltipPos({
|
||||
x: (e.clientX - rect.left) * scaleX,
|
||||
y: (e.clientY - rect.top) * scaleY,
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const box = svgRef.current?.parentElement;
|
||||
if (!box) return;
|
||||
const measure = () => {
|
||||
const r = box.getBoundingClientRect();
|
||||
if (r.width > 0 && r.height > 0) setDims({ w: r.width, h: r.height });
|
||||
};
|
||||
/* ResizeObserver 的回调靠 rAF 投递:页面切到后台时会整段挂起,舞台刚进场那几帧
|
||||
flex 比例也还没定。这里同步测一次 + 补两次延时测 + 盯 window resize,
|
||||
保证布局坐标系最终等于真实容器,不会因为 RO 没投递而按默认尺寸画。 */
|
||||
measure();
|
||||
const ro = new ResizeObserver(([e]) => setDims({ w: e.contentRect.width, h: e.contentRect.height }));
|
||||
ro.observe(box);
|
||||
const t1 = setTimeout(measure, 120);
|
||||
const t2 = setTimeout(measure, 420);
|
||||
window.addEventListener('resize', measure);
|
||||
return () => {
|
||||
ro.disconnect();
|
||||
clearTimeout(t1); clearTimeout(t2);
|
||||
window.removeEventListener('resize', measure);
|
||||
};
|
||||
}, []);
|
||||
|
||||
/* ── 布局仿真:数据或尺寸变化即重跑(数据只有 8 节点,成本可忽略) ── */
|
||||
useEffect(() => {
|
||||
if (rawNodes.length === 0) return;
|
||||
const cx = dims.w / 2, cy = dims.h / 2;
|
||||
const deg: Record<string, number> = {};
|
||||
rawNodes.forEach(n => { deg[n.id] = 0; });
|
||||
edges.forEach(e => { deg[e.source] = (deg[e.source] || 0) + 1; deg[e.target] = (deg[e.target] || 0) + 1; });
|
||||
/* 舞台通常是横宽竖窄的:初始化用椭圆环而不是正圆,避免 8 个节点全挤在中间一条 */
|
||||
const rx = Math.max(150, dims.w * 0.34), ry = Math.max(96, dims.h * 0.34);
|
||||
setNodes(rawNodes.map((n, i) => {
|
||||
const a = (2 * Math.PI * i) / rawNodes.length - Math.PI / 2;
|
||||
return { ...n, deg: deg[n.id] || 0, x: cx + rx * Math.cos(a), y: cy + ry * Math.sin(a), vx: 0, vy: 0 };
|
||||
}));
|
||||
|
||||
// 斥力与弹簧原长按容器尺寸给:常数写死会让宽舞台只用到中间一小块
|
||||
const repel = 9000;
|
||||
const rest = Math.max(160, Math.min(260, Math.min(dims.w, dims.h) * 0.55));
|
||||
let frame = 0;
|
||||
const timer = setInterval(() => {
|
||||
if (frame++ > 120) { clearInterval(timer); return; }
|
||||
setNodes(prev => {
|
||||
const next = prev.map(n => ({ ...n }));
|
||||
for (let i = 0; i < next.length; i++) for (let j = i + 1; j < next.length; j++) {
|
||||
const dx = next[j].x - next[i].x, dy = next[j].y - next[i].y;
|
||||
const d = Math.max(Math.hypot(dx, dy), 1);
|
||||
const f = repel / (d * d);
|
||||
next[i].vx -= (dx / d) * f; next[i].vy -= (dy / d) * f;
|
||||
next[j].vx += (dx / d) * f; next[j].vy += (dy / d) * f;
|
||||
}
|
||||
const byId = new Map(next.map(n => [n.id, n]));
|
||||
for (const e of edges) {
|
||||
const s = byId.get(e.source), t = byId.get(e.target);
|
||||
if (!s || !t) continue;
|
||||
const dx = t.x - s.x, dy = t.y - s.y;
|
||||
const d = Math.max(Math.hypot(dx, dy), 1);
|
||||
const f = (d - rest) * 0.008;
|
||||
s.vx += (dx / d) * f; s.vy += (dy / d) * f;
|
||||
t.vx -= (dx / d) * f; t.vy -= (dy / d) * f;
|
||||
}
|
||||
for (const n of next) {
|
||||
n.vx += (cx - n.x) * 0.004; n.vy += (cy - n.y) * 0.004;
|
||||
n.vx *= 0.88; n.vy *= 0.88; n.x += n.vx; n.y += n.vy;
|
||||
n.x = Math.max(74, Math.min(dims.w - 74, n.x));
|
||||
n.y = Math.max(52, Math.min(dims.h - 62, n.y));
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, 16);
|
||||
return () => clearInterval(timer);
|
||||
}, [rawNodes, edges, dims]);
|
||||
|
||||
const maxDeg = useMemo(() => Math.max(...nodes.map(n => n.deg), 1), [nodes]);
|
||||
const byId = useMemo(() => new Map(nodes.map(n => [n.id, n] as const)), [nodes]);
|
||||
/** 度数决定半径:枢纽对象(销售订单)明显大于叶子对象(仓库) */
|
||||
const rOf = (deg: number) => 24 + (deg / maxDeg) * 12;
|
||||
|
||||
const active = hovered ?? selectedNodeId;
|
||||
const isNeighbor = (id: string) =>
|
||||
!!active && edges.some(e => (e.source === active && e.target === id) || (e.target === active && e.source === id));
|
||||
|
||||
return (
|
||||
<svg ref={svgRef} width="100%" height="100%" viewBox={`0 0 ${dims.w} ${dims.h}`}
|
||||
preserveAspectRatio="xMidYMid meet" style={{ display: 'block', userSelect: 'none' }}
|
||||
onMouseMove={handleSvgMouseMove}>
|
||||
<defs>
|
||||
<marker id={`${idPrefix}-ont-arrow`} markerWidth="9" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 9 3.5, 0 7" fill={tokens.textMuted} />
|
||||
</marker>
|
||||
<marker id={`${idPrefix}-ont-arrow-hl`} markerWidth="9" markerHeight="7" refX="9" refY="3.5" orient="auto">
|
||||
<polygon points="0 0, 9 3.5, 0 7" fill={tokens.accent} />
|
||||
</marker>
|
||||
<pattern id={`${idPrefix}-ont-dots`} width="26" height="26" patternUnits="userSpaceOnUse">
|
||||
<circle cx="13" cy="13" r="0.9" fill={tokens.svgStroke} opacity="0.5" />
|
||||
</pattern>
|
||||
<filter id={`${idPrefix}-ont-soft`} x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feDropShadow dx="0" dy="1.5" stdDeviation="3.5" floodColor={tokens.accentGlow} floodOpacity="0.25" />
|
||||
</filter>
|
||||
<filter id={`${idPrefix}-ont-strong`} x="-50%" y="-50%" width="200%" height="200%">
|
||||
<feDropShadow dx="0" dy="0" stdDeviation="7" floodColor={tokens.accentGlow} floodOpacity="0.55" />
|
||||
</filter>
|
||||
</defs>
|
||||
|
||||
<rect width="100%" height="100%" fill={`url(#${idPrefix}-ont-dots)`} />
|
||||
|
||||
{/* ── 关系边:透明粗线负责命中,细线负责显示 ── */}
|
||||
{edges.map(e => {
|
||||
const s = byId.get(e.source), t = byId.get(e.target);
|
||||
if (!s || !t) return null;
|
||||
const inChain = inChainEdge(e);
|
||||
const sel = e.id === selectedEdgeId;
|
||||
const hl = !chain && (sel || active === e.source || active === e.target);
|
||||
const stroke = sel ? tokens.accent : (chain && inChain) ? tokens.accent : hl ? tokens.info : tokens.textMuted;
|
||||
const strokeWidth = sel ? 2.4 : (chain && inChain) ? 2 : hl ? 1.6 : 1;
|
||||
const opacity = chain ? (sel || inChain ? 1 : 0.12) : (sel || hl ? 1 : 0.45);
|
||||
const markerEnd = (sel || hl || (chain && inChain)) ? `url(#${idPrefix}-ont-arrow-hl)` : `url(#${idPrefix}-ont-arrow)`;
|
||||
const textFill = sel ? tokens.accent : (chain && inChain) ? tokens.accent : hl ? tokens.info : tokens.textSub;
|
||||
const dx = t.x - s.x, dy = t.y - s.y;
|
||||
const d = Math.hypot(dx, dy) || 1;
|
||||
const sx = s.x + (dx / d) * (rOf(s.deg) + 5), sy = s.y + (dy / d) * (rOf(s.deg) + 5);
|
||||
const tx = t.x - (dx / d) * (rOf(t.deg) + 6), ty = t.y - (dy / d) * (rOf(t.deg) + 6);
|
||||
const mx = (sx + tx) / 2, my = (sy + ty) / 2;
|
||||
const label = `${e.label}${sel ? ' ⟶' : ''}`;
|
||||
const w = label.length * 10 + 10;
|
||||
return (
|
||||
<g key={e.id} style={{ cursor: 'pointer' }} onClick={() => onEdgeClick?.(e.id)}>
|
||||
<line x1={sx} y1={sy} x2={tx} y2={ty} stroke="transparent" strokeWidth={14} />
|
||||
<line x1={sx} y1={sy} x2={tx} y2={ty}
|
||||
stroke={stroke}
|
||||
strokeWidth={strokeWidth}
|
||||
opacity={opacity}
|
||||
markerEnd={markerEnd} />
|
||||
<rect x={mx - w / 2} y={my - 8} width={w} height={16} rx={5}
|
||||
fill={sel ? tokens.accentBg : tokens.panelBgAlt}
|
||||
stroke={stroke}
|
||||
strokeWidth={sel ? 1.4 : 0.7} />
|
||||
<text x={mx} y={my + 3.5} textAnchor="middle" fontSize={10} fontWeight={sel ? 700 : 500}
|
||||
fill={textFill}>{label}</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* ── 对象节点 ── */}
|
||||
{nodes.map(n => {
|
||||
const r = rOf(n.deg);
|
||||
const sel = n.id === selectedNodeId;
|
||||
const hl = hovered === n.id;
|
||||
const inChain = inChainNode(n);
|
||||
const dim = chain ? !inChain && !sel : (!!active && !sel && !hl && !isNeighbor(n.id));
|
||||
const ring = sel ? tokens.accent : hl ? tokens.info : (chain && inChain) ? toneColor(chainTone(n)) : n.color;
|
||||
return (
|
||||
<g key={n.id} transform={`translate(${n.x}, ${n.y})`} opacity={dim ? 0.28 : 1}
|
||||
style={{ cursor: 'pointer' }}
|
||||
onMouseEnter={() => setHovered(n.id)} onMouseLeave={() => setHovered(null)}
|
||||
onClick={() => onNodeClick?.(n.id)}>
|
||||
{sel && (
|
||||
<circle r={r + 9} fill="none" stroke={tokens.accent} strokeWidth={1.4}
|
||||
strokeDasharray="4 3" opacity={0.75} />
|
||||
)}
|
||||
<circle r={r + 4} fill="none" stroke={ring} strokeWidth={sel ? 2 : (chain && inChain) ? 2.2 : 1}
|
||||
opacity={chain && inChain ? 1 : (sel ? 0.85 : hl ? 0.5 : 0.16)}
|
||||
filter={sel || hl ? `url(#${idPrefix}-ont-strong)` : undefined} />
|
||||
<circle r={r} fill={tokens.panelBgAlt} stroke={ring}
|
||||
strokeWidth={sel ? 2.4 : hl ? 1.8 : (chain && inChain) ? 2.2 : 1.1} filter={`url(#${idPrefix}-ont-soft)`} />
|
||||
{/* 对象自身的品牌色压在底部,区分「销售订单 / 工单 / 采购单」 */}
|
||||
<path d={`M ${-r * 0.45} ${r - 2.5} A ${r} ${r} 0 0 0 ${r * 0.45} ${r - 2.5}`}
|
||||
fill="none" stroke={n.color} strokeWidth={2.4} strokeLinecap="round" opacity={dim ? 0.3 : 0.9} />
|
||||
<text textAnchor="middle" dy={-3} fontSize={r > 30 ? 12 : 11} fontWeight={700}
|
||||
fill={sel || hl ? ring : tokens.text}>{shortName(n.label)}</text>
|
||||
<text textAnchor="middle" dy={12} fontSize={10.5} fontWeight={700}
|
||||
fill={sel || hl ? ring : n.color}>{n.count}</text>
|
||||
<text textAnchor="middle" dy={r + 17} fontSize={10} fill={tokens.textMuted}>
|
||||
{shortName(n.label)} · {n.count} 实例
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
|
||||
{/* ── 链节点 hover tooltip ── */}
|
||||
{(() => {
|
||||
const hoveredMetrics = hovered ? chain?.metrics[hovered] : null;
|
||||
const entries = hoveredMetrics ? Object.entries(hoveredMetrics) : [];
|
||||
const tipW = 220;
|
||||
const tipH = 20 + entries.length * 16;
|
||||
const tipX = Math.min(Math.max(tooltipPos.x + 14, 8), dims.w - tipW - 8);
|
||||
const tipY = Math.min(Math.max(tooltipPos.y + 14, 8), dims.h - tipH - 8);
|
||||
return entries.length > 0 && hovered && chain?.nodeIds.has(hovered) ? (
|
||||
<g transform={`translate(${tipX}, ${tipY})`} pointerEvents="none">
|
||||
<rect x={0} y={0} width={tipW} height={tipH} rx={8}
|
||||
fill={tokens.panelBgAlt} stroke={tokens.border} strokeWidth={1}
|
||||
filter={`url(#${idPrefix}-ont-soft)`} />
|
||||
{entries.map(([k, v], i) => (
|
||||
<text key={k} x={10} y={18 + i * 16} fontSize={11} fill={tokens.text}>
|
||||
<tspan fontWeight={700}>{k}:</tspan>
|
||||
<tspan x={70}>{v}</tspan>
|
||||
</text>
|
||||
))}
|
||||
</g>
|
||||
) : null;
|
||||
})()}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,754 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { AlertTriangle, Boxes, CircleSlash2, Lock, MapPin, Network, Search, ShieldAlert, X, Zap } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import {
|
||||
actions, chainFor, graphEdges, graphNodes, objectById, objects, relations, rules,
|
||||
ONTOLOGY_AS_OF, type ChainNode, type OntAction, type OntInstance, type OntObject, type OntRelation, type OntRule, type Severity, type Tone,
|
||||
} from '../../data/ontology';
|
||||
import { salesOrders } from '../../data/ibp';
|
||||
import { money } from '../../lib/money';
|
||||
import OntologyGraph, { type ChainOverlay } from './OntologyGraph';
|
||||
|
||||
/**
|
||||
* 业务本体总览:把洁雅家居这批准单据(销售订单 / 生产工单 / 工单材料明细 / 采购订单 /
|
||||
* 客户 / 供应商 / 物料 / 仓库)抽象成「对象—关系—规则—动作」四层,结构在上方图谱里看,
|
||||
* 清单在下方四栏里选,点任意条目在右侧下钻到属性与真实实例。
|
||||
*
|
||||
* 所有数字(实例数、关系基数、规则命中数)都在 src/data/ontology.ts 里从 JSON 原始单据实时算出,
|
||||
* 页面不写死任何统计值。文案与本体数据层同源,全部是业务单据里的中文术语,因此不走 i18n 词典。
|
||||
*/
|
||||
|
||||
type Sel =
|
||||
| { kind: 'object'; id: string }
|
||||
| { kind: 'relation'; id: string }
|
||||
| { kind: 'rule'; id: string }
|
||||
| { kind: 'action'; id: string };
|
||||
|
||||
const toneColor = (tk: ThemeTokens, t: Tone) =>
|
||||
t === 'success' ? { c: tk.success, bg: tk.successBg }
|
||||
: t === 'warning' ? { c: tk.warning, bg: tk.warningBg }
|
||||
: t === 'danger' ? { c: tk.danger, bg: tk.dangerBg }
|
||||
: { c: tk.info, bg: tk.infoBg };
|
||||
|
||||
const sevTone = (s: Severity): Tone => (s === 'error' ? 'danger' : s === 'warning' ? 'warning' : 'info');
|
||||
|
||||
const ACTION_TYPE: Record<OntAction['type'], { label: string; tone: Tone }> = {
|
||||
query: { label: '查询', tone: 'info' },
|
||||
alert: { label: '告警', tone: 'warning' },
|
||||
report: { label: '报表', tone: 'success' },
|
||||
workflow: { label: '流程', tone: 'danger' },
|
||||
};
|
||||
|
||||
/* 卡片底:选中时压 accent 边框,未选中只靠边框与留白分组,不加彩色左边条 */
|
||||
const cardBase = (tk: ThemeTokens, on: boolean): React.CSSProperties => ({
|
||||
width: '100%', textAlign: 'left', cursor: 'pointer', marginBottom: 7,
|
||||
padding: '8px 10px', borderRadius: 9,
|
||||
background: on ? tk.accentBg : tk.panelBgAlt,
|
||||
border: `1px solid ${on ? tk.accent : tk.border}`,
|
||||
transition: 'background .15s ease, border-color .15s ease',
|
||||
});
|
||||
|
||||
const Pill = ({ tone, children }: { tone: Tone; children: React.ReactNode }) => {
|
||||
const { tokens } = useTheme();
|
||||
const c = toneColor(tokens, tone);
|
||||
return (
|
||||
<span style={{
|
||||
fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 999, whiteSpace: 'nowrap',
|
||||
color: c.c, background: c.bg, border: `1px solid ${c.c}44`,
|
||||
}}>{children}</span>
|
||||
);
|
||||
};
|
||||
|
||||
interface Props {
|
||||
onExit: () => void;
|
||||
/** 点「定位到订单」:退出本体页并在左栏选中该销售订单 */
|
||||
onLocateSO: (so: string) => void;
|
||||
}
|
||||
|
||||
export default function OntologyView({ onExit, onLocateSO }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const [sel, setSel] = useState<Sel>({ kind: 'object', id: 'so' });
|
||||
const [query, setQuery] = useState('');
|
||||
const [selectedSONo, setSelectedSONo] = useState<string | null>(null);
|
||||
|
||||
const nodes = useMemo(() => graphNodes(), []);
|
||||
const edges = useMemo(() => graphEdges(), []);
|
||||
const hitTotal = useMemo(() => rules.reduce((a, r) => a + (r.blocked ? 0 : r.hits().n), 0), []);
|
||||
|
||||
const chain = useMemo(() => (selectedSONo ? chainFor(selectedSONo) : null), [selectedSONo]);
|
||||
|
||||
const chainOverlay = useMemo<ChainOverlay | null>(() => {
|
||||
if (!chain) return null;
|
||||
|
||||
const toneRank: Record<Tone, number> = { danger: 3, warning: 2, info: 1, success: 0 };
|
||||
const byObjectId = new Map<string, ChainNode[]>();
|
||||
for (const n of chain.nodes) {
|
||||
const list = byObjectId.get(n.objectId);
|
||||
if (list) list.push(n);
|
||||
else byObjectId.set(n.objectId, [n]);
|
||||
}
|
||||
|
||||
const tones: Record<string, Tone> = {};
|
||||
const metrics: Record<string, Record<string, string>> = {};
|
||||
for (const [objectId, nodes] of byObjectId) {
|
||||
const worst = nodes.reduce((acc, cur) => (toneRank[cur.tone] > toneRank[acc.tone] ? cur : acc));
|
||||
tones[objectId] = worst.tone;
|
||||
metrics[objectId] = { ...worst.metrics, 节点数: `${nodes.length}` };
|
||||
}
|
||||
|
||||
return {
|
||||
nodeIds: new Set(chain.nodes.map(n => n.objectId)),
|
||||
edgeIds: new Set(chain.edges.map(e => e.relationId)),
|
||||
tones,
|
||||
metrics,
|
||||
};
|
||||
}, [chain]);
|
||||
|
||||
const q = query.trim().toLowerCase();
|
||||
const match = (...fields: (string | undefined)[]) =>
|
||||
!q || fields.some(f => (f ?? '').toLowerCase().includes(q));
|
||||
|
||||
const visObjects = useMemo(() => objects.filter(o => match(o.name, o.en, o.desc, o.source)), [q]);
|
||||
const visRelations = useMemo(() => relations.filter(r => match(r.name, r.key, r.desc)), [q]);
|
||||
const visRules = useMemo(() => rules.filter(r => match(r.name, r.expr, r.desc, r.on)), [q]);
|
||||
const visActions = useMemo(() => actions.filter(a => match(a.name, a.en, a.desc, a.trigger, a.object)), [q]);
|
||||
|
||||
const detail = useMemo(() => {
|
||||
if (sel.kind === 'object') return objectById(sel.id) as OntObject | undefined;
|
||||
if (sel.kind === 'relation') return relations.find(r => r.id === sel.id);
|
||||
if (sel.kind === 'rule') return rules.find(r => r.id === sel.id);
|
||||
return actions.find(a => a.id === sel.id);
|
||||
}, [sel]);
|
||||
|
||||
/** 当前选中对象的实例列表(只在选中对象时计算,避免每帧重建 63/70 行) */
|
||||
const instances = useMemo<OntInstance[]>(
|
||||
() => (sel.kind === 'object' ? (detail as OntObject | undefined)?.instances() ?? [] : []),
|
||||
[sel, detail],
|
||||
);
|
||||
|
||||
const selectedEdgeId = sel.kind === 'relation' ? sel.id : null;
|
||||
const selectedNodeId = sel.kind === 'object' ? sel.id
|
||||
: sel.kind === 'relation' ? (detail as OntRelation | undefined)?.from ?? null
|
||||
: null;
|
||||
|
||||
const colHead = (icon: React.ReactNode, label: string, n: number, total: number) => (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto',
|
||||
padding: '0 2px 7px', marginBottom: 8, borderBottom: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<span style={{ display: 'flex', color: tokens.accent }}>{icon}</span>
|
||||
<span style={{ fontSize: 13, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em' }}>{label}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: q ? tokens.warning : tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
|
||||
{n}/{total}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
const colScroll: React.CSSProperties = { flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', paddingRight: 4 };
|
||||
const colBox: React.CSSProperties = {
|
||||
flex: '1 1 0', minWidth: 0, display: 'flex', flexDirection: 'column',
|
||||
padding: '0 10px 8px', borderRadius: 12, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
|
||||
};
|
||||
|
||||
return (
|
||||
<div style={{ flex: 1, minHeight: 0, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
|
||||
{/* ── 标题栏:窄窗口时换行而不是把退出按钮挤出可视区(容器 overflow:hidden 会裁掉溢出) ── */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', flexWrap: 'wrap',
|
||||
padding: '2px 2px 0',
|
||||
}}>
|
||||
<Boxes size={19} style={{ color: tokens.accent, flexShrink: 0 }} aria-hidden />
|
||||
<span style={{ fontSize: 15.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.03em' }}>业务本体</span>
|
||||
<span style={{ fontSize: 11.5, color: tokens.textMuted, flexShrink: 0 }}>
|
||||
快照日 {ONTOLOGY_AS_OF} · 数据仅本批 Excel 单据
|
||||
</span>
|
||||
<span style={{ flex: '1 1 24px' }} />
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
|
||||
{[
|
||||
{ l: '对象', v: objects.length }, { l: '关系', v: relations.length },
|
||||
{ l: '规则', v: rules.length }, { l: '动作', v: actions.length },
|
||||
{ l: '当前命中', v: hitTotal, hot: true },
|
||||
].map(s => (
|
||||
<span key={s.l} style={{
|
||||
fontSize: 11, fontWeight: 700, padding: '2px 9px', borderRadius: 999, whiteSpace: 'nowrap',
|
||||
color: s.hot ? tokens.warning : tokens.textSub,
|
||||
background: s.hot ? tokens.warningBg : tokens.accentBg,
|
||||
border: `1px solid ${s.hot ? `${tokens.warning}55` : tokens.border}`,
|
||||
fontVariantNumeric: 'tabular-nums',
|
||||
}}>{s.l} {s.v}</span>
|
||||
))}
|
||||
</div>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '1 1 190px', minWidth: 150, maxWidth: 260,
|
||||
padding: '3px 9px', borderRadius: 999, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
<Search size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} aria-hidden />
|
||||
<input
|
||||
value={query}
|
||||
onChange={e => setQuery(e.target.value)}
|
||||
placeholder="搜索对象 / 关系 / 规则 / 动作"
|
||||
aria-label="搜索对象 / 关系 / 规则 / 动作"
|
||||
style={{
|
||||
flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none',
|
||||
color: tokens.text, fontSize: 12,
|
||||
}}
|
||||
/>
|
||||
{query && (
|
||||
<button onClick={() => setQuery('')} title="清空搜索" style={{ background: 'none', border: 'none', cursor: 'pointer', color: tokens.textMuted, display: 'flex' }}>
|
||||
<X size={12} aria-hidden />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={onExit}
|
||||
title="退出业务本体总览 (ESC)"
|
||||
style={{
|
||||
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
|
||||
padding: '4px 11px', borderRadius: 8, fontSize: 11.5, fontWeight: 700,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
<X size={13} aria-hidden /> 退出 ESC
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* ── SCHEMA 徽标行:一眼看清每类对象有多少实例 ── */}
|
||||
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', flex: '0 0 auto' }}>
|
||||
{objects.map(o => {
|
||||
const on = sel.kind === 'object' && sel.id === o.id;
|
||||
const n = o.instances().length;
|
||||
return (
|
||||
<button
|
||||
key={o.id}
|
||||
onClick={() => setSel({ kind: 'object', id: o.id })}
|
||||
title={o.desc}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', whiteSpace: 'nowrap',
|
||||
padding: '3px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: on ? 800 : 600,
|
||||
color: on ? tokens.text : tokens.textSub,
|
||||
background: on ? tokens.accentBg : tokens.kpiCardBg,
|
||||
border: `1px solid ${on ? o.color : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
<span style={{ width: 7, height: 7, borderRadius: 99, background: o.color, boxShadow: `0 0 7px ${o.color}88` }} />
|
||||
{o.name}
|
||||
<span style={{ color: o.color, fontVariantNumeric: 'tabular-nums' }}>{n}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* ── 上:销售订单选择器 + 图谱 + 详情面板 ── */}
|
||||
<div style={{ flex: '1.12 1 0', minHeight: 210, display: 'flex', gap: 10 }}>
|
||||
{/* 销售订单选择器 */}
|
||||
<div style={{
|
||||
flex: '0 0 220px', minWidth: 0, display: 'flex', flexDirection: 'column',
|
||||
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, flex: '0 0 auto',
|
||||
padding: '7px 12px', borderBottom: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<Boxes size={13} style={{ color: tokens.accent }} aria-hidden />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 800, color: tokens.text }}>销售订单</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{salesOrders.length}</span>
|
||||
</div>
|
||||
<div style={{ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '0 8px 8px' }}>
|
||||
{salesOrders.map(s => {
|
||||
const on = selectedSONo === s.销售订单号;
|
||||
return (
|
||||
<button
|
||||
key={s.销售订单号}
|
||||
onClick={() => setSelectedSONo(on ? null : s.销售订单号)}
|
||||
style={{
|
||||
width: '100%', textAlign: 'left', cursor: 'pointer', marginTop: 7,
|
||||
padding: '7px 9px', borderRadius: 9,
|
||||
background: on ? tokens.accentBg : tokens.panelBgAlt,
|
||||
border: `1px solid ${on ? tokens.accent : tokens.border}`,
|
||||
transition: 'background .15s ease, border-color .15s ease',
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{s.销售订单号}
|
||||
</div>
|
||||
<div style={{ marginTop: 2, fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{s.客户简称} · {s.预计发货日期}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{
|
||||
flex: '1 1 0', minWidth: 0, display: 'flex', flexDirection: 'column',
|
||||
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, flex: '0 0 auto',
|
||||
padding: '7px 12px', borderBottom: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<Network size={13} style={{ color: tokens.accent }} aria-hidden />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 800, color: tokens.text }}>本体图谱</span>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted }}>节点=对象(圈内数字为实例数)· 连线=关系 · 点节点或连线看定义</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>悬停可看关联链路</span>
|
||||
</div>
|
||||
<div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
|
||||
<OntologyGraph
|
||||
nodes={nodes} edges={edges}
|
||||
selectedNodeId={selectedNodeId} selectedEdgeId={selectedEdgeId}
|
||||
chain={chainOverlay}
|
||||
onNodeClick={id => setSel({ kind: 'object', id })}
|
||||
onEdgeClick={id => setSel({ kind: 'relation', id })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 详情面板 */}
|
||||
<div style={{
|
||||
flex: '0 0 clamp(360px, 34%, 520px)', minWidth: 0, display: 'flex', flexDirection: 'column',
|
||||
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
{selectedSONo && chain && <ChainSummary summary={chain.summary} />}
|
||||
<DetailPanel
|
||||
sel={sel} detail={detail} instances={instances}
|
||||
onPickObject={id => setSel({ kind: 'object', id })}
|
||||
onLocateSO={onLocateSO}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── 下:对象 / 关系 / 规则 / 动作 四栏清单 ── */}
|
||||
<div style={{ flex: '1 1 0', minHeight: 178, display: 'flex', gap: 10 }}>
|
||||
<div style={colBox}>
|
||||
{colHead(<Boxes size={13} aria-hidden />, '对象 Object', visObjects.length, objects.length)}
|
||||
<div style={colScroll}>
|
||||
{visObjects.map(o => {
|
||||
const on = sel.kind === 'object' && sel.id === o.id;
|
||||
return (
|
||||
<button key={o.id} onClick={() => setSel({ kind: 'object', id: o.id })} style={cardBase(tokens, on)}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ width: 6, height: 6, borderRadius: 99, background: o.color, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.name}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, fontWeight: 800, color: o.color, fontVariantNumeric: 'tabular-nums' }}>{o.instances().length}</span>
|
||||
</div>
|
||||
<div style={{ marginTop: 3, fontSize: 10.5, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>
|
||||
{o.en} · {o.attrs.length} 属性
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{visObjects.length === 0 && <Empty tk={tokens} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={colBox}>
|
||||
{colHead(<Network size={13} aria-hidden />, '关系 Relation', visRelations.length, relations.length)}
|
||||
<div style={colScroll}>
|
||||
{visRelations.map(r => {
|
||||
const on = sel.kind === 'relation' && sel.id === r.id;
|
||||
return (
|
||||
<button key={r.id} onClick={() => setSel({ kind: 'relation', id: r.id })} style={cardBase(tokens, on)}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.text }}>{r.name}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Pill tone="info">{r.cardinality}</Pill>
|
||||
</div>
|
||||
<div style={{ marginTop: 3, display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textSub, overflow: 'hidden', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ color: objectById(r.from)?.color, fontWeight: 700 }}>{objectById(r.from)?.name}</span>
|
||||
<span style={{ color: tokens.textMuted }}>→</span>
|
||||
<span style={{ color: objectById(r.to)?.color, fontWeight: 700 }}>{objectById(r.to)?.name}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{r.count()}</span>
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{visRelations.length === 0 && <Empty tk={tokens} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={colBox}>
|
||||
{colHead(<ShieldAlert size={13} aria-hidden />, '规则 Rule', visRules.length, rules.length)}
|
||||
<div style={colScroll}>
|
||||
{visRules.map(r => {
|
||||
const on = sel.kind === 'rule' && sel.id === r.id;
|
||||
const h = r.hits();
|
||||
return (
|
||||
<button
|
||||
key={r.id} onClick={() => setSel({ kind: 'rule', id: r.id })}
|
||||
style={{ ...cardBase(tokens, on), opacity: r.blocked ? 0.62 : 1 }}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||
{r.blocked
|
||||
? <CircleSlash2 size={11} style={{ color: tokens.textMuted, flexShrink: 0 }} aria-hidden />
|
||||
: <AlertTriangle size={11} style={{ color: toneColor(tokens, sevTone(r.severity)).c, flexShrink: 0 }} aria-hidden />}
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{r.blocked
|
||||
? <Pill tone="warning">数据缺口</Pill>
|
||||
: <span style={{ fontSize: 11.5, fontWeight: 800, color: h.n ? toneColor(tokens, sevTone(r.severity)).c : tokens.success, fontVariantNumeric: 'tabular-nums' }}>{h.n}</span>}
|
||||
</div>
|
||||
<div style={{ marginTop: 3, fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.on}{!r.blocked && ` · ${h.unit}`}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{visRules.length === 0 && <Empty tk={tokens} />}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={colBox}>
|
||||
{colHead(<Zap size={13} aria-hidden />, '动作 Action', visActions.length, actions.length)}
|
||||
<div style={colScroll}>
|
||||
{visActions.map(a => {
|
||||
const on = sel.kind === 'action' && sel.id === a.id;
|
||||
const n = a.targets?.().length ?? 0;
|
||||
return (
|
||||
<button key={a.id} onClick={() => setSel({ kind: 'action', id: a.id })} style={cardBase(tokens, on)}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.name}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Pill tone={ACTION_TYPE[a.type].tone}>{ACTION_TYPE[a.type].label}</Pill>
|
||||
{!a.targets && <Pill tone="warning">不可执行</Pill>}
|
||||
</div>
|
||||
<div style={{ marginTop: 3, display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', whiteSpace: 'nowrap' }}>
|
||||
<span style={{ fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>{a.en}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span>{a.object}</span>
|
||||
{a.targets && <span style={{ color: n ? tokens.accent : tokens.textMuted, fontWeight: 700 }}>· {n}</span>}
|
||||
</div>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{visActions.length === 0 && <Empty tk={tokens} />}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const Empty = ({ tk }: { tk: ThemeTokens }) => (
|
||||
<div style={{ padding: '22px 0', textAlign: 'center', fontSize: 12, color: tk.textMuted }}>无匹配条目</div>
|
||||
);
|
||||
|
||||
/* ── 链汇总 ──────────────────────────────────────────────────────────── */
|
||||
|
||||
function ChainSummary({ summary }: { summary: { level: Tone; text: string; redFlags: string[] } }) {
|
||||
const { tokens } = useTheme();
|
||||
const tc = toneColor(tokens, summary.level);
|
||||
return (
|
||||
<div style={{
|
||||
marginBottom: 10, padding: '9px 12px', borderRadius: 10,
|
||||
background: tc.bg, border: `1px solid ${tc.c}44`,
|
||||
}}>
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: tc.c }}>{summary.text}</div>
|
||||
{summary.redFlags.length > 0 && (
|
||||
<ul style={{ margin: '6px 0 0', paddingLeft: 16, fontSize: 11, color: tokens.textSub }}>
|
||||
{summary.redFlags.map((f, i) => <li key={i}>{f}</li>)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── 右侧详情面板 ─────────────────────────────────────────────────────── */
|
||||
|
||||
function DetailPanel({
|
||||
sel, detail, instances, onPickObject, onLocateSO,
|
||||
}: {
|
||||
sel: Sel;
|
||||
detail: OntObject | OntRelation | OntRule | OntAction | undefined;
|
||||
instances: OntInstance[];
|
||||
onPickObject: (id: string) => void;
|
||||
onLocateSO: (so: string) => void;
|
||||
}) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const label: React.CSSProperties = { fontSize: 10.5, fontWeight: 700, color: tokens.textMuted, letterSpacing: '0.06em' };
|
||||
const kv: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 3, marginBottom: 9 };
|
||||
|
||||
const head = (title: string, en: string | undefined, tone: Tone | null, tag: string) => (
|
||||
<div style={{ padding: '10px 12px 9px', borderBottom: `1px solid ${tokens.border}`, flex: '0 0 auto' }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
|
||||
<span style={{ fontSize: 10.5, fontWeight: 800, color: tokens.accent, padding: '1px 7px', borderRadius: 999, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}` }}>{tag}</span>
|
||||
<span style={{ fontSize: 14.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{tone && <Pill tone={tone}>{tone === 'danger' ? '硬约束' : tone === 'warning' ? '预警' : '提示'}</Pill>}
|
||||
</div>
|
||||
{en && <div style={{ marginTop: 4, fontSize: 10.5, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>{en}</div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
const body: React.CSSProperties = { flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '10px 12px' };
|
||||
|
||||
if (!detail) {
|
||||
return (
|
||||
<div style={{ flex: 1, display: 'grid', placeItems: 'center', color: tokens.textMuted, fontSize: 12.5 }}>
|
||||
在图谱或下方清单里选择一个条目
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── 对象:属性定义 + 实例下钻 ── */
|
||||
if (sel.kind === 'object') {
|
||||
const o = detail as OntObject;
|
||||
const locatable = o.id === 'so';
|
||||
return (
|
||||
<>
|
||||
{head(o.name, `${o.en} · ${instances.length} 实例`, null, '对象')}
|
||||
<div style={body}>
|
||||
<div style={kv}>
|
||||
<span style={label}>业务含义</span>
|
||||
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{o.desc}</span>
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>数据来源</span>
|
||||
<span style={{ fontSize: 11.5, color: tokens.textMuted }}>{o.source}</span>
|
||||
</div>
|
||||
<div style={{ ...kv, marginBottom: 4 }}>
|
||||
<span style={label}>属性 {o.attrs.length} 项</span>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
|
||||
{o.attrs.map(a => (
|
||||
<span
|
||||
key={a.en}
|
||||
title={`${a.name}:${a.type}${a.required ? ' · 必填' : ' · 可空'}${a.note ? ` — ${a.note}` : ''}`}
|
||||
style={{
|
||||
fontSize: 10.5, padding: '2px 7px', borderRadius: 6, cursor: 'default',
|
||||
fontFamily: 'ui-monospace, SFMono-Regular, monospace',
|
||||
color: a.required ? tokens.textSub : tokens.textMuted,
|
||||
background: a.required ? tokens.kpiCardBg : 'transparent',
|
||||
border: `1px dashed ${a.required ? tokens.borderAccent : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{a.en}{a.required ? '' : '?'}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>虚线=该列在本批数据里可空;悬停看中文列名与口径说明</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, margin: '10px 0 7px', paddingTop: 8, borderTop: `1px solid ${tokens.border}` }}>
|
||||
<span style={label}>实例下钻</span>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted }}>{instances.length} 条</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{locatable && <span style={{ fontSize: 10.5, color: tokens.accent }}>点击定位到左栏</span>}
|
||||
</div>
|
||||
{instances.map((it, i) => (
|
||||
<InstanceRow key={`${it.id}-${i}`} it={it} locatable={locatable} onLocateSO={onLocateSO} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── 关系:两端 + 基数 + 连接键 ── */
|
||||
if (sel.kind === 'relation') {
|
||||
const r = detail as OntRelation;
|
||||
const from = objectById(r.from), to = objectById(r.to);
|
||||
return (
|
||||
<>
|
||||
{head(`关系 · ${r.name}`, r.id, null, '关系')}
|
||||
<div style={body}>
|
||||
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8, marginBottom: 10 }}>
|
||||
{[from, to].map((o, i) => (
|
||||
<div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
|
||||
<button
|
||||
onClick={() => o && onPickObject(o.id)}
|
||||
title="查看该对象"
|
||||
style={{
|
||||
textAlign: 'left', cursor: 'pointer', padding: '7px 9px', borderRadius: 9,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${o?.color ?? tokens.border}66`,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 10, color: tokens.textMuted }}>{i ? '目标' : '起点'}</span>
|
||||
<div style={{ fontSize: 13, fontWeight: 700, color: o?.color }}>{o?.name ?? r[i ? 'to' : 'from']}</div>
|
||||
<div style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{o ? `${o.instances().length} 实例` : ''}</div>
|
||||
</button>
|
||||
{i === 0 && (
|
||||
<span style={{ textAlign: 'center', fontSize: 10.5, color: tokens.accent, fontWeight: 800, marginTop: -4 }}>{r.cardinality}</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>连接键</span>
|
||||
<span style={{ fontSize: 11.5, fontFamily: 'ui-monospace, SFMono-Regular, monospace', color: tokens.textSub }}>{r.key}</span>
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>当前实例数</span>
|
||||
<span style={{ fontSize: 20, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{r.count()}</span>
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>口径说明</span>
|
||||
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{r.desc}</span>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/* ── 规则:表达式 + 实时命中 + 命中订单 ── */
|
||||
const isRule = sel.kind === 'rule';
|
||||
const rule = detail as OntRule;
|
||||
const action = detail as OntAction;
|
||||
const actionTargets = action.targets?.() ?? [];
|
||||
const targets = isRule ? rule.hits() : { n: actionTargets.length, unit: '个目标对象', targets: actionTargets };
|
||||
const list = isRule ? targets.targets : actionTargets;
|
||||
const soObject = objects.find(o => o.id === 'so');
|
||||
const soSet = new Set(soObject?.instances().map(i => i.id) ?? []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{head(
|
||||
isRule ? rule.name : action.name,
|
||||
isRule ? `${rule.on} · ${rule.id}` : `${action.en} · ${action.object}`,
|
||||
isRule ? sevTone(rule.severity) : null,
|
||||
isRule ? '规则' : '动作',
|
||||
)}
|
||||
<div style={body}>
|
||||
{isRule ? (
|
||||
<>
|
||||
<div style={{
|
||||
...kv, padding: '7px 9px', borderRadius: 8, background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<span style={label}>判定表达式</span>
|
||||
<span style={{ fontSize: 11.5, lineHeight: 1.6, fontFamily: 'ui-monospace, SFMono-Regular, monospace', color: tokens.text }}>
|
||||
{rule.expr}
|
||||
</span>
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>约束强度</span>
|
||||
<span style={{ fontSize: 12, color: tokens.textSub }}>
|
||||
{rule.severity === 'error' ? '硬约束:违反即履约中断' : rule.severity === 'warning' ? '预警:需要人工确认后处置' : '提示:结构性风险画像'}
|
||||
</span>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div style={kv}>
|
||||
<span style={label}>触发条件</span>
|
||||
<span style={{ fontSize: 12, color: tokens.textSub }}>{action.trigger}</span>
|
||||
</div>
|
||||
<div style={kv}>
|
||||
<span style={label}>作用对象 / 类型</span>
|
||||
<span style={{ fontSize: 12, color: tokens.textSub }}>{action.object} · {ACTION_TYPE[action.type].label}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
<div style={kv}>
|
||||
<span style={label}>说明</span>
|
||||
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{isRule ? rule.desc : action.desc}</span>
|
||||
</div>
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'baseline', gap: 8, margin: '10px 0 8px', paddingTop: 9,
|
||||
borderTop: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<span style={{ fontSize: 22, fontWeight: 800, fontVariantNumeric: 'tabular-nums', color: isRule && rule.blocked ? tokens.textMuted : targets.n ? toneColor(tokens, isRule ? sevTone(rule.severity) : 'info').c : tokens.success }}>
|
||||
{isRule && rule.blocked ? '—' : targets.n}
|
||||
</span>
|
||||
<span style={{ fontSize: 11.5, color: tokens.textSub }}>
|
||||
{isRule && rule.blocked ? '数据缺口,规则无法执行' : targets.unit}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{isRule && !rule.blocked && targets.n === 0 && <Pill tone="success">本批无违反</Pill>}
|
||||
</div>
|
||||
{isRule && rule.blocked && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'flex-start', gap: 6, padding: '8px 10px', borderRadius: 9,
|
||||
background: tokens.warningBg, border: `1px solid ${tokens.warning}44`,
|
||||
}}>
|
||||
<Lock size={13} style={{ color: tokens.warning, marginTop: 1, flexShrink: 0 }} aria-hidden />
|
||||
<span style={{ fontSize: 11.5, lineHeight: 1.6, color: tokens.textSub }}>
|
||||
该规则依赖现存量 / 已分配 / 安全库存 / 在途入库四类字段,本批 Excel 单据均未提供,
|
||||
因此只标注为数据缺口,不给「通过」结论。
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{list.length > 0 && (
|
||||
<>
|
||||
<div style={{ ...label, margin: '11px 0 6px' }}>命中清单 {list.length} 项</div>
|
||||
{list.map((code, i) => {
|
||||
const isSO = soSet.has(code);
|
||||
return (
|
||||
<div
|
||||
key={`${code}-${i}`}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5, padding: '6px 9px',
|
||||
borderRadius: 8, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
|
||||
}}
|
||||
>
|
||||
<span style={{ fontSize: 11.5, fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{code}
|
||||
</span>
|
||||
{!isSO && <span style={{ fontSize: 10.5, color: tokens.textMuted }}>编码</span>}
|
||||
<span style={{ flex: 1 }} />
|
||||
{isSO ? (
|
||||
<button
|
||||
onClick={() => onLocateSO(code)}
|
||||
title="关闭本体页并在左栏选中该订单"
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer', flexShrink: 0,
|
||||
fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 999,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}
|
||||
>
|
||||
<MapPin size={11} aria-hidden /> 定位
|
||||
</button>
|
||||
) : (
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>非订单主键</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** 实例行:对象实例的通用展示,销售订单额外给「定位」入口 */
|
||||
function InstanceRow({ it, locatable, onLocateSO }: { it: OntInstance; locatable: boolean; onLocateSO: (so: string) => void }) {
|
||||
const { tokens } = useTheme();
|
||||
const tone = toneColor(tokens, it.tone ?? 'info');
|
||||
const style: React.CSSProperties = {
|
||||
display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5, padding: '6px 9px', borderRadius: 8,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`,
|
||||
};
|
||||
const content = (
|
||||
<>
|
||||
<span style={{ width: 5, height: 22, borderRadius: 3, background: tone.c, flexShrink: 0, opacity: 0.75 }} />
|
||||
<div style={{ minWidth: 0, flex: 1 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.title}</span>
|
||||
{it.badge && <Pill tone={it.tone ?? 'info'}>{it.badge}</Pill>}
|
||||
</div>
|
||||
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.sub}</div>
|
||||
</div>
|
||||
<div style={{ textAlign: 'right', flexShrink: 0 }}>
|
||||
{it.amount !== undefined && (
|
||||
<div style={{ fontSize: 12, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{money(it.amount)}</div>
|
||||
)}
|
||||
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 1 }}>{it.meta}</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
if (locatable) {
|
||||
return (
|
||||
<button
|
||||
onClick={() => onLocateSO(it.id)}
|
||||
title="关闭本体页并在左栏选中该订单"
|
||||
style={{ ...style, width: '100%', textAlign: 'left', font: 'inherit', color: 'inherit', cursor: 'pointer' }}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
return <div style={{ ...style, cursor: 'default' }}>{content}</div>;
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import { CircleDollarSign, FlaskConical, ShoppingCart, Target, Factory, Truck } from 'lucide-react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import { useText } from '../../i18n/useText';
|
||||
import { PanelBody } from '../layout/PanelShell';
|
||||
import type { MetricNode } from '../../data/sqlite';
|
||||
import { alertColor, fmt } from '../../lib/metric';
|
||||
import { achieveAt, levelAt, periodLabel, valueAt } from '../../lib/time';
|
||||
import { STAGES, flowStats, type FlowIcon } from '../../lib/process';
|
||||
|
||||
/**
|
||||
* 流程效能看板(研产供销六段价值链 · 过程指标层)。
|
||||
*
|
||||
* 与指标树的分工写在标题下那句话里:指标树是**结果**(钱和率的达成),
|
||||
* 这里是**过程**(一批商机/项目/工单在链上每段停留多久、流过多少、返工多少)。
|
||||
* 每段下方的指标片是真实 metric_node,点开即联动中央看板;
|
||||
* 过程量则是可复现的模拟值,随底部时间轴游标一起演变。
|
||||
*/
|
||||
interface Props {
|
||||
byCode: Map<string, MetricNode>;
|
||||
selected: string;
|
||||
onSelect: (code: string) => void;
|
||||
period: number;
|
||||
}
|
||||
|
||||
const ICONS: Record<FlowIcon, typeof Target> = {
|
||||
target: Target, flask: FlaskConical, cart: ShoppingCart, factory: Factory, truck: Truck, cash: CircleDollarSign,
|
||||
};
|
||||
|
||||
export default function ProcessFlowPanel({ byCode, selected, onSelect, period }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
const { t } = useText();
|
||||
|
||||
const { stats, summary } = flowStats(period);
|
||||
const bottleneck = STAGES.findIndex(s => s.key === summary.bottleneckKey);
|
||||
const constraint = STAGES.findIndex(s => s.key === summary.constraintKey);
|
||||
/* 在制品堆得最高的一段:比“总和”更能指出哪里在堵 */
|
||||
const wipTop = stats.reduce((mi, x, i) => (x.wip > stats[mi].wip ? i : mi), 0);
|
||||
|
||||
const tile = (label: string, value: string, sub: string | null, color: string) => (
|
||||
<div style={{
|
||||
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 9, padding: '5px 8px', minWidth: 0,
|
||||
}}>
|
||||
<div style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
|
||||
<div style={{
|
||||
fontSize: 16, fontWeight: 800, color, lineHeight: 1.25, fontVariantNumeric: 'tabular-nums',
|
||||
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>{value}</div>
|
||||
{sub && <div style={{ fontSize: 9.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
|
||||
</div>
|
||||
);
|
||||
|
||||
/** 过程量小格:标签 + 值 + 目标/环比提示 */
|
||||
const stat = (label: string, value: string, tone: string) => (
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4, minWidth: 0 }}>
|
||||
<span style={{ fontSize: 10, color: tokens.textMuted, flexShrink: 0 }}>{label}</span>
|
||||
<span style={{
|
||||
fontSize: 12, fontWeight: 700, color: tone, fontVariantNumeric: 'tabular-nums',
|
||||
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap',
|
||||
}}>{value}</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<PanelBody>
|
||||
{/* 口径提示:过程 vs 结果 */}
|
||||
<div style={{
|
||||
fontSize: 11, lineHeight: 1.55, color: tokens.textMuted, marginBottom: 8,
|
||||
padding: '6px 9px', borderRadius: 8, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
{t.flow.hint}
|
||||
</div>
|
||||
|
||||
{/* 全链汇总 */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 4 }}>
|
||||
{tile(t.flow.cycle, `${fmt(summary.cycle)}${t.flow.unitDay}`, `${t.flow.base} ${fmt(summary.cycleBase)}${t.flow.unitDay}`, tokens.text)}
|
||||
{tile(t.flow.e2e, `${fmt(summary.e2e)}%`, `${t.flow.base} ${fmt(summary.e2eBase)}%`, summary.e2e >= 55 ? tokens.success : summary.e2e >= 40 ? tokens.warning : tokens.danger)}
|
||||
{tile(t.flow.throughput, summary.throughput.toLocaleString(), `${t.flow.constraint} · ${STAGES[constraint].zh}`, tokens.info)}
|
||||
{tile(t.flow.wip, summary.wip.toLocaleString(), `max · ${STAGES[wipTop].zh}`, tokens.textSub)}
|
||||
</div>
|
||||
<div
|
||||
title={t.flow.bottleneckTip}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, marginBottom: 10,
|
||||
padding: '4px 8px', borderRadius: 8,
|
||||
background: `${alertColor(stats[bottleneck].status, tokens)}14`,
|
||||
border: `1px solid ${alertColor(stats[bottleneck].status, tokens)}3a`,
|
||||
}}>
|
||||
<span style={{ width: 6, height: 6, borderRadius: '50%', background: alertColor(stats[bottleneck].status, tokens), flexShrink: 0 }} />
|
||||
<span style={{ color: tokens.textSub, flexShrink: 0 }}>{t.flow.bottleneck}</span>
|
||||
<span style={{ color: tokens.text, fontWeight: 700, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{STAGES[bottleneck].zh}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ color: alertColor(stats[bottleneck].status, tokens), fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>
|
||||
{fmt(stats[bottleneck].score)}%
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 六段流程 */}
|
||||
{STAGES.map((s, i) => {
|
||||
const st = stats[i];
|
||||
const c = alertColor(st.status, tokens);
|
||||
const Icon = ICONS[s.icon];
|
||||
const active = s.codes.includes(selected);
|
||||
const dwellTone = st.dwell <= st.dwellTarget ? tokens.success : st.dwell <= st.dwellTarget * 1.12 ? tokens.warning : tokens.danger;
|
||||
const fpqcTone = st.fpqc >= st.fpqcTarget ? tokens.success : st.fpqc >= st.fpqcTarget - 4 ? tokens.warning : tokens.danger;
|
||||
const reworkTone = st.rework <= st.reworkTarget ? tokens.success : st.rework <= st.reworkTarget * 1.15 ? tokens.warning : tokens.danger;
|
||||
const trend = st.dwellDelta === null ? t.flow.flat
|
||||
: st.dwellDelta < -0.05 ? `${t.flow.faster} ${fmt(Math.abs(st.dwellDelta))}${t.flow.unitDay}`
|
||||
: st.dwellDelta > 0.05 ? `${t.flow.slower} ${fmt(st.dwellDelta)}${t.flow.unitDay}`
|
||||
: t.flow.flat;
|
||||
|
||||
return (
|
||||
<div key={s.key}>
|
||||
{/* 段间连线:在制品沿链流动 */}
|
||||
{i > 0 && (
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<div style={{ width: 26, flexShrink: 0, position: 'relative', height: 26 }}>
|
||||
<svg width={26} height={26} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
|
||||
<line x1={13} y1={-2} x2={13} y2={28} stroke={tokens.border} strokeWidth={1.4} />
|
||||
<line
|
||||
className="dash-flow" x1={13} y1={-2} x2={13} y2={28}
|
||||
stroke={alertColor(stats[i - 1].status, tokens)} strokeWidth={1.6} strokeDasharray="3 5" strokeLinecap="round"
|
||||
/>
|
||||
<path d="M 9.5,23 L 13,28 L 16.5,23" fill="none" stroke={tokens.border} strokeWidth={1.4} strokeLinecap="round" />
|
||||
</svg>
|
||||
<span style={{
|
||||
position: 'absolute', left: 30, top: 4, fontSize: 10, whiteSpace: 'nowrap', color: tokens.textMuted,
|
||||
fontVariantNumeric: 'tabular-nums',
|
||||
}}>
|
||||
{t.flow.wip} {stats[i - 1].wip.toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 0 }} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
{/* 轨道节点 */}
|
||||
<div style={{ width: 26, flexShrink: 0, display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
|
||||
<span style={{
|
||||
display: 'grid', placeItems: 'center', width: 26, height: 26, borderRadius: 9, flexShrink: 0,
|
||||
background: `${c}1f`, border: `1px solid ${c}66`, color: c,
|
||||
boxShadow: active ? `0 0 10px ${c}66` : 'none',
|
||||
}}>
|
||||
<Icon size={14} />
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* 段卡 */}
|
||||
<div style={{
|
||||
flex: 1, minWidth: 0, marginBottom: 2, borderRadius: 10, padding: '7px 9px',
|
||||
background: tokens.panelBgAlt,
|
||||
border: `1px solid ${active ? c : tokens.border}`,
|
||||
boxShadow: active ? `0 0 0 1px ${c}44, 0 4px 14px ${c}22` : 'none',
|
||||
transition: 'border-color 0.2s ease, box-shadow 0.2s ease',
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span className={st.status === 'red' ? 'net-breathe' : undefined} style={{
|
||||
width: 7, height: 7, borderRadius: '50%', flexShrink: 0, background: c, boxShadow: `0 0 6px ${c}`,
|
||||
}} />
|
||||
<span style={{ fontSize: 13.5, fontWeight: 800, color: tokens.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{s.zh}
|
||||
</span>
|
||||
<span style={{
|
||||
fontSize: 11.5, fontWeight: 800, color: c, flexShrink: 0, fontVariantNumeric: 'tabular-nums',
|
||||
fontFamily: 'ui-monospace, monospace',
|
||||
}}>{fmt(st.score)}%</span>
|
||||
</div>
|
||||
<div style={{ fontSize: 10, color: tokens.textMuted, marginBottom: 5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
|
||||
{s.roleZh} · {trend}
|
||||
</div>
|
||||
|
||||
{/* 段达成条 */}
|
||||
<div style={{ height: 3, borderRadius: 99, background: tokens.border, overflow: 'hidden', marginBottom: 6 }}>
|
||||
<span style={{
|
||||
display: 'block', height: '100%', width: `${Math.min(100, st.score)}%`, background: c,
|
||||
transition: 'width 0.4s ease',
|
||||
}} />
|
||||
</div>
|
||||
|
||||
{/* 过程四量 */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 8px', marginBottom: 6 }}>
|
||||
{stat(t.flow.dwell, `${fmt(st.dwell)}${t.flow.unitDay}`, dwellTone)}
|
||||
{stat(t.flow.flow, `${st.flow.toLocaleString()}`, tokens.textSub)}
|
||||
{stat(t.flow.fpqc, `${fmt(st.fpqc)}%`, fpqcTone)}
|
||||
{stat(t.flow.rework, `${st.rework}`, reworkTone)}
|
||||
</div>
|
||||
|
||||
{/* 关联指标片:真实 metric_node,点开联动中央看板 */}
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
|
||||
{s.codes.map(cd => {
|
||||
const n = byCode.get(cd);
|
||||
if (!n) return null;
|
||||
const nc = alertColor(levelAt(n, period), tokens);
|
||||
const on = cd === selected;
|
||||
const val = valueAt(n, period);
|
||||
return (
|
||||
<button
|
||||
key={cd} onClick={() => onSelect(cd)} className="ghost-btn"
|
||||
title={`${t.flow.linked} ${n.code} · ${n.name_zh} · ${t.flow.clickTip}`}
|
||||
style={{
|
||||
display: 'flex', alignItems: 'center', gap: 4, maxWidth: '100%', cursor: 'pointer',
|
||||
padding: '2px 6px', borderRadius: 7, fontSize: 10.5,
|
||||
background: on ? `${nc}22` : tokens.cardBg,
|
||||
border: `1px solid ${on ? nc : tokens.border}`,
|
||||
color: tokens.textSub,
|
||||
}}
|
||||
>
|
||||
<span style={{ width: 5, height: 5, borderRadius: '50%', background: nc, flexShrink: 0 }} />
|
||||
<span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: on ? tokens.text : undefined }}>
|
||||
{n.name_zh}
|
||||
</span>
|
||||
<span style={{ color: nc, fontWeight: 700, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>
|
||||
{fmt(val)}{n.unit}
|
||||
</span>
|
||||
<span style={{ color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>
|
||||
{fmt(achieveAt(n, period), 0)}%
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.6, padding: '8px 2px 12px' }}>
|
||||
{periodLabel(period)} · {t.flow.wipTip}
|
||||
</div>
|
||||
</PanelBody>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Boxes, Link2, Package, X } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import { productionOrders, type ProductionOrder } from '../../data/ibp';
|
||||
import { ScrollList } from './PurchaseOrderList';
|
||||
|
||||
/**
|
||||
* 生产工单页签内容:一单一工单(工单号 = WO-销售订单号),按「离完工最近的先处理」排序,已完工沉底。
|
||||
* 点卡片等于把它的来源销售订单送回左栏,与采购单页签共用同一条联动链路。
|
||||
*/
|
||||
|
||||
export const fmtQty = (n: number) => n.toLocaleString('zh-CN');
|
||||
|
||||
/** 未完结工单按预计完工日升序,已完工排最后 */
|
||||
export function sortWorkOrders(rows: ProductionOrder[]): ProductionOrder[] {
|
||||
return [...rows].sort((a, b) => {
|
||||
const doneA = a.单据状态 === '已完工' ? 1 : 0;
|
||||
const doneB = b.单据状态 === '已完工' ? 1 : 0;
|
||||
if (doneA !== doneB) return doneA - doneB;
|
||||
return a.预计完工日期 < b.预计完工日期 ? -1 : a.预计完工日期 > b.预计完工日期 ? 1 : 0;
|
||||
});
|
||||
}
|
||||
|
||||
/** filterSO 非空时只保留该销售订单派生的工单 */
|
||||
export function buildWorkOrders(filterSO: string | null): ProductionOrder[] {
|
||||
return sortWorkOrders(filterSO ? productionOrders.filter(w => w.来源销售订单号 === filterSO) : productionOrders);
|
||||
}
|
||||
|
||||
/** 工单号 / 来源订单 / 产品编码 / 车间 四向模糊匹配 */
|
||||
export function filterWorkOrders(rows: ProductionOrder[], query: string): ProductionOrder[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter(w =>
|
||||
w.工单号.toLowerCase().includes(q)
|
||||
|| w.来源销售订单号.toLowerCase().includes(q)
|
||||
|| w.产品编码.toLowerCase().includes(q)
|
||||
|| w.生产车间.toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
const statusColor = (s: string, tk: ThemeTokens) =>
|
||||
s === '已完工' ? { c: tk.success, bg: tk.successBg }
|
||||
: s === '已下达' ? { c: tk.info, bg: tk.infoBg }
|
||||
: { c: tk.warning, bg: tk.warningBg };
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
filterSO: string | null;
|
||||
onClearFilter: () => void;
|
||||
/** 点击工单:把来源销售订单交给左栏选中态 */
|
||||
onSelectSO: (so: string | null) => void;
|
||||
/** 当前左栏选中订单,用于卡片高亮 */
|
||||
selectedSO: string | null;
|
||||
}
|
||||
|
||||
export default function ProductionOrderList({ query, filterSO, onClearFilter, onSelectSO, selectedSO }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const list = useMemo(() => filterWorkOrders(buildWorkOrders(filterSO), query), [filterSO, query]);
|
||||
const totalQty = useMemo(() => list.reduce((a, w) => a + w.生产数量, 0), [list]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 左栏订单联动条 */}
|
||||
{filterSO && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
|
||||
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
<Link2 size={12} style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button onClick={onClearFilter} title="显示全部工单" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 汇总条 */}
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
|
||||
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
|
||||
}}>
|
||||
<span>{list.length} 张工单 · {new Set(list.map(w => w.生产车间)).size} 个车间</span>
|
||||
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{fmtQty(totalQty)} PCS</span>
|
||||
</div>
|
||||
|
||||
<ScrollList>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
|
||||
{filterSO ? '该销售订单暂无生产工单' : '无匹配工单'}
|
||||
</div>
|
||||
)}
|
||||
{list.map(w => {
|
||||
const active = selectedSO === w.来源销售订单号;
|
||||
const sc = statusColor(w.单据状态, tokens);
|
||||
return (
|
||||
<div
|
||||
key={w.工单号}
|
||||
onClick={() => onSelectSO(active ? null : w.来源销售订单号)}
|
||||
style={{
|
||||
position: 'relative', marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
|
||||
background: active ? tokens.accentBg : tokens.panelBgAlt,
|
||||
border: `1px solid ${active ? tokens.accent : tokens.border}`,
|
||||
transition: 'background .15s, border-color .15s',
|
||||
}}
|
||||
>
|
||||
{active && <span style={{ position: 'absolute', left: -1, top: 10, bottom: 10, width: 3, borderRadius: 2, background: tokens.accent }} />}
|
||||
{/* 行1:工单号 + 状态 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: active ? tokens.accent : tokens.text, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
|
||||
{w.工单号}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{
|
||||
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
|
||||
color: sc.c, background: sc.bg, border: `1px solid ${sc.c}44`, whiteSpace: 'nowrap',
|
||||
}}>{w.单据状态}</span>
|
||||
</div>
|
||||
{/* 行2:来源订单 + 车间 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted }}>来自</span>
|
||||
<span style={{ fontSize: 11.5, color: tokens.textSub, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.来源销售订单号}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{w.生产车间}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap' }}>BOM {w.BOM版本}</span>
|
||||
</div>
|
||||
{/* 行3:产品 + 规格 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5 }}>
|
||||
<Package size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 12.5, color: tokens.text, fontFamily: 'ui-monospace, monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.产品编码}</span>
|
||||
{w.规格型号 && (
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.规格型号}</span>
|
||||
)}
|
||||
</div>
|
||||
{/* 行4:数量 + 工期 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{fmtQty(w.生产数量)}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{w.计量单位}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, whiteSpace: 'nowrap' }}>
|
||||
{w.预计开工日期} → {w.预计完工日期} · {w['生产周期(天)']} 天
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ScrollList>
|
||||
|
||||
{/* 底部口径说明:工单由销售订单派生,一单一工单 */}
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, flex: '0 0 auto', paddingTop: 6,
|
||||
fontSize: 10.5, color: tokens.textMuted, borderTop: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<Boxes size={11} style={{ flexShrink: 0 }} />
|
||||
<span>工单由销售订单派生 · 生产数量已对齐订单数量 · 点击卡片可联动左栏订单</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { Link2, PackageSearch, X } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import { purchaseOrders, type PurchaseOrder } from '../../data/ibp';
|
||||
import { useAutoScroll } from '../../hooks/useAutoScroll';
|
||||
import { useAutoScrollEnabled } from '../layout/AutoScroll';
|
||||
import { money } from '../../lib/money';
|
||||
|
||||
/**
|
||||
* 采购单页签内容:按采购订单号把多行料项归并为一张卡片。
|
||||
* 列表口径(分组 / 过滤 / 金额汇总)全部由这里的纯函数给出,SupplyPanel 复用同一函数算徽标数,
|
||||
* 避免页签标题数字与实际条数各说各话。
|
||||
*/
|
||||
|
||||
export interface POGroup {
|
||||
采购订单号: string; 采购日期: string; 供应商编码: string; 供应商简称: string;
|
||||
预计到货日期: string; 订单状态: string; 金额: number; 行数: number; 材料: string[];
|
||||
来源销售订单: string[];
|
||||
}
|
||||
|
||||
/** 按采购订单号归并;filterSO 非空时只保留该销售订单反查到的采购单 */
|
||||
export function buildPurchaseGroups(filterSO: string | null): POGroup[] {
|
||||
const src = filterSO ? purchaseOrders.filter(p => p.来源销售订单号 === filterSO) : purchaseOrders;
|
||||
const byNo = new Map<string, POGroup>();
|
||||
src.forEach((p: PurchaseOrder) => {
|
||||
let g = byNo.get(p.采购订单号);
|
||||
if (!g) {
|
||||
g = {
|
||||
采购订单号: p.采购订单号, 采购日期: p.采购日期, 供应商编码: p.供应商编码, 供应商简称: p.供应商简称,
|
||||
预计到货日期: p.预计到货日期, 订单状态: p.订单状态, 金额: 0, 行数: 0, 材料: [], 来源销售订单: [],
|
||||
};
|
||||
byNo.set(p.采购订单号, g);
|
||||
}
|
||||
g.金额 += p.含税金额;
|
||||
g.行数 += 1;
|
||||
if (!g.材料.includes(p.材料编码)) g.材料.push(p.材料编码);
|
||||
if (p.来源销售订单号 && !g.来源销售订单.includes(p.来源销售订单号)) g.来源销售订单.push(p.来源销售订单号);
|
||||
});
|
||||
return [...byNo.values()].sort((a, b) => (a.采购日期 < b.采购日期 ? 1 : -1));
|
||||
}
|
||||
|
||||
/** 单号 / 供应商编码 / 供应商简称 / 物料 四向模糊匹配 */
|
||||
export function filterPurchaseGroups(groups: POGroup[], query: string): POGroup[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return groups;
|
||||
return groups.filter(g =>
|
||||
g.采购订单号.toLowerCase().includes(q)
|
||||
|| g.供应商编码.toLowerCase().includes(q)
|
||||
|| g.供应商简称.toLowerCase().includes(q)
|
||||
|| g.材料.some(m => m.toLowerCase().includes(q)));
|
||||
}
|
||||
|
||||
const statusColor = (s: string, tk: ThemeTokens) =>
|
||||
s === '生效' ? { c: tk.success, bg: tk.successBg } : { c: tk.warning, bg: tk.warningBg };
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
/** 左栏选中的销售订单号:非空时只看该订单反查到的采购单 */
|
||||
filterSO: string | null;
|
||||
onClearFilter: () => void;
|
||||
}
|
||||
|
||||
export default function PurchaseOrderList({ query, filterSO, onClearFilter }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const list = useMemo(() => filterPurchaseGroups(buildPurchaseGroups(filterSO), query), [filterSO, query]);
|
||||
const total = useMemo(() => list.reduce((a, g) => a + g.金额, 0), [list]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* 左栏订单联动条 */}
|
||||
{filterSO && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
|
||||
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
<Link2 size={12} style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button onClick={onClearFilter} title="显示全部采购单" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 汇总条 */}
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
|
||||
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
|
||||
}}>
|
||||
<span>{list.length} 张采购单 · {new Set(list.flatMap(g => g.材料)).size} 种物料</span>
|
||||
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{money(total)}</span>
|
||||
</div>
|
||||
|
||||
<ScrollList>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
|
||||
{filterSO ? '该销售订单暂无关联采购单' : '无匹配采购单'}
|
||||
</div>
|
||||
)}
|
||||
{list.map(g => {
|
||||
const sc = statusColor(g.订单状态, tokens);
|
||||
return (
|
||||
<div key={g.采购订单号} style={{
|
||||
marginBottom: 8, padding: '9px 11px', borderRadius: 9,
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
{/* 行1:单号 + 状态 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
|
||||
{g.采购订单号}
|
||||
</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{
|
||||
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
|
||||
color: sc.c, background: sc.bg, border: `1px solid ${sc.c}44`, whiteSpace: 'nowrap',
|
||||
}}>{g.订单状态}</span>
|
||||
</div>
|
||||
{/* 行2:供应商 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
|
||||
<span style={{ fontSize: 12, color: tokens.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{g.供应商简称}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{g.供应商编码}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap' }}>下单 {g.采购日期}</span>
|
||||
</div>
|
||||
{/* 行3:材料 */}
|
||||
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 5, marginTop: 5 }}>
|
||||
<PackageSearch size={12} style={{ color: tokens.textMuted, flexShrink: 0, marginTop: 2 }} />
|
||||
<span style={{ fontSize: 12, color: tokens.text, fontFamily: 'ui-monospace, monospace', lineHeight: 1.5, wordBreak: 'break-all' }}>
|
||||
{g.材料.slice(0, 3).join('、')}{g.材料.length > 3 ? ` 等 ${g.材料.length} 种` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{/* 行4:金额 + 到货 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{money(g.金额)}</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{g.行数} 行</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted }}>到货 {g.预计到货日期}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ScrollList>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 页签共用的滚动区,与 PanelBody 同一套样式。
|
||||
* 自动滚动默认跟随所在面板的开关(AutoScrollProvider),也可以显式传 autoScroll 覆盖。
|
||||
*/
|
||||
export function ScrollList({ children, autoScroll }: { children: React.ReactNode; autoScroll?: boolean }) {
|
||||
const ctx = useAutoScrollEnabled();
|
||||
const enabled = autoScroll ?? ctx.enabled;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useAutoScroll(ref, enabled, { cfg: ctx.cfg });
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className="space-scroll"
|
||||
data-autoscroll={enabled ? 'on' : 'off'}
|
||||
style={{ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '0 0 10px 0' }}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Link2, Users, X } from 'lucide-react';
|
||||
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
|
||||
import { purchaseOrders, suppliers, type Supplier } from '../../data/ibp';
|
||||
import { ScrollList } from './PurchaseOrderList';
|
||||
import { money } from '../../lib/money';
|
||||
|
||||
/**
|
||||
* 供应商资料页签:Excel「供应商资料」的 8 个字段全量展示(采购行数 / 采购金额沿用表内汇总口径)。
|
||||
* 左栏选中销售订单时,只列出该订单实际下单过的供应商——关联关系由采购订单行反推,不另外造数据。
|
||||
*/
|
||||
|
||||
/** 按采购金额从大到小:钱多的供应商先看 */
|
||||
export function sortSuppliers(rows: Supplier[]): Supplier[] {
|
||||
return [...rows].sort((a, b) => b.采购金额 - a.采购金额);
|
||||
}
|
||||
|
||||
/** filterSO 非空时用采购订单行反查该订单涉及的供应商编码 */
|
||||
export function buildSuppliers(filterSO: string | null): Supplier[] {
|
||||
if (!filterSO) return sortSuppliers(suppliers);
|
||||
const codes = new Set(purchaseOrders.filter(p => p.来源销售订单号 === filterSO).map(p => p.供应商编码));
|
||||
return sortSuppliers(suppliers.filter(s => codes.has(s.供应商编码)));
|
||||
}
|
||||
|
||||
/** 编码 / 简称 / 所属类别 / 分管部门 四向模糊匹配 */
|
||||
export function filterSuppliers(rows: Supplier[], query: string): Supplier[] {
|
||||
const q = query.trim().toLowerCase();
|
||||
if (!q) return rows;
|
||||
return rows.filter(s =>
|
||||
s.供应商编码.toLowerCase().includes(q)
|
||||
|| s.供应商简称.toLowerCase().includes(q)
|
||||
|| s.所属类别.toLowerCase().includes(q)
|
||||
|| (s.分管部门 ?? '').toLowerCase().includes(q));
|
||||
}
|
||||
|
||||
/** 客商一体(性质=客户/供应商)是治理关注项,单独给色 */
|
||||
const natureColor = (nature: string, tk: ThemeTokens) =>
|
||||
nature === '客户/供应商' ? { c: tk.warning, bg: tk.warningBg } : { c: tk.info, bg: tk.infoBg };
|
||||
|
||||
interface Props {
|
||||
query: string;
|
||||
filterSO: string | null;
|
||||
onClearFilter: () => void;
|
||||
/** 点击供应商:筛出它的采购单行,回到采购单页签看 */
|
||||
onPickSupplier: (code: string) => void;
|
||||
}
|
||||
|
||||
export default function SupplierList({ query, filterSO, onClearFilter, onPickSupplier }: Props) {
|
||||
const { tokens } = useTheme();
|
||||
|
||||
const list = useMemo(() => filterSuppliers(buildSuppliers(filterSO), query), [filterSO, query]);
|
||||
const total = useMemo(() => list.reduce((a, s) => a + s.采购金额, 0), [list]);
|
||||
const totalLines = useMemo(() => list.reduce((a, s) => a + s.采购行数, 0), [list]);
|
||||
|
||||
return (
|
||||
<>
|
||||
{filterSO && (
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
|
||||
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
|
||||
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
|
||||
}}>
|
||||
<Link2 size={12} style={{ flexShrink: 0 }} />
|
||||
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO} · 仅该单涉及的供应商</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<button onClick={onClearFilter} title="显示全部供应商" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
|
||||
<X size={13} />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 汇总条 */}
|
||||
<div style={{
|
||||
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
|
||||
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
|
||||
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
|
||||
}}>
|
||||
<span>{list.length} 家供应商 · {totalLines} 行采购</span>
|
||||
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{money(total)}</span>
|
||||
</div>
|
||||
|
||||
<ScrollList>
|
||||
{list.length === 0 && (
|
||||
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
|
||||
{filterSO ? '该销售订单暂无涉及供应商' : '无匹配供应商'}
|
||||
</div>
|
||||
)}
|
||||
{list.map(s => {
|
||||
const nc = natureColor(s.性质, tokens);
|
||||
return (
|
||||
<div
|
||||
key={s.供应商编码}
|
||||
onClick={() => onPickSupplier(s.供应商编码)}
|
||||
title="点击只看这家供应商的采购单"
|
||||
style={{
|
||||
marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
|
||||
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
|
||||
transition: 'background .15s, border-color .15s',
|
||||
}}
|
||||
>
|
||||
{/* 行1:简称 + 编码 + 性质 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
|
||||
<Users size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
|
||||
<span style={{ fontSize: 13, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{s.供应商简称}
|
||||
</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.供应商编码}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{
|
||||
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
|
||||
color: nc.c, background: nc.bg, border: `1px solid ${nc.c}44`, whiteSpace: 'nowrap',
|
||||
}}>{s.性质}</span>
|
||||
</div>
|
||||
{/* 行2:类别 + 部门 */}
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textSub, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{s.所属类别}</span>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{s.分管部门 || '分管部门未填'}
|
||||
</span>
|
||||
</div>
|
||||
{/* 行3:金额 + 行数 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
|
||||
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{money(s.采购金额)}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.采购行数} 行采购</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</ScrollList>
|
||||
|
||||
<div style={{
|
||||
display: 'flex', alignItems: 'center', gap: 5, flex: '0 0 auto', paddingTop: 6,
|
||||
fontSize: 10.5, color: tokens.textMuted, borderTop: `1px solid ${tokens.border}`,
|
||||
}}>
|
||||
<span style={{ flex: 1 }}>行数与金额为该供应商在本批采购订单中的合计,与采购单页签同源可核对</span>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
|
||||
const VB_W = 820;
|
||||
const VB_H = 250;
|
||||
const PAD = { l: 46, r: 14, t: 16, b: 26 };
|
||||
|
||||
export interface Series { name: string; color: string; values: number[]; dashed?: boolean }
|
||||
|
||||
/** tooltip 数值:整数不带小数点,小数保留一位 */
|
||||
const fmtTip = (v: number) => (Number.isInteger(v) ? String(v) : v.toFixed(1));
|
||||
|
||||
/** 图例:与 TrendChart 配套,多序列时标出每条线的含义 */
|
||||
export function ChartLegend({ items }: { items: { name: string; color: string; dashed?: boolean }[] }) {
|
||||
const { tokens } = useTheme();
|
||||
return (
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '4px 14px', marginTop: 2 }}>
|
||||
{items.map(it => (
|
||||
<span key={it.name} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: tokens.textMuted }}>
|
||||
<span style={{
|
||||
width: 14, height: 0, borderTop: `2px ${it.dashed ? 'dashed' : 'solid'} ${it.color}`, borderRadius: 1,
|
||||
}} />
|
||||
{it.name}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 折线 + 面积趋势图(viewBox 等比缩放,字号随图放大) */
|
||||
export function TrendChart({
|
||||
series, labels, height = 250, yDigits = 1, marker = 11,
|
||||
}: { series: Series[]; labels: string[]; height?: number; yDigits?: number; marker?: number | null }) {
|
||||
const { tokens } = useTheme();
|
||||
const all = series.flatMap(s => s.values).filter(v => Number.isFinite(v));
|
||||
if (!all.length) {
|
||||
return <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: tokens.textMuted, fontSize: 12 }} />;
|
||||
}
|
||||
let min = Math.min(...all);
|
||||
let max = Math.max(...all);
|
||||
if (min === max) { min -= 1; max += 1; }
|
||||
const pad = (max - min) * 0.14;
|
||||
min -= pad; max += pad;
|
||||
const w = VB_W - PAD.l - PAD.r;
|
||||
const h = VB_H - PAD.t - PAD.b;
|
||||
const n = series[0].values.length;
|
||||
const X = (i: number) => PAD.l + (n === 1 ? w / 2 : (i / (n - 1)) * w);
|
||||
const Y = (v: number) => PAD.t + h - ((v - min) / (max - min)) * h;
|
||||
const ticks = [0, 0.25, 0.5, 0.75, 1].map(f => min + (max - min) * f);
|
||||
const gid = `mec-area-${series.map(s => s.name).join('')}`.replace(/\W/g, '');
|
||||
|
||||
return (
|
||||
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} style={{ width: '100%', height, display: 'block' }} preserveAspectRatio="none">
|
||||
<defs>
|
||||
<linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={series[0].color} stopOpacity="0.24" />
|
||||
<stop offset="100%" stopColor={series[0].color} stopOpacity="0.01" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
{ticks.map((tv, i) => (
|
||||
<g key={i}>
|
||||
<line x1={PAD.l} x2={VB_W - PAD.r} y1={Y(tv)} y2={Y(tv)} stroke={tokens.border} strokeWidth={1} />
|
||||
<text x={PAD.l - 8} y={Y(tv) + 4} textAnchor="end" fontSize={11} fill={tokens.textMuted}>
|
||||
{tv.toFixed(Math.abs(max - min) < 5 ? 2 : yDigits)}
|
||||
</text>
|
||||
</g>
|
||||
))}
|
||||
{labels.map((l, i) => (
|
||||
(i % Math.ceil(n / 12) === 0 || i === n - 1) && (
|
||||
<text key={l} x={X(i)} y={VB_H - 8} textAnchor="middle" fontSize={11} fill={tokens.textMuted}>{l}</text>
|
||||
)
|
||||
))}
|
||||
|
||||
{series.map((s, si) => {
|
||||
const pts = s.values.map((v, i) => `${X(i)},${Y(v)}`).join(' ');
|
||||
return (
|
||||
<g key={s.name}>
|
||||
{si === 0 && !s.dashed && (
|
||||
<polygon points={`${PAD.l},${PAD.t + h} ${pts} ${X(n - 1)},${PAD.t + h}`} fill={`url(#${gid})`} />
|
||||
)}
|
||||
<polyline
|
||||
points={pts} fill="none" stroke={s.color} strokeWidth={s.dashed ? 1.4 : 2.2}
|
||||
strokeLinecap="round" strokeLinejoin="round"
|
||||
strokeDasharray={s.dashed ? '5 4' : undefined} opacity={s.dashed ? 0.75 : 1}
|
||||
className={s.dashed ? undefined : 'trend-line'}
|
||||
/>
|
||||
{!s.dashed && s.values.map((v, i) => (
|
||||
<g key={i}>
|
||||
<circle cx={X(i)} cy={Y(v)} r={i === marker ? 4 : 2.2} fill={s.color} className="trend-dot" />
|
||||
{/* 透明大命中区 + 原生 tooltip:鼠标停在点上能看到具体数值 */}
|
||||
<circle cx={X(i)} cy={Y(v)} r={9} fill="transparent">
|
||||
<title>{`${labels[i] ?? ''} · ${s.name}:${fmtTip(v)}`}</title>
|
||||
</circle>
|
||||
</g>
|
||||
))}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{marker !== null && marker >= 0 && series[0] && series[0].values[marker] !== undefined && (
|
||||
<line x1={X(marker)} x2={X(marker)} y1={PAD.t} y2={PAD.t + h} stroke={series[0].color} strokeWidth={1} opacity={0.3} strokeDasharray="3 3" />
|
||||
)}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
/** 横向条形(结构拆解);fill 时随卡片高度均摊剩余空间 */
|
||||
export function HBarChart({
|
||||
items, height, valueSuffix = '', fill,
|
||||
}: { items: { label: string; value: number; color?: string; sub?: string; display?: string; displayColor?: string }[];
|
||||
height?: number; valueSuffix?: string; fill?: boolean }) {
|
||||
const { tokens } = useTheme();
|
||||
const max = Math.max(...items.map(i => Math.abs(i.value)), 1);
|
||||
return (
|
||||
/* 高度由条数撑开(height 只当下限):写死高度 + space-between 会让多出来的条目
|
||||
溢出到卡片背景之外,视觉上就是「条形跑到底色外面」 */
|
||||
<div style={{
|
||||
display: 'flex', flexDirection: 'column', gap: 5,
|
||||
...(fill ? { flex: 1, minHeight: 0 } : { minHeight: height }),
|
||||
}}>
|
||||
{items.map((it, idx) => (
|
||||
<div key={it.label} style={{ display: 'flex', alignItems: 'center', gap: 8, minHeight: 22, animationDelay: `${idx * 40}ms`, ...(fill ? { flex: '1 1 auto' } : {}) }} className="card-in">
|
||||
<span style={{ width: 108, flex: '0 0 108px', fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>
|
||||
<div style={{ flex: 1, height: 14, borderRadius: 4, background: tokens.accentBg, position: 'relative', overflow: 'hidden' }}>
|
||||
<div style={{
|
||||
position: 'absolute', left: 0, top: 0, bottom: 0, width: `${(Math.abs(it.value) / max) * 100}%`,
|
||||
background: `linear-gradient(90deg, ${it.color ?? tokens.accent}, ${(it.color ?? tokens.accent)}99)`,
|
||||
borderRadius: 4, transition: 'width 0.5s cubic-bezier(0.4,0,0.2,1)',
|
||||
}} />
|
||||
</div>
|
||||
{/* 数值 + 副指标同列两行、各自不换行:原方案把两者塞进 84px 一行,
|
||||
「需求 / 已采」会折成三行顶爆行高,条形就跑到卡片底色外面 */}
|
||||
<span style={{ width: 122, flex: '0 0 122px', display: 'flex', flexDirection: 'column', alignItems: 'flex-end', minWidth: 0 }}>
|
||||
<span style={{ fontSize: 11.5, fontWeight: 700, color: it.displayColor ?? tokens.text, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>
|
||||
{it.display ?? `${it.value.toFixed(1)}${valueSuffix}`}
|
||||
</span>
|
||||
{it.sub && <span style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{it.sub}</span>}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 环形占比图:类别只有两三个时,横条会把卡片撑出一大片空白;
|
||||
* 饼图 + 右侧图例能占满整块区域,中心位给合计值。
|
||||
*/
|
||||
export function DonutChart({
|
||||
items, size = 172, centerValue, centerLabel,
|
||||
}: {
|
||||
items: { label: string; value: number; color?: string; display?: string; sub?: string }[];
|
||||
size?: number; centerValue: string; centerLabel: string;
|
||||
}) {
|
||||
const { tokens } = useTheme();
|
||||
const palette = [tokens.chartLine1, tokens.chartLine3, tokens.chartLine2, tokens.info, tokens.danger, tokens.warning];
|
||||
const total = items.reduce((s, i) => s + Math.abs(i.value), 0);
|
||||
const MID = 60, R = 45, SW = 19, C = 2 * Math.PI * R;
|
||||
let acc = 0;
|
||||
return (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 18, flex: 1, minHeight: 0 }}>
|
||||
<svg viewBox="0 0 120 120" style={{ width: size, height: size, flex: '0 0 auto' }}>
|
||||
<circle cx={MID} cy={MID} r={R} fill="none" stroke={tokens.accentBg} strokeWidth={SW} />
|
||||
{total > 0 && items.map((it, i) => {
|
||||
const frac = Math.abs(it.value) / total;
|
||||
/* 多切片之间留 2 单位缝,避免两色相接读成一块 */
|
||||
const dash = Math.max(frac * C - (items.length > 1 ? 2 : 0), 0.6);
|
||||
const start = acc;
|
||||
acc += frac;
|
||||
const col = it.color ?? palette[i % palette.length];
|
||||
return (
|
||||
<circle key={it.label} cx={MID} cy={MID} r={R} fill="none" stroke={col} strokeWidth={SW}
|
||||
strokeDasharray={`${dash} ${C - dash}`} strokeDashoffset={-start * C}
|
||||
transform={`rotate(-90 ${MID} ${MID})`}>
|
||||
<title>{`${it.label}:${it.display ?? fmtTip(it.value)}(${(frac * 100).toFixed(1)}%)`}</title>
|
||||
</circle>
|
||||
);
|
||||
})}
|
||||
<text x={MID} y={MID - 1} textAnchor="middle" fontSize={15} fontWeight={800} fill={tokens.text} style={{ fontVariantNumeric: 'tabular-nums' }}>{centerValue}</text>
|
||||
<text x={MID} y={MID + 13} textAnchor="middle" fontSize={8} fill={tokens.textMuted}>{centerLabel}</text>
|
||||
</svg>
|
||||
|
||||
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10, justifyContent: 'center' }}>
|
||||
{items.map((it, i) => {
|
||||
const frac = total > 0 ? Math.abs(it.value) / total : 0;
|
||||
const col = it.color ?? palette[i % palette.length];
|
||||
return (
|
||||
<div key={it.label}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
<span style={{ width: 9, height: 9, borderRadius: 3, background: col, flex: '0 0 9px' }} />
|
||||
<span style={{ fontSize: 12, color: tokens.text, flex: '0 1 auto', minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.label}</span>
|
||||
<span style={{ flex: '1 1 auto', height: 1, background: tokens.border, minWidth: 8 }} />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{it.display ?? fmtTip(it.value)}</span>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, width: 44, textAlign: 'right', fontVariantNumeric: 'tabular-nums', flex: '0 0 44px' }}>{(frac * 100).toFixed(1)}%</span>
|
||||
</div>
|
||||
{it.sub && <div style={{ fontSize: 10.5, color: tokens.textMuted, paddingLeft: 17, marginTop: 2 }}>{it.sub}</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 竖向柱(区域/产品线对比),支持双指标 */
|
||||
export function VBarChart({
|
||||
groups, labels, colors, names, height = 220, unit = '',
|
||||
}: {
|
||||
groups: number[][]; labels: string[]; colors: string[]; names: string[]; height?: number; unit?: string;
|
||||
}) {
|
||||
const { tokens } = useTheme();
|
||||
/* viewBox 高度跟着像素高度走(1 单位 = 1px):这张图用 preserveAspectRatio="none" 铺满卡片宽度,
|
||||
若 H 固定 240 而样式高度给到 330,柱子和文字会被纵向拉扁 */
|
||||
const W = 520, H = Math.max(height, 160), P = { l: 40, r: 12, t: 18, b: 30 };
|
||||
const w = W - P.l - P.r, h = H - P.t - P.b;
|
||||
const max = Math.max(...groups.flat().filter(Number.isFinite), 1) * 1.16;
|
||||
const gw = w / labels.length;
|
||||
const bw = Math.min(22, (gw - 12) / groups.length);
|
||||
return (
|
||||
<div>
|
||||
<svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block' }} preserveAspectRatio="none">
|
||||
{[0, 0.5, 1].map(f => (
|
||||
<g key={f}>
|
||||
<line x1={P.l} x2={W - P.r} y1={P.t + h * (1 - f)} y2={P.t + h * (1 - f)} stroke={tokens.border} />
|
||||
<text x={P.l - 6} y={P.t + h * (1 - f) + 4} textAnchor="end" fontSize={10} fill={tokens.textMuted}>{(max * f).toFixed(0)}</text>
|
||||
</g>
|
||||
))}
|
||||
{labels.map((l, i) => (
|
||||
<g key={l}>
|
||||
{groups.map((g, gi) => {
|
||||
const v = g[i] ?? 0;
|
||||
const bh = (v / max) * h;
|
||||
const x = P.l + gw * i + gw / 2 - (groups.length * bw) / 2 + gi * bw;
|
||||
return (
|
||||
<g key={gi}>
|
||||
<rect x={x} y={P.t + h - bh} width={bw - 3} height={Math.max(bh, 1)} rx={2} fill={colors[gi]} opacity={0.9} />
|
||||
<text x={x + (bw - 3) / 2} y={P.t + h - bh - 4} textAnchor="middle" fontSize={9.5} fill={tokens.textSub}>{v.toFixed(1)}</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
<text x={P.l + gw * i + gw / 2} y={H - 10} textAnchor="middle" fontSize={11} fill={tokens.textSub}>{l}</text>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
<div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 2 }}>
|
||||
{names.map((n, i) => (
|
||||
<span key={n} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: tokens.textMuted }}>
|
||||
<span style={{ width: 9, height: 9, borderRadius: 2, background: colors[i] }} />{n}{unit ? `(${unit})` : ''}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 雷达图:八维健康度 */
|
||||
export function RadarChart({
|
||||
axes, values, maxValue = 100, height = 260, compare,
|
||||
}: { axes: string[]; values: number[]; maxValue?: number; height?: number; compare?: number[] }) {
|
||||
const { tokens } = useTheme();
|
||||
const S = 320, C = S / 2, R = 108;
|
||||
const pt = (i: number, v: number) => {
|
||||
const a = -Math.PI / 2 + (i / axes.length) * Math.PI * 2;
|
||||
const r = (Math.max(0, Math.min(v, maxValue)) / maxValue) * R;
|
||||
return { x: C + r * Math.cos(a), y: C + r * Math.sin(a), a };
|
||||
};
|
||||
const poly = (arr: number[]) => arr.map((v, i) => { const p = pt(i, v); return `${p.x},${p.y}`; }).join(' ');
|
||||
return (
|
||||
<svg viewBox={`0 0 ${S} ${S + 18}`} style={{ width: '100%', height, display: 'block' }}>
|
||||
{[0.25, 0.5, 0.75, 1].map(f => (
|
||||
<polygon
|
||||
key={f}
|
||||
points={axes.map((_, i) => { const p = pt(i, maxValue * f); return `${p.x},${p.y}`; }).join(' ')}
|
||||
fill="none" stroke={tokens.border}
|
||||
/>
|
||||
))}
|
||||
{axes.map((label, i) => {
|
||||
const p = pt(i, maxValue);
|
||||
const outer = pt(i, maxValue * 1.24);
|
||||
return (
|
||||
<g key={label}>
|
||||
<line x1={C} y1={C} x2={p.x} y2={p.y} stroke={tokens.border} />
|
||||
<text
|
||||
x={outer.x} y={outer.y + 3} fontSize={11} fill={tokens.textSub}
|
||||
textAnchor={outer.x > C + 6 ? 'start' : outer.x < C - 6 ? 'end' : 'middle'}
|
||||
>{label}</text>
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
{compare && <polygon points={poly(compare)} fill={tokens.info} fillOpacity={0.08} stroke={tokens.info} strokeWidth={1.2} strokeDasharray="4 3" />}
|
||||
<polygon points={poly(values)} fill={tokens.accent} fillOpacity={0.16} stroke={tokens.accent} strokeWidth={2} />
|
||||
{values.map((v, i) => { const p = pt(i, v); return <circle key={i} cx={p.x} cy={p.y} r={3} fill={tokens.accent} />; })}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 风险矩阵散点:X = 概率(0-1),Y = 影响(万元,按当期最大值自适应定标)。
|
||||
* 早先把「影响万元」当成 0-1 比例直接乘进坐标,金额超过 1 万的点全部飞出顶边被裁掉,
|
||||
* 现在按 yMax 定标并给四周一圈内缩,点不会再压到图表边界。
|
||||
*/
|
||||
export function RiskMatrix({
|
||||
items, height = 300, fill = false,
|
||||
}: { items: { label: string; x: number; y: number; status: string; color: string }[]; height?: number; fill?: boolean }) {
|
||||
const { tokens } = useTheme();
|
||||
const S = 360, P = 34, R = 9, INSET = 15;
|
||||
const w = S - P * 2;
|
||||
const span = w - INSET * 2;
|
||||
const yMax = Math.max(...items.map(i => i.y), 0);
|
||||
const yDom = (yMax || 1) * 1.18;
|
||||
const X = (v: number) => P + INSET + Math.max(0, Math.min(1, v)) * span;
|
||||
const Y = (v: number) => S - P - INSET - (Math.max(0, v) / yDom) * span;
|
||||
/* 点一多标签就糊成一片:只给影响最大的 3 单挂订单号,其余靠悬停与右侧清单 */
|
||||
const labeled = new Set([...items].sort((a, b) => b.y - a.y).slice(0, 3).map(i => i.label));
|
||||
return (
|
||||
/* fill:高度交给外层卡片(配合 stretch 让左右两张卡底边对齐),方形画布按 meet 居中缩放,
|
||||
不拉伸坐标轴;非 fill 时保持固定像素高度 */
|
||||
<svg
|
||||
viewBox={`0 0 ${S} ${S}`}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
style={{
|
||||
width: '100%', height: fill ? '100%' : height, display: 'block',
|
||||
maxWidth: fill ? 560 : 420, margin: '0 auto', minHeight: 0,
|
||||
}}
|
||||
>
|
||||
<rect x={P} y={P} width={w / 2} height={w / 2} fill={tokens.warning} opacity={0.07} />
|
||||
<rect x={P + w / 2} y={P} width={w / 2} height={w / 2} fill={tokens.danger} opacity={0.1} />
|
||||
<rect x={P} y={P + w / 2} width={w / 2} height={w / 2} fill={tokens.info} opacity={0.06} />
|
||||
<rect x={P + w / 2} y={P + w / 2} width={w / 2} height={w / 2} fill={tokens.warning} opacity={0.07} />
|
||||
<line x1={P} x2={S - P} y1={S - P} y2={S - P} stroke={tokens.border} />
|
||||
<line x1={P} x2={P} y1={P} y2={S - P} stroke={tokens.border} />
|
||||
<text x={S - P} y={S - 8} textAnchor="end" fontSize={11} fill={tokens.textMuted}>概率 →</text>
|
||||
<text x={8} y={P - 10} fontSize={11} fill={tokens.textMuted}>↑ 影响</text>
|
||||
{/* 轴刻度:按 Y() 真实像素定位,避免把内缩边当成 0 / 最大值 */}
|
||||
{[0, 0.5, 1].map(f => (
|
||||
<text key={f} x={P - 5} y={Y(yMax * f) + 3} textAnchor="end" fontSize={9.5} fill={tokens.textMuted}>{(yMax * f).toFixed(1)}</text>
|
||||
))}
|
||||
{[0, 0.5, 1].map(f => (
|
||||
<text key={f} x={P + INSET + f * span} y={S - P + 12} textAnchor="middle" fontSize={9.5} fill={tokens.textMuted}>{`${f * 100}%`}</text>
|
||||
))}
|
||||
{items.map(it => {
|
||||
const cx = X(it.x), cy = Y(it.y), left = cx > S / 2;
|
||||
return (
|
||||
<g key={it.label}>
|
||||
<circle cx={cx} cy={cy} r={R} fill={it.color} opacity={0.85}>
|
||||
<title>{`${it.label} · ${it.status}:概率 ${(it.x * 100).toFixed(0)}% / 影响 ${it.y.toFixed(1)} 万元`}</title>
|
||||
</circle>
|
||||
{labeled.has(it.label) && (
|
||||
<text x={left ? cx - 13 : cx + 13} y={cy + 4} textAnchor={left ? 'end' : 'start'} fontSize={10} fill={tokens.textSub}>{it.label}</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
})}
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import { useTheme } from '../../context/ThemeContext';
|
||||
import type { MetricNode, MetricLink } from '../../data/sqlite';
|
||||
import {
|
||||
fulfillmentSummary, monthlyFulfillment, customerSummaries, productSummaries,
|
||||
materialGaps, poStatusSummary, riskScatter, topRisks, shipmentTrend, windowFulfillment,
|
||||
type OrderRisk,
|
||||
} from '../../data/fulfillmentMetrics';
|
||||
import { isCurrentPeriod, periodLabel } from '../../lib/time';
|
||||
import { money, moneyW } from '../../lib/money';
|
||||
import { ChartLegend, DonutChart, HBarChart, RiskMatrix, TrendChart, VBarChart } from './charts';
|
||||
|
||||
export interface ViewProps {
|
||||
selected: string;
|
||||
byCode: Map<string, MetricNode>;
|
||||
flat: MetricNode[];
|
||||
links: MetricLink[];
|
||||
onSelect: (code: string) => void;
|
||||
/** 全局回放游标(0-11):六个页签按此时点取该期账本 */
|
||||
period: number;
|
||||
}
|
||||
|
||||
/** 期别标签:当期标「当期快照」,历史期标「回放 · YYYY-MM」,避免把历史月误读成实时数 */
|
||||
function PeriodTag({ period }: { period: number }) {
|
||||
const { tokens } = useTheme();
|
||||
const cur = isCurrentPeriod(period);
|
||||
const col = cur ? tokens.textMuted : tokens.warning;
|
||||
return (
|
||||
<span style={{
|
||||
fontSize: 10.5, color: col, background: cur ? tokens.tableHeaderBg : `${tokens.warning}14`,
|
||||
border: `1px solid ${cur ? tokens.border : `${tokens.warning}44`}`,
|
||||
borderRadius: 5, padding: '1px 6px', whiteSpace: 'nowrap',
|
||||
}}>{cur ? '当期快照' : `回放 · ${periodLabel(period)}`}</span>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ title, right, children, tone, fill }: { title: string; right?: ReactNode; children: ReactNode; tone?: string; fill?: boolean }) {
|
||||
const { tokens } = useTheme();
|
||||
return (
|
||||
<div className="card-in" style={{
|
||||
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 11,
|
||||
padding: '10px 13px 12px', boxShadow: tokens.cardShadow, minWidth: 0,
|
||||
...(fill ? { display: 'flex', flexDirection: 'column' as const } : {}),
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flex: '0 0 auto' }}>
|
||||
<span style={{ width: 3, height: 13, borderRadius: 2, background: tone ?? tokens.accent }} />
|
||||
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text }}>{title}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
{right}
|
||||
</div>
|
||||
{/* fill:让内容吃掉卡片剩余高度,配合网格 stretch 才能填满整块区域 */}
|
||||
{fill ? <div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>{children}</div> : children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Th({ children, right, lg }: { children: ReactNode; right?: boolean; lg?: boolean }) {
|
||||
const { tokens } = useTheme();
|
||||
return (
|
||||
<th style={{
|
||||
textAlign: right ? 'right' : 'left', padding: lg ? '8px 10px' : '6px 8px', fontSize: lg ? 12.5 : 11, fontWeight: 600,
|
||||
color: tokens.textSub, background: tokens.tableHeaderBg, whiteSpace: 'nowrap',
|
||||
borderBottom: `1px solid ${tokens.border}`,
|
||||
}}>{children}</th>
|
||||
);
|
||||
}
|
||||
function Td({ children, right, mono, color, lg }: { children: ReactNode; right?: boolean; mono?: boolean; color?: string; lg?: boolean }) {
|
||||
const { tokens } = useTheme();
|
||||
return (
|
||||
<td style={{
|
||||
textAlign: right ? 'right' : 'left', padding: lg ? '8px 10px' : '5px 8px', fontSize: lg ? 13 : 11.5,
|
||||
color: color ?? tokens.textSub, borderBottom: `1px solid ${tokens.borderSub}`,
|
||||
fontVariantNumeric: mono ? 'tabular-nums' : undefined,
|
||||
fontFamily: mono ? 'ui-monospace, monospace' : undefined, whiteSpace: 'nowrap',
|
||||
}}>{children}</td>
|
||||
);
|
||||
}
|
||||
|
||||
/* ══════════════════ 1. 指标明细 → 履约台账 ══════════════════ */
|
||||
export function DetailView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const summary = useMemo(() => fulfillmentSummary(period), [period]);
|
||||
const risks = useMemo(() => topRisks(50, period), [period]);
|
||||
const [sortBy, setSortBy] = useState<'risk' | 'amount' | 'date'>('risk');
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
const arr = [...risks];
|
||||
if (sortBy === 'amount') arr.sort((a, b) => b.so.含税金额 - a.so.含税金额);
|
||||
else if (sortBy === 'date') arr.sort((a, b) => a.so.预计发货日期.localeCompare(b.so.预计发货日期));
|
||||
return arr;
|
||||
}, [risks, sortBy]);
|
||||
|
||||
const levelDot = (level: OrderRisk['level']) =>
|
||||
level === 'red' ? tokens.danger : level === 'yellow' ? tokens.warning : tokens.success;
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12,
|
||||
}}>
|
||||
{[
|
||||
{ k: '订单总数', v: summary.totalOrders, sub: '张销售订单', color: tokens.accent },
|
||||
{ k: '订单金额', v: moneyW(summary.totalAmount), sub: '含税金额', color: tokens.accent },
|
||||
{ k: '红色风险', v: summary.redOrders, sub: '确定延期', color: tokens.danger },
|
||||
{ k: '黄色风险', v: summary.yellowOrders, sub: '有延迟可能', color: tokens.warning },
|
||||
].map(b => (
|
||||
<div key={b.k} style={{ padding: '12px 14px', borderRadius: 11, background: tokens.cardBg, border: `1px solid ${tokens.border}` }}>
|
||||
<div style={{ fontSize: 11.5, color: tokens.textMuted }}>{b.k}</div>
|
||||
<div style={{ fontSize: 24, fontWeight: 800, color: b.color, fontVariantNumeric: 'tabular-nums', lineHeight: 1.2 }}>{b.v}</div>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted }}>{b.sub}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card title={`履约风险台账 · ${risks.length}`} right={
|
||||
<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
|
||||
<PeriodTag period={period} />
|
||||
{(['risk', 'amount', 'date'] as const).map(k => (
|
||||
<button
|
||||
key={k}
|
||||
onClick={() => setSortBy(k)}
|
||||
className="ghost-btn"
|
||||
style={{
|
||||
fontSize: 11, padding: '2px 8px', borderRadius: 6, cursor: 'pointer',
|
||||
background: sortBy === k ? tokens.accentBg : 'transparent',
|
||||
color: sortBy === k ? tokens.accent : tokens.textSub,
|
||||
border: `1px solid ${sortBy === k ? tokens.borderAccent : tokens.border}`,
|
||||
}}
|
||||
>
|
||||
{k === 'risk' ? '按风险' : k === 'amount' ? '按金额' : '按交期'}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>销售订单</Th><Th>客户</Th><Th>产品编码</Th>
|
||||
<Th right>数量</Th><Th right>金额</Th><Th>预计发货</Th>
|
||||
<Th right>风险分</Th><Th>风险等级</Th><Th>触发原因</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{sorted.map((r, i) => (
|
||||
<tr key={r.so.销售订单号} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
|
||||
<Td mono>{r.so.销售订单号}</Td>
|
||||
<Td>{r.so.客户简称}</Td>
|
||||
<Td mono>{r.so.产品编码}</Td>
|
||||
<Td right mono>{r.so.数量.toLocaleString()}</Td>
|
||||
<Td right mono>{money(r.so.含税金额)}</Td>
|
||||
<Td mono>{r.so.预计发货日期}</Td>
|
||||
<Td right mono><span style={{ color: levelDot(r.level), fontWeight: 700 }}>{r.score}</span></Td>
|
||||
<Td>
|
||||
<span style={{
|
||||
fontSize: 11, padding: '1px 6px', borderRadius: 6, fontWeight: 700,
|
||||
background: `${levelDot(r.level)}1f`, color: levelDot(r.level),
|
||||
}}>
|
||||
{r.level === 'red' ? '红' : r.level === 'yellow' ? '黄' : '绿'}
|
||||
</span>
|
||||
</Td>
|
||||
<Td>
|
||||
<span style={{ display: 'block', maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.fired.join(' · ') || '—'}
|
||||
</span>
|
||||
</Td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ══════════════════ 2. 趋势分析 → 交期与风险趋势 ══════════════════ */
|
||||
export function TrendView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const win = useMemo(() => windowFulfillment(), []);
|
||||
const labels = win.map(w => `${Number(w.month.slice(5, 7))}月`);
|
||||
/** 该期账本内部按发货月的分布:历史月单据的发货日会跨到次月,这里如实展开 */
|
||||
const months = useMemo(() => monthlyFulfillment(period), [period]);
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<Card title="回放窗口 · 12 期订单量与异常量" right={<PeriodTag period={period} />}>
|
||||
<TrendChart
|
||||
height={220}
|
||||
yDigits={0}
|
||||
marker={period}
|
||||
labels={labels}
|
||||
series={[
|
||||
{ name: '销售订单数', color: tokens.accent, values: win.map(w => w.orderCount) },
|
||||
{ name: '异常订单数', color: tokens.danger, values: win.map(w => w.riskCount) },
|
||||
{ name: '其中确定延期', color: tokens.warning, values: win.map(w => w.redCount), dashed: true },
|
||||
]}
|
||||
/>
|
||||
<ChartLegend items={[
|
||||
{ name: '销售订单数(张)', color: tokens.accent },
|
||||
{ name: '异常订单数(红+黄,张)', color: tokens.danger },
|
||||
{ name: '其中确定延期(红,张)', color: tokens.warning, dashed: true },
|
||||
]} />
|
||||
</Card>
|
||||
|
||||
{/* 同风险矩阵/区域对比:stretch 让两张卡底边对齐,矮的一侧撑开而不是留白 */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<Card title="该期发货月分布" right={<PeriodTag period={period} />} fill>
|
||||
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
||||
<VBarChart
|
||||
height={330}
|
||||
labels={months.map(m => m.month)}
|
||||
groups={[
|
||||
months.map(m => m.orderCount),
|
||||
months.map(m => m.redCount + m.yellowCount),
|
||||
]}
|
||||
colors={[tokens.accent, tokens.danger]}
|
||||
names={['订单数', '异常订单数']}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
|
||||
<Card title="逐期履约明细" right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>游标行为当前回放期</span>} fill>
|
||||
<table style={{ width: '100%', height: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>期间</Th><Th right>订单数</Th><Th right>订单金额</Th>
|
||||
<Th right>红</Th><Th right>黄</Th><Th right>绿</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{win.map((m, i) => {
|
||||
const on = i === period;
|
||||
return (
|
||||
<tr key={m.month} style={{
|
||||
background: on ? tokens.accentBg : i % 2 ? tokens.tableRowAlt : 'transparent',
|
||||
fontWeight: on ? 700 : 400,
|
||||
}}>
|
||||
<Td mono color={on ? tokens.accent : undefined}>{m.month}</Td>
|
||||
<Td right mono>{m.orderCount}</Td>
|
||||
<Td right mono>{moneyW(m.amount)}</Td>
|
||||
<Td right mono color={tokens.danger}>{m.redCount}</Td>
|
||||
<Td right mono color={tokens.warning}>{m.yellowCount}</Td>
|
||||
<Td right mono color={tokens.success}>{m.greenCount}</Td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ══════════════════ 3. 结构动因 → 履约动因 ══════════════════ */
|
||||
export function StructureView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const customers = useMemo(() => customerSummaries(period), [period]);
|
||||
const products = useMemo(() => productSummaries(period), [period]);
|
||||
const gaps = useMemo(() => materialGaps(period).filter(g => g.gap > 0).slice(0, 12), [period]);
|
||||
|
||||
const categoryMap = new Map<string, { name: string; amount: number; orders: number; red: number; yellow: number }>();
|
||||
customers.forEach(c => {
|
||||
const prev = categoryMap.get(c.category) ?? { name: c.category, amount: 0, orders: 0, red: 0, yellow: 0 };
|
||||
prev.amount += c.amount;
|
||||
prev.orders += c.orderCount;
|
||||
prev.red += c.redCount;
|
||||
prev.yellow += c.yellowCount;
|
||||
categoryMap.set(c.category, prev);
|
||||
});
|
||||
const categories = [...categoryMap.values()].sort((a, b) => b.amount - a.amount);
|
||||
const categoryTotal = categories.reduce((s, c) => s + c.amount, 0);
|
||||
|
||||
return (
|
||||
/* 行高取同行较高那张(stretch),四张卡都开 fill,避免出现大片空白 */
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<Card title="客户分类结构" right={<PeriodTag period={period} />} fill>
|
||||
<DonutChart
|
||||
items={categories.map(c => ({
|
||||
label: c.name,
|
||||
value: c.amount,
|
||||
display: moneyW(c.amount),
|
||||
sub: `${c.orders} 单 · ${c.red} 红 / ${c.yellow} 黄`,
|
||||
}))}
|
||||
centerValue={moneyW(categoryTotal)}
|
||||
centerLabel="订单金额合计"
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="产品结构" right={<PeriodTag period={period} />} fill>
|
||||
<HBarChart
|
||||
fill
|
||||
items={products.slice(0, 8).map(p => ({
|
||||
label: p.code,
|
||||
value: p.amount,
|
||||
color: p.redCount > 0 ? tokens.danger : p.yellowCount > 0 ? tokens.warning : tokens.success,
|
||||
sub: `${p.orderCount} 单`,
|
||||
}))}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="物料缺口 Top" right={<PeriodTag period={period} />} fill>
|
||||
<HBarChart
|
||||
fill
|
||||
items={gaps.map(g => ({
|
||||
label: g.code,
|
||||
value: g.gap,
|
||||
color: tokens.danger,
|
||||
sub: `需求 ${g.demand.toFixed(0)} / 已采 ${g.supplied.toFixed(0)}`,
|
||||
}))}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Card title="客户风险分布" right={<PeriodTag period={period} />} fill>
|
||||
{/* 表格 height:100% 由浏览器把多余高度摊到行上,与左侧条形卡对齐 */}
|
||||
<table style={{ width: '100%', height: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>客户</Th><Th>分类</Th><Th right>订单数</Th>
|
||||
<Th right>金额</Th><Th right>红</Th><Th right>黄</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{customers.slice(0, 10).map((c, i) => (
|
||||
<tr key={c.code} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
|
||||
<Td>{c.name}</Td>
|
||||
<Td>{c.category}</Td>
|
||||
<Td right mono>{c.orderCount}</Td>
|
||||
<Td right mono>{moneyW(c.amount)}</Td>
|
||||
<Td right mono color={tokens.danger}>{c.redCount}</Td>
|
||||
<Td right mono color={tokens.warning}>{c.yellowCount}</Td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
/* ══════════════════ 4. 区域对比 → 客户对比 ══════════════════ */
|
||||
export function RegionView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const rows = useMemo(() => customerSummaries(period), [period]);
|
||||
const labels = rows.map(r => r.name);
|
||||
|
||||
return (
|
||||
/* 与风险矩阵同一处理:stretch 让两张卡等高、底边对齐,矮的一侧内容撑开而不是留白 */
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1.1fr 1fr', gap: 12 }}>
|
||||
<Card title="客户订单金额" right={<PeriodTag period={period} />} fill>
|
||||
{/* 柱状图有固定像素高度,不会被 flex 压扁;这里只在它成为矮的一侧时居中 */}
|
||||
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
|
||||
<VBarChart
|
||||
height={250}
|
||||
labels={labels}
|
||||
groups={[rows.map(r => r.amount / 10000), rows.map(r => r.redCount + r.yellowCount)]}
|
||||
colors={[tokens.accent, tokens.danger]}
|
||||
names={['金额(万元)', '风险单数']}
|
||||
/>
|
||||
</div>
|
||||
</Card>
|
||||
<Card title={`客户履约明细 · ${rows.length}`} fill>
|
||||
<table style={{ width: '100%', height: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>客户</Th><Th>分类</Th><Th right>订单数</Th>
|
||||
<Th right>金额</Th><Th right>红</Th><Th right>黄</Th><Th right>绿</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => (
|
||||
<tr key={r.code} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
|
||||
<Td><span style={{ color: tokens.text }}>{r.name}</span></Td>
|
||||
<Td>{r.category}</Td>
|
||||
<Td right mono>{r.orderCount}</Td>
|
||||
<Td right mono>{moneyW(r.amount)}</Td>
|
||||
<Td right mono color={tokens.danger}>{r.redCount}</Td>
|
||||
<Td right mono color={tokens.warning}>{r.yellowCount}</Td>
|
||||
<Td right mono color={tokens.success}>{r.greenCount}</Td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ══════════════════ 5. 风险矩阵 → 订单风险矩阵 ══════════════════ */
|
||||
export function RiskView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const rows = useMemo(() => riskScatter(period), [period]);
|
||||
const items = rows.map(r => ({
|
||||
label: r.soNo,
|
||||
x: r.probability,
|
||||
y: r.impactWan,
|
||||
status: r.level === 'red' ? '确定延期' : r.level === 'yellow' ? '有延迟风险' : '正常',
|
||||
color: r.tone === 'danger' ? tokens.danger : r.tone === 'warning' ? tokens.warning : tokens.success,
|
||||
}));
|
||||
|
||||
return (
|
||||
/* stretch(默认)让两张卡等高:右侧清单有几行、左侧矩阵就撑到多高,底边自然对齐;
|
||||
用 alignItems:'start' 时左卡只有矩阵那点高,右边一长就把左边甩在半空 */
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1.15fr', gap: 12 }}>
|
||||
<Card title="订单风险矩阵" right={<PeriodTag period={period} />} fill>
|
||||
{/* minHeight 兜住清单很短的情况,矩阵不会被压扁;超出部分由 flex:1 吃掉 */}
|
||||
<div style={{ flex: 1, minHeight: 330, display: 'flex', flexDirection: 'column' }}>
|
||||
{items.length > 0 && <RiskMatrix items={items} fill />}
|
||||
</div>
|
||||
</Card>
|
||||
<Card title={`风险订单清单 · ${rows.length}`}>
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>销售订单</Th><Th>客户</Th><Th right>概率</Th>
|
||||
<Th right>影响(万元)</Th><Th>等级</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
{rows.map((r, i) => {
|
||||
const col = r.tone === 'danger' ? tokens.danger : r.tone === 'warning' ? tokens.warning : tokens.success;
|
||||
return (
|
||||
<tr key={r.soNo} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
|
||||
<Td mono>{r.soNo}</Td>
|
||||
<Td>{r.customer}</Td>
|
||||
<Td right mono>{(r.probability * 100).toFixed(0)}%</Td>
|
||||
<Td right mono>{r.impactWan.toFixed(1)}</Td>
|
||||
<Td>
|
||||
<span style={{
|
||||
fontSize: 11, padding: '1px 6px', borderRadius: 6, fontWeight: 700,
|
||||
background: `${col}1f`, color: col,
|
||||
}}>
|
||||
{r.level === 'red' ? '红' : r.level === 'yellow' ? '黄' : '绿'}
|
||||
</span>
|
||||
</Td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ══════════════════ 6. 全景驾驶舱 → 履约驾驶舱 ══════════════════ */
|
||||
export function CockpitView({ period }: ViewProps) {
|
||||
const { tokens } = useTheme();
|
||||
const summary = useMemo(() => fulfillmentSummary(period), [period]);
|
||||
const risks = useMemo(() => topRisks(6, period), [period]);
|
||||
const points = useMemo(() => shipmentTrend(period), [period]);
|
||||
const po = useMemo(() => poStatusSummary(period), [period]);
|
||||
/* 12 期窗口带游标:拖动时间轴时这条线是唯一能同时看到「历史 + 我在哪」的图 */
|
||||
const win = useMemo(() => windowFulfillment(), []);
|
||||
const last = points[points.length - 1];
|
||||
|
||||
const kpiCards = [
|
||||
{ label: '销售订单', value: summary.totalOrders, sub: '张', color: tokens.accent },
|
||||
{ label: '订单金额', value: moneyW(summary.totalAmount), sub: '', color: tokens.accent },
|
||||
{ label: '确定延期', value: summary.delayedOrders, sub: '张', color: tokens.danger },
|
||||
{ label: '风险敞口', value: moneyW(summary.atRiskAmount), sub: '', color: tokens.warning },
|
||||
{ label: '未审批采购', value: summary.unapprovedPoLines, sub: '行', color: tokens.danger },
|
||||
{ label: '物料缺口种数', value: summary.materialShortCount, sub: '种', color: tokens.warning },
|
||||
];
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
{/* 6 张卡固定等分一行:auto-fill 在窄窗口会折成 5+1,读数节奏被打断 */}
|
||||
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0, 1fr))', gap: 10 }}>
|
||||
{kpiCards.map((k, i) => (
|
||||
<div
|
||||
key={k.label}
|
||||
style={{
|
||||
padding: '12px 14px', borderRadius: 11, background: tokens.cardBg,
|
||||
border: `1px solid ${tokens.border}`, animationDelay: `${i * 18}ms`,
|
||||
}}
|
||||
>
|
||||
<div style={{ fontSize: 11, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{k.label}</div>
|
||||
{/* 量词跟着数字走同一行(基线对齐),不再单独占一行把卡片拉高 */}
|
||||
<div style={{ display: 'flex', alignItems: 'baseline', gap: 3, marginTop: 3, whiteSpace: 'nowrap' }}>
|
||||
<span style={{
|
||||
fontSize: 'clamp(18px, 1.5vw, 22px)', fontWeight: 800, color: k.color, fontVariantNumeric: 'tabular-nums',
|
||||
lineHeight: 1.25, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis',
|
||||
}}>
|
||||
{k.value}
|
||||
</span>
|
||||
{k.sub && <span style={{ fontSize: 11, color: tokens.textMuted, flex: '0 0 auto' }}>{k.sub}</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Card
|
||||
title="回放窗口 · 近 12 期订单量与异常量"
|
||||
right={<PeriodTag period={period} />}
|
||||
>
|
||||
<TrendChart
|
||||
height={168}
|
||||
yDigits={0}
|
||||
marker={period}
|
||||
labels={win.map(w => `${Number(w.month.slice(5, 7))}月`)}
|
||||
series={[
|
||||
{ name: '销售订单数', color: tokens.accent, values: win.map(w => w.orderCount) },
|
||||
{ name: '异常订单数', color: tokens.danger, values: win.map(w => w.riskCount) },
|
||||
{ name: '其中确定延期', color: tokens.warning, values: win.map(w => w.redCount), dashed: true },
|
||||
]}
|
||||
/>
|
||||
<ChartLegend items={[
|
||||
{ name: '销售订单数(张)', color: tokens.accent },
|
||||
{ name: '异常订单数(红+黄,张)', color: tokens.danger },
|
||||
{ name: '其中确定延期(红,张)', color: tokens.warning, dashed: true },
|
||||
]} />
|
||||
</Card>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
|
||||
<Card
|
||||
title="发货日历 · 当日应发与当日异常"
|
||||
right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>共 {points.length} 个发货日 · {summary.totalOrders} 张</span>}
|
||||
>
|
||||
<TrendChart
|
||||
height={190}
|
||||
yDigits={0}
|
||||
marker={null}
|
||||
labels={points.map(p => p.label)}
|
||||
series={[
|
||||
{ name: '当日应发订单', color: tokens.accent, values: points.map(p => p.orderCount) },
|
||||
{ name: '当日异常订单', color: tokens.danger, values: points.map(p => p.riskCount) },
|
||||
]}
|
||||
/>
|
||||
<ChartLegend items={[
|
||||
{ name: '当日应发订单(张)', color: tokens.accent },
|
||||
{ name: '当日异常订单(红+黄,张)', color: tokens.danger },
|
||||
]} />
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="累计压力曲线 · 订单量与异常量"
|
||||
right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>末端 {last?.cumOrders ?? 0} 张 / 异常 {last?.cumRisks ?? 0} 张</span>}
|
||||
>
|
||||
<TrendChart
|
||||
height={190}
|
||||
yDigits={0}
|
||||
marker={null}
|
||||
labels={points.map(p => p.label)}
|
||||
series={[
|
||||
{ name: '累计应发订单', color: tokens.accent, values: points.map(p => p.cumOrders) },
|
||||
{ name: '累计异常订单', color: tokens.warning, values: points.map(p => p.cumRisks) },
|
||||
]}
|
||||
/>
|
||||
<ChartLegend items={[
|
||||
{ name: '累计应发订单(张)', color: tokens.accent },
|
||||
{ name: '累计异常订单(张)', color: tokens.warning },
|
||||
]} />
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'start' }}>
|
||||
<Card title="Top 风险订单" tone={tokens.warning} right={<PeriodTag period={period} />}>
|
||||
{risks.map((r, i) => {
|
||||
const col = r.level === 'red' ? tokens.danger : r.level === 'yellow' ? tokens.warning : tokens.success;
|
||||
return (
|
||||
<div key={r.so.销售订单号} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 6px', borderRadius: 6 }}>
|
||||
<AlertTriangle size={12} style={{ color: col, flex: '0 0 12px' }} />
|
||||
<span style={{ fontSize: 11.5, color: tokens.text, width: 120, flex: '0 0 120px' }}>{r.so.销售订单号}</span>
|
||||
<span style={{ fontSize: 11, color: tokens.textMuted, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||
{r.so.客户简称} · {r.fired.join(' · ')}
|
||||
</span>
|
||||
<span style={{ fontSize: 11.5, color: col, fontVariantNumeric: 'tabular-nums', fontWeight: 700 }}>{r.score} 分</span>
|
||||
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{r.so.预计发货日期}</span>
|
||||
{i === 0 && <span style={{ fontSize: 9.5, color: tokens.onAccent, background: col, borderRadius: 6, padding: '0 5px' }}>TOP</span>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</Card>
|
||||
|
||||
<Card title="采购与物料状态">
|
||||
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
|
||||
<thead><tr>
|
||||
<Th>指标</Th><Th right>数值</Th><Th right>金额</Th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<tr style={{ background: 'transparent' }}>
|
||||
<Td>采购总行数</Td>
|
||||
<Td right mono>{po.totalLines}</Td>
|
||||
<Td right mono>—</Td>
|
||||
</tr>
|
||||
<tr style={{ background: tokens.tableRowAlt }}>
|
||||
<Td>未审批行</Td>
|
||||
<Td right mono color={tokens.danger}>{po.unapprovedLines}</Td>
|
||||
<Td right mono color={tokens.danger}>{money(po.unapprovedAmount)}</Td>
|
||||
</tr>
|
||||
<tr style={{ background: 'transparent' }}>
|
||||
<Td>在途逾期行</Td>
|
||||
<Td right mono color={tokens.warning}>{po.overdueLines}</Td>
|
||||
<Td right mono>—</Td>
|
||||
</tr>
|
||||
<tr style={{ background: tokens.tableRowAlt }}>
|
||||
<Td>物料缺口总量</Td>
|
||||
<Td right mono color={tokens.warning}>{summary.materialGapCount.toFixed(0)}</Td>
|
||||
<Td right mono>—</Td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
export type Theme = 'dark' | 'light';
|
||||
|
||||
export interface ThemeTokens {
|
||||
bodyBg: string;
|
||||
bodyBgImage: string;
|
||||
panelBg: string;
|
||||
panelBgAlt: string;
|
||||
cardBg: string;
|
||||
centerBg: string;
|
||||
border: string;
|
||||
borderSub: string;
|
||||
borderAccent: string;
|
||||
text: string;
|
||||
textSub: string;
|
||||
textMuted: string;
|
||||
textInverse: string;
|
||||
/** 压在 accent / 渐变底上的可读前景色(保证深浅主题都达 AA) */
|
||||
onAccent: string;
|
||||
accent: string;
|
||||
accentGlow: string;
|
||||
accentBg: string;
|
||||
success: string;
|
||||
successBg: string;
|
||||
warning: string;
|
||||
warningBg: string;
|
||||
danger: string;
|
||||
dangerBg: string;
|
||||
info: string;
|
||||
infoBg: string;
|
||||
headerScanLine: string;
|
||||
kpiCardBg: string;
|
||||
kpiCardBorder: string;
|
||||
tableHeaderBg: string;
|
||||
tableRowHover: string;
|
||||
tableRowAlt: string;
|
||||
scrollThumb: string;
|
||||
/** 左右侧板弧形背景(SVG 渐变端点) */
|
||||
svgPanelFrom: string;
|
||||
svgPanelTo: string;
|
||||
svgStroke: string;
|
||||
svgDot: string;
|
||||
titleBarColor: string;
|
||||
titleGlow: string;
|
||||
cardShadow: string;
|
||||
centerShadow: string;
|
||||
chartLine1: string;
|
||||
chartLine2: string;
|
||||
chartLine3: string;
|
||||
chartFill1: string;
|
||||
}
|
||||
|
||||
export const darkTokens: ThemeTokens = {
|
||||
bodyBg: '#0a0e1a',
|
||||
bodyBgImage: 'radial-gradient(1200px 600px at 15% -10%, rgba(99,102,241,0.16), transparent 60%), radial-gradient(1000px 500px at 90% 10%, rgba(56,189,248,0.10), transparent 60%), #0a0e1a',
|
||||
panelBg: 'rgba(15,23,42,0.85)',
|
||||
panelBgAlt: 'rgba(20,30,55,0.7)',
|
||||
cardBg: 'rgba(30,41,59,0.6)',
|
||||
centerBg: 'rgba(13,20,40,0.55)',
|
||||
border: 'rgba(99,102,241,0.15)',
|
||||
borderSub: 'rgba(99,102,241,0.08)',
|
||||
borderAccent: 'rgba(99,102,241,0.35)',
|
||||
text: '#e2e8f0',
|
||||
textSub: '#94a3b8',
|
||||
textMuted: 'rgba(168,184,208,0.85)',
|
||||
textInverse: '#ffffff',
|
||||
onAccent: '#0b1220',
|
||||
accent: '#818cf8',
|
||||
accentGlow: 'rgba(129,140,248,0.7)',
|
||||
accentBg: 'rgba(129,140,248,0.08)',
|
||||
success: '#34d399',
|
||||
successBg: 'rgba(52,211,153,0.1)',
|
||||
warning: '#fbbf24',
|
||||
warningBg: 'rgba(251,191,36,0.1)',
|
||||
danger: '#f87171',
|
||||
dangerBg: 'rgba(248,113,113,0.1)',
|
||||
info: '#38bdf8',
|
||||
infoBg: 'rgba(56,189,248,0.1)',
|
||||
headerScanLine: 'linear-gradient(90deg, transparent 0%, rgba(129,140,248,0.25) 20%, rgba(129,140,248,0.85) 50%, rgba(129,140,248,0.25) 80%, transparent 100%)',
|
||||
kpiCardBg: 'rgba(30,41,59,0.5)',
|
||||
kpiCardBorder: 'rgba(99,102,241,0.12)',
|
||||
tableHeaderBg: 'rgba(30,41,59,0.8)',
|
||||
tableRowHover: 'rgba(99,102,241,0.06)',
|
||||
tableRowAlt: 'rgba(20,30,55,0.4)',
|
||||
scrollThumb: 'rgba(129,140,248,0.28)',
|
||||
svgPanelFrom: 'rgba(18,26,52,0.72)',
|
||||
svgPanelTo: 'rgba(10,15,32,0.62)',
|
||||
svgStroke: 'rgba(129,140,248,0.4)',
|
||||
svgDot: 'rgba(129,140,248,0.9)',
|
||||
titleBarColor: '#c7d2fe',
|
||||
titleGlow: '0 0 22px rgba(129,140,248,0.55), 0 0 44px rgba(99,102,241,0.25)',
|
||||
cardShadow: '0 0 18px rgba(99,102,241,0.08)',
|
||||
centerShadow: '0 0 34px rgba(99,102,241,0.12), inset 0 0 30px rgba(15,23,42,0.5)',
|
||||
chartLine1: '#818cf8',
|
||||
chartLine2: '#34d399',
|
||||
chartLine3: '#fbbf24',
|
||||
chartFill1: 'rgba(129,140,248,0.15)',
|
||||
};
|
||||
|
||||
export const lightTokens: ThemeTokens = {
|
||||
bodyBg: '#eef2fa',
|
||||
bodyBgImage: 'radial-gradient(1200px 620px at 12% -12%, rgba(99,102,241,0.16), transparent 62%), radial-gradient(1000px 520px at 92% 4%, rgba(56,189,248,0.12), transparent 60%), linear-gradient(180deg, #f4f7fd 0%, #eaf0fa 100%)',
|
||||
panelBg: 'rgba(255,255,255,0.97)',
|
||||
panelBgAlt: 'rgba(248,250,255,0.95)',
|
||||
cardBg: 'rgba(255,255,255,0.92)',
|
||||
centerBg: 'linear-gradient(160deg, rgba(255,255,255,0.72) 0%, rgba(242,247,255,0.62) 50%, rgba(235,242,255,0.66) 100%)',
|
||||
border: 'rgba(30,58,138,0.14)',
|
||||
borderSub: 'rgba(30,58,138,0.08)',
|
||||
borderAccent: 'rgba(79,70,229,0.30)',
|
||||
text: '#0f172a',
|
||||
textSub: '#334155',
|
||||
textMuted: '#64748b',
|
||||
textInverse: '#ffffff',
|
||||
onAccent: '#ffffff',
|
||||
accent: '#4f46e5',
|
||||
accentGlow: 'rgba(79,70,229,0.35)',
|
||||
accentBg: 'rgba(79,70,229,0.06)',
|
||||
success: '#047857',
|
||||
successBg: 'rgba(4,120,87,0.07)',
|
||||
warning: '#b45309',
|
||||
warningBg: 'rgba(180,83,9,0.07)',
|
||||
danger: '#b91c1c',
|
||||
dangerBg: 'rgba(185,28,28,0.06)',
|
||||
info: '#1d4ed8',
|
||||
infoBg: 'rgba(29,78,216,0.07)',
|
||||
headerScanLine: 'linear-gradient(90deg, transparent 0%, rgba(79,70,229,0.12) 20%, rgba(79,70,229,0.42) 50%, rgba(79,70,229,0.12) 80%, transparent 100%)',
|
||||
kpiCardBg: 'rgba(255,255,255,0.85)',
|
||||
kpiCardBorder: 'rgba(79,70,229,0.12)',
|
||||
tableHeaderBg: 'rgba(237,242,252,0.95)',
|
||||
tableRowHover: 'rgba(79,70,229,0.05)',
|
||||
tableRowAlt: 'rgba(246,249,255,0.8)',
|
||||
scrollThumb: 'rgba(79,70,229,0.22)',
|
||||
svgPanelFrom: 'rgba(240,244,255,0.98)',
|
||||
svgPanelTo: 'rgba(226,235,252,0.96)',
|
||||
svgStroke: 'rgba(79,70,229,0.30)',
|
||||
svgDot: 'rgba(79,70,229,0.75)',
|
||||
titleBarColor: '#111827',
|
||||
titleGlow: 'none',
|
||||
cardShadow: '0 1px 4px rgba(30,60,130,0.07)',
|
||||
centerShadow: '0 4px 32px rgba(0,60,180,0.10), 0 1px 8px rgba(0,40,120,0.06)',
|
||||
chartLine1: '#4f46e5',
|
||||
chartLine2: '#059669',
|
||||
chartLine3: '#d97706',
|
||||
chartFill1: 'rgba(79,70,229,0.1)',
|
||||
};
|
||||
|
||||
interface ThemeContextValue {
|
||||
theme: Theme;
|
||||
tokens: ThemeTokens;
|
||||
toggleTheme: () => void;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = 'mec-theme';
|
||||
|
||||
function readStoredTheme(): Theme {
|
||||
try {
|
||||
const saved = localStorage.getItem(STORAGE_KEY);
|
||||
return saved === 'dark' || saved === 'light' ? saved : 'light';
|
||||
} catch {
|
||||
return 'light';
|
||||
}
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue>({
|
||||
theme: 'light',
|
||||
tokens: lightTokens,
|
||||
toggleTheme: () => {},
|
||||
});
|
||||
|
||||
export function ThemeProvider({ children }: { children: ReactNode }) {
|
||||
const [theme, setTheme] = useState<Theme>(readStoredTheme);
|
||||
const tokens = theme === 'dark' ? darkTokens : lightTokens;
|
||||
|
||||
const toggleTheme = useCallback(() => {
|
||||
setTheme(t => {
|
||||
const next: Theme = t === 'dark' ? 'light' : 'dark';
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
} catch {
|
||||
/* 忽略写入失败 */
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--body-bg', tokens.bodyBg);
|
||||
root.style.setProperty('--scroll-thumb', tokens.scrollThumb);
|
||||
root.style.setProperty('--glow-color', tokens.accentGlow);
|
||||
root.style.setProperty('--hover-bg', tokens.tableRowHover);
|
||||
document.body.style.background = tokens.bodyBgImage;
|
||||
document.body.style.color = tokens.text;
|
||||
}, [tokens]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, tokens, toggleTheme }}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* 履约监控指标计算层:从销售订单 → 工单 → 材料 → 采购的真实单据中
|
||||
* 实时算出 6 个中央看板页签需要的聚合指标与清单。
|
||||
*
|
||||
* 所有数字尽量复用 ontology.ts / ibpAsk.ts 的同一套关键路径中间量与评分规则,
|
||||
* 保证「业务本体总览 · 智能体对话 · 中央看板」三处口径一致。
|
||||
*
|
||||
* 时间游标:每个聚合都可传 period(0-11,见 lib/time.ts)。
|
||||
* 当期=ERP 导出的 17 张真实单据,与本体页/问答完全同源;
|
||||
* 历史期=data/ibp/history.ts 生成的同构单据,风险仍由同一套规则实算。
|
||||
* 不传 period 时一律按当期口径,老调用点行为不变。
|
||||
*/
|
||||
|
||||
import {
|
||||
salesOrders, productionOrders, purchaseOrders, workOrderMaterials,
|
||||
type SalesOrder, type ProductionOrder, type PurchaseOrder, type WorkOrderMaterial,
|
||||
} from './ibp';
|
||||
import { PATH, buildPaths, purchaseGroups, ONTOLOGY_AS_OF, type PathRow } from './ontology';
|
||||
import { orderRisks, rankRisks, scoreRisk, type OrderRisk } from '../lib/ibpAsk';
|
||||
import { historyBook } from './ibp/history';
|
||||
import { CURRENT_PERIOD, PERIOD_COUNT, PERIOD_MONTHS, isCurrentPeriod, periodAsOf } from '../lib/time';
|
||||
|
||||
const day = (s: string) => new Date(`${s}T00:00:00`).getTime();
|
||||
const diff = (a: string, b: string) => Math.round((day(a) - day(b)) / 86400000);
|
||||
|
||||
/* ══════════════════════════ 一期账本 ══════════════════════════ */
|
||||
|
||||
/** 游标期的全部单据与风险结果:看板所有数字的唯一取数入口 */
|
||||
export interface FulfillmentBook {
|
||||
period: number;
|
||||
/** YYYY-MM */
|
||||
month: string;
|
||||
/** 该期的数据截止日:当期=快照日,历史期=该月月末 */
|
||||
asOf: string;
|
||||
/** 是否当期(当期单据是 ERP 导出的真实单据) */
|
||||
current: boolean;
|
||||
salesOrders: SalesOrder[];
|
||||
productionOrders: ProductionOrder[];
|
||||
workOrderMaterials: WorkOrderMaterial[];
|
||||
purchaseOrders: PurchaseOrder[];
|
||||
paths: PathRow[];
|
||||
risks: OrderRisk[];
|
||||
}
|
||||
|
||||
const bookCache = new Map<number, FulfillmentBook>();
|
||||
|
||||
export function bookAt(period: number = CURRENT_PERIOD): FulfillmentBook {
|
||||
const p = Math.max(0, Math.min(PERIOD_COUNT - 1, period));
|
||||
const hit = bookCache.get(p);
|
||||
if (hit) return hit;
|
||||
|
||||
const book: FulfillmentBook = isCurrentPeriod(p)
|
||||
? {
|
||||
period: p, month: PERIOD_MONTHS[p], asOf: ONTOLOGY_AS_OF, current: true,
|
||||
salesOrders, productionOrders, workOrderMaterials, purchaseOrders,
|
||||
paths: PATH, risks: orderRisks(),
|
||||
}
|
||||
: (() => {
|
||||
const h = historyBook(PERIOD_MONTHS[p], p);
|
||||
const asOf = periodAsOf(p);
|
||||
const paths = buildPaths(h.salesOrders, h.productionOrders, h.purchaseOrders, asOf);
|
||||
return {
|
||||
period: p, month: PERIOD_MONTHS[p], asOf, current: false,
|
||||
salesOrders: h.salesOrders, productionOrders: h.productionOrders,
|
||||
workOrderMaterials: h.workOrderMaterials, purchaseOrders: h.purchaseOrders,
|
||||
paths, risks: rankRisks(paths.map(path => scoreRisk(path, asOf))),
|
||||
};
|
||||
})();
|
||||
|
||||
bookCache.set(p, book);
|
||||
return book;
|
||||
}
|
||||
|
||||
/* ══════════════════════════ 聚合结构 ══════════════════════════ */
|
||||
|
||||
/** 按月聚合:以销售订单的「预计发货日期」为时间轴 */
|
||||
export interface MonthlyFulfillment {
|
||||
month: string; // YYYY-MM
|
||||
orderCount: number;
|
||||
amount: number;
|
||||
quantity: number;
|
||||
redCount: number;
|
||||
yellowCount: number;
|
||||
greenCount: number;
|
||||
}
|
||||
|
||||
/** 客户维度聚合 */
|
||||
export interface CustomerSummary {
|
||||
code: string;
|
||||
name: string;
|
||||
category: string;
|
||||
orderCount: number;
|
||||
amount: number;
|
||||
quantity: number;
|
||||
redCount: number;
|
||||
yellowCount: number;
|
||||
greenCount: number;
|
||||
}
|
||||
|
||||
/** 产品维度聚合 */
|
||||
export interface ProductSummary {
|
||||
code: string;
|
||||
orderCount: number;
|
||||
amount: number;
|
||||
quantity: number;
|
||||
redCount: number;
|
||||
yellowCount: number;
|
||||
}
|
||||
|
||||
/** 物料供需缺口(复用 ibp/index.ts materialBalance,但补材料名与采购/需求占比) */
|
||||
export interface MaterialGap {
|
||||
code: string;
|
||||
demand: number;
|
||||
supplied: number;
|
||||
gap: number;
|
||||
demandOrders: number; // 多少张销售订单用到
|
||||
}
|
||||
|
||||
/** 采购订单状态聚合 */
|
||||
export interface POStatusSummary {
|
||||
totalLines: number;
|
||||
approvedLines: number;
|
||||
unapprovedLines: number;
|
||||
unapprovedAmount: number;
|
||||
overdueLines: number; // 已过预计到货日
|
||||
}
|
||||
|
||||
/** 总体 KPI */
|
||||
export interface FulfillmentSummary {
|
||||
totalOrders: number;
|
||||
totalAmount: number;
|
||||
totalQuantity: number;
|
||||
avgDeliveryLeadDays: number;
|
||||
redOrders: number;
|
||||
yellowOrders: number;
|
||||
greenOrders: number;
|
||||
atRiskAmount: number;
|
||||
delayedOrders: number; // critLag > 0
|
||||
kitLagOrders: number; // kitLag > 0
|
||||
unapprovedPoLines: number;
|
||||
unapprovedPoAmount: number;
|
||||
overduePoLines: number;
|
||||
materialGapCount: number;
|
||||
materialShortCount: number; // 缺口 > 0 的材料种数
|
||||
}
|
||||
|
||||
/* ════════════════════════════════════════════════════════════════════════ */
|
||||
|
||||
/** 该期的风险结果(按风险分降序) */
|
||||
export function getOrderRisks(period: number = CURRENT_PERIOD): OrderRisk[] {
|
||||
return bookAt(period).risks;
|
||||
}
|
||||
|
||||
/** 销售订单号 → 风险对象 */
|
||||
function riskMap(risks: OrderRisk[]): Map<string, OrderRisk> {
|
||||
return new Map(risks.map(r => [r.so.销售订单号, r]));
|
||||
}
|
||||
|
||||
/** 总体 KPI */
|
||||
export function fulfillmentSummary(period: number = CURRENT_PERIOD): FulfillmentSummary {
|
||||
const book = bookAt(period);
|
||||
const risks = book.risks;
|
||||
const red = risks.filter(r => r.level === 'red');
|
||||
const yellow = risks.filter(r => r.level === 'yellow');
|
||||
|
||||
const totalLead = book.salesOrders.reduce((s, o) => s + diff(o.预计发货日期, o.单据日期), 0);
|
||||
|
||||
const poStatus = poStatusSummary(period);
|
||||
const gaps = materialGaps(period);
|
||||
const shortCount = gaps.filter(g => g.gap > 0).length;
|
||||
|
||||
return {
|
||||
totalOrders: book.salesOrders.length,
|
||||
totalAmount: book.salesOrders.reduce((s, o) => s + o.含税金额, 0),
|
||||
totalQuantity: book.salesOrders.reduce((s, o) => s + o.数量, 0),
|
||||
avgDeliveryLeadDays: book.salesOrders.length ? Math.round(totalLead / book.salesOrders.length) : 0,
|
||||
redOrders: red.length,
|
||||
yellowOrders: yellow.length,
|
||||
greenOrders: risks.filter(r => r.level === 'green').length,
|
||||
atRiskAmount: red.reduce((s, r) => s + r.so.含税金额, 0) + yellow.reduce((s, r) => s + r.so.含税金额, 0),
|
||||
delayedOrders: risks.filter(r => r.path.critLag > 0).length,
|
||||
kitLagOrders: risks.filter(r => r.path.kitLag > 0 && r.path.critLag <= 0).length,
|
||||
unapprovedPoLines: poStatus.unapprovedLines,
|
||||
unapprovedPoAmount: poStatus.unapprovedAmount,
|
||||
overduePoLines: poStatus.overdueLines,
|
||||
materialGapCount: gaps.reduce((s, g) => s + Math.max(0, g.gap), 0),
|
||||
materialShortCount: shortCount,
|
||||
};
|
||||
}
|
||||
|
||||
/** 该期账本内按月聚合(基于预计发货日期) */
|
||||
export function monthlyFulfillment(period: number = CURRENT_PERIOD): MonthlyFulfillment[] {
|
||||
const book = bookAt(period);
|
||||
const risks = riskMap(book.risks);
|
||||
const map = new Map<string, MonthlyFulfillment>();
|
||||
book.salesOrders.forEach(o => {
|
||||
const m = o.预计发货日期.slice(0, 7);
|
||||
const r = risks.get(o.销售订单号);
|
||||
const prev = map.get(m) ?? {
|
||||
month: m, orderCount: 0, amount: 0, quantity: 0,
|
||||
redCount: 0, yellowCount: 0, greenCount: 0,
|
||||
};
|
||||
prev.orderCount += 1;
|
||||
prev.amount += o.含税金额;
|
||||
prev.quantity += o.数量;
|
||||
if (r?.level === 'red') prev.redCount += 1;
|
||||
else if (r?.level === 'yellow') prev.yellowCount += 1;
|
||||
else prev.greenCount += 1;
|
||||
map.set(m, prev);
|
||||
});
|
||||
return [...map.values()].sort((a, b) => a.month.localeCompare(b.month));
|
||||
}
|
||||
|
||||
/**
|
||||
* 回放窗口 12 期总览:每期一套账本,逐期汇总订单量与异常量。
|
||||
* 全景驾驶舱的趋势曲线与趋势页签用它,拖动游标时曲线上的高亮点会跟着走。
|
||||
*/
|
||||
export interface PeriodFulfillment extends MonthlyFulfillment {
|
||||
period: number;
|
||||
riskCount: number;
|
||||
}
|
||||
|
||||
let windowCache: PeriodFulfillment[] | null = null;
|
||||
|
||||
export function windowFulfillment(): PeriodFulfillment[] {
|
||||
if (!windowCache) {
|
||||
windowCache = Array.from({ length: PERIOD_COUNT }, (_, p) => {
|
||||
const book = bookAt(p);
|
||||
const red = book.risks.filter(r => r.level === 'red').length;
|
||||
const yellow = book.risks.filter(r => r.level === 'yellow').length;
|
||||
return {
|
||||
period: p,
|
||||
month: PERIOD_MONTHS[p],
|
||||
orderCount: book.salesOrders.length,
|
||||
amount: book.salesOrders.reduce((s, o) => s + o.含税金额, 0),
|
||||
quantity: book.salesOrders.reduce((s, o) => s + o.数量, 0),
|
||||
redCount: red,
|
||||
yellowCount: yellow,
|
||||
greenCount: book.risks.length - red - yellow,
|
||||
riskCount: red + yellow,
|
||||
};
|
||||
});
|
||||
}
|
||||
return windowCache;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按「预计发货日期」逐日聚合的履约时间轴,供驾驶舱画曲线。
|
||||
* 当期销售订单只有 17 张、集中在几个发货日,按月聚合画不成趋势,
|
||||
* 所以这里下沉到发货日粒度;风险等级复用 bookAt() 的同一套规则口径。
|
||||
*/
|
||||
export interface ShipmentTrendPoint {
|
||||
date: string; // YYYY-MM-DD
|
||||
label: string; // MM-DD,给 X 轴用
|
||||
orderCount: number; // 当日应发订单数
|
||||
riskCount: number; // 当日异常(红 + 黄)订单数
|
||||
redCount: number;
|
||||
yellowCount: number;
|
||||
amount: number; // 当日含税金额
|
||||
cumOrders: number; // 截至当日累计应发订单数
|
||||
cumRisks: number; // 截至当日累计异常订单数
|
||||
}
|
||||
|
||||
export function shipmentTrend(period: number = CURRENT_PERIOD): ShipmentTrendPoint[] {
|
||||
const book = bookAt(period);
|
||||
const risks = riskMap(book.risks);
|
||||
const map = new Map<string, ShipmentTrendPoint>();
|
||||
book.salesOrders.forEach(o => {
|
||||
const date = o.预计发货日期;
|
||||
const r = risks.get(o.销售订单号);
|
||||
const prev = map.get(date) ?? {
|
||||
date, label: date.slice(5),
|
||||
orderCount: 0, riskCount: 0, redCount: 0, yellowCount: 0,
|
||||
amount: 0, cumOrders: 0, cumRisks: 0,
|
||||
};
|
||||
prev.orderCount += 1;
|
||||
prev.amount += o.含税金额;
|
||||
if (r?.level === 'red') { prev.redCount += 1; prev.riskCount += 1; }
|
||||
else if (r?.level === 'yellow') { prev.yellowCount += 1; prev.riskCount += 1; }
|
||||
map.set(date, prev);
|
||||
});
|
||||
const list = [...map.values()].sort((a, b) => a.date.localeCompare(b.date));
|
||||
let cumOrders = 0;
|
||||
let cumRisks = 0;
|
||||
list.forEach(p => {
|
||||
cumOrders += p.orderCount;
|
||||
cumRisks += p.riskCount;
|
||||
p.cumOrders = cumOrders;
|
||||
p.cumRisks = cumRisks;
|
||||
});
|
||||
return list;
|
||||
}
|
||||
|
||||
/** 客户维度聚合 */
|
||||
export function customerSummaries(period: number = CURRENT_PERIOD): CustomerSummary[] {
|
||||
const book = bookAt(period);
|
||||
const risks = riskMap(book.risks);
|
||||
const map = new Map<string, CustomerSummary>();
|
||||
book.salesOrders.forEach(o => {
|
||||
const r = risks.get(o.销售订单号);
|
||||
const prev = map.get(o.客户编码) ?? {
|
||||
code: o.客户编码,
|
||||
name: o.客户简称,
|
||||
category: o.客户分类,
|
||||
orderCount: 0, amount: 0, quantity: 0,
|
||||
redCount: 0, yellowCount: 0, greenCount: 0,
|
||||
};
|
||||
prev.orderCount += 1;
|
||||
prev.amount += o.含税金额;
|
||||
prev.quantity += o.数量;
|
||||
if (r?.level === 'red') prev.redCount += 1;
|
||||
else if (r?.level === 'yellow') prev.yellowCount += 1;
|
||||
else prev.greenCount += 1;
|
||||
map.set(o.客户编码, prev);
|
||||
});
|
||||
return [...map.values()].sort((a, b) => b.amount - a.amount);
|
||||
}
|
||||
|
||||
/** 产品维度聚合 */
|
||||
export function productSummaries(period: number = CURRENT_PERIOD): ProductSummary[] {
|
||||
const book = bookAt(period);
|
||||
const risks = riskMap(book.risks);
|
||||
const map = new Map<string, ProductSummary>();
|
||||
book.salesOrders.forEach(o => {
|
||||
const r = risks.get(o.销售订单号);
|
||||
const prev = map.get(o.产品编码) ?? {
|
||||
code: o.产品编码,
|
||||
orderCount: 0, amount: 0, quantity: 0,
|
||||
redCount: 0, yellowCount: 0,
|
||||
};
|
||||
prev.orderCount += 1;
|
||||
prev.amount += o.含税金额;
|
||||
prev.quantity += o.数量;
|
||||
if (r?.level === 'red') prev.redCount += 1;
|
||||
else if (r?.level === 'yellow') prev.yellowCount += 1;
|
||||
map.set(o.产品编码, prev);
|
||||
});
|
||||
return [...map.values()].sort((a, b) => b.amount - a.amount);
|
||||
}
|
||||
|
||||
/** 物料供需缺口 */
|
||||
export function materialGaps(period: number = CURRENT_PERIOD): MaterialGap[] {
|
||||
const book = bookAt(period);
|
||||
const demand = new Map<string, number>();
|
||||
const demandOrders = new Map<string, Set<string>>();
|
||||
book.workOrderMaterials.forEach(m => {
|
||||
demand.set(m.材料编码, (demand.get(m.材料编码) ?? 0) + m.应领数量);
|
||||
const set = demandOrders.get(m.材料编码) ?? new Set<string>();
|
||||
set.add(m.来源销售订单号);
|
||||
demandOrders.set(m.材料编码, set);
|
||||
});
|
||||
const supplied = new Map<string, number>();
|
||||
book.purchaseOrders.forEach(p => {
|
||||
supplied.set(p.材料编码, (supplied.get(p.材料编码) ?? 0) + p.数量);
|
||||
});
|
||||
const codes = new Set([...demand.keys(), ...supplied.keys()]);
|
||||
return [...codes].map(code => ({
|
||||
code,
|
||||
demand: +(demand.get(code) ?? 0).toFixed(2),
|
||||
supplied: +(supplied.get(code) ?? 0).toFixed(2),
|
||||
gap: +(((demand.get(code) ?? 0) - (supplied.get(code) ?? 0)).toFixed(2)),
|
||||
demandOrders: demandOrders.get(code)?.size ?? 0,
|
||||
})).sort((a, b) => b.gap - a.gap);
|
||||
}
|
||||
|
||||
/** 采购订单状态汇总(逾期口径按该期截止日判定) */
|
||||
export function poStatusSummary(period: number = CURRENT_PERIOD): POStatusSummary {
|
||||
const book = bookAt(period);
|
||||
let unapprovedLines = 0;
|
||||
let unapprovedAmount = 0;
|
||||
let overdueLines = 0;
|
||||
book.purchaseOrders.forEach(p => {
|
||||
if (p.订单状态 !== '生效') {
|
||||
unapprovedLines += 1;
|
||||
unapprovedAmount += p.含税金额;
|
||||
}
|
||||
if (day(p.预计到货日期) < day(book.asOf)) overdueLines += 1;
|
||||
});
|
||||
return {
|
||||
totalLines: book.purchaseOrders.length,
|
||||
approvedLines: book.purchaseOrders.length - unapprovedLines,
|
||||
unapprovedLines,
|
||||
unapprovedAmount,
|
||||
overdueLines,
|
||||
};
|
||||
}
|
||||
|
||||
/** 风险矩阵散点:x=风险概率,y=影响金额(万元) */
|
||||
export interface RiskScatterItem {
|
||||
soNo: string;
|
||||
customer: string;
|
||||
probability: number;
|
||||
impactWan: number;
|
||||
level: 'red' | 'yellow' | 'green';
|
||||
tone: 'danger' | 'warning' | 'success';
|
||||
}
|
||||
|
||||
export function riskScatter(period: number = CURRENT_PERIOD): RiskScatterItem[] {
|
||||
return getOrderRisks(period).map(r => ({
|
||||
soNo: r.so.销售订单号,
|
||||
customer: r.so.客户简称,
|
||||
probability: r.level === 'red' ? 0.75 + Math.min(r.score, 25) / 100
|
||||
: r.level === 'yellow' ? 0.45 + Math.min(r.score, 20) / 80
|
||||
: 0.15 + Math.min(r.score, 10) / 100,
|
||||
impactWan: r.so.含税金额 / 10000,
|
||||
level: r.level,
|
||||
tone: r.level === 'red' ? 'danger' : r.level === 'yellow' ? 'warning' : 'success',
|
||||
}));
|
||||
}
|
||||
|
||||
/** 看板 Top 风险订单 */
|
||||
export function topRisks(limit = 8, period: number = CURRENT_PERIOD): OrderRisk[] {
|
||||
return getOrderRisks(period).slice(0, limit);
|
||||
}
|
||||
|
||||
/** 复用 ontology PATH 与 ibpAsk 风险类型给看板展示 */
|
||||
export { PATH, purchaseGroups, type PathRow };
|
||||
export type { OrderRisk } from '../lib/ibpAsk';
|
||||
@@ -0,0 +1,123 @@
|
||||
[
|
||||
{
|
||||
"序号": 1,
|
||||
"客户编码": "GM0045",
|
||||
"客户简称": "YCSFHWLYXGS",
|
||||
"性质": "客户/供应商",
|
||||
"客户分类": "杂项开票",
|
||||
"所属类别": "杂项开票",
|
||||
"分管部门": null,
|
||||
"订单笔数": 2,
|
||||
"订单金额": 140612.8
|
||||
},
|
||||
{
|
||||
"序号": 2,
|
||||
"客户编码": "KA0033",
|
||||
"客户简称": "NBLARYPYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 2,
|
||||
"订单金额": 16499.9
|
||||
},
|
||||
{
|
||||
"序号": 3,
|
||||
"客户编码": "KA0049",
|
||||
"客户简称": "ZJJLYZFZPXSYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 1,
|
||||
"订单金额": 27518.4
|
||||
},
|
||||
{
|
||||
"序号": 4,
|
||||
"客户编码": "KA0087",
|
||||
"客户简称": "LSMMJJYP(ZJ)YXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 1,
|
||||
"订单金额": 10836.62
|
||||
},
|
||||
{
|
||||
"序号": 5,
|
||||
"客户编码": "KA0090",
|
||||
"客户简称": "KCTZ(ZG)YXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 1,
|
||||
"订单金额": 115200
|
||||
},
|
||||
{
|
||||
"序号": 6,
|
||||
"客户编码": "KA0099",
|
||||
"客户简称": "ZJSJLHWLPSYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 2,
|
||||
"订单金额": 62400
|
||||
},
|
||||
{
|
||||
"序号": 7,
|
||||
"客户编码": "KA0116",
|
||||
"客户简称": "NBJQHYGMYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 2,
|
||||
"订单金额": 89510.4
|
||||
},
|
||||
{
|
||||
"序号": 8,
|
||||
"客户编码": "KA0124",
|
||||
"客户简称": "TJSTNGJMYYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 2,
|
||||
"订单金额": 30960
|
||||
},
|
||||
{
|
||||
"序号": 9,
|
||||
"客户编码": "KA0154",
|
||||
"客户简称": "HNZQNGYLGLYXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 1,
|
||||
"订单金额": 14040
|
||||
},
|
||||
{
|
||||
"序号": 10,
|
||||
"客户编码": "KA0162",
|
||||
"客户简称": "ZSMGYL(SY)YXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 2,
|
||||
"订单金额": 121919.1
|
||||
},
|
||||
{
|
||||
"序号": 11,
|
||||
"客户编码": "KA0210",
|
||||
"客户简称": "BGGGCZ(GZ)YXGS",
|
||||
"性质": "客户",
|
||||
"客户分类": "OEM开票",
|
||||
"所属类别": "OEM开票",
|
||||
"分管部门": "销售科",
|
||||
"订单笔数": 1,
|
||||
"订单金额": 21850
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* 历史履约单据生成器:为「回放时间轴」上除当期外的月份各生成一套
|
||||
* 销售订单 → 生产工单 → 工单材料明细 → 采购订单行,让中央看板在拖动/回放时
|
||||
* 有真实可算的单据,而不是只有一期的快照。
|
||||
*
|
||||
* 三条硬约束:
|
||||
* 1. 确定性——mulberry32 以月份序号做种子,同一个月永远生成同一批单据,刷新不跳数;
|
||||
* 2. 口径一致——字段结构与 ERP 导出的 JSON 完全相同,风险仍由 ontology/ibpAsk 的
|
||||
* 同一套规则引擎实算,历史月的红黄绿不是画出来的假数;
|
||||
* 3. 不污染当期——本模块不被 ibp/index.ts 引用,业务本体总览与智能体问答仍只读
|
||||
* 真实导出的 17 张单据,回放只驱动中央看板页签。
|
||||
*/
|
||||
|
||||
import {
|
||||
customers, items, suppliers,
|
||||
type ProductionOrder, type PurchaseOrder, type SalesOrder, type WorkOrderMaterial,
|
||||
} from './index';
|
||||
|
||||
/** 一期(一个自然月)的完整单据账本 */
|
||||
export interface HistoryBook {
|
||||
month: string; // YYYY-MM
|
||||
salesOrders: SalesOrder[];
|
||||
productionOrders: ProductionOrder[];
|
||||
workOrderMaterials: WorkOrderMaterial[];
|
||||
purchaseOrders: PurchaseOrder[];
|
||||
}
|
||||
|
||||
/* ── 确定性随机:与 sqlite.ts 的 LCG 同思路,换个实现避免跨模块耦合 ───────── */
|
||||
|
||||
function mulberry32(seed: number) {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6D2B79F5) >>> 0;
|
||||
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
/* ── 日期工具:全部按 UTC 计算,避免本地时区把月份边界挪一天 ─────────────── */
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, '0');
|
||||
const ymd = (d: Date) => `${d.getUTCFullYear()}-${pad2(d.getUTCMonth() + 1)}-${pad2(d.getUTCDate())}`;
|
||||
const parseYmd = (s: string) => new Date(Date.UTC(+s.slice(0, 4), +s.slice(5, 7) - 1, +s.slice(8, 10)));
|
||||
const addDays = (s: string, n: number) => {
|
||||
const d = parseYmd(s);
|
||||
d.setUTCDate(d.getUTCDate() + n);
|
||||
return ymd(d);
|
||||
};
|
||||
/** 该月最后一天 */
|
||||
const monthEnd = (month: string) => {
|
||||
const d = new Date(Date.UTC(+month.slice(0, 4), +month.slice(5, 7), 0));
|
||||
return ymd(d);
|
||||
};
|
||||
|
||||
const round = (n: number, digits: number) => +n.toFixed(digits);
|
||||
|
||||
/* ── 主数据池:历史单据复用真实导出的客户 / 成品 / 物料 / 供应商 ─────────── */
|
||||
|
||||
const FINISHED = items.filter(i => i.类型 === '成品').map(i => i.物料编码);
|
||||
const MATERIALS = items.filter(i => i.类型 === '材料').map(i => i.物料编码);
|
||||
const MAKERS = ['王晓静', '吴东琴', '赵广粉'];
|
||||
const SHOPS = ['分卷组', '手工包装组'];
|
||||
const WHORES = ['辅料仓', '外购半成品仓', '车间现场仓'];
|
||||
|
||||
/** 该月的「供应压力指数」0.05~0.95:决定到货延迟与未审采购的比例 */
|
||||
function stressOf(i: number, rnd: () => number) {
|
||||
const seasonal = 0.5 + 0.5 * Math.sin(((i + 2) / 12) * Math.PI * 2); // 年内两峰
|
||||
return Math.min(0.95, Math.max(0.05, 0.16 + 0.55 * seasonal + (rnd() - 0.5) * 0.22));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成一个月的单据账本。
|
||||
* @param month YYYY-MM
|
||||
* @param i 月份在窗口中的序号(做种子,保证确定性)
|
||||
*/
|
||||
function buildBook(month: string, i: number): HistoryBook {
|
||||
const rnd = mulberry32(0x2026_1017 + i * 7919);
|
||||
const stress = stressOf(i, rnd);
|
||||
const pick = <T,>(arr: T[]) => arr[Math.floor(rnd() * arr.length) % arr.length];
|
||||
|
||||
const sos: SalesOrder[] = [];
|
||||
const wos: ProductionOrder[] = [];
|
||||
const woms: WorkOrderMaterial[] = [];
|
||||
const pos: PurchaseOrder[] = [];
|
||||
const first = `${month}-01`;
|
||||
const lastDay = +monthEnd(month).slice(8, 10);
|
||||
// 单量:9~17 张,带一点年内增长,保证每月台账都有内容
|
||||
const count = 9 + Math.round(5 * Math.abs(Math.sin(i * 1.3)) + rnd() * 3) + Math.floor(i / 4);
|
||||
let poSeq = 1;
|
||||
|
||||
for (let k = 0; k < count; k++) {
|
||||
const cus = pick(customers);
|
||||
const product = FINISHED.length ? pick(FINISHED) : `CP${1000 + k}`;
|
||||
const orderDate = addDays(first, Math.floor(rnd() * Math.max(1, lastDay - 3)));
|
||||
const shipDate = addDays(orderDate, 20 + Math.floor(rnd() * 40));
|
||||
const qty = Math.round((1500 + rnd() * 18000) / 10) * 10;
|
||||
const price = round(0.6 + rnd() * 10, 2);
|
||||
const soNo = `H${orderDate.replace(/-/g, '')}${100 + k}`;
|
||||
|
||||
sos.push({
|
||||
序号: 0, 销售订单号: soNo, 单据日期: orderDate, 客户编码: cus.客户编码,
|
||||
客户分类: cus.客户分类, 客户简称: cus.客户简称, 产品编码: product, 数量: qty,
|
||||
含税单价: price, 含税金额: round(qty * price, 2), 预计发货日期: shipDate,
|
||||
仓库名称: 'OEM事业部成品仓', 制单人: MAKERS[k % MAKERS.length], 单据状态: '生效',
|
||||
});
|
||||
|
||||
// 工单:完工=发货−2 天(与当期真实单据同一缓冲口径),周期 7/10/12/15 天
|
||||
const cycle = pick([7, 10, 12, 15]);
|
||||
const finish = addDays(shipDate, -2);
|
||||
const start = addDays(finish, -cycle);
|
||||
const woNo = `WO-${soNo}`;
|
||||
wos.push({
|
||||
序号: 0, 工单号: woNo, 来源销售订单号: soNo, 产品编码: product, 规格型号: null,
|
||||
计量单位: 'PCS', 生产数量: qty, 生产车间: SHOPS[k % SHOPS.length],
|
||||
预计开工日期: start, 预计完工日期: finish, '生产周期(天)': cycle,
|
||||
BOM版本: rnd() < 0.3 ? '—' : 'V1.0',
|
||||
单据状态: rnd() < 0.75 ? '已完工' : '已下达',
|
||||
});
|
||||
|
||||
// 材料明细 2~4 行,采购行与材料行一一对应(沿用真实单据的「请购单」来源)
|
||||
const matCount = 2 + Math.floor(rnd() * 3);
|
||||
const used = new Set<string>();
|
||||
for (let m = 0; m < matCount; m++) {
|
||||
const mat = MATERIALS.length ? pick(MATERIALS) : `M${100 + m}`;
|
||||
if (used.has(mat)) continue;
|
||||
used.add(mat);
|
||||
const usage = round(1 + rnd() * 2.2, 4);
|
||||
const need = round(qty * usage, 3);
|
||||
const bom = wos[wos.length - 1].BOM版本;
|
||||
woms.push({
|
||||
序号: 0, 工单号: woNo, 来源销售订单号: soNo, 产品编码: product, 材料编码: mat,
|
||||
规格型号: null, 计量单位: 'PCS', 工单数量: qty, 单位用量: usage, 损耗率: null,
|
||||
应领数量: need, 预出仓库: pick(WHORES),
|
||||
材料来源: bom === '—' ? '采购需求反推' : (rnd() < 0.8 ? '采购需求反推' : 'BOM展开'),
|
||||
BOM版本: bom, 子件BOM: null,
|
||||
});
|
||||
|
||||
// 到货计划:正常早于开工 3 天;压力月按比例延后,延过完工日即触发关键路径冲突
|
||||
const late = rnd() < stress;
|
||||
const arrival = late ? addDays(start, 1 + Math.floor(rnd() * cycle * 1.4)) : addDays(start, -3);
|
||||
const sup = pick(suppliers);
|
||||
const poQty = round(need * (0.98 + rnd() * 0.08), 2);
|
||||
const poPrice = round(0.2 + rnd() * 4, 2);
|
||||
pos.push({
|
||||
序号: 0,
|
||||
采购订单号: `PO-${month}-${String(poSeq++).padStart(4, '0')}`,
|
||||
采购日期: addDays(start, -(5 + Math.floor(rnd() * 18))),
|
||||
来源销售订单号: soNo, 产品工单号: woNo,
|
||||
供应商编码: sup.供应商编码, 供应商简称: sup.供应商简称, 材料编码: mat,
|
||||
数量: poQty, 单价: poPrice, 含税金额: round(poQty * poPrice, 2),
|
||||
预计到货日期: arrival,
|
||||
订单状态: rnd() < 0.08 + stress * 0.16 ? '未审' : '生效',
|
||||
来源单据: '请购单',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 序号统一续编,保持与 ERP 导出一致的展示口径
|
||||
[sos, wos, woms, pos].forEach(rows => rows.forEach((r, idx) => { r.序号 = idx + 1; }));
|
||||
return { month, salesOrders: sos, productionOrders: wos, workOrderMaterials: woms, purchaseOrders: pos };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按月批量生成。调用方传入需要补齐的历史月份(当期不在其中),
|
||||
* 结果缓存在模块级,避免每次切换游标重算。
|
||||
*/
|
||||
const cache = new Map<string, HistoryBook>();
|
||||
|
||||
export function historyBook(month: string, index: number): HistoryBook {
|
||||
let b = cache.get(month);
|
||||
if (!b) {
|
||||
b = buildBook(month, index);
|
||||
cache.set(month, b);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 洁雅家居 · 集成业务计划 —— 模拟业务单据数据(前端内置,不落后端库)
|
||||
* 来源:source-data/测试业务单据.xlsx(ERP 导出单据按真实业务链路重组)
|
||||
* 链路:销售订单 → 生产工单(WO-销售订单号) → 工单材料明细 → 材料采购订单
|
||||
*/
|
||||
import salesOrdersRaw from './sales_orders.json';
|
||||
import productionOrdersRaw from './production_orders.json';
|
||||
import workOrderMaterialsRaw from './work_order_materials.json';
|
||||
import purchaseOrdersRaw from './purchase_orders.json';
|
||||
import customersRaw from './customers.json';
|
||||
import suppliersRaw from './suppliers.json';
|
||||
import itemsRaw from './items.json';
|
||||
|
||||
export interface SalesOrder {
|
||||
序号: number; 销售订单号: string; 单据日期: string; 客户编码: string; 客户分类: string;
|
||||
客户简称: string; 产品编码: string; 数量: number; 含税单价: number; 含税金额: number;
|
||||
预计发货日期: string; 仓库名称: string; 制单人: string; 单据状态: string;
|
||||
}
|
||||
export interface ProductionOrder {
|
||||
序号: number; 工单号: string; 来源销售订单号: string; 产品编码: string; 规格型号: string | null;
|
||||
计量单位: string; 生产数量: number; 生产车间: string; 预计开工日期: string; 预计完工日期: string;
|
||||
'生产周期(天)': number; BOM版本: string; 单据状态: string;
|
||||
}
|
||||
export interface WorkOrderMaterial {
|
||||
序号: number; 工单号: string; 来源销售订单号: string; 产品编码: string; 材料编码: string;
|
||||
规格型号: string | null; 计量单位: string; 工单数量: number; 单位用量: number; 损耗率: number | null;
|
||||
应领数量: number; 预出仓库: string; 材料来源: string; BOM版本: string; 子件BOM: string | null;
|
||||
}
|
||||
export interface PurchaseOrder {
|
||||
序号: number; 采购订单号: string; 采购日期: string; 来源销售订单号: string; 产品工单号: string;
|
||||
供应商编码: string; 供应商简称: string; 材料编码: string; 数量: number; 单价: number;
|
||||
含税金额: number; 预计到货日期: string; 订单状态: string; 来源单据: string;
|
||||
}
|
||||
export interface Customer {
|
||||
序号: number; 客户编码: string; 客户简称: string; 性质: string; 客户分类: string;
|
||||
所属类别: string; 分管部门: string | null; 订单笔数: number; 订单金额: number;
|
||||
}
|
||||
export interface Supplier {
|
||||
序号: number; 供应商编码: string; 供应商简称: string; 性质: string; 所属类别: string;
|
||||
分管部门: string | null; 采购行数: number; 采购金额: number;
|
||||
}
|
||||
export interface Item {
|
||||
序号: number; 物料编码: string; 类型: string; 规格型号: string | null;
|
||||
计量单位: string; BOM版本: string | null; 数据来源: string;
|
||||
}
|
||||
|
||||
export const salesOrders = salesOrdersRaw as unknown as SalesOrder[];
|
||||
export const productionOrders = productionOrdersRaw as unknown as ProductionOrder[];
|
||||
export const workOrderMaterials = workOrderMaterialsRaw as unknown as WorkOrderMaterial[];
|
||||
export const purchaseOrders = purchaseOrdersRaw as unknown as PurchaseOrder[];
|
||||
export const customers = customersRaw as unknown as Customer[];
|
||||
export const suppliers = suppliersRaw as unknown as Supplier[];
|
||||
export const items = itemsRaw as unknown as Item[];
|
||||
|
||||
/** 单据全链路追溯:给定销售订单号,返回 工单 → 材料需求 → 采购订单 */
|
||||
export function traceSalesOrder(soNo: string) {
|
||||
const so = salesOrders.find(s => s.销售订单号 === soNo) ?? null;
|
||||
const wo = productionOrders.filter(p => p.来源销售订单号 === soNo);
|
||||
const mats = workOrderMaterials.filter(m => m.来源销售订单号 === soNo);
|
||||
const pos = purchaseOrders.filter(p => p.来源销售订单号 === soNo);
|
||||
return { salesOrder: so, workOrders: wo, materials: mats, purchaseOrders: pos };
|
||||
}
|
||||
|
||||
/** 供需汇总:按材料编码聚合应领数量与已采购数量,用于供应计划缺口分析 */
|
||||
export function materialBalance() {
|
||||
const demand = new Map<string, number>();
|
||||
workOrderMaterials.forEach(m =>
|
||||
demand.set(m.材料编码, (demand.get(m.材料编码) ?? 0) + m.应领数量));
|
||||
const supplied = new Map<string, number>();
|
||||
purchaseOrders.forEach(p =>
|
||||
supplied.set(p.材料编码, (supplied.get(p.材料编码) ?? 0) + p.数量));
|
||||
const codes = new Set([...demand.keys(), ...supplied.keys()]);
|
||||
return [...codes].map(code => ({
|
||||
材料编码: code,
|
||||
应领数量: +(demand.get(code) ?? 0).toFixed(2),
|
||||
已采购数量: +(supplied.get(code) ?? 0).toFixed(2),
|
||||
缺口: +((demand.get(code) ?? 0) - (supplied.get(code) ?? 0)).toFixed(2),
|
||||
})).sort((a, b) => b.缺口 - a.缺口);
|
||||
}
|
||||
|
||||
export {
|
||||
inventorySnapshots, purchaseReceipts, productionPicking, workOrderReports, salesDeliveries,
|
||||
type InventorySnapshot, type PurchaseReceipt, type ProductionPicking, type WorkOrderReport, type SalesDelivery,
|
||||
} from './mock-state';
|
||||
|
||||
export {
|
||||
itemMasters, workCenterCalendars, supplierPerformances, bomVersions,
|
||||
type ItemMaster, type WorkCenterCalendar, type SupplierPerformance, type BOMVersion,
|
||||
} from './mock-master';
|
||||
@@ -0,0 +1,632 @@
|
||||
[
|
||||
{
|
||||
"序号": 1,
|
||||
"物料编码": "BA028",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 2,
|
||||
"物料编码": "BA284",
|
||||
"类型": "材料",
|
||||
"规格型号": "10*8*3.5cm",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 3,
|
||||
"物料编码": "BA285",
|
||||
"类型": "材料",
|
||||
"规格型号": "10*8*3.5cm",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 4,
|
||||
"物料编码": "BA296",
|
||||
"类型": "材料",
|
||||
"规格型号": "10*8*3.5cm",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 5,
|
||||
"物料编码": "BA380",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 6,
|
||||
"物料编码": "BD006",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 7,
|
||||
"物料编码": "BDBG01",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 8,
|
||||
"物料编码": "BG-001",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 9,
|
||||
"物料编码": "BJ-5341",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 10,
|
||||
"物料编码": "BJ040",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 11,
|
||||
"物料编码": "BKC026",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 12,
|
||||
"物料编码": "BKC027",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 13,
|
||||
"物料编码": "BKC028",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 14,
|
||||
"物料编码": "BN001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 15,
|
||||
"物料编码": "BN002",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 16,
|
||||
"物料编码": "BZA25090-1",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "KG",
|
||||
"BOM版本": "V1.0",
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 17,
|
||||
"物料编码": "FABG001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 18,
|
||||
"物料编码": "FABJ008",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 19,
|
||||
"物料编码": "FAFP011",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 20,
|
||||
"物料编码": "FAJZ0005",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 21,
|
||||
"物料编码": "FANBLA011",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 22,
|
||||
"物料编码": "FANBLA012",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 23,
|
||||
"物料编码": "FANBLA057",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 24,
|
||||
"物料编码": "FASJ052",
|
||||
"类型": "材料",
|
||||
"规格型号": "50*45*32.5",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 25,
|
||||
"物料编码": "FASJ056",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 26,
|
||||
"物料编码": "FASJLH024",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 27,
|
||||
"物料编码": "FASJLH026",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 28,
|
||||
"物料编码": "FASTN001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 29,
|
||||
"物料编码": "FASTN002",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 30,
|
||||
"物料编码": "FAXTL022",
|
||||
"类型": "材料",
|
||||
"规格型号": "31*25.5*27",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 31,
|
||||
"物料编码": "FAZSM007",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 32,
|
||||
"物料编码": "FAZSM011",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 33,
|
||||
"物料编码": "FBBXD007",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 34,
|
||||
"物料编码": "FBBXM029",
|
||||
"类型": "材料",
|
||||
"规格型号": "35*25.3cm",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 35,
|
||||
"物料编码": "FCBG001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 36,
|
||||
"物料编码": "FEDRF015",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 37,
|
||||
"物料编码": "FEJZ005",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 38,
|
||||
"物料编码": "FESJLH023",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 39,
|
||||
"物料编码": "FESJLH025",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 40,
|
||||
"物料编码": "FEXTL012",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 41,
|
||||
"物料编码": "FFJLY022",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 42,
|
||||
"物料编码": "FFJLY026",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 43,
|
||||
"物料编码": "FFSJ022",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "BOM展开"
|
||||
},
|
||||
{
|
||||
"序号": 44,
|
||||
"物料编码": "FFSJ023",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 45,
|
||||
"物料编码": "FFZSM001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 46,
|
||||
"物料编码": "FFZSM004",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 47,
|
||||
"物料编码": "FHBSJLH024",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 48,
|
||||
"物料编码": "FHCJZ001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 49,
|
||||
"物料编码": "FHSTN001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 50,
|
||||
"物料编码": "FHSTN002",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 51,
|
||||
"物料编码": "FHSTN003",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 52,
|
||||
"物料编码": "FHSTN004",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 53,
|
||||
"物料编码": "FLBG001",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 54,
|
||||
"物料编码": "FMD007",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 55,
|
||||
"物料编码": "FMD019",
|
||||
"类型": "材料",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "采购需求反推"
|
||||
},
|
||||
{
|
||||
"序号": 56,
|
||||
"物料编码": "FP-LJD-2",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 57,
|
||||
"物料编码": "GJQ5001",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 58,
|
||||
"物料编码": "GJQ6001",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 59,
|
||||
"物料编码": "GSH007-C-029KC",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 60,
|
||||
"物料编码": "GSL023-M1",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 61,
|
||||
"物料编码": "JDJZ-0987",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 62,
|
||||
"物料编码": "LHGB006",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 63,
|
||||
"物料编码": "LHGB008",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 64,
|
||||
"物料编码": "LSMM031",
|
||||
"类型": "成品",
|
||||
"规格型号": "25cm*55m*0.9s",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": "V1.0",
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 65,
|
||||
"物料编码": "SJ-LBT-5898",
|
||||
"类型": "成品",
|
||||
"规格型号": "10*8*3.5cm*6片",
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": "v1.0",
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 66,
|
||||
"物料编码": "SJ-LBT-5911",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 67,
|
||||
"物料编码": "XJB-9734",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 68,
|
||||
"物料编码": "XJB-9749",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 69,
|
||||
"物料编码": "XTL-0109",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
},
|
||||
{
|
||||
"序号": 70,
|
||||
"物料编码": "XTL-0110",
|
||||
"类型": "成品",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"BOM版本": null,
|
||||
"数据来源": "销售订单/生产工单"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,115 @@
|
||||
import type { Item, ProductionOrder, PurchaseOrder, WorkOrderMaterial } from '.';
|
||||
import itemsRaw from './items.json';
|
||||
import productionOrdersRaw from './production_orders.json';
|
||||
import purchaseOrdersRaw from './purchase_orders.json';
|
||||
import workOrderMaterialsRaw from './work_order_materials.json';
|
||||
|
||||
const items = itemsRaw as unknown as Item[];
|
||||
const productionOrders = productionOrdersRaw as unknown as ProductionOrder[];
|
||||
const purchaseOrders = purchaseOrdersRaw as unknown as PurchaseOrder[];
|
||||
const workOrderMaterials = workOrderMaterialsRaw as unknown as WorkOrderMaterial[];
|
||||
|
||||
export interface ItemMaster {
|
||||
物料编码: string;
|
||||
标准提前期: number; // 天
|
||||
批量规则: string; // "FOQ" / "LFL" / "POQ-7"
|
||||
最小订货量: number;
|
||||
替代料: string[]; // 物料编码数组
|
||||
}
|
||||
|
||||
export interface WorkCenterCalendar {
|
||||
工作中心: string; // 生产车间
|
||||
日期: string;
|
||||
可用产能: number; // 小时
|
||||
已排产能: number; // 小时
|
||||
}
|
||||
|
||||
export interface SupplierPerformance {
|
||||
供应商编码: string;
|
||||
物料编码: string;
|
||||
配额: number; // 0~1
|
||||
历史准时率: number; // 0~1
|
||||
平均交付周期: number; // 天
|
||||
}
|
||||
|
||||
export interface BOMVersion {
|
||||
父件编码: string;
|
||||
版本: string;
|
||||
子件编码: string;
|
||||
单位用量: number;
|
||||
损耗率: number;
|
||||
}
|
||||
|
||||
const AS_OF = '2026-10-17';
|
||||
const seeded = (s: string) => {
|
||||
let h = 0;
|
||||
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
|
||||
return () => {
|
||||
h = (h * 1664525 + 1013904223) >>> 0;
|
||||
return h / 0xffffffff;
|
||||
};
|
||||
};
|
||||
|
||||
export const itemMasters: ItemMaster[] = items.map(i => {
|
||||
const rng = seeded(i.物料编码);
|
||||
const lot = rng() < 0.33 ? 'LFL' : rng() < 0.66 ? 'FOQ' : 'POQ-7';
|
||||
const moq = Math.round(rng() * 500);
|
||||
// 为 20% 物料生成 0~1 个替代料
|
||||
const alternates: string[] = [];
|
||||
if (rng() < 0.2) {
|
||||
const others = items.filter(x => x.物料编码 !== i.物料编码 && x.类型 === i.类型);
|
||||
const pick = others[Math.floor(rng() * others.length)];
|
||||
if (pick) alternates.push(pick.物料编码);
|
||||
}
|
||||
return {
|
||||
物料编码: i.物料编码,
|
||||
标准提前期: Math.round(7 + rng() * 35),
|
||||
批量规则: lot,
|
||||
最小订货量: moq,
|
||||
替代料: alternates,
|
||||
};
|
||||
});
|
||||
|
||||
export const workCenterCalendars: WorkCenterCalendar[] = (() => {
|
||||
const centers = [...new Set(productionOrders.map(w => w.生产车间))];
|
||||
const out: WorkCenterCalendar[] = [];
|
||||
const start = new Date(`${AS_OF}T00:00:00Z`);
|
||||
for (let d = 0; d < 45; d++) {
|
||||
const date = new Date(start.getTime() + d * 86400000);
|
||||
const ds = date.toISOString().slice(0, 10);
|
||||
centers.forEach(c => {
|
||||
const rng = seeded(`${c}|${ds}`);
|
||||
const cap = Math.round(8 + rng() * 8); // 8~16 小时/天
|
||||
const used = Math.round(cap * rng() * 0.85);
|
||||
out.push({ 工作中心: c, 日期: ds, 可用产能: cap, 已排产能: used });
|
||||
});
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
export const supplierPerformances: SupplierPerformance[] = (() => {
|
||||
const pairs = [...new Set(purchaseOrders.map(p => `${p.供应商编码}|${p.材料编码}`))];
|
||||
return pairs.map(key => {
|
||||
const [sup, mat] = key.split('|');
|
||||
const rng = seeded(key);
|
||||
return {
|
||||
供应商编码: sup, 物料编码: mat,
|
||||
配额: 1, // 本批全部单源,后续可扩展
|
||||
历史准时率: Math.round((0.6 + rng() * 0.38) * 100) / 100,
|
||||
平均交付周期: Math.round(7 + rng() * 35),
|
||||
};
|
||||
});
|
||||
})();
|
||||
|
||||
export const bomVersions: BOMVersion[] = (() => {
|
||||
const out: BOMVersion[] = [];
|
||||
const bomProducts = [...new Set(workOrderMaterials.filter(m => m.材料来源 === 'BOM展开').map(m => m.产品编码))];
|
||||
bomProducts.forEach(prod => {
|
||||
const mats = workOrderMaterials.filter(m => m.产品编码 === prod && m.材料来源 === 'BOM展开');
|
||||
mats.forEach(m => out.push({
|
||||
父件编码: prod, 版本: m.BOM版本 || 'v1.0', 子件编码: m.材料编码,
|
||||
单位用量: m.单位用量, 损耗率: m.损耗率 ?? 0,
|
||||
}));
|
||||
});
|
||||
return out;
|
||||
})();
|
||||
@@ -0,0 +1,126 @@
|
||||
import type {
|
||||
SalesOrder, ProductionOrder, WorkOrderMaterial, PurchaseOrder,
|
||||
} from '.';
|
||||
import salesOrdersRaw from './sales_orders.json';
|
||||
import productionOrdersRaw from './production_orders.json';
|
||||
import workOrderMaterialsRaw from './work_order_materials.json';
|
||||
import purchaseOrdersRaw from './purchase_orders.json';
|
||||
|
||||
const salesOrders = salesOrdersRaw as unknown as SalesOrder[];
|
||||
const productionOrders = productionOrdersRaw as unknown as ProductionOrder[];
|
||||
const workOrderMaterials = workOrderMaterialsRaw as unknown as WorkOrderMaterial[];
|
||||
const purchaseOrders = purchaseOrdersRaw as unknown as PurchaseOrder[];
|
||||
|
||||
export interface InventorySnapshot {
|
||||
物料编码: string;
|
||||
仓库名称: string;
|
||||
现存量: number;
|
||||
已分配量: number;
|
||||
安全库存: number;
|
||||
在途入库: number;
|
||||
快照日: string;
|
||||
}
|
||||
|
||||
export interface PurchaseReceipt {
|
||||
采购订单号: string;
|
||||
材料编码: string;
|
||||
收货日期: string | null; // null 表示未到货
|
||||
收货数量: number;
|
||||
}
|
||||
|
||||
export interface ProductionPicking {
|
||||
工单号: string;
|
||||
材料编码: string;
|
||||
领料日期: string | null;
|
||||
领料数量: number;
|
||||
}
|
||||
|
||||
export interface WorkOrderReport {
|
||||
工单号: string;
|
||||
实际开工日期: string | null;
|
||||
实际完工日期: string | null;
|
||||
合格数量: number | null;
|
||||
报废数量: number;
|
||||
}
|
||||
|
||||
export interface SalesDelivery {
|
||||
销售订单号: string;
|
||||
出库日期: string | null;
|
||||
出库数量: number;
|
||||
}
|
||||
|
||||
const AS_OF = '2026-10-17';
|
||||
|
||||
/** 简单确定性伪随机:同一输入永远得到同一输出,保证刷新不跳变 */
|
||||
const seeded = (s: string) => {
|
||||
let h = 0;
|
||||
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) >>> 0;
|
||||
return () => {
|
||||
h = (h * 1664525 + 1013904223) >>> 0;
|
||||
return h / 0xffffffff;
|
||||
};
|
||||
};
|
||||
|
||||
export const inventorySnapshots: InventorySnapshot[] = (() => {
|
||||
const map = new Map<string, InventorySnapshot>();
|
||||
workOrderMaterials.forEach(m => {
|
||||
const key = `${m.材料编码}|${m.预出仓库}`;
|
||||
if (!map.has(key)) {
|
||||
const rng = seeded(key);
|
||||
const req = m.应领数量;
|
||||
// 现存量覆盖应领的 0~150%,让部分物料出现缺口
|
||||
const onHand = Math.round(req * (rng() * 1.5) * 100) / 100;
|
||||
const allocated = Math.round(req * rng() * 100) / 100;
|
||||
const safety = Math.round(req * 0.1 * 100) / 100;
|
||||
const inTransit = Math.round(req * rng() * 0.6 * 100) / 100;
|
||||
map.set(key, {
|
||||
物料编码: m.材料编码, 仓库名称: m.预出仓库,
|
||||
现存量: onHand, 已分配量: allocated, 安全库存: safety, 在途入库: inTransit, 快照日: AS_OF,
|
||||
});
|
||||
}
|
||||
});
|
||||
return [...map.values()];
|
||||
})();
|
||||
|
||||
export const purchaseReceipts: PurchaseReceipt[] = purchaseOrders.map(p => {
|
||||
const eta = new Date(`${p.预计到货日期}T00:00:00`).getTime();
|
||||
const asOf = new Date(`${AS_OF}T00:00:00`).getTime();
|
||||
// 只有已生效(审批通过)的采购订单行才可能被收货,且到货日早于快照日并按 30% 概率命中
|
||||
const received = p.订单状态 === '生效' && seeded(p.采购订单号 + p.材料编码)() < 0.3 && eta < asOf;
|
||||
return {
|
||||
采购订单号: p.采购订单号, 材料编码: p.材料编码,
|
||||
收货日期: received ? p.预计到货日期 : null,
|
||||
收货数量: received ? p.数量 : 0,
|
||||
};
|
||||
});
|
||||
|
||||
export const productionPicking: ProductionPicking[] = workOrderMaterials.map(m => {
|
||||
const wo = productionOrders.find(w => w.工单号 === m.工单号);
|
||||
// 生产工单 JSON 中 单据状态 为 "已下达" 或 "已完工"
|
||||
const started = wo && (wo.单据状态 === '已下达' || wo.单据状态 === '已完工');
|
||||
const picked = started && seeded(m.工单号 + m.材料编码)() > 0.2;
|
||||
return {
|
||||
工单号: m.工单号, 材料编码: m.材料编码,
|
||||
领料日期: picked ? (wo?.预计开工日期 ?? null) : null,
|
||||
领料数量: picked ? m.应领数量 : 0,
|
||||
};
|
||||
});
|
||||
|
||||
export const workOrderReports: WorkOrderReport[] = productionOrders.map(w => ({
|
||||
工单号: w.工单号,
|
||||
// 生产工单 JSON 中 单据状态 为 "已下达" 或 "已完工"
|
||||
实际开工日期: w.单据状态 === '已下达' || w.单据状态 === '已完工' ? w.预计开工日期 : null,
|
||||
实际完工日期: w.单据状态 === '已完工' ? w.预计完工日期 : null,
|
||||
合格数量: w.单据状态 === '已完工' ? w.生产数量 : null,
|
||||
报废数量: 0,
|
||||
}));
|
||||
|
||||
export const salesDeliveries: SalesDelivery[] = salesOrders.map(s => {
|
||||
// 销售订单 JSON 中 单据状态 只有 "生效",用计划发货日是否已过 AS_OF 来模拟是否已出库
|
||||
const delivered = s.预计发货日期 <= AS_OF && seeded(s.销售订单号)() < 0.3;
|
||||
return {
|
||||
销售订单号: s.销售订单号,
|
||||
出库日期: delivered ? s.预计发货日期 : null,
|
||||
出库数量: delivered ? s.数量 : 0,
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
[
|
||||
{
|
||||
"序号": 1,
|
||||
"工单号": "WO-W202610161037",
|
||||
"来源销售订单号": "W202610161037",
|
||||
"产品编码": "GSH007-C-029KC",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 2880,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-11-04",
|
||||
"预计完工日期": "2026-11-11",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 2,
|
||||
"工单号": "WO-W202610161036",
|
||||
"来源销售订单号": "W202610161036",
|
||||
"产品编码": "GSL023-M1",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 2690,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-12-19",
|
||||
"预计完工日期": "2026-12-26",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 3,
|
||||
"工单号": "WO-L20261015638",
|
||||
"来源销售订单号": "L20261015638",
|
||||
"产品编码": "XTL-0110",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 7200,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-27",
|
||||
"预计完工日期": "2026-11-06",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 4,
|
||||
"工单号": "WO-L20261015637",
|
||||
"来源销售订单号": "L20261015637",
|
||||
"产品编码": "XTL-0109",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 4800,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-30",
|
||||
"预计完工日期": "2026-11-06",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 5,
|
||||
"工单号": "WO-L20261014635",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品编码": "JDJZ-0987",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 5000,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-29",
|
||||
"预计完工日期": "2026-11-08",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 6,
|
||||
"工单号": "WO-L20261014634",
|
||||
"来源销售订单号": "L20261014634",
|
||||
"产品编码": "GJQ5001",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 19980,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-24",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 7,
|
||||
"工单号": "WO-W202610141021",
|
||||
"来源销售订单号": "W202610141021",
|
||||
"产品编码": "FP-LJD-2",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 24000,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-20",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 14,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 8,
|
||||
"工单号": "WO-L20261014631",
|
||||
"来源销售订单号": "L20261014631",
|
||||
"产品编码": "SJ-LBT-5911",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 10080,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-24",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 9,
|
||||
"工单号": "WO-L20261014630",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品编码": "SJ-LBT-5898",
|
||||
"规格型号": "10*8*3.5cm*6片",
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 10080,
|
||||
"生产车间": "手工包装组",
|
||||
"预计开工日期": "2026-10-24",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "v1.0",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 10,
|
||||
"工单号": "WO-L20261012621",
|
||||
"来源销售订单号": "L20261012621",
|
||||
"产品编码": "GJQ6001",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 10080,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-24",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 11,
|
||||
"工单号": "WO-Z20261013492",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品编码": "BG-001",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 5000,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-11-01",
|
||||
"预计完工日期": "2026-11-11",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 12,
|
||||
"工单号": "WO-WC20261013060",
|
||||
"来源销售订单号": "WC20261013060",
|
||||
"产品编码": "LHGB008",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 4800,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-28",
|
||||
"预计完工日期": "2026-11-04",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 13,
|
||||
"工单号": "WO-W202610131020",
|
||||
"来源销售订单号": "W202610131020",
|
||||
"产品编码": "LHGB006",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 4800,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-28",
|
||||
"预计完工日期": "2026-11-04",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 14,
|
||||
"工单号": "WO-W202610131017",
|
||||
"来源销售订单号": "W202610131017",
|
||||
"产品编码": "XJB-9734",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 9990,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-24",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 10,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 15,
|
||||
"工单号": "WO-W202610131016",
|
||||
"来源销售订单号": "W202610131016",
|
||||
"产品编码": "XJB-9749",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 20010,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-10-20",
|
||||
"预计完工日期": "2026-11-03",
|
||||
"生产周期(天)": 14,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 16,
|
||||
"工单号": "WO-Z20261012490",
|
||||
"来源销售订单号": "Z20261012490",
|
||||
"产品编码": "BJ-5341",
|
||||
"规格型号": null,
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 3600,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-11-03",
|
||||
"预计完工日期": "2026-11-10",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "—",
|
||||
"单据状态": "已下达"
|
||||
},
|
||||
{
|
||||
"序号": 17,
|
||||
"工单号": "WO-W20260629448",
|
||||
"来源销售订单号": "W20260629448",
|
||||
"产品编码": "LSMM031",
|
||||
"规格型号": "25cm*55m*0.9s",
|
||||
"计量单位": "PCS",
|
||||
"生产数量": 4504,
|
||||
"生产车间": "分卷组",
|
||||
"预计开工日期": "2026-07-14",
|
||||
"预计完工日期": "2026-07-21",
|
||||
"生产周期(天)": 7,
|
||||
"BOM版本": "V1.0",
|
||||
"单据状态": "已完工"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,866 @@
|
||||
[
|
||||
{
|
||||
"序号": 1,
|
||||
"采购订单号": "PO-2026-06-0319",
|
||||
"采购日期": "2026-06-30",
|
||||
"来源销售订单号": "W20260629448",
|
||||
"产品工单号": "WO-W20260629448",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FAXTL022",
|
||||
"数量": 150,
|
||||
"单价": 1.97,
|
||||
"含税金额": 295.5,
|
||||
"预计到货日期": "2026-07-07",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 2,
|
||||
"采购订单号": "PO-2026-06-0329",
|
||||
"采购日期": "2026-06-30",
|
||||
"来源销售订单号": "W20260629448",
|
||||
"产品工单号": "WO-W20260629448",
|
||||
"供应商编码": "GC0012",
|
||||
"供应商简称": "GTZG",
|
||||
"材料编码": "FBBXM029",
|
||||
"数量": 1000,
|
||||
"单价": 0.22,
|
||||
"含税金额": 220,
|
||||
"预计到货日期": "2026-07-07",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 3,
|
||||
"采购订单号": "PO-2026-10-0128",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "W202610131020",
|
||||
"产品工单号": "WO-W202610131020",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FESJLH023",
|
||||
"数量": 4800,
|
||||
"单价": 0.12,
|
||||
"含税金额": 576,
|
||||
"预计到货日期": "2026-10-20",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 4,
|
||||
"采购订单号": "PO-2026-10-0128",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "WC20261013060",
|
||||
"产品工单号": "WO-WC20261013060",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FESJLH025",
|
||||
"数量": 4800,
|
||||
"单价": 0.12,
|
||||
"含税金额": 576,
|
||||
"预计到货日期": "2026-10-19",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 5,
|
||||
"采购订单号": "PO-2026-10-0128",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "W202610131020",
|
||||
"产品工单号": "WO-W202610131020",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHBSJLH024",
|
||||
"数量": 400,
|
||||
"单价": 0.022,
|
||||
"含税金额": 8.8,
|
||||
"预计到货日期": "2026-10-20",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 6,
|
||||
"采购订单号": "PO-2026-10-0132",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "W202610131020",
|
||||
"产品工单号": "WO-W202610131020",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FASJLH024",
|
||||
"数量": 200,
|
||||
"单价": 2.15,
|
||||
"含税金额": 430,
|
||||
"预计到货日期": "2026-10-20",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 7,
|
||||
"采购订单号": "PO-2026-10-0132",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "WC20261013060",
|
||||
"产品工单号": "WO-WC20261013060",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FASJLH026",
|
||||
"数量": 200,
|
||||
"单价": 2.78,
|
||||
"含税金额": 556,
|
||||
"预计到货日期": "2026-10-19",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 8,
|
||||
"采购订单号": "PO-2026-10-0135",
|
||||
"采购日期": "2026-10-14",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品工单号": "WO-Z20261013492",
|
||||
"供应商编码": "GE0001",
|
||||
"供应商简称": "JJBT",
|
||||
"材料编码": "BDBG01",
|
||||
"数量": 4800,
|
||||
"单价": 0.82,
|
||||
"含税金额": 3936,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 9,
|
||||
"采购订单号": "PO-2026-10-0136",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品工单号": "WO-Z20261013492",
|
||||
"供应商编码": "GC0055",
|
||||
"供应商简称": "YCSDFQJLBZYXGS",
|
||||
"材料编码": "FLBG001",
|
||||
"数量": 5000,
|
||||
"单价": 0.052,
|
||||
"含税金额": 260,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 10,
|
||||
"采购订单号": "PO-2026-10-0138",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品工单号": "WO-L20261014630",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BA284",
|
||||
"数量": 19460,
|
||||
"单价": 0.3,
|
||||
"含税金额": 5838,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 11,
|
||||
"采购订单号": "PO-2026-10-0138",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品工单号": "WO-L20261014630",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BA285",
|
||||
"数量": 19860,
|
||||
"单价": 0.3,
|
||||
"含税金额": 5958,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 12,
|
||||
"采购订单号": "PO-2026-10-0138",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品工单号": "WO-L20261014630",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BA296",
|
||||
"数量": 19860,
|
||||
"单价": 0.3,
|
||||
"含税金额": 5958,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 13,
|
||||
"采购订单号": "PO-2026-10-0138",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品工单号": "WO-Z20261013492",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BA380",
|
||||
"数量": 10000,
|
||||
"单价": 0.5,
|
||||
"含税金额": 5000,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 14,
|
||||
"采购订单号": "PO-2026-10-0139",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品工单号": "WO-Z20261013492",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FCBG001",
|
||||
"数量": 5000,
|
||||
"单价": 0.08,
|
||||
"含税金额": 400,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 15,
|
||||
"采购订单号": "PO-2026-10-0139",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "W202610141021",
|
||||
"产品工单号": "WO-W202610141021",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FEDRF015",
|
||||
"数量": 21000,
|
||||
"单价": 0.078,
|
||||
"含税金额": 1638,
|
||||
"预计到货日期": "2026-10-22",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 16,
|
||||
"采购订单号": "PO-2026-10-0140",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014631",
|
||||
"产品工单号": "WO-L20261014631",
|
||||
"供应商编码": "GE0070",
|
||||
"供应商简称": "ZJGHYRJSTYXGS",
|
||||
"材料编码": "BN001",
|
||||
"数量": 9790,
|
||||
"单价": 1.65,
|
||||
"含税金额": 16153.5,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 17,
|
||||
"采购订单号": "PO-2026-10-0140",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014631",
|
||||
"产品工单号": "WO-L20261014631",
|
||||
"供应商编码": "GE0070",
|
||||
"供应商简称": "ZJGHYRJSTYXGS",
|
||||
"材料编码": "BN002",
|
||||
"数量": 10080,
|
||||
"单价": 1.65,
|
||||
"含税金额": 16632,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 18,
|
||||
"采购订单号": "PO-2026-10-0141",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261012621",
|
||||
"产品工单号": "WO-L20261012621",
|
||||
"供应商编码": "GC0079",
|
||||
"供应商简称": "YCDFWYYSBZYXGS",
|
||||
"材料编码": "FFJLY026",
|
||||
"数量": 30000,
|
||||
"单价": 0.176,
|
||||
"含税金额": 5280,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 19,
|
||||
"采购订单号": "PO-2026-10-0145",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品工单号": "WO-L20261014630",
|
||||
"供应商编码": "GC0020",
|
||||
"供应商简称": "WXSXHYSYXGS",
|
||||
"材料编码": "FFSJ022",
|
||||
"数量": 10080,
|
||||
"单价": 0.26,
|
||||
"含税金额": 2620.8,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 20,
|
||||
"采购订单号": "PO-2026-10-0145",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014631",
|
||||
"产品工单号": "WO-L20261014631",
|
||||
"供应商编码": "GC0020",
|
||||
"供应商简称": "WXSXHYSYXGS",
|
||||
"材料编码": "FFSJ023",
|
||||
"数量": 10080,
|
||||
"单价": 0.17,
|
||||
"含税金额": 1713.6,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 21,
|
||||
"采购订单号": "PO-2026-10-0146",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261012621",
|
||||
"产品工单号": "WO-L20261012621",
|
||||
"供应商编码": "GE0005",
|
||||
"供应商简称": "JSYJ",
|
||||
"材料编码": "GJQ6001",
|
||||
"数量": 10080,
|
||||
"单价": 1.8,
|
||||
"含税金额": 18144,
|
||||
"预计到货日期": "2026-11-05",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 22,
|
||||
"采购订单号": "PO-2026-10-0147",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261013492",
|
||||
"产品工单号": "WO-Z20261013492",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FABG001",
|
||||
"数量": 50,
|
||||
"单价": 5.35,
|
||||
"含税金额": 267.5,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 23,
|
||||
"采购订单号": "PO-2026-10-0148",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "W202610141021",
|
||||
"产品工单号": "WO-W202610141021",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FAFP011",
|
||||
"数量": 800,
|
||||
"单价": 2.11,
|
||||
"含税金额": 1688,
|
||||
"预计到货日期": "2026-10-24",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 24,
|
||||
"采购订单号": "PO-2026-10-0148",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014630",
|
||||
"产品工单号": "WO-L20261014630",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FASJ052",
|
||||
"数量": 280,
|
||||
"单价": 4.7,
|
||||
"含税金额": 1316,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 25,
|
||||
"采购订单号": "PO-2026-10-0148",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014631",
|
||||
"产品工单号": "WO-L20261014631",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FASJ056",
|
||||
"数量": 280,
|
||||
"单价": 1.88,
|
||||
"含税金额": 526.4,
|
||||
"预计到货日期": "2026-10-31",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 26,
|
||||
"采购订单号": "PO-2026-10-0149",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "WC20261013060",
|
||||
"产品工单号": "WO-WC20261013060",
|
||||
"供应商编码": "GE0047",
|
||||
"供应商简称": "RYSYTZYXGS",
|
||||
"材料编码": "LHGB008",
|
||||
"数量": 4800,
|
||||
"单价": 5.96,
|
||||
"含税金额": 28608,
|
||||
"预计到货日期": "2026-11-06",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 27,
|
||||
"采购订单号": "PO-2026-10-0153",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261012490",
|
||||
"产品工单号": "WO-Z20261012490",
|
||||
"供应商编码": "GE0009",
|
||||
"供应商简称": "SZYL",
|
||||
"材料编码": "BKC026",
|
||||
"数量": 3600,
|
||||
"单价": 0.66,
|
||||
"含税金额": 2376,
|
||||
"预计到货日期": "2026-11-12",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 28,
|
||||
"采购订单号": "PO-2026-10-0153",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261012490",
|
||||
"产品工单号": "WO-Z20261012490",
|
||||
"供应商编码": "GE0009",
|
||||
"供应商简称": "SZYL",
|
||||
"材料编码": "BKC027",
|
||||
"数量": 3600,
|
||||
"单价": 0.66,
|
||||
"含税金额": 2376,
|
||||
"预计到货日期": "2026-11-12",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 29,
|
||||
"采购订单号": "PO-2026-10-0153",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "Z20261012490",
|
||||
"产品工单号": "WO-Z20261012490",
|
||||
"供应商编码": "GE0009",
|
||||
"供应商简称": "SZYL",
|
||||
"材料编码": "BKC028",
|
||||
"数量": 3600,
|
||||
"单价": 0.66,
|
||||
"含税金额": 2376,
|
||||
"预计到货日期": "2026-11-12",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 30,
|
||||
"采购订单号": "PO-2026-10-0156",
|
||||
"采购日期": "2026-10-15",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品工单号": "WO-L20261014635",
|
||||
"供应商编码": "GC0011",
|
||||
"供应商简称": "YLZG",
|
||||
"材料编码": "FBBXD007",
|
||||
"数量": 5000,
|
||||
"单价": 0.146,
|
||||
"含税金额": 730,
|
||||
"预计到货日期": "2026-11-01",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 31,
|
||||
"采购订单号": "PO-2026-10-0159",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610131017",
|
||||
"产品工单号": "WO-W202610131017",
|
||||
"供应商编码": "GC0032",
|
||||
"供应商简称": "JSLBXCLKJYXGS",
|
||||
"材料编码": "FMD007",
|
||||
"数量": 29970,
|
||||
"单价": 0.012,
|
||||
"含税金额": 359.64,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 32,
|
||||
"采购订单号": "PO-2026-10-0159",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品工单号": "WO-L20261014635",
|
||||
"供应商编码": "GC0032",
|
||||
"供应商简称": "JSLBXCLKJYXGS",
|
||||
"材料编码": "FMD019",
|
||||
"数量": 5000,
|
||||
"单价": 0.046,
|
||||
"含税金额": 230,
|
||||
"预计到货日期": "2026-11-01",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 33,
|
||||
"采购订单号": "PO-2026-10-0160",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品工单号": "WO-L20261014635",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FEJZ005",
|
||||
"数量": 5000,
|
||||
"单价": 0.09,
|
||||
"含税金额": 450,
|
||||
"预计到货日期": "2026-11-01",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 34,
|
||||
"采购订单号": "PO-2026-10-0160",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品工单号": "WO-L20261014635",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHCJZ001",
|
||||
"数量": 10000,
|
||||
"单价": 0.023,
|
||||
"含税金额": 230,
|
||||
"预计到货日期": "2026-11-01",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 35,
|
||||
"采购订单号": "PO-2026-10-0162",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014634",
|
||||
"产品工单号": "WO-L20261014634",
|
||||
"供应商编码": "GC0079",
|
||||
"供应商简称": "YCDFWYYSBZYXGS",
|
||||
"材料编码": "FFJLY022",
|
||||
"数量": 19980,
|
||||
"单价": 0.245,
|
||||
"含税金额": 4895.1,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 36,
|
||||
"采购订单号": "PO-2026-10-0162",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610131017",
|
||||
"产品工单号": "WO-W202610131017",
|
||||
"供应商编码": "GC0079",
|
||||
"供应商简称": "YCDFWYYSBZYXGS",
|
||||
"材料编码": "FFZSM001",
|
||||
"数量": 9990,
|
||||
"单价": 0.165,
|
||||
"含税金额": 1648.35,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 37,
|
||||
"采购订单号": "PO-2026-10-0162",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610131016",
|
||||
"产品工单号": "WO-W202610131016",
|
||||
"供应商编码": "GC0079",
|
||||
"供应商简称": "YCDFWYYSBZYXGS",
|
||||
"材料编码": "FFZSM004",
|
||||
"数量": 20010,
|
||||
"单价": 0.283,
|
||||
"含税金额": 5662.83,
|
||||
"预计到货日期": "2026-10-29",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 38,
|
||||
"采购订单号": "PO-2026-10-0164",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014634",
|
||||
"产品工单号": "WO-L20261014634",
|
||||
"供应商编码": "GE0005",
|
||||
"供应商简称": "JSYJ",
|
||||
"材料编码": "GJQ5001",
|
||||
"数量": 19980,
|
||||
"单价": 2.57,
|
||||
"含税金额": 51348.6,
|
||||
"预计到货日期": "2026-11-05",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 39,
|
||||
"采购订单号": "PO-2026-10-0165",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "Z20261012490",
|
||||
"产品工单号": "WO-Z20261012490",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FABJ008",
|
||||
"数量": 120,
|
||||
"单价": 2.29,
|
||||
"含税金额": 274.8,
|
||||
"预计到货日期": "2026-11-12",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 40,
|
||||
"采购订单号": "PO-2026-10-0166",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610131017",
|
||||
"产品工单号": "WO-W202610131017",
|
||||
"供应商编码": "GC0078",
|
||||
"供应商简称": "JSXYYWKJYXGS",
|
||||
"材料编码": "FAZSM007",
|
||||
"数量": 333,
|
||||
"单价": 2.43,
|
||||
"含税金额": 809.19,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 41,
|
||||
"采购订单号": "PO-2026-10-0166",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610131016",
|
||||
"产品工单号": "WO-W202610131016",
|
||||
"供应商编码": "GC0078",
|
||||
"供应商简称": "JSXYYWKJYXGS",
|
||||
"材料编码": "FAZSM011",
|
||||
"数量": 667,
|
||||
"单价": 4.41,
|
||||
"含税金额": 2941.47,
|
||||
"预计到货日期": "2026-10-29",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 42,
|
||||
"采购订单号": "PO-2026-10-0168",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261014635",
|
||||
"产品工单号": "WO-L20261014635",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FAJZ0005",
|
||||
"数量": 250,
|
||||
"单价": 3.26,
|
||||
"含税金额": 815,
|
||||
"预计到货日期": "2026-11-07",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 43,
|
||||
"采购订单号": "PO-2026-10-0171",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015637",
|
||||
"产品工单号": "WO-L20261015637",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BA028",
|
||||
"数量": 19200,
|
||||
"单价": 0.35,
|
||||
"含税金额": 6720,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 44,
|
||||
"采购订单号": "PO-2026-10-0171",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015638",
|
||||
"产品工单号": "WO-L20261015638",
|
||||
"供应商编码": "GE0004",
|
||||
"供应商简称": "HFHM",
|
||||
"材料编码": "BD006",
|
||||
"数量": 7200,
|
||||
"单价": 0.3296,
|
||||
"含税金额": 2373.12,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 45,
|
||||
"采购订单号": "PO-2026-10-0175",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610161036",
|
||||
"产品工单号": "WO-W202610161036",
|
||||
"供应商编码": "GE0021",
|
||||
"供应商简称": "KJSL",
|
||||
"材料编码": "BJ040",
|
||||
"数量": 2690,
|
||||
"单价": 4.1,
|
||||
"含税金额": 11029,
|
||||
"预计到货日期": "2026-12-01",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 46,
|
||||
"采购订单号": "PO-2026-10-0176",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610161037",
|
||||
"产品工单号": "WO-W202610161037",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FANBLA011",
|
||||
"数量": 60,
|
||||
"单价": 1.55,
|
||||
"含税金额": 93,
|
||||
"预计到货日期": "2026-10-26",
|
||||
"订单状态": "未审",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 47,
|
||||
"采购订单号": "PO-2026-10-0176",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610161037",
|
||||
"产品工单号": "WO-W202610161037",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FANBLA012",
|
||||
"数量": 20,
|
||||
"单价": 5.54,
|
||||
"含税金额": 110.8,
|
||||
"预计到货日期": "2026-10-26",
|
||||
"订单状态": "未审",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 48,
|
||||
"采购订单号": "PO-2026-10-0176",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "W202610161036",
|
||||
"产品工单号": "WO-W202610161036",
|
||||
"供应商编码": "GC0040",
|
||||
"供应商简称": "YCSDFJCZXYXGS",
|
||||
"材料编码": "FANBLA057",
|
||||
"数量": 56,
|
||||
"单价": 4.94,
|
||||
"含税金额": 276.64,
|
||||
"预计到货日期": "2026-12-01",
|
||||
"订单状态": "未审",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 49,
|
||||
"采购订单号": "PO-2026-10-0177",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015637",
|
||||
"产品工单号": "WO-L20261015637",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FASTN001",
|
||||
"数量": 400,
|
||||
"单价": 2.11,
|
||||
"含税金额": 844,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 50,
|
||||
"采购订单号": "PO-2026-10-0177",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015638",
|
||||
"产品工单号": "WO-L20261015638",
|
||||
"供应商编码": "GC0001",
|
||||
"供应商简称": "FYBZ",
|
||||
"材料编码": "FASTN002",
|
||||
"数量": 300,
|
||||
"单价": 2.2655,
|
||||
"含税金额": 679.65,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 51,
|
||||
"采购订单号": "PO-2026-10-0179",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015637",
|
||||
"产品工单号": "WO-L20261015637",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHSTN001",
|
||||
"数量": 800,
|
||||
"单价": 0.05,
|
||||
"含税金额": 40,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 52,
|
||||
"采购订单号": "PO-2026-10-0179",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015637",
|
||||
"产品工单号": "WO-L20261015637",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHSTN002",
|
||||
"数量": 800,
|
||||
"单价": 0.1,
|
||||
"含税金额": 80,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 53,
|
||||
"采购订单号": "PO-2026-10-0179",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015638",
|
||||
"产品工单号": "WO-L20261015638",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHSTN003",
|
||||
"数量": 600,
|
||||
"单价": 0.05,
|
||||
"含税金额": 30,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
},
|
||||
{
|
||||
"序号": 54,
|
||||
"采购订单号": "PO-2026-10-0179",
|
||||
"采购日期": "2026-10-16",
|
||||
"来源销售订单号": "L20261015638",
|
||||
"产品工单号": "WO-L20261015638",
|
||||
"供应商编码": "GC0003",
|
||||
"供应商简称": "JSFY",
|
||||
"材料编码": "FHSTN004",
|
||||
"数量": 600,
|
||||
"单价": 0.1,
|
||||
"含税金额": 60,
|
||||
"预计到货日期": "2026-10-30",
|
||||
"订单状态": "生效",
|
||||
"来源单据": "请购单"
|
||||
}
|
||||
]
|
||||