新增模块

This commit is contained in:
2026-10-18 15:27:02 +08:00
parent 5b7d1e8f64
commit f2e6d2b3f1
228 changed files with 46089 additions and 11 deletions
+172
View File
@@ -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
}
]
+177
View File
@@ -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;
}
+89
View File
@@ -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';
+632
View File
@@ -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",
"订单状态": "生效",
"来源单据": "请购单"
}
]
@@ -0,0 +1,274 @@
[
{
"序号": 1,
"销售订单号": "W202610161037",
"单据日期": "2026-10-16",
"客户编码": "KA0033",
"客户分类": "OEM开票",
"客户简称": "NBLARYPYXGS",
"产品编码": "GSH007-C-029KC",
"数量": 2880,
"含税单价": 0.62,
"含税金额": 1785.6,
"预计发货日期": "2026-11-13",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 2,
"销售订单号": "W202610161036",
"单据日期": "2026-10-15",
"客户编码": "KA0033",
"客户分类": "OEM开票",
"客户简称": "NBLARYPYXGS",
"产品编码": "GSL023-M1",
"数量": 2690,
"含税单价": 5.47,
"含税金额": 14714.3,
"预计发货日期": "2026-12-28",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 3,
"销售订单号": "L20261015638",
"单据日期": "2026-10-15",
"客户编码": "KA0124",
"客户分类": "OEM开票",
"客户简称": "TJSTNGJMYYXGS",
"产品编码": "XTL-0110",
"数量": 7200,
"含税单价": 2.6,
"含税金额": 18720,
"预计发货日期": "2026-11-08",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 4,
"销售订单号": "L20261015637",
"单据日期": "2026-10-15",
"客户编码": "KA0124",
"客户分类": "OEM开票",
"客户简称": "TJSTNGJMYYXGS",
"产品编码": "XTL-0109",
"数量": 4800,
"含税单价": 2.55,
"含税金额": 12240,
"预计发货日期": "2026-11-08",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 5,
"销售订单号": "L20261014635",
"单据日期": "2026-10-15",
"客户编码": "GM0045",
"客户分类": "杂项开票",
"客户简称": "YCSFHWLYXGS",
"产品编码": "JDJZ-0987",
"数量": 5000,
"含税单价": 10.7,
"含税金额": 53500,
"预计发货日期": "2026-11-10",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 6,
"销售订单号": "L20261014634",
"单据日期": "2026-10-15",
"客户编码": "GM0045",
"客户分类": "杂项开票",
"客户简称": "YCSFHWLYXGS",
"产品编码": "GJQ5001",
"数量": 19980,
"含税单价": 4.36,
"含税金额": 87112.8,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 7,
"销售订单号": "W202610141021",
"单据日期": "2026-10-14",
"客户编码": "KA0090",
"客户分类": "OEM开票",
"客户简称": "KCTZ(ZG)YXGS",
"产品编码": "FP-LJD-2",
"数量": 24000,
"含税单价": 4.8,
"含税金额": 115200,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 8,
"销售订单号": "L20261014631",
"单据日期": "2026-10-14",
"客户编码": "KA0116",
"客户分类": "OEM开票",
"客户简称": "NBJQHYGMYXGS",
"产品编码": "SJ-LBT-5911",
"数量": 10080,
"含税单价": 5.25,
"含税金额": 52920,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 9,
"销售订单号": "L20261014630",
"单据日期": "2026-10-14",
"客户编码": "KA0116",
"客户分类": "OEM开票",
"客户简称": "NBJQHYGMYXGS",
"产品编码": "SJ-LBT-5898",
"数量": 10080,
"含税单价": 3.63,
"含税金额": 36590.4,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 10,
"销售订单号": "L20261012621",
"单据日期": "2026-10-14",
"客户编码": "KA0049",
"客户分类": "OEM开票",
"客户简称": "ZJJLYZFZPXSYXGS",
"产品编码": "GJQ6001",
"数量": 10080,
"含税单价": 2.73,
"含税金额": 27518.4,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 11,
"销售订单号": "Z20261013492",
"单据日期": "2026-10-13",
"客户编码": "KA0210",
"客户分类": "OEM开票",
"客户简称": "BGGGCZ(GZ)YXGS",
"产品编码": "BG-001",
"数量": 5000,
"含税单价": 4.37,
"含税金额": 21850,
"预计发货日期": "2026-11-13",
"仓库名称": "OEM事业部成品仓",
"制单人": "赵广粉",
"单据状态": "生效"
},
{
"序号": 12,
"销售订单号": "WC20261013060",
"单据日期": "2026-10-13",
"客户编码": "KA0099",
"客户分类": "OEM开票",
"客户简称": "ZJSJLHWLPSYXGS",
"产品编码": "LHGB008",
"数量": 4800,
"含税单价": 7.9,
"含税金额": 37920,
"预计发货日期": "2026-11-06",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 13,
"销售订单号": "W202610131020",
"单据日期": "2026-10-13",
"客户编码": "KA0099",
"客户分类": "OEM开票",
"客户简称": "ZJSJLHWLPSYXGS",
"产品编码": "LHGB006",
"数量": 4800,
"含税单价": 5.1,
"含税金额": 24480,
"预计发货日期": "2026-11-06",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 14,
"销售订单号": "W202610131017",
"单据日期": "2026-10-13",
"客户编码": "KA0162",
"客户分类": "OEM开票",
"客户简称": "ZSMGYL(SY)YXGS",
"产品编码": "XJB-9734",
"数量": 9990,
"含税单价": 2.79,
"含税金额": 27872.1,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 15,
"销售订单号": "W202610131016",
"单据日期": "2026-10-13",
"客户编码": "KA0162",
"客户分类": "OEM开票",
"客户简称": "ZSMGYL(SY)YXGS",
"产品编码": "XJB-9749",
"数量": 20010,
"含税单价": 4.7,
"含税金额": 94047,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 16,
"销售订单号": "Z20261012490",
"单据日期": "2026-10-12",
"客户编码": "KA0154",
"客户分类": "OEM开票",
"客户简称": "HNZQNGYLGLYXGS",
"产品编码": "BJ-5341",
"数量": 3600,
"含税单价": 3.9,
"含税金额": 14040,
"预计发货日期": "2026-11-12",
"仓库名称": "OEM事业部成品仓",
"制单人": "赵广粉",
"单据状态": "生效"
},
{
"序号": 17,
"销售订单号": "W20260629448",
"单据日期": "2026-06-29",
"客户编码": "KA0087",
"客户分类": "OEM开票",
"客户简称": "LSMMJJYP(ZJ)YXGS",
"产品编码": "LSMM031",
"数量": 4504,
"含税单价": 2.406,
"含税金额": 10836.62,
"预计发货日期": "2026-07-23",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
}
]
@@ -0,0 +1,172 @@
[
{
"序号": 1,
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 6,
"采购金额": 3051.95
},
{
"序号": 2,
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 11,
"采购金额": 4088.8
},
{
"序号": 3,
"供应商编码": "GC0011",
"供应商简称": "YLZG",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 730
},
{
"序号": 4,
"供应商编码": "GC0012",
"供应商简称": "GTZG",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 220
},
{
"序号": 5,
"供应商编码": "GC0020",
"供应商简称": "WXSXHYSYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 4334.4
},
{
"序号": 6,
"供应商编码": "GC0032",
"供应商简称": "JSLBXCLKJYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 589.64
},
{
"序号": 7,
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 8,
"采购金额": 5121.34
},
{
"序号": 8,
"供应商编码": "GC0055",
"供应商简称": "YCSDFQJLBZYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 260
},
{
"序号": 9,
"供应商编码": "GC0078",
"供应商简称": "JSXYYWKJYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 3750.66
},
{
"序号": 10,
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 4,
"采购金额": 17486.28
},
{
"序号": 11,
"供应商编码": "GE0001",
"供应商简称": "JJBT",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 3936
},
{
"序号": 12,
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 6,
"采购金额": 31847.12
},
{
"序号": 13,
"供应商编码": "GE0005",
"供应商简称": "JSYJ",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 69492.6
},
{
"序号": 14,
"供应商编码": "GE0009",
"供应商简称": "SZYL",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 3,
"采购金额": 7128
},
{
"序号": 15,
"供应商编码": "GE0021",
"供应商简称": "KJSL",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 11029
},
{
"序号": 16,
"供应商编码": "GE0047",
"供应商简称": "RYSYTZYXGS",
"性质": "客户/供应商",
"所属类别": "外购半成品开票",
"分管部门": null,
"采购行数": 1,
"采购金额": 28608
},
{
"序号": 17,
"供应商编码": "GE0070",
"供应商简称": "ZJGHYRJSTYXGS",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 32785.5
}
]
File diff suppressed because it is too large Load Diff
+768
View File
@@ -0,0 +1,768 @@
import {
customers, items, productionOrders, purchaseOrders, salesOrders, suppliers,
workOrderMaterials,
inventorySnapshots, purchaseReceipts, productionPicking, workOrderReports,
itemMasters, supplierPerformances,
type Customer, type Item, type ProductionOrder, type PurchaseOrder,
type SalesOrder, type Supplier, type WorkOrderMaterial,
} from './ibp';
import { money } from '../lib/money';
/**
* 业务本体(Ontology)层:把 Excel 五张单据表抽象成「对象—关系—规则—动作」四件套。
* 所有实例数、关系基数、规则命中数都在这里从原始单据实时算出,页面不写死任何统计数字。
* 金额文案统一走 `lib/money`(1 位小数),与左右栏卡片、对话回答卡同一口径。
* 数据快照日与风险报告保持一致:2026-10-17。
*/
export const ONTOLOGY_AS_OF = '2026-10-17';
export type AttrType = 'string' | 'number' | 'date' | 'enum';
export interface OntAttr { name: string; en: string; type: AttrType; required: boolean; note?: string }
export interface OntInstance {
id: string; title: string; sub: string; meta: string;
amount?: number; badge?: string; tone?: 'success' | 'warning' | 'danger' | 'info';
}
export interface OntObject {
id: string; name: string; en: string; desc: string; source: string;
color: string; attrs: OntAttr[]; instances: () => OntInstance[];
}
export interface OntRelation {
id: string; from: string; to: string; name: string; cardinality: string;
key: string; desc: string; count: () => number;
}
export type Severity = 'error' | 'warning' | 'info';
/** 语义色档位:组件层按这个键去主题 token 里取色,深浅主题各有一套 */
export type Tone = 'success' | 'warning' | 'danger' | 'info';
export interface OntRule {
id: string; name: string; severity: Severity; on: string; expr: string; desc: string;
/** 数据缺口规则跑不出结果,标灰而不是标绿 */
blocked?: boolean;
hits: () => { n: number; unit: string; targets: string[] };
}
export type ActionType = 'query' | 'alert' | 'report' | 'workflow';
export interface OntAction {
id: string; name: string; en: string; object: string; type: ActionType;
trigger: string; desc: string; targets?: () => string[];
}
/* ── 小工具:属性元组展开、日期差、金额 ───────────────────────────────── */
type T = [string, string, AttrType] | [string, string, AttrType, 0 | 1] | [string, string, AttrType, 0 | 1, string];
const attrs = (list: T[]): OntAttr[] =>
list.map(([name, en, type, req, note]) => ({ name, en, type, required: req === 1, note }));
const day = (s: string) => new Date(`${s}T00:00:00`).getTime();
const diff = (a: string, b: string) => Math.round((day(a) - day(b)) / 86400000);
const AS_OF_TS = day(ONTOLOGY_AS_OF);
/** 采购订单头:按采购订单号归并,齐套日取组内**最晚**到货日(首行会低估,最大差 18 天) */
export interface PurchaseGroup {
no: string; date: string; supplier: string; supplierCode: string; so: string;
lines: number; amount: number; lastArrival: string; firstArrival: string; unapproved: number;
}
export function purchaseGroups(): PurchaseGroup[] {
const map = new Map<string, PurchaseGroup>();
purchaseOrders.forEach((p: PurchaseOrder) => {
let g = map.get(p.采购订单号);
if (!g) {
g = {
no: p.采购订单号, date: p.采购日期, supplier: p.供应商简称, supplierCode: p.供应商编码,
so: p.来源销售订单号, lines: 0, amount: 0, lastArrival: p.预计到货日期,
firstArrival: p.预计到货日期, unapproved: 0,
};
map.set(p.采购订单号, g);
}
g.lines += 1;
g.amount += p.含税金额;
if (p.预计到货日期 > g.lastArrival) g.lastArrival = p.预计到货日期;
if (p.预计到货日期 < g.firstArrival) g.firstArrival = p.预计到货日期;
if (p.订单状态 !== '生效') g.unapproved += 1;
});
return [...map.values()].sort((a, b) => (a.date < b.date ? 1 : -1));
}
/** 销售订单 → 工单 → 采购 的关键路径中间量,规则层、关系层与对话回答引擎共用同一份计算 */
export interface PathRow {
so: SalesOrder; wo: ProductionOrder; lines: PurchaseOrder[];
lastArrival: string; kitLag: number; critLag: number; buffer: number;
toFinish: number; unfinished: boolean; unapproved: number;
}
export function paths(): PathRow[] {
return buildPaths(salesOrders, productionOrders, purchaseOrders, ONTOLOGY_AS_OF);
}
/**
* 关键路径中间量的通用实现:给定「单据集合 + 截止日」即可算。
* 当期走 ERP 导出的真实单据,历史回放月走 history.ts 生成的同构单据,
* 两边共用这套口径,红黄绿才是规则算出来的而不是画出来的。
*/
export function buildPaths(
sos: SalesOrder[],
wos: ProductionOrder[],
pos: PurchaseOrder[],
asOf: string,
): PathRow[] {
const woBySo = new Map(wos.map(w => [w.来源销售订单号, w]));
const poBySo = new Map<string, PurchaseOrder[]>();
pos.forEach(p => {
const arr = poBySo.get(p.来源销售订单号) ?? [];
arr.push(p);
poBySo.set(p.来源销售订单号, arr);
});
const asOfTs = day(asOf);
return sos
.filter(s => woBySo.has(s.销售订单号))
.map(s => {
const w = woBySo.get(s.销售订单号)!;
const ps = poBySo.get(s.销售订单号) ?? [];
const lastArrival = ps.reduce((a, p) => (p.预计到货日期 > a ? p.预计到货日期 : a), '');
return {
so: s, wo: w, lines: ps,
lastArrival,
/** 齐套日 − 计划开工:正数=开工时料未到齐 */
kitLag: lastArrival ? diff(lastArrival, w.预计开工日期) : 0,
/** 齐套日 − 计划完工:正数=按现排程必然延期 */
critLag: lastArrival ? diff(lastArrival, w.预计完工日期) : 0,
/** 交期缓冲:完工日距发货日还有几天 */
buffer: diff(s.预计发货日期, w.预计完工日期),
/** 距计划完工剩余天数(负数=已超期) */
toFinish: Math.round((day(w.预计完工日期) - asOfTs) / 86400000),
unfinished: w.单据状态 !== '已完工',
unapproved: ps.filter(p => p.订单状态 !== '生效').length,
};
});
}
/** 模块级快照:规则层与对话层读同一份,避免每次调用重算 */
export const PATH = paths();
export interface ChainNode {
objectId: string; // 本体对象 id:so/wo/wom/mat/po/sup/cus/wh
instanceId: string; // 实例 id
label: string;
sub: string;
tone: Tone;
/** 悬停面板要展示的多行指标:key→value */
metrics: Record<string, string>;
}
export interface ChainEdge {
relationId: string;
fromObjectId: string; fromInstanceId: string;
toObjectId: string; toInstanceId: string;
}
export interface FulfillmentChain {
soNo: string;
nodes: ChainNode[];
edges: ChainEdge[];
summary: {
level: Tone;
text: string;
redFlags: string[];
};
}
const fmtDateDelta = (d: number) => (d > 0 ? `+${d} 天` : `${d} 天`);
export function chainFor(soNo: string): FulfillmentChain {
const so = salesOrders.find(s => s.销售订单号 === soNo);
if (!so) return { soNo, nodes: [], edges: [], summary: { level: 'info', text: '未找到销售订单', redFlags: [] } };
const wo = productionOrders.find(w => w.来源销售订单号 === soNo);
const mats = workOrderMaterials.filter(m => m.来源销售订单号 === soNo);
const pos = purchaseOrders.filter(p => p.来源销售订单号 === soNo);
const groups = purchaseGroups().filter(g => g.so === soNo);
const cus = customers.find(c => c.客户编码 === so.客户编码);
const item = items.find(i => i.物料编码 === so.产品编码);
const path = PATH.find(p => p.so.销售订单号 === soNo);
const redFlags: string[] = [];
// 显式 guard:销售订单若无对应工单,链路即存在断链,不能报 success
if (!wo) {
redFlags.push('未找到关联生产工单');
}
const nodeMap = new Map<string, ChainNode>();
const toneRank: Record<Tone, number> = { danger: 3, warning: 2, info: 1, success: 0 };
const addNode = (n: ChainNode) => {
const key = `${n.objectId}|${n.instanceId}`;
const existing = nodeMap.get(key);
if (!existing) {
nodeMap.set(key, n);
return;
}
const mergedMetrics = { ...n.metrics, ...existing.metrics };
const mergedTone = toneRank[n.tone] > toneRank[existing.tone] ? n.tone : existing.tone;
nodeMap.set(key, { ...existing, metrics: mergedMetrics, tone: mergedTone });
};
const edges: ChainEdge[] = [];
// 销售订单节点
const soTone: Tone = !wo ? 'danger'
: path?.critLag && path.critLag > 0 ? 'danger'
: path?.kitLag && path.kitLag > 0 ? 'warning'
: 'success';
if (path?.critLag && path.critLag > 0) redFlags.push(`关键路径冲突:齐套日晚于完工日 ${path.critLag} 天`);
else if (path?.kitLag && path.kitLag > 0) redFlags.push(`齐套延迟:开工时料未到齐 ${path.kitLag} 天`);
addNode({
objectId: 'so', instanceId: so.销售订单号, label: so.销售订单号,
sub: `${so.客户简称} · ${so.产品编码}`, tone: soTone,
metrics: {
交期: so.预计发货日期,
数量: `${so.数量.toLocaleString()} PCS`,
金额: money(so.含税金额),
缓冲: path ? fmtDateDelta(path.buffer) : '—',
状态: so.单据状态,
},
});
// 客户
if (cus) {
addNode({
objectId: 'cus', instanceId: cus.客户编码, label: cus.客户简称,
sub: cus.客户编码, tone: 'info',
metrics: { 性质: cus.性质, 分类: cus.客户分类, 订单金额: money(cus.订单金额) },
});
edges.push({ relationId: 'r-cus-so', fromObjectId: 'cus', fromInstanceId: cus.客户编码, toObjectId: 'so', toInstanceId: so.销售订单号 });
}
// 成品物料
if (item) {
const master = itemMasters.find(m => m.物料编码 === item.物料编码);
addNode({
objectId: 'mat', instanceId: item.物料编码, label: item.物料编码,
sub: `${item.类型} · ${item.计量单位}`, tone: 'info',
metrics: {
规格: item.规格型号 || '—',
标准提前期: master ? `${master.标准提前期} 天` : '—',
批量规则: master?.批量规则 || '—',
替代料: master?.替代料.join(', ') || '无',
},
});
// 连接销售订单 → 成品物料(避免与下方的 so→wo 边重复)
edges.push({ relationId: 'r-so-mat', fromObjectId: 'so', fromInstanceId: so.销售订单号, toObjectId: 'mat', toInstanceId: item.物料编码 });
}
// 生产工单
if (wo) {
const report = workOrderReports.find(r => r.工单号 === wo.工单号);
const woTone: Tone = path?.critLag && path.critLag > 0 ? 'danger'
: path?.kitLag && path.kitLag > 0 ? 'warning'
: wo.单据状态 === '已完工' ? 'success' : 'info';
addNode({
objectId: 'wo', instanceId: wo.工单号, label: wo.工单号,
sub: `${wo.生产车间} · ${wo.生产数量} PCS`, tone: woTone,
metrics: {
计划开工: wo.预计开工日期,
计划完工: wo.预计完工日期,
生产周期: `${wo['生产周期(天)']} 天`,
实际完工: report?.实际完工日期 || '未回报',
BOM: wo.BOM版本 || '—',
},
});
edges.push({ relationId: 'r-so-wo', fromObjectId: 'so', fromInstanceId: so.销售订单号, toObjectId: 'wo', toInstanceId: wo.工单号 });
// 工单材料
mats.forEach(m => {
const matItem = items.find(i => i.物料编码 === m.材料编码);
const master = itemMasters.find(i => i.物料编码 === m.材料编码);
const inv = inventorySnapshots.find(s => s.物料编码 === m.材料编码 && s.仓库名称 === m.预出仓库);
const pick = productionPicking.find(p => p.工单号 === m.工单号 && p.材料编码 === m.材料编码);
// 缺料判断:需求 > 可用(现存量 - 已分配 + 在途)视为缺口
const usable = inv ? inv.现存量 - inv.已分配量 + inv.在途入库 : 0;
const gap = Math.max(0, +(m.应领数量 - usable - (pick?.领料数量 ?? 0)).toFixed(2));
const womTone: Tone = gap > 0 ? 'danger' : pick?.领料日期 ? 'success' : 'info';
if (gap > 0) redFlags.push(`缺料:${m.材料编码} 缺口 ${gap.toFixed(1)} ${m.计量单位}`);
addNode({
objectId: 'wom', instanceId: `${m.工单号}-${m.材料编码}-${m.序号}`, label: m.材料编码,
sub: `${m.材料来源} · 应领 ${m.应领数量}`, tone: womTone,
metrics: {
应领数量: `${m.应领数量} ${m.计量单位}`,
现存量: inv ? `${inv.现存量}(${m.预出仓库})` : '无库存数据',
已分配: inv ? String(inv.已分配量) : '—',
在途入库: inv ? String(inv.在途入库) : '—',
已领料: pick?.领料日期 ? `${pick.领料数量} @ ${pick.领料日期}` : '未领',
缺口: gap > 0 ? `${gap.toFixed(1)} ${m.计量单位}` : '无',
标准提前期: master ? `${master.标准提前期} 天` : '—',
},
});
edges.push({ relationId: 'r-wo-wom', fromObjectId: 'wo', fromInstanceId: wo.工单号, toObjectId: 'wom', toInstanceId: `${m.工单号}-${m.材料编码}-${m.序号}` });
// 材料→物料
if (matItem) {
addNode({
objectId: 'mat', instanceId: matItem.物料编码, label: matItem.物料编码,
sub: `${matItem.类型} · ${matItem.计量单位}`, tone: 'success',
metrics: { 类型: matItem.类型, 数据来源: matItem.数据来源 },
});
edges.push({ relationId: 'r-wom-mat', fromObjectId: 'wom', fromInstanceId: `${m.工单号}-${m.材料编码}-${m.序号}`, toObjectId: 'mat', toInstanceId: matItem.物料编码 });
}
});
}
// 采购订单组
groups.forEach(g => {
const sup = suppliers.find(s => s.供应商编码 === g.supplierCode);
const groupLines = pos.filter(p => p.采购订单号 === g.no);
const perfs = groupLines
.map(p => supplierPerformances.find(sp => sp.供应商编码 === g.supplierCode && sp.物料编码 === p.材料编码))
.filter((sp): sp is NonNullable<typeof sp> => !!sp);
const avgOntime = perfs.length ? perfs.reduce((a, p) => a + p.历史准时率, 0) / perfs.length : null;
const avgLead = perfs.length ? perfs.reduce((a, p) => a + p.平均交付周期, 0) / perfs.length : null;
const asOf = day(ONTOLOGY_AS_OF);
const overdue = groupLines
.filter(p => day(p.预计到货日期) < asOf)
.some(p => !purchaseReceipts.some(r => r.采购订单号 === p.采购订单号 && r.材料编码 === p.材料编码 && r.收货日期 !== null));
const poTone: Tone = g.unapproved ? 'danger' : overdue ? 'warning' : 'success';
if (g.unapproved) redFlags.push(`采购未审:${g.no} 有 ${g.unapproved} 行未审批`);
if (overdue) redFlags.push(`在途逾期:${g.no} 最晚到货 ${g.lastArrival} 仍未收货`);
addNode({
objectId: 'po', instanceId: g.no, label: g.no,
sub: `${g.supplier} · ${g.lines} 行`, tone: poTone,
metrics: {
采购日期: g.date,
齐套日: g.lastArrival,
金额: money(g.amount),
未审批行: String(g.unapproved),
历史准时率: perfs.length ? `${(avgOntime! * 100).toFixed(0)}%` : '—',
平均交付周期: perfs.length ? `${avgLead!.toFixed(0)} 天` : '—',
},
});
edges.push({ relationId: 'r-po-so', fromObjectId: 'po', fromInstanceId: g.no, toObjectId: 'so', toInstanceId: so.销售订单号 });
if (sup) {
addNode({
objectId: 'sup', instanceId: sup.供应商编码, label: sup.供应商简称,
sub: sup.供应商编码, tone: 'info',
metrics: { 性质: sup.性质, 采购金额: money(sup.采购金额), 采购行数: String(sup.采购行数) },
});
edges.push({ relationId: 'r-sup-po', fromObjectId: 'sup', fromInstanceId: sup.供应商编码, toObjectId: 'po', toInstanceId: g.no });
}
});
const nodes = [...nodeMap.values()];
// 汇总等级
const hasDanger = nodes.some(n => n.tone === 'danger');
const hasWarning = nodes.some(n => n.tone === 'warning');
const summaryLevel: Tone = hasDanger ? 'danger' : hasWarning ? 'warning' : 'success';
const summaryText = redFlags.length
? `本单存在 ${redFlags.length} 项异常`
: '本单当前链路无明显异常';
return { soNo, nodes, edges, summary: { level: summaryLevel, text: summaryText, redFlags } };
}
/* ── 对象 Object ─────────────────────────────────────────────────────── */
export const objects: OntObject[] = [
{
id: 'so', name: '销售订单', en: 'SalesOrder', color: '#818cf8',
desc: '客户下单的履约起点,也是全部风险计算的锚点:交期、数量、金额都挂在它身上。',
source: 'Excel「销售订单」· 2,366 行原表按选取规则抽 17 行',
attrs: attrs([
['序号', 'seq', 'number', 1], ['销售订单号', 'so_no', 'string', 1, '履约链路主键'],
['单据日期', 'doc_date', 'date', 1], ['客户编码', 'cust_code', 'string', 1],
['客户分类', 'cust_class', 'enum'], ['客户简称', 'cust_abbr', 'string', 1, '取往来单位表助记码'],
['产品编码', 'item_code', 'string', 1], ['数量', 'qty', 'number', 1],
['含税单价', 'price_incl_tax', 'number', 1], ['含税金额', 'amount_incl_tax', 'number', 1, '数量 × 含税单价'],
['预计发货日期', 'ship_date', 'date', 1, '交期'], ['仓库名称', 'wh_name', 'string'],
['制单人', 'creator', 'string'], ['单据状态', 'doc_status', 'enum'],
]),
instances: () => salesOrders.map((s: SalesOrder) => ({
id: s.销售订单号, title: s.销售订单号, sub: `${s.客户简称} · ${s.产品编码}`,
meta: `发货 ${s.预计发货日期} · ${s.数量.toLocaleString()} PCS`, amount: s.含税金额,
badge: s.单据状态, tone: 'success' as const,
})),
},
{
id: 'wo', name: '生产工单', en: 'WorkOrder', color: '#38bdf8',
desc: '一张销售订单对应一张工单(工单号 = WO-销售订单号)。开工/完工日期是按交期倒推的模拟字段。',
source: 'Excel「生产工单」· 由销售交期倒推生成',
attrs: attrs([
['序号', 'seq', 'number', 1], ['工单号', 'wo_no', 'string', 1, 'WO-销售订单号'],
['来源销售订单号', 'so_no', 'string', 1], ['产品编码', 'item_code', 'string', 1],
['规格型号', 'spec', 'string', 0, '仅 BOM 样例有值'], ['计量单位', 'uom', 'enum'],
['生产数量', 'qty', 'number', 1], ['生产车间', 'workshop', 'enum', 0, '无 BOM 默认「分卷组」'],
['预计开工日期', 'plan_start', 'date', 1, '模拟推断'], ['预计完工日期', 'plan_finish', 'date', 1, '模拟推断=交期−2天'],
['生产周期(天)', 'cycle_days', 'number', 1, '按数量分档 7/10/14'], ['BOM版本', 'bom_version', 'string'],
['单据状态', 'doc_status', 'enum', 0, '完工日不早于快照日记为已下达'],
]),
instances: () => productionOrders.map((w: ProductionOrder) => ({
id: w.工单号, title: w.工单号, sub: `${w.产品编码} · ${w.生产车间}`,
meta: `${w.预计开工日期} → ${w.预计完工日期} · ${w['生产周期(天)']}天`,
badge: w.单据状态, tone: w.单据状态 === '已完工' ? 'success' as const : 'info' as const,
})),
},
{
id: 'wom', name: '工单材料明细', en: 'WorkOrderMaterial', color: '#34d399',
desc: '工单要领哪些料、各领多少。54/63 行由采购需求反推,只有 9 行来自真实 BOM 展开。',
source: 'Excel「工单材料明细」· BOM 展开 + 采购需求反推',
attrs: attrs([
['序号', 'seq', 'number', 1], ['工单号', 'wo_no', 'string', 1],
['来源销售订单号', 'so_no', 'string', 1], ['产品编码', 'item_code', 'string', 1],
['材料编码', 'mat_code', 'string', 1], ['规格型号', 'spec', 'string'],
['计量单位', 'uom', 'enum', 0, '反推行统一按 PCS'], ['工单数量', 'wo_qty', 'number', 1],
['单位用量', 'unit_usage', 'number', 1, 'BOM 需用量 ÷ BOM 生产数量'],
['损耗率', 'loss_rate', 'number', 0, '54 行为空'], ['应领数量', 'required_qty', 'number', 1, '工单数量 × 单位用量 × (1+损耗率)'],
['预出仓库', 'issue_wh', 'enum'], ['材料来源', 'source_type', 'enum', 1, 'BOM展开 / 采购需求反推'],
['BOM版本', 'bom_version', 'string'], ['子件BOM', 'child_bom', 'string'],
]),
instances: () => workOrderMaterials.map((m: WorkOrderMaterial) => ({
id: `${m.工单号}-${m.材料编码}-${m.序号}`, title: m.材料编码,
sub: `${m.工单号} · ${m.材料来源}`,
meta: `应领 ${m.应领数量.toLocaleString()} ${m.计量单位} · 出 ${m.预出仓库}`,
badge: m.材料来源 === 'BOM展开' ? 'BOM' : '反推',
tone: m.材料来源 === 'BOM展开' ? 'success' as const : 'warning' as const,
})),
},
{
id: 'po', name: '采购订单', en: 'PurchaseOrder', color: '#fbbf24',
desc: '为工单缺口下的采购单,行级带预计到货日期。齐套日必须取组内最晚到货行,取首行最多会低估 18 天。',
source: 'Excel「材料采购订单」· 7,472 行原表抽 54 行 / 29 单',
attrs: attrs([
['序号', 'seq', 'number', 1], ['采购订单号', 'po_no', 'string', 1],
['采购日期', 'po_date', 'date', 1], ['来源销售订单号', 'so_no', 'string', 1],
['产品工单号', 'wo_no', 'string', 1], ['供应商编码', 'sup_code', 'string', 1],
['供应商简称', 'sup_abbr', 'string', 1], ['材料编码', 'mat_code', 'string', 1],
['数量', 'qty', 'number', 1], ['单价', 'price', 'number', 1],
['含税金额', 'amount_incl_tax', 'number', 1], ['预计到货日期', 'eta_date', 'date', 1, '行级,齐套取 MAX'],
['订单状态', 'doc_status', 'enum', 1, '生效 / 未审'], ['来源单据', 'src_doc', 'enum', 0, '本批全部=请购单'],
]),
instances: () => purchaseGroups().map(g => ({
id: g.no, title: g.no, sub: `${g.supplier} · ${g.lines} 行`,
meta: `下单 ${g.date} · 齐套 ${g.lastArrival}`, amount: g.amount,
badge: g.unapproved ? `未审 ${g.unapproved} 行` : '生效',
tone: g.unapproved ? 'danger' as const : 'success' as const,
})),
},
{
id: 'cus', name: '客户', en: 'Customer', color: '#a78bfa',
desc: '本批销售订单涉及的往来客户。订单笔数与金额为表内汇总口径,与销售订单同源可核对。',
source: 'Excel「客户资料」· 由往来单位表(1,003 家)过滤',
attrs: attrs([
['序号', 'seq', 'number', 1], ['客户编码', 'cust_code', 'string', 1],
['客户简称', 'cust_abbr', 'string', 1, '助记码,源表无工商全称'],
['性质', 'nature', 'enum', 1, '客户 / 客户·供应商(客商一体)'],
['客户分类', 'cust_class', 'enum'], ['所属类别', 'category', 'enum'],
['分管部门', 'dept', 'string', 0, '1 家未填'], ['订单笔数', 'so_count', 'number', 1],
['订单金额', 'so_amount', 'number', 1],
]),
instances: () => customers.map((c: Customer) => ({
id: c.客户编码, title: c.客户简称, sub: `${c.客户编码} · ${c.客户分类}`,
meta: `${c.订单笔数} 笔订单 · ${c.分管部门 || '分管部门未填'}`, amount: c.订单金额,
badge: c.性质, tone: 'info' as const,
})),
},
{
id: 'sup', name: '供应商', en: 'Supplier', color: '#f472b6',
desc: '本批采购订单涉及的供货方。采购行数与金额为该供应商在本批的合计。',
source: 'Excel「供应商资料」· 由往来单位表(1,003 家)过滤',
attrs: attrs([
['序号', 'seq', 'number', 1], ['供应商编码', 'sup_code', 'string', 1],
['供应商简称', 'sup_abbr', 'string', 1, '助记码,无工商全称'],
['性质', 'nature', 'enum', 1], ['所属类别', 'category', 'enum'],
['分管部门', 'dept', 'string', 0, '1 家未填'], ['采购行数', 'po_lines', 'number', 1],
['采购金额', 'po_amount', 'number', 1],
]),
instances: () => suppliers.map((s: Supplier) => ({
id: s.供应商编码, title: s.供应商简称, sub: `${s.供应商编码} · ${s.所属类别}`,
meta: `${s.采购行数} 行采购 · ${s.分管部门 || '分管部门未填'}`, amount: s.采购金额,
badge: s.性质, tone: 'info' as const,
})),
},
{
id: 'mat', name: '物料(成品 / 材料)', en: 'Item', color: '#22d3ee',
desc: '销售侧成品与工单侧材料共用一套编码体系;仅 2 个产品有真实 BOM,规格型号大面积缺失。',
source: 'Excel「物料」· 由销售/工单/采购/BOM 汇总去重',
attrs: attrs([
['序号', 'seq', 'number', 1], ['物料编码', 'item_code', 'string', 1],
['类型', 'item_type', 'enum', 1, '成品 / 材料'], ['规格型号', 'spec', 'string', 0, '仅 8/70 有值'],
['计量单位', 'uom', 'enum', 1, '69 PCS + 1 KG'], ['BOM版本', 'bom_version', 'string', 0, '大小写混用 v1.0 / V1.0'],
['数据来源', 'source_type', 'enum', 1, '销售订单/生产工单 · BOM展开 · 采购需求反推'],
]),
instances: () => items.map((i: Item) => ({
id: i.物料编码, title: i.物料编码, sub: `${i.类型} · ${i.计量单位}${i.规格型号 ? ` · ${i.规格型号}` : ''}`,
meta: `${i.数据来源}${i.BOM版本 ? ` · BOM ${i.BOM版本}` : ''}`,
badge: i.类型, tone: i.类型 === '成品' ? 'info' as const : 'success' as const,
})),
},
{
id: 'wh', name: '仓库', en: 'Warehouse', color: '#94a3b8',
desc: '从销售入库仓与工单预出仓库两个方向派生出的仓位节点,本批共 4 个。库存数量字段缺失,仓库目前只是位置节点。',
source: '派生:销售订单.仓库名称 + 工单材料明细.预出仓库',
attrs: attrs([
['仓库名称', 'wh_name', 'string', 1, '源表无仓库编码'],
['角色', 'role', 'enum', 1, '成品入库仓 / 工单预出仓'],
['关联单据行数', 'ref_lines', 'number', 1, '派生统计'],
['现存量', 'onhand_qty', 'number', 0, '数据缺口:源表无此字段'],
['安全库存', 'safety_stock', 'number', 0, '数据缺口'],
]),
instances: () => {
const inWh = new Map<string, number>();
salesOrders.forEach(s => inWh.set(s.仓库名称, (inWh.get(s.仓库名称) ?? 0) + 1));
const outWh = new Map<string, number>();
workOrderMaterials.forEach(m => outWh.set(m.预出仓库, (outWh.get(m.预出仓库) ?? 0) + 1));
return [
...[...inWh].map(([name, n]) => ({
id: `wh-in-${name}`, title: name, sub: '成品入库仓 · 销售订单',
meta: `${n} 张销售订单`, badge: '入库', tone: 'info' as const,
})),
...[...outWh].map(([name, n]) => ({
id: `wh-out-${name}`, title: name, sub: '工单预出仓 · 材料明细',
meta: `${n} 行领料需求`, badge: '预出', tone: 'success' as const,
})),
];
},
},
];
/* ── 关系 Relation ───────────────────────────────────────────────────── */
const matFromPo = new Set(purchaseOrders.map(p => p.材料编码));
const matFromWom = new Set(workOrderMaterials.map(m => m.材料编码));
const supMatPairs = new Set(purchaseOrders.map(p => `${p.供应商编码}|${p.材料编码}`));
export const relations: OntRelation[] = [
{
id: 'r-cus-so', from: 'cus', to: 'so', name: '下单', cardinality: '1:N',
key: '客户编码', desc: '11 家客户共下 17 张销售订单,单客户最多 2 张(选取规则限制)。',
count: () => salesOrders.length,
},
{
id: 'r-so-wo', from: 'so', to: 'wo', name: '生成', cardinality: '1:1',
key: '工单号 = WO-销售订单号', desc: '链路主键可直接推导,17/17 全部吻合,无断链。',
count: () => productionOrders.filter(w => w.工单号 === `WO-${w.来源销售订单号}`).length,
},
{
id: 'r-so-mat', from: 'so', to: 'mat', name: '需求', cardinality: '1:1',
key: '产品编码', desc: '销售订单的产品编码对应成品物料主数据。',
count: () => new Set(salesOrders.map(s => s.产品编码)).size,
},
{
id: 'r-wo-wom', from: 'wo', to: 'wom', name: '展开', cardinality: '1:N',
key: '工单号', desc: '工单按 BOM 或采购需求展开成领料明细,共 63 行。',
count: () => workOrderMaterials.length,
},
{
id: 'r-wom-mat', from: 'wom', to: 'mat', name: '领用', cardinality: 'N:1',
key: '材料编码', desc: '工单需求涉及 56 种材料,其中 54 种能在采购订单里找到。',
count: () => matFromWom.size,
},
{
id: 'r-mat-po', from: 'mat', to: 'po', name: '采购为', cardinality: '1:N',
key: '材料编码', desc: '54 行采购覆盖 54 种材料,每种材料在本批只出现一次。',
count: () => matFromPo.size,
},
{
id: 'r-sup-po', from: 'sup', to: 'po', name: '承接', cardinality: 'N:M',
key: '供应商编码 × 材料编码', desc: '17 家供应商承接 54 行采购;供应商-材料配对 54 组,全部单源。',
count: () => supMatPairs.size,
},
{
id: 'r-po-so', from: 'po', to: 'so', name: '回链', cardinality: 'N:1',
key: '来源销售订单号', desc: '采购行回指销售订单,形成闭环;本批 54/54 行都有来源单号。',
count: () => purchaseOrders.filter(p => !!p.来源销售订单号).length,
},
{
id: 'r-so-wh', from: 'so', to: 'wh', name: '入库', cardinality: 'N:1',
key: '仓库名称', desc: '成品入库仓只有「OEM事业部成品仓」一个节点,无仓位分仓数据。',
count: () => new Set(salesOrders.map(s => s.仓库名称)).size,
},
{
id: 'r-wom-wh', from: 'wom', to: 'wh', name: '预出', cardinality: 'N:1',
key: '预出仓库', desc: '领料从 3 个预出仓发出;反推行的预出仓库按辅料仓等默认值填写。',
count: () => new Set(workOrderMaterials.map(m => m.预出仓库)).size,
},
{
id: 'r-cus-sup', from: 'cus', to: 'sup', name: '客商一体', cardinality: 'N:M',
key: '性质 = 客户/供应商', desc: '1 家客户与 4 家供应商性质为客商一体;客户编码与供应商编码在本批无交集,只能靠性质字段标注。',
count: () => customers.filter(c => c.性质 === '客户/供应商').length + suppliers.filter(s => s.性质 === '客户/供应商').length,
},
];
/* ── 规则 Rule(全部实时计算,命中数会随数据变化) ─────────────────────── */
export const rules: OntRule[] = [
{
id: 'r-crit', name: '关键路径冲突', severity: 'error', on: '销售订单',
expr: 'MAX(采购.预计到货日期) > 工单.预计完工日期',
desc: '料全到齐那天已经晚于计划完工日,按现排程必然延期。',
hits: () => {
const t = PATH.filter(p => p.critLag > 0);
return { n: t.length, unit: '张订单', targets: t.map(p => p.so.销售订单号) };
},
},
{
id: 'r-kit', name: '齐套延迟', severity: 'warning', on: '生产工单',
expr: 'MAX(采购.预计到货日期) > 工单.预计开工日期',
desc: '开工日物料未到齐。缺库存字段,无法用线边库存降噪,命中偏保守。',
hits: () => {
const t = PATH.filter(p => p.kitLag > 0);
return { n: t.length, unit: `张订单(>7天 ${PATH.filter(p => p.kitLag > 7).length})`, targets: t.map(p => p.so.销售订单号) };
},
},
{
id: 'r-approve', name: '采购审批完备', severity: 'error', on: '采购订单',
expr: '采购.订单状态 ≠ 生效',
desc: '未审批的采购行不构成到料承诺,尤其压在长周期物料上时风险最高。',
hits: () => {
const t = purchaseOrders.filter(p => p.订单状态 !== '生效');
return { n: t.length, unit: `行 / ${new Set(t.map(p => p.来源销售订单号)).size} 张订单`, targets: [...new Set(t.map(p => p.来源销售订单号))] };
},
},
{
id: 'r-trace', name: '追溯链完整', severity: 'error', on: '采购订单',
expr: '来源销售订单号为空 或 产品工单号 ≠ WO-销售订单号',
desc: '断链的采购行无法归集到订单,风险敞口会算漏。',
hits: () => {
const t = purchaseOrders.filter(p => !p.来源销售订单号 || p.产品工单号 !== `WO-${p.来源销售订单号}`);
return { n: t.length, unit: '行', targets: [...new Set(t.map(p => p.来源销售订单号))] };
},
},
{
id: 'r-buffer', name: '交期缓冲下限', severity: 'warning', on: '销售订单',
expr: '销售.预计发货日期 − 工单.预计完工日期 < 5 天 且 工单未完工',
desc: '本批缓冲全为 2 天,是模拟排程(完工=交期−2)造成的,接真实排程后才有区分度。',
hits: () => {
const t = PATH.filter(p => p.unfinished && p.buffer < 5);
return { n: t.length, unit: '张订单', targets: t.map(p => p.so.销售订单号) };
},
},
{
id: 'r-overdue', name: '采购在途逾期', severity: 'warning', on: '采购订单',
expr: '采购.预计到货日期 < 快照日 且 未收到货',
desc: '源表只有 生效/未审 两种状态、没有收货字段,因此只能提疑、不能定案。',
hits: () => {
const t = purchaseOrders.filter(p => {
if (day(p.预计到货日期) >= AS_OF_TS) return false;
const received = purchaseReceipts.some(r => r.采购订单号 === p.采购订单号 && r.材料编码 === p.材料编码 && r.收货日期 !== null);
return !received;
});
return { n: t.length, unit: `行 ${money(t.reduce((a, p) => a + p.含税金额, 0))}`, targets: [...new Set(t.map(p => p.来源销售订单号))] };
},
},
{
id: 'r-missing-po', name: '漏采核查', severity: 'error', on: '工单材料明细',
expr: 'BOM 展开材料 ∉ 采购订单材料集合',
desc: '只有 2 张单有真 BOM 可做这项检验;其余 15 张的需求本身由采购反推,属循环论证,不计入。',
hits: () => {
const t = [...matFromWom].filter(m => !matFromPo.has(m));
const so = [...new Set(workOrderMaterials.filter(m => t.includes(m.材料编码)).map(m => m.来源销售订单号))];
return { n: t.length, unit: `种材料 · ${so.length} 张订单`, targets: so };
},
},
{
id: 'r-bom', name: 'BOM 完备性', severity: 'warning', on: '生产工单',
expr: '工单.BOM版本 为空或「—」',
desc: '无 BOM 的工单,其材料需求不可信,风险结论要降置信度。',
hits: () => {
const t = productionOrders.filter(w => !w.BOM版本 || w.BOM版本 === '—');
return { n: t.length, unit: `张工单 / ${productionOrders.length}`, targets: t.map(w => w.来源销售订单号) };
},
},
{
id: 'r-single', name: '单源供应', severity: 'info', on: '供应商',
expr: 'COUNT(DISTINCT 供应商) GROUP BY 材料 = 1',
desc: '本批 54 种材料全部只有一家供应商,指标无区分度(等于全员告警),需接物料主数据的多源配额才有意义。',
hits: () => ({ n: matFromPo.size, unit: '种材料单源', targets: [] }),
},
{
id: 'r-stock', name: '库存可用量校验', severity: 'error', on: '仓库',
expr: '需求数量 ≤ 现存量 − 已分配 + 在途入库',
desc: '数据缺口:源表无现存量、已分配、安全库存、在途入库,规则无法执行。',
blocked: true,
hits: () => ({ n: 0, unit: '无法计算(缺 4 个字段)', targets: [] }),
},
];
/* ── 动作 Action ─────────────────────────────────────────────────────── */
const ruleTargets = (id: string) => rules.find(r => r.id === id)!.hits().targets;
export const actions: OntAction[] = [
{
id: 'a-expedite', name: '催料提醒', en: 'expedite_material', object: '采购订单', type: 'alert',
trigger: '规则「齐套延迟」命中', desc: '向供应商发出到货确认,按最晚到货行逐行催料。',
targets: () => ruleTargets('r-kit'),
},
{
id: 'a-approve', name: '推进采购审批', en: 'push_po_approval', object: '采购订单', type: 'workflow',
trigger: '规则「采购审批完备」命中', desc: '把未审行推给采购科,优先处理交付周期最长的物料。',
targets: () => ruleTargets('r-approve'),
},
{
id: 'a-reschedule', name: '重排开工日', en: 'reschedule_start', object: '生产工单', type: 'workflow',
trigger: '规则「关键路径冲突」命中', desc: '把开工日后移到齐套日之后,或申请压缩生产周期。',
targets: () => ruleTargets('r-crit'),
},
{
id: 'a-split', name: '拆单先发', en: 'split_and_ship', object: '销售订单', type: 'workflow',
trigger: '缓冲 < 5 天且齐套延迟', desc: '与客户协商分批交付,先发到料齐全的部分。',
targets: () => ruleTargets('r-crit'),
},
{
id: 'a-missing', name: '漏采核查', en: 'check_missing_po', object: '工单材料明细', type: 'alert',
trigger: '规则「漏采核查」命中', desc: '确认是走库存直接领料,还是确实漏下采购单。',
targets: () => ruleTargets('r-missing-po'),
},
{
id: 'a-sup-confirm', name: '供应商交期确认', en: 'confirm_eta', object: '供应商', type: 'report',
trigger: '齐套延迟 > 7 天', desc: '按供应商汇总需确认的到货承诺清单。',
targets: () => {
const sos = new Set(ruleTargets('r-kit'));
return [...new Set(purchaseOrders.filter(p => sos.has(p.来源销售订单号)).map(p => p.供应商编码))];
},
},
{
id: 'a-cust-impact', name: '客户影响评估', en: 'assess_cust_impact', object: '客户', type: 'query',
trigger: '红色订单关联客户', desc: '按客户汇总延期敞口,决定沟通顺序。',
targets: () => {
const sos = new Set(ruleTargets('r-crit'));
return [...new Set(salesOrders.filter(s => sos.has(s.销售订单号)).map(s => s.客户编码))];
},
},
{
id: 'a-ledger', name: '生成风险台账', en: 'export_risk_ledger', object: '销售订单', type: 'report',
trigger: '每日快照', desc: '输出 17 单 × 风险分 / 等级 / 触发规则的台账,供计划员晨会。',
targets: () => salesOrders.map(s => s.销售订单号),
},
{
id: 'a-substitute', name: '替代料查询', en: 'query_substitute', object: '物料', type: 'query',
trigger: '单源材料断供', desc: '数据缺口:物料主数据无替代料清单,暂不可执行。',
},
{
id: 'a-inventory', name: '库存快照补数', en: 'request_inventory_snapshot', object: '仓库', type: 'workflow',
trigger: '规则「库存可用量校验」被阻塞', desc: '向 IT 提数:现存量、已分配、安全库存、在途入库四列,日刷。',
},
{
id: 'a-trace-check', name: '追溯链体检', en: 'check_traceability', object: '采购订单', type: 'query',
trigger: '每次数据导入后', desc: '校验采购行能否 100% 回链到销售订单与工单。',
targets: () => ruleTargets('r-trace'),
},
{
id: 'a-bom-backfill', name: 'BOM 补全', en: 'backfill_bom', object: '生产工单', type: 'workflow',
trigger: '规则「BOM 完备性」命中', desc: '为无 BOM 工单补真实结构,消除需求反推带来的循环论证。',
targets: () => ruleTargets('r-bom'),
},
{
id: 'a-locate', name: '定位到订单', en: 'locate_order', object: '销售订单', type: 'query',
trigger: '任意规则/动作明细', desc: '关闭本体页并在左栏选中该销售订单,联动右栏采购与工单。',
targets: () => salesOrders.map(s => s.销售订单号),
},
];
/* ── 图谱数据:节点半径按关系度数,标签带实例数 ─────────────────────────── */
export const graphNodes = () => objects.map(o => ({
id: o.id, label: o.name, count: o.instances().length, color: o.color,
}));
export const graphEdges = () => relations.map(r => ({
id: r.id, source: r.from, target: r.to, label: r.name,
}));
export const objectById = (id: string) => objects.find(o => o.id === id);
export const severityColor = (s: Severity): Tone => (s === 'error' ? 'danger' : s === 'warning' ? 'warning' : 'info');
+417
View File
@@ -0,0 +1,417 @@
import initSqlJs from 'sql.js';
import type { Database } from 'sql.js';
import { PERIOD_MONTHS } from '../lib/time';
let db: Database | null = null;
/* ── 种子数据:指标树(L0 总览 → L1 维度 → L2 KPI → L3 驱动因子)──────────── */
type NodeSeed = [
code: string, zh: string, parent: string, level: number, dim: string,
value: number, target: number, unit: string, freq: string, alertTh: number,
alert: string, polarity: 'up' | 'down', weight: number, formula: string,
owner: string, descZh: string,
];
const NODES: NodeSeed[] = [
['OV', '整体经营健康度', '', 0, 'overall', 87.4, 90, '分', '月', 80, 'yellow', 'up', 100, '八维加权合成', '经营管理部', '综合八大维度的加权健康度评分,是全部指标的最终汇聚点。'],
['D-R', '财务成果', 'OV', 1, 'result', 92.5, 90, '分', '月', 85, 'green', 'up', 20, '收入/利润/订单/现金流加权', '财务部', '衡量规模与盈利兑现能力,是经营结果最直接的一层。'],
['D-Q', '盈利质量', 'OV', 1, 'quality', 86.0, 88, '分', '月', 80, 'yellow', 'up', 15, '利润率与资本回报加权', '财务部', '看利润的含金量:毛利、净利率、资本回报与资金结构。'],
['D-E', '运营效率', 'OV', 1, 'efficiency', 88.2, 85, '分', '月', 80, 'green', 'up', 12, '周转类指标加权', '运营管理部', '资产周转与现金转换速度,决定同等利润下的真实回报。'],
['D-G', '研发动能', 'OV', 1, 'growth', 90.4, 88, '分', '季', 82, 'green', 'up', 13, '研发投入·过程·产出加权', '战略发展部', '研发投入—过程—产出的完整链路,决定未来 2-3 年的产品竞争力。'],
['D-M', '市场客户', 'OV', 1, 'market', 84.6, 86, '分', '月', 80, 'yellow', 'up', 12, '漏斗与客户价值加权', '市场部', '客户获取、留存与单客价值的健康度。'],
['D-P', '生产供应', 'OV', 1, 'production', 87.1, 85, '分', '周', 80, 'green', 'up', 12, '设备与履约指标加权', '供应链本部', '制造端稼动与交付履约能力。'],
['D-D', '数智化与AI', 'OV', 1, 'digital', 78.5, 80, '分', '季', 70, 'yellow', 'up', 8, 'AI渗透/成熟度/数据资产', '数字化推进部', '数字化底座与 AI 落地深度,是效率提升的杠杆项。'],
['D-K', '风险韧性', 'OV', 1, 'risk', 91.0, 90, '分', '月', 85, 'green', 'up', 8, '敞口与合规事件反向计分', '合规风控部', '外部冲击与内部合规的抗风险能力。'],
['R01', '营业收入', 'D-R', 2, 'result', 67.8, 72.5, '亿元', '月', 65, 'yellow', 'up', 0.20, 'Σ 各BU不含税收入', '财务部', '本月合并口径不含税收入,受大客户节奏与渠道覆盖影响明显。'],
['R02', '营收同比增速', 'D-R', 2, 'result', 18.7, 15.0, '%', '月', 0, 'green', 'up', 0.15, '(本期-同期)/同期', '财务部', '剔除并表影响后的自然增速。'],
['R03', '归母净利润', 'D-R', 2, 'result', 5.96, 6.4, '亿元', '月', 5.5, 'yellow', 'up', 0.20, '净利润-少数股东损益', '财务部', '利润低于预算主要来自毛利率与汇兑两项。'],
['R08', '新增订单', 'D-R', 2, 'result', 72.5, 68.0, '亿元', '月', 60, 'green', 'up', 0.20, '当月确认订单金额', '市场部', '领先收入约 2 个季度,是短期最可靠的先行指标。'],
['R10', '在手订单', 'D-R', 2, 'result', 85.3, 80.0, '亿元', '月', 70, 'green', 'up', 0.15, '期初结转+本期新签-本期确认', '市场部', '覆盖下一季度收入计划的比例。'],
['R13', '经营现金流', 'D-R', 2, 'result', 7.32, 7.0, '亿元', '月', 6.0, 'green', 'up', 0.10, '净利+折旧摊销-营运资金增加', '财务部', '现金流优于利润,说明回款质量在改善。'],
['R04', '毛利率', 'D-Q', 2, 'quality', 27.1, 27.3, '%', '月', 25, 'yellow', 'up', 0.20, '(收入-成本)/收入', '财务部', '低于目标 0.2pt,结构上是高毛利占比不足。'],
['R05', '净利率', 'D-Q', 2, 'quality', 8.8, 8.8, '%', '月', 8.0, 'green', 'up', 0.15, '净利润/收入', '财务部', '达标但无缓冲,费用端压缩空间有限。'],
['R06', 'EBITDA利润率', 'D-Q', 2, 'quality', 14.2, 14.0, '%', '季', 13.0, 'green', 'up', 0.15, 'EBITDA/收入', '财务部', '经营性盈利能力稳定。'],
['Q01', 'ROE', 'D-Q', 2, 'quality', 18.5, 18.0, '%', '季', 15.0, 'green', 'up', 0.20, '净利润/净资产', '财务部', '杜邦拆解:净利率×周转×杠杆。'],
['Q03', '资产负债率', 'D-Q', 2, 'quality', 58.2, 60.0, '%', '月', 70.0, 'green', 'down', 0.15, '总负债/总资产', '财务部', '低于目标即优于目标,杠杆健康。'],
['Q08', '现金转换周期', 'D-Q', 2, 'quality', 62, 75, '天', '月', 85, 'green', 'down', 0.15, '存货天数+应收天数-应付天数', '财务部', '缩短 13 天,营运资金效率显著改善。'],
['E01', '存货周转天数', 'D-E', 2, 'efficiency', 63, 63, '天', '月', 70, 'green', 'down', 0.30, '平均存货/日均销货成本', '运营管理部', '达标,但长尾 SKU 仍占用约 12% 库存。'],
['E03', '应收周转天数', 'D-E', 2, 'efficiency', 75, 75, '天', '月', 85, 'green', 'down', 0.30, '平均应收/日均收入', '财务部', '大客户账期偏长是主要拖累项。'],
['E05', '人均产值', 'D-E', 2, 'efficiency', 891, 880, '万元', '季', 800, 'green', 'up', 0.20, '营业收入/平均在职人数', '人力资源部', '自动化替代与产品结构升级共同抬升。'],
['G01', '研发费用率', 'D-G', 2, 'growth', 6.4, 6.5, '%', '月', 5.5, 'green', 'up', 0.14, '研发费用/营业收入', '战略发展部', '投入强度行业前列,重点是转化效率。'],
['G02', '研发里程碑按期率', 'D-G', 2, 'growth', 88.5, 92.0, '%', '月', 85, 'yellow', 'up', 0.16, '按期完成里程碑数/计划里程碑数', '研究院', '延期集中在样机评审与模具移交两个节点。'],
['G04', '新品上市周期', 'D-G', 2, 'growth', 17.2, 16.0, '天', '季', 20, 'yellow', 'down', 0.14, '立项到批量供货的自然日数', '产品企划部', '样机与模具串行仍是主要瓶颈,目标压缩至 16 天。'],
['G06', '设计变更件数', 'D-G', 2, 'growth', 46, 52, '件', '月', 60, 'green', 'down', 0.10, '量产前累计 ECN 变更单数', '研究院', '变更八成来自结构件,返工直接侵蚀交付确定性。'],
['G07', '通用件复用率', 'D-G', 2, 'growth', 62.0, 68.0, '%', '季', 58, 'yellow', 'up', 0.10, '通用件型号数/BOM 总型号数', '研究院', '通用化每提升 5pt,物料编码数与库存资金同步下降。'],
['G08', '在研新品项目数', 'D-G', 2, 'growth', 42, 40, '个', '季', 36, 'green', 'up', 0.08, '当期在研新品项目数量', '战略发展部', '在研项目储备是明年新品贡献率的前置水位。'],
['G03', '新品贡献率', 'D-G', 2, 'growth', 26.8, 25.0, '%', '季', 20.0, 'green', 'up', 0.20, '近24个月新品收入/总收入', '战略发展部', '新品节奏是毛利率的重要支撑。'],
['G05', '专利转化数', 'D-G', 2, 'growth', 34, 30, '件', '季', 25, 'green', 'up', 0.08, '当年实现量产的专利数', '研究院', '从"申请量"转向"落地量"的考核口径。'],
['M01', '销售漏斗转化率', 'D-M', 2, 'market', 23.6, 25.0, '%', '月', 20.0, 'yellow', 'up', 0.35, '成交商机数/有效商机数', '市场部', '主要流失发生在方案验证环节。'],
['M02', 'LTV/CAC', 'D-M', 2, 'market', 5.0, 5.0, '倍', '季', 3.0, 'green', 'up', 0.30, '客户生命周期价值/获客成本', '市场部', '刚好踩线,服务收入占比提升可改善。'],
['M04', '大客户留存率', 'D-M', 2, 'market', 93.4, 95.0, '%', '季', 90.0, 'yellow', 'up', 0.35, '期末留存TOP客户数/期初', '市场部', '两家客户因交付延期降级为观察名单。'],
['P01', 'OEE', 'D-P', 2, 'production', 84.2, 85.0, '%', '日', 78.0, 'yellow', 'up', 0.30, '可用率×性能率×良品率', '制造本部', '瓶颈在设备可用率,非计划停机占比偏高。'],
['P02', '生产平衡率', 'D-P', 2, 'production', 92.5, 90.0, '%', '日', 85.0, 'green', 'up', 0.20, '各工位负荷均衡度', '制造本部', '线平衡改善直接支撑交付及时率。'],
['R12', '交付及时率', 'D-P', 2, 'production', 96.2, 96.5, '%', '周', 93.0, 'yellow', 'up', 0.30, '按期交付订单/总交付订单', '供应链本部', '差 0.3pt,集中在智能检测系统定制单。'],
['K01', '双源覆盖率', 'D-P', 2, 'production', 78, 80, '%', '月', 70, 'green', 'up', 0.20, '双供应商物料数/A类物料总数', '采购本部', '关键器件仍有单源风险敞口。'],
['D01', 'AI渗透率', 'D-D', 2, 'digital', 42, 50, '%', '季', 30, 'yellow', 'up', 0.35, '已部署AI场景数/规划场景数', '数字化推进部', '质检与排程两类场景贡献主要渗透。'],
['D02', 'AI成熟度', 'D-D', 2, 'digital', 58, 65, '分', '季', 50, 'yellow', 'up', 0.35, '五级模型能力评估加权', '数字化推进部', '卡在"单点可用"到"流程嵌入"的门槛。'],
['D05', '数据资产在线率', 'D-D', 2, 'digital', 71, 80, '%', '月', 60, 'yellow', 'up', 0.30, '已治理可调用数据域/规划数据域', '数字化推进部', 'AI 成熟度的前置约束条件。'],
['RK01', '风险敞口指数', 'D-K', 2, 'risk', 31, 35, '分', '月', 45, 'green', 'down', 0.40, '概率×影响加权归一', '合规风控部', '数值越低越好,当前优于警戒线 14 分。'],
['RK02', '合规事件数', 'D-K', 2, 'risk', 2, 0, '件', '季', 5, 'yellow', 'down', 0.35, '当期新增合规/审计事件', '合规风控部', '两起为跨境数据传输流程瑕疵,已闭环。'],
['DR-01', '大客户订单量', 'R01', 3, 'result', 412, 400, '件', '月', 380, 'green', 'up', 0.34, '合同额≥500万的订单数', '市场部', 'AI 辅助商机评分提升了大客户命中。'],
['DR-02', '渠道覆盖率', 'R01', 3, 'result', 68.5, 72, '%', '季', 60, 'yellow', 'up', 0.33, '已签约渠道覆盖目标客户数/目标客户总数', '渠道发展部', '中西部与华南二线城市是缺口集中区。'],
['DR-03', '平均单价', 'R01', 3, 'result', 12.6, 12.0, '万元', '月', 11.0, 'green', 'up', 0.33, '收入/出货数量', '市场部', '产品结构上移带来单价改善。'],
['DR-04', '高毛利产品占比', 'R04', 3, 'quality', 33.2, 35, '%', '月', 30, 'yellow', 'up', 0.40, '毛利率>35% 产品收入/总收入', '产品企划部', '毛利率未达标的核心结构原因。'],
['DR-05', '关键物料成本占比', 'R04', 3, 'quality', 41.3, 40, '%', '月', 45, 'yellow', 'down', 0.35, 'A类物料成本/制造总成本', '采购本部', '与双源覆盖率呈负相关。'],
['DR-06', '汇率影响度', 'R04', 3, 'quality', -1.2, 0, 'pt', '月', -2.0, 'yellow', 'up', 0.25, '汇率变动对毛利率的冲击点数', '财务部', '日元结算敞口未完全对冲。'],
['DR-07', '设备可用率', 'P01', 3, 'production', 91.5, 92, '%', '日', 88, 'yellow', 'up', 0.36, '(计划时间-停机时间)/计划时间', '设备管理部', '非计划停机中 47% 为换型调试。'],
['DR-08', '性能稼动率', 'P01', 3, 'production', 94.2, 93, '%', '日', 90, 'green', 'up', 0.32, '实际产出/理论产出', '制造本部', 'SMT 线已达设计节拍。'],
['DR-09', '良品率', 'P01', 3, 'production', 97.6, 97.5, '%', '日', 96, 'green', 'up', 0.32, '合格数/投产总数', '品质保证部', 'AI 视觉质检上线后提升 0.6pt。'],
['DR-10', '数据治理成熟度', 'D02', 3, 'digital', 54, 60, '分', '季', 45, 'yellow', 'up', 0.40, 'DCMM 四级评估得分', '数字化推进部', '主数据一致性是最大短板。'],
['DR-11', '模型上线数', 'D01', 3, 'digital', 17, 20, '个', '季', 12, 'yellow', 'up', 0.35, '进入生产环境的 AI 模型数', '数字化推进部', '从 PoC 到生产的转化周期偏长。'],
['DR-12', '线索质量分', 'M01', 3, 'market', 72, 75, '分', '月', 65, 'yellow', 'up', 0.50, '市场线索多维评分均值', '市场部', '市场与销售的判定标准未统一。'],
['DR-13', '方案响应时效', 'M01', 3, 'market', 3.4, 2.5, '日', '月', 4.0, 'red', 'down', 0.50, '需求确认到方案交付天数', '解决方案部', '当前唯一红色指标,资源排布是主因。'],
['DR-14', '计划准确率', 'E01', 3, 'efficiency', 88.5, 90, '%', '月', 85, 'green', 'up', 0.55, '1-|实际-计划|/计划', '计划物流部', '提升可直接压降安全库存水位。'],
['DR-15', '安全库存策略覆盖率', 'E01', 3, 'efficiency', 82, 85, '%', '季', 75, 'yellow', 'up', 0.45, '按动态模型设置安全库存的SKU占比', '计划物流部', '长尾 SKU 仍用固定天数法。'],
];
/* 跨树驱动关系(网络视图):from → to,strength 带符号 */
const LINKS: [string, string, 'drive' | 'conflict' | 'monitor', number][] = [
['DR-05', 'R04', 'conflict', -0.58], ['DR-06', 'R04', 'conflict', -0.34], ['DR-06', 'R01', 'conflict', -0.21],
['DR-04', 'R04', 'drive', 0.61], ['DR-04', 'R03', 'drive', 0.42], ['DR-09', 'R04', 'drive', 0.37],
['DR-07', 'P01', 'drive', 0.52], ['DR-08', 'P01', 'drive', 0.44], ['DR-09', 'P01', 'drive', 0.33],
['P01', 'R12', 'drive', 0.46], ['P02', 'R12', 'drive', 0.31], ['R12', 'M04', 'drive', 0.55],
['M04', 'R08', 'drive', 0.39], ['DR-13', 'M01', 'conflict', -0.41], ['DR-12', 'M01', 'drive', 0.48],
['M01', 'R08', 'drive', 0.36], ['R08', 'R10', 'drive', 0.62], ['R02', 'R01', 'drive', 0.55],
['DR-14', 'E01', 'drive', 0.43], ['DR-15', 'E01', 'drive', 0.29], ['E01', 'Q08', 'drive', 0.51],
['E03', 'Q08', 'drive', 0.47], ['Q08', 'R13', 'drive', 0.38], ['D02', 'E01', 'drive', 0.27],
['D02', 'P01', 'drive', 0.24], ['D01', 'D02', 'drive', 0.58], ['D05', 'D02', 'drive', 0.49],
['DR-10', 'D05', 'drive', 0.44], ['DR-11', 'D01', 'drive', 0.35], ['G01', 'G03', 'drive', 0.41],
['G03', 'R01', 'drive', 0.33], ['G03', 'DR-04', 'drive', 0.46], ['K01', 'DR-05', 'conflict', -0.31],
['DR-01', 'R01', 'drive', 0.57], ['DR-02', 'R01', 'drive', 0.35], ['DR-03', 'R01', 'drive', 0.29],
['RK01', 'R03', 'monitor', -0.22], ['RK02', 'D-K', 'monitor', -0.18], ['E05', 'D-E', 'drive', 0.40],
['G01', 'G02', 'drive', 0.28], ['G02', 'G03', 'drive', 0.48], ['G04', 'G03', 'conflict', -0.36],
['G06', 'G02', 'conflict', -0.42], ['G07', 'G04', 'drive', 0.44], ['G07', 'R04', 'drive', 0.35],
['G08', 'G03', 'drive', 0.40], ['G08', 'G01', 'drive', 0.25],
];
type StaffSeed = [
code: string, zh: string, roleZh: string, status: string,
skillZh: string, tasks: number, success: number, conf: number,
load: number, lastRun: string, curZh: string, metric: string,
];
const STAFF: StaffSeed[] = [
// 命名约定:业务领域 + 智能体,让看的人一眼知道它负责什么;code 仅作内部标识
['METRIX', '指标监控智能体', '实时监控 · 异常检测', 'working', '阈值学习 / 多维权重偏移', 128, 99.2, 96, 72, '刚刚', '扫描 35 个 L2 指标,锁定 15 项偏离', 'OV'],
['CAUSAL', '指标归因智能体', '波动归因 · 链路追溯', 'working', '因果图 / SHAP 贡献分解', 42, 94.8, 91, 86, '2 分钟前', '正在为「毛利率 -0.2pt」追溯驱动链', 'R04'],
['ALERT', '预警调度智能体', '分级派单 · 闭环跟踪', 'alert', '严重度判定 / 责任人匹配', 17, 88.4, 83, 97, '刚刚', '方案响应时效连续 3 期红色,待升级', 'DR-13'],
['FORECAST', '趋势预测智能体', '滚动预测 · 情景推演', 'working', '时序模型 / 蒙特卡洛', 23, 91.5, 88, 64, '5 分钟前', '基于在手订单推演 Q4 收入区间', 'R10'],
['REPORT', '报表生成智能体', '自动出表 · 多语言', 'working', '口径对齐 / 中日双语排版', 56, 99.6, 98, 41, '12 分钟前', '生成 6 月经营分析月报(中/日)', 'D-R'],
['DATA', '数据质检智能体', '完整性 · 一致性校验', 'idle', '空值/跳变/主数据冲突', 9, 97.1, 95, 12, '38 分钟前', '主数据一致性巡检通过,无待处理项', 'DR-10'],
['BENCH', '标杆对标智能体', '同业拆解 · 差距定位', 'idle', '同业财报 / 专利地图', 4, 90.0, 82, 8, '1 小时前', '等待接入 Q2 同业披露数据', 'Q01'],
['ACTION', '行动规划智能体', '建议生成 · 任务编排', 'offline', '措施库匹配 / 责任人派发', 0, 0, 0, 0, '昨天', '已停用,等待授权接入 OA 派发', 'M01'],
['FINA', '财务分析智能体', '杜邦拆解 · 三表勾稽', 'working', '杜邦体系 / 三表勾稽校验', 64, 96.4, 93, 58, '3 分钟前', '拆解 6 月营收同比 +18.7% 的增长结构', 'R01'],
['COST', '成本管控智能体', '标准成本 · 差异归因', 'working', '成本桥 / 采购价差分解', 71, 95.2, 92, 66, '6 分钟前', '关键物料成本占比超 1.8pt,锁定 3 个采购批次', 'DR-05'],
['BUDG', '预算执行智能体', '预算偏差 · 滚动修正', 'working', '达成率测算 / 预算调整模拟', 38, 97.8, 94, 52, '9 分钟前', '重算 35 项 L2 达成率,5 项低于 90%', 'R03'],
['CASH', '现金流智能体', '回款预测 · 资金头寸', 'idle', '滚动现金流 / 付款计划排程', 12, 96.6, 90, 18, '42 分钟前', '本周回款计划已执行,资金头寸安全', 'R13'],
['ARMC', '应收管理智能体', '账龄分析 · 催收派单', 'working', '账龄分桶 / 催收策略匹配', 27, 93.4, 89, 47, '15 分钟前', '4 笔超 90 天账龄已生成催收任务', 'E03'],
['MARG', '盈利结构智能体', '毛利桥 · 产品组合', 'working', '毛利桥 / 组合贡献分解', 33, 94.1, 90, 55, '8 分钟前', '高毛利产品占比 -2.1pt,推演组合改善路径', 'DR-04'],
['OPEX', '费用管控智能体', '费用率 · 投入产出', 'idle', '费用基线 / 投入产出评估', 15, 95.8, 91, 22, '51 分钟前', '期间费用率处于预算区间,无需调整', 'R05'],
['HREF', '人效分析智能体', '人均产值 · 编制弹性', 'working', '人均产值拆解 / 编制情景', 29, 92.7, 88, 44, '21 分钟前', '华东区人均产值 1.4 倍于均值,提炼配置模型', 'E05'],
['ASST', '资产周转智能体', '周转效率 · 资金占用', 'idle', '周转拆解 / 占用成本核算', 8, 91.9, 86, 10, '2 小时前', '现金转换周期比同业长 6 天,列改善清单', 'Q08'],
['RDPG', '研发进度智能体', '里程碑跟踪 · 延期预警', 'working', '里程碑关键路径 / 延期影响', 44, 93.8, 90, 74, '4 分钟前', '2 个里程碑延期于样机评审,评估量产节点', 'G02'],
['PATO', '专利运营智能体', '转化跟踪 · 布局地图', 'idle', '转化管道 / 同业布局监测', 6, 89.5, 84, 9, '3 小时前', '3 件专利进入许可谈判,跟踪条款', 'G05'],
['NPIA', '新品贡献智能体', '新品占比 · 上市周期', 'working', '贡献拆解 / 上市进度联动', 31, 94.6, 91, 61, '11 分钟前', '新品贡献率距目标 1.2pt,倒排上市需求', 'G03'],
['CUST', '客户洞察智能体', '客户分层 · 流失预警', 'working', '流失预测 / 分层迁移监测', 36, 95.1, 92, 57, '7 分钟前', '2 家大客户活跃度下降,生成挽留建议', 'M04'],
['ORDR', '订单管理智能体', '订单评审 · 交期承诺', 'working', '订单结构 / 产能联动评审', 52, 96.8, 93, 69, '5 分钟前', '评审本周 47 笔新订单,3 笔需协调产能', 'R08'],
['CHNL', '渠道效能智能体', '渠道 ROI · 覆盖分析', 'idle', '渠道贡献 / 覆盖缺口扫描', 10, 90.8, 85, 14, '1 小时前', '华中渠道覆盖低规划 8pt,待区域反馈', 'DR-02'],
['QUAL', '质量管理智能体', 'SPC 监控 · 不良归因', 'alert', 'SPC 控制限 / 不良链归因', 58, 92.3, 87, 94, '刚刚', '良品率连续 2 期低于控制限,发起升级', 'DR-09'],
['SCHED', '生产排程智能体', 'APS 排程 · 插单影响', 'working', '约束排程 / 插单影响模拟', 47, 95.5, 92, 63, '10 分钟前', '完成 3 笔插单影响测算,平均延交 0.8 天', 'DR-14'],
['EQUIP', '设备运维智能体', 'OEE 分析 · 预测性维护', 'working', '振动频谱 / 主轴负载建模', 39, 96.1, 93, 54, '14 分钟前', '1 台加工中心主轴负载异常,已生成工单', 'P01'],
['DLVR', '交付保障智能体', '齐套检查 · 发运跟踪', 'working', '齐套缺件扫描 / 物流节点', 43, 94.9, 91, 60, '9 分钟前', '2 笔订单齐套缺件,协调采购加急', 'R12'],
['PROC', '采购管理智能体', '寻源比价 · 双源推进', 'working', '比价模型 / 供应风险扫描', 26, 93.2, 89, 46, '26 分钟前', '关键物料新增 1 家备选源,双源覆盖 +2pt', 'K01'],
['INV', '库存优化智能体', '安全库存 · 呆滞预警', 'alert', '周转模拟 / 呆滞识别', 26, 90.4, 85, 92, '2 分钟前', '呆滞金额超线 12%,待升级处置评审', 'E01'],
['SUPP', '供应商绩效智能体', '来料合格 · 交付评价', 'idle', '来料统计 / 交付达成排行', 9, 92.0, 87, 12, '1 小时前', 'Q2 供应商绩效排行已生成,发送采购', 'DR-15'],
['FXA', '汇兑风险智能体', '敞口对冲 · 汇率情景', 'working', '敞口测算 / 套保比例模拟', 21, 94.3, 90, 49, '18 分钟前', '日元波动放大,重估 Q3 套保比例', 'DR-06'],
['RISK', '风险预警智能体', '风险矩阵 · 敞口量化', 'working', '风险评分 / 敞口链路量化', 18, 93.6, 89, 43, '33 分钟前', '供应侧 2 项风险更新矩阵', 'RK01'],
['COMP', '合规审查智能体', '合同条款 · 出口管制', 'idle', '条款库匹配 / 管制清单筛查', 7, 98.2, 95, 8, '2 小时前', '本周 6 份合同审查完毕,无阻断条款', 'RK02'],
['GOV', '数据治理智能体', '主数据 · 血缘稽核', 'working', '血缘追溯 / 口径一致稽核', 24, 96.9, 94, 38, '29 分钟前', '3 张报表口径补充血缘链路,稽核通过', 'D05'],
['AIEV', '数智化评估智能体', '成熟度评估 · 场景 ROI', 'idle', '成熟度模型 / 场景 ROI 复盘', 5, 91.2, 86, 7, '4 小时前', '上半年 AI 成熟度自评完成,待管理层评审', 'D02'],
['LEAD', '线索转化智能体', '线索评分 · 转化路径', 'working', '线索评分 / 转化路径归因', 32, 92.8, 88, 51, '16 分钟前', '低分线索占比 21%,调整渠道投放权重', 'DR-12'],
['PRIC', '价格管理智能体', '价格带 · 折扣审批', 'idle', '价格带监测 / 折扣偏离回溯', 11, 93.0, 88, 16, '1 小时前', '平均单价同比 +1.5%,处于价格带内', 'DR-03'],
['RDIN', '研发投入智能体', '投入强度 · 预算结构', 'working', '投入对标 / 结构拆解', 16, 94.0, 90, 35, '47 分钟前', '研发费用率 6.8%,高于行业上四分位 0.3pt', 'G01'],
];
function hashCode(s: string): number {
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return Math.abs(h) + 1;
}
function makeRng(seed: number) {
let s = seed % 2147483647;
if (s <= 0) s += 2147483646;
return () => (s = (s * 16807) % 2147483647) / 2147483647;
}
/** 指标趋势的 12 期标签:与全局回放窗口同轴(以业务快照月为最后一期) */
export const MONTHS = PERIOD_MONTHS;
/** 由当期值反推 12 期历史:好的方向收敛到 value,噪声受 alert_level 影响 */
function buildTrend(value: number, target: number, polarity: string, alert: string, code: string): number[] {
const rnd = makeRng(hashCode(code));
const noise = alert === 'red' ? 0.10 : alert === 'yellow' ? 0.055 : 0.03;
const amp = Math.max(Math.abs(value) * 0.18, Math.abs(target) * 0.06, 0.3);
const start = polarity === 'down' ? value + amp * (0.7 + rnd() * 0.5) : value - amp * (0.5 + rnd() * 0.8);
const out: number[] = [];
for (let i = 0; i < 12; i++) {
const t = i / 11;
const ease = t * t * (3 - 2 * t);
const drift = start + (value - start) * ease;
const wobble = (rnd() - 0.5) * 2 * noise * Math.abs(value || 1);
out.push(+(drift + (i === 11 ? 0 : wobble)).toFixed(2));
}
out[11] = value;
return out;
}
export async function initDatabase(): Promise<Database> {
if (db) return db;
const SQL = await initSqlJs({
// sql.js 浏览器构建会请求 sql-wasm-browser.wasm,而 public/ 下只放了 sql-wasm.wasm
// (两者字节一致)。统一指回已存在的文件,否则未命中路径会被 SPA fallback
// 返回 index.html,报 "expected magic word 00 61 73 6d, found 3c 21 64 6f"。
locateFile: () => '/jieya-ibp/sql-wasm.wasm',
});
db = new SQL.Database();
db.run(`
CREATE TABLE metric_node (
id INTEGER PRIMARY KEY, code TEXT UNIQUE NOT NULL,
name_zh TEXT NOT NULL,
parent_code TEXT NOT NULL, level INTEGER NOT NULL, dimension TEXT NOT NULL,
value REAL, target REAL, unit TEXT, frequency TEXT,
alert_threshold REAL, alert_level TEXT, polarity TEXT, weight REAL,
formula TEXT, owner TEXT, desc_zh TEXT, updated_at TEXT
);
CREATE TABLE metric_link (
id INTEGER PRIMARY KEY, from_code TEXT NOT NULL, to_code TEXT NOT NULL,
relation TEXT NOT NULL, strength REAL NOT NULL
);
CREATE TABLE metric_trend (
id INTEGER PRIMARY KEY, code TEXT NOT NULL, period TEXT NOT NULL,
actual REAL, target REAL
);
CREATE TABLE digital_staff (
id INTEGER PRIMARY KEY, code TEXT NOT NULL,
name_zh TEXT, role_zh TEXT,
status TEXT, skill_zh TEXT,
tasks_today INTEGER, success_rate REAL, confidence REAL, load_pct REAL,
last_run TEXT, cur_zh TEXT, bound_metric TEXT
);
CREATE TABLE revenue_monthly (
id INTEGER PRIMARY KEY, month TEXT NOT NULL, entity TEXT NOT NULL,
revenue REAL, cost REAL, gross_profit REAL, gross_margin REAL, yoy_growth REAL
);
CREATE TABLE product_line (
id INTEGER PRIMARY KEY, name_zh TEXT,
revenue REAL, gross_margin REAL, share REAL, yoy_growth REAL
);
CREATE TABLE region_data (
id INTEGER PRIMARY KEY, name_zh TEXT,
revenue REAL, headcount INTEGER, per_capita REAL, gross_margin REAL
);
CREATE TABLE risk_matrix (
id INTEGER PRIMARY KEY, name_zh TEXT,
probability REAL, impact REAL, category TEXT,
mitigation_status TEXT, status_zh TEXT
);
`);
const insNode = db.prepare(`INSERT INTO metric_node VALUES
(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,datetime('now'))`);
NODES.forEach((n, i) => insNode.run([i + 1, ...n]));
insNode.free();
const insLink = db.prepare('INSERT INTO metric_link VALUES (?,?,?,?,?)');
LINKS.forEach((l, i) => insLink.run([i + 1, ...l]));
insLink.free();
const insTrend = db.prepare('INSERT INTO metric_trend VALUES (?,?,?,?,?)');
let tid = 1;
NODES.forEach(n => {
const [code, , , level, , value, target, , , , , polarity] = n;
if (level === undefined) return;
const series = buildTrend(value, target, polarity, n[10], code);
series.forEach((v, i) => insTrend.run([tid++, code, MONTHS[i], v, target]));
});
insTrend.free();
const insStaff = db.prepare('INSERT INTO digital_staff VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
STAFF.forEach((s, i) => insStaff.run([i + 1, ...s]));
insStaff.free();
db.run(`INSERT INTO revenue_monthly VALUES
(1,'2025-01','all',9.8,7.1,2.7,27.6,0),(2,'2025-02','all',8.2,6.0,2.2,26.8,0),
(3,'2025-03','all',11.5,8.4,3.1,27.0,0),(4,'2025-04','all',10.4,7.7,2.7,26.0,0),
(5,'2025-05','all',11.8,8.6,3.2,27.1,0),(6,'2025-06','all',12.3,9.0,3.3,26.8,0),
(7,'2025-01','mec',5.6,4.0,1.6,28.6,0),(8,'2025-02','mec',4.8,3.5,1.3,27.1,0),
(9,'2025-03','mec',6.7,4.8,1.9,28.4,0),(10,'2025-04','mec',7.1,5.2,1.9,26.8,0),
(11,'2025-05','mec',7.8,5.7,2.1,26.9,0),(12,'2025-06','mec',8.1,5.9,2.2,27.2,0)
`);
db.run(`INSERT INTO product_line VALUES
(1,'智能检测系统',22.5,31.2,33.2,28.5),
(2,'数字化方案',16.8,35.6,24.8,35.2),
(3,'通用装备',18.3,22.1,27.0,12.8),
(4,'配件与服务',10.2,42.5,15.0,18.6)
`);
db.run(`INSERT INTO region_data VALUES
(1,'华东',28.5,320,891,28.2),(2,'华南',18.2,210,867,27.5),
(3,'华北',12.6,155,813,26.8),(4,'中西部',8.5,95,895,25.9)
`);
db.run(`INSERT INTO risk_matrix VALUES
(1,'汇率波动风险',0.6,0.7,'financial','monitoring','监控中'),
(2,'关键物料供应中断',0.3,0.9,'supply','mitigating','缓释中'),
(3,'行业竞争加剧',0.7,0.6,'market','monitoring','监控中'),
(4,'核心人才流失',0.4,0.8,'hr','escalated','已升级'),
(5,'合规政策变化',0.3,0.5,'compliance','monitoring','监控中'),
(6,'地缘政治风险',0.5,0.7,'geopolitical','mitigating','缓释中')
`);
return db;
}
/* ── 查询层 ─────────────────────────────────────────────────────────────── */
function rows(sql: string): Record<string, unknown>[] {
if (!db) return [];
const res = db.exec(sql);
if (!res.length) return [];
const { columns, values } = res[0];
return values.map(row => {
const o: Record<string, unknown> = {};
columns.forEach((c, i) => { o[c] = row[i]; });
return o;
});
}
export interface MetricNode {
id: number; code: string; name_zh: string; parent_code: string;
level: number; dimension: string; value: number; target: number; unit: string;
frequency: string; alert_threshold: number; alert_level: string; polarity: 'up' | 'down';
weight: number; formula: string; owner: string; desc_zh: string;
updated_at: string;
children?: MetricNode[];
trend?: number[];
}
export interface MetricLink { id: number; from_code: string; to_code: string; relation: string; strength: number }
export interface DigitalStaff {
id: number; code: string; name_zh: string; role_zh: string;
status: 'working' | 'idle' | 'alert' | 'offline'; skill_zh: string;
tasks_today: number; success_rate: number; confidence: number; load_pct: number;
last_run: string; cur_zh: string; bound_metric: string;
}
const esc = (s: string) => s.replace(/'/g, "''");
/** 全量节点索引(一次查询,前端自行组树/找边,避免递归 SQL) */
export function queryMetricNodes(): MetricNode[] {
return rows('SELECT * FROM metric_node ORDER BY level, id') as unknown as MetricNode[];
}
/** 组装成树;顺带把 12 期趋势挂到节点上 */
export function queryMetricTree(): MetricNode[] {
const nodes = queryMetricNodes();
const trendMap = new Map<string, number[]>();
rows('SELECT code, actual FROM metric_trend ORDER BY code, period').forEach(r => {
const c = r.code as string;
if (!trendMap.has(c)) trendMap.set(c, []);
trendMap.get(c)!.push(r.actual as number);
});
const byCode = new Map<string, MetricNode>();
nodes.forEach(n => { n.children = []; n.trend = trendMap.get(n.code) ?? []; byCode.set(n.code, n); });
const roots: MetricNode[] = [];
nodes.forEach(n => {
if (n.parent_code && byCode.has(n.parent_code)) byCode.get(n.parent_code)!.children!.push(n);
else roots.push(n);
});
return roots;
}
export function queryMetricLinks(): MetricLink[] {
return rows('SELECT * FROM metric_link ORDER BY id') as unknown as MetricLink[];
}
/** 与某个指标直接相连的边(网络视图聚焦用) */
export function queryMetricLinksOf(code: string): MetricLink[] {
const c = esc(code);
return rows(`SELECT * FROM metric_link WHERE from_code='${c}' OR to_code='${c}' ORDER BY id`) as unknown as MetricLink[];
}
export interface TrendPoint { period: string; actual: number; target: number }
export function queryTrend(code: string): TrendPoint[] {
return rows(`SELECT period, actual, target FROM metric_trend WHERE code='${esc(code)}' ORDER BY period`) as unknown as TrendPoint[];
}
export function queryChildren(parentCode: string): MetricNode[] {
return rows(`SELECT * FROM metric_node WHERE parent_code='${esc(parentCode)}' ORDER BY id`) as unknown as MetricNode[];
}
export function queryDigitalStaff(): DigitalStaff[] {
return rows('SELECT * FROM digital_staff ORDER BY id') as unknown as DigitalStaff[];
}
/** 兼容旧调用:返回 L2 层 KPI(可按维度过滤),附 12 期 trend 与近 3 月环比 */
export function queryKPIs(dimension?: string): MetricNode[] {
const where = dimension && dimension !== 'all'
? `AND dimension='${esc(dimension)}'` : '';
const list = rows(`SELECT * FROM metric_node WHERE level=2 ${where} ORDER BY id`) as unknown as MetricNode[];
const trendMap = new Map<string, number[]>();
rows('SELECT code, actual FROM metric_trend ORDER BY code, period').forEach(r => {
const c = r.code as string;
if (!trendMap.has(c)) trendMap.set(c, []);
trendMap.get(c)!.push(r.actual as number);
});
return list.map(n => {
const t = trendMap.get(n.code) ?? [];
n.trend = t;
const last = t[t.length - 1];
const prev = t[t.length - 4];
(n as unknown as { trend_3m: number }).trend_3m =
prev ? +(((last - prev) / Math.abs(prev)) * 100).toFixed(1) : 0;
return n;
});
}
export interface ProductLine { name_zh: string; revenue: number; share: number; gross_margin: number; yoy_growth: number }
export interface Region { name_zh: string; revenue: number; headcount: number; per_capita: number; gross_margin: number }
export interface Risk { name_zh: string; probability: number; impact: number; category: string; status_zh: string }
export function queryRevenueMonthly() { return rows('SELECT * FROM revenue_monthly ORDER BY month') as unknown as { month: string; revenue: number; gross_profit: number }[]; }
export function queryProductLines() { return rows('SELECT * FROM product_line ORDER BY revenue DESC') as unknown as ProductLine[]; }
export function queryRegions() { return rows('SELECT * FROM region_data ORDER BY revenue DESC') as unknown as Region[]; }
export function queryRisks() { return rows('SELECT * FROM risk_matrix ORDER BY probability*impact DESC') as unknown as Risk[]; }
/** 顶部告警条数:red 为紧急,yellow 为关注;total 与指标树节点数同口径 */
export function queryAlertCounts() {
const r = rows(`SELECT
SUM(CASE WHEN alert_level='red' AND level>=2 THEN 1 ELSE 0 END) AS red,
SUM(CASE WHEN alert_level='yellow' AND level>=2 THEN 1 ELSE 0 END) AS yellow,
SUM(CASE WHEN alert_level='green' AND level>=2 THEN 1 ELSE 0 END) AS green,
COUNT(*) AS total FROM metric_node`);
return (r[0] ?? { red: 0, yellow: 0, green: 0, total: 0 }) as
{ red: number; yellow: number; green: number; total: number };
}
+181
View File
@@ -0,0 +1,181 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import type { DigitalStaff, MetricNode } from '../data/sqlite';
import type { I18n } from '../i18n/locales';
import { buildAskAnswer } from '../lib/ibpAsk';
import type { AskAnswer, IntentId } from '../lib/ibpAsk';
import { buildConsultScript } from '../lib/teams';
import type { ConsultTurn, ExpertTeam } from '../lib/teams';
/**
* 底部对话区的会话状态机:问候语 → 单轮问答(思考步骤逐条揭示)→ 专家团会诊播报。
*
* 状态放在 hook 里、由 MetricWorkspace 持有,而不是放在 AgentDock 组件内部:
* 本体舞台会替换掉整块内容区,对话区组件随之卸载;状态上提后
* 「从回答卡点进业务本体总览」再退回来,会话历史与进行中的推演都不会丢。
*/
export interface Msg {
id: number;
role: 'user' | 'ai';
text: string;
staff?: string;
time: string;
/** 专家团会诊:发言者名 / 角色标签 / 发言类型(系统播报 / 成员 / 牵头汇总) */
name?: string;
tag?: string;
kind?: 'system' | 'member' | 'lead';
/** 专家团结构化发言(成员卡 / 牵头结论卡的数据源) */
turn?: ConsultTurn;
/** 单轮问答:规范回答卡(结论 / 关键数字 / 明细 / 依据 / 行动 / 来源) */
answer?: AskAnswer;
/** 该回答的思考过程耗时(秒):步骤揭示完写回,卡头展示 */
elapsed?: number;
}
/** 思考中的回答:steps 按 revealed 逐条揭示,全部揭示后才落卡 */
export interface PendingAsk {
answer: AskAnswer;
staff?: string;
revealed: number;
/** performance.now() 起点,用于卡头「耗时 x.xs」 */
started: number;
}
export interface AgentChat {
msgs: Msg[];
/** 揭示中的问答:对话区用它渲染逐条出现的思考轨 */
pending: PendingAsk | null;
/** 会诊播报间隔的「分析中」气泡 */
thinking: boolean;
/** 输入区是否该锁住:会诊播报中或思考轨揭示中都算忙 */
busy: boolean;
draft: string;
setDraft: (v: string) => void;
ask: (raw: string) => void;
/** 清空:回到问候语,并掐掉所有在飞的定时器 */
reset: () => void;
}
const clock = () => {
const d = new Date();
const p = (n: number) => String(n).padStart(2, '0');
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
};
/** 意图 → 在岗数字员工:回答卡头部标注归属,保留「数字员工协同」的设定 */
const DISPATCH: Record<IntentId, string> = {
delay: 'ORDR', bottleneck: 'SCHED', po: 'ALERT', material: 'DATA', gap: 'DATA', ledger: 'REPORT', help: 'METRIX',
};
interface Input {
staff: DigitalStaff[];
byCode: Map<string, MetricNode>;
/** 会诊聚焦的指标:触发时快照,避免左侧选中变化导致会诊重跑 */
selected?: MetricNode;
team: ExpertTeam | null;
t: I18n;
}
export function useAgentChat({ staff, byCode, selected, team, t }: Input): AgentChat {
const [draft, setDraft] = useState('');
const [thinking, setThinking] = useState(false);
const [msgs, setMsgs] = useState<Msg[]>([]);
const [pending, setPending] = useState<PendingAsk | null>(null);
const seq = useRef(0);
const staffRef = useRef(staff); staffRef.current = staff;
const byCodeRef = useRef(byCode); byCodeRef.current = byCode;
const selectedRef = useRef(selected); selectedRef.current = selected;
const timersRef = useRef<number[]>([]);
const clearTimers = () => { timersRef.current.forEach(id => window.clearTimeout(id)); timersRef.current = []; };
const onDuty = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
const busy = thinking || !!pending;
// 问候语随文案变化刷新(不劫持用户正在输入的草稿)
useEffect(() => {
if (team) return; // 专家团激活时对话区交给会诊序列,不覆盖
clearTimers();
setPending(null);
seq.current = 0;
setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [t.agent.greeting, t.agent.subtitle, team]);
// 专家团会诊:按脚本依次播报(就位播报 → 各专家轮流发言 → 牵头汇总结论)
useEffect(() => {
clearTimers();
if (!team) return;
setPending(null);
const staffByCode = new Map(staffRef.current.map(x => [x.code, x]));
const script = buildConsultScript(team, staffByCode, byCodeRef.current, selectedRef.current);
seq.current = 0;
setThinking(false);
setMsgs([]);
let delay = 160;
script.forEach((turn, i) => {
if (i > 0) timersRef.current.push(window.setTimeout(() => setThinking(true), Math.max(0, delay - 420)));
timersRef.current.push(window.setTimeout(() => {
// id 必须在 updater 外定值:updater 需保持纯函数,批处理时否则多条消息读到同一 seq 撞 key
const id = ++seq.current;
const time = clock();
setThinking(false);
setMsgs(prev => [...prev, {
id, role: 'ai', text: turn.text ?? '',
name: turn.name, tag: turn.tag, kind: turn.kind, turn, time,
}]);
}, delay));
delay += turn.kind === 'lead' ? 1500 : turn.kind === 'system' ? 900 : 1150;
});
return clearTimers;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [team]);
/* 揭示节奏:首步 420ms 起步,其后每步 520–700ms 轻微抖动,步骤走完停 700ms 再落卡。
刻意慢于「瞬间甩结果」,让取数—建链路—跑规则—排序的推演过程可见;
总耗时回写进卡头,用户可复核它确实跑了这几步。 */
useEffect(() => {
if (!pending) return;
const atEnd = pending.revealed >= pending.answer.steps.length;
const delay = atEnd ? 700 : pending.revealed === 0 ? 420 : 520 + Math.round(Math.random() * 180);
const id = window.setTimeout(() => {
if (atEnd) {
const elapsed = (performance.now() - pending.started) / 1000;
setMsgs(prev => [...prev, {
id: ++seq.current, role: 'ai', text: pending.answer.conclusion,
answer: pending.answer, elapsed, staff: pending.staff, time: clock(),
}]);
setPending(null);
} else {
setPending(p => (p ? { ...p, revealed: p.revealed + 1 } : p));
}
}, delay);
return () => window.clearTimeout(id);
}, [pending]);
// 提问 → 履约风险问答引擎 → 思考步骤逐条揭示 → 规范回答卡落位
const ask = (raw: string) => {
const text = raw.trim();
if (!text || busy) return;
const { intent, answer } = buildAskAnswer(text);
const who = onDuty.find(s => s.code === DISPATCH[intent]) ?? onDuty[0];
setMsgs(prev => [...prev, { id: ++seq.current, role: 'user', text, time: clock() }]);
setDraft('');
setPending({
answer,
staff: who ? `${t.agent.dispatched}${who.name_zh}` : undefined,
revealed: 0,
started: performance.now(),
});
};
const reset = () => {
clearTimers();
setPending(null);
setThinking(false);
setDraft('');
seq.current = 0;
setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]);
};
return { msgs, pending, thinking, busy, draft, setDraft, ask, reset };
}
@@ -0,0 +1,155 @@
import { useEffect, type RefObject } from 'react';
/**
* 侧栏列表的自动滚动:让「销售订单 / 客户资料 / 采购单 / 生产工单 / 供应商资料」这些
* 一页装不下的卡片列表自己缓慢往下走,到底停一下再平滑回到顶部循环。
*
* 相位机(stepMotion)写成纯函数,滚动驱动(useAutoScroll)只负责喂帧和读几何,
* 这样循环逻辑可以脱离浏览器单独验算;rAF 在后台标签页不触发时循环自然停摆,
* 不浪费 CPU,也不需要额外的可见性判断。
*/
export type Phase = 'down' | 'holdB' | 'up' | 'holdT';
export interface MotionState {
/** 浮点累加的期望 scrollTop:28px/s 摊到 120Hz 每帧只有 0.23px,
* 直接读写整数 scrollTop 会被量化舍入吞掉而停摆,所以位置必须自己攒 */
pos: number;
phase: Phase;
/** 停留相位到期时刻(ms,performance.now 时钟) */
until: number;
}
export interface MotionCfg {
/** 下滚速度 px/s */
speed: number;
holdBottomMs: number;
holdTopMs: number;
/** 回顶速度:每秒收敛的比例,越大越快 */
rewind: number;
}
export const DEFAULT_MOTION: MotionCfg = { speed: 28, holdBottomMs: 1400, holdTopMs: 500, rewind: 5 };
/** 左侧工作区滚动速度:舒缓,让阅读节奏更稳 */
export const LEFT_MOTION: MotionCfg = { speed: 22, holdBottomMs: 1500, holdTopMs: 550, rewind: 5 };
/** 右侧工作区滚动速度:稍快,与左侧形成差异性动感 */
export const RIGHT_MOTION: MotionCfg = { speed: 38, holdBottomMs: 1100, holdTopMs: 400, rewind: 5 };
/** 容器几何:全部由调用方从 DOM 读好后传入,纯函数不碰 DOM */
export interface MotionGeo {
scrollTop: number;
clientHeight: number;
scrollHeight: number;
}
export interface MotionResult {
state: MotionState;
/** 需要写回的 scrollTop;null 表示这一帧不要动(暂停 / 够不着滚动) */
scrollTop: number | null;
}
/**
* 推进一帧。paused 为真(鼠标悬停、用户刚手动滚过、列表装得下没有滚动空间)时
* 只把累加器对齐到真实 scrollTop 并交还控制权,用户一松手就能从当前位置续跑。
*/
export function stepMotion(
s: MotionState, now: number, dtSec: number, geo: MotionGeo, paused: boolean, cfg: MotionCfg = DEFAULT_MOTION,
): MotionResult {
const overflow = geo.scrollHeight - geo.clientHeight;
if (overflow <= 4 || paused) return { state: { ...s, pos: geo.scrollTop }, scrollTop: null };
const dt = Math.min(0.05, Math.max(0, dtSec)); // 首帧/掉帧的长间隔一律夹到 50ms,避免瞬移
const pos = Math.min(Math.max(s.pos, 0), overflow);
const state: MotionState = { pos, phase: s.phase, until: s.until };
if (state.phase === 'down') {
if (pos + geo.clientHeight >= geo.scrollHeight - 2) {
state.phase = 'holdB';
state.until = now + cfg.holdBottomMs;
state.pos = geo.scrollTop;
return { state, scrollTop: null };
}
state.pos = Math.min(pos + cfg.speed * dt, overflow);
return { state, scrollTop: state.pos };
}
if (state.phase === 'holdB') {
state.pos = geo.scrollTop;
if (now >= state.until) state.phase = 'up';
return { state, scrollTop: null };
}
if (state.phase === 'up') {
state.pos = pos - pos * Math.min(1, dt * cfg.rewind);
if (state.pos <= 0.5) {
state.pos = 0;
state.phase = 'holdT';
state.until = now + cfg.holdTopMs;
}
return { state, scrollTop: state.pos };
}
/* holdT:在顶部停一下,让最后一屏和第一屏之间有个呼吸口 */
state.pos = geo.scrollTop;
if (now >= state.until) state.phase = 'down';
return { state, scrollTop: null };
}
interface Options {
/** 鼠标移到列表上 / 用户自己滚过之后,暂停多久再续跑(ms) */
wheelCooldownMs?: number;
cfg?: MotionCfg;
}
/**
* 把 stepMotion 接到真实滚动容器上。
* enabled 变 false 时循环与监听一起摘掉,容器停在当前位置——这就是「关闭滚动」按钮的语义。
*/
export function useAutoScroll(
ref: RefObject<HTMLElement | null> | { current: HTMLElement | null },
enabled: boolean,
{ wheelCooldownMs = 2200, cfg = DEFAULT_MOTION }: Options = {},
) {
useEffect(() => {
const el = ref.current;
if (!el || !enabled) return;
/* 系统要求减少动态效果时不做自动滚动(按钮仍可开启,只是不动) */
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return;
let hovering = false;
let coolUntil = 0;
const cool = () => { coolUntil = performance.now() + wheelCooldownMs; };
const enter = () => { hovering = true; };
const leave = () => { hovering = false; };
el.addEventListener('wheel', cool, { passive: true });
el.addEventListener('touchstart', cool, { passive: true });
el.addEventListener('pointerenter', enter);
el.addEventListener('pointerleave', leave);
let state: MotionState = { pos: el.scrollTop, phase: 'down', until: 0 };
let last = performance.now();
let raf = 0;
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = (now - last) / 1000;
last = now;
const res = stepMotion(
state, now, dt,
{ scrollTop: el.scrollTop, clientHeight: el.clientHeight, scrollHeight: el.scrollHeight },
hovering || now < coolUntil, cfg,
);
state = res.state;
if (res.scrollTop !== null) el.scrollTop = res.scrollTop;
};
raf = requestAnimationFrame(frame);
return () => {
cancelAnimationFrame(raf);
el.removeEventListener('wheel', cool);
el.removeEventListener('touchstart', cool);
el.removeEventListener('pointerenter', enter);
el.removeEventListener('pointerleave', leave);
};
}, [ref, enabled, wheelCooldownMs, cfg]);
}
+46
View File
@@ -0,0 +1,46 @@
import { useEffect, useMemo, useState } from 'react';
import {
queryMetricTree, queryMetricLinks, queryDigitalStaff, queryAlertCounts,
} from '../data/sqlite';
import type { MetricNode, MetricLink, DigitalStaff } from '../data/sqlite';
export interface MecData {
tree: MetricNode[];
flat: MetricNode[];
byCode: Map<string, MetricNode>;
links: MetricLink[];
staff: DigitalStaff[];
alerts: { red: number; yellow: number; green: number; total: number };
}
const EMPTY: MecData = {
tree: [], flat: [], byCode: new Map(), links: [], staff: [],
alerts: { red: 0, yellow: 0, green: 0, total: 0 },
};
/** db 就绪后一次性把指标中台的数据读进内存,供三栏共享 */
export function useMecData(dbReady: boolean): MecData {
const [snap, setSnap] = useState<MecData | null>(null);
useEffect(() => {
if (!dbReady) return;
// 从带 12 期 trend 的树拍平,flat/byCode 同样拥有历史序列(时间游标依赖)
const tree = queryMetricTree();
const flat: MetricNode[] = [];
const byCode = new Map<string, MetricNode>();
const walk = (nodes: MetricNode[]) => nodes.forEach(n => {
flat.push(n);
byCode.set(n.code, n);
if (n.children?.length) walk(n.children);
});
walk(tree);
setSnap({
tree, flat, byCode,
links: queryMetricLinks(),
staff: queryDigitalStaff(),
alerts: queryAlertCounts(),
});
}, [dbReady]);
return useMemo(() => snap ?? EMPTY, [snap]);
}
+194
View File
@@ -0,0 +1,194 @@
type Dict = Record<string, string>;
export interface AgentDict {
title: string; subtitle: string; placeholder: string; send: string; thinking: string;
clear: string; expand: string; collapse: string; greeting: string;
tall: string; tallOff: string; dispatched: string;
secStatus: string; secStance: string; secProposal: string; handoff: string;
concl: string; keypoints: string; judgeLabel: string; actionsLabel: string;
/** 履约风险回答卡:思考过程(逐条揭示后可折叠)+ 六段式正文 */
aiName: string; thinkTitle: string; thinkHint: string; thinkSteps: string; thinkElapsed: string;
secIntent: string; secNumbers: string; secTable: string; secBasis: string; secActions: string; secSource: string;
thinkNumbers: string; thinkTable: string; thinkBasis: string; thinkActions: string; thinkSource: string;
askMore: string;
}
export interface I18n {
appTitle: string;
appSubTitle: string;
nav: Dict;
kpi: Dict;
dim: Dict;
common: Dict;
ai: Dict;
dashboard: Dict;
panel: Dict;
tab: Dict;
tree: Dict;
net: Dict;
flow: Dict;
detail: Dict;
staff: Dict;
team: Dict;
agent: AgentDict;
header: Dict;
res: Dict;
}
const zh: I18n = {
appTitle: '销售订单履约控制塔',
appSubTitle: '销售订单履约 · 需求计划 · 供应计划',
nav: {
cockpit: '经营驾驶舱', structure: '结构动因', quality: '质量健康',
efficiency: '运营效率', growth: '研发动能', market: '市场客户',
production: '生产供应', digital: '数智化与AI', risk: '风险韧性', aiAgent: 'AI 智能体',
},
kpi: {},
dim: {
overall: '经营总览', result: '财务成果', quality: '盈利质量', efficiency: '运营效率',
growth: '研发动能', market: '市场客户', production: '生产供应', digital: '数智化与AI',
risk: '风险韧性',
},
common: {
target: '目标', actual: '实际', yoy: '同比', mom: '环比', budget: '预算',
alert: '预警', trend: '趋势', detail: '详情', close: '关闭', search: '搜索',
export: '导出', refresh: '刷新', dark: '深色', light: '浅色',
unit: '单位', billion: '亿', million: '万',
percent: '%', days: '天', times: '次', score: '分', pt: '点',
collapse: '收起', expand: '展开', fullscreen: '全屏', exitFullscreen: '退出全屏',
back: '返回', all: '全部', none: '无', total: '合计', weight: '权重', owner: '责任部门',
formula: '计算口径', frequency: '更新频率', updatedAt: '更新于', loading: '加载中',
snapshot: '静态快照 · 不随时间轴',
noData: '暂无数据', more: '更多', reset: '重置',
initializing: '正在初始化数据库...', initFailed: '数据初始化失败',
initTimeout: '初始化超时(超过 20 秒),WASM 或数据未能加载完成', retry: '重试',
good: '达标', watch: '关注', urgent: '紧急', better: '向好', worse: '转弱',
},
header: {
health: '经营健康度', metricTotal: '纳管指标',
dataAt: '数据期',
},
panel: {
metricTree: '指标树', metricNetwork: '指标网络', digitalStaff: '数字员工',
workspace: '销售订单履约监控', agent: '智能体对话区',
legendExec: '预算执行率', legendOk: '达标', legendWarn: '未达标', legendBad: '低于{n}%',
},
tab: {
detail: '指标明细', trend: '趋势分析', structure: '结构动因',
region: '区域对比', risk: '风险矩阵', cockpit: '全景驾驶舱',
clickToRestore: '点击恢复',
},
tree: {
search: '搜索指标 / 编码 / 责任部门', expandAll: '全展开', collapseAll: '全收起',
level: '层级', nodes: '个节点', noResult: '没有匹配的指标',
lv0: 'L0 总览', lv1: 'L1 维度', lv2: 'L2 KPI', lv3: 'L3 驱动因子',
},
net: {
drive: '正向驱动', conflict: '负向制约', monitor: '风险监控',
center: '中心节点', isolate: '无跨树关联,仅参与上层合成',
resetView: '重置视角', toStage: '送入中央工作区', exitStage: '退出全景',
stageHint: '滚轮缩放 · 拖拽平移 · 悬停读数 · 双击飞临 · 点击节点→右侧因果看板',
influence: '影响分析', incoming: '驱动来源', outgoing: '影响去向',
noConn: '暂无跨指标关联,仅参与上层合成', hubHint: '点击维度枢纽联动 · 右上送入中央工作区看全景',
allNodes: '全部节点', focusSel: '聚焦选中', nodes: '项指标',
propagate: '影响传播', flyTo: '聚焦飞行', topChains: '全图最强因果链',
/* 降密与时间游标 */
leaves: '末级因子', tipToPanel: '点击看完整因果',
tlPlay: '回放', tlPause: '暂停', tlBack: '回当期', tlLabel: '时间轴',
/* 右侧因果看板 */
causalTitle: '因果看板', causalOpen: '因果看板', causalClose: '收起看板',
causalCursor: '游标读数', causalTrend: '12 期趋势',
causalIn: '前因 · 驱动来源', causalOut: '后果 · 影响去向', causalKids: '下级回应',
causalSibs: '同层对标',
causalAi: 'AI 研判', causalReport: '汇报口径',
causalNoIn: '无前因(链路源头)', causalNoOut: '无后果(终端指标)',
causalNoKid: '末级驱动因子,无下级指标', causalNoStaff: '暂无智能体值守',
zFinance: '财务与利润', zFactory: '智能工厂', zMarket: '销售与市场',
zRd: '研发中心', zData: '数据与AI中心', zRisk: '风控中心',
},
flow: {
title: '流程效能',
hint: '研产供销六段价值链的过程指标:停留、流转、一次通过、返工。结果指标请看指标树。',
vsTree: '过程看这里 · 结果看指标树',
summary: '全链汇总', cycle: '端到端周期', e2e: '全链一次通过',
throughput: '有效产出', constraint: '约束段', wip: '在制品', bottleneck: '瓶颈段',
dwell: '停留', flow: '月流转', fpqc: '一次通过', rework: '返工', score: '段达成',
linked: '关联指标', unitDay: '天', stageUnit: '段', base: '基线',
faster: '较上期提速', slower: '较上期变慢', flat: '与上期持平',
bottleneckTip: '达成率最低的一段,优先改善对象',
wipTip: '在制品 = 月流转 × 停留 ÷ 30(Little 法则)',
clickTip: '指标片可点开中央看板明细',
},
detail: {
title: '指标明细', current: '当期值', targetVal: '目标值', gap: '偏差',
achieve: '达成度', reach: '达成', trend12: '近 12 期趋势', composition: '构成拆解',
drivers: '驱动因子(L3)', parentChain: '归属链路', related: '关联指标',
desc: '指标说明', noDesc: '该节点为聚合层,无独立业务说明。',
subMetrics: '下级指标', alertRule: '预警阈值', polarity: '方向',
polarityUp: '越高越好', polarityDown: '越低越好',
contribution: '贡献度', historyTable: '历史明细', period: '期间',
dimWeight: '八大维度权重', productContrib: '产品线收入贡献', watchTop: '重点关注 Top6(按偏差排序)',
gapNote: '偏差已按指标方向归一:正数=优于目标,负数=待改善(成本/周期类越低越好)。',
driversNote: '条长与主数字同为偏差幅度(已归一),右侧小字为当期值。',
agentHint: '可向下方智能体提问:为什么这个指标偏离目标?',
},
staff: {
title: '数字员工', online: '在岗', busy: '作业中', idle: '待命',
alert: '待升级', offline: '停用', tasks: '今日已完成', success: '成功率',
confidence: '置信度', load: '负载', lastRun: '最近运行',
skills: '能力', current: '当前动作', wake: '唤醒对话', viewMetric: '查看指标',
autoScroll: '自动滚动', pause: '暂停滚动', detail: '详情',
emptyFilter: '该状态下没有数字员工', filterAll: '全部',
},
team: {
entry: '组建专家团', panel: '专家团', back: '返回数字员工',
presetTitle: '预设专家团', customTitle: '自由勾选组建',
presetHint: '点击预设团一键就位,或在下方勾选智能体自建团队',
customHint: '勾选 2 位及以上智能体,首位为牵头',
selected: '已选成员', lead: '牵头', member: '成员',
convene: '发起会诊', conveneN: '发起会诊({n})', dismiss: '解散专家团',
needTwo: '至少选择 2 位智能体', clearSel: '清空',
activeTeam: '当前专家团', topic: '议题',
},
agent: {
title: '智能体对话', subtitle: '由在岗数字员工协同应答',
placeholder: '针对上方仪表内容追问根因,例如:哪些订单可能延期?',
send: '发送', thinking: '分析中', clear: '清空', expand: '展开', collapse: '收起',
tall: '拉高', tallOff: '还原高度',
greeting: '按 销售订单 → 工单 → 材料 → 采购 这条链路帮你追问根因、给出行动建议。'
+ '有什么问题请直接提问,或点下面的问题。',
dispatched: '已把该问题派发给',
secStatus: '现状', secStance: '观点', secProposal: '建议', handoff: '移交',
concl: '会诊结论', keypoints: '成员要点', judgeLabel: '综合研判', actionsLabel: '联合行动',
aiName: '履约风险智能体',
thinkTitle: '思考过程', thinkHint: '正在按业务本体规则推演',
thinkSteps: '{n} 步', thinkElapsed: '耗时 {s}s',
secIntent: '识别意图', secNumbers: '关键数字', secTable: '风险明细',
secBasis: '依据与口径', secActions: '建议动作', secSource: '数据来源',
thinkNumbers: '正在提取关键数字…',
thinkTable: '正在整理风险明细表…',
thinkBasis: '正在核对依据与口径…',
thinkActions: '正在生成建议动作…',
thinkSource: '正在标注数据来源…',
askMore: '继续追问',
},
res: {
region: '区域', revenue: '营业收入', headcount: '人数', perCapita: '人均产值',
grossMargin: '毛利率', productLine: '产品线', share: '占比', yoy: '同比增速',
riskName: '风险项', probability: '概率', impact: '影响', status: '状态',
netProfit: '归母净利润', newOrders: '新增订单', backlog: '在手订单', prob: '概率',
},
ai: {
title: '经营分析 AI 助手',
placeholder: '请输入您的问题,例如:本月营收为什么低于预算?',
send: '发送', thinking: '分析中...',
presetQ1: '本月经营概况?', presetQ2: '哪个产品线毛利率下降最多?',
presetQ3: '存货周转天数超标的品类有哪些?', presetQ4: '海外市场中哪个区域增速最快?',
},
dashboard: {
overview: '经营全景', finance: '财务表现', marketCustomer: '市场与客户',
supplyChain: '供应链与生产', digitalAI: '数智化进程', riskResilience: '风险与韧性',
},
};
/** 全站仅中文:词典不再按语言索引,useText() 直接把这份对象发给组件 */
export const texts: I18n = zh;
+12
View File
@@ -0,0 +1,12 @@
import { texts } from './locales';
import type { I18n } from './locales';
export type { I18n };
/**
* 全站只有中文一套文案(本系统不面向日本用户),
* 因此不再需要 Locale 状态、localStorage 记忆与 Provider:直接读词典。
*/
export function useText(): { t: I18n } {
return { t: texts };
}
+164
View File
@@ -0,0 +1,164 @@
/* 本模块样式仅保留动效/工具类;base 重置与 tailwind 由平台全局 index.css 提供 */
button { cursor: pointer; }
input, textarea { font-family: inherit; }
/* ═══════════════════════════════════════════
太空舱 / 三栏工作区 动效层
═══════════════════════════════════════════ */
@keyframes fade-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes pulse-glow {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
@keyframes number-roll {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes slide-in-left {
from { opacity: 0; transform: translateX(-20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slide-in-right {
from { opacity: 0; transform: translateX(20px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes slide-in-up {
from { opacity: 0; transform: translateY(16px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes card-in {
from { opacity: 0; transform: translateY(8px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes notice-in {
from { opacity: 0; transform: translateX(-12px); }
to { opacity: 1; transform: translateX(0); }
}
@keyframes content-reveal {
from { opacity: 0; transform: translateY(18px) scale(0.97); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes space-pulse {
0%, 100% { opacity: 0.55; }
50% { opacity: 1; }
}
@keyframes glow-pulse {
0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); }
50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); }
}
@keyframes dot-blink {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.35; transform: scale(0.78); }
}
@keyframes scan-sweep {
0% { left: -30%; }
100% { left: 110%; }
}
@keyframes typing-dot {
0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }
30% { opacity: 1; transform: translateY(-3px); }
}
@keyframes stream-cursor-blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
@keyframes bar-grow {
from { transform: scaleY(0.05); }
to { transform: scaleY(1); }
}
@keyframes dash-flow {
to { stroke-dashoffset: -24; }
}
/* 折线图:进场时把线"画"出来,点随后淡入,避免曲线一瞬间糊在屏上 */
@keyframes trend-draw {
from { stroke-dasharray: 2000; stroke-dashoffset: 2000; }
to { stroke-dasharray: 2000; stroke-dashoffset: 0; }
}
@keyframes trend-fade {
from { opacity: 0; }
to { opacity: 1; }
}
.trend-line { animation: trend-draw 1.1s cubic-bezier(0.4,0,0.2,1) both; }
.trend-dot { animation: trend-fade 0.4s ease-out 0.7s both; }
/* ═══════════════════════════════════════════
指标知识图谱 · 深空叙事动效层
(恒星呼吸 / 声呐告警 / 轨道旋转 / 传播涟漪 / 雷达扫描 / 星云漂移)
═══════════════════════════════════════════ */
@keyframes net-breathe {
0%, 100% { transform: scale(1); opacity: 0.5; }
50% { transform: scale(1.16); opacity: 0.95; }
}
@keyframes net-sonar {
0% { transform: scale(1); opacity: 0.5; }
75%,100% { transform: scale(3.6); opacity: 0; }
}
@keyframes net-orbit-spin { to { transform: rotate(360deg); } }
@keyframes net-ripple-in {
from { transform: scale(0.35); opacity: 0; }
to { transform: scale(1); opacity: 1; }
}
@keyframes net-radar { to { transform: rotate(360deg); } }
@keyframes net-twinkle {
0%, 100% { opacity: var(--tw-o, 0.5); }
50% { opacity: 0.08; }
}
@keyframes net-nebula {
0%, 100% { transform: translate(0, 0) scale(1); }
50% { transform: translate(-5%, 4%) scale(1.12); }
}
/* SVG 几何元素统一用 fill-box 做变换基准,保证 scale/rotate 围绕自身中心 */
.net-breathe { transform-box: fill-box; transform-origin: center; animation: net-breathe 4.2s ease-in-out infinite; }
.net-sonar { transform-box: fill-box; transform-origin: center; animation: net-sonar 3.6s ease-out infinite; }
.net-sonar-slow { animation-duration: 5.4s; }
.net-orbit { transform-box: fill-box; transform-origin: center; animation: net-orbit-spin 52s linear infinite; }
.net-orbit-rev { animation-direction: reverse; animation-duration: 78s; }
.net-ripple { transform-box: fill-box; transform-origin: center; animation: net-ripple-in 0.7s cubic-bezier(0.34,1.56,0.64,1) both; }
.net-twinkle { animation: net-twinkle var(--tw-d, 4s) ease-in-out infinite; animation-delay: var(--tw-delay, 0s); }
.net-nebula { animation: net-nebula var(--nb-d, 46s) ease-in-out infinite alternate; }
.animate-fade-in { animation: fade-in 0.4s ease-out; }
.animate-slide-in { animation: slide-in-left 0.3s ease-out; }
.animate-number { animation: number-roll 0.5s ease-out; }
.space-animate-left { animation: slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-right{ animation: slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); }
.space-animate-up { animation: slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); }
.card-in { animation: card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.notice-in { animation: notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }
.content-reveal { animation: content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; }
.stream-cursor { animation: stream-cursor-blink 0.9s step-end infinite; }
.space-pulse { animation: space-pulse 2.4s ease-in-out infinite; }
.dot-blink { animation: dot-blink 1.6s ease-in-out infinite; }
.glow-pulse { animation: glow-pulse 3s ease-in-out infinite; }
.bar-grow { animation: bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; }
.dash-flow { animation: dash-flow 1.2s linear infinite; }
/* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */
::-webkit-scrollbar { width: 5px; height: 5px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; }
::-webkit-scrollbar-corner { background: transparent; }
.space-scroll::-webkit-scrollbar { width: 4px; height: 8px; }
.space-scroll::-webkit-scrollbar-track { background: transparent; }
.space-scroll::-webkit-scrollbar-thumb { background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; }
/* 面板通用过渡 */
.panel-shell { transition: width 0.3s cubic-bezier(0.4,0,0.2,1); }
.ghost-btn { transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease; }
.ghost-btn:hover { background: var(--hover-bg, rgba(79,70,229,0.07)); }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
+14
View File
@@ -0,0 +1,14 @@
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: 'jieya-ibp',
name: '销售订单履约控制塔',
description: '洁雅家居智能经营平台:销售订单履约风险识别、需求计划、供应计划与指标知识图谱',
icon: 'Radar',
path: '/jieya-ibp',
accentColor: '#7c3aed',
accentColorLight: '#4c1d95',
gradient: 'linear-gradient(135deg, #1a1033, #2d1b5e, #3b2a7a)',
gradientLight: 'linear-gradient(135deg, #f0eaff, #e6dcff, #dcd0ff)',
tags: ['履约', '指标树', '知识图谱'],
};
+467
View File
@@ -0,0 +1,467 @@
import type { MetricLink, MetricNode } from '../data/sqlite';
import { queryProductLines, queryRegions, queryRisks, queryTrend } from '../data/sqlite';
import { achieveRate, fmt, fmtSigned, gapOf } from './metric';
import type { ParsedAsk } from './intent';
/**
* 结构化回答引擎:消费 intent.ts 的解析结果,查询 SQL 数据层,
* 产出对齐设计书 5.3 五段式(结论 + 迷你图 + 分点 + 行动 + 来源)的 AiReply。
* 全部计算离线完成:外推用最小二乘、传播用网络边强度、归因用偏差×权重贡献分解。
*/
export interface AiSpark {
/** 折线值:历史 12 期(+ 假设/外推段) */
values: number[];
/** values 末尾多少点属于外推(虚线渲染) */
forecastCount?: number;
/** 目标参考虚线 */
target?: number;
unit: string;
}
export interface AiPoint { label?: string; text: string; tone?: 'good' | 'warn' | 'bad' }
export interface AiAction {
label: string;
/** 跳转到指标(联动左侧树与中央看板) */
code?: string;
/** 以该问句继续追问 */
ask?: string;
}
export interface AiReply {
/** 核心结论:1-2 句,直接回答问句 */
conclusion: string;
spark?: AiSpark;
/** 分点详细分析 */
points: AiPoint[];
/** 建议行动(可点击) */
actions: AiAction[];
/** 数据来源标注:数据域 + 更新频率 + 权限 */
source: string;
/** 回答聚焦的指标,用于行动按钮联动 */
focusCode?: string;
}
export interface AnswerCtx {
flat: MetricNode[];
byCode: Map<string, MetricNode>;
links: MetricLink[];
/** 全局时间游标:历史序列截断到该期,结论文字与迷你图同口径(节点值已由 App 层投影) */
period: number;
}
const label = (n: MetricNode) => n.name_zh;
const unitOf = (n: MetricNode) => n.unit;
const SRC_METRIC = '指标中台(metric_node / metric_trend / metric_link)· 月度更新 · 内部可见';
const SRC_BIZ = '经营分析(product_line / region_data / risk_matrix)· 季度更新 · 内部可见';
/** 最小二乘线性回归:返回斜率与外推函数 */
function linreg(ys: number[]) {
const n = ys.length;
if (n < 2) return { slope: 0, at: (_i: number) => ys[0] ?? 0 };
const mx = (n - 1) / 2;
const my = ys.reduce((a, b) => a + b, 0) / n;
let num = 0, den = 0;
for (let i = 0; i < n; i++) { num += (i - mx) * (ys[i] - my); den += (i - mx) ** 2; }
const slope = den ? num / den : 0;
return { slope, at: (i: number) => my + slope * (i - mx) };
}
/** 游标前的历史序列(含游标当期):回答不会把“未来月份”当成已经历的实绩 */
const trendOf = (code: string, period: number): number[] =>
queryTrend(code).map(p => p.actual).slice(0, Math.max(2, period + 1));
/** 游标口径的红黄绿计数:ctx.flat 已由 App 投影,直接按定级字段统计即得该时点分布 */
const countAlerts = (ctx: AnswerCtx) => {
let red = 0, yellow = 0, green = 0;
ctx.flat.forEach(n => {
if (n.level < 2) return;
if (n.alert_level === 'red') red++;
else if (n.alert_level === 'yellow') yellow++;
else green++;
});
return { red, yellow, green, total: ctx.flat.length };
};
/** 偏差 / 变化量单位:% 类指标用百分点 pt(与目标值本身的 % 区分口径),其余按语言取单位 */
const gapUnit = (n: MetricNode) => (n.unit === '%' ? 'pt' : n.unit);
/* ── 各意图引擎 ─────────────────────────────────────────────────────────── */
/** 指标查询:当期值 / 目标 / 偏差 / 达成率 + 趋势 + 最大拖累 */
function answerQuery(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const n = ctx.byCode.get(parsed.metricCode!)!;
const gap = gapOf(n);
const rate = achieveRate(n);
const trend = trendOf(n.code, ctx.period);
const last3 = trend.slice(-3);
const good = gap >= 0;
const kids = ctx.flat
.filter(k => k.parent_code === n.code)
.sort((a, b) => Math.abs(gapOf(b)) - Math.abs(gapOf(a)));
const worst = kids.find(k => gapOf(k) < 0);
const mom = last3.length >= 2 ? last3[2] - last3[0] : 0;
const conclusion = `「${label(n)}」当期 ${fmt(n.value)}${unitOf(n)},目标 ${fmt(n.target)}${unitOf(n)}(偏差 ${fmtSigned(gap)}${gapUnit(n)}),达成率 ${fmt(rate, 0)}%,${good ? '处于达标线以上。' : '尚未达标。'}`;
return {
conclusion,
spark: { values: trend, target: n.target, unit: unitOf(n) },
focusCode: n.code,
points: [
{ label: '责任部门', text: `${n.owner} · ${n.frequency}更新` },
{ label: '近 3 期', text: `${last3.map(v => fmt(v)).join(' → ')}${unitOf(n)}(${mom >= 0 ? ('改善基调') : ('走弱')})`, tone: mom >= 0 ? 'good' : 'warn' },
worst && {
label: '最大拖累',
text: `下层「${label(worst)}」偏差最大(${fmtSigned(gapOf(worst))}${gapUnit(worst)})`,
tone: 'bad',
},
{ label: '指标说明', text: n.desc_zh},
].filter(Boolean) as AiPoint[],
actions: [
{ label: `查看「${label(n)}」归因`, code: n.code, ask: `${n.name_zh}为什么低于目标`},
{ label: '趋势预测', ask: `预测${n.name_zh}下月走势`},
],
source: SRC_METRIC,
};
}
/** 归因分析:子因子偏差×权重贡献分解 + 跨树驱动边排序 */
function answerAttribute(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!;
const gap = gapOf(n);
const kids = ctx.flat.filter(k => k.parent_code === n.code);
const contribs = kids
.map(k => ({ node: k, contrib: +(gapOf(k) * k.weight).toFixed(2) }))
.sort((a, b) => a.contrib - b.contrib); // 负贡献(拖累)优先
const totalNeg = contribs.filter(c => c.contrib < 0).reduce((a, b) => a + Math.abs(b.contrib), 0) || 1;
const outsiders = ctx.links
.filter(l => l.to_code === n.code && !kids.some(k => k.code === l.from_code))
.map(l => ({ link: l, node: ctx.byCode.get(l.from_code)! }))
.filter(x => x.node)
.sort((a, b) => Math.abs(b.link.strength) - Math.abs(a.link.strength))
.slice(0, 2);
const top = contribs.slice(0, 3);
const topStr = top
.map(c => `${label(c.node)}(贡献 ${Math.round(Math.abs(c.contrib) / totalNeg * 100)}%)`)
.join('、');
const conclusion = `「${label(n)}」偏差 ${fmtSigned(gap)}${gapUnit(n)} 的主因:${topStr}。属于结构性偏离,建议优先调整产品与供应结构,而非单纯压费用。`;
return {
conclusion,
spark: { values: trendOf(n.code, ctx.period), target: n.target, unit: unitOf(n) },
focusCode: n.code,
points: [
...top.map(c => ({
label: label(c.node),
text: `当期 ${fmt(c.node.value)}${unitOf(c.node)} / 目标 ${fmt(c.node.target)}${unitOf(c.node)}(${fmtSigned(gapOf(c.node))}${gapUnit(c.node)})· ${c.node.owner}`,
tone: c.contrib < 0 ? 'bad' as const : 'good' as const,
})),
...outsiders.map(x => ({
label: '跨树驱动',
text: `「${label(x.node)}」→ 本指标(强度 ${x.link.strength},${x.link.relation === 'conflict' ? '负向制约' : '正向驱动'})`,
})),
],
actions: [
...(top[0] ? [{ label: `打开主因「${label(top[0].node)}」`, code: top[0].node.code }] : []),
...(top[0] ? [{ label: `模拟改善路径`, ask: `如果${top[0].node.name_zh}提升到目标会怎样`}] : []),
],
source: SRC_METRIC,
};
}
/** 趋势预测:最小二乘外推 3 期 + 达标判断(在手订单特例:收入支撑度) */
function answerForecast(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const n = ctx.byCode.get(parsed.metricCode ?? 'R01')!;
const trend = trendOf(n.code, ctx.period);
const { slope, at } = linreg(trend);
/* 从游标往后外推三期(不是从 12 月末),历史越短回归越不稳定,因而标注样本期数 */
const h = trend.length;
const ext = [at(h), at(h + 1), at(h + 2)].map(v => +v.toFixed(2));
const end = ext[2];
const endGap = n.polarity === 'down' ? -(end - n.target) : end - n.target;
const willHit = endGap >= 0;
let conclusion: string;
const tail = `${fmt(trend[h - 1])} → ${fmt(ext[0])} → ${fmt(ext[2])}${unitOf(n)}`;
if (n.code === 'R10') {
const r1 = ctx.byCode.get('R01')!;
const cover = +((n.value / (r1.value * 3) * 100)).toFixed(1);
conclusion = `在手订单 ${fmt(n.value)}${unitOf(n)}约可覆盖未来 3 个月收入节奏(月均 ${fmt(r1.value)}${unitOf(r1)})的 ${fmt(cover, 0)}%,缺口需靠新签订单补齐。在手订单趋势:${tail}。`;
} else {
conclusion = `按游标前 ${h} 期线性趋势外推:「${label(n)}」下期 ${fmt(ext[0])}${unitOf(n)},3 期后 ${fmt(end)}${unitOf(n)}。对比目标 ${fmt(n.target)}${unitOf(n)},${willHit ? '有望达成' : `仍差 ${fmt(Math.abs(endGap))}${gapUnit(n)}`}。`;
}
const mom = slope; // 每期平均变化
return {
conclusion,
spark: { values: [...trend, ...ext], forecastCount: 3, target: n.target, unit: unitOf(n) },
focusCode: n.code,
points: [
{ label: '趋势斜率', text: `每期 ${fmtSigned(mom, 2)}${gapUnit(n)}(${h} 期回归斜率)`, tone: mom >= 0 ? 'good' : 'warn' },
{ label: '近期动能', text: trend.slice(-3).map(v => fmt(v)).join(' → ') + unitOf(n) },
{ label: '达标判定', text: willHit ? (`3 期外推终点回到目标线以上`) : (`当前节奏下缺口将持续,需要额外举措拉动`), tone: willHit ? 'good' : 'bad' },
],
actions: [
{ label: `查看「${label(n)}」归因`, code: n.code, ask: `${n.name_zh}为什么低于目标`},
],
source: SRC_METRIC + (' ※线性回归外推'),
};
}
/** 假设模拟:假设值 → 相对变化率沿网络边强度传播(单位无关近似) */
function answerWhatIf(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!;
const hasAbs = parsed.absValue !== undefined;
const hasDelta = parsed.deltaValue !== undefined;
if (!hasAbs && !hasDelta) {
return {
conclusion: `模拟需要给出假设数值。例如:「如果高毛利产品占比提升到 40% 会怎样」,指定指标与目标值即可推演。`,
points: [],
actions: [{ label: '试一个例子', ask: '如果高毛利产品占比提升到 40% 会怎样'}],
source: SRC_METRIC,
focusCode: n.code,
};
}
const newValue = hasAbs ? parsed.absValue! : +(n.value + parsed.deltaValue!).toFixed(2);
const delta = +(newValue - n.value).toFixed(2);
const relChange = n.value !== 0 ? delta / Math.abs(n.value) : 0;
const outs = ctx.links
.filter(l => l.from_code === n.code)
.map(l => ({ link: l, node: ctx.byCode.get(l.to_code)! }))
.filter(x => x.node)
.sort((a, b) => Math.abs(b.link.strength) - Math.abs(a.link.strength))
.slice(0, 3);
const selfGapNew = n.polarity === 'down' ? -(newValue - n.target) : newValue - n.target;
const conclusion = `若「${label(n)}」从 ${fmt(n.value)}${unitOf(n)} 变为 ${fmt(newValue)}${unitOf(n)}(${fmtSigned(delta)}${gapUnit(n)}):${selfGapNew >= 0 ? '该指标将回到目标线以上' : '该指标仍低于目标'}。${outs.length ? `影响最大的下游是「${label(outs[0].node)}」。` : ''}`;
return {
conclusion,
spark: { values: [...trendOf(n.code, ctx.period), newValue], forecastCount: 1, target: n.target, unit: unitOf(n) },
focusCode: n.code,
points: [
{
label: label(n),
text: `对比目标 ${fmt(n.target)}${unitOf(n)}:${selfGapNew >= 0 ? '达标(偏差' : '未达标(缺口'}${fmtSigned(selfGapNew)}${gapUnit(n)})`,
tone: selfGapNew >= 0 ? 'good' : 'warn',
},
...outs.map(x => {
const impacted = +(x.node.value * (1 + x.link.strength * relChange)).toFixed(2);
const chg = +(impacted - x.node.value).toFixed(2);
return {
label: label(x.node),
text: `${fmt(x.node.value)} → ${fmt(impacted)}${unitOf(x.node)}(${fmtSigned(chg)}${gapUnit(x.node)},传播强度 ${x.link.strength})`,
tone: chg >= 0 ? ('good' as const) : ('warn' as const),
};
}),
],
actions: [
{ label: `打开「${label(n)}」`, code: n.code },
...(outs[0] ? [{ label: `查看受影响的「${label(outs[0].node)}」`, code: outs[0].node.code }] : []),
],
source: SRC_METRIC + (' ※按网络边强度线性传播近似'),
};
}
/** 对比分析:产品线 / 区域 */
function answerCompare(parsed: ParsedAsk, _ctx: AnswerCtx): AiReply {
if (parsed.compareScope === 'region') {
const regions = queryRegions();
const top = regions[0];
const weakMargin = [...regions].sort((a, b) => a.gross_margin - b.gross_margin)[0];
const bestPerCapita = [...regions].sort((a, b) => b.per_capita - a.per_capita)[0];
return {
conclusion: `${top.name_zh}收入贡献最大(${fmt(top.revenue)} 亿元,占 ${fmt((top.revenue / regions.reduce((a, r) => a + r.revenue, 0)) * 100, 0)}%);人均产值以${bestPerCapita.name_zh}最高(${fmt(bestPerCapita.per_capita, 0)} 万元);${weakMargin.name_zh}毛利率最低(${fmt(weakMargin.gross_margin)}%),是盈利结构的洼地。`,
points: regions.map(r => ({
label: r.name_zh,
text: `收入 ${fmt(r.revenue)} 亿元 · 毛利率 ${fmt(r.gross_margin)}% · 人均产值 ${fmt(r.per_capita, 0)} 万元 · ${fmt(r.headcount, 0)} 人`,
tone: r.gross_margin === weakMargin.gross_margin ? 'bad' as const : undefined,
})),
actions: [{ label: '切到指标明细查看区域对比', code: 'R01' }],
source: SRC_BIZ,
};
}
const lines = queryProductLines();
const byRevenue = [...lines].sort((a, b) => b.revenue - a.revenue);
const byMargin = [...lines].sort((a, b) => b.gross_margin - a.gross_margin);
const byGrowth = [...lines].sort((a, b) => b.yoy_growth - a.yoy_growth);
const total = lines.reduce((a, l) => a + l.revenue, 0);
return {
conclusion: `${byRevenue[0].name_zh}收入规模最大(${fmt(byRevenue[0].revenue)} 亿元,占 ${fmt(byRevenue[0].revenue / total * 100, 0)}%);${byMargin[0].name_zh}毛利率最高(${fmt(byMargin[0].gross_margin)}%);${byGrowth[0].name_zh}增速最快(+${fmt(byGrowth[0].yoy_growth)}%),是结构升级的主引擎。`,
points: lines.map(l => ({
label: l.name_zh,
text: `收入 ${fmt(l.revenue)} 亿元(占比 ${fmt(l.share)}%)· 毛利率 ${fmt(l.gross_margin)}% · 同比 +${fmt(l.yoy_growth)}%`,
tone: l.gross_margin === byMargin[byMargin.length - 1].gross_margin ? 'warn' as const : undefined,
})),
actions: [
{ label: '模拟高毛利占比提升', ask: '如果高毛利产品占比提升到 40% 会怎样'},
{ label: '毛利率归因分析', ask: '毛利率为什么低于目标'},
],
source: SRC_BIZ,
};
}
/** 异常检测:红色 + 黄色偏离清单 */
function answerAnomaly(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const counts = countAlerts(ctx);
const bad = ctx.flat
.filter(n => n.level >= 2 && (n.alert_level === 'red' || (n.alert_level === 'yellow' && gapOf(n) < 0)))
.sort((a, b) => (a.alert_level === 'red' ? -1 : 1) - (b.alert_level === 'red' ? -1 : 1) || achieveRate(a) - achieveRate(b))
.slice(0, 5);
const worst = bad[0];
return {
conclusion: `当前红色告警 ${counts.red} 项、黄色偏离 ${counts.yellow} 项。最紧急:${worst ? `「${label(worst)}」达成率仅 ${fmt(achieveRate(worst), 0)}%` : '无'}。`,
points: bad.map(n => ({
label: `${label(n)}${n.alert_level === 'red' ? ' 🔴' : ' 🟡'}`,
text: `当期 ${fmt(n.value)}${unitOf(n)} / 目标 ${fmt(n.target)}${unitOf(n)}(偏差 ${fmtSigned(gapOf(n))}${gapUnit(n)})· ${n.owner}`,
tone: n.alert_level === 'red' ? 'bad' as const : 'warn' as const,
})),
actions: [
...(worst ? [{ label: `打开「${label(worst)}」`, code: worst.code }] : []),
{ label: '查看升级建议', ask: '哪些指标需要升级'},
],
source: SRC_METRIC,
};
}
/** 升级处置:红色 + 连续 3 期低于目标 */
function answerEscalate(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const streakOf = (n: MetricNode) => {
const ts = queryTrend(n.code).slice(0, Math.max(1, ctx.period + 1));
const gaps = ts.map(p => (n.polarity === 'down' ? -(p.actual - p.target) : p.actual - p.target));
let s = 0;
for (let i = gaps.length - 1; i >= 0 && gaps[i] < 0; i--) s++;
return s;
};
const targets = ctx.flat
.filter(n => n.level >= 2 && (n.alert_level === 'red' || streakOf(n) >= 3))
.map(n => ({ n, streak: streakOf(n) }))
.sort((a, b) => (a.n.alert_level === 'red' ? -1 : 1) - (b.n.alert_level === 'red' ? -1 : 1) || b.streak - a.streak)
.slice(0, 4);
return {
conclusion: `建议升级 ${targets.length} 项:${targets.map(x => label(x.n)).join('、') || '—'}。红色或连续 3 期未达标已触发上报阈值,建议纳入经营例会跟踪。`,
points: targets.map(x => ({
label: label(x.n),
text: `${x.streak >= 3 ? `连续 ${x.streak} 期低于目标` : '触发预警阈值'} · 责任部门 ${x.n.owner} · 达成率 ${fmt(achieveRate(x.n), 0)}%`,
tone: 'bad' as const,
})),
actions: targets.slice(0, 2).flatMap(x => [
{ label: `打开「${label(x.n)}」`, code: x.n.code },
]),
source: SRC_METRIC,
};
}
/** 行动建议:偏差拉回路径(子因子 top2) */
function answerAdvice(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const n = ctx.byCode.get(parsed.metricCode ?? 'R04')!;
const gap = gapOf(n);
const kids = ctx.flat
.filter(k => k.parent_code === n.code && gapOf(k) < 0)
.sort((a, b) => Math.abs(gapOf(b)) - Math.abs(gapOf(a)))
.slice(0, 2);
const paths = kids.length ? kids : ctx.flat.filter(k => k.parent_code === n.code).slice(0, 2);
return {
conclusion: `把「${label(n)}」拉回目标 ${fmt(n.target)}${unitOf(n)} 的两条路径:${paths.map(k => `将「${label(k)}」从 ${fmt(k.value)}${unitOf(k)} 提到 ${fmt(k.target)}${unitOf(k)}`).join(';')}。`,
spark: { values: trendOf(n.code, ctx.period), target: n.target, unit: unitOf(n) },
focusCode: n.code,
points: [
...paths.map((k, i) => ({
label: `路径 ${i + 1}`,
text: `把「${label(k)}」提到 ${fmt(k.target)}${unitOf(k)}(当前 ${fmt(k.value)}${unitOf(k)},偏差 ${fmtSigned(gapOf(k))}${gapUnit(k)})· 责任部门 ${k.owner}`,
tone: 'warn' as const,
})),
{
label: '现状',
text: `本指标达成率 ${fmt(achieveRate(n), 0)}%(偏差 ${fmtSigned(gap)}${gapUnit(n)}),${gap >= 0 ? '当前保持达标' : '需要纠偏动作'}`,
},
],
actions: [
...(paths[0] ? [
{ label: `模拟路径 1 影响`, ask: `如果${paths[0].name_zh}提升到 ${fmt(paths[0].target)}会怎样`},
{ label: `打开「${label(paths[0])}」`, code: paths[0].code },
] : []),
],
source: SRC_METRIC,
};
}
/** 经营总览:OV + 八维度 + 红黄绿 */
function answerOverview(_parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
const ov = ctx.byCode.get('OV')!;
const dims = ctx.flat.filter(n => n.level === 1).sort((a, b) => gapOf(b) - gapOf(a));
const counts = countAlerts(ctx);
const weakest = dims[dims.length - 1];
const strongest = dims[0];
return {
conclusion: `整体经营健康度 ${fmt(ov.value)} 分(目标 ${fmt(ov.target)} 分,达成率 ${fmt(achieveRate(ov), 0)}%)。八大维度 ${dims.filter(d => d.alert_level === 'green').length} 项绿灯,最弱的是「${label(weakest)}」(${fmt(weakest.value)} 分)。`,
spark: { values: trendOf('OV', ctx.period), target: ov.target, unit: '分'},
focusCode: 'OV',
points: [
{ label: '最强维度', text: `「${label(strongest)}」${fmt(strongest.value)} 分(偏差 ${fmtSigned(gapOf(strongest))} 分)`, tone: 'good' },
{ label: '最弱维度', text: `「${label(weakest)}」${fmt(weakest.value)} 分(偏差 ${fmtSigned(gapOf(weakest))} 分)· 瓶颈在 AI 渗透与数据资产在线率`, tone: 'bad' },
{ label: '指标状态', text: `L2 及以下:红色 ${counts.red} 项 / 黄色 ${counts.yellow} 项 / 绿色 ${counts.green} 项(共 ${counts.total - 9} 项)`},
],
actions: [
{ label: `打开「${label(weakest)}」`, code: weakest.code },
{ label: '查看异常指标', ask: '哪些指标异常'},
],
source: SRC_METRIC,
};
}
/** 风险矩阵 */
function answerRisk(_parsed: ParsedAsk, _ctx: AnswerCtx): AiReply {
const risks = queryRisks();
const top = risks[0];
const escalated = risks.filter(r => r.status_zh.includes('升级'));
return {
conclusion: `当前登记风险 ${risks.length} 项。评分最高:${top.name_zh}(概率 ${fmt(top.probability, 1)} × 影响 ${fmt(top.impact, 1)})。${escalated.length ? `已升级 ${escalated.length} 项(${escalated.map(r => r.name_zh).join('、')}),需管理层跟踪。` : ''}`,
points: risks.slice(0, 4).map(r => ({
label: r.name_zh,
text: `概率 ${fmt(r.probability, 1)} × 影响 ${fmt(r.impact, 1)} · ${r.status_zh}`,
tone: (r.probability * r.impact) >= 0.4 ? 'bad' as const : 'warn' as const,
})),
actions: [{ label: '打开风险敞口指数', code: 'RK01' }],
source: SRC_BIZ,
};
}
/** 兜底:能力引导 */
function answerFallback(_parsed: ParsedAsk, _ctx: AnswerCtx): AiReply {
const samples: [string, string][] = ([
['指标查询', '毛利率现在多少?'],
['归因分析', '毛利率为什么低于目标?'],
['趋势预测', '预测下季度营业收入'],
['假设模拟', '如果高毛利产品占比提升到 40% 会怎样'],
['对比分析', '各产品线毛利率对比'],
]);
return {
conclusion: '这个问题我暂时没有理解。围绕经营指标,我可以帮你做这些:',
points: samples.map(([cap, q]) => ({ label: cap, text: q })),
actions: samples.map(([cap, q]) => ({ label: cap, ask: q })),
source: SRC_METRIC,
};
}
/* ── 主入口 ─────────────────────────────────────────────────────────────── */
export function buildAnswer(parsed: ParsedAsk, ctx: AnswerCtx): AiReply {
switch (parsed.intent) {
case 'query': return answerQuery(parsed, ctx);
case 'attribute': return answerAttribute(parsed, ctx);
case 'forecast': return answerForecast(parsed, ctx);
case 'whatif': return answerWhatIf(parsed, ctx);
case 'compare': return answerCompare(parsed, ctx);
case 'anomaly': return answerAnomaly(parsed, ctx);
case 'escalate': return answerEscalate(parsed, ctx);
case 'advice': return answerAdvice(parsed, ctx);
case 'overview': return answerOverview(parsed, ctx);
case 'risk': return answerRisk(parsed, ctx);
default: return answerFallback(parsed, ctx);
}
}
+523
View File
@@ -0,0 +1,523 @@
import {
ONTOLOGY_AS_OF, PATH, actions, objects, purchaseGroups, relations, rules, type PathRow,
} from '../data/ontology';
import {
customers, items, productionOrders, purchaseOrders, salesOrders, suppliers, workOrderMaterials,
type PurchaseOrder, type SalesOrder,
} from '../data/ibp';
import { money, moneyW } from './money';
/**
* 履约风险问答引擎:把「智能体对话」从旧的指标树问答换成本应用真正的目标——
* 销售订单履约风险识别。所有数字都从 ontology 层现算(规则命中、关键路径中间量),
* 与「业务本体总览」页同源,对话里出现的每个数都能在本体页找到同一口径的出处。
*
* 回答是结构化的(结论 / 关键数字 / 明细表 / 依据与口径 / 建议动作 / 数据来源),
* 并带一份「思考步骤」:前端按步骤逐条揭示,让推演过程可见而不是瞬间甩结论。
*/
export type AskTone = 'success' | 'warning' | 'danger' | 'info';
export interface AskStep { act: string; detail: string }
export interface AskMetric { label: string; value: string; tone?: AskTone }
export interface AskTableRow { cells: string[]; tone?: AskTone }
export interface AskTable { cols: string[]; rows: AskTableRow[] }
export interface AskPoint { label: string; text: string; tone?: AskTone }
export interface AskAction {
label: string;
/** 以该问句继续追问 */
ask?: string;
/** 在左栏选中该销售订单 */
locateSO?: string;
/** 打开业务本体总览 */
ontology?: boolean;
}
export interface AskAnswer {
/** 识别到的意图,展示在卡头,用户能确认「它听懂了什么」 */
intent: string;
severity: AskTone;
conclusion: string;
metrics: AskMetric[];
table?: AskTable;
points: AskPoint[];
actions: AskAction[];
source: string;
steps: AskStep[];
}
export type IntentId = 'delay' | 'bottleneck' | 'po' | 'material' | 'gap' | 'ledger' | 'help';
/* ── 小工具:与 ontology 层同一套金额/日期口径 ─────────────────────────── */
const day = (s: string) => new Date(`${s}T00:00:00`).getTime();
const daysFrom = (a: string, b: string) => Math.round((day(a) - day(b)) / 86400000);
const md = (s: string) => s.slice(5); // 2026-10-28 → 10-28
const rule = (id: string) => rules.find(r => r.id === id)!;
const hit = (id: string) => rule(id).hits();
/* ── 单订单风险评分:口径全部写在 points 里,不做黑箱 ────────────────── */
export interface OrderRisk {
so: SalesOrder; path: PathRow; score: number; level: 'red' | 'yellow' | 'green'; fired: string[];
}
/**
* 风险分 = 关键路径冲突 40 + min(20, 延期天数)
* | 或(仅齐套延迟)min(25, 齐套延迟天数)
* + 有未审批采购行 15 + 缓冲<5 天且未完工 10 + 有已过预计到货日仍未收的采购行 10
* 等级:≥45 红(按现排程必延期)|≥20 黄(有延迟风险)|其余 绿。
*
* asOf 可切换:当期用业务快照日,历史回放月用该月月末,
* 「在途逾期」这条才有正确的时点含义。
*/
export function scoreRisk(path: PathRow, asOf: string = ONTOLOGY_AS_OF): OrderRisk {
const fired: string[] = [];
let score = 0;
if (path.critLag > 0) {
score += 40 + Math.min(20, path.critLag);
fired.push('关键路径冲突');
} else if (path.kitLag > 0) {
score += Math.min(25, path.kitLag);
fired.push('齐套延迟');
}
if (path.unapproved > 0) { score += 15; fired.push(`采购未审批 ${path.unapproved} 行`); }
if (path.unfinished && path.buffer < 5) { score += 10; fired.push(`交期缓冲仅 ${path.buffer} 天`); }
const overdue = path.lines.filter(p => day(p.预计到货日期) < day(asOf));
if (overdue.length) { score += 10; fired.push(`在途逾期 ${overdue.length} 行`); }
if (!path.wo.BOM版本 || path.wo.BOM版本 === '—') fired.push('工单无 BOM');
const level: OrderRisk['level'] = score >= 45 ? 'red' : score >= 20 ? 'yellow' : 'green';
return { so: path.so, path, score, level, fired };
}
/** 按风险分降序排(同分按含税金额),对话层与看板层共用 */
export function rankRisks(risks: OrderRisk[]): OrderRisk[] {
return risks.sort((a, b) => (b.score - a.score || b.so.含税金额 - a.so.含税金额));
}
export function orderRisks(): OrderRisk[] {
return rankRisks(PATH.map(path => scoreRisk(path)));
}
const levelTone: Record<OrderRisk['level'], AskTone> = { red: 'danger', yellow: 'warning', green: 'success' };
const levelText: Record<OrderRisk['level'], string> = { red: '红', yellow: '黄', green: '绿' };
/** 取数步骤要报真实条数,让用户看到「它确实读了这几张表」 */
function dataStep(): AskStep {
return {
act: '取数',
detail: `销售订单 ${salesOrders.length} · 生产工单 ${productionOrders.length} · 工单材料 ${workOrderMaterials.length} 行 · `
+ `采购订单 ${purchaseGroups().length} 张 / ${purchaseOrders.length} 行 · 客户 ${customers.length} · 供应商 ${suppliers.length} · 物料 ${items.length}`,
};
}
const STEP_PARSE = (intent: string): AskStep => ({
act: '解析问句', detail: `识别意图「${intent}」,锚定对象:销售订单(履约风险以订单为锚点)· 快照日 ${ONTOLOGY_AS_OF}`,
});
const STEP_LINK = (): AskStep => ({
act: '建链路',
detail: '销售订单 → 工单(工单号 = WO-销售订单号)→ 工单材料明细 → 采购订单(靠「来源销售订单号」回链);齐套日取组内最晚到货行',
});
const STEP_RULES = (ids: string[]): AskStep => ({
act: '跑本体规则',
detail: ids.map(id => `${rule(id).name} ${hit(id).n}`).join(' · ') || '无适用规则',
});
const STEP_RANK = (detail: string): AskStep => ({ act: '排序取要项', detail });
const STEP_DONE = (detail: string): AskStep => ({ act: '出结论', detail });
const SOURCE = `Excel「销售订单 / 生产工单 / 工单材料明细 / 材料采购订单 / 客户 / 供应商 / 物料」· 快照 ${ONTOLOGY_AS_OF} · `
+ `规则命中数与「业务本体总览」同源`;
/* ── 意图路由:关键词命中,问句与推荐问句共用同一函数 ────────────────── */
const KEYS: { id: IntentId; words: string[] }[] = [
{ id: 'ledger', words: ['台账', '清单', '全部订单', '每一单', '打分', '评分'] },
{ id: 'gap', words: ['数据够', '缺什么', '缺口', '字段', '能不能支撑', '够不够', '补数', '局限'] },
{ id: 'material', words: ['物料', '材料', '断供', '单源', '漏采', 'bom', '替代料', '齐套料'] },
{ id: 'po', words: ['采购', '到货', '在途', '逾期', '供应商交期', '催料', '审批', '未审'] },
{ id: 'bottleneck', words: ['卡点', '卡在哪', '最危险', '最紧急', '瓶颈', '为什么延期', '根因', '单订单'] },
{ id: 'delay', words: ['延期', '可能延', '交期风险', '哪些订单', '风险', '准时', '交付', '延误'] },
];
export function matchIntent(raw: string): IntentId {
const q = raw.trim().toLowerCase();
if (!q) return 'help';
/* 命中词数多的意图优先,避免「哪些订单可能延期」被泛词抢走 */
let best: { id: IntentId; n: number } = { id: 'help', n: 0 };
KEYS.forEach(k => {
const n = k.words.reduce((a, w) => (q.includes(w) ? a + 1 : a), 0);
if (n > best.n) best = { id: k.id, n };
});
return best.id;
}
/* ── 各意图的回答 ─────────────────────────────────────────────────────── */
function answerDelay(): AskAnswer {
const crit = hit('r-crit');
const kit = hit('r-kit');
const risks = orderRisks();
const red = risks.filter(r => r.level === 'red');
const yellow = risks.filter(r => r.level === 'yellow');
const exposure = red.reduce((a, r) => a + r.so.含税金额, 0);
const rows = risks.filter(r => r.path.critLag > 0 || r.path.kitLag > 0).slice(0, 6);
return {
intent: '订单延期风险',
severity: crit.n ? 'danger' : 'success',
conclusion: `${salesOrders.length} 张订单里 ${crit.n} 张按现排程必然延期(齐套日已晚于计划完工日),另有 ${kit.n - crit.n} 张开工时料未到齐但还能靠压缩生产周期救回;`
+ `红色订单含税金额合计 ${moneyW(exposure)},风险最高的是 ${red[0]?.so.销售订单号 ?? '—'}(${red[0]?.so.预计发货日期 ?? '—'} 发货,客户 ${red[0]?.so.客户简称 ?? '—'})。`,
metrics: [
{ label: '确定延期', value: `${crit.n} 张`, tone: 'danger' },
{ label: '齐套延迟', value: `${kit.n} 张`, tone: 'warning' },
{ label: '延迟 >7 天', value: `${PATH.filter(p => p.kitLag > 7).length} 张`, tone: 'warning' },
{ label: '红色敞口', value: money(exposure), tone: 'danger' },
],
table: {
cols: ['销售订单', '客户', '计划发货', '齐套日', '延期', '含税金额'],
rows: rows.map(r => ({
tone: levelTone[r.level],
cells: [
r.so.销售订单号, r.so.客户简称, md(r.so.预计发货日期), md(r.path.lastArrival),
r.path.critLag > 0 ? `晚完工 +${r.path.critLag} 天` : `晚开工 +${r.path.kitLag} 天`,
money(r.so.含税金额),
],
})),
},
points: [
{ label: '规则', text: `「${rule('r-crit').name}」${rule('r-crit').expr},命中 ${crit.n} 张订单:${crit.targets.join('、')}`, tone: 'danger' },
{ label: '规则', text: `「${rule('r-kit').name}」${rule('r-kit').expr},命中 ${kit.n} ${kit.unit}`, tone: 'warning' },
{ label: '齐套口径', text: '齐套日 = 该订单全部采购行的最晚预计到货日;取首行会低估最多 18 天,导致把「晚到」误读成「早到」' },
{ label: '置信度', text: `工单 ${hit('r-bom').n} ${hit('r-bom').unit} 没有 BOM,其材料需求由采购单反推,齐套日只覆盖「已下单的料」——真实缺料可能更多,本结论偏乐观`, tone: 'warning' },
{ label: '无区分度', text: `「${rule('r-buffer').name}」命中 ${hit('r-buffer').n} 张,但本批缓冲全为 2 天(模拟排程:完工=交期−2),接真实排程前这条不作为定级依据`, tone: 'info' },
],
actions: [
...(red[0] ? [{ label: `定位 ${red[0].so.销售订单号}`, locateSO: red[0].so.销售订单号 }] : []),
{ label: '采购到货明细', ask: '采购到货来得及吗' },
{ label: '看今日风险台账', ask: '生成今日风险台账' },
{ label: '打开业务本体总览', ontology: true },
],
source: SOURCE,
steps: [
STEP_PARSE('订单延期风险'), dataStep(), STEP_LINK(),
STEP_RULES(['r-crit', 'r-kit', 'r-buffer', 'r-approve', 'r-overdue']),
STEP_RANK('按延期天数降序,同分按含税金额;取前 6 张进明细表'),
STEP_DONE(`${crit.n} 张定红、${yellow.length} 张定黄,红色敞口 ${moneyW(exposure)}`),
],
};
}
function answerBottleneck(): AskAnswer {
const risks = orderRisks();
const top = risks[0];
const p = top.path;
const poLines = p.lines.slice().sort((a, b) => (a.预计到货日期 < b.预计到货日期 ? 1 : -1));
const blocker = poLines[0];
const mats = workOrderMaterials.filter(m => m.来源销售订单号 === p.so.销售订单号);
const unapproved = p.lines.filter(x => x.订单状态 !== '生效');
const overdue = p.lines.filter(x => day(x.预计到货日期) < day(ONTOLOGY_AS_OF));
return {
intent: '单订单卡点定位',
severity: levelTone[top.level],
conclusion: `最危险的是 ${p.so.销售订单号}(${p.so.客户简称} · ${money(p.so.含税金额)}),风险分 ${top.score}:`
+ `齐套日 ${p.lastArrival} 比计划完工 ${p.wo.预计完工日期} 晚 ${p.critLag} 天,卡点在 ${blocker?.采购订单号 ?? '—'} 的 ${blocker?.材料编码 ?? '—'}(${blocker?.供应商简称 ?? '—'},应到 ${blocker?.预计到货日期 ?? '—'})。`,
metrics: [
{ label: '风险分', value: String(top.score), tone: levelTone[top.level] },
{ label: '延期', value: p.critLag > 0 ? `晚完工 +${p.critLag} 天` : p.kitLag > 0 ? `晚开工 +${p.kitLag} 天` : '未到齐无延期', tone: p.critLag > 0 ? 'danger' : 'warning' },
{ label: '距发货', value: `${daysFrom(p.so.预计发货日期, ONTOLOGY_AS_OF)} 天`, tone: 'info' },
{ label: '采购行', value: `${p.lines.length} 行 / ${mats.length} 种料`, tone: 'info' },
],
table: {
cols: ['采购订单', '供应商', '材料', '应到', '状态', '金额'],
rows: poLines.map(x => ({
tone: (x.订单状态 !== '生效' ? 'danger' : day(x.预计到货日期) < day(ONTOLOGY_AS_OF) ? 'warning' : undefined) as AskTone | undefined,
cells: [x.采购订单号, x.供应商简称, x.材料编码, md(x.预计到货日期), x.订单状态, money(x.含税金额)],
})),
},
points: [
{ label: '链路', text: `${p.so.销售订单号} → 工单 ${p.wo.工单号}(${p.wo.生产车间},${p.wo.预计开工日期} 开工 / ${p.wo.预计完工日期} 完工,周期 ${p.wo['生产周期(天)']} 天)→ 材料 ${mats.length} 种 → 采购 ${p.lines.length} 行` },
{ label: '触发规则', text: top.fired.join(' · ') || '无', tone: levelTone[top.level] },
{ label: '审批', text: unapproved.length ? `未审批 ${unapproved.length} 行(${unapproved.map(x => x.采购订单号).join('、')}),这些行不构成到料承诺` : '该单采购行全部已审批生效', tone: unapproved.length ? 'danger' : 'success' },
{ label: '在途', text: overdue.length ? `${overdue.length} 行已过预计到货日(${overdue.map(x => `${x.采购订单号} ${md(x.预计到货日期)}`).join('、')}),源表无收货字段,只能提疑` : '无已过预计到货日的采购行', tone: overdue.length ? 'warning' : 'success' },
{ label: 'BOM', text: p.wo.BOM版本 && p.wo.BOM版本 !== '—' ? `工单 BOM 版本 ${p.wo.BOM版本},材料需求可信` : '工单无 BOM,材料清单由采购单反推,卡点判断的置信度要降一档', tone: p.wo.BOM版本 && p.wo.BOM版本 !== '—' ? 'success' : 'warning' },
],
actions: [
{ label: `定位 ${p.so.销售订单号}`, locateSO: p.so.销售订单号 },
{ label: '哪些订单可能延期', ask: '哪些订单可能延期' },
{ label: '打开业务本体总览', ontology: true },
],
source: SOURCE,
steps: [
STEP_PARSE('单订单卡点定位'), dataStep(),
{ act: '评分选单', detail: `对 ${risks.length} 张订单按风险分排序,最高 ${top.score} 分(${p.so.销售订单号})` },
STEP_LINK(),
{ act: '逐行核对', detail: `该单 ${p.lines.length} 行采购:未审批 ${unapproved.length} 行、已过应到日 ${overdue.length} 行、最晚到货 ${p.lastArrival}` },
STEP_DONE(`卡点落在 ${blocker?.采购订单号 ?? '—'} / ${blocker?.材料编码 ?? '—'},延 ${p.critLag} 天`),
],
};
}
function answerPO(): AskAnswer {
const ovd = purchaseOrders.filter(p => day(p.预计到货日期) < day(ONTOLOGY_AS_OF));
const unapp = purchaseOrders.filter(p => p.订单状态 !== '生效');
const groups = purchaseGroups();
const kit = hit('r-kit');
const lateSuppliers = new Map<string, { n: number; max: string; amount: number }>();
ovd.concat(unapp).forEach(p => {
const cur = lateSuppliers.get(p.供应商编码) ?? { n: 0, max: '', amount: 0 };
cur.n += 1; cur.amount += p.含税金额;
if (p.预计到货日期 > cur.max) cur.max = p.预计到货日期;
lateSuppliers.set(p.供应商编码, cur);
});
const supRows = [...lateSuppliers.entries()].map(([code, v]) => ({
name: suppliers.find(s => s.供应商编码 === code)?.供应商简称 ?? code, code, ...v,
})).sort((a, b) => b.amount - a.amount);
const ovdAmount = ovd.reduce((a, p) => a + p.含税金额, 0);
return {
intent: '采购到货承诺',
severity: ovd.length || unapp.length ? 'warning' : 'success',
conclusion: `${groups.length} 张采购单 / ${purchaseOrders.length} 行里,${ovd.length} 行已过预计到货日仍未收货(${money(ovdAmount)},需向供应商提疑),`
+ `${unapp.length} 行未审批、不构成到料承诺;${kit.n} ${kit.unit}的齐套日晚于计划开工,供应侧是当前主要瓶颈。`,
metrics: [
{ label: '在途逾期', value: `${ovd.length} 行`, tone: ovd.length ? 'warning' : 'success' },
{ label: '逾期金额', value: money(ovdAmount), tone: ovd.length ? 'warning' : 'success' },
{ label: '未审批', value: `${hit('r-approve').n} ${hit('r-approve').unit}`, tone: 'danger' },
{ label: '齐套延迟', value: `${kit.n} 张`, tone: 'warning' },
],
table: {
cols: ['采购订单', '供应商', '材料', '应到', '状态', '金额'],
rows: [...ovd, ...unapp].slice(0, 8).map(p => ({
tone: (p.订单状态 !== '生效' ? 'danger' : 'warning') as AskTone,
cells: [p.采购订单号, p.供应商简称, p.材料编码, md(p.预计到货日期), p.订单状态, money(p.含税金额)],
})),
},
points: [
{ label: '规则', text: `「${rule('r-overdue').name}」${rule('r-overdue').expr},命中 ${ovd.length} ${hit('r-overdue').unit}`, tone: 'warning' },
{ label: '规则', text: `「${rule('r-approve').name}」${rule('r-approve').expr},命中 ${hit('r-approve').n} ${hit('r-approve').unit}`, tone: 'danger' },
{ label: '局限', text: '源表只有 生效/未审 两种状态、没有收货与实际到货日期,因此逾期只能提出疑点、不能定案为延迟', tone: 'info' },
{ label: '催料顺序', text: supRows.length ? `按金额优先确认:${supRows.slice(0, 3).map(s => `${s.name}(${s.n} 行 ${money(s.amount)})`).join('、')}` : '本批无逾期与未审批行', tone: 'info' },
],
actions: [
...(ovd[0] ? [{ label: `定位 ${ovd[0].来源销售订单号}`, locateSO: ovd[0].来源销售订单号 }] : []),
{ label: '哪些订单可能延期', ask: '哪些订单可能延期' },
{ label: '物料断供风险', ask: '哪些物料有断供风险' },
],
source: SOURCE,
steps: [
STEP_PARSE('采购到货承诺'), dataStep(),
{ act: '筛采购行', detail: `在途逾期(应到 < ${ONTOLOGY_AS_OF})${ovd.length} 行 · 未审批 ${unapp.length} 行 · 其余 ${purchaseOrders.length - ovd.length - unapp.length} 行状态正常` },
STEP_RULES(['r-overdue', 'r-approve', 'r-kit']),
{ act: '按供应商汇总', detail: supRows.length ? `涉及 ${supRows.length} 家供应商,金额最高 ${supRows[0].name}` : '无需催料' },
STEP_DONE(`供应侧风险:${ovd.length + unapp.length} 行需要人工确认`),
],
};
}
function answerMaterial(): AskAnswer {
const single = hit('r-single');
const miss = hit('r-missing-po');
const bom = hit('r-bom');
const mats = new Map<string, { sup: Set<string>; lines: number; amount: number }>();
purchaseOrders.forEach(p => {
const cur = mats.get(p.材料编码) ?? { sup: new Set<string>(), lines: 0, amount: 0 };
cur.sup.add(p.供应商编码); cur.lines += 1; cur.amount += p.含税金额;
mats.set(p.材料编码, cur);
});
/* 漏采 = BOM 展开出来的材料在采购行里找不到(与规则 r-missing-po 同一判据,这里要的是材料明细) */
const poMats = new Set(purchaseOrders.map(p => p.材料编码));
const missingRows = workOrderMaterials.filter(m => !poMats.has(m.材料编码));
const missingMats = [...new Set(missingRows.map(m => m.材料编码))];
return {
intent: '物料断供风险',
severity: 'warning',
conclusion: `本批 ${mats.size} 种在采材料全部只有一家供应商(${single.n} 单源),没有第二货源可切;`
+ `更实质的问题是 ${missingMats.length} ${miss.unit}——BOM 展开出来的材料在采购单里找不到(${missingMats.join('、')}),`
+ `${miss.targets.join('、')} 需先确认是走库存领料还是确实漏下单。`,
metrics: [
{ label: '单源材料', value: `${single.n} 种`, tone: 'warning' },
{ label: '漏采疑点', value: `${missingMats.length} 种`, tone: 'danger' },
{ label: '无 BOM 工单', value: `${bom.n} ${bom.unit}`, tone: 'warning' },
{ label: '物料主数据', value: `${items.length} 条`, tone: 'info' },
],
table: {
cols: ['材料编码', '涉及订单', '工单号', '应领数量', '单位用量', '采购单里'],
rows: missingRows.slice(0, 8).map(m => ({
tone: 'danger' as AskTone,
cells: [m.材料编码, m.来源销售订单号, m.工单号, String(m.应领数量), String(m.单位用量), '无记录'],
})),
},
points: [
{ label: '规则', text: `「${rule('r-missing-po').name}」${rule('r-missing-po').expr},命中 ${miss.n} ${miss.unit}`, tone: 'danger' },
{ label: '规则', text: `「${rule('r-single').name}」${rule('r-single').expr},命中 ${single.n} 种材料单源`, tone: 'warning' },
{ label: '无区分度', text: '本批 54 种材料供应商数都等于 1,「单源」指标等于全员告警;需接物料主数据的多源配额才能筛出真正的例外', tone: 'info' },
{ label: '循环论证', text: `只有 2 张单有真 BOM 可做这项检验,其余 ${bom.n} 张工单的材料需求本身由采购单反推,反推出来的「漏采」不成立,因此不计入`, tone: 'info' },
{ label: '数据缺口', text: '物料主数据只有编码/类型/规格/单位/BOM 版本五列,没有现存量、安全库存、替代料清单,断供时给不出替代方案', tone: 'warning' },
],
actions: [
...(miss.targets[0] ? [{ label: `定位 ${miss.targets[0]}`, locateSO: miss.targets[0] }] : []),
{ label: '缺哪些数据', ask: '数据够做风险识别吗' },
{ label: '打开业务本体总览', ontology: true },
],
source: SOURCE,
steps: [
STEP_PARSE('物料断供风险'), dataStep(),
{ act: '材料维度聚合', detail: `按材料编码归并 ${purchaseOrders.length} 行采购 → ${mats.size} 种材料,统计每种的去重供应商数` },
STEP_RULES(['r-missing-po', 'r-single', 'r-bom']),
{ act: '交叉核对', detail: `BOM 展开材料集合 ${new Set(workOrderMaterials.map(m => m.材料编码)).size} 种 ∩ 采购材料集合 ${mats.size} 种 → 差集 ${missingMats.length} 种(${missingMats.join('、')})` },
STEP_DONE(`单源无区分度,真正可行动的是 ${missingMats.length} 种漏采疑点`),
],
};
}
/** 数据缺口清单:缺哪个字段 → 卡住哪条判断 → 该找谁补 */
const GAPS: { miss: string; block: string; from: string }[] = [
{ miss: '现存量 / 已分配 / 安全库存 / 在途入库', block: '「库存可用量校验」无法执行:判断不了料够不够,只能判断已下单的料何时到', from: 'ERP 即时库存快照,日刷' },
{ miss: '实际到货日期 / 收货状态', block: '「采购在途逾期」只能提疑不能定案,逾期天数算不准', from: '采购收货单 / 入库单' },
{ miss: '工单报工与实际开工完工', block: '排程冲突只能按计划日期算,无法识别「已经晚了但状态还没改」', from: '车间报工(MES)' },
{ miss: 'BOM 结构(15/17 工单缺)', block: '材料需求由采购单反推,漏采核查对这批单不成立(循环论证)', from: '工程 BOM 主数据' },
{ miss: '替代料清单 / 多源配额', block: '断供时给不出替代方案,单源指标全员告警无区分度', from: '物料主数据 + 采购目录' },
{ miss: '供应商产能与物流在途', block: '到货承诺只有 Excel 里一个日期,无法验证是否已发货', from: 'SRM / 物流跟踪接口' },
{ miss: '客户侧允收与分批交付约定', block: '拆单先发这类处置动作无法自动判断是否可行', from: '合同 / 客户主数据备注' },
];
function answerGap(): AskAnswer {
const runnable = rules.filter(r => !r.blocked);
const blocked = rules.filter(r => r.blocked);
return {
intent: '数据充分性评估',
severity: 'warning',
conclusion: `够做「已下单的料是否按时到」这一层,做不了「料够不够」那一层:${rules.length} 条本体规则里 ${runnable.length} 条可执行、${blocked.length} 条因缺字段被阻塞;`
+ `链路覆盖 ${PATH.filter(p => p.lines.length > 0).length}/${salesOrders.length} 张订单可完整回溯到采购行,风险识别的地基是够的。`,
metrics: [
{ label: '可执行规则', value: `${runnable.length}/${rules.length}`, tone: 'success' },
{ label: '被阻塞规则', value: `${blocked.length} 条`, tone: 'danger' },
{ label: '链路完整', value: `${PATH.filter(p => p.lines.length > 0).length}/${salesOrders.length} 单`, tone: 'info' },
{ label: '断链采购行', value: `${hit('r-trace').n} ${hit('r-trace').unit}`, tone: hit('r-trace').n ? 'danger' : 'success' },
],
table: {
cols: ['缺失字段', '卡住的判断', '补数来源'],
rows: GAPS.map(g => ({ tone: 'warning' as AskTone, cells: [g.miss, g.block, g.from] })),
},
points: [
{ label: '已具备', text: `订单交期与金额(${salesOrders.length} 单)、工单开完工与周期(${productionOrders.length} 张)、材料需求(${workOrderMaterials.length} 行)、采购承诺(${purchaseOrders.length} 行)、客户/供应商归属(${customers.length}/${suppliers.length})` },
{ label: '被阻塞', text: `${blocked.map(r => `「${r.name}」${r.desc}`).join(';')}`, tone: 'danger' },
{ label: '结论边界', text: '当前风险结论=「按已下单的到货承诺,哪些订单会延期」;不是「缺哪些料」。对外沟通要用前者措辞,后者需补库存数据', tone: 'info' },
{ label: '补数优先级', text: '先补库存四列(解锁齐套与缺口判断)→ 再补收货状态(把在途疑点变成定案)→ 再补 BOM(让漏采核查覆盖全部工单)', tone: 'info' },
],
actions: [
{ label: '哪些订单可能延期', ask: '哪些订单可能延期' },
{ label: '物料断供风险', ask: '哪些物料有断供风险' },
{ label: '打开业务本体总览', ontology: true },
],
source: `本体规则层 ${rules.length} 条 · 动作 ${actions.length} 项 · 对象 ${objects.length} 类 · 快照 ${ONTOLOGY_AS_OF}`,
steps: [
STEP_PARSE('数据充分性评估'), dataStep(),
{ act: '逐条体检规则', detail: `${runnable.length} 条可执行:${runnable.map(r => r.name).join('、')}` },
{ act: '标记阻塞项', detail: blocked.length ? `${blocked.map(r => `「${r.name}」${r.hits().unit}`).join('、')}` : '无' },
{ act: '核对链路覆盖', detail: `采购行回链销售订单 ${purchaseOrders.filter(p => p.来源销售订单号).length}/${purchaseOrders.length} 行,断链 ${hit('r-trace').n} ${hit('r-trace').unit}` },
STEP_DONE(`给出 ${GAPS.length} 项补数清单并按解锁收益排序`),
],
};
}
function answerLedger(): AskAnswer {
const risks = orderRisks();
const red = risks.filter(r => r.level === 'red');
const yellow = risks.filter(r => r.level === 'yellow');
const green = risks.filter(r => r.level === 'green');
const total = risks.reduce((a, r) => a + r.so.含税金额, 0);
return {
intent: '今日风险台账',
severity: red.length ? 'danger' : yellow.length ? 'warning' : 'success',
conclusion: `${ONTOLOGY_AS_OF} 快照:${risks.length} 张订单 红 ${red.length} / 黄 ${yellow.length} / 绿 ${green.length},`
+ `红色订单金额 ${money(red.reduce((a, r) => a + r.so.含税金额, 0))} 占总盘 ${((red.reduce((a, r) => a + r.so.含税金额, 0) / total) * 100).toFixed(1)}%;`
+ `最高分 ${risks[0].score}(${risks[0].so.销售订单号}),最低 ${risks[risks.length - 1].score}。`,
metrics: [
{ label: '红', value: `${red.length} 单`, tone: 'danger' },
{ label: '黄', value: `${yellow.length} 单`, tone: 'warning' },
{ label: '绿', value: `${green.length} 单`, tone: 'success' },
{ label: '总盘', value: moneyW(total), tone: 'info' },
],
table: {
cols: ['销售订单', '客户', '等级', '分', '延期', '触发规则'],
rows: risks.slice(0, 10).map(r => ({
tone: levelTone[r.level],
cells: [
r.so.销售订单号, r.so.客户简称, levelText[r.level], String(r.score),
r.path.critLag > 0 ? `晚完工 +${r.path.critLag} 天` : r.path.kitLag > 0 ? `晚开工 +${r.path.kitLag} 天` : '—',
r.fired.slice(0, 2).join(' · ') || '无',
],
})),
},
points: [
{ label: '评分口径', text: '关键路径冲突 40 + min(20, 延期天数);仅齐套延迟 min(25, 延迟天数);未审批采购行 +15;缓冲<5 天且未完工 +10;有已过应到日的采购行 +10', tone: 'info' },
{ label: '定级', text: `≥45 红(${red.length})· ≥20 黄(${yellow.length})· 其余绿(${green.length});红=按现排程必延期,黄=有延迟风险但可救,绿里仍有齐套延迟≤7 天的单,只是当前排程还兜得住`, tone: 'info' },
{ label: '权重说明', text: '权重是演示口径(延期最重、审批与在途次之),不是公司制度;接真实排程与库存后要重新标定', tone: 'warning' },
{ label: '台账范围', text: `明细表按风险分降序取前 10,共 ${risks.length} 单;当前为前端演示,未接导出与推送`, tone: 'info' },
],
actions: [
{ label: `定位 ${risks[0].so.销售订单号}`, locateSO: risks[0].so.销售订单号 },
{ label: '最危险的单卡在哪', ask: '最危险的单卡在哪' },
{ label: '打开业务本体总览', ontology: true },
],
source: SOURCE,
steps: [
STEP_PARSE('今日风险台账'), dataStep(), STEP_LINK(),
STEP_RANK(`${risks.length} 单逐单评分 → 红 ${red.length} / 黄 ${yellow.length} / 绿 ${green.length}`),
{ act: '汇总敞口', detail: `红色订单金额 ${money(red.reduce((a, r) => a + r.so.含税金额, 0))} / 总盘 ${money(total)}` },
STEP_DONE('输出台账前 10 行,附评分口径供晨会核对'),
],
};
}
function answerHelp(): AskAnswer {
return {
intent: '能力说明',
severity: 'info',
conclusion: '我按「销售订单 → 工单 → 材料 → 采购」这条链路做履约风险识别,回答里的每个数字都来自本体规则实时计算,与「业务本体总览」页同一口径。',
metrics: [
{ label: '覆盖订单', value: `${salesOrders.length} 张`, tone: 'info' },
{ label: '本体规则', value: `${rules.length} 条`, tone: 'info' },
{ label: '可执行动作', value: `${actions.length} 项`, tone: 'info' },
{ label: '快照日', value: ONTOLOGY_AS_OF, tone: 'info' },
],
points: [
{ label: '订单延期', text: '哪些订单可能延期 · 生成今日风险台账' },
{ label: '单点根因', text: '最危险的单卡在哪(逐行核对采购承诺)' },
{ label: '供应侧', text: '采购到货来得及吗 · 哪些物料有断供风险' },
{ label: '数据边界', text: '数据够做风险识别吗(缺哪些字段、卡住哪条判断)' },
{ label: '不做', text: '不预测销量、不算毛利、不改数据——本应用数据只读自 Excel,不落库', tone: 'info' },
],
actions: [
{ label: '哪些订单可能延期', ask: '哪些订单可能延期' },
{ label: '数据够做风险识别吗', ask: '数据够做风险识别吗' },
{ label: '打开业务本体总览', ontology: true },
],
source: SOURCE,
steps: [
STEP_PARSE('能力说明(未命中具体风险问句)'),
dataStep(),
{ act: '读本体', detail: `对象 ${objects.length} · 关系 ${relations.length} · 规则 ${rules.length} · 动作 ${actions.length}(与「业务本体总览」同一份定义)` },
{ act: '列出可用意图', detail: '订单延期 / 单订单卡点 / 采购到货 / 物料断供 / 数据缺口 / 风险台账' },
STEP_DONE('返回能力清单,等用户选定问题'),
],
};
}
const BUILDERS: Record<IntentId, () => AskAnswer> = {
delay: answerDelay, bottleneck: answerBottleneck, po: answerPO,
material: answerMaterial, gap: answerGap, ledger: answerLedger, help: answerHelp,
};
/** 推荐问句:与 matchIntent 的路由词同源,避免文案改了却问不出答案 */
export const SUGGESTED: string[] = [
'哪些订单可能延期', '最危险的单卡在哪', '采购到货来得及吗', '哪些物料有断供风险', '数据够做风险识别吗',
];
export function buildAskAnswer(raw: string): { intent: IntentId; answer: AskAnswer } {
const intent = matchIntent(raw);
return { intent, answer: BUILDERS[intent]() };
}
/** 单条采购行的到货承诺(回答卡里给「已下单未到货」明细时用) */
export const pendingLines = (): PurchaseOrder[] =>
purchaseOrders.filter(p => day(p.预计到货日期) >= day(ONTOLOGY_AS_OF));
+186
View File
@@ -0,0 +1,186 @@
import type { MetricNode } from '../data/sqlite';
/**
* 离线意图理解:把用户的一句话拆成「意图 + 指标实体 + 假设参数」。
* 纯关键词规则(仅中文),无网络依赖,与 answers.ts 组成单轮问答的本地智能引擎。
*/
export type Intent =
| 'overview' // 经营概况
| 'query' // 指标查询
| 'compare' // 对比分析(产品线 / 区域)
| 'attribute' // 归因分析
| 'forecast' // 趋势预测
| 'whatif' // 假设模拟
| 'anomaly' // 异常检测
| 'escalate' // 升级处置
| 'advice' // 行动建议
| 'risk' // 风险矩阵
| 'fallback'; // 兜底引导
export interface ParsedAsk {
intent: Intent;
/** 抽取到的指标 code(查询/归因/预测/模拟的对象) */
metricCode?: string;
/** 假设模拟:目标值(绝对值)与增量(相对当期)二选一 */
absValue?: number;
deltaValue?: number;
/** 对比分析的范围 */
compareScope?: 'product' | 'region';
/** 原始问句(保留大小写用于展示) */
raw: string;
}
/* ── 意图关键词:命中优先级即数组顺序 ─────────────────────────────────── */
const INTENT_KEYS: [Intent, string[]][] = [
['whatif', ['如果', '假如', '假设', '要是', '提升到', '提高到', '降到', '变成', '变为',
'what if', 'whatif', 'simulate']],
['forecast', ['预测', '预计', '下月', '下个月', '下季度', '未来', '走势会', '会怎样', '会达到', '能支撑', '支撑', '能跑多远', '够不够',
'forecast']],
['escalate', ['升级', 'escalat', '上报']],
['anomaly', ['红色', '告警', '预警', '异常', '超标', '不达标', '哪些指标', '偏离']],
['attribute', ['为什么', '为何', '原因', '主因', '归因', '怎么回事', 'why']],
['advice', ['怎么处理', '怎么办', '建议', '措施', '方案', '对策', '怎么改', '怎么提升', '怎么压降',
'suggest', 'advice']],
['compare', ['对比', '比较', '哪个更', '哪个最', '排名', '产品线', '区域', '地域', '各家', '排行']],
['risk', ['风险', 'risk']],
['overview', ['概况', '总览', '整体', '大盘', '全局', '经营状况', '经营情况', '健康度',
'overview', 'summary']],
];
/* ── 指标别名:口语 / 简称 → code(与节点中文名互补,最长优先) ── */
const ALIASES: Record<string, string> = {
// 经营结果
'营收': 'R01', '收入': 'R01', '营业额': 'R01',
'增长': 'R02', '增速': 'R02', '同比': 'R02',
'净利润': 'R03', '利润': 'R03',
'现金流': 'R13', 'cf': 'R13',
'在手订单': 'R10', 'backlog': 'R10', '在手': 'R10',
'新增订单': 'R08', '新订单': 'R08', '订单': 'R08',
// 盈利质量
'毛利率': 'R04', '毛利': 'R04',
'净利率': 'R05', 'ebitda': 'R06', 'roe': 'Q01',
'负债率': 'Q03', '资产负债率': 'Q03',
'ccc': 'Q08', '现金转换': 'Q08', '现金周期': 'Q08',
// 运营效率
'存货': 'E01', '库存': 'E01', '库存周转': 'E01', '呆滞': 'E01',
'应收': 'E03', '账期': 'E03',
'人均': 'E05', '人效': 'E05',
'计划准确': 'DR-14', '安全库存': 'DR-15',
// 研发动能
'研发费用': 'G01', '研发投入': 'G01', '研发费率': 'G01',
'里程碑': 'G02', '按期率': 'G02',
'新品贡献': 'G03',
'上市周期': 'G04', '新品周期': 'G04',
'设计变更': 'G06', '变更件数': 'G06',
'复用率': 'G07', '通用件': 'G07',
'在研': 'G08', '专利': 'G05',
// 市场客户
'漏斗': 'M01', '转化率': 'M01',
'ltv': 'M02', 'cac': 'M02',
'留存': 'M04', '大客户留存': 'M04',
'线索': 'DR-12',
'响应时效': 'DR-13', '响应速度': 'DR-13',
// 生产供应
'oee': 'P01', '平衡率': 'P02',
'交付': 'R12', '交期': 'R12', '及时率': 'R12',
'双源': 'K01',
'可用率': 'DR-07',
'性能稼动': 'DR-08',
'良品率': 'DR-09', '品质': 'DR-09',
// 数智化
'渗透': 'D01', 'ai渗透': 'D01',
'成熟度': 'D02', 'ai成熟': 'D02',
'数据资产': 'D05', '在线率': 'D05',
'治理': 'DR-10', '主数据': 'DR-10',
'模型上线': 'DR-11',
// 风险
'敞口': 'RK01', '风险指数': 'RK01',
'合规事件': 'RK02',
// 驱动因子(归因高频对象)
'大客户订单': 'DR-01',
'渠道': 'DR-02', '覆盖': 'DR-02',
'单价': 'DR-03',
'高毛利占比': 'DR-04', '高毛利产品': 'DR-04',
'物料成本': 'DR-05', '关键物料': 'DR-05',
'汇率': 'DR-06',
// 八大维度
'财务': 'D-R',
'盈利质量': 'D-Q', '质量': 'D-Q',
'效率': 'D-E',
'研发': 'D-G', '动能': 'D-G',
'市场': 'D-M', '客户': 'D-M',
'生产': 'D-P', '供应': 'D-P',
'ai': 'D-D', '数字化': 'D-D', '数智': 'D-D', 'dx': 'D-D',
'风险韧性': 'D-K',
'总览': 'OV', '健康度': 'OV', '经营': 'OV',
};
/** 指标实体抽取:别名 + 节点中文名 + code 全匹配,最长别名优先(在手订单 > 订单) */
export function extractMetricCode(text: string, flat: MetricNode[]): string | undefined {
const entries: [string, string][] = [];
flat.forEach(n => {
entries.push([n.name_zh, n.code], [n.code.toLowerCase(), n.code]);
});
Object.entries(ALIASES).forEach(([alias, code]) => entries.push([alias, code]));
entries.sort((a, b) => b[0].length - a[0].length);
for (const [alias, code] of entries) {
if (alias.length >= 2 && text.includes(alias)) return code;
}
return undefined;
}
/** 假设模拟的数值解析:绝对值(提升到 40)与增量(提升 2pt / +2) */
function extractHypothesis(text: string): { absValue?: number; deltaValue?: number } {
const m = text.match(/([-+]?\d+(?:\.\d+)?)/);
if (!m) return {};
const num = parseFloat(m[1]);
if (Number.isNaN(num)) return {};
// 「提升到 / 降到 / 达到」→ 绝对值;「提升 2pt / 下降 2 / +2」→ 增量
const before = text.slice(0, m.index ?? 0);
const isAbs = /到|至|达到|为|变成/.test(before) && !/[-+]/.test(m[1]);
const isPt = /pt|点/i.test(text.slice(m.index ?? 0));
if (isAbs) return { absValue: num };
if (m[1].startsWith('-') || m[1].startsWith('+')) return { deltaValue: num };
if (isPt) return { deltaValue: num };
return { absValue: num };
}
/**
* 意图解析主入口。
* @param raw 用户原话
* @param ctx flat=全量节点;selectedCode=当前选中指标(实体缺失时的上下文兜底)
*/
export function parseIntent(
raw: string,
ctx: { flat: MetricNode[]; selectedCode?: string; },
): ParsedAsk {
const text = raw.toLowerCase();
// 意图:按优先级找第一个命中的关键词组
let intent: Intent = 'fallback';
for (const [it, keys] of INTENT_KEYS) {
if (keys.some(k => text.includes(k))) { intent = it; break; }
}
// 实体:抽取到的优先,其次沿用当前选中节点(上下文兜底)
const extracted = extractMetricCode(text, ctx.flat);
const metricCode = extracted ?? ctx.selectedCode;
// 问句里确实点到了指标但没命中任何意图词 → 视为查询;
// 纯闲聊(无抽取实体)保持 fallback,不因选中节点而误判
if (intent === 'fallback' && extracted) intent = 'query';
// 问“怎么样/多少”却没说对象 → 给经营概览;归因/预测无对象时由 answers 用默认指标
if (intent === 'query' && !metricCode) intent = 'overview';
const out: ParsedAsk = { intent, metricCode, raw };
if (intent === 'whatif') {
Object.assign(out, extractHypothesis(text));
}
if (intent === 'compare') {
out.compareScope = /区域|地域|大区|地区/.test(text) ? 'region' : 'product';
}
return out;
}
+77
View File
@@ -0,0 +1,77 @@
import type { ThemeTokens } from '../context/ThemeContext';
import type { MetricNode } from '../data/sqlite';
export function alertColor(alert: string, tokens: ThemeTokens): string {
if (alert === 'red') return tokens.danger;
if (alert === 'yellow') return tokens.warning;
return tokens.success;
}
/** 偏差:正数代表优于目标(已按 polarity 归一方向) */
export function gapOf(node: { value: number; target: number; polarity: string }): number {
const raw = node.value - node.target;
return +(node.polarity === 'down' ? -raw : raw).toFixed(2);
}
/** 达成度(%),越低越好类指标取倒数口径 */
export function achieveRate(node: { value: number; target: number; polarity: string }): number {
if (!node.target) return 100;
const r = node.polarity === 'down'
? (node.target / (node.value || 1)) * 100
: (node.value / node.target) * 100;
return +Math.min(r, 999).toFixed(1);
}
/** 预算执行临界值(%):达成率跌破此线即进入红色档 */
export const EXEC_RED_LINE = 90;
/** 预算执行分档配色:达标绿 → 未达标黄 → 跌破临界值红。各面板统一走这里,避免阈值各说各话 */
export function execColor(rate: number, tokens: ThemeTokens): string {
if (rate >= 100) return tokens.success;
if (rate >= EXEC_RED_LINE) return tokens.warning;
return tokens.danger;
}
export function fmt(n: number | null | undefined, digits = 1): string {
if (n === null || n === undefined || Number.isNaN(n)) return '-';
return Math.abs(n) >= 1000
? n.toLocaleString('en-US', { maximumFractionDigits: 0 })
: n.toFixed(digits).replace(/\.0$/, '');
}
/** 带符号显示,用于偏差列 */
export function fmtSigned(n: number, digits = 1): string {
return `${n > 0 ? '+' : ''}${fmt(n, digits)}`;
}
/** 归属链路 codes:['OV','D-Q','R04'] */
export function chainOf(code: string, byCode: Map<string, MetricNode>): string[] {
const out: string[] = [];
let cur = byCode.get(code);
let guard = 0;
while (cur && guard++ < 10) {
out.unshift(cur.code);
cur = cur.parent_code ? byCode.get(cur.parent_code) : undefined;
}
return out;
}
/** 子孙节点(含自身下层全部层级) */
export function descendantsOf(code: string, flat: MetricNode[]): MetricNode[] {
const childrenOf = new Map<string, MetricNode[]>();
flat.forEach(n => {
if (!n.parent_code) return;
const arr = childrenOf.get(n.parent_code) ?? [];
arr.push(n);
childrenOf.set(n.parent_code, arr);
});
const out: MetricNode[] = [];
const stack = [...(childrenOf.get(code) ?? [])];
while (stack.length) {
const n = stack.pop()!;
out.push(n);
(childrenOf.get(n.code) ?? []).forEach(c => stack.push(c));
}
return out;
}
+24
View File
@@ -0,0 +1,24 @@
/**
* 全站金额展示口径的唯一来源:人民币元、1 位小数。
*
* 源 Excel 的金额是 2 位小数(如 ¥10,836.62),按用户 2026-10-17 的决定统一显示 1 位,
* 所以单个金额会有 ≤0.05 元的四舍五入尾差——这是口径选择的结果,不是取数错误。
* 任何页签卡片、本体页、对话回答卡都从这里取格式化函数,不得再自己写死小数位,
* 否则同一栏里又会出现「一位与两位并存」的老问题。
*/
/** 全站小数位:改口径只改这一处 */
export const MONEY_DP = 1;
/** 纯数字(千分位 + 1 位小数),调用方自己决定要不要加 ¥ 时使用 */
export const moneyNum = (n: number) =>
n.toLocaleString('zh-CN', { minimumFractionDigits: MONEY_DP, maximumFractionDigits: MONEY_DP });
/** ¥1,234.6 —— 金额读数的标准写法 */
export const money = (n: number) => `¥${moneyNum(n)}`;
/** 万元纯数字(1 位小数),顶栏 KPI 那种「数值 + 单位分开排」的用这个 */
export const wan = (n: number) => (n / 10000).toFixed(1);
/** 万元口径:满 1 万换算成「x.x 万元」,小额退回元口径,避免「0.0 万元」这种读不出数的写法 */
export const moneyW = (n: number) => (n >= 10000 ? `${wan(n)} 万元` : money(n));
+195
View File
@@ -0,0 +1,195 @@
/**
* 研产供销端到端流程模型(过程指标层)。
*
* 与指标树的分工:指标树看的是**结果指标**(收入、毛利率、OEE…),
* 这里看的是**过程指标**——一批订单/项目在每一段价值链上停留多久、流过多少、
* 一次通过多少、返工多少。两者共用同一批 metric_node 作为"关联指标",
* 所以点击流程卡上的指标片仍然能联动中央看板。
*
* 过程量是确定性模拟:同一 (stage, period) 永远得到同一读数,
* 拖动底部时间轴会沿 12 期平滑演变(改善/恶化趋势由各段 improve 决定),
* 不会像 Math.random() 那样每次刷新都变,演示与复盘都可复现。
*/
export type FlowIcon = 'target' | 'flask' | 'cart' | 'factory' | 'truck' | 'cash';
export interface FlowStage {
key: string;
zh: string;
/** 责任口 · 这一段把什么变成什么 */
roleZh: string;
icon: FlowIcon;
/** 关联的结果/过程指标(metric_node.code),点击联动中央看板 */
codes: string[];
/** 停留天数基线 / 目标(越短越好) */
dwell: number;
dwellTarget: number;
/** 月流转量基线(批次口径) */
flow: number;
flowUnitZh: string;
/** 一次通过率 % 基线 / 目标(越高越好) */
fpqc: number;
fpqcTarget: number;
/** 月返工/退回件数基线 / 目标(越少越好) */
rework: number;
reworkTarget: number;
/** 12 期改善强度:+1 = 全期持续变好,-1 = 持续变差 */
improve: number;
}
/** 研 → 产 → 供 → 销 的完整链路,六段 */
export const STAGES: FlowStage[] = [
{
key: 'demand', zh: '需求与方案',
roleZh: '市场部 · 商机到方案',
icon: 'target', codes: ['M01', 'DR-12', 'DR-13'],
dwell: 12.4, dwellTarget: 9.0, flow: 620, flowUnitZh: '条商机',
fpqc: 72.5, fpqcTarget: 80, rework: 88, reworkTarget: 60,
improve: -0.6,
},
{
key: 'rd', zh: '研发设计',
roleZh: '研究院 · 方案到样机',
icon: 'flask', codes: ['G02', 'G04', 'G06', 'G07'],
dwell: 42.0, dwellTarget: 36.0, flow: 42, flowUnitZh: '个项目',
fpqc: 84.0, fpqcTarget: 90, rework: 46, reworkTarget: 38,
improve: 0.45,
},
{
key: 'buy', zh: '采购齐套',
roleZh: '采购本部 · 订单到齐套',
icon: 'cart', codes: ['K01', 'DR-05', 'DR-15'],
dwell: 8.6, dwellTarget: 7.0, flow: 1240, flowUnitZh: '张采购单',
fpqc: 91.2, fpqcTarget: 94, rework: 104, reworkTarget: 80,
improve: 0.2,
},
{
key: 'mfg', zh: '生产制造',
roleZh: '制造本部 · 投产到下线',
icon: 'factory', codes: ['P01', 'P02', 'DR-07', 'DR-09'],
dwell: 3.6, dwellTarget: 3.2, flow: 3600, flowUnitZh: '张工单',
fpqc: 96.4, fpqcTarget: 97.5, rework: 132, reworkTarget: 110,
improve: 0.8,
},
{
key: 'deliver', zh: '仓储交付',
roleZh: '供应链本部 · 计划到签收',
icon: 'truck', codes: ['R12', 'E01', 'DR-14'],
dwell: 5.2, dwellTarget: 4.5, flow: 2900, flowUnitZh: '张出货单',
fpqc: 94.8, fpqcTarget: 96.5, rework: 68, reworkTarget: 55,
improve: 0.3,
},
{
key: 'cash', zh: '服务与回款',
roleZh: '财务/服务部 · 交付到回款',
icon: 'cash', codes: ['E03', 'Q08', 'M04', 'R13'],
dwell: 9.4, dwellTarget: 8.0, flow: 480, flowUnitZh: '件服务工单',
fpqc: 88.6, fpqcTarget: 92, rework: 55, reworkTarget: 45,
improve: -0.25,
},
];
/** 两频正弦叠加:让 12 期有起伏但不毛躁,同 seed 同 period 恒定 */
function wave(period: number, seed: number) {
const p = period + 1;
return Math.sin(p * 0.78 + seed * 1.7) * 0.55 + Math.sin(p * 0.31 + seed * 0.9) * 0.45;
}
/** 全链流量随季节缓涨(年末交付高峰),到当期约 +12% */
const season = (period: number) => 1 + 0.12 * (period - 5.5) / 5.5;
const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
const r1 = (v: number) => +v.toFixed(1);
export interface StageStats {
/** 本段平均停留(周期)天数 */
dwell: number;
dwellTarget: number;
/** 月流转量 */
flow: number;
/** 一次通过率 % */
fpqc: number;
fpqcTarget: number;
/** 月返工/退回件数 */
rework: number;
reworkTarget: number;
/** 在制品:Little 法则 WIP = 吞吐 × 停留 / 30 */
wip: number;
/** 段达成率 %(停留 40% + 一次通过 40% + 返工 20%) */
score: number;
status: 'green' | 'yellow' | 'red';
/** 相对上期的停留变化(天),负 = 在提速 */
dwellDelta: number | null;
}
export function stageStats(index: number, period: number): StageStats {
const s = STAGES[index];
const t = (period - 5.5) / 5.5; // -1 → 0 → +1 的全期趋势轴
const drift = (k: number) => wave(period, index * 7 + k);
const dwell = dwellAt(index, period);
const fpqc = r1(clamp(s.fpqc + s.improve * 3.4 * t + drift(2) * 1.3, 55, 99.5));
const flow = Math.round(s.flow * season(period) * (1 + drift(3) * 0.035));
const rework = Math.max(0, Math.round(s.rework * (1 - s.improve * 0.16 * t - drift(4) * 0.05)));
const wip = Math.round(flow * dwell / 30);
const score = (
clamp(s.dwellTarget / dwell, 0.6, 1.2) * 0.4
+ clamp(fpqc / s.fpqcTarget, 0.6, 1.2) * 0.4
+ clamp(s.reworkTarget / Math.max(1, rework), 0.6, 1.2) * 0.2
) * 100;
return {
dwell, dwellTarget: s.dwellTarget, flow, fpqc, fpqcTarget: s.fpqcTarget,
rework, reworkTarget: s.reworkTarget, wip,
score: +score.toFixed(1),
status: score >= 99.5 ? 'green' : score >= 92 ? 'yellow' : 'red',
dwellDelta: period > 0 ? r1(dwell - dwellAt(index, period - 1)) : null,
};
}
/** 单段停留:stageStats 与环比都要用,抽出来保证两处口径一致 */
function dwellAt(index: number, period: number) {
const s = STAGES[index];
const t = (period - 5.5) / 5.5;
return r1(s.dwell * (1 - s.improve * 0.14 * t + wave(period, index * 7 + 1) * 0.05));
}
export interface FlowSummary {
/** 端到端总周期(各段停留之和,天) */
cycle: number;
cycleBase: number;
/** 端到端一次通过率(各段 FPQC 连乘,%) */
e2e: number;
e2eBase: number;
/** 有效产出 = 链上最小吞吐(约束理论,批次/月) */
throughput: number;
constraintKey: string;
/** 全链在制品 */
wip: number;
/** 达成率最低的一段 */
bottleneckKey: string;
bottleneckScore: number;
}
export function flowStats(period: number): { stats: StageStats[]; summary: FlowSummary } {
const stats = STAGES.map((_, i) => stageStats(i, period));
const cycle = +stats.reduce((a, x) => a + x.dwell, 0).toFixed(1);
const e2e = +(stats.reduce((a, x) => a * x.fpqc / 100, 1) * 100).toFixed(1);
const constraint = stats.reduce((mi, x, i) => (x.flow < stats[mi].flow ? i : mi), 0);
const worst = stats.reduce((mi, x, i) => (x.score < stats[mi].score ? i : mi), 0);
return {
stats,
summary: {
cycle,
cycleBase: +STAGES.reduce((a, s) => a + s.dwell, 0).toFixed(1),
e2e,
e2eBase: +(STAGES.reduce((a, s) => a * s.fpqc / 100, 1) * 100).toFixed(1),
throughput: stats[constraint].flow,
constraintKey: STAGES[constraint].key,
wip: stats.reduce((a, x) => a + x.wip, 0),
bottleneckKey: STAGES[worst].key,
bottleneckScore: stats[worst].score,
},
};
}
+292
View File
@@ -0,0 +1,292 @@
import type { DigitalStaff, MetricNode } from '../data/sqlite';
import { achieveRate, fmt, fmtSigned, gapOf } from './metric';
/**
* 专家团(多智能体协作):把若干数智智能体拉到一起,围绕当前聚焦指标做「轮流会诊 → 牵头汇总」。
* 这里只放纯数据与纯函数(无副作用、不依赖 UI / tokens),由 AgentDock 消费并做时序播放。
*/
/** 预设团语义色:映射到主题 tokens,避免组件里硬编码色值 */
export type TeamTone = 'success' | 'danger' | 'info' | 'warning' | 'accent';
export interface ExpertTeam {
/** 唯一 id:自由团用时间戳,预设团用 key。AgentDock 依赖它变化重新触发会诊 */
id: string;
nameZh: string;
topicZh: string;
/** 牵头智能体 code(负责最终汇总) */
leadCode: string;
/** 全部成员 code(含牵头,顺序即会诊发言顺序) */
memberCodes: string[];
/** 是否预设团(自由勾选团为 false,展示时区分) */
preset: boolean;
/** 卡片主色(语义 token 键) */
tone: TeamTone;
}
interface PresetDef {
key: string;
tone: TeamTone;
nameZh: string;
topicZh: string;
lead: string;
members: string[];
}
/**
* 5 个预设专家团:按业务场景编排,牵头智能体放在成员首位。
* code 全部对应 data/sqlite.ts 的 STAFF 种子,改种子不会漏改这里(build 时按 code 解析)。
*/
const PRESET_DEFS: PresetDef[] = [
{
key: 'profit', tone: 'success', nameZh: '盈利攻坚团',
topicZh: '毛利率与盈利结构改善',
lead: 'MARG', members: ['MARG', 'COST', 'FINA', 'CAUSAL', 'OPEX'],
},
{
key: 'risk', tone: 'danger', nameZh: '风险处置团',
topicZh: '红色告警与风险敞口处置',
lead: 'RISK', members: ['RISK', 'ALERT', 'INV', 'FXA', 'COMP'],
},
{
key: 'growth', tone: 'info', nameZh: '增长突破团',
topicZh: '订单、客户与新品增长',
lead: 'ORDR', members: ['ORDR', 'CUST', 'NPIA', 'LEAD', 'CHNL'],
},
{
key: 'delivery', tone: 'warning', nameZh: '交付提效团',
topicZh: '产能、质量与交付保障',
lead: 'SCHED', members: ['SCHED', 'EQUIP', 'DLVR', 'QUAL', 'PROC'],
},
{
key: 'rnd', tone: 'accent', nameZh: '研发动能团',
topicZh: '研发进度、专利与新品贡献',
lead: 'RDPG', members: ['RDPG', 'PATO', 'NPIA'],
},
];
/** 把预设定义解析为 ExpertTeam(供面板渲染与选择) */
export function presetTeams(): ExpertTeam[] {
return PRESET_DEFS.map(d => ({
id: d.key, nameZh: d.nameZh, topicZh: d.topicZh,
leadCode: d.lead, memberCodes: d.members, preset: true, tone: d.tone,
}));
}
/** 自由勾选组建:给定 code 列表(首位视作牵头),生成一个自定义专家团 */
export function customTeam(codes: string[]): ExpertTeam | null {
if (codes.length < 2) return null;
return {
id: `custom-${Date.now()}`,
nameZh: '自定义专家团',
topicZh: '跨维度多智能体协同会诊',
leadCode: codes[0], memberCodes: codes, preset: false, tone: 'accent',
};
}
/** 指标快照:成员卡顶部的数据条 */
export interface MetricSnap {
label: string;
value: string;
target: string;
rate: number;
gap: string;
level: 'good' | 'warn' | 'bad';
}
/** 会诊里的一条发言(结构化,供对话区渲染成卡片) */
export interface ConsultTurn {
kind: 'system' | 'member' | 'lead';
/** 展示名(指标名) */
name: string;
/** 角色 / 技能小标签 */
tag: string;
/** 该成员绑定指标 code(牵头汇总为 undefined) */
boundMetric?: string;
/** system 就位播报纯文本 */
text?: string;
/** member:当前动作 */
status?: string;
/** member:绑定指标快照 */
metric?: MetricSnap;
/** member:观点一句话 */
stance?: string;
/** member:具体建议 */
proposal?: string;
/** member:协作移交对象名(多智能体剧情衔接) */
handoff?: string;
/** lead:结论 headline */
conclusion?: string;
/** lead:成员要点 */
summary?: { name: string; point: string }[];
/** lead:综合研判 */
judge?: { label: string; rate: number; gap: string; verdict: string; level: MetricSnap['level'] };
/** lead:联合行动清单 */
actions?: { owner: string; role: string; action: string }[];
}
/** 取 role 的第一段作为短标签('标准成本 · 差异归因' → '标准成本') */
function shortRole(role: string): string {
return role.split(/[·]/)[0].trim();
}
const levelOf = (rate: number): MetricSnap['level'] => (rate >= 100 ? 'good' : rate >= 95 ? 'warn' : 'bad');
/** 观点句式模板(b=指标名 r=达成率 g=偏差 f=聚焦指标),5 套轮换保证同团内不重复 */
type StanceTpl = (b: string, r: string, g: string, f: string) => string;
const STANCE_GOOD_ZH: StanceTpl[] = [
(b, r, _g, f) => `我这条「${b}」已达标(${r}),可以把余力投向${f}。`,
(b, r, _g, f) => `「${b}」运行在目标之上(${r}),不是${f}的拖累项。`,
(b, r, _g, _f) => `「${b}」运行平稳(${r}),我有余力支援短板线。`,
(b, r, _g, f) => `「${b}」已站上目标(${r}),可作为${f}的稳定压舱石。`,
(b, r, _g, f) => `「${b}」达标(${r}),我建议把增量资源集中到${f}的短板而非平均撒网。`,
];
const STANCE_BAD_ZH: StanceTpl[] = [
(b, _r, g, f) => `我这条「${b}」还差 ${g},是拖累${f}的主因之一。`,
(b, _r, g, f) => `「${b}」缺口 ${g},若不纠偏会持续侵蚀${f}。`,
(b, r, _g, f) => `「${b}」达成率仅 ${r},是我这条线对${f}的最大负贡献。`,
(b, _r, g, f) => `「${b}」当前 ${g} 的缺口若不止血,${f} 的下月口径还会被拉低。`,
(b, r, g, f) => `「${b}」达成率 ${r}、缺口 ${g},是我这条线最需要${f}会诊资源的地方。`,
];
/**
* 生成完整会诊脚本:系统就位播报 → 各成员轮流发言(现状+指标+观点+建议+移交)→ 牵头汇总(结论+要点+研判+行动)。
* 内容全部由真实数据驱动,并按成员序号轮换措辞,避免千篇一律;成员间带移交衔接,体现多智能体协作剧情。
*/
export function buildConsultScript(
team: ExpertTeam,
staffByCode: Map<string, DigitalStaff>,
nodeByCode: Map<string, MetricNode>,
focus: MetricNode | undefined,
): ConsultTurn[] {
const members = team.memberCodes
.map(c => staffByCode.get(c))
.filter((s): s is DigitalStaff => !!s);
if (!members.length) return [];
const nm = (s: DigitalStaff) => (s.name_zh);
const rl = (s: DigitalStaff) => (s.role_zh);
const cur = (s: DigitalStaff) => (s.cur_zh);
const nodeName = (n: MetricNode) => (n.name_zh);
/* 单位口径与单轮问答一致:% 类指标的偏差用百分点 pt,非 % 类按语言取单位 */
const unitOf = (u: string) => (u);
const gapU = (n: MetricNode) => (n.unit === '%' ? 'pt' : unitOf(n.unit));
const snapOf = (n?: MetricNode): MetricSnap | undefined => n ? {
label: nodeName(n),
value: `${fmt(n.value)}${unitOf(n.unit)}`,
target: `${fmt(n.target)}${unitOf(n.unit)}`,
rate: achieveRate(n),
gap: `${fmtSigned(gapOf(n))}${gapU(n)}`,
level: levelOf(achieveRate(n)),
} : undefined;
const tName = team.nameZh;
const tTopic = team.topicZh;
const focusLabel = focus ? nodeName(focus) : tTopic;
const focusStr = focus
? (`「${focusLabel}」达成率 ${fmt(achieveRate(focus), 0)}%(偏差 ${fmtSigned(gapOf(focus))}${gapU(focus)})`)
: (`主题「${tTopic}」`);
const turns: ConsultTurn[] = [];
// 1) 系统就位播报
const roster = members.map(nm).join('、');
turns.push({
kind: 'system',
name: '会诊主持',
tag: '多智能体协作',
text: `「${tName}」已就位(${members.length} 位专家):${roster}。\n围绕${focusStr},各位专家依次会诊。`,
});
// 2) 各成员轮流发言(结构化:现状 / 指标 / 观点 / 建议 / 移交)
const lead = staffByCode.get(team.leadCode) ?? members[0];
const stances: string[] = [];
members.forEach((s, i) => {
const bound = nodeByCode.get(s.bound_metric);
const metric = snapOf(bound);
const bLabel = metric?.label ?? '';
const rateStr = metric ? `${fmt(metric.rate, 0)}%` : '';
const gapStr = metric?.gap ?? '';
const targetStr = metric?.target ?? '';
const good = (metric?.rate ?? 0) >= 100;
const stance = (good
? (STANCE_GOOD_ZH)
: (STANCE_BAD_ZH))[i % 5](bLabel, rateStr, gapStr, focusLabel);
stances.push(stance);
let proposal: string;
if (good) {
proposal = i % 2 === 0
? (`保持「${bLabel}」节奏,并把富余资源调剂给短板线。`)
: (`把「${bLabel}」的达标打法固化,向其他线横向复制。`);
} else {
proposal = i % 3 === 0
? (`未来 2 周把「${bLabel}」拉回 ${targetStr},按日跟踪缺口收敛。`)
: i % 3 === 1
? (`本周锁定「${bLabel}」责任人与对策,目标缺口 ${gapStr} 清零。`)
: (`对「${bLabel}」启动专项,先止住 ${gapStr} 缺口再谈改善。`);
}
const handoffName = i === members.length - 1 ? nm(lead) : nm(members[i + 1]);
turns.push({
kind: 'member',
name: nm(s),
tag: rl(s),
boundMetric: s.bound_metric,
status: cur(s),
metric,
stance,
proposal,
handoff: handoffName,
});
});
// 3) 牵头汇总:结论 + 成员要点 + 综合研判 + 联合行动
const snaps = members.map(s => ({ s, m: snapOf(nodeByCode.get(s.bound_metric)) }));
const ranked = snaps.filter(x => x.m).sort((a, b) => a.m!.rate - b.m!.rate);
const worst = ranked[0];
const rate = focus ? achieveRate(focus) : null;
const gap = focus ? gapOf(focus) : null;
const conclusion = worst
? (`综合 ${members.length} 位专家口径,${focusLabel}的核心矛盾是 ${nm(worst.s)} 线的 ${worst.m!.gap} 缺口。`)
: (`综合 ${members.length} 位专家口径,形成${focusLabel}的纠偏共识。`);
const summary = members.map((s, i) => ({
name: nm(s),
point: stances[i].split(/[。,]/)[0],
}));
const judge = {
label: focusLabel,
rate: rate ?? 0,
gap: focus ? `${fmtSigned(gap!)}${focus.unit === '%' ? 'pt' : unitOf(focus.unit)}` : '',
verdict: rate === null
? ('需跨维度协同推进')
: rate >= 100
? ('整体达标,保持并扩大优势')
: rate >= 95
? ('接近达标,需针对性纠偏')
: ('偏离目标,需专项攻坚'),
level: levelOf(rate ?? 0),
};
const actions = ranked.slice(0, 3).map(x => ({
owner: nm(x.s),
role: shortRole(rl(x.s)),
action: `把「${x.m!.label}」从 ${x.m!.value} 拉回 ${x.m!.target}(缺口 ${x.m!.gap}),锁定责任人与期限`,
}));
turns.push({
kind: 'lead',
name: nm(lead),
tag: '牵头汇总',
conclusion,
summary,
judge,
actions,
});
return turns;
}
+117
View File
@@ -0,0 +1,117 @@
import { ONTOLOGY_AS_OF } from '../data/ontology';
import type { MetricNode } from '../data/sqlite';
/**
* 全局时间游标:0-11 对应「以业务快照日为锚点的近 12 个月」。
* 窗口锚在 ONTOLOGY_AS_OF 所在月(2026-10),因此最后一期=当期,往前 11 期为历史,
* 回放条、指标趋势(metric_trend)与履约单据用的是同一条时间轴。
* 节点当期值(value)只是游标=11 的快照;图谱/看板/Header 统一经此模块
* 按游标重算取值与状态,拖动时间滑块即可"回放"每个时点的指标表现。
*/
export const PERIOD_COUNT = 12;
/** 默认停在最后一期(当期) */
export const CURRENT_PERIOD = PERIOD_COUNT - 1;
/** 12 期标签:2025-11 … 2026-10(随 ONTOLOGY_AS_OF 自动滚动,不再硬编码年份) */
export const PERIOD_MONTHS: string[] = (() => {
const y = Number(ONTOLOGY_AS_OF.slice(0, 4));
const m = Number(ONTOLOGY_AS_OF.slice(5, 7));
return Array.from({ length: PERIOD_COUNT }, (_, i) => {
const idx = m - (PERIOD_COUNT - 1 - i);
const year = y + Math.floor((idx - 1) / 12);
const month = ((idx - 1) % 12 + 12) % 12 + 1;
return `${year}-${String(month).padStart(2, '0')}`;
});
})();
/** 游标是否为当期(业务快照所在期) */
export const isCurrentPeriod = (period: number) => period >= CURRENT_PERIOD;
/** 游标期的数据截止日:当期用真实快照日,历史期取该月月末 */
export function periodAsOf(period: number): string {
if (isCurrentPeriod(period)) return ONTOLOGY_AS_OF;
const month = PERIOD_MONTHS[Math.max(0, Math.min(PERIOD_COUNT - 1, period))];
const [y, m] = month.split('-').map(Number);
return `${month}-${String(new Date(y, m, 0).getDate()).padStart(2, '0')}`;
}
/** 游标期首日:用于把该期的单据窗口切出来 */
export function periodStart(period: number): string {
return `${PERIOD_MONTHS[Math.max(0, Math.min(PERIOD_COUNT - 1, period))]}-01`;
}
/** 游标时点的指标值:trend 缺失时回退当期值 */
export function valueAt(n: MetricNode, period: number): number {
const t = n.trend;
if (!t || !t.length) return n.value;
return t[Math.min(period, t.length - 1)] ?? n.value;
}
/** 游标时点偏差(已按 polarity 归一:正=优于目标) */
export function gapAt(n: MetricNode, period: number): number {
const raw = valueAt(n, period) - n.target;
return +(n.polarity === 'down' ? -raw : raw).toFixed(2);
}
/** 游标时点达成率(%),越低越好类取倒数口径 */
export function achieveAt(n: MetricNode, period: number): number {
const v = valueAt(n, period);
if (!n.target) return 100;
const r = n.polarity === 'down'
? (n.target / (v || 1)) * 100
: (v / n.target) * 100;
return +Math.min(r, 999).toFixed(1);
}
/** 游标时点的动态预警分级:按「达标 → 警戒线」两档判定,比固定比率更贴合口径 */
export function statusAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' {
const v = valueAt(n, period);
const better = n.polarity === 'down' ? v <= n.target : v >= n.target;
if (better) return 'green';
const safe = n.polarity === 'down' ? v <= n.alert_threshold : v >= n.alert_threshold;
return safe ? 'yellow' : 'red';
}
/** 图谱/看板取色用状态:当期沿用主数据定级(与告警计数、指标树一致),
* 历史期由游标值反推,拖动滑块即可看到红黄绿的时空迁移。 */
export function levelAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' {
return period === CURRENT_PERIOD
? (n.alert_level === 'red' || n.alert_level === 'yellow' ? n.alert_level : 'green')
: statusAt(n, period);
}
/** 环比上期变化(原始值差,不做 polarity 归一,由调用方按语义着色) */
export function momAt(n: MetricNode, period: number): number | null {
if (period <= 0) return null;
return +(valueAt(n, period) - valueAt(n, period - 1)).toFixed(2);
}
/** 游标期标签:2026-03 */
export function periodLabel(period: number): string {
return PERIOD_MONTHS[Math.max(0, Math.min(PERIOD_COUNT - 1, period))];
}
/** 完整 12 期序列(trend 缺失时以当期值补齐,保证柱子数量恒定为 12) */
export function seriesOf(n: MetricNode): number[] {
return Array.from({ length: PERIOD_COUNT }, (_, i) => valueAt(n, i));
}
/**
* 游标投影:把“该时点的值 + 该时点的定级”贴回节点本身。
* 下游所有当期口径工具(gapOf / achieveRate / alertColor(n.alert_level))无需改造即变成时点口径,
* 避免逐个改 30+ 取值点带来的遗漏。trend 不投影,回看历史与预测仍拿得到完整序列。
*/
export function projectAt(n: MetricNode, period: number): MetricNode {
if (period === CURRENT_PERIOD) return n;
return { ...n, value: valueAt(n, period), alert_level: statusAt(n, period) };
}
/** 整棵树投影(MetricTreePanel 依赖 children 遍历) */
export function projectTree(nodes: MetricNode[], period: number): MetricNode[] {
if (period === CURRENT_PERIOD) return nodes;
return nodes.map(n => ({
...projectAt(n, period),
children: n.children ? projectTree(n.children, period) : undefined,
}));
}
+27
View File
@@ -0,0 +1,27 @@
declare module 'sql.js' {
export interface SqlJsStatic {
Database: new (data?: ArrayLike<number> | null) => Database;
}
export interface QueryExecResult {
columns: string[];
values: any[][];
}
export interface Statement {
bind(values?: any[] | Record<string, any>): boolean;
run(values?: any[]): Statement;
step(): boolean;
get(): any[];
getAsObject(): Record<string, any>;
reset(): void;
free(): boolean;
}
export interface Database {
run(sql: string, params?: any[]): Database;
exec(sql: string, params?: any[]): QueryExecResult[];
prepare(sql: string, params?: any[]): Statement;
close(): void;
getRowsModified(): number;
export(): Uint8Array;
}
export default function initSqlJs(config?: { locateFile?: (file: string) => string }): Promise<SqlJsStatic>;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />