diff --git a/.gitignore b/.gitignore index 2552dc5..2a32257 100644 --- a/.gitignore +++ b/.gitignore @@ -36,6 +36,7 @@ lerna-debug.log* .env.*.local # Cache +.screenshots/ .cache/ .temp/ .eslintcache diff --git a/package-lock.json b/package-lock.json index 14fe04f..2554e8f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -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 + } + } } } } diff --git a/package.json b/package.json index 0a5b92e..12b40ca 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/public/mod-assets/tfamd-oee/methods/anodizing.jpg b/public/mod-assets/tfamd-oee/methods/anodizing.jpg new file mode 100644 index 0000000..22eb75e Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/anodizing.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/cnc-bending.jpg b/public/mod-assets/tfamd-oee/methods/cnc-bending.jpg new file mode 100644 index 0000000..1c1657c Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/cnc-bending.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/cnc-punch.jpg b/public/mod-assets/tfamd-oee/methods/cnc-punch.jpg new file mode 100644 index 0000000..14f39cf Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/cnc-punch.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/diecast-chamfer.jpg b/public/mod-assets/tfamd-oee/methods/diecast-chamfer.jpg new file mode 100644 index 0000000..bf37a72 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/diecast-chamfer.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/fixture-assembly.jpg b/public/mod-assets/tfamd-oee/methods/fixture-assembly.jpg new file mode 100644 index 0000000..05b77e4 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/fixture-assembly.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/hand-assembly.jpg b/public/mod-assets/tfamd-oee/methods/hand-assembly.jpg new file mode 100644 index 0000000..26f37bb Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/hand-assembly.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/hand-bending.jpg b/public/mod-assets/tfamd-oee/methods/hand-bending.jpg new file mode 100644 index 0000000..4afc73c Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/hand-bending.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/hand-chamfer.jpg b/public/mod-assets/tfamd-oee/methods/hand-chamfer.jpg new file mode 100644 index 0000000..2719f9a Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/hand-chamfer.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/hand-grinding.jpg b/public/mod-assets/tfamd-oee/methods/hand-grinding.jpg new file mode 100644 index 0000000..f7a356b Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/hand-grinding.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/laser-weld.jpg b/public/mod-assets/tfamd-oee/methods/laser-weld.jpg new file mode 100644 index 0000000..77e29f5 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/laser-weld.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/machine-chamfer.jpg b/public/mod-assets/tfamd-oee/methods/machine-chamfer.jpg new file mode 100644 index 0000000..cccfc5f Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/machine-chamfer.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/powder-coating.jpg b/public/mod-assets/tfamd-oee/methods/powder-coating.jpg new file mode 100644 index 0000000..2373766 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/powder-coating.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/repair-weld.jpg b/public/mod-assets/tfamd-oee/methods/repair-weld.jpg new file mode 100644 index 0000000..44a9b8a Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/repair-weld.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/rivet-nut.jpg b/public/mod-assets/tfamd-oee/methods/rivet-nut.jpg new file mode 100644 index 0000000..b8dd074 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/rivet-nut.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/robot-arc-weld.jpg b/public/mod-assets/tfamd-oee/methods/robot-arc-weld.jpg new file mode 100644 index 0000000..a876dee Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/robot-arc-weld.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/spot-weld.jpg b/public/mod-assets/tfamd-oee/methods/spot-weld.jpg new file mode 100644 index 0000000..1433b8b Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/spot-weld.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/tapping.jpg b/public/mod-assets/tfamd-oee/methods/tapping.jpg new file mode 100644 index 0000000..26bbafa Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/tapping.jpg differ diff --git a/public/mod-assets/tfamd-oee/methods/tig-weld.jpg b/public/mod-assets/tfamd-oee/methods/tig-weld.jpg new file mode 100644 index 0000000..9367501 Binary files /dev/null and b/public/mod-assets/tfamd-oee/methods/tig-weld.jpg differ diff --git a/public/mod-assets/tfamd-oee/sql-wasm.wasm b/public/mod-assets/tfamd-oee/sql-wasm.wasm new file mode 100755 index 0000000..f6487ca Binary files /dev/null and b/public/mod-assets/tfamd-oee/sql-wasm.wasm differ diff --git a/public/mod-assets/tfamd-oee/tfamd-logo.png b/public/mod-assets/tfamd-oee/tfamd-logo.png new file mode 100644 index 0000000..a677fa3 Binary files /dev/null and b/public/mod-assets/tfamd-oee/tfamd-logo.png differ diff --git a/src/App.tsx b/src/App.tsx index 0135ce6..47c008e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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() { } /> } /> } /> + } /> } /> diff --git a/src/modules/registry.ts b/src/modules/registry.ts index 782624c..64ad3d5 100644 --- a/src/modules/registry.ts +++ b/src/modules/registry.ts @@ -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, ]; diff --git a/src/modules/tfamd-oee/App.tsx b/src/modules/tfamd-oee/App.tsx new file mode 100644 index 0000000..005734d --- /dev/null +++ b/src/modules/tfamd-oee/App.tsx @@ -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(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(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( + () => ({ 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 ( +
+ + {!errMsg ? ( +
+
+ {t.common.initializing} +
+ ) : ( +
+
{t.common.initFailed}
+
{errMsg}
+
{location.host}
+ +
+ )} +
+ ); + } + + return ( +
+ {/* 流动透明球体科技感背景层 */} + + + {/* 内容层:置于背景球体之上 */} +
+ + {/* 质量预防角色条是 demo 故事线(风险点检单流程)的抬头汇总。 */} + + + + {/* 三栏:左=菜单导航,中=页面内容(底部时间回放轴),右=OEE专家智能体 */} +
+ setNetStage(false)} + /> +
+
+
+ ); +} + +export default function App() { + return ( + + + + ); +} diff --git a/src/modules/tfamd-oee/components/AgentDock.tsx b/src/modules/tfamd-oee/components/AgentDock.tsx new file mode 100644 index 0000000..3f7cd8a --- /dev/null +++ b/src/modules/tfamd-oee/components/AgentDock.tsx @@ -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 ( +
+ {label} + + {text}{typing && } + +
+ ); +} + +/** 卡片刚立起来、正文还没铺开时的占位:避免出现一个空白发言卡 */ +function ReaderHint({ tk, t }: { tk: ThemeTokens; t: I18n }) { + return ( +
+ + {[0, 1, 2].map(i => )} + + {t.agent.thinking}… +
+ ); +} + +/** 会诊流式:某个块此刻该显示到什么程度;没有 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 ( +
+
+
+ + + + {turn.name} + {turn.tag && {turn.tag}} + {turn.intent && ( + + {t.agent.secIntent}:{turn.intent} + + )} + {time} +
+
+ {stream && stream.done === 0 && stream.typed === 0 && stream.items === 0 && } + {m && metric.visible && ( +
+
+ {m.label} + {m.value} + {m.state} + {m.deviation} +
+ {/* 判定线原文:源表没设线就照实写,不补达成率 */} +
+ {t.agent.lineLabel}:{m.line} +
+
+ )} + {!!turn.reading?.length && reading.visible && ( +
+ {turn.reading.map((r, i) => ( + + {r.label} + {r.value} + + ))} +
+ )} + {status.visible && ( +
+ +
+ )} + {stance.visible && ( +
+ +
+ )} + {proposal.visible && ( +
+ +
+ )} + {handoff.visible && ( +
+ {turn.handoff && ( +
+ + {t.agent.handoff} → + {turn.handoff} +
+ )} + + {turn.jump && } +
+ )} +
+
+
+ ); +} + +/** 牵头结论卡:结论 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 ( +
+
+
+ + + + {turn.name} + {turn.tag && {turn.tag}} + {time} +
+
+ {stream && stream.done === 0 && stream.typed === 0 && stream.items === 0 && } + {turn.conclusion && concl.visible && ( +
+ {t.agent.concl} + + {concl.text ?? turn.conclusion}{concl.typing && } + +
+ )} + {!!turn.summary?.length && summary.visible && ( +
+ {t.agent.keypoints} + {turn.summary.slice(0, summary.items).map((srow, i) => ( +
+ + {srow.name} + {srow.point} +
+ ))} +
+ )} + {j && judge.visible && ( +
+ {t.agent.judgeLabel} +
+ {j.value} + {j.label} · {j.note} + {j.state} +
+
+ )} + {!!turn.actions?.length && actions.visible && ( +
+ {t.agent.actionsLabel} + {turn.actions.slice(0, actions.items).map((a, i) => ( +
+ {marks[i] ?? '·'} + + {a.owner} + ({a.role}) {a.action} + + {a.jump && } +
+ ))} +
+ )} +
+
+
+ ); +} + +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(null); + /** 专家团召集面板:点头部「组建专家团」展开 */ + const [picker, setPicker] = useState(false); + + /** 质量专家名册来自 lib/teams(与会诊同一批人),不再显示经营口径的数字员工 */ + const experts = useMemo(() => qualityExperts(), []); + + /* 滚动策略:回答卡通常远高于对话区,一律贴底用户只能看到末尾。 + - 思考/打字阶段:对齐卡片顶部,让思考轨和逐字结论看得见; + - 分段亮出后:贴底跟随新段; + - 落卡与高度变化:仍然对齐最新答案卡顶部(避免只看到"数据来源"一行)。 */ + useEffect(() => { + const el = listRef.current; + if (!el) return; + const cards = el.querySelectorAll('[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('[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('[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('[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 ( +
+ {/* 与上方工作区的分隔饰条:中央亮渐变主线 + 下溢光晕 + 菱形饰点,比 1px 实线更清晰且有仪式感 */} +
+
+
+
+
+
+
+
+ + + + {t.agent.title} + + {/* 在岗质量专家:六位,悬停看角色;不再是经营口径的数字员工 */} + + {experts.map(e => ( + + ))} + + + + + +
+ + {picker && ( + setPicker(false)} /> + )} + + {team && ( +
+ + {team.nameZh} + + · {team.memberCodes.length} 位专家 · {team.topicZh} + + + +
+ )} + + {expanded && ( + <> +
+ {/* 消息贴底:对话从输入框往上长,不留中段空洞(内容满时该占位自动压为 0,不影响滚动) */} +
+ {msgs.map(m => { + /* 专家团就位播报:居中虚线卡,区别于专家发言 */ + if (m.kind === 'system') { + return ( +
+
+ + {m.name} · {m.tag} + + {m.text} +
+
+ ); + } + if ((m.kind === 'member' || m.kind === 'lead') && m.turn) { + return m.kind === 'member' + ? + : ; + } + /* 单轮问答:思考过程条 + 规范回答卡(结论/关键数字/明细/依据/行动/来源) */ + if (m.role === 'ai' && m.answer) { + return ( + + ); + } + const consult = m.kind === 'member' || m.kind === 'lead'; + const isLead = m.kind === 'lead'; + return ( +
+
+ {consult && ( +
+ + + + {m.name} + {m.tag && ( + {m.tag} + )} + {isLead && } +
+ )} +
{m.text}
+
+ {m.staff && ( + + {m.role === 'ai' && }{m.staff} + + )} + {m.time} +
+
+
+ ); + })} + {/* 会诊流式:就位播报逐字打出 → 成员卡/牵头卡逐块铺开 */} + {pendingTurn && pendingTurn.turn.kind === 'system' && (() => { + const full = pendingTurn.turn.text ?? ''; + const shown = full.slice(0, pendingTurn.typed); + return ( +
+
+ + {pendingTurn.turn.name} · {pendingTurn.turn.tag} + + {shown}{pendingTurn.typed < full.length && } +
+
+ ); + })()} + {pendingTurn && pendingTurn.turn.kind === 'member' && ( + + )} + {pendingTurn && pendingTurn.turn.kind === 'lead' && ( + + )} + {/* 流式推演:思考轨逐条揭示 → 结论打字 → 正文分段亮出;可一键跳过 */} + {pending && ( + + )} + {thinking && ( +
+ + {[0, 1, 2].map(i => )} + + {thinkingName ? `${thinkingName}${t.agent.thinking}` : t.agent.thinking}… +
+ )} +
+ +
+ {SUGGESTED.map(q => ( + + ))} +
+ + )} + +
+ + 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', + }} + /> + +
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/DemandPanel.tsx b/src/modules/tfamd-oee/components/DemandPanel.tsx new file mode 100644 index 0000000..28db680 --- /dev/null +++ b/src/modules/tfamd-oee/components/DemandPanel.tsx @@ -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 ( + } + title="质量流程" + badge={} + extra={ setAutoScroll(v => !v)} expanded={expanded} />} + animClass="space-animate-left" + > + + + + + ); +} diff --git a/src/modules/tfamd-oee/components/MecHeader.tsx b/src/modules/tfamd-oee/components/MecHeader.tsx new file mode 100644 index 0000000..749ac75 --- /dev/null +++ b/src/modules/tfamd-oee/components/MecHeader.tsx @@ -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['tokens']; title?: string; +}) { + return ( + + ); +} + +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) => 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 ( +
+
+
+ + +
+ + {/* ── 第一行:品牌 + 全局筛选 + 口径版本/数据模式 + 时钟主题 ── */} +
+
+ {/* 通富超威 TF-AMD 官方标识:红底白字,源图 513x128(官网 logo)。 + 浅色 / 深色两套主题沿用同一枚官方标识;宽度随视口收敛,避免挤压筛选区 */} + TF-AMD 通富超威 +
+

{t.appTitle}

+
+
+ +
+ + {/* 全局筛选:区域→线体→设备三级级联 + 业务日 + 班次。 + 上级换了就把不兼容的下级复位为 ALL,不允许矛盾组合流到下游。 */} +
+ {filters.map((f) => ( + + ))} +
+ +
+ +
+
+ {/* 本机时钟:时钟为本机时间、非数据新鲜度;日期行「本机」前缀于 2026-11-14 按要求移除 */} +
{timeStr}
+
{dateStr}
+
+ + +
+
+ + {children && ( +
+ {children} +
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/MetricNetwork.tsx b/src/modules/tfamd-oee/components/MetricNetwork.tsx new file mode 100644 index 0000000..8a5db18 --- /dev/null +++ b/src/modules/tfamd-oee/components/MetricNetwork.tsx @@ -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; + 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(null); + const hostRef = useRef(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(); + 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(); + 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(); + const anchors = new Set(); + [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(); + 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(); + 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(); + 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(); + 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(); + 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) => { + dragRef.current = { x: e.clientX, y: e.clientY }; + movedRef.current = false; + setCamAnim(false); + /* 不能在 pointerdown 就捕获指针:一旦捕获,浏览器会把后续 click 重定向到宿主元素, + 节点 永远收不到事件——表现就是“点实体后右侧看板不联动”。 + 指针捕获改到确实拖拽起来的那一刻(onMove 里)。 */ + }; + const onMove = (e: RPointerEvent) => { + 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 ( +
+ {/* 工具条可换行 + 上层 minWidth:0:不让按钮的 min-content 反过来决定图谱宽度; + minHeight 兜住一行高度,避免子项瞬时空高把工具条塌下去(塌一次 = 图谱重取景一次)。 */} +
+ {stage && ( + <> + + + {/* M4 影响传播:沿链路 BFS 涟漪 */} + + {/* 降密开关:末级驱动因子平时收起,避免图“密麻” */} + + + )} + + {/* 游标chip:提醒全图取值已锁定在该时点。 + “回放中”后缀恒定占位(只切 visibility):条件挂/卸会改工具条宽度 → 换行行数变 + → 图谱容器高度变 → 重取景,与悬停展开是同一条自激链。 */} + {stage && ( + + {periodLabel(period)} + 回放中 + + )} + + {/* 缩放徽标恒定占位:条件挂/卸会改变工具条 min-content → 容器宽度变 → 重放推镜 → 无限拖动 */} + {stage && ( + 0.01 ? 1 : 0, + }}>{Math.round((cam.k / fit) * 100)}% + )} + {/* 计数文本恒定宽:visible.size 会从 9 变到 59(悬停维度时), + 不定宽就会改变工具条 min-content → 换行/塌陷 → 图谱容器高变 → 重取景, + 节点从光标下移开 → 悬停失效 → 换行回去……就是“鼠标停在图上时一直抖”。 */} + + {stage ? `${visible.size}/${flat.length}` : flat.length} · {links.length} + + {stage ? ( + + ) : ( + + )} +
+ +
+ {/* M5 深空氛围:星云/星点/雷达扫描/暗角 */} + + + + {(['drive', 'conflict', 'monitor'] as const).map(r => ( + + + + ))} + {/* M1 星体渐变:亮心→本色→暗边,节点自带体积光 */} + + + + + + {(['green', 'yellow', 'red'] as const).map(lv => ( + + + + + + ))} + + + {!stage ? ( + /* ---------- 面板态:枢纽星座总览 ---------- */ + + {[-1, 0, 1].map(kk => ( + + ))} + {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 ( + + ); + })} + {['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 ( + { if (!dragRef.current) setHover(code); }} + onPointerLeave={() => { if (hover === code) setHover(null); }} + onClick={e => { if (!movedRef.current) { e.stopPropagation(); onSelect(code); } }} + > + {(isSel || isHot) && ( + + )} + {/* M3 声呐:枢纽偏离也自主扩散 */} + {sonar && !isOv && ( + + )} + {/* L1 行星达成率环 + 中心恒星呼吸光晕 */} + {isOv && } + {!isOv && } + {!isOv && } + + {nameOf(code)} + {count} {t.net.nodes} + + ); + })} + + ) : ( + /* ---------- 舞台态:指标知识图谱全景(深空叙事) ---------- */ + <> + + {/* 星系轨道环:呼吸的层级星环,强化径向布局的天体秩序 */} + {[300, 420, 545].map((rr, i) => ( + + ))} + + {/* 层级父子边(极淡底衬;悬停维度/总览时点亮整个扇区) */} + {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 ( + + ); + })} + + {/* 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 ( + + ); + } + return ( + + {/* 光晕底 / 主线 / 白亮芯 */} + + + + {/* 能量粒子:速度∝强度;conflict 额外逆向对撞 */} + + + + {l.relation === 'conflict' && ( + + + + )} + + ); + })} + + {/* 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 ( + { 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); }} + > + + {/* M3 声呐环(red 双波错峰 / yellow 单波慢速) */} + {sonar && ( + + )} + {sonar && lv === 'red' && ( + + )} + {(isSel || isHot) && ( + + )} + {/* L0 中心恒星:双层反转刻度环 + 呼吸光晕 */} + {code === 'OV' && ( + <> + + {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 ( + + ); + })} + + + + + + )} + {/* L1 行星:体积光球体 + 达成率环 */} + {n.level === 1 && ( + <> + + + + + + )} + {/* L2 KPI:达成率细弧卫星 */} + {n.level === 2 && ( + <> + + + + + )} + {/* L3 驱动因子:尘埃光点 */} + {n.level === 3 && ( + + )} + + ); + })} + + + {/* 标签层:世界坐标随相机同步 fly-to,字号逆缩放保持恒定可读;过渡期降透避让瞬时重叠 */} + + {labelPlan().map(l => ( + + {l.text} + {l.sub && ( + {l.sub} + )} + + ))} + + + )} + + + {/* 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 ( +
+
+ + {nameOf(hover)} + {hn.code} +
+
+ {([[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]) => ( +
+
{lab}
+
{val}
+
+ ))} +
+
+ {hn.owner} + {t.net.tipToPanel} +
+
+ ); + })()} + + {/* 图例与操作提示:深空下加玻璃胶囊衬底,不与标签打架 */} +
+ {(['drive', 'conflict', 'monitor'] as const).map(r => ( + + {t.net[r]} + + ))} +
+
+ {stage ? t.net.stageHint : t.net.hubHint} +
+
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/MetricTreePanel.tsx b/src/modules/tfamd-oee/components/MetricTreePanel.tsx new file mode 100644 index 0000000..7553fd6 --- /dev/null +++ b/src/modules/tfamd-oee/components/MetricTreePanel.tsx @@ -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; + 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>(() => 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(() => { + 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(); + 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 ( + : } + title={isTree ? t.panel.metricTree : t.flow.title} + badge={} + animClass="space-animate-left" + /* 指标网络不再占一个页签,改为标题行上的一颗按钮:点了就把图谱送到中央工作区。 + 两种页签下都保留这颗钮,不让人从流程效能绕路才能回图谱。 */ + extra={onMaximize ? ( + + ) : undefined} + tabs={ + <> + + + + } + > + {isTree ? ( + <> +
+ + 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 && ( + + )} +
+ + {/* 色条语义图例:三档与 execColor / EXEC_RED_LINE 同源,改阈值不会漏改 */} + {expanded && ( +
+ {t.panel.legendExec} + {[ + { 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 => ( + + {x.k} + + ))} +
+ )} + + + {rows.length === 0 && ( +
{t.tree.noResult}
+ )} + {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) => { if (!active) e.currentTarget.style.background = tokens.tableRowHover; }; + const leave = (e: MouseEvent) => { if (!active) e.currentTarget.style.background = base; }; + + const dot = ; + + const label = ( +
+
{name(n)}
+ {expanded && n.level >= 2 && ( +
{n.code} · {n.owner}
+ )} +
+ ); + + const nums = ( +
+
+ {fmt(valueAt(n, period))} + {unit} +
+
+ {t.detail.reach} {fmt(rate)}% +
+
+ ); + + /* L2 指标 → 独立指标卡:卡内留白撑开名称与数值,底边一条达成度进度条 */ + if (kind === 'card') { + return ( +
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, + }} + > +
+ {hasKids && ( + { e.stopPropagation(); toggleNode(n.code); }} + style={{ width: 16, flex: '0 0 16px', display: 'flex', alignItems: 'center', color: tokens.textMuted, cursor: 'pointer' }} + > + + + )} + {dot} + {label} + {nums} +
+
+
+
+
+ ); + } + + /* L3 驱动因子 → 从属子条目:左侧一道状态色连接线,挂在上方指标卡之下 */ + if (kind === 'drive') { + return ( +
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} +
+ ); + } + + /* L0 / L1 → 分组标题行,不参与卡片化,避免 54 行同质方框 */ + return ( +
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'}`, + }} + > + { 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 && } + + {dot} + {label} + {nums} +
+ ); + })} + + + ) : ( + + )} + + ); +} diff --git a/src/modules/tfamd-oee/components/MetricWorkspace.tsx b/src/modules/tfamd-oee/components/MetricWorkspace.tsx new file mode 100644 index 0000000..268dee8 --- /dev/null +++ b/src/modules/tfamd-oee/components/MetricWorkspace.tsx @@ -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('cockpit'); + /* D9:线体图节点/设备卡点击 → 主数据台账定位(携带设备 id,跨页签聚焦) */ + const [masterFocus, setMasterFocus] = useState(null); + /* 改善任务共享 state(W3-A):优先清单生成 → 录入台派发/流转,两页签共用一份。 + 初值由 L3 initialTasks() 现算优先级分(断言⑧),不在种子里写死; + 原型不落库(SQLite 锁定四表),改善任务为内存态。 */ + const [tasks, setTasks] = useState(() => 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 ; + /* 六个 OEE 页签统一吃 L3(oeeService):filter 决定范围/口径/业务日(与顶栏同源), + period 让趋势游标与底部回放同轴。视图只消费 L3 结果、不二次计算(断言②); + 未接入范围照实给缺口、不显示 0。原品质六视图已于 W2-B 换下(W4 删除 legacy 代码)。 */ + const oee = { filter, period }; + if (tab === 'cockpit') return ; + if (tab === 'trend') return ; + if (tab === 'structure') return ; + if (tab === 'region') return ; + if (tab === 'risk') return ; + if (tab === 'priority') return setTasks((prev) => [...prev, t])} />; + if (tab === 'entry') return ; + if (tab === 'task') return setTab(t as TabKey)} />; + if (tab === 'master') return ; + if (tab === 'caliber') return ; + if (tab === 'integration') return ; + /* W4-B:AI 预测(示意·非模型)/ 2D 线体图(SVG 拓扑+状态灯)/ 报表导出(7 类,与工具同源)。 + 报表读共享 tasks(改善闭环报表),与优先清单/录入台/任务中心同一份内存态。 */ + if (tab === 'forecast') return ; + if (tab === 'linemap') return { if (dev) setMasterFocus(dev); setTab(t as TabKey); }} />; + if (tab === 'report') return ; + return ; + }; + + 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 ( +
+ +
+ {corners.map(c =>
)} + + {/* 页头:当前菜单名;舞台入口已移到左侧菜单「全景舞台」组 */} +
+
+ +
+ +

+ {knowStage ? '知识库' : featStage ? '工艺建模' + : ontStage ? '业务本体' : dataStage ? '数据集总览' : netStage ? t.panel.metricNetwork : t.tab[tab]} +

+ +
+ {fullscreen && {t.tab.clickToRestore} / ESC} +
+
+ + {/* 内容区:页面视图 + 底部时间回放轴;对话区已移到右侧独立列(常驻挂载,进出舞台会话不丢)。 + 舞台 7:3:左=图谱 + 时间轴(70%)· 右=因果看板贯通到底(30%) + 本体等舞台独占整块内容区,时间轴在此让位。 */} +
+ {knowStage ? ( + { setKnowStage(false); setKbFocus(null); setFullscreen(false); }} + focus={kbFocus} + /> + ) : featStage ? ( + { setFeatStage(false); setFeatFocus(null); setFullscreen(false); }} + focus={featFocus} + /> + ) : ontStage ? ( + { setOntStage(false); setFullscreen(false); }} /> + ) : dataStage ? ( + { setDataStage(false); setFullscreen(false); }} focus={dataFocus} /> + ) : ( + <> +
+ {netStage ? ( +
+ +
+ ) : ( + /* key=tab 触发入场动画,让切换有落点感 */ +
+ {renderView()} +
+ )} + {/* 全局时间游标:两种形态都常驻——时间轴是全局口径开关,不该只活在全景里 */} + +
+ {/* 地板降到 240:非全屏的小窗口下也不至多把图谱压成几十px */} + {netStage && (causalOpen ? ( +
+ setCausalOpen(false)} + /> +
+ ) : ( + + ))} + + )} +
+
+ {agentOpen ? ( +
+ +
+ setAgentOpen(false)} /> +
+
+ ) : ( +
+ + +
+ )} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/OeeAgentDock.tsx b/src/modules/tfamd-oee/components/OeeAgentDock.tsx new file mode 100644 index 0000000..f32bfc4 --- /dev/null +++ b/src/modules/tfamd-oee/components/OeeAgentDock.tsx @@ -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 ( + + + {agent.name} + + 运行中 + + + ); +} + +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(null); + const expanded = column || height > 120; + + /* 滚动策略:回答卡通常远高于对话区,一律贴底用户只能看到末尾。 + - 思考 / 打字阶段:对齐卡片顶部,让思考轨和逐字结论看得见; + - 分段亮出后:贴底跟随新段; + - 落卡与高度变化:对齐最新答案卡顶部(避免只看到"出处"一行)。 */ + useEffect(() => { + const el = listRef.current; + if (!el) return; + const cards = el.querySelectorAll('[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('[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) => ( + + ); + + return ( +
+ {/* 头部:标题 + 模型增强开关 + 清空 / 拉高 / 展开 */} +
+ + + + + OEE专家智能体 + + + {/* 模型增强开关:'llm' 现场演示降级①(无端点 → 规则引擎应答) */} + + + + {iconBtn(reset, '清空对话,回到问候', )} + {expanded && !column && onToggleTall && iconBtn(onToggleTall, tall ? '还原高度' : '拉高对话区', tall ? : , tall)} + {column + ? iconBtn(onToggle, '收起对话区', ) + : iconBtn(onToggle, expanded ? '收起对话区' : '展开对话区', expanded ? : )} +
+ + {/* A1–A7 名册:A1–A4 运行中,A5–A7 分期占位(仅展开态显示) */} + {expanded && ( +
+ {OEE_AGENTS.filter((a) => a.implemented).map((a) => )} +
+ )} + + {/* 对话列表 */} + {expanded && ( +
+ {msgs.map((m) => { + if (m.role === 'user') { + return ( +
+
+ {m.text} + {m.time} +
+
+ ); + } + if (m.answer) { + return ; + } + /* 问候 / 纯文本 ai 消息 */ + return ( +
+
+ {m.text} +
+
+ ); + })} + + {/* 流式回答卡 */} + {pending && ( + + )} + + {/* 异步取数中:分析中气泡 */} + {thinking && ( +
+ + {[0, 1, 2].map((i) => )} + + 正在经五类受控工具取数… +
+ )} +
+ )} + + {/* 快捷问句:一句一个意图 / 智能体(仅展开态、空闲时显示) */} + {expanded && !busy && ( +
+ {OEE_SUGGESTED.map((s, i) => ( + + ))} +
+ )} + + {/* 输入区 */} +
+ 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, + }} + /> + +
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/StarBackground.tsx b/src/modules/tfamd-oee/components/StarBackground.tsx new file mode 100644 index 0000000..cc5f4fe --- /dev/null +++ b/src/modules/tfamd-oee/components/StarBackground.tsx @@ -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(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 ( + + ); +} diff --git a/src/modules/tfamd-oee/components/SupplyPanel.tsx b/src/modules/tfamd-oee/components/SupplyPanel.tsx new file mode 100644 index 0000000..af03db5 --- /dev/null +++ b/src/modules/tfamd-oee/components/SupplyPanel.tsx @@ -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('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 ( + } + title={current.label} + badge={} + extra={ setAutoScroll(v => !v)} expanded={expanded} />} + animClass="space-animate-right" + tabs={ + <> + {TABS.map(x => ( + /* 收起态宽度只够两个字:页签用短标签,避免挤成一列竖排 */ + + ))} + + } + > + {/* 搜索:三个页签共用,占位提示随页签切换 */} +
+ + 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 && ( + + )} +
+ + + {tab === 'po' && ( + onSelectSO(null)} + /> + )} + {tab === 'wo' && ( + onSelectSO(null)} + selectedSO={selectedSO} + onSelectSO={onSelectSO} + /> + )} + {tab === 'sup' && ( + onSelectSO(null)} + /* 点供应商=带着它的编码跳到采购单页签,只看这家下的单 */ + onPickSupplier={code => { setQuery(code); setTab('po'); }} + /> + )} + +
+ ); +} diff --git a/src/modules/tfamd-oee/components/agent/AskAnswerCard.tsx b/src/modules/tfamd-oee/components/agent/AskAnswerCard.tsx new file mode 100644 index 0000000..92faf65 --- /dev/null +++ b/src/modules/tfamd-oee/components/agent/AskAnswerCard.tsx @@ -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 ( +
+ {icon} + {text} + {hint && · {hint}} + +
+ ); +} + +/** 打字点:思考进行中用,揭示一条停一条 */ +function Dots({ tk }: { tk: ThemeTokens }) { + return ( + + {[0, 1, 2].map(i => ( + + ))} + + ); +} + +/** + * 思考过程轨: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 ( +
+ + {open && ( +
+ {shown.map((s, i) => ( +
+ {i + 1} + + {s.act} + · {s.detail} + +
+ ))} + {running && revealed < steps.length && ( +
+ + {steps[revealed]?.act ?? t.agent.thinkHint} +
+ )} +
+ )} +
+ ); +} + +/** 跳转目的地的图标与 data-role(供核验脚本点击) */ +const JUMP_META: Record = { + metric: { icon: , role: 'jump-metric' }, + tab: { icon: , role: 'jump-tab' }, + ontology: { icon: , role: 'jump-ontology' }, + dataset: { icon: , role: 'jump-dataset' }, + knowledge: { icon: , role: 'jump-knowledge' }, + feature: { icon: , role: 'jump-feature' }, + ask: { icon: , 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 ( + + ); +} + +/** 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: () => ( +
+ + + {answer.conclusion} + +
+ ), + }); + if (answer.metrics.length) { + out.push({ + key: 'numbers', count: answer.metrics.length, + node: (limit) => ( +
+ } text={t.agent.secNumbers} tk={tk} /> +
+ {answer.metrics.slice(0, limit).map((m, i) => { + const c = tone(m.tone); + return ( + + {m.label} + {m.value} + + ); + })} +
+
+ ), + }); + } + if (answer.table) { + const tbl = answer.table; + out.push({ + key: 'table', count: tbl.rows.length, + node: (limit) => ( +
+ } text={t.agent.secTable} tk={tk} hint={`${Math.min(limit, tbl.rows.length)} 行`} /> +
+ + + + {tbl.cols.map((c, i) => ( + + ))} + + + + {tbl.rows.slice(0, limit).map((r, ri) => { + const c = tone(r.tone); + return ( + + {r.cells.map((cell, ci) => ( + + ))} + + ); + })} + +
{c}
{cell}
+
+
+ ), + }); + } + if (answer.points.length) { + out.push({ + key: 'basis', count: answer.points.length, + node: (limit) => ( +
+ } text={t.agent.secBasis} tk={tk} /> +
+ {answer.points.slice(0, limit).map((p, i) => { + const c = tone(p.tone); + return ( +
+ {p.label} + {p.text} +
+ ); + })} +
+
+ ), + }); + } + if (answer.actions.length) { + out.push({ + key: 'actions', count: answer.actions.length, + node: (limit) => ( +
+ } text={t.agent.secActions} tk={tk} + hint={t.agent.jumpHint} + /> +
+ {answer.actions.slice(0, limit).map((a, i) => ( + + + + ))} +
+
+ ), + }); + } + out.push({ + key: 'source', count: 1, + node: () => ( +
+ + + {t.agent.secSource}:{answer.source} + +
+ ), + }); + 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 ( +
+
+ {/* 卡头:智能体名 + 识别到的意图 + 应答归属 + 时间 */} +
+ + + + {t.agent.aiName} + {t.agent.secIntent}:{answer.intent} + {staff && ( + {staff} + )} + {time} +
+ + {/* 思考轨:推演中逐条展开,落卡后折叠成一行供复查 */} + + +
+ {/* 思考阶段:正文还没开始写,只给一行"正在取数"的占位,不摆假数字 */} + {streaming && !inBody && ( +
+ + {answer.steps[Math.min(streaming.revealedSteps, answer.steps.length - 1)]?.act ?? t.agent.thinkHint} + · {t.agent.thinkHint} +
+ )} + + {inBody && ( + <> +
+ + + {typedText} + {typing && ▍} + +
+ {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
{p.node(limit)}
; + })} + + )} + + {!streaming && parts.map(p =>
{p.node(p.count)}
)} + + {/* 推演进行中:给一个「跳过推演」,不想等的用户一键落到完整卡 */} + {streaming && onSkip && ( + + )} +
+
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/agent/OeeAnswerCard.tsx b/src/modules/tfamd-oee/components/agent/OeeAnswerCard.tsx new file mode 100644 index 0000000..bd13b14 --- /dev/null +++ b/src/modules/tfamd-oee/components/agent/OeeAnswerCard.tsx @@ -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 = { + 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 ( +
+ {icon} + {text} + {hint && · {hint}} + +
+ ); +} + +/** 打字点:思考进行中用,揭示一条停一条 */ +function Dots({ tk }: { tk: ThemeTokens }) { + return ( + + {[0, 1, 2].map((i) => ( + + ))} + + ); +} + +/** 思考过程轨: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 ( +
+ + {open && ( +
+ {shown.map((s, i) => ( +
+ {i + 1} + + {s.act} + · {s.detail} + +
+ ))} + {running && revealed < steps.length && ( +
+ + {steps[revealed]?.act ?? L.thinkHint} +
+ )} +
+ )} +
+ ); +} + +/** 跳转目的地的图标与 data-role(供核验脚本点击)。OEE 只有 tab / ontology / ask 三种。 */ +const JUMP_META: Record = { + tab: { icon: , role: 'jump-tab' }, + ontology: { icon: , role: 'jump-ontology' }, + ask: { icon: , 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 ( + + ); +} + +/** 横幅:降级 / 停止 / 闸门拦截,照实展示,不藏缺口。 */ +function Banner({ icon, title, text, color, tk }: { icon: ReactNode; title: string; text: string; color: string; tk: ThemeTokens }) { + return ( +
+ {icon} + + {title} + · {text} + +
+ ); +} + +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: () => ( +
+
+ + {concl} +
+ {answer.four.evidence && ( +
+ + {L.evidence}:{answer.four.evidence} + +
+ )} +
+ ), + }); + if (answer.metrics.length) { + out.push({ + key: 'numbers', count: answer.metrics.length, + node: (limit) => ( +
+ } text={L.secNumbers} tk={tk} /> +
+ {answer.metrics.slice(0, limit).map((m, i) => { + const c = tone(m.tone); + return ( + + {m.label} + {m.value} + + ); + })} +
+
+ ), + }); + } + if (answer.table) { + const tbl = answer.table; + out.push({ + key: 'table', count: tbl.rows.length, + node: (limit) => ( +
+ } text={tbl.title || L.secTable} tk={tk} hint={`${Math.min(limit, tbl.rows.length)} 行`} /> +
+ + + + {tbl.cols.map((c, i) => ( + + ))} + + + + {tbl.rows.slice(0, limit).map((r, ri) => ( + + {r.map((cell, ci) => ( + + ))} + + ))} + +
{c}
{cell}
+
+
+ ), + }); + } + if (answer.benefits?.length) { + const bs = answer.benefits; + out.push({ + key: 'benefits', count: bs.length, + node: (limit) => ( +
+ } text={L.secBenefits} tk={tk} /> +
+ {bs.slice(0, limit).map((b, i) => ( + + + {b.min} – {b.max} + + {b.unit} + + ))} +
+
+ ), + }); + } + if (answer.points.length) { + out.push({ + key: 'basis', count: answer.points.length, + node: (limit) => ( +
+ } text={L.secBasis} tk={tk} /> +
+ {answer.points.slice(0, limit).map((p, i) => { + const c = tone(p.tone); + return ( +
+ {p.label} + {p.text} +
+ ); + })} +
+
+ ), + }); + } + if (answer.citations.length) { + out.push({ + key: 'citations', count: answer.citations.length, + node: (limit) => ( +
+ } text={L.secCitations} tk={tk} hint="本地 TF-IDF 余弦·零依赖" /> +
+ {answer.citations.slice(0, limit).map((c, i) => ( +
+ {c.corpus} + + {c.title} + · {c.source} · 命中 {c.score.toFixed(3)} + +
+ ))} +
+
+ ), + }); + } + if (answer.actions.length) { + out.push({ + key: 'actions', count: answer.actions.length, + node: (limit) => ( +
+ } text={L.secActions} tk={tk} hint={L.jumpHint} /> +
+ {answer.actions.slice(0, limit).map((a, i) => ( + + {a.jump + ? + : {a.label}} + + ))} +
+
+ ), + }); + } + out.push({ + key: 'source', count: 1, + node: () => ( +
+
+ + + {L.secSource}:{answer.four.source} + +
+ {answer.four.nextStep && ( +
+ + + {L.secNext}:{answer.four.nextStep} + +
+ )} +
+ ), + }); + 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 ( +
+
+ {/* 卡头:智能体标准名 + 识别意图 + 业务日 / 口径 + 发布状态 + 时间 */} +
+ + + + {answer.agentName} + {L.intent}:{answer.intentLabel} + {answer.bizDate} + {answer.published ? L.published : answer.halt ? L.halted : L.unpublished} + {time} +
+ + {/* 思考轨 */} + + + {/* 闸门 / 降级 / 停止横幅:照实展示,不藏缺口 */} + {!answer.guard.ok && ( + } title={`${L.guardFail} · 闸${answer.guard.gate}`} text={answer.guard.reason ?? ''} color={tk.danger} tk={tk} /> + )} + {answer.stopped && ( + } title={`${L.stoppedTitle} · ${answer.stopped.skill}`} text={`${answer.stopped.condition} → ${answer.stopped.action}`} color={tk.warning} tk={tk} /> + )} + {answer.degraded && ( + } + title={DEGRADE_LABEL[answer.degraded]} + text={answer.four.degradedReason ?? ''} + color={answer.degraded === 'MODEL_UNAVAILABLE' ? tk.info : tk.warning} + tk={tk} + /> + )} + +
+ {/* 思考阶段:正文还没开始写,只给一行"正在取数"的占位,不摆假数字 */} + {streaming && !inBody && ( +
+ + {answer.steps[Math.min(streaming.revealedSteps, answer.steps.length - 1)]?.act ?? L.thinkHint} · {L.thinkHint} +
+ )} + + {inBody && ( + <> +
+ + + {typedText}{typing && ▍} + +
+ {conclDone && answer.four.evidence && ( +
+ + {L.evidence}:{answer.four.evidence} + +
+ )} + {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
{p.node(limit)}
; + })} + + )} + + {!streaming && parts.map((p) =>
{p.node(p.count)}
)} + + {/* 推演进行中:给一个「跳过推演」,不想等的用户一键落到完整卡 */} + {streaming && onSkip && ( + + )} +
+ + {/* 应答来源标注:规则引擎(LLM 是增强项,不是前提) */} +
+ + {answer.four.answeredBy === 'RULE_ENGINE' ? L.ruleEngine : '大模型应答'} · 五道防幻觉闸门 · 数字只来自五类受控工具 + +
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/agent/TeamPicker.tsx b/src/modules/tfamd-oee/components/agent/TeamPicker.tsx new file mode 100644 index 0000000..45d0cf0 --- /dev/null +++ b/src/modules/tfamd-oee/components/agent/TeamPicker.tsx @@ -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([]); + + 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 ( +
+
+ + {t.team.panel} + + +
+
{t.team.presetHint}
+ + {/* 预设团:一键就位 */} +
+ {presets.map(p => { + const c = toneColor(p.tone, tk); + return ( + + ); + })} +
+ + {/* 自建团:勾选专家,首位为牵头 */} +
+
{t.team.customTitle}
+
{t.team.customHint}
+
+ {experts.map(e => { + const on = sel.includes(e.code); + const lead = sel[0] === e.code && sel.length >= 2; + return ( + + ); + })} +
+
+ = 2 ? tk.textSub : tk.textMuted }}> + {sel.length >= 2 ? `${t.team.selected}:${sel.map(nameOf).join('、')}` : t.team.needTwo} + + + + +
+
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/alert/OeeAlertPanel.tsx b/src/modules/tfamd-oee/components/alert/OeeAlertPanel.tsx new file mode 100644 index 0000000..482f9cb --- /dev/null +++ b/src/modules/tfamd-oee/components/alert/OeeAlertPanel.tsx @@ -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(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 ( + } + title="OEE 告警" + badge={} + extra={ setAutoScroll((v) => !v)} expanded={expanded} />} + animClass="space-animate-right" + > + {/* 汇总带固定在标题下方,不随列表滚走:滚到哪儿都知道整池是什么结构 */} +
+
+ {day ? '当日实测' : '未接入'} + {scope.bizDate} + {day && · {day.device.id}} +
+ + {/* S4 阻断置顶:有权暂停发布,必须在汇总带就看见,不靠展开卡片才发现 */} + {sum.blocksPublish && ( +
+ + 结论暂缓发布 · S4 数据质量阻断 +
+ )} + + {day ? ( +
+ {bands.length === 0 && ( + 当日无告警触发 + )} + {bands.map((x) => ( + + + {x.n} + {ALERT_LEVELS[x.lv].label} + + ))} +
+ ) : ( +
{scope.scopeLabel}
+ )} +
+ + + + {!day && ( +
+
+ 该范围无日志贯通结果,不显示告警,也不显示 0 +
+
{scope.gap}
+
+ )} + {day && alerts.length === 0 && ( +
+ 当日无告警触发 +
+ )} + {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 ( + + {!prev || prev.level !== x.level ? ( +
+ + {ALERT_LEVELS[x.level].label} · {sum.byLevel[x.level]} + + +
+ ) : null} + setOpenId(openId === x.id ? null : x.id)} tk={tokens} delay={delay} /> +
+ ); + })} +
+
+ + {/* 优先清单脚注:全站候选 Top3(信息性披露),不在此跳页。 + 导航指引半句「详见中央『优先处理清单』页签」于 2026-11-14 按要求移除(与标题行同名、冗余); + 口径披露「全站候选(POC 指向)」保留:Top3 不随筛选变化,防误读为当日单机现算。 */} +
+
+ + 优先处理清单 · Top3 + + 默认 B 套权重 +
+ {top3.map((r) => ( +
+ {r.rank} + {r.item.title} + + {r.score.score.toFixed(3)} + +
+ ))} +
+ 全站候选(POC 指向) +
+
+
+ ); +} + +/* ── 单张告警卡 ───────────────────────────────────────────────────────── */ +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 ( +
+ + + {/* 展开态:判定字段 + 处置动作 + 责任/升级 + 状态 + 口径 + 来源,就地给出,不跳转 */} + {open && ( +
+
+ {x.fields.map((f) => ( +
+ {/* 标签列不折行:'判定条件' 被压成两行时整块明细读起来很碎 */} + {f.label} + {f.value} +
+ ))} +
+ +
+ 处置动作 +
{x.action}
+
+ 责任:{x.owner} · 升级:{x.escalation} +
+
+ 状态 + {ALERT_STATE_LABEL[x.state]} +
+
+ +
+
判定口径:{x.caliber}
+
+ {x.source} + 数据来源 +
+
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/alert/OeeAlertStrip.tsx b/src/modules/tfamd-oee/components/alert/OeeAlertStrip.tsx new file mode 100644 index 0000000..2f5629e --- /dev/null +++ b/src/modules/tfamd-oee/components/alert/OeeAlertStrip.tsx @@ -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 && ( +
setDrawer(false)} + style={{ position: 'fixed', inset: 0, zIndex: 70, background: 'rgba(0,0,0,0.28)', display: 'flex', justifyContent: 'flex-end' }} + > +
e.stopPropagation()} style={{ height: '100%', padding: '16px 0', display: 'flex' }}> + setDrawer(false)} filter={filter} /> +
+
+ ); + + if (compact) { + return ( + <> + + {drawerEl} + + ); + } + + return ( + <> +
+
+ + OEE 告警 + + + {day ? '当日实测' : '未接入'} · {scope.bizDate}{day ? ` · ${day.device.id}` : ''} + + + +
+ +
+ {sum.blocksPublish && ( + + 结论暂缓发布 + + )} + {day && bands.length === 0 && 当日无告警触发} + {bands.map((x) => ( + + + {x.n} + {ALERT_LEVELS[x.lv].label} + + ))} + {!day && {scope.scopeLabel}} +
+ + {alerts.slice(0, 2).map((x) => ( +
+ + {x.kind} + {x.title} +
+ ))} +
+ + {drawerEl} + + ); +} diff --git a/src/modules/tfamd-oee/components/alert/QualityAlertPanel.tsx b/src/modules/tfamd-oee/components/alert/QualityAlertPanel.tsx new file mode 100644 index 0000000..06d22a9 --- /dev/null +++ b/src/modules/tfamd-oee/components/alert/QualityAlertPanel.tsx @@ -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(null); + + const list = useMemo(() => qualityAlertsAt(period), [period]); + const sum = useMemo(() => alertSummary(list), [list]); + const a = t.alert; + const levelName: Record = { + 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 ( + } + title={a.title} + badge={} + extra={ setAutoScroll(v => !v)} expanded={expanded} />} + animClass="space-animate-right" + > + {/* 汇总带固定在标题下方,不随列表滚走:滚到哪儿都知道整池是什么结构 */} +
+
+ {period === CURRENT_PERIOD ? '源表当期' : '回放推算'} + {period === CURRENT_PERIOD ? '2026-10 快照' : `${periodLabel(period)} · 缺口明细仍为源表`} +
+
+ {bands.map(x => ( + + + {x.n} + {levelName[x.lv]} + + ))} +
+
+ + + + {list.length === 0 && ( +
{a.empty}
+ )} + {list.map((x, i) => { + const prev = list[i - 1]; + /* 换档时插一条分带线:滚动流里靠颜色条看不出档位变化 */ + return ( + + {!prev || prev.level !== x.level ? ( +
+ + {levelName[x.level]} · {sum[x.level]} + + +
+ ) : null} + setOpenId(openId === x.id ? null : x.id)} tk={tokens} /> +
+ ); + })} +
+
+
+ ); +} + +/* ── 单张告警卡 ───────────────────────────────────────────────────────── */ +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 ( +
+ + + {/* 展开态:原表全部字段 + 处置动作 + 判定口径 + 来源,就地给出,不跳转 */} + {open && ( +
+
+ {x.fields.map(f => ( +
+ {/* 标签列不折行:'标准值 / 允许偏差' 被压成两行时整块明细读起来很碎 */} + {f.label} + {f.value} +
+ ))} +
+ +
+ {a.action} +
{x.action}
+ {(x.owner || x.role) && ( +
+ {a.owner}:{x.owner || '—'} · {x.role} +
+ )} +
+ +
+
{a.caliber}:{x.caliber}
+
+ {x.source.ds} + {a.source}:{x.source.table} +
+
+
+ )} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/caliber/CaliberVersionPanel.tsx b/src/modules/tfamd-oee/components/caliber/CaliberVersionPanel.tsx new file mode 100644 index 0000000..2173d27 --- /dev/null +++ b/src/modules/tfamd-oee/components/caliber/CaliberVersionPanel.tsx @@ -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 = { + 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([baseline]); + const [editId, setEditId] = useState('C03'); + const [editValue, setEditValue] = useState(''); + const [replayIdx, setReplayIdx] = useState(null); + const [ackCross, setAckCross] = useState(false); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + const [signSandbox, setSignSandbox] = useState(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 项口径字典(真实台账,全未签字) ── */} + } + full + right={待 IE 签字 {realStatus.unsigned}/{realStatus.total}} + note="两个「优先级」不可混:priority P0/P1/P2 影响「能不能算」(P0 16/P1 11/P2 1);isSensitivityKey(★)影响「算出来是多少」(5 项承载 4 议题)。本次不安排口径工作坊,signedOff 全 false,P0 标灰「待 IE 签字」——灰不等于错,是还没人签字。" + > + +
+ + + }> + {items.map((c) => ( + { setEditId(c.id); setEditValue(''); setMsg(null); }}> + + + + + + + + ))} +
编号口径项默认值优先级归口签字
{c.id}{c.isSensitivityKey && ★}{c.name}{String(c.defaultValue)}{c.priority}{c.owner}待签字
+
+ + {/* 试改一项 → 解析新版本 */} +
+
+ + +
+
+ + setEditValue(e.target.value)} placeholder={editItem ? `如改 ${editId} 的取值…` : '选择口径项'} /> +
+ +
+ {editItem?.isSensitivityKey && ( + ★ {editId} 属敏感性议题({Object.values(SENSITIVITY_ISSUES).filter((s) => (s.items as readonly string[]).includes(editId)).map((s) => s.label).join('、')}):改它会改变 OEE 绝对值,须 IE 定版。跨版本对比默认拒绝。 + )} + {msg && ( +
{msg.text}
+ )} +
+ + {/* ── 版本历史/回放/跨版本闸 + 签字沙箱 ── */} +
+ } + right={{cmp.allowed ? '允许对比' : '拒绝跨版本'}} + note="断言⑩:两个口径版本的结果不可直接相减。默认拒绝;显式确认(IE)后也只允许并列展示,差值含口径效应,不得作为改善成果发布。点历史条目回放旧版。" + > + {/* 版本历史 */} + }> + {history.map((h, i) => { + const on = i === viewIdx; + return ( + { setReplayIdx(i === currentIdx ? null : i); setMsg(null); }} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}> + + + + + + ); + })} +
版本来源变更回放
{h.version}{h.label}{i === currentIdx ? '(当前)' : ''}{h.changeCount}{on ? 查看中 : 回放}
+ + {/* 跨版本闸通知 */} +
+
+ {cmp.allowed ? : } + + {diff.sameVersion ? '同一口径版本' : cmp.allowed ? '已确认·仅并列不相减' : '拒绝跨版本对比'} + +
+
{cmp.notice}
+ {!diff.sameVersion && ( + + )} +
+ + {/* 差异明细 */} + {diff.changes.length > 0 ? ( +
+ 对基线({baseline.version})的取值差异(只比取值,不比签字状态): + }> + {diff.changes.map((c) => ( + + + + + + + ))} +
编号基线值回放值敏感性
{c.id}{c.isSensitivityKey && ★}{String(c.before)}{String(c.after)}{c.isSensitivityKey ? 影响 OEE : 非敏感}
+ {diff.affectedIssues.length > 0 && ( +
+ {diff.affectedIssues.map((k) => {SENSITIVITY_LABEL[k]})} +
+ )} +
+ ) : ( + 当前查看版本与基线取值一致(无差异)。改一项敏感性口径即可看到跨版本拒绝闸。 + )} + + {/* 回放快照 */} +
+ 回放快照 · {viewed.version} 的敏感性取值(引擎现推,不写死): + }> + + + + +
议题取值
Plan 边界{viewed.config.sensitivitySnapshot.planBoundary}
Occ 判定{viewed.config.sensitivitySnapshot.occRule}
Q 定义{viewed.config.sensitivitySnapshot.qDefinition}
FT 的 PM 计入{viewed.config.sensitivitySnapshot.ftPmIncluded ? '是' : '否'}
+
+
+ + } + right={真实台账 P0 {realStatus.p0Tone === 'green' ? '已签' : '标灰'}} + note="签字改的是治理状态,不改取值 ⇒ signOff 不递增版本号(引擎 invariant)。真实台账 CALIBER_CONFIG 永远全未签字;下方沙箱只在副本上演示「IE 签字后 P0 才转绿」,明确标注模拟,不写回真实台账。" + > + {/* 真实签字状态 */} + +
+ +
+ + {/* 沙箱 */} +
+ + {signSandbox && ( + + )} +
+ {sandboxStatus && signSandbox && ( +
+
沙箱结果(模拟,非真实 IE 确认)
+
+ P0 {sandboxStatus.p0Tone === 'green' ? '转绿' : '仍灰'} + 已签 {sandboxStatus.signed}/{sandboxStatus.total} + 版本仍 {signSandbox.version} +
+ 签字后版本不变({signSandbox.version}):signOff 只改 signedOff 治理状态,不改取值,OEE 数值不变。真实台账未受影响,仍全未签字。 +
+ )} + {!signSandbox && 点「模拟 IE 签字」在副本上演示治理流程:P0 全签后 p0Tone 才转 green,且版本号不递增。真实台账保持「待 IE 签字」。} +
+
+ + ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/caliber/ConfigAxesPanel.tsx b/src/modules/tfamd-oee/components/caliber/ConfigAxesPanel.tsx new file mode 100644 index 0000000..d41342f --- /dev/null +++ b/src/modules/tfamd-oee/components/caliber/ConfigAxesPanel.tsx @@ -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({ ...OEE_PARAMS }); + const [applied, setApplied] = useState<{ params: ThreeTierParams; revision: number } | null>(null); + const [revision, setRevision] = useState(0); + const [paramMsg, setParamMsg] = useState(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(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 ( + <> + {/* ① 三层参数重算(断言②) */} + } + right={沙箱试算 · 不写全局} + note={ + <> + 试改 C27/C28 五个参数 → runDekDay(seed, {'{params, revision}'}) 重算。 + 实际档由实测算出(RT/PPT、N×ICT/RT、良品/N),与参数无关,Δ 恒为 0; + 参数只移动理论/计划档。试算版本标签 {versionTag} 为沙箱修订号; + 数据血缘口径版本(caliberVersion)仅在 D 类补录时递增,治理见上方「口径字典与版本」。 + + } + > + {baseline ? ( +
+ {/* 左:参数编辑器 */} +
+ + + }> + {PARAM_META.map((m) => ( + + + + + + ))} +
参数(口径项)驱动试改值
+ {m.label} +
+ {m.caliber} · 待 IE 签字 +
+
{m.drives}
{m.unit}
+ { + const v = Number(e.target.value); + setDraft((d) => ({ ...d, [m.key]: Number.isFinite(v) ? v : d[m.key] })); + }} + /> +
默认 {OEE_PARAMS[m.key]}
+
+
+ + + + 修订 r{revision} +
+ {paramMsg && ( +
+ {paramMsg} +
+ )} +
+ {/* 右:三档对照 */} +
+ + + }> + {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 ( + + + + + + + ); + })} +
口径档基线重算Δ(pp)
+ {r.label} +
{r.note}
+
{pct(b)}%{pct(n)}% 0 ? tokens.success : tokens.warning}> + {isActual ? '0.00 · 实测' : `${d >= 0 ? '+' : ''}${d.toFixed(2)}`} +
+ +
+
+ ) : ( + 业务日 {bizDate} 无锚点单机种子,无法重算。请在顶栏选择已接入的锚点设备日。 + )} +
+ + {/* ② 算法模板 · 三区域不同构 */} + } + right={口径骨架 · 不嵌结果数字} + note="三站分母与算式不同构:SRF 缓冲解耦、FT 多因子连乘(A 不是 RT/PPT)、ASLT 事件驱动(活跃窗口)。每个中间量带 formula+operands+source,可在「工序·工位对比」页逐项展开复核(断言①)。" + > +
+ {TEMPLATE_DESC.map((t) => ( +
+
{TEMPLATE_LABEL[t.id]}
+ {([['A', t.a], ['P', t.p], ['Q', t.q]] as const).map(([f, txt]) => ( +
+ {f} + {txt} +
+ ))} +
+ {t.caliber} +
+
+ ))} +
+
+ + {/* ③ 间隙阈值 + ④ 优先级权重:两卡并列,内容量相近,stretch 底边对齐 */} +
+ } + right={POC 单列 {ds.gapFromPoc} 台} + note="公式默认 max(5min, 3×ICT/60);台账校准值优先。kohyoung AOI001=15min(公式 18)、Jetting JET001=3min(公式 5)两处≠默认值,逐台对照如下。ICT=0 的设备公式默认落 5min。阈值为主数据,编辑在「主数据」页。" + > + + + }> + {DEVICES.map((d) => { + const formula = defaultGapThresholdMin(d.ictSec); + const overridden = d.gapSource === 'POC' && Math.abs(formula - d.gapThresholdMin) > 1e-9; + return ( + + + + + + + + + ); + })} +
设备区域ICT(s)公式默认台账值来源
+ {d.id} +
{d.name}
+
{d.region} 0 ? tokens.textSub : tokens.textMuted}>{d.ictSec > 0 ? d.ictSec : '—'}{formula.toFixed(1)}{d.gapThresholdMin} + + {d.gapSource === 'POC' ? 'POC' : '默认'} + + {overridden &&
≠公式
} +
+
+ + } + right={ + + {(['A', 'B'] as WeightSchemeId[]).map((id) => ( + + ))} + + } + note={`当前 ${ws.label}(${ws.source})。A/B 五维互不重叠(${ps.schemesDisjoint ? '已校验' : '异常'}),权重之和 A=${ps.weightSumA.toFixed(2)} / B=${ps.weightSumB.toFixed(2)}。完整逐项 weight×factor 贡献在「优先处理清单」页展开(断言⑧)。`} + > + 下表 A/B 名次对比为演示沙箱(PRIORITY_CANDIDATES demo 候选 C1–C6)。 +
+ + + }> + {ws.dims.map((dim) => ( + + + + + ))} +
当前方案维度权重
{dim.label}{dim.weight.toFixed(2)}
+
+ + 换权重排序: + {cmp.orderChanged ? '名次变化' : '名次未变'} +
+ + + }> + {PRIORITY_CANDIDATES.map((c) => { + const ra = rankAOf(c.id); + const rb = rankBOf(c.id); + const moved = ra !== rb; + return ( + + + + + + + ); + })} +
候选项A 名次B 名次变化
+ {c.id} +
{c.title}
+
{ra}{rb}{moved ? `${ra}→${rb}` : '—'}
+
+
+
+ + ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/caliber/OeeCaliberCenter.tsx b/src/modules/tfamd-oee/components/caliber/OeeCaliberCenter.tsx new file mode 100644 index 0000000..2412c33 --- /dev/null +++ b/src/modules/tfamd-oee/components/caliber/OeeCaliberCenter.tsx @@ -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 ( +
+ } + extra={口径治理 · 断言②⑩} + /> + + + 配置中心是 OEE 的口径单一来源:28 项口径字典(附录 E 默认值)+ 三层参数(C27/C28)+ + 三区域算法模板 + 逐台间隙阈值 + 优先级权重 A/B。本次不安排口径工作坊,{cs.total} 项 signedOff 全 false, + P0 标灰「待 IE 签字」({PARAMS_SIGNOFF_NOTE})。版本治理兑现断言⑩:试改取值才递增版本、旧版可回放、 + 跨版本对比默认拒绝;参数重算兑现断言②:切换触发重算,实际档实测不动。 + + + + + {/* 口径登记(demo 沙箱):版本/生效日/逐项签字状态,全部取自内置口径字典 */} + } + full + right={demo · 不落库} + note="登记口径版本、生效日与逐项签字状态,全部取自内置 CALIBER_CONFIG。本次不安排口径工作坊,signedOff 全 false,一律标「待 IE 签字」,不代签、不标绿。" + > +
+ 在用版本: + {CALIBER_CONFIG.version} + 生效日: + {CALIBER_CONFIG.effectiveFrom} +
+ + + }> + {realItems.map((c) => ( + + + + + + + + ))} +
编号口径项优先级归口状态
{c.id}{c.name}{c.priority}{c.owner}{c.signedOff ? '已签字' : '待 IE 签字'}
+
+ + {/* A. 口径字典与版本治理(断言⑩) */} + + + {/* B. 四轴配置:三层参数重算(断言②)+ 算法模板 + 间隙阈值(断言⑤)+ 优先级权重 A/B */} +
+ + 参数 · 模板 · 阈值 · 权重 + 四轴配置 + + + 业务日 {scope.bizDate} · 锚点单机重算 +
+ +
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/common/StageHint.tsx b/src/modules/tfamd-oee/components/common/StageHint.tsx new file mode 100644 index 0000000..9601351 --- /dev/null +++ b/src/modules/tfamd-oee/components/common/StageHint.tsx @@ -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 ( +
+
+ + 使用提示 · 演示动线 + + +
+
    + {steps.map((s, i) => ( +
  1. + {i + 1} + {s} +
  2. + ))} +
+
+ + 关闭后不再自动弹出 +
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/demand/CustomerList.tsx b/src/modules/tfamd-oee/components/demand/CustomerList.tsx new file mode 100644 index 0000000..6ec7783 --- /dev/null +++ b/src/modules/tfamd-oee/components/demand/CustomerList.tsx @@ -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 && ( +
+ + 关联订单 {filterSO} · 仅该单涉及的客户 + + +
+ )} + + {/* 汇总条 */} +
+ {list.length} 家客户 · {totalOrders} 笔订单 + ¥{money2(total)} +
+ + + {list.length === 0 && ( +
+ {filterSO ? '该销售订单暂无匹配客户' : '无匹配客户'} +
+ )} + {list.map(c => { + const nc = natureColor(c.性质, tokens); + return ( +
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:简称 + 编码 + 性质 */} +
+ + + {c.客户简称} + + {c.客户编码} + + {c.性质} +
+ {/* 行2:客户分类 + 所属类别 */} +
+ {c.客户分类} + {c.所属类别} +
+ {/* 行3:分管部门 + 序号 */} +
+ + {c.分管部门 || '分管部门未填'} + + + 序 {c.序号} +
+ {/* 行4:金额 + 笔数 */} +
+ ¥{money2(c.订单金额)} + + {c.订单笔数} 笔订单 +
+
+ ); + })} +
+ +
+ 笔数与金额为该客户在本批销售订单中的合计,与销售订单页签同源可核对 +
+ + ); +} diff --git a/src/modules/tfamd-oee/components/demand/SalesOrderList.tsx b/src/modules/tfamd-oee/components/demand/SalesOrderList.tsx new file mode 100644 index 0000000..740ecdd --- /dev/null +++ b/src/modules/tfamd-oee/components/demand/SalesOrderList.tsx @@ -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 ( + <> + {/* 汇总条 */} +
+ {list.length} 张订单 · {new Set(list.map(s => s.客户编码)).size} 家客户 + ¥{money(total)} +
+ + + {list.length === 0 && ( +
无匹配订单
+ )} + {list.map(s => { + const active = selectedSO === s.销售订单号; + const sc = statusColor(s.单据状态, tokens); + return ( +
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 && } + {/* 行1:单号 + 状态 */} +
+ + {s.销售订单号} + + + {s.单据状态} +
+ {/* 行2:客户 */} +
+ {s.客户简称} + {s.客户分类} +
+ {/* 行3:产品 + 数量 */} +
+ + {s.产品编码} + + {s.数量.toLocaleString()} PCS +
+ {/* 行4:金额 + 交期 */} +
+ ¥{money(s.含税金额)} + + 发货 {s.预计发货日期} +
+ {expanded && ( +
{s.仓库名称} · {s.制单人} · 下单 {s.单据日期}
+ )} +
+ ); + })} +
+ + ); +} diff --git a/src/modules/tfamd-oee/components/feature/FeatureTreeView.tsx b/src/modules/tfamd-oee/components/feature/FeatureTreeView.tsx new file mode 100644 index 0000000..c907ef5 --- /dev/null +++ b/src/modules/tfamd-oee/components/feature/FeatureTreeView.tsx @@ -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 = { + PE: '工艺', IE: '工业', QE: '质量', ME: '制造', +}; + +const ROLE_FULL: Record = { + 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(() => { + 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(() => { + const last = readLastSelection(); + return validSelection(last) ? last! : initialSelection; + }); + const [expanded, setExpanded] = useState>(() => { + const first = tree.models.find(m => m.id === KB_MODEL) ?? tree.models[0]; + const set = new Set(); + 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 ( +
+ {/* ── 标题栏 ── */} +
+ + 工艺建模 + + 快照日 {ONTOLOGY_AS_OF} · 机型 → 工艺 → 生产方法 + + +
+ {[ + { 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 => ( + {s.l} {s.v} + ))} +
+
+ + setQuery(e.target.value)} + placeholder="搜索机型 / 工艺 / 方法 / 问题" + style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', color: tokens.text, fontSize: 13.5 }} + /> + {query && ( + + )} +
+ +
+ + {/* ── 主区:左树 + 右详情 ── */} +
+ {/* 左侧树 */} +
+
+ + 特征树 + + 叶子=生产方法 +
+
+ {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 ( +
+ + {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 ( +
+ + {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 ( + + ); + })} +
+ ); + })} +
+ ); + })} +
+
+ + {/* 右侧详情 */} +
+ setSelected({ + modelId: method.modelId, processId: method.processId, methodId: method.id, + })} + /> +
+
+
+ ); +} + +/* ── 选中记忆(仅本舞台,刷新后保留) ─────────────────────────────────── */ +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 ( + + {n} + + ); +} + +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 ( +
+ 在左侧特征树选择一个节点 +
+ ); + } + + 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 ( +
+
+ {tag} + {title} + {subtitle && ( + + {subtitle} + + )} + + {kind === 'method' && ( + + )} +
+ +
+ {kind === 'method' + ? + : ( + <> + + + {kind === 'model' && ( +
+ 工艺 {(n as FeatureModel).processes.length} 个 +
+ {(n as FeatureModel).processes.map(p => ( + + ))} +
+
+ )} + + {kind === 'process' && ( +
+ 生产方法 {(n as FeatureProcess).methods.length} 个 +
+ {(n as FeatureProcess).methods.map(m => ( + + ))} +
+
+ )} + + + + )} +
+
+ ); +} + +function MethodStats({ method, tokens }: { method: FeatureMethod; tokens: ThemeTokens }) { + return ( +
+ 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} + 示例 {method.exampleCount} + 共 {method.summary.length} 行 +
+ ); +} + +/* ── 生产方法详情:问题 / 原因 / 对策 / 角色 总结表 ───────────────────── */ +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 && ( +
+ 示例 + + {hasReal + ? `有 ${method.exampleCount} 行是示例补齐(不是知识库原文),其余来自知识库切片。` + : `该生产方法暂无知识库切片,以下 ${method.exampleCount} 行按方法模板生成,仅用于演示结构,不作为知识事实。`} + +
+ )} + +
+
+ + + + + + + + + + + {['角色', '问题', '原因', '对策', '来源'].map((h, i) => ( + + ))} + + + + {method.summary.map((row, i) => ( + + ))} + +
{h}
+
+
+ + + + + + {method.refs.length > 0 && ( +
+ 关联数据 {method.refs.length} 项 +
+ {method.refs.map((r, i) => ( + + {r.objKey} + {r.instanceId ? ` · ${r.instanceId}` : ''} + + ))} +
+
+ )} + +
+ + +
+ + {siblings.length > 0 && ( +
+ 同工艺其他方法 {siblings.length} 个 +
+ {siblings.map(m => ( + + ))} +
+
+ )} + + ); +} + +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 ( +
+
+ 角色覆盖 + + {roles.filter(r => method.summary.some(x => x.role === r)).length} / 4 角色已挂载 + +
+
+ {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 ( +
+
+ {role} + {ROLE_FULL[role]} + {empty ? '未覆盖' : `${rows.length} 行`} +
+
+ {empty ? 无知识行 : <>真实 {real}示例 {example}} +
+
+ ); + })} +
+
+ ); +} + +/* 知识原文节选:表格是提炼行,这里保留可核对的原文 */ +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 ( +
+
+ 该生产方法还没有知识库切片 +
+
+ 上表 {method.exampleCount} 行全部是示例。补齐路径:① 在知识库上传该方法的 SOP / 检验标准; + ② 给切片标注「所属特征树」;③ 回到这里即可换成带来源的真实总结。 +
+
+ {checklist.map(([role, items]) => ( +
+ {role} + {items} +
+ ))} +
+
+ ); + } + return ( +
+
+ 知识原文节选 {rows.length} 条 + 点卡片回到知识库切片 +
+
+ {rows.map(row => { + if (row.source.kind !== 'kb') return null; + const text = chunkText(row.role, row.source.chunkId); + return ( + + ); + })} +
+
+ ); +} + +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 ( + + +
+ {row.role} + {ROLE_LABEL[row.role]} +
+ + {row.problem} + {row.cause} + {row.action} + + {isKb ? ( + + ) : ( + 示例 + )} + + + ); +} + +function ContextDetails({ title, attrs, tokens }: { title: string; attrs: { label: string; value: string }[]; tokens: ThemeTokens }) { + if (attrs.length === 0) return null; + return ( +
+ + {title} · {attrs.length} 项 + +
+ {attrs.map(a => ( +
+ {a.label} + {a.value} +
+ ))} +
+
+ ); +} + +function AttrGrid({ attrs, tokens, label }: { attrs: { label: string; value: string }[]; tokens: ThemeTokens; label: React.CSSProperties }) { + if (attrs.length === 0) return null; + return ( +
+ 属性 {attrs.length} 项 +
+ {attrs.map(a => ( +
+
{a.label}
+
{a.value}
+
+ ))} +
+
+ ); +} + +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 ( +
+ 知识挂载 {list.length} 条 +
+ {list.map((r, i) => ( + + ))} +
+
+ ); +} + +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}`, +}); diff --git a/src/modules/tfamd-oee/components/knowledge/KnowledgeView.tsx b/src/modules/tfamd-oee/components/knowledge/KnowledgeView.tsx new file mode 100644 index 0000000..f586e33 --- /dev/null +++ b/src/modules/tfamd-oee/components/knowledge/KnowledgeView.tsx @@ -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 = { + 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(null); + const [query, setQuery] = useState(''); + const [openChunk, setOpenChunk] = useState(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 ( +
+ {/* ── 标题栏 ── */} +
+ + 知识库 + 四语料 · 公开资料转录(synthetic) + +
+ {[ + { l: '资料', v: stats.docCount }, { l: '切片', v: stats.total }, + { l: '活跃', v: stats.active }, { l: '失效', v: stats.retired }, + { l: '口径', v: CALIBER_VERSION }, + ].map((s) => ( + {s.l} {s.v} + ))} +
+
+ + setQuery(e.target.value)} + placeholder="检索语料,如「未归因」「31317」" + style={{ flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', color: tokens.text, fontSize: 12 }} + /> + {query && ( + + )} +
+ +
+ + {/* ── 主区:左语料目录 + 右检索增强 ── */} +
+ {/* 左:语料目录 + 失效规则 + 迁移路径。grid 单列让 Card 撑满宽/高(flex 行里 Card 会按内容缩宽)。 */} +
+ } full + right={{CORPUS_ORDER.length} 类 · {KB_DOCS.length} 份资料}> +
+ { 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 ( + { setCorpus(k); setOpenChunk(null); }} + /> + ); + })} + +
+
+ + 失效规则(比切片粒度更重要) +
+ {[ + 'active=false 永不召回:旧版 SOP / 待复核案例 / 改钟标记。', + `口径语料锁定 ${CALIBER_VERSION},禁止跨版本混合检索。`, + '升版重新入库,旧切片停止召回;明细表仍标灰可审计。', + ].map((s) => ( +
+ ·{s} +
+ ))} +
+ + {KNOWLEDGE_NOTE} +
+
+
+ + {/* 右:检索增强 */} +
+ } full + right={ + + {corpusLabel} + 口径锁定 {CALIBER_VERSION} + top-{TOP_K} + + }> +
+ {!q && ( + <> + {/* 知识库输入资料:每类 3–4 份公开资料;点卡片按该资料的检索词召回切片,原文可外跳。 */} +
+ + + 知识库输入资料 · {corpus ? CORPUS_META[corpus].label : '全部语料'} + + + {docs.length} 份 · 公开来源 · 点卡片试检索 + +
+
+ {docs.map((d) => { + const col = tokens[CORPUS_META[d.corpus].color]; + return ( +
{ 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}`, + }} + > +
+ {d.corpus} + + {d.publisher} · {d.date} + +
+
{d.title}
+
{d.note}
+ +
+ ); + })} +
+
+
+ 输入关键词检索四语料,或点下方演示词。检索只召回 active=true 的切片;口径语料锁定 {CALIBER_VERSION}。 +
+ + {DEMO_QUERIES.map((d) => ( + + ))} + +
+ + )} + + {q && hits.length === 0 && retiredMatches.length === 0 && ( + 「{q}」无活跃切片命中。换个关键词,或点左侧演示词。 + )} + + {q && hits.length === 0 && retiredMatches.length > 0 && ( + + 活跃语料中无「{q}」命中:命中的切片均已失效并停止召回。
+ 下方明细表仍标灰留痕、可审计——这正是失效规则要防的「过期知识致幻」。 +
+ )} + + {hits.map((h, i) => { + const c = h.chunk; + const col = tokens[CORPUS_META[c.corpus].color]; + return ( +
+
+ #{i + 1} + {c.title} + {c.corpus} + {SIM_BADGE} + + 余弦 {h.score.toFixed(3)} +
+
+
+
+
{c.text}
+
+ 来源:{c.source} +
+
+ ); + })} + + {/* 停止召回实证:命中关键词却被失效规则排除的切片 */} + {q && retiredMatches.length > 0 && ( +
+
+ + + 另有 {retiredMatches.length} 条失效切片命中「{q}」,但已停止召回(active=false) + +
+
+ {retiredMatches.map((c) => ( + {c.id} + ))} +
+
+ 这些切片不进检索结果(防过期知识致幻),但下方明细表仍标灰留痕、可审计。 +
+
+ )} +
+ + 余弦分由注入语料池现算(字符级 TF-IDF),非真实嵌入模型;retrieve() 签名不变,生产内部换 Milvus,语料切片与失效规则完全复用。 + + +
+
+ + {/* ── 底部:语料切片明细表(含失效切片,标灰可审计) ── */} +
+ } full + right={ + + {tableRows.length} 条 · 失效标灰 · 点行展开 + + }> +
+ + + + + + + + {tableRows.map((c, i) => { + const open = openChunk === c.id; + const col = tokens[CORPUS_META[c.corpus].color]; + const retired = !c.active; + return ( + + setOpenChunk(open ? null : c.id)} + style={{ + cursor: 'pointer', + background: open ? tokens.accentBg : retired ? tokens.panelBgAlt : 'transparent', + opacity: retired ? 0.78 : 1, + }} + > + + + + + + + + {open && ( + + + + )} + + ); + })} + {tableRows.length === 0 && ( + + )} + +
#切片 id标题语料状态来源 / 失效原因
{i + 1}{c.id}{c.title}{c.corpus} + + {retired + ? 失效 + : 活跃} + {SIM_BADGE} + + + {c.source}{retired && c.retiredReason ? ` — ${c.retiredReason}` : ''} +
+
+ 原文切片 · {c.id}{retired ? ' · 已停止召回' : ''} +
+
{c.text}
+
无匹配切片
+
+ + 明细表含失效切片(标灰 + 失效原因),与检索侧「只召回活跃」形成对照:知识可审计、召回防过期。 + {q ? ` 当前关键词「${q}」命中 ${tableRows.length} 条(含失效)。` : ''} + +
+
+
+ ); +} + +/* ── 语料目录按钮:色条 + 名称 + 描述 + 切片/活跃/失效计数 ─────────────── */ +function CorpusButton({ tokens, on, color, label, desc, total, active, retired, onClick }: { + tokens: ReturnType['tokens']; on: boolean; color: string; + label: string; desc: string; total: number; active: number; retired: number; onClick: () => void; +}) { + return ( + + ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/layout/AutoScroll.tsx b/src/modules/tfamd-oee/components/layout/AutoScroll.tsx new file mode 100644 index 0000000..0a5b22c --- /dev/null +++ b/src/modules/tfamd-oee/components/layout/AutoScroll.tsx @@ -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 ( + + ); +} + +/** + * 面板内带自动滚动的列表容器:样式同 PanelBody,差别是它挂了滚动循环。 + * 开关默认跟随所在面板的 AutoScrollProvider,也可以显式传 autoScroll 覆盖。 + */ +export function ScrollList({ children, autoScroll }: { children: ReactNode; autoScroll?: boolean }) { + const ctx = useAutoScrollEnabled(); + const enabled = autoScroll ?? ctx; + const ref = useRef(null); + useAutoScroll(ref, enabled); + return ( +
+ {children} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/layout/LeftNav.tsx b/src/modules/tfamd-oee/components/layout/LeftNav.tsx new file mode 100644 index 0000000..05ad61a --- /dev/null +++ b/src/modules/tfamd-oee/components/layout/LeftNav.tsx @@ -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 = { + 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 => ( + + ); + + const heading = (title: string, first = false) => ( + <> + {!first &&
} +
+ + {title} +
+ + ); + + return ( + + ); +} diff --git a/src/modules/tfamd-oee/components/layout/PanelShell.tsx b/src/modules/tfamd-oee/components/layout/PanelShell.tsx new file mode 100644 index 0000000..ec87d6a --- /dev/null +++ b/src/modules/tfamd-oee/components/layout/PanelShell.tsx @@ -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 ( +
+ + + + + + + + + + + + + + + {/* 内容层压在弧板之上,宽度不超过直边区域 */} +
+
+ + {icon && {icon}} + {title} + {badge} + + {extra} + +
+ + {tabs && ( +
{tabs}
+ )} + + {hint && ( +
+ {hint} +
+ )} + +
+ {children} +
+
+
+ ); +} + +/** 面板内统一的滚动容器;ref 外放,供调用方实现自动滚动等滚动控制 */ +export const PanelBody = forwardRef( + function PanelBody({ children, pad = '0 0 10px 0' }, ref) { + return ( +
+ {children} +
+ ); + }, +); + +/** 标题栏数量徽标 */ +export function CountBadge({ n, color }: { n: number | string; color?: string }) { + const { tokens } = useTheme(); + return ( + {n} + ); +} diff --git a/src/modules/tfamd-oee/components/network/CausalPanel.tsx b/src/modules/tfamd-oee/components/network/CausalPanel.tsx new file mode 100644 index 0000000..dbefc6c --- /dev/null +++ b/src/modules/tfamd-oee/components/network/CausalPanel.tsx @@ -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; + 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([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 ( +
+ 点击图谱中的任意节点,这里将展开它的前因、后果与下级回应。 +
+ ); + } + + 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) => ( +
+ + {label} + {n !== undefined && {n}} + +
+ ); + + 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 ( + + ); + }; + + /* 下级回应条:子指标在该期的达成率,一眼看出谁在拖、谁在扛 */ + const kidRow = (k: MetricNode) => { + const ka = achieveAt(k, period); + const kc = alertColor(levelAt(k, period), tk); + const kg = gapAt(k, period); + return ( + + ); + }; + + /* 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 ( +
+ {series.map((v, i) => { + const h = 6 + ((v - mn) / span) * (H - 12); + const on = i === period; + const col = alertColor(levelAt(node, i), tk); + return ( +
+ ); + })} +
+
+ ); + }; + + const guards = staff.filter(s => s.bound_metric === node.code); + + return ( +
+ {/* 实体抬头 */} +
+ + {name} + {node.code} + {onClose && ( + + )} +
+
+ L{node.level}·{node.owner}· + {node.frequency}· + {node.parent_code && node.parent_code !== 'OV' ? `上级 ${nameOf(node.parent_code)}` : 'OV'} +
+ + {/* 看板现已贯通到底(整屏高),纵向叙事优先填满高度;只有超宽屏才自动分双列 */} +
+ + {/* 游标读数 */} +
+ {secTitle(`${t.net.causalCursor} · ${periodLabel(period)}`)} +
+ {([ + [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]) => ( +
+
{lab}
+
{v}
+
+ ))} +
+
+ + {/* 趋势柱 */} +
+ {secTitle(t.net.causalTrend)} + {trendBars()} +
+ {periodLabel(0)}虚线=目标{periodLabel(11)} +
+
+ + {/* 前因 */} +
+ {secTitle(t.net.causalIn, incoming.length)} + {incoming.length + ?
{incoming.map(l => linkRow(l, false))}
+ :
{isRoot ? t.net.noConn : t.net.causalNoIn}
} +
+ + {/* 后果 */} +
+ {secTitle(isRoot ? t.net.topChains : t.net.causalOut, outgoing.length)} + {outgoing.length + ?
{outgoing.map(l => linkRow(l, true))}
+ :
{t.net.causalNoOut}
} +
+ + {/* 下级回应 */} +
+ {secTitle(t.net.causalKids, kids.length)} + {kids.length + ?
{[...kidGaps].map(x => kidRow(x.k))}
+ :
{t.net.causalNoKid}
} +
+ + {/* 同层对标(仅末级:没有下级可拆时,用兄弟指标补齐这块高度) */} + {!kids.length && sibs.length > 0 && ( +
+ {secTitle(t.net.causalSibs, sibs.length)} +
+ {[...sibs].sort((a, b) => gapAt(a, period) - gapAt(b, period)).slice(0, 6).map(k => kidRow(k))} +
+
+ )} + + {/* AI 研判:整行占位,长句不拆栏 */} +
+ {secTitle(t.net.causalAi)} +
+ {verdicts.map(v => ( +
{v.text}
+ ))} +
+
+ + {/* 汇报口径 */} +
+ {secTitle(t.net.causalReport)} +
+
{t.common.formula}
+
{node.formula}
+
{t.detail.desc}
+
{(node.desc_zh) || t.detail.noDesc}
+
+
+ {guards.length ? guards.map(s => ( +
+ + {s.name_zh} + {s.cur_zh} +
+ )) :
{t.net.causalNoStaff}
} +
+
+
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/network/DeepSpaceBackdrop.tsx b/src/modules/tfamd-oee/components/network/DeepSpaceBackdrop.tsx new file mode 100644 index 0000000..d11634c --- /dev/null +++ b/src/modules/tfamd-oee/components/network/DeepSpaceBackdrop.tsx @@ -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 ( +
+ {/* 星云光斑:双色呼吸漂移 */} +
+
+ + {/* 中心恒星辉光 + 雷达扫描(两者只在深空模式出现) */} + {deep && ( + <> +
+ {radar && ( +
+
+
+ )} + {/* 星点闪烁 */} + {stars.map((s, i) => ( + + ))} + + )} + + {/* 边缘暗角:收束视线,制造纵深 */} + {deep && ( +
+ )} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/network/MetricTimeline.tsx b/src/modules/tfamd-oee/components/network/MetricTimeline.tsx new file mode 100644 index 0000000..d26b28c --- /dev/null +++ b/src/modules/tfamd-oee/components/network/MetricTimeline.tsx @@ -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(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 ( +
+ {/* 回放控制 */} + + + {/* 轨道:12 根健康度柱 + 游标 */} +
{ + 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; }} + > + {/* 柱阵列 */} +
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 ( +
+
+
+ ); + })} +
+ {/* 游标发光线 */} +
+ +
+ {/* 日刻度 */} +
+ {shownTicks.map((i) => ( + {periodShortLabel(i)} + ))} +
+
+ + {/* 当前期读数 */} +
+ + + {cur} + + + +
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/network/deepTheme.ts b/src/modules/tfamd-oee/components/network/deepTheme.ts new file mode 100644 index 0000000..480335e --- /dev/null +++ b/src/modules/tfamd-oee/components/network/deepTheme.ts @@ -0,0 +1,21 @@ +import type { ThemeTokens } from '../../context/ThemeContext'; + +/** 舞台态强制深空(Bloomberg 黑屏模式):图谱与看板共用同一套语义色,不随用户主题漂移 */ +export const DEEP: Partial = { + 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)}`; +} diff --git a/src/modules/tfamd-oee/components/ontology/OntologyGraph.tsx b/src/modules/tfamd-oee/components/ontology/OntologyGraph.tsx new file mode 100644 index 0000000..561ae6d --- /dev/null +++ b/src/modules/tfamd-oee/components/ontology/OntologyGraph.tsx @@ -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(null); + const [nodes, setNodes] = useState([]); + const [dims, setDims] = useState({ w: 720, h: 420 }); + const [hovered, setHovered] = useState(null); + /* 药签入场:不用 CSS animation(fill-mode:both 会把 0% 关键帧钉死, + 动画被挂起时终态就永远停在 opacity:0 / scale(0.2),无头截图里药签整个消失)。 + 改成 JS 定时器翻状态 + 内层 的 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 = {}; + 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 = ( + + + + + + + + + + + + + + + + + + ); + + /* ── 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 ( + + {svgDefs} + + + {/* 中心锚到每个药签的辐条:explode=属于,instance=字段 */} + {pts.map(([x, y], i) => { + const dx = x - cx, dy = y - cy; + const d = Math.hypot(dx, dy) || 1; + return ( + + ); + })} + + {/* 中心锚:外圈呼吸环 + 品牌色圆 */} + + + + + {center.label} + {mode === 'instance' + ? {center.sub ?? ''} + : {center.count ?? 0} 条实例} + {center.badge && ( + + + {center.badge} + + )} + + + {/* 环上药签:炸开时有 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 ( + onSatelliteClick?.(st.id)}> + {/* 位置在外层 (transform 属性,与动画无关);缩放在内层 (transition,终态恒为 1) */} + + {text} + + {shown} + {st.badge && ( + + + + {st.badge.slice(0, 2)} + + + )} + + + ); + })} + + ); + } + + return ( + + {svgDefs} + + + + {/* ── 关系边:透明粗线负责命中,细线负责显示 ── */} + {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 ( + onEdgeClick?.(e.id)}> + + + {showLabel && ( + <> + + {label} + + )} + + ); + })} + + {/* ── 对象节点 ── */} + {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 ( + setHovered(n.id)} onMouseLeave={() => setHovered(null)} + onClick={() => onNodeClick?.(n.id)} onDoubleClick={() => onNodeDoubleClick?.(n.id)}> + {sel && ( + + )} + + + {/* 对象自身的品牌色压在底部,区分「销售订单 / 工单 / 采购单」 */} + + 30 ? 12 : 11} fontWeight={700} + fill={sel || hl ? ring : tokens.text}>{shortName(n.label)} + {n.count} + {!dense && ( + + {shortName(n.label)} · {n.count} 实例 + + )} + + ); + })} + + ); +} diff --git a/src/modules/tfamd-oee/components/ontology/OntologyView.tsx b/src/modules/tfamd-oee/components/ontology/OntologyView.tsx new file mode 100644 index 0000000..5c36fe0 --- /dev/null +++ b/src/modules/tfamd-oee/components/ontology/OntologyView.tsx @@ -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 = { + 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 ( + {children} + ); +}; + +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 = { + all: null, + feature: ['equipment', 'event', 'stateSegment', 'loss'], +}; + +export default function OntologyView({ onExit, scope = 'all', focus }: Props) { + const { tokens } = useTheme(); + /* 初值取对象清单首项,不写死 id:换本体种子时不会指向一个不存在的对象 */ + const [sel, setSel] = useState({ kind: 'object', id: objects[0].id }); + const [query, setQuery] = useState(''); + const [view, setView] = useState({ 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>({}); + 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( + () => (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) => ( +
+ {icon} + {label} + + + {n}/{total} + +
+ ); + + 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 ( +
+ {/* ── 标题栏:窄窗口时换行而不是把退出按钮挤出可视区(容器 overflow:hidden 会裁掉溢出) ── */} +
+ {scope === 'feature' + ? + : } + + {scope === 'feature' ? '工艺建模' : '业务本体'} + + + 快照日 {ONTOLOGY_AS_OF} · {scope === 'feature' ? '特征对象' : '对象即业务实体'} {scObjects.length} 类对象 + + +
+ {[ + { 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 => ( + {s.l} {s.v} + ))} +
+
+ + setQuery(e.target.value)} + placeholder="搜索对象 / 关系 / 规则 / 动作" + style={{ + flex: 1, minWidth: 0, background: 'transparent', border: 'none', outline: 'none', + color: tokens.text, fontSize: 12, + }} + /> + {query && ( + + )} +
+ +
+ + {/* ── SCHEMA 徽标行:一眼看清每类对象有多少实例 ── */} +
+ {scObjects.map(o => { + const on = sel.kind === 'object' && sel.id === o.id; + const n = o.instances().length; + return ( + + ); + })} +
+ + {/* ── 上:图谱 + 详情面板 ── */} +
+
+
+ + {view.mode === 'graph' ? ( + <> + {scope === 'feature' ? '特征图谱' : '本体图谱'} + 节点={scope === 'feature' ? '特征对象' : '对象'}(圈内数字为实例数)· 连线=关系 + + ) : ( + + + + + {view.mode === 'instance' && ( + <> + + + + )} + + )} + + {/* 现场讲解用的动词提示:观众不用听说也知道下一步点哪 */} + + {view.mode === 'graph' ? '单击聚焦 · 双击展开实例' : view.mode === 'explode' ? '点实例标签看字段 · 空白/ESC 返回' : '空白/ESC 返回上一层'} + +
+
+ + 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} + /> +
+
+ + {/* 详情面板:放宽占比与上限,属性标签与实例行不再被挤成两三行 */} +
+ setSel({ kind: 'object', id })} + onBack={back} + /> +
+
+ + {/* ── 下:对象 / 关系 / 规则 / 动作 四栏清单 ── */} +
+
+ {colHead(scope === 'feature' ? : , + scope === 'feature' ? '特征对象 Feature' : '对象 Object', visObjects.length, scObjects.length)} +
+ {visObjects.map(o => { + const on = sel.kind === 'object' && sel.id === o.id; + const focus = isFocusTable(o.id); + return ( + + ); + })} + {visObjects.length === 0 && } +
+
+ +
+ {colHead(, '关系 Relation', visRelations.length, scRelations.length)} +
+ {visRelations.map(r => { + const on = sel.kind === 'relation' && sel.id === r.id; + const focus = relLinked(r); + return ( + + ); + })} + {visRelations.length === 0 && } +
+
+ +
+ {colHead(, '规则 Rule', visRules.length, scRules.length)} +
+ {visRules.map(r => { + const on = sel.kind === 'rule' && sel.id === r.id; + const h = r.hits(); + const focus = linkedTo(r.tables); + return ( + + ); + })} + {visRules.length === 0 && } +
+
+ +
+ {colHead(, '动作 Action', visActions.length, scActions.length)} +
+ {visActions.map(a => { + const on = sel.kind === 'action' && sel.id === a.id; + const n = a.targets?.().length ?? 0; + const focus = linkedTo(a.tables); + return ( + + ); + })} + {visActions.length === 0 && } +
+
+
+ + {/* ── 页脚:范围与缺口常驻披露(不藏 tooltip)── + 主数据全量 vs 事实层只取锚点三日,三处未落地一律 blocked+gap 标灰、不造实例充数。 + 文案从 ontologyOee 的 ONTOLOGY_SCOPE_NOTE 取,数字现算,页面不另写一份。 */} +
+ {ONTOLOGY_SCOPE_NOTE} + + 数据源:src/data/ontologyOee.ts + (数值唯一来源为 L3 lib/oeeService)· 校验: + scripts/verify-oee-ontology.ts + +
+
+ ); +} + +const Empty = ({ tk }: { tk: ThemeTokens }) => ( +
无匹配条目
+); + +/* ── 右侧详情面板 ─────────────────────────────────────────────────────── */ + +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) => ( +
+
+ {tag} + {title} + + {tone && {tone === 'danger' ? '硬约束' : tone === 'warning' ? '预警' : '提示'}} +
+ {en &&
{en}
} +
+ ); + + 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, '实例')} +
+ + {inst.sub && ( +
+ 概要 + {inst.sub} +
+ )} + {inst.meta && ( +
+ 上下文 + {inst.meta} +
+ )} +
+ 字段 {fields.length} 项(列名 = 值) +
+ {fields.map(f => ( +
+ {f.name} + {f.value} +
+ ))} +
+
+
+ + ); + } + + if (!detail) { + return ( +
+ 在图谱或下方清单里选择一个条目 +
+ ); + } + + /* ── 对象:属性定义 + 实例下钻 ── */ + if (sel.kind === 'object') { + const o = detail as OntObject; + return ( + <> + {head(o.name, `${o.en} · ${instances.length} 实例`, null, '对象')} +
+
+ 业务含义 + {o.desc} +
+
+ 数据来源 + {o.source} +
+
+ 属性 {o.attrs.length} 项 +
+ {o.attrs.map(a => ( + + {a.en}{a.required ? '' : '?'} + + ))} +
+ 虚线=该列在本批数据里可空;悬停看中文列名与口径说明 +
+
+ 实例下钻 + {instances.length} 条 +
+ {instances.map((it, i) => ( + + ))} +
+ + ); + } + + /* ── 关系:两端 + 基数 + 连接键 ── */ + 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, '关系')} +
+
+ {[from, to].map((o, i) => ( +
+ + {i === 0 && ( + {r.cardinality} + )} +
+ ))} +
+
+ 连接键 + {r.key} +
+
+ 当前实例数 + {r.count()} +
+
+ 口径说明 + {r.desc} +
+
+ + ); + } + + /* ── 规则:表达式 + 实时命中 + 命中订单 ── */ + 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 ? '规则' : '动作', + )} +
+ {isRule ? ( + <> +
+ 判定表达式 + + {rule.expr} + +
+
+ 约束强度 + + {rule.severity === 'error' ? '硬约束:违反即质量风险外溢,必须处置' : rule.severity === 'warning' ? '预警:需要责任角色确认后处置' : '提示:结构性风险画像'} + +
+ + ) : ( + <> +
+ 触发条件 + {action.trigger} +
+
+ 作用对象 / 类型 + {action.object} · {ACTION_TYPE[action.type].label} +
+ + )} +
+ 说明 + {isRule ? rule.desc : action.desc} +
+
+ + {isRule && rule.blocked ? '—' : targets.n} + + + {isRule && rule.blocked ? '数据缺口,规则无法执行' : targets.unit} + + + {isRule && !rule.blocked && targets.n === 0 && 本批无违反} +
+ {isRule && rule.blocked && ( +
+ + {rule.gap} +
+ )} + {list.length > 0 && ( + <> +
命中清单 {list.length} 项
+ {list.map((code, i) => ( +
+ + + {code} + +
+ ))} + + )} +
+ + ); +} + +/** 实例行:一行数据表记录,左=主键与口径,右=该行最该看的那个值 */ +function InstanceRow({ it }: { it: OntInstance }) { + const { tokens } = useTheme(); + const tone = toneColor(tokens, it.tone ?? 'info'); + return ( +
+ +
+
+ {it.title} + {it.badge && {it.badge}} +
+
{it.sub}
+
+
+ {it.value && ( +
{it.value}
+ )} +
{it.meta}
+
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/process/ProcessFlowPanel.tsx b/src/modules/tfamd-oee/components/process/ProcessFlowPanel.tsx new file mode 100644 index 0000000..fbd057f --- /dev/null +++ b/src/modules/tfamd-oee/components/process/ProcessFlowPanel.tsx @@ -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; + selected: string; + onSelect: (code: string) => void; + period: number; +} + +const ICONS: Record = { + 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) => ( +
+
{label}
+
{value}
+ {sub &&
{sub}
} +
+ ); + + /** 过程量小格:标签 + 值 + 目标/环比提示 */ + const stat = (label: string, value: string, tone: string) => ( +
+ {label} + {value} +
+ ); + + return ( + + {/* 口径提示:过程 vs 结果 */} +
+ {t.flow.hint} +
+ + {/* 全链汇总 */} +
+ {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)} +
+
+ + {t.flow.bottleneck} + + {STAGES[bottleneck].zh} + + + + {fmt(stats[bottleneck].score)}% + +
+ + {/* 六段流程 */} + {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 ( +
+ {/* 段间连线:在制品沿链流动 */} + {i > 0 && ( +
+
+ + + + + + + {t.flow.wip} {stats[i - 1].wip.toLocaleString()} + +
+
+
+ )} + +
+ {/* 轨道节点 */} +
+ + + +
+ + {/* 段卡 */} +
+
+ + + {s.zh} + + {fmt(st.score)}% +
+
+ {s.roleZh} · {trend} +
+ + {/* 段达成条 */} +
+ +
+ + {/* 过程四量 */} +
+ {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)} +
+ + {/* 关联指标片:真实 metric_node,点开联动中央看板 */} +
+ {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 ( + + ); + })} +
+
+
+
+ ); + })} + +
+ {periodLabel(period)} · {t.flow.wipTip} +
+ + ); +} diff --git a/src/modules/tfamd-oee/components/qap/QapDataView.tsx b/src/modules/tfamd-oee/components/qap/QapDataView.tsx new file mode 100644 index 0000000..5f7fd0f --- /dev/null +++ b/src/modules/tfamd-oee/components/qap/QapDataView.tsx @@ -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) => ( +
+
{label}
+
{value}
+
+); + +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(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) => ( +
+
+ {title} + + {right} +
+
+ {children} +
+
+ ); + + return ( +
+ {/* 标题栏 */} +
+ + 数据集总览 + demo 沙箱 · 数据来自内置合成种子,不连接后端 + +
+ {REGIONS.map(r => { + const on = region === r; + return ( + + ); + })} +
+ +
+ + {/* 指标磁贴 */} +
+ {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)} +
+ +
+ {/* 业务日种子 */} + {panel('业务日种子', `${days.length} 个业务日`, ( + + + + + + + + + + {days.map((d) => ( + + + + + + + + ))} + +
业务日设备口径版本日志行事件数
{d.bizDate}{d.device.id}{d.caliberVersion}{fmtNum(d.seed.lines.length)}{fmtNum(d.normalize.events.length)}
+ ))} + + {/* 台账设备 */} + {panel('台账设备', `${devices.length} 台`, ( + + + + + + + + + + {devices.map((d) => ( + + + + + + + + ))} + +
设备名称区域线体 · 工站计 OEE
{d.id}{d.name}{d.region}{d.lineId} · {d.station}{d.countsForOee ? '是' : '否(中间缓存)'}
+ ))} + + {/* SQLite 指标表 */} + {panel('浏览器内 SQLite 指标表', `${SQLITE_TABLES.length} 张`, ( + + + + + + + + + {SQLITE_TABLES.map((t) => ( + + + + + + + ))} + +
表名称内容用途
{t.table}{t.name}{t.detail}{t.use}
+ ))} +
+ +
+ 只读静态展示 · demo 沙箱数据全部来自内置合成种子,不连接后端 · SQLite 指标表在浏览器内存中初始化 +
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/quality/QualityFlowPanel.tsx b/src/modules/tfamd-oee/components/quality/QualityFlowPanel.tsx new file mode 100644 index 0000000..cb525cd --- /dev/null +++ b/src/modules/tfamd-oee/components/quality/QualityFlowPanel.tsx @@ -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 = { + 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(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) => ( +
+ {label} + {value} +
+ ); + + return ( + + {/* 口径提示:过程 vs 结果 */} +
+ {t.qflow.hint} +
+ + {/* 瓶颈横幅:达成率最低的一段,和约束段一起说清楚 */} +
+ + {t.qflow.bottleneck} + + {ROLES[bottleneck].key} · {ROLES[bottleneck].zh} + + + + {fmt(stats[bottleneck].score)}% + +
+ + {/* 四段角色流程 */} + {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 ( +
+ {/* 段间连线:单据沿链流转,线上标上一段积压 */} + {from && ( + /* 段间箭头放在整栏水平中央,不再贴着左缘的轨道图标; + 标签跟在箭头右侧,居中留白左右对称 */ +
+ + {/* 上端探出 2px 贴住上一张卡的下沿,箭头正好落在下一张卡的上沿 */} + + + + + + {from.r.key}→{r.key} · {t.flow.wip} {stats[from.i].wip} + +
+ )} + +
+ {/* 轨道节点 */} +
+ + + +
+ + {/* 角色卡 */} +
+ {/* 角色行:编码 + 名称 + 达成率 */} +
+ + {r.key} + {r.zh} + {fmt(st.score)}% +
+ +
+ {r.duty} · {trend} +
+ + {/* 段达成条 */} +
+ +
+ + {/* 过程四量 */} +
+ {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)} +
+ + {/* 流转三行:输入 → 输出 → 后续动作。收起态宽度不够,只在展开态显示 */} + {expanded && ( +
+
+ {t.qflow.input} + {r.input} +
+
+ {t.qflow.output} + {r.output} +
+
+ + {t.qflow.next} + {r.next} +
+
+ )} + + {/* 本段质量 KPI:4 项/角色,点开看职责表现状原文 */} +
+ {t.qflow.kpiGroup} + + {/* 现状原文要两行才放得下,收起态宽度不够,只在展开态给这个入口 */} + {expanded && ( + + )} +
+ +
+ {st.kpis.map(k => { + const kc = alertColor(k.status, tokens); + return ( +
+
{k.zh}
+
+ {fmt(k.value, k.decimals)}{k.unit} + + /{k.target} + + + {k.achieve}% +
+ {/* 现状原文:只在展开态且点了「详情」时铺出来,避免左栏变成文档堆 */} + {isOpen && expanded && ( +
+ {/* 比率类指标的差值用百分点表述,写成「+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} +
{k.now} +
+ )} +
+ ); + })} +
+
+
+
+ ); + })} + + {/* 数据来源口径:明确标注这是模拟读数,以及换成真实数据要接哪几张表 */} +
+ {periodLabel(period)} · {t.flow.wipTip} +
{t.qflow.dataSource} +
{t.qflow.kpiTip} +
+
+ ); +} diff --git a/src/modules/tfamd-oee/components/quality/QualityFlowStrip.tsx b/src/modules/tfamd-oee/components/quality/QualityFlowStrip.tsx new file mode 100644 index 0000000..4906fc4 --- /dev/null +++ b/src/modules/tfamd-oee/components/quality/QualityFlowStrip.tsx @@ -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 = { 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(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) => ( +
+
{label}
+
{value}
+
+ ); + + return ( +
+
+ {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 ( + + {i > 0 && ( +
+ + + + + + + {stats[i - 1].wip} + +
+ )} + +
+ ); + })} +
+ + {openIdx >= 0 && (() => { + const r = ROLES[openIdx]; + const st = stats[openIdx]; + const c = alertColor(st.status, tokens); + return ( +
+
+
{r.key} · {r.zh}
+
{t.qflow.input} {r.input}
+
{t.qflow.output} {r.output}
+
+ + {t.qflow.next} {r.next} +
+
+
+ {st.kpis.map(k => { + const kc = alertColor(k.status, tokens); + return ( +
+
{k.zh}
+
+ + {fmt(k.value, k.decimals)}{k.unit} + + /{k.target} + + {k.achieve}% +
+
+ {t.qflow.situation}:{k.base}{k.unit} · {t.qflow.vsBase} {k.vsBase > 0 ? '+' : ''}{fmt(k.vsBase, k.decimals)}{k.unit === '%' ? 'pt' : k.unit} +
{k.now} +
+
+ ); + })} +
+
+ ); + })()} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/stepchain/ChainBoard.tsx b/src/modules/tfamd-oee/components/stepchain/ChainBoard.tsx new file mode 100644 index 0000000..3a57dbe --- /dev/null +++ b/src/modules/tfamd-oee/components/stepchain/ChainBoard.tsx @@ -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 = { + 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 = { TASK: '任务', GATE: '质量门', DERIVED: '派生' }; +/** 七态色调(走主题令牌键,与闭环六态色调表各自独立)。 */ +const STATE_TONE: Record = { + 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(cloneSeed); + const [selectedId, setSelectedId] = useState('n6_qc_verify'); + const [clock, setClock] = useState(() => 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 + 质量门状态 ── */} + } + full + right={ + + + {gate ? '质量门已通过' : '质量门未通过'} + + + {close.ok ? '整链可关闭' : '整链不可关闭'} + + + + } + note={CHAIN_SEED_NOTE + ' 点击节点查看详情与流转;七态=已创建→已接单→执行中→已提交→已核准→已关闭(已提交可驳回返工)。'} + > + {/* 一行等分 7 节点(看板红线:flex:1 + 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 ( +
+
{ 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', + }} + > +
+ + {KIND_LABEL[n.kind]} + {blocked && } + {st?.escalated && } +
+
+ {NODE_LABEL[n.id] ?? n.id} +
+
+ {n.role} · {n.slaMin !== undefined ? `${n.slaMin}min` : '无 SLA'} +
+
{CHAIN_STATE_LABEL[st?.state ?? 'CREATED']}
+
+ {i < SRF_CHAIN.length - 1 && ( + + )} +
+ ); + })} +
+ + {/* 质量门阻挡披露:把「不可跳过」写在脸上 */} + {!gate && ( +
+ +
+ )} + {gate && close.ok && ( + 质量门已核准、全部节点通过 → 整链可关闭。这是「QA 核准 → 解锁 n7 → 推进至关闭」的完整闭环演示。 + )} +
+ + {/* ── 节点详情 + T6 派生/SLA ── */} +
+ } + right={{CHAIN_STATE_LABEL[selected?.state ?? 'CREATED']}} + note="判据原文照录建议书 §4.9.1;当前处理人为演示角色(不编造真实姓名)。流转由引擎 chainTransition 校验合法性,历史全程留痕可重放。" + > + }> + + + + + + + + +
字段值
节点编码{selectedDef.id}
种类 / 角色{KIND_LABEL[selectedDef.kind]} {selectedDef.role}
判据原文{selectedDef.criterion}
触发器{selectedDef.trigger}
节点 SLA{selectedDef.slaMin !== undefined ? `${selectedDef.slaMin} min` : '—(无 SLA)'}
升级对象{escalationFor(selectedDef)}
当前处理人{selected?.owner ?? '—'}
开始时刻{selected?.startedAt ? timeOf(selected.startedAt) : '—(未开始)'}
+ + {/* 流转动作 */} +
+ {nextChainStates(selected?.state ?? 'CREATED').map((s) => { + const isGateApprove = selectedDef.kind === 'GATE' && s === 'APPROVED'; + const disabled = (selected?.state === 'CREATED') && !selActivatable.ok; + return ( + + ); + })} + {nextChainStates(selected?.state ?? 'CREATED').length === 0 && 终态·无后继} + {selected?.state === 'CREATED' && !selActivatable.ok && 受质量门阻挡} +
+ {msg && ( +
{msg.text}
+ )} + + {/* 历史时间线 */} +
+ 流转留痕(at/by 注入,可重放): +
+ {(selected?.history ?? []).map((h, i, arr) => ( +
+
+ + {i < arr.length - 1 && } +
+
+
+ {CHAIN_STATE_LABEL[h.state]} + {timeOf(h.at)} + {h.by} +
+ {h.note &&
{h.note}
} +
+
+ ))} +
+
+
+ + } + right={演示时钟 {clockOf(clock)}} + note="n7 时刻由 Xray 锚点经 T6 反推(纯算术,不手填);SLA 截止=开始时刻+slaMin,超时升级到节点 escalateTo。无 SLA / 无起点不判超时(不猜)。" + > + {/* T6 派生 */} +
+ + + T6 不变量:n7=n4−10min({derived ? `${dur(derived.n4StartEpoch - derived.n7EndEpoch)}` : '—'})。 + 现算校验 reverseDeriveN7(n4)=n7: + + {derived && reverseDeriveN7(derived.n4StartEpoch) === derived.n7EndEpoch ? ' 成立' : ' 锚点缺失/不成立'} + 。锚点缺失则不派生、不猜一个时间塞进去。 + +
+ + {/* 选中节点 SLA */} + }> + + + + + + + + + + + +
SLA 项值
选中节点{selectedDef.id}
SLA 上限{selectedDef.slaMin !== undefined ? `${selectedDef.slaMin} min` : '—(无 SLA)'}
SLA 截止{selDeadline !== undefined ? clockOf(selDeadline) : '—(无起点/无 SLA)'}
是否超时{selDeadline === undefined + ? 不判超时 + : selBreached ? 已超时 : 未超时} +
升级状态{selected?.escalated + ? 已升级 → {selected.escalatedTo} + : 未升级} +
+ + 本链曾超时升级 {escalatedCount} 个节点(n4_setup_mfg_start 超 20min SLA → 升级 MFG 主管后完成,留痕)。 + 节点级 SLA(n1–n4)与录入台表单级 SLA(下表)是两套,不混用。 + +
+
+ + {/* ── 六触发器 + 表单级 SLA ── */} +
+ } + right={实现 {CHAIN_TRIGGERS.filter((t) => t.implemented).length}/{CHAIN_TRIGGERS.length}} + note="触发器归属按判据语义判定(§4.9.2)。T5 计划对齐 implemented=false:契约占位,不假装已接排产系统。T4 手动触发在事务内(提交即流转、可回滚)。" + > + }> + {CHAIN_TRIGGERS.map((t) => ( + + + + + + + ))} +
编号类型实现说明
{t.id}{t.kind}{t.implemented + ? 已实现 + : 契约占位} + {t.note}
+
+ + } + right={{FORM_SLA_ESCALATION.length} 张归因/登记单} + note="区别于节点级 SLA:这是录入台四张归因/登记单的表单级 SLA(§4.9.3 原文)。Jam 归因无独立表单(并入停机归因流程),form=null,不臆造表单。" + > + }> + {FORM_SLA_ESCALATION.map((f) => ( + + + + + + + ))} +
表单对应录入单SLA升级对象
{f.label}{f.form ? ENTRY_FORM_LABEL[f.form] : 无独立表单}{f.sla}{f.escalateTo}
+ 超时升级对象照录原文:Down 归因 2h→EQ+MFG;Jam 归因当班内→MFG 班组长;等待登记当班内→PC;5S 当班内→EA。 +
+
+ + ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/stepchain/OeeTaskCenter.tsx b/src/modules/tfamd-oee/components/stepchain/OeeTaskCenter.tsx new file mode 100644 index 0000000..dd3d23f --- /dev/null +++ b/src/modules/tfamd-oee/components/stepchain/OeeTaskCenter.tsx @@ -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 = { + 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(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 ( +
+ } + extra={两套状态机·独立枚举} + /> + + 任务中心承载两套独立状态机:StepChain 换型链走 ChainTaskState 七态(现场换型执行,n6 质量门不可跳过), + 改善闭环走 TaskState 六态(改善立项,四项必填齐备才派发)。两者都有「执行中」,但属不同枚举、不同流转表,互不引用(D17)。 + 换型链实例为模拟种子;改善任务与优先清单/录入台共享同一份状态。 + + + + + {/* ── A. StepChain 换型链七态 ── */} + + + {/* ── B. 改善闭环六态治理台 ── */} + } + full + right={{tasks.length} 条任务 · 与录入台共享} + note="六态:待生成→待审核→已派发→执行中→已验证→已归档(待审核可退回待生成)。派发闸只挂「待审核→已派发」:四项必填任一缺失即拒派,任务停在待审核(断言⑨)。点击行选中。四项必填的编辑在录入台。" + > + + + }> + {tasks.map((t) => { + const on = t.id === selectedTaskId; + return ( + selectTask(t.id)} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}> + + + + + + + + ); + })} +
任务标题状态真因优先分负责人
{t.id}{t.title}{TASK_STATE_LABEL[t.state]}{t.causeClass} 类{t.priorityScore.toFixed(4)}{t.owner ?? 未指定}
+ {tasks.length === 0 && 暂无改善任务。前往「优先处理清单」由 POC 候选生成待审核任务,再回本页治理派发。} +
+ + {selectedTask && ( +
+ } + right={{taskCheck?.ok ? '齐备·可派发' : `缺 ${taskCheck?.missing.length ?? 0} 项`}} + note="负责人 / 完成时限 / 预期收益(区间) / 验证方式。本页只读展示齐备状态;缺项时派发被拒,任务停在待审核。补齐编辑请前往录入台。" + > +
+ {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 ( +
+ {ok ? : } + {f.label} + {val} +
+ ); + })} +
+ +
+ {selectedTask.state === 'PENDING_REVIEW' && ( + + )} + {nextStates(selectedTask.state).filter((s) => s !== 'DISPATCHED').map((s) => ( + + ))} + {nextStates(selectedTask.state).length === 0 && 终态·无后继} + {selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && onNavigate && ( + + )} +
+ + {gateMsg && ( +
+
+ {gateMsg.ok ? '流转成功' : '被拒绝'} +
+ {gateMsg.reason &&
{gateMsg.reason}
} + {gateMsg.missing && gateMsg.missing.length > 0 && ( +
+ {gateMsg.missing.map((m) => {m.label}:{m.prompt})} +
+ )} +
+ )} + {selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && ( +
+ m.label).join('、') ?? ''} + stage="录入台补齐后派发" + note="缺一项即拒派:任务停在「待审核」,绝不静默推进到「已派发」。补齐后 SLA 方才起算(断言⑨)。" + /> +
+ )} +
+ + } + right={{TASK_STATE_LABEL[selectedTask.state]}} + note="历史时间线由引擎在每次合法流转时追加(at/by 注入,可重放)。SLA 计时起点=首次进入「已派发」的时刻。非法跨态跳转被拒绝。" + > +
+ {selectedTask.history.map((h, i) => ( +
+
+ + {i < selectedTask.history.length - 1 && } +
+
+
+ {TASK_STATE_LABEL[h.state]} + {h.at.slice(0, 19).replace('T', ' ')} + {h.by} +
+ {h.note &&
{h.note}
} +
+
+ ))} +
+
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/supply/ProductionOrderList.tsx b/src/modules/tfamd-oee/components/supply/ProductionOrderList.tsx new file mode 100644 index 0000000..8e4caaa --- /dev/null +++ b/src/modules/tfamd-oee/components/supply/ProductionOrderList.tsx @@ -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 && ( +
+ + 关联订单 {filterSO} + + +
+ )} + + {/* 汇总条 */} +
+ {list.length} 张工单 · {new Set(list.map(w => w.生产车间)).size} 个车间 + {fmtQty(totalQty)} PCS +
+ + + {list.length === 0 && ( +
+ {filterSO ? '该销售订单暂无生产工单' : '无匹配工单'} +
+ )} + {list.map(w => { + const active = selectedSO === w.来源销售订单号; + const sc = statusColor(w.单据状态, tokens); + return ( +
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 && } + {/* 行1:工单号 + 状态 */} +
+ + {w.工单号} + + + {w.单据状态} +
+ {/* 行2:来源订单 + 车间 */} +
+ 来自 + {w.来源销售订单号} + {w.生产车间} + + BOM {w.BOM版本} +
+ {/* 行3:产品 + 规格 */} +
+ + {w.产品编码} + {w.规格型号 && ( + {w.规格型号} + )} +
+ {/* 行4:数量 + 工期 */} +
+ {fmtQty(w.生产数量)} + {w.计量单位} + + + {w.预计开工日期} → {w.预计完工日期} · {w['生产周期(天)']} 天 + +
+
+ ); + })} +
+ + {/* 底部口径说明:工单由销售订单派生,一单一工单 */} +
+ + 工单由销售订单派生 · 生产数量已对齐订单数量 · 点击卡片可联动左栏订单 +
+ + ); +} diff --git a/src/modules/tfamd-oee/components/supply/PurchaseOrderList.tsx b/src/modules/tfamd-oee/components/supply/PurchaseOrderList.tsx new file mode 100644 index 0000000..fde68e9 --- /dev/null +++ b/src/modules/tfamd-oee/components/supply/PurchaseOrderList.tsx @@ -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(); + 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 && ( +
+ + 关联订单 {filterSO} + + +
+ )} + + {/* 汇总条 */} +
+ {list.length} 张采购单 · {new Set(list.flatMap(g => g.材料)).size} 种物料 + ¥{money(total)} +
+ + + {list.length === 0 && ( +
+ {filterSO ? '该销售订单暂无关联采购单' : '无匹配采购单'} +
+ )} + {list.map(g => { + const sc = statusColor(g.订单状态, tokens); + return ( +
+ {/* 行1:单号 + 状态 */} +
+ + {g.采购订单号} + + + {g.订单状态} +
+ {/* 行2:供应商 */} +
+ {g.供应商简称} + {g.供应商编码} + + 下单 {g.采购日期} +
+ {/* 行3:材料 */} +
+ + + {g.材料.slice(0, 3).join('、')}{g.材料.length > 3 ? ` 等 ${g.材料.length} 种` : ''} + +
+ {/* 行4:金额 + 到货 */} +
+ ¥{money(g.金额)} + {g.行数} 行 + + 到货 {g.预计到货日期} +
+
+ ); + })} +
+ + ); +} + +/** + * 滚动区已上移到 layout/AutoScroll(新告警面板也用它),这里只留转发导出, + * 免得 demand/supply 三个旧列表各自再抄一份。 + */ +export { ScrollList }; diff --git a/src/modules/tfamd-oee/components/supply/SupplierList.tsx b/src/modules/tfamd-oee/components/supply/SupplierList.tsx new file mode 100644 index 0000000..a6bf3ea --- /dev/null +++ b/src/modules/tfamd-oee/components/supply/SupplierList.tsx @@ -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 && ( +
+ + 关联订单 {filterSO} · 仅该单涉及的供应商 + + +
+ )} + + {/* 汇总条 */} +
+ {list.length} 家供应商 · {totalLines} 行采购 + ¥{money2(total)} +
+ + + {list.length === 0 && ( +
+ {filterSO ? '该销售订单暂无涉及供应商' : '无匹配供应商'} +
+ )} + {list.map(s => { + const nc = natureColor(s.性质, tokens); + return ( +
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:简称 + 编码 + 性质 */} +
+ + + {s.供应商简称} + + {s.供应商编码} + + {s.性质} +
+ {/* 行2:类别 + 部门 */} +
+ {s.所属类别} + + {s.分管部门 || '分管部门未填'} + +
+ {/* 行3:金额 + 行数 */} +
+ ¥{money2(s.采购金额)} + + {s.采购行数} 行采购 +
+
+ ); + })} +
+ +
+ 行数与金额为该供应商在本批采购订单中的合计,与采购单页签同源可核对 +
+ + ); +} diff --git a/src/modules/tfamd-oee/components/workspace/DisclosureView.tsx b/src/modules/tfamd-oee/components/workspace/DisclosureView.tsx new file mode 100644 index 0000000..16ae479 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/DisclosureView.tsx @@ -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 ( + {children} + ); +} + +function Card({ title, icon, right, children, note, full }: { + title: string; icon?: ReactNode; right?: ReactNode; children: ReactNode; note?: ReactNode; full?: boolean; +}) { + const { tokens } = useTheme(); + return ( +
+
+ + {icon} + {title} + + {right} +
+
{children}
+ {note &&
{note}
} +
+ ); +} + +function Th({ children, right }: { children: ReactNode; right?: boolean }) { + const { tokens } = useTheme(); + return ( + {children} + ); +} + +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 ( + {children} + ); +} + +function Table({ head, children, maxHeight }: { head: ReactNode; children: ReactNode; maxHeight?: number }) { + const { tokens } = useTheme(); + return ( +
+ + {head} + {children} +
+
+ ); +} + +/** 一行等分的统计砖(看板红线:等分、stretch、底边对齐) */ +function Tiles({ items }: { items: { label: string; value: string; sub?: string; color?: string }[] }) { + const { tokens } = useTheme(); + return ( +
+ {items.map((it) => ( +
+
{it.label}
+
{it.value}
+ {it.sub &&
{it.sub}
} +
+ ))} +
+ ); +} + +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>({}); + + 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 }) => ( + + {g.group} + {g.total} + {g.real} + {g.placeholder} + + ); + + const th = (t: string, right?: boolean) => {t}; + + return ( +
+ {/* 抬头:本页用途 + 与顶栏同源的范围/口径/业务日标签 */} +
+ + + 说明与对照 · 评审防穿帮页 + + {simBadge() && {simBadge()}} + 业务日 {scope.bizDate} + + {scope.scopeLabel} + + + + {s.pageTotal} 页映射 · {s.noPromiseTotal} 条不承诺 · {s.caliberTotal} 项口径出处 · {s.assertionCount} 条断言 + +
+ + {/* 章节导航:点一下滚到对应卡片,评审时不必翻长页 */} +
+ {sections.map(({ id, label, Icon }) => ( + + ))} +
+ + {/* ══════════ 一、20 页映射 ══════════ */} +
+ } + right={{s.pageTotal} 页} + note={PAGE_TALLY_NOTE}> + th(t))}> + {PAGE_MAP.map((p) => ( + + + + + + + + + + + ))} +
{p.no}{p.name}{p.group} + {p.tally} + + + {p.status === 'real' ? '做实' : '占位'} + + {p.stage}{p.chapter}{p.acceptance}
+
+ + } + note={`左表=建议书 §5.2.3 核对表原值(${s.tallyReal}/${s.tallyPlaceholder});右表=本原型实际实现(${s.pageReal}/${s.pagePlaceholder})。差异页已在左侧 status 列逐一披露,不圆整。`}> +
+
+
文档核对表 tally
+ th(t, i > 0))}> + {s.tallyGroups.map(groupRow)} + + + + + + +
合计{s.pageTotal}{s.tallyReal}{s.tallyPlaceholder}
+
+
+
本原型实际 status
+ th(t, i > 0))}> + {s.groups.map(groupRow)} + + + + + + +
合计{s.pageTotal}{s.pageReal}{s.pagePlaceholder}
+
+
+
+
+ + {/* ══════════ 二、11 条不承诺清单 ══════════ */} +
+ } + right={主动出示,不等被问} + note={`出处:建议书 §1.2(6 条)+ §6.7.2(7 条,从价值角度重述)+ 规划书 §8「Demo 不承诺等保」。两表去重合并后恰为 ${s.noPromiseTotal} 条,逐条标注来源,不新增无出处的承诺。`}> + th(t))}> + {NO_PROMISE.map((r) => ( + + + + + + + + ))} +
{r.no}{r.item}{r.prototype}{r.production}{r.source}
+
+
+ + {/* ══════════ 三、28 项口径出处 ══════════ */} +
+ + } + right={待 IE 签字} + note={CALIBER_SOURCE_NOTE + ' 两个「优先级」概念不可混:priority P0/P1/P2 影响「能不能算」;isSensitivityKey 影响「算出来是多少」,两者不是同一集合。'}> + th(t))}> + {calibers.map((c) => ( + + + + + + + + + + + + ))} +
{c.id}{c.name}{c.defaultValue} + {/* ★ P0 一律灰(warning 底 + muted 字),绝不 success 绿 */} + {c.priority} + {c.owner}{c.scope}{c.sensitivityIssue ? {c.sensitivityIssue} : —}{c.statusLabel}{c.source}
+
+
+ + {/* ══════════ 四、三套「六」分类 ══════════ */} +
+ } + note={`六-1 与六-2 各自成立求和恒等式;六-3 是事件表归口用词,不成立恒等式,其中 ${s.grossNullEvents} 条计划类事件不进六-1。断言必须分两条写:null 键=${s.grossNullKeys} 个、覆盖事件=${s.grossNullEvents} 条;写成「null 项数=${s.grossNullEvents}」是错的。`}> +
+ {six.map((r) => ( +
+
+ {r.key} + {r.name} + + + {r.hasIdentity ? '有恒等式' : '无恒等式'} + +
+
+ {r.members.map((m) => ( + {m} + ))} +
+
{r.usage}|{r.identity}
+
承载:{r.carrier}|{r.source}
+
+ ))} +
+
+ + } + note={ASLT_DAY_GAP_NOTE}> + th(t, i > 0))}> + {ASLT_TIME_ACCOUNT_POC.map((r) => ( + + + + + + ))} + + + + + +
{r.cls}{r.hours.toFixed(2)}{r.pct.toFixed(2)}
合计{ASLT_ACCOUNT_TOTAL_HOURS.toFixed(2)}{s.asltPocSumPct.toFixed(2)}
+
+
+
Wait + Plan
+
{ASLT_WAIT_PLAN_PCT}%
+
物料保障与排产优先于设备维修
+
+
+
残差
+
0.000000h
+
POC 实测;日历日 32 / 时间账 31
+
+
+
+
+ + {/* ══════════ 五、同名不同口径的读数 ══════════ */} +
+ } + right={风险 P4} + note={READING_DISCIPLINE_NOTE}> + th(t))}> + {CONFLICT_READINGS.map((r, i) => ( + + + + + + + + + + + ))} +
{r.region}{r.value}{r.metric}{r.scope}{r.window}{r.caliber}{r.note}{r.source}
+
+ + } + note="目标值为〔方案〕给出的改善方向,不是承诺值(见不承诺清单第 7、8 条)。"> +
+ {POC_ANCHORS.map((a) => ( +
+
+ {a.region} + + 目标 {a.target} +
+
{a.oee}
+
{a.apq}
+
{a.baselineNote}
+
+
{a.lever}
+
+ ))} +
+ +
+ + {/* ══════════ 六、数据来源标注 ══════════ */} +
+ } + right={{s.mode} 模式} + note={dataModeNote() + ' ' + s.coverageGap}> + th(t))}> + {sources.map((r) => ( + + + + + + + ))} +
{r.layer} + {r.what} +
{r.module}
+
+ 〔{r.tag}〕 + {r.simulated &&
{SIM_BADGE}
} +
{r.gap ?? '无'}
+
+ + } + note="页面每个数字旁都要能落到其中之一。〔POC〕是 POC 阶段实测结论、作参考基线;「模拟」是本原型合成种子,不是客户生产实况。"> +
+ {EVIDENCE_LEDGER.map((e) => ( +
+
+ {e.label} + {e.simulated && 非生产实况} +
+
{e.meaning}
+
+ ))} +
+
+
+ + {/* ══════════ 六-2、附件判定矩阵修正清单(核验报告 §3) ══════════ */} +
+ } + right={矩阵 ≠ 实测处逐条披露} + note={MATRIX_CORRECTION_NOTE}> + th(t))}> + {MATRIX_CORRECTIONS.map((r) => ( + + + + + + + ))} +
{r.no}{r.claim}{r.measured}{r.action}
+
+
+ + {/* ══════════ 七、W0 阻塞项与追问清单 ══════════ */} +
+ } + right={{s.blockerSelfSolvable.length} / {s.blockerCount} 我方可自解} + note="W0 不做完,W1 不开工。四件事里只有 W0-1 我方能自行解决(已改 5203)。W0-2/W0-3 未签字时 W1 仍可开工,但必须用附录 E 默认值、全站标「待 IE 签字」、配置中心 P0 标灰不标绿——不得假装已签字。"> + th(t))}> + {W0_BLOCKERS.map((b) => ( + + + + + + + + ))} +
{b.id}{b.item}{b.owner}{b.deliverable} + {b.status} +
+
+ + } + note="拿到三份基准表时一并问清,否则原型只能标「待确认」。Q1 与 Q4 会直接改变核心结论的分母与考核基线。"> + th(t))}> + {W0_QUESTIONS.map((q) => ( + + + + + + + ))} +
{q.id}{q.q}{q.why}{q.source}
+
+
+ + {/* ══════════ 八、断言核验登记 ══════════ */} +
+ } + right={ + + {s.registryScriptCount} 脚本 + + {s.extraVerifyCount} 实施附加 + {VERIFY_COMMAND} + + } + note={VERIFY_NOTE}> + th(t))}> + {ASSERTION_REGISTRY.map((a) => ( + + + + + + + + ))} + {EXTRA_VERIFY_SCRIPTS.map((e) => ( + + + + + + + + ))} + + + + + + + +
{a.id}{a.name}{a.invariant}{a.script} + {a.stage} +
附加{e.name}实施中另加,不在规划书 {s.assertionCount} 条内,守同一批纪律{e.script}{e.stage}
入口聚合执行依次跑全部脚本,打印汇总,任一失败则非零退出{VERIFY_AGGREGATE}W1-G
+
+ + } + note="门禁不通过就停下修,不带着问题横向扩展。本页只登记判据,通过与否以现场执行输出为准。"> +
+ {GATES.map((g) => ( +
+
+ {g.id} + {g.when} +
+
{g.criterion}
+
+
+ 不通过:{g.onFail} +
+
+ ))} +
+ +
+ + {/* 页脚:本页自身的出处与纪律 */} +
+ 本页数据源:src/data/oee/disclosure.ts + ({s.pageTotal} 页映射与 POC 实测值为转录常量,逐条带出处;其余计数全部现算自 calibers28 / events48 / devices / oeeService)。 + 校验脚本:scripts/verify-oee-disclosure.ts。 + 纪律:未签字不标绿 · POC 数字只作参考基线 · 三套六分类不混用 · 同名读数三标签齐全 · 文档冲突显式披露不圆整。 +
+
+ ); +} + +/** 供视图外壳渲染页签标题时用(与 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, +}); \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeDq.tsx b/src/modules/tfamd-oee/components/workspace/OeeDq.tsx new file mode 100644 index 0000000..755692e --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeDq.tsx @@ -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 = { + NO_PAIR: '无配对事件', NO_LOT: '无批次窗口', NO_SOURCE: '无来源事件', + GAP_FILL: '间隙填充留白', AMBIGUOUS: '归属歧义', +}; + +/** 问题单状态 → 中文与色(OPEN 待处理 / ASSIGNED 已派单 / CLOSED 已关闭)。 */ +const ISSUE_STATE_LABEL: Record = { 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 ( +
+ } /> + + 数据质量治理仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。
+ {scope.gap ?? scope.coverageNote} +
+
+ ); + } + + 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 ( +
+ } + extra={{dq.blocked ? '结论暂缓发布' : '当日结论可发布'}} + /> + + {/* 发布门禁横幅:阻断→danger,缺证据→warning,全清→success。话术由 L3 publishNotice 原文给出。 */} + {dq.blocked ? ( +
+ +
+
结论暂缓发布
+
{dq.publishNotice}
+
+ {dq.blockedBy.map((c) => {c} {DQ_RULE_BY_CODE[c].name})} +
+
+ 补录入口:中央「录入台」页签的停机归因单 / 等待登记单(D 类事件 5M1E 人工补录)。 + 提交后按口径重算当日 OEE:未归因占比下降、DQ-06 可能解除,口径版本号递增留痕;阻断解除前结论仍暂缓发布。 +
+
+
+ ) : ( +
+ + {dq.publishNotice} +
+ )} + + {/* 治理概览砖:一行等分(看板红线)。未归因占比是比例×100,阈值同源 DQ_DEFAULTS。 */} + + + {/* 第一行:12 条规则评估台账 + 处置分布与关键统计 */} +
+ } + right={缺证据 ≠ 通过} + note="判定条件与处置动作照录规划书 DQ 表原文。已评估=有证据并实际判定;缺证据=标灰不标绿,治理台据此提示补证;阻断级命中即暂停当日结论发布。" + > + + + }> + {DQ_RULES.map((r) => { + const isEval = evaluatedSet.has(r.code); + const missing = notEvalMap.get(r.code); + const hits = hitCount(r.code); + return ( + + + + + + + ); + })} +
规则处置评估状态命中
+ {r.code} + {r.name} + {dispoLabel(r.disposition)} + {isEval + ? 已评估 + : 缺证据·未评估} + {missing &&
缺:{missing}
} +
0 ? (r.blocking ? tokens.danger : tokens.warning) : tokens.textMuted}> + {isEval ? (hits > 0 ? `${hits} 项` : '未命中') : '—'} +
+
+ + } + note="自动修正类(DQ-01/02/05/09)只在 L1 采集适配层落地,L2 引擎只报告应如何修正,保持纯函数可重放、修正过程可审计;标注类进人工确认队列;阻断类暂停发布。" + > + +
+ + + }> + + + + + + + + + + + + + + + + + + + + + +
规则统计项读数
DQ-01时钟回跳 / 已校正{stats.clockBackwardCount} 次 / {stats.correctedCount} 条
DQ-05编码异常行(latin-1 回退){day.normalize.malformed.length} / {day.seed.lines.length} 行
DQ-09重复事件丢弃 / 重复率{stats.duplicateCount} 条 / {pct(stats.duplicateRate)}%
DQ-06未归因占比(阈值 {pct(DQ_DEFAULTS.unattributedBlockPct)}%){pct(stats.unattributedPct)}%
DQ-10未采集 UNKNOWN(≠无生产) 0 ? tokens.warning : tokens.textSub}>{dur(tot.unknownSec)}
+
+ {/* 缺证据规则的补证依赖:标灰不标绿,写明缺什么、依赖谁、何时做实(看板红线:空区填满) */} + {dq.notEvaluated.length > 0 && ( +
+ n.code).join('、')})`} + dependsOn={dq.notEvaluated.map((n) => `${n.code}:${n.missing}`).join(';')} + stage="W3 录入台补录 + 二期采集侧证据接入" + note="缺证据 ≠ 通过:这些规则本期无法判定,治理台标灰,不并入「未命中」。证据到位后自动转为已评估。" + /> +
+ )} +
+
+ + {/* 第二行:当日命中问题明细 + 未归因池与未采集 */} +
+ } + right={{dq.issues.length} 项} + note="命中条件为引擎按当日证据现算的原文,不是规则字典里的通用判定式。阻断级问题的状态照录引擎(当前为「待处理」),须在任务中心派单处理后才能解除阻断发布;不预设已派单。" + > + {dq.issues.length === 0 ? ( + + 当日已评估规则均未命中问题。
+ 缺证据未评估的规则见上方台账(标灰,不视为通过)。 +
+ ) : ( + + + }> + {dq.issues.map((i) => ( + + + + + + + ))} +
规则命中条件处置状态
+ {i.code}
{DQ_RULE_BY_CODE[i.code].name}
+
+ {i.condition} + {i.gap &&
缺口:{i.gap}
} +
{dispoLabel(DQ_RULE_BY_CODE[i.code].disposition)} + {ISSUE_STATE_LABEL[i.state] ?? i.state} + {i.blocking &&
阻断发布
} +
+ )} +
+ + } + right={{pool.length} 段未采集} + note="未归因 IDLE(采到了但归不了因,DQ-06,计入分母)≠ 未采集 UNKNOWN(日志断流,不计 PPT 分母,DQ-10)≠ 无生产。下表只列 UNKNOWN 段;未归因 IDLE 无段级明细(见设备时间轴),补录入口同在 W3「录入台」。" + > + 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 段数' }, + ]} /> +
+ {pool.length === 0 ? ( + 当日无未采集 UNKNOWN 段(日志连续)。
未归因 IDLE 合计见上方读数,与未采集分开统计。
+ ) : ( + + + }> + {pool.map((u) => ( + + + + + + + + ))} +
段时长占 PPT原因建议表单
{u.id.replace(`unk-${day.device.id}-`, '')}{dur(u.durationSec)}{pct(u.pctOfPlanTime)}%{REASON_LABEL[u.reason] ?? u.reason} + {u.suggestedForm ? ENTRY_FORM_LABEL[u.suggestedForm] : '—'} + {u.resolved &&
已解决
} +
+ )} +
+
+
+ + {/* demo:3 个业务日种子的全量 DQ 发现聚合 */} + } + full + right={{findings.length} 条 · 3 个业务日} + note="聚合内置 3 个业务日种子的引擎 DQ 发现(规则/设备/业务日/判定条件),只读展示,视图不重判。demo 沙箱不落库、不连接后端。" + > + + + } maxHeight={320}> + {findings.map((r) => ( + + + + + + + + + ))} +
规则设备业务日判定条件处置阻断
{r.code}{r.device ?? '—'}{r.bizDate} + {r.condition} + {ISSUE_STATE_LABEL[r.state] ?? r.state}{r.blocking ? 阻断 : 否}
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeEntry.tsx b/src/modules/tfamd-oee/components/workspace/OeeEntry.tsx new file mode 100644 index 0000000..51011c1 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeEntry.tsx @@ -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 = { + 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 } +interface EntrySubmitResult { entry: { id: number }; before: Record | null; after: Record | 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, 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(null); + const [values, setValues] = useState>({}); + const [prefilled, setPrefilled] = useState>(new Set()); + const [device, setDevice] = useState(scope.day?.device.id ?? 'DEK001'); + const [checks, setChecks] = useState(null); + const [err, setErr] = useState(null); + const [result, setResult] = useState(null); + const [audit, setAudit] = useState([]); + 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 = { operator: ENTRY_OPERATOR }; + const pre = new Set(['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, operator: ENTRY_OPERATOR, + }), [formId, device, bizDate, values]); + + const doValidate = () => { + if (!form) return; + setErr(null); + setChecks(buildChecks(form, values, device)); + }; + + const snapshot = (d: ReturnType | 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) => { + onTasksChange(tasks.map((t) => (t.id === id ? { ...t, ...patch } : t))); + }; + const [selectedTaskId, setSelectedTaskId] = useState(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 ; + } + if (fd.type === 'bool') { + return ( + + ); + } + if (fd.type === 'select') { + return ( + + ); + } + return ( + setField(fd.key, e.target.value)} + placeholder={isPre ? '已自动带出(可修改)' : ''} + /> + ); + }; + + return ( +
+ } + extra={demo · 不落库} + /> + + {err && 错误:{err}} + +
+ {/* 左:八张表单 */} + } + right={{forms.length || 8} 张} + note="机台/时间/人员灰底为系统预填,可改;* 为必填。提交后生成现场事件并写入审计。"> +
+ {forms.map((f) => { + const on = f.id === formId; + return ( + + ); + })} +
+
+ + {/* 右:表单 */} + } + right={<>独立录入{form && {form.events.join(' / ')}}} + note="六项防呆:必填完整 / 时间合法 / 不重叠 / 区域匹配 / 前置状态 / 人员在册。SLA 超时只提示、不阻断。"> +
+
+ + { setDevice(e.target.value); if (formId) loadPrefill(formId, e.target.value); }} /> +
+ {form ? ( +
+ {form.fields.filter((fd) => fd.key !== 'device').map((fd) => ( +
+ + {renderField(fd)} +
+ ))} +
+ ) : 选择一张录入单开始。} + + {form && ( +
+ + + demo 沙箱:提交只写内存状态与审计流,不落库 +
+ )} + + {checks && ( +
+
+ 防呆校验 + c.ok) ? tokens.success : tokens.warning}> + {checks.filter((c) => c.ok).length}/{checks.length} 通过 + +
+
+ {checks.map((c) => ( +
+ {c.ok ? + : } + + {c.id} {c.name}{c.msg ? `:${c.msg}` : ''} + +
+ ))} +
+ {checks.every((c) => c.ok) &&
校验通过 · demo 沙箱可提交
} +
+ )} + + {result && ( +
+
+ + 提交成功 · 当日重算(demo 演示) + {`单号 ${String(result.entry.id ?? '')}`} +
+ }> + {(['oee', 'a', 'p', 'q'] as const).map((k) => ( + + + + + + ))} + + + + + +
指标提交前重算后
{k.toUpperCase()}{typeof result.before?.[k] === 'number' ? `${pct(result.before[k] as number)}%` : '—'}{typeof result.after?.[k] === 'number' ? `${pct(result.after[k] as number)}%` : '—'}
灯号{result.before?.light ?? '—'}{result.after?.light ?? '—'}
+
+ )} +
+
+
+ + } full + right={{audit.length} 条} + note="每次提交写入页面内存的 SUBMIT 与 RECOMPUTE 两条记录;重算前后快照都在 detail 里,可追溯、可对比。demo 沙箱不落库。"> + {audit.length === 0 ? 暂无审计记录。提交任意录入单后在此留痕(仅页面内存)。 : ( + }> + {audit.map((a) => ( + + + + + + + + ))} +
时间动作执行者单号详情
{a.at.slice(0, 19).replace('T', ' ')}{a.action}{a.actor}{a.entry_id ?? '—'}{JSON.stringify(a.detail)}
+ )} +
+ + {/* ── B. 改善任务 · 派发闸与六态流转(原样保留) ── */} + } + full + right={{tasks.length} 条任务} + note="六态:待生成→待审核→已派发→执行中→已验证→已归档(待审核可退回待生成)。派发闸只挂在「待审核→已派发」:四项必填任一缺失即拒派,任务停在待审核(断言⑨)。点击行选中。" + > + + + }> + {tasks.map((t) => { + const on = t.id === selectedTaskId; + return ( + { setSelectedTaskId(t.id); setGateMsg(null); }} style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }}> + + + + + + + + ); + })} +
任务标题状态真因优先分负责人
{t.id}{t.title}{TASK_STATE_LABEL[t.state]}{t.causeClass} 类{t.priorityScore.toFixed(4)}{t.owner ?? 未指定}
+
+ + {selectedTask && ( +
+ } + right={{taskCheck?.ok ? '齐备·可派发' : `缺 ${taskCheck?.missing.length ?? 0} 项`}} + note="负责人 / 完成时限 / 预期收益(区间) / 验证方式。待审核态可在此补齐;缺项时派发被拒,任务停在待审核,绝不静默推进。" + > +
+ {REQUIRED_FIELDS.map((f) => { + const ok = !missingKeys.has(f.key); + const editable = selectedTask.state === 'PENDING_REVIEW'; + return ( +
+
+ {ok ? : } + {f.label} + {!ok && {f.prompt}} +
+ {f.key === 'expectedBenefit' ? ( + editable ? ( +
+ patchTask(selectedTask.id, { expectedBenefit: { min: Number(e.target.value), max: selectedTask.expectedBenefit?.max ?? Number(e.target.value), unit: selectedTask.expectedBenefit?.unit ?? 'min/月' } })} placeholder="min" /> + – + patchTask(selectedTask.id, { expectedBenefit: { min: selectedTask.expectedBenefit?.min ?? 0, max: Number(e.target.value), unit: selectedTask.expectedBenefit?.unit ?? 'min/月' } })} placeholder="max" /> + patchTask(selectedTask.id, { expectedBenefit: { min: selectedTask.expectedBenefit?.min ?? 0, max: selectedTask.expectedBenefit?.max ?? 0, unit: e.target.value } })} placeholder="单位" /> +
+ ) :
{benefitText(selectedTask.expectedBenefit)}
+ ) : ( + editable ? ( + patchTask(selectedTask.id, { [f.key]: e.target.value } as Partial)} + placeholder={f.prompt} + /> + ) :
{(selectedTask[f.key] as string | undefined) || '—'}
+ )} +
+ ); + })} +
+ +
+ {selectedTask.state === 'PENDING_REVIEW' && ( + + )} + {nextStates(selectedTask.state).filter((s) => s !== 'DISPATCHED').map((s) => ( + + ))} + {nextStates(selectedTask.state).length === 0 && 终态·无后继} +
+ + {gateMsg && ( +
+
+ {gateMsg.ok ? '流转成功' : '被拒绝'} +
+ {gateMsg.reason &&
{gateMsg.reason}
} + {gateMsg.missing && gateMsg.missing.length > 0 && ( +
+ {gateMsg.missing.map((m) => {m.label}:{m.prompt})} +
+ )} +
+ )} +
+ + } + right={{TASK_STATE_LABEL[selectedTask.state]}} + note="历史时间线由引擎在每次合法流转时追加(at/by 注入,可重放)。SLA 计时起点=首次进入「已派发」的时刻。非法跨态跳转被拒绝。" + > +
+ {selectedTask.history.map((h, i) => ( +
+
+ + {i < selectedTask.history.length - 1 && } +
+
+
+ {TASK_STATE_LABEL[h.state]} + {h.at.slice(0, 19).replace('T', ' ')} + {h.by} +
+ {h.note &&
{h.note}
} +
+
+ ))} +
+ {selectedTask.state === 'PENDING_REVIEW' && !taskCheck?.ok && ( +
+ m.label).join('、') ?? ''} + stage="补齐后于本录入台派发" + note="缺一项即拒派:任务停在「待审核」,绝不静默推进到「已派发」。补齐左侧四项后再派发,SLA 方才起算。" + /> +
+ )} +
+
+ )} +
+ ); +} diff --git a/src/modules/tfamd-oee/components/workspace/OeeForecast.tsx b/src/modules/tfamd-oee/components/workspace/OeeForecast.tsx new file mode 100644 index 0000000..c24f6bc --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeForecast.tsx @@ -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 ( +
+ } + extra={{FORECAST_LABEL}} + /> + + {/* 为什么不上模型:四门槛全未达,把诚实判断写在脸上 */} + } tone={tokens.warning}> + {FORECAST_GATE_NOTE} + + + {!fc.available || !risk ? ( + + 当前筛选范围({scope.scopeLabel})无日志贯通结果,不做预测外推,也不显示 0。
+ {fc.gap ?? scope.gap ?? scope.coverageNote} +
+ ) : ( + <> + + {fc.anchorOee == null && fc.gap && {fc.gap}} + +
+ {/* 未来 30min 停机风险:规则外推 + 可重算规则文字 */} + } + right={{FORECAST_LABEL}} + tone={riskColor} + note={risk.rule} + > +
+ {RISK_LEVEL_LABEL[risk.level]} +
+
非计划停机占比 {pct(risk.unplannedPct)}%
+
=(故障桶 + 小停机桶)/ PPT
+
+
+ {/* 占比计量条:刻度 3% / 10% 两条阈值线,量程 0–20% */} + + {risk.degraded && ( + ⚠ DQ 阻断或未归因 >5%,本读数降级为仅供参考,不可发布。 + )} +
+ + {/* 未来 4h OEE:历史趋势 + 线性外推点(参考线),示意区间数值化;OEE 缺口时诚实空态 */} + {oee4h ? ( + } + right={{FORECAST_LABEL}} + note={oee4h.method} + > + +
+ 点值 {pct(oee4h.point)}% + 示意区间 {pct(oee4h.bandLow)}–{pct(oee4h.bandHigh)}% + 历史 {fc.history.length} 日 + {oee4h.degraded && 降级·仅供参考} +
+
+ ) : ( + } + right={缺口 · 不标 0} + > + {fc.gap ?? '当日实际 OEE 缺口:不做 OEE 外推、不显示 0。'} + {histValues.length > 0 ? ( + + ) : ( + 历史窗口内亦无有限 OEE 读数(Q 无良率源),趋势图不画假点。 + )} + }> + + + + + + + + + + + + + + + +
外推入参状态处置
当日实际 OEE 锚点缺口(G)不做 OEE 外推、不显示 0
历史有限 OEE 序列{fc.history.length} 日{fc.history.length === 0 ? '无有限读数,不画假点' : '仅有限日入外推'}
实测六桶(停机风险入参)可用停机风险仍按后端实测桶规则外推
+
+ )} +
+ + )} + + {/* 四门槛:全未达,标灰不标绿 */} + } full note="照录建议书 §4.6.1。四门槛全未达,原型处置一律「不训练」。"> + }> + {FORECAST_GATES.map((g) => ( + + + + + + + + ))} +
门槛要求当前状态达标原型处置
{g.name}{g.requirement}{g.status}{g.met ? '已达' : '未达'}{g.disposition}
+
+ + {/* 生产阶段模型路线:只登记,原型不实现 */} + } full note={MODEL_ROADMAP_NOTE}> + }> + {MODEL_ROADMAP.map((r) => ( + + + + + + + + ))} +
任务特征标签来源模型路线阶段
{r.task}{r.features}{r.labelSource}{r.models}{r.phase}
+
+
+ ); +} + +/** 停机风险占比计量条(量程 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 ( +
+
+
+ {[STOP_RISK_MED, STOP_RISK_HIGH].map((t) => ( +
+ ))} +
+
+ 中 {STOP_RISK_MED * 100}% + 高 {STOP_RISK_HIGH * 100}% + 量程 20% +
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeIntegration.tsx b/src/modules/tfamd-oee/components/workspace/OeeIntegration.tsx new file mode 100644 index 0000000..e066c20 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeIntegration.tsx @@ -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 ( +
+ } + extra={契约占位 · 无真实连接} + /> + + 原型不接任何真实系统:六通道全部为模拟适配器读本地种子,本页显示 IF-01~IF-12 的契约 + 频率 + 幂等 + 联调签收状态 + 过渡方案,不显示真实连接。 + 全部 {is.total} 份接口均未签收(过渡方案 {is.transition} / 未启动 {is.notStarted}),未签收接口不进入 P2/P3 依赖项。{LATENCY_200MS_NOTE} + + + + + {/* demo 沙箱:六条采集通道的合成/演示状态(静态说明,不连接后端) */} + } + full + right={demo · 不落库} + note="本工程为 demo 沙箱,六条采集通道均为模拟适配器读内置合成种子,不产生任何真实导入水位、行数或 DQ 计数。下表说明各数据源在 demo 中的合成/演示状态;下方 IF-01~IF-12 契约仍为草案占位(未签收),演示状态≠接口联调签收。" + > + + + }> + {CHANNELS.map((c) => ( + + + + + + + ))} +
数据源 / 通道协议与频率覆盖范围demo 状态
{c.name}{c.protocol} · {c.frequency}{c.coverage} + {channelProtoLabel(c.proto)} +
{c.protoImpl}
+
+
+ + {/* 12 接口契约 */} + } + right={联调签收标准} + note="方向/协议/频率/幂等逐条转录规划书 4.4.3。签收状态原型只有「过渡方案/未启动」两态,绝不出现「已签收」。原型替代列诚实描述当前用什么顶替(种子适配器/录入台/无),切换条件见下方过渡方案十项。" + > + + + }> + {IF_CONTRACTS.map((c) => ( + + + + + + + + + + + + ))} +
编号接口名称 · 方向协议与格式频率级幂等与补偿责任方 · 阶段签收状态原型替代
{c.id} + {c.name} +
{c.direction}
+
{c.protocol}{c.frequency}{c.tier}{c.idempotency}{c.owner}
{c.stage}
{c.signoff}{c.demo === 'seed' ? '种子适配器' : c.demo === 'manual' ? '录入台·W3' : '无'}
+
+ + {/* 六通道 + 三级实时性 */} +
+ } + right={模拟适配器} + note="LogAdapter 五方法为采集层统一契约(parse/normalize/dedupKey/clockCorrect/evidenceRef)。IO/三色灯通道需加装硬件,过渡期靠人工录入;人工录入通道 14 个 D 类事件真实可提交(断言⑥,W3-A)。" + > + + + }> + {CHANNELS.map((ch) => ( + + + + + + + + ))} +
通道协议/方式频率覆盖原型实现
{ch.name}{ch.needsHardware &&
需加装
}
{ch.protocol}{ch.frequency}{ch.coverage}{channelProtoLabel(ch.proto)}
+
+ + + }> + {LOG_ADAPTER_METHODS.map((m) => ( + + + + + ))} +
LogAdapter 五方法职责
{m.method}{m.desc}
+
+
+ + } + right={<200ms 只适用 L1} + note="原型必须在 UI 上区分三级,不能一律标「实时」。SOW 的「<200ms」只适用 L1 流式(规划书 H.7);原型不得在任何页面宣称全链路 <200ms。原型无流式(L1),OEE 重算为种子批跑(L2),班次窗口切分(L3)。" + > + + + }> + {LATENCY_TIERS.map((t) => ( + + + + + + + + ))} +
级别时延覆盖生产实现原型实现
{t.tier} {t.label}{t.latency}{t.coverage}{t.prodImpl}{t.protoImpl}
+
+ +
+
+ +
+
+
+ + {/* 适配器陷阱 + 可靠性七条 */} +
+ } + right={DEK · FT · ASLT} + note="原型实现的 3 个必须正确处理这些陷阱,否则数字失真;此表另列 5 类契约态陷阱(全厂适配器类别以主数据台账为准)。报警≠停机:FT「Temperature Wait」单日 500 次若判停机则 A=0,必须按 alarm_class 分类(event_def)。" + > + + + }> + {ADAPTER_TRAPS.map((a) => ( + + + + + + + ))} +
设备陷阱正确处理原型
{a.device}{a.trap}{a.correctHandle}{a.implemented ? '已实现' : '契约'}
+
+ + } + right={实现 {is.reliabilityImplemented}/{is.reliabilityTotal}} + note="原型实现前四条(可在种子里演示)+ 健康监控,后两条标生产阶段。增量拉取/幂等重试/编码自适应/时钟校正均在 DEK 一日 4 次改钟、三种编码混杂、滚动文件样本里真实演示。" + > + + + }> + {RELIABILITY_MEASURES.map((r) => ( + + + + + + + ))} +
#措施说明阶段
{r.n}{r.measure}{r.detail}{r.proto}
+
+
+ + {/* 异常处置 + 过渡方案 */} +
+ } + note="数据延迟会影响 OEE 出数(按延迟标注),其余四类不影响(保留上一版口径/转录入台/丢弃计数)。来源不可用转录入台补录,恢复后自动比对替换——不静默补数。" + > + + + }> + {IF_EXCEPTIONS.map((e) => ( + + + + + + + ))} +
异常类别判定条件系统处置影响 OEE
{e.category}{e.condition}{e.handling}{e.affectsOee}
+
+ + } + right={{TRANSITION_PLANS.length} 系统} + note="逐系统回答「拿不到接口怎么办」,比「风险:日志格式与时效需确认」有用得多,直接回应 SOW 的 9 系统集成要求。每个过渡态标明当前用什么替代、切换条件是什么。" + > + + + }> + {TRANSITION_PLANS.map((t) => ( + + + + + + + ))} +
系统依赖方用途过渡方案
{t.system}{t.dependsOn}{t.usage}{t.transition}
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeLineMap.tsx b/src/modules/tfamd-oee/components/workspace/OeeLineMap.tsx new file mode 100644 index 0000000..02e79cd --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeLineMap.tsx @@ -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 = { ok: '有读数·可发布', warn: '有读数·阻断/存疑', gap: '无读数·缺口' }; +const SOURCE_SHORT: Record = { 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 & { 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 ( +
+ } + extra={ + + 状态灯=数据可得性 + + } + /> + + + + {/* 拓扑:2D SVG / 3D 场景切换。3D=SOW 数字孪生可选包,造型为真实机台照片的风格化抽象 */} + } full + right={ +
+ {(['2d', '3d'] as const).map((v) => ( + + ))} +
+ } + note={view === '2d' + ? '主流程只连有工位序号的 5 台(DEK→FUJI→Datacon→回流焊→AOI);辅助工站无序号,不臆造拓扑连线。FT 三台并行按投入量加权,不串连。流动虚线/呼吸外环只出现在涉及当日告警或瓶颈的连线/设备上,是真实状态的强调,不是实时设备心跳。' + : '3D 造型参照真实机台照片做风格化抽象(DEK 圆拱罩+前观察窗 / FUJI 模块+供料 reel 排 / Datacon 前玻璃窗+侧显示器臂 / 回流焊隧道+排风管 / AOI 顶屏蓝光),不是 CAD 复刻。状态灯语义与 2D 一致=数据可得性;呼吸 halo 只挂当日告警设备、瓶颈环静态、传送带高亮只挂告警/瓶颈事实,未接入全静态,不是实时设备心跳。'}> + {view === '2d' ? ( + + + + + + + + + + + {/* ── SRF band ── */} + SRF 表面贴装 · 13 台(主流程 5 + 辅助/缓存 8) + {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 ( + + ); + })} + {srfMain.map((n, i) => )} + 辅助工站 / 中间缓存(无主流程序号,不臆造拓扑) + {srfAux.map((n, i) => )} + + {/* ── FT band ── */} + + FT 终测 · 3 台(并行 · 按投入量加权) + {ft.map((n, i) => )} + + {/* ── ASLT band ── */} + + ASLT 系统级测试 · 1 台 12 Site(事件驱动 · 活跃窗口) + {asltNode && } + {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 ( + + + Site {s.siteId} + + + {pct(s.enabledPct, 0)}% + + ); + })} + + ) : ( + + 3D 场景加载中… +
+ }> + + + )} + + +
+ {/* 图例 */} + }> +
+ {(['ok', 'warn', 'gap'] as LineMapLight[]).map((l) => ( +
+ + {LIGHT_LABEL[l]} +
+ ))} +
+ + {view === '2d' ? '瓶颈环(SRF→DCP005)' : '瓶颈地环(SRF→DCP005,静态)'} +
+ {view === '2d' ? ( + <> +
+ + 流动虚线:连线涉及当日告警设备或瓶颈(无则实线) +
+
+ + 呼吸外环:当日有告警的设备(无告警不呼吸) +
+ + ) : ( + <> +
+ + 传送带高亮:连线涉及当日告警设备或瓶颈(无则灰) +
+
+ + 呼吸 halo:当日有告警的设备(无告警不呼吸) +
+
+ + 点击设备:右侧明细卡(数字与下表同源 L3) +
+ + )} + 来源徽标:实测=日志贯通(DEK001)· 仿真=模板产物(DCP005/FT/ASLT)· 缺口=无读数。状态灯只表达数据可得性,不表达实时运行/停机。{view === '2d' ? '流动与呼吸只挂当日真实告警/瓶颈事实,未接入范围全图静态。' : '3D 造型为风格化抽象非 CAD;高亮与呼吸只挂当日真实告警/瓶颈事实,未接入范围全场景静态。'} +
+
+ + {/* 诚实披露 */} + } tone={tokens.warning}> + + 17 台台账里只有 DEK001 一台日志贯通到行号(绿);DCP005 与 FT 三台、ASLT 是模板仿真(非实测); + 其余 {stats.gap} 台标灰——台账在、日志通道未接,不显示 0。BUF001 中间缓存不生产、不计 OEE,只作缓冲解耦输入。 + 瓶颈环指向 DCP005(POC:751min 缺失 + 124min 停机)。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。 + + +
+ + {/* 节点明细表:17 台逐台来源/状态灯/三率/备注 */} + + } maxHeight={360}> + {nodes.map((n) => ( + + + + + + + + + + + + + ))} +
设备工站线别来源状态灯OEEAPQ备注
{n.deviceId}{n.bottleneck && 瓶颈}{n.station}{n.lineId}{SOURCE_SHORT[n.source]}{LIGHT_LABEL[n.light].split('·').map((part, k) => {k > 0 &&
}{k === 0 && }{part}{k === 0 && '·'}
)}
{n.oee == null ? '—' : `${pct(n.oee)}%`}{n.a == null ? '—' : pct(n.a)}{n.p == null ? '—' : pct(n.p)}{n.q == null ? '—' : pct(n.q)}{n.buffer ? `缓存占用 ${pct(n.buffer.occupancyPct, 0)}% · B≥${n.buffer.minCapacity} 解耦${n.buffer.fullyDecoupled ? '成立' : '不成立'}` : n.note}
+
+
+ ); +} + +/** 单个设备节点(SVG ):状态灯 + 设备码 + 工站 + 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 ( + + {pulse && ( + + )} + {node.bottleneck && } + + + {trunc(node.deviceId, compact ? 11 : 16)} + {SOURCE_SHORT[node.source]} + {trunc(node.station, stationMax)} + {oeeText} + {node.oee == null && 无读数} + {node.bottleneck && 瓶颈} + + ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeLineMap3D.tsx b/src/modules/tfamd-oee/components/workspace/OeeLineMap3D.tsx new file mode 100644 index 0000000..36a8e51 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeLineMap3D.tsx @@ -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 = { + 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; + 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 ( + + + + + ); +} +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 ( + + + + + ); +} +/** 圆拱罩:半圆柱横放(DEK/Datacon 的弧形顶盖特征) */ +function Hood({ w, r, p, c }: { w: number; r: number; p: V3; c: string }) { + return ; +} +const GLASS = '#101820'; +const FEET = (w: number, d: number, c: string) => ( + <> + {[[-1, -1], [1, -1], [-1, 1], [1, 1]].map(([sx, sz], i) => ( + + ))} + +); + +/* ── 五类主设备 + 辅助工站的抽象造型(要素来自真实机台照片) ── */ +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)} + + + + + + + + + + ); + case 'fuji': /* 长底座 + 4 模块单元(斜控制面板+小屏)+ 双层供料 reel 排 + 蓝色饰带 */ + return ( + <> + {FEET(w, d, dark)} + + + + {[0, 1, 2, 3].map((m) => { + const mx = -w / 2 + (m + 0.5) * (w / 4); + return ( + + + + + {[0, 1].map((tier) => ( + + + {Array.from({ length: 7 }, (_, i) => ( + + ))} + + ))} + + ); + })} + + ); + case 'datacon': /* 高柜 + 圆顶 + 大前玻璃窗(内龙门横梁)+ 侧挂显示器臂+键盘托 */ + return ( + <> + {FEET(w, d, dark)} + + + + + + + + + + + ); + case 'reflow': /* 长隧道体 + 顶加热罩 + 温区分缝 + 顶排风管×2 + 进出口导轨 + 入口小屏 */ + return ( + <> + + + {[1, 2, 3, 4].map((z) => ( + + ))} + {[-w * 0.22, w * 0.18].map((px, i) => ( + + + + + ))} + + + + {[0, 1, 2, 3, 4, 5].map((i) => ( + + ))} + + ); + case 'aoi': case 'dpvs': /* 箱体 + 倾斜顶屏 + 前检测窗(AOI 蓝光 / DPVS 绿光) */ + return ( + <> + {FEET(w, d, dark)} + + + + + + + ); + case 'xray': /* 铅灰防护箱体 + 小圆观察窗 + 顶部警示标 */ + return ( + <> + {FEET(w, d, dark)} + + + + + + ); + case 'jet': /* 点胶:小箱 + 龙门 + 双点胶针头 */ + return ( + <> + {FEET(w, d, dark)} + + + + + {[-0.2, 0.2].map((px, i) => ( + + ))} + + ); + case 'flip': /* 翻转机:箱体 + 45° 翻转框 */ + return ( + <> + {FEET(w, d, dark)} + + + + + + + + + ); + case 'loader': /* 上料机:料仓_magazine 叠板 + 推板机构 */ + return ( + <> + {FEET(w, d, dark)} + + {[0, 1, 2, 3, 4].map((i) => ( + + ))} + + + + ); + case 'conveyor': case 'green': /* 分轨/绿皮:双轨 conveyor + 支腿(绿皮加绿色罩) */ + return ( + <> + {[-1, 1].map((s) => ( + + + + + ))} + + + + {kind === 'green' && } + + ); + case 'buffer': /* 中间缓存:多层货架 + 占位板 */ + return ( + <> + {[-1, 1].map((s) => ( + + ))} + {[0, 1, 2].map((i) => ( + + + + + ))} + + ); + case 'tester': /* FT 终测一体机:测试柜 + 斜前面板 + 圆形测试头 + handler 臂 */ + return ( + <> + {FEET(w, d, dark)} + + + + + + + + + ); + case 'aslt': /* 系统级测试:12 Site 机架(2 行×6),使能 Site 亮绿 */ + return ( + <> + + + + {[-1, 1].map((s) => ( + + ))} + {(node.sites ?? []).map((s, i) => { + const c = i % 6, r = Math.floor(i / 6); + const on = s.enabledPct > 0; + return ( + + ); + })} + + ); + } +} + +/** 三色塔灯:亮段=状态灯语义(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 ( + + + {segs.map((s, i) => ( + + ))} + + ); +} + +/** 呼吸 halo:只挂当日告警设备;reduced-motion 静态。只动 opacity,不改几何。 */ +function PulseRing({ r, color, reduced }: { r: number; color: string; reduced: boolean }) { + const mat = useRef(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 ( + + + + + ); +} + +/** 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 ( + + + + ); +} + +function Orbit({ tz = -8 }: { tz?: number }) { + const { camera, gl } = useThree(); + const ref = useRef(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 ( + + + + + + + + + + ); +} + +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(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(); + 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) => { e.stopPropagation(); setSelected(id); }; + const hover = (on: boolean) => (e: ThreeEvent) => { + e.stopPropagation(); + // 光标只作用于模块内画布,不写 document.body(避免污染平台全局光标) + const el = e.nativeEvent.target as HTMLElement | null; + if (el) el.style.cursor = on ? 'pointer' : ''; + }; + + return ( +
+ setSelected(null)}> + + + + + + + + + + + + + <> + + + {/* 操作提示 */} +
+ 拖拽旋转 · 滚轮缩放 · 点击设备看明细(点空白取消) +
+ + {/* 下钻明细:数字一律 L3 传入,与 2D 明细表同源 */} + {sel && ( +
+
+ + {sel.deviceId} + {sel.bottleneck && 瓶颈} + + +
+
{sel.name} · {sel.station} · {sel.lineId}
+
+ OEE {sel.oee == null ? '—' : `${pct(sel.oee)}%`} + A {sel.a == null ? '—' : pct(sel.a)} + P {sel.p == null ? '—' : pct(sel.p)} + Q {sel.q == null ? '—' : pct(sel.q)} +
+
+ {sel.buffer ? `缓存占用 ${pct(sel.buffer.occupancyPct, 0)}% · B≥${sel.buffer.minCapacity} 解耦${sel.buffer.fullyDecoupled ? '成立' : '不成立'}` : sel.note} +
+
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeLoss.tsx b/src/modules/tfamd-oee/components/workspace/OeeLoss.tsx new file mode 100644 index 0000000..b18d17f --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeLoss.tsx @@ -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 ( +
+ } /> + + 六桶损失分解仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。
+ {scope.gap ?? scope.coverageNote} +
+
+ ); + } + + 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 ( +
+ } + extra={ + {b.zeroResidual ? '六桶残差 0' : `残差 ${dur(b.residualSec)}`} + } + /> + + 0.05 ? '超 5% 阻断' : '≤5%', color: b.unattributedPct > 0.05 ? tokens.danger : tokens.textSub, title: '未归因 IDLE 时长 ÷ PPT,>5% 触发 DQ-06 结论暂缓发布' }, + ]} /> + +
+ } + right={分母 PPT} + 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。' : ''}`} + > + { + 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], + }; + })} + /> + + {LOSS_BUCKETS.filter((k) => bucketOf(k).derivedFromCycleDeviation).map((k) => BUCKET_LABEL[k]).join('、')} + {' '}为推导量(节拍偏差/检测结果),无事件级下钻;其余桶可下钻到事件族与原始日志行号。 + + + + } + right={{b.zeroResidual ? '恒等成立' : '残差=未归因+缺口'}} + note={b.residualNote} + > + +
+ + + }> + + + + + + + {LOSS_BUCKETS.map((k) => { + const row = bucketOf(k); + return ( + + + + + + + ); + })} + + + + + + +
构成项时长占 PPT归口
有效生产时间{dur(b.effectiveSec)}{pct(b.effectiveSec / (tot.pptSec || 1))}%良品×ICT
{BUCKET_LABEL[k]}{dur(row.durationSec)}{pct(row.pctOfPlanTime)}%{row.factor}{row.derivedFromCycleDeviation ? ' · 推导' : ''}
{isFuji ? '残差(量纲差)' : '残差(未归因+缺口)'}{dur(b.residualSec)}{pct(b.residualSec / (tot.pptSec || 1))}%{isFuji ? '=PPT−有效−Σ桶' : '=PPT−有效−Σ已计量桶'}
+ {!isFuji && !b.zeroResidual && ( + + 残差构成(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)}` : ''}。 + 未计量部分只随残差暴露,不摊进任何桶,也不按假设比例拆分。 + + )} +
+
+
+ + {/* 因子下钻 + 数据缺口(缺 EA 到场时间戳的子因子标灰,不摊数) */} + } + full + right={{b.factors.length} 个因子 · {b.untimedSubFactors.length} 项缺口} + note="一个状态段只归一个因子(整段归首事件),其余事件只留证不计时,避免同段时长被重复计入两个因子。被跳过的子因子作为数据缺口显式披露。" + > + {b.factors.length > 0 ? ( + + + } maxHeight={260}> + {b.factors.map((f) => ( + + + + + + + + + + ))} +
一级因子二级因子归口桶A/P/Q时长占 PPT事件码
{f.factorL1}{f.factorL2}{f.bucket ? BUCKET_LABEL[f.bucket] : '—'}{f.factor}{dur(f.durationSec)}{pct(f.durationSec / (tot.pptSec || 1))}%{f.eventIds.length} 个实例
+ ) : ( + 引擎本日未输出因子级明细(六桶排行仍照实出数;FAULT 等 A 类事件驱动的因子未成对,并非「无损失」)。 + )} + + {b.untimedSubFactors.length > 0 && ( +
+
未单独计量的子因子(数据缺口,标灰不摊数)
+ {b.untimedSubFactors.map((u) => ( + + ))} +
+ )} +
+ + {/* ── 质量损失:Q 因子与 Rescreen 关联(三区域 Q 不同构,并列对照,绝不混算)── */} +
+ {/* DEK 锚点 Q:日志贯通,良品/产出 */} + } + right={日志贯通} + 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 零,非零损失。' : ''}`} + > + +
+ + + }> + {qBuckets.map((k) => { + const row = bucketOf(k); + const isStartup = k === 'STARTUP_DEFECT'; + return ( + + + + + + + ); + })} +
Q 桶时长占 PPT来源
{BUCKET_LABEL[k]}{dur(row.durationSec)}{pct(row.pctOfPlanTime)}%{isStartup ? (startupEntered ? '推导+补录' : '未补录') : '节拍推导'}
+
+ {!startupEntered && ( + 开机不良尚未补录:当前 {dur(bucketOf('PROCESS_DEFECT').durationSec)} 过程不良含未拆分的开机部分,待录入台 D 类事件补录后重新拆分(不摊一个数充精度)。 + )} +
+ + {/* FT Q=1−Rescreen×良率损失:复测关联链 */} + } + right={模拟} + tone={FACTOR_COLORS.Q} + note="FT 无标准节拍,Q 用「复测率×良率损失」连乘扣减:复测越高、良率越低,Q 损失越大。操作数为演示合成种子(客户未给逐机值),不得冒充 POC 锚点 81.69%。" + > + + {ft.bizDate !== scope.bizDate && ( + 该业务日({scope.bizDate})无 FT 种子:照实参考最近可用日 {ft.bizDate}(真实覆盖窗口不重叠),不与 DEK 当日混算。 + )} +
+ + + }> + {ft.devices.map((dev) => ( + + + + + + + ))} +
设备Rescreen良率损失Q
{dev.deviceId}{pctUnitOrGap(ftQ(dev, 'rescreen').value)}{pctUnitOrGap(ftQ(dev, 'yieldLoss').value)}{pctUnitOrGap(ftQ(dev, 'q').value)}
+
+ {ftRep && ( +
+
复测关联链({ftRep.deviceId} · 照录引擎算式)
+ {(['rescreen', 'yieldLoss', 'q'] as const).map((key) => ( +
+ {ftQ(ftRep, key).label}:{ftQ(ftRep, key).formula} +
+ ))} +
+ )} +
+ + {/* ASLT Q=终测合格率:C03/C10 口径敏感 */} + } + right={模拟} + tone={FACTOR_COLORS.Q} + note="Q=(FT合格+RC复测合格)/FT投入。C03 取终测合格率(P0,待 IE 签字;FPY/UTT 为备选);C10 工程批是否剔除影响 Q≈2.08pp(P1)。与 DEK/FT 的 Q 不同构,不可跨区混算。" + > + + {aslt.bizDate !== scope.bizDate && ( + 该业务日({scope.bizDate})无 ASLT 种子:照实参考最近可用日 {aslt.bizDate}(真实覆盖窗口不重叠),不与 DEK 当日混算。 + )} +
+ + + }> + + + +
终测计数数量来源
FT 投入{qty(aslt.result.output.ftInput)}颗 · 合成
FT 合格{qty(aslt.result.output.ftGood)}颗 · 合成
RC 复测合格{qty(aslt.result.output.rcGood)}颗 · 合成
+
+
+
照录引擎算式
+
+ {asltQ.formula} +
+
+
+
+ + {/* Q 定义口径敏感性:C03/C10 决定 Q 绝对值,三区域不可混算 */} + } + full + right={C03 / C10 · 待 IE 签字} + tone={tokens.warning} + note="三区域 Q 定义不同构:DEK=良品/产出(日志贯通)、FT=1−复测×良率损失(连乘扣减)、ASLT=终测合格率(计数比)。分母与口径各异,严禁跨区混算或求平均;下表两项口径一旦定版变更,Q 绝对值随之改变,须走版本管理(断言⑩)。" + > + + + }> + {(['C03', 'C10'] as const).map((id) => { + const it = CALIBER_ITEMS[id]; + return ( + + + + + + + + ); + })} +
口径项议题默认值(待签字)优先级影响范围
{id}{it.name}{String(it.defaultValue)}{it.priority}{it.note}
+ + 当前口径版本 {day.caliberVersion};C03/C10 属 Q 定义敏感性议题,原型默认未签字,P0 项标灰不标绿。 + Q 定义快照=「{CALIBER_CONFIG.sensitivitySnapshot.qDefinition}」,与口径配置中心同源;定版变更须生成新版本并保留旧版本可回放(断言⑩)。 + +
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeMasterData.tsx b/src/modules/tfamd-oee/components/workspace/OeeMasterData.tsx new file mode 100644 index 0000000..e219d93 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeMasterData.tsx @@ -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 {d.ictSec}s/{d.unit}{d.ictSource === 'DERIVED' && 推导}; + } + return {d.ictSource === 'PENDING_IE' ? '待 IE' : '不适用'}; + }; + const collectCell = (d: DeviceMaster) => { + if (d.hasLog) return {d.logFormat}; + const fb = d.fallbackChannel === 'IO_LIGHT' ? '需加装 IO' : d.fallbackChannel === 'UPSTREAM_INFER' ? '上下游反推' : '人工录入'; + return {fb}; + }; + + return ( +
+ } + extra={全局台账字典} + /> + + 主数据是全局常量字典,不随业务日/筛选变化。沿用客户既有台账编码,{ds.demoCode} 台演示占位码标「待客户台账确认」; + ICT 无实测写 0 + 缺口说明(待 IE / 不适用),绝不编数;间隙阈值按设备可配置,台账值优先于公式(断言⑤)。 + 本次不安排口径工作坊,{cs.total} 项 signedOff 全 false,P0 标灰「待 IE 签字」。 + + + + + {/* 设备台账:全局常量字典台账 */} + } + right={现场 ≈{POC_FLEET_WITH_LOG + POC_FLEET_NO_LOG_APPROX} 台} + note="能力 ★1–3 为信号完整度;ICT 待 IE/不适用是口径事实非缺数;间隙阈值 kohyoung AOI001=15min(公式默认 18)、Jetting JET001=3min(公式默认 5),台账值优先于公式(断言⑤逐台比对)。中间缓存 BUF001 不计 OEE(只作缓冲解耦输入)。" + > + + + }> + {DEVICES.map((d) => ( + + + + + + + + + ))} +
设备(编码 · 名称)区域 · 工站能力ICT间隙采集 / 编码来源
+ {d.id} +
{d.name}
+
{d.region} · {d.station}{'★'.repeat(d.capability)}{ictCell(d)} + {d.gapThresholdMin}min + + {collectCell(d)} +
+ + {d.codeSource === 'DEMO' ? '占位码·待确认' : `真实码·${d.codeSource}`} + +
+
+
+ +
+
+ + {/* 48 事件字典 + 28 口径配置 */} +
+ } + right={缺号 {MISSING_CODES.length}} + note="等级按逐事件统计着色(A14/B7/C12/D14/E1),不按方案附录 A 分布表(其区域数字与逐条等级对不上,规划书 H.11)。bucket 由 GROSS_TO_BUCKET 现推,计划类 20 条 bucket=null 不进六桶。" + > +
+ ({ + label: `${g} 类`, value: String(es.grade[g] ?? 0), sub: GRADE_LABEL[g].slice(0, 4), color: gradeColor(g), title: GRADE_LABEL[g], + }))} /> +
+ + + }> + {EVENTS_48.map((e) => ( + + + + + + + + + + ))} +
码名称区域等级形式归口桶状态
{e.code}{e.name}{e.region}{e.grade}{e.form}{e.bucket ? {BUCKET_LABEL[e.bucket]} : 计划类}{EVENT_STATUS_LABEL[e.status]}
+
+ + } + right={待 IE 签字 {cs.total - cs.signed}} + 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 数值。" + > +
+ +
+ + + }> + {caliberRows.map((c) => ( + + + + + + + + + ))} +
编号口径项默认值优先级归口签字
{c.id}{c.isSensitivityKey && ★}{c.name}{String(c.defaultValue)}{c.priority}{c.owner}待签字
+
+
+ + {/* 线体班次 + 六桶/六-3 映射 */} +
+ } + note={SHIFT_ASSUMPTION_NOTE + '。C24:跨天班次归属到事件开始时刻所在业务日;本 pattern 每班起始于当天,故业务日=日历日,CT 窗口 00:00→24:00。'} + > + + + }> + {LINES.map((l) => ( + + + + + + + + ))} +
线体区域模板设备瓶颈
{l.id}{l.region}{TEMPLATE_LABEL[l.template]}{l.deviceIds.length}{l.bottleneckDeviceId ?? '—'}
+
+ + + }> + {SHIFT_PATTERN.map((s) => ( + + + + + + + + ))} +
班次名称起止跨天
{s.id}{s.name}{String(s.startHour).padStart(2, '0')}:00{String(s.endHour).padStart(2, '0')}:00{s.crossesMidnight ? '是' : '否'}
+
+ SRF 台账按建议书 3.5「13 类各 1 台」建;规划书 4.6.1 的 FUJI×2/Datacon×2 在原型以单台+2 Lane(FUJI)与 POC 改善标的 DCP005(Datacon)代表,差异已在此披露。 +
+ + } + right={六-1 · 互斥完备} + note="每事件码唯一归口一个桶。计划类时间(计划停机/计划待料/工程借用)bucket=null,进 PDT 从分母扣除或按 C06/C10 处理,不进六桶。残差恒等于未归因 IDLE,绝不为凑零而偷偷归一化(G2 门)。" + > + + + }> + {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 ( + + + + + + + ); + })} +
损失桶三率六-3 归口用词事件数
{BUCKET_LABEL[b]}{BUCKET_FACTOR[b]}{gross.join('、')}{cnt}
+
+ + + }> + {GROSS_CATEGORIES.filter((g) => GROSS_TO_BUCKET[g] === null).map((g) => ( + + + + + + ))} + + + + + +
六-3 归口(计划类)去向事件数
{g}{g === '工程借用' ? 'ENG·按 C06/C10' : '进 PDT 扣分母'}{GROSS_CATEGORY_COUNT[g]}
计划类合计不进六桶{es.nullBucketEvents}
+
+
+
+ + {/* 因子字典:一级/二级因子 */} + } + right={二级因子 {factors.length} 项} + 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('、') + '。'} + > + + + }> + {factors.map((f) => ( + + + + + + + + + + ))} +
一级因子二级因子六-3 归口损失桶三率承载事件码条数
{f.factorL1}{f.factorL2}{f.grossCategory}{f.bucket ? {BUCKET_LABEL[f.bucket]} : 计划类}{f.factor ? {f.factor} : —}{f.codes.join(' ')}{f.count}
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeOverview.tsx b/src/modules/tfamd-oee/components/workspace/OeeOverview.tsx new file mode 100644 index 0000000..a731c51 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeOverview.tsx @@ -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 ( +
+ } /> + + {/* 三层 OEE 概览砖:与顶栏五指标互补(这里是理论/计划/实际三档 + 残差),不重复 */} + {day ? ( + + ) : ( + + 当前筛选范围({scope.scopeLabel})无日志贯通结果,三层 OEE 不显示数字、也不显示 0。
+ {scope.gap ?? scope.coverageNote} +
+ )} + + {/* 第一行:计划与等待排行(POC) + 三站基线与改善目标(POC) */} +
+ } + tone={tokens.warning} + note={PLAN_WAIT_RANK_NOTE} + > + ({ + label: a.region, + value: a.planWaitShare, + display: `${a.planWaitShare}%`, + sub: a.planWaitLabel, + color: tokens.warning, + }))} + valueSuffix="%" + /> + {/* 同分母对照:每站内部「计划与等待」远大于「设备/真停机」——首页不是故障排行的依据 */} +
+ + + }> + {POC_ANCHORS.map((a) => ( + + + + + + + ))} +
区域计划与等待设备/真停机分母
{a.region}{a.planWaitShare}%{a.trueStopShare}%{a.denom}
+
+
+ + } + tone={tokens.info} + note="改善抓手按 POC 真因排序:组织与管理优先,设备维修排最后。" + > + + + }> + {POC_ANCHORS.map((a) => ( + + + + + + + + ))} +
区域基线 OEEA / P / Q目标改善抓手
{a.region}{a.oee} + {a.apq.split(' / ').map((s) =>
{s}
)} +
{a.target}{a.lever}
+ 基线明细:{POC_ANCHORS.map((a) => `${a.region} ${a.baselineNote}`).join(';')} +
+
+ + {/* 第二行:三层 OEE 与顺序替代(锚点) + 三区域合成读数(模拟) */} +
+ } + right={day ? 锚点单机 · 模拟 : undefined} + note={day ? `${PARAMS_SIGNOFF_NOTE}。顺序替代固定 A→P→Q,三项差异之和恒等于总差异。` : undefined} + > + {day ? ( + <> + + + }> + {tierRows.map((r) => ( + + + + + + + + ))} +
口径档APQOEE
{r.label}{pctUnitOrGap(r.t.a)}{pctUnitOrGap(r.t.p)}{pctUnitOrGap(r.t.q)}{pctUnitOrGap(r.t.oee)}
+ {delta && ( +
+
+ + 计划 → 实际 差异分解(pp) + + + {delta.identityHolds ? '恒等成立' : Number.isFinite(delta.total) ? '恒等不成立' : '恒等不可评(G 缺口)'} + +
+ +
+ )} + {tierRows.map((r) => `${r.label}:${r.note}`).join(' ')} + + ) : ( + + 三层 OEE 仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入。
+ 请切换到锚点设备,或到「工序·工位对比」页查看三区域模板仿真合成读数(模拟,非实测)。 +
+ )} +
+ + } + right={模拟 · 模板仿真} + note="线体合成已于 W2-A 落地(断言④):串行 A/Q 连乘、P 取瓶颈;并行按投入量加权;区域按线别投入量加权。合成非实测,不复现 POC 锚点,不与上方 POC 基线混算。" + > + + + }> + {rollup.lines.map((l, i) => ( + + + {l.ok ? ( + <> + + + + + + + ) : ( + <> + + + + + + + )} + + ))} + + + {rollup.region.ok ? ( + <> + + + + + + + ) : ( + <> + + + + + + + )} + +
范围APQOEE合成法
{['SRF-L1', 'FT-L1', 'ASLT-L1'][i]}{pctUnitOrGap(l.a)}{pctUnitOrGap(l.p)}{pctUnitOrGap(l.q)}{pctUnitOrGap(l.oee)}{METHOD_LABEL[l.method]}————该日无种子 · 不显示 0({l.problems.join(';')})
三区域加权{pctUnitOrGap(rollup.region.a)}{pctUnitOrGap(rollup.region.p)}{pctUnitOrGap(rollup.region.q)}{pctUnitOrGap(rollup.region.oee)}{METHOD_LABEL[rollup.region.method]}————{rollup.region.problems.join(';')}
+ {/* 反例对照:为什么不能那么算(三种错误方法的结果,与正确加权并列)。缺区时反例数字无意义,不提供 */} + {rollup.lines.every((l) => l.ok) ? ( +
+
反例对照(错误算法,仅供说明)
+ + + }> + + + + + + + + + + + + + + + +
错误方法OEE为什么错
线别算术平均{pctUnitOrGap(rollup.wrongMethods.arithmeticMeanOfLines)}忽略各线投入量差异
线别 OEE 加权{pctUnitOrGap(rollup.wrongMethods.weightedMeanOfLineOee)}OEE 是乘法合成,不能直接加权
日 OEE 求平均{pctUnitOrGap(rollup.wrongMethods.meanOfDailyOee)}应累加原始量再重算,非日均
+
+ ) : ( + 当前业务日有区域无种子(真实覆盖窗口不重叠):缺区行标 — 不标 0,跨区加权与反例对照不提供;各区域最近可用日读数见「工序·工位对比」页。 + )} +
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeePriority.tsx b/src/modules/tfamd-oee/components/workspace/OeePriority.tsx new file mode 100644 index 0000000..18d4950 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeePriority.tsx @@ -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 = { + 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(DEFAULT_WEIGHT_SCHEME); + const [selectedId, setSelectedId] = useState(candidates[0].id); + const [formTitle, setFormTitle] = useState(candidates[0].title); + const [rootType, setRootType] = useState('人员班组'); + const [rootId, setRootId] = useState(''); + const [causeClass, setCauseClass] = useState('B'); + const [lastCreated, setLastCreated] = useState(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 ( +
+ } + extra={POC 候选·跨三区域·分数现算} + /> + + + + 候选真因来自三站 POC 一致指向(组织与管理,而非设备维修),标「POC 候选·跨三区域」,不是当日单机现算,故本页不按 scope.day 门禁。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。 + + {/* 第一行:优先排序(可切换权重)+ 选中项可解释打分 */} +
+ } + right={ + + + {(['A', 'B'] as WeightSchemeId[]).map((id) => ( + + ))} + + } + note={`当前 ${ws.label}(${ws.source})。点击行选中,右侧摊开权重×分项逐条贡献。同分按候选 id 升序(确定性 tie-break,不用随机)。`} + > + + + }> + {ranked.map((r) => { + const on = r.item.id === selected.id; + return ( + selectCandidate(r.item.id)} + style={{ cursor: 'pointer', background: on ? tokens.accentBg : undefined }} + > + + + + + + ); + })} +
名次候选项区域分数
{r.rank} + {r.item.id} + {r.item.title} + {r.item.region ?? '—'}{r.score.score.toFixed(4)}
+
+ + } + right={总分 {score.score.toFixed(4)}} + note="断言⑧:contrib = weight × factor 原样返回,不做隐藏归一化/截断/缩放。评审可用下表逐条加回总分;权重之和透明展示。" + > +
+ {selected.title} + {selected.note &&
{selected.note}
} +
+ + + }> + {score.breakdown.map((b) => ( + + + + + + + ))} + + + + + + +
分项权重打分贡献
{b.label}{b.weight.toFixed(2)}{b.factor.toFixed(2)}{b.contrib.toFixed(4)}
Σ 总分{score.weightSum.toFixed(2)}—{score.score.toFixed(4)}
+
+
+ + {/* 第二行:换权重 → 排序对比(评审现场最有说服力的一屏) */} + } + full + right={{cmp.orderChanged ? '排序随权重改变' : '两套排序一致'}} + note="只比名次序列、不比分数(分数本来就不同)。A=SOW 直译偏「损失/产能」,B=金额导向,偏「金额/频次/可改善性」,故事线不同 → 优先序不同。默认 B。" + > + + + }> + {cmp.rankB.map((r) => { + const a = rankAOf(r.item.id); + const b = rankBOf(r.item.id); + const delta = a - b; // >0:B 比 A 更靠前(上升) + return ( + + + + + + + + ); + })} +
候选项区域A 名次B 名次B 相对 A
+ {r.item.id} + {r.item.title} + {r.item.region ?? '—'}{a}{b} 0 ? tokens.success : delta < 0 ? tokens.danger : tokens.textMuted}> + {delta > 0 ? `↑${delta}` : delta < 0 ? `↓${-delta}` : '—'} +
+
+ + {/* 第三行:由候选生成改善任务(只到待审核,四项必填留空) */} + } + full + right={lastCreated + ? 已生成 {lastCreated}·待审核 + : 生成后进入「待审核」} + note="首要真因挂五实体之一(不允许并列多个);真因 A/B/C 分类与「识别途径」是两回事。生成的任务四项必填留空 → 录入台派发闸会拒派,补齐后才能派发(断言⑨)。" + > +
+
+ + setFormTitle(e.target.value)} placeholder="改善任务标题" /> +
+
+ + +
+
+ + setRootId(e.target.value)} placeholder="如 FT-甲班 / XRAY-SETUP-01" /> +
+
+ + +
+
+ +
+ {CAUSE_CLASS_NOTE[causeClass]} + + + 证据链预填:{selected.note ?? selected.title} + + +
+ + {!canSubmit && ( + 请填写「实体 ID」后再生成(首要真因必须落到一个具体实体,不允许空挂或臆造)。 + )} + {lastCreated && ( + + 已生成 {lastCreated}(待审核·四项必填留空)。 + 前往「录入台 · 改善任务」体验派发闸:缺负责人/完成时限/预期收益/验证方式任一项即拒派,任务停在待审核。 + 当前共有改善任务 {tasks.length} 条。 + + )} +
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeRegion.tsx b/src/modules/tfamd-oee/components/workspace/OeeRegion.tsx new file mode 100644 index 0000000..5c411d4 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeRegion.tsx @@ -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 ( +
+ } /> + 当前业务日({scope.bizDate})无三区域种子结果,不显示数字、也不显示 0。 +
+ ); + } + + 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 ( +
+ } + extra={模拟 · 模板仿真} + /> + + 三区域线体合成已于 W2-A 落地(断言④)。本页读数为模板仿真合成,非实测、不复现 POC 锚点, + 不与日志贯通单机值混算;日志贯通全链路仅 DEK001 一台。三站算法不同构({TEMPLATE_LABEL.SRF_BUFFER} / {TEMPLATE_LABEL.FT_MULTIPLY} / {TEMPLATE_LABEL.ASLT_EVENT}), + 通用 A×P×Q 式套三站必错,故各站独立模板、各自标注口径。本工程为 demo 沙箱,数据来自内置合成种子,不连接后端。 + + + + +
+ {/* SRF 缓冲解耦 */} + } + right={<>{buf.fullyDecoupled ? '全线解耦' : '至少一侧未解耦'}} + note="上游停机靠缓冲覆盖(C_down=B×下游ICT),下游停机靠上游填充(C_up=B×上游ICT),两侧分母 ICT 不同不可混用。零缓冲是理论下界,不是本线考核口径。产出量取仿真值时 P 恒 100%(模型产物,非实测性能率)。" + > + + + }> + + + + + + + +
缓冲力学量值口径
缓冲容量 B{buf.capacity}在制品单位
覆盖时间 C_down{dur(buf.coverageSec)}B×下游ICT
上游最长停机{dur(buf.upstreamMaxStopSec)}合并非计划段
B_min(上游侧){buf.minCapacity}{buf.decoupled ? '已满足' : '未满足'}
B_min(下游侧){buf.minCapacityDownstream}{buf.decoupledDownstream ? '已满足' : '未满足'}(分母上游ICT)
上游阻塞损失{dur(buf.upstream.blockedSec)}{buf.upstream.blockCount} 次满载受限
下游饥饿损失{dur(buf.downstream.starvedSec)}{buf.downstream.starveCount} 次空缓冲受限
+
+ 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 全耦合,不是本线口径' }, + ]} /> +
+ {srf.dq.blocked && ( + DQ-10:{srf.dq.reason} + )} +
+ + {/* FT 多因子连乘 */} + } + right={<>A≠RT/PPT} + note="A=(1−Down率)(1−SetupLoss)(1−Corr)−计划损失,P=1−(OE+Index+Jam),Q=1−(Rescreen×良率损失)。并行合成按投入量对三率分别加权再连乘,不是对各台 OEE 求加权平均。SetupLoss 五操作数含义待 IE 确认。" + > + + + }> + {ft.devices.map((d) => ( + + + + + + + + + ))} + + + + + + + + +
设备APQOEEPM(C06)
{d.deviceId}{pctUnitOrGap(d.a)}{pctUnitOrGap(d.p)}{pctUnitOrGap(d.q)}{pctUnitOrGap(d.oee)}{d.pmIncluded ? `开 ${dur(d.pmSec)}` : '关'}
FT-L1 加权{pctUnitOrGap(ft.line.a)}{pctUnitOrGap(ft.line.p)}{pctUnitOrGap(ft.line.q)}{pctUnitOrGap(ft.line.oee)}投入量加权
+ {pmDev && pmOff && ( +
+
PM 敏感性(C06 开关对照 · {pmDev.deviceId})
+ +
+ )} +
+
反例:误用通用式 A=RT/PPT(错误,仅供对照)
+ + + }> + {ft.devices.map((d) => ( + + + + + + ))} +
设备连乘扣减 A(正确)通用 RT/PPT(错误)
{d.deviceId}{pctUnitOrGap(d.a)}{pctUnitOrGap(d.contrastGenericA)}
+
+
+
+ +
+ {/* ASLT 事件驱动 · 六-2 时间账 */} + } + right={<>残差 {dur(aslt.result.timeAccountResidualSec)}} + note="A/P 为活跃窗口口径(>60min 间隔切窗,单台 12 Site),与站别汇总口径(POC 41.75%)是两套读数,不得交叉配对。六分类时间账残差须为 0。Wait+Plan 占比是改善顺序依据(物料→排产→满载→换型→维修)。" + > + { + 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" + /> +
+ + + }> + {ASLT_TIME_CLASSES.map((c) => { + const row = aslt.result.timeAccount.find((t) => t.class === c)!; + const hot = c === 'WAIT' || c === 'PLAN'; + return ( + + + + + + ); + })} +
时间分类时长(h)占比
{ASLT_CLASS_LABEL[c]}{hot ? ' ★' : ''}{hrs(row.durationSec)}{row.pctOfTotal.toFixed(2)}%
+
+
+ ${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 }, + ]} /> +
+
+ + {/* 线体合成法与反例 */} + } + right={断言④ · 不用均值} + note="串行 A/Q 连乘·P 取瓶颈;并行按投入量对三率分别加权再连乘;区域按线别投入量加权。周期累计 Σ分子/Σ分母,不用日 OEE 求平均倒推。下方反例为错误算法,只供说明为什么不能那么算。" + > + + + }> + {rollup.lines.map((l, i) => ( + + + + + + + ))} + + + + + + +
范围投入量(权重)OEE合成法
{lineNames[i]}{qty(rollup.lineMembers[i].inputQty)}{pct(l.oee)}%{METHOD_LABEL[l.method]}
三区域加权{qty(rollup.lineMembers.reduce((a, m) => a + m.inputQty, 0))}{pct(rollup.region.oee)}%{METHOD_LABEL[rollup.region.method]}
+
+
反例对照(错误算法,仅供说明)
+ + + }> + + + + + + + + + + + + + + + +
错误方法OEE为什么错
线别算术平均{pct(rollup.wrongMethods.arithmeticMeanOfLines)}%忽略各线投入量差异
对线别 OEE 加权{pct(rollup.wrongMethods.weightedMeanOfLineOee)}%应对三率分别加权再连乘
日 OEE 求平均{pct(rollup.wrongMethods.meanOfDailyOee)}%应累加原始量再重算,非日均
+
+ {rollup.lines.some((l) => !l.ok) && ( + 合成输入存在问题:{rollup.lines.filter((l) => !l.ok).map((l) => `${l.scopeLabel}:${l.problems.join(';')}`).join(' ')} + )} +
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeReport.tsx b/src/modules/tfamd-oee/components/workspace/OeeReport.tsx new file mode 100644 index 0000000..b3939a1 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeReport.tsx @@ -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 = { + 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('DAILY'); + const [lastDownload, setLastDownload] = useState(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) => ( + + ); + + return ( +
+ } + extra={7 类固定报表 · 与智能体工具同源} + /> + + {/* 报表类别选择器:七类固定,点选即换预览与下载内容 */} + } + note="班次 OEE / 日报 / 异常 / 周报 / 月度口径 / 改善闭环 / 审计追溯。原型 OEE 为日级,班次筛选不改变日级口径;周/月仅 3 日种子,不足累计照实标缺口。"> +
+ {REPORT_KINDS.map((k) => { + const on = k === kind; + return ( + + ); + })} +
+
+ + + + {/* DQ 阻断 / 无种子:照实披露,不抹平 */} + {build.blocked && build.gap && ( + } tone={tokens.warning}> + + {build.gap} + + + )} + + {/* 周/月报诚实说明:种子覆盖不足一周/一月,不编累计数 */} + {isPeriodReport && ( + } tone={tokens.info}> + 原型仅 3 日种子(2026-09-01/02/03),不足一周/一月累计。本报表照实给出缺口说明行,不编造周/月累计数;生产阶段接入连续日志后再做实累计口径。 + + )} + + {/* 预览:动态列(行键并集,首见顺序),所见即所导出 */} + } + full + right={
{dlBtn('JSON', , 'JSON')}{dlBtn('CSV', , 'CSV')}
} + note="预览按可读格式渲染(比率 ×100、秒 → 时长、布尔 → 是/否);下载文件保留原始数值口径(JSON 原值 / CSV RFC4180,CSV 前置 BOM 供 Excel 识别 UTF-8)。列头为导出字段名。" + > + {rows.length === 0 ? ( + + {build.gap ?? `${scope.bizDate} 无种子日志,报表为空(不编数)。`} + + ) : ( + {cols.map((c) => )}} maxHeight={340}> + {rows.map((r, i) => ( + + {cols.map((c) => { + const v = r[c]; + const isRatio = RATIO_KEYS.has(c); + const isBool = typeof v === 'boolean'; + return ( + + ); + })} + + ))} +
{COL_LABEL[c] ?? c}
+ {fmtCell(c, v)} +
+ )} +
+ +
+ {/* 导出留痕:文件名 + 最近一次下载 */} + }> +
+
+ 文件名:{fileName} +
+
+ 命名规则 oee_<类>_<业务日>_<口径版本>.<json|csv>,口径版本随文件留痕(断言⑩),便于评审现场核对同一口径。 +
+ {lastDownload ? ( + 已下载 {lastDownload} + ) : ( + 尚未下载 · 点右上 JSON / CSV + )} + 下载为浏览器本地 Blob,不落库、不改种子(原型 SQLite 锁定四表,报表导出只读不写)。 +
+
+ + {/* 报表口径与边界 */} + } tone={tokens.warning}> + + ① 七类报表与智能体 exportReport 工具同源(buildReportPayload → reportRows),视图不另算一份数(断言②)。
+ ② 审计追溯报表带行号血缘(lineNo/source/wired),可回溯到 EVENT.DAT 原始行。
+ ③ 改善闭环报表读共享 tasks(与优先清单/录入台/任务中心同一份内存态)。
+ ④ 无种子日空行不编数;DQ 阻断标暂缓发布;周/月仅 3 日种子照实标缺口。
+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeTimeline.tsx b/src/modules/tfamd-oee/components/workspace/OeeTimeline.tsx new file mode 100644 index 0000000..cd7d4f3 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeTimeline.tsx @@ -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(null); + + if (!day) { + return ( +
+ } /> + + 状态段时间轴仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入。
+ {scope.gap ?? scope.coverageNote} +
+
+ ); + } + + 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 ( +
+ } /> + + {day.caliberVersion === 'rollup-day-v1' + ? '区域汇总(rollup-day-v1)无状态段(桶/段不加总,量纲异质)。成员逐台时间轴请切换到具体设备。' + : `${day.device.id} 为 ft-lot-q-v1 批次质量口径:无设备时间源(只有 lot 计数),状态段时间轴不适用。Q 读数见「损失结构」页。`} + +
+ ); + } + const selEvents = sel + ? sel.eventIds.map((id) => day.normalize.events.find((e) => e.id === id)).filter((e): e is NonNullable => !!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 ( +
+ } + extra={{day.detailRef}} + /> + + {scope.shiftNote && ( + {scope.shiftNote}(当前筛选:{selShift?.name ?? '全班次'},仅作用于下方时间轴与状态段表) + )} + + 0 ? tokens.warning : tokens.textSub, title: 'DQ-10:日志断流窗口,不得记为无生产' }, + { label: '状态段数', value: String(segs.length), sub: selShift ? `${visibleSegs.length} 段在本班` : '全班次', color: tokens.textSub }, + ]} /> + + {/* 十态甘特(手写 SVG) */} + } + right={点选状态段下钻血缘} + note="按抢占优先级解析后的非重叠状态段。UNKNOWN 单独着色(未采集,不计分母);虚线描边=间隙填充段;PM 窗口内停机保留影子双记录。班次筛选只高亮/筛选本段时间轴,OEE 仍为日级。" + > + {/* 班次带(HTML,避免 SVG 文字拉伸):3×8h 演示假设,宽度按真实窗口占比 */} +
+ {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 ( +
+ {pat?.name ?? sh.id} {sh.start.slice(11, 16)}–{sh.end.slice(11, 16)} +
+ ); + })} +
+ + + {/* 班次分隔线(8h/16h) */} + {[8, 16].map((h) => ( + + ))} + {segs.map((s) => { + const { x, w } = barOf(s); + const inShift = selShiftQualified ? s.shiftId === selShiftQualified : true; + const isSel = s.id === selId; + return ( + setSelId(s.id === selId ? null : s.id)} + > + {`${STATE_LABEL[s.state]} ${hhmmss(s.start)}–${hhmmss(s.end)} · ${dur(s.durationSec)}${s.filledByGapRule ? ' · 间隙填充' : ''}${s.shadowOf ? ' · 影子段' : ''}`} + + ); + })} + + + {/* 小时刻度(HTML,等分不拉伸) */} +
+ {[0, 4, 8, 12, 16, 20, 24].map((h) => {String(h % 24).padStart(2, '0')}:00)} +
+ + {/* 状态图例 + 计数 */} +
+ {STATE_ORDER.map((st) => ( + + + + {STATE_LABEL[st]} {stateCount(st)} + + + ))} +
+
+ +
+ {/* 状态段表(班次筛选时只列本班) */} + } + right={{visibleSegs.length} 段} + note="点行选中,与甘特高亮联动。置信度<1 或间隙填充段须人工确认;未归因 IDLE 段进未归因池(DQ-06)。" + > + + + } maxHeight={300}> + {visibleSegs.map((s) => { + const pat = SHIFT_PATTERN.find((p) => s.shiftId.endsWith(p.id)); + return ( + setSelId(s.id === selId ? null : s.id)} style={{ cursor: 'pointer', background: s.id === selId ? tokens.accentBg : undefined }}> + + + + + + + + + ); + })} +
状态起止时长班次事件标记
{STATE_LABEL[s.state]}{hhmmss(s.start)}{hhmmss(s.end)}{dur(s.durationSec)}{pat?.name ?? '—'}{s.evidenceCount ?? s.eventIds.length} + {s.filledByGapRule ? '间隙填充' : ''}{s.shadowOf ? ' 影子' : ''}{s.confidence < 1 ? ` ${s.confidence.toFixed(2)}` : ''}{s.state === 'IDLE' ? ' 未归因' : ''} +
+
+ + {/* 选中段血缘下钻:事件实例 → L1 原始日志行号(断言①) */} + } + right={sel ? ( + + {STATE_LABEL[sel.state]} + + ) : undefined} + note="每个数字都能从 detailRef 一路回溯到 L1 原始行号。原型无 oee_result_detail 表,用字符串句柄;生产改真外键(建议书 3.4.1)。" + > + {sel ? ( + <> + +
+ {selEvents.length > 0 ? ( + + + } maxHeight={220}> + {selEvents.map((e) => { + const def = EVENT_BY_CODE[e.defCode]; + return ( + + + + + + + ); + })} +
事件码事件名L1 行号原始时刻
{e.defCode}{def?.name ?? '(字典外)'}L{e.evidence.lineNo}{hhmmss(e.rawTime)}
+ ) : ( + + <>该段无成对事件证据({sel.state === 'IDLE' ? '未归因 IDLE:采到了但归不了因,进未归因池' : sel.state === 'UNKNOWN' ? '未采集窗口:日志断流,不计分母' : '由间隙填充/锚点推导'})。
不编造事件归属,血缘到此为数据缺口。 +
+ )} +
+ {sel.unknownPoolId && 未归因池 ID:{sel.unknownPoolId}(DQ-06 计算基础,须在录入台补录归因)。} + + ) : ( + 在上方甘特或状态段表点选一段,这里显示构成它的事件实例与 L1 原始日志行号。 + )} +
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/OeeTrend.tsx b/src/modules/tfamd-oee/components/workspace/OeeTrend.tsx new file mode 100644 index 0000000..cf2ca2a --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/OeeTrend.tsx @@ -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 ( +
+ } /> + + 逐业务日趋势仅对日志贯通的锚点单机出数。当前范围({scope.scopeLabel})未接入,不显示数字、也不显示 0。
+ {scope.gap ?? scope.coverageNote} +
+
+ ); + } + + 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 ( +
+ } + extra={{days.length} 个业务日 · 不补期} + /> + + = 0 ? '+' : ''}${momOee.toFixed(2)}pp`, sub: prev ? `较 ${labels[cursor - 1]}` : '首期无环比', color: momOee === null ? tokens.textMuted : momOee >= 0 ? tokens.success : tokens.danger, title: '两期 L3 实际 OEE 读数之差(比较量,非重算)' }, + ]} /> + +
+ } + right={单位 % · 游标 {labels[cursor]}} + note={`${PARAMS_SIGNOFF_NOTE}。实线为实际档逐日现算值;虚线参考线取当期理论/计划档。脏日不插值、不抹平。`} + > + +
+ {rateSeries.map((s) => ( + + {s.name} + + ))} +
+
+ + } + right={分母 PPT · 残差恒等} + note="每日 PPT = 有效生产 + Σ六桶 + 残差;残差 = 未归因 IDLE + 未计量的性能/工艺损失(P/Q 桶无源,不摊派)。脏日(2026-09-02)残差 > 0 触发 DQ-06,照实堆叠不归一化;RT=0 的日不按损失拆(否则整日余量会被误读为损失)。" + > + + +
+ + } + full + right={{days.length} 期 · 与 metric_trend.period 同值} + note={`${AXIS_SCOPE_NOTE} 回放轴只覆盖种子业务日(${days.map((d) => d.bizDate).join(' / ')}),不补期。DQ-06 阻断日结论暂缓发布,趋势仍照实出数供诊断。`} + > + + + + }> + {days.map((d, i) => ( + + + + + + + + + + + + ))} +
业务日OEEAPQPPT(h)残差未归因占比发布状态
{d.bizDate}{i === cursor ? ' · 游标' : ''}{pctUnitOrGap(d.tiers.actual.oee)}{pctUnitOrGap(d.tiers.actual.a)}{pctUnitOrGap(d.tiers.actual.p)}{pctUnitOrGap(d.tiers.actual.q)}{hrs(d.segments.totals.pptSec)}{dur(d.buckets.residualSec)} 0.05 ? tokens.danger : tokens.textSub}>{pct(d.buckets.unattributedPct)}% + {noRun(d) &&
无运行段
} + {d.dq.blocked + ? 结论暂缓发布 + : 可发布} +
+
+
+ ); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/charts.tsx b/src/modules/tfamd-oee/components/workspace/charts.tsx new file mode 100644 index 0000000..ad61095 --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/charts.tsx @@ -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 已被虚线占用,不能叠描线)。 + * 系列 的 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(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
; + } + 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 + 各系列数值和。变了→ 重挂载→描线重播;只换主题不重播 */ + const drawKey = `${labels.join('|')}#${series.map(s => s.values.reduce((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) => { + 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 ( +
setHover(null)} + > + + + + + + + + {ticks.map((tv, i) => ( + + + + {tv.toFixed(Math.abs(max - min) < 5 ? 2 : yDigits)} + + + ))} + {band?.map((b, i) => { + const top = Y(b.hi); + const bottom = Y(b.lo); + return ( + + + + + {b.label && {b.label}} + + ); + })} + {refs?.map((r, i) => ( + + + {r.label} + + ))} + {labels.map((l, i) => ( + (i % Math.ceil(n / 12) === 0 || i === n - 1) && ( + {l} + ) + ))} + + {series.map((s, si) => { + const runs = finiteRuns(s.values); + return ( + + {si === 0 && !s.dashed && runs.map((r, ri) => ( + + ))} + {runs.map((r, ri) => (s.dashed ? ( + + ) : ( + + )))} + {!s.dashed && ( + + {s.values.map((v, i) => ( + v != null && Number.isFinite(v) + ? + : null + ))} + + )} + + ); + })} + {marker !== null && marker >= 0 && series[0] && series[0].values[marker] != null + && Number.isFinite(series[0].values[marker]) && ( + + )} + + + {/* hover 准星(HTML 覆盖层):竖线 + 各系列圆点 + 读数气泡。pointerEvents:none 不挡交互 */} + {hover !== null && ( +
+
+ {series.map((s) => { + const v = s.values[hover]; + if (v == null || !Number.isFinite(v)) return null; + return ( +
+ ); + })} +
+
{labels[hover] ?? ''}
+ {series.map((s) => { + const v = s.values[hover]; + return ( +
+ + {s.name} + + {v != null && Number.isFinite(v) ? v.toFixed(2) : '—'} + +
+ ); + })} +
+
+ )} +
+ ); +} +/** 横向条形(结构拆解) */ +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 ( +
+ {items.map((it, idx) => ( +
+ {it.label} +
+
+
+ + {it.display ?? `${it.value.toFixed(1)}${valueSuffix}`} + {it.sub && {it.sub}} + +
+ ))} +
+ ); +} + +/** 纵轴取整: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 ( +
+ + {Array.from({ length: axis.divs + 1 }, (_, i) => i).map(i => { + const f = i / axis.divs; + return ( + + + + {fmtTick(axis.step * i)} + + + ); + })} + {labels.map((l, i) => ( + + {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 ( + + + {v.toFixed(1)} + + ); + })} + {l} + + ))} + +
+ {names.map((n, i) => ( + + {n}{unit ? `(${unit})` : ''} + + ))} +
+
+ ); +} + +/** 雷达图:八维健康度 */ +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 ( + + {[0.25, 0.5, 0.75, 1].map(f => ( + { 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 ( + + + C + 6 ? 'start' : outer.x < C - 6 ? 'end' : 'middle'} + >{label} + + ); + })} + {compare && } + + {values.map((v, i) => { const p = pt(i, v); return ; })} + + ); +} + +/** 风险矩阵散点 */ +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 ( + + + + + + + + {xLabel} + {yLabel} + {(() => { + /** + * 点可以压在一起,字不行。两步走:同格点(同次数×同严重度)先把圆点上下错开, + * 标签再各自做一轮避让——被推离本位的标签用一条细线连回自己的点。 + * 全是展示位移,不改源表读数;精确值看下方明细表。 + */ + 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(); + 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 ( + + {lifted && ( + + )} + + + {nd.it.label} + + + ); + }); + })()} + + ); +} + +/** + * 堆叠横向条:一个主体拆成若干分量(如一个结构特征里的四类缺陷率)。 + * 条长按各段数值直接累加,右侧给出合计读数,不做归一化——归一会把「谁更差」这层信息抹掉。 + */ +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 ( +
+
5 ? 'flex-start' : 'space-between' }}> + {items.map((it, idx) => { + const sum = it.segs.reduce((a, s) => a + segVal(s.value), 0); + return ( +
onClick?.(it.key)} + style={{ + display: 'flex', alignItems: 'center', gap: 8, animationDelay: `${idx * 40}ms`, + cursor: onClick ? 'pointer' : 'default', + }} + > + {it.label} +
+ {it.segs.map(s => ( + s.value != null && Number.isFinite(s.value) ? ( +
+ ) : null + ))} +
+ + {it.display ?? `${sum.toFixed(1)}${unit}`} + {it.sub && {it.sub}} + +
+ ); + })} +
+
+ {legend.map(([label, color]) => ( + + {label} + + ))} +
+
+ ); +} + +/** + * 环规(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 ( +
+ + + + = 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)} + + + {label && {label}} +
+ ); +} + diff --git a/src/modules/tfamd-oee/components/workspace/oeeUi.tsx b/src/modules/tfamd-oee/components/workspace/oeeUi.tsx new file mode 100644 index 0000000..34fc5ff --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/oeeUi.tsx @@ -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 = { + 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 = { + 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 = { + 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 ( + {children} + ); +} + +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 ( +
+
+ + {icon} + {title} + + {right} +
+ {/* minHeight:0 是红线「不溢出卡片底色」的 kit 级保证:缺它时 flex:1 的 min-height:auto + 会把内容高度顶穿卡片边框(内部 overflow:auto 的滚动块随之失效)。 */} +
{children}
+ {note &&
{note}
} +
+ ); +} + +export function Th({ children, right, minW, wrap }: { children: ReactNode; right?: boolean; minW?: number; wrap?: boolean }) { + const { tokens } = useTheme(); + return ( + {children} + ); +} + +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 ( + {children} + ); +} + +export function Table({ head, children, maxHeight }: { head: ReactNode; children: ReactNode; maxHeight?: number }) { + const { tokens } = useTheme(); + return ( +
+ + {head} + {children} +
+
+ ); +} + +/** 一行等分的统计砖(看板红线:等分、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 ( +
+ {items.map((it) => )} +
+ ); +} + +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 ( +
+
{it.label}
+ {it.ring && it.roll ? ( +
+ +
+ ) : ( +
{text}
+ )} + {it.sub &&
{it.sub}
} +
+ ); +} + +export function Note({ children }: { children: ReactNode }) { + const { tokens } = useTheme(); + return
{children}
; +} + +/** 数据缺口盒:标灰不标绿,四件披露齐备(缺什么/依赖谁/何时做实/为什么不能替代)。 */ +export function GapBox({ missing, dependsOn, stage, note }: { missing: string; dependsOn: string; stage: string; note: string }) { + const { tokens } = useTheme(); + return ( +
+
+ 数据缺口 + {missing} +
+
+ 依赖:{dependsOn}|做实:{stage} +
+
{note}
+
+ ); +} + +/** 诚实空态:未接入范围不显示 0(0 会被误读为"当天没有损失")。 */ +export function EmptyBox({ children }: { children: ReactNode }) { + const { tokens } = useTheme(); + return ( +
{children}
+ ); +} + +/** + * 页抬头:与顶栏同源的范围/口径/业务日标签(resolveScope),不另存一份。 + * 未接入范围把缺口写在脸上,绝不拿单机值冒充聚合值。 + */ +export function ScopeBar({ filter, title, icon, extra }: { + filter: OeeFilter; title: string; icon?: ReactNode; extra?: ReactNode; +}) { + const { tokens } = useTheme(); + const scope = resolveScope(filter); + return ( +
+ {icon} + {title} + {SIM_BADGE} + 业务日 {scope.bizDate} + + {scope.scopeLabel} + + {scope.shiftLabel && {scope.shiftLabel}} + + {extra} +
+ ); +} + +/** 两列等分网格(看板红线: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; \ No newline at end of file diff --git a/src/modules/tfamd-oee/components/workspace/views.tsx b/src/modules/tfamd-oee/components/workspace/views.tsx new file mode 100644 index 0000000..06a6ffa --- /dev/null +++ b/src/modules/tfamd-oee/components/workspace/views.tsx @@ -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; + 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 ; +} + +/* ══════════════════ 公共小块 ══════════════════ */ + +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 = { red: '红档', yellow: '黄档', green: '达标', na: '源表未设判定线' }; + +function StatusChip({ status }: { status: Status }) { + const { tokens } = useTheme(); + const c = statusColor(status, tokens); + return ( + {STATUS_LABEL[status]} + ); +} + +/** 源表快照标记:本页读数由数据集现算,与底部时间轴无关 */ +function SnapshotTag({ label = '源表现算快照' }: { label?: string }) { + const { tokens } = useTheme(); + return ( + {label} + ); +} + +export function Card({ title, right, children, tone, full }: { + title: string; right?: ReactNode; children: ReactNode; tone?: string; full?: boolean; +}) { + const { tokens } = useTheme(); + return ( +
+
+ + {title} + + {right} +
+ {children} +
+ ); +} + +function Th({ children, right }: { children: ReactNode; right?: boolean }) { + const { tokens } = useTheme(); + return ( + {children} + ); +} + +function Td({ children, right, mono, color }: { children: ReactNode; right?: boolean; mono?: boolean; color?: string }) { + const { tokens } = useTheme(); + return ( + {children} + ); +} + +/** 一句口径说明,放在卡片底部,避免图上数字与原表口径各说各话 */ +function Note({ children }: { children: ReactNode }) { + const { tokens } = useTheme(); + return
{children}
; +} + +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 ( +
+ + + {table.columns.map(c => ( + + ))} + + + {rows.map((r, i) => { + const focused = !!table.focus && cellText(r[table.focus.column]) === table.focus.value; + return ( + + {table.columns.map(c => { + const raw = r[c]; + const numeric = typeof raw === 'number'; + return ( + + ); + })} + + ); + })} + +
+ {c} + {c.includes('现算') && ◆} +
+ {cellText(raw)} +
+ {table.rows.length > rows.length && ( + 共 {table.rows.length} 行,此处显示前 {rows.length} 行。 + )} +
+ ); +} + +/** 严重度 → 展示色(字典与检查表共用) */ +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 = { + 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 ( +
+ } + tone={tokens.accent} + > + + + 六轴=DS-09 六类结构特征的综合良率(100 − 四类缺陷率之和,现算);虚线=基准轴 {radar.baselineLabel}。 + 多边形越瘪的那一角就是当下最该防的结构。 + + + +
+ }> +
+ {tiles.map((tile, i) => { + const c = statusColor(tile.status, tokens); + return ( + + ); + })} +
+ + 八块读数随底部回放同轴:当期取源表快照,历史期由 2026-10 快照按统一质量曲线回推,切换时点可见缺陷率、良率、负荷与告警量的时空迁移。 + 每块读数各自回到自己的数据集;点任意一块 → 「指标明细」页签看判定线、口径与源表明细。 + +
+ + }> + {watch.map((a, i) => { + const c = levelColor(a.level); + return ( +
onOpen(KIND_TO_METRIC[a.kind])} + className="ghost-btn" + style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '4px 6px', borderRadius: 6, cursor: 'pointer' }} + > + + {alertKindLabel(a.kind)} + {a.title} + + {a.subject} · {a.action} + + + {a.metric.label} {a.metric.value} + + {a.owner || a.role} + {i === 0 && TOP} +
+ ); + })} + 队列按「先分档再分类型」排:滞留天数、偏移率、负荷率三个量纲不跨类型硬比,避免排出假次序。 +
+
+
+ ); +} + +/** 雷达:良率刻度从 60% 起才看得出差异,直接 0 起会让六边形糊成一团 */ +function RadarBlock({ radar, onOpen }: { radar: ReturnType; 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 ( +
+ +
+ + 六类特征综合良率 + + + 基准平板拼焊 + +
+
+ {radar.axes.map((axis, i) => ( + + ))} +
+ 刻度自 {min}% 起放大差异;点任一轴签看该特征的四类缺陷拆分与样本数。 +
+ ); +} + +/* ══════════════════ 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 ( +
+ {main && ( + }> + +
+ + 状态「{main.latestStatus}」· 处理动作「{main.latestAction}」 + +
+ + {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)}%`}。 + +
+ )} + +
+ {main && ( + }> + +
+ 功率 −{Math.abs(main.values[0] - main.values[main.values.length - 1]).toFixed(1)}W 的同时缺陷率 {main.defects[0]}% → {main.defects[main.defects.length - 1]}%; + 两条序列的皮尔逊相关系数 {trend.corr ?? '—'} +
+ 相关系数为负即「功率越低、缺陷越多」,这条曲线是把参数漂移翻译成质量后果的那一环。 +
+ )} + + + 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} 条`, + }))} + /> +
+ {singles.map(s => ( +
+ + {s.device} {s.param} + {s.values[0]}{s.unit} + /标准 {s.stdText}{/^-?\d/.test(s.stdText) ? s.unit : ''} + {s.latestStatus} +
+ ))} +
+ {trend.sequenceCount} 条参数配到多日监控,其余 {singles.length} 条为单日快照;单日快照不构成趋势,列在下方明细表里。 +
+
+ + 偏移率现算 · 明细为源表 2026-10 当期}> + + +
+ ); +} + +/* ══════════════════ 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 ( +
+ } + > + ({ + 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)} + /> + + {period === CURRENT_PERIOD ? '' : `${periodLabel(period)} 回放:四类缺陷率按统一质量曲线回推,条长仍由四段累加。`} + 全厂样本加权综合不良率 {overallDefectRateAt(period, feats).toFixed(1)}%; + 基准平板拼焊 {feats.find(f => /基准/.test(f.conclusion))?.defect.toFixed(1) ?? '—'}% 是这六类里最稳的一档。 + 点任意一条 → 该结构的明细与结论。 + + + + {/* Pareto 独占左列;右侧两张小卡上下堆叠,并把图表各拉高一点补齐到 Pareto 的高度 */} +
+
+ }> + ({ + label: d.name, + value: d.share, + color: severityColor(d.severity, tokens), + display: `${d.share.toFixed(1)}%`, + sub: `累计${d.cum.toFixed(0)}%`, + }))} + /> +
+ {sev.map(s => ( + + ))} +
+ 占比取原表「近3月占比」列(比率 ×100),合计为字典内 11 个缺陷码之和,不是全数;累计列按降序现算。点档位药签看该档最高频缺陷码的明细。 +
+
+ +
+ + ({ + label: p.label, value: p.share, color: tokens.accent, + display: `${p.share.toFixed(1)}%`, sub: `${p.codes} 个码`, + }))} + /> + 同一本字典按「所属工序」汇总,看得出不合格集中在哪一段工艺:焊接段码数最多。 + + + 重复拦截命中 {dup.length}/6}> + ({ + label: g.label, value: g.n, + color: i === 0 ? tokens.danger : tokens.accent, + display: `${g.n} 件`, sub: g.items.join(' '), + }))} + /> + + 拦截口径:相似度 > 0.85 判为重复问题(原表列值)。命中 {dup.length} 件里最高 {dup[0].相似度}({dup[0]['8D编号']}), + 说明根因没有沉淀成标准,同一类问题在不同客户重复开单。 + + +
+
+ + }> +
+
+ ({ + 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} 水平`, + }))} + /> + 极差=该因子各水平均值良率的最高 − 最低,就是它对良率的动因强度;红色是最强那根。 +
+
+ + {[0, 1, 2].map(i => )} + + {factors.map((f, i) => { + const best = f.levels.reduce((bi, l, li) => (l.meanYield > f.levels[bi].meanYield ? li : bi), 0); + return ( + + + {f.levels.map(l => )} + {f.levels.length < 3 && [0, 1, 2].slice(f.levels.length).map(k => )} + + + + ); + })} + +
因子水平{i + 1}极差(pt)推荐
{f.label}{l.meanYield.toFixed(1)}—{f.spread.toFixed(2)}{f.levels[best].level}{f.unit}
+ + 三水平均值良率同表对照;最优组合落在试验 {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.试验号} 的参数窗口内即可,不必为它另开一轮。 + +
+ +
+
+
+
+
+ ); +} + +/* ══════════════════ 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 ( +
+ }> + ({ + label: l.label, + value: l.load, + color: statusColor(l.status, tokens), + display: `${l.load.toFixed(1)}%`, + sub: `WIP ${l.wip.toLocaleString('en-US')}`, + }))} + /> +
+ {lines.map(l => ( + + ))} +
+ + 负荷率 = 需求节拍 ÷ 实际产能(现算)。需求节拍按订单口径折到班次: + 月需求 {QAP_CALIBER.monthlyDemand.toLocaleString('en-US')} 件 ÷({QAP_CALIBER.workDays} 工作日 × {QAP_CALIBER.shifts} 班), + 当前有 {lines.filter(l => l.load > 100).length} 道工序 >100%;档位沿用原表「预警」列(最大瓶颈/严重瓶颈红,超负荷黄)。 + {period === CURRENT_PERIOD ? '' : ` 当前为 ${periodLabel(period)} 回放:负荷按年末放行的季节曲线回推。`} + +
+ + {/* 两栏各自纵向堆叠,而不是按行对齐: + 按行放时 DS-02 比 DS-10 矮 300px,左列会空出一大块; + 改成一列「DS-02 + DS-01」对一列「DS-10」,卡片间距仍然一致,但不再留洞。 */} +
+
+ }> + s.process)} + groups={[stations.map(s => s.rate)]} + colors={[tokens.accent]} + names={['产能达成率(班次产能 ÷ 理论产能,现算)']} + /> +
+ {stations.map(s => ( + + ))} +
+ + 理论产能 = 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)}%)排为最大瓶颈——前者看单件耗时,后者看需求÷实际产能,两列各按源表原话显示。 + +
+ + + ({ + label: `${m.label}(${m.items} 料号)`, + value: m.annual, + color: tokens.accent, + display: m.annual.toLocaleString('en-US'), + sub: `${m.welded} 涉焊`, + }))} + /> + {/* 左列比右列矮一截,把留白换成四个源表读数:既能补齐高度,也把「共几个料号/机型」从文字里提出来 */} +
+ {([ + ['机型', `${master.models} 个`], + ['料号', `${master.items} 个`], + ['年用量', `${master.annual.toLocaleString('en-US')} 件`], + ['涉焊料号', `${master.welded} 个`], + ] as const).map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+ + 条长=年用量,右侧标该机型里涉焊接的料号数——特征码(材质 × 结构特征 × 工艺方法)就挂在这张表上。 + +
+
+ +
+ }> + + + + 同料号 SRV2U-FANW-01、同批次板材对照;原表结论:设备化把一次良率抬 14~20pt(68.5 → 88.9%), + 返修/补焊工时从 3.2 压到 0.6 min/件,换型时间反而从 5 涨到 15 min——柔性是小批量手工的强项,这张表也照着原表列全了代价。 + + +
+
+
+ ); +} + +/* ══════════════════ 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 ( +
+ }> + + + 横轴直接取原表「历史发生次数」,纵轴用严重度做展示映射(致命 0.9/严重 0.6/一般 0.3)—— + 这是坐标摆放,不是源表判定线。右上=高频且致命,是最该先补标准的那格。 + 同严重度的几点会挤在同一横线上,图里只把它们上下错开、标签让位,次数与严重度的读数以下方明细为准。 + + + + }> + 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, + }))} + /> + + 滞留天数 = 回放基准日 {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)} 天(已闭环那单不计入)。 + + + + + + 相似度按材质 × 板厚 × 结构特征 × 焊接方式加权;标「无相似件」的行就是模型盲区——高亮那行没有可比历史,预测区间为空,只能靠首件验证补。 + + + }> +
+
+
+ {cov.rate} + % 覆盖率 +
+
+
+
+
+ {cov.pending.map(p => ( + + ))} +
+
+ +
+ + 状态=「待 QE 确认」即标准缺口(原表口径),确认后转「已覆盖」;AI 提示直接引用相似件历史 8D,把 QE 段最依赖个人经验的那一步补上。 + {period === CURRENT_PERIOD ? '' : ` ${periodLabel(period)} 回放:缺口数以源表待确认项为基数按质量曲线回推,下列明细仍为 2026-10 当期。`} + + + + + + +
+ ); +} + +/* ══════════════════ 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 ( +
+ {/* 指标脊导航:四组读数横排,点一个换主体 */} +
+ {groups.map(g => ( +
+ {g} +
+ {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 ( + + ); + })} +
+
+ ))} +
+ + {/* Hero + 判定 */} +
+
+
{m.name}
+
+ + {m.value || '—'} + + {m.unit} +
+
+ + {m.code} + {m.ds} {m.dsName} + {period !== CURRENT_PERIOD && } +
+
+ +
+
+
读数
+
{m.reading}
+
+
+
判定依据
+
{m.rule}
+
+
+
+ + {/* 元信息 */} +
+ {[ + ['归属分组', m.group], + ['责任角色', m.role], + ['计算式', m.formula], + ['数据集口径', m.caliber], + ].map(([k, v]) => ( +
+
{k}
+
{v}
+
+ ))} +
+ + 带 ◆ 的列是现算,不在原表里}> + + + + +
+ {METRICS.filter(x => x.group === m.group && x.code !== m.code).map(x => { + const xm = metricAt(x.code, period) ?? x; + return ( + + ); + })} +
+ 全部读数只出自这本 Excel 的 16 个数据集;比率类字段按原表存小数、页面 ×100 展示,计算列一律现算。 + {period === CURRENT_PERIOD ? '' : ` ${REPLAY_DETAIL_NOTE}`} + +
+
+ ); +} + +/* 局部小工具 */ +function numCell(v: unknown): number { + const n = Number(v); + return Number.isFinite(n) ? n : 0; +} diff --git a/src/modules/tfamd-oee/context/ThemeContext.tsx b/src/modules/tfamd-oee/context/ThemeContext.tsx new file mode 100644 index 0000000..8263187 --- /dev/null +++ b/src/modules/tfamd-oee/context/ThemeContext.tsx @@ -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({ + theme: 'light', + tokens: lightTokens, + toggleTheme: () => {}, +}); + +export function ThemeProvider({ children }: { children: ReactNode }) { + const [theme, setTheme] = useState(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 ( + +
+ {children} +
+
+ ); +} + +export function useTheme() { + return useContext(ThemeContext); +} diff --git a/src/modules/tfamd-oee/data/featureTree.ts b/src/modules/tfamd-oee/data/featureTree.ts new file mode 100644 index 0000000..8ab59fa --- /dev/null +++ b/src/modules/tfamd-oee/data/featureTree.ts @@ -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; + /** DS 对象/实例 → 方法节点(可能多个方法指向同一实例) */ + refIndex: Map; +} + +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[]).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[]).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(); + const refIndex = new Map(); + 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(); + 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) ?? []; +}; diff --git a/src/modules/tfamd-oee/data/ibp/customers.json b/src/modules/tfamd-oee/data/ibp/customers.json new file mode 100644 index 0000000..705e7a0 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/customers.json @@ -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 + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/index.ts b/src/modules/tfamd-oee/data/ibp/index.ts new file mode 100644 index 0000000..7230242 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/index.ts @@ -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(); + workOrderMaterials.forEach(m => + demand.set(m.材料编码, (demand.get(m.材料编码) ?? 0) + m.应领数量)); + const supplied = new Map(); + 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.缺口); +} diff --git a/src/modules/tfamd-oee/data/ibp/items.json b/src/modules/tfamd-oee/data/ibp/items.json new file mode 100644 index 0000000..c6cbfd1 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/items.json @@ -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, + "数据来源": "销售订单/生产工单" + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/production_orders.json b/src/modules/tfamd-oee/data/ibp/production_orders.json new file mode 100644 index 0000000..a8624c2 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/production_orders.json @@ -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", + "单据状态": "已完工" + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/purchase_orders.json b/src/modules/tfamd-oee/data/ibp/purchase_orders.json new file mode 100644 index 0000000..e14c914 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/purchase_orders.json @@ -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", + "订单状态": "生效", + "来源单据": "请购单" + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/sales_orders.json b/src/modules/tfamd-oee/data/ibp/sales_orders.json new file mode 100644 index 0000000..7ee8b96 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/sales_orders.json @@ -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事业部成品仓", + "制单人": "王晓静", + "单据状态": "生效" + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/suppliers.json b/src/modules/tfamd-oee/data/ibp/suppliers.json new file mode 100644 index 0000000..0ad4021 --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/suppliers.json @@ -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 + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ibp/work_order_materials.json b/src/modules/tfamd-oee/data/ibp/work_order_materials.json new file mode 100644 index 0000000..3b5ca6f --- /dev/null +++ b/src/modules/tfamd-oee/data/ibp/work_order_materials.json @@ -0,0 +1,1073 @@ +[ + { + "序号": 1, + "工单号": "WO-L20261012621", + "来源销售订单号": "L20261012621", + "产品编码": "GJQ6001", + "材料编码": "FFJLY026", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 2.9762, + "损耗率": null, + "应领数量": 29999.995, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 2, + "工单号": "WO-L20261012621", + "来源销售订单号": "L20261012621", + "产品编码": "GJQ6001", + "材料编码": "GJQ6001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1, + "损耗率": null, + "应领数量": 10080, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 3, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA284", + "规格型号": "10*8*3.5cm", + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 2, + "损耗率": 0, + "应领数量": 20160, + "预出仓库": "外购半成品仓", + "材料来源": "BOM展开", + "BOM版本": "v1.0", + "子件BOM": null + }, + { + "序号": 4, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA285", + "规格型号": "10*8*3.5cm", + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 2, + "损耗率": 0, + "应领数量": 20160, + "预出仓库": "外购半成品仓", + "材料来源": "BOM展开", + "BOM版本": "v1.0", + "子件BOM": null + }, + { + "序号": 5, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA296", + "规格型号": "10*8*3.5cm", + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 2, + "损耗率": 0, + "应领数量": 20160, + "预出仓库": "外购半成品仓", + "材料来源": "BOM展开", + "BOM版本": "v1.0", + "子件BOM": null + }, + { + "序号": 6, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "FASJ052", + "规格型号": "50*45*32.5", + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 0.0278, + "损耗率": 0, + "应领数量": 280.002, + "预出仓库": "辅料仓", + "材料来源": "BOM展开", + "BOM版本": "v1.0", + "子件BOM": null + }, + { + "序号": 7, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "FFSJ022", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1, + "损耗率": 0, + "应领数量": 10080, + "预出仓库": "辅料仓", + "材料来源": "BOM展开", + "BOM版本": "v1.0", + "子件BOM": null + }, + { + "序号": 8, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA284", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1.9306, + "损耗率": null, + "应领数量": 19460.004, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 9, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA285", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1.9702, + "损耗率": null, + "应领数量": 19859.999, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 10, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "BA296", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1.9702, + "损耗率": null, + "应领数量": 19859.999, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 11, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "FASJ052", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 0.0278, + "损耗率": null, + "应领数量": 280.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 12, + "工单号": "WO-L20261014630", + "来源销售订单号": "L20261014630", + "产品编码": "SJ-LBT-5898", + "材料编码": "FFSJ022", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1, + "损耗率": null, + "应领数量": 10080, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 13, + "工单号": "WO-L20261014631", + "来源销售订单号": "L20261014631", + "产品编码": "SJ-LBT-5911", + "材料编码": "BN001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 0.9712, + "损耗率": null, + "应领数量": 9789.998, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 14, + "工单号": "WO-L20261014631", + "来源销售订单号": "L20261014631", + "产品编码": "SJ-LBT-5911", + "材料编码": "BN002", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1, + "损耗率": null, + "应领数量": 10080, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 15, + "工单号": "WO-L20261014631", + "来源销售订单号": "L20261014631", + "产品编码": "SJ-LBT-5911", + "材料编码": "FASJ056", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 0.0278, + "损耗率": null, + "应领数量": 280.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 16, + "工单号": "WO-L20261014631", + "来源销售订单号": "L20261014631", + "产品编码": "SJ-LBT-5911", + "材料编码": "FFSJ023", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 10080, + "单位用量": 1, + "损耗率": null, + "应领数量": 10080, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 17, + "工单号": "WO-L20261014634", + "来源销售订单号": "L20261014634", + "产品编码": "GJQ5001", + "材料编码": "FFJLY022", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 19980, + "单位用量": 1, + "损耗率": null, + "应领数量": 19980, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 18, + "工单号": "WO-L20261014634", + "来源销售订单号": "L20261014634", + "产品编码": "GJQ5001", + "材料编码": "GJQ5001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 19980, + "单位用量": 1, + "损耗率": null, + "应领数量": 19980, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 19, + "工单号": "WO-L20261014635", + "来源销售订单号": "L20261014635", + "产品编码": "JDJZ-0987", + "材料编码": "FAJZ0005", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 0.05, + "损耗率": null, + "应领数量": 250, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 20, + "工单号": "WO-L20261014635", + "来源销售订单号": "L20261014635", + "产品编码": "JDJZ-0987", + "材料编码": "FBBXD007", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 1, + "损耗率": null, + "应领数量": 5000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 21, + "工单号": "WO-L20261014635", + "来源销售订单号": "L20261014635", + "产品编码": "JDJZ-0987", + "材料编码": "FEJZ005", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 1, + "损耗率": null, + "应领数量": 5000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 22, + "工单号": "WO-L20261014635", + "来源销售订单号": "L20261014635", + "产品编码": "JDJZ-0987", + "材料编码": "FHCJZ001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 2, + "损耗率": null, + "应领数量": 10000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 23, + "工单号": "WO-L20261014635", + "来源销售订单号": "L20261014635", + "产品编码": "JDJZ-0987", + "材料编码": "FMD019", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 1, + "损耗率": null, + "应领数量": 5000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 24, + "工单号": "WO-L20261015637", + "来源销售订单号": "L20261015637", + "产品编码": "XTL-0109", + "材料编码": "BA028", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 4, + "损耗率": null, + "应领数量": 19200, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 25, + "工单号": "WO-L20261015637", + "来源销售订单号": "L20261015637", + "产品编码": "XTL-0109", + "材料编码": "FASTN001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.0833, + "损耗率": null, + "应领数量": 399.998, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 26, + "工单号": "WO-L20261015637", + "来源销售订单号": "L20261015637", + "产品编码": "XTL-0109", + "材料编码": "FHSTN001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.1667, + "损耗率": null, + "应领数量": 800.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 27, + "工单号": "WO-L20261015637", + "来源销售订单号": "L20261015637", + "产品编码": "XTL-0109", + "材料编码": "FHSTN002", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.1667, + "损耗率": null, + "应领数量": 800.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 28, + "工单号": "WO-L20261015638", + "来源销售订单号": "L20261015638", + "产品编码": "XTL-0110", + "材料编码": "BD006", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 7200, + "单位用量": 1, + "损耗率": null, + "应领数量": 7200, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 29, + "工单号": "WO-L20261015638", + "来源销售订单号": "L20261015638", + "产品编码": "XTL-0110", + "材料编码": "FASTN002", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 7200, + "单位用量": 0.0417, + "损耗率": null, + "应领数量": 300.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 30, + "工单号": "WO-L20261015638", + "来源销售订单号": "L20261015638", + "产品编码": "XTL-0110", + "材料编码": "FHSTN003", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 7200, + "单位用量": 0.0833, + "损耗率": null, + "应领数量": 599.998, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 31, + "工单号": "WO-L20261015638", + "来源销售订单号": "L20261015638", + "产品编码": "XTL-0110", + "材料编码": "FHSTN004", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 7200, + "单位用量": 0.0833, + "损耗率": null, + "应领数量": 599.998, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 32, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "BZA25090-1", + "规格型号": null, + "计量单位": "KG", + "工单数量": 4504, + "单位用量": 0.1145, + "损耗率": 0.0198, + "应领数量": 525.781, + "预出仓库": "车间现场仓", + "材料来源": "BOM展开", + "BOM版本": "V1.0", + "子件BOM": "V1.0" + }, + { + "序号": 33, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "FAXTL022", + "规格型号": "31*25.5*27", + "计量单位": "PCS", + "工单数量": 4504, + "单位用量": 0.0333, + "损耗率": 0, + "应领数量": 150.132, + "预出仓库": "辅料仓", + "材料来源": "BOM展开", + "BOM版本": "V1.0", + "子件BOM": null + }, + { + "序号": 34, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "FBBXM029", + "规格型号": "35*25.3cm", + "计量单位": "PCS", + "工单数量": 4504, + "单位用量": 1, + "损耗率": 0, + "应领数量": 4504, + "预出仓库": "辅料仓", + "材料来源": "BOM展开", + "BOM版本": "V1.0", + "子件BOM": null + }, + { + "序号": 35, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "FEXTL012", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4504, + "单位用量": 1, + "损耗率": 0, + "应领数量": 4504, + "预出仓库": "辅料仓", + "材料来源": "BOM展开", + "BOM版本": "V1.0", + "子件BOM": null + }, + { + "序号": 36, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "FAXTL022", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4504, + "单位用量": 0.0333, + "损耗率": null, + "应领数量": 150.001, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 37, + "工单号": "WO-W20260629448", + "来源销售订单号": "W20260629448", + "产品编码": "LSMM031", + "材料编码": "FBBXM029", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4504, + "单位用量": 0.222, + "损耗率": null, + "应领数量": 1000.001, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 38, + "工单号": "WO-W202610131016", + "来源销售订单号": "W202610131016", + "产品编码": "XJB-9749", + "材料编码": "FAZSM011", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 20010, + "单位用量": 0.0333, + "损耗率": null, + "应领数量": 666.993, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 39, + "工单号": "WO-W202610131016", + "来源销售订单号": "W202610131016", + "产品编码": "XJB-9749", + "材料编码": "FFZSM004", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 20010, + "单位用量": 1, + "损耗率": null, + "应领数量": 20010, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 40, + "工单号": "WO-W202610131017", + "来源销售订单号": "W202610131017", + "产品编码": "XJB-9734", + "材料编码": "FAZSM007", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 9990, + "单位用量": 0.0333, + "损耗率": null, + "应领数量": 332.997, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 41, + "工单号": "WO-W202610131017", + "来源销售订单号": "W202610131017", + "产品编码": "XJB-9734", + "材料编码": "FFZSM001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 9990, + "单位用量": 1, + "损耗率": null, + "应领数量": 9990, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 42, + "工单号": "WO-W202610131017", + "来源销售订单号": "W202610131017", + "产品编码": "XJB-9734", + "材料编码": "FMD007", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 9990, + "单位用量": 3, + "损耗率": null, + "应领数量": 29970, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 43, + "工单号": "WO-W202610131020", + "来源销售订单号": "W202610131020", + "产品编码": "LHGB006", + "材料编码": "FASJLH024", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.0417, + "损耗率": null, + "应领数量": 200.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 44, + "工单号": "WO-W202610131020", + "来源销售订单号": "W202610131020", + "产品编码": "LHGB006", + "材料编码": "FESJLH023", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 1, + "损耗率": null, + "应领数量": 4800, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 45, + "工单号": "WO-W202610131020", + "来源销售订单号": "W202610131020", + "产品编码": "LHGB006", + "材料编码": "FHBSJLH024", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.0833, + "损耗率": null, + "应领数量": 399.998, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 46, + "工单号": "WO-W202610141021", + "来源销售订单号": "W202610141021", + "产品编码": "FP-LJD-2", + "材料编码": "FAFP011", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 24000, + "单位用量": 0.0333, + "损耗率": null, + "应领数量": 799.992, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 47, + "工单号": "WO-W202610141021", + "来源销售订单号": "W202610141021", + "产品编码": "FP-LJD-2", + "材料编码": "FEDRF015", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 24000, + "单位用量": 0.875, + "损耗率": null, + "应领数量": 21000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 48, + "工单号": "WO-W202610161036", + "来源销售订单号": "W202610161036", + "产品编码": "GSL023-M1", + "材料编码": "BJ040", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 2690, + "单位用量": 1, + "损耗率": null, + "应领数量": 2690, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 49, + "工单号": "WO-W202610161036", + "来源销售订单号": "W202610161036", + "产品编码": "GSL023-M1", + "材料编码": "FANBLA057", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 2690, + "单位用量": 0.0208, + "损耗率": null, + "应领数量": 56, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 50, + "工单号": "WO-W202610161037", + "来源销售订单号": "W202610161037", + "产品编码": "GSH007-C-029KC", + "材料编码": "FANBLA011", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 2880, + "单位用量": 0.0208, + "损耗率": null, + "应领数量": 59.999, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 51, + "工单号": "WO-W202610161037", + "来源销售订单号": "W202610161037", + "产品编码": "GSH007-C-029KC", + "材料编码": "FANBLA012", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 2880, + "单位用量": 0.0069, + "损耗率": null, + "应领数量": 19.999, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 52, + "工单号": "WO-WC20261013060", + "来源销售订单号": "WC20261013060", + "产品编码": "LHGB008", + "材料编码": "FASJLH026", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 0.0417, + "损耗率": null, + "应领数量": 200.002, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 53, + "工单号": "WO-WC20261013060", + "来源销售订单号": "WC20261013060", + "产品编码": "LHGB008", + "材料编码": "FESJLH025", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 1, + "损耗率": null, + "应领数量": 4800, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 54, + "工单号": "WO-WC20261013060", + "来源销售订单号": "WC20261013060", + "产品编码": "LHGB008", + "材料编码": "LHGB008", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 4800, + "单位用量": 1, + "损耗率": null, + "应领数量": 4800, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 55, + "工单号": "WO-Z20261012490", + "来源销售订单号": "Z20261012490", + "产品编码": "BJ-5341", + "材料编码": "BKC026", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 3600, + "单位用量": 1, + "损耗率": null, + "应领数量": 3600, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 56, + "工单号": "WO-Z20261012490", + "来源销售订单号": "Z20261012490", + "产品编码": "BJ-5341", + "材料编码": "BKC027", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 3600, + "单位用量": 1, + "损耗率": null, + "应领数量": 3600, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 57, + "工单号": "WO-Z20261012490", + "来源销售订单号": "Z20261012490", + "产品编码": "BJ-5341", + "材料编码": "BKC028", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 3600, + "单位用量": 1, + "损耗率": null, + "应领数量": 3600, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 58, + "工单号": "WO-Z20261012490", + "来源销售订单号": "Z20261012490", + "产品编码": "BJ-5341", + "材料编码": "FABJ008", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 3600, + "单位用量": 0.0333, + "损耗率": null, + "应领数量": 119.999, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 59, + "工单号": "WO-Z20261013492", + "来源销售订单号": "Z20261013492", + "产品编码": "BG-001", + "材料编码": "BA380", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 2, + "损耗率": null, + "应领数量": 10000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 60, + "工单号": "WO-Z20261013492", + "来源销售订单号": "Z20261013492", + "产品编码": "BG-001", + "材料编码": "BDBG01", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 0.96, + "损耗率": null, + "应领数量": 4800, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 61, + "工单号": "WO-Z20261013492", + "来源销售订单号": "Z20261013492", + "产品编码": "BG-001", + "材料编码": "FABG001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 0.01, + "损耗率": null, + "应领数量": 50, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 62, + "工单号": "WO-Z20261013492", + "来源销售订单号": "Z20261013492", + "产品编码": "BG-001", + "材料编码": "FCBG001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 1, + "损耗率": null, + "应领数量": 5000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + }, + { + "序号": 63, + "工单号": "WO-Z20261013492", + "来源销售订单号": "Z20261013492", + "产品编码": "BG-001", + "材料编码": "FLBG001", + "规格型号": null, + "计量单位": "PCS", + "工单数量": 5000, + "单位用量": 1, + "损耗率": null, + "应领数量": 5000, + "预出仓库": "辅料仓", + "材料来源": "采购需求反推", + "BOM版本": "—", + "子件BOM": null + } +] \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/kbLinks.ts b/src/modules/tfamd-oee/data/kbLinks.ts new file mode 100644 index 0000000..5c5ad97 --- /dev/null +++ b/src/modules/tfamd-oee/data/kbLinks.ts @@ -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 = { + '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(); + 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; +}; diff --git a/src/modules/tfamd-oee/data/knowledge.ts b/src/modules/tfamd-oee/data/knowledge.ts new file mode 100644 index 0000000..7cc0920 --- /dev/null +++ b/src/modules/tfamd-oee/data/knowledge.ts @@ -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; + /** 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): KbChunk => ({ + id, text, cells, vector: vectorOf(`${id}|${Object.values(cells).join('|')}`), +}); + +/* 角色色:沿用本体层的品牌色族,四角色各一色,深浅主题下都可读 */ +export const ROLE_COLOR: Record = { + 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), +}); diff --git a/src/modules/tfamd-oee/data/methodImages.ts b/src/modules/tfamd-oee/data/methodImages.ts new file mode 100644 index 0000000..6be740a --- /dev/null +++ b/src/modules/tfamd-oee/data/methodImages.ts @@ -0,0 +1,31 @@ +/** + * 生产方法的实拍示意图:一张方法一张 4:3 缩略图,放在特征树叶子左侧。 + * 图片由 AI 生成、统一压到 320×240 的 JPG,放在 public/methods/ 下, + * 按方法 id 映射,避免在多个机型 / 工艺间重复打包同一张图。 + */ +const METHOD_IMAGE: Record = { + '数控冲孔': '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; +} diff --git a/src/modules/tfamd-oee/data/methodSummaries.ts b/src/modules/tfamd-oee/data/methodSummaries.ts new file mode 100644 index 0000000..ff36ee6 --- /dev/null +++ b/src/modules/tfamd-oee/data/methodSummaries.ts @@ -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 = { + 'NCT.手工倒角': { processId: 'NCT', methodId: '手工倒角' }, + 'NCT.孔位': { processId: 'NCT', methodId: '数控冲孔' }, + '折弯.回弹补偿': { processId: '折弯', methodId: '数控折弯' }, + '焊接.激光焊焊瘤': { processId: '焊接', methodId: '激光焊' }, + '焊接.焊接变形': { processId: '焊接', methodId: '机器人弧焊' }, + '表面处理.色差': { processId: '表面处理', methodId: '阳极氧化' }, +}; + +/** IE 切片没有「所属特征树」列,按场景关键词显式映射 */ +const IE_TARGET: Record = { + 'ie-1': { processId: '折弯', methodId: '数控折弯' }, + 'ie-2': { processId: '焊接', methodId: '激光焊' }, + 'ie-3': { processId: 'NCT', methodId: '手工倒角' }, + 'ie-4': { processId: '组装', methodId: '工装组装' }, +}; + +/** IE 切片的自然语言字段不是「问题 / 原因 / 对策」口径,这里按原文提炼 */ +const IE_ROWS: Record = { + '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 = { + 'me-1': '参数未标准化,换料依赖经验', + 'me-2': '后挡料定位漂移,未做回弹补偿', + 'me-3': '垫块磨损未按周期点检', + 'me-4': '转速与刀具状态未闭环控制', +}; + +const KB_MODEL = 'SRV-2U-620'; +const ROLE_ORDER: Record = { 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(); + 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]); +}; diff --git a/src/modules/tfamd-oee/data/oee/agents.ts b/src/modules/tfamd-oee/data/oee/agents.ts new file mode 100644 index 0000000..8ccdddb --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/agents.ts @@ -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', 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 = { 一期: 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, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/calibers28.ts b/src/modules/tfamd-oee/data/oee/calibers28.ts new file mode 100644 index 0000000..8951a08 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/calibers28.ts @@ -0,0 +1,116 @@ +/** + * 28 项口径配置与默认值 —— 逐条转录《OEE智能优化平台改造规划书-2026-10-25.md》附录 E〔方案〕。 + * + * 三条落地纪律(建议书 §7.2「未签字时仍可开工」+ 第9章第3项): + * 1. 口径工作坊本次不安排,因此 **signedOff 一律 false**,全站标「待 IE 签字」,不得假装已签字。 + * 2. P0 的 16 项在 UI 上标灰(待确认),P1/P2 标「默认值生效中」——灰不等于错,是"还没人签字"。 + * 3. 平台按默认值先行落地;参数确认后在配置中心切换并保留旧版本,不影响已采集的历史数据。 + * + * ⚠ 两个「优先级」概念不可混为一谈(规划书附录 E 明确澄清): + * - priority P0/P1/P2 = 影响「能不能算」(P0 16 项 / P1 11 项 / P2 1 项) + * - isSensitivityKey = 影响「算出来是多少」(4 项敏感性议题:Plan边界 / Occ判定 / Q定义 / FT的PM是否计入) + * 两者不是同一集合:C04/C10 标 P1,却分别影响 A 约 3.6pp、Q 约 2.08pp;C15 标 P0,却不改变 OEE 数值口径。 + */ +import type { CaliberConfig, CaliberItem } from '../../types/oee'; + +/** 口径版本号:全站唯一来源,四处读数(页面/报表/智能体/导出)都带它。 */ +export const CALIBER_VERSION = 'v0.1-demo'; + +/** 4 项敏感性议题 → 承载它的口径项。一个议题可由多项承载(Q 定义含 C03 与 C10)。 */ +export const SENSITIVITY_ISSUES = { + planBoundary: { label: 'Plan 边界', items: ['C09'] }, + occRule: { label: 'Occ 判定', items: ['C04'] }, + qDefinition: { label: 'Q 定义', items: ['C03', 'C10'] }, + ftPmIncluded: { label: 'FT 的 PM 是否计入', items: ['C06'] }, +} as const; + +const SENSITIVITY_IDS = new Set( + Object.values(SENSITIVITY_ISSUES).flatMap((v) => [...v.items]), +); + +/** 原始表的一行。owner 取归口第一顺位中能落进枚举的那个;完整归口原文保留在 note 里。 */ +type Row = { + id: `C${string}`; + name: string; + scope: string; // 影响范围(原文) + ownerRaw: string; // 归口(原文) + owner: CaliberItem['owner']; + defaultValue: string | number | boolean; + priority: CaliberItem['priority']; +}; + +const ROWS: Row[] = [ + { id:'C01', name:'头级 PAUSE 如何折算 Lane 级停机(SRF)', scope:'Down 归因与 A/P 拆分', ownerRaw:'IE + EQ', owner:'IE', defaultValue:'按全头同时暂停判定为 Lane 级停机', priority:'P0' }, + { id:'C02', name:'每日休息时点与是否全线停机', scope:'Cap 口径', ownerRaw:'生产 + IE', owner:'MFG', defaultValue:'按 12:00—13:00 全线停机计入计划损失', priority:'P1' }, + { id:'C03', name:'ASLT 的 Q 采用哪个口径(终测/FPY/UTT)', scope:'OEE 绝对值', ownerRaw:'IE + 质量', owner:'IE', defaultValue:'取终测合格率', priority:'P0' }, + { id:'C04', name:'ASLT 门开换盘是否计为在机', scope:'A 因子约 3.6pp', ownerRaw:'IE + 现场', owner:'IE', defaultValue:'不计入运行时间', priority:'P1' }, + { id:'C05', name:'ASLT 是否有标准节拍/UPH', scope:'P 的计算方式', ownerRaw:'IE + EQ', owner:'IE', defaultValue:'无标准节拍时按理论工时/实际工时计算', priority:'P1' }, + { id:'C06', name:'FT 的 PM 是否计入计划损失', scope:'A 的分母', ownerRaw:'IE', owner:'IE', defaultValue:'计入计划损失并从计划可用时间扣除', priority:'P0' }, + { id:'C07', name:'一级因子标准归属表', scope:'48 事件分类', ownerRaw:'IE', owner:'IE', defaultValue:'按方案映射表执行', priority:'P0' }, + { id:'C08', name:'Down/Jam 的时长阈值与去重主键', scope:'事件分类', ownerRaw:'EQ + IE', owner:'IE', defaultValue:'统一按 300 秒分界', priority:'P0' }, + { id:'C09', name:'计划与非计划待料的判定标志', scope:'因子归属', ownerRaw:'PC + MFG', owner:'PC', defaultValue:'命中 APS plan idle 计计划待料,其余计现场反馈待料', priority:'P0' }, + { id:'C10', name:'工程批是否从 OEE 分母剔除', scope:'Q 值约 2.08pp', ownerRaw:'IE + PE', owner:'IE', defaultValue:'剔除 ENG 开头的工程批次', priority:'P1' }, + { id:'C11', name:'Reflow 能否提供 SMEMA/PLC 过站信号', scope:'PM 结束时点(S-02)', ownerRaw:'IE + 设备', owner:'IE', defaultValue:'以现场确认前三盘进入 Reflow 的时刻为准', priority:'P0' }, + { id:'C12', name:'Xray 图片目录/接口开放范围与哪类图片作为 Setup 完成证据', scope:'Setup 判定点(S-15/16/18)', ownerRaw:'QA + Xray Owner', owner:'QA', defaultValue:'取炉后首张确认图的保存时刻', priority:'P0' }, + { id:'C13', name:'Down 权威时间取 MT2 还是设备日志,差异如何裁决', scope:'Down 时长', ownerRaw:'EQ + IE', owner:'IE', defaultValue:'取最早可信时间,差异超 5 分钟转人工复核', priority:'P0' }, + { id:'C14', name:'Jam 与 Down 的分界按单次事件还是累计时长', scope:'Jam/Down 归类', ownerRaw:'IE', owner:'IE', defaultValue:'按单次连续停机的持续时长判定', priority:'P0' }, + { id:'C15', name:'瓶颈站如何定义与维护,是否随产品变化', scope:'Down/Jam 取数范围', ownerRaw:'IE', owner:'IE', defaultValue:'主数据维护瓶颈站表,按产品路线分别配置', priority:'P0' }, + { id:'C16', name:'FT/ASLT 的 PM、Down、Jam、待料等因子事件定义补充', scope:'12 个因子的可核算性', ownerRaw:'IE + MFG', owner:'IE', defaultValue:'按附录 C 的 F/A 系列事件定义补齐', priority:'P0' }, + { id:'C17', name:'Lot Start Date(ASLT)语义是首颗测试还是 lot 装载', scope:'换 lot 时长口径', ownerRaw:'PE', owner:'PE', defaultValue:'取 lot 装载时间', priority:'P0' }, + { id:'C18', name:'Setup(MFG) 的 ±5 分钟偏移是否对所有产品一致', scope:'S-15/16/18', ownerRaw:'IE', owner:'IE', defaultValue:'先按全局 ±5 分钟,后续按产品可配置', priority:'P1' }, + { id:'C19', name:'换 sub/换电容的额外时长余量由谁维护', scope:'S-08/09', ownerRaw:'IE', owner:'IE', defaultValue:'由 IE 在配置中心按产品维护', priority:'P1' }, + { id:'C20', name:'SMR 借机的跨班顺延规则如何判定', scope:'S-10/11', ownerRaw:'SMR Leader + IE', owner:'IE', defaultValue:'顺延至下一班并按实际交付时刻记录', priority:'P1' }, + { id:'C21', name:'FT 最后一颗测试时间是否必须精确', scope:'F-47 口径', ownerRaw:'PE', owner:'PE', defaultValue:'可用 prod summary 打印时间等效', priority:'P1' }, + { id:'C22', name:'rescreen 按测试颗数 > lot 数还是多份 summary 判定', scope:'F-49/A-57', ownerRaw:'PE', owner:'PE', defaultValue:'以测试颗数 > lot 数为主判据', priority:'P1' }, + { id:'C23', name:'双口径并行的具体差异点与切换权', scope:'计算层设计', ownerRaw:'IE', owner:'IE', defaultValue:'默认口径为主线,切换由 IE 审批', priority:'P1' }, + { id:'C24', name:'跨天班次定义与业务日归属规则', scope:'全部时间切分', ownerRaw:'PC + MFG', owner:'PC', defaultValue:'跨天班次归属到事件开始时刻所在业务日', priority:'P0' }, + { id:'C25', name:'三色灯是否开放接入采集', scope:'Down 实时性', ownerRaw:'IE + 设备', owner:'IE', defaultValue:'不依赖三色灯,以设备日志与按灯信号为主路径', priority:'P1' }, + { id:'C26', name:'是否与现有 OEE 报表并行一段时间', scope:'上线策略', ownerRaw:'IE', owner:'IE', defaultValue:'并行一个自然月,差异超阈值逐日复核', priority:'P2' }, + { id:'C27', name:'三层 OEE 参数(设计良率/计划性能率/目标良率/每日不可避免停机)由谁定版、多久校准', scope:'理论/计划 OEE 可信度', ownerRaw:'IE + PE', owner:'IE', defaultValue:'由 IE 定版,每季度校准一次', priority:'P0' }, + { id:'C28', name:'计划 OEE 的计划损失取 APS 计划待料还是 IE 月度目标', scope:'计划 OEE 口径', ownerRaw:'PC + IE', owner:'PC', defaultValue:'采用 IE 的月度计划停机率目标', priority:'P0' }, +]; + +/** 28 项口径条目。signedOff 全 false —— 本次不安排口径工作坊,默认值生效但无人签字。 */ +export const CALIBER_ITEMS: Record = Object.fromEntries( + ROWS.map((r) => [ + r.id, + { + id: r.id, + name: r.name, + defaultValue: r.defaultValue, + priority: r.priority, + owner: r.owner, + isSensitivityKey: SENSITIVITY_IDS.has(r.id), + signedOff: false, + note: `影响范围:${r.scope}|归口:${r.ownerRaw}`, + } satisfies CaliberItem, + ]), +); + +/** 生效时间窗:原型演示期。切换任一项会生成新版本,旧版本结果保留可回放。 */ +export const CALIBER_CONFIG: CaliberConfig = { + version: CALIBER_VERSION, + items: CALIBER_ITEMS, + effectiveFrom: '2026-11-01', + sensitivitySnapshot: { + planBoundary: String(CALIBER_ITEMS.C09.defaultValue), + occRule: String(CALIBER_ITEMS.C04.defaultValue), + // Q 定义同时受 C03(终测/FPY/UTT)与 C10(工程批是否剔除)影响,两者都进快照。 + // 唯一推导入口是 lib/oee/caliber.ts 的 sensitivitySnapshotOf,此处字面量由校验脚本比对防漂移。 + qDefinition: [String(CALIBER_ITEMS.C03.defaultValue), String(CALIBER_ITEMS.C10.defaultValue)].join('|'), + ftPmIncluded: true, // C06 默认「计入计划损失并从计划可用时间扣除」 + }, +}; + +/** 供校验脚本与配置中心用的计数(现算,不写死)。 */ +export function caliberStats() { + const items = Object.values(CALIBER_ITEMS); + return { + total: items.length, + p0: items.filter((i) => i.priority === 'P0').length, + p1: items.filter((i) => i.priority === 'P1').length, + p2: items.filter((i) => i.priority === 'P2').length, + signed: items.filter((i) => i.signedOff).length, + sensitivityKeys: items.filter((i) => i.isSensitivityKey).length, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/dekCodes.ts b/src/modules/tfamd-oee/data/oee/dekCodes.ts new file mode 100644 index 0000000..b18259d --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/dekCodes.ts @@ -0,0 +1,69 @@ +/** + * DEK 印刷机事件码表(演示子集)。 + * + * ⚠⚠ 客户 96 事件码全表**未提供**。规划书/POC 只明确了两个码:31317 / 31318 = 改钟标记, + * 必须跳过不入事件表〔POC 附录 H〕。其余码是**演示占位映射**,接入前必须替换为客户全表。 + * 本文件存在的意义是让"日志→事件"这条链真的跑通,而不是假装知道客户的码表。 + * + * 映射纪律: + * 1. 只映射 DEK 自身日志能产出的事件。D 类(必须人工录入)事件**不在码表里**—— + * 例如 S-30/S-31 Jam 开始结束、S-15/S-16 Setup(MFG),它们走现场录入台, + * 把它们写成自动映射就是伪造采集能力。 + * 2. S-02(PM 结束)是 E 类「不适用」:其判定点是"前三 boat 进 reflow",属回流焊站信号, + * DEK 单机日志给不出,故不映射。这正是规划书说的"E 类事件走推导 + 录入台过渡"。 + * 3. 板级开始/完成不是 48 字典事件,映射到产出锚点伪码;开始行不计数。 + */ +import { OUTPUT_ANCHOR, OUTPUT_ANCHOR_START } from '../../lib/oee/adapterDek'; + +export interface DekCodeMeta { + code: string; + label: string; + /** 映射到 48 字典事件码,或产出锚点伪码 */ + target: string; + /** 该码在客户全表中的确认状态 */ + confirmed: 'POC' | 'DEMO'; + note: string; +} + +export const DEK_CODE_META: DekCodeMeta[] = [ + { code: '10101', label: '印刷开始', target: OUTPUT_ANCHOR_START, confirmed: 'DEMO', note: '板级窗口起点,不计数' }, + { code: '10102', label: '印刷完成', target: OUTPUT_ANCHOR, confirmed: 'DEMO', note: '板级产出锚点,params 带实测节拍与结果' }, + { code: '20101', label: 'Down 开始', target: 'S-27', confirmed: 'DEMO', note: 'C 类,按灯/口头/MT2 取最早可信时间' }, + { code: '20102', label: 'Down 结束', target: 'S-28', confirmed: 'DEMO', note: 'C 类,二级因子是「维修等待」,与开始端不同' }, + { code: '20103', label: 'Down 时长抓取', target: 'S-29', confirmed: 'DEMO', note: 'A 类 DERIVED,>5min 停机自含区间,DEK 最强信号' }, + { code: '20203', label: 'Jam 时长抓取', target: 'S-32', confirmed: 'DEMO', note: 'A 类 DERIVED,≤5min 短停自含区间' }, + { code: '30101', label: '关机开始', target: 'S-33', confirmed: 'DEMO', note: 'C 类,APS 关机时点 + OTA 最后 lot unload' }, + { code: '30102', label: '关机结束', target: 'S-34', confirmed: 'DEMO', note: 'C 类,APS 开线时点 + OTA 第一个 lot load' }, + { code: '30201', label: '计划待料开始(APS)', target: 'S-39', confirmed: 'DEMO', note: 'C 类,APS plan idle,精确到分钟' }, + { code: '30202', label: '计划待料结束(APS)', target: 'S-40', confirmed: 'DEMO', note: 'C 类,与起点成对' }, + { code: '30301', label: 'Conversion 开始', target: 'S-13', confirmed: 'DEMO', note: 'C 类,OTA 调 recipe + 设备 Log 换型开始' }, + { code: '30302', label: 'Conversion 结束', target: 'S-14', confirmed: 'DEMO', note: 'B 类,以 Setup 开始时间为结束判定点' }, + { code: '30401', label: 'Lot setup loss 开始', target: 'S-25', confirmed: 'DEMO', note: 'B 类,上个 lot 结束 + 隔板 + 1min 固定' }, + { code: '30402', label: 'Lot setup loss 结束', target: 'S-26', confirmed: 'DEMO', note: 'B 类,新 lot 开启 Datacon 的时间点' }, + { code: '31317', label: '改钟标记(前)', target: 'CLOCK_MARK', confirmed: 'POC', note: '★ 跳过,不入事件表〔POC〕' }, + { code: '31318', label: '改钟标记(后)', target: 'CLOCK_MARK', confirmed: 'POC', note: '★ 跳过,不入事件表;params.off 声明校正偏移' }, +]; + +/** 适配器注入用的码表。改钟标记不进表(由适配器 DEK_CLOCK_MARKS 单独处理)。 */ +export const DEK_CODE_MAP: Record = Object.fromEntries( + DEK_CODE_META.filter((m) => m.target !== 'CLOCK_MARK').map((m) => [m.code, m.target]), +); + +/** 客户已确认的码只有 2 个(31317/31318)。其余全是演示占位,主数据页必须显示这个比例。 */ +export function dekCodeStats() { + return { + total: DEK_CODE_META.length, + confirmed: DEK_CODE_META.filter((m) => m.confirmed === 'POC').length, + demo: DEK_CODE_META.filter((m) => m.confirmed === 'DEMO').length, + mapped: Object.keys(DEK_CODE_MAP).length, + clockMarks: DEK_CODE_META.filter((m) => m.target === 'CLOCK_MARK').length, + /** + * 客户实证码覆盖率 = POC 确认码 / 客户全表 96 码。 + * ★ 只有 31317/31318 两码来自 POC 实证,这才是真实接入进度(2.1%)。 + * 不得用演示子集规模冒充覆盖率——其余 14 码是演示编造,未必存在于客户码表。 + */ + coverageOf96: DEK_CODE_META.filter((m) => m.confirmed === 'POC').length / 96, + /** 演示子集规模占 96 码全表的比例(含编造码,仅说明演示体量,不是接入进度) */ + subsetOf96: DEK_CODE_META.length / 96, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/devices.ts b/src/modules/tfamd-oee/data/oee/devices.ts new file mode 100644 index 0000000..26e721e --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/devices.ts @@ -0,0 +1,497 @@ +/** + * 设备台账(17 台)+ 线体 + 班次。来源:规划书附录 D.1/D.2/D.3、4.6.1、7.3。 + * + * ★ 三条不可违反的台账纪律: + * 1. **沿用客户既有台账编码,不重新编号**(规划书 5.1)。已知真实编码只有 5 个: + * DCP005〔POC〕、93k178/93k250/93k287〔方案〕、suzamdaslt386〔POC〕。 + * 其余 12 台客户未给编码 → 用演示占位码并标 codeSource:'DEMO',接入前必须替换。 + * 占位码不是"假装知道",UI 与主数据页必须显示"待客户台账确认"。 + * 2. **ICT 无实测值就写 0 + 缺口说明,绝不编一个数**。回流焊/MBT/Xray/无日志三类的节拍 + * 规划书未给;FT 的 P 是「1 − 三项损失占比」不用 ICT;ASLT 按 C05「无标准节拍时 + * 按理论工时/实际工时计算」。这三类 ictSec=0 是**口径事实**,不是数据缺失。 + * 3. **间隙阈值按设备可配置,不是全局常量**(规划书 7.3)。kohyoung 必须 15min、 + * Jetting 必须 3min——这两台恰好都**不等于** max(5, 3×ICT/60) 的公式默认值, + * 正是台账值优先于公式的证据。校验脚本会逐台比对并断言这两处差异。 + * + * 本文件是**常量字典**,零 IO、不 import 引擎层,所有统计现算不写死。 + */ +import type { Device, RegionTemplate } from '../../types/oee'; + +/** 附录 D.1 能力矩阵的六个维度,☆=0 / ★=1 / ★★=2 / ★★★=3。未列入矩阵的设备为 null。 */ +export interface CapabilityStars { + cycle: number; // 节拍 + down: number; // Down + jam: number; // Jam + wait: number; // 待料 + setup: number; // 换型 + unit: number; // 单件级 +} + +/** ICT 取值来源。PENDING_IE = 规划书未给实测节拍,须 IE 提供后才能算 P。 */ +export type IctSource = 'POC' | 'DERIVED' | 'NOT_APPLICABLE' | 'PENDING_IE'; +/** 间隙阈值来源。DEFAULT = 规划书未单列,取 max(5, 3×ICT/60) 的公式默认值。 */ +export type GapSource = 'POC' | 'DEFAULT'; +/** 台账编码来源。DEMO = 客户未提供编码,演示占位,接入前须替换。 */ +export type CodeSource = 'POC' | '方案' | 'DEMO'; + +export interface DeviceMaster extends Device { + codeSource: CodeSource; + /** 该类型在客户现场的台数〔POC〕。"少量"/"1 类"未给具体数字时为 null。 */ + pocFleetCount: number | null; + capabilityStars: CapabilityStars | null; + /** 附录 D.1「总体评价」原文 */ + capabilityNote: string; + ictSource: IctSource; + ictNote: string; + gapSource: GapSource; + /** 附录 D.2 日志格式原文 */ + logFormat: string; + encoding: string; + /** 附录 D.2 时间轴重建策略原文 */ + rebuildStrategy: string; + /** 附录 D.3「解析要点(陷阱)」——原型必须复现,否则数字失真 */ + adapterTraps: string[]; + /** 是否参与 OEE 聚合。中间缓存不生产,只反推缓冲占用率,不计 OEE。 */ + countsForOee: boolean; + /** 规划书 1.1 主流程工位序号;未列入主流程的设备不给序号,不臆造拓扑。 */ + mainPathSeq?: number; + /** FUJI NXT 每台 2 Lane〔POC〕 */ + lanes?: string[]; + /** ASLT 12 Site 独立使能/禁用〔POC〕。使能窗口是时变的,由事件种子提供,不在此写死。 */ + siteCount?: number; + /** 演示讲解顺序中的角色(规划书附录 D.1 六台设备演完六类数据可得性场景) */ + demoRole: string; +} + +const SRF: RegionTemplate = 'SRF_BUFFER'; +const FT: RegionTemplate = 'FT_MULTIPLY'; +const ASLT: RegionTemplate = 'ASLT_EVENT'; + +/** 无日志三类的共同过渡方案:加装 IO 三色灯/光电,走 L1 级硬件信号。 */ +const NO_LOG_TRAPS = ['无日志输出,需加装 IO 三色灯/光电后才能采集', '过渡期靠人工录入,D 类事件超时触发 DQ-11']; + +const ROWS: DeviceMaster[] = [ + // ── SRF 13 类各 1 台(附录 D.2 的 13 行)────────────────────────────────── + { + id: 'DEK001', name: 'DEK 印刷机 01', region: 'SRF', type: 'DEK', lineId: 'SRF-L1', station: '印刷', + capability: 3, hasLog: true, gapThresholdMin: 5, ictSec: 28, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 6, + capabilityStars: { cycle: 3, down: 3, jam: 3, wait: 3, setup: 3, unit: 3 }, + capabilityNote: '最强(96 事件码状态机)', + ictSource: 'POC', ictNote: '28s/板〔POC〕附录 D 间隙阈值表', + gapSource: 'POC', + logFormat: '定宽 91 字符文本(EVENT.DAT)', encoding: 'ASCII', + rebuildStrategy: '设备原生状态机(最精确)', + adapterTraps: [ + '96 事件码构成原生状态机;改钟事件 31317/31318 跳过,不入事件表', + '一日发生 4 次时钟回跳〔POC〕→ DQ-01 自动修正 + 原始/校正双时间字段', + '定宽切列:日期[0:10] 时间[11:19] 事件码[20:25] 文本[26:71] 参数[71:91]', + ], + countsForOee: true, mainPathSeq: 10, + demoRole: '① 信号最全,做端到端锚点(日志→事件→状态段→六桶→OEE)', + }, + { + id: 'NXT001', name: 'FUJI NXT 贴装机 01', region: 'SRF', type: 'FUJI NXT', lineId: 'SRF-L1', station: '贴装', + capability: 2, hasLog: true, gapThresholdMin: 5, ictSec: 27, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 12, + capabilityStars: { cycle: 2, down: 2, jam: 2, wait: 2, setup: 1, unit: 1 }, + capabilityNote: '间接(需产品映射)', + ictSource: 'DERIVED', ictNote: 'POC 给区间 24~30s/板,取中值 27s;区间两端须 IE 定版后收窄', + gapSource: 'POC', + logFormat: 'SQLite(Dic1/*_L*.db)', encoding: '—', + rebuildStrategy: '生产节拍区间法', + adapterTraps: [ + 'Module=0 为汇总行,必须过滤,否则双倍计数', + '状态字段需产品映射才能归口', + '每台 2 Lane,Lane 维度不可合并', + '处理时钟回跳', + ], + countsForOee: true, mainPathSeq: 20, lanes: ['L1', 'L2'], + demoRole: '辅助:演示 Module=0 汇总行过滤与 Lane 维度', + }, + { + id: 'DCP005', name: 'Datacon 贴装机 05', region: 'SRF', type: 'Datacon', lineId: 'SRF-L1', station: '贴装', + capability: 2, hasLog: true, gapThresholdMin: 5, ictSec: 36, unit: 'TU', template: SRF, + codeSource: 'POC', pocFleetCount: 22, + capabilityStars: { cycle: 2, down: 2, jam: 1, wait: 1, setup: 1, unit: 2 }, + capabilityNote: 'Lot 字段为空', + ictSource: 'POC', ictNote: '36s/TU〔POC〕;亦为 SRF 缓冲解耦阈值 B≥25 单位的下游节拍', + gapSource: 'POC', + logFormat: '结构化日志(02_09.log)', encoding: 'UTF-8', + rebuildStrategy: '生产节拍区间法', + adapterTraps: [ + 'Lot 字段为空,归属由排产计划 + 时间窗口反推(五级级联归因的主战场)', + 'Cycle start/end 配对,Output report 去重', + '本机是 POC 改善标的:751min 缺失数据 + 124min 停机〔POC〕', + ], + countsForOee: true, mainPathSeq: 30, + demoRole: '④ Lot 为空,演示五级级联归因;也是优先处理清单第一名', + }, + { + id: 'DPVS001', name: 'DPVS 锡膏检测 01', region: 'SRF', type: 'DPVS', lineId: 'SRF-L1', station: '锡膏检测', + capability: 1, hasLog: true, gapThresholdMin: 5, ictSec: 46, unit: 'boat', template: SRF, + codeSource: 'DEMO', pocFleetCount: 11, + capabilityStars: { cycle: 2, down: 1, jam: 1, wait: 1, setup: 1, unit: 0 }, + capabilityNote: '仅 PLC 位信号', + ictSource: 'POC', ictNote: '46s/boat〔POC〕附录 D 间隙阈值表', + gapSource: 'POC', + logFormat: 'PLC 位信号', encoding: '—', + rebuildStrategy: '生产节拍区间法', + adapterTraps: ['仅 PLC 位,机器名与 lot 由 MES 侧关联补齐', 'boat 进/出、检验完成、Wait_boat 三类位信号'], + countsForOee: true, + demoRole: '辅助:演示位信号→事件的归一化与 MES 侧补齐', + }, + { + id: 'AOI001', name: 'kohyoung AOI 01', region: 'SRF', type: 'kohyoung AOI', lineId: 'SRF-L1', station: 'AOI 检测', + capability: 1, hasLog: true, gapThresholdMin: 15, ictSec: 360, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 22, + capabilityStars: { cycle: 1, down: 1, jam: 0, wait: 0, setup: 0, unit: 1 }, + capabilityNote: '仅报警码', + ictSource: 'POC', ictNote: '~6min/板 = 360s〔POC〕。节拍是分钟级,用 5min 阈值会把正常生产误判为停机', + gapSource: 'POC', + logFormat: '累积式日志', encoding: 'GB18030', + rebuildStrategy: '报警驱动', + adapterTraps: [ + '按增量偏移量去重(实测 9 个重复目录已收敛〔POC〕)', + '日志自 1 月未清理,累积式文件不按偏移去重会把历史报警重复计入当日', + 'GB18030 编码,解码失败触发 DQ-03', + '报警码 1204 = 前门;单板检验完成是唯一的产出锚点', + '★ 间隙阈值必须 15min,不是 5min——整份方案最有价值的单条工程经验', + ], + countsForOee: true, mainPathSeq: 50, + demoRole: '⑤ 仅报警码,演示「5min vs 15min 阈值误判」对比', + }, + { + id: 'RF001', name: '回流焊 01', region: 'SRF', type: '回流焊', lineId: 'SRF-L1', station: '回流焊', + capability: 1, hasLog: true, gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 16, + capabilityStars: { cycle: 0, down: 0, jam: 0, wait: 0, setup: 0, unit: 0 }, + capabilityNote: '最弱(无进出板信号)', + ictSource: 'PENDING_IE', ictNote: '无进出板信号,节拍无法实测;须由上下游工站事件配对推导后由 IE 确认', + gapSource: 'DEFAULT', + logFormat: 'UTF-16 文本(WCALARM)', encoding: 'UTF-16', + rebuildStrategy: '无法重建 → SRF 时间分配法按上下游节拍拆分', + adapterTraps: [ + '仅报警/配置/状态行,无进出板信号', + '进出板与节拍由上下游工站事件配对推导', + 'E 类事件(S-02 PM 结束)不适用,走录入台过渡', + ], + countsForOee: true, mainPathSeq: 40, + demoRole: '⑥ 无信号,演示时间分配法推导(并显式标注推导置信度)', + }, + { + id: 'JET001', name: 'Jetting 点胶机 01', region: 'SRF', type: 'Jetting', lineId: 'SRF-L1', station: '点胶', + capability: 3, hasLog: true, gapThresholdMin: 3, ictSec: 40.2, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 16, + capabilityStars: { cycle: 3, down: 3, jam: 3, wait: 3, setup: 3, unit: 3 }, + capabilityNote: '次强(板级全数据)', + ictSource: 'POC', ictNote: '40.2s/板〔POC〕附录 D 间隙阈值表', + gapSource: 'POC', + logFormat: '结构化日志(CSV)', encoding: '—', + rebuildStrategy: '板级事件驱动(数据最完整)', + adapterTraps: [ + 'Current Program 每次 GO 重印,需检测值变化才取新值,否则同一程序被当成多次换型', + '唯一同时给出板级开始/结束/结果/等待时间的设备', + ], + countsForOee: true, + demoRole: '② 板级全数据,演示板级事件驱动重建', + }, + { + id: 'MBT001', name: 'MBT 翻转机 01', region: 'SRF', type: 'MBT', lineId: 'SRF-L1', station: '翻转', + capability: 1, hasLog: true, gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: 3, + capabilityStars: null, capabilityNote: '未列入附录 D.1 能力矩阵', + ictSource: 'PENDING_IE', ictNote: '规划书未给实测节拍,须 IE 提供', + gapSource: 'DEFAULT', + logFormat: 'CSV', encoding: 'GBK', + rebuildStrategy: '报警 + 节拍推断', + adapterTraps: ['中文报警,无恢复行 → 缺失结束配对(MISSING_END 策略)', 'GBK 编码,需 GBK→UTF-8 回退'], + countsForOee: true, + demoRole: '辅助:演示「无恢复行」的缺失结束配对', + }, + { + id: 'XR001', name: 'Xray 检测 01', region: 'SRF', type: 'Xray', lineId: 'SRF-L1', station: 'X 光检测', + capability: 1, hasLog: true, gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: null, + capabilityStars: null, capabilityNote: '未列入附录 D.1 能力矩阵(现场"少量")', + ictSource: 'PENDING_IE', ictNote: '规划书未给实测节拍,须 IE 提供', + gapSource: 'DEFAULT', + logFormat: '文件系统', encoding: '—', + rebuildStrategy: '文件 mtime 触发', + adapterTraps: ['无 API,仅文件修改时间;mtime 不等于生产时刻,只能作采集触发信号'], + countsForOee: true, + demoRole: '辅助:演示 MTIME 通道与其局限', + }, + { + id: 'LDR001', name: 'Loader 上料机 01', region: 'SRF', type: 'Loader', lineId: 'SRF-L1', station: '上料', + capability: 1, hasLog: false, fallbackChannel: 'IO_LIGHT', gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: null, + capabilityStars: null, capabilityNote: '无日志三类之一(Loader/分轨机/绿皮机合计约 10 台〔POC〕)', + ictSource: 'PENDING_IE', ictNote: '无日志,节拍须加装 IO 后测定', + gapSource: 'DEFAULT', + logFormat: '无日志', encoding: '—', + rebuildStrategy: '硬件信号(L1 级)', + adapterTraps: NO_LOG_TRAPS, + countsForOee: true, + demoRole: '辅助:演示无日志设备的 L1/录入过渡通道', + }, + { + id: 'SPL001', name: '分轨机 01', region: 'SRF', type: '分轨机', lineId: 'SRF-L1', station: '分轨', + capability: 1, hasLog: false, fallbackChannel: 'IO_LIGHT', gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: null, + capabilityStars: null, capabilityNote: '无日志三类之一(合计约 10 台〔POC〕,单类台数未给出)', + ictSource: 'PENDING_IE', ictNote: '无日志,节拍须加装 IO 后测定', + gapSource: 'DEFAULT', + logFormat: '无日志', encoding: '—', + rebuildStrategy: '硬件信号(L1 级)', + adapterTraps: NO_LOG_TRAPS, + countsForOee: true, + demoRole: '辅助:无日志设备', + }, + { + id: 'GRN001', name: '绿皮机 01', region: 'SRF', type: '绿皮机', lineId: 'SRF-L1', station: '辅助工站(待客户确认)', + capability: 1, hasLog: false, fallbackChannel: 'IO_LIGHT', gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: null, + capabilityStars: null, capabilityNote: '无日志三类之一(合计约 10 台〔POC〕,单类台数未给出)', + ictSource: 'PENDING_IE', ictNote: '无日志,节拍须加装 IO 后测定', + gapSource: 'DEFAULT', + logFormat: '无日志', encoding: '—', + rebuildStrategy: '硬件信号(L1 级)', + adapterTraps: [...NO_LOG_TRAPS, '现场俗称,正式工站名与工艺位置待客户确认,不臆造拓扑'], + countsForOee: true, + demoRole: '辅助:无日志设备', + }, + { + id: 'BUF001', name: '中间缓存 Buffer 01', region: 'SRF', type: 'Buffer', lineId: 'SRF-L1', station: '中间缓存', + capability: 1, hasLog: false, fallbackChannel: 'UPSTREAM_INFER', gapThresholdMin: 5, ictSec: 0, unit: '板', template: SRF, + codeSource: 'DEMO', pocFleetCount: null, + capabilityStars: null, capabilityNote: '无独立日志,由上下游进出板时间反推', + ictSource: 'NOT_APPLICABLE', ictNote: '缓存不生产,无节拍概念;缓冲覆盖时间 C = B × 下游 ICT', + gapSource: 'DEFAULT', + logFormat: '无独立日志', encoding: '—', + rebuildStrategy: '缓冲占用率反推', + adapterTraps: ['由上下游进出板时间反推占用率', '解耦条件 C ≥ 上游最长停机时间;POC 实测 B ≥ 25 单位'], + // 〔规划〕缓存本身不产出,计 OEE 会凭空多一个分母。它只作为缓冲解耦算法的输入对象。 + countsForOee: false, + demoRole: '辅助:SRF 缓冲解耦主口径的输入(25.50% 而非 16.02% 的关键)', + }, + + // ── FT 3 台 Handler+Tester 一体机〔方案〕────────────────────────────────── + ...(['93k178', '93k250', '93k287'] as const).map((id, i): DeviceMaster => ({ + id, name: `FT 终测一体机 ${id}`, region: 'FT', type: 'FT Tester', lineId: 'FT-L1', station: '终测', + capability: 2, hasLog: true, gapThresholdMin: 5, ictSec: 0, unit: '颗', template: FT, + codeSource: '方案', pocFleetCount: 108, + capabilityStars: { cycle: 2, down: 2, jam: 2, wait: 1, setup: 2, unit: 3 }, + capabilityNote: '唯一 Lot 级自包含', + ictSource: 'NOT_APPLICABLE', + ictNote: 'FT 多因子连乘:P = 1 −(OE效率损失 + Index时间占比 + Jam率),不用 N×ICT/RT。' + + 'Index 时间由客户参数 1.5s/(1.5+30)s 推得,不是设备 ICT。', + gapSource: 'POC', + logFormat: 'Handler CSV + Tester 文本报告(两类适配器)', encoding: 'GBK / UTF-8', + rebuildStrategy: 'lot_summary 自包含 Lot 级数据', + adapterTraps: [ + 'Handler:AlarmCode + StopedTime,>300s=Down、≤300s=Jam', + '编码混杂,GBK→UTF-8 回退', + 'Tester:lot_summary 解析 IN_QTY / Good Bin / Yield', + '93k287 的 PM 1,633.5min 计入与否 → OEE 82.12% ↔ 78.59%〔POC〕,C06 敏感性议题', + ], + countsForOee: true, + demoRole: i === 0 + ? '③ Lot 级自包含,演示业务归因(设备自识别 1.00)' + : `辅助:FT 产线按投入量加权的第 ${i + 1} 台`, + })), + + // ── ASLT 1 台 12 Site〔POC〕─────────────────────────────────────────────── + { + id: 'suzamdaslt386', name: 'ASLT 系统级测试机 386', region: 'ASLT', type: 'ASLT', lineId: 'ASLT-L1', station: '系统级测试', + capability: 2, hasLog: true, gapThresholdMin: 5, ictSec: 0, unit: '颗', template: ASLT, + codeSource: 'POC', pocFleetCount: 540, + capabilityStars: null, capabilityNote: '未列入附录 D.1 能力矩阵;报警行配对率仅 70%〔POC〕', + ictSource: 'NOT_APPLICABLE', + ictNote: 'C05「ASLT 是否有标准节拍/UPH」默认:无标准节拍时按理论工时/实际工时计算。' + + 'P = 12站使能总时长 / (12 × 活跃窗口时间),不用 ICT。', + gapSource: 'DEFAULT', + logFormat: 'Handler 文本日志 + SUM 报告(两类适配器)', encoding: 'UTF-8', + rebuildStrategy: '活跃窗口切分(相邻事件间隔 > 60min 视为断点)', + adapterTraps: [ + 'message record 秒级事件流,状态机分类', + '报警行配对率仅 70%,以活跃窗口切分补足', + '46 份报告 / 129 份 summary,按 Lot 号去重关联', + '12 Site 独立使能/禁用是 P 因子的唯一来源,必须在数据模型里体现', + ], + countsForOee: true, siteCount: 12, + demoRole: '辅助:演示 12 Site 使能占比与事件驱动口径', + }, +]; + +/** 17 台台账。全站唯一来源,页面不得另写一份设备清单。 */ +export const DEVICES: DeviceMaster[] = ROWS; + +export const DEVICE_BY_ID: Record = Object.fromEntries(ROWS.map((d) => [d.id, d])); + +/** 参与 OEE 聚合的设备(剔除中间缓存)。 */ +export const OEE_DEVICES: DeviceMaster[] = ROWS.filter((d) => d.countsForOee); + +/** 端到端锚点设备:先把一台 DEK 的时间轴做对,再铺其余设备(规划书 8.2 方法论)。 */ +export const ANCHOR_DEVICE_ID = 'DEK001'; + +/** + * 演示讲解顺序(附录 D.1 原文):六台设备演完全部六类数据可得性场景。 + * DEK → Jetting → FT Tester → Datacon → kohyoung → 回流焊 + */ +export const DEMO_ORDER: string[] = ['DEK001', 'JET001', '93k178', 'DCP005', 'AOI001', 'RF001']; + +/* ══════════════════════════════════════════════════════════════════ + * 线体 + * ══════════════════════════════════════════════════════════════════ */ + +export interface LineMaster { + id: string; + name: string; + region: Device['region']; + template: RegionTemplate; + deviceIds: string[]; + /** 瓶颈设备。SRF 的 POC 结论指向 DCP005(751min 缺失 + 124min 停机)。 */ + bottleneckDeviceId?: string; + note: string; +} + +export const LINES: LineMaster[] = [ + { + id: 'SRF-L1', name: 'SRF 演示线(DEK + DCP 串行)', region: 'SRF', template: SRF, + deviceIds: ROWS.filter((d) => d.region === 'SRF').map((d) => d.id), + bottleneckDeviceId: 'DCP005', + note: '主流程:DEK 印刷 → FUJI 贴装 → Datacon 贴装 → 回流焊 → AOI 检测〔规划书 1.1〕。' + + '缓冲解耦为主口径(25.50%),零缓冲 16.02% 为理论下界,两者不可混用。' + + '台账按建议书 3.5「SRF 13 类各 1 台」建;规划书 4.6.1 的 FUJI×2 / Datacon×2 在原型中' + + '以单台 + 2 Lane(FUJI)与 POC 改善标的 DCP005(Datacon)代表,差异已在主数据页披露。', + }, + { + id: 'FT-L1', name: 'FT 终测线', region: 'FT', template: FT, + deviceIds: ['93k178', '93k250', '93k287'], + note: '3 台按投入量加权 = 81.69%(A 92.58 / P 88.47 / Q 99.75)〔POC 2026M06〕。' + + '客户算法表《FT_OEE.xlsx》v3,A 为连乘扣减式,与通用 A=RT/PPT 不同构。', + }, + { + id: 'ASLT-L1', name: 'ASLT 系统级测试线', region: 'ASLT', template: ASLT, + deviceIds: ['suzamdaslt386'], + note: '1 台 12 Site。★ 两套三率属不同口径,不得交叉配对:站别汇总 A 61.39 / P 74.86 / Q 90.84 → 41.75%;' + + '活跃窗口口径 A 66.15 / P 68.21 / Q 90.84 → 40.99%〔均为 POC 参考基线〕。' + + '页面必须标明是"站别汇总"还是"活跃窗口"。无客户算法表,口径为系统建议,须 IE 定版。', + }, +]; + +export const LINE_BY_ID: Record = Object.fromEntries(LINES.map((l) => [l.id, l])); + +/* ══════════════════════════════════════════════════════════════════ + * 班次(3 班) + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 〔规划〕规划书 4.6.1 只写"3 班",未给具体时刻。此处取 3×8h 标准三班制作为**演示假设**, + * 并在主数据页标注"班次时刻为演示假设,待客户排班表确认"。不假装是客户真实排班。 + * + * C24(P0):跨天班次归属到**事件开始时刻所在业务日**。 + * 本 pattern 下每个班次都起始于其 bizDate 当天,故业务日 = 日历日,CT 窗口 = 00:00→24:00。 + */ +export interface ShiftPattern { + id: string; + name: string; + /** 相对业务日 00:00 的起始小时 */ + startHour: number; + endHour: number; + crossesMidnight: boolean; +} + +export const SHIFT_PATTERN: ShiftPattern[] = [ + { id: 'SH-C', name: '夜班', startHour: 0, endHour: 8, crossesMidnight: false }, + { id: 'SH-A', name: '白班', startHour: 8, endHour: 16, crossesMidnight: false }, + { id: 'SH-B', name: '中班', startHour: 16, endHour: 24, crossesMidnight: true }, +]; + +/** 班次时刻是演示假设,不是客户排班表。UI 必须带此标注。 */ +export const SHIFT_ASSUMPTION_NOTE = '班次时刻为演示假设(3×8h),待客户排班表确认'; + +function pad(n: number): string { return String(n).padStart(2, '0'); } + +/** 业务日 + 小时 → ISO。endHour=24 落到次日 00:00。 */ +function atHour(bizDate: string, hour: number): string { + const day = hour >= 24 ? nextDate(bizDate) : bizDate; + return `${day}T${pad(hour % 24)}:00:00Z`; +} + +/** 纯字符串日期 +1 天,不读时钟、不用 Date.now,保证可重放。 */ +export function nextDate(bizDate: string): string { + const [y, m, d] = bizDate.split('-').map(Number); + const daysInMonth = [31, (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + let dd = d + 1, mm = m, yy = y; + if (dd > daysInMonth[mm - 1]) { dd = 1; mm += 1; } + if (mm > 12) { mm = 1; yy += 1; } + return `${yy}-${pad(mm)}-${pad(dd)}`; +} + +/** 某业务日的三个班次窗口。跨天班次的 bizDate 仍为起始日(C24)。 */ +export function shiftsForDate(bizDate: string): { id: string; start: string; end: string; bizDate: string }[] { + return SHIFT_PATTERN.map((s) => ({ + id: `${bizDate}-${s.id}`, + start: atHour(bizDate, s.startHour), + end: atHour(bizDate, s.endHour), + bizDate, + })); +} + +/** 某业务日的 CT 窗口(00:00 → 次日 00:00)。 */ +export function ctWindowForDate(bizDate: string): { start: string; end: string } { + return { start: `${bizDate}T00:00:00Z`, end: `${nextDate(bizDate)}T00:00:00Z` }; +} + +/** 三日回放窗(种子数据覆盖范围)。09-02 是故意构造的脏数据日。 */ +export const SEED_DATES = ['2026-09-01', '2026-09-02', '2026-09-03'] as const; +export const SEED_DIRTY_DATE = '2026-09-02'; + +/* ══════════════════════════════════════════════════════════════════ + * 统计(现算,不写死) + * ══════════════════════════════════════════════════════════════════ */ + +export function deviceStats() { + const byRegion = { SRF: 0, FT: 0, ASLT: 0 }; + const byCapability = { 1: 0, 2: 0, 3: 0 }; + for (const d of ROWS) { + byRegion[d.region] += 1; + byCapability[d.capability] += 1; + } + return { + total: ROWS.length, + oeeCount: OEE_DEVICES.length, + byRegion, + byCapability, + hasLog: ROWS.filter((d) => d.hasLog).length, + noLog: ROWS.filter((d) => !d.hasLog).length, + /** 客户真实编码 vs 演示占位码 */ + realCode: ROWS.filter((d) => d.codeSource !== 'DEMO').length, + demoCode: ROWS.filter((d) => d.codeSource === 'DEMO').length, + /** ICT 有实测/推导值的台数;其余是口径不适用或待 IE 提供 */ + ictKnown: ROWS.filter((d) => d.ictSec > 0).length, + ictNotApplicable: ROWS.filter((d) => d.ictSource === 'NOT_APPLICABLE').length, + ictPendingIe: ROWS.filter((d) => d.ictSource === 'PENDING_IE').length, + /** 阈值由 POC 单列的台数(含 kohyoung 15 / Jetting 3 两处与公式默认值不同) */ + gapFromPoc: ROWS.filter((d) => d.gapSource === 'POC').length, + sites: ROWS.reduce((a, d) => a + (d.siteCount ?? 0), 0), + lanes: ROWS.reduce((a, d) => a + (d.lanes?.length ?? 0), 0), + }; +} + +/** 附录 D.1 能力矩阵的现场台数合计(有日志 8 类 = 108 台)。用于核对台账未漏类。 */ +export const POC_FLEET_WITH_LOG = 6 + 12 + 22 + 11 + 22 + 16 + 16 + 3; // = 108 +export const POC_FLEET_NO_LOG_APPROX = 10; // Loader/分轨机/绿皮机约 10 台 +export const POC_FLEET_SRF_TOTAL = POC_FLEET_WITH_LOG + POC_FLEET_NO_LOG_APPROX; // ≈ 118 + +/** 按 region 取设备。页面筛选用,不在组件里另写过滤逻辑。 */ +export function devicesOfRegion(region: Device['region']): DeviceMaster[] { + return ROWS.filter((d) => d.region === region); +} + +/** 按 lineId 取设备(保持台账顺序,主流程工站在前)。 */ +export function devicesOfLine(lineId: string): DeviceMaster[] { + return ROWS.filter((d) => d.lineId === lineId); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/disclosure.ts b/src/modules/tfamd-oee/data/oee/disclosure.ts new file mode 100644 index 0000000..d083434 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/disclosure.ts @@ -0,0 +1,822 @@ +/** + * 「说明与对照」页的唯一数据源 —— 建议书 §5.2.2 第 10 页(P0,必须做实且最先做)。 + * + * 这一页是评审现场的**防穿帮页**:客户问「这页呢」「这数哪来的」「你到底不承诺什么」, + * 答案都在这里,主动出示,不等被问。 + * + * 四条落地纪律: + * 1. **能现算的一律现算**:28 项口径、48 事件、三套「六」分类的成员与计数都从 + * calibers28 / events48 / types/oee 推导,页面不写死统计数字。 + * 只有「POC 供应商实测值」与「文档章节映射」是转录常量——它们不是我方可推算的量, + * 照录不改,并逐条带出处。 + * 2. **三套「六」分类永不混用**(六-1 损失桶 / 六-2 ASLT 时间账 / 六-3 事件表归口用词)。 + * 3. **同名不同口径的读数必须三标签齐全**(线体范围 + 时间窗 + 口径版本), + * 否则同一页会出现互相矛盾的数字(建议书 §5.3.2 演示纪律、风险 P4)。 + * 4. **未签字不标绿**:28 项 signedOff 全 false,P0 标灰;POC 数字标「参考基线·来源:鼎捷 POC」。 + */ +import { + LOSS_BUCKETS, BUCKET_LABEL, BUCKET_FACTOR, + ASLT_TIME_CLASSES, ASLT_CLASS_LABEL, + GROSS_CATEGORIES, GROSS_CATEGORY_COUNT, +} from '../../types/oee'; +import { CALIBER_CONFIG, CALIBER_ITEMS, SENSITIVITY_ISSUES, caliberStats } from './calibers28'; +import { EVENTS_48, eventStats } from './events48'; +import { DEVICES, LINES, ANCHOR_DEVICE_ID, DEVICE_BY_ID } from './devices'; +import { PARAMS_SIGNOFF_NOTE, serviceStats } from '../../lib/oeeService'; + +/** 出处标记:与建议书全文一致,页面每个数字旁都要能落到其中之一。 */ +export type EvidenceTag = 'SOW' | 'POC' | '方案' | '规划' | '实测' | '模拟'; + +export const EVIDENCE_LEDGER: { tag: EvidenceTag; label: string; meaning: string; simulated: boolean }[] = [ + { tag: 'SOW', label: '〔SOW〕', meaning: '《OEE分析项目需求说明书-20260826》原文要求,甲方提出的验收口径', simulated: false }, + { tag: 'POC', label: '〔POC〕', meaning: 'POC 阶段实测结论,作为三站参考基线,不随本系统重算', simulated: false }, + { tag: '方案', label: '〔方案〕', meaning: '《通富超威OEE分析解决方案 v5》的设计与配方', simulated: false }, + { tag: '规划', label: '〔规划〕', meaning: '《OEE智能优化平台改造规划书-2026-10-25》v0.2 的我方判断与细化', simulated: false }, + { tag: '实测', label: '〔实测〕', meaning: '本原型代码/命令实测所得(读文件、跑脚本),可复现', simulated: false }, + { tag: '模拟', label: '模拟', meaning: '本原型合成种子,**不是客户生产实况**;每张卡片右上角灰标', simulated: true }, +]; + +/** POC 数字统一挂的标签,全站唯一来源。 */ +export const POC_BASELINE_LABEL = '参考基线·来源:鼎捷 POC'; +export const POC_NOT_VERIFIED_NOTE = '三站 OEE 基线全部来自鼎捷 POC,我方未独立复核;不得当作客户生产实况引用。'; +export const SIM_BADGE = '模拟'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、20 页映射(建议书 §5.2.1 / §5.2.2 / §5.2.3) + * ══════════════════════════════════════════════════════════════════ */ + +export type PageGroup = '运营' | '分析' | '可视化' | '配置治理'; +export type PageStatus = 'real' | 'placeholder'; +/** 建议书 §5.2.3 核对表的列归属(与 status 是两个轴,见 PAGE_TALLY_NOTE)。 */ +export type PageTally = '九页做实' | '十一页占位'; + +export interface PageMapRow { + no: number; + name: string; + group: PageGroup; + /** 本原型是否真的实现这一页 */ + status: PageStatus; + /** 建议书 §5.2.3 核对表把它算在哪一列 */ + tally: PageTally; + /** 做实阶段 / 占位转做实阶段 */ + stage: string; + priority: 'P0' | 'P1'; + /** 对应方案章节(客户问「这页呢」时的答案) */ + chapter: string; + capability: string; + dataDep: string; + landing: string; + /** 验收点:挂到 11 条断言之一,或写明占位不做验收 */ + acceptance: string; +} + +export const PAGE_MAP: PageMapRow[] = [ + // ── 运营 5 页:全部做实 ── + { no: 1, name: '总览看板', group: '运营', status: 'real', tally: '九页做实', stage: 'W2-B', priority: 'P0', + chapter: '方案 5.2.1 #1 / 建议书 §5.2.1', capability: '五类结果指标、三层 OEE 对比、A/P/Q 分解、目标对比、趋势、线体/站别排行', + dataDep: 'oee_result × 三区域', landing: 'views.tsx 总览页签改造 + 复用 TrendChart/HBarChart', + acceptance: '断言②:四处读数一致;口径版本号可见' }, + { no: 2, name: '设备时间轴', group: '运营', status: 'real', tally: '九页做实', stage: 'W2-B', priority: 'P0', + chapter: '方案 5.2.1 #2 / 建议书 §5.5.2', capability: '当日状态段甘特、十态着色、每段起止与原始日志行、跨班拆分、影子时长', + dataDep: 'state_segment', landing: '新建 components/timeline/(SVG 习语,ADR-01 不引 ECharts)', + acceptance: '断言①:点段跳行号;断言⑤:kohyoung 15min' }, + { no: 3, name: '事件流', group: '运营', status: 'real', tally: '九页做实', stage: 'W2-B', priority: 'P0', + chapter: '方案 5.2.1 #3 / 建议书 §3.5', capability: '48 事件逐条、A–E 等级、配对状态、置信度、证据行号、三种表现形式区分', + dataDep: 'event_instance + event_def', landing: 'QapDataView 改造', + acceptance: '断言⑥:48 条全在;分级 A14/B7/C12/D14/E1' }, + { no: 4, name: '任务中心', group: '运营', status: 'real', tally: '九页做实', stage: 'W3-B 闭环治理台 + W4-A 换型链', priority: 'P0', + chapter: '方案 5.2.1 #6 / 建议书 §5.7', capability: 'StepChain 步骤链、节点 SLA、升级对象、当前处理人、改善闭环六态', + dataDep: 'improvement_task + DSL 常量', landing: '新建 components/stepchain/', + acceptance: '断言⑨:四项必填齐备才派发' }, + { no: 5, name: '现场录入台', group: '运营', status: 'real', tally: '九页做实', stage: 'W3-A', priority: 'P0', + chapter: '方案 5.2.1 #7 / 建议书 §5.6', capability: '8 大表单、预填充、一键提交、批量归因、超时提醒、5M1E 七字段', + dataDep: 'event_instance.manualEntry', landing: '新建 components/entry/', + acceptance: '断言⑥:D 类真实提交并触发重算' }, + // ── 分析 5 页:4 做实 + 1 占位 ── + { no: 6, name: '因子与 OEE', group: '分析', status: 'real', tally: '九页做实', stage: 'W2-B', priority: 'P0', + chapter: '方案 5.2.1 #4 / 建议书 §3.7', capability: '因子时长、损失 Pareto、六大损失桶 + 残差显示、产能/金额换算(参数占位)', + dataDep: 'loss_bucket + factor_duration', landing: 'views.tsx 损失结构页签 + HBarChart', + acceptance: '断言③:残差=0 且显式显示;≠0 时告警不归一化' }, + { no: 7, name: '数据质量台', group: '分析', status: 'real', tally: '九页做实', stage: 'W3-B', priority: 'P0', + chapter: '方案 5.2.1 #5 / 建议书 §3.8', capability: '12 条 DQ 命中、阻断项、未归因占比、修正清单、blocked/gap 标灰', + dataDep: 'dq_issue + unknown_event_pool', landing: 'QapDataView 改造 + 复用 OntRule.blocked 模式', + acceptance: '断言⑦:>5% 触发 DQ-06,显示「暂缓发布」' }, + { no: 8, name: '分析中心', group: '分析', status: 'real', tally: '九页做实', stage: 'W3-C', priority: 'P0', + chapter: '方案 5.2.1 #8 / 建议书 §5.4', capability: '5Why 追问链、鱼骨图(5M1E)、FMEA 评分、历史案例检索同屏', + dataDep: '知识四语料 + 归因结果', landing: 'MetricNetwork + CausalPanel 改造', + acceptance: '断言⑩:每条根因挂五实体之一;证据链不全只作候选' }, + { no: 9, name: 'AI 预测', group: '分析', status: 'real', tally: '十一页占位', stage: 'W4-B(规则外推示意,非模型)', priority: 'P1', + chapter: '方案 5.2.2 / 建议书 §4.9', capability: '规则外推 + 显式标「示意·非模型输出」', + dataDep: '四门槛未达(历史标签/样本量/特征/验证)', landing: 'components/workspace/OeeForecast.tsx', + acceptance: '断言⑪+D13:标「示意·非模型输出」;四门槛全未达不上模型' }, + { no: 10, name: '因子/事件定义', group: '分析', status: 'placeholder', tally: '十一页占位', stage: '建议提前至 W1', priority: 'P0', + chapter: '方案 5.2.2 / 建议书 §3.5', capability: '48 事件字典 + 四种状态着色', + dataDep: 'event_def(已落地)', landing: '建议提前做实:字典已在 data/oee/events48.ts', + acceptance: '字典层已由断言⑥覆盖;页面待提前' }, + // ── 可视化 3 页:1 做实 + 2 占位 ── + { no: 11, name: '大屏看板', group: '可视化', status: 'placeholder', tally: '十一页占位', stage: '原型 W4 可选', priority: 'P1', + chapter: '方案 5.2.2', capability: '1920×1080 版式示意 + 说明', + dataDep: '同总览看板', landing: '占位说明页', acceptance: '占位不做验收' }, + { no: 12, name: '线体图(2D)', group: '可视化', status: 'real', tally: '十一页占位', stage: 'W4-B', priority: 'P1', + chapter: '方案 5.2.2', capability: 'SVG 拓扑 + 状态灯(瓶颈定位)', + dataDep: 'LINES + 设备状态', landing: 'components/workspace/OeeLineMap.tsx', acceptance: '断言②:节点 OEE 与 L3 同源;状态灯只表达数据可得性' }, + { no: 13, name: '移动端预览', group: '可视化', status: 'placeholder', tally: '十一页占位', stage: 'P2', priority: 'P1', + chapter: '方案 5.2.2', capability: '响应式截图 + PWA 说明', + dataDep: '同各业务页', landing: '占位说明页', acceptance: '占位不做验收' }, + // ── 配置治理 7 页:5 做实 + 2 占位 ── + { no: 14, name: '配置中心', group: '配置治理', status: 'real', tally: '九页做实', stage: 'W4-A', priority: 'P0', + chapter: '方案 5.2.1 #9 / 建议书 §3.10', capability: '28 项口径默认值、算法模板、间隙阈值、优先级权重(A/B 切换)、版本与签批', + dataDep: 'caliber_config', landing: '新建 components/caliber/', + acceptance: '断言②⑩:切换触发重算 + 版本递增 + 旧版可回放' }, + { no: 15, name: '告警中心', group: '配置治理', status: 'placeholder', tally: '十一页占位', stage: '原型 W3', priority: 'P0', + chapter: '方案 5.2.2', capability: 'S1–S5 分级列表(右栏已含,独立页占位)', + dataDep: 'alert', landing: '右栏告警流已含分级', acceptance: '占位不做验收' }, + { no: 16, name: '主数据', group: '配置治理', status: 'real', tally: '十一页占位', stage: 'W2-C', priority: 'P0', + chapter: '方案 5.2.2 / 建议书 §3.3', capability: '设备/线体/站点/人员班次四类(种子常量可视化)', + dataDep: 'device/line/station/shift(已落地)', landing: 'components/workspace/OeeMasterData.tsx', acceptance: '断言⑪:种子常量可视化+模拟标注;P0 待 IE 签字标灰' }, + { no: 17, name: '集成接口', group: '配置治理', status: 'real', tally: '十一页占位', stage: 'W2-C', priority: 'P0', + chapter: '方案 5.2.2 / 建议书 §3.11', capability: 'IF-01~IF-12 契约、频率、幂等、签收状态、过渡方案', + dataDep: '接口契约(未联调)', landing: 'components/workspace/OeeIntegration.tsx', acceptance: '显示契约与状态,不显示真实连接' }, + { no: 18, name: '审计与权限', group: '配置治理', status: 'placeholder', tally: '十一页占位', stage: 'P4', priority: 'P0', + chapter: '方案 5.2.2', capability: '角色权限矩阵示意 + 操作审计(内存日志)', + dataDep: 'audit_log', landing: '占位说明页', acceptance: '占位不做验收;不承诺等保' }, + { no: 19, name: '报表导出', group: '配置治理', status: 'real', tally: '十一页占位', stage: 'W4-B', priority: 'P1', + chapter: '方案 5.2.2', capability: '7 类固定报表版式 + 导出 JSON/CSV', + dataDep: 'oee_result', landing: 'components/workspace/OeeReport.tsx', acceptance: '断言②⑩:七类与 exportReport 同源;口径版本随文件名留痕' }, + { no: 20, name: '说明与对照', group: '配置治理', status: 'real', tally: '十一页占位', stage: 'W1(本页,最先做)', priority: 'P0', + chapter: '建议书 §5.2.2 第 10 页', capability: '20 页与方案章节映射、口径出处、数据来源标注、不承诺清单', + dataDep: '本文件 disclosure.ts', landing: '新建 components/workspace/DisclosureView.tsx', + acceptance: '断言⑩:出处完整、不编数;11 条不承诺项齐全' }, +]; + +export const PAGE_GROUPS: PageGroup[] = ['运营', '分析', '可视化', '配置治理']; + +/** + * ★ 文档自身的一处口径冲突,显式披露、不自行圆整(与 ASLT 744h/32 日同类处理): + * + * 建议书 §5.2.3「页面与 20 页原型的映射核对」表把**说明与对照**算进「占位」列, + * 于是合计为 **9 页做实 + 11 页占位**(配置治理 7 页 = 1 做实 + 6 占位)。 + * 但同节 §5.2.2 的占位清单里,说明与对照的「做实阶段」写的是 + * **「原型 W1(评审用,必须做实)」**,正文更强调「必须做实且必须最先做」。 + * + * 两处不可同时成立。本原型的处置: + * - `tally` 忠实照录 §5.2.3 核对表的列归属 → 九页做实 9 / 十一页占位 11; + * - `status` 记录**本原型实际是否实现** → 说明与对照按正文要求做实, + * 且实施中把 AI 预测 / 线体图(2D)/ 主数据 / 集成接口 / 报表导出 五页由占位提前做实 + * (W2-C / W4-B),故实际实现 15 页、占位 5 页(配置治理 5 做实 + 2 占位)。 + * 两个轴分开展示,评审时主动说明差异来源,不静默选一边、也不改文档数字凑一致。 + */ +export const PAGE_TALLY_NOTE = + '建议书 §5.2.3 核对表为「9 页做实 + 11 页占位」,其中说明与对照被算进占位列;' + + '但 §5.2.2 正文要求该页「原型 W1 必须做实且最先做」。' + + '本原型按正文做实该页,并在实施中把 AI 预测 / 线体图(2D)/ 主数据 / 集成接口 / 报表导出 五页由占位提前做实(W2-C / W4-B),故实际实现 15 页 / 占位 5 页。' + + '两个口径并列展示:tally=文档核对表列归属(9/11),status=本原型实际实现(15/5)。差异已披露,未改文档数字凑一致。'; + +/* ══════════════════════════════════════════════════════════════════ + * 二、11 条不承诺清单 + * + * 出处:建议书 §1.2(6 条)+ §6.7.2(7 条,从价值角度重述)+ 规划书 §8「Demo 不承诺等保」。 + * 两表去重合并后恰为 11 条(「AI 准确率」与「根因准确率≥95%」是同一条的两个说法,合并; + * 「金额化收益绝对值」与「具体金额收益」同理)。此处逐条标注来源,不新增无出处的承诺。 + * ══════════════════════════════════════════════════════════════════ */ + +export interface NoPromiseRow { + no: number; + item: string; + prototype: string; + production: string; + source: string; +} + +export const NO_PROMISE: NoPromiseRow[] = [ + { no: 1, item: '真实数据采集', + prototype: '六通道全部为模拟适配器,读本地种子文件;接口页显示 IF-01~IF-12 的契约与状态而非真实连接', + production: 'P2(8 周,13 类适配器 ≥98%)〔方案〕', source: '建议书 §1.2' }, + { no: 2, item: 'AI 准确率(含根因准确率 ≥95%)', + prototype: '意图识别走规则+关键词,根因走 A/B/C 判定矩阵;不报准确率数字', + production: '一期 A1–A4 达 A≥85%/B≥70%〔规划〕;不采用 95% 口径', source: '建议书 §1.2 + §6.7.2' }, + { no: 3, item: 'OEE 计算准确率 99%', + prototype: '以原始日志行号为证据做断言核验;展示值与 POC 全精度值偏差 ≤0.02pp 视为一致', + production: 'SOW 为 ≥98%,99% 是供应商自我加码,不承诺〔规划 H.3〕', source: '建议书 §6.7.2' }, + { no: 4, item: '生产性能(200 并发 / <200ms / 99.5% 可用性)', + prototype: '不做并发压测,只保证单机演示流畅', + production: 'P4/P5 压测〔规划〕', source: '建议书 §1.2 + 规划书 §8' }, + { no: 5, item: '等保与安全合规认证', + prototype: '原型无认证、无权限隔离、无审计落库;审计页为内存日志示意', + production: '生产建设阶段按甲方安全要求另行立项', source: '规划书 §8「Demo 不承诺…等保」' }, + { no: 6, item: '金额化收益绝对值', + prototype: '金额列显示公式与参数占位,参数标「待财务签字」', + production: '财务专家交付损失金额模型后〔规划〕;三个财务参数未签字前只给区间', source: '建议书 §1.2 + §6.7.2' }, + { no: 7, item: '「产能 +10%」', + prototype: '不出现该表述;价值页给三条折损与三档情景', + production: '瓶颈约束 + Q 提升不增产能 + 订单支撑,三条折损未量化前不承诺〔规划〕', source: '建议书 §6.2.2 + §6.7.2' }, + { no: 8, item: '「OEE 提升 5%」', + prototype: '不出现该表述;每个 OEE 数字绑定线体范围 + 时间窗 + 口径版本三标签', + production: '三种读法歧义未澄清前不承诺〔规划 H.2〕', source: '建议书 §6.7.2' }, + { no: 9, item: '预测模型效果', + prototype: '预测页用规则外推并显式标「示意·非模型输出」', + production: '四门槛(历史标签/样本量/特征/验证)全未达,达标后另评', source: '建议书 §6.7.2 + §4.9' }, + { no: 10, item: '历史数据真实性 / POC 数字为客户生产实况', + prototype: '全部标「模拟」;POC 锚点只作参考基线,不与合成数据混算', + production: '永不兑现为客户生产实况,除非客户自己的数据接入', source: '建议书 §1.2 + §6.7.2' }, + { no: 11, item: '3D 孪生 / 语音交互', + prototype: '不做,在技术路线图里标「可选包/二期」', + production: '3D 依赖线体图数据模型,不改主链路〔方案〕', source: '建议书 §1.2' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 三、口径出处(28 项,全部现算自 calibers28) + * ══════════════════════════════════════════════════════════════════ */ + +export interface CaliberSourceRow { + id: string; + name: string; + defaultValue: string; + priority: 'P0' | 'P1' | 'P2'; + owner: string; + scope: string; + sensitivityIssue: string | null; + signedOff: boolean; + /** P0 未签字 → 标灰不标绿;P1/P2 → 默认值生效中 */ + tone: 'neutral' | 'muted'; + statusLabel: string; + source: string; +} + +export const CALIBER_SOURCE_NOTE = + '28 项逐条转录《OEE智能优化平台改造规划书-2026-10-25.md》附录 E〔方案〕。' + + '本次不安排口径工作坊,故 signedOff 全为 false:默认值生效,但无人签字,全站标「待 IE 签字」。'; + +/** 敏感性议题反查:一个口径项可能承载多个议题(此表按 SENSITIVITY_ISSUES 现推)。 */ +function issueOf(id: string): string | null { + const hit = Object.values(SENSITIVITY_ISSUES).filter((v) => (v.items as readonly string[]).includes(id)); + return hit.length ? hit.map((v) => v.label).join(' + ') : null; +} + +export function caliberSourceRows(): CaliberSourceRow[] { + return Object.values(CALIBER_ITEMS).map((c) => { + const note = c.note ?? ''; + const scope = note.split('|')[0].replace('影响范围:', ''); + return { + id: c.id, + name: c.name, + defaultValue: String(c.defaultValue), + priority: c.priority, + owner: c.owner, + scope, + sensitivityIssue: issueOf(c.id), + signedOff: c.signedOff, + // ★ P0 一律 neutral(灰),绝不 success(绿)——灰不等于错,是「还没人签字」 + tone: 'neutral', + statusLabel: c.signedOff ? '已签字' : c.priority === 'P0' ? '待 IE 签字(P0)' : '默认值生效中·待签字', + source: '规划书附录 E〔方案〕', + }; + }); +} + +/* ══════════════════════════════════════════════════════════════════ + * 四、三套「六」分类(建议书 §3.7)—— 并列展示,防混用 + * ══════════════════════════════════════════════════════════════════ */ + +export interface SixClassRow { + key: '六-1' | '六-2' | '六-3'; + name: string; + members: string[]; + usage: string; + carrier: string; + identity: string; + /** 是否成立求和恒等式 */ + hasIdentity: boolean; + source: string; +} + +export function threeSixRows(): SixClassRow[] { + const es = eventStats(); + return [ + { + key: '六-1', name: '六大损失桶', + members: LOSS_BUCKETS.map((b) => `${BUCKET_LABEL[b]}→${BUCKET_FACTOR[b]}`), + usage: '对外沟通与改善立项;映射 A/P/Q', + carrier: 'LossBucket / LossBucketResult', + identity: 'Σ桶时长 = PPT − 有效生产时间,残差 0(残差≠0 的唯一合法来源是未归因 IDLE)', + hasIdentity: true, source: '建议书 §3.7 / 规划书 4.2', + }, + { + key: '六-2', name: 'ASLT 时间六分类', + members: ASLT_TIME_CLASSES.map((c) => `${c} ${ASLT_CLASS_LABEL[c]}`), + usage: 'ASLT 站时间账,POC 实测用', + carrier: 'AsltTimeClass / AsltTimeAccount', + identity: 'Σ六类 = 总时长,残差 0.000000h〔POC〕', + hasIdentity: true, source: '建议书 §3.7 六-2 表〔POC〕', + }, + { + key: '六-3', name: '事件表「损失桶归口」用词', + members: GROSS_CATEGORIES.map((g) => `${g} ${GROSS_CATEGORY_COUNT[g]}`), + usage: `方案事件表的归口列,共 ${es.total} 项`, + carrier: 'EventDef.grossCategory 原始文本 → GROSS_TO_BUCKET 映射', + identity: `不成立恒等式;其中 ${es.nullBucketEvents} 个计划类事件不进六-1(${es.nullBucketKeys} 个 null 键)`, + hasIdentity: false, source: '规划书附录 C 逐条统计〔方案〕', + }, + ]; +} + +/** 六-2 的 POC 实测值:照录不改(供应商实测结论,不是我方推算)。 */ +export const ASLT_TIME_ACCOUNT_POC: { cls: string; hours: number; pct: number }[] = [ + { cls: 'Wait', hours: 153.52, pct: 20.63 }, + { cls: 'Plan', hours: 125.80, pct: 16.91 }, + { cls: 'Occ', hours: 379.41, pct: 51.00 }, + { cls: 'Eng', hours: 61.87, pct: 8.32 }, + { cls: 'Stop', hours: 23.29, pct: 3.13 }, + { cls: 'Standby', hours: 0.11, pct: 0.01 }, +]; +export const ASLT_ACCOUNT_TOTAL_HOURS = 744.00; +export const ASLT_WAIT_PLAN_PCT = 37.54; +/** ★ 不自行圆整:日历日 32(768h)与时间账 744.00h(31 日)差 1 日,待甲方确认(W0-4 Q1)。 */ +export const ASLT_DAY_GAP_NOTE = + '日历日 32 / 时间账 31,差 1 日待甲方确认。' + + '六类合计 744.00h = 31.0 日,而时间窗 2026-06-30~07-31 为 32 个日历日 = 768h,差 24h。' + + '三种可能解释(06-30 为接入日不计 / 1 日数据缺失被剔除 / 日历日与有效统计日口径不同)对应三种分母,会改变全部占比与 37.54% 这个核心结论。' + + '禁止为凑 768h 放大某类时长,也禁止把 32 日悄悄改成 31 日。'; + +/* ══════════════════════════════════════════════════════════════════ + * 五、同名不同口径的读数(三标签齐全才允许上屏) + * ══════════════════════════════════════════════════════════════════ */ + +export interface ReadingRow { + region: 'SRF' | 'FT' | 'ASLT'; + value: string; + metric: string; + scope: string; // 线体范围 + window: string; // 时间窗 + caliber: string; // 口径版本 / 口径名 + note: string; + source: string; +} + +export const CONFLICT_READINGS: ReadingRow[] = [ + { region: 'SRF', value: '25.50%', metric: 'OEE(A 39.17 / P 65.10 / Q 100)', + scope: 'DEK+DCP 串行线(站别基线)', window: 'POC 期', caliber: '缓冲解耦模板·站别基线', + note: '6.2 承诺「25.50→35%+」用的就是这个值', source: '建议书 §3.9.1〔POC〕' }, + { region: 'SRF', value: '57.2%', metric: 'OEE 实际层(理论 96.9 / 计划 91.2)', + scope: 'SRF 13 台', window: '2026-09-03 单日', caliber: '三层示例·实际层', + note: '与 25.50% 不是同一口径,切换时三个标签必须同步变化', source: '建议书 §3.9.1 / §5.3.2〔POC〕' }, + { region: 'SRF', value: '29.84%', metric: 'OEE 敏感性恒定值', + scope: '敏感性样本(四种 PAUSE 配对口径)', window: 'POC 敏感性样本期', caliber: 'A×P=Σideal/ΣCap,RT 约掉', + note: '与站别基线差 4.34pp,样本范围是否一致待确认(W0-4 Q4)', source: '建议书 §3.9.1 / 附录 G.3〔POC〕' }, + { region: 'SRF', value: '16.02%', metric: 'OEE 零缓冲下界', + scope: 'DEK+DCP 串行线·零缓冲', window: 'POC 期', caliber: '缓冲解耦·下界(不适用)', + note: '演示缓冲参数敏感性用,不是考核基线', source: '建议书 §5.3.2〔POC〕' }, + { region: 'FT', value: '81.69%', metric: 'OEE(A 92.58 / P 88.47 / Q 99.75)', + scope: 'FT 区域加权(108 台)', window: '2026M06,28 完整日', caliber: '多因子连乘·区域加权', + note: '《FT_OEE.xlsx》v3 偏差 0;考核口径待确认(W0-4 Q5)', source: '建议书 §3.9.2〔POC〕' }, + { region: 'FT', value: '81.90%', metric: 'OEE(A 92.63 / P 88.65 / Q 99.73)', + scope: '单机 93k178(Handler + Tester)', window: '2026M06,28 完整日', caliber: '多因子连乘·单机', + note: 'A/P/Q 分项是单机口径,与加权差约 0.21pp,两者都对但必须各自带标签', source: '建议书 §3.9.2〔实测〕' }, + { region: 'FT', value: '82.12% → 78.59%', metric: 'OEE(PM 计入前后)', + scope: '单机 93k287(不是 93k178)', window: '2026M06', caliber: 'C06 开关:PM 1,633.5min 计入计划损失', + note: '第三套范围;演示 C06 时 UI 必须同时切换设备号', source: '建议书 §3.9.2〔POC〕' }, + { region: 'ASLT', value: '41.75%', metric: 'OEE(A 61.39 / P 74.86 / Q 90.84)', + scope: '1 台 12 Site(suzamdaslt386)', window: '2026-06-30~07-31', caliber: '事件驱动模板·系统建议口径', + note: '37 断言 PASS;A/P 另有活跃窗口口径读数,必须双标', source: '建议书 §3.9.3〔POC〕' }, + { region: 'ASLT', value: 'A 66.15% / P 68.21%', metric: 'A=377.84h/571.20h;P=4,675.39h/6,854.40h', + scope: '同上 1 台 12 Site', window: '同上', caliber: '活跃窗口口径(>60min 间隔切分)', + note: '与 61.39%/74.86% 差异来自口径,不能只选一个显示(W0-4 Q3)', source: '建议书 §3.9.3〔POC〕' }, + + /* ── 以下三条是**我方实测复算发现的文档矛盾**,照录不抹平、不四舍五入 ────────── + * 断言④第八节以可执行形式守住;页面必须显式披露,不得静默选一个值上屏。 */ + { region: 'FT', value: '94.87% ≠ 92.63%', metric: '照录操作数连乘 vs 公布 A 值', + scope: '单机 93k178(Handler + Tester)', window: '2026M06,28 完整日', caliber: '规划书操作数笔误(实测复算)', + note: '规划书 line 435 写 0.997384×0.97057×0.98,实算 94.8670%,不是 92.63%。' + + '正确操作数应为 0.97384(Down率 2.616% 的补数),得 92.6276%。差 2.24pp 远超显示容差 0.02pp,' + + '引擎按 Down率 实算,不复现笔误值', + source: '规划书 v0.2 line 435〔实测复算〕' }, + { region: 'ASLT', value: '40.99%', metric: 'OEE(A 66.15 / P 68.21 / Q 90.84)', + scope: '1 台 12 Site·活跃窗口口径', window: '2026-06-30~07-31', caliber: '活跃窗口口径(>60min 间隔切分)', + note: '★ 41.75% 属**站别汇总**(0.6139×0.7486×0.9084=41.7469%);活跃窗口三率连乘是 40.9878%。' + + '两口径差 0.76pp,两套三率**不得交叉配对**(把 66.15/68.21 挂到 41.75% 上即错)', + source: '建议书 §3.9.3〔POC〕+ 我方实测复算' }, + { region: 'FT', value: '87,429.82s/日', metric: 'baseSec 2,448,035s ÷ 28 完整日', + scope: '单机 93k178', window: '2026M06,28 完整日', caliber: '分母口径待 IE 确认(W0-4 新增疑点)', + note: '★ 每日 87,429.82s > 日历日 86,400s,28 日共多出 28,835s≈8.01h。' + + 'baseSec 不是纯日历秒分母(可能含跨日重叠或双计),口径须 IE 确认。' + + '演示日一律取 86400s,不沿用该分母,也不声称复现 POC 的 28 日累计', + source: '建议书 §3.9.2〔实测复算〕' }, +]; + +export const READING_DISCIPLINE_NOTE = + '每个数字旁必须同时显示「线体范围 + 时间窗 + 口径版本」三个标签。' + + '缺任一标签就会出现同页自相矛盾(风险 P4):SRF 一会儿 25.50% 一会儿 57.2%,观众会认为系统算错了。'; + +/** + * 三站 POC 基线与改善目标(价值页与说明页共用,照录不改)。 + * + * planWaitShare / trueStopShare 是为「计划与等待排行」结构化照录的 POC 占比, + * 避免视图去解析 baselineNote 字符串(脆弱)。**两者在每站内部同分母可比**: + * FT 分母=损失时长(tray 4,111.9min 占 69.3%;Tester I/F 设备型约 8.5%) + * SRF 分母=计划时间(计划损失+待机 49.1%;真停机 5.9%) + * ASLT 分母=时间账 744h(Wait+Plan 37.54%;Stop 3.13%) + * 三站之间分母不同,**不可直接比大小**——并列只为说明同一结论:改善标的是计划与等待,不是设备维修。 + */ +export const POC_ANCHORS: { + region: 'SRF' | 'FT' | 'ASLT'; oee: string; apq: string; baselineNote: string; target: string; lever: string; + planWaitShare: number; planWaitLabel: string; trueStopShare: number; trueStopLabel: string; denom: string; +}[] = [ + { region: 'FT', oee: '81.69%', apq: 'A 92.58 / P 88.47 / Q 99.75', + baselineNote: 'tray 类 3,963 次(72.8%)/ 4,111.9min(69.3%);真因清盘不及时 45% / 节拍不匹配 30% / Tray 周转不足 25%', + target: '85%+', lever: '卸盘器满载预警联动、清盘 SOP、Tray 周转;回收 ≥400min/月', + planWaitShare: 69.3, planWaitLabel: 'tray 类(清盘/周转)', trueStopShare: 8.5, trueStopLabel: 'Tester I/F 设备型', denom: '损失时长' }, + { region: 'SRF', oee: '25.50%', apq: 'A 39.17 / P 65.10 / Q 100', + baselineNote: '计划损失 + 待机 49.1%,真停机仅 5.9%;DEK 847 次阻塞/日累计 7.3h;未归因 31.7%', + target: '35%+', lever: '排产计划、缓冲配置、物料保障(不是维修)', + planWaitShare: 49.1, planWaitLabel: '计划损失 + 待机', trueStopShare: 5.9, trueStopLabel: '真停机', denom: '计划时间' }, + { region: 'ASLT', oee: '41.75%', apq: 'A 61.39 / P 74.86 / Q 90.84', + baselineNote: 'Wait+Plan 37.54%,Stop 仅 3.13%;495 段 Stop(82 Down + 413 Jam);49 活跃窗口 / 48,717 行', + target: '50%+', lever: '物料保障 → 排产计划 → 站点满载 → 换型标准化 → 设备维修(维修排最后)', + planWaitShare: 37.54, planWaitLabel: 'Wait + Plan', trueStopShare: 3.13, trueStopLabel: 'Stop(Down+Jam)', denom: '时间账 744h' }, +]; + +/** 「计划与等待排行」的口径披露:每站内部同分母可比,三站之间分母不同不可比大小。 */ +export const PLAN_WAIT_RANK_NOTE = + '首页排行是「计划与等待」而非「故障」:三站 POC 一致指向组织与管理(排产/物料/清盘),不是设备维修。' + + '每站内部「计划与等待」与「设备/真停机」同分母可比(FT 占损失时长 / SRF 占计划时间 / ASLT 占时间账 744h);' + + '三站之间分母不同,不可直接比大小,并列只为说明同一结论。'; + +/* ══════════════════════════════════════════════════════════════════ + * 六、W0 阻塞项与随表追问清单(建议书 §7.1) + * ══════════════════════════════════════════════════════════════════ */ + +export interface BlockerRow { + id: string; item: string; owner: string; deliverable: string; selfSolvable: boolean; status: string; +} + +export const W0_BLOCKERS: BlockerRow[] = [ + { id: 'W0-1', item: '修端口 5202→5203', owner: '我方', + deliverable: 'vite.config.ts 改一行 + tsc -b 通过 + 两应用可同时启动', selfSolvable: true, status: '已解决(ADR-08)' }, + { id: 'W0-2', item: '4 项敏感性口径签字', owner: 'IE(Peter / Li Juyan / Xin Jennie〔方案〕)', + deliverable: '《OEE 口径 v0.1》签字版:Plan 边界 / Occ 判定 / Q 定义 / FT 的 PM 是否计入', + selfSolvable: false, status: '未签(本次不安排口径工作坊,按附录 E 默认值先行)' }, + { id: 'W0-3', item: '48 事件分级确认', owner: 'IE + PE + MFG', + deliverable: '48 事件签字表,尤其 14 个 D 类的录入责任人与时点', selfSolvable: false, status: '未签' }, + { id: 'W0-4', item: '三份客户基准表', owner: 'IE + 财务', + deliverable: '《FT_OEE.xlsx》《20260520SRF_OEE_计算逻辑.xlsx》《ASLT 37 断言表》', selfSolvable: false, status: '未到位' }, +]; + +export const W0_QUESTIONS: { id: string; q: string; why: string; source: string }[] = [ + { id: 'Q1', q: 'ASLT 日历日 32 与时间账 744.00h(31 日)差的 1 日去哪了?', + why: '三种解释对应三种分母,会改变六分类全部占比与 37.54% 这个核心结论', source: '建议书 §3.7 六-2 表〔实测〕' }, + { id: 'Q2', q: 'FT 月度基数 2,448,035s 是否等于 28 完整日 × 86400s?', + why: '28×86400=2,419,200s,差 28,835s(≈8.0h),需确认是否含跨月边界或加班', source: '建议书 §3.9.2 / §6.2〔实测〕' }, + { id: 'Q3', q: 'ASLT 的 A 有 66.15% 与 61.39% 两个读数,各自分母是什么?', + why: '活跃窗口口径与系统建议口径不可混用,页面必须双标', source: '建议书 §3.9.3〔POC〕' }, + { id: 'Q4', q: 'SRF 考核基线取 25.50% 还是 29.84%?', + why: '差 4.34pp;若客户认 29.84% 为基线,则提升幅度与验收口径全部要重算', source: '建议书 §3.9.1 / 附录 G.3〔POC〕' }, + { id: 'Q5', q: 'FT 的 81.69%(区域加权)与 81.90%(单机 93k178)哪个进考核?PM 敏感性用的是 93k287,是否同一台?', + why: '三套范围混用会让「81.69→85%」的承诺失去可验收性', source: '建议书 §3.9.2〔实测〕' }, + { id: 'Q6', q: '收益换算的三个财务参数(单颗边际贡献、达成率、可变现比例)由谁签字?', + why: 'ROI 三档全部依赖这三个参数,缺签字则只能给区间不能给金额', source: '建议书 §6.3 / §6.5' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 七、数据来源标注(本原型到底读了什么) + * ══════════════════════════════════════════════════════════════════ */ + +export interface SourceRow { + layer: string; module: string; what: string; tag: EvidenceTag; simulated: boolean; gap: string | null; +} + +/** demo 沙箱固定口径:本工程不接后端。 */ +const DEMO_SANDBOX_GAP = '本工程为 demo 沙箱,不接后端;数据来自内置合成种子,不冒充实测'; + +export function dataSourceRows(): SourceRow[] { + const ss = serviceStats(); + const anchor = DEVICE_BY_ID[ANCHOR_DEVICE_ID]; + return [ + { layer: 'L1 采集适配', module: 'lib/oee/adapterDek.ts + data/oee/dekCodes.ts', + what: `DEK EVENT.DAT 合成种子 ${ss.totalLines.toLocaleString()} 行;码表为演示子集`, + tag: '模拟', simulated: true, + gap: DEMO_SANDBOX_GAP }, + { layer: 'L1 主数据', module: 'data/oee/devices.ts', + what: `设备 ${DEVICES.length} 台 / 线体 ${LINES.length} 条;锚点 ${ANCHOR_DEVICE_ID}(${anchor?.name ?? ''})`, + tag: '方案', simulated: false, gap: '班次时刻为演示假设(3×8h),待客户排班表确认' }, + { layer: 'L1 事件字典', module: 'data/oee/events48.ts', + what: `48 事件定义,分级 A${eventStats().grade.A}/B${eventStats().grade.B}/C${eventStats().grade.C}/D${eventStats().grade.D}/E${eventStats().grade.E}`, + tag: '方案', simulated: false, gap: '48 事件分级未签字(W0-3),14 个 D 类录入责任人待定' }, + { layer: 'L1 口径', module: 'data/oee/calibers28.ts', + what: `28 项口径,版本 ${CALIBER_CONFIG.version},生效 ${CALIBER_CONFIG.effectiveFrom}`, + tag: '方案', simulated: false, gap: PARAMS_SIGNOFF_NOTE }, + { layer: 'L2 引擎', module: 'lib/oee/*.ts(7 个纯函数模块)', + what: '配对 / 状态机 / 六桶 / 三档 OEE / DQ / 口径敏感性;零 IO、零时钟、零随机', tag: '实测', simulated: false, gap: null }, + { layer: 'L3 服务', module: 'lib/oeeService.ts', + what: `唯一取数入口;三日回放 ${ss.dates.join('、')};异常日 ${ss.dirtyDate}`, + tag: '实测', simulated: true, + gap: ss.coverageGap }, + { layer: 'L3 本体', module: 'data/ontologyOee.ts', + what: '九类对象 / 关系 / 规则 / 动作,instances()/count()/hits() 全部现算', tag: '实测', simulated: true, + gap: '线体/区域绩效实例已随 W2-B 落地、改善任务已随 W3-B 落地(任务中心内存态);不造实例充数' }, + { layer: 'L4 视图', module: 'components/*', + what: '只消费 L3 结果,不做二次计算', tag: '实测', simulated: true, gap: null }, + { layer: 'POC 锚点', module: '本文件 POC_ANCHORS / CONFLICT_READINGS / ASLT_TIME_ACCOUNT_POC', + what: '三站基线与敏感性读数,照录 POC 实测结论', tag: 'POC', simulated: false, gap: '参考基线,不随本系统重算' }, + ]; +} + +export const DATA_MODE_NOTE = + '当前为 demo 模式:L1 读合成种子,全部数据标「模拟」。本工程为 demo 沙箱,不接后端(客户侧采集通道与码表全表未到位),不假装已支持直采。'; + +/** 运行时徽标:demo 固定挂「模拟」。 + * SIM_BADGE 常量保留给校验脚本基线与知识库页(知识条目仍为合成示例)。 */ +export function simBadge(): string | null { + return SIM_BADGE; +} + +/** 运行时模式说明:demo 固定文案(校验脚本锁定子串)。 */ +export function dataModeNote(): string { + return DATA_MODE_NOTE; +} + +/* ══════════════════════════════════════════════════════════════════ + * 七之二、11 条断言 → 校验脚本登记表(建议书 §5.7 / §3.8) + * + * ★ 本表是**声明式登记**:浏览器里没有 fs,无法在运行时数脚本文件。 + * 真正的「文件是否存在 / 是否全绿」由 scripts/verify-oee-disclosure.ts + * 用 readdirSync 对账,并由聚合入口 verify-oee-all.ts 现场跑出来。 + * 页面只展示登记与阶段,**不声称已全绿**——绿不绿以现场执行输出为准。 + * ══════════════════════════════════════════════════════════════════ */ + +export interface AssertionRow { + /** ①..⑪;附加检查用 '附加' */ + id: string; + name: string; + invariant: string; + script: string; + kind: 'assertion' | 'extra'; + /** 落地阶段 */ + stage: string; +} + +export const ASSERTION_REGISTRY: AssertionRow[] = [ + { id: '①', name: '可下钻到行号', kind: 'assertion', script: 'verify-oee-trace.ts', stage: 'W1-G(已落地)', + invariant: 'oee_result.detailRef → factor_duration → state_segment → event_instance.evidence.lineNo 全链非空;随机抽 20 个 OEE 数字回溯' }, + { id: '②', name: '四处读数一致', kind: 'assertion', script: 'verify-oee-caliber.ts', stage: 'W1-E(已落地)', + invariant: '同一 scope 调 4 次服务结果深相等;组件依赖扫描无二次计算' }, + { id: '③', name: '残差=0 + 顺序替代恒等', kind: 'assertion', script: 'verify-oee-buckets.ts', stage: 'W1-C(已落地,W2-A 追加区域分支)', + invariant: 'residualSec===0;dA+dP+dQ===oee2−oee1(EPS=1e-9);三区域各跑。' + + '区域分支:SRF 流体时间账残差=0 + 站别 PPT 闭合;FT 八中间量闭合到三率(连乘扣减式,非通用 A=RT/PPT);' + + 'ASLT 六分类时间账残差=0 + 活跃窗口分母。三套区域读数各自再守恒等。' + + '两套容差分工:时间账 1e-6s(浮点噪声)、三率恒等 EPS、展示复算 ±0.02pp,不得互相放宽;' + + 'POC 锚点只作参考基线,口径差异(FT 单机 81.8960% vs 区域 81.69%)如实披露不抹平' }, + { id: '④', name: '产线合成不用均值', kind: 'assertion', script: 'verify-oee-synthesis.ts', stage: 'W2-A(已落地)', + invariant: '串行 A/Q 连乘、P 取瓶颈;并行按投入量加权;区域线别加权;周期累加原始量重算。' + + '反例非退化:算术平均 / 线别 OEE 加权 / 日均 OEE 三者两两不同且均 ≠ 正确值。' + + '另守 SRF 两侧解耦分开判(分母 ICT 不同)、FT 与 POC 操作数对齐、ASLT 越界显式报问题、两处文档矛盾' }, + { id: '⑤', name: 'kohyoung 15min', kind: 'assertion', script: 'verify-oee-threshold.ts', stage: 'W2-A(已落地)', + invariant: '台账校准优先于公式:AOI001 15≠18、JET001 3≠5(含低于公式的情形),全台账恰好两台不同。' + + '同一份日志 15min 未归因 0s、5min 未归因 1560s(18.57%)并真跑 DQ 引擎证明 DQ-06 阻断;' + + '阈值只改 RUN/IDLE 归属,PPT 与 A 类三桶不变,残差恒等于未归因 IDLE;' + + '恰好等于阈值判 IDLE(严格小于才填 RUN);Down/Jam C08 300s 分界与间隙阈值互不干扰。' + + '另守量纲:unattributedPct 与 DQ-06 阈值同为比例 0–1,展示才 ×100' }, + { id: '⑥', name: '48 事件 + D 类重算', kind: 'assertion', script: 'verify-oee-events.ts', stage: 'W1-B 字典 + W3-A D 类重算(均已落地)', + invariant: '48 条唯一;A14/B7/C12/D14/E1;提交 D 类后版本递增' }, + { id: '⑦', name: 'DQ-06 阻断', kind: 'assertion', script: 'verify-oee-dq.ts', stage: 'W1-C(已落地)', + invariant: '构造 >5% 与 <5% 两日,阻断状态正确切换' }, + { id: '⑧', name: '优先级可解释', kind: 'assertion', script: 'verify-oee-priority.ts', stage: 'W3-A(已落地)', + invariant: '分数可由权重重算;A/B 两套权重切换后排序变化' }, + { id: '⑨', name: '四项必填', kind: 'assertion', script: 'verify-oee-closure.ts', stage: 'W3-A 引擎 + W3-B 治理台 UI(均已落地)', + invariant: '四项任一缺失 → canDispatch===false;六态流转合法' }, + { id: '⑩', name: '出处 + 跨版本拒绝', kind: 'assertion', script: 'verify-oee-guards.ts', stage: 'W3-C(已落地)', + invariant: '五道闸逐条触发;跨版本对比返回拒绝' }, + { id: '⑪', name: '模拟标注', kind: 'assertion', script: 'verify-oee-labels.ts', stage: 'W4-C(已落地)', + invariant: '所有种子 synthetic===true;POC 锚点带 baselineNote' }, + { id: '附加', name: '引擎纯函数', kind: 'extra', script: 'verify-oee-purity.ts', stage: 'W1-C(已落地)', + invariant: '扫描 lib/oee/*.ts 的 import,出现 data/ / fetch / Date.now 即失败' }, + { id: '附加', name: '三套六分类', kind: 'extra', script: 'verify-oee-bucketmap.ts', stage: 'W1-G(已落地)', + invariant: 'GROSS_TO_BUCKET 值域只含六桶或 null;null 键=3 个;这 3 键覆盖事件数=20,其余 28 条落六桶' }, +]; + +/** 本建议书 13 脚本之外、实施中另加的校验(不在规划书 11 条内,但守同一批纪律)。 */ +export const EXTRA_VERIFY_SCRIPTS: { script: string; name: string; stage: string }[] = [ + { script: 'verify-oee-dek.ts', name: '单台 DEK 端到端(①②部分⑥)', stage: 'W1-D(已落地)' }, + { script: 'verify-oee-ontology.ts', name: '本体层九类对象与真实来源对账', stage: 'W1-E(已落地)' }, + { script: 'verify-oee-filters.ts', name: '全局筛选与五类结果指标(②⑪延伸)', stage: 'W1-F(已落地)' }, + { script: 'verify-oee-disclosure.ts', name: '说明与对照页:出处齐全、不承诺清单、两轴对账', stage: 'W1-F(已落地)' }, + { script: 'verify-oee-improvement.ts', name: '改善运营 L3 编排:现算分·候选→任务·派发闸·六态·5M1E(⑧⑨⑥延伸)', stage: 'W3-A(已落地)' }, + { script: 'verify-oee-alerts.ts', name: '五级告警流 L3 编排:S1–S5 映射不丢不造·S4 独立成级暂停发布·S1 诚实为空(⑦延伸)', stage: 'W3-B(已落地)' }, + { script: 'verify-oee-stepchain.ts', name: 'StepChain 换型链 DSL:7 节点照录·七态独立于闭环六态(D17)·GATE 不可跳过·T6 派生 n7=n4−10min·T5 占位·SLA 升级(⑨延伸)', stage: 'W4-A(已落地)' }, + { script: 'verify-oee-w4b.ts', name: '预测示意/2D 线体图/报表导出:四门槛全未达不上模型(D13)·规则外推可重算·报表七类与 exportReport 工具同源(②)·CSV RFC4180+口径留痕(⑩)·线体图 17 节点诚实状态灯+瓶颈+ASLT 12 Site', stage: 'W4-B(已落地)' }, +]; + +export const VERIFY_AGGREGATE = 'verify-oee-all.ts'; +export const VERIFY_COMMAND = 'npm run verify'; +export const VERIFY_NOTE = + '13 个校验脚本 + 1 个聚合入口 = 14 个 .ts 文件(建议书 §5.7 文件计数口径)。' + + '「13 个验证脚本」均指不含聚合入口。评审现场跑 ' + VERIFY_COMMAND + ',以实际输出为准;' + + '本页只登记断言与落地阶段,不声称已全绿。' + + '实施中另加 ' + EXTRA_VERIFY_SCRIPTS.length + ' 个校验脚本(DEK 端到端 / 本体 / 筛选 / 本页 / 改善编排 / 告警 / 换型链 / 预测·线体·报表),不在规划书 11 条内。'; + +/** 四道阶段门(建议书 §7.3)。 */ +export const GATES: { id: string; when: string; criterion: string; onFail: string }[] = [ + { id: 'G1', when: 'W1 末', criterion: 'DEK 单机端到端可下钻到行号;断言①②⑥通过', onFail: '停止横向扩展,先修 DEK 链路' }, + { id: 'G2', when: 'W2 末', criterion: '三区域模板各自跑通;六桶残差=0;断言③④⑤通过', onFail: '不进入 W3,先修口径与合成' }, + { id: 'G3', when: 'W3 末', criterion: 'D 类真实提交触发重算;DQ-06 阻断可见;断言⑦⑧⑨⑩通过', onFail: '削减 W4 范围,保闭环' }, + { id: 'G4', when: 'W4 末', criterion: '13 脚本全绿;模拟标注齐全;断言⑪通过', onFail: '不出评审包,先补标注与一致性' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 八、自检(供校验脚本引用,数字一律现算) + * ══════════════════════════════════════════════════════════════════ */ + +export function disclosureStats() { + const cs = caliberStats(); + const es = eventStats(); + const ss = serviceStats(); + const real = PAGE_MAP.filter((p) => p.status === 'real'); + const ph = PAGE_MAP.filter((p) => p.status === 'placeholder'); + const groups = PAGE_GROUPS.map((g) => { + const rows = PAGE_MAP.filter((p) => p.group === g); + return { + group: g, + total: rows.length, + real: rows.filter((p) => p.status === 'real').length, + placeholder: rows.filter((p) => p.status === 'placeholder').length, + }; + }); + const six = threeSixRows(); + const caliberRows = caliberSourceRows(); + const sources = dataSourceRows(); + const tallyReal = PAGE_MAP.filter((p) => p.tally === '九页做实'); + const tallyPh = PAGE_MAP.filter((p) => p.tally === '十一页占位'); + const tallyGroups = PAGE_GROUPS.map((g) => { + const rows = PAGE_MAP.filter((p) => p.group === g); + return { + group: g, + total: rows.length, + real: rows.filter((p) => p.tally === '九页做实').length, + placeholder: rows.filter((p) => p.tally === '十一页占位').length, + }; + }); + return { + /** 20 页。两个轴分开:status=本原型实际实现;tally=建议书 §5.2.3 核对表列归属 */ + pageTotal: PAGE_MAP.length, + pageReal: real.length, + pagePlaceholder: ph.length, + /** 文档核对表口径:9 做实 + 11 占位(说明与对照被算进占位列) */ + tallyReal: tallyReal.length, + tallyPlaceholder: tallyPh.length, + tallyGroups, + /** ★ 两轴唯一差异页必须是说明与对照,且差异已显式披露(不静默圆整) */ + tallyStatusDiffPages: PAGE_MAP.filter((p) => (p.tally === '九页做实') !== (p.status === 'real')).map((p) => p.name), + tallyNote: PAGE_TALLY_NOTE, + tallyDiscrepancyDisclosed: PAGE_TALLY_NOTE.includes('9 页做实 + 11 页占位') && PAGE_TALLY_NOTE.includes('15 页 / 占位 5 页'), + pageNosUnique: new Set(PAGE_MAP.map((p) => p.no)).size === PAGE_MAP.length, + pageNosContiguous: PAGE_MAP.every((p, i) => p.no === i + 1), + groups, + /** 分组页数必须是 5/5/3/7 */ + groupCounts: groups.map((g) => g.total), + /** 每页都要有方案章节出处与验收点,占位页也不例外 */ + pagesAllChapters: PAGE_MAP.every((p) => p.chapter.length > 0), + pagesAllAcceptance: PAGE_MAP.every((p) => p.acceptance.length > 0), + /** 说明与对照页自己必须在做实清单里,且阶段标 W1 */ + disclosurePageReal: PAGE_MAP.some((p) => p.name === '说明与对照' && p.status === 'real' && p.stage.startsWith('W1')), + /** 11 条不承诺项,逐条四件齐备 */ + noPromiseTotal: NO_PROMISE.length, + noPromiseNosContiguous: NO_PROMISE.every((r, i) => r.no === i + 1), + noPromiseComplete: NO_PROMISE.every((r) => r.item && r.prototype && r.production && r.source), + /** 六件事(§1.2)与七件事(§6.7.2)的关键项都必须在清单里 */ + noPromiseCovers: { + realCollection: NO_PROMISE.some((r) => r.item.includes('真实数据采集')), + aiAccuracy: NO_PROMISE.some((r) => r.item.includes('AI 准确率')), + performance: NO_PROMISE.some((r) => r.item.includes('生产性能')), + money: NO_PROMISE.some((r) => r.item.includes('金额化收益')), + historyTruth: NO_PROMISE.some((r) => r.item.includes('历史数据真实性')), + twin3d: NO_PROMISE.some((r) => r.item.includes('3D')), + capacity10: NO_PROMISE.some((r) => r.item.includes('产能 +10%')), + oee5: NO_PROMISE.some((r) => r.item.includes('OEE 提升 5%')), + calc99: NO_PROMISE.some((r) => r.item.includes('99%')), + forecast: NO_PROMISE.some((r) => r.item.includes('预测模型效果')), + security: NO_PROMISE.some((r) => r.item.includes('等保')), + }, + /** 28 项口径出处:P0 全灰不绿,签字数必须为 0 */ + caliberTotal: caliberRows.length, + caliberP0: cs.p0, + caliberP1: cs.p1, + caliberP2: cs.p2, + caliberSigned: cs.signed, + caliberSensitivityKeys: cs.sensitivityKeys, + caliberNoneGreen: caliberRows.every((r) => r.tone !== 'muted' || r.priority !== 'P0') && caliberRows.every((r) => r.tone === 'neutral'), + caliberP0AllUnsigned: caliberRows.filter((r) => r.priority === 'P0').every((r) => !r.signedOff), + caliberP0Labelled: caliberRows.filter((r) => r.priority === 'P0').every((r) => r.statusLabel.includes('待 IE 签字')), + caliberAllSourced: caliberRows.every((r) => r.source.includes('附录 E')), + /** 4 项敏感性议题各自承载的口径项 */ + sensitivityIssues: Object.entries(SENSITIVITY_ISSUES).map(([k, v]) => ({ key: k, label: v.label, items: [...v.items] })), + sensitivityIssueCount: Object.keys(SENSITIVITY_ISSUES).length, + /** 三套「六」分类:成员数都必须是 6,且键不重复 */ + sixCount: six.length, + sixMemberCounts: six.map((r) => r.members.length), + sixKeysUnique: new Set(six.map((r) => r.key)).size === six.length, + sixIdentityFlags: six.map((r) => ({ key: r.key, hasIdentity: r.hasIdentity })), + /** 六-3 的 20 条计划类事件与 3 个 null 键(两条独立断言,不写成「null 项数=20」) */ + grossNullKeys: es.nullBucketKeys, + grossNullEvents: es.nullBucketEvents, + grossBucketedEvents: es.bucketedEvents, + grossCountSum: GROSS_CATEGORIES.reduce((a, g) => a + GROSS_CATEGORY_COUNT[g], 0), + /** 六-2 POC 时间账:照录不改,合计与差 1 日必须显式披露 */ + asltPocRows: ASLT_TIME_ACCOUNT_POC.length, + asltPocSumHours: +ASLT_TIME_ACCOUNT_POC.reduce((a, r) => a + r.hours, 0).toFixed(2), + asltPocSumPct: +ASLT_TIME_ACCOUNT_POC.reduce((a, r) => a + r.pct, 0).toFixed(2), + asltTotalHours: ASLT_ACCOUNT_TOTAL_HOURS, + asltWaitPlanPct: ASLT_WAIT_PLAN_PCT, + asltDayGapDisclosed: ASLT_DAY_GAP_NOTE.includes('差 1 日待甲方确认'), + /** 同名不同口径读数:三标签必须齐全 */ + readingCount: CONFLICT_READINGS.length, + readingsAllThreeLabels: CONFLICT_READINGS.every((r) => r.scope.length > 0 && r.window.length > 0 && r.caliber.length > 0), + /** SRF 三值与 FT 三套范围都必须在表里 */ + srfThreeValues: ['25.50%', '57.2%', '29.84%'].every((v) => CONFLICT_READINGS.some((r) => r.region === 'SRF' && r.value === v)), + ftThreeScopes: ['81.69%', '81.90%', '82.12% → 78.59%'].every((v) => CONFLICT_READINGS.some((r) => r.region === 'FT' && r.value === v)), + asltDualCaliber: CONFLICT_READINGS.filter((r) => r.region === 'ASLT').length >= 2, + /** 三站 POC 锚点 */ + pocAnchorCount: POC_ANCHORS.length, + pocAnchorRegions: POC_ANCHORS.map((a) => a.region), + pocLabel: POC_BASELINE_LABEL, + pocNotVerifiedDisclosed: POC_NOT_VERIFIED_NOTE.includes('未独立复核'), + /** W0 阻塞项与追问 */ + blockerCount: W0_BLOCKERS.length, + blockerSelfSolvable: W0_BLOCKERS.filter((b) => b.selfSolvable).map((b) => b.id), + questionCount: W0_QUESTIONS.length, + questionsAllSourced: W0_QUESTIONS.every((q) => q.source.length > 0), + /** 数据来源标注 */ + sourceRowCount: sources.length, + sourceRowsAllTagged: sources.every((r) => r.tag.length > 0), + simulatedRowCount: sources.filter((r) => r.simulated).length, + gapRowCount: sources.filter((r) => r.gap !== null).length, + evidenceTags: EVIDENCE_LEDGER.map((e) => e.tag), + /** 断言登记表:11 条 + 2 附加 = 13 脚本,另加聚合入口 = 14 文件 */ + assertionCount: ASSERTION_REGISTRY.filter((a) => a.kind === 'assertion').length, + extraCheckCount: ASSERTION_REGISTRY.filter((a) => a.kind === 'extra').length, + registryScriptCount: ASSERTION_REGISTRY.length, + registryScriptsUnique: new Set(ASSERTION_REGISTRY.map((a) => a.script)).size === ASSERTION_REGISTRY.length, + registryAllInvariants: ASSERTION_REGISTRY.every((a) => a.invariant.length > 0 && a.stage.length > 0), + /** ①..⑪ 必须齐全且不重复 */ + assertionIds: ASSERTION_REGISTRY.filter((a) => a.kind === 'assertion').map((a) => a.id), + extraVerifyCount: EXTRA_VERIFY_SCRIPTS.length, + /** 13 + 附加 + 聚合 = 磁盘上应有的 .ts 文件数(由校验脚本用 readdirSync 对账) */ + expectedScriptFiles: ASSERTION_REGISTRY.length + EXTRA_VERIFY_SCRIPTS.length + 1, + aggregateScript: VERIFY_AGGREGATE, + verifyCommand: VERIFY_COMMAND, + verifyNote: VERIFY_NOTE, + gateCount: GATES.length, + gateIds: GATES.map((g) => g.id), + gatesAllCriteria: GATES.every((g) => g.criterion.length > 0 && g.onFail.length > 0), + /** 范围与模式:与服务层同源,不另写一份 */ + mode: 'demo' as const, + dataModeNote: dataModeNote(), + caliberVersion: CALIBER_CONFIG.version, + effectiveFrom: CALIBER_CONFIG.effectiveFrom, + anchorDevice: ANCHOR_DEVICE_ID, + seedDates: ss.dates, + dirtyDate: ss.dirtyDate, + signoffNote: PARAMS_SIGNOFF_NOTE, + coverageGap: ss.coverageGap, + deviceCount: DEVICES.length, + lineCount: LINES.length, + eventCount: EVENTS_48.length, + }; +} +/* ══════════════════════════════════════════════════════════════════ + * 附件判定矩阵修正清单(核验报告 §3 照录摘要) + * 矩阵=客户提供的参考口径;与独立重算不一致处逐条披露,不抹平。 + * ══════════════════════════════════════════════════════════════════ */ +export interface MatrixCorrectionRow { + no: number; + claim: string; + measured: string; + action: string; +} + +export const MATRIX_CORRECTION_NOTE = + '出处:docs/判定矩阵可计算性核验报告-2026-11-18.md §3(Python 独立重算留痕)。' + + '矩阵数字与实测不一致时以本清单为准;后端解析器口径已按「实测」列固化并配 golden 测试。'; + +export const MATRIX_CORRECTIONS: MatrixCorrectionRow[] = [ + { no: 1, claim: 'DEK 六组码计数、DPVS Wait_boat 8,039 标为「09-02 当日」', + measured: '实为 09-02~09-09 窗口累计(DEK 卡料当日实际 847 次,非 5,567 次)', + action: '引用一律改标「窗口累计」;当日与窗口两个口径分开出数' }, + { no: 2, claim: 'tab03 DEK 代表日为 09-02', + measured: '状态段首段时刻精确命中 09-03', + action: '代表日更正为 09-03' }, + { no: 3, claim: 'fuji 09-03 只有 27min(G-10 表述不完整)', + measured: '每日两份同名 db:当日目录是截断快照、次日目录是全天完整库(09-03 全天 29,411 行在 20260904/Dic1/)', + action: '解析器合并两副本并按 sha+id 去重;真缺档是 09-09 与 L8/MINI/MINI4' }, + { no: 4, claim: 'fuji「4,943 条 PRODEND 实为 1,241 块板」', + measured: '4,943 是 09-03 的 Module≠0 行数(当日板数 1,235);1,241 是 09-04 板数', + action: '两数各属一天,不得混用同日' }, + { no: 5, claim: 'ASLT START/PAUSE 绝对数 3,730/2,627', + measured: '实测 3,400/2,382(差约 9.7%、比例一致);folder 仅 07-01~07-31 共 31 文件', + action: '配对率 70.06% 结论不受影响;绝对数以解析器口径为准' }, + { no: 6, claim: 'KY 报警「6,800+ 条」', + measured: '条目级去重(DATE+内容)13,603 条唯一(原始 80,652 行、6 个累积副本)', + action: '去重必要性结论一致;绝对数以解析器口径为准' }, + { no: 7, claim: 'tab02「实测事件量」如 DEK 58,658', + measured: '归一化子集(按码字典映射后);21 个已确认码试算 33,473,方向一致', + action: 'stg 全量留痕 + cur 归一化子集双层存储,两口径都可出数、不混标' }, +]; + diff --git a/src/modules/tfamd-oee/data/oee/events48.ts b/src/modules/tfamd-oee/data/oee/events48.ts new file mode 100644 index 0000000..a67ba1c --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/events48.ts @@ -0,0 +1,225 @@ +/** + * 48 事件判定矩阵 —— 逐条转录《OEE智能优化平台改造规划书-2026-10-25.md》附录 C.2〔方案〕。 + * 原表来源:鼎捷方案附录 A(60 行,其中 12 行为同一事件在多条产线上的重复登记,去重后 48 个唯一事件)。 + * + * 完整性自检(三条都可由 eventStats() 现算复核): + * 1. 缺失编号恰为 12 个:S-03~07、S-17、S-21~22、S-35~38 → 60 − 12 = 48。 + * 2. 等级分布 A14 / B7 / C12 / D14 / E1 = 48(A+B=21 个完全自动化)。 + * ⚠ 区域拆分按**逐事件统计**:SRF A2/B7/C12/D10/E1、FT A6/B0/C0/D2/E0、ASLT A6/B0/C0/D2/E0。 + * 鼎捷附录 A 的分布表区域数字与逐条等级对不上(规划书附录 H.11),事件字典页必须按逐事件等级着色。 + * 3. 六-3 归口用词计数:换型调整16 / 工程借用12 / 空转短停9 / 计划停机6 / 故障停机3 / 计划待料2 = 48。 + * 其中「工程借用+计划停机+计划待料」= 20 条属计划类时间,bucket 为 null,**不进六大损失**。 + * + * 表现形式(POINT 31 / INTERVAL 6 / DERIVED 11)的判定规则,本文件按规划书 4.3 的定义落地: + * - INTERVAL 6:Down(S-27/28)、Jam(S-30/31)、Setup(MFG)(S-15/16) 三对,带 pair_id 与间隙补全规则。 + * - DERIVED 11:时刻由**其他事件实例按规则算出**、不可人工编辑者 —— + * 全部 B 类 7 条(S-01/14/23/24/25/26/44,跨源配对推导)+ E 类 S-02(上下游事件推导) + * + C 类 S-20(起点+计划时长−理论换线,算术推算)+ A 类 S-29/S-32(logfile 时长抓取)。 + * 这 11 条的 acquisition 全为 AUTO/SEMI_AUTO,**无一 MANUAL**,与「不可人工编辑」自洽。 + * - POINT 31:其余单条记录 + 时间戳 + 证据。 + * ⚠ S-15/16/18 的「±5 分钟」是录入/接口时刻的**固定偏移**,不是从别的事件实例派生, + * 故 S-15/16 属 INTERVAL、S-18 属 POINT(S-18 在附录 C.2 里是 D 类录入台点选)。 + * §4.9 StepChain 的 n7_setup_ea_end kind=DERIVED 是**链节点种类**,与 EventForm 是两套枚举,不冲突。 + * + * 四种状态的原型取值规则(规划书 4.3 定义,逐条状态原表未给,按等级推导并在此声明): + * A/B → ACTIVE(采集侧即全自动);C → PENDING_SRC(随接口建设分批转自动); + * D → ACTIVE(录入台过渡手段,原型真实提交,但不纳入终态口径);E → PENDING_DEF(C11 口径未确认)。 + * NOT_APPLICABLE 是**按设备**的适用性状态(区域不匹配),不是字典里的第 49 条,见 statusForDevice()。 + */ +import { + GROSS_TO_BUCKET, BUCKET_FACTOR, + type EventDef, type EventForm, type GrossCategory, type Device, type EventDefStatus, type LossBucket, +} from '../../types/oee'; + +type Row = { + code: string; + name: string; + region: EventDef['region']; + triggerPoint: string; + source: string; + grade: EventDef['grade']; + gross: GrossCategory; + factorL1: string; + factorL2: string; + acquisition: EventDef['acquisition']; + form: EventForm; + alarmClass?: EventDef['alarmClass']; +}; + +/** 归属因子列原文为「—」者,是计划类时间,不进六桶(不是缺数据)。 */ +const PLAN = '—'; + +const ROWS: Row[] = [ + // ── SRF 32 条 ──────────────────────────────────────────────────────────── + { code:'S-01', name:'PM — 开始', region:'SRF', triggerPoint:'最后一个 lot 的 trackout 时间;通知 PM 前机台全部清空', source:'设备 Log(最后 lot trackout)', grade:'B', gross:'计划停机', factorL1:'计划停机', factorL2:'PM', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-02', name:'PM — 结束', region:'SRF', triggerPoint:'以前三个 boat 进入 reflow 的时间点为 PM 结束', source:'设备 Log(前三 boat 进 reflow)', grade:'E', gross:'计划停机', factorL1:'计划停机', factorL2:'PM', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-08', name:'NPI Engineering — 开始', region:'SRF', triggerPoint:'量产最后一个 lot unload OTA 为起点;换 sub/换电容按计划时长加 IE 余量', source:'OTA', grade:'C', gross:'工程借用', factorL1:'工程借用', factorL2:'NPI Engineering', acquisition:'AUTO', form:'POINT' }, + { code:'S-09', name:'NPI Engineering — 结束', region:'SRF', triggerPoint:'SMR 最后一个 lot unload OTA 为终点', source:'OTA;FUJI 设备 Log', grade:'C', gross:'工程借用', factorL1:'工程借用', factorL2:'NPI Engineering', acquisition:'AUTO', form:'POINT' }, + { code:'S-10', name:'SMR 借机 — 开始', region:'SRF', triggerPoint:'SMR Leader 与 Line Leader 现场确认机台与 OTA 清空', source:'OTA unload;MES lot trackout', grade:'C', gross:'工程借用', factorL1:'工程借用', factorL2:'SMR 借机', acquisition:'AUTO', form:'POINT' }, + { code:'S-11', name:'SMR 借机 — 结束', region:'SRF', triggerPoint:'现场确认清空后,加下个产品换线理论时间为结束点', source:'现场确认记录;MES lot trackout', grade:'D', gross:'工程借用', factorL1:'工程借用', factorL2:'SMR 借机', acquisition:'MANUAL', form:'POINT' }, + { code:'S-12', name:'Conversion 前期准备', region:'SRF', triggerPoint:'上个产品材料清空、下个产品材料备齐', source:'线体清空与齐套检查记录', grade:'D', gross:'换型调整', factorL1:'Set up loss', factorL2:'Conversion', acquisition:'MANUAL', form:'POINT' }, + { code:'S-13', name:'Conversion — 开始', region:'SRF', triggerPoint:'OTA 调 recipe(MDC 触发表单)与设备 Log 换型开始记录', source:'OTA recipe Log;设备 Log', grade:'C', gross:'换型调整', factorL1:'Set up loss', factorL2:'Conversion', acquisition:'AUTO', form:'POINT' }, + { code:'S-14', name:'Conversion — 结束', region:'SRF', triggerPoint:'与 Setup 共用判定点,以 Setup 开始时间为 Conversion 结束', source:'Setup 开始时间点', grade:'B', gross:'换型调整', factorL1:'Set up loss', factorL2:'Conversion', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-15', name:'Setup(MFG) — 开始', region:'SRF', triggerPoint:'Xray 图片保存时间 加 5 分钟', source:'Xray 图片保存时间', grade:'D', gross:'换型调整', factorL1:'Set up loss', factorL2:'Setup', acquisition:'MANUAL', form:'INTERVAL' }, + { code:'S-16', name:'Setup(MFG) — 结束', region:'SRF', triggerPoint:'第一盘炉后确认时间 加 5 分钟', source:'第一盘炉后确认时间', grade:'D', gross:'换型调整', factorL1:'Set up loss', factorL2:'Setup', acquisition:'MANUAL', form:'INTERVAL' }, + { code:'S-18', name:'Setup(EA) — 结束', region:'SRF', triggerPoint:'Xray 图片保存时间 减 5 分钟', source:'Xray 图片保存时间', grade:'D', gross:'换型调整', factorL1:'Set up loss', factorL2:'Setup', acquisition:'MANUAL', form:'POINT' }, + { code:'S-19', name:'PE 借机 — 开始', region:'SRF', triggerPoint:'APS 借机时间点为起点;量产延迟时以现场确认清空时间为起点', source:'APS;OTA;通知系统', grade:'C', gross:'工程借用', factorL1:'工程借用', factorL2:'PE 借机', acquisition:'AUTO', form:'POINT' }, + { code:'S-20', name:'PE 借机 — 结束', region:'SRF', triggerPoint:'实际借机起点 + 计划借机时长 − 理论换线时间', source:'APS 计划时长;通知系统', grade:'C', gross:'工程借用', factorL1:'工程借用', factorL2:'PE 借机', acquisition:'AUTO', form:'DERIVED' }, + { code:'S-23', name:'Run Dummy — 开始', region:'SRF', triggerPoint:'上个 lot 最后一个 boat 进 DPVS 后,加一个空 boat 进 DPVS 的时间点', source:'跨源事件配对', grade:'B', gross:'工程借用', factorL1:'工程借用', factorL2:'Run Dummy', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-24', name:'Run Dummy — 结束', region:'SRF', triggerPoint:'新 lot 开启 Datacon 的时间点', source:'跨源事件配对', grade:'B', gross:'工程借用', factorL1:'工程借用', factorL2:'Run Dummy', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-25', name:'Lot setup loss — 开始', region:'SRF', triggerPoint:'上个 lot 结束时间点,DPVS 最后一个 boat 之后放隔板再加 1 分钟固定时间', source:'OTA;设备 Log', grade:'B', gross:'换型调整', factorL1:'Set up loss', factorL2:'Lot setup loss', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-26', name:'Lot setup loss — 结束', region:'SRF', triggerPoint:'新 lot 开启 Datacon 的时间点', source:'OTA;设备 Log', grade:'B', gross:'换型调整', factorL1:'Set up loss', factorL2:'Lot setup loss', acquisition:'SEMI_AUTO', form:'DERIVED' }, + { code:'S-27', name:'Down — 开始', region:'SRF', triggerPoint:'OP 按灯或通知 EA 的时间点与 MT2 建 Down 事件,取最早可信时间', source:'按灯信号;口头通知;MT2 Down', grade:'C', gross:'故障停机', factorL1:'Down Time', factorL2:'Down', acquisition:'AUTO', form:'INTERVAL', alarmClass:'DOWN' }, + { code:'S-28', name:'Down — 结束', region:'SRF', triggerPoint:'EA 验证无异常并通知 OP 恢复,与 MT2 解 Down 配对', source:'口头通知;MT2 Down', grade:'C', gross:'故障停机', factorL1:'Down Time', factorL2:'维修等待', acquisition:'AUTO', form:'INTERVAL', alarmClass:'DOWN' }, + { code:'S-29', name:'Down — 时长抓取', region:'SRF', triggerPoint:'从 logfile 抓取本线瓶颈站 >5 分钟的停机起止', source:'设备 logfile', grade:'A', gross:'故障停机', factorL1:'Down Time', factorL2:'Down', acquisition:'AUTO', form:'DERIVED', alarmClass:'DOWN' }, + { code:'S-30', name:'Jam — 开始', region:'SRF', triggerPoint:'OP 口头通知 EA 的时间点', source:'OP/EA 口头通知记录', grade:'D', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'Jam time', acquisition:'MANUAL', form:'INTERVAL', alarmClass:'JAM' }, + { code:'S-31', name:'Jam — 结束', region:'SRF', triggerPoint:'EA 验证无异常并口头通知 OP', source:'OP/EA 口头通知记录', grade:'D', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'Jam time', acquisition:'MANUAL', form:'INTERVAL', alarmClass:'JAM' }, + { code:'S-32', name:'Jam — 时长抓取', region:'SRF', triggerPoint:'从 logfile 抓取本线瓶颈站 ≤5 分钟的停机起止', source:'设备 logfile', grade:'A', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'短停', acquisition:'AUTO', form:'DERIVED', alarmClass:'JAM' }, + { code:'S-33', name:'关机 — 开始', region:'SRF', triggerPoint:'APS 设置关机时点为基准,结合 OTA 与机台 Log 确认最后 lot unload 且清空', source:'APS(IE 维护);OTA', grade:'C', gross:'计划停机', factorL1:'计划停机', factorL2:'关机', acquisition:'AUTO', form:'POINT' }, + { code:'S-34', name:'关机 — 结束', region:'SRF', triggerPoint:'APS 设置开线时点为基准,结合 OTA 确认第一个 lot load', source:'APS(IE 维护);OTA', grade:'C', gross:'计划停机', factorL1:'计划停机', factorL2:'关机', acquisition:'AUTO', form:'POINT' }, + { code:'S-39', name:'计划待料 — 开始(APS 口径)', region:'SRF', triggerPoint:'APS 提供 plan idle(线、班次,精确到分钟);该时点机台未生产则取为起点', source:'APS;机台 Log;OTA', grade:'C', gross:'计划待料', factorL1:'计划待料', factorL2:'APS plan idle', acquisition:'AUTO', form:'POINT' }, + { code:'S-40', name:'计划待料 — 结束(APS 口径)', region:'SRF', triggerPoint:'APS plan idle;该时点机台在产则取为终点', source:'APS;机台 Log;OTA', grade:'C', gross:'计划待料', factorL1:'计划待料', factorL2:'APS plan idle', acquisition:'AUTO', form:'POINT' }, + { code:'S-41', name:'待料 — 开始(现场反馈口径)', region:'SRF', triggerPoint:'现场反馈事件起点,并填写跑不满的原因', source:'现场反馈记录', grade:'D', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'待料', acquisition:'MANUAL', form:'POINT' }, + { code:'S-42', name:'待料 — 结束(现场反馈口径)', region:'SRF', triggerPoint:'与起点同次反馈的终点时间,成对录入', source:'现场反馈记录', grade:'D', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'待料', acquisition:'MANUAL', form:'POINT' }, + { code:'S-43', name:'5S — 开始', region:'SRF', triggerPoint:'瓶颈岗位停机后,OP 通知 EA 开始 5S', source:'瓶颈岗位停机信号;OP 通知', grade:'D', gross:'计划停机', factorL1:'计划停机', factorL2:'5S', acquisition:'MANUAL', form:'POINT' }, + { code:'S-44', name:'5S — 结束', region:'SRF', triggerPoint:'以 EA 开始 Setup 的时间点为 5S 结束', source:'Setup 开始时间点', grade:'B', gross:'计划停机', factorL1:'计划停机', factorL2:'5S', acquisition:'SEMI_AUTO', form:'DERIVED' }, + + // ── FT 8 条 ────────────────────────────────────────────────────────────── + { code:'F-45', name:'Lab debug — 开始', region:'FT', triggerPoint:'工程发邮件至 IE 确认借机,与产线现场确认机台清空交付工程', source:'借机邮件;现场确认', grade:'D', gross:'工程借用', factorL1:'工程借用', factorL2:'Lab debug', acquisition:'MANUAL', form:'POINT' }, + { code:'F-46', name:'Lab debug — 结束', region:'FT', triggerPoint:'现场确认已切回借机前生产程序且完成 corr 验证', source:'现场确认;corr 验证结果', grade:'D', gross:'工程借用', factorL1:'工程借用', factorL2:'Lab debug', acquisition:'MANUAL', form:'POINT' }, + { code:'F-47', name:'换 lot — 开始(生产)', region:'FT', triggerPoint:'打印 prod summary、OTA unload 与最后一颗测试时间', source:'prod summary;OTA unload', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'换 lot', acquisition:'AUTO', form:'POINT' }, + { code:'F-48', name:'换 lot — 结束', region:'FT', triggerPoint:'新 lot load OTA 及第一颗测试开始时间', source:'OTA load;第一颗测试开始', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'换 lot', acquisition:'AUTO', form:'POINT' }, + { code:'F-49', name:'rescreen — 开始', region:'FT', triggerPoint:'打印 summary 且测试颗数 > lot 数量', source:'summary 打印记录', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'rescreen', acquisition:'AUTO', form:'POINT' }, + { code:'F-50', name:'rescreen — 结束', region:'FT', triggerPoint:'本次 rescreen 的 summary 打印时间', source:'summary 打印记录', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'rescreen', acquisition:'AUTO', form:'POINT' }, + { code:'F-51', name:'人员等待 — 开始', region:'FT', triggerPoint:'机台报警且需员工即时响应并影响测试', source:'机台报警日志', grade:'A', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'人员等待', acquisition:'AUTO', form:'POINT', alarmClass:'JAM' }, + { code:'F-52', name:'人员等待 — 结束', region:'FT', triggerPoint:'报警处理完且开始正常测试', source:'机台报警日志;测试恢复记录', grade:'A', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'人员等待', acquisition:'AUTO', form:'POINT', alarmClass:'JAM' }, + + // ── ASLT 8 条 ──────────────────────────────────────────────────────────── + { code:'A-53', name:'Lab debug — 开始', region:'ASLT', triggerPoint:'同 F-45', source:'借机邮件;现场确认', grade:'D', gross:'工程借用', factorL1:'工程借用', factorL2:'Lab debug', acquisition:'MANUAL', form:'POINT' }, + { code:'A-54', name:'Lab debug — 结束', region:'ASLT', triggerPoint:'同 F-46', source:'现场确认;corr 验证结果', grade:'D', gross:'工程借用', factorL1:'工程借用', factorL2:'Lab debug', acquisition:'MANUAL', form:'POINT' }, + { code:'A-55', name:'换 lot — 开始(生产)', region:'ASLT', triggerPoint:'同 F-47', source:'prod summary;OTA unload', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'换 lot', acquisition:'AUTO', form:'POINT' }, + { code:'A-56', name:'换 lot — 结束', region:'ASLT', triggerPoint:'同 F-48', source:'OTA load;第一颗测试开始', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'换 lot', acquisition:'AUTO', form:'POINT' }, + { code:'A-57', name:'rescreen — 开始', region:'ASLT', triggerPoint:'同 F-49', source:'summary 打印记录', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'rescreen', acquisition:'AUTO', form:'POINT' }, + { code:'A-58', name:'rescreen — 结束', region:'ASLT', triggerPoint:'同 F-50', source:'summary 打印记录', grade:'A', gross:'换型调整', factorL1:'Set up loss', factorL2:'rescreen', acquisition:'AUTO', form:'POINT' }, + { code:'A-59', name:'人员等待 — 开始', region:'ASLT', triggerPoint:'同 F-51', source:'机台报警日志', grade:'A', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'人员等待', acquisition:'AUTO', form:'POINT', alarmClass:'JAM' }, + { code:'A-60', name:'人员等待 — 结束', region:'ASLT', triggerPoint:'同 F-52', source:'机台报警日志;测试恢复记录', grade:'A', gross:'空转短停', factorL1:'Down Time + Waiting time', factorL2:'人员等待', acquisition:'AUTO', form:'POINT', alarmClass:'JAM' }, +]; + +/** 等级 → 字典状态(规则见文件头)。 */ +function statusOf(grade: EventDef['grade']): EventDefStatus { + if (grade === 'C') return 'PENDING_SRC'; + if (grade === 'E') return 'PENDING_DEF'; + return 'ACTIVE'; +} + +/** + * 48 事件定义。bucket 不手写,一律由 GROSS_TO_BUCKET 现推, + * 保证「六-3 归口用词」与「六-1 六大损失桶」两套分类永不打架。 + */ +export const EVENTS_48: EventDef[] = ROWS.map((r) => ({ + code: r.code, + name: r.name, + region: r.region, + grade: r.grade, + form: r.form, + status: statusOf(r.grade), + triggerPoint: r.triggerPoint, + source: r.source, + bucket: GROSS_TO_BUCKET[r.gross], + factorL1: r.factorL1, + factorL2: r.factorL2 === PLAN ? PLAN : r.factorL2, + acquisition: r.acquisition, + ...(r.alarmClass ? { alarmClass: r.alarmClass } : {}), + grossCategory: r.gross, +})); + +export const EVENT_BY_CODE: Record = Object.fromEntries( + EVENTS_48.map((e) => [e.code, e]), +); + +/** 按设备的适用性状态:区域不匹配 → NOT_APPLICABLE(不改字典本身的 48 条计数)。 */ +export function statusForDevice(def: EventDef, device: Device): EventDefStatus { + return def.region === device.region ? def.status : 'NOT_APPLICABLE'; +} + +/** 缺失编号(原表 60 行去重 12 行的校验锚点)。 */ +export const MISSING_CODES = [ + 'S-03','S-04','S-05','S-06','S-07','S-17','S-21','S-22','S-35','S-36','S-37','S-38', +]; + +/** 全部计数现算,页面与校验脚本都读这里,不写死任何统计数字。 */ +export function eventStats() { + const by = (key: (e: EventDef) => K) => { + const out = {} as Record; + for (const e of EVENTS_48) { + const k = key(e); + out[k] = (out[k] ?? 0) + 1; + } + return out; + }; + const gross = by((e) => e.grossCategory); + const nullKeys = (Object.keys(GROSS_TO_BUCKET) as GrossCategory[]).filter((k) => GROSS_TO_BUCKET[k] === null); + return { + total: EVENTS_48.length, + grade: by((e) => e.grade), + form: by((e) => e.form), + status: by((e) => e.status), + region: by((e) => e.region), + gross, + /** 六-3 → 六-1:null 键数(应为 3) */ + nullBucketKeys: nullKeys.length, + /** 这 3 个 null 键覆盖的事件条数(应为 20) */ + nullBucketEvents: EVENTS_48.filter((e) => e.bucket === null).length, + /** 落六桶的事件条数(应为 28) */ + bucketedEvents: EVENTS_48.filter((e) => e.bucket !== null).length, + /** 区域 × 等级交叉表(按逐事件统计,不按鼎捷分布表) */ + regionGrade: EVENTS_48.reduce>>((acc, e) => { + acc[e.region] ??= {}; + acc[e.region][e.grade] = (acc[e.region][e.grade] ?? 0) + 1; + return acc; + }, {}), + missingCodes: MISSING_CODES.length, + }; +} + +/** 因子字典一行:一级因子 → 二级因子 → 唯一归口桶 → 三率归属 → 承载事件码。 */ +export interface FactorDictRow { + factorL1: string; + factorL2: string; + bucket: LossBucket | null; + /** 桶归属的三率;计划类时间(bucket=null)不进六桶,factor 为 null。 */ + factor: 'A' | 'P' | 'Q' | null; + grossCategory: GrossCategory; + codes: string[]; + count: number; +} + +/** + * 因子字典(factor_def 域):由 48 事件字典现推,不另写一份。 + * 按 一级因子 + 二级因子 分组,桶由 GROSS_TO_BUCKET 现推、三率由 BUCKET_FACTOR 现推, + * 保证「六-3 归口用词」「六-1 六大损失桶」「A/P/Q 三率」三套分类永不打架。 + * 计划类时间(计划停机/计划待料/工程借用)bucket=null,进 PDT 或按 C06/C10 处理,不进六桶。 + */ +export function factorDictionary(): FactorDictRow[] { + const map = new Map(); + for (const e of EVENTS_48) { + const key = `${e.factorL1}||${e.factorL2}`; + const bucket = GROSS_TO_BUCKET[e.grossCategory]; + const row = map.get(key); + if (row) { + row.codes.push(e.code); + row.count += 1; + } else { + map.set(key, { + factorL1: e.factorL1, + factorL2: e.factorL2, + bucket, + factor: bucket ? BUCKET_FACTOR[bucket] : null, + grossCategory: e.grossCategory, + codes: [e.code], + count: 1, + }); + } + } + return [...map.values()]; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/improvement.ts b/src/modules/tfamd-oee/data/oee/improvement.ts new file mode 100644 index 0000000..8041f89 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/improvement.ts @@ -0,0 +1,159 @@ +/** + * 改善运营种子(W3-A):优先处理清单候选 + 改善任务骨架 + D 类待补录事件。 + * + * ★ 纯静态数据层:不含 IO / 时钟 / 随机。priorityScore 不在此写死—— + * 由 L3 oeeService.initialTasks() 用 priority.scorePriority 现算(断言⑧可解释)。 + * + * 候选真因来自三站 POC 的一致指向(组织与管理,而非设备维修): + * FT tray 类占损失时长 69.3% / SRF 计划+待机 49.1% / ASLT Wait+Plan 37.54%。 + * 十个因子 ∈[0,1]:A 套(SOW 直译)5 项 + B 套(鼎捷)5 项,两套并列可切换、默认 B。 + * ★ 标题/note 里的损失占比是真实 POC 锚点;十个因子是**合成演示判断值**(非实测), + * 刻意构造为 A/B 非退化:A lens(损失/产能)C1 居首、B lens(金额/频次/可改善性)C2 居首, + * 换权重 → 优先序翻转(C1↔C2),兑现建议书 §5.3 的现场对比(与断言⑧合成夹具同纪律)。 + * + * 任务骨架的 priorityScore 留空(Omit),candidateId 指向候选,供 L3 现算填分。 + * 时间戳一律固定字符串(引擎/种子禁 Date.now),by 为演示角色。 + */ +import type { PriorityItem } from '../../lib/oee/priority'; +import type { ImprovementTask } from '../../types/oee'; + +/** 优先处理清单候选(六项,覆盖三区域 + 锚点数据缺口)。 */ +export const PRIORITY_CANDIDATES: PriorityItem[] = [ + { + id: 'C1', title: 'FT tray 清盘不及时(tray 类占损失 69.3%)', region: 'FT', + note: 'POC:FT tray 类停机占损失时长 69.3%,属组织/管理而非设备维修', + factors: { + lossSeverity: 0.9, impactScope: 0.8, duration: 0.85, capacityLoss: 0.9, deliveryImpact: 0.7, + moneyImpact: 0.85, frequency: 0.9, trendWorsening: 0.6, improvability: 0.8, evidenceCompleteness: 0.9, + }, + }, + { + id: 'C2', title: 'SRF 排产计划缺口(计划+待机 49.1%)', region: 'SRF', + note: 'POC:SRF 计划+待机占 49.1%,APS 计划版本/班次目标量未签收', + // B 套(鼎捷:金额/频次/可改善性)刻意高于 C1:计划缺口每班复发、闲置瓶颈产能金额高、 + // APS 签收属流程治理可改善性高 → B lens 下 C2 居首;A lens(损失/产能)下 C1(tray 69.3%)居首。 + // 由此 A/B 切换产生非退化排序翻转(C1↔C2),兑现建议书「换权重→优先序变」的现场对比。 + factors: { + lossSeverity: 0.8, impactScope: 0.9, duration: 0.7, capacityLoss: 0.75, deliveryImpact: 0.8, + moneyImpact: 0.9, frequency: 0.95, trendWorsening: 0.75, improvability: 0.9, evidenceCompleteness: 0.8, + }, + }, + { + id: 'C3', title: 'ASLT 物料保障等待(Wait+Plan 37.54%)', region: 'ASLT', + note: 'POC:ASLT Wait+Plan 37.54%,改善顺序物料保障优先', + factors: { + lossSeverity: 0.75, impactScope: 0.8, duration: 0.8, capacityLoss: 0.7, deliveryImpact: 0.6, + moneyImpact: 0.7, frequency: 0.85, trendWorsening: 0.5, improvability: 0.75, evidenceCompleteness: 0.8, + }, + }, + { + id: 'C4', title: '换型标准化(Setup/Conversion 口径待 IE 定版)', region: 'SRF', + note: 'S-12/S-15/S-16 换型判定点依赖 Xray 图 ±5min,口径 C18 待签字', + factors: { + lossSeverity: 0.6, impactScope: 0.7, duration: 0.6, capacityLoss: 0.55, deliveryImpact: 0.5, + moneyImpact: 0.6, frequency: 0.6, trendWorsening: 0.4, improvability: 0.85, evidenceCompleteness: 0.7, + }, + }, + { + id: 'C5', title: 'DEK 开机不良补录缺口(D 类未录入)', region: 'SRF', + note: 'DEK 为 SRF-L1 锚点站;开机/过程不良拆分依赖录入台 D 类补录,未补录前证据完备度低', + factors: { + lossSeverity: 0.4, impactScope: 0.3, duration: 0.3, capacityLoss: 0.35, deliveryImpact: 0.2, + moneyImpact: 0.35, frequency: 0.5, trendWorsening: 0.3, improvability: 0.9, evidenceCompleteness: 0.4, + }, + }, + { + id: 'C6', title: 'FT 复测率偏高(Rescreen 拉低 Q)', region: 'FT', + note: 'Q=1−Rescreen×良率损失;复测系数 1.04 使 Q 损失放大', + factors: { + lossSeverity: 0.5, impactScope: 0.6, duration: 0.4, capacityLoss: 0.5, deliveryImpact: 0.4, + moneyImpact: 0.55, frequency: 0.65, trendWorsening: 0.45, improvability: 0.6, evidenceCompleteness: 0.8, + }, + }, +]; + +/** 改善任务骨架:priorityScore 由 L3 现算;candidateId 指向候选。 */ +export type TaskSeed = Omit & { candidateId: string }; + +export const TASK_SEEDS: TaskSeed[] = [ + { + // 演示 §5.4.4:缺 dueDate + verificationResult → 拒绝派发,停留待审核 + id: 'T1', candidateId: 'C1', state: 'PENDING_REVIEW', + title: 'FT tray 清盘节拍化(甲班试点)', + rootCauseEntity: { type: '人员班组', id: 'FT-甲班' }, causeClass: 'B', + evidenceChain: ['FT tray 类停机占损失 69.3%(POC 参考基线)', '事件族 S-41/S-42 待料成对记录'], + owner: 'MFG-王线长', expectedBenefit: { min: 200, max: 400, unit: 'min/月' }, + weightScheme: 'B', + history: [ + { state: 'DRAFT', at: '2026-09-03T08:00:00Z', by: 'IE-李工' }, + { state: 'PENDING_REVIEW', at: '2026-09-03T09:00:00Z', by: 'IE-李工', note: '证据链齐,待补四项必填' }, + ], + }, + { + // 四项齐备 → 可派发 + id: 'T2', candidateId: 'C3', state: 'PENDING_REVIEW', + title: 'ASLT 物料齐套预警(Wait 压缩)', + rootCauseEntity: { type: '物料批次', id: 'MAT-ASLT-0903' }, causeClass: 'B', + evidenceChain: ['ASLT Wait+Plan 37.54%(POC 参考基线)', 'WAIT 期间仅 3/12 Site 使能'], + owner: 'PC-物料组', dueDate: '2026-09-10', + expectedBenefit: { min: 150, max: 300, unit: 'min/月' }, + verificationResult: '连续 5 班 Wait 时长 <60min', + weightScheme: 'B', + history: [ + { state: 'DRAFT', at: '2026-09-03T08:30:00Z', by: 'IE-李工' }, + { state: 'PENDING_REVIEW', at: '2026-09-03T09:30:00Z', by: 'IE-李工' }, + ], + }, + { + // 已派发:SLA 已起算 + id: 'T3', candidateId: 'C2', state: 'DISPATCHED', + title: 'SRF 排产计划签收闭环', + rootCauseEntity: { type: '程序参数', id: 'APS-PLAN-v3' }, causeClass: 'C', + evidenceChain: ['SRF 计划+待机 49.1%(POC 参考基线)', 'APS 计划版本未签收(IF-06 缺口)'], + owner: 'PC-排产组', dueDate: '2026-09-12', + expectedBenefit: { min: 100, max: 250, unit: 'min/月' }, + verificationResult: '计划达成率连续 3 日 ≥95% 且欠产为 0', + weightScheme: 'B', + history: [ + { state: 'DRAFT', at: '2026-09-02T08:00:00Z', by: 'IE-李工' }, + { state: 'PENDING_REVIEW', at: '2026-09-02T09:00:00Z', by: 'IE-李工' }, + { state: 'DISPATCHED', at: '2026-09-02T10:00:00Z', by: 'IE-李工', note: '四项齐备,SLA 起算' }, + ], + }, + { + // 执行中 + id: 'T4', candidateId: 'C4', state: 'IN_PROGRESS', + title: '换型 Setup 判定点标准化', + rootCauseEntity: { type: '模具工装', id: 'XRAY-SETUP-01' }, causeClass: 'B', + evidenceChain: ['S-15/S-16 依赖 Xray 图 ±5min(C18 待签字)'], + owner: 'PE-换型组', dueDate: '2026-09-15', + expectedBenefit: { min: 80, max: 160, unit: 'min/月' }, + verificationResult: '换型时长标准差下降 ≥30%(连续 10 次换型)', + weightScheme: 'B', + history: [ + { state: 'DRAFT', at: '2026-09-01T08:00:00Z', by: 'IE-李工' }, + { state: 'PENDING_REVIEW', at: '2026-09-01T09:00:00Z', by: 'IE-李工' }, + { state: 'DISPATCHED', at: '2026-09-01T10:00:00Z', by: 'IE-李工' }, + { state: 'IN_PROGRESS', at: '2026-09-02T08:00:00Z', by: 'PE-换型组' }, + ], + }, +]; + +/** D 类待补录事件(真实事件码,grade=D 必须人工录入)。录入台 5M1E 七字段由此驱动。 */ +export interface DClassPending { + id: string; + eventCode: string; + device: string; + bizDate: string; + note: string; +} + +export const D_CLASS_PENDING: DClassPending[] = [ + { id: 'D-01', eventCode: 'S-41', device: 'DEK001', bizDate: '2026-09-03', note: '现场反馈待料起点,跑不满原因待填' }, + { id: 'D-02', eventCode: 'S-30', device: 'DEK001', bizDate: '2026-09-03', note: 'OP 口头通知 EA 的 Jam 起点,无自动时间戳' }, + { id: 'D-03', eventCode: 'S-15', device: 'DEK001', bizDate: '2026-09-03', note: 'Setup(MFG) 开始=Xray 图保存 +5min,需人工确认' }, + { id: 'D-04', eventCode: 'F-45', device: '93k178', bizDate: '2026-09-03', note: 'Lab debug 借机开始,借机邮件 + 现场确认' }, +]; + +/** 录入台演示角色(补录人自动写入,不可手填)。 */ +export const ENTRY_OPERATOR = 'IE-李工'; \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/integration.ts b/src/modules/tfamd-oee/data/oee/integration.ts new file mode 100644 index 0000000..7f6bd6e --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/integration.ts @@ -0,0 +1,358 @@ +/** + * 集成接口契约字典 —— 逐条转录《OEE智能优化平台改造规划书-2026-10-25.md》4.4.1~4.4.4〔方案〕 + * 与《OEE分析AI原型系统构建建议书-2026-11-12.md》4.7〔方案〕。 + * + * ★ 三条不可违反的诚实纪律(建议书 §1.3 不承诺清单 / 规划书 4.4.4): + * 1. **原型不接任何真实系统**。六通道全部为模拟适配器读本地种子;本页显示的是 + * IF-01~IF-12 的「契约 + 状态 + 过渡方案」,不是真实连接。所有接口 signoff 一律 + * 非「已签收」,不得假装联调通过。 + * 2. **三级实时性必须在 UI 上区分**,不能一律标「实时」。SOW 的「<200ms」只适用 L1 + * (规划书 H.7),原型不得在任何页面宣称全链路 <200ms。 + * 3. **拿不到接口怎么办**逐系统给答案(过渡方案 + 切换条件),这比「风险:日志格式 + * 与时效需确认」有用得多,直接回应 SOW 的 9 系统集成要求。 + * + * 本文件是**常量字典**,零 IO、不 import 引擎层;统计由 integrationStats() 现算不写死。 + */ + +/** 联调签收四态(规划书 4.4.4)。原型只有「过渡方案 / 未启动」两态,绝不出现「已签收」。 */ +export type IfSignoff = '已签收' | '联调中' | '过渡方案' | '未启动'; +/** 原型演示程度:seed=种子适配器已演示 / manual=录入台过渡(W3) / none=未启动。 */ +export type IfDemo = 'seed' | 'manual' | 'none'; +/** 三级实时性归属。会话级/事件级不属 L1~L3 实时模型,标 '—'。 */ +export type LatencyTier = 'L1' | 'L2' | 'L3' | '—'; + +export interface IfContract { + id: string; + name: string; + direction: string; + protocol: string; + /** 约定频率(原文) */ + frequency: string; + tier: LatencyTier; + idempotency: string; + owner: string; + /** 联调时点(生产阶段) */ + stage: 'P1' | 'P2' | 'P3'; + signoff: IfSignoff; + demo: IfDemo; + /** 原型实际用什么替代(诚实描述,不假装已接) */ + protoImpl: string; + /** 过渡方案:拿不到接口怎么办 */ + transition: string; + /** 切换条件:什么时候从过渡切到真实接口 */ + switchCondition: string; +} + +/** 12 接口契约。逐条转录规划书 4.4.3 表 + 4.4.4 过渡方案。 */ +export const IF_CONTRACTS: IfContract[] = [ + { + id: 'IF-01', name: 'OTA 换型与报警日志读取', direction: '客户→平台', + protocol: 'SMB/NFS 只读 + 增量扫描', frequency: '≤15min', tier: 'L2', + idempotency: '文件指纹去重,断点续扫', owner: '设备 PE', stage: 'P1', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'DEK 种子适配器读本地 EVENT.DAT(定宽 91 字符);OTA 真实接口未接', + transition: '先由事件录入台补录 Conversion/PM,接口就绪后切换', + switchCondition: '客户 IT 开放 OTA 只读目录 + 增量扫描指纹约定签收', + }, + { + id: 'IF-02', name: 'TestDash 测试产出查询', direction: '双向', + protocol: 'HTTPS REST + JSON + Token', frequency: '≤15min', tier: 'L2', + idempotency: '按 Lot+Site 幂等,失败重试 3 次后落异常表', owner: '测试工程', stage: 'P1', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'FT 种子含 lot_summary 产出/良率;TestDash REST 未接', + transition: '先以本地报表文件导入 FT 良率与 FTRD', + switchCondition: '测试工程提供 TestDash Token + Lot/Site 字段映射签收', + }, + { + id: 'IF-03', name: 'Tester Log 实时抓取', direction: '客户→平台', + protocol: '目录监听 + 数据库只读视图', frequency: '1~5s', tier: 'L1', + idempotency: '行级偏移记录,重放不重复计数', owner: '测试工程', stage: 'P1', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'FT/ASLT 种子适配器读本地文本报告;目录监听未接', + transition: '先以本地 Tester 报告文件导入,按行级偏移去重', + switchCondition: '测试工程开放只读视图 + 行级偏移约定签收', + }, + { + id: 'IF-04', name: 'Handler 上下料与 Tray 状态', direction: '双向', + protocol: 'SECS-GEM(HSR/SECS-II)或文件', frequency: '1~5s', tier: 'L1', + idempotency: '消息序列号去重,断线按时间窗补齐', owner: '设备 PE', stage: 'P2', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'FT Handler CSV(GBK) 种子适配器;SECS-GEM 通道未开放', + transition: '未开放通道的机型以厂商私有日志解析实现', + switchCondition: '设备厂商开放 SECS/GEM(甲方侧高风险项)+ 序列号去重签收', + }, + { + id: 'IF-05', name: 'MT2 报警与 Andon 状态', direction: '客户→平台', + protocol: 'WebSocket 订阅 + REST 补查', frequency: '1~5s', tier: 'L1', + idempotency: '以 alarmId 幂等,重复推送合并', owner: '设备 PE', stage: 'P2', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'DEK 种子含 Down/Jam 事件码;MT2 WebSocket 未接', + transition: '先以设备日志 + 录入台补录 Down/Jam(录入台 W3 落地)', + switchCondition: '设备团队开放 MT2 订阅 + alarmId 幂等约定签收', + }, + { + id: 'IF-06', name: 'APS 排产与标准产能', direction: '客户→平台', + protocol: '中间库只读 / REST', frequency: '≤15min', tier: 'L2', + idempotency: '版本号比对,只增不改', owner: '生产计划', stage: 'P1', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'FT_DAY_PLANS 种子提供计划版本;APS 中间库未接', + transition: '先人工录入计划版本(计划 idle 与计划达成率取数)', + switchCondition: '计划部门开放中间库只读 + 版本号比对约定签收', + }, + { + id: 'IF-07', name: 'EMO 安全回路与保养工单', direction: '客户→平台', + protocol: 'REST + 数据库', frequency: '1~5s', tier: 'L1', + idempotency: '安全事件双写审计表,不可覆盖', owner: 'EHS/设备 PE', stage: 'P2', + signoff: '未启动', demo: 'none', + protoImpl: '无 EMO 种子;安全紧急停机事件未采集', + transition: '先由设备报警日志 + 录入台补录(需 EHS 与设备授权)', + switchCondition: 'EHS 授权 + 安全事件双写审计表约定签收', + }, + { + id: 'IF-08', name: 'MES 工单与 Lot 流转', direction: '双向', + protocol: '文件/中间库/REST', frequency: '≤15min', tier: 'L2', + idempotency: '按 Lot 状态机校验,乱序自动重排', owner: '制造 IT', stage: 'P1', + signoff: '过渡方案', demo: 'seed', + protoImpl: 'FT/ASLT 自包含 Lot;SRF Lot 由锚点反推;MES 未接', + transition: '先用 FT/ASLT 自包含 Lot 数据,其他区域按批次人工归因', + switchCondition: '制造 IT 开放 Lot 流转 + 状态机校验约定签收', + }, + { + id: 'IF-09', name: 'HR 班组与技能等级', direction: '客户→平台', + protocol: 'REST/文件/中间库', frequency: '班次级', tier: 'L3', + idempotency: '按班次快照留存,历史不回填', owner: 'HR/生产', stage: 'P2', + signoff: '未启动', demo: 'none', + protoImpl: '班次为演示假设(3×8h);HR 名单/技能等级未接', + transition: '先在主数据维护人员名单与岗位技能等级', + switchCondition: '人力授权 + 技能等级来源明确 + 班次快照约定签收', + }, + { + id: 'IF-10', name: '统一身份认证与门户跳转', direction: '双向', + protocol: 'OAuth 2.0 / OIDC', frequency: '会话级', tier: '—', + idempotency: '令牌续期,失败退回独立登录', owner: '制造 IT', stage: 'P1', + signoff: '未启动', demo: 'none', + protoImpl: '原型无登录/权限/审计;OAuth2/OIDC 未接', + transition: '生产 P4 接 SSO/AD + RBAC + 最小权限 + 数据范围', + switchCondition: '制造 IT 提供 OIDC 客户端 + 令牌续期约定签收', + }, + { + id: 'IF-11', name: '消息推送(企微/钉钉)', direction: '平台→客户', + protocol: '群机器人/工作通知 API', frequency: '事件级', tier: '—', + idempotency: '同一告警 5 分钟内合并,避免刷屏', owner: '制造 IT', stage: 'P2', + signoff: '未启动', demo: 'none', + protoImpl: '原型无企微/钉钉推送;告警仅在右栏内存日志', + transition: '生产 P2 接群机器人,同一告警 5 分钟内合并', + switchCondition: '制造 IT 提供机器人 Webhook + 合并窗口约定签收', + }, + { + id: 'IF-12', name: '归档存储读写', direction: '内部', + protocol: 'S3 兼容对象存储 API', frequency: '日批', tier: 'L3', + idempotency: '冷数据回捞按对象版本号定位', owner: '乙方', stage: 'P3', + signoff: '未启动', demo: 'none', + protoImpl: '数据在浏览器内存/SQLite WASM;S3 对象存储未接', + transition: '生产 P3 接对象存储 + Parquet 冷归档(~2TB/年,14 年)', + switchCondition: '乙方对象存储就位 + 对象版本号回捞约定签收', + }, +]; + +export const IF_BY_ID: Record = Object.fromEntries(IF_CONTRACTS.map((c) => [c.id, c])); + +/** 六条采集通道(规划书 4.4.1 / 建议书 4.7.1)。原型全部为模拟适配器或契约占位。 */ +export interface CollectionChannel { + name: string; + protocol: string; + frequency: string; + coverage: string; + tier: LatencyTier; + /** 原型实现:seed=读本地种子 / contract=契约占位 / manual=真实可提交(W3) */ + proto: 'seed' | 'contract' | 'manual'; + protoImpl: string; + /** 需加装硬件的通道显式标注,不假装已采集 */ + needsHardware?: boolean; +} + +export const CHANNELS: CollectionChannel[] = [ + { + name: '文件采集', protocol: 'SMB/NFS + 增量扫描 + 指纹', frequency: '5~15min', + coverage: '11 类设备', tier: 'L2', proto: 'seed', + protoImpl: '读本地种子文件(DEK EVENT.DAT / FT Handler CSV / ASLT 文本流)', + }, + { + name: '数据库直连', protocol: 'JDBC', frequency: '1~5min', + coverage: 'FUJI SQLite(过滤 Module=0 汇总行)', tier: 'L2', proto: 'seed', + protoImpl: '读种子 JSON;Module=0 汇总行过滤已在适配器陷阱中声明', + }, + { + name: 'REST/MQ', protocol: 'REST + Token / MQ', frequency: '分钟级', + coverage: 'OTA/APS/MT2/MES/TestDash', tier: 'L2', proto: 'contract', + protoImpl: '契约占位(IF-01/02/05/06/08),不显示真实连接', + }, + { + name: 'IO/三色灯', protocol: 'Modbus TCP / OPC UA', frequency: '秒级', + coverage: 'Loader/分轨机/绿皮机(无日志)', tier: 'L1', proto: 'contract', + protoImpl: '契约占位 + 标「需加装」;过渡期靠人工录入', needsHardware: true, + }, + { + name: '人工录入', protocol: 'Web/PDA', frequency: '实时', + coverage: '14 个 D 类事件,≤15min/班', tier: 'L1', proto: 'manual', + protoImpl: '真实可提交(断言⑥,录入台 W3-A 落地);当前字典已就位', + }, + { + name: '文件监控', protocol: 'mtime 触发', frequency: '5min', + coverage: 'Xray(无接口)', tier: 'L2', proto: 'contract', + protoImpl: '契约占位;mtime 不等于生产时刻,只作采集触发信号', + }, +]; + +/** 三级实时性(建议书 4.7.4)。原型必须在 UI 上区分,不能一律标「实时」。 */ +export interface LatencyTierDef { + tier: 'L1' | 'L2' | 'L3'; + label: string; + latency: string; + coverage: string; + prodImpl: string; + protoImpl: string; +} + +export const LATENCY_TIERS: LatencyTierDef[] = [ + { + tier: 'L1', label: '流式', latency: '1~5 秒', + coverage: '状态变化、停机、卡料、报警、看板与告警', + prodImpl: '消息队列 + 流式计算', protoImpl: '无(原型不需要流式;告警为内存日志)', + }, + { + tier: 'L2', label: '批量', latency: '≤15min', + coverage: '日志解析、因子时长、OEE 重算', + prodImpl: '定时批处理', protoImpl: '种子批跑(runDekDay 端到端,浏览器内现算)', + }, + { + tier: 'L3', label: '班次级', latency: '班后', + coverage: '报表、结算、口径校准', + prodImpl: '班次任务', protoImpl: '班次窗口切分(shiftsForDate,3×8h 演示假设)', + }, +]; + +/** ★ SOW 的「<200ms」只适用 L1(规划书 H.7)。原型不得宣称全链路 <200ms。 */ +export const LATENCY_200MS_NOTE = + 'SOW 的「<200ms」只适用 L1 流式(规划书 H.7);L2 批量 ≤15min、L3 班次级班后。原型不得在任何页面宣称全链路 <200ms。'; + +/** 适配器关键陷阱(建议书 4.7.2)。全厂 12 类适配器,此表列 8 项关键陷阱: + * 原型实现 3 个(DEK/FT/ASLT),其余 5 项显示契约与陷阱。类别全集以主数据台账为准。 */ +export interface AdapterTrap { + device: string; + trap: string; + correctHandle: string; + /** 原型是否已实现该适配器 */ + implemented: boolean; +} + +export const ADAPTER_TRAPS: AdapterTrap[] = [ + { device: 'DEK', trap: '定宽切片:日期[0:10] 时间[11:19] 事件码[20:25] 文本[26:71] 参数[71:91];31317/31318 是改钟事件', correctHandle: '按位切片;改钟事件跳过但记录偏移(DQ-01)', implemented: true }, + { device: 'FT Handler', trap: 'CSV GBK 编码;StopedTime > 300s = Down,≤ 300s = Jam', correctHandle: 'GBK→UTF-8 回退;300 秒分界(C08)', implemented: true }, + { device: 'ASLT Handler', trap: '报警行配对率仅 70%', correctHandle: '活跃窗口切分补足剩余 30%(>60min 间隔切窗)', implemented: true }, + { device: 'FUJI NXT', trap: 'Module=0 是汇总行', correctHandle: '必须过滤,否则事件翻倍', implemented: false }, + { device: 'kohyoung', trap: '累积式日志,9 个重复目录', correctHandle: '按增量偏移去重;间隙阈值必须 15min', implemented: false }, + { device: 'Jetting', trap: 'Current Program 每次 GO 重印', correctHandle: '检测值变化才取新值,否则同一程序被当成多次换型', implemented: false }, + { device: 'Datacon', trap: 'Lot 字段为空', correctHandle: '由排产计划 + 时间窗反推(五级级联归因)', implemented: false }, + { device: '回流焊', trap: 'UTF-16,无进出板信号', correctHandle: '由上下游工站事件配对推导(SRF 时间分配法)', implemented: false }, +]; + +/** LogAdapter 五方法(建议书 4.7.2)——采集层统一契约。 */ +export const LOG_ADAPTER_METHODS = [ + { method: 'parse(rawLine)', desc: '原始行 → ParsedEvent | null' }, + { method: 'normalize(e)', desc: 'ParsedEvent → EventInstance' }, + { method: 'dedupKey(e)', desc: '幂等去重主键' }, + { method: 'clockCorrect(ts)', desc: '时钟回跳校正,返回 corrected + offsetSec' }, + { method: 'evidenceRef(e)', desc: '证据引用:filePath + lineNo + digest' }, +] as const; + +/** 可靠性工程七条(建议书 4.7.3)。原型实现前四条,后三条标生产阶段。 */ +export interface ReliabilityMeasure { + n: number; + measure: string; + proto: '实现' | '生产'; + detail: string; +} + +export const RELIABILITY_MEASURES: ReliabilityMeasure[] = [ + { n: 1, measure: '增量拉取', proto: '实现', detail: '(size, mtime) 变化检测,滚动文件用首 1KB-md5 + 末行时间校验(种子含滚动文件样本)' }, + { n: 2, measure: '幂等重试', proto: '实现', detail: '指数退避 3 次 → pending 队列(内存队列)' }, + { n: 3, measure: '编码自适应', proto: '实现', detail: 'latin-1 回退,处理 GBK/UTF-16/UTF-8-BOM 混杂(种子含三种编码)' }, + { n: 4, measure: '时钟校正', proto: '实现', detail: '检测回跳,记录偏移,保证时间轴不重叠(DEK 一日 4 次改钟样本)' }, + { n: 5, measure: '反压控制', proto: '生产', detail: '峰值 200 次/秒,Kafka 削峰' }, + { n: 6, measure: '健康监控', proto: '实现', detail: '15 分钟内解析异常可见(治理台显示)' }, + { n: 7, measure: 'DQ 关闭率', proto: '生产', detail: 'DQ 关闭率 ≥80% 在 24h 内' }, +]; + +/** 接口异常处置五类(规划书 4.4.3)。 */ +export interface IfException { + category: string; + condition: string; + handling: string; + affectsOee: string; +} + +export const IF_EXCEPTIONS: IfException[] = [ + { category: '鉴权失效', condition: '连续 3 次 401/403', handling: '告警接口责任人,相关数据标注未采集', affectsOee: '否,保留上一版口径' }, + { category: '报文格式变更', condition: '解析失败率 >1%', handling: '自动切回上一版解析适配器并告警', affectsOee: '否' }, + { category: '数据延迟', condition: '超过约定频率 3 倍', handling: '页面标注延迟时长,不参与实时告警', affectsOee: '是,按延迟标注' }, + { category: '来源不可用', condition: '健康检查连续失败', handling: '转录入台补录,来源恢复后自动比对替换', affectsOee: '否' }, + { category: '重复推送', condition: '幂等键命中', handling: '丢弃并计数,不重复计入事件', affectsOee: '否' }, +]; + +/** 接口未就绪时的过渡方案十项(规划书 4.4.4)。逐系统回答「拿不到接口怎么办」。 */ +export interface TransitionPlan { + system: string; + dependsOn: string; + usage: string; + transition: string; +} + +export const TRANSITION_PLANS: TransitionPlan[] = [ + { system: 'OTA', dependsOn: '客户 IT + 设备部门', usage: 'Conversion、PM 事件自动采集', transition: '先由事件录入台补录,接口就绪后切换' }, + { system: 'APS', dependsOn: '客户 IT + 计划部门', usage: '计划 idle 与计划达成率取数', transition: '先人工录入计划版本' }, + { system: 'MT2/Andon', dependsOn: '客户 IT + 设备团队', usage: 'Down、Jam 事件实时检测', transition: '先以设备日志 + 录入台补录' }, + { system: 'MES/Camstar', dependsOn: '客户 IT', usage: '批次(Lot)归因', transition: '先用 FT/ASLT 自包含 Lot 数据,其他区域按批次人工归因' }, + { system: 'TestDash', dependsOn: '客户 IT + 测试工程', usage: 'FT 良率与 FTRD 取数', transition: '先以本地报表文件导入' }, + { system: 'Xray', dependsOn: '客户 IT + 质量工程', usage: '无损检测结果与质量因子', transition: '先以检测结果文件导入' }, + { system: 'EMO', dependsOn: '客户 IT,需 EHS 与设备授权', usage: '安全紧急停机事件与 EMO 时长', transition: '先由设备报警日志 + 录入台补录' }, + { system: 'HR', dependsOn: '客户 IT,需人力授权并明确技能等级来源', usage: '人员资质关联、录入权限分级', transition: '先在主数据维护人员名单与岗位技能等级' }, + { system: 'SECS-GEM', dependsOn: '客户 IT + 设备团队', usage: '支持机型状态与报警标准接入', transition: '未开放通道的机型以厂商私有日志解析实现' }, + { system: '回流焊进出板信号', dependsOn: '客户设备团队', usage: '回流焊工站板级时间对齐', transition: '以 SRF 时间分配法按上下游节拍拆分' }, +]; + +/** 联调签收标准(规划书 4.4.3)。 */ +export const SIGNOFF_STANDARD_NOTE = + '双方在约定时间窗内比对逐条记录一致;未签收的接口不进入 P2/P3 依赖项;接口变更同步更新契约表与清单,两处不得出现两个版本。'; + +/** 全部计数现算,页面与校验脚本都读这里,不写死任何统计数字。 */ +export function integrationStats() { + const bySignoff = (s: IfSignoff) => IF_CONTRACTS.filter((c) => c.signoff === s).length; + const byDemo = (d: IfDemo) => IF_CONTRACTS.filter((c) => c.demo === d).length; + const byTier = (t: LatencyTier) => IF_CONTRACTS.filter((c) => c.tier === t).length; + return { + total: IF_CONTRACTS.length, + signed: bySignoff('已签收'), + integrating: bySignoff('联调中'), + transition: bySignoff('过渡方案'), + notStarted: bySignoff('未启动'), + demoSeed: byDemo('seed'), + demoManual: byDemo('manual'), + demoNone: byDemo('none'), + tierL1: byTier('L1'), + tierL2: byTier('L2'), + tierL3: byTier('L3'), + tierOther: byTier('—'), + channels: CHANNELS.length, + channelSeed: CHANNELS.filter((c) => c.proto === 'seed').length, + channelContract: CHANNELS.filter((c) => c.proto === 'contract').length, + channelManual: CHANNELS.filter((c) => c.proto === 'manual').length, + needsHardware: CHANNELS.filter((c) => c.needsHardware).length, + adaptersImplemented: ADAPTER_TRAPS.filter((a) => a.implemented).length, + adaptersTotal: ADAPTER_TRAPS.length, + reliabilityImplemented: RELIABILITY_MEASURES.filter((r) => r.proto === '实现').length, + reliabilityTotal: RELIABILITY_MEASURES.length, + transitionPlans: TRANSITION_PLANS.length, + exceptions: IF_EXCEPTIONS.length, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/knowledge.ts b/src/modules/tfamd-oee/data/oee/knowledge.ts new file mode 100644 index 0000000..df258d7 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/knowledge.ts @@ -0,0 +1,312 @@ +/** + * 四语料知识库(建议书 4.5.1)——原型版,全部本地、零外部依赖。 + * + * ★ 失效规则比切片粒度更重要:过期知识被召回是幻觉的主要来源之一。 + * 每条 chunk 带 active 标志,retrieve() 只召回 active=true 的切片: + * - 故障码字典 CODE:覆盖率纳入季度体检;演示码表未确认者标 active 但 source 注明 DEMO。 + * - SOP:升版重新入库,旧切片 active=false 停止召回。 + * - 口径说明 CALIBER:与版本号绑定,禁止跨版本混合检索(retrieve 的 caliberVersion 过滤)。 + * - 历史改善案例 CASE:验证不通过 → active=false 标待复核,不参与召回。 + * + * ★ 诚实性:CODE/CALIBER/CASE 尽量从真实数据底座派生(EVENTS_48 / CALIBER_ITEMS / PRIORITY_CANDIDATES), + * 不另编一套与看板漂移的知识。SOP 为演示转录,逐条标 synthetic。 + * 另附 15 份与通富超威封装测试相关的公开资料(KB_DOCS),按资料转录成切片,source 逐条标注出处与 URL; + * 转录仍标 synthetic=true,不冒充客户内部知识库。 + * 所有切片 synthetic=true(断言⑪),不得冒充客户真实知识库。 + */ +import { EVENTS_48 } from './events48'; +import { DEK_CODE_META } from './dekCodes'; +import { CALIBER_ITEMS, CALIBER_VERSION } from './calibers28'; +import { PRIORITY_CANDIDATES } from './improvement'; +import { BUCKET_LABEL, type Corpus, type KnowledgeChunk } from '../../types/oee'; + +/* 契约类型在契约层定义(引擎 retrieval.ts 共用);此处再导出供数据层引用。 */ +export type { Corpus, KnowledgeChunk } from '../../types/oee'; +export type Chunk = KnowledgeChunk; + +/* ── 知识库输入资料(公开来源)────────────────────────────────────────── + * 语料页展示的「文件」:每类 3–4 份公开资料,切为下方 *DocChunks 入库。 + * 只收录公开可访问的规范/白皮书/官网/案例页;source 与 URL 逐条透明,不冒充客户文档。 */ +export interface KbDoc { + id: string; + corpus: Corpus; + title: string; + publisher: string; + date: string; + url: string; + /** 这份资料给语料贡献了什么 */ + note: string; + /** 点击资料时填入检索框的关键词(保证召回其切片) */ + query: string; +} + +export const KB_DOCS: KbDoc[] = [ + /* CODE —— 状态/等级/判据类码表(4 份) */ + { id: 'DOC-E10', corpus: 'CODE', title: 'SEMI E10 设备 RAM 与利用率定义', publisher: 'SEMI', date: '现行版', url: 'https://www.semi.org/en/Standards/CTR_031244', note: '六状态互斥、状态切换与 uptime 定义', query: 'E10 六状态' }, + { id: 'DOC-E79', corpus: 'CODE', title: 'SEMI E79 设备生产率定义', publisher: 'SEMI', date: '现行版', url: 'https://store-us.semi.org/products/e07900-semi-e79-specification-for-definition-and-measurement-of-equipment-productivity', note: '可用率/运行率/速率/质量四率因子', query: 'E79 四率' }, + { id: 'DOC-IPC610', corpus: 'CODE', title: 'IPC-A-610 BGA 空洞验收判据', publisher: 'IPC(HVT 解读)', date: '2024', url: 'https://www.hvttec.com/ipc-a-610-smt-solder-void-standards.html', note: '验收等级 Class 1/2/3 与单球空洞百分比', query: 'IPC-A-610 空洞' }, + { id: 'DOC-JSTD020', corpus: 'CODE', title: 'IPC/JEDEC J-STD-020 湿敏等级分类', publisher: 'IPC/JEDEC(Cofactr 解读)', date: '现行版', url: 'https://www.cofactr.com/articles/understanding-j-std-020', note: 'MSL 1–6 等级与车间寿命', query: 'MSL 湿敏等级' }, + + /* SOP —— 站位流程/处置规程(4 份) */ + { id: 'DOC-TFAMD', corpus: 'SOP', title: '通富超威槟城 封装与测试服务目录', publisher: 'TF-AMD', date: '官网现行', url: 'https://tf-amd.com.my/cn/', note: '十段后期流程:Bumping/FOED/CP/Assembly/BI/FT/SLT 等', query: 'TF-AMD 服务流程' }, + { id: 'DOC-TFME', corpus: 'SOP', title: '通富微电与 AMD 封测合资公告', publisher: '通富微电', date: '2015-10-17', url: 'https://www.tfme.com/news/400.html', note: 'FCBGA/FCPGA/FCLGA/MCM 封装族与产品线', query: 'FCBGA 封装族' }, + { id: 'DOC-JSTD033', corpus: 'SOP', title: 'IPC/JEDEC J-STD-033 湿敏器件处置', publisher: 'IPC/JEDEC', date: '现行版', url: 'https://www.navsea.navy.mil/Portals/103/Documents/NSWC_Crane/SD-18/Test%20Methods/jstd033.pdf', note: '防潮袋、拆封、车间寿命与烘烤条件', query: '拆封 烘烤 车间寿命' }, + { id: 'DOC-HARMONY', corpus: 'SOP', title: 'OEE for Semiconductor Manufacturing: E10 and E79', publisher: 'Harmony AI', date: '2025', url: 'https://www.tryharmony.ai/oee-for-semiconductor-manufacturing', note: '状态日志记录与工程时间口径的落地做法', query: '状态日志 工程时间' }, + + /* CALIBER —— 口径条款(3 份,切片仍绑 CALIBER_VERSION) */ + { id: 'DOC-CAL-E79', corpus: 'CALIBER', title: 'SEMI E79 四率与 OEE 连乘(口径条款)', publisher: 'SEMI', date: '现行版', url: 'https://store-us.semi.org/products/e07900-semi-e79-specification-for-definition-and-measurement-of-equipment-productivity', note: '四率公式与良品 die 口径', query: '四率 连乘 良品' }, + { id: 'DOC-CAL-E10', corpus: 'CALIBER', title: 'SEMI E10 六状态与 uptime(口径条款)', publisher: 'SEMI', date: '现行版', url: 'https://www.semi.org/en/Standards/CTR_031244', note: '六状态互斥与 uptime=生产+待机+工程', query: 'uptime 六状态' }, + { id: 'DOC-CAL-IPC', corpus: 'CALIBER', title: 'IPC-A-610 Class 2/3 空洞判级(口径条款)', publisher: 'IPC(HVT 解读)', date: '2024', url: 'https://www.hvttec.com/ipc-a-610-smt-solder-void-standards.html', note: '按单焊点判、界面空洞优先', query: '空洞 判级 单焊点' }, + + /* CASE —— 公开案例/拆解/论文(4 份) */ + { id: 'DOC-AMD-CHIPLET', corpus: 'CASE', title: 'AMD Chiplet 架构白皮书', publisher: 'AMD', date: '2023', url: 'https://www.amd.com/content/dam/amd/en/documents/solutions/technologies/chiplet-architecture-white-paper.pdf', note: 'KGD 与封装复杂度对良率的影响', query: 'Chiplet 良率 KGD' }, + { id: 'DOC-7950X3D', corpus: 'CASE', title: 'Ryzen 9 7950X3D 先进封装拆解', publisher: 'TechInsights', date: '2023', url: 'https://www.techinsights.com/blog/amd-ryzen-9-7950x3d-advanced-packaging-process-flow-analysis', note: '3D 堆叠与 TSV 键合工序', query: '3D 堆叠 TSV 键合' }, + { id: 'DOC-SIXSIGMA', corpus: 'CASE', title: '半导体厂 OEE 六西格玛改善案例', publisher: 'ResearchGate 论文', date: '2015', url: 'https://www.researchgate.net/publication/282939339_Improving_Overall_Equipment_Effectiveness_OEE_through_the_six_sigma_methodology_in_a_semiconductor_firm_A_case_study', note: 'DMAIC 损失分解与瓶颈挖潜', query: '六西格玛 OEE 案例' }, + { id: 'DOC-INFICON', corpus: 'CASE', title: '设备可用率与利用率辨析', publisher: 'Inficon', date: '2024', url: 'https://www.inficon.com/en/news/what-do-we-mean-when-we-refer-to-tool-availability', note: '可用率≠利用率,停机与待料分账', query: '可用率 利用率 停机' }, +]; + +/* ── 语料一:故障码字典(一码一条)───────────────────────────────────── + * 派生自 48 事件字典 + DEK 演示码表。客户 96 码全表未提供,DEK 码标 DEMO。 */ +const codeChunks: Chunk[] = [ + ...EVENTS_48.map((e): Chunk => ({ + id: `CODE-${e.code}`, + corpus: 'CODE', + title: `${e.code} ${e.name}`, + text: `${e.code} ${e.name} ${e.region} ${e.grossCategory} ${e.factorL1} ${e.factorL2} ` + + `判定时点 ${e.triggerPoint} 数据源 ${e.source} 等级 ${e.grade} 获取 ${e.acquisition}` + + (e.bucket ? ` 归口损失桶 ${BUCKET_LABEL[e.bucket]}` : ' 计划类时间不进六桶'), + active: true, + source: `派生自 48 事件字典 ${e.code}(规划书附录 C.2 转录)`, + synthetic: true, + })), + /* 改钟标记 31317/31318 不在此映射(与 DEK_CODE_MAP 同纪律): + 它们由下方两条 active=false 切片单独承载,避免 id 重复,且确保改钟标记永不召回为损失。 */ + ...DEK_CODE_META.filter((m) => m.target !== 'CLOCK_MARK').map((m): Chunk => ({ + id: `CODE-DEK-${m.code}`, + corpus: 'CODE', + title: `DEK 原始码 ${m.code} ${m.label}`, + text: `DEK 印刷机 原始事件码 ${m.code} ${m.label} 映射到 ${m.target} ${m.note}`, + active: true, + source: m.confirmed === 'POC' + ? `POC 确认码 ${m.code}(POC 附录 H)` + : `演示占位映射 ${m.code}(客户 96 码全表未提供,接入前必须替换)`, + synthetic: true, + })), + /* 改钟标记:必须跳过不入事件表〔POC〕。active=false 演示「无效码不召回为损失」。 */ + { + id: 'CODE-DEK-31317', corpus: 'CODE', title: 'DEK 31317 改钟标记', + text: 'DEK 31317 改钟标记 clock change 跳过 不入事件表', + active: false, source: 'POC 附录 H:31317/31318 为改钟标记', synthetic: true, + retiredReason: '改钟标记非损失事件,按 POC 纪律跳过,不参与损失召回', + }, + { + id: 'CODE-DEK-31318', corpus: 'CODE', title: 'DEK 31318 改钟标记', + text: 'DEK 31318 改钟标记 clock change 跳过 不入事件表', + active: false, source: 'POC 附录 H:31317/31318 为改钟标记', synthetic: true, + retiredReason: '改钟标记非损失事件,按 POC 纪律跳过,不参与损失召回', + }, + /* 公开资料转录:SEMI E10/E79 状态与效率因子、IPC-A-610 验收等级、J-STD-020 湿敏等级。 */ + { + id: 'CODE-DOC-E10-STATE', corpus: 'CODE', title: 'SEMI E10 设备六状态码', + text: 'SEMI E10 设备状态码 productive 生产 standby 待机 engineering 工程 scheduled down 计划停机 unscheduled down 非计划停机 non-scheduled 非排程 六状态互斥 同一时刻只归一个状态 事件码按占用时间归口', + active: true, source: 'SEMI E10 公开规范转录(semi.org/Standards/CTR_031244)', synthetic: true, + }, + { + id: 'CODE-DOC-E10-CLOCK', corpus: 'CODE', title: '状态切换与改钟标记', + text: 'SEMI E10 状态切换 时间戳 timestamp 状态段 duration 时钟回拨 时间跳变 改钟标记 31317 31318 不计入损失 数据质量 DQ 复核 状态段衔接', + active: true, source: 'SEMI E10 公开规范转录(semi.org/Standards/CTR_031244)', synthetic: true, + }, + { + id: 'CODE-DOC-E79-FACTOR', corpus: 'CODE', title: 'SEMI E79 四率因子码', + text: 'SEMI E79 效率因子 availability 可用率 operational 运行率 rate 速率 quality 质量 engineering time 工程时间 不得埋入 productive time 生产时间 良品按 die 统计 不按 wafer', + active: true, source: 'SEMI E79 公开规范转录(store-us.semi.org E07900)', synthetic: true, + }, + { + id: 'CODE-DOC-IPC-CLASS', corpus: 'CODE', title: 'IPC-A-610 验收等级码', + text: 'IPC-A-610 验收等级 Class 1 通用电子 Class 2 专用服务 Class 3 高可靠 BGA 焊球 void 空洞 面积占比 25% 单焊点 X-ray 抽检 界面空洞 更关键', + active: true, source: 'IPC-A-610 公开判据解读(hvttec.com)', synthetic: true, + }, + { + id: 'CODE-DOC-MSL', corpus: 'CODE', title: 'J-STD-020 湿敏等级码', + text: 'IPC/JEDEC J-STD-020 MSL 湿敏等级 MSL1 不限 MSL2 一年 MSL2a 四周 MSL3 168 小时 MSL4 72 小时 MSL5 48 小时 MSL5a 24 小时 MSL6 使用前必须烘烤 车间寿命 floor life', + active: true, source: 'IPC/JEDEC J-STD-020 公开解读(cofactr.com)', synthetic: true, + }, +]; + +/* ── 语料二:SOP(按工序与设备切片)───────────────────────────────────── + * 演示转录,逐条标 synthetic。含两条旧版(active=false)演示「升版停止召回」。 */ +const sopChunks: Chunk[] = [ + { id: 'SOP-01', corpus: 'SOP', title: 'DEK 印刷机 Down 响应 SOP', text: 'DEK 印刷机 Down 停机 5 分钟内响应 EQ MFG 到场确认 连续 DOWN 超阈值升级邮件 维修等待 二级因子', active: true, source: '演示转录·告警 S2 处置规程', synthetic: true }, + { id: 'SOP-02', corpus: 'SOP', title: 'DEK Jam 短停处理 SOP', text: 'DEK Jam 空转短停 ≤5min 自含区间 时长抓取 300 秒分界 待料 现场反馈', active: true, source: '演示转录·C08/C14 口径', synthetic: true }, + { id: 'SOP-03', corpus: 'SOP', title: 'Conversion 换型标准化 SOP', text: 'Conversion 换型 前期准备 材料清空 备齐 齐套检查 recipe OTA 调机 Setup 判定点 Xray 首张确认图', active: true, source: '演示转录·S-12/S-13/S-14', synthetic: true }, + { id: 'SOP-04', corpus: 'SOP', title: 'PM 交接与完工 SOP', text: 'PM 计划停机 交接单 完工单 最后 lot trackout 前三 boat 进 reflow 结束判定点 ENG Time', active: true, source: '演示转录·S-01/S-02', synthetic: true }, + { id: 'SOP-05', corpus: 'SOP', title: '计划待料登记 SOP', text: '计划待料 APS plan idle 精确到分钟 等待登记单 现场反馈待料 C09 判定标志', active: true, source: '演示转录·S-39/S-40/C09', synthetic: true }, + { id: 'SOP-06', corpus: 'SOP', title: '停机归因 5M1E 补录 SOP', text: '停机归因单 5M1E 人机料法环测 D 类事件 人工补录 未归因 IDLE 重算 口径版本递增', active: true, source: '演示转录·录入台 D 类补录', synthetic: true }, + { id: 'SOP-07', corpus: 'SOP', title: 'FT tray 清盘 SOP', text: 'FT tray 清盘 不及时 组织管理 非设备维修 占损失 69.3% 物料保障', active: true, source: '演示转录·POC FT tray 类', synthetic: true }, + { id: 'SOP-08', corpus: 'SOP', title: 'SRF 排产计划签收 SOP', text: 'SRF 排产计划 缺口 APS 计划版本 班次目标量 签收 计划待机 49.1%', active: true, source: '演示转录·POC SRF 计划+待机', synthetic: true }, + { id: 'SOP-09', corpus: 'SOP', title: 'ASLT 物料保障 SOP', text: 'ASLT 物料保障 等待 Wait Plan 37.54% 改善顺序 物料优先 排产计划 维修排最后', active: true, source: '演示转录·POC ASLT 时间账', synthetic: true }, + { id: 'SOP-10', corpus: 'SOP', title: '数据质量阻断处置 SOP', text: '数据质量 DQ-06 未归因占比 5% 阻断 结论暂缓发布 治理台 补录 当日闭环', active: true, source: '演示转录·DQ 治理规程', synthetic: true }, + { id: 'SOP-11', corpus: 'SOP', title: '改善任务派发 SOP', text: '改善任务 派发 四项必填 责任人 时限 预期收益区间 验证结果 待审核 已派发 六态', active: true, source: '演示转录·closure 四项必填', synthetic: true }, + { id: 'SOP-12', corpus: 'SOP', title: '口径变更管理 SOP', text: '口径变更 配置中心 版本号递增 旧版可回放 IE 签字 待签字 标灰不标绿', active: true, source: '演示转录·口径治理', synthetic: true }, + { id: 'SOP-13', corpus: 'SOP', title: 'NPI 工程借用 SOP', text: 'NPI Engineering 工程借用 借机 SMR 量产最后 lot unload OTA 换 sub 换电容 IE 余量', active: true, source: '演示转录·S-08/S-09/S-10', synthetic: true }, + { id: 'SOP-14', corpus: 'SOP', title: '开机不良补录 SOP', text: '开机不良 首件不良 数量来源 人工补录 非采集 过程不良 拆分 录入台 D 类', active: true, source: '演示转录·startupDefectQty', synthetic: true }, + { id: 'SOP-15', corpus: 'SOP', title: '班次 OEE 速览 SOP', text: '班次 OEE 速览 夜班 白班 中班 日级口径 班次筛选 报表导出', active: true, source: '演示转录·班次报表', synthetic: true }, + { id: 'SOP-16', corpus: 'SOP', title: '告警分级响应 SOP', text: '告警 五级 S1 安全 S2 非计划停机 S3 瓶颈偏移 S4 数据质量 S5 观察项 响应时限 升级', active: true, source: '演示转录·规划书 §5.5', synthetic: true }, + { id: 'SOP-17', corpus: 'SOP', title: '证据链下钻 SOP', text: '证据链 下钻 行号 lineNo 状态段 事件实例 任一层缺证据即停 转人工 补录', active: true, source: '演示转录·断言①血缘', synthetic: true }, + { id: 'SOP-18', corpus: 'SOP', title: '跨版本对比拒绝 SOP', text: '跨版本 对比 口径版本不一致 拒绝输出对比结论 顺序替代 ΔA ΔP ΔQ 同口径', active: true, source: '演示转录·断言⑩闸 3', synthetic: true }, + /* 旧版 SOP:升版后停止召回(演示失效规则)。 */ + { id: 'SOP-OLD-01', corpus: 'SOP', title: 'DEK Down 响应 SOP(旧版 v1)', text: 'DEK Down 停机 30 分钟响应 旧版 已废止', active: false, source: '演示转录·旧版', synthetic: true, retiredReason: '已升版为 SOP-01(5 分钟响应),旧切片停止召回' }, + { id: 'SOP-OLD-02', corpus: 'SOP', title: 'Jam 分界 SOP(旧版 v1)', text: 'Jam Down 分界 600 秒 旧版 已废止', active: false, source: '演示转录·旧版', synthetic: true, retiredReason: '已升版为 C08 统一 300 秒分界,旧切片停止召回' }, + /* 公开资料转录:TF-AMD 服务流程、封装族、X-ray 空洞判定、湿敏器件处置、状态日志。 */ + { + id: 'SOP-DOC-TFAMD-FLOW', corpus: 'SOP', title: 'TF-AMD 封装测试全流程 SOP(官方服务目录)', + text: 'TF-AMD 槟城 封装测试 服务流程 Bumping 凸点与背金 BSM FOED 扇出嵌入式芯片中介层 Chip Probe 晶圆测试 Wafer Sort Assembly 封装 Burn-In 老化 Final Test 成品测试 SLT 系统级测试 Back-end Inspection Packing 后端检测与包装 FA Reliability 失效分析可靠性 转站签核 首件确认', + active: true, source: 'TF-AMD 官网服务目录(tf-amd.com.my/cn/)', synthetic: true, + }, + { + id: 'SOP-DOC-TFME-PKG', corpus: 'SOP', title: 'FCBGA/FCPGA/FCLGA/MCM 封装族换型 SOP', + text: 'FCBGA FCPGA FCLGA MCM 封装族 CPU GPU APU 游戏主机芯片 先进封装占比 100% 2015 年 AMD 与通富微电 合资 封装族切换 recipe 与测试程序 同步 首件 X-ray 确认 换型 Setup 判定', + active: true, source: '通富微电合资公告(tfme.com/news/400.html,2015-10-17)', synthetic: true, + }, + { + id: 'SOP-DOC-IPC-XRAY', corpus: 'SOP', title: 'BGA 焊接空洞 X-ray 判定 SOP', + text: 'BGA 焊接空洞 X-ray 判定 SOP 隐藏焊点 必检 单球空洞面积 25% 合格 超过判缺陷 Class 3 更严 界面空洞 比中心空洞 更关键 DOE 参数窗口 Cp Cpk 抽检频次 复判', + active: true, source: 'IPC-A-610 判据解读(hvttec.com)', synthetic: true, + }, + { + id: 'SOP-DOC-JSTD033', corpus: 'SOP', title: '湿敏器件拆封/烘烤/车间寿命 SOP', + text: '湿敏器件 拆封 烘烤 车间寿命 SOP J-STD-033 防潮袋 MBB 湿度指示卡 HIC 拆封登记 车间寿命 floor life MSL3 168 小时 MSL2a 四周 MSL5 48 小时 MSL6 使用前必须烘烤 超时烘烤 按厂商推荐温度 回流前处理', + active: true, source: 'IPC/JEDEC J-STD-033 公开规范(navsea.navy.mil PDF)', synthetic: true, + }, + { + id: 'SOP-DOC-E10-LOG', corpus: 'SOP', title: '设备状态记录与工程时间 SOP', + text: '设备状态记录 SOP 六状态日志 状态切换时间戳 审核 engineering time 工程时间 不得埋入 productive time 生产时间 uptime 定义 与 OEE 口径一致 数据治理 DQ 未归因 当班闭环', + active: true, source: 'Harmony AI《OEE for Semiconductor Manufacturing》(tryharmony.ai)', synthetic: true, + }, +]; + +/* ── 语料三:口径说明(与版本号绑定,28 条)───────────────────────────── + * 派生自 CALIBER_ITEMS,version=CALIBER_VERSION。禁止跨版本混合检索。 */ +const caliberChunks: Chunk[] = Object.values(CALIBER_ITEMS).map((c): Chunk => ({ + id: `CALIBER-${c.id}`, + corpus: 'CALIBER', + title: `${c.id} ${c.name}`, + text: `${c.id} ${c.name} 默认值 ${String(c.defaultValue)} 归口 ${c.owner} 优先级 ${c.priority} ${c.note}` + + (c.signedOff ? ' 已签字' : ' 待 IE 签字'), + version: CALIBER_VERSION, + active: true, + source: `派生自口径项 ${c.id}(规划书附录 E,${CALIBER_VERSION})`, + synthetic: true, +})); + +/* 公开规范条款转录:仍绑 CALIBER_VERSION,与 28 条口径项同池、跨版本一起失效。 */ +const caliberDocChunks: Chunk[] = [ + { + id: 'CALIBER-DOC-E79-FOUR', corpus: 'CALIBER', title: 'E79 四率与 OEE 连乘', + text: '可用率 availability = uptime 除以 operations time 运行率 operational = productive 除以 uptime 速率 rate = 实际产出的理论时间 除以 productive time 质量 quality = 良品的理论时间 除以 实际产出的理论时间 OEE 四率连乘 良品按 die 统计 不按 wafer', + version: CALIBER_VERSION, active: true, + source: 'SEMI E79 公开规范转录(store-us.semi.org E07900)', synthetic: true, + }, + { + id: 'CALIBER-DOC-E79-TIME', corpus: 'CALIBER', title: '理论节拍 ICT 与良品分母', + text: '理论节拍 ICT 理论时间 = 理想节拍 乘以 产出数量 分母口径 良品 die 数量 速率损失 与 质量损失 分开归因 不合并 改善排序 先看分母口径', + version: CALIBER_VERSION, active: true, + source: 'SEMI E79 公开规范转录(store-us.semi.org E07900)', synthetic: true, + }, + { + id: 'CALIBER-DOC-E10', corpus: 'CALIBER', title: 'E10 六状态与 uptime 分母', + text: '六状态互斥 productive standby engineering scheduled down unscheduled down non-scheduled uptime = productive + standby + engineering operations time 排除 non-scheduled 工程借用 不计入可用率分母 状态日志 逐段可审计', + version: CALIBER_VERSION, active: true, + source: 'SEMI E10 公开规范转录(semi.org/Standards/CTR_031244)', synthetic: true, + }, + { + id: 'CALIBER-DOC-IPC610', corpus: 'CALIBER', title: 'BGA 空洞判级口径', + text: 'BGA 空洞判级 按单焊点判 不按整颗器件 单球空洞面积 25% 验收线 Class 2 个别情形 可放宽到约 30% Class 3 更严 批量均值 15% 到 20% 界面空洞 优先 功率器件 一级供应商 常按 10%', + version: CALIBER_VERSION, active: true, + source: 'IPC-A-610 Class 2/3 判据解读(hvttec.com)', synthetic: true, + }, +]; + +/* ── 语料四:历史改善案例(一案一条)───────────────────────────────────── + * 派生自优先清单候选。验证不通过者 active=false 标待复核,不参与召回。 */ +const caseChunks: Chunk[] = [ + ...PRIORITY_CANDIDATES.map((c): Chunk => ({ + id: `CASE-${c.id}`, + corpus: 'CASE', + title: c.title, + text: `${c.title} ${c.region ?? ''} ${c.note ?? ''} 改善案例 损失结构 收益区间`, + active: true, + source: `派生自优先清单候选 ${c.id}(POC 指向,参考基线)`, + synthetic: true, + })), + /* 补充案例:含两条验证不通过(active=false)演示「待复核不参与召回」。 */ + { id: 'CASE-X1', corpus: 'CASE', title: 'DEK 刮刀压力参数优化', text: 'DEK 刮刀压力 参数优化 程序参数 开机不良下降 收益区间 验证通过', active: true, source: '演示转录·改善案例', synthetic: true }, + { id: 'CASE-X2', corpus: 'CASE', title: 'SRF 缓冲容量调整', text: 'SRF 缓冲 容量调整 排产 等待下降 收益区间 验证通过', active: true, source: '演示转录·改善案例', synthetic: true }, + { id: 'CASE-X3', corpus: 'CASE', title: 'FT 测试程序节拍优化', text: 'FT 测试程序 节拍优化 速度损失 收益区间 验证通过', active: true, source: '演示转录·改善案例', synthetic: true }, + { id: 'CASE-X4', corpus: 'CASE', title: 'ASLT 换盘流程标准化', text: 'ASLT 换盘 流程标准化 门开换盘 在机判定 收益区间 验证通过', active: true, source: '演示转录·改善案例', synthetic: true }, + { id: 'CASE-OLD-01', corpus: 'CASE', title: '某停机改善(验证不通过)', text: '停机改善 验证不通过 待复核 收益未确认', active: false, source: '演示转录·待复核案例', synthetic: true, retiredReason: '验证结果不通过,标待复核,不参与召回(建议书 4.5.1)' }, + { id: 'CASE-OLD-02', corpus: 'CASE', title: '某换型改善(验证缺失)', text: '换型改善 验证缺失 待复核 收益未确认', active: false, source: '演示转录·待复核案例', synthetic: true, retiredReason: '验证结果缺失,标待复核,不参与召回(建议书 4.5.1)' }, + /* 公开资料转录:先进封装良率与设备效率类案例。 */ + { + id: 'CASE-DOC-SIXSIGMA', corpus: 'CASE', title: '半导体厂 OEE 六西格玛改善案例', + text: '半导体厂 OEE 六西格玛 改善案例 DMAIC 定义 测量 分析 改进 控制 损失分解 瓶颈设备 换型时间 小停机 良率 不扩产 挖潜 收益区间 验证 复盘', + active: true, source: 'ResearchGate 论文:Improving OEE through the six sigma methodology in a semiconductor firm', synthetic: true, + }, + { + id: 'CASE-DOC-CHIPLET', corpus: 'CASE', title: 'Chiplet 架构对封装良率的影响', + text: 'AMD Chiplet 架构 白皮书 chiplet 拆分 小裸片 良率 提升 已知合格裸片 KGD 先测后装 封装复杂度 2.5D 3D 互连 Infinity Fabric 成本 质量损失 风险分担', + active: true, source: 'AMD Chiplet 架构白皮书(amd.com PDF)', synthetic: true, + }, + { + id: 'CASE-DOC-7950X3D', corpus: 'CASE', title: '3D V-Cache 先进封装拆解', + text: 'Ryzen 9 7950X3D 先进封装 拆解 3D V-Cache 堆叠 TSV 硅通孔 键合 工序增加 返修不可行 良率风险 封装面积 热管理 失效分析', + active: true, source: 'TechInsights:7950X3D advanced packaging process flow analysis', synthetic: true, + }, + { + id: 'CASE-DOC-INFICON', corpus: 'CASE', title: '可用率与利用率辨析', + text: '设备可用率 与 利用率 辨析 tool availability 可用率反映 停机 计划维护 待料 利用率反映 需求 排产缺口 两者不能混用 产能瓶颈 判断 OEE 分母', + active: true, source: 'Inficon:what do we mean by tool availability', synthetic: true, + }, +]; + +export const CHUNKS: Chunk[] = [ + ...codeChunks, ...sopChunks, ...caliberChunks, ...caseChunks, + ...caliberDocChunks, +]; + +export const KNOWLEDGE_NOTE = + '四语料由两类输入组成(全部 synthetic=true,不冒充客户内部知识库):' + + '① 数据底座派生(EVENTS_48 / CALIBER_ITEMS / PRIORITY_CANDIDATES);② 15 份公开资料转录' + + '(SEMI E10/E79、IPC-A-610、J-STD-020/033、TF-AMD 官网与合资公告、AMD 白皮书等,source 逐条带出处)。' + + '失效规则在 retrieve() 生效:active=false 不召回、口径语料禁止跨版本混合检索。' + + '生产迁移路径:retrieve() 签名不变,内部换 Milvus,语料切片与失效规则完全复用。'; + +/** 知识库页自检:四语料计数、失效切片数、口径版本绑定。数字一律现算。 */ +export function knowledgeStats() { + const byCorpus: Record = { CODE: 0, SOP: 0, CALIBER: 0, CASE: 0 }; + for (const c of CHUNKS) byCorpus[c.corpus] += 1; + const retired = CHUNKS.filter((c) => !c.active); + return { + total: CHUNKS.length, + byCorpus, + active: CHUNKS.filter((c) => c.active).length, + retired: retired.length, + retiredAllReasoned: retired.length > 0 && retired.every((c) => !!c.retiredReason), + docCount: KB_DOCS.length, + /** 口径语料核心 28 条(公开条款转录另计,见 caliberDocCount) */ + caliberCoreCount: caliberChunks.length, + caliberDocCount: caliberDocChunks.length, + caliberAllVersioned: caliberChunks.length === 28 + && caliberChunks.every((c) => c.version === CALIBER_VERSION) + && caliberDocChunks.every((c) => c.version === CALIBER_VERSION), + allSynthetic: CHUNKS.length > 0 && CHUNKS.every((c) => c.synthetic === true), + idsUnique: new Set(CHUNKS.map((c) => c.id)).size === CHUNKS.length, + /** 季度体检三项指标的计算方式(原型显示当前值与算法,不承诺达标) */ + health: { + codeCoverage: 'CODE 活跃切片数 / 客户码表全表(96 码未提供,分母待定,不报覆盖率数字)', + recentCaseShare: '近 12 个月案例数 / 案例总数(演示案例无真实时间戳,不报占比数字)', + adoptionRate: '检索被采纳次数 / 检索总次数(问答引擎接入后由真实调用计数)', + }, + note: KNOWLEDGE_NOTE, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/metricTree.ts b/src/modules/tfamd-oee/data/oee/metricTree.ts new file mode 100644 index 0000000..6d3a534 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/metricTree.ts @@ -0,0 +1,379 @@ +/** + * OEE 指标树种子(替换原 IBP 经营指标树 · 实测 M5)。 + * + * ★ 三条纪律: + * ① **所有数字现算**:一律取自 L3 服务层 `oeeService`,本文件不写死任何指标值。 + * 服务层是断言②「四处读数一致」的实现点,指标树只是它的一个投影。 + * ② **不编造分级带宽**:28 条口径里没有任何一条定义红黄绿阈值带宽, + * 故 `alert_threshold = target`(达标/未达标二值),并在 desc 里明说。 + * 比率类目标取自**计划档**(附录 E 默认值,C27/C28 待 IE 签字)——不是客户确认口径。 + * ③ **结构项不当考核项**:CT/PDT/PPT/RUN 是恒等式核对用的口径量, + * value=target 只表示恒等成立,不代表"达标"。这些 code 列入 STRUCTURAL_CODES, + * UI 必须渲染为中性灰,不得显示绿色达标。 + * + * 范围:当前只有 DEK 锚点设备贯通日志→OEE 全链路。 + * SRF/FT/ASLT 三区域线体合成在 W2 接入,**此处不造区域节点充数**。 + * + * 层级:L0 OEE → L1 A/P/Q/时间 → L2 六桶 + 时间口径 → L3 事件驱动因子。 + * 回放轴:3 个业务日(种子覆盖范围),不是 12 个月——旧月轴只留给月度口径报告页。 + */ +import { + dekDays, currentDay, PARAMS_SIGNOFF_NOTE, type OeeDayResult, +} from '../../lib/oeeService'; +import { BUCKET_FACTOR, BUCKET_LABEL, LOSS_BUCKETS, type LossBucket } from '../../types/oee'; +import { EVENT_BY_CODE } from './events48'; +import { ANCHOR_DEVICE_ID, DEVICE_BY_ID } from './devices'; +import { CALIBER_CONFIG } from './calibers28'; + +/** 与 sqlite.ts 的 metric_node 插入顺序严格一致的 17 元组(末位 gap=G 缺口说明,无缺口为 '') */ +export type OeeNodeSeed = [ + code: string, zh: string, parent: string, level: number, dim: string, + value: number, target: number, unit: string, freq: string, alertTh: number, + alert: string, polarity: 'up' | 'down', weight: number, formula: string, + owner: string, descZh: string, gap: string, +]; + +export type OeeLinkSeed = [from: string, to: string, relation: string, strength: number]; + +export const METRIC_TREE_AS_OF = '2026-11-12'; + +/** 范围与口径披露:UI 必须原样展示,不得省略 */ +export const TREE_SCOPE_NOTE = + `指标树当前只覆盖锚点设备 ${ANCHOR_DEVICE_ID}(${DEVICE_BY_ID[ANCHOR_DEVICE_ID].name});` + + 'SRF/FT/ASLT 三区域线体合成待 W2 接入,未接入前不显示区域节点。'; +export const TREE_TARGET_NOTE = + `比率类目标取自计划档 OEE(${PARAMS_SIGNOFF_NOTE})。` + + '28 条口径未定义红黄绿带宽,故警戒线=目标线,只有达标/未达标二值。'; +export const TREE_WEIGHT_NOTE = + 'OEE 为乘法合成(A×P×Q),不做加权求和;weight 一律为 0,避免被误读成加权口径。'; + +/** 结构项(恒等式核对用,非考核 KPI)——UI 渲染中性灰,不显示达标绿 */ +export const STRUCTURAL_CODES = ['T-CT', 'T-PDT', 'T-PPT', 'T-RUN'] as const; + +/** 比率 → 百分数,保留两位;时长保持整秒,不做单位换算以免引入舍入漂移 */ +const pct = (x: number) => +(x * 100).toFixed(2); +const r2 = (x: number) => +x.toFixed(2); + +/** 二值定级:警戒线=目标线,故只有 green / red,不臆造 yellow 带宽 */ +function levelOf(value: number, target: number, polarity: 'up' | 'down'): string { + const better = polarity === 'down' ? value <= target : value >= target; + return better ? 'green' : 'red'; +} + +/** 事件族名:去掉「— 开始/— 结束/— 时长抓取」与括号补充,得到驱动因子的显示名 */ +function familyLabel(code: string): string { + const def = EVENT_BY_CODE[code]; + if (!def) return code; + return def.name + .replace(/\s*—\s*(开始|结束|时长抓取)\s*/g, '') + .replace(/([^)]*)/g, '') + .trim(); +} + +/* ── 逐日取值:同一套 code,每日重算 ─────────────────────────────────── */ + +/** 六桶 code */ +const bucketCode = (b: LossBucket) => `L-${b}`; + +/** + * L3 驱动因子:按**事件族**聚合配对时长,归到其所属桶。 + * 桶归属由 `buckets[].eventCodes` 反查,不在本文件另写一份映射表。 + * SPEED / 两 Q 桶由节拍偏差推导(derivedFromCycleDeviation),无成对事件 → 无 L3 子节点, + * 这是数据缺口而非 0,desc 里明说,不摊一个数充精度。 + */ +function driversOf(d: OeeDayResult): { code: string; label: string; bucket: LossBucket; sec: number; startCode: string }[] { + const codeToBucket = new Map(); + for (const b of d.buckets.buckets) for (const c of b.eventCodes) codeToBucket.set(c, b.bucket); + + const agg = new Map(); + for (const p of d.pairs) { + const bucket = codeToBucket.get(p.startCode); + if (!bucket) continue; // 不属于任何损失桶的配对(如计划待料)不建驱动节点 + const code = `E-${p.startCode}`; + const cur = agg.get(code); + if (cur) cur.sec += p.durationSec; + else agg.set(code, { code, label: familyLabel(p.startCode), bucket, sec: p.durationSec, startCode: p.startCode }); + } + return [...agg.values()].sort((a, b) => a.code.localeCompare(b.code)); +} + +/** 一个业务日的全部节点取值(code → value)。趋势与当期值共用此函数,保证同源。 */ +export function valuesOf(d: OeeDayResult): Record { + const t = d.tiers.actual; + const tot = d.segments.totals; + const v: Record = { + OEE: pct(t.oee), A: pct(t.a), P: pct(t.p), Q: pct(t.q), + // 时间结构节点的考核值=未解释时间(未采集 + 未归因),目标 0:干净日真为 0,脏日真超线 + TIME: tot.unknownSec + d.buckets.unattributedSec, + 'T-CT': tot.ctSec, 'T-PDT': tot.pdtSec, 'T-PPT': tot.pptSec, 'T-RUN': tot.runSec, + 'T-UNKNOWN': tot.unknownSec, 'T-IDLE': d.buckets.unattributedSec, + 'T-RESIDUAL': d.buckets.residualSec, + }; + for (const b of d.buckets.buckets) v[bucketCode(b.bucket)] = b.durationSec; + for (const dr of driversOf(d)) v[dr.code] = dr.sec; + return v; +} + +/** 目标值:比率取计划档,损失/驱动/未解释时间取 0,结构项取自身(恒等) */ +function targetsOf(d: OeeDayResult): Record { + const pl = d.tiers.planned; + const tot = d.segments.totals; + const t: Record = { + OEE: pct(pl.oee), A: pct(pl.a), P: pct(pl.p), Q: pct(pl.q), TIME: 0, + 'T-CT': tot.ctSec, 'T-PDT': tot.pdtSec, 'T-PPT': tot.pptSec, 'T-RUN': tot.runSec, + 'T-UNKNOWN': 0, 'T-IDLE': 0, 'T-RESIDUAL': 0, + }; + for (const b of LOSS_BUCKETS) t[bucketCode(b)] = 0; + for (const dr of driversOf(d)) t[dr.code] = 0; + return t; +} + +/* ── 节点定义:结构写在这里,数字全部来自 valuesOf / targetsOf ─────────── */ + +interface NodeSpec { + code: string; zh: string; parent: string; level: number; dim: string; + unit: string; polarity: 'up' | 'down'; formula: string; owner: string; desc: string; +} + +const SPECS: NodeSpec[] = [ + { + code: 'OEE', zh: '设备综合效率', parent: '', level: 0, dim: 'oee', unit: '%', polarity: 'up', + formula: 'A×P×Q = 良品数×ICT ÷ PPT', owner: 'IE', + desc: '三档共用同一分母 PPT=CT−PDT−UNKNOWN。目标取计划档 OEE。' + + '口径 C27/C28 属 P0 且待 IE 签字,未签字前不得当作客户确认口径。', + }, + { + code: 'A', zh: '时间稼动率', parent: 'OEE', level: 1, dim: 'factor', unit: '%', polarity: 'up', + formula: 'RT ÷ PPT', owner: 'IE', + desc: '运行时间占负荷生产时间之比。下挂故障停机/换型调整/空转短停三桶。' + + '目标取计划档 A=1−IE 月度计划停机率(C28,待 IE 签字)。', + }, + { + code: 'P', zh: '性能稼动率', parent: 'OEE', level: 1, dim: 'factor', unit: '%', polarity: 'up', + formula: 'N×ICT ÷ RT', owner: 'IE', + desc: '理想节拍产出占运行时间之比。下挂速度降低桶(由节拍偏差推导,无成对事件)。' + + '目标取计划档 P(C27 计划性能率,待 IE 签字)。', + }, + { + code: 'Q', zh: '良品率', parent: 'OEE', level: 1, dim: 'factor', unit: '%', polarity: 'up', + formula: '良品数 ÷ N', owner: 'PE', + desc: '下挂过程不良与开机不良两桶。目标取计划档 Q(C27 目标良率,待 IE 签字)。' + + '开机不良需首件检验数据,未采集到时计 0 并标缺口,不摊派。', + }, + { + code: 'TIME', zh: '未解释时间', parent: 'OEE', level: 1, dim: 'time', unit: 's', polarity: 'down', + formula: 'UNKNOWN(未采集)+ IDLE(未归因)', owner: 'PC', + desc: '考核值=未解释时间合计,目标 0。子节点给出 CT/PDT/PPT/RUN 分母口径与残差,供逐层核对恒等式。' + + '残差=PPT−良品数×ICT−Σ六桶,恒等于未归因时长;不为 0 即阻断发布(DQ-06)。', + }, +]; + +/** 六桶节点:归口父节点由 BUCKET_FACTOR 决定,不在本文件另写映射 */ +function bucketSpecs(): NodeSpec[] { + const ownerOf: Record = { + FAULT: 'EQ', CHANGEOVER: 'MFG', IDLE_MINOR: 'EQ', + SPEED: 'IE', PROCESS_DEFECT: 'PE', STARTUP_DEFECT: 'PE', + }; + const descOf: Record = { + FAULT: '故障停机(Down)。时长阈值按 C08 统一 300 秒分界,>300s 归 Down;权威时间按 C13 取最早可信时间。可下钻到事件与原始日志行号。', + CHANGEOVER: '换型调整(Conversion + Lot setup loss)。可下钻到事件族;换型链 StepChain 已在 W4-A 接入(任务中心)。', + IDLE_MINOR: '空转短停(Jam)。≤300s 归 Jam(C08/C14 按单次连续停机时长判定)。D 类人工录入事件已在 W3-A 录入台补齐。', + SPEED: '速度降低=RT−N×ICT,由节拍偏差推导,**无成对事件证据**,故不提供事件级下钻。这是推导量而非观测量,页面须标明。', + PROCESS_DEFECT: '过程不良=(N−良品数−开机不良数)×ICT,由节拍偏差推导,无成对事件证据。质量关联在二期 A5 接入 MES 良率后细化。', + STARTUP_DEFECT: '开机不良=首件不良数×ICT。首件检验数据未接入时计 0 并显式标缺口,**不得把过程不良摊进来充精度**。', + }; + return LOSS_BUCKETS.map((b) => ({ + code: bucketCode(b), zh: BUCKET_LABEL[b], parent: BUCKET_FACTOR[b], level: 2, dim: 'loss', + unit: 's', polarity: 'down' as const, + formula: b === 'SPEED' ? 'RT − N×ICT' + : b === 'PROCESS_DEFECT' ? '(N − 良品数 − 开机不良数)×ICT' + : b === 'STARTUP_DEFECT' ? '开机不良数×ICT' + : `Σ ${BUCKET_LABEL[b]} 状态段时长`, + owner: ownerOf[b], desc: descOf[b] + ' 目标 0(损失越少越好);分母口径为 PPT,不是 CT。', + })); +} + +/** 时间口径节点:结构项与考核项分开标注 */ +function timeSpecs(): NodeSpec[] { + const structural = (code: string, zh: string, formula: string, desc: string): NodeSpec => ({ + code, zh, parent: 'TIME', level: 2, dim: 'time', unit: 's', polarity: 'up', + formula, owner: 'PC', + desc: `【结构项·非考核 KPI】${desc} value=target 仅表示恒等式成立,不代表达标,UI 须渲染中性灰。`, + }); + return [ + structural('T-CT', '日历时间', '业务日 00:00 → 次日 00:00', 'CT=24h,是全部时间切分的总窗口(C24 跨天班次归属到事件开始时刻所在业务日)。'), + structural('T-PDT', '计划停机时间', 'Σ PLAN_STOP + Σ PM', 'PDT 从分母扣除。含计划待料(C09 命中 APS plan idle)与预防性维护(C06)。'), + structural('T-PPT', '负荷生产时间', 'CT − PDT − UNKNOWN', 'PPT 是理论/计划/实际三档**共用**的分母;换分母即换口径,跨版本对比默认拒绝。'), + structural('T-RUN', '运行时间', 'Σ RUN 状态段(生产锚点 lot 窗口)', 'RT 由产出锚点识别,不是"日志有行就算运行"。'), + { + code: 'T-UNKNOWN', zh: '未采集时间', parent: 'TIME', level: 2, dim: 'time', unit: 's', polarity: 'down', + formula: 'Σ UNKNOWN 状态段(日志断流窗口)', owner: 'EQ', + desc: '日志断流/未采集窗口,**不计入分母**(DQ-10 三态分开)。目标 0;不为 0 说明采集有缺口,须补采而不是估一个数。', + }, + { + code: 'T-IDLE', zh: '未归因时间', parent: 'TIME', level: 2, dim: 'time', unit: 's', polarity: 'down', + formula: 'Σ IDLE 状态段(超过间隙阈值仍无事件覆盖)', owner: 'IE', + desc: '与未采集严格分开:这是**采到了但归不了因**的空档。目标 0;占 PPT 超 5% 触发 DQ-06 阻断,结论暂缓发布。', + }, + { + code: 'T-RESIDUAL', zh: '六桶残差', parent: 'TIME', level: 2, dim: 'time', unit: 's', polarity: 'down', + formula: 'PPT − 良品数×ICT − Σ六桶时长', owner: 'IE', + desc: '恒等于未归因时长。第二个合法非零来源是超产(N×ICT>RT)把速度桶夹到 0,此时残差为负——**必须照实暴露,不得归一化抹平**。', + }, + ]; +} + +/** L3 事件驱动因子:结构由当日配对结果决定(有事件才有节点) */ +function driverSpecs(d: OeeDayResult): NodeSpec[] { + return driversOf(d).map((dr) => { + const def = EVENT_BY_CODE[dr.startCode]; + return { + code: dr.code, zh: dr.label, parent: bucketCode(dr.bucket), level: 3, dim: 'event', + unit: 's', polarity: 'down' as const, + formula: `Σ ${dr.label} 配对时长(事件码 ${dr.startCode}${def && def.form === 'INTERVAL' ? '/结束码' : ''})`, + owner: def?.region === 'SRF' ? 'EQ' : 'IE', + desc: `事件族「${dr.label}」,归口 ${BUCKET_LABEL[dr.bucket]}(C07 一级因子标准归属表)。` + + `自动化等级 ${def?.grade ?? '—'};可下钻到状态段与原始日志行号。目标 0。`, + }; + }); +} + +/* ── 对外:节点种子 / 趋势 / 关系边 ─────────────────────────────────── */ + +/** 当期(种子最后一天)节点种子。所有数字取自服务层,无一处写死。 + * ★ 非有限值不入库 NaN:value 记 0+gap 说明+定级 'gap', + * UI 见 gap 渲染「—」,绝不补 0/100% 冒充达标。 */ +export function oeeMetricNodes(): OeeNodeSeed[] { + const d = currentDay(); + const vals = valuesOf(d); + const tgts = targetsOf(d); + const specs = [...SPECS, ...bucketSpecs(), ...timeSpecs(), ...driverSpecs(d)]; + return specs.map((s) => { + const rawValue = vals[s.code] ?? 0; + const rawTarget = tgts[s.code] ?? 0; + const valueFinite = Number.isFinite(rawValue); + const targetFinite = Number.isFinite(rawTarget); + const value = valueFinite ? rawValue : 0; + const target = targetFinite ? rawTarget : 0; + const gap = valueFinite && targetFinite + ? '' + : 'G 缺口:后端无此因子数据源,不以 0/100% 冒充'; + return [ + s.code, s.zh, s.parent, s.level, s.dim, + value, target, s.unit, '日', target, + valueFinite && targetFinite ? levelOf(value, target, s.polarity) : 'gap', s.polarity, + 0, // OEE 乘法合成,不做加权求和(见 TREE_WEIGHT_NOTE) + s.formula, s.owner, s.desc, gap, + ] as OeeNodeSeed; + }); +} + +/** + * 逐日趋势:code → 3 个业务日的值。 + * ★ 不是 12 个月合成曲线——种子只有 3 天,造 12 期就是编数据。 + * 期标签由 oeeTime 的日轴给出,与 metric_trend.period 一致。 + * ★ 非有限值 → null:趋势表存 NULL、图表断线,不补 0 冒充。 + */ +export function oeeMetricTrends(): Record { + const days = dekDays(); + const perDay = days.map(valuesOf); + const codes = Object.keys(perDay[perDay.length - 1]); + const out: Record = {}; + for (const c of codes) { + out[c] = perDay.map((v) => { + const x = v[c] ?? 0; + return Number.isFinite(x) ? x : null; + }); + } + return out; +} + +/** 趋势期标签(业务日),与 oeeMetricTrends 的数组下标一一对应 */ +export function trendPeriods(): string[] { + return dekDays().map((d) => d.bizDate); +} + +/** + * 关系边:因子→OEE 用顺序替代贡献度,桶→因子用占 PPT 份额,驱动→桶用占桶份额。 + * strength 全部现算,不写死相关系数——原型没有统计拟合,编一个 r 值就是假证据。 + */ +export function oeeMetricLinks(): OeeLinkSeed[] { + const d = currentDay(); + const vals = valuesOf(d); + const ppt = d.segments.totals.pptSec || 1; + const delta = d.tiers.deltaPlannedToActual; + const absSum = Math.abs(delta.dA) + Math.abs(delta.dP) + Math.abs(delta.dQ) || 1; + const links: OeeLinkSeed[] = []; + + // 因子 → OEE:乘法合成,贡献度取计划→实际顺序替代的 |Δ| 占比 + // (缺 Q 源时 dQ 为 NaN → 记 0,贡献度只在有源因子间分配,不编一个 r 值) + const fin = (x: number) => (Number.isFinite(x) ? x : 0); + const contrib: Record = { A: fin(Math.abs(delta.dA)), P: fin(Math.abs(delta.dP)), Q: fin(Math.abs(delta.dQ)) }; + for (const f of ['A', 'P', 'Q']) { + links.push([f, 'OEE', 'drive', r2(contrib[f] / absSum)]); + } + // 时间结构 → 未解释时间:只有未采集/未归因/残差是它的构成项 + for (const c of ['T-UNKNOWN', 'T-IDLE']) { + links.push([c, 'TIME', 'drive', r2((vals[c] ?? 0) / (vals.TIME || 1))]); + } + links.push(['T-RESIDUAL', 'T-IDLE', 'monitor', 1]); // 恒等关系,强度 1 + links.push(['T-PPT', 'OEE', 'monitor', 1]); // 共用分母,恒等关系 + // 桶 → 因子:占 PPT 份额 + for (const b of d.buckets.buckets) { + links.push([bucketCode(b.bucket), b.factor, 'drive', r2(b.durationSec / ppt)]); + } + // 驱动 → 桶:占桶份额 + for (const dr of driversOf(d)) { + const bucketSec = vals[bucketCode(dr.bucket)] || 1; + links.push([dr.code, bucketCode(dr.bucket), 'drive', r2(dr.sec / bucketSec)]); + } + return links; +} + +/** 指标树自检:供校验脚本与"说明与对照"页引用 */ +export function metricTreeStats() { + const nodes = oeeMetricNodes(); + const trends = oeeMetricTrends(); + const links = oeeMetricLinks(); + const days = dekDays(); + const structural = nodes.filter((n) => (STRUCTURAL_CODES as readonly string[]).includes(n[0])); + return { + asOf: METRIC_TREE_AS_OF, + nodeCount: nodes.length, + linkCount: links.length, + byLevel: [0, 1, 2, 3].map((l) => nodes.filter((n) => n[3] === l).length), + periodCount: days.length, + periods: trendPeriods(), + trendCodes: Object.keys(trends).length, + /** 每个 code 的趋势长度必须等于业务日数,不允许补期 */ + trendLengthUniform: Object.values(trends).every((t) => t.length === days.length), + structuralCodes: structural.map((n) => n[0]), + /** 结构项必须 value===target,且不得被当成考核项 */ + structuralIdentityHolds: structural.every((n) => n[5] === n[6]), + /** 六桶归口父节点必须与 BUCKET_FACTOR 一致 */ + bucketParentCorrect: LOSS_BUCKETS.every((b) => { + const n = nodes.find((x) => x[0] === bucketCode(b)); + return n !== undefined && n[2] === BUCKET_FACTOR[b]; + }), + /** 驱动因子时长合计必须与所属桶对账(无重复计数、无遗漏) */ + driverReconciles: LOSS_BUCKETS.every((b) => { + const day = currentDay(); + const row = day.buckets.buckets.find((x) => x.bucket === b); + const drs = driversOf(day).filter((x) => x.bucket === b); + const sum = drs.reduce((a, x) => a + x.sec, 0); + const bucketSec = row?.durationSec ?? 0; + // 由节拍偏差推导的桶(SPEED / 两 Q 桶)没有成对事件 → 无驱动节点,合计必须为 0。 + // 这是数据缺口而非"对账失败",不得为了让检查通过而摊一个数出来。 + if (row?.derivedFromCycleDeviation) return drs.length === 0 && sum === 0; + return Math.abs(sum - bucketSec) < 1e-6; + }), + /** 推导桶清单:这些桶没有事件级下钻,页面必须标明是推导量 */ + derivedBuckets: currentDay().buckets.buckets + .filter((b) => b.derivedFromCycleDeviation).map((b) => b.bucket), + scopeNote: TREE_SCOPE_NOTE, + targetNote: TREE_TARGET_NOTE, + weightNote: TREE_WEIGHT_NOTE, + caliberVersion: CALIBER_CONFIG.version, + anchorDevice: ANCHOR_DEVICE_ID, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/resultMetrics.ts b/src/modules/tfamd-oee/data/oee/resultMetrics.ts new file mode 100644 index 0000000..f549f5c --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/resultMetrics.ts @@ -0,0 +1,188 @@ +/** + * 五类结果指标(规划书 3.3「第一类:结果有没有异常」)。 + * + * 五项固定为:计划达成率 | 欠产数量 | OEE | 良率 | 单位工时产出。 + * 不增项、不减项、不换口径——顶栏指标带与总览页共用本文件,保证断言②「四处读数一致」。 + * + * ★ 三条纪律: + * ① **数字只从 L3 服务层取**:OEE 与良率直接取 `tiers.actual`,与指标树 `valuesOf` + * 同一个来源、同一套百分数换算(×100 保留两位),不在视图里二次计算。 + * ② **缺口就是缺口,不编数**:计划达成率/欠产数量依赖**计划产量**,单位工时产出依赖**工时**。 + * 实测种子(DekSeedFile)与口径层(calibers28)**均无这两个字段**: + * 种子只有 intent(生成意图,明确标注"不是引擎输出,避免自证"), + * 口径层只有 C05 提到 ASLT 的理论/实际工时,而 ASLT 在 W1 未接入。 + * 规划书 6.x 已把「计划达成、欠产、工单进度」列为 **P1,依赖 IF-06/IF-08 签收**, + * APS 计划版本"先人工录入"。故这三项 value=null(**不是 0**), + * 并给出公式、缺失字段、依赖接口与做实阶段,标灰不标绿。 + * ③ **不拿相近量冒充**:不得用「理论产能达成率」冒充计划达成率, + * 不得用「设备小时产出 UPH」冒充单位工时产出(人工工时)——那是换口径,不是补数据。 + */ +import { currentDay, dayByDate, PARAMS_SIGNOFF_NOTE, type OeeDayResult } from '../../lib/oeeService'; +import { CALIBER_CONFIG } from './calibers28'; +import { ANCHOR_DEVICE_ID, DEVICE_BY_ID } from './devices'; + +/** 与 metricTree 完全一致的百分数换算,保证顶栏与指标树逐位相等 */ +const pct = (x: number) => +(x * 100).toFixed(2); +/** G 缺口:因子为 null/NaN 时 value 必须落 null(不是 0/NaN),并给出缺口文案 */ +const fin = (x: number | null | undefined): number | null => + (x != null && Number.isFinite(x) ? x : null); +const pctStr = (x: number | null | undefined): string => + (fin(x) === null ? '—' : String(pct(x as number))); + +export type ResultMetricId = 'PLAN_RATE' | 'SHORTFALL' | 'OEE' | 'YIELD' | 'LABOR_UPH'; + +/** 数据缺口:必须四件齐备(缺什么/依赖谁/何时做实/为什么不能替代),否则等于留空白 */ +export interface MetricGap { + missing: string; + dependsOn: string; + stage: string; + note: string; +} + +export interface ResultMetric { + id: ResultMetricId; + label: string; + unit: string; + /** null = 数据缺口,**不是 0**。UI 必须标灰并展示 gap,不得渲染成 0.00 */ + value: number | null; + /** 考核方向:up 越高越好,down 越低越好 */ + polarity: 'up' | 'down'; + formula: string; + /** 实算项的取数出处(可回溯到 L3 字段) */ + source: string; + /** 目标值:有才给,没有不编。null 表示无已签字目标 */ + target: number | null; + targetNote: string; + /** 卡片副行:实算项给构成量,缺口项给缺失输入 */ + sub: string; + gap: MetricGap | null; + caliberVersion: string; +} + +/** 计划产量缺口:IF-06 APS 计划版本未签收,原型无计划量来源 */ +const PLAN_QTY_GAP: MetricGap = { + missing: '计划产量(APS 计划版本 / 班次目标量)', + dependsOn: 'IF-06 APS 计划接口(未签收)', + stage: 'W2 起可人工录入计划版本;生产阶段 P1 依赖 IF-06/IF-08 签收', + note: '种子只有生成意图 intent,明确标注"不是引擎输出,避免自证",不得当计划量用。' + + '也不得用 ICT×PPT 的理论产能冒充计划产量——那是换口径。', +}; + +/** 工时缺口:IF-08 MES 工时未签收,原型无人工工时来源 */ +const LABOR_GAP: MetricGap = { + missing: '人工工时(投入工时 / 出勤工时)', + dependsOn: 'IF-08 MES 工时接口(未签收)', + stage: '生产阶段 P1;C05 的理论/实际工时口径只适用 ASLT,W1 未接入', + note: '不得用设备运行小时(RT)冒充人工工时算 UPH——两者分母不同,' + + '「产量增长来自效率还是投入」这个问题只有人工工时能回答。', +}; + +/** + * 五类结果指标。传入业务日结果则按该日取数,缺省取当期。 + * ★ 只有 OEE 与良率两项可实算,另三项如实标缺口——这是实测事实,不是实现偷懒。 + */ +export function resultMetrics(day: OeeDayResult = currentDay()): ResultMetric[] { + const t = day.tiers.actual; + const pl = day.tiers.planned; + const tot = day.segments.totals; + const unit = day.device.unit; + const ver = day.caliberVersion; + + return [ + { + id: 'PLAN_RATE', label: '计划达成率', unit: '%', value: null, polarity: 'up', + formula: '实际产量 ÷ 计划产量', + source: '缺计划产量,无法取数', + target: null, targetNote: '无已签字计划版本,不给目标', + sub: `实际产量 ${tot.outputQty.toLocaleString()} ${unit}(已采到)`, + gap: PLAN_QTY_GAP, caliberVersion: ver, + }, + { + id: 'SHORTFALL', label: '欠产数量', unit, value: null, polarity: 'down', + formula: '计划产量 − 实际产量', + source: '缺计划产量,无法取数', + target: null, targetNote: '无已签字计划版本,不给目标', + sub: `实际产量 ${tot.outputQty.toLocaleString()} ${unit}(已采到)`, + gap: PLAN_QTY_GAP, caliberVersion: ver, + }, + { + id: 'OEE', label: 'OEE', unit: '%', value: fin(t.oee) === null ? null : pct(t.oee), polarity: 'up', + formula: 'A×P×Q = 良品数×ICT ÷ PPT', + source: 'oeeService.tiers.actual.oee(与指标树 OEE 节点同源)', + target: pct(pl.oee), targetNote: `目标取计划档 OEE。${PARAMS_SIGNOFF_NOTE}`, + sub: `A ${pctStr(t.a)} · P ${pctStr(t.p)} · Q ${pctStr(t.q)}`, + gap: fin(t.oee) === null ? { + missing: '因子缺口,OEE 不给数', + dependsOn: '客户侧 NG/良率源与 DEK EVENT.DAT 码表全表(96 码)(G-01~05 P0 缺口)', + stage: '全量重算已按日重算 A/P;Q 源到位后 OEE 自动出数', + note: '不假设 100%、不以 0 冒充,不做日均摊派。', + } : null, caliberVersion: ver, + }, + { + id: 'YIELD', label: '良率', unit: '%', value: fin(t.q) === null ? null : pct(t.q), polarity: 'up', + formula: '良品数 ÷ 产出数', + source: 'oeeService.tiers.actual.q(与指标树 Q 节点同源)', + target: pct(pl.q), targetNote: `目标取计划档 Q(C27 目标良率)。${PARAMS_SIGNOFF_NOTE}`, + sub: fin(tot.goodQty) === null + ? `良品 —(G 缺口)/ 产出 ${tot.outputQty.toLocaleString()} ${unit}` + : `良品 ${(tot.goodQty as number).toLocaleString()} / 产出 ${tot.outputQty.toLocaleString()} ${unit}`, + gap: fin(t.q) === null ? { + missing: '无 NG/良率源(G 缺口)', + dependsOn: '客户侧 NG/良率采集通道(G-01~05 P0 缺口)', + stage: '全量重算无此因子源;源到位后按日实测', + note: '不假设 100%,不以 0 冒充。', + } : null, caliberVersion: ver, + }, + { + id: 'LABOR_UPH', label: '单位工时产出', unit: `${unit}/工时`, value: null, polarity: 'up', + formula: '产量 ÷ 人工工时', + source: '缺人工工时,无法取数', + target: null, targetNote: '无已签字工时口径,不给目标', + sub: `产量 ${tot.outputQty.toLocaleString()} ${unit}(已采到)`, + gap: LABOR_GAP, caliberVersion: ver, + }, + ]; +} + +/** 按业务日取五类指标(顶栏日期筛选用)。日期不在种子范围内则返回 null,不夹回造一期。 */ +export function resultMetricsOfDate(bizDate: string): ResultMetric[] | null { + const d = dayByDate(bizDate); + return d ? resultMetrics(d) : null; +} + +/** 范围披露:顶栏必须原样展示,不得省略 */ +export const RESULT_SCOPE_NOTE = + `五类结果指标当前只覆盖锚点设备 ${ANCHOR_DEVICE_ID}(${DEVICE_BY_ID[ANCHOR_DEVICE_ID].name})。` + + '计划达成率/欠产数量缺计划产量(IF-06 未签收),单位工时产出缺人工工时(IF-08 未签收),' + + '三项按数据缺口标灰,不编数、不用相近量冒充。'; + +/** 缺口项计数:供校验脚本与"说明与对照"页引用(现算,不写死) */ +export function resultMetricStats(day: OeeDayResult = currentDay()) { + const ms = resultMetrics(day); + const computable = ms.filter((m) => m.value !== null); + const gaps = ms.filter((m) => m.gap !== null); + return { + total: ms.length, + /** 固定五项,顺序即规划书 3.3 原文顺序 */ + ids: ms.map((m) => m.id), + computableCount: computable.length, + gapCount: gaps.length, + /** 缺口项 value 必须为 null(不是 0),且四件披露齐备 */ + gapsAreNullNotZero: gaps.every((m) => m.value === null), + gapsFullyDisclosed: gaps.every((m) => + m.gap !== null && m.gap.missing !== '' && m.gap.dependsOn !== '' + && m.gap.stage !== '' && m.gap.note !== '' && m.formula !== ''), + /** 实算项必须与 L3 逐位相等(断言②的实现点之一) */ + oeeMatchesService: ms.find((m) => m.id === 'OEE')?.value === pct(day.tiers.actual.oee), + yieldMatchesService: ms.find((m) => m.id === 'YIELD')?.value === pct(day.tiers.actual.q), + /** 实算项目标取计划档,且必须带"待 IE 签字"披露 */ + targetsFromPlannedTier: ms.find((m) => m.id === 'OEE')?.target === pct(day.tiers.planned.oee) + && ms.find((m) => m.id === 'YIELD')?.target === pct(day.tiers.planned.q), + signoffDisclosed: computable.every((m) => m.targetNote.includes('待 IE 签字')), + caliberVersion: day.caliberVersion, + caliberVersionUniform: ms.every((m) => m.caliberVersion === day.caliberVersion), + scopeNote: RESULT_SCOPE_NOTE, + anchorDevice: ANCHOR_DEVICE_ID, + caliberConfigVersion: CALIBER_CONFIG.version, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/seed/asltLine.ts b/src/modules/tfamd-oee/data/oee/seed/asltLine.ts new file mode 100644 index 0000000..3d17e0b --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/seed/asltLine.ts @@ -0,0 +1,311 @@ +/** + * ASLT 系统级测试线(suzamdaslt386,1 台 12 Site)合成种子。 + * + * ★ synthetic: true —— 全部为模拟数据,UI 必须渲染"模拟"标签(断言⑪)。 + * 本种子**不复现** POC 锚点,且 POC 自身有两个口径必须分开标注: + * · 站别汇总口径 A 61.39% / P 74.86% / Q 90.84% → OEE **41.75%** + * · 活跃窗口口径 A 66.15% / P 68.21% / Q 90.84% → OEE **40.99%** + * 规划书 line 474 与旧台账 note 把 41.75% 挂在活跃窗口三率上,属**交叉配对错误**, + * 已在 CONFLICT_READINGS 披露。本模板算的是活跃窗口口径,不得声称等于 41.75%。 + * + * ★ 另一处实测口径疑点:POC 六分类合计 744.00h = 31 日,但事件范围 2026-06-30~07-31 + * 为 32 个日历日 = 768h,**差 1 日(24h)**。客户未说明是边界日剔除还是统计缺失, + * 待甲方确认(W0-4 Q1)。原型按单日 86400s 闭合,不替客户补那 24h,也不四舍五入抹平。 + * + * 生成规则(与 POC 口径一致): + * · 事件只在**非 PLAN** 块产生(PLAN = 无排产/未开机的静默段); + * · 相邻事件间隔 > 60min 切分活跃窗口(ASLT_ACTIVE_GAP_SEC); + * · 六分类时间账由块序列**构造性闭合**:Σ块长 = calendarSec,残差恒为 0; + * · 运行窗口 = OCC 块;站点使能 = OCC 全 12 Site + WAIT 期间部分 Site(演示站点未满載); + * · 配对率按 POC 的 70% 构造,未配对 30% 用活跃窗口补足,不当 0 时长丢弃。 + * + * ★ 确定性:不用 Math.random、不读时钟。事件时刻由块边界 + 固定步长推出。 + */ +import type { AsltInput, AsltClassifiedInterval } from '../../../lib/oee/templates'; +import { ASLT_ACTIVE_GAP_SEC } from '../../../lib/oee/templates'; +import type { AsltTimeClass } from '../../../types/oee'; +import { SEED_DATES } from '../devices'; + +export const ASLT_SEED_META = { + synthetic: true, + source: 'DEMO_SEED', + lineId: 'ASLT-L1', + deviceId: 'suzamdaslt386', + siteCount: 12, + dates: [...SEED_DATES], + activeGapSec: ASLT_ACTIVE_GAP_SEC, + eventStepSec: 300, + note: '本页数据为模拟。ASLT 无客户算法表,口径为系统建议,须纳入版本管理并由 IE 定版(C03/C04/C05)。', + pocAnchor: { + stationRollup: { a: 0.6139, p: 0.7486, q: 0.9084, oee: 0.4175, scope: '站别汇总口径' }, + activeWindow: { a: 0.6615, p: 0.6821, q: 0.9084, oee: 0.4099, scope: '单台 12 Site · 活跃窗口口径' }, + crossPairingWarning: '41.75% 属站别汇总,40.99% 属活跃窗口;两套三率不得交叉配对', + eventRows: 48717, + activeWindows: 49, + calendarDays: 32, + sixClassTotalHours: 744.0, + dayGapIssue: '六分类合计 744.00h = 31 日,事件范围 32 日历日 = 768h,差 24h 待甲方确认(W0-4 Q1)', + pairingRate: 0.70, + output: { ftInput: 3036, ftGood: 2738, rcGood: 20, note: 'Q = (FT合格 2738 + RC复测合格 20) / FT投入 3036 = 2758/3036 = 90.84%' }, + sixClass: [ + { cls: 'WAIT', hours: 153.52, pct: 20.63 }, + { cls: 'PLAN', hours: 125.80, pct: 16.91 }, + { cls: 'OCC', hours: 379.41, pct: 51.00 }, + { cls: 'ENG', hours: 61.87, pct: 8.32 }, + { cls: 'STOP', hours: 23.29, pct: 3.13 }, + { cls: 'STANDBY', hours: 0.11, pct: 0.01 }, + ] as { cls: AsltTimeClass; hours: number; pct: number }[], + improvementOrder: ['物料保障', '排产计划', '站点满载', '换型标准化', '设备维修'], + baselineNote: '参考基线·来源:鼎捷 POC', + notReproduced: '演示种子为合成数据,不复现上述锚点;两者并列展示、不可混用', + }, +} as const; + +/** 六分类块。PLAN 块不产事件,是活跃窗口的切分依据。 */ +export interface AsltBlock { + cls: AsltTimeClass; + startSec: number; + endSec: number; +} + +export interface AsltDayPlan { + bizDate: string; + story: string; + blocks: AsltBlock[]; + /** WAIT 期间仍使能的 Site 数(演示站点未满载;OCC 期间固定全 12 Site) */ + waitEnabledSites: number; + output: { ftInput: number; ftGood: number; rcGood: number }; + pairingRate: number; +} + +const H = 3600; +const M = 60; +const DAY_SEC = 86400; +const SITE_COUNT = 12; +const STEP = ASLT_SEED_META.eventStepSec; + +/* ══════════════════════════════════════════════════════════════════ + * 三日块序列(每段首尾相接,精确铺满 86400s) + * ══════════════════════════════════════════════════════════════════ */ + +/** 09-01 基线日:Wait 为最大损失桶,Stop 很小 → 改善主因不是设备故障。 */ +function baselineBlocks(): AsltBlock[] { + return [ + { cls: 'PLAN', startSec: 0, endSec: 5 * H }, + { cls: 'ENG', startSec: 5 * H, endSec: 6 * H }, + { cls: 'OCC', startSec: 6 * H, endSec: 10 * H }, + { cls: 'WAIT', startSec: 10 * H, endSec: 12 * H + 30 * M }, + { cls: 'PLAN', startSec: 12 * H + 30 * M, endSec: 14 * H }, + { cls: 'OCC', startSec: 14 * H, endSec: 17 * H }, + { cls: 'STOP', startSec: 17 * H, endSec: 17 * H + 30 * M }, + { cls: 'WAIT', startSec: 17 * H + 30 * M, endSec: 18 * H + 30 * M }, + { cls: 'OCC', startSec: 18 * H + 30 * M, endSec: 20 * H }, + { cls: 'ENG', startSec: 20 * H, endSec: 20 * H + 30 * M }, + { cls: 'WAIT', startSec: 20 * H + 30 * M, endSec: 21 * H + 30 * M }, + { cls: 'OCC', startSec: 21 * H + 30 * M, endSec: 23 * H }, + { cls: 'STANDBY', startSec: 23 * H, endSec: 23 * H + 1 * M }, + { cls: 'PLAN', startSec: 23 * H + 1 * M, endSec: 24 * H }, + ]; +} + +/** 09-02 劣化日:待料与报警停机拉长,无排产静默段增加。 */ +function degradedBlocks(): AsltBlock[] { + return [ + { cls: 'PLAN', startSec: 0, endSec: 6 * H }, + { cls: 'ENG', startSec: 6 * H, endSec: 7 * H }, + { cls: 'OCC', startSec: 7 * H, endSec: 10 * H }, + { cls: 'WAIT', startSec: 10 * H, endSec: 13 * H }, + { cls: 'PLAN', startSec: 13 * H, endSec: 15 * H }, + { cls: 'OCC', startSec: 15 * H, endSec: 17 * H }, + { cls: 'STOP', startSec: 17 * H, endSec: 18 * H }, + { cls: 'WAIT', startSec: 18 * H, endSec: 19 * H + 30 * M }, + { cls: 'OCC', startSec: 19 * H + 30 * M, endSec: 21 * H }, + { cls: 'ENG', startSec: 21 * H, endSec: 21 * H + 40 * M }, + { cls: 'WAIT', startSec: 21 * H + 40 * M, endSec: 22 * H + 40 * M }, + { cls: 'OCC', startSec: 22 * H + 40 * M, endSec: 23 * H + 30 * M }, + { cls: 'STANDBY', startSec: 23 * H + 30 * M, endSec: 23 * H + 31 * M }, + { cls: 'PLAN', startSec: 23 * H + 31 * M, endSec: 24 * H }, + ]; +} + +/** 09-03 改善日:物料保障见效 → Wait 大幅压缩;排产补齐 → Plan 静默段缩短。 */ +function improvedBlocks(): AsltBlock[] { + return [ + { cls: 'PLAN', startSec: 0, endSec: 4 * H }, + { cls: 'ENG', startSec: 4 * H, endSec: 4 * H + 40 * M }, + { cls: 'OCC', startSec: 4 * H + 40 * M, endSec: 9 * H }, + { cls: 'WAIT', startSec: 9 * H, endSec: 9 * H + 40 * M }, + { cls: 'PLAN', startSec: 9 * H + 40 * M, endSec: 11 * H }, + { cls: 'OCC', startSec: 11 * H, endSec: 15 * H }, + { cls: 'STOP', startSec: 15 * H, endSec: 15 * H + 12 * M }, + { cls: 'WAIT', startSec: 15 * H + 12 * M, endSec: 15 * H + 42 * M }, + { cls: 'OCC', startSec: 15 * H + 42 * M, endSec: 19 * H }, + { cls: 'ENG', startSec: 19 * H, endSec: 19 * H + 20 * M }, + { cls: 'WAIT', startSec: 19 * H + 20 * M, endSec: 19 * H + 50 * M }, + { cls: 'OCC', startSec: 19 * H + 50 * M, endSec: 23 * H }, + { cls: 'STANDBY', startSec: 23 * H, endSec: 23 * H + 1 * M }, + { cls: 'PLAN', startSec: 23 * H + 1 * M, endSec: 24 * H }, + ]; +} + +export const ASLT_DAY_PLANS: AsltDayPlan[] = [ + { + bizDate: SEED_DATES[0], story: '基线日:Wait 为最大损失桶,Stop 占比很小;WAIT 期间仅 3/12 Site 使能。', + blocks: baselineBlocks(), waitEnabledSites: 3, + output: { ftInput: 1080, ftGood: 962, rcGood: 20 }, pairingRate: 0.70, + }, + { + bizDate: SEED_DATES[1], story: '劣化日:待料与报警停机拉长、无排产静默段增加,终测合格率下滑。', + blocks: degradedBlocks(), waitEnabledSites: 2, + output: { ftInput: 860, ftGood: 742, rcGood: 18 }, pairingRate: 0.70, + }, + { + bizDate: SEED_DATES[2], story: '改善日:物料保障见效 Wait 压缩、排产补齐 Plan 缩短,Site 使能数回升。', + blocks: improvedBlocks(), waitEnabledSites: 7, + output: { ftInput: 1240, ftGood: 1128, rcGood: 26 }, pairingRate: 0.70, + }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 生成器 + * ══════════════════════════════════════════════════════════════════ */ + +/** 铺满校验:块必须首尾相接覆盖 [0, 86400]。六分类闭合由此保证。 */ +export function checkAsltTiling(blocks: AsltBlock[], daySec = DAY_SEC): { ok: boolean; problems: string[] } { + const problems: string[] = []; + if (blocks.length === 0) return { ok: false, problems: ['时间轴为空'] }; + if (blocks[0].startSec !== 0) problems.push(`首块起点 ${blocks[0].startSec} ≠ 0`); + if (blocks[blocks.length - 1].endSec !== daySec) problems.push(`末块终点 ${blocks[blocks.length - 1].endSec} ≠ ${daySec}`); + for (let i = 0; i < blocks.length; i++) { + const b = blocks[i]; + if (b.endSec <= b.startSec) problems.push(`第 ${i} 块零长或倒序:${b.startSec}→${b.endSec}`); + if (i > 0 && blocks[i - 1].endSec !== b.startSec) problems.push(`第 ${i - 1}/${i} 块不连续:${blocks[i - 1].endSec} → ${b.startSec}`); + } + return { ok: problems.length === 0, problems }; +} + +/** 事件时刻:非 PLAN 块内按固定步长发点,块起点必发一条(保证窗口边界落在块边界上)。 */ +export function eventTimestamps(blocks: AsltBlock[], step = STEP): number[] { + const out: number[] = []; + for (const b of blocks) { + if (b.cls === 'PLAN') continue; + for (let t = b.startSec; t < b.endSec; t += step) out.push(t); + } + return out.sort((x, y) => x - y); +} + +/** 运行窗口 = OCC 块。 */ +export function runWindowsOf(blocks: AsltBlock[]): { startSec: number; endSec: number }[] { + return blocks.filter((b) => b.cls === 'OCC').map((b) => ({ startSec: b.startSec, endSec: b.endSec })); +} + +/** + * 站点使能:OCC 期间全 12 Site;WAIT 期间只有 waitEnabledSites 个 Site 仍使能。 + * ENG/STOP/STANDBY/PLAN 期间不使能(换型与报警时站点不投产)。 + * 同一 Site 的窗口天然不重叠(块互斥),跨 Site 不去重。 + */ +export function siteEnableOf(blocks: AsltBlock[], waitEnabledSites: number): { siteId: number; startSec: number; endSec: number }[] { + const out: { siteId: number; startSec: number; endSec: number }[] = []; + for (const b of blocks) { + const n = b.cls === 'OCC' ? SITE_COUNT : b.cls === 'WAIT' ? waitEnabledSites : 0; + for (let s = 1; s <= n; s++) out.push({ siteId: s, startSec: b.startSec, endSec: b.endSec }); + } + return out; +} + +/** 六分类区间 = 块本身(构造性闭合)。 */ +export function classifiedOf(blocks: AsltBlock[]): AsltClassifiedInterval[] { + return blocks.map((b) => ({ startSec: b.startSec, endSec: b.endSec, cls: b.cls })); +} + +export interface AsltSeedDay { + bizDate: string; + story: string; + input: AsltInput; + tiling: { ok: boolean; problems: string[] }; + /** 自检:运行时长不得超过活跃窗口、站点使能不得超过容量(引擎也会判,这里先暴露种子问题) */ + precheck: { runSec: number; siteEnableSec: number; eventCount: number }; +} + +export interface AsltSeed { + meta: AsltSeedMeta; + days: AsltSeedDay[]; +} + +/** meta 结构化:demo 常量满足本接口。 */ +export interface AsltSeedMeta { + synthetic: boolean; + source: string; + lineId: string; + deviceId: string; + siteCount: number; + dates: readonly string[]; + activeGapSec: number; + /** demo 种子的构造步长 */ + eventStepSec?: number; + note: string; + pocAnchor: { + stationRollup: { a: number; p: number; q: number; oee: number; scope: string }; + activeWindow: { a: number; p: number; q: number; oee: number; scope: string }; + crossPairingWarning: string; + eventRows: number; + activeWindows: number; + calendarDays?: number; + sixClassTotalHours?: number; + dayGapIssue?: string; + pairingRate?: number; + output?: { ftInput: number; ftGood: number; rcGood: number; note: string }; + sixClass?: { cls: AsltTimeClass; hours: number; pct: number }[]; + improvementOrder?: readonly string[]; + baselineNote: string; + notReproduced: string; + }; +} + +export function buildAsltSeed(): AsltSeed { + const days: AsltSeedDay[] = ASLT_DAY_PLANS.map((p) => { + const ts = eventTimestamps(p.blocks); + const run = runWindowsOf(p.blocks); + const enable = siteEnableOf(p.blocks, p.waitEnabledSites); + const paired = Math.round(ts.length * p.pairingRate); + const input: AsltInput = { + deviceId: ASLT_SEED_META.deviceId, + scopeLabel: `${ASLT_SEED_META.deviceId} · 1 台 ${SITE_COUNT} Site · ${p.bizDate} 演示日`, + siteCount: SITE_COUNT, + eventTimestampsSec: ts, + runWindows: run, + siteEnable: enable, + output: p.output, + classified: classifiedOf(p.blocks), + calendarSec: DAY_SEC, + pairing: { paired, unpaired: ts.length - paired }, + activeGapSec: ASLT_ACTIVE_GAP_SEC, + synthetic: true, + }; + return { + bizDate: p.bizDate, + story: p.story, + input, + tiling: checkAsltTiling(p.blocks), + precheck: { + runSec: run.reduce((s, w) => s + (w.endSec - w.startSec), 0), + siteEnableSec: enable.reduce((s, w) => s + (w.endSec - w.startSec), 0), + eventCount: ts.length, + }, + }; + }); + return { meta: ASLT_SEED_META, days }; +} + +export function asltSeedStats(seed: AsltSeed) { + return { + days: seed.days.length, + siteCount: SITE_COUNT, + eventRows: seed.days.reduce((s, d) => s + d.precheck.eventCount, 0), + runSecTotal: seed.days.reduce((s, d) => s + d.precheck.runSec, 0), + siteEnableSecTotal: seed.days.reduce((s, d) => s + d.precheck.siteEnableSec, 0), + tilingOk: seed.days.every((d) => d.tiling.ok), + ftInputTotal: seed.days.reduce((s, d) => s + d.input.output.ftInput, 0), + activeGapMin: ASLT_ACTIVE_GAP_SEC / 60, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/seed/dekLog.ts b/src/modules/tfamd-oee/data/oee/seed/dekLog.ts new file mode 100644 index 0000000..0733613 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/seed/dekLog.ts @@ -0,0 +1,394 @@ +/** + * DEK 印刷机合成原始日志种子(三日回放)。 + * + * ★ synthetic: true —— 全部为模拟数据,UI 必须渲染"模拟"标签(断言⑪)。 + * POC 实测 35,245 行/日〔POC〕,原型按约 1/17 缩放;实际行数以生成结果为准,不写死。 + * + * 格式:定宽 91 字符 EVENT.DAT(附录 D.3) + * 日期[0:10] 时间[11:19] 事件码[20:25] 文本[26:71] 参数[71:91] + * + * 三日故事线(故意构造,用于演示 DQ-06 阻断与解除): + * 09-01 正常日 残差 0,未归因 0% + * 09-02 异常日 日志断流 30min(UNKNOWN,不计分母)+ 无事件无产出空档 60min(IDLE) + * → 未归因 3600/43200 = 8.33% > 5% → DQ-06 阻断发布 + * 09-03 恢复日 空档补齐,残差回到 0,不良数下降(治理见效) + * + * 脏样本(没有脏数据,12 条 DQ 规则就是摆设): + * · 一日 4 次改钟〔POC〕:31317/31318 成对,其中 2 次原始时刻回跳 + * · 重复采集行 3 条(dedup_key 去重) + * · 定宽畸形行 1 条(宽度不足 → 解析失败显式披露) + * · 未映射码 1 条(码表没有 → 记缺口,不猜归口) + * + * ★ 确定性:不用 Math.random、不读时钟。所有时刻由 blocks 精确铺满 24h 推出, + * 板级间隔取整数秒,避免浮点漂移导致 lot 窗口闭合不齐。 + */ +import type { RawLogLine } from '../../../types/oee'; +import { digestOf } from '../../../lib/oee/adapterDek'; +import { ANCHOR_DEVICE_ID, SEED_DATES, SEED_DIRTY_DATE, nextDate } from '../devices'; + +export const DEK_SEED_META = { + synthetic: true, + source: 'DEMO_SEED', + device: ANCHOR_DEVICE_ID, + format: '定宽 91 字符文本(EVENT.DAT)', + encoding: 'ASCII', + dates: [...SEED_DATES], + dirtyDate: SEED_DIRTY_DATE, + note: '本页数据为模拟。DEK 事件码为演示子集,客户 96 码全表未提供,接入前须替换。', + pocAnchor: { + realLinesPerDay: 35245, + scaleNote: '原型按约 1/17 缩放', + baselineNote: '参考基线·来源:鼎捷 POC', + }, +} as const; + +/** 块类型。NO_DATA 与 UNEXPLAINED 都不产日志行,但语义完全不同(DQ-10 三态分开)。 */ +export type DekBlockKind = + | 'SHUTDOWN' // 关机 → PLAN_STOP(S-33/S-34) + | 'PLAN_IDLE' // APS 计划待料 → PLAN_STOP(S-39/S-40) + | 'CONVERSION' // 换型 → CHANGE(S-13/S-14) + | 'LOT_SETUP' // Lot setup loss → CHANGE(S-25/S-26) + | 'DOWN' // >5min 停机 → DOWN(S-29 DERIVED) + | 'JAM' // ≤5min 短停 → JAM(S-32 DERIVED) + | 'LOT' // 生产 → RUN(板级锚点推 lot 窗口) + | 'NO_DATA' // 日志断流 → UNKNOWN,**不计入分母** + | 'UNEXPLAINED'; // 无事件无产出 → IDLE,未归因,**计入分母** + +export interface DekBlock { + kind: DekBlockKind; + /** 相对业务日 00:00 的起始秒 */ + startSec: number; + endSec: number; + /** LOT 块:lot 后缀与板数。板间隔 = (endSec-startSec)/boards,必须整除。 */ + lot?: string; + boards?: number; + /** LOT 块:判为不良的板序号(0 基) */ + defects?: number[]; + /** JAM 块:拆成几段等长短停(每段须 ≤300s 才落 JAM) */ + jamParts?: number; +} + +export interface DekDayPlan { + bizDate: string; + blocks: DekBlock[]; + /** 改钟标记:trueSec 为真实时刻,off 为校正偏移(加到原始时刻上得真实时刻) */ + clockMarks: { startSec: number; off: number }[]; + /** 09-02 额外脏样本 */ + extraDirty?: boolean; +} + +const H = 3600; +const M = 60; + +/** 正常日块序列。精确铺满 86400s。PLAN_IDLE 按班次边界拆两块,避免配对跨班被拒。 */ +function cleanBlocks(): DekBlock[] { + return [ + { kind: 'SHUTDOWN', startSec: 0, endSec: 6 * H }, + { kind: 'CONVERSION', startSec: 6 * H, endSec: 6 * H + 30 * M }, + { kind: 'LOT_SETUP', startSec: 6 * H + 30 * M, endSec: 7 * H }, + { kind: 'LOT', startSec: 7 * H, endSec: 10 * H, lot: 'A', boards: 240, defects: [10, 120] }, + { kind: 'DOWN', startSec: 10 * H, endSec: 10 * H + 40 * M }, + { kind: 'JAM', startSec: 10 * H + 40 * M, endSec: 10 * H + 52 * M, jamParts: 3 }, + { kind: 'LOT', startSec: 10 * H + 52 * M, endSec: 12 * H, lot: 'B', boards: 102, defects: [40] }, + { kind: 'PLAN_IDLE', startSec: 12 * H, endSec: 16 * H }, + { kind: 'PLAN_IDLE', startSec: 16 * H, endSec: 18 * H }, + { kind: 'LOT', startSec: 18 * H, endSec: 20 * H, lot: 'C', boards: 160, defects: [80] }, + { kind: 'CONVERSION', startSec: 20 * H, endSec: 20 * H + 20 * M }, + { kind: 'LOT', startSec: 20 * H + 20 * M, endSec: 24 * H, lot: 'D', boards: 300, defects: [] }, + ]; +} + +/** 异常日:关机缩短 30min 让位给日志断流;LOT C 缩短 60min 让位给未归因空档。 */ +function dirtyBlocks(): DekBlock[] { + return [ + { kind: 'SHUTDOWN', startSec: 0, endSec: 5 * H + 30 * M }, + { kind: 'NO_DATA', startSec: 5 * H + 30 * M, endSec: 6 * H }, + { kind: 'CONVERSION', startSec: 6 * H, endSec: 6 * H + 30 * M }, + { kind: 'LOT_SETUP', startSec: 6 * H + 30 * M, endSec: 7 * H }, + { kind: 'LOT', startSec: 7 * H, endSec: 10 * H, lot: 'A', boards: 240, defects: [10, 120] }, + { kind: 'DOWN', startSec: 10 * H, endSec: 10 * H + 40 * M }, + { kind: 'JAM', startSec: 10 * H + 40 * M, endSec: 10 * H + 52 * M, jamParts: 3 }, + { kind: 'LOT', startSec: 10 * H + 52 * M, endSec: 12 * H, lot: 'B', boards: 102, defects: [40] }, + { kind: 'PLAN_IDLE', startSec: 12 * H, endSec: 16 * H }, + { kind: 'PLAN_IDLE', startSec: 16 * H, endSec: 18 * H }, + { kind: 'LOT', startSec: 18 * H, endSec: 19 * H, lot: 'C', boards: 80, defects: [20, 60] }, + { kind: 'UNEXPLAINED', startSec: 19 * H, endSec: 20 * H }, + { kind: 'CONVERSION', startSec: 20 * H, endSec: 20 * H + 20 * M }, + { kind: 'LOT', startSec: 20 * H + 20 * M, endSec: 24 * H, lot: 'D', boards: 300, defects: [150] }, + ]; +} + +/** 恢复日:结构同正常日,不良数下降(治理见效)。 */ +function recoveredBlocks(): DekBlock[] { + return cleanBlocks().map((b) => { + if (b.kind !== 'LOT') return b; + if (b.lot === 'A') return { ...b, defects: [10] }; + if (b.lot === 'B') return { ...b, defects: [] }; + return b; + }); +} + +/** 一日 4 次改钟〔POC〕。全部落在 LOT 块内,保证回跳可被观测到。 + * 偏移幅度须大于板间隔,否则相邻行的回跳量 = off − spacing 会低于 DQ-01 的 60s 阈值: + * LOT A/C 板间隔 45s → off=120 产生 75s 回跳、off=300 产生 255s 回跳,两者都能被检出。 */ +const CLOCK_MARKS = [ + { startSec: 7 * H + 30 * M, off: 120 }, // 落在 LOT A 板级行上:锚点回跳,不进事件表 + { startSec: 9 * H, off: 0 }, // 恢复 + // 落在 JAM 块内(10:40/10:44/10:48 三条 DERIVED 之间): + // 让回跳发生在**两条真实事件**之间,DQ-01 才检得到。只改板级行的话, + // 事件序列仍然单调向前,回跳次数会是 0——这是采集侧最容易漏掉的盲区。 + { startSec: 10 * H + 41 * M, off: 600 }, // JAM2 原始时刻 10:44 → 10:34,倒退 360s + { startSec: 10 * H + 50 * M, off: 0 }, // 恢复(LOT B 10:52 开始前) + { startSec: 18 * H + 30 * M, off: 300 }, // 落在换型事件上:原始时刻回跳 + { startSec: 21 * H, off: 0 }, // 恢复 +]; + +export const DEK_DAY_PLANS: DekDayPlan[] = [ + { bizDate: SEED_DATES[0], blocks: cleanBlocks(), clockMarks: CLOCK_MARKS }, + { bizDate: SEED_DATES[1], blocks: dirtyBlocks(), clockMarks: CLOCK_MARKS, extraDirty: true }, + { bizDate: SEED_DATES[2], blocks: recoveredBlocks(), clockMarks: CLOCK_MARKS }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 生成器 + * ══════════════════════════════════════════════════════════════════ */ + +interface Emission { + trueSec: number; + seq: number; + code: string; + text: string; + params: string; + /** 脏样本标记:duplicate 复制前一条;malformed 截断;unmapped 用码表外的码 */ + dirty?: 'duplicate' | 'malformed' | 'unmapped'; +} + +function pad(n: number, w = 2): string { return String(n).padStart(w, '0'); } + +function hhmmss(sec: number): string { + return `${pad(Math.floor(sec / 3600) % 24)}:${pad(Math.floor(sec / 60) % 60)}:${pad(sec % 60)}`; +} + +function hhmm(sec: number): string { + return `${pad(Math.floor(sec / 3600) % 24)}${pad(Math.floor(sec / 60) % 60)}`; +} + +/** 定宽 91 字符拼装。文本 45 / 参数 20,超长直接抛错——宁可生成失败也不产出畸形行。 */ +export function packDekLine(date: string, time: string, code: string, text: string, params: string): string { + if (text.length > 45) throw new Error(`文本区超长(${text.length}>45):${text}`); + if (params.length > 20) throw new Error(`参数区超长(${params.length}>20):${params}`); + if (code.length !== 5) throw new Error(`事件码须 5 位:${code}`); + return date + ' ' + time + ' ' + code + ' ' + text.padEnd(45, ' ') + params.padEnd(20, ' '); +} + +const POINT_CODES: Record = { + // 开始码 结束码 开始文本 结束文本 + SHUTDOWN: ['30101', '30102', 'SHUTDOWN START (APS)', 'SHUTDOWN END (APS)'], + PLAN_IDLE: ['30201', '30202', 'APS PLAN IDLE START', 'APS PLAN IDLE END'], + CONVERSION: ['30301', '30302', 'CONVERSION START', 'CONVERSION END'], + LOT_SETUP: ['30401', '30402', 'LOT SETUP LOSS START', 'LOT SETUP LOSS END'], +}; + +/** 把一天的块序列展开成待发行(真实时刻),含改钟标记与脏样本。 */ +function emissionsFor(plan: DekDayPlan): Emission[] { + const out: Emission[] = []; + let seq = 0; + const push = (trueSec: number, code: string, text: string, params: string, dirty?: Emission['dirty']) => { + out.push({ trueSec, seq: seq++, code, text, params, ...(dirty ? { dirty } : {}) }); + }; + const lotId = (suffix: string) => `LOT-${plan.bizDate.slice(2).replace(/-/g, '')}${suffix}`; + + for (const b of plan.blocks) { + const dur = b.endSec - b.startSec; + switch (b.kind) { + case 'SHUTDOWN': + case 'PLAN_IDLE': + case 'CONVERSION': + case 'LOT_SETUP': { + const [sc, ec, st, et] = POINT_CODES[b.kind]; + push(b.startSec, sc, st, ''); + push(b.endSec, ec, et, ''); + break; + } + case 'DOWN': + push(b.startSec, '20103', 'DOWN >5MIN BOTTLENECK', `s=${hhmm(b.startSec)};e=${hhmm(b.endSec)}`); + break; + case 'JAM': { + const parts = b.jamParts ?? 1; + const each = dur / parts; + if (!Number.isInteger(each)) throw new Error(`JAM 分段须整除:${dur}/${parts}`); + for (let i = 0; i < parts; i++) { + const s = b.startSec + i * each; + push(s, '20203', 'JAM <=5MIN', `s=${hhmm(s)};e=${hhmm(s + each)}`); + } + break; + } + case 'LOT': { + const n = b.boards ?? 0; + const spacing = dur / n; + if (!Number.isInteger(spacing)) throw new Error(`板间隔须整数秒:${dur}/${n}`); + const lid = lotId(b.lot ?? 'X'); + const defects = new Set(b.defects ?? []); + for (let i = 0; i < n; i++) { + const s = b.startSec + i * spacing; + const bs = pad(i + 1, 4); + push(s, '10101', `PRINT START ${lid} B${bs}`, `b=${bs};c=${spacing}`); + push(s + spacing, '10102', `PRINT COMPLETE ${lid} B${bs}`, `b=${bs};c=${spacing};r=${defects.has(i) ? 0 : 1}`); + } + break; + } + case 'NO_DATA': + case 'UNEXPLAINED': + // 故意不产任何日志行。两者的差别由 noDataWindows 是否覆盖决定(DQ-10 三态分开)。 + break; + } + } + + // 改钟标记:31317 在前、31318 在后(相隔 30s),off 声明自此生效的校正偏移 + for (const cm of plan.clockMarks) { + push(cm.startSec, '31317', 'CLOCK CHANGE MARK', ''); + push(cm.startSec + 30, '31318', 'CLOCK CHANGE MARK', `off=${cm.off}`); + } + + // 额外脏样本。重复行必须是**真重复**:同码、同时刻、同参数 → dedupKey 相同才会被去掉。 + // 换个时刻或换个板号就不是重复采集,而是多产出一块板,会把 N 悄悄放大。 + if (plan.extraDirty) { + const completes = out.filter((e) => e.code === '10102'); + for (const idx of [10, 20, 30]) { + const src = completes[idx]; + out.push({ trueSec: src.trueSec, seq: seq++, code: src.code, text: src.text, params: src.params, dirty: 'duplicate' }); + } + push(8 * H, '10102', 'PRINT COMPLETE TRUNCATED LINE', 'b=0034;c=45;r=1', 'malformed'); + push(8 * H, '99999', 'UNKNOWN EVENT CODE', '', 'unmapped'); + } + + return out.sort((a, b) => a.trueSec - b.trueSec || a.seq - b.seq); +} + +export interface DekSeedFile { + bizDate: string; + filePath: string; + lines: RawLogLine[]; + /** 日志断流窗口 → UNKNOWN,不计入分母(DQ-10)。未归因空档不在此列。 */ + noDataWindows: { start: string; end: string }[]; + /** 生成意图,供校验脚本独立比对(不是引擎输出,避免自证) */ + intent: { + boards: number; + defects: number; + shutdownSec: number; + planIdleSec: number; + conversionSec: number; + lotSetupSec: number; + downSec: number; + jamSec: number; + runSec: number; + noDataSec: number; + unexplainedSec: number; + }; +} + +export interface DekSeed { + meta: DekSeedMeta; + files: DekSeedFile[]; +} + +/** + * Dek 种子 meta 结构:demo 常量 DEK_SEED_META 原样可赋值。 + */ +export interface DekSeedMeta { + synthetic: boolean; + source: string; + device: string; + format: string; + encoding: string; + dates: readonly string[]; + dirtyDate?: string; + note: string; + pocAnchor: { realLinesPerDay: number; scaleNote: string; baselineNote: string }; +} + +function isoAt(bizDate: string, sec: number): string { + const day = sec >= 86400 ? nextDate(bizDate) : bizDate; + return `${day}T${hhmmss(sec % 86400)}Z`; +} + +/** 生成三日种子。纯函数:同一输入永远得到同一批行,可重放、可深相等比对。 */ +export function buildDekSeed(): DekSeed { + const files: DekSeedFile[] = []; + + for (const plan of DEK_DAY_PLANS) { + const emissions = emissionsFor(plan); + const filePath = `/mnt/dek/${ANCHOR_DEVICE_ID}/${plan.bizDate}/EVENT.DAT`; + const lines: RawLogLine[] = []; + let off = 0; + let lineNo = 0; + + for (const e of emissions) { + lineNo += 1; + const isMark = e.code === '31317' || e.code === '31318'; + // 改钟标记本身按真实时刻记录;31318 之后偏移生效 + const rawSec = isMark ? e.trueSec : e.trueSec - off; + // 文本里的日期/时刻必须与元数据 rawTime **同源**:跨零点要进位到次日。 + // 否则末板完成行文本写「当日 00:00:00」而元数据写「次日 00:00:00」, + // 适配器只信文本 → 该锚点整整回退一天,lot 窗口横跨全天把 UNKNOWN/IDLE 全吃成 RUN。 + const rawIso = isoAt(plan.bizDate, rawSec); + const rawDate = rawIso.slice(0, 10); + const rawClock = rawIso.slice(11, 19); + let rawText = packDekLine(rawDate, rawClock, e.code, e.text, e.params); + if (e.dirty === 'malformed') rawText = rawText.slice(0, 80); + if (e.dirty === 'unmapped') rawText = packDekLine(rawDate, rawClock, '99999', e.text, e.params); + if (isMark && e.code === '31318') { + const m = /^off=(-?\d+)$/.exec(e.params); + if (m) off = Number(m[1]); + } + lines.push({ + id: `raw-${ANCHOR_DEVICE_ID}-${plan.bizDate}-${lineNo}`, + device: ANCHOR_DEVICE_ID, + filePath, + lineNo, + rawText, + digest: digestOf(rawText), + channel: 'FILE', + rawTime: rawIso, + }); + } + + const sum = (k: DekBlockKind) => plan.blocks.filter((b) => b.kind === k).reduce((a, b) => a + (b.endSec - b.startSec), 0); + const lots = plan.blocks.filter((b) => b.kind === 'LOT'); + const noDataWindows = plan.blocks.filter((b) => b.kind === 'NO_DATA') + .map((b) => ({ start: isoAt(plan.bizDate, b.startSec), end: isoAt(plan.bizDate, b.endSec) })); + + files.push({ + bizDate: plan.bizDate, + filePath, + lines, + noDataWindows, + intent: { + boards: lots.reduce((a, b) => a + (b.boards ?? 0), 0), + defects: lots.reduce((a, b) => a + (b.defects?.length ?? 0), 0), + shutdownSec: sum('SHUTDOWN'), + planIdleSec: sum('PLAN_IDLE'), + conversionSec: sum('CONVERSION'), + lotSetupSec: sum('LOT_SETUP'), + downSec: sum('DOWN'), + jamSec: sum('JAM'), + runSec: sum('LOT'), + noDataSec: sum('NO_DATA'), + unexplainedSec: sum('UNEXPLAINED'), + }, + }); + } + + return { meta: DEK_SEED_META, files }; +} + +/** 种子总行数(现算)。用于核对规模与 20MB 内存预算。 */ +export function dekSeedStats(seed: DekSeed) { + const perDay = seed.files.map((f) => ({ bizDate: f.bizDate, lines: f.lines.length })); + return { + days: seed.files.length, + totalLines: seed.files.reduce((a, f) => a + f.lines.length, 0), + perDay, + synthetic: seed.meta.synthetic, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/seed/ftLine.ts b/src/modules/tfamd-oee/data/oee/seed/ftLine.ts new file mode 100644 index 0000000..8338a74 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/seed/ftLine.ts @@ -0,0 +1,270 @@ +/** + * FT 终测线(93k178 / 93k250 / 93k287)合成种子。 + * + * ★ synthetic: true —— 全部为模拟数据,UI 必须渲染"模拟"标签(断言⑪)。 + * + * 操作数来源分级(**不可混为一谈**): + * · 93k178:POC 给了 2026M06 的完整操作数〔POC〕,本种子按其**比率**缩放到单日, + * 标注 operandSource='SEED'、synthetic=true —— 是"按 POC 比率构造的演示日", + * **不是** POC 实测日,不得声称复现 81.69%。 + * · 93k250 / 93k287:客户**未给**任何操作数,全部为演示假设,note 里逐台写明。 + * + * ★ 实测口径疑点(须 IE 确认,不自行赋义): + * POC baseSec = 2,448,035s,除以 28 完整日 = 87,429.82s > 86,400s(一日)。 + * 28 × 86400 = 2,419,200,POC 多出 28,835s ≈ 8.01h。 + * 说明 baseSec **不是纯日历秒分母**(可能含多 handler 并行时间或跨月边界)。 + * 本种子单日一律取 baseSec = 86400,并把该疑点披露在 meta 与口径页,不抹平。 + * + * ★ SetupLoss 五操作数 (196.2×12/1000)×9/720 照录《FT_OEE.xlsx》v3, + * 物理含义与单位客户未给,待 IE 确认(FT_SETUP_SEMANTICS_NOTE)。 + * + * 三日故事线:09-01 基线 → 09-02 劣化(停机↑、良率↓)→ 09-03 改善。 + * 三日投入量刻意不等,使"按投入量加权"与"简单平均"、"周期累计"与"日均"可被区分(断言④)。 + */ +import type { FtInput, FtSetupOperands } from '../../../lib/oee/templates'; +import { FT_SETUP_SEMANTICS_NOTE } from '../../../lib/oee/templates'; +import { SEED_DATES } from '../devices'; + +/** POC 93k178 · 2026M06 原操作数〔POC〕。只作参考基线,不参与演示日计算。 */ +export const FT_POC_93K178 = { + deviceId: '93k178', + scope: '93k178 · 2026M06 · 28 完整日', + algorithmTable: '《FT_OEE.xlsx》v3', + baseSec: 2448035, + downSec: 64050, + jamSec: 46866, + setup: { op1: 196.2, op2: 12, op3: 1000, op4: 9, op5: 720 } as FtSetupOperands, + corrRate: 0.02, + oeRate: 0.05, + indexSec: 1.5, + testSec: 30, + rescreenFactor: 1.04, + yieldRate: 0.9301, + planLossRate: 0, + inputQty: 135107, + baselineNote: '参考基线·来源:鼎捷 POC', + /** 我方按原操作数独立复算的结果,与 POC 公布值并列展示 */ + recomputed: { a: 0.926273, p: 0.886529, q: 0.997312, oee: 0.818960 }, +} as const; + +/** POC 产线锚点与 PM 敏感性〔POC〕。只作参考基线。 */ +export const FT_POC_ANCHORS = { + line: { scope: 'FT 产线 · 2026M06 · 3 台按投入量加权', a: 0.9258, p: 0.8847, q: 0.9975, oee: 0.8169 }, + pmSensitivity: { + deviceId: '93k287', before: 0.8212, after: 0.7859, + note: 'C06:PM 计入 Down 分子、分母不变。POC 未给 93k287 的操作数,' + + '故原型在 93k178(操作数已知)上演示同一开关,并把本锚点作为**另一台设备**的参考值并列,不声称复现。', + }, + baselineNote: '参考基线·来源:鼎捷 POC', + notReproduced: '演示种子为合成数据,不复现上述锚点;两者并列展示、不可混用', +} as const; + +export const FT_SEED_META = { + synthetic: true, + source: 'DEMO_SEED', + lineId: 'FT-L1', + deviceIds: ['93k178', '93k250', '93k287'], + dates: [...SEED_DATES], + algorithmTable: '《FT_OEE.xlsx》v3', + setupSemanticsNote: FT_SETUP_SEMANTICS_NOTE, + baseSecIssue: 'POC baseSec 2,448,035s ÷ 28 日 = 87,429.82s > 86,400s,多出 28,835s≈8.01h;' + + 'baseSec 非纯日历秒分母,口径待 IE 确认。演示日一律取 86400s。', + operandCoverage: '仅 93k178 有 POC 操作数;93k250 / 93k287 全部为演示假设,客户未提供。', + note: '本页数据为模拟。FT 的 A 为连乘扣减式、P 为 1−三项损失,与通用 A=RT/PPT 不同构,不可套通用式。', +} as const; + +/** 单台单日的操作数Profile。比率制,便于按日缩放且保持量纲一致。 */ +export interface FtDeviceProfile { + deviceId: string; + baseSec: number; + downRate: number; + jamRate: number; + setup: FtSetupOperands; + corrRate: number; + oeRate: number; + indexSec: number; + testSec: number; + rescreenFactor: number; + yieldRate: number; + planLossRate: number; + inputQty: number; + /** C06 PM 开关:计入 Down 分子,分母不变 */ + pmMin?: number; + note: string; +} + +export interface FtDayPlan { + bizDate: string; + story: string; + devices: FtDeviceProfile[]; +} + +const DAY_SEC = 86400; +/** POC 93k178 的比率(由原操作数算出,作为 93k178 演示日的基线) */ +const POC_DOWN_RATE = FT_POC_93K178.downSec / FT_POC_93K178.baseSec; +const POC_JAM_RATE = FT_POC_93K178.jamSec / FT_POC_93K178.baseSec; +const POC_SETUP = FT_POC_93K178.setup; + +/** 93k178:按 POC 比率缩放。dayFactor 只作用于停机率,良率单独给。 */ +function k178(dayFactor: number, yieldRate: number, inputQty: number, note: string): FtDeviceProfile { + return { + deviceId: '93k178', baseSec: DAY_SEC, + downRate: POC_DOWN_RATE * dayFactor, jamRate: POC_JAM_RATE * dayFactor, + setup: POC_SETUP, corrRate: 0.02, oeRate: 0.05, indexSec: 1.5, testSec: 30, + rescreenFactor: 1.04, yieldRate, planLossRate: 0, inputQty, note, + }; +} + +/** 93k250:客户未给操作数。演示假设为较旧 handler——短停多、良率低。 */ +function k250(dayFactor: number, yieldRate: number, inputQty: number, note: string): FtDeviceProfile { + return { + deviceId: '93k250', baseSec: DAY_SEC, + downRate: 0.0410 * dayFactor, jamRate: 0.0325 * dayFactor, + setup: { op1: 210.0, op2: 12, op3: 1000, op4: 9, op5: 720 }, + corrRate: 0.025, oeRate: 0.062, indexSec: 1.8, testSec: 30, + rescreenFactor: 1.06, yieldRate, planLossRate: 0, inputQty, note, + }; +} + +/** 93k287:客户未给操作数。演示假设为较新机台——A 高但 P 低(换型/索引损失大)。 */ +function k287(dayFactor: number, yieldRate: number, inputQty: number, note: string, pmMin?: number): FtDeviceProfile { + return { + deviceId: '93k287', baseSec: DAY_SEC, + downRate: 0.0180 * dayFactor, jamRate: 0.0140 * dayFactor, + setup: { op1: 180.0, op2: 12, op3: 1000, op4: 9, op5: 720 }, + corrRate: 0.018, oeRate: 0.088, indexSec: 2.4, testSec: 30, + rescreenFactor: 1.03, yieldRate, planLossRate: 0, inputQty, pmMin, note, + }; +} + +const SEED_NOTE_178 = '按 POC 93k178·2026M06 比率缩放到单日的演示数据,非 POC 实测日。'; +const SEED_NOTE_250 = '★ 客户未提供 93k250 操作数,本台全部为演示假设(较旧 handler:短停多、良率低)。'; +const SEED_NOTE_287 = '★ 客户未提供 93k287 操作数,本台全部为演示假设(较新机台:A 高、P 低)。'; + +export const FT_DAY_PLANS: FtDayPlan[] = [ + { + bizDate: SEED_DATES[0], + story: '基线日:93k178 取 POC 比率,另两台为演示假设。三台投入量不等,用于演示按投入量加权。', + devices: [ + k178(1.0, 0.9301, 4820, SEED_NOTE_178), + k250(1.0, 0.9180, 1560, SEED_NOTE_250), + k287(1.0, 0.9410, 640, SEED_NOTE_287), + ], + }, + { + bizDate: SEED_DATES[1], + story: '劣化日:停机率上浮、良率下滑;93k287 叠加 PM 1633.5min 演示 C06 开关(计入 Down 分子、分母不变)。', + devices: [ + k178(1.8, 0.9150, 3910, `${SEED_NOTE_178} 本日停机率×1.8、良率降至 91.50%。`), + k250(1.6, 0.9020, 1180, `${SEED_NOTE_250} 本日停机率×1.6、良率降至 90.20%。`), + k287(1.5, 0.9260, 520, `${SEED_NOTE_287} 本日停机率×1.5,并计入 PM 1633.5min(C06 演示)。`, 1633.5), + ], + }, + { + bizDate: SEED_DATES[2], + story: '改善日:停机率回落、良率回升,投入量恢复。用于演示周期累计 ≠ 日均。', + devices: [ + k178(0.7, 0.9420, 5240, `${SEED_NOTE_178} 本日停机率×0.7、良率升至 94.20%。`), + k250(0.8, 0.9310, 1720, `${SEED_NOTE_250} 本日停机率×0.8、良率升至 93.10%。`), + k287(0.75, 0.9480, 700, `${SEED_NOTE_287} 本日停机率×0.75、良率升至 94.80%。`), + ], + }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 生成器:Profile → FtInput + * ══════════════════════════════════════════════════════════════════ */ + +export function toFtInput(p: FtDeviceProfile, bizDate: string, pmOn = true): FtInput { + return { + deviceId: p.deviceId, + scopeLabel: `${p.deviceId} · ${bizDate} · 演示日`, + algorithmTable: FT_SEED_META.algorithmTable, + baseSec: p.baseSec, + downSec: p.baseSec * p.downRate, + jamSec: p.baseSec * p.jamRate, + setup: p.setup, + corrRate: p.corrRate, + oeRate: p.oeRate, + indexSec: p.indexSec, + testSec: p.testSec, + rescreenFactor: p.rescreenFactor, + yieldRate: p.yieldRate, + planLossRate: p.planLossRate, + inputQty: p.inputQty, + pmMin: pmOn ? p.pmMin : undefined, + operandSource: 'SEED', + synthetic: true, + }; +} + +export interface FtSeedDay { + bizDate: string; + story: string; + inputs: FtInput[]; + /** C06 对照:同一批操作数关掉 PM 的输入,供敏感性演示 */ + inputsPmOff: FtInput[]; +} + +export interface FtSeed { + meta: FtSeedMeta; + /** POC 参考基线(demo 种子携带;参考行由 ftPocReference 独立复算) */ + poc?: { device: typeof FT_POC_93K178; anchors: typeof FT_POC_ANCHORS }; + days: FtSeedDay[]; +} + +/** meta 结构化:demo 常量满足本接口。 */ +export interface FtSeedMeta { + synthetic: boolean; + source: string; + lineId: string; + deviceIds: readonly string[]; + dates: readonly string[]; + algorithmTable: string; + setupSemanticsNote: string; + baseSecIssue: string; + operandCoverage: string; + note: string; +} + +export function buildFtSeed(): FtSeed { + return { + meta: FT_SEED_META, + poc: { device: FT_POC_93K178, anchors: FT_POC_ANCHORS }, + days: FT_DAY_PLANS.map((d) => ({ + bizDate: d.bizDate, + story: d.story, + inputs: d.devices.map((p) => toFtInput(p, d.bizDate, true)), + inputsPmOff: d.devices.map((p) => toFtInput(p, d.bizDate, false)), + })), + }; +} + +/** POC 原操作数 → FtInput(operandSource='POC'、synthetic=false),供参考基线行独立复算。 */ +export function pocFtInput(): FtInput { + const p = FT_POC_93K178; + return { + deviceId: p.deviceId, scopeLabel: p.scope, algorithmTable: p.algorithmTable, + baseSec: p.baseSec, downSec: p.downSec, jamSec: p.jamSec, setup: p.setup, + corrRate: p.corrRate, oeRate: p.oeRate, indexSec: p.indexSec, testSec: p.testSec, + rescreenFactor: p.rescreenFactor, yieldRate: p.yieldRate, planLossRate: p.planLossRate, + inputQty: p.inputQty, operandSource: 'POC', synthetic: false, + }; +} + +export function ftSeedStats(seed: FtSeed) { + const all = seed.days.flatMap((d) => d.inputs); + /* demo 维持 93k178 一台 POC 比率 */ + const pocDevices = 1; + return { + days: seed.days.length, + devices: seed.meta.deviceIds.length, + readings: all.length, + inputQtyTotal: all.reduce((s, i) => s + i.inputQty, 0), + pmReadings: all.filter((i) => (i.pmMin ?? 0) > 0).length, + pocOperandDevices: pocDevices, + assumedOperandDevices: seed.meta.deviceIds.length - pocDevices, + baseSecPerDay: DAY_SEC, + pocBaseSecPerDay: FT_POC_93K178.baseSec / 28, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/seed/srfLine.ts b/src/modules/tfamd-oee/data/oee/seed/srfLine.ts new file mode 100644 index 0000000..21e9cb2 --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/seed/srfLine.ts @@ -0,0 +1,331 @@ +/** + * SRF 串行线(DEK001 → BUF001 → DCP005)合成种子。 + * + * ★ synthetic: true —— 全部为模拟数据,UI 必须渲染"模拟"标签(断言⑪)。 + * 本种子**不复现** POC 锚点 25.50%,原因有二,页面必须同时披露: + * ① 范围不同:POC 的 A=39.17% 是 **13 台设备连乘**;原型 SRF-L1 只建 + * DEK + DCP 两台代表站(台账 note 已说明),两站连乘天然高于十三站连乘。 + * ② 数量来源不同:流体仿真的 RT=N×ICT 会让 P≡100%(模型产物), + * 故本种子另给**实测锚点计数** anchors,P 由 N×ICT/RT 实算,必然 <100%。 + * + * 三日故事线(故意构造,用于演示缓冲解耦的成立与击穿): + * 09-01 解耦成立 上游最长连续停机 894s(14.9min)→ B_min=ceil(894/36)=25,B=25 恰好够; + * 下游最长停机 672s → 下游侧 B_min=ceil(672/28)=24 ≤ B=25,两侧都成立 + * 09-02 下游击穿 DCP005 长停机 7440s(124min,POC 改善标的)→ 下游侧 B_min=266,B=25 远远不够, + * 上游被大面积阻塞;另有 90min 日志缺失窗口(演示 DQ-10 机制,不冒充 POC 的 751min), + * 由 L3 阻断发布——缺失数据不能靠模型补出来。 + * 09-03 恢复 上游长停机压缩到 480s,但换型 600s 成为新的最长非计划停机 + * → B_min=ceil(600/36)=17(不是 14)。瓶颈由故障转移到换型,仍 ≤ B=25,解耦重新成立。 + * + * ★ 确定性:不用 Math.random、不读时钟。所有时刻由 blocks 精确铺满 86400s 推出。 + * ★ 单位换算演示假设:1 板 = 1 TU。真实拼板换算比客户未给,接入前必须替换(C 类口径)。 + */ +import type { BufferInterval, BufferSimInput, SrfAnchorCounts } from '../../../lib/oee/templates'; +import { SEED_DATES } from '../devices'; + +export const SRF_SEED_META = { + synthetic: true, + source: 'DEMO_SEED', + lineId: 'SRF-L1', + upstreamDeviceId: 'DEK001', + downstreamDeviceId: 'DCP005', + bufferDeviceId: 'BUF001', + dates: [...SEED_DATES], + unitAssumption: '1 板 = 1 TU(演示假设,真实拼板换算比待客户确认)', + note: '本页数据为模拟。SRF 只建 DEK + DCP 两台代表站,与 POC 的 13 台范围不可直接比数。', + pocAnchor: { + lineOee: 0.2550, a: 0.3917, p: 0.6510, q: 1.0, + zeroBufferOee: 0.1602, + scope: 'SRF 产线 13 台设备 · 缓冲解耦主口径', + upstreamMaxStopMin: 14.9, + downstreamIctSec: 36, + minCapacity: 25, + dekBlockCountPerDay: 847, + dekBlockedHoursPerDay: 7.3, + dcp005MissingMin: 751, + dcp005StopMin: 124, + baselineNote: '参考基线·来源:鼎捷 POC', + notReproduced: '原型为两站代表模型 + 合成种子,不复现该锚点;两者并列展示、不可混用', + }, +} as const; + +/** 块类型。planned=true 的段从 PPT 分母扣除(PDT),planned=false 的非在产段进可用性损失。 */ +export type SrfBlockKind = 'PLAN_STOP' | 'CHANGE' | 'DOWN' | 'JAM' | 'RUN'; + +export interface SrfBlock { + kind: SrfBlockKind; + startSec: number; + endSec: number; +} + +export interface SrfStationPlan { + deviceId: string; + ictSec: number; + blocks: SrfBlock[]; +} + +export interface SrfDayPlan { + bizDate: string; + /** 缓冲容量 B(单位数)。台账 BUF001 的演示配置。 */ + capacity: number; + upstream: SrfStationPlan; + downstream: SrfStationPlan; + /** 实测产出锚点计数。P = N×ICT/RT 由此实算,不用仿真数量。 */ + anchors: { upstream: SrfAnchorCounts; downstream: SrfAnchorCounts }; + yieldRate: { upstream: number; downstream: number }; + /** 日志缺失窗口:不进仿真,由 L3 判 DQ-10 并阻断发布 */ + noDataWindows: { deviceId: string; startSec: number; endSec: number; note: string }[]; + story: string; +} + +const H = 3600; +const M = 60; + +/* ══════════════════════════════════════════════════════════════════ + * 时间轴(精确铺满 86400s) + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 上游 DEK001:ict 28s/板。最长连续**非计划**停机 894s = 14.9min〔POC 操作数〕。 + * 换型刻意压到 600s/480s(均 < 894s),否则最长停机会被换型顶掉,B_min 就不是 25。 + * 计划停机(关机 6h、计划待料 4h)是屏障,不参与最长停机合并。 + */ +function dekBlocks(): SrfBlock[] { + return [ + { kind: 'PLAN_STOP', startSec: 0, endSec: 6 * H }, + { kind: 'CHANGE', startSec: 6 * H, endSec: 6 * H + 600 }, + { kind: 'RUN', startSec: 6 * H + 600, endSec: 10 * H }, + { kind: 'DOWN', startSec: 10 * H, endSec: 10 * H + 894 }, // ★ 894s = 14.9min + { kind: 'RUN', startSec: 10 * H + 894, endSec: 12 * H }, + { kind: 'PLAN_STOP', startSec: 12 * H, endSec: 16 * H }, + { kind: 'RUN', startSec: 16 * H, endSec: 18 * H }, + { kind: 'JAM', startSec: 18 * H, endSec: 18 * H + 4 * M }, + { kind: 'RUN', startSec: 18 * H + 4 * M, endSec: 20 * H }, + { kind: 'CHANGE', startSec: 20 * H, endSec: 20 * H + 480 }, + { kind: 'RUN', startSec: 20 * H + 480, endSec: 24 * H }, + ]; +} + +/** + * 下游 DCP005:ict 36s/TU。最长非计划停机 672s → 下游侧 B_min=ceil(672/28)=24 ≤ B=25, + * 故 09-01 两侧解耦都成立。换型 600s/480s 同样短于 672s。 + */ +function dcpBlocks(): SrfBlock[] { + return [ + { kind: 'PLAN_STOP', startSec: 0, endSec: 6 * H }, + { kind: 'CHANGE', startSec: 6 * H, endSec: 6 * H + 600 }, + { kind: 'RUN', startSec: 6 * H + 600, endSec: 11 * H }, + { kind: 'DOWN', startSec: 11 * H, endSec: 11 * H + 672 }, + { kind: 'RUN', startSec: 11 * H + 672, endSec: 12 * H }, + { kind: 'PLAN_STOP', startSec: 12 * H, endSec: 16 * H }, + { kind: 'RUN', startSec: 16 * H, endSec: 20 * H }, + { kind: 'CHANGE', startSec: 20 * H, endSec: 20 * H + 480 }, + { kind: 'RUN', startSec: 20 * H + 480, endSec: 24 * H }, + ]; +} + +/** + * 09-02 击穿日:**DCP005(下游)**长停机 7440s(124min,POC 改善标的)。 + * 下游停机时缓冲由上游以 28s/板 填充,C_up = 25×28 = 700s ≪ 7440s, + * 故下游侧 B_min = ceil(7440/28) = 266,现有 B=25 远远不够 → 上游被大面积阻塞。 + * 上游侧仍成立(最长停机 894s,B_min=25),**两侧必须分开判**,只看上游侧会误判为解耦成立。 + * + * 另有日志缺失窗口(POC 披露 DCP005 缺口 751min)。751min 的统计周期客户未明确, + * 且 751min=12.5h 无法放进单个业务日的在产时段,故演示日取 **90min** 窗口呈现机制, + * **不声称等于 751min**。该窗口不改变仿真时间轴,由 L3 判 DQ-10 并阻断发布—— + * 缺失数据不能靠模型补出来,读数可看但不可作为考核依据。 + */ +function dcpBlocksBroken(): SrfBlock[] { + return [ + { kind: 'PLAN_STOP', startSec: 0, endSec: 6 * H }, + { kind: 'CHANGE', startSec: 6 * H, endSec: 6 * H + 600 }, + { kind: 'RUN', startSec: 6 * H + 600, endSec: 11 * H }, + { kind: 'DOWN', startSec: 11 * H, endSec: 11 * H + 7440 }, // ★ 124min,属 DCP005 + { kind: 'RUN', startSec: 11 * H + 7440, endSec: 16 * H }, + { kind: 'PLAN_STOP', startSec: 16 * H, endSec: 18 * H }, + { kind: 'RUN', startSec: 18 * H, endSec: 20 * H }, + { kind: 'CHANGE', startSec: 20 * H, endSec: 20 * H + 480 }, + { kind: 'RUN', startSec: 20 * H + 480, endSec: 24 * H }, + ]; +} + +/** + * 09-03 恢复日:长停机压到 480s(8min)。 + * ★ B_min 不是 14 而是 17:故障缩短后,换型 600s 成了最长非计划停机,ceil(600/36)=17。 + * 这是模型算出的结论——压缩故障后瓶颈转移到换型,改善顺序应随之调整,不是把叙事凑成 14。 + */ +function dekBlocksRecovered(): SrfBlock[] { + const shortened: SrfBlock[] = dekBlocks().map((b): SrfBlock => { + if (b.kind !== 'DOWN') return b; + return { kind: 'DOWN', startSec: 10 * H, endSec: 10 * H + 480 }; + }); + return shortened.map((b, i, arr): SrfBlock => { + // DOWN 缩短后,紧随其后的 RUN 段起点必须跟着前移,否则时间轴出现空洞 + if (b.kind === 'RUN' && i > 0 && arr[i - 1].kind === 'DOWN') { + return { ...b, startSec: arr[i - 1].endSec }; + } + return b; + }); +} + +/* ══════════════════════════════════════════════════════════════════ + * 三日计划 + * ══════════════════════════════════════════════════════════════════ */ + +export const SRF_DAY_PLANS: SrfDayPlan[] = [ + { + bizDate: SEED_DATES[0], + capacity: 25, + upstream: { deviceId: 'DEK001', ictSec: 28, blocks: dekBlocks() }, + downstream: { deviceId: 'DCP005', ictSec: 36, blocks: dcpBlocks() }, + anchors: { + upstream: { outputQty: 1180, goodQty: 1174 }, + downstream: { outputQty: 812, goodQty: 806 }, + }, + yieldRate: { upstream: 1174 / 1180, downstream: 806 / 812 }, + noDataWindows: [], + story: '解耦成立:上游最长停机 894s(14.9min),B=25 提供 900s 覆盖,恰好够。', + }, + { + bizDate: SEED_DATES[1], + capacity: 25, + upstream: { deviceId: 'DEK001', ictSec: 28, blocks: dekBlocks() }, + downstream: { deviceId: 'DCP005', ictSec: 36, blocks: dcpBlocksBroken() }, + anchors: { + upstream: { outputQty: 1150, goodQty: 1136 }, + downstream: { outputQty: 1080, goodQty: 1065 }, + }, + yieldRate: { upstream: 1136 / 1150, downstream: 1065 / 1080 }, + noDataWindows: [ + { + deviceId: 'DCP005', startSec: 14 * H, endSec: 14 * H + 90 * M, + note: 'DCP005 日志缺失 90min(演示窗口)。POC 披露该设备缺口 751min,其统计周期客户未明确,' + + '本窗口只呈现 DQ-10 机制,不声称等于 751min。缺失段状态未经日志验证,读数不可作为考核依据。', + }, + ], + story: '下游侧解耦击穿:DCP005 长停机 7440s(124min)需 B≥266,现有 B=25 仅提供 700s 覆盖,上游被大面积阻塞;另有 90min 缺失数据待补采。', + }, + { + bizDate: SEED_DATES[2], + capacity: 25, + upstream: { deviceId: 'DEK001', ictSec: 28, blocks: dekBlocksRecovered() }, + downstream: { deviceId: 'DCP005', ictSec: 36, blocks: dcpBlocks() }, + anchors: { + upstream: { outputQty: 1246, goodQty: 1242 }, + downstream: { outputQty: 869, goodQty: 864 }, + }, + yieldRate: { upstream: 1242 / 1246, downstream: 864 / 869 }, + noDataWindows: [], + story: '恢复:长停机压到 480s(8min),但换型 600s 成为最长非计划停机 → B_min=17(非 14),仍 ≤ B=25,两侧解耦重新成立;瓶颈由故障转移到换型。', + }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 生成器:blocks → BufferInterval[] + * ══════════════════════════════════════════════════════════════════ */ + +/** 块 → 仿真区间。PLAN_STOP 标 planned,其余非 RUN 段都是非计划损失。 */ +export function toIntervals(blocks: SrfBlock[]): BufferInterval[] { + return blocks.map((b) => ({ + startSec: b.startSec, + endSec: b.endSec, + running: b.kind === 'RUN', + planned: b.kind === 'PLAN_STOP', + })); +} + +/** 铺满校验:段必须首尾相接覆盖 [0, 86400],不留空洞也不重叠。 */ +export function checkTiling(blocks: SrfBlock[], daySec = 86400): { ok: boolean; problems: string[] } { + const problems: string[] = []; + if (blocks.length === 0) return { ok: false, problems: ['时间轴为空'] }; + if (blocks[0].startSec !== 0) problems.push(`首段起点 ${blocks[0].startSec} ≠ 0`); + if (blocks[blocks.length - 1].endSec !== daySec) problems.push(`末段终点 ${blocks[blocks.length - 1].endSec} ≠ ${daySec}`); + for (let i = 0; i < blocks.length; i++) { + const b = blocks[i]; + if (b.endSec <= b.startSec) problems.push(`第 ${i} 段零长或倒序:${b.startSec}→${b.endSec}`); + if (i > 0 && blocks[i - 1].endSec !== b.startSec) { + problems.push(`第 ${i - 1}/${i} 段不连续:${blocks[i - 1].endSec} → ${b.startSec}`); + } + } + return { ok: problems.length === 0, problems }; +} + +export interface SrfSeedDay { + bizDate: string; + story: string; + capacity: number; + sim: BufferSimInput; + anchors: { upstream: SrfAnchorCounts; downstream: SrfAnchorCounts }; + yieldRate: { upstream: number; downstream: number }; + noDataWindows: { deviceId: string; startSec: number; endSec: number; note: string }[]; + tiling: { upstream: { ok: boolean; problems: string[] }; downstream: { ok: boolean; problems: string[] } }; +} + +export interface SrfSeed { + meta: SrfSeedMeta; + days: SrfSeedDay[]; +} + +/** meta 结构化:demo 常量满足本接口。 */ +export interface SrfSeedMeta { + synthetic: boolean; + source: string; + lineId: string; + upstreamDeviceId: string; + downstreamDeviceId: string; + bufferDeviceId: string; + dates: readonly string[]; + unitAssumption: string; + note: string; + pocAnchor: { + lineOee: number; a: number; p: number; q: number; + zeroBufferOee: number; + scope: string; + upstreamMaxStopMin: number; + downstreamIctSec: number; + minCapacity: number; + dekBlockCountPerDay: number; + dekBlockedHoursPerDay: number; + dcp005MissingMin: number; + dcp005StopMin: number; + baselineNote: string; + notReproduced: string; + }; +} + +export function buildSrfSeed(): SrfSeed { + const days: SrfSeedDay[] = SRF_DAY_PLANS.map((p) => ({ + bizDate: p.bizDate, + story: p.story, + capacity: p.capacity, + sim: { + upstream: { deviceId: p.upstream.deviceId, ictSec: p.upstream.ictSec, intervals: toIntervals(p.upstream.blocks) }, + downstream: { deviceId: p.downstream.deviceId, ictSec: p.downstream.ictSec, intervals: toIntervals(p.downstream.blocks) }, + capacity: p.capacity, + initialLevel: 0, + simWindow: { startSec: 0, endSec: 86400 }, + }, + anchors: p.anchors, + yieldRate: p.yieldRate, + noDataWindows: p.noDataWindows, + tiling: { + upstream: checkTiling(p.upstream.blocks), + downstream: checkTiling(p.downstream.blocks), + }, + })); + return { meta: SRF_SEED_META, days }; +} + +/** 种子自检计数,供主数据页与校验脚本展示(不写死在视图里)。 */ +export function srfSeedStats(seed: SrfSeed) { + return { + days: seed.days.length, + stations: 2, + bufferCapacity: seed.days[0]?.capacity ?? 0, + totalBlocks: seed.days.reduce((s, d) => s + d.sim.upstream.intervals.length + d.sim.downstream.intervals.length, 0), + noDataWindowCount: seed.days.reduce((s, d) => s + d.noDataWindows.length, 0), + noDataSec: seed.days.reduce((s, d) => s + d.noDataWindows.reduce((t, w) => t + (w.endSec - w.startSec), 0), 0), + tilingOk: seed.days.every((d) => d.tiling.upstream.ok && d.tiling.downstream.ok), + anchorQtyTotal: seed.days.reduce((s, d) => s + d.anchors.upstream.outputQty + d.anchors.downstream.outputQty, 0), + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/oee/stepchain.ts b/src/modules/tfamd-oee/data/oee/stepchain.ts new file mode 100644 index 0000000..1d3dfca --- /dev/null +++ b/src/modules/tfamd-oee/data/oee/stepchain.ts @@ -0,0 +1,247 @@ +/** + * StepChain 换型链 DSL 数据层(建议书 §4.9,断言⑨的现场执行侧)。 + * + * 来源:《OEE分析AI原型系统构建建议书-2026-11-12.md》§4.9.1/§4.9.2/§4.9.3。 + * 本文件是**常量字典 + 现算统计**:链定义照录方案 7 节点表,触发器照录 6 触发器表, + * SLA 升级对象照录 §4.9.3 原文;演示实例是**模拟种子**(标「模拟」,不是客户生产实况)。 + * + * 三条诚实性纪律(与引擎 lib/oee/stepchain.ts 同源): + * 1. **GATE 不可跳过**:n6_qc_verify 是质量门,演示实例特意停在「n1–n5 已关闭、 + * n6 已提交待核准、n7 受阻挡未激活」——整链就差质量确认,但绝不放行。 + * 2. **DERIVED 不手填**:n7_setup_ea_end 的时刻由 Xray 锚点经 T6 反推(n7=n4−10min), + * 种子只给锚点,派生时刻一律现算,不写死。 + * 3. **T5 计划对齐是契约占位**:implemented=false,不假装已接 APS 排产系统。 + * + * ★ 两套状态机不得共用枚举(D17):本链走 ChainTaskState 七态(现场换型执行), + * 改善闭环走 TaskState 六态(改善立项),互不引用。 + * + * 数据层可 import 纯引擎(data→engine 是允许方向;engine→data 被 purity 脚本禁止)。 + */ +import type { + ChainNode, ChainTrigger, ChainInstance, ChainNodeState, ChainTaskState, EntryForm, +} from '../../types/oee'; +import { + chainStats, deriveSetupTimes, reverseDeriveN7, isoToEpoch, + gateSatisfied, canCloseChain, canActivateNode, +} from '../../lib/oee/stepchain'; +import { ANCHOR_DEVICE_ID } from './devices'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、SRF 换型链 7 节点(建议书 §4.9.1 表,照录不改) + * + * 触发器归属按判据语义判定(§4.9.2 六触发器): + * n1 最后 lot trackout → T1 事件触发(trackout 事件) + * n2 第三 boat 进 reflow → T1 事件触发(进炉事件) + * n3 OTA 调 recipe + 设备 Log → T1 事件触发(recipe 变更事件) + * n4 Xray 图片 + 5min → T2 时间触发(锚点 + 偏移) + * n5 第一盘炉后确认 + 5min → T3 条件触发(炉后确认条件成立) + * n6 质量确认(不可跳过) → T4 手动触发(事务内,QA 核准) + * n7 Xray 图片 − 5min → T6 派生反向超时(由 n4 反推) + * T5 计划对齐无节点承载,是独立契约占位(见 CHAIN_TRIGGERS)。 + * ══════════════════════════════════════════════════════════════════ */ + +export const SRF_CHAIN: ChainNode[] = [ + { id: 'n1_pm_start', kind: 'TASK', role: 'EQ', slaMin: 30, trigger: 'T1', + criterion: '最后 lot trackout', escalateTo: 'EQ 主管' }, + { id: 'n2_pm_end', kind: 'TASK', role: 'EQ', slaMin: 240, trigger: 'T1', + criterion: '第三 boat 进 reflow', escalateTo: 'EQ 主管 + IE' }, + { id: 'n3_conversion_start', kind: 'TASK', role: 'EA', slaMin: 15, trigger: 'T1', + criterion: 'OTA 调 recipe + 设备 Log', escalateTo: 'EA 主管' }, + { id: 'n4_setup_mfg_start', kind: 'TASK', role: 'MFG', slaMin: 20, trigger: 'T2', + criterion: 'Xray 图片 + 5min', escalateTo: 'MFG 主管' }, + { id: 'n5_setup_mfg_end', kind: 'TASK', role: 'MFG', trigger: 'T3', + criterion: '第一盘炉后确认 + 5min', escalateTo: 'MFG 班组长' }, + { id: 'n6_qc_verify', kind: 'GATE', role: 'QA', trigger: 'T4', + criterion: '质量确认(不可跳过)', escalateTo: 'QA 主管' }, + { id: 'n7_setup_ea_end', kind: 'DERIVED', role: 'EA', trigger: 'T6', + criterion: 'Xray 图片 − 5min', escalateTo: 'EA 主管' }, +]; + +/** 节点判定点相对 Xray 锚点的偏移(分钟),与引擎 SETUP_OFFSET_SEC=300s 同源。 */ +export const SETUP_OFFSET_MIN = 5; + +/* ══════════════════════════════════════════════════════════════════ + * 二、六触发器(建议书 §4.9.2 表,照录实现状态) + * ══════════════════════════════════════════════════════════════════ */ + +export const CHAIN_TRIGGERS: ChainTrigger[] = [ + { id: 'T1', kind: '事件触发', implemented: true, + note: '事件流驱动:lot trackout / boat 进 reflow / recipe 变更等事件到达即触发对应节点' }, + { id: 'T2', kind: '时间触发', implemented: true, + note: '模拟时钟推进:Xray 锚点 + 5min 触发 n4_setup_mfg_start(演示用注入时钟,不读 Date.now)' }, + { id: 'T3', kind: '条件触发', implemented: true, + note: '条件成立触发:第一盘炉后确认 + 5min → n5_setup_mfg_end' }, + { id: 'T4', kind: '手动触发(事务内)', implemented: true, + note: '录入台提交:QA 在事务内手动核准 n6_qc_verify 质量门,提交即流转、可回滚' }, + { id: 'T5', kind: '计划对齐', implemented: false, + note: '契约占位:与 APS 排产计划对齐触发换型窗口。原型未接排产系统,不假装已实现(建议书 §4.9.2)' }, + { id: 'T6', kind: '派生反向超时', implemented: true, + note: 'n7 由 n4 反推:n7=Xray−5min=n4−10min,纯算术派生(引擎 reverseDeriveN7),锚点缺失则不派生' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 三、录入台表单级 SLA 升级(建议书 §4.9.3 原文,区别于节点级 SLA) + * + * 节点级 SLA(n1–n4)已在 SRF_CHAIN.escalateTo;此处是录入台四张归因/登记单的 + * 表单级 SLA。Jam 归因无独立表单(并入停机归因流程),form=null,不臆造表单。 + * ══════════════════════════════════════════════════════════════════ */ + +export interface FormSlaEscalation { + label: string; + /** 对应录入台表单;无独立表单则 null(诚实标注,不强行映射) */ + form: EntryForm | null; + sla: string; + escalateTo: string; + note: string; +} + +export const FORM_SLA_ESCALATION: FormSlaEscalation[] = [ + { label: 'Down 归因', form: 'FORM_DOWN_ATTR', sla: '2h', escalateTo: 'EQ + MFG', + note: '停机归因单提交后 2h 内未完成归因 → 升级 EQ + MFG' }, + { label: 'Jam 归因', form: null, sla: '当班内', escalateTo: 'MFG 班组长', + note: '卡料短停归因,当班内完成 → 超时升级 MFG 班组长;原型无独立表单,并入停机归因流程' }, + { label: '等待登记', form: 'FORM_WAIT_REGISTER', sla: '当班内', escalateTo: 'PC', + note: '等待登记单当班内未登记 → 升级 PC(生产控制)' }, + { label: '5S', form: 'FORM_5S', sla: '当班内', escalateTo: 'EA', + note: '5S 记录单当班内未完成 → 升级 EA(设备工程)' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 四、演示实例(模拟种子):停在质量门,演示「不可跳过」 + * + * 业务日 2026-09-03(当期干净日),SRF 演示线换型批次。 + * Xray 锚点 11:00 → n4 派生 11:05、n7 派生 10:55(现算,不写死)。 + * n1–n5 已关闭;n4 执行中曾超 20min SLA → 升级 MFG 主管后完成(留痕); + * n6 质量门已提交待 QA 主管核准(SUBMITTED,未通过); + * n7 受 n6 阻挡,仍 CREATED,不可激活、整链不可关闭。 + * ★ 这是模拟种子,不是客户生产实况;时刻为演示假设。 + * ══════════════════════════════════════════════════════════════════ */ + +/** 演示「当前时刻」(注入时钟,引擎不读 Date.now)。略晚于 n6 提交时刻。 */ +export const CHAIN_DEMO_NOW = '2026-09-03T12:35:00Z'; + +/** 由紧凑步骤序列构造节点运行时态:当前态=末步,history 全程留痕(可重放)。 */ +function nodeState( + nodeId: string, + owner: string, + steps: { state: ChainTaskState; at: string; by?: string; note?: string }[], + opts?: { startedAt?: string; escalated?: boolean; escalatedTo?: string }, +): ChainNodeState { + const last = steps[steps.length - 1]; + return { + nodeId, + owner, + state: last.state, + at: last.at, + ...(opts?.startedAt !== undefined ? { startedAt: opts.startedAt } : {}), + ...(opts?.escalated ? { escalated: true, escalatedTo: opts.escalatedTo } : {}), + history: steps.map((s) => ({ + state: s.state, at: s.at, by: s.by ?? owner, ...(s.note !== undefined ? { note: s.note } : {}), + })), + }; +} + +export const CHAIN_SEED: ChainInstance = { + id: 'CHAIN-SRF-0903-A', + deviceId: ANCHOR_DEVICE_ID, + bizDate: '2026-09-03', + lot: 'LOT-SRF-0903-A(演示批次)', + xrayAnchor: '2026-09-03T11:00:00Z', + nodes: [ + nodeState('n1_pm_start', 'EQ-张工', [ + { state: 'CREATED', at: '2026-09-03T08:00:00Z', note: '最后 lot trackout 事件触发(T1)' }, + { state: 'ACCEPTED', at: '2026-09-03T08:02:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T08:05:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T08:25:00Z' }, + { state: 'APPROVED', at: '2026-09-03T08:28:00Z' }, + { state: 'CLOSED', at: '2026-09-03T08:30:00Z', note: 'PM 交接完成,25min<30min SLA' }, + ], { startedAt: '2026-09-03T08:05:00Z' }), + nodeState('n2_pm_end', 'EQ-张工', [ + { state: 'CREATED', at: '2026-09-03T08:30:00Z', note: '第三 boat 进 reflow 事件触发(T1)' }, + { state: 'ACCEPTED', at: '2026-09-03T08:32:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T08:35:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T10:25:00Z' }, + { state: 'APPROVED', at: '2026-09-03T10:28:00Z' }, + { state: 'CLOSED', at: '2026-09-03T10:30:00Z', note: 'PM 结束,115min<4h SLA' }, + ], { startedAt: '2026-09-03T08:35:00Z' }), + nodeState('n3_conversion_start', 'EA-赵工', [ + { state: 'CREATED', at: '2026-09-03T10:30:00Z', note: 'OTA 调 recipe + 设备 Log 事件触发(T1)' }, + { state: 'ACCEPTED', at: '2026-09-03T10:32:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T10:35:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T10:48:00Z' }, + { state: 'APPROVED', at: '2026-09-03T10:49:00Z' }, + { state: 'CLOSED', at: '2026-09-03T10:50:00Z', note: 'Conversion 开始,15min=SLA 上限(未超时)' }, + ], { startedAt: '2026-09-03T10:35:00Z' }), + nodeState('n4_setup_mfg_start', 'MFG-李工', [ + { state: 'CREATED', at: '2026-09-03T11:05:00Z', note: 'Xray 图片 + 5min 时间触发(T2),锚点 11:00' }, + { state: 'ACCEPTED', at: '2026-09-03T11:06:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T11:07:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T11:35:00Z', note: '★ 超 20min SLA(截止 11:27),升级 MFG 主管后提交' }, + { state: 'APPROVED', at: '2026-09-03T11:38:00Z' }, + { state: 'CLOSED', at: '2026-09-03T11:40:00Z', note: 'MFG 换型开始完成(曾超时升级,留痕)' }, + ], { startedAt: '2026-09-03T11:07:00Z', escalated: true, escalatedTo: 'MFG 主管' }), + nodeState('n5_setup_mfg_end', 'MFG-李工', [ + { state: 'CREATED', at: '2026-09-03T11:40:00Z', note: '第一盘炉后确认 + 5min 条件触发(T3)' }, + { state: 'ACCEPTED', at: '2026-09-03T11:42:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T11:45:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T12:05:00Z' }, + { state: 'APPROVED', at: '2026-09-03T12:08:00Z' }, + { state: 'CLOSED', at: '2026-09-03T12:10:00Z', note: 'MFG 换型结束(无 SLA)' }, + ], { startedAt: '2026-09-03T11:45:00Z' }), + nodeState('n6_qc_verify', 'QA-王工', [ + { state: 'CREATED', at: '2026-09-03T12:10:00Z', note: '质量门:QA 手动核准(T4,事务内)' }, + { state: 'ACCEPTED', at: '2026-09-03T12:12:00Z' }, + { state: 'IN_PROGRESS', at: '2026-09-03T12:15:00Z' }, + { state: 'SUBMITTED', at: '2026-09-03T12:30:00Z', note: '★ 质量确认已提交,待 QA 主管核准;未核准前整链不得关闭' }, + ], { startedAt: '2026-09-03T12:15:00Z' }), + nodeState('n7_setup_ea_end', 'EA-赵工', [ + { state: 'CREATED', at: '2026-09-03T10:55:00Z', by: '系统(T6 派生)', + note: 'Xray 图片 − 5min 派生(T6),锚点 11:00 → 10:55;受 n6 质量门阻挡,未激活' }, + ]), + ], +}; + +/** 演示实例的「模拟」标注(全站统一,与 disclosure SIM_BADGE 同义)。 */ +export const CHAIN_SEED_NOTE = + '换型链实例为模拟种子(业务日 2026-09-03,SRF 演示线),时刻为演示假设,不是客户生产实况。' + + 'n7 派生时刻由 Xray 锚点现算(n7=n4−10min),不写死;n6 质量门未核准前 n7 不可激活、整链不可关闭。'; + +/* ══════════════════════════════════════════════════════════════════ + * 五、现算统计(供校验脚本与任务中心引用,数字一律现算) + * ══════════════════════════════════════════════════════════════════ */ + +export function chainDslStats() { + const eng = chainStats(SRF_CHAIN); + const seed = CHAIN_SEED; + const anchorEpoch = seed.xrayAnchor !== undefined ? isoToEpoch(seed.xrayAnchor) : undefined; + const derived = anchorEpoch !== undefined ? deriveSetupTimes(anchorEpoch) : undefined; + const close = canCloseChain(SRF_CHAIN, seed.nodes); + const activateN7 = canActivateNode('n7_setup_ea_end', SRF_CHAIN, seed.nodes); + return { + ...eng, + triggerCount: CHAIN_TRIGGERS.length, + implementedTriggers: CHAIN_TRIGGERS.filter((t) => t.implemented).length, + placeholderTriggers: CHAIN_TRIGGERS.filter((t) => !t.implemented).map((t) => t.id), + formSlaCount: FORM_SLA_ESCALATION.length, + setupOffsetMin: SETUP_OFFSET_MIN, + seed: { + id: seed.id, + deviceId: seed.deviceId, + bizDate: seed.bizDate, + lot: seed.lot, + nodeStates: seed.nodes.map((n) => ({ nodeId: n.nodeId, state: n.state })), + gateSatisfied: gateSatisfied(SRF_CHAIN, seed.nodes), + canClose: close.ok, + pendingNodes: close.pendingNodes ?? [], + n7Activatable: activateN7.ok, + n7BlockedByGates: activateN7.blockedByGates ?? [], + escalatedNodes: seed.nodes.filter((n) => n.escalated).map((n) => n.nodeId), + xrayAnchor: seed.xrayAnchor, + n4DerivedEpoch: derived?.n4StartEpoch, + n7DerivedEpoch: derived?.n7EndEpoch, + /** T6 不变量:n7=n4−10min(600s),现算校验 */ + n7IsN4Minus10min: derived !== undefined && reverseDeriveN7(derived.n4StartEpoch) === derived.n7EndEpoch, + derivedGapSec: derived !== undefined ? derived.n4StartEpoch - derived.n7EndEpoch : undefined, + }, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ontology.ts b/src/modules/tfamd-oee/data/ontology.ts new file mode 100644 index 0000000..9428134 --- /dev/null +++ b/src/modules/tfamd-oee/data/ontology.ts @@ -0,0 +1,515 @@ +import { + customers, items, productionOrders, purchaseOrders, salesOrders, suppliers, + workOrderMaterials, type Customer, type Item, type ProductionOrder, type PurchaseOrder, + type SalesOrder, type Supplier, type WorkOrderMaterial, +} from './ibp'; + +/** + * 业务本体(Ontology)层:把 Excel 五张单据表抽象成「对象—关系—规则—动作」四件套。 + * 所有实例数、关系基数、规则命中数都在这里从原始单据实时算出,页面不写死任何统计数字。 + * 数据快照日与风险报告保持一致:2026-10-17。 + */ +export const ONTOLOGY_AS_OF = '2026-10-17'; + +export type AttrType = 'string' | 'number' | 'date' | 'enum'; +export interface OntAttr { name: string; en: string; type: AttrType; required: boolean; note?: string } + +export interface OntInstance { + id: string; title: string; sub: string; meta: string; + amount?: number; badge?: string; tone?: 'success' | 'warning' | 'danger' | 'info'; +} + +export interface OntObject { + id: string; name: string; en: string; desc: string; source: string; + color: string; attrs: OntAttr[]; instances: () => OntInstance[]; +} + +export interface OntRelation { + id: string; from: string; to: string; name: string; cardinality: string; + key: string; desc: string; count: () => number; +} + +export type Severity = 'error' | 'warning' | 'info'; +/** 语义色档位:组件层按这个键去主题 token 里取色,深浅主题各有一套 */ +export type Tone = 'success' | 'warning' | 'danger' | 'info'; +export interface OntRule { + id: string; name: string; severity: Severity; on: string; expr: string; desc: string; + /** 数据缺口规则跑不出结果,标灰而不是标绿 */ + blocked?: boolean; + hits: () => { n: number; unit: string; targets: string[] }; +} + +export type ActionType = 'query' | 'alert' | 'report' | 'workflow'; +export interface OntAction { + id: string; name: string; en: string; object: string; type: ActionType; + trigger: string; desc: string; targets?: () => string[]; +} + +/* ── 小工具:属性元组展开、日期差、金额 ───────────────────────────────── */ +type T = [string, string, AttrType] | [string, string, AttrType, 0 | 1] | [string, string, AttrType, 0 | 1, string]; +const attrs = (list: T[]): OntAttr[] => + list.map(([name, en, type, req, note]) => ({ name, en, type, required: req === 1, note })); +const day = (s: string) => new Date(`${s}T00:00:00`).getTime(); +const diff = (a: string, b: string) => Math.round((day(a) - day(b)) / 86400000); +const money = (n: number) => `¥${n.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; +const AS_OF_TS = day(ONTOLOGY_AS_OF); + +/** 采购订单头:按采购订单号归并,齐套日取组内**最晚**到货日(首行会低估,最大差 18 天) */ +export interface PurchaseGroup { + no: string; date: string; supplier: string; supplierCode: string; so: string; + lines: number; amount: number; lastArrival: string; firstArrival: string; unapproved: number; +} +export function purchaseGroups(): PurchaseGroup[] { + const map = new Map(); + purchaseOrders.forEach((p: PurchaseOrder) => { + let g = map.get(p.采购订单号); + if (!g) { + g = { + no: p.采购订单号, date: p.采购日期, supplier: p.供应商简称, supplierCode: p.供应商编码, + so: p.来源销售订单号, lines: 0, amount: 0, lastArrival: p.预计到货日期, + firstArrival: p.预计到货日期, unapproved: 0, + }; + map.set(p.采购订单号, g); + } + g.lines += 1; + g.amount += p.含税金额; + if (p.预计到货日期 > g.lastArrival) g.lastArrival = p.预计到货日期; + if (p.预计到货日期 < g.firstArrival) g.firstArrival = p.预计到货日期; + if (p.订单状态 !== '生效') g.unapproved += 1; + }); + return [...map.values()].sort((a, b) => (a.date < b.date ? 1 : -1)); +} + +/** 销售订单 → 工单 → 采购 的关键路径中间量,规则层、关系层与对话回答引擎共用同一份计算 */ +export interface PathRow { + so: SalesOrder; wo: ProductionOrder; lines: PurchaseOrder[]; + lastArrival: string; kitLag: number; critLag: number; buffer: number; + toFinish: number; unfinished: boolean; unapproved: number; +} +export function paths(): PathRow[] { + const woBySo = new Map(productionOrders.map(w => [w.来源销售订单号, w])); + const poBySo = new Map(); + purchaseOrders.forEach(p => { + const arr = poBySo.get(p.来源销售订单号) ?? []; + arr.push(p); + poBySo.set(p.来源销售订单号, arr); + }); + return salesOrders.map(s => { + const w = woBySo.get(s.销售订单号)!; + const ps = poBySo.get(s.销售订单号) ?? []; + const lastArrival = ps.reduce((a, p) => (p.预计到货日期 > a ? p.预计到货日期 : a), ''); + return { + so: s, wo: w, lines: ps, + lastArrival, + /** 齐套日 − 计划开工:正数=开工时料未到齐 */ + kitLag: lastArrival ? diff(lastArrival, w.预计开工日期) : 0, + /** 齐套日 − 计划完工:正数=按现排程必然延期 */ + critLag: lastArrival ? diff(lastArrival, w.预计完工日期) : 0, + /** 交期缓冲:完工日距发货日还有几天 */ + buffer: diff(s.预计发货日期, w.预计完工日期), + /** 距计划完工剩余天数(负数=已超期) */ + toFinish: Math.round((day(w.预计完工日期) - AS_OF_TS) / 86400000), + unfinished: w.单据状态 !== '已完工', + unapproved: ps.filter(p => p.订单状态 !== '生效').length, + }; + }); +} +/** 模块级快照:规则层与对话层读同一份,避免每次调用重算 */ +export const PATH = paths(); + +/* ── 对象 Object ─────────────────────────────────────────────────────── */ +export const objects: OntObject[] = [ + { + id: 'so', name: '销售订单', en: 'SalesOrder', color: '#818cf8', + desc: '客户下单的履约起点,也是全部风险计算的锚点:交期、数量、金额都挂在它身上。', + source: 'Excel「销售订单」· 2,366 行原表按选取规则抽 17 行', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['销售订单号', 'so_no', 'string', 1, '履约链路主键'], + ['单据日期', 'doc_date', 'date', 1], ['客户编码', 'cust_code', 'string', 1], + ['客户分类', 'cust_class', 'enum'], ['客户简称', 'cust_abbr', 'string', 1, '取往来单位表助记码'], + ['产品编码', 'item_code', 'string', 1], ['数量', 'qty', 'number', 1], + ['含税单价', 'price_incl_tax', 'number', 1], ['含税金额', 'amount_incl_tax', 'number', 1, '数量 × 含税单价'], + ['预计发货日期', 'ship_date', 'date', 1, '交期'], ['仓库名称', 'wh_name', 'string'], + ['制单人', 'creator', 'string'], ['单据状态', 'doc_status', 'enum'], + ]), + instances: () => salesOrders.map((s: SalesOrder) => ({ + id: s.销售订单号, title: s.销售订单号, sub: `${s.客户简称} · ${s.产品编码}`, + meta: `发货 ${s.预计发货日期} · ${s.数量.toLocaleString()} PCS`, amount: s.含税金额, + badge: s.单据状态, tone: 'success' as const, + })), + }, + { + id: 'wo', name: '生产工单', en: 'WorkOrder', color: '#38bdf8', + desc: '一张销售订单对应一张工单(工单号 = WO-销售订单号)。开工/完工日期是按交期倒推的模拟字段。', + source: 'Excel「生产工单」· 由销售交期倒推生成', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['工单号', 'wo_no', 'string', 1, 'WO-销售订单号'], + ['来源销售订单号', 'so_no', 'string', 1], ['产品编码', 'item_code', 'string', 1], + ['规格型号', 'spec', 'string', 0, '仅 BOM 样例有值'], ['计量单位', 'uom', 'enum'], + ['生产数量', 'qty', 'number', 1], ['生产车间', 'workshop', 'enum', 0, '无 BOM 默认「分卷组」'], + ['预计开工日期', 'plan_start', 'date', 1, '模拟推断'], ['预计完工日期', 'plan_finish', 'date', 1, '模拟推断=交期−2天'], + ['生产周期(天)', 'cycle_days', 'number', 1, '按数量分档 7/10/14'], ['BOM版本', 'bom_version', 'string'], + ['单据状态', 'doc_status', 'enum', 0, '完工日不早于快照日记为已下达'], + ]), + instances: () => productionOrders.map((w: ProductionOrder) => ({ + id: w.工单号, title: w.工单号, sub: `${w.产品编码} · ${w.生产车间}`, + meta: `${w.预计开工日期} → ${w.预计完工日期} · ${w['生产周期(天)']}天`, + badge: w.单据状态, tone: w.单据状态 === '已完工' ? 'success' as const : 'info' as const, + })), + }, + { + id: 'wom', name: '工单材料明细', en: 'WorkOrderMaterial', color: '#34d399', + desc: '工单要领哪些料、各领多少。54/63 行由采购需求反推,只有 9 行来自真实 BOM 展开。', + source: 'Excel「工单材料明细」· BOM 展开 + 采购需求反推', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['工单号', 'wo_no', 'string', 1], + ['来源销售订单号', 'so_no', 'string', 1], ['产品编码', 'item_code', 'string', 1], + ['材料编码', 'mat_code', 'string', 1], ['规格型号', 'spec', 'string'], + ['计量单位', 'uom', 'enum', 0, '反推行统一按 PCS'], ['工单数量', 'wo_qty', 'number', 1], + ['单位用量', 'unit_usage', 'number', 1, 'BOM 需用量 ÷ BOM 生产数量'], + ['损耗率', 'loss_rate', 'number', 0, '54 行为空'], ['应领数量', 'required_qty', 'number', 1, '工单数量 × 单位用量 × (1+损耗率)'], + ['预出仓库', 'issue_wh', 'enum'], ['材料来源', 'source_type', 'enum', 1, 'BOM展开 / 采购需求反推'], + ['BOM版本', 'bom_version', 'string'], ['子件BOM', 'child_bom', 'string'], + ]), + instances: () => workOrderMaterials.map((m: WorkOrderMaterial) => ({ + id: `${m.工单号}-${m.材料编码}-${m.序号}`, title: m.材料编码, + sub: `${m.工单号} · ${m.材料来源}`, + meta: `应领 ${m.应领数量.toLocaleString()} ${m.计量单位} · 出 ${m.预出仓库}`, + badge: m.材料来源 === 'BOM展开' ? 'BOM' : '反推', + tone: m.材料来源 === 'BOM展开' ? 'success' as const : 'warning' as const, + })), + }, + { + id: 'po', name: '采购订单', en: 'PurchaseOrder', color: '#fbbf24', + desc: '为工单缺口下的采购单,行级带预计到货日期。齐套日必须取组内最晚到货行,取首行最多会低估 18 天。', + source: 'Excel「材料采购订单」· 7,472 行原表抽 54 行 / 29 单', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['采购订单号', 'po_no', 'string', 1], + ['采购日期', 'po_date', 'date', 1], ['来源销售订单号', 'so_no', 'string', 1], + ['产品工单号', 'wo_no', 'string', 1], ['供应商编码', 'sup_code', 'string', 1], + ['供应商简称', 'sup_abbr', 'string', 1], ['材料编码', 'mat_code', 'string', 1], + ['数量', 'qty', 'number', 1], ['单价', 'price', 'number', 1], + ['含税金额', 'amount_incl_tax', 'number', 1], ['预计到货日期', 'eta_date', 'date', 1, '行级,齐套取 MAX'], + ['订单状态', 'doc_status', 'enum', 1, '生效 / 未审'], ['来源单据', 'src_doc', 'enum', 0, '本批全部=请购单'], + ]), + instances: () => purchaseGroups().map(g => ({ + id: g.no, title: g.no, sub: `${g.supplier} · ${g.lines} 行`, + meta: `下单 ${g.date} · 齐套 ${g.lastArrival}`, amount: g.amount, + badge: g.unapproved ? `未审 ${g.unapproved} 行` : '生效', + tone: g.unapproved ? 'danger' as const : 'success' as const, + })), + }, + { + id: 'cus', name: '客户', en: 'Customer', color: '#a78bfa', + desc: '本批销售订单涉及的往来客户。订单笔数与金额为表内汇总口径,与销售订单同源可核对。', + source: 'Excel「客户资料」· 由往来单位表(1,003 家)过滤', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['客户编码', 'cust_code', 'string', 1], + ['客户简称', 'cust_abbr', 'string', 1, '助记码,源表无工商全称'], + ['性质', 'nature', 'enum', 1, '客户 / 客户·供应商(客商一体)'], + ['客户分类', 'cust_class', 'enum'], ['所属类别', 'category', 'enum'], + ['分管部门', 'dept', 'string', 0, '1 家未填'], ['订单笔数', 'so_count', 'number', 1], + ['订单金额', 'so_amount', 'number', 1], + ]), + instances: () => customers.map((c: Customer) => ({ + id: c.客户编码, title: c.客户简称, sub: `${c.客户编码} · ${c.客户分类}`, + meta: `${c.订单笔数} 笔订单 · ${c.分管部门 || '分管部门未填'}`, amount: c.订单金额, + badge: c.性质, tone: c.性质 === '客户/供应商' ? 'warning' as const : 'info' as const, + })), + }, + { + id: 'sup', name: '供应商', en: 'Supplier', color: '#f472b6', + desc: '本批采购订单涉及的供货方。采购行数与金额为该供应商在本批的合计。', + source: 'Excel「供应商资料」· 由往来单位表(1,003 家)过滤', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['供应商编码', 'sup_code', 'string', 1], + ['供应商简称', 'sup_abbr', 'string', 1, '助记码,无工商全称'], + ['性质', 'nature', 'enum', 1], ['所属类别', 'category', 'enum'], + ['分管部门', 'dept', 'string', 0, '1 家未填'], ['采购行数', 'po_lines', 'number', 1], + ['采购金额', 'po_amount', 'number', 1], + ]), + instances: () => suppliers.map((s: Supplier) => ({ + id: s.供应商编码, title: s.供应商简称, sub: `${s.供应商编码} · ${s.所属类别}`, + meta: `${s.采购行数} 行采购 · ${s.分管部门 || '分管部门未填'}`, amount: s.采购金额, + badge: s.性质, tone: s.性质 === '客户/供应商' ? 'warning' as const : 'info' as const, + })), + }, + { + id: 'mat', name: '物料(成品 / 材料)', en: 'Item', color: '#22d3ee', + desc: '销售侧成品与工单侧材料共用一套编码体系;仅 2 个产品有真实 BOM,规格型号大面积缺失。', + source: 'Excel「物料」· 由销售/工单/采购/BOM 汇总去重', + attrs: attrs([ + ['序号', 'seq', 'number', 1], ['物料编码', 'item_code', 'string', 1], + ['类型', 'item_type', 'enum', 1, '成品 / 材料'], ['规格型号', 'spec', 'string', 0, '仅 8/70 有值'], + ['计量单位', 'uom', 'enum', 1, '69 PCS + 1 KG'], ['BOM版本', 'bom_version', 'string', 0, '大小写混用 v1.0 / V1.0'], + ['数据来源', 'source_type', 'enum', 1, '销售订单/生产工单 · BOM展开 · 采购需求反推'], + ]), + instances: () => items.map((i: Item) => ({ + id: i.物料编码, title: i.物料编码, sub: `${i.类型} · ${i.计量单位}${i.规格型号 ? ` · ${i.规格型号}` : ''}`, + meta: `${i.数据来源}${i.BOM版本 ? ` · BOM ${i.BOM版本}` : ''}`, + badge: i.类型, tone: i.类型 === '成品' ? 'info' as const : 'success' as const, + })), + }, + { + id: 'wh', name: '仓库', en: 'Warehouse', color: '#94a3b8', + desc: '从销售入库仓与工单预出仓库两个方向派生出的仓位节点,本批共 4 个。库存数量字段缺失,仓库目前只是位置节点。', + source: '派生:销售订单.仓库名称 + 工单材料明细.预出仓库', + attrs: attrs([ + ['仓库名称', 'wh_name', 'string', 1, '源表无仓库编码'], + ['角色', 'role', 'enum', 1, '成品入库仓 / 工单预出仓'], + ['关联单据行数', 'ref_lines', 'number', 1, '派生统计'], + ['现存量', 'onhand_qty', 'number', 0, '数据缺口:源表无此字段'], + ['安全库存', 'safety_stock', 'number', 0, '数据缺口'], + ]), + instances: () => { + const inWh = new Map(); + salesOrders.forEach(s => inWh.set(s.仓库名称, (inWh.get(s.仓库名称) ?? 0) + 1)); + const outWh = new Map(); + workOrderMaterials.forEach(m => outWh.set(m.预出仓库, (outWh.get(m.预出仓库) ?? 0) + 1)); + return [ + ...[...inWh].map(([name, n]) => ({ + id: `wh-in-${name}`, title: name, sub: '成品入库仓 · 销售订单', + meta: `${n} 张销售订单`, badge: '入库', tone: 'info' as const, + })), + ...[...outWh].map(([name, n]) => ({ + id: `wh-out-${name}`, title: name, sub: '工单预出仓 · 材料明细', + meta: `${n} 行领料需求`, badge: '预出', tone: 'success' as const, + })), + ]; + }, + }, +]; + +/* ── 关系 Relation ───────────────────────────────────────────────────── */ +const matFromPo = new Set(purchaseOrders.map(p => p.材料编码)); +const matFromWom = new Set(workOrderMaterials.map(m => m.材料编码)); +const supMatPairs = new Set(purchaseOrders.map(p => `${p.供应商编码}|${p.材料编码}`)); + +export const relations: OntRelation[] = [ + { + id: 'r-cus-so', from: 'cus', to: 'so', name: '下单', cardinality: '1:N', + key: '客户编码', desc: '11 家客户共下 17 张销售订单,单客户最多 2 张(选取规则限制)。', + count: () => salesOrders.length, + }, + { + id: 'r-so-wo', from: 'so', to: 'wo', name: '生成', cardinality: '1:1', + key: '工单号 = WO-销售订单号', desc: '链路主键可直接推导,17/17 全部吻合,无断链。', + count: () => productionOrders.filter(w => w.工单号 === `WO-${w.来源销售订单号}`).length, + }, + { + id: 'r-wo-wom', from: 'wo', to: 'wom', name: '展开', cardinality: '1:N', + key: '工单号', desc: '工单按 BOM 或采购需求展开成领料明细,共 63 行。', + count: () => workOrderMaterials.length, + }, + { + id: 'r-wom-mat', from: 'wom', to: 'mat', name: '领用', cardinality: 'N:1', + key: '材料编码', desc: '工单需求涉及 56 种材料,其中 54 种能在采购订单里找到。', + count: () => matFromWom.size, + }, + { + id: 'r-mat-po', from: 'mat', to: 'po', name: '采购为', cardinality: '1:N', + key: '材料编码', desc: '54 行采购覆盖 54 种材料,每种材料在本批只出现一次。', + count: () => matFromPo.size, + }, + { + id: 'r-sup-po', from: 'sup', to: 'po', name: '承接', cardinality: 'N:M', + key: '供应商编码 × 材料编码', desc: '17 家供应商承接 54 行采购;供应商-材料配对 54 组,全部单源。', + count: () => supMatPairs.size, + }, + { + id: 'r-po-so', from: 'po', to: 'so', name: '回链', cardinality: 'N:1', + key: '来源销售订单号', desc: '采购行回指销售订单,形成闭环;本批 54/54 行都有来源单号。', + count: () => purchaseOrders.filter(p => !!p.来源销售订单号).length, + }, + { + id: 'r-so-wh', from: 'so', to: 'wh', name: '入库', cardinality: 'N:1', + key: '仓库名称', desc: '成品入库仓只有「OEM事业部成品仓」一个节点,无仓位分仓数据。', + count: () => new Set(salesOrders.map(s => s.仓库名称)).size, + }, + { + id: 'r-wom-wh', from: 'wom', to: 'wh', name: '预出', cardinality: 'N:1', + key: '预出仓库', desc: '领料从 3 个预出仓发出;反推行的预出仓库按辅料仓等默认值填写。', + count: () => new Set(workOrderMaterials.map(m => m.预出仓库)).size, + }, + { + id: 'r-cus-sup', from: 'cus', to: 'sup', name: '客商一体', cardinality: 'N:M', + key: '性质 = 客户/供应商', desc: '1 家客户与 4 家供应商性质为客商一体;客户编码与供应商编码在本批无交集,只能靠性质字段标注。', + count: () => customers.filter(c => c.性质 === '客户/供应商').length + suppliers.filter(s => s.性质 === '客户/供应商').length, + }, +]; + +/* ── 规则 Rule(全部实时计算,命中数会随数据变化) ─────────────────────── */ +export const rules: OntRule[] = [ + { + id: 'r-crit', name: '关键路径冲突', severity: 'error', on: '销售订单', + expr: 'MAX(采购.预计到货日期) > 工单.预计完工日期', + desc: '料全到齐那天已经晚于计划完工日,按现排程必然延期。', + hits: () => { + const t = PATH.filter(p => p.critLag > 0); + return { n: t.length, unit: '张订单', targets: t.map(p => p.so.销售订单号) }; + }, + }, + { + id: 'r-kit', name: '齐套延迟', severity: 'warning', on: '生产工单', + expr: 'MAX(采购.预计到货日期) > 工单.预计开工日期', + desc: '开工日物料未到齐。缺库存字段,无法用线边库存降噪,命中偏保守。', + hits: () => { + const t = PATH.filter(p => p.kitLag > 0); + return { n: t.length, unit: `张订单(>7天 ${PATH.filter(p => p.kitLag > 7).length})`, targets: t.map(p => p.so.销售订单号) }; + }, + }, + { + id: 'r-approve', name: '采购审批完备', severity: 'error', on: '采购订单', + expr: '采购.订单状态 ≠ 生效', + desc: '未审批的采购行不构成到料承诺,尤其压在长周期物料上时风险最高。', + hits: () => { + const t = purchaseOrders.filter(p => p.订单状态 !== '生效'); + return { n: t.length, unit: `行 / ${new Set(t.map(p => p.来源销售订单号)).size} 张订单`, targets: [...new Set(t.map(p => p.来源销售订单号))] }; + }, + }, + { + id: 'r-trace', name: '追溯链完整', severity: 'error', on: '采购订单', + expr: '来源销售订单号为空 或 产品工单号 ≠ WO-销售订单号', + desc: '断链的采购行无法归集到订单,风险敞口会算漏。', + hits: () => { + const t = purchaseOrders.filter(p => !p.来源销售订单号 || p.产品工单号 !== `WO-${p.来源销售订单号}`); + return { n: t.length, unit: '行', targets: [...new Set(t.map(p => p.来源销售订单号))] }; + }, + }, + { + id: 'r-buffer', name: '交期缓冲下限', severity: 'warning', on: '销售订单', + expr: '销售.预计发货日期 − 工单.预计完工日期 < 5 天 且 工单未完工', + desc: '本批缓冲全为 2 天,是模拟排程(完工=交期−2)造成的,接真实排程后才有区分度。', + hits: () => { + const t = PATH.filter(p => p.unfinished && p.buffer < 5); + return { n: t.length, unit: '张订单', targets: t.map(p => p.so.销售订单号) }; + }, + }, + { + id: 'r-overdue', name: '采购在途逾期', severity: 'warning', on: '采购订单', + expr: '采购.预计到货日期 < 快照日 且 未收到货', + desc: '源表只有 生效/未审 两种状态、没有收货字段,因此只能提疑、不能定案。', + hits: () => { + const t = purchaseOrders.filter(p => day(p.预计到货日期) < AS_OF_TS); + return { n: t.length, unit: `行 ${money(t.reduce((a, p) => a + p.含税金额, 0))}`, targets: [...new Set(t.map(p => p.来源销售订单号))] }; + }, + }, + { + id: 'r-missing-po', name: '漏采核查', severity: 'error', on: '工单材料明细', + expr: 'BOM 展开材料 ∉ 采购订单材料集合', + desc: '只有 2 张单有真 BOM 可做这项检验;其余 15 张的需求本身由采购反推,属循环论证,不计入。', + hits: () => { + const t = [...matFromWom].filter(m => !matFromPo.has(m)); + const so = [...new Set(workOrderMaterials.filter(m => t.includes(m.材料编码)).map(m => m.来源销售订单号))]; + return { n: t.length, unit: `种材料 · ${so.length} 张订单`, targets: so }; + }, + }, + { + id: 'r-bom', name: 'BOM 完备性', severity: 'warning', on: '生产工单', + expr: '工单.BOM版本 为空或「—」', + desc: '无 BOM 的工单,其材料需求不可信,风险结论要降置信度。', + hits: () => { + const t = productionOrders.filter(w => !w.BOM版本 || w.BOM版本 === '—'); + return { n: t.length, unit: `张工单 / ${productionOrders.length}`, targets: t.map(w => w.来源销售订单号) }; + }, + }, + { + id: 'r-single', name: '单源供应', severity: 'info', on: '供应商', + expr: 'COUNT(DISTINCT 供应商) GROUP BY 材料 = 1', + desc: '本批 54 种材料全部只有一家供应商,指标无区分度(等于全员告警),需接物料主数据的多源配额才有意义。', + hits: () => ({ n: matFromPo.size, unit: '种材料单源', targets: [] }), + }, + { + id: 'r-stock', name: '库存可用量校验', severity: 'error', on: '仓库', + expr: '需求数量 ≤ 现存量 − 已分配 + 在途入库', + desc: '数据缺口:源表无现存量、已分配、安全库存、在途入库,规则无法执行。', + blocked: true, + hits: () => ({ n: 0, unit: '无法计算(缺 4 个字段)', targets: [] }), + }, +]; + +/* ── 动作 Action ─────────────────────────────────────────────────────── */ +const ruleTargets = (id: string) => rules.find(r => r.id === id)!.hits().targets; + +export const actions: OntAction[] = [ + { + id: 'a-expedite', name: '催料提醒', en: 'expedite_material', object: '采购订单', type: 'alert', + trigger: '规则「齐套延迟」命中', desc: '向供应商发出到货确认,按最晚到货行逐行催料。', + targets: () => ruleTargets('r-kit'), + }, + { + id: 'a-approve', name: '推进采购审批', en: 'push_po_approval', object: '采购订单', type: 'workflow', + trigger: '规则「采购审批完备」命中', desc: '把未审行推给采购科,优先处理交付周期最长的物料。', + targets: () => ruleTargets('r-approve'), + }, + { + id: 'a-reschedule', name: '重排开工日', en: 'reschedule_start', object: '生产工单', type: 'workflow', + trigger: '规则「关键路径冲突」命中', desc: '把开工日后移到齐套日之后,或申请压缩生产周期。', + targets: () => ruleTargets('r-crit'), + }, + { + id: 'a-split', name: '拆单先发', en: 'split_and_ship', object: '销售订单', type: 'workflow', + trigger: '缓冲 < 5 天且齐套延迟', desc: '与客户协商分批交付,先发到料齐全的部分。', + targets: () => ruleTargets('r-crit'), + }, + { + id: 'a-missing', name: '漏采核查', en: 'check_missing_po', object: '工单材料明细', type: 'alert', + trigger: '规则「漏采核查」命中', desc: '确认是走库存直接领料,还是确实漏下采购单。', + targets: () => ruleTargets('r-missing-po'), + }, + { + id: 'a-sup-confirm', name: '供应商交期确认', en: 'confirm_eta', object: '供应商', type: 'report', + trigger: '齐套延迟 > 7 天', desc: '按供应商汇总需确认的到货承诺清单。', + targets: () => { + const sos = new Set(ruleTargets('r-kit')); + return [...new Set(purchaseOrders.filter(p => sos.has(p.来源销售订单号)).map(p => p.供应商编码))]; + }, + }, + { + id: 'a-cust-impact', name: '客户影响评估', en: 'assess_cust_impact', object: '客户', type: 'query', + trigger: '红色订单关联客户', desc: '按客户汇总延期敞口,决定沟通顺序。', + targets: () => { + const sos = new Set(ruleTargets('r-crit')); + return [...new Set(salesOrders.filter(s => sos.has(s.销售订单号)).map(s => s.客户编码))]; + }, + }, + { + id: 'a-ledger', name: '生成风险台账', en: 'export_risk_ledger', object: '销售订单', type: 'report', + trigger: '每日快照', desc: '输出 17 单 × 风险分 / 等级 / 触发规则的台账,供计划员晨会。', + targets: () => salesOrders.map(s => s.销售订单号), + }, + { + id: 'a-substitute', name: '替代料查询', en: 'query_substitute', object: '物料', type: 'query', + trigger: '单源材料断供', desc: '数据缺口:物料主数据无替代料清单,暂不可执行。', + }, + { + id: 'a-inventory', name: '库存快照补数', en: 'request_inventory_snapshot', object: '仓库', type: 'workflow', + trigger: '规则「库存可用量校验」被阻塞', desc: '向 IT 提数:现存量、已分配、安全库存、在途入库四列,日刷。', + }, + { + id: 'a-trace-check', name: '追溯链体检', en: 'check_traceability', object: '采购订单', type: 'query', + trigger: '每次数据导入后', desc: '校验采购行能否 100% 回链到销售订单与工单。', + targets: () => ruleTargets('r-trace'), + }, + { + id: 'a-bom-backfill', name: 'BOM 补全', en: 'backfill_bom', object: '生产工单', type: 'workflow', + trigger: '规则「BOM 完备性」命中', desc: '为无 BOM 工单补真实结构,消除需求反推带来的循环论证。', + targets: () => ruleTargets('r-bom'), + }, + { + id: 'a-locate', name: '定位到订单', en: 'locate_order', object: '销售订单', type: 'query', + trigger: '任意规则/动作明细', desc: '关闭本体页并在左栏选中该销售订单,联动右栏采购与工单。', + targets: () => salesOrders.map(s => s.销售订单号), + }, +]; + +/* ── 图谱数据:节点半径按关系度数,标签带实例数 ─────────────────────────── */ +export const graphNodes = () => objects.map(o => ({ + id: o.id, label: o.name, count: o.instances().length, color: o.color, +})); +export const graphEdges = () => relations.map(r => ({ + id: r.id, source: r.from, target: r.to, label: r.name, +})); + +export const objectById = (id: string) => objects.find(o => o.id === id); +export const severityColor = (s: Severity): Tone => (s === 'error' ? 'danger' : s === 'warning' ? 'warning' : 'info'); diff --git a/src/modules/tfamd-oee/data/ontologyOee.ts b/src/modules/tfamd-oee/data/ontologyOee.ts new file mode 100644 index 0000000..8acbe95 --- /dev/null +++ b/src/modules/tfamd-oee/data/ontologyOee.ts @@ -0,0 +1,2061 @@ +/** + * 通富超威 · OEE 智能优化 —— 业务本体层(对象—关系—规则—动作)。 + * + * 与品质那套本体**同结构、同 API**(ADR-05:类型直接 import 自 ontologyQap,不重新定义), + * 内容换成建议书 3.6 定义的 9 类对象: + * 设备 / 产线拓扑 / 批次 / 事件 / 状态段 / 损失 / 绩效 / 口径 / 改善 + * + * ★ 四条不可违反的本体纪律: + * 1. **数值唯一来源是 L3 服务层**(lib/oeeService)。本文件不写死任何统计数字, + * 也不自己再跑一遍链路——这是断言②「四处读数一致」在本体层的实现方式。 + * 2. **数据缺口标灰不标绿**:跑不出结果的规则一律 blocked + gap(复用 ontologyQap 模式)。 + * 线体合成待 W2、改善任务待 W3-B、首件检验未接入、班次时刻是演示假设—— + * 这些都如实标缺口,**绝不造实例充数**(尤其不编那"6 条改善任务")。 + * 3. **P0 口径未签字不得显示为达标**:本次不安排口径工作坊,28 项 signedOff 全 false, + * P0 的 16 项 tone 用中性 info(灰),不用 success(绿)。 + * 4. **三套"六"分类不混用**:六-1 损失桶(LossBucket)/ 六-2 ASLT 时间六分类 / + * 六-3 事件表归口用词(GROSS_TO_BUCKET)。本层只承载六-1 与六-3 的映射关系, + * 六-2 属 ASLT 站时间账,W2 接入 ASLT 模板时另建对象,不塞进损失桶。 + * + * ★ tables 字段填**对象 id**(不是物理表名):OntologyView 的聚焦联动按 tables 匹配对象, + * 填物理表名会让高亮静默失效。建议书 3.6 示例里的 'loss_bucket' 是表名口径,此处按视图契约落地。 + */ +import type { + AttrType, OntAttr, OntInstance, OntObject, OntRelation, OntRule, OntAction, OntField, Tone, +} from './ontologyQap'; +import { + DEVICES, DEVICE_BY_ID, LINES, LINE_BY_ID, OEE_DEVICES, ANCHOR_DEVICE_ID, DEMO_ORDER, + SHIFT_PATTERN, SHIFT_ASSUMPTION_NOTE, deviceStats, +} from './oee/devices'; +import { EVENTS_48, EVENT_BY_CODE, eventStats, MISSING_CODES } from './oee/events48'; +import { + CALIBER_ITEMS, CALIBER_CONFIG, CALIBER_VERSION, SENSITIVITY_ISSUES, caliberStats, +} from './oee/calibers28'; +import { + currentDay, dekDays, serviceStats, PARAMS_SIGNOFF_NOTE, + type OeeDayResult, +} from '../lib/oeeService'; +import { DQ_RULES, DQ_RULE_BY_CODE, DQ_DEFAULTS } from '../lib/oee/dq'; +import { defaultGapThresholdMin } from '../lib/oee/stateMachine'; +import { STATE_TO_BUCKET, checkUniqueBucketAssignment } from '../lib/oee/lossBuckets'; +import { + BUCKET_LABEL, BUCKET_FACTOR, LOSS_BUCKETS, STATE_LABEL, GRADE_LABEL, EVENT_STATUS_LABEL, + TEMPLATE_LABEL, ATTR_METHOD_LABEL, GROSS_TO_BUCKET, TASK_STATE_LABEL, BLOCKING_DQ, EPS, + type LossBucket, type EventGrade, +} from '../types/oee'; + +/** 本体版本日。与指标树 METRIC_TREE_AS_OF 同日,便于"说明与对照"页核对同源。 */ +export const OEE_ONTOLOGY_AS_OF = '2026-11-12'; +/** 别名:视图层只换 import 来源即可复用四栏骨架(ADR-05 的落地形式)。 */ +export const ONTOLOGY_AS_OF = OEE_ONTOLOGY_AS_OF; + +/** demo 沙箱固定缺口口径:本工程不接后端。 */ +const REFERENCES_DEMO_SANDBOX_GAP = '本工程为 demo 沙箱,不接后端;数据来自内置合成种子,不冒充实测'; + +/** + * ★ 类型再导出(type-only,编译期擦除):视图层**只依赖本模块**即可拿到四层骨架的全部类型。 + * + * 为什么必须走这里而不是让视图直接 import ontologyQap: + * ontologyQap.ts 自身 `import { … } from './qap'` 取的是**值**, + * 视图一旦从它 import 任何运行时符号,整套品质 JSON 就被拖进 OEE 的包。 + * ADR-05 说"类型直接复用",复用的是类型不是数据——故在此收口成一个接缝。 + * W4-C 删除 data/qap 时,只需把下面这一行的来源换成 types/ontology.ts,视图零改动。 + */ +export type { + AttrType, OntAttr, OntInstance, OntObject, OntRelation, OntRule, OntAction, OntField, + ActionType, Tone, Severity, +} from './ontologyQap'; + +/* ── 取数与格式化小工具(与 ontologyQap 同形) ─────────────────────────── */ +type Row = Record; +const s = (v: unknown) => (v === null || v === undefined || v === '' ? '—' : String(v)); +const num = (v: unknown) => (typeof v === 'number' ? v.toLocaleString('zh-CN') : s(v)); +const pct2 = (v: unknown) => (typeof v === 'number' ? `${(v * 100).toFixed(2)}%` : '—'); +const hhmmss = (iso: string) => iso.slice(11, 19); +const hm = (iso: string) => iso.slice(11, 16); +const filled = (v: unknown) => v !== null && v !== undefined && v !== ''; +const isDate = (v: unknown) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v); + +/** 列类型靠实际值反推:全数值 → number,全日期 → date,取值 ≤6 种 → enum,其余 string */ +function inferType(vals: unknown[]): AttrType { + const got = vals.filter(filled); + if (got.length === 0) return 'string'; + if (got.every((v) => typeof v === 'number')) return 'number'; + if (got.every(isDate)) return 'date'; + if (got.every((v) => typeof v === 'string') && new Set(got).size <= 6) return 'enum'; + return 'string'; +} + +/** 属性表就是表头:必填=该列在全部行里都非空,可空则把非空行数写进口径 */ +function deriveAttrs(rows: Row[]): OntAttr[] { + if (rows.length === 0) return []; + return Object.keys(rows[0]).map((col) => { + const vals = rows.map((r) => r[col]); + const ok = vals.filter(filled).length; + return { + name: col, en: col, type: inferType(vals), required: ok === rows.length, + note: ok === rows.length ? undefined : `非空 ${ok}/${rows.length} 行`, + }; + }); +} + +/* ── L3 取数:全部走服务层,本层不重算 ─────────────────────────────────── */ +const days = (): OeeDayResult[] => dekDays(); +const cur = (): OeeDayResult => currentDay(); +const allEvents = () => days().flatMap((d) => d.normalize.events); +const curEvents = () => cur().normalize.events; + +/** 事件实例 id → 定义。键空间必须是**实例 id**(与 lossBuckets 注入同一纪律)。 */ +const defOfInstance = (id: string) => { + const e = curEvents().find((x) => x.id === id); + return e ? EVENT_BY_CODE[e.defCode] : undefined; +}; + +const bucketOfState = (state: string): LossBucket | undefined => + STATE_TO_BUCKET[state as keyof typeof STATE_TO_BUCKET]; + +const gradeTone = (g: EventGrade): Tone => + g === 'A' ? 'success' : g === 'B' ? 'info' : g === 'C' ? 'warning' : g === 'D' ? 'danger' : 'info'; + +/* ══════════════════════════════════════════════════════════════════ + * 九类对象的行集(属性=表头列,实例=真实行) + * ══════════════════════════════════════════════════════════════════ */ + +/** ① 设备:17 台台账全量。间隙阈值/ICT/编码来源逐台如实标注。 */ +function equipmentRows(): Row[] { + return DEVICES.map((d) => ({ + 设备编码: d.id, + 设备名称: d.name, + 区域: d.region, + 设备类型: d.type, + 所属线体: d.lineId, + 工站: d.station, + 信号完整度: d.capability, + 有日志: d.hasLog ? '是' : '否', + 间隙阈值min: d.gapThresholdMin, + 公式默认阈值min: defaultGapThresholdMin(d.ictSec), + 标准节拍ICT秒: d.ictSec, + 计量单位: d.unit, + 计算模板: TEMPLATE_LABEL[d.template], + 台账编码来源: d.codeSource, + 现场台数: d.pocFleetCount ?? '', + ICT来源: d.ictSource, + ICT口径说明: d.ictNote, + 阈值来源: d.gapSource, + 日志格式: d.logFormat, + 字符编码: d.encoding, + 时间轴重建策略: d.rebuildStrategy, + 解析陷阱: d.adapterTraps.join(';'), + 计入OEE: d.countsForOee ? '是' : '否', + 主流程序号: d.mainPathSeq ?? '', + 能力矩阵: d.capabilityStars + ? `节拍${d.capabilityStars.cycle} Down${d.capabilityStars.down} Jam${d.capabilityStars.jam}` + + ` 待料${d.capabilityStars.wait} 换型${d.capabilityStars.setup} 单件${d.capabilityStars.unit}` + : '', + 总体评价: d.capabilityNote, + 过渡采集通道: d.fallbackChannel ?? '', + Lane数: d.lanes?.length ?? '', + Site数: d.siteCount ?? '', + 演示角色: d.demoRole, + })); +} + +/** ② 产线拓扑:3 条线。合成引擎待 W2,故合成状态如实标"待接入"。 */ +function lineRows(): Row[] { + return LINES.map((l) => { + const devs = l.deviceIds.map((id) => DEVICE_BY_ID[id]).filter(Boolean); + const path = devs.filter((d) => d.mainPathSeq !== undefined) + .sort((a, b) => (a.mainPathSeq ?? 0) - (b.mainPathSeq ?? 0)) + .map((d) => `${d.mainPathSeq} ${d.station}`); + return { + 线体编码: l.id, + 线体名称: l.name, + 区域: l.region, + 计算模板: TEMPLATE_LABEL[l.template], + 设备台数: devs.length, + 计入OEE台数: devs.filter((d) => d.countsForOee).length, + 设备清单: l.deviceIds.join(' / '), + 瓶颈设备: l.bottleneckDeviceId ?? '', + 主流程工站: path.join(' → '), + 有日志台数: devs.filter((d) => d.hasLog).length, + 合成状态: '待 W2 接入(lineSynthesis 未落地)', + 口径说明: l.note, + }; + }); +} + +/** ③ 批次:三日 lot 窗口。DEK 日志直接印 lot 号 → 设备自识别 1.00。 */ +function lotRows(): Row[] { + return days().flatMap((d) => d.lots.map((w) => { + const out = w.outputQty ?? 0; + const good = w.goodQty ?? 0; + const method = w.selfIdentified ? 'SELF_IDENTIFIED' : 'UNATTRIBUTED'; + return { + 业务日: d.bizDate, + 批次号: w.lotId, + 设备: w.device, + 工单号: w.workOrderId ?? '', + 开始时刻: new Date(w.startEpoch * 1000).toISOString(), + 结束时刻: new Date(w.endEpoch * 1000).toISOString(), + 窗口时长秒: w.endEpoch - w.startEpoch, + 投入数: out, + 合格数: good, + 批次良率: out > 0 ? good / out : '', + 归因方式: ATTR_METHOD_LABEL[method], + 归因置信度: w.selfIdentified ? 1.0 : 0.0, + 换型窗口: w.isSetupWindow ? '是' : '否', + 工程批: w.isEngineering ? '是' : '否', + 计入OEE分母: w.isEngineering ? '否(C10 默认剔除 ENG 工程批)' : '是', + 产出证据: out > 0 ? '有完成行锚点' : '无完成行 → 不造窗口', + }; + })); +} + +/** + * ④ 事件:48 条定义 + 当期业务日的事件实例(建议书 3.6「48 定义 + 实例」)。 + * 定义行带现算的实例计数;实例行带原始行号与双时间字段,是断言①血缘链的落点。 + */ +function eventRows(): Row[] { + const curEv = curEvents(); + const allEv = allEvents(); + const defs: Row[] = EVENTS_48.map((e) => ({ + 类别: '定义', + 事件码: e.code, + 事件名: e.name, + 区域: e.region, + 自动化等级: e.grade, + 等级含义: GRADE_LABEL[e.grade], + 形态: e.form, + 适用状态: EVENT_STATUS_LABEL[e.status], + 触发点: e.triggerPoint, + 来源: e.source, + 归口用词: e.grossCategory, + 损失桶: e.bucket ? BUCKET_LABEL[e.bucket] : '不进六桶(计划类)', + 一级因子: e.factorL1, + 二级因子: e.factorL2, + 采集方式: e.acquisition, + 报警类: e.alarmClass ?? '', + 当期实例数: curEv.filter((x) => x.defCode === e.code).length, + 三日实例数: allEv.filter((x) => x.defCode === e.code).length, + 实例id: '', 设备: '', 业务日: '', 原始时刻: '', 校正时刻: '', + 时钟偏移秒: '', 已校正: '', 配对id: '', 配对角色: '', 配对策略: '', + 原始行号: '', 文件路径: '', 摘要哈希: '', 归因批次: '', 归因置信度: '', + })); + const insts: Row[] = curEv.map((x) => { + const e = EVENT_BY_CODE[x.defCode]; + return { + 类别: '实例', + 事件码: x.defCode, + 事件名: e?.name ?? x.defCode, + 区域: e?.region ?? '', + 自动化等级: e?.grade ?? '', + 等级含义: e ? GRADE_LABEL[e.grade] : '', + 形态: x.form, + 适用状态: '', 触发点: '', 来源: '', + 归口用词: e?.grossCategory ?? '', + 损失桶: e?.bucket ? BUCKET_LABEL[e.bucket] : '不进六桶(计划类)', + 一级因子: e?.factorL1 ?? '', + 二级因子: e?.factorL2 ?? '', + 采集方式: e?.acquisition ?? '', + 报警类: e?.alarmClass ?? '', + 当期实例数: '', 三日实例数: '', + 实例id: x.id, + 设备: x.device, + 业务日: cur().bizDate, + 原始时刻: x.rawTime, + 校正时刻: x.correctedTime, + 时钟偏移秒: x.clockOffsetSec ?? '', + 已校正: x.isCorrected ? '是' : '否', + 配对id: x.pairId ?? '', + 配对角色: x.pairRole ?? '', + 配对策略: x.pairStrategy ?? '', + 原始行号: x.evidence.lineNo, + 文件路径: x.evidence.filePath, + 摘要哈希: x.evidence.digest, + 归因批次: x.attribution?.lotId ?? '', + 归因置信度: x.attribution?.confidence ?? '', + }; + }); + return [...defs, ...insts]; +} + +/** ⑤ 状态段:当期业务日。十态抢占优先级 + 影子时长 + 间隙填充来源全部留证。 */ +function segmentRows(): Row[] { + const d = cur(); + return d.segments.segments.map((g) => ({ + 段id: g.id, + 设备: g.device, + 业务日: g.bizDate, + 状态码: g.state, + 状态名: STATE_LABEL[g.state], + 抢占优先级: g.priority, + 开始时刻: g.start, + 结束时刻: g.end, + 时长秒: g.durationSec, + 班次: g.shiftId, + 跨班拆分组: g.splitGroupId ?? '', + 影子段: g.shadowOf ?? '', + 影子时长秒: g.shadowSec ?? '', + 间隙填充: g.filledByGapRule ? '是' : '否', + 置信度: g.confidence, + 归口损失桶: bucketOfState(g.state) ? BUCKET_LABEL[bucketOfState(g.state)!] : '不进六桶', + 事件数: g.eventIds.length, + 事件id清单: g.eventIds.join(' / '), + 未归因池id: g.unknownPoolId ?? '', + })); +} + +/** ⑥ 损失:当期六桶 + 已计时因子 + 未计时子因子。推导桶显式标注,不假装有事件证据。 */ +function lossRows(): Row[] { + const d = cur(); + const segs = d.segments.segments; + const buckets: Row[] = d.buckets.buckets.map((b) => ({ + 类别: '损失桶', + 编码: `L-${b.bucket}`, + 名称: BUCKET_LABEL[b.bucket], + 归属因子: b.factor, + 时长秒: b.durationSec, + 占PPT: b.pctOfPlanTime, + 推导量: b.derivedFromCycleDeviation ? '是' : '否', + 事件码清单: b.eventCodes.join(' / '), + 状态段数: segs.filter((g) => bucketOfState(g.state) === b.bucket).length, + 事件实例数: curEvents().filter((x) => b.eventCodes.includes(x.defCode)).length, + 一级因子: '', 二级因子: '', + 缺口说明: b.derivedFromCycleDeviation + ? '由节拍偏差/检测结果推导,无成对事件证据 → 不提供事件级下钻(数据缺口,非对账失败)' + : '', + })); + const factors: Row[] = d.buckets.factors.map((f) => ({ + 类别: '因子', + 编码: `F-${f.factorL1}|${f.factorL2}`, + 名称: `${f.factorL1} / ${f.factorL2}`, + 归属因子: f.factor, + 时长秒: f.durationSec, + 占PPT: d.segments.totals.pptSec > 0 ? f.durationSec / d.segments.totals.pptSec : 0, + 推导量: '否', + 事件码清单: [...new Set(f.eventIds.map((id) => defOfInstance(id)?.code ?? ''))].filter(Boolean).join(' / '), + 状态段数: f.segmentIds.length, + 事件实例数: f.eventIds.length, + 一级因子: f.factorL1, + 二级因子: f.factorL2, + 缺口说明: '', + })); + /* 未计时子因子:时长**留空**而不是填 0——缺 EA 到场时间戳就是量不出来, + 填 0 会被读成"没有损失",摊一个数更是假精度。 */ + const untimed: Row[] = d.buckets.untimedSubFactors.map((u) => ({ + 类别: '未计时子因子', + 编码: `U-${u.factorL1}|${u.factorL2}`, + 名称: `${u.factorL1} / ${u.factorL2}`, + 归属因子: 'A', + 时长秒: '', + 占PPT: '', + 推导量: '否', + 事件码清单: [...new Set(u.eventIds.map((id) => defOfInstance(id)?.code ?? ''))].filter(Boolean).join(' / '), + 状态段数: u.segmentIds.length, + 事件实例数: u.eventIds.length, + 一级因子: u.factorL1, + 二级因子: u.factorL2, + 缺口说明: '段内出现但未单独计量:缺子因子的起止时间戳,无法从父段里拆出时长。标灰不摊数。', + })); + return [...buckets, ...factors, ...untimed]; +} + +const TIER_LABEL = { theoretical: '理论档', planned: '计划档', actual: '实际档' } as const; +type TierKey = keyof typeof TIER_LABEL; + +/** ⑦ 绩效:三日 × 三档 = 9 条。理论/计划档是口径推算,实际档才是种子实测,逐行标明。 */ +function performanceRows(): Row[] { + return days().flatMap((d) => (Object.keys(TIER_LABEL) as TierKey[]).map((k) => { + const t = d.tiers[k]; + const isActual = k === 'actual'; + const delta = isActual ? d.tiers.deltaPlannedToActual : null; + return { + 业务日: d.bizDate, + 档位: TIER_LABEL[k], + 范围层级: 'DEVICE', + 设备: d.device.id, + 口径版本: d.caliberVersion, + 计算模板: TEMPLATE_LABEL[d.device.template], + 数值性质: isActual ? '实测(三日合成种子日志)' : '口径推算(附录 E 默认值,待 IE 签字)', + CT秒: d.segments.totals.ctSec, + PDT秒: d.segments.totals.pdtSec, + PPT秒: d.segments.totals.pptSec, + A: t.a, P: t.p, Q: t.q, OEE: t.oee, + RT秒: t.rtSec, + 产出数: isActual ? t.outputQty : '', + 合格数: isActual ? t.goodQty : '', + ICT秒: t.ictSec, + 六桶残差秒: isActual ? d.buckets.residualSec : '', + 未归因占比: isActual ? d.buckets.unattributedPct : '', + DQ阻断: isActual ? (d.dq.blocked ? '是' : '否') : '', + 阻断规则: isActual ? d.dq.blockedBy.join(' / ') : '', + 对比基准: isActual ? '计划档' : '', + ΔA: delta ? delta.dA : '', + ΔP: delta ? delta.dP : '', + ΔQ: delta ? delta.dQ : '', + Δ合计: delta ? delta.total : '', + 参数出处: isActual ? 'L1 种子 → L2 引擎 → L3 服务层' : PARAMS_SIGNOFF_NOTE, + }; + })); +} + +/** ⑧ 口径:28 项 × 当前版本。signedOff 全 false,P0 标灰不标绿。 */ +function caliberRows(): Row[] { + const issuesOf = (id: string) => Object.values(SENSITIVITY_ISSUES) + .filter((v) => (v.items as readonly string[]).includes(id)) + .map((v) => v.label); + return Object.values(CALIBER_ITEMS).map((c) => ({ + 口径编号: c.id, + 口径名称: c.name, + 默认值: String(c.defaultValue), + 优先级: c.priority, + 归口责任人: c.owner, + 敏感性议题: issuesOf(c.id).join(' / '), + 是敏感性关键项: c.isSensitivityKey ? '是' : '否', + 已签字: c.signedOff ? '是' : '否', + 签字状态: c.signedOff ? '已签字' : '待 IE 签字', + 影响范围与归口: c.note, + 生效版本: CALIBER_CONFIG.version, + 生效起始: CALIBER_CONFIG.effectiveFrom, + })); +} + +/** + * ⑨ 改善:当前只有 DQ 命中(三日)。 + * ★ 改善任务实例为 0:closure 引擎与任务中心在 W3-B 落地。 + * 建议书 3.6 写的"6 条任务"是**目标态**,不是现有数据——此处不编 6 条任务充数, + * 由 R-TASK-DISPATCH 规则以 blocked + gap 明示缺口。 + */ +function improvementRows(): Row[] { + return days().flatMap((d) => d.dq.issues.map((i) => ({ + 类别: 'DQ问题', + 编号: i.id, + 规则码: i.code, + 规则名: DQ_RULE_BY_CODE[i.code]?.name ?? i.code, + 设备: i.device ?? '', + 业务日: i.bizDate, + 命中条件: i.condition, + 是否阻断: i.blocking ? '是' : '否', + 处置动作: i.action, + 处理状态: i.state, + 缺口说明: i.gap ?? '', + 任务状态: '', 根因实体: '', 责任人: '', 期限: '', 预期收益: '', 证据链: '', + }))); +} + +/* ══════════════════════════════════════════════════════════════════ + * ⑩-⑬ 共同分析本体:SoW 三组要求的共用底层 + * ⑩ 分析问题 —— 判断顺序(A-01..A-05)+ 指标组合(M-01..M-07) + * ⑪ 因子定义 —— IE 因子清单 → 六大损失的量化标准(起止判定 + 口径约束) + * ⑫ 改善对策 —— 由损失结构触发的对策候选(SMED / TPM / 短停 / 质量) + * ⑬ 成本参数 —— 每分钟停机损失与 ROI 的参数位(费率未签字 → 不出金额) + * 这四类都是**方法论对象**,不含统计结果;命中照旧回到 L3 的损失/绩效/事件。 + * ══════════════════════════════════════════════════════════════════ */ + +const objLabel = (id: string) => DEFS.find((d) => d.id === id)?.name ?? id; + +interface CardDef { + id: string; kind: '分析逻辑' | '指标组合'; question: string; + order: string; dims: string; metrics: string; sources: string[]; + trap: string; out: string; status: '可算' | '部分可算' | '缺口'; gap: string; +} + +/** SoW「生产分析逻辑」五步 + 「生产指标组合」七组,原文的判断顺序与误判提醒逐条落库。 */ +const CARD_DEFS: CardDef[] = [ + { + id: 'A-01', kind: '分析逻辑', question: '计划完成了没有?完成后再看产出效率是否正常', + order: '① 计划达成 → ② 欠产缺口 → ③ 产出效率', + dims: '计划量 vs 实际产出、欠产数量、计划达成率', + metrics: '计划达成率、欠产数、OEE 实际档', + sources: ['performance', 'lot', 'loss'], + trap: '只看完成比例会被订单结构摊薄:小产量订单与大产量订单的比例变化会误导达成率,须同时看欠产数量与订单结构', + out: '转入 A-02 效率三因子拆解', + status: '部分可算', + gap: '排产计划量未接入:当前计划档取 IE 参数推算(C27/C28 待签字),订单结构(小单/大单比例)未接入', + }, + { + id: 'A-02', kind: '分析逻辑', question: '效率异常时,先拆 OEE 判断是时间、速度还是质量损失', + order: '① A 时间损失 → ② P 速度损失 → ③ Q 质量损失', + dims: '停机/换型/短停(A)、节拍偏差(P)、良率(Q)', + metrics: 'A/P/Q 三因子、六大损失桶时长、计划档→实际档 Δ', + sources: ['performance', 'loss', 'factorDef', 'caliber'], + trap: '不要从 OEE 直接跳到根因:先定位损失桶再归因;Δ 分解顺序固定 A→P→Q,换序会换结论', + out: '分头进入 A-03(停机)或 A-04(质量)下钻', + status: '可算', + gap: '', + }, + { + id: 'A-03', kind: '分析逻辑', question: '发现停机后,继续分析设备、故障类型、发生频率和产能影响', + order: '① 设备 → ② 故障类型 → ③ 发生频率 → ④ 产能影响', + dims: 'DOWN/JAM 状态段、事件码、故障类型 Pareto、重复停机设备', + metrics: '停机时长、停机次数、单次时长、瓶颈站产能损失', + sources: ['stateSegment', 'event', 'equipment', 'factorDef'], + trap: '只看总时长会漏掉高频短停:频次反映稳定性,时长反映大损失,两者要并列看', + out: '按影响程度排序,转 A-05 排优先级', + status: '部分可算', + gap: '故障类型真因(人机料法环测)依赖 D 类事件补录;缺 EA 到场/离场时间戳时无法拆分「故障」与「等维修」', + }, + { + id: 'A-04', kind: '分析逻辑', question: '发现质量问题后,拆产品、产线、工单、缺陷', + order: '① 产品 → ② 产线 → ③ 工单 → ④ 缺陷', + dims: '批次良率、工单良率、缺陷分类、返工/复筛批次', + metrics: '良率、FTRD、返工率、rescreen 批次数', + sources: ['lot', 'event', 'equipment', 'lineTopology'], + trap: '最终良率高不代表生产过程稳定:一次合格率(FTRD)下降与返工持续增加,质量成本已在上升', + out: '质量损失计入 Q,转 A-05 排优先级', + status: '部分可算', + gap: '产品/工单维度需 MES 工单号贯通(lot 窗口只到批次);缺陷分类无数据源,FTRD 与返工数据未接入', + }, + { + id: 'A-05', kind: '分析逻辑', question: '把异常按影响程度和产能损失排出优先级,形成整改', + order: '① 影响程度 × 产能损失 → ② 优先级 → ③ 立项 → ④ 验证', + dims: '六桶时长排名、Δ vs 计划档、占用瓶颈产能、可执行对策', + metrics: '损失占比、产能损失、对策预期收益区间', + sources: ['loss', 'performance', 'improvement'], + trap: '收益给区间不给点值;金额化须费率签字后才可测算,不允许先给金额再倒推', + out: '生成改善对策候选;四项必填齐备才派单', + status: '部分可算', + gap: '优先级权重口径未定义(影响程度与产能损失如何加权);任务中心 W3-B 未落地;金额化需成本参数签字', + }, + { + id: 'M-01', kind: '指标组合', question: '计划达成(完成比例)+ 欠产数量(缺口)', + order: '先看达成比例,再拆欠产缺口', + dims: '计划量/实际产出/缺口、订单结构(小单 vs 大单)', + metrics: '计划达成率、欠产数量、订单结构占比', + sources: ['performance', 'lot'], + trap: '小产量订单与大产量订单之间的比例会误导达成率:大单占比高时比例好看,欠产绝对值仍可能很大', + out: '欠产转 M-02 看投入产出关系', + status: '部分可算', + gap: '排产计划量与订单结构未接入;计划档当前取 IE 参数推算', + }, + { + id: 'M-02', kind: '指标组合', question: '产量 + 工时 + 单位工时产出', + order: '产量增长来自效率,还是来自增加投入?', + dims: '产量、工时(PPT/RT)、单位工时产出', + metrics: '产量、工时、产量/工时', + sources: ['performance', 'stateSegment', 'lot'], + trap: '如果产量增加但工时增长更快,可能效率在下降——必须看单位工时产出,而不是总产量', + out: '单位工时产出下降转 A-02 拆 OEE', + status: '可算', + gap: '', + }, + { + id: 'M-03', kind: '指标组合', question: 'OEE + 三项损失', + order: '先看整体效率变化,再看三项损失来源', + dims: 'A/P/Q、六大损失桶、Δ vs 计划档', + metrics: 'OEE、A/P/Q、损失桶占比', + sources: ['performance', 'loss', 'factorDef'], + trap: '不要直接从 OEE 跳到根因分析:先看整体效率变化,再看三项损失来源,最后才做根因', + out: '损失桶排名转 A-03 / A-04 下钻', + status: '可算', + gap: '', + }, + { + id: 'M-04', kind: '指标组合', question: '停机时长 + 停机次数', + order: '时长看大损失,次数看稳定性', + dims: 'DOWN/JAM 时长与次数、单次时长分布、设备排名', + metrics: '停机时长、停机次数、次均时长', + sources: ['stateSegment', 'event'], + trap: '停机时长看大损失,停机次数看稳定性;高频短停往往比偶发长停更容易被忽略', + out: '高频短停转 P-03 对策,长停机转 P-02', + status: '部分可算', + gap: 'Jam 多为 D 类人工录入,频次可信度受补录完整度影响;频次告警阈值待定', + }, + { + id: 'M-05', kind: '指标组合', question: '良率 + 一次合格率(FTRD)+ 返工', + order: '最终良率 → 一次合格率 → 返工/复筛', + dims: '批次良率、FTRD、返工率、rescreen 批次', + metrics: '良率、FTRD、返工率', + sources: ['lot', 'event'], + trap: '最终良率高不代表生产过程稳定:一次合格率下降与返工持续增加,说明质量成本已经上升', + out: '质量成本上升转 P-05 质量改善', + status: '缺口', + gap: 'FTRD 与返工数据源未接入;当前只能看批次良率与 rescreen 事件定义,不能合成 FTRD', + }, + { + id: 'M-06', kind: '指标组合', question: '设备利用率 + 在制品', + order: '利用率高是有效产出,还是在制品堆积/等待?', + dims: '设备开动率、在制品数量与等待时长', + metrics: '设备利用率、WIP、等待时长', + sources: ['equipment', 'stateSegment'], + trap: '设备利用率高不一定代表现场效率高:可能只是在制品堆积或工单等待把设备"撑"起来了', + out: '利用率与 WIP 背离转 A-01 查计划与齐套', + status: '缺口', + gap: '在制品(WIP)数据源未接入;利用率口径待 IE 定义(C 系列口径)', + }, + { + id: 'M-07', kind: '指标组合', question: '产量 + 设备负荷 + 故障趋势', + order: '短期产量增长是否在透支设备稳定性?', + dims: '产量、设备负荷、维修次数与故障间隔趋势', + metrics: '产量、负荷率、维修次数、MTBF 趋势', + sources: ['performance', 'equipment', 'event'], + trap: '短期产量增长伴随高负荷、维修次数增加,可能在透支设备稳定性——要把故障趋势和产量放在同一时间轴上看', + out: '故障趋势恶化转 P-02 TPM 预防维护', + status: '缺口', + gap: '设备负荷与维修记录无数据源;MTBF 需维修工单接入,当前只有事件表里的停机记录', + }, +]; + +function cardRows(): Row[] { + return CARD_DEFS.map((c) => ({ + 编号: c.id, + 类别: c.kind, + 分析问题: c.question, + 判断顺序: c.order, + 展开维度: c.dims, + 关键指标: c.metrics, + 取数对象: c.sources.map(objLabel).join('、'), + 误判提醒: c.trap, + 输出承接: c.out, + 可达性: c.status, + 缺口说明: c.gap, + })); +} + +/* ── ⑪ 因子定义:IE 因子清单 → 六桶归属 + 起止判定 + 量化规则 ── */ + +interface QuantDef { start: string; end: string; rule: string; caliber: string } + +/** 20 个二级因子组的判定口径(键=factorL2);阈值只引口径原文,不另造门槛。 */ +const QUANT_DEFS: Record = { + 'PM': { start: '末 lot trackout(通知 PM 前机台清空)', end: '前三 boat 进入 reflow', rule: 'PM 窗口整段计时', caliber: '计划停机·不进六桶' }, + 'NPI Engineering': { start: '量产末 lot unload OTA', end: 'SMR 末 lot unload OTA', rule: '工程借用整段计时', caliber: '计划类·不进六桶' }, + 'SMR 借机': { start: 'SMR Leader 现场确认机台与 OTA 清空', end: '加下个产品换线理论时间', rule: '工程借用整段计时', caliber: '计划类·不进六桶' }, + 'PE 借机': { start: 'APS 借机时点(量产延迟取现场清空)', end: '实际起点 + 计划借机时长 − 理论换线', rule: '工程借用整段计时', caliber: '计划类·不进六桶' }, + 'Run Dummy': { start: '上 lot 末 boat 进 DPVS 后,空 boat 进 DPVS', end: '新 lot 开启 Datacon', rule: '工程借用整段计时', caliber: '计划类·不进六桶' }, + 'Lab debug': { start: '实验室调试任务开始', end: '调试任务结束', rule: '工程借用整段计时', caliber: '计划类·不进六桶' }, + 'Conversion': { start: '上产品材料清空、下产品材料备齐', end: '与 Setup 共用判定点(S-14 以 Setup 开始为终点)', rule: '整段计入 CHANGEOVER', caliber: 'C07 一级因子标准归属' }, + 'Setup': { start: 'Xray 图保存 +5min(S-15)', end: '第一盘炉后确认 +5min(S-16)', rule: '成对 INTERVAL;S-18 取 Xray 保存 −5min。±5min 是录入固定偏移,不是派生', caliber: 'C08 / C07;换型调整→CHANGEOVER' }, + 'Lot setup loss': { start: '上 lot 末 boat 后放隔板再 +1min', end: '新 lot 开启 Datacon', rule: '整段计入 CHANGEOVER', caliber: 'C07 一级因子标准归属' }, + '换 lot': { start: 'FT 换 lot 开始(F-47 / A-55)', end: '第一个新 lot 产出(F-48 / A-56)', rule: '整段计入 CHANGEOVER', caliber: 'C07 一级因子标准归属' }, + 'rescreen': { start: '重测/复筛批次开始(F-49 / A-57)', end: '重测/复筛结束(F-50 / A-58)', rule: '单独计时,不并进过程不良', caliber: '质量成本来源;C07' }, + 'Down': { start: '按灯/通知 EA 与 MT2 Down 取最早可信时间(S-27)', end: 'EA 验证恢复(S-28);logfile 抓取 S-29', rule: '单次连续停机 >300s 归 DOWN', caliber: 'C08 / C14 按单次连续时长;C13 差异 >5min 转人核' }, + '维修等待': { start: 'Down 段内开始等待 EA', end: 'EA 到场', rule: '缺 EA 到场/离场时间戳时不可拆,标未计时', caliber: '未计时子因子不摊数' }, + 'Jam time': { start: 'OP 口头通知 EA(S-30)', end: 'EA 验证无异常恢复(S-31)', rule: '单次连续停机 ≤300s 归 JAM', caliber: 'C08 300s 分界' }, + '短停': { start: 'logfile 抓取瓶颈站 ≤5min 停机起点(S-32)', end: 'logfile 抓取停机终点', rule: '与 Jam 同桶,仅计时途径不同', caliber: 'C08 / C07' }, + '待料': { start: '等待物料/上游断供起点', end: '物料到位恢复生产', rule: '非计划待料计入 IDLE_MINOR(计划待料不进六桶)', caliber: 'C07;计划/非计划待料严格分开' }, + '人员等待': { start: 'OP 未到岗/交接等待起点', end: '人员到位恢复', rule: '计入 IDLE_MINOR', caliber: 'C07 一级因子标准归属' }, + '关机': { start: 'APS 关机时点(结合最后 lot unload 清空)', end: 'APS 开线时点(第一个 lot load)', rule: '计划停机整段计时', caliber: '计划停机·不进六桶' }, + 'APS plan idle': { start: 'APS plan idle 时点且机台未生产', end: '生产恢复', rule: '计划待料整段计时', caliber: '计划待料·不进六桶' }, + '5S': { start: '5S 开始', end: '5S 结束', rule: '计划类整段计时', caliber: '计划停机·不进六桶' }, +}; + +/** 公式派生因子(无事件码):速度/过程不良/开机不良 + FT Index。 */ +const DERIVED_FACTORS: { l1: string; l2: string; bucket: LossBucket; rule: string; caliber: string; status: string; gap: string }[] = [ + { + l1: '速度损失', l2: '速度降低', bucket: 'SPEED', + rule: '由节拍偏差推导:P = 良品数×ICT / RT;无成对事件证据', + caliber: '推导量·不提供事件级下钻', status: '部分可算', gap: '推导量:由节拍偏差推导,无事件级证据,不能下钻到原始行号', + }, + { + l1: '质量损失', l2: '过程不良', bucket: 'PROCESS_DEFECT', + rule: '由检测结果推导:Q 缺口 = 投入×(1−良率),再换算 ICT', + caliber: '推导量·不提供事件级下钻', status: '部分可算', gap: '检测明细未接入,只有批次良率;不能拆到具体缺陷类型', + }, + { + l1: '质量损失', l2: '开机不良', bucket: 'STARTUP_DEFECT', + rule: '首件不良数×ICT(换型后爬坡/首件不良/rescreen 复测)', + caliber: '推导量;首检未接入时计 0 并标缺口', status: '缺口', gap: '首件检验数据未接入,三日开机不良桶均为 0——是数据缺口而不是没有开机不良', + }, + { + l1: 'Index loss', l2: 'FT Index', bucket: 'SPEED', + rule: 'Index 损失 = [Index/(Index+Test)]×(1−OE Eff Loss−Jam Factor);Index 1.5s、Test 30s;GPIB 0.5s 列于输入但未进入公式', + caliber: 'P = 1 − (OE Eff Loss + Index 损失 + Jam Factor)', status: '部分可算', + gap: 'Index/Test 为方案给定参数,未在客户日志实测;UPH 推导与 GPIB 用途待确认(Q6)', + }, +]; + +interface FactorGroup { l1: string; l2: string; bucket: LossBucket | null; codes: string[]; gross: string } + +function factorGroups(): FactorGroup[] { + const m = new Map(); + for (const e of EVENTS_48) { + const k = `${e.factorL1}|${e.factorL2}`; + const g = m.get(k); + if (g) g.codes.push(e.code); + else m.set(k, { l1: e.factorL1, l2: e.factorL2, bucket: e.bucket, codes: [e.code], gross: e.grossCategory }); + } + return [...m.values()]; +} + +function factorRows(): Row[] { + const groups: Row[] = factorGroups().map((g, i) => { + const q = QUANT_DEFS[g.l2]; + return { + 因子编号: `F-${String(i + 1).padStart(2, '0')}`, + 一级因子: g.l1, + 二级因子: g.l2, + 归口用词: g.gross, + 损失桶: g.bucket ? BUCKET_LABEL[g.bucket] : '计划类·不进六桶', + 事件码: g.codes.join(' / '), + 事件数: g.codes.length, + 判定起点: q?.start ?? '按事件触发点', + 判定终点: q?.end ?? '按事件配对点', + 量化规则: q?.rule ?? '整段计时', + 口径约束: q?.caliber ?? 'C07 一级因子标准归属', + 状态: g.bucket ? '已定义' : '计划类', + 缺口说明: q ? '' : '判定口径待 IE 补充', + }; + }); + const derived: Row[] = DERIVED_FACTORS.map((f, i) => ({ + 因子编号: `F-${String(factorGroups().length + i + 1).padStart(2, '0')}`, + 一级因子: f.l1, + 二级因子: f.l2, + 归口用词: '—(公式派生)', + 损失桶: BUCKET_LABEL[f.bucket], + 事件码: '—(公式派生)', + 事件数: 0, + 判定起点: '—', + 判定终点: '—', + 量化规则: f.rule, + 口径约束: f.caliber, + 状态: f.status, + 缺口说明: f.gap, + })); + return [...groups, ...derived]; +} + +/* ── ⑫ 改善对策:由损失结构触发的对策候选(SMED / TPM / 短停 / 速度 / 质量) ── */ + +interface PlayDef { + id: string; name: string; bucket: string; trigger: string; basis: string[]; + kpi: string; verify: string; gate: string; status: string; gap: string; +} + +const PLAY_DEFS: PlayDef[] = [ + { + id: 'P-01', name: 'SMED 快速换线', bucket: '换型调整→CHANGEOVER', + trigger: 'CHANGEOVER 占 PPT 排名居前且换型次数高(门槛待 IE 定)', + basis: ['loss', 'event', 'factorDef'], kpi: '换型时长均值、换型次数、Setup 损失占比', + verify: '改善前后同口径版本对比,收益给区间', + gate: '换型时长/次数/占比的触发门槛须由 IE 定版', + status: '规则就绪·门槛待定', + gap: '触发门槛(占比与次数)未签字;对策只出候选,不自动派单(任务中心 W3-B)', + }, + { + id: 'P-02', name: 'TPM 预防维护', bucket: '故障停机→FAULT', + trigger: '故障停机次数或故障间隔(MTBF)趋势恶化,且停机器 Pareto 集中', + basis: ['stateSegment', 'event', 'equipment'], kpi: 'MTBF、MTTR、Down 损失占比', + verify: '改善前后同口径对比故障次数与时长', + gate: '维修工单/维修记录须接入才能算 MTBF', + status: '规则就绪·数据源缺口', + gap: '维修记录未接入,当前只有事件表的停机段;故障类型真因依赖 D 类补录', + }, + { + id: 'P-03', name: '短停(Jam)治理', bucket: '空转短停→IDLE_MINOR', + trigger: '高频短停:停机次数排名前列但单次 <300s,时长不大易被忽略', + basis: ['stateSegment', 'event', 'factorDef'], kpi: '短停次数、次均时长、短停占比', + verify: '同一设备改善前后短停次数对比', + gate: '频次告警阈值待定;Jam 多为 D 类人工录入', + status: '规则就绪·门槛待定', + gap: '频次阈值未定义;补录完整度影响次数可信度(DQ-11 超时升级)', + }, + { + id: 'P-04', name: '速度/Index 损失治理', bucket: '速度降低→SPEED', + trigger: 'P 低于计划档,且 Index 损失或节拍偏差占比高', + basis: ['performance', 'loss', 'factorDef'], kpi: 'P 因子、Index 损失、节拍偏差', + verify: '改善前后同口径 P 与单位工时产出对比', + gate: 'FT Index/Test 参数须实测确认(Q6)', + status: '规则就绪·数据源缺口', + gap: 'FT Index 为方案给定参数,未在客户日志实测;UPH 推导不明(Q6)', + }, + { + id: 'P-05', name: '质量改善(FTRD/返工)', bucket: '过程不良+开机不良→PROCESS/STARTUP_DEFECT', + trigger: '最终良率高但 FTRD 下降、返工/rescreen 持续增加', + basis: ['lot', 'event', 'factorDef'], kpi: 'FTRD、返工率、质量成本、rescreen 批次', + verify: '同产品/工单改善前后良率与返工率对比', + gate: 'FTRD 与返工数据源须接入;缺陷分类须定义', + status: '规则就绪·数据源缺口', + gap: 'FTRD/返工未接入;缺陷分类无数据源,当前只能看到批次良率', + }, + { + id: 'P-06', name: '排产与齐套治理', bucket: '计划待料/计划停机→不进六桶', + trigger: '计划待料、APS plan idle 或非计划待料累计时长居前', + basis: ['stateSegment', 'event', 'lot'], kpi: '计划待料时长、非计划待料时长、齐套率', + verify: '同线体前后期计划待料时长对比', + gate: 'APS 排产与齐套数据须接入', + status: '规则就绪·数据源缺口', + gap: 'APS/齐套数据未接入;计划类时间不进六桶,须单独看,不能与 OEE 损失混算', + }, +]; + +function playRows(): Row[] { + return PLAY_DEFS.map((p) => ({ + 编号: p.id, + 对策: p.name, + 目标损失: p.bucket, + 触发条件: p.trigger, + 依据对象: p.basis.map(objLabel).join('、'), + 度量KPI: p.kpi, + 验证方式: p.verify, + 落地门槛: p.gate, + 状态: p.status, + 缺口说明: p.gap, + })); +} + +/* ── ⑬ 成本参数:每分钟停机损失与 ROI 的参数位 ── */ + +interface CostDef { + id: string; name: string; unit: string; use: string; formula: string; source: string; gap: string; +} + +const COST_DEFS: CostDef[] = [ + { id: 'C-01', name: '设备折旧率', unit: '元/小时/台', use: '每分钟停机损失之设备占用部分', formula: '折旧率 ÷ 60 × 停机分钟数', source: '财务固定资产台账', gap: '未提供:费率与折旧年限待财务确认' }, + { id: 'C-02', name: '人工费率', unit: '元/小时/人', use: '停机/等待期间的人工成本', formula: '费率 ÷ 60 × 停机分钟数 × 在岗人数', source: '财务/HR 人工成本', gap: '未提供:直接人工与间接人工攤分口径待财务确认' }, + { id: 'C-03', name: '能源单价', unit: '元/kWh', use: '停机期间的能源基载与重启能耗', formula: '单价 × 设备功率 × 小时数', source: '动力/能源账单', gap: '未提供:分时电价与设备功率表待接入' }, + { id: 'C-04', name: '良品边际价值', unit: '元/件', use: '欠产与不良的产出损失折算', formula: '良品数缺口 × 边际价值(或按瓶颈节拍折算产能损失)', source: '财务毛利/产品定价', gap: '未提供:用边际贡献还是售价,须财务定口径' }, + { id: 'C-05', name: '返工/复筛成本', unit: '元/批(或元/件)', use: 'rescreen 与返工批次的质量成本', formula: '返工批次 × 单批返工成本', source: '财务质量成本科目', gap: '未提供:返工成本归集科目待财务确认' }, + { id: 'C-06', name: '每分钟停机损失', unit: '元/分钟', use: '损失桶 → 金额的统一换算口径', formula: '折旧/60 + 人工/60 + 能耗×功率/60 + 产出损失(瓶颈节拍折算)', source: 'C-01 ~ C-04 组合', gap: '公式已建模,参数未签字 → 拒绝输出任何金额' }, + { id: 'C-07', name: 'ROI 评估模型', unit: '比率', use: '量化系统上线后的经营效益', formula: 'ROI =(年化损失减少 + 质量成本下降 − 系统投入)÷ 系统投入', source: 'C-06 + 改善前后对比 + 项目投入清单', gap: '缺基线、费率与收益区间三者之一即拒绝测算(与 OA-BENEFIT 同一门槛)' }, +]; + +function costRows(): Row[] { + return COST_DEFS.map((c) => ({ + 参数编码: c.id, + 参数名: c.name, + 单位: c.unit, + 用途: c.use, + 计算口径: c.formula, + 来源: c.source, + 当前值: '—(未提供)', + 签字状态: '待财务签字', + 缺口说明: c.gap, + })); +} + +/* ══════════════════════════════════════════════════════════════════ + * 对象定义:行集懒算一次就缓存,视图多处取 length 不必反复重建 + * ══════════════════════════════════════════════════════════════════ */ + +interface OntoDef { + id: string; name: string; en: string; short: string; color: string; + desc: string; source: string; + rows: () => Row[]; + present: (r: Row) => OntInstance; +} + +const DEFS: OntoDef[] = [ + { + id: 'equipment', name: '设备', en: 'Equipment', short: '设备台账', color: '#3b82f6', + desc: '17 台种子设备台账:沿用客户既有编码(真实编码 5 个,其余为演示占位码并标注),' + + '含能力矩阵、按设备可配置的间隙阈值、ICT 来源与解析陷阱。无日志设备标缺口,不假装有数据。', + source: 'data/oee/devices.ts(规划书附录 D.1/D.2/D.3)', + rows: equipmentRows, + present: (r) => { + const d = DEVICE_BY_ID[s(r['设备编码'])]; + const cap = d?.capability ?? 1; + const noLog = d ? !d.hasLog : false; + const excluded = d ? !d.countsForOee : false; + return { + id: s(r['设备编码']), title: s(r['设备编码']), + sub: `${s(r['设备名称'])} · ${s(r['工站'])}`, + meta: `${s(r['区域'])} · ${s(r['计算模板'])} · 阈值 ${s(r['间隙阈值min'])}min · ICT ${ + d && d.ictSec > 0 ? `${d.ictSec}s/${d.unit}` : '不适用/待 IE'}`, + value: `信号 ${'★'.repeat(cap)}${'☆'.repeat(3 - cap)}`, + badge: excluded ? '不计 OEE' : noLog ? '无日志' : s(r['台账编码来源']) === 'DEMO' ? '占位码' : '有日志', + tone: excluded ? 'info' : noLog ? 'danger' : cap === 3 ? 'success' : cap === 2 ? 'info' : 'warning', + }; + }, + }, + { + id: 'lineTopology', name: '产线拓扑', en: 'LineTopology', short: '产线拓扑', color: '#818cf8', + desc: 'SRF 串行线(缓冲解耦为主口径)/ FT 并行机群(按投入量加权)/ ASLT 12 Site(事件驱动)。' + + '三套模板不同构,不可混用;线体合成引擎待 W2 接入,当前只呈现拓扑与瓶颈站,不出合成数字。', + source: 'data/oee/devices.ts LINES(规划书 1.1 / 4.6.1)', + rows: lineRows, + present: (r) => ({ + id: s(r['线体编码']), title: s(r['线体编码']), sub: s(r['线体名称']), + meta: `${s(r['区域'])} · ${s(r['设备台数'])} 台(计入 OEE ${s(r['计入OEE台数'])} 台)· ${s(r['计算模板'])}`, + value: `瓶颈 ${s(r['瓶颈设备'])}`, + badge: '合成待接入', tone: 'warning', + }), + }, + { + id: 'lot', name: '批次', en: 'Lot', short: '批次归因', color: '#22d3ee', + desc: '三日种子的 lot 窗口,由产出锚点(完成行)识别。DEK 日志直接印 lot 号 → 设备自识别,置信度 1.00。' + + '只有开始行没有完成行的 lot 不造窗口(N=0 会让 P/Q 失去意义)。工程批按 C10 默认剔除。', + source: 'L3 oeeService → adapterDek.lotWindowsFromAnchors', + rows: lotRows, + present: (r) => ({ + id: `${s(r['业务日'])}|${s(r['批次号'])}`, + title: s(r['批次号']), sub: `${s(r['业务日'])} · ${s(r['设备'])}`, + meta: `${hm(s(r['开始时刻']))}→${hm(s(r['结束时刻']))} · 投入 ${num(r['投入数'])} · 合格 ${num(r['合格数'])}`, + value: `良率 ${pct2(r['批次良率'])}`, + badge: s(r['归因方式']), + tone: r['工程批'] === '是' ? 'info' : filled(r['批次良率']) ? 'success' : 'warning', + }), + }, + { + id: 'event', name: '事件', en: 'Event', short: '事件流', color: '#a78bfa', + desc: '48 条事件定义(六-3 归口用词 → 六-1 损失桶由 GROSS_TO_BUCKET 现推,20 个计划类事件不进六桶)' + + '+当期业务日的事件实例。实例带原始/校正双时间字段与原始日志行号,是血缘下钻的终点。', + source: 'data/oee/events48.ts + L3 normalize.events', + rows: eventRows, + present: (r) => { + const isDef = r['类别'] === '定义'; + const g = (s(r['自动化等级']) || 'E') as EventGrade; + return { + id: isDef ? s(r['事件码']) : s(r['实例id']), + title: isDef ? s(r['事件码']) : `${s(r['事件码'])} · ${hhmmss(s(r['校正时刻']))}`, + sub: s(r['事件名']), + meta: isDef + ? `${s(r['区域'])} · ${s(r['等级含义'])} · ${s(r['损失桶'])} · 当期 ${num(r['当期实例数'])} 次` + : `${s(r['设备'])} · 行 ${num(r['原始行号'])} · ${s(r['配对角色']) || '未配对'}`, + value: isDef ? `${s(r['归口用词'])}` : s(r['已校正']) === '是' ? '已校钟' : '原始时刻', + badge: isDef ? s(r['自动化等级']) : s(r['类别']), + tone: gradeTone(g), + }; + }, + }, + { + id: 'stateSegment', name: '状态段', en: 'StateSegment', short: '状态段', color: '#34d399', + desc: '当期业务日的设备状态段,十态抢占优先级(PLAN_STOP 1 → IDLE 10,UNKNOWN 99 不计分母)。' + + '跨班拆分共享 splitGroupId,PM 窗口内停机保留影子双记录,间隙填充段标来源便于审计。', + source: 'L3 oeeService → stateMachine.buildSegments', + rows: segmentRows, + present: (r) => { + const st = s(r['状态码']); + const tone: Tone = st === 'RUN' ? 'success' + : st === 'UNKNOWN' ? 'danger' + : st === 'IDLE' ? 'warning' + : st === 'DOWN' || st === 'JAM' ? 'danger' + : st === 'PLAN_STOP' || st === 'PM' ? 'info' : 'warning'; + return { + id: s(r['段id']), + title: `${s(r['状态名'])} ${hm(s(r['开始时刻']))}→${hm(s(r['结束时刻']))}`, + sub: `${s(r['设备'])} · ${s(r['业务日'])}`, + meta: `${num(r['时长秒'])}s · 优先级 ${s(r['抢占优先级'])} · ${s(r['班次'])} · 事件 ${num(r['事件数'])} 个`, + value: s(r['归口损失桶']), + badge: r['间隙填充'] === '是' ? '间隙填充' : st, + tone, + }; + }, + }, + { + id: 'loss', name: '损失', en: 'Loss', short: '损失结构', color: '#f87171', + desc: '六-1 六大损失桶(互斥完备,映射 A/P/Q)+已计时因子+未计时子因子。' + + '速度降低与两类不良由节拍偏差推导,无成对事件证据,显式标"推导量";' + + '未计时子因子时长留空不填 0,缺什么就说什么。' + + '当期 DEK 种子停机段只含单一子因子,故未计时子因子实例为 0(引擎路径由校验脚本合成输入验证,不造实例充数)。', + source: 'L3 oeeService → lossBuckets.mapToBuckets', + rows: lossRows, + present: (r) => { + const kind = s(r['类别']); + const sec = r['时长秒']; + return { + id: s(r['编码']), title: s(r['名称']), + sub: `${kind} · 归属 ${s(r['归属因子'])}`, + meta: `${s(r['一级因子']) || s(r['归口损失桶']) || '—'} · 状态段 ${num(r['状态段数'])} 个 · 事件 ${num(r['事件实例数'])} 个`, + value: typeof sec === 'number' ? `${num(sec)}s · ${pct2(r['占PPT'])}` : '未计量', + badge: kind === '损失桶' ? (r['推导量'] === '是' ? '推导量' : '有事件证据') : kind, + tone: kind === '未计时子因子' ? 'info' : r['推导量'] === '是' ? 'warning' : 'danger', + }; + }, + }, + { + id: 'performance', name: '绩效', en: 'Performance', short: '三层绩效', color: '#fbbf24', + desc: '三日 × 三档(理论/计划/实际)=9 条结果,三档共用同一分母 PPT=CT−PDT−UNKNOWN。' + + '顺序替代固定 A→P→Q;每条都带口径版本号,跨版本对比默认拒绝。' + + '理论/计划档是附录 E 默认值推算,C27/C28 待 IE 签字,不得当作客户确认口径。', + source: 'L3 oeeService → threeTier.calcThreeTier', + rows: performanceRows, + present: (r) => { + const blocked = r['DQ阻断'] === '是'; + const isActual = r['档位'] === '实际档'; + return { + id: `${s(r['业务日'])}|${s(r['档位'])}`, + title: `${s(r['业务日'])} · ${s(r['档位'])}`, + sub: `${s(r['设备'])} · ${s(r['口径版本'])}`, + meta: `A ${pct2(r['A'])} · P ${pct2(r['P'])} · Q ${pct2(r['Q'])} · PPT ${num(r['PPT秒'])}s`, + value: `OEE ${pct2(r['OEE'])}`, + badge: blocked ? '结论暂缓发布' : isActual ? '可发布' : '口径推算', + tone: blocked ? 'danger' : isActual ? 'success' : 'info', + }; + }, + }, + { + id: 'caliber', name: '口径', en: 'Caliber', short: '口径配置', color: '#94a3b8', + desc: '28 项口径 × 当前版本。priority P0/P1/P2 影响"能不能算",isSensitivityKey 影响"算出来是多少",' + + '两者不是同一集合。本次不安排口径工作坊 → signedOff 全 false,P0 的 16 项标灰(待 IE 签字),不标绿。', + source: 'data/oee/calibers28.ts(规划书附录 E 逐条转录)', + rows: caliberRows, + present: (r) => { + const p0 = r['优先级'] === 'P0'; + const signed = r['已签字'] === '是'; + return { + id: s(r['口径编号']), title: s(r['口径编号']), sub: s(r['口径名称']), + meta: `${s(r['优先级'])} · 归口 ${s(r['归口责任人'])} · 默认「${s(r['默认值'])}」`, + value: s(r['签字状态']), + badge: r['是敏感性关键项'] === '是' ? `敏感性:${s(r['敏感性议题'])}` : s(r['优先级']), + // ★ P0 未签字 → 中性 info(灰),绝不 success(绿) + tone: signed ? 'success' : p0 ? 'info' : 'warning', + }; + }, + }, + { + id: 'improvement', name: '改善', en: 'Improvement', short: '改善闭环', color: '#fb923c', + desc: '当前实例=三日 DQ 命中(12 条规则里三条阻断级:DQ-06 未归因>5% / DQ-08 主数据缺失 / DQ-12 口径版本不一致)。' + + '改善任务与六态流转在 W3-B 落地,**当前无任务实例,不编造**;四项必填闸门与证据链要求先以规则明示。', + source: 'L3 oeeService → dq.runDq(任务中心待 W3-B)', + rows: improvementRows, + present: (r) => ({ + id: s(r['编号']), + title: `${s(r['规则码'])} · ${s(r['业务日'])}`, + sub: s(r['规则名']), + meta: `${s(r['设备']) || '全设备'} · ${s(r['命中条件'])}`, + value: r['是否阻断'] === '是' ? '阻断发布' : s(r['处置动作']).slice(0, 12), + badge: s(r['处理状态']), + tone: r['是否阻断'] === '是' ? 'danger' : filled(r['缺口说明']) ? 'info' : 'warning', + }), + }, + { + id: 'analysisCard', name: '分析问题', en: 'AnalysisCard', short: '分析卡', color: '#38bdf8', + desc: 'SoW 两组分析要求的共用入口:分析逻辑五步(A-01 计划达成 → A-05 排优先级)' + + '+指标组合七组(M-01 计划达成/欠产 … M-07 产量/负荷/故障趋势)。每张卡都带判断顺序、' + + '展开维度、取数对象和**误判提醒**(小/大订单比例误导、工时增长快于产量、不要从 OEE 直接跳根因、' + + '高频短停易被忽略、良率高≠过程稳定、利用率高≠效率高、高负荷透支设备)。', + source: 'SoW 生产分析逻辑 / 生产指标组合(逐条转录,数字回到 L3)', + rows: cardRows, + present: (r) => { + const status = s(r['可达性']); + return { + id: s(r['编号']), title: `${s(r['编号'])} · ${s(r['类别'])}`, + sub: s(r['分析问题']), + meta: `${s(r['判断顺序'])} · 取数 ${s(r['取数对象'])}`, + value: s(r['关键指标']), + badge: status, + tone: status === '可算' ? 'success' : status === '部分可算' ? 'warning' : 'info', + }; + }, + }, + { + id: 'factorDef', name: '因子定义', en: 'FactorDef', short: '因子定义', color: '#e879f9', + desc: 'IE 因子清单 → OEE 六大损失的量化标准:20 个二级因子组(每码唯一归口)' + + '+4 个公式派生因子(速度/过程不良/开机不良/FT Index)。逐条写明判定起点、判定终点、' + + '量化规则与口径约束——Setup 取 Xray 保存 +5min 至首盘炉后确认 +5min(±5min 是录入偏移不是派生)、' + + 'Jam 与 Down 以单次连续 300s 分界(C08/C14)、Index 损失按 [Index/(Index+Test)]×(1−OE Eff Loss−Jam Factor)。', + source: 'data/oee/events48.ts(附录 C.2)+ docs/后端引擎数据结构规划书-v0.1-2026-11-18.md(FT Index)', + rows: factorRows, + present: (r) => { + const status = s(r['状态']); + const plan = s(r['损失桶']) === '计划类·不进六桶'; + return { + id: s(r['因子编号']), + title: `${s(r['一级因子'])} / ${s(r['二级因子'])}`, + sub: `${s(r['损失桶'])}${s(r['归口用词']) !== '—(公式派生)' ? ` · ${s(r['归口用词'])}` : ''}`, + meta: `${s(r['事件码'])} · 判定 ${s(r['判定起点'])} → ${s(r['判定终点'])}`, + value: s(r['量化规则']), + badge: status, + tone: status === '缺口' ? 'danger' : status.startsWith('部分') ? 'warning' : plan ? 'info' : 'success', + }; + }, + }, + { + id: 'improvePlaybook', name: '改善对策', en: 'ImprovementPlaybook', short: '改善对策', color: '#f472b6', + desc: '由损失结构触发的对策候选:SMED 快速换线(CHANGEOVER)、TPM 预防维护(FAULT)、' + + '短停治理(IDLE_MINOR)、速度/Index 治理(SPEED)、质量改善(过程/开机不良)、排产齐套治理(计划类)。' + + '每张对策都挂触发条件、依据对象、度量 KPI、验证方式与**落地门槛**;只出候选,' + + '四项必填齐备才派单(任务中心 W3-B 未落地,不造任务实例)。', + source: 'SoW 改善建议逻辑规则(SMED/TPM)+ 现有损失桶/事件因子', + rows: playRows, + present: (r) => ({ + id: s(r['编号']), title: `${s(r['编号'])} · ${s(r['对策'])}`, sub: s(r['目标损失']), + meta: `触发:${s(r['触发条件'])}`, + value: s(r['度量KPI']), + badge: s(r['状态']), + tone: s(r['状态']).includes('缺口') ? 'info' : 'warning', + }), + }, + { + id: 'costParam', name: '成本参数', en: 'CostParam', short: '成本参数', color: '#84cc16', + desc: '损失金额化与 ROI 的**参数位**:设备折旧率、人工费率、能源单价、良品边际价值、返工成本,' + + '以及每分钟停机损失公式与 ROI 模型。费率未由财务提供与签字前,' + + '**当前值一律留空、拒绝输出任何金额数字**——与 OA-BENEFIT 的三期 A7 门槛一致。', + source: 'SoW 损失金额化模型(参数位建模,值待财务)', + rows: costRows, + present: (r) => ({ + id: s(r['参数编码']), title: `${s(r['参数编码'])} · ${s(r['参数名'])}`, sub: s(r['单位']), + meta: `用途:${s(r['用途'])}`, + value: s(r['计算口径']), + badge: s(r['签字状态']), + tone: 'info', + }), + }, +]; + +const rowCache = new Map(); +const rowsOf = (id: string): Row[] => { + let v = rowCache.get(id); + if (!v) { + const def = DEFS.find((d) => d.id === id); + v = def ? def.rows() : []; + rowCache.set(id, v); + } + return v; +}; + +const instCache = new Map(); + +/** 9 类对象。instances() 是函数,数字现算,页面不写死。 */ +export const objects: OntObject[] = DEFS.map((d) => ({ + id: d.id, name: d.name, en: d.en, short: d.short, desc: d.desc, + source: d.source, color: d.color, + attrs: deriveAttrs(d.rows()), + instances: () => { + let v = instCache.get(d.id); + if (!v) { v = rowsOf(d.id).map(d.present); instCache.set(d.id, v); } + return v; + }, +})); + +export const objectById = (id: string): OntObject | undefined => objects.find((o) => o.id === id); + +/** + * 按「对象 id + 实例 id」取回该实例所在行的全部列值。 + * 实例 id 有的是复合(业务日|批次号、业务日|档位),不反解 id 格式, + * 而是把每行过一遍呈现器、取 id 相符的那行,再按列顺序拉出字段。 + */ +export function instanceFields(objectId: string, instId: string): OntField[] { + const def = DEFS.find((d) => d.id === objectId); + if (!def) return []; + const row = rowsOf(objectId).find((r) => def.present(r).id === instId); + if (!row) return []; + return Object.keys(row).map((col) => ({ name: col, value: s(row[col]) })); +} + +/* ══════════════════════════════════════════════════════════════════ + * 关系:连接键与实例数全按真实外键交集现算,不估算 + * ══════════════════════════════════════════════════════════════════ */ + +const eqRows = () => rowsOf('equipment'); +const segRows = () => rowsOf('stateSegment'); +const lotRowsC = () => rowsOf('lot'); +const perfRows = () => rowsOf('performance'); +const impRows = () => rowsOf('improvement'); +const factorRowsC = () => rowsOf('factorDef'); +const playRowsC = () => rowsOf('improvePlaybook'); +const costRowsC = () => rowsOf('costParam'); + +/** 卡片/对策的「取数对象」以对象 id 形式存定义,计数按真实引用现算,不另抄一份 */ +const cardsUsing = (objectId: string) => CARD_DEFS.filter((c) => c.sources.includes(objectId)).length; +const playsUsing = (objectId: string) => PLAY_DEFS.filter((p) => p.basis.includes(objectId)).length; +const sixBucketFactorRows = () => factorRowsC().filter((r) => s(r['损失桶']) !== '计划类·不进六桶'); + +export const relations: OntRelation[] = [ + { + id: 'eq-line', from: 'equipment', to: 'lineTopology', name: '属于', cardinality: 'N:1', + key: 'lineId', desc: '设备归属线体。17 台全部落在 3 条线上,无孤儿设备。', + count: () => eqRows().filter((r) => LINE_BY_ID[s(r['所属线体'])] !== undefined).length, + }, + { + id: 'line-eq', from: 'lineTopology', to: 'equipment', name: '包含', cardinality: '1:N', + key: 'deviceIds', desc: '线体包含设备。与「属于」互为反向,两侧计数必须相等(无悬空引用)。', + count: () => LINES.reduce((a, l) => a + l.deviceIds.filter((id) => DEVICE_BY_ID[id]).length, 0), + }, + { + id: 'line-bottleneck', from: 'lineTopology', to: 'equipment', name: '瓶颈站', cardinality: 'N:1', + key: 'bottleneckDeviceId', + desc: 'SRF 瓶颈指向 DCP005(751min 缺失数据 + 124min 停机〔POC〕)。' + + 'FT/ASLT 未单列瓶颈站——不臆造,按 C15 由主数据维护瓶颈站表后补齐。', + count: () => LINES.filter((l) => l.bottleneckDeviceId && DEVICE_BY_ID[l.bottleneckDeviceId]).length, + }, + { + id: 'eq-seg', from: 'equipment', to: 'stateSegment', name: '产生', cardinality: '1:N', + key: 'device', desc: '设备产生状态段。当期只有锚点设备 DEK001 贯通全链路,其余设备待 W2 接入。', + count: () => segRows().filter((r) => DEVICE_BY_ID[s(r['设备'])] !== undefined).length, + }, + { + id: 'event-seg', from: 'event', to: 'stateSegment', name: '构成', cardinality: 'N:M', + key: 'eventIds', + desc: '事件实例构成状态段。★ 键空间是**实例 id**(不是事件定义码)——' + + '传错会让归口全空且不报错,故此处按实例 id 求交集,可反查原始日志行号。', + count: () => { + const ids = new Set(curEvents().map((e) => e.id)); + const used = new Set(cur().segments.segments.flatMap((g) => g.eventIds)); + return [...used].filter((id) => ids.has(id)).length; + }, + }, + { + id: 'lot-eq', from: 'lot', to: 'equipment', name: '在制于', cardinality: 'N:1', + key: 'device', desc: '批次在制于设备。三日 lot 窗口全部落在锚点设备上。', + count: () => lotRowsC().filter((r) => DEVICE_BY_ID[s(r['设备'])] !== undefined).length, + }, + { + id: 'lot-event', from: 'lot', to: 'event', name: '归因', cardinality: '1:N', + key: 'attribution.lotId', + desc: '事件按五级级联归因挂到批次。★ 当前计数为 0 是**实测事实而非对账失败**:' + + 'DEK 只有板级 PRINT START/COMPLETE 行印 lot 号,停机/换型/关机事件行不带 lot;' + + 'lot 窗口已由板级锚点自识别(SELF_IDENTIFIED 1.00),但事件级归因链尚未落地。' + + '不拿窗口包含关系冒充"设备自识别",也不造归因结果充数(见 R-EVENT-ATTRIBUTION)。' + + 'Datacon 的 Lot 字段为空才是五级归因的主战场(W2 接入)。', + count: () => { + const lots = new Set(cur().lots.map((w) => w.lotId)); + return curEvents().filter((e) => e.attribution?.lotId && lots.has(e.attribution.lotId)).length; + }, + }, + { + id: 'seg-loss', from: 'stateSegment', to: 'loss', name: '归口', cardinality: 'N:1', + key: 'STATE_TO_BUCKET[state]', + desc: '状态段按十态→六桶映射归口。计划停机/PM/待料/未归因/未采集不进六桶,' + + '其中未归因 IDLE 是残差的唯一合法来源。', + count: () => segRows().filter((r) => bucketOfState(s(r['状态码'])) !== undefined).length, + }, + { + id: 'event-loss', from: 'event', to: 'loss', name: '唯一归口', cardinality: 'N:1', + key: 'GROSS_TO_BUCKET[grossCategory]', + desc: '六-3 归口用词 → 六-1 损失桶。48 码里 28 码落六桶、20 码属计划类映射为 null;' + + '每码唯一归口,由 checkUniqueBucketAssignment 守住(C07)。', + count: () => EVENTS_48.filter((e) => e.bucket !== null).length, + }, + { + id: 'loss-perf', from: 'loss', to: 'performance', name: '计入', cardinality: 'N:1', + key: 'bizDate', desc: '六桶时长计入当日绩效。Σ桶时长 = PPT − 有效生产时间,残差必须照实暴露。', + count: () => days().reduce((a, d) => a + d.buckets.buckets.length, 0), + }, + { + id: 'perf-eq', from: 'performance', to: 'equipment', name: '绑定', cardinality: 'N:1', + key: 'device', desc: '绩效结果绑定设备。本体绩效对象当前只实例化到 DEVICE(DEK 锚点 3 日×3 档=9 行);' + + '线体/区域合成引擎已落地(W2-A,L3 出线体/区域读数,断言④守住),本体线体/区域实例与视图待 W2-B。', + count: () => perfRows().filter((r) => DEVICE_BY_ID[s(r['设备'])] !== undefined).length, + }, + { + id: 'caliber-perf', from: 'caliber', to: 'performance', name: '约束', cardinality: '1:N', + key: 'caliberVersion', + desc: '口径版本约束绩效结果。四处读数(页面/报表/智能体/导出)都带同一版本号;' + + '混用两个版本触发 DQ-12 阻断(断言⑩)。', + count: () => perfRows().filter((r) => s(r['口径版本']) === CALIBER_VERSION).length, + }, + { + id: 'caliber-event', from: 'caliber', to: 'event', name: '归口约束', cardinality: '1:N', + key: 'C07 一级因子标准归属表', + desc: 'C07(P0)约束全部 48 个事件码的一级因子归属;C08/C14 约束 Down/Jam 的 300 秒分界。', + count: () => EVENTS_48.length, + }, + { + id: 'dq-eq', from: 'improvement', to: 'equipment', name: '挂设备', cardinality: 'N:1', + key: 'device', desc: 'DQ 问题挂到设备。未带设备号的是全局性问题(如口径版本不一致)。', + count: () => impRows().filter((r) => filled(r['设备']) && DEVICE_BY_ID[s(r['设备'])] !== undefined).length, + }, + { + id: 'dq-loss', from: 'improvement', to: 'loss', name: '立项依据', cardinality: 'N:1', + key: 'DQ-06 → 未归因时长', + desc: 'DQ-06 未归因占比 >5% 阻断当日结论发布并派单,是改善立项的第一顺位依据。' + + '任务实体待 W3-B 落地,当前只呈现依据不呈现派单结果。', + count: () => impRows().filter((r) => s(r['规则码']) === 'DQ-06').length, + }, + /* ── 共同分析本体的 11 条关系:分析卡取数 / 因子归口 / 对策治理 / 参数金额化 ── */ + { + id: 'card-loss', from: 'analysisCard', to: 'loss', name: '拆解', cardinality: '1:N', + key: 'sources ⊇ loss', + desc: '分析卡从损失对象取数:A-02 拆三因子、A-03 停机下钻、A-05 排优先级、M-03 三项损失。' + + '取数对象按对象 id 引用(不是表名),页面聚焦联动才不会静默失效。', + count: () => cardsUsing('loss'), + }, + { + id: 'card-perf', from: 'analysisCard', to: 'performance', name: '取数', cardinality: '1:N', + key: 'sources ⊇ performance', + desc: '计划达成、产量、OEE 与 Δ 分解都从三层绩效取数;跨口径版本对比一律拒绝。', + count: () => cardsUsing('performance'), + }, + { + id: 'card-event', from: 'analysisCard', to: 'event', name: '下钻', cardinality: '1:N', + key: 'sources ⊇ event', + desc: '停机与质量下钻落到事件实例,再回原始日志行号(断言①血缘链)。', + count: () => cardsUsing('event'), + }, + { + id: 'card-improve', from: 'analysisCard', to: 'improvement', name: '形成整改', cardinality: '1:N', + key: 'sources ⊇ improvement', + desc: 'A-05 按影响程度与产能损失排序后转改善;当前任务实例为 0(W3-B 未落地),只出依据不出派单。', + count: () => cardsUsing('improvement'), + }, + { + id: 'card-factor', from: 'analysisCard', to: 'factorDef', name: '按因子拆', cardinality: '1:N', + key: 'sources ⊇ factorDef', + desc: 'A-02 / A-03 / M-03 的损失拆解落到二级因子定义(起止判定 + 量化规则),避免"拆到桶就停"。', + count: () => cardsUsing('factorDef'), + }, + { + id: 'factor-loss', from: 'factorDef', to: 'loss', name: '归口', cardinality: 'N:1', + key: 'GROSS_TO_BUCKET[grossCategory]', + desc: '每个二级因子组唯一归口一个损失桶或计划类;20 组来自 48 个事件码的因子列,' + + '另有 4 个公式派生因子(速度/过程不良/开机不良/FT Index)直接归桶。', + count: () => sixBucketFactorRows().length, + }, + { + id: 'factor-event', from: 'factorDef', to: 'event', name: '由事件定义', cardinality: '1:N', + key: 'factorL1 / factorL2', + desc: '20 个有事件证据的因子组各挂若干事件码;归口用词到损失桶由 GROSS_TO_BUCKET 现推,不手写第二份映射。', + count: () => factorRowsC().filter((r) => s(r['事件码']) !== '—(公式派生)').length, + }, + { + id: 'play-loss', from: 'improvePlaybook', to: 'loss', name: '针对', cardinality: 'N:1', + key: '目标损失桶', + desc: '每张对策针对一个损失归口(CHANGEOVER / FAULT / IDLE_MINOR / SPEED / 质量 / 计划类),' + + '触发条件全部基于损失结构与事件频次,不含拍脑袋的经验阈值。', + count: () => playRowsC().length, + }, + { + id: 'play-factor', from: 'improvePlaybook', to: 'factorDef', name: '治理因子', cardinality: 'N:M', + key: 'basis ⊇ factorDef', + desc: '对策落到可量化的二级因子上(SMED→Setup/Lot setup/换 lot;短停→Jam time/短停;质量→过程/开机不良)。', + count: () => playsUsing('factorDef'), + }, + { + id: 'cost-loss', from: 'costParam', to: 'loss', name: '金额化', cardinality: '1:N', + key: '每分钟停机损失公式', + desc: '损失桶时长 × 每分钟停机损失 → 金额。★ 费率(折旧/人工/能源/边际价值/返工)未签字前,' + + '参数位留空、拒绝输出金额,与 OA-BENEFIT 同一门槛。', + count: () => costRowsC().length, + }, + { + id: 'cost-play', from: 'costParam', to: 'improvePlaybook', name: 'ROI 折算', cardinality: '1:N', + key: 'ROI =(损失减少 + 质量成本下降 − 投入)÷ 投入', + desc: '对策收益的 ROI 折算依赖成本参数。缺基线、费率或收益区间任一即拒绝测算(SK8 停止条件)。', + count: () => costRowsC().length, + }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 规则:阈值照口径原文,命中数按真实数据现算;跑不出结果的标 blocked + gap + * ══════════════════════════════════════════════════════════════════ */ + +const residualDays = () => days().filter((d) => Math.abs(d.buckets.residualSec) > EPS); +const overUnattr = () => days().filter((d) => d.buckets.unattributedPct > DQ_DEFAULTS.unattributedBlockPct); +const blockedDays = () => days().filter((d) => d.dq.blocked); +const unsignedP0 = () => Object.values(CALIBER_ITEMS).filter((c) => c.priority === 'P0' && !c.signedOff); +const gapOverrideDevices = () => DEVICES.filter((d) => d.gapThresholdMin !== defaultGapThresholdMin(d.ictSec)); +const noLogDevices = () => DEVICES.filter((d) => !d.hasLog); +const notEvaluated = () => days().flatMap((d) => d.dq.notEvaluated.map((x) => ({ bizDate: d.bizDate, ...x }))); +const untimedAll = () => days().flatMap((d) => d.buckets.untimedSubFactors.map((u) => ({ bizDate: d.bizDate, ...u }))); +const crossVersion = () => perfRows().filter((r) => s(r['口径版本']) !== CALIBER_VERSION); +const zeroStartupDays = () => days().filter( + (d) => (d.buckets.buckets.find((b) => b.bucket === 'STARTUP_DEFECT')?.durationSec ?? 0) === 0, +); +const unknownDays = () => days().filter((d) => d.segments.totals.unknownSec > 0); +const sumStat = (f: (d: OeeDayResult) => number) => days().reduce((a, d) => a + f(d), 0); + +export const rules: OntRule[] = [ + { + id: 'R-BUCKET-RESIDUAL', name: '六桶残差必须照实暴露', severity: 'error', on: 'loss', + tables: ['loss', 'performance'], + expr: '残差 = PPT − 良品数×ICT − Σ六桶时长 ≡ 未归因 IDLE 时长', + desc: '残差≠0 有两个合法来源:① 未归因空档(IDLE);② 超产(N×ICT>RT)把速度桶夹到 0,此时残差为负。' + + '两种都必须在页面显式告警,**禁止悄悄归一化抹平**——服务层若偷偷修正,断言②与 G2 门同时失效。', + hits: () => ({ + n: residualDays().length, unit: '个业务日残差≠0', + targets: residualDays().map((d) => `${d.bizDate} 残差 ${d.buckets.residualSec}s`), + }), + }, + { + id: 'R-UNATTRIBUTED', name: '未归因占比 >5% 阻断', severity: 'error', on: 'improvement', + tables: ['improvement', 'stateSegment', 'loss'], + expr: `unattributedPct <= ${DQ_DEFAULTS.unattributedBlockPct}`, + desc: 'DQ-06:暂停该设备当日结论发布并派单补录。分母统一为 PPT,不是 CT。' + + '未归因(采到了但归不了因)与未采集(日志断流)严格分开,后者不计入分母。', + hits: () => ({ + n: overUnattr().length, unit: '个业务日超阈值', + targets: overUnattr().map((d) => `${d.bizDate} ${(d.buckets.unattributedPct * 100).toFixed(2)}%`), + }), + }, + { + id: 'R-CALIBER-SIGNOFF', name: 'P0 口径需 IE 签字', severity: 'warning', on: 'caliber', + tables: ['caliber', 'performance'], + expr: 'items.filter(P0).every(signedOff)', + desc: '16 项 P0 未签字时标灰不标绿。平台按附录 E 默认值先行落地,' + + '参数确认后在配置中心切换并保留旧版本,不影响已采集的历史数据。', + blocked: true, + gap: '本次不安排口径工作坊,28 项 signedOff 全 false;C27/C28(三层 OEE 参数、计划损失来源)' + + '与 4 项敏感性议题(Plan 边界 / Occ 判定 / Q 定义 / FT 的 PM 是否计入)待 IE 定版。', + hits: () => ({ + n: unsignedP0().length, unit: '项 P0 待签字', + targets: unsignedP0().map((c) => `${c.id} ${c.name}`), + }), + }, + { + id: 'R-EVENT-UNIQUE', name: '每事件码唯一归口', severity: 'error', on: 'event', + tables: ['event', 'loss'], + expr: 'checkUniqueBucketAssignment(EVENTS_48).ok', + desc: '一个事件码不得同时归两个损失桶,否则 Σ桶时长会重复计数、残差恒不为 0。' + + '归口由 GROSS_TO_BUCKET 现推,不手写第二份映射表(C07)。', + hits: () => { + const r = checkUniqueBucketAssignment(EVENTS_48); + return { n: r.conflicts.length, unit: '处归口冲突', targets: r.conflicts }; + }, + }, + { + id: 'R-GROSS-MAPPING', name: '六-3 → 六-1 映射完备', severity: 'info', on: 'event', + tables: ['event', 'loss'], + expr: '20 个计划类事件 bucket = null(不进六桶)', + desc: '事件表归口用词共 48 项,其中计划停机/计划待料/工程借用三类 20 项不属六大损失桶。' + + '这是**口径事实而非缺陷**:把它们塞进六桶会让 OEE 严重偏低。三套"六"分类不可混用。', + hits: () => ({ + n: eventStats().nullBucketEvents, unit: '个计划类事件不进六桶', + targets: (Object.keys(GROSS_TO_BUCKET) as (keyof typeof GROSS_TO_BUCKET)[]) + .filter((k) => GROSS_TO_BUCKET[k] === null).map((k) => `${k}(${eventStats().gross[k] ?? 0} 项)`), + }), + }, + { + id: 'R-EVENT-ATTRIBUTION', name: '事件级归因链未落地', severity: 'warning', on: 'event', + tables: ['event', 'lot'], + expr: 'event.attribution.lotId ∈ lot.lotId(五级级联:自识别→MES唯一→换型窗口→多候选→未归因)', + desc: 'lot 窗口由板级锚点自识别(SELF_IDENTIFIED 1.00)已落地;但**事件行本身不带 lot 号**,' + + '事件挂批次须按窗口归属/MES 唯一性推导并定置信度。当前 attribution 全为空,' + + '故 lot→event 关系计数为 0——实测事实,不拿窗口包含冒充自识别,也不造归因结果充数。' + + '★ 识别途径(怎么认出来的)与真因 A/B/C 分类(为什么发生)是两回事,不得混用。', + blocked: true, + gap: '五级级联归因引擎待 W2 落地:DEK 事件行无 lot 字段,需按自识别 lot 窗口推导归属并显式标注置信度;' + + 'Datacon 的 Lot 字段为空,须走 MES 唯一匹配 / 换型窗口 / 多候选三级。' + + '多候选不得强判唯一真因,未归因如实进 UNATTRIBUTED(置信度 0.00)。', + hits: () => ({ + n: curEvents().filter((e) => e.attribution?.lotId).length, + unit: '个事件已挂批次(当期)', + targets: curEvents().filter((e) => e.attribution?.lotId).map((e) => `${e.id} → ${e.attribution!.lotId}`), + }), + }, + { + id: 'R-DQ-BLOCK', name: 'DQ 阻断当日结论发布', severity: 'error', on: 'improvement', + tables: ['improvement', 'performance'], + expr: `blockingDq ⊆ {${BLOCKING_DQ.join(', ')}}`, + desc: '三条阻断级规则命中即暂停发布,页面给出完整话术:结论暂缓发布 + 原因 + 补录入口。' + + '阻断不是"算不出来",是"算出来了但不许发布"。', + hits: () => ({ + n: blockedDays().length, unit: '个业务日被阻断', + targets: blockedDays().map((d) => `${d.bizDate} ${d.dq.blockedBy.join('/')}`), + }), + }, + { + id: 'R-DQ-NOT-EVALUATED', name: '缺证据的 DQ 规则标灰', severity: 'warning', on: 'improvement', + tables: ['improvement'], + expr: 'notEvaluated.length 逐条列出缺什么', + desc: '12 条规则里没有证据支撑的不得标绿通过,必须列出缺失项。' + + '治理台按"已评估 / 未评估"两栏分开呈现,避免"全绿"假象。', + hits: () => ({ + n: notEvaluated().length, unit: '条规则缺证据未评估', + targets: notEvaluated().map((x) => `${x.bizDate} ${x.code} 缺 ${x.missing}`), + }), + }, + { + id: 'R-DOWN-JAM-300', name: 'Down/Jam 按 300 秒分界', severity: 'info', on: 'stateSegment', + tables: ['stateSegment', 'event', 'caliber'], + expr: '单次连续停机 >300s → DOWN;≤300s → JAM', + desc: 'C08 统一 300 秒分界,C14 明确按**单次连续停机的持续时长**判定(不是累计时长)。' + + 'C13 权威时间取最早可信时间,差异超 5 分钟转人工复核。', + hits: () => { + const segs = cur().segments.segments.filter((g) => g.state === 'DOWN' || g.state === 'JAM'); + return { + n: segs.length, unit: '个停机段(当期)', + targets: segs.map((g) => `${STATE_LABEL[g.state]} ${g.durationSec}s ${g.id}`), + }; + }, + }, + { + id: 'R-GAP-THRESHOLD', name: '间隙阈值按设备生效', severity: 'warning', on: 'equipment', + tables: ['equipment', 'stateSegment'], + expr: 'gapThresholdMin ≠ max(5, 3×ICT/60) 的设备须以台账值为准', + desc: 'kohyoung AOI 必须 15min(节拍是分钟级,用 5min 会把正常生产误判为停机)、' + + 'Jetting 必须 3min。这两台恰好都不等于公式默认值,正是**台账值优先于公式**的证据。', + hits: () => ({ + n: gapOverrideDevices().length, unit: '台阈值覆盖公式默认值', + targets: gapOverrideDevices().map( + (d) => `${d.id} 台账 ${d.gapThresholdMin}min ≠ 公式 ${defaultGapThresholdMin(d.ictSec)}min`, + ), + }), + }, + { + id: 'R-NO-LOG', name: '无日志设备需加装 IO', severity: 'warning', on: 'equipment', + tables: ['equipment'], + expr: 'hasLog = false → 过渡通道 IO_LIGHT / UPSTREAM_INFER', + desc: 'Loader/分轨机/绿皮机无日志输出(合计约 10 台〔POC〕),需加装 IO 三色灯/光电后才能采集;' + + '中间缓存无独立日志,由上下游进出板时间反推占用率,且**不计 OEE**(不生产,计进去会凭空多一个分母)。', + blocked: true, + gap: '无日志设备尚未加装 IO 硬件,过渡期靠人工录入;D 类事件超时触发 DQ-11。' + + '绿皮机的正式工站名与工艺位置待客户确认,不臆造拓扑。', + hits: () => ({ + n: noLogDevices().length, unit: '台无独立日志', + targets: noLogDevices().map((d) => `${d.id} ${d.name}(${d.fallbackChannel ?? '—'})`), + }), + }, + { + id: 'R-ICT-PENDING', name: 'ICT 待 IE 提供', severity: 'warning', on: 'equipment', + tables: ['equipment', 'performance'], + expr: "ictSource = 'PENDING_IE' → ictSec = 0,不编数", + desc: '回流焊/MBT/Xray/无日志三类的节拍规划书未给。ictSec=0 是**口径事实**而非数据缺失:' + + 'FT 的 P 用「1 − 三项损失占比」不用 ICT,ASLT 按 C05 用理论工时/实际工时。' + + '回流焊须由上下游工站事件配对推导后由 IE 确认。', + blocked: true, + gap: '规划书未给这些设备的实测节拍,须 IE 提供后才能算 P;回流焊无进出板信号,' + + '只能走 SRF 时间分配法按上下游节拍拆分,并显式标注推导置信度。', + hits: () => ({ + n: deviceStats().ictPendingIe, unit: '台节拍待 IE 提供', + targets: DEVICES.filter((d) => d.ictSource === 'PENDING_IE').map((d) => `${d.id} ${d.name}`), + }), + }, + { + id: 'R-DEMO-CODE', name: '演示占位码须替换', severity: 'warning', on: 'equipment', + tables: ['equipment'], + expr: "codeSource = 'DEMO' → 接入前必须替换为客户台账编码", + desc: '沿用客户既有台账编码、不重新编号(规划书 5.1)。已知真实编码只有 5 个:' + + 'DCP005〔POC〕、93k178/93k250/93k287〔方案〕、suzamdaslt386〔POC〕。' + + '其余 12 台客户未给编码,用演示占位码并明示"待客户台账确认"。', + hits: () => ({ + n: deviceStats().demoCode, unit: '台用演示占位码', + targets: DEVICES.filter((d) => d.codeSource === 'DEMO').map((d) => d.id), + }), + }, + { + id: 'R-TASK-DISPATCH', name: '四项必填才派发', severity: 'error', on: 'improvement', + tables: ['improvement'], + expr: 'owner && dueDate && expectedBenefit && verificationResult → canDispatch', + desc: '改善任务六态(待生成→待审核→已派发→执行中→已验证→已归档);四项任一缺失即 canDispatch=false。' + + '证据链不完整只作候选不进派单;根因只挂五实体之一,不允许多个并列首要真因;收益给区间不给点值。', + blocked: true, + gap: 'closure 引擎与任务中心在 W3-B 落地,当前**无改善任务实例**。' + + '建议书 3.6 写的"6 条任务"是目标态而非现有数据,此处不编造任务充数。', + hits: () => ({ n: 0, unit: '条任务(引擎未落地)', targets: [] }), + }, + { + id: 'R-CROSS-VERSION', name: '跨口径版本拒绝对比', severity: 'error', on: 'performance', + tables: ['performance', 'caliber'], + expr: 'compare(a, b) 要求 a.caliberVersion === b.caliberVersion', + desc: '换分母即换口径。同一报表混用两个 caliber_version 触发 DQ-12 阻断;' + + '智能体技能 SK3/SK8 在版本不同时直接拒绝,不做"看起来能比"的拼接(断言⑩)。', + hits: () => ({ + n: crossVersion().length, unit: '条结果版本不一致', + targets: crossVersion().map((r) => `${s(r['业务日'])} ${s(r['档位'])} ${s(r['口径版本'])}`), + }), + }, + { + id: 'R-SHIFT-ASSUMPTION', name: '班次时刻为演示假设', severity: 'warning', on: 'stateSegment', + tables: ['stateSegment', 'equipment', 'caliber'], + expr: 'SHIFT_PATTERN = 3×8h(夜班 0–8 / 白班 8–16 / 中班 16–24)', + desc: '规划书 4.6.1 只写"3 班"未给具体时刻,此处取标准三班制作为演示假设。' + + 'C24(P0)跨天班次归属到**事件开始时刻所在业务日**;本 pattern 下业务日=日历日,CT 窗口=00:00→24:00。', + blocked: true, + gap: SHIFT_ASSUMPTION_NOTE, + hits: () => ({ + n: SHIFT_PATTERN.length, unit: '个班次(假设时刻)', + targets: SHIFT_PATTERN.map((x) => `${x.id} ${x.name} ${x.startHour}:00–${x.endHour}:00`), + }), + }, + { + id: 'R-LINE-SYNTHESIS', name: '线体/区域绩效实例待接入', severity: 'warning', on: 'lineTopology', + tables: ['lineTopology', 'performance'], + expr: 'SRF 串行 A/Q 连乘、P 取瓶颈;FT 并行按投入量加权;ASLT 12 Site 使能占比', + desc: '三套模板不同构:SRF 缓冲解耦为主口径(25.50%)、零缓冲 16.02% 为理论下界,两者不可混用;' + + 'FT 的 A 是连乘扣减式,与通用 A=RT/PPT 不同构。合成引擎已落地(W2-A,L3 出线体/区域读数,断言④守住);' + + '本体绩效对象仍只实例化到 DEVICE(DEK 锚点),线体/区域实例与视图待 W2-B。', + blocked: true, + gap: serviceStats().coverageGap, + hits: () => ({ + n: LINES.length, unit: '条线待出本体实例', + targets: LINES.map((l) => `${l.id} ${TEMPLATE_LABEL[l.template]}`), + }), + }, + { + id: 'R-STARTUP-DEFECT', name: '开机不良未采集计 0 标缺口', severity: 'warning', on: 'loss', + tables: ['loss', 'event'], + expr: 'startupDefectQty 未注入 → 桶时长 0,且不得把过程不良摊进来', + desc: '开机不良=首件不良数×ICT(换型后爬坡/首件不良/rescreen 复测)。' + + '首件检验数据未接入时计 0 并显式标缺口——**摊派会制造假精度**,让评审误以为已量到。', + blocked: true, + gap: '首件检验/首件不良数据未接入,三日开机不良桶均为 0。这是数据缺口而非"没有开机不良"。', + hits: () => ({ + n: zeroStartupDays().length, unit: '个业务日开机不良为 0', + targets: zeroStartupDays().map((d) => d.bizDate), + }), + }, + { + id: 'R-UNTIMED-SUBFACTOR', name: '未计时子因子标灰不摊数', severity: 'warning', on: 'loss', + tables: ['loss', 'stateSegment'], + expr: 'untimedSubFactors 时长留空(不是 0)', + desc: '段内出现但未单独计量的子因子(如 Down 段里的「维修等待」):缺 EA 到场时间戳就无法把停机' + + '拆成「故障」与「等维修」。UI 标灰并说明缺什么,禁止摊一个数出来充精度。' + + '★ 当期实例为 0 是种子覆盖事实:DEK 停机段只含单一子因子 S-29(Down Time/Down),' + + '未构造同段多子因子场景;引擎路径已由校验脚本用合成输入(S-27 Down + S-28 维修等待 同段)验证。', + blocked: true, + gap: '当前 DEK 种子的停机段只含单一子因子(S-29 Down Time/Down),未计时子因子实例为 0。' + + '引擎路径已用合成输入验证(整段归首事件因子、被跳过子因子只留证不计时);' + + '真实场景需 EA 到场/离场时间戳才能拆分「故障」与「等维修」,待 W2 接入。', + hits: () => ({ + n: untimedAll().length, unit: '个未计时子因子', + targets: untimedAll().map((u) => `${u.bizDate} ${u.factorL1}/${u.factorL2}`), + }), + }, + { + id: 'R-CLOCK-BACKWARD', name: '时钟回跳自动修正留双字段', severity: 'info', on: 'event', + tables: ['event', 'improvement'], + expr: '相邻事件时间戳倒退 >60 秒 → DQ-01 自动修正', + desc: 'DEK 一日发生 4 次时钟回跳〔POC〕。修正在 L1 采集适配层完成,L2 引擎保持纯函数可重放;' + + '原始/校正双时间字段都保留,改钟事件 31317/31318 跳过不入事件表但留证供审计。', + hits: () => ({ + n: sumStat((d) => d.dq.stats.clockBackwardCount), unit: '次回跳(三日)', + targets: days().filter((d) => d.dq.stats.clockBackwardCount > 0) + .map((d) => `${d.bizDate} ${d.dq.stats.clockBackwardCount} 次 / 已校正 ${d.dq.stats.correctedCount} 条`), + }), + }, + { + id: 'R-DUPLICATE', name: '重复事件丢弃并计数', severity: 'info', on: 'event', + tables: ['event', 'improvement'], + expr: 'dedup_key 命中已有记录 → DQ-09 丢弃并计数', + desc: '去重点在 L1,被丢弃的重复行必须留证上报(keptLineNo 给出血缘)。' + + '若只在已去重的事件表上再数一遍,重复率永远是 0——治理台就看不到真实采集质量。', + hits: () => ({ + n: sumStat((d) => d.dq.stats.duplicateCount), unit: '条重复被丢弃(三日)', + targets: days().filter((d) => d.dq.stats.duplicateCount > 0) + .map((d) => `${d.bizDate} ${d.dq.stats.duplicateCount} 条 / 重复率 ${(d.dq.stats.duplicateRate * 100).toFixed(2)}%`), + }), + }, + { + id: 'R-UNKNOWN-SEC', name: '未采集 ≠ 无生产', severity: 'warning', on: 'stateSegment', + tables: ['stateSegment', 'performance', 'improvement'], + expr: 'UNKNOWN 段不计入分母 PPT(DQ-10 三态分开)', + desc: '日志断流窗口标"未采集",不等同于"无生产",也不计入分母。' + + '三态(未采集 / 未归因 / 已归因)必须分开:混在一起会让 A 因子被采集缺口污染。', + hits: () => ({ + n: unknownDays().length, unit: '个业务日有未采集窗口', + targets: unknownDays().map((d) => `${d.bizDate} ${d.segments.totals.unknownSec}s`), + }), + }, + { + id: 'R-MISSING-CODES', name: '事件表缺失编号留证', severity: 'info', on: 'event', + tables: ['event'], + expr: '原表 60 行去重 12 行 → 48 个事件码', + desc: '缺失编号是原表事实,不补号、不猜归口。码表里没有的码在 L1 显式进 unmapped 缺口池,' + + '不静默丢弃(DEK 96 码全表到位前,未映射码如实上报)。', + hits: () => ({ + n: MISSING_CODES.length, unit: '个缺失编号', + targets: [...MISSING_CODES], + }), + }, + { + id: 'R-DEMO-MODE', name: '纯 demo 数据沙箱', severity: 'warning', on: 'equipment', + tables: ['equipment', 'event', 'performance'], + expr: 'dataMode = demo(L1 读合成种子)', + desc: '本工程为纯 demo 前端:L1 读内置合成种子,不连接后端、不做任何实时直采。' + + '采集通道接入前不得声称已支持直采;页面与导出都带来源标注(DEMO_SEED),POC 锚点数字只作参考基线。', + blocked: true, + gap: REFERENCES_DEMO_SANDBOX_GAP, + hits: () => ({ + n: 1, unit: '个数据模式缺口', + targets: ['DATA_MODE=demo'], + }), + }, + /* ── 共同分析本体的 6 条规则:因子口径、分析顺序、对策门槛、费率签字、质量源缺口 ── */ + { + id: 'R-FACTOR-UNIQUE', name: '每个二级因子唯一归口', severity: 'error', on: 'factorDef', + tables: ['factorDef', 'event', 'loss'], + expr: 'factorGroup.bucket ∈ 六桶 ∪ {null},且组内全部事件码同桶', + desc: '一个二级因子不得同时归两个损失桶,否则 Σ桶时长重复计数。20 组由 48 个事件码的因子列现聚,' + + '不手写第二份映射;派生因子(速度/过程不良/开机不良/FT Index)由公式归桶并标推导量。', + hits: () => ({ + n: factorGroups().length, unit: '个二级因子组唯一归口', + targets: factorGroups().map((g) => `${g.l1}/${g.l2} → ${g.bucket ? BUCKET_LABEL[g.bucket] : '计划类'}`), + }), + }, + { + id: 'R-ANALYSIS-ORDER', name: '分析顺序不可跳步', severity: 'info', on: 'analysisCard', + tables: ['analysisCard', 'performance', 'loss'], + expr: '计划达成 → 产出效率 → A/P/Q 拆解 → 停机/质量下钻 → 排优先级', + desc: 'SoW 要求的分析动线:先看计划有没有完成,再看产出效率;效率异常才拆 OEE;' + + '不直接从 OEE 跳到根因。指标组合七组同样先看组合再看单项,避免单指标误判。', + hits: () => ({ + n: CARD_DEFS.length, unit: '张分析卡按顺序编排', + targets: CARD_DEFS.map((c) => `${c.id} ${c.kind}:${c.question.slice(0, 18)}…`), + }), + }, + { + id: 'R-SETUP-SMED', name: '换型损失触发 SMED 候选', severity: 'warning', on: 'loss', + tables: ['loss', 'factorDef', 'improvePlaybook'], + expr: 'CHANGEOVER 因子(Setup / Conversion / Lot setup / 换 lot)占 PPT 居前 → SMED 候选', + desc: 'Setup/Conversion/Lot setup/换 lot 全部归 CHANGEOVER 桶;当换型时长或次数居前时生成 SMED 对策候选。' + + '触发门槛未定版前只提示、不自动派单。', + blocked: true, + gap: 'SMED 触发门槛(换型次数/时长/占比)待 IE 定版;对策中心与任务中心在 W3-B,' + + '当前只出候选不派单。', + hits: () => { + const fs = cur().buckets.factors.filter((f) => f.factorL1 === 'Set up loss'); + return { + n: fs.length, unit: '个换型类因子(当期)', + targets: fs.map((f) => `${f.factorL2} ${f.durationSec}s`), + }; + }, + }, + { + id: 'R-JAM-FREQUENCY', name: '短停按次数与时长双看', severity: 'warning', on: 'event', + tables: ['event', 'stateSegment', 'factorDef'], + expr: 'Jam time / 短停:次数看稳定性,时长看大损失,不得只按总时长排名', + desc: '高频短停单次 ≤300s、总时长不显眼,但次数反映设备稳定性。' + + '排名必须同时给次数与时长,否则高频短停会被偶发长停盖住。', + blocked: true, + gap: '频次告警阈值待定;Jam 多为 D 类人工录入,次数可信度受补录完整度影响(DQ-11 超时升级)。', + hits: () => { + const jam = curEvents().filter((e) => { + const d = EVENT_BY_CODE[e.defCode]; + return d?.factorL2 === 'Jam time' || d?.factorL2 === '短停'; + }); + return { n: jam.length, unit: '个短停事件(当期)', targets: jam.map((e) => `${e.defCode} ${e.id}`) }; + }, + }, + { + id: 'R-COST-SIGNOFF', name: '费率未签字拒绝金额化', severity: 'error', on: 'costParam', + tables: ['costParam', 'loss', 'improvePlaybook'], + expr: 'C-01…C-05 费率全部提供并签字 → 才允许 C-06/C-07 出金额与 ROI', + desc: '损失金额化与 ROI 的四项门槛:费率签字、基线、收益区间、同口径对比。' + + '任一缺失即拒绝测算,**不给任何金额数字**(与 OA-BENEFIT 的三期 A7 同一门槛)。', + blocked: true, + gap: '设备折旧率/人工费率/能源单价/良品边际价值/返工成本未由财务提供与签字;' + + '当前参数位留空,任何金额与 ROI 均不产出。', + hits: () => ({ + n: COST_DEFS.length, unit: '个成本参数待签字', + targets: COST_DEFS.map((c) => `${c.id} ${c.name}(${c.unit})`), + }), + }, + { + id: 'R-FTRD-GAP', name: 'FTRD/在制品/负荷数据源未接入', severity: 'warning', on: 'analysisCard', + tables: ['analysisCard', 'lot', 'event'], + expr: 'M-05 良率+FTRD+返工 / M-06 利用率+在制品 / M-07 产量+负荷+故障趋势', + desc: '三组指标组合依赖尚未接入的数据源:FTRD 与返工、在制品(WIP)、设备负荷与维修记录。' + + '缺源时标灰说明缺什么,不拿良率冒充 FTRD、不拿运行率冒充负荷。', + blocked: true, + gap: 'FTRD/返工、WIP、维修工单与设备负荷均无数据源;' + + '当前只能看批次良率与事件表停机,三个组合标"缺口"而非"可算"。', + hits: () => ({ + n: CARD_DEFS.filter((c) => c.status === '缺口').length, unit: '个指标组合依赖未接入数据源', + targets: CARD_DEFS.filter((c) => c.status === '缺口').map((c) => `${c.id} ${c.question.slice(0, 16)}…`), + }), + }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 动作:只覆盖口径/规则里真写了的处置,不另编 + * ══════════════════════════════════════════════════════════════════ */ + +const targetsOf = (id: string) => rules.find((r) => r.id === id)?.hits().targets ?? []; +const objName = (id: string) => DEFS.find((d) => d.id === id)?.name ?? id; + +export const actions: OntAction[] = [ + { + id: 'OA-TIMELINE', name: '查设备时间轴', en: 'query_device_timeline', + object: objName('stateSegment'), type: 'query', tables: ['stateSegment', 'event', 'equipment'], + trigger: '选中设备 + 业务日(三要素齐备)', + desc: '按十态抢占优先级渲染甘特,跨班拆分段共享 splitGroupId,影子时长双记录不重复扣减。' + + '受控工具 TL2:只读,下钻必须回得到 lineNo,否则即停。', + targets: () => segRows().map((r) => s(r['段id'])), + }, + { + id: 'OA-GANTT-LINENO', name: '跳转原始日志行号', en: 'jump_to_raw_line', + object: objName('event'), type: 'query', tables: ['event', 'stateSegment'], + trigger: '状态段 → 事件实例 → 原始行', + desc: '断言①血缘链的终点:指标→桶→因子→状态段→事件实例→原始日志行号。' + + '对外只给行号与摘要哈希,全文仅内网审计链路可取。', + targets: () => curEvents().filter((e) => e.evidence.lineNo > 0).map((e) => `${e.defCode} 行 ${e.evidence.lineNo}`), + }, + { + id: 'OA-CAPABILITY', name: '查能力矩阵', en: 'query_capability_matrix', + object: objName('equipment'), type: 'query', tables: ['equipment'], + trigger: '讲解六类数据可得性场景', + desc: '按附录 D.1 演示顺序(DEK→Jetting→FT Tester→Datacon→kohyoung→回流焊)逐台展开六维星级,' + + '信号完整度单调不增,演完全部六类场景。', + targets: () => [...DEMO_ORDER], + }, + { + id: 'OA-LINE-SYNTH', name: '查线体合成', en: 'query_line_synthesis', + object: objName('lineTopology'), type: 'query', tables: ['lineTopology', 'performance'], + trigger: '选中线体 + 周期', + desc: 'SRF 串行 A/Q 连乘、P 取瓶颈;FT 并行按投入量加权;ASLT 按 12 Site 使能占比。' + + '**合成引擎待 W2 接入**,当前只呈现拓扑与口径,不出合成数字。', + targets: () => LINES.map((l) => l.id), + }, + { + id: 'OA-BOTTLENECK', name: '定位瓶颈站', en: 'locate_bottleneck', + object: objName('lineTopology'), type: 'query', tables: ['lineTopology', 'equipment'], + trigger: '线体 OEE 低于目标', + desc: 'SRF 瓶颈指向 DCP005(751min 缺失数据 + 124min 停机〔POC〕),也是优先处理清单第一名。' + + '瓶颈站按 C15 由主数据维护、按产品路线分别配置,不臆造。', + targets: () => LINES.filter((l) => l.bottleneckDeviceId).map((l) => `${l.id} → ${l.bottleneckDeviceId}`), + }, + { + id: 'OA-LOT-YIELD', name: '查批次良率', en: 'query_lot_yield', + object: objName('lot'), type: 'query', tables: ['lot', 'performance'], + trigger: '选中批次号', + desc: '批次良率=合格数/投入数,由完成行锚点现算。工程批按 C10 默认剔除(影响 Q 约 2.08pp)。' + + '无完成行的 lot 不造窗口,N=0 时 P/Q 失去意义,由 DQ 暴露缺口。', + targets: () => lotRowsC().map((r) => `${s(r['业务日'])}|${s(r['批次号'])}`), + }, + { + id: 'OA-ATTR-TRACE', name: '追溯归因途径', en: 'trace_attribution', + object: objName('lot'), type: 'query', tables: ['lot', 'event'], + trigger: '事件需要挂批次', + desc: '五级级联归因:设备自识别 1.00 → MES 窗口唯一 0.95 → 换型窗口 0.90 → 多候选缩小 0.85 → 无法归因 0.00。' + + '无法归因进未归因池,**绝不猜测**。注意这是"识别途径",与真因 A/B/C 分类是两回事。', + targets: () => curEvents().filter((e) => e.attribution).map((e) => `${e.defCode} → ${e.attribution?.lotId ?? '未归因池'}`), + }, + { + id: 'OA-EVENT-STREAM', name: '查事件流', en: 'query_event_stream', + object: objName('event'), type: 'query', tables: ['event'], + trigger: '选中设备 + 业务日', + desc: '48 码字典 + 当期实例流。双时间字段并列显示(原始/校正),配对四策略' + + '(TIGHT / MISSING_END / MISSING_START / MULTI_ALARM)逐条标注,补出的时刻不是观测值。', + targets: () => curEvents().map((e) => e.id), + }, + { + id: 'OA-MANUAL-ENTRY', name: '提交 5M1E 补录', en: 'submit_manual_entry', + object: objName('event'), type: 'workflow', tables: ['event', 'improvement'], + trigger: 'D 类事件(必须人工录入)发生', + desc: '七字段:真因一级(人/机/料/法/环/测)、真因二级、原因描述≤50 字、对策、建议归口、是否计划内、' + + '补录人/时间由系统写入不可手填。班次结束后 30 分钟未录入触发 DQ-11 升级提醒班组长。' + + '**录入台在 W3-A 落地**,当前只登记契约。', + targets: () => EVENTS_48.filter((e) => e.grade === 'D').map((e) => `${e.code} ${e.name}`), + }, + { + id: 'OA-PARETO', name: '查损失 Pareto', en: 'query_loss_pareto', + object: objName('loss'), type: 'report', tables: ['loss', 'performance'], + trigger: '当期 OEE 低于目标', + desc: '六桶按时长降序 + 占 PPT 份额。分母统一为 PPT(不是 CT,也不是日历时间)。' + + '推导桶(速度降低/过程不良/开机不良)标"推导量",不提供事件级下钻。', + targets: () => [...cur().buckets.buckets].sort((a, b) => b.durationSec - a.durationSec) + .map((b) => `${BUCKET_LABEL[b.bucket]} ${b.durationSec}s(${b.factor})`), + }, + { + id: 'OA-RESIDUAL', name: '查六桶残差', en: 'query_residual', + object: objName('loss'), type: 'report', tables: ['loss', 'stateSegment'], + trigger: '残差 ≠ 0', + desc: '残差=PPT−良品数×ICT−Σ六桶,恒等于未归因时长。第二个合法非零来源是超产把速度桶夹到 0(残差为负)。' + + '照实暴露并给来源解释,不让评审猜,更不许归一化抹平。', + targets: () => targetsOf('R-BUCKET-RESIDUAL'), + }, + { + id: 'OA-THREE-TIER', name: '查三层 OEE', en: 'query_three_tier', + object: objName('performance'), type: 'query', tables: ['performance', 'caliber'], + trigger: '选中设备 + 业务日', + desc: '理论/计划/实际三档共用同一分母 PPT=CT−PDT−UNKNOWN。' + + '理论档 A=1−每日不可避免停机/PPT、P=1、Q=设计良率;计划档取 IE 月度目标。' + + 'C27/C28 待 IE 签字,未签字前不得当作客户确认口径。', + targets: () => perfRows().map((r) => `${s(r['业务日'])}|${s(r['档位'])}`), + }, + { + id: 'OA-DELTA', name: '顺序替代差异分解', en: 'sequential_replace_delta', + object: objName('performance'), type: 'report', tables: ['performance'], + trigger: '两档同口径结果对比', + desc: '顺序固定 A→P→Q:ΔA=(t.a−b.a)×b.p×b.q,ΔP=t.a×(t.p−b.p)×b.q,ΔQ=t.a×t.p×(t.q−b.q)。' + + '换顺序会换结论,故顺序不可配置。跨口径版本直接拒绝(SK3 停止条件)。', + targets: () => days().map((d) => { + const x = d.tiers.deltaPlannedToActual; + return `${d.bizDate} ΔA ${(x.dA * 100).toFixed(2)}pp / ΔP ${(x.dP * 100).toFixed(2)}pp / ΔQ ${(x.dQ * 100).toFixed(2)}pp`; + }), + }, + { + id: 'OA-CALIBER-SOURCE', name: '查口径出处', en: 'query_caliber_source', + object: objName('caliber'), type: 'query', tables: ['caliber', 'performance'], + trigger: '任一指标被质疑', + desc: '每个数字都能回指口径编号、默认值、归口责任人与版本号。' + + 'P0 未签字标灰;4 项敏感性议题优先呈现(Plan 边界 / Occ 判定 / Q 定义 / FT 的 PM 是否计入)。', + targets: () => targetsOf('R-CALIBER-SIGNOFF'), + }, + { + id: 'OA-VERSION-REPLAY', name: '切换口径版本回放', en: 'switch_caliber_version', + object: objName('caliber'), type: 'workflow', tables: ['caliber', 'performance'], + trigger: 'IE 定版后切换参数', + desc: '切换任一项生成新版本,旧版本结果保留可回放,不影响已采集的历史数据。' + + '带覆盖参数时服务层不走缓存、必须真重算(断言⑩)。**配置中心在 W4-A 落地**。', + targets: () => [CALIBER_VERSION], + }, + { + id: 'OA-DQ-NOTICE', name: '结论暂缓发布告警', en: 'publish_block_notice', + object: objName('improvement'), type: 'alert', tables: ['improvement', 'performance'], + trigger: 'DQ-06 / DQ-08 / DQ-12 命中', + desc: '阻断时给 UI 完整话术:结论暂缓发布 + 原因 + 补录入口。' + + '原型只在站内提示(TL5),不接真实 OA/邮件通道。', + targets: () => blockedDays().map((d) => d.bizDate), + }, + { + id: 'OA-DISPATCH', name: '派改善单', en: 'dispatch_improvement', + object: objName('improvement'), type: 'workflow', tables: ['improvement', 'loss'], + trigger: '四项必填齐备 + 证据链完整', + desc: '四项必填:责任人、期限、预期收益区间、验证方式。任一缺失 canDispatch=false,不派发。' + + '根因只挂五实体之一(设备/模具工装/物料批次/人员班组/程序参数)。**任务中心在 W3-B 落地**。', + targets: () => targetsOf('R-UNATTRIBUTED'), + }, + { + id: 'OA-SLA', name: '查 SLA 与升级', en: 'query_sla_escalation', + object: objName('improvement'), type: 'alert', tables: ['improvement'], + trigger: '任务超期未推进', + desc: '六态流转非法即拒;超期按 slaEscalatedTo 升级。D 类补录超时走 DQ-11 升级班组长,' + + '报表以快照值出数并标注。**闭环引擎在 W3-B 落地**。', + targets: () => Object.values(TASK_STATE_LABEL), + }, + { + id: 'OA-BENEFIT', name: '验证改善收益', en: 'verify_benefit', + object: objName('improvement'), type: 'report', tables: ['improvement', 'performance', 'caliber'], + trigger: '任务已闭环 + 前后期同口径', + desc: '前后对比必须同口径版本,否则拒绝(SK8 停止条件)。收益给区间不给点值。' + + '金额化测算属三期 A7:四门槛齐备且费率签字前**拒绝测算,不给任何金额数字**。', + targets: () => targetsOf('R-CROSS-VERSION'), + }, + { + id: 'OA-EXPORT', name: '导出口径对齐报表', en: 'export_caliber_aligned_report', + object: objName('performance'), type: 'report', tables: ['performance', 'caliber'], + trigger: '评审/月度复盘', + desc: '导出必带口径版本与模拟标注(DEMO_SEED);POC 锚点数字标为参考基线。' + + '跨版本拼装拒绝(TL4 白名单约束)。**报表导出在 W4-B 落地**。', + targets: () => [`${CALIBER_VERSION} · demo`], + }, + /* ── 共同分析本体的 4 个动作:按分析卡下钻 / 查因子口径 / 出对策候选 / 查金额化 ── */ + { + id: 'OA-CARD-DRILL', name: '按分析卡下钻', en: 'drill_analysis_card', + object: objName('analysisCard'), type: 'query', tables: ['analysisCard', 'performance', 'loss'], + trigger: '用户问"计划完成了没有 / 效率为什么降 / 停机原因 / 质量问题"', + desc: '按 A-01→A-05 的固定动线取数:先计划达成,再产出效率,再拆 A/P/Q,再分头下钻,最后排优先级。' + + '每张卡先亮"误判提醒"再给数,避免小/大订单比例、工时快于产量等口径陷阱。', + targets: () => CARD_DEFS.map((c) => `${c.id} ${c.question.slice(0, 16)}…`), + }, + { + id: 'OA-FACTOR-QUANT', name: '查因子量化标准', en: 'query_factor_quantification', + object: objName('factorDef'), type: 'query', tables: ['factorDef', 'event', 'loss'], + trigger: '质疑某个损失怎么算(Setup / Jam / Index / 待料)', + desc: '给判定起点、判定终点、量化规则与口径编号:Setup ±5min 是录入偏移不是派生;' + + 'Jam/Down 按单次连续 300s;Index 损失按 [Index/(Index+Test)]×(1−OE Eff Loss−Jam Factor)。', + targets: () => factorRowsC().map((r) => s(r['因子编号'])), + }, + { + id: 'OA-PLAYBOOK-SUGGEST', name: '出改善对策候选', en: 'suggest_improvement_playbook', + object: objName('improvePlaybook'), type: 'workflow', tables: ['improvePlaybook', 'loss', 'improvement'], + trigger: '损失桶排名确定 + 对策触发条件满足', + desc: '按损失结构匹配 SMED / TPM / 短停 / 速度 / 质量 / 排产六类对策,输出触发条件、KPI 与验证方式。' + + '**只出候选**:四项必填齐备才派单,任务中心 W3-B 未落地前不产生任务实例。', + targets: () => PLAY_DEFS.map((p) => `${p.id} ${p.name}`), + }, + { + id: 'OA-COST-ROI', name: '查损失金额化与 ROI', en: 'query_cost_model', + object: objName('costParam'), type: 'report', tables: ['costParam', 'loss', 'improvePlaybook'], + trigger: '评审问"损失折合多少钱 / 上线 ROI 多少"', + desc: '给公式与参数位,但**不给金额**:费率未签字前当前值留空,' + + '每分钟停机损失与 ROI 一律拒绝测算(与 OA-BENEFIT 同一门槛)。', + targets: () => COST_DEFS.map((c) => `${c.id} ${c.name}`), + }, +]; + +/* ── 图谱:节点=对象,连线=关系 ───────────────────────────────────── */ +export const graphNodes = (): { id: string; label: string; count: number; color: string }[] => + objects.map((o) => ({ id: o.id, label: o.short, count: o.instances().length, color: o.color })); + +export const graphEdges = (): { id: string; source: string; target: string; label: string }[] => + relations.map((r) => ({ id: r.id, source: r.from, target: r.to, label: r.name })); + +/* ══════════════════════════════════════════════════════════════════ + * 范围披露与自检(供校验脚本与"说明与对照"页引用,数字一律现算) + * ══════════════════════════════════════════════════════════════════ */ + +export const ONTOLOGY_SCOPE_NOTE = + `主数据全量:设备 ${DEVICES.length} 台 / 线体 ${LINES.length} 条 / 事件定义 ${EVENTS_48.length} 码 / 口径 ${caliberStats().total} 项。` + + `事实层取锚点设备 ${ANCHOR_DEVICE_ID} 的业务日明细(demo 三日种子;${serviceStats().dates.join('、')}):` + + '批次与绩效覆盖三日,事件实例与状态段只取当期业务日,损失取当期六桶+因子。' + + `线体合成待 W2、改善任务待 W3-B、实时直采通道未接入——三处均以 blocked+gap 标灰,不造实例充数。` + + `另叠共同分析本体:分析问题 ${CARD_DEFS.length} 张(A-01~A-05 / M-01~M-07)、` + + `因子定义 ${factorGroups().length + DERIVED_FACTORS.length} 个(20 个事件因子组+4 个公式派生)、` + + `改善对策 ${PLAY_DEFS.length} 张、成本参数 ${COST_DEFS.length} 项;` + + 'FTRD/返工/在制品/负荷未接入、费率未签字处一律 blocked+gap,不拿良率冒充 FTRD、不出任何金额。'; + +export function ontologyStats() { + const ids = new Set(objects.map((o) => o.id)); + const instCounts = objects.map((o) => ({ id: o.id, n: o.instances().length })); + const nodes = graphNodes(); + const edges = graphEdges(); + const p0Instances = objectById('caliber')!.instances(); + const p0Rows = caliberRows().filter((r) => r['优先级'] === 'P0'); + return { + asOf: OEE_ONTOLOGY_AS_OF, + objectCount: objects.length, + objectIds: objects.map((o) => o.id), + instCounts, + totalInstances: instCounts.reduce((a, x) => a + x.n, 0), + attrCounts: objects.map((o) => ({ id: o.id, n: o.attrs.length })), + relationCount: relations.length, + ruleCount: rules.length, + actionCount: actions.length, + /** 图谱节点数=对象数,边数=关系数 */ + graphNodeCount: nodes.length, + graphEdgeCount: edges.length, + /** 每条边的两端都必须是真实对象 id */ + edgesValid: edges.every((e) => ids.has(e.source) && ids.has(e.target)), + /** 关系两端也必须是真实对象 id(与 edgesValid 同源但独立复核) */ + relationEndpointsValid: relations.every((r) => ids.has(r.from) && ids.has(r.to)), + /** ★ tables 必须填对象 id,否则视图聚焦联动静默失效 */ + ruleTablesValid: rules.every((r) => r.tables.length > 0 && r.tables.every((t) => ids.has(t))), + actionTablesValid: actions.every((a) => a.tables.length > 0 && a.tables.every((t) => ids.has(t))), + actionObjectsValid: actions.every((a) => objects.some((o) => o.name === a.object)), + /** blocked 规则必须给 gap,否则详情面板无话可说 */ + blockedRules: rules.filter((r) => r.blocked).map((r) => r.id), + blockedWithoutGap: rules.filter((r) => r.blocked && !r.gap).map((r) => r.id), + /** 非真空守卫:不能全部规则都 0 命中(那说明 hits 根本没接上真实数据) */ + rulesWithHits: rules.filter((r) => r.hits().n > 0).length, + /** 每条规则都能跑出结果且不抛错 */ + hitsCallable: rules.every((r) => { const h = r.hits(); return typeof h.n === 'number' && Array.isArray(h.targets); }), + /** 每条关系的 count() 都是非负整数 */ + countsCallable: relations.every((r) => Number.isInteger(r.count()) && r.count() >= 0), + /** 关系两端计数互反(属于/包含必须相等) */ + belongsMatchesContains: relations.find((r) => r.id === 'eq-line')!.count() + === relations.find((r) => r.id === 'line-eq')!.count(), + /** ★ P0 未签字不得为绿 */ + p0NotGreen: p0Rows.every((r) => { + const inst = p0Instances.find((x) => x.id === s(r['口径编号'])); + return inst !== undefined && inst.tone !== 'success'; + }), + p0Count: p0Rows.length, + /** ★ 不编造改善任务:当前实例只能是 DQ 问题 */ + noFabricatedTasks: impRows().every((r) => s(r['类别']) === 'DQ问题'), + taskInstanceCount: impRows().filter((r) => s(r['类别']) === '改善任务').length, + /** 事件对象必须同时含定义与实例(建议书 3.6「48 定义 + 实例」) */ + eventDefCount: rowsOf('event').filter((r) => r['类别'] === '定义').length, + eventInstCount: rowsOf('event').filter((r) => r['类别'] === '实例').length, + /** 绩效=三日 × 三档 */ + perfCount: perfRows().length, + tierCount: Object.keys(TIER_LABEL).length, + /** 血缘:每个状态段的事件 id 都能回指真实实例(键空间正确性) */ + segmentEventRefsValid: cur().segments.segments + .every((g) => g.eventIds.every((id) => curEvents().some((e) => e.id === id))), + /** 血缘:每个因子的 segmentIds 都能回指真实状态段 */ + factorSegmentRefsValid: cur().buckets.factors.length > 0 + && cur().buckets.factors.every((f) => f.segmentIds.length > 0 + && f.segmentIds.every((id) => cur().segments.segments.some((g) => g.id === id))), + /** ★ 事件级归因覆盖:当前为 0 是实测事实(事件行不带 lot 号),由 R-EVENT-ATTRIBUTION 标灰披露 */ + attributedEventCount: curEvents().filter((e) => e.attribution?.lotId).length, + /** lot 窗口自识别数(板级锚点印 lot 号 → SELF_IDENTIFIED 1.00),与事件级归因是两件事 */ + lotSelfIdentifiedCount: days().reduce((a, d) => a + d.lots.filter((w) => w.selfIdentified).length, 0), + /** ★ 未计时子因子:当期种子未覆盖同段多子因子场景,故为 0;引擎路径由校验脚本合成输入验证 */ + untimedCount: days().reduce((a, d) => a + d.buckets.untimedSubFactors.length, 0), + factorCount: cur().buckets.factors.length, + caliberVersion: CALIBER_VERSION, + anchorDevice: ANCHOR_DEVICE_ID, + mode: 'demo' as const, + scopeNote: ONTOLOGY_SCOPE_NOTE, + signoffNote: PARAMS_SIGNOFF_NOTE, + /** ★ 共同分析本体:方法论对象计数(不含统计结果) */ + analysisCardCount: CARD_DEFS.length, + analysisLogicCount: CARD_DEFS.filter((c) => c.kind === '分析逻辑').length, + metricComboCount: CARD_DEFS.filter((c) => c.kind === '指标组合').length, + analysisCardGapCount: CARD_DEFS.filter((c) => c.status === '缺口').length, + factorDefCount: factorRowsC().length, + factorGroupCount: factorGroups().length, + factorDerivedCount: DERIVED_FACTORS.length, + factorTimedCount: sixBucketFactorRows().length, + playbookCount: PLAY_DEFS.length, + costParamCount: COST_DEFS.length, + /** ★ 成本参数当前值必须全部留空、签字必须全部待办 → 不产出任何金额 */ + costValueFilled: costRowsC().filter((r) => s(r['当前值']) !== '—(未提供)').length, + costSignedCount: costRowsC().filter((r) => s(r['签字状态']) !== '待财务签字').length, + /** 三套"六"分类的成员数,供"说明与对照"页并列展示,防混用 */ + sixClassification: { + lossBuckets: LOSS_BUCKETS.length, + grossCategories: Object.keys(GROSS_TO_BUCKET).length, + grossNullKeys: eventStats().nullBucketKeys, + bucketFactorMap: { ...BUCKET_FACTOR }, + dqRules: DQ_RULES.length, + blockingDq: [...BLOCKING_DQ], + taskStates: Object.keys(TASK_STATE_LABEL).length, + }, + oeeDevices: OEE_DEVICES.length, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/data/ontologyQap.ts b/src/modules/tfamd-oee/data/ontologyQap.ts new file mode 100644 index 0000000..2af5c76 --- /dev/null +++ b/src/modules/tfamd-oee/data/ontologyQap.ts @@ -0,0 +1,648 @@ +import { + CATALOG, QAP_CALIBER, QAP_SOURCE, TABLES, calc, type QapTableKey, +} from './qap'; + +/** + * 和信精密 · 品质异常预防 —— 业务本体层(对象—关系—规则—动作)。 + * + * 与履约那套本体同结构、同 API(视图层只换 import 来源,不改四栏骨架), + * 但内容是「数据集总览」里那 16 组数据集 / 17 张表: + * 对象 = 一张表(DS-01…DS-16;DS-06 拆成 DS-06a 夹具验收 / DS-06b SOP 两对象) + * 属性 = 表头列,类型 / 必填与否 / 可空说明全部从真实行里推出来,不手写 + * 实例 = 真实行,DS-06a 三类夹具与 DS-15 六张异常单一样,一条行就是一条实例 + * 关系 = 两张表之间的真实连接键(缺陷码、8D 编号、料号、工位…),实例数按列值交集现算 + * 规则 = 原表口径里写明的阈值(滞留 >3 天升级、偏移超允差 60%、相似度 >0.85 拦截…) + * 动作 = 原表「处理动作 / 建议 / 对策」列里真写了的处置,不另编 + * + * 数值唯一来源是 src/data/qap 的 JSON(由 source-data 的 xlsx 逐页签转出), + * 计算列一律走 qap/calc 现算,页面与本文件都不写死任何统计数字。 + */ +export const ONTOLOGY_AS_OF = QAP_CALIBER.warningPoolBaseDate; + +/* ── 类型:与 data/ontology.ts 保持同名同形,视图层因此可以整体替换 ─────── */ +export type AttrType = 'string' | 'number' | 'date' | 'enum'; +export interface OntAttr { name: string; en: string; type: AttrType; required: boolean; note?: string } + +export interface OntInstance { + id: string; title: string; sub: string; meta: string; + /** 右栏强调值。本体里没有金额字段,所以是通用字符串而不是 ¥ 金额 */ + value?: string; badge?: string; tone?: Tone; +} + +export interface OntObject { + id: string; name: string; en: string; desc: string; source: string; + /** 图谱节点用的四字短名:图谱圈里塞不下「结构特征 × 缺陷关联矩阵」 */ + short: string; color: string; + attrs: OntAttr[]; instances: () => OntInstance[]; +} + +export interface OntRelation { + id: string; from: string; to: string; name: string; cardinality: string; + key: string; desc: string; count: () => number; +} + +export type Severity = 'error' | 'warning' | 'info'; +export type Tone = 'success' | 'warning' | 'danger' | 'info'; + +export interface OntRule { + id: string; name: string; severity: Severity; on: string; expr: string; desc: string; + /** 这条规则作用在哪几张表上(表 key):图谱聚焦某张表时,四栏据此高亮相关规则 */ + tables: string[]; + /** 数据缺口规则跑不出结果,标灰而不是标绿 */ + blocked?: boolean; + /** 数据缺口的具体原因,详情面板直接引用(blocked 为真时必填) */ + gap?: string; + hits: () => { n: number; unit: string; targets: string[] }; +} + +export type ActionType = 'query' | 'alert' | 'report' | 'workflow'; +export interface OntAction { + id: string; name: string; en: string; object: string; type: ActionType; + trigger: string; desc: string; + /** 这个动作作用于哪几张表(表 key),与规则同口径,供聚焦联动高亮 */ + tables: string[]; + targets?: () => string[]; +} + +/* ── 取数与格式化小工具 ─────────────────────────────────────────────── */ +type Row = Record; +/** 类型断言:TABLES 里每张表都是各自 interface 的强类型数组,本体层按列名泛化处理 */ +const R = (k: QapTableKey): Row[] => TABLES[k] as unknown as Row[]; +const s = (v: unknown) => (v === null || v === undefined || v === '' ? '—' : String(v)); +const num = (v: unknown) => (typeof v === 'number' ? v.toLocaleString('zh-CN') : s(v)); +const pct1 = (v: unknown) => (typeof v === 'number' ? `${(v * 100).toFixed(1)}%` : '—'); + +const isDate = (v: unknown) => typeof v === 'string' && /^\d{4}-\d{2}-\d{2}/.test(v); +const filled = (v: unknown) => v !== null && v !== undefined && v !== ''; + +/** 列类型靠实际值反推:全数值 → number,全日期 → date,取值 ≤6 种 → enum,其余 string */ +function inferType(vals: unknown[]): AttrType { + const got = vals.filter(filled); + if (got.length === 0) return 'string'; + if (got.every(v => typeof v === 'number')) return 'number'; + if (got.every(isDate)) return 'date'; + if (got.every(v => typeof v === 'string') && new Set(got).size <= 6) return 'enum'; + return 'string'; +} + +/** 属性表就是表头:必填=该列在全部行里都非空,可空则把非空行数写进口径 */ +function deriveAttrs(rows: Row[]): OntAttr[] { + if (rows.length === 0) return []; + return Object.keys(rows[0]).map(col => { + const vals = rows.map(r => r[col]); + const ok = vals.filter(filled).length; + return { + name: col, en: col, type: inferType(vals), required: ok === rows.length, + note: ok === rows.length ? undefined : `非空 ${ok}/${rows.length} 行`, + }; + }); +} + +/* ── 关系/规则共用的列值提取 ─────────────────────────────────────────── */ +const CODE_RE = /DF-[A-Z]+-\d+/g; +const D8_RE = /8D-\d{4}-\d+/g; +const codesIn = (text: unknown) => s(text).match(CODE_RE) ?? []; +const d8sIn = (text: unknown) => s(text).match(D8_RE) ?? []; +/** 两个列集合的交集大小:关系实例数全部这么算,不估算 */ +function overlap(aRows: Row[], aKey: string, bRows: Row[], bKey: string): number { + const b = new Set(bRows.map(r => s(r[bKey]))); + let n = 0; + new Set(aRows.map(r => s(r[aKey]))).forEach(v => { if (b.has(v)) n += 1; }); + return n; +} + +const findCat = (dataset: string) => CATALOG.find(c => c.id === dataset); + +interface TableDef { + key: QapTableKey; + /** 归属数据集编号:DS-06 的两张表都归 DS-06,口径说明取其页签名 */ + dataset: string; + name: string; short: string; color: string; desc: string; + row: (r: Row) => OntInstance; +} + +const DEFS: TableDef[] = [ + { + key: 'DS-01', dataset: 'DS-01', name: '产品-工艺-特征主数据', short: '产品工艺', color: '#818cf8', + desc: '把「材质 × 结构特征 × 工艺方法」压成一个特征码:同族件共享工艺与风险画像,是特征缺陷矩阵与新机型相似度评估的底座。', + row: r => ({ + id: s(r['料号']), title: s(r['料号']), sub: `${s(r['品名'])} · ${s(r['机型'])}`, + meta: `${s(r['材质'])} ${s(r['板厚(mm)'])}mm · ${s(r['工序数'])} 道工序`, + value: `${num(r['年用量(件)'])} 件/年`, badge: s(r['焊接作业方式']), + tone: s(r['焊接作业方式']).startsWith('无') ? 'info' : 'success', + }), + }, + { + key: 'DS-02', dataset: 'DS-02', name: '工位-设备-工装台账', short: '工位设备', color: '#38bdf8', + desc: '八道工序的节拍底账:单班 480min 撑出理论产能,与班次产能一比就是达成率,瓶颈工位由此暴露。', + row: r => ({ + id: s(r['工位']), title: s(r['工位']), sub: `${s(r['工序'])} · ${s(r['设备'])}`, + meta: `工装 ${s(r['工装/夹具'])} · 人机配比 ${s(r['人机配比'])}`, + value: `${num(r['班次产能(件)'])} 件/班`, badge: s(r['瓶颈']), + tone: s(r['瓶颈']) === '否' ? 'success' : s(r['瓶颈']).includes('最大') ? 'danger' : 'warning', + }), + }, + { + key: 'DS-03', dataset: 'DS-03', name: '缺陷代码字典', short: '缺陷字典', color: '#fbbf24', + desc: '全链路的统一语言:检验、异常、8D、知识库共用同一缺陷码,别名列收着各车间历史上的叫法,归并后口径才唯一。', + row: r => ({ + id: s(r['缺陷码']), title: s(r['缺陷码']), sub: `${s(r['缺陷名称'])} · ${s(r['所属工序'])}`, + meta: `检测 ${s(r['检测方式'])} · 历史 8D ${num(r['历史8D数'])} 个`, + value: `近 3 月占比 ${pct1(r['近3月占比'])}`, badge: s(r['严重度']), + tone: s(r['严重度']) === '致命' ? 'danger' : s(r['严重度']) === '严重' ? 'warning' : 'info', + }), + }, + { + key: 'DS-04', dataset: 'DS-04', name: '设备参数采集点台账', short: '采集点', color: '#34d399', + desc: '定义每台设备该采哪些参数、采到多准;采集数据强制带料号 + 批次 + 时间戳,漂移预警与关联分析才有得比。', + row: r => ({ + id: `${s(r['设备编号'])}-${s(r['参数名'])}`, title: s(r['设备编号']), sub: `${s(r['参数名'])} · ${s(r['单位'])}`, + meta: `允许区间 ${s(r['允许区间'])} · ${s(r['采集频率'])}`, + value: `标准值 ${s(r['标准值'])}`, badge: s(r['采集方式']), tone: 'info', + }), + }, + { + key: 'DS-05', dataset: 'DS-05', name: '风险点检表-焊接工序', short: '风险点检', color: '#a78bfa', + desc: '把历史 8D 与 PFMEA 推导成的焊接风险清单,逐条配控制措施、检验频次与责任人,风险项后括注的缺陷码直指缺陷字典。', + row: r => ({ + id: `#${s(r['序号'])}-${s(r['风险项'])}`, title: `#${s(r['序号'])} ${s(r['风险项'])}`, + sub: `${s(r['工序'])} · 责任人 ${s(r['责任人'])}`, + meta: `来源 ${s(r['来源引用'])} · 检验 ${s(r['检验方法/频次'])}`, + value: `历史 ${num(r['历史发生次数'])} 次`, badge: s(r['严重度']), + tone: s(r['严重度']) === '致命' ? 'danger' : s(r['严重度']) === '严重' ? 'warning' : 'info', + }), + }, + { + key: 'DS-06a', dataset: 'DS-06', name: '夹具验收标准卡', short: '夹具验收', color: '#22d3ee', + desc: '给工装夹具补上验收项与更换阈值,让「夹具什么时候该修该换」从老师傅的经验变成可判定、可追溯的判据。', + row: r => ({ + id: `${s(r['夹具编号'])}-${s(r['验收项'])}`, title: s(r['夹具编号']), sub: `${s(r['名称'])} · ${s(r['验收项'])}`, + meta: `适用 ${s(r['适用料号'])} · 点检 ${s(r['点检频次'])}`, + value: `阈值 ${s(r['更换/复检阈值'])}`, badge: s(r['责任']), tone: 'info', + }), + }, + { + key: 'DS-06b', dataset: 'DS-06', name: 'SOP 节选', short: 'SOP', color: '#06b6d4', + desc: '风扇墙焊接的作业步骤,每步的「常见错误」都回指该工序的历史缺陷码——SOP 因此从规程变成了带证据的提醒。', + row: r => ({ + id: `S${s(r['步骤'])}`, title: `步骤 ${s(r['步骤'])}`, sub: s(r['作业内容']), + meta: `工具 ${s(r['工具/工装'])} · 自检 ${s(r['自检项'])}`, + value: s(r['关键参数']), tone: 'info', + }), + }, + { + key: 'DS-07', dataset: 'DS-07', name: '检验标准与遗漏提示', short: '检验标准', color: '#f59e0b', + desc: '机箱底座的检验清单;AI 提示列标出标准缺口(如平面度、外观限度样板),状态列由 QE 确认后才生效。', + row: r => ({ + id: s(r['特征/项目']), title: s(r['特征/项目']), sub: s(r['检验项目']), + meta: `依据 ${s(r['依据'])} · 抽样 ${s(r['抽样'])}`, + value: `频次 ${s(r['频次'])}`, badge: s(r['状态']), + tone: s(r['状态']) === '已覆盖' ? 'success' : 'warning', + }), + }, + { + key: 'DS-08', dataset: 'DS-08', name: '参数卡矩阵(Recipe)', short: '参数卡', color: '#10b981', + desc: '按材质与板厚给出激光焊 / 机器人弧焊的最优参数组合,并标注每个组合的缺陷敏感点,供 HMI 扫码调用。', + row: r => ({ + id: `${s(r['工艺'])}-${s(r['材质/板厚'])}`, title: `${s(r['工艺'])} · ${s(r['材质/板厚'])}`, + sub: `${s(r['焊接形式'])}焊`, + meta: `气 ${s(r['保护气(L/min)'])} L/min · 焊速 ${s(r['焊速(mm/s)'])} mm/s · 离焦 ${s(r['离焦量(mm)'])} mm`, + value: `${s(r['激光功率(W)/电流(A)'])} ${s(r['工艺']) === '机器人弧焊' ? 'A' : 'W'}`, + tone: 'info', + }), + }, + { + key: 'DS-09', dataset: 'DS-09', name: '结构特征 × 缺陷关联矩阵', short: '特征缺陷', color: '#6366f1', + desc: '近 3 个月 4,860 件分批化焊件的特征—缺陷画像,回答「哪类结构最不稳」;综合不良率为四类缺陷率之和。', + row: r => { + const rate = calc.defectRate(r as never); + return { + id: s(r['结构特征维度']), title: s(r['结构特征维度']), sub: s(r['结论']), + meta: `典型料号 ${s(r['典型料号'])} · 样本 ${num(r['样本数'])} 件`, + value: `综合不良率 ${pct1(rate)}`, tone: rate > 0.3 ? 'danger' : rate > 0.2 ? 'warning' : 'success', + }; + }, + }, + { + key: 'DS-10', dataset: 'DS-10', name: '手工与设备焊接方式对比', short: '工法对比', color: '#0ea5e9', + desc: '同料号、同批次板材下三种作业方式的良率、工时与成本对比,把「手工 vs 设备」的差异从印象变成数字。', + row: r => ({ + id: s(r['对比项']), title: s(r['对比项']), + sub: `手工 ${s(r['手工氩弧焊'])} → 激光焊 ${s(r['激光焊(设备)'])}(${s(r['单位'])})`, + meta: s(r['差异结论']), + value: `机器人弧焊 ${s(r['机器人弧焊'])} ${s(r['单位'])}`, tone: 'info', + }), + }, + { + key: 'DS-11', dataset: 'DS-11', name: '8D 知识库(结构化)', short: '8D库', color: '#fb923c', + desc: '历史 8D 的结构化沉淀:缺陷码 + 根因 + 对策 + 相似度。相似度按「缺陷码 + 特征码 + 现象描述」三重算,高即提示这个问题犯过。', + row: r => ({ + id: s(r['8D编号']), title: s(r['8D编号']), sub: `${s(r['客户'])} · ${s(r['机型/料号'])}`, + meta: `根因 ${s(r['根因类别'])}:${s(r['根因描述'])}`, + value: `相似度 ${pct1(r['相似度'])}`, badge: s(r['缺陷码']), + tone: typeof r['相似度'] === 'number' && r['相似度'] > QAP_CALIBER.duplicateGuardThreshold ? 'danger' : 'warning', + }), + }, + { + key: 'DS-12', dataset: 'DS-12', name: '激光焊 DOE 试验', short: 'DOE', color: '#4ade80', + desc: 'L9 正交试验:四参数九组合各 50 件,用焊瘤率与未焊透率筛出推荐组合(试验 5)。', + row: r => { + const yield_ = calc.yieldRate(r as never); + return { + id: `T${s(r['试验号'])}`, title: `试验 ${s(r['试验号'])}`, + sub: `功率 ${s(r['激光功率(W)'])}W · 焊速 ${s(r['焊速(mm/s)'])} mm/s`, + meta: `气 ${s(r['保护气(L/min)'])} L/min · 离焦 ${s(r['离焦量(mm)'])} mm`, + value: `综合良率 ${pct1(yield_)}`, + badge: filled(r['标记']) ? s(r['标记']) : undefined, + tone: yield_ >= 0.9 ? 'success' : yield_ >= 0.85 ? 'warning' : 'danger', + }; + }, + }, + { + key: 'DS-13', dataset: 'DS-13', name: '新机型良率预测', short: '良率预测', color: '#8b5cf6', + desc: '新机型投产前的良率预估:靠相似机型的实际良率与特征相似度外推,相似度不足(如新型导风罩)即拒绝预测。', + row: r => ({ + id: s(r['新机型/料号']), title: s(r['新机型/料号']), sub: `相似 ${s(r['相似机型'])}`, + meta: s(r['建议动作']), + value: `预测 ${s(r['预测良率区间'])}`, badge: `相似度 ${pct1(r['特征相似度'])}`, + tone: typeof r['特征相似度'] === 'number' && r['特征相似度'] >= QAP_CALIBER.duplicateGuardThreshold ? 'success' : 'warning', + }), + }, + { + key: 'DS-14', dataset: 'DS-14', name: '工序负荷与线平衡', short: '线平衡', color: '#2dd4bf', + desc: '月需求 12,000 件(22 工作日 × 2 班)拆到每道工序,负荷率一算就知道哪里是瓶颈、该怎么调配。', + row: r => ({ + id: s(r['工序']), title: s(r['工序']), sub: s(r['工位/设备']), + meta: `在制 ${num(r['在制品(件)'])} 件 · 建议 ${s(r['建议'])}`, + value: `负荷率 ${pct1(calc.loadRate(r as never))}`, badge: s(r['预警']), + tone: s(r['预警']).includes('瓶颈') ? 'danger' : 'warning', + }), + }, + { + key: 'DS-15', dataset: 'DS-15', name: '三日预警池快照', short: '预警池', color: '#f472b6', + desc: '近三日质量异常的在场清单,滞留天数一超 3 天就自动升级;缺陷码与料号分别回指缺陷字典与产品主数据。', + row: r => ({ + id: s(r['异常单号']), title: s(r['异常单号']), sub: `${s(r['料号'])} · ${s(r['缺陷'])}`, + meta: `${s(r['发生日'])} 发生 · ${s(r['升级级别'])} · ${s(r['责任人'])}`, + value: `滞留 ${calc.dwellDays(r as never)} 天`, badge: s(r['当前状态']), + tone: s(r['当前状态']) === '已闭环' ? 'success' + : s(r['当前状态']) === '滞留未动' || s(r['当前状态']) === '待处理' ? 'danger' : 'warning', + }), + }, + { + key: 'DS-16', dataset: 'DS-16', name: '参数漂移监控记录', short: '参数漂移', color: '#22c55e', + desc: '把采集到的实测均值与标准值逐日比:偏移超允差 60% 或呈单调趋势即预警,标准值非数值(如「按图」)时留空。', + row: r => { + const drift = calc.driftRate(r as never); + const st = s(r['状态']); + return { + id: `${s(r['日期'])}-${s(r['设备'])}-${s(r['参数'])}`, + title: `${s(r['日期'])} · ${s(r['设备'])}`, sub: `${s(r['参数'])}(${s(r['单位'])})`, + meta: `实测 ${num(r['实测均值'])} · 允差 ${s(r['允许偏差'])} · 同步缺陷率 ${pct1(r['同步缺陷率'])}`, + value: `偏移 ${drift === null ? '—' : pct1(drift)}`, badge: st, + tone: st === '正常' ? 'success' : st.startsWith('预警') || st.startsWith('超差') ? 'danger' : 'warning', + }; + }, + }, +]; + +/* ── 对象 Object:实例列表懒算一次就缓存,视图多处取 length 不必反复重建 ── */ +const instCache = new Map(); + +export const objects: OntObject[] = DEFS.map(d => { + const cat = findCat(d.dataset); + return { + id: d.key as string, + name: d.name, + en: d.key as string, + short: d.short, + desc: d.desc, + source: cat ? `原表页签 ${cat.sheets.join(' + ')}` : QAP_SOURCE, + color: d.color, + attrs: deriveAttrs(R(d.key)), + instances: () => { + let v = instCache.get(d.key); + if (!v) { v = R(d.key).map(d.row); instCache.set(d.key, v); } + return v; + }, + }; +}); + +export const objectById = (id: string): OntObject | undefined => objects.find(o => o.id === id); + +/** 下钻到某条实例时,外环要摊开的「字段 = 值」列表 */ +export interface OntField { name: string; value: string } + +/** + * 按「表 key + 实例 id」取回该实例所在原始行的全部列值。 + * 实例 id 有的是复合(设备编号-参数名)、有的带前缀(S3 / T5 / #1-…), + * 所以不反解 id 格式,而是把每行过一遍 row 呈现器、取 id 相符的那行,再按列顺序拉出字段。 + */ +export function instanceFields(tableKey: string, instId: string): OntField[] { + const def = DEFS.find(d => (d.key as string) === tableKey); + if (!def) return []; + const row = R(def.key).find(r => def.row(r).id === instId); + if (!row) return []; + return Object.keys(row).map(col => ({ name: col, value: s(row[col]) })); +} + +/* ── 关系 Relation:连接键与实例数全按真实列值交集现算 ──────────────── */ +const ds03CodeSet = new Set(R('DS-03').map(r => s(r['缺陷码']))); +const dsItemSet = new Set(R('DS-01').map(r => s(r['料号']))); +const ds03DefectNames = R('DS-03').map(r => s(r['缺陷名称'])); +const pointKeySet = new Set(R('DS-04').map(r => `${s(r['设备编号'])}|${s(r['参数名'])}`)); +const wsSet = new Set(R('DS-02').map(r => s(r['工位']))); +const modelSet = new Set(R('DS-01').map(r => s(r['机型']))); +const opSet = new Set(R('DS-02').map(r => s(r['工序']))); +/** DS-01 的焊接作业方式带「(设备)/(手工)」后缀,去掉才与 DS-02 的工序名对得上 */ +const weldOps = [...new Set(R('DS-01').map(r => s(r['焊接作业方式']).replace(/(.*?)/g, '')).filter(x => x && x !== '无'))]; + +export const relations: OntRelation[] = [ + { + id: 'qr-03-11', from: 'DS-03', to: 'DS-11', name: '双库同码', cardinality: '1:N', + key: '缺陷码', + desc: '8D 知识库的每条记录都挂在缺陷字典的一个码上,两库因此能互相点开;本批 6 个 8D 全部可归码。', + count: () => overlap(R('DS-11'), '缺陷码', R('DS-03'), '缺陷码'), + }, + { + id: 'qr-03-15', from: 'DS-03', to: 'DS-15', name: '异常归码', cardinality: 'N:1', + key: '缺陷码', + desc: '预警池里的异常单按缺陷码归一到字典,才能统计「哪类缺陷反复出现」。', + count: () => overlap(R('DS-15'), '缺陷码', R('DS-03'), '缺陷码'), + }, + { + id: 'qr-03-05', from: 'DS-03', to: 'DS-05', name: '点检覆盖', cardinality: '1:N', + key: '风险项内嵌 (缺陷码)', + desc: '风险点检表的「风险项」列把缺陷码写在括号里,6 条风险点全部对得上字典,没有孤儿风险项。', + count: () => R('DS-05').filter(r => codesIn(r['风险项']).some(c => ds03CodeSet.has(c))).length, + }, + { + id: 'qr-03-06b', from: 'DS-03', to: 'DS-06b', name: 'SOP 提示', cardinality: '1:N', + key: '常见错误内嵌 (缺陷码)', + desc: 'SOP 的「常见错误」栏回指历史缺陷码,5 个步骤里有 3 步带着明确的问题指向。', + count: () => R('DS-06b').filter(r => codesIn(r['常见错误(来自历史缺陷)']).length > 0).length, + }, + { + id: 'qr-11-05', from: 'DS-11', to: 'DS-05', name: '8D 溯源', cardinality: 'N:M', + key: '8D编号 ⊂ 来源引用', + desc: '点检表的「来源引用」按 8D 编号回指知识库,6 条风险点全部对得上历史 8D(部分同时引客户投诉或 PFMEA 条目),风险项因此有据可查。', + count: () => new Set(R('DS-05').flatMap(r => d8sIn(r['来源引用']))).size, + }, + { + id: 'qr-04-16', from: 'DS-04', to: 'DS-16', name: '监控落地', cardinality: '1:N', + key: '设备编号 + 参数名', + desc: '采集点台账定义「该采什么」,漂移监控记录是「采到了什么」;8 条记录里 7 条能落回台账,模具冲次累计尚未登记。', + count: () => R('DS-16').filter(r => pointKeySet.has(`${s(r['设备']).split(' ')[0]}|${s(r['参数'])}`)).length, + }, + { + id: 'qr-02-14', from: 'DS-02', to: 'DS-14', name: '负荷测算', cardinality: '1:N', + key: '工位', + desc: '线平衡按工位取产能与节拍,7 道工序参与测算(压铆/攻牙不在本次月需求链路上)。', + count: () => R('DS-14').filter(r => wsSet.has(s(r['工位/设备']).split('/')[0].trim())).length, + }, + { + id: 'qr-01-06a', from: 'DS-01', to: 'DS-06a', name: '夹具适配', cardinality: '1:N', + key: '适用料号', + desc: '验收标准卡按料号挂夹具,2 个专用夹具有明确料号,1 个组装治具标为通用 2U 系列。', + count: () => new Set(R('DS-06a').map(r => s(r['适用料号'])).filter(x => dsItemSet.has(x))).size, + }, + { + id: 'qr-01-09', from: 'DS-01', to: 'DS-09', name: '特征归集', cardinality: '1:N', + key: '料号', + desc: '缺陷矩阵的 6 个特征维度各以一个典型料号代表,全部出自产品主数据。', + count: () => R('DS-09').filter(r => dsItemSet.has(s(r['典型料号']))).length, + }, + { + id: 'qr-01-15', from: 'DS-01', to: 'DS-15', name: '在制异常', cardinality: '1:N', + key: '料号', + desc: '预警池 6 张异常单的料号都能回到产品主数据,异常因此能顺藤摸到工艺与结构特征。', + count: () => R('DS-15').filter(r => dsItemSet.has(s(r['料号']))).length, + }, + { + id: 'qr-01-13', from: 'DS-01', to: 'DS-13', name: '机型相似', cardinality: '1:N', + key: '机型 ⊂ 相似机型', + desc: '良率预测靠「相似机型」外推,3 条能找到 SRV-2U-620 上的同族件,新型导风罩则无相似件。', + count: () => R('DS-13').filter(r => [...modelSet].some(m => s(r['相似机型']).includes(m))).length, + }, + { + id: 'qr-03-09', from: 'DS-03', to: 'DS-09', name: '缺陷维度对齐', cardinality: '1:N', + key: '缺陷名称 ⊂ 矩阵列头', + desc: '矩阵的四个列头(焊瘤 / 未焊透 / 搭接不良 / 焊接变形)都能在缺陷字典里找到对应条目,口径可对齐。', + count: () => ['焊瘤', '未焊透', '搭接不良', '焊接变形'] + .filter(d => ds03DefectNames.some(nm => nm.includes(d))).length, + }, + { + id: 'qr-01-02', from: 'DS-01', to: 'DS-02', name: '工艺承接', cardinality: '1:N', + key: '焊接作业方式 ↔ 工序', + desc: '产品主数据的焊接作业方式落到具体工位上;3 种焊接方式在台账里有对应工序,点焊与不涉焊接则无。', + count: () => weldOps.filter(x => opSet.has(x)).length, + }, +]; + +/* ── 规则 Rule:阈值全部照原表口径,命中数按真实数据现算 ───────────────── */ +const dwellOverdue = R('DS-15').filter(r => calc.dwellDays(r as never) > 3); +const driftWarn = R('DS-16').filter(r => /^(预警|超差)/.test(s(r['状态']))); +const dup8d = R('DS-11').filter(r => typeof r['相似度'] === 'number' && r['相似度'] > QAP_CALIBER.duplicateGuardThreshold); +const aliasTodo = R('DS-03').filter(r => filled(r['历史别名(待归并)'])); +const confirmTodo = R('DS-07').filter(r => s(r['状态']) === '待 QE 确认'); +const specialCodes = R('DS-03').filter(r => s(r['特殊特性']) === '是'); +const openWarn = R('DS-15').filter(r => s(r['当前状态']) !== '已闭环'); +const bottleneck = R('DS-14').filter(r => s(r['预警']) === '最大瓶颈'); +/** 基准件 SRV2U-BASE-01 在矩阵里被明确标为对比基准,别的特征维度以它为准绳 */ +const baseFeature = R('DS-09').find(r => s(r['典型料号']) === 'SRV2U-BASE-01')!; +const baseRate = calc.defectRate(baseFeature as never); +const overBaseFeature = R('DS-09').filter(r => calc.defectRate(r as never) > baseRate); + +export const rules: OntRule[] = [ + { + id: 'qr-dwell', name: '预警滞留升级', severity: 'warning', on: '三日预警池快照', + tables: ['DS-15'], + expr: '快照日 − 发生日 > 3 天 → 自动升级至管理层', + desc: '滞留天数按基准日 2026-10-16 减发生日算;超过 3 天的必须升级,不能压在车间里等。', + hits: () => ({ + n: dwellOverdue.length, unit: `单(>3 天)`, + targets: dwellOverdue.map(r => s(r['异常单号'])), + }), + }, + { + id: 'qr-drift', name: '参数漂移预警', severity: 'error', on: '参数漂移监控记录', + tables: ['DS-16'], + expr: '偏移率 > 允差 60% 或呈单调下行趋势', + desc: '激光功率连续五日记录一路下行(1196→1128),偏移率已到 −6%,同步缺陷率同步抬升,属典型的设备劣化前兆。', + hits: () => ({ + n: driftWarn.length, unit: '条记录', + targets: driftWarn.map(r => `${s(r['设备'])} · ${s(r['参数'])}`), + }), + }, + { + id: 'qr-dup8d', name: '相似 8D 重复拦截', severity: 'error', on: '8D 知识库', + tables: ['DS-11'], + expr: `相似度 > ${QAP_CALIBER.duplicateGuardThreshold}`, + desc: '相似度按缺陷码 + 特征码 + 现象描述三重算;超过阈值即判定为重复问题,要求直接复用已验证的对策而不是重开一张 8D。', + hits: () => ({ + n: dup8d.length, unit: '条 8D', + targets: dup8d.map(r => s(r['8D编号'])), + }), + }, + { + id: 'qr-alias', name: '缺陷别名待归并', severity: 'warning', on: '缺陷代码字典', + tables: ['DS-03'], + expr: '历史别名(待归并)非空', + desc: '每个缺陷码都挂着 2~3 个车间叫法(焊凸 / 焊包 / 焊渣堆积…)。归并前,同一现象在异常、8D、检验三处可能各记各的,统计必然失真。', + hits: () => ({ + n: aliasTodo.length, unit: '个缺陷码', + targets: aliasTodo.map(r => s(r['缺陷码'])), + }), + }, + { + id: 'qr-confirm', name: '检验标准待确认', severity: 'warning', on: '检验标准与遗漏提示', + tables: ['DS-07'], + expr: "状态 = '待 QE 确认'", + desc: 'AI 提示列已经点出标准缺口(焊接变形平面度、外观限度样板),但状态列未生效,检验现场暂时无法照此执行。', + hits: () => ({ + n: confirmTodo.length, unit: '项标准', + targets: confirmTodo.map(r => s(r['特征/项目'])), + }), + }, + { + id: 'qr-hifeature', name: '特征不良高于基准件', severity: 'warning', on: '结构特征 × 缺陷关联矩阵', + tables: ['DS-09'], + expr: `综合不良率 > 基准件 SRV2U-BASE-01 的 ${(baseRate * 100).toFixed(1)}%`, + desc: '以结构最稳的普通平板拼焊件为基准线,综合不良率高于它的特征维度都应进重点管控清单。', + hits: () => ({ + n: overBaseFeature.length, unit: '个特征维度', + targets: overBaseFeature.map(r => s(r['结构特征维度'])), + }), + }, + { + id: 'qr-special', name: '特殊特性强制全检', severity: 'error', on: '缺陷代码字典', + tables: ['DS-03'], + expr: "特殊特性 = '是'", + desc: '标为特殊特性的缺陷不可抽检遗漏:它们要么致命、要么会被客户端检出,必须带检测手段与频次落到检验标准上。', + hits: () => ({ + n: specialCodes.length, unit: '个缺陷码', + targets: specialCodes.map(r => s(r['缺陷码'])), + }), + }, + { + id: 'qr-open', name: '异常未闭环', severity: 'warning', on: '三日预警池快照', + tables: ['DS-15'], + expr: "当前状态 ≠ '已闭环'", + desc: '未闭环的异常单是当前的在制风险敞口,其中「滞留未动」的最危险——没人认领才滞留。', + hits: () => ({ + n: openWarn.length, unit: '单未闭环', + targets: openWarn.map(r => s(r['异常单号'])), + }), + }, + { + id: 'qr-bottleneck', name: '最大瓶颈定位', severity: 'error', on: '工序负荷与线平衡', + tables: ['DS-14'], + expr: "预警 = '最大瓶颈'(负荷率最高)", + desc: '负荷率 = 需求节拍 ÷ 实际产能。激光焊负荷率 3.5 倍,是全线最粗的瓶颈,其余工序的排产改善都要绕开它才有效。', + hits: () => ({ + n: bottleneck.length, unit: '道工序', + targets: bottleneck.map(r => s(r['工序'])), + }), + }, + { + id: 'qr-verify', name: '预测良率回验', severity: 'info', on: '新机型良率预测', + tables: ['DS-13'], + expr: '预测良率区间 ⊇ 试制实测良率', + desc: '预测只有和试制实测对上才有价值。当前只做了投产前评估,尚未投产,因此这条规则无法执行。', + blocked: true, + gap: '缺 SRV-2U-720 四条料号的试制实测良率与首批缺陷分布;本批数据集是「投产前评估」,没有实测列可回验。', + hits: () => ({ n: 0, unit: '无法计算(缺试制实测)', targets: [] }), + }, +]; + +/* ── 动作 Action:全部来自原表的「处理动作 / 建议 / 对策」列 ─────────── */ +const targetsOf = (id: string) => rules.find(r => r.id === id)!.hits().targets; +const pick = (rows: Row[], key: string, value: string) => rows.filter(r => s(r[key]) === value).map(r => s(r['工序'])); + +export const actions: OntAction[] = [ + { + id: 'qa-maintenance', name: '派设备保养工单', en: 'create_maintenance_order', + object: '参数漂移监控记录', type: 'workflow', tables: ['DS-16'], + trigger: '规则「参数漂移预警」命中(超允差 60%)', + desc: '照 DS-16 的处理动作:生成保养工单并通知 ME;本例的根因是光路镜片污染,清洁后功率恢复 1204W。', + targets: () => targetsOf('qr-drift'), + }, + { + id: 'qa-escalate', name: '超期异常升级', en: 'escalate_overdue_warning', + object: '三日预警池快照', type: 'alert', tables: ['DS-15'], + trigger: '规则「预警滞留升级」命中', + desc: '滞留超 3 天的异常单置顶看板并升级至管理层,避免「没人认领」的滞留件拖成批量风险。', + targets: () => targetsOf('qr-dwell'), + }, + { + id: 'qa-third-shift', name: '开第 3 班 / 部分外协', en: 'add_third_shift', + object: '工序负荷与线平衡', type: 'workflow', tables: ['DS-14'], + trigger: "负荷率 > 1(预警 = '超负荷')", + desc: 'DS-14 对超负荷工序给出的建议:开第 3 班或把部分产能外协,先保住节点。', + targets: () => pick(R('DS-14'), '预警', '超负荷'), + }, + { + id: 'qa-bending-machine', name: '增折弯机 + 1 人', en: 'add_bending_machine', + object: '工序负荷与线平衡', type: 'workflow', tables: ['DS-14'], + trigger: "预警 = '严重瓶颈'(折弯)", + desc: 'DS-14 判断折弯加设备是 ROI 最优的一笔投入:需求节拍 273 对实际产能 165,缺口最紧、投资最小。', + targets: () => pick(R('DS-14'), '预警', '严重瓶颈'), + }, + { + id: 'qa-switch-laser', name: '手工氩弧焊切激光焊', en: 'switch_to_laser', + object: '手工与设备焊接方式对比', type: 'workflow', tables: ['DS-10'], + trigger: '手工氩弧焊超负荷且良率垫底', + desc: 'DS-10 的差异结论:设备化可提升一次良率 14~20 个百分点,先替良率最低、负荷又满的手工氩弧焊。', + targets: () => ['手工氩弧焊'], + }, + { + id: 'qa-alias-merge', name: '缺陷别名归并', en: 'merge_defect_alias', + object: '缺陷代码字典', type: 'workflow', tables: ['DS-03'], + trigger: '规则「缺陷别名待归并」命中', + desc: '把「焊凸 / 焊包 / 焊渣堆积」这类历史叫法归一到一个缺陷码,归并后异常统计与 8D 检索才可比。', + targets: () => targetsOf('qr-alias'), + }, + { + id: 'qa-standard-fill', name: '补齐检验标准', en: 'complete_inspection_standard', + object: '检验标准与遗漏提示', type: 'workflow', tables: ['DS-07'], + trigger: '规则「检验标准待确认」命中', + desc: 'QE 确认 AI 提示的两处缺口(平面度、外观限度样板),确认后检验标准才生效。', + targets: () => targetsOf('qr-confirm'), + }, + { + id: 'qa-8d-search', name: '检索相似 8D', en: 'search_similar_8d', + object: '8D 知识库(结构化)', type: 'query', tables: ['DS-11'], + trigger: '规则「相似 8D 重复拦截」命中', + desc: '按缺陷码 + 特征码 + 现象描述三重相似度检索历史 8D,命中即复用已验证对策,不再重复分析。', + targets: () => targetsOf('qr-dup8d'), + }, + { + id: 'qa-doe-best', name: '筛 DOE 推荐组合', en: 'pick_doe_combination', + object: '激光焊 DOE 试验', type: 'report', tables: ['DS-12'], + trigger: 'L9 九组合里带标记的试验', + desc: '从九组正交试验里挑出推荐组合与需规避组合:试验 5(1200W / 气 15 / 焊速 38)综合良率最高。', + targets: () => R('DS-12').filter(r => filled(r['标记'])).map(r => `试验 ${s(r['试验号'])} · ${s(r['标记'])}`), + }, + { + id: 'qa-first-cmm', name: '首件 CMM 确认', en: 'first_article_cmm', + object: '检验标准与遗漏提示', type: 'query', tables: ['DS-15', 'DS-07'], + trigger: '孔位 / 垫块类缺陷(DF-NCT-01)在预警池出现', + desc: '照 8D-2026-022 的对策:垫块装夹偏位导致的孔位 NG,靠增加防错垫块 + 首件 CMM 确认闭环。', + targets: () => R('DS-15').filter(r => s(r['缺陷码']) === 'DF-NCT-01').map(r => s(r['异常单号'])), + }, + { + id: 'qa-sop-backfill', name: 'SOP 常见错误回填', en: 'backfill_sop_pitfalls', + object: 'SOP 节选', type: 'report', tables: ['DS-06b'], + trigger: '历史缺陷码在 SOP 步骤里出现', + desc: '把带缺陷码的步骤抽成现场提醒卡贴到工位,让 SOP 的「常见错误」栏真正发挥作用。', + targets: () => R('DS-06b').filter(r => codesIn(r['常见错误(来自历史缺陷)']).length > 0) + .map(r => `步骤 ${s(r['步骤'])}`), + }, +]; + +/* ── 图谱:节点=对象,连线=关系 ───────────────────────────────────── */ +export const graphNodes = (): { id: string; label: string; count: number; color: string }[] => + objects.map(o => ({ id: o.id, label: o.short, count: o.instances().length, color: o.color })); + +export const graphEdges = (): { id: string; source: string; target: string; label: string }[] => + relations.map(r => ({ id: r.id, source: r.from, target: r.to, label: r.name })); diff --git a/src/modules/tfamd-oee/data/qap/ds01_product_process_master.json b/src/modules/tfamd-oee/data/qap/ds01_product_process_master.json new file mode 100644 index 0000000..3ad51ca --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds01_product_process_master.json @@ -0,0 +1,90 @@ +[ + { + "料号": "SRV2U-BASE-01", + "品名": "机箱底座", + "机型": "SRV-2U-620", + "材质": "SECC", + "板厚(mm)": 1, + "结构特征": "双侧折弯+R角×4+6处焊点", + "工序数": 9, + "焊接作业方式": "激光焊(设备)", + "年用量(件)": 12000 + }, + { + "料号": "SRV2U-TOP-01", + "品名": "机箱上盖", + "机型": "SRV-2U-620", + "材质": "SECC", + "板厚(mm)": 0.8, + "结构特征": "四边折弯+散热孔阵列+2处焊点", + "工序数": 8, + "焊接作业方式": "点焊(设备)", + "年用量(件)": 12000 + }, + { + "料号": "SRV2U-FANW-01", + "品名": "风扇墙", + "机型": "SRV-2U-620", + "材质": "SGCC", + "板厚(mm)": 1, + "结构特征": "网孔阵列+加强筋×3+12处焊点", + "工序数": 9, + "焊接作业方式": "手工氩弧焊(手工)", + "年用量(件)": 12000 + }, + { + "料号": "SRV2U-PSUCAGE-01", + "品名": "电源仓", + "机型": "SRV-2U-620", + "材质": "SECC", + "板厚(mm)": 1.2, + "结构特征": "盒体折弯+压铆螺母×12+8处焊点", + "工序数": 10, + "焊接作业方式": "激光焊(设备)", + "年用量(件)": 12000 + }, + { + "料号": "SRV2U-HDDCAGE-01", + "品名": "硬盘架", + "机型": "SRV-2U-620", + "材质": "SGCC", + "板厚(mm)": 1, + "结构特征": "多级折弯×5+抽拉导轨面+16处焊点", + "工序数": 10, + "焊接作业方式": "机器人焊(设备)", + "年用量(件)": 24000 + }, + { + "料号": "SRV1U-TOP-01", + "品名": "1U 上盖", + "机型": "SRV-1U-430", + "材质": "SECC", + "板厚(mm)": 0.8, + "结构特征": "平板+四边折弯+网孔", + "工序数": 7, + "焊接作业方式": "无(不涉焊接)", + "年用量(件)": 8000 + }, + { + "料号": "SRV4U-BEAM-01", + "品名": "存储横梁", + "机型": "SRV-4U-840", + "材质": "AL5052", + "板厚(mm)": 1.5, + "结构特征": "长条折弯+定位槽×4", + "工序数": 6, + "焊接作业方式": "无(不涉焊接)", + "年用量(件)": 6000 + }, + { + "料号": "RACK-POST-01", + "品名": "机柜立柱", + "机型": "RACK-42U", + "材质": "SUS304", + "板厚(mm)": 1.2, + "结构特征": "多孔阵列+折边+螺孔×36", + "工序数": 5, + "焊接作业方式": "点焊(设备)", + "年用量(件)": 3000 + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds02_station_equipment_tooling.json b/src/modules/tfamd-oee/data/qap/ds02_station_equipment_tooling.json new file mode 100644 index 0000000..87cc1db --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds02_station_equipment_tooling.json @@ -0,0 +1,82 @@ +[ + { + "工位": "WS-01", + "工序": "NCT 冲孔", + "设备": "通快 TruPunch 5000", + "工装/夹具": "通用模架", + "人机配比": "0.5 人", + "标准工时(min/件)": 2.4, + "班次产能(件)": 220, + "瓶颈": "否" + }, + { + "工位": "WS-02", + "工序": "折弯", + "设备": "AMADA HG-1003", + "工装/夹具": "折弯模 R0.5/88°", + "人机配比": "1 人", + "标准工时(min/件)": 2.8, + "班次产能(件)": 165, + "瓶颈": "否" + }, + { + "工位": "WS-03", + "工序": "压铆/攻牙", + "设备": "压铆机 PB-12", + "工装/夹具": "压铆工装", + "人机配比": "1 人", + "标准工时(min/件)": 1.6, + "班次产能(件)": 280, + "瓶颈": "否" + }, + { + "工位": "WS-04", + "工序": "激光焊", + "设备": "IPG 光纤激光焊机", + "工装/夹具": "焊接夹具 WJ-2U-BASE", + "人机配比": "1 人", + "标准工时(min/件)": 6.2, + "班次产能(件)": 78, + "瓶颈": "是" + }, + { + "工位": "WS-05", + "工序": "机器人焊", + "设备": "发那科 ARC Mate", + "工装/夹具": "焊接夹具 WJ-HDD-01", + "人机配比": "0.5 人", + "标准工时(min/件)": 7, + "班次产能(件)": 62, + "瓶颈": "是" + }, + { + "工位": "WS-06", + "工序": "手工氩弧焊", + "设备": "松下 TIG 焊机", + "工装/夹具": "焊接夹具 WJ-FANW-01", + "人机配比": "1 人", + "标准工时(min/件)": 10, + "班次产能(件)": 44, + "瓶颈": "是-最大瓶颈" + }, + { + "工位": "WS-07", + "工序": "打磨/补焊", + "设备": "角磨机 + 补焊台", + "工装/夹具": "打磨治具", + "人机配比": "1 人", + "标准工时(min/件)": 3.3, + "班次产能(件)": 140, + "瓶颈": "否" + }, + { + "工位": "WS-08", + "工序": "组装", + "设备": "装配线 A", + "工装/夹具": "定位治具 ZJ-01", + "人机配比": "2 人", + "标准工时(min/件)": 4.8, + "班次产能(件)": 96, + "瓶颈": "否" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds03_defect_code_dict.json b/src/modules/tfamd-oee/data/qap/ds03_defect_code_dict.json new file mode 100644 index 0000000..7c65a26 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds03_defect_code_dict.json @@ -0,0 +1,123 @@ +[ + { + "缺陷码": "DF-WLD-01", + "缺陷名称": "焊瘤", + "历史别名(待归并)": "焊凸 / 焊包 / 焊渣堆积", + "所属工序": "焊接", + "检测方式": "目视 + 卡尺", + "严重度": "严重", + "特殊特性": "否", + "近3月占比": 0.124, + "历史8D数": 23 + }, + { + "缺陷码": "DF-WLD-02", + "缺陷名称": "未焊透", + "历史别名(待归并)": "虚焊 / 焊不透 / 根部未熔合", + "所属工序": "焊接", + "检测方式": "目视 + 破坏性抽检", + "严重度": "致命", + "特殊特性": "是", + "近3月占比": 0.061, + "历史8D数": 17 + }, + { + "缺陷码": "DF-WLD-03", + "缺陷名称": "搭接不良/错位", + "历史别名(待归并)": "搭接 / 错边 / 对不齐", + "所属工序": "焊接", + "检测方式": "目视 + 塞尺", + "严重度": "严重", + "特殊特性": "是", + "近3月占比": 0.053, + "历史8D数": 11 + }, + { + "缺陷码": "DF-WLD-04", + "缺陷名称": "虚焊/漏焊", + "历史别名(待归并)": "没焊 / 少焊点", + "所属工序": "焊接", + "检测方式": "目视 + 拉力扭力抽检", + "严重度": "致命", + "特殊特性": "是", + "近3月占比": 0.032, + "历史8D数": 14 + }, + { + "缺陷码": "DF-WLD-05", + "缺陷名称": "焊接变形", + "历史别名(待归并)": "变形 / 翘曲 / 平面度超差", + "所属工序": "焊接", + "检测方式": "大理石平台 + 塞尺 / 三坐标", + "严重度": "严重", + "特殊特性": "是", + "近3月占比": 0.046, + "历史8D数": 8 + }, + { + "缺陷码": "DF-BND-01", + "缺陷名称": "折弯角度NG", + "历史别名(待归并)": "角度超差 / 折歪", + "所属工序": "折弯", + "检测方式": "角度尺 / 投影仪", + "严重度": "严重", + "特殊特性": "是", + "近3月占比": 0.087, + "历史8D数": 9 + }, + { + "缺陷码": "DF-BND-02", + "缺陷名称": "折弯回弹超差", + "历史别名(待归并)": "回弹 / 弹开", + "所属工序": "折弯", + "检测方式": "角度尺", + "严重度": "一般", + "特殊特性": "否", + "近3月占比": 0.045, + "历史8D数": 5 + }, + { + "缺陷码": "DF-NCT-01", + "缺陷名称": "孔位/垫块NG", + "历史别名(待归并)": "孔偏 / 垫块不对", + "所属工序": "NCT冲压", + "检测方式": "三次元 CMM", + "严重度": "严重", + "特殊特性": "是", + "近3月占比": 0.039, + "历史8D数": 7 + }, + { + "缺陷码": "DF-NCT-02", + "缺陷名称": "毛刺超标", + "历史别名(待归并)": "毛边 / 刀纹", + "所属工序": "NCT冲压", + "检测方式": "目视 + 手感", + "严重度": "一般", + "特殊特性": "否", + "近3月占比": 0.058, + "历史8D数": 4 + }, + { + "缺陷码": "DF-SRF-01", + "缺陷名称": "外观划伤", + "历史别名(待归并)": "划痕 / 擦伤 / 拉丝痕", + "所属工序": "组装/搬运", + "检测方式": "目视(标准样板比对)", + "严重度": "一般", + "特殊特性": "否", + "近3月占比": 0.092, + "历史8D数": 12 + }, + { + "缺陷码": "DF-ASM-01", + "缺陷名称": "漏装/错装", + "历史别名(待归并)": "少件 / 装错件", + "所属工序": "组装", + "检测方式": "目视 + 扭矩校验", + "严重度": "致命", + "特殊特性": "是", + "近3月占比": 0.021, + "历史8D数": 6 + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds04_param_collection_points.json b/src/modules/tfamd-oee/data/qap/ds04_param_collection_points.json new file mode 100644 index 0000000..24812e5 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds04_param_collection_points.json @@ -0,0 +1,82 @@ +[ + { + "设备编号": "EQ-WLD-01", + "设备名称": "IPG 光纤激光焊机", + "参数名": "激光功率", + "单位": "W", + "标准值": 1200, + "允许区间": "1140 ~ 1260", + "采集频率": "每件", + "采集方式": "PLC 自动" + }, + { + "设备编号": "EQ-WLD-01", + "设备名称": "IPG 光纤激光焊机", + "参数名": "保护气流量", + "单位": "L/min", + "标准值": 15, + "允许区间": "13 ~ 17", + "采集频率": "每件", + "采集方式": "PLC 自动" + }, + { + "设备编号": "EQ-WLD-01", + "设备名称": "IPG 光纤激光焊机", + "参数名": "焊接速度", + "单位": "mm/s", + "标准值": 35, + "允许区间": "32 ~ 38", + "采集频率": "每件", + "采集方式": "PLC 自动" + }, + { + "设备编号": "EQ-WLD-01", + "设备名称": "IPG 光纤激光焊机", + "参数名": "离焦量", + "单位": "mm", + "标准值": 0, + "允许区间": "-0.5 ~ +0.5", + "采集频率": "每件", + "采集方式": "人工录入 + 卡控" + }, + { + "设备编号": "EQ-RBT-01", + "设备名称": "发那科弧焊机器人", + "参数名": "焊接电流", + "单位": "A", + "标准值": 145, + "允许区间": "135 ~ 155", + "采集频率": "每件", + "采集方式": "PLC 自动" + }, + { + "设备编号": "EQ-BND-02", + "设备名称": "AMADA 折弯机", + "参数名": "折弯压力", + "单位": "kN", + "标准值": 320, + "允许区间": "300 ~ 340", + "采集频率": "每批", + "采集方式": "PLC 自动" + }, + { + "设备编号": "EQ-BND-02", + "设备名称": "AMADA 折弯机", + "参数名": "后挡料定位", + "单位": "mm", + "标准值": "按图", + "允许区间": "±0.10", + "采集频率": "每批", + "采集方式": "人工录入" + }, + { + "设备编号": "EQ-ENV-01", + "设备名称": "车间环境(焊接区)", + "参数名": "温度 / 相对湿度", + "单位": "℃ / %RH", + "标准值": "23 / 50", + "允许区间": "18~28 / 40~65", + "采集频率": "每小时", + "采集方式": "传感器自动" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds05_risk_checklist_welding.json b/src/modules/tfamd-oee/data/qap/ds05_risk_checklist_welding.json new file mode 100644 index 0000000..96b2d79 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds05_risk_checklist_welding.json @@ -0,0 +1,68 @@ +[ + { + "序号": 1, + "工序": "焊接", + "风险项": "焊瘤(DF-WLD-01)", + "来源引用": "8D-2026-031 / PFMEA-焊接-07", + "历史发生次数": 9, + "严重度": "严重", + "控制措施": "激光功率锁定 1200±60W,保护气 15±2 L/min", + "检验方法/频次": "目视 + 卡尺,首件 + 每 10 件", + "责任人": "ME" + }, + { + "序号": 2, + "工序": "焊接", + "风险项": "未焊透(DF-WLD-02)", + "来源引用": "8D-2026-018 / 客户 A 投诉", + "历史发生次数": 5, + "严重度": "致命", + "控制措施": "焊速 ≤38 mm/s;搭接量 ≥0.8×板厚;首件破坏性验证", + "检验方法/频次": "破坏性抽检,首件 + 每批 1 件", + "责任人": "QE" + }, + { + "序号": 3, + "工序": "焊接", + "风险项": "搭接不良/错位(DF-WLD-03)", + "来源引用": "8D-2026-025", + "历史发生次数": 4, + "严重度": "严重", + "控制措施": "使用焊接夹具 WJ-FANW-01,定位销磨损 ≤0.05mm", + "检验方法/频次": "塞尺 0.10mm 通规,每 20 件", + "责任人": "IE" + }, + { + "序号": 4, + "工序": "焊接", + "风险项": "焊接变形(DF-WLD-05)", + "来源引用": "8D-2026-009", + "历史发生次数": 3, + "严重度": "严重", + "控制措施": "分段对称跳焊,控制热输入;焊后自然冷却 30min 再检", + "检验方法/频次": "平面度检测(平板 + 塞尺),每批", + "责任人": "PE" + }, + { + "序号": 5, + "工序": "折弯(来件)", + "风险项": "折弯角度NG(DF-BND-01)", + "来源引用": "8D-2026-022", + "历史发生次数": 3, + "严重度": "严重", + "控制措施": "上道工序角度全检,超差件不得流入焊接", + "检验方法/频次": "角度尺,100% 上料前确认", + "责任人": "IE" + }, + { + "序号": 6, + "工序": "组装", + "风险项": "网孔毛刺超标(DF-NCT-02)", + "来源引用": "8D-2026-014", + "历史发生次数": 2, + "严重度": "一般", + "控制措施": "模具刃口寿命计数 ≤8 万冲次强制刃磨", + "检验方法/频次": "目视 + 手感,每 2h 抽 3 件", + "责任人": "ME" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds06a_fixture_acceptance.json b/src/modules/tfamd-oee/data/qap/ds06a_fixture_acceptance.json new file mode 100644 index 0000000..8e7889d --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds06a_fixture_acceptance.json @@ -0,0 +1,62 @@ +[ + { + "夹具编号": "WJ-2U-BASE", + "名称": "底座焊接夹具", + "适用料号": "SRV2U-BASE-01", + "验收项": "定位销磨损", + "判定标准": "直径公差 ±0.02mm", + "更换/复检阈值": "磨损 >0.05mm 更换", + "点检频次": "每班", + "责任": "ME" + }, + { + "夹具编号": "WJ-2U-BASE", + "名称": "底座焊接夹具", + "适用料号": "SRV2U-BASE-01", + "验收项": "夹紧力", + "判定标准": "≥800 N(压力表读数)", + "更换/复检阈值": "<700 N 检修", + "点检频次": "每周", + "责任": "ME" + }, + { + "夹具编号": "WJ-2U-BASE", + "名称": "底座焊接夹具", + "适用料号": "SRV2U-BASE-01", + "验收项": "定位面平面度", + "判定标准": "≤0.10 mm", + "更换/复检阈值": ">0.15mm 修复或报废", + "点检频次": "每月", + "责任": "IE" + }, + { + "夹具编号": "WJ-FANW-01", + "名称": "风扇墙焊接夹具", + "适用料号": "SRV2U-FANW-01", + "验收项": "搭接间隙控制", + "判定标准": "≤0.10 mm", + "更换/复检阈值": ">0.15mm 调整垫片", + "点检频次": "每班", + "责任": "IE" + }, + { + "夹具编号": "WJ-FANW-01", + "名称": "风扇墙焊接夹具", + "适用料号": "SRV2U-FANW-01", + "验收项": "防错标记(方向销)", + "判定标准": "不可反转装入", + "更换/复检阈值": "防错失效立即停用", + "点检频次": "每班", + "责任": "IE" + }, + { + "夹具编号": "ZJ-01", + "名称": "组装定位治具", + "适用料号": "通用 2U 系列", + "验收项": "导向柱垂直度", + "判定标准": "≤0.05 mm/100mm", + "更换/复检阈值": ">0.10 更换", + "点检频次": "每周", + "责任": "ME" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds06b_sop_excerpt.json b/src/modules/tfamd-oee/data/qap/ds06b_sop_excerpt.json new file mode 100644 index 0000000..9606c6c --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds06b_sop_excerpt.json @@ -0,0 +1,42 @@ +[ + { + "步骤": 1, + "作业内容": "来件确认:核对料号与批次,检查上道折弯角度", + "关键参数": "角度 88°±0.5°", + "工具/工装": "角度尺", + "自检项": "贴合无缝隙", + "常见错误(来自历史缺陷)": "折弯超差件直接流入焊接 → 焊接错位(DF-WLD-03)" + }, + { + "步骤": 2, + "作业内容": "装夹:装入夹具 WJ-FANW-01,确认防错销到位", + "关键参数": "搭接间隙 ≤0.10mm", + "工具/工装": "塞尺", + "自检项": "防错销不可反转", + "常见错误(来自历史缺陷)": "漏装防错销 → 反向装夹 → 批量错位" + }, + { + "步骤": 3, + "作业内容": "参数调用:扫描料号二维码自动调取参数卡", + "关键参数": "功率 1200W / 气 15L/min / 焊速 35mm/s", + "工具/工装": "设备 HMI", + "自检项": "参数与参数卡一致", + "常见错误(来自历史缺陷)": "人工手调参数忘记复位 → 焊瘤(DF-WLD-01)" + }, + { + "步骤": 4, + "作业内容": "分段对称焊接(先内后外,跳焊)", + "关键参数": "单段长度 ≤60mm,间隔 30mm", + "工具/工装": "激光焊机", + "自检项": "无烧穿、无变形", + "常见错误(来自历史缺陷)": "连续单向焊接 → 热输入集中 → 焊接变形(DF-WLD-05)" + }, + { + "步骤": 5, + "作业内容": "焊后自检 + 补充打磨", + "关键参数": "焊瘤高度 ≤0.3mm", + "工具/工装": "卡尺 / 角磨机", + "自检项": "无未焊透(目视根部)", + "常见错误(来自历史缺陷)": "焊瘤未打磨直接流入组装 → 装配干涉" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds07_inspection_standard.json b/src/modules/tfamd-oee/data/qap/ds07_inspection_standard.json new file mode 100644 index 0000000..b22eed6 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds07_inspection_standard.json @@ -0,0 +1,72 @@ +[ + { + "特征/项目": "外形尺寸", + "检验项目": "长 × 宽 × 高", + "依据": "图纸 GD&T / 客户规格", + "抽样": "AQL 0.65", + "量具": "卷尺 / 卡尺", + "频次": "每批 5 件", + "AI 提示": "—", + "状态": "已覆盖" + }, + { + "特征/项目": "孔位", + "检验项目": "关键安装孔位置度", + "依据": "图纸特殊特性 ◎", + "抽样": "首件 100% + 抽检", + "量具": "三次元 CMM", + "频次": "首件 + 每批 2 件", + "AI 提示": "—", + "状态": "已覆盖" + }, + { + "特征/项目": "焊缝", + "检验项目": "未焊透 / 焊缝外观", + "依据": "焊接工艺标准 WI-WLD-03", + "抽样": "破坏性抽检", + "量具": "目视 + 拉力计", + "频次": "每批 1 件", + "AI 提示": "—", + "状态": "已覆盖" + }, + { + "特征/项目": "焊接变形", + "检验项目": "底座平面度", + "依据": "—(原标准缺失)", + "抽样": "—", + "量具": "大理石平台 + 塞尺", + "频次": "每批 5 件", + "AI 提示": "建议新增:相似件 SRV2U-HDDCAGE-01 曾因平面度超差导致装配干涉(8D-2026-009)", + "状态": "待 QE 确认" + }, + { + "特征/项目": "压铆", + "检验项目": "压铆螺母扭矩/推出力", + "依据": "紧固件标准", + "抽样": "每批 3 件", + "量具": "扭力扳手 / 推出力计", + "频次": "每批 3 件", + "AI 提示": "—", + "状态": "已覆盖" + }, + { + "特征/项目": "表面", + "检验项目": "喷涂附着力 / 色差", + "依据": "客户外观规范", + "抽样": "AQL 1.0", + "量具": "百格刀 / 色卡", + "频次": "每批 3 件", + "AI 提示": "建议补充:同族料号近 3 月外观划伤占比 9.2%,建议增加外观限度样板比对", + "状态": "待 QE 确认" + }, + { + "特征/项目": "材料", + "检验项目": "材质 / 板厚证明", + "依据": "来料检验记录", + "抽样": "每批", + "量具": "千分尺 / 材质报告", + "频次": "每批", + "AI 提示": "—", + "状态": "已覆盖" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds08_recipe_matrix.json b/src/modules/tfamd-oee/data/qap/ds08_recipe_matrix.json new file mode 100644 index 0000000..7245fc0 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds08_recipe_matrix.json @@ -0,0 +1,52 @@ +[ + { + "工艺": "激光焊", + "材质/板厚": "SECC 1.0", + "焊接形式": "搭接", + "激光功率(W)/电流(A)": 1200, + "保护气(L/min)": 15, + "焊速(mm/s)": 35, + "离焦量(mm)": 0, + "关联缺陷提醒": "功率 >1260W 易焊瘤;焊速 >38 易未焊透" + }, + { + "工艺": "激光焊", + "材质/板厚": "SECC 1.2", + "焊接形式": "搭接", + "激光功率(W)/电流(A)": 1400, + "保护气(L/min)": 16, + "焊速(mm/s)": 32, + "离焦量(mm)": 0, + "关联缺陷提醒": "板厚增加需同步提升功率,否则未焊透" + }, + { + "工艺": "激光焊", + "材质/板厚": "SGCC 1.0", + "焊接形式": "角焊", + "激光功率(W)/电流(A)": 1300, + "保护气(L/min)": 18, + "焊速(mm/s)": 30, + "离焦量(mm)": -0.3, + "关联缺陷提醒": "镀层锌挥发,气量不足易气孔" + }, + { + "工艺": "激光焊", + "材质/板厚": "SUS304 1.2", + "焊接形式": "拼焊", + "激光功率(W)/电流(A)": 1500, + "保护气(L/min)": 20, + "焊速(mm/s)": 28, + "离焦量(mm)": 0, + "关联缺陷提醒": "不锈钢导热率低,注意焊接变形" + }, + { + "工艺": "机器人弧焊", + "材质/板厚": "SGCC 1.0", + "焊接形式": "角焊", + "激光功率(W)/电流(A)": 145, + "保护气(L/min)": 12, + "焊速(mm/s)": 6, + "离焦量(mm)": null, + "关联缺陷提醒": "电流 >155A 易咬边/烧穿" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds09_feature_defect_matrix.json b/src/modules/tfamd-oee/data/qap/ds09_feature_defect_matrix.json new file mode 100644 index 0000000..d9d622a --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds09_feature_defect_matrix.json @@ -0,0 +1,62 @@ +[ + { + "结构特征维度": "厚板搭接(≥1.2mm)", + "典型料号": "SRV2U-PSUCAGE-01", + "样本数": 1020, + "焊瘤": 0.082, + "未焊透": 0.096, + "搭接不良": 0.031, + "焊接变形": 0.024, + "结论": "最高风险:功率不足为主因" + }, + { + "结构特征维度": "密集焊点(≥12 点)", + "典型料号": "SRV2U-FANW-01", + "样本数": 1180, + "焊瘤": 0.141, + "未焊透": 0.042, + "搭接不良": 0.058, + "焊接变形": 0.069, + "结论": "最高风险:热输入集中" + }, + { + "结构特征维度": "长条形(>400mm)", + "典型料号": "SRV4U-BEAM-01", + "样本数": 540, + "焊瘤": 0.035, + "未焊透": 0.039, + "搭接不良": 0.044, + "焊接变形": 0.087, + "结论": "变形主导,需分段对称焊" + }, + { + "结构特征维度": "镀层板(SGCC)", + "典型料号": "SRV2U-HDDCAGE-01", + "样本数": 1260, + "焊瘤": 0.093, + "未焊透": 0.051, + "搭接不良": 0.028, + "焊接变形": 0.032, + "结论": "气孔 / 锌挥发相关" + }, + { + "结构特征维度": "薄板(≤0.8mm)", + "典型料号": "SRV1U-TOP-01", + "样本数": 620, + "焊瘤": 0.021, + "未焊透": 0.024, + "搭接不良": 0.056, + "焊接变形": 0.072, + "结论": "易烧穿,需降功率" + }, + { + "结构特征维度": "普通平板拼焊(基准)", + "典型料号": "SRV2U-BASE-01", + "样本数": 240, + "焊瘤": 0.047, + "未焊透": 0.04, + "搭接不良": 0.03, + "焊接变形": 0.021, + "结论": "相对稳定,作为对比基准" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds10_manual_vs_machine.json b/src/modules/tfamd-oee/data/qap/ds10_manual_vs_machine.json new file mode 100644 index 0000000..ee15e6a --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds10_manual_vs_machine.json @@ -0,0 +1,66 @@ +[ + { + "对比项": "一次良率", + "手工氩弧焊": 0.685, + "机器人弧焊": 0.823, + "激光焊(设备)": 0.889, + "单位": "%", + "差异结论": "设备化可提升 14~20 个百分点" + }, + { + "对比项": "焊瘤率(DF-WLD-01)", + "手工氩弧焊": 0.141, + "机器人弧焊": 0.074, + "激光焊(设备)": 0.038, + "单位": "%", + "差异结论": "差异显著(p<0.01)" + }, + { + "对比项": "未焊透率(DF-WLD-02)", + "手工氩弧焊": 0.086, + "机器人弧焊": 0.041, + "激光焊(设备)": 0.022, + "单位": "%", + "差异结论": "差异显著(p<0.01)" + }, + { + "对比项": "单件工时", + "手工氩弧焊": 11.5, + "机器人弧焊": 8.2, + "激光焊(设备)": 6.5, + "单位": "min", + "差异结论": "设备化省时 30~43%" + }, + { + "对比项": "返修/补焊工时", + "手工氩弧焊": 3.2, + "机器人弧焊": 1.5, + "激光焊(设备)": 0.6, + "单位": "min", + "差异结论": "返修成本差异同样显著" + }, + { + "对比项": "单件综合成本(含返修)", + "手工氩弧焊": 18.6, + "机器人弧焊": 12.4, + "激光焊(设备)": 9.8, + "单位": "元", + "差异结论": "手工单件成本高约 90%" + }, + { + "对比项": "换型时间", + "手工氩弧焊": 5, + "机器人弧焊": 25, + "激光焊(设备)": 15, + "单位": "min", + "差异结论": "手工柔性最好(小批量优势)" + }, + { + "对比项": "适用批量建议", + "手工氩弧焊": null, + "机器人弧焊": null, + "激光焊(设备)": null, + "单位": "件", + "差异结论": "手工 <50 件|机器人 50~500 件|激光 >500 件" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds11_8d_knowledge_base.json b/src/modules/tfamd-oee/data/qap/ds11_8d_knowledge_base.json new file mode 100644 index 0000000..3332e56 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds11_8d_knowledge_base.json @@ -0,0 +1,68 @@ +[ + { + "8D编号": "8D-2026-031", + "客户": "A 客户", + "机型/料号": "SRV-2U-620 / 底座", + "缺陷码": "DF-WLD-01", + "根因类别": "设备类", + "根因描述": "激光功率漂移 +120W 未复位", + "对策": "参数卡锁定 + 开机自检", + "验证结果": "有效(焊瘤 12.4%→3.8%)", + "相似度": 0.94 + }, + { + "8D编号": "8D-2026-018", + "客户": "A 客户", + "机型/料号": "SRV-2U-620 / 风扇墙", + "缺陷码": "DF-WLD-02", + "根因类别": "方法类", + "根因描述": "搭接量不足 0.6×板厚", + "对策": "夹具增加搭接限位 + 首件破坏性验证", + "验证结果": "有效(未焊透 6.1%→2.2%)", + "相似度": 0.88 + }, + { + "8D编号": "8D-2026-025", + "客户": "B 客户", + "机型/料号": "SRV-4U-840 / 横梁", + "缺陷码": "DF-WLD-03", + "根因类别": "工装类", + "根因描述": "定位销磨损 0.08mm", + "对策": "定位销寿命管理(≤0.05mm 更换)", + "验证结果": "有效", + "相似度": 0.91 + }, + { + "8D编号": "8D-2026-009", + "客户": "A 客户", + "机型/料号": "SRV-2U-620 / 硬盘架", + "缺陷码": "DF-WLD-05", + "根因类别": "方法类", + "根因描述": "连续单向焊接热输入集中", + "对策": "改分段对称跳焊,单段 ≤60mm", + "验证结果": "有效(变形 8.7%→2.4%)", + "相似度": 0.86 + }, + { + "8D编号": "8D-2026-014", + "客户": "B 客户", + "机型/料号": "SRV-1U-430 / 上盖", + "缺陷码": "DF-NCT-02", + "根因类别": "设备类", + "根因描述": "模具刃口超 12 万冲次未刃磨", + "对策": "刃口寿命计数 + 强制刃磨", + "验证结果": "部分有效", + "相似度": 0.72 + }, + { + "8D编号": "8D-2026-022", + "客户": "C 客户", + "机型/料号": "RACK-42U / 立柱", + "缺陷码": "DF-NCT-01", + "根因类别": "设备类", + "根因描述": "垫块装夹偏位", + "对策": "增加防错垫块 + 首件 CMM 确认", + "验证结果": "有效", + "相似度": 0.69 + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds12_laser_doe.json b/src/modules/tfamd-oee/data/qap/ds12_laser_doe.json new file mode 100644 index 0000000..88785df --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds12_laser_doe.json @@ -0,0 +1,92 @@ +[ + { + "试验号": 1, + "激光功率(W)": 1100, + "保护气(L/min)": 13, + "焊速(mm/s)": 32, + "离焦量(mm)": 0, + "焊瘤率": 0.06, + "未焊透率": 0.1, + "标记": null + }, + { + "试验号": 2, + "激光功率(W)": 1100, + "保护气(L/min)": 15, + "焊速(mm/s)": 35, + "离焦量(mm)": -0.5, + "焊瘤率": 0.04, + "未焊透率": 0.12, + "标记": null + }, + { + "试验号": 3, + "激光功率(W)": 1100, + "保护气(L/min)": 17, + "焊速(mm/s)": 38, + "离焦量(mm)": 0.5, + "焊瘤率": 0.02, + "未焊透率": 0.16, + "标记": null + }, + { + "试验号": 4, + "激光功率(W)": 1200, + "保护气(L/min)": 13, + "焊速(mm/s)": 35, + "离焦量(mm)": 0.5, + "焊瘤率": 0.08, + "未焊透率": 0.04, + "标记": null + }, + { + "试验号": 5, + "激光功率(W)": 1200, + "保护气(L/min)": 15, + "焊速(mm/s)": 38, + "离焦量(mm)": 0, + "焊瘤率": 0.04, + "未焊透率": 0.02, + "标记": "推荐组合" + }, + { + "试验号": 6, + "激光功率(W)": 1200, + "保护气(L/min)": 17, + "焊速(mm/s)": 32, + "离焦量(mm)": -0.5, + "焊瘤率": 0.06, + "未焊透率": 0.04, + "标记": null + }, + { + "试验号": 7, + "激光功率(W)": 1300, + "保护气(L/min)": 13, + "焊速(mm/s)": 38, + "离焦量(mm)": -0.5, + "焊瘤率": 0.14, + "未焊透率": 0.02, + "标记": "功率过高" + }, + { + "试验号": 8, + "激光功率(W)": 1300, + "保护气(L/min)": 15, + "焊速(mm/s)": 32, + "离焦量(mm)": 0.5, + "焊瘤率": 0.1, + "未焊透率": 0.02, + "标记": null + }, + { + "试验号": 9, + "激光功率(W)": 1300, + "保护气(L/min)": 17, + "焊速(mm/s)": 35, + "离焦量(mm)": 0, + "焊瘤率": 0.12, + "未焊透率": 0.02, + "标记": null + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds13_new_model_yield_prediction.json b/src/modules/tfamd-oee/data/qap/ds13_new_model_yield_prediction.json new file mode 100644 index 0000000..df54eba --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds13_new_model_yield_prediction.json @@ -0,0 +1,38 @@ +[ + { + "新机型/料号": "SRV-2U-720 / 底座", + "相似机型": "SRV-2U-620 / 底座", + "特征相似度": 0.91, + "相似机型实际良率": 0.862, + "预测良率区间": "84% ~ 89%", + "高概率缺陷(Top3)": "焊瘤 12.4% / 未焊透 6.1% / 尺寸NG 3.9%", + "建议动作": "沿用激光焊参数卡 + 首件破坏性验证" + }, + { + "新机型/料号": "SRV-2U-720 / 风扇墙", + "相似机型": "SRV-2U-620 / 风扇墙", + "特征相似度": 0.88, + "相似机型实际良率": 0.69, + "预测良率区间": "66% ~ 73%", + "高概率缺陷(Top3)": "焊瘤 14.1% / 变形 6.9% / 搭接不良 5.8%", + "建议动作": "重点风险:建议直接切换到激光焊工艺" + }, + { + "新机型/料号": "SRV-2U-720 / 硬盘架", + "相似机型": "SRV-2U-620 / 硬盘架", + "特征相似度": 0.93, + "相似机型实际良率": 0.885, + "预测良率区间": "87% ~ 91%", + "高概率缺陷(Top3)": "孔位NG 3.9% / 毛刺 5.8%", + "建议动作": "沿用现有控制计划,关注模具寿命" + }, + { + "新机型/料号": "SRV-2U-720 / 新型导风罩", + "相似机型": "无相似件", + "特征相似度": 0.55, + "相似机型实际良率": null, + "预测良率区间": "无法预测", + "高概率缺陷(Top3)": "新结构:薄壁 + 多筋,历史无同族件", + "建议动作": "列入试制验证清单:变形 / 回弹 / 焊接热影响" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds14_line_balance.json b/src/modules/tfamd-oee/data/qap/ds14_line_balance.json new file mode 100644 index 0000000..209e9bb --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds14_line_balance.json @@ -0,0 +1,65 @@ +[ + { + "工序": "NCT 冲孔", + "工位/设备": "WS-01 / 通快 TruPunch", + "需求节拍(件/班)": 273, + "实际产能(件/班)": 220, + "在制品(件)": 180, + "预警": "超负荷", + "建议": "开第 3 班或部分外协" + }, + { + "工序": "折弯", + "工位/设备": "WS-02 / AMADA HG-1003", + "需求节拍(件/班)": 273, + "实际产能(件/班)": 165, + "在制品(件)": 420, + "预警": "严重瓶颈", + "建议": "加 1 台折弯机 + 1 人(ROI 最优)" + }, + { + "工序": "激光焊", + "工位/设备": "WS-04 / IPG 激光焊机", + "需求节拍(件/班)": 273, + "实际产能(件/班)": 78, + "在制品(件)": 860, + "预警": "最大瓶颈", + "建议": "按 DS-10:从手工切激光焊 + 增 1 台" + }, + { + "工序": "机器人焊", + "工位/设备": "WS-05 / 发那科 ARC Mate", + "需求节拍(件/班)": 136, + "实际产能(件/班)": 62, + "在制品(件)": 310, + "预警": "超负荷", + "建议": "优化焊接程序节拍或增 1 台" + }, + { + "工序": "手工氩弧焊", + "工位/设备": "WS-06 / 松下 TIG", + "需求节拍(件/班)": 68, + "实际产能(件/班)": 44, + "在制品(件)": 150, + "预警": "超负荷", + "建议": "逐步由激光焊替代(良率更高)" + }, + { + "工序": "打磨/补焊", + "工位/设备": "WS-07 / 角磨机", + "需求节拍(件/班)": 273, + "实际产能(件/班)": 140, + "在制品(件)": 260, + "预警": "超负荷", + "建议": "减少补焊量 = 从源头提升焊接良率" + }, + { + "工序": "组装", + "工位/设备": "WS-08 / 装配线 A", + "需求节拍(件/班)": 273, + "实际产能(件/班)": 96, + "在制品(件)": 520, + "预警": "超负荷", + "建议": "增加 1 条装配线" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds15_warning_pool_snapshot.json b/src/modules/tfamd-oee/data/qap/ds15_warning_pool_snapshot.json new file mode 100644 index 0000000..5da54b4 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds15_warning_pool_snapshot.json @@ -0,0 +1,68 @@ +[ + { + "异常单号": "AB-2026-1042", + "料号": "SRV2U-FANW-01", + "缺陷": "未焊透", + "缺陷码": "DF-WLD-02", + "严重度": "致命", + "发生日": "2026-10-16", + "当前状态": "待处理", + "升级级别": "已即时通知车间主任", + "责任人": "QE 张" + }, + { + "异常单号": "AB-2026-1038", + "料号": "SRV2U-BASE-01", + "缺陷": "焊接变形(平面度超差)", + "缺陷码": "DF-WLD-05", + "严重度": "严重", + "发生日": "2026-10-15", + "当前状态": "分析中", + "升级级别": "正常", + "责任人": "PE 李" + }, + { + "异常单号": "AB-2026-1031", + "料号": "SRV2U-HDDCAGE-01", + "缺陷": "焊瘤", + "缺陷码": "DF-WLD-01", + "严重度": "严重", + "发生日": "2026-10-13", + "当前状态": "措施未验证", + "升级级别": "升至厂长(看板置顶)", + "责任人": "ME 王" + }, + { + "异常单号": "AB-2026-1027", + "料号": "SRV2U-PSUCAGE-01", + "缺陷": "尺寸NG", + "缺陷码": "DF-NCT-01", + "严重度": "严重", + "发生日": "2026-10-11", + "当前状态": "对策执行中", + "升级级别": "升至厂长(超期 2 天)", + "责任人": "IE 陈" + }, + { + "异常单号": "AB-2026-1019", + "料号": "SRV1U-TOP-01", + "缺陷": "外观划伤", + "缺陷码": "DF-SRF-01", + "严重度": "一般", + "发生日": "2026-10-09", + "当前状态": "滞留未动", + "升级级别": "已升级至管理层", + "责任人": "IE 陈" + }, + { + "异常单号": "AB-2026-1012", + "料号": "RACK-POST-01", + "缺陷": "孔位NG", + "缺陷码": "DF-NCT-01", + "严重度": "严重", + "发生日": "2026-10-05", + "当前状态": "已闭环", + "升级级别": "闭环(超期 8 天)", + "责任人": "QE 张" + } +] diff --git a/src/modules/tfamd-oee/data/qap/ds16_param_drift.json b/src/modules/tfamd-oee/data/qap/ds16_param_drift.json new file mode 100644 index 0000000..619b575 --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/ds16_param_drift.json @@ -0,0 +1,98 @@ +[ + { + "日期": "2026-10-10", + "设备": "EQ-WLD-01 激光焊机", + "参数": "激光功率", + "单位": "W", + "标准值": 1200, + "实测均值": 1196, + "允许偏差": "±5%", + "同步缺陷率": 0.042, + "状态": "正常", + "处理动作": "—" + }, + { + "日期": "2026-10-12", + "设备": "EQ-WLD-01 激光焊机", + "参数": "激光功率", + "单位": "W", + "标准值": 1200, + "实测均值": 1189, + "允许偏差": "±5%", + "同步缺陷率": 0.046, + "状态": "正常", + "处理动作": "—" + }, + { + "日期": "2026-10-14", + "设备": "EQ-WLD-01 激光焊机", + "参数": "激光功率", + "单位": "W", + "标准值": 1200, + "实测均值": 1172, + "允许偏差": "±5%", + "同步缺陷率": 0.061, + "状态": "注意(趋势下行)", + "处理动作": "加密监控频次至每小时" + }, + { + "日期": "2026-10-15", + "设备": "EQ-WLD-01 激光焊机", + "参数": "激光功率", + "单位": "W", + "标准值": 1200, + "实测均值": 1152, + "允许偏差": "±5%", + "同步缺陷率": 0.093, + "状态": "预警(超允差60%)", + "处理动作": "生成保养工单并通知 ME" + }, + { + "日期": "2026-10-16", + "设备": "EQ-WLD-01 激光焊机", + "参数": "激光功率", + "单位": "W", + "标准值": 1200, + "实测均值": 1128, + "允许偏差": "±5%", + "同步缺陷率": 0.138, + "状态": "超差(已出允差)", + "处理动作": "停机校验:光路镜片污染,清洁后恢复 1204W" + }, + { + "日期": "2026-10-16", + "设备": "EQ-BND-02 折弯机", + "参数": "后挡料定位", + "单位": "mm", + "标准值": "按图", + "实测均值": 0.14, + "允许偏差": "±0.10mm", + "同步缺陷率": 0.031, + "状态": "预警", + "处理动作": "校正丝杆并重新校准零点" + }, + { + "日期": "2026-10-16", + "设备": "EQ-RBT-01 弧焊机器人", + "参数": "焊接电流", + "单位": "A", + "标准值": 145, + "实测均值": 146, + "允许偏差": "±7%", + "同步缺陷率": 0.034, + "状态": "正常", + "处理动作": "—" + }, + { + "日期": "2026-10-16", + "设备": "EQ-NCT-01 NCT冲床", + "参数": "模具冲次累计", + "单位": "冲次", + "标准值": 80000, + "实测均值": 76400, + "允许偏差": "寿命上限", + "同步缺陷率": 0.058, + "状态": "临近寿命", + "处理动作": "排产空档安排刃磨(剩余 3,600 冲次)" + } +] diff --git a/src/modules/tfamd-oee/data/qap/index.ts b/src/modules/tfamd-oee/data/qap/index.ts new file mode 100644 index 0000000..367134b --- /dev/null +++ b/src/modules/tfamd-oee/data/qap/index.ts @@ -0,0 +1,275 @@ +/** + * 和信精密 · 品质异常预防 —— 前端内置的数据集底座(15 张源表 + 2 张拆分表,不落后端库)。 + * + * 来源:source-data/品质异常预防工作台Demo.xlsx(16 组数据集 · 4 个场景 · 16 个用例), + * 由 scripts/xlsx-to-qap-json.py 逐页签转出,**数值不做任何改写**。 + * + * 两条口径约定(照原表的写法来,不自己另立一套): + * 1. 计算方法列不落盘。原表备注里写明「XX 为计算列」的那几列(理论产能/产能达成率/综合不良率/ + * 综合良率/负荷率/滞留天数/偏移率)在转 JSON 时已剔除,统一由本文件的 `calc` 现算, + * 避免"表里是值、代码里是另一套算法"两处口径打架。 + * 2. 比率类字段原表存的是小数(如 0.685 = 68.5%、0.124 = 12.4%),单位列写 '%'。 + * 展示层要乘 100,别直接当百分数贴。 + * + * 四角色 × 四场景是一个整齐的 4×4:PE 拿每场景的第 1 个用例,IE 第 2 个,QE 第 3 个,ME 第 4 个 + * (见 ROLE_DATASETS),所以质量流程看板里 PE/IE/QE/ME 四段各自的"数据依据"就是这一行四个数据集。 + */ +import ds01 from './ds01_product_process_master.json'; +import ds02 from './ds02_station_equipment_tooling.json'; +import ds03 from './ds03_defect_code_dict.json'; +import ds04 from './ds04_param_collection_points.json'; +import ds05 from './ds05_risk_checklist_welding.json'; +import ds06a from './ds06a_fixture_acceptance.json'; +import ds06b from './ds06b_sop_excerpt.json'; +import ds07 from './ds07_inspection_standard.json'; +import ds08 from './ds08_recipe_matrix.json'; +import ds09 from './ds09_feature_defect_matrix.json'; +import ds10 from './ds10_manual_vs_machine.json'; +import ds11 from './ds11_8d_knowledge_base.json'; +import ds12 from './ds12_laser_doe.json'; +import ds13 from './ds13_new_model_yield_prediction.json'; +import ds14 from './ds14_line_balance.json'; +import ds15 from './ds15_warning_pool_snapshot.json'; +import ds16 from './ds16_param_drift.json'; + +/** 四个质量角色,与 lib/qualityFlow.ts 的 QRoleKey 同值 */ +export type QapRole = 'PE' | 'IE' | 'QE' | 'ME'; + +/* ── DS-01 产品-工艺-特征主数据(特征码维度:材质 × 结构特征 × 工艺方法)── */ +export interface ProductProcessMaster { + 料号: string; 品名: string; 机型: string; 材质: string; '板厚(mm)': number; + 结构特征: string; 工序数: number; 焊接作业方式: string; '年用量(件)': number; +} + +/* ── DS-02 工位-设备-工装台账(单班 8h=480min)── */ +export interface StationEquipmentTooling { + 工位: string; 工序: string; 设备: string; '工装/夹具': string; 人机配比: string; + '标准工时(min/件)': number; '班次产能(件)': number; 瓶颈: string; +} + +/* ── DS-03 缺陷代码字典(全链路统一语言)── */ +export interface DefectCodeDict { + 缺陷码: string; 缺陷名称: string; '历史别名(待归并)': string; 所属工序: string; + 检测方式: string; 严重度: string; 特殊特性: string; 近3月占比: number; 历史8D数: number; +} + +/* ── DS-04 设备参数采集点台账 ── */ +export interface ParamCollectionPoint { + 设备编号: string; 设备名称: string; 参数名: string; 单位: string; + 标准值: string; 允许区间: string; 采集频率: string; 采集方式: string; +} + +/* ── DS-05 风险点检表-焊接工序 ── */ +export interface RiskChecklistItem { + 序号: number; 工序: string; 风险项: string; 来源引用: string; 历史发生次数: number; + 严重度: string; 控制措施: string; '检验方法/频次': string; 责任人: string; +} + +/* ── DS-06a 夹具验收标准卡 ── */ +export interface FixtureAcceptance { + 夹具编号: string; 名称: string; 适用料号: string; 验收项: string; + 判定标准: string; '更换/复检阈值': string; 点检频次: string; 责任: string; +} + +/* ── DS-06b SOP 节选 ── */ +export interface SopStep { + 步骤: number; 作业内容: string; 关键参数: string; '工具/工装': string; + 自检项: string; '常见错误(来自历史缺陷)': string; +} + +/* ── DS-07 检验标准与 AI 遗漏提示 ── */ +export interface InspectionStandard { + '特征/项目': string; 检验项目: string; 依据: string; 抽样: string; 量具: string; + 频次: string; 'AI 提示': string; 状态: string; +} + +/* ── DS-08 参数卡矩阵(Recipe)── */ +export interface RecipeMatrix { + 工艺: string; '材质/板厚': string; 焊接形式: string; + '激光功率(W)/电流(A)': number; '保护气(L/min)': number; '焊速(mm/s)': number; + '离焦量(mm)': number | null; 关联缺陷提醒: string; +} + +/* ── DS-09 结构特征 × 缺陷类型关联矩阵 ── */ +export interface FeatureDefectMatrix { + 结构特征维度: string; 典型料号: string; 样本数: number; + 焊瘤: number; 未焊透: number; 搭接不良: number; 焊接变形: number; 结论: string; +} + +/* ── DS-10 手工与设备焊接方式对比 ── */ +export interface ManualVsMachine { + 对比项: string; 手工氩弧焊: number | null; 机器人弧焊: number | null; + '激光焊(设备)': number | null; 单位: string; 差异结论: string; +} + +/* ── DS-11 8D 知识库(结构化)── */ +export interface EightDRecord { + '8D编号': string; 客户: string; '机型/料号': string; 缺陷码: string; 根因类别: string; + 根因描述: string; 对策: string; 验证结果: string; 相似度: number; +} + +/* ── DS-12 激光焊 DOE 试验结果(L9 正交)── */ +export interface LaserDoeRun { + 试验号: number; '激光功率(W)': number; '保护气(L/min)': number; '焊速(mm/s)': number; + '离焦量(mm)': number; 焊瘤率: number; 未焊透率: number; 标记: string | null; +} + +/* ── DS-13 新机型良率预测 ── */ +export interface YieldPrediction { + '新机型/料号': string; 相似机型: string; 特征相似度: number; + 相似机型实际良率: number | null; 预测良率区间: string; '高概率缺陷(Top3)': string; 建议动作: string; +} + +/* ── DS-14 工序负荷与线平衡 ── */ +export interface LineBalance { + 工序: string; '工位/设备': string; '需求节拍(件/班)': number; '实际产能(件/班)': number; + '在制品(件)': number; 预警: string; 建议: string; +} + +/* ── DS-15 三日预警池快照(基准日 2026-10-16)── */ +export interface WarningPoolItem { + 异常单号: string; 料号: string; 缺陷: string; 缺陷码: string; 严重度: string; + 发生日: string; 当前状态: string; 升级级别: string; 责任人: string; +} + +/* ── DS-16 关键参数漂移监控记录 ── */ +export interface ParamDrift { + 日期: string; 设备: string; 参数: string; 单位: string; 标准值: string; + 实测均值: number; 允许偏差: string; 同步缺陷率: number; 状态: string; 处理动作: string; +} + +/* ── 数据集目录(照 00-数据集总览 页签,含原表首行的口径说明)────────────── */ +export interface QapDatasetMeta { + id: string; + name: string; + useCase: string; + role: QapRole; + audit: string; + /** 原表首行那句口径说明,原样保留:算列公式、样本范围都写在这里 */ + caliber: string; + sheets: string[]; +} + +export const CATALOG: QapDatasetMeta[] = [ + { id: 'DS-01', name: '产品-工艺-特征主数据', useCase: 'UC-1.1', role: 'PE', audit: '料号、材质、板厚、结构特征、作业方式', caliber: '特征码维度:材质 × 结构特征 × 工艺方法', sheets: ['DS-01 产品工艺特征主数据'] }, + { id: 'DS-02', name: '工位-设备-工装台账', useCase: 'UC-1.2', role: 'IE', audit: '工位、设备、工装、人机配比、标准工时', caliber: '单班 8h(480min);理论产能 = ROUND(480÷标准工时);达成率 = 班次产能÷理论产能', sheets: ['DS-02 工位设备工装台账'] }, + { id: 'DS-03', name: '缺陷代码字典', useCase: 'UC-1.3', role: 'QE', audit: '缺陷码、别名、工序、严重度、特殊特性', caliber: '全链路统一语言:检验 / 异常 / 8D / 知识库共用同一缺陷码(别名列为待归并的历史叫法)', sheets: ['DS-03 缺陷代码字典'] }, + { id: 'DS-04', name: '设备参数采集点台账', useCase: 'UC-1.4', role: 'ME', audit: '设备、参数、标准值、允许区间、采集方式', caliber: '采集数据强制携带料号 + 批次号 + 时间戳,是 S3 关联分析与 S4 漂移预警的前置条件', sheets: ['DS-04 设备参数采集点台账'] }, + { id: 'DS-05', name: '风险点检表-焊接工序', useCase: 'UC-2.1', role: 'PE', audit: '风险项、来源引用、控制措施、检验频次', caliber: 'SRV2U-FANW-01 风扇墙 · 焊接工序(由历史 8D + PFMEA 自动推导并附来源引用)', sheets: ['DS-05 风险点检表-焊接'] }, + { id: 'DS-06', name: '夹具验收标准卡 + SOP 节选', useCase: 'UC-2.2', role: 'IE', audit: '夹具编号、验收项、判定标准、更换阈值 / 步骤、关键参数、自检项、常见错误', caliber: '补齐「工装夹具无验收标准」缺口;SOP 的「常见错误」栏来自该工序历史缺陷 Top', sheets: ['DS-06a 夹具验收标准卡', 'DS-06b SOP节选'] }, + { id: 'DS-07', name: '检验标准与遗漏提示', useCase: 'UC-2.3', role: 'QE', audit: '检验项目、依据、抽样、AI 提示、状态', caliber: 'SRV2U-BASE-01 机箱底座;状态列由 QE 确认后生效', sheets: ['DS-07 检验标准与遗漏提示'] }, + { id: 'DS-08', name: '参数卡矩阵(Recipe)', useCase: 'UC-2.4', role: 'ME', audit: '材质板厚、焊接形式、功率、气量、焊速', caliber: '激光焊接与机器人弧焊;数值来源于 DOE 试验与最优批次反推', sheets: ['DS-08 参数卡矩阵'] }, + { id: 'DS-09', name: '结构特征 × 缺陷关联矩阵', useCase: 'UC-3.1', role: 'PE', audit: '特征维度、各缺陷率、综合不良率', caliber: '近 3 个月 4,860 批次化焊件;综合不良率 = 四类缺陷率之和(计算列)', sheets: ['DS-09 特征缺陷关联矩阵'] }, + { id: 'DS-10', name: '手工与设备焊接方式对比', useCase: 'UC-3.2', role: 'IE', audit: '对比项、三种作业方式、差异结论', caliber: '同料号 SRV2U-FANW-01、同批次板材对比(回答「手工/设备差异未量化」)', sheets: ['DS-10 手工与设备焊接对比'] }, + { id: 'DS-11', name: '8D 知识库(结构化)', useCase: 'UC-3.3', role: 'QE', audit: '8D 编号、客户、根因、对策、相似度', caliber: '相似度 = 缺陷码 + 特征码 + 现象描述 三重相似度;>0.85 触发重复问题拦截', sheets: ['DS-11 8D知识库'] }, + { id: 'DS-12', name: '激光焊 DOE 试验', useCase: 'UC-3.4', role: 'ME', audit: '四参数、焊瘤率、未焊透率、综合良率', caliber: 'L9 正交,SECC 1.0mm 搭接,每组合 50 件;综合良率 = 1 − 焊瘤率 − 未焊透率(受控试验仅统计两类目标缺陷)', sheets: ['DS-12 激光焊DOE试验'] }, + { id: 'DS-13', name: '新机型良率预测', useCase: 'UC-4.1', role: 'PE', audit: '相似度、实际良率、预测区间、建议', caliber: '新机型 SRV-2U-720 投产前评估(相似度 = 材质+板厚+结构特征+焊接方式 加权)', sheets: ['DS-13 新机型良率预测'] }, + { id: 'DS-14', name: '工序负荷与线平衡', useCase: 'UC-4.2', role: 'IE', audit: '需求节拍、实际产能、负荷率、建议', caliber: '订单 SRV-2U-620 月需求 12,000 件,22 工作日 × 2 班;负荷率 = 需求节拍 ÷ 实际产能(计算列)', sheets: ['DS-14 工序负荷与线平衡'] }, + { id: 'DS-15', name: '三日预警池快照', useCase: 'UC-4.3', role: 'QE', audit: '严重度、滞留天数、状态、升级级别', caliber: '基准日 2026-10-16;滞留天数 = 基准日 − 发生日(计算列,>3 天自动升级至管理层)', sheets: ['DS-15 三日预警池快照'] }, + { id: 'DS-16', name: '参数漂移监控记录', useCase: 'UC-4.4', role: 'ME', audit: '标准值、实测值、偏移率、同步缺陷率', caliber: '偏移率 =(实测均值 − 标准值)÷ 标准值(计算列,标准值非数值时留空);偏移超允差 60% 或呈单调趋势即预警', sheets: ['DS-16 参数漂移监控'] }, +]; + +/** 四角色的数据依据:每场景(UC-1~4)各取一个用例,正好 4 个数据集 */ +export const ROLE_DATASETS: Record = { + PE: ['DS-01', 'DS-05', 'DS-09', 'DS-13'], + IE: ['DS-02', 'DS-06', 'DS-10', 'DS-14'], + QE: ['DS-03', 'DS-07', 'DS-11', 'DS-15'], + ME: ['DS-04', 'DS-08', 'DS-12', 'DS-16'], +}; + +/** 四个场景(编号由用例号 UC-n.x 推出,原表未给场景名) */ +export const SCENARIOS = [ + { id: 'UC-1', label: '场景一 · 主数据与台账底座' }, + { id: 'UC-2', label: '场景二 · 标准与规程补齐' }, + { id: 'UC-3', label: '场景三 · 关联分析与试验验证' }, + { id: 'UC-4', label: '场景四 · 预测与预警' }, +] as const; + +export const allDatasets = (): QapDatasetMeta[] => CATALOG; +export const datasetsOfRole = (role: QapRole): QapDatasetMeta[] => + CATALOG.filter(d => d.role === role); +export const datasetById = (id: string): QapDatasetMeta | undefined => + CATALOG.find(d => d.id === id); +export const scenarioOf = (d: QapDatasetMeta): string => d.useCase.split('.')[0]; + +/** + * 表名 → 行数据。键取数据集编号,DS-06 的两张表用 'DS-06a'/'DS-06b', + * 供后续要按表整体渲染的场景(数据浏览器、明细下钻)统一取数。 + */ +export const TABLES = { + 'DS-01': ds01, 'DS-02': ds02, 'DS-03': ds03, 'DS-04': ds04, 'DS-05': ds05, + 'DS-06a': ds06a, 'DS-06b': ds06b, 'DS-07': ds07, 'DS-08': ds08, 'DS-09': ds09, + 'DS-10': ds10, 'DS-11': ds11, 'DS-12': ds12, 'DS-13': ds13, 'DS-14': ds14, + 'DS-15': ds15, 'DS-16': ds16, +} as const; + +export type QapTableKey = keyof typeof TABLES; + +/** DS-06 一个数据集两张表,目录里只登记一条,取数时两张都要给 */ +export const tablesOfDataset = (id: string): { key: QapTableKey; rows: readonly unknown[] }[] => + id === 'DS-06' + ? [{ key: 'DS-06a', rows: ds06a }, { key: 'DS-06b', rows: ds06b }] + : (Object.keys(TABLES).includes(id) ? [{ key: id as QapTableKey, rows: TABLES[id as QapTableKey] }] : []); + +export const allTables = () => ds01 && { ds01, ds02, ds03, ds04, ds05, ds06a, ds06b, ds07, ds08, ds09, ds10, ds11, ds12, ds13, ds14, ds15, ds16 }; + +/* ── 计算方法列:公式照原表首行写的来 ───────────────────────────────────── */ +const SINGLE_SHIFT_MIN = 480; +const WARNING_POOL_BASE_DATE = '2026-10-16'; + +const round = (v: number, digits: number) => { + const f = 10 ** digits; + return Math.round((v + Number.EPSILON) * f) / f; +}; + +/** 日期差(天):b − a,按自然日算,避免时区把 0 算成 1 */ +export const daysBetween = (a: string, b: string): number => + Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86400000); + +/** 数值化:'按图'、'—' 这类非数值口径返回 null(DS-04/DS-16 的标准值列就有) */ +export const num = (v: string | number | null | undefined): number | null => { + if (typeof v === 'number') return Number.isFinite(v) ? v : null; + if (typeof v !== 'string') return null; + const m = v.match(/-?\d+(\.\d+)?/); + return m ? Number(m[0]) : null; +}; + +export const calc = { + /** DS-02 理论产能 = ROUND(480 ÷ 标准工时) */ + theoryCapacity: (r: StationEquipmentTooling) => Math.round(SINGLE_SHIFT_MIN / r['标准工时(min/件)']), + /** DS-02 产能达成率 = 班次产能 ÷ 理论产能(分母取四舍五入后的值,与原表一致) */ + capacityRate: (r: StationEquipmentTooling) => r['班次产能(件)'] / Math.round(SINGLE_SHIFT_MIN / r['标准工时(min/件)']), + /** DS-09 综合不良率 = 四类缺陷率之和 */ + defectRate: (r: FeatureDefectMatrix) => round(r.焊瘤 + r.未焊透 + r.搭接不良 + r.焊接变形, 4), + /** DS-12 综合良率 = 1 − 焊瘤率 − 未焊透率 */ + yieldRate: (r: LaserDoeRun) => round(1 - r.焊瘤率 - r.未焊透率, 4), + /** DS-14 负荷率 = 需求节拍 ÷ 实际产能 */ + loadRate: (r: LineBalance) => r['需求节拍(件/班)'] / r['实际产能(件/班)'], + /** DS-15 滞留天数 = 基准日 − 发生日 */ + dwellDays: (r: WarningPoolItem) => daysBetween(r.发生日, WARNING_POOL_BASE_DATE), + /** DS-16 偏移率 =(实测均值 − 标准值)÷ 标准值;标准值非数值(如「按图」)返回 null */ + driftRate: (r: ParamDrift): number | null => { + const std = num(r.标准值); + if (std === null || std === 0) return null; + return (r.实测均值 - std) / std; + }, +}; + +/* ── 常用口径常量:原表首行里写死的,视图引用这里,不在组件里再抄一遍 ── */ +export const QAP_CALIBER = { + /** 单班可用分钟(DS-02) */ + singleShiftMinutes: SINGLE_SHIFT_MIN, + /** 三日预警池的基准日(DS-15) */ + warningPoolBaseDate: WARNING_POOL_BASE_DATE, + /** DS-09 样本总量(近 3 个月化焊件批次) */ + featureDefectSamples: 4860, + /** DS-14 月需求与班次(22 工作日 × 2 班) */ + monthlyDemand: 12000, + workDays: 22, + shifts: 2, + /** DS-11 相似度触发重复问题拦截的阈值 */ + duplicateGuardThreshold: 0.85, +} as const; + +/** 原始文件出处:改数据请改 source-data 里的 xlsx 再跑 scripts/xlsx-to-qap-json.py 重转 */ +export const QAP_SOURCE = 'source-data/品质异常预防工作台Demo.xlsx'; diff --git a/src/modules/tfamd-oee/data/sqlite.ts b/src/modules/tfamd-oee/data/sqlite.ts new file mode 100644 index 0000000..1e6e573 --- /dev/null +++ b/src/modules/tfamd-oee/data/sqlite.ts @@ -0,0 +1,235 @@ +import initSqlJs from 'sql.js'; +import type { Database } from 'sql.js'; +import { + oeeMetricNodes, oeeMetricLinks, oeeMetricTrends, trendPeriods, + METRIC_TREE_AS_OF, TREE_SCOPE_NOTE, TREE_TARGET_NOTE, TREE_WEIGHT_NOTE, +} from './oee/metricTree'; +import { agentStaffSeeds } from './oee/agents'; + +let db: Database | null = null; + +/* + * ══════════════════════════════════════════════════════════════════════ + * M5 · OEE 指标中台的内存 SQLite(原 IBP 经营指标种子已整体替换) + * ══════════════════════════════════════════════════════════════════════ + * 规划书 line 111:「保留初始化与看门狗机制,只换 schema 与种子」。 + * 本文件只负责三件事:建表、灌种子、提供只读查询。 + * + * ★ 数字来源纪律(防幻觉) + * - 指标节点/关系边/趋势 全部由 data/oee/metricTree.ts 从 L3 服务层现算, + * 这里不写死任何一个 OEE 数值,也不再用 hashCode/makeRng 合成曲线。 + * - 时间轴是**业务日**(3 个种子日),不是 12 个月。种子只有 3 天, + * 补到 12 期就是编数据;旧月轴仅留给"月度口径报告"页(ADR-03)。 + * - 智能体由 data/oee/agents.ts 的 registry 派生,未接入者统计一律 0。 + * + * ★ 已删除的 IBP 遗留(唯一消费方 lib/answers.ts 已同步删除) + * revenue_monthly / product_line / region_data / risk_matrix 四张表及其查询、 + * MONTHS / buildTrend / queryKPIs / trend_3m。OEE 平台不得出现"营业收入"。 + * + * ★ 为什么 locateFile 必须指回 /sql-wasm.wasm + * sql.js 浏览器构建会请求 sql-wasm-browser.wasm,而 public/ 下只放了 + * sql-wasm.wasm(两者字节一致)。未命中路径会被 SPA fallback 返回 index.html, + * 报 "expected magic word 00 61 73 6d, found 3c 21 64 6f"。 + */ + +/** + * 快照时刻:取种子最后一个业务日的 21:00Z,**确定性**而非 datetime('now')。 + * 原型每次刷新若时间戳都在变,血缘页就无法复核"这一版数字是什么时候算的"。 + */ +function snapshotAt(): string { + const periods = trendPeriods(); + return `${periods[periods.length - 1]}T21:00:00Z`; +} + +export async function initDatabase(): Promise { + if (db) return db; + const SQL = await initSqlJs({ locateFile: () => '/mod-assets/tfamd-oee/sql-wasm.wasm' }); + db = new SQL.Database(); + + db.run(` + CREATE TABLE metric_node ( + id INTEGER PRIMARY KEY, code TEXT UNIQUE NOT NULL, + name_zh TEXT NOT NULL, + parent_code TEXT NOT NULL, level INTEGER NOT NULL, dimension TEXT NOT NULL, + value REAL, target REAL, unit TEXT, frequency TEXT, + alert_threshold REAL, alert_level TEXT, polarity TEXT, weight REAL, + formula TEXT, owner TEXT, desc_zh TEXT, updated_at TEXT, gap TEXT + ); + CREATE TABLE metric_link ( + id INTEGER PRIMARY KEY, from_code TEXT NOT NULL, to_code TEXT NOT NULL, + relation TEXT NOT NULL, strength REAL NOT NULL + ); + CREATE TABLE metric_trend ( + id INTEGER PRIMARY KEY, code TEXT NOT NULL, period TEXT NOT NULL, + actual REAL, target REAL + ); + CREATE TABLE digital_staff ( + id INTEGER PRIMARY KEY, code TEXT NOT NULL, + name_zh TEXT, role_zh TEXT, + status TEXT, skill_zh TEXT, + tasks_today INTEGER, success_rate REAL, confidence REAL, load_pct REAL, + last_run TEXT, cur_zh TEXT, bound_metric TEXT + ); + `); + + seedMetricTables(db); + + const staff = agentStaffSeeds(); + const insStaff = db.prepare('INSERT INTO digital_staff VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)'); + staff.forEach((s, i) => insStaff.run([i + 1, ...s])); + insStaff.free(); + + return db; +} + +/** 灌指标三表(节点/边/趋势):全部由 metricTree 从 L3 服务层现算,不写死任何 OEE 数值。 */ +function seedMetricTables(database: Database): void { + const updatedAt = snapshotAt(); + const nodes = oeeMetricNodes(); + const links = oeeMetricLinks(); + const trends = oeeMetricTrends(); + const periods = trendPeriods(); + + const insNode = database.prepare(`INSERT INTO metric_node VALUES + (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`); + nodes.forEach((n, i) => insNode.run([i + 1, ...n, updatedAt])); + insNode.free(); + + const insLink = database.prepare('INSERT INTO metric_link VALUES (?,?,?,?,?)'); + links.forEach((l, i) => insLink.run([i + 1, ...l])); + insLink.free(); + + // 趋势的 target 取节点当期目标(计划档),period 用业务日而非月份 + // ★ G 缺口(null/NaN)绑定为 NULL:趋势表不存 NaN,读出时 valueAt 还原为 NaN → 「—」 + const targetOf = new Map(nodes.map((n) => [n[0], n[6]])); + const insTrend = database.prepare('INSERT INTO metric_trend VALUES (?,?,?,?,?)'); + let tid = 1; + Object.keys(trends).forEach((code) => { + const target = targetOf.get(code) ?? 0; + trends[code].forEach((v, i) => insTrend.run([tid++, code, periods[i], v != null && Number.isFinite(v) ? v : null, target])); + }); + insTrend.free(); +} + +/** + * 重灌指标三表:metricTree 全部从 oeeService 现算, + * 种子换了数字就跟着换——这里只负责删旧灌新,不做第二套计算。 + * digital_staff 是 registry 派生,不动。db 未初始化时 no-op。 + */ +export function reseedMetricStore(): void { + if (!db) return; + db.run('DELETE FROM metric_node; DELETE FROM metric_link; DELETE FROM metric_trend;'); + seedMetricTables(db); +} + +/* ── 查询层 ─────────────────────────────────────────────────────────────── */ + +function rows(sql: string): Record[] { + if (!db) return []; + const res = db.exec(sql); + if (!res.length) return []; + const { columns, values } = res[0]; + return values.map(row => { + const o: Record = {}; + columns.forEach((c, i) => { o[c] = row[i]; }); + return o; + }); +} + +export interface MetricNode { + id: number; code: string; name_zh: string; parent_code: string; + level: number; dimension: string; value: number; target: number; unit: string; + frequency: string; alert_threshold: number; alert_level: string; polarity: 'up' | 'down'; + weight: number; formula: string; owner: string; desc_zh: string; + updated_at: string; + /** G 缺口说明(无源因子):非空时 value=0 仅占位,UI 须渲染「—」+此说明 */ + gap?: string; + children?: MetricNode[]; + trend?: (number | null)[]; +} + +export interface MetricLink { id: number; from_code: string; to_code: string; relation: string; strength: number } +export interface DigitalStaff { + id: number; code: string; name_zh: string; role_zh: string; + status: 'working' | 'idle' | 'alert' | 'offline'; skill_zh: string; + tasks_today: number; success_rate: number; confidence: number; load_pct: number; + last_run: string; cur_zh: string; bound_metric: string; +} + +const esc = (s: string) => s.replace(/'/g, "''"); + +/** 全量节点索引(一次查询,前端自行组树/找边,避免递归 SQL) */ +export function queryMetricNodes(): MetricNode[] { + return rows('SELECT * FROM metric_node ORDER BY level, id') as unknown as MetricNode[]; +} + +/** 组装成树;顺带把逐业务日趋势挂到节点上(NULL=G 缺口,保留 null 不补值) */ +export function queryMetricTree(): MetricNode[] { + const nodes = queryMetricNodes(); + const trendMap = new Map(); + rows('SELECT code, actual FROM metric_trend ORDER BY code, period').forEach(r => { + const c = r.code as string; + if (!trendMap.has(c)) trendMap.set(c, []); + trendMap.get(c)!.push(r.actual as number | null); + }); + const byCode = new Map(); + nodes.forEach(n => { n.children = []; n.trend = trendMap.get(n.code) ?? []; byCode.set(n.code, n); }); + const roots: MetricNode[] = []; + nodes.forEach(n => { + if (n.parent_code && byCode.has(n.parent_code)) byCode.get(n.parent_code)!.children!.push(n); + else roots.push(n); + }); + return roots; +} + +export function queryMetricLinks(): MetricLink[] { + return rows('SELECT * FROM metric_link ORDER BY id') as unknown as MetricLink[]; +} + +/** 与某个指标直接相连的边(网络视图聚焦用) */ +export function queryMetricLinksOf(code: string): MetricLink[] { + const c = esc(code); + return rows(`SELECT * FROM metric_link WHERE from_code='${c}' OR to_code='${c}' ORDER BY id`) as unknown as MetricLink[]; +} + +export interface TrendPoint { period: string; actual: number; target: number } + +export function queryTrend(code: string): TrendPoint[] { + return rows(`SELECT period, actual, target FROM metric_trend WHERE code='${esc(code)}' ORDER BY period`) as unknown as TrendPoint[]; +} + +export function queryChildren(parentCode: string): MetricNode[] { + return rows(`SELECT * FROM metric_node WHERE parent_code='${esc(parentCode)}' ORDER BY id`) as unknown as MetricNode[]; +} + +export function queryDigitalStaff(): DigitalStaff[] { + return rows('SELECT * FROM digital_staff ORDER BY id') as unknown as DigitalStaff[]; +} + +/** 顶部告警条数:red 为紧急,yellow 为关注;total 与指标树节点数同口径 */ +export function queryAlertCounts() { + const r = rows(`SELECT + SUM(CASE WHEN alert_level='red' AND level>=2 THEN 1 ELSE 0 END) AS red, + SUM(CASE WHEN alert_level='yellow' AND level>=2 THEN 1 ELSE 0 END) AS yellow, + SUM(CASE WHEN alert_level='green' AND level>=2 THEN 1 ELSE 0 END) AS green, + COUNT(*) AS total FROM metric_node`); + return (r[0] ?? { red: 0, yellow: 0, green: 0, total: 0 }) as + { red: number; yellow: number; green: number; total: number }; +} + +/** + * 中台元信息:口径版本、快照时刻、期轴与三条口径说明。 + * "说明与对照"页与血缘页直接引用,避免各处各写一套解释。 + */ +export function metricStoreMeta() { + const periods = trendPeriods(); + return { + asOf: METRIC_TREE_AS_OF, + snapshotAt: snapshotAt(), + periods, + axis: 'day' as const, + scopeNote: TREE_SCOPE_NOTE, + targetNote: TREE_TARGET_NOTE, + weightNote: TREE_WEIGHT_NOTE, + }; +} diff --git a/src/modules/tfamd-oee/hooks/useAgentChat.ts b/src/modules/tfamd-oee/hooks/useAgentChat.ts new file mode 100644 index 0000000..c5e71f7 --- /dev/null +++ b/src/modules/tfamd-oee/hooks/useAgentChat.ts @@ -0,0 +1,438 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import type { I18n } from '../i18n/locales'; +import { DISPATCH, buildAskAnswer } from '../lib/qualityAsk'; +import type { AskAnswer, IntentId } from '../lib/qualityAsk'; +import { buildConsultScript, qualityExperts } from '../lib/teams'; +import type { ConsultTurn, ExpertTeam } from '../lib/teams'; + +/** + * 底部对话区的会话状态机:问候 → 质量问答(思考轨逐条揭示 → 正文分段流出)→ 专家团会诊播报。 + * + * 状态放在 hook 里、由 MetricWorkspace 持有,而不是放在 AgentDock 组件内部: + * 本体/数据集/知识库/特征建模舞台会替换掉整块内容区,对话区组件随之卸载; + * 状态上提后「从回答卡点进舞台」再退回来,会话历史与进行中的推演都不会丢。 + * + * 流式分两段,刻意做得比"瞬间甩结果"慢: + * A 段思考轨(解析问句 → 取数 → 套本体规则 → 跨表对照 → 定级与排序 → 出结论)逐条揭示; + * B 段正文先打字出结论,再按段亮出关键数字 / 明细表 / 依据与口径 / 建议动作 / 数据来源。 + * 期间输入区锁住,右下角给「跳过推演」,不想等的用户一键落到最终卡。 + */ + +export interface Msg { + id: number; + role: 'user' | 'ai'; + text: string; + /** 应答归属("由缺陷归因专家作答"这类一行小字) */ + staff?: string; + time: string; + /** 专家团会诊:发言者名 / 角色标签 / 发言类型 */ + name?: string; + tag?: string; + kind?: 'system' | 'member' | 'lead'; + /** 专家团结构化发言(成员卡 / 牵头结论卡的数据源) */ + turn?: ConsultTurn; + /** 单轮问答:规范回答卡(结论 / 关键数字 / 明细 / 依据 / 行动 / 来源) */ + answer?: AskAnswer; + /** 该回答的推演耗时(秒):流式结束后写回,卡头展示 */ + elapsed?: number; +} + +/** 正文段:结论恒占一段,其余按有没有内容追加;count 是该段要逐条亮出的条目数 */ +export type BodySectionKey = 'conclusion' | 'numbers' | 'table' | 'basis' | 'actions' | 'source'; + +export function sectionPlan(a: AskAnswer): { key: BodySectionKey; count: number }[] { + const plan: { key: BodySectionKey; count: number }[] = [{ key: 'conclusion', count: 1 }]; + if (a.metrics.length) plan.push({ key: 'numbers', count: a.metrics.length }); + if (a.table) plan.push({ key: 'table', count: a.table.rows.length }); + if (a.points.length) plan.push({ key: 'basis', count: a.points.length }); + if (a.actions.length) plan.push({ key: 'actions', count: a.actions.length }); + plan.push({ key: 'source', count: 1 }); + return plan; +} + +/** 正文段数:结论恒占一段,其余按有没有内容计数 */ +export function bodySectionCount(a: AskAnswer): number { + return sectionPlan(a).length; +} + +/* ══════════════ 专家团会诊流式 ══════════════ */ + +/** 会诊发言里的可见块:按顺序逐块出现,文本块逐字打出,列表块逐条亮出 */ +export type ConsultBlockKey = + | 'system' | 'metric' | 'reading' | 'status' | 'stance' | 'proposal' | 'handoff' + | 'conclusion' | 'summary' | 'judge' | 'actions'; + +export interface ConsultBlock { + key: ConsultBlockKey; + mode: 'type' | 'reveal' | 'item'; + text?: string; + count?: number; + /** reveal:出现前的停顿;item:相邻两条的间隔 */ + delay: number; +} + +/** + * 发言的播放脚本:先亮数据条,再逐句写「现状 → 观点 → 建议」,最后交代移交; + * 牵头卡先写结论,再逐条列成员要点与联合行动。顺序与 MemberCard / LeadCard 的排版一致。 + */ +export function consultPlan(turn: ConsultTurn): ConsultBlock[] { + if (turn.kind === 'system') { + return [{ key: 'system', mode: 'type', text: turn.text ?? '', delay: 360 }]; + } + if (turn.kind === 'member') { + const plan: ConsultBlock[] = []; + if (turn.metric) plan.push({ key: 'metric', mode: 'reveal', delay: 840 }); + if (turn.reading?.length) plan.push({ key: 'reading', mode: 'reveal', delay: 600 }); + if (turn.status) plan.push({ key: 'status', mode: 'type', text: turn.status, delay: 430 }); + if (turn.stance) plan.push({ key: 'stance', mode: 'type', text: turn.stance, delay: 500 }); + if (turn.proposal) plan.push({ key: 'proposal', mode: 'type', text: turn.proposal, delay: 560 }); + plan.push({ key: 'handoff', mode: 'reveal', delay: 620 }); + return plan; + } + const plan: ConsultBlock[] = []; + if (turn.conclusion) plan.push({ key: 'conclusion', mode: 'type', text: turn.conclusion, delay: 640 }); + if (turn.summary?.length) plan.push({ key: 'summary', mode: 'item', count: turn.summary.length, delay: 580 }); + if (turn.judge) plan.push({ key: 'judge', mode: 'reveal', delay: 800 }); + if (turn.actions?.length) plan.push({ key: 'actions', mode: 'item', count: turn.actions.length, delay: 740 }); + return plan; +} + +/** 会诊发言的流式状态:done 为已完成的块数,typed / items 是当前块的进度 */ +export interface PendingConsult { + turn: ConsultTurn; + done: number; + typed: number; + items: number; + started: number; +} + +/** 流式中的回答:thinking 轨按 revealed 揭示,body 按 typed / sections 分段流出 */ +export interface PendingAsk { + answer: AskAnswer; + staff?: string; + phase: 'think' | 'body'; + /** 已揭示的思考步数 */ + revealed: number; + /** 结论已打出的字符数 */ + typed: number; + /** 已亮出的正文段数(含结论) */ + sections: number; + /** 当前最后一段里已逐条亮出的条目数(数字 / 表格行 / 依据 / 建议动作) */ + items: number; + /** performance.now() 起点,用于卡头「耗时 x.xs」 */ + started: number; +} + +export interface AgentChat { + msgs: Msg[]; + /** 流式中的回答:对话区用它渲染思考轨与分段正文 */ + pending: PendingAsk | null; + /** 流式中的会诊发言:逐块出现、文本逐字打出 */ + pendingTurn: PendingConsult | null; + /** 会诊播报间隔的「分析中」气泡 */ + thinking: boolean; + /** 气泡里正在分析的专家名(会诊轮次之间) */ + thinkingName: string | null; + /** 输入区是否该锁住:会诊播报中或流式推演中都算忙 */ + busy: boolean; + draft: string; + setDraft: (v: string) => void; + ask: (raw: string) => void; + /** 跳过推演:把当前这条流式回答直接落成完整卡 */ + skip: () => void; + /** 清空:回到问候语,并掐掉所有在飞的定时器 */ + reset: () => void; +} + +const clock = () => { + const d = new Date(); + const p = (n: number) => String(n).padStart(2, '0'); + return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`; +}; + +/** 打字节奏:每 tick 出的字符数与间隔(慢到看得出在写,快不到让人等) */ +const TYPE_CHUNK = 2; +const TYPE_TICK = 34; + +/** 会诊发言的打字节奏:比单轮结论再慢一点,像专家边想边写;就位播报只是通报,可快一档 */ +const CONSULT_CHUNK = 2; +const CONSULT_TICK = 38; +const BROADCAST_CHUNK = 3; +const BROADCAST_TICK = 30; + +/** + * 思考步的停留时间。不再是统一步频:取数、套规则、跨表对照这些中段步骤最费时, + * 解析问句与出结论更快,首尾轻、中间重,才像真的在查表算数。 + * 每步再叠 ±240ms 抖动,避免节拍器式的机械感。 + */ +function thinkStepDelay(index: number, total: number): number { + const center = Math.max(0, (total - 2) / 2); + const spread = Math.max(1, total / 2); + const weight = Math.max(0, 1 - Math.abs(index - center) / spread); + return Math.round(760 + weight * 900 + Math.random() * 280); +} + +/** + * 段内逐条亮出的间隔:依据与建议是整句论证,读起来最费时;数字与表格行是 + * 结构化取数,可以快一些。长文本再按字数加权,避免短条目与长条目同速闪过。 + */ +function itemDelay(key: BodySectionKey, text: string): number { + switch (key) { + case 'numbers': + return 300 + Math.round(Math.random() * 140); + case 'table': + return 200 + Math.round(Math.random() * 120); + case 'basis': + return 520 + Math.min(700, text.length * 6) + Math.round(Math.random() * 180); + case 'actions': + return 480 + Math.min(420, text.length * 12) + Math.round(Math.random() * 160); + default: + return 420 + Math.round(Math.random() * 140); + } +} + +interface Input { + team: ExpertTeam | null; + t: I18n; +} + +export function useAgentChat({ team, t }: Input): AgentChat { + const [draft, setDraft] = useState(''); + const [thinking, setThinking] = useState(false); + const [thinkingName, setThinkingName] = useState(null); + const [msgs, setMsgs] = useState([]); + const [pending, setPending] = useState(null); + const [pendingTurn, setPendingTurn] = useState(null); + const seq = useRef(0); + const pendingRef = useRef(null); pendingRef.current = pending; + const timersRef = useRef([]); + /** 会诊脚本队列:一条播完再起下一条,中途「解散」或「清空」直接掐掉 */ + const queueRef = useRef([]); + const queueIndexRef = useRef(0); + const clearTimers = () => { timersRef.current.forEach(id => window.clearTimeout(id)); timersRef.current = []; }; + + const experts = useMemo(() => qualityExperts(), []); + const busy = thinking || !!pending || !!pendingTurn; + + /** 把当前流式回答直接落成完整卡(供正常播完与「跳过推演」共用) */ + const commit = (p: PendingAsk) => { + const elapsed = (performance.now() - p.started) / 1000; + setMsgs(prev => [...prev, { + id: ++seq.current, role: 'ai', text: p.answer.conclusion, + answer: p.answer, elapsed, staff: p.staff, time: clock(), + }]); + setPending(null); + }; + + // 问候语随文案变化刷新(不劫持用户正在输入的草稿;会诊中交给会诊序列) + useEffect(() => { + if (team) return; + clearTimers(); + setPending(null); + setPendingTurn(null); + setThinking(false); + setThinkingName(null); + queueRef.current = []; + queueIndexRef.current = 0; + seq.current = 0; + setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [t.agent.greeting, t.agent.subtitle, team]); + + /** 一条会诊发言播完:落成消息,隔一拍再起下一位(中间给「分析中」气泡) */ + const finishTurn = (p: PendingConsult) => { + // id 必须在 updater 外定值:updater 需保持纯函数,批处理时否则多条消息读到同一 seq 撞 key + const id = ++seq.current; + const time = clock(); + setMsgs(prev => [...prev, { + id, role: 'ai', text: p.turn.text ?? '', + name: p.turn.name, tag: p.turn.tag, kind: p.turn.kind, turn: p.turn, time, + }]); + setPendingTurn(null); + queueIndexRef.current += 1; + + const next = queueRef.current[queueIndexRef.current]; + if (!next) { setThinkingName(null); return; } + // 牵头汇总前多想一会儿:读完成员的读数再下结论 + const wait = next.kind === 'lead' ? 2900 : 1900 + Math.round(Math.random() * 400); + timersRef.current.push(window.setTimeout(() => { + setThinkingName(next.name); + setThinking(true); + }, 520)); + timersRef.current.push(window.setTimeout(() => { + setThinking(false); + setThinkingName(null); + setPendingTurn({ turn: next, done: 0, typed: 0, items: 0, started: performance.now() }); + }, wait)); + }; + + /* 专家团会诊:按脚本排队(就位播报 → 各专家轮流发言 → 牵头汇总)。 + 每条发言不再整卡甩出,而是先立卡头,再按 consultPlan 逐块出现、逐字打出。 */ + useEffect(() => { + clearTimers(); + setPending(null); + setPendingTurn(null); + setThinking(false); + setThinkingName(null); + if (!team) return; + const script = buildConsultScript(team); + seq.current = 0; + setMsgs([]); + queueRef.current = script; + queueIndexRef.current = 0; + const first = script[0]; + if (!first) return; + timersRef.current.push(window.setTimeout(() => { + setPendingTurn({ turn: first, done: 0, typed: 0, items: 0, started: performance.now() }); + }, 260)); + return clearTimers; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [team]); + + /* 会诊流式驱动器:一次 tick 只推进一个字 / 一个块 / 一条列表项 */ + useEffect(() => { + if (!pendingTurn) return; + const plan = consultPlan(pendingTurn.turn); + let delay = 0; + let next: PendingConsult | null = null; + + if (pendingTurn.done >= plan.length) { + /* 整条说完,停一拍再落卡(留出读完最后一句的时间) */ + delay = 720; + } else { + const b = plan[pendingTurn.done]; + if (b.mode === 'type') { + const text = b.text ?? ''; + const broadcast = b.key === 'system'; + if (pendingTurn.typed < text.length) { + /* 开口前先顿一拍:像翻完材料在心里组织措辞,再落笔 */ + delay = pendingTurn.typed === 0 + ? 420 + Math.round(Math.random() * 180) + : (broadcast ? BROADCAST_TICK : CONSULT_TICK) + Math.round(Math.random() * 18); + next = { + ...pendingTurn, + typed: Math.min(text.length, pendingTurn.typed + (broadcast ? BROADCAST_CHUNK : CONSULT_CHUNK)), + }; + } else { + delay = 360 + Math.round(Math.random() * 120); + next = { ...pendingTurn, done: pendingTurn.done + 1, typed: 0, items: 0 }; + } + } else if (b.mode === 'item') { + const count = b.count ?? 0; + if (pendingTurn.items < count) { + delay = b.delay + Math.round(Math.random() * 220); + next = { ...pendingTurn, items: pendingTurn.items + 1 }; + } else { + delay = 480 + Math.round(Math.random() * 160); + next = { ...pendingTurn, done: pendingTurn.done + 1, typed: 0, items: 0 }; + } + } else { + delay = b.delay + Math.round(Math.random() * 240); + next = { ...pendingTurn, done: pendingTurn.done + 1 }; + } + } + + const id = window.setTimeout(() => { + if (next) setPendingTurn(next); + else finishTurn(pendingTurn); + }, delay); + return () => window.clearTimeout(id); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pendingTurn]); + + /* 流式驱动器:一条 tick 只推进一格,状态变化后 effect 重新排下一条。 + 节奏带轻微抖动,避免机械等宽;抖动只影响播放速度,不影响任何读数。 */ + useEffect(() => { + if (!pending) return; + const totalSteps = pending.answer.steps.length; + const conclLen = pending.answer.conclusion.length; + const plan = sectionPlan(pending.answer); + const totalSections = plan.length; + + let delay = TYPE_TICK + Math.round(Math.random() * 16); + let next: PendingAsk | null = null; + + if (pending.phase === 'think') { + if (pending.revealed < totalSteps) { + /* 第一步前先顿一下,像在读懂问题;之后按步骤轻重分配停留 */ + delay = pending.revealed === 0 ? 560 : thinkStepDelay(pending.revealed, totalSteps); + next = { ...pending, revealed: pending.revealed + 1 }; + } else { + /* 思考轨走完到正文落笔之间留一拍:查表结束、组织结论 */ + delay = 1050; + next = { ...pending, phase: 'body', sections: 1 }; + } + } else if (pending.typed < conclLen) { + delay = TYPE_TICK + Math.round(Math.random() * 18); + next = { ...pending, typed: Math.min(conclLen, pending.typed + TYPE_CHUNK) }; + } else if (pending.sections < totalSections) { + const si = pending.sections - 1; + const section = plan[si]; + if (si === 0) { + /* 结论打完,停一拍再开始铺数字 */ + delay = 760; + next = { ...pending, sections: 2, items: 1 }; + } else if (pending.items < section.count) { + /* 段内逐条出现:数字一颗颗、明细一行行、依据/动作一条条 */ + const a = pending.answer; + const text = section.key === 'basis' + ? `${a.points[pending.items]?.label ?? ''}${a.points[pending.items]?.text ?? ''}` + : section.key === 'actions' ? a.actions[pending.items]?.label ?? '' : ''; + delay = itemDelay(section.key, text); + next = { ...pending, items: pending.items + 1 }; + } else { + /* 当前段铺完,停一拍再进入下一段 */ + delay = 560 + Math.round(Math.random() * 220); + next = { ...pending, sections: pending.sections + 1, items: 1 }; + } + } + + const id = window.setTimeout(() => { + if (next) setPending(next); + else commit(pending); + }, delay); + return () => window.clearTimeout(id); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pending]); + + /** 提问 → 质量问答引擎 → 思考轨 → 正文分段 → 回答卡落位 */ + const ask = (raw: string) => { + const text = raw.trim(); + if (!text || busy) return; + const { intent, answer } = buildAskAnswer(text); + const who = intent === 'help' ? undefined : experts.find(e => e.code === DISPATCH[intent as Exclude]); + setMsgs(prev => [...prev, { id: ++seq.current, role: 'user', text, time: clock() }]); + setDraft(''); + setPending({ + answer, + staff: who ? `${t.agent.dispatched}${who.name}` : undefined, + phase: 'think', + revealed: 0, + typed: 0, + sections: 0, + items: 0, + started: performance.now(), + }); + }; + + const skip = () => { + const p = pendingRef.current; + if (!p) return; + commit({ ...p, revealed: p.answer.steps.length, typed: p.answer.conclusion.length, sections: bodySectionCount(p.answer), items: 0 }); + }; + + const reset = () => { + clearTimers(); + setPending(null); + setPendingTurn(null); + setThinking(false); + setThinkingName(null); + queueRef.current = []; + queueIndexRef.current = 0; + setDraft(''); + seq.current = 0; + setMsgs([{ id: 0, role: 'ai', text: t.agent.greeting, staff: t.agent.subtitle, time: clock() }]); + }; + + return { msgs, pending, pendingTurn, thinking, thinkingName, busy, draft, setDraft, ask, skip, reset }; +} diff --git a/src/modules/tfamd-oee/hooks/useAutoScroll.ts b/src/modules/tfamd-oee/hooks/useAutoScroll.ts new file mode 100644 index 0000000..f22c2c5 --- /dev/null +++ b/src/modules/tfamd-oee/hooks/useAutoScroll.ts @@ -0,0 +1,150 @@ +import { useEffect, type RefObject } from 'react'; + +/** + * 侧栏列表的自动滚动:让「销售订单 / 客户资料 / 采购单 / 生产工单 / 供应商资料」这些 + * 一页装不下的卡片列表自己缓慢往下走,到底停一下再平滑回到顶部循环。 + * + * 相位机(stepMotion)写成纯函数,滚动驱动(useAutoScroll)只负责喂帧和读几何, + * 这样循环逻辑可以脱离浏览器单独验算;rAF 在后台标签页不触发时循环自然停摆, + * 不浪费 CPU,也不需要额外的可见性判断。 + */ + +export type Phase = 'down' | 'holdB' | 'up' | 'holdT'; + +export interface MotionState { + /** 浮点累加的期望 scrollTop:28px/s 摊到 120Hz 每帧只有 0.23px, + * 直接读写整数 scrollTop 会被量化舍入吞掉而停摆,所以位置必须自己攒 */ + pos: number; + phase: Phase; + /** 停留相位到期时刻(ms,performance.now 时钟) */ + until: number; +} + +export interface MotionCfg { + /** 下滚速度 px/s */ + speed: number; + holdBottomMs: number; + holdTopMs: number; + /** 回顶速度:每秒收敛的比例,越大越快 */ + rewind: number; +} + +export const DEFAULT_MOTION: MotionCfg = { speed: 28, holdBottomMs: 1400, holdTopMs: 500, rewind: 5 }; + +/** 容器几何:全部由调用方从 DOM 读好后传入,纯函数不碰 DOM */ +export interface MotionGeo { + scrollTop: number; + clientHeight: number; + scrollHeight: number; +} + +export interface MotionResult { + state: MotionState; + /** 需要写回的 scrollTop;null 表示这一帧不要动(暂停 / 够不着滚动) */ + scrollTop: number | null; +} + +/** + * 推进一帧。paused 为真(鼠标悬停、用户刚手动滚过、列表装得下没有滚动空间)时 + * 只把累加器对齐到真实 scrollTop 并交还控制权,用户一松手就能从当前位置续跑。 + */ +export function stepMotion( + s: MotionState, now: number, dtSec: number, geo: MotionGeo, paused: boolean, cfg: MotionCfg = DEFAULT_MOTION, +): MotionResult { + const overflow = geo.scrollHeight - geo.clientHeight; + if (overflow <= 4 || paused) return { state: { ...s, pos: geo.scrollTop }, scrollTop: null }; + + const dt = Math.min(0.05, Math.max(0, dtSec)); // 首帧/掉帧的长间隔一律夹到 50ms,避免瞬移 + const pos = Math.min(Math.max(s.pos, 0), overflow); + const state: MotionState = { pos, phase: s.phase, until: s.until }; + + if (state.phase === 'down') { + if (pos + geo.clientHeight >= geo.scrollHeight - 2) { + state.phase = 'holdB'; + state.until = now + cfg.holdBottomMs; + state.pos = geo.scrollTop; + return { state, scrollTop: null }; + } + state.pos = Math.min(pos + cfg.speed * dt, overflow); + return { state, scrollTop: state.pos }; + } + + if (state.phase === 'holdB') { + state.pos = geo.scrollTop; + if (now >= state.until) state.phase = 'up'; + return { state, scrollTop: null }; + } + + if (state.phase === 'up') { + state.pos = pos - pos * Math.min(1, dt * cfg.rewind); + if (state.pos <= 0.5) { + state.pos = 0; + state.phase = 'holdT'; + state.until = now + cfg.holdTopMs; + } + return { state, scrollTop: state.pos }; + } + + /* holdT:在顶部停一下,让最后一屏和第一屏之间有个呼吸口 */ + state.pos = geo.scrollTop; + if (now >= state.until) state.phase = 'down'; + return { state, scrollTop: null }; +} + +interface Options { + /** 鼠标移到列表上 / 用户自己滚过之后,暂停多久再续跑(ms) */ + wheelCooldownMs?: number; + cfg?: MotionCfg; +} + +/** + * 把 stepMotion 接到真实滚动容器上。 + * enabled 变 false 时循环与监听一起摘掉,容器停在当前位置——这就是「关闭滚动」按钮的语义。 + */ +export function useAutoScroll( + ref: RefObject | { current: HTMLElement | null }, + enabled: boolean, + { wheelCooldownMs = 2200, cfg = DEFAULT_MOTION }: Options = {}, +) { + useEffect(() => { + const el = ref.current; + if (!el || !enabled) return; + /* 系统要求减少动态效果时不做自动滚动(按钮仍可开启,只是不动) */ + if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) return; + + let hovering = false; + let coolUntil = 0; + const cool = () => { coolUntil = performance.now() + wheelCooldownMs; }; + const enter = () => { hovering = true; }; + const leave = () => { hovering = false; }; + el.addEventListener('wheel', cool, { passive: true }); + el.addEventListener('touchstart', cool, { passive: true }); + el.addEventListener('pointerenter', enter); + el.addEventListener('pointerleave', leave); + + let state: MotionState = { pos: el.scrollTop, phase: 'down', until: 0 }; + let last = performance.now(); + let raf = 0; + const frame = (now: number) => { + raf = requestAnimationFrame(frame); + const dt = (now - last) / 1000; + last = now; + const res = stepMotion( + state, now, dt, + { scrollTop: el.scrollTop, clientHeight: el.clientHeight, scrollHeight: el.scrollHeight }, + hovering || now < coolUntil, cfg, + ); + state = res.state; + if (res.scrollTop !== null) el.scrollTop = res.scrollTop; + }; + raf = requestAnimationFrame(frame); + + return () => { + cancelAnimationFrame(raf); + el.removeEventListener('wheel', cool); + el.removeEventListener('touchstart', cool); + el.removeEventListener('pointerenter', enter); + el.removeEventListener('pointerleave', leave); + }; + }, [ref, enabled, wheelCooldownMs, cfg]); +} diff --git a/src/modules/tfamd-oee/hooks/useCountUp.ts b/src/modules/tfamd-oee/hooks/useCountUp.ts new file mode 100644 index 0000000..3c8fd9c --- /dev/null +++ b/src/modules/tfamd-oee/hooks/useCountUp.ts @@ -0,0 +1,54 @@ +import { useEffect, useRef, useState } from 'react'; + +/** + * 数字滚动(2026-11-14 动效层):rAF 从旧值插值到新值,easeOutCubic,默认 600ms。 + * + * 纪律: + * - 终值严格等于 target(末帧直接 setDisplay(target))——滚动只是过渡,不产生第二份读数; + * - 首挂直落(不从 0 滚起,避免开场"造数"错觉); + * - 旧值或新值为 null(数据缺口)时快照直落,绝不跨缺口滚动; + * - 中途被打断从当前显示值续滚(fromRef 跟随显示值),切日连点不跳变; + * - prefers-reduced-motion 直落:CSS 全局开关只管 animation/transition, + * rAF 是 JS 驱动,须在此自查(与 useAutoScroll 同款判定)。 + * + * 视图只拿它做"显示插值";读数本身仍一律 L3 现算传入(断言②不被破坏)。 + */ +export function useCountUp(rawTarget: number | null, duration = 600): number | null { + // NaN/非有限=G 缺口,与 null 同待遇:快照直落「—」,不滚出 NaN + const target = rawTarget != null && Number.isFinite(rawTarget) ? rawTarget : null; + const [display, setDisplay] = useState(target); + const fromRef = useRef(target); + const rafRef = useRef(0); + + useEffect(() => { + const from = fromRef.current; + if (from === null || target === null || from === target) { + fromRef.current = target; + setDisplay(target); + return; + } + if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) { + fromRef.current = target; + setDisplay(target); + return; + } + const t0 = performance.now(); + const tick = (t: number) => { + const p = Math.min(1, (t - t0) / duration); + const e = 1 - (1 - p) ** 3; + const v = from + (target - from) * e; + fromRef.current = v; + setDisplay(v); + if (p < 1) { + rafRef.current = requestAnimationFrame(tick); + } else { + fromRef.current = target; + setDisplay(target); + } + }; + rafRef.current = requestAnimationFrame(tick); + return () => cancelAnimationFrame(rafRef.current); + }, [target, duration]); + + return display; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/hooks/useMecData.ts b/src/modules/tfamd-oee/hooks/useMecData.ts new file mode 100644 index 0000000..3371b50 --- /dev/null +++ b/src/modules/tfamd-oee/hooks/useMecData.ts @@ -0,0 +1,48 @@ +import { useEffect, useMemo, useState } from 'react'; +import { + queryMetricTree, queryMetricLinks, queryDigitalStaff, queryAlertCounts, +} from '../data/sqlite'; +import type { MetricNode, MetricLink, DigitalStaff } from '../data/sqlite'; + +export interface MecData { + tree: MetricNode[]; + flat: MetricNode[]; + byCode: Map; + links: MetricLink[]; + staff: DigitalStaff[]; + alerts: { red: number; yellow: number; green: number; total: number }; +} + +const EMPTY: MecData = { + tree: [], flat: [], byCode: new Map(), links: [], staff: [], + alerts: { red: 0, yellow: 0, green: 0, total: 0 }, +}; + +/** db 就绪后一次性把指标中台的数据读进内存,供三栏共享。 + * modeVersion:重读计数,变化时重读快照——指标树数字随种子换源,不在这里做第二套计算。 */ +export function useMecData(dbReady: boolean, modeVersion = 0): MecData { + const [snap, setSnap] = useState(null); + + useEffect(() => { + if (!dbReady) return; + // 从带逐业务日 trend 的树拍平,flat/byCode 同样拥有历史序列(日轴游标依赖) + // ★ 期数是种子真实业务日数(3 天),不是 12 个月合成曲线 + const tree = queryMetricTree(); + const flat: MetricNode[] = []; + const byCode = new Map(); + const walk = (nodes: MetricNode[]) => nodes.forEach(n => { + flat.push(n); + byCode.set(n.code, n); + if (n.children?.length) walk(n.children); + }); + walk(tree); + setSnap({ + tree, flat, byCode, + links: queryMetricLinks(), + staff: queryDigitalStaff(), + alerts: queryAlertCounts(), + }); + }, [dbReady, modeVersion]); + + return useMemo(() => snap ?? EMPTY, [snap]); +} diff --git a/src/modules/tfamd-oee/hooks/useOeeChat.ts b/src/modules/tfamd-oee/hooks/useOeeChat.ts new file mode 100644 index 0000000..ca84037 --- /dev/null +++ b/src/modules/tfamd-oee/hooks/useOeeChat.ts @@ -0,0 +1,266 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { answerOee, makeTools } from '../lib/oeeAnswerEngine'; +import type { AnswerContext, OeeAnswer } from '../lib/oeeAnswerEngine'; +import type { ImprovementTask } from '../types/oee'; + +/** + * OEE 底部对话区的会话状态机(建议书 §4.3 / §5.3): + * 问候 → 异步规则引擎应答(answerOee)→ 思考轨逐条揭示 → 正文分段流出 → 回答卡落位。 + * + * ★ 与旧质量对话(useAgentChat)的三点不同: + * ① 单轮问答,**去掉专家团会诊 / 轮流播报**那套队列(OEE 一期是 A1–A4 按意图路由,不是会诊)。 + * ② ask 是**异步**的:answerOee 返回 Promise(五类工具皆 async),先置 thinking 再落 pending。 + * ③ 持有 modelMode 开关:'rule' 默认纯规则;'llm' 现场演示降级①(模型通道未接入 → 规则引擎应答)。 + * + * ★ 分层:本 hook 在 L4,可用 new Date() / performance.now() / Math.random()(引擎层禁止)。 + * 数字与文案全部来自 L3 answerOee,hook 只负责播放节奏,不二次计算任何 OEE(断言②)。 + * 状态由 MetricWorkspace 持有:进出本体 / 数据集舞台时对话区卸载,历史与在飞推演不丢。 + */ + +export type ModelMode = 'rule' | 'llm'; + +export interface OeeMsg { + id: number; + role: 'user' | 'ai'; + text: string; + time: string; + /** 单轮问答的规范回答卡(四段 + 结构化卡片 + 闸门 / 降级元数据) */ + answer?: OeeAnswer; + /** 该回答的推演耗时(秒):流式结束后写回,卡头展示 */ + elapsed?: number; +} + +/** 正文段:结论恒占一段,其余按有没有内容追加;count 是该段要逐条亮出的条目数。 + * 顺序必须与 OeeAnswerCard 的 parts 完全一致,否则流式会跳段。 */ +export type OeeSectionKey = + | 'conclusion' | 'numbers' | 'table' | 'benefits' | 'basis' | 'citations' | 'actions' | 'source'; + +export function oeeSectionPlan(a: OeeAnswer): { key: OeeSectionKey; count: number }[] { + const plan: { key: OeeSectionKey; count: number }[] = [{ key: 'conclusion', count: 1 }]; + if (a.metrics.length) plan.push({ key: 'numbers', count: a.metrics.length }); + if (a.table) plan.push({ key: 'table', count: a.table.rows.length }); + if (a.benefits?.length) plan.push({ key: 'benefits', count: a.benefits.length }); + if (a.points.length) plan.push({ key: 'basis', count: a.points.length }); + if (a.citations.length) plan.push({ key: 'citations', count: a.citations.length }); + if (a.actions.length) plan.push({ key: 'actions', count: a.actions.length }); + plan.push({ key: 'source', count: 1 }); + return plan; +} + +export function oeeSectionCount(a: OeeAnswer): number { + return oeeSectionPlan(a).length; +} + +/** 流式中的回答:think 轨按 revealed 揭示,body 按 typed / sections / items 分段流出 */ +export interface PendingOee { + answer: OeeAnswer; + phase: 'think' | 'body'; + revealed: number; + typed: number; + sections: number; + items: number; + started: number; +} + +export interface OeeChat { + msgs: OeeMsg[]; + pending: PendingOee | null; + /** 异步取数中(answerOee 尚未 resolve):对话区给「分析中」气泡 */ + thinking: boolean; + busy: boolean; + draft: string; + setDraft: (v: string) => void; + ask: (raw: string) => void; + /** 跳过推演:把当前这条流式回答直接落成完整卡 */ + skip: () => void; + reset: () => void; + /** 模型增强开关:'llm' 演示降级①(无端点 → 规则引擎) */ + modelMode: ModelMode; + setModelMode: (m: ModelMode) => void; +} + +/** 问候语:标准命名(无花名),明示 A1–A4 就位,数字只来自工具;分期占位不在对话区点名。 */ +export const OEE_GREETING = + '指标问数 → 损失诊断 → 改善建议 → 闭环跟踪,四类一期智能体已就位。' + + '数字只来自五类受控工具,结论必带口径出处,收益只给区间、跨版本对比一律拒绝。你想先问哪一类?'; + +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())}`; +}; + +/* 打字节奏:每 tick 出的字符数与间隔(慢到看得出在写,快不到让人等) */ +const TYPE_CHUNK = 2; +const TYPE_TICK = 34; + +/** + * 思考步停留:取数 / 套口径 / 过闸这些中段步骤最费时,解析问句与出结论更快, + * 首尾轻、中间重,才像真的在查表算数。每步再叠抖动,避免节拍器式机械感。 + */ +function thinkStepDelay(index: number, total: number): number { + const center = Math.max(0, (total - 2) / 2); + const spread = Math.max(1, total / 2); + const weight = Math.max(0, 1 - Math.abs(index - center) / spread); + return Math.round(760 + weight * 900 + Math.random() * 280); +} + +/** 段内逐条亮出的间隔:依据 / 引用 / 建议是整句论证,读起来最费时;数字 / 表格行 / 收益是结构化取数,可快一些。 */ +function itemDelay(key: OeeSectionKey, text: string): number { + switch (key) { + case 'numbers': + return 300 + Math.round(Math.random() * 140); + case 'table': + return 200 + Math.round(Math.random() * 120); + case 'benefits': + return 420 + Math.round(Math.random() * 160); + case 'basis': + return 520 + Math.min(700, text.length * 6) + Math.round(Math.random() * 180); + case 'citations': + return 460 + Math.min(500, text.length * 5) + Math.round(Math.random() * 160); + case 'actions': + return 480 + Math.min(420, text.length * 12) + Math.round(Math.random() * 160); + default: + return 420 + Math.round(Math.random() * 140); + } +} + +interface Input { + /** 改善任务存储(内存态,SQLite 锁定四表):派单 / 复盘意图读它 */ + tasks: ImprovementTask[]; + setTasks: (tasks: ImprovementTask[]) => void; + /** 当前业务日(顶栏筛选同源,periodLabel(filter.day)) */ + bizDate: string; + /** 顶栏当前设备(筛了单台时传入):问句没点名设备就跟它 */ + device?: string; +} + +export function useOeeChat({ tasks, setTasks, bizDate, device }: Input): OeeChat { + const [draft, setDraft] = useState(''); + const [thinking, setThinking] = useState(false); + const [modelMode, setModelMode] = useState('rule'); + const [msgs, setMsgs] = useState(() => [{ id: 0, role: 'ai', text: OEE_GREETING, time: clock() }]); + const [pending, setPending] = useState(null); + const seq = useRef(0); + const pendingRef = useRef(null); pendingRef.current = pending; + const timersRef = useRef([]); + const clearTimers = () => { timersRef.current.forEach((id) => window.clearTimeout(id)); timersRef.current = []; }; + + /* 工具与上下文用 ref 取最新值,工具实例本身稳定(useMemo 空依赖): + 任务存储 / 业务日 / 模型开关随渲染更新,但不会每次重建工具。 */ + const tasksRef = useRef(tasks); tasksRef.current = tasks; + const setTasksRef = useRef(setTasks); setTasksRef.current = setTasks; + const bizDateRef = useRef(bizDate); bizDateRef.current = bizDate; + const deviceRef = useRef(device); deviceRef.current = device; + const modelModeRef = useRef(modelMode); modelModeRef.current = modelMode; + const tools = useMemo(() => makeTools({ + getTasks: () => tasksRef.current, + setTasks: (t) => setTasksRef.current(t), + now: () => new Date().toISOString(), + }), []); + + const busy = thinking || !!pending; + + /** 把当前流式回答直接落成完整卡(供正常播完与「跳过推演」共用) */ + const commit = (p: PendingOee) => { + const elapsed = (performance.now() - p.started) / 1000; + const id = ++seq.current; + const time = clock(); + setMsgs((prev) => [...prev, { id, role: 'ai', text: p.answer.four.conclusion, answer: p.answer, elapsed, time }]); + setPending(null); + }; + + /* 流式驱动器:一条 tick 只推进一格,状态变化后 effect 重新排下一条。 + 节奏带轻微抖动,避免机械等宽;抖动只影响播放速度,不影响任何读数。 */ + useEffect(() => { + if (!pending) return; + const totalSteps = pending.answer.steps.length; + const conclLen = pending.answer.four.conclusion.length; + const plan = oeeSectionPlan(pending.answer); + const totalSections = plan.length; + + let delay = TYPE_TICK + Math.round(Math.random() * 16); + let next: PendingOee | null = null; + + if (pending.phase === 'think') { + if (pending.revealed < totalSteps) { + delay = pending.revealed === 0 ? 560 : thinkStepDelay(pending.revealed, totalSteps); + next = { ...pending, revealed: pending.revealed + 1 }; + } else { + /* 思考轨走完到正文落笔之间留一拍:查表结束、组织结论 */ + delay = 1050; + next = { ...pending, phase: 'body', sections: 1 }; + } + } else if (pending.typed < conclLen) { + delay = TYPE_TICK + Math.round(Math.random() * 18); + next = { ...pending, typed: Math.min(conclLen, pending.typed + TYPE_CHUNK) }; + } else if (pending.sections < totalSections) { + const si = pending.sections - 1; + const section = plan[si]; + if (si === 0) { + /* 结论打完,停一拍再开始铺数字 */ + delay = 760; + next = { ...pending, sections: 2, items: 1 }; + } else if (pending.items < section.count) { + const a = pending.answer; + const text = section.key === 'basis' + ? `${a.points[pending.items]?.label ?? ''}${a.points[pending.items]?.text ?? ''}` + : section.key === 'citations' + ? `${a.citations[pending.items]?.title ?? ''}${a.citations[pending.items]?.source ?? ''}` + : section.key === 'actions' ? a.actions[pending.items]?.label ?? '' : ''; + delay = itemDelay(section.key, text); + next = { ...pending, items: pending.items + 1 }; + } else { + delay = 560 + Math.round(Math.random() * 220); + next = { ...pending, sections: pending.sections + 1, items: 1 }; + } + } + + const id = window.setTimeout(() => { + if (next) setPending(next); + else commit(pending); + }, delay); + return () => window.clearTimeout(id); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [pending]); + + /** 提问 → 异步规则引擎 → 思考轨 → 正文分段 → 回答卡落位 */ + const ask = (raw: string) => { + const text = raw.trim(); + if (!text || busy) return; + setMsgs((prev) => [...prev, { id: ++seq.current, role: 'user', text, time: clock() }]); + setDraft(''); + setThinking(true); + const ctx: AnswerContext = { tools, bizDate: bizDateRef.current, device: deviceRef.current, modelMode: modelModeRef.current }; + answerOee(text, ctx, tasksRef.current) + .then((answer) => { + setThinking(false); + setPending({ answer, phase: 'think', revealed: 0, typed: 0, sections: 0, items: 0, started: performance.now() }); + }) + .catch(() => { + /* 诚实兜底:引擎异常不编数字,落一条说明(原型内 answerOee 不抛错,此为防御) */ + setThinking(false); + setMsgs((prev) => [...prev, { id: ++seq.current, role: 'ai', text: '应答引擎异常,未生成结论;请重试或转人工核对。', time: clock() }]); + }); + }; + + const skip = () => { + const p = pendingRef.current; + if (!p) return; + commit({ ...p, revealed: p.answer.steps.length, typed: p.answer.four.conclusion.length, sections: oeeSectionCount(p.answer), items: 0 }); + }; + + const reset = () => { + clearTimers(); + setPending(null); + setThinking(false); + setDraft(''); + seq.current = 0; + setMsgs([{ id: 0, role: 'ai', text: OEE_GREETING, time: clock() }]); + }; + + /* 卸载时掐掉所有在飞定时器,避免舞台切换后 setState 落到已卸载组件 */ + useEffect(() => clearTimers, []); + + return { msgs, pending, thinking, busy, draft, setDraft, ask, skip, reset, modelMode, setModelMode }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/i18n/locales.ts b/src/modules/tfamd-oee/i18n/locales.ts new file mode 100644 index 0000000..392fd8c --- /dev/null +++ b/src/modules/tfamd-oee/i18n/locales.ts @@ -0,0 +1,215 @@ +type Dict = Record; +export interface AgentDict { + title: string; subtitle: string; placeholder: string; send: string; thinking: string; + clear: string; expand: string; collapse: string; greeting: string; + tall: string; tallOff: string; dispatched: string; + secStatus: string; secStance: string; secProposal: string; handoff: string; + concl: string; keypoints: string; judgeLabel: string; actionsLabel: string; + /** 质量问答回答卡:思考过程(逐条揭示后可折叠)+ 六段式正文 */ + aiName: string; thinkTitle: string; thinkHint: string; thinkSteps: string; thinkElapsed: string; + secIntent: string; secNumbers: string; secTable: string; secBasis: string; secActions: string; secSource: string; + askMore: string; + /** 流式推演:跳过 / 跳转落点 / 判定线 */ + skip: string; jumpSee: string; jumpHint: string; lineLabel: string; +} + +export interface I18n { + appTitle: string; + nav: Dict; + kpi: Dict; + dim: Dict; + common: Dict; + ai: Dict; + dashboard: Dict; + panel: Dict; + tab: Dict; + tree: Dict; + net: Dict; + flow: Dict; + /** 左栏「质量流程」页签:PE→IE→QE→ME 四角色质量预防流转 */ + qflow: Dict; + /** 右栏「质量告警」:四张源表汇成的告警流 */ + alert: Dict; + detail: Dict; + staff: Dict; + team: Dict; + agent: AgentDict; + header: Dict; + res: Dict; +} + +const zh: I18n = { + appTitle: 'OEE智能分析', + nav: { + cockpit: '经营驾驶舱', structure: '结构动因', quality: '质量健康', + efficiency: '运营效率', growth: '研发动能', market: '市场客户', + production: '生产供应', digital: '数智化与AI', risk: '风险韧性', aiAgent: 'AI 智能体', + }, + kpi: {}, + dim: { + overall: '经营总览', result: '财务成果', quality: '盈利质量', efficiency: '运营效率', + growth: '研发动能', market: '市场客户', production: '生产供应', digital: '数智化与AI', + risk: '风险韧性', + }, + common: { + target: '目标', actual: '实际', yoy: '同比', mom: '环比', budget: '预算', + alert: '预警', trend: '趋势', detail: '详情', close: '关闭', search: '搜索', + export: '导出', refresh: '刷新', dark: '深色', light: '浅色', + unit: '单位', billion: '亿', million: '万', + percent: '%', days: '天', times: '次', score: '分', pt: '点', + collapse: '收起', expand: '展开', fullscreen: '全屏', exitFullscreen: '退出全屏', + back: '返回', all: '全部', none: '无', total: '合计', weight: '权重', owner: '责任部门', + formula: '计算口径', frequency: '更新频率', updatedAt: '更新于', loading: '加载中', + snapshot: '静态快照 · 不随时间轴', + noData: '暂无数据', more: '更多', reset: '重置', + initializing: '正在初始化数据库...', initFailed: '数据初始化失败', + initTimeout: '初始化超时(超过 20 秒),WASM 或数据未能加载完成', retry: '重试', + good: '达标', watch: '关注', urgent: '紧急', better: '向好', worse: '转弱', + }, + header: { + health: '经营健康度', metricTotal: '纳管指标', + }, + panel: { + metricTree: '指标树', metricNetwork: '指标网络', digitalStaff: '数字员工', + workspace: 'OEE 智能优化', agent: '智能体对话区', + legendExec: '预算执行率', legendOk: '达标', legendWarn: '未达标', legendBad: '低于{n}%', + }, + tab: { + detail: '设备时间轴', trend: '趋势分析', structure: '损失结构', + region: '工序·工位对比', risk: '数据质量', cockpit: '总览看板', + priority: '优先处理清单', entry: '手工录入台', task: '任务中心', + master: '主数据', caliber: '配置中心', integration: '集成接口', disclosure: '说明与对照', + forecast: 'AI智能预测分析', linemap: '2D/3D 线体图', report: '报表导出', + clickToRestore: '点击恢复', + }, + tree: { + search: '搜索指标 / 编码 / 责任部门', expandAll: '全展开', collapseAll: '全收起', + level: '层级', nodes: '个节点', noResult: '没有匹配的指标', + lv0: 'L0 总览', lv1: 'L1 维度', lv2: 'L2 KPI', lv3: 'L3 驱动因子', + }, + net: { + drive: '正向驱动', conflict: '负向制约', monitor: '风险监控', + center: '中心节点', isolate: '无跨树关联,仅参与上层合成', + resetView: '重置视角', toStage: '送入中央工作区', exitStage: '退出全景', + stageHint: '滚轮缩放 · 拖拽平移 · 悬停读数 · 双击飞临 · 点击节点→右侧因果看板', + influence: '影响分析', incoming: '驱动来源', outgoing: '影响去向', + noConn: '暂无跨指标关联,仅参与上层合成', hubHint: '点击维度枢纽联动 · 右上送入中央工作区看全景', + allNodes: '全部节点', focusSel: '聚焦选中', nodes: '项指标', + propagate: '影响传播', flyTo: '聚焦飞行', topChains: '全图最强因果链', + /* 降密与时间游标 */ + leaves: '末级因子', tipToPanel: '点击看完整因果', + tlPlay: '回放', tlPause: '暂停', tlBack: '回当期', tlLabel: '时间轴', + /* 右侧因果看板 */ + causalTitle: '因果看板', causalOpen: '因果看板', causalClose: '收起看板', + causalCursor: '游标读数', causalTrend: '12 期趋势', + causalIn: '前因 · 驱动来源', causalOut: '后果 · 影响去向', causalKids: '下级回应', + causalSibs: '同层对标', + causalAi: 'AI 研判', causalReport: '汇报口径', + causalNoIn: '无前因(链路源头)', causalNoOut: '无后果(终端指标)', + causalNoKid: '末级驱动因子,无下级指标', causalNoStaff: '暂无智能体值守', + zFinance: '财务与利润', zFactory: '智能工厂', zMarket: '销售与市场', + zRd: '研发中心', zData: '数据与AI中心', zRisk: '风控中心', + }, + flow: { + title: '流程效能', + hint: '研产供销六段价值链的过程指标:停留、流转、一次通过、返工。结果指标请看指标树。', + vsTree: '过程看这里 · 结果看指标树', + summary: '全链汇总', cycle: '端到端周期', e2e: '全链一次通过', + throughput: '有效产出', constraint: '约束段', wip: '在制品', bottleneck: '瓶颈段', + dwell: '停留', flow: '月流转', fpqc: '一次通过', rework: '返工', score: '段达成', + linked: '关联指标', unitDay: '天', stageUnit: '段', base: '基线', + faster: '较上期提速', slower: '较上期变慢', flat: '与上期持平', + bottleneckTip: '达成率最低的一段,优先改善对象', + wipTip: '在制品 = 月流转 × 停留 ÷ 30(Little 法则)', + clickTip: '指标片可点开中央看板明细', + }, + qflow: { + title: '质量流程', + hint: 'PE → IE → QE → ME 四段质量预防流转:每段停留多久、流过多少、一次通过多少、退回多少。结果指标(良率/客诉/质量成本)看指标树。', + cycle: '闭环周期', e2e: '四段一次通过', + kpiOk: '质量 KPI 达标', constraint: '约束角色', bottleneck: '瓶颈角色', + input: '输入', output: '输出', next: '后续动作', situation: '现状', + kpiGroup: '本段质量 KPI', vsBase: '较现状', targetShort: '目标', + score: '段达成', redKpis: '红档 KPI', + dataSource: '口径:以下数字为可复现的确定性模拟,接入 8D 报告、风险检验单、异常处理记录、特征树、历史检验报告、设备参数表后由真实数据替换。', + kpiTip: '悬停看职责表现状;达成率 = 当期值 ÷ 目标(越低越好类取倒数口径)', + kpiTileTip: '两套口径分开看:段达成率量的是流转效率(停留/一次通过/退回),质量 KPI 量的是预防能力(标准覆盖、遗漏数)。流转快不等于标准全,所以 PE 段达成 98% 而 KPI 仍有黄档。', + handoff: '流转', + }, + alert: { + title: '质量告警', + hint: '', + levelRed: '需立即处置', levelOrange: '当班跟进', levelBlue: '持续观察', levelMuted: '已闭环', + action: '处置动作', owner: '责任人', source: '来源', caliber: '判定口径', + empty: '当前没有待处置告警', + }, + detail: { + title: '指标明细', current: '当期值', targetVal: '目标值', gap: '偏差', + achieve: '达成度', reach: '达成', trend12: '近 12 期趋势', composition: '构成拆解', + drivers: '驱动因子(L3)', parentChain: '归属链路', related: '关联指标', + desc: '指标说明', noDesc: '该节点为聚合层,无独立业务说明。', + subMetrics: '下级指标', alertRule: '预警阈值', polarity: '方向', + polarityUp: '越高越好', polarityDown: '越低越好', + contribution: '贡献度', historyTable: '历史明细', period: '期间', + dimWeight: '八大维度权重', productContrib: '产品线收入贡献', watchTop: '重点关注 Top6(按偏差排序)', + gapNote: '偏差已按指标方向归一:正数=优于目标,负数=待改善(成本/周期类越低越好)。', + driversNote: '条长与主数字同为偏差幅度(已归一),右侧小字为当期值。', + agentHint: '可向下方智能体提问:为什么这个指标偏离目标?', + }, + staff: { + title: '数字员工', online: '在岗', busy: '作业中', idle: '待命', + alert: '待升级', offline: '停用', tasks: '今日已完成', success: '成功率', + confidence: '置信度', load: '负载', lastRun: '最近运行', + skills: '能力', current: '当前动作', wake: '唤醒对话', viewMetric: '查看指标', + autoScroll: '自动滚动', pause: '暂停滚动', detail: '详情', + emptyFilter: '该状态下没有数字员工', filterAll: '全部', + }, + team: { + entry: '组建专家团', panel: '专家团', back: '返回数字员工', + presetTitle: '预设专家团', customTitle: '自由勾选组建', + presetHint: '点击预设团一键就位,或在下方勾选智能体自建团队', + customHint: '勾选 2 位及以上智能体,首位为牵头', + selected: '已选成员', lead: '牵头', member: '成员', + convene: '发起会诊', conveneN: '发起会诊({n})', dismiss: '解散专家团', + needTwo: '至少选择 2 位智能体', clearSel: '清空', + activeTeam: '当前专家团', topic: '议题', + }, + agent: { + title: '智能体对话', subtitle: '由在岗质量专家协同应答', + placeholder: '提问:哪档结构特征最伤?参数掉到哪了?几单超期未闭环?', + send: '发送', thinking: '分析中', clear: '清空', expand: '展开', collapse: '收起', + tall: '拉高', tallOff: '还原高度', + greeting: 'PE → IE → QE → ME 四段质量预防一路流转:PE 定工艺、IE 定标准与工装、QE 定检验、ME 定设备参数,问题、原因、对策与责任人都落到同一棵特征树上。你想先问哪一段?', + dispatched: '已把该问题派发给', + secStatus: '现状', secStance: '观点', secProposal: '建议', handoff: '移交', + concl: '会诊结论', keypoints: '成员要点', judgeLabel: '综合研判', actionsLabel: '联合行动', + aiName: 'OEE 智能优化智能体', + thinkTitle: '思考过程', thinkHint: '正在按业务本体规则推演', + thinkSteps: '{n} 步', thinkElapsed: '耗时 {s}s', + secIntent: '识别意图', secNumbers: '关键数字', secTable: '质量明细', + secBasis: '依据与口径', secActions: '建议动作', secSource: '数据来源', + askMore: '继续追问', + skip: '跳过推演', jumpSee: '看同一口径', jumpHint: '点一下跳到对应页签或舞台', + lineLabel: '判定线', + }, + res: { + region: '区域', revenue: '营业收入', headcount: '人数', perCapita: '人均产值', + grossMargin: '毛利率', productLine: '产品线', share: '占比', yoy: '同比增速', + riskName: '风险项', probability: '概率', impact: '影响', status: '状态', + netProfit: '归母净利润', newOrders: '新增订单', backlog: '在手订单', prob: '概率', + }, + ai: { + title: '经营分析 AI 助手', + placeholder: '请输入您的问题,例如:本月营收为什么低于预算?', + send: '发送', thinking: '分析中...', + presetQ1: '本月经营概况?', presetQ2: '哪个产品线毛利率下降最多?', + presetQ3: '存货周转天数超标的品类有哪些?', presetQ4: '海外市场中哪个区域增速最快?', + }, + dashboard: { + overview: '经营全景', finance: '财务表现', marketCustomer: '市场与客户', + supplyChain: '供应链与生产', digitalAI: '数智化进程', riskResilience: '风险与韧性', + }, +}; + +/** 全站仅中文:词典不再按语言索引,useText() 直接把这份对象发给组件 */ +export const texts: I18n = zh; diff --git a/src/modules/tfamd-oee/i18n/useText.ts b/src/modules/tfamd-oee/i18n/useText.ts new file mode 100644 index 0000000..4eeb011 --- /dev/null +++ b/src/modules/tfamd-oee/i18n/useText.ts @@ -0,0 +1,12 @@ +import { texts } from './locales'; +import type { I18n } from './locales'; + +export type { I18n }; + +/** + * 全站只有中文一套文案(本系统不面向日本用户), + * 因此不再需要 Locale 状态、localStorage 记忆与 Provider:直接读词典。 + */ +export function useText(): { t: I18n } { + return { t: texts }; +} diff --git a/src/modules/tfamd-oee/index.css b/src/modules/tfamd-oee/index.css new file mode 100644 index 0000000..3fcb749 --- /dev/null +++ b/src/modules/tfamd-oee/index.css @@ -0,0 +1,116 @@ +.tfamd-root button{ cursor: pointer; }.tfamd-root input,.tfamd-root textarea{ font-family: inherit; } + +/* ═══════════════════════════════════════════ + 太空舱 / 三栏工作区 动效层 + ═══════════════════════════════════════════ */ + +@keyframes tfamd-fade-in{ + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +}@keyframes tfamd-pulse-glow{ + 0%, 100% { opacity: 0.6; } + 50% { opacity: 1; } +}@keyframes tfamd-number-roll{ + from { opacity: 0; transform: translateY(10px); } + to { opacity: 1; transform: translateY(0); } +}@keyframes tfamd-slide-in-left{ + from { opacity: 0; transform: translateX(-20px); } + to { opacity: 1; transform: translateX(0); } +}@keyframes tfamd-slide-in-right{ + from { opacity: 0; transform: translateX(20px); } + to { opacity: 1; transform: translateX(0); } +}@keyframes tfamd-slide-in-up{ + from { opacity: 0; transform: translateY(16px); } + to { opacity: 1; transform: translateY(0); } +}@keyframes tfamd-card-in{ + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +}@keyframes tfamd-notice-in{ + from { opacity: 0; transform: translateX(-12px); } + to { opacity: 1; transform: translateX(0); } +}@keyframes tfamd-content-reveal{ + from { opacity: 0; transform: translateY(18px) scale(0.97); } + to { opacity: 1; transform: translateY(0) scale(1); } +}@keyframes tfamd-space-pulse{ + 0%, 100% { opacity: 0.55; } + 50% { opacity: 1; } +}@keyframes tfamd-glow-pulse{ + 0%, 100% { box-shadow: 0 0 0 rgba(79,70,229,0); } + 50% { box-shadow: 0 0 18px var(--glow-color, rgba(79,70,229,0.35)); } +}@keyframes tfamd-dot-blink{ + 0%, 100% { opacity: 1; transform: scale(1); } + 50% { opacity: 0.35; transform: scale(0.78); } +}@keyframes tfamd-scan-sweep{ + 0% { left: -30%; } + 100% { left: 110%; } +}@keyframes tfamd-stream-caret-blink{ + 0%, 45% { opacity: 1; } + 50%, 95% { opacity: 0; } + 100% { opacity: 1; } +}@keyframes tfamd-typing-dot{ + 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); } + 30% { opacity: 1; transform: translateY(-3px); } +}@keyframes tfamd-bar-grow{ + from { transform: scaleY(0.05); } + to { transform: scaleY(1); } +}@keyframes tfamd-dash-flow{ + to { stroke-dashoffset: -24; } +} +/* 趋势图描线入场(2026-11-14 动效层):polyline 设 pathLength=1 + dasharray=1, + offset 1→0 一次性描出(≤600ms);虚线系列/面积/数据点用 line-fade 淡入,避免与虚线 dasharray 冲突 */ +@keyframes tfamd-line-draw{ + from { stroke-dashoffset: 1; } + to { stroke-dashoffset: 0; } +}@keyframes tfamd-line-fade{ + from { opacity: 0; } + to { opacity: 1; } +} + +/* ═══════════════════════════════════════════ + 指标知识图谱 · 深空叙事动效层 + (恒星呼吸 / 声呐告警 / 轨道旋转 / 传播涟漪 / 雷达扫描 / 星云漂移) + ═══════════════════════════════════════════ */ +@keyframes tfamd-net-breathe{ + 0%, 100% { transform: scale(1); opacity: 0.5; } + 50% { transform: scale(1.16); opacity: 0.95; } +}@keyframes tfamd-net-sonar{ + 0% { transform: scale(1); opacity: 0.5; } + 75%,100% { transform: scale(3.6); opacity: 0; } +}@keyframes tfamd-net-orbit-spin{ to { transform: rotate(360deg); } } +/* 本体裂变:环上药签的入场不再用 animation(fill-mode:both 会把 0% 关键帧钉死, + 动画被挂起时药签永远停在 opacity:0;改由组件内 JS 定时器翻状态 + 内层 的 transition 承担, + 终态恒为 scale(1)/opacity:1)。此处仅保留 keyframes 以备非交互场景复用。 */ +@keyframes tfamd-ont-sat-pop{ + 0% { transform: scale(0.2); opacity: 0; } + 60% { opacity: 1; } + 100% { transform: scale(1); opacity: 1; } +}@keyframes tfamd-net-ripple-in{ + from { transform: scale(0.35); opacity: 0; } + to { transform: scale(1); opacity: 1; } +}@keyframes tfamd-net-radar{ to { transform: rotate(360deg); } }@keyframes tfamd-net-twinkle{ + 0%, 100% { opacity: var(--tw-o, 0.5); } + 50% { opacity: 0.08; } +}@keyframes tfamd-net-nebula{ + 0%, 100% { transform: translate(0, 0) scale(1); } + 50% { transform: translate(-5%, 4%) scale(1.12); } +} + +/* SVG 几何元素统一用 fill-box 做变换基准,保证 scale/rotate 围绕自身中心 */ +.tfamd-root .net-breathe{ transform-box: fill-box; transform-origin: center; animation: tfamd-net-breathe 4.2s ease-in-out infinite; }.tfamd-root .net-sonar{ transform-box: fill-box; transform-origin: center; animation: tfamd-net-sonar 3.6s ease-out infinite; }.tfamd-root .net-sonar-slow{ animation-duration: 5.4s; }.tfamd-root .net-orbit{ transform-box: fill-box; transform-origin: center; animation: tfamd-net-orbit-spin 52s linear infinite; }.tfamd-root .net-orbit-rev{ animation-direction: reverse; animation-duration: 78s; }.tfamd-root .net-ripple{ transform-box: fill-box; transform-origin: center; animation: tfamd-net-ripple-in 0.7s cubic-bezier(0.34,1.56,0.64,1) both; }.tfamd-root .net-twinkle{ animation: tfamd-net-twinkle var(--tw-d, 4s) ease-in-out infinite; animation-delay: var(--tw-delay, 0s); }.tfamd-root .net-nebula{ animation: tfamd-net-nebula var(--nb-d, 46s) ease-in-out infinite alternate; }.tfamd-root .animate-fade-in{ animation: tfamd-fade-in 0.4s ease-out; }.tfamd-root .animate-slide-in{ animation: tfamd-slide-in-left 0.3s ease-out; }.tfamd-root .animate-number{ animation: tfamd-number-roll 0.5s ease-out; }.tfamd-root .space-animate-left{ animation: tfamd-slide-in-left 0.4s cubic-bezier(0.4,0,0.2,1); }.tfamd-root .space-animate-right{ animation: tfamd-slide-in-right 0.4s cubic-bezier(0.4,0,0.2,1); }.tfamd-root .space-animate-up{ animation: tfamd-slide-in-up 0.4s cubic-bezier(0.4,0,0.2,1); }.tfamd-root .card-in{ animation: tfamd-card-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }.tfamd-root .notice-in{ animation: tfamd-notice-in 0.35s cubic-bezier(0.4,0,0.2,1) both; }.tfamd-root .content-reveal{ animation: tfamd-content-reveal 0.5s cubic-bezier(0.34,1.56,0.64,1) both; }.tfamd-root .stream-caret{ display: inline-block; width: 2px; height: 0.95em; margin-left: 2px; vertical-align: -0.12em; background: currentColor; animation: tfamd-stream-caret-blink 1s steps(1) infinite; }.tfamd-root .space-pulse{ animation: tfamd-space-pulse 2.4s ease-in-out infinite; }.tfamd-root .dot-blink{ animation: tfamd-dot-blink 1.6s ease-in-out infinite; }.tfamd-root .glow-pulse{ animation: tfamd-glow-pulse 3s ease-in-out infinite; }.tfamd-root .bar-grow{ animation: tfamd-bar-grow 0.6s cubic-bezier(0.4,0,0.2,1) both; transform-origin: bottom; }.tfamd-root .dash-flow{ animation: tfamd-dash-flow 1.2s linear infinite; }.tfamd-root .line-draw{ animation: tfamd-line-draw 0.6s cubic-bezier(0.4,0,0.2,1) both; } + +/* 滚动条:颜色由 --scroll-thumb 注入(跟随主题 token) */ +.tfamd-root ::-webkit-scrollbar{ width: 5px; height: 5px; }.tfamd-root ::-webkit-scrollbar-track{ background: transparent; }.tfamd-root ::-webkit-scrollbar-thumb{ background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 10px; }.tfamd-root ::-webkit-scrollbar-corner{ background: transparent; }.tfamd-root .space-scroll::-webkit-scrollbar{ width: 4px; height: 8px; }.tfamd-root .space-scroll::-webkit-scrollbar-track{ background: transparent; }.tfamd-root .space-scroll::-webkit-scrollbar-thumb{ background: var(--scroll-thumb, rgba(79,70,229,0.22)); border-radius: 4px; } +/* 自身带圆角又自身滚动的容器:轨道上下各让出一个圆角,拖条不越过圆弧 */ +.tfamd-root .round-scroll::-webkit-scrollbar-track{ margin-block: 14px; } + +/* 面板通用过渡 */ +.tfamd-root .panel-shell{ transition: width 0.3s cubic-bezier(0.4,0,0.2,1); }.tfamd-root .ghost-btn{ transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease; }.tfamd-root .ghost-btn:hover{ background: var(--hover-bg, rgba(79,70,229,0.07)); } + +/* 统计砖 hover 微 lift(2026-11-14 动效层):只动 transform/shadow,不改布局度量, + 等分/stretch/底边对齐红线不受影响;reduced-motion 全局开关已覆盖 transition */ +.tfamd-root .tile-lift{ transition: transform 0.18s ease, box-shadow 0.18s ease; }.tfamd-root .tile-lift:hover{ transform: translateY(-2px); box-shadow: 0 6px 16px rgba(15, 23, 42, 0.10); }@media (prefers-reduced-motion: reduce){.tfamd-root *,.tfamd-root *::before,.tfamd-root *::after{ + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/index.ts b/src/modules/tfamd-oee/index.ts new file mode 100644 index 0000000..ebf2b87 --- /dev/null +++ b/src/modules/tfamd-oee/index.ts @@ -0,0 +1,14 @@ +import type { ModuleConfig } from '../registry'; + +export const moduleConfig: ModuleConfig = { + id: 'tfamd-oee', + name: '通富超威 OEE 智能分析', + description: '通富超威 OEE 指标中台:指标树、质量流程、知识图谱、3D 线体与 OEE 智能体全链路分析', + icon: 'Gauge', + path: '/tfamd-oee', + accentColor: '#56ace0', + accentColorLight: '#006ca7', + gradient: 'linear-gradient(135deg, #0a1a2f, #0e3a5f, #1267a8)', + gradientLight: 'linear-gradient(135deg, #eaf3fc, #d8eaf8, #c4dff4)', + tags: ['OEE', '设备效率', '智能体'], +}; diff --git a/src/modules/tfamd-oee/lib/metric.ts b/src/modules/tfamd-oee/lib/metric.ts new file mode 100644 index 0000000..781fc0f --- /dev/null +++ b/src/modules/tfamd-oee/lib/metric.ts @@ -0,0 +1,77 @@ +import type { ThemeTokens } from '../context/ThemeContext'; +import type { MetricNode } from '../data/sqlite'; + +export function alertColor(alert: string, tokens: ThemeTokens): string { + if (alert === 'red') return tokens.danger; + if (alert === 'yellow') return tokens.warning; + return tokens.success; +} + +/** 偏差:正数代表优于目标(已按 polarity 归一方向) */ +export function gapOf(node: { value: number; target: number; polarity: string }): number { + const raw = node.value - node.target; + return +(node.polarity === 'down' ? -raw : raw).toFixed(2); +} + +/** 达成度(%),越低越好类指标取倒数口径 */ +export function achieveRate(node: { value: number; target: number; polarity: string }): number { + if (!node.target) return 100; + const r = node.polarity === 'down' + ? (node.target / (node.value || 1)) * 100 + : (node.value / node.target) * 100; + return +Math.min(r, 999).toFixed(1); +} + +/** 预算执行临界值(%):达成率跌破此线即进入红色档 */ +export const EXEC_RED_LINE = 90; + +/** 预算执行分档配色:达标绿 → 未达标黄 → 跌破临界值红。各面板统一走这里,避免阈值各说各话 */ +export function execColor(rate: number, tokens: ThemeTokens): string { + if (rate >= 100) return tokens.success; + if (rate >= EXEC_RED_LINE) return tokens.warning; + return tokens.danger; +} + +export function fmt(n: number | null | undefined, digits = 1): string { + if (n === null || n === undefined || Number.isNaN(n)) return '-'; + return Math.abs(n) >= 1000 + ? n.toLocaleString('en-US', { maximumFractionDigits: 0 }) + : n.toFixed(digits).replace(/\.0$/, ''); +} + +/** 带符号显示,用于偏差列 */ +export function fmtSigned(n: number, digits = 1): string { + return `${n > 0 ? '+' : ''}${fmt(n, digits)}`; +} + +/** 归属链路 codes:['OV','D-Q','R04'] */ +export function chainOf(code: string, byCode: Map): string[] { + const out: string[] = []; + let cur = byCode.get(code); + let guard = 0; + while (cur && guard++ < 10) { + out.unshift(cur.code); + cur = cur.parent_code ? byCode.get(cur.parent_code) : undefined; + } + return out; +} + +/** 子孙节点(含自身下层全部层级) */ +export function descendantsOf(code: string, flat: MetricNode[]): MetricNode[] { + const childrenOf = new Map(); + flat.forEach(n => { + if (!n.parent_code) return; + const arr = childrenOf.get(n.parent_code) ?? []; + arr.push(n); + childrenOf.set(n.parent_code, arr); + }); + const out: MetricNode[] = []; + const stack = [...(childrenOf.get(code) ?? [])]; + while (stack.length) { + const n = stack.pop()!; + out.push(n); + (childrenOf.get(n.code) ?? []).forEach(c => stack.push(c)); + } + return out; +} + diff --git a/src/modules/tfamd-oee/lib/oee/adapterDek.ts b/src/modules/tfamd-oee/lib/oee/adapterDek.ts new file mode 100644 index 0000000..8e86fb3 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/adapterDek.ts @@ -0,0 +1,332 @@ +/** + * L1 适配器 · DEK 印刷机(定宽 91 字符 EVENT.DAT)。 + * + * ★ 零 IO 纯函数:不 import data/、不 fetch、不读时钟。字典(码表)由调用方注入, + * 与 lossBuckets 注入 eventDefByInstanceId 同一纪律。守断言①(血缘可追)。 + * + * 规划书附录 D.3 的五个适配器方法在此逐一落地: + * parse(raw_line) / normalize(event) / dedup_key(event) / clock_correct(timestamp) / evidence_ref(event) + * + * 定宽切列(附录 D.3 原文):日期[0:10] 时间[11:19] 事件码[20:25] 文本[26:71] 参数[71:91] + * 10 + 1 + 8 + 1 + 5 + 1 + 45 + 20 = 91 + * + * ⚠ 两处必须诚实标注的演示约定: + * 1. 客户 96 事件码全表**未提供**,只知 31317/31318 是改钟标记〔POC〕。本适配器用的码表 + * 是演示子集,由 data/oee/dekCodes.ts 注入并标 DEMO,接入前必须替换为客户全表。 + * 2. 改钟参数语义(off=秒)是**演示协议**,客户实际格式待确认。校正算法本身是通用的: + * 按文件顺序累计偏移,原始时间与校正时间双字段保留(DQ-01)。 + */ +import type { EventDef, EventInstance, RawLogLine } from '../../types/oee'; +import { toEpoch, type LotWindow } from './pairing'; + +/** 定宽行宽。不足或超出都判为格式异常(DQ-03 编码/格式问题的入口)。 */ +export const DEK_LINE_WIDTH = 91; + +/** 改钟标记:跳过,不入事件表(附录 D.3 / 附录 H 原文)。 */ +export const DEK_CLOCK_MARKS: readonly string[] = ['31317', '31318']; + +/** 产出锚点伪码:不在 48 事件字典内,只用于推 lot 窗口与投入/合格数。 */ +export const OUTPUT_ANCHOR = 'OUTPUT_ANCHOR'; +/** 板级开始行:只用于确定 lot 窗口起点,**不计数**,否则一块板会被算成两块。 */ +export const OUTPUT_ANCHOR_START = 'OUTPUT_ANCHOR_START'; + +export interface DekParsed { + date: string; + time: string; + code: string; + text: string; + params: string; + /** 设备原始时刻(未校钟),ISO */ + rawTime: string; + lineNo: number; + filePath: string; + rawText: string; +} + +export interface DekCodeMap { + /** DEK 事件码 → 48 字典事件码,或 OUTPUT_ANCHOR */ + [dekCode: string]: string; +} + +/** parse(raw_line):定宽切列。宽度不符返回 null,由调用方记为格式异常,不静默丢弃。 */ +export function parseDekLine(rawText: string, lineNo: number, filePath: string): DekParsed | null { + if (rawText.length !== DEK_LINE_WIDTH) return null; + const date = rawText.slice(0, 10); + const time = rawText.slice(11, 19); + const code = rawText.slice(20, 25).trim(); + const text = rawText.slice(26, 71).trim(); + const params = rawText.slice(71, 91).trim(); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null; + if (!/^\d{2}:\d{2}:\d{2}$/.test(time)) return null; + if (!/^\d{5}$/.test(code)) return null; + return { date, time, code, text, params, rawTime: `${date}T${time}Z`, lineNo, filePath, rawText }; +} + +/** 参数区解析:`k=v;k=v`,最多 20 字符。空串返回 {}。 */ +export function parseDekParams(params: string): Record { + const out: Record = {}; + if (!params) return out; + for (const seg of params.split(';')) { + const eq = seg.indexOf('='); + if (eq <= 0) continue; + out[seg.slice(0, eq).trim()] = seg.slice(eq + 1).trim(); + } + return out; +} + +/** 文本区取 lot 号。DEK 信号最全(★★★ 单件级),lot 直接印在消息文本里。 */ +export function lotFromText(text: string): string | undefined { + const m = /LOT-([A-Z0-9]+)/.exec(text); + return m ? `LOT-${m[1]}` : undefined; +} + +/** HHMM → 当日 ISO。用于 DERIVED 事件的 intervalStart/intervalEnd。 */ +export function hhmmToIso(date: string, hhmm: string): string { + if (!/^\d{4}$/.test(hhmm)) throw new Error(`不可解析的 HHMM:${hhmm}`); + return `${date}T${hhmm.slice(0, 2)}:${hhmm.slice(2, 4)}:00Z`; +} + +/** dedup_key(event):设备 + 码 + 原始时刻 + 参数。同一行重复采集不会变成两条事件。 */ +export function dekDedupKey(device: string, p: DekParsed): string { + return `${device}|${p.code}|${p.rawTime}|${p.params}`; +} + +export interface ClockCorrected { + correctedTime: string; + clockOffsetSec: number; + isCorrected: boolean; +} + +/** + * clock_correct(timestamp):按文件顺序累计改钟偏移。 + * 31317/31318 自身不产出事件,但 31318 的 off 参数声明"自此生效的偏移秒数"。 + * 原始时刻一律保留,校正只新增字段——这是 DQ-01 双时间字段的物理基础。 + */ +export function correctDekClock(lines: DekParsed[]): ClockCorrected[] { + let offset = 0; + const out: ClockCorrected[] = []; + for (const p of lines) { + if (DEK_CLOCK_MARKS.includes(p.code)) { + const prm = parseDekParams(p.params); + if (p.code === '31318' && prm.off !== undefined) { + const n = Number(prm.off); + if (Number.isFinite(n)) offset = n; + } + // 改钟标记本身不校时(它不是生产事件),但仍占一行,保持行号对齐 + out.push({ correctedTime: p.rawTime, clockOffsetSec: offset, isCorrected: false }); + continue; + } + const corrected = toEpoch(p.rawTime) + offset; + out.push({ + correctedTime: isoOf(corrected), + clockOffsetSec: offset, + isCorrected: offset !== 0, + }); + } + return out; +} + +/** epoch → ISO。与 stateMachine.isoOf 同规则,此处独立实现避免引擎间横向依赖。 */ +function isoOf(epochSec: number): string { + const d = new Date(epochSec * 1000); + const p = (n: number) => String(n).padStart(2, '0'); + return `${d.getUTCFullYear()}-${p(d.getUTCMonth() + 1)}-${p(d.getUTCDate())}T${p(d.getUTCHours())}:${p(d.getUTCMinutes())}:${p(d.getUTCSeconds())}Z`; +} + +/** evidence_ref(event):对外只给行号与摘要哈希,全文仅内网审计链路可取〔方案〕。 */ +export function dekEvidenceRef(line: RawLogLine): EventInstance['evidence'] { + return { rawLineId: line.id, lineNo: line.lineNo, filePath: line.filePath, digest: line.digest }; +} + +/** 板级产出锚点。不是 48 字典事件,不参与损失归口,只用于推 lot 窗口与 N/good。 */ +export interface OutputAnchor { + device: string; + lotId: string; + boardSeq: number; + /** 实测单板节拍(秒)。P 因子的证据:Σcycle 与 N×ICT 的差就是速度损失。 */ + cycleSec: number; + good: boolean; + epoch: number; + /** START 只定窗口起点;COMPLETE 才计入 N/good。 */ + phase: 'START' | 'COMPLETE'; + rawLineId: string; + lineNo: number; +} + +export interface NormalizeResult { + events: EventInstance[]; + anchors: OutputAnchor[]; + /** 改钟标记行(跳过不入事件表,但留证供 DQ-01 与审计) */ + clockMarks: { lineNo: number; code: string; rawTime: string; offsetSec: number }[]; + /** 码表里没有的码 → 显式缺口,不静默丢弃、不猜归口 */ + unmapped: { lineNo: number; code: string; rawTime: string }[]; + /** 定宽解析失败的行 */ + malformed: { lineNo: number; length: number }[]; + /** + * 去重点在 L1,被丢弃的重复行必须**留证上报**: + * DQ-09 要在治理台显示"丢弃并计数",若只在已去重的事件表上再数一遍,永远是 0。 + * keptLineNo 给出血缘——哪一行活了下来,可回查原文。 + */ + duplicates: { lineNo: number; keptLineNo: number; code: string; rawTime: string; dedupKey: string }[]; + /** 进入去重器的记录数(已解析、已映射、含产出锚点),作为重复率分母 */ + dedupScanned: number; +} + +/** + * normalize(event):原始日志行 → 事件实例 + 产出锚点。 + * 一次处理整个文件(按行号有序),因为校钟需要顺序上下文。 + */ +export function normalizeDekLog( + lines: RawLogLine[], + codeMap: DekCodeMap, + defs: Record, + device: string, +): NormalizeResult { + const ordered = [...lines].sort((a, b) => a.lineNo - b.lineNo); + /** 解析结果与原始行成对保存,避免后面按行号回查(O(n²) 且易错配) */ + const parsed: { p: DekParsed; line: RawLogLine }[] = []; + const malformed: NormalizeResult['malformed'] = []; + + for (const ln of ordered) { + const p = parseDekLine(ln.rawText, ln.lineNo, ln.filePath); + if (!p) { malformed.push({ lineNo: ln.lineNo, length: ln.rawText.length }); continue; } + parsed.push({ p, line: ln }); + } + + const corrected = correctDekClock(parsed.map((x) => x.p)); + const events: EventInstance[] = []; + const anchors: OutputAnchor[] = []; + const clockMarks: NormalizeResult['clockMarks'] = []; + const unmapped: NormalizeResult['unmapped'] = []; + const duplicates: NormalizeResult['duplicates'] = []; + let dedupScanned = 0; + /** dedupKey → 存活行号,供重复行回查血缘 */ + const seen = new Map(); + + for (let i = 0; i < parsed.length; i++) { + const { p, line: rawLine } = parsed[i]; + const c = corrected[i]; + const evidence = dekEvidenceRef(rawLine); + + if (DEK_CLOCK_MARKS.includes(p.code)) { + clockMarks.push({ lineNo: p.lineNo, code: p.code, rawTime: p.rawTime, offsetSec: c.clockOffsetSec }); + continue; + } + + const target = codeMap[p.code]; + if (!target) { unmapped.push({ lineNo: p.lineNo, code: p.code, rawTime: p.rawTime }); continue; } + + const dedupKey = dekDedupKey(device, p); + dedupScanned += 1; + const keptLineNo = seen.get(dedupKey); + if (keptLineNo !== undefined) { + // 增量扫描重复采集 → 丢弃但留证,交 DQ-09 计数;不重复计数、不让时长翻倍 + duplicates.push({ lineNo: p.lineNo, keptLineNo, code: p.code, rawTime: p.rawTime, dedupKey }); + continue; + } + seen.set(dedupKey, p.lineNo); + + const prm = parseDekParams(p.params); + + if (target === OUTPUT_ANCHOR || target === OUTPUT_ANCHOR_START) { + const lotId = lotFromText(p.text); + // 无 lot 号的产出锚点不编造归属,交由五级级联归因处理(此处直接记缺口) + if (!lotId) { unmapped.push({ lineNo: p.lineNo, code: p.code, rawTime: p.rawTime }); continue; } + anchors.push({ + device, + lotId, + boardSeq: Number(prm.b ?? 0), + cycleSec: Number(prm.c ?? 0), + good: prm.r !== '0', + epoch: toEpoch(c.correctedTime), + phase: target === OUTPUT_ANCHOR_START ? 'START' : 'COMPLETE', + rawLineId: evidence.rawLineId, + lineNo: evidence.lineNo, + }); + continue; + } + + const def = defs[target]; + if (!def) { unmapped.push({ lineNo: p.lineNo, code: p.code, rawTime: p.rawTime }); continue; } + + const params: Record = {}; + // DERIVED 自含区间:把 HHMM 展开成 ISO,pairing 的①分支直接成对 + if (def.form === 'DERIVED' && prm.s && prm.e) { + params.intervalStart = hhmmToIso(p.date, prm.s); + params.intervalEnd = hhmmToIso(p.date, prm.e); + } + for (const [k, v] of Object.entries(prm)) { + if (k === 's' || k === 'e') continue; + params[k] = v; + } + + const role = /—\s*开始/.test(def.name) ? 'START' as const + : /—\s*结束/.test(def.name) ? 'END' as const : undefined; + + events.push({ + id: `ev-${device}-${p.lineNo}`, + defCode: def.code, + device, + rawTime: p.rawTime, + correctedTime: c.correctedTime, + ...(c.clockOffsetSec !== 0 ? { clockOffsetSec: c.clockOffsetSec } : {}), + form: def.form, + ...(role ? { pairRole: role } : {}), + isCorrected: c.isCorrected, + dedupKey, + evidence, + params, + }); + } + + return { events, anchors, clockMarks, unmapped, malformed, duplicates, dedupScanned }; +} + +/** + * 产出锚点 → lot 窗口。窗口 = 该 lot 首板开始 → 末板完成,N/good 由锚点计数得出。 + * ★ 不手填 lot 窗口:让"日志→产出→RUN 段"这条链真的跑通,断言①才有意义。 + * 板级间隔小于间隙阈值时由状态机填为 RUN,故 RT = 窗口时长,P = N×ICT/RT < 1 即速度损失。 + */ +export function lotWindowsFromAnchors(anchors: OutputAnchor[], device: string): LotWindow[] { + const byLot = new Map(); + for (const a of anchors) { + if (a.device !== device) continue; + const arr = byLot.get(a.lotId) ?? []; + arr.push(a); + byLot.set(a.lotId, arr); + } + const out: LotWindow[] = []; + for (const [lotId, arr] of byLot) { + arr.sort((x, y) => x.epoch - y.epoch || x.boardSeq - y.boardSeq); + const done = arr.filter((a) => a.phase === 'COMPLETE'); + // 只有开始行没有完成行 → 该 lot 无产出证据,不造窗口(N=0 会让 P/Q 失去意义) + if (done.length === 0) continue; + const first = arr[0]; + const last = done[done.length - 1]; + out.push({ + lotId, + device, + startEpoch: first.epoch, + // 完成行的时间戳**就是**末板完成时刻,不能再加一次节拍(否则窗口超出块尾一个节拍) + endEpoch: last.epoch, + // DEK 日志直接印 lot 号 → 设备自识别(置信度 1.00) + selfIdentified: true, + outputQty: done.length, + goodQty: done.filter((a) => a.good).length, + }); + } + return out.sort((a, b) => a.startEpoch - b.startEpoch || a.lotId.localeCompare(b.lotId)); +} + +/** + * 摘要哈希(FNV-1a 32 位)。**演示用非密码学摘要**,只为血缘比对与去重, + * 生产环境应换 SHA-256 并由采集侧计算。纯函数、确定性、不依赖 crypto。 + */ +export function digestOf(text: string): string { + let h = 0x811c9dc5; + for (let i = 0; i < text.length; i++) { + h ^= text.charCodeAt(i); + h = Math.imul(h, 0x01000193) >>> 0; + } + return h.toString(16).padStart(8, '0'); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/caliber.ts b/src/modules/tfamd-oee/lib/oee/caliber.ts new file mode 100644 index 0000000..54ff5bb --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/caliber.ts @@ -0,0 +1,304 @@ +/** + * L2 引擎 · 口径解析与版本管理(规划书 4.1.7 / 附录 E)。 + * + * ★ 零 IO 纯函数。守断言②(四处读数一致)与断言⑩(跨版本对比拒绝)。 + * + * 三条硬规则: + * 1. **全站唯一来源**:任何页面/服务/智能体读数都必须带同一个 caliberVersion, + * 不允许组件自己二次计算(断言②)。 + * 2. **不发布单一数字**:双口径并行展示、差异高亮;口径切换需 IE 审批并留审计轨迹。 + * 3. **跨版本对比默认拒绝**:两个 caliber_version 的结果不可直接相减, + * 必须显式确认后才允许,且返回里带拒绝理由(断言⑩)。 + * + * ★ 本次不安排口径工作坊 ⇒ 28 项 signedOff 全 false。 + * 默认值生效但**无人签字**:UI 必须显示「待 IE 签字」,P0 项标灰不标绿。 + * 本引擎不提供任何"假装已签字"的捷径。 + * + * ★ 敏感性 4 议题(决定"算出来是多少")与 P0 16 项(决定"能不能算")**不是同一集合**: + * 前者 5 个条目(C03/C04/C06/C09/C10),后者 16 个条目,交集只有 C03/C06/C09。 + */ +import { + EPS, + type CaliberConfig, type CaliberItem, +} from '../../types/oee'; + +/** 4 项敏感性议题 → 条目映射(与 data/oee/calibers28.ts 的 SENSITIVITY_ISSUES 同源同义)。 */ +export const SENSITIVITY_ISSUE_ITEMS = { + planBoundary: ['C09'], + occRule: ['C04'], + qDefinition: ['C03', 'C10'], + ftPmIncluded: ['C06'], +} as const; + +export type SensitivityIssue = keyof typeof SENSITIVITY_ISSUE_ITEMS; + +export const SENSITIVITY_ISSUE_LABEL: Record = { + planBoundary: 'Plan 边界', + occRule: 'Occ 判定', + qDefinition: 'Q 定义', + ftPmIncluded: 'FT 的 PM 是否计入', +}; + +/** 取值读取。缺项返回 undefined,由调用方决定是否报缺口,不静默给默认值。 */ +export function caliberValue(config: CaliberConfig, id: string): string | number | boolean | undefined { + return config.items[id]?.defaultValue; +} + +/** 缺项即抛:用于"这项必须有值才能算"的路径,宁可失败也不猜。 */ +export function requireCaliberValue(config: CaliberConfig, id: string): string | number | boolean { + const v = caliberValue(config, id); + if (v === undefined) throw new Error(`口径 ${id} 在版本 ${config.version} 中不存在,无法计算`); + return v; +} + +/** + * 从条目现推敏感性快照。**唯一推导入口**: + * resolveCaliber 每次都重算,数据层的字面量由校验脚本比对,防止两处漂移。 + * qDefinition 同时受 C03(终测/FPY/UTT)与 C10(工程批是否剔除)影响,故两者都进快照。 + */ +export function sensitivitySnapshotOf(items: Record): CaliberConfig['sensitivitySnapshot'] { + const s = (id: string) => String(items[id]?.defaultValue ?? ''); + const c06 = s('C06'); + return { + planBoundary: s('C09'), + occRule: s('C04'), + qDefinition: [s('C03'), s('C10')].filter(Boolean).join('|'), + // "不计入…" 必须判 false,不能用 includes('计入') 一把抓 + ftPmIncluded: /计入/.test(c06) && !/^不/.test(c06), + }; +} + +/** 版本号递增:v0.1-demo → v0.1-demo.r1 → v0.1-demo.r2(不叠加后缀)。 */ +export function bumpVersion(version: string, revision: number): string { + const root = version.replace(/\.r\d+$/, ''); + return `${root}.r${revision}`; +} + +export interface ResolveOptions { + /** 修订号,由调用方(D 类提交 / 配置中心保存)递增,引擎不维护全局计数 */ + revision?: number; + effectiveFrom?: string; + effectiveTo?: string; +} + +/** + * 解析口径:把覆盖值合进条目,生成**新对象**(绝不改入参)。 + * 只有取值真的变了才递增版本号——改备注、改签字状态不影响 OEE,不该产生新版本。 + */ +export function resolveCaliber( + base: CaliberConfig, + overrides?: Record, + opts: ResolveOptions = {}, +): CaliberConfig { + const items: Record = {}; + const changed: string[] = []; + for (const [id, item] of Object.entries(base.items)) { + const ov = overrides?.[id]; + const hit = ov !== undefined && !sameValue(ov, item.defaultValue); + if (hit) changed.push(id); + items[id] = hit ? { ...item, defaultValue: ov } : { ...item }; + } + // 覆盖里出现字典外的编号 ⇒ 显式失败,不静默丢弃(防"以为改了其实没改") + const unknown = Object.keys(overrides ?? {}).filter((id) => !base.items[id]); + if (unknown.length) throw new Error(`口径覆盖含未知编号:${unknown.join(', ')}`); + + const version = changed.length ? bumpVersion(base.version, opts.revision ?? 1) : base.version; + return { + version, + items, + effectiveFrom: opts.effectiveFrom ?? base.effectiveFrom, + ...(opts.effectiveTo ?? base.effectiveTo ? { effectiveTo: opts.effectiveTo ?? base.effectiveTo } : {}), + sensitivitySnapshot: sensitivitySnapshotOf(items), + }; +} + +function sameValue(a: string | number | boolean, b: string | number | boolean): boolean { + if (typeof a === 'number' && typeof b === 'number') return Math.abs(a - b) < EPS; + return a === b; +} + +/** + * 签字。**不递增版本号**:签字改的是治理状态,不改取值,OEE 数值不变。 + * 只允许对已存在的条目签字;未知编号抛错。 + */ +export function signOff(config: CaliberConfig, ids: string[]): CaliberConfig { + const unknown = ids.filter((id) => !config.items[id]); + if (unknown.length) throw new Error(`签字含未知口径编号:${unknown.join(', ')}`); + const items = { ...config.items }; + for (const id of ids) items[id] = { ...items[id], signedOff: true }; + return { ...config, items, sensitivitySnapshot: sensitivitySnapshotOf(items) }; +} + +export interface CaliberChange { + id: string; + name: string; + before: string | number | boolean; + after: string | number | boolean; + isSensitivityKey: boolean; + priority: CaliberItem['priority']; +} + +export interface VersionDiff { + sameVersion: boolean; + versionA: string; + versionB: string; + changes: CaliberChange[]; + /** 命中敏感性议题的变更 —— 这些会改变 OEE 绝对值,必须 IE 定版 */ + sensitivityChanges: CaliberChange[]; + affectedIssues: SensitivityIssue[]; + /** 是否可直接对比。跨版本一律 false,除非显式确认 */ + comparable: boolean; + reason: string; +} + +/** 版本差异。只比取值,不比签字状态(签字不影响数值)。 */ +export function diffVersions(a: CaliberConfig, b: CaliberConfig): VersionDiff { + const ids = [...new Set([...Object.keys(a.items), ...Object.keys(b.items)])].sort(); + const changes: CaliberChange[] = []; + for (const id of ids) { + const x = a.items[id]; + const y = b.items[id]; + if (!x || !y) { + changes.push({ + id, name: x?.name ?? y?.name ?? id, + before: x?.defaultValue ?? '(不存在)', after: y?.defaultValue ?? '(不存在)', + isSensitivityKey: (x ?? y)!.isSensitivityKey, priority: (x ?? y)!.priority, + }); + continue; + } + if (!sameValue(x.defaultValue, y.defaultValue)) { + changes.push({ + id, name: x.name, before: x.defaultValue, after: y.defaultValue, + isSensitivityKey: x.isSensitivityKey, priority: x.priority, + }); + } + } + const sensitivityChanges = changes.filter((c) => c.isSensitivityKey); + const affectedIssues = (Object.keys(SENSITIVITY_ISSUE_ITEMS) as SensitivityIssue[]) + .filter((k) => SENSITIVITY_ISSUE_ITEMS[k].some((id) => changes.some((c) => c.id === id))); + const sameVersion = a.version === b.version; + return { + sameVersion, versionA: a.version, versionB: b.version, + changes, sensitivityChanges, affectedIssues, + comparable: sameVersion, + reason: sameVersion + ? '同一口径版本,可直接对比' + : `跨口径版本(${a.version} vs ${b.version})默认拒绝直接对比:` + + `${changes.length} 项取值不同,其中 ${sensitivityChanges.length} 项属敏感性议题` + + (affectedIssues.length ? `(${affectedIssues.map((i) => SENSITIVITY_ISSUE_LABEL[i]).join('、')})` : '') + + '。需显式确认后方可并列展示,且不得相减出"改善幅度"。', + }; +} + +/** + * 跨版本对比闸门(断言⑩)。默认拒绝;显式确认后也只允许**并列展示**, + * 不允许把差值当作改善成果——口径变了,差值里混着口径效应。 + */ +export function compareAcrossVersions( + a: CaliberConfig, + b: CaliberConfig, + opts: { acknowledgedBy?: string; allowCrossVersion?: boolean } = {}, +): { allowed: boolean; diff: VersionDiff; notice: string } { + const diff = diffVersions(a, b); + if (diff.sameVersion) { + return { allowed: true, diff, notice: '同一口径版本,允许对比与相减。' }; + } + if (!opts.allowCrossVersion || !opts.acknowledgedBy) { + return { allowed: false, diff, notice: `拒绝跨版本对比:${diff.reason}` }; + } + return { + allowed: true, diff, + notice: `已由 ${opts.acknowledgedBy} 确认跨版本并列展示(${a.version} / ${b.version})。` + + '仅并列,不相减:差值含口径效应,不得作为改善成果发布。', + }; +} + +/** 同一报表内版本号必须唯一(DQ-12 的引擎侧前置校验)。 */ +export function assertSingleVersion(versions: string[]): { ok: boolean; uniq: string[]; reason: string } { + const uniq = [...new Set(versions)]; + return { + ok: uniq.length <= 1, + uniq, + reason: uniq.length <= 1 + ? `口径版本唯一:${uniq[0] ?? '(空)'}` + : `混用 ${uniq.length} 个口径版本:${uniq.join(' / ')},触发 DQ-12 阻断`, + }; +} + +export interface SignOffStatus { + total: number; + signed: number; + unsigned: number; + p0Total: number; + p0Unsigned: number; + sensitivityTotal: number; + sensitivityUnsigned: number; + allSigned: boolean; + /** UI 直接用的话术与色调。P0 未签字 ⇒ gray,绝不 green */ + uiLabel: string; + p0Tone: 'gray' | 'green'; +} + +/** 签字状态。原型默认全 false ⇒ uiLabel 必须是「待 IE 签字」,p0Tone 必须是 gray。 */ +export function signOffStatus(config: CaliberConfig): SignOffStatus { + const items = Object.values(config.items); + const p0 = items.filter((i) => i.priority === 'P0'); + const sens = items.filter((i) => i.isSensitivityKey); + const signed = items.filter((i) => i.signedOff).length; + const p0Unsigned = p0.filter((i) => !i.signedOff).length; + const sensitivityUnsigned = sens.filter((i) => !i.signedOff).length; + const allSigned = signed === items.length && items.length > 0; + return { + total: items.length, signed, unsigned: items.length - signed, + p0Total: p0.length, p0Unsigned, + sensitivityTotal: sens.length, sensitivityUnsigned, + allSigned, + uiLabel: allSigned + ? `口径 ${config.version} 已签字(${signed}/${items.length})` + : `口径 ${config.version} 待 IE 签字(已签 ${signed}/${items.length},P0 未签 ${p0Unsigned} 项)`, + p0Tone: p0Unsigned === 0 ? 'green' : 'gray', + }; +} + +/** 敏感性条目(决定 OEE 绝对值的 5 项)。 */ +export function sensitivityItems(config: CaliberConfig): CaliberItem[] { + return Object.values(config.items).filter((i) => i.isSensitivityKey).sort((a, b) => a.id.localeCompare(b.id)); +} + +/** 按议题分组,供口径工作坊议程与配置中心分区展示。 */ +export function groupByIssue(config: CaliberConfig): Record { + const out = {} as Record; + for (const k of Object.keys(SENSITIVITY_ISSUE_ITEMS) as SensitivityIssue[]) { + out[k] = SENSITIVITY_ISSUE_ITEMS[k].map((id) => config.items[id]).filter(Boolean); + } + return out; +} + +/** 字典自检:28 项、P0=16/P1=11/P2=1、敏感性 5 项覆盖 4 议题、快照与条目一致。 */ +export function checkCaliberDictionary(config: CaliberConfig): { ok: boolean; problems: string[] } { + const problems: string[] = []; + const items = Object.values(config.items); + if (items.length !== 28) problems.push(`口径条目 ${items.length} ≠ 28`); + const ids = items.map((i) => i.id).sort(); + const expectIds = Array.from({ length: 28 }, (_, k) => `C${String(k + 1).padStart(2, '0')}`); + if (ids.join(',') !== expectIds.join(',')) problems.push('编号不是 C01..C28 连续无缺'); + const p0 = items.filter((i) => i.priority === 'P0').length; + const p1 = items.filter((i) => i.priority === 'P1').length; + const p2 = items.filter((i) => i.priority === 'P2').length; + if (p0 !== 16 || p1 !== 11 || p2 !== 1) problems.push(`优先级分布 P0=${p0}/P1=${p1}/P2=${p2} ≠ 16/11/1`); + const sens = items.filter((i) => i.isSensitivityKey); + if (sens.length !== 5) problems.push(`敏感性条目 ${sens.length} ≠ 5`); + const mapped = Object.values(SENSITIVITY_ISSUE_ITEMS).flat(); + if (sens.map((i) => i.id).sort().join(',') !== [...mapped].sort().join(',')) { + problems.push('敏感性条目与 4 议题映射不一致'); + } + const snap = sensitivitySnapshotOf(config.items); + for (const k of Object.keys(snap) as (keyof typeof snap)[]) { + if (snap[k] !== config.sensitivitySnapshot[k]) problems.push(`快照 ${k} 与条目现推值不一致`); + } + for (const i of items) { + if (!i.name || !i.note) problems.push(`${i.id} 缺名称或说明`); + if (i.defaultValue === undefined || i.defaultValue === '') problems.push(`${i.id} 缺默认值`); + } + return { ok: problems.length === 0, problems }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/closure.ts b/src/modules/tfamd-oee/lib/oee/closure.ts new file mode 100644 index 0000000..93e58cc --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/closure.ts @@ -0,0 +1,205 @@ +/** + * L2 引擎 · 改善闭环六态 + 四项必填校验(断言⑨「四项必填」)。 + * + * 来源:《OEE分析AI原型系统构建建议书-2026-11-12.md》§5.1.3 / §5.4.4(line 2103-2116)。 + * 闭环跟踪智能体(A4)演示:用户「把建议 1 派给设备科」→ canDispatch() 校验四项必填: + * 负责人 ✓ / 完成时限 ✗「请指定完成时限」/ 预期收益 ✓ / 验证方式 ✗「请指定验证方式…」 + * → **拒绝派发**,任务停在「待审核」;补齐后 → 「已派发」,SLA 计时开始。 + * + * 六态(TaskState,与 StepChain 的 ChainTaskState 七态是两套,不得共用): + * 待生成 DRAFT → 待审核 PENDING_REVIEW → 已派发 DISPATCHED → 执行中 IN_PROGRESS + * → 已验证 VERIFIED → 已归档 ARCHIVED + * 待审核可退回待生成(补录);已归档为终态。 + * + * 四条诚实性纪律: + * 1. **缺一项即拒派**:四项(负责人/完成时限/预期收益/验证方式)任一缺失或非法 → canDispatch=false, + * 任务**停在待审核**,绝不静默推进到已派发。 + * 2. **只在派发口设闸**:四项必填是 PENDING_REVIEW→DISPATCHED 的前置;其余合法流转不额外加闸 + * (证据链完备性属断言⑩,不在本模块越权判定)。 + * 3. **纯函数 + 注入时钟**:transition 不改入参、不读 Date.now;history 的 at/by 由调用方注入,可重放。 + * 4. **收益给区间**:expectedBenefit 必须是 {min,max,unit} 且 max≥min、unit 非空; + * 点值(min===max)不阻断派发(属「已填」),但 UI 入口应引导给区间。 + * + * 本模块只 import 契约层(types/oee),不 import data/,符合 verify-oee-purity 白名单。 + */ +import { + TASK_STATES, TASK_STATE_LABEL, + type TaskState, type ImprovementTask, +} from '../../types/oee'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、四项必填(派发前置) + * ══════════════════════════════════════════════════════════════════ */ + +export type RequiredFieldKey = 'owner' | 'dueDate' | 'expectedBenefit' | 'verificationResult'; + +export interface RequiredField { + key: RequiredFieldKey; + label: string; + /** 缺失时给用户的提示原文(与建议书 §5.4.4 一致) */ + prompt: string; +} + +/** 四项必填,顺序即建议书表格顺序。全站唯一来源,UI 不得另写一套。 */ +export const REQUIRED_FIELDS: RequiredField[] = [ + { key: 'owner', label: '负责人', prompt: '请指定负责人' }, + { key: 'dueDate', label: '完成时限', prompt: '请指定完成时限' }, + { key: 'expectedBenefit', label: '预期收益', prompt: '请指定预期收益(区间,如 200–400min/月)' }, + { key: 'verificationResult', label: '验证方式', prompt: '请指定验证方式(如:连续 5 班 tray 类停机时长 f.key); + +export interface RequiredFieldGap { + key: RequiredFieldKey; + label: string; + prompt: string; + /** 缺失原因:未填 / 非法(如收益区间 max typeof s === 'string' && s.trim().length > 0; + +/** 预期收益是否合法:{min,max,unit},min/max 为有限数且 max≥min≥0,unit 非空。 */ +function benefitOk(b: ImprovementTask['expectedBenefit']): boolean { + if (!b) return false; + if (!Number.isFinite(b.min) || !Number.isFinite(b.max)) return false; + if (b.min < 0 || b.max < b.min) return false; + return nonEmpty(b.unit); +} + +/** 单项是否满足(已填且合法)。 */ +function fieldSatisfied(task: ImprovementTask, key: RequiredFieldKey): boolean { + switch (key) { + case 'owner': return nonEmpty(task.owner); + case 'dueDate': return nonEmpty(task.dueDate); + case 'expectedBenefit': return benefitOk(task.expectedBenefit); + case 'verificationResult': return nonEmpty(task.verificationResult); + } +} + +export interface DispatchCheck { + ok: boolean; + /** 缺失/非法项清单(ok=true 时为空) */ + missing: RequiredFieldGap[]; +} + +/** + * 四项必填校验(断言⑨核心)。任一缺失或非法 → ok=false。 + * 纯函数:只读 task,不改任何字段。 + */ +export function canDispatch(task: ImprovementTask): DispatchCheck { + const missing: RequiredFieldGap[] = []; + for (const f of REQUIRED_FIELDS) { + if (fieldSatisfied(task, f.key)) continue; + // 区分「未填」与「填了但非法」:收益对象存在但区间非法 → INVALID,其余未填 → MISSING + const present = f.key === 'expectedBenefit' ? task.expectedBenefit !== undefined + : f.key === 'owner' ? task.owner !== undefined + : f.key === 'dueDate' ? task.dueDate !== undefined + : task.verificationResult !== undefined; + missing.push({ key: f.key, label: f.label, prompt: f.prompt, reason: present ? 'INVALID' : 'MISSING' }); + } + return { ok: missing.length === 0, missing }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 二、六态合法流转 + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 合法后继态。★ 待审核→已派发 额外受 canDispatch 四项必填闸约束(见 transition)。 + * 已归档为终态(无后继)。待审核可退回待生成补录。 + */ +export const LEGAL_TRANSITIONS: Record = { + DRAFT: ['PENDING_REVIEW'], + PENDING_REVIEW: ['DISPATCHED', 'DRAFT'], + DISPATCHED: ['IN_PROGRESS'], + IN_PROGRESS: ['VERIFIED'], + VERIFIED: ['ARCHIVED'], + ARCHIVED: [], +}; + +/** from→to 是否在合法流转表内(不含四项必填闸,那由 transition 叠加)。 */ +export function isLegalTransition(from: TaskState, to: TaskState): boolean { + return (LEGAL_TRANSITIONS[from] ?? []).includes(to); +} + +/** 当前态的合法后继(含派发闸未过时的提示由调用方处理)。 */ +export function nextStates(state: TaskState): TaskState[] { + return [...(LEGAL_TRANSITIONS[state] ?? [])]; +} + +export interface TransitionContext { + /** 流转时刻,由调用方注入(引擎内禁止 Date.now) */ + at: string; + /** 操作人 */ + by: string; + note?: string; +} + +export interface TransitionResult { + ok: boolean; + /** 成功时返回**新任务对象**(state 已推进、history 已追加);失败时为 undefined,入参不被改动 */ + task?: ImprovementTask; + /** 失败原因(非法流转 / 四项未齐) */ + reason?: string; + /** 因四项必填被拒时,附缺失清单供 UI 逐条提示 */ + missing?: RequiredFieldGap[]; +} + +/** + * 状态流转(断言⑨「六态流转合法」)。 + * - to 不在 LEGAL_TRANSITIONS[from] → 拒绝,reason 说明非法。 + * - from=待审核 且 to=已派发 → 先过 canDispatch;不齐则拒绝,任务停在待审核,附 missing。 + * - 其余合法流转 → 追加 history,返回新对象。 + * 纯函数:不改动入参 task;at/by 注入,可重放。 + */ +export function transition(task: ImprovementTask, to: TaskState, ctx: TransitionContext): TransitionResult { + const from = task.state; + if (!isLegalTransition(from, to)) { + return { + ok: false, + reason: `非法流转:${TASK_STATE_LABEL[from]} → ${TASK_STATE_LABEL[to]}(合法后继:${nextStates(from).map((s) => TASK_STATE_LABEL[s]).join('、') || '无(终态)'})`, + }; + } + // ★ 唯一的派发闸:待审核 → 已派发 必须四项齐备 + if (from === 'PENDING_REVIEW' && to === 'DISPATCHED') { + const check = canDispatch(task); + if (!check.ok) { + return { + ok: false, + reason: `拒绝派发:四项必填未齐(${check.missing.map((m) => m.label).join('、')}),任务停在「${TASK_STATE_LABEL[from]}」`, + missing: check.missing, + }; + } + } + const next: ImprovementTask = { + ...task, + state: to, + history: [...task.history, { state: to, at: ctx.at, by: ctx.by, ...(ctx.note !== undefined ? { note: ctx.note } : {}) }], + }; + return { ok: true, task: next }; +} + +/** + * SLA 计时起点 = 首次进入「已派发」的 history.at(建议书:补齐后已派发,SLA 计时开始)。 + * 未派发返回 undefined。纯查表,不读时钟。 + */ +export function slaStartOf(task: ImprovementTask): string | undefined { + return task.history.find((h) => h.state === 'DISPATCHED')?.at; +} + +/** 引擎自检:供校验脚本⑨与说明页引用。 */ +export function closureStats() { + return { + states: [...TASK_STATES], + stateCount: TASK_STATES.length, + requiredFields: REQUIRED_FIELDS.map((f) => ({ key: f.key, label: f.label, prompt: f.prompt })), + requiredFieldCount: REQUIRED_FIELDS.length, + legalTransitions: TASK_STATES.map((s) => ({ from: s, to: [...LEGAL_TRANSITIONS[s]] })), + /** 终态必须无后继;六态都必须可达(除 DRAFT 为起点) */ + terminalStates: TASK_STATES.filter((s) => LEGAL_TRANSITIONS[s].length === 0), + /** 派发闸只挂在 待审核→已派发 这一条边上 */ + dispatchGateEdge: { from: 'PENDING_REVIEW' as TaskState, to: 'DISPATCHED' as TaskState }, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/dq.ts b/src/modules/tfamd-oee/lib/oee/dq.ts new file mode 100644 index 0000000..9a89ea3 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/dq.ts @@ -0,0 +1,390 @@ +/** + * L2 引擎 · 12 条数据质量规则(规划书 8.x DQ 表,逐条照录判定条件与处置动作)。 + * + * ★ 零 IO 纯函数。守断言⑦(DQ-06 阻断)。 + * + * 三类处置动作必须区分显示: + * AUTO_FIX 自动修正 / ANNOTATE 标注 / BLOCK 阻断 + * **阻断类(DQ-06/08/12)触发时,该设备当日 OEE 不发布**, + * 页面显示「结论暂缓发布 + 原因 + 补录入口」,而不是显示一个看起来正常的数字。 + * + * ★ 诚实性约束:**缺证据 ≠ 通过**。 + * 某条规则所需的输入没给,就记入 notEvaluated 并说明缺什么, + * 绝不静默当作"未命中"。治理台据此标灰,不标绿。 + * + * ★ DQ-10 三态必须分开:「未采集 / 空档 / 无生产」。 + * 设备关机或日志中断造成的空档不能算成"无生产",否则 OEE 分母被悄悄缩小。 + * UNKNOWN 段不计入 PPT(见 stateMachine),本规则只负责告警与标记。 + */ +import { + BLOCKING_DQ, EPS, + type Device, type DqCode, type DqIssue, type EventInstance, type StateSegment, +} from '../../types/oee'; +import { toEpoch, type EventPair } from './pairing'; +import { findOverlaps } from './stateMachine'; + +export type DqDisposition = 'AUTO_FIX' | 'ANNOTATE' | 'BLOCK'; + +export interface DqRule { + code: DqCode; + name: string; + /** 判定条件(规划书原文) */ + condition: string; + /** 处置动作(规划书原文) */ + action: string; + disposition: DqDisposition; + blocking: boolean; +} + +/** 12 条规则字典。condition/action 为原文,不在实现里改写措辞。 */ +export const DQ_RULES: DqRule[] = [ + { code: 'DQ-01', name: '时钟回跳', condition: '同一设备相邻事件时间戳倒退 >60 秒', action: '自动修正:记录偏移量并对齐,保留原始/校正双字段', disposition: 'AUTO_FIX', blocking: false }, + { code: 'DQ-02', name: '状态段重叠', condition: '同一设备同一时刻存在两条以上状态段', action: '自动修正:按抢占优先级重排,低优先级段裁剪', disposition: 'AUTO_FIX', blocking: false }, + { code: 'DQ-03', name: '段时长超阈值', condition: '单段状态持续超过设备级校准阈值(如 RUN 连续 24h 无产出)', action: '标注:进入人工确认队列', disposition: 'ANNOTATE', blocking: false }, + { code: 'DQ-04', name: '事件缺失配对', condition: '只有开始无结束(或反之)且已跨过当日 23:59', action: '推断并标注:用下一状态开始时间强制闭合', disposition: 'ANNOTATE', blocking: false }, + { code: 'DQ-05', name: '编码异常', condition: '解码失败或非法字符占比 >1%', action: '自动修正:latin-1 逐行回退,异常行原文入冷存储', disposition: 'AUTO_FIX', blocking: false }, + { code: 'DQ-06', name: '未归因占比过高', condition: '单台设备当日 UNKNOWN 时长占比 >5%', action: '阻断计算并派单:暂停该设备当日结论发布', disposition: 'BLOCK', blocking: true }, + { code: 'DQ-07', name: '节拍异常偏离', condition: '单件实际节拍偏离理论节拍 >3σ', action: '标注:性能因子按理论与实测双值出数', disposition: 'ANNOTATE', blocking: false }, + { code: 'DQ-08', name: '主数据缺失', condition: '设备/线体/站点/班次在主数据中不存在', action: '阻断计算:记录不入聚合,进入补录队列', disposition: 'BLOCK', blocking: true }, + { code: 'DQ-09', name: '重复事件', condition: 'dedup_key 命中已有记录', action: '自动修正:丢弃并计数,重复率单独统计', disposition: 'AUTO_FIX', blocking: false }, + { code: 'DQ-10', name: '日志断流', condition: '设备连续两个采集周期无新增数据', action: '标注并告警:生成"未采集"标记,不等同于"无生产"', disposition: 'ANNOTATE', blocking: false }, + { code: 'DQ-11', name: '人工补录超时', condition: 'D 类事件在班次结束后 30 分钟未录入', action: '派单并标注:升级提醒班组长,报表以快照值出数', disposition: 'ANNOTATE', blocking: false }, + { code: 'DQ-12', name: '口径版本不一致', condition: '同一报表混用两个 caliber_version', action: '阻断计算:提示口径版本号并要求确认', disposition: 'BLOCK', blocking: true }, +]; + +export const DQ_RULE_BY_CODE: Record = Object.fromEntries(DQ_RULES.map((r) => [r.code, r])); + +/** 阈值默认值。全部可由调用方覆盖(口径配置中心接入后从 C 项取值)。 */ +export const DQ_DEFAULTS = { + clockBackwardSec: 60, + unattributedBlockPct: 0.05, + encodeBadPct: 0.01, + cycleSigmaK: 3, + manualGraceSec: 30 * 60, + maxRunNoOutputSec: 24 * 3600, + collectionCycles: 2, +} as const; + +export interface DqInput { + bizDate: string; + /** 注入的"当前时间",引擎内禁止 Date.now() */ + now: string; + device?: Device; + + // 各规则所需证据。缺哪块,对应规则就记 notEvaluated。 + events?: EventInstance[]; + pairs?: EventPair[]; + segments?: StateSegment[]; + /** DQ-06:未归因时长与分母(来自 lossBuckets / stateMachine,不在此重算) */ + unattributedSec?: number; + pptSec?: number; + /** DQ-03:RUN 段产出,用于"连续 24h 无产出"判定 */ + runOutputQty?: number; + encoding?: { totalLines: number; badLines: number }; + /** + * DQ-09:L1 适配器去重时丢弃的条数与扫描总数。 + * 去重点在适配器,事件表交到此处时已无重复;只数 events 会永远得 0, + * 必须由采集侧把计数作为证据传进来(scanned 作重复率分母)。 + */ + dedup?: { dropped: number; scanned: number }; + cycle?: { ictSec: number; actualMeanSec: number; sigmaSec: number }; + masterData?: { deviceIds: string[]; lineIds: string[]; stations: string[]; shiftIds: string[] }; + refs?: { device?: string; lineId?: string; station?: string; shiftId?: string }; + collection?: { cycleSec: number; lastLineEpoch: number }; + manualPending?: { defCode: string; shiftEndEpoch: number; enteredAtEpoch?: number }[]; + caliberVersions?: string[]; + + // 阈值覆盖 + clockBackwardSec?: number; + unattributedBlockPct?: number; + encodeBadPct?: number; + cycleSigmaK?: number; + manualGraceSec?: number; + maxRunNoOutputSec?: number; +} + +export interface DqOutput { + issues: DqIssue[]; + /** 是否阻断当日结论发布 */ + blocked: boolean; + blockedBy: DqCode[]; + /** 已评估的规则(有证据) */ + evaluated: DqCode[]; + /** 缺证据未评估的规则 —— 治理台标灰不标绿 */ + notEvaluated: { code: DqCode; missing: string }[]; + stats: { + autoFix: number; annotate: number; block: number; + /** DQ-09 重复率单独统计 */ + duplicateCount: number; duplicateRate: number; + /** DQ-01 回跳次数与已校正条数 */ + clockBackwardCount: number; correctedCount: number; + /** DQ-06 未归因占比 */ + unattributedPct: number; + /** DQ-10 未采集时长(≠ 无生产) */ + unknownSec: number; + }; + /** 阻断时给 UI 的完整话术:结论暂缓发布 + 原因 + 补录入口 */ + publishNotice: string; +} + +/** + * 跑 12 条规则。**只判定与标注,不改数据**: + * 自动修正类规则在本引擎里只报告"应如何修正",真正的修正在采集适配层(L1)完成, + * 这样 L2 保持纯函数、可重放,且修正过程可审计。 + */ +export function runDq(input: DqInput): DqOutput { + // issue id 用**函数内局部**计数器,不用模块级全局: + // 同一输入两次调用必须产生同一批 id,否则不可重放、也无法做深相等比对。 + let issueSeq = 0; + const issue = (code: DqCode, cond: string, gap?: string): DqIssue => { + const rule = DQ_RULE_BY_CODE[code]; + return { + id: `dq-${input.bizDate}-${input.device?.id ?? 'ALL'}-${code}-${++issueSeq}`, + code, + ...(input.device ? { device: input.device.id } : {}), + bizDate: input.bizDate, + condition: cond, + blocking: rule.blocking, + action: rule.action, + state: rule.blocking ? 'ASSIGNED' : 'OPEN', + ...(gap ? { gap } : {}), + }; + }; + + const th = { + clockBackwardSec: input.clockBackwardSec ?? DQ_DEFAULTS.clockBackwardSec, + unattributedBlockPct: input.unattributedBlockPct ?? DQ_DEFAULTS.unattributedBlockPct, + encodeBadPct: input.encodeBadPct ?? DQ_DEFAULTS.encodeBadPct, + cycleSigmaK: input.cycleSigmaK ?? DQ_DEFAULTS.cycleSigmaK, + manualGraceSec: input.manualGraceSec ?? DQ_DEFAULTS.manualGraceSec, + maxRunNoOutputSec: input.maxRunNoOutputSec ?? DQ_DEFAULTS.maxRunNoOutputSec, + }; + const issues: DqIssue[] = []; + const evaluated: DqCode[] = []; + const notEvaluated: { code: DqCode; missing: string }[] = []; + const nowEpoch = toEpoch(input.now); + + let duplicateCount = 0; + let duplicateRate = 0; + let clockBackwardCount = 0; + let correctedCount = 0; + let unattributedPct = 0; + let unknownSec = 0; + + /* ── DQ-01 时钟回跳:按日志行序比较相邻 rawTime ─────────────────── */ + if (input.events) { + evaluated.push('DQ-01'); + const byLog = [...input.events].sort((a, b) => a.evidence.lineNo - b.evidence.lineNo); + for (let i = 1; i < byLog.length; i++) { + const prev = toEpoch(byLog[i - 1].rawTime); + const cur = toEpoch(byLog[i].rawTime); + if (prev - cur > th.clockBackwardSec) { + clockBackwardCount++; + issues.push(issue('DQ-01', + `L${byLog[i].evidence.lineNo} 相对 L${byLog[i - 1].evidence.lineNo} 倒退 ${prev - cur}s(>${th.clockBackwardSec}s)`)); + } + } + correctedCount = input.events.filter((e) => e.isCorrected).length; + // 双时间字段完整性:校正过的事件必须保留 rawTime ≠ correctedTime 与偏移量 + const lostRaw = input.events.filter((e) => e.isCorrected && (e.rawTime === e.correctedTime || e.clockOffsetSec === undefined)); + if (lostRaw.length) { + issues.push(issue('DQ-01', `${lostRaw.length} 条已校正事件未保留原始/校正双字段或偏移量`, + '双时间字段缺失,无法审计改钟过程')); + } + } else notEvaluated.push({ code: 'DQ-01', missing: 'events(含 rawTime/correctedTime/evidence.lineNo)' }); + + /* ── DQ-02 状态段重叠 ─────────────────────────────────────────── */ + if (input.segments) { + evaluated.push('DQ-02'); + const ov = findOverlaps(input.segments); + for (const o of ov) issues.push(issue('DQ-02', `段 ${o.a} 与 ${o.b} 时间重叠`)); + } else notEvaluated.push({ code: 'DQ-02', missing: 'segments' }); + + /* ── DQ-03 段时长超阈值(RUN 连续 24h 无产出)──────────────────── */ + if (input.segments) { + evaluated.push('DQ-03'); + for (const s of input.segments) { + if (s.state !== 'RUN') continue; + if (s.durationSec >= th.maxRunNoOutputSec && (input.runOutputQty ?? 0) === 0) { + issues.push(issue('DQ-03', + `RUN 段 ${s.id} 连续 ${(s.durationSec / 3600).toFixed(1)}h 无产出(阈值 ${th.maxRunNoOutputSec / 3600}h)`)); + } + } + } else notEvaluated.push({ code: 'DQ-03', missing: 'segments + runOutputQty' }); + + /* ── DQ-04 事件缺失配对且已跨过当日 23:59 ─────────────────────── */ + if (input.pairs) { + evaluated.push('DQ-04'); + const dayEnd = toEpoch(`${input.bizDate}T23:59:00Z`); + const crossed = nowEpoch >= dayEnd; + for (const p of input.pairs) { + if (!p.filledEnd && !p.filledStart) continue; + const which = p.filledEnd ? '缺失结束' : '缺失开始'; + if (crossed) { + issues.push(issue('DQ-04', + `${p.pairId} ${which},已跨过 ${input.bizDate} 23:59,按规则强制闭合(补出端非观测值)`)); + } else { + issues.push(issue('DQ-04', + `${p.pairId} ${which},当日尚未结束,暂按封顶时长闭合`, '当日未结束,闭合时刻为推断值')); + } + } + } else notEvaluated.push({ code: 'DQ-04', missing: 'pairs(含 filledEnd/filledStart)' }); + + /* ── DQ-05 编码异常 ─────────────────────────────────────────── */ + if (input.encoding) { + evaluated.push('DQ-05'); + const { totalLines, badLines } = input.encoding; + const rate = totalLines > 0 ? badLines / totalLines : 0; + if (rate > th.encodeBadPct + EPS) { + issues.push(issue('DQ-05', + `非法字符/解码失败 ${badLines}/${totalLines} 行 = ${(rate * 100).toFixed(2)}%(>${th.encodeBadPct * 100}%)`)); + } + } else notEvaluated.push({ code: 'DQ-05', missing: 'encoding{totalLines,badLines}' }); + + /* ── DQ-06 未归因占比过高 ★阻断 ─────────────────────────────── */ + if (typeof input.unattributedSec === 'number' && typeof input.pptSec === 'number') { + evaluated.push('DQ-06'); + unattributedPct = input.pptSec > 0 ? input.unattributedSec / input.pptSec : 0; + if (unattributedPct > th.unattributedBlockPct + EPS) { + issues.push(issue('DQ-06', + `未归因 ${input.unattributedSec.toFixed(0)}s / PPT ${input.pptSec.toFixed(0)}s = ${(unattributedPct * 100).toFixed(2)}%(>${th.unattributedBlockPct * 100}%)`)); + } + } else notEvaluated.push({ code: 'DQ-06', missing: 'unattributedSec + pptSec' }); + + /* ── DQ-07 节拍异常偏离 >3σ ─────────────────────────────────── */ + if (input.cycle) { + evaluated.push('DQ-07'); + const { ictSec, actualMeanSec, sigmaSec } = input.cycle; + const dev = Math.abs(actualMeanSec - ictSec); + if (sigmaSec > EPS && dev > th.cycleSigmaK * sigmaSec + EPS) { + issues.push(issue('DQ-07', + `实际均值节拍 ${actualMeanSec.toFixed(2)}s 偏离理论 ${ictSec}s 达 ${dev.toFixed(2)}s(>${th.cycleSigmaK}σ=${(th.cycleSigmaK * sigmaSec).toFixed(2)}s)`)); + } + } else notEvaluated.push({ code: 'DQ-07', missing: 'cycle{ictSec,actualMeanSec,sigmaSec}' }); + + /* ── DQ-08 主数据缺失 ★阻断 ─────────────────────────────────── */ + if (input.masterData && input.refs) { + evaluated.push('DQ-08'); + const md = input.masterData; + const r = input.refs; + const missing: string[] = []; + if (r.device && !md.deviceIds.includes(r.device)) missing.push(`设备 ${r.device}`); + if (r.lineId && !md.lineIds.includes(r.lineId)) missing.push(`线体 ${r.lineId}`); + if (r.station && !md.stations.includes(r.station)) missing.push(`站点 ${r.station}`); + if (r.shiftId && !md.shiftIds.includes(r.shiftId)) missing.push(`班次 ${r.shiftId}`); + if (missing.length) { + issues.push(issue('DQ-08', `主数据中不存在:${missing.join('、')}`)); + } + } else notEvaluated.push({ code: 'DQ-08', missing: 'masterData + refs' }); + + /* ── DQ-09 重复事件(dedup_key 命中)────────────────────────── */ + if (input.events || input.dedup) { + evaluated.push('DQ-09'); + // ① 采集侧(L1 适配器)去重时丢弃的条数——去重点在那里,计数必须作为证据传进来 + const adapterDropped = input.dedup?.dropped ?? 0; + // ② 事件表内仍残留的重复(未走去重器直接入表时的兜底) + let ownRepeats = 0; + if (input.events) { + const seen = new Set(); + for (const e of input.events) { + if (seen.has(e.dedupKey)) ownRepeats++; + else seen.add(e.dedupKey); + } + } + duplicateCount = adapterDropped + ownRepeats; + // 分母=进入去重器的扫描总数。给了 dedup 证据就用采集侧的 scanned; + // 没给则事件表本身就是原始扫描集(含重复),直接取长度——再加 ownRepeats 会把重复算两次。 + const scanned = input.dedup?.scanned ?? (input.events?.length ?? 0); + duplicateRate = scanned > 0 ? duplicateCount / scanned : 0; + if (duplicateCount > 0) { + issues.push(issue('DQ-09', + `dedup_key 命中 ${duplicateCount} 条(采集侧丢弃 ${adapterDropped}、表内残留 ${ownRepeats}),` + + `重复率 ${(duplicateRate * 100).toFixed(2)}%(丢弃并计数,不让时长翻倍)`)); + } + } else notEvaluated.push({ code: 'DQ-09', missing: 'events(含 dedupKey)或 dedup 计数' }); + + /* ── DQ-10 日志断流:未采集 ≠ 无生产 ────────────────────────── */ + if (input.collection || input.segments) { + evaluated.push('DQ-10'); + if (input.segments) { + unknownSec = input.segments.filter((s) => s.state === 'UNKNOWN').reduce((a, s) => a + s.durationSec, 0); + if (unknownSec > 0) { + issues.push(issue('DQ-10', + `UNKNOWN(未采集)${unknownSec.toFixed(0)}s,已从 PPT 分母扣除;不得记为"无生产"`)); + } + } + if (input.collection) { + const idle = nowEpoch - input.collection.lastLineEpoch; + const need = DQ_DEFAULTS.collectionCycles * input.collection.cycleSec; + if (idle >= need) { + issues.push(issue('DQ-10', + `连续 ${Math.floor(idle / input.collection.cycleSec)} 个采集周期无新增数据(${idle}s ≥ ${need}s)`, + '断流期间产出未知,不能按 0 计入')); + } + } + } else notEvaluated.push({ code: 'DQ-10', missing: 'collection{cycleSec,lastLineEpoch} 或 segments' }); + + /* ── DQ-11 人工补录超时(班次结束后 30min)──────────────────── */ + if (input.manualPending) { + evaluated.push('DQ-11'); + for (const m of input.manualPending) { + const deadline = m.shiftEndEpoch + th.manualGraceSec; + const entered = m.enteredAtEpoch; + if (entered === undefined && nowEpoch > deadline) { + issues.push(issue('DQ-11', + `D 类事件 ${m.defCode} 班次结束后 ${th.manualGraceSec / 60}min 仍未录入(已超 ${((nowEpoch - deadline) / 60).toFixed(0)}min)`)); + } else if (entered !== undefined && entered > deadline) { + issues.push(issue('DQ-11', + `D 类事件 ${m.defCode} 迟录 ${((entered - deadline) / 60).toFixed(0)}min,报表以快照值出数`)); + } + } + } else notEvaluated.push({ code: 'DQ-11', missing: 'manualPending[]' }); + + /* ── DQ-12 口径版本不一致 ★阻断 ─────────────────────────────── */ + if (input.caliberVersions) { + evaluated.push('DQ-12'); + const uniq = [...new Set(input.caliberVersions)]; + if (uniq.length > 1) { + issues.push(issue('DQ-12', `同一报表混用 ${uniq.length} 个口径版本:${uniq.join(' / ')}`)); + } + } else notEvaluated.push({ code: 'DQ-12', missing: 'caliberVersions[]' }); + + const blockedBy = issues.filter((i) => i.blocking).map((i) => i.code); + const blocked = blockedBy.length > 0; + const stats = { + autoFix: issues.filter((i) => DQ_RULE_BY_CODE[i.code].disposition === 'AUTO_FIX').length, + annotate: issues.filter((i) => DQ_RULE_BY_CODE[i.code].disposition === 'ANNOTATE').length, + block: issues.filter((i) => DQ_RULE_BY_CODE[i.code].disposition === 'BLOCK').length, + duplicateCount, duplicateRate, clockBackwardCount, correctedCount, unattributedPct, unknownSec, + }; + + return { + issues, blocked, blockedBy, evaluated, notEvaluated, stats, + publishNotice: blocked + ? `结论暂缓发布:${blockedBy.map((c) => `${c} ${DQ_RULE_BY_CODE[c].name}`).join('、')}。` + + '请先在未归因池/补录队列完成处理,再重新计算当日 OEE。' + : notEvaluated.length + ? `当日结论可发布,但有 ${notEvaluated.length} 条规则因缺证据未评估(标灰,不视为通过)。` + : '当日结论可发布:12 条规则全部评估且无阻断项。', + }; +} + +/** 是否阻断。只认三条阻断级规则,其余标注/自动修正不影响发布。 */ +export function isBlocked(issues: DqIssue[]): boolean { + return issues.some((i) => i.blocking && BLOCKING_DQ.includes(i.code)); +} + +/** 规则字典自检:12 条齐全、阻断集恰好三条、处置动作与 blocking 标记一致。 */ +export function checkDqDictionary(): { ok: boolean; problems: string[] } { + const problems: string[] = []; + if (DQ_RULES.length !== 12) problems.push(`规则数 ${DQ_RULES.length} ≠ 12`); + const codes = DQ_RULES.map((r) => r.code); + if (new Set(codes).size !== codes.length) problems.push('规则码重复'); + const blocking = DQ_RULES.filter((r) => r.blocking).map((r) => r.code).sort(); + if (blocking.join(',') !== [...BLOCKING_DQ].sort().join(',')) problems.push(`阻断集 ${blocking.join(',')} ≠ DQ-06/08/12`); + for (const r of DQ_RULES) { + if ((r.disposition === 'BLOCK') !== r.blocking) problems.push(`${r.code} 处置动作与 blocking 不一致`); + if (!r.condition || !r.action) problems.push(`${r.code} 缺判定条件或处置动作`); + } + return { ok: problems.length === 0, problems }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/forecast.ts b/src/modules/tfamd-oee/lib/oee/forecast.ts new file mode 100644 index 0000000..6008545 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/forecast.ts @@ -0,0 +1,231 @@ +/** + * L2 预测引擎(纯函数 · 建议书 §4.6 / 决策 D13)。 + * + * ★ 本模块最重要的纪律:**四门槛全未达 ⇒ 不引入任何预测模型**。 + * 这里只有「规则外推」,每一条输出都带 label='示意·非模型输出'。 + * 这比在 6 周数据上训练一个过拟合模型更诚实,也符合规划书 6.8 的分阶段口径。 + * 生产阶段的模型路线(XGBoost/LightGBM→LSTM/TCN、生存分析)只登记在 MODEL_ROADMAP, + * 不在原型里实现, phase=P4~P5。 + * + * 纯度(verify-oee-purity.ts 守卫):零 import、零 IO、零时钟、零随机、零模块级可变全局。 + * 输入一律由 L3 现算后注入(故障桶时长 / PPT / 历史 OEE 序列),本层不取数、不读时钟。 + * 所有函数都是入参 → 出参的确定性映射,可重放、可单测。 + */ + +/* ══════════════════════════════════════════════════════════════════ + * 一、四门槛(照录建议书 §4.6.1,当前状态全「未达」) + * ══════════════════════════════════════════════════════════════════ */ + +export type ForecastGateId = 'CODEBOOK' | 'SAMPLING' | 'SAMPLE_SPAN' | 'CLASS_BALANCE'; + +export interface ForecastGate { + id: ForecastGateId; + name: string; + requirement: string; + /** 当前状态(照录建议书,含〔POC〕出处) */ + status: string; + /** 是否达标。四门槛全 false ⇒ 原型不上模型。 */ + met: boolean; + disposition: string; +} + +export const FORECAST_GATES: ForecastGate[] = [ + { + id: 'CODEBOOK', name: '故障码表覆盖', requirement: '≥90%', + status: '未达(FUJI MCSTATUS 与 DPVS Err 无码本〔POC〕)', met: false, disposition: '不训练', + }, + { + id: 'SAMPLING', name: '关键信号采样', requirement: '≥1Hz', + status: '未达(文件采集 5~15min,仅 IO 通道秒级)', met: false, disposition: '不训练', + }, + { + id: 'SAMPLE_SPAN', name: '有效样本跨度', requirement: '≥6 个月', + status: '未达(POC 仅 6 周)', met: false, disposition: '不训练', + }, + { + id: 'CLASS_BALANCE', name: '类别不平衡', requirement: '已处理', + status: '未达(停机是稀有事件)', met: false, disposition: '不训练', + }, +]; + +/** 全站统一标注:预测页任何外推读数都必须带这句,绝不冒充模型输出。 */ +export const FORECAST_LABEL = '示意·非模型输出'; + +export const FORECAST_GATE_NOTE = + '四门槛全未达(码表覆盖 / 采样率 / 样本跨度 / 类别不平衡),因此原型不引入任何预测模型。' + + '本页用规则外推 + 显式标注「' + FORECAST_LABEL + '」。' + + '这比训练一个在 6 周数据上过拟合的模型更诚实,也更符合规划书 6.8 的分阶段口径。'; + +/* ══════════════════════════════════════════════════════════════════ + * 二、规则外推(示意,非模型) + * ══════════════════════════════════════════════════════════════════ */ + +const clamp01 = (x: number): number => (Number.isFinite(x) ? Math.min(1, Math.max(0, x)) : 0); + +/** 未归因占比阻断阈值(与 DQ-06 同口径,比例 0–1)。超过即降级,读数仅供参考。 */ +export const FORECAST_DEGRADE_UNATTRIBUTED = 0.05; + +export type RiskLevel = 'HIGH' | 'MED' | 'LOW'; + +export const RISK_LEVEL_LABEL: Record = { HIGH: '高', MED: '中', LOW: '低' }; + +/** 未来 30min 停机风险外推的入参(全部由 L3 从当日六桶 / DQ 现算注入)。 */ +export interface StopRiskInput { + /** 计划生产时间 PPT = CT − PDT(秒),分母 */ + pptSec: number; + /** 故障桶(FAULT / DOWN)时长(秒) */ + faultSec: number; + /** 小停机桶(IDLE_MINOR / JAM·待料)时长(秒) */ + idleMinorSec: number; + /** DQ 是否阻断(阻断则降级) */ + blocked: boolean; + /** 未归因占比(0–1),>5% 降级 */ + unattributedPct: number; +} + +export interface StopRisk { + level: RiskLevel; + /** 非计划停机占比 =(故障 + 小停机)/ PPT(0–1) */ + unplannedPct: number; + horizonMin: number; + /** 降级:DQ 阻断或未归因 >5%,读数仅供参考、不可发布 */ + degraded: boolean; + /** 可解释规则文字(评审现场可照着重算) */ + rule: string; + label: typeof FORECAST_LABEL; +} + +/** 高 / 中风险阈值(占比,0–1)。规则外推,非模型概率。 */ +export const STOP_RISK_HIGH = 0.10; +export const STOP_RISK_MED = 0.03; + +/** + * 未来 30min 停机风险=规则外推。 + * 规则:非计划停机占比 =(故障桶 + 小停机桶)/ PPT;≥10% 高 / ≥3% 中 / 否则低。 + * ★ 这是「按当日损失结构外推下一时段」的示意,不是分类模型,不给概率、不给置信度。 + */ +export function extrapolateStopRisk(input: StopRiskInput): StopRisk { + const unplannedPct = input.pptSec > 0 ? clamp01((input.faultSec + input.idleMinorSec) / input.pptSec) : 0; + const level: RiskLevel = unplannedPct >= STOP_RISK_HIGH ? 'HIGH' : unplannedPct >= STOP_RISK_MED ? 'MED' : 'LOW'; + const degraded = input.blocked || input.unattributedPct > FORECAST_DEGRADE_UNATTRIBUTED; + return { + level, unplannedPct, horizonMin: 30, degraded, + rule: `非计划停机占比 =(故障 ${(input.faultSec / 60).toFixed(1)}min + 小停机 ${(input.idleMinorSec / 60).toFixed(1)}min)/ PPT ${(input.pptSec / 3600).toFixed(2)}h = ${(unplannedPct * 100).toFixed(2)}%;` + + `≥${STOP_RISK_HIGH * 100}% 高 / ≥${STOP_RISK_MED * 100}% 中 / 否则低 → ${RISK_LEVEL_LABEL[level]}。` + + (degraded ? ' DQ 阻断或未归因 >5%,降级为仅供参考。' : ''), + label: FORECAST_LABEL, + }; +} + +/** 历史 OEE 序列点(按业务日升序,含当日)。由 L3 从 dekDays 现算注入。 */ +export interface OeeTrendPoint { bizDate: string; oee: number; } + +export interface Oee4hInput { + /** 当日实际 OEE(0–1),外推锚点 */ + anchorOee: number; + /** 截至当日的历史序列(升序,至少含当日) */ + history: OeeTrendPoint[]; + blocked: boolean; + unattributedPct: number; +} + +export interface Oee4hForecast { + horizonHours: number; + /** 外推点值(0–1) */ + point: number; + /** 示意区间下 / 上界(0–1)。★ 非置信区间,只是示意带宽。 */ + bandLow: number; + bandHigh: number; + /** 线性趋势斜率(每日 OEE 变化,0–1/日) */ + slopePerDay: number; + degraded: boolean; + method: string; + label: typeof FORECAST_LABEL; +} + +/** 示意区间半宽:正常 ±3pp,降级 ±6pp。非置信区间,仅示意。 */ +export const OEE4H_BAND = 0.03; +export const OEE4H_BAND_DEGRADED = 0.06; + +/** + * 未来 4h OEE=线性规则外推。 + * 规则:取历史序列首末两点求每日斜率,4h = 1/6 日,point = clamp(当日 OEE + 斜率 × 1/6)。 + * ★ 只有 3 日种子,斜率极不稳定,故必须标「示意·非模型输出」并给示意带宽,绝不冒充回归预测。 + */ +export function extrapolateOee4h(input: Oee4hInput): Oee4hForecast { + const n = input.history.length; + const slopePerDay = n >= 2 ? (input.history[n - 1].oee - input.history[0].oee) / (n - 1) : 0; + const horizonDays = 4 / 24; + const point = clamp01(input.anchorOee + slopePerDay * horizonDays); + const degraded = input.blocked || input.unattributedPct > FORECAST_DEGRADE_UNATTRIBUTED; + const half = degraded ? OEE4H_BAND_DEGRADED : OEE4H_BAND; + return { + horizonHours: 4, point, + bandLow: clamp01(point - half), bandHigh: clamp01(point + half), + slopePerDay, degraded, + method: `线性外推:历史 ${n} 日首末斜率 ${(slopePerDay * 100).toFixed(2)}pp/日,4h=1/6 日,` + + `点值 = clamp(当日 ${(input.anchorOee * 100).toFixed(2)}% + 斜率×1/6) = ${(point * 100).toFixed(2)}%;` + + `示意区间 ±${half * 100}pp(非置信区间)。` + + (degraded ? ' DQ 阻断或未归因 >5%,降级为仅供参考。' : ''), + label: FORECAST_LABEL, + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三、生产阶段模型路线(照录建议书 §4.6.2,供演进参考,原型不实现) + * ══════════════════════════════════════════════════════════════════ */ + +export interface ModelRoadmapRow { + task: string; + features: string; + labelSource: string; + models: string; + phase: string; +} + +export const MODEL_ROADMAP: ModelRoadmapRow[] = [ + { + task: '未来 30min 停机分类', + features: '节拍偏差序列、报警序列、停机间隔分布、换型时长、温度压力、批次、班次、设备年龄', + labelSource: '由事件与状态段自动生成(无需人工标注)', + models: 'XGBoost/LightGBM → LSTM/TCN', phase: 'P4~P5', + }, + { + task: '未来 4h OEE 回归', + features: '同上', + labelSource: '同上', + models: 'XGBoost/LightGBM → LSTM/TCN', phase: 'P4~P5', + }, + { + task: '停机时长预测', + features: '同上 + 维修历史', + labelSource: '同上', + models: '生存分析(处理右删失)', phase: 'P4~P5', + }, +]; + +export const MODEL_ROADMAP_NOTE = + '「标签由事件与状态段自动生成」是这条路线最大的成本优势——制造业数据标注成本高,' + + '而 OEE 场景的标签恰好可以从已解析的事件里推导。这也是为什么 L2 引擎(状态段生成)必须先做对:它是预测模型的地基。'; + +/* ══════════════════════════════════════════════════════════════════ + * 四、自检(供校验脚本与预测页引用,数字一律现算) + * ══════════════════════════════════════════════════════════════════ */ + +export function forecastStats() { + const met = FORECAST_GATES.filter((g) => g.met).length; + return { + gateTotal: FORECAST_GATES.length, + gateMet: met, + allUnmet: met === 0, + riskLevels: Object.keys(RISK_LEVEL_LABEL).length, + roadmapRows: MODEL_ROADMAP.length, + label: FORECAST_LABEL, + /** 外推阈值(供校验脚本照着重算) */ + stopRiskHigh: STOP_RISK_HIGH, + stopRiskMed: STOP_RISK_MED, + band: OEE4H_BAND, + bandDegraded: OEE4H_BAND_DEGRADED, + degradeUnattributed: FORECAST_DEGRADE_UNATTRIBUTED, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/guards.ts b/src/modules/tfamd-oee/lib/oee/guards.ts new file mode 100644 index 0000000..9f3eddf --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/guards.ts @@ -0,0 +1,131 @@ +/** + * 防幻觉五道闸(建议书 4.3.4 / 规划书 6.9)——**全部在代码里实现,不靠提示词自觉**。 + * + * ★ 纯函数层纪律(ADR-02):只 import 契约层,无 IO/时钟/随机/可变全局。 + * 同输入两次调用深相等、可重放。断言⑩逐条触发本模块。 + * + * 五道闸(触发行为): + * 闸 1 数字只来自工具:草稿文本里的数字必须能在 ServiceResult.data 找到匹配,否则重生成。 + * 闸 2 出处强制:任一 fact 缺 caliberVersion / timeRange / source → 不发布(重生成 ≤2 次)。 + * 闸 3 跨版本拒绝:COMPARE 意图且两个 caliberVersion 不同 → 直接拒绝输出对比结论。 + * 闸 4 证据链完整性:下钻任一层缺证据 → 停止下钻,列出缺失环节与补录项,转人工。 + * 闸 5 收益给区间:建议收益必须 {min,max} 且 min≠max,点值一律拒绝(重生成)。 + * + * 能力边界(写进系统提示,不可协商):可读、可算、可建议、可派单;不可改数、不可代签核。 + * 本模块是「不可改数」的最后一道防线:数字无工具来源即拦下。 + */ +import type { AnswerDraft, GuardResult, ServiceResult } from '../../types/oee'; + +/** 五道闸的中文标签与触发行为,供 UI 与校验脚本同源引用。 */ +export const GATE_LABEL: Record<1 | 2 | 3 | 4 | 5, { name: string; action: string }> = { + 1: { name: '数字只来自工具', action: '重生成' }, + 2: { name: '出处强制', action: '重生成(≤2 次)' }, + 3: { name: '跨版本拒绝', action: '直接拒绝' }, + 4: { name: '证据链完整性', action: '转人工' }, + 5: { name: '收益给区间', action: '重生成' }, +}; + +/** + * 从文本抽取数字(含小数、百分号前的数)。 + * 只抽数值 token,不抽版本号里的数字(v0.1-demo 的 0.1 由调用方按需排除)。 + * 确定性:正则全局匹配,按出现顺序返回。 + */ +export function extractNumbers(text: string): number[] { + const out: number[] = []; + const re = /\d+(?:\.\d+)?/g; + let m: RegExpExecArray | null; + while ((m = re.exec(text)) !== null) { + const n = Number(m[0]); + if (Number.isFinite(n)) out.push(n); + } + return out; +} + +/** 递归收集对象/数组里的所有有限数值(含嵌套)。字符串里的数字不抽(只认结构化数据值)。 */ +export function collectNumbers(value: unknown): number[] { + const out: number[] = []; + const walk = (v: unknown): void => { + if (typeof v === 'number') { if (Number.isFinite(v)) out.push(v); return; } + if (Array.isArray(v)) { for (const x of v) walk(x); return; } + if (v && typeof v === 'object') { for (const x of Object.values(v)) walk(x); } + }; + walk(value); + return out; +} + +/** + * 数字 n 是否能在 facts 的 data 里找到匹配。 + * 容差兼顾展示舍入与量纲:比例 0–1 在文本里常以百分数出现(×100), + * 秒在文本里常以分钟出现(÷60)。故匹配 n≈v、n≈v×100、n≈v÷60 三种换算。 + * 容差 = max(0.01, |目标|×0.001),覆盖两位小数舍入。 + */ +export function factsContain(facts: ServiceResult[], n: number): boolean { + const values = facts.flatMap((f) => collectNumbers(f.data)); + const near = (a: number, b: number): boolean => Math.abs(a - b) <= Math.max(0.01, Math.abs(b) * 0.001); + return values.some((v) => near(n, v) || near(n, v * 100) || near(n, v / 60)); +} + +/** 出处三件齐备:caliberVersion + timeRange(from/to) + source。 */ +function hasFullSource(f: ServiceResult): boolean { + return !!f.caliberVersion && !!f.timeRange && !!f.timeRange.from && !!f.timeRange.to && !!f.source; +} + +/** + * 五道闸统一入口(闸 2→3→1→5;闸 4 由 guardDrill 单独守,因为它是下钻链而非单条回答)。 + * 顺序与建议书 4.3.4 示例一致:先验出处,再验跨版本,再验数字,最后验收益区间。 + * ★ 非空守卫:facts 为空时,若草稿含数字则闸 1 拦下(无工具来源);不含数字也按闸 2 拦(无出处)。 + */ +export function guardAnswer(draft: AnswerDraft, facts: ServiceResult[]): GuardResult { + /* 闸 2:出处强制。任一 fact 缺三件 → 不发布。空 facts 同样视为出处缺失。 */ + if (facts.length === 0 || !facts.every(hasFullSource)) { + return { ok: false, gate: 2, reason: '出处缺失:caliberVersion / timeRange / source 任一不全' }; + } + /* 闸 3:跨版本拒绝。仅 COMPARE 意图触发;多版本并列查询不拦(各自带版本即可)。 */ + const versions = new Set(facts.map((f) => f.caliberVersion)); + if (versions.size > 1 && draft.intent === 'COMPARE') { + return { ok: false, gate: 3, reason: '口径版本不一致,无法对比' }; + } + /* 闸 1:数字只来自工具。草稿里每个数字都必须能在 facts.data 找到匹配。 */ + const unmatched = extractNumbers(draft.text).filter((n) => !factsContain(facts, n)); + if (unmatched.length > 0) { + return { ok: false, gate: 1, reason: `数字无工具来源: ${unmatched.join(', ')}` }; + } + /* 闸 5:收益给区间。点值(min===max)一律拒绝。 */ + if (draft.benefits?.some((b) => b.min === b.max)) { + return { ok: false, gate: 5, reason: '收益必须给区间,点值拒绝' }; + } + return { ok: true }; +} + +/** 下钻链的一层:层级名 + 是否有证据 + 缺失环节说明。 */ +export interface DrillLayer { + layer: string; + hasEvidence: boolean; + /** 缺证据时列出缺失环节与补录项 */ + missing?: string[]; +} + +/** + * 闸 4:证据链完整性。下钻任一层缺证据 → 停止下钻,列出缺失环节,转人工。 + * ★ 非空守卫:空链视为缺证据(不允许「无链即通过」)。 + */ +export function guardDrill(layers: DrillLayer[]): GuardResult { + if (layers.length === 0) { + return { ok: false, gate: 4, reason: '证据链为空,停止下钻' }; + } + const broken = layers.filter((l) => !l.hasEvidence); + if (broken.length > 0) { + const missing = broken.flatMap((l) => (l.missing?.length ? l.missing : [`${l.layer} 缺证据`])); + return { ok: false, gate: 4, reason: `证据链不全,停止下钻;缺失环节:${missing.join('、')};请补录后重试` }; + } + return { ok: true }; +} + +/** 五道闸自检:供校验脚本与「说明与对照」页引用。 */ +export function guardStats() { + return { + gateCount: 5, + gates: ([1, 2, 3, 4, 5] as const).map((g) => ({ gate: g, ...GATE_LABEL[g] })), + boundary: '可读、可算、可建议、可派单;不可改数、不可代签核', + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/lineSynthesis.ts b/src/modules/tfamd-oee/lib/oee/lineSynthesis.ts new file mode 100644 index 0000000..a4fa23d --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/lineSynthesis.ts @@ -0,0 +1,271 @@ +/** + * L2 引擎 · 产线合成与周期汇总(规划书 4.1.5 / 建议书 §2.5 lineSynthesis)。 + * + * ★ 零 IO 纯函数。守断言④:**产线合成不用均值**。 + * + * 四条规则(原文照录,一条都不能改): + * 1. 串行线(SRF):A/Q 连乘,P 取瓶颈站。**不做算术平均。** + * 2. 并行线(FT):按投入量加权。**不做简单平均。** + * 3. 区域汇总:线别加权。 + * 4. 周期汇总:按 biz_date 累加分子分母,月度按日分配。 + * **不用月度平均倒推日 OEE。** + * + * 两个最容易写错、且错了看不出来的地方: + * - 并行加权是**对 A/P/Q 三率分别加权后再连乘**,不是"对各台 OEE 求加权平均"。 + * 两者数值不同(交叉项归属不同),POC 的 81.69% 是前者。 + * - 周期汇总是**Σ分子/Σ分母**,不是"日 OEE 求平均"。日与日的分母不等长, + * 平均会让短日与长日同权,月度数字必然偏。 + * + * 本模块刻意提供 arithmeticMean / meanOfDailyOee 两个**错误方法**出口, + * 只供校验脚本与 UI 做反例对照,任何真实读数都不得走这两条路。 + */ +import { EPS, type TierValues } from '../../types/oee'; + +/** 参与合成的成员。设备 / 线体 / 日 都用同一形状,避免三套结构。 */ +export interface SynthesisMember { + id: string; + a: number; + p: number; + q: number; + oee: number; + /** 投入量:并行加权的权重。串行不用它。 */ + inputQty: number; + /** 周期累计用的分子分母(日→月)。缺失则该成员不参与周期累计。 */ + pptSec?: number; + runSec?: number; + /** 理想工时 = outputQty × ICT */ + idealSec?: number; + outputQty?: number; + goodQty?: number; +} + +export type SynthesisMethod = 'SERIAL_MULTIPLY' | 'PARALLEL_WEIGHTED' | 'PERIOD_ACCUMULATE'; + +export const METHOD_LABEL: Record = { + SERIAL_MULTIPLY: '串行连乘(A/Q 连乘,P 取瓶颈)', + PARALLEL_WEIGHTED: '并行加权(按投入量对三率分别加权)', + PERIOD_ACCUMULATE: '周期累计(Σ分子/Σ分母)', +}; + +export interface SynthesisResult { + method: SynthesisMethod; + scopeLabel: string; + memberIds: string[]; + a: number; + p: number; + q: number; + oee: number; + /** 串行:瓶颈站 id 与选取依据 */ + bottleneckId?: string; + bottleneckReason?: string; + /** 并行:各成员权重(归一化后),供 UI 展开 */ + weights?: { id: string; inputQty: number; weight: number }[]; + /** 周期:累计后的分子分母,供 UI 展开 */ + accumulated?: { pptSec: number; runSec: number; idealSec: number; outputQty: number; goodQty: number }; + /** 输入不合法时为 false,页面必须显示原因而不是显示 0% */ + ok: boolean; + problems: string[]; + /** 算式原文,数字由成员现算 */ + formula: string; +} + +function clamp01(x: number): number { + if (!Number.isFinite(x)) return 0; + return Math.min(1, Math.max(0, x)); +} + +function div(n: number, d: number): number { + return d > EPS ? n / d : 0; +} + +function emptyResult(method: SynthesisMethod, scopeLabel: string, problems: string[]): SynthesisResult { + return { + method, scopeLabel, memberIds: [], a: 0, p: 0, q: 0, oee: 0, + ok: false, problems, formula: '输入为空或非法,未计算', + }; +} + +/** 三率必须落在 [0,1]。超界说明上游算错,合成层不替它兜底。 */ +function rateProblems(members: SynthesisMember[]): string[] { + const problems: string[] = []; + for (const m of members) { + for (const k of ['a', 'p', 'q', 'oee'] as const) { + const v = m[k]; + if (!Number.isFinite(v)) problems.push(`${m.id}.${k} 非有限数`); + else if (v < -EPS || v > 1 + EPS) problems.push(`${m.id}.${k}=${v} 超出 [0,1]`); + } + if (!Number.isFinite(m.inputQty) || m.inputQty < 0) problems.push(`${m.id}.inputQty 非法`); + } + return problems; +} + +/** + * 串行线合成:A/Q 连乘,P 取瓶颈站。 + * + * 瓶颈站选取:显式 bottleneckId 优先(台账 LineMaster.bottleneckDeviceId); + * 未给则取 **P 最低站**(性能约束最紧的一站),并把依据写进 bottleneckReason。 + * 不取 OEE 最低站——OEE 低可能是质量差,与产能瓶颈不是一回事。 + */ +export function synthesizeSerial( + members: SynthesisMember[], + scopeLabel: string, + bottleneckId?: string, +): SynthesisResult { + if (members.length === 0) return emptyResult('SERIAL_MULTIPLY', scopeLabel, ['成员为空']); + const problems = rateProblems(members); + if (problems.length > 0) return emptyResult('SERIAL_MULTIPLY', scopeLabel, problems); + + let bottleneck: SynthesisMember | undefined; + let reason = ''; + if (bottleneckId) { + bottleneck = members.find((m) => m.id === bottleneckId); + if (!bottleneck) { + return emptyResult('SERIAL_MULTIPLY', scopeLabel, [`指定瓶颈站 ${bottleneckId} 不在成员内`]); + } + reason = `台账指定瓶颈站 ${bottleneckId}`; + } else { + bottleneck = members.reduce((lo, m) => (m.p < lo.p ? m : lo), members[0]); + reason = `未指定瓶颈站,取 P 最低站 ${bottleneck.id}(P=${(bottleneck.p * 100).toFixed(2)}%)`; + } + + const a = members.reduce((acc, m) => acc * m.a, 1); + const q = members.reduce((acc, m) => acc * m.q, 1); + const p = bottleneck.p; + return { + method: 'SERIAL_MULTIPLY', scopeLabel, memberIds: members.map((m) => m.id), + a: clamp01(a), p: clamp01(p), q: clamp01(q), oee: clamp01(a * p * q), + bottleneckId: bottleneck.id, bottleneckReason: reason, + ok: true, problems: [], + formula: `A=${members.map((m) => m.a.toFixed(6)).join('×')};Q=${members.map((m) => m.q.toFixed(6)).join('×')};` + + `P=P(${bottleneck.id})=${p.toFixed(6)};OEE=A×P×Q`, + }; +} + +/** + * 并行机群合成:按投入量对 **A/P/Q 三率分别加权**,再连乘得 OEE。 + * ⚠ 不是对各台 OEE 求加权平均——那是另一个数,POC 的 81.69% 用的是本式。 + */ +export function synthesizeParallel(members: SynthesisMember[], scopeLabel: string): SynthesisResult { + if (members.length === 0) return emptyResult('PARALLEL_WEIGHTED', scopeLabel, ['成员为空']); + const problems = rateProblems(members); + const totalQty = members.reduce((s, m) => s + m.inputQty, 0); + if (totalQty <= EPS) problems.push('投入量合计为 0,无法加权(不得退化为简单平均)'); + if (problems.length > 0) return emptyResult('PARALLEL_WEIGHTED', scopeLabel, problems); + + const weights = members.map((m) => ({ id: m.id, inputQty: m.inputQty, weight: m.inputQty / totalQty })); + const wsum = (k: 'a' | 'p' | 'q') => members.reduce((s, m) => s + m[k] * m.inputQty, 0) / totalQty; + const a = wsum('a'); + const p = wsum('p'); + const q = wsum('q'); + return { + method: 'PARALLEL_WEIGHTED', scopeLabel, memberIds: members.map((m) => m.id), + a: clamp01(a), p: clamp01(p), q: clamp01(q), oee: clamp01(a * p * q), + weights, ok: true, problems: [], + formula: `权重=投入量/Σ投入量(Σ=${totalQty});A=Σ(aᵢwᵢ);P=Σ(pᵢwᵢ);Q=Σ(qᵢwᵢ);OEE=A×P×Q`, + }; +} + +/** + * 周期汇总:Σ分子 / Σ分母。**不用日 OEE 求平均倒推。** + * 缺分子分母的成员直接判非法,不静默跳过——跳过会让月度数字悄悄偏。 + */ +export function synthesizePeriod(members: SynthesisMember[], scopeLabel: string): SynthesisResult { + if (members.length === 0) return emptyResult('PERIOD_ACCUMULATE', scopeLabel, ['成员为空']); + const problems: string[] = []; + for (const m of members) { + for (const k of ['pptSec', 'runSec', 'idealSec', 'outputQty', 'goodQty'] as const) { + const v = m[k]; + if (typeof v !== 'number' || !Number.isFinite(v) || v < 0) problems.push(`${m.id}.${k} 缺失或非法,周期累计不得静默跳过`); + } + } + if (problems.length > 0) return emptyResult('PERIOD_ACCUMULATE', scopeLabel, problems); + + const acc = { + pptSec: members.reduce((s, m) => s + (m.pptSec ?? 0), 0), + runSec: members.reduce((s, m) => s + (m.runSec ?? 0), 0), + idealSec: members.reduce((s, m) => s + (m.idealSec ?? 0), 0), + outputQty: members.reduce((s, m) => s + (m.outputQty ?? 0), 0), + goodQty: members.reduce((s, m) => s + (m.goodQty ?? 0), 0), + }; + const a = clamp01(div(acc.runSec, acc.pptSec)); + const p = clamp01(div(acc.idealSec, acc.runSec)); + const q = clamp01(div(acc.goodQty, acc.outputQty)); + return { + method: 'PERIOD_ACCUMULATE', scopeLabel, memberIds: members.map((m) => m.id), + a, p, q, oee: clamp01(a * p * q), accumulated: acc, ok: true, problems: [], + formula: `A=ΣrunSec/ΣpptSec=${acc.runSec}/${acc.pptSec};P=ΣidealSec/ΣrunSec;Q=ΣgoodQty/ΣoutputQty`, + }; +} + +/** 区域汇总 = 线别加权(规划书 4.1.5 第 3 条)。复用并行加权,权重取线体投入量。 */ +export function synthesizeRegion(lines: SynthesisMember[], scopeLabel: string): SynthesisResult { + const r = synthesizeParallel(lines, scopeLabel); + return { ...r, formula: `区域=线别加权;${r.formula}` }; +} + +/** 统一入口:按方法分派。页面只调这一个,不在组件里另写合成逻辑(断言②)。 */ +export function synthesizeLine( + method: SynthesisMethod, + members: SynthesisMember[], + scopeLabel: string, + bottleneckId?: string, +): SynthesisResult { + if (method === 'SERIAL_MULTIPLY') return synthesizeSerial(members, scopeLabel, bottleneckId); + if (method === 'PARALLEL_WEIGHTED') return synthesizeParallel(members, scopeLabel); + return synthesizePeriod(members, scopeLabel); +} + +/* ══════════════════════════════════════════════════════════════════ + * 反例出口(**错误方法**,只供对照,任何真实读数不得调用) + * ══════════════════════════════════════════════════════════════════ */ + +/** 错误方法①:算术平均。断言④要求它必须与正确合成结果不同。 */ +export function arithmeticMean(members: SynthesisMember[]): { a: number; p: number; q: number; oee: number } { + const n = members.length; + if (n === 0) return { a: 0, p: 0, q: 0, oee: 0 }; + const mean = (k: 'a' | 'p' | 'q' | 'oee') => members.reduce((s, m) => s + m[k], 0) / n; + return { a: mean('a'), p: mean('p'), q: mean('q'), oee: mean('oee') }; +} + +/** 错误方法②:对各台 OEE 求投入量加权平均(≠ 三率分别加权后连乘)。 */ +export function weightedMeanOfOee(members: SynthesisMember[]): number { + const total = members.reduce((s, m) => s + m.inputQty, 0); + if (total <= EPS) return 0; + return members.reduce((s, m) => s + m.oee * m.inputQty, 0) / total; +} + +/** 错误方法③:日 OEE 求平均倒推月度。 */ +export function meanOfDailyOee(daily: { oee: number }[]): number { + if (daily.length === 0) return 0; + return daily.reduce((s, d) => s + d.oee, 0) / daily.length; +} + +/** + * 合成结果的独立复核:不用 result.oee,直接从三率重算, + * 防止「oee 字段算错但页面照样显示」的假通过(与 threeTier.verifyIdentityFromRates 同一手法)。 + */ +export function verifySynthesisFromRates(r: SynthesisResult): { ok: boolean; residual: number } { + const residual = r.a * r.p * r.q - r.oee; + return { ok: Math.abs(residual) < EPS, residual }; +} + +/** 把合成结果转成 TierValues 形状(rtSec/avSec/opSec 在合成层无定义,置 0 并由调用方标注)。 */ +export function toTierValues(r: SynthesisResult, ictSec: number): TierValues { + return { + a: r.a, p: r.p, q: r.q, oee: r.oee, + rtSec: 0, avSec: 0, opSec: 0, + outputQty: r.accumulated?.outputQty ?? 0, + goodQty: r.accumulated?.goodQty ?? 0, + ictSec, + }; +} + +/** 串行连乘的一个性质:成员越多,A/Q 只会更小或相等(每率 ≤1)。用于反例自检。 */ +export function serialNeverExceedsMin(members: SynthesisMember[]): boolean { + if (members.length === 0) return false; + const r = synthesizeSerial(members, '自检'); + if (!r.ok) return false; + const minA = Math.min(...members.map((m) => m.a)); + const minQ = Math.min(...members.map((m) => m.q)); + return r.a <= minA + EPS && r.q <= minQ + EPS; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/lossBuckets.ts b/src/modules/tfamd-oee/lib/oee/lossBuckets.ts new file mode 100644 index 0000000..32be76a --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/lossBuckets.ts @@ -0,0 +1,242 @@ +/** + * L2 引擎 · 六大损失桶三级映射 + 残差恒等式(规划书 4.2 / 4.1.6)。 + * + * ★ 零 IO 纯函数。守断言③(残差=0)。 + * + * 三级映射:损失桶 ↔ A/P/Q ↔ 一级/二级因子 ↔ 代表事件。 + * 两条硬约束: + * 1. 六桶互斥且完整覆盖,桶内时长之和恒等于「计划可用时间 − 有效生产时间」,残差为 0; + * 2. 每个事件码唯一归口一个桶,禁止一对多。 + * + * ★ 本引擎把残差做成**可解释的量**,而不是一个神秘的误差项: + * + * PPT = RUN + (DOWN+CHANGE+JAM+WAIT_*) + IDLE (PLAN_STOP/PM 已作 PDT 扣除,UNKNOWN 不计分母) + * RT = RUN + * A 桶 = FAULT + CHANGEOVER + IDLE_MINOR = PPT − RT − IDLE + * P 桶 = SPEED = RT − N×ICT (节拍偏差,无成对事件) + * Q 桶 = PROCESS_DEFECT + STARTUP_DEFECT = (N − good)×ICT (检测结果,无成对事件) + * 有效生产时间 = good×ICT + * ⇒ Σ六桶 = PPT − IDLE − good×ICT + * ⇒ **残差 = PPT − good×ICT − Σ六桶 = IDLE(未归因时长)** + * + * 所以残差 ≠ 0 的唯一合法来源就是「还没归因的时间」。这正是 DQ-06 存在的理由: + * 未归因 > 5% 时阻断发布,页面显式告警,**绝不允许用"其他"桶把它悄悄吸收掉,也不允许归一化**。 + * 全部归因完成时 IDLE=0,残差自然为 0。 + */ +import { + LOSS_BUCKETS, BUCKET_FACTOR, BUCKET_LABEL, EPS, + type Device, type EventDef, type FactorDuration, type LossBucket, + type LossBucketResult, type StateSegment, +} from '../../types/oee'; + +/** 状态 → 损失桶。计划类(PLAN_STOP/PM)与 UNKNOWN 不进桶;IDLE 是残差来源,也不进桶。 */ +export const STATE_TO_BUCKET: Partial> = { + DOWN: 'FAULT', + CHANGE: 'CHANGEOVER', + JAM: 'IDLE_MINOR', + WAIT_MAT: 'IDLE_MINOR', + WAIT_UNLOAD: 'IDLE_MINOR', + WAIT_PERSON: 'IDLE_MINOR', +}; + +export interface BucketInput { + device: Device; + segments: StateSegment[]; + /** + * **事件实例 id** → 事件定义。由调用方显式注入(引擎不读数据层、不用模块级全局)。 + * 缺了它就无法把状态段回溯到事件码,断言①的血缘链会断。 + * + * ★ 键空间陷阱(曾真实踩中,故字段名带 InstanceId 明示): + * segments[].eventIds 来自 EventPair.eventIds = [st.id, en.id],装的是**实例 id**; + * 而 EVENT_BY_CODE 是按**定义码**(S-27/S-29…)建索引的字典。 + * 若把 EVENT_BY_CODE 直接传进来,`dict[实例id]` 恒为 undefined: + * - eventCodes 全空 → 指标树 L3 驱动因子一个都建不出来; + * - 因子层 `if (!primaryDef) continue` 跳过每个段 → factors/untimedSubFactors 恒为空数组。 + * 两者都**不报错**,且 `factors.every(...)` 在空数组上恒真 → 校验假绿。 + * 正确构造:Object.fromEntries(events.map(e => [e.id, EVENT_BY_CODE[e.defCode]])) + */ + eventDefByInstanceId: Record; + /** 计划可用时间 PPT = CT − PDT − UNKNOWN,由状态机给出,不在这里重算 */ + pptSec: number; + /** 运行时间 RT = RUN 段时长之和 */ + rtSec: number; + outputQty: number; + goodQty: number; + /** + * 开机不良颗数(换型后爬坡 / 首件不良 / rescreen 复测)。 + * 过程不良 = 总不良 − 开机不良。原型由调用方按检测结果注入,引擎不猜。 + */ + startupDefectQty?: number; +} + +export interface BucketOutput { + buckets: LossBucketResult[]; + factors: FactorDuration[]; + /** + * 段内出现但**未单独计量**的子因子(如 Down 段里的「维修等待」)。 + * 这是数据缺口,不是 0:缺 EA 到场时间戳就无法把停机拆成「故障」与「等维修」。 + * UI 必须标灰并说明缺什么,禁止摊一个数出来充精度。 + */ + untimedSubFactors: { factorL1: string; factorL2: string; segmentIds: string[]; eventIds: string[] }[]; + /** 有效生产时间 = good×ICT */ + effectiveSec: number; + /** 残差 = PPT − 有效生产时间 − Σ桶时长;恒等于未归因 IDLE 时长 */ + residualSec: number; + /** 未归因时长(IDLE 段),残差的唯一合法来源 */ + unattributedSec: number; + unattributedPct: number; + /** 残差是否为 0(EPS 内)。false 时页面必须显式告警 */ + zeroResidual: boolean; + /** 残差来源解释,供 UI 直接展示,不让评审猜 */ + residualNote: string; +} + +export function mapToBuckets(input: BucketInput): BucketOutput { + const { device, segments, eventDefByInstanceId, pptSec, rtSec, outputQty, goodQty } = input; + const ict = device.ictSec; + + // ── A 类三桶:来自状态段,有事件证据 ────────────────────────────────── + const acc = new Map }>(); + for (const b of LOSS_BUCKETS) acc.set(b, { sec: 0, segIds: [], codes: new Set() }); + + let unattributedSec = 0; + for (const s of segments) { + if (s.state === 'IDLE') { unattributedSec += s.durationSec; continue; } + const bucket = STATE_TO_BUCKET[s.state]; + if (!bucket) continue; // PLAN_STOP / PM / UNKNOWN / RUN 不进桶 + const slot = acc.get(bucket)!; + slot.sec += s.durationSec; + slot.segIds.push(s.id); + for (const id of s.eventIds) { + const code = eventDefByInstanceId[id]?.code; + if (code) slot.codes.add(code); + } + } + + // ── P 桶:速度降低 = RT − N×ICT(节拍缺口,无成对事件)───────────────── + const idealSec = outputQty * ict; + const speedSec = Math.max(0, rtSec - idealSec); + acc.get('SPEED')!.sec = speedSec; + + // ── Q 两桶:(N − good)×ICT,按开机/过程拆分(无成对事件)─────────────── + const defectQty = Math.max(0, outputQty - goodQty); + const startupQty = Math.min(defectQty, Math.max(0, input.startupDefectQty ?? 0)); + const processQty = defectQty - startupQty; + acc.get('STARTUP_DEFECT')!.sec = startupQty * ict; + acc.get('PROCESS_DEFECT')!.sec = processQty * ict; + + const buckets: LossBucketResult[] = LOSS_BUCKETS.map((b) => { + const slot = acc.get(b)!; + return { + bucket: b, + factor: BUCKET_FACTOR[b], + durationSec: slot.sec, + // 分母统一为 PPT,不是 CT,也不是日历时间 + pctOfPlanTime: pptSec > 0 ? slot.sec / pptSec : 0, + derivedFromCycleDeviation: b === 'SPEED' || b === 'PROCESS_DEFECT' || b === 'STARTUP_DEFECT', + eventCodes: [...slot.codes].sort(), + }; + }); + + // ── 因子时长(原型不落库,现算返回;类型必须存在,生产阶段直接落库)──── + // ★ 一个段只能归一个因子。成对事件的开始/结束两端二级因子可能不同 + // (S-27 = Down Time/Down,S-28 = Down Time/维修等待),若按事件逐个累加, + // 同一段 2400s 会被计进两个因子,因子合计就会大于 A 桶合计。 + // 规则:整段归**首事件**(pairing 保证 eventIds 开始在前的二级因子), + // 其余事件只留证不计时;被跳过的子因子作为**数据缺口**显式披露,不摊造数字。 + const factors: FactorDuration[] = []; + const factorAcc = new Map(); + const untimed = new Map(); + for (const s of segments) { + const bucket = STATE_TO_BUCKET[s.state]; + if (!bucket) continue; + const primaryId = s.eventIds[0]; + const primaryDef = primaryId ? eventDefByInstanceId[primaryId] : undefined; + if (!primaryDef) continue; // 无事件证据的段不编造因子归属 + const key = `${primaryDef.factorL1}|${primaryDef.factorL2}`; + const cur = factorAcc.get(key) ?? { + factorL1: primaryDef.factorL1, factorL2: primaryDef.factorL2, bucket, + factor: BUCKET_FACTOR[bucket], durationSec: 0, segmentIds: [], eventIds: [], + }; + if (!cur.segmentIds.includes(s.id)) { + cur.durationSec += s.durationSec; + cur.segmentIds.push(s.id); + } + for (const id of s.eventIds) { + if (!cur.eventIds.includes(id)) cur.eventIds.push(id); + const def = eventDefByInstanceId[id]; + if (!def || id === primaryId) continue; + const subKey = `${def.factorL1}|${def.factorL2}`; + if (subKey === key) continue; + const slot = untimed.get(subKey) ?? { + factorL1: def.factorL1, factorL2: def.factorL2, segmentIds: [], eventIds: [], + }; + if (!slot.segmentIds.includes(s.id)) slot.segmentIds.push(s.id); + if (!slot.eventIds.includes(id)) slot.eventIds.push(id); + untimed.set(subKey, slot); + } + factorAcc.set(key, cur); + } + factors.push(...factorAcc.values()); + + const effectiveSec = goodQty * ict; + const sumBuckets = buckets.reduce((a, b) => a + b.durationSec, 0); + const residualSec = pptSec - effectiveSec - sumBuckets; + const zeroResidual = Math.abs(residualSec) < EPS; + const unattributedPct = pptSec > 0 ? unattributedSec / pptSec : 0; + + return { + buckets, factors, untimedSubFactors: [...untimed.values()], + effectiveSec, residualSec, unattributedSec, unattributedPct, zeroResidual, + residualNote: zeroResidual + ? '残差 0:计划可用时间已被六桶与有效生产时间完整解释' + : `残差 ${residualSec.toFixed(3)}s = 未归因时长 ${unattributedSec.toFixed(3)}s(占 PPT ${(unattributedPct * 100).toFixed(2)}%)。` + + '这不是计算误差,是还没归因的时间;不得归一化,不得塞进"其他"桶。', + }; +} + +/** + * 残差断言。**不做归一化**:不通过就返回 ok=false 与差额,由调用方显式告警。 + * 允许的差额只有 EPS 级浮点误差;IDLE 造成的差额是业务事实,必须暴露。 + */ +export function assertZeroResidual(out: BucketOutput): { ok: boolean; residualSec: number; reason: string } { + if (out.zeroResidual) return { ok: true, residualSec: out.residualSec, reason: '残差为 0' }; + return { + ok: false, + residualSec: out.residualSec, + reason: `残差 ${out.residualSec.toFixed(6)}s ≠ 0,来源为未归因时长 ${out.unattributedSec.toFixed(6)}s。` + + '按 G2 门要求显式告警,禁止悄悄归一化。', + }; +} + +/** 六桶是否互斥且完备:每个桶的 factor 必须与 BUCKET_FACTOR 一致,且六桶齐全。 */ +export function checkBucketShape(buckets: LossBucketResult[]): { ok: boolean; problems: string[] } { + const problems: string[] = []; + if (buckets.length !== LOSS_BUCKETS.length) problems.push(`桶数 ${buckets.length} ≠ 6`); + const seen = new Set(); + for (const b of buckets) { + if (seen.has(b.bucket)) problems.push(`桶 ${b.bucket} 重复`); + seen.add(b.bucket); + if (!LOSS_BUCKETS.includes(b.bucket)) problems.push(`非法桶 ${b.bucket}`); + if (b.factor !== BUCKET_FACTOR[b.bucket]) problems.push(`${b.bucket} 的 A/P/Q 归属错`); + if (b.durationSec < -EPS) problems.push(`${b.bucket} 时长为负`); + if (!BUCKET_LABEL[b.bucket]) problems.push(`${b.bucket} 缺中文名`); + } + for (const b of LOSS_BUCKETS) if (!seen.has(b)) problems.push(`缺桶 ${b}`); + return { ok: problems.length === 0, problems }; +} + +/** + * 事件唯一归口校验:同一事件码不得映射到两个桶。 + * 这是「禁止一对多映射」的可执行形式。 + */ +export function checkUniqueBucketAssignment(defs: EventDef[]): { ok: boolean; conflicts: string[] } { + const map = new Map>(); + for (const d of defs) { + const set = map.get(d.code) ?? new Set(); + set.add(d.bucket ?? 'NULL'); + map.set(d.code, set); + } + const conflicts = [...map.entries()].filter(([, v]) => v.size > 1).map(([k, v]) => `${k}→${[...v].join('/')}`); + return { ok: conflicts.length === 0, conflicts }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/pairing.ts b/src/modules/tfamd-oee/lib/oee/pairing.ts new file mode 100644 index 0000000..19998a0 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/pairing.ts @@ -0,0 +1,325 @@ +/** + * L2 引擎 · 事件配对与五级级联归因(规划书 7.4)。 + * + * ★ 零 IO 纯函数:不 import data/、不 fetch、不读时钟(Date.now 禁用)。 + * 所有输入由调用方注入,所有"当前时间"来自 ctx.now,保证可重放。 + * 守断言①(血缘可追)与断言⑥(D 类重算)。 + * + * 四种配对策略:紧密配对 TIGHT(A 高) / 缺失结束 MISSING_END(C) / 缺失开始 MISSING_START(B) / 多报警共存 MULTI_ALARM(C) + * 配对约束:同类优先、不跨报警码;结束 > 开始且间隔 ≤ 规则最大值(12h);不跨班次、不跨关机;双向引用。 + * 五级级联归因:1.00 设备自识别 → 0.95 MES 窗口唯一 → 0.85 多候选缩小 → 0.90 换型窗口 → 0.00 无法归因进池。 + * ⚠ 第 5 级是整套设计的诚实性所在:**绝不猜测**,不允许用"其他"桶把未归因悄悄吸收掉。 + */ +import { + ATTR_CONFIDENCE, EPS, + type AttributionLink, type AttrMethod, type CalcContext, type EventDef, type EventInstance, +} from '../../types/oee'; + +/** 配对规则最大值:12 小时(规划书 7.4「间隔 ≤ 规则最大值(如 12h)」) */ +export const MAX_PAIR_GAP_SEC = 12 * 3600; + +/** 缺失结束时的兜底时长上限:不外推到无穷,封顶到窗口结束或此值 */ +export const MISSING_END_CAP_SEC = 4 * 3600; + +export type PairStrategy = 'TIGHT' | 'MISSING_END' | 'MISSING_START' | 'MULTI_ALARM'; + +/** 策略 → 置信度(规划书 7.4 的 A/B/C 是定性等级,这里落到可比的数值) */ +export const STRATEGY_CONFIDENCE: Record = { + TIGHT: 1.00, // A 高 + MISSING_START: 0.90, // B + MISSING_END: 0.85, // C + MULTI_ALARM: 0.85, // C +}; + +export interface EventPair { + pairId: string; + /** 家族键 = region|归一化事件名(去掉 —开始/—结束 与括号补充说明) */ + family: string; + region: EventDef['region']; + startCode: string; + endCode: string; + start?: EventInstance; + end?: EventInstance; + strategy: PairStrategy; + startEpoch: number; + endEpoch: number; + durationSec: number; + confidence: number; + /** 双向引用:两端事件的 id 都记在这里,任一端的 evidence 都能回溯 */ + eventIds: string[]; + /** 缺失端是否由规则补出(补出的时刻不是观测值,必须标出来) */ + filledEnd: boolean; + filledStart: boolean; +} + +export interface LotWindow { + lotId: string; + workOrderId?: string; + device: string; + startEpoch: number; + endEpoch: number; + /** 设备自识别(FT/ASLT lot_summary 直接带 lot 号) */ + selfIdentified: boolean; + /** 换型窗口(EOM)标记 */ + isSetupWindow?: boolean; + /** 工程批(ENG 开头)——C10 默认剔除 */ + isEngineering?: boolean; + /** + * 本 lot 在该设备上的投入/合格数量。状态机③把它作为 RUN 锚点的产出来源。 + * 不给数量时按 0 计(不凭空造数),此时 P/Q 无法计算,由 DQ 规则暴露缺口。 + */ + outputQty?: number; + goodQty?: number; +} + +export interface PairOptions { + /** 班次窗口,用于「不跨班次」约束 */ + shifts?: { id: string; startEpoch: number; endEpoch: number }[]; + /** 关机窗口,用于「不跨关机」约束 */ + shutdowns?: { startEpoch: number; endEpoch: number }[]; + maxGapSec?: number; + missingEndCapSec?: number; +} + +export function toEpoch(iso: string): number { + const t = Date.parse(iso); + if (Number.isNaN(t)) throw new Error(`不可解析的时间:${iso}`); + return Math.floor(t / 1000); +} + +/** + * 事件名 → 家族键。数据驱动(用注入的字典),不硬编码 48 个事件码。 + * 'Down — 开始' → 'Down';'换 lot — 开始(生产)' → '换 lot';'Down — 时长抓取' 保持原样(自含区间)。 + */ +export function familyOf(def: EventDef): string { + const base = def.name + .replace(/\s*—\s*(开始|结束)\s*/g, '') + .replace(/([^)]*)/g, '') + .trim(); + return `${def.region}|${base}`; +} + +function sameShift(a: number, b: number, shifts?: PairOptions['shifts']): boolean { + if (!shifts || shifts.length === 0) return true; + const sa = shifts.find((s) => a >= s.startEpoch && a < s.endEpoch); + /* + * ★ 结束时刻用**左开右闭** (start, end] 查找。 + * 区间 [a,b) 完整落在一个班次内时,b 恰好等于该班次终点仍属同一班。 + * 若两端都用半开 [start,end),12:00→16:00 的计划待料会被判成跨班(16:00 落进中班), + * 于是被拆成 MISSING_END + MISSING_START 两条——把**已完整观测**的起止当成缺失去补造, + * 等于凭空生成证据。这是防幻觉纪律不允许的,故此处按区间归属判定。 + */ + const sb = shifts.find((s) => b > s.startEpoch && b <= s.endEpoch); + // 任一端落在班次外(如跨天班次的边角)时不强行判否,交给跨班拆分处理 + if (!sa || !sb) return true; + return sa.id === sb.id; +} + +function crossesShutdown(a: number, b: number, shutdowns?: PairOptions['shutdowns']): boolean { + if (!shutdowns) return false; + return shutdowns.some((s) => s.startEpoch < b && s.endEpoch > a && !(s.startEpoch <= a && s.endEpoch >= b)); +} + +/** + * 四策略配对。输入同一设备的事件实例(可含未配对散点),输出区间对 + 无法配对的散点。 + * 自含区间的 DERIVED 事件(S-29/S-32 时长抓取)直接成对,params 里带 start/end。 + */ +export function pairEvents( + events: EventInstance[], + defs: Record, + opts: PairOptions = {}, +): { pairs: EventPair[]; unpaired: EventInstance[] } { + const maxGap = opts.maxGapSec ?? MAX_PAIR_GAP_SEC; + const cap = opts.missingEndCapSec ?? MISSING_END_CAP_SEC; + const pairs: EventPair[] = []; + const unpaired: EventInstance[] = []; + const consumed = new Set(); + + // ① 自含区间的派生事件:Down/Jam 时长抓取,params 直接给起止 + for (const ev of events) { + const def = defs[ev.defCode]; + if (!def) { unpaired.push(ev); continue; } + const pStart = ev.params?.intervalStart; + const pEnd = ev.params?.intervalEnd; + if (def.form === 'DERIVED' && typeof pStart === 'string' && typeof pEnd === 'string') { + const a = toEpoch(pStart); + const b = toEpoch(pEnd); + if (b > a) { + consumed.add(ev.id); + pairs.push({ + pairId: `pair-${ev.id}`, family: familyOf(def), region: def.region, + startCode: def.code, endCode: def.code, start: ev, end: ev, + strategy: 'TIGHT', startEpoch: a, endEpoch: b, durationSec: b - a, + confidence: STRATEGY_CONFIDENCE.TIGHT, eventIds: [ev.id], + filledEnd: false, filledStart: false, + }); + } + } + } + + // ② 按家族分组,族内按时间排序后顺序配对 + const groups = new Map(); + for (const ev of events) { + if (consumed.has(ev.id)) continue; + const def = defs[ev.defCode]; + if (!def) continue; + const role = roleOf(ev, def); + if (role === 'NONE') { unpaired.push(ev); consumed.add(ev.id); continue; } + const key = familyOf(def); + const arr = groups.get(key) ?? []; + arr.push(ev); + groups.set(key, arr); + } + + let seq = 0; + for (const [family, arr] of groups) { + arr.sort((x, y) => toEpoch(x.correctedTime) - toEpoch(y.correctedTime) || x.id.localeCompare(y.id)); + const region = defs[arr[0].defCode].region; + const starts = arr.filter((e) => roleOf(e, defs[e.defCode]) === 'START'); + const ends = arr.filter((e) => roleOf(e, defs[e.defCode]) === 'END'); + const usedEnd = new Set(); + + for (const st of starts) { + if (consumed.has(st.id)) continue; + const a = toEpoch(st.correctedTime); + const stDef = defs[st.defCode]; + // 同类优先、不跨报警码 + const cand = ends.filter((en) => { + if (usedEnd.has(en.id) || consumed.has(en.id)) return false; + const enDef = defs[en.defCode]; + if ((stDef.alarmClass ?? '') !== (enDef.alarmClass ?? '')) return false; + const b = toEpoch(en.correctedTime); + if (b <= a) return false; // 结束 > 开始 + if (b - a > maxGap) return false; // 间隔 ≤ 12h + if (!sameShift(a, b, opts.shifts)) return false; // 不跨班次 + if (crossesShutdown(a, b, opts.shutdowns)) return false; // 不跨关机 + return true; + }); + + // 多报警共存:同一开始时刻附近有多个同类开始 → 标 MULTI_ALARM + const concurrent = starts.filter((o) => o.id !== st.id && !consumed.has(o.id) && + Math.abs(toEpoch(o.correctedTime) - a) <= 60); + const multi = concurrent.length > 0; + + if (cand.length > 0) { + const en = cand[0]; + const b = toEpoch(en.correctedTime); + usedEnd.add(en.id); consumed.add(st.id); consumed.add(en.id); + const strategy: PairStrategy = multi ? 'MULTI_ALARM' : 'TIGHT'; + pairs.push({ + pairId: `pair-${++seq}`, family, region, + startCode: stDef.code, endCode: defs[en.defCode].code, + start: st, end: en, strategy, + startEpoch: a, endEpoch: b, durationSec: b - a, + confidence: STRATEGY_CONFIDENCE[strategy], eventIds: [st.id, en.id], + filledEnd: false, filledStart: false, + }); + } else { + // 缺失结束:封顶补出,明确标记 filledEnd,置信度降为 C + const b = a + Math.min(cap, maxGap); + consumed.add(st.id); + pairs.push({ + pairId: `pair-${++seq}`, family, region, + startCode: stDef.code, endCode: stDef.code, + start: st, end: undefined, strategy: 'MISSING_END', + startEpoch: a, endEpoch: b, durationSec: b - a, + confidence: STRATEGY_CONFIDENCE.MISSING_END, eventIds: [st.id], + filledEnd: true, filledStart: false, + }); + } + } + + // 缺失开始:只有结束没有开始 → 往前回推一个 cap,标 filledStart,置信度 B + for (const en of ends) { + if (consumed.has(en.id) || usedEnd.has(en.id)) continue; + const b = toEpoch(en.correctedTime); + const a = Math.max(b - cap, b - maxGap); + consumed.add(en.id); + const enDef = defs[en.defCode]; + pairs.push({ + pairId: `pair-${++seq}`, family, region, + startCode: enDef.code, endCode: enDef.code, + start: undefined, end: en, strategy: 'MISSING_START', + startEpoch: a, endEpoch: b, durationSec: b - a, + confidence: STRATEGY_CONFIDENCE.MISSING_START, eventIds: [en.id], + filledEnd: false, filledStart: true, + }); + } + } + + pairs.sort((x, y) => x.startEpoch - y.startEpoch || x.pairId.localeCompare(y.pairId)); + return { pairs, unpaired }; +} + +/** 从事件名判开始/结束角色。时长抓取类是自含区间,已在①处理,这里返回 NONE。 */ +export function roleOf(ev: EventInstance, def: EventDef): 'START' | 'END' | 'NONE' { + if (ev.pairRole) return ev.pairRole; + if (/—\s*开始/.test(def.name)) return 'START'; + if (/—\s*结束/.test(def.name)) return 'END'; + return 'NONE'; +} + +/** + * 五级级联归因。按置信度从高到低试,命中即返回;全不中 → UNATTRIBUTED(0.00) 进池。 + * 顺序按 ATTR_CONFIDENCE 的数值降序,不按规划书表格的行序(表格里第 3/4 行是 0.85/0.90)。 + */ +export function attributeLot( + ev: EventInstance, + lots: LotWindow[], + ctx: Pick, +): AttributionLink { + const t = toEpoch(ev.correctedTime); + const covering = lots.filter((l) => l.device === ev.device && t >= l.startEpoch && t <= l.endEpoch); + + // 级 1:设备自识别(FT/ASLT lot_summary 直接带 lot 号) + const self = covering.filter((l) => l.selfIdentified); + if (self.length === 1) { + return link(self[0], 'SELF_IDENTIFIED', [ev.evidence.rawLineId]); + } + + // 级 2:MES 窗口唯一匹配 + if (covering.length === 1) { + return link(covering[0], 'MES_UNIQUE', [ev.evidence.rawLineId]); + } + + // 级 4(0.90):换型窗口推断(EOM)——优先于级 3(0.85),按置信度降序 + const setup = covering.filter((l) => l.isSetupWindow); + if (setup.length === 1) { + return link(setup[0], 'SETUP_WINDOW', [ev.evidence.rawLineId]); + } + + // 级 3(0.85):多候选缩小 —— 取窗口最贴近事件时刻的一个,但置信度只给 0.85 + if (covering.length > 1) { + const best = [...covering].sort((x, y) => + Math.abs(x.startEpoch - t) - Math.abs(y.startEpoch - t) || x.lotId.localeCompare(y.lotId))[0]; + return { + ...link(best, 'MULTI_CANDIDATE', [ev.evidence.rawLineId]), + // 多候选必须把候选集全部留证,便于工程师复核 + evidenceRefs: [ev.evidence.rawLineId, ...covering.map((l) => `lot:${l.lotId}`)], + }; + } + + // 级 5:无法归因 → 未归因池,绝不猜测 + void ctx; + return { + method: 'UNATTRIBUTED', + confidence: ATTR_CONFIDENCE.UNATTRIBUTED, + evidenceRefs: [ev.evidence.rawLineId], + unknownPoolId: `unk-${ev.device}-${ev.id}`, + }; +} + +function link(lot: LotWindow, method: AttrMethod, refs: string[]): AttributionLink { + return { + lotId: lot.lotId, + ...(lot.workOrderId ? { workOrderId: lot.workOrderId } : {}), + method, + confidence: ATTR_CONFIDENCE[method], + evidenceRefs: refs, + }; +} + +/** 归因置信度必须恰好是五档之一,不允许出现中间值(防"看起来像归因了"的假置信度)。 */ +export function isValidConfidence(c: number): boolean { + return Object.values(ATTR_CONFIDENCE).some((v) => Math.abs(v - c) < EPS); +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/priority.ts b/src/modules/tfamd-oee/lib/oee/priority.ts new file mode 100644 index 0000000..ad4e456 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/priority.ts @@ -0,0 +1,253 @@ +/** + * L2 引擎 · 优先级评分(断言⑧「优先级可解释」)。 + * + * 来源:《OEE分析AI原型系统构建建议书-2026-11-12.md》§5.3 / 第9章第6项(line 2639)。 + * 方案 A(SOW 直译):损失程度 .30 / 影响范围 .20 / 持续时间 .15 / 产能损失 .20 / 交付影响 .15 + * 方案 B(鼎捷) :影响金额 .30 / 发生频次 .20 / 趋势恶化 .20 / 可改善性 .20 / 证据完备度 .10 + * **两套并列可切换,默认 B**(更贴合「组织与管理」故事线)。 + * + * 评分模型(唯一口径,全站不得另写一份): + * score = Σ_i ( weight_i × factor_i ),factor_i ∈ [0,1],weight_i 之和 = 1。 + * 每个候选项在 10 个维度上各有一个 0..1 分项打分;A/B 两套各取其中 5 个维度加权。 + * 同一批候选项换一套权重 → 排序变化,这正是评审现场要对比的东西。 + * + * 三条诚实性纪律: + * 1. **可重算**:score 必须能由 breakdown 里的 weight×factor 逐条加回(断言⑧核心)。 + * 引擎不做任何隐藏归一化 / 截断 / 缩放;contrib = weight×factor 原样返回。 + * 2. **不静默钳位**:factor 越界(<0 或 >1)属数据质量问题,由 validatePriorityItem 显式报, + * 不在评分里偷偷 clamp 把错误抹平。clampFactor 只是 L3/UI 入口的可选 sanitizer。 + * 3. **纯函数**:零 IO、零时钟、零随机、零模块级可变全局;权重是常量字典,排序 tie-break 用 id。 + * + * 本模块只 import 契约层(types/oee),不 import data/,符合 verify-oee-purity 白名单。 + */ +import { EPS } from '../../types/oee'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、维度字典(10 个分项,A/B 各取 5 个) + * ══════════════════════════════════════════════════════════════════ */ + +/** A 套五维(SOW 直译) */ +export const A_FACTOR_KEYS = ['lossSeverity', 'impactScope', 'duration', 'capacityLoss', 'deliveryImpact'] as const; +/** B 套五维(鼎捷) */ +export const B_FACTOR_KEYS = ['moneyImpact', 'frequency', 'trendWorsening', 'improvability', 'evidenceCompleteness'] as const; +/** 全部 10 个分项键(A∪B,互不重叠)。候选项必须给齐 10 个,才能两套权重都算。 */ +export const PRIORITY_FACTOR_KEYS = [...A_FACTOR_KEYS, ...B_FACTOR_KEYS] as const; +export type PriorityFactorKey = typeof PRIORITY_FACTOR_KEYS[number]; + +/** 分项中文名。全站唯一来源,breakdown 与 UI 共用,不得另写一套。 */ +export const PRIORITY_FACTOR_LABEL: Record = { + lossSeverity: '损失程度', impactScope: '影响范围', duration: '持续时间', + capacityLoss: '产能损失', deliveryImpact: '交付影响', + moneyImpact: '影响金额', frequency: '发生频次', trendWorsening: '趋势恶化', + improvability: '可改善性', evidenceCompleteness: '证据完备度', +}; + +/** 每个分项的 0..1 打分。 */ +export type PriorityFactors = Record; + +/* ══════════════════════════════════════════════════════════════════ + * 二、两套权重(常量字典,权重之和必须 = 1) + * ══════════════════════════════════════════════════════════════════ */ + +export type WeightSchemeId = 'A' | 'B'; + +export interface WeightDim { + key: PriorityFactorKey; + label: string; + /** 权重,0..1;一套之内 Σweight = 1 */ + weight: number; +} + +export interface WeightScheme { + id: WeightSchemeId; + label: string; + /** 出处标注,UI 与说明页共用 */ + source: string; + dims: WeightDim[]; +} + +const dim = (key: PriorityFactorKey, weight: number): WeightDim => + ({ key, label: PRIORITY_FACTOR_LABEL[key], weight }); + +/** + * ★ 权重照录建议书 line 2639,不自行调整。 + * A: .30+.20+.15+.20+.15 = 1.00 + * B: .30+.20+.20+.20+.10 = 1.00 + */ +export const WEIGHT_SCHEMES: Record = { + A: { + id: 'A', label: '方案 A · SOW 直译', source: '建议书第9章第6项〔SOW〕', + dims: [ + dim('lossSeverity', 0.30), dim('impactScope', 0.20), dim('duration', 0.15), + dim('capacityLoss', 0.20), dim('deliveryImpact', 0.15), + ], + }, + B: { + id: 'B', label: '方案 B · 金额/频次导向', source: '建议书第9章第6项〔方案〕', + dims: [ + dim('moneyImpact', 0.30), dim('frequency', 0.20), dim('trendWorsening', 0.20), + dim('improvability', 0.20), dim('evidenceCompleteness', 0.10), + ], + }, +}; + +/** 默认 B(建议书明确:更贴合「组织与管理」故事线)。 */ +export const DEFAULT_WEIGHT_SCHEME: WeightSchemeId = 'B'; + +/** 权重之和(浮点),供透明展示与校验。 */ +export function weightSum(scheme: WeightScheme): number { + return scheme.dims.reduce((a, d) => a + d.weight, 0); +} + +/** 一套权重是否合法:5 维、键唯一、每权 ∈[0,1]、Σ=1(EPS 容差)。 */ +export function validateWeightScheme(scheme: WeightScheme): { ok: boolean; problems: string[] } { + const problems: string[] = []; + if (scheme.dims.length !== 5) problems.push(`维度数应为 5,实际 ${scheme.dims.length}`); + const keys = scheme.dims.map((d) => d.key); + if (new Set(keys).size !== keys.length) problems.push('维度键有重复'); + for (const d of scheme.dims) { + if (!(d.weight >= 0 && d.weight <= 1)) problems.push(`${d.label} 权重 ${d.weight} 越界 [0,1]`); + } + const sum = weightSum(scheme); + if (Math.abs(sum - 1) > EPS) problems.push(`权重之和 ${sum} ≠ 1(容差 ${EPS})`); + return { ok: problems.length === 0, problems }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三、候选项与评分 + * ══════════════════════════════════════════════════════════════════ */ + +export interface PriorityItem { + id: string; + title: string; + /** 10 个分项打分,每个 ∈[0,1]。A/B 各取所需 5 个。 */ + factors: PriorityFactors; + /** 以下为可选展示上下文,**不参与评分**(评分只认 factors)。 */ + region?: 'SRF' | 'FT' | 'ASLT'; + note?: string; +} + +export interface ScoreBreakdownRow { + key: PriorityFactorKey; + label: string; + weight: number; + factor: number; + /** 贡献 = weight × factor,原样不缩放 */ + contrib: number; +} + +export interface PriorityScore { + /** 总分 = Σcontrib,∈[0,1](当 factors 与 weights 均合法时) */ + score: number; + scheme: WeightSchemeId; + schemeLabel: string; + /** 实际用到的权重之和,透明展示(合法时应 = 1) */ + weightSum: number; + breakdown: ScoreBreakdownRow[]; +} + +/** 可选 sanitizer:把越界分项钳到 [0,1]。仅在 L3/UI 入口用,评分本身不调用它。 */ +export function clampFactor(x: number): number { + if (!Number.isFinite(x)) return 0; + return x < 0 ? 0 : x > 1 ? 1 : x; +} + +/** 校验候选项:10 个分项齐全且 ∈[0,1]。越界显式报,不静默抹平。 */ +export function validatePriorityItem(item: PriorityItem): { ok: boolean; problems: string[] } { + const problems: string[] = []; + for (const k of PRIORITY_FACTOR_KEYS) { + const v = item.factors[k]; + if (v === undefined || !Number.isFinite(v)) problems.push(`分项 ${PRIORITY_FACTOR_LABEL[k]} 缺失或非数`); + else if (v < 0 || v > 1) problems.push(`分项 ${PRIORITY_FACTOR_LABEL[k]} = ${v} 越界 [0,1]`); + } + return { ok: problems.length === 0, problems }; +} + +/** 把 scheme 参数('A'|'B' 或自定义权重对象)解析成 WeightScheme。 */ +function resolveScheme(scheme: WeightSchemeId | WeightScheme): WeightScheme { + return typeof scheme === 'string' ? WEIGHT_SCHEMES[scheme] : scheme; +} + +/** + * 评分(断言⑧):score = Σ weight×factor,逐条 breakdown 可重算。 + * @param item 候选项(factors 应已校验 ∈[0,1]) + * @param scheme 'A' | 'B' | 自定义 WeightScheme,默认 B + * + * ★ 不做隐藏变换:contrib 原样 = weight×factor,score = Σcontrib。 + * 校验脚本独立重算 Σweight×factor 必须与此处的 score 深相等(EPS)。 + */ +export function scorePriority( + item: PriorityItem, + scheme: WeightSchemeId | WeightScheme = DEFAULT_WEIGHT_SCHEME, +): PriorityScore { + const ws = resolveScheme(scheme); + const breakdown: ScoreBreakdownRow[] = ws.dims.map((d) => { + const factor = item.factors[d.key]; + return { key: d.key, label: d.label, weight: d.weight, factor, contrib: d.weight * factor }; + }); + const score = breakdown.reduce((a, r) => a + r.contrib, 0); + return { score, scheme: ws.id, schemeLabel: ws.label, weightSum: weightSum(ws), breakdown }; +} + +export interface RankedItem { + item: PriorityItem; + /** 名次,从 1 起 */ + rank: number; + score: PriorityScore; +} + +/** + * 排序:score 降序;同分按 id 升序(确定性 tie-break,不用随机、不用输入顺序)。 + * 返回新数组,不改动入参。 + */ +export function rankPriority( + items: PriorityItem[], + scheme: WeightSchemeId | WeightScheme = DEFAULT_WEIGHT_SCHEME, +): RankedItem[] { + const scored = items.map((item) => ({ item, score: scorePriority(item, scheme) })); + scored.sort((a, b) => { + const d = b.score.score - a.score.score; + if (Math.abs(d) > EPS) return d; + return a.item.id < b.item.id ? -1 : a.item.id > b.item.id ? 1 : 0; + }); + return scored.map((s, i) => ({ item: s.item, rank: i + 1, score: s.score })); +} + +/** + * 两套权重排序对比(评审现场用):返回 A/B 各自的名次序列与「名次是否变化」。 + * 只比 id 序列,不比分数——分数本来就不同,关键是**排序**变没变。 + */ +export function compareSchemes(items: PriorityItem[]): { + orderA: string[]; orderB: string[]; orderChanged: boolean; + rankA: RankedItem[]; rankB: RankedItem[]; +} { + const rankA = rankPriority(items, 'A'); + const rankB = rankPriority(items, 'B'); + const orderA = rankA.map((r) => r.item.id); + const orderB = rankB.map((r) => r.item.id); + const orderChanged = orderA.length === orderB.length && orderA.some((id, i) => id !== orderB[i]); + return { orderA, orderB, orderChanged, rankA, rankB }; +} + +/** 引擎自检:供校验脚本⑧与说明页引用,数字一律现算。 */ +export function priorityStats() { + const a = validateWeightScheme(WEIGHT_SCHEMES.A); + const b = validateWeightScheme(WEIGHT_SCHEMES.B); + return { + factorKeyCount: PRIORITY_FACTOR_KEYS.length, + aFactorKeys: [...A_FACTOR_KEYS], + bFactorKeys: [...B_FACTOR_KEYS], + /** A/B 维度互不重叠 */ + schemesDisjoint: A_FACTOR_KEYS.every((k) => !(B_FACTOR_KEYS as readonly string[]).includes(k)), + schemeIds: Object.keys(WEIGHT_SCHEMES) as WeightSchemeId[], + defaultScheme: DEFAULT_WEIGHT_SCHEME, + weightSumA: weightSum(WEIGHT_SCHEMES.A), + weightSumB: weightSum(WEIGHT_SCHEMES.B), + schemeAValid: a.ok, + schemeBValid: b.ok, + schemeAProblems: a.problems, + schemeBProblems: b.problems, + aDims: WEIGHT_SCHEMES.A.dims.map((d) => ({ key: d.key, label: d.label, weight: d.weight })), + bDims: WEIGHT_SCHEMES.B.dims.map((d) => ({ key: d.key, label: d.label, weight: d.weight })), + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/retrieval.ts b/src/modules/tfamd-oee/lib/oee/retrieval.ts new file mode 100644 index 0000000..46098df --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/retrieval.ts @@ -0,0 +1,111 @@ +/** + * 原型版检索增强(建议书 4.5.2)——内存余弦,零依赖、零向量数据库。 + * + * ★ 纯函数层纪律(ADR-02 / 附加断言):本文件不 import data/,语料池由调用方注入; + * 无 IO、无时钟、无随机、无模块级可变全局。同输入两次调用结果深相等、可重放。 + * + * ★ 失效规则在此生效(比切片粒度更重要): + * - active=false 的切片永不召回(SOP 旧版 / 待复核案例 / 改钟标记)。 + * - caliberVersion 过滤:口径语料禁止跨版本混合检索(闸 3 的检索侧体现)。 + * + * 算法:字符级 TF-IDF + 余弦。语料 <500 条时性能足够(实测 <5ms)。 + * 生产迁移路径:retrieve() 签名不变,内部换 Milvus 查询,语料切片与失效规则完全复用。 + */ +import type { KnowledgeChunk, ScoredChunk, Corpus } from '../../types/oee'; + +export interface RetrievalFilter { + corpus?: Corpus; + /** 传入则只召回该版本的口径语料;非口径语料不受此限 */ + caliberVersion?: string; +} + +/** + * 分词:CJK 逐字 + 相邻二元组(bigram),ASCII 按词。 + * 中文无空格,单字召回噪声大,加 bigram 提升短语区分度(如「未归因」「计划待料」)。 + * 确定性:不依赖任何外部词表或随机。 + */ +export function tokenize(text: string): string[] { + const tokens: string[] = []; + const lower = text.toLowerCase(); + /* ASCII 词(字母数字下划线,含小数点与连字符以保留版本号/事件码) */ + const asciiWords = lower.match(/[a-z0-9][a-z0-9_.\-]*/g) ?? []; + for (const w of asciiWords) tokens.push(w); + /* CJK 逐字 + bigram */ + const cjk = lower.match(/[\u4e00-\u9fff]/g) ?? []; + for (const ch of cjk) tokens.push(ch); + for (let i = 0; i + 1 < cjk.length; i += 1) tokens.push(cjk[i] + cjk[i + 1]); + return tokens; +} + +/** 词频向量(term → count)。 */ +function termFreq(tokens: string[]): Map { + const tf = new Map(); + for (const t of tokens) tf.set(t, (tf.get(t) ?? 0) + 1); + return tf; +} + +/** + * 余弦相似度(TF-IDF 加权)。idf 由注入的语料池现算,保证同池同 query 结果一致。 + * 只对在 query 与 doc 都出现的词求和;向量长度各自归一。 + */ +function cosine(queryTf: Map, docTf: Map, idf: Map): number { + let dot = 0; + let qNorm = 0; + let dNorm = 0; + for (const [term, qCount] of queryTf) { + const w = idf.get(term) ?? 0; + const qWeight = qCount * w; + qNorm += qWeight * qWeight; + const dCount = docTf.get(term); + if (dCount !== undefined) dot += qWeight * (dCount * w); + } + /* doc 范数:遍历全部 doc 词,只含有 idf 的词贡献 */ + for (const [term, dCount] of docTf) { + const w = idf.get(term) ?? 0; + const dWeight = dCount * w; + dNorm += dWeight * dWeight; + } + if (qNorm === 0 || dNorm === 0) return 0; + return dot / (Math.sqrt(qNorm) * Math.sqrt(dNorm)); +} + +/** + * 检索 top-k。失效规则先过滤,再算分排序。 + * ★ 排序确定性:分数降序,同分按 id 升序(不依赖 Map 迭代顺序的不确定性)。 + * @param pool 注入的语料池(L3 传 CHUNKS),引擎不自行 import 数据。 + */ +export function retrieve( + query: string, k: number, filter: RetrievalFilter, pool: KnowledgeChunk[], +): ScoredChunk[] { + const candidates = pool.filter((c) => + c.active + && (!filter.corpus || c.corpus === filter.corpus) + && (!filter.caliberVersion || c.corpus !== 'CALIBER' || c.version === filter.caliberVersion)); + if (candidates.length === 0 || k <= 0) return []; + + /* idf:log(N / df),df 为含该词的活跃切片数。N=candidates.length。 */ + const docTfs = candidates.map((c) => termFreq(tokenize(c.text))); + const df = new Map(); + for (const tf of docTfs) { + for (const term of tf.keys()) df.set(term, (df.get(term) ?? 0) + 1); + } + const n = candidates.length; + const idf = new Map(); + for (const [term, d] of df) idf.set(term, Math.log((n + 1) / (d + 1)) + 1); + + const queryTf = termFreq(tokenize(query)); + const scored: ScoredChunk[] = candidates.map((c, i) => ({ + chunk: c, score: cosine(queryTf, docTfs[i], idf), + })); + scored.sort((a, b) => (b.score - a.score) || (a.chunk.id < b.chunk.id ? -1 : a.chunk.id > b.chunk.id ? 1 : 0)); + return scored.slice(0, k).filter((s) => s.score > 0); +} + +/** 检索自检:供校验脚本引用。 */ +export function retrievalStats(pool: KnowledgeChunk[]) { + return { + poolSize: pool.length, + active: pool.filter((c) => c.active).length, + retired: pool.filter((c) => !c.active).length, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/skills.ts b/src/modules/tfamd-oee/lib/oee/skills.ts new file mode 100644 index 0000000..2d9443c --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/skills.ts @@ -0,0 +1,168 @@ +/** + * 八项技能(建议书 4.4.2)——每项有明确输入输出契约与**代码强制的停止条件**。 + * + * ★ 纯函数层纪律(ADR-02):只 import 契约层与同目录引擎(guards/closure), + * 不 import data/,无 IO/时钟/随机/可变全局。停止条件不靠提示词自觉,靠函数返回 stopped。 + * + * 八项停止条件(与建议书 §4.4.2 表逐条对应,断言⑩逐条触发): + * SK1 问数:三要素不全 → 先反问,不猜 + * SK2 下钻:任一层缺证据 → 即停(闸 4) + * SK3 对比:口径版本不同 → 拒绝(闸 3) + * SK4 归因:低置信 → 转工程师;残差≠0/证据缺失 → 只报缺口不下结论 + * SK5 测算:参数未签字 → 标占位,不给金额 + * SK6 建议:证据链不全 → 只作候选;无匹配案例 → 标「无历史依据」不编收益 + * SK7 派单:四项必填不全 → 拒绝派发(canDispatch=false) + * SK8 复盘:前后期口径版本不同 → 拒绝对比;验证结果缺失 → 标待复核 + * + * 技能链六步(§4.4.3):取数→下钻→归因→引用→建议→派单,每步停止条件串成不可跳步的链。 + */ +import type { ImprovementTask, ServiceResult, ScoredChunk } from '../../types/oee'; +import { EPS } from '../../types/oee'; +import { guardDrill, type DrillLayer } from './guards'; +import { canDispatch } from './closure'; + +/** 技能结果:stopped=true 时带停止条件与处置动作;false 时带产出值。 */ +export type SkillResult = + | { stopped: true; skill: string; condition: string; action: string; prompt?: string } + | { stopped: false; skill: string; value: T }; + +const stop = (skill: string, condition: string, action: string, prompt?: string): SkillResult => + ({ stopped: true, skill, condition, action, prompt }); + +/* ── SK1 问数:三要素(设备 + 时间范围 + 指标)不全 → 先反问,不猜 ─────────── */ +export interface AskInput { device?: string; timeRange?: string; metric?: string; } +export function skillAsk(input: AskInput): SkillResult { + const missing: string[] = []; + if (!input.device) missing.push('设备'); + if (!input.timeRange) missing.push('时间范围'); + if (!input.metric) missing.push('指标'); + if (missing.length > 0) { + return stop('问数', '三要素不全', '先反问,不猜', `请补充:${missing.join('、')}(不猜测默认值)`); + } + return { stopped: false, skill: '问数', value: input }; +} + +/* ── SK2 下钻:任一层缺证据 → 即停(闸 4)───────────────────────────────── */ +export function skillDrill(layers: DrillLayer[]): SkillResult { + const g = guardDrill(layers); + if (!g.ok) return stop('下钻', '任一层缺证据', '即停,转人工', g.reason); + return { stopped: false, skill: '下钻', value: layers }; +} + +/* ── SK3 对比:口径版本不同 → 拒绝(闸 3)───────────────────────────────── */ +export function skillCompare( + a: ServiceResult, b: ServiceResult, +): SkillResult<{ a: ServiceResult; b: ServiceResult }> { + if (a.caliberVersion !== b.caliberVersion) { + return stop('对比', '口径版本不同', '拒绝输出对比结论', '口径版本不一致,无法对比'); + } + return { stopped: false, skill: '对比', value: { a, b } }; +} + +/* ── SK4 归因:低置信 → 转工程师;残差≠0/证据缺失 → 只报缺口 ─────────────── */ +export interface AttributeInput { + /** 归因置信度 0–1(A 类唯一映射高、B 类多变量低) */ + confidence: number; + /** 残差(必须为 0 才下结论) */ + residualSec: number; + /** 证据是否齐备 */ + evidenceComplete: boolean; + /** 低置信阈值,默认 0.7(B 类需补录) */ + confidenceFloor?: number; +} +export function skillAttribute(input: AttributeInput): SkillResult<{ causeClass: 'A' | 'B' | 'C'; confidence: number }> { + const floor = input.confidenceFloor ?? 0.7; + if (!input.evidenceComplete || Math.abs(input.residualSec) > EPS) { + return stop('归因', '残差≠0 或证据缺失', '只报缺口,不下结论', '证据不足,以下为损失结构(不给根因结论)'); + } + if (input.confidence < floor) { + return stop('归因', '低置信', '转工程师', `置信度 ${input.confidence.toFixed(2)} < ${floor},转工程师人工判定`); + } + /* A 类唯一映射置信度高;B 类多变量但证据齐备且过阈值 → 给结论但标 B */ + const causeClass: 'A' | 'B' | 'C' = input.confidence >= 0.9 ? 'A' : 'B'; + return { stopped: false, skill: '归因', value: { causeClass, confidence: input.confidence } }; +} + +/* ── SK5 测算:参数未签字 → 标占位,不给金额 ────────────────────────────── */ +export interface EstimateInput { + /** 费率/参数是否已签字(C27/C28 待 IE 签字 → false) */ + paramsSigned: boolean; + /** 收益区间(仅签字后才允许给金额) */ + benefit?: { min: number; max: number; unit: string }; +} +export function skillEstimate(input: EstimateInput): SkillResult<{ placeholder: boolean; benefit?: { min: number; max: number; unit: string } }> { + if (!input.paramsSigned) { + return stop('测算', '参数未签字', '标占位,不给金额', '费率/参数待 IE 签字,收益标占位,不输出金额数字'); + } + if (input.benefit && input.benefit.min === input.benefit.max) { + return stop('测算', '收益为点值', '重生成(闸 5)', '收益必须给区间'); + } + return { stopped: false, skill: '测算', value: { placeholder: false, benefit: input.benefit } }; +} + +/* ── SK6 建议:证据链不全 → 只作候选;无匹配案例 → 标「无历史依据」────────── */ +export interface SuggestInput { + /** 检索命中的案例(已按失效规则过滤) */ + cases: ScoredChunk[]; + /** 证据链是否完整 */ + evidenceComplete: boolean; +} +export function skillSuggest(input: SuggestInput): SkillResult<{ candidateOnly: boolean; cases: ScoredChunk[] }> { + if (input.cases.length === 0) { + return stop('建议', '无匹配案例', '标「无历史依据」,不编收益', '无历史依据,不编造收益数字'); + } + if (!input.evidenceComplete) { + /* 证据链不全:建议只作候选,不进派单(仍可返回,但标 candidateOnly) */ + return { stopped: false, skill: '建议', value: { candidateOnly: true, cases: input.cases } }; + } + return { stopped: false, skill: '建议', value: { candidateOnly: false, cases: input.cases } }; +} + +/* ── SK7 派单:四项必填不全 → 拒绝派发(canDispatch=false)───────────────── */ +export function skillDispatch(task: ImprovementTask): SkillResult { + const check = canDispatch(task); + if (!check.ok) { + const labels = check.missing.map((m) => m.label).join('、'); + return stop('派单', '四项必填不全', '拒绝派发', `缺四项必填:${labels}(补齐后才能派发)`); + } + return { stopped: false, skill: '派单', value: task }; +} + +/* ── SK8 复盘:前后期口径版本不同 → 拒绝对比;验证结果缺失 → 标待复核 ─────── */ +export interface ReviewInput { + beforeVersion: string; + afterVersion: string; + /** 验证结果(缺失则标待复核) */ + verificationResult?: string; +} +export function skillReview(input: ReviewInput): SkillResult<{ comparable: boolean; pendingReview: boolean }> { + if (input.beforeVersion !== input.afterVersion) { + return stop('复盘', '前后期口径版本不同', '拒绝对比', '口径版本不一致,无法对比前后效果'); + } + if (!input.verificationResult) { + return stop('复盘', '验证结果缺失', '标待复核', '验证结果缺失,标待复核,不给采纳率结论'); + } + return { stopped: false, skill: '复盘', value: { comparable: true, pendingReview: false } }; +} + +/** 八项技能登记:供校验脚本与 UI 同源引用(停止条件与建议书 §4.4.2 表一致)。 */ +export const SKILL_REGISTRY = [ + { id: 'SK1', name: '问数', stop: '三要素不全 → 先反问,不猜', fn: skillAsk }, + { id: 'SK2', name: '下钻', stop: '任一层缺证据 → 即停', fn: skillDrill }, + { id: 'SK3', name: '对比', stop: '口径版本不同 → 拒绝', fn: skillCompare }, + { id: 'SK4', name: '归因', stop: '低置信 → 转工程师', fn: skillAttribute }, + { id: 'SK5', name: '测算', stop: '参数未签字 → 标占位', fn: skillEstimate }, + { id: 'SK6', name: '建议', stop: '证据链不全 → 只作候选', fn: skillSuggest }, + { id: 'SK7', name: '派单', stop: '四项必填不全 → 拒绝派发', fn: skillDispatch }, + { id: 'SK8', name: '复盘', stop: '验证结果缺失 → 标待复核', fn: skillReview }, +] as const; + +export function skillStats() { + return { + count: SKILL_REGISTRY.length, + ids: SKILL_REGISTRY.map((s) => s.id), + names: SKILL_REGISTRY.map((s) => s.name), + chain: '取数 → 下钻 → 归因 → 引用 → 建议 → 派单', + boundary: '可读、可算、可建议、可派单;不可改数、不可代签核', + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/stateMachine.ts b/src/modules/tfamd-oee/lib/oee/stateMachine.ts new file mode 100644 index 0000000..0c5deb9 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/stateMachine.ts @@ -0,0 +1,429 @@ +/** + * L2 引擎 · 十态抢占状态机 + 状态段生成九步算法(规划书 7.3)。 + * + * ★ 零 IO 纯函数:不 import data/、不 fetch、不 Date.now。所有输入注入,可重放。 + * + * 十态优先级见 types/oee.ts 的 STATE_PRIORITY(数字越小越优先)。两条例外规则: + * - 同优先级按时间戳先后; + * - **PM 窗口内发生停机保留双记录**:状态段取高优先级(PM),重叠部分标"影子时长",不重复扣减。 + * + * 九步:① 加载事件 ② 优先级去重 ③ 选取锚点事件 ④ 按状态事件切分 + * ⑤ 间隙填充(阈值按设备校准) ⑥ 报警分类(报警 ≠ 停机) ⑦ 派生事件应用 + * ⑧ 跨班拆分 ⑨ 未归因标记 + * + * ⑤ 的语义(最容易搞反的一步):**间隙 < 阈值 → 填为 RUN**(正常节拍间隙,不是停机); + * 间隙 ≥ 阈值 → 留为 IDLE 未归因,进池并参与 DQ-06。 + * kohyoung AOI 节拍 ~6min/板,阈值必须 15min;用 5min 会把正常生产误判为停机(断言⑤)。 + */ +import { + STATE_PRIORITY, UNKNOWN_PRIORITY, EPS, + type CaliberConfig, type Device, type EventDef, type EventInstance, + type SegmentState, type StateSegment, type UnknownEvent, type StateCode, +} from '../../types/oee'; +import { toEpoch, type EventPair, type LotWindow } from './pairing'; + +/** 间隙阈值默认公式:max(5min, 3×中位节拍)。设备台账里的校准值优先于公式。 */ +export function defaultGapThresholdMin(ictSec: number): number { + return Math.max(5, (3 * ictSec) / 60); +} + +/** + * 可被 PM 窗口「影子化」的状态:全部会进六桶的可用性损失。 + * 与 lossBuckets.STATE_TO_BUCKET 的键集一致(此处不 import,避免引擎内部循环依赖)。 + */ +const SHADOWABLE = new Set(['DOWN', 'JAM', 'WAIT_MAT', 'WAIT_UNLOAD', 'WAIT_PERSON', 'CHANGE']); + +/** 按设备取阈值:台账校准值优先(kohyoung 校准为 15,公式给 18,以校准值为准)。 */ +export function gapThresholdMin(device: Device, override?: number): number { + if (typeof override === 'number' && override > 0) return override; + return device.gapThresholdMin; +} + +export interface ShiftWindow { + id: string; + start: string; + end: string; + /** 跨天班次归属到**事件开始时刻所在业务日**(C24) */ + bizDate: string; +} + +/** 候选区间:一个事件对 / 一个生产锚点 / 一段无数据窗口 */ +interface Candidate { + startEpoch: number; + endEpoch: number; + state: SegmentState; + priority: number; + eventIds: string[]; + confidence: number; + /** 来源标记,便于审计与影子时长判定 */ + origin: 'EVENT' | 'RUN_ANCHOR' | 'NO_DATA' | 'GAP_FILL'; + pairId?: string; + outputQty?: number; + goodQty?: number; +} + +export interface BuildSegmentsInput { + device: Device; + pairs: EventPair[]; + events: EventInstance[]; + defs: Record; + /** 日历时间 CT 窗口。命名刻意避开 window,防止在纯函数层遮蔽浏览器全局。 */ + ctWindow: { start: string; end: string }; + shifts: ShiftWindow[]; + caliber: CaliberConfig; + /** 生产锚点:lot 窗口即 RUN 段(③ 选取锚点事件) */ + lots?: LotWindow[]; + /** 日志断流/未采集窗口 → UNKNOWN,不计入分母(DQ-10) */ + noDataWindows?: { start: string; end: string }[]; + /** 覆盖设备阈值,用于 5min vs 15min 误判对比演示 */ + gapThresholdMinOverride?: number; +} + +export interface BuildSegmentsResult { + segments: StateSegment[]; + unknown: UnknownEvent[]; + /** ⑤ 的对比证据:本次用了多少阈值、填了多少段、留了多少未归因 */ + gapInfo: { + thresholdMin: number; + filledCount: number; + filledSec: number; + idleCount: number; + idleSec: number; + }; + totals: { + ctSec: number; + /** 计划类时长(PLAN_STOP + PM)= PDT,从分母扣除 */ + pdtSec: number; + pptSec: number; + runSec: number; + /** 影子时长:PM 窗口内的停机,不重复扣减 */ + shadowSec: number; + unknownSec: number; + outputQty: number; + goodQty: number; + }; + /** 九步各步的产出计数,供"说明与对照"页展示算法可解释性 */ + steps: { step: string; count: number; note: string }[]; +} + +/** + * 事件 → 状态码。计划类(bucket=null)落 PLAN_STOP / PM,不进六桶。 + * Down/Jam 的分界按**单次连续停机的持续时长**判定(C14),统一 300 秒(C08)。 + */ +export function stateForEvent(def: EventDef, durationSec: number, downJamThresholdSec = 300): StateCode { + // PM 与工程借用都属 ENG Time(C06/C10 口径),从分母扣除 + if (def.factorL2 === 'PM') return 'PM'; + if (def.grossCategory === '工程借用') return 'PM'; + if (def.grossCategory === '计划停机') return 'PLAN_STOP'; + if (def.grossCategory === '计划待料') return 'PLAN_STOP'; + if (def.grossCategory === '故障停机') return durationSec > downJamThresholdSec ? 'DOWN' : 'JAM'; + if (def.grossCategory === '换型调整') return 'CHANGE'; + // 空转短停:按二级因子细分待料 / 待人 / 短停 + if (def.factorL2 === '待料') return 'WAIT_MAT'; + if (def.factorL2 === '人员等待') return 'WAIT_PERSON'; + if (def.factorL2 === '待卸料') return 'WAIT_UNLOAD'; + return 'JAM'; +} + +/** ⑥ 报警分类:INFO / CLOCK_CHANGE 不是停机,不得生成 DOWN/JAM 段。 */ +export function isStopAlarm(def: EventDef): boolean { + if (def.alarmClass === 'INFO' || def.alarmClass === 'CLOCK_CHANGE') return false; + return true; +} + +/** Down/Jam 阈值取口径 C08 的默认值(统一 300 秒),可由配置中心切换。 */ +export function downJamThresholdSec(caliber: CaliberConfig): number { + const raw = caliber.items.C08?.defaultValue; + if (typeof raw === 'number' && raw > 0) return raw; + const m = typeof raw === 'string' ? raw.match(/(\d+)\s*秒/) : null; + return m ? Number(m[1]) : 300; +} + +export function buildSegments(input: BuildSegmentsInput): BuildSegmentsResult { + const { device, pairs, defs, ctWindow, shifts, caliber } = input; + const wStart = toEpoch(ctWindow.start); + const wEnd = toEpoch(ctWindow.end); + const ctSec = Math.max(0, wEnd - wStart); + const thresholdSec = gapThresholdMin(device, input.gapThresholdMinOverride) * 60; + const djThreshold = downJamThresholdSec(caliber); + const steps: BuildSegmentsResult['steps'] = []; + + // ── ① 加载事件 ──────────────────────────────────────────────────────── + const candidates: Candidate[] = []; + for (const p of pairs) { + const def = defs[p.startCode]; + if (!def) continue; + const a = Math.max(p.startEpoch, wStart); + const b = Math.min(p.endEpoch, wEnd); + if (b <= a) continue; + candidates.push({ + startEpoch: a, endEpoch: b, + state: stateForEvent(def, p.durationSec, djThreshold), + priority: 0, // ② 再填 + eventIds: p.eventIds, + confidence: p.confidence, + origin: 'EVENT', + pairId: p.pairId, + }); + } + steps.push({ step: '① 加载事件', count: candidates.length, note: `${pairs.length} 个事件对 → 候选区间` }); + + // ── ⑥ 报警分类(提前到去重之前:报警 ≠ 停机,INFO/CLOCK_CHANGE 直接剔除)── + const beforeAlarm = candidates.length; + const kept = candidates.filter((c) => { + const def = defs[pairs.find((p) => p.pairId === c.pairId)?.startCode ?? '']; + return def ? isStopAlarm(def) : true; + }); + candidates.length = 0; + candidates.push(...kept); + steps.push({ step: '⑥ 报警分类', count: beforeAlarm - candidates.length, note: '剔除 INFO/CLOCK_CHANGE,报警不等于停机' }); + + // ── ③ 选取锚点事件:lot 窗口 → RUN ──────────────────────────────────── + let outputQty = 0; + let goodQty = 0; + for (const lot of input.lots ?? []) { + if (lot.device !== device.id) continue; + const a = Math.max(lot.startEpoch, wStart); + const b = Math.min(lot.endEpoch, wEnd); + if (b <= a) continue; + const qty = lotOutput(lot); + outputQty += qty.output; + goodQty += qty.good; + candidates.push({ + startEpoch: a, endEpoch: b, state: 'RUN', priority: STATE_PRIORITY.RUN, + eventIds: [], confidence: lot.selfIdentified ? 1.0 : 0.95, + origin: 'RUN_ANCHOR', outputQty: qty.output, goodQty: qty.good, + }); + } + steps.push({ step: '③ 选取锚点事件', count: (input.lots ?? []).length, note: `lot 窗口 → RUN,产出 ${outputQty}` }); + + // ── 无数据窗口 → UNKNOWN(不计分母,DQ-10)──────────────────────────── + for (const nd of input.noDataWindows ?? []) { + const a = Math.max(toEpoch(nd.start), wStart); + const b = Math.min(toEpoch(nd.end), wEnd); + if (b <= a) continue; + candidates.push({ + startEpoch: a, endEpoch: b, state: 'UNKNOWN', priority: UNKNOWN_PRIORITY, + eventIds: [], confidence: 0, origin: 'NO_DATA', + }); + } + + // ── ② 优先级去重:填优先级 + 按 dedupKey 去重(重复采集不得让时长翻倍)── + const seen = new Set(); + const deduped: Candidate[] = []; + for (const c of candidates) { + c.priority = c.state === 'UNKNOWN' ? UNKNOWN_PRIORITY : STATE_PRIORITY[c.state as StateCode]; + const key = `${c.state}|${c.startEpoch}|${c.endEpoch}|${c.eventIds.join(',')}`; + if (seen.has(key)) continue; + seen.add(key); + deduped.push(c); + } + // 同优先级按时间戳先后 + deduped.sort((x, y) => x.priority - y.priority || x.startEpoch - y.startEpoch); + steps.push({ step: '② 优先级去重', count: candidates.length - deduped.length, note: `去重后 ${deduped.length} 个候选` }); + + // ── ④ 按状态事件切分:扫描线,每个基本区间取最高优先级 ──────────────── + const bounds = new Set([wStart, wEnd]); + for (const c of deduped) { bounds.add(c.startEpoch); bounds.add(c.endEpoch); } + const cuts = [...bounds].filter((t) => t >= wStart && t <= wEnd).sort((a, b) => a - b); + + interface Elem { a: number; b: number; win?: Candidate; shadow?: Candidate } + const elems: Elem[] = []; + for (let i = 0; i < cuts.length - 1; i++) { + const a = cuts[i]; + const b = cuts[i + 1]; + if (b <= a) continue; + const covering = deduped.filter((c) => c.startEpoch <= a && c.endEpoch >= b); + if (covering.length === 0) { elems.push({ a, b }); continue; } + const win = covering[0]; // 已按优先级排序 + // PM 影子:PM 窗口内发生停机保留双记录,段取 PM,重叠标影子,不重复扣减。 + // 「停机」取全部会进六桶的状态(DOWN/JAM/WAIT_*/CHANGE),不只 DOWN/JAM—— + // FT 的「人员等待」落 WAIT_PERSON,同样是可用性损失,漏标就会重复扣减。 + const shadow = win.state === 'PM' + ? covering.find((c) => SHADOWABLE.has(c.state)) + : undefined; + elems.push({ a, b, win, shadow }); + } + steps.push({ step: '④ 按状态事件切分', count: elems.length, note: `${cuts.length} 个切点 → 基本区间` }); + + // ── ⑤ 间隙填充:间隙 < 阈值 → RUN;≥ 阈值 → IDLE 未归因 ─────────────── + let filledCount = 0; + let filledSec = 0; + let idleCount = 0; + let idleSec = 0; + for (const el of elems) { + if (el.win) continue; + const gap = el.b - el.a; + if (gap < thresholdSec - EPS) { + el.win = { + startEpoch: el.a, endEpoch: el.b, state: 'RUN', priority: STATE_PRIORITY.RUN, + eventIds: [], confidence: 0.8, origin: 'GAP_FILL', + }; + filledCount++; filledSec += gap; + } else { + el.win = { + startEpoch: el.a, endEpoch: el.b, state: 'IDLE', priority: STATE_PRIORITY.IDLE, + eventIds: [], confidence: 0, origin: 'GAP_FILL', + }; + idleCount++; idleSec += gap; + } + } + steps.push({ + step: '⑤ 间隙填充', count: filledCount + idleCount, + note: `阈值 ${thresholdSec / 60}min:填为 RUN ${filledCount} 段/${filledSec}s,留 IDLE ${idleCount} 段/${idleSec}s`, + }); + + // ── ⑦ 派生事件应用:派生区间若被更高优先级区间完全覆盖,标影子不重复计 ── + let derivedShadow = 0; + for (const el of elems) { + if (!el.win || el.win.origin !== 'EVENT' || !el.win.pairId) continue; + const p = pairs.find((x) => x.pairId === el.win!.pairId); + if (!p) continue; + const def = defs[p.startCode]; + if (def?.form !== 'DERIVED') continue; + const higher = deduped.find((c) => c.priority < el.win!.priority && + c.startEpoch <= el.a && c.endEpoch >= el.b && c.pairId !== p.pairId); + if (higher) { el.shadow = higher; derivedShadow++; } + } + steps.push({ step: '⑦ 派生事件应用', count: derivedShadow, note: '派生区间被高优先级覆盖时标影子,不重复扣减' }); + + // 合并相邻同状态区间(同一 win 签名) + const merged: Elem[] = []; + for (const el of elems) { + const last = merged[merged.length - 1]; + const sig = (e: Elem) => e.win ? `${e.win.state}|${e.win.origin}|${e.win.eventIds.join(',')}|${e.win.pairId ?? ''}` : 'NONE'; + if (last && last.b === el.a && sig(last) === sig(el) && !last.shadow && !el.shadow) { + last.b = el.b; + if (last.win && el.win) { + last.win.endEpoch = el.b; + last.win.outputQty = (last.win.outputQty ?? 0) + (el.win.outputQty ?? 0); + last.win.goodQty = (last.win.goodQty ?? 0) + (el.win.goodQty ?? 0); + } + } else { + merged.push({ ...el, win: el.win ? { ...el.win } : undefined }); + } + } + + // ── ⑧ 跨班拆分:同一物理段按班次切成多条,共享 splitGroupId ─────────── + const segments: StateSegment[] = []; + let seq = 0; + for (const el of merged) { + if (!el.win) continue; + const pieces = splitByShift(el.a, el.b, shifts, wStart, wEnd); + const groupId = pieces.length > 1 ? `split-${++seq}` : undefined; + for (const pc of pieces) { + const dur = pc.b - pc.a; + if (dur <= 0) continue; + const shift = shifts.find((s) => s.id === pc.shiftId); + segments.push({ + id: `seg-${device.id}-${++seq}`, + device: device.id, + state: el.win.state, + priority: el.win.priority, + start: isoOf(pc.a), + end: isoOf(pc.b), + durationSec: dur, + shiftId: pc.shiftId, + ...(groupId ? { splitGroupId: groupId } : {}), + ...(el.shadow ? { shadowOf: el.shadow.pairId ?? el.shadow.state, shadowSec: dur } : {}), + filledByGapRule: el.win.origin === 'GAP_FILL', + confidence: el.win.confidence, + eventIds: el.win.eventIds, + bizDate: shift?.bizDate ?? bizDateOf(pc.a, shifts, ctWindow.start), + }); + } + } + steps.push({ step: '⑧ 跨班拆分', count: segments.length, note: `合并后 ${merged.length} 段 → 按班次拆为 ${segments.length} 段` }); + + // ── ⑨ 未归因标记:IDLE 段进池,占比分母统一为 PPT ───────────────────── + // UNKNOWN(日志断流/未采集)不计入分母(DQ-10),故 PPT = CT − PDT − UNKNOWN。 + const pdtSec = segments + .filter((s) => s.state === 'PLAN_STOP' || s.state === 'PM') + .reduce((a, s) => a + s.durationSec, 0); + const unknownSecTotal = segments + .filter((s) => s.state === 'UNKNOWN') + .reduce((a, s) => a + s.durationSec, 0); + const pptSec = Math.max(0, ctSec - pdtSec - unknownSecTotal); + const unknown: UnknownEvent[] = []; + for (const s of segments) { + if (s.state !== 'IDLE') continue; + const poolId = `unk-${device.id}-${s.id}`; + s.unknownPoolId = poolId; + unknown.push({ + id: poolId, + device: device.id, + bizDate: s.bizDate, + durationSec: s.durationSec, + reason: s.filledByGapRule ? 'GAP_FILL' : 'NO_SOURCE', + pctOfPlanTime: pptSec > 0 ? s.durationSec / pptSec : 0, + suggestedForm: 'FORM_DOWN_ATTR', + resolved: false, + }); + } + steps.push({ step: '⑨ 未归因标记', count: unknown.length, note: `IDLE 段进池,PPT=${pptSec}s` }); + + const runSec = segments.filter((s) => s.state === 'RUN').reduce((a, s) => a + s.durationSec, 0); + const shadowSec = segments.reduce((a, s) => a + (s.shadowSec ?? 0), 0); + const unknownSec = segments.filter((s) => s.state === 'UNKNOWN').reduce((a, s) => a + s.durationSec, 0); + + return { + segments, unknown, + gapInfo: { thresholdMin: thresholdSec / 60, filledCount, filledSec, idleCount, idleSec }, + totals: { ctSec, pdtSec, pptSec, runSec, shadowSec, unknownSec, outputQty, goodQty }, + steps, + }; +} + +/** lot 窗口的产出:没有给数量时按节拍推算(ICT 来自设备台账),不凭空造数。 */ +function lotOutput(lot: LotWindow & { outputQty?: number; goodQty?: number }): { output: number; good: number } { + if (typeof lot.outputQty === 'number') { + return { output: lot.outputQty, good: typeof lot.goodQty === 'number' ? lot.goodQty : lot.outputQty }; + } + return { output: 0, good: 0 }; +} + +function splitByShift( + a: number, b: number, shifts: ShiftWindow[], wStart: number, wEnd: number, +): { a: number; b: number; shiftId: string }[] { + if (shifts.length === 0) return [{ a, b, shiftId: 'SHIFT-DEFAULT' }]; + const out: { a: number; b: number; shiftId: string }[] = []; + for (const s of shifts) { + const sa = Math.max(toEpoch(s.start), wStart); + const sb = Math.min(toEpoch(s.end), wEnd); + const x = Math.max(a, sa); + const y = Math.min(b, sb); + if (y > x) out.push({ a: x, b: y, shiftId: s.id }); + } + if (out.length === 0) return [{ a, b, shiftId: shifts[0].id }]; + // 班次未覆盖到的边角(如窗口早于第一班)归到最近班次,避免时间丢失 + out.sort((p, q) => p.a - q.a); + let cursor = a; + for (const piece of out) { + if (piece.a > cursor) out.push({ a: cursor, b: piece.a, shiftId: piece.shiftId }); + cursor = Math.max(cursor, piece.b); + } + if (cursor < b) out.push({ a: cursor, b, shiftId: out[out.length - 1].shiftId }); + return out.sort((p, q) => p.a - q.a); +} + +function bizDateOf(epoch: number, shifts: ShiftWindow[], fallbackStart: string): string { + const s = shifts.find((x) => epoch >= toEpoch(x.start) && epoch < toEpoch(x.end)); + return s?.bizDate ?? fallbackStart.slice(0, 10); +} + +/** 秒级 epoch → ISO(UTC,原型统一用带 Z 的 ISO 串,避免本地时区漂移) */ +export function isoOf(epochSec: number): string { + return new Date(epochSec * 1000).toISOString().replace('.000Z', 'Z'); +} + +/** 十态抢占的不变量自检:任意两段不得时间重叠(同设备同班次)。 */ +export function findOverlaps(segments: StateSegment[]): { a: string; b: string }[] { + const out: { a: string; b: string }[] = []; + const sorted = [...segments].sort((x, y) => toEpoch(x.start) - toEpoch(y.start)); + for (let i = 1; i < sorted.length; i++) { + if (toEpoch(sorted[i].start) < toEpoch(sorted[i - 1].end) - EPS) { + out.push({ a: sorted[i - 1].id, b: sorted[i].id }); + } + } + return out; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/stepchain.ts b/src/modules/tfamd-oee/lib/oee/stepchain.ts new file mode 100644 index 0000000..e84f1e8 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/stepchain.ts @@ -0,0 +1,265 @@ +/** + * L2 引擎 · StepChain 换型链 DSL(建议书 §4.9,断言⑨的现场执行侧延伸)。 + * + * 来源:《OEE分析AI原型系统构建建议书-2026-11-12.md》§4.9.1/§4.9.2/§4.9.3。 + * SRF 换型链 7 节点(n1–n7),其中 n6_qc_verify 为 **GATE(质量确认不可跳过)**、 + * n7_setup_ea_end 为 **DERIVED(由 n4 经 T6 派生反向超时反推)**。 + * 节点任务走 **ChainTaskState 七态**(CREATED→ACCEPTED→IN_PROGRESS→SUBMITTED→APPROVED→CLOSED, + * SUBMITTED 可 REJECTED 退回 IN_PROGRESS)。 + * + * ★ 两套状态机不得共用枚举(D17):本模块的 ChainTaskState(七态,面向现场换型执行) + * 与 closure.ts 的 TaskState(六态,面向改善立项)是**两套独立类型**,互不引用。 + * + * 四条诚实性纪律: + * 1. **GATE 不可跳过**:n6 未核准(APPROVED/CLOSED)前,其下游节点(n7)不得激活, + * 整链不得关闭。canActivateNode / canCloseChain 显式拒绝,绝不静默放行。 + * 2. **DERIVED 不手填**:n7 的时刻由 n4 经 T6 反推(n7=Xray−5min=n4−10min), + * 纯算术派生;锚点缺失则不派生、不猜一个时间塞进去。 + * 3. **纯函数 + 注入时钟**:transition 不改入参、不读 Date.now;at/by/now 由调用方注入,可重放。 + * ISO→epoch 用 Date.parse(iso)(白名单允许),派生用整数秒算术。 + * 4. **T5 计划对齐是契约占位**:本引擎不实现 APS 对齐,trigger 字典里 implemented=false, + * 不假装已接排产系统。 + * + * 本模块只 import 契约层(types/oee),不 import data/,符合 verify-oee-purity 白名单。 + */ +import { + CHAIN_TASK_STATES, CHAIN_STATE_LABEL, + type ChainTaskState, type ChainNode, type ChainNodeState, type ChainInstance, +} from '../../types/oee'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、七态合法流转(建议书 §4.9.3 状态机图) + * + * CREATED → ACCEPTED → IN_PROGRESS → SUBMITTED → APPROVED → CLOSED + * ↑ │ + * └─ REJECTED ─┘ + * CLOSED 为终态;REJECTED 退回 IN_PROGRESS 返工。任意阶段可升级(escalation,见 SLA)。 + * ══════════════════════════════════════════════════════════════════ */ + +export const CHAIN_TRANSITIONS: Record = { + CREATED: ['ACCEPTED'], + ACCEPTED: ['IN_PROGRESS'], + IN_PROGRESS: ['SUBMITTED'], + SUBMITTED: ['APPROVED', 'REJECTED'], + APPROVED: ['CLOSED'], + CLOSED: [], + REJECTED: ['IN_PROGRESS'], +}; + +/** from→to 是否在合法流转表内。 */ +export function isLegalChainTransition(from: ChainTaskState, to: ChainTaskState): boolean { + return (CHAIN_TRANSITIONS[from] ?? []).includes(to); +} + +/** 当前态的合法后继。 */ +export function nextChainStates(state: ChainTaskState): ChainTaskState[] { + return [...(CHAIN_TRANSITIONS[state] ?? [])]; +} + +export interface ChainTransitionContext { + /** 流转时刻(ISO,注入;引擎内禁止 Date.now) */ + at: string; + /** 操作人(演示角色) */ + by: string; + note?: string; +} + +export interface ChainTransitionResult { + ok: boolean; + /** 成功时返回**新节点状态对象**(state 推进、history 追加);失败时 undefined,入参不被改动 */ + node?: ChainNodeState; + reason?: string; +} + +/** + * 节点状态流转。纯函数:不改动入参;at/by 注入,可重放。 + * 非法流转 → 拒绝并说明合法后继。★ GATE 不可跳过由 canActivateNode/canCloseChain 在链层叠加, + * 本函数只管单节点七态合法性(与 closure.transition 同构,但枚举独立)。 + */ +export function chainTransition(node: ChainNodeState, to: ChainTaskState, ctx: ChainTransitionContext): ChainTransitionResult { + const from = node.state; + if (!isLegalChainTransition(from, to)) { + return { + ok: false, + reason: `非法流转:${CHAIN_STATE_LABEL[from]} → ${CHAIN_STATE_LABEL[to]}(合法后继:${nextChainStates(from).map((s) => CHAIN_STATE_LABEL[s]).join('、') || '无(终态)'})`, + }; + } + const next: ChainNodeState = { + ...node, + state: to, + at: ctx.at, + // 首次进入执行中即记 SLA 计时起点(已有则不覆盖) + ...(to === 'IN_PROGRESS' && !node.startedAt ? { startedAt: ctx.at } : {}), + history: [...node.history, { state: to, at: ctx.at, by: ctx.by, ...(ctx.note !== undefined ? { note: ctx.note } : {}) }], + }; + return { ok: true, node: next }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 二、节点种类与 GATE 不可跳过 + * ══════════════════════════════════════════════════════════════════ */ + +export const gateNodeIds = (nodes: ChainNode[]): string[] => nodes.filter((n) => n.kind === 'GATE').map((n) => n.id); +export const derivedNodeIds = (nodes: ChainNode[]): string[] => nodes.filter((n) => n.kind === 'DERIVED').map((n) => n.id); +export const taskNodeIds = (nodes: ChainNode[]): string[] => nodes.filter((n) => n.kind === 'TASK').map((n) => n.id); + +/** 取实例里某节点的运行时状态;未命中返回 undefined(不猜)。 */ +export function nodeStateOf(instance: ChainInstance, nodeId: string): ChainNodeState | undefined { + return instance.nodes.find((n) => n.nodeId === nodeId); +} + +/** 节点是否已「通过」:TASK 须 CLOSED;GATE/DERIVED 须 APPROVED 或 CLOSED。 */ +export function nodePassed(node: ChainNode, state: ChainTaskState | undefined): boolean { + if (state === undefined) return false; + if (node.kind === 'TASK') return state === 'CLOSED'; + return state === 'APPROVED' || state === 'CLOSED'; +} + +/** + * GATE 是否全部满足(核准/关闭)。★ 这是「质量确认不可跳过」的核心判据: + * 任一 GATE 未通过 → false,整链不得关闭、其下游节点不得激活。 + */ +export function gateSatisfied(nodes: ChainNode[], states: ChainNodeState[]): boolean { + const gates = nodes.filter((n) => n.kind === 'GATE'); + if (gates.length === 0) return true; + return gates.every((g) => nodePassed(g, states.find((s) => s.nodeId === g.id)?.state)); +} + +export interface ActivateCheck { + ok: boolean; + reason?: string; + /** 阻挡本节点激活的未通过 GATE id 清单 */ + blockedByGates?: string[]; +} + +/** + * 某节点能否激活(离开 CREATED)。★ GATE precedence:链顺序(nodes 数组序)中 + * 排在本节点之前的每个 GATE 都必须先通过,否则拒绝。n7 在 n6 之后 → n6 未核准不得激活 n7。 + * 纯查表:不读时钟、不改入参。 + */ +export function canActivateNode(nodeId: string, nodes: ChainNode[], states: ChainNodeState[]): ActivateCheck { + const idx = nodes.findIndex((n) => n.id === nodeId); + if (idx < 0) return { ok: false, reason: `链中无节点 ${nodeId}` }; + const upstreamGates = nodes.slice(0, idx).filter((n) => n.kind === 'GATE'); + const blocked = upstreamGates.filter((g) => !nodePassed(g, states.find((s) => s.nodeId === g.id)?.state)); + if (blocked.length > 0) { + return { + ok: false, + blockedByGates: blocked.map((g) => g.id), + reason: `质量门未通过,不可跳过:${blocked.map((g) => `${g.id}(${g.criterion})`).join('、')} 须先核准`, + }; + } + return { ok: true }; +} + +export interface CloseCheck { + ok: boolean; + reason?: string; + /** 尚未通过的节点 id */ + pendingNodes?: string[]; +} + +/** + * 整链能否关闭。★ 双重闸:① 每个节点都已通过(nodePassed);② GATE 全部满足。 + * 任一不满足 → 拒绝并列出未通过节点,绝不把「还差质量确认」的链标成已完成。 + */ +export function canCloseChain(nodes: ChainNode[], states: ChainNodeState[]): CloseCheck { + const pending = nodes.filter((n) => !nodePassed(n, states.find((s) => s.nodeId === n.id)?.state)).map((n) => n.id); + if (pending.length > 0) { + return { ok: false, pendingNodes: pending, reason: `尚有节点未通过:${pending.join('、')},整链不得关闭` }; + } + if (!gateSatisfied(nodes, states)) { + return { ok: false, reason: '质量门(GATE)未核准,不可跳过,整链不得关闭' }; + } + return { ok: true }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三、DERIVED 派生(T6 反向超时):n7 由 n4 反推 + * + * 判据原文:n4_setup_mfg_start=Xray 图片 + 5min;n7_setup_ea_end=Xray 图片 − 5min。 + * 故 n7=n4 − 10min。锚点是同一张 Xray 图片,两个节点各偏 ±5min。 + * ★ 纯整数秒算术,不读时钟;锚点缺失(undefined)则不派生,返回 undefined,不猜。 + * ══════════════════════════════════════════════════════════════════ */ + +/** Setup 判定点相对 Xray 锚点的偏移:5min=300s(建议书 §4.9.1)。 */ +export const SETUP_OFFSET_SEC = 300; + +export interface DerivedSetupTimes { + /** n4_setup_mfg_start=锚点 + 5min */ + n4StartEpoch: number; + /** n7_setup_ea_end=锚点 − 5min */ + n7EndEpoch: number; +} + +/** 由 Xray 锚点(epoch 秒)派生 n4/n7 两个判定点。 */ +export function deriveSetupTimes(xrayAnchorEpoch: number): DerivedSetupTimes { + return { + n4StartEpoch: xrayAnchorEpoch + SETUP_OFFSET_SEC, + n7EndEpoch: xrayAnchorEpoch - SETUP_OFFSET_SEC, + }; +} + +/** + * T6 派生反向超时:已知 n4 开始时刻,反推 n7 结束时刻。 + * n7=Xray−5min=(n4−5min)−5min=n4−10min。纯算术,可重放。 + */ +export function reverseDeriveN7(n4StartEpoch: number): number { + return n4StartEpoch - 2 * SETUP_OFFSET_SEC; +} + +/** ISO→epoch 秒(Date.parse 白名单允许)。非法串返回 NaN,由调用方判缺口,不静默取 0。 */ +export function isoToEpoch(iso: string): number { + return Date.parse(iso) / 1000; +} + +/* ══════════════════════════════════════════════════════════════════ + * 四、SLA 超时与升级(建议书 §4.9.3) + * + * 节点 SLA:n1 PM 交接 30min / n2 PM 结束 4h / n3 Conversion 15min / n4 Setup 20min; + * n5/n6/n7 无 SLA(—)。超时 → 升级到 node.escalateTo。 + * ★ now 由调用方注入;无 slaMin 或无 startedAt 的节点不判超时(不猜一个起点)。 + * ══════════════════════════════════════════════════════════════════ */ + +/** SLA 截止时刻(epoch 秒)。无 slaMin 或无起点 → undefined。 */ +export function slaDeadlineEpoch(node: ChainNode, startedAtEpoch: number | undefined): number | undefined { + if (node.slaMin === undefined || startedAtEpoch === undefined || !Number.isFinite(startedAtEpoch)) return undefined; + return startedAtEpoch + node.slaMin * 60; +} + +/** 是否 SLA 超时(now > 截止)。无截止 → false(不判超时)。 */ +export function isSlaBreached(node: ChainNode, startedAtEpoch: number | undefined, nowEpoch: number): boolean { + const deadline = slaDeadlineEpoch(node, startedAtEpoch); + return deadline !== undefined && nowEpoch > deadline; +} + +/** 升级对象(节点自带 escalateTo)。无 SLA 的节点也保留升级对象供人工升级。 */ +export function escalationFor(node: ChainNode): string { + return node.escalateTo; +} + +/* ══════════════════════════════════════════════════════════════════ + * 五、引擎自检(供校验脚本与任务中心引用,数字一律现算) + * ══════════════════════════════════════════════════════════════════ */ + +export function chainStats(nodes: ChainNode[]) { + const byKind = { TASK: taskNodeIds(nodes).length, GATE: gateNodeIds(nodes).length, DERIVED: derivedNodeIds(nodes).length }; + return { + states: [...CHAIN_TASK_STATES], + stateCount: CHAIN_TASK_STATES.length, + nodeCount: nodes.length, + byKind, + gateNodeIds: gateNodeIds(nodes), + derivedNodeIds: derivedNodeIds(nodes), + /** 有 SLA 的节点(n1–n4),无 SLA 的(n5–n7)如实分列 */ + slaNodes: nodes.filter((n) => n.slaMin !== undefined).map((n) => ({ id: n.id, slaMin: n.slaMin, escalateTo: n.escalateTo })), + noSlaNodes: nodes.filter((n) => n.slaMin === undefined).map((n) => n.id), + legalTransitions: CHAIN_TASK_STATES.map((s) => ({ from: s, to: [...CHAIN_TRANSITIONS[s]] })), + terminalStates: CHAIN_TASK_STATES.filter((s) => CHAIN_TRANSITIONS[s].length === 0), + /** REJECTED 必须退回 IN_PROGRESS(返工环),不得直连 CLOSED/APPROVED */ + rejectedLoop: CHAIN_TRANSITIONS.REJECTED, + setupOffsetSec: SETUP_OFFSET_SEC, + /** 七态 ≠ 改善闭环六态:本引擎不引用 TaskState,枚举独立(D17) */ + distinctFromClosure: CHAIN_TASK_STATES.length === 7, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/templates.ts b/src/modules/tfamd-oee/lib/oee/templates.ts new file mode 100644 index 0000000..00c338e --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/templates.ts @@ -0,0 +1,1142 @@ +/** + * L2 引擎 · 三区域算法模板(规划书 4.1.4 / 建议书 §3.9)。 + * + * ★ 零 IO 纯函数。守断言①③:三站各自跑通、每个中间量可展开、残差为 0。 + * + * **三站不同构,用一套 A×P×Q 通用式套三站,数字一定错**(建议书 §1.3 第 1 条): + * - SRF:缓冲解耦。上游最长停机 ≤ B×下游ICT 时,停机不传导到全线; + * 零缓冲是理论下界(16.02%),不是本线口径(25.50%)。 + * - FT :多因子连乘。A=(1−Down率)(1−SetupLoss)(1−Corr)−计划损失, + * P=1−(OE+Index+Jam),Q=1−(Rescreen×良率损失)。**A 不是 RT/PPT。** + * - ASLT:事件驱动。>60min 间隔切活跃窗口;A=运行/活跃窗口, + * P=12站使能总时长/(12×活跃窗口),Q=(FT合格+RC复测合格)/FT投入。 + * + * 本模块只放**公式**,不放任何 POC 结果数字。操作数与锚点一律由数据层注入, + * 每个中间量都带 formula + operands + source,UI 展开即可复核(断言①的口径侧)。 + * + * 已实测的两处文档矛盾(引擎不抹平,显式披露,见 disclosure.CONFLICT_READINGS): + * 1. 规划书 4.1.4 写 `A = 0.997384 × 0.97057 × 0.98 = 92.63%`。 + * 1−2.616% = 0.97384,不是 0.997384;照原式实算 94.8670%,与 92.63% 矛盾。 + * 本引擎按定义式 (1−Down率) 计算,得 92.6273%,与 POC 展示值 92.63% 一致。 + * 2. ASLT 的 41.75% 属**站别汇总**口径(61.39×74.86×90.84=41.7469%); + * **活跃窗口**口径 66.1485×68.2101×90.8432 = 40.9884%,不是 41.75%。 + * 规划书第 474 行把两套口径混写成一行。本引擎两套各自算、各自标,禁止交叉配对。 + */ +import { + EPS, ASLT_TIME_CLASSES, + type AsltTimeAccount, type AsltTimeClass, type RegionTemplate, +} from '../../types/oee'; +import { synthesizeSerial, type SynthesisMember } from './lineSynthesis'; + +/* ══════════════════════════════════════════════════════════════════ + * 零、公共:可展开的中间量 + * ══════════════════════════════════════════════════════════════════ */ + +/** 操作数来源。PENDING_IE = 客户未给,须 IE 提供后才能定版。 */ +export type QuantitySource = 'SEED' | 'POC' | 'CALIBER' | 'DERIVED' | 'PENDING_IE'; + +export const QUANTITY_SOURCE_LABEL: Record = { + SEED: '演示合成种子', + POC: '参考基线', + + CALIBER: '口径配置(附录 E 默认值,待 IE 签字)', + DERIVED: '引擎现算', + PENDING_IE: '待 IE 提供', +}; + +export interface Operand { + name: string; + value: number; + unit?: string; + source: QuantitySource; + note?: string; +} + +/** 一个可展开的中间量。value 一律由 operands 现算,不写死结果。 */ +export interface TemplateQuantity { + key: string; + label: string; + value: number; + unit: 'ratio' | 'sec' | 'min' | 'h' | 'qty' | 'unit'; + /** 算式原文(含数字),供 UI 直接展示 */ + formula: string; + operands: Operand[]; + source: QuantitySource; + note?: string; +} + +function clamp01(x: number): number { + if (!Number.isFinite(x)) return 0; + return Math.min(1, Math.max(0, x)); +} + +function div(n: number, d: number): number { + return d > EPS ? n / d : 0; +} + +function pct(x: number, digits = 4): string { + return `${(x * 100).toFixed(digits)}%`; +} + +/* ══════════════════════════════════════════════════════════════════ + * 一、FT:多因子连乘(客户算法表《FT_OEE.xlsx》v3) + * ══════════════════════════════════════════════════════════════════ */ + +/** + * SetupLoss 算式的五个操作数,**照录客户算法表原式** `(op1×op2/op3)×op4/op5`。 + * 〔实测〕POC 只给了算式与结果 (196.2×12/1000)×9/720=2.943%, + * 未给各操作数的物理含义与单位。此处不猜语义、不改名, + * 由主数据页标「操作数含义待 IE 确认」,列入 W0 追问。 + */ +export interface FtSetupOperands { + op1: number; + op2: number; + op3: number; + op4: number; + op5: number; +} + +export const FT_SETUP_SEMANTICS_NOTE = + 'SetupLoss 算式 (196.2×12/1000)×9/720 照录《FT_OEE.xlsx》v3;' + + '五个操作数的物理含义与单位客户未给,待 IE 确认后方可定版(不得自行赋予语义)。'; + +export interface FtInput { + deviceId: string; + /** 范围标签:设备号 + 时间窗 + 完整日数。每个数字必须绑定它。 */ + scopeLabel: string; + algorithmTable: string; + /** 分母:总可用秒(POC 93k178 = 2,448,035s) */ + baseSec: number; + downSec: number; + jamSec: number; + setup: FtSetupOperands; + /** 客户参数:Corr 相关性损失率 */ + corrRate: number; + /** 客户参数:OE 效率损失率 */ + oeRate: number; + /** Index 时间(秒/颗) */ + indexSec: number; + /** 测试时间(秒/颗) */ + testSec: number; + /** 复测系数(POC 1.04) */ + rescreenFactor: number; + /** 良率(POC 93.01%) */ + yieldRate: number; + /** A 的扣减项:计划损失率。单机口径为 0。 */ + planLossRate: number; + /** 投入量(颗):并行加权的权重 */ + inputQty: number; + /** C06 开关:PM 计入停机的分钟数。0/undefined = 不计入。 */ + pmMin?: number; + /** 操作数来源:POC = 客户算法表原值;SEED = 演示合成(客户未给该机操作数)。 */ + operandSource: 'POC' | 'SEED'; + synthetic: boolean; +} + +export interface FtResult { + deviceId: string; + template: RegionTemplate; + scopeLabel: string; + algorithmTable: string; + /** 七个中间量 + 计划损失 + 三率,UI 必须可逐项展开 */ + quantities: TemplateQuantity[]; + a: number; + p: number; + q: number; + oee: number; + /** C06 开关状态与计入的 PM 秒数 */ + pmIncluded: boolean; + pmSec: number; + baseSec: number; + inputQty: number; + operandSource: 'POC' | 'SEED'; + synthetic: boolean; + /** + * 反例对照:若误用通用式 A=RT/PPT(把 Down+Jam 当全部停机)会得到什么。 + * **这是错误公式**,只供"FT 的 A 为什么不是 RT/PPT"这一屏做对照,不得当读数。 + */ + contrastGenericA: number; + notes: string[]; + ok: boolean; + problems: string[]; +} + +/** FT 多因子连乘。七个中间量全部返回,任何一个都可在 UI 展开到操作数。 */ +export function calcFt(input: FtInput): FtResult { + const problems: string[] = []; + if (input.baseSec <= EPS) problems.push('baseSec 必须为正(分母为 0 不得静默返回 0%)'); + if (input.setup.op3 <= EPS || input.setup.op5 <= EPS) problems.push('SetupLoss 算式除数为 0'); + if (input.indexSec + input.testSec <= EPS) problems.push('Index+Test 时间为 0,无法算 Index 占比'); + if (input.rescreenFactor < 1 - EPS) problems.push('复测系数 <1 不合定义(Rescreen=(f−1)/f)'); + for (const k of ['corrRate', 'oeRate', 'planLossRate', 'yieldRate'] as const) { + const v = input[k]; + if (!Number.isFinite(v) || v < -EPS || v > 1 + EPS) problems.push(`${k}=${v} 超出 [0,1]`); + } + + const src: QuantitySource = input.operandSource === 'POC' ? 'POC' : 'SEED'; + const pmSec = Math.max(0, (input.pmMin ?? 0) * 60); + const pmIncluded = pmSec > EPS; + /** C06:PM 计入停机 → 加到 Down 的分子上,分母不变。 */ + const downSecTotal = input.downSec + pmSec; + + const downRate = div(downSecTotal, input.baseSec); + const setupLoss = ((input.setup.op1 * input.setup.op2) / input.setup.op3) * input.setup.op4 / input.setup.op5; + const corr = input.corrRate; + const a = clamp01((1 - downRate) * (1 - setupLoss) * (1 - corr) - input.planLossRate); + + const jamRate = div(input.jamSec, input.baseSec); + const indexShare = div(input.indexSec, input.indexSec + input.testSec); + const indexLoss = indexShare * (1 - input.oeRate - jamRate); + const p = clamp01(1 - (input.oeRate + indexLoss + jamRate)); + + const rescreen = input.rescreenFactor > EPS ? (input.rescreenFactor - 1) / input.rescreenFactor : 0; + const yieldLoss = 1 - input.yieldRate; + const q = clamp01(1 - rescreen * yieldLoss); + + const oee = clamp01(a * p * q); + const contrastGenericA = clamp01(div(input.baseSec - downSecTotal - input.jamSec, input.baseSec)); + + const s = input.setup; + const quantities: TemplateQuantity[] = [ + { + key: 'downRate', label: 'Down 率', value: downRate, unit: 'ratio', + formula: `${downSecTotal} / ${input.baseSec} = ${pct(downRate)}`, + operands: [ + { name: 'Down 秒数', value: input.downSec, unit: 's', source: src }, + ...(pmIncluded ? [{ name: 'PM 计入秒数(C06 开)', value: pmSec, unit: 's', source: 'CALIBER' as QuantitySource }] : []), + { name: '总可用秒数', value: input.baseSec, unit: 's', source: src }, + ], + source: 'DERIVED', + note: pmIncluded ? `C06 开:PM ${input.pmMin}min 计入停机,Down 分子 +${pmSec}s` : 'C06 关:PM 未计入停机', + }, + { + key: 'setupLoss', label: 'SetupLoss', value: setupLoss, unit: 'ratio', + formula: `(${s.op1}×${s.op2}/${s.op3})×${s.op4}/${s.op5} = ${pct(setupLoss)}`, + operands: [ + { name: '操作数①', value: s.op1, source: src, note: '含义待 IE 确认' }, + { name: '操作数②', value: s.op2, source: src, note: '含义待 IE 确认' }, + { name: '操作数③', value: s.op3, source: src, note: '含义待 IE 确认' }, + { name: '操作数④', value: s.op4, source: src, note: '含义待 IE 确认' }, + { name: '操作数⑤', value: s.op5, source: src, note: '含义待 IE 确认' }, + ], + source: 'DERIVED', note: FT_SETUP_SEMANTICS_NOTE, + }, + { + key: 'corr', label: 'Corr 相关性损失', value: corr, unit: 'ratio', + formula: `客户参数 = ${pct(corr)}`, + operands: [{ name: 'Corr', value: corr, unit: 'ratio', source: src }], + source: src, + }, + { + key: 'planLoss', label: '计划损失(A 的扣减项)', value: input.planLossRate, unit: 'ratio', + formula: `客户参数 = ${pct(input.planLossRate)}`, + operands: [{ name: '计划损失率', value: input.planLossRate, unit: 'ratio', source: src }], + source: src, note: '单机 93k178 口径为 0;区域口径若含计划损失须 IE 定版', + }, + { + key: 'oe', label: 'OE 效率损失', value: input.oeRate, unit: 'ratio', + formula: `客户参数 = ${pct(input.oeRate)}`, + operands: [{ name: 'OE', value: input.oeRate, unit: 'ratio', source: src }], + source: src, + }, + { + key: 'index', label: 'Index 时间占比', value: indexLoss, unit: 'ratio', + formula: `(${input.indexSec}/(${input.indexSec}+${input.testSec})) × (1−${input.oeRate}−${jamRate.toFixed(6)}) = ${pct(indexLoss)}`, + operands: [ + { name: 'Index 时间', value: input.indexSec, unit: 's/颗', source: src }, + { name: '测试时间', value: input.testSec, unit: 's/颗', source: src }, + { name: 'Index 毛占比', value: indexShare, unit: 'ratio', source: 'DERIVED' }, + { name: 'OE', value: input.oeRate, unit: 'ratio', source: src }, + { name: 'Jam 率', value: jamRate, unit: 'ratio', source: 'DERIVED' }, + ], + source: 'DERIVED', note: 'Index 占比要扣掉 OE 与 Jam 已占用的时间,避免重复计入', + }, + { + key: 'jamRate', label: 'Jam 率', value: jamRate, unit: 'ratio', + formula: `${input.jamSec} / ${input.baseSec} = ${pct(jamRate)}`, + operands: [ + { name: 'Jam 秒数', value: input.jamSec, unit: 's', source: src }, + { name: '总可用秒数', value: input.baseSec, unit: 's', source: src }, + ], + source: 'DERIVED', note: 'PM 计入只影响 Down,不影响 Jam(C06 口径)', + }, + { + key: 'rescreen', label: 'Rescreen 复测率', value: rescreen, unit: 'ratio', + formula: `(${input.rescreenFactor}−1)/${input.rescreenFactor} = ${pct(rescreen)}`, + operands: [{ name: '复测系数', value: input.rescreenFactor, source: src }], + source: 'DERIVED', + }, + { + key: 'yieldLoss', label: '良率损失', value: yieldLoss, unit: 'ratio', + formula: `1 − ${pct(input.yieldRate, 2)} = ${pct(yieldLoss)}`, + operands: [{ name: '良率', value: input.yieldRate, unit: 'ratio', source: src }], + source: 'DERIVED', + }, + { + key: 'a', label: 'A 可用性(连乘扣减式)', value: a, unit: 'ratio', + formula: `(1−${downRate.toFixed(6)})×(1−${setupLoss.toFixed(6)})×(1−${corr})−${input.planLossRate} = ${pct(a)}`, + operands: [ + { name: 'Down 率', value: downRate, source: 'DERIVED' }, + { name: 'SetupLoss', value: setupLoss, source: 'DERIVED' }, + { name: 'Corr', value: corr, source: src }, + { name: '计划损失', value: input.planLossRate, source: src }, + ], + source: 'DERIVED', note: '★ 不是 RT/PPT。通用式套 FT 会算出完全不同的数', + }, + { + key: 'p', label: 'P 性能(1−三项损失)', value: p, unit: 'ratio', + formula: `1 − (${input.oeRate} + ${indexLoss.toFixed(6)} + ${jamRate.toFixed(6)}) = ${pct(p)}`, + operands: [ + { name: 'OE', value: input.oeRate, source: src }, + { name: 'Index', value: indexLoss, source: 'DERIVED' }, + { name: 'Jam 率', value: jamRate, source: 'DERIVED' }, + ], + source: 'DERIVED', note: '★ 不是 N×ICT/RT。FT 无标准节拍(ictSec=0 是口径事实)', + }, + { + key: 'q', label: 'Q 质量(1−复测×良率损失)', value: q, unit: 'ratio', + formula: `1 − (${rescreen.toFixed(6)} × ${yieldLoss.toFixed(6)}) = ${pct(q)}`, + operands: [ + { name: 'Rescreen', value: rescreen, source: 'DERIVED' }, + { name: '良率损失', value: yieldLoss, source: 'DERIVED' }, + ], + source: 'DERIVED', + }, + ]; + + const notes: string[] = [ + `模板:FT 多因子连乘;算法表 ${input.algorithmTable};范围 ${input.scopeLabel}`, + input.operandSource === 'POC' + ? '操作数为客户算法表原值〔POC〕;展示值复算容差 ±0.02pp(分项已四舍五入)' + : '★ 该机操作数客户未给,为演示合成种子;算出的加权值不得冒充 POC 锚点 81.69%', + FT_SETUP_SEMANTICS_NOTE, + ]; + if (pmIncluded) notes.push(`C06 开:PM ${input.pmMin}min 计入停机,A 与 OEE 同步下降;演示时 UI 必须同时标明设备号`); + + return { + deviceId: input.deviceId, template: 'FT_MULTIPLY', scopeLabel: input.scopeLabel, + algorithmTable: input.algorithmTable, quantities, + a, p, q, oee, pmIncluded, pmSec, baseSec: input.baseSec, inputQty: input.inputQty, + operandSource: input.operandSource, synthetic: input.synthetic, + contrastGenericA, notes, ok: problems.length === 0, problems, + }; +} + +/** FT → 合成成员。并行加权用投入量,周期累计用 baseSec 作分母。 */ +export function ftToMember(r: FtResult): SynthesisMember { + return { + id: r.deviceId, a: r.a, p: r.p, q: r.q, oee: r.oee, inputQty: r.inputQty, + pptSec: r.baseSec, runSec: r.baseSec * r.a, idealSec: r.baseSec * r.a * r.p, + outputQty: r.inputQty, goodQty: r.inputQty * r.q, + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 二、SRF:缓冲解耦(流体模型,确定性、可重放) + * ══════════════════════════════════════════════════════════════════ */ + +/** 站点时间轴的一段。时间用 epoch 秒,避免字符串解析进引擎。 */ +export interface BufferInterval { + startSec: number; + endSec: number; + /** 是否在产(RUN)。故障/等待/换型/计划停机都 = false */ + running: boolean; + /** 计划类(PLAN_STOP / PM)→ 进 PDT,从分母扣除 */ + planned?: boolean; +} + +export interface BufferStation { + deviceId: string; + /** 标准节拍(秒/单位)。0 = 无标准节拍,该站不能参与流体模型 */ + ictSec: number; + intervals: BufferInterval[]; +} + +export interface BufferSimInput { + upstream: BufferStation; + downstream: BufferStation; + /** 缓冲容量 B(在制品单位数)。0 = 零缓冲对照(全耦合下界) */ + capacity: number; + initialLevel?: number; + /** 仿真窗口。命名刻意避开 window,防止在纯函数层遮蔽浏览器全局(与 stateMachine.ctWindow 同一纪律)。 */ + simWindow: { startSec: number; endSec: number }; +} + +export interface BufferSimResult { + capacity: number; + /** 下游侧覆盖时间 C_down = B × 下游 ICT:上游停机时下游靠它继续吃料(秒) */ + coverageSec: number; + /** 上游最长连续停机(秒) */ + upstreamMaxStopSec: number; + /** 上游侧最小解耦容量 B_min = ceil(上游最长停机 / 下游 ICT)〔POC 口径:14.9min/36s → 25〕 */ + minCapacity: number; + /** 上游侧解耦条件 C_down ≥ 上游最长停机 */ + decoupled: boolean; + /** + * ★ 下游侧解耦(POC 未给,原型补充;两个方向的分母 ICT **不同**,不可混用): + * 下游停机时上游仍在产,缓冲以**上游速率**填充,故覆盖时间 C_up = B × 上游 ICT。 + * 要吸收下游最长停机 D_down,需 B × ICT_up ≥ D_down。 + * 漏掉这一侧会把"下游长停机导致上游大面积阻塞"误判为解耦成立。 + */ + coverageUpSec: number; + downstreamMaxStopSec: number; + minCapacityDownstream: number; + decoupledDownstream: boolean; + /** 两侧都成立才算全线解耦 */ + fullyDecoupled: boolean; + windowSec: number; + upstream: { + /** 实际生产时间 = 产出量 × ICT */ + runSec: number; + /** 缓冲满载导致的损失时长(想产而不能产的部分) */ + blockedSec: number; + blockCount: number; + producedQty: number; + unplannedStopSec: number; + plannedStopSec: number; + }; + downstream: { + runSec: number; + /** 缓冲空导致的饥饿时长 */ + starvedSec: number; + starveCount: number; + consumedQty: number; + unplannedStopSec: number; + plannedStopSec: number; + }; + /** 缓冲水位轨迹,供 UI 画水位图 */ + levelTrace: { atSec: number; level: number }[]; + /** 时间账残差:runSec + 非计划停机 + 缓冲损失 + 计划停机 − 窗口,必须为 0 */ + residualSec: { upstream: number; downstream: number }; + ok: boolean; + problems: string[]; +} + +function runningAt(intervals: BufferInterval[], t: number): BufferInterval | undefined { + for (const iv of intervals) if (t >= iv.startSec && t < iv.endSec) return iv; + return undefined; +} + +/** + * 最长连续**非计划**停机:把相邻/重叠的非在产段合并后取最长。 + * + * ★ 计划停机(planned=true)必须排除,且必须作为**屏障**打断合并: + * ① 排除:关机/计划待料属 PDT,整线按规划停产,缓冲不需要覆盖它。 + * 若把它算进来,"关机 6h + 紧随换型 30min" 会合并成 23400s, + * B_min 从 POC 的 25 变成 650——量级完全错(已实测踩到)。 + * ② 屏障:若只是 filter 掉计划段,被它隔开的两段故障会在过滤后的数组里 + * 变成"相邻"而被错误连成一段。故遍历完整时间轴,遇到在产段**或**计划段就闭合当前累计。 + */ +export function longestStopSec(intervals: BufferInterval[], simWindow: { startSec: number; endSec: number }): number { + const clipped = intervals + .filter((iv) => iv.endSec > simWindow.startSec && iv.startSec < simWindow.endSec) + .map((iv) => ({ + s: Math.max(iv.startSec, simWindow.startSec), + e: Math.min(iv.endSec, simWindow.endSec), + running: iv.running, + planned: iv.planned === true, + })) + .sort((x, y) => x.s - y.s); + let best = 0; + let curS = -1; + let curE = -1; + for (const iv of clipped) { + if (!iv.running && !iv.planned) { + if (curS < 0) { curS = iv.s; curE = iv.e; continue; } + if (iv.s <= curE + EPS) curE = Math.max(curE, iv.e); + else { best = Math.max(best, curE - curS); curS = iv.s; curE = iv.e; } + } else if (curS >= 0) { + best = Math.max(best, curE - curS); + curS = -1; curE = -1; + } + } + if (curS >= 0) best = Math.max(best, curE - curS); + return best; +} + +/** + * 缓冲流体仿真。确定性:同一输入必得同一输出,不读时钟、不用随机。 + * + * 模型:上游以 1/ICT_up 入缓冲,下游以 1/ICT_down 出缓冲,缓冲上限 B。 + * - 缓冲满且上游想更快 → 上游被阻塞,实际产出速率降到下游速率; + * - 缓冲空且下游想更快 → 下游饥饿,实际消耗速率降到上游速率; + * - B=0 退化为全耦合:全线速率 = min(上游, 下游),即零缓冲下界。 + * + * 阻塞次数 = 进入"满载受限"状态的次数(不是日志行数),口径写在 UI 上。 + */ +export function simulateBuffer(input: BufferSimInput): BufferSimResult { + const problems: string[] = []; + const { upstream, downstream, simWindow } = input; + const B = input.capacity; + const windowSec = simWindow.endSec - simWindow.startSec; + if (!(windowSec > 0)) problems.push('仿真窗口长度必须为正'); + if (!Number.isFinite(B) || B < 0) problems.push('缓冲容量 B 非法'); + if (upstream.ictSec <= EPS) problems.push(`${upstream.deviceId} 无标准节拍,不能参与缓冲流体模型`); + if (downstream.ictSec <= EPS) problems.push(`${downstream.deviceId} 无标准节拍,不能参与缓冲流体模型`); + for (const st of [upstream, downstream]) { + const sorted = [...st.intervals].sort((x, y) => x.startSec - y.startSec); + for (let i = 0; i + 1 < sorted.length; i++) { + if (sorted[i].endSec > sorted[i + 1].startSec + EPS) problems.push(`${st.deviceId} 时间轴有重叠段(十态互斥被破坏)`); + } + for (const iv of st.intervals) if (iv.endSec <= iv.startSec) problems.push(`${st.deviceId} 存在零长或倒序段`); + } + + const upRateFull = upstream.ictSec > EPS ? 1 / upstream.ictSec : 0; + const downRateFull = downstream.ictSec > EPS ? 1 / downstream.ictSec : 0; + const maxStop = longestStopSec(upstream.intervals, simWindow); + const minCapacity = downstream.ictSec > EPS ? Math.ceil(maxStop / downstream.ictSec) : 0; + const coverageSec = B * downstream.ictSec; + /* 下游侧:分母换成**上游 ICT**(下游停机时缓冲由上游填充) */ + const maxStopDown = longestStopSec(downstream.intervals, simWindow); + const minCapacityDownstream = upstream.ictSec > EPS ? Math.ceil(maxStopDown / upstream.ictSec) : 0; + const coverageUpSec = B * upstream.ictSec; + const decoupled = coverageSec >= maxStop - EPS; + const decoupledDownstream = coverageUpSec >= maxStopDown - EPS; + + const base: BufferSimResult = { + capacity: B, coverageSec, upstreamMaxStopSec: maxStop, minCapacity, decoupled, + coverageUpSec, downstreamMaxStopSec: maxStopDown, minCapacityDownstream, decoupledDownstream, + fullyDecoupled: decoupled && decoupledDownstream, + windowSec, + upstream: { runSec: 0, blockedSec: 0, blockCount: 0, producedQty: 0, unplannedStopSec: 0, plannedStopSec: 0 }, + downstream: { runSec: 0, starvedSec: 0, starveCount: 0, consumedQty: 0, unplannedStopSec: 0, plannedStopSec: 0 }, + levelTrace: [], residualSec: { upstream: 0, downstream: 0 }, + ok: problems.length === 0, problems, + }; + if (problems.length > 0) return base; + + const points = new Set([simWindow.startSec, simWindow.endSec]); + for (const st of [upstream, downstream]) { + for (const iv of st.intervals) { + if (iv.endSec <= simWindow.startSec || iv.startSec >= simWindow.endSec) continue; + points.add(Math.max(iv.startSec, simWindow.startSec)); + points.add(Math.min(iv.endSec, simWindow.endSec)); + } + } + const ts = [...points].sort((x, y) => x - y); + + let level = Math.min(B, Math.max(0, input.initialLevel ?? 0)); + let produced = 0; + let consumed = 0; + let blockedSec = 0; + let starvedSec = 0; + let blockCount = 0; + let starveCount = 0; + let wasBlocked = false; + let wasStarved = false; + let upPlanned = 0; + let upUnplanned = 0; + let downPlanned = 0; + let downUnplanned = 0; + const trace: { atSec: number; level: number }[] = [{ atSec: ts[0], level }]; + + for (let i = 0; i + 1 < ts.length; i++) { + const t = ts[i]; + const dt = ts[i + 1] - t; + if (dt <= EPS) continue; + const upIv = runningAt(upstream.intervals, t); + const downIv = runningAt(downstream.intervals, t); + const upOn = upIv?.running === true; + const downOn = downIv?.running === true; + if (!upOn) { if (upIv?.planned) upPlanned += dt; else upUnplanned += dt; } + if (!downOn) { if (downIv?.planned) downPlanned += dt; else downUnplanned += dt; } + + const ur = upOn ? upRateFull : 0; + const dr = downOn ? downRateFull : 0; + const net = ur - dr; + let tHit = Number.POSITIVE_INFINITY; + if (net > EPS) tHit = (B - level) / net; + else if (net < -EPS) tHit = level / -net; + + const normalDur = Math.min(dt, Math.max(0, tHit)); + produced += ur * normalDur; + consumed += dr * normalDur; + level = Math.min(B, Math.max(0, level + net * normalDur)); + + const rest = dt - normalDur; + if (rest > EPS) { + if (net > EPS) { + // 缓冲满:上游只能按下游速率产 + level = B; + produced += dr * rest; + consumed += dr * rest; + // ★ 量纲:ur/dr 是「单位/秒」,(ur−dr)×rest 得到的是**损失的单位数**, + // 必须 × 上游 ICT 才是秒。漏乘会让时间账残差恒不为 0(已实测踩到)。 + blockedSec += (ur - dr) * rest * upstream.ictSec; + if (!wasBlocked) { blockCount++; wasBlocked = true; } + wasStarved = false; + } else { + // 缓冲空:下游只能按上游速率耗 + level = 0; + produced += ur * rest; + consumed += ur * rest; + starvedSec += (dr - ur) * rest * downstream.ictSec; + if (!wasStarved) { starveCount++; wasStarved = true; } + wasBlocked = false; + } + } else { + wasBlocked = false; + wasStarved = false; + } + trace.push({ atSec: ts[i + 1], level }); + } + + const upRunSec = produced * upstream.ictSec; + const downRunSec = consumed * downstream.ictSec; + base.upstream = { + runSec: upRunSec, blockedSec, blockCount, producedQty: produced, + unplannedStopSec: upUnplanned, plannedStopSec: upPlanned, + }; + base.downstream = { + runSec: downRunSec, starvedSec, starveCount, consumedQty: consumed, + unplannedStopSec: downUnplanned, plannedStopSec: downPlanned, + }; + base.levelTrace = trace; + base.residualSec = { + upstream: upRunSec + upUnplanned + blockedSec + upPlanned - windowSec, + downstream: downRunSec + downUnplanned + starvedSec + downPlanned - windowSec, + }; + if (Math.abs(base.residualSec.upstream) > 1e-6) problems.push(`上游时间账残差 ${base.residualSec.upstream}s ≠ 0`); + if (Math.abs(base.residualSec.downstream) > 1e-6) problems.push(`下游时间账残差 ${base.residualSec.downstream}s ≠ 0`); + base.ok = problems.length === 0; + base.problems = problems; + return base; +} + +export interface SrfStationReading { + deviceId: string; + role: 'UPSTREAM' | 'DOWNSTREAM'; + ictSec: number; + /** PPT = 窗口 − 计划停机 */ + pptSec: number; + runSec: number; + unplannedStopSec: number; + plannedStopSec: number; + /** 上游=阻塞损失,下游=饥饿损失 */ + bufferLossSec: number; + outputQty: number; + goodQty: number; + /** + * ★ 数量来源。SIM = 流体仿真值(此时 P 恒为 1,是模型产物不是实测); + * ANCHOR = 产出锚点计数(P 才能真实反映速度损失)。页面必须显示这个标签。 + */ + qtySource: 'ANCHOR' | 'SIM'; + /** 仿真产出量,供与锚点计数对账(差异即速度损失或计数缺口) */ + simQty: number; + a: number; + p: number; + q: number; + oee: number; +} + +/** 产出锚点计数。demo 种子给了才算实测口径。 */ +export interface SrfAnchorCounts { + outputQty: number; + goodQty: number; +} + +export interface SrfInput { + lineId: string; + scopeLabel: string; + bizDate: string; + sim: BufferSimInput; + /** 良率:无质量数据时取 1,并在 notes 标注"Q=100% 为口径假设" */ + yieldRate: { upstream: number; downstream: number }; + /** + * 产出锚点计数(可选)。给了就用它算 P/Q,并与仿真量对账; + * 不给则退回仿真量,此时 **P 恒为 1**,必须标"模型产物,非实测性能率"。 + */ + anchors?: { upstream: SrfAnchorCounts; downstream: SrfAnchorCounts }; + bottleneckDeviceId?: string; +} + +export interface SrfResult { + template: RegionTemplate; + lineId: string; + scopeLabel: string; + bizDate: string; + buffer: BufferSimResult; + stations: SrfStationReading[]; + quantities: TemplateQuantity[]; + /** 缓冲解耦主口径(串行连乘)。数量来源见 stations[].qtySource */ + line: { a: number; p: number; q: number; oee: number; bottleneckId: string; formula: string }; + /** + * ★ 同为仿真数量的主口径读数。缓冲敏感性必须拿它与 zeroBuffer 比, + * 否则"锚点计数 vs 仿真计数"的差异会被误当成缓冲效应。 + */ + simBased: { a: number; p: number; q: number; oee: number }; + /** 零缓冲对照:同一时间轴 B=0 重跑,**仿真数量**,理论下界,不是考核口径 */ + zeroBuffer: { a: number; p: number; q: number; oee: number; stations: SrfStationReading[] }; + /** 锚点计数与仿真量的对账(给了 anchors 才有)。差异即速度损失或计数缺口。 */ + qtyCrossCheck?: { deviceId: string; anchorQty: number; simQty: number; diffQty: number; diffPct: number }[]; + notes: string[]; + ok: boolean; + problems: string[]; +} + +/** + * 站别读数。上下游字段名不同(producedQty/blockedSec vs consumedQty/starvedSec), + * 故传整个仿真结果按 role 取,不用联合类型硬塞——硬塞会让"上游阻塞"与"下游饥饿"混为一谈。 + */ +function stationReading( + st: BufferStation, + role: 'UPSTREAM' | 'DOWNSTREAM', + sim: BufferSimResult, + yieldRate: number, + anchor?: SrfAnchorCounts, +): SrfStationReading { + const isUp = role === 'UPSTREAM'; + const side = isUp ? sim.upstream : sim.downstream; + const pptSec = Math.max(0, sim.windowSec - side.plannedStopSec); + const simQty = isUp ? sim.upstream.producedQty : sim.downstream.consumedQty; + const outputQty = anchor ? anchor.outputQty : simQty; + const goodQty = anchor ? anchor.goodQty : outputQty * clamp01(yieldRate); + const bufferLossSec = isUp ? sim.upstream.blockedSec : sim.downstream.starvedSec; + const a = clamp01(div(side.runSec, pptSec)); + const p = clamp01(div(outputQty * st.ictSec, side.runSec)); + const q = clamp01(div(goodQty, outputQty)); + return { + deviceId: st.deviceId, role, ictSec: st.ictSec, pptSec, + runSec: side.runSec, unplannedStopSec: side.unplannedStopSec, + plannedStopSec: side.plannedStopSec, bufferLossSec, + outputQty, goodQty, qtySource: anchor ? 'ANCHOR' : 'SIM', simQty, + a, p, q, oee: clamp01(a * p * q), + }; +} + +function toMember(s: SrfStationReading): SynthesisMember { + return { + id: s.deviceId, a: s.a, p: s.p, q: s.q, oee: s.oee, inputQty: s.outputQty, + pptSec: s.pptSec, runSec: s.runSec, idealSec: s.outputQty * s.ictSec, + outputQty: s.outputQty, goodQty: s.goodQty, + }; +} + +/** SRF 缓冲解耦模板:仿真 → 站别三率 → 串行连乘;同时给零缓冲下界做对照。 */ +export function calcSrf(input: SrfInput): SrfResult { + const buffer = simulateBuffer(input.sim); + const problems = [...buffer.problems]; + const up = stationReading(input.sim.upstream, 'UPSTREAM', buffer, input.yieldRate.upstream, input.anchors?.upstream); + const down = stationReading(input.sim.downstream, 'DOWNSTREAM', buffer, input.yieldRate.downstream, input.anchors?.downstream); + const stations = [up, down]; + + const serial = synthesizeSerial(stations.map(toMember), input.scopeLabel, input.bottleneckDeviceId); + if (!serial.ok) problems.push(...serial.problems); + + /* 同为仿真数量的主口径:缓冲敏感性只能拿它与零缓冲比 */ + const simUp = stationReading(input.sim.upstream, 'UPSTREAM', buffer, input.yieldRate.upstream); + const simDown = stationReading(input.sim.downstream, 'DOWNSTREAM', buffer, input.yieldRate.downstream); + const simSerial = synthesizeSerial([simUp, simDown].map(toMember), `${input.scopeLabel}·仿真数量`, input.bottleneckDeviceId); + + const zeroSim = simulateBuffer({ ...input.sim, capacity: 0, initialLevel: 0 }); + const zUp = stationReading(input.sim.upstream, 'UPSTREAM', zeroSim, input.yieldRate.upstream); + const zDown = stationReading(input.sim.downstream, 'DOWNSTREAM', zeroSim, input.yieldRate.downstream); + const zeroSerial = synthesizeSerial([zUp, zDown].map(toMember), `${input.scopeLabel}·零缓冲`, input.bottleneckDeviceId); + if (!zeroSim.ok) problems.push(...zeroSim.problems); + /* 缓冲只会帮忙不会添乱:同口径下 B>0 的 OEE 必须 ≥ B=0。违反即模型有 bug。 */ + if (simSerial.oee < zeroSerial.oee - 1e-9) { + problems.push(`缓冲模型反常:B=${input.sim.capacity} 的 OEE ${simSerial.oee} 低于零缓冲 ${zeroSerial.oee}`); + } + + const qtyCrossCheck = input.anchors + ? stations.map((s) => ({ + deviceId: s.deviceId, anchorQty: s.outputQty, simQty: s.simQty, + diffQty: s.outputQty - s.simQty, + diffPct: div(s.outputQty - s.simQty, s.simQty) * 100, + })) + : undefined; + + const b = buffer; + const quantities: TemplateQuantity[] = [ + { + key: 'coverage', label: '缓冲覆盖时间 C', value: b.coverageSec, unit: 'sec', + formula: `C = B × 下游ICT = ${b.capacity} × ${input.sim.downstream.ictSec} = ${b.coverageSec}s`, + operands: [ + { name: '缓冲容量 B', value: b.capacity, unit: '单位', source: 'CALIBER' }, + { name: '下游 ICT', value: input.sim.downstream.ictSec, unit: 's/单位', source: 'POC' }, + ], + source: 'DERIVED', + }, + { + key: 'maxStop', label: '上游最长连续停机', value: b.upstreamMaxStopSec, unit: 'sec', + formula: `合并相邻非在产段后取最长 = ${b.upstreamMaxStopSec}s(${(b.upstreamMaxStopSec / 60).toFixed(2)}min)`, + operands: [{ name: '上游时间轴段数', value: input.sim.upstream.intervals.length, unit: '段', source: 'SEED' }], + source: 'DERIVED', + }, + { + key: 'minCapacity', label: '最小解耦容量 B_min(上游侧)', value: b.minCapacity, unit: 'unit', + formula: `B_min = ceil(上游最长停机 / 下游ICT) = ceil(${b.upstreamMaxStopSec}/${input.sim.downstream.ictSec}) = ${b.minCapacity}`, + operands: [ + { name: '上游最长停机', value: b.upstreamMaxStopSec, unit: 's', source: 'DERIVED' }, + { name: '下游 ICT', value: input.sim.downstream.ictSec, unit: 's/单位', source: 'POC' }, + ], + source: 'DERIVED', note: '解耦条件 C ≥ 上游最长停机;B < B_min 时停机仍会传导到全线', + }, + { + key: 'minCapacityDown', label: '最小解耦容量 B_min(下游侧)', value: b.minCapacityDownstream, unit: 'unit', + formula: `B_min = ceil(下游最长停机 / 上游ICT) = ceil(${b.downstreamMaxStopSec}/${input.sim.upstream.ictSec}) = ${b.minCapacityDownstream}`, + operands: [ + { name: '下游最长停机', value: b.downstreamMaxStopSec, unit: 's', source: 'DERIVED' }, + { name: '上游 ICT', value: input.sim.upstream.ictSec, unit: 's/单位', source: 'DERIVED' }, + ], + source: 'DERIVED', + note: '★ 分母是**上游 ICT**:下游停机时缓冲由上游填充。POC 只给上游侧,本侧为原型补充,两侧不可混用', + }, + { + key: 'blocked', label: '上游阻塞损失', value: b.upstream.blockedSec, unit: 'sec', + formula: `Σ(上游速率−下游速率)×满载受限时长 = ${b.upstream.blockedSec.toFixed(3)}s,共 ${b.upstream.blockCount} 次`, + operands: [ + { name: '阻塞次数', value: b.upstream.blockCount, unit: '次', source: 'DERIVED' }, + { name: '上游产出量', value: b.upstream.producedQty, unit: '单位', source: 'DERIVED' }, + ], + source: 'DERIVED', note: '阻塞次数口径=进入"缓冲满载受限"状态的次数,不是日志行数', + }, + { + key: 'starved', label: '下游饥饿损失', value: b.downstream.starvedSec, unit: 'sec', + formula: `Σ(下游速率−上游速率)×空缓冲受限时长 = ${b.downstream.starvedSec.toFixed(3)}s,共 ${b.downstream.starveCount} 次`, + operands: [{ name: '饥饿次数', value: b.downstream.starveCount, unit: '次', source: 'DERIVED' }], + source: 'DERIVED', + }, + ]; + + const notes: string[] = [ + `模板:SRF 缓冲解耦;范围 ${input.scopeLabel};业务日 ${input.bizDate}`, + b.decoupled + ? `上游侧解耦成立:C_down=${b.coverageSec}s ≥ 上游最长停机 ${b.upstreamMaxStopSec}s(B=${b.capacity} ≥ B_min=${b.minCapacity})` + : `★ 上游侧解耦不成立:C_down=${b.coverageSec}s < 上游最长停机 ${b.upstreamMaxStopSec}s,需 B ≥ ${b.minCapacity}`, + b.decoupledDownstream + ? `下游侧解耦成立:C_up=${b.coverageUpSec}s ≥ 下游最长停机 ${b.downstreamMaxStopSec}s(B=${b.capacity} ≥ B_min=${b.minCapacityDownstream})` + : `★ 下游侧解耦不成立:C_up=${b.coverageUpSec}s < 下游最长停机 ${b.downstreamMaxStopSec}s,需 B ≥ ${b.minCapacityDownstream}(分母为上游 ICT)`, + b.fullyDecoupled + ? '两侧均成立 → 全线解耦' + : '★ 至少一侧不成立 → 停机仍会传导,缓冲容量需按两侧 B_min 的较大值配置', + `零缓冲对照 OEE ${(zeroSerial.oee * 100).toFixed(2)}% 是理论下界(全耦合),**不是本线考核口径**,两者不可混用`, + `缓冲敏感性只用同为仿真数量的口径比:B=${b.capacity} → ${(simSerial.oee * 100).toFixed(2)}%,B=0 → ${(zeroSerial.oee * 100).toFixed(2)}%`, + ]; + if (input.anchors) { + notes.push( + `产出量取实测锚点(${stations.map((s) => `${s.deviceId}=${s.qtySource}`).join('、')}),` + + 'P = N×ICT/RT 为实测性能率;仿真数量另存 simQty 供数量对账(DQ)', + ); + } else { + notes.push( + '★ 产出量取仿真值:流体模型下 RT=N×ICT,故 P 恒等于 100%,这是**模型产物不是实测性能率**。' + + '接入产出锚点计数前,不得把本口径的 P 当作速度损失结论(接入后必须替换并做数量对账 DQ)', + ); + } + if (input.yieldRate.upstream >= 1 - EPS && input.yieldRate.downstream >= 1 - EPS) { + notes.push('Q=100% 为口径假设(种子无质量数据),不是实测良率;接入检测数据后必须替换'); + } + + return { + template: 'SRF_BUFFER', lineId: input.lineId, scopeLabel: input.scopeLabel, bizDate: input.bizDate, + buffer, stations, quantities, + line: { + a: serial.a, p: serial.p, q: serial.q, oee: serial.oee, + bottleneckId: serial.bottleneckId ?? '', formula: serial.formula, + }, + simBased: { a: simSerial.a, p: simSerial.p, q: simSerial.q, oee: simSerial.oee }, + zeroBuffer: { a: zeroSerial.a, p: zeroSerial.p, q: zeroSerial.q, oee: zeroSerial.oee, stations: [zUp, zDown] }, + qtyCrossCheck, + notes, ok: problems.length === 0, problems, + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三、ASLT:事件驱动(活跃窗口 + 12 Site 使能 + 六分类时间账) + * ══════════════════════════════════════════════════════════════════ */ + +/** 活跃窗口切分阈值:相邻事件间隔 > 60min 视为断点(POC 口径,C03)。 */ +export const ASLT_ACTIVE_GAP_SEC = 60 * 60; + +export interface ActiveWindow { + startSec: number; + endSec: number; + durationSec: number; + eventCount: number; +} + +/** + * 按 >gapSec 间隔切分活跃窗口。窗口取 [首事件, 末事件]。 + * 单事件窗口时长为 0,保留并计数(不静默丢弃,否则窗口数会与 POC 的 49 对不上)。 + */ +export function splitActiveWindows(timestampsSec: number[], gapSec: number = ASLT_ACTIVE_GAP_SEC): ActiveWindow[] { + const ts = [...timestampsSec].filter((t) => Number.isFinite(t)).sort((a, b) => a - b); + if (ts.length === 0) return []; + const out: ActiveWindow[] = []; + let start = ts[0]; + let prev = ts[0]; + let count = 1; + for (let i = 1; i < ts.length; i++) { + if (ts[i] - prev > gapSec) { + out.push({ startSec: start, endSec: prev, durationSec: prev - start, eventCount: count }); + start = ts[i]; + count = 0; + } + prev = ts[i]; + count++; + } + out.push({ startSec: start, endSec: prev, durationSec: prev - start, eventCount: count }); + return out; +} + +/** 已归入六分类的时间段。由 L3 从状态段/事件归口后注入,引擎只做加总与闭合校验。 */ +export interface AsltClassifiedInterval { + startSec: number; + endSec: number; + cls: AsltTimeClass; +} + +export interface AsltInput { + deviceId: string; + scopeLabel: string; + siteCount: number; + /** 全部事件时刻(epoch 秒),用于切活跃窗口 */ + eventTimestampsSec: number[]; + /** 运行窗口(A 的分子) */ + runWindows: { startSec: number; endSec: number }[]; + /** 各 Site 使能窗口(P 的分子,按 Site 分别给,重叠不重复计) */ + siteEnable: { siteId: number; startSec: number; endSec: number }[]; + /** 产出:FT 投入 / FT 合格 / RC 复测合格 */ + output: { ftInput: number; ftGood: number; rcGood: number }; + /** 六分类时间段(覆盖整个日历窗口) */ + classified: AsltClassifiedInterval[]; + /** 日历窗口秒数(六分类的分母) */ + calendarSec: number; + /** 报警行配对情况:paired + unpaired = 总报警行 */ + pairing: { paired: number; unpaired: number }; + activeGapSec?: number; + synthetic: boolean; + /** 数据来源分级;缺省按 synthetic 推断 SEED/POC。 */ + operandSource?: 'POC' | 'SEED'; +} + +export interface AsltResult { + template: RegionTemplate; + deviceId: string; + scopeLabel: string; + siteCount: number; + activeGapSec: number; + activeWindows: ActiveWindow[]; + activeWindowSec: number; + runSec: number; + /** Σ 各 Site 使能时长(同一 Site 内重叠去重) */ + siteEnableSec: number; + /** P 的分母 = siteCount × 活跃窗口 */ + siteCapacitySec: number; + a: number; + p: number; + q: number; + oee: number; + timeAccount: AsltTimeAccount[]; + /** 六分类残差 = calendarSec − Σ六类,必须为 0(POC 0.000000h) */ + timeAccountResidualSec: number; + calendarSec: number; + /** Wait + Plan 占比(POC 37.54%,改善顺序的依据) */ + waitPlanPct: number; + pairing: { paired: number; unpaired: number; total: number; rate: number }; + /** 终测计数原样透出:周期累计要 Σ合格/Σ投入,不得让调用方按索引去 quantities 里掏操作数 */ + output: { ftInput: number; ftGood: number; rcGood: number }; + quantities: TemplateQuantity[]; + notes: string[]; + ok: boolean; + problems: string[]; +} + +/** 同一 Site 的使能窗口合并去重后求总时长。跨 Site 不去重(12 站可同时使能)。 */ +export function mergedDurationSec(windows: { startSec: number; endSec: number }[]): number { + const sorted = windows + .filter((w) => Number.isFinite(w.startSec) && Number.isFinite(w.endSec) && w.endSec > w.startSec) + .sort((a, b) => a.startSec - b.startSec); + let total = 0; + let curS = -1; + let curE = -1; + for (const w of sorted) { + if (curS < 0) { curS = w.startSec; curE = w.endSec; continue; } + if (w.startSec <= curE + EPS) curE = Math.max(curE, w.endSec); + else { total += curE - curS; curS = w.startSec; curE = w.endSec; } + } + if (curS >= 0) total += curE - curS; + return total; +} + +/** ASLT 事件驱动模板。A/P 用活跃窗口口径,与站别汇总口径分开返回,禁止交叉配对。 */ +export function calcAslt(input: AsltInput): AsltResult { + const problems: string[] = []; + const gapSec = input.activeGapSec ?? ASLT_ACTIVE_GAP_SEC; + /* 计数类操作数的来源分级:demo=SEED、POC 参考=POC(不冒充 POC) */ + const dataSrc: QuantitySource = input.synthetic ? 'SEED' : (input.operandSource ?? 'POC'); + if (input.siteCount <= 0) problems.push('siteCount 必须为正(ASLT 为 12 Site)'); + if (input.calendarSec <= EPS) problems.push('calendarSec 必须为正'); + if (input.output.ftInput <= 0) problems.push('FT 投入为 0,Q 无定义(不得静默返回 0%)'); + if (input.output.ftGood + input.output.rcGood > input.output.ftInput + EPS) { + problems.push('合格数(FT+RC)超过投入数,计数口径有误'); + } + + const windows = splitActiveWindows(input.eventTimestampsSec, gapSec); + const activeWindowSec = windows.reduce((s, w) => s + w.durationSec, 0); + if (activeWindowSec <= EPS) problems.push('活跃窗口总时长为 0,A/P 无定义'); + + const runSec = mergedDurationSec(input.runWindows); + const bySite = new Map(); + for (const w of input.siteEnable) { + const list = bySite.get(w.siteId) ?? []; + list.push({ startSec: w.startSec, endSec: w.endSec }); + bySite.set(w.siteId, list); + } + let siteEnableSec = 0; + for (const [, list] of bySite) siteEnableSec += mergedDurationSec(list); + const siteCapacitySec = input.siteCount * activeWindowSec; + + /* ★ 一致性守卫:不一致必须报问题,不能靠 clamp01 把 A/P 悄悄压到 100% 后 ok:true。 + 运行时长超出活跃窗口 = 运行窗口与事件时间轴不同源;站点使能超出容量 = 站点数或窗口切分错。 + 这类错误一旦被 clamp 吃掉,页面会显示"A=100%"而无人察觉(探针实测踩过)。 */ + if (runSec > activeWindowSec + EPS) { + problems.push(`运行时长 ${runSec.toFixed(3)}s 超过活跃窗口总时长 ${activeWindowSec.toFixed(3)}s,运行窗口与事件时间轴不一致`); + } + if (siteEnableSec > siteCapacitySec + EPS) { + problems.push(`站点使能总时长 ${siteEnableSec.toFixed(3)}s 超过 Site 容量 ${siteCapacitySec.toFixed(3)}s(${input.siteCount} Site × 活跃窗口),站点数或窗口切分有误`); + } + const a = clamp01(div(runSec, activeWindowSec)); + const p = clamp01(div(siteEnableSec, siteCapacitySec)); + const q = clamp01(div(input.output.ftGood + input.output.rcGood, input.output.ftInput)); + const oee = clamp01(a * p * q); + + const sums: Record = { + WAIT: 0, PLAN: 0, OCC: 0, ENG: 0, STOP: 0, STANDBY: 0, + }; + for (const iv of input.classified) { + if (!ASLT_TIME_CLASSES.includes(iv.cls)) { problems.push(`非法六分类 ${iv.cls}`); continue; } + if (iv.endSec <= iv.startSec) { problems.push('六分类存在零长或倒序段'); continue; } + sums[iv.cls] += iv.endSec - iv.startSec; + } + const classifiedTotal = ASLT_TIME_CLASSES.reduce((s, c) => s + sums[c], 0); + const residual = input.calendarSec - classifiedTotal; + if (Math.abs(residual) > 1e-6) problems.push(`六分类时间账残差 ${residual.toFixed(6)}s ≠ 0(POC 要求 0.000000h)`); + const timeAccount: AsltTimeAccount[] = ASLT_TIME_CLASSES.map((c) => ({ + class: c, durationSec: sums[c], pctOfTotal: div(sums[c], input.calendarSec) * 100, + })); + const waitPlanPct = div(sums.WAIT + sums.PLAN, input.calendarSec) * 100; + + const pairTotal = input.pairing.paired + input.pairing.unpaired; + const pairRate = div(input.pairing.paired, pairTotal); + + const h = (sec: number) => sec / 3600; + const quantities: TemplateQuantity[] = [ + { + key: 'activeWindow', label: '活跃窗口总时长', value: activeWindowSec, unit: 'sec', + formula: `相邻事件间隔 > ${gapSec / 60}min 切分,得 ${windows.length} 个窗口,Σ时长 = ${h(activeWindowSec).toFixed(2)}h`, + operands: [ + { name: '事件行数', value: input.eventTimestampsSec.length, unit: '行', source: dataSrc }, + { name: '活跃窗口数', value: windows.length, unit: '个', source: 'DERIVED' }, + { name: '切分阈值', value: gapSec / 60, unit: 'min', source: 'CALIBER' }, + ], + source: 'DERIVED', + }, + { + key: 'a', label: 'A 可用性(活跃窗口口径)', value: a, unit: 'ratio', + formula: `运行时间 / 活跃窗口时间 = ${h(runSec).toFixed(2)}h / ${h(activeWindowSec).toFixed(2)}h = ${pct(a, 2)}`, + operands: [ + { name: '运行时间', value: runSec, unit: 's', source: 'DERIVED' }, + { name: '活跃窗口时间', value: activeWindowSec, unit: 's', source: 'DERIVED' }, + ], + source: 'DERIVED', note: '★ 这是活跃窗口口径,不是站别汇总口径;两者必须各自标注,不得交叉配对', + }, + { + key: 'p', label: 'P 性能(12 Site 使能占比)', value: p, unit: 'ratio', + formula: `Σ站点使能时长 / (Site数 × 活跃窗口) = ${h(siteEnableSec).toFixed(2)}h / ${h(siteCapacitySec).toFixed(2)}h = ${pct(p, 2)}`, + operands: [ + { name: '站点使能总时长', value: siteEnableSec, unit: 's', source: 'DERIVED' }, + { name: 'Site 数', value: input.siteCount, unit: '站', source: 'POC' }, + { name: '站点容量时长', value: siteCapacitySec, unit: 's', source: 'DERIVED' }, + ], + source: 'DERIVED', note: '同一 Site 内重叠窗口去重,跨 Site 不去重', + }, + { + key: 'q', label: 'Q 质量(终测合格率)', value: q, unit: 'ratio', + formula: `(FT合格 + RC复测合格) / FT投入 = (${input.output.ftGood} + ${input.output.rcGood}) / ${input.output.ftInput} = ${pct(q, 2)}`, + operands: [ + { name: 'FT 投入', value: input.output.ftInput, unit: '颗', source: dataSrc }, + { name: 'FT 合格', value: input.output.ftGood, unit: '颗', source: dataSrc }, + { name: 'RC 复测合格', value: input.output.rcGood, unit: '颗', source: dataSrc }, + ], + source: 'DERIVED', + }, + { + key: 'waitPlan', label: 'Wait + Plan 占比', value: waitPlanPct, unit: 'ratio', + formula: `(Wait ${h(sums.WAIT).toFixed(2)}h + Plan ${h(sums.PLAN).toFixed(2)}h) / 日历 ${h(input.calendarSec).toFixed(2)}h = ${waitPlanPct.toFixed(2)}%`, + operands: [ + { name: 'Wait', value: sums.WAIT, unit: 's', source: 'DERIVED' }, + { name: 'Plan', value: sums.PLAN, unit: 's', source: 'DERIVED' }, + { name: '日历窗口', value: input.calendarSec, unit: 's', source: 'DERIVED' }, + ], + source: 'DERIVED', note: '改善顺序依据:物料保障 → 排产计划 → 站点满载 → 换型标准化 → 设备维修(设备维修排最后)', + }, + { + key: 'pairing', label: '报警行配对率', value: pairRate, unit: 'ratio', + formula: `${input.pairing.paired} / ${pairTotal} = ${pct(pairRate, 2)}`, + operands: [ + { name: '已配对', value: input.pairing.paired, unit: '行', source: 'DERIVED' }, + { name: '未配对', value: input.pairing.unpaired, unit: '行', source: 'DERIVED' }, + ], + source: 'DERIVED', note: '未配对部分用活跃窗口补足,不得当作 0 时长丢弃', + }, + ]; + + const notes: string[] = [ + `模板:ASLT 事件驱动;范围 ${input.scopeLabel};${input.siteCount} Site`, + 'A/P 为**活跃窗口口径**(单台 12 Site)。站别汇总口径的 A/P 是另一套读数,需要时由数据层并列展示,不得混算', + 'ASLT 无客户算法表,口径为系统建议,须纳入版本管理并由 IE 定版(C03/C04/C05)', + `六分类时间账残差 ${residual.toFixed(6)}s;Wait+Plan=${waitPlanPct.toFixed(2)}%`, + ]; + if (input.synthetic) notes.push('★ 本读数为演示合成种子,不得冒充 POC 锚点 41.75%(该值属站别汇总口径)'); + + return { + template: 'ASLT_EVENT', deviceId: input.deviceId, scopeLabel: input.scopeLabel, + siteCount: input.siteCount, activeGapSec: gapSec, activeWindows: windows, + activeWindowSec, runSec, siteEnableSec, siteCapacitySec, + a, p, q, oee, timeAccount, timeAccountResidualSec: residual, calendarSec: input.calendarSec, + waitPlanPct, pairing: { ...input.pairing, total: pairTotal, rate: pairRate }, + output: { ...input.output }, + quantities, notes, ok: problems.length === 0, problems, + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 四、口径混用守卫(两处已实测文档矛盾的可执行形式) + * ══════════════════════════════════════════════════════════════════ */ + +export interface LabelledReading { + label: string; + a: number; + p: number; + q: number; + oee: number; +} + +/** + * 同一套读数内部必须自洽:A×P×Q ≡ OEE。 + * 跨口径交叉配对(如 ASLT 活跃窗口 A/P 配站别汇总 OEE 41.75%)会在这里暴露。 + */ +export function checkReadingSelfConsistency(r: LabelledReading): { ok: boolean; residual: number; recomputed: number } { + const recomputed = r.a * r.p * r.q; + const residual = recomputed - r.oee; + return { ok: Math.abs(residual) < 1e-4, residual, recomputed }; +} + +/** + * FT 通用式误用守卫:FT 的 A 必须来自连乘扣减式。 + * 若有人把 actualTier 的 RT/PPT 套到 FT 上,两者差异会远超容差。 + */ +export function checkFtNotGeneric(r: FtResult): { ok: boolean; diff: number } { + const diff = Math.abs(r.a - r.contrastGenericA); + return { ok: diff > 1e-4, diff }; +} + +/** 展示值复算容差(分项已四舍五入到 2 位小数)。引擎内部仍用 EPS=1e-9。 */ +export const DISPLAY_RECOMPUTE_TOLERANCE_PP = 0.02; + +/** 用 POC 展示值(百分数,2 位小数)复算,偏差 ≤0.02pp 视为一致。 */ +export function recomputeFromDisplayPct(aPct: number, pPct: number, qPct: number): number { + return (aPct / 100) * (pPct / 100) * (qPct / 100) * 100; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/threeTier.ts b/src/modules/tfamd-oee/lib/oee/threeTier.ts new file mode 100644 index 0000000..281ca63 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/threeTier.ts @@ -0,0 +1,184 @@ +/** + * L2 引擎 · 三层 OEE + 顺序替代法差异分解(规划书 4.1.2 / 4.1.3)。 + * + * ★ 零 IO 纯函数。守断言③(顺序替代恒等)。 + * + * 三层定义(原文照录): + * 理论 OEE = A_th × 100% × Q_design 设备能力上限,对标行业最佳 + * 计划 OEE = A_plan × P_plan × Q_plan 管理水平标杆,评估排产合理性 + * 实际 OEE = A_act × P_act × Q_act 实际运营效果,用于考核与改善 + * + * 三条设计约束: + * 1. **同一分母**:三层共用 PPT = CT − PDT,计划停机只扣除一次; + * 2. **间隙可加**:顺序替换法,三项差异之和恒等于总差异; + * 3. **参数可校**:设计良率/计划性能率/目标良率/日不可消除停机均可配置(C27/C28)。 + * + * 顺序替换法(**顺序固定 A → P → Q,不可调换**,否则交叉项归属不同、结果不可加): + * ΔA = (A₂ − A₁) × P₁ × Q₁ + * ΔP = A₂ × (P₂ − P₁) × Q₁ + * ΔQ = A₂ × P₂ × (Q₂ − Q₁) + * ΔA + ΔP + ΔQ ≡ OEE₂ − OEE₁ + */ +import { EPS, type OeeResult, type TierValues } from '../../types/oee'; + +/** 三层参数。由口径配置中心注入(C27/C28),引擎不写死任何参数值。 */ +export interface ThreeTierParams { + /** 设计良率 Q_design(C27) */ + designYield: number; + /** 计划性能率 P_plan(C27) */ + planPerformanceRate: number; + /** 目标良率 Q_plan(C27) */ + targetYield: number; + /** 每日不可避免停机(秒),理论层的 A 由它决定(C27) */ + dailyUnavoidableStopSec: number; + /** IE 月度计划停机率目标(C28:计划 OEE 的计划损失取 IE 月度目标,不取 APS 计划待料) */ + monthlyPlannedStopRate: number; +} + +export interface ActualInput { + pptSec: number; + /** RUN 段时长之和 */ + rtSec: number; + outputQty: number; + goodQty: number; + ictSec: number; + /** 六桶时长,用于 AV/OP 的口径推算 */ + faultSec: number; + changeoverSec: number; + idleMinorSec: number; +} + +/** 安全除法:分母为 0 时返回 0,不产生 NaN/Infinity 污染下游。 */ +function div(n: number, d: number): number { + return d > EPS ? n / d : 0; +} + +function clamp01(x: number): number { + if (!Number.isFinite(x)) return 0; + return Math.min(1, Math.max(0, x)); +} + +/** + * 实际层:A = RT/PPT(通用式)、P = N×ICT/RT、Q = good/N。 + * ⚠ **FT 不适用本式**:FT 的 A 是多因子连乘、P 是 1−三项损失占比,见 templates.calcFt。 + * 把通用式套到 FT 上会算出完全不同的数,且无法与客户基准对账(规划书 4.1.4 口径不同构警告)。 + */ +export function actualTier(a: ActualInput): TierValues { + const A = clamp01(div(a.rtSec, a.pptSec)); + const P = clamp01(div(a.outputQty * a.ictSec, a.rtSec)); + const Q = clamp01(div(a.goodQty, a.outputQty)); + // AV = PPT 扣除停机与卡料等可用性损失;OP = AV 扣除空转与短停(附录 F 定义) + const avSec = Math.max(0, a.pptSec - a.faultSec - a.changeoverSec); + const opSec = Math.max(0, avSec - a.idleMinorSec); + return { + a: A, p: P, q: Q, oee: A * P * Q, + rtSec: a.rtSec, avSec, opSec, + outputQty: a.outputQty, goodQty: a.goodQty, ictSec: a.ictSec, + }; +} + +/** 理论层:P 恒为 100%(完美执行),A 由每日不可避免停机决定,Q 取设计良率。 */ +export function theoreticalTier(pptSec: number, ictSec: number, p: ThreeTierParams): TierValues { + const A = clamp01(1 - div(p.dailyUnavoidableStopSec, pptSec)); + const P = 1; + const Q = clamp01(p.designYield); + const rtSec = pptSec * A; + const outputQty = div(rtSec, ictSec); // 理想节拍下应有的产出 + const goodQty = outputQty * Q; + return { a: A, p: P, q: Q, oee: A * P * Q, rtSec, avSec: rtSec, opSec: rtSec, outputQty, goodQty, ictSec }; +} + +/** 计划层:A 由 IE 月度计划停机率目标决定(C28),P/Q 取 C27 的计划性能率与目标良率。 */ +export function plannedTier(pptSec: number, ictSec: number, p: ThreeTierParams): TierValues { + const A = clamp01(1 - p.monthlyPlannedStopRate); + const P = clamp01(p.planPerformanceRate); + const Q = clamp01(p.targetYield); + const rtSec = pptSec * A; + const outputQty = div(rtSec * P, ictSec); + const goodQty = outputQty * Q; + return { a: A, p: P, q: Q, oee: A * P * Q, rtSec, avSec: rtSec, opSec: rtSec, outputQty, goodQty, ictSec }; +} + +export interface ThreeTierInput { + pptSec: number; + ictSec: number; + params: ThreeTierParams; + actual: ActualInput; +} + +export interface ThreeTierOutput { + theoretical: TierValues; + planned: TierValues; + actual: TierValues; + /** 理论 → 实际的顺序替代分解(评审最有说服力的一屏) */ + deltaTheoreticalToActual: DeltaResult; + /** 计划 → 实际 */ + deltaPlannedToActual: DeltaResult; +} + +export function calcThreeTier(input: ThreeTierInput): ThreeTierOutput { + const theoretical = theoreticalTier(input.pptSec, input.ictSec, input.params); + const planned = plannedTier(input.pptSec, input.ictSec, input.params); + const actual = actualTier(input.actual); + return { + theoretical, planned, actual, + deltaTheoreticalToActual: sequentialReplace(theoretical, actual), + deltaPlannedToActual: sequentialReplace(planned, actual), + }; +} + +export interface DeltaResult { + dA: number; dP: number; dQ: number; total: number; + /** 恒等式是否成立(EPS 内)。任何页面出现残差即视为 bug。 */ + identityHolds: boolean; + /** 三项之差与总差异的浮点残差,供校验脚本打印 */ + identityResidual: number; +} + +/** + * 顺序替换法。**替换顺序固定 A → P → Q**,不得调换。 + * 记 1 为基准、2 为对照。该式可推广到任意两个口径或两个时段的对比。 + */ +export function sequentialReplace(base: TierValues, target: TierValues): DeltaResult { + const dA = (target.a - base.a) * base.p * base.q; + const dP = target.a * (target.p - base.p) * base.q; + const dQ = target.a * target.p * (target.q - base.q); + const total = target.oee - base.oee; + const sum = dA + dP + dQ; + const identityResidual = sum - total; + return { dA, dP, dQ, total, identityHolds: Math.abs(identityResidual) < EPS, identityResidual }; +} + +/** + * 恒等式的独立复核:不用 oee 字段,直接从 A/P/Q 三率重算, + * 防止「oee 字段本身算错但恒等式照样成立」的假通过。 + */ +export function verifyIdentityFromRates(base: TierValues, target: TierValues): { ok: boolean; residual: number } { + const dA = (target.a - base.a) * base.p * base.q; + const dP = target.a * (target.p - base.p) * base.q; + const dQ = target.a * target.p * (target.q - base.q); + const oee1 = base.a * base.p * base.q; + const oee2 = target.a * target.p * target.q; + const residual = (dA + dP + dQ) - (oee2 - oee1); + return { ok: Math.abs(residual) < EPS, residual }; +} + +/** 把三层结果装进 OeeResult 的 tiers 字段(保持契约形状,不在这里另立结构)。 */ +export function toTiers(out: ThreeTierOutput): OeeResult['tiers'] { + return { theoretical: out.theoretical, planned: out.planned, actual: out.actual }; +} + +/** + * POC 锚点:SRF 产线 2026-09-03、13 台设备的三层实测示例〔POC〕。 + * 我方未独立复核,引用必须显示「参考基线·来源:鼎捷 POC」。 + * 这三个数与站别基线 25.50%、敏感性 29.84% 是**不同口径,不可混用**。 + */ +export const POC_SRF_THREE_TIER_EXAMPLE = { + scope: 'SRF 产线 · 2026-09-03 · 13 台设备', + baselineNote: '参考基线·来源:鼎捷 POC' as const, + theoretical: { a: 0.979, p: 1.000, q: 0.990, oee: 0.969 }, + planned: { a: 0.980, p: 0.950, q: 0.980, oee: 0.912 }, + actual: { a: 0.974, p: 0.596, q: 0.985, oee: 0.572 }, + /** 未归因(间隙/无数据)占计划时间的比例 —— 第一优先级不是买设备,是把未归因段归因 */ + unattributedPctOfPlanTime: 0.317, +}; \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oee/trace.ts b/src/modules/tfamd-oee/lib/oee/trace.ts new file mode 100644 index 0000000..4ed554c --- /dev/null +++ b/src/modules/tfamd-oee/lib/oee/trace.ts @@ -0,0 +1,441 @@ +/** + * L2 引擎 · 五层血缘回溯(断言①:可下钻到行号)。 + * + * ★ 零 IO 纯函数:原始行、事件、状态段、因子、桶、三档结果全部由 L3 注入, + * 本文件不 import 数据层、不取时钟、不掷随机数、无模块级可变全局。 + * + * 回溯链(建议书 3.1,单向): + * L5 oee_result.detailRef → L4 factor_duration / loss_bucket → L3 state_segment + * → L2 event_instance.evidence → L1 raw_log_line.lineNo + * + * ★ 三条诚实性纪律(违反即"假证据",比没有证据更危险): + * 1. **三种结论形态必须分开**: + * - event :真能落到原始行号,wired=true; + * - derived :由节拍偏差/检测结果/间隙规则现算,**没有对应原始行**,wired=false 且 note 说明为什么; + * - parameter :理论档/计划档由附录 E 参数派生,与当日日志无关,wired=false 且 note 点名参数。 + * 把 derived/parameter 硬塞一个行号就是编造证据;把它们静默留空则会让评审以为链路断了。 + * 2. **行号必须对账**:evidence.rawLineId 要真在注入的 rawLines 里找到,且 lineNo/filePath 逐字相等。 + * 引用一个不存在的行=血缘断裂,matchedRawLine=false 会被断言①抓出来。 + * 3. **残差与未归因不编证据**:IDLE 空档多由间隙规则生成(filledByGapRule),本就没有事件行; + * 如实标 derived,并指明这正是 DQ-06 要阻断的对象。 + * + * 原型无 oee_result_detail 表,故 detailRef 用字符串句柄(建议书 3.4.1:生产改为真外键)。 + * 句柄格式固定 `oee:设备:业务日:口径版本`,parseDetailRef 可逆解,供断言①做往返对账。 + */ +import { + BUCKET_LABEL, + type EventInstance, type FactorDuration, type LossBucket, type LossBucketResult, + type RawLogLine, type StateSegment, type TierValues, +} from '../../types/oee'; +import { STATE_TO_BUCKET } from './lossBuckets'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、血缘入口句柄 + * ══════════════════════════════════════════════════════════════════ */ + +/** 构造 detailRef。三段都非空才成立,空段直接返回空串让上游断言失败,不静默拼出残缺句柄。 */ +export function buildDetailRef(deviceId: string, bizDate: string, caliberVersion: string): string { + if (!deviceId || !bizDate || !caliberVersion) return ''; + return `oee:${deviceId}:${bizDate}:${caliberVersion}`; +} + +/** 逆解 detailRef。格式不符返回 null(不猜、不补默认值)。 */ +export function parseDetailRef(ref: string): { deviceId: string; bizDate: string; caliberVersion: string } | null { + const parts = ref.split(':'); + if (parts.length !== 4 || parts[0] !== 'oee') return null; + const [, deviceId, bizDate, caliberVersion] = parts; + if (!deviceId || !bizDate || !caliberVersion) return null; + return { deviceId, bizDate, caliberVersion }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 二、回溯目标与结论 + * ══════════════════════════════════════════════════════════════════ */ + +export type TraceTargetKind = 'tier' | 'bucket' | 'factor' | 'residual'; +export type TierName = 'theoretical' | 'planned' | 'actual'; +export type TierMetric = 'a' | 'p' | 'q' | 'oee'; + +/** 一个"OEE 数字"。断言①抽样抽的就是这些叶子。 */ +export interface TraceTarget { + kind: TraceTargetKind; + /** 稳定键:tier:actual.oee / bucket:FAULT / factor:一级>二级 / residual / unattributed */ + key: string; + label: string; + value: number; + unit: 'ratio' | 'sec'; + bucket: LossBucket | null; + tier?: TierName; + metric?: TierMetric; +} + +/** 证据落点:L1 原始日志行。source 区分事件行与产出锚点行。 */ +export interface TraceEvidence { + rawLineId: string; + lineNo: number; + filePath: string; + digest: string; + source: 'event' | 'anchor'; + /** ★ 该行是否真在种子文件里找到且行号/路径逐字相等(防"引用了不存在的行") */ + matchedRawLine: boolean; +} + +export type TraceKind = 'event' | 'derived' | 'parameter'; + +export interface TraceResult { + detailRef: string; + target: TraceTarget; + kind: TraceKind; + /** 逐层链路,供 UI 面包屑;任何形态都必须非空 */ + chain: string[]; + segmentIds: string[]; + eventIds: string[]; + evidence: TraceEvidence[]; + /** 为什么没有行号(derived/parameter 必填);event 形态写清走的是哪条路 */ + note: string; + /** 全链是否真贯通到行号:只有 event 且每条证据都对账成功才为 true */ + wired: boolean; +} + +/** 产出锚点(L1 行号自带):P 因子看 cycleSec,Q 因子看 good。 */ +export interface TraceAnchor { + rawLineId: string; + lineNo: number; + cycleSec: number; + good: boolean; + phase: 'START' | 'COMPLETE'; +} + +export interface TraceInput { + detailRef: string; + bizDate: string; + deviceId: string; + caliberVersion: string; + rawLines: RawLogLine[]; + events: EventInstance[]; + anchors: TraceAnchor[]; + segments: StateSegment[]; + factors: FactorDuration[]; + buckets: LossBucketResult[]; + tiers: { theoretical: TierValues; planned: TierValues; actual: TierValues }; + residualSec: number; + unattributedSec: number; + /** 首件不良数(录入台 D 类人工补录)。开机不良桶的唯一数量来源,锚点不区分首件与过程不良。 */ + startupDefectQty: number; + /** 理论/计划档的参数出处说明(由 L3 注入,引擎不自己写口径文案) */ + paramsNote: string; +} + +const TIER_LABEL: Record = { theoretical: '理论档', planned: '计划档', actual: '实际档' }; +const METRIC_LABEL: Record = { a: 'A 时间开动率', p: 'P 性能开动率', q: 'Q 合格品率', oee: 'OEE' }; + +/* ══════════════════════════════════════════════════════════════════ + * 三、枚举可回溯的数字叶子 + * ══════════════════════════════════════════════════════════════════ */ + +/** 12 个三档读数 + 6 个桶时长 + N 个因子时长 + 残差 + 未归因。顺序固定,便于可重放对账。 */ +export function enumerateTargets(input: TraceInput): TraceTarget[] { + const out: TraceTarget[] = []; + const tierNames: TierName[] = ['theoretical', 'planned', 'actual']; + const metrics: TierMetric[] = ['a', 'p', 'q', 'oee']; + for (const t of tierNames) { + for (const m of metrics) { + out.push({ + kind: 'tier', key: `tier:${t}.${m}`, + label: `${TIER_LABEL[t]} · ${METRIC_LABEL[m]}`, + value: input.tiers[t][m], unit: 'ratio', bucket: null, tier: t, metric: m, + }); + } + } + for (const b of input.buckets) { + out.push({ + kind: 'bucket', key: `bucket:${b.bucket}`, + label: `${BUCKET_LABEL[b.bucket]}(${b.factor})`, + value: b.durationSec, unit: 'sec', bucket: b.bucket, + }); + } + for (const f of input.factors) { + out.push({ + kind: 'factor', key: `factor:${f.factorL1}>${f.factorL2}`, + label: `${f.factorL1} › ${f.factorL2}`, + value: f.durationSec, unit: 'sec', bucket: f.bucket, + }); + } + out.push({ kind: 'residual', key: 'residual', label: '残差(PPT − 有效生产 − Σ六桶)', value: input.residualSec, unit: 'sec', bucket: null }); + out.push({ kind: 'residual', key: 'unattributed', label: '未归因时长(IDLE)', value: input.unattributedSec, unit: 'sec', bucket: null }); + return out; +} + +/* ══════════════════════════════════════════════════════════════════ + * 四、证据取回与对账 + * ══════════════════════════════════════════════════════════════════ */ + +/** 按 rawLineId 对账原始行:行号与路径都必须逐字相等,找不到就标 false,不补一个"看起来对"的行号。 */ +function matchRaw(rawLines: RawLogLine[], rawLineId: string, lineNo: number, filePath: string): boolean { + const hit = rawLines.find((l) => l.id === rawLineId); + return !!hit && hit.lineNo === lineNo && hit.filePath === filePath; +} + +function evidenceOfEvents(input: TraceInput, eventIds: string[]): TraceEvidence[] { + const byId = new Map(input.events.map((e) => [e.id, e])); + const seen = new Set(); + const out: TraceEvidence[] = []; + for (const id of eventIds) { + const ev = byId.get(id); + if (!ev || seen.has(ev.evidence.rawLineId)) continue; + seen.add(ev.evidence.rawLineId); + out.push({ + rawLineId: ev.evidence.rawLineId, lineNo: ev.evidence.lineNo, + filePath: ev.evidence.filePath, digest: ev.evidence.digest, source: 'event', + matchedRawLine: matchRaw(input.rawLines, ev.evidence.rawLineId, ev.evidence.lineNo, ev.evidence.filePath), + }); + } + return out; +} + +function evidenceOfAnchors(input: TraceInput, anchors: TraceAnchor[]): TraceEvidence[] { + const byId = new Map(input.rawLines.map((l) => [l.id, l])); + const seen = new Set(); + const out: TraceEvidence[] = []; + for (const a of anchors) { + if (seen.has(a.rawLineId)) continue; + seen.add(a.rawLineId); + const raw = byId.get(a.rawLineId); + out.push({ + rawLineId: a.rawLineId, lineNo: a.lineNo, + filePath: raw?.filePath ?? '', digest: raw?.digest ?? '', source: 'anchor', + matchedRawLine: !!raw && raw.lineNo === a.lineNo, + }); + } + return out; +} + +/** 段 → 事件 id(去重、保序)。段是 L3 与 L2 之间唯一的桥。 */ +function eventIdsOfSegments(segments: StateSegment[], segmentIds: string[]): string[] { + const want = new Set(segmentIds); + const out: string[] = []; + const seen = new Set(); + for (const s of segments) { + if (!want.has(s.id)) continue; + for (const id of s.eventIds) { if (!seen.has(id)) { seen.add(id); out.push(id); } } + } + return out; +} + +/** 进入分母的段:UNKNOWN 不计分母,PLAN_STOP/PM 已作 PDT 扣除。 */ +function denominatorSegments(segments: StateSegment[]): StateSegment[] { + return segments.filter((s) => s.state !== 'UNKNOWN' && s.state !== 'PLAN_STOP' && s.state !== 'PM'); +} + +const uniq = (xs: string[]): string[] => [...new Set(xs)]; + +/** 只有 event 形态且每条证据都对账成功、行号为正,才算真贯通。 */ +function isWired(kind: TraceKind, evidence: TraceEvidence[]): boolean { + return kind === 'event' && evidence.length > 0 + && evidence.every((e) => e.matchedRawLine && e.lineNo > 0 && e.filePath.length > 0); +} + +/* ══════════════════════════════════════════════════════════════════ + * 五、逐形态回溯 + * ══════════════════════════════════════════════════════════════════ */ + +function traceTier(input: TraceInput, target: TraceTarget): TraceResult { + const tier = target.tier as TierName; + const base = [`oee_result(${input.detailRef})`, `three_tier.${tier}`]; + if (tier !== 'actual') { + return { + detailRef: input.detailRef, target, kind: 'parameter', + chain: [...base, 'caliber_param(附录 E)'], + segmentIds: [], eventIds: [], evidence: [], + note: `${TIER_LABEL[tier]}由口径参数派生,与当日日志无关,故无原始行号。${input.paramsNote}`, + wired: false, + }; + } + const segs = denominatorSegments(input.segments); + const segmentIds = segs.map((s) => s.id); + const eventIds = eventIdsOfSegments(input.segments, segmentIds); + const complete = input.anchors.filter((a) => a.phase === 'COMPLETE'); + const evidence = [...evidenceOfEvents(input, eventIds), ...evidenceOfAnchors(input, complete)]; + const kind: TraceKind = evidence.length > 0 ? 'event' : 'derived'; + return { + detailRef: input.detailRef, target, kind, + chain: [...base, 'state_segment(进入分母的段)', 'event_instance', 'output_anchor(COMPLETE)', 'raw_log_line'], + segmentIds, eventIds, evidence, + note: kind === 'event' + ? `实际档=当日段时长合计与产出锚点现算(A=RT/PPT、P=N×ICT/RT、Q=good/N、OEE=good×ICT/PPT);证据为构成分母段的事件行+COMPLETE 产出锚点行,共 ${evidence.length} 行。` + : '当日无进入分母的段、也无 COMPLETE 产出锚点,实际档无法落到原始行;如实标缺口,不编造行号。', + wired: isWired(kind, evidence), + }; +} + +function traceBucket(input: TraceInput, target: TraceTarget): TraceResult { + const bucket = target.bucket as LossBucket; + const b = input.buckets.find((x) => x.bucket === bucket); + const base = [`oee_result(${input.detailRef})`, `loss_bucket(${bucket})`]; + const factorRows = input.factors.filter((f) => f.bucket === bucket); + const segmentIds = uniq(factorRows.flatMap((f) => f.segmentIds)); + /* 因子层为空时退到状态段层:按 STATE_TO_BUCKET 反查同桶的段,绝不跨桶借证据 */ + const fallbackSegs = segmentIds.length > 0 + ? [] + : input.segments.filter((s) => STATE_TO_BUCKET[s.state] === bucket); + const allSegIds = uniq([...segmentIds, ...fallbackSegs.map((s) => s.id)]); + const eventIds = uniq([ + ...eventIdsOfSegments(input.segments, allSegIds), + ...factorRows.flatMap((f) => f.eventIds), + ]); + + if (b?.derivedFromCycleDeviation) { + /* + * 开机不良的数量来自录入台 D 类人工补录,产出锚点只标 good/不良、**不区分首件与过程不良**, + * 故不能拿不良锚点当它的证据(那会与 PROCESS_DEFECT 重复计同一批行)。如实标 derived。 + * ★ 这一支必须在"零时长"判断**之前**:0 件也要点名数量来源是人工补录, + * 否则评审会以为 0 是采集来的(实测踩过:0s 桶的 note 只说"无构成量",没说来源)。 + */ + if (bucket === 'STARTUP_DEFECT') { + return { + detailRef: input.detailRef, target, kind: 'derived', + chain: [...base, 'factor_duration(首件不良数 × ICT)', 'caliber_param(录入台 D 类补录)'], + segmentIds: allSegIds, eventIds, evidence: [], + note: `开机不良=首件不良数 ${input.startupDefectQty} × ICT ${input.tiers.actual.ictSec}s = ${b.durationSec}s。` + + '数量来自人工补录(D 类事件),产出锚点不区分首件与过程不良,故无独立原始行号;' + + (b.durationSec <= 0 ? '当日补录为 0 件,桶时长为 0,不借用过程不良的行号充数;' : '') + + 'W3 录入台落地后由补录单据提供证据链,此处不编造行号。', + wired: false, + }; + } + /* + * ★ 零时长桶不许借证据(实测踩过):若沿用"不良 COMPLETE 锚点"这条路, + * 0s 的桶会挂上别的桶的行号、反而 wired=true——比"没有证据"更危险。 + * 桶时长为 0 就是没有构成事实。 + */ + if (b.durationSec <= 0) { + return { + detailRef: input.detailRef, target, kind: 'derived', + chain: [...base, 'factor_duration(当日无构成量)'], + segmentIds: allSegIds, eventIds, evidence: [], + note: `${BUCKET_LABEL[bucket]}当日时长为 0(无构成事件、也无派生量),没有可落的原始行;如实标缺口,不借用其他桶的行号充数。`, + wired: false, + }; + } + /* 速度/过程不良:无成对停机事件,证据是 COMPLETE 产出锚点行(实测节拍 / 不良标记)。 + START 锚点只定 lot 窗口起点、不计入 N,故不作为 P/Q 的证据。 */ + const anchors = bucket === 'SPEED' + ? input.anchors.filter((a) => a.phase === 'COMPLETE') + : input.anchors.filter((a) => a.phase === 'COMPLETE' && !a.good); + const evidence = evidenceOfAnchors(input, anchors); + const kind: TraceKind = evidence.length > 0 ? 'event' : 'derived'; + return { + detailRef: input.detailRef, target, kind, + chain: [...base, 'factor_duration(节拍/检测派生)', 'output_anchor(COMPLETE)', 'raw_log_line'], + segmentIds: allSegIds, eventIds, evidence, + note: kind === 'event' + ? (bucket === 'SPEED' + ? `速度损失=RT − N×ICT,由实测单板节拍与理论节拍之差现算,无成对停机事件;证据为 ${evidence.length} 条 COMPLETE 产出锚点行(cycleSec)。` + : `过程不良=(N − good)×ICT,由检测结果现算,无成对停机事件;证据为 ${evidence.length} 条不良 COMPLETE 锚点行。`) + : (bucket === 'SPEED' + ? '当日无 COMPLETE 产出锚点,速度损失无法落到原始行;如实标缺口,不编造行号。' + : '当日无不良 COMPLETE 锚点,过程不良无法落到原始行;如实标缺口,不编造行号。'), + wired: isWired(kind, evidence), + }; + } + + const evidence = evidenceOfEvents(input, eventIds); + const kind: TraceKind = evidence.length > 0 ? 'event' : 'derived'; + return { + detailRef: input.detailRef, target, kind, + chain: [...base, 'factor_duration', 'state_segment', 'event_instance', 'raw_log_line'], + segmentIds: allSegIds, eventIds, evidence, + note: kind === 'event' + ? `${BUCKET_LABEL[bucket]}由成对事件构成:桶 → 因子 → ${allSegIds.length} 个状态段 → ${eventIds.length} 条事件实例 → ${evidence.length} 条原始行。` + : `${BUCKET_LABEL[bucket]}当日无构成事件(段可能由间隙规则生成或时长为 0),无原始行号可落;如实标缺口,不编造证据。`, + wired: isWired(kind, evidence), + }; +} + +function traceFactor(input: TraceInput, target: TraceTarget): TraceResult { + const f = input.factors.find((x) => `factor:${x.factorL1}>${x.factorL2}` === target.key); + const base = [`oee_result(${input.detailRef})`, `factor_duration(${target.label})`]; + const segmentIds = uniq(f?.segmentIds ?? []); + const eventIds = uniq([...eventIdsOfSegments(input.segments, segmentIds), ...(f?.eventIds ?? [])]); + const evidence = evidenceOfEvents(input, eventIds); + const kind: TraceKind = evidence.length > 0 ? 'event' : 'derived'; + return { + detailRef: input.detailRef, target, kind, + chain: [...base, 'state_segment', 'event_instance', 'raw_log_line'], + segmentIds, eventIds, evidence, + note: kind === 'event' + ? `因子时长由 ${segmentIds.length} 个状态段累加,落到 ${evidence.length} 条原始行。` + : '该因子当日无构成事件(时长为 0 或来自未单独计量的子因子),无原始行号;如实标缺口,不摊一个数充精度。', + wired: isWired(kind, evidence), + }; +} + +function traceResidual(input: TraceInput, target: TraceTarget): TraceResult { + const idle = input.segments.filter((s) => s.state === 'IDLE'); + const segmentIds = idle.map((s) => s.id); + const eventIds = eventIdsOfSegments(input.segments, segmentIds); + const evidence = evidenceOfEvents(input, eventIds); + const filled = idle.filter((s) => s.filledByGapRule).length; + const base = [`oee_result(${input.detailRef})`, target.key === 'residual' ? 'residual(残差恒等式)' : 'unattributed(IDLE)']; + /* 残差有事件证据时才算 event;纯间隙填充的空档本就没有行号,这是 DQ-06 的对象,不是链路 bug */ + const kind: TraceKind = evidence.length > 0 ? 'event' : 'derived'; + return { + detailRef: input.detailRef, target, kind, + chain: [...base, 'state_segment(IDLE)', 'event_instance', 'raw_log_line'], + segmentIds, eventIds, evidence, + note: kind === 'event' + ? `未归因时长来自 ${segmentIds.length} 个 IDLE 段,其中 ${filled} 个由间隙规则生成;有事件的段落落到 ${evidence.length} 条原始行。` + : `残差=未归因 IDLE 时长(${input.unattributedSec}s)。${segmentIds.length} 个 IDLE 段中 ${filled} 个由间隙规则生成,本就没有事件行号;` + + '这正是 DQ-06「未归因 >5% 阻断发布」要治的缺口——如实标 derived,不编造行号,也不把残差归一化掉。', + wired: isWired(kind, evidence), + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 六、入口 + * ══════════════════════════════════════════════════════════════════ */ + +/** 回溯单个数字。未知 key 返回 null(不猜一个目标凑数)。 */ +export function resolveTrace(input: TraceInput, target: TraceTarget): TraceResult { + switch (target.kind) { + case 'tier': return traceTier(input, target); + case 'bucket': return traceBucket(input, target); + case 'factor': return traceFactor(input, target); + case 'residual': return traceResidual(input, target); + default: return traceResidual(input, target); + } +} + +/** 回溯全部数字叶子。顺序与 enumerateTargets 一致,脱离缓存重跑逐字相同。 */ +export function traceAll(input: TraceInput): TraceResult[] { + return enumerateTargets(input).map((t) => resolveTrace(input, t)); +} + +/** 汇总:供断言①与"说明与对照"页引用,数字一律现算。 */ +export function traceStats(results: TraceResult[]) { + const byKind = { event: 0, derived: 0, parameter: 0 }; + for (const r of results) byKind[r.kind] += 1; + const evidence = results.flatMap((r) => r.evidence); + const lineNos = evidence.map((e) => e.lineNo); + return { + total: results.length, + byKind, + wiredCount: results.filter((r) => r.wired).length, + /** 链路为空=血缘断裂,必须为 0 */ + emptyChainCount: results.filter((r) => r.chain.length === 0).length, + /** note 为空=让人猜为什么没有行号,必须为 0 */ + emptyNoteCount: results.filter((r) => r.note.length === 0).length, + evidenceCount: evidence.length, + /** 引用了不存在的原始行=假证据,必须为 0 */ + unmatchedEvidenceCount: evidence.filter((e) => !e.matchedRawLine).length, + nonPositiveLineNoCount: evidence.filter((e) => !(e.lineNo > 0)).length, + minLineNo: lineNos.length ? Math.min(...lineNos) : null, + maxLineNo: lineNos.length ? Math.max(...lineNos) : null, + /** derived/parameter 却标 wired=假绿,必须为 0 */ + falseWiredCount: results.filter((r) => r.wired && r.kind !== 'event').length, + /** event 却没证据=空口宣称贯通,必须为 0 */ + eventWithoutEvidenceCount: results.filter((r) => r.kind === 'event' && r.evidence.length === 0).length, + chainDepthMin: results.length ? Math.min(...results.map((r) => r.chain.length)) : 0, + detailRefs: uniq(results.map((r) => r.detailRef)), + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oeeAnswerEngine.ts b/src/modules/tfamd-oee/lib/oeeAnswerEngine.ts new file mode 100644 index 0000000..6fb3993 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oeeAnswerEngine.ts @@ -0,0 +1,1031 @@ +/** + * L3 规则引擎问答(建议书 §4.3 / §4.4)——A1–A4 一期智能体的应答编排。 + * + * ★ 默认纯规则引擎,不接大模型 / 网络(ADR:LLM 是增强项,不是前提)。 + * modelMode='llm' 时演示降级策略①:模型通道未接入 / 健康检查失败 → 规则引擎应答。 + * ★ 数字只来自五类受控工具(闸1)。本层把工具返回的 ServiceResult 当作唯一事实源, + * 结论草稿 draft.text 里**只允许出现 fact 派生的 ASCII 数字**;设备号 / 业务日 / 口径版本 / + * DQ 码 / 计数一律放进 source / evidence / metrics 等结构化字段(闸1 只校验 draft.text, + * 闸2 校验 ServiceResult 的出处三件)。这样既守住「数字无工具来源即拦」,又不让标识符误伤闸1。 + * ★ 分层:本文件在 L3(lib/,非 lib/oee/),可 import data 层与引擎;视图只消费本层输出。 + * 引擎纯函数(guards/skills/retrieval)经 oeeService 再导出,本层不直接 import lib/oee/*。 + */ +import { + createOeeTools, dayByDate, currentDay, blockedDay, deriveAlerts, traceDay, + taskFromCandidate, tryDispatch, advanceTask, + guardAnswer, guardDrill, GATE_LABEL, + skillAsk, skillCompare, skillAttribute, skillEstimate, skillSuggest, skillDispatch, skillReview, + retrieve, CHUNKS, OEE_AGENTS, agentById, + answerDayOf, knownDeviceIds, + type OeeTools, type OeeToolsDeps, +} from './oeeService'; +import { ANCHOR_DEVICE_ID, SEED_DATES, SEED_DIRTY_DATE, DEVICE_BY_ID } from '../data/oee/devices'; +import { PRIORITY_CANDIDATES } from '../data/oee/improvement'; +import { + BUCKET_LABEL, TASK_STATE_LABEL, type AnswerIntent, type AnswerDraft, type FourSectionAnswer, + type GuardResult, type ServiceResult, type ImprovementTask, type KnowledgeChunk, + type ScoredChunk, type LossBucket, +} from '../types/oee'; +import type { DrillLayer as GuardDrillLayer } from './oeeService'; + +/* ══════════════════════════════════════════════════════════════════ + * 一、跳转与回答卡契约(视图消费) + * ══════════════════════════════════════════════════════════════════ */ + +/** OEE 工作区页签(与 MetricWorkspace TabKey 同集合)。 */ +export type OeeTabKey = + | 'cockpit' | 'trend' | 'structure' | 'region' | 'risk' | 'detail' + | 'priority' | 'entry' | 'task' | 'master' | 'caliber' | 'integration' | 'disclosure'; + +/** 回答卡跳转:只送到能看到这张图 / 这条证据的地方,卡片本身不画图表。 */ +export type OeeJump = + | { kind: 'tab'; tab: OeeTabKey; label: string } + | { kind: 'ontology'; label: string } + | { kind: 'ask'; text: string; label: string }; + +export type OeeTone = 'danger' | 'warning' | 'success' | 'info'; +export interface OeeMetric { label: string; value: string; tone?: OeeTone } +export interface OeeTable { title: string; cols: string[]; rows: string[][] } +export interface OeePoint { label: string; text: string; tone?: OeeTone } +export interface OeeAction { label: string; jump?: OeeJump } +export interface OeeStep { act: string; detail: string } +/** RAG 引用:切片 id + 标题 + 语料 + 来源 + 命中分(出处强制,闸2 的延伸)。 */ +export interface OeeCitation { id: string; title: string; corpus: string; source: string; score: number } + +/** 降级策略(建议书 §4.3.5)。原型必须现场演示 ① 与 ③。 */ +export type DegradeKind = 'MODEL_UNAVAILABLE' | 'LOW_CONFIDENCE' | 'EVIDENCE_MISSING'; + +/** 一条完整回答:四段 + 结构化卡片 + 智能体归属 + 闸门 / 降级 / 停止元数据。 */ +export interface OeeAnswer { + agentId: 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7'; + agentName: string; + intent: AnswerIntent; + intentLabel: string; + severity: OeeTone; + four: FourSectionAnswer; + metrics: OeeMetric[]; + table?: OeeTable; + points: OeePoint[]; + actions: OeeAction[]; + citations: OeeCitation[]; + benefits?: { min: number; max: number; unit: string }[]; + steps: OeeStep[]; + /** 五道闸校验结果(ok=true 才发布;false 时 four 为拒绝 / 暂缓文案)。 */ + guard: GuardResult; + published: boolean; + /** 不取数的答复(范围外 / 时间或设备待确认):卡片据此显示中性标识,不挂“未发布”闸门横幅。 */ + halt?: 'OUT_OF_SCOPE' | 'UNRESOLVED_TIME'; + /** 技能停止条件命中(不猜、不补、不摊派)。 */ + stopped?: { skill: string; condition: string; action: string }; + degraded?: DegradeKind; + /** 该回答引用的业务日与口径版本(卡头展示,与顶栏同源)。 */ + bizDate: string; + caliberVersion: string; +} + +/* ══════════════════════════════════════════════════════════════════ + * 二、意图路由(规则 + 关键词,不用大模型) + * ══════════════════════════════════════════════════════════════════ */ + +export const INTENT_LABEL: Record = { + QUERY: '指标问数', DRILL: '血缘下钻', COMPARE: '同口径对比', ATTRIBUTE: '损失归因', + ESTIMATE: '经营测算', SUGGEST: '改善建议', DISPATCH: '任务派单', REVIEW: '闭环复盘', +}; + +/** 意图 → 一期智能体(A1–A4)。ESTIMATE 落 A7(三期,拒绝测算)。 */ +const INTENT_AGENT: Record = { + QUERY: 'A1', COMPARE: 'A1', DRILL: 'A2', ATTRIBUTE: 'A2', + SUGGEST: 'A3', DISPATCH: 'A4', REVIEW: 'A4', ESTIMATE: 'A7', +}; + +/** 每类意图触发词:口语与源表用语都收,命中最多者胜出;全不命中 → 不取数、明说可答范围。 + * ★ COMPARE 收单字「比」(如「和昨天比」):评分前先摘掉「占比/比例/百分比/比重」这类统计用语, + * 否则归因问句会被误判成对比。 */ +const KEYS: Record = { + QUERY: ['oee', '多少', '几', '指标', '达成', '问数', '查一下', '时间开动', '性能开动', '合格品率', '良率', 'a/p/q', '读数'], + DRILL: ['下钻', '明细', '行号', '血缘', '追溯', '哪一行', '日志', '时间轴', '状态段', '证据链', '怎么算出来'], + COMPARE: ['对比', '比较', '比', 'vs', '差异', '昨天', '前天', '环比', '两天', '顺序替代', 'δa', 'δp', 'δq', '比一比'], + ATTRIBUTE: ['为什么', '归因', '损失', '主因', '瓶颈', '帕累托', '哪类损失', '故障', '换型', '停机', '原因', '最伤', '压在哪'], + ESTIMATE: ['测算', '金额', '值多少', '钱', '产能换算', '费率', '收益多少', '折算'], + SUGGEST: ['建议', '怎么改', '改善', '对策', '措施', '案例', '怎么办', '优化', '有什么办法'], + DISPATCH: ['派单', '派发', '任务', '责任人', '工单', '闭环', '审核', '发给', '立项'], + REVIEW: ['复盘', '验证', '效果', '前后', '回验', '闭环效果', '改善后'], +}; + +export function matchedKeys(raw: string): string[] { + const q = raw.toLowerCase(); + return (Object.keys(KEYS) as AnswerIntent[]).reduce( + (acc, id) => acc.concat(KEYS[id].filter((k) => q.includes(k))), []); +} + +/** 对比评分用的问句预处理:摘掉统计用语里的「比」,避免「占比多少」命中 COMPARE。 */ +const stripRatioWords = (q: string): string => q.replace(/占比|比例|百分比|比重/g, ''); + +/** 意图路由:命中数胜出;同分时具体意图优先于 QUERY 兜底,再比命中词总长(长词更具体)。 */ +export function classifyIntent(raw: string): AnswerIntent { + const q = raw.toLowerCase(); + const order = Object.keys(KEYS) as AnswerIntent[]; + const score = (id: AnswerIntent): { n: number; len: number } => { + const src = id === 'COMPARE' ? stripRatioWords(q) : q; + const hits = KEYS[id].filter((k) => src.includes(k)); + return { n: hits.length, len: hits.reduce((a, k) => a + k.length, 0) }; + }; + let best: AnswerIntent = 'QUERY'; + let bestN = 0; + let bestLen = 0; + for (const id of order) { + const s = score(id); + if (s.n === 0) continue; + const better = s.n > bestN + || (s.n === bestN && best === 'QUERY' && id !== 'QUERY') + || (s.n === bestN && best !== 'QUERY' && id !== 'QUERY' && s.len > bestLen); + if (better) { best = id; bestN = s.n; bestLen = s.len; } + } + return best; +} + +/** 快捷问句:一句一个意图 / 智能体,点下去就是那场演示。 + * ★ 问句里不写「昨天」:相对日期会按问句实际解析(demo 昨日=09-02 为 DQ 阻断日), + * 快捷句应演示可发布读数,故直接问顶栏业务日。 */ +export const OEE_SUGGESTED: { text: string; agent: string }[] = [ + { text: 'DEK001 的 OEE 是多少,A/P/Q 各多少?', agent: '指标问数智能体' }, + { text: '损失主要压在哪一类,占比多少?', agent: '损失诊断智能体' }, + { text: '这个 OEE 数字能下钻到原始日志行号吗?', agent: '损失诊断智能体' }, + { text: '针对最大损失有什么改善建议,收益区间多少?', agent: '改善建议智能体' }, + { text: '把这条改善派单给责任人,四项必填齐了吗?', agent: '闭环跟踪智能体' }, + { text: '把 OEE 折算成金额收益。', agent: '经营测算智能体' }, +]; + +/* ══════════════════════════════════════════════════════════════════ + * 三、格式化(保证闸1:展示数字与 fact 同量纲、两位小数舍入在容差内) + * ══════════════════════════════════════════════════════════════════ */ + +/** 比例 → 百分数两位小数(舍入误差 ≤0.005 < 闸1 容差下限 0.01)。 */ +const pct = (v: number): string => `${(v * 100).toFixed(2)}%`; +/** 秒 → 分钟两位小数(factsContain 认 v÷60)。 */ +const min = (sec: number): string => `${(sec / 60).toFixed(2)} min`; +const toneOfOee = (v: number): OeeTone => (v >= 0.85 ? 'success' : v >= 0.7 ? 'warning' : 'danger'); + +/* ══════════════════════════════════════════════════════════════════ + * 四、应答上下文与工具构造 + * ══════════════════════════════════════════════════════════════════ */ + +export interface AnswerContext { + /** 五类受控工具(由调用方注入任务存储 / 时钟构造)。 */ + tools: OeeTools; + /** 当前业务日(顶栏筛选同源)。 */ + bizDate: string; + /** 顶栏当前设备(顶栏筛了单台时传入):问句没点名设备就跟它,不固定锚点。 */ + device?: string; + /** 模型增强开关:'rule' 默认纯规则;'llm' 演示降级①。 */ + modelMode: 'rule' | 'llm'; + /** 检索语料池,默认四语料 CHUNKS。 */ + pool?: KnowledgeChunk[]; +} + +/* ── 问句解析:设备 / 业务日。**只认明确说法,解析不了先反问,不猜默认值** ── */ + +/** 业务日平移(ISO 日期,UTC 无时区抖动)。 */ +function shiftIso(iso: string, days: number): string { + const d = new Date(`${iso}T00:00:00Z`); + d.setUTCDate(d.getUTCDate() + days); + return d.toISOString().slice(0, 10); +} + +/** 问句里点名的设备(台账 17 台 + 前端别名);没点名跟 ctx.device,缺省锚点。 */ +function parseDevice(raw: string, ctx: AnswerContext): string { + const up = raw.toUpperCase(); + const ids = knownDeviceIds().slice().sort((a, b) => b.length - a.length); + for (const id of ids) { + const token = id.toUpperCase().replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + if (new RegExp(`(^|[^A-Z0-9])${token}([^A-Z0-9]|$)`).test(up)) return id; + } + return ctx.device ?? ANCHOR_DEVICE_ID; +} + +/** 问句里的业务日(升序去重):显式 2026-07-14 / 7月14日,相对 今天/昨天/前天(基准=顶栏业务日)。 */ +function parseDates(raw: string, base: string): string[] { + const out: string[] = []; + const push = (d: string) => { if (/^\d{4}-\d{2}-\d{2}$/.test(d) && !out.includes(d)) out.push(d); }; + (raw.match(/20\d{2}-\d{1,2}-\d{1,2}/g) ?? []).forEach((d) => { + const [y, m, dd] = d.split('-'); + push(`${y}-${m.padStart(2, '0')}-${dd.padStart(2, '0')}`); + }); + for (const m of raw.match(/\d{1,2}\s*月\s*\d{1,2}\s*[日号]/g) ?? []) { + const mm = Number(m.match(/(\d{1,2})\s*月/)![1]); + const dd = Number(m.match(/月\s*(\d{1,2})/)![1]); + push(`${base.slice(0, 4)}-${String(mm).padStart(2, '0')}-${String(dd).padStart(2, '0')}`); + } + if (/今天|今日/.test(raw)) push(base); + if (/昨天|昨日/.test(raw)) push(shiftIso(base, -1)); + if (/前天/.test(raw)) push(shiftIso(base, -2)); + return out.sort(); +} + +/** 认得出是时间说法、但解析不成具体业务日 → 反问,不套用顶栏日期。 */ +const UNRESOLVED_TIME = /(上个?月|本月|下个?月|上个?周|上个?星期|本周|下周|本季度|上个?季度|去年|今年|第一季度|第二季度|第三季度|第四季度|最近\s*\d+\s*(天|日|周|月))/; + +export interface AskScope { device: string; dates: string[]; unresolvedTime: boolean } + +export function parseAsk(raw: string, ctx: AnswerContext): AskScope { + const dates = parseDates(raw, ctx.bizDate); + return { + device: parseDevice(raw, ctx), + dates, + unresolvedTime: dates.length === 0 && UNRESOLVED_TIME.test(raw), + }; +} + +/** 由依赖构造工具(视图 / hook 持有任务存储与时钟,L3 不藏模块级可变全局)。 */ +export function makeTools(deps: OeeToolsDeps): OeeTools { + return createOeeTools(deps); +} + +/** 模型网关(原型诚实:无端点)。modelMode='llm' 时返回 NO_ENDPOINT,触发降级①。 */ +function tryLlm(): { ok: false; reason: string } { + return { ok: false, reason: '模型通道未接入(NO_ENDPOINT)/ 健康检查失败' }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 五、四段装配 + 闸门 + 降级 + * ══════════════════════════════════════════════════════════════════ */ + +interface DraftBundle { + intent: AnswerIntent; + agentId: OeeAnswer['agentId']; + /** 受闸1 校验的结论草稿:只含 fact 派生 ASCII 数字。 */ + draft: AnswerDraft; + facts: ServiceResult[]; + evidence: string; + nextStep: string; + metrics: OeeMetric[]; + table?: OeeTable; + points: OeePoint[]; + actions: OeeAction[]; + citations: OeeCitation[]; + steps: OeeStep[]; + severity: OeeTone; + /** 本答指向的设备 / 业务日(问句点名优先;缺省由 answerOee 按顶栏补齐)。 */ + device?: string; + bizDate?: string; + /** 不取数的答复(问句不在可答范围 / 时间说法待确认):跳过数据闸门,照实说明。 */ + halt?: 'OUT_OF_SCOPE' | 'UNRESOLVED_TIME'; + /** 卡头意图标签覆盖(范围外 / 待确认问询没有对应的八意图,不硬套“指标问数”)。 */ + label?: string; + stopped?: OeeAnswer['stopped']; + degraded?: DegradeKind; + /** 下钻链(闸4 单独守)。 */ + drill?: GuardDrillLayer[]; +} + +/** 出处段:口径版本 + 业务日 + 来源 + 设备(标识符在此,不进 draft.text)。 + * 业务日一律取本答实际指向的业务日(问句点名或顶栏),不用操作时刻。 */ +function sourceLine(f: ServiceResult, device: string, bizDate: string): string { + const src = '演示种子(synthetic)'; + return `口径 ${f.caliberVersion} · 业务日 ${bizDate} · 来源 ${src} · ${device}`; +} + +/** 设备展示名:台账内带中文名,台账外设备只给 id,不硬凑名称。 */ +function deviceLabel(id: string): string { + const d = DEVICE_BY_ID[id]; + return d ? `${id} · ${d.name}` : id; +} + +/** + * 把草稿 bundle 过五道闸 + 降级,装配成最终四段回答。 + * 闸2/3 不过 → 不发布(拒绝 / 暂缓文案);闸1 不过 → 重生成一次(剔除无源数字); + * 闸5 不过 → 收益点值拒绝,只留区间说明;闸4 由 drill 链单独守。 + */ +function finalize(b: DraftBundle, ctx: AnswerContext): OeeAnswer { + const agent = agentById(b.agentId)!; + const device = deviceLabel(b.device ?? ctx.device ?? ANCHOR_DEVICE_ID); + const bizDate = b.bizDate ?? ctx.bizDate; + const primary = b.facts[0]; + const source = primary + ? sourceLine(primary, device, bizDate) + : `业务日 ${bizDate} · 无工具事实(本答未取数)`; + + /* 不取数的答复(问句不在可答范围 / 时间说法待确认):没有数据结论,就不走数据闸门, + 照实说明能答什么;不发布、不取数、不借闸门横幅伪装成“暂缓发布”。 */ + if (b.halt) { + return { + agentId: b.agentId, agentName: agent.name, intent: b.intent, intentLabel: b.label ?? INTENT_LABEL[b.intent], + severity: b.severity, + four: { + conclusion: b.draft.text, evidence: b.evidence, source, nextStep: b.nextStep, + answeredBy: 'RULE_ENGINE', + }, + metrics: [], points: b.points, actions: b.actions, citations: [], steps: b.steps, + guard: { ok: true }, published: false, stopped: b.stopped, halt: b.halt, + bizDate, caliberVersion: '', + }; + } + + /* 降级①:模型增强不可用 → 规则引擎应答(仍走全部闸门)。 */ + let degraded = b.degraded; + let degradedReason: string | undefined; + if (ctx.modelMode === 'llm') { + const llm = tryLlm(); + degraded = 'MODEL_UNAVAILABLE'; + degradedReason = `${llm.reason} → 规则引擎应答`; + } + + /* 闸4:下钻链完整性(独立于 guardAnswer)。 */ + let guard: GuardResult = { ok: true }; + if (b.drill) { + const g4 = guardDrill(b.drill); + if (!g4.ok) guard = g4; + } + /* 闸2→3→1→5。 */ + if (guard.ok) guard = guardAnswer(b.draft, b.facts); + + let conclusion = b.draft.text; + /* published = 过闸 且 非停止 / 缺口 / 低置信。后者是诚实的降级 / 拒绝响应(照实展示缺口与补录入口), + 但不作为「数据结论」发布。降级①(MODEL_UNAVAILABLE)仍是规则引擎的有效数据结论,照常发布。 + 用 b.degraded(builder 原意)判定,不用被 llm 模式覆写后的 degraded。 */ + let published = guard.ok && !b.stopped && b.degraded !== 'EVIDENCE_MISSING' && b.degraded !== 'LOW_CONFIDENCE'; + let evidence = b.evidence; + let nextStep = b.nextStep; + let benefits = b.draft.benefits; + + if (!guard.ok) { + const gate = guard.gate!; + const label = GATE_LABEL[gate]; + if (gate === 3) { + /* 跨版本对比:直接拒绝,不输出任何对比结论。 */ + conclusion = '拒绝对比:两个读数的口径版本不一致,跨版本拼装会误导决策。'; + evidence = guard.reason ?? ''; + nextStep = '请先在口径配置中心统一版本,或分别查看各自口径下的读数(不并列对比)。'; + published = false; + } else if (gate === 2) { + conclusion = '暂缓发布:出处三件(口径版本 / 时间范围 / 来源)不全,结论不可追溯。'; + evidence = guard.reason ?? ''; + nextStep = '补齐工具返回的出处字段后重生成(≤2 次);仍缺则转人工核对。'; + published = false; + } else if (gate === 4) { + conclusion = '停止下钻:证据链不全,无法贯通到原始日志行号。'; + evidence = guard.reason ?? ''; + nextStep = '按缺失环节到录入台补录(5M1E),证据到位后再下钻;当前转人工。'; + published = false; + degraded = degraded ?? 'EVIDENCE_MISSING'; + degradedReason = degradedReason ?? '证据缺失 → 列出缺口 + 补录入口(降级③)'; + } else if (gate === 5) { + conclusion = '收益拒绝点值:预估收益必须给区间,单点数字会被当作承诺。'; + evidence = guard.reason ?? ''; + nextStep = '改用 {min,max} 区间并标注「预估·待 IE 签字」后重生成。'; + benefits = undefined; + published = false; + } else { + /* 闸1:数字无工具来源 → 重生成(剔除无源数字,保留有源部分)。 */ + conclusion = '已重生成:原结论含无工具来源的数字,按闸1 拦下并剔除。'; + evidence = guard.reason ?? ''; + nextStep = '所有数字必须经五类受控工具取得;如仍缺数,转人工核对工具返回。'; + published = false; + } + void label; + } + + /* 降级②:低置信 → 只报损失结构,不下真因结论(由 builder 标 degraded,这里补文案)。 */ + if (degraded === 'LOW_CONFIDENCE' && published) { + degradedReason = degradedReason ?? '证据不足 / 低置信 → 只报损失结构,不下真因结论(降级②)'; + } + + const four: FourSectionAnswer = { + conclusion, evidence, source, nextStep, + answeredBy: 'RULE_ENGINE', + degradedReason, + }; + + return { + agentId: b.agentId, agentName: agent.name, intent: b.intent, intentLabel: b.label ?? INTENT_LABEL[b.intent], + severity: b.severity, four, metrics: b.metrics, table: b.table, points: b.points, + actions: b.actions, citations: b.citations, benefits, steps: b.steps, + guard, published, stopped: b.stopped, degraded, + bizDate, + caliberVersion: primary?.caliberVersion ?? '', + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 六、各意图应答 builder(数字一律来自工具) + * ══════════════════════════════════════════════════════════════════ */ + +const stepParse = (raw: string, intent: AnswerIntent): OeeStep => ({ + act: '解析问句', + detail: `命中关键词 [${matchedKeys(raw).join('、') || '无'}] → 意图「${INTENT_LABEL[intent]}」(规则路由,不用大模型)`, +}); + +/** A1 问数:三要素(设备 + 时间 + 指标)齐 → 取数;缺 → 先反问(SK1 停止条件)。 + * 设备/业务日按问句解析(点名优先,没点名跟顶栏),解析不了由 answerOee 先反问,不猜。 */ +async function buildQuery(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const device = scope.device; + const bizDate = scope.dates[0] ?? ctx.bizDate; + const ask = skillAsk({ device, timeRange: bizDate, metric: 'OEE' }); + const steps: OeeStep[] = [stepParse(raw, 'QUERY'), + { act: '校验三要素', detail: `设备 ${device} · 业务日 ${bizDate} · 指标 OEE/A/P/Q(SK1:三要素不全先反问)` + + (scope.dates.length > 0 ? ';业务日取自问句' : ';业务日跟顶栏') }]; + if (ask.stopped) { + return { ...stoppedBundle('QUERY', 'A1', ask, steps, ctx), device, bizDate }; + } + const fact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate }); + steps.push({ act: '工具取数', detail: `TL1 queryMetric(${device} · ${bizDate}) → ServiceResult(口径 ${fact.caliberVersion} · 来源 ${fact.source})` }); + const r = fact.data; + if (fact.gap || r.blocked) { + /* 未接入 / 阻断:不显示数字,照实给缺口(降级③)。 */ + steps.push({ act: '范围校验', detail: fact.gap ?? '当日 DQ 阻断,结论暂缓发布' }); + return { + intent: 'QUERY', agentId: 'A1', device, bizDate, + draft: { intent: 'QUERY', text: '该范围当前无可发布读数,不显示数字也不显示零。' }, + facts: [fact], evidence: fact.gap ?? '当日数据质量阻断(DQ-06),结论暂缓发布。', + nextStep: '到数据质量台查看阻断项,或到录入台补录后重算。', + metrics: [], points: [{ label: '缺口', text: fact.gap ?? 'DQ 阻断', tone: 'warning' }], + actions: [{ label: '查看数据质量台', jump: { kind: 'tab', tab: 'risk', label: '数据质量台' } }, + { label: '去录入台补录', jump: { kind: 'tab', tab: 'entry', label: '手工录入台' } }], + citations: [], steps, severity: 'warning', degraded: 'EVIDENCE_MISSING', + }; + } + const a = r.tiers.actual; + steps.push({ act: '套口径', detail: `三层共用分母 PPT = CT − PDT;实际档 A×P×Q(${r.template} 模板)` }); + steps.push({ act: '过五道闸', detail: '闸2 出处三件 → 闸1 数字只来自工具 → 闸5 收益区间(本答无收益)' }); + const draft: AnswerDraft = { + intent: 'QUERY', + text: `实际档 OEE ${pct(a.oee)}(时间开动率 ${pct(a.a)} × 性能开动率 ${pct(a.p)} × 合格品率 ${pct(a.q)})。`, + }; + return { + intent: 'QUERY', agentId: 'A1', draft, facts: [fact], device, bizDate, + evidence: `理论档 OEE ${pct(r.tiers.theoretical.oee)}、计划档 ${pct(r.tiers.planned.oee)}、实际档 ${pct(a.oee)};` + + `计划时间 PPT ${min(r.pptSec)}(日历时间 CT ${min(r.ctSec)} − 计划停机 PDT ${min(r.pdtSec)})。` + + `残差 ${r.residualSec.toFixed(2)} 秒(须为 0),未归因占比 ${pct(r.unattributedPct)}。`, + nextStep: '可继续下钻到行号,或问损失主因;口径切换请到配置中心(跨版本对比会被拒绝)。', + metrics: [ + { label: '实际 OEE', value: pct(a.oee), tone: toneOfOee(a.oee) }, + { label: '时间开动率 A', value: pct(a.a) }, + { label: '性能开动率 P', value: pct(a.p) }, + { label: '合格品率 Q', value: pct(a.q) }, + ], + table: { + title: '三层 OEE(共用分母 PPT)', cols: ['档位', 'A', 'P', 'Q', 'OEE'], + rows: [ + ['理论档', pct(r.tiers.theoretical.a), pct(r.tiers.theoretical.p), pct(r.tiers.theoretical.q), pct(r.tiers.theoretical.oee)], + ['计划档', pct(r.tiers.planned.a), pct(r.tiers.planned.p), pct(r.tiers.planned.q), pct(r.tiers.planned.oee)], + ['实际档', pct(a.a), pct(a.p), pct(a.q), pct(a.oee)], + ], + }, + points: [{ label: '口径', text: `C27/C28 待 IE 签字,附录 E 默认值生效;P0 项标灰不标绿。`, tone: 'warning' }], + actions: [{ label: '看总览看板', jump: { kind: 'tab', tab: 'cockpit', label: '总览' } }, + { label: '下钻到行号', jump: { kind: 'ask', text: '这个 OEE 数字能下钻到原始日志行号吗?', label: '下钻' } }], + citations: [], steps, severity: toneOfOee(a.oee), + }; +} + +/** A2 归因:六桶 Pareto + 顺序替代;残差≠0 或证据缺 → 只报缺口(SK4 停止条件)。 */ +async function buildAttribute(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const bizDate = scope.dates[0] ?? ctx.bizDate; + const fact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: scope.device, bizDate }); + const r = fact.data; + const steps: OeeStep[] = [stepParse(raw, 'ATTRIBUTE'), + { act: '工具取数', detail: `TL1 queryMetric(${scope.device} · ${bizDate}) → 六桶 + 三档 + 残差` }, + { act: '六桶 Pareto', detail: '按占计划时间比降序,定位 Top1 损失桶' }]; + const ranked = [...r.buckets].sort((x, y) => y.pctOfPlanTime - x.pctOfPlanTime); + const top = ranked[0]; + const evidenceComplete = !fact.gap && !r.blocked && Math.abs(r.residualSec) < 1e-9; + const attr = skillAttribute({ confidence: evidenceComplete ? 0.92 : 0.4, residualSec: r.residualSec, evidenceComplete }); + if (attr.stopped) { + steps.push({ act: '归因闸门', detail: attr.condition }); + /* 低置信 / 残差≠0:只报损失结构,不下真因结论(降级②)。 */ + return { + intent: 'ATTRIBUTE', agentId: 'A2', device: scope.device, bizDate, + draft: { intent: 'ATTRIBUTE', text: '证据不足,以下仅为损失结构,不下真因结论。' }, + facts: [fact], + evidence: `残差 ${r.residualSec.toFixed(2)} 秒、未归因占比 ${pct(r.unattributedPct)};` + + (r.blocked ? '当日 DQ 阻断,结论暂缓。' : '置信度低于阈值,转工程师人工归因。'), + nextStep: '到录入台补录未归因段(5M1E),残差归零后再下真因结论。', + metrics: ranked.slice(0, 3).map((b) => ({ label: BUCKET_LABEL[b.bucket], value: pct(b.pctOfPlanTime), tone: 'warning' as OeeTone })), + points: [{ label: '停止条件', text: attr.condition, tone: 'warning' }], + actions: [{ label: '看损失结构', jump: { kind: 'tab', tab: 'structure', label: '损失结构' } }, + { label: '去录入台', jump: { kind: 'tab', tab: 'entry', label: '手工录入台' } }], + citations: [], steps, severity: 'warning', stopped: { skill: '归因', condition: attr.condition, action: attr.action }, + degraded: 'LOW_CONFIDENCE', + }; + } + steps.push({ act: '顺序替代', detail: 'ΔA→ΔP→ΔQ 固定顺序分解计划档→实际档差异' }); + steps.push({ act: '过五道闸', detail: '闸1 数字只来自工具;闸2 出处三件齐' }); + const d = r.delta; + const draft: AnswerDraft = { + intent: 'ATTRIBUTE', + text: top + ? `最大损失为${BUCKET_LABEL[top.bucket]},占计划时间 ${pct(top.pctOfPlanTime)}(${min(top.durationSec)})。` + : '当日六桶损失均为零。', + }; + return { + intent: 'ATTRIBUTE', agentId: 'A2', draft, facts: [fact], device: scope.device, bizDate, + evidence: (d ? `顺序替代分解:ΔA ${pct(d.dA)}、ΔP ${pct(d.dP)}、ΔQ ${pct(d.dQ)},合计 ${pct(d.total)}。` : '') + + `未归因占比 ${pct(r.unattributedPct)},残差 ${r.residualSec.toFixed(2)} 秒。`, + nextStep: '可下钻该桶到事件 / 行号,或问改善建议(匹配历史案例)。', + metrics: ranked.slice(0, 4).map((b) => ({ label: BUCKET_LABEL[b.bucket], value: pct(b.pctOfPlanTime), tone: b.bucket === top?.bucket ? 'danger' as OeeTone : undefined })), + table: { + title: '六大损失桶(占计划时间 PPT)', cols: ['损失桶', '因子', '时长', '占比'], + rows: ranked.map((b) => [BUCKET_LABEL[b.bucket], b.factor, min(b.durationSec), pct(b.pctOfPlanTime)]), + }, + points: [{ label: '真因实体', text: `候选真因挂五实体之一(设备 / 模具工装 / 物料批次 / 人员班组 / 程序参数),不并列多个首要真因。` }], + actions: [{ label: '看损失结构', jump: { kind: 'tab', tab: 'structure', label: '损失结构' } }, + { label: '问改善建议', jump: { kind: 'ask', text: '针对最大损失有什么改善建议,收益区间多少?', label: '建议' } }], + citations: [], steps, severity: 'danger', + }; +} + +/** A2 下钻:detailRef → 因子 → 状态段 → 事件 → 行号;任一层缺证据即停(SK2 / 闸4)。 */ +async function buildDrill(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const device = scope.device; + const bizDate = scope.dates[0] ?? ctx.bizDate; + const day = await answerDayOf(device, bizDate); + const steps: OeeStep[] = [stepParse(raw, 'DRILL'), + { act: '工具取数', detail: `TL2 queryTimeline(${device} · ${bizDate}) → 状态段;TL1 queryMetric → detailRef` }]; + const metricFact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate }); + const tlFact = await ctx.tools.queryTimeline({ device, bizDate, page: 1, pageSize: 200 }); + if (!day) { + const reason = metricFact.gap ?? tlFact.gap ?? `${device} ${bizDate} 无可下钻日结果`; + const layers: GuardDrillLayer[] = [{ layer: '业务日结果', hasEvidence: false, missing: [reason] }]; + return { + intent: 'DRILL', agentId: 'A2', device, bizDate, + draft: { intent: 'DRILL', text: '停止下钻:该设备当日无日结果,证据链起点缺失。' }, + facts: [metricFact, tlFact], evidence: reason, + nextStep: '换有后端日结果的设备/业务日再下钻,或先到数据集总览核对覆盖日。', metrics: [], points: [], actions: [], + citations: [], steps, severity: 'warning', drill: layers, degraded: 'EVIDENCE_MISSING', + }; + } + const traces = traceDay(day); + const oeeTrace = traces.find((t) => t.target.key === 'tier:actual.oee') ?? traces[0]; + /* 逐层证据:detailRef → 因子 → 状态段 → 事件 → 行号。wired 且每条证据对账成功才算贯通。 */ + const layers: GuardDrillLayer[] = [ + { layer: 'detailRef 句柄', hasEvidence: !!oeeTrace?.detailRef }, + { layer: '因子 / 状态段', hasEvidence: (oeeTrace?.segmentIds.length ?? 0) > 0 || oeeTrace?.kind !== 'event' }, + { layer: '事件实例', hasEvidence: oeeTrace?.kind === 'event' ? oeeTrace.eventIds.length > 0 : true }, + { layer: '原始日志行号', hasEvidence: oeeTrace?.wired ?? false, missing: oeeTrace?.wired ? undefined : ['该数字为 derived/parameter,无成对事件行号'] }, + ]; + const g4 = guardDrill(layers); + steps.push({ act: '逐层回溯', detail: `detailRef → 因子 → 状态段 → 事件 → 行号;wired=${oeeTrace?.wired ?? false}` }); + steps.push({ act: '闸4 证据链', detail: g4.ok ? '全链贯通到行号' : g4.reason ?? '' }); + const seg = tlFact.data; + const draft: AnswerDraft = { + intent: 'DRILL', + text: g4.ok + ? `已贯通到原始日志行号,当日状态段共 ${seg.total} 段。` + : '停止下钻:证据链不全,列出缺失环节并转人工。', + }; + return { + intent: 'DRILL', agentId: 'A2', draft, facts: [metricFact, tlFact], device, bizDate, + evidence: oeeTrace + ? `目标「${oeeTrace.target.label}」链路:${oeeTrace.chain.join(' → ')};` + + (oeeTrace.evidence[0] ? `行号 L${oeeTrace.evidence[0].lineNo}(${oeeTrace.evidence[0].filePath})。` : oeeTrace.note) + : '无可回溯目标。', + nextStep: g4.ok ? '可在设备时间轴页查看逐段状态与事件证据。' : '按缺失环节到录入台补录后重试(降级③)。', + metrics: [{ label: '状态段总数', value: `${seg.total}`, tone: 'info' }, + { label: '全链贯通', value: oeeTrace?.wired ? '是' : '否', tone: oeeTrace?.wired ? 'success' : 'warning' }], + table: { + title: '证据链逐层(闸4)', cols: ['层级', '证据', '缺失环节'], + rows: layers.map((l) => [l.layer, l.hasEvidence ? '✓' : '✗', l.missing?.join('、') ?? '—']), + }, + points: [], + actions: [{ label: '看设备时间轴', jump: { kind: 'tab', tab: 'detail', label: '时间轴' } }, + ...(g4.ok ? [] : [{ label: '去录入台补录', jump: { kind: 'tab' as const, tab: 'entry' as OeeTabKey, label: '手工录入台' } }])], + citations: [], steps, severity: g4.ok ? 'success' : 'warning', drill: layers, + degraded: g4.ok ? undefined : 'EVIDENCE_MISSING', + }; +} + +/** 找 d 之前最近一个「可发布」业务日(有日结果且未 DQ 阻断,默认回溯 14 天)。 + * 阻断日读数不并列下结论,跳过;对比两日都阻断时放宽窗口找最近可发布日; + * 全阻断/无结果 → undefined,由调用方反问。 */ +async function previousAnswerableDate(device: string, d: string, limitDays = 14): Promise { + for (let i = 1; i <= limitDays; i += 1) { + const iso = shiftIso(d, -i); + const day = await answerDayOf(device, iso); + if (day && !day.dq.blocked) return iso; + } + return undefined; +} + +/** A1 对比:同口径两日顺序替代;口径版本不同 → 闸3 直接拒绝(SK3)。 + * ★ 对比日按问句解析:点名两日取该两日;只点名一日(「和昨天比」)与顶栏业务日比; + * 没点名则顶栏业务日 vs 其前一可算日。时间说法解析不了 → 反问,不套默认。 */ +async function buildCompare(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const device = scope.device; + const steps: OeeStep[] = [stepParse(raw, 'COMPARE')]; + if (scope.dates.length > 2) { + return { + ...haltBundle({ + kind: 'UNRESOLVED_TIME', label: '待确认时间', agentId: 'A1', device, + text: '问句里出现了多个业务日,请明确要对比的两天。', steps, + evidence: `解析到业务日 ${scope.dates.join('、')};同口径对比一次只看两天。`, + nextStep: '改写为「2026-09-08 和 2026-09-09 比一下」这类明确两日的问法。', + }), + }; + } + let d1: string | undefined; + let d2: string; + if (scope.dates.length === 2) { + [d1, d2] = scope.dates; + } else if (scope.dates.length === 1) { + /* 「和昨天比」只点名一日:与顶栏业务日比;顶栏就是那天,则与它的前一可算日比。 */ + const other = ctx.bizDate !== scope.dates[0] ? ctx.bizDate : await previousAnswerableDate(device, scope.dates[0]); + if (!other) { + return { + ...haltBundle({ + kind: 'UNRESOLVED_TIME', label: '待确认时间', agentId: 'A1', device, bizDate: scope.dates[0], + text: `只点名了 ${scope.dates[0]},且它之前没有可算日,无法对比。`, steps, + evidence: `${device} 回溯 14 天无后端日结果;不拿别的日期顶替。`, + nextStep: '请点名另一个有数据的业务日,或先在数据集总览核对覆盖日。', + }), + }; + } + [d1, d2] = [scope.dates[0], other].sort(); + steps.push({ act: '补齐对比日', detail: `问句只点名 ${scope.dates[0]}:与 ${other === ctx.bizDate ? '顶栏业务日' : '前一可算日'} ${other} 对比` }); + } else { + d2 = ctx.bizDate; + d1 = await previousAnswerableDate(device, d2); + if (!d1) { + return { + ...haltBundle({ + kind: 'UNRESOLVED_TIME', label: '待确认时间', agentId: 'A1', device, bizDate: d2, + text: `${deviceLabel(device)} 在 ${d2} 之前没有可算日,无法对比。`, steps, + evidence: `${device} 回溯 14 天无后端日结果;不拿别的日期顶替。`, + nextStep: '请点名另一个有数据的业务日,或先在数据集总览核对覆盖日。', + }), + }; + } + steps.push({ act: '补齐对比日', detail: `问句没点名业务日:顶栏 ${d2} vs 其前最近有结果的 ${d1}` }); + } + steps.push({ act: '取两日读数', detail: `TL1 queryMetric(${device} · ${d1} / ${d2})` }); + const f1 = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate: d1 }); + const f2 = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate: d2 }); + if (f1.gap || f2.gap) { + const bad = [f1.gap ? d1 : null, f2.gap ? d2 : null].filter(Boolean).join(' / '); + const reason = [[f1.gap ? d1 : null, f1.gap], [f2.gap ? d2 : null, f2.gap]] + .filter(([d]) => !!d).map(([d, g]) => `${d}:${g}`).join(';'); + steps.push({ act: '范围校验', detail: `${bad} 无可发布读数:${reason}` }); + /* 两日都被 DQ 阻断才是「整段窗口不可用」:往前找最近可发布日(日期来自实际回溯,不写死)。 */ + const bothBlocked = !!f1.gap && !!f2.gap && /DQ/.test(f1.gap) && /DQ/.test(f2.gap); + const nearest = bothBlocked ? await previousAnswerableDate(device, d1, 60) : undefined; + if (nearest) steps.push({ act: '找最近可发布日', detail: `两日均 DQ 阻断,往前回溯至 ${nearest}` }); + const points: OeePoint[] = nearest + ? [{ label: '最近可发布日', text: `${nearest}:两日均 DQ 阻断后,往前最近一天有可发布读数`, tone: 'info' }, + { label: '缺口', text: reason, tone: 'warning' }] + : [{ label: '缺口', text: reason, tone: 'warning' }]; + const actions: OeeAction[] = [ + ...(nearest + ? [{ label: `看 ${nearest} 的可发布读数`, jump: { kind: 'ask' as const, text: `${device} ${nearest} 的 OEE 是多少`, label: '最近可发布日' } }] + : []), + { label: '查看数据质量台', jump: { kind: 'tab' as const, tab: 'risk' as const, label: '数据质量台' } }, + ]; + return { + intent: 'COMPARE', agentId: 'A1', device, bizDate: f1.gap ? d1 : d2, + draft: { intent: 'COMPARE', text: bothBlocked + ? '两日均无可发布读数(DQ 阻断),不并列下结论,也不显示零。' + : '其中一日无可发布读数(无后端日结果或 DQ 阻断),不并列下结论,也不显示零。' }, + facts: [f1, f2], evidence: reason, + nextStep: nearest + ? `两日均 DQ 阻断:可先看最近可发布日 ${nearest},或到数据质量台核对阻断原因。` + : '核对两日是否都在覆盖范围内,或换有后端日结果的业务日再比。', + metrics: [], points, actions, + citations: [], steps, severity: 'warning', degraded: 'EVIDENCE_MISSING', + }; + } + const cmp = skillCompare(f1, f2); + steps.push({ act: '口径校验', detail: `版本 ${f1.caliberVersion} vs ${f2.caliberVersion}(SK3:不同即拒绝)` }); + if (cmp.stopped) { + return { + intent: 'COMPARE', agentId: 'A1', device, bizDate: d2, + draft: { intent: 'COMPARE', text: '拒绝对比:口径版本不一致。' }, + facts: [f1, f2], evidence: cmp.condition, nextStep: cmp.action, + metrics: [], points: [{ label: '闸3', text: cmp.condition, tone: 'danger' }], + actions: [{ label: '口径配置中心', jump: { kind: 'tab', tab: 'caliber', label: '配置中心' } }], + citations: [], steps, severity: 'danger', stopped: { skill: '对比', condition: cmp.condition, action: cmp.action }, + }; + } + const o1 = f1.data.tiers.actual.oee; + const o2 = f2.data.tiers.actual.oee; + const diff = o2 - o1; + steps.push({ act: '过五道闸', detail: '闸3 同版本通过 → 闸1 数字只来自工具' }); + /* 闸1:draft.text 只放两日 OEE(各自 fact 里有);环比差值是派生量、口径版本含数字, + 都放 metrics / evidence,不进结论叙述(标识符与版本号会误伤闸1)。 */ + const draft: AnswerDraft = { + intent: 'COMPARE', + text: `两日实际 OEE 分别为 ${pct(o1)} 与 ${pct(o2)}。`, + }; + return { + intent: 'COMPARE', agentId: 'A1', draft, facts: [f1, f2], device, bizDate: d2, + evidence: `同口径 ${f1.caliberVersion};顺序替代分解见各自当日 ΔA/ΔP/ΔQ。跨版本拼装一律拒绝(闸3)。`, + nextStep: '可分别下钻两日损失结构,定位环比变化主因。', + metrics: [{ label: `${d1} OEE`, value: pct(o1) }, { label: `${d2} OEE`, value: pct(o2) }, + { label: '环比', value: `${diff >= 0 ? '+' : ''}${pct(diff)}`, tone: diff >= 0 ? 'success' : 'danger' }], + points: [], + actions: [{ label: '看趋势', jump: { kind: 'tab', tab: 'trend', label: '趋势' } }], + citations: [], steps, severity: diff >= 0 ? 'success' : 'warning', + }; +} + +/** A3 建议:检索 CASE 语料 → 建议清单 + 收益区间;无匹配案例 → 标无历史依据(SK6)。 */ +async function buildSuggest(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const device = scope.device; + const bizDate = scope.dates[0] ?? ctx.bizDate; + const fact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate }); + const r = fact.data; + const top = [...r.buckets].sort((x, y) => y.pctOfPlanTime - x.pctOfPlanTime)[0]; + const pool = ctx.pool ?? CHUNKS; + const query = top ? `${BUCKET_LABEL[top.bucket]} 改善 对策 案例` : 'OEE 改善 案例'; + const hits: ScoredChunk[] = retrieve(query, 4, { corpus: 'CASE' }, pool); + const steps: OeeStep[] = [stepParse(raw, 'SUGGEST'), + { act: '工具取数', detail: 'TL1 queryMetric → 最大损失桶' }, + { act: '向量检索', detail: `retrieve(CASE, k=4) → 命中 ${hits.length} 条(本地 TF-IDF 余弦,零依赖;生产换 Milvus 签名不变)` }]; + const sug = skillSuggest({ cases: hits, evidenceComplete: !fact.gap && !r.blocked }); + if (sug.stopped) { + return { + intent: 'SUGGEST', agentId: 'A3', device, bizDate, + draft: { intent: 'SUGGEST', text: '无匹配历史案例,标「无历史依据」,不编收益。' }, + facts: [fact], evidence: sug.condition, nextStep: sug.action, + metrics: [], points: [{ label: '停止条件', text: sug.condition, tone: 'warning' }], + actions: [{ label: '看优先清单', jump: { kind: 'tab', tab: 'priority', label: '优先清单' } }], + citations: [], steps, severity: 'warning', stopped: { skill: '建议', condition: sug.condition, action: sug.action }, + }; + } + const candidateOnly = !sug.stopped && sug.value.candidateOnly; + /* 收益给区间(闸5):min≠max,标注预估·待 IE 签字。数字不进 draft.text(闸1 只守结论叙述)。 */ + const benefits = top && top.pctOfPlanTime > 0 + ? [{ min: Math.round(top.pctOfPlanTime * 100 * 0.3 * 100) / 100, max: Math.round(top.pctOfPlanTime * 100 * 0.6 * 100) / 100, unit: 'OEE 百分点(预估·待 IE 签字)' }] + : undefined; + steps.push({ act: '过五道闸', detail: '闸5 收益给区间(min≠max);闸2 出处三件齐' }); + const draft: AnswerDraft = { + intent: 'SUGGEST', + text: candidateOnly + ? '证据链不全,以下建议只作候选,不进派单;收益以区间给出。' + : '已生成改善建议清单,收益以区间给出,待 IE 签字后派发。', + benefits, + }; + const citations: OeeCitation[] = hits.map((h) => ({ id: h.chunk.id, title: h.chunk.title, corpus: h.chunk.corpus, source: h.chunk.source, score: h.score })); + return { + intent: 'SUGGEST', agentId: 'A3', draft, facts: [fact], device, bizDate, + evidence: top ? `针对最大损失「${BUCKET_LABEL[top.bucket]}」(占计划时间 ${pct(top.pctOfPlanTime)})匹配历史案例。` : '按损失结构匹配案例。', + nextStep: candidateOnly ? '补齐证据链后建议方可进派单(闸4 / SK6)。' : '可在优先清单生成任务,补齐四项必填后派发。', + metrics: top ? [{ label: '目标损失', value: BUCKET_LABEL[top.bucket] }, { label: '占计划时间', value: pct(top.pctOfPlanTime), tone: 'danger' }] : [], + points: hits.map((h) => ({ label: h.chunk.title, text: `${h.chunk.text.slice(0, 60)}…(来源:${h.chunk.source})` })), + actions: [{ label: '看优先清单', jump: { kind: 'tab', tab: 'priority', label: '优先清单' } }, + { label: '生成派单', jump: { kind: 'ask', text: '把这条改善派单给责任人,四项必填齐了吗?', label: '派单' } }], + citations, steps, severity: candidateOnly ? 'warning' : 'info', + stopped: candidateOnly ? { skill: '建议', condition: '证据链不全', action: '只作候选,不进派单' } : undefined, + }; +} + +/** A4 派单:四项必填齐 → 可派发;缺 → canDispatch=false 拒绝(SK7 / 闸9)。 */ +async function buildDispatch(raw: string, ctx: AnswerContext, tasks: ImprovementTask[]): Promise { + const steps: OeeStep[] = [stepParse(raw, 'DISPATCH'), + { act: '查任务', detail: 'TL3 manageTask(QUERY) → 待审核任务' }]; + const pending = tasks.find((t) => t.state === 'PENDING_REVIEW') ?? tasks[0]; + if (!pending) { + return { + intent: 'DISPATCH', agentId: 'A4', + draft: { intent: 'DISPATCH', text: '当前无待审核任务,先在优先清单生成任务。' }, + facts: [], evidence: '任务存储为空。', nextStep: '到优先清单由候选生成待审核任务。', + metrics: [], points: [], actions: [{ label: '看优先清单', jump: { kind: 'tab', tab: 'priority', label: '优先清单' } }], + citations: [], steps, severity: 'info', + }; + } + const disp = skillDispatch(pending); + const fact = await ctx.tools.manageTask({ op: 'QUERY', taskId: pending.id }); + steps.push({ act: '四项必填闸', detail: disp.stopped ? disp.condition : '责任人 / 期限 / 收益区间 / 验证结果齐备' }); + if (disp.stopped) { + return { + intent: 'DISPATCH', agentId: 'A4', + draft: { intent: 'DISPATCH', text: '拒绝派发:四项必填不全,任务停在待审核。' }, + facts: [fact], evidence: disp.condition, nextStep: disp.action, + metrics: [{ label: '任务状态', value: TASK_STATE_LABEL[pending.state], tone: 'warning' }], + points: [{ label: '缺项', text: disp.condition, tone: 'danger' }], + actions: [{ label: '去录入台补齐', jump: { kind: 'tab', tab: 'entry', label: '手工录入台' } }], + citations: [], steps, severity: 'warning', stopped: { skill: '派单', condition: disp.condition, action: disp.action }, + }; + } + steps.push({ act: '过闸门', detail: '闸9 四项必填通过 → 待审核→已派发(无 approveTask,智能体不代签核)' }); + return { + intent: 'DISPATCH', agentId: 'A4', + draft: { intent: 'DISPATCH', text: '四项必填齐备,任务可由待审核推进到已派发。' }, + facts: [fact], + evidence: `任务「${pending.title}」责任人 ${pending.owner ?? '—'}、期限 ${pending.dueDate ?? '—'};审核通过按钮仅 IE / 主管角色可见,智能体无此权限。`, + nextStep: '在录入台 / 任务中心点击派发;派发后 SLA 开始计时。', + metrics: [{ label: '任务状态', value: TASK_STATE_LABEL[pending.state], tone: 'info' }, + { label: '优先级分', value: pending.priorityScore.toFixed(3) }], + points: [], actions: [{ label: '去任务中心', jump: { kind: 'tab', tab: 'task', label: '任务中心' } }], + citations: [], steps, severity: 'success', + }; +} + +/** A4 复盘:前后同口径 + 验证结果;缺验证 → 标待复核(SK8)。 */ +async function buildReview(raw: string, ctx: AnswerContext, tasks: ImprovementTask[]): Promise { + const steps: OeeStep[] = [stepParse(raw, 'REVIEW'), + { act: '查已闭环任务', detail: 'TL3 manageTask(QUERY) → 已验证 / 已归档任务' }]; + const done = tasks.find((t) => t.state === 'VERIFIED' || t.state === 'ARCHIVED'); + const scope = parseAsk(raw, ctx); + const device = scope.device; + const bizDate = scope.dates[0] ?? ctx.bizDate; + const fact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate }); + if (!done) { + const rev = skillReview({ beforeVersion: fact.caliberVersion, afterVersion: fact.caliberVersion, verificationResult: undefined }); + return { + intent: 'REVIEW', agentId: 'A4', device, bizDate, + draft: { intent: 'REVIEW', text: '暂无已闭环任务,或验证结果缺失,标待复核。' }, + facts: [fact], evidence: rev.stopped ? rev.condition : '无已验证任务。', + nextStep: rev.stopped ? rev.action : '任务完成并录入验证结果后再复盘。', + metrics: [], points: [{ label: '停止条件', text: rev.stopped ? rev.condition : '无已闭环任务', tone: 'warning' }], + actions: [{ label: '看任务中心', jump: { kind: 'tab', tab: 'task', label: '任务中心' } }], + citations: [], steps, severity: 'warning', + stopped: rev.stopped ? { skill: '复盘', condition: rev.condition, action: rev.action } : undefined, + }; + } + const rev = skillReview({ beforeVersion: fact.caliberVersion, afterVersion: fact.caliberVersion, verificationResult: done.verificationResult }); + steps.push({ act: '复盘闸门', detail: rev.stopped ? rev.condition : '前后同口径 + 验证结果齐备' }); + if (rev.stopped) { + return { + intent: 'REVIEW', agentId: 'A4', device, bizDate, + draft: { intent: 'REVIEW', text: '拒绝复盘:前后期口径版本不同或验证结果缺失。' }, + facts: [fact], evidence: rev.condition, nextStep: rev.action, + metrics: [], points: [{ label: '停止条件', text: rev.condition, tone: 'danger' }], + actions: [], citations: [], steps, severity: 'danger', + stopped: { skill: '复盘', condition: rev.condition, action: rev.action }, + }; + } + return { + intent: 'REVIEW', agentId: 'A4', device, bizDate, + draft: { intent: 'REVIEW', text: '前后同口径且验证结果齐备,可输出效果对比。' }, + facts: [fact], + evidence: `任务「${done.title}」验证结果:${done.verificationResult ?? '—'};口径 ${fact.caliberVersion}。`, + nextStep: '效果对比与口径出处归档,进入已归档态。', + metrics: [{ label: '任务状态', value: TASK_STATE_LABEL[done.state], tone: 'success' }], + points: [], actions: [{ label: '看任务中心', jump: { kind: 'tab', tab: 'task', label: '任务中心' } }], + citations: [], steps, severity: 'success', + }; +} + +/** A7 测算(三期):费率未签字 → 拒绝测算,不给任何金额(SK5)。 */ +async function buildEstimate(raw: string, ctx: AnswerContext): Promise { + const scope = parseAsk(raw, ctx); + const device = scope.device; + const bizDate = scope.dates[0] ?? ctx.bizDate; + const fact = await ctx.tools.queryMetric({ scope: 'DEVICE', id: device, bizDate }); + const steps: OeeStep[] = [stepParse(raw, 'ESTIMATE'), + { act: '四门槛校验', detail: 'SK5:产能 + 费率四门槛齐备且费率已签字才测算' }]; + const est = skillEstimate({ paramsSigned: false }); + steps.push({ act: '拒绝测算', detail: est.stopped ? est.condition : '费率已签字(原型恒未签字)' }); + return { + intent: 'ESTIMATE', agentId: 'A7', device, bizDate, + draft: { intent: 'ESTIMATE', text: '拒绝测算:费率未签字,不给任何金额数字。' }, + facts: [fact], + evidence: est.stopped ? est.condition : '经营测算智能体属三期,四门槛齐备且 A1~A6 稳定运行一季度后才启动。', + nextStep: est.stopped ? est.action : '待费率签字后启动测算。', + metrics: [], points: [{ label: '分期', text: 'A7 经营测算智能体为三期占位,不隐藏、不假装已接。', tone: 'warning' }], + actions: [{ label: '看说明与对照', jump: { kind: 'tab', tab: 'disclosure', label: '说明与对照' } }], + citations: [], steps, severity: 'warning', + stopped: est.stopped ? { skill: '测算', condition: est.condition, action: est.action } : undefined, + }; +} + +/** 技能停止条件的统一拒绝 bundle(facts 仍带工具出处,闸2 不缺)。 */ +function stoppedBundle(intent: AnswerIntent, agentId: OeeAnswer['agentId'], s: { condition: string; action: string; prompt?: string }, steps: OeeStep[], _ctx: AnswerContext): DraftBundle { + return { + intent, agentId, + draft: { intent, text: s.prompt ?? '要素不全,先反问,不猜。' }, + facts: [], evidence: s.condition, nextStep: s.action, + metrics: [], points: [{ label: '停止条件', text: s.condition, tone: 'warning' }], + actions: [], citations: [], steps, severity: 'warning', + stopped: { skill: INTENT_LABEL[intent], condition: s.condition, action: s.action }, + }; +} + +/** 不取数的答复(范围外 / 时间或设备待确认):不套八意图、不借闸门横幅,照实说明能答什么。 */ +function haltBundle(p: { + kind: NonNullable; + label: string; + agentId: OeeAnswer['agentId']; + device?: string; + bizDate?: string; + text: string; + evidence: string; + nextStep: string; + steps: OeeStep[]; + actions?: OeeAction[]; +}): DraftBundle { + return { + intent: 'QUERY', agentId: p.agentId, label: p.label, halt: p.kind, + device: p.device, bizDate: p.bizDate, + draft: { intent: 'QUERY', text: p.text }, + facts: [], evidence: p.evidence, nextStep: p.nextStep, + metrics: [], points: [], actions: p.actions ?? [], + citations: [], steps: p.steps, severity: 'info', + }; +} + +/** 问句里的设备编码样式(2–6 位字母 + 2–4 位数字),用于认出「没接入的编码」而不是硬套锚点。 */ +const DEVICE_TOKEN = /(^|[^A-Z0-9])([A-Z]{2,6}\d{2,4})(?=[^A-Z0-9]|$)/g; + +function unknownDeviceTokens(raw: string): string[] { + const known = new Set(knownDeviceIds().map((id) => id.toUpperCase())); + const out: string[] = []; + for (const m of raw.toUpperCase().matchAll(DEVICE_TOKEN)) if (!known.has(m[2])) out.push(m[2]); + return out; +} + +/** 问句不在可答范围:列明能答什么,不取数、不编数。 */ +function buildOutOfScope(raw: string, _ctx: AnswerContext, device: string): DraftBundle { + return haltBundle({ + kind: 'OUT_OF_SCOPE', label: '不在可答范围', agentId: 'A1', device, + text: '这个问题不在 OEE 工作台的应答范围:我只答 OEE 口径读数、损失归因、可下钻证据、改善建议和任务闭环。', + evidence: `问句「${raw.trim().slice(0, 40)}」未命中任何 OEE 应答关键词;不取数、不猜数。`, + nextStep: '换成「设备 + 业务日 + OEE 指标」的问法,或点下方示例问句。', + steps: [{ act: '范围判定', detail: '未命中八意图关键词 → 不路由到取数工具,照实说明可答范围' }], + actions: [ + { label: '示例:问 OEE', jump: { kind: 'ask', text: OEE_SUGGESTED[0].text, label: '问 OEE' } }, + { label: '示例:问损失', jump: { kind: 'ask', text: OEE_SUGGESTED[1].text, label: '问损失' } }, + ], + }); +} + +/** 时间说法认得出但落不到具体业务日:反问,不套顶栏日期。 */ +function buildUnresolvedTime(raw: string, _ctx: AnswerContext, device: string): DraftBundle { + const phrase = raw.match(UNRESOLVED_TIME)?.[0] ?? '这段时间'; + return haltBundle({ + kind: 'UNRESOLVED_TIME', label: '待确认时间', agentId: 'A1', device, + text: `「${phrase}」落不到具体业务日,先确认时间再取数,不套用顶栏日期。`, + evidence: '时间范围不明确时取任何一天都会把结论说错;本系统只答明确到某一天的读数。', + nextStep: '改写为「2026-09-09」「9月8日」「昨天」这类具体某一天,再问一次。', + steps: [{ act: '时间解析', detail: `识别到「${phrase}」但无法换算为具体业务日 → 反问` }], + }); +} + +/** 设备编码不在台账:反问,不拿锚点设备顶替。 */ +function buildUnknownDevice(_raw: string, _ctx: AnswerContext, token: string): DraftBundle { + const sample = knownDeviceIds().slice(0, 4).join('、'); + return haltBundle({ + kind: 'UNRESOLVED_TIME', label: '待确认设备', agentId: 'A1', + text: `没认出设备「${token}」,先确认设备再取数。`, + evidence: `后端台账与演示台账里都没有这个编码;不拿其他设备顶替。可用设备如 ${sample} 等(以顶栏设备筛选为准)。`, + nextStep: '写明台账里的设备编码(如 DEK001),或先在顶栏选中设备再问。', + steps: [{ act: '设备解析', detail: `问句设备「${token}」不在已知设备集合 → 反问` }], + }); +} + +/* ══════════════════════════════════════════════════════════════════ + * 七、总入口 + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 回答一句自然语言问数。规则路由 → 工具取数 → 技能停止条件 → 五道闸 → 四段装配。 + * @param tasks 当前任务存储(派单 / 复盘用),由调用方注入(内存态,SQLite 锁定四表)。 + */ +export async function answerOee(raw: string, ctx: AnswerContext, tasks: ImprovementTask[] = []): Promise { + const scope = parseAsk(raw, ctx); + const unknown = unknownDeviceTokens(raw); + let bundle: DraftBundle; + if (unknown.length > 0) { + bundle = buildUnknownDevice(raw, ctx, unknown[0]); + } else if (scope.unresolvedTime) { + bundle = buildUnresolvedTime(raw, ctx, scope.device); + } else if (matchedKeys(raw).length === 0) { + bundle = buildOutOfScope(raw, ctx, scope.device); + } else { + switch (classifyIntent(raw)) { + case 'QUERY': bundle = await buildQuery(raw, ctx); break; + case 'ATTRIBUTE': bundle = await buildAttribute(raw, ctx); break; + case 'DRILL': bundle = await buildDrill(raw, ctx); break; + case 'COMPARE': bundle = await buildCompare(raw, ctx); break; + case 'SUGGEST': bundle = await buildSuggest(raw, ctx); break; + case 'DISPATCH': bundle = await buildDispatch(raw, ctx, tasks); break; + case 'REVIEW': bundle = await buildReview(raw, ctx, tasks); break; + case 'ESTIMATE': bundle = await buildEstimate(raw, ctx); break; + default: bundle = await buildQuery(raw, ctx); + } + } + return finalize(bundle, ctx); +} + +/** 引擎自检:供校验脚本与「说明与对照」页引用。 */ +export function answerEngineStats() { + const intents = Object.keys(INTENT_LABEL) as AnswerIntent[]; + return { + intentCount: intents.length, + intents: intents.map((i) => ({ intent: i, label: INTENT_LABEL[i], agent: INTENT_AGENT[i] })), + defaultModel: 'rule', + llmIsEnhancement: true, + degradeKinds: ['MODEL_UNAVAILABLE', 'LOW_CONFIDENCE', 'EVIDENCE_MISSING'] as DegradeKind[], + gateCount: 5, + boundary: '可读、可算、可建议、可派单;不可改数、不可代签核', + suggestedCount: OEE_SUGGESTED.length, + }; +} + +/* 供视图 / hook 复用的取数助手(与看板同源,断言②)。 */ +export { dayByDate, currentDay, blockedDay, deriveAlerts, SEED_DATES, SEED_DIRTY_DATE, ANCHOR_DEVICE_ID, PRIORITY_CANDIDATES, OEE_AGENTS, agentById, taskFromCandidate, tryDispatch, advanceTask }; +export type { OeeTools, OeeToolsDeps, ImprovementTask, KnowledgeChunk, ScoredChunk, LossBucket }; +export type { GuardDrillLayer as DrillLayer }; \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oeeFilters.ts b/src/modules/tfamd-oee/lib/oeeFilters.ts new file mode 100644 index 0000000..c4d2d35 --- /dev/null +++ b/src/modules/tfamd-oee/lib/oeeFilters.ts @@ -0,0 +1,355 @@ +/** + * 全局筛选的**单一来源**(规划书 3.3 顶栏:区域/线体/设备/日期/班次 + 口径版本号)。 + * + * ★ 四条纪律: + * ① **一处状态,级联收敛**:区域 → 线体 → 设备三级级联,上级换了就把不兼容的下级复位为 ALL, + * 不允许出现「区域=FT 但设备=DEK001」这种自相矛盾的筛选组合。 + * ② **口径版本号只有一个来源**:`CALIBER_CONFIG.version`。顶栏/卡片/报表/对话四处都读它, + * 不在视图里另写一份字符串(断言⑩:跨版本对比默认拒绝)。 + * ③ **不拿单机值冒充线体值**:日志贯通全链路只有 DEK001 一台。 + * 选中任何**聚合范围**(区域/线体)或**非锚点设备**时,`resolveScope` 返回 wired=false、day=null + * 并给出该范围的具体缺口,而不是把 DEK 的数字贴上去当线体 OEE。 + * 线体/区域合成(串行连乘/并行加权/瓶颈 P)已于 W2-A 落地为**模板仿真**(断言④), + * 合成读数由 regionRollup 提供、在「工序·工位对比」页展示;但那是合成非实测, + * resolveScope.day 仍只代表**日志贯通**结果,故聚合范围依旧 wired=false。 + * ④ **班次筛选不改 OEE 分母**:班次/小时级游标只筛选时间轴与状态段(见 oeeTime.AXIS_SCOPE_NOTE)。 + * 班次级 OEE 需按班次重算 PPT,属 W2;在此之前**不提供班次级 OEE 数字**,更不做日均摊派。 + * + * 本文件在 lib/ 顶层(非 lib/oee/),与 oeeTime.ts 同级:可 import data 层与 L3 服务, + * 不受引擎零 IO 守卫约束,但自身同样不读时钟、不产生随机数。 + */ +import { + DEVICES, DEVICE_BY_ID, LINES, ANCHOR_DEVICE_ID, + devicesOfRegion, devicesOfLine, shiftsForDate, SHIFT_PATTERN, SHIFT_ASSUMPTION_NOTE, + type DeviceMaster, +} from '../data/oee/devices'; +import { CALIBER_CONFIG } from '../data/oee/calibers28'; +import { dayByDate, type OeeDayResult } from './oeeService'; +import { + PERIOD_COUNT, CURRENT_PERIOD, clampPeriod, periodLabel, AXIS_SCOPE_NOTE, +} from './oeeTime'; + +export const ALL = 'ALL'; +export type RegionFilter = typeof ALL | DeviceMaster['region']; + +export interface OeeFilter { + region: RegionFilter; + /** ALL 或线体 id */ + lineId: string; + /** ALL 或设备 id */ + deviceId: string; + /** 业务日下标 0..PERIOD_COUNT-1 */ + day: number; + /** ALL 或班次 id(SH-C/SH-A/SH-B) */ + shiftId: string; + /** 口径版本号:唯一来源 CALIBER_CONFIG.version */ + caliberVersion: string; +} + +export const DEFAULT_FILTER: OeeFilter = { + region: ALL, lineId: ALL, deviceId: ALL, + day: CURRENT_PERIOD, shiftId: ALL, + caliberVersion: CALIBER_CONFIG.version, +}; + +/* ── 选项:全部由主数据现算,不写死清单 ─────────────────────────────── */ + +export interface FilterOption { value: string; label: string; note?: string } + +export function regionOptions(): FilterOption[] { + const regions: DeviceMaster['region'][] = ['SRF', 'FT', 'ASLT']; + return [ + { value: ALL, label: '全部区域', note: `台账 ${DEVICES.length} 台` }, + ...regions.map((r) => ({ + value: r, label: r, note: `${devicesOfRegion(r).length} 台`, + })), + ]; +} + +export function lineOptions(region: RegionFilter): FilterOption[] { + const ls = region === ALL ? LINES : LINES.filter((l) => l.region === region); + return [ + { value: ALL, label: '全部线体' }, + ...ls.map((l) => ({ value: l.id, label: l.name, note: `${l.deviceIds.length} 台` })), + ]; +} + +export function deviceOptions(region: RegionFilter, lineId: string): FilterOption[] { + let ds = DEVICES; + if (lineId !== ALL) ds = devicesOfLine(lineId); + else if (region !== ALL) ds = devicesOfRegion(region); + return [ + { value: ALL, label: '全部设备' }, + ...ds.map((d) => ({ + value: d.id, + label: `${d.id} · ${d.name}`, + // 未接入的设备在选项里就标出来,不让用户选完才发现是空的 + note: d.id === ANCHOR_DEVICE_ID ? '已贯通' : (d.countsForOee ? '待接入' : '不计入 OEE'), + })), + ]; +} + +export function dayOptions(): FilterOption[] { + return Array.from({ length: PERIOD_COUNT }, (_, i) => ({ + value: String(i), label: periodLabel(i), + })); +} + +/** + * 班次选项。 + * ★ value 存**班次模式 id**(SH-C/SH-A/SH-B),不是 shiftsForDate 返回的 + * `${bizDate}-${id}` 全限定 id——全限定 id 换一天就失效,会把用户已选的班次静默复位。 + * ★ label 用 SHIFT_PATTERN 的真实班次名(夜班/白班/中班)。 + * 不得用 `id.split('-').pop()`:全限定 id 是 `2026-09-03-SH-A`,pop() 得到 'A' 而非 'SH-A'。 + */ +export function shiftOptions(day: number): FilterOption[] { + const windows = shiftsForDate(periodLabel(clampPeriod(day))); + return [ + { value: ALL, label: '全班次', note: SHIFT_ASSUMPTION_NOTE }, + ...SHIFT_PATTERN.map((p, i) => ({ + value: p.id, + label: p.name, + note: `${windows[i].start.slice(11, 16)}–${windows[i].end.slice(11, 16)}`, + })), + ]; +} + +/* ── 级联收敛:上级换了就复位不兼容的下级 ───────────────────────────── */ + +/** + * 规范化筛选:夹回越界日期、复位不兼容的线体/设备、口径版本强制取唯一来源。 + * 纯函数,不改入参。任何写入筛选状态的入口都必须先过这里,避免矛盾组合流到下游。 + */ +export function normalizeFilter(f: OeeFilter): OeeFilter { + const day = clampPeriod(f.day); + let region = f.region; + let lineId = f.lineId; + let deviceId = f.deviceId; + + // 设备决定线体与区域:选了具体设备就把上级对齐到它,而不是把设备复位 + if (deviceId !== ALL && DEVICE_BY_ID[deviceId]) { + const d = DEVICE_BY_ID[deviceId]; + lineId = d.lineId; + region = d.region; + } else { + if (deviceId !== ALL) deviceId = ALL; // 未知设备 id → 复位,不静默当成锚点 + if (lineId !== ALL) { + const l = LINES.find((x) => x.id === lineId); + if (!l || (region !== ALL && l.region !== region)) lineId = ALL; + else region = l.region; // 线体决定区域 + } + } + if (region !== ALL && !['SRF', 'FT', 'ASLT'].includes(region)) region = ALL; + + // 班次按**模式 id** 校验(SH-C/SH-A/SH-B),跨业务日稳定;全限定 id 与非法值一律复位 + const shiftId = f.shiftId !== ALL && SHIFT_PATTERN.some((p) => p.id === f.shiftId) ? f.shiftId : ALL; + + return { + region, lineId, deviceId, day, shiftId, + // 口径版本号不接受外部传入值:W1 只有一个生效版本,切换版本属 W4 配置中心 + caliberVersion: CALIBER_CONFIG.version, + }; +} + +/* ── 范围解析:诚实回答「这个筛选到底能算出什么」 ───────────────────── */ + +export type ScopeKind = 'device' | 'line' | 'region' | 'all'; + +export interface ResolvedScope { + kind: ScopeKind; + /** 数字实际覆盖的对象(不是筛选字面值)。未接入时为 null */ + day: OeeDayResult | null; + wired: boolean; + /** 顶栏必须显示的真实覆盖范围,避免"选了 SRF 却看到 DEK 的数" */ + scopeLabel: string; + /** 未接入原因:具体到设备/线体,不给一句通用套话 */ + gap: string | null; + /** 覆盖范围披露:即使 wired 也要说明全站未合成 */ + coverageNote: string; + /** 班次筛选是否生效;生效时 OEE 仍是日级,必须带这句 */ + shiftNote: string | null; + /** 生效的班次模式 id(ALL 表示全班次) */ + shiftId: string; + /** 生效班次的中文名(夜班/白班/中班),全班次时为 null */ + shiftLabel: string | null; + caliberVersion: string; + bizDate: string; +} + +/** 非锚点设备的具体缺口:用它自己的台账字段说话,不编原因 */ +function deviceGap(d: DeviceMaster): string { + if (!d.countsForOee) { + return `${d.id}(${d.name})为中间缓存,台账 countsForOee=false,**不计入 OEE 聚合**,` + + '不是数据缺失。如需查看其状态,请在设备时间轴页按"非 OEE 对象"单独展示。'; + } + const parts: string[] = [`${d.id}(${d.name})的日志适配与算法模板待 W2 接入`]; + if (!d.hasLog) parts.push(`无设备日志(hasLog=false),过渡采集方式 ${d.fallbackChannel ?? '未定'},需加装 IO`); + if (d.ictSource === 'PENDING_IE') parts.push(`标准节拍 ICT 待 IE 定版(ictSource=PENDING_IE),无节拍无法算 P`); + if (d.ictSource === 'NOT_APPLICABLE') parts.push('该设备类型不适用节拍口径(ictSource=NOT_APPLICABLE)'); + if (d.codeSource === 'DEMO') parts.push('事件码表为演示映射(codeSource=DEMO),非客户真实码表'); + parts.push(`当前只有 ${ANCHOR_DEVICE_ID} 一台贯通日志→事件→状态段→六桶→OEE 全链路`); + return `${parts.join(';')}。`; +} + +/** + * 解析筛选 → 可取数的范围。 + * ★ 只有两种情况给数字:显式选中锚点设备,或三级全 ALL(此时**明确标注只覆盖锚点单机**)。 + * 其余一律 wired=false + 具体缺口,绝不用单机值冒充聚合值。 + */ +export function resolveScope(f: OeeFilter): ResolvedScope { + const n = normalizeFilter(f); + const bizDate = periodLabel(n.day); + const shiftNote = n.shiftId === ALL ? null : AXIS_SCOPE_NOTE; + const shiftLabel = n.shiftId === ALL ? null : (SHIFT_PATTERN.find((p) => p.id === n.shiftId)?.name ?? null); + const base = { caliberVersion: n.caliberVersion, bizDate, shiftNote, shiftId: n.shiftId, shiftLabel }; + + if (n.deviceId !== ALL) { + const d = DEVICE_BY_ID[n.deviceId]; + if (d.id === ANCHOR_DEVICE_ID) { + return { + ...base, kind: 'device', day: dayByDate(bizDate) ?? null, wired: true, + scopeLabel: `${d.id} · ${d.name}(单机)`, + gap: null, + coverageNote: `当前筛选为单台设备,数字即该设备当日口径。${SHIFT_ASSUMPTION_NOTE}`, + }; + } + return { + ...base, kind: 'device', day: null, wired: false, + scopeLabel: `${d.id} · ${d.name}(未接入)`, + gap: deviceGap(d), + coverageNote: '未接入范围不显示任何 OEE 数字,也不显示 0——0 会被误读为"当天没有损失"。', + }; + } + + if (n.lineId !== ALL) { + const l = LINES.find((x) => x.id === n.lineId)!; + return { + ...base, kind: 'line', day: null, wired: false, + scopeLabel: `${l.name}(线体合成·模板仿真)`, + gap: `线体级 OEE 按 ${l.template} 模板合成:串行 A/Q 连乘、P 取瓶颈,并行按投入量加权。` + + `该算法已于 W2-A 落地为模板仿真(断言④),合成读数见「工序·工位对比」页;` + + `但**日志贯通全链路仍仅 ${ANCHOR_DEVICE_ID} 一台**,线体读数为合成非实测,` + + `不得用 ${ANCHOR_DEVICE_ID} 单机值冒充线体值,也不得对成员设备取算术平均。` + + (l.bottleneckDeviceId ? `本线瓶颈设备为 ${l.bottleneckDeviceId},合成时 P 取其节拍。` : ''), + coverageNote: '线体读数为模板仿真(非日志贯通、非实测);此处 day=null 指无日志贯通结果,未接入日志的范围不显示 0。', + }; + } + + if (n.region !== ALL) { + const ds = devicesOfRegion(n.region); + return { + ...base, kind: 'region', day: null, wired: false, + scopeLabel: `${n.region} 区域(区域合成·模板仿真)`, + gap: `${n.region} 区域共 ${ds.length} 台台账设备,区域级 OEE 先做线体合成再按投入量加权,` + + `已于 W2-A 落地为模板仿真(断言④),合成读数见「工序·工位对比」页。` + + `日志贯通全链路仍仅 ${ANCHOR_DEVICE_ID} 一台,区域读数为合成非实测,` + + `不造区域节点充数、不取算术平均、不用单机值冒充区域值。`, + coverageNote: '区域读数为模板仿真(非日志贯通);未接入日志的范围不显示任何 OEE 数字,也不显示 0。', + }; + } + + // 三级全 ALL:给锚点单机的数,但把"全站未合成"写在脸上 + const anchor = DEVICE_BY_ID[ANCHOR_DEVICE_ID]; + return { + ...base, kind: 'all', day: dayByDate(bizDate) ?? null, wired: true, + scopeLabel: `${anchor.id} · ${anchor.name}(锚点单机)`, + gap: null, + coverageNote: `筛选为"全部",但日志贯通全链路只有 ${ANCHOR_DEVICE_ID} 一台,` + + `故当前数字**只覆盖这一台**,不是 ${DEVICES.length} 台台账的全站汇总。` + + 'SRF/FT/ASLT 三区域线体合成已于 W2-A 落地为模板仿真(见「工序·工位对比」页),' + + '但那是合成非实测,不在此处冒充全站汇总。', + }; +} + +/** 顶栏读数区一句话:真实覆盖范围 + 业务日 + 口径版本 */ +export function scopeSummary(f: OeeFilter): string { + const s = resolveScope(f); + return `${s.scopeLabel} · ${s.bizDate} · 口径 ${s.caliberVersion}`; +} + +/* ── 自检:供校验脚本引用(数字一律现算) ───────────────────────────── */ + +export function filterStats() { + const anchorFilter = normalizeFilter({ ...DEFAULT_FILTER, deviceId: ANCHOR_DEVICE_ID }); + const allScope = resolveScope(DEFAULT_FILTER); + const anchorScope = resolveScope(anchorFilter); + + // 矛盾组合必须被收敛:区域=FT 但设备=DEK001(SRF)→ 以设备为准 + const conflict = normalizeFilter({ ...DEFAULT_FILTER, region: 'FT', lineId: 'FT-L1', deviceId: ANCHOR_DEVICE_ID }); + // 未知设备 id 必须复位为 ALL,不得静默当成锚点 + const unknown = normalizeFilter({ ...DEFAULT_FILTER, deviceId: 'NO-SUCH-DEVICE' }); + // 越界日期夹回,不造期 + const clamped = normalizeFilter({ ...DEFAULT_FILTER, day: 99 }); + // 外部传入的口径版本号一律被唯一来源覆盖 + const verOverride = normalizeFilter({ ...DEFAULT_FILTER, caliberVersion: 'v9.9-fake' }); + + const nonAnchor = DEVICES.filter((d) => d.id !== ANCHOR_DEVICE_ID); + const nonAnchorScopes = nonAnchor.map((d) => resolveScope({ ...DEFAULT_FILTER, deviceId: d.id })); + const lineScopes = LINES.map((l) => resolveScope({ ...DEFAULT_FILTER, lineId: l.id })); + const regionScopes = (['SRF', 'FT', 'ASLT'] as const).map((r) => resolveScope({ ...DEFAULT_FILTER, region: r })); + + return { + periodCount: PERIOD_COUNT, + currentPeriod: CURRENT_PERIOD, + deviceCount: DEVICES.length, + lineCount: LINES.length, + regionOptionCount: regionOptions().length, + dayOptionCount: dayOptions().length, + shiftOptionCount: shiftOptions(CURRENT_PERIOD).length, + /** 级联:设备决定上级,矛盾组合被收敛 */ + cascadeConverges: conflict.region === 'SRF' && conflict.lineId === DEVICE_BY_ID[ANCHOR_DEVICE_ID].lineId + && conflict.deviceId === ANCHOR_DEVICE_ID, + unknownDeviceResets: unknown.deviceId === ALL, + dayClamped: clamped.day === CURRENT_PERIOD, + /** 口径版本唯一来源,外部值不得生效 */ + caliberVersionSingleSource: verOverride.caliberVersion === CALIBER_CONFIG.version + && DEFAULT_FILTER.caliberVersion === CALIBER_CONFIG.version, + /** 全 ALL 与显式锚点都必须 wired,且取到同一天的同一个结果对象 */ + allScopeWired: allScope.wired && allScope.day !== null, + anchorScopeWired: anchorScope.wired && anchorScope.day !== null, + sameDayResult: allScope.day !== null && anchorScope.day !== null && allScope.day === anchorScope.day, + /** 全 ALL 必须明说只覆盖锚点单机,不得冒充全站汇总 */ + allScopeDisclosesAnchor: allScope.scopeLabel.includes(ANCHOR_DEVICE_ID) + && allScope.coverageNote.includes('W2-A'), + /** 非锚点设备一律不 wired、不给数字、缺口非空 */ + nonAnchorAllBlocked: nonAnchorScopes.length > 0 && nonAnchorScopes.every((s) => !s.wired && s.day === null), + nonAnchorGapsFilled: nonAnchorScopes.every((s) => (s.gap ?? '').length > 20), + /** 线体/区域聚合一律不 wired(断言④未落地前不给聚合值) */ + lineScopesBlocked: lineScopes.length > 0 && lineScopes.every((s) => !s.wired && s.day === null), + regionScopesBlocked: regionScopes.length > 0 && regionScopes.every((s) => !s.wired && s.day === null), + /** 线体缺口必须写明"不得用单机值冒充"与"不得算术平均" */ + lineGapForbidsSubstitution: lineScopes.every((s) => /冒充/.test(s.gap ?? '') && /算术平均/.test(s.gap ?? '')), + /** 班次筛选生效时必须带"不做日均摊派"的作用域披露 */ + shiftScopeDisclosed: (() => { + const s = resolveScope({ ...DEFAULT_FILTER, shiftId: SHIFT_PATTERN[0].id }); + return s.shiftId === SHIFT_PATTERN[0].id && s.shiftNote !== null + && /不提供班次级 OEE/.test(s.shiftNote) && s.wired; + })(), + /** + * 班次筛选不得改变日级 OEE 取值(分母未重算前不许摊派)。 + * ★ 非真空守卫:必须先确认班次**真的生效**(shiftId 未被复位为 ALL), + * 否则就是拿日级和日级比,恒真而毫无意义。此处曾因此出过假绿。 + */ + shiftDoesNotChangeOee: (() => { + const f = normalizeFilter({ ...DEFAULT_FILTER, shiftId: SHIFT_PATTERN[1].id }); + if (f.shiftId !== SHIFT_PATTERN[1].id) return false; // 没生效就不算通过 + const day = resolveScope(DEFAULT_FILTER).day; + const sh = resolveScope(f).day; + return day !== null && sh !== null && day.tiers.actual.oee === sh.tiers.actual.oee; + })(), + /** 班次模式 id 跨业务日稳定:换一天仍保留已选班次,不被静默复位 */ + shiftStableAcrossDays: SHIFT_PATTERN.every((p) => + Array.from({ length: PERIOD_COUNT }, (_, i) => i) + .every((i) => normalizeFilter({ ...DEFAULT_FILTER, day: i, shiftId: p.id }).shiftId === p.id)), + /** 全限定 id(2026-09-03-SH-A)不是合法筛选值,必须复位为 ALL */ + qualifiedShiftIdResets: normalizeFilter({ + ...DEFAULT_FILTER, shiftId: shiftsForDate(periodLabel(CURRENT_PERIOD))[0].id, + }).shiftId === ALL, + /** 班次选项 label 必须是真实班次名,不得是 split('-').pop() 得到的 'A' */ + shiftLabelsAreNames: JSON.stringify(shiftOptions(CURRENT_PERIOD).slice(1).map((o) => o.label)) + === JSON.stringify(SHIFT_PATTERN.map((p) => p.name)), + shiftAssumptionNote: SHIFT_ASSUMPTION_NOTE, + axisScopeNote: AXIS_SCOPE_NOTE, + caliberVersion: CALIBER_CONFIG.version, + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oeeService.ts b/src/modules/tfamd-oee/lib/oeeService.ts new file mode 100644 index 0000000..6fa8baf --- /dev/null +++ b/src/modules/tfamd-oee/lib/oeeService.ts @@ -0,0 +1,1719 @@ +/** + * L3 服务层:OEE 的**唯一取数入口**。 + * + * 组件 / 本体层 / 指标树 / 校验脚本一律从这里拿数,不得各自再跑一遍链路、 + * 也不得在视图里二次计算。这是断言②「四处读数深相等 + 组件无二次计算」的实现点。 + * + * 分层纪律(ADR-02): + * L1 采集适配 lib/oee/adapterDek.ts 纯函数,码表与事件字典由外部注入 + * L2 引擎 lib/oee/*.ts 零 IO、零时钟、零随机、零模块级可变全局 + * L3 服务 本文件 可 import data 层,负责编排与依赖注入 + * L4 视图 components/* 只消费本层结果 + * + * ★ 本层不做任何"修正":引擎算出残差就照实返回残差,DQ 判阻断就照实返回阻断。 + * 服务层若偷偷归一化,断言②与 G2 门就同时失效。 + */ +import { buildDekSeed, type DekSeed, type DekSeedFile } from '../data/oee/seed/dekLog'; +import { DEK_CODE_MAP } from '../data/oee/dekCodes'; +import { + DEVICE_BY_ID, DEVICES, ANCHOR_DEVICE_ID, shiftsForDate, ctWindowForDate, + SEED_DATES, SEED_DIRTY_DATE, LINE_BY_ID, type DeviceMaster, +} from '../data/oee/devices'; +import { buildSrfSeed, type SrfSeed } from '../data/oee/seed/srfLine'; +import { + buildFtSeed, pocFtInput, FT_SEED_META, FT_POC_93K178, FT_POC_ANCHORS, FT_DAY_PLANS, type FtSeed, +} from '../data/oee/seed/ftLine'; +import { buildAsltSeed, type AsltSeed } from '../data/oee/seed/asltLine'; +import { + calcSrf, calcFt, ftToMember, calcAslt, mergedDurationSec, + type SrfResult, type FtResult, type FtInput, type AsltResult, type BufferSimInput, +} from './oee/templates'; +import { + synthesizeSerial, synthesizeParallel, synthesizeRegion, + arithmeticMean, weightedMeanOfOee, meanOfDailyOee, + type SynthesisResult, type SynthesisMember, +} from './oee/lineSynthesis'; +/* L4 视图只消费 L3:合成法中文标签与结果类型在此再导出,视图不直接 import 引擎模块(ADR-02)。 */ +export { METHOD_LABEL, type SynthesisMethod, type SynthesisResult, type SynthesisMember } from './oee/lineSynthesis'; +import { EVENT_BY_CODE } from '../data/oee/events48'; +import { CALIBER_CONFIG } from '../data/oee/calibers28'; +import { normalizeDekLog, lotWindowsFromAnchors, type NormalizeResult } from './oee/adapterDek'; +import { pairEvents, toEpoch, type LotWindow, type EventPair } from './oee/pairing'; +import { buildSegments, type BuildSegmentsResult } from './oee/stateMachine'; +import { mapToBuckets, type BucketOutput } from './oee/lossBuckets'; +import { calcThreeTier, type ThreeTierOutput, type ThreeTierParams } from './oee/threeTier'; +/* L4 视图只消费 L3:三层参数 / 三层结果类型在此再导出(ADR-02)。配置中心参数重算面板用。 */ +export type { ThreeTierOutput, ThreeTierParams } from './oee/threeTier'; +import { runDq, DQ_RULE_BY_CODE, DQ_DEFAULTS, type DqOutput } from './oee/dq'; +/* L4 视图只消费 L3:DQ 规则字典/阈值/结果类型在此再导出,视图不直接 import 引擎模块(ADR-02)。 */ +export { DQ_RULES, DQ_RULE_BY_CODE, DQ_DEFAULTS, type DqRule, type DqDisposition, type DqOutput } from './oee/dq'; +/* L4 视图只消费 L3:间隙阈值公式默认值 / 台账校准值优先(断言⑤)在此再导出(ADR-02)。 + * 配置中心「间隙阈值」面板用 defaultGapThresholdMin 现算公式默认值,与台账 gapThresholdMin 逐台对照。 */ +export { defaultGapThresholdMin, gapThresholdMin } from './oee/stateMachine'; +import { + buildDetailRef, enumerateTargets, resolveTrace, traceAll, traceStats, + type TraceInput, type TraceResult, type TraceTarget, +} from './oee/trace'; +/* L4 视图只消费 L3:优先级权重字典 / 评分 / 排序 / 结果类型在此再导出,视图不直接 import 引擎模块(ADR-02)。 */ +export { + scorePriority, rankPriority, compareSchemes, validatePriorityItem, validateWeightScheme, clampFactor, priorityStats, + WEIGHT_SCHEMES, DEFAULT_WEIGHT_SCHEME, PRIORITY_FACTOR_LABEL, PRIORITY_FACTOR_KEYS, A_FACTOR_KEYS, B_FACTOR_KEYS, + type PriorityItem, type PriorityScore, type RankedItem, type WeightScheme, type WeightSchemeId, + type PriorityFactors, type PriorityFactorKey, type WeightDim, type ScoreBreakdownRow, +} from './oee/priority'; +/* L4 视图只消费 L3:闭环四项必填 / 六态流转 / 结果类型在此再导出(ADR-02)。 */ +export { + canDispatch, transition, isLegalTransition, nextStates, slaStartOf, closureStats, + REQUIRED_FIELDS, REQUIRED_FIELD_KEYS, LEGAL_TRANSITIONS, + type DispatchCheck, type RequiredField, type RequiredFieldKey, type RequiredFieldGap, + type TransitionContext, type TransitionResult, +} from './oee/closure'; +/* L4 视图只消费 L3:StepChain 换型链七态流转 / GATE 不可跳过 / T6 派生 / SLA 在此再导出(ADR-02,建议书 §4.9)。 + * ★ ChainTaskState 七态与闭环 TaskState 六态是两套独立枚举(D17),分别再导出,不合并。 */ +export { + CHAIN_TRANSITIONS, isLegalChainTransition, nextChainStates, chainTransition, + gateNodeIds, derivedNodeIds, taskNodeIds, nodeStateOf, nodePassed, gateSatisfied, + canActivateNode, canCloseChain, + SETUP_OFFSET_SEC, deriveSetupTimes, reverseDeriveN7, isoToEpoch, + slaDeadlineEpoch, isSlaBreached, escalationFor, chainStats, + type ChainTransitionContext, type ChainTransitionResult, type ActivateCheck, type CloseCheck, type DerivedSetupTimes, +} from './oee/stepchain'; +/* StepChain DSL 数据(7 节点 / 6 触发器 / 表单级 SLA / 演示实例)再导出;统计现算。 */ +export { + SRF_CHAIN, CHAIN_TRIGGERS, FORM_SLA_ESCALATION, SETUP_OFFSET_MIN, + CHAIN_SEED, CHAIN_DEMO_NOW, CHAIN_SEED_NOTE, chainDslStats, + type FormSlaEscalation, +} from '../data/oee/stepchain'; +export { CHAIN_TASK_STATES, CHAIN_STATE_LABEL, CHAIN_TRIGGER_IDS } from '../types/oee'; +export type { ChainNode, ChainTrigger, ChainInstance, ChainNodeState, ChainTaskState, ChainTriggerId } from '../types/oee'; +/* L4 视图只消费 L3:口径解析 / 版本管理 / 跨版本拒绝 / 签字状态在此再导出(ADR-02,断言②⑩)。 + * ★ 本次不安排口径工作坊 ⇒ 28 项 signedOff 全 false,P0 标灰不标绿,全站「待 IE 签字」。 */ +export { + SENSITIVITY_ISSUE_ITEMS, SENSITIVITY_ISSUE_LABEL, caliberValue, requireCaliberValue, + sensitivitySnapshotOf, bumpVersion, resolveCaliber, signOff, diffVersions, compareAcrossVersions, + assertSingleVersion, signOffStatus, sensitivityItems, groupByIssue, checkCaliberDictionary, + type SensitivityIssue, type ResolveOptions, type CaliberChange, type VersionDiff, type SignOffStatus, +} from './oee/caliber'; +/* 28 项口径字典 + 配置 + 敏感性议题(数据层)再导出;统计现算。 */ +export { CALIBER_VERSION, CALIBER_ITEMS, CALIBER_CONFIG, SENSITIVITY_ISSUES, caliberStats } from '../data/oee/calibers28'; +export type { CaliberConfig, CaliberItem } from '../types/oee'; +/* 改善运营(W3-A):候选/待补录事件字典再导出;任务初值与纯流转助手在本层编排。 */ +import { PRIORITY_CANDIDATES, TASK_SEEDS, ENTRY_OPERATOR } from '../data/oee/improvement'; +import { scorePriority, DEFAULT_WEIGHT_SCHEME, type WeightSchemeId } from './oee/priority'; +import { canDispatch as closureCanDispatch, transition as closureTransition } from './oee/closure'; +import { bumpVersion } from './oee/caliber'; +import { STATE_PRIORITY, EPS, BUCKET_LABEL, ALERT_LEVELS, ALERT_LEVEL_ORDER, type ImprovementTask, type ManualEntry5M1E, type TaskState, type EventDef, type StateCode, type OeeAlert, type AlertLevel, type LossBucket, type OeeResult, type ServiceResult, type ReportKind, type ReportPayload, type StateSegment, type SegmentState } from '../types/oee'; +import type { TransitionContext as ClosureCtx, TransitionResult as ClosureResult, DispatchCheck as ClosureCheck } from './oee/closure'; +export { PRIORITY_CANDIDATES, D_CLASS_PENDING, ENTRY_OPERATOR, type DClassPending, type TaskSeed } from '../data/oee/improvement'; +/* L4 视图/智能体只消费 L3:防幻觉五道闸 / 八项技能 / 检索在此再导出(ADR-02 / ADR-06)。 */ +export { + guardAnswer, guardDrill, extractNumbers, collectNumbers, factsContain, GATE_LABEL, guardStats, + type DrillLayer, +} from './oee/guards'; +export { + skillAsk, skillDrill, skillCompare, skillAttribute, skillEstimate, skillSuggest, skillDispatch, skillReview, + SKILL_REGISTRY, skillStats, + type SkillResult, type AskInput, type AttributeInput, type EstimateInput, type SuggestInput, type ReviewInput, +} from './oee/skills'; +export { retrieve, tokenize, retrievalStats, type RetrievalFilter } from './oee/retrieval'; +export { CHUNKS, KB_DOCS, knowledgeStats, KNOWLEDGE_NOTE, type KbDoc, type Chunk, type Corpus } from '../data/oee/knowledge'; +export { OEE_AGENTS, OEE_SKILLS, OEE_TOOLS, AGENT_NAMING_NOTE, AGENT_PHASE_NOTE, AGENT_STATS_NOTE, agentStats, agentById, agentByCode, agentStaffSeeds, type OeeAgent, type OeeSkill, type OeeTool } from '../data/oee/agents'; + +/* ══════════════════════════════════════════════════════════════════ + * W4-B 再导出(ADR-02):预测规则引擎 / 报表版式标签。 + * ★ 预测四门槛全未达 ⇒ 引擎只有规则外推,输出恒带 label='示意·非模型输出'(D13)。 + * 视图只消费本层 forecastOfDay / lineMapNodes / buildReportPayload,不直接 import 引擎模块。 + * ══════════════════════════════════════════════════════════════════ */ +import { + extrapolateStopRisk, extrapolateOee4h, + type StopRisk, type Oee4hForecast, type OeeTrendPoint, +} from './oee/forecast'; +export { + FORECAST_GATES, FORECAST_LABEL, FORECAST_GATE_NOTE, FORECAST_DEGRADE_UNATTRIBUTED, + RISK_LEVEL_LABEL, STOP_RISK_HIGH, STOP_RISK_MED, OEE4H_BAND, OEE4H_BAND_DEGRADED, + MODEL_ROADMAP, MODEL_ROADMAP_NOTE, forecastStats, + type ForecastGate, type ForecastGateId, type RiskLevel, type StopRisk, type Oee4hForecast, + type ModelRoadmapRow, +} from './oee/forecast'; +/* 七类报表版式标签(契约层)再导出,报表导出页选择器用。 */ +export { REPORT_KIND_LABEL } from '../types/oee'; +/** + * 本工程为 demo-only:L1 读内置合成种子,不连接后端、不提供运行时切换。 + * 不用 import.meta.env,以便本层在 Node 校验环境同样可跑。 + */ +export const DATA_MODE = 'demo' as const; + +/** 当前模式的业务日轴:demo 三日种子。 */ +export function activeDates(): string[] { + return [...SEED_DATES]; +} + +/** 「无日志」守卫文案:demo 保持三日贯通原文(校验脚本锁定)。 */ +function noSeedNote(bizDate: string): string { + const dates = activeDates(); + return `${bizDate} 无种子日志(仅 ${dates.join('/')} 三日贯通)`; +} + + + +/** + * 三档共用参数(附录 E 默认值)。 + * ★ C27/C28 属 P0 且**无人签字**(本次不安排口径工作坊), + * 故全站必须标"待 IE 签字",P0 项标灰不标绿。唯一来源在此,视图不得另写一份。 + */ +export const OEE_PARAMS: ThreeTierParams = { + designYield: 0.990, + planPerformanceRate: 0.950, + targetYield: 0.980, + dailyUnavoidableStopSec: 600, + monthlyPlannedStopRate: 0.020, +}; +export const PARAMS_SIGNOFF_NOTE = '附录 E 默认值生效,C27/C28 待 IE 签字;未签字前不得当作客户确认口径'; + +/** 一天的完整计算结果。所有下游读数都从这一个对象取,保证同源。 */ +export interface OeeDayResult { + bizDate: string; + device: DeviceMaster; + seed: DekSeedFile; + normalize: NormalizeResult; + lots: LotWindow[]; + pairs: EventPair[]; + unpaired: ReturnType['unpaired']; + segments: BuildSegmentsResult; + buckets: BucketOutput; + tiers: ThreeTierOutput; + dq: DqOutput; + /** 口径版本号:跨版本对比默认拒绝(断言⑩) */ + caliberVersion: string; + /** + * 血缘入口句柄(断言①的起点)。格式 `oee:设备:业务日:口径版本`,可逆解。 + * ★ 原型无 oee_result_detail 表,故用字符串句柄;生产改真外键(建议书 3.4.1)。 + * 每个数字都必须能从这个句柄一路回溯到 L1 行号,否则不许显示为"已贯通"。 + */ + detailRef: string; + /** + * 本次计算注入的首件不良数(录入台 D 类补录)。 + * ★ 必须随结果留痕:开机不良桶的数量来源是人工补录而非日志, + * 血缘回溯要能点名"这个数是谁填的口径",不能让人以为是采集来的。 + */ + startupDefectQty: number; +} + +export interface RunDayOptions { + /** 覆盖三档参数(口径配置中心切换版本时用),默认 OEE_PARAMS */ + params?: ThreeTierParams; + /** 注入"当前时间",引擎内禁止 Date.now() */ + now?: string; + /** 首件不良数(开机不良桶)。未采集到就传 0,不编造 */ + startupDefectQty?: number; + /** DQ-06 阈值覆盖,默认 5% */ + unattributedBlockPct?: number; + /** + * D 类补录归因(断言⑥):把未归因 IDLE 段归到具体损失桶/状态后重算。 + * 录入台真实提交一条 5M1E → 未归因占比下降、DQ-06 可能解除、版本号递增。 + * ★ 只归因 IDLE 段;非 IDLE / 未知池 id / 非法人事件码一律跳过,不猜。 + */ + resolutions?: UnknownResolution[]; + /** 数据修订号:有补录时版本号递增 v0.1-demo.r{revision}(引擎不维护全局计数) */ + revision?: number; +} + +/** 一条 D 类补录归因:未归因池 id + D 类事件码 + 5M1E 审计记录。 */ +export interface UnknownResolution { + /** 未归因池 id(unk-设备-段id),必须命中一个 IDLE 段 */ + unknownPoolId: string; + /** D 类事件码(决定归口桶/状态),必须是 MANUAL 获取方式 */ + eventCode: string; + /** 补录记录 id(写入 unknown.resolvedByEntryId,供血缘点名"谁填的") */ + entryId: string; + /** 5M1E 七字段(审计留痕;重算只用 eventCode 定桶,不拿描述当数) */ + entry: ManualEntry5M1E; +} + +/** + * D 类事件 → 归因后的状态段状态。按事件唯一归口桶反推: + * FAULT→DOWN · CHANGEOVER→CHANGE · IDLE_MINOR→JAM(待料则 WAIT_MAT) + * bucket=null 的计划类:工程借用→PM(ENG Time),其余→PLAN_STOP(进 PDT,从分母扣除) + * ★ 这是「补录归因」而非「改产能」:IDLE→损失桶时 PPT/RT 不变,OEE 数值不变, + * 只是未归因时间落到具体桶;IDLE→计划类时分母收缩,A 上升(属 C09 Plan 边界口径,待 IE 签字)。 + */ +function resolutionState(def: EventDef): StateCode { + switch (def.bucket) { + case 'FAULT': return 'DOWN'; + case 'CHANGEOVER': return 'CHANGE'; + case 'IDLE_MINOR': return def.factorL2.includes('待料') ? 'WAIT_MAT' : 'JAM'; + case null: return def.grossCategory === '工程借用' ? 'PM' : 'PLAN_STOP'; + // SPEED / 两 Q 桶是节拍/检测派生,无成对事件,D 类不会归到这里;兜底保持 IDLE 不猜 + default: return 'IDLE'; + } +} + +/** + * 跑通单台 DEK 一天的端到端链路: + * 原始行 → 事件/锚点 → lot 窗口 → 配对 → 状态段 → 六桶 → 三档 OEE → DQ。 + * 纯编排:不改引擎结论,不补数,不归一化。 + */ +export function runDekDay(file: DekSeedFile, opts: RunDayOptions = {}): OeeDayResult { + const device = DEVICE_BY_ID[ANCHOR_DEVICE_ID]; + const params = opts.params ?? OEE_PARAMS; + const shifts = shiftsForDate(file.bizDate); + + const normalize = normalizeDekLog(file.lines, DEK_CODE_MAP, EVENT_BY_CODE, device.id); + const lots = lotWindowsFromAnchors(normalize.anchors, device.id); + /* + * ★ 单位换算必须在 L3 边界做完: + * buildSegments 的 ShiftWindow 用 ISO 串(内部 toEpoch), + * pairEvents 的 PairOptions.shifts 用秒级 epoch。 + * 直接把 ISO 串塞给 pairEvents 不会报错——sameShift 里 `a >= undefined` 恒 false, + * 找不到班次就 return true,「不跨班次」约束会**静默失效**。此处显式换算,杜绝该盲区。 + */ + const shiftEpochs = shifts.map((s) => ({ id: s.id, startEpoch: toEpoch(s.start), endEpoch: toEpoch(s.end) })); + const { pairs, unpaired } = pairEvents(normalize.events, EVENT_BY_CODE, { shifts: shiftEpochs }); + + const segments = buildSegments({ + device, pairs, events: normalize.events, defs: EVENT_BY_CODE, + ctWindow: ctWindowForDate(file.bizDate), shifts, caliber: CALIBER_CONFIG, + lots, noDataWindows: file.noDataWindows, + }); + + /* + * ★ 键空间换算必须在 L3 边界做完(与上面 shifts 的 ISO→epoch 同类陷阱): + * segments[].eventIds 是**事件实例 id**,而 EVENT_BY_CODE 按**定义码**建索引。 + * 直接传 EVENT_BY_CODE 不会报错,但 eventCodes 会全空、因子层会跳过每个段, + * 导致 factors/untimedSubFactors 恒为空数组,指标树 L3 驱动因子一个也建不出来。 + * 此处显式建「实例 id → 定义」索引;未映射事件(defCode 不在字典内)如实剔除,不猜。 + */ + const eventDefByInstanceId = Object.fromEntries( + normalize.events + .filter((e) => EVENT_BY_CODE[e.defCode] !== undefined) + .map((e) => [e.id, EVENT_BY_CODE[e.defCode]]), + ); + + /* + * ── D 类补录归因(断言⑥):录入台真实提交后,把未归因 IDLE 段归到具体桶/状态再重算 ── + * ★ 只归因 IDLE 段、只认 MANUAL(D 类)事件码;命中不了就跳过,绝不猜一个桶塞进去。 + * ★ 归因后重算 PDT/PPT:IDLE→计划类(PLAN_STOP/PM)会把时长移进 PDT,分母收缩、A 上升; + * IDLE→损失桶(DOWN/CHANGE/JAM/WAIT_MAT)时分母不变,OEE 数值不变,只是未归因落到具体桶。 + * 两种都让未归因占比下降、残差下降,DQ-06 可能解除阻断。版本号随修订递增。 + */ + const resolutions = opts.resolutions ?? []; + if (resolutions.length > 0) { + const byPool = new Map(resolutions.map((r) => [r.unknownPoolId, r])); + const resolvedPoolIds = new Set(); + segments.segments = segments.segments.map((s) => { + const r = s.unknownPoolId ? byPool.get(s.unknownPoolId) : undefined; + if (!r || s.state !== 'IDLE') return s; + const def = EVENT_BY_CODE[r.eventCode]; + if (!def || def.acquisition !== 'MANUAL') return s; + const st = resolutionState(def); + const instId = `manual-${r.entryId}`; + eventDefByInstanceId[instId] = def; + resolvedPoolIds.add(r.unknownPoolId); + return { ...s, state: st, priority: STATE_PRIORITY[st], filledByGapRule: false, confidence: 1, eventIds: [instId] }; + }); + for (const u of segments.unknown) { + const r = byPool.get(u.id); + if (r && resolvedPoolIds.has(u.id)) { u.resolved = true; u.resolvedByEntryId = r.entryId; } + } + const pdtSec = segments.segments + .filter((s) => s.state === 'PLAN_STOP' || s.state === 'PM') + .reduce((a, s) => a + s.durationSec, 0); + const unknownSecTotal = segments.segments + .filter((s) => s.state === 'UNKNOWN') + .reduce((a, s) => a + s.durationSec, 0); + segments.totals.pdtSec = pdtSec; + segments.totals.pptSec = Math.max(0, segments.totals.ctSec - pdtSec - unknownSecTotal); + } + const caliberVersion = resolutions.length > 0 + ? bumpVersion(CALIBER_CONFIG.version, opts.revision ?? 1) + : CALIBER_CONFIG.version; + + const buckets = mapToBuckets({ + device, segments: segments.segments, eventDefByInstanceId, + pptSec: segments.totals.pptSec, rtSec: segments.totals.runSec, + outputQty: segments.totals.outputQty, goodQty: segments.totals.goodQty, + startupDefectQty: opts.startupDefectQty ?? 0, + }); + + const bucketSec = (k: string) => buckets.buckets.find((b) => b.bucket === k)?.durationSec ?? 0; + const tiers = calcThreeTier({ + pptSec: segments.totals.pptSec, ictSec: device.ictSec, params, + actual: { + pptSec: segments.totals.pptSec, rtSec: segments.totals.runSec, + outputQty: segments.totals.outputQty, goodQty: segments.totals.goodQty, + ictSec: device.ictSec, + faultSec: bucketSec('FAULT'), + changeoverSec: bucketSec('CHANGEOVER'), + idleMinorSec: bucketSec('IDLE_MINOR'), + }, + }); + + const dq = runDq({ + bizDate: file.bizDate, + now: opts.now ?? `${file.bizDate}T21:00:00Z`, + device, + events: normalize.events, pairs, segments: segments.segments, + unattributedSec: buckets.unattributedSec, pptSec: segments.totals.pptSec, + runOutputQty: segments.totals.outputQty, + encoding: { totalLines: file.lines.length, badLines: normalize.malformed.length }, + // 去重点在 L1,计数必须作为证据传进 DQ-09,否则在已去重的事件表上再数一遍恒为 0 + dedup: { dropped: normalize.duplicates.length, scanned: normalize.dedupScanned }, + masterData: { + deviceIds: [device.id], lineIds: [device.lineId], + stations: [device.station], shiftIds: shifts.map((s) => s.id), + }, + refs: { device: device.id, lineId: device.lineId, station: device.station, shiftId: shifts[0].id }, + caliberVersions: [caliberVersion], + ...(opts.unattributedBlockPct !== undefined ? { unattributedBlockPct: opts.unattributedBlockPct } : {}), + }); + + return { + bizDate: file.bizDate, device, seed: file, normalize, lots, pairs, unpaired, + segments, buckets, tiers, dq, caliberVersion, + detailRef: buildDetailRef(device.id, file.bizDate, caliberVersion), + startupDefectQty: opts.startupDefectQty ?? 0, + }; +} + +/* ── 种子结果缓存:同一份种子只跑一次,多处取数必然深相等 ────────────── */ +let seedCache: DekSeed | null = null; +let resultCache: OeeDayResult[] | null = null; + +/** 三日种子(合成)。缓存保证指标树/本体/组件/校验拿到的是同一批对象。 */ +export function dekSeed(): DekSeed { + if (!seedCache) seedCache = buildDekSeed(); + return seedCache; +} + +/** 三日端到端结果,按业务日升序。 */ +export function dekDays(opts: RunDayOptions = {}): OeeDayResult[] { + // 带覆盖参数时不走缓存:口径切换 / D 类补录归因必须真重算(断言⑩ / ⑥) + if (opts.params || opts.now || opts.startupDefectQty !== undefined || opts.unattributedBlockPct !== undefined + || (opts.resolutions && opts.resolutions.length > 0) || opts.revision !== undefined) { + return dekSeed().files.map((f) => runDekDay(f, opts)); + } + if (!resultCache) resultCache = dekSeed().files.map((f) => runDekDay(f)); + return resultCache; +} + +/** 当期=种子最后一天(与旧月轴"默认停在最后一期"语义一致)。 */ +export function currentDay(): OeeDayResult { + const days = dekDays(); + return days[days.length - 1]; +} + +/** 异常日:断流 + 未归因空档 → DQ-06 阻断。演示"结论暂缓发布"用这一天。 */ +export function blockedDay(): OeeDayResult { + return dekDays().find((d) => d.bizDate === SEED_DIRTY_DATE) ?? currentDay(); +} + +export function dayByDate(bizDate: string): OeeDayResult | undefined { + return dekDays().find((d) => d.bizDate === bizDate); +} + +/** 问答/时间轴可解析的设备 id 集合(台账 17 台)。 */ +export function knownDeviceIds(): string[] { + return Object.keys(DEVICE_BY_ID); +} + +/** 「这一天能不能取到数」:demo 仅锚点种子。 */ +export async function answerDayOf(deviceId: string, bizDate: string): Promise { + return deviceId === ANCHOR_DEVICE_ID ? dayByDate(bizDate) : undefined; +} + +/** + * 录入台 D 类补录重算(断言⑥):在指定业务日的种子上注入归因,返回**新版本**结果。 + * 不改缓存里的基线读数(断言②四处读数仍深相等);修订号 revision 由视图按提交次数递增。 + * 未知业务日返回 undefined,由调用方显示"无此日",不猜。 + */ +export function recomputeDay(bizDate: string, resolutions: UnknownResolution[], revision: number): OeeDayResult | undefined { + const base = dayByDate(bizDate); + if (!base) return undefined; + return runDekDay(base.seed, { resolutions, revision }); +} + +/* ══════════════════════════════════════════════════════════════════ + * 血缘回溯(断言①):视图 / 指标树 / 本体 / 校验脚本共用这一个入口。 + * ★ L3 只做"装配注入":把当天已有的原始行、事件、锚点、段、因子、桶、三档 + * 原样交给 L2 纯函数 trace,不在这里二次计算、也不补造证据。 + * ══════════════════════════════════════════════════════════════════ */ + +/** 由一天的结果装配 TraceInput。锚点自带 rawLineId/lineNo,无需再猜行号。 */ +export function traceInputOf(day: OeeDayResult): TraceInput { + return { + detailRef: day.detailRef, + bizDate: day.bizDate, + deviceId: day.device.id, + caliberVersion: day.caliberVersion, + rawLines: day.seed.lines, + events: day.normalize.events, + anchors: day.normalize.anchors.map((a) => ({ + rawLineId: a.rawLineId, lineNo: a.lineNo, cycleSec: a.cycleSec, good: a.good, phase: a.phase, + })), + segments: day.segments.segments, + factors: day.buckets.factors, + buckets: day.buckets.buckets, + tiers: { theoretical: day.tiers.theoretical, planned: day.tiers.planned, actual: day.tiers.actual }, + residualSec: day.buckets.residualSec, + unattributedSec: day.buckets.unattributedSec, + startupDefectQty: day.startupDefectQty, + paramsNote: PARAMS_SIGNOFF_NOTE, + }; +} + +/** 当天全部可回溯的数字叶子(12 三档 + 6 桶 + N 因子 + 残差 + 未归因),顺序固定。 */ +export function traceDay(day: OeeDayResult = currentDay()): TraceResult[] { + return traceAll(traceInputOf(day)); +} + +/** 回溯单个数字。未知 key 返回 null,让调用方显示"该数暂无血缘",不猜一个凑数。 */ +export function traceNumberOf(day: OeeDayResult, key: string): TraceResult | null { + const input = traceInputOf(day); + const target: TraceTarget | undefined = enumerateTargets(input).find((t) => t.key === key); + return target ? resolveTrace(input, target) : null; +} + +/** 三天血缘汇总:断言①与"说明与对照"页都从这里取数,禁止各自重跑链路。 */ +export function traceStatsOfDays(days: OeeDayResult[] = dekDays()) { + return days.map((d) => ({ bizDate: d.bizDate, detailRef: d.detailRef, ...traceStats(traceDay(d)) })); +} + +/** 服务层自检:供校验脚本与"说明与对照"页引用,数字一律现算。 */ +export function serviceStats() { + const days = dekDays(); + const cur = currentDay(); + return { + mode: DATA_MODE, + dataGap: '实时直采未接:本工程为 demo 沙箱,状态灯只表达演示数据可得性', + anchorDevice: ANCHOR_DEVICE_ID, + dates: days.map((d) => d.bizDate), + seedDates: activeDates(), + dirtyDate: activeDates().includes(SEED_DIRTY_DATE) ? SEED_DIRTY_DATE : activeDates()[activeDates().length - 1], + caliberVersion: cur.caliberVersion, + paramsSignoff: PARAMS_SIGNOFF_NOTE, + totalLines: days.reduce((a, d) => a + d.seed.lines.length, 0), + blockedDates: days.filter((d) => d.dq.blocked).map((d) => d.bizDate), + residualByDate: days.map((d) => ({ bizDate: d.bizDate, residualSec: d.buckets.residualSec })), + oeeByDate: days.map((d) => ({ bizDate: d.bizDate, oee: d.tiers.actual.oee })), + /** + * 血缘贯通统计(断言①):现算,不写死。 + * wired 只统计"真落到行号"的数字;derived/parameter 如实分列, + * 让评审一眼看出哪些数有原始行、哪些是参数/节拍派生——不许把三类混成一个"贯通率"。 + */ + traceByDate: traceStatsOfDays(days).map((t) => ({ + bizDate: t.bizDate, detailRef: t.detailRef, total: t.total, wired: t.wiredCount, + event: t.byKind.event, derived: t.byKind.derived, parameter: t.byKind.parameter, + evidence: t.evidenceCount, + })), + /** 三区域线体合成已接入(W2-A);仍有缺口,如实列出 */ + coverageGap: 'DEK 锚点贯通日志→OEE 全链路;SRF/FT/ASLT 三区域模板与线体合成已接入,' + + '但 SRF 仅建 DEK+DCP 两台代表站(POC 为 13 台)、FT 仅 93k178 有客户操作数、' + + 'ASLT 无客户算法表;三区域种子均为合成,不复现 POC 锚点', + regions: regionStats(), + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三区域模板与线体合成(W2-A) + * + * ★ L3 职责:从台账注入 ICT/Site 数、编排 L2 纯函数、附加 DQ 阻断判定。 + * 不改引擎结论、不归一化、不补数。POC 锚点只作**并列参考行**,绝不混进计算。 + * + * ★ 周期汇总的口径判断(规划书 4.1.5「按 biz_date 累加,不用月度平均倒推日 OEE」): + * · SRF:累加各站 PPT/RT/N/good 原始量 → 重算各站三率 → 再走串行规则。 + * · FT :A 是连乘扣减式,**不能套 ΣRT/ΣPPT**;必须累加操作数后重跑 calcFt。 + * · ASLT:Σ运行/Σ活跃窗口、Σ站点使能/Σ站点容量、Σ合格/Σ投入。 + * 三者都是"累加原始量再按同一口径重算",不是对日 OEE 求平均。 + * ══════════════════════════════════════════════════════════════════ */ + +/** 台账 ICT 注入:种子不得自带与台账冲突的节拍。不一致就报问题,不静默取其一。 */ +function ictFromMaster(deviceId: string, seedIctSec: number): { ictSec: number; problem?: string } { + const dev = DEVICE_BY_ID[deviceId]; + if (!dev) return { ictSec: seedIctSec, problem: `台账无设备 ${deviceId},ICT 无法核对` }; + if (dev.ictSec <= 0) return { ictSec: seedIctSec, problem: `${deviceId} 台账 ICT 为 0(${dev.ictSource}),不得用于仿真` }; + if (Math.abs(dev.ictSec - seedIctSec) > 1e-9) { + return { ictSec: dev.ictSec, problem: `${deviceId} 种子 ICT ${seedIctSec} 与台账 ${dev.ictSec} 不一致,已取台账值` }; + } + return { ictSec: dev.ictSec }; +} + +/* ── SRF ───────────────────────────────────────────────────────── */ + +export interface SrfDayResult { + bizDate: string; + story: string; + result: SrfResult; + /** DQ-10:缺失窗口未经日志验证,读数可看但不可发布 */ + dq: { + noDataWindows: { deviceId: string; startSec: number; endSec: number; note: string }[]; + unverifiedSec: number; + unverifiedPct: number; + blocked: boolean; + reason: string; + }; + caliberVersion: string; + /** 是否为合成种子 */ + synthetic: boolean; +} + +let srfSeedCache: SrfSeed | null = null; +let srfResultCache: SrfDayResult[] | null = null; + +export function srfSeed(): SrfSeed { + if (!srfSeedCache) srfSeedCache = buildSrfSeed(); + return srfSeedCache; +} + +export function srfDays(): SrfDayResult[] { + if (srfResultCache) return srfResultCache; + const seed = srfSeed(); + srfResultCache = seed.days.map((d) => { + // demo:台账注入 ICT,不一致就报问题(不静默取其一)。 + const upIct: { ictSec: number; problem?: string } = ictFromMaster(d.sim.upstream.deviceId, d.sim.upstream.ictSec); + const downIct: { ictSec: number; problem?: string } = ictFromMaster(d.sim.downstream.deviceId, d.sim.downstream.ictSec); + const sim: BufferSimInput = { + ...d.sim, + upstream: { ...d.sim.upstream, ictSec: upIct.ictSec }, + downstream: { ...d.sim.downstream, ictSec: downIct.ictSec }, + }; + const result = calcSrf({ + lineId: seed.meta.lineId, + scopeLabel: `${seed.meta.lineId} · ${d.bizDate} · DEK+DCP 两台代表站`, + bizDate: d.bizDate, + sim, + yieldRate: d.yieldRate, + anchors: d.anchors, + bottleneckDeviceId: LINE_BY_ID[seed.meta.lineId]?.bottleneckDeviceId, + }); + // ICT 不一致属主数据问题,附加披露但不篡改引擎 ok + for (const p of [upIct.problem, downIct.problem]) if (p) result.problems.push(p); + if (result.problems.length > 0) result.ok = false; + + const unverifiedSec = d.noDataWindows.reduce((s, w) => s + (w.endSec - w.startSec), 0); + const unverifiedPct = (unverifiedSec / 86400) * 100; + const blocked = unverifiedSec > 0; + return { + bizDate: d.bizDate, + story: d.story, + result, + dq: { + noDataWindows: d.noDataWindows, + unverifiedSec, + unverifiedPct, + blocked, + reason: blocked + ? `DQ-10:${d.noDataWindows.map((w) => w.deviceId).join('/')} 存在 ${unverifiedSec / 60}min 日志缺失窗口,` + + '该段状态未经日志验证,仿真按构造时间轴计算,结论暂缓发布(不得作为考核依据)' + : '无缺失窗口,时间轴全程有日志支撑', + }, + caliberVersion: CALIBER_CONFIG.version, + synthetic: seed.meta.synthetic, + }; + }); + return srfResultCache; +} + +export function srfCurrent(): SrfDayResult { + const days = srfDays(); + return days[days.length - 1]; +} + +export function srfDayByDate(bizDate: string): SrfDayResult | undefined { + return srfDays().find((d) => d.bizDate === bizDate); +} + +/** SRF 周期汇总:累加各站原始量 → 重算三率 → 串行规则。不对日 OEE 求平均。 */ +export function srfPeriod(days: SrfDayResult[] = srfDays()): SynthesisResult { + const ids = days[0]?.result.stations.map((s) => s.deviceId) ?? []; + const members: SynthesisMember[] = ids.map((id, idx) => { + const rows = days.map((d) => d.result.stations[idx]).filter((s) => s.deviceId === id); + const pptSec = rows.reduce((s, r) => s + r.pptSec, 0); + const runSec = rows.reduce((s, r) => s + r.runSec, 0); + const outputQty = rows.reduce((s, r) => s + r.outputQty, 0); + const goodQty = rows.reduce((s, r) => s + r.goodQty, 0); + const ictSec = rows[0]?.ictSec ?? 0; + const a = pptSec > 0 ? runSec / pptSec : 0; + const p = runSec > 0 ? (outputQty * ictSec) / runSec : 0; + const q = outputQty > 0 ? goodQty / outputQty : 0; + return { id, a, p, q, oee: a * p * q, inputQty: outputQty, pptSec, runSec, idealSec: outputQty * ictSec, outputQty, goodQty }; + }); + return synthesizeSerial(members, `SRF-L1 · ${days.length} 日累计`, LINE_BY_ID['SRF-L1']?.bottleneckDeviceId); +} + +/* ── FT ────────────────────────────────────────────────────────── */ + +export interface FtDayResult { + bizDate: string; + story: string; + devices: FtResult[]; + /** C06 对照:同操作数关掉 PM */ + devicesPmOff: FtResult[]; + line: SynthesisResult; + caliberVersion: string; + /** 是否为合成种子 */ + synthetic: boolean; +} + +let ftSeedCache: FtSeed | null = null; +let ftResultCache: FtDayResult[] | null = null; + +export function ftSeed(): FtSeed { + if (!ftSeedCache) ftSeedCache = buildFtSeed(); + return ftSeedCache; +} + +export function ftDays(): FtDayResult[] { + if (ftResultCache) return ftResultCache; + const seed = ftSeed(); + ftResultCache = seed.days.map((d) => { + const devices = d.inputs.map((i) => calcFt(i)); + const devicesPmOff = d.inputsPmOff.map((i) => calcFt(i)); + const line = synthesizeParallel(devices.map(ftToMember), `${seed.meta.lineId} · ${d.bizDate} · ${d.inputs.length} 台按投入量加权`); + return { bizDate: d.bizDate, story: d.story, devices, devicesPmOff, line, caliberVersion: CALIBER_CONFIG.version, synthetic: seed.meta.synthetic }; + }); + return ftResultCache; +} + +export function ftCurrent(): FtDayResult { + const days = ftDays(); + return days[days.length - 1]; +} + +export function ftDayByDate(bizDate: string): FtDayResult | undefined { + return ftDays().find((d) => d.bizDate === bizDate); +} + +/** + * FT 周期汇总:**累加操作数后重跑 calcFt**。 + * A 是连乘扣减式,ΣRT/ΣPPT 与它不同构,套通用式会算出完全不同的数(规划书 4.1.4 警告)。 + * 比率类操作数按 baseSec 加权还原成秒/绝对量再累加,保持量纲一致。 + */ +export function ftPeriod(days: FtDayResult[] = ftDays()): { devices: FtResult[]; line: SynthesisResult } { + const seed = ftSeed(); + const ids = seed.meta.deviceIds; + const devices = ids.map((id) => { + const rows = days.map((d, i) => ({ + r: d.devices.find((x) => x.deviceId === id), + plan: FT_DAY_PLANS[i]?.devices.find((p) => p.deviceId === id), + })).filter((x) => x.r && x.plan); + const baseSec = rows.reduce((s, x) => s + (x.r?.baseSec ?? 0), 0); + const downSec = rows.reduce((s, x) => s + (x.plan ? x.plan.baseSec * x.plan.downRate : 0), 0); + const jamSec = rows.reduce((s, x) => s + (x.plan ? x.plan.baseSec * x.plan.jamRate : 0), 0); + const inputQty = rows.reduce((s, x) => s + (x.r?.inputQty ?? 0), 0); + const pmMin = rows.reduce((s, x) => s + (x.plan?.pmMin ?? 0), 0); + const first = rows[0]?.plan; + // SetupLoss/Corr/OE/Index/Rescreen 为比率或固定操作数:取首日值并披露"跨日按首日口径" + const input: FtInput = { + deviceId: id, + scopeLabel: `${id} · ${days.length} 日累计`, + algorithmTable: FT_SEED_META.algorithmTable, + baseSec, downSec, jamSec, + setup: first?.setup ?? { op1: 0, op2: 0, op3: 1, op4: 0, op5: 1 }, + corrRate: first?.corrRate ?? 0, + oeRate: first?.oeRate ?? 0, + indexSec: first?.indexSec ?? 0, + testSec: first?.testSec ?? 1, + rescreenFactor: first?.rescreenFactor ?? 1, + yieldRate: first?.yieldRate ?? 0, + planLossRate: first?.planLossRate ?? 0, + inputQty, + pmMin: pmMin > 0 ? pmMin : undefined, + operandSource: 'SEED', + synthetic: true, + }; + const r = calcFt(input); + r.notes.push(`周期累计口径:baseSec/downSec/jamSec/inputQty/PM 按日累加;` + + 'SetupLoss/Corr/OE/Index/Rescreen/良率取首日操作数(客户未给逐日值),跨日口径须 IE 确认'); + return r; + }); + return { devices, line: synthesizeParallel(devices.map(ftToMember), `FT-L1 · ${days.length} 日累计`) }; +} + +/** POC 参考基线(独立复算,不与演示种子混算)。 */ +export function ftPocReference(): { result: FtResult; published: typeof FT_POC_93K178.recomputed; anchors: typeof FT_POC_ANCHORS } { + return { result: calcFt(pocFtInput()), published: FT_POC_93K178.recomputed, anchors: FT_POC_ANCHORS }; +} + +/* ── ASLT ──────────────────────────────────────────────────────── */ + +export interface AsltDayResult { + bizDate: string; + story: string; + result: AsltResult; + caliberVersion: string; + /** 是否为合成种子 */ + synthetic: boolean; +} + +let asltSeedCache: AsltSeed | null = null; +let asltResultCache: AsltDayResult[] | null = null; + +export function asltSeed(): AsltSeed { + if (!asltSeedCache) asltSeedCache = buildAsltSeed(); + return asltSeedCache; +} + +export function asltDays(): AsltDayResult[] { + if (asltResultCache) return asltResultCache; + const seed = asltSeed(); + asltResultCache = seed.days.map((d) => { + const siteCount = DEVICE_BY_ID[seed.meta.deviceId]?.siteCount ?? d.input.siteCount; + const result = calcAslt({ ...d.input, siteCount }); + if (siteCount !== d.input.siteCount) { + result.problems.push(`种子 Site 数 ${d.input.siteCount} 与台账 ${siteCount} 不一致,已取台账值`); + result.ok = false; + } + return { bizDate: d.bizDate, story: d.story, result, caliberVersion: CALIBER_CONFIG.version, synthetic: seed.meta.synthetic }; + }); + return asltResultCache; +} + +export function asltCurrent(): AsltDayResult { + const days = asltDays(); + return days[days.length - 1]; +} + +export function asltDayByDate(bizDate: string): AsltDayResult | undefined { + return asltDays().find((d) => d.bizDate === bizDate); +} + +/** ASLT 周期汇总:Σ运行/Σ活跃窗口、Σ站点使能/Σ站点容量、Σ合格/Σ投入。 */ +export function asltPeriod(days: AsltDayResult[] = asltDays()): { a: number; p: number; q: number; oee: number; formula: string } { + const runSec = days.reduce((s, d) => s + d.result.runSec, 0); + const activeSec = days.reduce((s, d) => s + d.result.activeWindowSec, 0); + const enableSec = days.reduce((s, d) => s + d.result.siteEnableSec, 0); + const capSec = days.reduce((s, d) => s + d.result.siteCapacitySec, 0); + const ftInput = days.reduce((s, d) => s + d.result.output.ftInput, 0); + const good = days.reduce((s, d) => s + d.result.output.ftGood + d.result.output.rcGood, 0); + const a = activeSec > 0 ? runSec / activeSec : 0; + const p = capSec > 0 ? enableSec / capSec : 0; + const q = ftInput > 0 ? good / ftInput : 0; + return { + a, p, q, oee: a * p * q, + formula: `A=Σ运行${(runSec / 3600).toFixed(2)}h/Σ活跃窗口${(activeSec / 3600).toFixed(2)}h;` + + `P=Σ使能${(enableSec / 3600).toFixed(2)}h/Σ容量${(capSec / 3600).toFixed(2)}h;` + + `Q=Σ合格${good}/Σ投入${ftInput}(${days.length} 日累计,非日均)`, + }; +} + +/* ── 线别 / 区域汇总 ───────────────────────────────────────────── */ + +export interface RegionRollup { + scopeLabel: string; + lines: SynthesisResult[]; + /** 线别加权用的成员(带 id 与投入量),反例对照也用它,保证权重同源 */ + lineMembers: SynthesisMember[]; + region: SynthesisResult; + /** 反例对照:三种错误方法的结果,供"说明与对照"页展示为什么不能那么算 */ + wrongMethods: { arithmeticMeanOfLines: number; weightedMeanOfLineOee: number; meanOfDailyOee: number }; +} + +/** 当期三线汇总 + 区域加权。线别加权按投入量,不做简单平均(规划书 4.1.5)。 */ +export function regionRollup(bizDate?: string): RegionRollup { + const srf = bizDate ? srfDayByDate(bizDate) : srfCurrent(); + const ft = bizDate ? ftDayByDate(bizDate) : ftCurrent(); + const aslt = bizDate ? asltDayByDate(bizDate) : asltCurrent(); + const scope = bizDate ?? srf?.bizDate ?? ''; + + const srfLine: SynthesisResult = srf + ? synthesizeSerial(srf.result.stations.map((s) => ({ + id: s.deviceId, a: s.a, p: s.p, q: s.q, oee: s.oee, inputQty: s.outputQty, + pptSec: s.pptSec, runSec: s.runSec, idealSec: s.outputQty * s.ictSec, outputQty: s.outputQty, goodQty: s.goodQty, + })), `SRF-L1 · ${scope}`, LINE_BY_ID['SRF-L1']?.bottleneckDeviceId) + : synthesizeSerial([], `SRF-L1 · ${scope}`); + + const ftLine = ft?.line ?? synthesizeParallel([], `FT-L1 · ${scope}`); + + const asltLine: SynthesisResult = aslt + ? synthesizeSerial([{ + id: aslt.result.deviceId, a: aslt.result.a, p: aslt.result.p, q: aslt.result.q, oee: aslt.result.oee, + inputQty: aslt.result.output.ftInput, + }], `ASLT-L1 · ${scope} · 单台 12 Site`) + : synthesizeSerial([], `ASLT-L1 · ${scope}`); + + const lines = [srfLine, ftLine, asltLine]; + /* 线别权重的投入量口径:SRF 取上游产出(进线物料)、FT 取三台投入之和、ASLT 取 FT 投入。 + SynthesisResult 不带 id/inputQty,故显式构造 member,不让反例函数去猜权重。 */ + const lineMembers: SynthesisMember[] = [ + { + id: 'SRF-L1', a: srfLine.a, p: srfLine.p, q: srfLine.q, oee: srfLine.oee, + inputQty: srf?.result.stations.find((s) => s.role === 'UPSTREAM')?.outputQty ?? 0, + }, + { + id: 'FT-L1', a: ftLine.a, p: ftLine.p, q: ftLine.q, oee: ftLine.oee, + inputQty: ft?.devices.reduce((s, d) => s + d.inputQty, 0) ?? 0, + }, + { + id: 'ASLT-L1', a: asltLine.a, p: asltLine.p, q: asltLine.q, oee: asltLine.oee, + inputQty: aslt?.result.output.ftInput ?? 0, + }, + ]; + /* 缺区不加权:任一区域该日无种子时,跨区加权直接判不可用(ok=false)。 + 不得让缺区成员以 0 权重静默混入——那会把"SRF 单区读数"冒充成"三区域加权"。 */ + const missing = [!srf && 'SRF', !ft && 'FT', !aslt && 'ASLT'].filter(Boolean) as string[]; + const region = missing.length > 0 + ? { ...synthesizeRegion([], `三区域 · ${scope}`), problems: [`${missing.join('/')} 该日无种子,缺区不加权(不显示 0)`] } + : synthesizeRegion(lineMembers, `三区域 · ${scope} · 线别按投入量加权`); + return { + scopeLabel: scope, + lines, + lineMembers, + region, + wrongMethods: { + arithmeticMeanOfLines: arithmeticMean(lineMembers).oee, + weightedMeanOfLineOee: weightedMeanOfOee(lineMembers), + meanOfDailyOee: meanOfDailyOee(srfDays().map((d) => ({ oee: d.result.line.oee }))), + }, + }; +} + +/** 三区域服务自检:供校验脚本④与主数据页引用,数字一律现算。 */ +export function regionStats() { + const srf = srfDays(); + const ft = ftDays(); + const aslt = asltDays(); + return { + srf: { + days: srf.length, stations: 2, capacity: srf[0]?.result.buffer.capacity ?? 0, + blockedDates: srf.filter((d) => d.dq.blocked).map((d) => d.bizDate), + oeeByDate: srf.map((d) => ({ bizDate: d.bizDate, oee: d.result.line.oee, qtySource: d.result.stations[0]?.qtySource })), + decoupledByDate: srf.map((d) => ({ + bizDate: d.bizDate, up: d.result.buffer.decoupled, down: d.result.buffer.decoupledDownstream, + fully: d.result.buffer.fullyDecoupled, bMinUp: d.result.buffer.minCapacity, bMinDown: d.result.buffer.minCapacityDownstream, + })), + residualByDate: srf.map((d) => ({ bizDate: d.bizDate, ...d.result.buffer.residualSec })), + pocAnchor: srfSeed().meta.pocAnchor, + }, + ft: { + days: ft.length, devices: ftSeed().meta.deviceIds.length, + oeeByDate: ft.map((d) => ({ bizDate: d.bizDate, oee: d.line.oee, method: d.line.method })), + pmSensitivity: ft.map((d) => ({ + bizDate: d.bizDate, + on: d.devices.find((x) => (x.pmSec ?? 0) > 0)?.oee ?? null, + off: d.devicesPmOff.find((_x, i) => (d.devices[i]?.pmSec ?? 0) > 0)?.oee ?? null, + deviceId: d.devices.find((x) => (x.pmSec ?? 0) > 0)?.deviceId ?? null, + })), + baseSecIssue: ftSeed().meta.baseSecIssue, + pocAnchor: FT_POC_ANCHORS, + }, + aslt: { + days: aslt.length, siteCount: asltSeed().meta.siteCount, + oeeByDate: aslt.map((d) => ({ bizDate: d.bizDate, oee: d.result.oee, a: d.result.a, p: d.result.p, q: d.result.q })), + residualByDate: aslt.map((d) => ({ bizDate: d.bizDate, residualSec: d.result.timeAccountResidualSec })), + waitPlanByDate: aslt.map((d) => ({ bizDate: d.bizDate, waitPlanPct: d.result.waitPlanPct })), + problemsByDate: aslt.map((d) => ({ bizDate: d.bizDate, ok: d.result.ok, problems: d.result.problems })), + pocAnchor: asltSeed().meta.pocAnchor, + }, + signoff: PARAMS_SIGNOFF_NOTE, + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 改善运营编排(W3-A):任务初值现算 + 派发闸 + 六态流转 + 5M1E 补录。 + * + * ★ 本层只编排 L2 纯函数(priority / closure),不另写一份评分或校验逻辑。 + * 任务态保存在视图 React state —— sqlite 锁四表(断言②),improvement_task 不落库。 + * 时钟由调用方注入(ctx.at / at / by):引擎与本层都不读 Date.now,用户动作时刻由视图给。 + * 所有流转助手都返回**新数组**,绝不原地改入参(React 不可变更新)。 + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 装配初始改善任务:priorityScore 由候选现算(断言⑧可解释),不在种子里写死。 + * 候选缺失属种子完整性错误 → 显式抛错,不静默补 0 分把问题抹平。 + */ +export function initialTasks(): ImprovementTask[] { + return TASK_SEEDS.map((s) => { + const cand = PRIORITY_CANDIDATES.find((c) => c.id === s.candidateId); + if (!cand) throw new Error(`任务种子 ${s.id} 指向未知候选 ${s.candidateId}(种子完整性错误)`); + const { candidateId, ...rest } = s; + void candidateId; // 仅用于定位候选,不进任务对象 + return { ...rest, priorityScore: scorePriority(cand, s.weightScheme).score }; + }); +} + +/** 候选 → 待审核任务的入参(真因实体/证据链由视图给,不臆造)。 */ +export interface NewTaskInit { + id: string; + candidateId: string; + title: string; + rootCauseEntity: ImprovementTask['rootCauseEntity']; + causeClass: ImprovementTask['causeClass']; + evidenceChain: string[]; + /** 生成时刻与操作人,由视图注入 */ + at: string; + by: string; + scheme?: WeightSchemeId; +} + +/** + * 由优先清单候选生成一条「待审核」任务:priorityScore 现算,history 从 DRAFT 两步到 PENDING_REVIEW。 + * 四项必填留空 → 派发闸会拒派,正好演示「补齐后才能派发」。 + */ +export function taskFromCandidate(init: NewTaskInit): ImprovementTask { + const cand = PRIORITY_CANDIDATES.find((c) => c.id === init.candidateId); + if (!cand) throw new Error(`未知候选 ${init.candidateId}(无法现算优先级分)`); + const scheme = init.scheme ?? DEFAULT_WEIGHT_SCHEME; + return { + id: init.id, + state: 'PENDING_REVIEW', + title: init.title, + rootCauseEntity: init.rootCauseEntity, + causeClass: init.causeClass, + evidenceChain: init.evidenceChain, + priorityScore: scorePriority(cand, scheme).score, + weightScheme: scheme, + history: [ + { state: 'DRAFT', at: init.at, by: init.by }, + { state: 'PENDING_REVIEW', at: init.at, by: init.by, note: '由优先清单生成,待补四项必填' }, + ], + }; +} + +/** + * 派发闸(断言⑨):先跑四项必填 canDispatch,再走 待审核→已派发 流转。 + * 缺项 → result.ok=false,tasks 原样返回(任务停在待审核),check.missing 供 UI 逐条提示。 + */ +export function tryDispatch( + tasks: ImprovementTask[], id: string, ctx: ClosureCtx, +): { tasks: ImprovementTask[]; check: ClosureCheck; result: ClosureResult } { + const task = tasks.find((t) => t.id === id); + if (!task) { + return { tasks, check: { ok: false, missing: [] }, result: { ok: false, reason: `未找到任务 ${id}` } }; + } + const check = closureCanDispatch(task); + const result = closureTransition(task, 'DISPATCHED', ctx); + if (!result.ok || !result.task) return { tasks, check, result }; + const next = result.task; + return { tasks: tasks.map((t) => (t.id === id ? next : t)), check, result }; +} + +/** 通用六态流转(派发以外的合法边)。非法/被拒 → tasks 原样返回,result.reason 说明。 */ +export function advanceTask( + tasks: ImprovementTask[], id: string, to: TaskState, ctx: ClosureCtx, +): { tasks: ImprovementTask[]; result: ClosureResult } { + const task = tasks.find((t) => t.id === id); + if (!task) return { tasks, result: { ok: false, reason: `未找到任务 ${id}` } }; + const result = closureTransition(task, to, ctx); + if (!result.ok || !result.task) return { tasks, result }; + const next = result.task; + return { tasks: tasks.map((t) => (t.id === id ? next : t)), result }; +} + +/** + * 5M1E 七字段补录(D 类事件唯一来源):enteredBy / enteredAt 由系统写入,不可手填。 + * at 由调用方注入(用户提交时刻),by 默认演示角色 ENTRY_OPERATOR。 + */ +export function makeEntry( + fields: Omit, + at: string, + by: string = ENTRY_OPERATOR, +): ManualEntry5M1E { + return { ...fields, enteredBy: by, enteredAt: at }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 改善运营(W3-B):五级告警流 —— 右栏 OeeAlertPanel 的唯一取数入口。 + * ★ 全部从当日读数现算(day.dq / buckets / tiers / segments.unknown / normalize.events), + * 不另写一份统计、不臆造告警(断言②同源)。S4 阻断级与停机同级、有权暂停发布(规划书 §5.5)。 + * ★ 纯编排:不读 Date.now、不随机;id 用函数内局部计数器,同输入两次调用深相等、可重放。 + * ══════════════════════════════════════════════════════════════════ */ + +/** + * 安全(EMO/安全回路)事件码集合。 + * ★ 诚实性:原型 48 事件字典全部是 OEE 损失事件,**不含 EMO/安全回路事件** + * (安全属厂级 EHS 系统,不在 OEE 损失归因范围)。故此集合为空,S1 对种子结构为空, + * 绝不为了"五级看起来齐全"而臆造一条安全告警。真实安全码表接入后在此登记即可生效。 + */ +export const SAFETY_EVENT_CODES: readonly string[] = []; + +/** deriveAlerts 可选参数。oeeTarget 缺省取计划档 OEE(day.tiers.planned.oee),即"计划偏移"基准。 */ +export interface DeriveAlertsOptions { + oeeTarget?: number; +} + +/** + * 由当日完整结果现算五级告警流(S1→S5 严重度降序)。 + * 每一档都有明确的 L3 来源,缺触发即该档为空(诚实,不补假告警): + * S1 安全 ← normalize.events 中 defCode ∈ SAFETY_EVENT_CODES(种子为空) + * S2 非计划停机 ← buckets 里 FAULT/IDLE_MINOR 时长 > 0 + * S3 瓶颈/偏移 ← 实际 OEE < 计划档 + 六桶 Pareto Top1 + * S4 数据质量 ← dq.blockedBy(DQ-06/08/12),blocksPublish=true + * S5 观察项 ← dq.notEvaluated(缺证据)+ segments.unknown 未解决段 + */ +export function deriveAlerts(day: OeeDayResult, opts: DeriveAlertsOptions = {}): OeeAlert[] { + const out: OeeAlert[] = []; + const dev = day.device.id; + const subject = `${dev} · ${day.bizDate}`; + const cal = day.caliberVersion; + let seq = 0; + const nid = (lv: AlertLevel) => `al-${day.bizDate}-${dev}-${lv}-${++seq}`; + const meta = (lv: AlertLevel) => ALERT_LEVELS[lv]; + const fmtPct = (x: number) => `${(x * 100).toFixed(2)}%`; + const fmtDur = (sec: number) => (sec >= 3600 ? `${(sec / 3600).toFixed(2)}h` : `${(sec / 60).toFixed(1)}min`); + + /* ── S1 安全:扫描当日事件 defCode ∈ SAFETY_EVENT_CODES。种子无安全事件 → 结构为空。 ── */ + const safetyHits = day.normalize.events.filter((e) => SAFETY_EVENT_CODES.includes(e.defCode)); + for (const e of safetyHits) { + const m = meta('S1'); + out.push({ + id: nid('S1'), level: 'S1', kind: '安全', + title: `安全回路触发 · ${e.defCode}`, + subject, metric: { label: '事件', value: e.defCode }, + fields: [ + { label: '事件码', value: e.defCode }, + { label: '校正时刻', value: e.correctedTime.slice(0, 19).replace('T', ' ') }, + { label: '响应要求', value: m.response }, + ], + action: '立即停机确认安全回路,按值班电话链上报', owner: m.owner, escalation: m.escalation, + caliber: `安全事件码表 · ${cal}`, source: '设备时间轴', state: 'OPEN', + }); + } + + /* ── S2 非计划停机:故障停机 / 空转短停桶时长 > 0(A 类非计划损失)。 ── */ + const unplanned: LossBucket[] = ['FAULT', 'IDLE_MINOR']; + for (const b of day.buckets.buckets) { + if (!unplanned.includes(b.bucket) || b.durationSec <= EPS) continue; + const m = meta('S2'); + out.push({ + id: nid('S2'), level: 'S2', kind: '非计划停机', + title: `${BUCKET_LABEL[b.bucket]} · 非计划停机`, + subject, metric: { label: '时长', value: fmtDur(b.durationSec) }, + fields: [ + { label: '损失桶', value: `${b.bucket}(${BUCKET_LABEL[b.bucket]})` }, + { label: '占 PPT', value: fmtPct(b.pctOfPlanTime) }, + { label: '事件码', value: b.eventCodes.length ? b.eventCodes.join('、') : '(节拍偏差派生)' }, + { label: '响应要求', value: m.response }, + ], + action: '5 分钟内响应,EQ + MFG 到场确认;连续 DOWN 超阈值升级邮件', + owner: m.owner, escalation: m.escalation, + caliber: `六桶损失 · PPT 分母 · ${cal}`, source: '损失结构', state: 'OPEN', + }); + } + + /* ── S3 瓶颈与计划偏移:实际 OEE 低于计划档 + Pareto Top1 损失桶。 ── */ + const target = opts.oeeTarget ?? day.tiers.planned.oee; + if (day.tiers.actual.oee < target - EPS) { + const m = meta('S3'); + out.push({ + id: nid('S3'), level: 'S3', kind: '计划偏移', + title: '实际 OEE 低于计划档', + subject, metric: { label: '实际 OEE', value: fmtPct(day.tiers.actual.oee) }, + fields: [ + { label: '计划档 OEE', value: fmtPct(target) }, + { label: '缺口', value: `${((target - day.tiers.actual.oee) * 100).toFixed(2)}pp` }, + { label: 'A / P / Q', value: `${fmtPct(day.tiers.actual.a)} / ${fmtPct(day.tiers.actual.p)} / ${fmtPct(day.tiers.actual.q)}` }, + { label: '响应要求', value: m.response }, + ], + action: '30 分钟内确认瓶颈工序,IE + PC 核对计划偏移', owner: m.owner, escalation: m.escalation, + caliber: `三层 OEE · 计划档基准 · ${cal}`, source: '总览看板', state: 'OPEN', + }); + } + const rankedBuckets = day.buckets.buckets.filter((b) => b.durationSec > EPS).sort((a, b) => b.durationSec - a.durationSec); + if (rankedBuckets.length > 0) { + const top = rankedBuckets[0]; + const m = meta('S3'); + out.push({ + id: nid('S3'), level: 'S3', kind: '瓶颈', + title: `损失 Top1 · ${BUCKET_LABEL[top.bucket]}`, + subject, metric: { label: '占 PPT', value: fmtPct(top.pctOfPlanTime) }, + fields: [ + { label: '损失桶', value: `${top.bucket}(${BUCKET_LABEL[top.bucket]})` }, + { label: '时长', value: fmtDur(top.durationSec) }, + { label: '因子', value: `${top.factor} 类` }, + { label: '响应要求', value: m.response }, + ], + action: '看板高亮 Top1 损失,进任务中心立项改善', owner: m.owner, escalation: m.escalation, + caliber: `六桶 Pareto · PPT 分母 · ${cal}`, source: '损失结构', state: 'OPEN', + }); + } + + /* ── S4 数据质量阻断:每条阻断级 DQ(06/08/12)一条告警,有权暂停发布。 ── */ + for (const code of day.dq.blockedBy) { + const rule = DQ_RULE_BY_CODE[code]; + const m = meta('S4'); + const metric = code === 'DQ-06' + ? { label: '未归因占比', value: fmtPct(day.dq.stats.unattributedPct) } + : { label: '阻断规则', value: code }; + out.push({ + id: nid('S4'), level: 'S4', kind: '数据质量', + title: `数据质量阻断 · ${code} ${rule.name}`, + subject, metric, + fields: [ + { label: '判定条件', value: rule.condition }, + { label: '处置', value: rule.action }, + { label: '响应要求', value: m.response }, + { label: '发布门禁', value: '结论暂缓发布' }, + ], + action: '当日闭环:录入台补录归因后重算当日 OEE 方可发布', owner: m.owner, escalation: m.escalation, + caliber: `DQ 治理 · 阈值 ${fmtPct(DQ_DEFAULTS.unattributedBlockPct)} · ${cal}`, source: '数据质量', state: 'ASSIGNED', + blocksPublish: true, + }); + } + + /* ── S5 观察项:缺证据未评估规则 + 未归因池待补录段(不推送、按周收敛)。 ── */ + if (day.dq.notEvaluated.length > 0) { + const m = meta('S5'); + out.push({ + id: nid('S5'), level: 'S5', kind: '观察', + title: `${day.dq.notEvaluated.length} 条 DQ 规则缺证据未评估`, + subject, metric: { label: '缺证据', value: `${day.dq.notEvaluated.length} 条` }, + fields: [ + { label: '规则', value: day.dq.notEvaluated.map((n) => n.code).join('、') }, + { label: '处置', value: '标灰不标绿,证据到位后转已评估' }, + { label: '响应要求', value: m.response }, + ], + action: '录入台待办,按周收敛;缺证据 ≠ 通过', owner: m.owner, escalation: m.escalation, + caliber: `DQ 治理 · 缺证据不视为未命中 · ${cal}`, source: '数据质量', state: 'OBSERVE', + }); + } + const pendingPool = day.segments.unknown.filter((u) => !u.resolved); + if (pendingPool.length > 0) { + const m = meta('S5'); + out.push({ + id: nid('S5'), level: 'S5', kind: '观察', + title: `未归因池 ${pendingPool.length} 段待补录`, + subject, metric: { label: '待补录', value: `${pendingPool.length} 段` }, + fields: [ + { label: '合计时长', value: fmtDur(pendingPool.reduce((s, u) => s + u.durationSec, 0)) }, + { label: '处置', value: 'D 类事件 5M1E 人工补录归因' }, + { label: '响应要求', value: m.response }, + ], + action: '录入台待办,补录后未归因占比下降、DQ-06 可能解除', owner: m.owner, escalation: m.escalation, + caliber: `未归因池 · DQ-06 计算基础 · ${cal}`, source: '录入台', state: 'OBSERVE', + }); + } + + /* 严重度降序(S1→S5);稳定排序保持同档内上面 push 的确定性次序。 */ + return out.sort((a, b) => ALERT_LEVEL_ORDER.indexOf(a.level) - ALERT_LEVEL_ORDER.indexOf(b.level)); +} + +/** 告警汇总:按档计数 + 总数 + 是否有阻断发布项。右栏汇总带与角标用,不在视图重算。 */ +export function alertStats(alerts: OeeAlert[]): { + total: number; byLevel: Record; blocksPublish: boolean; +} { + const byLevel: Record = { S1: 0, S2: 0, S3: 0, S4: 0, S5: 0 }; + for (const a of alerts) byLevel[a.level]++; + return { total: alerts.length, byLevel, blocksPublish: alerts.some((a) => a.blocksPublish) }; +} + +/* ══════════════════════════════════════════════════════════════════ + * 五类受控工具(W3-C,建议书 4.4.4 / ADR-06)——智能体唯一可用通道。 + * ★ 没有第六个工具:没有 executeSQL、没有 writeDatabase、没有 approveTask。 + * 能力边界由接口形状保证,不由提示词保证。所有指标出口统一带 caliberVersion。 + * ★ 工具实现是 L3 编排:只从既有取数入口(dayByDate/regionRollup/initialTasks…)拿数, + * 不另跑链路、不改引擎结论。任务存储由调用方注入(improvement_task 是内存态,SQLite 锁四表)。 + * ══════════════════════════════════════════════════════════════════ */ + +/** OeeDayResult → OeeResult(queryMetric 的返回数据形状,契约见 types/oee)。 */ +export function toOeeResult(day: OeeDayResult): OeeResult { + const t = day.segments.totals; + const d = day.tiers.deltaPlannedToActual; + return { + scope: { level: 'DEVICE', id: day.device.id }, + bizDate: day.bizDate, + caliberVersion: day.caliberVersion, + template: day.device.template, + ctSec: t.ctSec, pptSec: t.pptSec, pdtSec: t.pdtSec, + tiers: { theoretical: day.tiers.theoretical, planned: day.tiers.planned, actual: day.tiers.actual }, + delta: { dA: d.dA, dP: d.dP, dQ: d.dQ, total: d.total }, + buckets: day.buckets.buckets, + residualSec: day.buckets.residualSec, + unattributedPct: day.buckets.unattributedPct, + blocked: day.dq.blocked, + blockingDq: day.dq.blockedBy, + detailRef: day.detailRef, + }; +} + +/** 未接入范围的占位结果:blocked=true + gap,数值字段置 0 但**绝不展示为数字**(引擎先查 gap/blocked)。 */ +function gapOeeResult(level: OeeResult['scope']['level'], id: string, bizDate: string, caliberVersion: string): OeeResult { + const zero = { a: 0, p: 0, q: 0, oee: 0, rtSec: 0, avSec: 0, opSec: 0, outputQty: 0, goodQty: 0, ictSec: 0 }; + return { + scope: { level, id }, bizDate, caliberVersion, template: 'SRF_BUFFER', + ctSec: 0, pptSec: 0, pdtSec: 0, + tiers: { theoretical: zero, planned: zero, actual: zero }, + buckets: [], residualSec: 0, unattributedPct: 0, + blocked: true, blockingDq: [], detailRef: '', + }; +} + +/** 统一包装 ServiceResult:必带 caliberVersion + timeRange + source(闸 2 的出处三件)。 */ +function wrap(data: T, caliberVersion: string, bizDate: string, extra?: Partial>): ServiceResult { + return { + data, caliberVersion, timeRange: { from: bizDate, to: bizDate }, + source: 'DEMO_SEED', ...extra, + }; +} + +/** 工具 1 入参(建议书 4.4.4 原样)。 */ +export interface QueryMetricReq { + scope: 'DEVICE' | 'LINE' | 'REGION' | 'PERIOD'; id: string; + bizDate: string; shiftId?: string; tier?: 'theoretical' | 'planned' | 'actual'; + caliberVersion?: string; +} +/** 工具 2 入参。强制分页,pageSize ≤ 200。 */ +export interface QueryTimelineReq { + device: string; bizDate: string; page: number; pageSize: number; states?: SegmentState[]; +} +/** 工具 3 入参。只能创建与查询/流转,不能审核(无 approveTask)。 */ +export interface ManageTaskReq { + op: 'CREATE' | 'QUERY' | 'TRANSITION'; + task?: Partial & { candidateId?: string }; + taskId?: string; toState?: TaskState; +} +/** 工具 4 入参。7 类固定报表。 */ +export interface ExportReportReq { kind: ReportKind; bizDate: string; format: 'JSON' | 'CSV'; } +/** 工具 5 入参。原型为内存日志,不真发。 */ +export interface PushMessageReq { + level: AlertLevel; to: string; title: string; body: string; mergeWindowMin?: number; +} +export interface PushMessage { + level: AlertLevel; to: string; title: string; body: string; mergeWindowMin?: number; at: string; +} + +/** + * 五类受控工具契约(建议书 4.4.4)。**恰好五个方法,没有第六个**。 + * 生产原样使用此签名(契约 3):换传输不换边界。 + */ +export interface OeeTools { + queryMetric(req: QueryMetricReq): Promise>; + queryTimeline(req: QueryTimelineReq): Promise>; + manageTask(req: ManageTaskReq): Promise>; + exportReport(req: ExportReportReq): Promise>; + pushMessage(req: PushMessageReq): Promise>; +} + +/** 工具依赖注入:任务存储/时钟/操作人/消息日志由调用方持有(L3 不藏模块级可变全局)。 */ +export interface OeeToolsDeps { + getTasks: () => ImprovementTask[]; + setTasks: (tasks: ImprovementTask[]) => void; + /** 注入时钟(历史时间戳用),引擎内禁止 Date.now() */ + now: () => string; + operator?: string; + pushLog?: (msg: PushMessage) => void; +} + +const TIMELINE_MAX_PAGE_SIZE = 200; + +/** + * 构造五类受控工具。所有取数走既有 L3 入口,保证与看板同源(断言②)。 + * ★ manageTask 的 TRANSITION→DISPATCHED 必过 canDispatch 四项必填闸(断言⑨); + * 无 approveTask:智能体不可代签核(能力边界)。 + */ +export function createOeeTools(deps: OeeToolsDeps): OeeTools { + const operator = deps.operator ?? ENTRY_OPERATOR; + /* 缺口结果的兜底口径:取当日结果版本,无结果回退全局口径版本。 */ + const caliberOf = (bizDate: string): string => + dayByDate(bizDate)?.caliberVersion ?? CALIBER_CONFIG.version; + + return { + async queryMetric(req) { + const cal = req.caliberVersion ?? caliberOf(req.bizDate); + /* demo:只有锚点单机 DEVICE 给实测数;其余范围诚实标 gap,不用单机值冒充聚合(断言②)。 */ + if (req.scope === 'DEVICE' && req.id === ANCHOR_DEVICE_ID) { + const day = dayByDate(req.bizDate); + if (!day) { + return wrap(gapOeeResult('DEVICE', req.id, req.bizDate, cal), cal, req.bizDate, + { gap: noSeedNote(req.bizDate), blocked: true }); + } + const res = toOeeResult(day); + if (req.shiftId) res.shiftId = req.shiftId; + return wrap(res, day.caliberVersion, req.bizDate, + day.dq.blocked ? { blocked: true, gap: day.dq.publishNotice } : undefined); + } + const gap = req.scope === 'DEVICE' + ? `${req.id} 非锚点设备,日志贯通全链路仅 ${ANCHOR_DEVICE_ID} 一台;不显示数字也不显示 0` + : `${req.scope} 级读数为模板仿真(见「工序·工位对比」页),日志贯通仅 ${ANCHOR_DEVICE_ID} 一台,此处不冒充聚合`; + return wrap(gapOeeResult(req.scope, req.id, req.bizDate, cal), cal, req.bizDate, { gap, blocked: true }); + }, + + async queryTimeline(req) { + const cal = caliberOf(req.bizDate); + const day = req.device === ANCHOR_DEVICE_ID ? dayByDate(req.bizDate) : undefined; + if (!day) { + const gap = `${req.device} 无日志贯通结果,不显示时间轴`; + return wrap({ segments: [], total: 0 }, cal, req.bizDate, { gap, blocked: true }); + } + const all = req.states?.length + ? day.segments.segments.filter((s) => req.states!.includes(s.state)) + : day.segments.segments; + const pageSize = Math.min(Math.max(1, req.pageSize), TIMELINE_MAX_PAGE_SIZE); + const page = Math.max(1, req.page); + const start = (page - 1) * pageSize; + return wrap({ segments: all.slice(start, start + pageSize), total: all.length }, day.caliberVersion, req.bizDate); + }, + + async manageTask(req) { + const dates = activeDates(); + const cal = caliberOf(dates[dates.length - 1]); + const at = deps.now(); + if (req.op === 'QUERY') { + const tasks = deps.getTasks(); + if (req.taskId) { + const one = tasks.find((t) => t.id === req.taskId); + return wrap(one ? [one] : [], cal, at, one ? undefined : { gap: `未找到任务 ${req.taskId}` }); + } + return wrap(tasks, cal, at); + } + if (req.op === 'CREATE') { + const t = req.task; + if (!t?.id || !t.title || !t.candidateId) { + return wrap([] as ImprovementTask[], cal, at, { gap: 'CREATE 需 id/title/candidateId(优先级分由候选现算,断言⑧)' }); + } + const created = taskFromCandidate({ + id: t.id, candidateId: t.candidateId, title: t.title, + rootCauseEntity: t.rootCauseEntity ?? { type: '设备', id: ANCHOR_DEVICE_ID }, + causeClass: t.causeClass ?? 'B', evidenceChain: t.evidenceChain ?? [], + at, by: operator, scheme: t.weightScheme, + }); + deps.setTasks([...deps.getTasks(), created]); + return wrap(created, cal, at); + } + /* TRANSITION:派发必过四项必填闸;其余合法边走状态机。无审核 op。 */ + if (!req.taskId || !req.toState) { + return wrap([] as ImprovementTask[], cal, at, { gap: 'TRANSITION 需 taskId + toState' }); + } + const ctx: ClosureCtx = { at, by: operator }; + if (req.toState === 'DISPATCHED') { + const { tasks, check, result } = tryDispatch(deps.getTasks(), req.taskId, ctx); + if (!result.ok || !result.task) { + return wrap(deps.getTasks(), cal, at, + { gap: `拒绝派发:${check.missing.map((m) => m.label).join('、') || result.reason}` }); + } + deps.setTasks(tasks); + return wrap(result.task, cal, at); + } + const { tasks, result } = advanceTask(deps.getTasks(), req.taskId, req.toState, ctx); + if (!result.ok || !result.task) { + return wrap(deps.getTasks(), cal, at, { gap: result.reason }); + } + deps.setTasks(tasks); + return wrap(result.task, cal, at); + }, + + async exportReport(req) { + /* 与报表导出页同源:都走 buildReportPayload(单一来源,断言②)。 */ + const { payload, blocked, gap } = buildReportPayload(req.kind, req.bizDate, deps.getTasks(), req.format); + return wrap(payload, payload.caliberVersion, req.bizDate, + blocked || gap ? { blocked, gap } : undefined); + }, + + async pushMessage(req) { + const at = deps.now(); + const msg: PushMessage = { level: req.level, to: req.to, title: req.title, body: req.body, mergeWindowMin: req.mergeWindowMin, at }; + deps.pushLog?.(msg); + /* 原型只在站内提示,不接真实 OA/邮件通道(工具 5 白名单)。 */ + return wrap({ queued: true }, caliberOf(activeDates()[activeDates().length - 1]), at); + }, + }; +} + +/** 7 类报表的行数据(全部从当日读数现算,不编数)。WEEKLY/MONTHLY 仅 3 日种子,诚实标缺口。 */ +function reportRows(kind: ReportKind, day: OeeDayResult, tasks: ImprovementTask[]): Record[] { + const a = day.tiers.actual; + switch (kind) { + case 'SHIFT_OEE': + /* 班次 OEE 速览:原型 OEE 为日级,班次筛选不改变日级口径(AXIS_SCOPE_NOTE)。 */ + return [{ scope: '日级(班次筛选不改变日级 OEE)', bizDate: day.bizDate, a: a.a, p: a.p, q: a.q, oee: a.oee }]; + case 'DAILY': + return [{ bizDate: day.bizDate, device: day.device.id, a: a.a, p: a.p, q: a.q, oee: a.oee, pptSec: day.segments.totals.pptSec, unattributedPct: day.buckets.unattributedPct, blocked: day.dq.blocked }]; + case 'ANOMALY': + return deriveAlerts(day).map((x) => ({ id: x.id, level: x.level, kind: x.kind, title: x.title, subject: x.subject, state: x.state, blocksPublish: x.blocksPublish })); + case 'CLOSURE': + return tasks.map((t) => ({ id: t.id, title: t.title, state: t.state, owner: t.owner ?? '', priorityScore: t.priorityScore, weightScheme: t.weightScheme, causeClass: t.causeClass })); + case 'AUDIT': + /* TraceResult:值在 target.value,行号/来源在 evidence[](可能多条,取首条);wired 标是否真贯通到行号。 */ + return traceDay(day).map((tr) => ({ + target: tr.target.label, kind: tr.kind, value: tr.target.value, unit: tr.target.unit, + lineNo: tr.evidence[0]?.lineNo ?? null, source: tr.evidence[0]?.source ?? null, wired: tr.wired, + })); + case 'WEEKLY': + case 'MONTHLY_CALIBER': { + /* 不足周/月:诚实标缺口,不编累计数。 */ + const dates = activeDates(); + const note = `原型仅 ${dates.length} 日种子(${dates.join('/')}),不足周/月累计;不编数`; + return [{ note, bizDate: day.bizDate }]; + } + default: + return []; + } +} + +/** 工具契约自检:供校验脚本与「说明与对照」页引用。恰好五方法,无 SQL/写库/审核。 */ +export function toolsStats() { + const sample = createOeeTools({ getTasks: () => [], setTasks: () => {}, now: () => '2026-09-03T00:00:00' }); + const methods = Object.keys(sample); + return { + methodCount: methods.length, + methods, + exactlyFive: methods.length === 5, + noSql: !methods.some((m) => /sql|executeSQL/i.test(m)), + noWriteDb: !methods.some((m) => /writeDatabase|writeDb/i.test(m)), + noApprove: !methods.some((m) => /approve/i.test(m)), + boundary: '可读、可算、可建议、可派单;不可改数、不可代签核', + adr: 'ADR-06:智能体只走 5 类受控工具,不直连数据库,无 NL2SQL', + }; +} + +/* ══════════════════════════════════════════════════════════════════ + * W4-B 编排:报表导出 / 预测示意 / 2D 线体图(建议书 §5.2.2 no.9/12/19)。 + * + * ★ 三页都只消费既有取数入口,不另跑链路、不二次计算 OEE(断言②): + * 报表 → reportRows(与 exportReport 工具同源); + * 预测 → forecast 纯规则引擎(四门槛全未达,恒标「示意·非模型输出」); + * 线体图 → DEVICES 台账 + 当日 anchor/srf/ft/aslt 读数,状态灯=数据可得性/可发布性。 + * ★ 本层不做任何"修正":无种子就照实给缺口,阻断就照实标 warn,绝不拿单机值冒充聚合。 + * ══════════════════════════════════════════════════════════════════ */ + +/** 七类固定报表的选择器顺序(与 ReportKind 契约一致)。 */ +export const REPORT_KINDS: ReportKind[] = ['SHIFT_OEE', 'DAILY', 'ANOMALY', 'WEEKLY', 'MONTHLY_CALIBER', 'CLOSURE', 'AUDIT']; + +export interface ReportBuild { payload: ReportPayload; blocked: boolean; gap?: string; } + +/** + * 同步构造报表载荷(报表导出页与 exportReport 工具共用,单一来源)。 + * 无种子日 → 空行 + 缺口(不编数);DQ 阻断 → 照实标 blocked + publishNotice。 + * WEEKLY/MONTHLY_CALIBER 的「仅 3 日种子」诚实说明落在行内 note,不假装有累计数。 + */ +export function buildReportPayload(kind: ReportKind, bizDate: string, tasks: ImprovementTask[], format: 'JSON' | 'CSV' = 'JSON'): ReportBuild { + const day = dayByDate(bizDate); + const cal = day?.caliberVersion ?? CALIBER_CONFIG.version; + if (!day) { + return { + payload: { kind, bizDate, caliberVersion: cal, rows: [], format }, + blocked: true, gap: `${noSeedNote(bizDate)},报表为空(不编数)`, + }; + } + const payload: ReportPayload = { kind, bizDate, caliberVersion: cal, rows: reportRows(kind, day, tasks), format }; + return day.dq.blocked ? { payload, blocked: true, gap: day.dq.publishNotice } : { payload, blocked: false }; +} + +/** + * 报表载荷 → CSV(纯序列化,RFC4180:含逗号/引号/换行的字段加双引号,内部引号翻倍)。 + * 表头取所有行键的并集(首见顺序),空行集返回空串。CRLF 行尾。 + * ★ 不加 BOM:BOM 由视图下载时按 Excel 兼容需要前置,保持序列化器纯净可单测。 + */ +export function reportToCsv(payload: ReportPayload): string { + const rows = payload.rows; + if (rows.length === 0) return ''; + const keys: string[] = []; + for (const r of rows) for (const k of Object.keys(r)) if (!keys.includes(k)) keys.push(k); + const esc = (v: unknown): string => { + const s = v === null || v === undefined ? '' : String(v); + return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; + }; + const lines = [keys.map(esc).join(',')]; + for (const r of rows) lines.push(keys.map((k) => esc(r[k])).join(',')); + return lines.join('\r\n'); +} + +/** 报表文件名:oee_<类>_<业务日>_<口径版本>.。口径版本随文件留痕(断言⑩)。 */ +export function reportFileName(payload: ReportPayload): string { + const ext = payload.format === 'CSV' ? 'csv' : 'json'; + return `oee_${payload.kind}_${payload.bizDate}_${payload.caliberVersion}.${ext}`; +} + +/* ── 预测示意(规则外推,非模型)───────────────────────────────────── */ + +export interface ForecastOfDay { + bizDate: string; + available: boolean; + gap?: string; + /** 当日锚点实际 OEE(0–1),无种子为 null */ + anchorOee: number | null; + /** 截至当日的历史 OEE 序列(升序),供趋势示意 */ + history: OeeTrendPoint[]; + stopRisk: StopRisk | null; + oee4h: Oee4hForecast | null; +} + +/** + * 当日预测示意:从锚点当日六桶 / DQ / 历史序列现算入参,喂给 forecast 纯规则引擎。 + * ★ 只有锚点单机有日志贯通结果;无种子日不外推(available=false + 缺口),绝不编一个预测数。 + */ +export function forecastOfDay(bizDate: string): ForecastOfDay { + /* T7:OEE 缺口(DEK 无 NG/良率源 → Q/OEE 不给数)时历史序列只收有限值, + 不把 NaN 喂进外推/图表。 */ + const history: OeeTrendPoint[] = dekDays() + .filter((d) => d.bizDate <= bizDate && Number.isFinite(d.tiers.actual.oee)) + .map((d) => ({ bizDate: d.bizDate, oee: d.tiers.actual.oee })); + const day = dayByDate(bizDate); + if (!day) { + return { + bizDate, available: false, anchorOee: null, history, stopRisk: null, oee4h: null, + gap: `${noSeedNote(bizDate)},不外推`, + }; + } + const faultSec = day.buckets.buckets.find((b) => b.bucket === 'FAULT')?.durationSec ?? 0; + const idleMinorSec = day.buckets.buckets.find((b) => b.bucket === 'IDLE_MINOR')?.durationSec ?? 0; + const stopRisk = extrapolateStopRisk({ + pptSec: day.segments.totals.pptSec, faultSec, idleMinorSec, + blocked: day.dq.blocked, unattributedPct: day.buckets.unattributedPct, + }); + /* 停机风险来自六桶实测,照常外推;OEE 外推必须有有限锚点值, + 缺口时 oee4h=null+gap 签,不拿 NaN/0 冒充可外推。 */ + const anchorOee = day.tiers.actual.oee; + if (!Number.isFinite(anchorOee)) { + return { + bizDate, available: true, anchorOee: null, history, stopRisk, oee4h: null, + gap: '当日实际 OEE 缺口(Q 无良率源,G 缺口):不做 OEE 外推、不显示 0;停机风险仍按后端实测六桶规则外推。', + }; + } + const oee4h = extrapolateOee4h({ + anchorOee, history, + blocked: day.dq.blocked, unattributedPct: day.buckets.unattributedPct, + }); + return { bizDate, available: true, anchorOee, history, stopRisk, oee4h }; +} + +/* ── 2D 线体图(SVG 拓扑 + 状态灯 + 瓶颈定位)──────────────────────── */ + +/** 节点读数来源:ANCHOR_LOG=日志贯通实测;*_SIM=模板仿真;NONE=无读数(缺口)。 */ +export type LineMapSource = 'ANCHOR_LOG' | 'SRF_SIM' | 'FT_SIM' | 'ASLT_SIM' | 'NONE'; +/** 状态灯=数据可得性/可发布性,不是绩效红绿灯:ok 有读数可发布 / warn 有读数但阻断或存疑 / gap 无读数。 */ +export type LineMapLight = 'ok' | 'warn' | 'gap'; + +export interface LineMapSite { siteId: number; enabledPct: number; } + +export interface LineMapNode { + deviceId: string; name: string; lineId: string; region: DeviceMaster['region']; + station: string; mainPathSeq?: number; countsForOee: boolean; hasLog: boolean; + source: LineMapSource; + oee: number | null; a: number | null; p: number | null; q: number | null; + qtySource?: 'ANCHOR' | 'SIM'; + blocked: boolean; ok: boolean; bottleneck: boolean; + light: LineMapLight; note: string; + /** ASLT 12 Site 使能占比(0–1),由种子使能窗口 / 活跃窗口现算 */ + siteCount?: number; sites?: LineMapSite[]; + /** BUF001 中间缓存:不计 OEE,只作缓冲解耦输入 */ + buffer?: { capacity: number; minCapacity: number; occupancyPct: number; decoupled: boolean; fullyDecoupled: boolean }; +} + +/** + * 当日 17 台台账设备的线体图节点。状态灯诚实反映数据可得性: + * DEK001=ANCHOR_LOG(唯一日志贯通);DCP005=SRF_SIM(下游代表站); + * FT 三台=FT_SIM;ASLT=ASLT_SIM(含 12 Site 使能);其余 SRF 台账在但无仿真读数=NONE/gap; + * BUF001 不计 OEE,给缓冲占用率。瓶颈环来自 LINE_BY_ID.bottleneckDeviceId(SRF→DCP005)。 + * ★ 实时运行/停机需直采通道,原型状态灯只表达数据可得性,不冒充实时设备状态。 + */ +export function lineMapNodes(bizDate: string): LineMapNode[] { + const day = dayByDate(bizDate); + const srf = srfDayByDate(bizDate); + const ft = ftDayByDate(bizDate); + const aslt = asltDayByDate(bizDate); + const asltInput = asltSeed().days.find((d) => d.bizDate === bizDate)?.input; + + const nodes = DEVICES.map((d): LineMapNode => { + const bottleneck = LINE_BY_ID[d.lineId]?.bottleneckDeviceId === d.id; + const base = { + deviceId: d.id, name: d.name, lineId: d.lineId, region: d.region, station: d.station, + mainPathSeq: d.mainPathSeq, countsForOee: d.countsForOee, hasLog: d.hasLog, bottleneck, + }; + + /* 中间缓存:不生产、不计 OEE,只作缓冲解耦输入。 */ + if (!d.countsForOee) { + const buf = srf?.result.buffer; + const occupancyPct = buf && buf.capacity > 0 && buf.levelTrace.length > 0 + ? buf.levelTrace.reduce((s, p) => s + p.level, 0) / buf.levelTrace.length / buf.capacity + : 0; + return { + ...base, source: 'NONE', oee: null, a: null, p: null, q: null, + blocked: false, ok: true, light: 'gap', + note: '中间缓存不生产、不计 OEE;只作缓冲解耦输入(占用率由上下游进出板反推)', + buffer: buf ? { capacity: buf.capacity, minCapacity: buf.minCapacity, occupancyPct, decoupled: buf.decoupled, fullyDecoupled: buf.fullyDecoupled } : undefined, + }; + } + + /* 锚点 DEK001:日志贯通全链路唯一一台,给实测三档。 */ + if (d.id === ANCHOR_DEVICE_ID) { + if (!day) { + return { ...base, source: 'NONE', oee: null, a: null, p: null, q: null, blocked: true, ok: false, light: 'gap', note: `${bizDate} 无锚点日志,不显示数字也不显示 0` }; + } + const t = day.tiers.actual; + const blocked = day.dq.blocked; + return { + ...base, source: 'ANCHOR_LOG', oee: t.oee, a: t.a, p: t.p, q: t.q, qtySource: 'ANCHOR', + blocked, ok: !blocked, light: blocked ? 'warn' : 'ok', + note: '日志贯通全链路唯一一台:EVENT.DAT→事件→状态段→六桶→三档 OEE,可下钻到行号', + }; + } + + /* SRF 其余台:只有 DCP005 在仿真代表站里,其它台账在但无读数。 */ + if (d.region === 'SRF') { + const st = srf?.result.stations.find((s) => s.deviceId === d.id); + if (!st) { + return { + ...base, source: 'NONE', oee: null, a: null, p: null, q: null, blocked: false, ok: true, light: 'gap', + note: srf ? 'SRF 仿真只建 DEK+DCP 两台代表站,本台无仿真读数(台账在、日志通道未接)' : `${bizDate} 无 SRF 种子`, + }; + } + const blocked = srf!.dq.blocked; + const ok = srf!.result.ok; + return { + ...base, source: 'SRF_SIM', oee: st.oee, a: st.a, p: st.p, q: st.q, qtySource: st.qtySource, + blocked, ok, light: blocked || !ok ? 'warn' : 'ok', + note: st.qtySource === 'SIM' ? '流体仿真产出,P 恒为 1(模型产物,非实测性能率)' : '产出锚点计数,P 反映速度损失', + }; + } + + /* FT 三台:多因子连乘仿真。 */ + if (d.region === 'FT') { + const r = ft?.devices.find((x) => x.deviceId === d.id); + if (!r) { + return { ...base, source: 'NONE', oee: null, a: null, p: null, q: null, blocked: false, ok: true, light: 'gap', note: `${bizDate} 无 FT 种子` }; + } + return { + ...base, source: 'FT_SIM', oee: r.oee, a: r.a, p: r.p, q: r.q, + blocked: false, ok: r.ok, light: r.ok ? 'ok' : 'warn', + note: `FT 多因子连乘(${r.operandSource} 操作数);P=1−三项损失占比,不用 ICT`, + }; + } + + /* ASLT:事件驱动·活跃窗口口径,含 12 Site 使能占比。 */ + if (d.region === 'ASLT') { + const r = aslt?.result; + if (!r) { + return { ...base, source: 'NONE', oee: null, a: null, p: null, q: null, blocked: false, ok: true, light: 'gap', note: `${bizDate} 无 ASLT 种子` }; + } + const activeSec = r.activeWindowSec; + const sites: LineMapSite[] = []; + for (let siteId = 1; siteId <= r.siteCount; siteId++) { + const wins = (asltInput?.siteEnable ?? []).filter((w) => w.siteId === siteId); + const enabledPct = activeSec > 0 ? mergedDurationSec(wins) / activeSec : 0; + sites.push({ siteId, enabledPct: Math.min(1, Math.max(0, enabledPct)) }); + } + return { + ...base, source: 'ASLT_SIM', oee: r.oee, a: r.a, p: r.p, q: r.q, + blocked: false, ok: r.ok, light: r.ok ? 'ok' : 'warn', siteCount: r.siteCount, sites, + note: '事件驱动·活跃窗口口径;P=12 站使能总时长 /(12×活跃窗口)', + }; + } + + return { ...base, source: 'NONE', oee: null, a: null, p: null, q: null, blocked: false, ok: true, light: 'gap', note: '未接入' }; + }); + + /* 非有限值统一归一为 null;视图缺口守卫只认 null,NaN 不得漏进页面。 */ + const finOrNull = (v: number | null) => (v != null && Number.isFinite(v) ? v : null); + for (const n of nodes) { + n.oee = finOrNull(n.oee); n.a = finOrNull(n.a); n.p = finOrNull(n.p); n.q = finOrNull(n.q); + } + + return nodes; +} + +/** 线体图自检:供校验脚本与页面引用,数字一律现算。 */ +export function lineMapStats(nodes: LineMapNode[]) { + const byLight: Record = { ok: 0, warn: 0, gap: 0 }; + const bySource: Record = { ANCHOR_LOG: 0, SRF_SIM: 0, FT_SIM: 0, ASLT_SIM: 0, NONE: 0 }; + for (const n of nodes) { byLight[n.light] += 1; bySource[n.source] += 1; } + return { + total: nodes.length, + oeeDevices: nodes.filter((n) => n.countsForOee).length, + byLight, bySource, + bottleneck: nodes.filter((n) => n.bottleneck).map((n) => n.deviceId), + wired: bySource.ANCHOR_LOG, + sim: bySource.SRF_SIM + bySource.FT_SIM + bySource.ASLT_SIM, + gap: byLight.gap, + sites: nodes.reduce((a, n) => a + (n.siteCount ?? 0), 0), + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/oeeTime.ts b/src/modules/tfamd-oee/lib/oeeTime.ts new file mode 100644 index 0000000..b7eacaf --- /dev/null +++ b/src/modules/tfamd-oee/lib/oeeTime.ts @@ -0,0 +1,259 @@ +/** + * OEE 回放游标:日 / 班次 / 小时三级(ADR-03 · 实测 M6)。 + * + * ★ 与旧 `lib/time.ts` 的分工: + * - 旧月轴(12 期 2025-11~2026-10)**只留给"月度口径报告"页**,本文件不动它。 + * - OEE 全站用**日轴**:种子只覆盖 3 个业务日,造 12 期就是编数据。 + * + * ★ 三级游标的作用范围必须说清楚,不假装能力: + * - **日级**:指标树/看板/抬头全部按日重算取值与定级(valuesOf 逐日现算)。 + * - **班次/小时级**:只作用于**时间轴与状态段筛选**(段自带 shiftId 与起止时刻)。 + * 班次级 OEE 需要按班次重算 PPT 分母,属 W2 范围;在此之前**不提供班次级 OEE 数字**, + * 而不是把日级值除以 3 摊一个出来。 + * + * API 形状刻意与 time.ts 对齐(valueAt/gapAt/achieveAt/statusAt/levelAt/momAt/seriesOf/ + * projectAt/projectTree),下游组件换 import 即可,不必逐个改取值点。 + */ +import type { MetricNode } from '../data/sqlite'; +import { SEED_DATES, SEED_DIRTY_DATE, shiftsForDate, ctWindowForDate } from '../data/oee/devices'; +import type { StateSegment } from '../types/oee'; + +/** 回放期数=种子业务日数,不补期。 */ +export let PERIOD_COUNT: number = SEED_DATES.length; +/** 默认停在最后一期(当期),与旧月轴语义一致 */ +export let CURRENT_PERIOD: number = PERIOD_COUNT - 1; + +/** 轴覆盖:null=内置三日种子。 */ +let axisDates: readonly string[] | null = null; +function axis(): readonly string[] { return axisDates ?? SEED_DATES; } + +/** 重设日轴。传 null 复位回内置种子轴。只改轴,不造期。 + * currentPeriod:不传则停在最后一期(demo 语义)。 */ +export function setAxisDates(dates: string[] | null, currentPeriod?: number): void { + axisDates = dates && dates.length > 0 ? [...dates] : null; + PERIOD_COUNT = axis().length; + CURRENT_PERIOD = currentPeriod !== undefined && Number.isFinite(currentPeriod) + ? Math.max(0, Math.min(PERIOD_COUNT - 1, Math.floor(currentPeriod))) + : PERIOD_COUNT - 1; +} + +export type AxisLevel = 'day' | 'shift' | 'hour'; + +export const AXIS_SCOPE_NOTE = + '日级游标重算指标树与看板取值;班次/小时级游标只筛选时间轴与状态段。' + + '班次级 OEE 需按班次重算 PPT 分母(W2 接入),在此之前不提供班次级 OEE 数字,不做日均摊派。'; +export const SHIFT_ASSUMPTION_NOTE = '班次时刻为演示假设(3×8h),待客户排班表确认'; + +/** 游标越界即夹回,不抛错也不静默造一期 */ +export function clampPeriod(period: number): number { + if (!Number.isFinite(period)) return CURRENT_PERIOD; + return Math.max(0, Math.min(PERIOD_COUNT - 1, Math.floor(period))); +} + +/** 期标签:2026-09-01(日轴用完整业务日,不用"9月"这种月轴标签) */ +export function periodLabel(period: number): string { + return axis()[clampPeriod(period)]; +} +/** 时间轴刻度短标签:09-01 */ +export function periodShortLabel(period: number): string { + return periodLabel(period).slice(5); +} +/** 回放期内的业务日(与 metric_trend.period 同值) */ +export function periodDate(period: number): string { + return periodLabel(period); +} +/** 该业务日的 CT 窗口 */ +export function periodWindow(period: number): { start: string; end: string } { + return ctWindowForDate(periodLabel(period)); +} +/** 异常日所在期:演示"结论暂缓发布"用;轴无该日则停在当期 */ +export function dirtyPeriod(): number { + const i = axis().indexOf(SEED_DIRTY_DATE); + return i < 0 ? CURRENT_PERIOD : i; +} + +/* ── 取值与定级:与 time.ts 同形,但轴是日 ─────────────────────────── */ + +/** 游标时点的指标值:trend 缺失/该期未定义时回退当期值; + * ★ null=G 缺口,返回 NaN 交由 pctOrGap 渲染「—」,不回退当期值冒充。 */ +export function valueAt(n: MetricNode, period: number): number { + const t = n.trend; + if (!t || !t.length) return n.value; + const v = t[clampPeriod(period)]; + if (v === undefined) return n.value; + return v === null ? NaN : v; +} + +/** 游标时点偏差(已按 polarity 归一:正=优于目标) */ +export function gapAt(n: MetricNode, period: number): number { + const raw = valueAt(n, period) - n.target; + return +(n.polarity === 'down' ? -raw : raw).toFixed(2); +} + +/** 游标时点达成率(%),越低越好类取倒数口径 */ +export function achieveAt(n: MetricNode, period: number): number { + const v = valueAt(n, period); + if (!n.target) return 100; + const r = n.polarity === 'down' ? (n.target / (v || 1)) * 100 : (v / n.target) * 100; + return +Math.min(r, 999).toFixed(1); +} + +/** + * 动态定级:28 条口径未定义红黄绿带宽,且指标树里 alert_threshold === target, + * 故实际只有 green/red 二值。保留 yellow 分支是为了将来口径签字后加带宽时不改调用方, + * **不是**现在就能给出黄色——阈值相等时该分支不可达。 + */ +export function statusAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' { + const v = valueAt(n, period); + const better = n.polarity === 'down' ? v <= n.target : v >= n.target; + if (better) return 'green'; + const safe = n.polarity === 'down' ? v <= n.alert_threshold : v >= n.alert_threshold; + return safe ? 'yellow' : 'red'; +} + +/** 图谱/看板取色:当期沿用主数据定级,历史期由游标值反推 */ +export function levelAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' { + return clampPeriod(period) === CURRENT_PERIOD + ? (n.alert_level === 'red' || n.alert_level === 'yellow' ? n.alert_level : 'green') + : statusAt(n, period); +} + +/** 环比上一业务日(原始值差,不做 polarity 归一,由调用方按语义着色) */ +export function momAt(n: MetricNode, period: number): number | null { + const p = clampPeriod(period); + if (p <= 0) return null; + return +(valueAt(n, p) - valueAt(n, p - 1)).toFixed(2); +} + +/** 完整日序列(trend 缺失时以当期值补齐,保证柱子数量恒等于期数) */ +export function seriesOf(n: MetricNode): number[] { + return Array.from({ length: PERIOD_COUNT }, (_, i) => valueAt(n, i)); +} + +/** 游标投影:把该时点的值与定级贴回节点,下游当期口径工具无需改造即变成时点口径 */ +export function projectAt(n: MetricNode, period: number): MetricNode { + const p = clampPeriod(period); + if (p === CURRENT_PERIOD) return n; + return { ...n, value: valueAt(n, p), alert_level: statusAt(n, p) }; +} + +/** 整棵树投影 */ +export function projectTree(nodes: MetricNode[], period: number): MetricNode[] { + const p = clampPeriod(period); + if (p === CURRENT_PERIOD) return nodes; + return nodes.map((n) => ({ + ...projectAt(n, p), + children: n.children ? projectTree(n.children, p) : undefined, + })); +} + +/* ── 班次 / 小时级游标 ─────────────────────────────────────────────── */ + +export interface OeeCursor { + level: AxisLevel; + /** 业务日下标 0..PERIOD_COUNT-1 */ + day: number; + /** 班次下标 0..2(仅 level!=='day' 时有意义) */ + shift: number; + /** 小时 0..23(仅 level==='hour' 时有意义) */ + hour: number; +} + +export const DEFAULT_CURSOR: OeeCursor = { level: 'day', day: CURRENT_PERIOD, shift: 0, hour: 0 }; + +export function clampCursor(c: OeeCursor): OeeCursor { + const day = clampPeriod(c.day); + const shifts = shiftsForDate(periodLabel(day)); + const shift = Math.max(0, Math.min(shifts.length - 1, Math.floor(c.shift) || 0)); + const hour = Math.max(0, Math.min(23, Math.floor(c.hour) || 0)); + return { level: c.level, day, shift, hour }; +} + +/** 游标对应的班次窗口(日级返回全部三班) */ +export function cursorShifts(c: OeeCursor): { id: string; start: string; end: string; bizDate: string }[] { + const cc = clampCursor(c); + const all = shiftsForDate(periodLabel(cc.day)); + return cc.level === 'day' ? all : [all[cc.shift]]; +} + +/** 游标对应的 ISO 时间窗:日级=CT 窗口,班次级=该班,小时级=该小时 */ +export function cursorWindow(c: OeeCursor): { start: string; end: string } { + const cc = clampCursor(c); + const date = periodLabel(cc.day); + if (cc.level === 'day') return ctWindowForDate(date); + const sh = shiftsForDate(date)[cc.shift]; + if (cc.level === 'shift') return { start: sh.start, end: sh.end }; + const base = Date.parse(sh.start); + const hourStart = base + cc.hour * 3600 * 1000; + return { + start: new Date(hourStart).toISOString().replace('.000Z', 'Z'), + end: new Date(hourStart + 3600 * 1000).toISOString().replace('.000Z', 'Z'), + }; +} + +/** 游标读数区文案 */ +export function cursorLabel(c: OeeCursor): string { + const cc = clampCursor(c); + const date = periodLabel(cc.day); + if (cc.level === 'day') return date; + const sh = shiftsForDate(date)[cc.shift]; + const name = sh.id.split('-').pop() ?? sh.id; + if (cc.level === 'shift') return `${date} ${name}班`; + return `${date} ${String(cc.hour).padStart(2, '0')}:00–${String((cc.hour + 1) % 24).padStart(2, '0')}:00`; +} + +/** + * 按游标筛选状态段:段与游标窗口有交集即入选,并裁到窗口内。 + * 这是**筛选**,不是重算 OEE——班次级分母口径未定版前不给班次级 OEE 数字。 + */ +export function segmentsInCursor( + segments: StateSegment[], c: OeeCursor, +): { segment: StateSegment; clippedSec: number }[] { + const w = cursorWindow(c); + const a = Date.parse(w.start) / 1000; + const b = Date.parse(w.end) / 1000; + const out: { segment: StateSegment; clippedSec: number }[] = []; + for (const s of segments) { + const sa = Date.parse(s.start) / 1000; + const sb = Date.parse(s.end) / 1000; + const x = Math.max(sa, a); + const y = Math.min(sb, b); + if (y > x) out.push({ segment: s, clippedSec: y - x }); + } + return out; +} + +/** 日轴自检:供校验脚本引用 */ +export function oeeTimeStats() { + const n: MetricNode = { + id: 0, code: 'PROBE', name_zh: '探针', parent_code: '', level: 0, dimension: 'oee', + value: 50, target: 60, unit: '%', frequency: '日', alert_threshold: 60, + alert_level: 'red', polarity: 'up', weight: 0, formula: '', owner: '', desc_zh: '', + updated_at: '', trend: [10, 20, 50], + }; + return { + periodCount: PERIOD_COUNT, + currentPeriod: CURRENT_PERIOD, + periods: Array.from({ length: PERIOD_COUNT }, (_, i) => periodLabel(i)), + dirtyPeriod: dirtyPeriod(), + axisScopeNote: AXIS_SCOPE_NOTE, + shiftAssumptionNote: SHIFT_ASSUMPTION_NOTE, + /** 越界夹回,不造期 */ + clampWorks: clampPeriod(-5) === 0 && clampPeriod(99) === CURRENT_PERIOD && clampPeriod(NaN) === CURRENT_PERIOD, + /** 投影后当期值不变、历史期取 trend */ + projectionWorks: projectAt(n, CURRENT_PERIOD).value === 50 && projectAt(n, 0).value === 10, + /** 警戒线=目标线 → 二值定级,yellow 分支不可达 */ + binaryGrading: statusAt(n, 0) === 'red' && statusAt(n, CURRENT_PERIOD) === 'red' + && statusAt({ ...n, trend: [70, 70, 70] }, 0) === 'green', + /** 日级游标窗口=CT 24h */ + dayWindowIsCt: (() => { + const w = cursorWindow(DEFAULT_CURSOR); + return (Date.parse(w.end) - Date.parse(w.start)) / 1000 === 86400; + })(), + /** 小时级游标窗口=1h */ + hourWindowIsOneHour: (() => { + const w = cursorWindow({ level: 'hour', day: 0, shift: 1, hour: 9 }); + return (Date.parse(w.end) - Date.parse(w.start)) / 1000 === 3600; + })(), + }; +} \ No newline at end of file diff --git a/src/modules/tfamd-oee/lib/process.ts b/src/modules/tfamd-oee/lib/process.ts new file mode 100644 index 0000000..1766f73 --- /dev/null +++ b/src/modules/tfamd-oee/lib/process.ts @@ -0,0 +1,195 @@ +/** + * 研产供销端到端流程模型(过程指标层)。 + * + * 与指标树的分工:指标树看的是**结果指标**(收入、毛利率、OEE…), + * 这里看的是**过程指标**——一批订单/项目在每一段价值链上停留多久、流过多少、 + * 一次通过多少、返工多少。两者共用同一批 metric_node 作为"关联指标", + * 所以点击流程卡上的指标片仍然能联动中央看板。 + * + * 过程量是确定性模拟:同一 (stage, period) 永远得到同一读数, + * 拖动底部时间轴会沿 12 期平滑演变(改善/恶化趋势由各段 improve 决定), + * 不会像 Math.random() 那样每次刷新都变,演示与复盘都可复现。 + */ + +export type FlowIcon = 'target' | 'flask' | 'cart' | 'factory' | 'truck' | 'cash'; + +export interface FlowStage { + key: string; + zh: string; + /** 责任口 · 这一段把什么变成什么 */ + roleZh: string; + icon: FlowIcon; + /** 关联的结果/过程指标(metric_node.code),点击联动中央看板 */ + codes: string[]; + /** 停留天数基线 / 目标(越短越好) */ + dwell: number; + dwellTarget: number; + /** 月流转量基线(批次口径) */ + flow: number; + flowUnitZh: string; + /** 一次通过率 % 基线 / 目标(越高越好) */ + fpqc: number; + fpqcTarget: number; + /** 月返工/退回件数基线 / 目标(越少越好) */ + rework: number; + reworkTarget: number; + /** 12 期改善强度:+1 = 全期持续变好,-1 = 持续变差 */ + improve: number; +} + +/** 研 → 产 → 供 → 销 的完整链路,六段 */ +export const STAGES: FlowStage[] = [ + { + key: 'demand', zh: '需求与方案', + roleZh: '市场部 · 商机到方案', + icon: 'target', codes: ['M01', 'DR-12', 'DR-13'], + dwell: 12.4, dwellTarget: 9.0, flow: 620, flowUnitZh: '条商机', + fpqc: 72.5, fpqcTarget: 80, rework: 88, reworkTarget: 60, + improve: -0.6, + }, + { + key: 'rd', zh: '研发设计', + roleZh: '研究院 · 方案到样机', + icon: 'flask', codes: ['G02', 'G04', 'G06', 'G07'], + dwell: 42.0, dwellTarget: 36.0, flow: 42, flowUnitZh: '个项目', + fpqc: 84.0, fpqcTarget: 90, rework: 46, reworkTarget: 38, + improve: 0.45, + }, + { + key: 'buy', zh: '采购齐套', + roleZh: '采购本部 · 订单到齐套', + icon: 'cart', codes: ['K01', 'DR-05', 'DR-15'], + dwell: 8.6, dwellTarget: 7.0, flow: 1240, flowUnitZh: '张采购单', + fpqc: 91.2, fpqcTarget: 94, rework: 104, reworkTarget: 80, + improve: 0.2, + }, + { + key: 'mfg', zh: '生产制造', + roleZh: '制造本部 · 投产到下线', + icon: 'factory', codes: ['P01', 'P02', 'DR-07', 'DR-09'], + dwell: 3.6, dwellTarget: 3.2, flow: 3600, flowUnitZh: '张工单', + fpqc: 96.4, fpqcTarget: 97.5, rework: 132, reworkTarget: 110, + improve: 0.8, + }, + { + key: 'deliver', zh: '仓储交付', + roleZh: '供应链本部 · 计划到签收', + icon: 'truck', codes: ['R12', 'E01', 'DR-14'], + dwell: 5.2, dwellTarget: 4.5, flow: 2900, flowUnitZh: '张出货单', + fpqc: 94.8, fpqcTarget: 96.5, rework: 68, reworkTarget: 55, + improve: 0.3, + }, + { + key: 'cash', zh: '服务与回款', + roleZh: '财务/服务部 · 交付到回款', + icon: 'cash', codes: ['E03', 'Q08', 'M04', 'R13'], + dwell: 9.4, dwellTarget: 8.0, flow: 480, flowUnitZh: '件服务工单', + fpqc: 88.6, fpqcTarget: 92, rework: 55, reworkTarget: 45, + improve: -0.25, + }, +]; + +/** 两频正弦叠加:让 12 期有起伏但不毛躁,同 seed 同 period 恒定 */ +function wave(period: number, seed: number) { + const p = period + 1; + return Math.sin(p * 0.78 + seed * 1.7) * 0.55 + Math.sin(p * 0.31 + seed * 0.9) * 0.45; +} + +/** 全链流量随季节缓涨(年末交付高峰),到当期约 +12% */ +const season = (period: number) => 1 + 0.12 * (period - 5.5) / 5.5; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); +const r1 = (v: number) => +v.toFixed(1); + +export interface StageStats { + /** 本段平均停留(周期)天数 */ + dwell: number; + dwellTarget: number; + /** 月流转量 */ + flow: number; + /** 一次通过率 % */ + fpqc: number; + fpqcTarget: number; + /** 月返工/退回件数 */ + rework: number; + reworkTarget: number; + /** 在制品:Little 法则 WIP = 吞吐 × 停留 / 30 */ + wip: number; + /** 段达成率 %(停留 40% + 一次通过 40% + 返工 20%) */ + score: number; + status: 'green' | 'yellow' | 'red'; + /** 相对上期的停留变化(天),负 = 在提速 */ + dwellDelta: number | null; +} + +export function stageStats(index: number, period: number): StageStats { + const s = STAGES[index]; + const t = (period - 5.5) / 5.5; // -1 → 0 → +1 的全期趋势轴 + const drift = (k: number) => wave(period, index * 7 + k); + + const dwell = dwellAt(index, period); + const fpqc = r1(clamp(s.fpqc + s.improve * 3.4 * t + drift(2) * 1.3, 55, 99.5)); + const flow = Math.round(s.flow * season(period) * (1 + drift(3) * 0.035)); + const rework = Math.max(0, Math.round(s.rework * (1 - s.improve * 0.16 * t - drift(4) * 0.05))); + const wip = Math.round(flow * dwell / 30); + + const score = ( + clamp(s.dwellTarget / dwell, 0.6, 1.2) * 0.4 + + clamp(fpqc / s.fpqcTarget, 0.6, 1.2) * 0.4 + + clamp(s.reworkTarget / Math.max(1, rework), 0.6, 1.2) * 0.2 + ) * 100; + + return { + dwell, dwellTarget: s.dwellTarget, flow, fpqc, fpqcTarget: s.fpqcTarget, + rework, reworkTarget: s.reworkTarget, wip, + score: +score.toFixed(1), + status: score >= 99.5 ? 'green' : score >= 92 ? 'yellow' : 'red', + dwellDelta: period > 0 ? r1(dwell - dwellAt(index, period - 1)) : null, + }; +} + +/** 单段停留:stageStats 与环比都要用,抽出来保证两处口径一致 */ +function dwellAt(index: number, period: number) { + const s = STAGES[index]; + const t = (period - 5.5) / 5.5; + return r1(s.dwell * (1 - s.improve * 0.14 * t + wave(period, index * 7 + 1) * 0.05)); +} + +export interface FlowSummary { + /** 端到端总周期(各段停留之和,天) */ + cycle: number; + cycleBase: number; + /** 端到端一次通过率(各段 FPQC 连乘,%) */ + e2e: number; + e2eBase: number; + /** 有效产出 = 链上最小吞吐(约束理论,批次/月) */ + throughput: number; + constraintKey: string; + /** 全链在制品 */ + wip: number; + /** 达成率最低的一段 */ + bottleneckKey: string; + bottleneckScore: number; +} + +export function flowStats(period: number): { stats: StageStats[]; summary: FlowSummary } { + const stats = STAGES.map((_, i) => stageStats(i, period)); + const cycle = +stats.reduce((a, x) => a + x.dwell, 0).toFixed(1); + const e2e = +(stats.reduce((a, x) => a * x.fpqc / 100, 1) * 100).toFixed(1); + const constraint = stats.reduce((mi, x, i) => (x.flow < stats[mi].flow ? i : mi), 0); + const worst = stats.reduce((mi, x, i) => (x.score < stats[mi].score ? i : mi), 0); + return { + stats, + summary: { + cycle, + cycleBase: +STAGES.reduce((a, s) => a + s.dwell, 0).toFixed(1), + e2e, + e2eBase: +(STAGES.reduce((a, s) => a * s.fpqc / 100, 1) * 100).toFixed(1), + throughput: stats[constraint].flow, + constraintKey: STAGES[constraint].key, + wip: stats.reduce((a, x) => a + x.wip, 0), + bottleneckKey: STAGES[worst].key, + bottleneckScore: stats[worst].score, + }, + }; +} diff --git a/src/modules/tfamd-oee/lib/qualityAlerts.ts b/src/modules/tfamd-oee/lib/qualityAlerts.ts new file mode 100644 index 0000000..205979a --- /dev/null +++ b/src/modules/tfamd-oee/lib/qualityAlerts.ts @@ -0,0 +1,421 @@ +/** + * 质量告警流:把四张源表里「现在该处理什么」的行汇成一条按严重度排序的队列。 + * + * 数据来源与判定口径(阈值一律照原表首行写的来,不自己另立一套): + * DS-15 三日预警池 —— 滞留天数 = 基准日 2026-10-16 − 发生日(calc.dwellDays) + * DS-16 参数漂移监控 —— 偏移率 =(实测均值 − 标准值)÷ 标准值(calc.driftRate,标准值非数值时为 null) + * DS-14 工序负荷与线平衡 —— 负荷率 = 需求节拍 ÷ 实际产能(calc.loadRate) + * DS-07 检验标准与遗漏提示 —— 状态 = '待 QE 确认' 才算缺口 + * + * 三条约定: + * 1. 同一设备 + 同一参数的连续多条漂移记录合成一张卡(激光功率五日 1196→1128 是一条劣化趋势, + * 不是五条独立告警),展开时按日期给出序列。 + * 2. 读数一律现算,页面不写死任何统计值;`alertSummary` 的计数与卡片同源。 + * 3. 排序先分档再分类型,不跨类型比大小:滞留天数、偏移率、负荷率三个量纲硬排会排出假次序。 + */ +import { + TABLES, calc, datasetById, QAP_CALIBER, + type ParamDrift, type WarningPoolItem, type LineBalance, type InspectionStandard, +} from '../data/qap'; +import { abnormalModelsAt, driftSeriesAt, lineModelsAt } from './replayQuality'; +import { replayBaseDate } from './replay'; +import { CURRENT_PERIOD } from './time'; + +/** 告警类型:对应四张源表 */ +export type AlertKind = 'abnormal' | 'drift' | 'bottleneck' | 'gap'; + +/** 严重档位。muted 只给已闭环条目,保留在队列末尾做全貌 */ +export type AlertLevel = 'red' | 'orange' | 'blue' | 'muted'; + +export interface AlertField { label: string; value: string } + +export interface QualityAlert { + id: string; + kind: AlertKind; + level: AlertLevel; + /** 卡片主标题:缺陷名 / 设备·参数 / 工序 / 检验项目 */ + title: string; + /** 标题下的主体(料号、工位等),没有则不占行 */ + subject: string; + /** 一行关键读数 */ + metric: { label: string; value: string }; + /** 归属角色:取源表在数据集目录里的责任角色,用于和左栏四段对上 */ + role: string; + /** 责任人 / 处置方,源表没写就是空 */ + owner: string; + /** 同档同类型内的紧迫度,降序排(各类型口径不同,不跨类型比大小) */ + urgency: number; + /** 这张卡背后合并了几条源表记录,汇总里用来解释「卡片数 < 命中行数」 */ + rowsIn: number; + /** 当前处置动作(源表原文) */ + action: string; + /** 来源:数据集编号 + 表名,展开时标出来,便于回「数据集总览」对账 */ + source: { ds: string; table: string }; + /** 展开后的字段明细 */ + fields: AlertField[]; + /** 该条判定所依据的原表口径 */ + caliber: string; +} + +const KIND_LABEL: Record = { + abnormal: '异常单', + drift: '参数漂移', + bottleneck: '产能瓶颈', + gap: '标准遗漏', +}; + +export const alertKindLabel = (k: AlertKind) => KIND_LABEL[k]; + +const LEVEL_RANK: Record = { red: 0, orange: 1, blue: 2, muted: 3 }; + +const pct = (v: number, digits = 1) => `${(v * 100).toFixed(digits)}%`; +const roleOf = (ds: string) => datasetById(ds)?.role ?? ''; +const tableOf = (ds: string) => datasetById(ds)?.name ?? ds; + +/* ── DS-15 三日预警池 ─────────────────────────────────────────────────── */ +/** + * 判档:致命直接红;未闭环且滞留超 3 天按原表口径必须升级,同样判红; + * 其余按严重度落橙/蓝;已闭环压灰排到最后,让预警池看得出全貌而不是凭空少一条。 + */ +function abnormalAlerts(): QualityAlert[] { + const caliber = datasetById('DS-15')?.caliber ?? ''; + return (TABLES['DS-15'] as unknown as WarningPoolItem[]).map(r => { + const dwell = calc.dwellDays(r); + const closed = r['当前状态'] === '已闭环'; + const overdue = dwell > 3; + const level: AlertLevel = closed ? 'muted' : r['严重度'] === '致命' || overdue ? 'red' : r['严重度'] === '严重' ? 'orange' : 'blue'; + return { + id: `ab-${r['异常单号']}`, + kind: 'abnormal' as const, + level, + title: r['缺陷'], + subject: r['料号'], + metric: { label: '滞留', value: `${dwell} 天` }, + role: roleOf('DS-15'), + owner: r['责任人'], + /* 滞留天数即紧迫度;致命单独 +100 顶到本类最前——今天刚发生的致命单不该排在别人的尾巴后面 */ + urgency: dwell + (r['严重度'] === '致命' && !closed ? 100 : 0), + rowsIn: 1, + action: r['升级级别'], + source: { ds: 'DS-15', table: tableOf('DS-15') }, + fields: [ + { label: '异常单号', value: r['异常单号'] }, + { label: '缺陷 / 缺陷码', value: `${r['缺陷']}(${r['缺陷码']})` }, + { label: '严重度', value: r['严重度'] }, + { label: '发生日', value: r['发生日'] }, + { label: '滞留天数', value: `${dwell} 天(基准日 ${QAP_CALIBER.warningPoolBaseDate})` }, + { label: '当前状态', value: r['当前状态'] }, + { label: '升级级别', value: r['升级级别'] }, + ], + caliber: `${caliber}${overdue && !closed ? ';本单已超 3 天,按口径必须升级' : ''}`, + }; + }); +} + +/* ── DS-16 关键参数漂移 ───────────────────────────────────────────────── */ +/** 状态前缀 → 档位。原表状态写成「预警(超允差60%)」这类带括号的补充说明,按前缀判 */ +const driftLevel = (status: string): AlertLevel | null => { + if (status.startsWith('超差')) return 'red'; + if (status.startsWith('预警')) return 'orange'; + if (status.startsWith('注意') || status.startsWith('临近')) return 'blue'; + return null; +}; + +/** + * 同设备同参数并成一张卡:判档看最新那条记录(现在到底是什么状态), + * 监控序列给出该参数的全部监控日(含「正常」那几天),劣化从哪天起步一眼看得出。 + * 最新一条已回到正常的参数不挂卡——它此刻不构成在制告警,历史劣化留给序列里的同类卡说明。 + */ +function driftAlerts(): QualityAlert[] { + const caliber = datasetById('DS-16')?.caliber ?? ''; + + const groups = new Map(); + (TABLES['DS-16'] as unknown as ParamDrift[]).forEach(r => { + const key = `${r['设备']}|${r['参数']}`; + groups.set(key, [...(groups.get(key) ?? []), r]); + }); + + const cards = [...groups.entries()].map(([key, all]): QualityAlert | null => { + /* 日期升序,末位即最新 */ + const seq = [...all].sort((a, b) => String(a['日期']).localeCompare(String(b['日期']))); + const last = seq[seq.length - 1]; + const level = driftLevel(String(last['状态'])); + if (!level) return null; + const hits = seq.filter(x => driftLevel(String(x['状态'])) !== null); + + const drift = calc.driftRate(last); + const std = String(last['标准值']); + const isNum = Number.isFinite(Number(std)); + /* 模具冲次这类行的「标准值」是寿命上限而不是标称值:算出来的负偏移会被读成 + 「低于标准所以安全」,正好反了。这里按寿命口径给已用比例。 */ + const isCap = isNum && String(last['允许偏差']).includes('上限'); + const used = isCap ? Number(last['实测均值']) / Number(std) : null; + /* 标准值是「按图」这类文字时偏移率算不出来,读数改看实测对允差的位置 */ + const metricValue = used !== null + ? `${last['实测均值']}${last['单位']} / ${last['允许偏差']} ${std}${last['单位']}(已用 ${pct(used)})` + : drift === null + ? `${last['实测均值']}${last['单位']} / 允差 ${last['允许偏差']}` + : `${last['实测均值']}${last['单位']}(偏移 ${drift > 0 ? '+' : ''}${pct(drift)})`; + /* 偏移只按告警行统计;「正常」那几天是趋势背景,不算命中 */ + const rates = hits.map(x => calc.driftRate(x)).filter((v): v is number => v !== null); + const worst = rates.length ? Math.min(...rates) : null; + const mergeNote = hits.length > 1 + ? `;本卡由 ${hits.length} 条同参数告警记录合并${worst === null ? '' : `,最差偏移 ${pct(worst)}`}` + : ''; + const spanNote = seq.length > 1 ? `,监控序列给出 ${seq.length} 天` : ''; + + return { + id: `dr-${key.replace(/[^\w\u4e00-\u9fa5]+/g, '-')}`, + kind: 'drift' as const, + level, + title: `${last['参数']} ${last['状态']}`, + subject: last['设备'], + metric: { label: '实测', value: metricValue }, + role: roleOf('DS-16'), + owner: '', + urgency: used !== null ? used : drift === null ? 0.2 : Math.abs(drift), + rowsIn: hits.length, + action: last['处理动作'], + source: { ds: 'DS-16', table: tableOf('DS-16') }, + fields: [ + { label: '设备', value: last['设备'] }, + { label: '参数', value: `${last['参数']}(${last['单位']})` }, + { label: '标准值 / 允许偏差', value: isNum ? `${std} ${last['单位']} / ${last['允许偏差']}` : `${std} / ${last['允许偏差']}` }, + { label: '最新实测', value: `${last['实测均值']}${last['单位']}(${last['日期']})` }, + { label: '偏移率', value: used !== null ? '—(寿命上限口径,见已用比例)' : drift === null ? '—(标准值非数值)' : `${drift > 0 ? '+' : ''}${pct(drift)}` }, + ...(used !== null ? [{ label: '已用寿命', value: `${pct(used)}(剩余 ${Math.round(Number(std) - Number(last['实测均值'])).toLocaleString('en-US')} ${last['单位']})` }] : []), + { label: '同步缺陷率', value: pct(last['同步缺陷率']) }, + /* 多天监控才给序列,状态去掉括号里的补充说明只留前缀,序列才排得开 */ + ...(seq.length > 1 + ? [{ label: '监控序列', value: seq.map(x => `${String(x['日期']).slice(5)} ${x['实测均值']}${last['单位']} ${String(x['状态']).split('(')[0]}`).join(' → ') }] + : []), + { label: '状态', value: last['状态'] }, + ], + caliber: `${caliber}${mergeNote}${spanNote}`, + }; + }); + + return cards.filter((x): x is QualityAlert => x !== null); +} + +/* ── DS-14 工序负荷与线平衡 ───────────────────────────────────────────── */ +function bottleneckAlerts(): QualityAlert[] { + const caliber = datasetById('DS-14')?.caliber ?? ''; + return (TABLES['DS-14'] as unknown as LineBalance[]) + .filter(r => String(r['预警']).trim() !== '') + .map(r => { + const load = calc.loadRate(r); + const warn = String(r['预警']); + const level: AlertLevel = warn.includes('瓶颈') ? 'red' : 'orange'; + return { + id: `bn-${r['工序']}`, + kind: 'bottleneck' as const, + level, + title: `${r['工序']} ${warn}`, + subject: r['工位/设备'], + metric: { label: '负荷率', value: `${load.toFixed(2)}(${r['实际产能(件/班)']} / ${r['需求节拍(件/班)']} 件·班)` }, + role: roleOf('DS-14'), + owner: '', + urgency: load, + rowsIn: 1, + action: r['建议'], + source: { ds: 'DS-14', table: tableOf('DS-14') }, + fields: [ + { label: '工序', value: r['工序'] }, + { label: '工位 / 设备', value: r['工位/设备'] }, + { label: '需求节拍', value: `${r['需求节拍(件/班)']} 件/班` }, + { label: '实际产能', value: `${r['实际产能(件/班)']} 件/班` }, + { label: '负荷率', value: load.toFixed(2) }, + { label: '在制品', value: `${r['在制品(件)']} 件` }, + { label: '预警', value: warn }, + ], + caliber, + }; + }); +} + +/* ── DS-07 检验标准与 AI 遗漏提示 ─────────────────────────────────────── */ +function gapAlerts(): QualityAlert[] { + const caliber = datasetById('DS-07')?.caliber ?? ''; + return (TABLES['DS-07'] as unknown as InspectionStandard[]) + .filter(r => r['状态'] === '待 QE 确认' && r['AI 提示'] !== '—') + .map(r => ({ + id: `gp-${r['特征/项目']}`, + kind: 'gap' as const, + level: 'orange' as AlertLevel, + title: `${r['特征/项目']}检验缺口`, + subject: r['检验项目'], + metric: { label: '状态', value: r['状态'] }, + role: roleOf('DS-07'), + owner: 'QE', + /* 缺口条数不多,按特征名排即可,给个固定紧迫度排在橙档尾部 */ + urgency: 0, + rowsIn: 1, + action: r['AI 提示'], + source: { ds: 'DS-07', table: tableOf('DS-07') }, + fields: [ + { label: '特征 / 项目', value: r['特征/项目'] }, + { label: '检验项目', value: r['检验项目'] }, + { label: '依据', value: r['依据'] }, + { label: '抽样 / 频次', value: `${r['抽样']} · ${r['频次']}` }, + { label: '量具', value: r['量具'] }, + { label: 'AI 提示', value: r['AI 提示'] }, + { label: '状态', value: r['状态'] }, + ], + caliber, + })); +} + +/** 同档同类型里的固定次序:异常单是已经成单的问题,优先于趋势类信号 */ +const KIND_ORDER: AlertKind[] = ['abnormal', 'drift', 'bottleneck', 'gap']; +const kindRank = (k: AlertKind) => KIND_ORDER.indexOf(k); + +/** + * 全量告警队列:先按严重度分带,带内按类型次序,类型内按各自口径的紧迫度降序。 + * 不跨类型比紧迫度——滞留天数和负荷率不是同一个量纲,硬比会排出一个假次序。 + */ +export function qualityAlerts(): QualityAlert[] { + return [...abnormalAlerts(), ...driftAlerts(), ...bottleneckAlerts(), ...gapAlerts()] + .sort((a, b) => + LEVEL_RANK[a.level] - LEVEL_RANK[b.level] + || kindRank(a.kind) - kindRank(b.kind) + || b.urgency - a.urgency); +} + +/** + * 右栏告警流的时间投影:异常单按回放期重算滞留/升级,漂移按回放曲线重取实测与状态, + * 瓶颈按季节负荷重算负荷率与在制品。判定口径与四个 builder 完全一致; + * 检验缺口明细仍是源表当期(不凭空造出第 N 条标准行),所以只在卡片读数上投影。 + */ +export function qualityAlertsAt(period: number): QualityAlert[] { + if (period === CURRENT_PERIOD) return qualityAlerts(); + + const abn = abnormalModelsAt(period); + const lines = lineModelsAt(period); + const series = driftSeriesAt(period); + const baseDate = replayBaseDate(period); + + const patched = qualityAlerts().map((card): QualityAlert | null => { + if (card.kind === 'abnormal') { + const m = abn.find(a => card.id === `ab-${a.order}`); + if (!m) return card; + const level: AlertLevel = m.closed ? 'muted' + : m.severity === '致命' || m.overdue ? 'red' + : m.severity === '严重' ? 'orange' : 'blue'; + const action = m.closed ? card.action + : m.overdue ? `升至厂长(超期 ${m.dwell - 3} 天)` + : m.severity === '致命' ? '已即时通知车间主任' + : '正常'; + return { + ...card, + level, + action, + metric: { label: '滞留', value: `${m.dwell} 天` }, + urgency: m.dwell + (m.severity === '致命' && !m.closed ? 100 : 0), + fields: card.fields.map(f => + f.label === '发生日' ? { ...f, value: m.occurred } + : f.label === '滞留天数' ? { ...f, value: `${m.dwell} 天(基准日 ${baseDate})` } + : f.label === '升级级别' ? { ...f, value: action } + : f), + }; + } + + if (card.kind === 'drift') { + const param = card.title.split(' ')[0]; + const s = series.find(x => x.device === card.subject && x.param === param); + if (!s) return card; + const level = driftLevel(s.latestStatus); + /* 最新一天回到正常就不挂卡,和源表 builder 同一取舍 */ + if (!level) return null; + const latest = s.values[s.values.length - 1] ?? s.std ?? 0; + const lastDate = s.dates[s.dates.length - 1] ?? ''; + const lastDefect = s.defects[s.defects.length - 1] ?? 0; + const drift = s.std ? (latest - s.std) / s.std : null; + const used = s.lifeCap && s.std ? latest / s.std : null; + const metricValue = used !== null + ? `${latest}${s.unit} / ${s.tolText} ${s.stdText}${s.unit}(已用 ${pct(used)})` + : drift === null + ? `${latest}${s.unit} / 允差 ${s.tolText}` + : `${latest}${s.unit}(偏移 ${drift > 0 ? '+' : ''}${pct(drift)})`; + return { + ...card, + level, + title: `${s.param} ${s.latestStatus}`, + metric: { label: '实测', value: metricValue }, + urgency: used ?? (drift === null ? 0.2 : Math.abs(drift)), + fields: card.fields.map(f => + f.label === '最新实测' ? { ...f, value: `${latest}${s.unit}(${lastDate})` } + : f.label === '偏移率' ? { ...f, value: used !== null ? '—(寿命上限口径,见已用比例)' : drift === null ? '—(标准值非数值)' : `${drift > 0 ? '+' : ''}${pct(drift)}` } + : f.label === '已用寿命' ? { ...f, value: used !== null ? `${pct(used)}(剩余 ${Math.round((s.std ?? 0) - latest).toLocaleString('en-US')} ${s.unit})` : f.value } + : f.label === '同步缺陷率' ? { ...f, value: `${lastDefect.toFixed(1)}%` } + : f.label === '监控序列' ? { ...f, value: s.dates.map((d, i) => `${d.slice(5)} ${s.values[i]}${s.unit}`).join(' → ') } + : f.label === '状态' ? { ...f, value: s.latestStatus } + : f), + caliber: `${card.caliber};回放期读数按统一质量曲线回推`, + }; + } + + if (card.kind === 'bottleneck') { + const proc = card.fields.find(f => f.label === '工序')?.value ?? card.title.split(' ')[0]; + const m = lines.find(l => l.label === proc); + if (!m) return card; + const load = m.load / 100; + return { + ...card, + metric: { label: '负荷率', value: `${load.toFixed(2)}(${m.capacity} / ${m.demand} 件·班)` }, + urgency: load, + fields: card.fields.map(f => + f.label === '负荷率' ? { ...f, value: load.toFixed(2) } + : f.label === '在制品' ? { ...f, value: `${m.wip} 件` } + : f), + caliber: `${card.caliber};回放期负荷按季节曲线回推`, + }; + } + + return card; + }); + + return patched + .filter((x): x is QualityAlert => x !== null) + .sort((a, b) => + LEVEL_RANK[a.level] - LEVEL_RANK[b.level] + || kindRank(a.kind) - kindRank(b.kind) + || b.urgency - a.urgency); +} + +export interface AlertSummary { + /** 卡片数:同参数漂移已合并 */ + total: number; + /** 命中告警的源表行数,比卡片多出来的部分就是被合并掉的 */ + matched: number; + /** 四张源表一共扫了多少行,用于说明「正常」的行没有凭空消失 */ + scanned: number; + red: number; + orange: number; + blue: number; + muted: number; + /** 已闭环条数,单列出来好在标题栏讲清「在制敞口」 */ + closed: number; + baseDate: string; +} + +/** 汇总计数与卡片同一个函数源,标题栏读数不会和列表条数打架 */ +export function alertSummary(list: QualityAlert[] = qualityAlerts()): AlertSummary { + const n = (lv: AlertLevel) => list.filter(a => a.level === lv).length; + return { + total: list.length, + matched: list.reduce((a, x) => a + x.rowsIn, 0), + scanned: R('DS-15').length + R('DS-16').length + R('DS-14').length + R('DS-07').length, + red: n('red'), + orange: n('orange'), + blue: n('blue'), + muted: n('muted'), + closed: n('muted'), + baseDate: QAP_CALIBER.warningPoolBaseDate, + }; +} + +/** 只取原表行数用的窄助手,避免上面四个 builder 的类型在这里再抄一遍 */ +function R(key: 'DS-15' | 'DS-16' | 'DS-14' | 'DS-07'): unknown[] { + return TABLES[key] as unknown as unknown[]; +} diff --git a/src/modules/tfamd-oee/lib/qualityAsk.ts b/src/modules/tfamd-oee/lib/qualityAsk.ts new file mode 100644 index 0000000..33ef2e4 --- /dev/null +++ b/src/modules/tfamd-oee/lib/qualityAsk.ts @@ -0,0 +1,710 @@ +/** + * 质量异常预防问答引擎(中央工作区底部对话区的取数与作答层)。 + * + * 这个引擎只讲本应用的四件事:**为什么不良、参数还在不在窗口里、异常闭环了没有、 + * 标准与数据够不够撑起预防**。所有读数一律现场从 + * `lib/qualityMetrics`(六页签品质指标脊)、`data/ontologyQap`(本体对象/关系/规则/动作)、 + * `lib/qualityAlerts`(告警流)和 `data/qap`(17 张源表)算出来, + * 页面里不写死任何一个统计值——左栏流程、右栏告警、六个页签看到的数,和这里回答的数同源。 + * + * 三条红线(与 qualityMetrics / qualityAlerts 保持同一套写法): + * 1. 计算列只走 `calc.*`,比率字段源表存小数、这里 ×100 后交视图; + * 2. **源表没写判定线的读数一律只报高低和倍数关系,不编达成率**,口径行会写明「源表未设判定线」; + * 3. 跨表分母不同(DS-09 近 3 月 4,860 批次 vs DS-16 单日抽检 vs DS-03 字典内占比) + * 时把矛盾摊在「依据与口径」里,不合并、不换算、不抹平。 + * + * 回答卡里每个建议动作都带一个 `AskJump`:页签、指标主体、四个舞台(本体/数据集/ + * 知识库/特征建模)或一次追问,用户点下去就走到那一眼数据,而不是只看一段结论。 + */ +import { + TABLES, QAP_CALIBER, calc, + type ParamDrift, type ParamCollectionPoint, type QapTableKey, +} from '../data/qap'; +import { rules as ONT_RULES, actions as ONT_ACTIONS, objects as ONT_OBJECTS } from '../data/ontologyQap'; +import { + DEFECT_COLUMNS, abnormalModels, baselineFeature, collectionModel, coverageModel, + defectPareto, doeModel, duplicateHits, featureModels, lineModels, masterModel, + methodModels, overallDefectRate, predictionModels, recipeModel, riskPoints, + severityCount, standardBuildModel, stationModels, trendModel, + type FeatureModel, +} from './qualityMetrics'; +import { alertSummary, qualityAlerts } from './qualityAlerts'; + +/* ══════════════════ 卡片的结构 ══════════════════ */ + +export type AskTone = 'danger' | 'warning' | 'success' | 'info'; +/** 中央工作区六个页签(与 MetricWorkspace 的 TabKey 同集合) */ +export type AskTabKey = 'detail' | 'trend' | 'structure' | 'region' | 'risk' | 'cockpit'; +export type AskRoleKey = 'PE' | 'IE' | 'QE' | 'ME'; + +/** + * 跳转目的地。回答卡不画图表,只负责把用户送到能看到这张图的地方: + * - metric:设主体并切到「指标明细」,code 直接给 resolveMetric 认的口径码 + * (静态指标脊 DEFECT-WGT/DRIFT-CURD…,或动态下钻族 DS09:料号 / DS14:工序 / DS02:工位 / DS03:缺陷码) + * - tab:只切页签,主体沿用当前 + * - ontology / dataset / knowledge / feature:四个整屏舞台,dataset 带数据集编号、 + * knowledge 带角色+切片号、feature 带数据对象+实例 + * - ask:把问题再抛回对话区,形成一条可追问的链路 + */ +export type AskJump = + | { kind: 'metric'; code: string } + | { kind: 'tab'; tab: AskTabKey } + | { kind: 'ontology' } + | { kind: 'dataset'; id: string } + | { kind: 'knowledge'; role: AskRoleKey; chunkId: string } + | { kind: 'feature'; objKey: string; instanceId?: string } + | { kind: 'ask'; text: string }; + +export interface AskStep { act: string; detail: string } +export interface AskMetric { label: string; value: string; tone?: AskTone } +export interface AskTableRow { cells: string[]; tone?: AskTone } +export interface AskTable { cols: string[]; rows: AskTableRow[] } +export interface AskPoint { label: string; text: string; tone?: AskTone } +export interface AskAction { label: string; jump: AskJump } + +export interface AskAnswer { + /** 卡片头部展示的意图名 */ + intent: string; + severity: AskTone; + conclusion: string; + metrics: AskMetric[]; + table?: AskTable; + points: AskPoint[]; + actions: AskAction[]; + source: string; + /** 思考轨:逐条揭示,揭示完折叠成一行供复查 */ + steps: AskStep[]; +} + +export type IntentId = + | 'defect' /* 缺陷主因 */ + | 'drift' /* 参数漂移与工艺窗口 */ + | 'closed' /* 异常闭环与滞留 */ + | 'bottleneck' /* 工序工位瓶颈 */ + | 'standard' /* 标准缺口与知识复用 */ + | 'data' /* 数据充分性 */ + | 'help'; /* 能力说明兜底 */ + +export const INTENT_LABEL: Record = { + defect: '缺陷主因定位', + drift: '参数漂移与工艺窗口', + closed: '异常闭环与滞留', + bottleneck: '工序产能瓶颈', + standard: '标准缺口与知识复用', + data: '数据充分性体检', + help: '能力说明', +}; + +/** + * 意图 → 应答专家 code(对应 lib/teams.ts 的质量专家名册): + * 回答卡头部标注「这条由哪位专家答」,会诊里同一位专家也用同一份读数。 + */ +export const DISPATCH: Record, string> = { + defect: 'QDEF', drift: 'QPAR', closed: 'QCLO', + bottleneck: 'QCAP', standard: 'QSTD', data: 'QDAT', +}; + +/* ══════════════════ 关键词路由 ══════════════════ */ + +/** 每类意图的触发词:口语说法和源表用语都收,命中数最多的胜出,打不过就落 help */ +const KEYS: Record, string[]> = { + defect: ['不良', '缺陷', '主因', '为什么坏', '焊瘤', '未焊透', '搭接', '变形', '结构特征', '特征', '不良率', '良率', '最伤', '高频缺陷', '帕累托', '哪类问题最多', '集中在'], + drift: ['漂移', '功率', '参数', '工艺窗口', '窗口', '镜片', '光路', '偏离', '超差', '允差', '设备劣化', '趋势', ' DOE', 'doe', '试验', '组合', '参数卡', 'recipe'], + closed: ['闭环', '滞留', '预警池', '异常单', '超期', '升级', '没人处理', '没闭环', '待处理', '处理了吗', '谁负责', '责任人', '8D', '卡了多久'], + bottleneck: ['瓶颈', '负荷', '线平衡', '产能', '节拍', '在制品', '工序', '工位', '排产', '插单', '最快改善', '卡在哪', '开第', '三班', '人力'], + standard: ['标准', '检验标准', 'SOP', '作业标准', '缺口', '遗漏', '待确认', '别名', '归并', '复用', '知识', '夹具', '验收', '防错', '点检', '谁定'], + data: ['数据', '采集', '够不够', '准确', '覆盖', '主数据', '台账', '可信', '自动', '盲区', '预测', '试制', '回验', '接入', '还差什么'], +}; + +/** 命中的关键词(按原词返回,供思考轨如实交代"到底认了哪几个词") */ +export function matchedKeys(raw: string): string[] { + const q = raw.toLowerCase(); + return Object.values(KEYS).reduce((acc, list) => acc.concat( + list.filter(k => q.includes(k.toLowerCase())), + ), []); +} + +export function matchIntent(raw: string): IntentId { + const q = raw.toLowerCase(); + let best: IntentId = 'help'; + let score = 0; + (Object.keys(KEYS) as Exclude[]).forEach(id => { + const s = KEYS[id].reduce((a, k) => a + (q.includes(k.toLowerCase()) ? 1 : 0), 0); + if (s > score) { score = s; best = id; } + }); + return score === 0 ? 'help' : best; +} + +/** 快捷问句:一句一个意图,点下去就是那场演示 */ +export const SUGGESTED = [ + '近 3 个月不良主要压在哪类结构特征上?', + '激光功率还在往下掉吗,会不会演成批量问题?', + '预警池里哪些异常还没闭环、超期了?', + '全线最卡的工序是哪道,负荷率多少?', + '检验标准还缺哪几项,能复用历史 8D 吗?', + '这些数据够做质量预测吗,还差什么?', +]; + +/* ══════════════════ 公共助手 ══════════════════ */ + +const n = (key: QapTableKey) => (TABLES[key] as unknown[]).length; +const sum = (xs: number[]) => xs.reduce((a, x) => a + x, 0); +/** 本体规则现算命中:规则改了这里跟着变,不在问答层另立阈值 */ +const hit = (id: string) => ONT_RULES.find(r => r.id === id)!.hits(); +const rule = (id: string) => ONT_RULES.find(r => r.id === id)!; +const p1 = (v: number) => v.toFixed(1); +/** 源表比率 ×100 后的一位小数字符串 */ +const pc = (v: number | null | undefined, digits = 1) => + v === null || v === undefined || !Number.isFinite(v) ? '—' : (v * 100).toFixed(digits); + +/** DS-09 四类缺陷里最主导的那一类(现算,源表没有这列) */ +function dominantDefect(f: FeatureModel): string { + let bi = 0; + f.parts.forEach((p, i) => { if (p > f.parts[bi]) bi = i; }); + return `${DEFECT_COLUMNS[bi]} ${p1(f.parts[bi])}%`; +} + +/** + * 思考轨第一步:如实说明命中了哪些词、落到哪个意图。 + * 没有关键词命中就是 help,不假装"理解了一句不存在的话"。 + */ +function stepParse(raw: string, id: IntentId): AskStep { + const ks = matchedKeys(raw); + return { + act: '解析问句', + detail: ks.length + ? `命中关键词 ${ks.length} 个(${ks.slice(0, 5).join('、')}${ks.length > 5 ? '…' : ''})→ 意图「${INTENT_LABEL[id]}」` + : `没落进六类质量意图,走能力说明`, + }; +} + +/** 取数步:把真实行数写进口径里,用户能回数据集一页条数对上 */ +const stepFetch = (detail: string): AskStep => ({ act: '取数', detail }); +const stepRule = (detail: string): AskStep => ({ act: '套本体规则', detail }); +const stepCross = (detail: string): AskStep => ({ act: '跨表对照', detail }); +const stepGrade = (detail: string): AskStep => ({ act: '定级与排序', detail }); +const stepDone = (detail: string): AskStep => ({ act: '出结论', detail }); + +const SOURCE = (parts: string[]) => `现算自 ${parts.join(' · ')};与左栏流程、右栏告警、六个页签同一取数函数,不打架`; + +/* ══════════════════ ① 缺陷主因(DS-09 × DS-03)══════════════════ */ + +function answerDefect(raw: string): AskAnswer { + const fs = [...featureModels()].sort((a, b) => b.defect - a.defect); + const base = baselineFeature(); + const overall = overallDefectRate(); + const pareto = defectPareto(); + const top = fs[0]; + const ratio = base && base.defect > 0 ? +(top.defect / base.defect).toFixed(1) : null; + const over = hit('qr-hifeature'); + const special = hit('qr-special'); + const sev = severityCount(); + const dictTotal = +sum(defectPareto().map(d => d.share)).toFixed(1); + const samples = sum(fs.map(f => f.samples)); + + return { + intent: INTENT_LABEL.defect, + severity: ratio && ratio >= 2 ? 'danger' : 'warning', + conclusion: + `${top.label}(${top.item})综合不良率 ${p1(top.defect)}%,主导缺陷是${dominantDefect(top)};` + + `是基准平板拼焊件(${p1(base?.defect ?? 0)}%)的 ${ratio ?? '—'} 倍。` + + `近 3 月 ${QAP_CALIBER.featureDefectSamples.toLocaleString('en-US')} 批次样本加权后全线综合不良率 ${p1(overall)}%,` + + `${over.n}/${fs.length} 档特征已高于基准件,${top.samples.toLocaleString('en-US')} 件样本的这一档最该先动手。`, + metrics: [ + { label: '样本加权综合不良率', value: `${p1(overall)}%`, tone: 'warning' }, + { label: '最高风险结构特征', value: `${p1(top.defect)}%`, tone: 'danger' }, + { label: '基准平板拼焊', value: `${p1(base?.defect ?? 0)}%`, tone: 'success' }, + { label: '高于基准件', value: `${over.n}/${fs.length} 档`, tone: 'warning' }, + { label: '特殊特性缺陷码', value: `${special.n} 个`, tone: 'danger' }, + { label: '致命档占比合计', value: `${p1(sev[0].share)}%`, tone: 'danger' }, + ], + table: { + cols: ['结构特征', '典型料号', '样本', '综合不良率%', 'vs 基准', '主导缺陷(现算)'], + rows: fs.map(f => ({ + cells: [ + f.label, f.item, f.samples.toLocaleString('en-US'), p1(f.defect), + base && base.defect > 0 ? `${(f.defect / base.defect).toFixed(2)}×` : '—', + dominantDefect(f), + ], + tone: f.code === top.code ? 'danger' : f.defect > (base?.defect ?? 0) ? 'warning' : undefined, + })), + }, + points: [ + { label: '计算口径', text: `综合不良率 = 焊瘤 + 未焊透 + 搭接不良 + 焊接变形(DS-09 计算列,本层现算);加权口径为 Σ(单特征不良率 × 样本数) ÷ Σ样本数,本组样本合计 ${samples.toLocaleString('en-US')}。` }, + { label: '判定线', text: '源表未设判定线:DS-09 只给四类缺陷率,没有合格线,所以这里只报绝对高低与倍数,不编达成率。基准件 SRV2U-BASE-01 是「结论」列明确标注的对比基准,不是本层挑的。', tone: 'info' }, + { label: '本体规则', text: `qr-hifeature「特征不良高于基准件」命中 ${over.n} 个特征维度:${over.targets.join('、')}。` }, + { label: '字典侧证', text: `DS-03 近 3 月占比 Top1 是${pareto[0].name}(${p1(pareto[0].share)}%,严重度${pareto[0].severity},历史 8D ${pareto[0].h8d} 件),与 DS-09 的主导缺陷分属两张表。` }, + { label: '跨表矛盾', text: `DS-09 只有 4 类缺陷列、6 档特征,DS-03 有 ${n('DS-03')} 个缺陷码且「近3月占比」合计只到 ${dictTotal}%(不足 100%)。两边分母不同,不做直接换算,各自看高低。`, tone: 'warning' }, + { label: '不可漏检', text: `特殊特性 ${special.n} 个缺陷码(${special.targets.join('、')})要么致命、要么客户端会检出,必须落到检验标准的检测手段与频次上,不能抽检放过。`, tone: 'danger' }, + ], + actions: [ + { label: '看结构特征 × 缺陷页签', jump: { kind: 'tab', tab: 'structure' } }, + { label: `这档特征明细 · ${top.label}`, jump: { kind: 'metric', code: top.code } }, + { label: `缺陷字典 Top1 · ${pareto[0].name}`, jump: { kind: 'metric', code: pareto[0].code } }, + { label: '综合不良率整体口径', jump: { kind: 'metric', code: 'DEFECT-WGT' } }, + { label: '回数据集对账 DS-09', jump: { kind: 'dataset', id: 'DS-09' } }, + { label: '工艺建模里找这档结构', jump: { kind: 'feature', objKey: 'DS-09', instanceId: top.item } }, + { label: '接着问:是不是参数掉了', jump: { kind: 'ask', text: '激光功率还在往下掉吗,会不会演成批量问题?' } }, + ], + source: SOURCE([ + `DS-09 结构特征 × 缺陷关联矩阵 ${n('DS-09')} 行`, + `DS-03 缺陷代码字典 ${n('DS-03')} 行`, + '本体规则 qr-hifeature / qr-special', + ]), + steps: [ + stepParse(raw, 'defect'), + stepFetch(`读 DS-09 ${n('DS-09')} 行结构特征 × 缺陷率、DS-03 ${n('DS-03')} 行缺陷字典;四类缺陷率都是源表原值,综合不良率现算`), + stepRule(`qr-hifeature 综合不良率 > 基准件 ${p1((base?.defect ?? 0))}% → 命中 ${over.n} 个特征维度;qr-special 特殊特性 = 是 → ${special.n} 个缺陷码`), + stepCross(`DS-09 加权 ${p1(overall)}% 与 DS-03 占比 Top1 ${pareto[0].name} ${p1(pareto[0].share)}% 同向;两表分母不同,只比高低不做换算`), + stepGrade(`源表未设判定线 → 不给达成率,按综合不良率降序排;最高 ${p1(top.defect)}% 为基准件 ${ratio ?? '—'} 倍,判${ratio && ratio >= 2 ? '红' : '黄'}`), + stepDone(`${top.label} ${p1(top.defect)}% 是这一轮的主因档,主导缺陷${dominantDefect(top)};结论落这一档而不是"全线都不行"`), + ], + }; +} + +/* ══════════════════ ② 参数漂移与工艺窗口(DS-16 × DS-12 × DS-08)══════════════════ */ + +function answerDrift(raw: string): AskAnswer { + const trend = trendModel(); + const all = trend.all; + const out = all.filter(s => /^超差/.test(s.latestStatus)); + const warn = all.filter(s => /^预警/.test(s.latestStatus)); + const main = trend.main ?? all[0]; + const last = main.values[main.values.length - 1]; + const first = main.values[0]; + const lastDefect = main.defects[main.defects.length - 1]; + const doe = doeModel(); + const bestYield = (calc.yieldRate(doe.best) || 0) * 100; + const factors = [...doe.factors].sort((a, b) => b.spread - a.spread); + const manualPoints = (TABLES['DS-04'] as unknown as ParamCollectionPoint[]).filter(r => !r.采集方式.includes('自动')); + const mono = main.values.every((v, i) => i === 0 || v <= main.values[i - 1]); + const driftRule = rule('qr-drift'); + + const seriesRows = (TABLES['DS-16'] as unknown as ParamDrift[]) + .filter(r => r.设备 === main.device && r.参数 === main.param) + .sort((a, b) => a.日期.localeCompare(b.日期)); + + return { + intent: INTENT_LABEL.drift, + severity: out.length ? 'danger' : warn.length ? 'warning' : 'info', + conclusion: + `${main.device} 的${main.param}五日一路${last <= first ? '下' : '上'}行(${first}→${last} ${main.unit},标准 ${main.stdText}${main.unit}、允差 ${main.tolText}),` + + `偏移率 ${main.driftLatest === null ? '—' : `${main.driftLatest}%`},状态「${main.latestStatus}」;` + + `同期缺陷率从 ${p1(main.defects[0])}% 抬到 ${p1(lastDefect)}%,与功率的相关系数 ${trend.corr ?? '—'}——` + + `参数掉和缺陷升是同一条劣化曲线的两端,不是两件巧合的事。${out.length} 条序列已超差,处理动作照原表是「${main.latestAction}」。`, + metrics: [ + { label: '超差序列', value: `${out.length}/${all.length}`, tone: out.length ? 'danger' : 'success' }, + { label: '预警序列', value: `${warn.length} 条`, tone: 'warning' }, + { label: `${main.param}最新`, value: `${last}${main.unit}`, tone: 'danger' }, + { label: '偏移率(现算)', value: main.driftLatest === null ? '—' : `${main.driftLatest}%`, tone: 'danger' }, + { label: '同步缺陷率', value: `${p1(lastDefect)}%`, tone: 'warning' }, + { label: '功率↔缺陷相关', value: trend.corr === null ? '—' : String(trend.corr), tone: 'info' }, + ], + table: { + cols: ['日期', '实测均值', '同步缺陷率%', '状态(原表)', '处理动作(原表)'], + rows: seriesRows.map(r => ({ + cells: [r.日期.slice(5), `${r.实测均值} ${r.单位}`, pc(r.同步缺陷率), r.状态, r.处理动作], + tone: /超差/.test(r.状态) ? 'danger' : /预警/.test(r.状态) ? 'warning' : undefined, + })), + }, + points: [ + { label: '判定线', text: `原表口径(DS-16 首行):偏移超允差 60% 或呈单调趋势即预警。本条${mono ? '五日单调下行,趋势条件已成立' : '尚未单调,按偏移量判定'};偏移率 =(实测均值 − 标准值)÷ 标准值(现算)。` }, + { label: '本体规则', text: `${driftRule.name}命中 ${out.length + warn.length} 条记录:${driftRule.hits().targets.join(';')}。` }, + { label: '工艺窗口', text: `DS-12 的 L9 试验给出安全侧窗口:推荐组合 ${doe.best['激光功率(W)']}W/气 ${doe.best['保护气(L/min)']}L/焊速 ${doe.best['焊速(mm/s)']}mm·s⁻¹,综合良率 ${p1(bestYield)}%;功率从 ${factors[0].levels[0].level}W 到 ${factors[0].levels[factors[0].levels.length - 1]?.level}W 均值良率极差 ${factors[0].spread.toFixed(2)}pt,功率是四个因子里最强的一根。`, tone: 'info' }, + { label: '参数卡', text: `DS-08 共 ${recipeModel().cards} 张参数卡覆盖 ${recipeModel().processes} 个工艺;DS-12 的最优组合要落到卡片上才算被锁住,否则换料还是凭经验调参。` }, + { label: '预警盲区', text: `${manualPoints.length} 个采集点仍靠人工录入(${manualPoints.map(r => r.参数名).join('、')}),这些参数根本没有连续序列可判趋势——漂移预警现在就瞎在这几行上。`, tone: 'warning' }, + { label: '跨表矛盾', text: `DS-16 的同步缺陷率是单日抽检口径,DS-09 的近 3 月不良率是 ${QAP_CALIBER.featureDefectSamples.toLocaleString('en-US')} 批次口径,两者数值不可对齐,只能看方向是否一致。`, tone: 'info' }, + ], + actions: [ + { label: '看漂移趋势页签', jump: { kind: 'tab', tab: 'trend' } }, + { label: '超差序列指标', jump: { kind: 'metric', code: 'DRIFT-CURD' } }, + { label: 'DOE 最优组合', jump: { kind: 'metric', code: 'DOE-BEST' } }, + { label: '最强动因 · ' + factors[0].label, jump: { kind: 'metric', code: 'DOE-FACTOR' } }, + { label: '回数据集对账 DS-16', jump: { kind: 'dataset', id: 'DS-16' } }, + { label: '参数卡矩阵 DS-08', jump: { kind: 'dataset', id: 'DS-08' } }, + { label: 'ME 侧的设备参数标准', jump: { kind: 'knowledge', role: 'ME', chunkId: 'me-1' } }, + { label: '接着问:这算不算设备问题', jump: { kind: 'ask', text: '这些数据够做质量预测吗,还差什么?' } }, + ], + source: SOURCE([ + `DS-16 参数漂移监控记录 ${n('DS-16')} 行(按设备+参数并成 ${all.length} 条序列)`, + `DS-12 激光焊 DOE 试验 ${n('DS-12')} 组`, + `DS-04 采集点 ${n('DS-04')} 个`, + '本体规则 qr-drift', + ]), + steps: [ + stepParse(raw, 'drift'), + stepFetch(`读 DS-16 ${n('DS-16')} 行漂移记录,同设备同参数并序为 ${all.length} 条;再取 DS-12 ${n('DS-12')} 组试验与 DS-04 ${n('DS-04')} 个采集点`), + stepRule(`qr-drift「偏移率 > 允差 60% 或单调下行」→ 超差 ${out.length} 条、预警 ${warn.length} 条;主序列 ${main.device}·${main.param} 五日 ${main.values.join('→')}`), + stepCross(`同步缺陷率与实测均值做皮尔逊相关 → r = ${trend.corr ?? '—'}(负值即功率越低缺陷越高);DOE 主效应显示功率极差 ${factors[0].spread.toFixed(2)}pt 为四因子之首`), + stepGrade(`${out.length ? `有序列状态写明超差 → 判红(原表状态列口径)` : '全部在允差内 → 判绿'};人工采集点 ${manualPoints.length} 个单列为盲区,不参与定级`), + stepDone(`${main.param} ${first}→${last}${main.unit} 与缺陷率 ${p1(main.defects[0])}%→${p1(lastDefect)}% 同向,按原表动作「${main.latestAction}」处理,并把 ${doe.best['激光功率(W)']}W 窗口写回参数卡`), + ], + }; +} + +/* ══════════════════ ③ 异常闭环与滞留(DS-15 × DS-11 × 告警流)══════════════════ */ + +function answerClosed(raw: string): AskAnswer { + const abn = abnormalModels(); + const open = abn.filter(a => !a.closed).sort((a, b) => b.dwell - a.dwell); + const overdue = open.filter(a => a.overdue); + const closed = abn.filter(a => a.closed); + const worst = open[0]; + const avg = open.length ? sum(open.map(a => a.dwell)) / open.length : 0; + const noOwner = open.filter(a => !a.owner || a.owner === '—'); + const sumAlert = alertSummary(); + const list = qualityAlerts(); + const dup = hit('qr-dup8d'); + const groups = rootCauseGroupsSafe(); + + return { + intent: INTENT_LABEL.closed, + severity: overdue.length ? 'danger' : 'warning', + conclusion: + `三日预警池 ${abn.length} 单里 ${open.length} 单未闭环,${overdue.length} 单滞留已超过 3 天——按 DS-15 口径这几单必须升级至管理层,不能再压在车间里等;` + + `最长一单 ${worst?.order}(${worst?.defect}|${worst?.severity})滞留 ${worst?.dwell} 天、责任人「${worst?.owner || '—'}」,升级级别写的是「${worst?.escalation}」。` + + `未闭环平均滞留 ${p1(avg)} 天,已闭环的 ${closed.length} 单滞留 ${closed.map(c => c.dwell).join('、')} 天,节奏差距就在这几行里。`, + metrics: [ + { label: '未闭环', value: `${open.length}/${abn.length} 单`, tone: 'danger' }, + { label: '超 3 天待升级', value: `${overdue.length} 单`, tone: 'danger' }, + { label: '平均滞留(现算)', value: `${p1(avg)} 天`, tone: 'warning' }, + { label: '最长滞留', value: `${worst?.dwell ?? 0} 天`, tone: 'danger' }, + { label: '告警队列红档', value: `${sumAlert.red} 张`, tone: 'danger' }, + { label: '无责任人', value: `${noOwner.length} 单`, tone: noOwner.length ? 'warning' : 'success' }, + ], + table: { + cols: ['异常单号', '缺陷', '严重度', '滞留天(现算)', '当前状态', '升级级别', '责任人'], + rows: abn.map(a => ({ + cells: [a.order, a.defect, a.severity, String(a.dwell), a.statusText, a.escalation, a.owner || '—'], + tone: a.overdue && !a.closed ? 'danger' : !a.closed ? 'warning' : undefined, + })), + }, + points: [ + { label: '滞留口径', text: `滞留天数 = 基准日 ${QAP_CALIBER.warningPoolBaseDate} − 发生日(DS-15 计算列,现算);>3 天自动升级至管理层是原表写明的规则,不是本层自设。` }, + { label: '本体规则', text: `qr-dwell「预警滞留升级」命中 ${overdue.length} 单;qr-open「异常未闭环」命中 ${open.length} 单——未闭环是敞口,超期才是必须动的那一刀。` }, + { label: '告警同数', text: `右栏告警流共 ${sumAlert.total} 张卡(${list.filter(a => a.kind === 'abnormal').length} 张异常单卡),命中 ${sumAlert.matched} 行源表记录、扫描 ${sumAlert.scanned} 行;这里的条数与卡片数一致,因为两处调同一个函数。`, tone: 'info' }, + { label: '可复用对策', text: `DS-11 里相似度 > ${QAP_CALIBER.duplicateGuardThreshold} 的重复问题已有 ${dup.n} 条被拦截,根因类别以${groups.slice(0, 2).map(g => `${g.label}(${g.n} 件)`).join('、')}居多——这几单若与历史 8D 相似,该直接复用已验证对策,而不是重开一轮分析。` }, + { + label: '认领缺口', + text: noOwner.length + ? `${noOwner.length} 单未闭环且责任人栏为空——「滞留」多半不是没处理,而是没人认领。` + : '未闭环单都挂了责任人,滞留属跟进速度问题而不是认领问题。', + tone: noOwner.length ? 'warning' : 'success', + }, + ], + actions: [ + { label: '看风险预警页签', jump: { kind: 'tab', tab: 'risk' } }, + { label: '预警池指标', jump: { kind: 'metric', code: 'ALERT-POOL' } }, + { label: '回数据集对账 DS-15', jump: { kind: 'dataset', id: 'DS-15' } }, + { label: '相似 8D 检索 DS-11', jump: { kind: 'metric', code: 'DUP-GUARD' } }, + { label: '本体里的升级规则', jump: { kind: 'ontology' } }, + { label: 'QE 的异常闭环标准', jump: { kind: 'knowledge', role: 'QE', chunkId: 'qe-1' } }, + { label: '接着问:标准到底缺哪几项', jump: { kind: 'ask', text: '检验标准还缺哪几项,能复用历史 8D 吗?' } }, + ], + source: SOURCE([ + `DS-15 三日预警池快照 ${n('DS-15')} 行`, + `DS-11 8D 知识库 ${n('DS-11')} 条`, + `告警流 ${sumAlert.total} 张卡`, + `基准日 ${QAP_CALIBER.warningPoolBaseDate}`, + ]), + steps: [ + stepParse(raw, 'closed'), + stepFetch(`读 DS-15 ${n('DS-15')} 单预警池快照,滞留天数按基准日现算;再取 DS-11 ${n('DS-11')} 条 8D 与右栏 ${sumAlert.total} 张告警卡`), + stepRule(`qr-open 当前状态 ≠ 已闭环 → ${open.length} 单;qr-dwell 滞留 > 3 天 → ${overdue.length} 单待升级;qr-dup8d 相似度 > ${QAP_CALIBER.duplicateGuardThreshold} → ${dup.n} 条`), + stepCross(`未闭环单与告警流异常单卡逐条比对 → 同一函数源,条数一致;已闭环 ${closed.length} 单滞留 ${closed.map(c => c.dwell).join('、')} 天,作为对照不入均值`), + stepGrade(`超期未闭环 ${overdue.length} 单按原表口径判红;其余未闭环按严重度落黄;已闭环压灰留全貌,不凭空删条`), + stepDone(`先把 ${overdue.map(o => o.order).join('、') || '暂无'} 升级到管理层,其余 ${open.length - overdue.length} 单按责任人跟进,重复问题走 8D 复用`), + ], + }; +} + +/** DS-11 根因类别分布(本体层没导出,这里从源表直接分组,保证与指标脊同口径) */ +function rootCauseGroupsSafe() { + const src = TABLES['DS-11'] as unknown as { 根因类别: string }[]; + const m = new Map(); + src.forEach(r => m.set(r.根因类别, (m.get(r.根因类别) ?? 0) + 1)); + return [...m.entries()].map(([label, count]) => ({ label, n: count })).sort((a, b) => b.n - a.n); +} + +/* ══════════════════ ④ 工序产能瓶颈(DS-14 × DS-02 × DS-10)══════════════════ */ + +function answerBottleneck(raw: string): AskAnswer { + const lines = [...lineModels()].sort((a, b) => b.load - a.load); + const stations = stationModels(); + const worst = lines[0]; + const redLines = lines.filter(l => l.status === 'red'); + const over = lines.filter(l => l.load > 100); + const wipTotal = sum(lines.map(l => l.wip)); + const worstWip = [...lines].sort((a, b) => b.wip - a.wip)[0]; + const minStation = [...stations].sort((a, b) => a.rate - b.rate)[0]; + const bn = stations.filter(s => s.bottleneck !== '否'); + const methods = methodModels(); + const bnRule = rule('qr-bottleneck'); + + return { + intent: INTENT_LABEL.bottleneck, + severity: /最大瓶颈/.test(worst.warn) ? 'danger' : 'warning', + conclusion: + `${worst.label}是全线最粗的一道瓶颈:负荷率 ${p1(worst.load)}%(需求 ${worst.demand} 对实际产能 ${worst.capacity} 件·班⁻¹),${worst.wip} 件在制品正压在这一位。` + + `七道工序里 ${over.length} 道负荷超 100%、${redLines.length} 道被原表判为瓶颈/最大瓶颈,在制品合计 ${wipTotal.toLocaleString('en-US')} 件;` + + `工位侧同一结论——${minStation.station}产能达成率 ${p1(minStation.rate)}% 垫底。原表给这一道的建议是「${worst.advice}」。`, + metrics: [ + { label: `最大负荷率 · ${worst.label}`, value: `${p1(worst.load)}%`, tone: 'danger' }, + { label: '需求 / 实际', value: `${worst.demand} / ${worst.capacity}`, tone: 'danger' }, + { label: '超 100% 工序', value: `${over.length}/${lines.length}`, tone: 'warning' }, + { label: '瓶颈工序数', value: `${redLines.length} 道`, tone: 'danger' }, + { label: '在制品合计', value: `${wipTotal.toLocaleString('en-US')} 件`, tone: 'warning' }, + { label: '最低工位达成率', value: `${p1(minStation.rate)}%`, tone: 'danger' }, + ], + table: { + cols: ['工序', '工位/设备', '需求(件/班)', '实际(件/班)', '负荷率%(现算)', '在制品', '预警'], + rows: lines.map(l => ({ + cells: [l.label, l.station, String(l.demand), String(l.capacity), p1(l.load), String(l.wip), l.warn], + tone: l.status === 'red' ? 'danger' : l.status === 'yellow' ? 'warning' : undefined, + })), + }, + points: [ + { label: '负荷率口径', text: `负荷率 = 需求节拍 ÷ 实际产能(DS-14 计算列,现算);需求节拍由订单 SRV-2U-620 月需求 ${QAP_CALIBER.monthlyDemand.toLocaleString('en-US')} 件 ÷(${QAP_CALIBER.workDays} 工作日 × ${QAP_CALIBER.shifts} 班)反推。` }, + { label: '本体规则', text: `${bnRule.name}命中 ${bnRule.hits().n} 道工序:${bnRule.hits().targets.join('、')}。其余工序的排产改善都要绕开这一道才有效。` }, + { label: '原表建议', text: `瓶颈段建议「${worst.advice}」;${lines.filter(l => /严重瓶颈/.test(l.warn)).map(l => `${l.label}「${l.advice}」`).join(',')}——先解最紧的这一段。`, tone: 'warning' }, + { label: '工位侧印证', text: `DS-02 ${stations.length} 个工位里 ${bn.length} 个被标为瓶颈(${bn.map(b => b.station).join('、')}),全部落在焊接与折弯段;理论产能 = ROUND(480 ÷ 标准工时),${minStation.station}标准工时 ${minStation.hours} min·件⁻¹ → 理论 ${minStation.theory} 件·班⁻¹、实际 ${minStation.actual} 件。` }, + { label: '工法差', text: `同样件数下手工氩弧焊一次良率 ${methods[0].values['一次良率']}%、激光焊 ${methods[2].values['一次良率']}%,手工件返修工时 ${methods[0].values['返修/补焊工时']} min/件对激光 ${methods[2].values['返修/补焊工时']} min——设备化既补产能又补良率,DS-10 的「差异结论」列已写明提升 14~20 个百分点。`, tone: 'info' }, + { label: '跨表矛盾', text: `DS-14 的负荷率分母是订单节拍,DS-02 的达成率分母是 480min 理论产能,两个口径不是同一把尺;这里分别列示,不合成一个"产能指数"。`, tone: 'warning' }, + ], + actions: [ + { label: '看结构/负荷页签', jump: { kind: 'tab', tab: 'structure' } }, + { label: `瓶颈工序明细 · ${worst.label}`, jump: { kind: 'metric', code: worst.code } }, + { label: '最大负荷率指标', jump: { kind: 'metric', code: 'LOAD-MAX' } }, + { label: `最低工位 · ${minStation.station}`, jump: { kind: 'metric', code: minStation.code } }, + { label: '三种焊接方式对比', jump: { kind: 'metric', code: 'METHOD-FPY' } }, + { label: '回数据集对账 DS-14', jump: { kind: 'dataset', id: 'DS-14' } }, + { label: '本体里的瓶颈规则与动作', jump: { kind: 'ontology' } }, + { label: '接着问:改善要先补哪块数据', jump: { kind: 'ask', text: '这些数据够做质量预测吗,还差什么?' } }, + ], + source: SOURCE([ + `DS-14 工序负荷与线平衡 ${n('DS-14')} 道工序`, + `DS-02 工位设备台账 ${n('DS-02')} 个工位`, + `DS-10 手工与设备对比 ${n('DS-10')} 项`, + '本体规则 qr-bottleneck', + ]), + steps: [ + stepParse(raw, 'bottleneck'), + stepFetch(`读 DS-14 ${n('DS-14')} 道工序的节拍与产能、DS-02 ${n('DS-02')} 个工位的标准工时;负荷率与理论产能全部现算`), + stepRule(`qr-bottleneck「预警 = 最大瓶颈」→ ${bnRule.hits().targets.join('、')};DS-02 瓶颈列命中 ${bn.length} 个工位`), + stepCross(`工序侧(负荷率 ${p1(worst.load)}% 最高)与工位侧(达成率 ${p1(minStation.rate)}% 最低)都落在${worst.label}段 → 两个口径互相印证;在制品最多的一档${worstWip.label === worst.label ? '正是' : '不是'}最大瓶颈`), + stepGrade(`原表「预警」列判档:最大瓶颈/严重瓶颈红,超负荷黄;两把尺(订单节拍 / 480min 理论)不合成一个指数`), + stepDone(`先动 ${worst.label}:${worst.advice};同时把${bn.map(b => b.station).join('、')}的瓶颈一并列入同一轮改善`), + ], + }; +} + +/* ══════════════════ ⑤ 标准缺口与知识复用(DS-07 × DS-03 × DS-11 × DS-06)══════════════════ */ + +function answerStandard(raw: string): AskAnswer { + const cov = coverageModel(); + const alias = hit('qr-alias'); + const dup = hit('qr-dup8d'); + const build = standardBuildModel(); + const rp = riskPoints(); + const fatal = rp.filter(r => r.severity === '致命'); + const aliases = (TABLES['DS-03'] as unknown as { 缺陷码: string; 缺陷名称: string; '历史别名(待归并)'?: string }[]) + .filter(r => r['历史别名(待归并)']); + const dups = duplicateHits(); + + return { + intent: INTENT_LABEL.standard, + severity: cov.pending.length ? 'warning' : 'success', + conclusion: + `检验标准 ${cov.total} 项里 ${cov.pending.length} 项还挂在「待 QE 确认」,已覆盖 ${cov.rate}%——缺口是${cov.pending.map(p => p.检验项目).join('、')}。` + + `AI 提示列已经点出这两处标准缺失并回指相似件历史 8D,但状态列未生效,现场没法照此检验;` + + `同时缺陷字典还有 ${alias.n} 个码挂着历史别名待归并,${dup.n} 条 8D 相似度已超 ${QAP_CALIBER.duplicateGuardThreshold} 该复用而不是重开分析。`, + metrics: [ + { label: '待 QE 确认', value: `${cov.pending.length}/${cov.total} 项`, tone: 'warning' }, + { label: '标准覆盖率', value: `${cov.rate}%`, tone: 'info' }, + { label: '待归并别名码', value: `${alias.n} 个`, tone: 'warning' }, + { label: '重复 8D 拦截', value: `${dup.n} 条`, tone: 'danger' }, + { label: '夹具验收项', value: `${build.acceptanceItems} 条`, tone: 'info' }, + { label: 'SOP 步骤', value: `${build.sopSteps} 步`, tone: 'info' }, + ], + table: { + cols: ['检验项目', '依据', '抽样', 'AI 提示', '状态'], + rows: (TABLES['DS-07'] as unknown as { '特征/项目': string; 检验项目: string; 依据: string; 抽样: string; 'AI 提示': string; 状态: string }[]) + .map(r => ({ + cells: [r.检验项目, r.依据, r.抽样, r['AI 提示'], r.状态], + tone: r.状态 === '待 QE 确认' ? 'warning' : undefined, + })), + }, + points: [ + { label: '判定线', text: `缺口口径照原表:DS-07 状态列 =「待 QE 确认」才算缺口,确认后生效;本层不自设"标准完备度评分"。` }, + ...cov.pending.map(p => ({ + label: `缺口 · ${p.检验项目}`, + text: `依据「${p.依据}」,AI 提示原文:${p['AI 提示']}。${p.抽样 !== '' ? `拟用抽样 ${p.抽样}、量具 ${p.量具}、频次 ${p.频次}。` : ''}`, + tone: 'warning' as AskTone, + })), + { label: '别名归并', text: `${alias.n} 个缺陷码各有 2~3 个车间叫法(${aliases.slice(0, 2).map(a => `${a.缺陷名称}:${a['历史别名(待归并)']}`).join(';')})。归并前,同一现象在异常、8D、检验三处各记各的,统计必然失真。`, tone: 'danger' }, + { label: '知识复用', text: `相似度 = 缺陷码 + 特征码 + 现象描述三重匹配(DS-11 口径);${dup.n} 条已超 ${QAP_CALIBER.duplicateGuardThreshold},最高 ${dups[0]?.相似度 ?? '—'}(${dups[0]?.['8D编号']} ${dups[0]?.客户}),按本体动作「检索相似 8D」直接复用已验证对策。` }, + { label: '补齐物', text: `DS-06 已把两个缺口物化:${build.fixtures} 套夹具共 ${build.acceptanceItems} 条验收项(判定标准 + 更换复检阈值 + 点检频次),SOP 节选 ${build.sopSteps} 步、每步「常见错误」回指历史缺陷码。`, tone: 'info' }, + { label: '四段归属', text: `标准链按 PE 定风险 → IE 定作业标准 → QE 定检验标准 → ME 锁设备参数走:${cov.pending.length} 项缺口全在 QE 段,但根因来自 PE 的风险点检未覆盖关键特征(致命风险 ${fatal.length} 项,最高频「${[...rp].sort((a, b) => b.count - a.count)[0].label}」历史发生 ${[...rp].sort((a, b) => b.count - a.count)[0].count} 次)。` }, + ], + actions: [ + { label: '看区域/标准页签', jump: { kind: 'tab', tab: 'region' } }, + { label: '检验标准缺口指标', jump: { kind: 'metric', code: 'STD-GAP' } }, + { label: '夹具验收与 SOP 补齐', jump: { kind: 'metric', code: 'STD-BUILD' } }, + { label: '8D 重复拦截指标', jump: { kind: 'metric', code: 'DUP-GUARD' } }, + { label: '回数据集对账 DS-07', jump: { kind: 'dataset', id: 'DS-07' } }, + { label: '缺陷字典 DS-03', jump: { kind: 'dataset', id: 'DS-03' } }, + { label: 'QE 的检验标准知识切片', jump: { kind: 'knowledge', role: 'QE', chunkId: 'qe-2' } }, + { label: 'IE 的 SOP 建议切片', jump: { kind: 'knowledge', role: 'IE', chunkId: 'ie-1' } }, + { label: '本体里的标准规则', jump: { kind: 'ontology' } }, + ], + source: SOURCE([ + `DS-07 检验标准与遗漏提示 ${n('DS-07')} 项`, + `DS-03 缺陷代码字典 ${n('DS-03')} 行`, + `DS-11 8D 知识库 ${n('DS-11')} 条`, + `DS-06a ${n('DS-06a')} 条验收项 + DS-06b ${n('DS-06b')} 步 SOP`, + ]), + steps: [ + stepParse(raw, 'standard'), + stepFetch(`读 DS-07 ${n('DS-07')} 项检验标准、DS-03 ${n('DS-03')} 个缺陷码(含待归并别名列)、DS-11 ${n('DS-11')} 条 8D、DS-06 两张补齐表`), + stepRule(`qr-confirm 状态 = 待 QE 确认 → ${cov.pending.length} 项;qr-alias 别名列非空 → ${alias.n} 个码;qr-dup8d 相似度 > ${QAP_CALIBER.duplicateGuardThreshold} → ${dup.n} 条`), + stepCross(`待确认项的「AI 提示」逐条回指 DS-11 相似件 8D,与 DS-05 风险点检的致命项 ${fatal.length} 条交叉比对 → 缺口在检验段,源头在 PE 风险识别段`), + stepGrade(`只有源表状态列写明「待 QE 确认」的才判黄;覆盖率 ${cov.rate}% 是分母明确的实数,不给"标准完备度"编分数`), + stepDone(`${cov.pending.map(p => p.检验项目).join('、')}由 QE 当确认人落地,同时先做别名归并,否则归因统计仍不可比`), + ], + }; +} + +/* ══════════════════ ⑥ 数据充分性体检(DS-04 × DS-01 × DS-13 × 规则缺口)══════════════════ */ + +function answerData(raw: string): AskAnswer { + const coll = collectionModel(); + const rows = TABLES['DS-04'] as unknown as ParamCollectionPoint[]; + const manual = rows.filter(r => !r.采集方式.includes('自动')); + const auto = rows.filter(r => r.采集方式.includes('自动')); + const master = masterModel(); + const preds = predictionModels(); + const blind = preds.filter(p => p.blind); + const verify = rule('qr-verify'); + const blocked = ONT_RULES.filter(r => r.blocked); + const alias = hit('qr-alias'); + const dup = hit('qr-dup8d'); + const noStd = rows.filter(r => !Number.isFinite(Number(r.标准值))); + + return { + intent: INTENT_LABEL.data, + severity: 'warning', + conclusion: + `底座不缺表,缺的是三类字段:${coll.points} 个采集点分布在 ${coll.devices} 台设备,${manual.length} 个仍靠人工录入(${manual.map(r => r.参数名).join('、')}),` + + `这些参数拿不到连续序列,漂移预警就判不了趋势;本体 ${ONT_RULES.length} 条规则里 ${blocked.length} 条跑不出结果——「${verify.name}」缺 SRV-2U-720 的试制实测良率,` + + `新机型侧 ${blind.length} 件标为「无相似件」无法预测。主数据 ${master.items} 个料号 / ${master.models} 个机型是齐的,${master.welded} 个涉焊。`, + metrics: [ + { label: '采集点', value: `${coll.points} 个`, tone: 'info' }, + { label: '自动采集率', value: `${p1(coll.autoRate)}%`, tone: 'warning' }, + { label: '人工录入点', value: `${manual.length} 个`, tone: 'danger' }, + { label: '良率可预测', value: `${preds.length - blind.length}/${preds.length} 件`, tone: blind.length ? 'warning' : 'success' }, + { label: '可执行规则', value: `${ONT_RULES.length - blocked.length}/${ONT_RULES.length} 条`, tone: 'warning' }, + { label: '主数据料号', value: `${master.items}/${master.models} 机型`, tone: 'success' }, + ], + table: { + cols: ['设备编号', '设备名称', '参数名', '标准值', '允许区间', '采集频率', '采集方式'], + rows: rows.map(r => ({ + cells: [r.设备编号, r.设备名称, r.参数名, String(r.标准值), r.允许区间, r.采集频率, r.采集方式], + tone: r.采集方式.includes('自动') ? undefined : 'warning', + })), + }, + points: [ + { label: '前置条件', text: `DS-04 口径写明:采集数据强制携带料号 + 批次号 + 时间戳,这是关联分析(S3)与漂移预警(S4)的前置条件。现在 ${auto.length} 个自动点满足,${manual.length} 个手工点靠人补,时间戳精度与漏采都不可控。` }, + { label: '规则缺口', text: `${verify.name}(blocked):${verify.gap ?? ''}本批数据集是投产前评估,没有实测列可回验——这条只能标灰,不能标绿。`, tone: 'danger' }, + { label: '预测盲区', text: `DS-13 ${preds.length} 件新机型里 ${blind.length} 件相似机型为「无相似件」:${blind.map(b => `${b.item}(相似度 ${b.sim}%)`).join('、')}${blind.length ? '' : '(本批无盲区)'};其余 ${preds.length - blind.length} 件由相似件实际良率给出区间。`, tone: 'warning' }, + { label: '可比性前提', text: `${alias.n} 个缺陷码的别名未归并。归并之前,异常、8D、检验三处的同类问题各记各的,任何占比与 Pareto 都是不可比口径——这是数据问题而不是分析技巧问题。`, tone: 'danger' }, + { label: '标准值不可算', text: noStd.length + ? `${noStd.length} 个采集点的标准值写成非数值(${noStd.map(r => `${r.参数名}「${r.标准值}」`).join('、')}),偏移率算不出来,DS-16 对应序列的偏移率列留空而不是填 0。` + : '全部采集点标准值均可数值化,偏移率可算。', tone: 'info' }, + { label: '表内自洽', text: `${dup.n} 条 8D 已超相似度阈值,说明知识侧字段结构够用;缺的是设备侧连续采集与试制实测回流这两块,接上后本层的规则缺口会自己消失。` }, + ], + actions: [ + { label: '看全景驾驶舱', jump: { kind: 'tab', tab: 'cockpit' } }, + { label: '自动采集率指标', jump: { kind: 'metric', code: 'DATA-COLLECT' } }, + { label: '良率可预测度指标', jump: { kind: 'metric', code: 'PREDICT-BLIND' } }, + { label: '产品结构主数据', jump: { kind: 'metric', code: 'MASTER-DATA' } }, + { label: '回数据集对账 DS-04', jump: { kind: 'dataset', id: 'DS-04' } }, + { label: '新机型良率预测 DS-13', jump: { kind: 'dataset', id: 'DS-13' } }, + { label: '看本体里的规则与数据缺口', jump: { kind: 'ontology' } }, + { label: '接着问:标准缺哪几项', jump: { kind: 'ask', text: '检验标准还缺哪几项,能复用历史 8D 吗?' } }, + ], + source: SOURCE([ + `DS-04 采集点台账 ${n('DS-04')} 点`, + `DS-01 主数据 ${n('DS-01')} 料号`, + `DS-13 良率预测 ${n('DS-13')} 件`, + `本体规则 ${ONT_RULES.length} 条 / 动作 ${ONT_ACTIONS.length} 个`, + ]), + steps: [ + stepParse(raw, 'data'), + stepFetch(`读 DS-04 ${n('DS-04')} 个采集点、DS-01 ${n('DS-01')} 个料号、DS-13 ${n('DS-13')} 件预测;逐点判断采集方式与标准值可否数值化`), + stepRule(`遍历本体 ${ONT_RULES.length} 条规则的 hits() → 可执行 ${ONT_RULES.length - blocked.length} 条,blocked ${blocked.length} 条(${blocked.map(b => b.name).join('、')})`), + stepCross(`自动点 ${auto.length} 个 vs 人工点 ${manual.length} 个;可预测 ${preds.length - blind.length} 件 vs 无相似件 ${blind.length} 件;${alias.n} 个待归并别名会让三处统计不可比`), + stepGrade(`缺口只按「有没有这列」判定,不按"数据质量评分"判定:blocked 规则标灰、盲区标黄,其余标齐`), + stepDone(`先补 SRV-2U-720 的试制实测良率与人工采集点自动化,${ONT_RULES.length} 条规则里最后一条才能从灰转可执行`), + ], + }; +} + +/* ══════════════════ ⑦ 能力说明(兜底)══════════════════ */ + +function answerHelp(raw: string): AskAnswer { + const alerts = alertSummary(); + return { + intent: INTENT_LABEL.help, + severity: 'info', + conclusion: + `我读的是这本「品质异常预防工作台」的 ${n('DS-01') + n('DS-02') + n('DS-03') + n('DS-04') + n('DS-05') + n('DS-06a') + n('DS-06b') + n('DS-07') + n('DS-08') + n('DS-09') + n('DS-10') + n('DS-11') + n('DS-12') + n('DS-13') + n('DS-14') + n('DS-15') + n('DS-16')} 行源数据(${Object.keys(TABLES).length} 张表),` + + `按本体层 ${ONT_RULES.length} 条规则现算作答,覆盖六类质量问题:缺陷主因、参数漂移与工艺窗口、异常闭环与滞留、工序产能瓶颈、标准缺口与知识复用、数据充分性。` + + `当前右栏告警 ${alerts.total} 张(红 ${alerts.red}/橙 ${alerts.orange}/蓝 ${alerts.blue}),基准日 ${alerts.baseDate}。`, + metrics: [ + { label: '源表', value: `${Object.keys(TABLES).length} 张`, tone: 'info' }, + { label: '本体对象', value: `${ONT_OBJECTS.length} 个`, tone: 'info' }, + { label: '规则 / 动作', value: `${ONT_RULES.length}/${ONT_ACTIONS.length}`, tone: 'info' }, + { label: '质量意图', value: '6 类', tone: 'info' }, + { label: '告警队列', value: `${alerts.total} 张`, tone: alerts.red ? 'danger' : 'warning' }, + ], + points: [ + { label: '缺陷主因', text: 'DS-09 结构特征 × 缺陷关联矩阵 + DS-03 缺陷字典:哪档特征最伤、主导缺陷是哪一类、与基准件差多少倍。' }, + { label: '参数漂移', text: 'DS-16 五日序列 + DS-12 DOE 工艺窗口 + DS-08 参数卡:参数掉到哪、与缺陷率是否同向、该锁回哪组参数。' }, + { label: '异常闭环', text: 'DS-15 预警池 + 告警流:几单未闭环、几单超 3 天必须升级、责任人有没有认领。' }, + { label: '产能瓶颈', text: 'DS-14 线平衡 + DS-02 工位台账 + DS-10 工法对比:最卡的一道工序、原表建议、工位侧是否同一结论。' }, + { label: '标准缺口', text: 'DS-07 检验标准 + DS-11 8D + DS-06 验收/SOP:哪几项待 QE 确认、别名要不要先归并、哪些对策可直接复用。' }, + { label: '数据充分性', text: 'DS-04 采集点 + DS-01 主数据 + DS-13 预测:能不能撑起预测与预警,本体哪条规则因缺字段跑不出来。', tone: 'info' }, + { label: '口径纪律', text: '源表没写判定线的读数只报高低与倍数,不给达成率;跨表分母不同的数不合并、不换算。', tone: 'warning' }, + ], + actions: SUGGESTED.map((text, i) => ({ label: ['问缺陷主因', '问参数漂移', '问异常闭环', '问产能瓶颈', '问标准缺口', '问数据充分性'][i] ?? text, jump: { kind: 'ask' as const, text } })), + source: SOURCE([ + 'DS-01…DS-16 共 17 张表(前端内置,不落库)', + `本体规则 ${ONT_RULES.length} 条 / 动作 ${ONT_ACTIONS.length} 个`, + '告警流 qualityAlerts()', + ]), + steps: [ + stepParse(raw, 'help'), + stepFetch('未命中六类质量意图 → 列出可读的数据范围与能问的问题'), + stepRule(`本体规则 ${ONT_RULES.length} 条全部现算过一遍,其中 ${ONT_RULES.filter(r => r.blocked).length} 条因缺字段标灰`), + stepDone(`给六类意图各一条示例问句,点进去就是那场演示`), + ], + }; +} + +/** + * 对话区唯一的入口:一句自然语言 → 意图 → 结构化回答。 + * 纯函数、无副作用、无随机——同一句话在同一批数据上永远给出同一张卡, + * 演示可复现,复盘也对得上。 + */ +export function buildAskAnswer(raw: string): { intent: IntentId; answer: AskAnswer } { + const intent = matchIntent(raw); + const answer = + intent === 'defect' ? answerDefect(raw) + : intent === 'drift' ? answerDrift(raw) + : intent === 'closed' ? answerClosed(raw) + : intent === 'bottleneck' ? answerBottleneck(raw) + : intent === 'standard' ? answerStandard(raw) + : intent === 'data' ? answerData(raw) + : answerHelp(raw); + return { intent, answer }; +} diff --git a/src/modules/tfamd-oee/lib/qualityFlow.ts b/src/modules/tfamd-oee/lib/qualityFlow.ts new file mode 100644 index 0000000..99a776c --- /dev/null +++ b/src/modules/tfamd-oee/lib/qualityFlow.ts @@ -0,0 +1,320 @@ +/** + * 质量异常预防流程模型(PE → IE → QE → ME 四角色流转 · 过程指标层)。 + * + * 与指标树的分工和三菱电机那版「流程效能」一致:指标树看**结果**(良率、客诉、质量成本), + * 这里看**过程**——一张风险点检单从工艺口流到制造口,每段停多久、流过多少、一次通过多少、 + * 退回多少。四个角色自上而下流转,正好对应质量职责表里 PE/IE/QE/ME 四行。 + * + * 每个角色挂 4 项质量检查/质量防范 KPI(共 16 项),KPI 的基线取职责表「当前实施情况」 + * 那一列的描述,目标取改善方向;**全部是确定性模拟**: + * 同一 (role, period) 永远得到同一读数,拖底部时间轴沿 12 期平滑演变, + * 不像 Math.random() 那样刷新就变,演示与复盘都可复现。 + * 客户把 8D 报告、风险检验单、异常处理记录、特征树、历史检验报告、设备参数表接进来后, + * 这套数字应当由真实数据替换,模型结构不用改。 + */ + +export type QRoleKey = 'PE' | 'IE' | 'QE' | 'ME'; +export type QIcon = 'wrench' | 'ruler' | 'shield' | 'cog'; + +export interface QualityKpi { + code: string; + zh: string; + unit: string; + /** up = 越高越好,down = 越低越好 */ + polarity: 'up' | 'down'; + /** 现状基线(游标 0 期起点),取自质量职责表「当前实施情况」 */ + base: number; + /** 目标值 */ + target: number; + /** 警戒线:未达标但尚未跌破红档的分界,与 metric_node.alert_threshold 同口径 */ + alert: number; + /** 12 期改善强度:1 = 当期推进到目标,0 = 原地不动,负数 = 继续恶化 */ + improve: number; + /** 小数位:比率类留 1 位,计件计数类取整 */ + decimals: number; + /** 职责表「当前实施情况」原话,卡片直接展示,避免看板数字与业务口径各说各话 */ + now: string; +} + +export interface QualityRole { + key: QRoleKey; + /** 中文角色名 */ + zh: string; + /** 英文全称,用于页签与卡片副标题 */ + en: string; + icon: QIcon; + /** 职责范围:这一段把什么变成什么 */ + duty: string; + /** 输入(承接上一段什么) */ + input: string; + /** 输出(本段交付什么) */ + output: string; + /** 后续动作:交给谁、触发什么 */ + next: string; + /** 当前实施情况的一句话诊断 */ + situation: string; + /** 停留天数基线 / 目标(越短越好) */ + dwell: number; + dwellTarget: number; + /** 月流转量(批次口径,四段刻意用可比的数量级,便于找约束段) */ + flow: number; + flowUnitZh: string; + /** 一次通过率 % 基线 / 目标(越高越好) */ + fpqc: number; + fpqcTarget: number; + /** 月退回/返工件数基线 / 目标(越少越好) */ + rework: number; + reworkTarget: number; + /** 12 期改善强度:+1 = 全期持续变好,-1 = 持续变差 */ + improve: number; + kpis: QualityKpi[]; +} + +/** + * 需求到量产放行的质量预防链,四段。 + * 顺序按质量职责表:PE 定风险 → IE 定作业标准 → QE 定检验标准 → ME 定设备保证。 + */ +export const ROLES: QualityRole[] = [ + { + key: 'PE', zh: '工艺工程师', en: 'Process Engineering', + icon: 'wrench', + duty: '把产品要求拆成风险点检单', + input: '客户图纸 · 特征树 · 历史 8D 报告', + output: '风险点检单 · 关键工序清单', + next: '交 IE 落成作业标准', + situation: '风险识别靠个人经验,手工与设备操作未区分', + dwell: 4.2, dwellTarget: 3.6, + flow: 96, flowUnitZh: '张风险点检单', + fpqc: 86, fpqcTarget: 88, + rework: 14, reworkTarget: 13, + improve: 0.5, + kpis: [ + { code: 'PE-K1', zh: '手工/设备操作区分率', unit: '%', polarity: 'up', base: 46, target: 100, alert: 80, improve: 0.85, decimals: 1, now: '职责表:未明确区分手工与设备操作' }, + { code: 'PE-K2', zh: '风险点检项覆盖率', unit: '%', polarity: 'up', base: 62, target: 90, alert: 78, improve: 1.05, decimals: 1, now: '新机型风险点仍靠工程师个人补充' }, + { code: 'PE-K3', zh: '关键特征识别完整率', unit: '%', polarity: 'up', base: 71, target: 95, alert: 85, improve: 0.9, decimals: 1, now: '特征树与图纸未逐条对照' }, + { code: 'PE-K4', zh: '工艺漏检引发的异常', unit: '次', polarity: 'down', base: 7, target: 2, alert: 5, improve: 1.0, decimals: 0, now: '异常多追溯到工艺段漏列风险点' }, + ], + }, + { + key: 'IE', zh: '工业工程师', en: 'Industrial Engineering', + icon: 'ruler', + duty: '把风险点检单落成可执行作业标准', + input: 'PE 风险点检单 · 产线节拍', + output: 'SOP · 作业参数匹配建议', + next: '交 QE 定检验标准与抽检方案', + situation: '标准缺失问题集中在换型与手工工位', + dwell: 3.1, dwellTarget: 2.8, + flow: 88, flowUnitZh: '项标准作业匹配', + fpqc: 88, fpqcTarget: 90, + rework: 18, reworkTarget: 16, + improve: 0.2, + kpis: [ + { code: 'IE-K1', zh: 'SOP 标准作业覆盖率', unit: '%', polarity: 'up', base: 58, target: 95, alert: 78, improve: 0.8, decimals: 1, now: '职责表:存在标准缺失问题' }, + { code: 'IE-K2', zh: '待补 SOP 缺失项', unit: '项', polarity: 'down', base: 23, target: 8, alert: 14, improve: 0.75, decimals: 0, now: '换型与手工工位缺口最多' }, + { code: 'IE-K3', zh: '作业参数与工艺匹配率', unit: '%', polarity: 'up', base: 76, target: 96, alert: 88, improve: 1.0, decimals: 1, now: '参数版本靠现场核对,未系统化' }, + { code: 'IE-K4', zh: '动作经济性评审通过率', unit: '%', polarity: 'up', base: 69, target: 90, alert: 82, improve: 0.7, decimals: 1, now: '评审滞后于试产,返工补评审' }, + ], + }, + { + key: 'QE', zh: '质量工程师', en: 'Quality Engineering', + icon: 'shield', + duty: '把作业标准升级为检验标准', + input: 'IE 作业标准 · 客诉与异常处理记录', + output: '检验标准 · 抽检方案 · 8D 闭环', + next: '交 ME 做设备与工装保证确认', + situation: '标准制定依赖个人经验,存在遗漏风险', + dwell: 5.6, dwellTarget: 4.6, + flow: 74, flowUnitZh: '批检验标准发布', + fpqc: 79, fpqcTarget: 88, + rework: 31, reworkTarget: 24, + improve: -0.3, + kpis: [ + { code: 'QE-K1', zh: '检验项遗漏数', unit: '项', polarity: 'down', base: 19, target: 5, alert: 12, improve: -0.3, decimals: 0, now: '职责表:依赖个人经验,存在遗漏风险' }, + { code: 'QE-K2', zh: '检验标准覆盖率', unit: '%', polarity: 'up', base: 74, target: 95, alert: 86, improve: 0.2, decimals: 1, now: '新品检验项与风险点未一一对应' }, + { code: 'QE-K3', zh: '标准复用历史报告率', unit: '%', polarity: 'up', base: 34, target: 70, alert: 55, improve: 0.25, decimals: 1, now: '历史 8D 与检验报告未被检索复用' }, + { code: 'QE-K4', zh: '8D 报告按期闭环率', unit: '%', polarity: 'up', base: 61, target: 90, alert: 78, improve: 0.15, decimals: 1, now: '围堵措施多、根因标准化少' }, + ], + }, + { + key: 'ME', zh: '制造工程师', en: 'Manufacturing Engineering', + icon: 'cog', + duty: '用设备与工装把标准锁住', + input: 'QE 检验标准 · 设备能力数据', + output: '设备参数基线 · 预防性点检计划', + next: '量产后放行,异常回传 PE 更新风险点检单', + situation: 'ME 角色缺位,设备参数由产线代管', + dwell: 2.7, dwellTarget: 2.4, + flow: 82, flowUnitZh: '台次设备保证确认', + fpqc: 88, fpqcTarget: 92, + rework: 17, reworkTarget: 15, + improve: 0.15, + kpis: [ + { code: 'ME-K1', zh: 'ME 专职在岗率', unit: '%', polarity: 'up', base: 30, target: 100, alert: 70, improve: 0.6, decimals: 1, now: '职责表:角色缺位,无专职设备保证' }, + { code: 'ME-K2', zh: '设备参数受控率', unit: '%', polarity: 'up', base: 68, target: 95, alert: 82, improve: 1.0, decimals: 1, now: '参数修改留痕不全,版本难追溯' }, + { code: 'ME-K3', zh: '预防性点检完成率', unit: '%', polarity: 'up', base: 55, target: 92, alert: 76, improve: 0.9, decimals: 1, now: '点检计划多为事后补做' }, + { code: 'ME-K4', zh: '设备原因异常占比', unit: '%', polarity: 'down', base: 22, target: 8, alert: 14, improve: 0.75, decimals: 1, now: '异常归因里设备因素占两成' }, + ], + }, +]; + +/** 两频正弦叠加:让 12 期有起伏但不毛躁,同 seed 同 period 恒定 */ +function wave(period: number, seed: number) { + const p = period + 1; + return Math.sin(p * 0.78 + seed * 1.7) * 0.55 + Math.sin(p * 0.31 + seed * 0.9) * 0.45; +} + +/** 全链流量随季节缓涨(年末新品集中放行),到当期约 +12% */ +const season = (period: number) => 1 + 0.12 * (period - 5.5) / 5.5; + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)); +const r1 = (v: number) => +v.toFixed(1); + +export interface QKpiStats { + code: string; + zh: string; + unit: string; + polarity: 'up' | 'down'; + /** 小数位:随 stats 一起下发,视图不必再按单位猜 */ + decimals: number; + /** 游标时点读数 */ + value: number; + /** 职责表现状基线 */ + base: number; + target: number; + /** 达成率 %(越低越好类取倒数口径) */ + achieve: number; + status: 'green' | 'yellow' | 'red'; + /** 相对基线的变化(已按 polarity 归一:正 = 比现状好) */ + vsBase: number; + now: string; +} + +/** 单段 KPI 游标读数:seed 用角色序号×7+KPI 序号,保证跨角色相位不重叠 */ +function kpiStats(k: QualityKpi, period: number, seed: number): QKpiStats { + const t = period / 11; // 0 → 1 + const span = k.target - k.base; + const drift = clamp(k.improve * t, -0.6, 1); // 相对基线朝目标推进的比例 + const value = +(k.base + span * drift + wave(period, seed) * Math.abs(span) * 0.025).toFixed(k.decimals); + + const ok = k.polarity === 'down' ? value <= k.target : value >= k.target; + const safe = k.polarity === 'down' ? value <= k.alert : value >= k.alert; + const achieve = k.polarity === 'down' + ? +(Math.min((k.target / (value || 1)) * 100, 999)).toFixed(0) + : +(Math.min((value / k.target) * 100, 999)).toFixed(0); + + return { + code: k.code, zh: k.zh, unit: k.unit, polarity: k.polarity, decimals: k.decimals, + value, base: k.base, target: k.target, achieve, + status: ok ? 'green' : safe ? 'yellow' : 'red', + vsBase: +(k.polarity === 'down' ? k.base - value : value - k.base).toFixed(k.decimals), + now: k.now, + }; +} + +export interface QRoleStats { + /** 本段平均停留(天) */ + dwell: number; + dwellTarget: number; + /** 月流转量 */ + flow: number; + /** 一次通过率 % */ + fpqc: number; + fpqcTarget: number; + /** 月退回/返工件数 */ + rework: number; + reworkTarget: number; + /** 在制品:Little 法则 WIP = 吞吐 × 停留 ÷ 30 */ + wip: number; + /** 段达成率 %(停留 40% + 一次通过 40% + 退回 20%) */ + score: number; + status: 'green' | 'yellow' | 'red'; + /** 相对上期的停留变化(天),负 = 在提速 */ + dwellDelta: number | null; + kpis: QKpiStats[]; + /** 本段 KPI 里跌破警戒线(红档)的项数 */ + redKpis: number; +} + +/** 单段停留:roleStats 与环比都要用,抽出来保证两处口径一致 */ +function dwellAt(index: number, period: number) { + const s = ROLES[index]; + const t = (period - 5.5) / 5.5; + return r1(s.dwell * (1 - s.improve * 0.14 * t + wave(period, index * 7 + 1) * 0.05)); +} + +export function roleStats(index: number, period: number): QRoleStats { + const s = ROLES[index]; + const t = (period - 5.5) / 5.5; // -1 → 0 → +1 的全期趋势轴 + const drift = (k: number) => wave(period, index * 7 + k); + + const dwell = dwellAt(index, period); + const fpqc = r1(clamp(s.fpqc + s.improve * 3.4 * t + drift(2) * 1.3, 55, 99.5)); + const flow = Math.round(s.flow * season(period) * (1 + drift(3) * 0.035)); + const rework = Math.max(0, Math.round(s.rework * (1 - s.improve * 0.16 * t - drift(4) * 0.05))); + const wip = Math.round(flow * dwell / 30); + + const score = ( + clamp(s.dwellTarget / dwell, 0.6, 1.2) * 0.4 + + clamp(fpqc / s.fpqcTarget, 0.6, 1.2) * 0.4 + + clamp(s.reworkTarget / Math.max(1, rework), 0.6, 1.2) * 0.2 + ) * 100; + + const kpis = s.kpis.map((k, i) => kpiStats(k, period, index * 7 + 11 + i * 3)); + + return { + dwell, dwellTarget: s.dwellTarget, flow, fpqc, fpqcTarget: s.fpqcTarget, + rework, reworkTarget: s.reworkTarget, wip, + score: +score.toFixed(1), + status: score >= 99.5 ? 'green' : score >= 92 ? 'yellow' : 'red', + dwellDelta: period > 0 ? r1(dwell - dwellAt(index, period - 1)) : null, + kpis, + redKpis: kpis.filter(x => x.status === 'red').length, + }; +} + +export interface QFlowSummary { + /** 端到端闭环周期(各段停留之和,天) */ + cycle: number; + cycleBase: number; + /** 四段一次通过率(各段 FPQC 连乘,%) */ + e2e: number; + e2eBase: number; + /** 有效产出 = 链上最小流转量(约束理论,批次/月) */ + throughput: number; + constraintKey: QRoleKey; + /** 全链在制品 */ + wip: number; + /** 达成率最低的一段 */ + bottleneckKey: QRoleKey; + bottleneckScore: number; + /** 16 项质量 KPI 中的达标项 / 红档项 */ + okKpis: number; + redKpis: number; + kpiTotal: number; +} + +export function qualityStats(period: number): { stats: QRoleStats[]; summary: QFlowSummary } { + const stats = ROLES.map((_, i) => roleStats(i, period)); + const cycle = +stats.reduce((a, x) => a + x.dwell, 0).toFixed(1); + const e2e = +(stats.reduce((a, x) => a * x.fpqc / 100, 1) * 100).toFixed(1); + const constraint = stats.reduce((mi, x, i) => (x.flow < stats[mi].flow ? i : mi), 0); + const worst = stats.reduce((mi, x, i) => (x.score < stats[mi].score ? i : mi), 0); + const all = stats.flatMap(x => x.kpis); + return { + stats, + summary: { + cycle, + cycleBase: +ROLES.reduce((a, s) => a + s.dwell, 0).toFixed(1), + e2e, + e2eBase: +(ROLES.reduce((a, s) => a * s.fpqc / 100, 1) * 100).toFixed(1), + throughput: stats[constraint].flow, + constraintKey: ROLES[constraint].key, + wip: stats.reduce((a, x) => a + x.wip, 0), + bottleneckKey: ROLES[worst].key, + bottleneckScore: stats[worst].score, + okKpis: all.filter(x => x.status === 'green').length, + redKpis: all.filter(x => x.status === 'red').length, + kpiTotal: all.length, + }, + }; +} diff --git a/src/modules/tfamd-oee/lib/qualityMetrics.ts b/src/modules/tfamd-oee/lib/qualityMetrics.ts new file mode 100644 index 0000000..4880194 --- /dev/null +++ b/src/modules/tfamd-oee/lib/qualityMetrics.ts @@ -0,0 +1,1163 @@ +/** + * 中央工作区六个页签的可视化数据层:读数一律现场从 src/data/qap 那 17 张源表算出来, + * 页面不写死统计值,也不接指标树(data/sqlite.ts 的八维经营评分是洁雅履约演示的底座, + * 讲的是经营健康度,与这里的焊接品质口径不通用,所以六页签整体换到本层取数)。 + * + * 三条约定(与 lib/qualityAlerts.ts 保持同一套写法): + * 1. 计算列只走 `calc.*`;比率类字段源表存小数,本层统一 ×100 后交给视图, + * 明细行里的计算列一律带「(现算)」后缀,回数据集总览对账时一眼能认出。 + * 2. 只有源表写明判定规则的读数才给红/黄/绿(DS-14 预警列、DS-15 严重度+滞留>3 天、 + * DS-16 状态列、DS-07 状态列、DS-02 瓶颈列、DS-11 相似度>0.85)。源表没给判定线的标 'na', + * 视图写「源表未设判定线」,不替客户编一个目标值。 + * 3. 严重度→散点纵轴(致命 0.9/严重 0.6/一般 0.3)是**展示映射**不是业务口径, + * 图上必须注明;横向的「历史发生次数」才是源表原值。 + */ +import { + TABLES, CATALOG, calc, datasetById, QAP_CALIBER, num, + type QapTableKey, + type ProductProcessMaster, type StationEquipmentTooling, type DefectCodeDict, + type ParamCollectionPoint, type RiskChecklistItem, type InspectionStandard, + type RecipeMatrix, type FeatureDefectMatrix, type ManualVsMachine, type EightDRecord, + type LaserDoeRun, type YieldPrediction, type LineBalance, type WarningPoolItem, type ParamDrift, +} from '../data/qap'; +import { qualityAlerts, type QualityAlert } from './qualityAlerts'; + +/* ══════════════════ 公共助手 ══════════════════ */ + +export type Status = 'red' | 'yellow' | 'green' | 'na'; + +/** 源表存小数 → 展示百分数(数值,不带 %) */ +export const pctOf = (v: number | null | undefined, digits = 1): number | null => + v === null || v === undefined || !Number.isFinite(v) ? null : +(v * 100).toFixed(digits); + +/** 明细单元格:比率一律已 ×100 并带上小数位,视图不再猜单位;小数位补齐,避免同列出现 31 与 23.3 混排 */ +const pc = (v: number | null | undefined, digits = 1): string => { + const x = pctOf(v, digits); + return x === null ? '—' : x.toFixed(digits); +}; + +export type Cell = string | number | null; +export type DisplayRow = Record; + +export interface DetailTable { + /** 回「数据集总览」对账用的表键 */ + tableKey: QapTableKey; + title: string; + columns: string[]; + rows: DisplayRow[]; + /** 需要高亮的那一行(下钻来源) */ + focus?: { column: string; value: string }; +} + +const rowsOf = (key: K) => TABLES[key] as unknown as Record[]; +const table = (key: K) => TABLES[key] as unknown as DisplayRow[]; +const dsName = (id: string) => datasetById(id)?.name ?? id; +const dsCaliber = (id: string) => datasetById(id)?.caliber ?? ''; +const dsRole = (id: string) => datasetById(id)?.role ?? '—'; +const sum = (xs: number[]) => xs.reduce((a, x) => a + x, 0); +const mean = (xs: number[]) => (xs.length ? sum(xs) / xs.length : 0); + +/** 皮尔逊相关系数:漂移趋势与同步缺陷率的同向程度 */ +function pearson(a: number[], b: number[]): number | null { + if (a.length < 3 || a.length !== b.length) return null; + const ma = mean(a); + const mb = mean(b); + let num_ = 0; + let da = 0; + let db = 0; + a.forEach((x, i) => { + const dx = x - ma; + const dy = b[i] - mb; + num_ += dx * dy; + da += dx * dx; + db += dy * dy; + }); + if (!da || !db) return null; + return +(num_ / Math.sqrt(da * db)).toFixed(3); +} + +/* ══════════════════ DS-09 结构特征 × 缺陷 ══════════════════ */ + +export const DEFECT_COLUMNS = ['焊瘤', '未焊透', '搭接不良', '焊接变形'] as const; + +export interface FeatureModel { + code: string; + label: string; + item: string; + samples: number; + conclusion: string; + /** 四类缺陷率(%),顺序与 DEFECT_COLUMNS 一致 */ + parts: number[]; + /** 综合不良率 =(现算)% 与 综合良率 % */ + defect: number; + yieldRate: number; +} + +export function featureModels(): FeatureModel[] { + return (TABLES['DS-09'] as unknown as FeatureDefectMatrix[]).map(r => { + const d = calc.defectRate(r) * 100; + return { + code: `DS09:${r.典型料号}`, + label: r.结构特征维度, + item: r.典型料号, + samples: r.样本数, + conclusion: r.结论, + parts: DEFECT_COLUMNS.map(c => +(r[c] * 100).toFixed(2)), + defect: +d.toFixed(2), + yieldRate: +((1 - d / 100) * 100).toFixed(2), + }; + }); +} + +/** 样本加权综合不良率:Σ(特征不良率 × 样本数) ÷ Σ样本数 */ +export function overallDefectRate(): number { + const fs = featureModels(); + const s = sum(fs.map(f => f.samples)); + return +((sum(fs.map(f => f.defect * f.samples)) / s)).toFixed(2); +} + +/** 结论里写明「作为对比基准」的那一行 */ +export function baselineFeature(): FeatureModel | undefined { + return featureModels().find(f => /基准/.test(f.conclusion)); +} + +export function ds09Rows(): DisplayRow[] { + return (TABLES['DS-09'] as unknown as FeatureDefectMatrix[]).map(r => ({ + 结构特征维度: r.结构特征维度, + 典型料号: r.典型料号, + 样本数: r.样本数.toLocaleString('en-US'), + ...Object.fromEntries(DEFECT_COLUMNS.map(c => [c, pc(r[c])])), + '综合不良率%(现算)': ((calc.defectRate(r) || 0) * 100).toFixed(1), + 结论: r.结论, + })); +} + +/* ══════════════════ DS-03 缺陷代码字典 ══════════════════ */ + +export interface DefectModel { + code: string; + name: string; + defectCode: string; + process: string; + detect: string; + severity: string; + special: boolean; + /** 近 3 月占比 % */ + share: number; + h8d: number; +} + +export function defectModels(): DefectModel[] { + return (TABLES['DS-03'] as unknown as DefectCodeDict[]).map(r => ({ + code: `DS03:${r.缺陷码}`, + name: r.缺陷名称, + defectCode: r.缺陷码, + process: r.所属工序, + detect: r.检测方式, + severity: r.严重度, + special: r.特殊特性 === '是', + share: +(r.近3月占比 * 100).toFixed(1), + h8d: r.历史8D数, + })); +} + +/** Pareto:占比降序 + 累计占比(合计为字典内各缺陷占比之和,非全数) */ +export function defectPareto(): (DefectModel & { cum: number })[] { + const list = [...defectModels()].sort((a, b) => b.share - a.share); + const total = sum(list.map(d => d.share)); + let acc = 0; + return list.map(d => { + acc += d.share; + return { ...d, cum: +((acc / total) * 100).toFixed(1) }; + }); +} + +/** 按工序聚合的缺陷占比 */ +export function defectByProcess(): { label: string; share: number; codes: number }[] { + const m = new Map(); + defectModels().forEach(d => { + const cur = m.get(d.process) ?? { share: 0, codes: 0 }; + m.set(d.process, { share: +(cur.share + d.share).toFixed(2), codes: cur.codes + 1 }); + }); + return [...m.entries()] + .map(([label, v]) => ({ label, share: v.share, codes: v.codes })) + .sort((a, b) => b.share - a.share); +} + +export function severityCount(): { label: string; n: number; share: number }[] { + const list = defectModels(); + const total = sum(list.map(d => d.share)); + return ['致命', '严重', '一般'].map(s => { + const share = +((sum(list.filter(d => d.severity === s).map(d => d.share)) / total) * 100).toFixed(1); + return { label: s, n: list.filter(d => d.severity === s).length, share }; + }); +} + +export const defectDictRows = (): DisplayRow[] => + (TABLES['DS-03'] as unknown as DefectCodeDict[]).map(r => ({ + 缺陷码: r.缺陷码, + 缺陷名称: r.缺陷名称, + 所属工序: r.所属工序, + 检测方式: r.检测方式, + 严重度: r.严重度, + 特殊特性: r.特殊特性, + '近3月占比%': pc(r.近3月占比), + 历史8D数: r.历史8D数, + '待归并别名': r['历史别名(待归并)'], + })); + +/* ══════════════════ DS-10 手工 / 机器人 / 激光 ══════════════════ */ + +export const WELD_METHODS = ['手工氩弧焊', '机器人弧焊', '激光焊(设备)'] as const; + +export interface MethodModel { + key: string; + /** 指标名 → 展示值(比率已 ×100) */ + values: Record; + conclusion: Record; +} + +export function methodModels(): MethodModel[] { + const src = TABLES['DS-10'] as unknown as ManualVsMachine[]; + return WELD_METHODS.map(name => { + const key = name as keyof ManualVsMachine; + const values: Record = {}; + const conclusion: Record = {}; + src.forEach(r => { + const v = r[key]; + values[r.对比项] = r.单位 === '%' ? pc(typeof v === 'number' ? v : null) : (v ?? '—'); + conclusion[r.对比项] = r.差异结论; + }); + return { key: name, values, conclusion }; + }); +} + +/** 差异结论列本身就是一句话,单指标对比表用得上 */ +export const methodCompareRows = (): DisplayRow[] => + (TABLES['DS-10'] as unknown as ManualVsMachine[]).map(r => ({ + 对比项: r.对比项, + 手工氩弧焊: r.单位 === '%' ? pc(r.手工氩弧焊) : (r.手工氩弧焊 ?? '—'), + 机器人弧焊: r.单位 === '%' ? pc(r.机器人弧焊) : (r.机器人弧焊 ?? '—'), + '激光焊(设备)': r.单位 === '%' ? pc(r['激光焊(设备)']) : (r['激光焊(设备)'] ?? '—'), + 单位: r.单位, + 差异结论: r.差异结论, + })); + +/* ══════════════════ DS-12 激光焊 DOE ══════════════════ */ + +export interface DoeFactor { + /** 原表列名 */ + column: '激光功率(W)' | '保护气(L/min)' | '焊速(mm/s)' | '离焦量(mm)'; + label: string; + unit: string; + levels: { level: string; meanYield: number; runs: number[] }[]; + /** 极差(最高水平均值 − 最低),就是该因子对良率的动因强度 */ + spread: number; +} + +const DOE_FACTORS: { column: DoeFactor['column']; label: string; unit: string }[] = [ + { column: '激光功率(W)', label: '激光功率', unit: 'W' }, + { column: '保护气(L/min)', label: '保护气', unit: 'L/min' }, + { column: '焊速(mm/s)', label: '焊速', unit: 'mm/s' }, + { column: '离焦量(mm)', label: '离焦量', unit: 'mm' }, +]; + +export function doeModel() { + const runs = TABLES['DS-12'] as unknown as LaserDoeRun[]; + const factors: DoeFactor[] = DOE_FACTORS.map(f => { + const groups = new Map(); + runs.forEach(r => { + const k = String(r[f.column]); + const g = groups.get(k) ?? { runs: [], yields: [] }; + g.runs.push(r.试验号); + g.yields.push(calc.yieldRate(r) * 100); + groups.set(k, g); + }); + const levels = [...groups.entries()] + .sort((a, b) => Number(a[0]) - Number(b[0])) + .map(([level, g]) => ({ level, meanYield: +mean(g.yields).toFixed(2), runs: g.runs })); + const ys = levels.map(l => l.meanYield); + return { ...f, levels, spread: +(Math.max(...ys) - Math.min(...ys)).toFixed(2) }; + }); + const best = runs.reduce((mi, r, i) => (calc.yieldRate(r) > calc.yieldRate(runs[mi]) ? i : mi), 0); + const worst = runs.reduce((mi, r, i) => (calc.yieldRate(r) < calc.yieldRate(runs[mi]) ? i : mi), 0); + const marked = runs.filter(r => r.标记); + return { factors, best: runs[best], worst: runs[worst], marked, runs }; +} + +export const doeRows = (): DisplayRow[] => + (TABLES['DS-12'] as unknown as LaserDoeRun[]).map(r => ({ + 试验号: r.试验号, + '激光功率(W)': r['激光功率(W)'], + '保护气(L/min)': r['保护气(L/min)'], + '焊速(mm/s)': r['焊速(mm/s)'], + '离焦量(mm)': r['离焦量(mm)'], + '焊瘤率%': pc(r.焊瘤率), + '未焊透率%': pc(r.未焊透率), + '综合良率%(现算)': ((calc.yieldRate(r) || 0) * 100).toFixed(1), + 标记: r.标记 ?? '—', + })); + +/* ══════════════════ DS-11 8D 知识库 ══════════════════ */ + +export function rootCauseGroups(): { label: string; n: number; items: string[] }[] { + const src = TABLES['DS-11'] as unknown as EightDRecord[]; + const m = new Map(); + src.forEach(r => m.set(r.根因类别, [...(m.get(r.根因类别) ?? []), r['8D编号']])); + return [...m.entries()].map(([label, items]) => ({ label, n: items.length, items })) + .sort((a, b) => b.n - a.n); +} + +/** 相似度 > 0.85 触发重复问题拦截(原表口径) */ +export function duplicateHits(): EightDRecord[] { + return (TABLES['DS-11'] as unknown as EightDRecord[]) + .filter(r => r.相似度 > QAP_CALIBER.duplicateGuardThreshold) + .sort((a, b) => b.相似度 - a.相似度); +} + +export const eightDRows = (): DisplayRow[] => + (TABLES['DS-11'] as unknown as EightDRecord[]).map(r => ({ + '8D编号': r['8D编号'], + 客户: r.客户, + '机型/料号': r['机型/料号'], + 缺陷码: r.缺陷码, + 根因类别: r.根因类别, + 根因描述: r.根因描述, + 对策: r.对策, + 验证结果: r.验证结果, + 相似度: r.相似度, + })); + +/* ══════════════════ DS-14 工序负荷与线平衡 ══════════════════ */ + +export interface LineModel { + code: string; + label: string; + station: string; + demand: number; + capacity: number; + /** 负荷率 %(现算) */ + load: number; + wip: number; + warn: string; + advice: string; + status: Status; +} + +/** 预警列文案 → 档位:最大瓶颈/严重瓶颈红,其余(超负荷)黄 */ +const lineStatus = (warn: string): Status => + /最大瓶颈|严重瓶颈/.test(warn) ? 'red' : /超负荷/.test(warn) ? 'yellow' : 'na'; + +export function lineModels(): LineModel[] { + return (TABLES['DS-14'] as unknown as LineBalance[]).map(r => ({ + code: `DS14:${r.工序}`, + label: r.工序, + station: r['工位/设备'], + demand: r['需求节拍(件/班)'], + capacity: r['实际产能(件/班)'], + load: +(calc.loadRate(r) * 100).toFixed(1), + wip: r['在制品(件)'], + warn: r.预警, + advice: r.建议, + status: lineStatus(r.预警), + })); +} + +export const lineRows = (): DisplayRow[] => + (TABLES['DS-14'] as unknown as LineBalance[]).map(r => ({ + 工序: r.工序, + '工位/设备': r['工位/设备'], + '需求节拍(件/班)': r['需求节拍(件/班)'], + '实际产能(件/班)': r['实际产能(件/班)'], + '负荷率%(现算)': ((calc.loadRate(r) || 0) * 100).toFixed(1), + '在制品(件)': r['在制品(件)'], + 预警: r.预警, + 建议: r.建议, + })); + +/* ══════════════════ DS-02 工位台账 ══════════════════ */ + +export interface StationModel { + code: string; + station: string; + process: string; + equipment: string; + hours: number; + theory: number; + actual: number; + /** 产能达成率 %(现算) */ + rate: number; + bottleneck: string; + status: Status; +} + +export function stationModels(): StationModel[] { + return (TABLES['DS-02'] as unknown as StationEquipmentTooling[]).map(r => ({ + code: `DS02:${r.工位}`, + station: r.工位, + process: r.工序, + equipment: r.设备, + hours: r['标准工时(min/件)'], + theory: calc.theoryCapacity(r), + actual: r['班次产能(件)'], + rate: +((calc.capacityRate(r) || 0) * 100).toFixed(1), + bottleneck: r.瓶颈, + status: /最大瓶颈/.test(r.瓶颈) ? 'red' : /^是$/.test(r.瓶颈) ? 'yellow' : 'green', + })); +} + +export const stationRows = (): DisplayRow[] => + stationModels().map(s => ({ + 工位: s.station, + 工序: s.process, + 设备: s.equipment, + '标准工时(min/件)': s.hours, + '理论产能(件/班)·现算': s.theory, + '班次产能(件)': s.actual, + '产能达成率%·现算': s.rate.toFixed(1), + 瓶颈: s.bottleneck, + })); + +/* ══════════════════ DS-15 预警池 ══════════════════ */ + +export interface AbnormalModel { + id: string; + order: string; + item: string; + defect: string; + defectCode: string; + severity: string; + occurred: string; + dwell: number; + statusText: string; + escalation: string; + owner: string; + closed: boolean; + overdue: boolean; + status: Status; +} + +export function abnormalModels(): AbnormalModel[] { + return (TABLES['DS-15'] as unknown as WarningPoolItem[]).map(r => { + const dwell = calc.dwellDays(r); + const closed = r.当前状态 === '已闭环'; + const overdue = dwell > 3; + return { + id: `DS15:${r.异常单号}`, + order: r.异常单号, + item: r.料号, + defect: r.缺陷, + defectCode: r.缺陷码, + severity: r.严重度, + occurred: r.发生日, + dwell, + statusText: r.当前状态, + escalation: r.升级级别, + owner: r.责任人, + closed, + overdue, + status: closed ? 'green' : r.严重度 === '致命' || overdue ? 'red' : r.严重度 === '严重' ? 'yellow' : 'na', + }; + }); +} + +export const warningPoolRows = (): DisplayRow[] => + abnormalModels().map(a => ({ + 异常单号: a.order, + 料号: a.item, + 缺陷: a.defect, + 缺陷码: a.defectCode, + 严重度: a.severity, + 发生日: a.occurred, + '滞留天数(现算)': a.dwell, + 当前状态: a.statusText, + 升级级别: a.escalation, + 责任人: a.owner, + })); + +/* ══════════════════ DS-16 参数漂移 ══════════════════ */ + +export interface DriftSeries { + device: string; + param: string; + unit: string; + stdText: string; + /** 数值标准值('按图' 这类为 null) */ + std: number | null; + tolText: string; + /** 由允许偏差算出的上下限(仅 ±x% 形式可用) */ + tolLow: number | null; + tolHigh: number | null; + dates: string[]; + values: number[]; + /** 同步缺陷率 % */ + defects: number[]; + driftLatest: number | null; + latestStatus: string; + latestAction: string; + lifeCap: boolean; +} + +const parseTol = (tol: string, std: number | null): { low: number | null; high: number | null } => { + const m = tol.match(/±\s*([\d.]+)\s*%/); + if (m && std !== null) { + const k = Number(m[1]) / 100; + return { low: +(std * (1 - k)).toFixed(1), high: +(std * (1 + k)).toFixed(1) }; + } + return { low: null, high: null }; +}; + +export function driftSeries(): DriftSeries[] { + const src = TABLES['DS-16'] as unknown as ParamDrift[]; + const groups = new Map(); + src.forEach(r => { + const k = `${r.设备}|${r.参数}`; + groups.set(k, [...(groups.get(k) ?? []), r]); + }); + return [...groups.values()].map(list => { + const asc = [...list].sort((a, b) => a.日期.localeCompare(b.日期)); + const last = asc[asc.length - 1]; + const std = num(last.标准值); + const tol = parseTol(last.允许偏差, std); + return { + device: last.设备, + param: last.参数, + unit: last.单位, + stdText: String(last.标准值), + std, + tolText: last.允许偏差, + tolLow: tol.low, + tolHigh: tol.high, + dates: asc.map(r => r.日期.slice(5)), + values: asc.map(r => r.实测均值), + defects: asc.map(r => +(r.同步缺陷率 * 100).toFixed(1)), + driftLatest: calc.driftRate(last) === null ? null : +((calc.driftRate(last) || 0) * 100).toFixed(2), + latestStatus: last.状态, + latestAction: last.处理动作, + lifeCap: last.允许偏差.includes('上限'), + }; + }); +} + +/** 监控中真正带时间序列(≥2 天)的参数 */ +export const trendableSeries = () => driftSeries().filter(s => s.values.length > 1); + +export const driftRows = (): DisplayRow[] => + (TABLES['DS-16'] as unknown as ParamDrift[]).map(r => { + const d = calc.driftRate(r); + return { + 日期: r.日期, + 设备: r.设备, + 参数: r.参数, + 标准值: r.标准值, + 实测均值: r.实测均值, + 单位: r.单位, + '偏移率%(现算)': d === null ? '—' : (d * 100).toFixed(2), + 允许偏差: r.允许偏差, + '同步缺陷率%': pc(r.同步缺陷率), + 状态: r.状态, + 处理动作: r.处理动作, + }; + }); + +/* ══════════════════ DS-05 / DS-07 / DS-13 ══════════════════ */ + +/** 严重度→纵轴权重:展示映射,不是源表口径 */ +export const SEVERITY_WEIGHT: Record = { 致命: 0.9, 严重: 0.6, 一般: 0.3 }; + +export interface RiskPoint { + label: string; + /** 历史发生次数(源表原值) */ + count: number; + severity: string; + owner: string; + measure: string; + method: string; + source: string; + process: string; +} + +export function riskPoints(): RiskPoint[] { + return (TABLES['DS-05'] as unknown as RiskChecklistItem[]).map(r => ({ + label: r.风险项, + count: r.历史发生次数, + severity: r.严重度, + owner: r.责任人, + measure: r.控制措施, + method: r['检验方法/频次'], + source: r.来源引用, + process: r.工序, + })); +} + +export const riskChecklistRows = (): DisplayRow[] => + (TABLES['DS-05'] as unknown as RiskChecklistItem[]).map(r => ({ + 序号: r.序号, + 风险项: r.风险项, + 工序: r.工序, + '历史发生次数': r.历史发生次数, + 严重度: r.严重度, + 控制措施: r.控制措施, + '检验方法/频次': r['检验方法/频次'], + 责任人: r.责任人, + 来源引用: r.来源引用, + })); + +export function coverageModel() { + const rows = TABLES['DS-07'] as unknown as InspectionStandard[]; + const pending = rows.filter(r => r.状态 === '待 QE 确认'); + const covered = rows.filter(r => r.状态 === '已覆盖'); + return { + total: rows.length, + pending, + covered, + /** 已覆盖 ÷ 全部检验项 */ + rate: +((covered.length / rows.length) * 100).toFixed(1), + rows: (): DisplayRow[] => rows.map(r => ({ + '特征/项目': r['特征/项目'], + 检验项目: r.检验项目, + 依据: r.依据, + 抽样: r.抽样, + 量具: r.量具, + 频次: r.频次, + 'AI 提示': r['AI 提示'], + 状态: r.状态, + })), + }; +} + +export interface PredictionModel { + item: string; + similar: string; + sim: number; + actualYield: number | null; + range: string; + defects: string; + advice: string; + blind: boolean; +} + +export function predictionModels(): PredictionModel[] { + return (TABLES['DS-13'] as unknown as YieldPrediction[]).map(r => ({ + item: r['新机型/料号'], + similar: r.相似机型, + sim: +(r.特征相似度 * 100).toFixed(0), + actualYield: pctOf(r.相似机型实际良率), + range: r.预测良率区间, + defects: r['高概率缺陷(Top3)'], + advice: r.建议动作, + blind: r.相似机型 === '无相似件' || r.预测良率区间.includes('无法'), + })); +} + +export const predictionRows = (): DisplayRow[] => + (TABLES['DS-13'] as unknown as YieldPrediction[]).map(r => ({ + '新机型/料号': r['新机型/料号'], + 相似机型: r.相似机型, + '特征相似度': +(r.特征相似度 * 100).toFixed(0), + '相似机型实际良率%': pc(r.相似机型实际良率), + 预测良率区间: r.预测良率区间, + '高概率缺陷(Top3)': r['高概率缺陷(Top3)'], + 建议动作: r.建议动作, + })); + +/* ══════════════════ DS-01 / DS-04 / DS-06 / DS-08 ══════════════════ */ + +export function masterModel() { + const rows = TABLES['DS-01'] as unknown as ProductProcessMaster[]; + const welded = rows.filter(r => !r.焊接作业方式.startsWith('无')); + const byModel = new Map(); + rows.forEach(r => { + const cur = byModel.get(r.机型) ?? { items: 0, annual: 0, welded: 0 }; + byModel.set(r.机型, { + items: cur.items + 1, + annual: cur.annual + r['年用量(件)'], + welded: cur.welded + (r.焊接作业方式.startsWith('无') ? 0 : 1), + }); + }); + return { + items: rows.length, + models: byModel.size, + welded: welded.length, + annual: sum(rows.map(r => r['年用量(件)'])), + byModel: [...byModel.entries()].map(([label, v]) => ({ label, ...v })).sort((a, b) => b.annual - a.annual), + rows: (): DisplayRow[] => rows.map(r => ({ + 料号: r.料号, 品名: r.品名, 机型: r.机型, 材质: r.材质, '板厚(mm)': r['板厚(mm)'], + 结构特征: r.结构特征, 工序数: r.工序数, 焊接作业方式: r.焊接作业方式, '年用量(件)': r['年用量(件)'], + })), + }; +} + +export function collectionModel() { + const rows = TABLES['DS-04'] as unknown as ParamCollectionPoint[]; + const auto = rows.filter(r => r.采集方式.includes('自动')); + return { + points: rows.length, + devices: new Set(rows.map(r => r.设备编号)).size, + autoRate: +((auto.length / rows.length) * 100).toFixed(1), + rows: (): DisplayRow[] => rows.map(r => ({ + 设备编号: r.设备编号, 设备名称: r.设备名称, 参数名: r.参数名, 单位: r.单位, + 标准值: r.标准值, 允许区间: r.允许区间, 采集频率: r.采集频率, 采集方式: r.采集方式, + })), + }; +} + +export function standardBuildModel() { + const fix = rowsOf('DS-06a') as unknown as { 夹具编号: string; 验收项: string }[]; + const sop = rowsOf('DS-06b') as unknown as { 步骤: number; 常见错误: string }[]; + return { + fixtures: new Set(fix.map(f => f.夹具编号)).size, + acceptanceItems: fix.length, + sopSteps: sop.length, + rowsA: () => table('DS-06a'), + rowsB: () => table('DS-06b'), + }; +} + +export function recipeModel() { + const rows = TABLES['DS-08'] as unknown as RecipeMatrix[]; + return { + cards: rows.length, + processes: new Set(rows.map(r => r.工艺)).size, + rows: (): DisplayRow[] => rows.map(r => ({ + 工艺: r.工艺, '材质/板厚': r['材质/板厚'], 焊接形式: r.焊接形式, + '激光功率(W)/电流(A)': r['激光功率(W)/电流(A)'], + '保护气(L/min)': r['保护气(L/min)'], '焊速(mm/s)': r['焊速(mm/s)'], + '离焦量(mm)': r['离焦量(mm)'] ?? '—', 关联缺陷提醒: r.关联缺陷提醒, + })), + }; +} + +/* ══════════════════ 驾驶舱 ══════════════════ */ + +export interface CockpitTile { + code: string; + label: string; + value: string; + unit: string; + sub: string; + status: Status; + ds: string; +} + +export function cockpitTiles(): CockpitTile[] { + const fs = featureModels(); + const worst = fs.reduce((mi, f, i) => (f.defect > fs[mi].defect ? i : mi), 0); + const lines = lineModels(); + const maxLoad = lines.reduce((mi, l, i) => (l.load > lines[mi].load ? i : mi), 0); + const abn = abnormalModels(); + const open = abn.filter(a => !a.closed); + const overdueOpen = open.filter(a => a.overdue); + const series = driftSeries(); + const outOfTol = series.filter(s => /^超差/.test(s.latestStatus)); + const cov = coverageModel(); + const methods = methodModels(); + const doe = doeModel(); + return [ + { + code: 'DEFECT-WGT', label: '样本加权综合不良率', value: overallDefectRate().toFixed(1), unit: '%', + sub: `近 3 个月 ${QAP_CALIBER.featureDefectSamples.toLocaleString('en-US')} 批次 · 六类结构特征`, + status: 'na', ds: 'DS-09', + }, + { + code: fs[worst].code, label: '最高风险结构特征', value: fs[worst].defect.toFixed(1), unit: '%', + sub: `${fs[worst].label} · 样本 ${fs[worst].samples.toLocaleString('en-US')}`, + status: 'na', ds: 'DS-09', + }, + { + code: 'METHOD-FPY', label: '激光焊一次良率', value: String(methods[2].values['一次良率']), unit: '%', + sub: `手工 ${methods[0].values['一次良率']}% · 机器人 ${methods[1].values['一次良率']}%`, + status: 'na', ds: 'DS-10', + }, + { + code: 'DOE-BEST', label: 'DOE 最优组合综合良率', value: ((calc.yieldRate(doe.best) || 0) * 100).toFixed(1), unit: '%', + sub: `试验 ${doe.best.试验号} · ${doe.best['激光功率(W)']}W/${doe.best['保护气(L/min)']}L/${doe.best['焊速(mm/s)']}mm·s⁻¹`, + status: 'na', ds: 'DS-12', + }, + { + code: lines[maxLoad].code, label: `最大工序负荷率 · ${lines[maxLoad].label}`, value: lines[maxLoad].load.toFixed(1), unit: '%', + sub: `需求 ${lines[maxLoad].demand} /实际 ${lines[maxLoad].capacity} 件·班⁻¹ · ${lines[maxLoad].warn}`, + status: lines[maxLoad].status, ds: 'DS-14', + }, + { + code: 'ALERT-POOL', label: '预警池未闭环异常', value: String(open.length), unit: `/${abn.length} 单`, + sub: `超期未闭环 ${overdueOpen.length} 单 · 基准日 ${QAP_CALIBER.warningPoolBaseDate}`, + status: overdueOpen.length ? 'red' : 'yellow', ds: 'DS-15', + }, + { + code: 'DRIFT-CURD', label: '参数漂移超差序列', value: String(outOfTol.length), unit: `/${series.length} 序列`, + sub: outOfTol.length ? `${outOfTol[0].param} ${outOfTol[0].values[outOfTol[0].values.length - 1]}${outOfTol[0].unit}` : '全部在允差内', + status: outOfTol.length ? 'red' : 'green', ds: 'DS-16', + }, + { + code: 'STD-GAP', label: '检验标准待 QE 确认', value: String(cov.pending.length), unit: `/${cov.total} 项`, + sub: `已覆盖 ${cov.covered.length} 项 · 覆盖率 ${cov.rate}%`, + status: 'yellow', ds: 'DS-07', + }, + ]; +} + +/** 驾驶舱雷达:六类结构特征的综合良率,对比线取基准平板 */ +export function radarModel() { + const fs = featureModels(); + const base = baselineFeature(); + return { + axes: fs.map(f => f.label), + values: fs.map(f => +f.yieldRate.toFixed(1)), + compare: fs.map(() => +(base?.yieldRate ?? 0).toFixed(1)), + baselineLabel: base ? `${base.label} ${base.yieldRate.toFixed(1)}%` : '—', + codes: fs.map(f => f.code), + }; +} + +/** 关注清单:与右栏质量告警同一函数源,读数永远一致 */ +export function watchList(limit = 6): QualityAlert[] { + return qualityAlerts().filter(a => a.level !== 'muted').slice(0, limit); +} + +/* ══════════════════ 趋势模型 ══════════════════ */ + +export function trendModel() { + const all = driftSeries(); + const trendable = all.filter(s => s.values.length > 1); + const main = trendable[0]; + return { + all, + trendable, + main: main ?? null, + /** 功率与同步缺陷率的相关系数(负值=功率越低缺陷越高) */ + corr: main ? pearson(main.values, main.defects) : null, + counts: ['超差', '预警', '注意', '临近', '正常'].map(k => ({ + label: k, + n: all.filter(s => s.latestStatus.startsWith(k)).length, + })), + monitored: all.length, + /** 同参数多日监控的序列条数 */ + sequenceCount: trendable.length, + }; +} + +/* ══════════════════ 品质指标脊(指标明细页签)══════════════════ */ + +export interface QualityMetric { + code: string; + name: string; + /** 主读数(已换算成展示单位) */ + value: string; + unit: string; + status: Status; + /** 判定依据:源表写明的规则 */ + rule: string; + /** 一句话读数解释 */ + reading: string; + /** 计算式 */ + formula: string; + group: string; + ds: string; + dsName: string; + role: string; + caliber: string; + detail: DetailTable; +} + +const detail = (tableKey: QapTableKey, columns: string[], rows: DisplayRow[], focus?: DetailTable['focus']): DetailTable => + ({ tableKey, title: `${tableKey} ${dsName(tableKey.split(':')[0])}`, columns, rows, focus }); + +export const METRICS: QualityMetric[] = []; + +const push = (m: QualityMetric) => { METRICS.push(m); }; + +/* ── 不良与良率(DS-09 / DS-03 / DS-10)── */ +push({ + code: 'DEFECT-WGT', name: '样本加权综合不良率', value: overallDefectRate().toFixed(1), unit: '%', + status: 'na', rule: '源表未设判定线:DS-09 只给各结构特征的四类缺陷率,未给合格线', + reading: `六类结构特征按样本数加权,近 3 个月 ${QAP_CALIBER.featureDefectSamples.toLocaleString('en-US')} 批次;基准平板拼焊 ${(baselineFeature()?.defect ?? 0).toFixed(1)}% 是本组里最稳的一档`, + formula: 'Σ(单特征综合不良率 × 样本数) ÷ Σ样本数;综合不良率 = 焊瘤 + 未焊透 + 搭接不良 + 焊接变形', + group: '不良与良率', ds: 'DS-09', dsName: dsName('DS-09'), role: dsRole('DS-09'), caliber: dsCaliber('DS-09'), + detail: detail('DS-09', ['结构特征维度', '典型料号', '样本数', '焊瘤', '未焊透', '搭接不良', '焊接变形', '综合不良率%(现算)', '结论'], ds09Rows()), +}); + +const worstFeature = () => featureModels().reduce((mi, f, i, a) => (f.defect > a[mi].defect ? i : mi), 0); +push({ + code: 'FEATURE-WORST', name: '最高风险结构特征', value: '', unit: '%', + status: 'na', rule: '源表未设判定线;「结论」列写明该特征的主导成因', + reading: '', formula: '同 DS-09 综合不良率(现算)', + group: '不良与良率', ds: 'DS-09', dsName: dsName('DS-09'), role: dsRole('DS-09'), caliber: dsCaliber('DS-09'), + detail: detail('DS-09', ['结构特征维度', '典型料号', '样本数', '焊瘤', '未焊透', '搭接不良', '焊接变形', '综合不良率%(现算)', '结论'], ds09Rows()), +}); +(() => { + const f = featureModels()[worstFeature()]; + const m = METRICS.find(x => x.code === 'FEATURE-WORST')!; + m.code = f.code; + m.value = f.defect.toFixed(1); + m.name = `最高风险结构特征 · ${f.label}`; + m.reading = `样本 ${f.samples.toLocaleString('en-US')} 件,${f.conclusion};是基准平板拼焊(${(baselineFeature()?.defect ?? 0).toFixed(1)}%)的 ${(f.defect / (baselineFeature()?.defect ?? 1)).toFixed(2)} 倍`; + m.detail = { ...m.detail, focus: { column: '典型料号', value: f.item } }; +})(); + +push({ + code: 'DEFECT-TOP', name: '近 3 月最高频缺陷', value: '', unit: '%', + status: 'na', rule: '源表未设判定线;「近3月占比」是字典内各缺陷占比,合计不足 100%', + reading: '', formula: 'DS-03 近3月占比(比率 ×100);历史8D数取字典原值', + group: '不良与良率', ds: 'DS-03', dsName: dsName('DS-03'), role: dsRole('DS-03'), caliber: dsCaliber('DS-03'), + detail: detail('DS-03', ['缺陷码', '缺陷名称', '所属工序', '检测方式', '严重度', '特殊特性', '近3月占比%', '历史8D数', '待归并别名'], defectDictRows()), +}); +(() => { + const d = defectPareto()[0]; + const m = METRICS.find(x => x.code === 'DEFECT-TOP')!; + m.code = d.code; + m.value = d.share.toFixed(1); + m.name = `近 3 月最高频缺陷 · ${d.name}`; + m.reading = `${d.defectCode}|${d.process}|严重度${d.severity}|历史 8D ${d.h8d} 件|Top1 占字典内合计的 ${d.share.toFixed(1)}%`; + m.detail = { ...m.detail, focus: { column: '缺陷码', value: d.defectCode } }; +})(); + +const sevCount = severityCount(); +push({ + code: 'SEVERITY-MIX', name: '致命缺陷占比合计', value: String(sevCount[0].share), unit: '%', + status: 'red', rule: '致命缺陷为特殊特性项,源表 DS-05 把「未焊透」列为致命并要求首件破坏性验证', + reading: `致命档 ${sevCount[0].n} 个缺陷码(未焊透/虚焊漏焊/漏装错装),占字典内合计 ${sevCount[0].share}%;严重档 ${sevCount[1].share}%、一般档 ${sevCount[2].share}%`, + formula: '按严重度分组求 Σ近3月占比,再除以字典内合计', + group: '不良与良率', ds: 'DS-03', dsName: dsName('DS-03'), role: dsRole('DS-03'), caliber: dsCaliber('DS-03'), + detail: detail('DS-03', ['缺陷码', '缺陷名称', '所属工序', '检测方式', '严重度', '特殊特性', '近3月占比%', '历史8D数'], defectDictRows()), +}); + +push({ + code: 'METHOD-FPY', name: '三种焊接方式一次良率', value: '', unit: '%', + status: 'na', rule: '源表未设判定线;「差异结论」列写明设备化提升 14~20 个百分点', + reading: '', formula: 'DS-10 一次良率(比率 ×100),同料号 SRV2U-FANW-01 同批次板材对比', + group: '不良与良率', ds: 'DS-10', dsName: dsName('DS-10'), role: dsRole('DS-10'), caliber: dsCaliber('DS-10'), + detail: detail('DS-10', ['对比项', '手工氩弧焊', '机器人弧焊', '激光焊(设备)', '单位', '差异结论'], methodCompareRows()), +}); +(() => { + const ms = methodModels(); + const m = METRICS.find(x => x.code === 'METHOD-FPY')!; + m.value = String(ms[2].values['一次良率']); + m.reading = `激光焊 ${ms[2].values['一次良率']}% > 机器人 ${ms[1].values['一次良率']}% > 手工 ${ms[0].values['一次良率']}%,手工与设备差 ${(+String(ms[2].values['一次良率']) - +String(ms[0].values['一次良率'])).toFixed(1)}pt;手工件返修工时 ${ms[0].values['返修/补焊工时']}min/件,激光 ${ms[2].values['返修/补焊工时']}min`; +})(); + +/* ── 工艺与试验(DS-12 / DS-08 / DS-11)── */ +const doe = doeModel(); +push({ + code: 'DOE-BEST', name: 'DOE 最优组合综合良率', value: ((calc.yieldRate(doe.best) || 0) * 100).toFixed(1), unit: '%', + status: 'na', rule: '源表未设判定线;「标记」列已把试验 5 定为推荐组合', + reading: `L9 正交 ${doe.runs.length} 组里最优;最差试验 ${doe.worst.试验号} 良率 ${((calc.yieldRate(doe.worst) || 0) * 100).toFixed(1)}%(功率 1300W 时焊瘤率 ${(doe.worst.焊瘤率 * 100).toFixed(0)}%)`, + formula: '综合良率 = 1 − 焊瘤率 − 未焊透率(受控试验仅统计两类目标缺陷)', + group: '工艺与试验', ds: 'DS-12', dsName: dsName('DS-12'), role: dsRole('DS-12'), caliber: dsCaliber('DS-12'), + detail: detail('DS-12', ['试验号', '激光功率(W)', '保护气(L/min)', '焊速(mm/s)', '离焦量(mm)', '焊瘤率%', '未焊透率%', '综合良率%(现算)', '标记'], doeRows(), { column: '试验号', value: String(doe.best.试验号) }), +}); + +const factorSorted = [...doe.factors].sort((a, b) => b.spread - a.spread); +push({ + code: 'DOE-FACTOR', name: `DOE 最强动因 · ${factorSorted[0].label}`, value: factorSorted[0].spread.toFixed(2), unit: 'pt', + status: 'na', rule: '源表未设判定线;极差=该因子各水平均值良率的最高 − 最低', + reading: `${factorSorted[0].label}从 ${factorSorted[0].levels[0].level} 到 ${factorSorted[0].levels[factorSorted[0].levels.length - 1]?.level} ${factorSorted[0].unit},均值良率极差 ${factorSorted[0].spread.toFixed(2)}pt;四个因子极差依次 ${factorSorted.map(f => `${f.label} ${f.spread.toFixed(1)}`).join('、')}`, + formula: 'L9 正交主效应:按因子水平分组求 calc.yieldRate 均值', + group: '工艺与试验', ds: 'DS-12', dsName: dsName('DS-12'), role: dsRole('DS-12'), caliber: dsCaliber('DS-12'), + detail: detail('DS-12', ['试验号', '激光功率(W)', '保护气(L/min)', '焊速(mm/s)', '离焦量(mm)', '焊瘤率%', '未焊透率%', '综合良率%(现算)', '标记'], doeRows()), +}); + +push({ + code: 'RECIPE-CARD', name: '焊接参数卡覆盖', value: String(recipeModel().cards), unit: '张', + status: 'na', rule: '源表未设判定线;参数卡是 ME 段把标准锁进设备的载体', + reading: `覆盖 ${recipeModel().processes} 个工艺、${new Set((TABLES['DS-08'] as unknown as RecipeMatrix[]).map(r => r['材质/板厚'])).size} 种材质板厚组合;「关联缺陷提醒」列给出越界后果`, + formula: 'DS-08 行数;数值来源 DOE 试验与最优批次反推', + group: '工艺与试验', ds: 'DS-08', dsName: dsName('DS-08'), role: dsRole('DS-08'), caliber: dsCaliber('DS-08'), + detail: detail('DS-08', ['工艺', '材质/板厚', '焊接形式', '激光功率(W)/电流(A)', '保护气(L/min)', '焊速(mm/s)', '离焦量(mm)', '关联缺陷提醒'], recipeModel().rows()), +}); + +const dup = duplicateHits(); +push({ + code: 'DUP-GUARD', name: '8D 重复问题拦截命中', value: `${dup.length}/${(TABLES['DS-11'] as unknown as EightDRecord[]).length}`, unit: '件', + status: 'yellow', rule: `相似度 > ${QAP_CALIBER.duplicateGuardThreshold} 触发重复问题拦截(原表口径)`, + reading: `最高 ${dup[0].相似度}(${dup[0]['8D编号']} ${dup[0].客户});根因类别分布 ${rootCauseGroups().map(g => `${g.label} ${g.n}`).join('、')},相似度=缺陷码+特征码+现象描述三重匹配`, + formula: 'DS-11 相似度列 > 0.85 计数', + group: '工艺与试验', ds: 'DS-11', dsName: dsName('DS-11'), role: dsRole('DS-11'), caliber: dsCaliber('DS-11'), + detail: detail('DS-11', ['8D编号', '客户', '机型/料号', '缺陷码', '根因类别', '根因描述', '对策', '验证结果', '相似度'], eightDRows()), +}); + +/* ── 负荷与设备(DS-14 / DS-02 / DS-16 / DS-04)── */ +const lines = lineModels(); +const maxLoad = lines.reduce((mi, l, i) => (l.load > lines[mi].load ? i : mi), 0); +push({ + code: 'LOAD-MAX', name: `最大工序负荷率 · ${lines[maxLoad].label}`, value: lines[maxLoad].load.toFixed(1), unit: '%', + status: lines[maxLoad].status, rule: `源表「预警」列=${lines[maxLoad].warn}`, + reading: `需求 ${lines[maxLoad].demand} 件·班⁻¹,实际 ${lines[maxLoad].capacity} 件·班⁻¹;七道工序负荷率全部 >100%,${lines.filter(l => l.status === 'red').length} 道判为瓶颈/最大瓶颈`, + formula: '负荷率 = 需求节拍 ÷ 实际产能(现算);订单 SRV-2U-620 月需求 12,000 件 ÷(22 工作日 × 2 班)', + group: '负荷与设备', ds: 'DS-14', dsName: dsName('DS-14'), role: dsRole('DS-14'), caliber: dsCaliber('DS-14'), + detail: detail('DS-14', ['工序', '工位/设备', '需求节拍(件/班)', '实际产能(件/班)', '负荷率%(现算)', '在制品(件)', '预警', '建议'], lineRows(), { column: '工序', value: lines[maxLoad].label }), +}); + +push({ + code: 'WIP-TOTAL', name: '产线在制品合计', value: sum(lines.map(l => l.wip)).toLocaleString('en-US'), unit: '件', + status: 'na', rule: '源表未设判定线;DS-02 与 DS-14 的瓶颈工序都排在焊接段', + reading: `七道工序在制品之和,其中 ${lines.reduce((mi, l, i) => (l.wip > lines[mi].wip ? i : mi), 0) === maxLoad ? '最多的一档正是最大瓶颈工序' : '最多的一档不是最大瓶颈工序'} ${Math.max(...lines.map(l => l.wip))} 件`, + formula: 'Σ DS-14 在制品(件)', + group: '负荷与设备', ds: 'DS-14', dsName: dsName('DS-14'), role: dsRole('DS-14'), caliber: dsCaliber('DS-14'), + detail: detail('DS-14', ['工序', '工位/设备', '需求节拍(件/班)', '实际产能(件/班)', '负荷率%(现算)', '在制品(件)', '预警', '建议'], lineRows()), +}); + +const stations = stationModels(); +const minRate = stations.reduce((mi, s, i) => (s.rate < stations[mi].rate ? i : mi), 0); +push({ + code: 'CAP-MIN', name: `最低工位产能达成率 · ${stations[minRate].station}`, value: stations[minRate].rate.toFixed(1), unit: '%', + status: stations[minRate].status, rule: `源表「瓶颈」列:${stations.filter(s => s.bottleneck !== '否').length} 个工位标为瓶颈,其中 ${stations.filter(s => /最大瓶颈/.test(s.bottleneck)).length} 个最大瓶颈`, + reading: `理论产能 ${stations[minRate].theory} 件·班⁻¹(480min ÷ ${stations[minRate].hours}min·件⁻¹),实际 ${stations[minRate].actual} 件;三个焊接工位全被列为瓶颈`, + formula: '理论产能 = ROUND(480 ÷ 标准工时);产能达成率 = 班次产能 ÷ 理论产能(现算)', + group: '负荷与设备', ds: 'DS-02', dsName: dsName('DS-02'), role: dsRole('DS-02'), caliber: dsCaliber('DS-02'), + detail: detail('DS-02', ['工位', '工序', '设备', '标准工时(min/件)', '理论产能(件/班)·现算', '班次产能(件)', '产能达成率%·现算', '瓶颈'], stationRows(), { column: '工位', value: stations[minRate].station }), +}); + +const trend = trendModel(); +const curd = trend.all.filter(s => /^超差/.test(s.latestStatus)); +push({ + code: 'DRIFT-CURD', name: '参数漂移超差序列', value: `${curd.length}/${trend.all.length}`, unit: '序列', + status: curd.length ? 'red' : 'green', rule: '原表口径:偏移超允差 60% 或呈单调趋势即预警;状态列写明超差/预警/注意/正常', + reading: curd.length + ? `${curd[0].device} ${curd[0].param} 实测 ${curd[0].values[curd[0].values.length - 1]}${curd[0].unit},标准 ${curd[0].stdText}${curd[0].unit}、允差 ${curd[0].tolText};五日趋势与同步缺陷率相关系数 ${trend.corr}` + : '全部监控参数仍在允差内', + formula: '偏移率 =(实测均值 − 标准值)÷ 标准值(现算,标准值非数值时留空)', + group: '负荷与设备', ds: 'DS-16', dsName: dsName('DS-16'), role: dsRole('DS-16'), caliber: dsCaliber('DS-16'), + detail: detail('DS-16', ['日期', '设备', '参数', '标准值', '实测均值', '单位', '偏移率%(现算)', '允许偏差', '同步缺陷率%', '状态', '处理动作'], driftRows()), +}); + +const coll = collectionModel(); +push({ + code: 'DATA-COLLECT', name: '设备参数自动采集率', value: coll.autoRate.toFixed(1), unit: '%', + status: 'na', rule: '源表未设判定线;DS-04 口径要求采集数据强制携带料号+批次号+时间戳', + reading: `${coll.points} 个采集点分布在 ${coll.devices} 台设备,${coll.points - Math.round((coll.autoRate / 100) * coll.points)} 个仍靠人工录入(离焦量、后挡料定位),是漂移预警的盲区`, + formula: '采集方式含「自动」的点数 ÷ 全部采集点', + group: '负荷与设备', ds: 'DS-04', dsName: dsName('DS-04'), role: dsRole('DS-04'), caliber: dsCaliber('DS-04'), + detail: detail('DS-04', ['设备编号', '设备名称', '参数名', '单位', '标准值', '允许区间', '采集频率', '采集方式'], coll.rows()), +}); + +/* ── 标准与预警(DS-15 / DS-07 / DS-05 / DS-13 / DS-06 / DS-01)── */ +const abn = abnormalModels(); +const openAbn = abn.filter(a => !a.closed); +const overdueAbn = openAbn.filter(a => a.overdue); +push({ + code: 'ALERT-POOL', name: '预警池未闭环异常', value: `${openAbn.length}/${abn.length}`, unit: '单', + status: overdueAbn.length ? 'red' : 'yellow', rule: `滞留天数 = 基准日 ${QAP_CALIBER.warningPoolBaseDate} − 发生日,>3 天自动升级至管理层`, + reading: `超期未闭环 ${overdueAbn.length} 单${overdueAbn.length ? `(${overdueAbn.map(a => `${a.order} 滞留 ${a.dwell} 天`).join(';')})` : ''};未闭环 ${openAbn.length} 单平均滞留 ${(sum(openAbn.map(a => a.dwell)) / openAbn.length).toFixed(1)} 天、最长 ${Math.max(...openAbn.map(a => a.dwell))} 天(已闭环那单滞留 ${Math.max(...abn.filter(a => a.closed).map(a => a.dwell), 0)} 天,不计入均值)`, + formula: 'DS-15 当前状态 ≠ 已闭环 计数;滞留天数现算', + group: '标准与预警', ds: 'DS-15', dsName: dsName('DS-15'), role: dsRole('DS-15'), caliber: dsCaliber('DS-15'), + detail: detail('DS-15', ['异常单号', '料号', '缺陷', '缺陷码', '严重度', '发生日', '滞留天数(现算)', '当前状态', '升级级别', '责任人'], warningPoolRows()), +}); + +const cov = coverageModel(); +push({ + code: 'STD-GAP', name: '检验标准待 QE 确认', value: `${cov.pending.length}/${cov.total}`, unit: '项', + status: 'yellow', rule: '状态列=「待 QE 确认」即缺口,确认后生效(原表口径)', + reading: `已覆盖 ${cov.covered.length} 项(${cov.rate}%);缺口是${cov.pending.map(p => p.检验项目).join('、')},AI 提示直接引用相似件历史 8D`, + formula: 'DS-07 状态列分组计数', + group: '标准与预警', ds: 'DS-07', dsName: dsName('DS-07'), role: dsRole('DS-07'), caliber: dsCaliber('DS-07'), + detail: detail('DS-07', ['特征/项目', '检验项目', '依据', '抽样', '量具', '频次', 'AI 提示', '状态'], cov.rows()), +}); + +const rp = riskPoints(); +const topRisk = rp.reduce((mi, r, i) => (r.count > rp[mi].count ? i : mi), 0); +push({ + code: 'RISK-TOP', name: `最高频风险项 · ${rp[topRisk].label}`, value: String(rp[topRisk].count), unit: '次', + status: 'na', rule: '源表未设判定线;严重度列给出致命/严重/一般,控制措施已写死参数窗口', + reading: `历史发生 ${rp[topRisk].count} 次,严重度${rp[topRisk].severity},责任人 ${rp[topRisk].owner};控制措施「${rp[topRisk].measure}」;六项风险合计 ${sum(rp.map(r => r.count))} 次历史发生`, + formula: 'DS-05 历史发生次数列(PFMEA + 8D 推导)', + group: '标准与预警', ds: 'DS-05', dsName: dsName('DS-05'), role: dsRole('DS-05'), caliber: dsCaliber('DS-05'), + detail: detail('DS-05', ['序号', '风险项', '工序', '历史发生次数', '严重度', '控制措施', '检验方法/频次', '责任人', '来源引用'], riskChecklistRows(), { column: '风险项', value: rp[topRisk].label }), +}); + +const preds = predictionModels(); +const blind = preds.filter(p => p.blind); +push({ + code: 'PREDICT-BLIND', name: '新机型良率可预测度', value: `${preds.length - blind.length}/${preds.length}`, unit: '件', + status: blind.length ? 'yellow' : 'green', rule: '相似机型=「无相似件」时原表直接写「无法预测」', + reading: `${blind.length ? `盲区 ${blind.map(b => `${b.item}(相似度 ${b.sim}%)`).join('、')},` : ''}可预测的 ${preds.length - blind.length} 件里最低区间 ${preds.filter(p => !p.blind).map(p => p.range).sort()[0]}`, + formula: '相似度 = 材质+板厚+结构特征+焊接方式 加权;预测区间由相似机型实际良率给出', + group: '标准与预警', ds: 'DS-13', dsName: dsName('DS-13'), role: dsRole('DS-13'), caliber: dsCaliber('DS-13'), + detail: detail('DS-13', ['新机型/料号', '相似机型', '特征相似度', '相似机型实际良率%', '预测良率区间', '高概率缺陷(Top3)', '建议动作'], predictionRows()), +}); + +const build = standardBuildModel(); +push({ + code: 'STD-BUILD', name: '夹具验收与 SOP 补齐', value: `${build.acceptanceItems}/${build.sopSteps}`, unit: '验收项/SOP 步', + status: 'na', rule: '源表未设判定线;这两张表是「工装夹具无验收标准」缺口的补齐物', + reading: `${build.fixtures} 套夹具共 ${build.acceptanceItems} 条验收项(判定标准+更换复检阈值+点检频次);SOP 节选 ${build.sopSteps} 步,每步的「常见错误」都回指历史缺陷码`, + formula: 'DS-06a 验收项计数、DS-06b 步骤计数', + group: '标准与预警', ds: 'DS-06', dsName: '夹具验收标准卡 + SOP 节选', role: dsRole('DS-06'), caliber: dsCaliber('DS-06'), + detail: detail('DS-06a', ['夹具编号', '名称', '适用料号', '验收项', '判定标准', '更换/复检阈值', '点检频次', '责任'], build.rowsA()), +}); + +const master = masterModel(); +push({ + code: 'MASTER-DATA', name: '产品结构主数据', value: `${master.items}/${master.models}`, unit: '料号/机型', + status: 'na', rule: '源表未设判定线;主数据是特征码(材质 × 结构特征 × 工艺方法)的地基', + reading: `${master.welded} 个料号涉焊接,年用量合计 ${master.annual.toLocaleString('en-US')} 件;机型 ${[...master.byModel].map(m => `${m.label} ${m.items} 件`).join('、')}`, + formula: 'DS-01 料号计数、机型去重计数', + group: '标准与预警', ds: 'DS-01', dsName: dsName('DS-01'), role: dsRole('DS-01'), caliber: dsCaliber('DS-01'), + detail: detail('DS-01', ['料号', '品名', '机型', '材质', '板厚(mm)', '结构特征', '工序数', '焊接作业方式', '年用量(件)'], master.rows()), +}); + +export const DEFAULT_METRIC = 'DEFECT-WGT'; + +/** + * 指标明细页签的取数入口:先查静态指标脊,再认四个动态下钻族 + * (DS-09 结构特征 / DS-14 工序 / DS-02 工位 / DS-03 缺陷码), + * 让六页签里的任一根柱子都能落到一张带口径的明细卡。 + */ +export function resolveMetric(code: string): QualityMetric | undefined { + const hit = METRICS.find(m => m.code === code); + if (hit) return hit; + const [ds, ...rest] = code.split(':'); + const key = rest.join(':'); + if (ds === 'DS-09' || ds === 'DS09') { + const f = featureModels().find(x => x.item === key || x.label === key); + if (!f) return undefined; + return { + code: f.code, name: `结构特征综合不良率 · ${f.label}`, value: f.defect.toFixed(1), unit: '%', + status: 'na', rule: '源表未设判定线;「结论」列写明该特征的主导缺陷', + reading: `样本 ${f.samples.toLocaleString('en-US')} 件(占近 3 月 ${QAP_CALIBER.featureDefectSamples.toLocaleString('en-US')} 批次的 ${((f.samples / QAP_CALIBER.featureDefectSamples) * 100).toFixed(1)}%),四类缺陷率依次 ${f.parts.map((p, i) => `${DEFECT_COLUMNS[i]} ${p.toFixed(1)}%`).join('、')};${f.conclusion}`, + formula: '综合不良率 = 焊瘤 + 未焊透 + 搭接不良 + 焊接变形(现算)', + group: '不良与良率', ds: 'DS-09', dsName: dsName('DS-09'), role: dsRole('DS-09'), caliber: dsCaliber('DS-09'), + detail: detail('DS-09', ['结构特征维度', '典型料号', '样本数', '焊瘤', '未焊透', '搭接不良', '焊接变形', '综合不良率%(现算)', '结论'], ds09Rows(), { column: '典型料号', value: f.item }), + }; + } + if (ds === 'DS14') { + const l = lineModels().find(x => x.label === key); + if (!l) return undefined; + return { + code: l.code, name: `工序负荷率 · ${l.label}`, value: l.load.toFixed(1), unit: '%', + status: l.status, rule: `源表「预警」列=${l.warn}`, + reading: `需求节拍 ${l.demand} 件·班⁻¹,实际产能 ${l.capacity} 件·班⁻¹,在制品 ${l.wip} 件;建议「${l.advice}」(工位/设备 ${l.station})`, + formula: '负荷率 = 需求节拍 ÷ 实际产能(现算)', + group: '负荷与设备', ds: 'DS-14', dsName: dsName('DS-14'), role: dsRole('DS-14'), caliber: dsCaliber('DS-14'), + detail: detail('DS-14', ['工序', '工位/设备', '需求节拍(件/班)', '实际产能(件/班)', '负荷率%(现算)', '在制品(件)', '预警', '建议'], lineRows(), { column: '工序', value: l.label }), + }; + } + if (ds === 'DS02') { + const s = stationModels().find(x => x.station === key); + if (!s) return undefined; + return { + code: s.code, name: `工位产能达成率 · ${s.station}`, value: s.rate.toFixed(1), unit: '%', + status: s.status, rule: `源表「瓶颈」列=${s.bottleneck}`, + reading: `${s.process}|设备 ${s.equipment}|标准工时 ${s.hours} min·件⁻¹|理论产能 ${s.theory} 件·班⁻¹|班次产能 ${s.actual} 件`, + formula: '理论产能 = ROUND(480 ÷ 标准工时);达成率 = 班次产能 ÷ 理论产能(现算)', + group: '负荷与设备', ds: 'DS-02', dsName: dsName('DS-02'), role: dsRole('DS-02'), caliber: dsCaliber('DS-02'), + detail: detail('DS-02', ['工位', '工序', '设备', '标准工时(min/件)', '理论产能(件/班)·现算', '班次产能(件)', '产能达成率%·现算', '瓶颈'], stationRows(), { column: '工位', value: s.station }), + }; + } + if (ds === 'DS03') { + const d = defectModels().find(x => x.defectCode === key); + if (!d) return undefined; + return { + code: d.code, name: `缺陷占比 · ${d.name}`, value: d.share.toFixed(1), unit: '%', + status: d.severity === '致命' ? 'red' : 'na', rule: d.severity === '致命' ? '严重度=致命,源表 DS-05 要求首件破坏性验证' : '源表未设判定线;严重度列给出档位', + reading: `${d.defectCode}|${d.process}|严重度${d.severity}|特殊特性${d.special ? '是' : '否'}|检测方式 ${d.detect}|历史 8D ${d.h8d} 件`, + formula: 'DS-03 近3月占比(比率 ×100)', + group: '不良与良率', ds: 'DS-03', dsName: dsName('DS-03'), role: dsRole('DS-03'), caliber: dsCaliber('DS-03'), + detail: detail('DS-03', ['缺陷码', '缺陷名称', '所属工序', '检测方式', '严重度', '特殊特性', '近3月占比%', '历史8D数', '待归并别名'], defectDictRows(), { column: '缺陷码', value: d.defectCode }), + }; + } + return undefined; +} + +/** 数据集目录里登记过的全部编号,指标明细页脚用得上(说明这批数来自哪几本表) */ +export const DATASET_IDS = CATALOG.map(c => c.id); diff --git a/src/modules/tfamd-oee/lib/replay.ts b/src/modules/tfamd-oee/lib/replay.ts new file mode 100644 index 0000000..6350f4d --- /dev/null +++ b/src/modules/tfamd-oee/lib/replay.ts @@ -0,0 +1,116 @@ +/** + * 回放投影的公共口径。 + * + * 中央六个页签的源表是**当期快照**(2026-10-16):DS-09 的样本、DS-14 的负荷、 + * DS-15 的告警池都只有这一刻。时间轴向前回放时,不能把这些数字原样复制到过去, + * 也不能另造一套互相矛盾的数。这里用一条确定性的「质量成熟度」曲线做投影: + * + * - 游标 11(2026-10)恒等于 1,投影后的读数与源表逐位一致; + * - 越往前,缺陷率越高、良率越低、告警积压越多、检验缺口越大; + * - 负荷另走季节项(年末新品集中放行),当期最高; + * - 同 (period) 永远得到同一结果,演示与复盘都可复现。 + * + * 投影只改「回放期的读数」,不改源表明细;明细表仍是 2026-10 当期, + * 用于口径对账。页签上的标记会写明「回放推算 · 源表 2026-10 反推」。 + */ + +import { CURRENT_PERIOD, periodDate, periodLabel, periodParts, PERIOD_COUNT } from './time'; + +export interface ReplayFrame { + period: number; + /** 是否停在源表当期 */ + isCurrent: boolean; + /** 质量成熟度:0 = 窗口起点,1 = 源表当期 */ + maturity: number; + /** 缺陷率乘数(≥1,越早越高) */ + defect: number; + /** 良率「距 100% 的差值」乘数(≥1,越早良率越低) */ + yieldHeadroom: number; + /** 告警积压乘数(≥1,越早越多) */ + alert: number; + /** 检验标准缺口乘数(≥1,越早缺口越大) */ + gap: number; + /** 工序负荷乘数(季节项,当期=1,越早越低) */ + load: number; + /** 参数漂移乘数(≤1,越早偏移越小) */ + drift: number; +} + +/** 两频叠加的成熟度曲线:平滑抬升 + 轻微起伏,锚点固定在当期 */ +const curve = (p: number) => + 0.58 + 0.42 * Math.pow(p / (PERIOD_COUNT - 1), 1.08) + 0.028 * Math.sin(p * 0.95 + 0.6); + +const CURVE_START = curve(0); +const CURVE_CURRENT = curve(CURRENT_PERIOD); + +export function replayFrame(period: number): ReplayFrame { + const p = Math.max(0, Math.min(PERIOD_COUNT - 1, period)); + const maturity = +(curve(p) / CURVE_CURRENT).toFixed(4); + const early = 1 - maturity; + const isCurrent = p === CURRENT_PERIOD; + /* 负荷季节项:年末新品集中放行,当期最高;再除以当期值保证 p=11 时正好为 1 */ + const season = (1 + 0.1 * (p - 5.5) / 5.5) / 1.1; + return { + period: p, + isCurrent, + maturity, + defect: isCurrent ? 1 : +(1 + 0.62 * early).toFixed(4), + yieldHeadroom: isCurrent ? 1 : +(1 + 0.55 * early).toFixed(4), + alert: isCurrent ? 1 : +(1 + 1.15 * early).toFixed(4), + gap: isCurrent ? 1 : +(1 + 0.9 * early).toFixed(4), + load: isCurrent ? 1 : +season.toFixed(4), + drift: isCurrent ? 1 : +(0.72 + 0.28 * maturity).toFixed(4), + }; +} + +/** 良率类读数投影:只压缩/放大距 100% 的差值,避免把 88.9% 直接乘成负数 */ +export function projectYield(value: number, frame: ReplayFrame): number { + if (frame.isCurrent) return value; + return +(100 - (100 - value) * frame.yieldHeadroom).toFixed(1); +} + +/** 不良率类读数投影 */ +export function projectDefect(value: number, frame: ReplayFrame): number { + if (frame.isCurrent) return value; + return +(value * frame.defect).toFixed(1); +} + +/** 时间轴背景柱:由同一成熟度曲线合成,不再借用经营指标 OV。 + * 55 → 97:窗口起点红档、中段黄档、当期绿档,和六页签的读数方向一致。 */ +export function replayHealth(period: number): number { + const frame = replayFrame(period); + if (frame.isCurrent) return 97; + const norm = (frame.maturity - CURVE_START / CURVE_CURRENT) / (1 - CURVE_START / CURVE_CURRENT); + return Math.round(55 + 42 * norm + 1.5 * Math.sin(period * 0.8)); +} + +/** 页签标记文案 */ +export const replayTag = (period: number): string => + period === CURRENT_PERIOD ? '源表现算快照' : `回放推算 · ${periodLabel(period)}`; + +/** 回放期的数据日(用于告警池基准日等文案) */ +export const replayBaseDate = (period: number): string => periodDate(period); + +const pad = (n: number) => String(n).padStart(2, '0'); +const daysInMonth = (y: number, m: number) => new Date(y, m, 0).getDate(); + +/** + * 把源表日期(YYYY-MM-DD 或 MM-DD)平移到回放期。 + * 当期原样返回;历史期按 (period - 11) 个月整体平移,日号越界时压到月末。 + * 月份用 UTC 计算,避免本地时区把 1 号挤到上个月。 + */ +export function shiftMonthDate(date: string, period: number): string { + if (period === CURRENT_PERIOD) return date; + const offset = period - CURRENT_PERIOD; + const full = date.match(/^(\d{4})-(\d{2})-(\d{2})$/); + const short = date.match(/^(\d{2})-(\d{2})$/); + if (!full && !short) return date; + const baseYear = full ? Number(full[1]) : periodParts(CURRENT_PERIOD).year; + const baseMonth = Number(full ? full[2] : short![1]); + const baseDay = Number(full ? full[3] : short![2]); + const idx = baseYear * 12 + (baseMonth - 1) + offset; + const year = Math.floor(idx / 12); + const month = (idx % 12) + 1; + const day = Math.min(baseDay, daysInMonth(year, month)); + return full ? `${year}-${pad(month)}-${pad(day)}` : `${pad(month)}-${pad(day)}`; +} diff --git a/src/modules/tfamd-oee/lib/replayQuality.ts b/src/modules/tfamd-oee/lib/replayQuality.ts new file mode 100644 index 0000000..6bc825c --- /dev/null +++ b/src/modules/tfamd-oee/lib/replayQuality.ts @@ -0,0 +1,324 @@ +/** + * 六个品质页签的「回放期」取数层。 + * + * 源表函数(lib/qualityMetrics)保持不动,继续作为 2026-10 当期口径; + * 本层只做一件事:以当期快照为锚,按 lib/replay 的统一曲线回推历史期。 + * 所有回放函数在 period = CURRENT_PERIOD 时直接返回源表结果, + * 保证「当期」与数据总览逐位一致,不会出现两套快照。 + */ + +import { calc } from '../data/qap'; +import { CURRENT_PERIOD, periodLabel } from './time'; +import { + projectDefect, projectYield, replayBaseDate, replayFrame, shiftMonthDate, type ReplayFrame, +} from './replay'; +import { + abnormalModels, cockpitTiles, coverageModel, doeModel, driftSeries, featureModels, lineModels, + methodModels, radarModel, resolveMetric, stationModels, + type AbnormalModel, type CockpitTile, type FeatureModel, type QualityMetric, type Status, +} from './qualityMetrics'; + +/* ── 结构特征 / 雷达 ── */ + +export function featureModelsAt(period: number): FeatureModel[] { + const frame = replayFrame(period); + if (frame.isCurrent) return featureModels(); + return featureModels().map(f => { + /* 综合不良率 = 四类缺陷率之和,投影后必须重新加总,避免主读数与分段对不上 */ + const parts = f.parts.map(p => +(p * frame.defect).toFixed(2)); + const defect = +parts.reduce((a, x) => a + x, 0).toFixed(2); + return { ...f, parts, defect, yieldRate: +(100 - defect).toFixed(2) }; + }); +} + +export function overallDefectRateAt(period: number, features = featureModelsAt(period)): number { + const samples = features.reduce((a, f) => a + f.samples, 0); + return +((features.reduce((a, f) => a + f.defect * f.samples, 0) / samples)).toFixed(2); +} + +export function radarModelAt(period: number) { + if (period === CURRENT_PERIOD) return radarModel(); + const fs = featureModelsAt(period); + const base = fs.find(f => /基准/.test(f.conclusion)); + return { + axes: fs.map(f => f.label), + values: fs.map(f => +f.yieldRate.toFixed(1)), + compare: fs.map(() => +(base?.yieldRate ?? 0).toFixed(1)), + baselineLabel: base ? `${base.label} ${base.yieldRate.toFixed(1)}%` : '—', + codes: fs.map(f => f.code), + }; +} + +/* ── 负荷 / 工位 ── */ + +export function lineModelsAt(period: number) { + const frame = replayFrame(period); + if (frame.isCurrent) return lineModels(); + return lineModels().map(l => ({ + ...l, + load: +(l.load * frame.load).toFixed(1), + wip: Math.round(l.wip * frame.load), + })); +} + +export function stationModelsAt(period: number) { + const frame = replayFrame(period); + if (frame.isCurrent) return stationModels(); + return stationModels().map(s => ({ + ...s, + rate: +(s.rate * frame.load).toFixed(1), + })); +} + +/* ── 告警池 ── */ + +export function abnormalModelsAt(period: number): AbnormalModel[] { + const frame = replayFrame(period); + if (frame.isCurrent) return abnormalModels(); + return abnormalModels().map(a => { + const dwell = a.closed ? a.dwell : Math.max(0, Math.round(a.dwell * frame.alert)); + const overdue = !a.closed && dwell > 3; + const status: Status = a.closed ? 'green' + : a.severity === '致命' || overdue ? 'red' + : a.severity === '严重' ? 'yellow' : 'na'; + return { ...a, occurred: shiftMonthDate(a.occurred, period), dwell, overdue, status }; + }); +} + +/* ── 检验标准缺口 ── */ + +export function coverageModelAt(period: number) { + const base = coverageModel(); + const frame = replayFrame(period); + if (frame.isCurrent) { + return { ...base, pendingCount: base.pending.length, coveredCount: base.covered.length }; + } + const pendingCount = Math.min(base.total, Math.max(base.pending.length, Math.round(base.pending.length * frame.gap))); + const coveredCount = base.total - pendingCount; + return { + ...base, + rate: +((coveredCount / base.total) * 100).toFixed(1), + pendingCount, + coveredCount, + }; +} + +/* ── 参数漂移 ── */ + +const parseTolPct = (tol: string): number | null => { + const m = tol.match(/±\s*([\d.]+)\s*%/); + return m ? Number(m[1]) : null; +}; + +/** 与 DS-16 源表同一套判定:>100% 允差超差、>60% 预警、>40% 注意、>20% 临近 */ +const driftStatus = (ratio: number | null): string | null => { + if (ratio === null) return null; + if (ratio > 1) return '超差(已出允差)'; + if (ratio > 0.6) return '预警(超允差60%)'; + if (ratio > 0.4) return '注意(趋势下行)'; + if (ratio > 0.2) return '临近允差'; + return '正常'; +}; + +export function driftSeriesAt(period: number) { + const base = driftSeries(); + const frame = replayFrame(period); + if (frame.isCurrent) return base; + return base.map(s => { + if (s.std === null) { + return { ...s, dates: s.dates.map(d => shiftMonthDate(d, period)) }; + } + const std = s.std; + const values = s.values.map(v => +(std + (v - std) * frame.drift).toFixed(1)); + const defects = s.defects.map(d => +(d * frame.defect).toFixed(1)); + const latest = values[values.length - 1] ?? std; + const driftLatest = +(((latest - std) / std) * 100).toFixed(2); + const tol = parseTolPct(s.tolText); + const status = driftStatus(tol === null ? null : Math.abs(driftLatest) / tol); + return { + ...s, + dates: s.dates.map(d => shiftMonthDate(d, period)), + values, + defects, + driftLatest, + latestStatus: status ?? s.latestStatus, + }; + }); +} + +/* ── 趋势模型 ── */ + +function pearson(a: number[], b: number[]): number | null { + if (a.length < 3 || a.length !== b.length) return null; + const ma = a.reduce((x, y) => x + y, 0) / a.length; + const mb = b.reduce((x, y) => x + y, 0) / b.length; + let n = 0, da = 0, db = 0; + a.forEach((x, i) => { + const dx = x - ma; + const dy = b[i] - mb; + n += dx * dy; da += dx * dx; db += dy * dy; + }); + if (!da || !db) return null; + return +(n / Math.sqrt(da * db)).toFixed(3); +} + +export function trendModelAt(period: number) { + const all = driftSeriesAt(period); + const trendable = all.filter(s => s.values.length > 1); + const main = trendable[0]; + return { + all, + trendable, + main: main ?? null, + corr: main ? pearson(main.values, main.defects) : null, + counts: ['超差', '预警', '注意', '临近', '正常'].map(k => ({ + label: k, + n: all.filter(s => s.latestStatus.startsWith(k)).length, + })), + monitored: all.length, + sequenceCount: trendable.length, + }; +} + +/* ── DOE ── */ + +export function doeModelAt(period: number) { + const frame = replayFrame(period); + const base = doeModel(); + if (frame.isCurrent) return base; + const factors = base.factors.map(f => { + const levels = f.levels.map(l => ({ ...l, meanYield: projectYield(l.meanYield, frame) })); + const ys = levels.map(l => l.meanYield); + return { ...f, levels, spread: +(Math.max(...ys) - Math.min(...ys)).toFixed(2) }; + }); + return { ...base, factors }; +} + +/* ── 驾驶舱八块读数 ── */ + +export function cockpitTilesAt(period: number): CockpitTile[] { + if (period === CURRENT_PERIOD) return cockpitTiles(); + const frame = replayFrame(period); + const features = featureModelsAt(period); + const worst = features.reduce((mi, f, i) => (f.defect > features[mi].defect ? i : mi), 0); + const lines = lineModelsAt(period); + const maxLoad = lines.reduce((mi, l, i) => (l.load > lines[mi].load ? i : mi), 0); + const abn = abnormalModelsAt(period); + const open = abn.filter(a => !a.closed); + const overdue = open.filter(a => a.overdue); + const series = driftSeriesAt(period); + const outOfTol = series.filter(s => /^超差/.test(s.latestStatus)); + const cov = coverageModelAt(period); + const methods = methodModels(); + const laser = projectYield(Number(methods[2].values['一次良率']), frame); + const manual = projectYield(Number(methods[0].values['一次良率']), frame); + const robot = projectYield(Number(methods[1].values['一次良率']), frame); + const doe = doeModelAt(period); + const doeBest = projectYield(+((calc.yieldRate(doe.best) || 0) * 100).toFixed(1), frame); + + return [ + { + code: 'DEFECT-WGT', label: '样本加权综合不良率', value: overallDefectRateAt(period, features).toFixed(1), unit: '%', + sub: `回放 ${periodLabel(period)} · 六类结构特征按当期曲线回推`, status: 'na', ds: 'DS-09', + }, + { + code: features[worst].code, label: '最高风险结构特征', value: features[worst].defect.toFixed(1), unit: '%', + sub: `${features[worst].label} · 样本 ${features[worst].samples.toLocaleString('en-US')}`, + status: 'na', ds: 'DS-09', + }, + { + code: 'METHOD-FPY', label: '激光焊一次良率', value: laser.toFixed(1), unit: '%', + sub: `手工 ${manual.toFixed(1)}% · 机器人 ${robot.toFixed(1)}%`, status: 'na', ds: 'DS-10', + }, + { + code: 'DOE-BEST', label: 'DOE 最优组合综合良率', value: doeBest.toFixed(1), unit: '%', + sub: `试验 ${doe.best.试验号} · ${doe.best['激光功率(W)']}W/${doe.best['保护气(L/min)']}L/${doe.best['焊速(mm/s)']}mm·s⁻¹`, + status: 'na', ds: 'DS-12', + }, + { + code: lines[maxLoad].code, label: `最大工序负荷率 · ${lines[maxLoad].label}`, value: lines[maxLoad].load.toFixed(1), unit: '%', + sub: `需求 ${lines[maxLoad].demand} /实际 ${lines[maxLoad].capacity} 件·班⁻¹ · ${lines[maxLoad].warn}`, + status: lines[maxLoad].status, ds: 'DS-14', + }, + { + code: 'ALERT-POOL', label: '预警池未闭环异常', value: String(open.length), unit: `/${abn.length} 单`, + sub: `超期未闭环 ${overdue.length} 单 · 基准日 ${replayBaseDate(period)}`, + status: overdue.length ? 'red' : 'yellow', ds: 'DS-15', + }, + { + code: 'DRIFT-CURD', label: '参数漂移超差序列', value: String(outOfTol.length), unit: `/${series.length} 序列`, + sub: outOfTol.length ? `${outOfTol[0].param} ${outOfTol[0].values[outOfTol[0].values.length - 1]}${outOfTol[0].unit}` : '全部在允差内', + status: outOfTol.length ? 'red' : 'green', ds: 'DS-16', + }, + { + code: 'STD-GAP', label: '检验标准待 QE 确认', value: String(cov.pendingCount), unit: `/${cov.total} 项`, + sub: `已覆盖 ${cov.coveredCount} 项 · 覆盖率 ${cov.rate}%`, + status: 'yellow', ds: 'DS-07', + }, + ]; +} + +/* ── 指标明细页签 ── */ + +/** 图表层常用的小投影:不良率 / 良率 / 负荷率 */ +export const defectPctAt = (value: number, period: number) => projectDefect(value, replayFrame(period)); +export const yieldPctAt = (value: number, period: number) => projectYield(value, replayFrame(period)); +export const loadPctAt = (value: number, period: number) => { + const frame = replayFrame(period); + return +(value * frame.load).toFixed(1); +}; + +/** + * 指标明细的主读数投影。只改「读数 / 状态」, + * 口径、计算式、判定依据与明细表仍取源表,避免回放把口径也一起改写。 + */ +export function metricAt(code: string, period: number): QualityMetric | undefined { + const base = resolveMetric(code); + if (!base || period === CURRENT_PERIOD) return base; + const frame = replayFrame(period); + /* 读数值可能带千分位(如 2,700),先剥逗号再判数值,否则会误判成非数值、原样透传 */ + const numeric = Number(String(base.value).replace(/,/g, '')); + const num = Number.isFinite(numeric) ? numeric : null; + let value = base.value; + let status: Status = base.status; + + if (num !== null) { + if (code === 'DEFECT-WGT' || /^DS09:/.test(code)) { + value = projectDefect(num, frame).toFixed(1); + } else if (code === 'METHOD-FPY' || code === 'DOE-BEST') { + value = projectYield(num, frame).toFixed(1); + } else if (code === 'DOE-FACTOR') { + value = (num * (1 + 0.22 * (1 - frame.maturity))).toFixed(2); + } else if (code === 'LOAD-MAX' || /^DS14:/.test(code)) { + value = (num * frame.load).toFixed(1); + } else if (code === 'WIP-TOTAL') { + value = Math.round(num * frame.load).toLocaleString('en-US'); + } else if (code === 'CAP-MIN' || /^DS02:/.test(code)) { + value = (num * frame.load).toFixed(1); + } + } + + if (code === 'ALERT-POOL') { + const abn = abnormalModelsAt(period); + const open = abn.filter(a => !a.closed); + const overdue = open.filter(a => a.overdue); + value = `${open.length}/${abn.length}`; + status = overdue.length ? 'red' : 'yellow'; + } else if (code === 'STD-GAP') { + const cov = coverageModelAt(period); + value = `${cov.pendingCount}/${cov.total}`; + status = 'yellow'; + } else if (code === 'DRIFT-CURD') { + const series = driftSeriesAt(period); + const out = series.filter(s => /^超差/.test(s.latestStatus)); + value = `${out.length}/${series.length}`; + status = out.length ? 'red' : 'green'; + } + + return { ...base, value, status }; +} + +/** 回放期窗口提示:DetailView 底部口径说明用 */ +export const REPLAY_DETAIL_NOTE = '回放期的读数按统一质量曲线回推;口径、计算式与下方明细表仍为源表 2026-10 当期,用于逐行对账。'; + +export type { ReplayFrame }; diff --git a/src/modules/tfamd-oee/lib/teams.ts b/src/modules/tfamd-oee/lib/teams.ts new file mode 100644 index 0000000..21f2a40 --- /dev/null +++ b/src/modules/tfamd-oee/lib/teams.ts @@ -0,0 +1,394 @@ +/** + * 质量专家团(多智能体协作会诊):把若干质量专家拉到一起,围绕当前议题轮流报读数 → 牵头汇总。 + * + * 与单轮问答同一个引擎:每位专家绑定六类质量意图之一,会诊发言里的每个数字都调 + * `qualityAsk.buildAskAnswer(该专家的示例问句)` 现算,所以「会诊里说的数」和 + * 「单独问它说的数」「六个页签看到的数」「右栏告警数」是同一套读数,不会出现两套口径。 + * 专家名册放在本层(不走 data/sqlite 那批经营数字员工):那些智能体讲毛利率、订单交期, + * 与焊接品质异常预防口径不通用,硬套会让会诊说出不属于本应用的话。 + * + * 口径纪律(与 qualityMetrics / qualityAsk 同一套): + * 1. 会诊卡片只报源表写明的读数与判定线,**不显示达成率**——本层 `rate` 恒为 null, + * 徽章位置显示定级与原表状态(state 字段),源表没给线的照实写「源表未设判定线」; + * 2. 定级取自问答引擎的 severity(它已按各表判定列推过),本层不另设阈值; + * 3. 牵头汇总按定级排短板;跨表分母不同的读数只并列、不合并。 + */ +import { abnormalModels, resolveMetric } from './qualityMetrics'; +import { alertSummary } from './qualityAlerts'; +import { INTENT_LABEL, buildAskAnswer, SUGGESTED } from './qualityAsk'; +import type { AskAnswer, AskJump, AskTone, IntentId } from './qualityAsk'; + +/** 卡片主色语义 token(映射到主题色,组件里不硬编码色值) */ +export type TeamTone = 'success' | 'danger' | 'info' | 'warning' | 'accent'; +/** 会诊定级:取自问答引擎 severity;na = 源表未设判定线且无红黄判据 */ +export type SnapLevel = 'good' | 'warn' | 'bad' | 'na'; + +export interface ExpertTeam { + /** 唯一 id:预设团用 key,自由团用时间戳。AgentDock 依赖它变化重新触发会诊 */ + id: string; + nameZh: string; + topicZh: string; + /** 为什么是这几位(面板与开场播报用) */ + brief?: string; + /** 牵头专家 code(负责最终汇总) */ + leadCode: string; + /** 全部成员 code(含牵头,顺序即发言顺序) */ + memberCodes: string[]; + preset: boolean; + tone: TeamTone; +} + +/** + * 会诊卡片顶部的数据条。 + * `rate` 保留但恒为 null:品质侧没有「达成率」这把尺,源表给的是判定列与状态列, + * 卡片因此显示 state(本轮定级)与 deviation(相对高低),避免把品质读数伪装成经营 KPI。 + */ +export interface MetricSnap { + /** 绑定的指标脊 code,点击可跳「指标明细」看同一口径 */ + code: string; + label: string; + value: string; + /** 判定线原文(源表没写线就照实写「源表未设判定线」) */ + line: string; + /** 相对高低:倍数/原表状态/缺口件数,全部现算 */ + deviation: string; + /** 徽章文字(替代达成率) */ + state: string; + rate: number | null; + level: SnapLevel; +} + +/** 一位质量专家:绑定一个意图、一条主读数、一句示例问句 */ +interface ExpertDef { + code: string; + name: string; + role: string; + /** 能力小标签 */ + skill: string; + intent: IntentId; + /** 绑定指标脊 code(会诊卡片的数据条) */ + boundMetric: string; + /** 发言取数用的问句:与快捷问句同句,保证单问与会诊同数 */ + probe: string; + /** 会诊里的当前动作 / 观点 / 建议 / 牵头行动句 / 相对高低 / 跳转落点 */ + status: (a: AskAnswer) => string; + stance: (a: AskAnswer) => string; + proposal: (a: AskAnswer) => string; + action: (a: AskAnswer) => string; + deviation: (a: AskAnswer) => string; + jump: (a: AskAnswer) => AskJump; +} + +export type QualityExpert = Omit< + ExpertDef, 'status' | 'stance' | 'proposal' | 'action' | 'deviation' | 'jump' +> & { intentLabel: string }; + +/* ══════════════════ 取回答卡里的读数(按标签找,不写死数值)══════════════════ */ + +/** 按标签关键词取关键数字;取不到返回破折号,绝不补一个编出来的数 */ +const mv = (a: AskAnswer, key: string, fb = '—') => a.metrics.find(m => m.label.includes(key))?.value ?? fb; +/** 明细表第一行(缺陷/负荷/预警池口径都按严重度降序) */ +const r0 = (a: AskAnswer): string[] => a.table?.rows[0]?.cells ?? []; +/** 明细表最后一行(漂移序列按日期升序,末行即最新一天) */ +const rLast = (a: AskAnswer): string[] => { + const rows = a.table?.rows ?? []; + return rows.length ? rows[rows.length - 1].cells : []; +}; +const levelOf = (sev: AskTone): SnapLevel => + sev === 'danger' ? 'bad' : sev === 'warning' ? 'warn' : sev === 'success' ? 'good' : 'na'; +const stateOf = (a: AskAnswer) => + a.severity === 'danger' ? '本轮判红' + : a.severity === 'warning' ? '本轮判黄' + : a.severity === 'success' ? '本轮判绿' : '源表未设判定线'; + +/* ══════════════════ 六位质量专家 ══════════════════ */ + +const EXPERT_DEFS: ExpertDef[] = [ + { + code: 'QDEF', name: '缺陷归因专家', role: 'QE · 结构特征 × 缺陷', skill: '加权不良率 / 帕累托', + intent: 'defect', boundMetric: 'DEFECT-WGT', probe: SUGGESTED[0], + status: () => '正在把 DS-09 各档结构特征按综合不良率降序排,并比对基准平板拼焊件', + stance: a => `最伤的一档是「${r0(a)[0]}」(${r0(a)[3]}%,主导缺陷 ${r0(a)[5]}),是基准件的 ${r0(a)[4]}——` + + '不良不是均匀摊开的,是压在这几档特征上的。', + proposal: a => `按 qr-hifeature 命中的 ${mv(a, '高于基准件')} 档开专项,先攻「${r0(a)[0]}」:` + + '四类缺陷率逐类定线,线由 QE 与工艺在 DS-07 上一起来定,不凭空拍。', + action: a => `两周内把「${r0(a)[0]}」的四类缺陷率逐类压下来,定线与责任人写回 DS-07`, + deviation: a => `为基准件 ${r0(a)[4]}`, + jump: a => ({ kind: 'metric', code: `DS09:${r0(a)[1]}` }), + }, + { + code: 'QPAR', name: '工艺参数专家', role: 'PE / ME · 参数窗口', skill: '漂移序列 / DOE 主效应', + intent: 'drift', boundMetric: 'DRIFT-CURD', probe: SUGGESTED[1], + status: () => '正在按设备+参数并序读 DS-16,逐条比标准值与允差', + stance: a => `${mv(a, '超差序列')} 序列已判超差、${mv(a, '预警序列')} 条在预警;` + + `最新一条实测 ${rLast(a)[1]},原表状态「${rLast(a)[3]}」——参数掉下去和缺陷升上来是同一条劣化曲线的两端。`, + proposal: a => `照原表处理动作「${rLast(a)[4]}」先恢复,再把 DS-12 推荐窗口写回 DS-08 参数卡;` + + '只调一次不锁卡,换料还是凭经验调参。', + action: () => '把 DS-12 最优组合固化进 DS-08 参数卡,并补人工采集点的连续序列', + deviation: a => `原表状态「${rLast(a)[3]}」`, + jump: () => ({ kind: 'metric', code: 'DOE-BEST' }), + }, + { + code: 'QCLO', name: '异常闭环专家', role: 'QE · 预警池督办', skill: '滞留天数 / 8D 复用', + intent: 'closed', boundMetric: 'ALERT-POOL', probe: SUGGESTED[2], + status: () => '正在按基准日重算预警池滞留天数,并与右栏告警流逐条对齐', + stance: a => `${mv(a, '未闭环')} 里 ${mv(a, '超 3 天待升级')} 单滞留已过 3 天,最长一单 ${mv(a, '最长滞留')}——` + + '按 DS-15 原表口径这几单必须升级至管理层,不能再压在车间里等。', + proposal: a => `${mv(a, '超 3 天待升级')} 单当场升级,${mv(a, '无责任人')} 单补认领人;` + + '与历史 8D 相似的直接复用已验证对策,不重开一轮分析。', + action: a => `升级超期 ${mv(a, '超 3 天待升级')} 单,并补齐 ${mv(a, '无责任人')} 单的空责任人`, + deviation: a => `最长滞留 ${mv(a, '最长滞留')}`, + jump: () => ({ kind: 'metric', code: 'ALERT-POOL' }), + }, + { + code: 'QCAP', name: '产线负荷专家', role: 'IE · 线平衡', skill: '负荷率 / 节拍反推', + intent: 'bottleneck', boundMetric: 'LOAD-MAX', probe: SUGGESTED[3], + status: () => '正在按订单节拍反推各工序负荷率,并与工位台账达成率交叉核对', + stance: a => `最粗的一道瓶颈是「${r0(a)[0]}」,负荷率 ${mv(a, '最大负荷率')}%(需求 ${mv(a, '需求 / 实际')}),` + + `${mv(a, '超 100% 工序')} 道超 100%、${mv(a, '瓶颈工序数')} 道被原表判为瓶颈——在制品 ${mv(a, '在制品合计')} 正压在这一段。`, + proposal: a => `先解「${r0(a)[0]}」这一段,工位侧同一结论;` + + `手工段按 DS-10 往激光焊迁移,既补产能又补良率(一次良率 ${mv(a, '最低工位达成率')}% 那一档最该动)。`, + action: a => `对「${r0(a)[0]}」按原表预警「${r0(a)[6]}」开改善,瓶颈工位并入同一轮`, + deviation: a => `原表判「${r0(a)[6]}」`, + jump: a => ({ kind: 'metric', code: `DS14:${r0(a)[0]}` }), + }, + { + code: 'QSTD', name: '标准治理专家', role: 'QE · 检验标准与知识', skill: '缺口清点 / 别名归并', + intent: 'standard', boundMetric: 'STD-GAP', probe: SUGGESTED[4], + status: () => '正在过 DS-07 状态列与 DS-03 别名列,并检索 DS-11 相似 8D', + stance: a => `${mv(a, '待 QE 确认')} 项检验标准还挂在「待 QE 确认」,覆盖率 ${mv(a, '标准覆盖率')}%;` + + `${mv(a, '待归并别名码')} 个缺陷码的车间别名没归并——归并前,异常、8D、检验三处各记各的,占比统计本就不可比。`, + proposal: a => `QE 当确认人把缺口项落到 DS-07 生效,${mv(a, '重复 8D 拦截')} 条重复问题走本体动作「检索相似 8D」复用,` + + `DS-06 的 ${mv(a, '夹具验收项')} 条验收项先挂进点检。`, + action: a => `确认 ${mv(a, '待 QE 确认')} 项缺口标准,并启动 ${mv(a, '待归并别名码')} 个缺陷码别名归并`, + deviation: a => `覆盖率 ${mv(a, '标准覆盖率')}%`, + jump: () => ({ kind: 'knowledge', role: 'QE', chunkId: 'qe-2' }), + }, + { + code: 'QDAT', name: '数据底座专家', role: 'ME / 数据 · 采集与主数据', skill: '采集覆盖 / 规则可执行', + intent: 'data', boundMetric: 'DATA-COLLECT', probe: SUGGESTED[5], + status: () => '正在逐点判断 DS-04 采集方式与标准值可否数值化,并遍历本体规则可否跑通', + stance: a => `${mv(a, '人工录入点')} 个采集点仍靠人工录入,自动采集率 ${mv(a, '自动采集率')}%;` + + `本体规则可执行 ${mv(a, '可执行规则')} 条——这些参数拿不到连续序列,漂移预警就瞎在这几行上。`, + proposal: () => '先补 SRV-2U-720 的试制实测良率(被拦的那条规则就差这一列回流),再把人工录入点接进自动采集。', + action: a => `接入 ${mv(a, '人工录入点')} 个手工采集点,并回流试制实测良率`, + deviation: a => `自动率 ${mv(a, '自动采集率')}%`, + jump: () => ({ kind: 'dataset', id: 'DS-04' }), + }, +]; + +/** 名册(含意图展示名),供对话区与专家团面板渲染 */ +export function qualityExperts(): QualityExpert[] { + return EXPERT_DEFS.map(({ status, stance, proposal, action, deviation, jump, ...rest }) => ({ + ...rest, + intentLabel: INTENT_LABEL[rest.intent], + })); +} + +const expertDef = (code: string) => EXPERT_DEFS.find(e => e.code === code); + +/** 意图 → 应答专家 code(对话区派发用,与 qualityAsk.DISPATCH 同一套人) */ +export function expertCodeForIntent(intent: IntentId): string { + return expertDefByIntent(intent)?.code ?? 'QDEF'; +} +const expertDefByIntent = (intent: IntentId) => EXPERT_DEFS.find(e => e.intent === intent); + +/* ══════════════════ 5 个预设质量专家团 ══════════════════ */ + +interface PresetDef { + key: string; tone: TeamTone; nameZh: string; topicZh: string; + lead: string; members: string[]; + /** 为什么是这几位(面板与开场播报用) */ + brief: string; +} + +const PRESET_DEFS: PresetDef[] = [ + { + key: 'weld', tone: 'danger', nameZh: '焊接不良攻坚团', topicZh: '结构特征不良归因与对策落地', + lead: 'QDEF', members: ['QDEF', 'QPAR', 'QSTD'], + brief: '先定位哪档特征最伤,再看参数是否已滑出窗口,最后把对策落到检验标准上', + }, + { + key: 'drift', tone: 'warning', nameZh: '参数漂移预警团', topicZh: '工艺窗口、采集盲区与劣化趋势', + lead: 'QPAR', members: ['QPAR', 'QDAT', 'QDEF'], + brief: '漂移序列、采集点覆盖、缺陷率同向性三方对齐,判断是趋势还是抖动', + }, + { + key: 'close', tone: 'info', nameZh: '异常闭环督办团', topicZh: '滞留升级、认领与 8D 复用', + lead: 'QCLO', members: ['QCLO', 'QSTD', 'QDEF'], + brief: '把未闭环与超期单摊开,标准缺口和相似 8D 一并处置,避免重复开分析', + }, + { + key: 'output', tone: 'success', nameZh: '产能良率协同团', topicZh: '瓶颈段负荷与焊接良率同解', + lead: 'QCAP', members: ['QCAP', 'QDEF', 'QPAR'], + brief: '瓶颈段往往也是不良高发段,负荷与良率要一起解,不能只加人', + }, + { + key: 'base', tone: 'accent', nameZh: '质量数据底座团', topicZh: '采集自动化、主数据与规则可执行', + lead: 'QDAT', members: ['QDAT', 'QSTD', 'QCLO'], + brief: '先确认数据撑不撑得起预警与预测,再谈标准与闭环', + }, +]; + +export function presetTeams(): ExpertTeam[] { + return PRESET_DEFS.map(d => ({ + id: d.key, nameZh: d.nameZh, topicZh: d.topicZh, brief: d.brief, + leadCode: d.lead, memberCodes: d.members, preset: true, tone: d.tone, + })); +} + +/** 自由勾选组建:给定 code 列表(首位视作牵头) */ +export function customTeam(codes: string[]): ExpertTeam | null { + if (codes.length < 2) return null; + return { + id: `custom-${Date.now()}`, + nameZh: '自定义质量专家组', + topicZh: '按勾选口径协同会诊', + brief: '勾选 2 位以上质量专家,首位牵头汇总', + leadCode: codes[0], memberCodes: codes, preset: false, tone: 'accent', + }; +} + +/* ══════════════════ 会诊发言 ══════════════════ */ + +/** 会诊里的一条发言(结构化,由 AgentDock 渲染成卡片并按序播放) */ +export interface ConsultTurn { + kind: 'system' | 'member' | 'lead'; + name: string; + /** 角色标签(专家 role / 牵头汇总) */ + tag: string; + /** 该成员负责的意图展示名 */ + intent?: string; + /** system 就位播报纯文本 */ + text?: string; + /** member:当前动作 */ + status?: string; + /** member:绑定主读数 */ + metric?: MetricSnap; + /** member:2 条佐证读数(取自同源回答卡的关键数字) */ + reading?: { label: string; value: string }[]; + /** member:观点一句话 */ + stance?: string; + /** member:具体建议 */ + proposal?: string; + /** member:移交对象名(多智能体衔接) */ + handoff?: string; + /** member:这一眼数据的落点 */ + jump?: AskJump; + /** lead:结论 headline */ + conclusion?: string; + /** lead:成员要点 */ + summary?: { name: string; point: string }[]; + /** lead:综合研判(读数+原表判定线+短板定位,无达成率) */ + judge?: { label: string; value: string; state: string; level: SnapLevel; note: string }; + /** lead:联合行动清单 */ + actions?: { owner: string; role: string; action: string; jump?: AskJump }[]; +} + +/** 主读数条:判定线取自指标脊,定级取自回答卡 severity,本层不另设阈值 */ +function snapOf(def: ExpertDef, a: AskAnswer): MetricSnap { + const m = resolveMetric(def.boundMetric); + return { + code: def.boundMetric, + label: m?.name ?? def.boundMetric, + value: m ? `${m.value}${m.unit}` : '—', + line: m?.rule ?? '源表未设判定线', + deviation: def.deviation(a), + state: stateOf(a), + rate: null, + level: levelOf(a.severity), + }; +} + +const RANK: Record = { bad: 0, warn: 1, na: 2, good: 3 }; + +/** + * 生成完整会诊脚本:就位播报 → 各专家轮流发言(当前动作+主读数+佐证读数+观点+建议+移交) + * → 牵头汇总(结论+成员要点+综合研判+联合行动)。 + * 纯函数、无随机:同一批数据永远同一份脚本,回放与复盘对得上。 + */ +export function buildConsultScript(team: ExpertTeam): ConsultTurn[] { + const defs = team.memberCodes + .map(c => expertDef(c)) + .filter((e): e is ExpertDef => !!e); + if (!defs.length) return []; + + const alerts = alertSummary(); + const turns: ConsultTurn[] = []; + + turns.push({ + kind: 'system', + name: '会诊主持', + tag: '多智能体协作', + text: `「${team.nameZh}」已就位(${defs.length} 位专家):${defs.map(d => d.name).join('、')}。\n` + + `议题「${team.topicZh}」· 基准日 ${alerts.baseDate} · 右栏告警 ${alerts.total} 张(红 ${alerts.red}/橙 ${alerts.orange})。\n` + + `${team.brief ?? '各位依次报现算读数,牵头汇总定联合行动。'}`, + }); + + const lead = expertDef(team.leadCode) ?? defs[0]; + const answers = new Map(); + const snaps = new Map(); + + defs.forEach((d, i) => { + const a = buildAskAnswer(d.probe).answer; + const snap = snapOf(d, a); + answers.set(d.code, a); + snaps.set(d.code, snap); + + const reading = a.metrics.slice(1, 3).map(m => ({ label: m.label, value: m.value })); + const next = i === defs.length - 1 ? lead : defs[i + 1]; + + turns.push({ + kind: 'member', + name: d.name, + tag: d.role, + intent: INTENT_LABEL[d.intent], + status: d.status(a), + metric: snap, + reading, + stance: d.stance(a), + proposal: d.proposal(a), + handoff: i === defs.length - 1 ? `${next.name}(牵头汇总)` : next.name, + jump: d.jump(a), + }); + }); + + /* 牵头汇总:按定级排短板 → 结论 → 成员要点 → 综合研判 → 联合行动 */ + const ranked = defs + .map(d => ({ d, a: answers.get(d.code)!, s: snaps.get(d.code)! })) + .sort((x, y) => RANK[x.s.level] - RANK[y.s.level]); + const worst = ranked[0]; + const leadSnap = snaps.get(lead.code)!; + const leadAnswer = answers.get(lead.code)!; + const openCnt = abnormalModels().filter(x => !x.closed).length; + + turns.push({ + kind: 'lead', + name: lead.name, + tag: '牵头汇总', + conclusion: + `综合 ${defs.length} 位专家口径,「${team.topicZh}」这一轮最紧的是 ${worst.d.name} 线的` + + `「${worst.s.label}」(${worst.s.value},${worst.s.deviation});` + + `预警池 ${openCnt} 单未闭环、右栏 ${alerts.red} 张红档告警,` + + `本轮判红 ${ranked.filter(x => x.s.level === 'bad').length} 线、判黄 ${ranked.filter(x => x.s.level === 'warn').length} 线。`, + summary: defs.map(d => ({ + name: d.name, + point: (answers.get(d.code)!.conclusion.split(';')[0] ?? '').slice(0, 62), + })), + judge: { + label: leadAnswer.intent, + value: leadSnap.value, + state: leadSnap.state, + level: leadSnap.level, + note: `牵头线判定线:${leadSnap.line}。DS-09 近 3 月批次、DS-16 单日抽检、DS-15 三日快照分母不同,只并列不合并。`, + }, + actions: ranked.slice(0, 3).map(x => ({ + owner: x.d.name, + role: x.d.role.split('·')[0].trim(), + action: x.d.action(x.a), + jump: x.d.jump(x.a), + })), + }); + + return turns; +} diff --git a/src/modules/tfamd-oee/lib/time.ts b/src/modules/tfamd-oee/lib/time.ts new file mode 100644 index 0000000..c9e9087 --- /dev/null +++ b/src/modules/tfamd-oee/lib/time.ts @@ -0,0 +1,110 @@ +import type { MetricNode } from '../data/sqlite'; + +/** + * 全局时间游标:0-11 对应 2025-11 ~ 2026-10。 + * 窗口末端与源表数据期(2026-10-16)对齐——回放不是另一套虚构日历, + * 而是「以源表当期快照为锚,向前回看 12 个月」。 + * 节点当期值(value)只是游标=11 的快照;图谱/看板/Header 统一经此模块 + * 按游标重算取值与状态,拖动时间滑块即可"回放"每个时点的指标表现。 + */ + +export const PERIOD_COUNT = 12; +/** 默认停在最后一期(当期) */ +export const CURRENT_PERIOD = 11; + +/** 回放窗口起点:与源表当期 2026-10 相差 11 个月 */ +const REPLAY_START_YEAR = 2025; +const REPLAY_START_MONTH = 11; + +/** 游标 → 年月(0 → 2025-11,11 → 2026-10) */ +export function periodParts(period: number): { year: number; month: number } { + const idx = REPLAY_START_YEAR * 12 + (REPLAY_START_MONTH - 1) + period; + return { year: Math.floor(idx / 12), month: (idx % 12) + 1 }; +} + +/** 游标时点的指标值:trend 缺失时回退当期值 */ +export function valueAt(n: MetricNode, period: number): number { + const t = n.trend; + if (!t || !t.length) return n.value; + return t[Math.min(period, t.length - 1)] ?? n.value; +} + +/** 游标时点偏差(已按 polarity 归一:正=优于目标) */ +export function gapAt(n: MetricNode, period: number): number { + const raw = valueAt(n, period) - n.target; + return +(n.polarity === 'down' ? -raw : raw).toFixed(2); +} + +/** 游标时点达成率(%),越低越好类取倒数口径 */ +export function achieveAt(n: MetricNode, period: number): number { + const v = valueAt(n, period); + if (!n.target) return 100; + const r = n.polarity === 'down' + ? (n.target / (v || 1)) * 100 + : (v / n.target) * 100; + return +Math.min(r, 999).toFixed(1); +} + +/** 游标时点的动态预警分级:按「达标 → 警戒线」两档判定,比固定比率更贴合口径 */ +export function statusAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' { + const v = valueAt(n, period); + const better = n.polarity === 'down' ? v <= n.target : v >= n.target; + if (better) return 'green'; + const safe = n.polarity === 'down' ? v <= n.alert_threshold : v >= n.alert_threshold; + return safe ? 'yellow' : 'red'; +} + +/** 图谱/看板取色用状态:当期沿用主数据定级(与告警计数、指标树一致), + * 历史期由游标值反推,拖动滑块即可看到红黄绿的时空迁移。 */ +export function levelAt(n: MetricNode, period: number): 'green' | 'yellow' | 'red' { + return period === CURRENT_PERIOD + ? (n.alert_level === 'red' || n.alert_level === 'yellow' ? n.alert_level : 'green') + : statusAt(n, period); +} + +/** 环比上期变化(原始值差,不做 polarity 归一,由调用方按语义着色) */ +export function momAt(n: MetricNode, period: number): number | null { + if (period <= 0) return null; + return +(valueAt(n, period) - valueAt(n, period - 1)).toFixed(2); +} + +/** 游标期标签:2026-07 */ +export function periodLabel(period: number): string { + const { year, month } = periodParts(period); + return `${year}-${String(month).padStart(2, '0')}`; +} + +/** 时间轴刻度用的短标签:11月 / 12月 / 1月…(跨年由读数区的完整年月兜住) */ +export function periodMonthLabel(period: number): string { + return `${periodParts(period).month}月`; +} + +/** 回放期内的数据日(与源表基准日同为每月 16 日) */ +export function periodDate(period: number): string { + const { year, month } = periodParts(period); + return `${year}-${String(month).padStart(2, '0')}-16`; +} + +/** 完整 12 期序列(trend 缺失时以当期值补齐,保证柱子数量恒定为 12) */ +export function seriesOf(n: MetricNode): number[] { + return Array.from({ length: PERIOD_COUNT }, (_, i) => valueAt(n, i)); +} + +/** + * 游标投影:把“该时点的值 + 该时点的定级”贴回节点本身。 + * 下游所有当期口径工具(gapOf / achieveRate / alertColor(n.alert_level))无需改造即变成时点口径, + * 避免逐个改 30+ 取值点带来的遗漏。trend 不投影,回看历史与预测仍拿得到完整序列。 + */ +export function projectAt(n: MetricNode, period: number): MetricNode { + if (period === CURRENT_PERIOD) return n; + return { ...n, value: valueAt(n, period), alert_level: statusAt(n, period) }; +} + +/** 整棵树投影(MetricTreePanel 依赖 children 遍历) */ +export function projectTree(nodes: MetricNode[], period: number): MetricNode[] { + if (period === CURRENT_PERIOD) return nodes; + return nodes.map(n => ({ + ...projectAt(n, period), + children: n.children ? projectTree(n.children, period) : undefined, + })); +} diff --git a/src/modules/tfamd-oee/r3f-jsx.d.ts b/src/modules/tfamd-oee/r3f-jsx.d.ts new file mode 100644 index 0000000..d19b886 --- /dev/null +++ b/src/modules/tfamd-oee/r3f-jsx.d.ts @@ -0,0 +1,9 @@ +import type { ThreeElements } from '@react-three/fiber'; + +// @types/react 19 移除了全局 JSX 命名空间,@react-three/fiber 8 仍在全局 JSX 上做声明合并, +// 这里把 three 元素补到 React.JSX 上,保证 等 R3F 内置元素类型可用。 +declare module 'react' { + namespace JSX { + interface IntrinsicElements extends ThreeElements {} + } +} diff --git a/src/modules/tfamd-oee/types/oee.ts b/src/modules/tfamd-oee/types/oee.ts new file mode 100644 index 0000000..4630b37 --- /dev/null +++ b/src/modules/tfamd-oee/types/oee.ts @@ -0,0 +1,680 @@ +/** + * 通富超威 OEE 分析 AI 原型 —— L1/L2/L3 三层共用的类型契约。 + * + * 来源:《OEE分析AI原型系统构建建议书-2026-11-12.md》§3.3(核心类型)+ 附录 C(补充类型)。 + * 引擎(src/lib/oee/*)、服务、组件、校验脚本(scripts/verify-oee-*)全部 import 同一份, + * 不允许任何一处另立一套字段名或枚举。 + * + * 三条硬约束(对应建议书「三不改契约」之一): + * 1. 本文件只有类型与常量,**零 IO**:不 import data/、不 fetch、不读时钟。 + * 2. 两套状态机不得共用枚举:改善闭环 TaskState(六态)vs StepChain ChainTaskState(七态)。 + * 3. 三套「六」分类不得混用:六大损失桶 LOSS_BUCKETS / ASLT 时间六分类 ASLT_TIME_CLASSES / + * 事件表归口用词 GROSS_TO_BUCKET(6 键,其中 3 键为 null,覆盖 20 条计划类事件)。 + */ + +/* ══════════════════════════════════════════════════════════════════ + * 一、枚举与常量(§3.3.1) + * ══════════════════════════════════════════════════════════════════ */ + +/** 十态抢占状态机。数值即优先级,越小越优先。UNKNOWN 不计入分母。 */ +export const STATE_PRIORITY = { + PLAN_STOP: 1, // Plan Idle —— 无排产/计划停机 + PM: 2, // ENG Time —— 预防性维护 + DOWN: 3, // StopedTime > 300s + JAM: 4, // StopedTime ≤ 300s + WAIT_MAT: 5, // 待料 + WAIT_UNLOAD: 6, // 待卸料/下游阻塞 + WAIT_PERSON: 7, // 待人员 + CHANGE: 8, // Set up loss —— 换型调整 + RUN: 9, // 生产 + IDLE: 10, // 未归因(计入分母,进未归因池) +} as const; +export type StateCode = keyof typeof STATE_PRIORITY; +/** UNKNOWN 独立于十态之外:日志断流/未采集,不计分母(DQ-10) */ +export type SegmentState = StateCode | 'UNKNOWN'; +/** UNKNOWN 的优先级哨兵值,不参与抢占比较 */ +export const UNKNOWN_PRIORITY = 99; + +/** 状态中文名。全站统一,页面不得另写一套。 */ +export const STATE_LABEL: Record = { + PLAN_STOP: '计划停机', PM: '预防性维护', DOWN: '故障停机', JAM: '空转短停', + WAIT_MAT: '待料', WAIT_UNLOAD: '待卸料', WAIT_PERSON: '待人员', + CHANGE: '换型调整', RUN: '生产', IDLE: '未归因', UNKNOWN: '未采集', +}; + +/** 六大损失桶(六-1)。互斥且完备,每事件码唯一归口。 */ +export const LOSS_BUCKETS = ['FAULT','CHANGEOVER','IDLE_MINOR','SPEED','PROCESS_DEFECT','STARTUP_DEFECT'] as const; +export type LossBucket = typeof LOSS_BUCKETS[number]; +export const BUCKET_LABEL: Record = { + FAULT:'故障停机', CHANGEOVER:'换型调整', IDLE_MINOR:'空转短停', + SPEED:'速度降低', PROCESS_DEFECT:'过程不良', STARTUP_DEFECT:'开机不良', +}; +export const BUCKET_FACTOR: Record = { + FAULT:'A', CHANGEOVER:'A', IDLE_MINOR:'A', + SPEED:'P', PROCESS_DEFECT:'Q', STARTUP_DEFECT:'Q', +}; + +/** 48 事件的自动化等级 A–E */ +export type EventGrade = 'A'|'B'|'C'|'D'|'E'; +/** A 全自动唯一映射 / B 多变量需补录 / C 可能计划内需确认 / D 必须人工录入 / E 不适用 */ +export const GRADE_LABEL: Record = { + A:'全自动唯一映射', B:'多变量需补录', C:'可能计划内需确认', D:'必须人工录入', E:'不适用', +}; + +/** 事件定义四种状态 */ +export type EventDefStatus = 'ACTIVE'|'PENDING_DEF'|'PENDING_SRC'|'NOT_APPLICABLE'; +export const EVENT_STATUS_LABEL: Record = { + ACTIVE:'已生效', PENDING_DEF:'待定义', PENDING_SRC:'待接源', NOT_APPLICABLE:'不适用', +}; + +/** 事件三种表现形式:POINT 31 / INTERVAL 6 / DERIVED 11 */ +export type EventForm = 'POINT'|'INTERVAL'|'DERIVED'; + +/** 三区域算法模板 */ +export type RegionTemplate = 'SRF_BUFFER'|'FT_MULTIPLY'|'ASLT_EVENT'; +export const TEMPLATE_LABEL: Record = { + SRF_BUFFER:'SRF 缓冲解耦', FT_MULTIPLY:'FT 多因子连乘', ASLT_EVENT:'ASLT 事件驱动', +}; + +/** 改善闭环六态(与 ChainTaskState 是两套,不得共用) */ +export const TASK_STATES = ['DRAFT','PENDING_REVIEW','DISPATCHED','IN_PROGRESS','VERIFIED','ARCHIVED'] as const; +export type TaskState = typeof TASK_STATES[number]; +export const TASK_STATE_LABEL: Record = { + DRAFT:'待生成', PENDING_REVIEW:'待审核', DISPATCHED:'已派发', + IN_PROGRESS:'执行中', VERIFIED:'已验证', ARCHIVED:'已归档', +}; + +/** 12 条 DQ 规则编号 */ +export type DqCode = `DQ-${'01'|'02'|'03'|'04'|'05'|'06'|'07'|'08'|'09'|'10'|'11'|'12'}`; +/** 其中三条为阻断级:DQ-06 未归因>5% / DQ-08 主数据缺失 / DQ-12 口径版本不一致 */ +export const BLOCKING_DQ: DqCode[] = ['DQ-06','DQ-08','DQ-12']; + +/** 五级告警 */ +export type AlertLevel = 'S1'|'S2'|'S3'|'S4'|'S5'; + +/** 告警严重度降序(S1 最重)。deriveAlerts 输出按此排序,同档内按确定性次序。 */ +export const ALERT_LEVEL_ORDER: AlertLevel[] = ['S1','S2','S3','S4','S5']; + +/** 告警处置状态。OBSERVE=S5 观察项(不推送、按周收敛)。 */ +export type AlertState = 'OPEN'|'ASSIGNED'|'CLOSED'|'OBSERVE'; +export const ALERT_STATE_LABEL: Record = { + OPEN:'待处理', ASSIGNED:'已派单', CLOSED:'已关闭', OBSERVE:'观察', +}; + +/** + * 一条 OEE 告警。全部由 L3 deriveAlerts 从当日读数现算(day.dq / day.buckets / day.tiers / + * day.segments.unknown / day.normalize.events),视图不写死任何统计值(断言②同源纪律)。 + */ +export interface OeeAlert { + id: string; + level: AlertLevel; + /** 短角标:安全 / 非计划停机 / 瓶颈 / 数据质量 / 观察 */ + kind: string; + title: string; + /** 主体行:设备 · 业务日 */ + subject: string; + metric: { label: string; value: string }; + fields: { label: string; value: string }[]; + action: string; + owner: string; + /** 升级链(规划书 §5.5 原文) */ + escalation: string; + /** 判定口径(含口径版本号,可回溯) */ + caliber: string; + /** 来源页签(治理台 / 损失结构 / 总览 / 录入台) */ + source: string; + state: AlertState; + /** S4 阻断级:有权暂停当日结论发布(规划书 §5.5 关键设计) */ + blocksPublish?: boolean; +} + +/** + * 五级告警字典(照录规划书 §5.5,阈值可配置、留痕、仅对新事件生效)。 + * tone 走语义色(TF-AMD 红只用于品牌识别,损失/告警仍用语义红,规划书 §7.2)。 + * S4 独立成级是关键设计:数据质量问题不是"提示",而是与停机同级、有权阻断发布的告警。 + */ +export const ALERT_LEVELS: Record = { + S1: { label:'S1 安全', scene:'安全(EMO/安全回路)', response:'立即', channel:'移动端强提醒 + 大屏置顶', fallback:'值班电话链', escalation:'设备 PE → 厂级', owner:'设备 PE', tone:'danger' }, + S2: { label:'S2 非计划停机', scene:'非计划停机(连续 DOWN 超阈值)', response:'5 分钟内响应', channel:'移动端 + 看板 + 企微', fallback:'邮件', escalation:'EQ + MFG', owner:'EQ + MFG', tone:'danger' }, + S3: { label:'S3 瓶颈/计划偏移', scene:'瓶颈与计划偏移', response:'30 分钟内确认', channel:'看板高亮 + 任务中心', fallback:'日报', escalation:'IE + PC', owner:'IE + PC', tone:'warning' }, + S4: { label:'S4 数据质量阻断', scene:'数据质量阻断', response:'当日闭环', channel:'治理页 + 邮件', fallback:'—', escalation:'数据治理小组', owner:'数据治理小组', tone:'warning' }, + S5: { label:'S5 观察项', scene:'观察项', response:'不推送', channel:'录入台待办', fallback:'按周收敛', escalation:'—', owner:'—', tone:'textMuted' }, +}; + +/** + * 归因置信度五级(五级级联归因)。 + * 注意:这是「识别途径」,与 improvement_task.causeClass 的「真因 A/B/C 分类」是两回事。 + */ +export const ATTR_CONFIDENCE = { + SELF_IDENTIFIED: 1.00, // 设备自识别(FT/ASLT lot_summary) + MES_UNIQUE: 0.95, // MES 窗口唯一 + SETUP_WINDOW: 0.90, // 换型窗口(EOM) + MULTI_CANDIDATE: 0.85, // 多候选缩小(OTA 装卸料) + UNATTRIBUTED: 0.00, // 无法归因 → unknown_event_pool,绝不猜测 +} as const; +export type AttrMethod = keyof typeof ATTR_CONFIDENCE; +export const ATTR_METHOD_LABEL: Record = { + SELF_IDENTIFIED:'设备自识别', MES_UNIQUE:'MES 窗口唯一', SETUP_WINDOW:'换型窗口', + MULTI_CANDIDATE:'多候选缩小', UNATTRIBUTED:'无法归因', +}; + +/** 数值比较容差:引擎内部一律用它,不用 === 比浮点 */ +export const EPS = 1e-9; +/** 展示值复算容差(±0.02pp):分项已四舍五入的 POC 锚点数字用这条,见附录 D21 */ +export const DISPLAY_PP_TOLERANCE = 0.02; + +/* ══════════════════════════════════════════════════════════════════ + * 二、字典层(§3.3.2) + * ══════════════════════════════════════════════════════════════════ */ + +/** 48 事件定义。来源:规划书附录 C(逐条转录自鼎捷方案附录 A)。 */ +export interface EventDef { + code: string; // 'S-01' | 'F-45' | 'A-53',S/F/A = SRF/FT/ASLT + name: string; + region: 'SRF'|'FT'|'ASLT'; + grade: EventGrade; + form: EventForm; + status: EventDefStatus; + /** 判定时点:如"最后 lot trackout 后 5min" */ + triggerPoint: string; + /** 数据源:如 'DEK EVENT.DAT' | 'MT2' | '人工录入' */ + source: string; + /** 唯一归口的损失桶;计划类事件为 null(不进六桶,见 GROSS_TO_BUCKET 映射) */ + bucket: LossBucket | null; + /** 一级/二级因子 */ + factorL1: string; + factorL2: string; + /** 获取方式:AUTO / SEMI_AUTO / MANUAL */ + acquisition: 'AUTO'|'SEMI_AUTO'|'MANUAL'; + /** 报警分类:解决 FT "Temperature Wait" 单日 500 次误判停机的问题 */ + alarmClass?: 'DOWN'|'JAM'|'INFO'|'CLOCK_CHANGE'; + /** 六-3 事件表归口用词,6 个取值之一;经 GROSS_TO_BUCKET 决定 bucket */ + grossCategory: GrossCategory; +} + +/** 28 项口径配置。来源:规划书附录 E。 */ +export interface CaliberItem { + id: `C${string}`; // C01..C28 + name: string; + defaultValue: string | number | boolean; + /** P0=16 项(决定能不能算)/ P1=11 / P2=1 */ + priority: 'P0'|'P1'|'P2'; + owner: 'IE'|'PE'|'MFG'|'QA'|'PC'|'FIN'|'IT'; + /** 是否属于决定 OEE 绝对值的 4 项敏感性议题 */ + isSensitivityKey: boolean; // Plan边界 / Occ判定 / Q定义 / FT的PM是否计入 + signedOff: boolean; // 原型默认 false,UI 标"待 IE 签字" + note: string; +} + +export interface CaliberConfig { + version: string; // 'v0.1-demo',全站唯一来源 + items: Record; + /** 生效时间窗,用于版本回放 */ + effectiveFrom: string; + effectiveTo?: string; + /** 4 项敏感性议题的取值快照,便于对比 */ + sensitivitySnapshot: { + planBoundary: string; + occRule: string; + qDefinition: string; + ftPmIncluded: boolean; + }; +} + +/** 设备清单 + 能力矩阵 + 按设备间隙阈值。来源:规划书附录 D、7.3。 */ +export interface Device { + id: string; // 沿用客户既有台账编码,不重新编号 + name: string; + region: 'SRF'|'FT'|'ASLT'; + type: string; // 'DEK' | 'FUJI NXT' | 'Datacon' | 'kohyoung AOI' | ... + lineId: string; + station: string; + /** ★ 1–3,信号完整度 */ + capability: 1|2|3; + hasLog: boolean; // Loader/分轨机/绿皮机 = false,需加装 IO + /** 间隙填充阈值(分钟)= max(5, 3×中位节拍)。kohyoung 必须是 15 */ + gapThresholdMin: number; + /** 标准节拍 ICT(秒/单位) */ + ictSec: number; + unit: '板'|'TU'|'boat'|'颗'; + template: RegionTemplate; + /** 无日志设备的过渡采集方式 */ + fallbackChannel?: 'IO_LIGHT'|'MANUAL'|'UPSTREAM_INFER'; +} + +/* ══════════════════════════════════════════════════════════════════ + * 三、事实层(§3.3.3) + * ══════════════════════════════════════════════════════════════════ */ + +/** 原始日志行。L1 血缘终点,断言①的落点。 */ +export interface RawLogLine { + id: string; + device: string; + filePath: string; + lineNo: number; // ← UI"跳转行号"指向这里 + rawText: string; + /** 对外只给行号与摘要哈希,全文仅内网审计链路可取 */ + digest: string; + channel: 'FILE'|'DB'|'REST_MQ'|'IO'|'MANUAL'|'MTIME'; + rawTime: string; +} + +/** 事件实例。不可变;修正通过新增 is_corrected 记录。 */ +export interface EventInstance { + id: string; + defCode: string; // → EventDef.code + device: string; + /** 双时间字段:时钟回跳校正前后都保留(DQ-01) */ + rawTime: string; + correctedTime: string; + clockOffsetSec?: number; + form: EventForm; + /** 区间事件的配对 ID */ + pairId?: string; + pairRole?: 'START'|'END'; + /** 配对四策略的结果 */ + pairStrategy?: 'TIGHT'|'MISSING_END'|'MISSING_START'|'MULTI_ALARM'; + /** 派生事件的来源,不可人工编辑 */ + derivedFrom?: string[]; + isCorrected: boolean; + correctsEventId?: string; + dedupKey: string; + /** 内联证据(生产阶段拆为 event_evidence 表) */ + evidence: { rawLineId: string; lineNo: number; filePath: string; digest: string }; + /** 归因结果 */ + attribution?: AttributionLink; + params?: Record; + /** 人工补录的 5M1E 七字段 */ + manualEntry?: ManualEntry5M1E; +} + +/** 五级级联归因结果 */ +export interface AttributionLink { + lotId?: string; + workOrderId?: string; + method: AttrMethod; + confidence: number; // 1.00 / 0.95 / 0.90 / 0.85 / 0.00 + evidenceRefs: string[]; + /** 无法归因时必填,指向未归因池 */ + unknownPoolId?: string; +} + +/** 5M1E 七字段人工补录。D 类事件(14 个)的唯一来源。 */ +export interface ManualEntry5M1E { + /** 真因一级:人/机/料/法/环/测 */ + causeL1: '人'|'机'|'料'|'法'|'环'|'测'; + causeL2: string; + /** 原因描述 ≤50 字符 */ + description: string; + action: string; + ownerSuggest: 'MFG'|'EQ'|'PE'; + isPlanned: boolean; + /** 补录人/时间由系统自动写入,不可手填 */ + enteredBy: string; + enteredAt: string; +} + +/** 设备状态段。时间轴的物理载体。 */ +export interface StateSegment { + id: string; + device: string; + state: SegmentState; + priority: number; // = STATE_PRIORITY[state],UNKNOWN 为 99 + start: string; + end: string; + durationSec: number; + /** 跨班拆分:同一物理段按班次切成多条,共享 splitGroupId */ + shiftId: string; + splitGroupId?: string; + /** 影子时长:PM 窗口内停机保留双记录,段取高优先级,重叠部分标影子 */ + shadowOf?: string; + shadowSec?: number; + /** 间隙填充产生的段,标记来源便于审计 */ + filledByGapRule: boolean; + confidence: number; + /** 指向构成该段的事件 */ + eventIds: string[]; + /** 扩容:fuji 合并跨度的贡献模块段数(merged=true 时 evidence_event_ids 为空) */ + evidenceCount?: number; + /** 未归因段进池 */ + unknownPoolId?: string; + bizDate: string; // 跨天班次归属事件开始时刻所在业务日(C24) +} + +/** 未归因池。DQ-06 的计算基础。 */ +export interface UnknownEvent { + id: string; + device: string; + bizDate: string; + durationSec: number; + reason: 'NO_PAIR'|'NO_LOT'|'NO_SOURCE'|'GAP_FILL'|'AMBIGUOUS'; + /** 占当日计划时间的比例(分母统一为 PPT),>5% 触发阻断 */ + pctOfPlanTime: number; + suggestedForm?: EntryForm; // 指向录入台八表单之一 + resolved: boolean; + resolvedByEntryId?: string; +} + +/** 因子时长。原型不落库,由引擎现算返回。 */ +export interface FactorDuration { + factorL1: string; + factorL2: string; + bucket: LossBucket | null; + factor: 'A'|'P'|'Q'; + durationSec: number; + segmentIds: string[]; + eventIds: string[]; +} + +/** 六大损失桶结果。残差必须为 0。 */ +export interface LossBucketResult { + bucket: LossBucket; + factor: 'A'|'P'|'Q'; + durationSec: number; + /** 分母统一为 PPT = CT − PDT(不是 CT,也不是日历时间) */ + pctOfPlanTime: number; + /** 速度/质量/开机三类来自节拍偏差与检测结果,无成对事件 */ + derivedFromCycleDeviation: boolean; + eventCodes: string[]; +} + +/** 三层 OEE 结果。 */ +export interface OeeResult { + /** 粒度:设备 / 线体 / 区域 / 周期 */ + scope: { level: 'DEVICE'|'LINE'|'REGION'|'PERIOD'; id: string }; + bizDate: string; + shiftId?: string; + caliberVersion: string; // ← 全站四处读数的同一来源 + template: RegionTemplate; + /** 三层共用分母 PPT = CT − PDT */ + ctSec: number; + pptSec: number; + pdtSec: number; + tiers: { + theoretical: TierValues; + planned: TierValues; + actual: TierValues; + }; + /** 顺序替代法差异分解,顺序固定 A→P→Q */ + delta?: { dA: number; dP: number; dQ: number; total: number }; + buckets: LossBucketResult[]; + /** 残差 = PPT − 有效生产时间 − Σ桶时长,必须为 0 */ + residualSec: number; + /** 未归因占比,>5% 阻断 */ + unattributedPct: number; + /** DQ 阻断状态 */ + blocked: boolean; + blockingDq: DqCode[]; + /** 血缘入口,供 UI 下钻 */ + detailRef: string; +} + +export interface TierValues { + a: number; p: number; q: number; oee: number; + rtSec: number; avSec: number; opSec: number; + outputQty: number; goodQty: number; + ictSec: number; +} + +/** 改善任务。四项必填齐备才能从待审核推进到已派发。 */ +export interface ImprovementTask { + id: string; + state: TaskState; + title: string; + /** 挂五实体之一,不允许多个并列首要真因 */ + rootCauseEntity: { type: '设备'|'模具工装'|'物料批次'|'人员班组'|'程序参数'; id: string }; + causeClass: 'A'|'B'|'C'; + evidenceChain: string[]; // 证据链不完整只作候选,不进派单 + /** 四项必填 */ + owner?: string; + dueDate?: string; + expectedBenefit?: { min: number; max: number; unit: string }; // 收益给区间不给点值 + verificationResult?: string; + priorityScore: number; + weightScheme: 'A'|'B'; // 两套权重可切换,默认 B(第9章第6项) + chainId?: string; + slaEscalatedTo?: string; + history: { state: TaskState; at: string; by: string; note?: string }[]; +} + +/** 数据质量问题 */ +export interface DqIssue { + id: string; + code: DqCode; + device?: string; + bizDate: string; + condition: string; // 命中的判定条件 + blocking: boolean; + action: string; + state: 'OPEN'|'ASSIGNED'|'CLOSED'; + /** 数据缺口标灰不标绿(复用 ontologyQap 的 blocked/gap 模式) */ + gap?: string; +} + +/* ══════════════════════════════════════════════════════════════════ + * 四、引擎上下文与输出契约(§3.3.4) + * ══════════════════════════════════════════════════════════════════ */ + +/** 引擎计算上下文。所有"当前时间"由调用方传入,引擎内禁止 Date.now()。 */ +export interface CalcContext { + bizDate: string; + shiftId: string; + now: string; // 由调用方注入,保证可重放 + caliber: CaliberConfig; + devices: Device[]; + eventDefs: EventDef[]; +} + +/** L3 五类受控工具的返回包装。所有指标出口统一带版本号。 */ +export interface ServiceResult { + data: T; + caliberVersion: string; + timeRange: { from: string; to: string }; + source: 'DEMO_SEED'; + /** POC 锚点数字必须带此标注 */ + baselineNote?: '参考基线·来源:鼎捷 POC'; + /** 数据缺口时填,UI 标灰 */ + gap?: string; + blocked?: boolean; +} + +/* ══════════════════════════════════════════════════════════════════ + * 五、补充类型(附录 C) + * ══════════════════════════════════════════════════════════════════ */ + +/** 六-2:ASLT 时间六分类。与六大损失桶(六-1)是不同分类,不可混用。 */ +export const ASLT_TIME_CLASSES = ['WAIT','PLAN','OCC','ENG','STOP','STANDBY'] as const; +export type AsltTimeClass = typeof ASLT_TIME_CLASSES[number]; +export const ASLT_CLASS_LABEL: Record = { + WAIT:'等待', PLAN:'计划', OCC:'占用', ENG:'工程', STOP:'停机', STANDBY:'待机', +}; +export interface AsltTimeAccount { + class: AsltTimeClass; + durationSec: number; + pctOfTotal: number; +} +/** 不变量:Σ durationSec === 总时长,残差 0(POC 实测 0.000000h) */ + +/** + * 六-3:事件表归口用词 → 六大损失桶。 + * 6 个键,其中 3 个为 null(计划停机/计划待料/工程借用),这 3 键覆盖 20 条事件 + * (工程借用 12 + 计划停机 6 + 计划待料 2);其余 28 条落六桶(故障 3 + 换型 16 + 空转 9)。 + * 断言必须分两条写:null 键=3 个、覆盖事件=20 条。写成「null 项数=20」是错的(附录 D20)。 + */ +export const GROSS_CATEGORIES = ['故障停机','换型调整','空转短停','计划停机','计划待料','工程借用'] as const; +export type GrossCategory = typeof GROSS_CATEGORIES[number]; +export const GROSS_TO_BUCKET: Record = { + '故障停机': 'FAULT', + '换型调整': 'CHANGEOVER', + '空转短停': 'IDLE_MINOR', + '计划停机': null, // ← 进 PDT,从分母扣除,不是损失桶 + '计划待料': null, // ← 同上 + '工程借用': null, // ← ENG Time,按 C06/C10 口径处理 +}; +/** 六-3 各归口用词的事件条数,合计 48。来源:规划书附录 C 逐条统计。 */ +export const GROSS_CATEGORY_COUNT: Record = { + '换型调整': 16, '工程借用': 12, '空转短停': 9, '计划停机': 6, '故障停机': 3, '计划待料': 2, +}; + +/** StepChain 节点任务状态。与改善闭环 TaskState 是两套,不得共用枚举。 */ +export const CHAIN_TASK_STATES = + ['CREATED','ACCEPTED','IN_PROGRESS','SUBMITTED','APPROVED','CLOSED','REJECTED'] as const; +export type ChainTaskState = typeof CHAIN_TASK_STATES[number]; +export const CHAIN_STATE_LABEL: Record = { + CREATED:'已创建', ACCEPTED:'已接单', IN_PROGRESS:'执行中', SUBMITTED:'已提交', + APPROVED:'已核准', CLOSED:'已关闭', REJECTED:'已驳回', +}; + +export interface ChainNode { + id: string; // 'n1_pm_start' + kind: 'TASK'|'GATE'|'DERIVED'; + role: 'EQ'|'EA'|'MFG'|'QA'|'PC'|'IE'; + slaMin?: number; + trigger: 'T1'|'T2'|'T3'|'T4'|'T5'|'T6'; + criterion: string; // 判据原文 + escalateTo: string; +} + +/** StepChain 六触发器编号(建议书 §4.9.2)。T5 计划对齐为契约占位,原型不实现。 */ +export const CHAIN_TRIGGER_IDS = ['T1','T2','T3','T4','T5','T6'] as const; +export type ChainTriggerId = typeof CHAIN_TRIGGER_IDS[number]; + +export interface ChainTrigger { + id: ChainTriggerId; + /** 触发类型原文:事件触发 / 时间触发 / 条件触发 / 手动触发(事务内)/ 计划对齐 / 派生反向超时 */ + kind: string; + /** 原型是否实现。T5=false(契约占位),其余 true。 */ + implemented: boolean; + /** 实现方式或未实现缺口说明(诚实标注,不假装已接 APS) */ + note: string; +} + +/** + * 链节点任务的运行时状态。★ 与改善闭环 ImprovementTask(TaskState 六态)是两套, + * 不得共用枚举(D17):这里走 ChainTaskState 七态,面向现场换型执行。 + * 时刻一律 ISO 字符串、由调用方注入;引擎不读 Date.now(纯函数纪律)。 + */ +export interface ChainNodeState { + nodeId: string; // 指向 ChainNode.id + state: ChainTaskState; + /** 当前处理人(演示角色,不编造真实姓名) */ + owner: string; + /** 进入当前态的时刻(ISO,注入) */ + at: string; + /** 节点开始执行时刻(SLA 计时起点;未开始为 undefined) */ + startedAt?: string; + /** 是否已升级(SLA 超时触发) */ + escalated?: boolean; + /** 升级对象(命中超时时填 ChainNode.escalateTo) */ + escalatedTo?: string; + /** 流转留痕(可重放) */ + history: { state: ChainTaskState; at: string; by: string; note?: string }[]; +} + +/** 一条换型链实例(SRF 换型批次)。原型用内存态,不落库(SQLite 锁定四表)。 */ +export interface ChainInstance { + id: string; + deviceId: string; + bizDate: string; + /** 换型批次 / lot 标识 */ + lot: string; + /** + * Xray 图片时间锚点(ISO):n4_setup_mfg_start=锚点+5min,n7_setup_ea_end=锚点−5min。 + * T6 派生反向超时:n7 由 n4 反推(n7=n4−10min)。未采集到锚点则不派生,不猜。 + */ + xrayAnchor?: string; + nodes: ChainNodeState[]; +} + +/** 录入台八表单 */ +export const ENTRY_FORMS = [ + 'FORM_PM_HANDOVER','FORM_PM_FINISH','FORM_SETUP','FORM_CHANGEOVER', + 'FORM_WAIT_REGISTER','FORM_DOWN_ATTR','FORM_5S','FORM_LAB_DEBUG', +] as const; +export type EntryForm = typeof ENTRY_FORMS[number]; +export const ENTRY_FORM_LABEL: Record = { + FORM_PM_HANDOVER:'PM 交接单', FORM_PM_FINISH:'PM 完工单', FORM_SETUP:'换型准备单', + FORM_CHANGEOVER:'换型记录单', FORM_WAIT_REGISTER:'等待登记单', FORM_DOWN_ATTR:'停机归因单', + FORM_5S:'5S 记录单', FORM_LAB_DEBUG:'实验室调试单', +}; + +/** 七类固定报表 */ +export type ReportKind = + | 'SHIFT_OEE' | 'DAILY' | 'ANOMALY' | 'WEEKLY' + | 'MONTHLY_CALIBER' | 'CLOSURE' | 'AUDIT'; +export const REPORT_KIND_LABEL: Record = { + SHIFT_OEE:'班次 OEE 报表', DAILY:'日报', ANOMALY:'异常报表', WEEKLY:'周报', + MONTHLY_CALIBER:'月度口径报表', CLOSURE:'改善闭环报表', AUDIT:'审计追溯报表', +}; +export interface ReportPayload { + kind: ReportKind; bizDate: string; caliberVersion: string; + rows: Record[]; format: 'JSON'|'CSV'; +} + +/** 智能体回答草稿与四段输出 */ +export type AnswerIntent = + | 'QUERY'|'DRILL'|'COMPARE'|'ATTRIBUTE'|'ESTIMATE'|'SUGGEST'|'DISPATCH'|'REVIEW'; +export interface AnswerDraft { + intent: AnswerIntent; + text: string; + benefits?: { min: number; max: number; unit: string }[]; +} +export interface FourSectionAnswer { + conclusion: string; // 结论 + evidence: string; // 依据 + source: string; // 出处(口径版本 + 时间范围 + 来源) + nextStep: string; // 下一步 + /** 应答来源标注:LLM / 规则引擎降级 */ + answeredBy: 'LLM'|'RULE_ENGINE'; + degradedReason?: string; +} +export interface GuardResult { + ok: boolean; gate?: 1|2|3|4|5; reason?: string; +} + +/** LLM 网关 */ +export interface LlmRequest { messages: { role: string; content: string }[]; } +export type LlmResult = + | { ok: true; text: string } + | { ok: false; reason: 'NO_ENDPOINT'|'TIMEOUT_OR_NETWORK'|`HTTP_${number}` }; + +/** 知识库四语料(建议书 4.5.1)。契约放契约层,引擎 retrieval.ts 与数据 knowledge.ts 共用。 */ +export type Corpus = 'CODE' | 'SOP' | 'CALIBER' | 'CASE'; +export interface KnowledgeChunk { + id: string; + corpus: Corpus; + text: string; + title: string; + version?: string; + /** 失效规则:false 的切片永不召回 */ + active: boolean; + source: string; + synthetic: true; + retiredReason?: string; +} +/** 检索命中:切片 + 余弦相似度分。 */ +export interface ScoredChunk { chunk: KnowledgeChunk; score: number; } + +/* ══════════════════════════════════════════════════════════════════ + * 六、智能体标准命名(附录 E / 第9章第8项:不得用花名) + * ══════════════════════════════════════════════════════════════════ */ + +/** 编号仅内部映射,全站展示一律用 name。 */ +export const AGENTS = [ + { id: 'A1', name: '指标问数智能体' }, + { id: 'A2', name: '损失诊断智能体' }, + { id: 'A3', name: '改善建议智能体' }, + { id: 'A4', name: '闭环跟踪智能体' }, + { id: 'A5', name: '质量关联智能体' }, + { id: 'A6', name: '排产协同智能体' }, + { id: 'A7', name: '经营测算智能体' }, +] as const; +export type AgentId = typeof AGENTS[number]['id']; +export const AGENT_NAME: Record = { + A1:'指标问数智能体', A2:'损失诊断智能体', A3:'改善建议智能体', A4:'闭环跟踪智能体', + A5:'质量关联智能体', A6:'排产协同智能体', A7:'经营测算智能体', +}; \ No newline at end of file diff --git a/src/modules/tfamd-oee/types/sql.d.ts b/src/modules/tfamd-oee/types/sql.d.ts new file mode 100644 index 0000000..f5c5a69 --- /dev/null +++ b/src/modules/tfamd-oee/types/sql.d.ts @@ -0,0 +1,27 @@ +declare module 'sql.js' { + export interface SqlJsStatic { + Database: new (data?: ArrayLike | null) => Database; + } + export interface QueryExecResult { + columns: string[]; + values: any[][]; + } + export interface Statement { + bind(values?: any[] | Record): boolean; + run(values?: any[]): Statement; + step(): boolean; + get(): any[]; + getAsObject(): Record; + reset(): void; + free(): boolean; + } + export interface Database { + run(sql: string, params?: any[]): Database; + exec(sql: string, params?: any[]): QueryExecResult[]; + prepare(sql: string, params?: any[]): Statement; + close(): void; + getRowsModified(): number; + export(): Uint8Array; + } + export default function initSqlJs(config?: { locateFile?: (file: string) => string }): Promise; +} diff --git a/src/pages/HomePage.tsx b/src/pages/HomePage.tsx index 75f9b01..16243ed 100644 --- a/src/pages/HomePage.tsx +++ b/src/pages/HomePage.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; import { useNavigate, useSearchParams } from 'react-router-dom'; -import { BrainCircuit, Calculator, Network, Boxes, ReceiptText, CalendarClock, Sparkles, LogOut, Radar, ShieldCheck, ClipboardCheck, Building2, FileSpreadsheet } from 'lucide-react'; +import { BrainCircuit, Calculator, Network, Boxes, ReceiptText, CalendarClock, Sparkles, LogOut, Radar, ShieldCheck, ClipboardCheck, Building2, FileSpreadsheet, Gauge } from 'lucide-react'; import { useTheme } from '@/shared/context/ThemeContext'; import StarBackground from '@/shared/components/StarBackground'; import ThemeToggle from '@/shared/components/ThemeToggle'; @@ -20,6 +20,7 @@ const ICON_MAP: Record