20 Commits
Author SHA1 Message Date
dongsk 9c45aedbe8 update css 2026-10-18 23:02:15 +08:00
dongsk 90ee2b30f5 搜索 2026-10-18 21:50:40 +08:00
dongsk 4e2459f2c8 新增融合skill 2026-10-18 21:41:09 +08:00
dongsk 2a34c94268 新增融合经验 2026-10-18 21:38:01 +08:00
dongsk 8f6904b2d1 新增武传demo 2026-10-18 21:20:33 +08:00
dongsk 32c16e86b0 修改细节 2026-10-18 20:47:02 +08:00
dongsk 5a6dc3b9f7 调整异常 2026-10-18 16:10:50 +08:00
dongsk f2e6d2b3f1 新增模块 2026-10-18 15:27:02 +08:00
dongsk 5b7d1e8f64 镜像源调整 2026-09-03 11:56:49 +08:00
dongsk 2336d345c0 更新bexapi 地址 2026-09-03 11:29:19 +08:00
dongsk dc4da05083 调整打包部署 2026-09-01 18:52:39 +08:00
dongsk d07ada995f /bexapi 接口调用带iam token鉴权 2026-09-01 17:36:56 +08:00
dongsk 7cf86b3735 添加 routerLink参数 2026-09-01 10:46:59 +08:00
dongsk 12c8a852a1 更新order-cost-analysis 2026-09-01 10:39:19 +08:00
dongsk 0edd4c8969 chore: add deploy script and deployment docs 2026-08-28 17:30:07 +08:00
dongsk cbb5cfd167 update 2026-08-28 16:07:18 +08:00
dongsk d027eba044 修改调整登录界面 2026-08-27 16:57:34 +08:00
dongsk cd5a385cda 所有模块添加路由守卫 2026-08-27 16:46:52 +08:00
dongsk 989120cab8 sso-login调整 2026-08-27 16:37:33 +08:00
dongsk 2d19c736a6 登录1 2026-08-27 16:06:23 +08:00
277 changed files with 51984 additions and 96 deletions
+1
View File
@@ -0,0 +1 @@
registry=https://registry.npmmirror.com
@@ -0,0 +1,37 @@
---
name: react-module-integration
description: 将独立 React(Vite) 前端项目融合进 ai-platform 平台成为首页可进入的模块,覆盖前期勘察、静态资源迁移、CSS 样式隔离、平台注册与验证部署全流程。当用户要求把 React 项目接入或融合进 ai-platform、新增平台模块、排查模块融合后白屏或部署异常时使用。不用于从零新建独立项目或纯后端接入。
---
# ai-platform React 模块融合
完整操作手册在 `references/react-module-integration-sop.md`(含命令、代码模板、案例),执行任何一步前先阅读对应章节。以下为必须遵守的红线与执行顺序。
## 执行顺序
1. **前期勘察**(SOP §1):对源项目逐项检查——新增依赖、路由方式、入口 Provider、全局 CSS、`document.body` 操作、public 资源清单、存储 key 前缀、`@keyframes` 命名、React 版本差异。
2. **目录规划与复制**(SOP §2):源码进 `src/modules/<name>/`,禁止复制 `main.tsx`、`__tests__`。
3. **静态资源迁移**(SOP §3):资源统一放 `public/mod-assets/<name>/`,代码引用全部改为绝对路径 `/mod-assets/<name>/xxx`(含 `locateFile`)。
4. **样式隔离**(SOP §4):模块根容器类(如 `.xxx-root`)作为所有选择器前缀;`body`/`:root`/`html`/`#root` 规则必须改写或删除;class、ID、裸元素三类冲突源都要检测。
5. **代码适配**(SOP §5):源 `main.tsx` 的 Provider 包裹与 CSS import 全部迁入模块 `App.tsx`;`tsc -b` 报错按清单修(TS6133、TS2554)。
6. **平台注册**(SOP §6):`moduleConfig` + `registry.ts` + `App.tsx` 路由(模块用 `React.lazy` 动态导入 + `<Suspense fallback={<ModuleLoading />}>` 包 `<Routes>`,禁止静态 import,否则模块 CSS 进主包)+ `HomePage.tsx` ICON_MAP 四件套。
7. **验证**(SOP §7):构建层、浏览器层(mock 登录注入)、回归层逐项打勾。
8. **部署检查**(SOP §8):nginx 加固与生产地址冒烟。
## 红线(违反必出事故)
- **路由与资源目录永不同名**:资源只放 `public/mod-assets/<name>/`,绝不能放 `public/<name>/`。否则 dist 下出现与路由同名目录,nginx 目录 301 补斜杠并把容器端口 `:8901` 泄漏进浏览器地址栏,新页签 403/空白(2026-10 生产事故,SOP §3、§8)。
- **样式绝对隔离**:所有 CSS 选择器挂模块根容器类下。模块 CSS 虽随 React.lazy 路由 chunk 按需加载,但加载后仍全局生效,裸选择器必然跨模块污染;同名 `@keyframes`/工具类若值不同必须重命名或作用域化。全局选择器由 `npm run check:styles` 零容忍门禁拦截(已接入 build,SOP §4.5);ID 选择器特异性最高,`#nav` 类冲突需给旧模块规则也加前缀(SOP §4.2)。
- **零平台侵入**:不改 `document.body`/`document.documentElement`,存储 key 带模块前缀,不与平台路由冲突。
- **Provider 必须迁移**:漏迁 `AppProvider` 会导致路由渲染时 context 为 null 白屏。
## 验证捷径
- 提交/构建前跑 `npm run check:styles`(已接入 build 门禁),退出码 0 = 模块 CSS 无全局选择器违规。
- 构建后 `ls dist/` 确认根目录无与路由同名目录。
- 部署后 `curl -sI https://生产域名/<name>` 期望 200(或 302 跳登录);出现 301 且 Location 带 `:8901` 即端口泄漏信号。
- 浏览器验证前先注入 mock 会话:`sessionStorage.setItem('userToken', 'mock-token-for-ui-check')`。
## 历史踩坑速查
详见 SOP §9 速查表。最高频三坑:同名资源目录端口泄漏、`#nav` ID 冲突、漏迁 Provider。
@@ -0,0 +1,276 @@
# React 前端项目融合 ai-platform 模块化 SOP
> 适用场景:将独立的 React 前端项目(Vite 构建)融合进 `ai-platform`,作为首页可进入的独立模块。
> 已按此 SOP 成功融合:jieya-ibp、welltrust-qap、baode-web、supplier-platform、wuc-quotation。
---
## 0. 核心原则(先记住这四条)
1. **样式绝对隔离**:模块 CSS 随 React.lazy 路由 chunk 按需加载(进入模块才下载该模块 JS+CSS),但加载后仍全局生效,任何裸元素选择器、`:root`/`body` 全局规则、裸 class/ID 选择器都会跨模块污染。**模块所有 CSS 选择器必须挂在模块根容器类下**;同名 `@keyframes` 与同名工具类若值不同,必须重命名或作用域化。
2. **路由与资源目录永不同名**:模块路由名(如 `/wuc-quotation`)绝不能与 `dist` 下静态资源目录同名,否则 nginx `try_files $uri` 命中目录触发自动 301 补斜杠重定向,Location 会带上容器内端口(8901)泄漏进浏览器地址栏,随后 403(详见 §3、§8)。资源统一放 `public/mod-assets/<模块名>/`。
3. **零平台侵入**:模块不得修改 `document.body`/`document.documentElement` 的 class/style,不得占用全局 localStorage key,不得与平台路由冲突。
4. **入口职责迁移**:源项目 `main.tsx` 中的 Provider 包裹、全局 CSS 引入等职责,全部迁移到模块 `App.tsx`,平台路由直接渲染模块默认导出。
---
## 1. 前期勘察(融合前必做,约 10 分钟)
对源项目逐项检查并记录结论:
| 检查项 | 命令/方法 | 判定 |
|---|---|---|
| 新增依赖 | 对比 `package.json` 与 ai-platform | 原则上零新增;有新增需评估版本冲突 |
| 路由方式 | 看源 `main.tsx`/`App.tsx` | URL 子路由 → 平台路由用 `/xxx/*`;内部 state 切页 → 精确 path 即可 |
| 入口 Provider | 看 `main.tsx` 的 `<XxxProvider>` 包裹 | **必须迁移**(否则路由渲染时 context 为 null 白屏) |
| 全局 CSS | grep `html`/`body`/`:root`/`#root` | 记录所有需剥离/迁移的全局规则 |
| body 操作 | grep `document.body`、`document.documentElement` | classList.toggle/style 修改需改为模块根容器 ref |
| public 资源 | `ls public/` | 记录文件清单与代码引用位置(grep 文件名) |
| 内嵌资产 | grep `data:` | base64 data URI 无需处理 |
| 存储 key | grep `localStorage`/`sessionStorage` | key 必须带项目前缀,无前缀需加 |
| keyframes | grep `@keyframes` | 与全平台 CSS 比对命名唯一性 |
| React 版本 | `package.json` | 平台为 React 18.3 + @types/react 19,注意类型差异(见 §5.3) |
---
## 2. 目录规划与代码复制
```
ai-platform/
├── src/modules/<name>/ # 模块源码
│ ├── App.tsx # 入口(含 Provider 包裹 + CSS 引入 + 根容器)
│ ├── index.ts # moduleConfig 导出
│ ├── app/ | pages/ | ... # 源项目 src 业务代码(排除 main.tsx、__tests__)
│ └── styles/ | *.css # 源项目样式
└── public/mod-assets/<name>/ # 模块静态资源(禁止放 public/<name>/)
```
```bash
mkdir -p ai-platform/src/modules/<name> ai-platform/public/mod-assets/<name>
cp -R <源项目>/src/app ai-platform/src/modules/<name>/app
cp -R <源项目>/src/styles ai-platform/src/modules/<name>/styles
cp <源项目>/src/App.tsx ai-platform/src/modules/<name>/App.tsx
# 不要复制 main.tsx、__tests__、vite.config 等入口/测试文件
```
---
## 3. 静态资源迁移
1. `public/` 下资源全部复制到 `public/mod-assets/<name>/`;
2. grep 源码中所有相对路径引用(`src="xxx.svg"`、`href="xxx.md"`、`locateFile` 等),统一改为绝对路径 `/mod-assets/<name>/xxx`;
3. 验证:dev 下直接访问 `http://localhost:<port>/mod-assets/<name>/xxx` 返回 200;
4. build 后确认 `dist/mod-assets/<name>/` 存在。
> 为什么不用 `public/<name>/`:Vite 会把 public 目录原样拷入 dist,形成与模块路由同名的目录。完整故障链(2026-10 生产事故):
> 1. 首页卡片 `window.open('/<name>')` → nginx `try_files $uri /index.html` 的 `$uri` 命中该**目录**(非文件);
> 2. nginx 对目录请求自动 301 补斜杠(`/`),且 `port_in_redirect` 默认为 on,Location 变成 `https://域名:8901/<name>/`——**容器内端口被泄漏到浏览器地址栏**;
> 3. `:8901` 在外网不可达/无该虚拟主机 → 目录又无 index.html → 最终 403 或空白。
> 症状特征:只有"新增且带同名静态目录"的模块新页签打开异常(地址栏出现 `:8901`),老模块完全正常。
---
## 4. 样式隔离(核心,必须逐条执行)
### 4.1 根容器命名空间
模块 App 最外层包一个根容器,所有 CSS 选择器挂到它下面:
```tsx
// App.tsx
const rootRef = useRef<HTMLDivElement>(null)
return <div className="xxx-root" ref={rootRef}>...</div>
```
命名空间化有三种落地方式(按源项目 CSS 规模选择):
| 方式 | 适用 | 案例 |
|---|---|---|
| 全量脚本转换 | CSS 大/规则多(尤其 minified) | wuc-quotation:5 个 CSS 全部选择器加 `.wuc-root` 前缀 |
| 仅冲突类加前缀 | CSS 小、冲突少 | baode-web:20 处冲突选择器加 `.baode-root` |
| 原生自带命名空间 | 源项目已经做好隔离 | supplier-platform:变量与布局挂 `.hansong-app` |
**脚本转换要点**(已踩坑):
- `:root{--var}` → `.xxx-root{--var}`(CSS 变量迁到根容器)
- `body` → `.xxx-root`;`body.dark`/`body.collapsed` → `.xxx-root.dark` 等(主题/状态类改挂根容器)
- `body > #root > header` → `.xxx-root > header`(层级补偿规则改写)
- `html, body{overflow:hidden}` 等 → **直接删除**(会锁死平台整页滚动);视口锁定改由 `.xxx-root{height:100vh}` 承接
- `@media` 块内部规则**必须递归处理**(漏掉会造成窄屏规则逃逸成全局)
- `@keyframes`/`@font-face` 原样保留;字符串(data URI)不能破坏——需状态机解析而非正则替换
- 转换完必须校验:无残留 `body`/`:root`/`html`/`#root` 选择器、brace 平衡
### 4.2 三类冲突源都要检测(缺一不可)
```python
# 检测思路(对每个已存在模块 + 平台全局样式执行)
# 1. class 冲突:新模块 TSX className 集合 ∩ 双方 CSS 类名集合
# 2. ID 冲突:新模块 TSX 中的 id="xxx" ∩ 其它模块 CSS 中的 #xxx(双向)
# 3. 裸元素选择器:新模块 CSS 中 html/body/header/aside/nav/button/input 等无前缀选择器
```
> **ID 冲突是隐藏最深的坑**:`#nav` 特异性(1,0,0)碾压任何 `.wuc-root nav`(0,1,1)。wuc-quotation 上线后菜单被 supplier-platform 的 `#nav{display:flex}` 强制水平排列。修复方式是给**旧模块**的 ID 规则也加根容器前缀(`.hansong-app #nav`)。
### 4.3 运行时全局副作用清理
- `document.body.classList.toggle('dark'/'collapsed')` → `rootRef.current?.classList.toggle(...)`
- `document.body.style.overflow = ...`(如 LoginPage 的 useEffect)→ 模块内改为根容器样式或卸载时恢复
- 弹窗/Portal 挂载点若用 `document.body`,改为模块根容器内渲染
- `@media print` 中 `body{...}` 规则 → `.xxx-root{...}`,并放开视口锁定(`height:auto;overflow:visible`)
### 4.4 其它隔离项
- localStorage/sessionStorage key 带项目前缀(如 `wuchuan-quotation-v1`)
- `@keyframes` 命名全平台唯一(冲突时给新模块 keyframes 加前缀)
- 各模块 CSS 文件内不放 `@import` 全局重置(normalize/reset 一律禁止)
### 4.5 全局选择器门禁(check:styles)
`scripts/check-module-styles.mjs`(`npm run check:styles`)是样式隔离的零容忍门禁:以状态机逐字符解析扫描 `src/modules/**/*.css`(兼容数 MB 的 minified CSS 与 data URI 字符串),命中裸标签选择器(`button`/`table` 等)、裸 `:root`/伪类伪元素(`::-webkit-scrollbar` 等)、通配符 `*`、裸属性选择器、`@import` 引入 reset/normalize 即判违规,非零码退出。已接入 build 门禁(`npm run build` = `tsc -b && npm run check:styles && vite build`),日常可单独运行:
```bash
npm run check:styles # 退出码 0 = 模块 CSS 无全局选择器违规
```
---
## 5. 代码适配
### 5.1 入口与 Provider
```tsx
// App.tsx 末尾:平台路由直接渲染默认导出,Provider 职责从 main.tsx 移到这里
import { AppProvider } from './app/store'
export default function App() {
return (
<AppProvider>
<AppShell />
</AppProvider>
)
}
```
同时把源 `main.tsx` 的 CSS import 全部搬到模块 `App.tsx` 顶部(保持原有顺序)。
### 5.2 严格 tsconfig 适配(tsc -b 报错清单)
- `TS6133` 未使用变量/import → 删除(含解构中未使用的成员)
- `TS2554`:`useRef<T>()` → `useRef<T | undefined>(undefined)`(@types/react 19 要求初始值)
- 默认导入 `import React` 未使用 → 删除(react-jsx transform 无需)
### 5.3 其他常见点
- 事件监听/定时器在组件卸载时清理(模块可被随时切走)
- 弹窗内 `dangerouslySetInnerHTML` 注入的 HTML,其类名也要被命名空间 CSS 覆盖(确认前缀后仍能匹配)
- 内部 state 切页的项目保留原交互,不强行改造为 URL 路由
---
## 6. 平台注册(三件套 + 图标)
```ts
// 1. src/modules/<name>/index.ts
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: '<name>',
name: '模块中文名',
description: '一句话描述',
icon: 'Lucide图标名', // 如 FileSpreadsheet / Radar / Building2
path: '/<name>',
accentColor: '#7C6FFF', // 暗色强调色
accentColorLight: '#5747EF', // 亮色强调色
gradient: 'linear-gradient(135deg, ...)', // 暗色卡片渐变
gradientLight: 'linear-gradient(135deg, ...)', // 亮色卡片渐变
tags: ['标签1', '标签2'],
};
```
```ts
// 2. src/modules/registry.ts:import + modules 数组追加
// 3. src/App.tsx:模块级 React.lazy 动态导入 + 路由(ModuleTitle 负责页签标题,卸载恢复 'EIOSpace')
const XxxApp = lazy(() => import('@/modules/<name>/App'));
...
<Routes>
<Suspense fallback={<ModuleLoading />}>
<Route path="/<name>" element={<RequireAuth><ModuleTitle title="模块中文名"><XxxApp /></ModuleTitle></RequireAuth>} />
...
</Suspense>
</Routes>
// 4. src/pages/HomePage.tsx:ICON_MAP 增加图标(先在 lucide-react import 中补图标名)
```
> 模块入口必须用 `React.lazy` 动态导入(模块 CSS 随路由 chunk 按需加载),**静态 import 会把模块 CSS 打进主包,禁止**。
> 首页卡片点击已是 `window.open(mod.path, '_blank')` 新页签打开,无需额外处理。
---
## 7. 验证清单
**构建层**
- [ ] `npx tsc --noEmit` 通过
- [ ] `npm run build` 通过(注意 `tsc -b` 比 `tsc --noEmit` 更严,以 build 为准;已含 `check:styles` 门禁)
- [ ] `npm run check:styles` 退出码 0(模块 CSS 全局选择器零容忍门禁,见 §4.5,已接入 build)
- [ ] `dist/mod-assets/<name>/` 资源齐全
- [ ] **`ls dist/` 确认根目录下没有与模块路由同名的目录**(防端口泄漏,见 §3)
**浏览器层**(dev server + mock 登录)
```js
// 平台守卫只查 sessionStorage.userToken,浏览器验证先注入:
sessionStorage.setItem('userToken', 'mock-token-for-ui-check');
sessionStorage.setItem('userInfo', JSON.stringify({ name: '演示用户', userId: 'demo' }));
```
- [ ] `/<name>` 页面完整渲染(header/侧栏/内容区),控制台无 React 报错、无 404
- [ ] 页内交互可用(菜单切换、弹窗、主题切换)
- [ ] 新页签打开后浏览器标题为模块中文名
- [ ] 首页出现新模块卡片(图标、配色正确)
- [ ] 首页(未进入任何模块)Network 面板无任何模块级 CSS chunk
- [ ] 首次进入模块路由时按需加载对应 JS+CSS chunk(React.lazy 生效)
**回归层(改了旧模块 CSS 时必做)**
- [ ] 新模块关键布局 computed style 复核(如 nav 的 display)
- [ ] 被 CSS 影响的旧模块核心页面正常(如 supplier 顶栏导航)
- [ ] 平台首页/登录页样式未受污染
---
## 8. 部署注意(nginx)
- `nginx.conf` SPA 回退必须是 `try_files $uri /index.html;`——**禁止 `$uri/`**(目录命中 → 403 且不回退)
- **必须加两条重定向加固**(防止容器内端口泄漏到浏览器地址栏,2026-10 事故根因):
```nginx
server {
listen 8901;
...
port_in_redirect off; # 301 重定向的 Location 不带 8901 端口
absolute_redirect off; # 使用相对路径 Location,彻底避免泄漏 host/port
}
```
- 部署后用生产地址冒烟验证(新页签打开路径):
```bash
curl -sI https://ai-workshop.digiwincloud.com.cn/<name> | head -5
# 期望:HTTP 200(或 302 跳登录页)
# 异常信号:HTTP 301 且 Location 带 :8901 —— 即存在与路由同名的静态目录触发了目录重定向
```
- 模块静态资源引用用绝对路径 `/mod-assets/...`,与部署子路径无关
---
## 9. 历史踩坑速查表
| 案例 | 坑 | 修复 |
|---|---|---|
| baode-web ↔ supplier-platform | baode 自检页 `.page{max-width:1080px}` 污染 supplier 的 `section.page` | `.page`→`.checkpage` + 冲突类加 `.baode-root` 前缀 |
| supplier-platform | 源 tsconfig 宽松,`useRef<T>()` 在 @types/react 19 下报 TS2554 | `useRef<T \| undefined>(undefined)` |
| 全部模块 | dist 下与路由同名目录:早期 `try_files $uri/` 命中目录 403;去掉 `$uri/` 后 `$uri` 仍命中目录触发 301 补斜杠,`port_in_redirect` 默认 on 把容器端口 `:8901` 泄漏进浏览器地址栏,新页签跳到带端口地址后 403/空白 | 资源统一迁 `mod-assets/`;nginx 加 `port_in_redirect off; absolute_redirect off;` |
| wuc-quotation | 漏迁 `AppProvider` → 白屏 `ctx is null` | Provider 移入模块默认导出 |
| wuc-quotation | 001.css 7.8MB 内嵌 data URI + minified,正则替换会破坏资产 | 状态机解析转换,字符串原样保留 |
| wuc-quotation | `document.body.classList.toggle('dark')` 污染平台 body | 改挂 `.wuc-root` 根容器 ref |
| wuc-quotation | `@media` 内规则未递归前缀化(首版转换脚本 bug) | 递归处理 + 转换后自动校验 |
| wuc-quotation ↔ supplier-platform | `#nav` ID 特异性碾压类前缀,菜单被改 flex 水平 | 旧模块规则改 `.hansong-app #nav`;SOP 增加 ID 冲突检测 |
| jieya-ibp / welltrust-qap | sql.js wasm 路径、logo 相对路径失效 | 统一 `locateFile: () => '/mod-assets/<name>/...'` |
| 全部模块 | 模块 CSS 全局选择器(`:root`/`button`/`table`/`::-webkit-scrollbar`/`*`)跨模块污染 | 加模块根容器前缀 + `check:styles` 门禁(§4.5,已接入 build) |
@@ -0,0 +1,12 @@
# Checklist
- [x] `src/App.tsx` 全部模块组件改为 `React.lazy()` 动态导入,`<Suspense>` 兜底生效
- [x] `npx tsc -b` 类型检查通过
- [x] `npm run build` 成功,`dist/assets` 中每个模块的 CSS 为独立 chunk 文件(8 个 css chunk:主 css 12KB 仅平台样式,wuc 7.8MB、supplier/baode/jieya/welltrust/bomx 各自独立,共享 styles chunk 1 个)
- [x] `scripts/check-module-styles.mjs` 存在且能正确检测 `:root`/`html`/`body`/`*`/裸元素选择器/`@import` 重置,违规时非 0 退出并列出文件+行号(对 git HEAD 存量验证:46 条违规全部检出且行号正确,wuc 7.8MB data URI 零误报)
- [x] `package.json` 含 `check:styles` 脚本,且 `build` 脚本已接入该门禁(`tsc -b && npm run check:styles && vite build`)
- [x] `bomx-reuse-analyzer/styles.css` 无 `:root` 残留,模块页面 CSS 变量取值正常、视觉无回归(浏览器实测浅色 BOM 界面正常渲染)
- [x] `npm run check:styles` 退出码 0(✓ 模块样式检查通过,扫描 12 个文件)
- [x] 首页加载时 Network 面板无任何模块级 CSS chunk(实测仅 /src/index.css)
- [x] 跳转 `supplier-platform`/`wuc-quotation`/`bomx-reuse-analyzer` 时按需加载对应样式且渲染正常、无控制台报错(wuc 6 个样式文件按需加载;另验 jieya-ibp 深色主题正常)
- [x] 平台首页与登录页视觉未受模块样式污染(星空动画、卡片、按钮样式实测正常)
- [x] `docs/react-module-integration-sop.md` 与 `.trae/skills/react-module-integration/SKILL.md` 已包含 lazy 路由约定与 check:styles 校验说明(references 副本同步)
@@ -0,0 +1,70 @@
# 模块样式隔离与按需加载 Spec
## Why
当前 `src/App.tsx` 静态 import 全部 12 个模块的 App 组件,导致所有模块的 JS 与 CSS 全部打进主包,用户打开首页即下载全部模块样式(wuc-quotation 单个模块 CSS 约 7.8MB)。同时样式隔离仅依赖 SOP 中的手工命名空间约定,无自动化守护,仍存在残留全局选择器(如 `bomx-reuse-analyzer/styles.css` 的 `:root` 规则)可跨模块污染。
## What Changes
- **路由级懒加载**:`src/App.tsx` 中模块组件改为 `React.lazy()` 动态导入,外层包 `<Suspense>` 加载兜底;Vite 自动将每个模块拆为独立 JS+CSS chunk,仅在跳转到对应路由时才加载该模块样式。
- **样式隔离自动化守护**:新增 `scripts/check-module-styles.mjs` 检查脚本,扫描 `src/modules/**/*.css` 中的全局选择器(`:root`/`html`/`body`/`*`/裸元素选择器/`@import` 全局重置),发现违规即报错退出;注册为 `npm run check:styles`。
- **修复存量违规**:`bomx-reuse-analyzer/styles.css` 的 `:root` CSS 变量迁移到模块根容器类下。
- **构建管线接入**:存量违规清零后,将 `check:styles` 纳入 `build` 脚本,防止后续模块引入全局选择器。
- **文档同步**:更新 SOP 文档与 react-module-integration 技能,明确新模块接入必须使用 lazy 路由模式 + 命名空间根容器。
## Impact
- Affected specs: 无既有 spec(首次建立)
- Affected code:
- `src/App.tsx`(懒加载改造)
- `src/modules/bomx-reuse-analyzer/styles.css`(存量违规修复)
- `scripts/check-module-styles.mjs`(新增)
- `package.json`(新增 check:styles 脚本、build 接入)
- `docs/react-module-integration-sop.md`、`.trae/skills/react-module-integration/SKILL.md`(文档同步)
## ADDED Requirements
### Requirement: 模块按需加载
系统 SHALL 以 `React.lazy()` 动态导入方式注册全部模块路由,保证模块代码与样式拆分为独立 chunk,仅在用户导航至该模块路由时才发起加载。
#### Scenario: 首页不加载模块样式
- **WHEN** 用户登录后停留在平台首页(`/`)
- **THEN** Network 面板中不出现任何模块级 CSS chunk(如 `wuc-quotation`、`supplier-platform` 的 CSS 文件)
#### Scenario: 跳转模块时加载对应样式
- **WHEN** 用户首次导航到某模块路由(如 `/supplier-platform`)
- **THEN** 浏览器按需加载该模块对应的 JS 与 CSS chunk,模块界面正常渲染
#### Scenario: 加载期间兜底 UI
- **WHEN** 模块 chunk 尚在加载中
- **THEN** Suspense 兜底占位展示(平台风格的加载提示),加载完成后无报错切换至模块界面
#### Scenario: 构建产物按模块拆分
- **WHEN** 执行 `npm run build`
- **THEN** `dist/assets` 中每个模块生成独立的 JS 与 CSS 产物(含路由引用关系),`tsc -b` 类型检查通过
### Requirement: 模块样式全局选择器零容忍
系统 SHALL 提供自动化检查脚本,确保 `src/modules/**/*.css` 中不出现全局作用选择器;检查结果 SHALL 作为构建门禁。
#### Scenario: 扫描通过
- **WHEN** 执行 `npm run check:styles` 且所有模块 CSS 均挂在模块命名空间根容器类下
- **THEN** 脚本以退出码 0 结束,无违规输出
#### Scenario: 扫描发现违规
- **WHEN** 某模块 CSS 中存在 `:root`、`html`、`body`、`*`、裸元素选择器或 `@import` 全局重置
- **THEN** 脚本以非 0 退出码失败,并逐条输出违规文件、行号与选择器内容
#### Scenario: 构建门禁生效
- **WHEN** 模块 CSS 存在全局选择器违规时执行 `npm run build`
- **THEN** 构建失败并提示先修复样式违规
### Requirement: 存量违规清零
系统 SHALL 保证现有 12 个模块 CSS 无全局选择器残留,不污染平台首页、登录页及其它模块。
#### Scenario: bomx-reuse-analyzer 变量迁移
- **WHEN** `src/modules/bomx-reuse-analyzer/styles.css` 中存在 `:root { --xxx }` 规则
- **THEN** 变量定义迁移至该模块根容器类下,模块页面变量取值正常,视觉无回归
### Requirement: 新模块接入约定同步
SOP 文档与 react-module-integration 技能 SHALL 同步更新:新模块路由必须使用 lazy 动态导入模式,CSS 必须挂载在模块命名空间根容器下,并通过 check:styles 校验。
#### Scenario: 文档含懒加载约定
- **WHEN** 查阅 SOP 文档或技能文件
- **THEN** 可找到 lazy 路由模式代码约定与 check:styles 校验说明
@@ -0,0 +1,30 @@
# Tasks
- [x] Task 1: 路由级懒加载改造
- [x] SubTask 1.1: `src/App.tsx` 将 12 个模块组件的静态 import 全部改为 `React.lazy(() => import('...'))`
- [x] SubTask 1.2: `<Routes>` 外层包 `<Suspense>`,提供平台风格 loading 兜底(居中 spinner + "模块加载中"文案)
- [x] SubTask 1.3: 验证 `npx tsc -b` 类型检查通过;`npm run build` 后确认 `dist/assets` 中各模块 CSS 拆分为独立文件
- [x] Task 2: 样式隔离自动检查脚本
- [x] SubTask 2.1: 新增 `scripts/check-module-styles.mjs`:递归扫描 `src/modules/**/*.css`,检测 `:root`/`html`/`body`/`*` 选择器、裸元素选择器(无类/ID/命名空间前缀的元素标签规则)、`@import` 全局重置;违规输出文件+行号+选择器,非 0 退出
- [x] SubTask 2.2: `package.json` 注册 `"check:styles": "node scripts/check-module-styles.mjs"`
- [ ] Task 3: 修复存量违规(勘察确认共 5 个模组存在裸选择器,修复后须全部通过 check:styles)
- [x] SubTask 3.1: `bomx-reuse-analyzer/styles.css`(根容器 `.bomx-app`):`:root`→`.bomx-app`、`::-webkit-scrollbar*`/`input[type=...]`/`select`/`input:focus`/`:focus-visible` 全部加前缀
- [x] SubTask 3.2: `order-cost-analysis`:为 `pages-orig/CostCockpit.tsx`、`pages-orig/AIMCockpit.tsx` 根 div 添加 `ordercost-root` 类,`styles.css` 顶部级 `::-webkit-scrollbar` 三条规则加前缀
- [x] SubTask 3.3: `jieya-ibp`:App.tsx 根 div(加载态 + 主态)添加 `jieya-root` 类;`index.css` 的 `button`/`input, textarea`/`::-webkit-scrollbar` 四条规则加前缀
- [x] SubTask 3.4: `welltrust-qap`:同 3.3,根类 `welltrust-root`
- [x] SubTask 3.5: `supplier-platform/index.css`:`main`、`table/th/td/tr.rec-row/tbody tr` 等裸元素规则加 `.hansong-app` 前缀
- [x] SubTask 3.6: 检查受影响模组的 `createPortal` 挂载点均位于模块根容器内(bomx Drawer 挂 document.body 需包 `.bomx-app` 类包裹层);baode/bomx/jieya/welltrust 的 `@media (prefers-reduced-motion)` 内 `*` 通配规则加根前缀;jieya/welltrust 的 `.space-*` 同名不同值工具类作用域化、`slide-in-right` 等同名不同体 keyframes 重命名
- [x] SubTask 3.7: `npm run check:styles` 退出码 0(存量违规清零)
- [x] Task 4: 构建门禁与文档同步
- [x] SubTask 4.1: `package.json` 的 `build` 脚本接入 `check:styles`(`tsc -b && npm run check:styles && vite build`)
- [x] SubTask 4.2: 更新 `docs/react-module-integration-sop.md`:新增「路由必须 lazy 动态导入」约定与 check:styles 校验说明
- [x] SubTask 4.3: 同步 `.trae/skills/react-module-integration/SKILL.md`(红线与验证清单补充懒加载要求)
- [x] Task 5: 端到端验证
- [x] SubTask 5.1: `npm run dev` 启动,浏览器验证:首页 Network 无任何模块 CSS chunk(实测仅 /src/index.css)
- [x] SubTask 5.2: 依次跳转 `supplier-platform`、`wuc-quotation`、`bomx-reuse-analyzer`:按需加载对应 chunk、界面渲染正常、无控制台报错(另验 jieya-ibp 深色主题正常)
- [x] SubTask 5.3: 抽查首页与登录页视觉无污染、`bomx-reuse-analyzer` 页面样式无回归
# Task Dependencies
- Task 3 依赖 Task 2(需要脚本先检测出违规)
- Task 4 依赖 Task 2、Task 3(违规清零后才接入构建门禁)
- Task 5 依赖 Task 1(懒加载完成后方可验证按需加载);SubTask 5.3 依赖 Task 3
- Task 2 与 Task 1 无依赖,可并行
+7 -4
View File
@@ -7,7 +7,7 @@ WORKDIR /app
COPY package.json package-lock.json* ./
# 安装依赖
RUN npm install
RUN npm install --registry=https://registry.npmmirror.com
# 复制源码
COPY . .
@@ -21,9 +21,12 @@ FROM nginx:alpine
# 将构建产物复制到 Nginx 默认静态目录
COPY --from=builder /app/dist /usr/share/nginx/html
# 自定义 Nginx 配置:支持 SPA 路由 fallback + gzip
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Nginx 配置模板(支持 envsubst 环境变量替换)
COPY nginx.conf /etc/nginx/templates/default.conf.template
EXPOSE 80
# 默认后端 API 地址(运行时可通过 -e BACKEND_URL=... 覆盖)
ENV BACKEND_URL=http://10.100.154.100:8000
EXPOSE 8901
CMD ["nginx", "-g", "daemon off;"]
Executable
+34
View File
@@ -0,0 +1,34 @@
#!/bin/bash
set -e
# ── 配置项 ──────────────────────────────────────────
IMAGE_NAME="ai-platform:1.0.0"
CONTAINER_NAME="ai-platform"
PORT=8901
BACKEND_URL="${BACKEND_URL:-http://host.docker.internal:8000}"
# ───────────────────────────────────────────────────
echo ">>> 构建镜像 ${IMAGE_NAME} ..."
sudo docker build -t "$IMAGE_NAME" .
echo ">>> 停止并移除旧容器 ..."
sudo docker stop "$CONTAINER_NAME" 2>/dev/null || true
sudo docker rm "$CONTAINER_NAME" 2>/dev/null || true
echo ">>> 启动新容器 ..."
sudo docker run -d \
--name "$CONTAINER_NAME" \
-p "$PORT:8901" \
--add-host=host.docker.internal:host-gateway \
-e BACKEND_URL="$BACKEND_URL" \
"$IMAGE_NAME"
echo ">>> 等待 nginx 启动 ..."
sleep 2
echo ">>> 验证 ..."
sudo docker exec "$CONTAINER_NAME" curl -s -o /dev/null -w "HTTP %{http_code}\n" http://localhost:8901/
echo ""
echo ">>> 部署完成: http://localhost:$PORT"
echo ">>> 后端代理: $BACKEND_URL"
+206
View File
@@ -0,0 +1,206 @@
# AI Platform 打包部署指南
## 项目概况
| 项目 | 说明 |
|------|------|
| 项目名称 | ai-platform |
| 前端框架 | React 18 + TypeScript + Vite 8 |
| UI 库 | Ant Design 5 + Tailwind CSS 3 |
| 构建产物 | 静态文件(`dist/`),由 nginx 提供服务 |
| 容器化 | Docker 多阶段构建(builder → nginx:alpine) |
| 部署端口 | 8901 |
| 后端代理 | `http://host.docker.internal:8000`(可运行时覆盖) |
## 目录结构要点
```
ai-platform/
├── Dockerfile # 多阶段构建:node:20-alpine 构建 → nginx:alpine 运行
├── nginx.conf # nginx 配置模板(支持 ${BACKEND_URL} 环境变量替换)
├── .dockerignore # 排除 node_modules / dist / .git / *.md 等
├── package.json # build 脚本:tsc -b && vite build
├── vite.config.ts # 开发代理配置(/api/v1, /health, /bexapi, /iam-api)
├── index.html # 入口 HTML
├── src/ # 源码
├── public/ # 静态资源
└── docs/ # 文档(本文件所在目录)
```
## Docker 镜像构建
### Dockerfile 构建流程
1. **Stage 1 — builder(node:20-alpine)**
- 复制 `package.json` + `package-lock.json`,执行 `npm install`
- 复制全部源码,执行 `npm run build`(即 `tsc -b && vite build`)
- 产物输出到 `/app/dist`
2. **Stage 2 — 运行时(nginx:alpine)**
- 将 builder 阶段的 `/app/dist` 复制到 `/usr/share/nginx/html`
- 复制 `nginx.conf` 到 `/etc/nginx/templates/default.conf.template`(nginx 入口脚本会通过 `envsubst` 替换其中的 `${BACKEND_URL}`)
- 默认环境变量 `BACKEND_URL=http://host.docker.internal:8000`
- 暴露端口 8901
### 构建命令
```bash
sudo docker build -t ai-platform:1.0.0 .
```
构建过程利用了 Docker 缓存层:如果 `package.json` / `package-lock.json` 未变,`npm install` 层会命中缓存,仅重新执行源码复制和构建。
## 容器部署
### 启动命令
```bash
sudo docker run -d \
--name ai-platform \
-p 8901:8901 \
--add-host=host.docker.internal:host-gateway \
-e BACKEND_URL=http://host.docker.internal:8000 \
ai-platform:1.0.0
```
### 参数说明
| 参数 | 说明 |
|------|------|
| `-d` | 后台运行 |
| `--name ai-platform` | 容器名称 |
| `-p 8901:8901` | 宿主机 8901 端口映射到容器 8901 |
| `--add-host=host.docker.internal:host-gateway` | **必须添加**,否则 nginx 启动时无法解析 `host.docker.internal`,容器会立即退出(exit code 1) |
| `-e BACKEND_URL=...` | 后端 API 地址,运行时可覆盖。默认 `http://host.docker.internal:8000` |
> **踩坑记录**:Docker 29.x 版本中,`host.docker.internal` 不会自动解析,必须通过 `--add-host=host.docker.internal:host-gateway` 显式添加。如果不加此参数,nginx 启动报错:`host not found in upstream "host.docker.internal"`,容器退出码为 1。
### 重新部署(完整流程)
```bash
# 1. 构建新镜像
sudo docker build -t ai-platform:1.0.0 .
# 2. 停止并移除旧容器
sudo docker stop ai-platform
sudo docker rm ai-platform
# 3. 启动新容器
sudo docker run -d \
--name ai-platform \
-p 8901:8901 \
--add-host=host.docker.internal:host-gateway \
-e BACKEND_URL=http://host.docker.internal:8000 \
ai-platform:1.0.0
```
### 验证部署
```bash
# 检查容器运行状态
sudo docker ps --filter "name=ai-platform"
# 从容器内部验证 nginx 响应
sudo docker exec ai-platform curl -s -o /dev/null -w "HTTP %{http_code}" http://localhost:8901/
# 预期输出:HTTP 200
# 查看页面内容
sudo docker exec ai-platform curl -s http://localhost:8901/
# 查看 nginx 日志
sudo docker logs ai-platform
```
## nginx 配置说明
`nginx.conf` 作为模板文件放在 `/etc/nginx/templates/default.conf.template`,nginx 容器入口脚本会自动用 `envsubst` 将 `${BACKEND_URL}` 替换为环境变量值,输出到 `/etc/nginx/conf.d/default.conf`。
### 路由规则
| 路径 | 代理目标 | 说明 |
|------|----------|------|
| `/api/v1/` | `${BACKEND_URL}/api/v1/` | 后端 API,支持 SSE 长连接(关闭 buffering,300s 超时) |
| `/health` | `${BACKEND_URL}/health` | 健康检查 |
| `/bexapi/` | `https://bexell-scheduling.dongsk.top/api/` | Bexell 排程 API |
| `/iam-api/` | `https://iam.digiwincloud.com.cn/` | 鼎捷云 IAM 登录服务 |
| `/` | `try_files $uri $uri/ /index.html` | SPA 路由 fallback |
| `/assets/` | 本地静态文件 | 长缓存 1 年,`Cache-Control: public, immutable` |
| `*.svg/png/jpg/...` | 本地静态文件 | 缓存 30 天 |
### 开发环境 vs 生产环境代理对照
开发时由 Vite dev server 代理(`vite.config.ts`),生产时由 nginx 代理(`nginx.conf`),两者路径需保持一致:
| 路径 | Vite target | nginx proxy_pass |
|------|------------|-------------------|
| `/api/v1` | `http://localhost:8000` | `${BACKEND_URL}/api/v1/` |
| `/health` | `http://localhost:8000` | `${BACKEND_URL}/health` |
| `/bexapi` | `https://bexell-scheduling.dongsk.top`(rewrite → `/api`) | `https://bexell-scheduling.dongsk.top/api/` |
| `/iam-api` | `https://iam.digiwincloud.com.cn`(rewrite → 去前缀) | `https://iam.digiwincloud.com.cn/` |
## 常见问题排查
### 容器启动后立即退出(exit code 1)
**原因**:nginx 无法解析 `host.docker.internal`。
**解决**:启动时添加 `--add-host=host.docker.internal:host-gateway`。
**验证**:`sudo docker logs ai-platform` 查看是否有 `host not found in upstream` 错误。
### 构建时 TypeScript 编译失败
`npm run build` 先执行 `tsc -b` 类型检查,类型错误会导致构建中断。需修复所有 TS 错误后重新构建。
### 构建产物体积过大
当前主 chunk 约 1.9MB(gzip 后 581KB),Vite 会输出警告。如需优化:
- 使用动态 `import()` 对路由模块做懒加载(代码分割)
- 在 `vite.config.ts` 中配置 `build.rollupOptions.output.manualChunks` 手动分包
- 调整 `build.chunkSizeWarningLimit` 提高警告阈值(仅消除警告,不减小体积)
### 端口被占用
```bash
# 查看占用 8901 端口的进程
sudo lsof -i :8901
# 停止旧容器后释放端口
sudo docker stop ai-platform
```
## 快速部署脚本
将以下内容保存为 `deploy.sh` 即可一键重新打包部署:
```bash
#!/bin/bash
set -e
IMAGE_NAME="ai-platform:1.0.0"
CONTAINER_NAME="ai-platform"
PORT=8901
BACKEND_URL="${BACKEND_URL:-http://host.docker.internal:8000}"
echo ">>> 构建镜像..."
sudo docker build -t "$IMAGE_NAME" .
echo ">>> 停止旧容器..."
sudo docker stop "$CONTAINER_NAME" 2>/dev/null || true
sudo docker rm "$CONTAINER_NAME" 2>/dev/null || true
echo ">>> 启动新容器..."
sudo docker run -d \
--name "$CONTAINER_NAME" \
-p "$PORT:8901" \
--add-host=host.docker.internal:host-gateway \
-e BACKEND_URL="$BACKEND_URL" \
"$IMAGE_NAME"
echo ">>> 验证..."
sleep 2
sudo docker exec "$CONTAINER_NAME" curl -s -o /dev/null -w "HTTP %{http_code}\n" http://localhost:8901/
echo ">>> 部署完成: http://localhost:$PORT"
```
+276
View File
@@ -0,0 +1,276 @@
# React 前端项目融合 ai-platform 模块化 SOP
> 适用场景:将独立的 React 前端项目(Vite 构建)融合进 `ai-platform`,作为首页可进入的独立模块。
> 已按此 SOP 成功融合:jieya-ibp、welltrust-qap、baode-web、supplier-platform、wuc-quotation。
---
## 0. 核心原则(先记住这四条)
1. **样式绝对隔离**:模块 CSS 随 React.lazy 路由 chunk 按需加载(进入模块才下载该模块 JS+CSS),但加载后仍全局生效,任何裸元素选择器、`:root`/`body` 全局规则、裸 class/ID 选择器都会跨模块污染。**模块所有 CSS 选择器必须挂在模块根容器类下**;同名 `@keyframes` 与同名工具类若值不同,必须重命名或作用域化。
2. **路由与资源目录永不同名**:模块路由名(如 `/wuc-quotation`)绝不能与 `dist` 下静态资源目录同名,否则 nginx `try_files $uri` 命中目录触发自动 301 补斜杠重定向,Location 会带上容器内端口(8901)泄漏进浏览器地址栏,随后 403(详见 §3、§8)。资源统一放 `public/mod-assets/<模块名>/`。
3. **零平台侵入**:模块不得修改 `document.body`/`document.documentElement` 的 class/style,不得占用全局 localStorage key,不得与平台路由冲突。
4. **入口职责迁移**:源项目 `main.tsx` 中的 Provider 包裹、全局 CSS 引入等职责,全部迁移到模块 `App.tsx`,平台路由直接渲染模块默认导出。
---
## 1. 前期勘察(融合前必做,约 10 分钟)
对源项目逐项检查并记录结论:
| 检查项 | 命令/方法 | 判定 |
|---|---|---|
| 新增依赖 | 对比 `package.json` 与 ai-platform | 原则上零新增;有新增需评估版本冲突 |
| 路由方式 | 看源 `main.tsx`/`App.tsx` | URL 子路由 → 平台路由用 `/xxx/*`;内部 state 切页 → 精确 path 即可 |
| 入口 Provider | 看 `main.tsx` 的 `<XxxProvider>` 包裹 | **必须迁移**(否则路由渲染时 context 为 null 白屏) |
| 全局 CSS | grep `html`/`body`/`:root`/`#root` | 记录所有需剥离/迁移的全局规则 |
| body 操作 | grep `document.body`、`document.documentElement` | classList.toggle/style 修改需改为模块根容器 ref |
| public 资源 | `ls public/` | 记录文件清单与代码引用位置(grep 文件名) |
| 内嵌资产 | grep `data:` | base64 data URI 无需处理 |
| 存储 key | grep `localStorage`/`sessionStorage` | key 必须带项目前缀,无前缀需加 |
| keyframes | grep `@keyframes` | 与全平台 CSS 比对命名唯一性 |
| React 版本 | `package.json` | 平台为 React 18.3 + @types/react 19,注意类型差异(见 §5.3) |
---
## 2. 目录规划与代码复制
```
ai-platform/
├── src/modules/<name>/ # 模块源码
│ ├── App.tsx # 入口(含 Provider 包裹 + CSS 引入 + 根容器)
│ ├── index.ts # moduleConfig 导出
│ ├── app/ | pages/ | ... # 源项目 src 业务代码(排除 main.tsx、__tests__)
│ └── styles/ | *.css # 源项目样式
└── public/mod-assets/<name>/ # 模块静态资源(禁止放 public/<name>/)
```
```bash
mkdir -p ai-platform/src/modules/<name> ai-platform/public/mod-assets/<name>
cp -R <源项目>/src/app ai-platform/src/modules/<name>/app
cp -R <源项目>/src/styles ai-platform/src/modules/<name>/styles
cp <源项目>/src/App.tsx ai-platform/src/modules/<name>/App.tsx
# 不要复制 main.tsx、__tests__、vite.config 等入口/测试文件
```
---
## 3. 静态资源迁移
1. `public/` 下资源全部复制到 `public/mod-assets/<name>/`;
2. grep 源码中所有相对路径引用(`src="xxx.svg"`、`href="xxx.md"`、`locateFile` 等),统一改为绝对路径 `/mod-assets/<name>/xxx`;
3. 验证:dev 下直接访问 `http://localhost:<port>/mod-assets/<name>/xxx` 返回 200;
4. build 后确认 `dist/mod-assets/<name>/` 存在。
> 为什么不用 `public/<name>/`:Vite 会把 public 目录原样拷入 dist,形成与模块路由同名的目录。完整故障链(2026-10 生产事故):
> 1. 首页卡片 `window.open('/<name>')` → nginx `try_files $uri /index.html` 的 `$uri` 命中该**目录**(非文件);
> 2. nginx 对目录请求自动 301 补斜杠(`/`),且 `port_in_redirect` 默认为 on,Location 变成 `https://域名:8901/<name>/`——**容器内端口被泄漏到浏览器地址栏**;
> 3. `:8901` 在外网不可达/无该虚拟主机 → 目录又无 index.html → 最终 403 或空白。
> 症状特征:只有"新增且带同名静态目录"的模块新页签打开异常(地址栏出现 `:8901`),老模块完全正常。
---
## 4. 样式隔离(核心,必须逐条执行)
### 4.1 根容器命名空间
模块 App 最外层包一个根容器,所有 CSS 选择器挂到它下面:
```tsx
// App.tsx
const rootRef = useRef<HTMLDivElement>(null)
return <div className="xxx-root" ref={rootRef}>...</div>
```
命名空间化有三种落地方式(按源项目 CSS 规模选择):
| 方式 | 适用 | 案例 |
|---|---|---|
| 全量脚本转换 | CSS 大/规则多(尤其 minified) | wuc-quotation:5 个 CSS 全部选择器加 `.wuc-root` 前缀 |
| 仅冲突类加前缀 | CSS 小、冲突少 | baode-web:20 处冲突选择器加 `.baode-root` |
| 原生自带命名空间 | 源项目已经做好隔离 | supplier-platform:变量与布局挂 `.hansong-app` |
**脚本转换要点**(已踩坑):
- `:root{--var}` → `.xxx-root{--var}`(CSS 变量迁到根容器)
- `body` → `.xxx-root`;`body.dark`/`body.collapsed` → `.xxx-root.dark` 等(主题/状态类改挂根容器)
- `body > #root > header` → `.xxx-root > header`(层级补偿规则改写)
- `html, body{overflow:hidden}` 等 → **直接删除**(会锁死平台整页滚动);视口锁定改由 `.xxx-root{height:100vh}` 承接
- `@media` 块内部规则**必须递归处理**(漏掉会造成窄屏规则逃逸成全局)
- `@keyframes`/`@font-face` 原样保留;字符串(data URI)不能破坏——需状态机解析而非正则替换
- 转换完必须校验:无残留 `body`/`:root`/`html`/`#root` 选择器、brace 平衡
### 4.2 三类冲突源都要检测(缺一不可)
```python
# 检测思路(对每个已存在模块 + 平台全局样式执行)
# 1. class 冲突:新模块 TSX className 集合 ∩ 双方 CSS 类名集合
# 2. ID 冲突:新模块 TSX 中的 id="xxx" ∩ 其它模块 CSS 中的 #xxx(双向)
# 3. 裸元素选择器:新模块 CSS 中 html/body/header/aside/nav/button/input 等无前缀选择器
```
> **ID 冲突是隐藏最深的坑**:`#nav` 特异性(1,0,0)碾压任何 `.wuc-root nav`(0,1,1)。wuc-quotation 上线后菜单被 supplier-platform 的 `#nav{display:flex}` 强制水平排列。修复方式是给**旧模块**的 ID 规则也加根容器前缀(`.hansong-app #nav`)。
### 4.3 运行时全局副作用清理
- `document.body.classList.toggle('dark'/'collapsed')` → `rootRef.current?.classList.toggle(...)`
- `document.body.style.overflow = ...`(如 LoginPage 的 useEffect)→ 模块内改为根容器样式或卸载时恢复
- 弹窗/Portal 挂载点若用 `document.body`,改为模块根容器内渲染
- `@media print` 中 `body{...}` 规则 → `.xxx-root{...}`,并放开视口锁定(`height:auto;overflow:visible`)
### 4.4 其它隔离项
- localStorage/sessionStorage key 带项目前缀(如 `wuchuan-quotation-v1`)
- `@keyframes` 命名全平台唯一(冲突时给新模块 keyframes 加前缀)
- 各模块 CSS 文件内不放 `@import` 全局重置(normalize/reset 一律禁止)
### 4.5 全局选择器门禁(check:styles)
`scripts/check-module-styles.mjs`(`npm run check:styles`)是样式隔离的零容忍门禁:以状态机逐字符解析扫描 `src/modules/**/*.css`(兼容数 MB 的 minified CSS 与 data URI 字符串),命中裸标签选择器(`button`/`table` 等)、裸 `:root`/伪类伪元素(`::-webkit-scrollbar` 等)、通配符 `*`、裸属性选择器、`@import` 引入 reset/normalize 即判违规,非零码退出。已接入 build 门禁(`npm run build` = `tsc -b && npm run check:styles && vite build`),日常可单独运行:
```bash
npm run check:styles # 退出码 0 = 模块 CSS 无全局选择器违规
```
---
## 5. 代码适配
### 5.1 入口与 Provider
```tsx
// App.tsx 末尾:平台路由直接渲染默认导出,Provider 职责从 main.tsx 移到这里
import { AppProvider } from './app/store'
export default function App() {
return (
<AppProvider>
<AppShell />
</AppProvider>
)
}
```
同时把源 `main.tsx` 的 CSS import 全部搬到模块 `App.tsx` 顶部(保持原有顺序)。
### 5.2 严格 tsconfig 适配(tsc -b 报错清单)
- `TS6133` 未使用变量/import → 删除(含解构中未使用的成员)
- `TS2554`:`useRef<T>()` → `useRef<T | undefined>(undefined)`(@types/react 19 要求初始值)
- 默认导入 `import React` 未使用 → 删除(react-jsx transform 无需)
### 5.3 其他常见点
- 事件监听/定时器在组件卸载时清理(模块可被随时切走)
- 弹窗内 `dangerouslySetInnerHTML` 注入的 HTML,其类名也要被命名空间 CSS 覆盖(确认前缀后仍能匹配)
- 内部 state 切页的项目保留原交互,不强行改造为 URL 路由
---
## 6. 平台注册(三件套 + 图标)
```ts
// 1. src/modules/<name>/index.ts
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: '<name>',
name: '模块中文名',
description: '一句话描述',
icon: 'Lucide图标名', // 如 FileSpreadsheet / Radar / Building2
path: '/<name>',
accentColor: '#7C6FFF', // 暗色强调色
accentColorLight: '#5747EF', // 亮色强调色
gradient: 'linear-gradient(135deg, ...)', // 暗色卡片渐变
gradientLight: 'linear-gradient(135deg, ...)', // 亮色卡片渐变
tags: ['标签1', '标签2'],
};
```
```ts
// 2. src/modules/registry.ts:import + modules 数组追加
// 3. src/App.tsx:模块级 React.lazy 动态导入 + 路由(ModuleTitle 负责页签标题,卸载恢复 'EIOSpace')
const XxxApp = lazy(() => import('@/modules/<name>/App'));
...
<Routes>
<Suspense fallback={<ModuleLoading />}>
<Route path="/<name>" element={<RequireAuth><ModuleTitle title="模块中文名"><XxxApp /></ModuleTitle></RequireAuth>} />
...
</Suspense>
</Routes>
// 4. src/pages/HomePage.tsx:ICON_MAP 增加图标(先在 lucide-react import 中补图标名)
```
> 模块入口必须用 `React.lazy` 动态导入(模块 CSS 随路由 chunk 按需加载),**静态 import 会把模块 CSS 打进主包,禁止**。
> 首页卡片点击已是 `window.open(mod.path, '_blank')` 新页签打开,无需额外处理。
---
## 7. 验证清单
**构建层**
- [ ] `npx tsc --noEmit` 通过
- [ ] `npm run build` 通过(注意 `tsc -b` 比 `tsc --noEmit` 更严,以 build 为准;已含 `check:styles` 门禁)
- [ ] `npm run check:styles` 退出码 0(模块 CSS 全局选择器零容忍门禁,见 §4.5,已接入 build)
- [ ] `dist/mod-assets/<name>/` 资源齐全
- [ ] **`ls dist/` 确认根目录下没有与模块路由同名的目录**(防端口泄漏,见 §3)
**浏览器层**(dev server + mock 登录)
```js
// 平台守卫只查 sessionStorage.userToken,浏览器验证先注入:
sessionStorage.setItem('userToken', 'mock-token-for-ui-check');
sessionStorage.setItem('userInfo', JSON.stringify({ name: '演示用户', userId: 'demo' }));
```
- [ ] `/<name>` 页面完整渲染(header/侧栏/内容区),控制台无 React 报错、无 404
- [ ] 页内交互可用(菜单切换、弹窗、主题切换)
- [ ] 新页签打开后浏览器标题为模块中文名
- [ ] 首页出现新模块卡片(图标、配色正确)
- [ ] 首页(未进入任何模块)Network 面板无任何模块级 CSS chunk
- [ ] 首次进入模块路由时按需加载对应 JS+CSS chunk(React.lazy 生效)
**回归层(改了旧模块 CSS 时必做)**
- [ ] 新模块关键布局 computed style 复核(如 nav 的 display)
- [ ] 被 CSS 影响的旧模块核心页面正常(如 supplier 顶栏导航)
- [ ] 平台首页/登录页样式未受污染
---
## 8. 部署注意(nginx)
- `nginx.conf` SPA 回退必须是 `try_files $uri /index.html;`——**禁止 `$uri/`**(目录命中 → 403 且不回退)
- **必须加两条重定向加固**(防止容器内端口泄漏到浏览器地址栏,2026-10 事故根因):
```nginx
server {
listen 8901;
...
port_in_redirect off; # 301 重定向的 Location 不带 8901 端口
absolute_redirect off; # 使用相对路径 Location,彻底避免泄漏 host/port
}
```
- 部署后用生产地址冒烟验证(新页签打开路径):
```bash
curl -sI https://ai-workshop.digiwincloud.com.cn/<name> | head -5
# 期望:HTTP 200(或 302 跳登录页)
# 异常信号:HTTP 301 且 Location 带 :8901 —— 即存在与路由同名的静态目录触发了目录重定向
```
- 模块静态资源引用用绝对路径 `/mod-assets/...`,与部署子路径无关
---
## 9. 历史踩坑速查表
| 案例 | 坑 | 修复 |
|---|---|---|
| baode-web ↔ supplier-platform | baode 自检页 `.page{max-width:1080px}` 污染 supplier 的 `section.page` | `.page`→`.checkpage` + 冲突类加 `.baode-root` 前缀 |
| supplier-platform | 源 tsconfig 宽松,`useRef<T>()` 在 @types/react 19 下报 TS2554 | `useRef<T \| undefined>(undefined)` |
| 全部模块 | dist 下与路由同名目录:早期 `try_files $uri/` 命中目录 403;去掉 `$uri/` 后 `$uri` 仍命中目录触发 301 补斜杠,`port_in_redirect` 默认 on 把容器端口 `:8901` 泄漏进浏览器地址栏,新页签跳到带端口地址后 403/空白 | 资源统一迁 `mod-assets/`;nginx 加 `port_in_redirect off; absolute_redirect off;` |
| wuc-quotation | 漏迁 `AppProvider` → 白屏 `ctx is null` | Provider 移入模块默认导出 |
| wuc-quotation | 001.css 7.8MB 内嵌 data URI + minified,正则替换会破坏资产 | 状态机解析转换,字符串原样保留 |
| wuc-quotation | `document.body.classList.toggle('dark')` 污染平台 body | 改挂 `.wuc-root` 根容器 ref |
| wuc-quotation | `@media` 内规则未递归前缀化(首版转换脚本 bug) | 递归处理 + 转换后自动校验 |
| wuc-quotation ↔ supplier-platform | `#nav` ID 特异性碾压类前缀,菜单被改 flex 水平 | 旧模块规则改 `.hansong-app #nav`;SOP 增加 ID 冲突检测 |
| jieya-ibp / welltrust-qap | sql.js wasm 路径、logo 相对路径失效 | 统一 `locateFile: () => '/mod-assets/<name>/...'` |
| 全部模块 | 模块 CSS 全局选择器(`:root`/`button`/`table`/`::-webkit-scrollbar`/`*`)跨模块污染 | 加模块根容器前缀 + `check:styles` 门禁(§4.5,已接入 build) |
+54 -2
View File
@@ -1,5 +1,5 @@
server {
listen 80;
listen 8901;
server_name localhost;
root /usr/share/nginx/html;
@@ -10,9 +10,61 @@ server {
gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript image/svg+xml;
gzip_min_length 256;
# 后端 API 反向代理(支持 SSE 长连接)
location /api/v1/ {
proxy_pass ${BACKEND_URL}/api/v1/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# SSE 支持
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 300s;
proxy_http_version 1.1;
proxy_set_header Connection "";
# 禁止浏览器缓存 API 响应
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
add_header Pragma "no-cache" always;
}
# 健康检查
location /health {
proxy_pass ${BACKEND_URL}/health;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# Bexell 排程 API 反向代理
location /bexapi/ {
proxy_pass https://ai-workshop.digiwincloud.com.cn/bexell-backend/api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 鼎捷云 IAM 登录服务反向代理(与 vite.config.ts 中 /iam-api 代理一致)
location /iam-api/ {
proxy_pass https://iam.digiwincloud.com.cn/;
proxy_set_header Host iam.digiwincloud.com.cn;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_ssl_server_name on;
# 禁止浏览器缓存 API 响应
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
add_header Pragma "no-cache" always;
}
# SPA 路由 fallback:所有非文件请求回退到 index.html
# 注意不能带 $uri/:dist 下存在与路由同名的静态资源目录(如 mod-assets/jieya-ibp),
# 若命中目录(无 index.html)会返回 403 导致 SPA 路由失效
location / {
try_files $uri $uri/ /index.html;
try_files $uri /index.html;
}
# 静态资源长缓存(Vite 构建产物带 hash)
+14
View File
@@ -14,10 +14,12 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.13",
"jsencrypt": "^3.5.4",
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.1",
"sql.js": "^1.14.2",
"tailwind-merge": "^2.6.0"
},
"devDependencies": {
@@ -1633,6 +1635,12 @@
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/jsencrypt": {
"version": "3.5.4",
"resolved": "https://registry.npmjs.org/jsencrypt/-/jsencrypt-3.5.4.tgz",
"integrity": "sha512-kNjfYEMNASxrDGsmcSQh/rUTmcoRfSUkxnAz+MMywM8jtGu+fFEZ3nJjHM58zscVnwR0fYmG9sGkTDjqUdpiwA==",
"license": "MIT"
},
"node_modules/json2mq": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/json2mq/-/json2mq-0.2.0.tgz",
@@ -3144,6 +3152,12 @@
"node": ">=0.10.0"
}
},
"node_modules/sql.js": {
"version": "1.14.2",
"resolved": "https://registry.npmmirror.com/sql.js/-/sql.js-1.14.2.tgz",
"integrity": "sha512-3ZGPovObMFrdw79zrUHbfdE/DLIsy8jdNdssmMSQuRAymedU6q84asPt0kgiqrdMYlPegDItiIMfmIXzZnYFcw==",
"license": "MIT"
},
"node_modules/string-convert": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/string-convert/-/string-convert-0.2.1.tgz",
+5 -2
View File
@@ -5,8 +5,9 @@
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview"
"build": "tsc -b && npm run check:styles && vite build",
"preview": "vite preview",
"check:styles": "node scripts/check-module-styles.mjs"
},
"dependencies": {
"@ant-design/icons": "^5.4.0",
@@ -15,10 +16,12 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.13",
"jsencrypt": "^3.5.4",
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.1",
"sql.js": "^1.14.2",
"tailwind-merge": "^2.6.0"
},
"devDependencies": {
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

@@ -0,0 +1,51 @@
# 重型装备内外套组件制造供货询价需求书
编号:RFQ-DEMO-2026-016 版本:A 日期:2026-10-16
**模拟客户需求,仅供DEMO。不是武汉武船实际订单;所有工程参数均为演示假设,不可据此生产。**
## 1. 项目与供需双方
采购方:华中装备工程有限公司(虚构)。拟询价承制方:武汉武船重型装备工程有限责任公司。
项目:重型装备伸缩支承内外套组件制造供货。数量:10套,每套内套1件、外套1件。交期:合同生效、预付款到账及技术资料确认后90日。
场景选择依据:客户提供的“213WS03-01(内套).pdf”“213WS03-02(外套).pdf”文件主题。由于本次无法取得可核对图像,未引用其具体尺寸、材质、公差、重量或实际用途。以下模拟结构和编号与原图区分。
## 2. 供货范围与边界
10套内外套组件(每套内套1件、外套1件),含采购、下料、成形、焊接、机加工、检测、防腐、包装运输及技术资料;不含主机、驱动装置及现场安装。
内部演示假设为焊接成形后机加工的套筒组件;原图可能采用不同结构或工艺,正式实施必须技术确认。
提供材料证明、关键尺寸检测记录、焊接与无损检测记录、出厂合格证及装箱清单。质量验收标准、焊缝等级、配合公差及表面防护要求由双方技术协议明确,不凭演示图替代。
## 3. 模拟图纸与参考物量
模拟内套图SIM-IS-01:筒体外径420mm,内径380mm,筒段长1200mm;法兰外径560mm、内径420mm、厚40mm;加强环外径480mm、内径420mm、厚30mm,每件内套2个。
模拟外套图SIM-OS-01:筒体外径540mm,内径500mm,筒段长1300mm;法兰外径680mm、内径540mm、厚50mm。
模拟钢材净重按圆环体积×密度7850kg/m³计算,每件重量四舍五入至0.01kg后乘10。加强环为每件2个。公式:π/4×(外径²−内径²)×长度×7.85×10⁻⁶(尺寸mm)。忽略孔槽及焊缝附加量,属于报价阶段几何估算;并非经原图确认的工程重量。
|参考物料号|物料|10套合计净用量|单位|来源|
|---|---|---:|---|---|
|M001|内套筒体 Q355B|2367.5|kg|SIM-IS-01 序1;236.75kg×10|
|M002|内套法兰 Q355B|338.4|kg|SIM-IS-01 序2;33.84kg×10|
|M003|内套加强环 Q355B|199.8|kg|SIM-IS-01 序3;19.98kg×10|
|M004|外套筒体 Q355B|3334.2|kg|SIM-OS-01 序1;333.42kg×10|
|M005|外套法兰 Q355B|526.5|kg|SIM-OS-01 序2;52.65kg×10|
|M006|导向衬套 铜合金|20|件|需求§3;2件×10|
|M007|密封组件|10|套|需求§3;1套×10|
|M008|配套紧固件|10|套|需求§3;1套×10|
说明:M001–M008为DEMO物料主数据映射编号,不能当作客户原图真实物料编码;外购物件规格为待澄清项。技术人员应确认实际ERP/PLM物料号。采购损耗由承制方另行核算,客户净用量不含损耗。
## 4. 图纸之外的补充需求
焊丝及焊剂由承制方承担,报价必须覆盖,不应因图纸BOM未列出而遗漏。演示参考用量160kg/项目,由技术人员人工补录并复核;不在自动解析的8项初始BOM中。
防腐材料及施工归入独立防腐费用,不重复加入物料表。密封与衬套的规格须在技术澄清环节确认。
## 5. 制造与检验要求
建议工艺路线:工艺深化→下料坡口→卷制组对→焊接→精加工→装配试配→检验→防腐包装。
焊接演示工作量480m,估算效率2m/工时;由生产部门复核,不能自动当作原图识别结果。其他工时由承制方工艺定额给出。
供应商到料不晚于第60天,预留后续制造与交付30天。任何技术或进度偏离应在报价前提出。
## 6. 报价响应与商务条款
请分别列示不含税单价、总价、税率、税额与含税总价,币种人民币。税率13%仅为DEMO参数,正式业务由财税确认。
预付款30%,工厂验收后发运前60%,到货验收后10%;质保12个月;报价有效期30天。
报价应说明供货边界、交期起算条件、技术偏离和价格有效期。未明确的技术条件应列入澄清表。
## 7. 内部演示数据的边界
本客户需求书不含供应商报价和企业利润底线。可上传JSON为了便于离线演示,额外包含内部参考单价、损耗与工艺估算,应作为演示种子包而非对外客户原始文件。
附件:模拟内套图.svg、模拟外套图.svg。图中模拟图号不得替代用户提供的原图号。
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1400" height="900" viewBox="0 0 1400 900"><defs><pattern id="h" width="9" height="9" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="9" stroke="#777"/></pattern><marker id="a" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8" fill="none" stroke="#111"/></marker></defs><rect x="30" y="30" width="1340" height="840" fill="white" stroke="#222" stroke-width="2"/><g font-family="Microsoft YaHei,Arial" fill="#222"><text x="65" y="85" font-size="25">内套组件 — 模拟机械图(仅供报价DEMO)</text><text x="65" y="119" font-size="17" fill="#bd4444">非附件复刻 · 尺寸、材质及结构均为假设 · 禁止作为生产依据</text><g stroke="#222" stroke-width="2" fill="none"><rect x="140" y="260" width="600" height="210"/><rect x="140" y="260" width="600" height="32" fill="url(#h)"/><rect x="140" y="438" width="600" height="32" fill="url(#h)"/><rect x="160" y="205" width="35" height="320" fill="url(#h)"/><rect x="650" y="225" width="30" height="280" fill="url(#h)"/><circle cx="1030" cy="365" r="145"/><circle cx="1030" cy="365" r="112"/><circle cx="1030" cy="365" r="90"/><path d="M100 365h690M1030 185v360M850 365h360" stroke-dasharray="12 6 3 6" stroke="#777"/><path d="M140 490v90M740 490v90M140 565h600"/><path d="M790 260h45M790 470h45M820 260v210"/><path d="M140 565h600" marker-start="url(#a)" marker-end="url(#a)"/><path d="M820 260v210" marker-start="url(#a)" marker-end="url(#a)"/></g><text x="370" y="552" font-size="20">筒段长 1200</text><text x="835" y="340" font-size="18">Φ420</text><text x="930" y="550" font-size="18">内径 Φ380 / 法兰 Φ560</text><text x="220" y="190" font-size="18">② 法兰</text><text x="370" y="245" font-size="18">① 筒体(剖视示意)</text><text x="620" y="195" font-size="18">③ 加强环</text><text x="65" y="625" font-size="18">技术说明(模拟):1. 材料暂定Q355B;2. 先成形焊接后机加工;3. 配合、公差、焊缝等级待技术协议。</text><text x="65" y="663" font-size="18">净重按模拟圆环体积估算(见需求书);孔槽未扣除,BOM须技术审核,图纸未含焊材。</text><path d="M30 710h1340M800 710v160M1100 710v160M800 765h570M800 820h570" stroke="#222" fill="none"/><text x="65" y="755" font-size="20">武汉武船重型装备工程有限责任公司 · AI报价平台</text><text x="65" y="793" font-size="16">场景参考:用户提供内套 / 外套附件主题,未核实原图工程参数</text><text x="65" y="832" font-size="16">净重、数量和材料号见《客户需求书》 §3;本图单位 mm,不按比例。</text><text x="825" y="746" font-size="23">内套组件</text><text x="1120" y="746" font-size="20">SIM-IS-01</text><text x="825" y="800" font-size="18">版本:A / 模拟</text><text x="1120" y="800" font-size="18">数量:10件</text><text x="825" y="855" font-size="18">2026-10-16</text><text x="1120" y="855" font-size="18">非生产图纸</text></g></svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1400" height="900" viewBox="0 0 1400 900"><defs><pattern id="h" width="9" height="9" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="9" stroke="#777"/></pattern><marker id="a" markerWidth="8" markerHeight="8" refX="4" refY="4" orient="auto-start-reverse"><path d="M0,0 L8,4 L0,8" fill="none" stroke="#111"/></marker></defs><rect x="30" y="30" width="1340" height="840" fill="white" stroke="#222" stroke-width="2"/><g font-family="Microsoft YaHei,Arial" fill="#222"><text x="65" y="85" font-size="25">外套组件 — 模拟机械图(仅供报价DEMO)</text><text x="65" y="119" font-size="17" fill="#bd4444">非附件复刻 · 尺寸、材质及结构均为假设 · 禁止作为生产依据</text><g stroke="#222" stroke-width="2" fill="none"><rect x="140" y="260" width="600" height="210"/><rect x="140" y="260" width="600" height="32" fill="url(#h)"/><rect x="140" y="438" width="600" height="32" fill="url(#h)"/><rect x="160" y="205" width="35" height="320" fill="url(#h)"/><rect x="650" y="225" width="30" height="280" fill="url(#h)"/><circle cx="1030" cy="365" r="145"/><circle cx="1030" cy="365" r="112"/><circle cx="1030" cy="365" r="90"/><path d="M100 365h690M1030 185v360M850 365h360" stroke-dasharray="12 6 3 6" stroke="#777"/><path d="M140 490v90M740 490v90M140 565h600"/><path d="M790 260h45M790 470h45M820 260v210"/><path d="M140 565h600" marker-start="url(#a)" marker-end="url(#a)"/><path d="M820 260v210" marker-start="url(#a)" marker-end="url(#a)"/></g><text x="370" y="552" font-size="20">筒段长 1300</text><text x="835" y="340" font-size="18">Φ540</text><text x="930" y="550" font-size="18">内径 Φ500 / 法兰 Φ680</text><text x="220" y="190" font-size="18">② 法兰</text><text x="370" y="245" font-size="18">① 筒体(剖视示意)</text><text x="620" y="195" font-size="18">③ 导向配合区</text><text x="65" y="625" font-size="18">技术说明(模拟):1. 材料暂定Q355B;2. 先成形焊接后机加工;3. 配合、公差、焊缝等级待技术协议。</text><text x="65" y="663" font-size="18">净重按模拟圆环体积估算(见需求书);孔槽未扣除,BOM须技术审核,图纸未含焊材。</text><path d="M30 710h1340M800 710v160M1100 710v160M800 765h570M800 820h570" stroke="#222" fill="none"/><text x="65" y="755" font-size="20">武汉武船重型装备工程有限责任公司 · AI报价平台</text><text x="65" y="793" font-size="16">场景参考:用户提供内套 / 外套附件主题,未核实原图工程参数</text><text x="65" y="832" font-size="16">净重、数量和材料号见《客户需求书》 §3;本图单位 mm,不按比例。</text><text x="825" y="746" font-size="23">外套组件</text><text x="1120" y="746" font-size="20">SIM-OS-01</text><text x="825" y="800" font-size="18">版本:A / 模拟</text><text x="1120" y="800" font-size="18">数量:10件</text><text x="825" y="855" font-size="18">2026-10-16</text><text x="1120" y="855" font-size="18">非生产图纸</text></g></svg>

After

Width:  |  Height:  |  Size: 3.0 KiB

+267
View File
@@ -0,0 +1,267 @@
#!/usr/bin/env node
/**
* 模块样式命名空间检查(门禁脚本)
*
* 平台规则:src/modules 下所有 .css 中选择器必须挂在模块根容器类(命名空间)下,
* 禁止全局作用选择器(裸标签 / :root / 通配符 / 裸伪类 / 裸属性选择器等)跨模块污染。
*
* 实现:状态机逐字符解析(模块内存在数 MB 的 minified CSS,含大量 data URI
* 字符串与花括号,不能依赖简单正则)。零依赖,Node >= 18。
*/
import { readdirSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const MODULES_DIR = path.join(ROOT, 'src', 'modules');
const MAX_LEN = 80;
/* ---------------------------------- 文件收集 ---------------------------------- */
function collectCssFiles(dir) {
const out = [];
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
} catch {
return out;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
out.push(...collectCssFiles(full));
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.css')) {
out.push(full);
}
}
return out;
}
/* --------------------------------- 选择器判定 --------------------------------- */
/**
* 判定单个选择器(已 trim)是否为全局作用选择器。
* 返回 null 表示合法(挂在类/ID 命名空间下),否则返回原因字符串。
*/
function classifySelector(sel) {
if (!sel || sel.startsWith('@')) return null;
// 裸伪类/伪元素::root、:focus-visible、::-webkit-scrollbar 等,等价于通配符
if (sel.startsWith(':')) {
if (/^:root(?![a-zA-Z0-9_-])/.test(sel)) return '裸 :root 选择器(全局作用)';
return '裸伪类/伪元素(等价于通配符,全局作用)';
}
if (sel.startsWith('*')) return '通配符 *(全局作用)';
if (sel.startsWith('[')) return '裸属性选择器(全局作用)';
// 裸标签:首 token 匹配 /^[a-zA-Z][a-zA-Z0-9-]*$/ 且不是 CSS 函数(后面紧跟 "(")
const m = sel.match(/^[a-zA-Z][a-zA-Z0-9-]*/);
if (m) {
const next = sel.charAt(m[0].length);
if (next !== '(') {
return `裸标签选择器「${m[0]}」(未挂在模块根容器下)`;
}
}
return null;
}
/**
* 按顶层逗号拆分选择器列表:括号 ( ) 与属性选择器 [ ] 内的逗号不拆分,
* 引号字符串内的逗号不拆分。
*/
function splitTopLevelCommas(s) {
const parts = [];
let cur = '';
let paren = 0;
let bracket = 0;
let quote = null;
let escaped = false;
for (const ch of s) {
if (quote) {
cur += ch;
if (escaped) escaped = false;
else if (ch === '\\') escaped = true;
else if (ch === quote) quote = null;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
cur += ch;
continue;
}
if (ch === '(') paren++;
else if (ch === ')') paren = Math.max(0, paren - 1);
else if (ch === '[') bracket++;
else if (ch === ']') bracket = Math.max(0, bracket - 1);
if (ch === ',' && paren === 0 && bracket === 0) {
parts.push(cur);
cur = '';
continue;
}
cur += ch;
}
parts.push(cur);
return parts;
}
function truncate(s) {
return s.length > MAX_LEN ? `${s.slice(0, MAX_LEN - 3)}...` : s;
}
/* --------------------------------- 状态机解析 --------------------------------- */
/**
* 逐字符解析 CSS 文本。
* - 跳过块注释与字符串内容(data URI 中的 { } ; ( ) 不影响结构);
* - 跟踪大括号深度与栈帧:'media'(@media/@supports 内继续扫描)、
* 'rule'(普通规则块,声明不扫描)、'skip'(@keyframes/@font-face 等块内不扫描);
* - prelude("{" 之前的文本)在扫描态下累积,用于选择器判定与 @import 检查。
*
* onRule(prelude, line) —— 每条普通规则回调;
* onImport(prelude, line) —— 每条顶层(或 @media 内)@import 回调。
*/
function parseCss(source, onRule, onImport) {
const stack = [];
let prelude = '';
let preludeLine = -1;
let line = 1;
let inComment = false;
let quote = null;
let escaped = false;
const scanMode = () => stack.length === 0 || stack[stack.length - 1] === 'media';
const resetPrelude = () => {
prelude = '';
preludeLine = -1;
};
for (let i = 0; i < source.length; i++) {
const ch = source[i];
if (ch === '\n') line++;
if (inComment) {
if (ch === '*' && source[i + 1] === '/') {
inComment = false;
i++;
}
continue;
}
if (quote) {
// 字符串内容原样跳过(不解析其中的 { } ; 等);
// 为支持 @import 目标检查,扫描态下仍原样记录进 prelude。
if (escaped) {
escaped = false;
} else if (ch === '\\') {
escaped = true;
} else if (ch === quote) {
quote = null;
}
if (scanMode()) prelude += ch;
continue;
}
if (ch === '"' || ch === "'") {
quote = ch;
if (scanMode()) {
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
prelude += ch;
}
continue;
}
if (ch === '/' && source[i + 1] === '*') {
inComment = true;
i++;
continue;
}
if (ch === '{') {
const trimmed = prelude.trim();
let frame;
if (scanMode() && trimmed.startsWith('@')) {
const m = trimmed.match(/^@([a-zA-Z0-9-]+)/);
const name = m ? m[1].toLowerCase() : '';
// @media / @supports 递归继续扫描内部规则;其余 at-rule 跳过块内选择器
frame = name === 'media' || name === 'supports' ? 'media' : 'skip';
} else if (scanMode()) {
if (trimmed) onRule(trimmed, preludeLine === -1 ? line : preludeLine);
frame = 'rule';
} else {
frame = 'skip';
}
stack.push(frame);
resetPrelude();
continue;
}
if (ch === '}') {
if (stack.length) stack.pop();
resetPrelude();
continue;
}
if (ch === ';') {
if (scanMode()) {
const trimmed = prelude.trim();
if (/^@import\b/.test(trimmed)) {
onImport(trimmed, preludeLine === -1 ? line : preludeLine);
}
}
resetPrelude();
continue;
}
if (scanMode()) {
if (preludeLine === -1 && /\S/.test(ch)) preludeLine = line;
prelude += ch;
}
}
}
/* ------------------------------------ 主流程 ----------------------------------- */
function main() {
const files = collectCssFiles(MODULES_DIR).sort();
const violations = [];
const addViolation = (rel, line, selector, reason) => {
violations.push(`[违规] ${rel}:${line} ${truncate(selector)} ${reason}`);
};
for (const file of files) {
const rel = path.relative(ROOT, file).split(path.sep).join('/');
const source = readFileSync(file, 'utf8');
parseCss(
source,
(prelude, line) => {
for (const part of splitTopLevelCommas(prelude)) {
const sel = part.trim();
const reason = classifySelector(sel);
if (reason) addViolation(rel, line, sel, reason);
}
},
(prelude, line) => {
if (/(^|[^a-z0-9])(reset|normalize)/i.test(prelude)) {
addViolation(rel, line, prelude, '@import 引入 reset/normalize 样式(全局污染)');
}
},
);
}
if (violations.length > 0) {
for (const v of violations) console.log(v);
const badFiles = new Set(violations.map((v) => v.split(' ')[0])).size;
console.log(
`[汇总] 模块样式命名空间检查失败:共 ${violations.length} 条违规,涉及 ${badFiles} 个文件(共扫描 ${files.length} 个文件)`,
);
process.exit(1);
}
console.log(`✓ 模块样式检查通过(扫描 ${files.length} 个文件)`);
process.exit(0);
}
main();
+66 -19
View File
@@ -1,30 +1,77 @@
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import HomePage from '@/pages/HomePage';
import SSOLogin from '@/pages/SSOLogin';
import AIMCockpit from '@/modules/ai-matching/pages/AIMCockpit';
import CostCockpit from '@/modules/cost-analysis/pages/CostCockpit';
import KnowledgeGraphHome from '@/modules/knowledge-graph/pages/KnowledgeGraphHome';
import SpaceCockpit from '@/modules/knowledge-graph/pages/SpaceCockpit';
import BomxReuseHome from '@/modules/bomx-reuse-analyzer/pages/BomxReuseHome';
import CostCockpitFull from '@/modules/order-cost-analysis/pages/CostCockpitFull';
import AIMCockpitFull from '@/modules/order-cost-analysis/pages/AIMCockpitFull';
import BexellSchedulingApp from '@/modules/bexell-scheduling-ai/App';
import SanruiAIDesignHome from '@/modules/sanrui-ai-design/pages/SanruiAIDesignHome';
import LoginPage from '@/pages/LoginPage';
import RequireAuth from '@/shared/components/RequireAuth';
import ModuleTitle from '@/shared/components/ModuleTitle';
const AIMCockpit = lazy(() => import('@/modules/ai-matching/pages/AIMCockpit'));
const CostCockpit = lazy(() => import('@/modules/cost-analysis/pages/CostCockpit'));
const KnowledgeGraphHome = lazy(() => import('@/modules/knowledge-graph/pages/KnowledgeGraphHome'));
const SpaceCockpit = lazy(() => import('@/modules/knowledge-graph/pages/SpaceCockpit'));
const BomxReuseHome = lazy(() => import('@/modules/bomx-reuse-analyzer/pages/BomxReuseHome'));
const CostCockpitFull = lazy(() => import('@/modules/order-cost-analysis/pages/CostCockpitFull'));
const AIMCockpitFull = lazy(() => import('@/modules/order-cost-analysis/pages/AIMCockpitFull'));
const BexellSchedulingApp = lazy(() => import('@/modules/bexell-scheduling-ai/App'));
const SanruiAIDesignHome = lazy(() => import('@/modules/sanrui-ai-design/pages/SanruiAIDesignHome'));
const JieyaIbpApp = lazy(() => import('@/modules/jieya-ibp/App'));
const WelltrustQapApp = lazy(() => import('@/modules/welltrust-qap/App'));
const BaodeWebApp = lazy(() => import('@/modules/baode-web/App'));
const SupplierPlatformApp = lazy(() => import('@/modules/supplier-platform/App'));
const WucQuotationApp = lazy(() => import('@/modules/wuc-quotation/App'));
function ModuleLoading() {
const spinnerStyle: React.CSSProperties = {
width: 44,
height: 44,
border: '3px solid rgba(0, 212, 255, 0.2)',
borderTopColor: '#00d4ff',
borderRadius: '50%',
animation: 'spin 1s linear infinite',
};
return (
<div
style={{
position: 'fixed',
inset: 0,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
gap: 18,
background: '#000a1e',
zIndex: 9999,
}}
>
<div style={spinnerStyle} />
<div style={{ color: '#00d4ff', fontSize: 14, letterSpacing: 2 }}>模块加载中…</div>
</div>
);
}
export default function App() {
return (
<Suspense fallback={<ModuleLoading />}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/login" element={<LoginPage />} />
<Route path="/sso-login" element={<SSOLogin />} />
<Route path="/ai-matching" element={<AIMCockpit />} />
<Route path="/cost-analysis" element={<CostCockpit />} />
<Route path="/knowledge-graph" element={<KnowledgeGraphHome />} />
<Route path="/knowledge-graph/space" element={<SpaceCockpit />} />
<Route path="/bomx-reuse-analyzer" element={<BomxReuseHome />} />
<Route path="/order-cost-analysis" element={<CostCockpitFull />} />
<Route path="/order-cost-analysis/aim" element={<AIMCockpitFull />} />
<Route path="/bexell-scheduling-ai/*" element={<BexellSchedulingApp />} />
<Route path="/sanrui-ai-design" element={<SanruiAIDesignHome />} />
<Route path="/" element={<RequireAuth><HomePage /></RequireAuth>} />
<Route path="/ai-matching" element={<RequireAuth><ModuleTitle title="AI+制造 智创空间"><AIMCockpit /></ModuleTitle></RequireAuth>} />
<Route path="/cost-analysis" element={<RequireAuth><ModuleTitle title="AI订单成本分析"><CostCockpit /></ModuleTitle></RequireAuth>} />
<Route path="/knowledge-graph" element={<RequireAuth><ModuleTitle title="采购域知识图谱"><KnowledgeGraphHome /></ModuleTitle></RequireAuth>} />
<Route path="/knowledge-graph/space" element={<RequireAuth><ModuleTitle title="采购域知识图谱"><SpaceCockpit /></ModuleTitle></RequireAuth>} />
<Route path="/bomx-reuse-analyzer" element={<RequireAuth><ModuleTitle title="企业级BOM标准化治理"><BomxReuseHome /></ModuleTitle></RequireAuth>} />
<Route path="/order-cost-analysis" element={<RequireAuth><ModuleTitle title="AI+成本智能分析平台"><CostCockpitFull /></ModuleTitle></RequireAuth>} />
<Route path="/order-cost-analysis/aim" element={<RequireAuth><ModuleTitle title="AI+成本智能分析平台"><AIMCockpitFull /></ModuleTitle></RequireAuth>} />
<Route path="/bexell-scheduling-ai/*" element={<RequireAuth><ModuleTitle title="试产排程评估及优化"><BexellSchedulingApp /></ModuleTitle></RequireAuth>} />
<Route path="/sanrui-ai-design" element={<RequireAuth><ModuleTitle title="AI设计标准化智能体"><SanruiAIDesignHome /></ModuleTitle></RequireAuth>} />
<Route path="/jieya-ibp" element={<RequireAuth><ModuleTitle title="销售订单履约控制塔"><JieyaIbpApp /></ModuleTitle></RequireAuth>} />
<Route path="/welltrust-qap" element={<RequireAuth><ModuleTitle title="品质异常预防工作台"><WelltrustQapApp /></ModuleTitle></RequireAuth>} />
<Route path="/baode-web" element={<RequireAuth><ModuleTitle title="需求评审多智能体"><BaodeWebApp /></ModuleTitle></RequireAuth>} />
<Route path="/supplier-platform" element={<RequireAuth><ModuleTitle title="供应商智能管控平台"><SupplierPlatformApp /></ModuleTitle></RequireAuth>} />
<Route path="/wuc-quotation" element={<RequireAuth><ModuleTitle title="武船AI智能报价平台"><WucQuotationApp /></ModuleTitle></RequireAuth>} />
</Routes>
</Suspense>
);
}
+5
View File
@@ -152,6 +152,11 @@
to { opacity: 1; transform: translateY(0); }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
@keyframes glow-pulse {
0%, 100% { box-shadow: 0 0 10px rgba(0,212,255,0.2); }
50% { box-shadow: 0 0 30px rgba(0,212,255,0.5); }
+36
View File
@@ -0,0 +1,36 @@
import "./styles.css";
import { useState } from "react";
import { Header } from "./components/Header";
import { HistoryPanel } from "./components/HistoryPanel";
import { OrchestrationCanvas } from "./components/OrchestrationCanvas";
import { RightPanel } from "./components/RightPanel";
import { SelfCheck } from "./components/SelfCheck";
import { useReviewRunner } from "./state/useReviewRunner";
const showCheck = typeof window !== "undefined" && window.location.search.includes("check=1");
function Cockpit() {
const runner = useReviewRunner();
const [historyOpen, setHistoryOpen] = useState(false);
return (
<div className="cockpit-root">
<Header onOpenHistory={() => setHistoryOpen(true)} />
<main className="cockpit">
<OrchestrationCanvas
nodes={runner.nodes}
floats={runner.floats}
floatFocus={runner.floatFocus}
scenario={runner.scenario}
ratingRevealed={runner.ratingRevealed}
/>
<RightPanel runner={runner} />
</main>
<HistoryPanel open={historyOpen} onClose={() => setHistoryOpen(false)} />
</div>
);
}
export default function App() {
// baode-root:模块样式命名空间根容器,避免通用类名(logo/btn/modal 等)污染其他模块
return <div className="baode-root">{showCheck ? <SelfCheck /> : <Cockpit />}</div>;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

@@ -0,0 +1,77 @@
import { useEffect } from "react";
import { bomLines, newBomAssumption, productMaster, steelCoils } from "../mock/bom";
import { yuan } from "../engine/format";
/** 新品 BOM 详细弹窗:展示 BL95A-58 多层 BOM(含下展层与失效件标识) */
export function BomModal({ open, onClose }: { open: boolean; onClose: () => void }) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
if (!open) return null;
const coilCost = steelCoils.reduce((s, c) => s + c.kgPerUnit * c.unitPrice, 0);
return (
<div className="modal-backdrop" onClick={onClose} role="presentation">
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label="新品 BOM 详细"
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<span>新品 BOM 详细 · {productMaster.itemName}</span>
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
✕
</button>
</div>
<dl className="kv-grid modal-kv">
<dt>品号</dt><dd>{productMaster.itemCode}</dd>
<dt>品名</dt><dd>{productMaster.itemName}</dd>
<dt>规格</dt><dd>{productMaster.spec}</dd>
<dt>品号类型</dt><dd>{productMaster.makeType}</dd>
<dt>工厂</dt><dd>{productMaster.plant}</dd>
<dt>图号</dt><dd>{productMaster.drawingNo}</dd>
<dt>BOM 日期</dt><dd>{productMaster.bomDate}</dd>
<dt>版次</dt><dd>{productMaster.revision}</dd>
</dl>
<table className="bom-table">
<thead>
<tr>
<th>序号</th>
<th>元件品号 / 品名</th>
<th>规格</th>
<th>用量</th>
<th>单价</th>
<th>总价</th>
<th>状态</th>
</tr>
</thead>
<tbody>
{bomLines.map((l) => (
<tr key={l.seq} className={l.level === 2 ? "lvl2" : l.status === "失效" ? "invalid" : ""}>
<td>{l.level === 2 ? "└" : l.seq}</td>
<td>
{l.itemName} <span className="sub">{l.itemCode}</span>
</td>
<td>{l.spec}</td>
<td>{l.level === 2 ? l.qtyDisplay : l.qtyPerUnit}</td>
<td>{l.unitPrice ? l.unitPrice.toFixed(2) : "—"}</td>
<td>{l.totalPrice ? l.totalPrice.toFixed(2) : "—"}</td>
<td>{l.status}</td>
</tr>
))}
</tbody>
</table>
<p className="modal-note">
钢卷用量汇总(复算口径):{steelCoils.map((c) => `${c.material} ${c.kgPerUnit} kg/台 × ${c.unitPrice} 元`).join(" + ")} ={" "}
<b>{yuan(coilCost)} 元/台</b>;{newBomAssumption.basis}。失效件 2220160034 仅做状态识别展示,不计用量与金额。
</p>
</div>
</div>
);
}
@@ -0,0 +1,22 @@
import type { EvidenceRow } from "../types";
/** 依据表(H7:每个结论都带依据表) */
export function EvidenceTable({ rows }: { rows: EvidenceRow[] }) {
return (
<table className="ev">
<tbody>
{rows.map((r, i) => (
<tr key={i}>
<td className="ev-label">{r.label}</td>
<td className="ev-value">{r.value}</td>
{r.verdict ? (
<td className={r.verdict === "通过" ? "ev-v pass" : "ev-v fail"}>{r.verdict}</td>
) : (
<td className="ev-v" />
)}
</tr>
))}
</tbody>
</table>
);
}
@@ -0,0 +1,28 @@
import { currentUser } from "../mock/user";
import logoUrl from "../assets/logo.png";
export function Header({ onOpenHistory }: { onOpenHistory: () => void }) {
return (
<header className="topbar">
<img className="logo" src={logoUrl} alt="宝得换热" width={212} height={40} />
<div className="topbar-title">
<strong>订单需求评审智能体</strong>
</div>
<div className="topbar-right">
<a
className="btn"
href="/mod-assets/baode-web/demo-text.zip"
download="演示文档.zip"
>
演示文档下载
</a>
<button type="button" className="btn" onClick={onOpenHistory}>
评审历史
</button>
<span className="user-chip">
{currentUser.name} · {currentUser.code}
</span>
</div>
</header>
);
}
@@ -0,0 +1,119 @@
import { useEffect, useState } from "react";
import type { ReviewRecord } from "../state/history";
import { getReviewRecord, listReviewRecords } from "../state/history";
import { EvidenceTable } from "./EvidenceTable";
/** 评审历史:已完成评审的清单与当次执行轨迹回看 */
function fmt(iso: string): string {
return new Date(iso).toLocaleString("zh-CN", { hour12: false });
}
function openReportHtml(html: string): void {
const url = URL.createObjectURL(new Blob([html], { type: "text/html;charset=utf-8" }));
window.open(url, "_blank");
setTimeout(() => URL.revokeObjectURL(url), 60_000);
}
export function HistoryPanel({ open, onClose }: { open: boolean; onClose: () => void }) {
const [records, setRecords] = useState<ReviewRecord[]>([]);
const [selected, setSelected] = useState<string | null>(null);
useEffect(() => {
if (open) {
setRecords(listReviewRecords());
setSelected(null);
}
}, [open]);
if (!open) return null;
const detail = selected ? getReviewRecord(selected) : null;
return (
<div className="hist-mask" role="dialog" aria-label="评审历史">
<div className="hist">
<div className="hist-head">
<span>{detail ? "执行详情" : "评审历史"}</span>
<button
type="button"
className="icon-btn"
onClick={detail ? () => setSelected(null) : onClose}
aria-label={detail ? "返回列表" : "关闭"}
>
{detail ? "←" : "✕"}
</button>
</div>
<div className="hist-body">
{detail ? (
<>
<dl className="kv-grid">
<dt>记录编号</dt><dd>{detail.id}</dd>
<dt>发起人</dt><dd>{detail.operator.name} · {detail.operator.code}</dd>
<dt>开始时间</dt><dd>{fmt(detail.startedAt)}</dd>
<dt>结束时间</dt><dd>{fmt(detail.finishedAt)}</dd>
<dt>来源文档</dt><dd>{detail.fileName}</dd>
<dt>需求</dt><dd>{detail.productType} {detail.quantity} 个 @ {detail.unitPrice} 元</dd>
<dt>可行性判定</dt><dd>{detail.feasibilityCategory}</dd>
<dt>评级记分</dt><dd>{detail.ratingTotal} 分</dd>
<dt>整体结论</dt><dd>{detail.overall}</dd>
<dt>订单 / 授信</dt><dd>{detail.orderNo ?? (detail.creditStarted ? "已发起临时授信" : "—")}</dd>
</dl>
<div className="todo-actions">
<button type="button" className="btn btn-primary" onClick={() => openReportHtml(detail.reportHtml)}>
打开当次评估报告
</button>
</div>
<h3 className="hist-sub">执行轨迹</h3>
<ol className="trace">
{detail.trace.map((t, i) => (
<li key={i}>
<div className="trace-head">
<span className="trace-time">{t.time}</span>
<span className="trace-agent">{t.agent}</span>
<strong>{t.title}</strong>
</div>
{t.note ? <p className="trace-note">{t.note}</p> : null}
{t.rows?.length ? <EvidenceTable rows={t.rows} /> : null}
</li>
))}
</ol>
</>
) : records.length === 0 ? (
<p className="chat-empty">暂无评审记录。上传需求文档发起评审后,完成的评审会自动归档在此。</p>
) : (
<table className="hist-table">
<thead>
<tr>
<th>记录编号</th>
<th>发起时间</th>
<th>发起人</th>
<th>需求</th>
<th>结论</th>
<th />
</tr>
</thead>
<tbody>
{records.map((r) => (
<tr key={r.id}>
<td>{r.id}</td>
<td>{fmt(r.startedAt)}</td>
<td>{r.operator.name}</td>
<td>{r.productType} {r.quantity} 个</td>
<td>
<span className={`badge ${r.orderNo ? "badge-ok" : "badge-fail"}`}>{r.overall}</span>
</td>
<td>
<button type="button" className="btn" onClick={() => setSelected(r.id)}>
查看
</button>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,31 @@
import type { Scenario } from "../mock/scenarios";
import { pct, yuan } from "../engine/format";
/** 订单毛利复算表:收入 / 钢卷成本 / 毛利 / 毛利率(无标题,直接可读) */
export function MarginCalcTable({ scenario }: { scenario: Scenario }) {
const m = scenario.margin;
const q = scenario.demand.parsed.quantity;
const p = scenario.demand.parsed.unitPrice;
return (
<table className="bom-table float-table">
<tbody>
<tr>
<td>收入</td>
<td>{q} × {yuan(p)} = {yuan(m.revenue)} 元</td>
</tr>
<tr>
<td>钢卷成本</td>
<td>{yuan(m.coilCostPerUnit)} 元/台 × {q} = {yuan(m.coilCostTotal)} 元</td>
</tr>
<tr>
<td>订单毛利</td>
<td>{yuan(m.revenue)} − {yuan(m.coilCostTotal)} = {yuan(m.grossProfit)} 元</td>
</tr>
<tr>
<td>订单毛利率</td>
<td>{yuan(m.grossProfit)} ÷ {yuan(m.revenue)} = {pct(m.grossMarginRate)}</td>
</tr>
</tbody>
</table>
);
}
@@ -0,0 +1,417 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import type { ReactNode } from "react";
import type { FloatCard, NodeId, NodeState } from "../state/types";
import { EvidenceTable } from "./EvidenceTable";
import { BomModal } from "./BomModal";
import { RndDetailModal } from "./RndDetailModal";
import { RatingDetailModal } from "./RatingDetailModal";
import { RatingScorePanels } from "./RatingScorePanels";
import { agentIntros } from "../mock/agents";
import type { Scenario } from "../mock/scenarios";
const LINK_LABELS: Record<"bom" | "cycle" | "invest", string> = {
bom: "查看新品 BOM 详细 →",
cycle: "周期详细 →",
invest: "投资详细 →",
};
const ICON_PATHS: Record<NodeId, string> = {
parse: "M14 3v4a1 1 0 0 0 1 1h4M7 3h7l5 5v11a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2zM9 13h6M9 17h6",
feasibility: "M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6l7-3zM9.5 12l2 2 3.5-4",
judge: "M12 4l6 8-6 8-6-8 6-8z",
rnd: "M9 3h6M10 3v5l-5 9a2 2 0 0 0 2 3h10a2 2 0 0 0 2-3l-5-9V3",
delivery: "M3 7h11v8H3zM14 10h4l3 3v2h-7M7 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3zM17 18a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z",
rating: "M12 4l2.4 4.9 5.4.8-3.9 3.8.9 5.4-4.8-2.5-4.8 2.5.9-5.4L4.2 9.7l5.4-.8L12 4z",
summary: "M9 5a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2M9 5a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2M9 5h6M9.5 14l2 2 3.5-4",
};
function NodeIcon({ id, onIntro, label }: { id: NodeId; onIntro: (id: NodeId) => void; label: string }) {
return (
<button
type="button"
className="node-icon"
title={`介绍:${label}`}
aria-label={`介绍:${label}`}
onClick={() => onIntro(id)}
>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden>
<path d={ICON_PATHS[id]} />
</svg>
</button>
);
}
const STATUS_ICON: Record<NodeState["status"], string> = {
排队: "○",
执行中: "◌",
等待填报: "◔",
待补全: "!",
已完成: "✓",
不通过: "✕",
跳过: "→",
};
const AGENT_IDS: NodeId[] = ["feasibility", "rnd", "delivery", "rating"];
function NodeCard(props: {
id: NodeId;
label: string;
note?: string;
state: NodeState;
kind?: "agent" | "control" | "decision";
onIntro: (id: NodeId) => void;
started: boolean;
}) {
const { id, label, note, state, kind = "agent", onIntro, started } = props;
const showStatus = state.status !== "排队" || (started && AGENT_IDS.includes(id));
return (
<div className={`fnode kind-${kind} s-${state.status}`} data-node={id}>
<div className="fnode-card">
<div className="fnode-top">
<NodeIcon id={id} label={label} onIntro={onIntro} />
<span className="fnode-dot" aria-hidden>{STATUS_ICON[state.status]}</span>
{showStatus ? <span className="fnode-status">{state.status}</span> : null}
</div>
<span className="fnode-label">
<span className="fnode-label-row">
{label}
{state.metric ? <span className="fnode-metric">{state.metric}</span> : null}
</span>
{kind === "agent" || note ? (
<em className="fnode-note">
{kind === "agent" ? <span className="agent-tag">智能体</span> : null}
{note ? <span>{note}</span> : null}
</em>
) : null}
</span>
</div>
</div>
);
}
interface BypassGeom {
left: number;
width: number;
leftDrop: number;
rightDrop: number;
}
function DecisionNode(props: { state: NodeState; onIntro: (id: NodeId) => void }) {
const { state, onIntro } = props;
const showStatus = state.status !== "排队";
return (
<div className={`fnode kind-decision s-${state.status}`} data-node="judge">
<button
type="button"
className="diamond"
title="介绍:标品判断"
aria-label="介绍:标品判断"
onClick={() => onIntro("judge")}
>
<div className="diamond-in">
<span className="diamond-label">标品判断</span>
<span className={state.metric ? "fnode-metric" : "fnode-metric muted"}>
{state.metric ?? "待判定"}
</span>
</div>
</button>
<div className="decision-status">
{showStatus ? <span className="fnode-status">{state.status}</span> : null}
</div>
</div>
);
}
export function OrchestrationCanvas(props: {
nodes: Record<NodeId, NodeState>;
floats: Partial<Record<NodeId, FloatCard>>;
floatFocus: NodeId | null;
scenario: Scenario | null;
ratingRevealed: number;
}) {
const { nodes, floats, floatFocus, scenario, ratingRevealed } = props;
const canvasRef = useRef<HTMLDivElement>(null);
const stageRefs = useRef<Partial<Record<string, HTMLDivElement | null>>>({});
const [bypass, setBypass] = useState<BypassGeom | null>(null);
const [mode, setMode] = useState<Partial<Record<NodeId, "open" | "closed">>>({});
const [bomOpen, setBomOpen] = useState(false);
const [rndDetail, setRndDetail] = useState<"cycle" | "invest" | null>(null);
const [ratingDetail, setRatingDetail] = useState<"margin" | null>(null);
const [panels, setPanels] = useState({ margin: false, credit: false });
const [intro, setIntro] = useState<NodeId | null>(null);
const toggleIntro = (id: NodeId) => setIntro((p) => (p === id ? null : id));
const allIds: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
const isFull = (id: NodeId) => {
if (!floats[id]) return false;
if (mode[id] === "open") return true;
if (mode[id] === "closed") return false;
const st = nodes[id].status;
return id === floatFocus || (st !== "排队" && st !== "跳过");
};
const spread = allIds.some((id) => floats[id] && isFull(id));
const started = allIds.some((id) => nodes[id].status !== "排队");
const active =
spread || intro !== null || allIds.some((id) => nodes[id].status !== "排队");
const measure = () => {
const j = stageRefs.current.judge;
const p = stageRefs.current.parallel;
if (!j || !p) return;
const jc = j.offsetLeft + j.offsetWidth / 2;
const pc = p.offsetLeft + p.offsetWidth / 2;
const next = {
left: jc,
width: Math.max(0, pc - jc),
leftDrop: Math.max(0, j.offsetTop - 18),
rightDrop: Math.max(0, p.offsetTop - 18),
};
setBypass((prev) =>
prev &&
prev.left === next.left &&
prev.width === next.width &&
prev.leftDrop === next.leftDrop &&
prev.rightDrop === next.rightDrop
? prev
: next,
);
};
useLayoutEffect(() => {
measure();
});
useEffect(() => {
const onResize = () => measure();
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
});
useEffect(() => {
const ORDER: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
const active =
ORDER.find((id) => nodes[id].status === "执行中" || nodes[id].status === "等待填报") ??
[...ORDER]
.reverse()
.find((id) =>
["已完成", "不通过", "待补全"].includes(nodes[id].status),
);
const stageKey = (id: NodeId) => (id === "delivery" || id === "rating" ? "parallel" : id);
const el = active ? stageRefs.current[stageKey(active)] : null;
const canvas = canvasRef.current;
if (!el || !canvas) return;
if (canvas.scrollWidth <= canvas.clientWidth + 4) {
if (canvas.scrollLeft !== 0) canvas.scrollTo({ left: 0, behavior: "smooth" });
return;
}
el.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
}, [nodes]);
const renderStage = (key: string, inner: ReactNode, floatIds: NodeId[]) => {
const chips = floatIds.filter((id) => floats[id] && !isFull(id));
const fulls = floatIds.filter((id) => floats[id] && isFull(id));
const introId = floatIds.find((id) => id === intro);
const introData = introId ? agentIntros[introId] : null;
return (
<div
className="stage"
key={key}
ref={(el) => {
stageRefs.current[key] = el;
}}
>
{inner}
<div className="chips">
{chips.map((id) => (
<button
key={id}
type="button"
className="chip-f"
title="展开依据卡"
onClick={() => setMode((p) => ({ ...p, [id]: "open" }))}
>
{floats[id]?.title}
{floats[id]?.verdict ? ` · ${floats[id]?.verdict}` : ""}
</button>
))}
</div>
{introData || fulls.length > 0 ? (
<div
className={`floats-col ${key === "parse" ? "align-left" : key === "summary" ? "align-right" : ""} ${fulls.includes("rating") || fulls.includes("delivery") ? "wide" : fulls.includes("rnd") ? "mid" : ""}`}
>
{introData ? (
<div className="float tone-info" role="dialog" aria-label={`${introData.title} 介绍`}>
<div className="float-head">
<span>{introData.title}</span>
<span className="float-verdict">介绍</span>
</div>
<p className="intro-desc">{introData.desc}</p>
<ul className="intro-points">
{introData.points.map((p, i) => (
<li key={i}>{p}</li>
))}
</ul>
<button type="button" className="chip-f float-close" onClick={() => setIntro(null)}>
关闭
</button>
</div>
) : null}
{fulls.map((id) => {
const f = floats[id];
if (!f) return null;
return (
<div className={`float tone-${f.tone}`} key={id} role="status">
<div className="float-head">
<span>{f.title}</span>
{f.verdict ? <span className="float-verdict">{f.verdict}</span> : null}
</div>
{id === "rating" && scenario ? (
<RatingScorePanels
scenario={scenario}
marginOpen={panels.margin}
creditOpen={panels.credit}
onToggleMargin={() => setPanels((p) => ({ ...p, margin: !p.margin }))}
onToggleCredit={() => setPanels((p) => ({ ...p, credit: !p.credit }))}
onMarginClick={() => setRatingDetail("margin")}
revealed={ratingRevealed}
/>
) : id === "rnd" && scenario && (f.links ?? []).includes("cycle") ? (
<>
<table className="bom-table float-table">
<thead>
<tr>
<th>评审项</th>
<th>标准</th>
<th>实际</th>
<th>判定</th>
</tr>
</thead>
<tbody>
{scenario.rnd.items.map((i) => (
<tr key={i.label}>
<td>{i.label}</td>
<td>{i.standard}</td>
<td>
{i.label === "毛利率" ? (
<button
type="button"
className="link-btn inline-link"
title="查看订单毛利计算逻辑"
onClick={() => setRatingDetail("margin")}
>
{i.actual}
</button>
) : (
i.actual
)}
</td>
<td className={i.pass ? "pass-cell" : "fail-cell"}>{i.pass ? "通过" : "不通过"}</td>
</tr>
))}
</tbody>
</table>
{f.note ? <p className="float-note">{f.note}</p> : null}
</>
) : (
<>
<EvidenceTable rows={f.rows} />
{f.note ? <p className="float-note">{f.note}</p> : null}
</>
)}
{(f.links ?? []).length > 0 ? (
<div className="link-row">
{(f.links ?? []).map((lk) => (
<button
key={lk}
type="button"
className="link-btn"
onClick={() => {
if (lk === "bom") setBomOpen(true);
else setRndDetail(lk);
}}
>
{LINK_LABELS[lk]}
</button>
))}
</div>
) : null}
<button
type="button"
className="chip-f float-close"
onClick={() => setMode((p) => ({ ...p, [id]: "closed" }))}
>
收起
</button>
</div>
);
})}
</div>
) : null}
</div>
);
};
return (
<section className="canvas-panel" aria-label="智能体编排与执行流程">
<div className="panel-head">
<h2>智能体编排与执行流程</h2>
<div className="legend" aria-hidden>
<span><i className="lg lg-run" />执行中</span>
<span><i className="lg lg-wait" />等待填报</span>
<span><i className="lg lg-todo" />待补全</span>
<span><i className="lg lg-ok" />已完成</span>
<span><i className="lg lg-fail" />不通过</span>
<span><i className="lg lg-skip" />跳过</span>
<span><i className="lg lg-agent" />智能体节点</span>
</div>
</div>
<div className="canvas" ref={canvasRef}>
<div
className="flow"
data-spread={spread ? "true" : "false"}
data-active={active ? "true" : "false"}
data-wide={
(floats.rating && isFull("rating")) ||
(floats.rnd && isFull("rnd")) ||
(floats.delivery && isFull("delivery"))
? "true"
: "false"
}
>
{bypass ? (
<div className="bypass-h" style={{ left: bypass.left, width: bypass.width }} aria-hidden>
<i className="stub stub-l" style={{ height: bypass.leftDrop }} />
<i className="stub stub-r" style={{ height: bypass.rightDrop }} />
<span>标品:跳过研发评审</span>
</div>
) : null}
{renderStage("parse", <NodeCard id="parse" kind="control" label="需求解析" note="总控" state={nodes.parse} onIntro={toggleIntro} started={started} />, ["parse"])}
<div className="conn-h" aria-hidden />
{renderStage("feasibility", <NodeCard id="feasibility" label="可行性智能体" state={nodes.feasibility} onIntro={toggleIntro} started={started} />, ["feasibility"])}
<div className="conn-h" aria-hidden />
{renderStage("judge", <DecisionNode state={nodes.judge} onIntro={toggleIntro} />, ["judge"])}
<div className="conn-h" aria-hidden>
<span>非标</span>
</div>
{renderStage("rnd", <NodeCard id="rnd" label="新品研发评估" note="仅非标进入" state={nodes.rnd} onIntro={toggleIntro} started={started} />, ["rnd"])}
<div className="conn-h" aria-hidden />
{renderStage(
"parallel",
<div
className={`pgroup ${nodes.delivery.status !== "排队" || nodes.rating.status !== "排队" ? "pg-active" : ""}`}
>
<span className="pgroup-badge">∥ 并行评审</span>
<NodeCard id="delivery" label="交期评审" state={nodes.delivery} onIntro={toggleIntro} started={started} />
<NodeCard id="rating" label="客户评级" state={nodes.rating} onIntro={toggleIntro} started={started} />
</div>,
["delivery", "rating"],
)}
<div className="conn-h" aria-hidden />
{renderStage("summary", <NodeCard id="summary" kind="control" label="汇总·订单" note="总控" state={nodes.summary} onIntro={toggleIntro} started={started} />, ["summary"])}
</div>
</div>
<BomModal open={bomOpen} onClose={() => setBomOpen(false)} />
<RndDetailModal section={rndDetail} scenario={scenario} onClose={() => setRndDetail(null)} />
<RatingDetailModal section={ratingDetail} scenario={scenario} onClose={() => setRatingDetail(null)} />
</section>
);
}
@@ -0,0 +1,36 @@
import { useEffect } from "react";
import type { Scenario } from "../mock/scenarios";
import { MarginCalcTable } from "./MarginCalcTable";
/** 评级明细弹窗:毛利达标四级链复算 / 信用达标数据拆解 */
export function RatingDetailModal(props: { section: "margin" | null; scenario: Scenario | null; onClose: () => void }) {
const { section, scenario, onClose } = props;
useEffect(() => {
if (!section) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [section, onClose]);
if (!section || !scenario) return null;
return (
<div className="modal-backdrop" onClick={onClose} role="presentation">
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label="订单毛利计算逻辑"
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<span>订单毛利计算逻辑</span>
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
✕
</button>
</div>
<MarginCalcTable scenario={scenario} />
</div>
</div>
);
}
@@ -0,0 +1,140 @@
import type { Scenario } from "../mock/scenarios";
import { pct, wan } from "../engine/format";
/** 信用达标拆解表(面板展开内容) */
function CreditBreakdownTable({ scenario }: { scenario: Scenario }) {
const cb = scenario.rating.creditBreakdown;
return (
<table className="bom-table float-table">
<tbody>
{cb.items.map((it, i) => (
<tr key={it.label}>
<td>{it.label}</td>
<td>{i === 0 ? wan(it.amount) : `− ${wan(it.amount)}`}</td>
<td>{it.source}</td>
</tr>
))}
<tr>
<td>信用可用余额</td>
<td>{wan(cb.available)}</td>
<td>{cb.pass ? "> 0 → 达标" : "≤ 0 → 不达标"}</td>
</tr>
</tbody>
</table>
);
}
/** 客户评级记分卡:毛利达标 / 信用达标为可展开面板(默认收起),其余记分项直接显示 */
export function RatingScorePanels(props: {
scenario: Scenario;
marginOpen: boolean;
creditOpen: boolean;
onToggleMargin: () => void;
onToggleCredit: () => void;
onMarginClick: () => void;
revealed: number;
}) {
const { scenario, marginOpen, creditOpen, onToggleMargin, onToggleCredit, onMarginClick, revealed } = props;
const r = scenario.rating;
const walked = r.marginChain.filter((c) => c.walked);
const hit = walked.find((c) => c.pass);
const marginItem = r.items[0];
const creditItem = r.items[1];
const THRESH = [1, 2, 4, 3];
const shown = (i: number) => revealed >= THRESH[i];
return (
<div className="score-panels">
<div className="score-panel">
<button type="button" className="score-panel-head" aria-expanded={marginOpen} onClick={onToggleMargin}>
<span className="sp-label">{marginItem.label}({marginItem.weight} 分)</span>
<span className="sp-value">
{shown(0)
? `本单毛利 ${pct(scenario.margin.grossMarginRate)}${hit && walked.length > 1 ? ` · 经 ${hit.step} 达标` : ""}`
: "计算中…"}
</span>
{shown(0) ? (
<span className={marginItem.pass ? "pass-cell" : "fail-cell"}>
{marginItem.pass ? "通过" : "不通过"} · {marginItem.score} 分
</span>
) : (
<span className="sp-muted">—</span>
)}
<span className="sp-caret" aria-hidden>{marginOpen ? "▲" : "▼"}</span>
</button>
{marginOpen ? (
<div className="score-panel-body">
<table className="bom-table float-table">
<thead>
<tr>
<th>层级</th>
<th>复算</th>
<th>对比行业指标 {walked[0] ? pct(walked[0].target) : ""}</th>
</tr>
</thead>
<tbody>
{walked.map((c) => (
<tr key={c.step}>
<td>{c.step} {c.label}</td>
<td>
{c.step === "①" ? (
<button type="button" className="link-btn inline-link" onClick={onMarginClick} title="查看订单毛利计算逻辑">
{pct(c.value)}
</button>
) : (
pct(c.value)
)}
</td>
<td className={c.pass ? "pass-cell" : "fail-cell"}>
{pct(c.value)} {c.pass ? "≥" : "<"} {pct(c.target)} → {c.pass ? "达标" : "不达标"}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : null}
</div>
<div className="score-panel">
<button type="button" className="score-panel-head" aria-expanded={creditOpen} onClick={onToggleCredit}>
<span className="sp-label">{creditItem.label}({creditItem.weight} 分)</span>
<span className="sp-value">
{shown(1)
? `可用余额 ${wan(r.creditBreakdown.available)} 万 ${r.creditBreakdown.pass ? "> 0" : "≤ 0"}`
: "计算中…"}
</span>
{shown(1) ? (
<span className={creditItem.pass ? "pass-cell" : "fail-cell"}>
{creditItem.pass ? "通过" : "不通过"} · {creditItem.score} 分
</span>
) : (
<span className="sp-muted">—</span>
)}
<span className="sp-caret" aria-hidden>{creditOpen ? "▲" : "▼"}</span>
</button>
{creditOpen ? (
<div className="score-panel-body">
<CreditBreakdownTable scenario={scenario} />
</div>
) : null}
</div>
<table className="ev">
<tbody>
{r.items.slice(2).map((i, idx) => (
<tr key={i.label}>
<td className="ev-label">{i.label}({i.weight} 分)</td>
<td className="ev-value">{shown(idx + 2) ? i.basis : "计算中…"}</td>
{shown(idx + 2) ? (
<td className={i.pass ? "ev-v pass" : "ev-v fail"}>{i.pass ? "通过" : "不通过"} · {i.score} 分</td>
) : (
<td className="ev-v sp-muted">—</td>
)}
</tr>
))}
</tbody>
</table>
{revealed >= 4 ? (
<p className="float-note">合计 {r.total} 分 · {r.pass ? "≥90 合格" : "<90 不合格"}</p>
) : null}
</div>
);
}
@@ -0,0 +1,272 @@
import { useEffect, useRef, useState } from "react";
import type { ChangeEvent, FormEvent } from "react";
import type { ReviewRunner } from "../state/useReviewRunner";
import type { Scenario } from "../mock/scenarios";
import type { ChatMsg, Todo } from "../state/types";
import { wan, yuan } from "../engine/format";
import { EvidenceTable } from "./EvidenceTable";
interface ChatCardViewProps {
msg: ChatMsg;
scenario: Scenario | null;
report: { fileName: string; html: string } | null;
onOpenReport: () => void;
}
function ChatCardView({ msg, scenario, report, onOpenReport }: ChatCardViewProps) {
if (msg.card.kind === "text") {
return <div className={msg.role === "user" ? "bubble user" : "bubble master"}>{msg.card.text}</div>;
}
if (!scenario) return null;
if (msg.card.kind === "summary") {
const s = scenario.summary;
return (
<div className="card master-card">
<div className="card-head">
<span>汇总结论</span>
<span className={s.order ? "badge badge-ok" : "badge badge-fail"}>{s.overall}</span>
</div>
<EvidenceTable rows={s.rows.map((r) => ({ label: r.agent, value: `${r.conclusion} · ${r.keyEvidence}` }))} />
{s.suggestions.length > 0 ? (
<ul className="card-list">
{s.suggestions.map((t, i) => (
<li key={i}>{t}</li>
))}
</ul>
) : null}
</div>
);
}
if (msg.card.kind === "order") {
const o = scenario.summary.order;
if (!o) return null;
return (
<div className="card master-card">
<div className="card-head">
<span>订单已生成</span>
<span className="badge badge-ok">{o.orderNo}</span>
</div>
<EvidenceTable
rows={[
{ label: "品项", value: o.itemSummary },
{ label: "金额", value: `${yuan(o.amount)} 元(${wan(o.amount)} 万)` },
{ label: "交期", value: o.deliveryDate },
]}
/>
</div>
);
}
if (msg.card.kind === "suggest") {
const g = scenario.summary.creditGap;
return (
<div className="card master-card tone-fail">
<div className="card-head">
<span>评审不通过 · 处理建议</span>
<span className="badge badge-fail">信用达标 0 分</span>
</div>
{g ? (
<EvidenceTable
rows={[
{ label: "精确缺口", value: `${wan(g.gap)} 万` },
{ label: "建议动作", value: `发起客户临时授信 ≥ ${wan(g.suggested)} 万(含缓冲)` },
{ label: "处理路径", value: g.path },
]}
/>
) : null}
</div>
);
}
if (msg.card.kind === "report") {
return (
<div className="card master-card">
<div className="card-head">
<span>需求评估报告已生成</span>
<span className="badge badge-ok">网页</span>
</div>
<p className="todo-prompt">{msg.card.fileName}</p>
<div className="todo-actions">
<button type="button" className="btn btn-primary" onClick={onOpenReport} disabled={!report}>
打开报告
</button>
</div>
</div>
);
}
return <div className="bubble master">临时授信流程已发起:授信审批 → 评级复跑 → 重新汇总。</div>;
}
function TodoCard({ todo, onResolve }: { todo: Todo; onResolve: (v: string | null) => void }) {
if (todo.kind === "followup") {
return (
<div className="card todo-card">
<div className="card-head">
<span>待办 · 补全追问</span>
<span className="badge badge-wait">等待响应</span>
</div>
<p className="todo-prompt">{todo.prompt}</p>
<div className="todo-actions">
{todo.options.map((o) => (
<button key={o} type="button" className="btn btn-opt" onClick={() => onResolve(o)}>
{o}
</button>
))}
</div>
</div>
);
}
if (todo.kind === "confirm") {
return (
<div className="card todo-card">
<div className="card-head">
<span>待办 · 确认评审结论</span>
<span className="badge badge-ok">评审通过</span>
</div>
<p className="todo-prompt">三个智能体结论齐备且依据透明,是否发起订单生成?</p>
<div className="todo-actions">
<button type="button" className="btn btn-primary" onClick={() => onResolve(null)}>
确认并发起订单
</button>
</div>
</div>
);
}
if (todo.kind === "next") {
return (
<div className="card todo-card">
<div className="card-head">
<span>待办 · 下一步</span>
<span className="badge badge-ok">评审收尾</span>
</div>
<p className="todo-prompt">本次评审已收尾并生成报告,接下来:</p>
<div className="todo-actions">
{todo.allowCreditRerun ? (
<button type="button" className="btn btn-primary" onClick={() => onResolve("credit-approved")}>
模拟授信审批通过 · 复跑评级
</button>
) : null}
<button type="button" className="btn btn-opt" onClick={() => onResolve("new-review")}>
发起新评审
</button>
</div>
</div>
);
}
return (
<div className="card todo-card tone-fail">
<div className="card-head">
<span>待办 · 异常处理</span>
<span className="badge badge-fail">评级不通过</span>
</div>
<p className="todo-prompt">信用项不达标,是否发起客户临时授信?</p>
<div className="todo-actions">
<button type="button" className="btn btn-danger" onClick={() => onResolve(null)}>
发起临时授信
</button>
</div>
</div>
);
}
export function RightPanel({ runner }: { runner: ReviewRunner }) {
const { demand, scenario, chat, todo, running } = runner;
const [text, setText] = useState("");
const chatRef = useRef<HTMLDivElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
useEffect(() => {
chatRef.current?.scrollTo({ top: chatRef.current.scrollHeight });
}, [chat.length, todo]);
const submit = (e: FormEvent) => {
e.preventDefault();
runner.sendText(text);
setText("");
};
const onFile = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = "";
if (file) void runner.uploadFile(file);
};
const openReport = () => {
const r = runner.report;
if (!r) return;
const url = URL.createObjectURL(new Blob([r.html], { type: "text/html;charset=utf-8" }));
window.open(url, "_blank");
setTimeout(() => URL.revokeObjectURL(url), 60_000);
};
return (
<aside className="right" aria-label="需求评审">
<div className="panel-head">
<h2>需求评审</h2>
</div>
{demand ? (
<div className="demand-card">
<div className="card-head">
<span>当前需求卡</span>
<span className={demand.missingFields.length === 0 ? "badge badge-ok" : "badge badge-wait"}>
{demand.missingFields.length > 0 ? "待补全" : "检查通过"}
</span>
</div>
<dl className="kv-grid">
<dt>客户</dt><dd>{demand.customerCode}</dd>
<dt>行业</dt><dd>{demand.parsed.industry ?? "缺失"}</dd>
<dt>产品类型</dt><dd>{demand.parsed.productType}</dd>
<dt>数量 / 单价</dt><dd>{demand.parsed.quantity} 个 / {yuan(demand.parsed.unitPrice)} 元</dd>
<dt>交期</dt><dd>{demand.parsed.deliveryDate}</dd>
<dt>钢卷材质</dt><dd>{demand.parsed.coilMaterial}</dd>
</dl>
</div>
) : (
<div className="demand-card demand-empty">
{running ? (
<>
<strong>正在解析需求文档…</strong>
<span>提取字段并做完整性检查,完成后在此显示需求卡</span>
</>
) : (
<>
<strong>尚未载入客户需求</strong>
<span>上传 Word / 文本需求文档开始评审</span>
</>
)}
</div>
)}
<div className="chat" ref={chatRef} aria-live="polite">
{chat.length === 0 ? (
<p className="chat-empty">上传需求文档或输入客户需求,主智能体将在此给出解析、追问、汇总与订单等关键反馈。</p>
) : (
chat.map((m) => (
<ChatCardView key={m.id} msg={m} scenario={scenario} report={runner.report} onOpenReport={openReport} />
))
)}
{todo ? <TodoCard todo={todo} onResolve={runner.resolveTodo} /> : null}
</div>
<form className="composer" onSubmit={submit}>
<input ref={fileRef} type="file" accept=".docx,.txt,.doc,.pdf" hidden onChange={onFile} />
<button
type="button"
className="icon-btn"
aria-label="上传需求文档并启动评审"
onClick={() => fileRef.current?.click()}
disabled={running}
>
<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden>
<path d="M12 16V4m0 0 4 4m-4-4-4 4" strokeLinecap="round" strokeLinejoin="round" />
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" strokeLinecap="round" />
</svg>
</button>
<input
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="输入客户需求,或点击左侧图标上传需求文档…"
aria-label="输入客户需求"
/>
<button type="submit" className="btn btn-primary" disabled={!text.trim()}>
发送
</button>
</form>
</aside>
);
}
@@ -0,0 +1,89 @@
import { useEffect } from "react";
import type { Scenario } from "../mock/scenarios";
import { RND_INVEST_ITEMS, RND_INVEST_TOTAL } from "../engine/filing";
import { yuan } from "../engine/format";
/** 研发评审详细弹窗:周期拆解 / 投资与回收期复算(按场景动态推导) */
export function RndDetailModal(props: {
section: "cycle" | "invest" | null;
scenario: Scenario | null;
onClose: () => void;
}) {
const { section, scenario, onClose } = props;
useEffect(() => {
if (!section) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [section, onClose]);
if (!section || !scenario) return null;
const f = scenario.filing;
return (
<div className="modal-backdrop" onClick={onClose} role="presentation">
<div
className="modal"
role="dialog"
aria-modal="true"
aria-label={section === "cycle" ? "周期详细" : "投资详细"}
onClick={(e) => e.stopPropagation()}
>
<div className="modal-head">
<span>{section === "cycle" ? "周期详细 · 模具 / 项目周期拆解" : "投资详细 · 投资回收期复算"}</span>
<button type="button" className="icon-btn" onClick={onClose} aria-label="关闭">
✕
</button>
</div>
{section === "cycle" ? (
<>
<h4 className="detail-title">模具周期 · 标准 ≤3 天 · 实际 {f.values[0]}</h4>
<table className="bom-table">
<thead>
<tr><th>阶段</th><th>天数</th></tr>
</thead>
<tbody>
{f.moldSteps.map((s) => (
<tr key={s.name}><td>{s.name}</td><td>{s.days} 天</td></tr>
))}
</tbody>
</table>
<h4 className="detail-title">项目周期 · 标准 ≤10 天 · 实际 {f.values[1]}</h4>
<table className="bom-table">
<thead>
<tr><th>阶段</th><th>天数</th></tr>
</thead>
<tbody>
{f.projectSteps.map((s) => (
<tr key={s.name}><td>{s.name}</td><td>{s.days} 天</td></tr>
))}
</tbody>
</table>
</>
) : (
<>
<h4 className="detail-title">投入构成 · 合计 {yuan(RND_INVEST_TOTAL)} 元</h4>
<table className="bom-table">
<thead>
<tr><th>项目</th><th>金额(元)</th></tr>
</thead>
<tbody>
{RND_INVEST_ITEMS.map((s) => (
<tr key={s.name}><td>{s.name}</td><td>{yuan(s.amount)}</td></tr>
))}
<tr><td>合计</td><td>{yuan(RND_INVEST_TOTAL)}</td></tr>
</tbody>
</table>
<h4 className="detail-title">回收期复算 · 标准 ≤1 年 · 实际 {f.paybackLabel}</h4>
<table className="bom-table">
<tbody>
<tr><td>本单毛利</td><td>{yuan(scenario.margin.grossProfit)} 元</td></tr>
<tr><td>复算口径</td><td>{f.investCalc}</td></tr>
</tbody>
</table>
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,31 @@
import { scenarios } from "../mock/scenarios";
import { yuan, wan } from "../engine/format";
/** 数据自检页(?check=1):核对 mock 复算关键数字 */
export function SelfCheck() {
return (
<div className="checkpage">
<h1>订单需求评审智能体 · Mock 数据自检</h1>
<p className="sub">数据字典对齐规格第 5 章;关键数字由规则引擎实时复算。</p>
{scenarios.map((s) => (
<section key={s.demand.id}>
<h2>需求 {s.demand.id} · {s.demand.label}</h2>
<table>
<tbody>
<tr><th>当期需求金额</th><td className="num">{yuan(s.margin.revenue)} 元({wan(s.margin.revenue)} 万)</td></tr>
<tr><th>可行性判定</th><td>{s.feasibility.category}({s.feasibility.routeLabel})</td></tr>
<tr><th>单台钢卷成本</th><td className="num">{yuan(s.coilCostPerUnit)} 元</td></tr>
<tr><th>毛利率</th><td className="num">{(s.margin.grossMarginRate * 100).toFixed(0)}%</td></tr>
<tr><th>研发评审</th><td className={s.rnd.pass ? "pass" : "fail"}>{s.rnd.pass ? "通过" : "不通过"}</td></tr>
<tr><th>客户评级记分</th><td className={s.rating.pass ? "pass" : "fail"}>{s.rating.total} 分</td></tr>
<tr><th>主智能体结论</th><td>{s.summary.overall}{s.summary.order ? ` · ${s.summary.order.orderNo}` : ""}</td></tr>
{s.creditGap ? (
<tr><th>临时授信建议</th><td className="num">缺口 {wan(s.creditGap.gap)} 万 · 建议 ≥ {wan(s.creditGap.suggested)} 万</td></tr>
) : null}
</tbody>
</table>
</section>
))}
</div>
);
}
+131
View File
@@ -0,0 +1,131 @@
import type { Demand, IndustryCode } from "../types";
import { customer } from "../mock/customer";
/** 上传文档解析:.docx 解包正文 / .txt 直读;字段口径对齐规格 5.2 */
export async function extractDocumentText(file: File): Promise<string> {
const name = file.name.toLowerCase();
if (name.endsWith(".txt") || name.endsWith(".md")) return file.text();
if (name.endsWith(".docx")) return extractDocxText(await file.arrayBuffer());
if (name.endsWith(".doc")) throw new Error("旧版 .doc 格式无法在线解析,请在 Word 中另存为 .docx 后重新上传。");
if (name.endsWith(".pdf")) throw new Error("PDF 解析通道暂未接入,请上传同一需求的 Word(.docx)或文本版本。");
throw new Error(`不支持的文件格式(${file.name}),当前支持 .docx / .txt。`);
}
async function extractDocxText(buffer: ArrayBuffer): Promise<string> {
const view = new DataView(buffer);
let eocd = -1;
for (let i = buffer.byteLength - 22; i >= 0; i--) {
if (view.getUint32(i, true) === 0x06054b50) {
eocd = i;
break;
}
}
if (eocd < 0) throw new Error("需求文档已损坏或不是有效的 .docx 文件,请重新导出后上传。");
const entries = view.getUint16(eocd + 10, true);
let offset = view.getUint32(eocd + 16, true);
for (let n = 0; n < entries; n++) {
if (view.getUint32(offset, true) !== 0x02014b50) break;
const method = view.getUint16(offset + 10, true);
const compSize = view.getUint32(offset + 20, true);
const nameLen = view.getUint16(offset + 28, true);
const extraLen = view.getUint16(offset + 30, true);
const commentLen = view.getUint16(offset + 32, true);
const localOffset = view.getUint32(offset + 42, true);
const entryName = new TextDecoder().decode(new Uint8Array(buffer, offset + 46, nameLen));
if (entryName === "word/document.xml") {
const lNameLen = view.getUint16(localOffset + 26, true);
const lExtraLen = view.getUint16(localOffset + 28, true);
const start = localOffset + 30 + lNameLen + lExtraLen;
const raw = new Uint8Array(buffer, start, compSize);
const xml = new TextDecoder().decode(method === 0 ? raw : await inflateRaw(raw));
return xmlToText(xml);
}
offset += 46 + nameLen + extraLen + commentLen;
}
throw new Error("未能从需求文档中读取正文,请确认其为 Word .docx 文件。");
}
async function inflateRaw(raw: Uint8Array): Promise<Uint8Array> {
const copy = new Uint8Array(raw);
const stream = new Blob([copy]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
function xmlToText(xml: string): string {
return xml
.replace(/<\/w:p>/g, "\n")
.replace(/<w:tab[^>]*>/g, "\t")
.replace(/<w:br[^>]*>/g, "\n")
.replace(/<[^>]+>/g, "")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
.replace(/&amp;/g, "&")
.trim();
}
export type ParseResult = { ok: true; demand: Demand } | { ok: false; reasons: string[] };
const INDUSTRIES: IndustryCode[] = ["CDU", "储能", "其他"];
function pick(text: string, re: RegExp): string | null {
const m = text.match(re);
return m ? m[1].trim() : null;
}
export function parseDemandDocument(text: string, fileName: string): ParseResult {
const reasons: string[] = [];
const code = pick(text, /客户(?:代码|编号)[::]\s*([A-Za-z0-9-]+)/);
if (!code) reasons.push("缺少「客户代码」");
else if (code !== customer.code) reasons.push(`客户 ${code} 不在客户主数据中(当前仅支持 ${customer.code})`);
const productType = pick(text, /产品(?:类型|名称)[::]\s*([^\n,,;;]+)/);
if (!productType) reasons.push("缺少「产品类型」");
const quantityRaw = pick(text, /(?:需求)?数量[::]\s*([0-9,]+)/);
const quantity = quantityRaw ? Number(quantityRaw.replace(/,/g, "")) : NaN;
if (!quantityRaw || !Number.isFinite(quantity) || quantity <= 0) reasons.push("缺少有效的「数量」");
const priceRaw = pick(text, /单价[::]\s*([0-9,]+)/);
const unitPrice = priceRaw ? Number(priceRaw.replace(/,/g, "")) : NaN;
if (!priceRaw || !Number.isFinite(unitPrice) || unitPrice <= 0) reasons.push("缺少有效的「单价」");
const coilMaterial = pick(text, /钢卷(?:材质)?[::]\s*([A-Za-z0-9]+)/);
if (!coilMaterial) reasons.push("缺少「钢卷材质」");
const dateMatch = text.match(/(?:交期|交付日期|交货日期)[::]\s*(\d{4})\s*[-年/.]\s*(\d{1,2})\s*[-月/.]\s*(\d{1,2})/);
if (!dateMatch) reasons.push("缺少有效的「交期」");
const deliveryDate = dateMatch
? `${dateMatch[1]}-${dateMatch[2].padStart(2, "0")}-${dateMatch[3].padStart(2, "0")}`
: "";
if (reasons.length > 0 || !productType || !coilMaterial) return { ok: false, reasons };
const industryRaw = pick(text, new RegExp(`行业[::]\\s*(${INDUSTRIES.join("|")})`));
const industry = (industryRaw as IndustryCode | null) ?? null;
return {
ok: true,
demand: {
id: fileName,
label: `${productType} · ${quantity} 个`,
customerCode: code as string,
document: { fileName, fileType: fileName.toLowerCase().endsWith(".txt") ? "txt" : "docx" },
parsed: {
industry,
productType,
quantity,
unitPrice,
deliveryDate,
coilMaterial,
},
missingFields: industry ? [] : ["industry"],
followUp: industry
? null
: { field: "industry", prompt: "需求文档缺少「行业」字段,请补全:", options: INDUSTRIES },
provenance: "上传文档解析",
},
};
}
+76
View File
@@ -0,0 +1,76 @@
import { yuan } from "./format";
/** 研发填报动态推导(规格 V1.3):模具/项目周期按数量,回收期按本单毛利额(假设年 1 单) */
export const RND_INVEST_TOTAL = 112_000;
export const RND_INVEST_ITEMS = [
{ name: "模具投入", amount: 80_000 },
{ name: "工装投入", amount: 20_000 },
{ name: "试产费用", amount: 12_000 },
];
export interface FilingValues {
moldDays: number;
projectDays: number;
paybackMonths: number;
paybackLabel: string;
paybackPass: boolean;
moldSteps: Array<{ name: string; days: number }>;
projectSteps: Array<{ name: string; days: number }>;
investCalc: string;
values: [string, string, string];
}
export function deriveFiling(quantity: number, grossProfit: number): FilingValues {
const moldDays = quantity <= 200 ? 2 : 3;
const projectDays = quantity <= 200 ? 8 : 10;
const moldSteps =
moldDays === 2
? [
{ name: "模具设计", days: 0.5 },
{ name: "CNC 加工", days: 1 },
{ name: "试模确认", days: 0.5 },
]
: [
{ name: "模具设计", days: 0.5 },
{ name: "CNC 加工", days: 1.5 },
{ name: "试模确认", days: 1 },
];
const projectSteps =
projectDays === 8
? [
{ name: "工艺与工装准备", days: 2 },
{ name: "316L 钢卷采购", days: 2 },
{ name: "冲压 + 铜钎焊生产", days: 3 },
{ name: "检验入库", days: 1 },
]
: [
{ name: "工艺与工装准备", days: 2 },
{ name: "316L 钢卷采购", days: 2 },
{ name: "冲压 + 铜钎焊生产(批量排产)", days: 5 },
{ name: "检验入库", days: 1 },
];
const paybackMonths = (RND_INVEST_TOTAL / grossProfit) * 12;
const paybackPass = paybackMonths <= 12;
const paybackLabel = !paybackPass
? `${(paybackMonths / 12).toFixed(1)} 年`
: paybackMonths < 1
? "约 1 个月"
: Math.abs(paybackMonths - 6) < 0.05
? "半年"
: `${Math.round(paybackMonths)} 个月`;
const profitWan = (grossProfit / 10_000).toLocaleString("zh-CN", { maximumFractionDigits: 1 });
const investCalc = paybackPass
? `投入 ${yuan(RND_INVEST_TOTAL)} 元 < 本单毛利 ${profitWan} 万,本单周期内全额回收(假设年 1 单)→ 投资回收期 ${paybackLabel}`
: `投入 ${yuan(RND_INVEST_TOTAL)} 元 > 本单毛利 ${profitWan} 万,一年内无法回收 → 投资回收期 ${paybackLabel}(不满足 ≤1 年)`;
return {
moldDays,
projectDays,
paybackMonths,
paybackLabel,
paybackPass,
moldSteps,
projectSteps,
investCalc,
values: [`${moldDays} 天`, `${projectDays} 天`, paybackLabel],
};
}
+10
View File
@@ -0,0 +1,10 @@
/** 展示格式化:金额统一存元,展示时转千分位 / 万 */
export function yuan(n: number): string {
return n.toLocaleString("zh-CN");
}
export function wan(n: number): string {
return (n / 10_000).toLocaleString("zh-CN", { maximumFractionDigits: 2 });
}
export function pct(rate: number, digits = 0): string {
return `${(rate * 100).toFixed(digits)}%`;
}
+154
View File
@@ -0,0 +1,154 @@
import type { EvidenceRow } from "../types";
import type { Scenario } from "../mock/scenarios";
import { pct, wan, yuan } from "./format";
/** 流程收尾自动出具的《需求评估报告》:自包含 HTML 网页,新标签页打开 */
export type ReviewOutcome = "order" | "credit";
const pad = (n: number) => `${n}`.padStart(2, "0");
export function reportFileName(s: Scenario, when: Date = new Date()): string {
const p = s.demand.parsed;
const stamp = `${when.getFullYear()}${pad(when.getMonth() + 1)}${pad(when.getDate())}-${pad(when.getHours())}${pad(when.getMinutes())}`;
return `需求评估报告-${p.productType}-${p.quantity}个-${stamp}.html`;
}
function esc(t: string): string {
return t.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function evidenceRows(rows: EvidenceRow[]): string {
return rows
.map(
(r) =>
`<tr><td class="k">${esc(r.label)}</td><td>${esc(r.value)}</td><td class="v ${r.verdict === "通过" ? "pass" : r.verdict === "不通过" ? "fail" : ""}">${r.verdict ? esc(r.verdict) : ""}</td></tr>`,
)
.join("");
}
const CSS = `
* { box-sizing: border-box; }
body { margin: 0; background: #f4f6fb; color: #1e293b; font: 14px/1.65 -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif; }
.wrap { max-width: 980px; margin: 0 auto; padding: 32px 20px 64px; }
.hero { background: linear-gradient(135deg, #0b2a6b 0%, #2563eb 62%, #3b82f6 100%); color: #fff; border-radius: 16px; padding: 28px 30px; box-shadow: 0 12px 32px rgba(37, 99, 235, .25); }
.hero .eyebrow { letter-spacing: .18em; font-size: 11px; opacity: .82; }
.hero h1 { margin: 6px 0 10px; font-size: 26px; letter-spacing: .02em; }
.hero .meta { display: flex; flex-wrap: wrap; gap: 8px 18px; font-size: 12px; opacity: .92; }
.banner { margin: 18px 0 0; border-radius: 12px; padding: 14px 18px; font-size: 15px; font-weight: 700; }
.banner.ok { background: #f0fdf4; color: #15803d; border: 1px solid #bbf7d0; }
.banner.fail { background: #fef2f2; color: #b91c1c; border: 1px solid #fecaca; }
.card { background: #fff; border: 1px solid #e2e8f0; border-radius: 14px; padding: 18px 20px; margin-top: 16px; box-shadow: 0 1px 2px rgba(15, 23, 42, .05), 0 8px 24px rgba(15, 23, 42, .06); }
.card h2 { margin: 0 0 10px; font-size: 15px; color: #0b2a6b; border-left: 4px solid #2563eb; padding-left: 10px; }
.lead { margin: 4px 0 10px; font-size: 13px; color: #475569; }
.grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 10px 18px; margin: 0; font-size: 13px; }
.grid dt { color: #64748b; font-size: 12px; }
.grid dd { margin: 2px 0 0; font-weight: 600; font-variant-numeric: tabular-nums; }
table { width: 100%; border-collapse: collapse; font-size: 13px; }
td, th { padding: 8px 10px; border-bottom: 1px solid #eef2f7; text-align: left; vertical-align: top; }
tr:last-child td { border-bottom: 0; }
td.k { color: #64748b; width: 34%; }
td.v { width: 64px; text-align: right; font-weight: 700; white-space: nowrap; }
td.v.pass { color: #15803d; }
td.v.fail { color: #b91c1c; }
.note { margin: 10px 0 0; padding: 10px 12px; background: #eff6ff; border-radius: 10px; color: #1d4ed8; font-size: 12.5px; }
.score { display: flex; align-items: baseline; gap: 10px; margin: 4px 0 8px; }
.score b { font-size: 30px; color: #0b2a6b; font-variant-numeric: tabular-nums; }
.score span { color: #64748b; font-size: 12px; }
.bar { height: 10px; border-radius: 999px; background: #e2e8f0; overflow: hidden; position: relative; }
.bar i { display: block; height: 100%; border-radius: 999px; background: linear-gradient(90deg, #2563eb, #60a5fa); }
.bar u { position: absolute; left: 90%; top: -3px; width: 2px; height: 16px; background: #b91c1c; }
.tags { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }
.tag { font-size: 12px; padding: 4px 10px; border-radius: 999px; background: #f1f5f9; color: #475569; }
.tag.ok { background: #f0fdf4; color: #15803d; }
.tag.fail { background: #fef2f2; color: #b91c1c; }
ul.sug { margin: 8px 0 0; padding-left: 20px; font-size: 13px; color: #475569; }
footer { margin-top: 22px; color: #94a3b8; font-size: 12px; text-align: center; }
b.ok { color: #15803d; } b.fail { color: #b91c1c; }
@media print { body { background: #fff; } .card, .hero { box-shadow: none; } }
`;
export function buildReportHtml(s: Scenario, outcome: ReviewOutcome): string {
const d = s.demand;
const p = d.parsed;
const order = s.summary.order;
const now = new Date().toLocaleString("zh-CN", { hour12: false });
const rndSection =
s.feasibility.route === "rnd"
? `<section class="card"><h2>新品研发评审</h2>
<p class="lead">结论:<b class="${s.rnd.pass ? "ok" : "fail"}">${s.rnd.pass ? "通过" : "不通过"}</b>(4 项评审全过才通过)</p>
<table><tbody>${s.rnd.items
.map(
(i) =>
`<tr><td class="k">${esc(i.label)}</td><td>标准 ${esc(i.standard)}</td><td>实际 ${esc(i.actual ?? "—")}</td><td class="v ${i.pass ? "pass" : "fail"}">${i.pass ? "通过" : "不通过"}</td></tr>`,
)
.join("")}</tbody></table>
<p class="note">毛利复算:收入 ${yuan(s.margin.revenue)} − 钢卷 ${yuan(s.margin.coilCostTotal)} = ${yuan(s.margin.grossProfit)} 元(毛利率 ${pct(s.margin.grossMarginRate)})</p></section>`
: "";
const ratingTags = s.rating.items
.map((i) => `<span class="tag ${i.pass ? "ok" : "fail"}">${esc(i.label)} ${i.score}/${i.weight}</span>`)
.join("");
const html = `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>需求评估报告 · ${esc(p.productType)} ${p.quantity} 个</title>
<style>${CSS}</style>
</head>
<body>
<div class="wrap">
<header class="hero">
<div class="eyebrow">BAODE · INTELLIGENT REVIEW</div>
<h1>需求评估报告</h1>
<div class="meta">
<span>来源文档:${esc(d.document.fileName)}</span>
<span>生成时间:${esc(now)}</span>
<span>出具:需求评审多智能体系统</span>
</div>
</header>
<div class="banner ${order ? "ok" : "fail"}">整体结论:${esc(s.summary.overall)}${order ? ` · 订单 ${esc(order.orderNo)}` : ""}</div>
<section class="card"><h2>需求概要</h2>
<dl class="grid">
<div><dt>客户</dt><dd>${esc(d.customerCode)}</dd></div>
<div><dt>行业</dt><dd>${esc(p.industry ?? "—")}</dd></div>
<div><dt>产品类型</dt><dd>${esc(p.productType)}</dd></div>
<div><dt>数量 / 单价</dt><dd>${p.quantity} 个 / ${yuan(p.unitPrice)} 元</dd></div>
<div><dt>当期需求金额</dt><dd>${wan(p.quantity * p.unitPrice)} 万</dd></div>
<div><dt>交期</dt><dd>${esc(p.deliveryDate)}</dd></div>
<div><dt>钢卷材质</dt><dd>${esc(p.coilMaterial)}</dd></div>
</dl>
</section>
<section class="card"><h2>可行性判定</h2>
<p class="lead">结论:<b>${esc(s.feasibility.category)}</b>(${esc(s.feasibility.routeLabel)})</p>
<table><tbody>${evidenceRows(s.feasibility.evidence)}</tbody></table>
</section>
${rndSection}
<section class="card"><h2>交期评审</h2>
<p class="lead">结论:<b class="${s.delivery.pass ? "ok" : "fail"}">${s.delivery.pass ? "通过" : "不通过"}</b> · 距交期 ${s.delivery.daysToDelivery} 天</p>
<table><tbody>${evidenceRows(s.delivery.evidence)}</tbody></table>
${s.delivery.suggestions.length ? `<ul class="sug">${s.delivery.suggestions.map((t) => `<li>${esc(t)}</li>`).join("")}</ul>` : ""}
</section>
<section class="card"><h2>客户评级</h2>
<div class="score"><b>${s.rating.total}</b><span>/ 100 分 · ≥90 合格 · 红线为合格线</span></div>
<div class="bar"><i style="width:${Math.min(100, s.rating.total)}%"></i><u></u></div>
<div class="tags">${ratingTags}</div>
<table><tbody>${s.rating.items
.map((i) => `<tr><td class="k">${esc(i.label)}(权重 ${i.weight})</td><td>${esc(i.basis)}</td><td class="v ${i.pass ? "pass" : "fail"}">${i.score} 分</td></tr>`)
.join("")}</tbody></table>
</section>
<section class="card"><h2>综合结论与处理</h2>
<p class="lead">整体结论:<b class="${order ? "ok" : "fail"}">${esc(s.summary.overall)}</b></p>
${order ? `<p class="note">订单:${esc(order.orderNo)}|金额 ${yuan(order.amount)} 元|交期 ${esc(order.deliveryDate)}</p>` : ""}
${s.summary.suggestions.length ? `<ul class="sug">${s.summary.suggestions.map((t) => `<li>${esc(t)}</li>`).join("")}</ul>` : ""}
<p class="lead">${outcome === "order" ? "处理结果:用户已确认评审结论并发起订单生成。" : "处理结果:用户已发起客户临时授信流程(授信审批 → 评级复跑 → 重新汇总)。"}</p>
</section>
<footer>需求评审多智能体系统 自动出具 · ${esc(now)}</footer>
</div>
</body>
</html>`;
return html;
}
+262
View File
@@ -0,0 +1,262 @@
import type { AgentResult, CustomerMaster, Demand, EvidenceRow, ProductCategory, Verdict } from "../types";
import { capacity, todayIso } from "../mock/capacity";
import { rndFiling } from "../mock/rndFiling";
import type { FilingValues } from "./filing";
import { newBomAssumption } from "../mock/bom";
import { demandAmount } from "../mock/demands";
import { pct, wan, yuan } from "./format";
/** 规格 4.3 规则与公式库 */
export interface MarginBreakdown {
revenue: number;
coilCostPerUnit: number;
coilCostTotal: number;
grossProfit: number;
grossMarginRate: number;
}
/** F-毛利:毛利额 = 数量×单价 − 新BOM钢卷用量×数量×钢卷单价 */
export function coilCostPerUnit(): number {
return newBomAssumption.coils.reduce((sum, c) => sum + c.kgPerUnit * c.unitPrice, 0);
}
export function computeMargin(demand: Demand): MarginBreakdown {
const revenue = demandAmount(demand);
const perUnit = coilCostPerUnit();
const coilCostTotal = perUnit * demand.parsed.quantity;
const grossProfit = revenue - coilCostTotal;
return { revenue, coilCostPerUnit: perUnit, coilCostTotal, grossProfit, grossMarginRate: grossProfit / revenue };
}
export interface FeasibilityResult extends AgentResult {
category: ProductCategory;
route: "rnd" | "parallel";
routeLabel: string;
}
/** R-可行-1 / R-可行-2 */
export function evaluateFeasibility(demand: Demand): FeasibilityResult {
const type = demand.parsed.productType;
const hitR1 = type.includes("可拆") || type.includes("钎焊式");
const category: ProductCategory = hitR1 ? "标品" : "非标品";
const evidence: EvidenceRow[] = [
{ label: "R-可行-1:类型含「可拆」或「钎焊式」→ 标品", value: `类型=${type}`, verdict: hitR1 ? "通过" : "不通过" },
{ label: "R-可行-2:否则 → 非标品", value: hitR1 ? "未进入" : "命中", verdict: hitR1 ? null : "通过" },
];
return {
agent: "feasibility",
category,
route: hitR1 ? "parallel" : "rnd",
routeLabel: hitR1 ? "标品 → 直接进入并行评审" : "非标品 → 新品研发评审",
conclusion: category,
verdict: "路由",
evidence,
suggestions: [],
};
}
export interface RndItem {
label: string;
standard: string;
actual: string | null;
pass: boolean;
waiting: boolean;
}
export interface RndResult extends AgentResult {
pass: boolean;
items: RndItem[];
margin: MarginBreakdown;
}
/** R-研发表:毛利率≥30%、模具≤3天、项目≤10天、回收期≤1年;四项全过才通过 */
export function evaluateRndReview(demand: Demand, filled: boolean, filing: FilingValues): RndResult {
const margin = computeMargin(demand);
const [mold, proj, payback] = rndFiling.items;
const items: RndItem[] = [
{ label: "毛利率", standard: "≥30%", actual: pct(margin.grossMarginRate), pass: margin.grossMarginRate >= 0.3, waiting: false },
{ label: mold.label, standard: mold.standard, actual: filled ? filing.values[0] : null, pass: filing.moldDays <= 3, waiting: !filled },
{ label: proj.label, standard: proj.standard, actual: filled ? filing.values[1] : null, pass: filing.projectDays <= 10, waiting: !filled },
{ label: payback.label, standard: payback.standard, actual: filled ? filing.values[2] : null, pass: filing.paybackPass, waiting: !filled },
];
const pass = filled && items.every((i) => i.pass);
const evidence: EvidenceRow[] = [
{
label: "毛利复算",
value: `收入 ${yuan(margin.revenue)} − 钢卷 ${yuan(margin.coilCostTotal)}(${margin.coilCostPerUnit} 元/台 × ${demand.parsed.quantity})= 毛利 ${yuan(margin.grossProfit)} → 毛利率 ${pct(margin.grossMarginRate)}`,
verdict: margin.grossMarginRate >= 0.3 ? "通过" : "不通过",
},
...items.slice(1).map((i) => ({ label: i.label, value: i.actual ?? "等待模具/项目/财务填报", verdict: i.waiting ? null : (i.pass ? "通过" as Verdict : "不通过" as Verdict) })),
];
return {
agent: "rnd",
pass,
items,
margin,
conclusion: filled ? (pass ? "通过" : "不通过") : "等待模具/项目/财务填报",
verdict: pass ? "通过" : "不通过",
evidence,
suggestions: [],
};
}
export interface DeliveryResult extends AgentResult {
pass: boolean;
daysToDelivery: number;
}
function daysBetween(fromIso: string, toIso: string): number {
return Math.round((Date.parse(toIso) - Date.parse(fromIso)) / 86_400_000);
}
/** 交期三维度:产能负荷 / 模具机台 / 物料采购交期 */
export function evaluateDelivery(demand: Demand): DeliveryResult {
const daysToDelivery = daysBetween(todayIso(), demand.parsed.deliveryDate);
const coilLead = capacity.purchase[0].leadDays;
const need = coilLead + capacity.productionCycleDays;
const dimensions: EvidenceRow[] = [
{ label: "产能负荷", value: `${capacity.pressLine.model}当前负荷 ${pct(capacity.pressLine.loadRate)},可吸收 ${demand.parsed.quantity} 台增量`, verdict: "通过" },
{ label: "模具/机台", value: `${capacity.mold.model}在库;钎焊炉排程有空档`, verdict: "通过" },
{ label: "物料采购交期", value: `316L 钢卷现货 ${coilLead} 天 + 生产 ${capacity.productionCycleDays} 天 = ${need} 天 ≤ 距交期 ${daysToDelivery} 天`, verdict: need <= daysToDelivery ? "通过" : "不通过" },
];
return {
agent: "delivery",
pass: dimensions.every((d) => d.verdict === "通过"),
daysToDelivery,
conclusion: "通过",
verdict: "通过",
evidence: dimensions,
suggestions: [capacity.tip],
};
}
export const INDUSTRY_MARGIN_TARGET: Record<string, number> = { CDU: 0.3, 储能: 0.2 };
export const SCORE_WEIGHT = { margin: 20, credit: 60, excess: 10, reconciliation: 10 } as const;
export const SCORE_PASS_LINE = 90;
export interface ScoreItem {
label: string;
weight: number;
score: number;
basis: string;
pass: boolean;
}
export interface RatingResult extends AgentResult {
pass: boolean;
total: number;
items: ScoreItem[];
creditAvailable: number;
marginChain: MarginChainStep[];
creditBreakdown: CreditBreakdown;
}
export interface MarginChainStep {
step: string;
label: string;
value: number;
target: number;
pass: boolean;
walked: boolean;
formula?: string;
}
export interface CreditBreakdown {
items: Array<{ label: string; amount: number; source: string }>;
available: number;
pass: boolean;
}
/** R-毛利达标链 ①②③④ + F-信用 + R-超额利润 + R-对账 + R-记分 */
export function evaluateRating(demand: Demand, customer: CustomerMaster, marginRate: number): RatingResult {
const amount = demandAmount(demand);
const industry = demand.parsed.industry ?? customer.industry;
const target = INDUSTRY_MARGIN_TARGET[industry];
const chainSteps = [
{ step: "①", label: "本单毛利率", value: marginRate },
{ step: "②", label: "客户近 12 月平均毛利率", value: customer.margin12mAvg },
{ step: "③", label: "集团近 12 月平均毛利率", value: customer.groupMargin12mAvg },
{ step: "④", label: `业务员 ${customer.salesRep.code} 近 12 月平均毛利率`, value: customer.salesRep.margin12mAvg },
];
const hitIndex = target === undefined ? -1 : chainSteps.findIndex((c) => c.value >= target);
const marginPass = hitIndex >= 0;
const walked = chainSteps.slice(0, hitIndex >= 0 ? hitIndex + 1 : chainSteps.length);
const marginBasis =
target === undefined
? `行业指标未命中(${industry})`
: marginPass
? walked
.map((c, i) =>
i === walked.length - 1
? `${c.step}${c.label} ${pct(c.value)} ≥ ${industry} 指标 ${pct(target)} → 达标`
: `${c.step}${c.label} ${pct(c.value)} < ${pct(target)}`,
)
.join(";")
: `达标链 ①②③④ 均未达 ${industry} 指标 ${pct(target)}`;
const creditAvailable = customer.creditLimit - customer.stockUnpickedAmount - customer.cancelledOrderAmount - amount;
const creditPass = creditAvailable > 0;
const creditBasis = `${wan(customer.creditLimit)} − ${wan(customer.stockUnpickedAmount)} − ${wan(customer.cancelledOrderAmount)} − ${wan(amount)} = ${wan(creditAvailable)} 万 ${creditAvailable > 0 ? "> 0" : "≤ 0"}`;
const excessProfit = amount * marginRate;
const overTarget = target !== undefined && marginRate > target;
const amountBig = amount >= 5_000_000;
const profitBig = excessProfit >= 2_000_000;
const excessPass = overTarget && amountBig && profitBig;
const excessBasis = excessPass
? `毛利率 ${pct(marginRate)} > 指标 ${pct(target ?? 0)},且金额 ${wan(amount)} 万 ≥ 500 万、毛利额 ${wan(excessProfit)} 万 ≥ 200 万`
: `超标准毛利(${pct(marginRate)} vs ${target !== undefined ? pct(target) : "无指标"})${overTarget ? "✓" : "✗"};金额 ≥ 500 万(${wan(amount)} 万)${amountBig ? "✓" : "✗"};毛利额 ≥ 200 万(${wan(excessProfit)} 万)${profitBig ? "✓" : "✗"}`;
const reconPass = customer.reconciliation.cyclesPerYear === 2 && customer.reconciliation.currentPeriodConfirmed;
const reconBasis = `${customer.reconciliation.system} 一年两次对账,本期${customer.reconciliation.currentPeriodConfirmed ? "已" : "未"}确认`;
const marginChain: MarginChainStep[] = chainSteps.map((c, i) => ({
step: c.step,
label: c.label,
value: c.value,
target: target ?? 0,
pass: target !== undefined && c.value >= target,
walked: hitIndex === -1 ? true : i <= hitIndex,
formula: i === 0 ? `1 − ${yuan(coilCostPerUnit())} ÷ ${yuan(demand.parsed.unitPrice)}` : undefined,
}));
const creditBreakdown: CreditBreakdown = {
items: [
{ label: "信用额度", amount: customer.creditLimit, source: "客户主数据 · 信用额度" },
{ label: "库存未提金额", amount: customer.stockUnpickedAmount, source: "ERP · 库存未提汇总" },
{ label: "客户取消订单金额", amount: customer.cancelledOrderAmount, source: "ERP · 取消订单汇总" },
{ label: "当期需求金额", amount, source: `需求文档 · 数量 ${demand.parsed.quantity} × 单价 ${yuan(demand.parsed.unitPrice)} 元` },
],
available: creditAvailable,
pass: creditPass,
};
const items: ScoreItem[] = [
{ label: "毛利达标", weight: SCORE_WEIGHT.margin, score: marginPass ? SCORE_WEIGHT.margin : 0, basis: marginBasis, pass: marginPass },
{ label: "信用达标", weight: SCORE_WEIGHT.credit, score: creditPass ? SCORE_WEIGHT.credit : 0, basis: creditBasis, pass: creditPass },
{ label: "超额利润", weight: SCORE_WEIGHT.excess, score: excessPass ? SCORE_WEIGHT.excess : 0, basis: excessBasis, pass: excessPass },
{ label: "对账单确认", weight: SCORE_WEIGHT.reconciliation, score: reconPass ? SCORE_WEIGHT.reconciliation : 0, basis: reconBasis, pass: reconPass },
];
const total = items.reduce((s, i) => s + i.score, 0);
const pass = total >= SCORE_PASS_LINE;
return {
agent: "rating",
pass,
total,
items,
creditAvailable,
marginChain,
creditBreakdown,
conclusion: pass ? `通过(${total} 分)` : `不通过(${total} 分 < ${SCORE_PASS_LINE})`,
verdict: pass ? "通过" : "不通过",
evidence: items.map((i) => ({ label: `${i.label}(${i.weight} 分)`, value: i.basis, verdict: i.pass ? "通过" as Verdict : "不通过" as Verdict })),
suggestions: [],
};
}
export interface CreditGap {
gap: number;
suggested: number;
bufferRatio: number;
path: string;
}
/** R-建议:授信缺口 = 当期需求金额 −(信用额度 − 库存未提 − 取消订单);建议值含 1.4 倍缓冲并向上取整到 10 万 */
export function computeCreditGap(demand: Demand, customer: CustomerMaster): CreditGap {
const base = customer.creditLimit - customer.stockUnpickedAmount - customer.cancelledOrderAmount;
const gap = demandAmount(demand) - base;
const bufferRatio = 1.4;
const suggested = Math.ceil((gap * bufferRatio) / 100_000) * 100_000;
return { gap, suggested, bufferRatio, path: "授信审批 → 评级复跑 → 重新汇总" };
}
+57
View File
@@ -0,0 +1,57 @@
import type { AgentResult, CustomerMaster, Demand } from "../types";
import type { DeliveryResult, FeasibilityResult, RatingResult, RndResult } from "./rules";
import { computeCreditGap } from "./rules";
import { customer } from "../mock/customer";
import { wan } from "./format";
export interface OrderMock {
orderNo: string;
itemSummary: string;
amount: number;
deliveryDate: string;
}
export interface SummaryResult {
overall: "评审通过" | "评审不通过";
rows: Array<{ agent: string; conclusion: string; keyEvidence: string }>;
suggestions: string[];
creditGap: ReturnType<typeof computeCreditGap> | null;
order: OrderMock | null;
}
/** 第四幕:主智能体汇总 + 订单 / 建议(规格 2.4) */
export function summarize(
demand: Demand,
feasibility: FeasibilityResult,
rnd: RndResult | null,
delivery: DeliveryResult,
rating: RatingResult,
customerOverride?: CustomerMaster,
): SummaryResult {
const rows = [
{ agent: "可行性", conclusion: feasibility.category, keyEvidence: `${demand.parsed.productType}命中 ${feasibility.category === "非标品" ? "R-可行-2" : "R-可行-1"}` },
...(rnd ? [{ agent: "新品研发评审", conclusion: rnd.pass ? "通过" : "不通过", keyEvidence: rnd.items.map((i) => i.actual ?? "—").join(" / ") }] : []),
{ agent: "交期评审", conclusion: delivery.pass ? "通过" : "不通过", keyEvidence: `负荷 78%;采购+生产 ${delivery.daysToDelivery} 天内可覆盖` },
{ agent: "客户评级", conclusion: rating.pass ? "通过" : "不通过", keyEvidence: `记分 ${rating.total} ${rating.pass ? "≥" : "<"} 90` },
];
const allPass = feasibility !== null && (rnd ? rnd.pass : true) && delivery.pass && rating.pass;
const suggestions: string[] = [...delivery.suggestions];
let creditGap: ReturnType<typeof computeCreditGap> | null = null;
if (!rating.pass && rating.items[1].score === 0) {
creditGap = computeCreditGap(demand, customerOverride ?? customer);
suggestions.push(
`建议发起客户临时授信:精确缺口 ${wan(creditGap.gap)} 万,建议授信 ≥ ${wan(creditGap.suggested)} 万(含缓冲)`,
`处理路径:${creditGap.path}`,
);
}
const order: OrderMock | null = allPass
? {
orderNo: "SO-2610-0001",
itemSummary: `${demand.parsed.productType} ${demand.parsed.quantity} 个 @ ${demand.parsed.unitPrice.toLocaleString("zh-CN")} 元`,
amount: demand.parsed.quantity * demand.parsed.unitPrice,
deliveryDate: demand.parsed.deliveryDate,
}
: null;
return { overall: allPass ? "评审通过" : "评审不通过", rows, suggestions, creditGap, order };
}
export type { AgentResult };
+14
View File
@@ -0,0 +1,14 @@
import type { ModuleConfig } from '../registry';
export const moduleConfig: ModuleConfig = {
id: 'baode-web',
name: '需求评审多智能体',
description: '江苏宝得需求评审 Cockpit:多智能体编排评审、毛利测算、研发加计与负荷校验',
icon: 'ClipboardCheck',
path: '/baode-web',
accentColor: '#2563eb',
accentColorLight: '#1d4ed8',
gradient: 'linear-gradient(135deg, #0c1a3a, #16307a, #1d4ed8)',
gradientLight: 'linear-gradient(135deg, #eef4ff, #dce8ff, #c8dcff)',
tags: ['需求评审', '多智能体', '规则引擎'],
};
+46
View File
@@ -0,0 +1,46 @@
import type { NodeId } from "../state/types";
/** 演示讲解用:每个节点的功能介绍(点击节点 icon 弹出) */
export interface AgentIntro {
title: string;
desc: string;
points: string[];
}
export const agentIntros: Record<NodeId, AgentIntro> = {
parse: {
title: "总控 · 需求解析",
desc: "主智能体:多模态解析上传的 Word / 文本需求文档,结构化关键字段,缺关键信息主动追问。",
points: ["解析字段:客户 / 行业 / 产品类型 / 数量 / 单价 / 交期 / 钢卷材质", "完整性检查,缺失字段生成追问卡,补全后刷新需求卡"],
},
feasibility: {
title: "可行性智能体",
desc: "规则引擎自动判定标品 / 非标品,规则命中过程透明可见。",
points: ["R-可行-1:类型含「可拆」或「钎焊式」→ 标品", "R-可行-2:否则 → 非标品,路由至新品研发评审"],
},
judge: {
title: "标品判断(if 决策)",
desc: "编排决策节点:按可行性判定结果路由到不同评审路径。",
points: ["非标 → 实线进入新品研发评审", "标品 → 虚线跳过研发,直达并行评审"],
},
rnd: {
title: "新品研发评审智能体",
desc: "非标专属:多层 BOM 展开至钢卷层并复算毛利;模具 / 项目 / 财务三人协同填报。",
points: ["评审表:毛利率 ≥30%、模具 ≤3 天、项目 ≤10 天、回收期 ≤1 年", "BOM 展开 + 单台钢卷成本 4,760 元复算闭环"],
},
delivery: {
title: "交期评审智能体",
desc: "三维度评审交期可行性,与客户评级并行执行。",
points: ["产能负荷 78%,可吸收增量", "采购 5 天 + 生产 7 天 ≤ 距交期天数", "提示:316L 钢卷建议立即发起采购"],
},
rating: {
title: "客户评级智能体",
desc: "记分卡评级,与交期评审并行执行;不通过时给出处理路径。",
points: ["毛利达标 20 + 信用达标 60 + 超额利润 10 + 对账 10,≥90 合格", "信用 = 额度 − 库存未提 − 取消订单 − 当期需求", "不通过 → 建议临时授信并测算缺口"],
},
summary: {
title: "总控 · 汇总·订单",
desc: "主智能体汇总三个智能体结论与依据;通过后一键生成订单,不通过输出处理建议。",
points: ["评审通过 → 订单 SO-2610-0001", "评级不通过 → 临时授信建议 + 精确缺口"],
},
};
+67
View File
@@ -0,0 +1,67 @@
import type { BomLine, SteelCoil } from "../types";
/** 规格 5.3 主件表头 + 客户 ERP 截图(维护BOM信息画面,版本 6.3.0.0.50.14) */
export const productMaster = {
itemCode: "310250000339",
itemName: "BL95A-58",
spec: "S31603-(R520-D1-D2, H2116-B3, H4152-D4)",
makeType: "自制件",
unit: "PCS",
plant: "江苏宝得",
refPlant: "江苏宝得",
drawingNo: "I-BL95A-000370",
bomDate: "2026-10-16",
revision: "0000",
standardLot: 1,
expandMode: "多阶",
expandStages: 20,
bomStatusFilter: "全部",
erpScreen: "维护BOM信息",
erpVersion: "6.3.0.0.50.14",
treeRoot: "310250000339[BL95A-58]-StandardBom",
provenance: "规格 5.3 + ERP 截图",
};
/**
* BOM 用量信息(一层 14 行 + 下展层)。
* 单价/总价取自客户 ERP 截图原值,仅做展示,不参与金额复算;
* 金额复算口径统一走 steelCoils 汇总(规格 5.3 / 5.7)。
*/
export const bomLines: BomLine[] = [
{ seq: 10, itemCode: "2020020184", itemName: "外螺纹接管", spec: "304-R520-3.1", qtyPerUnit: 2, unitPrice: 17.1, totalPrice: 34.19, category: "固定元件", status: "生效", level: 1 },
{ seq: 20, itemCode: "2020010083", itemName: "焊接管", spec: "304-H2116 系", qtyPerUnit: 1, unitPrice: 5.75, totalPrice: 5.75, category: "固定元件", status: "生效", level: 1 },
{ seq: 30, itemCode: "2020010148", itemName: "焊接管", spec: "304-H4152 系", qtyPerUnit: 1, unitPrice: 11.54, totalPrice: 11.54, category: "固定元件", status: "生效", level: 1 },
{ seq: 40, itemCode: "2010010019", itemName: "板片铜箔", spec: "BL95A 铜箔", qtyPerUnit: 64, unitPrice: 4.88, totalPrice: 312.4, category: "固定元件", status: "生效", level: 1 },
{ seq: 50, itemCode: "2220160011", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 14, unitPrice: 10.79, totalPrice: 151.05, category: "固定元件", status: "生效", level: 1, material: "316L" },
{ seq: 60, itemCode: "2220160012", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 15, unitPrice: 10.79, totalPrice: 161.84, category: "固定元件", status: "生效", level: 1, material: "316L" },
{ seq: 70, itemCode: "2220160013", itemName: "BL95 板片", spec: "316L-BL95 系", qtyPerUnit: 29, unitPrice: 10.79, totalPrice: 312.88, category: "固定元件", status: "生效", level: 1, material: "316L" },
{ seq: 80, itemCode: "2220160034", itemName: "BL95 板片(失效示例)", spec: "304-BL95A 系", qtyPerUnit: 0, unitPrice: 15.84, totalPrice: 15.84, category: "固定元件", status: "失效", level: 1, material: "304", note: "失效件仅做状态识别展示,不计用量与金额" },
{ seq: 90, itemCode: "2030160108", itemName: "BL95 前端板", spec: "304-F95A 系", qtyPerUnit: 1, unitPrice: 35.62, totalPrice: 35.62, category: "固定元件", status: "生效", level: 1, material: "304" },
{ seq: 100, itemCode: "2040160003", itemName: "BL95 后端板", spec: "304-R95A 系", qtyPerUnit: 1, unitPrice: 35.62, totalPrice: 35.62, category: "固定元件", status: "生效", level: 1, material: "304" },
{ seq: 110, itemCode: "2150020010", itemName: "垫圈", spec: "304-BL95A 系", qtyPerUnit: 2, unitPrice: 1.91, totalPrice: 3.82, category: "固定元件", status: "生效", level: 1 },
{ seq: 120, itemCode: "2010030003", itemName: "铜垫圈", spec: "2系-D35xd", qtyPerUnit: 1, unitPrice: 0.1, totalPrice: 0.1, category: "固定元件", status: "生效", level: 1 },
{ seq: 130, itemCode: "2010030005", itemName: "铜垫圈", spec: "4系-D48xd", qtyPerUnit: 1, unitPrice: 0.12, totalPrice: 0.12, category: "固定元件", status: "生效", level: 1 },
{ seq: 140, itemCode: "2010030006", itemName: "铜垫圈", spec: "5系-D61xd", qtyPerUnit: 2, unitPrice: 0.14, totalPrice: 0.28, category: "固定元件", status: "生效", level: 1 },
{ seq: 51, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 50, material: "316L", kind: "plate", qtyDisplay: "—" },
{ seq: 52, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 50, material: "316L", kind: "coil", qtyDisplay: "展阶" },
{ seq: 61, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 60, material: "316L", kind: "plate", qtyDisplay: "—" },
{ seq: 62, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 60, material: "316L", kind: "coil", qtyDisplay: "展阶" },
{ seq: 71, itemCode: "8010080029", itemName: "316L 平板", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 70, material: "316L", kind: "plate", qtyDisplay: "—" },
{ seq: 72, itemCode: "1010020011", itemName: "316L 钢卷", spec: "316L", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 70, material: "316L", kind: "coil", qtyDisplay: "展阶" },
{ seq: 81, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "失效", level: 2, parentSeq: 80, material: "304", kind: "coil", qtyDisplay: "展阶", note: "截图树中失效件下展 304 钢卷;失效不计用量" },
{ seq: 91, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 90, material: "304", kind: "coil", qtyDisplay: "展阶" },
{ seq: 101, itemCode: "1010010007", itemName: "304 钢卷", spec: "304", qtyPerUnit: 0, unitPrice: 0, totalPrice: 0, category: "固定元件", status: "生效", level: 2, parentSeq: 100, material: "304", kind: "coil", qtyDisplay: "展阶" },
];
/** 钢卷用量汇总(mock 汇总口径,金额复算唯一入口):316L 250kg/台 · 304 20kg/台 */
export const steelCoils: SteelCoil[] = [
{ material: "316L", itemCode: "1010020011", kgPerUnit: 250, unitPrice: 18 },
{ material: "304", itemCode: "1010010007", kgPerUnit: 20, unitPrice: 13 },
];
/** 新 BOM 假设:研发设计新 BOM 单台钢卷用量与现 BOM 汇总一致,保证毛利复算闭环 */
export const newBomAssumption = {
basis: "研发设计新 BOM 的单台钢卷用量取与现 BOM 汇总一致",
coils: steelCoils,
provenance: "规格 5.3",
};
+31
View File
@@ -0,0 +1,31 @@
/** 规格 5.5 产能与采购 mock */
export const capacity = {
pressLine: { model: "BL95 冲压机组", loadRate: 0.78, absorbableIncrementUnits: 500 },
mold: { model: "BL95 冲压模具", inStock: true },
brazingFurnace: { scheduleHasSlot: true },
purchase: [
{ material: "316L 钢卷", itemCode: "1010020011", source: "供应商确认现货", leadDays: 5 },
{ material: "304 钢卷", itemCode: "1010010007", source: "库存充足", leadDays: 0 },
],
productionCycleDays: 7,
tip: "316L 钢卷建议立即发起采购以保留缓冲",
provenance: "规格 5.5",
};
/** 系统当前日期:距交期天数等按此实时复算 */
export function todayIso(): string {
return formatIso(new Date());
}
/** 自今日起 n 天后的 ISO 日期(内置需求样本的交期按此生成,保证样本口径稳定) */
export function isoAfterDays(days: number): string {
const d = new Date();
d.setDate(d.getDate() + days);
return formatIso(d);
}
function formatIso(d: Date): string {
const mm = `${d.getMonth() + 1}`.padStart(2, "0");
const dd = `${d.getDate()}`.padStart(2, "0");
return `${d.getFullYear()}-${mm}-${dd}`;
}
+17
View File
@@ -0,0 +1,17 @@
import type { CustomerMaster } from "../types";
/** 规格 5.1 客户主数据;金额单位统一为元(500 万 = 5,000,000) */
export const customer: CustomerMaster = {
code: "C-BD-001",
name: "江苏宝得换热设备有限公司",
shortName: "江苏宝得",
industry: "CDU",
creditLimit: 5_000_000,
stockUnpickedAmount: 2_800_000,
cancelledOrderAmount: 200_000,
margin12mAvg: 0.12,
groupMargin12mAvg: 0.16,
salesRep: { code: "E-001", margin12mAvg: 0.21 },
reconciliation: { system: "OA", cyclesPerYear: 2, currentPeriodConfirmed: true },
provenance: "规格 5.1(V1.2:库存未提金额上调至 280 万,演示库存积压挤占信用额度)",
};
+85
View File
@@ -0,0 +1,85 @@
import type { Demand, DemandPresetId } from "../types";
import { isoAfterDays } from "./capacity";
/**
* 规格 5.2 需求样本(V1.2 演示三场景 + 一个备用):
* A 场景1 标品主线(字段齐备直通 → 全通过 → 订单 → 评审历史可查)
* B 场景2 非标信用超额(库存 280 万 + 本单 350 万 → 评级 30 分 → 临时授信)
* C 场景3 标品毛利达标链(储能 15% → ①②③ 不达标、④ 业务员 21% 兜底 → 90 分通过)
* D 备用 非标毛利硬不达标(单价 6000 → 研发 30% 门槛不过 → 授信无法扭转)
*/
export const demands: Record<DemandPresetId, Demand> = {
A: {
id: "A",
label: "场景1 · 钎焊式换热器 100 个(标品主线 · 全通过)",
customerCode: "C-BD-001",
document: { fileName: "客户需求评审申请-钎焊式换热器-100个-标品主线.docx", fileType: "docx" },
parsed: {
industry: "CDU",
productType: "钎焊式换热器",
quantity: 100,
unitPrice: 7000,
deliveryDate: isoAfterDays(14),
coilMaterial: "316L",
},
missingFields: [],
followUp: null,
provenance: "规格 5.2 需求 A(V1.2 场景1 标品主线)",
},
B: {
id: "B",
label: "场景2 · 半焊式换热器 500 个(非标 · 信用超额)",
customerCode: "C-BD-001",
document: { fileName: "客户需求评审申请-半焊式换热器-500个-信用超额.docx", fileType: "docx" },
parsed: {
industry: "CDU",
productType: "半焊式换热器",
quantity: 500,
unitPrice: 7000,
deliveryDate: isoAfterDays(44),
coilMaterial: "316L",
},
missingFields: [],
followUp: null,
provenance: "规格 5.2 需求 B(V1.2 场景2 信用超额)",
},
C: {
id: "C",
label: "场景3 · 钎焊式换热器 100 个(储能 · 毛利达标链)",
customerCode: "C-BD-001",
document: { fileName: "客户需求评审申请-钎焊式换热器-100个-储能-毛利达标链.docx", fileType: "docx" },
parsed: {
industry: "储能",
productType: "钎焊式换热器",
quantity: 100,
unitPrice: 5600,
deliveryDate: isoAfterDays(14),
coilMaterial: "316L",
},
missingFields: [],
followUp: null,
provenance: "规格 5.2 需求 C(V1.2 场景3 毛利达标链)",
},
D: {
id: "D",
label: "备用 · 半焊式换热器 100 个 @6000(毛利硬不达标)",
customerCode: "C-BD-001",
document: { fileName: "客户需求评审申请-半焊式换热器-100个-单价6000-毛利不达标.docx", fileType: "docx" },
parsed: {
industry: "CDU",
productType: "半焊式换热器",
quantity: 100,
unitPrice: 6000,
deliveryDate: isoAfterDays(14),
coilMaterial: "316L",
},
missingFields: [],
followUp: null,
provenance: "规格 5.2 需求 D(V1.2 备用:毛利不达标且授信无法扭转)",
},
};
/** 当期需求金额 = 数量 × 单价(元) */
export function demandAmount(demand: Demand): number {
return demand.parsed.quantity * demand.parsed.unitPrice;
}
+17
View File
@@ -0,0 +1,17 @@
/** 研发填报协同 meta(演示 mock):责任方 / 填报人 / 到达间隔;填报值由 engine/filing 按场景动态推导 */
export interface FilingMeta {
key: "mold" | "project" | "payback";
label: string;
standard: string;
waiter: string;
filler: string;
delayMs: number;
}
export const rndFiling: { items: FilingMeta[] } = {
items: [
{ key: "mold", label: "模具周期", standard: "≤3 天", waiter: "模具组", filler: "模具组 · 王工", delayMs: 4000 },
{ key: "project", label: "项目周期", standard: "≤10 天", waiter: "项目部", filler: "项目部 · 李经理", delayMs: 5000 },
{ key: "payback", label: "投资回收期", standard: "≤1 年", waiter: "财务", filler: "财务 · 赵经理", delayMs: 6000 },
],
};
+47
View File
@@ -0,0 +1,47 @@
import type { CustomerMaster, Demand, DemandPresetId } from "../types";
import { demands } from "./demands";
import { customer } from "./customer";
import { coilCostPerUnit, computeMargin, evaluateDelivery, evaluateFeasibility, evaluateRating, evaluateRndReview, computeCreditGap } from "../engine/rules";
import { deriveFiling } from "../engine/filing";
import type { FilingValues } from "../engine/filing";
import { summarize } from "../engine/summary";
export interface Scenario {
demand: Demand;
coilCostPerUnit: number;
margin: ReturnType<typeof computeMargin>;
feasibility: ReturnType<typeof evaluateFeasibility>;
rnd: ReturnType<typeof evaluateRndReview>;
filing: FilingValues;
delivery: ReturnType<typeof evaluateDelivery>;
rating: ReturnType<typeof evaluateRating>;
summary: ReturnType<typeof summarize>;
creditGap: ReturnType<typeof computeCreditGap> | null;
}
/** 场景快照:全部结论由规则引擎实时复算,保证口径自洽(规格 5.7) */
export function buildScenario(demand: Demand, customerOverride?: CustomerMaster): Scenario {
const c = customerOverride ?? customer;
const margin = computeMargin(demand);
const filing = deriveFiling(demand.parsed.quantity, margin.grossProfit);
const feasibility = evaluateFeasibility(demand);
const isStandard = feasibility.category === "标品";
const rnd = evaluateRndReview(demand, true, filing);
const delivery = evaluateDelivery(demand);
const rating = evaluateRating(demand, c, margin.grossMarginRate);
const summary = summarize(demand, feasibility, isStandard ? null : rnd, delivery, rating, c);
return {
demand,
coilCostPerUnit: coilCostPerUnit(),
margin,
feasibility,
rnd,
filing,
delivery,
rating,
summary,
creditGap: summary.creditGap,
};
}
export const scenarios: Scenario[] = (["A", "B", "C", "D"] as DemandPresetId[]).map((id) => buildScenario(demands[id]));
+17
View File
@@ -0,0 +1,17 @@
/** 演示讲解节奏表(ms):按各节点内容多寡设计「过程时长」与「结果停留」 */
export const pacing = {
/** 需求解析:需求卡在右栏常驻,画布间隔离短 */
parse: { process: 2000, cardDwell: 2500 },
/** 可行性:2 条规则行 */
feasibility: { steps: [1200, 1200], dwell: 4000 },
/** 标品判断:菱形翻转 + 路由讲解 */
judge: { flip: 400, dwell: 2500 },
/** 研发:6 行 BOM/毛利卡 + 4 行结论表 */
rnd: { bomSteps: [1500, 1200], bomDwell: 6000, conclusionDwell: 6000 },
/** 交期:3 维度 */
delivery: { steps: [1500, 1500, 1500], dwell: 5000 },
/** 评级:4 记分项 + 可展开面板,内容最多 */
rating: { steps: [1200, 1500, 1200, 1000], dwell: 8000 },
/** 汇总/订单/授信/报告 */
summary: { process: 1500, order: 1500, credit: 600, report: 3200 },
} as const;
+2
View File
@@ -0,0 +1,2 @@
/** 当前登录用户(mock 认证态):评审发起人身份 */
export const currentUser = { code: "E-001", name: "周销售" } as const;
+79
View File
@@ -0,0 +1,79 @@
import type { EvidenceRow, IndustryCode } from "../types";
/** 评审历史归档:浏览器优先 localStorage,非浏览器环境回退内存 */
export interface TraceEntry {
time: string;
agent: string;
title: string;
rows?: EvidenceRow[];
note?: string;
}
export interface ReviewRecordInput {
fileName: string;
customerCode: string;
productType: string;
quantity: number;
unitPrice: number;
industry: IndustryCode | null;
deliveryDate: string;
operator: { code: string; name: string };
startedAt: string;
overall: "评审通过" | "评审不通过";
orderNo: string | null;
creditStarted: boolean;
ratingTotal: number;
feasibilityCategory: string;
reportFileName: string;
reportHtml: string;
trace: TraceEntry[];
}
export interface ReviewRecord extends ReviewRecordInput {
id: string;
finishedAt: string;
}
const KEY = "bd-review-records-v1";
const memory = new Map<string, string>();
function readAll(): ReviewRecord[] {
try {
const raw = typeof localStorage !== "undefined" ? localStorage.getItem(KEY) : (memory.get(KEY) ?? null);
return raw ? (JSON.parse(raw) as ReviewRecord[]) : [];
} catch {
return [];
}
}
function writeAll(list: ReviewRecord[]): void {
const raw = JSON.stringify(list);
try {
if (typeof localStorage !== "undefined") localStorage.setItem(KEY, raw);
else memory.set(KEY, raw);
} catch {
memory.set(KEY, raw);
}
}
export function listReviewRecords(): ReviewRecord[] {
return readAll();
}
export function getReviewRecord(id: string): ReviewRecord | null {
return readAll().find((r) => r.id === id) ?? null;
}
export function saveReviewRecord(input: ReviewRecordInput): ReviewRecord {
const list = readAll();
const d = new Date();
const pad = (n: number) => `${n}`.padStart(2, "0");
const record: ReviewRecord = {
...input,
id: `RV-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${`${list.length + 1}`.padStart(3, "0")}`,
finishedAt: d.toISOString(),
};
writeAll([record, ...list].slice(0, 50));
return record;
}
+39
View File
@@ -0,0 +1,39 @@
import type { EvidenceRow } from "../types";
export type NodeId = "parse" | "feasibility" | "judge" | "rnd" | "delivery" | "rating" | "summary";
export type NodeStatus = "排队" | "执行中" | "等待填报" | "待补全" | "已完成" | "不通过" | "跳过";
export interface NodeState {
status: NodeStatus;
metric?: string;
}
/** 智能体旁悬浮卡:判断结果 + 判断依据(H7) */
export interface FloatCard {
title: string;
verdict?: string;
tone: "pass" | "fail" | "wait" | "info";
rows: EvidenceRow[];
note?: string;
links?: Array<"bom" | "cycle" | "invest">;
}
export type ChatCard =
| { kind: "text"; text: string }
| { kind: "summary" }
| { kind: "order" }
| { kind: "suggest" }
| { kind: "credit-started" }
| { kind: "report"; fileName: string };
export interface ChatMsg {
id: number;
role: "user" | "master";
card: ChatCard;
}
export type Todo =
| { kind: "followup"; prompt: string; options: string[] }
| { kind: "confirm" }
| { kind: "credit" }
| { kind: "next"; allowCreditRerun: boolean };
@@ -0,0 +1,549 @@
import { useEffect, useMemo, useRef, useState } from "react";
import type { CustomerMaster, Demand, EvidenceRow, IndustryCode } from "../types";
import { customer } from "../mock/customer";
import { buildScenario } from "../mock/scenarios";
import { currentUser } from "../mock/user";
import { rndFiling } from "../mock/rndFiling";
import { productMaster } from "../mock/bom";
import { steelCoils } from "../mock/bom";
import { pacing } from "../mock/timing";
import { extractDocumentText, parseDemandDocument } from "../engine/docParse";
import { buildReportHtml, reportFileName } from "../engine/report";
import { computeCreditGap } from "../engine/rules";
import { pct, wan, yuan } from "../engine/format";
import { saveReviewRecord } from "./history";
import type { TraceEntry } from "./history";
import type { ChatCard, ChatMsg, FloatCard, NodeId, NodeState, NodeStatus, Todo } from "./types";
const NODE_IDS: NodeId[] = ["parse", "feasibility", "judge", "rnd", "delivery", "rating", "summary"];
const initialNodes = (): Record<NodeId, NodeState> =>
Object.fromEntries(NODE_IDS.map((id) => [id, { status: "排队" as NodeStatus }])) as Record<NodeId, NodeState>;
let seq = 1;
const now = () => new Date().toLocaleTimeString("zh-CN", { hour12: false });
/** 评审运行器:上传需求文档后按「解析 → 路由 → 并行评审 → 汇总」推进编排状态、悬浮依据卡与右侧对话流 */
export function useReviewRunner() {
const [demand, setDemand] = useState<Demand | null>(null);
const [nodes, setNodes] = useState<Record<NodeId, NodeState>>(initialNodes);
const [floats, setFloats] = useState<Partial<Record<NodeId, FloatCard>>>({});
const [chat, setChat] = useState<ChatMsg[]>([]);
const [todo, setTodo] = useState<Todo | null>(null);
const [running, setRunning] = useState(false);
const [report, setReport] = useState<{ fileName: string; html: string } | null>(null);
const [customerOverride, setCustomerOverride] = useState<CustomerMaster | null>(null);
const [ratingRevealed, setRatingRevealed] = useState(0);
const [floatFocus, setFloatFocus] = useState<NodeId | null>(null);
const runIdRef = useRef(0);
const todoRef = useRef<Todo | null>(null);
const todoResolverRef = useRef<((v: string | null) => void) | null>(null);
const filingResolverRef = useRef<(() => void) | null>(null);
const traceRef = useRef<TraceEntry[]>([]);
const demandRef = useRef<Demand | null>(null);
const scenario = useMemo(() => (demand ? buildScenario(demand, customerOverride ?? undefined) : null), [demand, customerOverride]);
useEffect(() => {
demandRef.current = demand;
}, [demand]);
useEffect(() => {
demandRef.current = demand;
}, [demand]);
const alive = (id: number) => runIdRef.current === id;
const sleep = (ms: number, id: number) =>
new Promise<boolean>((res) => setTimeout(() => res(alive(id)), ms));
const setNode = (node: NodeId, status: NodeStatus, metric?: string) =>
setNodes((p) => ({ ...p, [node]: { status, metric } }));
const setFloat = (node: NodeId, card: FloatCard | null) => {
setFloats((p) => {
const next = { ...p };
if (card) next[node] = card;
else delete next[node];
return next;
});
if (card) setFloatFocus(node);
};
const pushChat = (role: "user" | "master", card: ChatCard) =>
setChat((p) => [...p, { id: seq++, role, card }]);
const pushTrace = (agent: string, title: string, rows?: EvidenceRow[], note?: string) => {
traceRef.current = [...traceRef.current, { time: now(), agent, title, rows, note }];
};
const clearAll = () => {
setNodes(initialNodes());
setFloats({});
setFloatFocus(null);
setRatingRevealed(0);
setChat([]);
setTodo(null);
todoRef.current = null;
setRunning(false);
setDemand(null);
setReport(null);
setCustomerOverride(null);
};
const askTodo = (t: Todo) => {
setTodo(t);
todoRef.current = t;
return new Promise<string | null>((res) => {
todoResolverRef.current = res;
});
};
const resolveTodo = (value: string | null) => {
const t = todoRef.current;
if (!t) return;
if (t.kind === "next") {
setTodo(null);
todoRef.current = null;
if (value === "new-review") {
pushChat("user", { kind: "text", text: "发起新评审" });
runIdRef.current++;
filingResolverRef.current = null;
clearAll();
setDemand(null);
setReport(null);
setCustomerOverride(null);
} else {
pushChat("user", { kind: "text", text: "模拟授信审批通过,复跑评级" });
void rerunAfterCredit();
}
return;
}
if (t.kind === "followup") {
pushChat("user", { kind: "text", text: `补充行业:${value}` });
} else if (t.kind === "confirm") {
pushChat("user", { kind: "text", text: "确认评审结论,发起订单生成" });
} else {
pushChat("user", { kind: "text", text: "发起客户临时授信" });
}
setTodo(null);
todoRef.current = null;
todoResolverRef.current?.(value);
todoResolverRef.current = null;
};
async function runFlow(initialDemand: Demand) {
const id = ++runIdRef.current;
setRunning(true);
let current = initialDemand;
let s = buildScenario(current);
const delay = (ms: number) => sleep(ms, id);
traceRef.current = [];
const startedAt = new Date();
pushTrace("主智能体", `接收需求文档《${current.document.fileName}》,发起评审`);
pushChat("user", { kind: "text", text: `上传《${current.document.fileName}》` });
setNode("parse", "执行中", "解析文档…");
if (!(await delay(pacing.parse.process))) return finish(id);
const missingNow = current.missingFields.length > 0;
setNode("parse", missingNow ? "待补全" : "已完成", missingNow ? "等待补全行业" : "解析完成");
setDemand(current);
pushTrace("主智能体", "需求解析完成", [
{ label: "客户", value: current.customerCode },
{ label: "行业", value: current.parsed.industry ?? "缺失(待补全)" },
{ label: "产品类型", value: current.parsed.productType },
{ label: "数量 / 单价", value: `${current.parsed.quantity} 个 / ${yuan(current.parsed.unitPrice)} 元` },
{ label: "交期", value: current.parsed.deliveryDate },
{ label: "钢卷材质", value: current.parsed.coilMaterial },
]);
if (!missingNow) {
pushChat("master", { kind: "text", text: "解析完成,完整性检查通过,进入可行性判定。" });
}
if (missingNow && current.followUp) {
pushTrace("主智能体", "完整性检查:缺「行业」字段,发出补全追问");
const v = await askTodo({ kind: "followup", prompt: current.followUp.prompt, options: current.followUp.options });
if (!alive(id)) return;
current = {
...current,
parsed: { ...current.parsed, industry: (v as IndustryCode) ?? current.parsed.industry },
missingFields: [],
followUp: null,
};
setDemand(current);
s = buildScenario(current);
pushTrace("用户", `补充行业:${v}`);
setNode("parse", "已完成", "解析完成");
pushChat("master", { kind: "text", text: "完整性检查通过,进入可行性判定。" });
}
if (!(await delay(pacing.parse.cardDwell))) return finish(id);
const feasRows = (stage: number) =>
s.feasibility.evidence.map((row, i) =>
stage > i ? row : { ...row, value: i === 0 ? "匹配中…" : "等待上一条规则结果", verdict: null },
);
setFloat("feasibility", {
title: "可行性判定",
tone: "info",
rows: feasRows(0),
note: "规则引擎匹配中…",
});
setNode("feasibility", "执行中", "加载规则库…");
if (!(await delay(pacing.feasibility.steps[0]))) return finish(id);
setFloat("feasibility", {
title: "可行性判定",
tone: "info",
rows: feasRows(1),
note: "R-可行-1 已出,匹配 R-可行-2…",
});
setNode("feasibility", "执行中", "匹配产品类型…");
if (!(await delay(pacing.feasibility.steps[1]))) return finish(id);
setNode("feasibility", "已完成", s.feasibility.category);
setFloat("feasibility", {
title: "可行性判定",
verdict: s.feasibility.category,
tone: "info",
rows: s.feasibility.evidence,
note: s.feasibility.routeLabel,
});
pushTrace("可行性智能体", `判定:${s.feasibility.category}`, s.feasibility.evidence, s.feasibility.routeLabel);
pushChat("master", { kind: "text", text: `可行性判定:${s.feasibility.category},${s.feasibility.route === "rnd" ? "进入新品研发评审。" : "标品路径,跳过研发评审直达并行评审。"}` });
if (!(await delay(pacing.feasibility.dwell))) return finish(id);
if (s.feasibility.route !== "rnd") {
setNode("rnd", "跳过", "标品跳过");
}
setNode("judge", "执行中", "读取判定结果…");
if (!(await delay(pacing.judge.flip))) return finish(id);
setNode("judge", "已完成", s.feasibility.category);
if (!(await delay(pacing.judge.dwell))) return finish(id);
if (s.feasibility.route === "rnd") {
const bomRowsFinal = [
{ label: "单台钢卷成本", value: `${yuan(s.coilCostPerUnit)} 元/台` },
{ label: "其中 316L", value: `${steelCoils[0].kgPerUnit} kg × ${steelCoils[0].unitPrice} 元 = ${yuan(steelCoils[0].kgPerUnit * steelCoils[0].unitPrice)} 元` },
{ label: "其中 304", value: `${steelCoils[1].kgPerUnit} kg × ${steelCoils[1].unitPrice} 元 = ${yuan(steelCoils[1].kgPerUnit * steelCoils[1].unitPrice)} 元` },
{ label: "收入", value: `${s.demand.parsed.quantity} × ${yuan(s.demand.parsed.unitPrice)} = ${yuan(s.margin.revenue)} 元` },
{ label: "钢卷成本", value: `${yuan(s.coilCostPerUnit)} × ${s.demand.parsed.quantity} = ${yuan(s.margin.coilCostTotal)} 元` },
{ label: "毛利 / 毛利率", value: `${yuan(s.margin.grossProfit)} 元 / ${pct(s.margin.grossMarginRate)}` },
];
const bomRows = (stage: number) =>
bomRowsFinal.map((row, i) => {
const need = i < 3 ? 1 : 2;
return stage >= need
? row
: { ...row, value: stage === 0 ? (i < 3 ? "展开 BOM…" : "—") : "计算中…", verdict: null };
});
setFloat("rnd", {
title: "BOM 展开 · 毛利复算",
tone: "info",
rows: bomRows(0),
note: "展开多层 BOM 中…",
});
setNode("rnd", "执行中", "展开多层 BOM…");
if (!(await delay(pacing.rnd.bomSteps[0]))) return finish(id);
setFloat("rnd", {
title: "BOM 展开 · 毛利复算",
tone: "info",
rows: bomRows(1),
note: "钢卷用量已出,获取钢卷价格中…",
});
setNode("rnd", "执行中", "获取钢卷价格…");
if (!(await delay(pacing.rnd.bomSteps[1]))) return finish(id);
setFloat("rnd", {
title: "BOM 展开 · 毛利复算",
tone: "info",
rows: bomRowsFinal,
note: `${productMaster.itemName} 多层 BOM 已展至钢卷层`,
links: ["bom"],
});
pushTrace("研发智能体", "BOM 展开与毛利复算完成", [
{ label: "单台钢卷成本", value: `${yuan(s.coilCostPerUnit)} 元` },
{ label: "毛利率", value: pct(s.margin.grossMarginRate) },
]);
if (!(await delay(pacing.rnd.bomDwell))) return finish(id);
const arrived: Array<{ label: string; text: string }> = [];
const waitRows = () =>
rndFiling.items.map((it) => {
const a = arrived.find((x) => x.label === it.label);
return { label: it.label, value: a ? a.text : `等待${it.waiter}填报`, verdict: null };
});
setNode("rnd", "等待填报", "等待填报 0/3");
setFloat("rnd", {
title: "等待模具/项目/财务填报",
tone: "wait",
rows: waitRows(),
note: "三项填报由模具 / 项目 / 财务分别提交,逐条到达",
});
for (const [idx, it] of rndFiling.items.entries()) {
const manual = new Promise<void>((res) => {
filingResolverRef.current = res;
});
await Promise.race([manual, delay(it.delayMs)]);
filingResolverRef.current = null;
if (!alive(id)) return;
arrived.push({ label: it.label, text: `${s.filing.values[idx]} · ${it.filler} ${now()}` });
pushTrace(it.filler, `${it.label}填报到达:${s.filing.values[idx]}`);
setNode("rnd", "等待填报", `等待填报 ${arrived.length}/3`);
setFloat("rnd", {
title: "等待模具/项目/财务填报",
tone: "wait",
rows: waitRows(),
note: `${it.label} 已到达(${arrived.length}/3)· ${it.filler}`,
});
}
setNode("rnd", s.rnd.pass ? "已完成" : "不通过", `毛利率 ${pct(s.margin.grossMarginRate)}`);
setFloat("rnd", {
title: "研发评审结论",
verdict: s.rnd.pass ? "通过" : "不通过",
tone: s.rnd.pass ? "pass" : "fail",
rows: s.rnd.items.map((i) => ({ label: i.label, value: `${i.standard} · 实际 ${i.actual}`, verdict: i.pass ? ("通过" as const) : ("不通过" as const) })),
note: `毛利复算:${yuan(s.margin.revenue)} − ${yuan(s.margin.coilCostTotal)} = ${yuan(s.margin.grossProfit)} → ${pct(s.margin.grossMarginRate)}`,
links: ["bom", "cycle", "invest"],
});
pushTrace("研发智能体", `研发评审结论:${s.rnd.pass ? "通过(4/4 项)" : "不通过"}`, s.rnd.evidence);
pushChat("master", { kind: "text", text: `新品研发评审:${s.rnd.pass ? "通过(4/4 项)。" : `不通过(毛利率 ${pct(s.margin.grossMarginRate)} < 30%)。`}` });
if (!(await delay(pacing.rnd.conclusionDwell))) return finish(id);
} else {
setNode("rnd", "跳过", "标品跳过");
}
setNode("delivery", "执行中");
setNode("rating", "执行中");
pushChat("master", { kind: "text", text: "并行评审启动:交期评审 ∥ 客户评级。" });
const tDelivery = (async () => {
const dims = s.delivery.evidence;
const rowsAt = (done: number) =>
dims.map((r, i) => (i < done ? r : { label: r.label, value: "计算中…", verdict: null }));
setFloat("delivery", {
title: "交期依据",
tone: "info",
rows: rowsAt(0),
note: "三个维度依次计算中…",
});
setNode("delivery", "执行中", "拉取冲压机组负荷…");
if (!(await delay(pacing.delivery.steps[0])) || !alive(id)) return;
setFloat("delivery", { title: "交期依据", tone: "info", rows: rowsAt(1), note: "产能负荷已出(1/3)" });
setNode("delivery", "执行中", "核对模具/钎焊炉排程…");
if (!(await delay(pacing.delivery.steps[1])) || !alive(id)) return;
setFloat("delivery", { title: "交期依据", tone: "info", rows: rowsAt(2), note: "模具/机台已出(2/3)" });
setNode("delivery", "执行中", "确认钢卷采购交期…");
if (!(await delay(pacing.delivery.steps[2])) || !alive(id)) return;
setNode("delivery", "已完成", `${s.delivery.daysToDelivery} 天可覆盖`);
setFloat("delivery", {
title: "交期依据",
verdict: s.delivery.pass ? "通过" : "不通过",
tone: s.delivery.pass ? "pass" : "fail",
rows: dims,
note: s.delivery.suggestions[0],
});
pushTrace("交期智能体", s.delivery.pass ? "交期评审通过" : "交期评审不通过", s.delivery.evidence, s.delivery.suggestions[0]);
pushChat("master", { kind: "text", text: `交期评审:${s.delivery.pass ? "通过。" : "不通过。"}` });
if (!(await delay(pacing.delivery.dwell)) || !alive(id)) return;
})();
const tRating = (async () => {
setFloat("rating", {
title: "客户评级记分卡",
tone: "info",
rows: [],
note: "四个记分项依次计算中…",
});
setNode("rating", "执行中", "读取客户主数据 / ERP 信用数据…");
if (!(await delay(pacing.rating.steps[0])) || !alive(id)) return;
setRatingRevealed(1);
setNode("rating", "执行中", "计算信用敞口…");
if (!(await delay(pacing.rating.steps[1])) || !alive(id)) return;
setRatingRevealed(2);
setNode("rating", "执行中", "拉取 OA 对账状态…");
if (!(await delay(pacing.rating.steps[2])) || !alive(id)) return;
setRatingRevealed(3);
setNode("rating", "执行中", "按记分规则打分…");
if (!(await delay(pacing.rating.steps[3])) || !alive(id)) return;
setRatingRevealed(4);
setNode("rating", s.rating.pass ? "已完成" : "不通过", `${s.rating.total} 分`);
setFloat("rating", {
title: "客户评级记分卡",
verdict: `${s.rating.total} 分 · ${s.rating.pass ? "合格" : "不合格"}`,
tone: s.rating.pass ? "pass" : "fail",
rows: s.rating.evidence,
note: `合计 ${s.rating.total} 分 · ${s.rating.pass ? "≥90 合格" : "<90 不合格"}`,
});
pushTrace("评级智能体", s.rating.conclusion, s.rating.evidence);
pushChat("master", { kind: "text", text: `客户评级:${s.rating.total} 分,${s.rating.pass ? "合格。" : "不合格。"}` });
if (!(await delay(pacing.rating.dwell)) || !alive(id)) return;
})();
await Promise.all([tDelivery, tRating]);
if (!alive(id)) return;
setNode("summary", "执行中", "汇总三个智能体结论…");
if (!(await delay(pacing.summary.process))) return finish(id);
setNode("summary", s.summary.order ? "已完成" : "不通过", s.summary.overall);
pushChat("master", { kind: "summary" });
pushTrace("主智能体", s.summary.overall, s.summary.rows.map((r) => ({ label: r.agent, value: `${r.conclusion} · ${r.keyEvidence}` })));
if (s.summary.order) {
await askTodo({ kind: "confirm" });
if (!alive(id)) return;
setNode("summary", "执行中", "生成订单号…");
if (!(await delay(pacing.summary.order))) return finish(id);
pushChat("master", { kind: "order" });
setNode("summary", "已完成", s.summary.order.orderNo);
pushTrace("主智能体", `订单已生成 ${s.summary.order.orderNo}`);
} else if (s.summary.creditGap) {
pushChat("master", { kind: "suggest" });
await askTodo({ kind: "credit" });
if (!alive(id)) return;
if (!(await delay(pacing.summary.credit))) return finish(id);
pushChat("master", { kind: "credit-started" });
pushTrace("主智能体", "客户临时授信流程已发起");
} else {
const failedAgents = s.summary.rows
.filter((r) => r.conclusion.includes("不通过"))
.map((r) => r.agent)
.join("、");
pushChat("master", {
kind: "text",
text: `评审不通过:${failedAgents} 未达标。该结论与信用额度无关,临时授信无法扭转;请调整单价、交期或工艺方案后重新发起评审。`,
});
pushTrace("主智能体", `评审不通过(${failedAgents}),不适用临时授信`);
}
pushChat("master", { kind: "text", text: "评审已收尾,正在生成《需求评估报告》…" });
setNode("summary", "执行中", "生成评估报告…");
if (!(await delay(pacing.summary.report))) return finish(id);
const fileName = reportFileName(s);
const html = buildReportHtml(s, s.summary.order ? "order" : "credit");
if (!alive(id)) return;
setReport({ fileName, html });
pushTrace("主智能体", `需求评估报告已生成《${fileName}》`);
saveReviewRecord({
fileName: current.document.fileName,
customerCode: current.customerCode,
productType: current.parsed.productType,
quantity: current.parsed.quantity,
unitPrice: current.parsed.unitPrice,
industry: current.parsed.industry,
deliveryDate: current.parsed.deliveryDate,
operator: currentUser,
startedAt: startedAt.toISOString(),
overall: s.summary.overall,
orderNo: s.summary.order?.orderNo ?? null,
creditStarted: !s.summary.order,
ratingTotal: s.rating.total,
feasibilityCategory: s.feasibility.category,
reportFileName: fileName,
reportHtml: html,
trace: traceRef.current,
});
setNode("summary", s.summary.order ? "已完成" : "不通过", s.summary.order ? s.summary.order.orderNo : s.summary.overall);
pushChat("master", { kind: "report", fileName });
const nextTodo: Todo = { kind: "next", allowCreditRerun: !s.summary.order };
setTodo(nextTodo);
todoRef.current = nextTodo;
finish(id);
}
function finish(id: number) {
if (alive(id)) setRunning(false);
}
async function rerunAfterCredit() {
const id = ++runIdRef.current;
setRunning(true);
const d = demandRef.current;
if (!d) return finish(id);
const granted = computeCreditGap(d, customer).suggested;
const override: CustomerMaster = { ...customer, creditLimit: customer.creditLimit + granted };
setCustomerOverride(override);
pushChat("master", { kind: "text", text: `授信审批通过:临时授信 ${wan(granted)} 万已生效,复跑客户评级与汇总…` });
const s2 = buildScenario(d, override);
setRatingRevealed(0);
setFloat("rating", {
title: "客户评级记分卡",
tone: "info",
rows: [],
note: "复跑:四个记分项依次计算中…",
});
setNode("rating", "执行中", "复跑评级(含临时授信)…");
if (!(await sleep(1800, id))) return finish(id);
setRatingRevealed(4);
setNode("rating", "已完成", `${s2.rating.total} 分`);
setFloat("rating", {
title: "客户评级记分卡(复跑)",
verdict: `${s2.rating.total} 分 · ${s2.rating.pass ? "合格" : "不合格"}`,
tone: s2.rating.pass ? "pass" : "fail",
rows: s2.rating.evidence,
note: `临时授信 ${wan(granted)} 万生效,信用项转通过`,
});
setNode("summary", "执行中", "重新汇总…");
if (!(await sleep(1500, id))) return finish(id);
setNode("summary", "已完成", s2.summary.overall);
pushChat("master", { kind: "summary" });
await askTodo({ kind: "confirm" });
if (!alive(id)) return;
setNode("summary", "执行中", "生成订单号…");
if (!(await sleep(1500, id))) return finish(id);
pushChat("master", { kind: "order" });
setNode("summary", "已完成", s2.summary.order?.orderNo ?? s2.summary.overall);
pushChat("master", { kind: "text", text: "评审已收尾,正在生成《需求评估报告》…" });
setNode("summary", "执行中", "生成评估报告…");
if (!(await sleep(3200, id))) return finish(id);
const fileName = reportFileName(s2);
const html = buildReportHtml(s2, "order");
if (!alive(id)) return;
setReport({ fileName, html });
setNode("summary", "已完成", s2.summary.order?.orderNo ?? s2.summary.overall);
pushChat("master", { kind: "report", fileName });
const t: Todo = { kind: "next", allowCreditRerun: false };
setTodo(t);
todoRef.current = t;
finish(id);
}
const uploadFile = async (file: File) => {
if (running) return;
let text: string;
try {
text = await extractDocumentText(file);
} catch (err) {
pushChat("master", { kind: "text", text: err instanceof Error ? err.message : "文档解析失败,请重新上传。" });
return;
}
const result = parseDemandDocument(text, file.name);
if (!result.ok) {
pushChat("master", {
kind: "text",
text: `《${file.name}》无法发起评审:${result.reasons.join(";")}。请补全后重新上传。`,
});
return;
}
runIdRef.current++;
filingResolverRef.current = null;
clearAll();
setCustomerOverride(null);
void runFlow(result.demand);
};
const sendText = (text: string) => {
const trimmed = text.trim();
if (!trimmed) return;
pushChat("user", { kind: "text", text: trimmed });
pushChat("master", {
kind: "text",
text: running
? "评审正在进行中,进度见左侧编排画布;待办事项会出现在此处。"
: "已收到。请通过下方附件按钮上传需求文档(Word / 文本)以启动评审。",
});
};
return {
demand,
scenario,
nodes,
floats,
floatFocus,
chat,
todo,
running,
report,
ratingRevealed,
activeCustomer: customerOverride ?? customer,
uploadFile,
sendText,
resolveTodo,
};
}
export type ReviewRunner = ReturnType<typeof useReviewRunner>;
+395
View File
@@ -0,0 +1,395 @@
/* 设计令牌:ui-ux-pro-max 推荐(enterprise B2B · Trust & Authority),离线包不引外部字体 */
/* 变量挂在模块根容器 .cockpit-root 上,避免与平台全局 :root 变量冲突 */
.cockpit-root {
--brand: #2563eb;
--brand-600: #1d4ed8;
--brand-soft: #eff6ff;
--cta: #f97316;
--cta-soft: #fff7ed;
--bg: #f8fafc;
--surface: #ffffff;
--ink: #1e293b;
--muted: #64748b;
--line: #e2e8f0;
--pass: #15803d;
--pass-bg: #f0fdf4;
--fail: #b91c1c;
--fail-bg: #fef2f2;
--wait: #b45309;
--wait-bg: #fffbeb;
--radius: 10px;
--shadow-1: 0 1px 2px rgba(15, 23, 42, 0.06), 0 4px 12px rgba(15, 23, 42, 0.08);
--shadow-2: 0 12px 32px rgba(15, 23, 42, 0.16);
--font: "Plus Jakarta Sans", -apple-system, BlinkMacSystemFont, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, sans-serif;
--label-col: 150px;
/* 原 body 全局样式收敛到模块根容器 */
height: 100dvh;
display: flex;
flex-direction: column;
font-family: var(--font);
font-size: 14px;
line-height: 1.55;
color: var(--ink);
background: var(--bg);
}
/* ---------- 顶栏 ---------- */
.topbar {
display: flex; align-items: center; gap: 12px;
padding: 8px 20px; background: var(--surface); border-bottom: 1px solid var(--line);
}
.baode-root .logo { height: 30px; width: auto; }
.topbar-title { display: flex; align-items: center; line-height: 1.2; padding-left: 14px; border-left: 1px solid var(--line); }
.topbar-title strong { font-size: 16px; font-weight: 600; letter-spacing: .01em; }
/* ---------- 主布局 ---------- */
.topbar-right { margin-left: auto; display: flex; gap: 10px; align-items: center; }
.user-chip { font-size: 12px; color: var(--muted); background: #f1f5f9; border-radius: 999px; padding: 4px 12px; }
/* ---------- 评审历史 ---------- */
.hist-mask { position: fixed; inset: 0; background: rgba(15, 23, 42, .45); z-index: 70; display: flex; justify-content: center; padding: 40px 16px; }
.hist { width: min(880px, 100%); max-height: calc(100dvh - 80px); display: flex; flex-direction: column; background: #fff; border-radius: 14px; overflow: hidden; box-shadow: var(--shadow-2); }
.hist-head { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; border-bottom: 1px solid var(--line); font-weight: 700; }
.hist-body { overflow: auto; padding: 14px 16px; }
.hist-table { width: 100%; border-collapse: collapse; font-size: 13px; }
.hist-table th, .hist-table td { padding: 8px 10px; border-bottom: 1px solid var(--line); text-align: left; }
.hist-table th { color: var(--muted); font-weight: 600; font-size: 12px; }
.hist-sub { margin: 18px 0 8px; font-size: 13px; }
.trace { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.trace li { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; }
.trace-head { display: flex; gap: 10px; align-items: baseline; font-size: 13px; flex-wrap: wrap; }
.trace-time { color: var(--muted); font-variant-numeric: tabular-nums; font-size: 12px; }
.trace-agent { background: var(--brand-soft); color: var(--brand-600); border-radius: 999px; padding: 1px 8px; font-size: 11px; font-weight: 600; }
.trace-note { margin: 6px 0 0; color: var(--muted); font-size: 12px; }
.cockpit {
flex: 1; min-height: 0;
display: grid; grid-template-columns: minmax(0, 1fr) clamp(320px, 28vw, 400px);
gap: 14px; padding: 14px 16px;
}
@media (max-width: 1100px) {
.cockpit { grid-template-columns: 1fr; grid-template-rows: minmax(430px, 1fr) minmax(400px, 1fr); }
}
.canvas-panel, .right {
display: flex; flex-direction: column; min-height: 0;
background: var(--surface); border: 1px solid var(--line);
border-radius: var(--radius); box-shadow: var(--shadow-1); overflow: hidden;
}
.baode-root .panel-head {
display: flex; align-items: center; justify-content: space-between; gap: 12px;
padding: 10px 14px; border-bottom: 1px solid var(--line);
}
.baode-root .panel-head h2 { margin: 0; font-size: 14px; }
.legend { display: flex; gap: 12px; font-size: 12px; color: var(--muted); flex-wrap: wrap; }
.lg { width: 8px; height: 8px; border-radius: 50%; display: inline-block; margin-right: 4px; }
.lg-run { background: var(--brand); }
.lg-wait { background: var(--wait); }
.lg-todo { background: var(--cta); }
.lg-ok { background: var(--pass); }
.lg-fail { background: var(--fail); }
.lg-skip { background: #cbd5e1; }
.lg-agent { background: #6366f1; border-radius: 2px; }
/* ---------- 编排画布 ---------- */
.canvas {
flex: 1; min-height: 0; overflow: auto; display: flex;
background-image: radial-gradient(circle, #e2e8f0 1px, transparent 1px);
background-size: 22px 22px;
}
.flow { position: relative; display: flex; flex-direction: row; align-items: flex-start; width: max-content; margin: auto; padding: 52px 20px 40px; transition: padding-bottom 0.25s ease; }
.flow[data-active="true"] { margin: 0 auto; padding-bottom: 480px; }
.stage { position: relative; display: flex; flex-direction: column; align-items: center; gap: 6px; }
.chips { display: flex; flex-direction: column; align-items: center; gap: 4px; }
.chip-f {
max-width: 118px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
font-size: 11px; padding: 2px 8px; border: 1px solid var(--line); border-radius: 999px;
background: #fff; color: var(--muted); cursor: pointer; transition: color 0.18s, border-color 0.18s;
}
.chip-f:hover { border-color: var(--brand); color: var(--brand-600); }
.fnode { position: relative; }
.fnode-card {
display: flex; flex-direction: column; gap: 6px; width: 118px; min-height: 92px;
background: #fff; border: 1px solid var(--line); border-top: 3px solid #cbd5e1;
border-radius: var(--radius); padding: 10px 12px; box-shadow: var(--shadow-1);
transition: border-color 0.2s, box-shadow 0.2s;
}
.kind-control .fnode-card { background: var(--brand-soft); }
.kind-agent .fnode-card {
background: linear-gradient(180deg, #eef2ff 0%, #ffffff 60%);
border-color: #c7d2fe; border-top-color: #6366f1;
}
.agent-tag {
font-style: normal; font-size: 10px; font-weight: 700;
color: #4338ca; background: #e0e7ff; border-radius: 999px; padding: 1px 6px;
}
.s-执行中 .fnode-card { border-top-color: var(--brand); box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12); }
.s-执行中 .fnode-card { position: relative; }
.s-执行中 .fnode-card::after {
content: ""; position: absolute; inset: -5px; border-radius: 14px; pointer-events: none;
background:
repeating-linear-gradient(90deg, var(--brand) 0 6px, transparent 6px 12px) 0 0 / 100% 2px no-repeat,
repeating-linear-gradient(90deg, var(--brand) 0 6px, transparent 6px 12px) 0 100% / 100% 2px no-repeat,
repeating-linear-gradient(0deg, var(--brand) 0 6px, transparent 6px 12px) 0 0 / 2px 100% no-repeat,
repeating-linear-gradient(0deg, var(--brand) 0 6px, transparent 6px 12px) 100% 0 / 2px 100% no-repeat;
animation: ants 1s linear infinite;
}
@keyframes ants {
to { background-position: 12px 0, -12px 100%, 0 -12px, 100% 12px; }
}
.s-等待填报 .fnode-card { border-top-color: var(--wait); }
.s-待补全 .fnode-card { border-top-color: var(--cta); box-shadow: 0 0 0 3px rgba(249, 115, 22, 0.12); }
.s-已完成 .fnode-card { border-top-color: var(--pass); }
.s-不通过 .fnode-card { border-top-color: var(--fail); }
.fnode-top { display: flex; align-items: center; gap: 6px; }
.fnode-top .fnode-status { margin-left: auto; }
.node-icon {
width: 22px; height: 22px; flex: none; display: grid; place-items: center;
border: none; border-radius: 6px; padding: 0; cursor: pointer;
background: var(--brand-soft); color: var(--brand-600);
transition: background 0.18s, color 0.18s;
}
.node-icon:hover { background: #dbeafe; color: var(--brand); }
.node-icon:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
.diamond {
position: relative; width: 150px; height: 84px; margin-top: 4px;
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
background: #cbd5e1; display: grid; place-items: center;
border: none; padding: 0; cursor: pointer;
}
.diamond:focus-visible { outline: 2px solid var(--brand); outline-offset: 3px; }
.diamond-in {
position: absolute; inset: 2px;
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);
background: var(--cta-soft);
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 2px;
}
.diamond-label { font-size: 12px; font-weight: 700; }
.fnode-metric.muted { color: var(--muted); font-weight: 500; }
.s-执行中 .diamond { background: var(--brand); animation: diamondPulse 1.2s ease-in-out infinite; }
.s-已完成 .diamond { background: var(--pass); }
.s-不通过 .diamond { background: var(--fail); }
@keyframes diamondPulse { 50% { filter: brightness(1.18); } }
.decision-status { display: flex; align-items: center; justify-content: center; gap: 6px; margin-top: 6px; }
.kind-decision .node-icon { background: var(--cta-soft); color: var(--cta); }
.intro-desc { margin: 0; font-size: 12px; color: var(--ink); }
.intro-points { margin: 6px 0 0; padding-left: 16px; font-size: 12px; }
.intro-points li { margin: 2px 0; }
.fnode-dot {
flex: none; width: 18px; height: 18px; border-radius: 50%;
display: grid; place-items: center; font-size: 11px; color: #fff; background: #cbd5e1;
}
.s-执行中 .fnode-dot { background: var(--brand); animation: baode-pulse 1.6s ease-in-out infinite; }
.s-等待填报 .fnode-dot { background: var(--wait); }
.s-待补全 .fnode-dot { background: var(--cta); }
.s-已完成 .fnode-dot { background: var(--pass); }
.s-不通过 .fnode-dot { background: var(--fail); }
.fnode-label { display: flex; flex-direction: column; font-size: 13px; font-weight: 600; }
.fnode-label-row { display: flex; align-items: baseline; gap: 6px; flex-wrap: wrap; }
.fnode-note { font-style: normal; font-weight: 400; font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }
.fnode-status { font-size: 10px; color: var(--muted); white-space: nowrap; }
.s-执行中 .fnode-status { color: var(--brand-600); font-weight: 600; }
.s-不通过 .fnode-status { color: var(--fail); font-weight: 600; }
.s-待补全 .fnode-status { color: var(--cta); font-weight: 600; }
.fnode-metric { font-size: 12px; font-weight: 700; color: var(--brand-600); font-variant-numeric: tabular-nums; }
.conn-h { flex: none; position: relative; width: 20px; height: 2px; margin-top: 45px; background: #cbd5e1; }
.flow[data-spread="true"] .conn-h { width: 210px; }
.flow[data-wide="true"] .conn-h { width: 380px; }
.conn-h::after {
content: ""; position: absolute; right: -2px; top: -3px;
border: 4px solid transparent; border-left-color: #cbd5e1;
}
.conn-h span {
position: absolute; bottom: 4px; left: 50%; transform: translateX(-50%); z-index: 6;
font-size: 11px; color: var(--muted); white-space: nowrap;
background: var(--bg); padding: 0 4px; border-radius: 4px;
}
.bypass-h { position: absolute; top: 18px; height: 0; border-top: 2px dashed #fdba74; }
.stub { position: absolute; top: 0; width: 0; border-left: 2px dashed #fdba74; }
.stub-l { left: -1px; }
.stub-l::after {
content: ""; position: absolute; bottom: -4px; left: -4px;
width: 6px; height: 6px; border-radius: 50%; background: #fdba74;
}
.stub-r { right: -1px; }
.stub-r::after {
content: ""; position: absolute; bottom: -6px; left: -5px;
border: 4px solid transparent; border-top-color: #fdba74;
}
.bypass-h span {
position: absolute; top: -18px; left: 50%; transform: translateX(-50%);
font-size: 11px; color: var(--cta); white-space: nowrap;
}
.pgroup {
position: relative; display: flex; flex-direction: column; gap: 8px; width: 136px;
padding: 16px 10px 10px;
border: 1.5px dashed var(--brand); border-radius: 12px; background: rgba(37, 99, 235, 0.03);
}
.pgroup-badge {
position: absolute; top: -10px; left: 12px;
background: var(--brand); color: #fff; font-size: 11px; font-weight: 600;
padding: 2px 10px; border-radius: 999px;
}
.pgroup .fnode-card { width: 100%; min-height: 76px; }
.pgroup.pg-active { width: 210px; }
/* ---------- 悬浮依据卡 ---------- */
.float {
background: #fff; border: 1px solid var(--line); border-left: 3px solid var(--brand);
border-radius: 8px; box-shadow: var(--shadow-2); padding: 10px 12px;
animation: floatIn 0.24s ease-out; z-index: 5;
}
.floats-col {
position: absolute; top: calc(100% + 8px); left: 50%; transform: translateX(-50%);
display: flex; flex-direction: column; gap: 10px; z-index: 10; width: 320px;
}
.floats-col.align-left { left: 0; transform: none; }
.floats-col.align-right { left: auto; right: 0; transform: none; }
.floats-col.wide { width: 560px; }
.floats-col.mid { width: 420px; }
.float-table { margin: 2px 0 6px; }
.float-table th, .float-table td { padding: 4px 6px; }
.floats-col .float { width: 100%; display: flex; flex-direction: column; }
.float-close { align-self: flex-end; margin-top: 6px; }
.link-btn {
align-self: flex-start; margin-top: 6px; padding: 0;
background: none; border: none; color: var(--brand-600);
font-size: 12px; cursor: pointer; text-decoration: underline;
}
.link-btn:hover { color: var(--brand); }
.link-row { display: flex; gap: 14px; flex-wrap: wrap; margin-top: 6px; }
.link-row .link-btn { margin-top: 0; }
.baode-root .modal-backdrop {
position: fixed; inset: 0; z-index: 100;
background: rgba(15, 23, 42, 0.45);
display: grid; place-items: center; padding: 24px;
}
.baode-root .modal {
background: #fff; border-radius: 12px; box-shadow: var(--shadow-2);
width: min(780px, 100%); max-height: 84vh; overflow: auto; padding: 16px 18px;
}
.baode-root .modal-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; font-size: 14px; font-weight: 700; margin-bottom: 10px; }
.baode-root .modal-kv { margin: 0 0 12px; }
.bom-table { width: 100%; border-collapse: collapse; font-size: 12px; }
.bom-table th, .bom-table td { border: 1px solid var(--line); padding: 5px 8px; text-align: left; }
.bom-table th { background: #f3f4f6; }
.bom-table .lvl2 td:nth-child(2) { padding-left: 22px; color: var(--muted); }
.bom-table .invalid td:nth-child(2) { text-decoration: line-through; }
.bom-table .invalid td:last-child { color: var(--fail); }
.baode-root .sub { color: var(--muted); font-size: 11px; }
.baode-root .modal-note { margin: 10px 0 0; font-size: 12px; color: var(--muted); }
.detail-title { margin: 12px 0 6px; font-size: 13px; font-weight: 700; }
.pass-cell { color: var(--pass); font-weight: 600; }
.fail-cell { color: var(--fail); font-weight: 600; }
.score-panels { display: flex; flex-direction: column; }
.score-panel { border-top: 1px dashed var(--line); }
.score-panel:first-child { border-top: none; }
.score-panel-head {
display: flex; align-items: center; gap: 8px; width: 100%;
padding: 6px 0; background: none; border: none; cursor: pointer;
font: inherit; font-size: 12px; text-align: left;
}
.score-panel-head:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
.sp-label { font-weight: 600; color: var(--muted); white-space: nowrap; width: var(--label-col); flex: none; }
.sp-value { flex: 1; color: var(--ink); }
.sp-caret { color: var(--muted); font-size: 10px; width: 14px; flex: none; text-align: center; }
.sp-muted { color: var(--muted); }
.score-panel-head .pass-cell, .score-panel-head .fail-cell { flex: none; width: 96px; text-align: right; }
.score-panel-body { padding: 2px 0 8px; }
.inline-link { display: inline; padding: 0; margin: 0; }
.score-panels .ev-v { width: 96px; padding-right: 22px; white-space: nowrap; text-align: right; }
.tone-pass { border-left-color: var(--pass); }
.tone-fail { border-left-color: var(--fail); }
.tone-wait { border-left-color: var(--wait); }
.float-head { display: flex; justify-content: space-between; gap: 8px; font-size: 12px; font-weight: 700; margin-bottom: 6px; }
.float-verdict { font-weight: 700; }
.tone-pass .float-verdict { color: var(--pass); }
.tone-fail .float-verdict { color: var(--fail); }
.tone-wait .float-verdict { color: var(--wait); }
.float-note { margin: 6px 0 0; font-size: 11px; color: var(--muted); }
.ev { width: 100%; border-collapse: collapse; }
.ev td { padding: 3px 6px 3px 0; font-size: 12px; vertical-align: top; border: 0; text-align: left; }
.ev tr + tr td { border-top: 1px dashed var(--line); }
.ev-label { color: var(--muted); width: calc(var(--label-col) + 8px); padding-right: 8px; }
.ev-value { color: var(--ink); }
.ev-v { width: 46px; text-align: right; font-weight: 600; }
.ev-v.pass { color: var(--pass); }
.ev-v.fail { color: var(--fail); }
/* ---------- 执行日志 ---------- */
.chat-empty { color: var(--muted); font-size: 12px; padding: 8px 2px; margin: 0; }
/* ---------- 右栏 ---------- */
.demand-card { padding: 10px 14px; border-bottom: 1px solid var(--line); background: #fbfcfe; }
.demand-empty { display: flex; flex-direction: column; gap: 4px; padding: 14px; color: var(--muted); font-size: 12px; }
.demand-empty strong { color: var(--ink); font-size: 13px; }
.kv-grid { display: grid; grid-template-columns: auto 1fr auto 1fr; gap: 4px 10px; margin: 8px 0 0; font-size: 12px; }
.kv-grid dt { color: var(--muted); }
.kv-grid dd { margin: 0; font-variant-numeric: tabular-nums; }
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; font-size: 12px; font-weight: 700; }
.badge { font-size: 11px; font-weight: 600; padding: 2px 8px; border-radius: 999px; white-space: nowrap; }
.badge-ok { background: var(--pass-bg); color: var(--pass); }
.badge-wait { background: var(--wait-bg); color: var(--wait); }
.badge-fail { background: var(--fail-bg); color: var(--fail); }
.chat { flex: 1; min-height: 0; overflow: auto; padding: 12px 14px; display: flex; flex-direction: column; gap: 10px; }
.bubble { max-width: 88%; padding: 8px 12px; border-radius: 12px; font-size: 13px; }
.bubble.user { align-self: flex-end; background: var(--brand); color: #fff; border-bottom-right-radius: 4px; }
.bubble.master { align-self: flex-start; background: #f1f5f9; color: var(--ink); border-bottom-left-radius: 4px; }
.card { align-self: stretch; background: #fff; border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; box-shadow: var(--shadow-1); }
.master-card { border-left: 3px solid var(--brand); }
.master-card.tone-fail, .todo-card.tone-fail { border-left-color: var(--fail); }
.card-list { margin: 8px 0 0; padding-left: 18px; font-size: 12px; }
.card-list li { margin: 2px 0; }
.todo-card { border-left: 3px solid var(--cta); }
.todo-prompt { margin: 8px 0; font-size: 12px; }
.todo-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.baode-root .btn {
font-size: 13px; padding: 7px 14px; border-radius: 8px; cursor: pointer;
border: 1px solid var(--line); background: #fff; color: var(--ink);
transition: background 0.18s, border-color 0.18s, color 0.18s;
}
.baode-root .btn:hover { border-color: var(--brand); color: var(--brand-600); }
.baode-root a.btn { text-decoration: none; display: inline-flex; align-items: center; }
.baode-root .btn-primary { background: var(--brand); border-color: var(--brand); color: #fff; font-weight: 600; }
.baode-root .btn-primary:hover { background: var(--brand-600); border-color: var(--brand-600); color: #fff; }
.baode-root .btn-danger { background: var(--fail); border-color: var(--fail); color: #fff; font-weight: 600; }
.baode-root .btn-danger:hover { background: #991b1b; border-color: #991b1b; color: #fff; }
.baode-root .btn:disabled { opacity: 0.45; cursor: not-allowed; }
.baode-root .icon-btn {
width: 38px; height: 38px; display: grid; place-items: center; flex: none;
border: 1px solid var(--line); border-radius: 8px; background: #fff;
color: var(--brand-600); cursor: pointer; transition: border-color 0.18s;
}
.baode-root .icon-btn:hover { border-color: var(--brand); }
.baode-root .icon-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.composer { display: flex; gap: 8px; padding: 10px 12px; border-top: 1px solid var(--line); background: #fbfcfe; }
.composer input {
flex: 1; min-width: 0; height: 38px; padding: 0 12px;
border: 1px solid var(--line); border-radius: 8px; background: #fff; font: inherit; font-size: 13px;
}
.baode-root .btn:focus-visible, .baode-root .icon-btn:focus-visible, .composer input:focus-visible {
outline: 2px solid var(--brand); outline-offset: 2px;
}
/* ---------- 数据自检页(类名用 checkpage,避免与 supplier-platform 的 .page 冲突) ---------- */
.checkpage { max-width: 1080px; margin: 0 auto; padding: 32px 24px 64px; }
.checkpage h1 { font-size: 22px; margin: 0 0 4px; }
.checkpage h2 { font-size: 16px; margin: 28px 0 10px; }
.checkpage .sub { color: var(--muted); font-size: 13px; margin: 0 0 20px; }
.checkpage table { width: 100%; border-collapse: collapse; background: #fff; font-size: 13px; }
.checkpage th, .checkpage td { border: 1px solid var(--line); padding: 7px 10px; text-align: left; }
.checkpage th { background: #f3f4f6; }
.checkpage td.num { font-variant-numeric: tabular-nums; }
.checkpage .pass { color: var(--pass); font-weight: 600; }
.checkpage .fail { color: var(--fail); font-weight: 600; }
@keyframes floatIn { from { opacity: 0; translate: 0 6px; } to { opacity: 1; translate: 0 0; } }
@keyframes baode-pulse {
0%, 100% { box-shadow: 0 0 0 0 rgba(37, 99, 235, 0.35); }
50% { box-shadow: 0 0 0 6px rgba(37, 99, 235, 0); }
}
@media (prefers-reduced-motion: reduce) {
.baode-root * { animation: none !important; transition: none !important; }
}
+85
View File
@@ -0,0 +1,85 @@
/** 江苏宝得需求评审多智能体 cockpit · 业务域类型 */
export type IndustryCode = "CDU" | "储能" | "其他";
/** 内置需求样本编号(数据自检页使用);上传解析的需求以文件名为 id */
export type DemandPresetId = "A" | "B" | "C" | "D";
export type ProductCategory = "标品" | "非标品";
export type AgentKey = "feasibility" | "rnd" | "delivery" | "rating";
export type Verdict = "通过" | "不通过";
/** 依据表行(H7:每个结论都带依据表) */
export interface EvidenceRow {
label: string;
value: string;
verdict?: Verdict | null;
}
/** 智能体统一返回结构(规格 4.2):{结论, 依据[], 建议[], 时间戳} */
export interface AgentResult {
agent: AgentKey | "master";
conclusion: string;
verdict: Verdict | "路由";
evidence: EvidenceRow[];
suggestions: string[];
}
/** 客户主数据(规格 5.1,金额单位:元) */
export interface CustomerMaster {
code: string;
name: string;
shortName: string;
industry: IndustryCode;
creditLimit: number;
stockUnpickedAmount: number;
cancelledOrderAmount: number;
margin12mAvg: number;
groupMargin12mAvg: number;
salesRep: { code: string; margin12mAvg: number };
reconciliation: { system: string; cyclesPerYear: number; currentPeriodConfirmed: boolean };
provenance: string;
}
/** 上传文档解析后的结构化需求(规格 5.2) */
export interface Demand {
id: string;
label: string;
customerCode: string;
document: { fileName: string; fileType: "docx" | "txt" };
parsed: {
industry: IndustryCode | null;
productType: string;
quantity: number;
unitPrice: number;
deliveryDate: string;
coilMaterial: string;
};
missingFields: Array<"industry">;
followUp: { field: "industry"; prompt: string; options: IndustryCode[] } | null;
provenance: string;
}
/** BOM 行(规格 5.3 + 客户 ERP 截图:维护BOM信息画面) */
export interface BomLine {
seq: number;
itemCode: string;
itemName: string;
spec: string;
qtyPerUnit: number;
unitPrice: number;
totalPrice: number;
category: string;
status: "生效" | "失效";
level: 1 | 2;
parentSeq?: number;
material?: "304" | "316L";
kind?: "coil" | "plate";
qtyDisplay?: string;
note?: string;
}
export interface SteelCoil {
material: "304" | "316L";
itemCode: string;
kgPerUnit: number;
unitPrice: number;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
@@ -1,10 +1,21 @@
import axios from 'axios'
import { APP_TOKEN, getUserToken } from '@/shared/services/iamAuth'
const api = axios.create({
baseURL: '/bexapi',
timeout: 10000,
})
// 请求拦截器:为 /bexapi 请求注入 IAM 鉴权头
api.interceptors.request.use((config) => {
config.headers['digi-middleware-auth-app'] = APP_TOKEN
const userToken = getUserToken()
if (userToken) {
config.headers['digi-middleware-auth-user'] = userToken
}
return config
})
// 系统参数
export const sysParameterApi = {
list: () => api.get('/sys-parameters/'),
@@ -12,7 +12,9 @@ export default function Drawer({ open, title, onClose, children, width = 540 }:
}, [open, onClose]);
return createPortal(
<>
// 模块根容器包裹层:为 portal 内容提供 .bomx-app 作用域下的 CSS 变量;
// overlay/panel 均 position:fixed,且平台 body 为 overflow:hidden,包裹层不影响布局
<div className="bomx-app">
{/* 遮罩:覆盖全屏(含导航条),点击任意非抽屉区域关闭 */}
{open && <div className="drawer-overlay" onClick={onClose} />}
@@ -29,7 +31,7 @@ export default function Drawer({ open, title, onClose, children, width = 540 }:
</div>
<div className="drawer-content">{children}</div>
</div>
</>,
</div>,
document.body
);
}
+13 -13
View File
@@ -3,7 +3,7 @@
风格:Premium Light · 深度层次 · 流畅交互
============================================================ */
:root {
.bomx-app {
--header-h: 64px;
/* 品牌渐变 */
--grad-brand: linear-gradient(135deg, #6366F1 0%, #8B5CF6 50%, #A855F7 100%);
@@ -85,9 +85,9 @@
z-index: 0;
}
::-webkit-scrollbar { width: 8px; height: 8px; }
::-webkit-scrollbar-thumb { background: var(--line-2); border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: var(--text-3); }
.bomx-app ::-webkit-scrollbar { width: 8px; height: 8px; }
.bomx-app ::-webkit-scrollbar-thumb { background: var(--line-2); border-radius: 4px; }
.bomx-app ::-webkit-scrollbar-thumb:hover { background: var(--text-3); }
/* ===== Header ===== */
.app-header {
@@ -260,7 +260,7 @@
.btn-sm { height: 32px; padding: 0 13px; font-size: 12px; border-radius: var(--r-sm); }
/* ===== Form ===== */
input[type="text"], input[type="number"], select {
.bomx-app input[type="text"], .bomx-app input[type="number"], .bomx-app select {
height: 38px;
padding: 0 13px;
border: 1px solid var(--line-2);
@@ -273,7 +273,7 @@ input[type="text"], input[type="number"], select {
transition: all var(--t-fast) var(--ease);
}
input:focus, select:focus {
.bomx-app input:focus, .bomx-app select:focus {
border-color: var(--indigo);
box-shadow: 0 0 0 3px rgba(99,102,241,0.14);
}
@@ -589,7 +589,7 @@ input:focus, select:focus {
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes bomx-fade-in { from { opacity: 0; } to { opacity: 1; } }
.drawer {
position: fixed;
@@ -645,7 +645,7 @@ input:focus, select:focus {
display: flex;
align-items: center;
justify-content: center;
animation: fade-in 0.2s ease;
animation: bomx-fade-in 0.2s ease;
}
.confirm-modal {
@@ -743,10 +743,10 @@ input:focus, select:focus {
.checkbox-label { display: inline-flex; align-items: center; gap: 7px; cursor: pointer; }
.checkbox-label input { width: 16px; height: 16px; accent-color: var(--indigo); cursor: pointer; }
:focus-visible { outline: 2px solid var(--indigo); outline-offset: 2px; }
.bomx-app :focus-visible { outline: 2px solid var(--indigo); outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
.bomx-app *, .bomx-app *::before, .bomx-app *::after { animation-duration: 0.01ms !important; transition-duration: 0.01ms !important; }
}
/* ===== 修复:BOM 树表头列样式统一 ===== */
@@ -896,11 +896,11 @@ input:focus, select:focus {
border: 2.5px solid var(--line-1);
border-top-color: var(--accent-primary);
border-radius: 50%;
animation: spin 0.8s linear infinite;
animation: bomx-spin 0.8s linear infinite;
flex-shrink: 0;
}
@keyframes spin {
@keyframes bomx-spin {
to { transform: rotate(360deg); }
}
@@ -1168,7 +1168,7 @@ input:focus, select:focus {
border: 2px solid var(--indigo-soft);
border-top-color: var(--indigo);
border-radius: 50%;
animation: spin 0.7s linear infinite;
animation: bomx-spin 0.7s linear infinite;
}
/* 阶段信息 */
+172
View File
@@ -0,0 +1,172 @@
import './index.css';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { ThemeProvider, useTheme } from './context/ThemeContext';
import { useText } from './i18n/useText';
import { initDatabase } from './data/sqlite';
import { useMecData } from './hooks/useMecData';
import { CURRENT_PERIOD, projectAt, projectTree } from './lib/time';
import MecHeader from './components/MecHeader';
import StarBackground from './components/StarBackground';
import DemandPanel from './components/DemandPanel';
import MetricWorkspace from './components/MetricWorkspace';
import SupplyPanel from './components/SupplyPanel';
import type { ViewProps } from './components/workspace/views';
import type { ExpertTeam } from './lib/teams';
const GAP = 36;
function AppInner() {
const { tokens } = useTheme();
const { t } = useText();
const [dbReady, setDbReady] = useState(false);
const [dbError, setDbError] = useState<string | null>(null);
const [dbTimedOut, setDbTimedOut] = useState(false);
useEffect(() => {
let settled = false;
// 看门狗:WASM 请求挂起时不再无限转圈
const watchdog = setTimeout(() => { if (!settled) setDbTimedOut(true); }, 20000);
initDatabase()
.then(() => { settled = true; clearTimeout(watchdog); setDbReady(true); })
.catch((e: unknown) => { settled = true; clearTimeout(watchdog); setDbError((e as Error).message); });
return () => { settled = true; clearTimeout(watchdog); };
}, []);
const data = useMecData(dbReady);
const [selected, setSelected] = useState('OV');
/* 左栏=销售订单 / 客户资料两个页签,右栏=采购单 / 生产工单 / 供应商资料三个页签;点选订单后两侧联动过滤 */
const [selectedSO, setSelectedSO] = useState<string | null>(null);
/* 缺省两侧收起:首屏中间内容区更平衡,用户需要时再展开 */
const [leftOpen, setLeftOpen] = useState(false);
const [rightOpen, setRightOpen] = useState(false);
const [netStage, setNetStage] = useState(false);
const [team, setTeam] = useState<ExpertTeam | null>(null);
/* 全局时间游标(0-11):知识图谱与因果看板按此时点重算取值与状态 */
const [period, setPeriod] = useState(CURRENT_PERIOD);
const onSelect = useCallback((code: string) => {
if (code) setSelected(code);
}, []);
/* 时间滑块拖动 / 回放:单一游标源,图谱与看板同一时点读数 */
const onPeriod = useCallback((p: number) => setPeriod(p), []);
// 指标网络全景舞台:ESC 退出(捕获阶段注册,子组件阻断冒泡也生效)
useEffect(() => {
if (!netStage) return;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setNetStage(false); };
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [netStage]);
// 专家团会诊状态:中央对话区仍消费 team / onDismissTeam
const onDismissTeam = useCallback(() => setTeam(null), []);
/* 游标投影:一处把时点值与定级贴回节点,下游(指标树 / 明细 / 趋势 / 结构 / 驾驶舱 /
图谱 / 因果看板 / 对话区)的当期口径自动变成“数据期口径”,避免逐点改造遗漏。
trend 不投影,回看历史与预测仍拿得到完整 12 期。 */
const view = useMemo(() => {
if (period === CURRENT_PERIOD) return { tree: data.tree, flat: data.flat, byCode: data.byCode };
const tree = projectTree(data.tree, period);
const flat = data.flat.map(n => projectAt(n, period));
return { tree, flat, byCode: new Map(flat.map(n => [n.code, n] as const)) };
}, [data, period]);
const viewProps = useMemo<ViewProps>(
() => ({ selected, byCode: view.byCode, flat: view.flat, links: data.links, onSelect, period }),
[selected, view.byCode, view.flat, data.links, onSelect, period],
);
if (!dbReady) {
const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null);
return (
<div className="jieya-root" style={{
width: '100vw', height: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
background: tokens.bodyBgImage, color: tokens.textSub, fontSize: 14,
}}>
<style>{`@keyframes mec-spin { to { transform: rotate(360deg); } }`}</style>
{!errMsg ? (
<div style={{ textAlign: 'center' }}>
<div style={{
width: 40, height: 40, border: `3px solid ${tokens.border}`, borderTopColor: tokens.accent,
borderRadius: '50%', margin: '0 auto 16px', animation: 'mec-spin 1s linear infinite',
}} />
{t.common.initializing}
</div>
) : (
<div style={{ maxWidth: 560, textAlign: 'center' }}>
<div style={{ color: tokens.danger, marginBottom: 6, fontWeight: 600 }}>{t.common.initFailed}</div>
<div style={{ fontSize: 12, color: tokens.textSub, wordBreak: 'break-all', marginBottom: 10 }}>{errMsg}</div>
<div style={{ fontSize: 11, color: tokens.textMuted, marginBottom: 14, fontFamily: 'monospace' }}>{location.host}</div>
<button
onClick={() => window.location.reload()}
style={{
padding: '6px 20px', fontSize: 13, cursor: 'pointer', borderRadius: 6,
background: tokens.accentBg, color: tokens.accent, border: `1px solid ${tokens.border}`,
}}
>
{t.common.retry}
</button>
</div>
)}
</div>
);
}
return (
<div className="jieya-root" style={{
width: '100vw', height: '100vh', display: 'flex', flexDirection: 'column',
background: tokens.bodyBgImage, color: tokens.text, overflow: 'hidden',
position: 'relative',
}}>
{/* 流动透明球体科技感背景层 */}
<StarBackground />
{/* 内容层:置于背景球体之上 */}
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1, minHeight: 0 }}>
<MecHeader period={period} />
{/* 三栏:左=销售订单 / 客户资料,中=指标工作区(底部内嵌对话区),右=采购单 / 生产工单 / 供应商资料 */}
<div style={{
flex: 1, display: 'flex', minHeight: 0, alignItems: 'stretch', padding: '28px 0 20px',
}}>
<DemandPanel
expanded={leftOpen}
onToggle={() => setLeftOpen(v => !v)}
selectedSO={selectedSO}
onSelectSO={setSelectedSO}
/>
<div style={{ width: GAP, flexShrink: 0 }} />
<MetricWorkspace
selected={selected} staff={data.staff} viewProps={viewProps}
period={period} onPeriod={onPeriod}
netStage={netStage} onExitNetStage={() => setNetStage(false)}
team={team} onDismissTeam={onDismissTeam}
onLocateSO={so => { setSelectedSO(so); setLeftOpen(true); setRightOpen(true); }}
/>
<div style={{ width: GAP, flexShrink: 0 }} />
<SupplyPanel
expanded={rightOpen}
onToggle={() => setRightOpen(v => !v)}
selectedSO={selectedSO}
onSelectSO={setSelectedSO}
/>
</div>
</div>
</div>
);
}
export default function App() {
return (
<ThemeProvider>
<AppInner />
</ThemeProvider>
);
}
@@ -0,0 +1,413 @@
import { useEffect, useMemo, useRef } from 'react';
import { ArrowRight, Ban, Bot, ChevronDown, ChevronsDown, ChevronUp, ChevronsUp, Layers, Radio, Send, Sparkles, User, Users } from 'lucide-react';
import { useTheme } from '../context/ThemeContext';
import type { ThemeTokens } from '../context/ThemeContext';
import { useText } from '../i18n/useText';
import type { I18n } from '../i18n/locales';
import type { DigitalStaff } from '../data/sqlite';
import { SUGGESTED } from '../lib/ibpAsk';
import { alertColor, fmt } from '../lib/metric';
import type { ConsultTurn, ExpertTeam, MetricSnap } from '../lib/teams';
import type { AgentChat } from '../hooks/useAgentChat';
import AskAnswerCard, { StepTrace } from './agent/AskAnswerCard';
interface AgentDockProps {
/** 在岗数字员工:头部状态点 */
staff: DigitalStaff[];
/** 会话状态机由父级持有:本体舞台换掉内容区时对话历史不丢 */
chat: AgentChat;
/** 专家团:非空时对话区切换为多智能体轮流会诊 */
team: ExpertTeam | null;
onDismissTeam: () => void;
/** 建议动作「定位到订单」:在左栏选中该销售订单 */
onLocateSO?: (so: string) => void;
/** 建议动作「打开业务本体总览」:切到本体页 */
onOpenOntology?: () => void;
/** 高度由父级持有,全屏切换时不丢失展开状态 */
height: number;
onToggle: () => void;
/** 拉高态:对话区进一步往上拉高(第三高度档) */
tall: boolean;
onToggleTall: () => void;
}
const levelColor = (lv: MetricSnap['level'], tk: ThemeTokens) =>
lv === 'good' ? tk.success : lv === 'warn' ? tk.warning : tk.danger;
/** 成员卡内的一行:小标签 + 文本 */
function SecRow({ label, text, tk, color }: { label: string; text?: string; tk: ThemeTokens; color?: string }) {
if (!text) return null;
return (
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
<span style={{
flex: '0 0 auto', fontSize: 10.5, fontWeight: 700, marginTop: 1, padding: '1px 6px', borderRadius: 6,
color: color ?? tk.textMuted,
background: color ? `${color}1a` : tk.panelBgAlt,
border: `1px solid ${color ? `${color}33` : tk.border}`,
}}>{label}</span>
<span style={{ fontSize: 12.5, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>{text}</span>
</div>
);
}
/** 专家成员发言卡:指标数据条 + 现状/观点/建议 + 移交衔接 */
function MemberCard({ turn, tk, t, time }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string }) {
const m = turn.metric;
const lc = m ? levelColor(m.level, tk) : tk.accent;
return (
<div className="content-reveal" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
<div style={{ maxWidth: '92%', minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
<span style={{ width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0, background: tk.cardBg, border: `1px solid ${tk.border}` }}>
<User size={11} color={tk.accent} />
</span>
<span style={{ fontSize: 12.5, fontWeight: 700, color: tk.text, flexShrink: 0 }}>{turn.name}</span>
{turn.tag && <span style={{ fontSize: 10.5, color: tk.textMuted, padding: '0 6px', borderRadius: 7, border: `1px solid ${tk.border}`, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160 }}>{turn.tag}</span>}
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums' }}>{time}</span>
</div>
<div style={{ background: tk.cardBg, border: `1px solid ${tk.border}`, borderLeft: `3px solid ${lc}`, borderRadius: '4px 10px 10px 10px', padding: '9px 11px', display: 'flex', flexDirection: 'column', gap: 7 }}>
{m && (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '5px 9px', borderRadius: 8, background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}` }}>
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: tk.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.label}</span>
<span style={{ fontSize: 13, fontWeight: 700, color: tk.text, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{m.value}</span>
<span style={{ fontSize: 11, fontWeight: 700, color: lc, background: `${lc}1a`, border: `1px solid ${lc}33`, borderRadius: 6, padding: '0 6px', fontVariantNumeric: 'tabular-nums' }}>{fmt(m.rate, 0)}%</span>
<span style={{ fontSize: 11.5, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{m.gap}</span>
</div>
)}
<SecRow label={t.agent.secStatus} text={turn.status} tk={tk} />
<SecRow label={t.agent.secStance} text={turn.stance} tk={tk} color={lc} />
<SecRow label={t.agent.secProposal} text={turn.proposal} tk={tk} color={tk.accent} />
{turn.handoff && (
<div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 11, color: tk.textMuted }}>
<ArrowRight size={11} color={tk.accent} style={{ flexShrink: 0 }} />
{t.agent.handoff} →
<span style={{ color: tk.accent, fontWeight: 700 }}>{turn.handoff}</span>
</div>
)}
</div>
</div>
</div>
);
}
/** 牵头结论卡:结论 headline + 成员要点 + 研判数据条 + 联合行动清单 */
function LeadCard({ turn, tk, t, time }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string }) {
const j = turn.judge;
const lc = j ? levelColor(j.level, tk) : tk.accent;
const marks = ['①', '②', '③'];
return (
<div className="content-reveal" style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
<div style={{ maxWidth: '94%', minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
<span style={{ width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0, background: `linear-gradient(135deg, ${tk.accent}, ${tk.info})` }}>
<Sparkles size={11} color={tk.onAccent} />
</span>
<span style={{ fontSize: 12.5, fontWeight: 700, color: tk.accent, flexShrink: 0 }}>{turn.name}</span>
{turn.tag && <span style={{ fontSize: 10.5, color: tk.accent, padding: '0 6px', borderRadius: 7, border: `1px solid ${tk.borderAccent}`, background: tk.accentBg, whiteSpace: 'nowrap' }}>{turn.tag}</span>}
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums' }}>{time}</span>
</div>
<div style={{ background: tk.accentBg, border: `1px solid ${tk.borderAccent}`, borderRadius: '4px 12px 12px 12px', padding: '10px 12px', display: 'flex', flexDirection: 'column', gap: 9, boxShadow: `0 0 0 1px ${tk.accent}1f` }}>
{turn.conclusion && (
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
<span style={{ flex: '0 0 auto', fontSize: 10.5, fontWeight: 700, color: tk.accent, background: `${tk.accent}1a`, border: `1px solid ${tk.borderAccent}`, borderRadius: 6, padding: '1px 6px', marginTop: 1 }}>{t.agent.concl}</span>
<span style={{ fontSize: 13, fontWeight: 700, lineHeight: 1.6, color: tk.text, minWidth: 0 }}>{turn.conclusion}</span>
</div>
)}
{!!turn.summary?.length && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.keypoints}</span>
{turn.summary.map((srow, i) => (
<div key={i} style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
<span style={{ width: 5, height: 5, borderRadius: 5, background: tk.accent, flex: '0 0 5px', marginTop: 6 }} />
<span style={{ fontSize: 12, color: tk.text, fontWeight: 600, flexShrink: 0 }}>{srow.name}</span>
<span style={{ fontSize: 12, color: tk.textSub, minWidth: 0 }}>{srow.point}</span>
</div>
))}
</div>
)}
{j && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.judgeLabel}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: 9, padding: '6px 10px', borderRadius: 8, background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}` }}>
<span style={{ fontSize: 20, fontWeight: 800, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', lineHeight: 1 }}>{fmt(j.rate, 0)}%</span>
<span style={{ flex: 1, minWidth: 0, fontSize: 12, color: tk.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{j.label}{j.gap ? ` · ${j.gap}` : ''}</span>
<span style={{ fontSize: 11, fontWeight: 700, color: lc, background: `${lc}1a`, border: `1px solid ${lc}33`, borderRadius: 6, padding: '1px 7px', whiteSpace: 'nowrap' }}>{j.verdict}</span>
</div>
</div>
)}
{!!turn.actions?.length && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<span style={{ fontSize: 10.5, fontWeight: 700, color: tk.textMuted, letterSpacing: '0.04em' }}>{t.agent.actionsLabel}</span>
{turn.actions.map((a, i) => (
<div key={i} style={{ display: 'flex', gap: 7, alignItems: 'flex-start' }}>
<span style={{ flex: '0 0 auto', fontSize: 12, color: tk.accent, fontWeight: 700, lineHeight: 1.5 }}>{marks[i] ?? '·'}</span>
<span style={{ fontSize: 12, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>
<span style={{ color: tk.text, fontWeight: 600 }}>{a.owner}</span>
<span style={{ color: tk.textMuted }}>({a.role})</span> {a.action}
</span>
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
export default function AgentDock({ staff, chat, team, onDismissTeam, onLocateSO, onOpenOntology, height, onToggle, tall, onToggleTall }: AgentDockProps) {
const { tokens } = useTheme();
const { t } = useText();
/* 会话状态机在父级:本组件只管渲染与滚动,进出本体舞台都不会丢掉对话历史 */
const { msgs, pending, thinking, busy, draft, setDraft, ask, reset } = chat;
const listRef = useRef<HTMLDivElement>(null);
const onDuty = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
const nameOf = (s: DigitalStaff) => (s.name_zh);
/* 新消息、思考步骤逐条揭示、高度变化都要贴底:对话区高度有限,
用户不该往下翻找刚出现的回答卡 */
useEffect(() => {
const el = listRef.current;
if (el) el.scrollTop = el.scrollHeight;
}, [msgs, pending, thinking, height]);
const expanded = height > 120;
const dotColor = (s: DigitalStaff) => alertColor(s.status === 'alert' ? 'red' : 'green', tokens);
return (
<div style={{
flexShrink: 0, position: 'relative', zIndex: 2,
background: tokens.panelBgAlt, borderRadius: '0 0 16px 16px',
display: 'flex', flexDirection: 'column', overflow: 'hidden', height,
transition: 'height 0.28s cubic-bezier(0.22,1,0.36,1)',
}}>
{/* 与上方工作区的分隔饰条:中央亮渐变主线 + 下溢光晕 + 菱形饰点,比 1px 实线更清晰且有仪式感 */}
<div style={{ flexShrink: 0, position: 'relative', height: 9 }}>
<div style={{
position: 'absolute', left: 0, right: 0, top: 3, height: 2,
background: `linear-gradient(90deg, transparent, ${tokens.accent}55 15%, ${tokens.accent}b3 50%, ${tokens.accent}55 85%, transparent)`,
}} />
<div style={{
position: 'absolute', left: 0, right: 0, top: 5, height: 4,
background: `linear-gradient(to bottom, ${tokens.accentGlow}, transparent)`,
}} />
<div style={{
position: 'absolute', left: '50%', top: 4, width: 7, height: 7,
transform: 'translate(-50%, -50%) rotate(45deg)',
background: tokens.accent, boxShadow: `0 0 8px ${tokens.accentGlow}`,
}} />
<div style={{ position: 'absolute', left: '12%', top: 4, width: 3, height: 3, transform: 'translate(-50%, -50%) rotate(45deg)', background: `${tokens.accent}88` }} />
<div style={{ position: 'absolute', left: '88%', top: 4, width: 3, height: 3, transform: 'translate(-50%, -50%) rotate(45deg)', background: `${tokens.accent}88` }} />
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px', flexShrink: 0 }}>
<span style={{
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
background: `linear-gradient(135deg, ${tokens.accent}, ${tokens.info})`,
}}>
<Bot size={13} color={tokens.onAccent} strokeWidth={2.2} />
</span>
<span style={{ color: tokens.text, fontSize: 14.5, fontWeight: 700, letterSpacing: '0.03em' }}>{t.agent.title}</span>
<span style={{ flex: 1 }} />
<span style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
{onDuty.slice(0, 4).map(s => (
<span key={s.code} title={nameOf(s)} style={{
width: 7, height: 7, borderRadius: '50%', background: dotColor(s),
boxShadow: `0 0 6px ${dotColor(s)}`,
}} />
))}
</span>
<button
onClick={reset}
title={t.agent.clear}
className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 4, color: tokens.textMuted, fontSize: 12, border: 'none', background: 'transparent', cursor: 'pointer', padding: '2px 6px' }}
>
<Ban size={12} />{t.agent.clear}
</button>
<button
onClick={onToggleTall}
title={tall ? t.agent.tallOff : t.agent.tall}
className="ghost-btn"
style={{
display: 'grid', placeItems: 'center', width: 24, height: 24, borderRadius: 8, cursor: 'pointer', flexShrink: 0,
color: tall ? tokens.onAccent : tokens.accent,
background: tall ? tokens.accent : tokens.accentBg,
border: `1px solid ${tokens.borderAccent}`,
}}
>
{tall ? <ChevronsDown size={13} /> : <ChevronsUp size={13} />}
</button>
<button
onClick={onToggle}
title={expanded ? t.agent.collapse : t.agent.expand}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 3, color: tokens.accent, fontSize: 12, fontWeight: 600,
border: `1px solid ${tokens.borderAccent}`, background: tokens.accentBg, borderRadius: 12, padding: '2px 9px', cursor: 'pointer', flexShrink: 0,
}}
>
{expanded ? <ChevronDown size={12} /> : <ChevronUp size={12} />}
{expanded ? t.agent.collapse : t.agent.expand}
</button>
</div>
{team && (
<div style={{
display: 'flex', alignItems: 'center', gap: 8, margin: '0 14px 6px', padding: '5px 10px',
borderRadius: 9, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`, flexShrink: 0,
}}>
<Users size={13} color={tokens.accent} style={{ flexShrink: 0 }} />
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.accent, flexShrink: 0 }}>{team.nameZh}</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
· {team.memberCodes.length} 位专家 · {team.topicZh}
</span>
<span style={{ flex: 1 }} />
<button
onClick={onDismissTeam}
title={t.team.dismiss}
className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: tokens.textMuted, border: 'none', background: 'transparent', cursor: 'pointer', padding: '2px 5px', flexShrink: 0 }}
>
<Ban size={11} />{t.team.dismiss}
</button>
</div>
)}
{expanded && (
<>
<div ref={listRef} className="space-scroll" style={{ flex: 1, overflowY: 'auto', padding: '2px 14px 0', minHeight: 0, display: 'flex', flexDirection: 'column' }}>
{/* 消息贴底:对话从输入框往上长,不留中段空洞(内容满时该占位自动压为 0,不影响滚动) */}
<div style={{ flex: '1 0 0px', minHeight: 0 }} />
{msgs.map(m => {
/* 专家团就位播报:居中虚线卡,区别于专家发言 */
if (m.kind === 'system') {
return (
<div key={m.id} className="content-reveal" style={{ display: 'flex', justifyContent: 'center', marginBottom: 8 }}>
<div style={{
maxWidth: '94%', padding: '7px 12px', borderRadius: 10, whiteSpace: 'pre-wrap', textAlign: 'center',
background: tokens.accentBg, border: `1px dashed ${tokens.borderAccent}`,
color: tokens.textSub, fontSize: 12.5, lineHeight: 1.6,
}}>
<span style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 5, color: tokens.accent, fontWeight: 700, marginBottom: 3 }}>
<Radio size={11} />{m.name} · {m.tag}
</span>
{m.text}
</div>
</div>
);
}
if ((m.kind === 'member' || m.kind === 'lead') && m.turn) {
return m.kind === 'member'
? <MemberCard key={m.id} turn={m.turn} tk={tokens} t={t} time={m.time} />
: <LeadCard key={m.id} turn={m.turn} tk={tokens} t={t} time={m.time} />;
}
/* 单轮问答:折叠的思考过程条 + 规范回答卡(结论/关键数字/明细/依据/行动/来源) */
if (m.role === 'ai' && m.answer) {
return (
<AskAnswerCard
key={m.id} answer={m.answer} elapsed={m.elapsed ?? 0} tk={tokens} t={t} time={m.time} staff={m.staff}
onLocate={so => onLocateSO?.(so)}
onAsk={q => ask(q)}
onOntology={() => onOpenOntology?.()}
/>
);
}
const consult = m.kind === 'member' || m.kind === 'lead';
const isLead = m.kind === 'lead';
return (
<div key={m.id} className={consult ? 'content-reveal' : undefined} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start', marginBottom: 8 }}>
<div style={{ maxWidth: consult ? '90%' : '76%', minWidth: 0 }}>
{consult && (
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
<span style={{
width: 18, height: 18, borderRadius: 6, display: 'grid', placeItems: 'center', flexShrink: 0,
background: isLead ? `linear-gradient(135deg, ${tokens.accent}, ${tokens.info})` : tokens.cardBg,
border: `1px solid ${isLead ? 'transparent' : tokens.border}`,
}}>
<User size={11} color={isLead ? tokens.onAccent : tokens.accent} />
</span>
<span style={{ fontSize: 12.5, fontWeight: 700, color: isLead ? tokens.accent : tokens.text, flexShrink: 0 }}>{m.name}</span>
{m.tag && (
<span style={{ fontSize: 10.5, color: tokens.textMuted, padding: '0 6px', borderRadius: 7, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 160 }}>{m.tag}</span>
)}
{isLead && <Sparkles size={11} color={tokens.accent} style={{ flexShrink: 0 }} />}
</div>
)}
<div style={{
padding: '8px 12px', fontSize: 13.5, lineHeight: 1.65, whiteSpace: 'pre-wrap',
borderRadius: m.role === 'user' ? '10px 10px 3px 10px' : '10px 10px 10px 3px',
background: m.role === 'user' ? `${tokens.accent}22` : isLead ? tokens.accentBg : tokens.cardBg,
border: `1px solid ${m.role === 'user' ? `${tokens.accent}44` : isLead ? tokens.borderAccent : tokens.border}`,
color: m.role === 'user' ? tokens.text : tokens.textSub,
boxShadow: isLead ? `0 0 0 1px ${tokens.accent}1f` : 'none',
}}>{m.text}</div>
<div style={{ display: 'flex', gap: 6, marginTop: 3, justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
{m.staff && (
<span style={{ color: m.role === 'user' ? tokens.textMuted : tokens.accent, fontSize: 11, display: 'flex', alignItems: 'center', gap: 3 }}>
{m.role === 'ai' && <Sparkles size={10} />}{m.staff}
</span>
)}
<span style={{ color: tokens.textMuted, fontSize: 11, fontVariantNumeric: 'tabular-nums' }}>{m.time}</span>
</div>
</div>
</div>
);
})}
{/* 思考中:已揭示的步骤逐条出现,未揭示的只显示当前这步在做什么 */}
{pending && (
<div style={{ marginBottom: 8 }}>
<StepTrace steps={pending.answer.steps} revealed={pending.revealed} running tk={tokens} t={t} />
</div>
)}
{thinking && (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '6px 10px', background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 10, width: 'fit-content' }}>
<span style={{ display: 'flex', gap: 3 }}>
{[0, 1, 2].map(i => <i key={i} className="typing-dot" style={{ animationDelay: `${i * 0.16}s` }} />)}
</span>
<span style={{ color: tokens.textMuted, fontSize: 12 }}>{t.agent.thinking}…</span>
</div>
)}
</div>
<div style={{ display: 'flex', gap: 6, padding: '0 14px 6px', flexWrap: 'wrap', flexShrink: 0 }}>
{SUGGESTED.map(q => (
<button key={q} onClick={() => ask(q)} disabled={busy} className="ghost-btn" style={{
color: busy ? tokens.textMuted : tokens.textSub, fontSize: 12, border: `1px solid ${tokens.border}`, background: tokens.cardBg,
borderRadius: 20, padding: '4px 11px', cursor: busy ? 'default' : 'pointer', whiteSpace: 'nowrap',
opacity: busy ? 0.55 : 1,
}}>{q}</button>
))}
</div>
</>
)}
<div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '0 14px 10px', flexShrink: 0 }}>
<Layers size={14} color={tokens.textMuted} style={{ flexShrink: 0 }} />
<input
value={draft}
onChange={e => setDraft(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter') ask(draft); }}
onFocus={() => { if (!expanded) onToggle(); }}
placeholder={t.agent.placeholder}
style={{
flex: 1, minWidth: 0, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
borderRadius: 10, padding: '8px 12px', color: tokens.text, fontSize: 13.5, outline: 'none',
}}
/>
<button
onClick={() => ask(draft)}
disabled={!draft.trim() || busy}
style={{
display: 'flex', alignItems: 'center', gap: 5, padding: '7px 14px', borderRadius: 10, border: 'none',
background: !draft.trim() || busy ? tokens.border : tokens.accent,
color: tokens.onAccent, fontSize: 13, fontWeight: 700,
cursor: !draft.trim() || busy ? 'default' : 'pointer', transition: 'background 0.18s ease', flexShrink: 0,
}}
>
<Send size={13} />{t.agent.send}
</button>
</div>
</div>
);
}
@@ -0,0 +1,124 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Building2, Search, ShoppingCart, X } from 'lucide-react';
import PanelShell, { CountBadge } from './layout/PanelShell';
import { AutoScrollProvider, AutoScrollToggle } from './layout/AutoScroll';
import { LEFT_MOTION } from '../hooks/useAutoScroll';
import { useTheme } from '../context/ThemeContext';
import SalesOrderList, { filterSalesOrders } from './demand/SalesOrderList';
import CustomerList, { buildCustomers, filterCustomers } from './demand/CustomerList';
import { salesOrders } from '../data/ibp';
type TabKey = 'so' | 'cus';
interface Props {
expanded: boolean;
onToggle: () => void;
/** 当前选中的销售订单号:本页两个页签与右侧供应栏共用同一联动游标 */
selectedSO: string | null;
onSelectSO: (so: string | null) => void;
}
const TABS: { key: TabKey; label: string; short: string; icon: typeof ShoppingCart; placeholder: string }[] = [
{ key: 'so', label: '销售订单', short: '订单', icon: ShoppingCart, placeholder: '搜索订单号 / 客户 / 产品编码' },
{ key: 'cus', label: '客户资料', short: '客户', icon: Building2, placeholder: '搜索客户编码 / 简称 / 分类 / 部门' },
];
/**
* 左侧需求栏:销售订单与客户资料两个页签共用一块弧板,
* 搜索关键词、展开态与选中订单联动在两者之间保持同一份状态。
*/
export default function DemandPanel({ expanded, onToggle, selectedSO, onSelectSO }: Props) {
const { tokens } = useTheme();
const [tab, setTab] = useState<TabKey>('so');
/* 外部定位(对话卡的「定位到订单」/ 本体页明细行)把订单选中时切回销售订单页签,
否则停在客户资料页签会让用户以为点了没反应 */
const prevSO = useRef(selectedSO);
useEffect(() => {
if (selectedSO && selectedSO !== prevSO.current) setTab('so');
prevSO.current = selectedSO;
}, [selectedSO]);
const [query, setQuery] = useState('');
/* 卡片多到一屏装不下时自动缓慢下滚;标题栏按钮可关闭,页签之间共用这一个开关 */
const [autoScroll, setAutoScroll] = useState(true);
/* 徽标数与页签内容走同一组纯函数,标题数字不会和列表条数打架 */
const count = useMemo(() => {
const q = query.trim();
if (tab === 'so') return filterSalesOrders(salesOrders, q).length;
return filterCustomers(buildCustomers(selectedSO), q).length;
}, [tab, query, selectedSO]);
const segBtn = (active: boolean) => ({
display: 'flex' as const, alignItems: 'center' as const, justifyContent: 'center' as const,
gap: 5, flex: 1, minWidth: 0, padding: '5px 8px', borderRadius: 7,
fontSize: 13, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap' as const,
background: active ? tokens.accent : 'transparent',
color: active ? tokens.onAccent : tokens.textMuted,
border: `1px solid ${active ? tokens.accent : tokens.border}`,
});
const current = TABS.find(x => x.key === tab)!;
const Icon = current.icon;
return (
<PanelShell
side="left" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={<Icon size={16} />}
title={current.label}
badge={<CountBadge n={count} />}
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll(v => !v)} expanded={expanded} />}
animClass="space-animate-left"
tabs={
<>
{TABS.map(x => (
/* 收起态宽度只够两个字:页签用短标签,避免挤成一列竖排 */
<button key={x.key} style={segBtn(tab === x.key)} onClick={() => setTab(x.key)}>
{expanded ? x.label : x.short}
</button>
))}
</>
}
>
{/* 搜索:两个页签共用,占位提示随页签切换 */}
<div style={{ position: 'relative', marginBottom: 10, flex: '0 0 auto' }}>
<Search size={14} style={{ position: 'absolute', left: 10, top: 10, color: tokens.textMuted }} />
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder={current.placeholder}
style={{
width: '100%', padding: '8px 30px 8px 31px', fontSize: 13.5, borderRadius: 9,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, color: tokens.text,
outline: 'none',
}}
/>
{query && (
<button onClick={() => setQuery('')} style={{ position: 'absolute', right: 9, top: 11, color: tokens.textMuted, cursor: 'pointer', background: 'none', border: 'none' }}>
<X size={14} />
</button>
)}
</div>
<AutoScrollProvider value={{ enabled: autoScroll, cfg: LEFT_MOTION }}>
{tab === 'so' && (
<SalesOrderList
query={query}
expanded={expanded}
selectedSO={selectedSO}
onSelectSO={onSelectSO}
/>
)}
{tab === 'cus' && (
<CustomerList
query={query}
filterSO={selectedSO}
onClearFilter={() => onSelectSO(null)}
/* 点客户=带着它的编码切到销售订单页签,只看这家下的单 */
onPickCustomer={code => { setQuery(code); setTab('so'); }}
/>
)}
</AutoScrollProvider>
</PanelShell>
);
}
@@ -0,0 +1,451 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { ArrowLeft, Bot, Check, ChevronDown, MessagesSquare, Radar, Target, Users } from 'lucide-react';
import PanelShell, { PanelBody, CountBadge } from './layout/PanelShell';
import { useTheme } from '../context/ThemeContext';
import { useText } from '../i18n/useText';
import type { DigitalStaff, MetricNode } from '../data/sqlite';
import { customTeam, presetTeams } from '../lib/teams';
import type { ExpertTeam } from '../lib/teams';
interface Props {
expanded: boolean;
onToggle: () => void;
staff: DigitalStaff[];
byCode: Map<string, MetricNode>;
selected: string;
onViewMetric: (code: string) => void;
onWake: (s: DigitalStaff) => void;
/** 专家团:当前已就位的团队 + 组建回调 */
activeTeam: ExpertTeam | null;
onConvene: (t: ExpertTeam) => void;
}
type Status = DigitalStaff['status'];
export default function DigitalStaffPanel({
expanded, onToggle, staff, byCode, selected, onViewMetric, onWake, activeTeam, onConvene,
}: Props) {
const { tokens } = useTheme();
const { t } = useText();
const [filter, setFilter] = useState<Status | 'all'>('all');
const [open, setOpen] = useState<string | null>('METRIX');
const [view, setView] = useState<'staff' | 'team'>('staff'); // 数字员工列表 / 专家团组建
const [selCodes, setSelCodes] = useState<string[]>([]); // 自由勾选的成员(首位为牵头)
const [presetKey, setPresetKey] = useState<string | null>(null); // 当前选中的预设团
const [tick, setTick] = useState(0);
const scrollRef = useRef<HTMLDivElement | null>(null);
const hoverRef = useRef(false); // 鼠标进入列表即暂停,方便点卡
const coolRef = useRef(0); // 滚轮手动滚动后的冷却截止时刻
const statusMeta = (s: Status) => ({
working: { label: t.staff.busy, color: tokens.accent },
idle: { label: t.staff.idle, color: tokens.textMuted },
alert: { label: t.staff.alert, color: tokens.danger },
offline: { label: t.staff.offline, color: tokens.warning },
}[s]);
const list = useMemo(() => (filter === 'all' ? staff : staff.filter(s => s.status === filter)), [staff, filter]);
const online = staff.filter(s => s.status !== 'offline').length;
const totalTasks = staff.reduce((a, s) => a + s.tasks_today, 0);
const avgConf = staff.filter(s => s.confidence > 0).reduce((a, s, _i, arr) => a + s.confidence / arr.length, 0);
const escalations = staff.filter(s => s.status === 'alert').length;
// 动作轮播:只轮播在岗员工,避免"停用"卡片抢镜
const feed = useMemo(() => staff.filter(s => s.status !== 'offline'), [staff]);
useEffect(() => {
if (feed.length < 2) return;
const id = setInterval(() => setTick(v => (v + 1) % feed.length), 3400);
return () => clearInterval(id);
}, [feed.length]);
const active = feed.length ? feed[tick % feed.length] : null;
// 鼠标进入 / 滚轮手动滚动时暂停自动滚动,避免和用户抢滚动条
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const onWheel = () => { coolRef.current = performance.now() + 2200; };
const onEnter = () => { hoverRef.current = true; };
const onLeave = () => { hoverRef.current = false; };
el.addEventListener('wheel', onWheel, { passive: true });
el.addEventListener('pointerenter', onEnter);
el.addEventListener('pointerleave', onLeave);
return () => {
el.removeEventListener('wheel', onWheel);
el.removeEventListener('pointerenter', onEnter);
el.removeEventListener('pointerleave', onLeave);
};
}, []);
// 自动滚动:营造"员工一个个在干活"的现场感;到底停留 1.4s 后回顶循环。
// pos 是浮点累加器:26px/s 摊到 120Hz 每帧只有 0.22px,直接读改写 scrollTop 会被量化舍入吞掉而停摆
useEffect(() => {
let raf = 0;
let last = performance.now();
let pos = scrollRef.current ? scrollRef.current.scrollTop : 0;
let phase: 'down' | 'holdB' | 'up' | 'holdT' = 'down';
let until = 0;
const step = (now: number) => {
raf = requestAnimationFrame(step);
const el = scrollRef.current;
const dt = Math.min(0.05, (now - last) / 1000);
last = now;
if (!el || el.scrollHeight <= el.clientHeight + 4) return;
// 被门控暂停期间以真实 scrollTop 为准(用户可能滚轮动过),恢复时从那里续跑
if (hoverRef.current || now < coolRef.current) { pos = el.scrollTop; return; }
if (phase === 'down') {
if (pos + el.clientHeight >= el.scrollHeight - 2) { phase = 'holdB'; until = now + 1400; pos = el.scrollTop; }
else { pos += 26 * dt; el.scrollTop = pos; }
} else if (phase === 'holdB') {
pos = el.scrollTop;
if (now >= until) phase = 'up';
} else if (phase === 'up') {
pos -= pos * Math.min(1, dt * 5);
el.scrollTop = pos;
if (pos <= 0.5) { el.scrollTop = 0; pos = 0; phase = 'holdT'; until = now + 500; }
} else {
pos = el.scrollTop;
if (now >= until) phase = 'down';
}
};
raf = requestAnimationFrame(step);
return () => cancelAnimationFrame(raf);
}, []);
const chip = (key: Status | 'all', label: string, color?: string) => {
const on = filter === key;
return (
<button
key={key}
onClick={() => setFilter(key)}
style={{
fontSize: 11.5, padding: '2px 7px', borderRadius: 9, cursor: 'pointer', lineHeight: '17px', whiteSpace: 'nowrap' as const,
background: on ? `${color ?? tokens.accent}22` : 'transparent',
color: on ? (color ?? tokens.accent) : tokens.textMuted,
border: `1px solid ${on ? `${color ?? tokens.accent}55` : tokens.border}`,
}}
>{label}</button>
);
};
const presets = useMemo(() => presetTeams(), []);
// 预设团语义色 → 主题 token,让五张卡片有各自的色彩识别(不硬编码色值)
const toneColor = (tone: ExpertTeam['tone']) =>
({ success: tokens.success, danger: tokens.danger, info: tokens.info, warning: tokens.warning, accent: tokens.accent }[tone] ?? tokens.accent);
const nameOfStaff = (x: DigitalStaff) => (x.name_zh);
// 选中一个预设团:填充成员并停留在组建视图,便于直接发起或再微调
const pickPreset = (tm: ExpertTeam) => { setPresetKey(tm.id); setSelCodes(tm.memberCodes); };
// 勾选/取消一个智能体:脱离预设,转为自定义团
const toggleCode = (code: string) => {
setPresetKey(null);
setSelCodes(prev => (prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]));
};
const convene = () => {
if (selCodes.length < 2) return;
const preset = presetKey ? presets.find(x => x.id === presetKey) : null;
const tm = preset ?? customTeam(selCodes);
if (tm) onConvene(tm);
};
const openTeamView = () => { if (!expanded) onToggle(); setView('team'); };
return (
<PanelShell
side="right" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={expanded ? (view === 'team' ? <Users size={15} /> : <Bot size={15} />) : undefined}
title={view === 'team' ? t.team.panel : t.staff.title}
badge={view === 'team' ? <CountBadge n={selCodes.length} /> : <CountBadge n={`${online}/${staff.length}`} />}
extra={
<>
<button
onClick={() => (view === 'team' ? setView('staff') : openTeamView())}
title={t.team.entry}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
width: 22, height: 22, borderRadius: 5, cursor: 'pointer',
color: view === 'team' ? tokens.onAccent : tokens.accent,
background: view === 'team' ? tokens.accent : `${tokens.accent}1f`,
border: `1px solid ${view === 'team' ? tokens.accent : `${tokens.accent}55`}`,
}}
>
<Users size={12} />
</button>
</>
}
animClass="space-animate-right"
>
{view === 'staff' && (
<>
<div style={{ display: 'flex', gap: 3, flexWrap: 'wrap', marginBottom: 8, flex: '0 0 auto' }}>
{chip('all', t.staff.filterAll)}
{chip('working', t.staff.busy, tokens.accent)}
{chip('idle', t.staff.idle)}
{chip('alert', t.staff.alert, tokens.danger)}
{chip('offline', t.staff.offline, tokens.warning)}
</div>
<div style={{
display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 1, marginBottom: 8, flex: '0 0 auto',
background: tokens.border, border: `1px solid ${tokens.border}`, borderRadius: 8, overflow: 'hidden',
}}>
{[
{ k: t.staff.online, v: String(online) },
{ k: t.staff.tasks, v: String(totalTasks) },
{ k: t.staff.confidence, v: `${avgConf.toFixed(0)}%` },
{ k: t.staff.alert, v: String(escalations), warn: escalations > 0 },
].map(c => (
<div key={c.k} style={{ background: tokens.panelBgAlt, padding: '5px 4px', textAlign: 'center' }}>
<div style={{ fontSize: 17, fontWeight: 800, color: c.warn ? tokens.danger : tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.15 }}>{c.v}</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 1 }}>{c.k}</div>
</div>
))}
</div>
<PanelBody ref={scrollRef}>
{list.length === 0 && (
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>{t.staff.emptyFilter}</div>
)}
{list.map((s, i) => {
const meta = statusMeta(s.status);
const isOpen = open === s.code;
const bound = byCode.get(s.bound_metric);
const nm = (n: MetricNode | undefined) => (n ? (n.name_zh) : s.bound_metric);
return (
<div
key={s.code}
className="card-in"
style={{
animationDelay: `${i * 45}ms`,
border: `1px solid ${s.status === 'alert' ? `${tokens.danger}66` : isOpen ? tokens.borderAccent : tokens.border}`,
background: isOpen ? tokens.cardBg : tokens.panelBgAlt,
borderRadius: 10, marginBottom: 7, overflow: 'hidden',
}}
>
<div
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 9px', cursor: 'pointer' }}
onClick={() => {
// 收起态没有详情空间:先展开面板再开详情,避免"点了没反应"
if (!expanded) { onToggle(); setOpen(s.code); }
else setOpen(isOpen ? null : s.code);
}}
>
<span
className={s.status === 'working' || s.status === 'alert' ? 'dot-blink' : undefined}
style={{ width: 7, height: 7, borderRadius: 7, background: meta.color, flex: '0 0 7px', boxShadow: `0 0 7px ${meta.color}88` }}
/>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span
title={s.name_zh}
style={{ fontSize: 14.5, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}
>
{s.name_zh}
</span>
{/* 收起态 268px 放不下「9 字名 + code」,code 只在展开态显示 */}
{expanded && (
<span style={{ fontSize: 10, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace' }}>{s.code}</span>
)}
</div>
<div style={{ fontSize: 11.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{s.role_zh}
</div>
</div>
<div style={{ textAlign: 'right', flex: '0 0 auto' }}>
<div style={{ fontSize: 11.5, color: meta.color, fontWeight: 600 }}>{meta.label}</div>
<div style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.tasks_today} {t.staff.tasks}</div>
</div>
<ChevronDown size={13} style={{ color: tokens.textMuted, transform: `rotate(${isOpen ? 180 : 0}deg)`, transition: 'transform 0.2s', flex: '0 0 13px' }} />
</div>
<div style={{ padding: '0 9px 6px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
<div style={{ flex: 1, height: 3, borderRadius: 3, background: `${tokens.border}`, overflow: 'hidden' }}>
<div style={{ width: `${s.load_pct}%`, height: '100%', background: meta.color, transition: 'width 0.4s ease' }} />
</div>
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', width: 34, textAlign: 'right' }}>{s.load_pct}%</span>
</div>
{expanded && (
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
<Radar size={9} style={{ verticalAlign: -1, marginRight: 3, color: meta.color }} />
{s.cur_zh}
</div>
)}
</div>
{isOpen && expanded && (
<div style={{ padding: '2px 9px 9px', borderTop: `1px dashed ${tokens.border}`, marginTop: 2 }}>
<Row label={t.staff.skills} value={s.skill_zh} tokens={tokens} text={tokens.textSub} />
<Row label={t.staff.success} value={`${s.success_rate}%`} tokens={tokens} text={tokens.text} mono />
<Row label={t.staff.confidence} value={`${s.confidence}%`} tokens={tokens} text={tokens.text} mono />
<Row label={t.staff.lastRun} value={s.last_run} tokens={tokens} text={tokens.textMuted} />
<Row label={t.staff.current} value={s.cur_zh} tokens={tokens} text={tokens.textSub} />
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
<button
onClick={() => onViewMetric(s.bound_metric)}
className="ghost-btn"
style={{
flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
padding: '4px 6px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
border: `1px solid ${selected === s.bound_metric ? tokens.accent : tokens.border}`,
color: tokens.accent, background: tokens.accentBg,
}}
>
<Target size={11} />{nm(bound)}
</button>
<button
onClick={() => onWake(s)}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 4,
padding: '4px 10px', fontSize: 12, borderRadius: 7, cursor: 'pointer',
border: `1px solid ${tokens.accent}`, color: tokens.onAccent, background: tokens.accent,
opacity: s.status === 'offline' ? 0.45 : 1,
}}
>
<MessagesSquare size={11} />{t.staff.wake}
</button>
</div>
</div>
)}
</div>
);
})}
</PanelBody>
{active && (
<div style={{
flex: '0 0 auto', marginTop: 6, padding: '6px 9px', borderRadius: 9,
background: tokens.accentBg, border: `1px solid ${tokens.border}`,
display: 'flex', alignItems: 'center', gap: 7, minWidth: 0,
}}>
<Radar size={13} style={{ color: tokens.accent, flex: '0 0 13px' }} className="dot-blink" />
<div key={active.code} className="content-reveal" style={{ minWidth: 0 }}>
<div style={{ fontSize: 11.5, color: tokens.accent, fontWeight: 700 }}>
{active.name_zh} · {active.last_run}
</div>
<div style={{ fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{active.cur_zh}
</div>
</div>
</div>
)}
</>
)}
{view === 'team' && (
<div style={{ display: 'flex', flexDirection: 'column', minHeight: 0, flex: 1, gap: 7 }}>
<button
onClick={() => setView('staff')}
className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 5, alignSelf: 'flex-start', fontSize: 12, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '2px 4px', flex: '0 0 auto' }}
>
<ArrowLeft size={13} />{t.team.back}
</button>
<div style={{ flex: '0 0 auto' }}>
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub, letterSpacing: '0.02em' }}>{t.team.presetTitle}</div>
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{t.team.presetHint}</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: '0 0 auto' }}>
{presets.map(tm => {
const on = presetKey === tm.id;
const isActive = activeTeam?.id === tm.id;
const c = toneColor(tm.tone);
return (
<button
key={tm.id} onClick={() => pickPreset(tm)} className="ghost-btn"
style={{
textAlign: 'left', padding: '8px 10px', borderRadius: 10, cursor: 'pointer',
background: on ? `${c}17` : `linear-gradient(135deg, ${c}0f, ${tokens.panelBgAlt} 60%)`,
border: `1px solid ${on ? `${c}88` : `${c}30`}`,
boxShadow: on ? `0 0 0 1px ${c}33, 0 2px 12px ${c}22` : 'none',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<span style={{
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
background: `${c}1f`, border: `1px solid ${c}44`, color: c,
}}>
<Users size={12} />
</span>
<span style={{ fontSize: 13.5, fontWeight: 700, color: on ? c : tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tm.nameZh}</span>
<span style={{ fontSize: 10.5, color: c, marginLeft: 'auto', flexShrink: 0, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{tm.memberCodes.length} 位</span>
{isActive && <Check size={13} color={c} style={{ flexShrink: 0 }} />}
</div>
<div style={{ fontSize: 11, color: tokens.textMuted, marginTop: 4, lineHeight: 1.45, paddingLeft: 29 }}>{tm.topicZh}</div>
</button>
);
})}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginTop: 2 }}>
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.textSub }}>{t.team.customTitle}</span>
{selCodes.length > 0 && (
<button
onClick={() => { setSelCodes([]); setPresetKey(null); }}
className="ghost-btn"
style={{ marginLeft: 'auto', fontSize: 11, color: tokens.textMuted, background: 'transparent', border: 'none', cursor: 'pointer', padding: '1px 4px' }}
>{t.team.clearSel}</button>
)}
</div>
<div style={{ fontSize: 11, color: tokens.textMuted, lineHeight: 1.5, flex: '0 0 auto' }}>{t.team.customHint}</div>
<PanelBody>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{feed.map(x => {
const idx = selCodes.indexOf(x.code);
const on = idx >= 0;
return (
<button
key={x.code} onClick={() => toggleCode(x.code)}
style={{
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11.5, padding: '3px 8px', borderRadius: 16, cursor: 'pointer',
background: on ? `${tokens.accent}22` : 'transparent',
color: on ? tokens.accent : tokens.textSub,
border: `1px solid ${on ? `${tokens.accent}66` : tokens.border}`,
}}
>
{on && (
<span style={{ width: 14, height: 14, borderRadius: 4, background: tokens.accent, color: tokens.onAccent, display: 'grid', placeItems: 'center', fontSize: 9, fontWeight: 800, flexShrink: 0 }}>{idx + 1}</span>
)}
{nameOfStaff(x)}
</button>
);
})}
</div>
</PanelBody>
<button
onClick={convene} disabled={selCodes.length < 2}
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
padding: '9px 12px', borderRadius: 10, border: 'none', fontSize: 13, fontWeight: 700,
cursor: selCodes.length < 2 ? 'default' : 'pointer',
background: selCodes.length < 2 ? tokens.border : tokens.accent,
color: selCodes.length < 2 ? tokens.textMuted : tokens.onAccent,
boxShadow: selCodes.length >= 2 ? `0 2px 10px ${tokens.accent}40` : 'none',
}}
>
<Users size={14} />
{selCodes.length < 2 ? t.team.needTwo : t.team.conveneN.replace('{n}', String(selCodes.length))}
</button>
</div>
)}
</PanelShell>
);
}
function Row({ label, value, tokens, text, mono }: {
label: string; value: string; tokens: { textMuted: string }; text: string; mono?: boolean;
}) {
return (
<div style={{ display: 'flex', gap: 8, fontSize: 11.5, lineHeight: '19px', minWidth: 0 }}>
<span style={{ color: tokens.textMuted, flex: '0 0 64px' }}>{label}</span>
<span style={{
color: text, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
...(mono ? { fontFamily: 'ui-monospace, monospace', fontVariantNumeric: 'tabular-nums' } : {}),
}}>{value}</span>
</div>
);
}
@@ -0,0 +1,167 @@
import { useEffect, useMemo, useState } from 'react';
import { AlarmClock, AlertOctagon, ClipboardList, ShoppingCart, TrendingUp, Moon, Sun, FileWarning } from 'lucide-react';
import { useTheme } from '../context/ThemeContext';
import { useText } from '../i18n/useText';
import { materialBalance, purchaseOrders, salesOrders } from '../data/ibp';
import { CURRENT_PERIOD, periodLabel } from '../lib/time';
import { wan } from '../lib/money';
interface HeaderProps {
/** 全局时间游标:仅用于右上角「数据期」标注,KPI 取自内置业务单据快照 */
period: number;
}
/** 单据金额合计(元);先按 2 位小数收敛浮点误差,展示口径交给 lib/money */
const sum = <T,>(rows: T[], pick: (r: T) => number) =>
+rows.reduce((acc, r) => acc + (pick(r) || 0), 0).toFixed(2);
export default function MecHeader({ period }: HeaderProps) {
const { tokens, theme, toggleTheme } = useTheme();
const { t } = useText();
const [time, setTime] = useState(() => new Date());
useEffect(() => {
const id = setInterval(() => setTime(new Date()), 1000);
return () => clearInterval(id);
}, []);
const pad = (n: number) => String(n).padStart(2, '0');
const timeStr = `${pad(time.getHours())}:${pad(time.getMinutes())}:${pad(time.getSeconds())}`;
const dateStr = `${time.getFullYear()}-${pad(time.getMonth() + 1)}-${pad(time.getDate())} ${time.toLocaleDateString('zh-CN', { weekday: 'short' })}`;
const isLight = theme === 'light';
/* KPI 全部取自内置单据快照:履约看订单与交期,异常看物料缺口与未审采购 */
const kpi = useMemo(() => {
const d = new Date();
const today = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
const gap = materialBalance().filter(m => m.缺口 > 0);
return {
soCount: salesOrders.length,
soAmount: sum(salesOrders, s => s.含税金额),
poCount: new Set(purchaseOrders.map(p => p.采购订单号)).size,
gapCount: gap.length,
overdue: salesOrders.filter(s => s.预计发货日期 < today).length,
draftPo: new Set(purchaseOrders.filter(p => p.订单状态 !== '生效').map(p => p.采购订单号)).size,
};
}, []);
const stats = [
{ label: '销售订单', value: String(kpi.soCount), unit: '张', color: tokens.accent, Icon: ClipboardList },
{ label: '订单金额', value: wan(kpi.soAmount), unit: '万元', color: tokens.accent, Icon: TrendingUp },
{ label: '采购订单', value: String(kpi.poCount), unit: '张', color: tokens.accent, Icon: ShoppingCart },
{ label: '物料缺口', value: String(kpi.gapCount), unit: '种', color: kpi.gapCount ? tokens.danger : tokens.success, Icon: AlertOctagon },
{ label: '交期逾期', value: String(kpi.overdue), unit: '单', color: kpi.overdue ? tokens.warning : tokens.success, Icon: AlarmClock },
{ label: '待审采购单', value: String(kpi.draftPo), unit: '张', color: kpi.draftPo ? tokens.warning : tokens.success, Icon: FileWarning },
];
return (
<header style={{
height: 88, flexShrink: 0, display: 'flex', alignItems: 'center', padding: '0 24px',
position: 'relative', zIndex: 10, overflow: 'visible',
}}>
<div style={{
position: 'absolute', top: 0, left: 0, right: 0, height: 1,
background: tokens.headerScanLine, boxShadow: `0 0 12px ${tokens.accentGlow}`, zIndex: 2,
}} />
<svg style={{
position: 'absolute', bottom: -26, left: 0, width: '100%', height: 28,
pointerEvents: 'none', zIndex: 0, overflow: 'visible',
}} viewBox="0 0 1000 28" preserveAspectRatio="none">
<path d="M 0,0 C 250,28 750,28 1000,0" fill="none" stroke={tokens.svgStroke} strokeWidth="1" vectorEffect="non-scaling-stroke" />
<path d="M 0,0 C 250,28 750,28 1000,0" fill="none" stroke={tokens.accent} strokeWidth="6" opacity="0.10" vectorEffect="non-scaling-stroke" />
<circle cx="0" cy="0" r="2.5" fill={tokens.svgDot} />
<circle cx="1000" cy="0" r="2.5" fill={tokens.svgDot} />
</svg>
{/* 品牌 + 标题 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 14, flex: 1, position: 'relative', zIndex: 1 }}>
{/* 品牌 logo:白底反预乘抠成透明,深浅主题各用一版——
浅色版保留原墨色,深色版把中性色(深蓝/灰)换成近白、品红方块原样保留 */}
<img
src={isLight ? '/mod-assets/jieya-ibp/jieya-logo-on-light.png' : '/mod-assets/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>
);
}

Some files were not shown because too many files have changed in this diff Show More