新增模块

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
@@ -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>
);
}