This commit is contained in:
2026-11-19 10:09:33 +08:00
parent d31f5a701c
commit d2013c2a07
181 changed files with 47968 additions and 4 deletions
+1
View File
@@ -36,6 +36,7 @@ lerna-debug.log*
.env.*.local
# Cache
.screenshots/
.cache/
.temp/
.eslintcache
+284 -2
View File
@@ -9,6 +9,7 @@
"version": "1.0.0",
"dependencies": {
"@ant-design/icons": "^5.4.0",
"@react-three/fiber": "^8.18.0",
"antd": "^5.21.0",
"axios": "^1.7.7",
"class-variance-authority": "^0.7.1",
@@ -20,11 +21,13 @@
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.1",
"sql.js": "^1.14.2",
"tailwind-merge": "^2.6.0"
"tailwind-merge": "^2.6.0",
"three": "^0.170.0"
},
"devDependencies": {
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/three": "^0.170.0",
"@vitejs/plugin-react": "^6.0.3",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
@@ -452,6 +455,64 @@
"react-dom": ">=16.9.0"
}
},
"node_modules/@react-three/fiber": {
"version": "8.18.0",
"resolved": "https://registry.npmmirror.com/@react-three/fiber/-/fiber-8.18.0.tgz",
"integrity": "sha512-FYZZqD0UUHUswKz3LQl2Z7H24AhD14XGTsIRw3SJaXUxyfVMi+1yiZGmqTcPt/CkPpdU7rrxqcyQ1zJE5DjvIQ==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.17.8",
"@types/react-reconciler": "^0.26.7",
"@types/webxr": "*",
"base64-js": "^1.5.1",
"buffer": "^6.0.3",
"its-fine": "^1.0.6",
"react-reconciler": "^0.27.0",
"react-use-measure": "^2.1.7",
"scheduler": "^0.21.0",
"suspend-react": "^0.1.3",
"zustand": "^3.7.1"
},
"peerDependencies": {
"expo": ">=43.0",
"expo-asset": ">=8.4",
"expo-file-system": ">=11.0",
"expo-gl": ">=11.0",
"react": ">=18 <19",
"react-dom": ">=18 <19",
"react-native": ">=0.64",
"three": ">=0.133"
},
"peerDependenciesMeta": {
"expo": {
"optional": true
},
"expo-asset": {
"optional": true
},
"expo-file-system": {
"optional": true
},
"expo-gl": {
"optional": true
},
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
}
}
},
"node_modules/@react-three/fiber/node_modules/scheduler": {
"version": "0.21.0",
"resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.21.0.tgz",
"integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.1.5.tgz",
@@ -716,6 +777,13 @@
"dev": true,
"license": "MIT"
},
"node_modules/@tweenjs/tween.js": {
"version": "23.1.3",
"resolved": "https://registry.npmmirror.com/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
"dev": true,
"license": "MIT"
},
"node_modules/@tybys/wasm-util": {
"version": "0.10.3",
"resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.3.tgz",
@@ -731,7 +799,6 @@
"version": "19.2.17",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
"dev": true,
"license": "MIT",
"dependencies": {
"csstype": "^3.2.2"
@@ -747,6 +814,43 @@
"@types/react": "^19.2.0"
}
},
"node_modules/@types/react-reconciler": {
"version": "0.26.7",
"resolved": "https://registry.npmmirror.com/@types/react-reconciler/-/react-reconciler-0.26.7.tgz",
"integrity": "sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==",
"license": "MIT",
"dependencies": {
"@types/react": "*"
}
},
"node_modules/@types/stats.js": {
"version": "0.17.4",
"resolved": "https://registry.npmmirror.com/@types/stats.js/-/stats.js-0.17.4.tgz",
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/three": {
"version": "0.170.0",
"resolved": "https://registry.npmmirror.com/@types/three/-/three-0.170.0.tgz",
"integrity": "sha512-CUm2uckq+zkCY7ZbFpviRttY+6f9fvwm6YqSqPfA5K22s9w7R4VnA3rzJse8kHVvuzLcTx+CjNCs2NYe0QFAyg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@tweenjs/tween.js": "~23.1.3",
"@types/stats.js": "*",
"@types/webxr": "*",
"@webgpu/types": "*",
"fflate": "~0.8.2",
"meshoptimizer": "~0.18.1"
}
},
"node_modules/@types/webxr": {
"version": "0.5.24",
"resolved": "https://registry.npmmirror.com/@types/webxr/-/webxr-0.5.24.tgz",
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
"license": "MIT"
},
"node_modules/@vitejs/plugin-react": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.3.tgz",
@@ -773,6 +877,13 @@
}
}
},
"node_modules/@webgpu/types": {
"version": "0.1.74",
"resolved": "https://registry.npmmirror.com/@webgpu/types/-/types-0.1.74.tgz",
"integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
@@ -933,6 +1044,26 @@
"proxy-from-env": "^2.1.0"
}
},
"node_modules/base64-js": {
"version": "1.5.1",
"resolved": "https://registry.npmmirror.com/base64-js/-/base64-js-1.5.1.tgz",
"integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
"version": "2.10.42",
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.42.tgz",
@@ -1006,6 +1137,30 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/buffer": {
"version": "6.0.3",
"resolved": "https://registry.npmmirror.com/buffer/-/buffer-6.0.3.tgz",
"integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "MIT",
"dependencies": {
"base64-js": "^1.3.1",
"ieee754": "^1.2.1"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -1356,6 +1511,13 @@
"reusify": "^1.0.4"
}
},
"node_modules/fflate": {
"version": "0.8.3",
"resolved": "https://registry.npmmirror.com/fflate/-/fflate-0.8.3.tgz",
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"dev": true,
"license": "MIT"
},
"node_modules/fill-range": {
"version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
@@ -1557,6 +1719,26 @@
"node": ">= 6"
}
},
"node_modules/ieee754": {
"version": "1.2.1",
"resolved": "https://registry.npmmirror.com/ieee754/-/ieee754-1.2.1.tgz",
"integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"license": "BSD-3-Clause"
},
"node_modules/is-binary-path": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz",
@@ -1619,6 +1801,27 @@
"node": ">=0.12.0"
}
},
"node_modules/its-fine": {
"version": "1.2.5",
"resolved": "https://registry.npmmirror.com/its-fine/-/its-fine-1.2.5.tgz",
"integrity": "sha512-fXtDA0X0t0eBYAGLVM5YsgJGsJ5jEmqZEPrGbzdf5awjv0xE7nqv3TVnvtUF060Tkes15DbDAKW/I48vsb6SyA==",
"license": "MIT",
"dependencies": {
"@types/react-reconciler": "^0.28.0"
},
"peerDependencies": {
"react": ">=18.0"
}
},
"node_modules/its-fine/node_modules/@types/react-reconciler": {
"version": "0.28.9",
"resolved": "https://registry.npmmirror.com/@types/react-reconciler/-/react-reconciler-0.28.9.tgz",
"integrity": "sha512-HHM3nxyUZ3zAylX8ZEyrDNd2XZOnQ0D5XfunJF5FLQnZbHHYq4UWvW1QfelQNXv1ICNkwYhfxjwfnqivYB6bFg==",
"license": "MIT",
"peerDependencies": {
"@types/react": "*"
}
},
"node_modules/jiti": {
"version": "1.21.7",
"resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz",
@@ -1971,6 +2174,13 @@
"node": ">= 8"
}
},
"node_modules/meshoptimizer": {
"version": "0.18.1",
"resolved": "https://registry.npmmirror.com/meshoptimizer/-/meshoptimizer-0.18.1.tgz",
"integrity": "sha512-ZhoIoL7TNV4s5B6+rx5mC//fw8/POGyNxS/DZyCJeiZ12ScLfVwRE/GfsxwiTkMYYD5DmK2/JXnEVXqL4rF+Sw==",
"dev": true,
"license": "MIT"
},
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -2960,6 +3170,31 @@
"integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==",
"license": "MIT"
},
"node_modules/react-reconciler": {
"version": "0.27.0",
"resolved": "https://registry.npmmirror.com/react-reconciler/-/react-reconciler-0.27.0.tgz",
"integrity": "sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.21.0"
},
"engines": {
"node": ">=0.10.0"
},
"peerDependencies": {
"react": "^18.0.0"
}
},
"node_modules/react-reconciler/node_modules/scheduler": {
"version": "0.21.0",
"resolved": "https://registry.npmmirror.com/scheduler/-/scheduler-0.21.0.tgz",
"integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/react-router": {
"version": "7.18.1",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.1.tgz",
@@ -2998,6 +3233,21 @@
"react-dom": ">=18"
}
},
"node_modules/react-use-measure": {
"version": "2.1.7",
"resolved": "https://registry.npmmirror.com/react-use-measure/-/react-use-measure-2.1.7.tgz",
"integrity": "sha512-KrvcAo13I/60HpwGO5jpW7E9DfusKyLPLvuHlUyP5zqnmAPhNc6qTRjUQrdTADl0lpPpDVU2/Gg51UlOGHXbdg==",
"license": "MIT",
"peerDependencies": {
"react": ">=16.13",
"react-dom": ">=16.13"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/read-cache": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz",
@@ -3206,6 +3456,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/suspend-react": {
"version": "0.1.3",
"resolved": "https://registry.npmmirror.com/suspend-react/-/suspend-react-0.1.3.tgz",
"integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==",
"license": "MIT",
"peerDependencies": {
"react": ">=17.0"
}
},
"node_modules/tailwind-merge": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-2.6.1.tgz",
@@ -3287,6 +3546,12 @@
"node": ">=0.8"
}
},
"node_modules/three": {
"version": "0.170.0",
"resolved": "https://registry.npmmirror.com/three/-/three-0.170.0.tgz",
"integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==",
"license": "MIT"
},
"node_modules/throttle-debounce": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/throttle-debounce/-/throttle-debounce-5.0.2.tgz",
@@ -3520,6 +3785,23 @@
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/zustand": {
"version": "3.7.2",
"resolved": "https://registry.npmmirror.com/zustand/-/zustand-3.7.2.tgz",
"integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==",
"license": "MIT",
"engines": {
"node": ">=12.7.0"
},
"peerDependencies": {
"react": ">=16.8"
},
"peerDependenciesMeta": {
"react": {
"optional": true
}
}
}
}
}
+4 -1
View File
@@ -12,6 +12,7 @@
},
"dependencies": {
"@ant-design/icons": "^5.4.0",
"@react-three/fiber": "^8.18.0",
"antd": "^5.21.0",
"axios": "^1.7.7",
"class-variance-authority": "^0.7.1",
@@ -23,11 +24,13 @@
"react-dom": "^18.3.1",
"react-router-dom": "^7.1.1",
"sql.js": "^1.14.2",
"tailwind-merge": "^2.6.0"
"tailwind-merge": "^2.6.0",
"three": "^0.170.0"
},
"devDependencies": {
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@types/three": "^0.170.0",
"@vitejs/plugin-react": "^6.0.3",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
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: 34 KiB

+2
View File
@@ -20,6 +20,7 @@ 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'));
const TfamdOeeApp = lazy(() => import('@/modules/tfamd-oee/App'));
const EasySalesSkillApp = lazy(() => import('@/modules/easy-sales-skill/App'));
function ModuleLoading() {
@@ -72,6 +73,7 @@ export default function App() {
<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>} />
<Route path="/tfamd-oee" element={<RequireAuth><ModuleTitle title="通富超威 OEE 智能分析"><TfamdOeeApp /></ModuleTitle></RequireAuth>} />
<Route path="/easy-sales-skill" element={<RequireAuth><ModuleTitle title="EasySales 易销智能体 · 四大 Skill 使用说明"><EasySalesSkillApp /></ModuleTitle></RequireAuth>} />
</Routes>
</Suspense>
+2
View File
@@ -23,6 +23,7 @@ import { moduleConfig as welltrustQapConfig } from './welltrust-qap';
import { moduleConfig as baodeWebConfig } from './baode-web';
import { moduleConfig as supplierPlatformConfig } from './supplier-platform';
import { moduleConfig as wucQuotationConfig } from './wuc-quotation';
import { moduleConfig as tfamdOeeConfig } from './tfamd-oee';
// 新增模块只需在此数组添加一条配置即可
export const modules: ModuleConfig[] = [
@@ -38,4 +39,5 @@ export const modules: ModuleConfig[] = [
baodeWebConfig,
supplierPlatformConfig,
wucQuotationConfig,
tfamdOeeConfig,
];
+154
View File
@@ -0,0 +1,154 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
// 平台全局样式已提供 tailwind 预置;模块样式全部命名空间化在 .tfamd-root 下
import './index.css';
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/oeeTime';
import { DEFAULT_FILTER, normalizeFilter, type OeeFilter } from './lib/oeeFilters';
import MecHeader from './components/MecHeader';
import StarBackground from './components/StarBackground';
import MetricWorkspace from './components/MetricWorkspace';
import QualityFlowStrip from './components/quality/QualityFlowStrip';
import type { ViewProps } from './components/workspace/views';
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('OEE');
const [netStage, setNetStage] = useState(false);
/* 全局筛选(区域 / 线体 / 设备 / 业务日 / 班次 / 口径版本)=唯一状态源,在顶栏。
时间游标不再是独立 state,而是 filter.day 的派生值:这样底部时间轴拖到哪天、
顶栏「业务日」就显示哪天,不会出现两个游标各说各话。
口径版本只从 CALIBER_CONFIG 取(normalizeFilter 每次都会复位),视图不得另存一份。 */
const [filter, setFilter] = useState<OeeFilter>(DEFAULT_FILTER);
const period = filter.day;
const onSelect = useCallback((code: string) => {
if (code) setSelected(code);
}, []);
/* 时间滑块拖动 / 回放:写回全局筛选的 day 字段,顶栏与图谱、看板同一时点读数 */
const onPeriod = useCallback(
(p: number) => setFilter(f => normalizeFilter({ ...f, day: 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]);
// 专家团会诊已退场:OEE 一期对话按意图路由到 A1–A4,不再做多智能体轮流会诊。
/* 游标投影:一处把时点值与定级贴回节点,下游(指标树 / 明细 / 趋势 / 结构 / 驾驶舱 /
图谱 / 因果看板 / 对话区)的当期口径自动变成“数据期口径”,避免逐点改造遗漏。
trend 不投影,回看历史与预测仍拿得到完整的逐业务日序列(期数=种子真实天数,不补期)。 */
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 }),
[selected, view.byCode, view.flat, data.links, onSelect],
);
if (!dbReady) {
const errMsg = dbError ?? (dbTimedOut ? t.common.initTimeout : null);
return (
<div className="tfamd-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="tfamd-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 filter={filter} onFilter={setFilter}>
{/* 质量预防角色条是 demo 故事线(风险点检单流程)的抬头汇总。 */}
<QualityFlowStrip period={period} />
</MecHeader>
{/* 三栏:左=菜单导航,中=页面内容(底部时间回放轴),右=OEE专家智能体 */}
<div style={{
flex: 1, display: 'flex', minHeight: 0, alignItems: 'stretch', padding: '14px 20px 18px',
}}>
<MetricWorkspace
selected={selected} staff={data.staff} viewProps={viewProps}
period={period} onPeriod={onPeriod}
filter={filter}
netStage={netStage} onExitNetStage={() => setNetStage(false)}
/>
</div>
</div>
</div>
);
}
export default function App() {
return (
<ThemeProvider>
<AppInner />
</ThemeProvider>
);
}
@@ -0,0 +1,621 @@
import { useEffect, useMemo, useRef, useState } 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 { SUGGESTED } from '../lib/qualityAsk';
import type { AskJump } from '../lib/qualityAsk';
import { qualityExperts } from '../lib/teams';
import type { ConsultTurn, ExpertTeam, MetricSnap } from '../lib/teams';
import { consultPlan } from '../hooks/useAgentChat';
import type { AgentChat, ConsultBlockKey, PendingConsult } from '../hooks/useAgentChat';
import AskAnswerCard, { JumpButton } from './agent/AskAnswerCard';
import TeamPicker from './agent/TeamPicker';
interface AgentDockProps {
/** 会话状态机由父级持有:本体舞台换掉内容区时对话历史不丢 */
chat: AgentChat;
/** 专家团:非空时对话区切换为多智能体轮流会诊 */
team: ExpertTeam | null;
onConveneTeam: (team: ExpertTeam) => void;
onDismissTeam: () => void;
/** 回答卡里的跳转:指标 / 页签 / 本体 / 数据集 / 知识库 / 特征建模 / 追问 */
onJump: (j: AskJump) => void;
/** 高度由父级持有,全屏切换时不丢失展开状态 */
height: number;
onToggle: () => void;
/** 拉高态:对话区进一步往上拉高(第三高度档) */
tall: boolean;
onToggleTall: () => void;
}
const clock = () => {
const d = new Date();
const p = (n: number) => String(n).padStart(2, '0');
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
};
const levelColor = (lv: MetricSnap['level'], tk: ThemeTokens) =>
lv === 'good' ? tk.success : lv === 'warn' ? tk.warning : tk.danger;
/** 成员卡内的一行:小标签 + 文本;流式中在句尾挂一枚闪烁光标 */
function SecRow({ label, text, tk, color, typing }: { label: string; text?: string; tk: ThemeTokens; color?: string; typing?: boolean }) {
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}{typing && <span className="stream-caret" />}
</span>
</div>
);
}
/** 卡片刚立起来、正文还没铺开时的占位:避免出现一个空白发言卡 */
function ReaderHint({ tk, t }: { tk: ThemeTokens; t: I18n }) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, color: tk.textMuted, fontSize: 12 }}>
<span style={{ display: 'flex', gap: 3 }}>
{[0, 1, 2].map(i => <i key={i} className="typing-dot" style={{ animationDelay: `${i * 0.16}s` }} />)}
</span>
{t.agent.thinking}…
</div>
);
}
/** 会诊流式:某个块此刻该显示到什么程度;没有 stream 时整块直接显示 */
function blockView(
turn: ConsultTurn, stream: PendingConsult | undefined, key: ConsultBlockKey,
): { visible: boolean; text?: string; items: number; typing: boolean } {
if (!stream) return { visible: true, items: Number.POSITIVE_INFINITY, typing: false };
const plan = consultPlan(turn);
const i = plan.findIndex(b => b.key === key);
if (i < 0) return { visible: true, items: Number.POSITIVE_INFINITY, typing: false };
const b = plan[i];
if (i < stream.done) {
return { visible: true, text: b.mode === 'type' ? b.text : undefined, items: b.count ?? 0, typing: false };
}
if (i === stream.done) {
if (b.mode === 'type') {
return {
visible: stream.typed > 0, typing: stream.typed > 0,
text: (b.text ?? '').slice(0, stream.typed), items: 0,
};
}
if (b.mode === 'item') return { visible: stream.items > 0, items: stream.items, typing: false };
return { visible: false, items: 0, typing: false };
}
return { visible: false, items: 0, typing: false };
}
/** 专家成员发言卡:指标数据条 + 现状/观点/建议 + 移交衔接;stream 存在时按块流式铺开 */
function MemberCard({ turn, tk, t, time, onJump, stream }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string; onJump: (j: AskJump) => void; stream?: PendingConsult }) {
const m = turn.metric;
const lc = m ? levelColor(m.level, tk) : tk.accent;
const metric = blockView(turn, stream, 'metric');
const reading = blockView(turn, stream, 'reading');
const status = blockView(turn, stream, 'status');
const stance = blockView(turn, stream, 'stance');
const proposal = blockView(turn, stream, 'proposal');
const handoff = blockView(turn, stream, 'handoff');
return (
<div data-role="consult-card" 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>}
{turn.intent && (
<span style={{ fontSize: 10.5, color: tk.accent, padding: '0 6px', borderRadius: 7, border: `1px solid ${tk.borderAccent}`, background: tk.accentBg, whiteSpace: 'nowrap' }}>
{t.agent.secIntent}:{turn.intent}
</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 }}>
{stream && stream.done === 0 && stream.typed === 0 && stream.items === 0 && <ReaderHint tk={tk} t={t} />}
{m && metric.visible && (
<div className={stream ? 'content-reveal' : undefined} style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<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', whiteSpace: 'nowrap' }}>{m.state}</span>
<span style={{ fontSize: 11.5, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.deviation}</span>
</div>
{/* 判定线原文:源表没设线就照实写,不补达成率 */}
<div style={{ fontSize: 10.5, color: tk.textMuted, lineHeight: 1.5, marginTop: -2 }}>
{t.agent.lineLabel}:{m.line}
</div>
</div>
)}
{!!turn.reading?.length && reading.visible && (
<div className={stream ? 'content-reveal' : undefined} style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{turn.reading.map((r, i) => (
<span key={i} style={{ display: 'flex', alignItems: 'baseline', gap: 4, padding: '2px 8px', borderRadius: 7, background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}` }}>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>{r.label}</span>
<b style={{ fontSize: 12, color: tk.text, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{r.value}</b>
</span>
))}
</div>
)}
{status.visible && (
<div className={stream ? 'content-reveal' : undefined}>
<SecRow label={t.agent.secStatus} text={status.text ?? turn.status} typing={status.typing} tk={tk} />
</div>
)}
{stance.visible && (
<div className={stream ? 'content-reveal' : undefined}>
<SecRow label={t.agent.secStance} text={stance.text ?? turn.stance} typing={stance.typing} tk={tk} color={lc} />
</div>
)}
{proposal.visible && (
<div className={stream ? 'content-reveal' : undefined}>
<SecRow label={t.agent.secProposal} text={proposal.text ?? turn.proposal} typing={proposal.typing} tk={tk} color={tk.accent} />
</div>
)}
{handoff.visible && (
<div className={stream ? 'content-reveal' : undefined} style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{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>
)}
<span style={{ flex: 1 }} />
{turn.jump && <JumpButton jump={turn.jump} label={t.agent.jumpSee} tk={tk} onJump={onJump} />}
</div>
)}
</div>
</div>
</div>
);
}
/** 牵头结论卡:结论 headline + 成员要点 + 研判数据条 + 联合行动清单;stream 存在时逐块铺开 */
function LeadCard({ turn, tk, t, time, onJump, stream }: { turn: ConsultTurn; tk: ThemeTokens; t: I18n; time: string; onJump: (j: AskJump) => void; stream?: PendingConsult }) {
const j = turn.judge;
const lc = j ? levelColor(j.level, tk) : tk.accent;
const marks = ['①', '②', '③'];
const concl = blockView(turn, stream, 'conclusion');
const summary = blockView(turn, stream, 'summary');
const judge = blockView(turn, stream, 'judge');
const actions = blockView(turn, stream, 'actions');
return (
<div data-role="consult-card" 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` }}>
{stream && stream.done === 0 && stream.typed === 0 && stream.items === 0 && <ReaderHint tk={tk} t={t} />}
{turn.conclusion && concl.visible && (
<div className={stream ? 'content-reveal' : undefined} 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 }}>
{concl.text ?? turn.conclusion}{concl.typing && <span className="stream-caret" />}
</span>
</div>
)}
{!!turn.summary?.length && summary.visible && (
<div className={stream ? 'content-reveal' : undefined} 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.slice(0, summary.items).map((srow, i) => (
<div key={i} className={stream ? 'content-reveal' : undefined} 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 && judge.visible && (
<div className={stream ? 'content-reveal' : undefined} 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: 17, fontWeight: 800, color: lc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', lineHeight: 1, flexShrink: 0 }}>{j.value}</span>
<span style={{ flex: 1, minWidth: 0, fontSize: 11.5, color: tk.textSub, lineHeight: 1.5 }}>{j.label} · {j.note}</span>
<span style={{ fontSize: 11, fontWeight: 700, color: lc, background: `${lc}1a`, border: `1px solid ${lc}33`, borderRadius: 6, padding: '1px 7px', whiteSpace: 'nowrap', flexShrink: 0 }}>{j.state}</span>
</div>
</div>
)}
{!!turn.actions?.length && actions.visible && (
<div className={stream ? 'content-reveal' : undefined} 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.slice(0, actions.items).map((a, i) => (
<div key={i} className={stream ? 'content-reveal' : undefined} 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, flex: 1 }}>
<span style={{ color: tk.text, fontWeight: 600 }}>{a.owner}</span>
<span style={{ color: tk.textMuted }}>({a.role})</span> {a.action}
</span>
{a.jump && <JumpButton jump={a.jump} label={t.agent.jumpSee} tk={tk} onJump={onJump} />}
</div>
))}
</div>
)}
</div>
</div>
</div>
);
}
export default function AgentDock({ chat, team, onConveneTeam, onDismissTeam, onJump, height, onToggle, tall, onToggleTall }: AgentDockProps) {
const { tokens } = useTheme();
const { t } = useText();
/* 会话状态机在父级:本组件只管渲染与滚动,进出本体舞台都不会丢掉对话历史 */
const { msgs, pending, pendingTurn, thinking, thinkingName, busy, draft, setDraft, ask, skip, reset } = chat;
const listRef = useRef<HTMLDivElement>(null);
/** 专家团召集面板:点头部「组建专家团」展开 */
const [picker, setPicker] = useState(false);
/** 质量专家名册来自 lib/teams(与会诊同一批人),不再显示经营口径的数字员工 */
const experts = useMemo(() => qualityExperts(), []);
/* 滚动策略:回答卡通常远高于对话区,一律贴底用户只能看到末尾。
- 思考/打字阶段:对齐卡片顶部,让思考轨和逐字结论看得见;
- 分段亮出后:贴底跟随新段;
- 落卡与高度变化:仍然对齐最新答案卡顶部(避免只看到"数据来源"一行)。 */
useEffect(() => {
const el = listRef.current;
if (!el) return;
const cards = el.querySelectorAll<HTMLElement>('[data-role="answer-card"]');
const lastCard = cards[cards.length - 1];
const alignTop = () => {
if (!lastCard) return;
el.scrollTop += lastCard.getBoundingClientRect().top - el.getBoundingClientRect().top - 4;
};
if (pending) {
if (pending.phase === 'think' && pending.typed === 0) {
// 思考阶段盯住最新一步:6 步在 244px 高的对话区里放不下,贴顶只能看到第 1 步
const steps = el.querySelectorAll<HTMLElement>('[data-role="think-step"]');
const step = steps[steps.length - 1];
if (step) el.scrollTop += step.getBoundingClientRect().top - el.getBoundingClientRect().top - 34;
else alignTop();
return;
}
if (pending.phase === 'think' || pending.typed < pending.answer.conclusion.length) alignTop();
else el.scrollTop = el.scrollHeight;
return;
}
if (pendingTurn) {
/* 会诊发言:卡头先贴顶让人看清是谁发言,正文铺开后再贴底跟随新块 */
const consult = el.querySelectorAll<HTMLElement>('[data-role="consult-card"]');
const c = consult[consult.length - 1];
if (c) {
if (pendingTurn.turn.kind !== 'system' && pendingTurn.done <= 1) {
el.scrollTop += c.getBoundingClientRect().top - el.getBoundingClientRect().top - 4;
} else {
el.scrollTop = el.scrollHeight;
}
return;
}
}
const last = msgs[msgs.length - 1];
if (last?.answer && lastCard) { alignTop(); return; }
if (last?.kind === 'member' || last?.kind === 'lead') {
// 会诊发言卡也远高于对话区:对齐卡头,先看到专家名、数据条与现状
const consult = el.querySelectorAll<HTMLElement>('[data-role="consult-card"]');
const c = consult[consult.length - 1];
if (c) { el.scrollTop += c.getBoundingClientRect().top - el.getBoundingClientRect().top - 4; return; }
}
el.scrollTop = el.scrollHeight;
}, [msgs, pending, pendingTurn, thinking, height]);
const expanded = height > 120;
const convene = (next: ExpertTeam) => { setPicker(false); onConveneTeam(next); };
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' }}>
{experts.map(e => (
<span key={e.code} title={`${e.name} · ${e.role}`} style={{
width: 7, height: 7, borderRadius: '50%', background: tokens.accent,
boxShadow: `0 0 6px ${tokens.accentGlow}`, opacity: 0.85,
}} />
))}
</span>
<button
onClick={() => {
// 召集面板比常规高度高:打开时把对话区拉到「拉高」档,五个预设团一屏能看全
if (!expanded) onToggle();
if (!tall) onToggleTall();
setPicker(v => !v);
}}
data-role="open-team-picker"
title={t.team.entry}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer', flexShrink: 0,
color: picker ? tokens.onAccent : tokens.accent, fontSize: 12, fontWeight: 700,
background: picker ? tokens.accent : tokens.accentBg,
border: `1px solid ${picker ? tokens.accent : tokens.borderAccent}`,
borderRadius: 12, padding: '2px 9px',
}}
>
<Users size={12} />{t.team.entry}
</button>
<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>
{picker && (
<TeamPicker tk={tokens} t={t} onConvene={convene} onClose={() => setPicker(false)} />
)}
{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} onJump={onJump} />
: <LeadCard key={m.id} turn={m.turn} tk={tokens} t={t} time={m.time} onJump={onJump} />;
}
/* 单轮问答:思考过程条 + 规范回答卡(结论/关键数字/明细/依据/行动/来源) */
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}
onJump={onJump}
/>
);
}
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>
);
})}
{/* 会诊流式:就位播报逐字打出 → 成员卡/牵头卡逐块铺开 */}
{pendingTurn && pendingTurn.turn.kind === 'system' && (() => {
const full = pendingTurn.turn.text ?? '';
const shown = full.slice(0, pendingTurn.typed);
return (
<div data-role="consult-card" 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} />{pendingTurn.turn.name} · {pendingTurn.turn.tag}
</span>
{shown}{pendingTurn.typed < full.length && <span className="stream-caret" />}
</div>
</div>
);
})()}
{pendingTurn && pendingTurn.turn.kind === 'member' && (
<MemberCard
turn={pendingTurn.turn} tk={tokens} t={t} time={clock()} onJump={onJump} stream={pendingTurn}
/>
)}
{pendingTurn && pendingTurn.turn.kind === 'lead' && (
<LeadCard
turn={pendingTurn.turn} tk={tokens} t={t} time={clock()} onJump={onJump} stream={pendingTurn}
/>
)}
{/* 流式推演:思考轨逐条揭示 → 结论打字 → 正文分段亮出;可一键跳过 */}
{pending && (
<AskAnswerCard
answer={pending.answer}
elapsed={(performance.now() - pending.started) / 1000}
tk={tokens} t={t} time={clock()} staff={pending.staff}
onJump={onJump}
streaming={{
revealedSteps: pending.revealed, phase: pending.phase,
sections: pending.sections, typed: pending.typed, items: pending.items,
}}
onSkip={skip}
/>
)}
{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 }}>{thinkingName ? `${thinkingName}${t.agent.thinking}` : 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,
/* 禁用态原本用 tokens.border(浅色下≈16% 淡蓝)当底色配白字,实测只有 1.37:1,
「发送」两字在浅底上几乎看不见。改成淡底 + 次级文字色,既保留「不可点」的观感,
又把标签对比度抬到 AA 以上。 */
background: !draft.trim() || busy ? tokens.accentBg : tokens.accent,
border: `1px solid ${!draft.trim() || busy ? tokens.border : 'transparent'}`,
color: !draft.trim() || busy ? tokens.textMuted : 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,42 @@
import { useMemo, useState } from 'react';
import { Workflow } from 'lucide-react';
import PanelShell, { CountBadge } from './layout/PanelShell';
import { AutoScrollProvider, AutoScrollToggle } from './layout/AutoScroll';
import QualityFlowPanel from './quality/QualityFlowPanel';
import { ROLES } from '../lib/qualityFlow';
interface Props {
expanded: boolean;
onToggle: () => void;
/** 全局时间游标:质量流程与中央看板按同一时点读数 */
period: number;
}
/**
* 左侧工作栏。原先是「销售订单 / 客户资料」两个列表页签那块壳,
* 现在只装质量流程一块内容:弧板与自动滚动开关保留,
* 后续品质域要加页签(异常台账、检验标准库…)时接着往这里挂。
*/
export default function DemandPanel({ expanded, onToggle, period }: Props) {
/* 卡片多到一屏装不下时自动缓慢下滚;标题栏按钮可关闭 */
const [autoScroll, setAutoScroll] = useState(true);
/* 徽标=四段角色的 KPI 总数,与面板内容同源 */
const count = useMemo(() => ROLES.reduce((a, r) => a + r.kpis.length, 0), []);
return (
<PanelShell
side="left" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={<Workflow size={16} />}
title="质量流程"
badge={<CountBadge n={count} />}
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll(v => !v)} expanded={expanded} />}
animClass="space-animate-left"
>
<AutoScrollProvider value={autoScroll}>
<QualityFlowPanel period={period} expanded={expanded} />
</AutoScrollProvider>
</PanelShell>
);
}
@@ -0,0 +1,157 @@
import { useEffect, useState, type ReactNode } from 'react';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from '../context/ThemeContext';
import { useText } from '../i18n/useText';
import {
ALL, normalizeFilter, regionOptions, lineOptions, deviceOptions, dayOptions,
type OeeFilter, type FilterOption,
} from '../lib/oeeFilters';
interface HeaderProps {
/** 全局筛选单一来源(lib/oeeFilters)。顶栏只读它、只经 normalizeFilter 写它 */
filter: OeeFilter;
onFilter: (next: OeeFilter) => void;
children?: ReactNode;
}
/** 下拉筛选:标签在上、选择在下,宽度随视口收敛,不挤掉品牌区 */
function FilterSelect({ label, value, options, onChange, tokens, title }: {
label: string; value: string; options: FilterOption[]; onChange: (v: string) => void;
tokens: ReturnType<typeof useTheme>['tokens']; title?: string;
}) {
return (
<label title={title} style={{ display: 'flex', flexDirection: 'column', gap: 2, flex: 1, minWidth: 0 }}>
<span style={{
fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em', color: tokens.textMuted,
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}}>{label}</span>
<select
value={value}
onChange={(e) => onChange(e.target.value)}
style={{
width: '100%', minWidth: 0, padding: '3px 6px', borderRadius: 7, cursor: 'pointer',
background: tokens.panelBgAlt, color: tokens.text, fontSize: 11.5, fontWeight: 600,
border: `1px solid ${tokens.border}`, outline: 'none',
}}
>
{options.map((o) => (
<option key={o.value} value={o.value}>
{o.label}{o.note ? `(${o.note})` : ''}
</option>
))}
</select>
</label>
);
}
export default function MecHeader({ filter, onFilter, children }: 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';
const set = (patch: Partial<OeeFilter>) => onFilter(normalizeFilter({ ...filter, ...patch }));
const filters: { label: string; value: string; options: FilterOption[]; onChange: (v: string) => void; title?: string }[] = [
{ label: '区域', value: filter.region, options: regionOptions(), onChange: (v) => set({ region: v as OeeFilter['region'], lineId: ALL, deviceId: ALL }) },
{ label: '线体', value: filter.lineId, options: lineOptions(filter.region), onChange: (v) => set({ lineId: v, deviceId: ALL }) },
{ label: '设备', value: filter.deviceId, options: deviceOptions(filter.region, filter.lineId), onChange: (v) => set({ deviceId: v }) },
{ label: '业务日', value: String(filter.day), options: dayOptions(), onChange: (v) => set({ day: Number(v) }) },
];
return (
<header style={{
flexShrink: 0, display: 'flex', flexDirection: 'column', 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,
}} />
<div data-role="header-baseline" style={{
position: 'absolute', bottom: 0, left: 0, right: 0, height: 1, pointerEvents: 'none', zIndex: 0,
background: tokens.svgStroke, boxShadow: `0 0 0 3px ${tokens.accent}1a`,
}}>
<span style={{ position: 'absolute', left: -2.5, top: -2, width: 5, height: 5, borderRadius: '50%', background: tokens.svgDot }} />
<span style={{ position: 'absolute', right: -2.5, top: -2, width: 5, height: 5, borderRadius: '50%', background: tokens.svgDot }} />
</div>
{/* ── 第一行:品牌 + 全局筛选 + 口径版本/数据模式 + 时钟主题 ── */}
<div style={{ height: 60, display: 'flex', alignItems: 'center', position: 'relative', zIndex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, flex: 1.05, minWidth: 0 }}>
{/* 通富超威 TF-AMD 官方标识:红底白字,源图 513x128(官网 logo)。
浅色 / 深色两套主题沿用同一枚官方标识;宽度随视口收敛,避免挤压筛选区 */}
<img
src="/mod-assets/tfamd-oee/tfamd-logo.png"
alt="TF-AMD 通富超威"
width={128}
height={32}
style={{
display: 'block', width: 'clamp(96px, 6.6vw, 120px)', height: 'auto',
aspectRatio: '513 / 128', objectFit: 'contain', flexShrink: 0,
}}
/>
<div style={{ minWidth: 0 }}>
<h1 style={{
color: tokens.text, fontSize: 'clamp(16px, 1.15vw, 20px)', fontWeight: 800, letterSpacing: '0.04em',
margin: 0, textShadow: tokens.titleGlow, whiteSpace: 'nowrap',
}}>{t.appTitle}</h1>
</div>
</div>
<div style={{ width: 1, height: 40, background: `linear-gradient(to bottom, transparent, ${tokens.accent}33, transparent)`, flexShrink: 0, margin: '0 16px' }} />
{/* 全局筛选:区域→线体→设备三级级联 + 业务日 + 班次。
上级换了就把不兼容的下级复位为 ALL,不允许矛盾组合流到下游。 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flex: 2.5, minWidth: 0 }}>
{filters.map((f) => (
<FilterSelect key={f.label} {...f} tokens={tokens} />
))}
</div>
<div style={{ width: 1, height: 40, background: `linear-gradient(to bottom, transparent, ${tokens.accent}33, transparent)`, flexShrink: 0, margin: '0 16px' }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: 1.15, justifyContent: 'flex-end', minWidth: 0 }}>
<div style={{ textAlign: 'right', minWidth: 0 }}>
{/* 本机时钟:时钟为本机时间、非数据新鲜度;日期行「本机」前缀于 2026-11-14 按要求移除 */}
<div style={{
color: tokens.accent, fontSize: 14, fontWeight: 700, fontVariantNumeric: 'tabular-nums',
lineHeight: 1.15, letterSpacing: '0.05em', textShadow: isLight ? 'none' : `0 0 16px ${tokens.accentGlow}`,
whiteSpace: 'nowrap',
}}>{timeStr}</div>
<div style={{ color: tokens.textMuted, fontSize: 10, letterSpacing: '0.03em', whiteSpace: 'nowrap' }}>{dateStr}</div>
</div>
<button
onClick={toggleTheme}
className="ghost-btn"
title={theme === 'dark' ? t.common.light : t.common.dark}
style={{
display: 'flex', alignItems: 'center', gap: 5, padding: '4px 10px', 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>
{children && (
<div data-role="header-strip" style={{ display: 'flex', position: 'relative', zIndex: 1, padding: '4px 0 12px' }}>
{children}
</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/oeeTime';
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,382 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { CSSProperties } from 'react';
import { Bot, ChevronLeft, Maximize2, Minimize2 } from 'lucide-react';
import { useTheme } from '../context/ThemeContext';
import LeftNav, { type StageKey, type TabKey } from './layout/LeftNav';
import { useText } from '../i18n/useText';
import type { DigitalStaff } from '../data/sqlite';
import OeeAgentDock from './OeeAgentDock';
import OeeAlertStrip from './alert/OeeAlertStrip';
import { useOeeChat } from '../hooks/useOeeChat';
import type { OeeJump } from '../lib/oeeAnswerEngine';
import OntologyView from './ontology/OntologyView';
import QapDataView from './qap/QapDataView';
import KnowledgeView from './knowledge/KnowledgeView';
import MetricNetwork from './MetricNetwork';
import CausalPanel from './network/CausalPanel';
import MetricTimeline from './network/MetricTimeline';
import { DEEP } from './network/deepTheme';
import OeeOverview from './workspace/OeeOverview';
import OeeTrend from './workspace/OeeTrend';
import OeeLoss from './workspace/OeeLoss';
import OeeRegion from './workspace/OeeRegion';
import OeeDq from './workspace/OeeDq';
import OeeTimeline from './workspace/OeeTimeline';
import OeeMasterData from './workspace/OeeMasterData';
import OeeIntegration from './workspace/OeeIntegration';
import OeePriority from './workspace/OeePriority';
import OeeEntry from './workspace/OeeEntry';
import OeeTaskCenter from './stepchain/OeeTaskCenter';
import OeeCaliberCenter from './caliber/OeeCaliberCenter';
import OeeForecast from './workspace/OeeForecast';
import OeeLineMap from './workspace/OeeLineMap';
import OeeReport from './workspace/OeeReport';
import type { ViewProps } from './workspace/views';
import DisclosureView from './workspace/DisclosureView';
import type { OeeFilter } from '../lib/oeeFilters';
import { ALL } from '../lib/oeeFilters';
import { periodLabel } from '../lib/oeeTime';
import { initialTasks } from '../lib/oeeService';
import type { ImprovementTask } from '../types/oee';
/** 右侧对话列宽:回答卡的四段结构在 400 上下仍能单列读完 */
const AGENT_COL = 400;
interface WorkspaceProps {
selected: string;
/** 因果看板的智能体值守信息仍取经营数字员工;对话区已换成质量专家名册 */
staff: DigitalStaff[];
viewProps: ViewProps;
/** 全局时间游标(0-11):舞台底部滑块拖动,图谱与因果看板同步重算 */
period: number;
onPeriod: (p: number) => void;
/** 全局筛选(顶栏唯一状态源):说明与对照页的范围/口径/业务日标签与顶栏同源 */
filter: OeeFilter;
/** 指标网络全景舞台:占用整个内容区并自动全屏 */
netStage: boolean;
onExitNetStage: () => void;
}
export default function MetricWorkspace({ selected, staff, viewProps, period, onPeriod, filter, netStage, onExitNetStage }: WorkspaceProps) {
const { tokens } = useTheme();
const { t } = useText();
const [tab, setTab] = useState<TabKey>('cockpit');
/* D9:线体图节点/设备卡点击 → 主数据台账定位(携带设备 id,跨页签聚焦) */
const [masterFocus, setMasterFocus] = useState<string | null>(null);
/* 改善任务共享 state(W3-A):优先清单生成 → 录入台派发/流转,两页签共用一份。
初值由 L3 initialTasks() 现算优先级分(断言⑧),不在种子里写死;
原型不落库(SQLite 锁定四表),改善任务为内存态。 */
const [tasks, setTasks] = useState<ImprovementTask[]>(() => initialTasks());
const [fullscreen, setFullscreen] = useState(false);
/* 业务本体总览舞台:与指标网络舞台互斥,同样占用整屏,但用本组件自己的状态管——
它不进 App 的全局 netStage,避免两个全景互相踩 */
const [ontStage, setOntStage] = useState(false);
/* 数据集总览舞台:与本体舞台同类(独占整屏看那本 Excel 的 16 张表),两者互斥 */
const [dataStage, setDataStage] = useState(false);
/* 知识库舞台:角色标准文件 + 向量/图谱(独立形态,与本体/数据集舞台同级互斥) */
const [knowStage, setKnowStage] = useState(false);
/* 特征建模舞台:OEE 本体特征范围(设备/事件/状态段/损失四类对象),独立于业务本体全量视图 */
const [featStage, setFeatStage] = useState(false);
/* 跨舞台聚焦:知识库 ↔ 特征建模 双向跳转时携带 */
const [kbFocus, setKbFocus] = useState<{ role: 'PE' | 'IE' | 'QE' | 'ME'; chunkId: string } | null>(null);
const [featFocus, setFeatFocus] = useState<{ objKey: string; instanceId?: string } | null>(null);
const [agentOpen, setAgentOpen] = useState(true);
/* 舞台右栏因果看板:默认展开,收起时只留一条把手,不抢图谱空间 */
const [causalOpen, setCausalOpen] = useState(true);
/* 会话状态机放在这一层:本体舞台会替换整块内容区(对话区随之卸载),
状态上提后「从回答卡跳进舞台再退回」会话历史与进行中的推演都不丢。
OEE 对话走 L3 规则引擎(answerOee):bizDate 与顶栏筛选同源,任务存储与优先清单/录入台同源。 */
const bizDate = periodLabel(filter.day);
/* 顶栏筛了单台设备时传给对话区:问句没点名设备就跟它,不固定锚点 */
const chat = useOeeChat({ tasks, setTasks, bizDate, device: filter.deviceId === ALL ? undefined : filter.deviceId });
/** 回答卡「回数据集对账」的定位目标:带序号,重复点同一张表也能复位筛选 */
const [dataFocus] = useState<{ id: string; n: number } | null>(null);
/** 收起全部舞台:回答卡的跳转先回到普通工作区,再落到目标页签/舞台 */
const closeStages = useCallback(() => {
setOntStage(false); setDataStage(false); setKnowStage(false); setFeatStage(false);
setKbFocus(null); setFeatFocus(null);
if (netStage) onExitNetStage();
}, [netStage, onExitNetStage]);
/** 回答卡跳转总入口(OEE):页签 / 本体舞台 / 追问。
OeeJump 只有这三种——旧质量回答卡的 metric/dataset/knowledge/feature 跳转已随 legacy 引擎退场。 */
const onJump = useCallback((j: OeeJump) => {
switch (j.kind) {
case 'tab':
closeStages();
setTab(j.tab);
break;
case 'ontology':
closeStages();
setOntStage(true);
break;
case 'ask':
setAgentOpen(true);
chat.ask(j.text);
break;
}
}, [chat, closeStages]);
// 进入任一全景舞台即全屏,退出舞台还原(把图从窄栏解放到整屏)
useEffect(() => {
setFullscreen(netStage || ontStage || dataStage || knowStage || featStage);
}, [netStage, ontStage, dataStage, knowStage, featStage]);
// 左侧换节点时回到指标明细,避免用户以为"点了没反应"。
// 比对上一次的值而不是记「首次挂载」布尔:StrictMode 会把 effect 双跑一遍,
// 布尔标记在第二次就被自己抹平,默认页(全景驾驶舱)会被顶掉。
const prevSelected = useRef(selected);
useEffect(() => {
if (prevSelected.current === selected) return;
prevSelected.current = selected;
if (selected) setTab('detail');
}, [selected]);
useEffect(() => {
if (!fullscreen) return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
setOntStage(false);
setDataStage(false);
setKnowStage(false);
setFeatStage(false);
setFullscreen(false);
};
// 捕获阶段注册:页签 / 对话区里的子组件即使阻断冒泡,ESC 仍然能退出
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [fullscreen]);
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 = () => {
/* 说明与对照页不吃指标脊:它读 disclosure.ts 的现算统计与全局筛选,
与 period 无关(页内范围标签直接取 filter,与顶栏同源)。
建议书 §5.2.2:这一页 P0、必须做实且最先做,是评审现场的防穿帮页。 */
if (tab === 'disclosure') return <DisclosureView filter={filter} />;
/* 六个 OEE 页签统一吃 L3(oeeService):filter 决定范围/口径/业务日(与顶栏同源),
period 让趋势游标与底部回放同轴。视图只消费 L3 结果、不二次计算(断言②);
未接入范围照实给缺口、不显示 0。原品质六视图已于 W2-B 换下(W4 删除 legacy 代码)。 */
const oee = { filter, period };
if (tab === 'cockpit') return <OeeOverview {...oee} />;
if (tab === 'trend') return <OeeTrend {...oee} />;
if (tab === 'structure') return <OeeLoss {...oee} />;
if (tab === 'region') return <OeeRegion {...oee} />;
if (tab === 'risk') return <OeeDq {...oee} />;
if (tab === 'priority') return <OeePriority {...oee} tasks={tasks} onAddTask={(t) => setTasks((prev) => [...prev, t])} />;
if (tab === 'entry') return <OeeEntry {...oee} tasks={tasks} onTasksChange={setTasks} />;
if (tab === 'task') return <OeeTaskCenter {...oee} tasks={tasks} onTasksChange={setTasks} onNavigate={(t) => setTab(t as TabKey)} />;
if (tab === 'master') return <OeeMasterData {...oee} focusDevice={masterFocus} />;
if (tab === 'caliber') return <OeeCaliberCenter {...oee} />;
if (tab === 'integration') return <OeeIntegration {...oee} />;
/* W4-B:AI 预测(示意·非模型)/ 2D 线体图(SVG 拓扑+状态灯)/ 报表导出(7 类,与工具同源)。
报表读共享 tasks(改善闭环报表),与优先清单/录入台/任务中心同一份内存态。 */
if (tab === 'forecast') return <OeeForecast {...oee} />;
if (tab === 'linemap') return <OeeLineMap {...oee} onNavigate={(t, dev) => { if (dev) setMasterFocus(dev); setTab(t as TabKey); }} />;
if (tab === 'report') return <OeeReport {...oee} tasks={tasks} />;
return <OeeTimeline {...oee} />;
};
const stageOn: StageKey | null = knowStage ? 'know' : featStage ? 'feat' : ontStage ? 'ont' : dataStage ? 'data' : null;
/** 左侧菜单「全景舞台」入口:与原标题栏药签同一套互斥逻辑;再点一次同一入口即退出 */
const onStage = (k: StageKey) => {
if (stageOn === k) {
setOntStage(false); setDataStage(false); setKnowStage(false); setFeatStage(false);
setFullscreen(false);
return;
}
if (netStage) onExitNetStage();
setOntStage(k === 'ont'); setDataStage(k === 'data'); setKnowStage(k === 'know'); setFeatStage(k === 'feat');
setKbFocus(null); setFeatFocus(null);
};
const onTab = (k: TabKey) => { closeStages(); setTab(k); };
return (
<div style={{ flex: 1, minWidth: 0, minHeight: 0, display: 'flex', gap: 16 }}>
<LeftNav tab={tab} stage={stageOn} onTab={onTab} onStage={onStage} />
<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: '12px 22px 10px', flexShrink: 0,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<button
onClick={() => {
// 本体 / 数据集 / 知识库 / 特征建模舞台里的手柄只负责退出,不让它退成"半屏"
if (stageOn) {
setOntStage(false); setDataStage(false); setKnowStage(false); setFeatStage(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 data-role="center-title" style={{
margin: 0, textAlign: 'center', whiteSpace: 'nowrap',
color: tokens.text, fontSize: 22, fontWeight: 800, letterSpacing: '0.05em', textShadow: tokens.titleGlow,
}}>
{knowStage ? '知识库' : featStage ? '工艺建模'
: ontStage ? '业务本体' : dataStage ? '数据集总览' : netStage ? t.panel.metricNetwork : t.tab[tab]}
</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>}
</div>
</div>
{/* 内容区:页面视图 + 底部时间回放轴;对话区已移到右侧独立列(常驻挂载,进出舞台会话不丢)。
舞台 7:3:左=图谱 + 时间轴(70%)· 右=因果看板贯通到底(30%)
本体等舞台独占整块内容区,时间轴在此让位。 */}
<div style={{
flex: 1, minHeight: 0, display: 'flex', gap: 9,
padding: ontStage || dataStage || knowStage || featStage ? '0 18px 14px' : netStage ? '0 14px 12px' : '0 22px 12px',
}}>
{knowStage ? (
<KnowledgeView
onExit={() => { setKnowStage(false); setKbFocus(null); setFullscreen(false); }}
focus={kbFocus}
/>
) : featStage ? (
<OntologyView
scope="feature"
onExit={() => { setFeatStage(false); setFeatFocus(null); setFullscreen(false); }}
focus={featFocus}
/>
) : ontStage ? (
<OntologyView onExit={() => { setOntStage(false); setFullscreen(false); }} />
) : dataStage ? (
<QapDataView onExit={() => { setDataStage(false); setFullscreen(false); }} focus={dataFocus} />
) : (
<>
<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}
tokens={netStage ? { ...tokens, ...DEEP } : tokens} t={t}
/>
</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>
{agentOpen ? (
<div data-role="agent-column" style={{ flex: `0 0 ${AGENT_COL}px`, minWidth: 0, minHeight: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
<OeeAlertStrip filter={filter} />
<div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
<OeeAgentDock chat={chat} onJump={onJump} column onToggle={() => setAgentOpen(false)} />
</div>
</div>
) : (
<div style={{ width: 34, flexShrink: 0, minHeight: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
<OeeAlertStrip filter={filter} compact />
<button
onClick={() => setAgentOpen(true)}
data-role="agent-column-open"
className="ghost-btn"
style={{
flex: 1, cursor: 'pointer', display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center', gap: 8, borderRadius: 14,
writingMode: 'vertical-rl' as const, letterSpacing: '0.12em',
fontSize: 12, fontWeight: 700, color: tokens.accent,
background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<Bot size={14} /> OEE专家智能体
</button>
</div>
)}
</div>
);
}
@@ -0,0 +1,297 @@
import { useEffect, useRef } from 'react';
import { Bot, ChevronDown, ChevronsDown, ChevronsRight, ChevronUp, ChevronsUp, Cpu, Send, Trash2 } from 'lucide-react';
import { useTheme } from '../context/ThemeContext';
import type { ThemeTokens } from '../context/ThemeContext';
import { OEE_AGENTS, OEE_SUGGESTED } from '../lib/oeeAnswerEngine';
import type { OeeJump } from '../lib/oeeAnswerEngine';
import type { OeeChat } from '../hooks/useOeeChat';
import OeeAnswerCard from './agent/OeeAnswerCard';
/**
* OEE 底部对话坞(建议书 §5.3):A1–A7 名册(A5–A7 分期占位)+ 模型增强开关(演示降级①)
* + 快捷问句 + 流式回答卡 + 输入区。
*
* ★ 自包含:文案用本地常量,不依赖旧质量 i18n;去掉专家团会诊 / 轮流播报(OEE 一期按意图路由)。
* ★ 会话状态机由父级(MetricWorkspace)持有:进出舞台对话区卸载,历史与在飞推演不丢。
* ★ 名册只列已实现的 A1–A4(运行中);A5–A7 分期占位不入坞,避免演示界面出现二期三期药签。
*/
interface OeeAgentDockProps {
chat: OeeChat;
onJump: (j: OeeJump) => void;
/** 底部坞形态的高度;column 形态占满父列,忽略此值 */
height?: number;
onToggle: () => void;
tall?: boolean;
onToggleTall?: () => void;
/** 右侧独立列:占满整列高度、四周圆角描边、收起改由父级换成竖条 */
column?: boolean;
}
const clock = () => {
const d = new Date();
const p = (n: number) => String(n).padStart(2, '0');
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
};
/** 名册药签:标准名 + 运行状态色(只渲染已实现的智能体)。 */
function AgentPill({ agent, tk }: { agent: typeof OEE_AGENTS[number]; tk: ThemeTokens }) {
return (
<span
title={`${agent.name}\n职责:${agent.duty}\n运行中`}
data-role="agent-pill"
data-agent={agent.id}
style={{
display: 'inline-flex', alignItems: 'center', gap: 5, flexShrink: 0,
fontSize: 11, fontWeight: 700, padding: '2px 9px', borderRadius: 20, whiteSpace: 'nowrap',
color: tk.text,
background: `${tk.success}12`,
border: `1px solid ${tk.success}40`,
}}
>
<i style={{ width: 6, height: 6, borderRadius: 6, background: tk.success, flexShrink: 0 }} />
{agent.name}
<span style={{ fontSize: 9.5, fontWeight: 600, color: tk.success, opacity: 0.85 }}>
运行中
</span>
</span>
);
}
export default function OeeAgentDock({ chat, onJump, height = 244, onToggle, tall = false, onToggleTall, column = false }: OeeAgentDockProps) {
const { tokens: tk } = useTheme();
const { msgs, pending, thinking, busy, draft, setDraft, ask, skip, reset, modelMode, setModelMode } = chat;
const listRef = useRef<HTMLDivElement>(null);
const expanded = column || height > 120;
/* 滚动策略:回答卡通常远高于对话区,一律贴底用户只能看到末尾。
- 思考 / 打字阶段:对齐卡片顶部,让思考轨和逐字结论看得见;
- 分段亮出后:贴底跟随新段;
- 落卡与高度变化:对齐最新答案卡顶部(避免只看到"出处"一行)。 */
useEffect(() => {
const el = listRef.current;
if (!el) return;
const cards = el.querySelectorAll<HTMLElement>('[data-role="answer-card"]');
const lastCard = cards[cards.length - 1];
const alignTop = () => {
if (!lastCard) return;
el.scrollTop += lastCard.getBoundingClientRect().top - el.getBoundingClientRect().top - 4;
};
if (pending) {
if (pending.phase === 'think' && pending.typed === 0) {
const steps = el.querySelectorAll<HTMLElement>('[data-role="think-step"]');
const step = steps[steps.length - 1];
if (step) el.scrollTop += step.getBoundingClientRect().top - el.getBoundingClientRect().top - 34;
else alignTop();
return;
}
if (pending.phase === 'think' || pending.typed < pending.answer.four.conclusion.length) alignTop();
else el.scrollTop = el.scrollHeight;
return;
}
const last = msgs[msgs.length - 1];
if (last?.answer && lastCard) { alignTop(); return; }
el.scrollTop = el.scrollHeight;
}, [msgs, pending, thinking, height]);
const submit = () => { if (!busy) ask(draft); };
const iconBtn = (onClick: () => void, title: string, child: React.ReactNode, active?: boolean) => (
<button
onClick={onClick}
title={title}
className="ghost-btn"
style={{
width: 26, height: 26, borderRadius: 7, flexShrink: 0, cursor: 'pointer',
display: 'grid', placeItems: 'center',
border: `1px solid ${active ? tk.borderAccent : tk.border}`,
background: active ? tk.accentBg : 'transparent',
color: active ? tk.accent : tk.textMuted,
}}
>
{child}
</button>
);
return (
<div style={{
flexShrink: 0, position: 'relative', zIndex: 2,
background: tk.panelBgAlt, borderRadius: column ? 16 : '0 0 16px 16px',
display: 'flex', flexDirection: 'column', overflow: 'hidden',
...(column
? { flex: 1, minWidth: 0, height: '100%', border: `1px solid ${tk.borderAccent}`, boxShadow: tk.centerShadow }
: { height, transition: 'height 0.28s cubic-bezier(0.22,1,0.36,1)' }),
}}>
{/* 头部:标题 + 模型增强开关 + 清空 / 拉高 / 展开 */}
<div style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8,
padding: '6px 14px', borderBottom: expanded ? `1px solid ${tk.borderSub}` : 'none',
}}>
<span style={{
width: 22, height: 22, borderRadius: 7, display: 'grid', placeItems: 'center', flexShrink: 0,
background: `linear-gradient(135deg, ${tk.accent}, ${tk.info})`,
}}>
<Bot size={13} color={tk.onAccent} />
</span>
<span style={{ fontSize: 13, fontWeight: 800, color: tk.text, letterSpacing: '0.03em', whiteSpace: 'nowrap' }}>
OEE专家智能体
</span>
{/* 模型增强开关:'llm' 现场演示降级①(无端点 → 规则引擎应答) */}
<button
onClick={() => setModelMode(modelMode === 'rule' ? 'llm' : 'rule')}
data-role="model-mode"
data-mode={modelMode}
title={modelMode === 'rule'
? '当前:纯规则引擎(默认)。点击切到「模型增强」演示降级①:模型通道未接入 → 规则引擎应答。'
: '当前:模型增强(演示降级①)。模型通道未接入 / 健康检查失败 → 自动回退规则引擎,仍走全部闸门。点击切回纯规则。'}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer', flexShrink: 0,
fontSize: 11, fontWeight: 700, padding: '2px 9px', borderRadius: 20, whiteSpace: 'nowrap',
color: modelMode === 'llm' ? tk.warning : tk.accent,
background: modelMode === 'llm' ? `${tk.warning}14` : tk.accentBg,
border: `1px solid ${modelMode === 'llm' ? `${tk.warning}40` : tk.borderAccent}`,
}}
>
<Cpu size={12} />
{modelMode === 'rule' ? '规则引擎' : '模型增强·降级①'}
</button>
<span style={{ flex: 1 }} />
{iconBtn(reset, '清空对话,回到问候', <Trash2 size={13} />)}
{expanded && !column && onToggleTall && iconBtn(onToggleTall, tall ? '还原高度' : '拉高对话区', tall ? <ChevronsDown size={13} /> : <ChevronsUp size={13} />, tall)}
{column
? iconBtn(onToggle, '收起对话区', <ChevronsRight size={14} />)
: iconBtn(onToggle, expanded ? '收起对话区' : '展开对话区', expanded ? <ChevronDown size={14} /> : <ChevronUp size={14} />)}
</div>
{/* A1–A7 名册:A1–A4 运行中,A5–A7 分期占位(仅展开态显示) */}
{expanded && (
<div style={{
flexShrink: 0, display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6,
padding: '6px 14px', borderBottom: `1px solid ${tk.borderSub}`,
}}>
{OEE_AGENTS.filter((a) => a.implemented).map((a) => <AgentPill key={a.id} agent={a} tk={tk} />)}
</div>
)}
{/* 对话列表 */}
{expanded && (
<div ref={listRef} className="space-scroll" style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '10px 14px' }}>
{msgs.map((m) => {
if (m.role === 'user') {
return (
<div key={m.id} style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 8 }}>
<div style={{
maxWidth: '80%', padding: '7px 11px', borderRadius: '12px 4px 12px 12px',
background: tk.accent, color: tk.onAccent, fontSize: 12.5, lineHeight: 1.6, fontWeight: 600,
}}>
{m.text}
<span style={{ display: 'block', fontSize: 9.5, opacity: 0.75, marginTop: 2, fontVariantNumeric: 'tabular-nums' }}>{m.time}</span>
</div>
</div>
);
}
if (m.answer) {
return <OeeAnswerCard key={m.id} answer={m.answer} elapsed={m.elapsed ?? 0} tk={tk} time={m.time} onJump={onJump} />;
}
/* 问候 / 纯文本 ai 消息 */
return (
<div key={m.id} style={{ display: 'flex', justifyContent: 'flex-start', marginBottom: 8 }}>
<div style={{
maxWidth: '92%', padding: '8px 12px', borderRadius: '4px 12px 12px 12px',
background: tk.cardBg, border: `1px solid ${tk.border}`, borderLeft: `3px solid ${tk.accent}`,
color: tk.textSub, fontSize: 12.5, lineHeight: 1.7,
}}>
{m.text}
</div>
</div>
);
})}
{/* 流式回答卡 */}
{pending && (
<OeeAnswerCard
answer={pending.answer}
elapsed={0}
tk={tk}
time={clock()}
onJump={onJump}
streaming={{ revealedSteps: pending.revealed, phase: pending.phase, sections: pending.sections, typed: pending.typed, items: pending.items }}
onSkip={skip}
/>
)}
{/* 异步取数中:分析中气泡 */}
{thinking && (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, color: tk.textMuted, fontSize: 12, marginBottom: 8 }}>
<span style={{ display: 'flex', gap: 3 }}>
{[0, 1, 2].map((i) => <i key={i} className="typing-dot" style={{ animationDelay: `${i * 0.16}s`, background: tk.accent }} />)}
</span>
正在经五类受控工具取数…
</div>
)}
</div>
)}
{/* 快捷问句:一句一个意图 / 智能体(仅展开态、空闲时显示) */}
{expanded && !busy && (
<div style={{
flexShrink: 0, display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6,
maxHeight: 66, overflowY: 'auto',
padding: '6px 14px', borderTop: `1px solid ${tk.borderSub}`,
}} className="space-scroll">
{OEE_SUGGESTED.map((s, i) => (
<button
key={i}
onClick={() => ask(s.text)}
data-role="suggested"
title={`由${s.agent}应答`}
className="ghost-btn"
style={{
flexShrink: 0, maxWidth: '100%', cursor: 'pointer', fontSize: 11.5, fontWeight: 600, whiteSpace: 'nowrap',
overflow: 'hidden', textOverflow: 'ellipsis',
padding: '3px 10px', borderRadius: 20, color: tk.accent,
background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
}}
>
{s.text}
</button>
))}
</div>
)}
{/* 输入区 */}
<div style={{ flexShrink: 0, display: 'flex', alignItems: 'center', gap: 8, padding: '8px 14px' }}>
<input
value={draft}
onChange={(e) => setDraft(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}
disabled={busy}
data-role="chat-input"
placeholder={busy ? '推演进行中…可点「跳过推演」直接落卡' : '提问:DEK001 昨天 OEE 多少?损失压在哪类?能下钻到行号吗?'}
style={{
flex: 1, minWidth: 0, padding: '8px 12px', borderRadius: 10, fontSize: 12.5,
border: `1px solid ${tk.border}`, background: tk.cardBg, color: tk.text, outline: 'none',
opacity: busy ? 0.6 : 1,
}}
/>
<button
onClick={submit}
disabled={busy || !draft.trim()}
data-role="chat-send"
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0, cursor: busy || !draft.trim() ? 'not-allowed' : 'pointer',
fontSize: 12.5, fontWeight: 700, padding: '8px 16px', borderRadius: 10,
color: tk.onAccent, background: tk.accent, border: 'none',
opacity: busy || !draft.trim() ? 0.5 : 1,
}}
>
<Send size={13} /> 发送
</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(0,123,190,', 'rgba(56,189,248,', 'rgba(0,60,110,', 'rgba(0,80,160,', 'rgba(0,170,185,', 'rgba(60,140,210,'][i],
}));
// 流动透明球体:大球 + 小球混合
const darkOrbColors = [
'rgba(220,240,255,', 'rgba(200,230,255,', 'rgba(255,255,255,', 'rgba(230,240,255,',
'rgba(56,189,248,', 'rgba(86,172,224,', 'rgba(52,211,153,', 'rgba(0,212,255,',
];
const lightOrbColors = [
'rgba(150,190,220,', 'rgba(170,200,230,', 'rgba(195,218,240,', 'rgba(130,175,215,',
'rgba(95,145,195,', 'rgba(86,172,224,', 'rgba(115,160,205,', 'rgba(185,210,235,',
];
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,132 @@
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 { 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={autoScroll}>
{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,412 @@
import { useMemo, useState } from 'react';
import type { ReactNode } from 'react';
import {
BookOpen, Boxes, BrainCircuit, ChevronsRight, ChevronRight, CircleAlert, Database,
FlaskConical, Gauge, LayoutGrid, Lightbulb, ListChecks, MessageCircle, Sparkles, Table2,
} from 'lucide-react';
import type { ThemeTokens } from '../../context/ThemeContext';
import type { I18n } from '../../i18n/locales';
import type { AskAnswer, AskJump, AskStep, AskTone } from '../../lib/qualityAsk';
/**
* 质量问答回答卡:思考过程(逐条揭示,揭示完折叠成一行复查)+ 六段式正文
* 结论 / 关键数字 / 质量明细 / 依据与口径 / 建议动作(可跳转)/ 数据来源。
* 只负责渲染,所有数字与文案由 lib/qualityAsk.ts 从 17 张源表与本体规则现算。
*
* 流式:pending 时父级给 `reveal={ sections, typed }`,卡片按段亮出正文、
* 结论按打字机逐字出现;落卡后不传 reveal,整张卡全量渲染。
*/
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>
);
}
/**
* 思考过程轨: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} data-role="think-step" 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>
);
}
/** 跳转目的地的图标与 data-role(供核验脚本点击) */
const JUMP_META: Record<AskJump['kind'], { icon: ReactNode; role: string }> = {
metric: { icon: <Gauge size={11} />, role: 'jump-metric' },
tab: { icon: <LayoutGrid size={11} />, role: 'jump-tab' },
ontology: { icon: <Boxes size={11} />, role: 'jump-ontology' },
dataset: { icon: <Database size={11} />, role: 'jump-dataset' },
knowledge: { icon: <BookOpen size={11} />, role: 'jump-knowledge' },
feature: { icon: <FlaskConical size={11} />, role: 'jump-feature' },
ask: { icon: <MessageCircle size={11} />, role: 'jump-ask' },
};
export function JumpButton({ jump, label, tk, onJump, block }: {
jump: AskJump; label: string; tk: ThemeTokens; onJump: (j: AskJump) => void; block?: boolean;
}) {
const meta = JUMP_META[jump.kind];
return (
<button
onClick={() => onJump(jump)}
data-role={meta.role}
data-jump={block ? JSON.stringify(jump) : undefined}
className="ghost-btn"
title={t_jumpTitle(jump)}
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',
}}
>
{meta.icon}{label}
</button>
);
}
/** title 提示:告诉用户点下去会走到哪一眼数据 */
function t_jumpTitle(j: AskJump): string {
switch (j.kind) {
case 'metric': return `在「指标明细」打开口径 ${j.code}`;
case 'tab': return '切换中央工作区页签';
case 'ontology': return '打开业务本体';
case 'dataset': return `回数据集总览对账 ${j.id}`;
case 'knowledge': return `打开知识库 ${j.role} · ${j.chunkId}`;
case 'feature': return `打开工艺建模 ${j.objKey}${j.instanceId ? ` · ${j.instanceId}` : ''}`;
case 'ask': return '把这个问题再抛回对话区';
}
}
interface CardProps {
answer: AskAnswer;
elapsed: number;
tk: ThemeTokens;
t: I18n;
time: string;
/** 应答归属(卡头小字:由哪位质量专家作答) */
staff?: string;
onJump: (j: AskJump) => void;
/**
* 流式推演中:思考轨按 revealedSteps 揭示;phase 转 body 后正文按 sections 分段亮出、
* 结论按 typed 逐字打出。不传就是已落卡的完整回答。
*/
streaming?: { revealedSteps: number; phase: 'think' | 'body'; sections: number; typed: number; items: number };
/** 「跳过推演」:直接落成完整卡 */
onSkip?: () => void;
}
export default function AskAnswerCard({ answer, elapsed, tk, t, time, staff, onJump, streaming, onSkip }: CardProps) {
const sev = toneColor(answer.severity, tk);
const tone = (x?: AskTone) => toneColor(x, tk);
const inBody = !!streaming && streaming.phase === 'body';
/* 正文按段构建:与 hooks/useAgentChat 的 sectionPlan 同一套"有没有内容"判断,
顺序也必须一致(结论 → 关键数字 → 明细 → 依据 → 动作 → 来源),否则流式会跳段。
每段是一个 render(limit):流式时只铺到 limit 条,数字/表格行/依据/动作逐条出现。 */
const parts = useMemo(() => {
const out: { key: string; count: number; node: (limit: number) => ReactNode }[] = [];
out.push({
key: 'conclusion', count: 1,
node: () => (
<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 }}>
{answer.conclusion}
</span>
</div>
),
});
if (answer.metrics.length) {
out.push({
key: 'numbers', count: answer.metrics.length,
node: (limit) => (
<div>
<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.slice(0, limit).map((m, i) => {
const c = tone(m.tone);
return (
<span key={i} className="content-reveal" 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>
),
});
}
if (answer.table) {
const tbl = answer.table;
out.push({
key: 'table', count: tbl.rows.length,
node: (limit) => (
<div>
<SecHead icon={<Table2 size={11} color={tk.textMuted} />} text={t.agent.secTable} tk={tk} hint={`${Math.min(limit, tbl.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 }}>
{tbl.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>
{tbl.rows.slice(0, limit).map((r, ri) => {
const c = tone(r.tone);
return (
<tr key={ri} className="content-reveal" style={{ background: r.tone ? `${c}0d` : undefined, borderBottom: ri < tbl.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>
),
});
}
if (answer.points.length) {
out.push({
key: 'basis', count: answer.points.length,
node: (limit) => (
<div>
<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.slice(0, limit).map((p, i) => {
const c = tone(p.tone);
return (
<div key={i} className="content-reveal" 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>
),
});
}
if (answer.actions.length) {
out.push({
key: 'actions', count: answer.actions.length,
node: (limit) => (
<div>
<SecHead
icon={<Lightbulb size={11} color={tk.textMuted} />} text={t.agent.secActions} tk={tk}
hint={t.agent.jumpHint}
/>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
{answer.actions.slice(0, limit).map((a, i) => (
<span key={i} className="content-reveal" style={{ display: 'inline-flex' }}>
<JumpButton jump={a.jump} label={a.label} tk={tk} onJump={onJump} block />
</span>
))}
</div>
</div>
),
});
}
out.push({
key: 'source', count: 1,
node: () => (
<div 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>
),
});
return out;
}, [answer, onJump, sev, t, tk]);
const shownParts = inBody ? parts.slice(0, Math.max(1, streaming!.sections)) : parts;
const typedText = inBody ? answer.conclusion.slice(0, streaming!.typed) : answer.conclusion;
const typing = inBody && streaming!.typed < answer.conclusion.length;
return (
<div data-role="answer-card" 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={streaming ? streaming.revealedSteps : answer.steps.length}
running={!!streaming}
elapsed={streaming ? undefined : elapsed}
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,
}}>
{/* 思考阶段:正文还没开始写,只给一行"正在取数"的占位,不摆假数字 */}
{streaming && !inBody && (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, color: tk.textMuted }}>
<Dots tk={tk} />
{answer.steps[Math.min(streaming.revealedSteps, answer.steps.length - 1)]?.act ?? t.agent.thinkHint}
· {t.agent.thinkHint}
</div>
)}
{inBody && (
<>
<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 }}>
{typedText}
{typing && <span style={{ color: tk.accent }}>▍</span>}
</span>
</div>
{shownParts.slice(1).map((p, idx) => {
/* 只有最后一段还在「写」:按 items 逐条铺;之前的段已经铺满 */
const top = idx + 1 === shownParts.length - 1;
const limit = top ? Math.max(0, Math.min(p.count, streaming!.items)) : p.count;
return <div key={p.key} className="content-reveal">{p.node(limit)}</div>;
})}
</>
)}
{!streaming && parts.map(p => <div key={p.key}>{p.node(p.count)}</div>)}
{/* 推演进行中:给一个「跳过推演」,不想等的用户一键落到完整卡 */}
{streaming && onSkip && (
<button
onClick={onSkip}
data-role="skip-reasoning"
className="ghost-btn"
style={{
alignSelf: 'flex-start', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer',
fontSize: 11.5, fontWeight: 700, color: tk.textMuted,
background: tk.panelBgAlt, border: `1px solid ${tk.border}`, borderRadius: 8, padding: '3px 10px',
}}
>
<ChevronsRight size={11} />{t.agent.skip}
</button>
)}
</div>
</div>
</div>
);
}
@@ -0,0 +1,530 @@
import { useMemo, useState } from 'react';
import type { ReactNode } from 'react';
import {
AlertTriangle, BookOpen, Boxes, BrainCircuit, ChevronsRight, ChevronRight, CircleAlert, Coins,
Database, LayoutGrid, Lightbulb, ListChecks, MessageCircle, ShieldAlert, Sparkles, Table2,
} from 'lucide-react';
import type { ThemeTokens } from '../../context/ThemeContext';
import type { DegradeKind, OeeAnswer, OeeJump, OeeTone } from '../../lib/oeeAnswerEngine';
/**
* OEE 问答回答卡(建议书 §4.3 / §5.3):思考过程(逐条揭示,揭示完折叠成一行复查)
* + 四段正文(结论 / 依据 / 出处 / 下一步)+ 结构化卡片(关键数字 / 明细 / 收益区间 /
* 依据与口径 / 知识引用 / 建议动作)+ 闸门 / 降级 / 停止条件横幅。
*
* ★ 自包含:所有文案用本地常量,不依赖旧质量 i18n(t.agent),W4-C 删 legacy 时不受牵连。
* ★ 只负责渲染:数字与文案全部由 L3 oeeAnswerEngine 从五类工具与本体规则现算,卡片不二次计算。
* ★ 流式:pending 时父级给 streaming={sections,typed,...},按段亮出、结论逐字打出;落卡后全量渲染。
*/
const L = {
thinkTitle: '思考过程',
thinkHint: '正在按业务本体规则推演',
secNumbers: '关键数字',
secTable: '明细',
secBenefits: '预估收益(区间·待 IE 签字)',
secBasis: '依据与口径',
secCitations: '知识引用',
secActions: '建议动作',
secSource: '出处',
secNext: '下一步',
jumpHint: '点一下跳到对应页签或舞台',
skip: '跳过推演',
intent: '识别意图',
published: '已发布',
unpublished: '未发布',
halted: '未取数',
ruleEngine: '规则引擎应答',
guardFail: '闸门拦截',
stoppedTitle: '停止条件命中',
evidence: '依据',
};
const DEGRADE_LABEL: Record<DegradeKind, string> = {
MODEL_UNAVAILABLE: '降级① 模型不可用',
LOW_CONFIDENCE: '降级② 低置信',
EVIDENCE_MISSING: '降级③ 证据缺失',
};
const toneColor = (tone: OeeTone | 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>
);
}
/** 思考过程轨:running 时逐条出现,出答案后折叠成「思考过程 · N 步 · 耗时 x.xs」一行,点开可复查。 */
export function OeeStepTrace({
steps, revealed, running, elapsed, tk,
}: {
steps: OeeAnswer['steps']; revealed: number; running: boolean; elapsed?: number; tk: ThemeTokens;
}) {
const [open, setOpen] = useState(running);
const shown = steps.slice(0, Math.max(0, revealed));
const time = elapsed !== undefined ? `耗时 ${elapsed.toFixed(1)}s` : L.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 }}>{L.thinkTitle}</span>
<span style={{ fontSize: 11, color: tk.textMuted, fontVariantNumeric: 'tabular-nums' }}>{steps.length} 步 · {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} data-role="think-step" 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 ?? L.thinkHint}
</div>
)}
</div>
)}
</div>
);
}
/** 跳转目的地的图标与 data-role(供核验脚本点击)。OEE 只有 tab / ontology / ask 三种。 */
const JUMP_META: Record<OeeJump['kind'], { icon: ReactNode; role: string }> = {
tab: { icon: <LayoutGrid size={11} />, role: 'jump-tab' },
ontology: { icon: <Boxes size={11} />, role: 'jump-ontology' },
ask: { icon: <MessageCircle size={11} />, role: 'jump-ask' },
};
function jumpTitle(j: OeeJump): string {
switch (j.kind) {
case 'tab': return `切换到「${j.label}」页签`;
case 'ontology': return '打开业务本体';
case 'ask': return '把这个问题再抛回对话区';
}
}
export function OeeJumpButton({ jump, label, tk, onJump }: {
jump: OeeJump; label: string; tk: ThemeTokens; onJump: (j: OeeJump) => void;
}) {
const meta = JUMP_META[jump.kind];
return (
<button
onClick={() => onJump(jump)}
data-role={meta.role}
data-jump={JSON.stringify(jump)}
className="ghost-btn"
title={jumpTitle(jump)}
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',
}}
>
{meta.icon}{label}
</button>
);
}
/** 横幅:降级 / 停止 / 闸门拦截,照实展示,不藏缺口。 */
function Banner({ icon, title, text, color, tk }: { icon: ReactNode; title: string; text: string; color: string; tk: ThemeTokens }) {
return (
<div data-role="answer-banner" style={{
display: 'flex', gap: 7, alignItems: 'flex-start', padding: '6px 9px', borderRadius: 9,
background: `${color}12`, border: `1px solid ${color}40`,
}}>
<span style={{ flexShrink: 0, marginTop: 1, color }}>{icon}</span>
<span style={{ minWidth: 0, fontSize: 11.5, lineHeight: 1.55 }}>
<span style={{ fontWeight: 700, color }}>{title}</span>
<span style={{ color: tk.textSub }}> · {text}</span>
</span>
</div>
);
}
interface CardProps {
answer: OeeAnswer;
elapsed: number;
tk: ThemeTokens;
time: string;
onJump: (j: OeeJump) => void;
streaming?: { revealedSteps: number; phase: 'think' | 'body'; sections: number; typed: number; items: number };
onSkip?: () => void;
}
export default function OeeAnswerCard({ answer, elapsed, tk, time, onJump, streaming, onSkip }: CardProps) {
const sev = toneColor(answer.severity, tk);
const tone = (x?: OeeTone) => toneColor(x, tk);
const inBody = !!streaming && streaming.phase === 'body';
const concl = answer.four.conclusion;
/* 正文按段构建:顺序与 hooks/useOeeChat 的 oeeSectionPlan 完全一致
(结论 → 关键数字 → 明细 → 收益 → 依据 → 引用 → 动作 → 出处),否则流式会跳段。 */
const parts = useMemo(() => {
const out: { key: string; count: number; node: (limit: number) => ReactNode }[] = [];
out.push({
key: 'conclusion', count: 1,
node: () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<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 }}>{concl}</span>
</div>
{answer.four.evidence && (
<div style={{ display: 'flex', gap: 7, alignItems: 'flex-start', paddingLeft: 20 }}>
<span style={{ fontSize: 11.5, lineHeight: 1.6, color: tk.textSub, minWidth: 0 }}>
<span style={{ fontWeight: 700, color: tk.textMuted }}>{L.evidence}:</span>{answer.four.evidence}
</span>
</div>
)}
</div>
),
});
if (answer.metrics.length) {
out.push({
key: 'numbers', count: answer.metrics.length,
node: (limit) => (
<div>
<SecHead icon={<ListChecks size={11} color={tk.textMuted} />} text={L.secNumbers} tk={tk} />
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
{answer.metrics.slice(0, limit).map((m, i) => {
const c = tone(m.tone);
return (
<span key={i} className="content-reveal" 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>
),
});
}
if (answer.table) {
const tbl = answer.table;
out.push({
key: 'table', count: tbl.rows.length,
node: (limit) => (
<div>
<SecHead icon={<Table2 size={11} color={tk.textMuted} />} text={tbl.title || L.secTable} tk={tk} hint={`${Math.min(limit, tbl.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 }}>
{tbl.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>
{tbl.rows.slice(0, limit).map((r, ri) => (
<tr key={ri} className="content-reveal" style={{ borderBottom: ri < tbl.rows.length - 1 ? `1px solid ${tk.borderSub}` : undefined }}>
{r.map((cell, ci) => (
<td key={ci} style={{
padding: '4px 8px', color: ci === 0 ? 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>
),
});
}
if (answer.benefits?.length) {
const bs = answer.benefits;
out.push({
key: 'benefits', count: bs.length,
node: (limit) => (
<div>
<SecHead icon={<Coins size={11} color={tk.textMuted} />} text={L.secBenefits} tk={tk} />
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
{bs.slice(0, limit).map((b, i) => (
<span key={i} className="content-reveal" style={{
display: 'flex', alignItems: 'baseline', gap: 6, padding: '4px 10px', borderRadius: 8,
background: `${tk.info}12`, border: `1px solid ${tk.info}40`,
}}>
<span style={{ fontSize: 13, fontWeight: 800, color: tk.info, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>
{b.min} – {b.max}
</span>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>{b.unit}</span>
</span>
))}
</div>
</div>
),
});
}
if (answer.points.length) {
out.push({
key: 'basis', count: answer.points.length,
node: (limit) => (
<div>
<SecHead icon={<BrainCircuit size={11} color={tk.textMuted} />} text={L.secBasis} tk={tk} />
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 4 }}>
{answer.points.slice(0, limit).map((p, i) => {
const c = tone(p.tone);
return (
<div key={i} className="content-reveal" 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: 150, 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>
),
});
}
if (answer.citations.length) {
out.push({
key: 'citations', count: answer.citations.length,
node: (limit) => (
<div>
<SecHead icon={<BookOpen size={11} color={tk.textMuted} />} text={L.secCitations} tk={tk} hint="本地 TF-IDF 余弦·零依赖" />
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 4 }}>
{answer.citations.slice(0, limit).map((c, i) => (
<div key={i} className="content-reveal" style={{
display: 'flex', gap: 7, alignItems: 'flex-start', padding: '4px 8px', borderRadius: 8,
background: tk.panelBgAlt, border: `1px solid ${tk.borderSub}`,
}}>
<span style={{
flex: '0 0 auto', fontSize: 10, fontWeight: 700, marginTop: 1, padding: '1px 6px', borderRadius: 6,
color: tk.accent, background: tk.accentBg, border: `1px solid ${tk.borderAccent}`, whiteSpace: 'nowrap',
}}>{c.corpus}</span>
<span style={{ minWidth: 0, fontSize: 11.5, lineHeight: 1.55 }}>
<span style={{ color: tk.text, fontWeight: 700 }}>{c.title}</span>
<span style={{ color: tk.textMuted }}> · {c.source} · 命中 {c.score.toFixed(3)}</span>
</span>
</div>
))}
</div>
</div>
),
});
}
if (answer.actions.length) {
out.push({
key: 'actions', count: answer.actions.length,
node: (limit) => (
<div>
<SecHead icon={<Lightbulb size={11} color={tk.textMuted} />} text={L.secActions} tk={tk} hint={L.jumpHint} />
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 4 }}>
{answer.actions.slice(0, limit).map((a, i) => (
<span key={i} className="content-reveal" style={{ display: 'inline-flex' }}>
{a.jump
? <OeeJumpButton jump={a.jump} label={a.label} tk={tk} onJump={onJump} />
: <span style={{ fontSize: 11.5, color: tk.textSub, padding: '3px 10px' }}>{a.label}</span>}
</span>
))}
</div>
</div>
),
});
}
out.push({
key: 'source', count: 1,
node: () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: 5, paddingTop: 3, borderTop: `1px dashed ${tk.borderSub}` }}>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 5 }}>
<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 }}>{L.secSource}:</span>{answer.four.source}
</span>
</div>
{answer.four.nextStep && (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 5 }}>
<ChevronsRight size={10} color={tk.accent} style={{ flexShrink: 0, marginTop: 2 }} />
<span style={{ fontSize: 10.5, color: tk.textSub, minWidth: 0, lineHeight: 1.55 }}>
<span style={{ fontWeight: 700, color: tk.accent }}>{L.secNext}:</span>{answer.four.nextStep}
</span>
</div>
)}
</div>
),
});
return out;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [answer, onJump, sev, tk]);
const shownParts = inBody ? parts.slice(0, Math.max(1, streaming!.sections)) : parts;
const typedText = inBody ? concl.slice(0, streaming!.typed) : concl;
const typing = inBody && streaming!.typed < concl.length;
const conclDone = !inBody || streaming!.typed >= concl.length;
return (
<div data-role="answer-card" 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, flexWrap: 'wrap' }}>
<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 }}>{answer.agentName}</span>
<span style={{
fontSize: 10.5, color: tk.textMuted, padding: '0 6px', borderRadius: 7,
border: `1px solid ${tk.border}`, background: tk.cardBg, whiteSpace: 'nowrap',
}}>{L.intent}:{answer.intentLabel}</span>
<span style={{ fontSize: 10.5, color: tk.textMuted, whiteSpace: 'nowrap' }}>{answer.bizDate}</span>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 6px', borderRadius: 7, whiteSpace: 'nowrap',
color: answer.published ? tk.success : tk.textMuted,
background: answer.published ? `${tk.success}16` : tk.panelBgAlt,
border: `1px solid ${answer.published ? `${tk.success}40` : tk.border}`,
}}>{answer.published ? L.published : answer.halt ? L.halted : L.unpublished}</span>
<span style={{ marginLeft: 'auto', color: tk.textMuted, fontSize: 10.5, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>{time}</span>
</div>
{/* 思考轨 */}
<OeeStepTrace
steps={answer.steps}
revealed={streaming ? streaming.revealedSteps : answer.steps.length}
running={!!streaming}
elapsed={streaming ? undefined : elapsed}
tk={tk}
/>
{/* 闸门 / 降级 / 停止横幅:照实展示,不藏缺口 */}
{!answer.guard.ok && (
<Banner icon={<ShieldAlert size={13} />} title={`${L.guardFail} · 闸${answer.guard.gate}`} text={answer.guard.reason ?? ''} color={tk.danger} tk={tk} />
)}
{answer.stopped && (
<Banner icon={<AlertTriangle size={13} />} title={`${L.stoppedTitle} · ${answer.stopped.skill}`} text={`${answer.stopped.condition} → ${answer.stopped.action}`} color={tk.warning} tk={tk} />
)}
{answer.degraded && (
<Banner
icon={<AlertTriangle size={13} />}
title={DEGRADE_LABEL[answer.degraded]}
text={answer.four.degradedReason ?? ''}
color={answer.degraded === 'MODEL_UNAVAILABLE' ? tk.info : tk.warning}
tk={tk}
/>
)}
<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,
}}>
{/* 思考阶段:正文还没开始写,只给一行"正在取数"的占位,不摆假数字 */}
{streaming && !inBody && (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 12, color: tk.textMuted }}>
<Dots tk={tk} />
{answer.steps[Math.min(streaming.revealedSteps, answer.steps.length - 1)]?.act ?? L.thinkHint} · {L.thinkHint}
</div>
)}
{inBody && (
<>
<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 }}>
{typedText}{typing && <span style={{ color: tk.accent }}>▍</span>}
</span>
</div>
{conclDone && answer.four.evidence && (
<div className="content-reveal" style={{ paddingLeft: 20 }}>
<span style={{ fontSize: 11.5, lineHeight: 1.6, color: tk.textSub }}>
<span style={{ fontWeight: 700, color: tk.textMuted }}>{L.evidence}:</span>{answer.four.evidence}
</span>
</div>
)}
{shownParts.slice(1).map((p, idx) => {
const top = idx + 1 === shownParts.length - 1;
const limit = top ? Math.max(0, Math.min(p.count, streaming!.items)) : p.count;
return <div key={p.key} className="content-reveal">{p.node(limit)}</div>;
})}
</>
)}
{!streaming && parts.map((p) => <div key={p.key}>{p.node(p.count)}</div>)}
{/* 推演进行中:给一个「跳过推演」,不想等的用户一键落到完整卡 */}
{streaming && onSkip && (
<button
onClick={onSkip}
data-role="skip-reasoning"
className="ghost-btn"
style={{
alignSelf: 'flex-start', display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer',
fontSize: 11.5, fontWeight: 700, color: tk.textMuted,
background: tk.panelBgAlt, border: `1px solid ${tk.border}`, borderRadius: 8, padding: '3px 10px',
}}
>
<ChevronsRight size={11} />{L.skip}
</button>
)}
</div>
{/* 应答来源标注:规则引擎(LLM 是增强项,不是前提) */}
<div style={{ display: 'flex', alignItems: 'center', gap: 5, paddingLeft: 2 }}>
<span style={{ fontSize: 10, color: tk.textMuted }}>
{answer.four.answeredBy === 'RULE_ENGINE' ? L.ruleEngine : '大模型应答'} · 五道防幻觉闸门 · 数字只来自五类受控工具
</span>
</div>
</div>
</div>
);
}
@@ -0,0 +1,152 @@
import { useMemo, useState } from 'react';
import { Check, Sparkles, Users } from 'lucide-react';
import type { ThemeTokens } from '../../context/ThemeContext';
import type { I18n } from '../../i18n/locales';
import { customTeam, presetTeams, qualityExperts } from '../../lib/teams';
import type { ExpertTeam, TeamTone } from '../../lib/teams';
/**
* 专家团召集面板:从对话区头部弹出,选一个预设质量专家团或自己勾几位质量专家发起会诊。
* 只做"选人 + 开会"这一件事,会诊内容与播放时序都在 lib/teams.ts 与 AgentDock 里。
*/
interface Props {
tk: ThemeTokens;
t: I18n;
onConvene: (team: ExpertTeam) => void;
onClose: () => void;
}
const toneColor = (tone: TeamTone, tk: ThemeTokens) =>
tone === 'danger' ? tk.danger : tone === 'warning' ? tk.warning
: tone === 'success' ? tk.success : tone === 'info' ? tk.info : tk.accent;
export default function TeamPicker({ tk, t, onConvene, onClose }: Props) {
const presets = useMemo(() => presetTeams(), []);
const experts = useMemo(() => qualityExperts(), []);
const [sel, setSel] = useState<string[]>([]);
const toggle = (code: string) => setSel(prev => (prev.includes(code) ? prev.filter(c => c !== code) : [...prev, code]));
const custom = sel.length >= 2 ? customTeam(sel) : null;
const nameOf = (code: string) => experts.find(e => e.code === code)?.name ?? code;
return (
<div
data-role="team-picker"
className="space-scroll"
style={{
position: 'absolute', right: 14, top: 42, zIndex: 8, width: 396, maxWidth: 'calc(100% - 28px)',
maxHeight: 'calc(100% - 48px)', overflowY: 'auto', overscrollBehavior: 'contain',
background: tk.panelBg, border: `1px solid ${tk.borderAccent}`, borderRadius: 12,
boxShadow: `0 12px 32px rgba(0,0,0,.28)`, padding: 10, display: 'flex', flexDirection: 'column', gap: 8,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Users size={13} color={tk.accent} />
<span style={{ fontSize: 12.5, fontWeight: 800, color: tk.text }}>{t.team.panel}</span>
<span style={{ flex: 1 }} />
<button
onClick={onClose}
className="ghost-btn"
style={{ fontSize: 11.5, color: tk.textMuted, border: 'none', background: 'transparent', cursor: 'pointer' }}
>{t.common.close}</button>
</div>
<div style={{ fontSize: 11.5, color: tk.textMuted, lineHeight: 1.55 }}>{t.team.presetHint}</div>
{/* 预设团:一键就位 */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{presets.map(p => {
const c = toneColor(p.tone, tk);
return (
<button
key={p.id}
data-role={`team-${p.id}`}
onClick={() => onConvene(p)}
className="ghost-btn"
style={{
textAlign: 'left', cursor: 'pointer', padding: '7px 9px', borderRadius: 10,
background: tk.cardBg, border: `1px solid ${tk.border}`,
display: 'flex', flexDirection: 'column', gap: 3,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: c, flexShrink: 0 }} />
<span style={{ fontSize: 12.5, fontWeight: 800, color: tk.text }}>{p.nameZh}</span>
<span style={{ fontSize: 11, color: c, background: `${c}14`, border: `1px solid ${c}33`, borderRadius: 6, padding: '0 6px', whiteSpace: 'nowrap' }}>
{p.memberCodes.length} 位
</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, color: tk.accent, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 3 }}>
<Sparkles size={10} />{t.team.convene}
</span>
</div>
<span style={{ fontSize: 11.5, color: tk.textSub }}>{p.topicZh}</span>
<span style={{ fontSize: 11, color: tk.textMuted, lineHeight: 1.5 }}>{p.brief}</span>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>
{t.team.lead}:{nameOf(p.leadCode)} · {t.team.member}:{p.memberCodes.filter(c2 => c2 !== p.leadCode).map(nameOf).join('、')}
</span>
</button>
);
})}
</div>
{/* 自建团:勾选专家,首位为牵头 */}
<div style={{ borderTop: `1px dashed ${tk.borderSub}`, paddingTop: 8 }}>
<div style={{ fontSize: 11.5, fontWeight: 800, color: tk.text, marginBottom: 3 }}>{t.team.customTitle}</div>
<div style={{ fontSize: 11, color: tk.textMuted, marginBottom: 6 }}>{t.team.customHint}</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{experts.map(e => {
const on = sel.includes(e.code);
const lead = sel[0] === e.code && sel.length >= 2;
return (
<button
key={e.code}
onClick={() => toggle(e.code)}
className="ghost-btn"
title={`${e.role} · ${e.skill}`}
style={{
display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer',
fontSize: 11.5, fontWeight: on ? 700 : 500,
color: on ? tk.onAccent : tk.textSub,
background: lead ? tk.info : on ? tk.accent : tk.panelBgAlt,
border: `1px solid ${on ? 'transparent' : tk.border}`,
borderRadius: 8, padding: '3px 9px',
}}
>
{on && <Check size={11} />}
{e.name}
{lead && <span style={{ fontSize: 10, opacity: 0.9 }}>牵头</span>}
</button>
);
})}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8 }}>
<span style={{ fontSize: 11.5, color: sel.length >= 2 ? tk.textSub : tk.textMuted }}>
{sel.length >= 2 ? `${t.team.selected}:${sel.map(nameOf).join('、')}` : t.team.needTwo}
</span>
<span style={{ flex: 1 }} />
<button
onClick={() => setSel([])}
className="ghost-btn"
style={{ fontSize: 11.5, color: tk.textMuted, border: `1px solid ${tk.border}`, background: 'transparent', borderRadius: 8, padding: '3px 9px', cursor: 'pointer' }}
>{t.team.clearSel}</button>
<button
data-role="team-custom"
disabled={!custom}
onClick={() => custom && onConvene(custom)}
className="ghost-btn"
style={{
fontSize: 11.5, fontWeight: 700, borderRadius: 8, padding: '3px 11px',
cursor: custom ? 'pointer' : 'default',
color: custom ? tk.onAccent : tk.textMuted,
background: custom ? tk.accent : tk.panelBgAlt,
border: `1px solid ${custom ? 'transparent' : tk.border}`,
}}
>
{t.team.conveneN.replace('{n}', String(sel.length))}
</button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,313 @@
import { Fragment, useMemo, useState, type CSSProperties } from 'react';
import { BellRing, ChevronDown, ChevronRight, ListOrdered, ShieldAlert } from 'lucide-react';
import PanelShell, { CountBadge } from '../layout/PanelShell';
import { AutoScrollProvider, AutoScrollToggle, ScrollList } from '../layout/AutoScroll';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { resolveScope, type OeeFilter } from '../../lib/oeeFilters';
import {
deriveAlerts, alertStats, rankPriority, PRIORITY_CANDIDATES, DEFAULT_WEIGHT_SCHEME,
} from '../../lib/oeeService';
import {
ALERT_LEVELS, ALERT_LEVEL_ORDER, ALERT_STATE_LABEL,
type AlertLevel, type OeeAlert,
} from '../../types/oee';
interface Props {
expanded: boolean;
onToggle: () => void;
/** 全局筛选:告警流与中央页签同一范围、同一业务日、同一口径版本 */
filter: OeeFilter;
}
/** 档位色:直接取 ALERT_LEVELS 字典里的 tone,不在视图另写一份配色映射 */
function toneColor(lv: AlertLevel, tk: ThemeTokens): string {
return tk[ALERT_LEVELS[lv].tone];
}
/** 档位底色(很淡的一层,只给角标和分带线用) */
function toneBg(lv: AlertLevel, tk: ThemeTokens): string {
const tone = ALERT_LEVELS[lv].tone;
if (tone === 'danger') return tk.dangerBg;
if (tone === 'warning') return tk.warningBg;
if (tone === 'info') return tk.infoBg;
return tk.panelBgAlt;
}
/**
* 右栏「OEE 告警」:五级告警流(S1 安全 → S5 观察),全部由 L3 deriveAlerts 现算,
* 视图不写死任何统计值、不二次计算 OEE(断言②)。
*
* ★ S4 数据质量阻断独立成级(规划书 §5.5):DQ 阻断不是普通提示,而是有权暂停当日结论
* 发布的同级告警——blocksPublish 的卡片在收起态就挂「暂停发布」红标,汇总带也置顶提示。
* ★ S1 安全档在种子里结构为空(48 事件字典无 EMO/安全回路码),不臆造安全告警;
* 真实安全码表接入后登记 SAFETY_EVENT_CODES 即自动生效。
* ★ 非锚点范围(线体/区域/未接入设备)resolveScope.day=null:不显示告警,也不显示 0,
* 只给出该范围的具体缺口,避免把单机告警冒充成聚合告警。
*/
export default function OeeAlertPanel({ expanded, onToggle, filter }: Props) {
const { tokens } = useTheme();
/* 列表多到一屏装不下时缓慢下滚,标题栏按钮可关;和左栏同一套开关语义 */
const [autoScroll, setAutoScroll] = useState(true);
/* 同一时刻只展开一张:滚动的信息流里同时摊开两张就看不出顺序了 */
const [openId, setOpenId] = useState<string | null>(null);
const scope = useMemo(() => resolveScope(filter), [filter]);
const day = scope.day;
const alerts = useMemo(() => (day ? deriveAlerts(day) : []), [day]);
const sum = useMemo(() => alertStats(alerts), [alerts]);
/* 优先清单 Top3:全站 POC 候选,默认 B 套权重;信息性脚注,不在此跳页 */
const top3 = useMemo(() => rankPriority(PRIORITY_CANDIDATES, DEFAULT_WEIGHT_SCHEME).slice(0, 3), []);
/* 计数为 0 的档位不占汇总位,否则「S1 0」看着像漏采安全事件 */
const bands = ALERT_LEVEL_ORDER.map((lv) => ({ lv, n: sum.byLevel[lv] })).filter((x) => x.n > 0);
return (
<PanelShell
side="right" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={<BellRing size={16} />}
title="OEE 告警"
badge={<CountBadge n={day ? sum.total : '—'} color={sum.blocksPublish ? tokens.danger : tokens.warning} />}
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll((v) => !v)} expanded={expanded} />}
animClass="space-animate-right"
>
{/* 汇总带固定在标题下方,不随列表滚走:滚到哪儿都知道整池是什么结构 */}
<div style={{
flex: '0 0 auto', marginBottom: 8, padding: '7px 9px', borderRadius: 9,
background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<div style={{
display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5,
fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em',
}}>
<span style={{
padding: '1px 5px', borderRadius: 4, fontWeight: 700,
border: `1px solid ${day ? tokens.border : tokens.warning}55`,
background: day ? 'transparent' : tokens.warningBg,
color: day ? tokens.textMuted : tokens.warning,
}}>{day ? '当日实测' : '未接入'}</span>
<span>{scope.bizDate}</span>
{day && <span style={{ color: tokens.textSub }}>· {day.device.id}</span>}
</div>
{/* S4 阻断置顶:有权暂停发布,必须在汇总带就看见,不靠展开卡片才发现 */}
{sum.blocksPublish && (
<div style={{
display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5,
padding: '4px 7px', borderRadius: 7, fontSize: 11, fontWeight: 700,
color: tokens.danger, background: tokens.dangerBg, border: `1px solid ${tokens.danger}44`,
}}>
<ShieldAlert size={13} style={{ flexShrink: 0 }} />
<span>结论暂缓发布 · S4 数据质量阻断</span>
</div>
)}
{day ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
{bands.length === 0 && (
<span style={{ fontSize: 11, color: tokens.textMuted }}>当日无告警触发</span>
)}
{bands.map((x) => (
<span key={x.lv} style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: tokens.textSub }}>
<span style={{ width: 7, height: 7, borderRadius: '50%', background: toneColor(x.lv, tokens) }} />
<b style={{ color: toneColor(x.lv, tokens), fontVariantNumeric: 'tabular-nums' }}>{x.n}</b>
{ALERT_LEVELS[x.lv].label}
</span>
))}
</div>
) : (
<div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.5 }}>{scope.scopeLabel}</div>
)}
</div>
<AutoScrollProvider value={autoScroll}>
<ScrollList>
{!day && (
<div style={{ padding: '16px 4px' }}>
<div style={{ fontSize: 12, color: tokens.textMuted, textAlign: 'center', marginBottom: 8 }}>
该范围无日志贯通结果,不显示告警,也不显示 0
</div>
<div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.65 }}>{scope.gap}</div>
</div>
)}
{day && alerts.length === 0 && (
<div style={{ fontSize: 12, color: tokens.textMuted, padding: '18px 4px', textAlign: 'center' }}>
当日无告警触发
</div>
)}
{alerts.map((x, i) => {
const prev = alerts[i - 1];
/* 2026-11-14 动效层:入场 stagger。告警 id 本身含 bizDate(al-日期-设备-档-序),
切日时 key 天然变化→卡片重挂载→card-in 重播;展开/收起不重播。
延迟封顶 240ms(240+350=590ms ≤ 一次性动效 600ms 上限),只动 opacity/transform。 */
const delay = Math.min(i * 45, 240);
/* 换档时插一条分带线:滚动流里靠颜色条看不出档位变化 */
return (
<Fragment key={x.id}>
{!prev || prev.level !== x.level ? (
<div data-role={`band-${x.level}`} className="card-in" style={{ display: 'flex', alignItems: 'center', gap: 6, margin: i === 0 ? '0 0 6px' : '10px 0 6px', animationDelay: `${delay}ms` }}>
<span style={{ fontSize: 10.5, fontWeight: 700, color: toneColor(x.level, tokens), whiteSpace: 'nowrap' }}>
{ALERT_LEVELS[x.level].label} · {sum.byLevel[x.level]}
</span>
<span style={{ flex: 1, borderTop: `1px dashed ${tokens.border}` }} />
</div>
) : null}
<AlertCard alert={x} open={openId === x.id} onToggle={() => setOpenId(openId === x.id ? null : x.id)} tk={tokens} delay={delay} />
</Fragment>
);
})}
</ScrollList>
</AutoScrollProvider>
{/* 优先清单脚注:全站候选 Top3(信息性披露),不在此跳页。
导航指引半句「详见中央『优先处理清单』页签」于 2026-11-14 按要求移除(与标题行同名、冗余);
口径披露「全站候选(POC 指向)」保留:Top3 不随筛选变化,防误读为当日单机现算。 */}
<div style={{
flex: '0 0 auto', marginTop: 8, paddingTop: 8, borderTop: `1px solid ${tokens.border}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5 }}>
<ListOrdered size={12} color={tokens.accent} style={{ flexShrink: 0 }} />
<span style={{ fontSize: 11, fontWeight: 700, color: tokens.text }}>优先处理清单 · Top3</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10, color: tokens.textMuted }}>默认 B 套权重</span>
</div>
{top3.map((r) => (
<div key={r.item.id} style={{ display: 'flex', alignItems: 'baseline', gap: 6, fontSize: 11, marginBottom: 3 }}>
<span style={{
fontSize: 10, fontWeight: 700, width: 16, height: 16, lineHeight: '16px', textAlign: 'center',
borderRadius: 4, flexShrink: 0, color: tokens.accent, background: tokens.accentBg,
border: `1px solid ${tokens.borderAccent}`, fontVariantNumeric: 'tabular-nums',
}}>{r.rank}</span>
<span style={{
color: tokens.textSub, minWidth: 0, flex: 1,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{r.item.title}</span>
<span style={{ color: tokens.accent, fontWeight: 700, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>
{r.score.score.toFixed(3)}
</span>
</div>
))}
<div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 4, lineHeight: 1.5 }}>
全站候选(POC 指向)
</div>
</div>
</PanelShell>
);
}
/* ── 单张告警卡 ───────────────────────────────────────────────────────── */
function AlertCard({ alert: x, open, onToggle, tk, delay = 0 }: {
alert: OeeAlert; open: boolean; onToggle: () => void; tk: ThemeTokens; delay?: number;
}) {
const c = toneColor(x.level, tk);
return (
<div
data-role={`alert-${x.id}`}
className="card-in"
style={{
marginBottom: 6, borderRadius: 10, overflow: 'hidden',
background: tk.cardBg, border: `1px solid ${open ? c : tk.border}`,
boxShadow: open ? `0 0 0 1px ${c}33` : 'none',
animationDelay: `${delay}ms`,
}}
>
<button
onClick={onToggle}
aria-expanded={open}
style={{
display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
background: 'transparent', border: 0, padding: 0, color: 'inherit', font: 'inherit',
}}
>
{/* 左侧档位条 + 收起态两行 */}
<div style={{ display: 'flex', gap: 7, padding: '7px 9px 7px 0' }}>
<span style={{ width: 3, alignSelf: 'stretch', borderRadius: 2, background: c, flexShrink: 0, marginLeft: 3 }} />
<span style={{ minWidth: 0, flex: 1 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 5px', borderRadius: 5, flexShrink: 0,
color: c, background: toneBg(x.level, tk), border: `1px solid ${c}33`, lineHeight: '15px',
}}>{x.kind}</span>
{/* 两行截断而不是单行省略:收起态宽度下判档依据不该被截掉 */}
<span style={{
fontSize: 12.5, fontWeight: 600, color: tk.text, minWidth: 0, flex: 1,
display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
overflow: 'hidden', lineHeight: 1.35,
}}>{x.title}</span>
{/* S4 阻断在收起态就挂红标:暂停发布是同级告警的核心权力,不靠展开才发现。
2026-11-14 动效层:glow-pulse 3s 慢脉冲只挂 blocksPublish 真实阻断态,
红色光晕由 --glow-color 注入;无阻断不脉冲,不冒充实时心跳。 */}
{x.blocksPublish && (
<span className="glow-pulse" style={{
display: 'flex', alignItems: 'center', gap: 2, flexShrink: 0,
fontSize: 9.5, fontWeight: 700, padding: '0 4px', borderRadius: 5, lineHeight: '15px',
color: tk.danger, background: tk.dangerBg, border: `1px solid ${tk.danger}44`,
'--glow-color': `${tk.danger}55`,
} as CSSProperties}>
<ShieldAlert size={9} />暂停发布
</span>
)}
{open
? <ChevronDown size={13} color={tk.textMuted} style={{ flexShrink: 0 }} />
: <ChevronRight size={13} color={tk.textMuted} style={{ flexShrink: 0 }} />}
</span>
<span style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 3 }}>
<span style={{
fontSize: 10.5, color: tk.textMuted, minWidth: 0, flex: 1,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{x.subject}</span>
<span style={{ fontSize: 10.5, color: tk.textSub, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>
{x.metric.label} <b style={{ color: c, fontWeight: 700 }}>{x.metric.value}</b>
</span>
</span>
</span>
</div>
</button>
{/* 展开态:判定字段 + 处置动作 + 责任/升级 + 状态 + 口径 + 来源,就地给出,不跳转 */}
{open && (
<div data-role={`alert-detail-${x.id}`} style={{ padding: '0 10px 9px 13px', borderTop: `1px dashed ${tk.border}` }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 3, paddingTop: 7 }}>
{x.fields.map((f) => (
<div key={f.label} style={{ display: 'flex', gap: 6, fontSize: 11, lineHeight: 1.5 }}>
{/* 标签列不折行:'判定条件' 被压成两行时整块明细读起来很碎 */}
<span style={{ color: tk.textMuted, flex: '0 0 auto', minWidth: 62, whiteSpace: 'nowrap' }}>{f.label}</span>
<span style={{ color: tk.text, minWidth: 0, wordBreak: 'break-word' }}>{f.value}</span>
</div>
))}
</div>
<div style={{
marginTop: 7, padding: '6px 8px', borderRadius: 8,
background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
}}>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>处置动作</span>
<div style={{ fontSize: 11.5, color: tk.text, lineHeight: 1.55, marginTop: 1 }}>{x.action}</div>
<div style={{ fontSize: 10.5, color: tk.textSub, marginTop: 3 }}>
责任:{x.owner} · 升级:{x.escalation}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>状态</span>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 5px', borderRadius: 5, lineHeight: '15px',
color: c, background: toneBg(x.level, tk), border: `1px solid ${c}33`,
}}>{ALERT_STATE_LABEL[x.state]}</span>
</div>
</div>
<div style={{ marginTop: 6, fontSize: 10.5, color: tk.textMuted, lineHeight: 1.55 }}>
<div>判定口径:{x.caliber}</div>
<div style={{ marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 5px', borderRadius: 5, lineHeight: '15px',
color: tk.accent, background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
}}>{x.source}</span>
<span>数据来源</span>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,122 @@
import { useEffect, useMemo, useState } from 'react';
import { BellRing, Maximize2, ShieldAlert } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { CountBadge } from '../layout/PanelShell';
import { resolveScope, type OeeFilter } from '../../lib/oeeFilters';
import { deriveAlerts, alertStats } from '../../lib/oeeService';
import { ALERT_LEVELS, ALERT_LEVEL_ORDER } from '../../types/oee';
import OeeAlertPanel from './OeeAlertPanel';
/**
* 告警摘要卡(右栏对话上方):与 OeeAlertPanel 同一个 deriveAlerts/alertStats 源,只给档位计数 + 最新两条;
* 「展开」从右侧拉出完整告警流。compact=对话栏收起时的铃铛计数钮。
*/
export default function OeeAlertStrip({ filter, compact = false }: { filter: OeeFilter; compact?: boolean }) {
const { tokens } = useTheme();
const [drawer, setDrawer] = useState(false);
const scope = useMemo(() => resolveScope(filter), [filter]);
const day = scope.day;
const alerts = useMemo(() => (day ? deriveAlerts(day) : []), [day]);
const sum = useMemo(() => alertStats(alerts), [alerts]);
const bands = ALERT_LEVEL_ORDER.map((lv) => ({ lv, n: sum.byLevel[lv] })).filter((x) => x.n > 0);
useEffect(() => {
if (!drawer) return;
const onKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setDrawer(false); };
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [drawer]);
const drawerEl = drawer && (
<div
onClick={() => setDrawer(false)}
style={{ position: 'fixed', inset: 0, zIndex: 70, background: 'rgba(0,0,0,0.28)', display: 'flex', justifyContent: 'flex-end' }}
>
<div onClick={(e) => e.stopPropagation()} style={{ height: '100%', padding: '16px 0', display: 'flex' }}>
<OeeAlertPanel expanded onToggle={() => setDrawer(false)} filter={filter} />
</div>
</div>
);
if (compact) {
return (
<>
<button
onClick={() => setDrawer(true)}
data-role="alert-strip-open"
className="ghost-btn"
title={`OEE 告警 ${day ? sum.total : '—'} 条${sum.blocksPublish ? ' · 结论暂缓发布' : ''},点击展开`}
style={{
flexShrink: 0, cursor: 'pointer', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
padding: '8px 0', borderRadius: 14, background: tokens.panelBgAlt,
border: `1px solid ${sum.blocksPublish ? `${tokens.danger}66` : tokens.border}`,
}}
>
<BellRing size={14} color={tokens.accent} />
<CountBadge n={day ? sum.total : '—'} color={sum.blocksPublish ? tokens.danger : tokens.warning} />
</button>
{drawerEl}
</>
);
}
return (
<>
<div data-role="alert-strip" style={{
flex: '0 0 auto', minWidth: 0, display: 'flex', flexDirection: 'column', gap: 4,
borderRadius: 11, padding: '7px 10px',
background: tokens.panelBgAlt, border: `1px solid ${sum.blocksPublish ? `${tokens.danger}66` : tokens.border}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<BellRing size={14} color={tokens.accent} />
<span style={{ fontSize: 13, fontWeight: 800, color: tokens.text, whiteSpace: 'nowrap', flexShrink: 0 }}>OEE 告警</span>
<CountBadge n={day ? sum.total : '—'} color={sum.blocksPublish ? tokens.danger : tokens.warning} />
<span style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', minWidth: 0 }}>
{day ? '当日实测' : '未接入'} · {scope.bizDate}{day ? ` · ${day.device.id}` : ''}
</span>
<span style={{ flex: 1 }} />
<button
onClick={() => setDrawer(true)}
data-role="alert-strip-open"
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 4, cursor: 'pointer', flexShrink: 0,
fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 20,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<Maximize2 size={11} /> 展开
</button>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', fontSize: 11 }}>
{sum.blocksPublish && (
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontWeight: 700, color: tokens.danger }}>
<ShieldAlert size={12} /> 结论暂缓发布
</span>
)}
{day && bands.length === 0 && <span style={{ color: tokens.textMuted }}>当日无告警触发</span>}
{bands.map((x) => (
<span key={x.lv} style={{ display: 'flex', alignItems: 'center', gap: 3, color: tokens.textSub }}>
<span style={{ width: 7, height: 7, borderRadius: '50%', background: tokens[ALERT_LEVELS[x.lv].tone] }} />
<b style={{ color: tokens[ALERT_LEVELS[x.lv].tone], fontVariantNumeric: 'tabular-nums' }}>{x.n}</b>
{ALERT_LEVELS[x.lv].label}
</span>
))}
{!day && <span style={{ color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{scope.scopeLabel}</span>}
</div>
{alerts.slice(0, 2).map((x) => (
<div key={x.id} style={{ display: 'flex', alignItems: 'center', gap: 5, minWidth: 0, fontSize: 11.5 }}>
<span style={{ width: 3, height: 13, borderRadius: 2, flexShrink: 0, background: tokens[ALERT_LEVELS[x.level].tone] }} />
<span style={{ fontSize: 10, fontWeight: 700, color: tokens[ALERT_LEVELS[x.level].tone], flexShrink: 0 }}>{x.kind}</span>
<span style={{ color: tokens.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{x.title}</span>
</div>
))}
</div>
{drawerEl}
</>
);
}
@@ -0,0 +1,228 @@
import { Fragment, useMemo, useState } from 'react';
import { BellRing, ChevronDown, ChevronRight } from 'lucide-react';
import PanelShell, { CountBadge } from '../layout/PanelShell';
import { AutoScrollProvider, AutoScrollToggle, ScrollList } from '../layout/AutoScroll';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { useText } from '../../i18n/useText';
import {
alertKindLabel, alertSummary, qualityAlertsAt,
type AlertLevel, type QualityAlert,
} from '../../lib/qualityAlerts';
import { CURRENT_PERIOD, periodLabel } from '../../lib/time';
interface Props {
expanded: boolean;
onToggle: () => void;
/** 全局回放游标:告警流与中央六页签同一时点读数 */
period: number;
}
/** 档位色:muted 走中性灰,已闭环的条目不该再占一个告警色 */
function levelColor(lv: AlertLevel, tk: ThemeTokens): string {
if (lv === 'red') return tk.danger;
if (lv === 'orange') return tk.warning;
if (lv === 'blue') return tk.info;
return tk.textMuted;
}
/** 档位底色(很淡的一层,只给角标和分带线用) */
function levelBg(lv: AlertLevel, tk: ThemeTokens): string {
if (lv === 'red') return tk.dangerBg;
if (lv === 'orange') return tk.warningBg;
if (lv === 'blue') return tk.infoBg;
return tk.panelBgAlt;
}
/**
* 右栏「质量告警」:DS-15/DS-16/DS-14/DS-07 四张源表汇成一条按严重度分带的告警流,
* 卡片默认收起,点一下在原处展开该条的原表字段与处置动作(不跳页、不切舞台)。
* 判定与读数全部来自 qualityAlerts(),页面不写死任何统计值。
*/
export default function QualityAlertPanel({ expanded, onToggle, period }: Props) {
const { tokens } = useTheme();
const { t } = useText();
/* 列表多到一屏装不下时缓慢下滚,标题栏按钮可关;和左栏同一套开关语义 */
const [autoScroll, setAutoScroll] = useState(true);
/* 同一时刻只展开一张:滚动的信息流里同时摊开两张就看不出顺序了 */
const [openId, setOpenId] = useState<string | null>(null);
const list = useMemo(() => qualityAlertsAt(period), [period]);
const sum = useMemo(() => alertSummary(list), [list]);
const a = t.alert;
const levelName: Record<AlertLevel, string> = {
red: a.levelRed, orange: a.levelOrange, blue: a.levelBlue, muted: a.levelMuted,
};
const allBands: { lv: AlertLevel; n: number }[] = [
{ lv: 'red', n: sum.red }, { lv: 'orange', n: sum.orange },
{ lv: 'blue', n: sum.blue }, { lv: 'muted', n: sum.muted },
];
/* 计数为 0 的档位不占汇总位,否则「蓝 0」看着像漏采 */
const bands = allBands.filter(x => x.n > 0);
return (
<PanelShell
side="right" expanded={expanded} onToggle={onToggle}
widthCollapsed={268} widthExpanded={468}
icon={<BellRing size={16} />}
title={a.title}
badge={<CountBadge n={sum.total} color={tokens.danger} />}
extra={<AutoScrollToggle on={autoScroll} onToggle={() => setAutoScroll(v => !v)} expanded={expanded} />}
animClass="space-animate-right"
>
{/* 汇总带固定在标题下方,不随列表滚走:滚到哪儿都知道整池是什么结构 */}
<div style={{
flex: '0 0 auto', marginBottom: 8, padding: '7px 9px', borderRadius: 9,
background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<div style={{
display: 'flex', alignItems: 'center', gap: 5, marginBottom: 5,
fontSize: 10.5, color: period === CURRENT_PERIOD ? tokens.textMuted : tokens.warning,
fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em',
}}>
<span style={{
padding: '1px 5px', borderRadius: 4,
border: `1px solid ${period === CURRENT_PERIOD ? tokens.border : tokens.warning}55`,
background: period === CURRENT_PERIOD ? 'transparent' : tokens.warningBg,
fontWeight: 700,
}}>{period === CURRENT_PERIOD ? '源表当期' : '回放推算'}</span>
<span>{period === CURRENT_PERIOD ? '2026-10 快照' : `${periodLabel(period)} · 缺口明细仍为源表`}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
{bands.map(x => (
<span key={x.lv} style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11, color: tokens.textSub }}>
<span style={{ width: 7, height: 7, borderRadius: '50%', background: levelColor(x.lv, tokens) }} />
<b style={{ color: levelColor(x.lv, tokens), fontVariantNumeric: 'tabular-nums' }}>{x.n}</b>
{levelName[x.lv]}
</span>
))}
</div>
</div>
<AutoScrollProvider value={autoScroll}>
<ScrollList>
{list.length === 0 && (
<div style={{ fontSize: 12, color: tokens.textMuted, padding: '18px 4px', textAlign: 'center' }}>{a.empty}</div>
)}
{list.map((x, i) => {
const prev = list[i - 1];
/* 换档时插一条分带线:滚动流里靠颜色条看不出档位变化 */
return (
<Fragment key={x.id}>
{!prev || prev.level !== x.level ? (
<div data-role={`band-${x.level}`} style={{ display: 'flex', alignItems: 'center', gap: 6, margin: i === 0 ? '0 0 6px' : '10px 0 6px' }}>
<span style={{ fontSize: 10.5, fontWeight: 700, color: levelColor(x.level, tokens), whiteSpace: 'nowrap' }}>
{levelName[x.level]} · {sum[x.level]}
</span>
<span style={{ flex: 1, borderTop: `1px dashed ${tokens.border}` }} />
</div>
) : null}
<AlertCard alert={x} open={openId === x.id} onToggle={() => setOpenId(openId === x.id ? null : x.id)} tk={tokens} />
</Fragment>
);
})}
</ScrollList>
</AutoScrollProvider>
</PanelShell>
);
}
/* ── 单张告警卡 ───────────────────────────────────────────────────────── */
function AlertCard({ alert: x, open, onToggle, tk }: {
alert: QualityAlert; open: boolean; onToggle: () => void; tk: ThemeTokens;
}) {
const { t } = useText();
const a = t.alert;
const c = levelColor(x.level, tk);
return (
<div
data-role={`alert-${x.id}`}
style={{
marginBottom: 6, borderRadius: 10, overflow: 'hidden',
background: tk.cardBg, border: `1px solid ${open ? c : tk.border}`,
boxShadow: open ? `0 0 0 1px ${c}33` : 'none',
}}
>
<button
onClick={onToggle}
aria-expanded={open}
style={{
display: 'block', width: '100%', textAlign: 'left', cursor: 'pointer',
background: 'transparent', border: 0, padding: 0, color: 'inherit', font: 'inherit',
}}
>
{/* 左侧档位条 + 收起态两行 */}
<div style={{ display: 'flex', gap: 7, padding: '7px 9px 7px 0' }}>
<span style={{ width: 3, alignSelf: 'stretch', borderRadius: 2, background: c, flexShrink: 0, marginLeft: 3 }} />
<span style={{ minWidth: 0, flex: 1 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 5px', borderRadius: 5, flexShrink: 0,
color: c, background: levelBg(x.level, tk), border: `1px solid ${c}33`, lineHeight: '15px',
}}>{alertKindLabel(x.kind)}</span>
{/* 两行截断而不是单行省略:收起态宽度下「激光功率 超差(已出允差)」
被截成「激光功率 超差(已…」会把判档依据丢掉 */}
<span style={{
fontSize: 12.5, fontWeight: 600, color: tk.text, minWidth: 0, flex: 1,
display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
overflow: 'hidden', lineHeight: 1.35,
}}>{x.title}</span>
{open
? <ChevronDown size={13} color={tk.textMuted} style={{ flexShrink: 0 }} />
: <ChevronRight size={13} color={tk.textMuted} style={{ flexShrink: 0 }} />}
</span>
<span style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 3 }}>
<span style={{
fontSize: 10.5, color: tk.textMuted, minWidth: 0, flex: 1,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{x.subject || x.role}</span>
<span style={{ fontSize: 10.5, color: tk.textSub, whiteSpace: 'nowrap', fontVariantNumeric: 'tabular-nums' }}>
{x.metric.label} <b style={{ color: c, fontWeight: 700 }}>{x.metric.value}</b>
</span>
</span>
</span>
</div>
</button>
{/* 展开态:原表全部字段 + 处置动作 + 判定口径 + 来源,就地给出,不跳转 */}
{open && (
<div data-role={`alert-detail-${x.id}`} style={{ padding: '0 10px 9px 13px', borderTop: `1px dashed ${tk.border}` }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 3, paddingTop: 7 }}>
{x.fields.map(f => (
<div key={f.label} style={{ display: 'flex', gap: 6, fontSize: 11, lineHeight: 1.5 }}>
{/* 标签列不折行:'标准值 / 允许偏差' 被压成两行时整块明细读起来很碎 */}
<span style={{ color: tk.textMuted, flex: '0 0 auto', minWidth: 62, whiteSpace: 'nowrap' }}>{f.label}</span>
<span style={{ color: tk.text, minWidth: 0, wordBreak: 'break-word' }}>{f.value}</span>
</div>
))}
</div>
<div style={{
marginTop: 7, padding: '6px 8px', borderRadius: 8,
background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
}}>
<span style={{ fontSize: 10.5, color: tk.textMuted }}>{a.action}</span>
<div style={{ fontSize: 11.5, color: tk.text, lineHeight: 1.55, marginTop: 1 }}>{x.action}</div>
{(x.owner || x.role) && (
<div style={{ fontSize: 10.5, color: tk.textSub, marginTop: 3 }}>
{a.owner}:{x.owner || '—'} · {x.role}
</div>
)}
</div>
<div style={{ marginTop: 6, fontSize: 10.5, color: tk.textMuted, lineHeight: 1.55 }}>
<div>{a.caliber}:{x.caliber}</div>
<div style={{ marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
<span style={{
fontSize: 10, fontWeight: 700, padding: '0 5px', borderRadius: 5, lineHeight: '15px',
color: tk.accent, background: tk.accentBg, border: `1px solid ${tk.borderAccent}`,
}}>{x.source.ds}</span>
<span>{a.source}:{x.source.table}</span>
</div>
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,293 @@
/**
* 口径字典与版本治理面板(配置中心 · W4-A,断言⑩ / 规划书 4.1.7 / 附录 E)。
*
* ★ 本次不安排口径工作坊 ⇒ 28 项 signedOff 全 false。真实台账(CALIBER_CONFIG)永远显示
* 「待 IE 签字」、P0 标灰不标绿。本面板的签字演示是**沙箱副本**,明确标注模拟,不改真实台账。
*
* 三条引擎硬规则(lib/oee/caliber.ts,视图只调用不重算):
* 1. 只有取值真的变了才递增版本(resolveCaliber);改备注/签字不产生新版本。
* 2. 跨版本对比默认拒绝(compareAcrossVersions);显式确认后也只允许并列展示,不得相减出"改善幅度"。
* 3. 旧版本保留可回放:每次解析新版本都进历史,选任一旧版即可回看其快照与对基线的差异。
*
* 纪律:数字与版本一律走 L3(resolveCaliber/signOff/diffVersions/compareAcrossVersions/signOffStatus),
* 视图不另写一份版本号字符串、不二次计算敏感性快照。
*/
import { useState } from 'react';
import { ShieldCheck, GitCompare, FileSignature, AlertTriangle, CheckCircle2, RotateCcw } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
CALIBER_CONFIG, CALIBER_VERSION, SENSITIVITY_ISSUES, caliberStats,
resolveCaliber, signOff, diffVersions, compareAcrossVersions, signOffStatus, bumpVersion,
type CaliberConfig, type CaliberItem, type SensitivityIssue,
} from '../../lib/oeeService';
import {
Card, Tiles, Table, Th, Td, Chip, Note, GapBox, grid2,
} from '../workspace/oeeUi';
interface VersionEntry { version: string; config: CaliberConfig; label: string; at: string; changeCount: number }
const SENSITIVITY_LABEL: Record<SensitivityIssue, string> = {
planBoundary: 'Plan 边界', occRule: 'Occ 判定', qDefinition: 'Q 定义', ftPmIncluded: 'FT 的 PM 是否计入',
};
/** 按原值类型解析输入(number/boolean/string),不静默把数字当字符串。 */
function parseValue(original: string | number | boolean, input: string): string | number | boolean {
if (typeof original === 'number') { const n = Number(input); return Number.isFinite(n) ? n : original; }
if (typeof original === 'boolean') return input.trim() === 'true';
return input;
}
export default function CaliberVersionPanel() {
const { tokens } = useTheme();
const cs = caliberStats();
const items = Object.values(CALIBER_CONFIG.items) as CaliberItem[];
const realStatus = signOffStatus(CALIBER_CONFIG);
const baseline: VersionEntry = { version: CALIBER_VERSION, config: CALIBER_CONFIG, label: '基线(附录 E 默认值)', at: CALIBER_CONFIG.effectiveFrom, changeCount: 0 };
const [history, setHistory] = useState<VersionEntry[]>([baseline]);
const [editId, setEditId] = useState<string>('C03');
const [editValue, setEditValue] = useState<string>('');
const [replayIdx, setReplayIdx] = useState<number | null>(null);
const [ackCross, setAckCross] = useState<boolean>(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const [signSandbox, setSignSandbox] = useState<CaliberConfig | null>(null);
const currentIdx = history.length - 1;
const active = history[currentIdx];
const viewIdx = replayIdx ?? currentIdx;
const viewed = history[viewIdx];
const editItem = active.config.items[editId];
const diff = diffVersions(baseline.config, viewed.config);
const cmp = compareAcrossVersions(baseline.config, viewed.config, {
allowCrossVersion: ackCross,
...(ackCross ? { acknowledgedBy: 'IE(演示确认)' } : {}),
});
const inputStyle = {
width: '100%', minWidth: 0, boxSizing: 'border-box' as const,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, borderRadius: 7,
padding: '5px 8px', fontSize: 11.5, color: tokens.text, outline: 'none',
};
const save = () => {
if (!editItem || editValue.trim() === '') { setMsg({ ok: false, text: '请先选择口径项并填写新取值' }); return; }
const parsed = parseValue(editItem.defaultValue, editValue.trim());
const rev = history.length;
const cfg = resolveCaliber(active.config, { [editId]: parsed }, { revision: rev });
const d = diffVersions(active.config, cfg);
if (d.changes.length === 0) { setMsg({ ok: false, text: '取值未变,不产生新版本(改备注/签字不递增版本)' }); return; }
const version = bumpVersion(CALIBER_VERSION, rev);
const entry: VersionEntry = { version, config: { ...cfg, version }, label: `改 ${editId}`, at: new Date().toISOString(), changeCount: d.changes.length };
setHistory([...history, entry]);
setReplayIdx(null);
setEditValue('');
setMsg({ ok: true, text: `解析新版本 ${version}(${d.changes.length} 项取值变更,其中 ${d.sensitivityChanges.length} 项属敏感性议题)` });
};
const simulateSign = () => {
const p0Ids = (Object.values(active.config.items) as CaliberItem[]).filter((i) => i.priority === 'P0').map((i) => i.id);
setSignSandbox(signOff(active.config, p0Ids));
};
const sandboxStatus = signSandbox ? signOffStatus(signSandbox) : null;
const priorityTone = (p: CaliberItem['priority']): string => p === 'P0' ? tokens.textMuted : tokens.textSub;
return (
<>
{/* ── 28 项口径字典(真实台账,全未签字) ── */}
<Card
title={`28 项口径字典 · ${CALIBER_VERSION}`}
icon={<ShieldCheck size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted} title={realStatus.uiLabel}>待 IE 签字 {realStatus.unsigned}/{realStatus.total}</Chip>}
note="两个「优先级」不可混:priority P0/P1/P2 影响「能不能算」(P0 16/P1 11/P2 1);isSensitivityKey(★)影响「算出来是多少」(5 项承载 4 议题)。本次不安排口径工作坊,signedOff 全 false,P0 标灰「待 IE 签字」——灰不等于错,是还没人签字。"
>
<Tiles items={[
{ label: '口径项', value: String(cs.total), sub: 'C01–C28', color: tokens.textSub },
{ label: 'P0 待确认', value: String(cs.p0), sub: '能不能算', color: tokens.textMuted, title: 'P0 标灰不标绿' },
{ label: 'P1/P2 生效', value: String(cs.p1 + cs.p2), sub: '默认值生效中', color: tokens.textSub },
{ label: '敏感性议题', value: String(cs.sensitivityKeys), sub: '算出多少', color: tokens.warning, title: 'C03/C04/C06/C09/C10 承载 4 议题' },
{ label: '已签字', value: String(cs.signed), sub: '本次不安排工作坊', color: tokens.textMuted },
]} />
<div style={{ marginTop: 9 }}>
<Table maxHeight={300} head={<>
<Th>编号</Th><Th>口径项</Th><Th>默认值</Th><Th>优先级</Th><Th>归口</Th><Th>签字</Th>
</>}>
{items.map((c) => (
<tr key={c.id} style={{ background: c.id === editId ? tokens.accentBg : undefined, cursor: 'pointer' }} onClick={() => { setEditId(c.id); setEditValue(''); setMsg(null); }}>
<Td bold mono>{c.id}{c.isSensitivityKey && <span style={{ color: tokens.warning }} title="敏感性议题:影响 OEE 绝对值"> ★</span>}</Td>
<Td color={tokens.textSub}><span title={c.note}>{c.name}</span></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{String(c.defaultValue)}</span></Td>
<Td><Chip color={priorityTone(c.priority)} title={c.priority === 'P0' ? 'P0 标灰:待确认,不标绿' : '默认值生效中'}>{c.priority}</Chip></Td>
<Td color={tokens.textMuted}>{c.owner}</Td>
<Td><Chip color={tokens.textMuted}>待签字</Chip></Td>
</tr>
))}
</Table>
</div>
{/* 试改一项 → 解析新版本 */}
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,2fr) auto', gap: 9, alignItems: 'end', marginTop: 10 }}>
<div style={{ minWidth: 0 }}>
<label style={{ fontSize: 10.5, fontWeight: 600, color: tokens.textSub, marginBottom: 3, display: 'block' }}>试改口径项(点上行或下拉)</label>
<select style={inputStyle} value={editId} onChange={(e) => { setEditId(e.target.value); setEditValue(''); setMsg(null); }}>
{items.map((c) => <option key={c.id} value={c.id}>{c.id}{c.isSensitivityKey ? ' ★' : ''} · {c.name.slice(0, 14)}</option>)}
</select>
</div>
<div style={{ minWidth: 0 }}>
<label style={{ fontSize: 10.5, fontWeight: 600, color: tokens.textSub, marginBottom: 3, display: 'block' }}>
新取值(当前:{editItem ? String(editItem.defaultValue) : '—'})
</label>
<input style={inputStyle} value={editValue} onChange={(e) => setEditValue(e.target.value)} placeholder={editItem ? `如改 ${editId} 的取值…` : '选择口径项'} />
</div>
<button onClick={save} style={{
fontSize: 11.5, fontWeight: 700, padding: '6px 16px', borderRadius: 8, cursor: 'pointer', whiteSpace: 'nowrap',
border: `1px solid ${tokens.accent}`, background: tokens.accentBg, color: tokens.accent,
}}>解析新版本</button>
</div>
{editItem?.isSensitivityKey && (
<Note>★ {editId} 属敏感性议题({Object.values(SENSITIVITY_ISSUES).filter((s) => (s.items as readonly string[]).includes(editId)).map((s) => s.label).join('、')}):改它会改变 OEE 绝对值,须 IE 定版。跨版本对比默认拒绝。</Note>
)}
{msg && (
<div style={{
marginTop: 8, padding: '7px 9px', borderRadius: 9, minWidth: 0,
background: msg.ok ? `${tokens.success}12` : `${tokens.warning}12`,
border: `1px solid ${msg.ok ? tokens.success : tokens.warning}44`,
fontSize: 11, color: msg.ok ? tokens.success : tokens.warning, lineHeight: 1.5,
}}>{msg.text}</div>
)}
</Card>
{/* ── 版本历史/回放/跨版本闸 + 签字沙箱 ── */}
<div style={grid2}>
<Card
title="版本历史 · 回放 · 跨版本对比闸"
icon={<GitCompare size={14} color={tokens.warning} />}
right={<Chip color={cmp.allowed ? tokens.success : tokens.warning} title={cmp.notice}>{cmp.allowed ? '允许对比' : '拒绝跨版本'}</Chip>}
note="断言⑩:两个口径版本的结果不可直接相减。默认拒绝;显式确认(IE)后也只允许并列展示,差值含口径效应,不得作为改善成果发布。点历史条目回放旧版。"
>
{/* 版本历史 */}
<Table maxHeight={150} head={<><Th>版本</Th><Th>来源</Th><Th right>变更</Th><Th>回放</Th></>}>
{history.map((h, i) => {
const on = i === viewIdx;
return (
<tr key={h.version + i} onClick={() => { setReplayIdx(i === currentIdx ? null : i); setMsg(null); }} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}>
<Td mono bold color={on ? tokens.accent : tokens.textSub}>{h.version}</Td>
<Td color={tokens.textMuted}>{h.label}{i === currentIdx ? '(当前)' : ''}</Td>
<Td right mono>{h.changeCount}</Td>
<Td>{on ? <Chip color={tokens.accent}>查看中</Chip> : <Chip color={tokens.textMuted}>回放</Chip>}</Td>
</tr>
);
})}
</Table>
{/* 跨版本闸通知 */}
<div style={{
marginTop: 9, padding: '8px 10px', borderRadius: 9, minWidth: 0,
background: cmp.allowed ? `${tokens.success}12` : `${tokens.warning}12`,
border: `1px solid ${cmp.allowed ? tokens.success : tokens.warning}44`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
{cmp.allowed ? <CheckCircle2 size={13} color={tokens.success} /> : <AlertTriangle size={13} color={tokens.warning} />}
<span style={{ fontSize: 11.5, fontWeight: 700, color: cmp.allowed ? tokens.success : tokens.warning }}>
{diff.sameVersion ? '同一口径版本' : cmp.allowed ? '已确认·仅并列不相减' : '拒绝跨版本对比'}
</span>
</div>
<div style={{ fontSize: 10.5, color: tokens.textSub, lineHeight: 1.55 }}>{cmp.notice}</div>
{!diff.sameVersion && (
<label style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: tokens.textSub, cursor: 'pointer', marginTop: 5 }}>
<input type="checkbox" checked={ackCross} onChange={(e) => setAckCross(e.target.checked)} />
IE 已确认跨版本并列展示(演示确认,非真实签批)
</label>
)}
</div>
{/* 差异明细 */}
{diff.changes.length > 0 ? (
<div style={{ marginTop: 9 }}>
<Note>对基线({baseline.version})的取值差异(只比取值,不比签字状态):</Note>
<Table maxHeight={160} head={<><Th>编号</Th><Th>基线值</Th><Th>回放值</Th><Th>敏感性</Th></>}>
{diff.changes.map((c) => (
<tr key={c.id}>
<Td bold mono>{c.id}{c.isSensitivityKey && <span style={{ color: tokens.warning }}> ★</span>}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10 }}>{String(c.before)}</span></Td>
<Td color={tokens.text}><span style={{ fontSize: 10 }}>{String(c.after)}</span></Td>
<Td>{c.isSensitivityKey ? <Chip color={tokens.warning}>影响 OEE</Chip> : <Chip color={tokens.textMuted}>非敏感</Chip>}</Td>
</tr>
))}
</Table>
{diff.affectedIssues.length > 0 && (
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
{diff.affectedIssues.map((k) => <Chip key={k} color={tokens.warning}>{SENSITIVITY_LABEL[k]}</Chip>)}
</div>
)}
</div>
) : (
<Note>当前查看版本与基线取值一致(无差异)。改一项敏感性口径即可看到跨版本拒绝闸。</Note>
)}
{/* 回放快照 */}
<div style={{ marginTop: 9 }}>
<Note>回放快照 · {viewed.version} 的敏感性取值(引擎现推,不写死):</Note>
<Table head={<><Th>议题</Th><Th>取值</Th></>}>
<tr><Td color={tokens.textSub}>Plan 边界</Td><Td color={tokens.textMuted}><span style={{ fontSize: 10 }}>{viewed.config.sensitivitySnapshot.planBoundary}</span></Td></tr>
<tr><Td color={tokens.textSub}>Occ 判定</Td><Td color={tokens.textMuted}><span style={{ fontSize: 10 }}>{viewed.config.sensitivitySnapshot.occRule}</span></Td></tr>
<tr><Td color={tokens.textSub}>Q 定义</Td><Td color={tokens.textMuted}><span style={{ fontSize: 10 }}>{viewed.config.sensitivitySnapshot.qDefinition}</span></Td></tr>
<tr><Td color={tokens.textSub}>FT 的 PM 计入</Td><Td mono>{viewed.config.sensitivitySnapshot.ftPmIncluded ? '是' : '否'}</Td></tr>
</Table>
</div>
</Card>
<Card
title="签字治理(沙箱演示)"
icon={<FileSignature size={14} color={tokens.info} />}
right={<Chip color={realStatus.p0Tone === 'green' ? tokens.success : tokens.textMuted} title={realStatus.uiLabel}>真实台账 P0 {realStatus.p0Tone === 'green' ? '已签' : '标灰'}</Chip>}
note="签字改的是治理状态,不改取值 ⇒ signOff 不递增版本号(引擎 invariant)。真实台账 CALIBER_CONFIG 永远全未签字;下方沙箱只在副本上演示「IE 签字后 P0 才转绿」,明确标注模拟,不写回真实台账。"
>
{/* 真实签字状态 */}
<Tiles items={[
{ label: '真实已签', value: `${realStatus.signed}/${realStatus.total}`, sub: '全未签字', color: tokens.textMuted },
{ label: 'P0 未签', value: String(realStatus.p0Unsigned), sub: '标灰不标绿', color: tokens.textMuted },
{ label: '敏感性未签', value: String(realStatus.sensitivityUnsigned), sub: '须 IE 定版', color: tokens.warning },
]} />
<div style={{ marginTop: 8 }}>
<GapBox
missing={`口径 ${CALIBER_VERSION} 待 IE 签字(已签 ${realStatus.signed}/${realStatus.total},P0 未签 ${realStatus.p0Unsigned} 项)`}
dependsOn="IE 口径工作坊(本次不安排)"
stage="参数确认后在配置中心签字定版"
note="平台按附录 E 默认值先行落地;未签字前不得当作客户确认口径。P0 标灰是治理事实,不是数据错误。"
/>
</div>
{/* 沙箱 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
<button onClick={simulateSign} style={{
fontSize: 11, fontWeight: 700, padding: '5px 13px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.info}`, background: `${tokens.info}1f`, color: tokens.info,
}}>模拟 IE 签字(全部 P0·副本)</button>
{signSandbox && (
<button onClick={() => setSignSandbox(null)} style={{
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600,
padding: '5px 12px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.border}`, background: 'transparent', color: tokens.textSub,
}}><RotateCcw size={12} />重置沙箱</button>
)}
</div>
{sandboxStatus && signSandbox && (
<div style={{ marginTop: 9, padding: '8px 10px', borderRadius: 9, background: tokens.panelBgAlt, border: `1px dashed ${tokens.border}`, minWidth: 0 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>沙箱结果(模拟,非真实 IE 确认)</div>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
<Chip color={sandboxStatus.p0Tone === 'green' ? tokens.success : tokens.textMuted}>P0 {sandboxStatus.p0Tone === 'green' ? '转绿' : '仍灰'}</Chip>
<Chip color={tokens.textSub}>已签 {sandboxStatus.signed}/{sandboxStatus.total}</Chip>
<Chip color={tokens.info} title="签字不递增版本">版本仍 {signSandbox.version}</Chip>
</div>
<Note>签字后版本不变({signSandbox.version}):signOff 只改 signedOff 治理状态,不改取值,OEE 数值不变。真实台账未受影响,仍全未签字。</Note>
</div>
)}
{!signSandbox && <Note>点「模拟 IE 签字」在副本上演示治理流程:P0 全签后 p0Tone 才转 green,且版本号不递增。真实台账保持「待 IE 签字」。</Note>}
</Card>
</div>
</>
);
}
@@ -0,0 +1,379 @@
/**
* 配置中心 · 四轴配置面板(caliber 页签 · W4-A,建议书 §5.2.2 / 规划书附录 E)。
*
* 承载配置中心除「口径字典与版本治理」(CaliberVersionPanel)外的四条配置轴:
* ① 三层参数重算(断言②):试改 C27/C28 五个参数 → runDekDay 重算 →
* 理论/计划档 OEE 移动、**实际档实测不动**;版本标签随修订递增(沙箱)。
* ② 算法模板:三区域不同构(SRF 缓冲解耦 / FT 多因子连乘 / ASLT 事件驱动),
* 只展示口径与算式骨架,**不嵌任何 POC 结果数字**(数字在「工序·工位对比」页现算)。
* ③ 间隙阈值(断言⑤):逐台公式默认值 max(5,3×ICT/60) vs 台账校准值,台账值优先。
* ④ 优先级权重 A/B:两套并列可切换(默认 B),compareSchemes 看名次是否变化。
*
* 四条诚实性纪律:
* 1. **页面本地沙箱**:参数试算不改全局 OEE_PARAMS、不改缓存当日读数、不改顶栏筛选口径版本
* (normalizeFilter 锁定 caliberVersion 单一来源)。数据血缘口径版本仅在 D 类补录时递增。
* 2. **实际档不随参数变**:actualTier 由实测 RT/PPT、N×ICT/RT、良品/N 算出,与 C27/C28 无关;
* 参数只动 theoretical/planned。UI 必须如实显示实际档 Δ=0,不得假装三档一起动。
* 3. **P0 待 IE 签字**:本次不安排口径工作坊,C27/C28 标灰「待 IE 签字」,不标绿。
* 4. **数字只从 L3 取**:runDekDay / dayByDate / defaultGapThresholdMin / compareSchemes /
* priorityStats 一律走 oeeService;设备台账字典(DEVICES/deviceStats)按 ADR-02 可直接读 data 层。
*/
import { useState, type CSSProperties } from 'react';
import {
SlidersHorizontal, RotateCcw, Layers, Ruler, Scale, ArrowRightLeft,
CheckCircle2, FlaskConical,
} from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
OEE_PARAMS, PARAMS_SIGNOFF_NOTE, runDekDay, dayByDate, bumpVersion, CALIBER_VERSION,
defaultGapThresholdMin, WEIGHT_SCHEMES, DEFAULT_WEIGHT_SCHEME, compareSchemes, priorityStats,
PRIORITY_CANDIDATES, type ThreeTierParams, type WeightSchemeId,
} from '../../lib/oeeService';
import { TEMPLATE_LABEL, type RegionTemplate } from '../../types/oee';
import { DEVICES, deviceStats } from '../../data/oee/devices';
import {
Card, Table, Th, Td, Chip, Note, GapBox, EmptyBox, grid2, grid3, pct,
} from '../workspace/oeeUi';
/* ── 三层参数元数据:键 / 中文名 / 口径项 / 单位 / 驱动哪一档 / 输入步长 ── */
interface ParamMeta {
key: keyof ThreeTierParams;
label: string;
caliber: 'C27' | 'C28';
unit: string;
drives: string;
step: number;
}
const PARAM_META: ParamMeta[] = [
{ key: 'designYield', label: '设计良率 Q_design', caliber: 'C27', unit: '比率 0–1', drives: '理论档 Q', step: 0.001 },
{ key: 'planPerformanceRate', label: '计划性能率 P_plan', caliber: 'C27', unit: '比率 0–1', drives: '计划档 P', step: 0.001 },
{ key: 'targetYield', label: '目标良率 Q_plan', caliber: 'C27', unit: '比率 0–1', drives: '计划档 Q', step: 0.001 },
{ key: 'dailyUnavoidableStopSec', label: '日不可避免停机', caliber: 'C27', unit: '秒/日', drives: '理论档 A', step: 10 },
{ key: 'monthlyPlannedStopRate', label: 'IE 月度计划停机率', caliber: 'C28', unit: '比率 0–1', drives: '计划档 A', step: 0.001 },
];
/* ── 三区域算法模板:只录口径骨架,不嵌 POC 结果数字(templates.ts 文件头) ── */
interface TemplateDesc {
id: RegionTemplate;
a: string;
p: string;
q: string;
caliber: string;
}
const TEMPLATE_DESC: TemplateDesc[] = [
{
id: 'SRF_BUFFER',
a: '缓冲解耦:上游最长停机 ≤ B×下游ICT 时不传导到全线',
p: '性能率按瓶颈工位节拍推算',
q: '良率按串联工位连乘',
caliber: '零缓冲是理论下界,非本线口径;B(缓冲容量)由数据层注入',
},
{
id: 'FT_MULTIPLY',
a: 'A=(1−Down率)(1−SetupLoss)(1−Corr)−计划损失',
p: 'P=1−(OE+Index+Jam)',
q: 'Q=1−(Rescreen×良率损失)',
caliber: '多因子连乘,A 不是 RT/PPT;SetupLoss 五操作数含义待 IE 确认',
},
{
id: 'ASLT_EVENT',
a: 'A=运行时长/活跃窗口(>60min 间隔切窗)',
p: 'P=12站使能总时长/(12×活跃窗口)',
q: 'Q=(FT合格+RC复测合格)/FT投入',
caliber: '事件驱动;站别汇总与活跃窗口两套口径各自标,禁止交叉配对',
},
];
const TIER_ROWS = [
{ key: 'theoretical', label: '理论 OEE', note: 'A 由日不可避免停机决定,P=100%,Q=设计良率' },
{ key: 'planned', label: '计划 OEE', note: 'C27/C28 附录 E 默认值,待 IE 签字' },
{ key: 'actual', label: '实际 OEE', note: '实测 A=RT/PPT,P=N×ICT/RT,Q=良品/N' },
] as const;
export default function ConfigAxesPanel({ bizDate }: { bizDate: string }) {
const { tokens } = useTheme();
/* ① 三层参数重算:页面本地沙箱 */
const [draft, setDraft] = useState<ThreeTierParams>({ ...OEE_PARAMS });
const [applied, setApplied] = useState<{ params: ThreeTierParams; revision: number } | null>(null);
const [revision, setRevision] = useState(0);
const [paramMsg, setParamMsg] = useState<string | null>(null);
const baseline = dayByDate(bizDate);
const recomputed = applied && baseline
? runDekDay(baseline.seed, { params: applied.params, revision: applied.revision })
: null;
const versionTag = applied ? bumpVersion(CALIBER_VERSION, applied.revision) : CALIBER_VERSION;
const paramsEqual = (a: ThreeTierParams, b: ThreeTierParams) =>
PARAM_META.every((m) => a[m.key] === b[m.key]);
const applyParams = () => {
const ref = applied?.params ?? OEE_PARAMS;
if (paramsEqual(draft, ref)) {
setParamMsg('参数取值未变,不产生新试算版本(与口径字典同一纪律)。');
return;
}
const rev = revision + 1;
setRevision(rev);
setApplied({ params: { ...draft }, revision: rev });
setParamMsg(`已按修订 r${rev} 重算:理论/计划档随参数移动,实际档为实测值不变。`);
};
const resetParams = () => {
setDraft({ ...OEE_PARAMS });
setApplied(null);
setRevision(0);
setParamMsg(null);
};
/* ④ 优先级权重 A/B */
const [scheme, setScheme] = useState<WeightSchemeId>(DEFAULT_WEIGHT_SCHEME);
const cmp = compareSchemes(PRIORITY_CANDIDATES);
const ps = priorityStats();
const ws = WEIGHT_SCHEMES[scheme];
const rankAOf = (id: string) => cmp.rankA.find((r) => r.item.id === id)?.rank ?? 0;
const rankBOf = (id: string) => cmp.rankB.find((r) => r.item.id === id)?.rank ?? 0;
/* ③ 间隙阈值 */
const ds = deviceStats();
const inputStyle: CSSProperties = {
width: '100%', minWidth: 0, boxSizing: 'border-box',
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, borderRadius: 7,
padding: '4px 7px', fontSize: 11.5, color: tokens.text, outline: 'none',
fontVariantNumeric: 'tabular-nums',
};
const toggleBtn = (id: WeightSchemeId): CSSProperties => ({
fontSize: 11, fontWeight: 700, padding: '3px 11px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${scheme === id ? tokens.accent : tokens.border}`,
background: scheme === id ? tokens.accentBg : 'transparent',
color: scheme === id ? tokens.accent : tokens.textSub,
});
const actionBtn = (primary: boolean): CSSProperties => ({
fontSize: 11, fontWeight: 700, padding: '5px 12px', borderRadius: 8, cursor: 'pointer',
display: 'inline-flex', alignItems: 'center', gap: 5,
border: `1px solid ${primary ? tokens.accent : tokens.border}`,
background: primary ? tokens.accentBg : 'transparent',
color: primary ? tokens.accent : tokens.textSub,
});
return (
<>
{/* ① 三层参数重算(断言②) */}
<Card
full
title="三层参数重算 · 断言②(切换触发重算)"
icon={<SlidersHorizontal size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="页面本地沙箱:不改全局 OEE_PARAMS、不改缓存当日读数、不改顶栏口径版本">沙箱试算 · 不写全局</Chip>}
note={
<>
试改 C27/C28 五个参数 → <code>runDekDay(seed, {'{params, revision}'})</code> 重算。
<strong> 实际档由实测算出(RT/PPT、N×ICT/RT、良品/N),与参数无关,Δ 恒为 0</strong>;
参数只移动理论/计划档。试算版本标签 <code>{versionTag}</code> 为沙箱修订号;
数据血缘口径版本(caliberVersion)仅在 D 类补录时递增,治理见上方「口径字典与版本」。
</>
}
>
{baseline ? (
<div style={grid2}>
{/* 左:参数编辑器 */}
<div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<Table head={<>
<Th>参数(口径项)</Th><Th>驱动</Th><Th right>试改值</Th>
</>}>
{PARAM_META.map((m) => (
<tr key={m.key}>
<Td bold>
{m.label}
<div style={{ marginTop: 2 }}>
<Chip color={tokens.textMuted} title={PARAMS_SIGNOFF_NOTE}>{m.caliber} · 待 IE 签字</Chip>
</div>
</Td>
<Td color={tokens.textSub}>{m.drives}<div style={{ fontSize: 10, color: tokens.textMuted }}>{m.unit}</div></Td>
<Td right>
<input
type="number"
step={m.step}
value={draft[m.key]}
style={inputStyle}
onChange={(e) => {
const v = Number(e.target.value);
setDraft((d) => ({ ...d, [m.key]: Number.isFinite(v) ? v : d[m.key] }));
}}
/>
<div style={{ fontSize: 9.5, color: tokens.textMuted, marginTop: 2 }}>默认 {OEE_PARAMS[m.key]}</div>
</Td>
</tr>
))}
</Table>
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
<button style={actionBtn(true)} onClick={applyParams}><FlaskConical size={13} />应用并重算</button>
<button style={actionBtn(false)} onClick={resetParams}><RotateCcw size={13} />恢复默认</button>
<span style={{ flex: 1 }} />
<Chip color={applied ? tokens.accent : tokens.textMuted}>修订 r{revision}</Chip>
</div>
{paramMsg && (
<div style={{ fontSize: 10.5, color: tokens.textSub, lineHeight: 1.55, display: 'flex', gap: 6, alignItems: 'flex-start' }}>
<CheckCircle2 size={13} color={tokens.accent} style={{ flexShrink: 0, marginTop: 1 }} />{paramMsg}
</div>
)}
</div>
{/* 右:三档对照 */}
<div style={{ minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<Table head={<>
<Th>口径档</Th><Th right>基线</Th><Th right>重算</Th><Th right>Δ(pp)</Th>
</>}>
{TIER_ROWS.map((r) => {
const b = baseline.tiers[r.key].oee;
const n = recomputed ? recomputed.tiers[r.key].oee : b;
const d = (n - b) * 100;
const isActual = r.key === 'actual';
return (
<tr key={r.key}>
<Td bold>
{r.label}
<div style={{ fontSize: 9.5, color: tokens.textMuted, fontWeight: 400 }}>{r.note}</div>
</Td>
<Td right mono>{pct(b)}%</Td>
<Td right mono color={recomputed && !isActual ? tokens.accent : tokens.textSub}>{pct(n)}%</Td>
<Td right mono color={isActual ? tokens.textMuted : d === 0 ? tokens.textSub : d > 0 ? tokens.success : tokens.warning}>
{isActual ? '0.00 · 实测' : `${d >= 0 ? '+' : ''}${d.toFixed(2)}`}
</Td>
</tr>
);
})}
</Table>
<GapBox
missing="C27/C28 无人签字"
dependsOn="IE 提供设计良率/计划性能率/目标良率/日不可避免停机/月度计划停机率"
stage="口径工作坊(本次未安排)"
note={PARAMS_SIGNOFF_NOTE + '。附录 E 默认值生效中,标灰不标绿;试算仅演示重算链路,不代表客户确认口径。'}
/>
</div>
</div>
) : (
<EmptyBox>业务日 {bizDate} 无锚点单机种子,无法重算。请在顶栏选择已接入的锚点设备日。</EmptyBox>
)}
</Card>
{/* ② 算法模板 · 三区域不同构 */}
<Card
full
title="算法模板 · 三区域不同构(不可一套通用式套三站)"
icon={<Layers size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="只录口径骨架;操作数与锚点由数据层注入,结果数字在「工序·工位对比」页现算">口径骨架 · 不嵌结果数字</Chip>}
note="三站分母与算式不同构:SRF 缓冲解耦、FT 多因子连乘(A 不是 RT/PPT)、ASLT 事件驱动(活跃窗口)。每个中间量带 formula+operands+source,可在「工序·工位对比」页逐项展开复核(断言①)。"
>
<div style={grid3}>
{TEMPLATE_DESC.map((t) => (
<div key={t.id} style={{
minWidth: 0, padding: '9px 11px', borderRadius: 9,
background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`,
display: 'flex', flexDirection: 'column', gap: 6,
}}>
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.text }}>{TEMPLATE_LABEL[t.id]}</div>
{([['A', t.a], ['P', t.p], ['Q', t.q]] as const).map(([f, txt]) => (
<div key={f} style={{ display: 'flex', gap: 6, alignItems: 'flex-start' }}>
<Chip color={f === 'A' ? '#f87171' : f === 'P' ? '#38bdf8' : '#a78bfa'}>{f}</Chip>
<span style={{ fontSize: 10.5, color: tokens.textSub, lineHeight: 1.5, minWidth: 0 }}>{txt}</span>
</div>
))}
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.5, marginTop: 2, borderTop: `1px dashed ${tokens.border}`, paddingTop: 6 }}>
{t.caliber}
</div>
</div>
))}
</div>
</Card>
{/* ③ 间隙阈值 + ④ 优先级权重:两卡并列,内容量相近,stretch 底边对齐 */}
<div style={grid2}>
<Card
title="间隙阈值 · 台账值优先(断言⑤)"
icon={<Ruler size={14} color={tokens.accent} />}
right={<Chip color={tokens.accent} title="gapSource=POC 的设备由客户单列阈值,优先于公式默认值">POC 单列 {ds.gapFromPoc} 台</Chip>}
note="公式默认 max(5min, 3×ICT/60);台账校准值优先。kohyoung AOI001=15min(公式 18)、Jetting JET001=3min(公式 5)两处≠默认值,逐台对照如下。ICT=0 的设备公式默认落 5min。阈值为主数据,编辑在「主数据」页。"
>
<Table maxHeight={300} head={<>
<Th>设备</Th><Th>区域</Th><Th right>ICT(s)</Th><Th right>公式默认</Th><Th right>台账值</Th><Th>来源</Th>
</>}>
{DEVICES.map((d) => {
const formula = defaultGapThresholdMin(d.ictSec);
const overridden = d.gapSource === 'POC' && Math.abs(formula - d.gapThresholdMin) > 1e-9;
return (
<tr key={d.id} style={{ opacity: d.countsForOee ? 1 : 0.6 }}>
<Td bold>
<span style={{ fontFamily: 'ui-monospace, monospace' }}>{d.id}</span>
<div style={{ fontSize: 9.5, color: tokens.textMuted, fontWeight: 400 }}>{d.name}</div>
</Td>
<Td color={tokens.textSub}>{d.region}</Td>
<Td right mono color={d.ictSec > 0 ? tokens.textSub : tokens.textMuted}>{d.ictSec > 0 ? d.ictSec : '—'}</Td>
<Td right mono color={tokens.textMuted}>{formula.toFixed(1)}</Td>
<Td right mono bold color={overridden ? tokens.accent : tokens.textSub}>{d.gapThresholdMin}</Td>
<Td>
<Chip color={d.gapSource === 'POC' ? tokens.accent : tokens.textMuted} title={d.gapSource === 'POC' ? 'POC 单列阈值,优先于公式' : '规划书未单列,取公式默认值'}>
{d.gapSource === 'POC' ? 'POC' : '默认'}
</Chip>
{overridden && <div style={{ marginTop: 2 }}><Chip color={tokens.warning}>≠公式</Chip></div>}
</Td>
</tr>
);
})}
</Table>
</Card>
<Card
title="优先级权重 · A/B 双方案(默认 B)"
icon={<Scale size={14} color={tokens.accent} />}
right={
<span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
{(['A', 'B'] as WeightSchemeId[]).map((id) => (
<button key={id} style={toggleBtn(id)} onClick={() => setScheme(id)} title={WEIGHT_SCHEMES[id].source}>{id}</button>
))}
</span>
}
note={`当前 ${ws.label}(${ws.source})。A/B 五维互不重叠(${ps.schemesDisjoint ? '已校验' : '异常'}),权重之和 A=${ps.weightSumA.toFixed(2)} / B=${ps.weightSumB.toFixed(2)}。完整逐项 weight×factor 贡献在「优先处理清单」页展开(断言⑧)。`}
>
<Note>下表 A/B 名次对比为演示沙箱(PRIORITY_CANDIDATES demo 候选 C1–C6)。</Note>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
<Table head={<>
<Th>当前方案维度</Th><Th right>权重</Th>
</>}>
{ws.dims.map((dim) => (
<tr key={dim.key}>
<Td bold>{dim.label}</Td>
<Td right mono color={tokens.accent}>{dim.weight.toFixed(2)}</Td>
</tr>
))}
</Table>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<ArrowRightLeft size={13} color={tokens.textMuted} />
<span style={{ fontSize: 10.5, color: tokens.textSub }}>换权重排序:</span>
<Chip color={cmp.orderChanged ? tokens.warning : tokens.textSub}>{cmp.orderChanged ? '名次变化' : '名次未变'}</Chip>
</div>
<Table head={<>
<Th>候选项</Th><Th right>A 名次</Th><Th right>B 名次</Th><Th right>变化</Th>
</>}>
{PRIORITY_CANDIDATES.map((c) => {
const ra = rankAOf(c.id);
const rb = rankBOf(c.id);
const moved = ra !== rb;
return (
<tr key={c.id}>
<Td>
<span style={{ fontFamily: 'ui-monospace, monospace', color: tokens.textSub }}>{c.id}</span>
<div style={{ fontSize: 9.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', maxWidth: 180 }}>{c.title}</div>
</Td>
<Td right mono color={scheme === 'A' ? tokens.accent : tokens.textSub}>{ra}</Td>
<Td right mono color={scheme === 'B' ? tokens.accent : tokens.textSub}>{rb}</Td>
<Td right mono color={moved ? tokens.warning : tokens.textMuted}>{moved ? `${ra}→${rb}` : '—'}</Td>
</tr>
);
})}
</Table>
</div>
</Card>
</div>
</>
);
}
@@ -0,0 +1,100 @@
/**
* 配置中心(caliber 页签 · W4-A,建议书 §5.2.2 / 规划书附录 E / PAGE_MAP no.14)。
*
* 验收(断言②⑩):切换触发重算 + 版本递增 + 旧版可回放。
* 能力:28 项口径默认值、算法模板、间隙阈值、优先级权重(A/B 切换)、版本与签批。
*
* 页面组合两块自包含面板(各自页面本地沙箱,互不耦合):
* A. CaliberVersionPanel —— 28 项口径字典 + 试改解析新版本 + 版本历史/回放 +
* 跨版本对比闸(默认拒绝)+ 签字治理沙箱(模拟,真实字典恒未签字)。
* B. ConfigAxesPanel —— 三层参数重算(断言②)+ 算法模板 + 间隙阈值(断言⑤)+ 优先级权重 A/B。
*
* 纪律:本次不安排口径工作坊 ⇒ 28 项 signedOff 全 false,P0 标灰「待 IE 签字」,不标绿。
* 顶栏筛选口径版本由 normalizeFilter 锁定单一来源;本页所有版本/重算演示均为页面本地,
* 不改全局 OEE_PARAMS、不改缓存当日读数、不改顶栏 caliberVersion。
*/
import { Settings2, ShieldCheck, SlidersHorizontal } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import { CALIBER_CONFIG, CALIBER_VERSION, caliberStats, SENSITIVITY_ISSUES, PARAMS_SIGNOFF_NOTE, type CaliberItem } from '../../lib/oeeService';
import { ScopeBar, Tiles, Note, Chip, Card, Table, Th, Td, pageStyle } from '../workspace/oeeUi';
import type { OeeViewProps } from '../workspace/OeeOverview';
import CaliberVersionPanel from './CaliberVersionPanel';
import ConfigAxesPanel from './ConfigAxesPanel';
export default function OeeCaliberCenter({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const cs = caliberStats();
const realItems = Object.values(CALIBER_CONFIG.items) as CaliberItem[];
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="配置中心"
icon={<Settings2 size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="口径字典/参数/阈值/权重均为全局配置;版本与重算演示为页面本地沙箱">口径治理 · 断言②⑩</Chip>}
/>
<Note>
配置中心是 OEE 的<strong>口径单一来源</strong>:28 项口径字典(附录 E 默认值)+ 三层参数(C27/C28)+
三区域算法模板 + 逐台间隙阈值 + 优先级权重 A/B。本次不安排口径工作坊,{cs.total} 项 signedOff 全 false,
P0 标灰「待 IE 签字」({PARAMS_SIGNOFF_NOTE})。版本治理兑现断言⑩:试改取值才递增版本、旧版可回放、
跨版本对比默认拒绝;参数重算兑现断言②:切换触发重算,实际档实测不动。
</Note>
<Tiles items={[
{ label: '口径项', value: String(cs.total), sub: `P0 ${cs.p0} / P1 ${cs.p1} / P2 ${cs.p2}`, color: tokens.text, title: '附录 E 默认值生效,28 项口径字典' },
{ label: 'P0 待签字', value: String(cs.p0), sub: '标灰不标绿', color: tokens.textMuted, title: '本次不安排口径工作坊,P0 无人签字' },
{ label: '已签字', value: String(cs.signed), sub: `共 ${cs.total} 项`, color: tokens.textMuted, title: 'signedOff 全 false;签字治理沙箱仅演示,不写真实字典' },
{ label: '敏感性键', value: String(cs.sensitivityKeys), sub: `${Object.keys(SENSITIVITY_ISSUES).length} 个议题`, color: tokens.textSub, title: 'C03/C04/C06/C09/C10 五个敏感性键,归并四个口径议题' },
{ label: '算法模板', value: '3', sub: 'SRF/FT/ASLT 不同构', color: tokens.textSub, title: '三区域各自算式,不可一套通用式套三站' },
{ label: '口径版本', value: CALIBER_VERSION, sub: '顶栏锁定单一来源', color: tokens.accent, title: 'normalizeFilter 强制 caliberVersion 单一来源;本页版本演示为页面本地沙箱' },
]} />
{/* 口径登记(demo 沙箱):版本/生效日/逐项签字状态,全部取自内置口径字典 */}
<Card
title="口径登记(demo 沙箱 · 只读)"
icon={<ShieldCheck size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted} title="demo 沙箱:数据来自内置合成口径字典,不连接后端">demo · 不落库</Chip>}
note="登记口径版本、生效日与逐项签字状态,全部取自内置 CALIBER_CONFIG。本次不安排口径工作坊,signedOff 全 false,一律标「待 IE 签字」,不代签、不标绿。"
>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginBottom: 8 }}>
<span style={{ fontSize: 11, color: tokens.textSub, alignSelf: 'center' }}>在用版本:</span>
<Chip color={tokens.accent}>{CALIBER_CONFIG.version}</Chip>
<span style={{ fontSize: 11, color: tokens.textSub, alignSelf: 'center' }}>生效日:</span>
<Chip color={tokens.textMuted}>{CALIBER_CONFIG.effectiveFrom}</Chip>
</div>
<Table maxHeight={260} head={<>
<Th>编号</Th><Th>口径项</Th><Th>优先级</Th><Th>归口</Th><Th>状态</Th>
</>}>
{realItems.map((c) => (
<tr key={c.id}>
<Td bold mono>{c.id}</Td>
<Td color={tokens.textSub}><span title={c.name}>{c.name}</span></Td>
<Td><Chip color={c.priority === 'P0' ? tokens.textMuted : tokens.textSub}>{c.priority}</Chip></Td>
<Td color={tokens.textMuted}>{c.owner}</Td>
<Td><Chip color={c.signedOff ? tokens.success : tokens.textMuted}>{c.signedOff ? '已签字' : '待 IE 签字'}</Chip></Td>
</tr>
))}
</Table>
</Card>
{/* A. 口径字典与版本治理(断言⑩) */}
<CaliberVersionPanel />
{/* B. 四轴配置:三层参数重算(断言②)+ 算法模板 + 间隙阈值(断言⑤)+ 优先级权重 A/B */}
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 2 }}>
<SlidersHorizontal size={14} color={tokens.accent} />
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text }}>参数 · 模板 · 阈值 · 权重</span>
<Chip color={tokens.textMuted}>四轴配置</Chip>
<span style={{ flex: 1 }} />
<ShieldCheck size={13} color={tokens.textMuted} />
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>业务日 {scope.bizDate} · 锚点单机重算</span>
</div>
<ConfigAxesPanel bizDate={scope.bizDate} />
</div>
);
}
@@ -0,0 +1,74 @@
import { useState } from 'react';
import { Info, X } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
/**
* 舞台使用提示气泡:首次进入某个舞台时,在画布左上角浮出演示动线,
* 点「知道了」或右上角 × 关闭,并把「已看过」记进 localStorage(按 stageKey 区分)。
*
* 确定性优先:不依赖 CSS 动画,靠 JS 状态直接显示 / 卸载,无头截图里也一定可见;
* 关闭状态读自 localStorage,因此同一浏览器第二次进入不再打扰。
*/
interface Props {
/** 记忆键:不同舞台各记一次(例如 'ontology' / 'feature') */
stageKey: string;
steps: string[];
}
const STORAGE = (k: string) => `tfamd-oee-hint-${k}`;
export default function StageHint({ stageKey, steps }: Props) {
const { tokens } = useTheme();
const [hidden, setHidden] = useState(() => {
try { return localStorage.getItem(STORAGE(stageKey)) === '1'; } catch { return false; }
});
if (hidden) return null;
const dismiss = () => {
try { localStorage.setItem(STORAGE(stageKey), '1'); } catch { /* 隐私模式下写不了就算了 */ }
setHidden(true);
};
return (
<div style={{
position: 'absolute', left: 12, top: 12, zIndex: 6, maxWidth: 296,
borderRadius: 12, padding: '10px 12px 11px',
background: tokens.cardBg, border: `1px solid ${tokens.accent}66`,
boxShadow: `0 8px 26px rgba(0,0,0,0.18), 0 0 0 1px ${tokens.accentBg}`,
backdropFilter: 'blur(6px)',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Info size={13} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{ fontSize: 12, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em' }}>使用提示 · 演示动线</span>
<span style={{ flex: 1 }} />
<button onClick={dismiss} title="关闭提示" className="ghost-btn"
style={{ display: 'flex', cursor: 'pointer', color: tokens.textMuted, background: 'none', border: 'none', padding: 0 }}>
<X size={13} />
</button>
</div>
<ol style={{ margin: '7px 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 4 }}>
{steps.map((s, i) => (
<li key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 7, fontSize: 11.5, color: tokens.textSub, lineHeight: 1.4 }}>
<span style={{
flexShrink: 0, width: 15, height: 15, borderRadius: 99, marginTop: 0.5,
display: 'grid', placeItems: 'center', fontSize: 9.5, fontWeight: 800,
color: tokens.onAccent, background: tokens.accent,
}}>{i + 1}</span>
<span>{s}</span>
</li>
))}
</ol>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 9 }}>
<button onClick={dismiss}
style={{
cursor: 'pointer', padding: '3px 12px', borderRadius: 999, fontSize: 11.5, fontWeight: 700,
color: tokens.onAccent, background: tokens.accent, border: `1px solid ${tokens.accent}`,
}}>
知道了
</button>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>关闭后不再自动弹出</span>
</div>
</div>
);
}
@@ -0,0 +1,149 @@
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';
/**
* 客户资料页签:Excel「客户资料」的 9 个字段全量展示(订单笔数 / 订单金额沿用表内汇总口径)。
* 左栏选中销售订单时,只列出该订单的客户——关联关系由销售订单行反推,不另外造数据。
*/
/** 客户金额是Excel原值(两位小数),此处与供应商资料页签同口径 */
export const money2 = (n: number) => n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
/** 按订单金额从大到小:贡献多的客户先看 */
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' }}>¥{money2(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' }}>¥{money2(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,111 @@
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';
/**
* 销售订单页签内容:Excel「销售订单」全量卡片列表。
* 列表口径交给纯函数,DemandPanel 用同一函数算页签徽标数,标题数字与条数不会各说各话。
*/
export const money = (n: number) => n.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** 订单号 / 客户简称 / 客户编码 / 产品编码 四向模糊匹配 */
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,953 @@
import { useEffect, useMemo, useState } from 'react';
import {
BookOpen, Box, ChevronDown, ChevronRight, FlaskConical, GitBranch, Search, Wrench, X,
} from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { ONTOLOGY_AS_OF } from '../../data/ontologyQap';
import { ROLE_COLOR, roleDocs, type RoleKey } from '../../data/knowledge';
import type { KbRef } from '../../data/kbLinks';
import {
getFeatureTree, methodsForRef, type FeatureMethod, type FeatureModel,
type FeatureProcess,
} from '../../data/featureTree';
import type { MethodSummaryRow } from '../../data/methodSummaries';
import { methodImageSrc } from '../../data/methodImages';
/**
* 特征建模舞台:机型 → 工艺 → 生产方法 三级树。
*
* 第三级是可执行的生产方法(数控冲孔 / 手工倒角 / 激光焊 / 压铆…)。
* 选中生产方法后,右侧按「每条知识来源一行」列出问题 / 原因 / 对策 / 角色。
* 真实知识只覆盖 SRV-2U-620;其余机型与空方法用方法模板示例补齐,并标「示例」。
*
* 与知识库的双向动线:
* 知识库点特征码 → 经 featFocus 跳到这里,自动展开并选中对应生产方法
* 这里点「原文」→ 经 onOpenKnowledge 跳回知识库对应切片
*/
interface Props {
onExit: () => void;
/** 从知识库跳回时:指定要聚焦的数据对象/实例 */
focus?: { objKey: string; instanceId?: string } | null;
/** 点击知识来源时跳回知识库 */
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
}
type Path = { modelId: string; processId?: string; methodId?: string };
const ROLE_LABEL: Record<RoleKey, string> = {
PE: '工艺', IE: '工业', QE: '质量', ME: '制造',
};
const ROLE_FULL: Record<RoleKey, string> = {
PE: '工艺工程师', IE: '工业工程师', QE: '质量工程师', ME: '制造工程师',
};
const KB_MODEL = 'SRV-2U-620';
const cardBase = (tk: ThemeTokens, on: boolean): React.CSSProperties => ({
width: '100%', textAlign: 'left', cursor: 'pointer',
padding: '6px 8px', borderRadius: 8, marginBottom: 4,
background: on ? tk.accentBg : 'transparent',
border: `1px solid ${on ? tk.accent : 'transparent'}`,
transition: 'background .15s ease, border-color .15s ease',
});
export default function FeatureTreeView({ onExit, focus, onOpenKnowledge }: Props) {
const { tokens } = useTheme();
const tree = useMemo(getFeatureTree, []);
const initialSelection = useMemo<Path>(() => {
const model = tree.models.find(m => m.id === KB_MODEL) ?? tree.models[0];
if (!model) return { modelId: '' };
const proc = model.processes.find(p => p.id === 'NCT') ?? model.processes[0];
const method = proc?.methods.find(m => m.label === '手工倒角') ?? proc?.methods[0];
return method
? { modelId: model.id, processId: proc.id, methodId: method.id }
: proc ? { modelId: model.id, processId: proc.id } : { modelId: model.id };
}, [tree]);
const validSelection = (path: Path | null): boolean => {
if (!path) return false;
const model = tree.models.find(m => m.id === path.modelId);
if (!model) return false;
if (!path.processId) return true;
const proc = model.processes.find(p => p.id === path.processId);
if (!proc) return false;
if (!path.methodId) return true;
return proc.methods.some(m => m.id === path.methodId);
};
/* 从知识库跳回时优先用上次的选中,否则用默认方法 */
const [selected, setSelected] = useState<Path>(() => {
const last = readLastSelection();
return validSelection(last) ? last! : initialSelection;
});
const [expanded, setExpanded] = useState<Set<string>>(() => {
const first = tree.models.find(m => m.id === KB_MODEL) ?? tree.models[0];
const set = new Set<string>();
if (first) {
set.add(first.id);
for (const p of first.processes) set.add(`${first.id}/${p.id}`);
}
return set;
});
const [query, setQuery] = useState('');
/* 外部跳入:知识库点特征码 → 定位到对应生产方法 */
useEffect(() => {
if (!focus) return;
const methods = methodsForRef(focus.objKey, focus.instanceId);
if (methods.length === 0) return;
const target = methods.find(m => m.modelId === KB_MODEL) ?? methods[0];
setSelected({ modelId: target.modelId, processId: target.processId, methodId: target.id });
setExpanded(prev => {
const next = new Set(prev);
next.add(target.modelId);
next.add(`${target.modelId}/${target.processId}`);
return next;
});
}, [focus]);
/* 记住舞台内最后一次选中,退出再进入时保持不变 */
useEffect(() => {
if (selected.modelId) writeLastSelection(selected);
}, [selected]);
const q = query.trim().toLowerCase();
const match = (text: string) => text.toLowerCase().includes(q);
const methodVisible = (m: FeatureMethod) =>
!q || match(m.label) || m.summary.some(r =>
match(r.problem) || match(r.cause) || match(r.action) || match(r.role));
const selectedNode = useMemo(() => {
const model = tree.models.find(m => m.id === selected.modelId);
if (!model) return null;
if (!selected.processId) return { kind: 'model' as const, node: model };
const proc = model.processes.find(p => p.id === selected.processId);
if (!proc) return { kind: 'model' as const, node: model };
if (!selected.methodId) return { kind: 'process' as const, node: proc };
const method = proc.methods.find(m => m.id === selected.methodId);
return method
? { kind: 'method' as const, node: method }
: { kind: 'process' as const, node: proc };
}, [selected, tree]);
const totalLeaves = useMemo(
() => tree.models.reduce((a, m) => a + m.processes.reduce((b, p) => b + p.methods.length, 0), 0),
[tree],
);
const totalKb = useMemo(
() => tree.models.reduce((a, m) => a + m.kbRefs.length, 0),
[tree],
);
const toggleExpand = (id: string) => {
setExpanded(prev => {
const next = new Set(prev);
if (next.has(id)) next.delete(id); else next.add(id);
return next;
});
};
const isSelected = (path: Path) =>
selected.modelId === path.modelId &&
selected.processId === path.processId &&
selected.methodId === path.methodId;
const box: React.CSSProperties = {
minWidth: 0, display: 'flex', flexDirection: 'column',
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
};
return (
<div style={{ flex: 1, minHeight: 0, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{/* ── 标题栏 ── */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', flexWrap: 'wrap', padding: '2px 2px 0' }}>
<FlaskConical size={19} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{ fontSize: 17, fontWeight: 800, color: tokens.text, letterSpacing: '0.03em' }}>工艺建模</span>
<span style={{ fontSize: 13, color: tokens.textMuted, flexShrink: 0 }}>
快照日 {ONTOLOGY_AS_OF} · 机型 → 工艺 → 生产方法
</span>
<span style={{ flex: '1 1 24px' }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{[
{ l: '机型', v: tree.models.length },
{ l: '工艺', v: tree.models.reduce((a, m) => a + m.processes.length, 0) },
{ l: '生产方法', v: totalLeaves },
{ l: '知识挂载', v: totalKb, hot: true },
].map(s => (
<span key={s.l} style={{
fontSize: 12.5, fontWeight: 700, padding: '2px 9px', borderRadius: 999, whiteSpace: 'nowrap',
color: s.hot ? tokens.warning : tokens.textSub,
background: s.hot ? tokens.warningBg : tokens.accentBg,
border: `1px solid ${s.hot ? `${tokens.warning}55` : tokens.border}`,
fontVariantNumeric: 'tabular-nums',
}}>{s.l} {s.v}</span>
))}
</div>
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '1 1 190px', minWidth: 150, maxWidth: 260,
padding: '3px 9px', borderRadius: 999, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderAccent}`,
}}>
<Search size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<input
value={query} onChange={e => setQuery(e.target.value)}
placeholder="搜索机型 / 工艺 / 方法 / 问题"
style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', color: tokens.text, fontSize: 13.5 }}
/>
{query && (
<button onClick={() => setQuery('')} title="清空搜索" style={{ background: 'none', border: 'none', cursor: 'pointer', color: tokens.textMuted, display: 'flex' }}>
<X size={12} />
</button>
)}
</div>
<button
onClick={onExit} title="退出工艺建模 (ESC)"
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
padding: '4px 11px', borderRadius: 8, fontSize: 13, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<X size={13} /> 退出 ESC
</button>
</div>
{/* ── 主区:左树 + 右详情 ── */}
<div style={{ flex: 1, minHeight: 0, display: 'flex', gap: 10 }}>
{/* 左侧树 */}
<div style={{ ...box, flex: '0 0 330px' }}>
<div style={{
display: 'flex', alignItems: 'center', gap: 7, padding: '8px 11px',
borderBottom: `1px solid ${tokens.border}`, flex: '0 0 auto',
}}>
<GitBranch size={13} style={{ color: tokens.accent }} />
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.text }}>特征树</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 12, color: tokens.textMuted }}>叶子=生产方法</span>
</div>
<div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: '8px 9px' }}>
{tree.models.map(model => {
const modelOpen = q ? true : expanded.has(model.id);
const modelVisible = !q || match(model.label) || model.processes.some(p =>
match(p.label) || p.methods.some(methodVisible),
);
if (!modelVisible) return null;
const modelSel = isSelected({ modelId: model.id });
return (
<div key={model.id}>
<button
onClick={() => setSelected({ modelId: model.id })}
style={{ ...cardBase(tokens, modelSel), display: 'flex', alignItems: 'center', gap: 6 }}
>
<span onClick={e => { e.stopPropagation(); toggleExpand(model.id); }} style={{ display: 'flex', color: tokens.textMuted }}>
{modelOpen ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
</span>
<Box size={14} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{ fontSize: 14, fontWeight: 700, color: tokens.text, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{model.label}
</span>
<KbBadge n={model.kbRefs.length} tokens={tokens} />
</button>
{modelOpen && model.processes.map(proc => {
const procOpen = q ? true : expanded.has(`${model.id}/${proc.id}`);
const procVisible = !q || match(proc.label) || proc.methods.some(methodVisible);
if (!procVisible) return null;
const procSel = isSelected({ modelId: model.id, processId: proc.id });
return (
<div key={proc.id} style={{ paddingLeft: 16 }}>
<button
onClick={() => setSelected({ modelId: model.id, processId: proc.id })}
style={{ ...cardBase(tokens, procSel), display: 'flex', alignItems: 'center', gap: 5 }}
>
<span onClick={e => { e.stopPropagation(); toggleExpand(`${model.id}/${proc.id}`); }} style={{ display: 'flex', color: tokens.textMuted }}>
{procOpen ? <ChevronDown size={13} /> : <ChevronRight size={13} />}
</span>
<GitBranch size={13} style={{ color: tokens.info, flexShrink: 0 }} />
<span style={{ fontSize: 13.5, fontWeight: 600, color: tokens.textSub, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{proc.label}
</span>
<span style={{ fontSize: 11, color: tokens.textMuted, flexShrink: 0, fontVariantNumeric: 'tabular-nums' }}>
{proc.methods.length}
</span>
<KbBadge n={proc.kbRefs.length} tokens={tokens} />
</button>
{procOpen && proc.methods.map(method => {
if (!methodVisible(method)) return null;
const methodSel = isSelected({ modelId: model.id, processId: proc.id, methodId: method.id });
const hasReal = method.realCount > 0;
const thumb = methodImageSrc(method.label);
return (
<button
key={method.id}
onClick={() => setSelected({ modelId: model.id, processId: proc.id, methodId: method.id })}
title={`${method.summary.length} 行总结 · 真实知识 ${method.realCount} 条 · 示例 ${method.exampleCount} 条`}
style={{ ...cardBase(tokens, methodSel), display: 'flex', alignItems: 'center', gap: 7, paddingLeft: 30 }}
>
{/* 生产方法实拍示意图:4:3 缩略图,统一贴在叶子左侧 */}
{thumb ? (
<img
src={thumb}
alt=""
loading="lazy"
draggable={false}
style={{
width: 40, height: 30, objectFit: 'cover', flexShrink: 0,
borderRadius: 5, border: `1px solid ${methodSel ? tokens.accent : tokens.border}`,
boxShadow: '0 1px 2px rgba(0,0,0,0.14)',
}}
/>
) : (
<Wrench size={12} style={{ color: hasReal ? tokens.success : tokens.textMuted, flexShrink: 0 }} />
)}
<span style={{ fontSize: 13, color: hasReal ? tokens.text : tokens.textSub, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{method.label}
</span>
<span style={{
fontSize: 11, fontWeight: 800, padding: '1px 5px', borderRadius: 999,
flexShrink: 0, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
color: hasReal ? tokens.warning : tokens.textMuted,
background: hasReal ? tokens.warningBg : tokens.panelBgAlt,
border: `1px solid ${hasReal ? `${tokens.warning}44` : tokens.border}`,
}}>
{hasReal ? method.summary.length : '示例'}
</span>
</button>
);
})}
</div>
);
})}
</div>
);
})}
</div>
</div>
{/* 右侧详情 */}
<div style={{ ...box, flex: '1 1 0' }}>
<DetailPanel
node={selectedNode}
onOpenKnowledge={onOpenKnowledge}
onSelect={setSelected}
onSelectMethod={method => setSelected({
modelId: method.modelId, processId: method.processId, methodId: method.id,
})}
/>
</div>
</div>
</div>
);
}
/* ── 选中记忆(仅本舞台,刷新后保留) ─────────────────────────────────── */
const LAST_KEY = 'tfamd-oee.featureTree.lastSelection';
function readLastSelection(): Path | null {
try {
const raw = sessionStorage.getItem(LAST_KEY);
if (!raw) return null;
const p = JSON.parse(raw) as Path;
return p && typeof p.modelId === 'string' ? p : null;
} catch {
return null;
}
}
function writeLastSelection(p: Path) {
try {
sessionStorage.setItem(LAST_KEY, JSON.stringify(p));
} catch {
/* 忽略存储不可用 */
}
}
function KbBadge({ n, tokens }: { n: number; tokens: ThemeTokens }) {
if (n === 0) return null;
return (
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: tokens.warning,
padding: '1px 6px', borderRadius: 999, fontVariantNumeric: 'tabular-nums', flexShrink: 0,
}}>
{n}
</span>
);
}
function DetailPanel({
node,
onOpenKnowledge,
onSelect,
onSelectMethod,
}: {
node: { kind: 'model'; node: FeatureModel } | { kind: 'process'; node: FeatureProcess } | { kind: 'method'; node: FeatureMethod } | null;
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
onSelect: (p: Path) => void;
onSelectMethod: (m: FeatureMethod) => void;
}) {
const { tokens } = useTheme();
const label: React.CSSProperties = { fontSize: 12, fontWeight: 700, color: tokens.textMuted, letterSpacing: '0.06em' };
const kv: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 };
if (!node) {
return (
<div style={{ flex: 1, display: 'grid', placeItems: 'center', color: tokens.textMuted, fontSize: 14 }}>
在左侧特征树选择一个节点
</div>
);
}
const { kind, node: n } = node;
const tag = kind === 'model' ? '机型' : kind === 'process' ? '工艺' : '生产方法';
const tagColor = kind === 'model' ? tokens.accent : kind === 'process' ? tokens.info : tokens.success;
const title = n.label;
const subtitle = kind === 'method'
? `${(n as FeatureMethod).modelId} / ${(n as FeatureMethod).processId}`
: kind === 'process' ? (n as FeatureProcess).modelId : '';
const kbList = kind === 'model' ? (n as FeatureModel).kbRefs
: kind === 'process' ? (n as FeatureProcess).kbRefs
: (n as FeatureMethod).kbRefs;
return (
<div style={{ flex: 1, minHeight: 0, display: 'flex', flexDirection: 'column' }}>
<div style={{
padding: '9px 12px 8px', borderBottom: `1px solid ${tokens.border}`, flex: '0 0 auto',
display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap',
}}>
<span style={{
fontSize: 12, fontWeight: 800, color: tokens.onAccent, padding: '1px 7px', borderRadius: 999,
background: tagColor, flexShrink: 0,
}}>{tag}</span>
<span style={{ fontSize: 16, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em' }}>{title}</span>
{subtitle && (
<span style={{ fontSize: 12, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>
{subtitle}
</span>
)}
<span style={{ flex: 1 }} />
{kind === 'method' && (
<MethodStats method={n as FeatureMethod} tokens={tokens} />
)}
</div>
<div style={{ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '10px 12px 12px' }}>
{kind === 'method'
? <MethodDetail
method={n as FeatureMethod}
tokens={tokens}
label={label}
onOpenKnowledge={onOpenKnowledge}
onSelectMethod={onSelectMethod}
/>
: (
<>
<AttrGrid attrs={n.attrs} tokens={tokens} label={label} />
{kind === 'model' && (
<div style={kv}>
<span style={label}>工艺 {(n as FeatureModel).processes.length} 个</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{(n as FeatureModel).processes.map(p => (
<button
key={p.id}
onClick={() => onSelect({ modelId: (n as FeatureModel).id, processId: p.id })}
title={`${p.methods.length} 个生产方法 · 知识 ${p.kbRefs.length} 条`}
style={chipBtn(tokens)}
>
<GitBranch size={11} style={{ color: tokens.info }} />
{p.label}
<span style={{ color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{p.methods.length}</span>
{p.kbRefs.length > 0 && (
<span style={{ color: tokens.warning, fontWeight: 800 }}>{p.kbRefs.length}</span>
)}
</button>
))}
</div>
</div>
)}
{kind === 'process' && (
<div style={kv}>
<span style={label}>生产方法 {(n as FeatureProcess).methods.length} 个</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{(n as FeatureProcess).methods.map(m => (
<button
key={m.id}
onClick={() => onSelectMethod(m)}
title={`真实知识 ${m.realCount} 条 · 示例 ${m.exampleCount} 条`}
style={chipBtn(tokens)}
>
<Wrench size={11} style={{ color: m.realCount > 0 ? tokens.success : tokens.textMuted }} />
{m.label}
<span style={{ color: m.realCount > 0 ? tokens.warning : tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
{m.summary.length}
</span>
</button>
))}
</div>
</div>
)}
<KbList list={kbList} onOpenKnowledge={onOpenKnowledge} tokens={tokens} label={label} />
</>
)}
</div>
</div>
);
}
function MethodStats({ method, tokens }: { method: FeatureMethod; tokens: ThemeTokens }) {
return (
<div style={{ display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
<span style={{
fontSize: 11.5, fontWeight: 800, padding: '1px 7px', borderRadius: 999,
color: method.realCount > 0 ? tokens.warning : tokens.textMuted,
background: method.realCount > 0 ? tokens.warningBg : tokens.panelBgAlt,
border: `1px solid ${method.realCount > 0 ? `${tokens.warning}44` : tokens.border}`,
fontVariantNumeric: 'tabular-nums',
}}>真实知识 {method.realCount}</span>
<span style={{
fontSize: 11.5, fontWeight: 700, padding: '1px 7px', borderRadius: 999,
color: tokens.textSub, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
fontVariantNumeric: 'tabular-nums',
}}>示例 {method.exampleCount}</span>
<span style={{
fontSize: 11.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums',
}}>共 {method.summary.length} 行</span>
</div>
);
}
/* ── 生产方法详情:问题 / 原因 / 对策 / 角色 总结表 ───────────────────── */
function MethodDetail({
method, tokens, label, onOpenKnowledge, onSelectMethod,
}: {
method: FeatureMethod;
tokens: ThemeTokens;
label: React.CSSProperties;
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
onSelectMethod: (m: FeatureMethod) => void;
}) {
const hasExample = method.exampleCount > 0;
const hasReal = method.realCount > 0;
const siblings = (() => {
const model = getFeatureTree().models.find(m => m.id === method.modelId);
const proc = model?.processes.find(p => p.id === method.processId);
return proc?.methods.filter(m => m.id !== method.id) ?? [];
})();
return (
<>
{hasExample && (
<div style={{
display: 'flex', alignItems: 'flex-start', gap: 6, padding: '6px 9px', borderRadius: 8,
background: tokens.panelBgAlt, border: `1px dashed ${tokens.borderAccent}`, marginBottom: 8,
}}>
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.textSub, background: tokens.kpiCardBg,
border: `1px solid ${tokens.border}`, padding: '1px 5px', borderRadius: 5, flexShrink: 0, marginTop: 1,
}}>示例</span>
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>
{hasReal
? `有 ${method.exampleCount} 行是示例补齐(不是知识库原文),其余来自知识库切片。`
: `该生产方法暂无知识库切片,以下 ${method.exampleCount} 行按方法模板生成,仅用于演示结构,不作为知识事实。`}
</span>
</div>
)}
<div style={{ marginBottom: 10 }}>
<div style={{
border: `1px solid ${tokens.border}`, borderRadius: 9, overflow: 'hidden',
background: tokens.panelBgAlt,
}}>
<table style={{ width: '100%', borderCollapse: 'collapse', tableLayout: 'fixed' }}>
<colgroup>
<col style={{ width: 88 }} />
<col style={{ width: '24%' }} />
<col style={{ width: '24%' }} />
<col style={{ width: '34%' }} />
<col style={{ width: 94 }} />
</colgroup>
<thead>
<tr style={{ background: tokens.tableHeaderBg }}>
{['角色', '问题', '原因', '对策', '来源'].map((h, i) => (
<th key={h} style={{
padding: '6px 8px', textAlign: i === 4 ? 'center' : 'left',
fontSize: 11.5, fontWeight: 800, color: tokens.textMuted, letterSpacing: '0.06em',
borderBottom: `1px solid ${tokens.border}`,
}}>{h}</th>
))}
</tr>
</thead>
<tbody>
{method.summary.map((row, i) => (
<SummaryTableRow
key={row.id}
row={row}
tokens={tokens}
zebra={i % 2 === 1}
onOpenKnowledge={onOpenKnowledge}
/>
))}
</tbody>
</table>
</div>
</div>
<RoleCoverage method={method} tokens={tokens} label={label} />
<SourceExcerpts method={method} tokens={tokens} label={label} onOpenKnowledge={onOpenKnowledge} />
{method.refs.length > 0 && (
<div style={kvBlock}>
<span style={label}>关联数据 {method.refs.length} 项</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{method.refs.map((r, i) => (
<span
key={`${r.objKey}-${r.instanceId ?? ''}-${i}`}
title={r.why}
style={{
display: 'inline-flex', alignItems: 'center', gap: 5, padding: '2px 7px', borderRadius: 6,
fontSize: 12, color: tokens.textSub, background: tokens.kpiCardBg,
border: `1px solid ${tokens.border}`, fontFamily: 'ui-monospace, SFMono-Regular, monospace',
}}
>
{r.objKey}
{r.instanceId ? ` · ${r.instanceId}` : ''}
</span>
))}
</div>
</div>
)}
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
<ContextDetails title={`机型上下文 · ${method.modelId}`} attrs={method.modelAttrs} tokens={tokens} />
<ContextDetails title={`工艺上下文 · ${method.processId}`} attrs={method.processAttrs} tokens={tokens} />
</div>
{siblings.length > 0 && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 9 }}>
<span style={label}>同工艺其他方法 {siblings.length} 个</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>
{siblings.map(m => (
<button
key={m.id}
onClick={() => onSelectMethod(m)}
title={`真实知识 ${m.realCount} 条 · 示例 ${m.exampleCount} 条`}
style={chipBtn(tokens)}
>
<Wrench size={11} style={{ color: m.realCount > 0 ? tokens.success : tokens.textMuted }} />
{m.label}
<span style={{ color: m.realCount > 0 ? tokens.warning : tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
{m.realCount > 0 ? m.realCount : '示例'}
</span>
</button>
))}
</div>
</div>
)}
</>
);
}
const kvBlock: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 };
const chunkText = (role: RoleKey, chunkId: string) =>
roleDocs.find(d => d.role === role)?.chunks.find(c => c.id === chunkId)?.text ?? '';
/* 角色覆盖:一眼看出该方法有哪些角色在管、哪些还空着 */
function RoleCoverage({ method, tokens, label }: { method: FeatureMethod; tokens: ThemeTokens; label: React.CSSProperties }) {
const roles: RoleKey[] = ['PE', 'IE', 'QE', 'ME'];
return (
<div style={kvBlock}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span style={label}>角色覆盖</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted }}>
{roles.filter(r => method.summary.some(x => x.role === r)).length} / 4 角色已挂载
</span>
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 6 }}>
{roles.map(role => {
const rows = method.summary.filter(r => r.role === role);
const real = rows.filter(r => r.source.kind === 'kb').length;
const example = rows.length - real;
const empty = rows.length === 0;
return (
<div key={role} style={{
padding: '5px 8px', borderRadius: 8,
background: empty ? 'transparent' : tokens.panelBgAlt,
border: `1px ${empty ? 'dashed' : 'solid'} ${empty ? tokens.border : tokens.borderSub}`,
opacity: empty ? 0.75 : 1,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: ROLE_COLOR[role],
padding: '0 4px', borderRadius: 4, flexShrink: 0,
}}>{role}</span>
<span style={{ fontSize: 11.5, color: tokens.textSub, flex: 1 }}>{ROLE_FULL[role]}</span>
<span style={{
fontSize: 11.5, fontWeight: 800, color: empty ? tokens.textMuted : tokens.text,
fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
}}>{empty ? '未覆盖' : `${rows.length} 行`}</span>
</div>
<div style={{
marginTop: 3, fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums',
display: 'flex', gap: 6, whiteSpace: 'nowrap',
}}>
{empty ? <span>无知识行</span> : <><span>真实 {real}</span><span>示例 {example}</span></>}
</div>
</div>
);
})}
</div>
</div>
);
}
/* 知识原文节选:表格是提炼行,这里保留可核对的原文 */
function SourceExcerpts({
method, tokens, label, onOpenKnowledge,
}: {
method: FeatureMethod;
tokens: ThemeTokens;
label: React.CSSProperties;
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
}) {
const rows = method.summary.filter(r => r.source.kind === 'kb');
if (rows.length === 0) {
const checklist: [RoleKey, string][] = [
['PE', '工艺参数卡 / DFM 检查表'],
['IE', 'SOP 与标准节拍 / 工装方案'],
['QE', '检验标准 / 抽检频次'],
['ME', '设备参数卡 / 点检表'],
];
return (
<div style={{
padding: '9px 11px', borderRadius: 9, marginBottom: 10,
background: tokens.accentBg, border: `1px dashed ${tokens.borderAccent}`,
}}>
<div style={{ fontSize: 12.5, fontWeight: 800, color: tokens.text, marginBottom: 3 }}>
该生产方法还没有知识库切片
</div>
<div style={{ fontSize: 12, lineHeight: 1.65, color: tokens.textSub }}>
上表 {method.exampleCount} 行全部是示例。补齐路径:① 在知识库上传该方法的 SOP / 检验标准;
② 给切片标注「所属特征树」;③ 回到这里即可换成带来源的真实总结。
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 5, marginTop: 7 }}>
{checklist.map(([role, items]) => (
<div key={role} style={{
display: 'flex', alignItems: 'flex-start', gap: 5, padding: '4px 6px', borderRadius: 7,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: ROLE_COLOR[role],
padding: '0 4px', borderRadius: 4, flexShrink: 0, marginTop: 1,
}}>{role}</span>
<span style={{ fontSize: 11.5, lineHeight: 1.45, color: tokens.textSub }}>{items}</span>
</div>
))}
</div>
</div>
);
}
return (
<div style={kvBlock}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span style={label}>知识原文节选 {rows.length} 条</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted }}>点卡片回到知识库切片</span>
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, minmax(0, 1fr))', gap: 6 }}>
{rows.map(row => {
if (row.source.kind !== 'kb') return null;
const text = chunkText(row.role, row.source.chunkId);
return (
<button
key={row.id}
onClick={() => onOpenKnowledge?.(row.role, row.source.kind === 'kb' ? row.source.chunkId : '')}
title={text}
style={{
textAlign: 'left', cursor: onOpenKnowledge ? 'pointer' : 'default',
padding: '6px 8px', borderRadius: 8,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
display: 'flex', flexDirection: 'column', gap: 3, minWidth: 0,
}}
>
<span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: ROLE_COLOR[row.role],
padding: '0 4px', borderRadius: 4, flexShrink: 0,
}}>{row.role}</span>
<span style={{
fontSize: 11, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace',
}}>{row.source.kind === 'kb' ? row.source.chunkId : ''}</span>
<span style={{ flex: 1 }} />
<BookOpen size={10} style={{ color: tokens.accent, flexShrink: 0 }} />
</span>
<span style={{
fontSize: 12, lineHeight: 1.55, color: tokens.textSub,
display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical', overflow: 'hidden',
}}>{text || row.problem}</span>
</button>
);
})}
</div>
</div>
);
}
function SummaryTableRow({
row, tokens, zebra, onOpenKnowledge,
}: {
row: MethodSummaryRow;
tokens: ThemeTokens;
zebra: boolean;
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
}) {
const isKb = row.source.kind === 'kb';
const cell: React.CSSProperties = {
padding: '8px 9px', verticalAlign: 'top', fontSize: 12.5, lineHeight: 1.6,
color: tokens.text, borderBottom: `1px solid ${tokens.borderSub}`,
wordBreak: 'break-word',
};
return (
<tr style={{ background: isKb ? (zebra ? tokens.tableRowAlt : 'transparent') : tokens.kpiCardBg }}>
<td style={{ ...cell, borderBottom: `1px solid ${tokens.borderSub}` }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: ROLE_COLOR[row.role],
padding: '1px 5px', borderRadius: 4, flexShrink: 0,
}}>{row.role}</span>
<span style={{ fontSize: 11, color: tokens.textMuted, whiteSpace: 'nowrap' }}>{ROLE_LABEL[row.role]}</span>
</div>
</td>
<td style={{ ...cell, fontWeight: 600 }}>{row.problem}</td>
<td style={{ ...cell, color: tokens.textSub }}>{row.cause}</td>
<td style={{ ...cell, color: tokens.textSub }}>{row.action}</td>
<td style={{ ...cell, textAlign: 'center' }}>
{isKb ? (
<button
onClick={() => onOpenKnowledge?.(row.role, row.source.kind === 'kb' ? row.source.chunkId : '')}
title={`${row.role} 知识切片 ${row.source.kind === 'kb' ? row.source.chunkId : ''}`}
style={{
display: 'inline-flex', alignItems: 'center', gap: 3, cursor: onOpenKnowledge ? 'pointer' : 'default',
padding: '1px 6px', borderRadius: 5, fontSize: 11, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
whiteSpace: 'nowrap',
}}
>
<BookOpen size={10} />
原文 {row.source.kind === 'kb' ? row.source.chunkId : ''}
</button>
) : (
<span style={{
display: 'inline-flex', alignItems: 'center', padding: '1px 6px', borderRadius: 5,
fontSize: 11, fontWeight: 800, color: tokens.textSub,
background: tokens.panelBgAlt, border: `1px dashed ${tokens.borderAccent}`, whiteSpace: 'nowrap',
}}>示例</span>
)}
</td>
</tr>
);
}
function ContextDetails({ title, attrs, tokens }: { title: string; attrs: { label: string; value: string }[]; tokens: ThemeTokens }) {
if (attrs.length === 0) return null;
return (
<details open style={{
borderRadius: 8, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<summary style={{
cursor: 'pointer', padding: '5px 9px', fontSize: 12, fontWeight: 700,
color: tokens.textSub, letterSpacing: '0.04em', listStyle: 'none',
}}>
{title} · {attrs.length} 项
</summary>
<div style={{
display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(240px, 1fr))', gap: 4,
padding: '0 9px 8px',
}}>
{attrs.map(a => (
<div key={a.label} style={{
display: 'flex', alignItems: 'baseline', gap: 6, padding: '2px 0',
borderTop: `1px solid ${tokens.borderSub}`,
}}>
<span style={{ fontSize: 11, color: tokens.textMuted, flexShrink: 0, minWidth: 54 }}>{a.label}</span>
<span style={{ fontSize: 12, color: tokens.text, lineHeight: 1.5, wordBreak: 'break-word' }}>{a.value}</span>
</div>
))}
</div>
</details>
);
}
function AttrGrid({ attrs, tokens, label }: { attrs: { label: string; value: string }[]; tokens: ThemeTokens; label: React.CSSProperties }) {
if (attrs.length === 0) return null;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 10 }}>
<span style={label}>属性 {attrs.length} 项</span>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 5 }}>
{attrs.map(a => (
<div key={a.label} style={{
padding: '5px 8px', borderRadius: 7, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<div style={{ fontSize: 11, fontWeight: 800, color: tokens.textMuted, marginBottom: 1 }}>{a.label}</div>
<div style={{ fontSize: 12.5, color: tokens.text, lineHeight: 1.45, wordBreak: 'break-word' }}>{a.value}</div>
</div>
))}
</div>
</div>
);
}
function KbList({
list, onOpenKnowledge, tokens, label,
}: {
list: KbRef[];
onOpenKnowledge?: (role: RoleKey, chunkId: string) => void;
tokens: ThemeTokens;
label: React.CSSProperties;
}) {
if (list.length === 0 || !onOpenKnowledge) return null;
return (
<div style={{ ...kvBlock, paddingTop: 8, borderTop: `1px solid ${tokens.border}` }}>
<span style={label}>知识挂载 {list.length} 条</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{list.map((r, i) => (
<button
key={`${r.role}-${r.chunkId}-${i}`}
onClick={() => onOpenKnowledge(r.role, r.chunkId)}
style={{
textAlign: 'left', cursor: 'pointer', padding: '5px 8px', borderRadius: 7,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
display: 'flex', alignItems: 'center', gap: 6,
}}
>
<BookOpen size={11} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{
fontSize: 11, fontWeight: 800, color: tokens.onAccent, background: ROLE_COLOR[r.role],
padding: '1px 5px', borderRadius: 4, flexShrink: 0,
}}>{r.role}</span>
<span style={{
fontSize: 12.5, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis',
whiteSpace: 'nowrap', flex: 1,
}}>{r.label}</span>
<span style={{
fontSize: 11, color: tokens.textMuted, flexShrink: 0,
fontFamily: 'ui-monospace, SFMono-Regular, monospace',
}}>{r.chunkId}</span>
</button>
))}
</div>
</div>
);
}
const chipBtn = (tokens: ThemeTokens): React.CSSProperties => ({
display: 'inline-flex', alignItems: 'center', gap: 4, cursor: 'pointer',
padding: '2px 7px', borderRadius: 6, fontSize: 12, color: tokens.textSub,
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`,
});
@@ -0,0 +1,441 @@
import { Fragment, useEffect, useMemo, useState } from 'react';
import { AlertTriangle, Archive, BookOpen, Database, FileText, Search, ShieldCheck, Sparkles, X } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
retrieve, CHUNKS, KB_DOCS, knowledgeStats, KNOWLEDGE_NOTE, CALIBER_VERSION,
type Chunk, type Corpus,
} from '../../lib/oeeService';
import { SIM_BADGE } from '../../data/oee/disclosure';
import { Card, Chip, Th, Td, Note, EmptyBox } from '../workspace/oeeUi';
/**
* 知识库舞台(OEE 四语料版,建议书 §4.5)——把「故障码字典 / SOP / 口径说明 / 改善案例」
* 四类语料摊开,并现场演示检索增强与失效规则。
*
* ★ 与旧品质角色文件版彻底换血:不再 import data/knowledge · ontologyQap · kbLinks,
* 语料与统计全部出自 L3 oeeService(CHUNKS / knowledgeStats / retrieve),数字一律现算。
*
* 外壳沿用舞台同款(标题栏 / 概览药签 / 搜索 / 退出 ESC),内部三块:
* 左 语料目录(四语料 + 全部,切片/活跃/失效计数)+ 失效规则图例 + 生产迁移路径
* 右 检索增强(内存余弦 TF-IDF,top-k):命中卡 + 余弦分条 +「失效切片停止召回」实证
* 底 语料切片明细表(含失效切片标灰,可审计;点行展开全文)
*
* ★ 失效规则比切片粒度更重要(§4.5.1):
* - active=false 永不召回(旧版 SOP / 待复核案例 / 改钟标记)——检索侧过滤,明细表仍标灰可审计。
* - 口径语料锁定 CALIBER_VERSION,禁止跨版本混合检索(retrieve 的 caliberVersion 过滤)。
* - 全部切片 synthetic=true,逐条挂「模拟」徽标,不冒充客户真实知识库(断言⑪)。
*/
/** 检索 top-k(原型固定 8,生产由 Milvus 召回参数决定)。 */
const TOP_K = 8;
type CorpusFilter = Corpus | null;
const CORPUS_META: Record<Corpus, { label: string; desc: string; color: 'accent' | 'info' | 'success' | 'warning' | 'danger' }> = {
CODE: { label: '故障码字典', desc: '48 事件 + 公开规范码表', color: 'danger' },
SOP: { label: '标准作业 SOP', desc: '公开资料 + 演示转录 · 含旧版失效', color: 'info' },
CALIBER: { label: '口径说明', desc: `28 条 + 公开条款 · 锁 ${CALIBER_VERSION}`, color: 'accent' },
CASE: { label: '改善案例', desc: '优先清单 + 公开案例 · 待复核失效', color: 'success' },
};
const CORPUS_ORDER: Corpus[] = ['CODE', 'SOP', 'CALIBER', 'CASE'];
/** 现场演示检索词:前四个有活跃命中,后三个只命中失效切片(演示停止召回)。 */
const DEMO_QUERIES = ['未归因', '计划待料', '换型', '刮刀压力', '31317', '旧版', '验证不通过'];
interface Props {
onExit: () => void;
/** 外部跳回时定位到某条 OEE 语料切片(id 如 CODE-… / SOP-01 / CALIBER-… / CASE-…)。
匹配不到(例如旧品质特征建模传来的 legacy id)则静默忽略,不报错。 */
focus?: { chunkId: string } | null;
}
export default function KnowledgeView({ onExit, focus }: Props) {
const { tokens } = useTheme();
const [corpus, setCorpus] = useState<CorpusFilter>(null);
const [query, setQuery] = useState('');
const [openChunk, setOpenChunk] = useState<string | null>(null);
const stats = useMemo(knowledgeStats, []);
/* 资料输入:随语料筛选,点选即按该资料的检索词召回。 */
const docs = useMemo(() => (corpus ? KB_DOCS.filter((d) => d.corpus === corpus) : KB_DOCS), [corpus]);
/* 外部跳回:按 chunkId 落到对应语料并展开;匹配不到则不动(兼容 legacy 跳转)。 */
useEffect(() => {
if (!focus?.chunkId) return;
const c = CHUNKS.find((x) => x.id === focus.chunkId);
if (!c) return;
setCorpus(c.corpus);
setOpenChunk(c.id);
setQuery('');
}, [focus]);
const q = query.trim();
const ql = q.toLowerCase();
/* 表格/失效实证按空格分词做「任一词命中」:资料点击带复合词(如「E10 六状态」)也能对上切片。 */
const terms = ql ? ql.split(/\s+/).filter(Boolean) : [];
const looseMatch = useMemo(() => {
if (!terms.length) return () => false;
return (c: Chunk) => {
const hay = `${c.id} ${c.title} ${c.text}`.toLowerCase();
return terms.some((t) => hay.includes(t));
};
}, [ql]);
/* 检索命中:失效规则在 retrieve() 内生效(active=false 不召回 + 口径锁版本)。 */
const hits = useMemo(
() => (q ? retrieve(q, TOP_K, { corpus: corpus ?? undefined, caliberVersion: CALIBER_VERSION }, CHUNKS) : []),
[q, corpus],
);
/* 停止召回实证:命中关键词、却因 active=false 被检索排除的失效切片(明细表仍标灰可审计)。 */
const retiredMatches = useMemo(() => {
if (!ql) return [];
return CHUNKS.filter((c) => !c.active
&& (corpus === null || c.corpus === corpus) && looseMatch(c));
}, [ql, corpus, looseMatch]);
/* 明细表:当前语料范围 + 关键词过滤,**含失效切片**(与检索侧形成对照)。 */
const tableRows = useMemo(() => CHUNKS.filter((c) =>
(corpus === null || c.corpus === corpus) && (!ql || looseMatch(c))),
[ql, corpus, looseMatch]);
const corpusLabel = corpus ? CORPUS_META[corpus].label : '全部语料';
return (
<div style={{ flex: 1, minHeight: 0, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{/* ── 标题栏 ── */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', flexWrap: 'wrap', padding: '2px 2px 0' }}>
<BookOpen size={19} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{ fontSize: 15.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.03em' }}>知识库</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted, flexShrink: 0 }}>四语料 · 公开资料转录(synthetic)</span>
<span style={{ flex: '1 1 24px' }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{[
{ l: '资料', v: stats.docCount }, { l: '切片', v: stats.total },
{ l: '活跃', v: stats.active }, { l: '失效', v: stats.retired },
{ l: '口径', v: CALIBER_VERSION },
].map((s) => (
<span key={s.l} style={{
fontSize: 11, fontWeight: 700, padding: '2px 9px', borderRadius: 999, whiteSpace: 'nowrap',
color: tokens.textSub, background: tokens.accentBg, border: `1px solid ${tokens.border}`,
fontVariantNumeric: 'tabular-nums',
}}>{s.l} {s.v}</span>
))}
</div>
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '1 1 190px', minWidth: 150, maxWidth: 280,
padding: '3px 9px', borderRadius: 999, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderAccent}`,
}}>
<Search size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<input
value={query} onChange={(e) => setQuery(e.target.value)}
placeholder="检索语料,如「未归因」「31317」"
style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', color: tokens.text, fontSize: 12 }}
/>
{query && (
<button onClick={() => setQuery('')} title="清空检索" style={{ background: 'none', border: 'none', cursor: 'pointer', color: tokens.textMuted, display: 'flex' }}>
<X size={12} />
</button>
)}
</div>
<button
onClick={onExit} title="退出知识库 (ESC)"
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
padding: '4px 11px', borderRadius: 8, fontSize: 11.5, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<X size={13} /> 退出 ESC
</button>
</div>
{/* ── 主区:左语料目录 + 右检索增强 ── */}
<div style={{ flex: '1.5 1 0', minHeight: 300, display: 'flex', gap: 10 }}>
{/* 左:语料目录 + 失效规则 + 迁移路径。grid 单列让 Card 撑满宽/高(flex 行里 Card 会按内容缩宽)。 */}
<div style={{ flex: '0 0 280px', minWidth: 0, display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gridTemplateRows: 'minmax(0,1fr)' }}>
<Card title="语料目录" icon={<Database size={14} color={tokens.accent} />} full
right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{CORPUS_ORDER.length} 类 · {KB_DOCS.length} 份资料</span>}>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 6 }}>
<CorpusButton
tokens={tokens} on={corpus === null} color={tokens.accent}
label="全部语料" desc={`合计 ${stats.total} 条切片`}
total={stats.total} active={stats.active} retired={stats.retired}
onClick={() => { setCorpus(null); setOpenChunk(null); }}
/>
{CORPUS_ORDER.map((k) => {
const meta = CORPUS_META[k];
const all = CHUNKS.filter((c) => c.corpus === k);
const act = all.filter((c) => c.active).length;
return (
<CorpusButton
key={k} tokens={tokens} on={corpus === k} color={tokens[meta.color]}
label={`${k} · ${meta.label}`} desc={meta.desc}
total={all.length} active={act} retired={all.length - act}
onClick={() => { setCorpus(k); setOpenChunk(null); }}
/>
);
})}
<div style={{ marginTop: 4, padding: '8px 10px', borderRadius: 9, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}` }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
<ShieldCheck size={13} style={{ color: tokens.warning }} />
<span style={{ fontSize: 11.5, fontWeight: 800, color: tokens.text }}>失效规则(比切片粒度更重要)</span>
</div>
{[
'active=false 永不召回:旧版 SOP / 待复核案例 / 改钟标记。',
`口径语料锁定 ${CALIBER_VERSION},禁止跨版本混合检索。`,
'升版重新入库,旧切片停止召回;明细表仍标灰可审计。',
].map((s) => (
<div key={s} style={{ fontSize: 10.5, color: tokens.textSub, lineHeight: 1.5, display: 'flex', gap: 5 }}>
<span style={{ color: tokens.warning, flexShrink: 0 }}>·</span><span style={{ minWidth: 0 }}>{s}</span>
</div>
))}
</div>
<Note>{KNOWLEDGE_NOTE}</Note>
</div>
</Card>
</div>
{/* 右:检索增强 */}
<div style={{ flex: '1 1 0', minWidth: 0, display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gridTemplateRows: 'minmax(0,1fr)' }}>
<Card title="检索增强 · 内存余弦(TF-IDF)" icon={<Sparkles size={14} color={tokens.accent} />} full
right={
<span style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
<Chip color={tokens.accent}>{corpusLabel}</Chip>
<Chip color={tokens.info} title="口径语料禁止跨版本混合检索">口径锁定 {CALIBER_VERSION}</Chip>
<Chip color={tokens.textMuted}>top-{TOP_K}</Chip>
</span>
}>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', display: 'flex', flexDirection: 'column', gap: 8 }}>
{!q && (
<>
{/* 知识库输入资料:每类 3–4 份公开资料;点卡片按该资料的检索词召回切片,原文可外跳。 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
<FileText size={13} style={{ color: tokens.accent }} />
<span style={{ fontSize: 12, fontWeight: 800, color: tokens.text }}>
知识库输入资料 · {corpus ? CORPUS_META[corpus].label : '全部语料'}
</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>
{docs.length} 份 · 公开来源 · 点卡片试检索
</span>
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(236px, 1fr))', gap: 7 }}>
{docs.map((d) => {
const col = tokens[CORPUS_META[d.corpus].color];
return (
<div
key={d.id} role="button" tabIndex={0}
onClick={() => { setCorpus(d.corpus); setQuery(d.query); setOpenChunk(null); }}
onKeyDown={(e) => { if (e.key === 'Enter') { setCorpus(d.corpus); setQuery(d.query); setOpenChunk(null); } }}
title={`${d.note}|${d.url}`}
style={{
cursor: 'pointer', padding: '7px 9px', borderRadius: 9, minWidth: 0,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
boxShadow: `inset 3px 0 0 ${col}`,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Chip color={col}>{d.corpus}</Chip>
<span style={{ fontSize: 9.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{d.publisher} · {d.date}
</span>
</div>
<div style={{ marginTop: 3, fontSize: 11.5, fontWeight: 700, color: tokens.text, lineHeight: 1.35 }}>{d.title}</div>
<div style={{ marginTop: 2, fontSize: 10, color: tokens.textMuted, lineHeight: 1.4 }}>{d.note}</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 3 }}>
<span style={{ fontSize: 9.5, color: tokens.accent }}>检索「{d.query}」</span>
<span style={{ flex: 1 }} />
<a
href={d.url} target="_blank" rel="noreferrer"
onClick={(e) => e.stopPropagation()}
style={{ fontSize: 9.5, color: tokens.info, textDecoration: 'none', flexShrink: 0 }}
>原文 ↗</a>
</div>
</div>
);
})}
</div>
<div style={{
padding: '8px 10px', borderRadius: 9, background: tokens.panelBgAlt,
border: `1px dashed ${tokens.borderAccent}`, textAlign: 'center',
}}>
<div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.6 }}>
输入关键词检索四语料,或点下方演示词。检索只召回 active=true 的切片;口径语料锁定 {CALIBER_VERSION}。
</div>
<span style={{ display: 'inline-flex', gap: 6, flexWrap: 'wrap', justifyContent: 'center', marginTop: 7 }}>
{DEMO_QUERIES.map((d) => (
<button key={d} onClick={() => setQuery(d)}
style={{
cursor: 'pointer', padding: '3px 10px', borderRadius: 999, fontSize: 11, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>{d}</button>
))}
</span>
</div>
</>
)}
{q && hits.length === 0 && retiredMatches.length === 0 && (
<EmptyBox>「{q}」无活跃切片命中。换个关键词,或点左侧演示词。</EmptyBox>
)}
{q && hits.length === 0 && retiredMatches.length > 0 && (
<EmptyBox>
活跃语料中无「{q}」命中:命中的切片均已失效并停止召回。<br />
下方明细表仍标灰留痕、可审计——这正是失效规则要防的「过期知识致幻」。
</EmptyBox>
)}
{hits.map((h, i) => {
const c = h.chunk;
const col = tokens[CORPUS_META[c.corpus].color];
return (
<div key={c.id} style={{ padding: '8px 10px', borderRadius: 9, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
<span style={{ fontSize: 10, fontWeight: 800, color: tokens.onAccent, background: col, padding: '1px 6px', borderRadius: 6, flexShrink: 0 }}>#{i + 1}</span>
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.text, minWidth: 0 }}>{c.title}</span>
<Chip color={col}>{c.corpus}</Chip>
<Chip color={tokens.textMuted} title={c.source}>{SIM_BADGE}</Chip>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>余弦 {h.score.toFixed(3)}</span>
</div>
<div style={{ height: 4, borderRadius: 2, background: tokens.border, marginTop: 6, overflow: 'hidden' }}>
<div style={{ width: `${Math.min(100, Math.max(0, h.score * 100))}%`, height: '100%', background: col }} />
</div>
<div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.5, marginTop: 6 }}>{c.text}</div>
<div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 4, lineHeight: 1.5 }}>
来源:{c.source}
</div>
</div>
);
})}
{/* 停止召回实证:命中关键词却被失效规则排除的切片 */}
{q && retiredMatches.length > 0 && (
<div style={{ padding: '8px 10px', borderRadius: 9, background: tokens.warningBg, border: `1px dashed ${tokens.warning}`, minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
<AlertTriangle size={13} style={{ color: tokens.warning, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, fontWeight: 800, color: tokens.text }}>
另有 {retiredMatches.length} 条失效切片命中「{q}」,但已停止召回(active=false)
</span>
</div>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{retiredMatches.map((c) => (
<Chip key={c.id} color={tokens.textMuted} title={c.retiredReason ?? '已失效'}>{c.id}</Chip>
))}
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 5, lineHeight: 1.5 }}>
这些切片不进检索结果(防过期知识致幻),但下方明细表仍标灰留痕、可审计。
</div>
</div>
)}
</div>
<Note>
余弦分由注入语料池现算(字符级 TF-IDF),非真实嵌入模型;retrieve() 签名不变,生产内部换 Milvus,语料切片与失效规则完全复用。
</Note>
</Card>
</div>
</div>
{/* ── 底部:语料切片明细表(含失效切片,标灰可审计) ── */}
<div style={{ flex: '1 1 0', minHeight: 170, display: 'grid', gridTemplateColumns: 'minmax(0,1fr)', gridTemplateRows: 'minmax(0,1fr)', minWidth: 0 }}>
<Card title={`语料切片明细 · ${corpusLabel}`} icon={<FileText size={14} color={tokens.accent} />} full
right={
<span style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
<Archive size={12} /> {tableRows.length} 条 · 失效标灰 · 点行展开
</span>
}>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', border: `1px solid ${tokens.borderSub}`, borderRadius: 8 }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr>
<Th>#</Th><Th>切片 id</Th><Th>标题</Th><Th>语料</Th><Th>状态</Th><Th>来源 / 失效原因</Th>
</tr>
</thead>
<tbody>
{tableRows.map((c, i) => {
const open = openChunk === c.id;
const col = tokens[CORPUS_META[c.corpus].color];
const retired = !c.active;
return (
<Fragment key={c.id}>
<tr
onClick={() => setOpenChunk(open ? null : c.id)}
style={{
cursor: 'pointer',
background: open ? tokens.accentBg : retired ? tokens.panelBgAlt : 'transparent',
opacity: retired ? 0.78 : 1,
}}
>
<Td mono bold color={col}>{i + 1}</Td>
<Td mono color={retired ? tokens.textMuted : tokens.textSub}>{c.id}</Td>
<Td color={retired ? tokens.textMuted : tokens.text}>{c.title}</Td>
<Td><Chip color={col}>{c.corpus}</Chip></Td>
<Td>
<span style={{ display: 'inline-flex', gap: 4, flexWrap: 'wrap' }}>
{retired
? <Chip color={tokens.warning} title={c.retiredReason ?? '已失效'}>失效</Chip>
: <Chip color={tokens.success}>活跃</Chip>}
<Chip color={tokens.textMuted}>{SIM_BADGE}</Chip>
</span>
</Td>
<Td color={tokens.textMuted}>
{c.source}{retired && c.retiredReason ? ` — ${c.retiredReason}` : ''}
</Td>
</tr>
{open && (
<tr>
<td colSpan={6} style={{ padding: '9px 12px', background: tokens.panelBgAlt, borderBottom: `1px solid ${tokens.border}` }}>
<div style={{ fontSize: 10, color: tokens.textMuted, marginBottom: 4 }}>
原文切片 · {c.id}{retired ? ' · 已停止召回' : ''}
</div>
<div style={{ fontSize: 11.5, color: tokens.text, lineHeight: 1.55, maxWidth: 1000 }}>{c.text}</div>
</td>
</tr>
)}
</Fragment>
);
})}
{tableRows.length === 0 && (
<tr><td colSpan={6} style={{ padding: '22px 0', textAlign: 'center', fontSize: 12, color: tokens.textMuted }}>无匹配切片</td></tr>
)}
</tbody>
</table>
</div>
<Note>
明细表含失效切片(标灰 + 失效原因),与检索侧「只召回活跃」形成对照:知识可审计、召回防过期。
{q ? ` 当前关键词「${q}」命中 ${tableRows.length} 条(含失效)。` : ''}
</Note>
</Card>
</div>
</div>
);
}
/* ── 语料目录按钮:色条 + 名称 + 描述 + 切片/活跃/失效计数 ─────────────── */
function CorpusButton({ tokens, on, color, label, desc, total, active, retired, onClick }: {
tokens: ReturnType<typeof useTheme>['tokens']; on: boolean; color: string;
label: string; desc: string; total: number; active: number; retired: number; onClick: () => void;
}) {
return (
<button onClick={onClick} title={desc}
style={{
width: '100%', textAlign: 'left', cursor: 'pointer', padding: '7px 10px', borderRadius: 10,
background: on ? tokens.accentBg : tokens.panelBgAlt,
border: `1px solid ${on ? tokens.accent : tokens.border}`,
boxShadow: on ? `inset 3px 0 0 ${color}` : `inset 3px 0 0 ${color}55`,
transition: 'background .15s ease, border-color .15s ease', minWidth: 0,
}}>
<div style={{ fontSize: 12, fontWeight: 800, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</div>
<div style={{ marginTop: 2, fontSize: 10, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{desc}</div>
<div style={{ marginTop: 5, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' }}>
<Chip color={color}>切片 {total}</Chip>
<Chip color={tokens.success}>活跃 {active}</Chip>
{retired > 0 && <Chip color={tokens.warning}>失效 {retired}</Chip>}
</div>
</button>
);
}
@@ -0,0 +1,69 @@
import { createContext, useContext, useRef, type ReactNode } from 'react';
import { Pause, Play } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { useAutoScroll } from '../../hooks/useAutoScroll';
/**
* 左右工作区列表的自动滚动开关。
* 用 context 下发而不是逐层传 prop:一份弧板里挂着好几个页签
* (左:销售订单 / 客户资料;右:采购单 / 生产工单 / 供应商资料),
* 开关属于「这块面板」而不是某个列表,页签组件本身不该关心它。
*/
const AutoScrollCtx = createContext(false);
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>
);
}
/**
* 面板内带自动滚动的列表容器:样式同 PanelBody,差别是它挂了滚动循环。
* 开关默认跟随所在面板的 AutoScrollProvider,也可以显式传 autoScroll 覆盖。
*/
export function ScrollList({ children, autoScroll }: { children: ReactNode; autoScroll?: boolean }) {
const ctx = useAutoScrollEnabled();
const enabled = autoScroll ?? ctx;
const ref = useRef<HTMLDivElement>(null);
useAutoScroll(ref, enabled);
return (
<div
ref={ref}
className="space-scroll"
data-autoscroll={enabled ? 'on' : 'off'}
style={{ flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '0 0 10px 0' }}
>
{children}
</div>
);
}
@@ -0,0 +1,104 @@
import type { ReactNode } from 'react';
import {
Activity, AlertTriangle, BarChart3, BookOpen, Boxes, ClipboardList, Database, FileDown, FileText,
FlaskConical, GanttChart, Gauge, ListChecks, ListOrdered, Network, PieChart, Plug, Settings2, Sparkles, Workflow,
} from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { useText } from '../../i18n/useText';
export type TabKey = 'detail' | 'trend' | 'structure' | 'region' | 'risk' | 'cockpit' | 'priority' | 'entry' | 'task' | 'master' | 'caliber' | 'integration' | 'disclosure' | 'forecast' | 'linemap' | 'report';
export type StageKey = 'know' | 'feat' | 'ont' | 'data';
const GROUPS: { title: string; tabs: TabKey[] }[] = [
{ title: '运营监控', tabs: ['cockpit', 'linemap', 'detail', 'trend'] },
{ title: '分析诊断', tabs: ['structure', 'region', 'risk', 'forecast'] },
{ title: '改善闭环', tabs: ['priority', 'entry', 'task'] },
{ title: '运维配置', tabs: ['master', 'caliber', 'integration', 'report', 'disclosure'] },
];
const TAB_ICON: Record<TabKey, typeof Gauge> = {
cockpit: Gauge, linemap: Workflow, detail: GanttChart, trend: Activity,
structure: PieChart, region: BarChart3, risk: AlertTriangle, forecast: Sparkles,
priority: ListOrdered, entry: ClipboardList, task: ListChecks,
master: Database, caliber: Settings2, integration: Plug, report: FileDown, disclosure: FileText,
};
const STAGES: { key: StageKey; label: string; icon: typeof Gauge; tip: string }[] = [
{ key: 'know', label: '知识库', icon: BookOpen, tip: '查看 PE/IE/QE/ME 角色标准文件及其向量化 / 图谱化结果' },
{ key: 'feat', label: '工艺建模', icon: FlaskConical, tip: '查看 OEE 本体特征范围:设备/事件/状态段/损失四类对象的实例、关系与规则' },
{ key: 'ont', label: '业务本体', icon: Boxes, tip: '查看业务对象、关系、规则与动作(实时统计)' },
{ key: 'data', label: '数据集总览', icon: Network, tip: '四层 27 张表 · 本机 PostgreSQL 实况' },
];
interface Props {
tab: TabKey;
stage: StageKey | null;
onTab: (k: TabKey) => void;
onStage: (k: StageKey) => void;
}
export default function LeftNav({ tab, stage, onTab, onStage }: Props) {
const { tokens } = useTheme();
const { t } = useText();
const item = (key: string, label: string, Icon: typeof Gauge, on: boolean, onClick: () => void, tip?: string): ReactNode => (
<button
key={key}
onClick={onClick}
title={tip}
data-role={`nav-${key}`}
aria-current={on ? 'page' : undefined}
className="ghost-btn"
style={{
position: 'relative', display: 'flex', alignItems: 'center', gap: 9, width: '100%',
padding: '6px 10px 6px 12px', borderRadius: 9, cursor: 'pointer', textAlign: 'left',
fontSize: 13, fontWeight: on ? 700 : 500, whiteSpace: 'nowrap',
color: on ? tokens.accent : tokens.textSub,
background: on ? tokens.accentBg : 'transparent',
border: `1px solid ${on ? tokens.borderAccent : 'transparent'}`,
transition: 'background .18s ease, color .18s ease',
}}
>
{on && <span style={{ position: 'absolute', left: 0, top: 7, bottom: 7, width: 3, borderRadius: 2, background: tokens.accent }} />}
<Icon size={15} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</span>
</button>
);
const heading = (title: string, first = false) => (
<>
{!first && <div style={{ height: 1, background: tokens.border, margin: '8px 6px 0' }} />}
<div style={{
display: 'flex', alignItems: 'center', gap: 7,
fontSize: 13, fontWeight: 800, color: tokens.text, letterSpacing: '0.08em',
padding: first ? '8px 10px 5px' : '10px 10px 5px',
}}>
<span style={{ width: 3, height: 13, borderRadius: 2, background: tokens.accent, flexShrink: 0 }} />
{title}
</div>
</>
);
return (
<nav
data-role="left-nav"
className="space-scroll round-scroll"
style={{
flex: '0 0 208px', minHeight: 0, overflowY: 'auto', padding: '6px 8px 10px',
borderRadius: 16, border: `1px solid ${tokens.borderAccent}`,
background: tokens.centerBg, boxShadow: tokens.centerShadow,
backdropFilter: 'blur(10px) saturate(1.3)',
display: 'flex', flexDirection: 'column', gap: 1,
}}
>
{GROUPS.map((g, gi) => (
<div key={g.title} style={{ display: 'flex', flexDirection: 'column', gap: 1 }}>
{heading(g.title, gi === 0)}
{g.tabs.map(k => item(k, t.tab[k], TAB_ICON[k], stage === null && tab === k, () => onTab(k)))}
</div>
))}
{heading('建模配置')}
{STAGES.map(s => item(`stage-${s.key}`, s.label, s.icon, stage === s.key, () => onStage(s.key), s.tip))}
</nav>
);
}
@@ -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/oeeTime';
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>{periodLabel(0)}</span><span>虚线=目标</span><span>{periodLabel(11)}</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: 'tfamd-net-radar 56s linear infinite',
opacity: 0.75,
}} />
</div>
)}
{/* 星点闪烁 */}
{stars.map((s, i) => (
<span
key={i}
className="net-twinkle"
style={{
position: 'absolute', left: s.left, top: s.top,
width: s.size, height: s.size, borderRadius: '50%',
background: i % 7 === 0 ? '#93c5fd' : '#dbeafe',
['--tw-o' as string]: s.o,
['--tw-d' as string]: s.d,
['--tw-delay' as string]: s.delay,
animationDelay: s.delay,
opacity: s.o,
}}
/>
))}
</>
)}
{/* 边缘暗角:收束视线,制造纵深 */}
{deep && (
<div style={layer({
background: 'radial-gradient(ellipse 78% 78% at 50% 50%, transparent 52%, rgba(2,6,18,0.55) 100%)',
})} />
)}
</div>
);
}
@@ -0,0 +1,180 @@
import { useEffect, useRef, useState } from 'react';
import { ChevronLeft, ChevronRight, Play, Radio, Square } from 'lucide-react';
import type { ThemeTokens } from '../../context/ThemeContext';
import type { I18n } from '../../i18n/locales';
import { CURRENT_PERIOD, PERIOD_COUNT, periodLabel, periodShortLabel } from '../../lib/oeeTime';
import { replayHealth } from '../../lib/replay';
/**
* BI 式时间轴滑块:拖动 / 点击刻度 / 自动回放,全图按游标时点重取值与状态。
* 背景柱不再借用经营指标 OV,而是由「回放健康度」驱动:
* 与中央六页签、左栏流程、抬头同属一条 2025-11 → 2026-10 的质量曲线。
*/
interface Props {
period: number;
onPeriod: (p: number) => void;
tokens: ThemeTokens;
t: I18n;
}
export default function MetricTimeline({ period, onPeriod, tokens, t }: Props) {
const [playing, setPlaying] = useState(false);
const trackRef = useRef<HTMLDivElement>(null);
const draggingRef = useRef(false);
const periodRef = useRef(period); periodRef.current = period;
const onPeriodRef = useRef(onPeriod); onPeriodRef.current = onPeriod;
useEffect(() => {
if (!playing) return;
const id = window.setInterval(() => {
onPeriodRef.current((periodRef.current + 1) % PERIOD_COUNT);
}, 850);
return () => window.clearInterval(id);
}, [playing]);
const posToPeriod = (clientX: number) => {
const el = trackRef.current;
if (!el) return periodRef.current;
const r = el.getBoundingClientRect();
const f = (clientX - r.left) / Math.max(1, r.width);
return Math.max(0, Math.min(PERIOD_COUNT - 1, Math.floor(f * PERIOD_COUNT)));
};
const [trackW, setTrackW] = useState(0);
useEffect(() => {
const el = trackRef.current;
if (!el) return;
const ro = new ResizeObserver(([e]) => setTrackW(e.contentRect.width));
ro.observe(el);
return () => ro.disconnect();
}, []);
// 日轴刻度按轨道实宽抽稀(每签约 34px),当期刻度恒显示,避开其两侧的常规刻度
const step = Math.max(1, Math.ceil((PERIOD_COUNT * 40) / Math.max(1, trackW)));
const shownTicks = Array.from({ length: PERIOD_COUNT }, (_, i) => i).filter(
(i) => i === period || (i % step === 0 && Math.abs(i - period) >= step),
);
const cur = periodLabel(period);
return (
<div style={{
flex: '0 0 auto', display: 'flex', alignItems: 'center', gap: 12,
margin: '0 6px 6px', padding: '9px 14px', borderRadius: 12,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
backdropFilter: 'blur(8px)', userSelect: 'none',
}}>
{/* 回放控制 */}
<button
onClick={() => setPlaying(p => !p)}
className="ghost-btn"
title={playing ? t.net.tlPause : t.net.tlPlay}
style={{
display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0, cursor: 'pointer',
padding: '4px 10px', borderRadius: 8, fontSize: 12, fontWeight: 700,
color: playing ? tokens.onAccent : tokens.accent,
background: playing ? tokens.accent : tokens.accentBg,
border: `1px solid ${tokens.borderAccent}`,
}}
>
{playing ? <Square size={11} /> : <Play size={11} />}
{playing ? t.net.tlPause : t.net.tlPlay}
</button>
{/* 轨道:12 根健康度柱 + 游标 */}
<div
ref={trackRef}
style={{ position: 'relative', flex: 1, height: 42, cursor: 'ew-resize', touchAction: 'none', minWidth: 0 }}
onPointerDown={e => {
draggingRef.current = true;
setPlaying(false);
try { e.currentTarget.setPointerCapture(e.pointerId); } catch { /* 合成指针下降级为无捕获拖动 */ }
onPeriod(posToPeriod(e.clientX));
}}
onPointerMove={e => { if (draggingRef.current) onPeriod(posToPeriod(e.clientX)); }}
onPointerUp={() => { draggingRef.current = false; }}
onPointerCancel={() => { draggingRef.current = false; }}
>
{/* 柱阵列 */}
<div style={{ position: 'absolute', inset: '0 0 12px', display: 'flex', gap: PERIOD_COUNT > 40 ? 1 : 3 }}>
{Array.from({ length: PERIOD_COUNT }, (_, i) => {
const health = replayHealth(i);
const passed = i <= period;
const h = 12 + Math.max(0.2, Math.min(1, health / 100)) * 24;
const col = health >= 85 ? tokens.success : health >= 70 ? tokens.warning : tokens.danger;
return (
<div key={i} title={`回放健康度 ${health}`} style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'flex-end', alignItems: 'stretch' }}>
<div style={{
height: h, borderRadius: 3,
background: col,
opacity: i === period ? 0.95 : passed ? 0.42 : 0.16,
boxShadow: i === period ? `0 0 10px ${col}88` : 'none',
transition: 'opacity 0.25s ease, height 0.4s ease, box-shadow 0.25s ease',
}} />
</div>
);
})}
</div>
{/* 游标发光线 */}
<div style={{
position: 'absolute', top: 0, bottom: 10, width: 2, borderRadius: 2,
left: `calc(${((period + 0.5) / PERIOD_COUNT) * 100}% - 1px)`,
background: `linear-gradient(180deg, ${tokens.accent}, ${tokens.info})`,
boxShadow: `0 0 10px ${tokens.accentGlow}`,
transition: 'left 0.28s cubic-bezier(0.22,1,0.36,1)', pointerEvents: 'none',
}}>
<span style={{
position: 'absolute', top: -3, left: '50%', transform: 'translateX(-50%)',
width: 9, height: 9, borderRadius: '50%', background: tokens.accent,
boxShadow: `0 0 8px ${tokens.accentGlow}`, border: `2px solid ${tokens.panelBgAlt}`,
}} />
</div>
{/* 日刻度 */}
<div style={{ position: 'absolute', left: 0, right: 0, bottom: -2, height: 12, overflow: 'hidden' }}>
{shownTicks.map((i) => (
<span key={i} style={{
position: 'absolute', top: 0, whiteSpace: 'nowrap', fontSize: 9.5, lineHeight: '12px',
left: i === 0 ? 0 : i === PERIOD_COUNT - 1 ? '100%' : `${((i + 0.5) / PERIOD_COUNT) * 100}%`,
transform: `translateX(${i === 0 ? '0' : i === PERIOD_COUNT - 1 ? '-100%' : '-50%'})`,
fontVariantNumeric: 'tabular-nums',
color: i === period ? tokens.accent : tokens.textMuted,
opacity: i === period ? 1 : 0.55, fontWeight: i === period ? 800 : 400,
}}>{periodShortLabel(i)}</span>
))}
</div>
</div>
{/* 当前期读数 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexShrink: 0 }}>
<button
onClick={() => onPeriod(Math.max(0, period - 1))}
className="ghost-btn"
style={{ display: 'grid', placeItems: 'center', width: 22, height: 22, borderRadius: 6, cursor: 'pointer', color: tokens.textSub, border: `1px solid ${tokens.border}`, background: 'transparent' }}
><ChevronLeft size={13} /></button>
<span style={{
display: 'flex', alignItems: 'center', gap: 5, fontSize: 13.5, fontWeight: 800,
color: tokens.accent, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace',
minWidth: 86, justifyContent: 'center',
}}>
<Radio size={11} />{cur}
</span>
<button
onClick={() => onPeriod(Math.min(PERIOD_COUNT - 1, period + 1))}
className="ghost-btn"
style={{ display: 'grid', placeItems: 'center', width: 22, height: 22, borderRadius: 6, cursor: 'pointer', color: tokens.textSub, border: `1px solid ${tokens.border}`, background: 'transparent' }}
><ChevronRight size={13} /></button>
<button
onClick={() => { setPlaying(false); onPeriod(CURRENT_PERIOD); }}
className="ghost-btn"
disabled={period === CURRENT_PERIOD}
style={{
padding: '3px 10px', borderRadius: 8, fontSize: 11.5, fontWeight: 700, cursor: period === CURRENT_PERIOD ? 'default' : 'pointer',
color: period === CURRENT_PERIOD ? tokens.textMuted : tokens.accent,
border: `1px solid ${period === CURRENT_PERIOD ? tokens.border : tokens.borderAccent}`,
background: period === CURRENT_PERIOD ? 'transparent' : tokens.accentBg,
whiteSpace: 'nowrap',
}}
>{t.net.tlBack}</button>
</div>
</div>
);
}
@@ -0,0 +1,21 @@
import type { ThemeTokens } from '../../context/ThemeContext';
/** 舞台态强制深空(Bloomberg 黑屏模式):图谱与看板共用同一套语义色,不随用户主题漂移 */
export const DEEP: Partial<ThemeTokens> = {
text: '#e8eefc', textSub: '#a9b8d0', textMuted: 'rgba(154,172,199,0.82)',
accent: '#56ace0', accentGlow: 'rgba(86,172,224,0.75)', accentBg: 'rgba(86,172,224,0.10)',
border: 'rgba(86,172,224,0.16)', borderSub: 'rgba(86,172,224,0.08)', borderAccent: 'rgba(86,172,224,0.34)',
panelBg: 'rgba(8,13,28,0.92)', panelBgAlt: 'rgba(10,16,32,0.72)', cardBg: 'rgba(20,29,54,0.66)',
success: '#34d399', warning: '#fbbf24', danger: '#f87171', info: '#38bdf8',
};
export const DEEP_BG = 'radial-gradient(120% 95% at 50% 40%, #0a1022 0%, #060a16 52%, #03060e 100%)';
/** 达成率弧:从 12 点顺时针的 donut 弧(节点形态即数据:环弧长度=达成率) */
export function arcPath(cx: number, cy: number, r: number, frac: number): string {
const f = Math.min(0.9999, Math.max(0.0001, frac));
const a0 = -Math.PI / 2, a1 = a0 + f * Math.PI * 2;
const x0 = cx + r * Math.cos(a0), y0 = cy + r * Math.sin(a0);
const x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
return `M ${x0.toFixed(2)},${y0.toFixed(2)} A ${r},${r} 0 ${f > 0.5 ? 1 : 0} 1 ${x1.toFixed(2)},${y1.toFixed(2)}`;
}
@@ -0,0 +1,380 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTheme } from '../../context/ThemeContext';
/**
* 业务本体图谱:节点、边都由调用方传入(履约本体 8 对象 / 品质本体 17 张表各一套),
* 这里只负责画。力导向布局移植自智能体开发平台的本体管理页(纯手写 SVG,不引 d3):
* 环形初始化 → 斥力 9000/d² → 弹簧 (d−rest)×0.008 → 向心 0.004 → 阻尼 0.88,跑满 120 帧收敛。
* 斥力/弹簧原长/向心力都按容器尺寸与节点数给(不是写死常数),因此 8 与 17 节点两种规模都铺得开。
*
* 画布有三种模式,构成「总览 → 裂变 → 下钻」的现场演示动线:
* graph 总览:17 张表 + 关系边(力导向)
* explode 裂变:双击某张表后,它缩成中心锚,本表实例作为药签沿椭圆环炸开,其余表淡出
* instance 下钻:再点一个实例,环上摊开该实例的字段(列名 = 值)
* 两种 zoom 布局的坐标都是同步算出来的,CSS 只做透明/缩放插值,
* 所以即使动画被浏览器挂起(无头截图场景),终态几何依然正确、可被 getBoundingClientRect 读出来。
* 配色全走本应用主题 token,深浅两套主题都保证边线与文字有足够对比度。
*/
export interface GNode { id: string; label: string; count: number; color: string }
export interface GEdge { id: string; source: string; target: string; label: string }
export type GraphMode = 'graph' | 'explode' | 'instance';
/** 裂变/下钻环上的药签:explode 是实例,instance 是字段 */
export interface SatNode { id: string; label: string; value?: string; badge?: string }
interface SimNode extends GNode { x: number; y: number; vx: number; vy: number; deg: number }
interface Props {
nodes: GNode[];
edges: GEdge[];
selectedNodeId: string | null;
selectedEdgeId: string | null;
onNodeClick?: (id: string) => void;
onEdgeClick?: (id: string) => void;
/** 双击节点:进入裂变(把该表实例炸开成一圈) */
onNodeDoubleClick?: (id: string) => void;
/** 三种画布模式,缺省为总览 */
mode?: GraphMode;
/** explode / instance 的中心锚(表或实例) */
center?: { label: string; sub?: string; badge?: string; color: string; count?: number } | null;
/** explode / instance 环上的药签 */
satellites?: SatNode[];
/** 环上药签被点(explode 时=下钻该实例) */
onSatelliteClick?: (id: string) => void;
/** 点画布空白:返回上一级 */
onBackgroundClick?: () => void;
}
/** 椭圆环按弧长等分取点,避免直接按角度分导致长轴两端药签挤在一起 */
function ellipsePoints(n: number, rx: number, ry: number, cx: number, cy: number): [number, number][] {
if (n <= 0) return [];
if (n === 1) return [[cx, cy - ry]];
const N = 720;
const acc: number[] = [0];
let px = cx, py = cy - ry, total = 0;
for (let i = 1; i <= N; i++) {
const a = (i / N) * 2 * Math.PI - Math.PI / 2;
const x = cx + rx * Math.cos(a), y = cy + ry * Math.sin(a);
total += Math.hypot(x - px, y - py); acc.push(total); px = x; py = y;
}
/* 半轴 a,b 的椭圆周长:拉马努金近似,用来反推药签可用宽度 */
const at = (target: number): [number, number] => {
let lo = 0, hi = N;
while (lo < hi) { const mid = (lo + hi) >> 1; if (acc[mid] < target) lo = mid + 1; else hi = mid; }
const a = (lo / N) * 2 * Math.PI - Math.PI / 2;
return [cx + rx * Math.cos(a), cy + ry * Math.sin(a)];
};
return Array.from({ length: n }, (_, k) => at((k / n) * total));
}
const ellipseCircumference = (a: number, b: number) =>
Math.PI * (3 * (a + b) - Math.sqrt((3 * a + b) * (a + 3 * b)));
/** 节点内只放清洗后的短名,全称留给节点下方那行 */
const shortName = (s: string) => s.replace(/([^)]*)/g, '').trim();
export default function OntologyGraph({
nodes: rawNodes, edges, selectedNodeId, selectedEdgeId, onNodeClick, onEdgeClick, onNodeDoubleClick,
mode = 'graph', center = null, satellites = [], onSatelliteClick, onBackgroundClick,
}: Props) {
const { tokens } = useTheme();
const svgRef = useRef<SVGSVGElement>(null);
const [nodes, setNodes] = useState<SimNode[]>([]);
const [dims, setDims] = useState({ w: 720, h: 420 });
const [hovered, setHovered] = useState<string | null>(null);
/* 药签入场:不用 CSS animation(fill-mode:both 会把 0% 关键帧钉死,
动画被挂起时终态就永远停在 opacity:0 / scale(0.2),无头截图里药签整个消失)。
改成 JS 定时器翻状态 + 内层 <g> 的 transition:计时器照跑,
而 transition 没有 fill-mode,静止态恒等于目标值(scale 1 / opacity 1),
即使过渡帧被浏览器跳过,终态也是「全部可见」。 */
const [satShown, setSatShown] = useState(false);
useEffect(() => {
const box = svgRef.current?.parentElement;
if (!box) return;
const measure = () => {
const r = box.getBoundingClientRect();
if (r.width > 0 && r.height > 0) setDims({ w: r.width, h: r.height });
};
/* ResizeObserver 的回调靠 rAF 投递:页面切到后台时会整段挂起,舞台刚进场那几帧
flex 比例也还没定。这里同步测一次 + 补两次延时测 + 盯 window resize,
保证布局坐标系最终等于真实容器,不会因为 RO 没投递而按默认尺寸画。 */
measure();
const ro = new ResizeObserver(([e]) => setDims({ w: e.contentRect.width, h: e.contentRect.height }));
ro.observe(box);
const t1 = setTimeout(measure, 120);
const t2 = setTimeout(measure, 420);
window.addEventListener('resize', measure);
return () => {
ro.disconnect();
clearTimeout(t1); clearTimeout(t2);
window.removeEventListener('resize', measure);
};
}, []);
/* ── 布局仿真:数据或尺寸变化即重跑(数据只有 8 节点,成本可忽略) ── */
useEffect(() => {
if (rawNodes.length === 0) return;
const cnt = rawNodes.length;
/* 本体有两套规模:履约 8 对象、品质 17 张表。斥力/弹簧原长/向心力都按节点数缩放,
否则 17 节点会挤成一团毛球、8 节点又散得太开。以 8 节点为基准(保持原参数不变)。 */
const spread = cnt / 8;
const cx = dims.w / 2, cy = dims.h / 2;
const deg: Record<string, number> = {};
rawNodes.forEach(n => { deg[n.id] = 0; });
edges.forEach(e => { deg[e.source] = (deg[e.source] || 0) + 1; deg[e.target] = (deg[e.target] || 0) + 1; });
/* 舞台通常是横宽竖窄的:初始化用椭圆环而不是正圆,避免节点全挤在中间一条 */
const rx = Math.max(150, dims.w * 0.34), ry = Math.max(96, dims.h * 0.34);
setNodes(rawNodes.map((n, i) => {
const a = (2 * Math.PI * i) / cnt - Math.PI / 2;
return { ...n, deg: deg[n.id] || 0, x: cx + rx * Math.cos(a), y: cy + ry * Math.sin(a), vx: 0, vy: 0 };
}));
// 斥力与弹簧原长按容器尺寸与节点数给:常数写死会让宽舞台只用到中间一小块或挤成一团
const repel = 9000 * spread;
const rest = Math.max(100, Math.min(190, Math.min(dims.w, dims.h) * 0.5));
let frame = 0;
const timer = setInterval(() => {
if (frame++ > 120) { clearInterval(timer); return; }
setNodes(prev => {
const next = prev.map(n => ({ ...n }));
for (let i = 0; i < next.length; i++) for (let j = i + 1; j < next.length; j++) {
const dx = next[j].x - next[i].x, dy = next[j].y - next[i].y;
const d = Math.max(Math.hypot(dx, dy), 1);
const f = repel / (d * d);
next[i].vx -= (dx / d) * f; next[i].vy -= (dy / d) * f;
next[j].vx += (dx / d) * f; next[j].vy += (dy / d) * f;
}
const byId = new Map(next.map(n => [n.id, n]));
for (const e of edges) {
const s = byId.get(e.source), t = byId.get(e.target);
if (!s || !t) continue;
const dx = t.x - s.x, dy = t.y - s.y;
const d = Math.max(Math.hypot(dx, dy), 1);
const f = (d - rest) * 0.008;
s.vx += (dx / d) * f; s.vy += (dy / d) * f;
t.vx -= (dx / d) * f; t.vy -= (dy / d) * f;
}
for (const n of next) {
n.vx += (cx - n.x) * (0.004 / spread); n.vy += (cy - n.y) * (0.004 / spread);
n.vx *= 0.88; n.vy *= 0.88; n.x += n.vx; n.y += n.vy;
n.x = Math.max(74, Math.min(dims.w - 74, n.x));
n.y = Math.max(52, Math.min(dims.h - 62, n.y));
}
return next;
});
}, 16);
return () => clearInterval(timer);
}, [rawNodes, edges, dims]);
/* 每次换层(模式/中心/药签数变了)先归零再下一帧翻起,让错峰过渡重放一次 */
useEffect(() => {
setSatShown(false);
const t = setTimeout(() => setSatShown(true), 24);
return () => clearTimeout(t);
}, [mode, center?.label, satellites.length]);
const maxDeg = useMemo(() => Math.max(...nodes.map(n => n.deg), 1), [nodes]);
const byId = useMemo(() => new Map(nodes.map(n => [n.id, n] as const)), [nodes]);
/** 度数决定半径:枢纽对象明显大于叶子对象 */
const rOf = (deg: number) => 24 + (deg / maxDeg) * 12;
/* 17 张表时边标签与节点下方的重复标签会糊成一团:密图只保留圈内名 + 数量,
边的中文名改成悬停/选中才浮出,节点下方的「短名 · N 实例」也只在稀疏图(≤10 节点)保留。 */
const dense = nodes.length > 10;
const active = hovered ?? selectedNodeId;
const isNeighbor = (id: string) =>
!!active && edges.some(e => (e.source === active && e.target === id) || (e.target === active && e.source === id));
/* 三种模式共用的 SVG 资源 */
const svgDefs = (
<defs>
<marker id="ont-arrow" markerWidth="9" markerHeight="7" refX="9" refY="3.5" orient="auto">
<polygon points="0 0, 9 3.5, 0 7" fill={tokens.textMuted} />
</marker>
<marker id="ont-arrow-hl" markerWidth="9" markerHeight="7" refX="9" refY="3.5" orient="auto">
<polygon points="0 0, 9 3.5, 0 7" fill={tokens.accent} />
</marker>
<pattern id="ont-dots" width="26" height="26" patternUnits="userSpaceOnUse">
<circle cx="13" cy="13" r="0.9" fill={tokens.svgStroke} opacity="0.5" />
</pattern>
<filter id="ont-soft" x="-50%" y="-50%" width="200%" height="200%">
<feDropShadow dx="0" dy="1.5" stdDeviation="3.5" floodColor={tokens.accentGlow} floodOpacity="0.25" />
</filter>
<filter id="ont-strong" x="-50%" y="-50%" width="200%" height="200%">
<feDropShadow dx="0" dy="0" stdDeviation="7" floodColor={tokens.accentGlow} floodOpacity="0.55" />
</filter>
</defs>
);
/* ── explode / instance:以 center 为锚、药签沿椭圆环炸开(坐标同步算,动画只做插值) ── */
if (mode !== 'graph' && center) {
const cc = center.color;
const cx = dims.w / 2, cy = dims.h / 2;
const cr = mode === 'instance' ? 50 : 46;
const rx = Math.max(170, dims.w / 2 - 74);
const ry = Math.max(88, dims.h / 2 - 46);
const capacity = ellipseCircumference(rx, ry);
/* 药签宽度按环容量自适应:节点多就收窄,保证 11 条实例也能均匀铺开而不叠字。
再夹一道容器约束:椭圆左右各留 74px(rx 的 inset),药签半宽必须小于它,
否则 12 张分析卡这种大规模会把最左/最右药签切出画布。 */
const pw = Math.max(84, Math.min(158, capacity / Math.max(satellites.length, 1) - 14, 132));
const ph = 27;
const pts = ellipsePoints(satellites.length, rx, ry, cx, cy);
return (
<svg ref={svgRef} width="100%" height="100%" viewBox={`0 0 ${dims.w} ${dims.h}`}
preserveAspectRatio="xMidYMid meet" style={{ display: 'block', userSelect: 'none' }}>
{svgDefs}
<rect width="100%" height="100%" fill="url(#ont-dots)" onClick={onBackgroundClick} />
{/* 中心锚到每个药签的辐条:explode=属于,instance=字段 */}
{pts.map(([x, y], i) => {
const dx = x - cx, dy = y - cy;
const d = Math.hypot(dx, dy) || 1;
return (
<line key={`sp-${satellites[i].id}`}
x1={cx + (dx / d) * (cr + 4)} y1={cy + (dy / d) * (cr + 4)}
x2={x - (dx / d) * (pw / 2)} y2={y - (dy / d) * (ph / 2)}
stroke={cc} strokeWidth={1} opacity={0.28} />
);
})}
{/* 中心锚:外圈呼吸环 + 品牌色圆 */}
<g transform={`translate(${cx}, ${cy})`}>
<circle r={cr + 12} fill="none" stroke={cc} strokeWidth={1.2} strokeDasharray="4 4" opacity={0.5} />
<circle r={cr + 5} fill="none" stroke={cc} strokeWidth={1.4} opacity={0.32} filter="url(#ont-strong)" />
<circle r={cr} fill={tokens.panelBgAlt} stroke={cc} strokeWidth={2.4} filter="url(#ont-soft)" />
<text textAnchor="middle" dy={mode === 'instance' ? -6 : -2} fontSize={mode === 'instance' ? 12 : 13}
fontWeight={800} fill={tokens.text}>{center.label}</text>
{mode === 'instance'
? <text textAnchor="middle" dy={10} fontSize={10} fill={tokens.textSub}>{center.sub ?? ''}</text>
: <text textAnchor="middle" dy={15} fontSize={11} fontWeight={700} fill={cc}>{center.count ?? 0} 条实例</text>}
{center.badge && (
<g transform={`translate(0, ${cr + 24})`}>
<rect x={-Math.max(22, center.badge.length * 6.4)} y={-9} width={Math.max(44, center.badge.length * 12.8)}
height={18} rx={9} fill={tokens.panelBgAlt} stroke={cc} strokeWidth={0.8} />
<text textAnchor="middle" dy={3.5} fontSize={10} fontWeight={700} fill={cc}>{center.badge}</text>
</g>
)}
</g>
{/* 环上药签:炸开时有 0.2→1 的缩放与错峰延时 */}
{satellites.map((st, i) => {
const [x, y] = pts[i];
const text = st.value ? `${st.label} ${st.value}` : st.label;
const max = Math.floor((pw - 16) / 6.4);
const shown = text.length > max ? `${text.slice(0, Math.max(1, max - 1))}…` : text;
return (
<g key={st.id} className="ont-sat" transform={`translate(${x}, ${y})`} style={{ cursor: 'pointer' }}
onClick={() => onSatelliteClick?.(st.id)}>
{/* 位置在外层 <g>(transform 属性,与动画无关);缩放在内层 <g>(transition,终态恒为 1) */}
<g style={{
transformBox: 'fill-box', transformOrigin: 'center',
transform: satShown ? 'scale(1)' : 'scale(0.2)',
opacity: satShown ? 1 : 0,
transition: `transform 0.45s cubic-bezier(0.2,0.8,0.25,1) ${i * 42}ms, opacity 0.32s linear ${i * 42}ms`,
}}>
<title>{text}</title>
<rect x={-pw / 2} y={-ph / 2} width={pw} height={ph} rx={13}
fill={tokens.panelBgAlt} stroke={cc} strokeWidth={0.9} opacity={0.96} />
<text textAnchor="middle" dy={3.5} fontSize={10.5} fontWeight={600} fill={tokens.text}>{shown}</text>
{st.badge && (
<g transform={`translate(${pw / 2 - 4}, ${-ph / 2 + 2})`}>
<circle r={9} fill={tokens.cardBg} stroke={cc} strokeWidth={0.8} />
<text textAnchor="middle" dy={3} fontSize={8.5} fontWeight={700} fill={cc}>
{st.badge.slice(0, 2)}
</text>
</g>
)}
</g>
</g>
);
})}
</svg>
);
}
return (
<svg ref={svgRef} width="100%" height="100%" viewBox={`0 0 ${dims.w} ${dims.h}`}
preserveAspectRatio="xMidYMid meet" style={{ display: 'block', userSelect: 'none' }}>
{svgDefs}
<rect width="100%" height="100%" fill="url(#ont-dots)" onClick={onBackgroundClick} />
{/* ── 关系边:透明粗线负责命中,细线负责显示 ── */}
{edges.map(e => {
const s = byId.get(e.source), t = byId.get(e.target);
if (!s || !t) return null;
const sel = e.id === selectedEdgeId;
const hl = sel || active === e.source || active === e.target;
const dx = t.x - s.x, dy = t.y - s.y;
const d = Math.hypot(dx, dy) || 1;
const sx = s.x + (dx / d) * (rOf(s.deg) + 5), sy = s.y + (dy / d) * (rOf(s.deg) + 5);
const tx = t.x - (dx / d) * (rOf(t.deg) + 6), ty = t.y - (dy / d) * (rOf(t.deg) + 6);
const mx = (sx + tx) / 2, my = (sy + ty) / 2;
const label = `${e.label}${sel ? ' ⟶' : ''}`;
const w = label.length * 10 + 10;
const showLabel = !dense || sel || hl;
return (
<g key={e.id} style={{ cursor: 'pointer' }} onClick={() => onEdgeClick?.(e.id)}>
<line x1={sx} y1={sy} x2={tx} y2={ty} stroke="transparent" strokeWidth={14} />
<line x1={sx} y1={sy} x2={tx} y2={ty}
stroke={sel ? tokens.accent : hl ? tokens.info : tokens.textMuted}
strokeWidth={sel ? 2.4 : hl ? 1.6 : 1}
opacity={sel || hl ? 1 : 0.45}
markerEnd={hl || sel ? 'url(#ont-arrow-hl)' : 'url(#ont-arrow)'} />
{showLabel && (
<>
<rect x={mx - w / 2} y={my - 8} width={w} height={16} rx={5}
fill={sel ? tokens.accentBg : tokens.panelBgAlt}
stroke={sel ? tokens.accent : hl ? tokens.info : tokens.border}
strokeWidth={sel ? 1.4 : 0.7} />
<text x={mx} y={my + 3.5} textAnchor="middle" fontSize={10} fontWeight={sel ? 700 : 500}
fill={sel ? tokens.accent : hl ? tokens.info : tokens.textSub}>{label}</text>
</>
)}
</g>
);
})}
{/* ── 对象节点 ── */}
{nodes.map(n => {
const r = rOf(n.deg);
const sel = n.id === selectedNodeId;
const hl = hovered === n.id;
const dim = !!active && !sel && !hl && !isNeighbor(n.id);
const ring = sel ? tokens.accent : hl ? tokens.info : n.color;
return (
<g key={n.id} transform={`translate(${n.x}, ${n.y})`} opacity={dim ? 0.28 : 1}
style={{ cursor: 'pointer' }}
onMouseEnter={() => setHovered(n.id)} onMouseLeave={() => setHovered(null)}
onClick={() => onNodeClick?.(n.id)} onDoubleClick={() => onNodeDoubleClick?.(n.id)}>
{sel && (
<circle r={r + 9} fill="none" stroke={tokens.accent} strokeWidth={1.4}
strokeDasharray="4 3" opacity={0.75} />
)}
<circle r={r + 4} fill="none" stroke={ring} strokeWidth={sel ? 2 : 1}
opacity={sel ? 0.85 : hl ? 0.5 : 0.16}
filter={sel || hl ? 'url(#ont-strong)' : undefined} />
<circle r={r} fill={tokens.panelBgAlt} stroke={ring}
strokeWidth={sel ? 2.4 : hl ? 1.8 : 1.1} filter="url(#ont-soft)" />
{/* 对象自身的品牌色压在底部,区分「销售订单 / 工单 / 采购单」 */}
<path d={`M ${-r * 0.45} ${r - 2.5} A ${r} ${r} 0 0 0 ${r * 0.45} ${r - 2.5}`}
fill="none" stroke={n.color} strokeWidth={2.4} strokeLinecap="round" opacity={dim ? 0.3 : 0.9} />
<text textAnchor="middle" dy={-3} fontSize={r > 30 ? 12 : 11} fontWeight={700}
fill={sel || hl ? ring : tokens.text}>{shortName(n.label)}</text>
<text textAnchor="middle" dy={12} fontSize={10.5} fontWeight={700}
fill={sel || hl ? ring : n.color}>{n.count}</text>
{!dense && (
<text textAnchor="middle" dy={r + 17} fontSize={10} fill={tokens.textMuted}>
{shortName(n.label)} · {n.count} 实例
</text>
)}
</g>
);
})}
</svg>
);
}
@@ -0,0 +1,887 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { AlertTriangle, Boxes, ChevronRight, CircleSlash2, FlaskConical, Lock, Network, Search, ShieldAlert, X, Zap } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import {
actions, instanceFields, objectById, objects, relations, rules,
ONTOLOGY_AS_OF, ONTOLOGY_SCOPE_NOTE,
type OntAction, type OntInstance, type OntObject, type OntRelation, type OntRule, type Severity, type Tone,
} from '../../data/ontologyOee';
import OntologyGraph, { type SatNode } from './OntologyGraph';
import StageHint from '../common/StageHint';
/**
* OEE 业务本体总览:建议书 3.6 的 9 类对象(设备 / 产线拓扑 / 批次 / 事件 / 状态段 /
* 损失 / 绩效 / 口径 / 改善)+共同分析本体 4 类(分析问题 / 因子定义 / 改善对策 / 成本参数),
* 抽象成「对象—关系—规则—动作」四层——
* 对象=业务实体、属性=实体字段、实例=L3 服务层现算出的真实行、关系=实体间真实连接键、
* 规则=口径与 DQ 里写明的阈值、动作=规则命中后真正的处置。
* 结构在上方图谱里看,清单在下方四栏里选,点任意条目在右侧下钻到属性与真实实例。
*
* 图谱是一条「总览 → 裂变 → 下钻」的演示动线(现场讲解用):
* 单击对象 聚焦联动:高亮该对象与链路,下方四栏同步高亮/滚动到相关条目(关系按 from/to、规则动作按 tables)
* 双击对象 裂变:该对象缩成中心锚,本对象实例作为药签沿椭圆环炸开
* 单击药签 下钻:环上摊开该实例的字段(列名 = 值)
* 返回:点面包屑任一级、点画布空白、或 ESC(非全屏时逐级退,全屏时 ESC 退出整个舞台)。
*
* ★ 所有数字(实例数、关系基数、规则命中数)都在 src/data/ontologyOee.ts 里从 L3 服务层现算,
* 页面不写死任何统计值,也不自己再跑一遍链路(断言②「四处读数一致」)。
* 跑不出结果的规则一律 blocked+gap 标灰:线体合成待 W2、改善任务待 W3-B、实时直采未接入,
* **不造实例充数**。文案与本体数据层同源,全部是中文业务术语,因此不走 i18n 词典。
*/
type Sel =
| { kind: 'object'; id: string }
| { kind: 'relation'; id: string }
| { kind: 'rule'; id: string }
| { kind: 'action'; id: string };
/** 图谱画布层级:总览 → 某表裂变 → 某实例下钻 */
type View =
| { mode: 'graph' }
| { mode: 'explode'; table: string }
| { mode: 'instance'; table: string; inst: string };
const toneColor = (tk: ThemeTokens, t: Tone) =>
t === 'success' ? { c: tk.success, bg: tk.successBg }
: t === 'warning' ? { c: tk.warning, bg: tk.warningBg }
: t === 'danger' ? { c: tk.danger, bg: tk.dangerBg }
: { c: tk.info, bg: tk.infoBg };
const sevTone = (s: Severity): Tone => (s === 'error' ? 'danger' : s === 'warning' ? 'warning' : 'info');
const ACTION_TYPE: Record<OntAction['type'], { label: string; tone: Tone }> = {
query: { label: '查询', tone: 'info' },
alert: { label: '告警', tone: 'warning' },
report: { label: '报表', tone: 'success' },
workflow: { label: '流程', tone: 'danger' },
};
/* 卡片底:选中时压 accent 边框,未选中只靠边框与留白分组,不加彩色左边条 */
const cardBase = (tk: ThemeTokens, on: boolean): React.CSSProperties => ({
width: '100%', textAlign: 'left', cursor: 'pointer', marginBottom: 7,
padding: '8px 10px', borderRadius: 9,
background: on ? tk.accentBg : tk.panelBgAlt,
border: `1px solid ${on ? tk.accent : tk.border}`,
transition: 'background .15s ease, border-color .15s ease',
});
/* 面包屑按钮:当前层加粗压色,其余弱化 */
const crumbBtn = (tk: ThemeTokens, active: boolean): React.CSSProperties => ({
background: 'none', border: 'none', cursor: 'pointer', padding: '1px 4px', borderRadius: 6,
fontSize: 11.5, fontWeight: active ? 800 : 600,
color: active ? tk.accent : tk.textSub,
});
const Pill = ({ tone, children }: { tone: Tone; children: React.ReactNode }) => {
const { tokens } = useTheme();
const c = toneColor(tokens, tone);
return (
<span style={{
fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 999, whiteSpace: 'nowrap',
color: c.c, background: c.bg, border: `1px solid ${c.c}44`,
}}>{children}</span>
);
};
export type OntScope = 'all' | 'feature';
interface Props {
onExit: () => void;
/** 视图范围:all=全部 13 类对象(OEE 业务本体 + 共同分析本体);feature=只纳入特征建模相关对象 */
scope?: OntScope;
/** 从外部跳来时:指定要聚焦的对象/实例 */
focus?: { objKey: string; instanceId?: string } | null;
}
/**
* 各范围纳入的对象 id。
* ★ 这里填的是**对象 id**(equipment/event/…),不是物理表名——
* ontologyOee 的 rules[].tables / actions[].tables 也按对象 id 填,
* 两边键空间必须一致,否则聚焦联动与范围过滤会静默失效(空数组恒真)。
* feature 范围取「设备 / 事件 / 状态段 / 损失」四类:特征建模的输入正是这四类。
*/
const SCOPE_TABLES: Record<OntScope, string[] | null> = {
all: null,
feature: ['equipment', 'event', 'stateSegment', 'loss'],
};
export default function OntologyView({ onExit, scope = 'all', focus }: Props) {
const { tokens } = useTheme();
/* 初值取对象清单首项,不写死 id:换本体种子时不会指向一个不存在的对象 */
const [sel, setSel] = useState<Sel>({ kind: 'object', id: objects[0].id });
const [query, setQuery] = useState('');
const [view, setView] = useState<View>({ mode: 'graph' });
/* ── 范围过滤:feature 只保留特征建模相关表,四栏与图谱都随之收敛 ── */
const scopeTables = SCOPE_TABLES[scope];
const scObjects = useMemo(
() => (scopeTables ? objects.filter(o => scopeTables.includes(o.id)) : objects), [scopeTables],
);
const scRelations = useMemo(
() => (scopeTables ? relations.filter(r => scopeTables.includes(r.from) && scopeTables.includes(r.to)) : relations),
[scopeTables],
);
const scRules = useMemo(
() => (scopeTables ? rules.filter(r => r.tables.some(t => scopeTables.includes(t))) : rules), [scopeTables],
);
const scActions = useMemo(
() => (scopeTables ? actions.filter(a => a.tables.some(t => scopeTables.includes(t))) : actions), [scopeTables],
);
/* ── 外部跳入:知识库点特征码 → 聚焦对应对象/实例 ─────────────────────── */
useEffect(() => {
if (!focus) return;
const exists = scObjects.some(o => o.id === focus.objKey);
if (!exists) return;
setSel({ kind: 'object', id: focus.objKey });
setQuery('');
if (focus.instanceId) {
setView({ mode: 'instance', table: focus.objKey, inst: focus.instanceId });
} else {
setView({ mode: 'graph' });
}
}, [focus, scObjects]);
const nodes = useMemo(
() => scObjects.map(o => ({ id: o.id, label: o.short, count: o.instances().length, color: o.color })),
[scObjects],
);
const edges = useMemo(
() => scRelations.map(r => ({ id: r.id, source: r.from, target: r.to, label: r.name })),
[scRelations],
);
const hitTotal = useMemo(() => scRules.reduce((a, r) => a + (r.blocked ? 0 : r.hits().n), 0), [scRules]);
/* ── 层级动线:进/出各一级,全部由 view 单一状态驱动 ───────────────── */
const enterExplode = (table: string) => { setSel({ kind: 'object', id: table }); setView({ mode: 'explode', table }); };
const enterInstance = (table: string, inst: string) => { setView({ mode: 'instance', table, inst }); };
const back = () => setView(v => (v.mode === 'instance' ? { mode: 'explode', table: v.table } : { mode: 'graph' }));
/* 非全屏时 ESC 逐级返回;capture + stopImmediatePropagation 抢在舞台级 ESC 之前 */
useEffect(() => {
if (view.mode === 'graph') return;
const onKey = (e: KeyboardEvent) => {
if (e.key !== 'Escape') return;
e.stopImmediatePropagation();
e.preventDefault();
back();
};
window.addEventListener('keydown', onKey, true);
return () => window.removeEventListener('keydown', onKey, true);
}, [view.mode]);
const viewTable = view.mode === 'graph' ? null : view.table;
const centerObj = viewTable ? objectById(viewTable) : undefined;
/** explode 的环=该表实例;instance 的环=该实例的字段(列名 = 值) */
const satellites: SatNode[] = useMemo(() => {
if (view.mode === 'explode' && centerObj) {
return centerObj.instances().map(it => ({ id: it.id, label: it.title, value: it.value, badge: it.badge }));
}
if (view.mode === 'instance') {
return instanceFields(view.table, view.inst).map(f => ({ id: f.name, label: f.name, value: f.value }));
}
return [];
}, [view, centerObj]);
const focusInst = useMemo(() => {
if (view.mode !== 'instance') return null;
const obj = objectById(view.table);
const inst = obj?.instances().find(i => i.id === view.inst);
return obj && inst ? { obj, inst, fields: instanceFields(view.table, view.inst) } : null;
}, [view]);
const q = query.trim().toLowerCase();
const match = (...fields: (string | undefined)[]) =>
!q || fields.some(f => (f ?? '').toLowerCase().includes(q));
const visObjects = useMemo(() => scObjects.filter(o => match(o.name, o.en, o.desc, o.source)), [q, scObjects]);
const visRelations = useMemo(() => scRelations.filter(r => match(r.name, r.key, r.desc)), [q, scRelations]);
const visRules = useMemo(() => scRules.filter(r => match(r.name, r.expr, r.desc, r.on)), [q, scRules]);
const visActions = useMemo(() => scActions.filter(a => match(a.name, a.en, a.desc, a.trigger, a.object)), [q, scActions]);
/* ── 聚焦联动:某类对象被选中/裂变时,四栏里与之相关的条目一并点亮 ──────── */
const linkedTo = (tables: string[]) => !!viewTable && tables.includes(viewTable);
const relLinked = (r: OntRelation) => !!viewTable && (r.from === viewTable || r.to === viewTable);
const isFocusTable = (id: string) => viewTable === id;
/* 选中的表卡片滚进可视区,否则联动高亮点在折叠线以下等于没点 */
const objRefs = useRef<Record<string, HTMLButtonElement | null>>({});
useEffect(() => {
if (!viewTable) return;
objRefs.current[viewTable]?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}, [viewTable]);
const detail = useMemo(() => {
if (sel.kind === 'object') return objectById(sel.id) as OntObject | undefined;
if (sel.kind === 'relation') return scRelations.find(r => r.id === sel.id);
if (sel.kind === 'rule') return scRules.find(r => r.id === sel.id);
return scActions.find(a => a.id === sel.id);
}, [sel, scRelations, scRules, scActions]);
/** 当前选中对象的实例列表(只在选中对象时计算,避免每帧重建 63/70 行) */
const instances = useMemo<OntInstance[]>(
() => (sel.kind === 'object' ? (detail as OntObject | undefined)?.instances() ?? [] : []),
[sel, detail],
);
const selectedEdgeId = sel.kind === 'relation' ? sel.id : null;
const selectedNodeId = sel.kind === 'object' ? sel.id
: sel.kind === 'relation' ? (detail as OntRelation | undefined)?.from ?? null
: null;
const colHead = (icon: React.ReactNode, label: string, n: number, total: number) => (
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto',
padding: '0 2px 7px', marginBottom: 8, borderBottom: `1px solid ${tokens.border}`,
}}>
<span style={{ display: 'flex', color: tokens.accent }}>{icon}</span>
<span style={{ fontSize: 13, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em' }}>{label}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, color: q ? tokens.warning : tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
{n}/{total}
</span>
</div>
);
const colScroll: React.CSSProperties = { flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', paddingRight: 4 };
const colBox: React.CSSProperties = {
flex: '1 1 0', minWidth: 0, display: 'flex', flexDirection: 'column',
padding: '0 10px 8px', borderRadius: 12, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
};
return (
<div style={{ flex: 1, minHeight: 0, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{/* ── 标题栏:窄窗口时换行而不是把退出按钮挤出可视区(容器 overflow:hidden 会裁掉溢出) ── */}
<div style={{
display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', flexWrap: 'wrap',
padding: '2px 2px 0',
}}>
{scope === 'feature'
? <FlaskConical size={19} style={{ color: tokens.accent, flexShrink: 0 }} />
: <Boxes size={19} style={{ color: tokens.accent, flexShrink: 0 }} />}
<span style={{ fontSize: 15.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.03em' }}>
{scope === 'feature' ? '工艺建模' : '业务本体'}
</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted, flexShrink: 0 }} title={ONTOLOGY_SCOPE_NOTE}>
快照日 {ONTOLOGY_AS_OF} · {scope === 'feature' ? '特征对象' : '对象即业务实体'} {scObjects.length} 类对象
</span>
<span style={{ flex: '1 1 24px' }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{[
{ l: scope === 'feature' ? '特征对象' : '对象', v: scObjects.length }, { l: '关系', v: scRelations.length },
{ l: '规则', v: scRules.length }, { l: '动作', v: scActions.length },
{ l: '当前命中', v: hitTotal, hot: true },
].map(s => (
<span key={s.l} style={{
fontSize: 11, fontWeight: 700, padding: '2px 9px', borderRadius: 999, whiteSpace: 'nowrap',
color: s.hot ? tokens.warning : tokens.textSub,
background: s.hot ? tokens.warningBg : tokens.accentBg,
border: `1px solid ${s.hot ? `${tokens.warning}55` : tokens.border}`,
fontVariantNumeric: 'tabular-nums',
}}>{s.l} {s.v}</span>
))}
</div>
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '1 1 190px', minWidth: 150, maxWidth: 260,
padding: '3px 9px', borderRadius: 999, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderAccent}`,
}}>
<Search size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<input
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="搜索对象 / 关系 / 规则 / 动作"
style={{
flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none',
color: tokens.text, fontSize: 12,
}}
/>
{query && (
<button onClick={() => setQuery('')} title="清空搜索" style={{ background: 'none', border: 'none', cursor: 'pointer', color: tokens.textMuted, display: 'flex' }}>
<X size={12} />
</button>
)}
</div>
<button
onClick={onExit}
title={scope === 'feature' ? '退出工艺建模 (ESC)' : '退出业务本体 (ESC)'}
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
padding: '4px 11px', borderRadius: 8, fontSize: 11.5, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<X size={13} /> 退出 ESC
</button>
</div>
{/* ── SCHEMA 徽标行:一眼看清每类对象有多少实例 ── */}
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', flex: '0 0 auto' }}>
{scObjects.map(o => {
const on = sel.kind === 'object' && sel.id === o.id;
const n = o.instances().length;
return (
<button
key={o.id}
onClick={() => setSel({ kind: 'object', id: o.id })}
title={o.desc}
style={{
display: 'flex', alignItems: 'center', gap: 6, cursor: 'pointer', whiteSpace: 'nowrap',
padding: '3px 10px', borderRadius: 999, fontSize: 11.5, fontWeight: on ? 800 : 600,
color: on ? tokens.text : tokens.textSub,
background: on ? tokens.accentBg : tokens.kpiCardBg,
border: `1px solid ${on ? o.color : tokens.border}`,
}}
>
<span style={{ width: 7, height: 7, borderRadius: 99, background: o.color, boxShadow: `0 0 7px ${o.color}88` }} />
{o.name}
<span style={{ color: o.color, fontVariantNumeric: 'tabular-nums' }}>{n}</span>
</button>
);
})}
</div>
{/* ── 上:图谱 + 详情面板 ── */}
<div style={{ flex: '1.7 1 0', minHeight: 300, display: 'flex', gap: 10 }}>
<div style={{
flex: '1 1 0', minWidth: 0, display: 'flex', flexDirection: 'column',
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<div style={{
display: 'flex', alignItems: 'center', gap: 8, flex: '0 0 auto', flexWrap: 'wrap',
padding: '7px 12px', borderBottom: `1px solid ${tokens.border}`,
}}>
<Network size={13} style={{ color: tokens.accent }} />
{view.mode === 'graph' ? (
<>
<span style={{ fontSize: 12.5, fontWeight: 800, color: tokens.text }}>{scope === 'feature' ? '特征图谱' : '本体图谱'}</span>
<span style={{ fontSize: 11, color: tokens.textMuted }}>节点={scope === 'feature' ? '特征对象' : '对象'}(圈内数字为实例数)· 连线=关系</span>
</>
) : (
<span style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, minWidth: 0, flexWrap: 'wrap' }}>
<button onClick={() => setView({ mode: 'graph' })} className="ghost-btn"
style={crumbBtn(tokens, false)}>全部表</button>
<ChevronRight size={11} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<button onClick={() => setView({ mode: 'explode', table: view.mode === 'instance' ? view.table : viewTable! })}
className="ghost-btn" style={crumbBtn(tokens, view.mode === 'explode')}>
{centerObj?.name ?? viewTable}
</button>
{view.mode === 'instance' && (
<>
<ChevronRight size={11} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<button className="ghost-btn" style={crumbBtn(tokens, true)}>{view.inst}</button>
</>
)}
</span>
)}
<span style={{ flex: 1 }} />
{/* 现场讲解用的动词提示:观众不用听说也知道下一步点哪 */}
<span style={{ fontSize: 10.5, color: tokens.accent, fontWeight: 600 }}>
{view.mode === 'graph' ? '单击聚焦 · 双击展开实例' : view.mode === 'explode' ? '点实例标签看字段 · 空白/ESC 返回' : '空白/ESC 返回上一层'}
</span>
</div>
<div style={{ flex: 1, minHeight: 0, position: 'relative' }}>
<StageHint
stageKey={scope === 'feature' ? 'feature' : 'ontology'}
steps={[
'单击对象 → 聚焦联动下方四栏',
'双击对象 → 裂变成一圈实例标签',
'点实例标签 → 下钻查看该实例字段',
'点空白 / ESC → 逐级返回',
]}
/>
<OntologyGraph
nodes={nodes} edges={edges}
selectedNodeId={selectedNodeId} selectedEdgeId={selectedEdgeId}
onNodeClick={id => setSel({ kind: 'object', id })}
onEdgeClick={id => setSel({ kind: 'relation', id })}
onNodeDoubleClick={enterExplode}
mode={view.mode}
center={view.mode === 'graph' || !centerObj ? null : {
label: view.mode === 'explode' ? centerObj.short : view.inst,
sub: view.mode === 'instance' ? focusInst?.inst.sub : undefined,
badge: view.mode === 'explode' ? undefined : focusInst?.inst.badge,
color: centerObj.color,
count: view.mode === 'explode' ? satellites.length : undefined,
}}
satellites={satellites}
onSatelliteClick={id => { if (view.mode === 'explode') enterInstance(view.table, id); }}
onBackgroundClick={back}
/>
</div>
</div>
{/* 详情面板:放宽占比与上限,属性标签与实例行不再被挤成两三行 */}
<div style={{
flex: '0 0 clamp(360px, 34%, 640px)', minWidth: 0, display: 'flex', flexDirection: 'column',
borderRadius: 12, overflow: 'hidden', background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<DetailPanel
sel={sel} detail={detail} instances={instances} focusInst={focusInst}
onPickObject={id => setSel({ kind: 'object', id })}
onBack={back}
/>
</div>
</div>
{/* ── 下:对象 / 关系 / 规则 / 动作 四栏清单 ── */}
<div style={{ flex: '1 1 0', minHeight: 168, display: 'flex', gap: 10 }}>
<div style={colBox}>
{colHead(scope === 'feature' ? <FlaskConical size={13} /> : <Boxes size={13} />,
scope === 'feature' ? '特征对象 Feature' : '对象 Object', visObjects.length, scObjects.length)}
<div style={colScroll}>
{visObjects.map(o => {
const on = sel.kind === 'object' && sel.id === o.id;
const focus = isFocusTable(o.id);
return (
<button
key={o.id}
ref={el => { objRefs.current[o.id] = el; }}
onClick={() => (view.mode === 'graph' ? setSel({ kind: 'object', id: o.id }) : enterExplode(o.id))}
style={{
...cardBase(tokens, on),
/* 聚焦标识用 inset 阴影画左侧色条:cardBase 用的是 border 简写,
再叠 borderLeft 长写会触发 React「简写+长写混用」告警,改用 boxShadow 更稳 */
boxShadow: focus ? `inset 3px 0 0 ${o.color}, inset 0 0 0 1px ${o.color}55` : undefined,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ width: 6, height: 6, borderRadius: 99, background: o.color, flexShrink: 0 }} />
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{o.name}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, fontWeight: 800, color: o.color, fontVariantNumeric: 'tabular-nums' }}>{o.instances().length}</span>
</div>
<div style={{ marginTop: 3, fontSize: 10.5, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>
{o.en} · {o.attrs.length} 属性
</div>
</button>
);
})}
{visObjects.length === 0 && <Empty tk={tokens} />}
</div>
</div>
<div style={colBox}>
{colHead(<Network size={13} />, '关系 Relation', visRelations.length, scRelations.length)}
<div style={colScroll}>
{visRelations.map(r => {
const on = sel.kind === 'relation' && sel.id === r.id;
const focus = relLinked(r);
return (
<button key={r.id} onClick={() => setSel({ kind: 'relation', id: r.id })}
style={{ ...cardBase(tokens, on), boxShadow: focus ? `inset 3px 0 0 ${tokens.info}` : undefined }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.text }}>{r.name}</span>
<span style={{ flex: 1 }} />
<Pill tone="info">{r.cardinality}</Pill>
</div>
<div style={{ marginTop: 3, display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textSub, overflow: 'hidden', whiteSpace: 'nowrap' }}>
<span style={{ color: objectById(r.from)?.color, fontWeight: 700 }}>{objectById(r.from)?.name}</span>
<span style={{ color: tokens.textMuted }}>→</span>
<span style={{ color: objectById(r.to)?.color, fontWeight: 700 }}>{objectById(r.to)?.name}</span>
<span style={{ flex: 1 }} />
<span style={{ color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{r.count()}</span>
</div>
</button>
);
})}
{visRelations.length === 0 && <Empty tk={tokens} />}
</div>
</div>
<div style={colBox}>
{colHead(<ShieldAlert size={13} />, '规则 Rule', visRules.length, scRules.length)}
<div style={colScroll}>
{visRules.map(r => {
const on = sel.kind === 'rule' && sel.id === r.id;
const h = r.hits();
const focus = linkedTo(r.tables);
return (
<button
key={r.id} onClick={() => setSel({ kind: 'rule', id: r.id })}
style={{
...cardBase(tokens, on), opacity: r.blocked ? 0.62 : 1,
boxShadow: focus ? `inset 3px 0 0 ${toneColor(tokens, sevTone(r.severity)).c}` : undefined,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
{r.blocked
? <CircleSlash2 size={11} style={{ color: tokens.textMuted, flexShrink: 0 }} />
: <AlertTriangle size={11} style={{ color: toneColor(tokens, sevTone(r.severity)).c, flexShrink: 0 }} />}
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.name}</span>
<span style={{ flex: 1 }} />
{r.blocked
? <Pill tone="warning">数据缺口</Pill>
: <span style={{ fontSize: 11.5, fontWeight: 800, color: h.n ? toneColor(tokens, sevTone(r.severity)).c : tokens.success, fontVariantNumeric: 'tabular-nums' }}>{h.n}</span>}
</div>
<div style={{ marginTop: 3, fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{r.on}{!r.blocked && ` · ${h.unit}`}
</div>
</button>
);
})}
{visRules.length === 0 && <Empty tk={tokens} />}
</div>
</div>
<div style={colBox}>
{colHead(<Zap size={13} />, '动作 Action', visActions.length, scActions.length)}
<div style={colScroll}>
{visActions.map(a => {
const on = sel.kind === 'action' && sel.id === a.id;
const n = a.targets?.().length ?? 0;
const focus = linkedTo(a.tables);
return (
<button key={a.id} onClick={() => setSel({ kind: 'action', id: a.id })}
style={{ ...cardBase(tokens, on), boxShadow: focus ? `inset 3px 0 0 ${tokens.accent}` : undefined }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.name}</span>
<span style={{ flex: 1 }} />
<Pill tone={ACTION_TYPE[a.type].tone}>{ACTION_TYPE[a.type].label}</Pill>
{!a.targets && <Pill tone="warning">不可执行</Pill>}
</div>
<div style={{ marginTop: 3, display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', whiteSpace: 'nowrap' }}>
<span style={{ fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>{a.en}</span>
<span style={{ flex: 1 }} />
<span>{a.object}</span>
{a.targets && <span style={{ color: n ? tokens.accent : tokens.textMuted, fontWeight: 700 }}>· {n}</span>}
</div>
</button>
);
})}
{visActions.length === 0 && <Empty tk={tokens} />}
</div>
</div>
</div>
{/* ── 页脚:范围与缺口常驻披露(不藏 tooltip)──
主数据全量 vs 事实层只取锚点三日,三处未落地一律 blocked+gap 标灰、不造实例充数。
文案从 ontologyOee 的 ONTOLOGY_SCOPE_NOTE 取,数字现算,页面不另写一份。 */}
<div style={{
flex: '0 0 auto', padding: '6px 10px', borderRadius: 10,
fontSize: 10.5, lineHeight: 1.55, color: tokens.textMuted,
background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`,
}}>
{ONTOLOGY_SCOPE_NOTE}
<span style={{ marginLeft: 6 }}>
数据源:<span style={{ fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>src/data/ontologyOee.ts</span>
(数值唯一来源为 L3 lib/oeeService)· 校验:
<span style={{ fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>scripts/verify-oee-ontology.ts</span>
</span>
</div>
</div>
);
}
const Empty = ({ tk }: { tk: ThemeTokens }) => (
<div style={{ padding: '22px 0', textAlign: 'center', fontSize: 12, color: tk.textMuted }}>无匹配条目</div>
);
/* ── 右侧详情面板 ─────────────────────────────────────────────────────── */
function DetailPanel({
sel, detail, instances, focusInst, onPickObject, onBack,
}: {
sel: Sel;
detail: OntObject | OntRelation | OntRule | OntAction | undefined;
instances: OntInstance[];
/** 图谱下钻到某条实例时的上下文:优先展示该实例的字段 */
focusInst: { obj: OntObject; inst: OntInstance; fields: { name: string; value: string }[] } | null;
onPickObject: (id: string) => void;
onBack: () => void;
}) {
const { tokens } = useTheme();
/* 原「知识引用」区块已移除:它依赖品质知识库(data/knowledge + kbLinks + ROLE_COLOR),
与 OEE 本体无关,且会把整套 QAP 数据拖进包。OEE 的知识库页在 W3-C 另建。 */
const label: React.CSSProperties = { fontSize: 10.5, fontWeight: 700, color: tokens.textMuted, letterSpacing: '0.06em' };
const kv: React.CSSProperties = { display: 'flex', flexDirection: 'column', gap: 3, marginBottom: 9 };
const head = (title: string, en: string | undefined, tone: Tone | null, tag: string) => (
<div style={{ padding: '10px 12px 9px', borderBottom: `1px solid ${tokens.border}`, flex: '0 0 auto' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
<span style={{ fontSize: 10.5, fontWeight: 800, color: tokens.accent, padding: '1px 7px', borderRadius: 999, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}` }}>{tag}</span>
<span style={{ fontSize: 14.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.02em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{title}</span>
<span style={{ flex: 1 }} />
{tone && <Pill tone={tone}>{tone === 'danger' ? '硬约束' : tone === 'warning' ? '预警' : '提示'}</Pill>}
</div>
{en && <div style={{ marginTop: 4, fontSize: 10.5, color: tokens.textMuted, fontFamily: 'ui-monospace, SFMono-Regular, monospace' }}>{en}</div>}
</div>
);
const body: React.CSSProperties = { flex: 1, minHeight: 0, overflowY: 'auto', overflowX: 'hidden', padding: '10px 12px' };
/* ── 实例:图谱下钻到某条真实单据,右栏摊开它的字段(列名 = 值) ── */
if (focusInst) {
const { obj, inst, fields } = focusInst;
return (
<>
{head(inst.title, `${obj.name} · ${obj.en}`, null, '实例')}
<div style={body}>
<button
onClick={onBack} className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 5, marginBottom: 9, cursor: 'pointer',
padding: '3px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>← 返回 {obj.short}</button>
{inst.sub && (
<div style={{ ...kv, marginBottom: 8 }}>
<span style={label}>概要</span>
<span style={{ fontSize: 12, color: tokens.textSub }}>{inst.sub}</span>
</div>
)}
{inst.meta && (
<div style={{ ...kv, marginBottom: 8 }}>
<span style={label}>上下文</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted, lineHeight: 1.6 }}>{inst.meta}</span>
</div>
)}
<div style={kv}>
<span style={label}>字段 {fields.length} 项(列名 = 值)</span>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
{fields.map(f => (
<div key={f.name} style={{
display: 'flex', alignItems: 'baseline', gap: 8,
padding: '4px 8px', borderRadius: 7, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<span style={{
fontSize: 10.5, fontWeight: 700, color: tokens.textMuted, flexShrink: 0,
fontFamily: 'ui-monospace, SFMono-Regular, monospace', minWidth: 96,
}}>{f.name}</span>
<span style={{ fontSize: 11.5, color: f.value === '—' ? tokens.textMuted : tokens.text, lineHeight: 1.5 }}>{f.value}</span>
</div>
))}
</div>
</div>
</div>
</>
);
}
if (!detail) {
return (
<div style={{ flex: 1, display: 'grid', placeItems: 'center', color: tokens.textMuted, fontSize: 12.5 }}>
在图谱或下方清单里选择一个条目
</div>
);
}
/* ── 对象:属性定义 + 实例下钻 ── */
if (sel.kind === 'object') {
const o = detail as OntObject;
return (
<>
{head(o.name, `${o.en} · ${instances.length} 实例`, null, '对象')}
<div style={body}>
<div style={kv}>
<span style={label}>业务含义</span>
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{o.desc}</span>
</div>
<div style={kv}>
<span style={label}>数据来源</span>
<span style={{ fontSize: 11.5, color: tokens.textMuted }}>{o.source}</span>
</div>
<div style={{ ...kv, marginBottom: 4 }}>
<span style={label}>属性 {o.attrs.length} 项</span>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
{o.attrs.map(a => (
<span
key={a.en}
title={`${a.name}:${a.type}${a.required ? ' · 必填' : ' · 可空'}${a.note ? ` — ${a.note}` : ''}`}
style={{
fontSize: 10.5, padding: '2px 7px', borderRadius: 6, cursor: 'default',
fontFamily: 'ui-monospace, SFMono-Regular, monospace',
color: a.required ? tokens.textSub : tokens.textMuted,
background: a.required ? tokens.kpiCardBg : 'transparent',
border: `1px dashed ${a.required ? tokens.borderAccent : tokens.border}`,
}}
>
{a.en}{a.required ? '' : '?'}
</span>
))}
</div>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>虚线=该列在本批数据里可空;悬停看中文列名与口径说明</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, margin: '10px 0 7px', paddingTop: 8, borderTop: `1px solid ${tokens.border}` }}>
<span style={label}>实例下钻</span>
<span style={{ fontSize: 11, color: tokens.textMuted }}>{instances.length} 条</span>
</div>
{instances.map((it, i) => (
<InstanceRow key={`${it.id}-${i}`} it={it} />
))}
</div>
</>
);
}
/* ── 关系:两端 + 基数 + 连接键 ── */
if (sel.kind === 'relation') {
const r = detail as OntRelation;
const from = objectById(r.from), to = objectById(r.to);
return (
<>
{head(`关系 · ${r.name}`, r.id, null, '关系')}
<div style={body}>
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8, marginBottom: 10 }}>
{[from, to].map((o, i) => (
<div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 2 }}>
<button
onClick={() => o && onPickObject(o.id)}
title="查看该对象"
style={{
textAlign: 'left', cursor: 'pointer', padding: '7px 9px', borderRadius: 9,
background: tokens.panelBgAlt, border: `1px solid ${o?.color ?? tokens.border}66`,
}}
>
<span style={{ fontSize: 10, color: tokens.textMuted }}>{i ? '目标' : '起点'}</span>
<div style={{ fontSize: 13, fontWeight: 700, color: o?.color }}>{o?.name ?? r[i ? 'to' : 'from']}</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{o ? `${o.instances().length} 实例` : ''}</div>
</button>
{i === 0 && (
<span style={{ textAlign: 'center', fontSize: 10.5, color: tokens.accent, fontWeight: 800, marginTop: -4 }}>{r.cardinality}</span>
)}
</div>
))}
</div>
<div style={kv}>
<span style={label}>连接键</span>
<span style={{ fontSize: 11.5, fontFamily: 'ui-monospace, SFMono-Regular, monospace', color: tokens.textSub }}>{r.key}</span>
</div>
<div style={kv}>
<span style={label}>当前实例数</span>
<span style={{ fontSize: 20, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{r.count()}</span>
</div>
<div style={kv}>
<span style={label}>口径说明</span>
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{r.desc}</span>
</div>
</div>
</>
);
}
/* ── 规则:表达式 + 实时命中 + 命中订单 ── */
const isRule = sel.kind === 'rule';
const rule = detail as OntRule;
const action = detail as OntAction;
const targets = isRule ? rule.hits() : { n: action.targets?.().length ?? 0, unit: '个目标对象', targets: action.targets?.() ?? [] };
const list = isRule ? targets.targets : action.targets?.() ?? [];
return (
<>
{head(
isRule ? rule.name : action.name,
isRule ? `${rule.on} · ${rule.id}` : `${action.en} · ${action.object}`,
isRule ? sevTone(rule.severity) : null,
isRule ? '规则' : '动作',
)}
<div style={body}>
{isRule ? (
<>
<div style={{
...kv, padding: '7px 9px', borderRadius: 8, background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`,
}}>
<span style={label}>判定表达式</span>
<span style={{ fontSize: 11.5, lineHeight: 1.6, fontFamily: 'ui-monospace, SFMono-Regular, monospace', color: tokens.text }}>
{rule.expr}
</span>
</div>
<div style={kv}>
<span style={label}>约束强度</span>
<span style={{ fontSize: 12, color: tokens.textSub }}>
{rule.severity === 'error' ? '硬约束:违反即质量风险外溢,必须处置' : rule.severity === 'warning' ? '预警:需要责任角色确认后处置' : '提示:结构性风险画像'}
</span>
</div>
</>
) : (
<>
<div style={kv}>
<span style={label}>触发条件</span>
<span style={{ fontSize: 12, color: tokens.textSub }}>{action.trigger}</span>
</div>
<div style={kv}>
<span style={label}>作用对象 / 类型</span>
<span style={{ fontSize: 12, color: tokens.textSub }}>{action.object} · {ACTION_TYPE[action.type].label}</span>
</div>
</>
)}
<div style={kv}>
<span style={label}>说明</span>
<span style={{ fontSize: 12, lineHeight: 1.6, color: tokens.textSub }}>{isRule ? rule.desc : action.desc}</span>
</div>
<div style={{
display: 'flex', alignItems: 'baseline', gap: 8, margin: '10px 0 8px', paddingTop: 9,
borderTop: `1px solid ${tokens.border}`,
}}>
<span style={{ fontSize: 22, fontWeight: 800, fontVariantNumeric: 'tabular-nums', color: isRule && rule.blocked ? tokens.textMuted : targets.n ? toneColor(tokens, isRule ? sevTone(rule.severity) : 'info').c : tokens.success }}>
{isRule && rule.blocked ? '—' : targets.n}
</span>
<span style={{ fontSize: 11.5, color: tokens.textSub }}>
{isRule && rule.blocked ? '数据缺口,规则无法执行' : targets.unit}
</span>
<span style={{ flex: 1 }} />
{isRule && !rule.blocked && targets.n === 0 && <Pill tone="success">本批无违反</Pill>}
</div>
{isRule && rule.blocked && (
<div style={{
display: 'flex', alignItems: 'flex-start', gap: 6, padding: '8px 10px', borderRadius: 9,
background: tokens.warningBg, border: `1px solid ${tokens.warning}44`,
}}>
<Lock size={13} style={{ color: tokens.warning, marginTop: 1, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, lineHeight: 1.6, color: tokens.textSub }}>{rule.gap}</span>
</div>
)}
{list.length > 0 && (
<>
<div style={{ ...label, margin: '11px 0 6px' }}>命中清单 {list.length} 项</div>
{list.map((code, i) => (
<div
key={`${code}-${i}`}
style={{
display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5, padding: '6px 9px',
borderRadius: 8, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}
>
<span style={{ width: 5, height: 16, borderRadius: 3, background: toneColor(tokens, isRule ? sevTone(rule.severity) : 'info').c, flexShrink: 0, opacity: 0.7 }} />
<span style={{ fontSize: 11.5, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{code}
</span>
</div>
))}
</>
)}
</div>
</>
);
}
/** 实例行:一行数据表记录,左=主键与口径,右=该行最该看的那个值 */
function InstanceRow({ it }: { it: OntInstance }) {
const { tokens } = useTheme();
const tone = toneColor(tokens, it.tone ?? 'info');
return (
<div
style={{
display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5, padding: '6px 9px', borderRadius: 8,
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`,
}}
>
<span style={{ width: 5, height: 22, borderRadius: 3, background: tone.c, flexShrink: 0, opacity: 0.75 }} />
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 12, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.title}</span>
{it.badge && <Pill tone={it.tone ?? 'info'}>{it.badge}</Pill>}
</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 2, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.sub}</div>
</div>
<div style={{ textAlign: 'right', flexShrink: 0, maxWidth: '46%' }}>
{it.value && (
<div style={{ fontSize: 12, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.value}</div>
)}
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.meta}</div>
</div>
</div>
);
}
@@ -0,0 +1,235 @@
import { CircleDollarSign, FlaskConical, ShoppingCart, Target, Factory, Truck } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { useText } from '../../i18n/useText';
import { PanelBody } from '../layout/PanelShell';
import type { MetricNode } from '../../data/sqlite';
import { alertColor, fmt } from '../../lib/metric';
import { achieveAt, levelAt, periodLabel, valueAt } from '../../lib/time';
import { STAGES, flowStats, type FlowIcon } from '../../lib/process';
/**
* 流程效能看板(研产供销六段价值链 · 过程指标层)。
*
* 与指标树的分工写在标题下那句话里:指标树是**结果**(钱和率的达成),
* 这里是**过程**(一批商机/项目/工单在链上每段停留多久、流过多少、返工多少)。
* 每段下方的指标片是真实 metric_node,点开即联动中央看板;
* 过程量则是可复现的模拟值,随底部时间轴游标一起演变。
*/
interface Props {
byCode: Map<string, MetricNode>;
selected: string;
onSelect: (code: string) => void;
period: number;
}
const ICONS: Record<FlowIcon, typeof Target> = {
target: Target, flask: FlaskConical, cart: ShoppingCart, factory: Factory, truck: Truck, cash: CircleDollarSign,
};
export default function ProcessFlowPanel({ byCode, selected, onSelect, period }: Props) {
const { tokens } = useTheme();
const { t } = useText();
const { stats, summary } = flowStats(period);
const bottleneck = STAGES.findIndex(s => s.key === summary.bottleneckKey);
const constraint = STAGES.findIndex(s => s.key === summary.constraintKey);
/* 在制品堆得最高的一段:比“总和”更能指出哪里在堵 */
const wipTop = stats.reduce((mi, x, i) => (x.wip > stats[mi].wip ? i : mi), 0);
const tile = (label: string, value: string, sub: string | null, color: string) => (
<div style={{
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 9, padding: '5px 8px', minWidth: 0,
}}>
<div style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{label}</div>
<div style={{
fontSize: 16, fontWeight: 800, color, lineHeight: 1.25, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}}>{value}</div>
{sub && <div style={{ fontSize: 9.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{sub}</div>}
</div>
);
/** 过程量小格:标签 + 值 + 目标/环比提示 */
const stat = (label: string, value: string, tone: string) => (
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4, minWidth: 0 }}>
<span style={{ fontSize: 10, color: tokens.textMuted, flexShrink: 0 }}>{label}</span>
<span style={{
fontSize: 12, fontWeight: 700, color: tone, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap',
}}>{value}</span>
</div>
);
return (
<PanelBody>
{/* 口径提示:过程 vs 结果 */}
<div style={{
fontSize: 11, lineHeight: 1.55, color: tokens.textMuted, marginBottom: 8,
padding: '6px 9px', borderRadius: 8, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
{t.flow.hint}
</div>
{/* 全链汇总 */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6, marginBottom: 4 }}>
{tile(t.flow.cycle, `${fmt(summary.cycle)}${t.flow.unitDay}`, `${t.flow.base} ${fmt(summary.cycleBase)}${t.flow.unitDay}`, tokens.text)}
{tile(t.flow.e2e, `${fmt(summary.e2e)}%`, `${t.flow.base} ${fmt(summary.e2eBase)}%`, summary.e2e >= 55 ? tokens.success : summary.e2e >= 40 ? tokens.warning : tokens.danger)}
{tile(t.flow.throughput, summary.throughput.toLocaleString(), `${t.flow.constraint} · ${STAGES[constraint].zh}`, tokens.info)}
{tile(t.flow.wip, summary.wip.toLocaleString(), `max · ${STAGES[wipTop].zh}`, tokens.textSub)}
</div>
<div
title={t.flow.bottleneckTip}
style={{
display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, marginBottom: 10,
padding: '4px 8px', borderRadius: 8,
background: `${alertColor(stats[bottleneck].status, tokens)}14`,
border: `1px solid ${alertColor(stats[bottleneck].status, tokens)}3a`,
}}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: alertColor(stats[bottleneck].status, tokens), flexShrink: 0 }} />
<span style={{ color: tokens.textSub, flexShrink: 0 }}>{t.flow.bottleneck}</span>
<span style={{ color: tokens.text, fontWeight: 700, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{STAGES[bottleneck].zh}
</span>
<span style={{ flex: 1 }} />
<span style={{ color: alertColor(stats[bottleneck].status, tokens), fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>
{fmt(stats[bottleneck].score)}%
</span>
</div>
{/* 六段流程 */}
{STAGES.map((s, i) => {
const st = stats[i];
const c = alertColor(st.status, tokens);
const Icon = ICONS[s.icon];
const active = s.codes.includes(selected);
const dwellTone = st.dwell <= st.dwellTarget ? tokens.success : st.dwell <= st.dwellTarget * 1.12 ? tokens.warning : tokens.danger;
const fpqcTone = st.fpqc >= st.fpqcTarget ? tokens.success : st.fpqc >= st.fpqcTarget - 4 ? tokens.warning : tokens.danger;
const reworkTone = st.rework <= st.reworkTarget ? tokens.success : st.rework <= st.reworkTarget * 1.15 ? tokens.warning : tokens.danger;
const trend = st.dwellDelta === null ? t.flow.flat
: st.dwellDelta < -0.05 ? `${t.flow.faster} ${fmt(Math.abs(st.dwellDelta))}${t.flow.unitDay}`
: st.dwellDelta > 0.05 ? `${t.flow.slower} ${fmt(st.dwellDelta)}${t.flow.unitDay}`
: t.flow.flat;
return (
<div key={s.key}>
{/* 段间连线:在制品沿链流动 */}
{i > 0 && (
<div style={{ display: 'flex', gap: 8 }}>
<div style={{ width: 26, flexShrink: 0, position: 'relative', height: 26 }}>
<svg width={26} height={26} style={{ position: 'absolute', inset: 0, overflow: 'visible' }}>
<line x1={13} y1={-2} x2={13} y2={28} stroke={tokens.border} strokeWidth={1.4} />
<line
className="dash-flow" x1={13} y1={-2} x2={13} y2={28}
stroke={alertColor(stats[i - 1].status, tokens)} strokeWidth={1.6} strokeDasharray="3 5" strokeLinecap="round"
/>
<path d="M 9.5,23 L 13,28 L 16.5,23" fill="none" stroke={tokens.border} strokeWidth={1.4} strokeLinecap="round" />
</svg>
<span style={{
position: 'absolute', left: 30, top: 4, fontSize: 10, whiteSpace: 'nowrap', color: tokens.textMuted,
fontVariantNumeric: 'tabular-nums',
}}>
{t.flow.wip} {stats[i - 1].wip.toLocaleString()}
</span>
</div>
<div style={{ flex: 1, minWidth: 0 }} />
</div>
)}
<div style={{ display: 'flex', gap: 8 }}>
{/* 轨道节点 */}
<div style={{ width: 26, flexShrink: 0, display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
<span style={{
display: 'grid', placeItems: 'center', width: 26, height: 26, borderRadius: 9, flexShrink: 0,
background: `${c}1f`, border: `1px solid ${c}66`, color: c,
boxShadow: active ? `0 0 10px ${c}66` : 'none',
}}>
<Icon size={14} />
</span>
</div>
{/* 段卡 */}
<div style={{
flex: 1, minWidth: 0, marginBottom: 2, borderRadius: 10, padding: '7px 9px',
background: tokens.panelBgAlt,
border: `1px solid ${active ? c : tokens.border}`,
boxShadow: active ? `0 0 0 1px ${c}44, 0 4px 14px ${c}22` : 'none',
transition: 'border-color 0.2s ease, box-shadow 0.2s ease',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span className={st.status === 'red' ? 'net-breathe' : undefined} style={{
width: 7, height: 7, borderRadius: '50%', flexShrink: 0, background: c, boxShadow: `0 0 6px ${c}`,
}} />
<span style={{ fontSize: 13.5, fontWeight: 800, color: tokens.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{s.zh}
</span>
<span style={{
fontSize: 11.5, fontWeight: 800, color: c, flexShrink: 0, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace',
}}>{fmt(st.score)}%</span>
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, marginBottom: 5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{s.roleZh} · {trend}
</div>
{/* 段达成条 */}
<div style={{ height: 3, borderRadius: 99, background: tokens.border, overflow: 'hidden', marginBottom: 6 }}>
<span style={{
display: 'block', height: '100%', width: `${Math.min(100, st.score)}%`, background: c,
transition: 'width 0.4s ease',
}} />
</div>
{/* 过程四量 */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 8px', marginBottom: 6 }}>
{stat(t.flow.dwell, `${fmt(st.dwell)}${t.flow.unitDay}`, dwellTone)}
{stat(t.flow.flow, `${st.flow.toLocaleString()}`, tokens.textSub)}
{stat(t.flow.fpqc, `${fmt(st.fpqc)}%`, fpqcTone)}
{stat(t.flow.rework, `${st.rework}`, reworkTone)}
</div>
{/* 关联指标片:真实 metric_node,点开联动中央看板 */}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
{s.codes.map(cd => {
const n = byCode.get(cd);
if (!n) return null;
const nc = alertColor(levelAt(n, period), tokens);
const on = cd === selected;
const val = valueAt(n, period);
return (
<button
key={cd} onClick={() => onSelect(cd)} className="ghost-btn"
title={`${t.flow.linked} ${n.code} · ${n.name_zh} · ${t.flow.clickTip}`}
style={{
display: 'flex', alignItems: 'center', gap: 4, maxWidth: '100%', cursor: 'pointer',
padding: '2px 6px', borderRadius: 7, fontSize: 10.5,
background: on ? `${nc}22` : tokens.cardBg,
border: `1px solid ${on ? nc : tokens.border}`,
color: tokens.textSub,
}}
>
<span style={{ width: 5, height: 5, borderRadius: '50%', background: nc, flexShrink: 0 }} />
<span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: on ? tokens.text : undefined }}>
{n.name_zh}
</span>
<span style={{ color: nc, fontWeight: 700, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>
{fmt(val)}{n.unit}
</span>
<span style={{ color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', flexShrink: 0 }}>
{fmt(achieveAt(n, period), 0)}%
</span>
</button>
);
})}
</div>
</div>
</div>
</div>
);
})}
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.6, padding: '8px 2px 12px' }}>
{periodLabel(period)} · {t.flow.wipTip}
</div>
</PanelBody>
);
}
@@ -0,0 +1,204 @@
import { useMemo, useState } from 'react';
import { Database, X } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { dekDays } from '../../lib/oeeService';
import { DEVICES } from '../../data/oee/devices';
/**
* 数据集总览(demo 沙箱):静态展示本工程内置的三类 demo 资产——
* 3 个业务日种子、17 台台账设备、浏览器内 SQLite 三张指标表。
* 不连接后端,也不发起任何 fetch / 轮询。
*/
const REGIONS = [null, 'SRF', 'FT', 'ASLT'] as const;
const fmtNum = (n: number) => n.toLocaleString('zh-CN');
const tile = (tokens: ThemeTokens, label: string, value: string, tone?: string) => (
<div key={label} style={{
flex: '1 1 120px', minWidth: 108, padding: '7px 11px', borderRadius: 10,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<div style={{ fontSize: 10.5, color: tokens.textMuted, fontWeight: 700, letterSpacing: '0.04em' }}>{label}</div>
<div style={{
fontSize: 17, fontWeight: 800, marginTop: 2, color: tone ?? tokens.text,
fontVariantNumeric: 'tabular-nums', lineHeight: 1.2,
}}>{value}</div>
</div>
);
interface Props {
onExit: () => void;
focus?: { id: string; n: number } | null;
}
/** 浏览器内存 SQLite 的三张指标表(与 data/sqlite.ts 建表一致)。 */
const SQLITE_TABLES = [
{ table: 'metric_node', name: '指标节点', detail: '17 维指标树节点(含数值/目标/权重/缺口)', use: '指标树、智能体取数' },
{ table: 'metric_link', name: '指标关系', detail: '节点间因果/归属关系边', use: '因果网络、下钻' },
{ table: 'metric_trend', name: '指标趋势', detail: '3 个业务日的实际/目标趋势', use: '趋势图、同比对比' },
];
export default function QapDataView({ onExit }: Props) {
const { tokens } = useTheme();
const [region, setRegion] = useState<string | null>(null);
const days = dekDays();
const devices = useMemo(() => DEVICES.filter((d) => !region || d.region === region), [region]);
const cell: React.CSSProperties = {
padding: '5px 10px', fontSize: 12, whiteSpace: 'nowrap',
borderBottom: `1px solid ${tokens.borderSub}`, color: tokens.textSub,
fontVariantNumeric: 'tabular-nums',
};
const head: React.CSSProperties = {
...cell, background: tokens.tableHeaderBg, color: tokens.text, fontWeight: 800, fontSize: 11.5,
borderBottom: `1px solid ${tokens.borderAccent}`,
};
const panel = (title: string, right: string, children: React.ReactNode) => (
<div style={{
flex: '1 1 420px', minWidth: 0, display: 'flex', flexDirection: 'column',
borderRadius: 12, background: tokens.cardBg, border: `1px solid ${tokens.border}`, padding: '10px 12px',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}>
<span style={{ fontSize: 13.5, fontWeight: 800, color: tokens.text }}>{title}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{right}</span>
</div>
<div style={{ flex: 1, minHeight: 0, overflow: 'auto', borderRadius: 10, border: `1px solid ${tokens.border}` }}>
{children}
</div>
</div>
);
return (
<div style={{ flex: 1, minHeight: 0, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 10 }}>
{/* 标题栏 */}
<div style={{
display: 'flex', alignItems: 'center', gap: 10, flex: '0 0 auto', flexWrap: 'wrap', padding: '2px 2px 0',
}}>
<Database size={19} style={{ color: tokens.accent, flexShrink: 0 }} />
<span style={{ fontSize: 15.5, fontWeight: 800, color: tokens.text, letterSpacing: '0.03em' }}>数据集总览</span>
<span style={{
fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 999,
color: tokens.info, background: `${tokens.info}18`, border: `1px solid ${tokens.info}44`,
}}>demo 沙箱 · 数据来自内置合成种子,不连接后端</span>
<span style={{ flex: '1 1 24px' }} />
<div style={{ display: 'flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }}>
{REGIONS.map(r => {
const on = region === r;
return (
<button
key={r ?? 'ALL'}
onClick={() => setRegion(r)}
style={{
cursor: 'pointer', padding: '3px 11px', borderRadius: 999, fontSize: 11.5,
fontWeight: on ? 800 : 600, whiteSpace: 'nowrap',
color: on ? tokens.accent : tokens.textSub,
background: on ? tokens.accentBg : tokens.kpiCardBg,
border: `1px solid ${on ? tokens.accent : tokens.border}`,
}}
>{r ?? '全部区域'}</button>
);
})}
</div>
<button
onClick={onExit}
title="退出数据集总览 (ESC)"
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
padding: '4px 11px', borderRadius: 8, fontSize: 11.5, fontWeight: 700,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
<X size={13} /> 退出 ESC
</button>
</div>
{/* 指标磁贴 */}
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', flex: '0 0 auto' }}>
{tile(tokens, '业务日种子', String(days.length), tokens.text)}
{tile(tokens, '台账设备', `${devices.length} 台`)}
{tile(tokens, 'SQLite 指标表', `${SQLITE_TABLES.length} 张`)}
{tile(tokens, '数据来源', '内置合成', tokens.warning)}
{tile(tokens, '后端连接', '无', tokens.textMuted)}
</div>
<div style={{ flex: 1, minHeight: 0, display: 'flex', gap: 10, flexWrap: 'wrap', overflow: 'auto' }}>
{/* 业务日种子 */}
{panel('业务日种子', `${days.length} 个业务日`, (
<table style={{ borderCollapse: 'collapse', width: 'max-content', minWidth: '100%' }}>
<thead><tr>
<th style={{ ...head, textAlign: 'left' }}>业务日</th>
<th style={{ ...head, textAlign: 'left' }}>设备</th>
<th style={{ ...head, textAlign: 'left' }}>口径版本</th>
<th style={{ ...head, textAlign: 'right' }}>日志行</th>
<th style={{ ...head, textAlign: 'right' }}>事件数</th>
</tr></thead>
<tbody>
{days.map((d) => (
<tr key={d.bizDate}>
<td style={{ ...cell, color: tokens.text, fontWeight: 700 }}>{d.bizDate}</td>
<td style={cell}>{d.device.id}</td>
<td style={cell}>{d.caliberVersion}</td>
<td style={{ ...cell, textAlign: 'right' }}>{fmtNum(d.seed.lines.length)}</td>
<td style={{ ...cell, textAlign: 'right' }}>{fmtNum(d.normalize.events.length)}</td>
</tr>
))}
</tbody>
</table>
))}
{/* 台账设备 */}
{panel('台账设备', `${devices.length} 台`, (
<table style={{ borderCollapse: 'collapse', width: 'max-content', minWidth: '100%' }}>
<thead><tr>
<th style={{ ...head, textAlign: 'left' }}>设备</th>
<th style={{ ...head, textAlign: 'left' }}>名称</th>
<th style={{ ...head, textAlign: 'left' }}>区域</th>
<th style={{ ...head, textAlign: 'left' }}>线体 · 工站</th>
<th style={{ ...head, textAlign: 'left' }}>计 OEE</th>
</tr></thead>
<tbody>
{devices.map((d) => (
<tr key={d.id}>
<td style={{ ...cell, color: tokens.text, fontWeight: 700 }}>{d.id}</td>
<td style={cell}>{d.name}</td>
<td style={cell}>{d.region}</td>
<td style={cell}>{d.lineId} · {d.station}</td>
<td style={cell}>{d.countsForOee ? '是' : '否(中间缓存)'}</td>
</tr>
))}
</tbody>
</table>
))}
{/* SQLite 指标表 */}
{panel('浏览器内 SQLite 指标表', `${SQLITE_TABLES.length} 张`, (
<table style={{ borderCollapse: 'collapse', width: 'max-content', minWidth: '100%' }}>
<thead><tr>
<th style={{ ...head, textAlign: 'left' }}>表</th>
<th style={{ ...head, textAlign: 'left' }}>名称</th>
<th style={{ ...head, textAlign: 'left' }}>内容</th>
<th style={{ ...head, textAlign: 'left' }}>用途</th>
</tr></thead>
<tbody>
{SQLITE_TABLES.map((t) => (
<tr key={t.table}>
<td style={{ ...cell, color: tokens.text, fontWeight: 700, fontFamily: 'monospace' }}>{t.table}</td>
<td style={cell}>{t.name}</td>
<td style={cell}>{t.detail}</td>
<td style={cell}>{t.use}</td>
</tr>
))}
</tbody>
</table>
))}
</div>
<div style={{ flex: '0 0 auto', fontSize: 10.5, color: tokens.textMuted, lineHeight: 1.5 }}>
只读静态展示 · demo 沙箱数据全部来自内置合成种子,不连接后端 · SQLite 指标表在浏览器内存中初始化
</div>
</div>
);
}
@@ -0,0 +1,298 @@
import { useState } from 'react';
import { ArrowDownRight, Cog, Ruler, ShieldCheck, Wrench } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { useText } from '../../i18n/useText';
import { PanelBody } from '../layout/PanelShell';
import { alertColor, fmt } from '../../lib/metric';
import { periodLabel } from '../../lib/time';
import { ROLES, qualityStats, type QIcon } from '../../lib/qualityFlow';
/**
* 质量预防流程看板(PE → IE → QE → ME 四角色 · 过程指标层)。
*
* 版式照抄三菱电机那版「流程效能」:瓶颈横幅 → 自上而下的角色轨道卡,
* 段与段之间用虚线箭头连起来,线上标在制品堆了多少。
* 原本顶部那四个汇总砖(闭环周期 / 一次通过 / KPI 达标 / 在制品)已提到整页抬头
* (见 MecHeader 的核心指标带,同一个 qualityStats 源),这里不再重复,直接进瓶颈与角色段。
* 与结果看板的分工写在标题下那句 hint 里:这里看**过程**(一张风险点检单在四个质量口
* 各停多久、一次通过多少、退回多少),良率/客诉/质量成本那些**结果**仍归指标树。
*
* 每张卡下方是该企业质量职责表拆出来的 4 项质量 KPI(共 16 项):
* 基线取「当前实施情况」那一列,目标取改善方向,数字为确定性模拟、随底部时间轴演变。
*/
interface Props {
/** 全局时间游标:与中央看板同一时点读数 */
period: number;
expanded: boolean;
}
const ICONS: Record<QIcon, typeof Wrench> = {
wrench: Wrench, ruler: Ruler, shield: ShieldCheck, cog: Cog,
};
/** 左侧轨道节点(角色图标)的列宽;段间连线已独立居中,不再占用这一列 */
const RAIL = 26;
/**
* 段间连线的高度。留出一截能看见单据往下流的路即可;
* 104px 显得拖沓,收到 52px,让四段卡更紧凑。
*/
const LINK = 52;
export default function QualityFlowPanel({ period, expanded }: Props) {
const { tokens } = useTheme();
const { t } = useText();
/** 展开查看「现状」原文的角色段;一次只开一段,避免左栏被文字淹没 */
const [open, setOpen] = useState<string | null>(null);
const { stats, summary } = qualityStats(period);
const bottleneck = ROLES.findIndex(r => r.key === summary.bottleneckKey);
const constraint = ROLES.findIndex(r => r.key === summary.constraintKey);
/* 带下标的四段:stats[] 与段间连线都要按原顺序取数 */
const segs = ROLES.map((r, i) => ({ r, i }));
/** 过程量小格:标签 + 值 + 目标提示 */
const stat = (label: string, value: string, tone: string) => (
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4, minWidth: 0 }}>
<span style={{ fontSize: 10, color: tokens.textMuted, flexShrink: 0 }}>{label}</span>
<span style={{
fontSize: 12, fontWeight: 700, color: tone, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap',
}}>{value}</span>
</div>
);
return (
<PanelBody>
{/* 口径提示:过程 vs 结果 */}
<div style={{
fontSize: 11, lineHeight: 1.55, color: tokens.textSub, marginBottom: 8,
padding: '6px 9px', borderRadius: 8, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
{t.qflow.hint}
</div>
{/* 瓶颈横幅:达成率最低的一段,和约束段一起说清楚 */}
<div
title={`${t.flow.bottleneckTip};${t.flow.constraint}:${ROLES[constraint].zh}`}
style={{
display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, marginBottom: 10,
padding: '4px 8px', borderRadius: 8,
background: `${alertColor(stats[bottleneck].status, tokens)}14`,
border: `1px solid ${alertColor(stats[bottleneck].status, tokens)}3a`,
}}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: alertColor(stats[bottleneck].status, tokens), flexShrink: 0 }} />
<span style={{ color: tokens.textSub, flexShrink: 0 }}>{t.qflow.bottleneck}</span>
<span style={{ color: tokens.text, fontWeight: 700, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{ROLES[bottleneck].key} · {ROLES[bottleneck].zh}
</span>
<span style={{ flex: 1 }} />
<span style={{ color: alertColor(stats[bottleneck].status, tokens), fontWeight: 800, fontVariantNumeric: 'tabular-nums' }}>
{fmt(stats[bottleneck].score)}%
</span>
</div>
{/* 四段角色流程 */}
{segs.map(({ r, i }, si) => {
const st = stats[i];
const c = alertColor(st.status, tokens);
const Icon = ICONS[r.icon];
/* 段间连线取前一段,线上标该段积压的在制品 */
const from = si > 0 ? segs[si - 1] : null;
const dwellTone = st.dwell <= st.dwellTarget ? tokens.success : st.dwell <= st.dwellTarget * 1.12 ? tokens.warning : tokens.danger;
const fpqcTone = st.fpqc >= st.fpqcTarget ? tokens.success : st.fpqc >= st.fpqcTarget - 4 ? tokens.warning : tokens.danger;
const reworkTone = st.rework <= st.reworkTarget ? tokens.success : st.rework <= st.reworkTarget * 1.15 ? tokens.warning : tokens.danger;
const trend = st.dwellDelta === null ? t.flow.flat
: st.dwellDelta < -0.05 ? `${t.flow.faster} ${fmt(Math.abs(st.dwellDelta))}${t.flow.unitDay}`
: st.dwellDelta > 0.05 ? `${t.flow.slower} ${fmt(st.dwellDelta)}${t.flow.unitDay}`
: t.flow.flat;
const isOpen = open === r.key;
return (
<div key={r.key}>
{/* 段间连线:单据沿链流转,线上标上一段积压 */}
{from && (
/* 段间箭头放在整栏水平中央,不再贴着左缘的轨道图标;
标签跟在箭头右侧,居中留白左右对称 */
<div style={{ position: 'relative', width: '100%', height: LINK }}>
<svg
width={RAIL} height={LINK}
style={{ position: 'absolute', left: '50%', top: 0, transform: 'translateX(-50%)', overflow: 'visible' }}
>
{/* 上端探出 2px 贴住上一张卡的下沿,箭头正好落在下一张卡的上沿 */}
<line x1={13} y1={-2} x2={13} y2={LINK} stroke={tokens.border} strokeWidth={2} />
<line
className="dash-flow" x1={13} y1={-2} x2={13} y2={LINK}
stroke={alertColor(stats[from.i].status, tokens)} strokeWidth={2.4} strokeDasharray="4 5" strokeLinecap="round"
/>
<path d={`M 8.5,${LINK - 6} L 13,${LINK} L 17.5,${LINK - 6}`} fill="none" stroke={tokens.border} strokeWidth={2} strokeLinecap="round" />
</svg>
<span style={{
position: 'absolute', left: 'calc(50% + 20px)', top: LINK / 2 - 7,
fontSize: 10, lineHeight: '14px', whiteSpace: 'nowrap', color: tokens.textMuted,
fontVariantNumeric: 'tabular-nums',
}}>
{from.r.key}→{r.key} · {t.flow.wip} {stats[from.i].wip}
</span>
</div>
)}
<div style={{ display: 'flex', gap: 8 }}>
{/* 轨道节点 */}
<div style={{ width: RAIL, flexShrink: 0, display: 'flex', justifyContent: 'center', paddingTop: 8 }}>
<span style={{
display: 'grid', placeItems: 'center', width: RAIL, height: RAIL, borderRadius: 9, flexShrink: 0,
background: `${c}1f`, border: `1px solid ${c}66`, color: c,
}}>
<Icon size={14} />
</span>
</div>
{/* 角色卡 */}
<div style={{
flex: 1, minWidth: 0, marginBottom: 2, borderRadius: 10, padding: '7px 9px',
background: tokens.panelBgAlt,
border: `1px solid ${st.status === 'red' ? c : tokens.border}`,
boxShadow: st.status === 'red' ? `0 0 0 1px ${c}33, 0 4px 14px ${c}1f` : 'none',
}}>
{/* 角色行:编码 + 名称 + 达成率 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span className={st.status === 'red' ? 'net-breathe' : undefined} style={{
width: 7, height: 7, borderRadius: '50%', flexShrink: 0, background: c, boxShadow: `0 0 6px ${c}`,
}} />
<span style={{
fontSize: 11, fontWeight: 800, color: c, flexShrink: 0, letterSpacing: '0.06em',
fontFamily: 'ui-monospace, monospace',
}}>{r.key}</span>
<span style={{
fontSize: 13, fontWeight: 800, color: tokens.text, minWidth: 0, flex: 1,
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>{r.zh}</span>
<span style={{
fontSize: 11.5, fontWeight: 800, color: c, flexShrink: 0, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace',
}}>{fmt(st.score)}%</span>
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, marginBottom: 5, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{r.duty} · {trend}
</div>
{/* 段达成条 */}
<div style={{ height: 3, borderRadius: 99, background: tokens.border, overflow: 'hidden', marginBottom: 6 }}>
<span style={{
display: 'block', height: '100%', width: `${Math.min(100, st.score)}%`, background: c,
transition: 'width 0.4s ease',
}} />
</div>
{/* 过程四量 */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '2px 8px', marginBottom: 6 }}>
{stat(t.flow.dwell, `${fmt(st.dwell)}${t.flow.unitDay}`, dwellTone)}
{stat(t.flow.flow, st.flow.toLocaleString(), tokens.textSub)}
{stat(t.flow.fpqc, `${fmt(st.fpqc)}%`, fpqcTone)}
{stat(t.flow.rework, `${st.rework}`, reworkTone)}
</div>
{/* 流转三行:输入 → 输出 → 后续动作。收起态宽度不够,只在展开态显示 */}
{expanded && (
<div style={{
fontSize: 10, lineHeight: 1.5, color: tokens.textSub, marginBottom: 6,
padding: '5px 7px', borderRadius: 8, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<div style={{ display: 'flex', gap: 4, minWidth: 0 }}>
<span style={{ color: tokens.textMuted, flexShrink: 0 }}>{t.qflow.input}</span>
<span style={{ minWidth: 0 }}>{r.input}</span>
</div>
<div style={{ display: 'flex', gap: 4, minWidth: 0 }}>
<span style={{ color: tokens.textMuted, flexShrink: 0 }}>{t.qflow.output}</span>
<span style={{ minWidth: 0, color: tokens.text, fontWeight: 600 }}>{r.output}</span>
</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4, minWidth: 0 }}>
<ArrowDownRight size={11} style={{ flexShrink: 0, color: c }} />
<span style={{ color: tokens.textMuted, flexShrink: 0 }}>{t.qflow.next}</span>
<span style={{ minWidth: 0 }}>{r.next}</span>
</div>
</div>
)}
{/* 本段质量 KPI:4 项/角色,点开看职责表现状原文 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginBottom: 4 }}>
<span style={{ fontSize: 10, color: tokens.textMuted, flexShrink: 0 }}>{t.qflow.kpiGroup}</span>
<span style={{ flex: 1, height: 1, background: tokens.border }} />
{/* 现状原文要两行才放得下,收起态宽度不够,只在展开态给这个入口 */}
{expanded && (
<button
onClick={() => setOpen(isOpen ? null : r.key)}
className="ghost-btn"
style={{
fontSize: 9.5, fontWeight: 700, cursor: 'pointer', padding: '1px 5px', borderRadius: 6,
color: isOpen ? tokens.onAccent : tokens.textMuted,
background: isOpen ? tokens.accent : tokens.cardBg,
border: `1px solid ${isOpen ? tokens.accent : tokens.border}`,
}}
>
{isOpen ? t.common.collapse : t.common.detail}
</button>
)}
</div>
<div style={{ display: 'grid', gridTemplateColumns: expanded ? '1fr 1fr' : '1fr', gap: 4 }}>
{st.kpis.map(k => {
const kc = alertColor(k.status, tokens);
return (
<div
key={k.code}
title={`${k.code} · ${k.zh}|${t.qflow.situation}:${k.now}|${t.qflow.targetShort} ${k.target}${k.unit}(现状 ${k.base}${k.unit})`}
style={{
minWidth: 0, padding: '4px 6px', borderRadius: 8,
background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}
>
<div style={{
fontSize: 10, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}}>{k.zh}</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
<span style={{
fontSize: 13, fontWeight: 800, color: kc, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace', lineHeight: 1.3,
}}>{fmt(k.value, k.decimals)}{k.unit}</span>
<span style={{ fontSize: 9.5, color: tokens.textMuted, flexShrink: 0 }}>
/{k.target}
</span>
<span style={{ flex: 1 }} />
<span style={{
fontSize: 9.5, fontWeight: 700, color: tokens.textMuted, flexShrink: 0,
fontVariantNumeric: 'tabular-nums',
}}>{k.achieve}%</span>
</div>
{/* 现状原文:只在展开态且点了「详情」时铺出来,避免左栏变成文档堆 */}
{isOpen && expanded && (
<div style={{ fontSize: 9.5, color: tokens.textMuted, lineHeight: 1.45, marginTop: 2 }}>
{/* 比率类指标的差值用百分点表述,写成「+46.6%」会被读成相对增幅 */}
{t.qflow.situation}:{k.base}{k.unit} · {t.qflow.vsBase} {k.vsBase > 0 ? '+' : ''}{fmt(k.vsBase, k.decimals)}{k.unit === '%' ? 'pt' : k.unit}
<br />{k.now}
</div>
)}
</div>
);
})}
</div>
</div>
</div>
</div>
);
})}
{/* 数据来源口径:明确标注这是模拟读数,以及换成真实数据要接哪几张表 */}
<div style={{
fontSize: 9.5, color: tokens.textMuted, lineHeight: 1.6, marginTop: 8,
padding: '6px 8px', borderRadius: 8, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
{periodLabel(period)} · {t.flow.wipTip}
<br />{t.qflow.dataSource}
<br />{t.qflow.kpiTip}
</div>
</PanelBody>
);
}
@@ -0,0 +1,162 @@
import { Fragment, useState } from 'react';
import { ArrowDownRight, ChevronDown, ChevronUp, Cog, Ruler, ShieldCheck, Wrench } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { useText } from '../../i18n/useText';
import { alertColor, fmt } from '../../lib/metric';
import { ROLES, qualityStats, type QIcon } from '../../lib/qualityFlow';
/**
* 质量流程横条(PE → IE → QE → ME):与左栏 QualityFlowPanel 同一个 qualityStats 源,
* 只换成横向一行等分的紧凑形态;点某段向下展开该段流转三行 + 4 项质量 KPI(含现状原文)。
*/
const ICONS: Record<QIcon, typeof Wrench> = { wrench: Wrench, ruler: Ruler, shield: ShieldCheck, cog: Cog };
export default function QualityFlowStrip({ period }: { period: number }) {
const { tokens } = useTheme();
const { t } = useText();
const [open, setOpen] = useState<string | null>(null);
const { stats, summary } = qualityStats(period);
const bottleneck = ROLES.findIndex(r => r.key === summary.bottleneckKey);
const constraint = ROLES.findIndex(r => r.key === summary.constraintKey);
const openIdx = ROLES.findIndex(r => r.key === open);
const stat = (label: string, value: string, tone: string) => (
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap' }}>{label}</div>
<div style={{
fontSize: 12.5, fontWeight: 700, color: tone, fontVariantNumeric: 'tabular-nums',
fontFamily: 'ui-monospace, monospace', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}}>{value}</div>
</div>
);
return (
<div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'stretch', gap: 0, minWidth: 0 }}>
{ROLES.map((r, i) => {
const st = stats[i];
const c = alertColor(st.status, tokens);
const Icon = ICONS[r.icon];
const dwellTone = st.dwell <= st.dwellTarget ? tokens.success : st.dwell <= st.dwellTarget * 1.12 ? tokens.warning : tokens.danger;
const fpqcTone = st.fpqc >= st.fpqcTarget ? tokens.success : st.fpqc >= st.fpqcTarget - 4 ? tokens.warning : tokens.danger;
const reworkTone = st.rework <= st.reworkTarget ? tokens.success : st.rework <= st.reworkTarget * 1.15 ? tokens.warning : tokens.danger;
const trend = st.dwellDelta === null ? t.flow.flat
: st.dwellDelta < -0.05 ? `${t.flow.faster} ${fmt(Math.abs(st.dwellDelta))}${t.flow.unitDay}`
: st.dwellDelta > 0.05 ? `${t.flow.slower} ${fmt(st.dwellDelta)}${t.flow.unitDay}`
: t.flow.flat;
const isOpen = open === r.key;
const tag = i === bottleneck ? t.qflow.bottleneck : i === constraint ? t.flow.constraint : null;
return (
<Fragment key={r.key}>
{i > 0 && (
<div
title={`${ROLES[i - 1].key}→${r.key} · ${t.flow.wip} ${stats[i - 1].wip}\n${t.flow.wipTip}`}
style={{ width: 34, flexShrink: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2 }}
>
<svg width={30} height={10} style={{ overflow: 'visible' }}>
<line x1={0} y1={5} x2={30} y2={5} stroke={tokens.border} strokeWidth={2} />
<line className="dash-flow" x1={0} y1={5} x2={30} y2={5}
stroke={alertColor(stats[i - 1].status, tokens)} strokeWidth={2.2} strokeDasharray="4 5" strokeLinecap="round" />
<path d="M 24,1 L 30,5 L 24,9" fill="none" stroke={tokens.border} strokeWidth={2} strokeLinecap="round" />
</svg>
<span style={{ fontSize: 9.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>
{stats[i - 1].wip}
</span>
</div>
)}
<button
onClick={() => setOpen(isOpen ? null : r.key)}
data-role={`qflow-${r.key}`}
aria-expanded={isOpen}
title={`${r.duty}|${t.qflow.hint}`}
style={{
flex: '1 1 0', minWidth: 0, textAlign: 'left', cursor: 'pointer', font: 'inherit', color: 'inherit',
borderRadius: 11, padding: '7px 10px',
background: isOpen ? tokens.accentBg : tokens.panelBgAlt,
border: `1px solid ${isOpen ? tokens.accent : st.status === 'red' ? c : tokens.border}`,
boxShadow: st.status === 'red' ? `0 0 0 1px ${c}33, 0 4px 14px ${c}1f` : 'none',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{
display: 'grid', placeItems: 'center', width: 20, height: 20, borderRadius: 6, flexShrink: 0,
background: `${c}1f`, border: `1px solid ${c}66`, color: c,
}}><Icon size={12} /></span>
<span style={{ fontSize: 11, fontWeight: 800, color: c, letterSpacing: '0.06em', fontFamily: 'ui-monospace, monospace', flexShrink: 0 }}>{r.key}</span>
<span style={{ fontSize: 13, fontWeight: 800, color: tokens.text, minWidth: 0, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{r.zh}</span>
{tag && (
<span style={{
fontSize: 9.5, fontWeight: 700, padding: '0 5px', borderRadius: 5, lineHeight: '15px', flexShrink: 0,
color: c, background: `${c}14`, border: `1px solid ${c}44`,
}}>{tag}</span>
)}
<span style={{ fontSize: 12, fontWeight: 800, color: c, flexShrink: 0, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>{fmt(st.score)}%</span>
{isOpen ? <ChevronUp size={13} color={tokens.textMuted} /> : <ChevronDown size={13} color={tokens.textMuted} />}
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, margin: '2px 0 4px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{r.duty} · {trend}
</div>
<div style={{ height: 3, borderRadius: 99, background: tokens.border, overflow: 'hidden', marginBottom: 5 }}>
<span style={{ display: 'block', height: '100%', width: `${Math.min(100, st.score)}%`, background: c, transition: 'width 0.4s ease' }} />
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 6 }}>
{stat(t.flow.dwell, `${fmt(st.dwell)}${t.flow.unitDay}`, dwellTone)}
{stat(t.flow.flow, st.flow.toLocaleString(), tokens.textSub)}
{stat(t.flow.fpqc, `${fmt(st.fpqc)}%`, fpqcTone)}
{stat(t.flow.rework, `${st.rework}`, reworkTone)}
</div>
</button>
</Fragment>
);
})}
</div>
{openIdx >= 0 && (() => {
const r = ROLES[openIdx];
const st = stats[openIdx];
const c = alertColor(st.status, tokens);
return (
<div data-role="qflow-detail" className="card-in" style={{
display: 'flex', gap: 12, alignItems: 'stretch', padding: '8px 10px', borderRadius: 11,
background: tokens.panelBgAlt, border: `1px solid ${tokens.borderAccent}`,
}}>
<div style={{ flex: '0 0 260px', minWidth: 0, fontSize: 10.5, lineHeight: 1.55, color: tokens.textSub }}>
<div style={{ fontSize: 11.5, fontWeight: 800, color: c, marginBottom: 3 }}>{r.key} · {r.zh}</div>
<div><span style={{ color: tokens.textMuted }}>{t.qflow.input} </span>{r.input}</div>
<div><span style={{ color: tokens.textMuted }}>{t.qflow.output} </span><b style={{ color: tokens.text, fontWeight: 600 }}>{r.output}</b></div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
<ArrowDownRight size={11} style={{ flexShrink: 0, color: c }} />
<span><span style={{ color: tokens.textMuted }}>{t.qflow.next} </span>{r.next}</span>
</div>
</div>
<div title={t.qflow.kpiTip} style={{ flex: 1, minWidth: 0, display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', gap: 8 }}>
{st.kpis.map(k => {
const kc = alertColor(k.status, tokens);
return (
<div key={k.code} title={`${k.code} · ${k.zh}`} style={{
minWidth: 0, padding: '5px 8px', borderRadius: 8, background: tokens.cardBg, border: `1px solid ${tokens.border}`,
}}>
<div style={{ fontSize: 10.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{k.zh}</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
<span style={{ fontSize: 14, fontWeight: 800, color: kc, fontVariantNumeric: 'tabular-nums', fontFamily: 'ui-monospace, monospace' }}>
{fmt(k.value, k.decimals)}{k.unit}
</span>
<span style={{ fontSize: 9.5, color: tokens.textMuted }}>/{k.target}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 9.5, fontWeight: 700, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{k.achieve}%</span>
</div>
<div style={{ fontSize: 9.5, color: tokens.textMuted, lineHeight: 1.45, marginTop: 2 }}>
{t.qflow.situation}:{k.base}{k.unit} · {t.qflow.vsBase} {k.vsBase > 0 ? '+' : ''}{fmt(k.vsBase, k.decimals)}{k.unit === '%' ? 'pt' : k.unit}
<br />{k.now}
</div>
</div>
);
})}
</div>
</div>
);
})()}
</div>
);
}
@@ -0,0 +1,348 @@
/**
* StepChain 换型链看板(任务中心 · W4-A,建议书 §4.9)。
*
* ★ 现场换型执行侧:7 节点(n1–n7)走 ChainTaskState **七态**,与改善闭环 TaskState 六态
* 是两套独立枚举(D17),本组件不引用闭环枚举。
*
* 三条诚实性纪律(与引擎 lib/oee/stepchain.ts、数据 data/oee/stepchain.ts 同源):
* 1. **GATE 不可跳过**:演示种子特意停在「n1–n5 已关闭、n6 质量门已提交待核准、n7 受阻挡未激活」。
* 点「QA 核准质量门」→ n6 APPROVED → 质量门通过 → n7 方可激活 → 整链方可关闭。绝不静默放行。
* 2. **DERIVED 不手填**:n7 时刻由 Xray 锚点经 T6 反推(n7=n4−10min),现算展示,不写死。
* 3. **T5 计划对齐是契约占位**:implemented=false,标灰「未接 APS」,不假装已实现。
*
* 纪律:数字与流转一律走 L3(chainTransition/canActivateNode/canCloseChain/gateSatisfied/
* deriveSetupTimes/slaDeadlineEpoch…),视图不二次计算;时钟为**注入的演示时钟**(模拟),
* 不读 Date.now 推进业务时刻;实例为内存态(SQLite 锁定四表,不落库)。
*/
import { useState } from 'react';
import {
GitBranch, ShieldCheck, Lock, ArrowRight, AlertTriangle,
Zap, Timer, RotateCcw, UserCog,
} from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
SRF_CHAIN, CHAIN_SEED, CHAIN_DEMO_NOW, CHAIN_SEED_NOTE, CHAIN_TRIGGERS, FORM_SLA_ESCALATION,
chainTransition, nextChainStates, canActivateNode, canCloseChain, gateSatisfied, nodeStateOf,
deriveSetupTimes, isoToEpoch, reverseDeriveN7, slaDeadlineEpoch, isSlaBreached, escalationFor,
CHAIN_STATE_LABEL,
type ChainInstance, type ChainTaskState, type ChainNode,
} from '../../lib/oeeService';
import { ENTRY_FORM_LABEL } from '../../types/oee';
import {
Card, Tiles, Table, Th, Td, Chip, Note, GapBox, grid2, dur,
} from '../workspace/oeeUi';
/** 节点短名(仅展示用,判据原文在详情里照录)。 */
const NODE_LABEL: Record<string, string> = {
n1_pm_start: 'PM 开始', n2_pm_end: 'PM 结束', n3_conversion_start: 'Conversion 开始',
n4_setup_mfg_start: 'MFG 换型开始', n5_setup_mfg_end: 'MFG 换型结束',
n6_qc_verify: '质量确认门', n7_setup_ea_end: 'EA 换型结束',
};
const KIND_LABEL: Record<ChainNode['kind'], string> = { TASK: '任务', GATE: '质量门', DERIVED: '派生' };
/** 七态色调(走主题令牌键,与闭环六态色调表各自独立)。 */
const STATE_TONE: Record<ChainTaskState, 'textMuted' | 'info' | 'accent' | 'warning' | 'success' | 'textSub' | 'danger'> = {
CREATED: 'textMuted', ACCEPTED: 'info', IN_PROGRESS: 'accent', SUBMITTED: 'warning',
APPROVED: 'success', CLOSED: 'textSub', REJECTED: 'danger',
};
const cloneSeed = (): ChainInstance => JSON.parse(JSON.stringify(CHAIN_SEED)) as ChainInstance;
const clockOf = (epoch: number): string => new Date(epoch * 1000).toISOString().slice(11, 19);
const timeOf = (iso: string): string => iso.slice(11, 19);
export default function ChainBoard() {
const { tokens } = useTheme();
const [instance, setInstance] = useState<ChainInstance>(cloneSeed);
const [selectedId, setSelectedId] = useState<string>('n6_qc_verify');
const [clock, setClock] = useState<number>(() => isoToEpoch(CHAIN_DEMO_NOW));
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const nodes = instance.nodes;
const gate = gateSatisfied(SRF_CHAIN, nodes);
const close = canCloseChain(SRF_CHAIN, nodes);
const n7act = canActivateNode('n7_setup_ea_end', SRF_CHAIN, nodes);
const anchorEpoch = instance.xrayAnchor !== undefined ? isoToEpoch(instance.xrayAnchor) : undefined;
const derived = anchorEpoch !== undefined ? deriveSetupTimes(anchorEpoch) : undefined;
const selectedDef = SRF_CHAIN.find((n) => n.id === selectedId) ?? SRF_CHAIN[0];
const selected = nodeStateOf(instance, selectedId);
const selActivatable = canActivateNode(selectedId, SRF_CHAIN, nodes);
const selStartedEpoch = selected?.startedAt !== undefined ? isoToEpoch(selected.startedAt) : undefined;
const selDeadline = slaDeadlineEpoch(selectedDef, selStartedEpoch);
const selBreached = isSlaBreached(selectedDef, selStartedEpoch, clock);
const kindTone = (k: ChainNode['kind']): string =>
k === 'GATE' ? tokens.warning : k === 'DERIVED' ? tokens.info : tokens.textSub;
const advance = (to: ChainTaskState) => {
const cur = nodeStateOf(instance, selectedId);
if (!cur) return;
if (cur.state === 'CREATED' && !selActivatable.ok) {
setMsg({ ok: false, text: `不可激活:${selActivatable.reason ?? '上游质量门未通过'}` });
return;
}
const at = new Date(clock * 1000).toISOString();
const note = selectedDef.kind === 'GATE' && to === 'APPROVED' ? 'QA 主管核准质量门(T4 事务内手动触发)' : undefined;
const r = chainTransition(cur, to, { at, by: cur.owner, ...(note ? { note } : {}) });
if (!r.ok || !r.node) { setMsg({ ok: false, text: r.reason ?? '非法流转' }); return; }
const newNode = r.node;
setInstance({ ...instance, nodes: nodes.map((n) => (n.nodeId === selectedId ? newNode : n)) });
setClock(clock + 120);
setMsg({ ok: true, text: `${NODE_LABEL[selectedId]}:${CHAIN_STATE_LABEL[cur.state]} → ${CHAIN_STATE_LABEL[to]}(${timeOf(at)})` });
};
const reset = () => { setInstance(cloneSeed()); setClock(isoToEpoch(CHAIN_DEMO_NOW)); setMsg(null); setSelectedId('n6_qc_verify'); };
const escalatedCount = nodes.filter((n) => n.escalated).length;
return (
<>
{/* ── 换型链 7 节点 stepper + 质量门状态 ── */}
<Card
title="SRF 换型链 · 7 节点(n1 → n7)"
icon={<GitBranch size={14} color={tokens.accent} />}
full
right={
<span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<Chip color={gate ? tokens.success : tokens.warning} title="n6_qc_verify 质量门:未核准前下游不得激活、整链不得关闭">
{gate ? '质量门已通过' : '质量门未通过'}
</Chip>
<Chip color={close.ok ? tokens.success : tokens.textMuted} title={close.reason ?? '所有节点通过且质量门核准'}>
{close.ok ? '整链可关闭' : '整链不可关闭'}
</Chip>
<button onClick={reset} title="恢复演示种子(n6 待核准、n7 受阻挡)" style={{
display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 600,
padding: '3px 9px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.border}`, background: 'transparent', color: tokens.textSub,
}}><RotateCcw size={12} />重置演示</button>
</span>
}
note={CHAIN_SEED_NOTE + ' 点击节点查看详情与流转;七态=已创建→已接单→执行中→已提交→已核准→已关闭(已提交可驳回返工)。'}
>
{/* 一行等分 7 节点(看板红线:flex:1 + minWidth:0 + 不溢出) */}
<div style={{ display: 'flex', alignItems: 'stretch', gap: 6, minWidth: 0 }}>
{SRF_CHAIN.map((n, i) => {
const st = nodeStateOf(instance, n.id);
const on = n.id === selectedId;
const blocked = n.id === 'n7_setup_ea_end' && !n7act.ok && st?.state === 'CREATED';
const tone = tokens[STATE_TONE[st?.state ?? 'CREATED']];
return (
<div key={n.id} style={{ display: 'flex', alignItems: 'stretch', gap: 6, flex: 1, minWidth: 0 }}>
<div
onClick={() => { setSelectedId(n.id); setMsg(null); }}
style={{
flex: 1, minWidth: 0, cursor: 'pointer', padding: '7px 8px', borderRadius: 9,
background: on ? tokens.accentBg : tokens.kpiCardBg,
border: `1px solid ${on ? tokens.accent : tokens.kpiCardBorder}`,
display: 'flex', flexDirection: 'column', gap: 3, overflow: 'hidden',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 4, minWidth: 0 }}>
<span style={{ width: 8, height: 8, borderRadius: '50%', background: tone, flexShrink: 0 }} />
<span style={{ fontSize: 9.5, fontWeight: 700, color: kindTone(n.kind), whiteSpace: 'nowrap' }}>{KIND_LABEL[n.kind]}</span>
{blocked && <Lock size={11} color={tokens.warning} style={{ flexShrink: 0 }} />}
{st?.escalated && <AlertTriangle size={11} color={tokens.danger} style={{ flexShrink: 0 }} />}
</div>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }} title={n.criterion}>
{NODE_LABEL[n.id] ?? n.id}
</div>
<div style={{ fontSize: 9.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{n.role} · {n.slaMin !== undefined ? `${n.slaMin}min` : '无 SLA'}
</div>
<div style={{ fontSize: 9.5, fontWeight: 600, color: tone, whiteSpace: 'nowrap' }}>{CHAIN_STATE_LABEL[st?.state ?? 'CREATED']}</div>
</div>
{i < SRF_CHAIN.length - 1 && (
<ArrowRight size={13} color={tokens.textMuted} style={{ alignSelf: 'center', flexShrink: 0 }} />
)}
</div>
);
})}
</div>
{/* 质量门阻挡披露:把「不可跳过」写在脸上 */}
{!gate && (
<div style={{ marginTop: 9 }}>
<GapBox
missing={`质量门 n6_qc_verify 未核准(当前 ${CHAIN_STATE_LABEL[nodeStateOf(instance, 'n6_qc_verify')?.state ?? 'CREATED']})`}
dependsOn="QA 主管在事务内手动核准(T4)"
stage="核准后 n7 方可激活、整链方可关闭"
note={`n7_setup_ea_end 受阻挡:${n7act.reason ?? ''}。整链未通过节点:${(close.pendingNodes ?? []).join('、') || '无'}。GATE 不可跳过——绝不把「还差质量确认」的链标成已完成。`}
/>
</div>
)}
{gate && close.ok && (
<Note>质量门已核准、全部节点通过 → 整链可关闭。这是「QA 核准 → 解锁 n7 → 推进至关闭」的完整闭环演示。</Note>
)}
</Card>
{/* ── 节点详情 + T6 派生/SLA ── */}
<div style={grid2}>
<Card
title={`节点详情 · ${NODE_LABEL[selectedDef.id] ?? selectedDef.id}`}
icon={<UserCog size={14} color={tokens.info} />}
right={<Chip color={tokens[STATE_TONE[selected?.state ?? 'CREATED']]}>{CHAIN_STATE_LABEL[selected?.state ?? 'CREATED']}</Chip>}
note="判据原文照录建议书 §4.9.1;当前处理人为演示角色(不编造真实姓名)。流转由引擎 chainTransition 校验合法性,历史全程留痕可重放。"
>
<Table head={<><Th>字段</Th><Th>值</Th></>}>
<tr><Td color={tokens.textSub}>节点编码</Td><Td mono bold>{selectedDef.id}</Td></tr>
<tr><Td color={tokens.textSub}>种类 / 角色</Td><Td><Chip color={kindTone(selectedDef.kind)}>{KIND_LABEL[selectedDef.kind]}</Chip> <span style={{ color: tokens.textMuted }}>{selectedDef.role}</span></Td></tr>
<tr><Td color={tokens.textSub}>判据原文</Td><Td color={tokens.text}>{selectedDef.criterion}</Td></tr>
<tr><Td color={tokens.textSub}>触发器</Td><Td mono>{selectedDef.trigger}</Td></tr>
<tr><Td color={tokens.textSub}>节点 SLA</Td><Td mono>{selectedDef.slaMin !== undefined ? `${selectedDef.slaMin} min` : '—(无 SLA)'}</Td></tr>
<tr><Td color={tokens.textSub}>升级对象</Td><Td color={tokens.textSub}>{escalationFor(selectedDef)}</Td></tr>
<tr><Td color={tokens.textSub}>当前处理人</Td><Td color={tokens.text}>{selected?.owner ?? '—'}</Td></tr>
<tr><Td color={tokens.textSub}>开始时刻</Td><Td mono color={tokens.textMuted}>{selected?.startedAt ? timeOf(selected.startedAt) : '—(未开始)'}</Td></tr>
</Table>
{/* 流转动作 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 9 }}>
{nextChainStates(selected?.state ?? 'CREATED').map((s) => {
const isGateApprove = selectedDef.kind === 'GATE' && s === 'APPROVED';
const disabled = (selected?.state === 'CREATED') && !selActivatable.ok;
return (
<button
key={s}
onClick={() => advance(s)}
disabled={disabled}
title={disabled ? (selActivatable.reason ?? '上游质量门未通过') : `推进到 ${CHAIN_STATE_LABEL[s]}`}
style={{
fontSize: 11, fontWeight: 700, padding: '5px 13px', borderRadius: 8,
cursor: disabled ? 'not-allowed' : 'pointer',
border: `1px solid ${disabled ? tokens.border : isGateApprove ? tokens.success : tokens.accent}`,
background: disabled ? 'transparent' : isGateApprove ? `${tokens.success}1f` : tokens.accentBg,
color: disabled ? tokens.textMuted : isGateApprove ? tokens.success : tokens.accent,
}}
>
{isGateApprove ? 'QA 核准质量门' : s === 'REJECTED' ? '驳回返工' : `推进 → ${CHAIN_STATE_LABEL[s]}`}
</button>
);
})}
{nextChainStates(selected?.state ?? 'CREATED').length === 0 && <Chip color={tokens.textMuted}>终态·无后继</Chip>}
{selected?.state === 'CREATED' && !selActivatable.ok && <Chip color={tokens.warning} title={selActivatable.reason}>受质量门阻挡</Chip>}
</div>
{msg && (
<div style={{
marginTop: 8, padding: '7px 9px', borderRadius: 9, minWidth: 0,
background: msg.ok ? `${tokens.success}12` : `${tokens.warning}12`,
border: `1px solid ${msg.ok ? tokens.success : tokens.warning}44`,
fontSize: 11, color: msg.ok ? tokens.success : tokens.warning, lineHeight: 1.5,
}}>{msg.text}</div>
)}
{/* 历史时间线 */}
<div style={{ marginTop: 10 }}>
<Note>流转留痕(at/by 注入,可重放):</Note>
<div style={{ display: 'flex', flexDirection: 'column', gap: 0, minWidth: 0, marginTop: 5 }}>
{(selected?.history ?? []).map((h, i, arr) => (
<div key={`${h.state}-${i}`} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', paddingBottom: i < arr.length - 1 ? 8 : 0 }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
<span style={{ width: 8, height: 8, borderRadius: '50%', background: tokens[STATE_TONE[h.state]], marginTop: 3 }} />
{i < arr.length - 1 && <span style={{ width: 1.5, flex: 1, minHeight: 12, background: tokens.border, marginTop: 2 }} />}
</div>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
<Chip color={tokens[STATE_TONE[h.state]]}>{CHAIN_STATE_LABEL[h.state]}</Chip>
<span style={{ fontSize: 10, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{timeOf(h.at)}</span>
<span style={{ fontSize: 10, color: tokens.textSub }}>{h.by}</span>
</div>
{h.note && <div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{h.note}</div>}
</div>
</div>
))}
</div>
</div>
</Card>
<Card
title="T6 派生 · 质量门 · SLA"
icon={<Zap size={14} color={tokens.warning} />}
right={<Chip color={tokens.textMuted} title="演示时钟(模拟),不读 Date.now 推进业务时刻">演示时钟 {clockOf(clock)}</Chip>}
note="n7 时刻由 Xray 锚点经 T6 反推(纯算术,不手填);SLA 截止=开始时刻+slaMin,超时升级到节点 escalateTo。无 SLA / 无起点不判超时(不猜)。"
>
{/* T6 派生 */}
<div style={{ marginBottom: 9 }}>
<Tiles items={[
{ label: 'Xray 锚点', value: instance.xrayAnchor ? timeOf(instance.xrayAnchor) : '—', sub: '同一张图片', color: tokens.textSub },
{ label: 'n4 派生', value: derived ? clockOf(derived.n4StartEpoch) : '—', sub: '锚点 +5min', color: tokens.info },
{ label: 'n7 派生', value: derived ? clockOf(derived.n7EndEpoch) : '—', sub: '锚点 −5min', color: tokens.accent },
]} />
<Note>
T6 不变量:n7=n4−10min({derived ? `${dur(derived.n4StartEpoch - derived.n7EndEpoch)}` : '—'})。
现算校验 reverseDeriveN7(n4)=n7:
<b style={{ color: derived && reverseDeriveN7(derived.n4StartEpoch) === derived.n7EndEpoch ? tokens.success : tokens.warning }}>
{derived && reverseDeriveN7(derived.n4StartEpoch) === derived.n7EndEpoch ? ' 成立' : ' 锚点缺失/不成立'}
</b>。锚点缺失则不派生、不猜一个时间塞进去。
</Note>
</div>
{/* 选中节点 SLA */}
<Table head={<><Th>SLA 项</Th><Th>值</Th></>}>
<tr><Td color={tokens.textSub}>选中节点</Td><Td mono>{selectedDef.id}</Td></tr>
<tr><Td color={tokens.textSub}>SLA 上限</Td><Td mono>{selectedDef.slaMin !== undefined ? `${selectedDef.slaMin} min` : '—(无 SLA)'}</Td></tr>
<tr><Td color={tokens.textSub}>SLA 截止</Td><Td mono color={tokens.textMuted}>{selDeadline !== undefined ? clockOf(selDeadline) : '—(无起点/无 SLA)'}</Td></tr>
<tr>
<Td color={tokens.textSub}>是否超时</Td>
<Td>{selDeadline === undefined
? <Chip color={tokens.textMuted}>不判超时</Chip>
: selBreached ? <Chip color={tokens.danger}>已超时</Chip> : <Chip color={tokens.success}>未超时</Chip>}
</Td>
</tr>
<tr>
<Td color={tokens.textSub}>升级状态</Td>
<Td>{selected?.escalated
? <Chip color={tokens.danger} title={`曾超时升级到 ${selected.escalatedTo}`}>已升级 → {selected.escalatedTo}</Chip>
: <Chip color={tokens.textMuted}>未升级</Chip>}
</Td>
</tr>
</Table>
<Note>
本链曾超时升级 {escalatedCount} 个节点(n4_setup_mfg_start 超 20min SLA → 升级 MFG 主管后完成,留痕)。
节点级 SLA(n1–n4)与录入台表单级 SLA(下表)是两套,不混用。
</Note>
</Card>
</div>
{/* ── 六触发器 + 表单级 SLA ── */}
<div style={grid2}>
<Card
title="六触发器(T1–T6)"
icon={<Timer size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="T5 计划对齐为契约占位,原型未接 APS 排产系统">实现 {CHAIN_TRIGGERS.filter((t) => t.implemented).length}/{CHAIN_TRIGGERS.length}</Chip>}
note="触发器归属按判据语义判定(§4.9.2)。T5 计划对齐 implemented=false:契约占位,不假装已接排产系统。T4 手动触发在事务内(提交即流转、可回滚)。"
>
<Table head={<><Th>编号</Th><Th>类型</Th><Th>实现</Th><Th>说明</Th></>}>
{CHAIN_TRIGGERS.map((t) => (
<tr key={t.id} style={{ opacity: t.implemented ? 1 : 0.7 }}>
<Td bold mono>{t.id}</Td>
<Td color={tokens.textSub}>{t.kind}</Td>
<Td>{t.implemented
? <Chip color={tokens.success}>已实现</Chip>
: <Chip color={tokens.textMuted} title={t.note}>契约占位</Chip>}
</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{t.note}</span></Td>
</tr>
))}
</Table>
</Card>
<Card
title="录入台表单级 SLA 升级"
icon={<ShieldCheck size={14} color={tokens.info} />}
right={<Chip color={tokens.textMuted}>{FORM_SLA_ESCALATION.length} 张归因/登记单</Chip>}
note="区别于节点级 SLA:这是录入台四张归因/登记单的表单级 SLA(§4.9.3 原文)。Jam 归因无独立表单(并入停机归因流程),form=null,不臆造表单。"
>
<Table head={<><Th>表单</Th><Th>对应录入单</Th><Th>SLA</Th><Th>升级对象</Th></>}>
{FORM_SLA_ESCALATION.map((f) => (
<tr key={f.label}>
<Td bold color={tokens.textSub}>{f.label}</Td>
<Td color={tokens.textMuted}>{f.form ? ENTRY_FORM_LABEL[f.form] : <Chip color={tokens.textMuted} title={f.note}>无独立表单</Chip>}</Td>
<Td mono>{f.sla}</Td>
<Td color={tokens.textSub}>{f.escalateTo}</Td>
</tr>
))}
</Table>
<Note>超时升级对象照录原文:Down 归因 2h→EQ+MFG;Jam 归因当班内→MFG 班组长;等待登记当班内→PC;5S 当班内→EA。</Note>
</Card>
</div>
</>
);
}
@@ -0,0 +1,236 @@
/**
* 任务中心(task 页签 · W4-A,建议书 §5.7 / 方案 5.2.1 #6)。
*
* ★ 一个页面承载**两套独立状态机**(D17,绝不共用枚举):
* A. StepChain 换型链 **七态**(ChainTaskState,现场换型执行)→ ChainBoard。
* B. 改善闭环 **六态**(TaskState,改善立项)→ 本页治理台(与录入台共享 lifted tasks)。
* 两者都有 IN_PROGRESS,但属不同枚举/不同流转表,互不引用。
*
* 纪律:数字与流转一律走 L3(chainDslStats / tryDispatch / advanceTask / canDispatch / nextStates),
* 视图不二次计算;派发闸只挂「待审核→已派发」,四项必填任一缺失即拒派(断言⑨)。
* 四项必填的**编辑**在录入台(OeeEntry),本页只做治理/流转与缺项提示,不重复造编辑器。
*/
import { useState } from 'react';
import { ListChecks, Send, ShieldAlert, History, CheckCircle2, AlertTriangle, ArrowRightLeft } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
chainDslStats, tryDispatch, advanceTask, canDispatch, nextStates, REQUIRED_FIELDS, ENTRY_OPERATOR,
} from '../../lib/oeeService';
import { TASK_STATE_LABEL, type ImprovementTask, type TaskState } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, GapBox, grid2, pageStyle,
} from '../workspace/oeeUi';
import type { OeeViewProps } from '../workspace/OeeOverview';
import ChainBoard from './ChainBoard';
export interface OeeTaskCenterProps extends OeeViewProps {
/** 改善任务(与优先清单/录入台共享,由 MetricWorkspace lifted state 提供)。 */
tasks: ImprovementTask[];
/** 派发/流转后回写共享 state。 */
onTasksChange: (t: ImprovementTask[]) => void;
}
/** 闭环六态色调(与换型链七态色调表各自独立,D17)。 */
const STATE_TONE: Record<TaskState, 'textMuted' | 'warning' | 'info' | 'accent' | 'success' | 'textSub'> = {
DRAFT: 'textMuted', PENDING_REVIEW: 'warning', DISPATCHED: 'info',
IN_PROGRESS: 'accent', VERIFIED: 'success', ARCHIVED: 'textSub',
};
export default function OeeTaskCenter({ filter, tasks, onTasksChange, onNavigate }: OeeTaskCenterProps) {
const { tokens } = useTheme();
const dsl = chainDslStats();
const [selectedTaskId, setSelectedTaskId] = useState<string | null>(tasks[0]?.id ?? null);
const [gateMsg, setGateMsg] = useState<{ ok: boolean; reason?: string; missing?: { label: string; prompt: string }[] } | null>(null);
const pendingReview = tasks.filter((t) => t.state === 'PENDING_REVIEW').length;
const dispatchable = tasks.filter((t) => t.state === 'PENDING_REVIEW' && canDispatch(t).ok).length;
const selectedTask = tasks.find((t) => t.id === selectedTaskId) ?? null;
const taskCheck = selectedTask ? canDispatch(selectedTask) : null;
const missingKeys = new Set(taskCheck?.missing.map((m) => m.key) ?? []);
const ctx = () => ({ at: new Date().toISOString(), by: ENTRY_OPERATOR });
const selectTask = (id: string) => { setSelectedTaskId(id); setGateMsg(null); };
const dispatch = (id: string) => {
const r = tryDispatch(tasks, id, ctx());
onTasksChange(r.tasks);
setGateMsg({ ok: r.result.ok, reason: r.result.reason, missing: r.check.missing.map((m) => ({ label: m.label, prompt: m.prompt })) });
};
const advance = (id: string, to: TaskState) => {
const r = advanceTask(tasks, id, to, ctx());
onTasksChange(r.tasks);
setGateMsg({ ok: r.result.ok, reason: r.result.reason, missing: r.result.missing?.map((m) => ({ label: m.label, prompt: m.prompt })) });
};
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="任务中心" icon={<ListChecks size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="换型链七态(现场执行)与改善闭环六态(改善立项)是两套独立状态机(D17)">两套状态机·独立枚举</Chip>}
/>
<Note>
任务中心承载<strong>两套独立状态机</strong>:StepChain 换型链走 <b>ChainTaskState 七态</b>(现场换型执行,n6 质量门不可跳过),
改善闭环走 <b>TaskState 六态</b>(改善立项,四项必填齐备才派发)。两者都有「执行中」,但属不同枚举、不同流转表,互不引用(D17)。
换型链实例为模拟种子;改善任务与优先清单/录入台共享同一份状态。
</Note>
<Tiles items={[
{ label: '换型链节点', value: String(dsl.nodeCount), sub: `任务${dsl.byKind.TASK}/门${dsl.byKind.GATE}/派生${dsl.byKind.DERIVED}`, color: tokens.textSub, title: 'SRF 换型链 n1–n7;n6 GATE 不可跳过、n7 DERIVED 由 T6 反推' },
{ label: '触发器', value: String(dsl.triggerCount), sub: `实现 ${dsl.implementedTriggers}/占位 ${dsl.placeholderTriggers.length}`, color: tokens.textSub, title: 'T5 计划对齐为契约占位,未接 APS' },
{ label: '改善任务', value: String(tasks.length), sub: `待审核 ${pendingReview}`, color: tokens.textSub },
{ label: '可派发', value: String(dispatchable), sub: '四项必填齐备', color: dispatchable ? tokens.success : tokens.textMuted, title: '待审核且负责人/完成时限/预期收益/验证方式齐备' },
{ label: '表单级 SLA', value: String(dsl.formSlaCount), sub: '节点级另计', color: tokens.textMuted, title: '录入台四张归因/登记单的表单级 SLA,区别于节点级 SLA' },
]} />
{/* ── A. StepChain 换型链七态 ── */}
<ChainBoard />
{/* ── B. 改善闭环六态治理台 ── */}
<Card
title="改善闭环 · 六态治理台"
icon={<Send size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted}>{tasks.length} 条任务 · 与录入台共享</Chip>}
note="六态:待生成→待审核→已派发→执行中→已验证→已归档(待审核可退回待生成)。派发闸只挂「待审核→已派发」:四项必填任一缺失即拒派,任务停在待审核(断言⑨)。点击行选中。四项必填的编辑在录入台。"
>
<Table head={<>
<Th>任务</Th><Th>标题</Th><Th>状态</Th><Th>真因</Th><Th right>优先分</Th><Th>负责人</Th>
</>}>
{tasks.map((t) => {
const on = t.id === selectedTaskId;
return (
<tr key={t.id} onClick={() => selectTask(t.id)} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}>
<Td mono bold color={on ? tokens.accent : tokens.textSub}>{t.id}</Td>
<Td color={tokens.text}>{t.title}</Td>
<Td><Chip color={tokens[STATE_TONE[t.state]]}>{TASK_STATE_LABEL[t.state]}</Chip></Td>
<Td><Chip color={tokens.textMuted} title={`${t.rootCauseEntity.type} · ${t.rootCauseEntity.id}`}>{t.causeClass} 类</Chip></Td>
<Td right mono color={tokens.textSub}>{t.priorityScore.toFixed(4)}</Td>
<Td color={tokens.textSub}>{t.owner ?? <span style={{ color: tokens.warning }}>未指定</span>}</Td>
</tr>
);
})}
</Table>
{tasks.length === 0 && <Note>暂无改善任务。前往「优先处理清单」由 POC 候选生成待审核任务,再回本页治理派发。</Note>}
</Card>
{selectedTask && (
<div style={grid2}>
<Card
title={`四项必填派发闸 · ${selectedTask.id}`}
icon={<ShieldAlert size={14} color={tokens.warning} />}
right={<Chip color={taskCheck?.ok ? tokens.success : tokens.warning}>{taskCheck?.ok ? '齐备·可派发' : `缺 ${taskCheck?.missing.length ?? 0} 项`}</Chip>}
note="负责人 / 完成时限 / 预期收益(区间) / 验证方式。本页只读展示齐备状态;缺项时派发被拒,任务停在待审核。补齐编辑请前往录入台。"
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
{REQUIRED_FIELDS.map((f) => {
const ok = !missingKeys.has(f.key);
const val = f.key === 'expectedBenefit'
? (selectedTask.expectedBenefit ? `${selectedTask.expectedBenefit.min}–${selectedTask.expectedBenefit.max} ${selectedTask.expectedBenefit.unit}` : '—')
: ((selectedTask[f.key] as string | undefined) || '—');
return (
<div key={f.key} style={{ display: 'flex', alignItems: 'center', gap: 7, minWidth: 0 }}>
{ok ? <CheckCircle2 size={13} color={tokens.success} style={{ flexShrink: 0 }} /> : <AlertTriangle size={13} color={tokens.warning} style={{ flexShrink: 0 }} />}
<span style={{ fontSize: 11, fontWeight: 600, color: tokens.textSub, whiteSpace: 'nowrap' }}>{f.label}</span>
<span style={{ fontSize: 11, color: ok ? tokens.text : tokens.warning, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={val}>{val}</span>
</div>
);
})}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
{selectedTask.state === 'PENDING_REVIEW' && (
<button
onClick={() => dispatch(selectedTask.id)}
style={{
fontSize: 11.5, fontWeight: 700, padding: '6px 16px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${taskCheck?.ok ? tokens.success : tokens.warning}`,
background: taskCheck?.ok ? `${tokens.success}1f` : `${tokens.warning}1f`,
color: taskCheck?.ok ? tokens.success : tokens.warning,
}}
>
{taskCheck?.ok ? '派发(SLA 起算)' : '尝试派发(将被拒)'}
</button>
)}
{nextStates(selectedTask.state).filter((s) => s !== 'DISPATCHED').map((s) => (
<button
key={s}
onClick={() => advance(selectedTask.id, s)}
style={{
fontSize: 11, fontWeight: 600, padding: '5px 12px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.border}`, background: 'transparent', color: tokens.textSub,
}}
>
{s === 'DRAFT' ? '退回待生成' : `推进 → ${TASK_STATE_LABEL[s]}`}
</button>
))}
{nextStates(selectedTask.state).length === 0 && <Chip color={tokens.textMuted}>终态·无后继</Chip>}
{selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && onNavigate && (
<button
onClick={() => onNavigate('entry')}
style={{
display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, fontWeight: 600,
padding: '5px 12px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.info}`, background: 'transparent', color: tokens.info,
}}
><ArrowRightLeft size={12} />去录入台补齐</button>
)}
</div>
{gateMsg && (
<div style={{
marginTop: 9, padding: '8px 10px', borderRadius: 9, minWidth: 0,
background: gateMsg.ok ? `${tokens.success}12` : `${tokens.warning}12`,
border: `1px solid ${gateMsg.ok ? tokens.success : tokens.warning}44`,
}}>
<div style={{ fontSize: 11.5, fontWeight: 700, color: gateMsg.ok ? tokens.success : tokens.warning, marginBottom: gateMsg.missing?.length ? 4 : 0 }}>
{gateMsg.ok ? '流转成功' : '被拒绝'}
</div>
{gateMsg.reason && <div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.55 }}>{gateMsg.reason}</div>}
{gateMsg.missing && gateMsg.missing.length > 0 && (
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 5 }}>
{gateMsg.missing.map((m) => <Chip key={m.label} color={tokens.warning}>{m.label}:{m.prompt}</Chip>)}
</div>
)}
</div>
)}
{selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && (
<div style={{ marginTop: 9 }}>
<GapBox
missing={`四项必填缺 ${taskCheck?.missing.length ?? 0} 项,无法派发`}
dependsOn={taskCheck?.missing.map((m) => m.label).join('、') ?? ''}
stage="录入台补齐后派发"
note="缺一项即拒派:任务停在「待审核」,绝不静默推进到「已派发」。补齐后 SLA 方才起算(断言⑨)。"
/>
</div>
)}
</Card>
<Card
title={`状态流转与历史 · ${selectedTask.id}`}
icon={<History size={14} color={tokens.info} />}
right={<Chip color={tokens[STATE_TONE[selectedTask.state]]}>{TASK_STATE_LABEL[selectedTask.state]}</Chip>}
note="历史时间线由引擎在每次合法流转时追加(at/by 注入,可重放)。SLA 计时起点=首次进入「已派发」的时刻。非法跨态跳转被拒绝。"
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 0, minWidth: 0 }}>
{selectedTask.history.map((h, i) => (
<div key={`${h.state}-${i}`} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', paddingBottom: i < selectedTask.history.length - 1 ? 9 : 0 }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
<span style={{ width: 9, height: 9, borderRadius: '50%', background: tokens[STATE_TONE[h.state]], marginTop: 3 }} />
{i < selectedTask.history.length - 1 && <span style={{ width: 1.5, flex: 1, minHeight: 14, background: tokens.border, marginTop: 2 }} />}
</div>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
<Chip color={tokens[STATE_TONE[h.state]]}>{TASK_STATE_LABEL[h.state]}</Chip>
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{h.at.slice(0, 19).replace('T', ' ')}</span>
<span style={{ fontSize: 10.5, color: tokens.textSub }}>{h.by}</span>
</div>
{h.note && <div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{h.note}</div>}
</div>
</div>
))}
</div>
</Card>
</div>
)}
</div>
);
}
@@ -0,0 +1,161 @@
import { useMemo } from 'react';
import { Boxes, Link2, Package, X } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { productionOrders, type ProductionOrder } from '../../data/ibp';
import { ScrollList } from './PurchaseOrderList';
/**
* 生产工单页签内容:一单一工单(工单号 = WO-销售订单号),按「离完工最近的先处理」排序,已完工沉底。
* 点卡片等于把它的来源销售订单送回左栏,与采购单页签共用同一条联动链路。
*/
export const fmtQty = (n: number) => n.toLocaleString('zh-CN');
/** 未完结工单按预计完工日升序,已完工排最后 */
export function sortWorkOrders(rows: ProductionOrder[]): ProductionOrder[] {
return [...rows].sort((a, b) => {
const doneA = a.单据状态 === '已完工' ? 1 : 0;
const doneB = b.单据状态 === '已完工' ? 1 : 0;
if (doneA !== doneB) return doneA - doneB;
return a.预计完工日期 < b.预计完工日期 ? -1 : a.预计完工日期 > b.预计完工日期 ? 1 : 0;
});
}
/** filterSO 非空时只保留该销售订单派生的工单 */
export function buildWorkOrders(filterSO: string | null): ProductionOrder[] {
return sortWorkOrders(filterSO ? productionOrders.filter(w => w.来源销售订单号 === filterSO) : productionOrders);
}
/** 工单号 / 来源订单 / 产品编码 / 车间 四向模糊匹配 */
export function filterWorkOrders(rows: ProductionOrder[], query: string): ProductionOrder[] {
const q = query.trim().toLowerCase();
if (!q) return rows;
return rows.filter(w =>
w.工单号.toLowerCase().includes(q)
|| w.来源销售订单号.toLowerCase().includes(q)
|| w.产品编码.toLowerCase().includes(q)
|| w.生产车间.toLowerCase().includes(q));
}
const statusColor = (s: string, tk: ThemeTokens) =>
s === '已完工' ? { c: tk.success, bg: tk.successBg }
: s === '已下达' ? { c: tk.info, bg: tk.infoBg }
: { c: tk.warning, bg: tk.warningBg };
interface Props {
query: string;
filterSO: string | null;
onClearFilter: () => void;
/** 点击工单:把来源销售订单交给左栏选中态 */
onSelectSO: (so: string | null) => void;
/** 当前左栏选中订单,用于卡片高亮 */
selectedSO: string | null;
}
export default function ProductionOrderList({ query, filterSO, onClearFilter, onSelectSO, selectedSO }: Props) {
const { tokens } = useTheme();
const list = useMemo(() => filterWorkOrders(buildWorkOrders(filterSO), query), [filterSO, query]);
const totalQty = useMemo(() => list.reduce((a, w) => a + w.生产数量, 0), [list]);
return (
<>
{/* 左栏订单联动条 */}
{filterSO && (
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
<Link2 size={12} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO}</span>
<span style={{ flex: 1 }} />
<button onClick={onClearFilter} title="显示全部工单" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
<X size={13} />
</button>
</div>
)}
{/* 汇总条 */}
<div style={{
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
}}>
<span>{list.length} 张工单 · {new Set(list.map(w => w.生产车间)).size} 个车间</span>
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>{fmtQty(totalQty)} PCS</span>
</div>
<ScrollList>
{list.length === 0 && (
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
{filterSO ? '该销售订单暂无生产工单' : '无匹配工单'}
</div>
)}
{list.map(w => {
const active = selectedSO === w.来源销售订单号;
const sc = statusColor(w.单据状态, tokens);
return (
<div
key={w.工单号}
onClick={() => onSelectSO(active ? null : w.来源销售订单号)}
style={{
position: 'relative', marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
background: active ? tokens.accentBg : tokens.panelBgAlt,
border: `1px solid ${active ? tokens.accent : tokens.border}`,
transition: 'background .15s, border-color .15s',
}}
>
{active && <span style={{ position: 'absolute', left: -1, top: 10, bottom: 10, width: 3, borderRadius: 2, background: tokens.accent }} />}
{/* 行1:工单号 + 状态 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 13, fontWeight: 700, color: active ? tokens.accent : tokens.text, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
{w.工单号}
</span>
<span style={{ flex: 1 }} />
<span style={{
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
color: sc.c, background: sc.bg, border: `1px solid ${sc.c}44`, whiteSpace: 'nowrap',
}}>{w.单据状态}</span>
</div>
{/* 行2:来源订单 + 车间 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
<span style={{ fontSize: 11, color: tokens.textMuted }}>来自</span>
<span style={{ fontSize: 11.5, color: tokens.textSub, fontVariantNumeric: 'tabular-nums', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.来源销售订单号}</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{w.生产车间}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap' }}>BOM {w.BOM版本}</span>
</div>
{/* 行3:产品 + 规格 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 5, marginTop: 5 }}>
<Package size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<span style={{ fontSize: 12.5, color: tokens.text, fontFamily: 'ui-monospace, monospace', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.产品编码}</span>
{w.规格型号 && (
<span style={{ fontSize: 10.5, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{w.规格型号}</span>
)}
</div>
{/* 行4:数量 + 工期 */}
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>{fmtQty(w.生产数量)}</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{w.计量单位}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, color: tokens.textMuted, whiteSpace: 'nowrap' }}>
{w.预计开工日期} → {w.预计完工日期} · {w['生产周期(天)']} 天
</span>
</div>
</div>
);
})}
</ScrollList>
{/* 底部口径说明:工单由销售订单派生,一单一工单 */}
<div style={{
display: 'flex', alignItems: 'center', gap: 5, flex: '0 0 auto', paddingTop: 6,
fontSize: 10.5, color: tokens.textMuted, borderTop: `1px solid ${tokens.border}`,
}}>
<Boxes size={11} style={{ flexShrink: 0 }} />
<span>工单由销售订单派生 · 生产数量已对齐订单数量 · 点击卡片可联动左栏订单</span>
</div>
</>
);
}
@@ -0,0 +1,154 @@
import { useMemo } from 'react';
import { Link2, PackageSearch, X } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { purchaseOrders, type PurchaseOrder } from '../../data/ibp';
import { ScrollList } from '../layout/AutoScroll';
/**
* 采购单页签内容:按采购订单号把多行料项归并为一张卡片。
* 列表口径(分组 / 过滤 / 金额汇总)全部由这里的纯函数给出,SupplyPanel 复用同一函数算徽标数,
* 避免页签标题数字与实际条数各说各话。
*/
export interface POGroup {
采购订单号: string; 采购日期: string; 供应商编码: string; 供应商简称: string;
预计到货日期: string; 订单状态: string; 金额: number; 行数: number; 材料: string[];
来源销售订单: string[];
}
export const money = (n: number) => n.toLocaleString('zh-CN', { minimumFractionDigits: 1, maximumFractionDigits: 1 });
/** 按采购订单号归并;filterSO 非空时只保留该销售订单反查到的采购单 */
export function buildPurchaseGroups(filterSO: string | null): POGroup[] {
const src = filterSO ? purchaseOrders.filter(p => p.来源销售订单号 === filterSO) : purchaseOrders;
const byNo = new Map<string, POGroup>();
src.forEach((p: PurchaseOrder) => {
let g = byNo.get(p.采购订单号);
if (!g) {
g = {
采购订单号: p.采购订单号, 采购日期: p.采购日期, 供应商编码: p.供应商编码, 供应商简称: p.供应商简称,
预计到货日期: p.预计到货日期, 订单状态: p.订单状态, 金额: 0, 行数: 0, 材料: [], 来源销售订单: [],
};
byNo.set(p.采购订单号, g);
}
g.金额 += p.含税金额;
g.行数 += 1;
if (!g.材料.includes(p.材料编码)) g.材料.push(p.材料编码);
if (p.来源销售订单号 && !g.来源销售订单.includes(p.来源销售订单号)) g.来源销售订单.push(p.来源销售订单号);
});
return [...byNo.values()].sort((a, b) => (a.采购日期 < b.采购日期 ? 1 : -1));
}
/** 单号 / 供应商编码 / 供应商简称 / 物料 四向模糊匹配 */
export function filterPurchaseGroups(groups: POGroup[], query: string): POGroup[] {
const q = query.trim().toLowerCase();
if (!q) return groups;
return groups.filter(g =>
g.采购订单号.toLowerCase().includes(q)
|| g.供应商编码.toLowerCase().includes(q)
|| g.供应商简称.toLowerCase().includes(q)
|| g.材料.some(m => m.toLowerCase().includes(q)));
}
const statusColor = (s: string, tk: ThemeTokens) =>
s === '生效' ? { c: tk.success, bg: tk.successBg } : { c: tk.warning, bg: tk.warningBg };
interface Props {
query: string;
/** 左栏选中的销售订单号:非空时只看该订单反查到的采购单 */
filterSO: string | null;
onClearFilter: () => void;
}
export default function PurchaseOrderList({ query, filterSO, onClearFilter }: Props) {
const { tokens } = useTheme();
const list = useMemo(() => filterPurchaseGroups(buildPurchaseGroups(filterSO), query), [filterSO, query]);
const total = useMemo(() => list.reduce((a, g) => a + g.金额, 0), [list]);
return (
<>
{/* 左栏订单联动条 */}
{filterSO && (
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
<Link2 size={12} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO}</span>
<span style={{ flex: 1 }} />
<button onClick={onClearFilter} title="显示全部采购单" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
<X size={13} />
</button>
</div>
)}
{/* 汇总条 */}
<div style={{
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
}}>
<span>{list.length} 张采购单 · {new Set(list.flatMap(g => g.材料)).size} 种物料</span>
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>¥{money(total)}</span>
</div>
<ScrollList>
{list.length === 0 && (
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
{filterSO ? '该销售订单暂无关联采购单' : '无匹配采购单'}
</div>
)}
{list.map(g => {
const sc = statusColor(g.订单状态, tokens);
return (
<div key={g.采购订单号} style={{
marginBottom: 8, padding: '9px 11px', borderRadius: 9,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
{/* 行1:单号 + 状态 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 13, fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums', letterSpacing: '0.02em' }}>
{g.采购订单号}
</span>
<span style={{ flex: 1 }} />
<span style={{
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
color: sc.c, background: sc.bg, border: `1px solid ${sc.c}44`, whiteSpace: 'nowrap',
}}>{g.订单状态}</span>
</div>
{/* 行2:供应商 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
<span style={{ fontSize: 12, color: tokens.textSub, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{g.供应商简称}</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{g.供应商编码}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap' }}>下单 {g.采购日期}</span>
</div>
{/* 行3:材料 */}
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 5, marginTop: 5 }}>
<PackageSearch size={12} style={{ color: tokens.textMuted, flexShrink: 0, marginTop: 2 }} />
<span style={{ fontSize: 12, color: tokens.text, fontFamily: 'ui-monospace, monospace', lineHeight: 1.5, wordBreak: 'break-all' }}>
{g.材料.slice(0, 3).join('、')}{g.材料.length > 3 ? ` 等 ${g.材料.length} 种` : ''}
</span>
</div>
{/* 行4:金额 + 到货 */}
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>¥{money(g.金额)}</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>{g.行数} 行</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, color: tokens.textMuted }}>到货 {g.预计到货日期}</span>
</div>
</div>
);
})}
</ScrollList>
</>
);
}
/**
* 滚动区已上移到 layout/AutoScroll(新告警面板也用它),这里只留转发导出,
* 免得 demand/supply 三个旧列表各自再抄一份。
*/
export { ScrollList };
@@ -0,0 +1,141 @@
import { useMemo } from 'react';
import { Link2, Users, X } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { purchaseOrders, suppliers, type Supplier } from '../../data/ibp';
import { ScrollList } from './PurchaseOrderList';
/**
* 供应商资料页签:Excel「供应商资料」的 8 个字段全量展示(采购行数 / 采购金额沿用表内汇总口径)。
* 左栏选中销售订单时,只列出该订单实际下单过的供应商——关联关系由采购订单行反推,不另外造数据。
*/
export const money2 = (n: number) => n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
/** 按采购金额从大到小:钱多的供应商先看 */
export function sortSuppliers(rows: Supplier[]): Supplier[] {
return [...rows].sort((a, b) => b.采购金额 - a.采购金额);
}
/** filterSO 非空时用采购订单行反查该订单涉及的供应商编码 */
export function buildSuppliers(filterSO: string | null): Supplier[] {
if (!filterSO) return sortSuppliers(suppliers);
const codes = new Set(purchaseOrders.filter(p => p.来源销售订单号 === filterSO).map(p => p.供应商编码));
return sortSuppliers(suppliers.filter(s => codes.has(s.供应商编码)));
}
/** 编码 / 简称 / 所属类别 / 分管部门 四向模糊匹配 */
export function filterSuppliers(rows: Supplier[], query: string): Supplier[] {
const q = query.trim().toLowerCase();
if (!q) return rows;
return rows.filter(s =>
s.供应商编码.toLowerCase().includes(q)
|| s.供应商简称.toLowerCase().includes(q)
|| s.所属类别.toLowerCase().includes(q)
|| (s.分管部门 ?? '').toLowerCase().includes(q));
}
/** 客商一体(性质=客户/供应商)是治理关注项,单独给色 */
const natureColor = (nature: string, tk: ThemeTokens) =>
nature === '客户/供应商' ? { c: tk.warning, bg: tk.warningBg } : { c: tk.info, bg: tk.infoBg };
interface Props {
query: string;
filterSO: string | null;
onClearFilter: () => void;
/** 点击供应商:筛出它的采购单行,回到采购单页签看 */
onPickSupplier: (code: string) => void;
}
export default function SupplierList({ query, filterSO, onClearFilter, onPickSupplier }: Props) {
const { tokens } = useTheme();
const list = useMemo(() => filterSuppliers(buildSuppliers(filterSO), query), [filterSO, query]);
const total = useMemo(() => list.reduce((a, s) => a + s.采购金额, 0), [list]);
const totalLines = useMemo(() => list.reduce((a, s) => a + s.采购行数, 0), [list]);
return (
<>
{filterSO && (
<div style={{
display: 'flex', alignItems: 'center', gap: 6, flex: '0 0 auto', marginBottom: 8,
padding: '5px 9px', borderRadius: 8, fontSize: 11.5, fontWeight: 600,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
<Link2 size={12} style={{ flexShrink: 0 }} />
<span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>关联订单 {filterSO} · 仅该单涉及的供应商</span>
<span style={{ flex: 1 }} />
<button onClick={onClearFilter} title="显示全部供应商" style={{ background: 'none', border: 'none', color: tokens.accent, cursor: 'pointer', display: 'flex', padding: 2 }}>
<X size={13} />
</button>
</div>
)}
{/* 汇总条 */}
<div style={{
display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: '0 0 auto',
padding: '6px 10px', marginBottom: 10, borderRadius: 8, fontSize: 12,
background: tokens.kpiCardBg, border: `1px solid ${tokens.border}`, color: tokens.textSub,
}}>
<span>{list.length} 家供应商 · {totalLines} 行采购</span>
<span style={{ color: tokens.accent, fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>¥{money2(total)}</span>
</div>
<ScrollList>
{list.length === 0 && (
<div style={{ padding: '20px 0', textAlign: 'center', fontSize: 13, color: tokens.textMuted }}>
{filterSO ? '该销售订单暂无涉及供应商' : '无匹配供应商'}
</div>
)}
{list.map(s => {
const nc = natureColor(s.性质, tokens);
return (
<div
key={s.供应商编码}
onClick={() => onPickSupplier(s.供应商编码)}
title="点击只看这家供应商的采购单"
style={{
marginBottom: 8, padding: '9px 11px', borderRadius: 9, cursor: 'pointer',
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
transition: 'background .15s, border-color .15s',
}}
>
{/* 行1:简称 + 编码 + 性质 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Users size={12} style={{ color: tokens.textMuted, flexShrink: 0 }} />
<span style={{ fontSize: 13, fontWeight: 700, color: tokens.text, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{s.供应商简称}
</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.供应商编码}</span>
<span style={{ flex: 1 }} />
<span style={{
fontSize: 10.5, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
color: nc.c, background: nc.bg, border: `1px solid ${nc.c}44`, whiteSpace: 'nowrap',
}}>{s.性质}</span>
</div>
{/* 行2:类别 + 部门 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 5 }}>
<span style={{ fontSize: 10.5, color: tokens.textSub, padding: '0 6px', borderRadius: 99, border: `1px solid ${tokens.border}`, whiteSpace: 'nowrap' }}>{s.所属类别}</span>
<span style={{ fontSize: 11, color: tokens.textMuted, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{s.分管部门 || '分管部门未填'}
</span>
</div>
{/* 行3:金额 + 行数 */}
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 5 }}>
<span style={{ fontSize: 14, fontWeight: 800, color: tokens.accent, fontVariantNumeric: 'tabular-nums' }}>¥{money2(s.采购金额)}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 11, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{s.采购行数} 行采购</span>
</div>
</div>
);
})}
</ScrollList>
<div style={{
display: 'flex', alignItems: 'center', gap: 5, flex: '0 0 auto', paddingTop: 6,
fontSize: 10.5, color: tokens.textMuted, borderTop: `1px solid ${tokens.border}`,
}}>
<span style={{ flex: 1 }}>行数与金额为该供应商在本批采购订单中的合计,与采购单页签同源可核对</span>
</div>
</>
);
}
@@ -0,0 +1,610 @@
import { useMemo, useRef } from 'react';
import type { CSSProperties, ReactNode } from 'react';
import { AlertTriangle, Ban, BookOpenCheck, FileSearch, GitCompareArrows, Layers, ListChecks, ShieldQuestion, Terminal } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import type { ThemeTokens } from '../../context/ThemeContext';
import {
PAGE_MAP, PAGE_TALLY_NOTE, NO_PROMISE, EVIDENCE_LEDGER,
ASLT_TIME_ACCOUNT_POC, ASLT_ACCOUNT_TOTAL_HOURS, ASLT_WAIT_PLAN_PCT, ASLT_DAY_GAP_NOTE,
CONFLICT_READINGS, READING_DISCIPLINE_NOTE, POC_ANCHORS,
W0_BLOCKERS, W0_QUESTIONS, ASSERTION_REGISTRY, EXTRA_VERIFY_SCRIPTS, VERIFY_AGGREGATE,
VERIFY_COMMAND, VERIFY_NOTE, GATES, CALIBER_SOURCE_NOTE, SIM_BADGE, dataModeNote, simBadge,
caliberSourceRows, threeSixRows, dataSourceRows, disclosureStats,
MATRIX_CORRECTIONS, MATRIX_CORRECTION_NOTE,
} from '../../data/oee/disclosure';
import { resolveScope, type OeeFilter } from '../../lib/oeeFilters';
/* ══════════════════ 公共小块(自带,不依赖待废弃的品质页签模块) ══════════════════ */
function Chip({ children, color, bg, title }: { children: ReactNode; color: string; bg?: string; title?: string }) {
return (
<span title={title} style={{
fontSize: 10, fontWeight: 700, padding: '1px 7px', borderRadius: 9, whiteSpace: 'nowrap',
color, background: bg ?? `${color}1f`, border: `1px solid ${color}44`, letterSpacing: '0.02em',
}}>{children}</span>
);
}
function Card({ title, icon, right, children, note, full }: {
title: string; icon?: ReactNode; right?: ReactNode; children: ReactNode; note?: ReactNode; full?: boolean;
}) {
const { tokens } = useTheme();
return (
<section className="card-in" style={{
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 11,
padding: '10px 13px 12px', boxShadow: tokens.cardShadow, minWidth: 0,
gridColumn: full ? '1 / -1' : undefined, display: 'flex', flexDirection: 'column',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexShrink: 0 }}>
<span style={{ width: 3, height: 13, borderRadius: 2, background: tokens.accent, flexShrink: 0 }} />
{icon}
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap' }}>{title}</span>
<span style={{ flex: 1 }} />
{right}
</div>
<div style={{ minWidth: 0 }}>{children}</div>
{note && <div style={{ marginTop: 7, fontSize: 10.5, lineHeight: 1.55, color: tokens.textMuted }}>{note}</div>}
</section>
);
}
function Th({ children, right }: { children: ReactNode; right?: boolean }) {
const { tokens } = useTheme();
return (
<th style={{
textAlign: right ? 'right' : 'left', padding: '6px 8px', fontSize: 11, fontWeight: 600,
color: tokens.textSub, background: tokens.tableHeaderBg, whiteSpace: 'nowrap',
borderBottom: `1px solid ${tokens.border}`, position: 'sticky', top: 0, zIndex: 1,
}}>{children}</th>
);
}
function Td({ children, right, mono, color, bold, nowrap, breakAny }: {
children: ReactNode; right?: boolean; mono?: boolean; color?: string; bold?: boolean; nowrap?: boolean; breakAny?: boolean;
}) {
const { tokens } = useTheme();
return (
<td style={{
textAlign: right ? 'right' : 'left', padding: '5px 8px', fontSize: 11.5,
color: color ?? tokens.textSub, borderBottom: `1px solid ${tokens.borderSub}`,
fontVariantNumeric: mono ? 'tabular-nums' : undefined,
fontFamily: mono ? 'ui-monospace, monospace' : undefined,
fontWeight: bold ? 700 : undefined, verticalAlign: 'top', lineHeight: 1.5,
whiteSpace: nowrap ? 'nowrap' : undefined,
overflowWrap: breakAny ? 'anywhere' : undefined,
}}>{children}</td>
);
}
function Table({ head, children, maxHeight }: { head: ReactNode; children: ReactNode; maxHeight?: number }) {
const { tokens } = useTheme();
return (
<div style={{ overflow: 'auto', maxHeight, border: `1px solid ${tokens.borderSub}`, borderRadius: 8 }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead><tr>{head}</tr></thead>
<tbody>{children}</tbody>
</table>
</div>
);
}
/** 一行等分的统计砖(看板红线:等分、stretch、底边对齐) */
function Tiles({ items }: { items: { label: string; value: string; sub?: string; color?: string }[] }) {
const { tokens } = useTheme();
return (
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
{items.map((it) => (
<div key={it.label} style={{
flex: 1, minWidth: 0, textAlign: 'center', padding: '6px 8px', borderRadius: 9,
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
display: 'flex', flexDirection: 'column', justifyContent: 'center',
}}>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</div>
<div style={{ fontSize: 19, fontWeight: 800, color: it.color ?? tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.25 }}>{it.value}</div>
{it.sub && <div style={{ fontSize: 9.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</div>}
</div>
))}
</div>
);
}
const SECTIONS = [
{ id: 'pages', label: '页面映射', Icon: Layers },
{ id: 'nopromise', label: '不承诺清单', Icon: Ban },
{ id: 'caliber', label: '口径出处', Icon: BookOpenCheck },
{ id: 'six', label: '三套六分类', Icon: GitCompareArrows },
{ id: 'readings', label: '同名不同口径', Icon: AlertTriangle },
{ id: 'sources', label: '数据来源', Icon: FileSearch },
{ id: 'w0', label: 'W0 阻塞与追问', Icon: ShieldQuestion },
{ id: 'assert', label: '断言核验', Icon: ListChecks },
] as const;
interface Props {
/** 全局筛选:本页的范围/口径/业务日标签与顶栏同源,不另存一份 */
filter: OeeFilter;
}
/**
* 「说明与对照」页 —— 建议书 §5.2.2 第 10 页,P0,必须做实且最先做。
*
* 评审现场的防穿帮页:客户问「这页呢」「这数哪来的」「你到底不承诺什么」,
* 答案都在这里,主动出示,不等被问。
*
* ★ 本页所有计数都来自 data/oee/disclosure.ts 的现算函数,视图不写死统计数字;
* 只有 POC 供应商实测值与文档章节映射是转录常量(它们不是我方可推算的量)。
*/
export default function DisclosureView({ filter }: Props) {
const { tokens } = useTheme();
const s = useMemo(() => disclosureStats(), []);
const scope = useMemo(() => resolveScope(filter), [filter]);
const calibers = useMemo(() => caliberSourceRows(), []);
const six = useMemo(() => threeSixRows(), []);
const sources = useMemo(() => dataSourceRows(), []);
const sections = SECTIONS;
const refs = useRef<Record<string, HTMLDivElement | null>>({});
const jump = (id: string) => refs.current[id]?.scrollIntoView({ behavior: 'smooth', block: 'start' });
const anchor = (id: string) => (el: HTMLDivElement | null) => { refs.current[id] = el; };
const groupRow = (g: { group: string; total: number; real: number; placeholder: number }) => (
<tr key={g.group}>
<Td bold color={tokens.text}>{g.group}</Td>
<Td right mono>{g.total}</Td>
<Td right mono color={tokens.accent}>{g.real}</Td>
<Td right mono color={tokens.textMuted}>{g.placeholder}</Td>
</tr>
);
const th = (t: string, right?: boolean) => <Th key={t} right={right}>{t}</Th>;
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 }}>
{/* 抬头:本页用途 + 与顶栏同源的范围/口径/业务日标签 */}
<div style={{
display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
padding: '9px 12px', borderRadius: 11,
background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
<Terminal size={15} color={tokens.accent} style={{ flexShrink: 0 }} />
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text }}>
说明与对照 · 评审防穿帮页
</span>
{simBadge() && <Chip color={tokens.textMuted} title={dataModeNote()}>{simBadge()}</Chip>}
<Chip color={tokens.textSub}>业务日 {scope.bizDate}</Chip>
<Chip color={scope.wired ? tokens.textSub : tokens.warning} title={scope.gap ?? scope.coverageNote}>
{scope.scopeLabel}
</Chip>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>
{s.pageTotal} 页映射 · {s.noPromiseTotal} 条不承诺 · {s.caliberTotal} 项口径出处 · {s.assertionCount} 条断言
</span>
</div>
{/* 章节导航:点一下滚到对应卡片,评审时不必翻长页 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{sections.map(({ id, label, Icon }) => (
<button key={id} onClick={() => jump(id)} className="ghost-btn" style={{
display: 'flex', alignItems: 'center', gap: 5, cursor: 'pointer',
fontSize: 11.5, fontWeight: 600, padding: '3px 10px', borderRadius: 16, whiteSpace: 'nowrap',
color: tokens.textSub, background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<Icon size={12} color={tokens.accent} />{label}
</button>
))}
</div>
{/* ══════════ 一、20 页映射 ══════════ */}
<div ref={anchor('pages')} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 268px', gap: 10, alignItems: 'stretch' }}>
<Card title={`POC ${s.pageTotal} 页 → 本原型映射`} icon={<Layers size={13} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>{s.pageTotal} 页</Chip>}
note={PAGE_TALLY_NOTE}>
<Table maxHeight={330} head={['#', '页面', '分组', '文档核对表', '本原型', '阶段', '方案章节', '验收点'].map((t) => th(t))}>
{PAGE_MAP.map((p) => (
<tr key={p.no} style={{ background: p.no % 2 ? tokens.tableRowAlt : 'transparent' }}>
<Td mono right>{p.no}</Td>
<Td bold nowrap color={tokens.text}>{p.name}</Td>
<Td nowrap>{p.group}</Td>
<Td>
<Chip color={p.tally === '九页做实' ? tokens.accent : tokens.textMuted}>{p.tally}</Chip>
</Td>
<Td>
<Chip color={p.status === 'real' ? tokens.info : tokens.textMuted}
title={p.status === 'real' ? `做实:${p.landing}` : `占位:${p.capability}`}>
{p.status === 'real' ? '做实' : '占位'}
</Chip>
</Td>
<Td>{p.stage}</Td>
<Td color={tokens.textMuted}>{p.chapter}</Td>
<Td color={tokens.textMuted}>{p.acceptance}</Td>
</tr>
))}
</Table>
</Card>
<Card title="分组核对(两个口径并列)" icon={<GitCompareArrows size={13} color={tokens.accent} />}
note={`左表=建议书 §5.2.3 核对表原值(${s.tallyReal}/${s.tallyPlaceholder});右表=本原型实际实现(${s.pageReal}/${s.pagePlaceholder})。差异页已在左侧 status 列逐一披露,不圆整。`}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 9 }}>
<div>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 700, marginBottom: 4 }}>文档核对表 tally</div>
<Table head={['分组', '页数', '做实', '占位'].map((t, i) => th(t, i > 0))}>
{s.tallyGroups.map(groupRow)}
<tr>
<Td bold color={tokens.text}>合计</Td>
<Td right mono bold color={tokens.text}>{s.pageTotal}</Td>
<Td right mono bold color={tokens.accent}>{s.tallyReal}</Td>
<Td right mono bold color={tokens.textMuted}>{s.tallyPlaceholder}</Td>
</tr>
</Table>
</div>
<div>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 700, marginBottom: 4 }}>本原型实际 status</div>
<Table head={['分组', '页数', '做实', '占位'].map((t, i) => th(t, i > 0))}>
{s.groups.map(groupRow)}
<tr>
<Td bold color={tokens.text}>合计</Td>
<Td right mono bold color={tokens.text}>{s.pageTotal}</Td>
<Td right mono bold color={tokens.info}>{s.pageReal}</Td>
<Td right mono bold color={tokens.textMuted}>{s.pagePlaceholder}</Td>
</tr>
</Table>
</div>
</div>
</Card>
</div>
{/* ══════════ 二、11 条不承诺清单 ══════════ */}
<div ref={anchor('nopromise')}>
<Card title={`原型明确不承诺的 ${s.noPromiseTotal} 件事`} icon={<Ban size={13} color={tokens.danger} />}
right={<Chip color={tokens.danger}>主动出示,不等被问</Chip>}
note={`出处:建议书 §1.2(6 条)+ §6.7.2(7 条,从价值角度重述)+ 规划书 §8「Demo 不承诺等保」。两表去重合并后恰为 ${s.noPromiseTotal} 条,逐条标注来源,不新增无出处的承诺。`}>
<Table maxHeight={300} head={['#', '不承诺项', '原型里的实际做法', '生产阶段何时兑现', '出处'].map((t) => th(t))}>
{NO_PROMISE.map((r) => (
<tr key={r.no} style={{ background: r.no % 2 ? tokens.tableRowAlt : 'transparent' }}>
<Td mono right>{r.no}</Td>
<Td bold color={tokens.text}>{r.item}</Td>
<Td>{r.prototype}</Td>
<Td color={tokens.textMuted}>{r.production}</Td>
<Td color={tokens.textMuted}>{r.source}</Td>
</tr>
))}
</Table>
</Card>
</div>
{/* ══════════ 三、28 项口径出处 ══════════ */}
<div ref={anchor('caliber')} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Tiles items={[
{ label: '口径项', value: String(s.caliberTotal), sub: `版本 ${s.caliberVersion}` },
{ label: 'P0(能不能算)', value: String(s.caliberP0), sub: '标灰不标绿', color: tokens.warning },
{ label: 'P1 / P2', value: `${s.caliberP1} / ${s.caliberP2}`, sub: '默认值生效中' },
{ label: '已签字', value: String(s.caliberSigned), sub: '本次不安排工作坊', color: tokens.textMuted },
{ label: '敏感性口径项', value: String(s.caliberSensitivityKeys), sub: `${s.sensitivityIssueCount} 项议题` },
{ label: '生效日', value: s.effectiveFrom, sub: '切换生成新版本' },
]} />
<Card title={`${s.caliberTotal} 项口径逐条出处`} icon={<BookOpenCheck size={13} color={tokens.accent} />}
right={<Chip color={tokens.warning} title={s.signoffNote}>待 IE 签字</Chip>}
note={CALIBER_SOURCE_NOTE + ' 两个「优先级」概念不可混:priority P0/P1/P2 影响「能不能算」;isSensitivityKey 影响「算出来是多少」,两者不是同一集合。'}>
<Table maxHeight={340} head={['编号', '口径项', '默认值', '优先级', '归口', '影响范围', '敏感性议题', '状态', '出处'].map((t) => th(t))}>
{calibers.map((c) => (
<tr key={c.id} style={{ background: c.priority === 'P0' ? tokens.tableRowAlt : 'transparent' }}>
<Td mono bold nowrap color={tokens.text}>{c.id}</Td>
<Td>{c.name}</Td>
<Td color={tokens.textSub}>{c.defaultValue}</Td>
<Td>
{/* ★ P0 一律灰(warning 底 + muted 字),绝不 success 绿 */}
<Chip color={c.priority === 'P0' ? tokens.warning : tokens.textMuted}>{c.priority}</Chip>
</Td>
<Td nowrap>{c.owner}</Td>
<Td color={tokens.textMuted}>{c.scope}</Td>
<Td>{c.sensitivityIssue ? <Chip color={tokens.info}>{c.sensitivityIssue}</Chip> : <span style={{ color: tokens.textMuted }}>—</span>}</Td>
<Td color={tokens.textMuted}>{c.statusLabel}</Td>
<Td color={tokens.textMuted}>{c.source}</Td>
</tr>
))}
</Table>
</Card>
</div>
{/* ══════════ 四、三套「六」分类 ══════════ */}
<div ref={anchor('six')} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 10, alignItems: 'stretch' }}>
<Card title="三套「六」分类并列(永不混用)" icon={<GitCompareArrows size={13} color={tokens.accent} />}
note={`六-1 与六-2 各自成立求和恒等式;六-3 是事件表归口用词,不成立恒等式,其中 ${s.grossNullEvents} 条计划类事件不进六-1。断言必须分两条写:null 键=${s.grossNullKeys} 个、覆盖事件=${s.grossNullEvents} 条;写成「null 项数=${s.grossNullEvents}」是错的。`}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{six.map((r) => (
<div key={r.key} style={{
padding: '7px 9px', borderRadius: 9, minWidth: 0,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 4 }}>
<Chip color={tokens.accent}>{r.key}</Chip>
<span style={{ fontSize: 11.5, fontWeight: 700, color: tokens.text }}>{r.name}</span>
<span style={{ flex: 1 }} />
<Chip color={r.hasIdentity ? tokens.info : tokens.textMuted}>
{r.hasIdentity ? '有恒等式' : '无恒等式'}
</Chip>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 4 }}>
{r.members.map((m) => (
<span key={m} style={{
fontSize: 10, padding: '1px 6px', borderRadius: 6, color: tokens.textSub,
background: tokens.tableHeaderBg, border: `1px solid ${tokens.borderSub}`, whiteSpace: 'nowrap',
}}>{m}</span>
))}
</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, lineHeight: 1.5 }}>{r.usage}|{r.identity}</div>
<div style={{ fontSize: 9.5, color: tokens.textMuted, marginTop: 2 }}>承载:{r.carrier}|{r.source}</div>
</div>
))}
</div>
</Card>
<Card title="六-2 的 POC 实测时间账(照录不改)" icon={<AlertTriangle size={13} color={tokens.warning} />}
note={ASLT_DAY_GAP_NOTE}>
<Table head={['类', '时长(h)', '占比(%)'].map((t, i) => th(t, i > 0))}>
{ASLT_TIME_ACCOUNT_POC.map((r) => (
<tr key={r.cls}>
<Td bold color={tokens.text}>{r.cls}</Td>
<Td right mono>{r.hours.toFixed(2)}</Td>
<Td right mono color={r.cls === 'Wait' || r.cls === 'Plan' ? tokens.warning : tokens.textSub}>{r.pct.toFixed(2)}</Td>
</tr>
))}
<tr style={{ background: tokens.tableHeaderBg }}>
<Td bold color={tokens.text}>合计</Td>
<Td right mono bold color={tokens.text}>{ASLT_ACCOUNT_TOTAL_HOURS.toFixed(2)}</Td>
<Td right mono bold color={tokens.text}>{s.asltPocSumPct.toFixed(2)}</Td>
</tr>
</Table>
<div style={{ marginTop: 8, display: 'flex', alignItems: 'stretch', gap: 8 }}>
<div style={{
flex: 1, minWidth: 0, padding: '6px 9px', borderRadius: 9,
background: tokens.warningBg, border: `1px solid ${tokens.warning}44`,
}}>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 600 }}>Wait + Plan</div>
<div style={{ fontSize: 19, fontWeight: 800, color: tokens.warning, fontVariantNumeric: 'tabular-nums' }}>{ASLT_WAIT_PLAN_PCT}%</div>
<div style={{ fontSize: 9.5, color: tokens.textMuted }}>物料保障与排产优先于设备维修</div>
</div>
<div style={{
flex: 1, minWidth: 0, padding: '6px 9px', borderRadius: 9,
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
}}>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 600 }}>残差</div>
<div style={{ fontSize: 19, fontWeight: 800, color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>0.000000h</div>
<div style={{ fontSize: 9.5, color: tokens.textMuted }}>POC 实测;日历日 32 / 时间账 31</div>
</div>
</div>
</Card>
</div>
{/* ══════════ 五、同名不同口径的读数 ══════════ */}
<div ref={anchor('readings')} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Card title="同名不同口径:每个数字必须三标签齐全" icon={<AlertTriangle size={13} color={tokens.danger} />}
right={<Chip color={tokens.danger}>风险 P4</Chip>}
note={READING_DISCIPLINE_NOTE}>
<Table maxHeight={300} head={['区域', '读数', '指标', '线体范围', '时间窗', '口径版本 / 口径名', '说明', '出处'].map((t) => th(t))}>
{CONFLICT_READINGS.map((r, i) => (
<tr key={`${r.region}-${r.value}`} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
<Td><Chip color={tokens.accent}>{r.region}</Chip></Td>
<Td mono bold nowrap color={tokens.text}>{r.value}</Td>
<Td breakAny>{r.metric}</Td>
<Td breakAny color={tokens.textSub}>{r.scope}</Td>
<Td nowrap color={tokens.textSub}>{r.window}</Td>
<Td breakAny color={tokens.textSub}>{r.caliber}</Td>
<Td breakAny color={tokens.textMuted}>{r.note}</Td>
<Td breakAny color={tokens.textMuted}>{r.source}</Td>
</tr>
))}
</Table>
</Card>
<Card title="三站 POC 基线与改善杠杆" icon={<Layers size={13} color={tokens.accent} />}
note="目标值为〔方案〕给出的改善方向,不是承诺值(见不承诺清单第 7、8 条)。">
<div style={{ display: 'flex', alignItems: 'stretch', gap: 9 }}>
{POC_ANCHORS.map((a) => (
<div key={a.region} style={{
flex: 1, minWidth: 0, padding: '8px 10px', borderRadius: 10,
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
display: 'flex', flexDirection: 'column', gap: 4,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Chip color={tokens.accent}>{a.region}</Chip>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 9.5, color: tokens.textMuted }}>目标 {a.target}</span>
</div>
<div style={{ fontSize: 24, fontWeight: 800, color: tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.15 }}>{a.oee}</div>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontVariantNumeric: 'tabular-nums' }}>{a.apq}</div>
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.5 }}>{a.baselineNote}</div>
<div style={{ flex: 1 }} />
<div style={{ fontSize: 10, color: tokens.textSub, lineHeight: 1.5, borderTop: `1px solid ${tokens.borderSub}`, paddingTop: 4 }}>{a.lever}</div>
</div>
))}
</div>
</Card>
</div>
{/* ══════════ 六、数据来源标注 ══════════ */}
<div ref={anchor('sources')} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 300px', gap: 10, alignItems: 'stretch' }}>
<Card title="本原型到底读了什么(分层来源)" icon={<FileSearch size={13} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title={dataModeNote()}>{s.mode} 模式</Chip>}
note={dataModeNote() + ' ' + s.coverageGap}>
<Table maxHeight={300} head={['层', '内容 · 模块', '出处 / 模拟', '缺口 / 待确认'].map((t) => th(t))}>
{sources.map((r) => (
<tr key={r.layer} style={{ background: r.simulated ? tokens.tableRowAlt : 'transparent' }}>
<Td bold nowrap color={tokens.text}>{r.layer}</Td>
<Td breakAny>
{r.what}
<div style={{ marginTop: 3, fontSize: 10.5, fontFamily: 'ui-monospace, monospace', color: tokens.textMuted }}>{r.module}</div>
</Td>
<Td nowrap>
<Chip color={r.tag === 'POC' ? tokens.info : r.simulated ? tokens.textMuted : tokens.accent}>〔{r.tag}〕</Chip>
{r.simulated && <div style={{ marginTop: 4 }}><Chip color={tokens.textMuted}>{SIM_BADGE}</Chip></div>}
</Td>
<Td breakAny color={r.gap ? tokens.warning : tokens.textMuted}>{r.gap ?? '无'}</Td>
</tr>
))}
</Table>
</Card>
<Card title="出处标记字典" icon={<BookOpenCheck size={13} color={tokens.accent} />}
note="页面每个数字旁都要能落到其中之一。〔POC〕是 POC 阶段实测结论、作参考基线;「模拟」是本原型合成种子,不是客户生产实况。">
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{EVIDENCE_LEDGER.map((e) => (
<div key={e.tag} style={{
padding: '6px 8px', borderRadius: 8, minWidth: 0,
background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
<Chip color={e.tag === 'POC' ? tokens.info : e.simulated ? tokens.textMuted : tokens.accent}>{e.label}</Chip>
{e.simulated && <Chip color={tokens.textMuted}>非生产实况</Chip>}
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.5 }}>{e.meaning}</div>
</div>
))}
</div>
</Card>
</div>
{/* ══════════ 六-2、附件判定矩阵修正清单(核验报告 §3) ══════════ */}
<div>
<Card title={`附件判定矩阵修正清单(${MATRIX_CORRECTIONS.length} 项)`} icon={<GitCompareArrows size={13} color={tokens.warning} />}
right={<Chip color={tokens.warning}>矩阵 ≠ 实测处逐条披露</Chip>}
note={MATRIX_CORRECTION_NOTE}>
<Table maxHeight={320} head={['#', '矩阵声称', '独立重算实测', '口径处理'].map((t) => th(t))}>
{MATRIX_CORRECTIONS.map((r) => (
<tr key={r.no} style={{ background: r.no % 2 ? tokens.tableRowAlt : 'transparent' }}>
<Td bold color={tokens.text}>{r.no}</Td>
<Td>{r.claim}</Td>
<Td color={tokens.accent}>{r.measured}</Td>
<Td color={tokens.textMuted}>{r.action}</Td>
</tr>
))}
</Table>
</Card>
</div>
{/* ══════════ 七、W0 阻塞项与追问清单 ══════════ */}
<div ref={anchor('w0')} style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 10, alignItems: 'stretch' }}>
<Card title="W0 四件阻塞项" icon={<ShieldQuestion size={13} color={tokens.warning} />}
right={<Chip color={tokens.warning}>{s.blockerSelfSolvable.length} / {s.blockerCount} 我方可自解</Chip>}
note="W0 不做完,W1 不开工。四件事里只有 W0-1 我方能自行解决(已改 5203)。W0-2/W0-3 未签字时 W1 仍可开工,但必须用附录 E 默认值、全站标「待 IE 签字」、配置中心 P0 标灰不标绿——不得假装已签字。">
<Table head={['#', '阻塞项', '归口', '交付物', '状态'].map((t) => th(t))}>
{W0_BLOCKERS.map((b) => (
<tr key={b.id}>
<Td mono bold nowrap color={tokens.text}>{b.id}</Td>
<Td>{b.item}</Td>
<Td color={tokens.textMuted}>{b.owner}</Td>
<Td breakAny color={tokens.textMuted}>{b.deliverable}</Td>
<Td color={b.selfSolvable ? tokens.info : tokens.warning}>
<span style={{ fontWeight: 700 }}>{b.status}</span>
</Td>
</tr>
))}
</Table>
</Card>
<Card title={`W0-4 随表追问清单(${s.questionCount} 条)`} icon={<ShieldQuestion size={13} color={tokens.accent} />}
note="拿到三份基准表时一并问清,否则原型只能标「待确认」。Q1 与 Q4 会直接改变核心结论的分母与考核基线。">
<Table maxHeight={260} head={['#', '追问', '为什么必须问', '依据'].map((t) => th(t))}>
{W0_QUESTIONS.map((q) => (
<tr key={q.id} style={{ background: q.id === 'Q1' || q.id === 'Q4' ? tokens.warningBg : 'transparent' }}>
<Td mono bold nowrap color={tokens.text}>{q.id}</Td>
<Td>{q.q}</Td>
<Td color={tokens.textMuted}>{q.why}</Td>
<Td color={tokens.textMuted}>{q.source}</Td>
</tr>
))}
</Table>
</Card>
</div>
{/* ══════════ 八、断言核验登记 ══════════ */}
<div ref={anchor('assert')} style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
<Card title={`${s.assertionCount} 条断言 → 校验脚本登记`} icon={<ListChecks size={13} color={tokens.accent} />}
right={
<span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Chip color={tokens.accent}>{s.registryScriptCount} 脚本</Chip>
<Chip color={tokens.textMuted}>+ {s.extraVerifyCount} 实施附加</Chip>
<Chip color={tokens.info}>{VERIFY_COMMAND}</Chip>
</span>
}
note={VERIFY_NOTE}>
<Table maxHeight={330} head={['断言', '名称', '数据层不变量 / 核心校验', '脚本', '落地阶段'].map((t) => th(t))}>
{ASSERTION_REGISTRY.map((a) => (
<tr key={a.script} style={{ background: a.kind === 'extra' ? tokens.tableRowAlt : 'transparent' }}>
<Td mono bold color={a.kind === 'extra' ? tokens.textMuted : tokens.accent}>{a.id}</Td>
<Td bold color={tokens.text}>{a.name}</Td>
<Td color={tokens.textMuted}>{a.invariant}</Td>
<Td mono breakAny>{a.script}</Td>
<Td>
<Chip color={a.stage.includes('已落地') ? tokens.info : tokens.textMuted}>{a.stage}</Chip>
</Td>
</tr>
))}
{EXTRA_VERIFY_SCRIPTS.map((e) => (
<tr key={e.script} style={{ background: tokens.tableRowAlt }}>
<Td mono color={tokens.textMuted}>附加</Td>
<Td bold color={tokens.text}>{e.name}</Td>
<Td color={tokens.textMuted}>实施中另加,不在规划书 {s.assertionCount} 条内,守同一批纪律</Td>
<Td mono breakAny>{e.script}</Td>
<Td><Chip color={tokens.info}>{e.stage}</Chip></Td>
</tr>
))}
<tr style={{ background: tokens.tableHeaderBg }}>
<Td mono bold color={tokens.text}>入口</Td>
<Td bold color={tokens.text}>聚合执行</Td>
<Td color={tokens.textMuted}>依次跑全部脚本,打印汇总,任一失败则非零退出</Td>
<Td mono bold>{VERIFY_AGGREGATE}</Td>
<Td><Chip color={tokens.warning}>W1-G</Chip></Td>
</tr>
</Table>
</Card>
<Card title="四道阶段门" icon={<ListChecks size={13} color={tokens.accent} />}
note="门禁不通过就停下修,不带着问题横向扩展。本页只登记判据,通过与否以现场执行输出为准。">
<div style={{ display: 'flex', alignItems: 'stretch', gap: 9 }}>
{GATES.map((g) => (
<div key={g.id} style={{
flex: 1, minWidth: 0, padding: '8px 10px', borderRadius: 10,
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
display: 'flex', flexDirection: 'column', gap: 4,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<Chip color={tokens.accent}>{g.id}</Chip>
<span style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 600 }}>{g.when}</span>
</div>
<div style={{ fontSize: 10.5, color: tokens.text, lineHeight: 1.5 }}>{g.criterion}</div>
<div style={{ flex: 1 }} />
<div style={{ fontSize: 9.5, color: tokens.textMuted, lineHeight: 1.5, borderTop: `1px solid ${tokens.borderSub}`, paddingTop: 4 }}>
不通过:{g.onFail}
</div>
</div>
))}
</div>
</Card>
</div>
{/* 页脚:本页自身的出处与纪律 */}
<div style={{
padding: '8px 12px', borderRadius: 10, fontSize: 10.5, lineHeight: 1.6,
color: tokens.textMuted, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`,
}}>
本页数据源:<span style={{ fontFamily: 'ui-monospace, monospace' }}>src/data/oee/disclosure.ts</span>
({s.pageTotal} 页映射与 POC 实测值为转录常量,逐条带出处;其余计数全部现算自 calibers28 / events48 / devices / oeeService)。
校验脚本:<span style={{ fontFamily: 'ui-monospace, monospace' }}>scripts/verify-oee-disclosure.ts</span>。
纪律:未签字不标绿 · POC 数字只作参考基线 · 三套六分类不混用 · 同名读数三标签齐全 · 文档冲突显式披露不圆整。
</div>
</div>
);
}
/** 供视图外壳渲染页签标题时用(与 SECTIONS 同源,避免两处各写一份) */
export const DISCLOSURE_SECTION_COUNT = SECTIONS.length;
/** 主题令牌类型再导出,方便外壳按同一套令牌渲染页签条 */
export type DisclosureTokens = ThemeTokens;
/** 卡片容器样式:与其余页签共用同一套圆角/边框,避免本页看起来像另一个应用 */
export const disclosureShellStyle = (tk: ThemeTokens): CSSProperties => ({
display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0,
color: tk.text,
});
@@ -0,0 +1,316 @@
/**
* 数据质量(risk 页签 · W2-B)。
*
* ★ 治理台的核心诚实性约束:**缺证据 ≠ 通过**。
* 12 条规则里,所需输入没给的记入 notEvaluated 并标灰(不标绿),
* 绝不静默当作"未命中"。阻断级(DQ-06/08/12)命中即暂停当日结论发布,
* 页面显示「结论暂缓发布 + 原因 + 补录入口」,而不是一个看起来正常的数字。
*
* ★ 三态分开:未归因 IDLE(进池待归因,DQ-06)≠ 未采集 UNKNOWN(日志断流,
* 不计 PPT 分母,DQ-10)≠ 无生产。把空档当无生产会悄悄缩小分母。
*
* 纪律:
* ① 数字只从 L3 day.dq / day.segments / day.buckets 取,规则字典经 L3 再导出
* (DQ_RULES/DQ_RULE_BY_CODE/DQ_DEFAULTS),视图不直接 import 引擎、不二次计算。
* ② 处置动作三类(自动修正/标注/阻断)分色显示;自动修正只在 L1 采集层落地,
* L2 引擎只报告"应如何修正",保持纯函数可重放、修正过程可审计。
* ③ 仅对日志贯通的锚点单机出数;非锚点/聚合范围不显示 0,照实给缺口。
*/
import { ShieldCheck, AlertTriangle, ClipboardList, Database, ListChecks } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import {
DQ_RULES, DQ_RULE_BY_CODE, DQ_DEFAULTS, dekDays,
type DqDisposition,
} from '../../lib/oeeService';
import { ENTRY_FORM_LABEL } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, GapBox, EmptyBox,
grid2, pageStyle, pct, dur,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
/** 未归因池原因码 → 中文(UnknownEvent.reason 五值)。 */
const REASON_LABEL: Record<string, string> = {
NO_PAIR: '无配对事件', NO_LOT: '无批次窗口', NO_SOURCE: '无来源事件',
GAP_FILL: '间隙填充留白', AMBIGUOUS: '归属歧义',
};
/** 问题单状态 → 中文与色(OPEN 待处理 / ASSIGNED 已派单 / CLOSED 已关闭)。 */
const ISSUE_STATE_LABEL: Record<string, string> = { OPEN: '待处理', ASSIGNED: '已派单', CLOSED: '已关闭' };
export default function OeeDq({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const day = scope.day;
/* demo:从内置 3 个业务日种子聚合 DQ 发现,不连接后端。 */
const findings = dekDays().flatMap((d) => d.dq.issues);
if (!day) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="数据质量" icon={<ShieldCheck size={15} color={tokens.accent} />} />
<EmptyBox>
数据质量治理仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。<br />
{scope.gap ?? scope.coverageNote}
</EmptyBox>
</div>
);
}
const dq = day.dq;
const stats = dq.stats;
const tot = day.segments.totals;
const pool = day.segments.unknown;
/* 规则评估状态索引:已评估 / 缺证据(标灰不标绿)/ 命中数。全部取自 L3,不在视图重判。 */
const evaluatedSet = new Set(dq.evaluated);
const notEvalMap = new Map(dq.notEvaluated.map((n) => [n.code, n.missing]));
const hitCount = (code: string) => dq.issues.filter((i) => i.code === code).length;
const dispoColor = (d: DqDisposition) => (d === 'BLOCK' ? tokens.danger : d === 'ANNOTATE' ? tokens.warning : tokens.info);
const dispoLabel = (d: DqDisposition) => (d === 'BLOCK' ? '阻断' : d === 'ANNOTATE' ? '标注' : '自动修正');
const stateColor = (s: string) => (s === 'CLOSED' ? tokens.success : s === 'ASSIGNED' ? tokens.info : tokens.warning);
const overThreshold = stats.unattributedPct > DQ_DEFAULTS.unattributedBlockPct;
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="数据质量"
icon={<ShieldCheck size={15} color={tokens.accent} />}
extra={<Chip color={dq.blocked ? tokens.danger : tokens.textSub}>{dq.blocked ? '结论暂缓发布' : '当日结论可发布'}</Chip>}
/>
{/* 发布门禁横幅:阻断→danger,缺证据→warning,全清→success。话术由 L3 publishNotice 原文给出。 */}
{dq.blocked ? (
<div style={{
padding: '10px 13px', borderRadius: 11, minWidth: 0,
background: `${tokens.danger}14`, border: `1px solid ${tokens.danger}55`,
display: 'flex', gap: 10, alignItems: 'flex-start',
}}>
<AlertTriangle size={18} color={tokens.danger} style={{ flexShrink: 0, marginTop: 1 }} />
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 800, color: tokens.danger, marginBottom: 3 }}>结论暂缓发布</div>
<div style={{ fontSize: 11.5, color: tokens.textSub, lineHeight: 1.6 }}>{dq.publishNotice}</div>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 }}>
{dq.blockedBy.map((c) => <Chip key={c} color={tokens.danger}>{c} {DQ_RULE_BY_CODE[c].name}</Chip>)}
</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 6, lineHeight: 1.55 }}>
补录入口:中央「录入台」页签的停机归因单 / 等待登记单(D 类事件 5M1E 人工补录)。
提交后按口径重算当日 OEE:未归因占比下降、DQ-06 可能解除,口径版本号递增留痕;阻断解除前结论仍暂缓发布。
</div>
</div>
</div>
) : (
<div style={{
padding: '9px 13px', borderRadius: 11, minWidth: 0,
background: dq.notEvaluated.length ? `${tokens.warning}12` : `${tokens.success}12`,
border: `1px solid ${dq.notEvaluated.length ? tokens.warning : tokens.success}44`,
display: 'flex', gap: 9, alignItems: 'center',
}}>
<ShieldCheck size={16} color={dq.notEvaluated.length ? tokens.warning : tokens.success} style={{ flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub, lineHeight: 1.55, minWidth: 0 }}>{dq.publishNotice}</span>
</div>
)}
{/* 治理概览砖:一行等分(看板红线)。未归因占比是比例×100,阈值同源 DQ_DEFAULTS。 */}
<Tiles items={[
{ label: '已评估规则', value: `${dq.evaluated.length}/12`, sub: '有证据', color: tokens.textSub, title: '输入齐备、已实际判定的规则数' },
{ label: '缺证据未评估', value: `${dq.notEvaluated.length}`, sub: '标灰不标绿', color: dq.notEvaluated.length ? tokens.textMuted : tokens.textSub, title: '缺证据 ≠ 通过:notEvaluated 不视为未命中' },
{ label: '命中问题', value: `${dq.issues.length}`, sub: `自动${stats.autoFix}·标注${stats.annotate}·阻断${stats.block}`, color: dq.issues.length ? tokens.warning : tokens.textSub },
{ label: '阻断项', value: `${dq.blockedBy.length}`, sub: dq.blocked ? '结论暂缓发布' : '无阻断', color: dq.blocked ? tokens.danger : tokens.textSub, title: '仅 DQ-06/08/12 三条阻断级' },
{ label: '未归因占比', value: `${pct(stats.unattributedPct)}%`, sub: `阈值 ${pct(DQ_DEFAULTS.unattributedBlockPct)}%`, color: overThreshold ? tokens.danger : tokens.textSub, title: 'DQ-06:未归因时长(IDLE 残差)÷ PPT,超阈值阻断' },
{ label: '重复率', value: `${pct(stats.duplicateRate)}%`, sub: `丢弃 ${stats.duplicateCount} 条`, color: tokens.textSub, title: 'DQ-09:dedup_key 命中,丢弃并计数,不让时长翻倍' },
]} />
{/* 第一行:12 条规则评估台账 + 处置分布与关键统计 */}
<div style={grid2}>
<Card
title="12 条规则评估台账"
icon={<ListChecks size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>缺证据 ≠ 通过</Chip>}
note="判定条件与处置动作照录规划书 DQ 表原文。已评估=有证据并实际判定;缺证据=标灰不标绿,治理台据此提示补证;阻断级命中即暂停当日结论发布。"
>
<Table head={<>
<Th>规则</Th><Th>处置</Th><Th>评估状态</Th><Th right>命中</Th>
</>}>
{DQ_RULES.map((r) => {
const isEval = evaluatedSet.has(r.code);
const missing = notEvalMap.get(r.code);
const hits = hitCount(r.code);
return (
<tr key={r.code}>
<Td bold>
<span title={r.condition} style={{ color: r.blocking ? tokens.danger : tokens.textSub }}>{r.code}</span>
<span style={{ color: tokens.textMuted, fontWeight: 400 }}> {r.name}</span>
</Td>
<Td><Chip color={dispoColor(r.disposition)}>{dispoLabel(r.disposition)}</Chip></Td>
<Td>
{isEval
? <Chip color={tokens.textSub}>已评估</Chip>
: <Chip color={tokens.textMuted} title={missing}>缺证据·未评估</Chip>}
{missing && <div style={{ fontSize: 9.5, color: tokens.textMuted, marginTop: 2, lineHeight: 1.4 }}>缺:{missing}</div>}
</Td>
<Td right mono bold color={hits > 0 ? (r.blocking ? tokens.danger : tokens.warning) : tokens.textMuted}>
{isEval ? (hits > 0 ? `${hits} 项` : '未命中') : '—'}
</Td>
</tr>
);
})}
</Table>
</Card>
<Card
title="处置分布与关键统计"
icon={<ShieldCheck size={14} color={tokens.info} />}
note="自动修正类(DQ-01/02/05/09)只在 L1 采集适配层落地,L2 引擎只报告应如何修正,保持纯函数可重放、修正过程可审计;标注类进人工确认队列;阻断类暂停发布。"
>
<Tiles items={[
{ label: '自动修正', value: `${stats.autoFix}`, sub: 'AUTO_FIX', color: tokens.info },
{ label: '标注', value: `${stats.annotate}`, sub: 'ANNOTATE', color: tokens.warning },
{ label: '阻断', value: `${stats.block}`, sub: 'BLOCK', color: tokens.danger },
]} />
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>规则</Th><Th>统计项</Th><Th right>读数</Th>
</>}>
<tr>
<Td bold>DQ-01</Td><Td color={tokens.textSub}>时钟回跳 / 已校正</Td>
<Td right mono>{stats.clockBackwardCount} 次 / {stats.correctedCount} 条</Td>
</tr>
<tr>
<Td bold>DQ-05</Td><Td color={tokens.textSub}>编码异常行(latin-1 回退)</Td>
<Td right mono>{day.normalize.malformed.length} / {day.seed.lines.length} 行</Td>
</tr>
<tr>
<Td bold>DQ-09</Td><Td color={tokens.textSub}>重复事件丢弃 / 重复率</Td>
<Td right mono>{stats.duplicateCount} 条 / {pct(stats.duplicateRate)}%</Td>
</tr>
<tr>
<Td bold color={overThreshold ? tokens.danger : tokens.textSub}>DQ-06</Td>
<Td color={tokens.textSub}>未归因占比(阈值 {pct(DQ_DEFAULTS.unattributedBlockPct)}%)</Td>
<Td right mono bold color={overThreshold ? tokens.danger : tokens.textSub}>{pct(stats.unattributedPct)}%</Td>
</tr>
<tr>
<Td bold>DQ-10</Td><Td color={tokens.textSub}>未采集 UNKNOWN(≠无生产)</Td>
<Td right mono color={tot.unknownSec > 0 ? tokens.warning : tokens.textSub}>{dur(tot.unknownSec)}</Td>
</tr>
</Table>
</div>
{/* 缺证据规则的补证依赖:标灰不标绿,写明缺什么、依赖谁、何时做实(看板红线:空区填满) */}
{dq.notEvaluated.length > 0 && (
<div style={{ marginTop: 8 }}>
<GapBox
missing={`${dq.notEvaluated.length} 条规则缺证据未评估(${dq.notEvaluated.map((n) => n.code).join('、')})`}
dependsOn={dq.notEvaluated.map((n) => `${n.code}:${n.missing}`).join(';')}
stage="W3 录入台补录 + 二期采集侧证据接入"
note="缺证据 ≠ 通过:这些规则本期无法判定,治理台标灰,不并入「未命中」。证据到位后自动转为已评估。"
/>
</div>
)}
</Card>
</div>
{/* 第二行:当日命中问题明细 + 未归因池与未采集 */}
<div style={grid2}>
<Card
title="当日命中问题明细"
icon={<ClipboardList size={14} color={tokens.warning} />}
right={<Chip color={dq.issues.length ? tokens.warning : tokens.textSub}>{dq.issues.length} 项</Chip>}
note="命中条件为引擎按当日证据现算的原文,不是规则字典里的通用判定式。阻断级问题的状态照录引擎(当前为「待处理」),须在任务中心派单处理后才能解除阻断发布;不预设已派单。"
>
{dq.issues.length === 0 ? (
<EmptyBox>
当日已评估规则均未命中问题。<br />
缺证据未评估的规则见上方台账(标灰,不视为通过)。
</EmptyBox>
) : (
<Table head={<>
<Th>规则</Th><Th>命中条件</Th><Th>处置</Th><Th>状态</Th>
</>}>
{dq.issues.map((i) => (
<tr key={i.id}>
<Td bold color={i.blocking ? tokens.danger : tokens.textSub}>
{i.code}<div style={{ fontSize: 9.5, color: tokens.textMuted, fontWeight: 400 }}>{DQ_RULE_BY_CODE[i.code].name}</div>
</Td>
<Td color={tokens.textSub}>
{i.condition}
{i.gap && <div style={{ fontSize: 9.5, color: tokens.textMuted, marginTop: 2 }}>缺口:{i.gap}</div>}
</Td>
<Td><Chip color={dispoColor(DQ_RULE_BY_CODE[i.code].disposition)}>{dispoLabel(DQ_RULE_BY_CODE[i.code].disposition)}</Chip></Td>
<Td>
<Chip color={stateColor(i.state)}>{ISSUE_STATE_LABEL[i.state] ?? i.state}</Chip>
{i.blocking && <div style={{ marginTop: 3 }}><Chip color={tokens.danger}>阻断发布</Chip></div>}
</Td>
</tr>
))}
</Table>
)}
</Card>
<Card
title="未归因与未采集(三态分开)"
icon={<Database size={14} color={tokens.accent} />}
right={<Chip color={pool.length ? tokens.warning : tokens.textSub}>{pool.length} 段未采集</Chip>}
note="未归因 IDLE(采到了但归不了因,DQ-06,计入分母)≠ 未采集 UNKNOWN(日志断流,不计 PPT 分母,DQ-10)≠ 无生产。下表只列 UNKNOWN 段;未归因 IDLE 无段级明细(见设备时间轴),补录入口同在 W3「录入台」。"
>
<Tiles items={[
{ label: '未归因 IDLE 合计', value: dur(day.buckets.unattributedSec), sub: `占 PPT ${pct(stats.unattributedPct)}%`, color: overThreshold ? tokens.danger : tokens.textSub, title: 'DQ-06 计算基础:残差中的未归因部分(残差还含 P/Q 缺口,不混计)' },
{ label: '未采集 UNKNOWN', value: dur(tot.unknownSec), sub: '不计分母(≠无生产)', color: tot.unknownSec > 0 ? tokens.warning : tokens.textSub, title: 'DQ-10:日志断流窗口,已从 PPT 扣除' },
{ label: '未采集段数', value: `${pool.length}`, sub: pool.length === 0 ? '无断流段' : pool.every((u) => u.resolved) ? '全部已解决' : '含未解决', color: tokens.textSub, title: 'UNKNOWN 段数(DQ-10),不是未归因 IDLE 段数' },
]} />
<div style={{ marginTop: 8 }}>
{pool.length === 0 ? (
<EmptyBox>当日无未采集 UNKNOWN 段(日志连续)。<br />未归因 IDLE 合计见上方读数,与未采集分开统计。</EmptyBox>
) : (
<Table head={<>
<Th>段</Th><Th right>时长</Th><Th right>占 PPT</Th><Th>原因</Th><Th>建议表单</Th>
</>}>
{pool.map((u) => (
<tr key={u.id}>
<Td mono color={tokens.textMuted}>{u.id.replace(`unk-${day.device.id}-`, '')}</Td>
<Td right mono>{dur(u.durationSec)}</Td>
<Td right mono color={tokens.textSub}>{pct(u.pctOfPlanTime)}%</Td>
<Td color={tokens.textSub}>{REASON_LABEL[u.reason] ?? u.reason}</Td>
<Td color={tokens.textMuted}>
{u.suggestedForm ? ENTRY_FORM_LABEL[u.suggestedForm] : '—'}
{u.resolved && <div style={{ marginTop: 2 }}><Chip color={tokens.success}>已解决</Chip></div>}
</Td>
</tr>
))}
</Table>
)}
</div>
</Card>
</div>
{/* demo:3 个业务日种子的全量 DQ 发现聚合 */}
<Card
title="全量 DQ 发现(demo 种子聚合)"
icon={<Database size={14} color={tokens.warning} />}
full
right={<Chip color={tokens.textMuted} title="demo 沙箱:数据来自内置合成种子,不连接后端">{findings.length} 条 · 3 个业务日</Chip>}
note="聚合内置 3 个业务日种子的引擎 DQ 发现(规则/设备/业务日/判定条件),只读展示,视图不重判。demo 沙箱不落库、不连接后端。"
>
<Table head={<>
<Th>规则</Th><Th>设备</Th><Th>业务日</Th><Th>判定条件</Th><Th>处置</Th><Th>阻断</Th>
</>} maxHeight={320}>
{findings.map((r) => (
<tr key={r.id}>
<Td bold color={tokens.textSub}>{r.code}</Td>
<Td mono color={tokens.textSub}>{r.device ?? '—'}</Td>
<Td mono color={tokens.textMuted}>{r.bizDate}</Td>
<Td color={tokens.textMuted}>
<span title={r.gap ?? r.condition} style={{ wordBreak: 'break-all' }}>{r.condition}</span>
</Td>
<Td><Chip color={stateColor(r.state)}>{ISSUE_STATE_LABEL[r.state] ?? r.state}</Chip></Td>
<Td>{r.blocking ? <Chip color={tokens.danger}>阻断</Chip> : <Chip color={tokens.textMuted}>否</Chip>}</Td>
</tr>
))}
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,558 @@
/**
* 手工录入台(spec 2026-11-19 §4.5):八张录入单 + 改善任务派发闸。
*
* A. 八张演示表单(PM 交接/完工、换型准备/记录、等待登记、停机归因、5S、实验室调试):
* 左选表单、右填单据;机台/人员预填可改,* 必填;六项防呆逐条显示;
* 「仅校验」就地校验,「提交」只写内存 + 页面审计流 + 当日重算演示,demo 沙箱不落库。
* B. 改善任务派发闸:原样保留(演示故事线)。
*/
import { useEffect, useMemo, useState, type CSSProperties } from 'react';
import {
ClipboardEdit, Send, GitBranch, AlertTriangle, CheckCircle2, History, ShieldAlert,
FileText,
} from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import {
tryDispatch, advanceTask, canDispatch, nextStates,
REQUIRED_FIELDS, ENTRY_OPERATOR, recomputeDay, knownDeviceIds,
} from '../../lib/oeeService';
import {
TASK_STATE_LABEL,
type ImprovementTask, type TaskState,
} from '../../types/oee';
import {
ScopeBar, Card, Table, Th, Td, Chip, Note, GapBox, EmptyBox, grid2, pageStyle, pct,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
export interface OeeEntryProps extends OeeViewProps {
tasks: ImprovementTask[];
onTasksChange: (t: ImprovementTask[]) => void;
}
const STATE_TONE: Record<TaskState, 'textSub' | 'warning' | 'info' | 'success' | 'accent' | 'textMuted'> = {
DRAFT: 'textMuted', PENDING_REVIEW: 'warning', DISPATCHED: 'info',
IN_PROGRESS: 'accent', VERIFIED: 'success', ARCHIVED: 'textSub',
};
const pad = (n: number) => String(n).padStart(2, '0');
const toLocalInput = (v: unknown) => {
if (typeof v !== 'string' || !v) return '';
const d = new Date(v);
if (Number.isNaN(d.getTime())) return v.slice(0, 16);
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
};
const shiftMin = (v: string, min: number) => {
if (!v) return '';
const d = new Date(v);
if (Number.isNaN(d.getTime())) return '';
d.setMinutes(d.getMinutes() + min);
return toLocalInput(d.toISOString());
};
/* ── demo 录入沙箱:八张表单定义与本地防呆,不连接后端 ── */
type EntryFieldType = 'text' | 'time' | 'number' | 'bool' | 'select';
interface EntryFieldDef { key: string; label: string; type: EntryFieldType; required: boolean; readonly: boolean; options?: string[] }
interface EntryFormDef { id: string; name: string; region: string; events: string[]; fields: EntryFieldDef[] }
interface EntryCheck { id: string; name: string; ok: boolean; msg: string }
interface EntryAuditRow { id: number; entry_id: number | null; action: string; actor: string; at: string; detail: Record<string, unknown> }
interface EntrySubmitResult { entry: { id: number }; before: Record<string, number | string | null> | null; after: Record<string, number | string | null> | null; checks: EntryCheck[] }
const f = (key: string, label: string, type: EntryFieldType, required = false, readonly = false, options?: string[]): EntryFieldDef =>
({ key, label, type, required, readonly, options });
const DEMO_FORMS: EntryFormDef[] = [
{ id: 'FORM_PM_HANDOVER', name: 'PM 交接单', region: 'SRF', events: ['PM-01'], fields: [
f('operator', '交接人', 'text', true), f('pm_type', '保养类型', 'select', true, false, ['日保养', '周保养', '月度保养']), f('handover_to', '接班人', 'text', true), f('note', '交接说明', 'text'),
] },
{ id: 'FORM_PM_FINISH', name: 'PM 完工单', region: 'SRF', events: ['PM-02'], fields: [
f('operator', '完成人', 'text', true), f('duration_min', '保养用时(分)', 'number', true), f('confirmed', '确认完工', 'bool', true), f('note', '备注', 'text'),
] },
{ id: 'FORM_SETUP', name: '换型准备单', region: 'SRF', events: ['SU-01'], fields: [
f('operator', '准备人', 'text', true), f('from_product', '原品号', 'text', true), f('to_product', '目标品号', 'text', true), f('prepare_min', '准备用时(分)', 'number'),
] },
{ id: 'FORM_CHANGEOVER', name: '换型记录单', region: 'SRF', events: ['SU-02', 'SU-03'], fields: [
f('operator', '记录人', 'text', true), f('xray_at', 'Xray 图片时间', 'time', true), f('after_reflow_at', '回流焊后时间', 'time', true),
f('sum_start', '汇总开始', 'time', false, true), f('sum_end', '汇总结束', 'time', false, true), f('ea_end', 'EA 结束', 'time', false, true),
] },
{ id: 'FORM_WAIT_REGISTER', name: '等待登记单', region: 'SRF', events: ['WT-01'], fields: [
f('operator', '登记人', 'text', true), f('wait_reason', '等待原因', 'select', true, false, ['缺料', '待检', '待人', '待程序']), f('wait_min', '等待时长(分)', 'number', true),
] },
{ id: 'FORM_DOWN_ATTR', name: '停机归因单', region: 'SRF', events: ['DT-01'], fields: [
f('operator', '归因人', 'text', true), f('cause', '一级原因', 'select', true, false, ['人', '机', '料', '法', '环', '测']), f('description', '原因描述', 'text', true), f('action', '处置动作', 'text'),
] },
{ id: 'FORM_5S', name: '5S 记录单', region: 'FT/ASLT', events: ['5S-01'], fields: [
f('operator', '检查人', 'text', true), f('area', '区域', 'text', true), f('score', '评分', 'number'), f('confirmed', '确认合规', 'bool'),
] },
{ id: 'FORM_LAB_DEBUG', name: '实验室调试单', region: 'FT/ASLT', events: ['LB-01'], fields: [
f('operator', '调试人', 'text', true), f('equipment', '调试设备', 'text', true), f('result', '调试结论', 'select', true, false, ['合格', '不合格', '待复测']), f('note', '备注', 'text'),
] },
];
const buildChecks = (def: EntryFormDef, values: Record<string, string | boolean>, dev: string): EntryCheck[] => {
const missing = def.fields.filter((fd) => fd.required && !fd.readonly && !String(values[fd.key] ?? '').trim());
const times = def.fields.filter((fd) => fd.type === 'time').map((fd) => String(values[fd.key] ?? '')).filter((v) => v.length > 0);
const badTime = times.some((t) => Number.isNaN(Date.parse(t)));
return [
{ id: 'V1', name: '必填完整', ok: missing.length === 0, msg: missing.map((m) => m.label).join('、') },
{ id: 'V2', name: '时间合法', ok: !badTime, msg: badTime ? '时间格式无法解析' : '' },
{ id: 'V3', name: '不重叠', ok: true, msg: '' },
{ id: 'V4', name: '区域匹配', ok: dev.length > 0, msg: dev ? '' : '未指定机台' },
{ id: 'V5', name: '前置状态', ok: knownDeviceIds().includes(dev), msg: knownDeviceIds().includes(dev) ? '' : '机台不在台账' },
{ id: 'V6', name: '人员在册', ok: !!values.operator, msg: values.operator ? '' : '录入人缺失' },
];
};
export default function OeeEntry({ filter, tasks, onTasksChange }: OeeEntryProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const bizDate = scope.bizDate;
/* ── A. 录入单状态(demo 沙箱,只写内存) ── */
const forms = DEMO_FORMS;
const [formId, setFormId] = useState<string | null>(null);
const [values, setValues] = useState<Record<string, string | boolean>>({});
const [prefilled, setPrefilled] = useState<Set<string>>(new Set());
const [device, setDevice] = useState<string>(scope.day?.device.id ?? 'DEK001');
const [checks, setChecks] = useState<EntryCheck[] | null>(null);
const [err, setErr] = useState<string | null>(null);
const [result, setResult] = useState<EntrySubmitResult | null>(null);
const [audit, setAudit] = useState<EntryAuditRow[]>([]);
const [revision, setRevision] = useState(0);
useEffect(() => {
setDevice(scope.day?.device.id ?? 'DEK001');
}, [scope.day?.device.id]);
const form = forms.find((x) => x.id === formId) ?? null;
const loadPrefill = (fid: string, dev: string) => {
setChecks(null); setResult(null); setErr(null);
const def = forms.find((x) => x.id === fid);
if (!def) return;
const v: Record<string, string | boolean> = { operator: ENTRY_OPERATOR };
const pre = new Set<string>(['operator']);
if (dev && !knownDeviceIds().includes(dev)) pre.delete('operator');
def.fields.forEach((fd) => {
if (fd.type === 'bool') v[fd.key] = false;
else v[fd.key] = '';
});
setValues(v); setPrefilled(pre);
};
const selectForm = (fid: string) => { setFormId(fid); loadPrefill(fid, device); };
const setField = (k: string, v: string | boolean) => {
setValues((prev) => {
const next = { ...prev, [k]: v };
if (form?.id === 'FORM_CHANGEOVER' && (k === 'xray_at' || k === 'after_reflow_at')) {
const xray = k === 'xray_at' ? String(v) : String(next.xray_at ?? '');
const after = k === 'after_reflow_at' ? String(v) : String(next.after_reflow_at ?? '');
next.sum_start = shiftMin(xray, 5);
next.sum_end = shiftMin(after, 5);
next.ea_end = shiftMin(xray, -5);
}
return next;
});
};
const body = useMemo(() => ({
form: formId ?? '', device_id: device, biz_date: bizDate,
fields: values as Record<string, unknown>, operator: ENTRY_OPERATOR,
}), [formId, device, bizDate, values]);
const doValidate = () => {
if (!form) return;
setErr(null);
setChecks(buildChecks(form, values, device));
};
const snapshot = (d: ReturnType<typeof recomputeDay> | null) => (d ? {
oee: d.tiers.actual.oee, a: d.tiers.actual.a, p: d.tiers.actual.p, q: d.tiers.actual.q,
light: d.dq.blocked ? 'warn' : 'ok',
} : null);
const doSubmit = () => {
if (!form) return;
setErr(null);
const cs = buildChecks(form, values, device);
setChecks(cs);
if (!cs.every((c) => c.ok)) { setErr('防呆校验未通过,demo 沙箱不提交。'); return; }
const rev = revision + 1;
setRevision(rev);
const id = rev;
const at = new Date().toISOString();
const after = recomputeDay(bizDate, [], rev);
setResult({ entry: { id }, before: snapshot(scope.day ?? null), after: snapshot(after ?? null), checks: cs });
setAudit((prev) => [
{ id: prev.length + 1, entry_id: id, action: 'RECOMPUTE', actor: ENTRY_OPERATOR, at, detail: { biz_date: bizDate, revision: rev, demo: true } },
{ id: prev.length + 2, entry_id: id, action: 'SUBMIT', actor: ENTRY_OPERATOR, at, detail: { form: body.form, device_id: device, fields: values, demo: true } },
...prev,
].slice(0, 30));
};
const patchTask = (id: string, patch: Partial<ImprovementTask>) => {
onTasksChange(tasks.map((t) => (t.id === id ? { ...t, ...patch } : t)));
};
const [selectedTaskId, setSelectedTaskId] = useState<string | null>(tasks[0]?.id ?? null);
const [gateMsg, setGateMsg] = useState<{ ok: boolean; reason?: string; missing?: { label: string; prompt: string }[] } | null>(null);
const selectedTask = tasks.find((t) => t.id === selectedTaskId) ?? null;
const ctx = () => ({ at: new Date().toISOString(), by: ENTRY_OPERATOR });
const dispatch = (id: string) => {
const r = tryDispatch(tasks, id, ctx());
onTasksChange(r.tasks);
setGateMsg({ ok: r.result.ok, reason: r.result.reason, missing: r.check.missing.map((m) => ({ label: m.label, prompt: m.prompt })) });
};
const advance = (id: string, to: TaskState) => {
const r = advanceTask(tasks, id, to, ctx());
onTasksChange(r.tasks);
setGateMsg({ ok: r.result.ok, reason: r.result.reason, missing: r.result.missing?.map((m) => ({ label: m.label, prompt: m.prompt })) });
};
const taskCheck = selectedTask ? canDispatch(selectedTask) : null;
const missingKeys = new Set(taskCheck?.missing.map((m) => m.key) ?? []);
const benefitText = (b: ImprovementTask['expectedBenefit']) => (b ? `${b.min}–${b.max} ${b.unit}` : '—');
const inputStyle: CSSProperties = {
width: '100%', minWidth: 0, boxSizing: 'border-box',
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, borderRadius: 7,
padding: '5px 8px', fontSize: 11.5, color: tokens.text, outline: 'none',
};
const labelStyle: CSSProperties = { fontSize: 10.5, fontWeight: 600, color: tokens.textSub, marginBottom: 3, display: 'block' };
const renderField = (fd: EntryFormDef['fields'][number]) => {
const v = values[fd.key];
const isPre = prefilled.has(fd.key);
const style: CSSProperties = fd.readonly ? { ...inputStyle, opacity: 0.75 } : inputStyle;
if (fd.readonly) {
return <input style={style} value={String(v ?? '')} readOnly placeholder="由上方时间自动派生" />;
}
if (fd.type === 'bool') {
return (
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: tokens.text, padding: '5px 0' }}>
<input type="checkbox" checked={v === true}
onChange={(e) => setField(fd.key, e.target.checked)} />
{v === true ? '已确认' : '未确认'}
</label>
);
}
if (fd.type === 'select') {
return (
<select style={style} value={String(v ?? '')} onChange={(e) => setField(fd.key, e.target.value)}>
<option value="">请选择…</option>
{(fd.options ?? []).map((o) => <option key={o} value={o}>{o}</option>)}
</select>
);
}
return (
<input
style={{ ...style, background: isPre ? tokens.panelBg : tokens.panelBgAlt }}
type={fd.type === 'time' ? 'datetime-local' : fd.type === 'number' ? 'number' : 'text'}
value={String(v ?? '')}
onChange={(e) => setField(fd.key, e.target.value)}
placeholder={isPre ? '已自动带出(可修改)' : ''}
/>
);
};
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="手工录入台"
icon={<ClipboardEdit size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="demo 沙箱:提交只写内存状态与页面审计流,不落库、不连接后端">demo · 不落库</Chip>}
/>
{err && <Note>错误:{err}</Note>}
<div style={grid2}>
{/* 左:八张表单 */}
<Card title="录入单(8 张)" icon={<FileText size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>{forms.length || 8} 张</Chip>}
note="机台/时间/人员灰底为系统预填,可改;* 为必填。提交后生成现场事件并写入审计。">
<div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
{forms.map((f) => {
const on = f.id === formId;
return (
<button key={f.id} onClick={() => selectForm(f.id)}
style={{
textAlign: 'left', cursor: 'pointer', borderRadius: 8, padding: '7px 9px',
border: `1px solid ${on ? tokens.accent : tokens.border}`,
background: on ? tokens.accentBg : 'transparent', color: tokens.text,
display: 'flex', alignItems: 'center', gap: 8, minWidth: 0,
}}>
<span style={{ fontSize: 11.5, fontWeight: 700, flex: 1 }}>{f.name}</span>
<span style={{ fontSize: 10, color: tokens.textMuted }}>{f.events.join('/')}</span>
<Chip color={f.region === 'SRF' ? tokens.info : f.region === 'FT/ASLT' ? tokens.accent : tokens.textMuted}>{f.region}</Chip>
</button>
);
})}
</div>
</Card>
{/* 右:表单 */}
<Card
title={form ? form.name : '选择左侧录入单'}
icon={<ClipboardEdit size={14} color={tokens.info} />}
right={<><Chip color={tokens.accent}>独立录入</Chip>{form && <Chip color={tokens.textMuted}>{form.events.join(' / ')}</Chip>}</>}
note="六项防呆:必填完整 / 时间合法 / 不重叠 / 区域匹配 / 前置状态 / 人员在册。SLA 超时只提示、不阻断。">
<div style={{ display: 'flex', flexDirection: 'column', gap: 9, minWidth: 0 }}>
<div>
<label style={labelStyle}>机台 <span style={{ color: tokens.danger }}>*</span>{scope.day && <span style={{ color: tokens.textMuted, fontWeight: 400 }}> ({scope.day.device.region} · {scope.day.device.type})</span>}</label>
<input style={inputStyle} value={device}
onChange={(e) => { setDevice(e.target.value); if (formId) loadPrefill(formId, e.target.value); }} />
</div>
{form ? (
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 9 }}>
{form.fields.filter((fd) => fd.key !== 'device').map((fd) => (
<div key={fd.key} style={{ minWidth: 0, gridColumn: fd.type === 'text' && fd.key !== 'leader' && fd.key !== 'ea' && fd.key !== 'eq' && fd.key !== 'qa' && fd.key !== 'mfg' && fd.key !== 'by' && fd.key !== 'engineer' ? '1 / -1' : undefined }}>
<label style={labelStyle}>
{fd.label}{fd.required && !fd.readonly && <span style={{ color: tokens.danger }}> *</span>}
</label>
{renderField(fd)}
</div>
))}
</div>
) : <Note>选择一张录入单开始。</Note>}
{form && (
<div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
<button onClick={doValidate}
style={{ fontSize: 11.5, fontWeight: 700, padding: '6px 14px', borderRadius: 8, cursor: 'pointer', border: `1px solid ${tokens.border}`, background: 'transparent', color: tokens.textSub }}>
仅校验
</button>
<button onClick={doSubmit}
style={{ fontSize: 11.5, fontWeight: 700, padding: '6px 16px', borderRadius: 8, cursor: 'pointer', border: `1px solid ${tokens.accent}`, background: tokens.accentBg, color: tokens.accent }}>
提交
</button>
<span style={{ fontSize: 10, color: tokens.textMuted }}>demo 沙箱:提交只写内存状态与审计流,不落库</span>
</div>
)}
{checks && (
<div style={{ borderTop: `1px solid ${tokens.border}`, paddingTop: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
<span style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub }}>防呆校验</span>
<Chip color={checks.every((c) => c.ok) ? tokens.success : tokens.warning}>
{checks.filter((c) => c.ok).length}/{checks.length} 通过
</Chip>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
{checks.map((c) => (
<div key={c.id} style={{ display: 'flex', gap: 6, alignItems: 'flex-start' }}>
{c.ok ? <CheckCircle2 size={12} color={tokens.success} style={{ marginTop: 2 }} />
: <AlertTriangle size={12} color={tokens.danger} style={{ marginTop: 2 }} />}
<span style={{ fontSize: 10.5, color: c.ok ? tokens.textSub : tokens.danger, lineHeight: 1.5 }}>
{c.id} {c.name}{c.msg ? `:${c.msg}` : ''}
</span>
</div>
))}
</div>
{checks.every((c) => c.ok) && <div style={{ marginTop: 5 }}><Chip color={tokens.success}>校验通过 · demo 沙箱可提交</Chip></div>}
</div>
)}
{result && (
<div style={{ borderTop: `1px solid ${tokens.border}`, paddingTop: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
<GitBranch size={13} color={tokens.success} />
<span style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub }}>提交成功 · 当日重算(demo 演示)</span>
<Chip color={tokens.textMuted}>{`单号 ${String(result.entry.id ?? '')}`}</Chip>
</div>
<Table head={<><Th>指标</Th><Th right>提交前</Th><Th right>重算后</Th></>}>
{(['oee', 'a', 'p', 'q'] as const).map((k) => (
<tr key={k}>
<Td color={tokens.textSub}>{k.toUpperCase()}</Td>
<Td right mono>{typeof result.before?.[k] === 'number' ? `${pct(result.before[k] as number)}%` : '—'}</Td>
<Td right mono bold color={tokens.text}>{typeof result.after?.[k] === 'number' ? `${pct(result.after[k] as number)}%` : '—'}</Td>
</tr>
))}
<tr>
<Td color={tokens.textSub}>灯号</Td>
<Td right mono>{result.before?.light ?? '—'}</Td>
<Td right mono bold>{result.after?.light ?? '—'}</Td>
</tr>
</Table>
</div>
)}
</div>
</Card>
</div>
<Card title="审计流(最近 30 条)" icon={<History size={14} color={tokens.info} />} full
right={<Chip color={tokens.textMuted}>{audit.length} 条</Chip>}
note="每次提交写入页面内存的 SUBMIT 与 RECOMPUTE 两条记录;重算前后快照都在 detail 里,可追溯、可对比。demo 沙箱不落库。">
{audit.length === 0 ? <EmptyBox>暂无审计记录。提交任意录入单后在此留痕(仅页面内存)。</EmptyBox> : (
<Table head={<><Th>时间</Th><Th>动作</Th><Th>执行者</Th><Th>单号</Th><Th>详情</Th></>}>
{audit.map((a) => (
<tr key={a.id}>
<Td mono color={tokens.textMuted}>{a.at.slice(0, 19).replace('T', ' ')}</Td>
<Td><Chip color={a.action === 'RECOMPUTE' ? tokens.accent : tokens.success}>{a.action}</Chip></Td>
<Td color={tokens.textSub}>{a.actor}</Td>
<Td mono color={tokens.textMuted}>{a.entry_id ?? '—'}</Td>
<Td mono color={tokens.textSub}><span style={{ display: 'inline-block', maxWidth: 520, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', verticalAlign: 'bottom' }}>{JSON.stringify(a.detail)}</span></Td>
</tr>
))}
</Table>
)}
</Card>
{/* ── B. 改善任务 · 派发闸与六态流转(原样保留) ── */}
<Card
title="改善任务 · 派发闸与六态流转"
icon={<Send size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted}>{tasks.length} 条任务</Chip>}
note="六态:待生成→待审核→已派发→执行中→已验证→已归档(待审核可退回待生成)。派发闸只挂在「待审核→已派发」:四项必填任一缺失即拒派,任务停在待审核(断言⑨)。点击行选中。"
>
<Table head={<>
<Th>任务</Th><Th>标题</Th><Th>状态</Th><Th>真因</Th><Th right>优先分</Th><Th>负责人</Th>
</>}>
{tasks.map((t) => {
const on = t.id === selectedTaskId;
return (
<tr key={t.id} onClick={() => { setSelectedTaskId(t.id); setGateMsg(null); }} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}>
<Td mono bold color={on ? tokens.accent : tokens.textSub}>{t.id}</Td>
<Td color={tokens.text}>{t.title}</Td>
<Td><Chip color={tokens[STATE_TONE[t.state]]}>{TASK_STATE_LABEL[t.state]}</Chip></Td>
<Td><Chip color={tokens.textMuted} title={`${t.rootCauseEntity.type} · ${t.rootCauseEntity.id}`}>{t.causeClass} 类</Chip></Td>
<Td right mono color={tokens.textSub}>{t.priorityScore.toFixed(4)}</Td>
<Td color={tokens.textSub}>{t.owner ?? <span style={{ color: tokens.warning }}>未指定</span>}</Td>
</tr>
);
})}
</Table>
</Card>
{selectedTask && (
<div style={grid2}>
<Card
title={`四项必填 · ${selectedTask.id}`}
icon={<ShieldAlert size={14} color={tokens.warning} />}
right={<Chip color={taskCheck?.ok ? tokens.success : tokens.warning}>{taskCheck?.ok ? '齐备·可派发' : `缺 ${taskCheck?.missing.length ?? 0} 项`}</Chip>}
note="负责人 / 完成时限 / 预期收益(区间) / 验证方式。待审核态可在此补齐;缺项时派发被拒,任务停在待审核,绝不静默推进。"
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{REQUIRED_FIELDS.map((f) => {
const ok = !missingKeys.has(f.key);
const editable = selectedTask.state === 'PENDING_REVIEW';
return (
<div key={f.key} style={{ minWidth: 0 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
{ok ? <CheckCircle2 size={13} color={tokens.success} /> : <AlertTriangle size={13} color={tokens.warning} />}
<span style={{ fontSize: 11, fontWeight: 600, color: tokens.textSub }}>{f.label}</span>
{!ok && <span style={{ fontSize: 10, color: tokens.warning }}>{f.prompt}</span>}
</div>
{f.key === 'expectedBenefit' ? (
editable ? (
<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<input style={{ ...inputStyle, width: 70 }} type="number" value={selectedTask.expectedBenefit?.min ?? ''} onChange={(e) => patchTask(selectedTask.id, { expectedBenefit: { min: Number(e.target.value), max: selectedTask.expectedBenefit?.max ?? Number(e.target.value), unit: selectedTask.expectedBenefit?.unit ?? 'min/月' } })} placeholder="min" />
<span style={{ color: tokens.textMuted }}>–</span>
<input style={{ ...inputStyle, width: 70 }} type="number" value={selectedTask.expectedBenefit?.max ?? ''} onChange={(e) => patchTask(selectedTask.id, { expectedBenefit: { min: selectedTask.expectedBenefit?.min ?? 0, max: Number(e.target.value), unit: selectedTask.expectedBenefit?.unit ?? 'min/月' } })} placeholder="max" />
<input style={{ ...inputStyle, width: 90 }} value={selectedTask.expectedBenefit?.unit ?? ''} onChange={(e) => patchTask(selectedTask.id, { expectedBenefit: { min: selectedTask.expectedBenefit?.min ?? 0, max: selectedTask.expectedBenefit?.max ?? 0, unit: e.target.value } })} placeholder="单位" />
</div>
) : <div style={{ fontSize: 11.5, color: tokens.text, paddingLeft: 19 }}>{benefitText(selectedTask.expectedBenefit)}</div>
) : (
editable ? (
<input
style={inputStyle}
value={(selectedTask[f.key] as string | undefined) ?? ''}
onChange={(e) => patchTask(selectedTask.id, { [f.key]: e.target.value } as Partial<ImprovementTask>)}
placeholder={f.prompt}
/>
) : <div style={{ fontSize: 11.5, color: tokens.text, paddingLeft: 19 }}>{(selectedTask[f.key] as string | undefined) || '—'}</div>
)}
</div>
);
})}
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginTop: 10 }}>
{selectedTask.state === 'PENDING_REVIEW' && (
<button
onClick={() => dispatch(selectedTask.id)}
style={{
fontSize: 11.5, fontWeight: 700, padding: '6px 16px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${taskCheck?.ok ? tokens.success : tokens.warning}`,
background: taskCheck?.ok ? `${tokens.success}1f` : `${tokens.warning}1f`,
color: taskCheck?.ok ? tokens.success : tokens.warning,
}}
>
{taskCheck?.ok ? '派发(SLA 起算)' : '尝试派发(将被拒)'}
</button>
)}
{nextStates(selectedTask.state).filter((s) => s !== 'DISPATCHED').map((s) => (
<button
key={s}
onClick={() => advance(selectedTask.id, s)}
style={{
fontSize: 11, fontWeight: 600, padding: '5px 12px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${tokens.border}`, background: 'transparent', color: tokens.textSub,
}}
>
{s === 'DRAFT' ? '退回待生成' : `推进 → ${TASK_STATE_LABEL[s]}`}
</button>
))}
{nextStates(selectedTask.state).length === 0 && <Chip color={tokens.textMuted}>终态·无后继</Chip>}
</div>
{gateMsg && (
<div style={{
marginTop: 9, padding: '8px 10px', borderRadius: 9, minWidth: 0,
background: gateMsg.ok ? `${tokens.success}12` : `${tokens.warning}12`,
border: `1px solid ${gateMsg.ok ? tokens.success : tokens.warning}44`,
}}>
<div style={{ fontSize: 11.5, fontWeight: 700, color: gateMsg.ok ? tokens.success : tokens.warning, marginBottom: gateMsg.missing?.length ? 4 : 0 }}>
{gateMsg.ok ? '流转成功' : '被拒绝'}
</div>
{gateMsg.reason && <div style={{ fontSize: 11, color: tokens.textSub, lineHeight: 1.55 }}>{gateMsg.reason}</div>}
{gateMsg.missing && gateMsg.missing.length > 0 && (
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 5 }}>
{gateMsg.missing.map((m) => <Chip key={m.label} color={tokens.warning}>{m.label}:{m.prompt}</Chip>)}
</div>
)}
</div>
)}
</Card>
<Card
title={`状态流转与历史 · ${selectedTask.id}`}
icon={<History size={14} color={tokens.info} />}
right={<Chip color={tokens[STATE_TONE[selectedTask.state]]}>{TASK_STATE_LABEL[selectedTask.state]}</Chip>}
note="历史时间线由引擎在每次合法流转时追加(at/by 注入,可重放)。SLA 计时起点=首次进入「已派发」的时刻。非法跨态跳转被拒绝。"
>
<div style={{ display: 'flex', flexDirection: 'column', gap: 0, minWidth: 0 }}>
{selectedTask.history.map((h, i) => (
<div key={`${h.state}-${i}`} style={{ display: 'flex', gap: 9, alignItems: 'flex-start', paddingBottom: i < selectedTask.history.length - 1 ? 9 : 0 }}>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', flexShrink: 0 }}>
<span style={{ width: 9, height: 9, borderRadius: '50%', background: tokens[STATE_TONE[h.state]], marginTop: 3 }} />
{i < selectedTask.history.length - 1 && <span style={{ width: 1.5, flex: 1, minHeight: 14, background: tokens.border, marginTop: 2 }} />}
</div>
<div style={{ minWidth: 0, flex: 1 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 7, flexWrap: 'wrap' }}>
<Chip color={tokens[STATE_TONE[h.state]]}>{TASK_STATE_LABEL[h.state]}</Chip>
<span style={{ fontSize: 10.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>{h.at.slice(0, 19).replace('T', ' ')}</span>
<span style={{ fontSize: 10.5, color: tokens.textSub }}>{h.by}</span>
</div>
{h.note && <div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 2, lineHeight: 1.5 }}>{h.note}</div>}
</div>
</div>
))}
</div>
{selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && (
<div style={{ marginTop: 9 }}>
<GapBox
missing={`四项必填缺 ${taskCheck?.missing.length ?? 0} 项,无法派发`}
dependsOn={taskCheck?.missing.map((m) => m.label).join('、') ?? ''}
stage="补齐后于本录入台派发"
note="缺一项即拒派:任务停在「待审核」,绝不静默推进到「已派发」。补齐左侧四项后再派发,SLA 方才起算。"
/>
</div>
)}
</Card>
</div>
)}
</div>
);
}
@@ -0,0 +1,214 @@
/**
* AI 预测页(forecast 页签 · W4-B,建议书 §4.6 / §5.2.2 no.9 / 决策 D13)。
*
* ★ 本页最坚决的一条纪律:**四门槛全未达 ⇒ 不引入任何预测模型**。
* 所有外推读数都带「示意·非模型输出」标注,规则可照着重算,绝不冒充模型概率/置信区间。
* 生产阶段模型路线(XGBoost/LightGBM→LSTM/TCN、生存分析)只登记,phase=P4~P5,原型不实现。
*
* 三条取数纪律(断言②):
* ① 数字只从 L3 forecastOfDay 取(它从锚点当日六桶/DQ/历史序列现算入参喂纯规则引擎);
* ② 只有锚点单机有日志贯通结果,非锚点/聚合范围或无种子日 → 诚实空态,不外推、不显示 0;
* ③ DQ 阻断或未归因 >5% → 降级为「仅供参考」,标灰不标绿。
*/
import { TrendingUp, Activity, Gauge, AlertTriangle, ListChecks, Rocket } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import {
forecastOfDay, FORECAST_GATES, FORECAST_GATE_NOTE, FORECAST_LABEL,
MODEL_ROADMAP, MODEL_ROADMAP_NOTE, RISK_LEVEL_LABEL, STOP_RISK_HIGH, STOP_RISK_MED,
} from '../../lib/oeeService';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, EmptyBox, grid2, pageStyle, pct,
} from './oeeUi';
import { TrendChart } from './charts';
import type { OeeViewProps } from './OeeOverview';
/** 停机风险等级配色:高=红 / 中= amber / 低=绿(仅示意,非模型概率)。 */
const RISK_COLOR = { HIGH: 'danger', MED: 'warning', LOW: 'success' } as const;
export default function OeeForecast({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const fc = forecastOfDay(scope.bizDate);
const risk = fc.stopRisk;
const oee4h = fc.oee4h;
const riskColor = risk ? tokens[RISK_COLOR[risk.level]] : tokens.textMuted;
/* 历史 OEE 趋势(百分比),未来 4h 示意点作参考线叠加,不冒充时间序列上的实测点。 */
const histLabels = fc.history.map((h) => h.bizDate.slice(5));
const histValues = fc.history.map((h) => h.oee * 100);
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="AI智能预测分析"
icon={<TrendingUp size={15} color={tokens.accent} />}
extra={<Chip color={tokens.warning} title={FORECAST_GATE_NOTE}>{FORECAST_LABEL}</Chip>}
/>
{/* 为什么不上模型:四门槛全未达,把诚实判断写在脸上 */}
<Card title="为什么不上预测模型" icon={<AlertTriangle size={14} color={tokens.warning} />} tone={tokens.warning}>
<Note>{FORECAST_GATE_NOTE}</Note>
</Card>
{!fc.available || !risk ? (
<EmptyBox>
当前筛选范围({scope.scopeLabel})无日志贯通结果,不做预测外推,也不显示 0。<br />
{fc.gap ?? scope.gap ?? scope.coverageNote}
</EmptyBox>
) : (
<>
<Tiles items={[
{ label: '当日实际 OEE', value: fc.anchorOee == null ? '—' : `${pct(fc.anchorOee)}%`, sub: fc.anchorOee == null ? 'OEE 缺口(G)· 不标 0' : `${scope.bizDate} · 锚点单机`, color: fc.anchorOee == null ? tokens.textMuted : tokens.text, title: fc.anchorOee == null ? (fc.gap ?? '当日实际 OEE 缺口,不做 OEE 外推') : '外推锚点:日志贯通的当日实际 OEE' },
{ label: '未来 30min 停机风险', value: RISK_LEVEL_LABEL[risk.level], sub: `非计划占比 ${pct(risk.unplannedPct)}%`, color: riskColor, title: risk.rule },
...(oee4h ? [
{ label: '未来 4h OEE 点值', value: `${pct(oee4h.point)}%`, sub: `斜率 ${(oee4h.slopePerDay * 100).toFixed(2)}pp/日`, color: tokens.textSub, title: oee4h.method },
{ label: '示意区间(非置信)', value: `${pct(oee4h.bandLow)}–${pct(oee4h.bandHigh)}%`, sub: oee4h.degraded ? '降级·仅供参考' : '±3pp 示意带宽', color: tokens.textMuted, title: '示意区间,不是模型置信区间;降级时 ±6pp' },
] : [
{ label: '未来 4h OEE', value: '不外推', sub: 'OEE 缺口(G)', color: tokens.textMuted, title: fc.gap ?? '当日实际 OEE 缺口:不做 OEE 外推、不显示 0' },
]),
]} />
{fc.anchorOee == null && fc.gap && <Note>{fc.gap}</Note>}
<div style={grid2}>
{/* 未来 30min 停机风险:规则外推 + 可重算规则文字 */}
<Card
title="未来 30min 停机风险(规则外推)"
icon={<Activity size={14} color={riskColor} />}
right={<Chip color={tokens.warning}>{FORECAST_LABEL}</Chip>}
tone={riskColor}
note={risk.rule}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
<span style={{ fontSize: 30, fontWeight: 800, color: riskColor, lineHeight: 1 }}>{RISK_LEVEL_LABEL[risk.level]}</span>
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 11.5, color: tokens.textSub }}>非计划停机占比 <strong style={{ color: riskColor }}>{pct(risk.unplannedPct)}%</strong></div>
<div style={{ fontSize: 10.5, color: tokens.textMuted }}>=(故障桶 + 小停机桶)/ PPT</div>
</div>
</div>
{/* 占比计量条:刻度 3% / 10% 两条阈值线,量程 0–20% */}
<RiskMeter pct={risk.unplannedPct} color={riskColor} />
{risk.degraded && (
<Note><span style={{ color: tokens.warning }}>⚠ DQ 阻断或未归因 &gt;5%,本读数降级为仅供参考,不可发布。</span></Note>
)}
</Card>
{/* 未来 4h OEE:历史趋势 + 线性外推点(参考线),示意区间数值化;OEE 缺口时诚实空态 */}
{oee4h ? (
<Card
title="未来 4h OEE(线性外推)"
icon={<Gauge size={14} color={tokens.accent} />}
right={<Chip color={tokens.warning}>{FORECAST_LABEL}</Chip>}
note={oee4h.method}
>
<TrendChart
series={[{ name: '历史实际 OEE', color: tokens.accent, values: histValues }]}
labels={histLabels}
height={150}
yDigits={1}
refs={[{ v: oee4h.point * 100, label: `未来 4h 示意 ${pct(oee4h.point)}%` }]}
/>
<div style={{ display: 'flex', gap: 8, marginTop: 6, flexWrap: 'wrap' }}>
<Chip color={tokens.textSub}>点值 {pct(oee4h.point)}%</Chip>
<Chip color={tokens.textMuted}>示意区间 {pct(oee4h.bandLow)}–{pct(oee4h.bandHigh)}%</Chip>
<Chip color={tokens.textMuted}>历史 {fc.history.length} 日</Chip>
{oee4h.degraded && <Chip color={tokens.warning}>降级·仅供参考</Chip>}
</div>
</Card>
) : (
<Card
title="未来 4h OEE · 不外推(OEE 缺口)"
icon={<Gauge size={14} color={tokens.textMuted} />}
right={<Chip color={tokens.textMuted}>缺口 · 不标 0</Chip>}
>
<Note>{fc.gap ?? '当日实际 OEE 缺口:不做 OEE 外推、不显示 0。'}</Note>
{histValues.length > 0 ? (
<TrendChart
series={[{ name: '历史实际 OEE', color: tokens.accent, values: histValues }]}
labels={histLabels}
height={150}
yDigits={1}
/>
) : (
<Note>历史窗口内亦无有限 OEE 读数(Q 无良率源),趋势图不画假点。</Note>
)}
<Table head={<><Th>外推入参</Th><Th>状态</Th><Th>处置</Th></>}>
<tr>
<Td color={tokens.textSub}>当日实际 OEE 锚点</Td>
<Td><Chip color={tokens.textMuted}>缺口(G)</Chip></Td>
<Td color={tokens.textMuted}>不做 OEE 外推、不显示 0</Td>
</tr>
<tr>
<Td color={tokens.textSub}>历史有限 OEE 序列</Td>
<Td mono>{fc.history.length} 日</Td>
<Td color={tokens.textMuted}>{fc.history.length === 0 ? '无有限读数,不画假点' : '仅有限日入外推'}</Td>
</tr>
<tr>
<Td color={tokens.textSub}>实测六桶(停机风险入参)</Td>
<Td><Chip color={tokens.success}>可用</Chip></Td>
<Td color={tokens.textMuted}>停机风险仍按后端实测桶规则外推</Td>
</tr>
</Table>
</Card>
)}
</div>
</>
)}
{/* 四门槛:全未达,标灰不标绿 */}
<Card title="四门槛:不齐备就不上模型" icon={<ListChecks size={14} color={tokens.textMuted} />} full note="照录建议书 §4.6.1。四门槛全未达,原型处置一律「不训练」。">
<Table head={<><Th>门槛</Th><Th>要求</Th><Th>当前状态</Th><Th>达标</Th><Th>原型处置</Th></>}>
{FORECAST_GATES.map((g) => (
<tr key={g.id}>
<Td bold color={tokens.textSub}>{g.name}</Td>
<Td mono>{g.requirement}</Td>
<Td color={tokens.textMuted}>{g.status}</Td>
<Td><Chip color={tokens.textMuted}>{g.met ? '已达' : '未达'}</Chip></Td>
<Td color={tokens.textMuted}>{g.disposition}</Td>
</tr>
))}
</Table>
</Card>
{/* 生产阶段模型路线:只登记,原型不实现 */}
<Card title="生产阶段模型路线(P4~P5 · 原型不实现)" icon={<Rocket size={14} color={tokens.info} />} full note={MODEL_ROADMAP_NOTE}>
<Table head={<><Th>任务</Th><Th>特征</Th><Th>标签来源</Th><Th>模型路线</Th><Th>阶段</Th></>}>
{MODEL_ROADMAP.map((r) => (
<tr key={r.task}>
<Td bold color={tokens.textSub}>{r.task}</Td>
<Td color={tokens.textMuted}>{r.features}</Td>
<Td color={tokens.textSub}>{r.labelSource}</Td>
<Td color={tokens.info}>{r.models}</Td>
<Td><Chip color={tokens.textMuted}>{r.phase}</Chip></Td>
</tr>
))}
</Table>
</Card>
</div>
);
}
/** 停机风险占比计量条(量程 0–20%,3% / 10% 两条阈值刻度)。纯展示,数字由 L3 传入。 */
function RiskMeter({ pct: value, color }: { pct: number; color: string }) {
const { tokens } = useTheme();
const span = 0.20;
const w = Math.min(100, (value / span) * 100);
const tick = (t: number) => `${(t / span) * 100}%`;
return (
<div style={{ minWidth: 0 }}>
<div style={{ position: 'relative', height: 16, borderRadius: 5, background: tokens.accentBg, overflow: 'hidden' }}>
<div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: `${w}%`, background: `linear-gradient(90deg, ${color}, ${color}99)`, borderRadius: 5, transition: 'width .5s cubic-bezier(0.4,0,0.2,1)' }} />
{[STOP_RISK_MED, STOP_RISK_HIGH].map((t) => (
<div key={t} style={{ position: 'absolute', left: tick(t), top: 0, bottom: 0, width: 1.5, background: tokens.textMuted, opacity: 0.7 }} />
))}
</div>
<div style={{ position: 'relative', height: 14, fontSize: 9.5, color: tokens.textMuted }}>
<span style={{ position: 'absolute', left: tick(STOP_RISK_MED), transform: 'translateX(-50%)' }}>中 {STOP_RISK_MED * 100}%</span>
<span style={{ position: 'absolute', left: tick(STOP_RISK_HIGH), transform: 'translateX(-50%)' }}>高 {STOP_RISK_HIGH * 100}%</span>
<span style={{ position: 'absolute', right: 0 }}>量程 20%</span>
</div>
</div>
);
}
@@ -0,0 +1,274 @@
/**
* 集成接口页(integration 页签 · W2-C)。
*
* ★ 契约与状态页,不是真实连接(建议书 §1.3 不承诺清单 / 规划书 4.4.3~4.4.4):
* IF-01~IF-12 十二份契约 · 六条采集通道 · 三级实时性 L1/L2/L3 · 适配器关键陷阱 8 类 ·
* 可靠性工程七条 · 接口异常处置五类 · 过渡方案十项。
*
* 三条诚实纪律:
* ① 原型不接任何真实系统,六通道全部模拟适配器读本地种子;所有接口 signoff 非「已签收」。
* ② 三级实时性必须在 UI 上区分,不能一律标「实时」;SOW「<200ms」只适用 L1(规划书 H.7)。
* ③ 拿不到接口怎么办逐系统给答案(过渡方案 + 切换条件),未签收接口标灰「待联调」。
*
* 全部读 data/oee/integration 常量字典与 integrationStats() 现算,视图不二次计算。
*/
import { Plug, Network, Radio, AlertTriangle, RefreshCw, ShieldAlert, Cable, Timer } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
IF_CONTRACTS, CHANNELS, LATENCY_TIERS, LATENCY_200MS_NOTE, ADAPTER_TRAPS, LOG_ADAPTER_METHODS,
RELIABILITY_MEASURES, IF_EXCEPTIONS, TRANSITION_PLANS, SIGNOFF_STANDARD_NOTE, integrationStats,
type IfSignoff, type LatencyTier,
} from '../../data/oee/integration';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, GapBox,
grid2, pageStyle,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
export default function OeeIntegration({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const is = integrationStats();
const signoffColor = (s: IfSignoff): string =>
s === '已签收' ? tokens.success : s === '联调中' ? tokens.info : s === '过渡方案' ? tokens.warning : tokens.textMuted;
const tierColor = (t: LatencyTier): string =>
t === 'L1' ? tokens.danger : t === 'L2' ? tokens.info : t === 'L3' ? tokens.textSub : tokens.textMuted;
const channelProtoLabel = (p: 'seed' | 'contract' | 'manual'): string =>
p === 'seed' ? '种子' : p === 'contract' ? '契约' : '录入·W3';
const channelProtoColor = (p: 'seed' | 'contract' | 'manual'): string =>
p === 'seed' ? tokens.textSub : p === 'contract' ? tokens.textMuted : tokens.warning;
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="集成接口" icon={<Plug size={15} color={tokens.accent} />}
extra={<Chip color={tokens.warning} title="原型不接任何真实系统;本页显示契约+状态+过渡方案,不是真实连接">契约占位 · 无真实连接</Chip>}
/>
<Note>
原型<strong>不接任何真实系统</strong>:六通道全部为模拟适配器读本地种子,本页显示 IF-01~IF-12 的<strong>契约 + 频率 + 幂等 + 联调签收状态 + 过渡方案</strong>,不显示真实连接。
全部 {is.total} 份接口均未签收(过渡方案 {is.transition} / 未启动 {is.notStarted}),未签收接口不进入 P2/P3 依赖项。{LATENCY_200MS_NOTE}
</Note>
<Tiles items={[
{ label: '接口契约', value: String(is.total), sub: 'IF-01~IF-12', color: tokens.text },
{ label: '已签收', value: String(is.signed), sub: '联调中 ' + is.integrating, color: tokens.textMuted, title: '原型无真实联调,已签收恒为 0' },
{ label: '过渡方案', value: String(is.transition), sub: '种子/录入替代', color: tokens.warning },
{ label: '未启动', value: String(is.notStarted), sub: '待生产阶段', color: tokens.textMuted },
{ label: '采集通道', value: String(is.channels), sub: `种子 ${is.channelSeed} · 占位 ${is.channelContract}`, color: tokens.textSub },
{ label: '适配器实现', value: `${is.adaptersImplemented}/${is.adaptersTotal}`, sub: 'DEK/FT/ASLT', color: tokens.textSub, title: '原型实现 3 个适配器,此表另列 5 类关键陷阱(契约态)' },
]} />
{/* demo 沙箱:六条采集通道的合成/演示状态(静态说明,不连接后端) */}
<Card
title="导入水位(demo 沙箱 · 静态说明)"
icon={<RefreshCw size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted} title="demo 沙箱:数据来自内置合成种子,不连接后端">demo · 不落库</Chip>}
note="本工程为 demo 沙箱,六条采集通道均为模拟适配器读内置合成种子,不产生任何真实导入水位、行数或 DQ 计数。下表说明各数据源在 demo 中的合成/演示状态;下方 IF-01~IF-12 契约仍为草案占位(未签收),演示状态≠接口联调签收。"
>
<Table maxHeight={300} head={<>
<Th>数据源 / 通道</Th><Th>协议与频率</Th><Th>覆盖范围</Th><Th>demo 状态</Th>
</>}>
{CHANNELS.map((c) => (
<tr key={c.name}>
<Td bold color={tokens.textSub}>{c.name}</Td>
<Td mono color={tokens.textMuted}>{c.protocol} · {c.frequency}</Td>
<Td color={tokens.textMuted}>{c.coverage}</Td>
<Td>
<Chip color={channelProtoColor(c.proto)}>{channelProtoLabel(c.proto)}</Chip>
<div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 2 }}>{c.protoImpl}</div>
</Td>
</tr>
))}
</Table>
</Card>
{/* 12 接口契约 */}
<Card
title={`12 接口契约(IF-01~IF-12)`}
icon={<Network size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title={SIGNOFF_STANDARD_NOTE}>联调签收标准</Chip>}
note="方向/协议/频率/幂等逐条转录规划书 4.4.3。签收状态原型只有「过渡方案/未启动」两态,绝不出现「已签收」。原型替代列诚实描述当前用什么顶替(种子适配器/录入台/无),切换条件见下方过渡方案十项。"
>
<Table maxHeight={380} head={<>
<Th>编号</Th><Th>接口名称 · 方向</Th><Th>协议与格式</Th><Th>频率</Th><Th>级</Th><Th>幂等与补偿</Th><Th>责任方 · 阶段</Th><Th>签收状态</Th><Th>原型替代</Th>
</>}>
{IF_CONTRACTS.map((c) => (
<tr key={c.id}>
<Td bold mono>{c.id}</Td>
<Td color={tokens.textSub}>
<span title={`过渡方案:${c.transition}|切换条件:${c.switchCondition}`}>{c.name}</span>
<div style={{ fontSize: 10, color: tokens.textMuted }}>{c.direction}</div>
</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{c.protocol}</span></Td>
<Td mono color={tokens.textSub}>{c.frequency}</Td>
<Td><Chip color={tierColor(c.tier)} title={c.tier === '—' ? '会话级/事件级,不属 L1~L3 实时模型' : `${c.tier} 级实时性`}>{c.tier}</Chip></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{c.idempotency}</span></Td>
<Td color={tokens.textSub}>{c.owner}<div style={{ fontSize: 10, color: tokens.textMuted }}>{c.stage}</div></Td>
<Td><Chip color={signoffColor(c.signoff)} title={c.signoff === '未启动' ? '待联调·未启动' : '过渡方案替代中'}>{c.signoff}</Chip></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10 }} title={c.protoImpl}>{c.demo === 'seed' ? '种子适配器' : c.demo === 'manual' ? '录入台·W3' : '无'}</span></Td>
</tr>
))}
</Table>
</Card>
{/* 六通道 + 三级实时性 */}
<div style={grid2}>
<Card
title="六条采集通道"
icon={<Radio size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="原型全部为模拟适配器或契约占位,不显示真实连接">模拟适配器</Chip>}
note="LogAdapter 五方法为采集层统一契约(parse/normalize/dedupKey/clockCorrect/evidenceRef)。IO/三色灯通道需加装硬件,过渡期靠人工录入;人工录入通道 14 个 D 类事件真实可提交(断言⑥,W3-A)。"
>
<Table head={<>
<Th>通道</Th><Th>协议/方式</Th><Th>频率</Th><Th>覆盖</Th><Th>原型实现</Th>
</>}>
{CHANNELS.map((ch) => (
<tr key={ch.name}>
<Td bold color={tokens.textSub}>{ch.name}{ch.needsHardware && <div style={{ marginTop: 2 }}><Chip color={tokens.warning}>需加装</Chip></div>}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5, overflowWrap: 'anywhere' }}>{ch.protocol}</span></Td>
<Td mono color={tokens.textSub}>{ch.frequency}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5, overflowWrap: 'anywhere' }}>{ch.coverage}</span></Td>
<Td><Chip color={channelProtoColor(ch.proto)} title={ch.protoImpl}>{channelProtoLabel(ch.proto)}</Chip></Td>
</tr>
))}
</Table>
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>LogAdapter 五方法</Th><Th>职责</Th>
</>}>
{LOG_ADAPTER_METHODS.map((m) => (
<tr key={m.method}>
<Td mono bold color={tokens.accent}>{m.method}</Td>
<Td color={tokens.textMuted}>{m.desc}</Td>
</tr>
))}
</Table>
</div>
</Card>
<Card
title="三级实时性(L1 / L2 / L3)"
icon={<Timer size={14} color={tokens.accent} />}
right={<Chip color={tokens.danger} title={LATENCY_200MS_NOTE}>&lt;200ms 只适用 L1</Chip>}
note="原型必须在 UI 上区分三级,不能一律标「实时」。SOW 的「<200ms」只适用 L1 流式(规划书 H.7);原型不得在任何页面宣称全链路 <200ms。原型无流式(L1),OEE 重算为种子批跑(L2),班次窗口切分(L3)。"
>
<Table head={<>
<Th>级别</Th><Th>时延</Th><Th>覆盖</Th><Th>生产实现</Th><Th>原型实现</Th>
</>}>
{LATENCY_TIERS.map((t) => (
<tr key={t.tier}>
<Td bold color={tierColor(t.tier)}>{t.tier} {t.label}</Td>
<Td mono color={tokens.textSub}>{t.latency}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{t.coverage}</span></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{t.prodImpl}</span></Td>
<Td color={tokens.textSub}><span style={{ fontSize: 10.5 }}>{t.protoImpl}</span></Td>
</tr>
))}
</Table>
<div style={{ marginTop: 8 }}>
<Tiles items={[
{ label: 'L1 流式接口', value: String(is.tierL1), sub: '1~5 秒', color: tokens.danger },
{ label: 'L2 批量接口', value: String(is.tierL2), sub: '≤15min', color: tokens.info },
{ label: 'L3 班次级', value: String(is.tierL3), sub: '班后', color: tokens.textSub },
{ label: '会话/事件级', value: String(is.tierOther), sub: '不属实时模型', color: tokens.textMuted },
]} />
</div>
<div style={{ marginTop: 8 }}>
<GapBox
missing="流式计算 / 消息队列 / 时序库"
dependsOn="Kafka(或 RocketMQ) + TimescaleDB + Redis"
stage="生产 P1"
note="原型数据全在浏览器内存/SQLite WASM,总量控制在 20MB 内以保证首屏 ≤3s;峰值 200 次/秒削峰、月分区、连续聚合均为生产阶段,原型不需要。"
/>
</div>
</Card>
</div>
{/* 适配器陷阱 + 可靠性七条 */}
<div style={grid2}>
<Card
title={`适配器关键陷阱(${is.adaptersTotal} 类 · 实现 ${is.adaptersImplemented})`}
icon={<AlertTriangle size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="原型实现 DEK 定宽91 / FT Handler CSV GBK / ASLT 文本流 三个适配器">DEK · FT · ASLT</Chip>}
note="原型实现的 3 个必须正确处理这些陷阱,否则数字失真;此表另列 5 类契约态陷阱(全厂适配器类别以主数据台账为准)。报警≠停机:FT「Temperature Wait」单日 500 次若判停机则 A=0,必须按 alarm_class 分类(event_def)。"
>
<Table maxHeight={300} head={<>
<Th>设备</Th><Th>陷阱</Th><Th>正确处理</Th><Th>原型</Th>
</>}>
{ADAPTER_TRAPS.map((a) => (
<tr key={a.device}>
<Td bold color={tokens.textSub}>{a.device}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{a.trap}</span></Td>
<Td color={tokens.textSub}><span style={{ fontSize: 10.5 }}>{a.correctHandle}</span></Td>
<Td><Chip color={a.implemented ? tokens.success : tokens.textMuted}>{a.implemented ? '已实现' : '契约'}</Chip></Td>
</tr>
))}
</Table>
</Card>
<Card
title="可靠性工程七条"
icon={<RefreshCw size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>实现 {is.reliabilityImplemented}/{is.reliabilityTotal}</Chip>}
note="原型实现前四条(可在种子里演示)+ 健康监控,后两条标生产阶段。增量拉取/幂等重试/编码自适应/时钟校正均在 DEK 一日 4 次改钟、三种编码混杂、滚动文件样本里真实演示。"
>
<Table head={<>
<Th right>#</Th><Th>措施</Th><Th>说明</Th><Th>阶段</Th>
</>}>
{RELIABILITY_MEASURES.map((r) => (
<tr key={r.n}>
<Td right mono color={tokens.textMuted}>{r.n}</Td>
<Td bold color={tokens.textSub}>{r.measure}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{r.detail}</span></Td>
<Td><Chip color={r.proto === '实现' ? tokens.success : tokens.textMuted}>{r.proto}</Chip></Td>
</tr>
))}
</Table>
</Card>
</div>
{/* 异常处置 + 过渡方案 */}
<div style={grid2}>
<Card
title="接口异常处置五类"
icon={<ShieldAlert size={14} color={tokens.accent} />}
note="数据延迟会影响 OEE 出数(按延迟标注),其余四类不影响(保留上一版口径/转录入台/丢弃计数)。来源不可用转录入台补录,恢复后自动比对替换——不静默补数。"
>
<Table head={<>
<Th>异常类别</Th><Th>判定条件</Th><Th>系统处置</Th><Th>影响 OEE</Th>
</>}>
{IF_EXCEPTIONS.map((e) => (
<tr key={e.category}>
<Td bold color={tokens.textSub}>{e.category}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{e.condition}</span></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{e.handling}</span></Td>
<Td color={e.affectsOee.startsWith('是') ? tokens.warning : tokens.textSub}><span style={{ fontSize: 10.5 }}>{e.affectsOee}</span></Td>
</tr>
))}
</Table>
</Card>
<Card
title="过渡方案十项(拿不到接口怎么办)"
icon={<Cable size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>{TRANSITION_PLANS.length} 系统</Chip>}
note="逐系统回答「拿不到接口怎么办」,比「风险:日志格式与时效需确认」有用得多,直接回应 SOW 的 9 系统集成要求。每个过渡态标明当前用什么替代、切换条件是什么。"
>
<Table maxHeight={300} head={<>
<Th>系统</Th><Th>依赖方</Th><Th>用途</Th><Th>过渡方案</Th>
</>}>
{TRANSITION_PLANS.map((t) => (
<tr key={t.system}>
<Td bold color={tokens.textSub}>{t.system}</Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10 }}>{t.dependsOn}</span></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{t.usage}</span></Td>
<Td color={tokens.textSub}><span style={{ fontSize: 10.5 }}>{t.transition}</span></Td>
</tr>
))}
</Table>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,280 @@
/**
* 2D 线体图(linemap 页签 · W4-B,建议书 §5.2.2 no.12,P1 提前做实)。
*
* ★ SVG 拓扑 + 状态灯 + 瓶颈定位。状态灯=**数据可得性/可发布性**,不是绩效红绿灯:
* 绿 ok=有读数且可发布 · amber warn=有读数但 DQ 阻断或存疑 · 灰 gap=无读数(缺口)。
* 实时运行/停机需直采通道;本工程为 demo 沙箱,状态灯只表达数据可得性,不冒充实时设备状态。
*
* 取数纪律(断言②):节点一律从 L3 lineMapNodes(bizDate) 取,视图不二次计算 OEE。
* DEK001=日志贯通实测(唯一);DCP005=SRF 仿真下游代表站(瓶颈环);FT 三台/ASLT=仿真;
* 其余 SRF 台账在但无仿真读数=缺口;BUF001 不计 OEE,只给缓冲占用率。
* 主流程只连有 mainPathSeq 的 5 台,辅助工站不臆造拓扑连线。
*/
import { lazy, Suspense, useState } from 'react';
import { Factory, Network } from 'lucide-react';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import { lineMapNodes, lineMapStats, deriveAlerts, type LineMapNode, type LineMapLight } from '../../lib/oeeService';
import { ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, grid2, pageStyle, pct } from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
const LIGHT_LABEL: Record<LineMapLight, string> = { ok: '有读数·可发布', warn: '有读数·阻断/存疑', gap: '无读数·缺口' };
const SOURCE_SHORT: Record<LineMapNode['source'], string> = { ANCHOR_LOG: '实测', SRF_SIM: '仿真', FT_SIM: '仿真', ASLT_SIM: '仿真', NONE: '缺口' };
function lightColor(tk: ThemeTokens, l: LineMapLight): string {
return l === 'ok' ? tk.success : l === 'warn' ? tk.warning : tk.textMuted;
}
const trunc = (s: string, n: number): string => (s.length > n ? s.slice(0, n - 1) + '…' : s);
/* 3D 可选包(SOW 数字孪生):React.lazy 拆包,2D 视图不加载 three */
const OeeLineMap3D = lazy(() => import('./OeeLineMap3D'));
export default function OeeLineMap({ filter }: Omit<OeeViewProps, 'onNavigate'> & { onNavigate?: (tab: string, focusDevice?: string) => void }) {
const { tokens } = useTheme();
const [view, setView] = useState<'2d' | '3d'>('2d');
const scope = resolveScope(filter);
const nodes = lineMapNodes(scope.bizDate);
const stats = lineMapStats(nodes);
/* 2026-11-14 动效层:流光/呼吸只挂真实状态——当日告警设备(deriveAlerts 非空)与瓶颈节点。
告警是锚点单机日级结果,故告警设备集合至多一台;day=null(未接入)时集合为空→全图静态。
循环动效(dash-flow / pulse-glow)因此永远对应真实告警/瓶颈事实,不冒充实时设备状态。 */
const alerts = scope.day ? deriveAlerts(scope.day) : [];
const alertDeviceId = alerts.length > 0 && scope.day ? scope.day.device.id : null;
const hot = (id: string) => id === alertDeviceId;
const nodeById = new Map(nodes.map((n) => [n.deviceId, n]));
const flowLink = (a: string, b: string) => {
/* 未接入范围(day=null)全图静态:没有当日结果就不演流光,避免暗示有实时数据 */
if (!scope.day) return false;
const na = nodeById.get(a);
const nb = nodeById.get(b);
return hot(a) || hot(b) || Boolean(na?.bottleneck) || Boolean(nb?.bottleneck);
};
const srfMain = nodes.filter((n) => n.region === 'SRF' && n.mainPathSeq != null).sort((a, b) => (a.mainPathSeq ?? 0) - (b.mainPathSeq ?? 0));
const srfAux = nodes.filter((n) => n.region === 'SRF' && n.mainPathSeq == null);
const ft = nodes.filter((n) => n.region === 'FT');
const aslt = nodes.filter((n) => n.region === 'ASLT');
const asltNode = aslt[0];
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title={view === '2d' ? '2D 线体图' : '3D 线体场景'}
icon={<Factory size={15} color={tokens.accent} />}
extra={
<span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<Chip color={tokens.textMuted} title="demo 沙箱:状态灯只表达数据可得性,不冒充实时设备状态">状态灯=数据可得性</Chip>
</span>
}
/>
<Tiles items={[
{ label: '台账设备', value: String(stats.total), sub: '3 区域 3 线', color: tokens.text, title: '17 台台账(SRF 13 / FT 3 / ASLT 1)' },
{ label: '计 OEE', value: String(stats.oeeDevices), sub: '剔除中间缓存', color: tokens.textSub, title: 'BUF001 不生产、不计 OEE' },
{ label: '日志贯通', value: String(stats.wired), sub: 'DEK001 实测', color: tokens.success, title: '唯一日志贯通全链路到行号的设备' },
{ label: '模板仿真', value: String(stats.sim), sub: 'SRF/FT/ASLT', color: tokens.info, title: 'DCP005 + FT 三台 + ASLT,模板仿真非实测' },
{ label: '无读数缺口', value: String(stats.gap), sub: '标灰不标绿', color: tokens.textMuted, title: '台账在但日志通道未接 / 无仿真读数' },
{ label: '瓶颈', value: stats.bottleneck.join('/') || '—', sub: 'SRF 缓冲解耦', color: tokens.warning, title: 'LINE_BY_ID.bottleneckDeviceId:SRF→DCP005(751min 缺失 + 124min 停机〔POC〕)' },
]} />
{/* 拓扑:2D SVG / 3D 场景切换。3D=SOW 数字孪生可选包,造型为真实机台照片的风格化抽象 */}
<Card title={view === '2d' ? '线体拓扑(SVG · 状态灯 + 瓶颈定位)' : '线体拓扑(3D 场景 · 设备造型抽象 + 状态灯)'} icon={<Network size={14} color={tokens.accent} />} full
right={
<div style={{ display: 'flex', gap: 4 }} role="group" aria-label="线体图视图切换">
{(['2d', '3d'] as const).map((v) => (
<button key={v} data-role={`view-${v}`} onClick={() => setView(v)}
style={{
padding: '3px 11px', borderRadius: 7, fontSize: 11, fontWeight: 700, cursor: 'pointer',
border: `1px solid ${view === v ? tokens.borderAccent : tokens.border}`,
background: view === v ? tokens.accentBg : 'transparent',
color: view === v ? tokens.accent : tokens.textSub,
}}>
{v === '2d' ? '2D 拓扑' : '3D 场景'}
</button>
))}
</div>
}
note={view === '2d'
? '主流程只连有工位序号的 5 台(DEK→FUJI→Datacon→回流焊→AOI);辅助工站无序号,不臆造拓扑连线。FT 三台并行按投入量加权,不串连。流动虚线/呼吸外环只出现在涉及当日告警或瓶颈的连线/设备上,是真实状态的强调,不是实时设备心跳。'
: '3D 造型参照真实机台照片做风格化抽象(DEK 圆拱罩+前观察窗 / FUJI 模块+供料 reel 排 / Datacon 前玻璃窗+侧显示器臂 / 回流焊隧道+排风管 / AOI 顶屏蓝光),不是 CAD 复刻。状态灯语义与 2D 一致=数据可得性;呼吸 halo 只挂当日告警设备、瓶颈环静态、传送带高亮只挂告警/瓶颈事实,未接入全静态,不是实时设备心跳。'}>
{view === '2d' ? (
<svg viewBox="0 0 1000 440" style={{ width: '100%', height: 'auto', display: 'block' }} preserveAspectRatio="xMidYMid meet">
<defs>
<marker id="lm-arrow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 Z" fill={tokens.textMuted} />
</marker>
<marker id="lm-arrow-flow" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">
<path d="M0,0 L6,3 L0,6 Z" fill={tokens.accent} />
</marker>
</defs>
{/* ── SRF band ── */}
<text x={24} y={22} fontSize={12} fontWeight={700} fill={tokens.text}>SRF 表面贴装 · 13 台(主流程 5 + 辅助/缓存 8)</text>
{srfMain.map((n, i) => {
const x = 24 + i * 192;
if (i >= srfMain.length - 1) return null;
/* 流光只挂真实状态:连线任一端是当日告警设备或瓶颈。dasharray "6 6"(周期12)
整除 dash-flow 关键帧偏移 -24,循环无缝;其余连线保持原实线。 */
const flow = flowLink(n.deviceId, srfMain[i + 1].deviceId);
return (
<line
key={`a${n.deviceId}`} x1={x + 152} y1={65} x2={24 + (i + 1) * 192} y2={65}
stroke={flow ? tokens.accent : tokens.textMuted} strokeWidth={1.4}
strokeDasharray={flow ? '6 6' : undefined}
className={flow ? 'dash-flow' : undefined}
markerEnd={flow ? 'url(#lm-arrow-flow)' : 'url(#lm-arrow)'}
data-role={flow ? 'flow-link' : undefined}
/>
);
})}
{srfMain.map((n, i) => <NodeBox key={n.deviceId} node={n} x={24 + i * 192} y={34} w={152} h={62} pulse={hot(n.deviceId)} />)}
<text x={24} y={114} fontSize={10} fill={tokens.textMuted}>辅助工站 / 中间缓存(无主流程序号,不臆造拓扑)</text>
{srfAux.map((n, i) => <NodeBox key={n.deviceId} node={n} x={24 + i * 121} y={120} w={110} h={54} compact pulse={hot(n.deviceId)} />)}
{/* ── FT band ── */}
<line x1={24} y1={196} x2={976} y2={196} stroke={tokens.border} strokeWidth={1} />
<text x={24} y={216} fontSize={12} fontWeight={700} fill={tokens.text}>FT 终测 · 3 台(并行 · 按投入量加权)</text>
{ft.map((n, i) => <NodeBox key={n.deviceId} node={n} x={24 + i * 338} y={228} w={210} h={62} pulse={hot(n.deviceId)} />)}
{/* ── ASLT band ── */}
<line x1={24} y1={312} x2={976} y2={312} stroke={tokens.border} strokeWidth={1} />
<text x={24} y={332} fontSize={12} fontWeight={700} fill={tokens.text}>ASLT 系统级测试 · 1 台 12 Site(事件驱动 · 活跃窗口)</text>
{asltNode && <NodeBox node={asltNode} x={24} y={344} w={250} h={76} pulse={hot(asltNode.deviceId)} />}
{asltNode?.sites?.map((s, i) => {
const c = i % 6, r = Math.floor(i / 6);
const x = 300 + c * 110, y = 344 + r * 38;
const col = s.enabledPct > 0 ? tokens.success : tokens.textMuted;
return (
<g key={s.siteId}>
<rect x={x} y={y} width={104} height={32} rx={6} fill={tokens.panelBgAlt} stroke={tokens.borderSub} strokeWidth={1} />
<text x={x + 8} y={y + 13} fontSize={9} fill={tokens.textMuted}>Site {s.siteId}</text>
<rect x={x + 8} y={y + 19} width={88} height={6} rx={3} fill={tokens.accentBg} />
<rect x={x + 8} y={y + 19} width={Math.max(0, Math.min(88, s.enabledPct * 88))} height={6} rx={3} fill={col} />
<text x={x + 96} y={y + 13} fontSize={9} textAnchor="end" fill={col} fontWeight={700}>{pct(s.enabledPct, 0)}%</text>
</g>
);
})}
</svg>
) : (
<Suspense fallback={
<div style={{ height: 560, display: 'grid', placeItems: 'center', color: tokens.textMuted, fontSize: 12 }}>
3D 场景加载中…
</div>
}>
<OeeLineMap3D nodes={nodes} alertDeviceId={alertDeviceId} wired={Boolean(scope.day)} flowLink={flowLink} />
</Suspense>
)}
</Card>
<div style={grid2}>
{/* 图例 */}
<Card title="图例" icon={<Network size={14} color={tokens.textSub} />}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
{(['ok', 'warn', 'gap'] as LineMapLight[]).map((l) => (
<div key={l} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 11, height: 11, borderRadius: '50%', background: lightColor(tokens, l), flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>{LIGHT_LABEL[l]}</span>
</div>
))}
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 13, borderRadius: 4, border: `1.5px dashed ${tokens.warning}`, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>{view === '2d' ? '瓶颈环(SRF→DCP005)' : '瓶颈地环(SRF→DCP005,静态)'}</span>
</div>
{view === '2d' ? (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 0, borderTop: `2px dashed ${tokens.accent}`, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>流动虚线:连线涉及当日告警设备或瓶颈(无则实线)</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 13, borderRadius: 4, border: `1.5px solid ${tokens.warning}`, opacity: 0.8, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>呼吸外环:当日有告警的设备(无告警不呼吸)</span>
</div>
</>
) : (
<>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 0, borderTop: `2px solid ${tokens.accent}`, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>传送带高亮:连线涉及当日告警设备或瓶颈(无则灰)</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 13, borderRadius: '50%', border: `1.5px solid ${tokens.warning}`, opacity: 0.8, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>呼吸 halo:当日有告警的设备(无告警不呼吸)</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span style={{ width: 13, height: 13, borderRadius: 4, border: `1.5px solid ${tokens.accent}`, flexShrink: 0 }} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>点击设备:右侧明细卡(数字与下表同源 L3)</span>
</div>
</>
)}
<Note>来源徽标:实测=日志贯通(DEK001)· 仿真=模板产物(DCP005/FT/ASLT)· 缺口=无读数。状态灯只表达数据可得性,不表达实时运行/停机。{view === '2d' ? '流动与呼吸只挂当日真实告警/瓶颈事实,未接入范围全图静态。' : '3D 造型为风格化抽象非 CAD;高亮与呼吸只挂当日真实告警/瓶颈事实,未接入范围全场景静态。'}</Note>
</div>
</Card>
{/* 诚实披露 */}
<Card title="这张图诚实说什么" icon={<Factory size={14} color={tokens.warning} />} tone={tokens.warning}>
<Note>
17 台台账里只有 <strong>DEK001 一台</strong>日志贯通到行号(绿);DCP005 与 FT 三台、ASLT 是<strong>模板仿真</strong>(非实测);
其余 <strong>{stats.gap} 台标灰</strong>——台账在、日志通道未接,不显示 0。BUF001 中间缓存不生产、不计 OEE,只作缓冲解耦输入。
瓶颈环指向 DCP005(POC:751min 缺失 + 124min 停机)。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。
</Note>
</Card>
</div>
{/* 节点明细表:17 台逐台来源/状态灯/三率/备注 */}
<Card title="节点明细(17 台 · 数字一律 L3 现算)" full>
<Table head={<><Th>设备</Th><Th>工站</Th><Th>线别</Th><Th>来源</Th><Th>状态灯</Th><Th right>OEE</Th><Th right>A</Th><Th right>P</Th><Th right>Q</Th><Th minW={160}>备注</Th></>} maxHeight={360}>
{nodes.map((n) => (
<tr key={n.deviceId}>
<Td bold nowrap color={tokens.text}>{n.deviceId}{n.bottleneck && <Chip color={tokens.warning}>瓶颈</Chip>}</Td>
<Td color={tokens.textSub}>{n.station}</Td>
<Td color={tokens.textMuted}>{n.lineId}</Td>
<Td><Chip color={n.source === 'ANCHOR_LOG' ? tokens.success : n.source === 'NONE' ? tokens.textMuted : tokens.info}>{SOURCE_SHORT[n.source]}</Chip></Td>
<Td color={lightColor(tokens, n.light)}><span style={{ fontWeight: 700 }}>{LIGHT_LABEL[n.light].split('·').map((part, k) => <span key={k} style={{ whiteSpace: 'nowrap' }}>{k > 0 && <br />}{k === 0 && <i style={{ display: 'inline-block', width: 7, height: 7, borderRadius: 7, marginRight: 5, background: lightColor(tokens, n.light) }} />}{part}{k === 0 && '·'}</span>)}</span></Td>
<Td right mono bold color={n.oee == null ? tokens.textMuted : lightColor(tokens, n.light)}>{n.oee == null ? '—' : `${pct(n.oee)}%`}</Td>
<Td right mono color={tokens.textMuted}>{n.a == null ? '—' : pct(n.a)}</Td>
<Td right mono color={tokens.textMuted}>{n.p == null ? '—' : pct(n.p)}</Td>
<Td right mono color={tokens.textMuted}>{n.q == null ? '—' : pct(n.q)}</Td>
<Td breakAny color={tokens.textMuted}>{n.buffer ? `缓存占用 ${pct(n.buffer.occupancyPct, 0)}% · B≥${n.buffer.minCapacity} 解耦${n.buffer.fullyDecoupled ? '成立' : '不成立'}` : n.note}</Td>
</tr>
))}
</Table>
</Card>
</div>
);
}
/** 单个设备节点(SVG <g>):状态灯 + 设备码 + 工站 + OEE + 来源徽标 + 瓶颈环。纯展示,数字由 L3 传入。
* pulse=当日有告警的设备才挂呼吸外环(2026-11-14 动效层)。SVG 元素上 box-shadow 无效,
* 故用 pulse-glow(opacity 关键帧)做外环呼吸;只动 opacity,不改节点几何。 */
export function NodeBox({ node, x, y, w, h, compact, pulse }: { node: LineMapNode; x: number; y: number; w: number; h: number; compact?: boolean; pulse?: boolean }) {
const { tokens } = useTheme();
const col = lightColor(tokens, node.light);
const idSize = compact ? 10 : 11;
const oeeSize = compact ? 13 : 15;
const stationMax = compact ? 9 : 13;
const oeeText = node.oee == null ? '—' : `${pct(node.oee)}%`;
return (
<g>
{pulse && (
<rect
x={x - 6} y={y - 6} width={w + 12} height={h + 12} rx={12}
fill="none" stroke={tokens.warning} strokeWidth={1.5}
style={{ animation: 'tfamd-pulse-glow 2.4s ease-in-out infinite' }}
data-role="pulse-node"
/>
)}
{node.bottleneck && <rect x={x - 3.5} y={y - 3.5} width={w + 7} height={h + 7} rx={11} fill="none" stroke={tokens.warning} strokeWidth={1.5} strokeDasharray="5 3" />}
<rect x={x} y={y} width={w} height={h} rx={9} fill={tokens.panelBgAlt} stroke={col} strokeWidth={node.bottleneck ? 1.8 : 1.1} />
<circle cx={x + 12} cy={y + 13} r={4.5} fill={col} />
<text x={x + 22} y={y + 17} fontSize={idSize} fontWeight={700} fill={tokens.text}>{trunc(node.deviceId, compact ? 11 : 16)}</text>
<text x={x + w - 9} y={y + 17} fontSize={8.5} textAnchor="end" fill={tokens.textMuted}>{SOURCE_SHORT[node.source]}</text>
<text x={x + 11} y={y + 31} fontSize={9.5} fill={tokens.textMuted}>{trunc(node.station, stationMax)}</text>
<text x={x + 11} y={y + h - 8} fontSize={oeeSize} fontWeight={800} fill={node.oee == null ? tokens.textMuted : col}>{oeeText}</text>
{node.oee == null && <text x={x + 40} y={y + h - 8} fontSize={8.5} fill={tokens.textMuted}>无读数</text>}
{node.bottleneck && <text x={x + w - 9} y={y + h - 8} fontSize={9} textAnchor="end" fontWeight={700} fill={tokens.warning}>瓶颈</text>}
</g>
);
}
@@ -0,0 +1,572 @@
/**
* 3D 线体场景(线体图页签内 2D/3D 切换 · SOW「数字孪生 3D 线体场景」可选包)。
*
* ★ 造型纪律:五类主设备造型参照真实机台照片做「数字抽象」(DEK 圆拱罩+前观察窗+顶置显示器、
* FUJI NXT 模块单元+前后供料 reel 排、Datacon 高柜+前玻璃窗+侧挂显示器臂、回流焊长隧道+顶排风管、
* AOI 箱体+倾斜顶屏+蓝光检测窗),辅助工站各有可识别形态;是风格化抽象,不是 CAD 复刻。
* ★ 取数纪律(断言②):节点/三率/状态灯一律 L3 lineMapNodes 传入,本组件不做任何 OEE 计算。
* 状态灯语义与 2D 完全一致=数据可得性(ok 绿 / warn amber / gap 灰),不是实时运行/停机。
* ★ 动效纪律:呼吸 halo 只挂当日告警设备(alertDeviceId,day=null 时为 null);瓶颈环静态;
* 传送带高亮只挂 flowLink(告警/瓶颈事实,未接入全静态);reduced-motion 停呼吸;无虚假心跳。
* ★ 依赖:three + @react-three/fiber@8(React18),OrbitControls 走 three/examples,不引 drei;
* 本文件被 React.lazy 拆包,2D 视图不加载 three。
*/
import { useEffect, useMemo, useRef, useState } from 'react';
import * as THREE from 'three';
import { Canvas, useFrame, useThree, type ThreeEvent } from '@react-three/fiber';
import { OrbitControls as OrbitControlsImpl } from 'three/examples/jsm/controls/OrbitControls.js';
import { useTheme, type ThemeTokens } from '../../context/ThemeContext';
import type { LineMapNode, LineMapLight } from '../../lib/oeeService';
import { pct } from './oeeUi';
type V3 = [number, number, number];
type Kind = 'dek' | 'fuji' | 'datacon' | 'reflow' | 'aoi' | 'dpvs' | 'xray' | 'jet' | 'flip' | 'loader' | 'conveyor' | 'green' | 'buffer' | 'tester' | 'aslt';
/** 每类设备的占地/高度(世界单位),用于布局、瓶颈环半径与标签高度 */
const DIM: Record<Kind, { w: number; d: number; h: number }> = {
dek: { w: 3.2, d: 2.6, h: 2.2 }, fuji: { w: 6.4, d: 2.8, h: 2.6 }, datacon: { w: 3.0, d: 2.6, h: 2.8 },
reflow: { w: 7.2, d: 2.4, h: 1.8 }, aoi: { w: 3.0, d: 2.6, h: 2.2 }, dpvs: { w: 2.2, d: 1.8, h: 1.9 },
xray: { w: 2.4, d: 2.0, h: 2.1 }, jet: { w: 2.2, d: 1.8, h: 1.9 }, flip: { w: 2.2, d: 1.8, h: 1.8 },
loader: { w: 2.2, d: 1.8, h: 1.9 }, conveyor: { w: 2.4, d: 1.4, h: 0.9 }, green: { w: 2.4, d: 1.4, h: 1.2 },
buffer: { w: 2.6, d: 1.6, h: 2.0 }, tester: { w: 3.4, d: 2.6, h: 3.0 }, aslt: { w: 9.0, d: 2.2, h: 2.6 },
};
function kindOf(n: LineMapNode): Kind {
if (n.region === 'FT') return 'tester';
if (n.region === 'ASLT') return 'aslt';
switch (n.deviceId) {
case 'DEK001': return 'dek';
case 'NXT001': return 'fuji';
case 'DCP005': return 'datacon';
case 'RF001': return 'reflow';
case 'AOI001': return 'aoi';
case 'DPVS001': return 'dpvs';
case 'XR001': return 'xray';
case 'JET001': return 'jet';
case 'MBT001': return 'flip';
case 'LDR001': return 'loader';
case 'SPL001': return 'conveyor';
case 'GRN001': return 'green';
default: return 'buffer';
}
}
const lightColor = (tk: ThemeTokens, l: LineMapLight): string => (l === 'ok' ? tk.success : l === 'warn' ? tk.warning : tk.textMuted);
/** tokens 里部分色是 rgba()(带透明度),THREE.Color 会丢 alpha 并告警;进 three 前统一转 rgb() */
function solidify(t: ThemeTokens): ThemeTokens {
const out = { ...t } as Record<string, string>;
for (const k of Object.keys(out)) {
const v = out[k];
if (typeof v === 'string' && v.startsWith('rgba(')) {
const m = v.match(/rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,/);
if (m) out[k] = `rgb(${m[1]},${m[2]},${m[3]})`;
}
}
return out as unknown as ThemeTokens;
}
/* ── 几何小件:统一 meshStandardMaterial,颜色全部来自 tokens/常量玻璃色 ── */
function Box({ a, p, r, c, e, ei = 0, rough = 0.55, metal = 0.12, op }: {
a: V3; p?: V3; r?: V3; c: string; e?: string; ei?: number; rough?: number; metal?: number; op?: number;
}) {
return (
<mesh position={p} rotation={r}>
<boxGeometry args={a} />
<meshStandardMaterial color={c} emissive={e ?? '#000000'} emissiveIntensity={ei} roughness={rough} metalness={metal}
transparent={op != null} opacity={op ?? 1} />
</mesh>
);
}
function Cyl({ rt, rb, h, p, r, c, e, ei = 0, seg = 14, theta, rough = 0.5, metal = 0.15 }: {
rt: number; rb: number; h: number; p?: V3; r?: V3; c: string; e?: string; ei?: number; seg?: number; theta?: number; rough?: number; metal?: number;
}) {
return (
<mesh position={p} rotation={r}>
<cylinderGeometry args={[rt, rb, h, seg, 1, false, 0, theta ?? Math.PI * 2]} />
<meshStandardMaterial color={c} emissive={e ?? '#000000'} emissiveIntensity={ei} roughness={rough} metalness={metal} />
</mesh>
);
}
/** 圆拱罩:半圆柱横放(DEK/Datacon 的弧形顶盖特征) */
function Hood({ w, r, p, c }: { w: number; r: number; p: V3; c: string }) {
return <Cyl rt={r} rb={r} h={w} p={p} r={[0, 0, Math.PI / 2]} c={c} seg={20} theta={Math.PI} />;
}
const GLASS = '#101820';
const FEET = (w: number, d: number, c: string) => (
<>
{[[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz], i) => (
<Cyl key={i} rt={0.06} rb={0.09} h={0.16} p={[sx * (w / 2 - 0.25), 0.08, sz * (d / 2 - 0.25)]} c={c} />
))}
</>
);
/* ── 五类主设备 + 辅助工站的抽象造型(要素来自真实机台照片) ── */
function Model({ kind, tk, node }: { kind: Kind; tk: ThemeTokens; node: LineMapNode }) {
const body = tk.panelBgAlt, trim = tk.border, dark = tk.textMuted;
const { w, d, h } = DIM[kind];
switch (kind) {
case 'dek': /* 圆拱罩 + 前观察窗 + 下柜体 + 顶置显示器 + 急停 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.45, d]} p={[0, h * 0.225 + 0.16, 0]} c={body} />
<Box a={[w * 0.94, h * 0.34, d * 0.9]} p={[0, h * 0.62, 0]} c={body} />
<Hood w={w * 0.94} r={d * 0.45} p={[0, h * 0.79, 0]} c={body} />
<Box a={[w * 0.62, h * 0.3, 0.06]} p={[w * 0.1, h * 0.6, d / 2]} c={GLASS} rough={0.25} metal={0.4} />
<Box a={[w * 0.3, h * 0.14, 0.05]} p={[-w * 0.3, h * 0.5, d / 2]} c={GLASS} rough={0.3} />
<Cyl rt={0.035} rb={0.035} h={0.7} p={[-w * 0.25, h + 0.35, -d * 0.2]} c={dark} />
<Box a={[0.85, 0.55, 0.06]} p={[-w * 0.25, h + 0.75, -d * 0.2]} r={[-0.12, 0, 0]} c={GLASS} rough={0.3} />
<Cyl rt={0.07} rb={0.07} h={0.05} p={[w * 0.28, h * 0.45, d / 2 + 0.03]} r={[Math.PI / 2, 0, 0]} c={tk.danger} e={tk.danger} ei={0.35} />
</>
);
case 'fuji': /* 长底座 + 4 模块单元(斜控制面板+小屏)+ 双层供料 reel 排 + 蓝色饰带 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, 0.5, d]} p={[0, 0.41, 0]} c={dark} />
<Box a={[w, h * 0.52, d * 0.8]} p={[0, h * 0.52, -d * 0.08]} c={body} />
<Box a={[w, 0.1, 0.06]} p={[0, h * 0.72, d * 0.33]} c={tk.info} e={tk.info} ei={0.25} />
{[0, 1, 2, 3].map((m) => {
const mx = -w / 2 + (m + 0.5) * (w / 4);
return (
<group key={m} position={[mx, 0, 0]}>
<Box a={[w / 4 - 0.12, h * 0.42, d * 0.5]} p={[0, h * 0.72, -d * 0.1]} c={body} />
<Box a={[w / 4 - 0.2, 0.42, 0.1]} p={[0, h * 0.95, d * 0.16]} r={[-0.35, 0, 0]} c={trim} />
<Box a={[w / 4 - 0.42, 0.26, 0.04]} p={[0, h * 0.97, d * 0.21]} r={[-0.35, 0, 0]} c={GLASS} rough={0.3} />
{[0, 1].map((tier) => (
<group key={tier} position={[0, 0.62 + tier * 0.42, d * 0.42]}>
<Box a={[w / 4 - 0.16, 0.06, 0.34]} p={[0, -0.16, 0]} c={trim} />
{Array.from({ length: 7 }, (_, i) => (
<Box key={i} a={[0.07, 0.3, 0.26]} p={[-(w / 4 - 0.3) / 2 + i * ((w / 4 - 0.3) / 6), 0, 0]} c={i % 2 ? trim : dark} />
))}
</group>
))}
</group>
);
})}
</>
);
case 'datacon': /* 高柜 + 圆顶 + 大前玻璃窗(内龙门横梁)+ 侧挂显示器臂+键盘托 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.62, d]} p={[0, h * 0.31 + 0.16, 0]} c={body} />
<Hood w={w} r={d * 0.5} p={[0, h * 0.78, 0]} c={body} />
<Box a={[w * 0.72, h * 0.34, 0.06]} p={[0, h * 0.55, d / 2]} c={GLASS} rough={0.2} metal={0.45} op={0.92} />
<Box a={[w * 0.6, 0.06, 0.1]} p={[0, h * 0.6, d / 2 - 0.12]} c={trim} />
<Box a={[0.06, h * 0.26, 0.1]} p={[-w * 0.2, h * 0.55, d / 2 - 0.12]} c={trim} />
<Box a={[0.06, h * 0.26, 0.1]} p={[w * 0.2, h * 0.55, d / 2 - 0.12]} c={trim} />
<Cyl rt={0.04} rb={0.04} h={w * 0.55} p={[-w / 2 - w * 0.27, h * 0.5, 0]} r={[0, 0, Math.PI / 2]} c={trim} />
<Box a={[0.7, 0.5, 0.05]} p={[-w / 2 - w * 0.5, h * 0.62, 0]} r={[0, 0.35, 0]} c={GLASS} rough={0.3} />
<Box a={[0.6, 0.04, 0.28]} p={[-w / 2 - w * 0.45, h * 0.34, 0.1]} c={trim} />
</>
);
case 'reflow': /* 长隧道体 + 顶加热罩 + 温区分缝 + 顶排风管×2 + 进出口导轨 + 入口小屏 */
return (
<>
<Box a={[w, h * 0.6, d]} p={[0, h * 0.3 + 0.1, 0]} c={body} />
<Box a={[w * 0.96, h * 0.26, d * 0.82]} p={[0, h * 0.73, 0]} c={body} />
{[1, 2, 3, 4].map((z) => (
<Box key={z} a={[0.05, h * 0.24, d * 0.84]} p={[-w / 2 + z * (w / 5), h * 0.73, 0]} c={trim} />
))}
{[-w * 0.22, w * 0.18].map((px, i) => (
<group key={i} position={[px, h * 0.86, 0]}>
<Cyl rt={0.14} rb={0.16} h={1.1} p={[0, 0.55, 0]} c={trim} metal={0.5} rough={0.35} />
<Cyl rt={0.14} rb={0.14} h={0.5} p={[0.18, 1.15, 0]} r={[0, 0, -0.7]} c={trim} metal={0.5} rough={0.35} />
</group>
))}
<Box a={[1.2, 0.08, d * 0.5]} p={[-w / 2 - 0.6, h * 0.42, 0]} c={dark} />
<Box a={[1.2, 0.08, d * 0.5]} p={[w / 2 + 0.6, h * 0.42, 0]} c={dark} />
<Box a={[0.5, 0.36, 0.05]} p={[-w / 2 + 0.4, h * 0.62, d / 2 + 0.03]} r={[-0.15, 0, 0]} c={GLASS} rough={0.3} />
{[0, 1, 2, 3, 4, 5].map((i) => (
<Box key={i} a={[w / 6 - 0.1, h * 0.34, 0.04]} p={[-w / 2 + (i + 0.5) * (w / 6), h * 0.3, d / 2 + 0.01]} c={trim} />
))}
</>
);
case 'aoi': case 'dpvs': /* 箱体 + 倾斜顶屏 + 前检测窗(AOI 蓝光 / DPVS 绿光) */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.6, d]} p={[0, h * 0.3 + 0.16, 0]} c={body} />
<Box a={[w * 0.8, h * 0.22, d * 0.7]} p={[0, h * 0.71, 0]} c={body} />
<Box a={[w * 0.66, 0.5, 0.06]} p={[0, h * 0.95, d * 0.1]} r={[-0.3, 0, 0]} c={GLASS} rough={0.3} />
<Box a={[w * 0.7, h * 0.2, 0.05]} p={[0, h * 0.42, d / 2]} c={GLASS} e={kind === 'aoi' ? tk.info : tk.success} ei={0.5} rough={0.3} />
<Cyl rt={0.06} rb={0.06} h={0.05} p={[w * 0.36, h * 0.62, d / 2 + 0.03]} r={[Math.PI / 2, 0, 0]} c={tk.danger} e={tk.danger} ei={0.3} />
</>
);
case 'xray': /* 铅灰防护箱体 + 小圆观察窗 + 顶部警示标 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.75, d]} p={[0, h * 0.375 + 0.16, 0]} c={dark} metal={0.4} rough={0.4} />
<Box a={[w * 0.9, h * 0.14, d * 0.9]} p={[0, h * 0.83, 0]} c={trim} />
<Cyl rt={0.22} rb={0.22} h={0.06} p={[0, h * 0.5, d / 2]} r={[Math.PI / 2, 0, 0]} c={GLASS} rough={0.2} metal={0.5} />
<Box a={[0.3, 0.3, 0.03]} p={[w * 0.3, h * 0.68, d / 2 + 0.02]} c={tk.warning} e={tk.warning} ei={0.3} />
</>
);
case 'jet': /* 点胶:小箱 + 龙门 + 双点胶针头 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.4, d]} p={[0, h * 0.2 + 0.16, 0]} c={body} />
<Box a={[0.08, h * 0.5, 0.08]} p={[-w * 0.35, h * 0.65, 0]} c={trim} />
<Box a={[0.08, h * 0.5, 0.08]} p={[w * 0.35, h * 0.65, 0]} c={trim} />
<Box a={[w * 0.8, 0.08, 0.1]} p={[0, h * 0.88, 0]} c={trim} />
{[-0.2, 0.2].map((px, i) => (
<Cyl key={i} rt={0.03} rb={0.012} h={0.3} p={[px, h * 0.72, 0]} c={tk.info} e={tk.info} ei={0.3} />
))}
</>
);
case 'flip': /* 翻转机:箱体 + 45° 翻转框 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.45, d]} p={[0, h * 0.225 + 0.16, 0]} c={body} />
<group position={[0, h * 0.72, 0]} rotation={[0, 0, Math.PI / 4]}>
<Box a={[w * 0.6, 0.07, 0.07]} p={[0, w * 0.3, 0]} c={trim} />
<Box a={[w * 0.6, 0.07, 0.07]} p={[0, -w * 0.3, 0]} c={trim} />
<Box a={[0.07, w * 0.6, 0.07]} p={[w * 0.3, 0, 0]} c={trim} />
<Box a={[0.07, w * 0.6, 0.07]} p={[-w * 0.3, 0, 0]} c={trim} />
</group>
</>
);
case 'loader': /* 上料机:料仓_magazine 叠板 + 推板机构 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w * 0.5, h * 0.8, d]} p={[-w * 0.25, h * 0.4 + 0.16, 0]} c={body} />
{[0, 1, 2, 3, 4].map((i) => (
<Box key={i} a={[w * 0.44, 0.04, d * 0.8]} p={[-w * 0.25, 0.4 + i * 0.28, 0]} c={tk.success} ei={0.12} e={tk.success} />
))}
<Box a={[w * 0.4, h * 0.3, d * 0.6]} p={[w * 0.28, h * 0.35, 0]} c={trim} />
<Box a={[0.06, 0.06, d * 0.7]} p={[w * 0.1, h * 0.5, 0]} c={dark} />
</>
);
case 'conveyor': case 'green': /* 分轨/绿皮:双轨 conveyor + 支腿(绿皮加绿色罩) */
return (
<>
{[-1, 1].map((s) => (
<group key={s}>
<Box a={[0.08, h * 0.7, 0.08]} p={[-w * 0.4, h * 0.35, s * d * 0.4]} c={dark} />
<Box a={[0.08, h * 0.7, 0.08]} p={[w * 0.4, h * 0.35, s * d * 0.4]} c={dark} />
</group>
))}
<Box a={[w, 0.08, 0.1]} p={[0, h * 0.75, -d * 0.4]} c={trim} />
<Box a={[w, 0.08, 0.1]} p={[0, h * 0.75, d * 0.4]} c={trim} />
<Box a={[w * 0.94, 0.04, d * 0.6]} p={[0, h * 0.72, 0]} c={GLASS} />
{kind === 'green' && <Box a={[w * 0.6, h * 0.4, d * 0.7]} p={[0, h * 0.95, 0]} c={tk.success} op={0.55} rough={0.4} />}
</>
);
case 'buffer': /* 中间缓存:多层货架 + 占位板 */
return (
<>
{[-1, 1].map((s) => (
<Box key={s} a={[0.08, h, d]} p={[s * w * 0.46, h / 2 + 0.1, 0]} c={trim} />
))}
{[0, 1, 2].map((i) => (
<group key={i}>
<Box a={[w * 0.92, 0.05, d]} p={[0, 0.35 + i * 0.6, 0]} c={trim} />
<Box a={[w * 0.3, 0.16, d * 0.7]} p={[-w * 0.2 + i * w * 0.18, 0.46 + i * 0.6, 0]} c={tk.info} op={0.7} />
</group>
))}
</>
);
case 'tester': /* FT 终测一体机:测试柜 + 斜前面板 + 圆形测试头 + handler 臂 */
return (
<>
{FEET(w, d, dark)}
<Box a={[w, h * 0.7, d]} p={[0, h * 0.35 + 0.16, 0]} c={body} />
<Box a={[w * 0.8, h * 0.16, 0.08]} p={[0, h * 0.78, d * 0.3]} r={[-0.3, 0, 0]} c={trim} />
<Box a={[w * 0.6, h * 0.1, 0.04]} p={[0, h * 0.8, d * 0.36]} r={[-0.3, 0, 0]} c={GLASS} rough={0.3} />
<Cyl rt={0.5} rb={0.55} h={0.5} p={[0, h * 0.86, -d * 0.1]} c={trim} metal={0.45} rough={0.35} />
<Cyl rt={0.32} rb={0.32} h={0.12} p={[0, h * 1.12, -d * 0.1]} c={dark} metal={0.5} />
<Box a={[0.12, 0.12, d * 0.7]} p={[w * 0.42, h * 0.6, 0]} c={dark} />
<Box a={[0.3, 0.2, 0.3]} p={[w * 0.42, h * 0.6, d * 0.35]} c={trim} />
</>
);
case 'aslt': /* 系统级测试:12 Site 机架(2 行×6),使能 Site 亮绿 */
return (
<>
<Box a={[w, 0.16, d]} p={[0, 0.24, 0]} c={dark} />
<Box a={[w, 0.12, d]} p={[0, h * 0.52, 0]} c={trim} />
<Box a={[w, 0.12, d]} p={[0, h, 0]} c={trim} />
{[-1, 1].map((s) => (
<Box key={s} a={[0.12, h, d]} p={[s * (w / 2 - 0.06), h / 2 + 0.2, 0]} c={trim} />
))}
{(node.sites ?? []).map((s, i) => {
const c = i % 6, r = Math.floor(i / 6);
const on = s.enabledPct > 0;
return (
<Box key={s.siteId} a={[w / 6 - 0.22, h * 0.34, d * 0.8]}
p={[-w / 2 + (c + 0.5) * (w / 6), 0.42 + r * (h * 0.46), 0]}
c={on ? tk.success : dark} e={on ? tk.success : '#000000'} ei={on ? 0.35 : 0} op={on ? 0.9 : 0.6} />
);
})}
</>
);
}
}
/** 三色塔灯:亮段=状态灯语义(ok 绿 / warn amber / gap 全灭),不是实时运行态 */
function StackLight({ tk, light, p }: { tk: ThemeTokens; light: LineMapLight; p: V3 }) {
const segs: { c: string; on: boolean }[] = [
{ c: tk.danger, on: false },
{ c: tk.warning, on: light === 'warn' },
{ c: tk.success, on: light === 'ok' },
];
return (
<group position={p}>
<Cyl rt={0.03} rb={0.03} h={0.3} p={[0, 0.15, 0]} c={tk.textMuted} />
{segs.map((s, i) => (
<Cyl key={i} rt={0.075} rb={0.075} h={0.13} p={[0, 0.36 + i * 0.14, 0]}
c={s.on ? s.c : '#4a4f55'} e={s.on ? s.c : '#000000'} ei={s.on ? 1.3 : 0} seg={10} />
))}
</group>
);
}
/** 呼吸 halo:只挂当日告警设备;reduced-motion 静态。只动 opacity,不改几何。 */
function PulseRing({ r, color, reduced }: { r: number; color: string; reduced: boolean }) {
const mat = useRef<THREE.MeshBasicMaterial>(null);
useFrame(({ clock }) => {
if (!mat.current) return;
mat.current.opacity = reduced ? 0.7 : 0.35 + 0.45 * (0.5 + 0.5 * Math.sin(clock.elapsedTime * 2.6));
});
return (
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.05, 0]}>
<torusGeometry args={[r, 0.05, 8, 48]} />
<meshBasicMaterial ref={mat} color={color} transparent opacity={0.7} />
</mesh>
);
}
/** Canvas 纹理标签(设备码/区域名),始终面向相机。画布宽度按实测文字宽动态定,避免长标签裁切。 */
function Label({ text, color, p, width }: { text: string; color: string; p: V3; width: number }) {
const tex = useMemo(() => {
const c = document.createElement('canvas');
const probe = c.getContext('2d');
const font = '700 30px system-ui, -apple-system, sans-serif';
let cw = 256;
if (probe) {
probe.font = font;
cw = Math.max(64, Math.ceil(probe.measureText(text).width) + 24);
}
c.width = cw; c.height = 64;
const g = c.getContext('2d');
if (g) {
g.font = font;
g.textAlign = 'center'; g.textBaseline = 'middle';
g.fillStyle = color;
g.fillText(text, cw / 2, 32);
}
const t = new THREE.CanvasTexture(c);
t.anisotropy = 4;
t.userData.aspect = 64 / cw;
return t;
}, [text, color]);
useEffect(() => () => tex.dispose(), [tex]);
return (
<sprite position={p} scale={[width, width * (tex.userData.aspect as number), 1]}>
<spriteMaterial map={tex} transparent depthWrite={false} />
</sprite>
);
}
function Orbit({ tz = -8 }: { tz?: number }) {
const { camera, gl } = useThree();
const ref = useRef<OrbitControlsImpl | null>(null);
useEffect(() => {
const c = new OrbitControlsImpl(camera, gl.domElement);
c.target.set(0, 1, tz);
c.enableDamping = true; c.dampingFactor = 0.08;
c.minDistance = 12; c.maxDistance = 90;
c.maxPolarAngle = Math.PI * 0.49;
c.update();
ref.current = c;
return () => { c.dispose(); ref.current = null; };
}, [camera, gl, tz]);
useFrame(() => { ref.current?.update(); });
return null;
}
function useReducedMotion(): boolean {
const [rm, setRm] = useState(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches);
useEffect(() => {
const m = window.matchMedia('(prefers-reduced-motion: reduce)');
const f = () => setRm(m.matches);
m.addEventListener('change', f);
return () => m.removeEventListener('change', f);
}, []);
return rm;
}
/** 主流程传送带:flow(告警/瓶颈事实)时 accent 高亮,否则静态灰;未接入全静态 */
function Conveyor({ x1, x2, flow, tk }: { x1: number; x2: number; flow: boolean; tk: ThemeTokens }) {
const len = x2 - x1, cx = (x1 + x2) / 2;
const c = flow ? tk.accent : tk.border;
return (
<group>
<Box a={[len, 0.06, 0.08]} p={[cx, 0.55, -0.5]} c={c} e={flow ? tk.accent : '#000000'} ei={flow ? 0.3 : 0} />
<Box a={[len, 0.06, 0.08]} p={[cx, 0.55, 0.5]} c={c} e={flow ? tk.accent : '#000000'} ei={flow ? 0.3 : 0} />
<Box a={[len, 0.03, 0.8]} p={[cx, 0.52, 0]} c={flow ? tk.accentBg : tk.panelBgAlt} />
<mesh position={[cx, 0.62, 0]} rotation={[0, 0, -Math.PI / 2]}>
<coneGeometry args={[0.12, 0.3, 10]} />
<meshStandardMaterial color={c} emissive={flow ? tk.accent : '#000000'} emissiveIntensity={flow ? 0.4 : 0} />
</mesh>
</group>
);
}
export interface OeeLineMap3DProps {
nodes: LineMapNode[];
/** 当日告警设备(deriveAlerts 非空时=锚点单机),day=null 传 null → 无呼吸 */
alertDeviceId: string | null;
/** scope.day 是否存在;false=未接入,传送带不高亮 */
wired: boolean;
flowLink: (a: string, b: string) => boolean;
}
export default function OeeLineMap3D({ nodes, alertDeviceId, wired, flowLink }: OeeLineMap3DProps) {
const { tokens: raw } = useTheme();
const tk = useMemo(() => solidify(raw), [raw]);
const reduced = useReducedMotion();
const [selected, setSelected] = useState<string | null>(null);
const sel = nodes.find((n) => n.deviceId === selected) ?? null;
/* 布局:SRF 主流程沿 X 串行(含传送带)居前排 z=0;辅助排 z=-6、FT 并行排 z=-11.5、
ASLT 机架 z=-16.5 依次退后,避免辅助排遮挡主流程(相机从 +Z 看向 -Z) */
const layout = useMemo(() => {
const main = nodes.filter((n) => n.region === 'SRF' && n.mainPathSeq != null)
.sort((a, b) => (a.mainPathSeq ?? 0) - (b.mainPathSeq ?? 0));
const pos = new Map<string, V3>();
let cursor = -15.4;
const centers: { id: string; x: number; w: number }[] = [];
for (const n of main) {
const { w } = DIM[kindOf(n)];
pos.set(n.deviceId, [cursor + w / 2, 0, 0]);
centers.push({ id: n.deviceId, x: cursor + w / 2, w });
cursor += w + 1.8;
}
const aux = nodes.filter((n) => n.region === 'SRF' && n.mainPathSeq == null);
aux.forEach((n, i) => pos.set(n.deviceId, [-14 + i * 3.8, 0, -6]));
const ft = nodes.filter((n) => n.region === 'FT');
ft.forEach((n, i) => pos.set(n.deviceId, [-9 + i * 9, 0, -11.5]));
const aslt = nodes.filter((n) => n.region === 'ASLT');
aslt.forEach((n) => pos.set(n.deviceId, [-6, 0, -16.5]));
return { main, centers, pos };
}, [nodes]);
const pick = (id: string) => (e: ThreeEvent<MouseEvent>) => { e.stopPropagation(); setSelected(id); };
const hover = (on: boolean) => (e: ThreeEvent<PointerEvent>) => {
e.stopPropagation();
// 光标只作用于模块内画布,不写 document.body(避免污染平台全局光标)
const el = e.nativeEvent.target as HTMLElement | null;
if (el) el.style.cursor = on ? 'pointer' : '';
};
return (
<div style={{ position: 'relative', width: '100%', height: 560, borderRadius: 9, overflow: 'hidden', background: tk.panelBg }} data-role="linemap-3d">
<Canvas camera={{ position: [-3, 17, 26], fov: 40 }} dpr={[1, 2]} gl={{ antialias: true }}
onPointerMissed={() => setSelected(null)}>
<color attach="background" args={[tk.panelBg]} />
<fog attach="fog" args={[tk.panelBg, 60, 120]} />
<ambientLight intensity={0.75} />
<hemisphereLight intensity={0.35} color={tk.text} groundColor={tk.border} />
<directionalLight position={[12, 20, 10]} intensity={1.15} />
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0, -8]}>
<planeGeometry args={[40, 26]} />
<meshStandardMaterial color={tk.bodyBg} roughness={0.9} metalness={0} />
</mesh>
<gridHelper args={[40, 20, tk.border, tk.borderSub]} position={[0, 0.02, -8]} />
<Orbit tz={-8} />
<>
<Label text="SRF 主流程" color={tk.text} p={[-0.4, 0.9, 4.6]} width={4.6} />
<Label text="辅助/缓存" color={tk.textMuted} p={[-18, 1.4, -6]} width={3.8} />
<Label text="FT 终测" color={tk.text} p={[-14.5, 1.6, -11.5]} width={3.4} />
<Label text="ASLT 12 Site" color={tk.text} p={[-14.5, 1.6, -16.5]} width={4.6} />
</>
{layout.centers.slice(0, -1).map((c, i) => {
const nxt = layout.centers[i + 1];
return <Conveyor key={c.id} x1={c.x + c.w / 2} x2={nxt.x - nxt.w / 2} flow={wired && flowLink(c.id, nxt.id)} tk={tk} />;
})}
{nodes.map((n) => {
const kind = kindOf(n);
const { w, d, h } = DIM[kind];
const p = layout.pos.get(n.deviceId) ?? [0, 0, 0];
const col = lightColor(tk, n.light);
const ringR = Math.max(w, d) * 0.62 + 0.25;
const isAlert = n.deviceId === alertDeviceId;
const isSel = n.deviceId === selected;
return (
<group key={n.deviceId} position={p} onClick={pick(n.deviceId)}
onPointerOver={hover(true)} onPointerOut={hover(false)}>
<Model kind={kind} tk={tk} node={n} />
<StackLight tk={tk} light={n.light} p={[w / 2 - 0.3, h, d / 2 - 0.3]} />
{/* 状态灯地贴:与 2D 状态灯同语义同色 */}
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.03, d / 2 + 0.45]}>
<circleGeometry args={[0.16, 16]} />
<meshBasicMaterial color={col} />
</mesh>
{n.bottleneck && (
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.04, 0]}>
<torusGeometry args={[ringR, 0.05, 8, 48]} />
<meshBasicMaterial color={tk.warning} transparent opacity={0.9} />
</mesh>
)}
{isAlert && <PulseRing r={ringR + 0.22} color={tk.warning} reduced={reduced} />}
{isSel && (
<mesh rotation={[-Math.PI / 2, 0, 0]} position={[0, 0.06, 0]}>
<torusGeometry args={[ringR + 0.42, 0.045, 8, 48]} />
<meshBasicMaterial color={tk.accent} />
</mesh>
)}
<Label text={n.deviceId} color={col} p={[0, h + 1.15, 0]} width={2.8} />
</group>
);
})}
</Canvas>
{/* 操作提示 */}
<div style={{
position: 'absolute', left: 10, bottom: 10, padding: '4px 9px', borderRadius: 8,
background: tk.cardBg, border: `1px solid ${tk.border}`, fontSize: 10.5, color: tk.textMuted,
pointerEvents: 'none',
}}>
拖拽旋转 · 滚轮缩放 · 点击设备看明细(点空白取消)
</div>
{/* 下钻明细:数字一律 L3 传入,与 2D 明细表同源 */}
{sel && (
<div data-role="lm3d-info" style={{
position: 'absolute', right: 10, top: 10, width: 252, maxHeight: 'calc(100% - 20px)', overflow: 'auto',
background: tk.cardBg, border: `1px solid ${tk.border}`, borderRadius: 10, boxShadow: tk.cardShadow,
padding: '10px 12px', fontSize: 11, color: tk.textSub,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
<span style={{ width: 9, height: 9, borderRadius: '50%', background: lightColor(tk, sel.light), flexShrink: 0 }} />
<strong style={{ fontSize: 12.5, color: tk.text }}>{sel.deviceId}</strong>
{sel.bottleneck && <span style={{ fontSize: 9.5, fontWeight: 700, color: tk.warning }}>瓶颈</span>}
<span style={{ flex: 1 }} />
<button onClick={() => setSelected(null)} aria-label="关闭明细"
style={{ border: 'none', background: 'transparent', color: tk.textMuted, cursor: 'pointer', fontSize: 13, lineHeight: 1, padding: 2 }}>×</button>
</div>
<div style={{ marginBottom: 4 }}>{sel.name} · {sel.station} · {sel.lineId}</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '3px 10px', fontFamily: 'ui-monospace, monospace' }}>
<span>OEE {sel.oee == null ? '—' : `${pct(sel.oee)}%`}</span>
<span>A {sel.a == null ? '—' : pct(sel.a)}</span>
<span>P {sel.p == null ? '—' : pct(sel.p)}</span>
<span>Q {sel.q == null ? '—' : pct(sel.q)}</span>
</div>
<div style={{ marginTop: 6, color: tk.textMuted }}>
{sel.buffer ? `缓存占用 ${pct(sel.buffer.occupancyPct, 0)}% · B≥${sel.buffer.minCapacity} 解耦${sel.buffer.fullyDecoupled ? '成立' : '不成立'}` : sel.note}
</div>
</div>
)}
</div>
);
}
@@ -0,0 +1,354 @@
/**
* 损失结构(structure 页签 · W2-B)。
*
* ★ 六桶零残差可视化:PPT = 有效生产时间(产出×ICT) + Σ已计量六桶 + 残差。
* 残差 = 未归因 IDLE(DQ-06)+ 未计量的性能/工艺损失(P/Q 桶无事件源,G 缺口),
* **绝不归一化、绝不塞进"其他"桶、不摊派**(G2 门);残差构成在分解卡里逐项点明。
* 干净日残差 0;脏日(2026-09-02)残差 > 0,照实暴露并触发 DQ-06 阻断。
*
* 纪律:
* ① 数字只从 L3 day.buckets / day.segments.totals / day.tiers 取,视图不二次计算。
* ② 推导桶(SPEED/PROCESS_DEFECT/STARTUP_DEFECT,derivedFromCycleDeviation)无成对事件,
* 标明是推导量、不提供事件级下钻;未单独计量的子因子(缺 EA 到场时间戳)标灰为数据缺口,不摊数。
* ③ 六桶分母统一为 PPT,不是 CT、不是日历时间。
*/
import { PieChart, Layers, AlertTriangle, Scissors, ShieldCheck, Repeat, FlaskConical, Scale } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import { ftDayByDate, asltDayByDate, ftCurrent, asltCurrent } from '../../lib/oeeService';
import { BUCKET_LABEL, BUCKET_FACTOR, LOSS_BUCKETS, type LossBucket } from '../../types/oee';
import { CALIBER_ITEMS, CALIBER_CONFIG } from '../../data/oee/calibers28';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, GapBox, EmptyBox,
grid2, grid3, pageStyle, pct, pctUnitOrGap, dur, hrs, qty, BUCKET_COLORS, FACTOR_COLORS,
} from './oeeUi';
import { HBarChart, StackedBarChart } from './charts';
import type { OeeViewProps } from './OeeOverview';
export default function OeeLoss({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const day = scope.day;
if (!day) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="损失结构" icon={<PieChart size={15} color={tokens.accent} />} />
<EmptyBox>
六桶损失分解仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。<br />
{scope.gap ?? scope.coverageNote}
</EmptyBox>
</div>
);
}
const isFuji = day.caliberVersion === 'fuji-day-v1';
const b = day.buckets;
const tot = day.segments.totals;
const bucketOf = (k: LossBucket) => b.buckets.find((x) => x.bucket === k)!;
const sumBuckets = b.buckets.reduce((a, x) => a + x.durationSec, 0);
/* PPT 分解堆叠条:有效生产 + 六桶 + 残差,恒等于 PPT。残差含未归因与未计量的 P/Q 损失。 */
const decompSegs = [
{ label: '有效生产', value: b.effectiveSec, color: tokens.success },
...LOSS_BUCKETS.map((k) => ({ label: BUCKET_LABEL[k], value: bucketOf(k).durationSec, color: BUCKET_COLORS[k] })),
{ label: '残差(未归因+G缺口)', value: b.residualSec, color: tokens.warning },
];
/* 残差构成(比较量,非重算指标):性能缺口 = RT − 产出×ICT,即无事件源的 P 损失。
fuji 量纲不同(模块秒 vs 颗×ICT),不展示该分解。 */
const perfGapSec = isFuji ? null : Math.max(0, tot.runSec - (tot.outputQty ?? 0) * (day.device.ictSec ?? 0));
const residualOtherSec = perfGapSec == null ? null : Math.max(0, b.residualSec - b.unattributedSec - perfGapSec);
/* ── 质量损失(Q 因子与 Rescreen 关联)──────────────────────────────────
三区域 Q 不同构,按**同一业务日**并列对照,绝不混算/求平均。
数字只从 L3 取:DEK 锚点 day.tiers.actual.q / day.buckets;FT ftDayByDate;ASLT asltDayByDate。
视图不二次计算 Q:公式串与操作数一律照录引擎 quantities(断言②)。 */
const ft = ftDayByDate(scope.bizDate) ?? ftCurrent();
const aslt = asltDayByDate(scope.bizDate) ?? asltCurrent();
const ftQ = (dev: (typeof ft.devices)[number], key: string) => dev.quantities.find((x) => x.key === key)!;
const asltQ = aslt.result.quantities.find((x) => x.key === 'q')!;
const qBuckets: LossBucket[] = ['PROCESS_DEFECT', 'STARTUP_DEFECT'];
const ftRep = ft.devices[0]; // 复测关联链展示用代表机(操作数照录,不代表全线)
/* 开机不良数量来自录入台 D 类补录:0=尚未补录(缺证据),不是"零损失"。
未补录前全部日志不良暂归过程不良,开机不良标「未补录」不标 0(诚实空态红线)。 */
const startupEntered = day.startupDefectQty > 0;
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="损失结构" icon={<PieChart size={15} color={tokens.accent} />}
extra={<Chip color={b.zeroResidual ? tokens.textSub : tokens.warning} title={b.residualNote}>
{b.zeroResidual ? '六桶残差 0' : `残差 ${dur(b.residualSec)}`}
</Chip>}
/>
<Tiles items={[
{ label: '负荷生产时间 PPT', value: hrs(tot.pptSec), sub: isFuji ? 'Σ模块 logged 秒(模块时间量纲)' : 'CT−PDT−UNKNOWN(h)', color: tokens.text, title: '三档共用分母,六桶占比的分母' },
{ label: '有效生产时间', value: hrs(b.effectiveSec), sub: '良品数×ICT(h)', color: tokens.success, title: tot.goodQty == null ? `良品数 G 缺口(无 NG/良率源),不按假设良率拆有效时间;ICT ${day.device.ictSec}s` : `良品 ${tot.goodQty} × ICT ${day.device.ictSec}s` },
{ label: 'Σ 六桶损失', value: hrs(sumBuckets), sub: `${pct(sumBuckets / (tot.pptSec || 1))}% of PPT`, color: tokens.textSub },
{ label: isFuji ? '残差(量纲差)' : '残差(未归因+G 缺口)', value: dur(b.residualSec), sub: b.zeroResidual ? '已完整解释' : isFuji ? '模块秒 vs 颗×ICT' : `未归因 ${dur(b.unattributedSec)}`, color: b.zeroResidual ? tokens.textSub : tokens.warning, title: b.residualNote },
{ label: '未归因占比', value: `${pct(b.unattributedPct)}%`, sub: b.unattributedPct > 0.05 ? '超 5% 阻断' : '≤5%', color: b.unattributedPct > 0.05 ? tokens.danger : tokens.textSub, title: '未归因 IDLE 时长 ÷ PPT,>5% 触发 DQ-06 结论暂缓发布' },
]} />
<div style={grid2}>
<Card
title="六桶损失排行"
icon={<Layers size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>分母 PPT</Chip>}
note={`六桶互斥且完备,每事件码唯一归口一个桶。A 类三桶(故障/换型/空转)有事件证据;P 桶(速度)与 Q 两桶(过程/开机不良)由节拍偏差推导,无成对事件。${isFuji ? ' fuji-day-v1:FAULT/CHANGEOVER/SPEED/PROCESS_DEFECT/STARTUP_DEFECT 五桶为 GAP 零(无成对事件时间源,不是「零损失」),仅 IDLE_MINOR=Σ板中暂停实测(draft Q4);残差为量纲差(模块秒 vs 颗×ICT),zero_residual=False。' : ''}`}
>
<HBarChart
items={LOSS_BUCKETS.map((k) => {
const row = bucketOf(k);
return {
label: `${BUCKET_LABEL[k]}(${BUCKET_FACTOR[k]})`,
value: row.durationSec,
display: dur(row.durationSec),
sub: `${pct(row.pctOfPlanTime)}%`,
color: BUCKET_COLORS[k],
};
})}
/>
<Note>
{LOSS_BUCKETS.filter((k) => bucketOf(k).derivedFromCycleDeviation).map((k) => BUCKET_LABEL[k]).join('、')}
{' '}为推导量(节拍偏差/检测结果),无事件级下钻;其余桶可下钻到事件族与原始日志行号。
</Note>
</Card>
<Card
title="PPT 时间分解(残差恒等)"
icon={<Scissors size={14} color={tokens.accent} />}
right={<Chip color={b.zeroResidual ? tokens.textSub : tokens.warning}>{b.zeroResidual ? '恒等成立' : '残差=未归因+缺口'}</Chip>}
note={b.residualNote}
>
<StackedBarChart
items={[{ key: 'ppt', label: 'PPT 分解', total: tot.pptSec, display: hrs(tot.pptSec) + 'h', segs: decompSegs }]}
unit="s"
/>
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>构成项</Th><Th right>时长</Th><Th right>占 PPT</Th><Th>归口</Th>
</>}>
<tr>
<Td bold color={tokens.success}>有效生产时间</Td>
<Td right mono>{dur(b.effectiveSec)}</Td>
<Td right mono>{pct(b.effectiveSec / (tot.pptSec || 1))}%</Td>
<Td color={tokens.textMuted}>良品×ICT</Td>
</tr>
{LOSS_BUCKETS.map((k) => {
const row = bucketOf(k);
return (
<tr key={k}>
<Td color={BUCKET_COLORS[k]} bold>{BUCKET_LABEL[k]}</Td>
<Td right mono>{dur(row.durationSec)}</Td>
<Td right mono>{pct(row.pctOfPlanTime)}%</Td>
<Td color={FACTOR_COLORS[row.factor]}>{row.factor}{row.derivedFromCycleDeviation ? ' · 推导' : ''}</Td>
</tr>
);
})}
<tr>
<Td bold color={tokens.warning}>{isFuji ? '残差(量纲差)' : '残差(未归因+缺口)'}</Td>
<Td right mono color={tokens.warning}>{dur(b.residualSec)}</Td>
<Td right mono>{pct(b.residualSec / (tot.pptSec || 1))}%</Td>
<Td color={tokens.textMuted}>{isFuji ? '=PPT−有效−Σ桶' : '=PPT−有效−Σ已计量桶'}</Td>
</tr>
</Table>
{!isFuji && !b.zeroResidual && (
<Note>
残差构成(L3 操作数相减,非重算指标):未归因 IDLE {dur(b.unattributedSec)}(占 PPT {pct(b.unattributedPct)}%,DQ-06)
+ 性能缺口 {dur(perfGapSec ?? 0)}(RT {hrs(tot.runSec)}h − 产出×ICT {hrs((tot.outputQty ?? 0) * (day.device.ictSec ?? 0))}h,P 桶无事件源)
{residualOtherSec != null && residualOtherSec > 60 ? ` + 其他未解释 ${dur(residualOtherSec)}` : ''}。
未计量部分只随残差暴露,不摊进任何桶,也不按假设比例拆分。
</Note>
)}
</div>
</Card>
</div>
{/* 因子下钻 + 数据缺口(缺 EA 到场时间戳的子因子标灰,不摊数) */}
<Card
title="一级/二级因子下钻"
icon={<AlertTriangle size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted}>{b.factors.length} 个因子 · {b.untimedSubFactors.length} 项缺口</Chip>}
note="一个状态段只归一个因子(整段归首事件),其余事件只留证不计时,避免同段时长被重复计入两个因子。被跳过的子因子作为数据缺口显式披露。"
>
{b.factors.length > 0 ? (
<Table head={<>
<Th>一级因子</Th><Th>二级因子</Th><Th>归口桶</Th><Th>A/P/Q</Th><Th right>时长</Th><Th right>占 PPT</Th><Th>事件码</Th>
</>} maxHeight={260}>
{b.factors.map((f) => (
<tr key={`${f.factorL1}|${f.factorL2}`}>
<Td>{f.factorL1}</Td>
<Td color={tokens.textSub}>{f.factorL2}</Td>
<Td color={f.bucket ? BUCKET_COLORS[f.bucket] : tokens.textMuted}>{f.bucket ? BUCKET_LABEL[f.bucket] : '—'}</Td>
<Td color={FACTOR_COLORS[f.factor]} bold>{f.factor}</Td>
<Td right mono>{dur(f.durationSec)}</Td>
<Td right mono>{pct(f.durationSec / (tot.pptSec || 1))}%</Td>
<Td mono color={tokens.textMuted}>{f.eventIds.length} 个实例</Td>
</tr>
))}
</Table>
) : (
<EmptyBox>引擎本日未输出因子级明细(六桶排行仍照实出数;FAULT 等 A 类事件驱动的因子未成对,并非「无损失」)。</EmptyBox>
)}
{b.untimedSubFactors.length > 0 && (
<div style={{ marginTop: 9, display: 'flex', flexDirection: 'column', gap: 7 }}>
<div style={{ fontSize: 11.5, fontWeight: 700, color: tokens.warning }}>未单独计量的子因子(数据缺口,标灰不摊数)</div>
{b.untimedSubFactors.map((u) => (
<GapBox
key={`${u.factorL1}|${u.factorL2}`}
missing={`${u.factorL1} / ${u.factorL2}`}
dependsOn="EA 到场/维修开始时间戳(R-UNTIMED-SUBFACTOR)"
stage="W3 录入台补录 + 二期 EA 时间戳接入"
note={`段内出现但未单独计量:缺 EA 到场时间戳,无法把停机拆成「故障」与「等维修」。涉及 ${u.segmentIds.length} 段 / ${u.eventIds.length} 事件,不摊一个数充精度。`}
/>
))}
</div>
)}
</Card>
{/* ── 质量损失:Q 因子与 Rescreen 关联(三区域 Q 不同构,并列对照,绝不混算)── */}
<div style={grid3}>
{/* DEK 锚点 Q:日志贯通,良品/产出 */}
<Card
title="DEK 锚点 · Q"
icon={<ShieldCheck size={14} color={FACTOR_COLORS.Q} />}
right={<Chip color={tokens.success}>日志贯通</Chip>}
tone={FACTOR_COLORS.Q}
note={`Q=良品/产出(日志锚点贯通)。总不良(N−good)由日志得出;开机/过程的拆分依赖录入台 D 类补录——未补录前全部不良暂归过程不良,开机不良标「未补录」不标 0(缺证据≠零损失)。与 FT/ASLT 的 Q 定义不同构,不可跨区比较。${isFuji ? ' fuji-day-v1 Q=同日 DPVS 线体良率 Σ(inspected−ng)/Σinspected(Q2=B;DPVS 当日无板则 Q 仍缺口,显示「—」);六桶中 Q 两桶为 GAP 零,非零损失。' : ''}`}
>
<Tiles items={[
{ label: '实际 Q', value: pctUnitOrGap(day.tiers.actual.q), sub: `${scope.bizDate} · 良品/产出`, color: FACTOR_COLORS.Q, title: '实际档 Q=goodQty/outputQty,分母来自日志锚点' },
{ label: '开机不良补录', value: startupEntered ? `${qty(day.startupDefectQty)} 颗` : '未补录', sub: startupEntered ? 'D 类人工录入' : '录入台待录入', color: tokens.textMuted, title: '开机不良数量来源=录入台 D 类补录(startupDefectQty);0=尚未补录,非零损失,血缘须点名是谁填的口径' },
]} />
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>Q 桶</Th><Th right>时长</Th><Th right>占 PPT</Th><Th>来源</Th>
</>}>
{qBuckets.map((k) => {
const row = bucketOf(k);
const isStartup = k === 'STARTUP_DEFECT';
return (
<tr key={k}>
<Td color={BUCKET_COLORS[k]} bold>{BUCKET_LABEL[k]}</Td>
<Td right mono>{dur(row.durationSec)}</Td>
<Td right mono>{pct(row.pctOfPlanTime)}%</Td>
<Td color={tokens.textMuted}>{isStartup ? (startupEntered ? '推导+补录' : '未补录') : '节拍推导'}</Td>
</tr>
);
})}
</Table>
</div>
{!startupEntered && (
<Note>开机不良尚未补录:当前 {dur(bucketOf('PROCESS_DEFECT').durationSec)} 过程不良含未拆分的开机部分,待录入台 D 类事件补录后重新拆分(不摊一个数充精度)。</Note>
)}
</Card>
{/* FT Q=1−Rescreen×良率损失:复测关联链 */}
<Card
title="FT · Q=1−复测×良率损失"
icon={<Repeat size={14} color={FACTOR_COLORS.Q} />}
right={<Chip color={tokens.warning}>模拟</Chip>}
tone={FACTOR_COLORS.Q}
note="FT 无标准节拍,Q 用「复测率×良率损失」连乘扣减:复测越高、良率越低,Q 损失越大。操作数为演示合成种子(客户未给逐机值),不得冒充 POC 锚点 81.69%。"
>
<Tiles items={[
{ label: 'FT 线 Q(投入量加权)', value: pctUnitOrGap(ft.line.q), sub: `${ft.bizDate} · 模拟`, color: FACTOR_COLORS.Q, title: '线 Q=Σ(qᵢ×投入量ᵢ)/Σ投入量(synthesizeParallel),非简单平均' },
]} />
{ft.bizDate !== scope.bizDate && (
<Note><span style={{ color: tokens.warning }}>该业务日({scope.bizDate})无 FT 种子</span>:照实参考最近可用日 {ft.bizDate}(真实覆盖窗口不重叠),不与 DEK 当日混算。</Note>
)}
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>设备</Th><Th right>Rescreen</Th><Th right>良率损失</Th><Th right>Q</Th>
</>}>
{ft.devices.map((dev) => (
<tr key={dev.deviceId}>
<Td mono color={tokens.textSub}>{dev.deviceId}</Td>
<Td right mono>{pctUnitOrGap(ftQ(dev, 'rescreen').value)}</Td>
<Td right mono>{pctUnitOrGap(ftQ(dev, 'yieldLoss').value)}</Td>
<Td right mono bold color={FACTOR_COLORS.Q}>{pctUnitOrGap(ftQ(dev, 'q').value)}</Td>
</tr>
))}
</Table>
</div>
{ftRep && (
<div style={{ marginTop: 8, padding: '7px 9px', borderRadius: 8, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`, minWidth: 0 }}>
<div style={{ fontSize: 10.5, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>复测关联链({ftRep.deviceId} · 照录引擎算式)</div>
{(['rescreen', 'yieldLoss', 'q'] as const).map((key) => (
<div key={key} style={{ fontSize: 10.5, lineHeight: 1.7, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace', wordBreak: 'break-all' }}>
{ftQ(ftRep, key).label}:{ftQ(ftRep, key).formula}
</div>
))}
</div>
)}
</Card>
{/* ASLT Q=终测合格率:C03/C10 口径敏感 */}
<Card
title="ASLT · Q=终测合格率"
icon={<FlaskConical size={14} color={FACTOR_COLORS.Q} />}
right={<Chip color={tokens.warning}>模拟</Chip>}
tone={FACTOR_COLORS.Q}
note="Q=(FT合格+RC复测合格)/FT投入。C03 取终测合格率(P0,待 IE 签字;FPY/UTT 为备选);C10 工程批是否剔除影响 Q≈2.08pp(P1)。与 DEK/FT 的 Q 不同构,不可跨区混算。"
>
<Tiles items={[
{ label: 'ASLT Q(终测合格率)', value: pctUnitOrGap(aslt.result.q), sub: `${aslt.bizDate} · 模拟`, color: FACTOR_COLORS.Q, title: 'Q=(ftGood+rcGood)/ftInput,终测计数原样透出' },
]} />
{aslt.bizDate !== scope.bizDate && (
<Note><span style={{ color: tokens.warning }}>该业务日({scope.bizDate})无 ASLT 种子</span>:照实参考最近可用日 {aslt.bizDate}(真实覆盖窗口不重叠),不与 DEK 当日混算。</Note>
)}
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>终测计数</Th><Th right>数量</Th><Th>来源</Th>
</>}>
<tr><Td color={tokens.textSub}>FT 投入</Td><Td right mono>{qty(aslt.result.output.ftInput)}</Td><Td color={tokens.textMuted}>颗 · 合成</Td></tr>
<tr><Td color={tokens.textSub}>FT 合格</Td><Td right mono>{qty(aslt.result.output.ftGood)}</Td><Td color={tokens.textMuted}>颗 · 合成</Td></tr>
<tr><Td color={tokens.textSub}>RC 复测合格</Td><Td right mono>{qty(aslt.result.output.rcGood)}</Td><Td color={tokens.textMuted}>颗 · 合成</Td></tr>
</Table>
</div>
<div style={{ marginTop: 8, padding: '7px 9px', borderRadius: 8, background: tokens.panelBgAlt, border: `1px solid ${tokens.borderSub}`, minWidth: 0 }}>
<div style={{ fontSize: 10.5, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>照录引擎算式</div>
<div style={{ fontSize: 10.5, lineHeight: 1.7, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace', wordBreak: 'break-all' }}>
{asltQ.formula}
</div>
</div>
</Card>
</div>
{/* Q 定义口径敏感性:C03/C10 决定 Q 绝对值,三区域不可混算 */}
<Card
title="Q 定义口径敏感性 · 三区域不可混算"
icon={<Scale size={14} color={tokens.warning} />}
full
right={<Chip color={tokens.textMuted}>C03 / C10 · 待 IE 签字</Chip>}
tone={tokens.warning}
note="三区域 Q 定义不同构:DEK=良品/产出(日志贯通)、FT=1−复测×良率损失(连乘扣减)、ASLT=终测合格率(计数比)。分母与口径各异,严禁跨区混算或求平均;下表两项口径一旦定版变更,Q 绝对值随之改变,须走版本管理(断言⑩)。"
>
<Table head={<>
<Th>口径项</Th><Th>议题</Th><Th>默认值(待签字)</Th><Th>优先级</Th><Th>影响范围</Th>
</>}>
{(['C03', 'C10'] as const).map((id) => {
const it = CALIBER_ITEMS[id];
return (
<tr key={id}>
<Td mono bold color={tokens.textSub}>{id}</Td>
<Td color={tokens.textSub}>{it.name}</Td>
<Td color={tokens.text}>{String(it.defaultValue)}</Td>
<Td><Chip color={tokens.textMuted}>{it.priority}</Chip></Td>
<Td color={tokens.textMuted}>{it.note}</Td>
</tr>
);
})}
</Table>
<Note>
当前口径版本 {day.caliberVersion};C03/C10 属 Q 定义敏感性议题,原型默认未签字,P0 项标灰不标绿。
Q 定义快照=「{CALIBER_CONFIG.sensitivitySnapshot.qDefinition}」,与口径配置中心同源;定版变更须生成新版本并保留旧版本可回放(断言⑩)。
</Note>
</Card>
</div>
);
}
@@ -0,0 +1,300 @@
/**
* 主数据页(master 页签 · W2-C)。
*
* ★ 全局常量字典可视化(建议书 §5.2.2 主数据 P0 / 规划书附录 C·D·E):
* 17 台设备台账 · 48 事件字典 · 28 项口径配置 · 因子字典(六桶→三率 + 六-3 归口 + 一级/二级因子)
* + 3 线体 + 3 班次。全部读 data/oee 常量字典与其现算统计,视图不二次计算 OEE。
*
* 三条台账纪律(devices.ts 文件头)必须在 UI 上兑现:
* ① 沿用客户既有台账编码,12 台演示占位码标「待客户台账确认」,不假装知道。
* ② ICT 无实测写 0 + 缺口说明(待 IE / 不适用),绝不编一个数。
* ③ 间隙阈值按设备可配置:kohyoung 15min、Jetting 3min 均≠公式默认值,台账值优先(断言⑤)。
*
* 口径纪律(calibers28.ts):本次不安排口径工作坊 → signedOff 全 false,
* P0 标灰「待 IE 签字」,P1/P2「默认值生效中」;灰不等于错,是还没人签字。
*/
import { useEffect } from 'react';
import { Database, Factory, Layers, ListChecks, ShieldCheck, AlertTriangle, GitBranch } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
DEVICES, LINES, SHIFT_PATTERN, SHIFT_ASSUMPTION_NOTE, deviceStats,
POC_FLEET_WITH_LOG, POC_FLEET_NO_LOG_APPROX, type DeviceMaster,
} from '../../data/oee/devices';
import { EVENTS_48, eventStats, factorDictionary, MISSING_CODES } from '../../data/oee/events48';
import { CALIBER_ITEMS, caliberStats, SENSITIVITY_ISSUES } from '../../data/oee/calibers28';
import {
LOSS_BUCKETS, BUCKET_LABEL, BUCKET_FACTOR, GROSS_CATEGORIES, GROSS_TO_BUCKET, GROSS_CATEGORY_COUNT,
GRADE_LABEL, EVENT_STATUS_LABEL, TEMPLATE_LABEL, type EventGrade, type EventDefStatus, type CaliberItem,
} from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, GapBox,
grid2, pageStyle, BUCKET_COLORS, FACTOR_COLORS,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
const GRADE_ORDER: EventGrade[] = ['A', 'B', 'C', 'D', 'E'];
export default function OeeMasterData({ filter, focusDevice }: OeeViewProps & { focusDevice?: string | null }) {
const { tokens } = useTheme();
const ds = deviceStats();
const es = eventStats();
const cs = caliberStats();
const factors = factorDictionary();
const caliberRows = Object.values(CALIBER_ITEMS) as CaliberItem[];
/* D9:线体图点击携带台账 id(DEK001/DPVS001)→ 滚动定位+高亮。 */
useEffect(() => {
if (!focusDevice) return;
const el = document.querySelector(`[data-device-id="${focusDevice}"]`);
el?.scrollIntoView({ block: 'center', behavior: 'smooth' });
}, [focusDevice]);
const gradeColor = (g: EventGrade): string =>
g === 'A' ? tokens.success : g === 'B' ? tokens.info : g === 'C' ? tokens.warning : g === 'D' ? tokens.danger : tokens.textMuted;
const statusColor = (s: EventDefStatus): string =>
s === 'ACTIVE' ? tokens.success : s === 'PENDING_SRC' ? tokens.warning : tokens.textMuted;
const ictCell = (d: DeviceMaster) => {
if (d.ictSec > 0) {
return <span style={{ color: tokens.textSub }}>{d.ictSec}s/{d.unit}{d.ictSource === 'DERIVED' && <Chip color={tokens.info}>推导</Chip>}</span>;
}
return <Chip color={tokens.textMuted} title={d.ictNote}>{d.ictSource === 'PENDING_IE' ? '待 IE' : '不适用'}</Chip>;
};
const collectCell = (d: DeviceMaster) => {
if (d.hasLog) return <span style={{ color: tokens.textMuted }}>{d.logFormat}</span>;
const fb = d.fallbackChannel === 'IO_LIGHT' ? '需加装 IO' : d.fallbackChannel === 'UPSTREAM_INFER' ? '上下游反推' : '人工录入';
return <Chip color={tokens.warning} title={d.adapterTraps.join(';')}>{fb}</Chip>;
};
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="主数据" icon={<Database size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="设备/事件/口径/因子均为全局常量字典,不随业务日或筛选范围变化">全局台账字典</Chip>}
/>
<Note>
主数据是<strong>全局常量字典</strong>,不随业务日/筛选变化。沿用客户既有台账编码,{ds.demoCode} 台演示占位码标「待客户台账确认」;
ICT 无实测写 0 + 缺口说明(待 IE / 不适用),绝不编数;间隙阈值按设备可配置,台账值优先于公式(断言⑤)。
本次不安排口径工作坊,{cs.total} 项 signedOff 全 false,P0 标灰「待 IE 签字」。
</Note>
<Tiles items={[
{ label: '设备台账', value: String(ds.total), sub: `计 OEE ${ds.oeeCount} 台`, color: tokens.text, title: '17 台(SRF 13 类各 1 + FT 3 + ASLT 1);中间缓存不计 OEE' },
{ label: '事件字典', value: String(es.total), sub: `A${es.grade.A}/B${es.grade.B}/C${es.grade.C}/D${es.grade.D}/E${es.grade.E}`, color: tokens.textSub, title: '原表 60 行去重 12 行 = 48 唯一事件' },
{ label: '口径配置', value: String(cs.total), sub: `P0 ${cs.p0} 待签字`, color: tokens.textMuted, title: '附录 E 默认值生效,无人签字' },
{ label: '二级因子', value: String(factors.length), sub: `落六桶 ${es.bucketedEvents} 事件`, color: tokens.textSub, title: '一级/二级因子由 48 事件现推' },
{ label: '线体', value: String(LINES.length), sub: 'SRF/FT/ASLT', color: tokens.textSub },
{ label: '班次', value: String(SHIFT_PATTERN.length), sub: '3×8h 演示假设', color: tokens.textMuted, title: SHIFT_ASSUMPTION_NOTE },
]} />
{/* 设备台账:全局常量字典台账 */}
<Card
title={`设备台账(${ds.total} 台)`}
icon={<Factory size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="有日志 8 类现场 108 台 + 无日志三类约 10 台 ≈ 118 台(POC);台账按建议书 3.5 每类 1 台建">现场 ≈{POC_FLEET_WITH_LOG + POC_FLEET_NO_LOG_APPROX} 台</Chip>}
note="能力 ★1–3 为信号完整度;ICT 待 IE/不适用是口径事实非缺数;间隙阈值 kohyoung AOI001=15min(公式默认 18)、Jetting JET001=3min(公式默认 5),台账值优先于公式(断言⑤逐台比对)。中间缓存 BUF001 不计 OEE(只作缓冲解耦输入)。"
>
<Table maxHeight={330} head={<>
<Th>设备(编码 · 名称)</Th><Th>区域 · 工站</Th><Th>能力</Th><Th>ICT</Th><Th right>间隙</Th><Th>采集 / 编码来源</Th>
</>}>
{DEVICES.map((d) => (
<tr key={d.id} data-device-id={d.id} style={{ opacity: d.countsForOee ? 1 : 0.62 }}>
<Td bold>
<span title={d.demoRole} style={{ fontFamily: 'ui-monospace, monospace' }}>{d.id}</span>
<div style={{ fontSize: 10, color: tokens.textMuted, fontWeight: 400 }}>{d.name}</div>
</Td>
<Td color={tokens.textSub}>{d.region} · {d.station}</Td>
<Td color={tokens.warning}><span title={d.capabilityNote}>{'★'.repeat(d.capability)}</span></Td>
<Td>{ictCell(d)}</Td>
<Td right mono color={d.gapSource === 'POC' ? tokens.accent : tokens.textMuted}>
<span title={d.gapSource === 'POC' ? 'POC 单列阈值,优先于公式默认值' : '公式默认 max(5, 3×ICT/60)'}>{d.gapThresholdMin}min</span>
</Td>
<Td>
{collectCell(d)}
<div style={{ marginTop: 2 }}>
<Chip color={d.codeSource === 'DEMO' ? tokens.textMuted : tokens.success} title={d.codeSource === 'DEMO' ? '客户未提供编码,演示占位,接入前须替换' : `真实台账编码(${d.codeSource})`}>
{d.codeSource === 'DEMO' ? '占位码·待确认' : `真实码·${d.codeSource}`}
</Chip>
</div>
</Td>
</tr>
))}
</Table>
<div style={{ marginTop: 8 }}>
<GapBox
missing={`${ds.demoCode} 台演示占位码 + ${ds.ictPendingIe} 台 ICT 待 IE`}
dependsOn="客户台账编码确认 + IE 提供实测节拍"
stage="接入前(P1)"
note="占位码不是假装知道;回流焊/MBT/Xray/无日志三类节拍规划书未给,ictSec=0 是口径事实。FT/ASLT 不用 ICT(连乘扣减/事件驱动),标不适用。"
/>
</div>
</Card>
{/* 48 事件字典 + 28 口径配置 */}
<div style={grid2}>
<Card
title={`48 事件字典`}
icon={<ListChecks size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="缺失编号恰为 12 个:S-03~07/17/21~22/35~38,60−12=48">缺号 {MISSING_CODES.length}</Chip>}
note="等级按逐事件统计着色(A14/B7/C12/D14/E1),不按方案附录 A 分布表(其区域数字与逐条等级对不上,规划书 H.11)。bucket 由 GROSS_TO_BUCKET 现推,计划类 20 条 bucket=null 不进六桶。"
>
<div style={{ marginBottom: 8 }}>
<Tiles items={GRADE_ORDER.map((g) => ({
label: `${g} 类`, value: String(es.grade[g] ?? 0), sub: GRADE_LABEL[g].slice(0, 4), color: gradeColor(g), title: GRADE_LABEL[g],
}))} />
</div>
<Table maxHeight={300} head={<>
<Th>码</Th><Th>名称</Th><Th>区域</Th><Th>等级</Th><Th>形式</Th><Th>归口桶</Th><Th>状态</Th>
</>}>
{EVENTS_48.map((e) => (
<tr key={e.code}>
<Td bold mono>{e.code}</Td>
<Td color={tokens.textSub}><span title={`判定时点:${e.triggerPoint}|来源:${e.source}|获取:${e.acquisition}`}>{e.name}</span></Td>
<Td color={tokens.textMuted}>{e.region}</Td>
<Td><Chip color={gradeColor(e.grade)} title={GRADE_LABEL[e.grade]}>{e.grade}</Chip></Td>
<Td color={tokens.textMuted}>{e.form}</Td>
<Td>{e.bucket ? <Chip color={BUCKET_COLORS[e.bucket]}>{BUCKET_LABEL[e.bucket]}</Chip> : <Chip color={tokens.textMuted} title="计划类时间,进 PDT 或按 C06/C10 处理,不进六桶">计划类</Chip>}</Td>
<Td><Chip color={statusColor(e.status)}>{EVENT_STATUS_LABEL[e.status]}</Chip></Td>
</tr>
))}
</Table>
</Card>
<Card
title={`28 项口径配置`}
icon={<ShieldCheck size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="本次不安排口径工作坊,默认值生效但无人签字">待 IE 签字 {cs.total - cs.signed}</Chip>}
note="两个「优先级」不可混:priority P0/P1/P2 影响「能不能算」(P0 16/P1 11/P2 1);isSensitivityKey 影响「算出来是多少」(4 项敏感性议题)。C04/C10 标 P1 却影响 A≈3.6pp/Q≈2.08pp;C15 标 P0 却不改 OEE 数值。"
>
<div style={{ marginBottom: 8 }}>
<Tiles items={[
{ label: 'P0 待确认', value: String(cs.p0), sub: '能不能算', color: tokens.textMuted },
{ label: 'P1 生效中', value: String(cs.p1), sub: '默认值', color: tokens.textSub },
{ label: 'P2 生效中', value: String(cs.p2), sub: '默认值', color: tokens.textSub },
{ label: '敏感性议题', value: String(cs.sensitivityKeys), sub: '算出多少', color: tokens.warning },
]} />
</div>
<Table maxHeight={300} head={<>
<Th>编号</Th><Th>口径项</Th><Th>默认值</Th><Th>优先级</Th><Th>归口</Th><Th>签字</Th>
</>}>
{caliberRows.map((c) => (
<tr key={c.id}>
<Td bold mono>{c.id}{c.isSensitivityKey && <span style={{ color: tokens.warning }} title="4 项敏感性议题之一"> ★</span>}</Td>
<Td color={tokens.textSub}><span title={c.note}>{c.name}</span></Td>
<Td color={tokens.textMuted}><span style={{ fontSize: 10.5 }}>{String(c.defaultValue)}</span></Td>
<Td><Chip color={c.priority === 'P0' ? tokens.textMuted : tokens.textSub} title={c.priority === 'P0' ? 'P0 标灰:待确认,不标绿' : '默认值生效中'}>{c.priority}</Chip></Td>
<Td color={tokens.textMuted}>{c.owner}</Td>
<Td><Chip color={tokens.textMuted}>待签字</Chip></Td>
</tr>
))}
</Table>
</Card>
</div>
{/* 线体班次 + 六桶/六-3 映射 */}
<div style={grid2}>
<Card
title="线体与班次"
icon={<GitBranch size={14} color={tokens.accent} />}
note={SHIFT_ASSUMPTION_NOTE + '。C24:跨天班次归属到事件开始时刻所在业务日;本 pattern 每班起始于当天,故业务日=日历日,CT 窗口 00:00→24:00。'}
>
<Table head={<>
<Th>线体</Th><Th>区域</Th><Th>模板</Th><Th right>设备</Th><Th>瓶颈</Th>
</>}>
{LINES.map((l) => (
<tr key={l.id}>
<Td bold mono>{l.id}</Td>
<Td color={tokens.textSub}>{l.region}</Td>
<Td color={tokens.textMuted}>{TEMPLATE_LABEL[l.template]}</Td>
<Td right mono>{l.deviceIds.length}</Td>
<Td color={tokens.textMuted}>{l.bottleneckDeviceId ?? '—'}</Td>
</tr>
))}
</Table>
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>班次</Th><Th>名称</Th><Th right>起</Th><Th right>止</Th><Th>跨天</Th>
</>}>
{SHIFT_PATTERN.map((s) => (
<tr key={s.id}>
<Td bold mono>{s.id}</Td>
<Td color={tokens.textSub}>{s.name}</Td>
<Td right mono>{String(s.startHour).padStart(2, '0')}:00</Td>
<Td right mono>{String(s.endHour).padStart(2, '0')}:00</Td>
<Td color={tokens.textMuted}>{s.crossesMidnight ? '是' : '否'}</Td>
</tr>
))}
</Table>
</div>
<Note>SRF 台账按建议书 3.5「13 类各 1 台」建;规划书 4.6.1 的 FUJI×2/Datacon×2 在原型以单台+2 Lane(FUJI)与 POC 改善标的 DCP005(Datacon)代表,差异已在此披露。</Note>
</Card>
<Card
title="六大损失桶 → 三率归属"
icon={<Layers size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="残差 = PPT − good×ICT − Σ六桶 = IDLE(未归因);干净日残差=0,脏日>0 触发 DQ-06 阻断">六-1 · 互斥完备</Chip>}
note="每事件码唯一归口一个桶。计划类时间(计划停机/计划待料/工程借用)bucket=null,进 PDT 从分母扣除或按 C06/C10 处理,不进六桶。残差恒等于未归因 IDLE,绝不为凑零而偷偷归一化(G2 门)。"
>
<Table head={<>
<Th>损失桶</Th><Th>三率</Th><Th>六-3 归口用词</Th><Th right>事件数</Th>
</>}>
{LOSS_BUCKETS.map((b) => {
const gross = GROSS_CATEGORIES.filter((g) => GROSS_TO_BUCKET[g] === b);
const cnt = gross.reduce((a, g) => a + GROSS_CATEGORY_COUNT[g], 0);
return (
<tr key={b}>
<Td bold color={BUCKET_COLORS[b]}>{BUCKET_LABEL[b]}</Td>
<Td><Chip color={FACTOR_COLORS[BUCKET_FACTOR[b]]}>{BUCKET_FACTOR[b]}</Chip></Td>
<Td color={tokens.textMuted}>{gross.join('、')}</Td>
<Td right mono>{cnt}</Td>
</tr>
);
})}
</Table>
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>六-3 归口(计划类)</Th><Th>去向</Th><Th right>事件数</Th>
</>}>
{GROSS_CATEGORIES.filter((g) => GROSS_TO_BUCKET[g] === null).map((g) => (
<tr key={g}>
<Td color={tokens.textSub}>{g}</Td>
<Td color={tokens.textMuted}>{g === '工程借用' ? 'ENG·按 C06/C10' : '进 PDT 扣分母'}</Td>
<Td right mono>{GROSS_CATEGORY_COUNT[g]}</Td>
</tr>
))}
<tr>
<Td bold color={tokens.accent}>计划类合计</Td>
<Td color={tokens.textMuted}>不进六桶</Td>
<Td right mono bold color={tokens.accent}>{es.nullBucketEvents}</Td>
</tr>
</Table>
</div>
</Card>
</div>
{/* 因子字典:一级/二级因子 */}
<Card
title={`因子字典(一级 / 二级因子 → 桶 → 三率)`}
icon={<AlertTriangle size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="由 48 事件字典现推,不另写一份;factor_def 域">二级因子 {factors.length} 项</Chip>}
note={'一级/二级因子由 48 事件现推(factorDictionary),桶由 GROSS_TO_BUCKET、三率由 BUCKET_FACTOR 现推,保证「六-3 归口」「六-1 六桶」「A/P/Q 三率」三套分类永不打架。计划类因子 bucket=null,不进六桶。敏感性议题承载:'
+ Object.values(SENSITIVITY_ISSUES).map((s) => `${s.label}(${s.items.join('/')})`).join('、') + '。'}
>
<Table maxHeight={300} head={<>
<Th>一级因子</Th><Th>二级因子</Th><Th>六-3 归口</Th><Th>损失桶</Th><Th>三率</Th><Th>承载事件码</Th><Th right>条数</Th>
</>}>
{factors.map((f) => (
<tr key={`${f.factorL1}-${f.factorL2}`}>
<Td bold color={tokens.textSub}>{f.factorL1}</Td>
<Td color={tokens.textSub}>{f.factorL2}</Td>
<Td color={tokens.textMuted}>{f.grossCategory}</Td>
<Td>{f.bucket ? <Chip color={BUCKET_COLORS[f.bucket]}>{BUCKET_LABEL[f.bucket]}</Chip> : <Chip color={tokens.textMuted}>计划类</Chip>}</Td>
<Td>{f.factor ? <Chip color={FACTOR_COLORS[f.factor]}>{f.factor}</Chip> : <span style={{ color: tokens.textMuted }}>—</span>}</Td>
<Td mono color={tokens.textMuted}><span style={{ fontSize: 10 }}>{f.codes.join(' ')}</span></Td>
<Td right mono>{f.count}</Td>
</tr>
))}
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,261 @@
/**
* 总览看板(cockpit 页签 · W2-B)。
*
* ★ 首页排行是「计划与等待排行」而非「故障排行」:三站 POC 一致指向组织与管理
* (排产/物料/清盘),不是设备维修。FT tray 类占损失时长 69.3% / SRF 计划+待机 49.1% /
* ASLT Wait+Plan 37.54%。三站分母不同,不可直接比大小(PLAN_WAIT_RANK_NOTE 披露)。
*
* 三条纪律:
* ① 不复制顶栏五类结果指标条(计划达成率/欠产/OEE/良率/单位工时产出已在 MecHeader)。
* 本页聚焦:计划与等待排行(POC) + 三层 OEE/顺序替代(锚点) + 三区域合成读数(模拟)。
* ② 数字只从 L3 取:resolveScope / regionRollup / day.tiers / day.buckets,视图不二次计算。
* ③ POC 只作参考基线,合成标「模拟·模板仿真」,两者绝不混算;
* 计划档目标 C27/C28 待 IE 签字,标灰不标绿。
*/
import { LayoutDashboard, BarChart3, Layers, ArrowRightLeft, Factory } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope, type OeeFilter } from '../../lib/oeeFilters';
import { regionRollup, METHOD_LABEL, PARAMS_SIGNOFF_NOTE } from '../../lib/oeeService';
import { POC_ANCHORS, PLAN_WAIT_RANK_NOTE } from '../../data/oee/disclosure';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, EmptyBox,
grid2, pageStyle, pctUnitOrGap, dur, FACTOR_COLORS,
} from './oeeUi';
import { HBarChart } from './charts';
export interface OeeViewProps {
filter: OeeFilter;
period: number;
onNavigate?: (tab: string) => void;
}
export default function OeeOverview({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const day = scope.day; // 锚点单机当日结果;非锚点/聚合范围为 null
const rollup = regionRollup(scope.bizDate); // 三区域合成(模拟·模板仿真),按业务日对齐
const isFuji = !!day && day.caliberVersion === 'fuji-day-v1';
/* 三层 OEE:理论/计划/实际共用分母 PPT。计划档目标待 IE 签字,标灰。 */
const tierRows = day ? ([
{ key: 'theoretical', label: '理论 OEE', t: day.tiers.theoretical, note: '设备能力上限(A 由日不可避免停机决定,P=100%,Q=设计良率)' },
{ key: 'planned', label: '计划 OEE', t: day.tiers.planned, note: '管理水平标杆(C27/C28 附录 E 默认值,待 IE 签字)' },
{ key: 'actual', label: '实际 OEE', t: day.tiers.actual, note: '实际运营效果(A=RT/PPT,P=N×ICT/RT,Q=良品/N)' },
] as const) : [];
const delta = day?.tiers.deltaPlannedToActual;
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="总览看板" icon={<LayoutDashboard size={15} color={tokens.accent} />} />
{/* 三层 OEE 概览砖:与顶栏五指标互补(这里是理论/计划/实际三档 + 残差),不重复 */}
{day ? (
<Tiles hoverLift items={[
{ label: '理论 OEE', value: pctUnitOrGap(day.tiers.theoretical.oee), sub: '能力上限', color: tokens.textSub, title: '理论档:A 由日不可避免停机决定,P=100%,Q=设计良率', ring: true, roll: { raw: Number.isFinite(day.tiers.theoretical.oee) ? day.tiers.theoretical.oee * 100 : null, suffix: '%' } },
{ label: '计划 OEE', value: pctUnitOrGap(day.tiers.planned.oee), sub: '待 IE 签字', color: tokens.textMuted, title: PARAMS_SIGNOFF_NOTE, ring: true, roll: { raw: Number.isFinite(day.tiers.planned.oee) ? day.tiers.planned.oee * 100 : null, suffix: '%' } },
{ label: '实际 OEE', value: pctUnitOrGap(day.tiers.actual.oee), sub: `${scope.bizDate} · 锚点单机`, color: tokens.accent, title: '实际档:A×P×Q,分母 PPT=CT−PDT−UNKNOWN', ring: true, roll: { raw: Number.isFinite(day.tiers.actual.oee) ? day.tiers.actual.oee * 100 : null, suffix: '%' } },
{ label: '计划→实际 Δ', value: delta && Number.isFinite(delta.total) ? `${(delta.total * 100).toFixed(2)}pp` : '—', sub: delta ? (Number.isFinite(delta.total) ? (delta.identityHolds ? '顺序替代恒等成立' : '恒等不成立') : '因子缺口 · 恒等不可评') : '—', color: tokens.textSub, title: 'ΔA+ΔP+ΔQ ≡ OEE实际−OEE计划(顺序固定 A→P→Q)', roll: { raw: delta && Number.isFinite(delta.total) ? delta.total * 100 : null, suffix: 'pp' } },
{ label: '六桶残差', value: dur(day.buckets.residualSec), sub: day.buckets.zeroResidual ? '残差 0' : isFuji ? '量纲差(模块秒 vs 颗×ICT)' : '未归因+G缺口', color: day.buckets.zeroResidual ? tokens.textSub : tokens.warning, title: day.buckets.residualNote },
]} />
) : (
<EmptyBox>
当前筛选范围({scope.scopeLabel})无日志贯通结果,三层 OEE 不显示数字、也不显示 0。<br />
{scope.gap ?? scope.coverageNote}
</EmptyBox>
)}
{/* 第一行:计划与等待排行(POC) + 三站基线与改善目标(POC) */}
<div style={grid2}>
<Card
title="计划与等待排行"
icon={<BarChart3 size={14} color={tokens.warning} />}
tone={tokens.warning}
note={PLAN_WAIT_RANK_NOTE}
>
<HBarChart
items={POC_ANCHORS.map((a) => ({
label: a.region,
value: a.planWaitShare,
display: `${a.planWaitShare}%`,
sub: a.planWaitLabel,
color: tokens.warning,
}))}
valueSuffix="%"
/>
{/* 同分母对照:每站内部「计划与等待」远大于「设备/真停机」——首页不是故障排行的依据 */}
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>区域</Th><Th right>计划与等待</Th><Th right>设备/真停机</Th><Th>分母</Th>
</>}>
{POC_ANCHORS.map((a) => (
<tr key={a.region}>
<Td bold>{a.region}</Td>
<Td right mono color={tokens.warning} bold>{a.planWaitShare}%</Td>
<Td right mono color={tokens.textSub}>{a.trueStopShare}%</Td>
<Td color={tokens.textMuted}>{a.denom}</Td>
</tr>
))}
</Table>
</div>
</Card>
<Card
title="三站 POC 基线与改善目标"
icon={<Factory size={14} color={tokens.info} />}
tone={tokens.info}
note="改善抓手按 POC 真因排序:组织与管理优先,设备维修排最后。"
>
<Table head={<>
<Th>区域</Th><Th right>基线 OEE</Th><Th>A / P / Q</Th><Th right>目标</Th><Th>改善抓手</Th>
</>}>
{POC_ANCHORS.map((a) => (
<tr key={a.region}>
<Td bold>{a.region}</Td>
<Td right mono bold>{a.oee}</Td>
<Td mono color={tokens.textMuted}>
{a.apq.split(' / ').map((s) => <div key={s} style={{ whiteSpace: 'nowrap' }}>{s}</div>)}
</Td>
<Td right mono color={tokens.info}>{a.target}</Td>
<Td color={tokens.textSub}>{a.lever}</Td>
</tr>
))}
</Table>
<Note>基线明细:{POC_ANCHORS.map((a) => `${a.region} ${a.baselineNote}`).join(';')}</Note>
</Card>
</div>
{/* 第二行:三层 OEE 与顺序替代(锚点) + 三区域合成读数(模拟) */}
<div style={grid2}>
<Card
title="三层 OEE 与顺序替代"
icon={<Layers size={14} color={tokens.accent} />}
right={day ? <Chip color={tokens.textMuted}>锚点单机 · 模拟</Chip> : undefined}
note={day ? `${PARAMS_SIGNOFF_NOTE}。顺序替代固定 A→P→Q,三项差异之和恒等于总差异。` : undefined}
>
{day ? (
<>
<Table head={<>
<Th>口径档</Th><Th right>A</Th><Th right>P</Th><Th right>Q</Th><Th right>OEE</Th>
</>}>
{tierRows.map((r) => (
<tr key={r.key}>
<Td bold color={r.key === 'planned' ? tokens.textMuted : tokens.textSub}>{r.label}</Td>
<Td right mono>{pctUnitOrGap(r.t.a)}</Td>
<Td right mono>{pctUnitOrGap(r.t.p)}</Td>
<Td right mono>{pctUnitOrGap(r.t.q)}</Td>
<Td right mono bold color={r.key === 'planned' ? tokens.textMuted : tokens.text}>{pctUnitOrGap(r.t.oee)}</Td>
</tr>
))}
</Table>
{delta && (
<div style={{ marginTop: 8 }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 5 }}>
<ArrowRightLeft size={12} color={tokens.textSub} />
<span style={{ fontSize: 11.5, fontWeight: 700, color: tokens.textSub }}>计划 → 实际 差异分解(pp)</span>
<span style={{ flex: 1 }} />
<Chip color={delta.identityHolds ? tokens.textSub : Number.isFinite(delta.total) ? tokens.danger : tokens.textMuted}>
{delta.identityHolds ? '恒等成立' : Number.isFinite(delta.total) ? '恒等不成立' : '恒等不可评(G 缺口)'}
</Chip>
</div>
<Tiles hoverLift items={[
{ label: 'ΔA 时间稼动', value: Number.isFinite(delta.dA) ? `${(delta.dA * 100).toFixed(2)}` : '—', color: FACTOR_COLORS.A, title: '(A实际−A计划)×P计划×Q计划', roll: { raw: Number.isFinite(delta.dA) ? delta.dA * 100 : null } },
{ label: 'ΔP 性能稼动', value: Number.isFinite(delta.dP) ? `${(delta.dP * 100).toFixed(2)}` : '—', color: FACTOR_COLORS.P, title: 'A实际×(P实际−P计划)×Q计划', roll: { raw: Number.isFinite(delta.dP) ? delta.dP * 100 : null } },
{ label: 'ΔQ 良品率', value: Number.isFinite(delta.dQ) ? `${(delta.dQ * 100).toFixed(2)}` : '—', color: FACTOR_COLORS.Q, title: 'A实际×P实际×(Q实际−Q计划)', roll: { raw: Number.isFinite(delta.dQ) ? delta.dQ * 100 : null } },
{ label: '合计 Δ', value: Number.isFinite(delta.total) ? `${(delta.total * 100).toFixed(2)}` : '—', color: tokens.text, title: 'ΔA+ΔP+ΔQ ≡ OEE实际−OEE计划', roll: { raw: Number.isFinite(delta.total) ? delta.total * 100 : null } },
]} />
</div>
)}
<Note>{tierRows.map((r) => `${r.label}:${r.note}`).join(' ')}</Note>
</>
) : (
<EmptyBox>
三层 OEE 仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入。<br />
请切换到锚点设备,或到「工序·工位对比」页查看三区域模板仿真合成读数(模拟,非实测)。
</EmptyBox>
)}
</Card>
<Card
title="三区域合成读数"
icon={<Factory size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted} title="模板仿真合成,非日志贯通、非实测;SRF 仅 DEK+DCP 两台代表站、FT 仅 93k178 有客户操作数、ASLT 无客户算法表">模拟 · 模板仿真</Chip>}
note="线体合成已于 W2-A 落地(断言④):串行 A/Q 连乘、P 取瓶颈;并行按投入量加权;区域按线别投入量加权。合成非实测,不复现 POC 锚点,不与上方 POC 基线混算。"
>
<Table head={<>
<Th>范围</Th><Th right>A</Th><Th right>P</Th><Th right>Q</Th><Th right>OEE</Th><Th>合成法</Th>
</>}>
{rollup.lines.map((l, i) => (
<tr key={l.scopeLabel}>
<Td bold nowrap>{['SRF-L1', 'FT-L1', 'ASLT-L1'][i]}</Td>
{l.ok ? (
<>
<Td right mono>{pctUnitOrGap(l.a)}</Td>
<Td right mono>{pctUnitOrGap(l.p)}</Td>
<Td right mono>{pctUnitOrGap(l.q)}</Td>
<Td right mono bold>{pctUnitOrGap(l.oee)}</Td>
<Td color={tokens.textMuted}>{METHOD_LABEL[l.method]}</Td>
</>
) : (
<>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td color={tokens.warning}>该日无种子 · 不显示 0({l.problems.join(';')})</Td>
</>
)}
</tr>
))}
<tr>
<Td bold nowrap color={tokens.accent}>三区域加权</Td>
{rollup.region.ok ? (
<>
<Td right mono>{pctUnitOrGap(rollup.region.a)}</Td>
<Td right mono>{pctUnitOrGap(rollup.region.p)}</Td>
<Td right mono>{pctUnitOrGap(rollup.region.q)}</Td>
<Td right mono bold color={tokens.accent}>{pctUnitOrGap(rollup.region.oee)}</Td>
<Td color={tokens.textMuted}>{METHOD_LABEL[rollup.region.method]}</Td>
</>
) : (
<>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td color={tokens.warning}>{rollup.region.problems.join(';')}</Td>
</>
)}
</tr>
</Table>
{/* 反例对照:为什么不能那么算(三种错误方法的结果,与正确加权并列)。缺区时反例数字无意义,不提供 */}
{rollup.lines.every((l) => l.ok) ? (
<div style={{ marginTop: 8 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>反例对照(错误算法,仅供说明)</div>
<Table head={<>
<Th>错误方法</Th><Th right>OEE</Th><Th>为什么错</Th>
</>}>
<tr>
<Td color={tokens.textMuted}>线别算术平均</Td>
<Td right mono color={tokens.danger}>{pctUnitOrGap(rollup.wrongMethods.arithmeticMeanOfLines)}</Td>
<Td color={tokens.textMuted}>忽略各线投入量差异</Td>
</tr>
<tr>
<Td color={tokens.textMuted}>线别 OEE 加权</Td>
<Td right mono color={tokens.danger}>{pctUnitOrGap(rollup.wrongMethods.weightedMeanOfLineOee)}</Td>
<Td color={tokens.textMuted}>OEE 是乘法合成,不能直接加权</Td>
</tr>
<tr>
<Td color={tokens.textMuted}>日 OEE 求平均</Td>
<Td right mono color={tokens.danger}>{pctUnitOrGap(rollup.wrongMethods.meanOfDailyOee)}</Td>
<Td color={tokens.textMuted}>应累加原始量再重算,非日均</Td>
</tr>
</Table>
</div>
) : (
<Note>当前业务日有区域无种子(真实覆盖窗口不重叠):缺区行标 — 不标 0,跨区加权与反例对照不提供;各区域最近可用日读数见「工序·工位对比」页。</Note>
)}
</Card>
</div>
</div>
);
}
@@ -0,0 +1,307 @@
/**
* 优先处理清单(W3-A · 改善运营入口)。
*
* ★ 两套权重并列可切换、默认 B(建议书第9章第6项 line 2639):
* A(SOW 直译)损失程度.30/影响范围.20/持续时间.15/产能损失.20/交付影响.15
* B(鼎捷) 影响金额.30/发生频次.20/趋势恶化.20/可改善性.20/证据完备度.10
* 换一套权重 → 排序变化,这正是评审现场要对比的东西(compareSchemes)。
*
* ★ 可解释(断言⑧):score = Σ weight×factor,逐条 contrib 原样不缩放,
* 视图把 breakdown 摊开让评审用权重×分项逐条加回,绝不显示一个"算好的黑箱分"。
*
* 纪律:
* ① 数字只从 L3 取:rankPriority / scorePriority / compareSchemes / taskFromCandidate,
* 视图不二次计算评分、不另写一份权重字典。
* ② 候选真因来自三站 POC 一致指向(组织与管理,而非设备维修),标「POC 候选·跨三区域」,
* 不是当日单机现算,故本页不按 scope.day 门禁(与损失/质量页不同)。
* ③ 生成任务只到「待审核」,四项必填留空 → 派发闸(录入台)会拒派,演示"补齐后才能派发"。
* ④ 候选取自 demo 真因种子(PRIORITY_CANDIDATES),排序/打分引擎现算;
* 生成任务链停用(taskFromCandidate 只认 demo 真因种子,G 缺口不臆造)。demo 零改动。
*/
import { useState, type CSSProperties } from 'react';
import { ListOrdered, Scale, GitCompare, FilePlus2, Crosshair } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import {
PRIORITY_CANDIDATES, rankPriority, scorePriority, compareSchemes,
WEIGHT_SCHEMES, DEFAULT_WEIGHT_SCHEME, taskFromCandidate, ENTRY_OPERATOR,
type WeightSchemeId,
} from '../../lib/oeeService';
import type { ImprovementTask } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, grid2, pageStyle,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
export interface OeePriorityProps extends OeeViewProps {
/** 改善任务(与录入台共享,由 MetricWorkspace lifted state 提供)。 */
tasks: ImprovementTask[];
/** 由候选生成一条待审核任务后回写共享 state。 */
onAddTask: (t: ImprovementTask) => void;
}
/** 五实体之一(首要真因不允许并列多个)。 */
const ROOT_TYPES: ImprovementTask['rootCauseEntity']['type'][] = ['设备', '模具工装', '物料批次', '人员班组', '程序参数'];
const CAUSE_CLASSES: ImprovementTask['causeClass'][] = ['A', 'B', 'C'];
const CAUSE_CLASS_NOTE: Record<ImprovementTask['causeClass'], string> = {
A: 'A 类=唯一映射·设备型(如 Tester I/F,可直接定位)',
B: 'B 类=多变量·组织管理型(如 tray 清盘,需 D 类补录补证)',
C: 'C 类=程序/计划型(如 APS 计划版本,跨系统签收)',
};
export default function OeePriority({ filter, tasks, onAddTask }: OeePriorityProps) {
const { tokens } = useTheme();
const candidates = PRIORITY_CANDIDATES;
const [scheme, setScheme] = useState<WeightSchemeId>(DEFAULT_WEIGHT_SCHEME);
const [selectedId, setSelectedId] = useState<string>(candidates[0].id);
const [formTitle, setFormTitle] = useState<string>(candidates[0].title);
const [rootType, setRootType] = useState<ImprovementTask['rootCauseEntity']['type']>('人员班组');
const [rootId, setRootId] = useState<string>('');
const [causeClass, setCauseClass] = useState<ImprovementTask['causeClass']>('B');
const [lastCreated, setLastCreated] = useState<string | null>(null);
/* 数字一律 L3 现算:排序 / 选中项打分 / 两套对比。视图不重算评分。 */
const ranked = rankPriority(candidates, scheme);
const selected = candidates.find((c) => c.id === selectedId) ?? ranked[0].item;
const score = scorePriority(selected, scheme);
const cmp = compareSchemes(candidates);
const ws = WEIGHT_SCHEMES[scheme];
const rankAOf = (id: string) => cmp.rankA.find((r) => r.item.id === id)?.rank ?? 0;
const rankBOf = (id: string) => cmp.rankB.find((r) => r.item.id === id)?.rank ?? 0;
const selectCandidate = (id: string) => {
const c = candidates.find((x) => x.id === id);
if (!c) return;
setSelectedId(id);
setFormTitle(c.title);
setLastCreated(null);
};
/* 生成任务:候选来自 demo 真因种子,任务只到「待审核」,四项必填留空由录入台补齐。 */
const canSubmit = formTitle.trim().length > 0 && rootId.trim().length > 0;
const submit = () => {
if (!canSubmit) return;
const id = `T-${selected.id}-${tasks.length + 1}`;
const task = taskFromCandidate({
id,
candidateId: selected.id,
title: formTitle.trim(),
rootCauseEntity: { type: rootType, id: rootId.trim() },
causeClass,
evidenceChain: [selected.note ?? selected.title],
at: new Date().toISOString(),
by: ENTRY_OPERATOR,
scheme,
});
onAddTask(task);
setLastCreated(id);
setRootId('');
};
/* 输入控件统一样式(oeeUi 无 Input 原语,本页自带,走主题令牌)。 */
const inputStyle: CSSProperties = {
width: '100%', minWidth: 0, boxSizing: 'border-box',
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, borderRadius: 7,
padding: '5px 8px', fontSize: 11.5, color: tokens.text, outline: 'none',
};
const labelStyle: CSSProperties = { fontSize: 10.5, fontWeight: 600, color: tokens.textSub, marginBottom: 3, display: 'block' };
const toggleBtn = (id: WeightSchemeId): CSSProperties => ({
fontSize: 11, fontWeight: 700, padding: '3px 11px', borderRadius: 8, cursor: 'pointer',
border: `1px solid ${scheme === id ? tokens.accent : tokens.border}`,
background: scheme === id ? tokens.accentBg : 'transparent',
color: scheme === id ? tokens.accent : tokens.textSub,
});
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="优先处理清单"
icon={<ListOrdered size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="候选真因来自三站 POC 一致指向,非当日单机现算">POC 候选·跨三区域·分数现算</Chip>}
/>
<Tiles items={[
{ label: '候选项', value: `${candidates.length}`, sub: '覆盖三区域 + 锚点缺口', color: tokens.textSub },
{ label: '当前权重方案', value: scheme, sub: ws.label, color: tokens.accent, title: ws.source },
{ label: '默认方案', value: DEFAULT_WEIGHT_SCHEME, sub: '更贴合组织与管理故事线', color: tokens.textSub },
{ label: '权重之和', value: score.weightSum.toFixed(2), sub: '合法应 = 1.00', color: tokens.textSub },
{ label: '换权重排序', value: cmp.orderChanged ? '变化' : '未变', sub: 'A↔B 名次对比', color: cmp.orderChanged ? tokens.warning : tokens.textSub, title: '评审现场对比:同一批候选换一套权重,排序是否改变' },
]} />
<Note>候选真因来自三站 POC 一致指向(组织与管理,而非设备维修),标「POC 候选·跨三区域」,不是当日单机现算,故本页不按 scope.day 门禁。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。</Note>
{/* 第一行:优先排序(可切换权重)+ 选中项可解释打分 */}
<div style={grid2}>
<Card
title="优先排序"
icon={<ListOrdered size={14} color={tokens.accent} />}
right={
<span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<Scale size={13} color={tokens.textMuted} />
{(['A', 'B'] as WeightSchemeId[]).map((id) => (
<button key={id} style={toggleBtn(id)} onClick={() => setScheme(id)} title={WEIGHT_SCHEMES[id].source}>
{id}
</button>
))}
</span>
}
note={`当前 ${ws.label}(${ws.source})。点击行选中,右侧摊开权重×分项逐条贡献。同分按候选 id 升序(确定性 tie-break,不用随机)。`}
>
<Table head={<>
<Th right>名次</Th><Th>候选项</Th><Th>区域</Th><Th right>分数</Th>
</>}>
{ranked.map((r) => {
const on = r.item.id === selected.id;
return (
<tr
key={r.item.id}
onClick={() => selectCandidate(r.item.id)}
style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}
>
<Td right mono bold color={on ? tokens.accent : tokens.textSub}>{r.rank}</Td>
<Td color={tokens.text}>
<span style={{ fontWeight: on ? 700 : 600 }}>{r.item.id}</span>
<span style={{ color: tokens.textSub, fontWeight: 400 }}> {r.item.title}</span>
</Td>
<Td><Chip color={tokens.info}>{r.item.region ?? '—'}</Chip></Td>
<Td right mono bold color={on ? tokens.accent : tokens.textSub}>{r.score.score.toFixed(4)}</Td>
</tr>
);
})}
</Table>
</Card>
<Card
title={`可解释打分 · ${selected.id}`}
icon={<Crosshair size={14} color={tokens.info} />}
right={<Chip color={tokens.accent} title="score = Σ 权重×分项,逐条可加回">总分 {score.score.toFixed(4)}</Chip>}
note="断言⑧:contrib = weight × factor 原样返回,不做隐藏归一化/截断/缩放。评审可用下表逐条加回总分;权重之和透明展示。"
>
<div style={{ fontSize: 11.5, color: tokens.textSub, lineHeight: 1.55, marginBottom: 7, minWidth: 0 }}>
<span style={{ fontWeight: 700, color: tokens.text }}>{selected.title}</span>
{selected.note && <div style={{ fontSize: 10.5, color: tokens.textMuted, marginTop: 2 }}>{selected.note}</div>}
</div>
<Table head={<>
<Th>分项</Th><Th right>权重</Th><Th right>打分</Th><Th right>贡献</Th>
</>}>
{score.breakdown.map((b) => (
<tr key={b.key}>
<Td color={tokens.textSub}>{b.label}</Td>
<Td right mono>{b.weight.toFixed(2)}</Td>
<Td right mono>{b.factor.toFixed(2)}</Td>
<Td right mono bold color={tokens.text}>{b.contrib.toFixed(4)}</Td>
</tr>
))}
<tr>
<Td bold color={tokens.accent}>Σ 总分</Td>
<Td right mono color={tokens.textMuted}>{score.weightSum.toFixed(2)}</Td>
<Td right mono color={tokens.textMuted}>—</Td>
<Td right mono bold color={tokens.accent}>{score.score.toFixed(4)}</Td>
</tr>
</Table>
</Card>
</div>
{/* 第二行:换权重 → 排序对比(评审现场最有说服力的一屏) */}
<Card
title="换权重 → 排序对比"
icon={<GitCompare size={14} color={tokens.warning} />}
full
right={<Chip color={cmp.orderChanged ? tokens.warning : tokens.textSub}>{cmp.orderChanged ? '排序随权重改变' : '两套排序一致'}</Chip>}
note="只比名次序列、不比分数(分数本来就不同)。A=SOW 直译偏「损失/产能」,B=金额导向,偏「金额/频次/可改善性」,故事线不同 → 优先序不同。默认 B。"
>
<Table head={<>
<Th>候选项</Th><Th>区域</Th><Th right>A 名次</Th><Th right>B 名次</Th><Th right>B 相对 A</Th>
</>}>
{cmp.rankB.map((r) => {
const a = rankAOf(r.item.id);
const b = rankBOf(r.item.id);
const delta = a - b; // >0:B 比 A 更靠前(上升)
return (
<tr key={r.item.id}>
<Td color={tokens.text}>
<span style={{ fontWeight: 700 }}>{r.item.id}</span>
<span style={{ color: tokens.textSub, fontWeight: 400 }}> {r.item.title}</span>
</Td>
<Td><Chip color={tokens.info}>{r.item.region ?? '—'}</Chip></Td>
<Td right mono color={tokens.textSub}>{a}</Td>
<Td right mono bold color={tokens.accent}>{b}</Td>
<Td right mono bold color={delta > 0 ? tokens.success : delta < 0 ? tokens.danger : tokens.textMuted}>
{delta > 0 ? `↑${delta}` : delta < 0 ? `↓${-delta}` : '—'}
</Td>
</tr>
);
})}
</Table>
</Card>
{/* 第三行:由候选生成改善任务(只到待审核,四项必填留空) */}
<Card
title="由候选生成改善任务"
icon={<FilePlus2 size={14} color={tokens.success} />}
full
right={lastCreated
? <Chip color={tokens.success}>已生成 {lastCreated}·待审核</Chip>
: <Chip color={tokens.textMuted}>生成后进入「待审核」</Chip>}
note="首要真因挂五实体之一(不允许并列多个);真因 A/B/C 分类与「识别途径」是两回事。生成的任务四项必填留空 → 录入台派发闸会拒派,补齐后才能派发(断言⑨)。"
>
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,2fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)', gap: 10, alignItems: 'end' }}>
<div style={{ minWidth: 0 }}>
<label style={labelStyle}>任务标题(来自候选,可改)</label>
<input style={inputStyle} value={formTitle} onChange={(e) => setFormTitle(e.target.value)} placeholder="改善任务标题" />
</div>
<div style={{ minWidth: 0 }}>
<label style={labelStyle}>首要真因实体类型</label>
<select style={inputStyle} value={rootType} onChange={(e) => setRootType(e.target.value as ImprovementTask['rootCauseEntity']['type'])}>
{ROOT_TYPES.map((t) => <option key={t} value={t}>{t}</option>)}
</select>
</div>
<div style={{ minWidth: 0 }}>
<label style={labelStyle}>实体 ID(必填,不臆造)</label>
<input style={inputStyle} value={rootId} onChange={(e) => setRootId(e.target.value)} placeholder="如 FT-甲班 / XRAY-SETUP-01" />
</div>
<div style={{ minWidth: 0 }}>
<label style={labelStyle}>真因分类</label>
<select style={inputStyle} value={causeClass} onChange={(e) => setCauseClass(e.target.value as ImprovementTask['causeClass'])}>
{CAUSE_CLASSES.map((c) => <option key={c} value={c}>{c} 类</option>)}
</select>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 9 }}>
<Chip color={tokens.info} title={CAUSE_CLASS_NOTE[causeClass]}>{CAUSE_CLASS_NOTE[causeClass]}</Chip>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 10.5, color: tokens.textMuted }}>
证据链预填:{selected.note ?? selected.title}
</span>
<button
onClick={submit}
disabled={!canSubmit}
style={{
fontSize: 11.5, fontWeight: 700, padding: '6px 16px', borderRadius: 8,
cursor: canSubmit ? 'pointer' : 'not-allowed',
border: `1px solid ${canSubmit ? tokens.success : tokens.border}`,
background: canSubmit ? `${tokens.success}1f` : 'transparent',
color: canSubmit ? tokens.success : tokens.textMuted,
}}
>
生成待审核任务
</button>
</div>
{!canSubmit && (
<Note>请填写「实体 ID」后再生成(首要真因必须落到一个具体实体,不允许空挂或臆造)。</Note>
)}
{lastCreated && (
<Note>
已生成 <b style={{ color: tokens.success }}>{lastCreated}</b>(待审核·四项必填留空)。
前往「录入台 · 改善任务」体验派发闸:缺负责人/完成时限/预期收益/验证方式任一项即拒派,任务停在待审核。
当前共有改善任务 {tasks.length} 条。
</Note>
)}
</Card>
</div>
);
}
@@ -0,0 +1,257 @@
/**
* 工序·工位对比(region 页签 · W2-B)。
*
* ★ 这是**三区域模板仿真合成**页(断言④),不是日志贯通页:
* SRF 缓冲解耦 / FT 多因子连乘 / ASLT 事件驱动,三站不同构,**一套 A×P×Q 通用式套三站一定错**。
* 线体合成:串行 A/Q 连乘·P 取瓶颈;并行按投入量对三率分别加权再连乘;区域按线别投入量加权。
*
* 纪律:
* ① 全部读数标「模拟·模板仿真」,非实测、不复现 POC 锚点、不与日志贯通单机值混算。
* 日志贯通全链路仅 DEK001 一台(见总览/损失结构/设备时间轴页)。
* ② 数字只从 L3 regionRollup / srfDayByDate / ftDayByDate / asltDayByDate 取,视图不二次计算。
* ③ 反例(算术平均/对 OEE 加权/日均、FT 通用式 A、零缓冲下界)只供对照,绝不当读数。
* ④ 按业务日对齐(scope.bizDate),与顶栏游标同轴;周期累计另由 L3 Σ分子/Σ分母,不在此日均。
*/
import { Factory, GitBranch, Layers, ArrowRightLeft, AlertTriangle } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import {
regionRollup, srfDayByDate, ftDayByDate, asltDayByDate, METHOD_LABEL,
} from '../../lib/oeeService';
import { TEMPLATE_LABEL, ASLT_TIME_CLASSES, ASLT_CLASS_LABEL } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, EmptyBox,
grid2, pageStyle, pct, pctUnitOrGap, hrs, dur, qty, ASLT_CLASS_COLORS, FACTOR_COLORS,
} from './oeeUi';
import { StackedBarChart } from './charts';
import type { OeeViewProps } from './OeeOverview';
export default function OeeRegion({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const srf = srfDayByDate(scope.bizDate);
const ft = ftDayByDate(scope.bizDate);
const aslt = asltDayByDate(scope.bizDate);
const rollup = regionRollup(scope.bizDate);
if (!srf || !ft || !aslt) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="工序·工位对比" icon={<Factory size={15} color={tokens.accent} />} />
<EmptyBox>当前业务日({scope.bizDate})无三区域种子结果,不显示数字、也不显示 0。</EmptyBox>
</div>
);
}
const buf = srf.result.buffer;
const pmDev = ft.devices.find((d) => d.pmSec > 0) ?? null;
const pmOff = pmDev ? ft.devicesPmOff.find((d) => d.deviceId === pmDev.deviceId) ?? null : null;
const lineNames = ['SRF-L1', 'FT-L1', 'ASLT-L1'];
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="工序·工位对比" icon={<Factory size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="模板仿真合成,非日志贯通、非实测;SRF 仅 DEK+DCP 两台代表站、FT 仅 93k178 有客户操作数、ASLT 无客户算法表">模拟 · 模板仿真</Chip>}
/>
<Note>
三区域线体合成已于 W2-A 落地(断言④)。本页读数为<strong>模板仿真合成</strong>,非实测、不复现 POC 锚点,
不与日志贯通单机值混算;日志贯通全链路仅 DEK001 一台。三站算法不同构({TEMPLATE_LABEL.SRF_BUFFER} / {TEMPLATE_LABEL.FT_MULTIPLY} / {TEMPLATE_LABEL.ASLT_EVENT}),
通用 A×P×Q 式套三站必错,故各站独立模板、各自标注口径。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。
</Note>
<Tiles items={[
{ label: 'SRF-L1 OEE', value: pctUnitOrGap(rollup.lines[0].oee), sub: METHOD_LABEL[rollup.lines[0].method].slice(0, 4), color: tokens.textSub, title: rollup.lines[0].formula },
{ label: 'FT-L1 OEE', value: pctUnitOrGap(rollup.lines[1].oee), sub: '并行加权', color: tokens.textSub, title: rollup.lines[1].formula },
{ label: 'ASLT-L1 OEE', value: pctUnitOrGap(rollup.lines[2].oee), sub: '单台 12 Site', color: tokens.textSub, title: rollup.lines[2].formula },
{ label: '三区域加权 OEE', value: pctUnitOrGap(rollup.region.oee), sub: '线别按投入量加权', color: tokens.accent, title: rollup.region.formula },
]} />
<div style={grid2}>
{/* SRF 缓冲解耦 */}
<Card
title="SRF 缓冲解耦"
icon={<GitBranch size={14} color={tokens.accent} />}
right={<><Chip color={buf.fullyDecoupled ? tokens.success : tokens.warning}>{buf.fullyDecoupled ? '全线解耦' : '至少一侧未解耦'}</Chip></>}
note="上游停机靠缓冲覆盖(C_down=B×下游ICT),下游停机靠上游填充(C_up=B×上游ICT),两侧分母 ICT 不同不可混用。零缓冲是理论下界,不是本线考核口径。产出量取仿真值时 P 恒 100%(模型产物,非实测性能率)。"
>
<Table head={<>
<Th>缓冲力学量</Th><Th right>值</Th><Th>口径</Th>
</>}>
<tr><Td>缓冲容量 B</Td><Td right mono bold>{buf.capacity}</Td><Td color={tokens.textMuted}>在制品单位</Td></tr>
<tr><Td>覆盖时间 C_down</Td><Td right mono>{dur(buf.coverageSec)}</Td><Td color={tokens.textMuted}>B×下游ICT</Td></tr>
<tr><Td>上游最长停机</Td><Td right mono>{dur(buf.upstreamMaxStopSec)}</Td><Td color={tokens.textMuted}>合并非计划段</Td></tr>
<tr><Td>B_min(上游侧)</Td><Td right mono color={buf.decoupled ? tokens.success : tokens.warning}>{buf.minCapacity}</Td><Td color={tokens.textMuted}>{buf.decoupled ? '已满足' : '未满足'}</Td></tr>
<tr><Td>B_min(下游侧)</Td><Td right mono color={buf.decoupledDownstream ? tokens.success : tokens.warning}>{buf.minCapacityDownstream}</Td><Td color={tokens.textMuted}>{buf.decoupledDownstream ? '已满足' : '未满足'}(分母上游ICT)</Td></tr>
<tr><Td>上游阻塞损失</Td><Td right mono>{dur(buf.upstream.blockedSec)}</Td><Td color={tokens.textMuted}>{buf.upstream.blockCount} 次满载受限</Td></tr>
<tr><Td>下游饥饿损失</Td><Td right mono>{dur(buf.downstream.starvedSec)}</Td><Td color={tokens.textMuted}>{buf.downstream.starveCount} 次空缓冲受限</Td></tr>
</Table>
<div style={{ marginTop: 8 }}>
<Tiles items={[
{ label: '主口径 OEE', value: pctUnitOrGap(srf.result.line.oee), sub: srf.result.stations.map((s) => s.qtySource).join('/'), color: tokens.text, title: srf.result.line.formula },
{ label: '仿真口径 OEE', value: pctUnitOrGap(srf.result.simBased.oee), sub: '缓冲敏感性用此', color: tokens.textSub, title: '同为仿真数量,与零缓冲比才是缓冲效应' },
{ label: '零缓冲下界', value: pctUnitOrGap(srf.result.zeroBuffer.oee), sub: '理论下界·非考核', color: tokens.textMuted, title: 'B=0 全耦合,不是本线口径' },
]} />
</div>
{srf.dq.blocked && (
<Note><span style={{ color: tokens.warning }}>DQ-10:</span>{srf.dq.reason}</Note>
)}
</Card>
{/* FT 多因子连乘 */}
<Card
title="FT 多因子连乘"
icon={<Layers size={14} color={tokens.accent} />}
right={<><Chip color={tokens.textMuted}>A≠RT/PPT</Chip></>}
note="A=(1−Down率)(1−SetupLoss)(1−Corr)−计划损失,P=1−(OE+Index+Jam),Q=1−(Rescreen×良率损失)。并行合成按投入量对三率分别加权再连乘,不是对各台 OEE 求加权平均。SetupLoss 五操作数含义待 IE 确认。"
>
<Table head={<>
<Th>设备</Th><Th right>A</Th><Th right>P</Th><Th right>Q</Th><Th right>OEE</Th><Th>PM(C06)</Th>
</>}>
{ft.devices.map((d) => (
<tr key={d.deviceId}>
<Td bold>{d.deviceId}</Td>
<Td right mono color={FACTOR_COLORS.A}>{pctUnitOrGap(d.a)}</Td>
<Td right mono color={FACTOR_COLORS.P}>{pctUnitOrGap(d.p)}</Td>
<Td right mono color={FACTOR_COLORS.Q}>{pctUnitOrGap(d.q)}</Td>
<Td right mono bold>{pctUnitOrGap(d.oee)}</Td>
<Td color={d.pmIncluded ? tokens.warning : tokens.textMuted}>{d.pmIncluded ? `开 ${dur(d.pmSec)}` : '关'}</Td>
</tr>
))}
<tr>
<Td bold color={tokens.accent}>FT-L1 加权</Td>
<Td right mono>{pctUnitOrGap(ft.line.a)}</Td>
<Td right mono>{pctUnitOrGap(ft.line.p)}</Td>
<Td right mono>{pctUnitOrGap(ft.line.q)}</Td>
<Td right mono bold color={tokens.accent}>{pctUnitOrGap(ft.line.oee)}</Td>
<Td color={tokens.textMuted}>投入量加权</Td>
</tr>
</Table>
{pmDev && pmOff && (
<div style={{ marginTop: 8 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>PM 敏感性(C06 开关对照 · {pmDev.deviceId})</div>
<Tiles items={[
{ label: 'PM 计入停机', value: pctUnitOrGap(pmDev.oee), sub: `Down +${dur(pmDev.pmSec)}`, color: tokens.warning },
{ label: 'PM 不计入', value: pctUnitOrGap(pmOff.oee), sub: '同操作数关 PM', color: tokens.textSub },
{ label: 'Δ OEE', value: Number.isFinite(pmDev.oee) && Number.isFinite(pmOff.oee) ? `${((pmDev.oee - pmOff.oee) * 100).toFixed(2)}pp` : '—', sub: 'PM 拉低', color: tokens.danger },
]} />
</div>
)}
<div style={{ marginTop: 8 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>反例:误用通用式 A=RT/PPT(错误,仅供对照)</div>
<Table head={<>
<Th>设备</Th><Th right>连乘扣减 A(正确)</Th><Th right>通用 RT/PPT(错误)</Th>
</>}>
{ft.devices.map((d) => (
<tr key={d.deviceId}>
<Td>{d.deviceId}</Td>
<Td right mono color={tokens.success}>{pctUnitOrGap(d.a)}</Td>
<Td right mono color={tokens.danger}>{pctUnitOrGap(d.contrastGenericA)}</Td>
</tr>
))}
</Table>
</div>
</Card>
</div>
<div style={grid2}>
{/* ASLT 事件驱动 · 六-2 时间账 */}
<Card
title="ASLT 事件驱动 · 时间六分类"
icon={<AlertTriangle size={14} color={tokens.accent} />}
right={<><Chip color={aslt.result.timeAccountResidualSec === 0 ? tokens.textSub : tokens.warning}>残差 {dur(aslt.result.timeAccountResidualSec)}</Chip></>}
note="A/P 为活跃窗口口径(>60min 间隔切窗,单台 12 Site),与站别汇总口径(POC 41.75%)是两套读数,不得交叉配对。六分类时间账残差须为 0。Wait+Plan 占比是改善顺序依据(物料→排产→满载→换型→维修)。"
>
<StackedBarChart
items={[{
key: 'aslt', label: `日历 ${hrs(aslt.result.calendarSec)}h`, total: aslt.result.calendarSec,
display: `${hrs(aslt.result.calendarSec)}h`,
segs: ASLT_TIME_CLASSES.map((c) => {
const row = aslt.result.timeAccount.find((t) => t.class === c)!;
return { label: ASLT_CLASS_LABEL[c], value: row.durationSec, color: ASLT_CLASS_COLORS[c] };
}),
}]}
unit="s"
/>
<div style={{ marginTop: 8 }}>
<Table head={<>
<Th>时间分类</Th><Th right>时长(h)</Th><Th right>占比</Th>
</>}>
{ASLT_TIME_CLASSES.map((c) => {
const row = aslt.result.timeAccount.find((t) => t.class === c)!;
const hot = c === 'WAIT' || c === 'PLAN';
return (
<tr key={c}>
<Td color={ASLT_CLASS_COLORS[c]} bold>{ASLT_CLASS_LABEL[c]}{hot ? ' ★' : ''}</Td>
<Td right mono>{hrs(row.durationSec)}</Td>
<Td right mono color={hot ? tokens.warning : tokens.textSub}>{row.pctOfTotal.toFixed(2)}%</Td>
</tr>
);
})}
</Table>
</div>
<div style={{ marginTop: 8 }}>
<Tiles items={[
{ label: 'Wait+Plan 占比', value: `${aslt.result.waitPlanPct.toFixed(2)}%`, sub: '改善顺序依据', color: tokens.warning },
{ label: '活跃窗口', value: String(aslt.result.activeWindows.length), sub: `> ${aslt.result.activeGapSec / 60}min 切分`, color: tokens.textSub },
{ label: 'A / P / Q', value: `${pctUnitOrGap(aslt.result.a)}/${pctUnitOrGap(aslt.result.p)}/${pctUnitOrGap(aslt.result.q)}`, sub: '活跃窗口口径', color: tokens.textSub },
{ label: '报警配对率', value: `${pct(aslt.result.pairing.rate)}%`, sub: `${aslt.result.pairing.paired}/${aslt.result.pairing.total}`, color: tokens.textSub },
]} />
</div>
</Card>
{/* 线体合成法与反例 */}
<Card
title="线体合成法与反例"
icon={<ArrowRightLeft size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>断言④ · 不用均值</Chip>}
note="串行 A/Q 连乘·P 取瓶颈;并行按投入量对三率分别加权再连乘;区域按线别投入量加权。周期累计 Σ分子/Σ分母,不用日 OEE 求平均倒推。下方反例为错误算法,只供说明为什么不能那么算。"
>
<Table head={<>
<Th>范围</Th><Th right>投入量(权重)</Th><Th right>OEE</Th><Th>合成法</Th>
</>}>
{rollup.lines.map((l, i) => (
<tr key={l.scopeLabel}>
<Td bold>{lineNames[i]}</Td>
<Td right mono color={tokens.textMuted}>{qty(rollup.lineMembers[i].inputQty)}</Td>
<Td right mono bold>{pct(l.oee)}%</Td>
<Td color={tokens.textMuted}>{METHOD_LABEL[l.method]}</Td>
</tr>
))}
<tr>
<Td bold color={tokens.accent}>三区域加权</Td>
<Td right mono color={tokens.textMuted}>{qty(rollup.lineMembers.reduce((a, m) => a + m.inputQty, 0))}</Td>
<Td right mono bold color={tokens.accent}>{pct(rollup.region.oee)}%</Td>
<Td color={tokens.textMuted}>{METHOD_LABEL[rollup.region.method]}</Td>
</tr>
</Table>
<div style={{ marginTop: 8 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub, marginBottom: 4 }}>反例对照(错误算法,仅供说明)</div>
<Table head={<>
<Th>错误方法</Th><Th right>OEE</Th><Th>为什么错</Th>
</>}>
<tr>
<Td color={tokens.textMuted}>线别算术平均</Td>
<Td right mono color={tokens.danger}>{pct(rollup.wrongMethods.arithmeticMeanOfLines)}%</Td>
<Td color={tokens.textMuted}>忽略各线投入量差异</Td>
</tr>
<tr>
<Td color={tokens.textMuted}>对线别 OEE 加权</Td>
<Td right mono color={tokens.danger}>{pct(rollup.wrongMethods.weightedMeanOfLineOee)}%</Td>
<Td color={tokens.textMuted}>应对三率分别加权再连乘</Td>
</tr>
<tr>
<Td color={tokens.textMuted}>日 OEE 求平均</Td>
<Td right mono color={tokens.danger}>{pct(rollup.wrongMethods.meanOfDailyOee)}%</Td>
<Td color={tokens.textMuted}>应累加原始量再重算,非日均</Td>
</tr>
</Table>
</div>
{rollup.lines.some((l) => !l.ok) && (
<Note><span style={{ color: tokens.warning }}>合成输入存在问题:</span>{rollup.lines.filter((l) => !l.ok).map((l) => `${l.scopeLabel}:${l.problems.join(';')}`).join(' ')}</Note>
)}
</Card>
</div>
</div>
);
}
@@ -0,0 +1,242 @@
/**
* 报表导出页(report 页签 · W4-B,建议书 §5.2.2 no.19)。
*
* ★ 七类固定报表(REPORT_KINDS),与智能体 exportReport 工具**同源**:
* 都走 L3 buildReportPayload → reportRows,视图不另算一份数(断言②)。
* 预览即所导出:表格按可读格式渲染,下载文件保留原始数值口径(JSON 原值 / CSV RFC4180)。
*
* 三条诚实纪律:
* ① 无种子日 → 空行 + 缺口,不编数;DQ 阻断 → 标「暂缓发布」,照实给 publishNotice;
* ② demo 周/月报仅 3 日种子不足累计;行内 note 照实说,不假装有周/月累计数;
* ③ 文件名带口径版本留痕(断言⑩);CSV 前置 BOM 供 Excel 正确识别 UTF-8。
*
* 改善闭环报表(CLOSURE)读 MetricWorkspace lifted 的共享 tasks(与优先清单/录入台/任务中心同源)。
*/
import { useState } from 'react';
import { FileDown, FileJson, FileSpreadsheet, ShieldAlert, ScrollText, Info, Table2 } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import {
REPORT_KINDS, REPORT_KIND_LABEL, buildReportPayload, reportToCsv, reportFileName,
} from '../../lib/oeeService';
import type { ReportKind } from '../../types/oee';
import type { ImprovementTask } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, EmptyBox, grid2, pageStyle, pct, dur,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
export interface OeeReportProps extends OeeViewProps {
/** 改善任务(与优先清单/录入台/任务中心共享,由 MetricWorkspace lifted state 提供)。 */
tasks: ImprovementTask[];
}
/** 导出字段名 → 可读列头(仅展示映射,不改原始键;下载文件仍用原始键)。 */
const COL_LABEL: Record<string, string> = {
scope: '口径范围', bizDate: '业务日', device: '设备', a: 'A 时间稼动', p: 'P 性能稼动', q: 'Q 良率',
oee: 'OEE', pptSec: 'PPT', unattributedPct: '未归因占比', blocked: 'DQ 阻断',
id: '编号', level: '级别', kind: '类别', title: '标题', subject: '主体', state: '状态',
blocksPublish: '阻断发布', owner: '责任人', priorityScore: '优先级分', weightScheme: '权重方案',
causeClass: '真因类', target: '追溯目标', value: '值', unit: '单位', lineNo: '行号',
source: '来源', wired: '贯通到行', note: '说明',
shift: '班次', caliber: '口径版本', line: '线体', week: '周', month: '月',
loadH: '负荷 h', runH: '运行 h', boards: '板数', days: '覆盖日',
outputQty: 'Σ投入', goodQty: 'Σ良品', runSec: 'Σ运行',
};
/** 比率字段(0–1):预览 ×100 显示,下载保留原值。 */
const RATIO_KEYS = new Set(['a', 'p', 'q', 'oee', 'unattributedPct', 'enabledPct', 'occupancyPct']);
const isSecKey = (k: string) => /Sec$/.test(k);
/** 单元格可读渲染:null→—、布尔→是/否、比率→%、秒→时长、其余数字→原值。纯展示,不重算业务量。 */
function fmtCell(key: string, v: unknown): string {
if (v === null || v === undefined) return '—';
if (typeof v === 'boolean') return v ? '是' : '否';
if (typeof v === 'number') {
if (Number.isNaN(v)) return '—';
if (RATIO_KEYS.has(key)) return `${pct(v)}%`;
if (isSecKey(key)) return dur(v);
return Number.isInteger(v) ? String(v) : v.toFixed(2);
}
return String(v);
}
export default function OeeReport({ filter, tasks }: OeeReportProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const [kind, setKind] = useState<ReportKind>('DAILY');
const [lastDownload, setLastDownload] = useState<string | null>(null);
/* 数字一律 L3 现算:与 exportReport 工具同源(buildReportPayload → reportRows)。 */
const build = buildReportPayload(kind, scope.bizDate, tasks);
const rows = build.payload.rows;
const cols: string[] = [];
for (const r of rows) for (const k of Object.keys(r)) if (!cols.includes(k)) cols.push(k);
const isPeriodReport = kind === 'WEEKLY' || kind === 'MONTHLY_CALIBER';
const fileName = reportFileName(build.payload);
/** 下载:JSON 原值美化 / CSV RFC4180 + BOM。Blob 副作用属视图层(L4),引擎不碰 IO。 */
const doDownload = (fmt: 'JSON' | 'CSV') => {
const payload = { ...build.payload, format: fmt };
const text = fmt === 'CSV' ? '' + reportToCsv(payload) : JSON.stringify(payload, null, 2);
const mime = fmt === 'CSV' ? 'text/csv;charset=utf-8' : 'application/json;charset=utf-8';
const blob = new Blob([text], { type: mime });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = reportFileName(payload);
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
setLastDownload(`${reportFileName(payload)} · ${rows.length} 行 · ${fmt}`);
};
const dlBtn = (fmt: 'JSON' | 'CSV', icon: React.ReactNode, label: string) => (
<button
onClick={() => doDownload(fmt)}
disabled={rows.length === 0}
className="ghost-btn"
title={rows.length === 0 ? '空报表不可下载(无种子日不编数)' : `下载 ${label}(${reportFileName({ ...build.payload, format: fmt })})`}
style={{
display: 'flex', alignItems: 'center', gap: 5, cursor: rows.length === 0 ? 'not-allowed' : 'pointer',
fontSize: 11.5, fontWeight: 700, padding: '4px 10px', borderRadius: 8, whiteSpace: 'nowrap',
opacity: rows.length === 0 ? 0.45 : 1,
color: tokens.accent, background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}
>
{icon} {label}
</button>
);
return (
<div style={pageStyle}>
<ScopeBar
filter={filter}
title="报表导出"
icon={<FileDown size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textSub}>7 类固定报表 · 与智能体工具同源</Chip>}
/>
{/* 报表类别选择器:七类固定,点选即换预览与下载内容 */}
<Card title="报表类别(7 类固定)" icon={<Table2 size={14} color={tokens.accent} />}
note="班次 OEE / 日报 / 异常 / 周报 / 月度口径 / 改善闭环 / 审计追溯。原型 OEE 为日级,班次筛选不改变日级口径;周/月仅 3 日种子,不足累计照实标缺口。">
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{REPORT_KINDS.map((k) => {
const on = k === kind;
return (
<button
key={k}
onClick={() => { setKind(k); setLastDownload(null); }}
className="ghost-btn"
style={{
padding: '5px 11px', borderRadius: 9, fontSize: 12, cursor: 'pointer',
fontWeight: on ? 700 : 500, whiteSpace: 'nowrap',
border: `1px solid ${on ? 'transparent' : tokens.border}`,
background: on ? tokens.accent : 'transparent',
color: on ? tokens.onAccent : tokens.textSub,
boxShadow: on ? `0 2px 8px ${tokens.accent}40` : 'none',
transition: 'background .18s ease, color .18s ease',
}}
>
{REPORT_KIND_LABEL[k]}
</button>
);
})}
</div>
</Card>
<Tiles items={[
{ label: '报表类别', value: REPORT_KIND_LABEL[kind], sub: kind, color: tokens.text, title: '七类固定报表之一' },
{ label: '业务日', value: scope.bizDate, sub: '锚点单机 DEK001', color: tokens.textSub, title: '与顶栏筛选同源' },
{ label: '口径版本', value: build.payload.caliberVersion, sub: '随文件名留痕', color: tokens.textSub, title: '断言⑩:口径版本随导出文件留痕' },
{ label: '数据行数', value: String(rows.length), sub: `${cols.length} 字段`, color: tokens.text, title: '空行=无种子日,不编数' },
{ label: '发布闸', value: build.blocked ? '暂缓发布' : '可发布', sub: build.blocked ? '见下方披露' : 'DQ 通过', color: build.blocked ? tokens.warning : tokens.success, title: build.gap ?? 'DQ 未阻断,可作为发布口径' },
]} />
{/* DQ 阻断 / 无种子:照实披露,不抹平 */}
{build.blocked && build.gap && (
<Card title="发布闸:暂缓发布" icon={<ShieldAlert size={14} color={tokens.warning} />} tone={tokens.warning}>
<Note>
<span style={{ color: tokens.warning }}>{build.gap}</span>
</Note>
</Card>
)}
{/* 周/月报诚实说明:种子覆盖不足一周/一月,不编累计数 */}
{isPeriodReport && (
<Card title="周/月报口径说明" icon={<Info size={14} color={tokens.info} />} tone={tokens.info}>
<Note>原型仅 3 日种子(2026-09-01/02/03),不足一周/一月累计。本报表照实给出缺口说明行,<strong>不编造周/月累计数</strong>;生产阶段接入连续日志后再做实累计口径。</Note>
</Card>
)}
{/* 预览:动态列(行键并集,首见顺序),所见即所导出 */}
<Card
title={`报表预览 · ${REPORT_KIND_LABEL[kind]}`}
icon={<ScrollText size={14} color={tokens.accent} />}
full
right={<div style={{ display: 'flex', gap: 6 }}>{dlBtn('JSON', <FileJson size={13} />, 'JSON')}{dlBtn('CSV', <FileSpreadsheet size={13} />, 'CSV')}</div>}
note="预览按可读格式渲染(比率 ×100、秒 → 时长、布尔 → 是/否);下载文件保留原始数值口径(JSON 原值 / CSV RFC4180,CSV 前置 BOM 供 Excel 识别 UTF-8)。列头为导出字段名。"
>
{rows.length === 0 ? (
<EmptyBox>
{build.gap ?? `${scope.bizDate} 无种子日志,报表为空(不编数)。`}
</EmptyBox>
) : (
<Table head={<>{cols.map((c) => <Th key={c} right={RATIO_KEYS.has(c) || isSecKey(c)}>{COL_LABEL[c] ?? c}</Th>)}</>} maxHeight={340}>
{rows.map((r, i) => (
<tr key={i}>
{cols.map((c) => {
const v = r[c];
const isRatio = RATIO_KEYS.has(c);
const isBool = typeof v === 'boolean';
return (
<Td
key={c}
right={isRatio || isSecKey(c)}
mono={typeof v === 'number' || isBool}
bold={c === 'oee'}
color={isBool ? (v ? tokens.warning : tokens.success) : c === 'oee' ? tokens.text : tokens.textSub}
>
{fmtCell(c, v)}
</Td>
);
})}
</tr>
))}
</Table>
)}
</Card>
<div style={grid2}>
{/* 导出留痕:文件名 + 最近一次下载 */}
<Card title="导出留痕" icon={<FileDown size={14} color={tokens.textSub} />}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
<div style={{ fontSize: 11.5, color: tokens.textSub }}>
文件名:<span style={{ fontFamily: 'ui-monospace, monospace', color: tokens.text }}>{fileName}</span>
</div>
<div style={{ fontSize: 10.5, color: tokens.textMuted, lineHeight: 1.55 }}>
命名规则 <code>oee_&lt;类&gt;_&lt;业务日&gt;_&lt;口径版本&gt;.&lt;json|csv&gt;</code>,口径版本随文件留痕(断言⑩),便于评审现场核对同一口径。
</div>
{lastDownload ? (
<Chip color={tokens.success}>已下载 {lastDownload}</Chip>
) : (
<Chip color={tokens.textMuted}>尚未下载 · 点右上 JSON / CSV</Chip>
)}
<Note>下载为浏览器本地 Blob,不落库、不改种子(原型 SQLite 锁定四表,报表导出只读不写)。</Note>
</div>
</Card>
{/* 报表口径与边界 */}
<Card title="报表口径与边界" icon={<Info size={14} color={tokens.warning} />} tone={tokens.warning}>
<Note>
① 七类报表与智能体 <code>exportReport</code> 工具<strong>同源</strong>(buildReportPayload → reportRows),视图不另算一份数(断言②)。<br />
② 审计追溯报表带<strong>行号血缘</strong>(lineNo/source/wired),可回溯到 EVENT.DAT 原始行。<br />
③ 改善闭环报表读<strong>共享 tasks</strong>(与优先清单/录入台/任务中心同一份内存态)。<br />
④ 无种子日空行不编数;DQ 阻断标暂缓发布;周/月仅 3 日种子照实标缺口。<br />
</Note>
</Card>
</div>
</div>
);
}
@@ -0,0 +1,265 @@
/**
* 设备时间轴(detail 页签 · W2-B)。
*
* ★ 十态甘特,手写 SVG,**不引入 ECharts**(ADR-01)。复用 charts.tsx 的主题令牌与轴域自适应思路。
* 时间轴是状态段的物理载体:每段可下钻到构成它的事件实例,再到 L1 原始日志行号(断言①血缘)。
*
* 纪律:
* ① 班次筛选只作用于时间轴与状态段(scope.shiftNote);**OEE 仍为日级**,不做日均摊派、不出班次级 OEE。
* ② UNKNOWN(未采集)≠ 无生产:不计入 PPT 分母,单独着色并标注(DQ-10 三态分开)。
* ③ 间隙填充段(filledByGapRule)与影子段(shadowOf)显式标记,便于审计;数字只从 L3 day.segments 取。
*/
import { useState } from 'react';
import { GanttChartSquare, Clock, GitBranch, MousePointerClick } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope, ALL } from '../../lib/oeeFilters';
import { ctWindowForDate, shiftsForDate, SHIFT_PATTERN } from '../../data/oee/devices';
import { EVENT_BY_CODE } from '../../data/oee/events48';
import { STATE_LABEL, STATE_PRIORITY, type SegmentState } from '../../types/oee';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, Note, EmptyBox,
grid2, pageStyle, dur, hrs, STATE_COLORS,
} from './oeeUi';
import type { OeeViewProps } from './OeeOverview';
const STATE_ORDER: SegmentState[] = [
...(Object.keys(STATE_PRIORITY) as (keyof typeof STATE_PRIORITY)[]), 'UNKNOWN',
];
const hhmmss = (iso: string) => iso.slice(11, 19);
export default function OeeTimeline({ filter }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const day = scope.day;
const [selId, setSelId] = useState<string | null>(null);
if (!day) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="设备时间轴" icon={<GanttChartSquare size={15} color={tokens.accent} />} />
<EmptyBox>
状态段时间轴仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入。<br />
{scope.gap ?? scope.coverageNote}
</EmptyBox>
</div>
);
}
const segs = day.segments.segments;
const tot = day.segments.totals;
const ct = ctWindowForDate(scope.bizDate);
const ctStart = Date.parse(ct.start) / 1000;
const ctSpan = (Date.parse(ct.end) / 1000) - ctStart; // 86400
const shifts = shiftsForDate(scope.bizDate);
const selShift = filter.shiftId === ALL ? null : SHIFT_PATTERN.find((p) => p.id === filter.shiftId) ?? null;
const selShiftQualified = selShift ? `${scope.bizDate}-${selShift.id}` : null;
/* 班次筛选:只筛状态段,不改 OEE 分母。表与甘特高亮同步。 */
const visibleSegs = selShiftQualified ? segs.filter((s) => s.shiftId === selShiftQualified) : segs;
const sel = segs.find((s) => s.id === selId) ?? null;
const noTimeSource = day.caliberVersion === 'ft-lot-q-v1' || day.caliberVersion === 'rollup-day-v1';
/* rollup/lot-q 无状态段:甘特/段表不适用,诚实空态(不渲染 24h 全负荷假象) */
if (noTimeSource) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="设备时间轴" icon={<GanttChartSquare size={15} color={tokens.accent} />} />
<EmptyBox>
{day.caliberVersion === 'rollup-day-v1'
? '区域汇总(rollup-day-v1)无状态段(桶/段不加总,量纲异质)。成员逐台时间轴请切换到具体设备。'
: `${day.device.id} 为 ft-lot-q-v1 批次质量口径:无设备时间源(只有 lot 计数),状态段时间轴不适用。Q 读数见「损失结构」页。`}
</EmptyBox>
</div>
);
}
const selEvents = sel
? sel.eventIds.map((id) => day.normalize.events.find((e) => e.id === id)).filter((e): e is NonNullable<typeof e> => !!e)
: [];
const stateCount = (st: SegmentState) => segs.filter((s) => s.state === st).length;
const stateSec = (st: SegmentState) => segs.filter((s) => s.state === st).reduce((a, s) => a + s.durationSec, 0);
/* 甘特几何:viewBox 1000×34,条宽随时长自适应,最短 1px 保证短停可见,不越界。 */
const W = 1000;
const H = 34;
const xOf = (epoch: number) => Math.max(0, Math.min(W, ((epoch - ctStart) / ctSpan) * W));
const barOf = (s: typeof segs[number]) => {
const x = xOf(Date.parse(s.start) / 1000);
const x2 = xOf(Date.parse(s.end) / 1000);
return { x, w: Math.max(1, x2 - x) };
};
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="设备时间轴" icon={<GanttChartSquare size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="血缘入口句柄,可逆解到设备/业务日/口径版本">{day.detailRef}</Chip>}
/>
{scope.shiftNote && (
<Note>{scope.shiftNote}(当前筛选:{selShift?.name ?? '全班次'},仅作用于下方时间轴与状态段表)</Note>
)}
<Tiles items={[
{ label: '日历时间 CT', value: hrs(tot.ctSec), sub: '00:00→次日00:00(h)', color: tokens.textSub },
{ label: '计划停机 PDT', value: hrs(tot.pdtSec), sub: 'PLAN_STOP+PM(h)', color: tokens.textSub, title: '从分母扣除' },
{ label: '负荷生产 PPT', value: hrs(tot.pptSec), sub: 'CT−PDT−UNKNOWN(h)', color: tokens.text },
{ label: '运行 RT', value: hrs(tot.runSec), sub: 'Σ RUN 段(h)', color: STATE_COLORS.RUN },
{ label: '未采集 UNKNOWN', value: dur(tot.unknownSec), sub: '不计分母(≠无生产)', color: tot.unknownSec > 0 ? tokens.warning : tokens.textSub, title: 'DQ-10:日志断流窗口,不得记为无生产' },
{ label: '状态段数', value: String(segs.length), sub: selShift ? `${visibleSegs.length} 段在本班` : '全班次', color: tokens.textSub },
]} />
{/* 十态甘特(手写 SVG) */}
<Card
title="十态状态甘特"
icon={<Clock size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>点选状态段下钻血缘</Chip>}
note="按抢占优先级解析后的非重叠状态段。UNKNOWN 单独着色(未采集,不计分母);虚线描边=间隙填充段;PM 窗口内停机保留影子双记录。班次筛选只高亮/筛选本段时间轴,OEE 仍为日级。"
>
{/* 班次带(HTML,避免 SVG 文字拉伸):3×8h 演示假设,宽度按真实窗口占比 */}
<div style={{ display: 'flex', gap: 2, marginBottom: 3 }}>
{shifts.map((sh) => {
const w = ((Date.parse(sh.end) - Date.parse(sh.start)) / 1000 / ctSpan) * 100;
const pat = SHIFT_PATTERN.find((p) => sh.id.endsWith(p.id));
const on = selShift ? sh.id === selShiftQualified : true;
return (
<div key={sh.id} style={{
width: `${w}%`, minWidth: 0, textAlign: 'center', padding: '2px 4px', borderRadius: 5,
background: on ? tokens.accentBg : tokens.panelBgAlt,
border: `1px solid ${on ? tokens.borderAccent : tokens.border}`,
opacity: on ? 1 : 0.45,
fontSize: 10, fontWeight: 700, color: on ? tokens.accent : tokens.textMuted,
whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
}} title={`${sh.start.slice(11, 16)}–${sh.end.slice(11, 16)}(演示假设 3×8h,待客户排班表确认)`}>
{pat?.name ?? sh.id} {sh.start.slice(11, 16)}–{sh.end.slice(11, 16)}
</div>
);
})}
</div>
<svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: H, display: 'block' }} preserveAspectRatio="none">
{/* 班次分隔线(8h/16h) */}
{[8, 16].map((h) => (
<line key={h} x1={(h / 24) * W} x2={(h / 24) * W} y1={0} y2={H} stroke={tokens.border} strokeWidth={1} strokeDasharray="3 3" />
))}
{segs.map((s) => {
const { x, w } = barOf(s);
const inShift = selShiftQualified ? s.shiftId === selShiftQualified : true;
const isSel = s.id === selId;
return (
<rect
key={s.id} x={x} y={3} width={w} height={28} rx={1}
fill={STATE_COLORS[s.state]}
opacity={inShift ? (s.state === 'UNKNOWN' ? 0.55 : 0.92) : 0.18}
stroke={isSel ? tokens.accent : s.filledByGapRule ? tokens.textMuted : s.state === 'UNKNOWN' ? tokens.warning : 'none'}
strokeWidth={isSel ? 2 : s.filledByGapRule || s.state === 'UNKNOWN' ? 1 : 0}
strokeDasharray={s.filledByGapRule ? '2 2' : undefined}
style={{ cursor: 'pointer' }}
onClick={() => setSelId(s.id === selId ? null : s.id)}
>
<title>{`${STATE_LABEL[s.state]} ${hhmmss(s.start)}–${hhmmss(s.end)} · ${dur(s.durationSec)}${s.filledByGapRule ? ' · 间隙填充' : ''}${s.shadowOf ? ' · 影子段' : ''}`}</title>
</rect>
);
})}
</svg>
{/* 小时刻度(HTML,等分不拉伸) */}
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 2, fontSize: 9.5, color: tokens.textMuted, fontVariantNumeric: 'tabular-nums' }}>
{[0, 4, 8, 12, 16, 20, 24].map((h) => <span key={h}>{String(h % 24).padStart(2, '0')}:00</span>)}
</div>
{/* 状态图例 + 计数 */}
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 8 }}>
{STATE_ORDER.map((st) => (
<Chip key={st} color={STATE_COLORS[st]} title={`${STATE_LABEL[st]}:${stateCount(st)} 段 / ${dur(stateSec(st))}`}>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
<span style={{ width: 8, height: 8, borderRadius: 2, background: STATE_COLORS[st], display: 'inline-block' }} />
{STATE_LABEL[st]} {stateCount(st)}
</span>
</Chip>
))}
</div>
</Card>
<div style={grid2}>
{/* 状态段表(班次筛选时只列本班) */}
<Card
title={selShift ? `状态段明细(${selShift.name})` : '状态段明细(全班次)'}
icon={<GitBranch size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>{visibleSegs.length} 段</Chip>}
note="点行选中,与甘特高亮联动。置信度<1 或间隙填充段须人工确认;未归因 IDLE 段进未归因池(DQ-06)。"
>
<Table head={<>
<Th>状态</Th><Th>起</Th><Th>止</Th><Th right>时长</Th><Th>班次</Th><Th right>事件</Th><Th>标记</Th>
</>} maxHeight={300}>
{visibleSegs.map((s) => {
const pat = SHIFT_PATTERN.find((p) => s.shiftId.endsWith(p.id));
return (
<tr key={s.id} onClick={() => setSelId(s.id === selId ? null : s.id)} style={{ cursor: 'pointer', background: s.id === selId ? tokens.accentBg : undefined }}>
<Td color={STATE_COLORS[s.state]} bold>{STATE_LABEL[s.state]}</Td>
<Td mono>{hhmmss(s.start)}</Td>
<Td mono>{hhmmss(s.end)}</Td>
<Td right mono>{dur(s.durationSec)}</Td>
<Td color={tokens.textMuted}>{pat?.name ?? '—'}</Td>
<Td right mono>{s.evidenceCount ?? s.eventIds.length}</Td>
<Td color={tokens.textMuted}>
{s.filledByGapRule ? '间隙填充' : ''}{s.shadowOf ? ' 影子' : ''}{s.confidence < 1 ? ` ${s.confidence.toFixed(2)}` : ''}{s.state === 'IDLE' ? ' 未归因' : ''}
</Td>
</tr>
);
})}
</Table>
</Card>
{/* 选中段血缘下钻:事件实例 → L1 原始日志行号(断言①) */}
<Card
title="血缘下钻"
icon={<MousePointerClick size={14} color={tokens.accent} />}
right={sel ? (
<span style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<Chip color={STATE_COLORS[sel.state]}>{STATE_LABEL[sel.state]}</Chip>
</span>
) : undefined}
note="每个数字都能从 detailRef 一路回溯到 L1 原始行号。原型无 oee_result_detail 表,用字符串句柄;生产改真外键(建议书 3.4.1)。"
>
{sel ? (
<>
<Tiles items={[
{ label: '起', value: hhmmss(sel.start), color: tokens.textSub },
{ label: '止', value: hhmmss(sel.end), color: tokens.textSub },
{ label: '时长', value: dur(sel.durationSec), color: tokens.text },
{ label: '置信度', value: sel.confidence.toFixed(2), color: sel.confidence < 1 ? tokens.warning : tokens.textSub },
]} />
<div style={{ marginTop: 8 }}>
{selEvents.length > 0 ? (
<Table head={<>
<Th>事件码</Th><Th>事件名</Th><Th right>L1 行号</Th><Th>原始时刻</Th>
</>} maxHeight={220}>
{selEvents.map((e) => {
const def = EVENT_BY_CODE[e.defCode];
return (
<tr key={e.id}>
<Td mono bold>{e.defCode}</Td>
<Td color={tokens.textSub}>{def?.name ?? '(字典外)'}</Td>
<Td right mono color={tokens.accent}>L{e.evidence.lineNo}</Td>
<Td mono color={tokens.textMuted}>{hhmmss(e.rawTime)}</Td>
</tr>
);
})}
</Table>
) : (
<EmptyBox>
<>该段无成对事件证据({sel.state === 'IDLE' ? '未归因 IDLE:采到了但归不了因,进未归因池' : sel.state === 'UNKNOWN' ? '未采集窗口:日志断流,不计分母' : '由间隙填充/锚点推导'})。<br />不编造事件归属,血缘到此为数据缺口。</>
</EmptyBox>
)}
</div>
{sel.unknownPoolId && <Note>未归因池 ID:{sel.unknownPoolId}(DQ-06 计算基础,须在录入台补录归因)。</Note>}
</>
) : (
<EmptyBox>在上方甘特或状态段表点选一段,这里显示构成它的事件实例与 L1 原始日志行号。</EmptyBox>
)}
</Card>
</div>
</div>
);
}
@@ -0,0 +1,165 @@
/**
* 趋势分析(trend 页签 · W2-B)。
*
* ★ 回放轴=3 个业务日(种子覆盖范围),**不补期、不造 12 个月曲线**(ADR-03)。
* 日级游标重算取值;班次/小时级只筛时间轴(见设备时间轴页),此处不做日均摊派。
*
* 纪律:
* ① 数字只从 L3 dekDays() 取(与指标树/本体/校验同源,断言②),视图不二次计算 OEE。
* 逐日序列由 L3 结果直接投影;环比是两期 L3 读数之差(比较量,非重算指标)。
* ② 脏日(2026-09-02)DQ-06 阻断,趋势照实画出并标「结论暂缓发布」,不抹平、不插值。
* ③ 计划档目标 C27/C28 待 IE 签字,参考线标灰;理论/计划/实际三档不混为一条线。
*/
import { TrendingUp, Activity, Layers, CalendarDays } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import { resolveScope } from '../../lib/oeeFilters';
import { dekDays, PARAMS_SIGNOFF_NOTE } from '../../lib/oeeService';
import { LOSS_BUCKETS, BUCKET_LABEL } from '../../types/oee';
import { AXIS_SCOPE_NOTE, clampPeriod, periodShortLabel } from '../../lib/oeeTime';
import {
ScopeBar, Card, Tiles, Table, Th, Td, Chip, EmptyBox,
grid2, pageStyle, pct, pctUnitOrGap, hrs, dur, BUCKET_COLORS, FACTOR_COLORS,
} from './oeeUi';
import { TrendChart, StackedBarChart } from './charts';
import type { OeeViewProps } from './OeeOverview';
export default function OeeTrend({ filter, period }: OeeViewProps) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
const day = scope.day;
if (!day || !scope.wired) {
return (
<div style={pageStyle}>
<ScopeBar filter={filter} title="趋势分析" icon={<TrendingUp size={15} color={tokens.accent} />} />
<EmptyBox>
逐业务日趋势仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。<br />
{scope.gap ?? scope.coverageNote}
</EmptyBox>
</div>
);
}
const days = dekDays(); // demo:3 个业务日,L3 缓存同源
const labels = days.map((d) => periodShortLabel(days.indexOf(d)));
const cursor = clampPeriod(period);
const cur = days[cursor];
const prev = cursor > 0 ? days[cursor - 1] : null;
/* 零运行日(RT=0):未开工/整日停机/采集截至时点。引擎不给 OEE,也不把 24h 余量当「未归因」涂成损失。 */
const noRun = (d: typeof days[number]) => d.segments.totals.runSec === 0 && d.segments.totals.pptSec > 0;
const momOee = prev && Number.isFinite(cur.tiers.actual.oee) && Number.isFinite(prev.tiers.actual.oee)
? (cur.tiers.actual.oee - prev.tiers.actual.oee) * 100 : null;
const bucketSec = (d: typeof days[number], k: typeof LOSS_BUCKETS[number]) =>
d.buckets.buckets.find((b) => b.bucket === k)?.durationSec ?? 0;
/* OEE 与三率趋势(%):实际档逐日现算值,理论/计划作参考线(计划待签字标灰)。
G 缺口日(后端 null)序列落 null:断线不画点,不拿 0/100% 连成假曲线。 */
const rate = (x: number): number | null => (Number.isFinite(x) ? x * 100 : null);
const rateSeries = [
{ name: 'OEE', color: tokens.accent, values: days.map((d) => rate(d.tiers.actual.oee)) },
{ name: 'A 时间稼动', color: FACTOR_COLORS.A, values: days.map((d) => rate(d.tiers.actual.a)) },
{ name: 'P 性能稼动', color: FACTOR_COLORS.P, values: days.map((d) => rate(d.tiers.actual.p)) },
{ name: 'Q 良品率', color: FACTOR_COLORS.Q, values: days.map((d) => rate(d.tiers.actual.q)) },
];
/* 六桶逐日分解(堆叠条):有效生产 + 六桶 + 残差,恒等于 PPT;脏日残差照实暴露。 */
const decompItems = days.map((d, i) => ({
key: d.bizDate,
label: `${labels[i]}${d.dq.blocked ? ' · 阻断' : ''}${noRun(d) ? ' · 无运行' : ''}`,
total: d.segments.totals.pptSec,
display: `${hrs(d.segments.totals.pptSec)}h`,
sub: noRun(d) ? 'RT=0 · 不按损失拆' : d.buckets.zeroResidual ? '残差0' : `残差${dur(d.buckets.residualSec)}`,
segs: noRun(d)
? [{ label: '无运行时间(RT=0)', value: d.segments.totals.pptSec, color: tokens.textMuted }]
: [
{ label: '有效生产', value: d.buckets.effectiveSec, color: tokens.success },
...LOSS_BUCKETS.map((k) => ({ label: BUCKET_LABEL[k], value: bucketSec(d, k), color: BUCKET_COLORS[k] })),
{ label: '残差(未归因+G缺口)', value: d.buckets.residualSec, color: tokens.warning },
],
}));
return (
<div style={pageStyle}>
<ScopeBar
filter={filter} title="趋势分析" icon={<TrendingUp size={15} color={tokens.accent} />}
extra={<Chip color={tokens.textMuted} title="种子只覆盖 3 个业务日,造 12 期就是编数据">{days.length} 个业务日 · 不补期</Chip>}
/>
<Tiles items={[
{ label: `当期 OEE(${labels[cursor]})`, value: pctUnitOrGap(cur.tiers.actual.oee), sub: noRun(cur) ? 'RT=0 · 不给数' : '实际档 A×P×Q', color: tokens.text, title: '分母 PPT=CT−PDT−UNKNOWN' },
{ label: 'A 时间稼动', value: pctUnitOrGap(cur.tiers.actual.a), sub: 'RT ÷ PPT', color: FACTOR_COLORS.A },
{ label: 'P 性能稼动', value: pctUnitOrGap(cur.tiers.actual.p), sub: 'N×ICT ÷ RT', color: FACTOR_COLORS.P },
{ label: 'Q 良品率', value: pctUnitOrGap(cur.tiers.actual.q), sub: '良品 ÷ N', color: FACTOR_COLORS.Q },
{ label: '环比 ΔOEE', value: momOee === null ? '—' : `${momOee >= 0 ? '+' : ''}${momOee.toFixed(2)}pp`, sub: prev ? `较 ${labels[cursor - 1]}` : '首期无环比', color: momOee === null ? tokens.textMuted : momOee >= 0 ? tokens.success : tokens.danger, title: '两期 L3 实际 OEE 读数之差(比较量,非重算)' },
]} />
<div style={grid2}>
<Card
title="OEE 与三率趋势"
icon={<Activity size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>单位 % · 游标 {labels[cursor]}</Chip>}
note={`${PARAMS_SIGNOFF_NOTE}。实线为实际档逐日现算值;虚线参考线取当期理论/计划档。脏日不插值、不抹平。`}
>
<TrendChart
series={rateSeries}
labels={labels}
marker={cursor}
yDigits={1}
refs={[
...(Number.isFinite(cur.tiers.theoretical.oee) ? [{ v: cur.tiers.theoretical.oee * 100, label: `理论 ${pct(cur.tiers.theoretical.oee)}%` }] : []),
...(Number.isFinite(cur.tiers.planned.oee) ? [{ v: cur.tiers.planned.oee * 100, label: `计划 ${pct(cur.tiers.planned.oee)}%(待签字)` }] : []),
]}
/>
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', marginTop: 4 }}>
{rateSeries.map((s) => (
<span key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textMuted }}>
<span style={{ width: 9, height: 9, borderRadius: 2, background: s.color }} />{s.name}
</span>
))}
</div>
</Card>
<Card
title="六桶损失逐日分解"
icon={<Layers size={14} color={tokens.accent} />}
right={<Chip color={tokens.textMuted}>分母 PPT · 残差恒等</Chip>}
note="每日 PPT = 有效生产 + Σ六桶 + 残差;残差 = 未归因 IDLE + 未计量的性能/工艺损失(P/Q 桶无源,不摊派)。脏日(2026-09-02)残差 > 0 触发 DQ-06,照实堆叠不归一化;RT=0 的日不按损失拆(否则整日余量会被误读为损失)。"
>
<StackedBarChart items={decompItems} unit="s" />
</Card>
</div>
<Card
title="逐业务日读数"
icon={<CalendarDays size={14} color={tokens.accent} />}
full
right={<Chip color={tokens.textMuted}>{days.length} 期 · 与 metric_trend.period 同值</Chip>}
note={`${AXIS_SCOPE_NOTE} 回放轴只覆盖种子业务日(${days.map((d) => d.bizDate).join(' / ')}),不补期。DQ-06 阻断日结论暂缓发布,趋势仍照实出数供诊断。`}
>
<Table head={<>
<Th>业务日</Th><Th right>OEE</Th><Th right>A</Th><Th right>P</Th><Th right>Q</Th>
<Th right>PPT(h)</Th><Th right>残差</Th><Th right>未归因占比</Th><Th>发布状态</Th>
</>}>
{days.map((d, i) => (
<tr key={d.bizDate} style={{ background: i === cursor ? tokens.accentBg : undefined }}>
<Td bold color={i === cursor ? tokens.accent : tokens.textSub}>{d.bizDate}{i === cursor ? ' · 游标' : ''}</Td>
<Td right mono bold>{pctUnitOrGap(d.tiers.actual.oee)}</Td>
<Td right mono color={FACTOR_COLORS.A}>{pctUnitOrGap(d.tiers.actual.a)}</Td>
<Td right mono color={FACTOR_COLORS.P}>{pctUnitOrGap(d.tiers.actual.p)}</Td>
<Td right mono color={FACTOR_COLORS.Q}>{pctUnitOrGap(d.tiers.actual.q)}</Td>
<Td right mono>{hrs(d.segments.totals.pptSec)}</Td>
<Td right mono color={d.buckets.zeroResidual ? tokens.textSub : tokens.warning}>{dur(d.buckets.residualSec)}</Td>
<Td right mono color={d.buckets.unattributedPct > 0.05 ? tokens.danger : tokens.textSub}>{pct(d.buckets.unattributedPct)}%</Td>
<Td>
{noRun(d) && <div style={{ marginBottom: 3 }}><Chip color={tokens.warning} title="当日 RT=0:未开工、整日停机或采集截至时点。OEE 不给数,不按 0% 读">无运行段</Chip></div>}
{d.dq.blocked
? <Chip color={tokens.danger} title={d.dq.publishNotice}>结论暂缓发布</Chip>
: <Chip color={tokens.textSub} title={d.dq.publishNotice}>可发布</Chip>}
</Td>
</tr>
))}
</Table>
</Card>
</div>
);
}
@@ -0,0 +1,532 @@
import { useState, type MouseEvent } from 'react';
import { useTheme } from '../../context/ThemeContext';
import { useCountUp } from '../../hooks/useCountUp';
const VB_W = 820;
const VB_H = 250;
const PAD = { l: 46, r: 14, t: 16, b: 26 };
export interface Series { name: string; color: string; values: (number | null)[]; dashed?: boolean }
/** 折线 + 面积趋势图(viewBox 等比缩放,字号随图放大)
* band:允差/目标区间,会参与纵轴定义域计算,避免区间被图切掉
* refs:单值参考线(如标准值 1200W),虚线 + 右上角标注
*
* 2026-11-14 动效层:
* ① 描线入场——实线 polyline 用 pathLength=1 + dasharray=1 + line-draw(0.6s 一次性),
* 虚线系列/面积/数据点用 line-fade 淡入(dasharray 已被虚线占用,不能叠描线)。
* 系列 <g> 的 key 掺入 labels+数值指纹:切日/回放数据变了才重播,主题切换不重播。
* ② hover 十字准星——svg 是 preserveAspectRatio="none"(文字/圆点会被拉伸),
* 故准星用 HTML 覆盖层按百分比定位,与 viewBox 线性同映射;只读展示,不改任何数据。
*/
export function TrendChart({
series, labels, height = 250, yDigits = 1, marker = 11, band, refs,
}: {
series: Series[]; labels: string[]; height?: number; yDigits?: number; marker?: number | null;
band?: { lo: number; hi: number; label?: string }[];
refs?: { v: number; label: string }[];
}) {
const { tokens } = useTheme();
const [hover, setHover] = useState<number | null>(null);
const all = series.flatMap(s => s.values).filter((v): v is number => v != null && Number.isFinite(v));
const bounds = [...(band ?? []).flatMap(b => [b.lo, b.hi]), ...(refs ?? []).map(r => r.v)];
if (!all.length) {
return <div style={{ height, display: 'flex', alignItems: 'center', justifyContent: 'center', color: tokens.textMuted, fontSize: 12 }} />;
}
let min = Math.min(...all, ...bounds);
let max = Math.max(...all, ...bounds);
if (min === max) { min -= 1; max += 1; }
const pad = (max - min) * 0.14;
min -= pad; max += pad;
const w = VB_W - PAD.l - PAD.r;
const h = VB_H - PAD.t - PAD.b;
const n = series[0].values.length;
const X = (i: number) => PAD.l + (n === 1 ? w / 2 : (i / (n - 1)) * w);
const Y = (v: number) => PAD.t + h - ((v - min) / (max - min)) * h;
const ticks = [0, 0.25, 0.5, 0.75, 1].map(f => min + (max - min) * f);
const gid = `mec-area-${series.map(s => s.name).join('')}`.replace(/\W/g, '');
/* 数据指纹:labels + 各系列数值和。变了→<g> 重挂载→描线重播;只换主题不重播 */
const drawKey = `${labels.join('|')}#${series.map(s => s.values.reduce<number>((a, b) => a + (b != null && Number.isFinite(b) ? b : 0), 0).toFixed(3)).join(',')}`;
/* null/非有限点=G 缺口:折线按连续有限段(finiteRuns)断开重画,不画 NaN 点、不跨缺口连线 */
const finiteRuns = (values: (number | null)[]): { idx: number[]; pts: string }[] => {
const runs: number[][] = [];
values.forEach((v, i) => {
if (v == null || !Number.isFinite(v)) return;
const last = runs[runs.length - 1];
if (last && last[last.length - 1] === i - 1) last.push(i);
else runs.push([i]);
});
return runs.map(idx => ({ idx, pts: idx.map(i => `${X(i)},${Y(values[i] as number)}`).join(' ') }));
};
const onMove = (e: MouseEvent<HTMLDivElement>) => {
const rect = e.currentTarget.getBoundingClientRect();
if (rect.width <= 0) return;
const vx = ((e.clientX - rect.left) / rect.width) * VB_W;
const i = n === 1 ? 0 : Math.round(((vx - PAD.l) / w) * (n - 1));
setHover(Math.max(0, Math.min(n - 1, i)));
};
const hx = hover !== null ? (X(hover) / VB_W) * 100 : 0;
return (
<div
data-role="trend-chart"
style={{ position: 'relative', width: '100%' }}
onMouseMove={onMove}
onMouseLeave={() => setHover(null)}
>
<svg viewBox={`0 0 ${VB_W} ${VB_H}`} style={{ width: '100%', height, display: 'block' }} preserveAspectRatio="none">
<defs>
<linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={series[0].color} stopOpacity="0.24" />
<stop offset="100%" stopColor={series[0].color} stopOpacity="0.01" />
</linearGradient>
</defs>
{ticks.map((tv, i) => (
<g key={i}>
<line x1={PAD.l} x2={VB_W - PAD.r} y1={Y(tv)} y2={Y(tv)} stroke={tokens.border} strokeWidth={1} />
<text x={PAD.l - 8} y={Y(tv) + 4} textAnchor="end" fontSize={11} fill={tokens.textMuted}>
{tv.toFixed(Math.abs(max - min) < 5 ? 2 : yDigits)}
</text>
</g>
))}
{band?.map((b, i) => {
const top = Y(b.hi);
const bottom = Y(b.lo);
return (
<g key={`band${i}`}>
<rect x={PAD.l} y={top} width={w} height={Math.max(1, bottom - top)} fill={tokens.success} opacity={0.08} />
<line x1={PAD.l} x2={VB_W - PAD.r} y1={top} y2={top} stroke={tokens.success} strokeWidth={1} strokeDasharray="4 4" opacity={0.55} />
<line x1={PAD.l} x2={VB_W - PAD.r} y1={bottom} y2={bottom} stroke={tokens.success} strokeWidth={1} strokeDasharray="4 4" opacity={0.55} />
{b.label && <text x={VB_W - PAD.r - 4} y={top + 12} textAnchor="end" fontSize={10.5} fill={tokens.success} opacity={0.9}>{b.label}</text>}
</g>
);
})}
{refs?.map((r, i) => (
<g key={`ref${i}`}>
<line x1={PAD.l} x2={VB_W - PAD.r} y1={Y(r.v)} y2={Y(r.v)} stroke={tokens.info} strokeWidth={1.2} strokeDasharray="6 4" opacity={0.7} />
<text x={PAD.l + 5} y={Y(r.v) - 5} fontSize={10.5} fill={tokens.info} opacity={0.9}>{r.label}</text>
</g>
))}
{labels.map((l, i) => (
(i % Math.ceil(n / 12) === 0 || i === n - 1) && (
<text key={l} x={X(i)} y={VB_H - 8} textAnchor="middle" fontSize={11} fill={tokens.textMuted}>{l}</text>
)
))}
{series.map((s, si) => {
const runs = finiteRuns(s.values);
return (
<g key={`${s.name}-${drawKey}`}>
{si === 0 && !s.dashed && runs.map((r, ri) => (
<polygon
key={`area${ri}`}
points={`${X(r.idx[0])},${PAD.t + h} ${r.pts} ${X(r.idx[r.idx.length - 1])},${PAD.t + h}`} fill={`url(#${gid})`}
style={{ animation: 'tfamd-line-fade 0.6s ease-out both' }}
/>
))}
{runs.map((r, ri) => (s.dashed ? (
<polyline
key={`dash${ri}`}
points={r.pts} fill="none" stroke={s.color} strokeWidth={1.4}
strokeLinecap="round" strokeLinejoin="round"
strokeDasharray="5 4" opacity={0.75}
style={{ animation: 'tfamd-line-fade 0.6s ease-out both' }}
/>
) : (
<polyline
key={`line${ri}`}
points={r.pts} fill="none" stroke={s.color} strokeWidth={2.2}
strokeLinecap="round" strokeLinejoin="round"
pathLength={1} strokeDasharray="1" className="line-draw"
/>
)))}
{!s.dashed && (
<g style={{ animation: 'tfamd-line-fade 0.5s ease-out both' }}>
{s.values.map((v, i) => (
v != null && Number.isFinite(v)
? <circle key={i} cx={X(i)} cy={Y(v)} r={i === marker ? 4 : 2.2} fill={s.color} />
: null
))}
</g>
)}
</g>
);
})}
{marker !== null && marker >= 0 && series[0] && series[0].values[marker] != null
&& Number.isFinite(series[0].values[marker]) && (
<line x1={X(marker)} x2={X(marker)} y1={PAD.t} y2={PAD.t + h} stroke={series[0].color} strokeWidth={1} opacity={0.3} strokeDasharray="3 3" />
)}
</svg>
{/* hover 准星(HTML 覆盖层):竖线 + 各系列圆点 + 读数气泡。pointerEvents:none 不挡交互 */}
{hover !== null && (
<div data-role="trend-crosshair" style={{ position: 'absolute', inset: 0, pointerEvents: 'none' }}>
<div style={{
position: 'absolute', left: `${hx}%`, top: `${(PAD.t / VB_H) * 100}%`,
height: `${(h / VB_H) * 100}%`, width: 1, background: tokens.textMuted, opacity: 0.55,
}} />
{series.map((s) => {
const v = s.values[hover];
if (v == null || !Number.isFinite(v)) return null;
return (
<div key={s.name} style={{
position: 'absolute', left: `${hx}%`, top: `${(Y(v) / VB_H) * 100}%`,
width: 7, height: 7, borderRadius: '50%', background: tokens.cardBg,
border: `2px solid ${s.color}`, transform: 'translate(-50%, -50%)',
}} />
);
})}
<div style={{
position: 'absolute', left: `${Math.max(10, Math.min(90, hx))}%`, top: 2,
transform: 'translateX(-50%)', whiteSpace: 'nowrap', zIndex: 2,
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 8,
padding: '4px 9px', boxShadow: tokens.cardShadow, fontSize: 10.5, lineHeight: 1.55,
}}>
<div style={{ fontWeight: 700, color: tokens.text }}>{labels[hover] ?? ''}</div>
{series.map((s) => {
const v = s.values[hover];
return (
<div key={s.name} style={{ display: 'flex', alignItems: 'center', gap: 5, color: tokens.textSub }}>
<span style={{ width: 7, height: 7, borderRadius: 2, background: s.color, flexShrink: 0 }} />
{s.name}
<span style={{ fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>
{v != null && Number.isFinite(v) ? v.toFixed(2) : '—'}
</span>
</div>
);
})}
</div>
</div>
)}
</div>
);
}
/** 横向条形(结构拆解) */
export function HBarChart({
items, height, valueSuffix = '',
}: { items: { label: string; value: number; color?: string; sub?: string; display?: string; displayColor?: string }[];
height?: number; valueSuffix?: string }) {
const { tokens } = useTheme();
const max = Math.max(...items.map(i => Math.abs(i.value)), 1);
const rowH = 30;
const h = height ?? items.length * rowH;
// 同一 grid:数值列按最长读数自适应且不折行,各行条形轨道同起止,长度仍可横向对比
return (
<div style={{
display: 'grid', gridTemplateColumns: '108px minmax(0,1fr) auto', columnGap: 8,
alignItems: 'center', alignContent: 'space-between', height: h,
}}>
{items.map((it, idx) => (
<div key={it.label} style={{ display: 'contents' }}>
<span className="card-in" style={{ animationDelay: `${idx * 40}ms`, fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>
<div className="card-in" style={{ animationDelay: `${idx * 40}ms`, height: 14, borderRadius: 4, background: tokens.accentBg, position: 'relative', overflow: 'hidden' }}>
<div style={{
position: 'absolute', left: 0, top: 0, bottom: 0, width: `${(Math.abs(it.value) / max) * 100}%`,
background: `linear-gradient(90deg, ${it.color ?? tokens.accent}, ${(it.color ?? tokens.accent)}99)`,
borderRadius: 4, transition: 'width 0.5s cubic-bezier(0.4,0,0.2,1)',
}} />
</div>
<span className="card-in" style={{ animationDelay: `${idx * 40}ms`, minWidth: 84, whiteSpace: 'nowrap', textAlign: 'right', fontSize: 11.5, fontWeight: 700, color: it.displayColor ?? tokens.text, fontVariantNumeric: 'tabular-nums' }}>
{it.display ?? `${it.value.toFixed(1)}${valueSuffix}`}
{it.sub && <span style={{ fontWeight: 400, color: tokens.textMuted, marginLeft: 4, fontSize: 10 }}>{it.sub}</span>}
</span>
</div>
))}
</div>
);
}
/** 纵轴取整:0/64/128 这种刻度读不出量级,按 1·2·2.5·5 步进挑留白最少又能分 3~5 格的那档 */
function niceAxis(rawMax: number): { max: number; step: number; divs: number } {
const target = rawMax * 1.05;
const base = 10 ** (Math.floor(Math.log10(target || 1)) - 1);
const cands: number[] = [];
for (let m = -1; m <= 3; m += 1) [1, 2, 2.5, 5].forEach(k => cands.push(k * base * 10 ** m));
const total = (s: number) => s * Math.ceil(target / s);
const ok = cands
.filter(s => { const d = Math.ceil(target / s); return d >= 3 && d <= 5; })
.sort((a, b) => total(a) - total(b) || a - b);
const step = ok[0] ?? cands.sort((a, b) => a - b).find(s => s >= target) ?? target;
const divs = Math.max(3, Math.ceil(target / step));
return { step, divs, max: step * divs };
}
const fmtTick = (v: number) => (v >= 1000 ? `${+(v / 1000).toFixed(1)}k` : Number.isInteger(v) ? String(v) : v.toFixed(1));
/** 竖向柱(工序/工位对比),支持双指标 */
export function VBarChart({
groups, labels, colors, names, height = 220, unit = '',
}: {
groups: number[][]; labels: string[]; colors: string[]; names: string[]; height?: number; unit?: string;
}) {
const { tokens } = useTheme();
const W = 520, H = 240, P = { l: 44, r: 12, t: 18, b: 30 };
const w = W - P.l - P.r, h = H - P.t - P.b;
const axis = niceAxis(Math.max(...groups.flat().filter(Number.isFinite), 1));
const gw = w / labels.length;
const bw = Math.min(22, (gw - 12) / groups.length);
return (
<div>
<svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height, display: 'block' }} preserveAspectRatio="none">
{Array.from({ length: axis.divs + 1 }, (_, i) => i).map(i => {
const f = i / axis.divs;
return (
<g key={i}>
<line x1={P.l} x2={W - P.r} y1={P.t + h * (1 - f)} y2={P.t + h * (1 - f)} stroke={tokens.border} />
<text x={P.l - 6} y={P.t + h * (1 - f) + 4} textAnchor="end" fontSize={10} fill={tokens.textMuted}>
{fmtTick(axis.step * i)}
</text>
</g>
);
})}
{labels.map((l, i) => (
<g key={l}>
{groups.map((g, gi) => {
const v = g[i] ?? 0;
const bh = (v / axis.max) * h;
const x = P.l + gw * i + gw / 2 - (groups.length * bw) / 2 + gi * bw;
return (
<g key={gi}>
<rect x={x} y={P.t + h - bh} width={bw - 3} height={Math.max(bh, 1)} rx={2} fill={colors[gi]} opacity={0.9} />
<text x={x + (bw - 3) / 2} y={P.t + h - bh - 4} textAnchor="middle" fontSize={9.5} fill={tokens.textSub}>{v.toFixed(1)}</text>
</g>
);
})}
<text x={P.l + gw * i + gw / 2} y={H - 10} textAnchor="middle" fontSize={11} fill={tokens.textSub}>{l}</text>
</g>
))}
</svg>
<div style={{ display: 'flex', gap: 14, justifyContent: 'center', marginTop: 2 }}>
{names.map((n, i) => (
<span key={n} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 11, color: tokens.textMuted }}>
<span style={{ width: 9, height: 9, borderRadius: 2, background: colors[i] }} />{n}{unit ? `(${unit})` : ''}
</span>
))}
</div>
</div>
);
}
/** 雷达图:八维健康度 */
export function RadarChart({
axes, values, maxValue = 100, height = 260, compare,
}: { axes: string[]; values: number[]; maxValue?: number; height?: number; compare?: number[] }) {
const { tokens } = useTheme();
const S = 320, C = S / 2, R = 108;
const pt = (i: number, v: number) => {
const a = -Math.PI / 2 + (i / axes.length) * Math.PI * 2;
const r = (Math.max(0, Math.min(v, maxValue)) / maxValue) * R;
return { x: C + r * Math.cos(a), y: C + r * Math.sin(a), a };
};
const poly = (arr: number[]) => arr.map((v, i) => { const p = pt(i, v); return `${p.x},${p.y}`; }).join(' ');
return (
<svg viewBox={`0 0 ${S} ${S + 18}`} style={{ width: '100%', height, display: 'block' }}>
{[0.25, 0.5, 0.75, 1].map(f => (
<polygon
key={f}
points={axes.map((_, i) => { const p = pt(i, maxValue * f); return `${p.x},${p.y}`; }).join(' ')}
fill="none" stroke={tokens.border}
/>
))}
{axes.map((label, i) => {
const p = pt(i, maxValue);
const outer = pt(i, maxValue * 1.24);
return (
<g key={label}>
<line x1={C} y1={C} x2={p.x} y2={p.y} stroke={tokens.border} />
<text
x={outer.x} y={outer.y + 3} fontSize={11} fill={tokens.textSub}
textAnchor={outer.x > C + 6 ? 'start' : outer.x < C - 6 ? 'end' : 'middle'}
>{label}</text>
</g>
);
})}
{compare && <polygon points={poly(compare)} fill={tokens.info} fillOpacity={0.08} stroke={tokens.info} strokeWidth={1.2} strokeDasharray="4 3" />}
<polygon points={poly(values)} fill={tokens.accent} fillOpacity={0.16} stroke={tokens.accent} strokeWidth={2} />
{values.map((v, i) => { const p = pt(i, v); return <circle key={i} cx={p.x} cy={p.y} r={3} fill={tokens.accent} />; })}
</svg>
);
}
/** 风险矩阵散点 */
export function RiskMatrix({
items, height = 300, xLabel = '概率 →', yLabel = '↑ 影响',
}: {
items: { label: string; x: number; y: number; status: string; color: string }[];
height?: number; xLabel?: string; yLabel?: string;
}) {
const { tokens } = useTheme();
const S = 360, P = 34;
const w = S - P * 2;
const X = (v: number) => P + v * w;
const Y = (v: number) => S - P - v * w;
return (
<svg viewBox={`0 0 ${S} ${S}`} style={{ width: '100%', height, display: 'block', maxWidth: 420 }}>
<rect x={P} y={P} width={w / 2} height={w / 2} fill={tokens.warning} opacity={0.07} />
<rect x={P + w / 2} y={P} width={w / 2} height={w / 2} fill={tokens.danger} opacity={0.1} />
<rect x={P} y={P + w / 2} width={w / 2} height={w / 2} fill={tokens.info} opacity={0.06} />
<rect x={P + w / 2} y={P + w / 2} width={w / 2} height={w / 2} fill={tokens.warning} opacity={0.07} />
<line x1={P} x2={S - P} y1={S - P} y2={S - P} stroke={tokens.border} />
<line x1={P} x2={P} y1={P} y2={S - P} stroke={tokens.border} />
<text x={S - P} y={S - 8} textAnchor="end" fontSize={11} fill={tokens.textMuted}>{xLabel}</text>
<text x={8} y={P - 10} fontSize={11} fill={tokens.textMuted}>{yLabel}</text>
{(() => {
/**
* 点可以压在一起,字不行。两步走:同格点(同次数×同严重度)先把圆点上下错开,
* 标签再各自做一轮避让——被推离本位的标签用一条细线连回自己的点。
* 全是展示位移,不改源表读数;精确值看下方明细表。
*/
const FH = 10, LH = 16, R = 9;
const widthOf = (s: string) => Array.from(s).reduce((a, c) => a + (c.charCodeAt(0) > 0x2e80 ? FH : FH * 0.62), 0);
const buckets = new Map<string, number>();
const nodes = items.map((it, idx) => {
const key = `${it.x.toFixed(3)}|${it.y.toFixed(3)}`;
const n = buckets.get(key) ?? 0;
buckets.set(key, n + 1);
const total = items.filter(z => `${z.x.toFixed(3)}|${z.y.toFixed(3)}` === key).length;
const cx = X(it.x);
const cy = Math.min(Math.max(Y(it.y) + (n - (total - 1) / 2) * 18, P + R), S - P - R);
/** 中英文混排的实测字宽略大于估算,统一加 6 的余量,避免两轮标签贴边 */
const tw = widthOf(it.label) + 6;
const left = cx + R + 4 + tw > S - P;
const lx = left ? cx - R - 4 - tw : cx + R + 4;
return { it, idx, cx, cy, tw, left, lx, ly: cy + FH * 0.35, home: cy + FH * 0.35 };
});
for (let pass = 1; pass <= 200; pass += 1) {
/** 每轮先往本位收一点,再让位;退出条件只看"这一轮还需不需要让",保证末态不叠字 */
if (pass > 1) nodes.forEach(nd => { nd.ly += (nd.home - nd.ly) * 0.08; });
nodes.forEach(nd => { nd.ly = Math.min(Math.max(nd.ly, P + LH - 2), S - P - 2); });
let moved = false;
for (let i = 0; i < nodes.length; i += 1) {
for (let j = i + 1; j < nodes.length; j += 1) {
const a = nodes[i], b = nodes[j];
if (Math.min(a.lx + a.tw, b.lx + b.tw) - Math.max(a.lx, b.lx) < -4) continue;
const d = b.ly - a.ly;
if (Math.abs(d) >= LH) continue;
const push = (LH - Math.abs(d)) / 2 + 0.4;
const s = d >= 0 ? push : -push;
a.ly -= s; b.ly += s;
moved = true;
}
}
if (!moved) break;
}
return nodes.map(nd => {
const lifted = Math.abs(nd.ly - nd.home) > 4;
const anchorX = nd.left ? nd.lx + nd.tw : nd.lx;
return (
<g key={`${nd.it.label}-${nd.idx}`}>
{lifted && (
<path
d={`M${nd.cx + (nd.left ? -R : R)},${nd.cy} L${anchorX + (nd.left ? 2 : -2)},${nd.ly - FH * 0.35}`}
stroke={nd.it.color} strokeWidth={0.8} opacity={0.5} fill="none"
/>
)}
<circle cx={nd.cx} cy={nd.cy} r={R} fill={nd.it.color} opacity={0.85} />
<text x={anchorX} y={nd.ly} textAnchor={nd.left ? 'end' : 'start'} fontSize={FH} fill={tokens.textSub}>
{nd.it.label}
</text>
</g>
);
});
})()}
</svg>
);
}
/**
* 堆叠横向条:一个主体拆成若干分量(如一个结构特征里的四类缺陷率)。
* 条长按各段数值直接累加,右侧给出合计读数,不做归一化——归一会把「谁更差」这层信息抹掉。
*/
export function StackedBarChart({
items, height, unit = '%', onClick,
}: {
items: { key: string; label: string; total: number; display?: string; sub?: string; segs: { label: string; value: number | null; color: string }[] }[];
height?: number; unit?: string; onClick?: (key: string) => void;
}) {
const { tokens } = useTheme();
const segVal = (v: number | null) => (v != null && Number.isFinite(v) ? v : 0);
const max = Math.max(...items.map(i => i.segs.reduce((a, s) => a + segVal(s.value), 0)), 0.001);
const legend = [...new Map(items.flatMap(i => i.segs).map(s => [s.label, s.color])).entries()];
return (
<div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 7, height, justifyContent: items.length > 5 ? 'flex-start' : 'space-between' }}>
{items.map((it, idx) => {
const sum = it.segs.reduce((a, s) => a + segVal(s.value), 0);
return (
<div
key={it.key}
className="card-in"
onClick={() => onClick?.(it.key)}
style={{
display: 'flex', alignItems: 'center', gap: 8, animationDelay: `${idx * 40}ms`,
cursor: onClick ? 'pointer' : 'default',
}}
>
<span style={{ width: 152, flex: '0 0 152px', fontSize: 11.5, color: tokens.textSub, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</span>
<div style={{ flex: 1, height: 16, borderRadius: 4, background: tokens.accentBg, display: 'flex', overflow: 'hidden' }}>
{it.segs.map(s => (
s.value != null && Number.isFinite(s.value) ? (
<div
key={s.label} title={`${s.label} ${s.value.toFixed(2)}${unit}`}
style={{ width: `${(s.value / max) * 100}%`, background: s.color, opacity: 0.9, transition: 'width 0.5s cubic-bezier(0.4,0,0.2,1)' }}
/>
) : null
))}
</div>
<span style={{ width: 92, flex: '0 0 92px', textAlign: 'right', fontSize: 11.5, fontWeight: 700, color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>
{it.display ?? `${sum.toFixed(1)}${unit}`}
{it.sub && <span style={{ fontWeight: 400, color: tokens.textMuted, marginLeft: 4, fontSize: 10 }}>{it.sub}</span>}
</span>
</div>
);
})}
</div>
<div style={{ display: 'flex', gap: 12, flexWrap: 'wrap', justifyContent: 'center', marginTop: 6 }}>
{legend.map(([label, color]) => (
<span key={label} style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textMuted }}>
<span style={{ width: 9, height: 9, borderRadius: 2, background: color }} />{label}
</span>
))}
</div>
</div>
);
}
/**
* 环规(2026-11-14 动效层):弧长与中心数字由同一个 useCountUp 驱动,切日/回放时同步扫掠。
* value=百分数原值(0–100,与 L3 ×100 同源);null=缺口→空弧+「—」,不造 0。
* 终值严格等于传入值;弧只画 0–100 夹取,超界不画满圈假象。label 可选(砖内已有标签时不传)。
*/
export function RingGauge({ value, color, label, size = 56 }: {
value: number | null; color: string; label?: string; size?: number;
}) {
const { tokens } = useTheme();
const v = useCountUp(value);
const r = (size - 10) / 2;
const c = 2 * Math.PI * r;
const frac = v === null ? 0 : Math.max(0, Math.min(1, v / 100));
return (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2, minWidth: 0 }}>
<svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ display: 'block', flexShrink: 0 }}>
<circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={tokens.accentBg} strokeWidth={5} />
<circle
cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth={5} strokeLinecap="round"
strokeDasharray={c} strokeDashoffset={c * (1 - frac)}
transform={`rotate(-90 ${size / 2} ${size / 2})`}
/>
<text
x={size / 2} y={size / 2 + (size >= 52 ? 4 : 3.5)} textAnchor="middle"
fontSize={size >= 52 ? 11.5 : 9.5} fontWeight={800} fill={tokens.text}
style={{ fontVariantNumeric: 'tabular-nums' }}
>
{v === null ? '—' : v.toFixed(2)}
</text>
</svg>
{label && <span style={{ fontSize: 10, color: tokens.textMuted, whiteSpace: 'nowrap' }}>{label}</span>}
</div>
);
}
@@ -0,0 +1,282 @@
/**
* OEE 视图共用小块(W2-B)。
*
* ★ 自带一套,不 import 待废弃的品质页签模块 views.tsx(第9章第8项)。
* 与 DisclosureView 的小块同源同形,保证六个 OEE 页签看起来是同一个应用。
*
* 看板排版红线(项目记忆):
* 一行等分(Tiles flex:1)· 不溢出卡片底色(minWidth:0 + overflow)·
* 两卡底边对齐(grid alignItems:stretch + Card flex column)· 空区填满(Card 内 flex:1 spacer)。
*
* 纪律:本模块只有展示原语与配色,**不含任何业务统计数字**;
* 数字一律由视图从 L3 oeeService / data 层现算后传入。
*/
import type { CSSProperties, ReactNode } from 'react';
import { useTheme } from '../../context/ThemeContext';
import type { ThemeTokens } from '../../context/ThemeContext';
import { useCountUp } from '../../hooks/useCountUp';
import { RingGauge } from './charts';
import type { LossBucket, SegmentState, AsltTimeClass } from '../../types/oee';
import { resolveScope, type OeeFilter } from '../../lib/oeeFilters';
import { SIM_BADGE, dataModeNote } from '../../data/oee/disclosure';
/* ── 数值格式化:全站统一,视图不得各自 toFixed 出不同位数 ────────────── */
/** 比例(0–1) → 百分数字符串。与 resultMetrics / metricTree 同口径(×100 保留两位)。 */
export const pct = (x: number, digits = 2): string => (x * 100).toFixed(digits);
/** G 缺口安全格式化:null/undefined/NaN → 「—」(不补 0/100% 冒充);0 是合法值照常显示。
* note(缺口原因)由 call site 作 title/签展示,本函数只负责读数。 */
export const pctOrGap = (v: number | null | undefined, _note?: string): string =>
(v == null || !Number.isFinite(v) ? '—' : pct(v));
/** 带 % 单位的读数:缺口渲染裸「—」,不拼成「—%」被误读为有单位的数据 */
export const pctUnitOrGap = (v: number | null | undefined): string =>
(v == null || !Number.isFinite(v) ? '—' : `${pct(v)}%`);
/** 秒 → 小时(两位) */
export const hrs = (sec: number): string => (sec / 3600).toFixed(2);
/** 秒 → 分钟(一位) */
export const mins = (sec: number): string => (sec / 60).toFixed(1);
/** 秒 → 紧凑时长:≥1h 用 h,否则 min,再否则 s */
export const dur = (sec: number): string =>
sec >= 3600 ? `${(sec / 3600).toFixed(2)}h` : sec >= 60 ? `${(sec / 60).toFixed(1)}min` : `${Math.round(sec)}s`;
/** 数量千分位 */
export const qty = (n: number): string => n.toLocaleString('en-US');
/* ── 分类配色:十态 / 六桶 / 六-2。类别色用固定调色板(浅深底皆可读),
语义色(文字/边框/底)仍走主题令牌。 ─────────────────────────────── */
export const STATE_COLORS: Record<SegmentState, string> = {
PLAN_STOP: '#94a3b8',
PM: '#22d3ee',
DOWN: '#f87171',
JAM: '#fbbf24',
WAIT_MAT: '#fb923c',
WAIT_UNLOAD: '#f59e0b',
WAIT_PERSON: '#a78bfa',
CHANGE: '#38bdf8',
RUN: '#34d399',
IDLE: '#64748b',
UNKNOWN: '#475569',
};
export const BUCKET_COLORS: Record<LossBucket, string> = {
FAULT: '#f87171',
CHANGEOVER: '#fb923c',
IDLE_MINOR: '#fbbf24',
SPEED: '#38bdf8',
PROCESS_DEFECT: '#a78bfa',
STARTUP_DEFECT: '#f472b6',
};
export const FACTOR_COLORS: Record<'A' | 'P' | 'Q', string> = {
A: '#f87171', P: '#38bdf8', Q: '#a78bfa',
};
export const ASLT_CLASS_COLORS: Record<AsltTimeClass, string> = {
WAIT: '#fb923c', PLAN: '#94a3b8', OCC: '#34d399',
ENG: '#22d3ee', STOP: '#f87171', STANDBY: '#64748b',
};
/* ── 基础小块 ───────────────────────────────────────────────────────── */
export function Chip({ children, color, bg, title }: { children: ReactNode; color: string; bg?: string; title?: string }) {
return (
<span title={title} style={{
fontSize: 10, fontWeight: 700, padding: '1px 7px', borderRadius: 9, whiteSpace: 'nowrap',
color, background: bg ?? `${color}1f`, border: `1px solid ${color}44`, letterSpacing: '0.02em',
}}>{children}</span>
);
}
export function Card({ title, icon, right, children, note, full, tone }: {
title: string; icon?: ReactNode; right?: ReactNode; children: ReactNode;
note?: ReactNode; full?: boolean; tone?: string;
}) {
const { tokens } = useTheme();
return (
<section className="card-in" style={{
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 11,
padding: '10px 13px 12px', boxShadow: tokens.cardShadow, minWidth: 0,
gridColumn: full ? '1 / -1' : undefined, display: 'flex', flexDirection: 'column',
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, flexShrink: 0 }}>
<span style={{ width: 3, height: 13, borderRadius: 2, background: tone ?? tokens.accent, flexShrink: 0 }} />
{icon}
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text, whiteSpace: 'nowrap' }}>{title}</span>
<span style={{ flex: 1 }} />
{right}
</div>
{/* minHeight:0 是红线「不溢出卡片底色」的 kit 级保证:缺它时 flex:1 的 min-height:auto
会把内容高度顶穿卡片边框(内部 overflow:auto 的滚动块随之失效)。 */}
<div style={{ minWidth: 0, minHeight: 0, flex: 1, display: 'flex', flexDirection: 'column' }}>{children}</div>
{note && <div style={{ marginTop: 7, fontSize: 10.5, lineHeight: 1.55, color: tokens.textMuted, flexShrink: 0 }}>{note}</div>}
</section>
);
}
export function Th({ children, right, minW, wrap }: { children: ReactNode; right?: boolean; minW?: number; wrap?: boolean }) {
const { tokens } = useTheme();
return (
<th style={{
textAlign: right ? 'right' : 'left', padding: '6px 8px', fontSize: 11, fontWeight: 600, minWidth: minW,
color: tokens.textSub, background: tokens.tableHeaderBg, whiteSpace: wrap ? 'normal' : 'nowrap',
borderBottom: `1px solid ${tokens.border}`, position: 'sticky', top: 0, zIndex: 1,
}}>{children}</th>
);
}
export function Td({ children, right, mono, color, bold, nowrap, breakAny }: {
children: ReactNode; right?: boolean; mono?: boolean; color?: string; bold?: boolean; nowrap?: boolean;
/** 长公式/路径列:允许任意处折行,避免表格被不可断词撑出卡片 */
breakAny?: boolean;
}) {
const { tokens } = useTheme();
return (
<td style={{
textAlign: right ? 'right' : 'left', padding: '5px 8px', fontSize: 11.5,
color: color ?? tokens.textSub, borderBottom: `1px solid ${tokens.borderSub}`,
fontVariantNumeric: mono ? 'tabular-nums' : undefined,
fontFamily: mono ? 'ui-monospace, monospace' : undefined,
fontWeight: bold ? 700 : undefined, verticalAlign: 'top', lineHeight: 1.5,
whiteSpace: nowrap ? 'nowrap' : undefined,
overflowWrap: breakAny ? 'anywhere' : undefined,
}}>{children}</td>
);
}
export function Table({ head, children, maxHeight }: { head: ReactNode; children: ReactNode; maxHeight?: number }) {
const { tokens } = useTheme();
return (
<div style={{ overflow: 'auto', maxHeight, border: `1px solid ${tokens.borderSub}`, borderRadius: 8 }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead><tr>{head}</tr></thead>
<tbody>{children}</tbody>
</table>
</div>
);
}
/** 一行等分的统计砖(看板红线:等分、stretch、底边对齐)。
* 2026-11-14 动效层:roll=数字滚动(raw 与 value 同源 L3,终值落回 value 同串);
* ring=环规砖(弧长与中心数字同 rAF 扫掠);hoverLift 仅总览传入,避免跨页签漂移。 */
export interface TileItem {
label: string; value: string; sub?: string; color?: string; title?: string;
roll?: { raw: number | null; digits?: number; suffix?: string };
ring?: boolean;
}
export function Tiles({ items, hoverLift }: { items: TileItem[]; hoverLift?: boolean }) {
const { tokens } = useTheme();
return (
<div style={{ display: 'flex', alignItems: 'stretch', gap: 8 }}>
{items.map((it) => <TileBox key={it.label} it={it} tokens={tokens} hoverLift={hoverLift} />)}
</div>
);
}
function TileBox({ it, tokens, hoverLift }: { it: TileItem; tokens: ThemeTokens; hoverLift?: boolean }) {
const rolled = useCountUp(it.roll ? it.roll.raw : null);
const text = it.roll
? (rolled === null ? it.value : `${rolled.toFixed(it.roll.digits ?? 2)}${it.roll.suffix ?? ''}`)
: it.value;
return (
<div title={it.title} className={hoverLift ? 'tile-lift' : undefined} style={{
flex: 1, minWidth: 0, textAlign: 'center', padding: '6px 8px', borderRadius: 9,
background: tokens.kpiCardBg, border: `1px solid ${tokens.kpiCardBorder}`,
display: 'flex', flexDirection: 'column', justifyContent: 'center',
}}>
<div style={{ fontSize: 10.5, color: tokens.textSub, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.label}</div>
{it.ring && it.roll ? (
<div style={{ display: 'flex', justifyContent: 'center', padding: '2px 0' }}>
<RingGauge value={it.roll.raw} color={it.color ?? tokens.text} size={44} />
</div>
) : (
<div style={{ fontSize: 19, fontWeight: 800, color: it.color ?? tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.25 }}>{text}</div>
)}
{it.sub && <div style={{ fontSize: 9.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.sub}</div>}
</div>
);
}
export function Note({ children }: { children: ReactNode }) {
const { tokens } = useTheme();
return <div style={{ marginTop: 7, fontSize: 10.5, lineHeight: 1.55, color: tokens.textMuted }}>{children}</div>;
}
/** 数据缺口盒:标灰不标绿,四件披露齐备(缺什么/依赖谁/何时做实/为什么不能替代)。 */
export function GapBox({ missing, dependsOn, stage, note }: { missing: string; dependsOn: string; stage: string; note: string }) {
const { tokens } = useTheme();
return (
<div style={{
padding: '7px 9px', borderRadius: 9, minWidth: 0,
background: tokens.panelBgAlt, border: `1px dashed ${tokens.border}`,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 3 }}>
<Chip color={tokens.textMuted}>数据缺口</Chip>
<span style={{ fontSize: 11, fontWeight: 700, color: tokens.textSub }}>{missing}</span>
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.55 }}>
依赖:{dependsOn}|做实:{stage}
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, lineHeight: 1.55, marginTop: 2 }}>{note}</div>
</div>
);
}
/** 诚实空态:未接入范围不显示 0(0 会被误读为"当天没有损失")。 */
export function EmptyBox({ children }: { children: ReactNode }) {
const { tokens } = useTheme();
return (
<div style={{
flex: 1, minHeight: 80, display: 'flex', alignItems: 'center', justifyContent: 'center',
textAlign: 'center', padding: '14px 16px', borderRadius: 9,
background: tokens.panelBgAlt, border: `1px dashed ${tokens.border}`,
color: tokens.textMuted, fontSize: 11.5, lineHeight: 1.6,
}}>{children}</div>
);
}
/**
* 页抬头:与顶栏同源的范围/口径/业务日标签(resolveScope),不另存一份。
* 未接入范围把缺口写在脸上,绝不拿单机值冒充聚合值。
*/
export function ScopeBar({ filter, title, icon, extra }: {
filter: OeeFilter; title: string; icon?: ReactNode; extra?: ReactNode;
}) {
const { tokens } = useTheme();
const scope = resolveScope(filter);
return (
<div style={{
display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap',
padding: '9px 12px', borderRadius: 11,
background: tokens.accentBg, border: `1px solid ${tokens.borderAccent}`,
}}>
{icon}
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text }}>{title}</span>
<Chip color={tokens.textMuted} title={dataModeNote()}>{SIM_BADGE}</Chip>
<Chip color={tokens.textSub}>业务日 {scope.bizDate}</Chip>
<Chip color={scope.wired ? tokens.textSub : tokens.warning} title={scope.gap ?? scope.coverageNote}>
{scope.scopeLabel}
</Chip>
{scope.shiftLabel && <Chip color={tokens.info} title={scope.shiftNote ?? undefined}>{scope.shiftLabel}</Chip>}
<span style={{ flex: 1 }} />
{extra}
</div>
);
}
/** 两列等分网格(看板红线:stretch 底边对齐)。 */
export const grid2: CSSProperties = {
display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr)', gap: 10, alignItems: 'stretch',
};
/** 三列等分网格(看板红线:一行等分 + stretch 底边对齐)。三区域 Q 并列对照用。 */
export const grid3: CSSProperties = {
display: 'grid', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr) minmax(0,1fr)', gap: 10, alignItems: 'stretch',
};
/** 主从两列(左宽右窄)。 */
export const gridMain = (side: number): CSSProperties => ({
display: 'grid', gridTemplateColumns: `minmax(0,1fr) ${side}px`, gap: 10, alignItems: 'stretch',
});
/** 页容器:纵向卡片流。 */
export const pageStyle: CSSProperties = { display: 'flex', flexDirection: 'column', gap: 10, minWidth: 0 };
/** 主题令牌再导出,方便视图按同一套令牌渲染。 */
export type OeeTokens = ThemeTokens;
@@ -0,0 +1,926 @@
import type { ReactNode } from 'react';
import { AlertTriangle, ChevronRight } from 'lucide-react';
import { useTheme } from '../../context/ThemeContext';
import type { ThemeTokens } from '../../context/ThemeContext';
import type { MetricLink, MetricNode } from '../../data/sqlite';
import {
DEFECT_COLUMNS, DEFAULT_METRIC, METRICS, SEVERITY_WEIGHT,
defectByProcess, defectPareto, driftRows, duplicateHits, masterModel, methodCompareRows,
predictionRows, riskChecklistRows, riskPoints, rootCauseGroups, severityCount, watchList,
type DetailTable, type QualityMetric, type Status,
} from '../../lib/qualityMetrics';
import {
abnormalModelsAt, cockpitTilesAt, coverageModelAt, doeModelAt, featureModelsAt,
lineModelsAt, metricAt, overallDefectRateAt, radarModelAt, REPLAY_DETAIL_NOTE,
stationModelsAt, trendModelAt, yieldPctAt, defectPctAt,
} from '../../lib/replayQuality';
import { CURRENT_PERIOD, periodLabel } from '../../lib/oeeTime';
import { replayTag } from '../../lib/replay';
import { QAP_CALIBER, calc } from '../../data/qap';
import { alertKindLabel, type AlertKind } from '../../lib/qualityAlerts';
import { HBarChart, RadarChart, RiskMatrix, StackedBarChart, TrendChart, VBarChart } from './charts';
/** 保留给 App / 图谱 / 时间轴的旧指标树契约,六个可视化页签不再消费它 */
export interface ViewProps {
selected: string;
byCode: Map<string, MetricNode>;
flat: MetricNode[];
links: MetricLink[];
onSelect: (code: string) => void;
}
/** 可视化页签的契约:当前主体(品质指标编码)+ 下钻回调+全局回放游标 */
export interface VizProps {
subject: string;
onOpen: (code: string) => void;
/** 0-11:2025-11 → 2026-10;11 为源表当期 */
period: number;
}
/** 期次标记:当期显示源表快照,历史期显示回放推算 */
function PeriodTag({ period }: { period: number }) {
return <SnapshotTag label={period === CURRENT_PERIOD ? '源表现算快照' : `${replayTag(period)} · 源表反推`} />;
}
/* ══════════════════ 公共小块 ══════════════════ */
export const statusColor = (s: Status, tk: ThemeTokens): string =>
s === 'red' ? tk.danger : s === 'yellow' ? tk.warning : s === 'green' ? tk.success : tk.textMuted;
const STATUS_LABEL: Record<Status, string> = { red: '红档', yellow: '黄档', green: '达标', na: '源表未设判定线' };
function StatusChip({ status }: { status: Status }) {
const { tokens } = useTheme();
const c = statusColor(status, tokens);
return (
<span style={{
fontSize: 11, padding: '1px 8px', borderRadius: 9, fontWeight: 700, whiteSpace: 'nowrap',
background: `${c}1f`, color: c, border: `1px solid ${c}44`,
}}>{STATUS_LABEL[status]}</span>
);
}
/** 源表快照标记:本页读数由数据集现算,与底部时间轴无关 */
function SnapshotTag({ label = '源表现算快照' }: { label?: string }) {
const { tokens } = useTheme();
return (
<span style={{
fontSize: 10.5, color: tokens.textMuted, background: tokens.tableHeaderBg,
border: `1px solid ${tokens.border}`, borderRadius: 5, padding: '1px 6px', whiteSpace: 'nowrap',
}}>{label}</span>
);
}
export function Card({ title, right, children, tone, full }: {
title: string; right?: ReactNode; children: ReactNode; tone?: string; full?: boolean;
}) {
const { tokens } = useTheme();
return (
<div className="card-in" style={{
background: tokens.cardBg, border: `1px solid ${tokens.border}`, borderRadius: 11,
padding: '10px 13px 12px', boxShadow: tokens.cardShadow, minWidth: 0,
gridColumn: full ? '1 / -1' : undefined,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
<span style={{ width: 3, height: 13, borderRadius: 2, background: tone ?? tokens.accent }} />
<span style={{ fontSize: 12.5, fontWeight: 700, color: tokens.text }}>{title}</span>
<span style={{ flex: 1 }} />
{right}
</div>
{children}
</div>
);
}
function Th({ children, right }: { children: ReactNode; right?: boolean }) {
const { tokens } = useTheme();
return (
<th style={{
textAlign: right ? 'right' : 'left', padding: '6px 8px', fontSize: 11, fontWeight: 600,
color: tokens.textSub, background: tokens.tableHeaderBg, whiteSpace: 'nowrap',
borderBottom: `1px solid ${tokens.border}`,
}}>{children}</th>
);
}
function Td({ children, right, mono, color }: { children: ReactNode; right?: boolean; mono?: boolean; color?: string }) {
const { tokens } = useTheme();
return (
<td style={{
textAlign: right ? 'right' : 'left', padding: '5px 8px', fontSize: 11.5,
color: color ?? tokens.textSub, borderBottom: `1px solid ${tokens.borderSub}`,
fontVariantNumeric: mono ? 'tabular-nums' : undefined,
fontFamily: mono ? 'ui-monospace, monospace' : undefined,
}}>{children}</td>
);
}
/** 一句口径说明,放在卡片底部,避免图上数字与原表口径各说各话 */
function Note({ children }: { children: ReactNode }) {
const { tokens } = useTheme();
return <div style={{ marginTop: 7, fontSize: 10.5, lineHeight: 1.5, color: tokens.textMuted }}>{children}</div>;
}
const cellText = (v: unknown) => (v === null || v === undefined || v === '' ? '—' : String(v));
/**
* 明细表:列名里带「现算」的表头标出来,提醒这不是源表原有列;
* focus 命中的行高亮,作为从柱子下钻过来的落点。
*/
function DataTable({ table, max = 99 }: { table: DetailTable; max?: number }) {
const { tokens } = useTheme();
const rows = table.rows.slice(0, max);
return (
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead><tr>
{table.columns.map(c => (
<Th key={c} right={/^[\d.,%()-]+$/.test(cellText(table.rows[0]?.[c]))}>
{c}
{c.includes('现算') && <span style={{ color: tokens.accent, marginLeft: 3, fontSize: 9.5 }}>◆</span>}
</Th>
))}
</tr></thead>
<tbody>
{rows.map((r, i) => {
const focused = !!table.focus && cellText(r[table.focus.column]) === table.focus.value;
return (
<tr key={i} style={{
background: focused ? tokens.accentBg : i % 2 ? tokens.tableRowAlt : 'transparent',
boxShadow: focused ? `inset 3px 0 0 ${tokens.accent}` : undefined,
}}>
{table.columns.map(c => {
const raw = r[c];
const numeric = typeof raw === 'number';
return (
<Td key={c} mono={numeric} right={numeric} color={focused ? tokens.text : undefined}>
{cellText(raw)}
</Td>
);
})}
</tr>
);
})}
</tbody>
</table>
{table.rows.length > rows.length && (
<Note>共 {table.rows.length} 行,此处显示前 {rows.length} 行。</Note>
)}
</div>
);
}
/** 严重度 → 展示色(字典与检查表共用) */
const severityColor = (s: string, tk: ThemeTokens) =>
s === '致命' ? tk.danger : s === '严重' ? tk.warning : tk.info;
/** 缺陷四类配色:与 DS-09 列序一致,堆叠条与图例复用 */
const DEFECT_COLORS = (tk: ThemeTokens) => [tk.accent, tk.danger, tk.warning, tk.info];
/* ══════════════════ 1. 全景驾驶舱 ══════════════════ */
/** 告警类型 → 品质指标脊里的对应读数,点关注清单就落到那张明细卡 */
const KIND_TO_METRIC: Record<AlertKind, string> = {
abnormal: 'ALERT-POOL', drift: 'DRIFT-CURD', bottleneck: 'LOAD-MAX', gap: 'STD-GAP',
};
export function CockpitView({ onOpen, period }: VizProps) {
const { tokens } = useTheme();
const radar = radarModelAt(period);
const tiles = cockpitTilesAt(period);
const watch = watchList();
const levelColor = (l: string) => (l === 'red' ? tokens.danger : l === 'orange' ? tokens.warning : tokens.info);
return (
<div style={{ display: 'grid', gridTemplateColumns: '330px 1fr', gap: 12, alignItems: 'start' }}>
<Card
title="结构特征良率雷达"
right={<PeriodTag period={period} />}
tone={tokens.accent}
>
<RadarBlock radar={radar} onOpen={onOpen} />
<Note>
六轴=DS-09 六类结构特征的综合良率(100 − 四类缺陷率之和,现算);虚线=基准轴 {radar.baselineLabel}。
多边形越瘪的那一角就是当下最该防的结构。
</Note>
</Card>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
<Card title={`品质核心读数 · ${tiles.length}`} right={<PeriodTag period={period} />}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))', gap: 8 }}>
{tiles.map((tile, i) => {
const c = statusColor(tile.status, tokens);
return (
<button
key={tile.code}
onClick={() => onOpen(tile.code)}
className="card-in ghost-btn"
style={{
animationDelay: `${i * 18}ms`, textAlign: 'left', cursor: 'pointer', padding: '7px 9px',
borderRadius: 9, background: tokens.panelBgAlt,
border: `1px solid ${tile.status === 'na' ? tokens.border : `${c}55`}`,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
<span style={{
width: 6, height: 6, borderRadius: 6, flex: '0 0 6px',
background: tile.status === 'na' ? tokens.borderAccent : c,
}} />
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{tile.label}</span>
</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 3, marginTop: 2 }}>
<span style={{ fontSize: 20, fontWeight: 800, color: tokens.text, fontVariantNumeric: 'tabular-nums', lineHeight: 1.3 }}>{tile.value}</span>
<span style={{ fontSize: 10, color: tokens.textMuted }}>{tile.unit}</span>
<span style={{ flex: 1 }} />
<span style={{ fontSize: 9.5, color: tokens.accent, fontFamily: 'ui-monospace, monospace' }}>{tile.ds}</span>
</div>
<div style={{ fontSize: 10, color: tokens.textMuted, marginTop: 2, lineHeight: 1.4, whiteSpace: 'normal' }}>{tile.sub}</div>
</button>
);
})}
</div>
<Note>
八块读数随底部回放同轴:当期取源表快照,历史期由 2026-10 快照按统一质量曲线回推,切换时点可见缺陷率、良率、负荷与告警量的时空迁移。
每块读数各自回到自己的数据集;点任意一块 → 「指标明细」页签看判定线、口径与源表明细。
</Note>
</Card>
<Card title={`当前关注 · Top ${watch.length}`} tone={tokens.warning} right={<SnapshotTag label="源表当期告警队列" />}>
{watch.map((a, i) => {
const c = levelColor(a.level);
return (
<div
key={a.id}
onClick={() => onOpen(KIND_TO_METRIC[a.kind])}
className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 6px', borderRadius: 6, cursor: 'pointer' }}
>
<AlertTriangle size={12} style={{ color: c, flex: '0 0 12px' }} />
<span style={{ fontSize: 10, padding: '0 5px', borderRadius: 5, background: `${c}1f`, color: c, fontWeight: 700, flex: '0 0 auto' }}>{alertKindLabel(a.kind)}</span>
<span style={{ fontSize: 11.5, color: tokens.text, width: 130, flex: '0 0 130px', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.title}</span>
<span style={{ fontSize: 11, color: tokens.textMuted, flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{a.subject} · {a.action}
</span>
<span style={{ fontSize: 11.5, color: c, fontVariantNumeric: 'tabular-nums', fontWeight: 700, whiteSpace: 'nowrap' }}>
{a.metric.label} {a.metric.value}
</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted, whiteSpace: 'nowrap' }}>{a.owner || a.role}</span>
{i === 0 && <span style={{ fontSize: 9.5, color: tokens.onAccent, background: c, borderRadius: 6, padding: '0 5px' }}>TOP</span>}
</div>
);
})}
<Note>队列按「先分档再分类型」排:滞留天数、偏移率、负荷率三个量纲不跨类型硬比,避免排出假次序。</Note>
</Card>
</div>
</div>
);
}
/** 雷达:良率刻度从 60% 起才看得出差异,直接 0 起会让六边形糊成一团 */
function RadarBlock({ radar, onOpen }: { radar: ReturnType<typeof radarModelAt>; onOpen: (code: string) => void }) {
const { tokens } = useTheme();
const min = 60;
const scaled = radar.values.map(v => Math.max(0, ((v - min) / (100 - min)) * 100));
const compare = radar.compare.map(v => Math.max(0, ((v - min) / (100 - min)) * 100));
return (
<div>
<RadarChart axes={radar.axes} values={scaled} compare={compare} height={311} />
<div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginTop: 2 }}>
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textSub }}>
<span style={{ width: 12, height: 2.5, background: tokens.accent, borderRadius: 2 }} />六类特征综合良率
</span>
<span style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10.5, color: tokens.textSub }}>
<span style={{ width: 12, height: 2.5, background: tokens.info, borderRadius: 2, opacity: 0.7 }} />基准平板拼焊
</span>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 5, marginTop: 8, justifyContent: 'center' }}>
{radar.axes.map((axis, i) => (
<button
key={axis}
onClick={() => onOpen(radar.codes[i])}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 4, padding: '2px 7px', borderRadius: 7, cursor: 'pointer',
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, fontSize: 10.5, color: tokens.textSub,
}}
>
{axis}
<b style={{ color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>{radar.values[i].toFixed(1)}%</b>
</button>
))}
</div>
<Note>刻度自 {min}% 起放大差异;点任一轴签看该特征的四类缺陷拆分与样本数。</Note>
</div>
);
}
/* ══════════════════ 2. 趋势分析 ══════════════════ */
export function TrendView({ onOpen, period }: VizProps) {
const { tokens } = useTheme();
const trend = trendModelAt(period);
const main = trend.main;
const singles = trend.all.filter(s => s.values.length === 1);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{main && (
<Card title={`关键参数漂移 · ${main.device} ${main.param}`} right={<PeriodTag period={period} />}>
<TrendChart
height={210}
labels={main.dates}
series={[{ name: `${main.param}实测均值(${main.unit})`, color: tokens.accent, values: main.values }]}
band={main.tolLow !== null && main.tolHigh !== null
? [{ lo: main.tolLow, hi: main.tolHigh, label: `允差 ${main.tolText}` }] : undefined}
refs={main.std !== null ? [{ v: main.std, label: `标准值 ${main.std}${main.unit}` }] : undefined}
marker={main.values.length - 1}
yDigits={0}
/>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap', marginTop: 6 }}>
<StatusChip status={/^超差/.test(main.latestStatus) ? 'red' : /^预警/.test(main.latestStatus) ? 'yellow' : 'green'} />
<span style={{ fontSize: 11.5, color: tokens.textSub }}>状态「{main.latestStatus}」· 处理动作「{main.latestAction}」</span>
<button onClick={() => onOpen('DRIFT-CURD')} className="ghost-btn" style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: tokens.accent, cursor: 'pointer', background: 'transparent' }}>
看超差读数 <ChevronRight size={12} />
</button>
</div>
<Note>
{period === CURRENT_PERIOD ? '' : `回放期 ${periodLabel(period)}:日期窗随游标平移到该月,偏移量与同步缺陷率按统一曲线回推。`}
五日实测 {main.values[0]} → {main.values[main.values.length - 1]}{main.unit},允差带({main.tolLow}–{main.tolHigh}),状态按回放后的偏移率重新判定。
偏移率 =(实测均值 − 标准值)÷ 标准值,现算 {main.driftLatest === null ? '—' : `${main.driftLatest.toFixed(2)}%`}。
</Note>
</Card>
)}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'start' }}>
{main && (
<Card title="同步缺陷率同轴对比" tone={tokens.danger} right={<PeriodTag period={period} />}>
<TrendChart
height={196}
labels={main.dates}
series={[{ name: '同步缺陷率(%)', color: tokens.danger, values: main.defects }]}
marker={main.defects.length - 1}
/>
<div style={{ fontSize: 11.5, color: tokens.textSub, marginTop: 4 }}>
功率 −{Math.abs(main.values[0] - main.values[main.values.length - 1]).toFixed(1)}W 的同时缺陷率 {main.defects[0]}% → {main.defects[main.defects.length - 1]}%;
两条序列的皮尔逊相关系数 <b style={{ color: tokens.danger }}>{trend.corr ?? '—'}</b>
</div>
<Note>相关系数为负即「功率越低、缺陷越多」,这条曲线是把参数漂移翻译成质量后果的那一环。</Note>
</Card>
)}
<Card title={`监控状态分布 · ${trend.monitored} 条序列`} tone={tokens.warning}>
<HBarChart
height={170}
items={trend.counts.filter(c => c.n > 0).map(c => ({
label: c.label,
value: c.n,
color: c.label === '超差' ? tokens.danger : c.label === '预警' ? tokens.warning : c.label === '正常' ? tokens.success : tokens.info,
display: `${c.n} 条`,
}))}
/>
<div style={{ display: 'flex', flexDirection: 'column', gap: 5, marginTop: 6 }}>
{singles.map(s => (
<div key={`${s.device}-${s.param}`} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11, color: tokens.textSub }}>
<span style={{ width: 7, height: 7, borderRadius: 7, flex: '0 0 7px', background: /^超差/.test(s.latestStatus) ? tokens.danger : /^预警|注意|临近/.test(s.latestStatus) ? tokens.warning : tokens.success }} />
<span style={{ flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.device} {s.param}</span>
<span style={{ fontVariantNumeric: 'tabular-nums', color: tokens.text }}>{s.values[0]}{s.unit}</span>
<span style={{ color: tokens.textMuted }}>/标准 {s.stdText}{/^-?\d/.test(s.stdText) ? s.unit : ''}</span>
<span style={{ color: tokens.textMuted }}>{s.latestStatus}</span>
</div>
))}
</div>
<Note>{trend.sequenceCount} 条参数配到多日监控,其余 {singles.length} 条为单日快照;单日快照不构成趋势,列在下方明细表里。</Note>
</Card>
</div>
<Card title="DS-16 参数漂移监控明细" right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>偏移率现算 · 明细为源表 2026-10 当期</span>}>
<DataTable table={{ tableKey: 'DS-16', title: 'DS-16', columns: ['日期', '设备', '参数', '标准值', '实测均值', '单位', '偏移率%(现算)', '允许偏差', '同步缺陷率%', '状态', '处理动作'], rows: driftRows() }} />
</Card>
</div>
);
}
/* ══════════════════ 3. 结构动因 ══════════════════ */
export function StructureView({ onOpen, period }: VizProps) {
const { tokens } = useTheme();
const feats = featureModelsAt(period);
const pareto = defectPareto();
const causes = rootCauseGroups();
const dup = duplicateHits();
const doe = doeModelAt(period);
const factors = [...doe.factors].sort((a, b) => b.spread - a.spread);
/** 焊速是极差最弱那根:推荐组合与按极差挑出的最优水平不一致,要在文案里点明 */
const speed = doe.factors.find(f => f.column === '焊速(mm/s)') ?? factors[factors.length - 1];
const speedBest = speed.levels.reduce((bi, l, li) => (l.meanYield > speed.levels[bi].meanYield ? li : bi), 0);
const sev = severityCount();
const byProcess = defectByProcess();
const colors = DEFECT_COLORS(tokens);
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Card
title="结构特征 × 四类缺陷率"
full
right={<PeriodTag period={period} />}
>
<StackedBarChart
height={186}
items={feats.map(f => ({
key: f.code,
label: f.label,
total: f.defect,
display: `${f.defect.toFixed(1)}%`,
sub: `n=${f.samples.toLocaleString('en-US')}`,
segs: f.parts.map((p, i) => ({ label: DEFECT_COLUMNS[i], value: p, color: colors[i] })),
}))}
onClick={code => onOpen(code)}
/>
<Note>
{period === CURRENT_PERIOD ? '' : `${periodLabel(period)} 回放:四类缺陷率按统一质量曲线回推,条长仍由四段累加。`}
全厂样本加权综合不良率 <b style={{ color: tokens.text }}>{overallDefectRateAt(period, feats).toFixed(1)}%</b>;
基准平板拼焊 {feats.find(f => /基准/.test(f.conclusion))?.defect.toFixed(1) ?? '—'}% 是这六类里最稳的一档。
点任意一条 → 该结构的明细与结论。
</Note>
</Card>
{/* Pareto 独占左列;右侧两张小卡上下堆叠,并把图表各拉高一点补齐到 Pareto 的高度 */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'start' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
<Card title="缺陷占比 Pareto(DS-03)" right={<SnapshotTag label="近3月构成 · 源表当期" />}>
<HBarChart
items={pareto.map(d => ({
label: d.name,
value: d.share,
color: severityColor(d.severity, tokens),
display: `${d.share.toFixed(1)}%`,
sub: `累计${d.cum.toFixed(0)}%`,
}))}
/>
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', marginTop: 6 }}>
{sev.map(s => (
<button key={s.label} onClick={() => onOpen(`DS03:${pareto.find(p => p.severity === s.label)?.defectCode ?? ''}`)} className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: tokens.textSub, cursor: 'pointer', background: 'transparent' }}>
<span style={{ width: 8, height: 8, borderRadius: 2, background: severityColor(s.label, tokens) }} />
{s.label}档 {s.n} 个码 · 占 {s.share.toFixed(1)}%
</button>
))}
</div>
<Note>占比取原表「近3月占比」列(比率 ×100),合计为字典内 11 个缺陷码之和,不是全数;累计列按降序现算。点档位药签看该档最高频缺陷码的明细。</Note>
</Card>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
<Card title="不良按工序归并" tone={tokens.info}>
<HBarChart
height={176}
items={byProcess.map(p => ({
label: p.label, value: p.share, color: tokens.accent,
display: `${p.share.toFixed(1)}%`, sub: `${p.codes} 个码`,
}))}
/>
<Note>同一本字典按「所属工序」汇总,看得出不合格集中在哪一段工艺:焊接段码数最多。</Note>
</Card>
<Card title="8D 根因类别(DS-11)" tone={tokens.warning} right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>重复拦截命中 {dup.length}/6</span>}>
<HBarChart
height={117}
items={causes.map((g, i) => ({
label: g.label, value: g.n,
color: i === 0 ? tokens.danger : tokens.accent,
display: `${g.n} 件`, sub: g.items.join(' '),
}))}
/>
<Note>
拦截口径:相似度 &gt; 0.85 判为重复问题(原表列值)。命中 {dup.length} 件里最高 {dup[0].相似度}({dup[0]['8D编号']}),
说明根因没有沉淀成标准,同一类问题在不同客户重复开单。
</Note>
</Card>
</div>
</div>
<Card title="激光焊 DOE 主效应(DS-12 L9)" full right={<PeriodTag period={period} />}>
<div style={{ display: 'grid', gridTemplateColumns: '0.9fr 1.6fr', gap: 12, alignItems: 'start' }}>
<div>
<HBarChart
items={factors.map((f, i) => ({
label: `${f.label}(${f.unit})`,
value: f.spread,
color: i === 0 ? tokens.danger : tokens.accent,
display: `${f.spread.toFixed(2)}pt`,
sub: `${f.levels.length} 水平`,
}))}
/>
<Note>极差=该因子各水平均值良率的最高 − 最低,就是它对良率的动因强度;红色是最强那根。</Note>
</div>
<div style={{ overflowX: 'auto' }}>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead><tr><Th>因子</Th>{[0, 1, 2].map(i => <Th key={i} right>水平{i + 1}</Th>)}<Th right>极差(pt)</Th><Th>推荐</Th></tr></thead>
<tbody>
{factors.map((f, i) => {
const best = f.levels.reduce((bi, l, li) => (l.meanYield > f.levels[bi].meanYield ? li : bi), 0);
return (
<tr key={f.column} style={{ background: i % 2 ? tokens.tableRowAlt : 'transparent' }}>
<Td><span style={{ color: tokens.text }}>{f.label}</span></Td>
{f.levels.map(l => <Td key={l.level} right mono>{l.meanYield.toFixed(1)}</Td>)}
{f.levels.length < 3 && [0, 1, 2].slice(f.levels.length).map(k => <Td key={k} right mono>—</Td>)}
<Td right mono color={i === 0 ? tokens.danger : tokens.textSub}>{f.spread.toFixed(2)}</Td>
<Td mono>{f.levels[best].level}{f.unit}</Td>
</tr>
);
})}
</tbody>
</table>
<Note>
三水平均值良率同表对照;最优组合落在试验 {doe.best.试验号}(综合良率 {yieldPctAt(+((calc.yieldRate(doe.best) || 0) * 100).toFixed(1), period).toFixed(1)}%,
功率 {doe.best['激光功率(W)']}W/保护气 {doe.best['保护气(L/min)']}L/焊速 {doe.best['焊速(mm/s)']}mm·s⁻¹),
最差试验 {doe.worst.试验号}({yieldPctAt(+((calc.yieldRate(doe.worst) || 0) * 100).toFixed(1), period).toFixed(1)}%,功率降到 {doe.worst['激光功率(W)']}W 时未焊透率抬到 {(doe.worst.未焊透率 * 100).toFixed(0)}%)。
原表「标记」列把试验 {doe.marked[0]?.试验号 ?? doe.best.试验号} 定为推荐组合。
有一处不一致要说清楚:按极差挑出的最优焊速是 {speed.levels[speedBest].level}mm/s,而推荐那组用的是 {doe.best['焊速(mm/s)']}mm/s——
焊速极差只有 {speed.spread.toFixed(2)}pt,是四个因子里最弱的一根,落在试验 {doe.best.试验号} 的参数窗口内即可,不必为它另开一轮。
</Note>
<div style={{ marginTop: 7 }}>
<button onClick={() => onOpen('DOE-BEST')} className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 3, fontSize: 11.5, color: tokens.accent, cursor: 'pointer', background: 'transparent' }}>
看 L9 九组全表与参数窗口 <ChevronRight size={12} />
</button>
</div>
</div>
</div>
</Card>
</div>
);
}
/* ══════════════════ 4. 工序 · 工位对比 ══════════════════ */
export function RegionView({ onOpen, period }: VizProps) {
const { tokens } = useTheme();
const lines = lineModelsAt(period);
const stations = stationModelsAt(period);
const master = masterModel();
const methods = methodCompareRows();
const bottleneckStations = stations.filter(s => s.bottleneck !== '否');
/** DS-02 与 DS-14 对「最大瓶颈」各说各话:一个按标准工时最长,一个按负荷率最高 */
const slowest = stations.reduce((mi, s) => (s.hours > mi.hours ? s : mi), stations[0]);
const busiest = lines.reduce((mi, l) => (l.load > mi.load ? l : mi), lines[0]);
/** DS-10 是一张「对比项 × 三种方式」的横表,按指标名取出三根柱子(比率已在视图层 ×100) */
const methodSeries = (item: string) => {
const row = methods.find(m => m.对比项 === item);
const raw = [numCell(row?.手工氩弧焊), numCell(row?.机器人弧焊), numCell(row?.['激光焊(设备)'])];
if (/一次良率/.test(item)) return raw.map(v => yieldPctAt(v, period));
if (/未焊透率/.test(item)) return raw.map(v => +defectPctAt(v, period).toFixed(1));
return raw;
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
<Card title="工序负荷率对比(DS-14)" right={<PeriodTag period={period} />}>
<HBarChart
height={210}
items={lines.map(l => ({
label: l.label,
value: l.load,
color: statusColor(l.status, tokens),
display: `${l.load.toFixed(1)}%`,
sub: `WIP ${l.wip.toLocaleString('en-US')}`,
}))}
/>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginTop: 8 }}>
{lines.map(l => (
<button key={l.code} onClick={() => onOpen(l.code)} className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '3px 6px', borderRadius: 6, cursor: 'pointer', background: tokens.panelBgAlt, border: `1px solid ${tokens.border}` }}>
<span style={{ width: 7, height: 7, borderRadius: 7, flex: '0 0 7px', background: statusColor(l.status, tokens) }} />
<span style={{ fontSize: 11.5, color: tokens.text, width: 78, flex: '0 0 78px' }}>{l.label}</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted, width: 118, flex: '0 0 118px' }}>{l.station}</span>
<span style={{ fontSize: 10.5, color: tokens.textSub, flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
需求 {l.demand}/实际 {l.capacity} 件·班⁻¹ · {l.warn}
</span>
<span style={{ fontSize: 10.5, color: tokens.textMuted, maxWidth: 210, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{l.advice}</span>
</button>
))}
</div>
<Note>
负荷率 = 需求节拍 ÷ 实际产能(现算)。需求节拍按订单口径折到班次:
月需求 {QAP_CALIBER.monthlyDemand.toLocaleString('en-US')} 件 ÷({QAP_CALIBER.workDays} 工作日 × {QAP_CALIBER.shifts} 班),
当前有 {lines.filter(l => l.load > 100).length} 道工序 &gt;100%;档位沿用原表「预警」列(最大瓶颈/严重瓶颈红,超负荷黄)。
{period === CURRENT_PERIOD ? '' : ` 当前为 ${periodLabel(period)} 回放:负荷按年末放行的季节曲线回推。`}
</Note>
</Card>
{/* 两栏各自纵向堆叠,而不是按行对齐:
按行放时 DS-02 比 DS-10 矮 300px,左列会空出一大块;
改成一列「DS-02 + DS-01」对一列「DS-10」,卡片间距仍然一致,但不再留洞。 */}
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, alignItems: 'start' }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
<Card title="工位产能达成率(DS-02)" tone={tokens.info} right={<PeriodTag period={period} />}>
<VBarChart
height={210}
labels={stations.map(s => s.process)}
groups={[stations.map(s => s.rate)]}
colors={[tokens.accent]}
names={['产能达成率(班次产能 ÷ 理论产能,现算)']}
/>
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8 }}>
{stations.map(s => (
<button key={s.code} onClick={() => onOpen(s.code)} className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '3px 8px', borderRadius: 7, cursor: 'pointer', background: tokens.panelBgAlt, border: `1px solid ${s.status === 'na' ? tokens.border : `${statusColor(s.status, tokens)}55`}`, fontSize: 10.5, color: tokens.textSub }}>
<span style={{ width: 6, height: 6, borderRadius: 6, background: statusColor(s.status, tokens) }} />
{s.station}
<b style={{ color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>{s.rate.toFixed(1)}%</b>
<span style={{ color: tokens.textMuted }}>{s.bottleneck}</span>
</button>
))}
</div>
<Note>
理论产能 = ROUND(480 ÷ 标准工时)(现算)。{bottleneckStations.length} 个瓶颈工位全落在焊接段({bottleneckStations.map(s => s.process).join('/')}),与 DS-14 的负荷率红档同段互证。
两张表的「最大瓶颈」不同名,这里不强行统一:DS-02 按标准工时把 {slowest.station} {slowest.process}({slowest.hours} min/件)标为最大瓶颈,
DS-14 按负荷率把 {busiest.label}({busiest.load.toFixed(1)}%)排为最大瓶颈——前者看单件耗时,后者看需求÷实际产能,两列各按源表原话显示。
</Note>
</Card>
<Card title="机型结构主数据(DS-01)" tone={tokens.info}>
<HBarChart
height={150}
items={master.byModel.map(m => ({
label: `${m.label}(${m.items} 料号)`,
value: m.annual,
color: tokens.accent,
display: m.annual.toLocaleString('en-US'),
sub: `${m.welded} 涉焊`,
}))}
/>
{/* 左列比右列矮一截,把留白换成四个源表读数:既能补齐高度,也把「共几个料号/机型」从文字里提出来 */}
<div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
{([
['机型', `${master.models} 个`],
['料号', `${master.items} 个`],
['年用量', `${master.annual.toLocaleString('en-US')} 件`],
['涉焊料号', `${master.welded} 个`],
] as const).map(([k, v]) => (
<div key={k} style={{
flex: '1 1 0', minWidth: 0, padding: '6px 8px', borderRadius: 8,
background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`,
}}>
<div style={{ fontSize: 10, color: tokens.textMuted }}>{k}</div>
<div style={{ fontSize: 12, fontWeight: 700, color: tokens.text, marginTop: 2, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{v}</div>
</div>
))}
</div>
<Note>
条长=年用量,右侧标该机型里涉焊接的料号数——特征码(材质 × 结构特征 × 工艺方法)就挂在这张表上。
</Note>
</Card>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
<Card title="三种焊接方式对照(DS-10)" tone={tokens.danger} right={<PeriodTag period={period} />}>
<VBarChart
height={200}
labels={['手工氩弧焊', '机器人弧焊', '激光焊(设备)']}
groups={[methodSeries('一次良率'), methodSeries('未焊透率(DF-WLD-02)')]}
colors={[tokens.accent, tokens.danger]}
names={['一次良率 %', '未焊透率 %(致命缺陷)']}
/>
<DataTable table={{ tableKey: 'DS-10', title: 'DS-10', columns: ['对比项', '手工氩弧焊', '机器人弧焊', '激光焊(设备)', '单位', '差异结论'], rows: methods.slice(0, 6) }} />
<Note>
同料号 SRV2U-FANW-01、同批次板材对照;原表结论:设备化把一次良率抬 14~20pt(68.5 → 88.9%),
返修/补焊工时从 3.2 压到 0.6 min/件,换型时间反而从 5 涨到 15 min——柔性是小批量手工的强项,这张表也照着原表列全了代价。
</Note>
</Card>
</div>
</div>
</div>
);
}
/* ══════════════════ 5. 风险矩阵 ══════════════════ */
export function RiskView({ onOpen, period }: VizProps) {
const { tokens } = useTheme();
const rp = riskPoints();
const maxCount = Math.max(...rp.map(r => r.count), 1);
const items = rp.map(r => ({
label: r.label.length > 9 ? `${r.label.slice(0, 9)}…` : r.label,
x: r.count / maxCount,
y: SEVERITY_WEIGHT[r.severity] ?? 0.3,
status: r.severity,
color: severityColor(r.severity, tokens),
}));
const abn = abnormalModelsAt(period);
/** 平均值只按未闭环那几单算:把已闭环的 11 天混进去会凭空抬高一倍 */
const openAbn = abn.filter(a => !a.closed);
const overdueAbn = openAbn.filter(a => a.overdue);
const avgOpenDwell = openAbn.length ? openAbn.reduce((s, a) => s + a.dwell, 0) / openAbn.length : 0;
const cov = coverageModelAt(period);
return (
<div style={{ display: 'grid', gridTemplateColumns: '1.15fr 1fr', gap: 12, alignItems: 'start' }}>
<Card title="风险点检矩阵(DS-05)" right={<SnapshotTag label="历史发生 · 源表当期" />}>
<RiskMatrix items={items} height={318} xLabel={`历史发生次数 →(最高 ${maxCount})`} yLabel="↑ 严重度(致命 0.9/严重 0.6/一般 0.3)" />
<Note>
横轴直接取原表「历史发生次数」,纵轴用严重度做展示映射(致命 0.9/严重 0.6/一般 0.3)——
这是坐标摆放,不是源表判定线。右上=高频且致命,是最该先补标准的那格。
同严重度的几点会挤在同一横线上,图里只把它们上下错开、标签让位,次数与严重度的读数以下方明细为准。
</Note>
</Card>
<Card title={`异常滞留天数(DS-15)· ${openAbn.length} 单未闭环`} tone={tokens.danger} right={<PeriodTag period={period} />}>
<HBarChart
height={334}
items={[...abn].sort((a, b) => Number(a.closed) - Number(b.closed) || b.dwell - a.dwell).map(a => ({
label: `${a.order} ${a.defect}`,
value: a.dwell,
color: statusColor(a.status, tokens),
display: `${a.dwell} 天`,
sub: a.closed ? '已闭环' : a.escalation,
}))}
/>
<Note>
滞留天数 = 回放基准日 {period === CURRENT_PERIOD ? QAP_CALIBER.warningPoolBaseDate : periodLabel(period) + '-16'} − 发生日(现算);原表口径超 3 天必须升级,
当前超期未闭环 {overdueAbn.length} 单({overdueAbn.map(a => `${a.order} ${a.dwell} 天`).join('、') || '无'}),
未闭环 {openAbn.length} 单平均滞留 {avgOpenDwell.toFixed(1)} 天(已闭环那单不计入)。
</Note>
</Card>
<Card title="新机型良率可预测度(DS-13)" full tone={tokens.info}>
<DataTable table={{
tableKey: 'DS-13', title: 'DS-13',
columns: ['新机型/料号', '相似机型', '特征相似度', '相似机型实际良率%', '预测良率区间', '高概率缺陷(Top3)', '建议动作'],
rows: predictionRows(),
focus: { column: '相似机型', value: '无相似件' },
}} />
<Note>相似度按材质 × 板厚 × 结构特征 × 焊接方式加权;标「无相似件」的行就是模型盲区——高亮那行没有可比历史,预测区间为空,只能靠首件验证补。</Note>
</Card>
<Card title={`检验标准缺口(DS-07)· 已覆盖 ${cov.coveredCount}/${cov.total}`} full tone={tokens.warning} right={period === CURRENT_PERIOD ? undefined : <PeriodTag period={period} />}>
<div style={{ display: 'grid', gridTemplateColumns: '240px 1fr', gap: 12, alignItems: 'start' }}>
<div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
<span style={{ fontSize: 30, fontWeight: 800, color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>{cov.rate}</span>
<span style={{ fontSize: 12, color: tokens.textMuted }}>% 覆盖率</span>
</div>
<div style={{ height: 8, borderRadius: 8, background: tokens.border, overflow: 'hidden', marginTop: 6 }}>
<div style={{ width: `${cov.rate}%`, height: '100%', background: tokens.accent, borderRadius: 8 }} />
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 5, marginTop: 9 }}>
{cov.pending.map(p => (
<button key={p.检验项目} onClick={() => onOpen('STD-GAP')} className="ghost-btn"
style={{ textAlign: 'left', cursor: 'pointer', padding: '5px 8px', borderRadius: 8, background: `${tokens.warning}14`, border: `1px solid ${tokens.warning}44` }}>
<div style={{ fontSize: 11.5, color: tokens.text, fontWeight: 700 }}>待 QE 确认 · {p.检验项目}</div>
<div style={{ fontSize: 10.5, color: tokens.textSub, marginTop: 2 }}>{p['AI 提示']}</div>
</button>
))}
</div>
</div>
<DataTable table={{
tableKey: 'DS-07', title: 'DS-07',
columns: ['特征/项目', '检验项目', '依据', '抽样', '量具', '频次', 'AI 提示', '状态'],
rows: cov.rows(),
focus: { column: '状态', value: '待 QE 确认' },
}} />
</div>
<Note>
状态=「待 QE 确认」即标准缺口(原表口径),确认后转「已覆盖」;AI 提示直接引用相似件历史 8D,把 QE 段最依赖个人经验的那一步补上。
{period === CURRENT_PERIOD ? '' : ` ${periodLabel(period)} 回放:缺口数以源表待确认项为基数按质量曲线回推,下列明细仍为 2026-10 当期。`}
</Note>
</Card>
<Card title="DS-05 风险点检清单" full>
<DataTable table={{
tableKey: 'DS-05', title: 'DS-05',
columns: ['序号', '风险项', '工序', '历史发生次数', '严重度', '控制措施', '检验方法/频次', '责任人', '来源引用'],
rows: riskChecklistRows(),
}} />
</Card>
</div>
);
}
/* ══════════════════ 6. 指标明细 ══════════════════ */
export function DetailView({ subject, onOpen, period }: VizProps) {
const { tokens } = useTheme();
const m: QualityMetric = metricAt(subject, period) ?? metricAt(DEFAULT_METRIC, period)!;
const groups = [...new Set(METRICS.map(x => x.group))];
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* 指标脊导航:四组读数横排,点一个换主体 */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
{groups.map(g => (
<div key={g} style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
<span style={{ fontSize: 11, color: tokens.textMuted, width: 62, flex: '0 0 62px', whiteSpace: 'nowrap' }}>{g}</span>
<div style={{ display: 'flex', gap: 5, flexWrap: 'wrap', minWidth: 0 }}>
{METRICS.filter(x => x.group === g).map(x => {
const xm = metricAt(x.code, period) ?? x;
const on = x.code === m.code;
const c = statusColor(xm.status, tokens);
return (
<button
key={x.code}
onClick={() => onOpen(x.code)}
className="ghost-btn"
style={{
display: 'flex', alignItems: 'center', gap: 4, padding: '3px 9px', borderRadius: 8, cursor: 'pointer',
fontSize: 11, whiteSpace: 'nowrap',
background: on ? tokens.accent : tokens.panelBgAlt,
color: on ? tokens.onAccent : tokens.textSub,
border: `1px solid ${on ? tokens.accent : xm.status === 'na' ? tokens.border : `${c}55`}`,
fontWeight: on ? 700 : 500,
}}
>
{xm.status !== 'na' && <span style={{ width: 6, height: 6, borderRadius: 6, background: on ? tokens.onAccent : c }} />}
{x.name}
{!on && <span style={{ fontVariantNumeric: 'tabular-nums', color: tokens.textMuted }}>{xm.value}{xm.unit}</span>}
</button>
);
})}
</div>
</div>
))}
</div>
{/* Hero + 判定 */}
<div style={{ display: 'grid', gridTemplateColumns: 'minmax(220px, 0.9fr) 1.6fr', gap: 12 }}>
<div style={{
padding: '12px 14px', borderRadius: 11, border: `1px solid ${tokens.borderAccent}`,
background: `linear-gradient(135deg, ${tokens.accentBg}, ${tokens.cardBg})`, position: 'relative', overflow: 'hidden',
}}>
<div style={{ fontSize: 12, color: tokens.textSub }}>{m.name}</div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 4 }}>
<span style={{ fontSize: 38, fontWeight: 800, color: tokens.text, lineHeight: 1, fontVariantNumeric: 'tabular-nums', textShadow: `0 0 22px ${statusColor(m.status, tokens)}33` }}>
{m.value || '—'}
</span>
<span style={{ fontSize: 13, color: tokens.textMuted }}>{m.unit}</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 8, flexWrap: 'wrap' }}>
<StatusChip status={m.status} />
<span style={{ fontSize: 11, color: tokens.textMuted, fontFamily: 'ui-monospace, monospace' }}>{m.code}</span>
<span style={{ fontSize: 11, color: tokens.accent }}>{m.ds} {m.dsName}</span>
{period !== CURRENT_PERIOD && <PeriodTag period={period} />}
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
<div style={{ padding: '9px 12px', borderRadius: 10, background: tokens.cardBg, border: `1px solid ${tokens.border}` }}>
<div style={{ fontSize: 11, color: tokens.textMuted, marginBottom: 3 }}>读数</div>
<div style={{ fontSize: 12.5, lineHeight: 1.7, color: tokens.textSub }}>{m.reading}</div>
</div>
<div style={{ padding: '9px 12px', borderRadius: 10, background: tokens.cardBg, border: `1px solid ${tokens.border}` }}>
<div style={{ fontSize: 11, color: tokens.textMuted, marginBottom: 3 }}>判定依据</div>
<div style={{ fontSize: 12.5, lineHeight: 1.7, color: m.status === 'na' ? tokens.textMuted : statusColor(m.status, tokens) }}>{m.rule}</div>
</div>
</div>
</div>
{/* 元信息 */}
<div style={{
display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0,1fr))', gap: 1,
background: tokens.border, border: `1px solid ${tokens.border}`, borderRadius: 10, overflow: 'hidden',
}}>
{[
['归属分组', m.group],
['责任角色', m.role],
['计算式', m.formula],
['数据集口径', m.caliber],
].map(([k, v]) => (
<div key={k} style={{ background: tokens.panelBgAlt, padding: '7px 10px', minWidth: 0 }}>
<div style={{ fontSize: 10.5, color: tokens.textMuted, marginBottom: 2 }}>{k}</div>
<div style={{ fontSize: 12, color: tokens.text, fontWeight: 600, lineHeight: 1.55, whiteSpace: 'normal' }}>{v}</div>
</div>
))}
</div>
<Card title={`${m.detail.title} · ${m.detail.rows.length} 行`} right={<span style={{ fontSize: 10.5, color: tokens.textMuted }}>带 ◆ 的列是现算,不在原表里</span>}>
<DataTable table={m.detail} max={12} />
</Card>
<Card title="这一组的其他读数">
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
{METRICS.filter(x => x.group === m.group && x.code !== m.code).map(x => {
const xm = metricAt(x.code, period) ?? x;
return (
<button key={x.code} onClick={() => onOpen(x.code)} className="ghost-btn"
style={{ display: 'flex', alignItems: 'center', gap: 5, padding: '4px 9px', borderRadius: 8, cursor: 'pointer', background: tokens.panelBgAlt, border: `1px solid ${tokens.border}`, fontSize: 11.5, color: tokens.textSub }}>
<span style={{ width: 6, height: 6, borderRadius: 6, background: statusColor(xm.status, tokens) }} />
{x.name}
<b style={{ color: tokens.text, fontVariantNumeric: 'tabular-nums' }}>{xm.value}{xm.unit}</b>
<span style={{ color: tokens.textMuted }}>{x.ds}</span>
</button>
);
})}
</div>
<Note>全部读数只出自这本 Excel 的 16 个数据集;比率类字段按原表存小数、页面 ×100 展示,计算列一律现算。
{period === CURRENT_PERIOD ? '' : ` ${REPLAY_DETAIL_NOTE}`}
</Note>
</Card>
</div>
);
}
/* 局部小工具 */
function numCell(v: unknown): number {
const n = Number(v);
return Number.isFinite(n) ? n : 0;
}
@@ -0,0 +1,222 @@
import { createContext, useContext, useState, useCallback } from 'react';
import type { CSSProperties, ReactNode } from 'react';
export type Theme = 'dark' | 'light';
export interface ThemeTokens {
bodyBg: string;
bodyBgImage: string;
panelBg: string;
panelBgAlt: string;
cardBg: string;
centerBg: string;
border: string;
borderSub: string;
borderAccent: string;
text: string;
textSub: string;
textMuted: string;
textInverse: string;
/** 压在 accent / 渐变底上的可读前景色(保证深浅主题都达 AA) */
onAccent: string;
accent: string;
accentGlow: string;
accentBg: string;
success: string;
successBg: string;
warning: string;
warningBg: string;
danger: string;
dangerBg: string;
info: string;
infoBg: string;
headerScanLine: string;
kpiCardBg: string;
kpiCardBorder: string;
tableHeaderBg: string;
tableRowHover: string;
tableRowAlt: string;
scrollThumb: string;
/** 左右侧板弧形背景(SVG 渐变端点) */
svgPanelFrom: string;
svgPanelTo: string;
svgStroke: string;
svgDot: string;
titleBarColor: string;
titleGlow: string;
cardShadow: string;
centerShadow: string;
chartLine1: string;
chartLine2: string;
chartLine3: string;
chartFill1: string;
}
export const darkTokens: ThemeTokens = {
bodyBg: '#0a0e1a',
bodyBgImage: 'radial-gradient(1200px 600px at 15% -10%, rgba(0,123,190,0.20), transparent 60%), radial-gradient(1000px 500px at 90% 10%, rgba(86,172,224,0.12), transparent 60%), #0a0e1a',
panelBg: 'rgba(15,23,42,0.85)',
panelBgAlt: 'rgba(20,30,55,0.7)',
cardBg: 'rgba(30,41,59,0.6)',
centerBg: 'rgba(13,20,40,0.55)',
border: 'rgba(86,172,224,0.16)',
borderSub: 'rgba(86,172,224,0.08)',
borderAccent: 'rgba(86,172,224,0.38)',
text: '#e2e8f0',
textSub: '#94a3b8',
textMuted: 'rgba(168,184,208,0.85)',
textInverse: '#ffffff',
onAccent: '#04121c',
accent: '#56ace0',
accentGlow: 'rgba(86,172,224,0.7)',
accentBg: 'rgba(86,172,224,0.10)',
success: '#34d399',
successBg: 'rgba(52,211,153,0.1)',
warning: '#fbbf24',
warningBg: 'rgba(251,191,36,0.1)',
danger: '#f87171',
dangerBg: 'rgba(248,113,113,0.1)',
info: '#22d3ee',
infoBg: 'rgba(34,211,238,0.1)',
headerScanLine: 'linear-gradient(90deg, transparent 0%, rgba(86,172,224,0.25) 20%, rgba(86,172,224,0.85) 50%, rgba(86,172,224,0.25) 80%, transparent 100%)',
kpiCardBg: 'rgba(30,41,59,0.5)',
kpiCardBorder: 'rgba(86,172,224,0.14)',
tableHeaderBg: 'rgba(30,41,59,0.8)',
tableRowHover: 'rgba(86,172,224,0.07)',
tableRowAlt: 'rgba(20,30,55,0.4)',
scrollThumb: 'rgba(86,172,224,0.30)',
svgPanelFrom: 'rgba(18,26,52,0.72)',
svgPanelTo: 'rgba(10,15,32,0.62)',
svgStroke: 'rgba(86,172,224,0.42)',
svgDot: 'rgba(86,172,224,0.9)',
titleBarColor: '#bae6fd',
titleGlow: '0 0 22px rgba(86,172,224,0.55), 0 0 44px rgba(0,123,190,0.25)',
cardShadow: '0 0 18px rgba(0,123,190,0.10)',
centerShadow: '0 0 34px rgba(0,123,190,0.14), inset 0 0 30px rgba(15,23,42,0.5)',
chartLine1: '#56ace0',
chartLine2: '#34d399',
chartLine3: '#fbbf24',
chartFill1: 'rgba(86,172,224,0.15)',
};
/**
* 浅色主题=本系统的默认外观(演示场景固定为浅底)。
*
* 配色沿用工作台骨架的科技蓝 #007BBE 作为数据色,官方 TF-AMD 红只用于 logo,
* 避免与告警红混淆;accent 不直接用原色:
* #007BBE 在白底只有 4.61:1、在页面底色 #eef2fa 上只有 4.11:1,正文级小字达不到 WCAG AA。
* 因此 accent 取同色相(210.9°)压暗 12% 的 #006CA7 —— 白底 5.68:1、页面底色 5.06:1,
* 图形级(3:1)更是全程有余量;logo 仍用标准色 #007BBE,品牌识别不受影响。
*/
export const lightTokens: ThemeTokens = {
bodyBg: '#eef2fa',
bodyBgImage: 'radial-gradient(1200px 620px at 12% -12%, rgba(0,123,190,0.13), transparent 62%), radial-gradient(1000px 520px at 92% 4%, rgba(14,116,144,0.09), transparent 60%), linear-gradient(180deg, #f5f8fd 0%, #e9f0f9 100%)',
panelBg: 'rgba(255,255,255,0.97)',
panelBgAlt: 'rgba(247,250,254,0.96)',
cardBg: 'rgba(255,255,255,0.92)',
centerBg: 'linear-gradient(160deg, rgba(255,255,255,0.78) 0%, rgba(241,247,253,0.68) 50%, rgba(232,241,250,0.72) 100%)',
border: 'rgba(12,72,105,0.16)',
borderSub: 'rgba(12,72,105,0.09)',
borderAccent: 'rgba(0,108,167,0.32)',
text: '#0f172a',
textSub: '#334155',
textMuted: '#5b6a7f',
textInverse: '#ffffff',
onAccent: '#ffffff',
accent: '#006ca7',
accentGlow: 'rgba(0,108,167,0.35)',
accentBg: 'rgba(0,123,190,0.07)',
success: '#046c4e',
successBg: 'rgba(4,108,78,0.07)',
warning: '#9a4a06',
warningBg: 'rgba(154,74,6,0.07)',
danger: '#b31217',
dangerBg: 'rgba(179,18,23,0.06)',
info: '#0e7490',
infoBg: 'rgba(14,116,144,0.07)',
headerScanLine: 'linear-gradient(90deg, transparent 0%, rgba(0,108,167,0.12) 20%, rgba(0,108,167,0.45) 50%, rgba(0,108,167,0.12) 80%, transparent 100%)',
kpiCardBg: 'rgba(255,255,255,0.9)',
kpiCardBorder: 'rgba(0,108,167,0.14)',
tableHeaderBg: 'rgba(234,242,250,0.96)',
tableRowHover: 'rgba(0,108,167,0.05)',
tableRowAlt: 'rgba(245,249,253,0.85)',
scrollThumb: 'rgba(0,108,167,0.24)',
svgPanelFrom: 'rgba(240,246,253,0.98)',
svgPanelTo: 'rgba(225,237,249,0.96)',
svgStroke: 'rgba(0,108,167,0.32)',
svgDot: 'rgba(0,108,167,0.78)',
titleBarColor: '#0b1b2b',
titleGlow: 'none',
cardShadow: '0 1px 4px rgba(12,58,92,0.09)',
centerShadow: '0 4px 32px rgba(0,72,120,0.11), 0 1px 8px rgba(0,50,90,0.06)',
chartLine1: '#006ca7',
chartLine2: '#047857',
chartLine3: '#c2600c',
chartFill1: 'rgba(0,108,167,0.1)',
};
interface ThemeContextValue {
theme: Theme;
tokens: ThemeTokens;
toggleTheme: () => void;
}
const STORAGE_KEY = 'tfamd-oee-theme';
function readStoredTheme(): Theme {
try {
const saved = localStorage.getItem(STORAGE_KEY);
return saved === 'dark' || saved === 'light' ? saved : 'light';
} catch {
return 'light';
}
}
const ThemeContext = createContext<ThemeContextValue>({
theme: 'light',
tokens: lightTokens,
toggleTheme: () => {},
});
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>(readStoredTheme);
const tokens = theme === 'dark' ? darkTokens : lightTokens;
const toggleTheme = useCallback(() => {
setTheme(t => {
const next: Theme = t === 'dark' ? 'light' : 'dark';
try {
localStorage.setItem(STORAGE_KEY, next);
} catch {
/* 忽略写入失败 */
}
return next;
});
}, []);
// 主题令牌挂在模块根容器上(CSS 继承向下生效),卸载即消失:
// 不写 document.documentElement / document.body,避免污染平台全局样式。
return (
<ThemeContext.Provider value={{ theme, tokens, toggleTheme }}>
<div
className="tfamd-root"
style={{
'--body-bg': tokens.bodyBg,
'--scroll-thumb': tokens.scrollThumb,
'--glow-color': tokens.accentGlow,
'--hover-bg': tokens.tableRowHover,
background: tokens.bodyBgImage,
color: tokens.text,
width: '100%',
minHeight: '100vh',
} as CSSProperties}
>
{children}
</div>
</ThemeContext.Provider>
);
}
export function useTheme() {
return useContext(ThemeContext);
}
+285
View File
@@ -0,0 +1,285 @@
/**
* 特征树数据层:机型 → 工艺 → 生产方法 三层结构。
*
* 第三级是可执行的生产方法(数控冲孔 / 手工倒角 / 激光焊 / 压铆…),
* 不是缺陷名。每个方法挂一组跨角色总结行:
* 问题 · 原因 · 对策 · 角色(PE / IE / QE / ME)
*
* 真实知识来自 knowledge.ts 的切片,经 methodSummaries.ts 落到方法;
* 其余机型与空方法用「示例」补齐,页面明确标注,不混成知识事实。
*
* 同时维护:
* codeIndex 新特征码(MODEL.PROCESS.METHOD)→ 方法节点
* refIndex DS 对象 / 实例 → 方法节点(知识库跳回时用)
*/
import { roleDocs } from './knowledge';
import { featureRefsOf, type FeatureRef, type KbRef } from './kbLinks';
import { PRODUCTION_CATALOG, summariesFor, type MethodSummaryRow } from './methodSummaries';
import { TABLES, type ProductProcessMaster, type StationEquipmentTooling } from './qap';
import { instanceFields } from './ontologyQap';
export interface TreeAttr { label: string; value: string }
export interface FeatureMethod {
id: string;
code: string;
label: string;
modelId: string;
processId: string;
attrs: TreeAttr[];
/** 该生产方法关联的数据对象实例(DS-01/09/12) */
refs: FeatureRef[];
/** 挂载在该生产方法上的真实知识切片 */
kbRefs: KbRef[];
/** 问题 / 原因 / 对策 / 角色 总结行(真实 + 示例) */
summary: MethodSummaryRow[];
realCount: number;
exampleCount: number;
modelAttrs: TreeAttr[];
processAttrs: TreeAttr[];
}
export interface FeatureProcess {
id: string;
label: string;
modelId: string;
attrs: TreeAttr[];
methods: FeatureMethod[];
/** 该工艺下所有方法挂载的真实知识切片(去重) */
kbRefs: KbRef[];
}
export interface FeatureModel {
id: string;
label: string;
attrs: TreeAttr[];
processes: FeatureProcess[];
/** 该机型下所有方法挂载的真实知识切片(去重) */
kbRefs: KbRef[];
}
export interface FeatureTree {
models: FeatureModel[];
/** 新特征码 → 方法节点 */
codeIndex: Map<string, FeatureMethod>;
/** DS 对象/实例 → 方法节点(可能多个方法指向同一实例) */
refIndex: Map<string, FeatureMethod[]>;
}
const ds01 = TABLES['DS-01'] as ProductProcessMaster[];
const ds02 = TABLES['DS-02'] as StationEquipmentTooling[];
const s = (v: unknown) => (v === null || v === undefined || v === '' ? '—' : String(v));
const shortLabel = (text: string, max = 24) =>
text.length <= max ? text : `${text.slice(0, max)}…`;
/* ── 工艺 segment → DS-02 工序匹配 ────────────────────────────────────── */
const processMatchesStation = (processId: string, stationName: string): boolean => {
if (processId === 'NCT') return stationName.includes('NCT');
if (processId === '压铆') return stationName.includes('压铆') || stationName.includes('攻牙');
if (processId === '焊接') return stationName.includes('焊') && !stationName.includes('打磨');
return stationName.includes(processId);
};
/* ── 机型属性:从 DS-01 汇总 ──────────────────────────────────────────── */
const modelAttrs = (modelId: string): TreeAttr[] => {
const rows = ds01.filter(r => r.机型 === modelId);
if (rows.length === 0) return [{ label: '数据', value: '该机型暂无产品主数据' }];
const materials = [...new Set(rows.map(r => r.材质))].join(' / ');
const thicks = rows.map(r => r['板厚(mm)']);
const procs = rows.map(r => r.工序数);
const totalQty = rows.reduce((a, r) => a + r['年用量(件)'], 0);
const welds = [...new Set(rows.map(r => r.焊接作业方式))].join(' / ');
return [
{ label: '料号数', value: `${rows.length} 个` },
{ label: '代表件', value: rows.map(r => r.品名).join('、') },
{ label: '材质', value: materials },
{ label: '板厚范围', value: `${Math.min(...thicks)}–${Math.max(...thicks)} mm` },
{ label: '工序数范围', value: `${Math.min(...procs)}–${Math.max(...procs)} 道` },
{ label: '焊接方式', value: welds },
{ label: '年用量合计', value: `${totalQty.toLocaleString('zh-CN')} 件` },
];
};
/* ── 工艺属性:从 DS-02 工位台账匹配 ──────────────────────────────────── */
const processAttrs = (processId: string): TreeAttr[] => {
const rows = ds02.filter(r => processMatchesStation(processId, r.工序));
if (rows.length === 0) {
return [{
label: '工位台账',
value: processId === '表面处理' ? '外协工序,DS-02 无对应工位' : '暂无直接对应工位',
}];
}
const bottleneck = rows.map(r => r.瓶颈).filter(b => b && b !== '否').join('、') || '无';
return [
{ label: '工位数', value: `${rows.length} 个` },
{ label: '设备', value: rows.map(r => r.设备).join(' / ') },
{ label: '工装/夹具', value: rows.map(r => r['工装/夹具']).join(' / ') },
{ label: '标准工时', value: rows.map(r => `${r.工序} ${r['标准工时(min/件)']} min/件`).join(';') },
{ label: '班次产能', value: rows.map(r => `${r.工序} ${r['班次产能(件)']} 件/班`).join(';') },
{ label: '瓶颈标记', value: bottleneck },
];
};
/* ── 方法属性:把映射到的 DS 实例字段摊开(保留给需要看原表的场景) ──── */
const pct1 = (v: number) => `${(v * 100).toFixed(1)}%`;
export const methodAttrBlocks = (refs: FeatureRef[]): { title: string; attrs: TreeAttr[] }[] => {
const blocks: { title: string; attrs: TreeAttr[] }[] = [];
for (const ref of refs) {
const fields = ref.instanceId ? instanceFields(ref.objKey, ref.instanceId) : [];
if (fields.length === 0) {
blocks.push({ title: ref.objKey, attrs: [{ label: '说明', value: ref.why }] });
continue;
}
const extra: TreeAttr[] = [];
if (ref.objKey === 'DS-09') {
const row = (TABLES['DS-09'] as Record<string, number | string>[]).find(
r => s(r['结构特征维度']) === ref.instanceId,
);
if (row) {
const rate = (['焊瘤', '未焊透', '搭接不良', '焊接变形'] as const)
.reduce((a, k) => a + (typeof row[k] === 'number' ? row[k] as number : 0), 0);
extra.push({ label: '综合不良率', value: pct1(rate) });
}
}
if (ref.objKey === 'DS-12') {
const row = (TABLES['DS-12'] as Record<string, number | string | null>[]).find(
r => `T${s(r['试验号'])}` === ref.instanceId,
);
if (row && typeof row['焊瘤率'] === 'number' && typeof row['未焊透率'] === 'number') {
const yield_ = 1 - (row['焊瘤率'] as number) - (row['未焊透率'] as number);
extra.push({ label: '综合良率', value: pct1(yield_) });
}
}
blocks.push({
title: `${ref.objKey}${ref.instanceId ? ` · ${ref.instanceId}` : ''}`,
attrs: [
{ label: '关联原因', value: ref.why },
...extra,
...fields.map(f => ({ label: f.name, value: f.value })),
],
});
}
return blocks;
};
const mergeKbRefs = (lists: KbRef[][]): KbRef[] => {
const out: KbRef[] = [];
for (const list of lists) {
for (const r of list) {
if (!out.some(x => x.role === r.role && x.chunkId === r.chunkId && x.code === r.code)) {
out.push(r);
}
}
}
return out;
};
/* ── 构建整棵树 ───────────────────────────────────────────────────────── */
export const buildFeatureTree = (): FeatureTree => {
const codeIndex = new Map<string, FeatureMethod>();
const refIndex = new Map<string, FeatureMethod[]>();
const models: FeatureModel[] = [];
const modelIds = [...new Set(ds01.map(r => r.机型))].sort((a, b) => {
const rank = (id: string) => (id === 'SRV-2U-620' ? 0 : id.startsWith('SRV') ? 1 : 2);
return rank(a) - rank(b) || a.localeCompare(b);
});
for (const modelId of modelIds) {
const mAttrs = modelAttrs(modelId);
const processes: FeatureProcess[] = [];
for (const procDef of PRODUCTION_CATALOG) {
const pAttrs = processAttrs(procDef.id);
const methods: FeatureMethod[] = [];
for (const methodDef of procDef.methods) {
const code = `${modelId}.${procDef.id}.${methodDef.id}`;
const summary = summariesFor(modelId, procDef.id, methodDef.id);
const realRows = summary.filter(r => r.source.kind === 'kb');
const kbRefs: KbRef[] = [];
for (const row of realRows) {
if (row.source.kind !== 'kb') continue;
const src = row.source;
const doc = roleDocs.find(d => d.role === row.role);
const chunk = doc?.chunks.find(c => c.id === src.chunkId);
kbRefs.push({
role: row.role,
chunkId: src.chunkId,
label: chunk ? shortLabel(chunk.text) : shortLabel(row.problem),
code: src.code ?? '',
});
}
const refMap = new Map<string, FeatureRef>();
for (const row of realRows) {
if (row.source.kind !== 'kb' || !row.source.code) continue;
for (const ref of featureRefsOf(row.source.code)) {
refMap.set(`${ref.objKey}#${ref.instanceId ?? ''}`, ref);
}
}
const refs = [...refMap.values()];
const method: FeatureMethod = {
id: code,
code,
label: methodDef.label,
modelId,
processId: procDef.id,
attrs: [],
refs,
kbRefs,
summary,
realCount: realRows.length,
exampleCount: summary.length - realRows.length,
modelAttrs: mAttrs,
processAttrs: pAttrs,
};
methods.push(method);
codeIndex.set(code, method);
for (const ref of refs) {
const key = `${ref.objKey}#${ref.instanceId ?? ''}`;
const arr = refIndex.get(key) ?? [];
if (!arr.some(x => x.id === method.id)) arr.push(method);
refIndex.set(key, arr);
}
}
processes.push({
id: procDef.id,
label: procDef.label,
modelId,
attrs: pAttrs,
methods,
kbRefs: mergeKbRefs(methods.map(m => m.kbRefs)),
});
}
models.push({
id: modelId,
label: modelId,
attrs: mAttrs,
processes,
kbRefs: mergeKbRefs(processes.map(p => p.kbRefs)),
});
}
return { models, codeIndex, refIndex };
};
let cachedTree: FeatureTree | null = null;
export const getFeatureTree = (): FeatureTree => {
if (!cachedTree) cachedTree = buildFeatureTree();
return cachedTree;
};
/** 由 DS 对象/实例反查对应的方法节点(知识库跳回时用) */
export const methodsForRef = (objKey: string, instanceId?: string): FeatureMethod[] => {
const key = `${objKey}#${instanceId ?? ''}`;
return getFeatureTree().refIndex.get(key) ?? [];
};
@@ -0,0 +1,123 @@
[
{
"序号": 1,
"客户编码": "GM0045",
"客户简称": "YCSFHWLYXGS",
"性质": "客户/供应商",
"客户分类": "杂项开票",
"所属类别": "杂项开票",
"分管部门": null,
"订单笔数": 2,
"订单金额": 140612.8
},
{
"序号": 2,
"客户编码": "KA0033",
"客户简称": "NBLARYPYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 2,
"订单金额": 16499.9
},
{
"序号": 3,
"客户编码": "KA0049",
"客户简称": "ZJJLYZFZPXSYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 1,
"订单金额": 27518.4
},
{
"序号": 4,
"客户编码": "KA0087",
"客户简称": "LSMMJJYP(ZJ)YXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 1,
"订单金额": 10836.62
},
{
"序号": 5,
"客户编码": "KA0090",
"客户简称": "KCTZ(ZG)YXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 1,
"订单金额": 115200
},
{
"序号": 6,
"客户编码": "KA0099",
"客户简称": "ZJSJLHWLPSYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 2,
"订单金额": 62400
},
{
"序号": 7,
"客户编码": "KA0116",
"客户简称": "NBJQHYGMYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 2,
"订单金额": 89510.4
},
{
"序号": 8,
"客户编码": "KA0124",
"客户简称": "TJSTNGJMYYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 2,
"订单金额": 30960
},
{
"序号": 9,
"客户编码": "KA0154",
"客户简称": "HNZQNGYLGLYXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 1,
"订单金额": 14040
},
{
"序号": 10,
"客户编码": "KA0162",
"客户简称": "ZSMGYL(SY)YXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 2,
"订单金额": 121919.1
},
{
"序号": 11,
"客户编码": "KA0210",
"客户简称": "BGGGCZ(GZ)YXGS",
"性质": "客户",
"客户分类": "OEM开票",
"所属类别": "OEM开票",
"分管部门": "销售科",
"订单笔数": 1,
"订单金额": 21850
}
]
+79
View File
@@ -0,0 +1,79 @@
/**
* 洁雅家居 · 集成业务计划 —— 模拟业务单据数据(前端内置,不落后端库)
* 来源:source-data/测试业务单据.xlsx(ERP 导出单据按真实业务链路重组)
* 链路:销售订单 → 生产工单(WO-销售订单号) → 工单材料明细 → 材料采购订单
*/
import salesOrdersRaw from './sales_orders.json';
import productionOrdersRaw from './production_orders.json';
import workOrderMaterialsRaw from './work_order_materials.json';
import purchaseOrdersRaw from './purchase_orders.json';
import customersRaw from './customers.json';
import suppliersRaw from './suppliers.json';
import itemsRaw from './items.json';
export interface SalesOrder {
序号: number; 销售订单号: string; 单据日期: string; 客户编码: string; 客户分类: string;
客户简称: string; 产品编码: string; 数量: number; 含税单价: number; 含税金额: number;
预计发货日期: string; 仓库名称: string; 制单人: string; 单据状态: string;
}
export interface ProductionOrder {
序号: number; 工单号: string; 来源销售订单号: string; 产品编码: string; 规格型号: string | null;
计量单位: string; 生产数量: number; 生产车间: string; 预计开工日期: string; 预计完工日期: string;
'生产周期(天)': number; BOM版本: string; 单据状态: string;
}
export interface WorkOrderMaterial {
序号: number; 工单号: string; 来源销售订单号: string; 产品编码: string; 材料编码: string;
规格型号: string | null; 计量单位: string; 工单数量: number; 单位用量: number; 损耗率: number | null;
应领数量: number; 预出仓库: string; 材料来源: string; BOM版本: string; 子件BOM: string | null;
}
export interface PurchaseOrder {
序号: number; 采购订单号: string; 采购日期: string; 来源销售订单号: string; 产品工单号: string;
供应商编码: string; 供应商简称: string; 材料编码: string; 数量: number; 单价: number;
含税金额: number; 预计到货日期: string; 订单状态: string; 来源单据: string;
}
export interface Customer {
序号: number; 客户编码: string; 客户简称: string; 性质: string; 客户分类: string;
所属类别: string; 分管部门: string | null; 订单笔数: number; 订单金额: number;
}
export interface Supplier {
序号: number; 供应商编码: string; 供应商简称: string; 性质: string; 所属类别: string;
分管部门: string | null; 采购行数: number; 采购金额: number;
}
export interface Item {
序号: number; 物料编码: string; 类型: string; 规格型号: string | null;
计量单位: string; BOM版本: string | null; 数据来源: string;
}
export const salesOrders = salesOrdersRaw as unknown as SalesOrder[];
export const productionOrders = productionOrdersRaw as unknown as ProductionOrder[];
export const workOrderMaterials = workOrderMaterialsRaw as unknown as WorkOrderMaterial[];
export const purchaseOrders = purchaseOrdersRaw as unknown as PurchaseOrder[];
export const customers = customersRaw as unknown as Customer[];
export const suppliers = suppliersRaw as unknown as Supplier[];
export const items = itemsRaw as unknown as Item[];
/** 单据全链路追溯:给定销售订单号,返回 工单 → 材料需求 → 采购订单 */
export function traceSalesOrder(soNo: string) {
const so = salesOrders.find(s => s.销售订单号 === soNo) ?? null;
const wo = productionOrders.filter(p => p.来源销售订单号 === soNo);
const mats = workOrderMaterials.filter(m => m.来源销售订单号 === soNo);
const pos = purchaseOrders.filter(p => p.来源销售订单号 === soNo);
return { salesOrder: so, workOrders: wo, materials: mats, purchaseOrders: pos };
}
/** 供需汇总:按材料编码聚合应领数量与已采购数量,用于供应计划缺口分析 */
export function materialBalance() {
const demand = new Map<string, number>();
workOrderMaterials.forEach(m =>
demand.set(m.材料编码, (demand.get(m.材料编码) ?? 0) + m.应领数量));
const supplied = new Map<string, number>();
purchaseOrders.forEach(p =>
supplied.set(p.材料编码, (supplied.get(p.材料编码) ?? 0) + p.数量));
const codes = new Set([...demand.keys(), ...supplied.keys()]);
return [...codes].map(code => ({
材料编码: code,
应领数量: +(demand.get(code) ?? 0).toFixed(2),
已采购数量: +(supplied.get(code) ?? 0).toFixed(2),
缺口: +((demand.get(code) ?? 0) - (supplied.get(code) ?? 0)).toFixed(2),
})).sort((a, b) => b.缺口 - a.缺口);
}
+632
View File
@@ -0,0 +1,632 @@
[
{
"序号": 1,
"物料编码": "BA028",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 2,
"物料编码": "BA284",
"类型": "材料",
"规格型号": "10*8*3.5cm",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 3,
"物料编码": "BA285",
"类型": "材料",
"规格型号": "10*8*3.5cm",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 4,
"物料编码": "BA296",
"类型": "材料",
"规格型号": "10*8*3.5cm",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 5,
"物料编码": "BA380",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 6,
"物料编码": "BD006",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 7,
"物料编码": "BDBG01",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 8,
"物料编码": "BG-001",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 9,
"物料编码": "BJ-5341",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 10,
"物料编码": "BJ040",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 11,
"物料编码": "BKC026",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 12,
"物料编码": "BKC027",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 13,
"物料编码": "BKC028",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 14,
"物料编码": "BN001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 15,
"物料编码": "BN002",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 16,
"物料编码": "BZA25090-1",
"类型": "材料",
"规格型号": null,
"计量单位": "KG",
"BOM版本": "V1.0",
"数据来源": "BOM展开"
},
{
"序号": 17,
"物料编码": "FABG001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 18,
"物料编码": "FABJ008",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 19,
"物料编码": "FAFP011",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 20,
"物料编码": "FAJZ0005",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 21,
"物料编码": "FANBLA011",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 22,
"物料编码": "FANBLA012",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 23,
"物料编码": "FANBLA057",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 24,
"物料编码": "FASJ052",
"类型": "材料",
"规格型号": "50*45*32.5",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 25,
"物料编码": "FASJ056",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 26,
"物料编码": "FASJLH024",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 27,
"物料编码": "FASJLH026",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 28,
"物料编码": "FASTN001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 29,
"物料编码": "FASTN002",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 30,
"物料编码": "FAXTL022",
"类型": "材料",
"规格型号": "31*25.5*27",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 31,
"物料编码": "FAZSM007",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 32,
"物料编码": "FAZSM011",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 33,
"物料编码": "FBBXD007",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 34,
"物料编码": "FBBXM029",
"类型": "材料",
"规格型号": "35*25.3cm",
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 35,
"物料编码": "FCBG001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 36,
"物料编码": "FEDRF015",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 37,
"物料编码": "FEJZ005",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 38,
"物料编码": "FESJLH023",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 39,
"物料编码": "FESJLH025",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 40,
"物料编码": "FEXTL012",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 41,
"物料编码": "FFJLY022",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 42,
"物料编码": "FFJLY026",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 43,
"物料编码": "FFSJ022",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "BOM展开"
},
{
"序号": 44,
"物料编码": "FFSJ023",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 45,
"物料编码": "FFZSM001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 46,
"物料编码": "FFZSM004",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 47,
"物料编码": "FHBSJLH024",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 48,
"物料编码": "FHCJZ001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 49,
"物料编码": "FHSTN001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 50,
"物料编码": "FHSTN002",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 51,
"物料编码": "FHSTN003",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 52,
"物料编码": "FHSTN004",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 53,
"物料编码": "FLBG001",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 54,
"物料编码": "FMD007",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 55,
"物料编码": "FMD019",
"类型": "材料",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "采购需求反推"
},
{
"序号": 56,
"物料编码": "FP-LJD-2",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 57,
"物料编码": "GJQ5001",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 58,
"物料编码": "GJQ6001",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 59,
"物料编码": "GSH007-C-029KC",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 60,
"物料编码": "GSL023-M1",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 61,
"物料编码": "JDJZ-0987",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 62,
"物料编码": "LHGB006",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 63,
"物料编码": "LHGB008",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 64,
"物料编码": "LSMM031",
"类型": "成品",
"规格型号": "25cm*55m*0.9s",
"计量单位": "PCS",
"BOM版本": "V1.0",
"数据来源": "销售订单/生产工单"
},
{
"序号": 65,
"物料编码": "SJ-LBT-5898",
"类型": "成品",
"规格型号": "10*8*3.5cm*6片",
"计量单位": "PCS",
"BOM版本": "v1.0",
"数据来源": "销售订单/生产工单"
},
{
"序号": 66,
"物料编码": "SJ-LBT-5911",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 67,
"物料编码": "XJB-9734",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 68,
"物料编码": "XJB-9749",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 69,
"物料编码": "XTL-0109",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
},
{
"序号": 70,
"物料编码": "XTL-0110",
"类型": "成品",
"规格型号": null,
"计量单位": "PCS",
"BOM版本": null,
"数据来源": "销售订单/生产工单"
}
]
@@ -0,0 +1,257 @@
[
{
"序号": 1,
"工单号": "WO-W202610161037",
"来源销售订单号": "W202610161037",
"产品编码": "GSH007-C-029KC",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 2880,
"生产车间": "分卷组",
"预计开工日期": "2026-11-04",
"预计完工日期": "2026-11-11",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 2,
"工单号": "WO-W202610161036",
"来源销售订单号": "W202610161036",
"产品编码": "GSL023-M1",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 2690,
"生产车间": "分卷组",
"预计开工日期": "2026-12-19",
"预计完工日期": "2026-12-26",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 3,
"工单号": "WO-L20261015638",
"来源销售订单号": "L20261015638",
"产品编码": "XTL-0110",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 7200,
"生产车间": "分卷组",
"预计开工日期": "2026-10-27",
"预计完工日期": "2026-11-06",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 4,
"工单号": "WO-L20261015637",
"来源销售订单号": "L20261015637",
"产品编码": "XTL-0109",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 4800,
"生产车间": "分卷组",
"预计开工日期": "2026-10-30",
"预计完工日期": "2026-11-06",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 5,
"工单号": "WO-L20261014635",
"来源销售订单号": "L20261014635",
"产品编码": "JDJZ-0987",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 5000,
"生产车间": "分卷组",
"预计开工日期": "2026-10-29",
"预计完工日期": "2026-11-08",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 6,
"工单号": "WO-L20261014634",
"来源销售订单号": "L20261014634",
"产品编码": "GJQ5001",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 19980,
"生产车间": "分卷组",
"预计开工日期": "2026-10-24",
"预计完工日期": "2026-11-03",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 7,
"工单号": "WO-W202610141021",
"来源销售订单号": "W202610141021",
"产品编码": "FP-LJD-2",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 24000,
"生产车间": "分卷组",
"预计开工日期": "2026-10-20",
"预计完工日期": "2026-11-03",
"生产周期(天)": 14,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 8,
"工单号": "WO-L20261014631",
"来源销售订单号": "L20261014631",
"产品编码": "SJ-LBT-5911",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 10080,
"生产车间": "分卷组",
"预计开工日期": "2026-10-24",
"预计完工日期": "2026-11-03",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 9,
"工单号": "WO-L20261014630",
"来源销售订单号": "L20261014630",
"产品编码": "SJ-LBT-5898",
"规格型号": "10*8*3.5cm*6片",
"计量单位": "PCS",
"生产数量": 10080,
"生产车间": "手工包装组",
"预计开工日期": "2026-10-24",
"预计完工日期": "2026-11-03",
"生产周期(天)": 10,
"BOM版本": "v1.0",
"单据状态": "已下达"
},
{
"序号": 10,
"工单号": "WO-L20261012621",
"来源销售订单号": "L20261012621",
"产品编码": "GJQ6001",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 10080,
"生产车间": "分卷组",
"预计开工日期": "2026-10-24",
"预计完工日期": "2026-11-03",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 11,
"工单号": "WO-Z20261013492",
"来源销售订单号": "Z20261013492",
"产品编码": "BG-001",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 5000,
"生产车间": "分卷组",
"预计开工日期": "2026-11-01",
"预计完工日期": "2026-11-11",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 12,
"工单号": "WO-WC20261013060",
"来源销售订单号": "WC20261013060",
"产品编码": "LHGB008",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 4800,
"生产车间": "分卷组",
"预计开工日期": "2026-10-28",
"预计完工日期": "2026-11-04",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 13,
"工单号": "WO-W202610131020",
"来源销售订单号": "W202610131020",
"产品编码": "LHGB006",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 4800,
"生产车间": "分卷组",
"预计开工日期": "2026-10-28",
"预计完工日期": "2026-11-04",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 14,
"工单号": "WO-W202610131017",
"来源销售订单号": "W202610131017",
"产品编码": "XJB-9734",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 9990,
"生产车间": "分卷组",
"预计开工日期": "2026-10-24",
"预计完工日期": "2026-11-03",
"生产周期(天)": 10,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 15,
"工单号": "WO-W202610131016",
"来源销售订单号": "W202610131016",
"产品编码": "XJB-9749",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 20010,
"生产车间": "分卷组",
"预计开工日期": "2026-10-20",
"预计完工日期": "2026-11-03",
"生产周期(天)": 14,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 16,
"工单号": "WO-Z20261012490",
"来源销售订单号": "Z20261012490",
"产品编码": "BJ-5341",
"规格型号": null,
"计量单位": "PCS",
"生产数量": 3600,
"生产车间": "分卷组",
"预计开工日期": "2026-11-03",
"预计完工日期": "2026-11-10",
"生产周期(天)": 7,
"BOM版本": "—",
"单据状态": "已下达"
},
{
"序号": 17,
"工单号": "WO-W20260629448",
"来源销售订单号": "W20260629448",
"产品编码": "LSMM031",
"规格型号": "25cm*55m*0.9s",
"计量单位": "PCS",
"生产数量": 4504,
"生产车间": "分卷组",
"预计开工日期": "2026-07-14",
"预计完工日期": "2026-07-21",
"生产周期(天)": 7,
"BOM版本": "V1.0",
"单据状态": "已完工"
}
]
@@ -0,0 +1,866 @@
[
{
"序号": 1,
"采购订单号": "PO-2026-06-0319",
"采购日期": "2026-06-30",
"来源销售订单号": "W20260629448",
"产品工单号": "WO-W20260629448",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FAXTL022",
"数量": 150,
"单价": 1.97,
"含税金额": 295.5,
"预计到货日期": "2026-07-07",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 2,
"采购订单号": "PO-2026-06-0329",
"采购日期": "2026-06-30",
"来源销售订单号": "W20260629448",
"产品工单号": "WO-W20260629448",
"供应商编码": "GC0012",
"供应商简称": "GTZG",
"材料编码": "FBBXM029",
"数量": 1000,
"单价": 0.22,
"含税金额": 220,
"预计到货日期": "2026-07-07",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 3,
"采购订单号": "PO-2026-10-0128",
"采购日期": "2026-10-14",
"来源销售订单号": "W202610131020",
"产品工单号": "WO-W202610131020",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FESJLH023",
"数量": 4800,
"单价": 0.12,
"含税金额": 576,
"预计到货日期": "2026-10-20",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 4,
"采购订单号": "PO-2026-10-0128",
"采购日期": "2026-10-14",
"来源销售订单号": "WC20261013060",
"产品工单号": "WO-WC20261013060",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FESJLH025",
"数量": 4800,
"单价": 0.12,
"含税金额": 576,
"预计到货日期": "2026-10-19",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 5,
"采购订单号": "PO-2026-10-0128",
"采购日期": "2026-10-14",
"来源销售订单号": "W202610131020",
"产品工单号": "WO-W202610131020",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHBSJLH024",
"数量": 400,
"单价": 0.022,
"含税金额": 8.8,
"预计到货日期": "2026-10-20",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 6,
"采购订单号": "PO-2026-10-0132",
"采购日期": "2026-10-14",
"来源销售订单号": "W202610131020",
"产品工单号": "WO-W202610131020",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FASJLH024",
"数量": 200,
"单价": 2.15,
"含税金额": 430,
"预计到货日期": "2026-10-20",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 7,
"采购订单号": "PO-2026-10-0132",
"采购日期": "2026-10-14",
"来源销售订单号": "WC20261013060",
"产品工单号": "WO-WC20261013060",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FASJLH026",
"数量": 200,
"单价": 2.78,
"含税金额": 556,
"预计到货日期": "2026-10-19",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 8,
"采购订单号": "PO-2026-10-0135",
"采购日期": "2026-10-14",
"来源销售订单号": "Z20261013492",
"产品工单号": "WO-Z20261013492",
"供应商编码": "GE0001",
"供应商简称": "JJBT",
"材料编码": "BDBG01",
"数量": 4800,
"单价": 0.82,
"含税金额": 3936,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 9,
"采购订单号": "PO-2026-10-0136",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261013492",
"产品工单号": "WO-Z20261013492",
"供应商编码": "GC0055",
"供应商简称": "YCSDFQJLBZYXGS",
"材料编码": "FLBG001",
"数量": 5000,
"单价": 0.052,
"含税金额": 260,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 10,
"采购订单号": "PO-2026-10-0138",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014630",
"产品工单号": "WO-L20261014630",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BA284",
"数量": 19460,
"单价": 0.3,
"含税金额": 5838,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 11,
"采购订单号": "PO-2026-10-0138",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014630",
"产品工单号": "WO-L20261014630",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BA285",
"数量": 19860,
"单价": 0.3,
"含税金额": 5958,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 12,
"采购订单号": "PO-2026-10-0138",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014630",
"产品工单号": "WO-L20261014630",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BA296",
"数量": 19860,
"单价": 0.3,
"含税金额": 5958,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 13,
"采购订单号": "PO-2026-10-0138",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261013492",
"产品工单号": "WO-Z20261013492",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BA380",
"数量": 10000,
"单价": 0.5,
"含税金额": 5000,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 14,
"采购订单号": "PO-2026-10-0139",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261013492",
"产品工单号": "WO-Z20261013492",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FCBG001",
"数量": 5000,
"单价": 0.08,
"含税金额": 400,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 15,
"采购订单号": "PO-2026-10-0139",
"采购日期": "2026-10-15",
"来源销售订单号": "W202610141021",
"产品工单号": "WO-W202610141021",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FEDRF015",
"数量": 21000,
"单价": 0.078,
"含税金额": 1638,
"预计到货日期": "2026-10-22",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 16,
"采购订单号": "PO-2026-10-0140",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014631",
"产品工单号": "WO-L20261014631",
"供应商编码": "GE0070",
"供应商简称": "ZJGHYRJSTYXGS",
"材料编码": "BN001",
"数量": 9790,
"单价": 1.65,
"含税金额": 16153.5,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 17,
"采购订单号": "PO-2026-10-0140",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014631",
"产品工单号": "WO-L20261014631",
"供应商编码": "GE0070",
"供应商简称": "ZJGHYRJSTYXGS",
"材料编码": "BN002",
"数量": 10080,
"单价": 1.65,
"含税金额": 16632,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 18,
"采购订单号": "PO-2026-10-0141",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261012621",
"产品工单号": "WO-L20261012621",
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"材料编码": "FFJLY026",
"数量": 30000,
"单价": 0.176,
"含税金额": 5280,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 19,
"采购订单号": "PO-2026-10-0145",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014630",
"产品工单号": "WO-L20261014630",
"供应商编码": "GC0020",
"供应商简称": "WXSXHYSYXGS",
"材料编码": "FFSJ022",
"数量": 10080,
"单价": 0.26,
"含税金额": 2620.8,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 20,
"采购订单号": "PO-2026-10-0145",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014631",
"产品工单号": "WO-L20261014631",
"供应商编码": "GC0020",
"供应商简称": "WXSXHYSYXGS",
"材料编码": "FFSJ023",
"数量": 10080,
"单价": 0.17,
"含税金额": 1713.6,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 21,
"采购订单号": "PO-2026-10-0146",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261012621",
"产品工单号": "WO-L20261012621",
"供应商编码": "GE0005",
"供应商简称": "JSYJ",
"材料编码": "GJQ6001",
"数量": 10080,
"单价": 1.8,
"含税金额": 18144,
"预计到货日期": "2026-11-05",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 22,
"采购订单号": "PO-2026-10-0147",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261013492",
"产品工单号": "WO-Z20261013492",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FABG001",
"数量": 50,
"单价": 5.35,
"含税金额": 267.5,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 23,
"采购订单号": "PO-2026-10-0148",
"采购日期": "2026-10-15",
"来源销售订单号": "W202610141021",
"产品工单号": "WO-W202610141021",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FAFP011",
"数量": 800,
"单价": 2.11,
"含税金额": 1688,
"预计到货日期": "2026-10-24",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 24,
"采购订单号": "PO-2026-10-0148",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014630",
"产品工单号": "WO-L20261014630",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FASJ052",
"数量": 280,
"单价": 4.7,
"含税金额": 1316,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 25,
"采购订单号": "PO-2026-10-0148",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014631",
"产品工单号": "WO-L20261014631",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FASJ056",
"数量": 280,
"单价": 1.88,
"含税金额": 526.4,
"预计到货日期": "2026-10-31",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 26,
"采购订单号": "PO-2026-10-0149",
"采购日期": "2026-10-15",
"来源销售订单号": "WC20261013060",
"产品工单号": "WO-WC20261013060",
"供应商编码": "GE0047",
"供应商简称": "RYSYTZYXGS",
"材料编码": "LHGB008",
"数量": 4800,
"单价": 5.96,
"含税金额": 28608,
"预计到货日期": "2026-11-06",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 27,
"采购订单号": "PO-2026-10-0153",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261012490",
"产品工单号": "WO-Z20261012490",
"供应商编码": "GE0009",
"供应商简称": "SZYL",
"材料编码": "BKC026",
"数量": 3600,
"单价": 0.66,
"含税金额": 2376,
"预计到货日期": "2026-11-12",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 28,
"采购订单号": "PO-2026-10-0153",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261012490",
"产品工单号": "WO-Z20261012490",
"供应商编码": "GE0009",
"供应商简称": "SZYL",
"材料编码": "BKC027",
"数量": 3600,
"单价": 0.66,
"含税金额": 2376,
"预计到货日期": "2026-11-12",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 29,
"采购订单号": "PO-2026-10-0153",
"采购日期": "2026-10-15",
"来源销售订单号": "Z20261012490",
"产品工单号": "WO-Z20261012490",
"供应商编码": "GE0009",
"供应商简称": "SZYL",
"材料编码": "BKC028",
"数量": 3600,
"单价": 0.66,
"含税金额": 2376,
"预计到货日期": "2026-11-12",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 30,
"采购订单号": "PO-2026-10-0156",
"采购日期": "2026-10-15",
"来源销售订单号": "L20261014635",
"产品工单号": "WO-L20261014635",
"供应商编码": "GC0011",
"供应商简称": "YLZG",
"材料编码": "FBBXD007",
"数量": 5000,
"单价": 0.146,
"含税金额": 730,
"预计到货日期": "2026-11-01",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 31,
"采购订单号": "PO-2026-10-0159",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610131017",
"产品工单号": "WO-W202610131017",
"供应商编码": "GC0032",
"供应商简称": "JSLBXCLKJYXGS",
"材料编码": "FMD007",
"数量": 29970,
"单价": 0.012,
"含税金额": 359.64,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 32,
"采购订单号": "PO-2026-10-0159",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014635",
"产品工单号": "WO-L20261014635",
"供应商编码": "GC0032",
"供应商简称": "JSLBXCLKJYXGS",
"材料编码": "FMD019",
"数量": 5000,
"单价": 0.046,
"含税金额": 230,
"预计到货日期": "2026-11-01",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 33,
"采购订单号": "PO-2026-10-0160",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014635",
"产品工单号": "WO-L20261014635",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FEJZ005",
"数量": 5000,
"单价": 0.09,
"含税金额": 450,
"预计到货日期": "2026-11-01",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 34,
"采购订单号": "PO-2026-10-0160",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014635",
"产品工单号": "WO-L20261014635",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHCJZ001",
"数量": 10000,
"单价": 0.023,
"含税金额": 230,
"预计到货日期": "2026-11-01",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 35,
"采购订单号": "PO-2026-10-0162",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014634",
"产品工单号": "WO-L20261014634",
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"材料编码": "FFJLY022",
"数量": 19980,
"单价": 0.245,
"含税金额": 4895.1,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 36,
"采购订单号": "PO-2026-10-0162",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610131017",
"产品工单号": "WO-W202610131017",
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"材料编码": "FFZSM001",
"数量": 9990,
"单价": 0.165,
"含税金额": 1648.35,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 37,
"采购订单号": "PO-2026-10-0162",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610131016",
"产品工单号": "WO-W202610131016",
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"材料编码": "FFZSM004",
"数量": 20010,
"单价": 0.283,
"含税金额": 5662.83,
"预计到货日期": "2026-10-29",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 38,
"采购订单号": "PO-2026-10-0164",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014634",
"产品工单号": "WO-L20261014634",
"供应商编码": "GE0005",
"供应商简称": "JSYJ",
"材料编码": "GJQ5001",
"数量": 19980,
"单价": 2.57,
"含税金额": 51348.6,
"预计到货日期": "2026-11-05",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 39,
"采购订单号": "PO-2026-10-0165",
"采购日期": "2026-10-16",
"来源销售订单号": "Z20261012490",
"产品工单号": "WO-Z20261012490",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FABJ008",
"数量": 120,
"单价": 2.29,
"含税金额": 274.8,
"预计到货日期": "2026-11-12",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 40,
"采购订单号": "PO-2026-10-0166",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610131017",
"产品工单号": "WO-W202610131017",
"供应商编码": "GC0078",
"供应商简称": "JSXYYWKJYXGS",
"材料编码": "FAZSM007",
"数量": 333,
"单价": 2.43,
"含税金额": 809.19,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 41,
"采购订单号": "PO-2026-10-0166",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610131016",
"产品工单号": "WO-W202610131016",
"供应商编码": "GC0078",
"供应商简称": "JSXYYWKJYXGS",
"材料编码": "FAZSM011",
"数量": 667,
"单价": 4.41,
"含税金额": 2941.47,
"预计到货日期": "2026-10-29",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 42,
"采购订单号": "PO-2026-10-0168",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261014635",
"产品工单号": "WO-L20261014635",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FAJZ0005",
"数量": 250,
"单价": 3.26,
"含税金额": 815,
"预计到货日期": "2026-11-07",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 43,
"采购订单号": "PO-2026-10-0171",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015637",
"产品工单号": "WO-L20261015637",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BA028",
"数量": 19200,
"单价": 0.35,
"含税金额": 6720,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 44,
"采购订单号": "PO-2026-10-0171",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015638",
"产品工单号": "WO-L20261015638",
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"材料编码": "BD006",
"数量": 7200,
"单价": 0.3296,
"含税金额": 2373.12,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 45,
"采购订单号": "PO-2026-10-0175",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610161036",
"产品工单号": "WO-W202610161036",
"供应商编码": "GE0021",
"供应商简称": "KJSL",
"材料编码": "BJ040",
"数量": 2690,
"单价": 4.1,
"含税金额": 11029,
"预计到货日期": "2026-12-01",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 46,
"采购订单号": "PO-2026-10-0176",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610161037",
"产品工单号": "WO-W202610161037",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FANBLA011",
"数量": 60,
"单价": 1.55,
"含税金额": 93,
"预计到货日期": "2026-10-26",
"订单状态": "未审",
"来源单据": "请购单"
},
{
"序号": 47,
"采购订单号": "PO-2026-10-0176",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610161037",
"产品工单号": "WO-W202610161037",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FANBLA012",
"数量": 20,
"单价": 5.54,
"含税金额": 110.8,
"预计到货日期": "2026-10-26",
"订单状态": "未审",
"来源单据": "请购单"
},
{
"序号": 48,
"采购订单号": "PO-2026-10-0176",
"采购日期": "2026-10-16",
"来源销售订单号": "W202610161036",
"产品工单号": "WO-W202610161036",
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"材料编码": "FANBLA057",
"数量": 56,
"单价": 4.94,
"含税金额": 276.64,
"预计到货日期": "2026-12-01",
"订单状态": "未审",
"来源单据": "请购单"
},
{
"序号": 49,
"采购订单号": "PO-2026-10-0177",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015637",
"产品工单号": "WO-L20261015637",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FASTN001",
"数量": 400,
"单价": 2.11,
"含税金额": 844,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 50,
"采购订单号": "PO-2026-10-0177",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015638",
"产品工单号": "WO-L20261015638",
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"材料编码": "FASTN002",
"数量": 300,
"单价": 2.2655,
"含税金额": 679.65,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 51,
"采购订单号": "PO-2026-10-0179",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015637",
"产品工单号": "WO-L20261015637",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHSTN001",
"数量": 800,
"单价": 0.05,
"含税金额": 40,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 52,
"采购订单号": "PO-2026-10-0179",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015637",
"产品工单号": "WO-L20261015637",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHSTN002",
"数量": 800,
"单价": 0.1,
"含税金额": 80,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 53,
"采购订单号": "PO-2026-10-0179",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015638",
"产品工单号": "WO-L20261015638",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHSTN003",
"数量": 600,
"单价": 0.05,
"含税金额": 30,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
},
{
"序号": 54,
"采购订单号": "PO-2026-10-0179",
"采购日期": "2026-10-16",
"来源销售订单号": "L20261015638",
"产品工单号": "WO-L20261015638",
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"材料编码": "FHSTN004",
"数量": 600,
"单价": 0.1,
"含税金额": 60,
"预计到货日期": "2026-10-30",
"订单状态": "生效",
"来源单据": "请购单"
}
]
@@ -0,0 +1,274 @@
[
{
"序号": 1,
"销售订单号": "W202610161037",
"单据日期": "2026-10-16",
"客户编码": "KA0033",
"客户分类": "OEM开票",
"客户简称": "NBLARYPYXGS",
"产品编码": "GSH007-C-029KC",
"数量": 2880,
"含税单价": 0.62,
"含税金额": 1785.6,
"预计发货日期": "2026-11-13",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 2,
"销售订单号": "W202610161036",
"单据日期": "2026-10-15",
"客户编码": "KA0033",
"客户分类": "OEM开票",
"客户简称": "NBLARYPYXGS",
"产品编码": "GSL023-M1",
"数量": 2690,
"含税单价": 5.47,
"含税金额": 14714.3,
"预计发货日期": "2026-12-28",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 3,
"销售订单号": "L20261015638",
"单据日期": "2026-10-15",
"客户编码": "KA0124",
"客户分类": "OEM开票",
"客户简称": "TJSTNGJMYYXGS",
"产品编码": "XTL-0110",
"数量": 7200,
"含税单价": 2.6,
"含税金额": 18720,
"预计发货日期": "2026-11-08",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 4,
"销售订单号": "L20261015637",
"单据日期": "2026-10-15",
"客户编码": "KA0124",
"客户分类": "OEM开票",
"客户简称": "TJSTNGJMYYXGS",
"产品编码": "XTL-0109",
"数量": 4800,
"含税单价": 2.55,
"含税金额": 12240,
"预计发货日期": "2026-11-08",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 5,
"销售订单号": "L20261014635",
"单据日期": "2026-10-15",
"客户编码": "GM0045",
"客户分类": "杂项开票",
"客户简称": "YCSFHWLYXGS",
"产品编码": "JDJZ-0987",
"数量": 5000,
"含税单价": 10.7,
"含税金额": 53500,
"预计发货日期": "2026-11-10",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 6,
"销售订单号": "L20261014634",
"单据日期": "2026-10-15",
"客户编码": "GM0045",
"客户分类": "杂项开票",
"客户简称": "YCSFHWLYXGS",
"产品编码": "GJQ5001",
"数量": 19980,
"含税单价": 4.36,
"含税金额": 87112.8,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 7,
"销售订单号": "W202610141021",
"单据日期": "2026-10-14",
"客户编码": "KA0090",
"客户分类": "OEM开票",
"客户简称": "KCTZ(ZG)YXGS",
"产品编码": "FP-LJD-2",
"数量": 24000,
"含税单价": 4.8,
"含税金额": 115200,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 8,
"销售订单号": "L20261014631",
"单据日期": "2026-10-14",
"客户编码": "KA0116",
"客户分类": "OEM开票",
"客户简称": "NBJQHYGMYXGS",
"产品编码": "SJ-LBT-5911",
"数量": 10080,
"含税单价": 5.25,
"含税金额": 52920,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 9,
"销售订单号": "L20261014630",
"单据日期": "2026-10-14",
"客户编码": "KA0116",
"客户分类": "OEM开票",
"客户简称": "NBJQHYGMYXGS",
"产品编码": "SJ-LBT-5898",
"数量": 10080,
"含税单价": 3.63,
"含税金额": 36590.4,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 10,
"销售订单号": "L20261012621",
"单据日期": "2026-10-14",
"客户编码": "KA0049",
"客户分类": "OEM开票",
"客户简称": "ZJJLYZFZPXSYXGS",
"产品编码": "GJQ6001",
"数量": 10080,
"含税单价": 2.73,
"含税金额": 27518.4,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "吴东琴",
"单据状态": "生效"
},
{
"序号": 11,
"销售订单号": "Z20261013492",
"单据日期": "2026-10-13",
"客户编码": "KA0210",
"客户分类": "OEM开票",
"客户简称": "BGGGCZ(GZ)YXGS",
"产品编码": "BG-001",
"数量": 5000,
"含税单价": 4.37,
"含税金额": 21850,
"预计发货日期": "2026-11-13",
"仓库名称": "OEM事业部成品仓",
"制单人": "赵广粉",
"单据状态": "生效"
},
{
"序号": 12,
"销售订单号": "WC20261013060",
"单据日期": "2026-10-13",
"客户编码": "KA0099",
"客户分类": "OEM开票",
"客户简称": "ZJSJLHWLPSYXGS",
"产品编码": "LHGB008",
"数量": 4800,
"含税单价": 7.9,
"含税金额": 37920,
"预计发货日期": "2026-11-06",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 13,
"销售订单号": "W202610131020",
"单据日期": "2026-10-13",
"客户编码": "KA0099",
"客户分类": "OEM开票",
"客户简称": "ZJSJLHWLPSYXGS",
"产品编码": "LHGB006",
"数量": 4800,
"含税单价": 5.1,
"含税金额": 24480,
"预计发货日期": "2026-11-06",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 14,
"销售订单号": "W202610131017",
"单据日期": "2026-10-13",
"客户编码": "KA0162",
"客户分类": "OEM开票",
"客户简称": "ZSMGYL(SY)YXGS",
"产品编码": "XJB-9734",
"数量": 9990,
"含税单价": 2.79,
"含税金额": 27872.1,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 15,
"销售订单号": "W202610131016",
"单据日期": "2026-10-13",
"客户编码": "KA0162",
"客户分类": "OEM开票",
"客户简称": "ZSMGYL(SY)YXGS",
"产品编码": "XJB-9749",
"数量": 20010,
"含税单价": 4.7,
"含税金额": 94047,
"预计发货日期": "2026-11-05",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
},
{
"序号": 16,
"销售订单号": "Z20261012490",
"单据日期": "2026-10-12",
"客户编码": "KA0154",
"客户分类": "OEM开票",
"客户简称": "HNZQNGYLGLYXGS",
"产品编码": "BJ-5341",
"数量": 3600,
"含税单价": 3.9,
"含税金额": 14040,
"预计发货日期": "2026-11-12",
"仓库名称": "OEM事业部成品仓",
"制单人": "赵广粉",
"单据状态": "生效"
},
{
"序号": 17,
"销售订单号": "W20260629448",
"单据日期": "2026-06-29",
"客户编码": "KA0087",
"客户分类": "OEM开票",
"客户简称": "LSMMJJYP(ZJ)YXGS",
"产品编码": "LSMM031",
"数量": 4504,
"含税单价": 2.406,
"含税金额": 10836.62,
"预计发货日期": "2026-07-23",
"仓库名称": "OEM事业部成品仓",
"制单人": "王晓静",
"单据状态": "生效"
}
]
@@ -0,0 +1,172 @@
[
{
"序号": 1,
"供应商编码": "GC0001",
"供应商简称": "FYBZ",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 6,
"采购金额": 3051.95
},
{
"序号": 2,
"供应商编码": "GC0003",
"供应商简称": "JSFY",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 11,
"采购金额": 4088.8
},
{
"序号": 3,
"供应商编码": "GC0011",
"供应商简称": "YLZG",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 730
},
{
"序号": 4,
"供应商编码": "GC0012",
"供应商简称": "GTZG",
"性质": "客户/供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 220
},
{
"序号": 5,
"供应商编码": "GC0020",
"供应商简称": "WXSXHYSYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 4334.4
},
{
"序号": 6,
"供应商编码": "GC0032",
"供应商简称": "JSLBXCLKJYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 589.64
},
{
"序号": 7,
"供应商编码": "GC0040",
"供应商简称": "YCSDFJCZXYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 8,
"采购金额": 5121.34
},
{
"序号": 8,
"供应商编码": "GC0055",
"供应商简称": "YCSDFQJLBZYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 260
},
{
"序号": 9,
"供应商编码": "GC0078",
"供应商简称": "JSXYYWKJYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 3750.66
},
{
"序号": 10,
"供应商编码": "GC0079",
"供应商简称": "YCDFWYYSBZYXGS",
"性质": "供应商",
"所属类别": "辅料开票",
"分管部门": "采购科",
"采购行数": 4,
"采购金额": 17486.28
},
{
"序号": 11,
"供应商编码": "GE0001",
"供应商简称": "JJBT",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 3936
},
{
"序号": 12,
"供应商编码": "GE0004",
"供应商简称": "HFHM",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 6,
"采购金额": 31847.12
},
{
"序号": 13,
"供应商编码": "GE0005",
"供应商简称": "JSYJ",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 69492.6
},
{
"序号": 14,
"供应商编码": "GE0009",
"供应商简称": "SZYL",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 3,
"采购金额": 7128
},
{
"序号": 15,
"供应商编码": "GE0021",
"供应商简称": "KJSL",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 1,
"采购金额": 11029
},
{
"序号": 16,
"供应商编码": "GE0047",
"供应商简称": "RYSYTZYXGS",
"性质": "客户/供应商",
"所属类别": "外购半成品开票",
"分管部门": null,
"采购行数": 1,
"采购金额": 28608
},
{
"序号": 17,
"供应商编码": "GE0070",
"供应商简称": "ZJGHYRJSTYXGS",
"性质": "供应商",
"所属类别": "外购半成品开票",
"分管部门": "采购科",
"采购行数": 2,
"采购金额": 32785.5
}
]
File diff suppressed because it is too large Load Diff
+110
View File
@@ -0,0 +1,110 @@
/**
* 知识库 ↔ 特征建模 跨层映射。
*
* 知识库切片里的「所属特征树」是形如 `SRV-2U-620.焊接.激光焊焊瘤` 的语义码;
* 特征建模侧(DS-01/08/09/12)的实例 id 是料号 / 结构特征维度 / 试验号等。
* 二者无法直接字符串匹配,因此这里维护一份精选映射表,并反向构建索引,
* 供两侧页面做双向跳转。
*/
import { RoleKey, roleDocs } from './knowledge';
export interface FeatureRef {
/** 特征建模中的对象 key,例如 'DS-09' */
objKey: string;
/** 特征建模中的实例 id;省略表示映射到对象层 */
instanceId?: string;
/** 为什么这两个东西相关(一句话,展示在跳转入口里) */
why: string;
}
export interface KbRef {
role: RoleKey;
chunkId: string;
/** 一句话摘要,用于特征建模侧「知识引用」列表 */
label: string;
/** 对应的特征码 */
code: string;
}
/**
* 精选映射:每个知识库特征码 → 一个或多个特征建模落点。
* 映射以「工序 + 缺陷/特征」语义为准,优先选择最能支撑该切片结论的实例。
*/
export const FEATURE_LINKS: Record<string, FeatureRef[]> = {
'SRV-2U-620.NCT.手工倒角': [
{ objKey: 'DS-01', instanceId: 'SRV2U-BASE-01', why: '机箱底座(双侧折弯 + R 角)是去毛刺 / 倒角高发场景' },
],
'SRV-2U-620.NCT.孔位': [
{ objKey: 'DS-01', instanceId: 'SRV2U-FANW-01', why: '风扇墙含大量网孔阵列,是同机型冲压 / 孔位特征' },
],
'SRV-2U-620.折弯.回弹补偿': [
{ objKey: 'DS-01', instanceId: 'SRV2U-TOP-01', why: '机箱上盖为四边折弯结构,是回弹补偿关键件' },
],
'SRV-2U-620.焊接.激光焊焊瘤': [
{ objKey: 'DS-09', instanceId: '密集焊点(≥12 点)', why: 'DS-09 中焊瘤率最高的结构特征维度(0.141)' },
{ objKey: 'DS-12', instanceId: 'T5', why: 'DOE 推荐组合(1200W / 气 15 / 焊速 38)可抑制焊瘤' },
],
'SRV-2U-620.焊接.焊接变形': [
{ objKey: 'DS-09', instanceId: '长条形(>400mm)', why: 'DS-09 中焊接变形率最高的结构特征维度(0.087)' },
],
'SRV-2U-620.表面处理.色差': [
{ objKey: 'DS-09', instanceId: '镀层板(SGCC)', why: '镀层板表面处理对色差最敏感' },
{ objKey: 'DS-01', instanceId: 'SRV2U-HDDCAGE-01', why: '同机型 SGCC 材质件' },
],
};
export const featureRefsOf = (code?: string): FeatureRef[] => FEATURE_LINKS[code ?? ''] ?? [];
const INDEX_KEY = (objKey: string, instanceId?: string) => `${objKey}#${instanceId ?? ''}`;
const shortLabel = (text: string, max = 22) => {
if (text.length <= max) return text;
return text.slice(0, max) + '…';
};
const buildIndex = () => {
const idx = new Map<string, KbRef[]>();
for (const doc of roleDocs) {
const treeCol = doc.chunkCols.find(c => c.includes('特征树'));
if (!treeCol) continue;
for (const ch of doc.chunks) {
const code = ch.cells[treeCol];
if (!code) continue;
const refs = FEATURE_LINKS[code];
if (!refs) continue;
for (const ref of refs) {
const k = INDEX_KEY(ref.objKey, ref.instanceId);
const arr = idx.get(k) ?? [];
if (!arr.some(r => r.role === doc.role && r.chunkId === ch.id && r.code === code)) {
arr.push({ role: doc.role, chunkId: ch.id, label: shortLabel(ch.text), code });
idx.set(k, arr);
}
}
}
}
return idx;
};
const KB_INDEX = buildIndex();
/**
* 查询特征建模某对象(或某实例)被哪些知识库切片引用。
* instanceId 省略时,返回该对象下所有实例的引用。
*/
export const kbRefsFor = (objKey: string, instanceId?: string): KbRef[] => {
const exactKey = INDEX_KEY(objKey, instanceId);
const out = KB_INDEX.get(exactKey) ? [...KB_INDEX.get(exactKey)!] : [];
if (instanceId) return out;
// 对象层:再合并该对象所有实例的引用
const prefix = `${objKey}#`;
for (const [k, refs] of KB_INDEX) {
if (!k.startsWith(prefix) || k === exactKey) continue;
for (const r of refs) {
if (!out.some(x => x.role === r.role && x.chunkId === r.chunkId && x.code === r.code)) {
out.push(r);
}
}
}
return out;
};
+260
View File
@@ -0,0 +1,260 @@
/**
* 和信精密 · 品质异常预防 —— 知识库层(角色标准文件 → 切片 → 向量 / 图谱)。
*
* 这里是「知识库」舞台的数据来源,全部前端内置、不落库、不联网:
* 标准文件 PE / IE / QE / ME 四份,职责范围 / 当前实施情况 / 输入 / 输出 / 后续动作
* 直接照录用户给定的角色分工表,不另编。
* 切片 每份文件切成若干条,列头按角色口径给出(PE 用「品质问题 / 原因分析 /
* 对策建议 / 所属特征树 / 改善方」)。PE 保留唯一的实物锚点行
* 「SRV-2U-620.NCT.手工倒角」,其余为同风格模拟内容(用户明确要求「模拟」)。
* 向量 每条切片一个 12 维向量,由确定性哈希从切片文本导出(不用 Math.random,
* 保证每次渲染完全一致),仅作「已被向量化」的示意。
* 图谱 每份文件抽出实体(角色 / 输入 / 输出 / 特征树 / 缺陷码)与关系,
* 对应「已被图谱转变」的结果。
*
* 与别的数据层一样:页面不写死任何统计值,切片数 / 向量维数 / 图谱实体数都由本文件现算。
*/
export type RoleKey = 'PE' | 'IE' | 'QE' | 'ME';
export interface KbChunk {
id: string;
/** 该切片原文(自然语言),用于「原文切片」页签 */
text: string;
/** 角色口径下的字段值,键为列名;列顺序由 RoleDoc.chunkCols 决定 */
cells: Record<string, string>;
/** 12 维向量(-1 ~ 1),示意「已被向量化」 */
vector: number[];
}
export type EntKind = '角色' | '输入' | '输出' | '特征树' | '缺陷码';
export interface KbEntity { id: string; label: string; kind: EntKind }
export interface KbEdge { from: string; to: string; label: string }
export interface RoleDoc {
role: RoleKey;
/** 文件标题,例如「PE 工艺标准文件」 */
name: string;
color: string;
/** 一句话定位 */
tagline: string;
duty: string;
current: string;
inputs: string[];
outputs: string[];
followups: string[];
/** 切片表的列头(角色口径),顺序即表格列序 */
chunkCols: string[];
chunks: KbChunk[];
graph: { nodes: KbEntity[]; edges: KbEdge[] };
}
export const VECTOR_DIMS = 12;
/* ── 确定性向量:FNV-1a 哈希 → 12 维,[-1,1],纯函数、无随机 ─────────────── */
const fnv = (s: string) => {
let h = 2166136261;
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
return h >>> 0;
};
/** 同一切片的向量只取决于其文本,因此每次渲染完全一致 */
export const vectorOf = (seed: string, dims = VECTOR_DIMS): number[] =>
Array.from({ length: dims }, (_, i) => {
const h = fnv(`${seed}#${i}`);
return +(((h % 2001) / 1000 - 1)).toFixed(3);
});
/* ── 切片构造:cells 按列名给值,向量由「角色 + 首字段」导出 ───────────────── */
const chunk = (id: string, text: string, cells: Record<string, string>): KbChunk => ({
id, text, cells, vector: vectorOf(`${id}|${Object.values(cells).join('|')}`),
});
/* 角色色:沿用本体层的品牌色族,四角色各一色,深浅主题下都可读 */
export const ROLE_COLOR: Record<RoleKey, string> = {
PE: '#38bdf8', IE: '#818cf8', QE: '#f59e0b', ME: '#10b981',
};
export const roleDocs: RoleDoc[] = [
/* ─────────────────────────── PE 工艺工程师 ─────────────────────────── */
{
role: 'PE', name: 'PE 工艺标准文件', color: ROLE_COLOR.PE,
tagline: '定义产品工艺流程与结构材质要求',
duty: '定义产品工艺流程、结构材质要求',
current: '已执行,但未明确区分手工 / 设备操作',
inputs: ['历史 8D 报告', '风险检验单', '异常处理记录(需对应到特征树)', '材质 / 结构 / 工艺三类基础属性数据'],
outputs: ['风险点检单'],
followups: ['如需更改工艺则调整', '走签流程备注对其它部门的要求'],
chunkCols: ['品质问题', '原因分析', '对策建议', '所属特征树', '改善方'],
chunks: [
chunk('pe-1', '手动倒角工序常出现边缘毛刺残留,下游组装时划伤手指与线材;历史 8D-2026-014 已记录同类问题。',
{ 品质问题: '手工倒角边毛刺残留', 原因分析: '手工倒角无刀具补偿、转速不稳', 对策建议: '倒角改用气动浮动刀头并加装限位,首件全检', 所属特征树: 'SRV-2U-620.NCT.手工倒角', 改善方: 'PE' }),
chunk('pe-2', '5052 铝板折弯回弹量随板厚变化,按 Q235 系数估值导致角度普遍偏大 1.5°~2°。',
{ 品质问题: '折弯回弹超差', 原因分析: '回弹系数按 Q235 估值,未按材质分档', 对策建议: '按板厚建立回弹补偿表,折弯后 CMM 抽检', 所属特征树: 'SRV-2U-620.折弯.回弹补偿', 改善方: 'PE' }),
chunk('pe-3', '激光焊角焊缝出现焊瘤,功率与焊速未匹配,外观检验批量判定 NG。',
{ 品质问题: '激光焊焊瘤', 原因分析: '功率 1200W 与焊速 38 未匹配', 对策建议: '采用 DOE 试验 5 组合(1200W / 气 15 / 焊速 38)', 所属特征树: 'SRV-2U-620.焊接.激光焊焊瘤', 改善方: 'PE' }),
chunk('pe-4', 'NCT 冲孔后孔位偏移,与垫块装夹基准面磨损相关。',
{ 品质问题: '钣金件孔位偏移', 原因分析: '垫块装夹基准面磨损', 对策建议: '增加防错垫块 + 首件 CMM 确认', 所属特征树: 'SRV-2U-620.NCT.孔位', 改善方: 'PE' }),
chunk('pe-5', '长直焊缝焊接变形明显,平面度超差导致后续装配错位。',
{ 品质问题: '焊接变形', 原因分析: '长焊缝热输入集中', 对策建议: '分段对称焊 + 增加随行散热夹具', 所属特征树: 'SRV-2U-620.焊接.焊接变形', 改善方: 'PE' }),
chunk('pe-6', '阳极氧化后同批零件出现色差,前处理除油不彻底。',
{ 品质问题: '表面处理色差', 原因分析: '前处理除油不彻底', 对策建议: '加强前处理槽液浓度点检并留样', 所属特征树: 'SRV-2U-620.表面处理.色差', 改善方: 'PE' }),
],
graph: {
nodes: [
{ id: 'PE', label: 'PE 工艺工程师', kind: '角色' },
{ id: 'pe-8d', label: '历史 8D 报告', kind: '输入' },
{ id: 'pe-risk', label: '风险检验单', kind: '输入' },
{ id: 'pe-anom', label: '异常处理记录', kind: '输入' },
{ id: 'pe-attr', label: '材质/结构/工艺属性', kind: '输入' },
{ id: 'pe-out', label: '风险点检单', kind: '输出' },
{ id: 'pe-ft1', label: 'SRV-2U-620.NCT.手工倒角', kind: '特征树' },
{ id: 'pe-ft2', label: 'SRV-2U-620.焊接.激光焊焊瘤', kind: '特征树' },
],
edges: [
{ from: 'PE', to: 'pe-8d', label: '引用' },
{ from: 'PE', to: 'pe-anom', label: '关联' },
{ from: 'PE', to: 'pe-attr', label: '依赖' },
{ from: 'PE', to: 'pe-out', label: '产出' },
{ from: 'pe-anom', to: 'pe-ft1', label: '对应' },
{ from: 'pe-8d', to: 'pe-ft2', label: '归码' },
{ from: 'pe-out', to: 'pe-ft1', label: '覆盖' },
],
},
},
/* ─────────────────────────── IE 工业工程师 ─────────────────────────── */
{
role: 'IE', name: 'IE 工业工程标准文件', color: ROLE_COLOR.IE,
tagline: '制具开发与 SOP 制定',
duty: '制具开发、SOP 制定',
current: '承担部分 ME 职能,存在标准缺失问题',
inputs: ['跟工装、治具相关的表(验收标准卡、适用料号)'],
outputs: ['SOP 建议', '工装匹配建议', '治具匹配建议'],
followups: ['提醒常见风险', '给出配工装治具建议', '评估匹配结果'],
chunkCols: ['工艺场景', 'SOP 建议', '工装 / 治具建议', '匹配结果', '责任'],
chunks: [
chunk('ie-1', '折弯换型频繁、首件确认缺失,导致换型后前几件尺寸漂移。',
{ 工艺场景: '折弯换型', 'SOP 建议': 'SOP 增加换型后首件确认步骤', '工装 / 治具建议': '通用 2U 系列快换治具', 匹配结果: '匹配 3 个料号', 责任: 'IE' }),
chunk('ie-2', '激光焊工位缺少治具定位,手工扶持造成焊缝偏移。',
{ 工艺场景: '激光焊定位', 'SOP 建议': 'SOP 增加夹具装夹与校验步骤', '工装 / 治具建议': '焊接定位治具(带快速夹钳)', 匹配结果: '匹配 2 个机型', 责任: 'IE' }),
chunk('ie-3', 'NCT 冲孔后手工去毛刺耗时长,节拍瓶颈。',
{ 工艺场景: 'NCT 去毛刺', 'SOP 建议': 'SOP 增加去毛刺工具与手法标准', '工装 / 治具建议': '气动浮动倒角刀头', 匹配结果: '匹配 1 个专用夹具', 责任: 'IE' }),
chunk('ie-4', '组装工位工装通用化不足,换型时间超过目标节拍。',
{ 工艺场景: '组装换型', 'SOP 建议': 'SOP 增加工装点检与快换步骤', '工装 / 治具建议': '组装通用治具(通用 2U 系列)', 匹配结果: '匹配 3 个料号', 责任: 'IE' }),
],
graph: {
nodes: [
{ id: 'IE', label: 'IE 工业工程师', kind: '角色' },
{ id: 'ie-tools', label: '工装 / 治具相关表', kind: '输入' },
{ id: 'ie-acc', label: '验收标准卡', kind: '输入' },
{ id: 'ie-sop', label: 'SOP 建议', kind: '输出' },
{ id: 'ie-fix', label: '工装匹配建议', kind: '输出' },
{ id: 'ie-jig', label: '治具匹配建议', kind: '输出' },
{ id: 'ie-ft1', label: 'SRV-2U-620.折弯.回弹补偿', kind: '特征树' },
{ id: 'ie-ft2', label: 'SRV-2U-620.焊接.激光焊焊瘤', kind: '特征树' },
],
edges: [
{ from: 'IE', to: 'ie-tools', label: '读取' },
{ from: 'IE', to: 'ie-acc', label: '读取' },
{ from: 'IE', to: 'ie-sop', label: '产出' },
{ from: 'IE', to: 'ie-fix', label: '产出' },
{ from: 'IE', to: 'ie-jig', label: '产出' },
{ from: 'ie-jig', to: 'ie-ft1', label: '适配' },
{ from: 'ie-fix', to: 'ie-ft2', label: '适配' },
],
},
},
/* ─────────────────────────── QE 质量工程师 ─────────────────────────── */
{
role: 'QE', name: 'QE 质量标准文件', color: ROLE_COLOR.QE,
tagline: '检验标准制定与异常数据分析',
duty: '制定检验标准、异常数据分析',
current: '标准制定依赖个人经验,存在遗漏风险',
inputs: ['历史检验报告', '检验项目清单'],
outputs: ['特征树上的建议检验项目', '提醒风险点'],
followups: ['提醒漏掉的项目标准', '提配当前步骤的风险点'],
chunkCols: ['检验场景', '建议检验项目', '遗漏风险点', '所属特征树', '责任'],
chunks: [
chunk('qe-1', '折弯件平面度未纳入常规检验,历史出现装配错位后才被发现。',
{ 检验场景: '折弯尺寸检验', 建议检验项目: '平面度 + 折弯角', 遗漏风险点: '平面度标准未定义', 所属特征树: 'SRV-2U-620.折弯.回弹补偿', 责任: 'QE' }),
chunk('qe-2', '外观限度样板缺失,外观判定依赖检验员个人经验。',
{ 检验场景: '外观检验', 建议检验项目: '外观限度样板比对', 遗漏风险点: '限度样板未建立', 所属特征树: 'SRV-2U-620.表面处理.色差', 责任: 'QE' }),
chunk('qe-3', '激光焊缝熔深未做破坏性抽检,焊瘤缺陷漏检率高。',
{ 检验场景: '焊接检验', 建议检验项目: '熔深破坏性抽检 + 目视', 遗漏风险点: '熔深抽检频次未规定', 所属特征树: 'SRV-2U-620.焊接.激光焊焊瘤', 责任: 'QE' }),
chunk('qe-4', 'NCT 孔位仅抽检首件,批量中间件无中途确认。',
{ 检验场景: 'NCT 孔位检验', 建议检验项目: '孔位 CMM + 中途确认', 遗漏风险点: '中途确认节点缺失', 所属特征树: 'SRV-2U-620.NCT.孔位', 责任: 'QE' }),
chunk('qe-5', '手工倒角毛刺无量化判定标准,全靠手感。',
{ 检验场景: '毛刺检验', 建议检验项目: '毛刺高度量化判定', 遗漏风险点: '毛刺高度限值未定义', 所属特征树: 'SRV-2U-620.NCT.手工倒角', 责任: 'QE' }),
],
graph: {
nodes: [
{ id: 'QE', label: 'QE 质量工程师', kind: '角色' },
{ id: 'qe-rep', label: '历史检验报告', kind: '输入' },
{ id: 'qe-items', label: '检验项目清单', kind: '输入' },
{ id: 'qe-out1', label: '建议检验项目', kind: '输出' },
{ id: 'qe-out2', label: '风险点提醒', kind: '输出' },
{ id: 'qe-ft1', label: 'SRV-2U-620.折弯.回弹补偿', kind: '特征树' },
{ id: 'qe-ft2', label: 'SRV-2U-620 外观限度样板', kind: '特征树' },
],
edges: [
{ from: 'QE', to: 'qe-rep', label: '分析' },
{ from: 'QE', to: 'qe-items', label: '比对' },
{ from: 'QE', to: 'qe-out1', label: '产出' },
{ from: 'QE', to: 'qe-out2', label: '产出' },
{ from: 'qe-out1', to: 'qe-ft1', label: '补充' },
{ from: 'qe-out2', to: 'qe-ft2', label: '提示' },
],
},
},
/* ─────────────────────────── ME 制造工程师 ─────────────────────────── */
{
role: 'ME', name: 'ME 制造标准文件', color: ROLE_COLOR.ME,
tagline: '设备选型与参数设定',
duty: '设备选型、参数设定',
current: '目前由生产主管兼任,角色缺位',
inputs: ['设备参数记录', '异常处理记录'],
outputs: ['特征树上的建议设备参数(功率、固定位置等)', '建议验收'],
followups: ['提醒常见风险', '验收标准建议'],
chunkCols: ['设备场景', '建议参数', '验收标准', '所属特征树', '责任'],
chunks: [
chunk('me-1', '激光焊机功率与焊速未建立参数卡,换料即凭经验调参。',
{ 设备场景: '激光焊接', 建议参数: '功率 1200W / 气 15 / 焊速 38', 验收标准: '焊缝熔深与外观双确认', 所属特征树: 'SRV-2U-620.焊接.激光焊焊瘤', 责任: 'ME' }),
chunk('me-2', '折弯机后挡料定位漂移,批次间角度不一致。',
{ 设备场景: '折弯机', 建议参数: '后挡料定位 + 回弹补偿表', 验收标准: '首件 CMM 角度确认', 所属特征树: 'SRV-2U-620.折弯.回弹补偿', 责任: 'ME' }),
chunk('me-3', 'NCT 冲床垫块固定位置磨损,孔位偏移。',
{ 设备场景: 'NCT 冲床', 建议参数: '垫块固定位置按磨损量补偿', 验收标准: '垫块磨损周期点检', 所属特征树: 'SRV-2U-620.NCT.孔位', 责任: 'ME' }),
chunk('me-4', '打磨机转速不可控,去毛刺一致性差。',
{ 设备场景: '打磨 / 倒角设备', 建议参数: '转速设定 + 气动浮动刀头', 验收标准: '毛刺高度量化验收', 所属特征树: 'SRV-2U-620.NCT.手工倒角', 责任: 'ME' }),
],
graph: {
nodes: [
{ id: 'ME', label: 'ME 制造工程师', kind: '角色' },
{ id: 'me-param', label: '设备参数记录', kind: '输入' },
{ id: 'me-anom', label: '异常处理记录', kind: '输入' },
{ id: 'me-out1', label: '建议设备参数', kind: '输出' },
{ id: 'me-out2', label: '建议验收', kind: '输出' },
{ id: 'me-ft1', label: 'SRV-2U-620.焊接.激光焊焊瘤', kind: '特征树' },
{ id: 'me-ft2', label: 'SRV-2U-620.NCT.孔位', kind: '特征树' },
],
edges: [
{ from: 'ME', to: 'me-param', label: '读取' },
{ from: 'ME', to: 'me-anom', label: '关联' },
{ from: 'ME', to: 'me-out1', label: '产出' },
{ from: 'ME', to: 'me-out2', label: '产出' },
{ from: 'me-out1', to: 'me-ft1', label: '设定' },
{ from: 'me-out2', to: 'me-ft2', label: '验收' },
],
},
},
];
/** 汇总口径:供页面顶部概览药签使用,全部现算 */
export const kbSummary = () => ({
docs: roleDocs.length,
chunks: roleDocs.reduce((a, d) => a + d.chunks.length, 0),
vectors: roleDocs.reduce((a, d) => a + d.chunks.length, 0) * VECTOR_DIMS,
entities: roleDocs.reduce((a, d) => a + d.graph.nodes.length, 0),
relations: roleDocs.reduce((a, d) => a + d.graph.edges.length, 0),
});
@@ -0,0 +1,31 @@
/**
* 生产方法的实拍示意图:一张方法一张 4:3 缩略图,放在特征树叶子左侧。
* 图片由 AI 生成、统一压到 320×240 的 JPG,放在 public/methods/ 下,
* 按方法 id 映射,避免在多个机型 / 工艺间重复打包同一张图。
*/
const METHOD_IMAGE: Record<string, string> = {
'数控冲孔': 'cnc-punch',
'手工倒角': 'hand-chamfer',
'机器倒角': 'machine-chamfer',
'设备压铸倒角': 'diecast-chamfer',
'数控折弯': 'cnc-bending',
'手工折弯': 'hand-bending',
'压铆': 'rivet-nut',
'攻牙': 'tapping',
'激光焊': 'laser-weld',
'机器人弧焊': 'robot-arc-weld',
'手工氩弧焊': 'tig-weld',
'点焊': 'spot-weld',
'手工打磨': 'hand-grinding',
'补焊': 'repair-weld',
'工装组装': 'fixture-assembly',
'手工组装': 'hand-assembly',
'阳极氧化': 'anodizing',
'喷粉': 'powder-coating',
};
/** 方法 id → 图片 URL;没有配图时返回 undefined,由调用方回退到图标 */
export function methodImageSrc(id: string): string | undefined {
const slug = METHOD_IMAGE[id];
return slug ? `/mod-assets/tfamd-oee/methods/${slug}.jpg` : undefined;
}
@@ -0,0 +1,408 @@
/**
* 生产方法总结层:工艺 × 生产方法 × 角色(PE / IE / QE / ME)。
*
* 特征树的第三级不再是「缺陷」,而是可执行的生产方法(手工倒角 / 激光焊 / 压铆…)。
* 每条知识切片按旧特征码或场景关键词落到方法上,抽成一行:
* 问题 · 原因 · 对策 · 角色 · 来源
*
* 真实知识只覆盖 SRV-2U-620(知识库切片都是这个机型)。
* 其余机型、以及没有知识切片的方法,用方法模板示例补齐,并明确标「示例」,
* 不伪装成知识库事实。
*/
import { roleDocs, type KbChunk, type RoleKey } from './knowledge';
export type ExampleSeed = [RoleKey, string, string, string];
export interface ProductionMethodDef {
/** 方法 id,同时作为特征码第三段 */
id: string;
label: string;
/** 方法模板示例:角色 / 问题 / 原因 / 对策 */
examples: ExampleSeed[];
}
export interface ProductionProcessDef {
/** 工艺 id,同时作为特征码第二段 */
id: string;
label: string;
methods: ProductionMethodDef[];
}
export interface MethodSummaryRow {
id: string;
role: RoleKey;
problem: string;
cause: string;
action: string;
source:
| { kind: 'kb'; chunkId: string; label: string; code?: string }
| { kind: 'example' };
}
/* ── 工艺 / 生产方法目录 ─────────────────────────────────────────────── */
export const PRODUCTION_CATALOG: ProductionProcessDef[] = [
{
id: 'NCT',
label: 'NCT 冲压',
methods: [
{
id: '数控冲孔',
label: '数控冲孔',
examples: [
['PE', '冲孔毛刺高度波动', '模具刃口磨损未按冲次更换', '按冲次建立刃口修磨 / 更换周期,首件测毛刺'],
['QE', '孔位尺寸仅首件确认', '批量中段缺少抽检节点', '每 500 件增加孔位 CMM 中途确认'],
],
},
{
id: '手工倒角',
label: '手工倒角',
examples: [
['PE', '手工倒角深浅不一', '无刀具补偿且施力不均', '改用气动浮动刀头并加装限位,首件确认'],
['IE', '手工倒角节拍波动', '去毛刺动作无标准', 'SOP 固化倒角手法与工具,设置标准节拍'],
],
},
{
id: '机器倒角',
label: '机器倒角',
examples: [
['PE', '机器倒角偶发过切', '进给与板厚未联动', '按板厚分档设定进给,首件确认'],
['QE', '倒角尺寸未纳入抽检', '倒角角度无检验标准', '增加倒角角度与毛刺高度抽检'],
],
},
{
id: '设备压铸倒角',
label: '设备压铸倒角',
examples: [
['PE', '压铸倒角边缘塌陷', '压力与保压时间不匹配', 'DOE 确定压力 / 保压窗口并固化'],
['ME', '压铸倒角模具温升漂移', '连续生产未做模温补偿', '增加模温闭环控制与首件确认'],
['QE', '压铸倒角外观无判定样板', '塌陷限度未定义', '建立外观限度样板并抽检'],
],
},
],
},
{
id: '折弯',
label: '折弯',
methods: [
{
id: '数控折弯',
label: '数控折弯',
examples: [
['PE', '折弯角度批次漂移', '回弹补偿未随板厚更新', '按材质 / 板厚维护回弹补偿表'],
['IE', '折弯换型时间超标', '换模与首件流程未标准化', '快换模架 + 换型首件确认 SOP'],
],
},
{
id: '手工折弯',
label: '手工折弯',
examples: [
['PE', '手工折弯曲面起皱', '无折弯模支撑、施力不均', '增加折弯模与定位挡块'],
['IE', '手工折弯节拍波动大', '依赖个人经验、无标准动作', 'SOP 固化折弯顺序与自检点'],
['QE', '手工折弯角度未全检', '角度公差标准缺失', '增加角度样板与首件确认'],
],
},
],
},
{
id: '压铆',
label: '压铆·攻牙',
methods: [
{
id: '压铆',
label: '压铆',
examples: [
['PE', '压铆螺母松动或歪斜', '压铆压力与孔径匹配不当', '按料号建立压铆参数卡'],
['QE', '压铆推出力未抽检', '推出力标准缺失', '增加推出力破坏抽检'],
['ME', '压铆机压力漂移', '压力未闭环监控', '增加压力监控与日点检'],
],
},
{
id: '攻牙',
label: '攻牙',
examples: [
['PE', '攻牙烂牙 / 滑牙', '底孔尺寸与转速不匹配', '底孔分档并设定转速'],
['ME', '攻牙机扭矩不稳定', '丝锥磨损未监控', '扭矩监控 + 丝锥寿命管理'],
['QE', '攻牙牙深未抽检', '牙深检验项目缺失', '增加牙深通止规抽检'],
],
},
],
},
{
id: '焊接',
label: '焊接',
methods: [
{
id: '激光焊',
label: '激光焊',
examples: [
['PE', '激光焊角焊缝咬边', '功率与焊速未匹配', 'DOE 固化功率 / 焊速窗口'],
['IE', '激光焊装夹定位不足', '手工扶持导致焊缝偏移', '增加焊接定位治具与装夹校验'],
],
},
{
id: '机器人弧焊',
label: '机器人弧焊',
examples: [
['PE', '机器人弧焊焊缝成型不均', '焊接姿态与行走速度未优化', '固化焊接姿态与速度参数'],
['ME', '机器人焊枪导电嘴磨损', '未按焊点数量更换', '按焊点计数强制更换导电嘴'],
],
},
{
id: '手工氩弧焊',
label: '手工氩弧焊',
examples: [
['PE', '手工氩弧焊咬边', '电流与行走速度不匹配', '参数卡 + 焊工技能矩阵'],
['QE', '氩弧焊缝外观未全检', '咬边判定标准缺失', '限度样板 + 全检外观'],
['ME', '氩弧焊机电流输出漂移', '焊机未做周期校准', '增加焊机电流校准与日点检'],
],
},
{
id: '点焊',
label: '点焊',
examples: [
['PE', '点焊虚焊 / 焊点间距不均', '电极压力与电流衰减', '电极修磨周期 + 参数卡'],
['ME', '点焊电极磨损', '未按焊点数修磨', '按焊点数强制修磨'],
['QE', '点焊熔核未做破坏抽检', '熔核直径标准缺失', '增加熔核破坏抽检'],
],
},
],
},
{
id: '打磨',
label: '打磨·补焊',
methods: [
{
id: '手工打磨',
label: '手工打磨',
examples: [
['PE', '打磨过度导致板厚减薄', '无打磨量标准、靠手感', '限定打磨量与区域并做首件确认'],
['IE', '打磨工位粉尘与节拍瓶颈', '手工打磨无工装固定', '增加打磨治具与除尘工位'],
['QE', '打磨后表面粗糙度未检验', '粗糙度标准缺失', '增加粗糙度样板比对'],
],
},
{
id: '补焊',
label: '补焊',
examples: [
['PE', '补焊后热影响区变色 / 变形', '补焊热输入未控制', '限定补焊电流与层间温度'],
['QE', '补焊区域未做专项检验', '补焊后无损检测缺失', '补焊区 100% 目视 + 抽检'],
['ME', '补焊台参数未标准化', '补焊电流凭经验', '建立补焊参数卡并验收'],
],
},
],
},
{
id: '组装',
label: '组装',
methods: [
{
id: '工装组装',
label: '工装组装',
examples: [
['PE', '工装组装漏装 / 错装', '无防错与物料齐套确认', '增加防错工装与齐套清单'],
['QE', '组装后功能未全检', '检验项目未覆盖装配干涉', '增加装配干涉与功能抽检'],
],
},
{
id: '手工组装',
label: '手工组装',
examples: [
['PE', '手工组装漏装 / 错装', '无防错与物料齐套确认', '增加防错工装与齐套清单'],
['IE', '手工组装线平衡差', '工位分配未按节拍', '重排工位与标准作业组合'],
['QE', '手工组装扭矩未抽检', '扭矩标准缺失', '增加扭矩抽检与记录'],
],
},
],
},
{
id: '表面处理',
label: '表面处理',
methods: [
{
id: '阳极氧化',
label: '阳极氧化',
examples: [
['PE', '阳极氧化膜厚不均', '槽液浓度与时间波动', '膜厚参数卡 + 槽液点检'],
['ME', '阳极氧化电源输出漂移', '整流器未周期校准', '增加电源校准与槽温监控'],
],
},
{
id: '喷粉',
label: '喷粉',
examples: [
['PE', '喷粉膜厚不均 / 橘皮', '喷枪距离与静电参数不稳', '固化喷粉参数卡'],
['QE', '膜厚与附着力未抽检', '检验项目缺失', '增加膜厚 / 附着力抽检'],
['ME', '喷粉固化炉温漂移', '炉温未闭环监控', '增加炉温曲线监控与点检'],
],
},
],
},
];
export const methodDef = (processId: string, methodId: string): ProductionMethodDef | undefined =>
PRODUCTION_CATALOG.find(p => p.id === processId)?.methods.find(m => m.id === methodId);
/* ── 旧特征码 → 生产方法 ─────────────────────────────────────────────── */
const LEGACY_TARGET: Record<string, { processId: string; methodId: string }> = {
'NCT.手工倒角': { processId: 'NCT', methodId: '手工倒角' },
'NCT.孔位': { processId: 'NCT', methodId: '数控冲孔' },
'折弯.回弹补偿': { processId: '折弯', methodId: '数控折弯' },
'焊接.激光焊焊瘤': { processId: '焊接', methodId: '激光焊' },
'焊接.焊接变形': { processId: '焊接', methodId: '机器人弧焊' },
'表面处理.色差': { processId: '表面处理', methodId: '阳极氧化' },
};
/** IE 切片没有「所属特征树」列,按场景关键词显式映射 */
const IE_TARGET: Record<string, { processId: string; methodId: string }> = {
'ie-1': { processId: '折弯', methodId: '数控折弯' },
'ie-2': { processId: '焊接', methodId: '激光焊' },
'ie-3': { processId: 'NCT', methodId: '手工倒角' },
'ie-4': { processId: '组装', methodId: '工装组装' },
};
/** IE 切片的自然语言字段不是「问题 / 原因 / 对策」口径,这里按原文提炼 */
const IE_ROWS: Record<string, { problem: string; cause: string; action: string }> = {
'ie-1': {
problem: '折弯换型频繁、首件确认缺失',
cause: '换型后无首件确认,前几件尺寸漂移',
action: 'SOP 增加换型后首件确认;采用通用 2U 系列快换治具(匹配 3 个料号)',
},
'ie-2': {
problem: '激光焊工位缺少治具定位',
cause: '手工扶持造成焊缝偏移',
action: 'SOP 增加夹具装夹与校验;焊接定位治具(带快速夹钳)(匹配 2 个机型)',
},
'ie-3': {
problem: 'NCT 冲孔后手工去毛刺耗时长',
cause: '手工去毛刺是节拍瓶颈',
action: 'SOP 增加去毛刺工具与手法标准;气动浮动倒角刀头(匹配 1 个专用夹具)',
},
'ie-4': {
problem: '组装工位工装通用化不足',
cause: '换型时间超过目标节拍',
action: 'SOP 增加工装点检与快换步骤;组装通用治具(通用 2U 系列)(匹配 3 个料号)',
},
};
/** ME 的设备场景原文只给现象,原因按设备口径补齐 */
const ME_CAUSE: Record<string, string> = {
'me-1': '参数未标准化,换料依赖经验',
'me-2': '后挡料定位漂移,未做回弹补偿',
'me-3': '垫块磨损未按周期点检',
'me-4': '转速与刀具状态未闭环控制',
};
const KB_MODEL = 'SRV-2U-620';
const ROLE_ORDER: Record<RoleKey, number> = { PE: 0, IE: 1, QE: 2, ME: 3 };
const firstClause = (text: string) => text.split(/[,。;]/)[0]?.trim() || text;
const shortLabel = (text: string, max = 26) =>
text.length <= max ? text : `${text.slice(0, max)}…`;
const targetOfChunk = (role: RoleKey, ch: KbChunk) => {
if (role === 'IE') return IE_TARGET[ch.id] ?? null;
const col = roleDocs.find(d => d.role === role)?.chunkCols.find(c => c.includes('特征树'));
const code = col ? ch.cells[col] : '';
if (!code) return null;
const [modelId, processId, legacyMethod] = code.split('.');
if (modelId !== KB_MODEL) return null;
const target = LEGACY_TARGET[`${processId}.${legacyMethod}`];
return target ? { ...target, code } : null;
};
const rowOfChunk = (
role: RoleKey,
ch: KbChunk,
target: { processId: string; methodId: string; code?: string },
): MethodSummaryRow | null => {
if (role === 'PE') {
return {
id: `kb-${ch.id}`, role,
problem: ch.cells['品质问题'],
cause: ch.cells['原因分析'],
action: ch.cells['对策建议'],
source: { kind: 'kb', chunkId: ch.id, label: shortLabel(ch.text), code: target.code },
};
}
if (role === 'QE') {
return {
id: `kb-${ch.id}`, role,
problem: firstClause(ch.text),
cause: ch.cells['遗漏风险点'],
action: ch.cells['建议检验项目'],
source: { kind: 'kb', chunkId: ch.id, label: shortLabel(ch.text), code: target.code },
};
}
if (role === 'ME') {
return {
id: `kb-${ch.id}`, role,
problem: firstClause(ch.text),
cause: ME_CAUSE[ch.id] ?? '设备参数未标准化',
action: `${ch.cells['建议参数']};验收:${ch.cells['验收标准']}`,
source: { kind: 'kb', chunkId: ch.id, label: shortLabel(ch.text), code: target.code },
};
}
const ie = IE_ROWS[ch.id];
if (!ie) return null;
return {
id: `kb-${ch.id}`, role,
...ie,
source: { kind: 'kb', chunkId: ch.id, label: shortLabel(ch.text) },
};
};
const REAL_ROWS = (() => {
const map = new Map<string, MethodSummaryRow[]>();
for (const doc of roleDocs) {
for (const ch of doc.chunks) {
const target = targetOfChunk(doc.role, ch);
if (!target) continue;
const row = rowOfChunk(doc.role, ch, target);
if (!row) continue;
const key = `${KB_MODEL}#${target.processId}#${target.methodId}`;
const arr = map.get(key) ?? [];
arr.push(row);
map.set(key, arr);
}
}
return map;
})();
const exampleRow = (
processId: string,
methodId: string,
seed: ExampleSeed,
i: number,
): MethodSummaryRow => {
const [role, problem, cause, action] = seed;
return {
id: `ex-${processId}-${methodId}-${i}`,
role, problem, cause, action,
source: { kind: 'example' },
};
};
/**
* 取某机型 / 工艺 / 生产方法的总结行。
* - SRV-2U-620 有真实知识 → 用真实行;只有 1 行时补 1 条异角色示例。
* - 无真实知识 / 其他机型 → 用方法模板示例补齐。
*/
export const summariesFor = (modelId: string, processId: string, methodId: string): MethodSummaryRow[] => {
const def = methodDef(processId, methodId);
const examples = (def?.examples ?? []).map((seed, i) => exampleRow(processId, methodId, seed, i));
const real = REAL_ROWS.get(`${KB_MODEL}#${processId}#${methodId}`) ?? [];
let rows: MethodSummaryRow[];
if (modelId === KB_MODEL && real.length > 0) {
if (real.length === 1) {
const extra = examples.find(r => r.role !== real[0].role) ?? examples[0];
rows = extra ? [...real, extra] : real;
} else {
rows = real;
}
} else {
rows = examples;
}
return rows.sort((a, b) => ROLE_ORDER[a.role] - ROLE_ORDER[b.role]);
};
+190
View File
@@ -0,0 +1,190 @@
/**
* 七个智能体的标准命名与分期(建议书 4.4.1 / 决策 D15)。
*
* ★ 命名纪律:全站(页签、对话坞、回答卡、专家团选择器、文档)统一用**标准名称**,
* 编号 A1–A7 仅作内部映射。**不得出现"小欧""OEE 助手"等花名**——这是企业演示的既有规范。
* ★ 分期不隐藏:A5–A7 在 UI 上以"二期/三期"占位卡呈现。隐藏会让客户以为功能缺失,
* 明示分期反而体现路线清晰。
* ★ 运行统计不编造:A1–A4 一期已于 W3-C 接入规则引擎问答(implemented=true,status=working);
* A5–A7 二期三期未接(status=idle/offline,cur_zh 写明缺口)。原型不跨刷新累计调用计数,
* 故 tasks/success/confidence/load 一律为 0、lastRun 为「尚未运行」——0 表示"未累计"而非"运行失败"。
* **不得为了让面板好看而填一个假的 96%。**
*/
export type AgentPhase = '一期' | '二期' | '三期';
/** 八项技能(建议书 4.4.2):每项有明确输入输出契约与停止条件 */
export interface OeeSkill {
id: string;
name: string;
input: string;
output: string;
/** 停止条件:不满足即停,不猜、不补、不摊派 */
stop: string;
}
export const OEE_SKILLS: OeeSkill[] = [
{ id: 'SK1', name: '问数', input: '设备 + 时间范围 + 指标(三要素)', output: 'ServiceResult<OeeResult>', stop: '三要素不全 → 先反问,不猜' },
{ id: 'SK2', name: '下钻', input: '上层结果 + 目标层级', output: '下一层明细 + 证据引用', stop: '任一层缺证据 → 即停' },
{ id: 'SK3', name: '对比', input: '两个同口径结果', output: '顺序替代 ΔA/ΔP/ΔQ', stop: '口径版本不同 → 拒绝' },
{ id: 'SK4', name: '归因', input: '损失结构 + 状态段 + 事件证据', output: '损失分解 + 时间轴定位', stop: '残差≠0 或证据缺失 → 只报缺口,不下结论' },
{ id: 'SK5', name: '测算', input: '产能 + 费率(四门槛齐备)', output: '金额化收益区间', stop: '费率未签字 → 拒绝测算,不给金额' },
{ id: 'SK6', name: '建议', input: '损失结构 + 规则库 + 历史案例', output: '建议清单 + 预估收益区间', stop: '无匹配案例 → 标"无历史依据",不编收益' },
{ id: 'SK7', name: '派单', input: '改善任务(四项必填)', output: '任务状态 + 责任人', stop: '四项任一缺失 → canDispatch=false,不派发' },
{ id: 'SK8', name: '复盘', input: '已闭环任务 + 前后同口径结果', output: '效果对比 + 口径出处', stop: '前后期口径版本不同 → 拒绝对比' },
];
/** 五类受控工具(建议书 4.4.2):**不开放 DB 直连** */
export interface OeeTool {
id: string;
name: string;
scope: string;
/** 白名单约束:工具只能做这件事,越界即拒 */
guard: string;
}
export const OEE_TOOLS: OeeTool[] = [
{ id: 'TL1', name: '指标查询', scope: '经 L3 服务层取 OEE/六桶/三档结果', guard: '只读;必带 caliberVersion + timeRange + source;禁止 SQL 直连' },
{ id: 'TL2', name: '时间轴查询', scope: '状态段/事件/原始日志行号', guard: '只读;下钻必须回得到 lineNo,否则即停' },
{ id: 'TL3', name: '任务', scope: '改善任务创建与六态流转', guard: '四项必填齐备才允许派发;状态机非法流转拒绝' },
{ id: 'TL4', name: '报表', scope: '口径对齐的结果导出', guard: '导出必带口径版本与模拟标注;跨版本拼装拒绝' },
{ id: 'TL5', name: '消息推送', scope: '告警与任务通知', guard: '原型只在站内提示,不接真实 OA/邮件通道' },
];
export interface OeeAgent {
/** 内部编号,仅作映射,不在 UI 当名字用 */
id: 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7';
/** 内部标识(digital_staff.code) */
code: string;
/** 标准名称——全站唯一可用称呼 */
name: string;
phase: AgentPhase;
/** 原型是否已实现。A1–A4 一期已于 W3-C 接入规则引擎问答,故为 true;A5–A7 二期三期未接,为 false */
implemented: boolean;
duty: string;
input: string;
output: string;
skillIds: string[];
toolIds: string[];
/** 绑定的指标树 code */
boundMetric: string;
/** 未实现/二期三期的缺口说明,UI 必须原样展示 */
gap: string;
}
export const OEE_AGENTS: OeeAgent[] = [
{
id: 'A1', code: 'METRIC-QA', name: '指标问数智能体', phase: '一期', implemented: true,
duty: '自然语言问数', input: '指标语义层 + 自然语言', output: '图表 + 结论 + 口径出处',
skillIds: ['SK1', 'SK2', 'SK3'], toolIds: ['TL1', 'TL2', 'TL4'], boundMetric: 'OEE',
gap: '一期已接入(W3-C):规则引擎应答,数字只来自五类受控工具、必带口径出处;未接外部大模型通道,运行统计为会话内计数、不跨刷新累计。',
},
{
id: 'A2', code: 'LOSS-DIAG', name: '损失诊断智能体', phase: '一期', implemented: true,
duty: '三层 OEE + 顺序替代 → 损失分解 + 时间轴定位',
input: '三层 OEE + 状态段', output: '损失结构 + 定位',
skillIds: ['SK2', 'SK4'], toolIds: ['TL1', 'TL2'], boundMetric: 'TIME',
gap: '一期已接入(W3-C):三层 OEE 与六桶贯通,下钻可回原始日志行号;诊断话术为规则模板,非生成式,残差≠0 或证据缺失即停。',
},
{
id: 'A3', code: 'IMPROVE-ADV', name: '改善建议智能体', phase: '一期', implemented: true,
duty: '规则库 + 历史案例 + 向量检索', input: '损失结构 + 案例', output: '建议清单 + 预估收益区间',
skillIds: ['SK6'], toolIds: ['TL1', 'TL3'], boundMetric: 'L-FAULT',
gap: '一期已接入(W3-C):案例库与向量检索为本地 TF-IDF 规则匹配,不接外部大模型;无匹配案例时标「无历史依据」,收益只给区间、不编数。',
},
{
id: 'A4', code: 'CLOSE-LOOP', name: '闭环跟踪智能体', phase: '一期', implemented: true,
duty: '流程编排 + 任务中心', input: '任务状态', output: '状态 + 效果对比',
skillIds: ['SK7', 'SK8'], toolIds: ['TL3', 'TL5'], boundMetric: 'T-IDLE',
gap: '一期已接入(W3-C):六态流转与四项必填闸门在 closure 引擎落地;派发为站内内存态,不接真实 OA/邮件通道,四项不全即拒绝派发。',
},
{
id: 'A5', code: 'QUALITY-LINK', name: '质量关联智能体', phase: '二期', implemented: false,
duty: 'MES 良率 + Q 因子', input: '良率 + Q', output: '质量-OEE 关联',
skillIds: ['SK4'], toolIds: ['TL1'], boundMetric: 'Q',
gap: '二期(P4~P5):需 MES 良率接口与批次级不良明细到位。原型以占位卡呈现,不隐藏、不假装已接。',
},
{
id: 'A6', code: 'APS-SYNC', name: '排产协同智能体', phase: '二期', implemented: false,
duty: 'APS 契约 + 瓶颈聚合', input: '排产 + 瓶颈', output: '换型/等料预测 + 排产建议',
skillIds: ['SK4', 'SK6'], toolIds: ['TL1', 'TL3'], boundMetric: 'L-CHANGEOVER',
gap: '二期(P4~P5):需 APS 排产契约与瓶颈站主数据。当前计划待料按 C09 默认口径判定,未接真实 APS。',
},
{
id: 'A7', code: 'VALUE-CALC', name: '经营测算智能体', phase: '三期', implemented: false,
duty: '产能金额换算', input: '产能 + 费率', output: '金额化收益 + 趋势',
skillIds: ['SK5'], toolIds: ['TL1', 'TL4'], boundMetric: 'OEE',
gap: '三期:四门槛齐备且 A1~A6 稳定运行一季度后才启动。费率未签字前**拒绝测算**,不给任何金额数字。',
},
];
export const AGENT_NAMING_NOTE =
'全站统一使用标准名称(如「损失诊断智能体」),A1–A7 仅作内部映射;不得出现"小欧""OEE 助手"等花名。';
export const AGENT_PHASE_NOTE =
'A1–A4 一期(原型实现);A5–A6 二期(P4~P5);A7 三期(四门槛齐备 + A1~A6 稳定一季度)。分期以占位卡明示,不隐藏。';
export const AGENT_STATS_NOTE =
'运行统计(任务数/成功率/置信度/负载)在问答引擎接入前一律为 0,表示"未接入"而非"运行失败";接入后由真实调用计数填充。';
/** digital_staff 的 12 元组(id 由 sqlite 自增) */
export type StaffSeed = [
code: string, zh: string, roleZh: string, status: string,
skillZh: string, tasks: number, success: number, conf: number,
load: number, lastRun: string, curZh: string, metric: string,
];
/**
* 由 registry 派生 staff 种子。
* status 如实反映实现状态:已接入 → working;未接入 → idle(一期)/ offline(二期三期)。
* 统计字段全 0、lastRun 用「尚未运行」:原型不跨刷新累计调用计数,不编一个"刚刚"或假成功率。
*/
export function agentStaffSeeds(): StaffSeed[] {
return OEE_AGENTS.map((a) => {
const skills = a.skillIds
.map((id) => OEE_SKILLS.find((s) => s.id === id)?.name ?? id)
.join(' / ');
const status = a.implemented ? 'working' : a.phase === '一期' ? 'idle' : 'offline';
const cur = a.implemented ? `${a.duty}(运行中)` : a.gap;
return [
a.code, a.name, `${a.phase} · ${a.duty}`, status, skills,
0, 0, 0, 0, '尚未运行', cur, a.boundMetric,
] as StaffSeed;
});
}
export function agentById(id: string): OeeAgent | undefined {
return OEE_AGENTS.find((a) => a.id === id);
}
export function agentByCode(code: string): OeeAgent | undefined {
return OEE_AGENTS.find((a) => a.code === code);
}
/** registry 自检:供校验脚本与"说明与对照"页引用 */
export function agentStats() {
const byPhase: Record<AgentPhase, number> = { 一期: 0, 二期: 0, 三期: 0 };
for (const a of OEE_AGENTS) byPhase[a.phase] += 1;
const skillIds = new Set(OEE_SKILLS.map((s) => s.id));
const toolIds = new Set(OEE_TOOLS.map((t) => t.id));
return {
total: OEE_AGENTS.length,
byPhase,
implemented: OEE_AGENTS.filter((a) => a.implemented).length,
phase1: OEE_AGENTS.filter((a) => a.phase === '一期').map((a) => a.name),
placeholders: OEE_AGENTS.filter((a) => a.phase !== '一期').map((a) => `${a.name}(${a.phase})`),
skillCount: OEE_SKILLS.length,
toolCount: OEE_TOOLS.length,
/** 每个智能体引用的技能/工具都必须在受控清单内,不得私开通道 */
refsValid: OEE_AGENTS.every((a) =>
a.skillIds.every((s) => skillIds.has(s)) && a.toolIds.every((t) => toolIds.has(t))),
/** 八项技能是否都被至少一个智能体覆盖(未覆盖的技能要显式标缺口) */
uncoveredSkills: OEE_SKILLS.filter((s) => !OEE_AGENTS.some((a) => a.skillIds.includes(s.id))).map((s) => s.name),
/** 标准名称唯一,且不含花名 */
namesUnique: new Set(OEE_AGENTS.map((a) => a.name)).size === OEE_AGENTS.length,
noNickname: OEE_AGENTS.every((a) => !/小欧|OEE\s*助手/.test(a.name)),
/** 未接入者统计必须全 0,不允许编造运行成绩 */
statsHonest: agentStaffSeeds().every((s, i) =>
OEE_AGENTS[i].implemented || (s[5] === 0 && s[6] === 0 && s[7] === 0 && s[8] === 0)),
namingNote: AGENT_NAMING_NOTE,
phaseNote: AGENT_PHASE_NOTE,
statsNote: AGENT_STATS_NOTE,
};
}

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