dsh-total-quality 2.0.55 → 2.0.57

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/CONTRIBUTING.md +51 -47
  2. package/LICENSE.md +37 -37
  3. package/README.en.md +32 -30
  4. package/README.md +90 -88
  5. package/agent-host.cjs +277 -277
  6. package/client.js +199 -92
  7. package/cordis.patch.yml +5 -5
  8. package/docs/enterprise-onboarding.md +10 -10
  9. package/docs/technical-reference.md +223 -223
  10. package/host.cjs +91 -124
  11. package/llm-bridge.cjs +234 -234
  12. package/locale/en.json +5 -5
  13. package/locale/zh.json +5 -5
  14. package/package.json +3 -2
  15. package/public/app.css +3 -0
  16. package/public/app.js +6 -2
  17. package/public/index.html +8 -9
  18. package/public/js/api.js +152 -152
  19. package/public/js/assistant-history.js +62 -62
  20. package/public/js/material-library.js +100 -100
  21. package/public/js/mobile-preview.js +119 -0
  22. package/public/js/pages-company-knowledge.js +9 -32
  23. package/public/js/pages-core.js +232 -232
  24. package/public/js/pages-growth.js +148 -148
  25. package/public/js/pages-qms.js +1 -1
  26. package/public/js/pages-qtools.js +410 -410
  27. package/public/js/pages-thanks.js +71 -71
  28. package/public/js/plugin-updates.js +53 -0
  29. package/public/js/quality-workflow.js +205 -205
  30. package/public/js/survey-dates.js +41 -41
  31. package/public/js/survey-knowledge.js +301 -301
  32. package/public/js/tool-wizards.js +621 -621
  33. package/public/js/ui.js +467 -467
  34. package/public/js/voice-capture-worklet.js +30 -30
  35. package/public/js/xiaozhi-voice.js +264 -264
  36. package/public/js/xiaozhi.js +468 -468
  37. package/public/platform-help.html +426 -426
  38. package/public/platform-site/assets/0468a68574112812.css +10703 -10703
  39. package/public/platform-site/assets/159e086d35adfa1c.css +2094 -2094
  40. package/public/platform-site/assets/169e3159cade0d9f.css +98 -98
  41. package/public/platform-site/assets/22b917c4a3d4ae3d.svg +14 -14
  42. package/public/platform-site/assets/476f9254ccf723e7.css +8265 -8265
  43. package/public/platform-site/assets/85a0a4fb4416ded9.css +120 -120
  44. package/public/platform-site/assets/a3b272383226f6d9.svg +135 -135
  45. package/public/platform-site/assets/fd16dc5f3cc9d97e.svg +104 -104
  46. package/public/platform-site/assets/qip-favicon.svg +5 -5
  47. package/public/platform-site/index.html +279 -279
  48. package/public/platform-site/offline.js +261 -261
  49. package/public/platform-site/qip-brand.css +566 -566
  50. package/public/platform-site/qip-module-guides.js +237 -237
  51. package/public/responsive.css +103 -101
  52. package/public/vendor/markdown-it-15.0.3.LICENSE +22 -22
  53. package/public/vendor/markdown-it-15.0.3.umd.min.js +13 -13
  54. package/public/workbench.css +7 -7
  55. package/public/xiaozhi.css +292 -292
  56. package/resources/qms-templates/019ffb58f24ed48d.docx +0 -0
  57. package/resources/qms-templates/04a69165fc15143a.docx +0 -0
  58. package/resources/qms-templates/09af69358c989a63.docx +0 -0
  59. package/resources/qms-templates/0e7ac77844e45311.docx +0 -0
  60. package/resources/qms-templates/12446a1b5e173c71.docx +0 -0
  61. package/resources/qms-templates/15ae40f67f9a3efc.docx +0 -0
  62. package/resources/qms-templates/18a69bbebf2ece7f.docx +0 -0
  63. package/resources/qms-templates/1978faa989134f02.docx +0 -0
  64. package/resources/qms-templates/1a30e121de752f7b.docx +0 -0
  65. package/resources/qms-templates/1b88907969ea7d4c.docx +0 -0
  66. package/resources/qms-templates/1e92b808722bf90a.docx +0 -0
  67. package/resources/qms-templates/2091cad340dc0e7f.docx +0 -0
  68. package/resources/qms-templates/271ae1002c896ed7.docx +0 -0
  69. package/resources/qms-templates/280ce53e5d3b5fcf.docx +0 -0
  70. package/resources/qms-templates/28ca8e4ede0adf6d.docx +0 -0
  71. package/resources/qms-templates/2ac6675f3cb1f993.docx +0 -0
  72. package/resources/qms-templates/2c3b799389909d8b.docx +0 -0
  73. package/resources/qms-templates/2c51038ba2cc3264.docx +0 -0
  74. package/resources/qms-templates/30c888851d16d764.docx +0 -0
  75. package/resources/qms-templates/3459fc4daaa2743d.docx +0 -0
  76. package/resources/qms-templates/3751dafc335e0e80.docx +0 -0
  77. package/resources/qms-templates/38798cd4298cd2db.docx +0 -0
  78. package/resources/qms-templates/38f551f9d738ab0a.docx +0 -0
  79. package/resources/qms-templates/3c85a23ea17018b4.docx +0 -0
  80. package/resources/qms-templates/3cdb7d14caf1b852.docx +0 -0
  81. package/resources/qms-templates/3f23239bb6b3e1db.docx +0 -0
  82. package/resources/qms-templates/42a5b9efeeaa8007.docx +0 -0
  83. package/resources/qms-templates/47352aafe9b8dac1.docx +0 -0
  84. package/resources/qms-templates/495359b1e3cbb8fe.docx +0 -0
  85. package/resources/qms-templates/4ca6920464785166.docx +0 -0
  86. package/resources/qms-templates/4ce862582a7791be.docx +0 -0
  87. package/resources/qms-templates/54c9a02a10991b9e.docx +0 -0
  88. package/resources/qms-templates/5aeb8fddf5f3693f.docx +0 -0
  89. package/resources/qms-templates/5d7e5576b0e73be7.docx +0 -0
  90. package/resources/qms-templates/5db3a40edac37791.docx +0 -0
  91. package/resources/qms-templates/5ffa21eb78eb6f77.docx +0 -0
  92. package/resources/qms-templates/60d0fbcb709b7161.docx +0 -0
  93. package/resources/qms-templates/63e1d3a166756095.docx +0 -0
  94. package/resources/qms-templates/65c724c080d32f10.docx +0 -0
  95. package/resources/qms-templates/674bd7826c6cbac2.docx +0 -0
  96. package/resources/qms-templates/677e851acca1b879.docx +0 -0
  97. package/resources/qms-templates/6bf15feb1a0d2a8d.docx +0 -0
  98. package/resources/qms-templates/6c3889c7d0918db9.docx +0 -0
  99. package/resources/qms-templates/6c4c349eeb0a96a8.docx +0 -0
  100. package/resources/qms-templates/6c5befbd33f759c1.docx +0 -0
  101. package/resources/qms-templates/6df8367901347508.docx +0 -0
  102. package/resources/qms-templates/71db51997037692b.docx +0 -0
  103. package/resources/qms-templates/78a8ef8c76510c99.docx +0 -0
  104. package/resources/qms-templates/8397bfd1c0a1b013.docx +0 -0
  105. package/resources/qms-templates/84d750cf858b60a1.docx +0 -0
  106. package/resources/qms-templates/880de58a4b334533.docx +0 -0
  107. package/resources/qms-templates/88c37d1b87d9b78c.docx +0 -0
  108. package/resources/qms-templates/88e9cd42f1849462.docx +0 -0
  109. package/resources/qms-templates/8956597403be35b6.docx +0 -0
  110. package/resources/qms-templates/94675c810a233e1f.docx +0 -0
  111. package/resources/qms-templates/94dff59dd7ebec6e.docx +0 -0
  112. package/resources/qms-templates/9670b9cd02141594.docx +0 -0
  113. package/resources/qms-templates/98c373ebd7b5163d.docx +0 -0
  114. package/resources/qms-templates/a4078cf2378a9388.docx +0 -0
  115. package/resources/qms-templates/a5b110c7ef917139.docx +0 -0
  116. package/resources/qms-templates/aec75820e45774be.docx +0 -0
  117. package/resources/qms-templates/b31c085e281d230c.docx +0 -0
  118. package/resources/qms-templates/b7c1c3c72f8ffeef.docx +0 -0
  119. package/resources/qms-templates/b81b82eaa5c8f422.docx +0 -0
  120. package/resources/qms-templates/b92a2fa31f75f137.docx +0 -0
  121. package/resources/qms-templates/b96c54ae9cfffc54.docx +0 -0
  122. package/resources/qms-templates/bc47cfd626c010e7.docx +0 -0
  123. package/resources/qms-templates/be60792734afca69.docx +0 -0
  124. package/resources/qms-templates/c0018d8ae9ad19e1.docx +0 -0
  125. package/resources/qms-templates/c171027c964c8be3.docx +0 -0
  126. package/resources/qms-templates/c4b93d71f5d98b4b.docx +0 -0
  127. package/resources/qms-templates/c531da29fcb3090f.docx +0 -0
  128. package/resources/qms-templates/c88eddd43358d015.docx +0 -0
  129. package/resources/qms-templates/cb978da542f0d892.docx +0 -0
  130. package/resources/qms-templates/ccde4a94532a8d36.docx +0 -0
  131. package/resources/qms-templates/cf3fb1e20ae6f24d.docx +0 -0
  132. package/resources/qms-templates/d231b4982fc8113e.docx +0 -0
  133. package/resources/qms-templates/d3c55aa5ed14055c.docx +0 -0
  134. package/resources/qms-templates/db45c44a00a13349.docx +0 -0
  135. package/resources/qms-templates/db849a41210f54e0.docx +0 -0
  136. package/resources/qms-templates/dba9ce363d83ddc8.docx +0 -0
  137. package/resources/qms-templates/dca3ea4c95eb2225.docx +0 -0
  138. package/resources/qms-templates/dfa4220d2b6b8131.docx +0 -0
  139. package/resources/qms-templates/dfa51222c777734f.docx +0 -0
  140. package/resources/qms-templates/e07ea511507e14f5.docx +0 -0
  141. package/resources/qms-templates/e0a2e00c03458dfa.docx +0 -0
  142. package/resources/qms-templates/e0e802f46b6764d1.docx +0 -0
  143. package/resources/qms-templates/e53fc85717f2852b.docx +0 -0
  144. package/resources/qms-templates/e9dd82d5e54520e5.docx +0 -0
  145. package/resources/qms-templates/ea7bfc22c06d82a9.docx +0 -0
  146. package/resources/qms-templates/ecf0db9f37294536.docx +0 -0
  147. package/resources/qms-templates/f05fcfc87e82ff39.docx +0 -0
  148. package/resources/qms-templates/fb9e56a17c4a4f97.docx +0 -0
  149. package/resources/qms-templates/manifest.json +932 -0
  150. package/src/data/seed-sme.js +317 -317
  151. package/src/data/seed.js +879 -879
  152. package/src/lib/backup-identity.js +57 -57
  153. package/src/lib/chat-answer.js +225 -225
  154. package/src/lib/chat-context.js +99 -99
  155. package/src/lib/company-library.js +28 -19
  156. package/src/lib/data-import.js +217 -217
  157. package/src/lib/data-sources.js +118 -118
  158. package/src/lib/demo-data.js +27 -1
  159. package/src/lib/employee-intake.js +84 -84
  160. package/src/lib/growth.js +53 -53
  161. package/src/lib/intake-packets.js +119 -119
  162. package/src/lib/issue-intake.js +88 -88
  163. package/src/lib/kb-revision.js +214 -214
  164. package/src/lib/llm.js +279 -279
  165. package/src/lib/model-error.js +14 -14
  166. package/src/lib/privacy.js +26 -26
  167. package/src/lib/qms-drafting.js +194 -194
  168. package/src/lib/qms-jobs.js +11 -7
  169. package/src/lib/qms-manual-review.js +185 -185
  170. package/src/lib/qms-procedure-review.js +109 -109
  171. package/src/lib/qms-templates.js +358 -326
  172. package/src/lib/qms.js +369 -369
  173. package/src/lib/quality-priority.js +100 -100
  174. package/src/lib/quality-state.js +92 -92
  175. package/src/lib/quality-workflow.js +65 -65
  176. package/src/lib/retrieval.js +159 -159
  177. package/src/lib/spc.js +127 -127
  178. package/src/lib/voice-hotwords.txt +22 -22
  179. package/src/lib/voice-text.js +13 -13
  180. package/src/lib/voice-worker.js +72 -72
  181. package/src/lib/voice.js +330 -330
  182. package/src/lib/workbench-notices.js +49 -49
  183. package/src/lib/workbench.js +103 -106
  184. package/src/package.json +3 -3
  185. package/src/tools/analysis.js +306 -306
  186. package/src/tools/data.js +596 -596
  187. package/src/tools/docs.js +430 -430
  188. package/src/tools/registry.js +57 -57
  189. package/tools-dsh.cjs +153 -153
  190. package//345/256/211/350/243/205/350/257/264/346/230/216.md +33 -25
  191. package//346/234/254/346/234/272/347/213/254/347/253/213/345/256/211/350/243/205/350/257/264/346/230/216.md +17 -17
  192. package//350/207/252/346/243/200.cjs +88 -88
  193. package/public/js/remote-knowledge.js +0 -165
  194. package/public/js/workbench-notices.js +0 -67
  195. package/public/remote-knowledge-help.html +0 -35
  196. package/public/remote-knowledge.css +0 -40
  197. package/src/lib/remote-knowledge.js +0 -284
package/src/tools/docs.js CHANGED
@@ -1,430 +1,430 @@
1
- 'use strict';
2
- /**
3
- * 文档与报表工具:让智能体产出"可交付物"
4
- * ------------------------------------------------------------------
5
- * · report_generate 生成真实的 .docx 报告(周报/月报/专项/根因分析/8D)
6
- * · data_export 把平台真实数据导出为真正的 .xlsx / .csv
7
- * · report_list 报表中心清单
8
- * 用到的 OOXML 能力来自 lib/office.js(零依赖自研)。
9
- */
10
- const fs = require('fs');
11
- const path = require('path');
12
- const { randomUUID } = require('node:crypto');
13
- const { define } = require('./registry');
14
- const store = require('../lib/store');
15
- const spc = require('../lib/spc');
16
- const { isOutOfSpec, hasUsableSpec } = require('./data');
17
- const { isOpen, deadlineTime, projectTiming } = require('../lib/quality-state');
18
- const { measurementFields } = require('../lib/data-import');
19
- const { STAGES } = require('./business');
20
-
21
- let office = null;
22
- function getOffice() {
23
- if (!office) office = require('../lib/office');
24
- return office;
25
- }
26
-
27
- /** 输出目录(服务器注入) */
28
- function outDir(ctx) {
29
- const dir = (ctx && ctx.outputDir) || path.join(process.cwd(), 'data', 'reports');
30
- fs.mkdirSync(dir, { recursive: true });
31
- return dir;
32
- }
33
- function localStamp(d) {
34
- const p = (n) => String(n).padStart(2, '0');
35
- d = new Date(d.getTime() + 8 * 3600000);
36
- return d.getUTCFullYear() + '-' + p(d.getUTCMonth() + 1) + '-' + p(d.getUTCDate()) + ' ' + p(d.getUTCHours()) + ':' + p(d.getUTCMinutes());
37
- }
38
- function safeName(s) { return String(s).replace(/[\\/:*?"<>|]/g, '_').slice(0, 80); }
39
-
40
- /* ------------------------------------------------------------------ */
41
- define({
42
- plugin: '@DOC', name: 'report_generate', label: '生成质量报告(Word)',
43
- description: '生成真实可下载的 Word 报告(.docx)。支持:质量周报、质量月报、专项分析报告、根因分析报告、8D 报告、SPC 分析报告。报告内含真实数据表格与统计结论。生成后返回下载链接。',
44
- parameters: {
45
- type: 'object',
46
- properties: {
47
- type: { type: 'string', enum: ['质量周报', '质量月报', '专项分析报告', '根因分析报告', '8D报告', 'SPC分析报告'], description: '报告类型' },
48
- title: { type: 'string', description: '报告标题(可自动生成)' },
49
- scope: { type: 'string', description: '范围:产品/车间/项目编号/特性编号' },
50
- period: { type: 'string', description: '期间,如 2026-09 或 第 40 周' },
51
- sections: { type: 'array', items: { type: 'object' }, description: '自定义章节 [{heading, paragraphs:[], bullets:[], table:{header,rows}}]' },
52
- includeCharts: { type: 'boolean', description: '是否包含表格化图表数据(默认 true)' },
53
- projectId: { type: 'string', description: '8D/根因分析报告可指定项目' },
54
- author: { type: 'string' },
55
- },
56
- required: ['type'],
57
- },
58
- run(args, ctx) {
59
- const blocks = [];
60
- const window = reportWindow(args.period, args.type, args.asOf);
61
- const period = window.label;
62
- const now = localStamp(new Date());
63
- const title = args.title || (args.scope ? args.scope + ' ' : '') + args.type + '(' + period + ')';
64
- blocks.push({ type: 'title', text: title });
65
- blocks.push({ type: 'subtitle', text: '某制造型企业 · 质量改进部门 | 编制日期:' + now + ' | 编制人:' + (args.author || 'AI 质量改进智能体(人工复核后发布)') });
66
- blocks.push({ type: 'hr' });
67
-
68
- const ov = dashboardSnapshot(args.projectId || args.scope, window);
69
- blocks.push({ type: 'p', text: 'UTC+08:00|' + localStamp(new Date(window.start)) + ' 至 ' +
70
- localStamp(new Date(window.calendarEnd)) + '(起含止不含)|范围 ' + (ov.scope || '全平台') });
71
- if (!ov.measurements && !ov.issueTotal && !ov.projects.length && !ov.ledger.length) {
72
- blocks.push({ type: 'p', text: '选定期间及范围内暂无业务数据。' });
73
- }
74
- blocks.push({ type: 'h1', text: '一、总体情况' });
75
- blocks.push({ type: 'p', text: '本期(' + period + ')平台共归集质量数据 ' + ov.measurements + ' 个在线测量点,命中 SPC 判异 ' + ov.violations + ' 条,超差点 ' + ov.oos + ' 个;质量问题 ' + ov.issueTotal + ' 起(未关闭 ' + ov.issueOpen + ' 起,其中 A 级 ' + ov.issueA + ' 起);在改改进项目 ' + ov.projOpen + ' 个,按期率 ' + ov.onTimeRate + ',超期 ' + ov.projOverdue + ' 个。' });
76
- blocks.push({ type: 'kv', items: [
77
- ['一次下线合格率(FTT 代理值)', ov.ftt],
78
- ['SPC 判异总数', String(ov.violations)],
79
- ['在线测量超差点', String(ov.oos)],
80
- ['未关闭质量问题', ov.issueOpen + ' 起(A 级 ' + ov.issueA + ' 起)'],
81
- ['在改改进项目', ov.projOpen + ' 个'],
82
- ['项目按期关闭率', ov.onTimeRate],
83
- ['已核定改进收益', ov.benefitVerified + ' 万元'],
84
- ['数据截至', ov.dataAt],
85
- ] });
86
-
87
- // 特性状态表
88
- blocks.push({ type: 'h1', text: '二、过程能力与判异情况' });
89
- blocks.push({ type: 'table', header: ['特性编号', '特性名称', '车间', 'USL/LSL', '均值', 'Cpk', '超差数', '判异数', '状态'],
90
- rows: ov.charRows.map((c) => [c.id, c.name, c.workshop, c.usl + ' / ' + c.lsl, c.mean, c.cpk, c.oos, c.hits, c.status]),
91
- widths: [1200, 2200, 900, 1400, 900, 700, 700, 700, 900] });
92
- if (ov.violations > 0) {
93
- blocks.push({ type: 'p', text: '本期判异明细(最严重的 5 项):' });
94
- blocks.push({ type: 'table', header: ['特性', '命中准则', '严重度', '涉及点数', '控制限'],
95
- rows: ov.violationRows.slice(0, 5).map((v) => [v.char, v.rules, v.severity, String(v.count), v.limits]) });
96
- blocks.push({ type: 'quote', text: 'SPC 判异结论由平台判异引擎按 GB/T 4091 八大准则自动计算得出,非人工目测判断。' });
97
- }
98
-
99
- // 问题与项目
100
- blocks.push({ type: 'h1', text: '三、重点问题与改进项目' });
101
- if (ov.topIssues.length) {
102
- blocks.push({ type: 'table', header: ['编号', '产品', '车间', '问题描述', '等级', '状态', '责任人', '关联项目'],
103
- rows: ov.topIssues.map((i) => [i.id, i.model, i.workshop, i.title, i.severity, i.status, i.owner, i.projectId || '—']) });
104
- }
105
- if (ov.projects.length) {
106
- blocks.push({ type: 'p', text: '' });
107
- blocks.push({ type: 'table', header: ['项目编号', '项目名称', '当前阶段', '责任人', '进度', '截止', '是否超期'],
108
- rows: ov.projects.map((p) => [p.id, p.title, p.stage, p.owner, p.progress + '%', (p.dueAt || '').slice(0, 10), p.overdue ? '超期 ' + p.overdueDays + ' 天' : '正常']) });
109
- }
110
-
111
- // 收益
112
- blocks.push({ type: 'h1', text: '四、改进收益' });
113
- const ledger = ov.ledger;
114
- const vt = ledger.filter((b) => b.status === 'verified').reduce((a, c) => a + (Number(c.amount) || 0), 0);
115
- const pd = ledger.filter((b) => b.status === 'pending').reduce((a, c) => a + (Number(c.amount) || 0), 0);
116
- blocks.push({ type: 'p', text: '已财务核定收益 ' + vt.toFixed(1) + ' 万元,待核定 ' + pd.toFixed(1) + ' 万元。收益口径:仅计直接损失(报废料、返工工时、停线损失、索赔),单价采用 ERP 当期标准价,摊销期不超过 12 个月。' });
117
- if (ledger.length) {
118
- blocks.push({ type: 'table', header: ['单号', '项目', '类型', '金额(万元)', '期间', '状态'],
119
- rows: ledger.slice(0, 15).map((b) => [b.id, b.projectId || '—', b.type, String(b.amount), b.period, b.status === 'verified' ? '财务已核定' : '待核定']) });
120
- }
121
-
122
- // 自定义章节
123
- (args.sections || []).forEach((s, i) => {
124
- blocks.push({ type: 'h1', text: String.fromCharCode(20116 + i) + '、' + s.heading });
125
- (s.paragraphs || []).forEach((p) => blocks.push({ type: 'p', text: p }));
126
- (s.bullets || []).forEach((b) => blocks.push({ type: 'bullet', text: b }));
127
- if (s.table) blocks.push({ type: 'table', header: s.table.header, rows: s.table.rows });
128
- });
129
-
130
- // 结论与建议
131
- blocks.push({ type: 'h1', text: '五、结论与下一步建议' });
132
- const conclusion = [];
133
- if (ov.violations > 0) conclusion.push('①本期存在 ' + ov.violations + ' 条 SPC 判异信号,需在 24h 内锁定失控起点并做 4M 变化点比对(换批、换人、换模、换参数)。');
134
- if (ov.projOverdue > 0) conclusion.push('②' + ov.projOverdue + ' 个改进项目超期,建议升级厂级 QRQC 并抄送科长,明确资源与卡点。');
135
- if (ov.issueA > 0) conclusion.push('③存在 ' + ov.issueA + ' 起未关闭 A 级问题,须按 2h 响应、24h 围堵的要求推进,必要时启动专题攻关。');
136
- if (ov.topIssueType) conclusion.push('④ 本期登记最多的问题类型为「' + ov.topIssueType.name + '」,' + ov.topIssueType.count +
137
- ' 起,占本期登记问题的 ' + (100 * ov.topIssueType.count / ov.issueTotal).toFixed(1) + '%。');
138
- conclusion.push('⑤持续把关闭项目的经验按「问题-原因-对策-效果」四元组沉淀入知识库,形成防再发闭环。');
139
- conclusion.forEach((c) => blocks.push({ type: 'numbered', text: c }));
140
- blocks.push({ type: 'hr' });
141
- blocks.push({ type: 'subtitle', text: '本报告由「' + brandName() + '」自动生成;所有数据来自平台插件(@MES/@SPC/@AQI/@OA/@FIN)实时查询,结论均挂接数据出处。对外发布前需经人工确认。' });
142
-
143
- const buf = getOffice().docxWrite(blocks);
144
- const dir = outDir(ctx);
145
- const fname = safeName(title) + '_' + randomUUID() + '.docx';
146
- const fp = path.join(dir, fname);
147
- fs.writeFileSync(fp, buf);
148
- const rec = store.col('reports').insert({
149
- type: args.type, title, period, scope: ov.scope, window, author: args.author || '智能体',
150
- format: 'docx', file: path.basename(fp), size: buf.length, sections: (args.sections || []).map((s) => s.heading),
151
- downloadUrl: '/qip-real-workbench/api/reports/download/' + encodeURIComponent(path.basename(fp)), status: 'draft',
152
- createdAt: new Date().toISOString(),
153
- });
154
- store.audit({ plugin: '@DOC', action: '生成报告', params: { type: args.type, title }, resultSummary: rec.id + ' ' + path.basename(fp), purpose: '报表生成' });
155
- return {
156
- ok: true, 报告编号: rec.id, 报告标题: title, 格式: 'Word (.docx)', 文件大小: Math.round(buf.length / 1024) + ' KB',
157
- 下载链接: rec.downloadUrl, 已保存至: '报表中心',
158
- 章节: blocks.filter((b) => b.type === 'h1').map((b) => b.text),
159
- 内容摘要: '含总体情况 KPI、' + ov.charRows.length + ' 个特性的过程能力表、' + ov.topIssues.length + ' 起重点问题、' + ov.projects.length + ' 个改进项目、收益台账与结论建议。',
160
- 提醒: '报告为草稿状态,对外发布前需人工确认(报告中心 → 确认发布)。',
161
- };
162
- },
163
- });
164
-
165
- const DAY = 86400000;
166
- const ZONE = 8 * 3600000;
167
- const dayText = (time) => new Date(time + ZONE).toISOString().slice(0, 10);
168
- function monthWindow(period) {
169
- if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(String(period || ''))) return null;
170
- const start = Date.parse(period + '-01T00:00:00+08:00');
171
- const next = new Date(start + ZONE);
172
- next.setUTCMonth(next.getUTCMonth() + 1);
173
- return { start, end: next.getTime() - ZONE };
174
- }
175
- function monday(time) {
176
- return time - ((new Date(time + ZONE).getUTCDay() + 6) % 7) * DAY;
177
- }
178
- function firstWeek(year) { return monday(Date.parse(String(year).padStart(4, '0') + '-01-04T00:00:00+08:00')); }
179
- function reportWindow(period, type, asOf) {
180
- const now = spc.windowOf(7, asOf).end;
181
- const today = dayText(now - 1);
182
- if (!period && type === '质量周报') {
183
- const start = monday(Date.parse(today + 'T00:00:00+08:00'));
184
- return { start, end: now, calendarEnd: start + 7 * DAY, label: dayText(start) + ' 至 ' + dayText(start + 6 * DAY) };
185
- }
186
- const label = String(period || today.slice(0, 7)).trim();
187
- let range = monthWindow(label);
188
- if (!range) {
189
- const iso = /^(\d{4})-W(\d{1,2})$/i.exec(label);
190
- const local = /^第\s*(\d{1,2})\s*周$/.exec(label);
191
- if (iso || local) {
192
- const year = Number(iso ? iso[1] : today.slice(0, 4));
193
- const week = Number(iso ? iso[2] : local[1]);
194
- const start = firstWeek(year) + (week - 1) * 7 * DAY;
195
- if (week > 0 && start < firstWeek(year + 1)) range = { start, end: start + 7 * DAY };
196
- }
197
- }
198
- if (!range) throw Object.assign(new Error('期间请填写 YYYY-MM 或 YYYY-Www'), { status: 400 });
199
- return { start: range.start, end: Math.min(range.end, now), calendarEnd: range.end, label };
200
- }
201
-
202
- function scopeFilters(scope) {
203
- const term = String(scope || '').trim();
204
- const project = store.col('projects').get(term);
205
- const ch = store.col('spcChars').get(term);
206
- const main = (row) => !term || row.model === term || row.workshop === term;
207
- const context = (row, ref) => (!ref.model || row.model === ref.model) && (!ref.workshop || row.workshop === ref.workshop) && !!(ref.model || ref.workshop);
208
- return {
209
- term,
210
- char: (row) => ch ? row.id === ch.id : project ? context(row, project) : main(row),
211
- issue: (row) => project ? row.id === project.issueId || row.projectId === project.id : ch ? row.charId === ch.id || context(row, ch) : main(row),
212
- project: (row) => project ? row.id === project.id : ch ? row.charId === ch.id || context(row, ch) : main(row),
213
- defect: (row) => project ? context(row, project) : ch ? context(row, ch) : main(row),
214
- };
215
- }
216
-
217
- function dashboardSnapshot(scope, window = spc.windowOf(7)) {
218
- const filters = scopeFilters(scope);
219
- const chars = store.col('spcChars').find(filters.char);
220
- const series = new Map(chars.map((ch) => [ch.id, []]));
221
- for (const row of store.col('measurements').all()) {
222
- if (series.has(row.charId) && spc.valid(row.value) && spc.inWindow(row.ts, window)) series.get(row.charId).push(row);
223
- }
224
- const charRows = [], violationRows = [];
225
- let measurements = 0, specSamples = 0, oos = 0, violations = 0;
226
- for (const ch of chars) {
227
- const rows = series.get(ch.id).sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts));
228
- const cap = spc.capability(rows, ch);
229
- const result = spc.chartFor(rows, ch.controlMethod || 'Xbar-R');
230
- const count = rows.filter((r) => isOutOfSpec(Number(r.value), ch)).length;
231
- measurements += rows.length; oos += count; violations += result.hits.length;
232
- if (hasUsableSpec(ch)) specSamples += rows.length;
233
- if (result.hits.length) violationRows.push({
234
- char: ch.id + ' ' + ch.name, rules: result.hits.map((h) => '准则' + h.rule).join('/'),
235
- severity: result.hits.some((h) => h.severity === 'high') ? '高' : '中',
236
- count: new Set(result.hits.flatMap((rule) => rule.indexes)).size,
237
- limits: result.limits.lcl.toFixed(3) + '~' + result.limits.ucl.toFixed(3),
238
- });
239
- charRows.push({ id: ch.id, name: ch.name, workshop: ch.workshop, usl: ch.usl ?? '—', lsl: ch.lsl ?? '—',
240
- mean: spc.round(cap.mean), cp: spc.round(cap.cp, 3), cpk: spc.round(cap.cpk, 3), ppk: spc.round(cap.ppk, 3),
241
- withinSd: spc.round(cap.withinSd), overallSd: spc.round(cap.sd), basis: cap.sigmaBasis, oos: count, hits: result.hits.length, status: result.status });
242
- }
243
- const issues = store.col('issues').find(filters.issue);
244
- const issuePeriod = issues.filter((i) => spc.inWindow(i.createdAt || i.ts, window));
245
- const openAtEnd = (row) => isOpen(row,window.end);
246
- const issueOpen = issues.filter(openAtEnd);
247
- const frequencies = new Map();
248
- for (const issue of issuePeriod) {
249
- const kind = issue.category || issue.defectType || issue.type;
250
- if (kind) frequencies.set(kind, (frequencies.get(kind) || 0) + 1);
251
- }
252
- const top = [...frequencies].sort((a, b) => b[1] - a[1])[0];
253
- const projects = store.col('projects').find(filters.project);
254
- const projectIds = new Set(projects.map((p) => p.id));
255
- const validDue = (p) => Number.isFinite(deadlineTime(p.dueAt));
256
- const open = projects.filter(openAtEnd).map((p) => projectTiming(p,window.end));
257
- const closed = projects.filter((p) => spc.inWindow(p.closedAt, window));
258
- const eligible = closed.filter(validDue);
259
- const ledger = store.col('benefits').find((b) => {
260
- if (filters.term && !projectIds.has(b.projectId) && b.model !== filters.term && b.workshop !== filters.term) return false;
261
- if (monthWindow(b.period) && monthWindow(window.label)) {
262
- return b.period === window.label && window.end > window.start && (!b.createdAt || Date.parse(b.createdAt) < window.end);
263
- }
264
- return spc.inWindow(b.createdAt || b.ts || b.period, window);
265
- }).map((b) => b.status === 'verified' && b.verifiedAt && Date.parse(b.verifiedAt) >= window.end ? { ...b, status: 'pending' } : b);
266
- const amount = (status) => spc.round(ledger.filter((b) => b.status === status).reduce((sum, b) => sum + (Number(b.amount) || 0), 0), 1);
267
- return {
268
- scope: filters.term, measurements, specSamples, unassessedMeasurements:measurements-specSamples, oos, violations, violationRows, charRows,
269
- defects: store.col('defects').find((row) => filters.defect(row) && spc.inWindow(row.ts, window)).length,
270
- ftt: specSamples ? (100 * (specSamples - oos) / specSamples).toFixed(2) + '%' : measurements ? '暂无可判定测量数据' : '暂无测量数据',
271
- issueTotal: issuePeriod.length, issueOpen: issueOpen.length, issueA: issueOpen.filter((i) => i.severity === 'A').length,
272
- topIssues: issuePeriod.slice().sort((a, b) => String(a.severity).localeCompare(String(b.severity)) || Date.parse(b.createdAt) - Date.parse(a.createdAt)).slice(0, 8),
273
- topIssueType: top && { name: top[0], count: top[1] }, projOpen: open.length, projOverdue: open.filter((p) => p.overdue).length,
274
- projClosed: closed.length, onTimeRate: eligible.length ? (100 * eligible.filter((p) => Date.parse(p.closedAt) <= deadlineTime(p.dueAt)).length / eligible.length).toFixed(1) + '%' : '—',
275
- projects: open.slice(0, 12), benefitVerified: amount('verified'), benefitPending: amount('pending'), ledger,
276
- dataAt: localStamp(new Date(window.end)),
277
- };
278
- }
279
-
280
- function writeExport(bytes, base, ext, ctx) {
281
- const filename = base + '_' + randomUUID() + '.' + ext;
282
- fs.writeFileSync(path.join(outDir(ctx), filename), bytes, { flag: 'wx' });
283
- return { 下载链接: '/qip-real-workbench/api/reports/download/' + encodeURIComponent(filename), 文件名: base + '.' + ext,
284
- 文件大小: Math.round(bytes.length / 1024) + ' KB' };
285
- }
286
-
287
- define({
288
- plugin: '@DOC', name: 'measurement_import_template', label: '下载测量导入模板',
289
- description: '创建仅含导入表头的 Excel 测量模板。',
290
- parameters: { type: 'object', properties: {} },
291
- run(_args, ctx) {
292
- const bytes = getOffice().xlsxWrite([{ name: '测量导入', headerRow: true, rows: [measurementFields] }]);
293
- return { ok: true, ...writeExport(bytes, '导入模板_测量数据', 'xlsx', ctx) };
294
- },
295
- });
296
-
297
- /* ------------------------------------------------------------------ */
298
- define({
299
- plugin: '@DOC', name: 'data_export', label: '导出真实数据(Excel/CSV)',
300
- description: '把平台真实数据导出为真正的 Excel(.xlsx,多工作表)或 CSV 文件,返回下载链接。支持导出:问题库、改进项目、SPC 测量数据、判异结果、知识库、收益台账、AI 质检缺陷、全部。',
301
- parameters: {
302
- type: 'object',
303
- properties: {
304
- dataset: { type: 'string', enum: ['issues', 'projects', 'measurements', 'spc', 'knowledge', 'benefits', 'defects', 'all'], description: '数据集' },
305
- format: { type: 'string', enum: ['xlsx', 'csv'], description: '默认 xlsx' },
306
- charId: { type: 'string', description: '导出测量数据时可指定特性' },
307
- days: { type: 'number', description: '时间窗天数' },
308
- filename: { type: 'string' },
309
- },
310
- required: ['dataset'],
311
- },
312
- run(args, ctx) {
313
- const ds = args.dataset;
314
- const sheets = [];
315
- const add = (name, rows) => { if (rows && rows.length) sheets.push({ name, rows }); };
316
-
317
- if (ds === 'issues' || ds === 'all') add('质量问题库', [['编号', '产品', '车间', '工位', '问题描述', '来源', '等级', '状态', '责任人', '关联项目', '登记时间', '关闭时间']].concat(
318
- store.col('issues').all().map((i) => [i.id, i.model, i.workshop, i.station, i.title, i.source, i.severity, i.status, i.owner, i.projectId || '', (i.createdAt || '').slice(0, 10), i.closedAt ? i.closedAt.slice(0, 10) : ''])));
319
- if (ds === 'projects' || ds === 'all') add('改进项目', [['编号', '项目名称', '产品', '车间', '责任人', '等级', '当前阶段', '进度', '截止日期', '是否超期', '来源问题', '预估收益(万元)']].concat(
320
- store.col('projects').all().map((row) => projectTiming(row)).map((p) => [p.id, p.title, p.model, p.workshop, p.owner, p.severity, p.stage, p.progress + '%', (p.dueAt || '').slice(0, 10), p.overdue ? '超期' : '正常', p.issueId, p.benefitEstimate])));
321
- if (ds === 'measurements' || ds === 'all') {
322
- const rows = [['特性编号', '特性名称', '产品', '车间', '工位', '时间', '班次', '测量值', '单位', '批次', '供应商', '操作者', 'VIN', '子组']];
323
- let ms = store.col('measurements').all();
324
- if (args.charId) ms = ms.filter((m) => m.charId === args.charId);
325
- if (args.days) {
326
- const window = spc.windowOf(args.days, args.asOf);
327
- ms = ms.filter((m) => spc.inWindow(m.ts, window));
328
- }
329
- for (const m of ms) rows.push([m.charId, m.charName, m.model, m.workshop, m.station, m.ts, m.shift, m.value, m.unit, m.batch, m.supplier, m.operator, m.vin, m.subgroup]);
330
- add('测量数据', rows);
331
- }
332
- if (ds === 'spc' || ds === 'all') {
333
- const rows = [['特性编号', '名称', 'USL', 'LSL', '均值', '组内标准差', '整体标准差', '估计方法', 'Cp', 'Cpk', 'Ppk', '超差数', '判异数', '状态']];
334
- const snap = dashboardSnapshot(args.charId, spc.windowOf(args.days ?? 7, args.asOf));
335
- snap.charRows.forEach((c) => rows.push([c.id, c.name, c.usl, c.lsl, c.mean, c.withinSd, c.overallSd, c.basis, c.cp, c.cpk, c.ppk, c.oos, c.hits, c.status]));
336
- add('SPC过程能力', rows);
337
- }
338
- if (ds === 'knowledge' || ds === 'all') add('知识库', [['编号', '类型', '类别', '标题', '问题', '原因', '对策', '效果', '标签', '出处', '作者', '浏览数']].concat(
339
- store.col('knowledge').all().map((k) => [k.id, k.type, k.category, k.title, k.problem, k.cause, k.action, k.effect, (k.tags || []).join('/'), k.source, k.author, k.views])));
340
- if (ds === 'benefits' || ds === 'all') add('收益台账', [['单号', '项目', '类型', '金额(万元)', '期间', '状态', '核定人', '口径']].concat(
341
- store.col('benefits').all().map((b) => [b.id, b.projectId, b.type, b.amount, b.period, b.status === 'verified' ? '财务已核定' : '待核定', b.verifiedBy, b.formula])));
342
- if (ds === 'defects' || ds === 'all') add('AI质检缺陷', [['时间', '产品', '车间', '工位', '缺陷类型', '置信度', '等级', '批次', '图片']].concat(
343
- store.col('defects').all().map((d) => [d.ts.slice(0, 19), d.model, d.workshop, d.station, d.type, d.confidence, d.severity, d.batch, d.imageRef])));
344
-
345
- if (!sheets.length) return { ok: false, error: '该数据集没有数据可导出' };
346
- const base = safeName(args.filename || (brandName() + '_质量数据_' + ds + '_' + dayText(Date.now())));
347
- const csv = args.format === 'csv';
348
- if (!csv && sheets.some((sheet) => sheet.rows.length > 1048576)) {
349
- return { ok: false, error: '数据超过 Excel 每表 1,048,576 行上限,请选择 CSV 导出或缩小时间范围。' };
350
- }
351
- const ext = csv ? sheets.length > 1 ? 'zip' : 'csv' : 'xlsx';
352
- const office = getOffice();
353
- const bytes = ext === 'zip'
354
- ? office.zipWrite(sheets.map((sheet) => ({ name: sheet.name + '.csv', data: office.csvWrite(sheet.rows) })))
355
- : csv ? office.csvWrite(sheets[0].rows) : office.xlsxWrite(sheets.map((s) => ({ ...s, headerRow: true })));
356
- return {
357
- ok: true, 数据集: ds, 格式: ext === 'zip' ? 'ZIP(各数据集 CSV)' : ext === 'csv' ? 'CSV' : 'Excel (.xlsx)',
358
- 工作表: sheets.map((s) => s.name + '(' + (s.rows.length - 1) + ' 行)'),
359
- ...writeExport(bytes, base, ext, ctx),
360
- };
361
-
362
- },
363
- });
364
-
365
- /* ------------------------------------------------------------------ */
366
- define({
367
- plugin: '@DOC', name: 'report_list', label: '报表清单',
368
- description: '查看报表中心已生成的报告与导出文件清单。',
369
- parameters: { type: 'object', properties: { limit: { type: 'number' } } },
370
- run(args) {
371
- const rows = store.col('reports').all().slice().sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
372
- return { ok: true, 报表数: rows.length, 清单: rows.slice(0, args.limit || 20).map((r) => ({ 编号: r.id, 类型: r.type, 标题: r.title, 期间: r.period, 格式: r.format, 状态: r.status === 'published' ? '已发布' : '草稿', 生成时间: (r.createdAt || '').slice(0, 16).replace('T', ' '), 下载: r.downloadUrl })) };
373
- },
374
- });
375
-
376
- /* ------------------------------------------------------------------ */
377
- define({
378
- plugin: '@DOC', name: 'qrqc_voice_report', label: '现场语音报问题',
379
- description: '把车间现场语音/文字描述(如「四车间三线右后门关门声发闷,连续第三台」)结构化为标准质量问题单:自动识别产品/车间/工位/缺陷类别/等级,回填 MES 工位批次,并匹配相似历史案例。',
380
- parameters: {
381
- type: 'object',
382
- properties: {
383
- text: { type: 'string', description: '现场语音转写文本或口头描述' },
384
- reporter: { type: 'string', description: '报告人' },
385
- },
386
- required: ['text'],
387
- },
388
- write: true,
389
- run(args) {
390
- const t = args.text || '';
391
- const wsNames = (((store.db.settings || {}).naming || {}).workshops) || ['一车间', '二车间', '三车间', '四车间', '五车间'];
392
- const workshop = wsNames.find((w) => t.indexOf(w) >= 0 || t.indexOf(w.replace(' ', '')) >= 0) || '';
393
- const pdNames = (((store.db.settings || {}).naming || {}).products) || ['产品A', '产品B', '产品C'];
394
- const modelHit = pdNames.find((p) => t.indexOf(p) >= 0) || '';
395
- const modelMatch = modelHit ? null : t.match(/产品\s*([ABC])/);
396
- const model = modelHit || (modelMatch ? '产品' + modelMatch[1] : '');
397
- const stationMatch = t.match(/([\u4e00-\u9fa5]{0,4}(?:一线|二线|三线|线|工位|车间))/);
398
- const station = stationMatch ? stationMatch[0] : (workshop ? workshop + '(工位待补)' : '');
399
- const severity = /(安全|起火|断裂|失效|批量|出口|法规)/.test(t) ? 'A' : /(连续|第[三四五六七八九十]台|多台|批量)/.test(t) ? 'B' : 'C';
400
- const rec = store.col('issues').insert({
401
- title: t.slice(0, 40), description: '【现场语音报障】' + t, model, workshop, station,
402
- source: '现场', severity, owner: '待指派', status: '整改中', projectId: null, tags: [],
403
- quantity: 0, history: [{ ts: new Date().toISOString(), user: args.reporter || '现场报障', action: '语音报障登记', note: 'AI 结构化提取' }],
404
- });
405
- const retrieval = require('../lib/retrieval');
406
- const { getKbIndex } = require('./business');
407
- const kb = retrieval.search(getKbIndex(), t, 3).map((h) => ({ 编号: h.doc.id, 标题: h.doc.title, 相关度: h.score }));
408
- return {
409
- ok: true, 问题编号: rec.id,
410
- 结构化结果: { 产品: model || '待确认', 车间: workshop || '待确认', 工位: station, 问题: t, 等级: severity, 定级依据: severity === 'A' ? '涉及安全/法规或已流出' : severity === 'B' ? '批量或重复发生' : '个案' },
411
- 回填建议: { 批次: '可由 @MES 按工位+时间窗自动回填', 班次: '按报障时间自动关联' },
412
- 相似历史案例: kb,
413
- 下一步: '已写入问题库;如为重复发生,建议调用 project_create 立项',
414
- };
415
- },
416
- });
417
-
418
- module.exports = { dashboardSnapshot, monthWindow, outDir };
419
-
420
- /** 平台显示名:初始设置里填了公司名称就用它(与 host.cjs 的 brandName 口径一致) */
421
- function brandName() {
422
- try {
423
- const s = (store.db && store.db.settings) || {};
424
- const b = typeof s.brand === 'string' ? s.brand.trim() : '';
425
- return b || '全质开源质量平台';
426
- } catch (e) {
427
- return '全质开源质量平台';
428
- }
429
- }
430
-
1
+ 'use strict';
2
+ /**
3
+ * 文档与报表工具:让智能体产出"可交付物"
4
+ * ------------------------------------------------------------------
5
+ * · report_generate 生成真实的 .docx 报告(周报/月报/专项/根因分析/8D)
6
+ * · data_export 把平台真实数据导出为真正的 .xlsx / .csv
7
+ * · report_list 报表中心清单
8
+ * 用到的 OOXML 能力来自 lib/office.js(零依赖自研)。
9
+ */
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { randomUUID } = require('node:crypto');
13
+ const { define } = require('./registry');
14
+ const store = require('../lib/store');
15
+ const spc = require('../lib/spc');
16
+ const { isOutOfSpec, hasUsableSpec } = require('./data');
17
+ const { isOpen, deadlineTime, projectTiming } = require('../lib/quality-state');
18
+ const { measurementFields } = require('../lib/data-import');
19
+ const { STAGES } = require('./business');
20
+
21
+ let office = null;
22
+ function getOffice() {
23
+ if (!office) office = require('../lib/office');
24
+ return office;
25
+ }
26
+
27
+ /** 输出目录(服务器注入) */
28
+ function outDir(ctx) {
29
+ const dir = (ctx && ctx.outputDir) || path.join(process.cwd(), 'data', 'reports');
30
+ fs.mkdirSync(dir, { recursive: true });
31
+ return dir;
32
+ }
33
+ function localStamp(d) {
34
+ const p = (n) => String(n).padStart(2, '0');
35
+ d = new Date(d.getTime() + 8 * 3600000);
36
+ return d.getUTCFullYear() + '-' + p(d.getUTCMonth() + 1) + '-' + p(d.getUTCDate()) + ' ' + p(d.getUTCHours()) + ':' + p(d.getUTCMinutes());
37
+ }
38
+ function safeName(s) { return String(s).replace(/[\\/:*?"<>|]/g, '_').slice(0, 80); }
39
+
40
+ /* ------------------------------------------------------------------ */
41
+ define({
42
+ plugin: '@DOC', name: 'report_generate', label: '生成质量报告(Word)',
43
+ description: '生成真实可下载的 Word 报告(.docx)。支持:质量周报、质量月报、专项分析报告、根因分析报告、8D 报告、SPC 分析报告。报告内含真实数据表格与统计结论。生成后返回下载链接。',
44
+ parameters: {
45
+ type: 'object',
46
+ properties: {
47
+ type: { type: 'string', enum: ['质量周报', '质量月报', '专项分析报告', '根因分析报告', '8D报告', 'SPC分析报告'], description: '报告类型' },
48
+ title: { type: 'string', description: '报告标题(可自动生成)' },
49
+ scope: { type: 'string', description: '范围:产品/车间/项目编号/特性编号' },
50
+ period: { type: 'string', description: '期间,如 2026-09 或 第 40 周' },
51
+ sections: { type: 'array', items: { type: 'object' }, description: '自定义章节 [{heading, paragraphs:[], bullets:[], table:{header,rows}}]' },
52
+ includeCharts: { type: 'boolean', description: '是否包含表格化图表数据(默认 true)' },
53
+ projectId: { type: 'string', description: '8D/根因分析报告可指定项目' },
54
+ author: { type: 'string' },
55
+ },
56
+ required: ['type'],
57
+ },
58
+ run(args, ctx) {
59
+ const blocks = [];
60
+ const window = reportWindow(args.period, args.type, args.asOf);
61
+ const period = window.label;
62
+ const now = localStamp(new Date());
63
+ const title = args.title || (args.scope ? args.scope + ' ' : '') + args.type + '(' + period + ')';
64
+ blocks.push({ type: 'title', text: title });
65
+ blocks.push({ type: 'subtitle', text: '某制造型企业 · 质量改进部门 | 编制日期:' + now + ' | 编制人:' + (args.author || 'AI 质量改进智能体(人工复核后发布)') });
66
+ blocks.push({ type: 'hr' });
67
+
68
+ const ov = dashboardSnapshot(args.projectId || args.scope, window);
69
+ blocks.push({ type: 'p', text: 'UTC+08:00|' + localStamp(new Date(window.start)) + ' 至 ' +
70
+ localStamp(new Date(window.calendarEnd)) + '(起含止不含)|范围 ' + (ov.scope || '全平台') });
71
+ if (!ov.measurements && !ov.issueTotal && !ov.projects.length && !ov.ledger.length) {
72
+ blocks.push({ type: 'p', text: '选定期间及范围内暂无业务数据。' });
73
+ }
74
+ blocks.push({ type: 'h1', text: '一、总体情况' });
75
+ blocks.push({ type: 'p', text: '本期(' + period + ')平台共归集质量数据 ' + ov.measurements + ' 个在线测量点,命中 SPC 判异 ' + ov.violations + ' 条,超差点 ' + ov.oos + ' 个;质量问题 ' + ov.issueTotal + ' 起(未关闭 ' + ov.issueOpen + ' 起,其中 A 级 ' + ov.issueA + ' 起);在改改进项目 ' + ov.projOpen + ' 个,按期率 ' + ov.onTimeRate + ',超期 ' + ov.projOverdue + ' 个。' });
76
+ blocks.push({ type: 'kv', items: [
77
+ ['一次下线合格率(FTT 代理值)', ov.ftt],
78
+ ['SPC 判异总数', String(ov.violations)],
79
+ ['在线测量超差点', String(ov.oos)],
80
+ ['未关闭质量问题', ov.issueOpen + ' 起(A 级 ' + ov.issueA + ' 起)'],
81
+ ['在改改进项目', ov.projOpen + ' 个'],
82
+ ['项目按期关闭率', ov.onTimeRate],
83
+ ['已核定改进收益', ov.benefitVerified + ' 万元'],
84
+ ['数据截至', ov.dataAt],
85
+ ] });
86
+
87
+ // 特性状态表
88
+ blocks.push({ type: 'h1', text: '二、过程能力与判异情况' });
89
+ blocks.push({ type: 'table', header: ['特性编号', '特性名称', '车间', 'USL/LSL', '均值', 'Cpk', '超差数', '判异数', '状态'],
90
+ rows: ov.charRows.map((c) => [c.id, c.name, c.workshop, c.usl + ' / ' + c.lsl, c.mean, c.cpk, c.oos, c.hits, c.status]),
91
+ widths: [1200, 2200, 900, 1400, 900, 700, 700, 700, 900] });
92
+ if (ov.violations > 0) {
93
+ blocks.push({ type: 'p', text: '本期判异明细(最严重的 5 项):' });
94
+ blocks.push({ type: 'table', header: ['特性', '命中准则', '严重度', '涉及点数', '控制限'],
95
+ rows: ov.violationRows.slice(0, 5).map((v) => [v.char, v.rules, v.severity, String(v.count), v.limits]) });
96
+ blocks.push({ type: 'quote', text: 'SPC 判异结论由平台判异引擎按 GB/T 4091 八大准则自动计算得出,非人工目测判断。' });
97
+ }
98
+
99
+ // 问题与项目
100
+ blocks.push({ type: 'h1', text: '三、重点问题与改进项目' });
101
+ if (ov.topIssues.length) {
102
+ blocks.push({ type: 'table', header: ['编号', '产品', '车间', '问题描述', '等级', '状态', '责任人', '关联项目'],
103
+ rows: ov.topIssues.map((i) => [i.id, i.model, i.workshop, i.title, i.severity, i.status, i.owner, i.projectId || '—']) });
104
+ }
105
+ if (ov.projects.length) {
106
+ blocks.push({ type: 'p', text: '' });
107
+ blocks.push({ type: 'table', header: ['项目编号', '项目名称', '当前阶段', '责任人', '进度', '截止', '是否超期'],
108
+ rows: ov.projects.map((p) => [p.id, p.title, p.stage, p.owner, p.progress + '%', (p.dueAt || '').slice(0, 10), p.overdue ? '超期 ' + p.overdueDays + ' 天' : '正常']) });
109
+ }
110
+
111
+ // 收益
112
+ blocks.push({ type: 'h1', text: '四、改进收益' });
113
+ const ledger = ov.ledger;
114
+ const vt = ledger.filter((b) => b.status === 'verified').reduce((a, c) => a + (Number(c.amount) || 0), 0);
115
+ const pd = ledger.filter((b) => b.status === 'pending').reduce((a, c) => a + (Number(c.amount) || 0), 0);
116
+ blocks.push({ type: 'p', text: '已财务核定收益 ' + vt.toFixed(1) + ' 万元,待核定 ' + pd.toFixed(1) + ' 万元。收益口径:仅计直接损失(报废料、返工工时、停线损失、索赔),单价采用 ERP 当期标准价,摊销期不超过 12 个月。' });
117
+ if (ledger.length) {
118
+ blocks.push({ type: 'table', header: ['单号', '项目', '类型', '金额(万元)', '期间', '状态'],
119
+ rows: ledger.slice(0, 15).map((b) => [b.id, b.projectId || '—', b.type, String(b.amount), b.period, b.status === 'verified' ? '财务已核定' : '待核定']) });
120
+ }
121
+
122
+ // 自定义章节
123
+ (args.sections || []).forEach((s, i) => {
124
+ blocks.push({ type: 'h1', text: String.fromCharCode(20116 + i) + '、' + s.heading });
125
+ (s.paragraphs || []).forEach((p) => blocks.push({ type: 'p', text: p }));
126
+ (s.bullets || []).forEach((b) => blocks.push({ type: 'bullet', text: b }));
127
+ if (s.table) blocks.push({ type: 'table', header: s.table.header, rows: s.table.rows });
128
+ });
129
+
130
+ // 结论与建议
131
+ blocks.push({ type: 'h1', text: '五、结论与下一步建议' });
132
+ const conclusion = [];
133
+ if (ov.violations > 0) conclusion.push('①本期存在 ' + ov.violations + ' 条 SPC 判异信号,需在 24h 内锁定失控起点并做 4M 变化点比对(换批、换人、换模、换参数)。');
134
+ if (ov.projOverdue > 0) conclusion.push('②' + ov.projOverdue + ' 个改进项目超期,建议升级厂级 QRQC 并抄送科长,明确资源与卡点。');
135
+ if (ov.issueA > 0) conclusion.push('③存在 ' + ov.issueA + ' 起未关闭 A 级问题,须按 2h 响应、24h 围堵的要求推进,必要时启动专题攻关。');
136
+ if (ov.topIssueType) conclusion.push('④ 本期登记最多的问题类型为「' + ov.topIssueType.name + '」,' + ov.topIssueType.count +
137
+ ' 起,占本期登记问题的 ' + (100 * ov.topIssueType.count / ov.issueTotal).toFixed(1) + '%。');
138
+ conclusion.push('⑤持续把关闭项目的经验按「问题-原因-对策-效果」四元组沉淀入知识库,形成防再发闭环。');
139
+ conclusion.forEach((c) => blocks.push({ type: 'numbered', text: c }));
140
+ blocks.push({ type: 'hr' });
141
+ blocks.push({ type: 'subtitle', text: '本报告由「' + brandName() + '」自动生成;所有数据来自平台插件(@MES/@SPC/@AQI/@OA/@FIN)实时查询,结论均挂接数据出处。对外发布前需经人工确认。' });
142
+
143
+ const buf = getOffice().docxWrite(blocks);
144
+ const dir = outDir(ctx);
145
+ const fname = safeName(title) + '_' + randomUUID() + '.docx';
146
+ const fp = path.join(dir, fname);
147
+ fs.writeFileSync(fp, buf);
148
+ const rec = store.col('reports').insert({
149
+ type: args.type, title, period, scope: ov.scope, window, author: args.author || '智能体',
150
+ format: 'docx', file: path.basename(fp), size: buf.length, sections: (args.sections || []).map((s) => s.heading),
151
+ downloadUrl: '/qip-real-workbench/api/reports/download/' + encodeURIComponent(path.basename(fp)), status: 'draft',
152
+ createdAt: new Date().toISOString(),
153
+ });
154
+ store.audit({ plugin: '@DOC', action: '生成报告', params: { type: args.type, title }, resultSummary: rec.id + ' ' + path.basename(fp), purpose: '报表生成' });
155
+ return {
156
+ ok: true, 报告编号: rec.id, 报告标题: title, 格式: 'Word (.docx)', 文件大小: Math.round(buf.length / 1024) + ' KB',
157
+ 下载链接: rec.downloadUrl, 已保存至: '报表中心',
158
+ 章节: blocks.filter((b) => b.type === 'h1').map((b) => b.text),
159
+ 内容摘要: '含总体情况 KPI、' + ov.charRows.length + ' 个特性的过程能力表、' + ov.topIssues.length + ' 起重点问题、' + ov.projects.length + ' 个改进项目、收益台账与结论建议。',
160
+ 提醒: '报告为草稿状态,对外发布前需人工确认(报告中心 → 确认发布)。',
161
+ };
162
+ },
163
+ });
164
+
165
+ const DAY = 86400000;
166
+ const ZONE = 8 * 3600000;
167
+ const dayText = (time) => new Date(time + ZONE).toISOString().slice(0, 10);
168
+ function monthWindow(period) {
169
+ if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(String(period || ''))) return null;
170
+ const start = Date.parse(period + '-01T00:00:00+08:00');
171
+ const next = new Date(start + ZONE);
172
+ next.setUTCMonth(next.getUTCMonth() + 1);
173
+ return { start, end: next.getTime() - ZONE };
174
+ }
175
+ function monday(time) {
176
+ return time - ((new Date(time + ZONE).getUTCDay() + 6) % 7) * DAY;
177
+ }
178
+ function firstWeek(year) { return monday(Date.parse(String(year).padStart(4, '0') + '-01-04T00:00:00+08:00')); }
179
+ function reportWindow(period, type, asOf) {
180
+ const now = spc.windowOf(7, asOf).end;
181
+ const today = dayText(now - 1);
182
+ if (!period && type === '质量周报') {
183
+ const start = monday(Date.parse(today + 'T00:00:00+08:00'));
184
+ return { start, end: now, calendarEnd: start + 7 * DAY, label: dayText(start) + ' 至 ' + dayText(start + 6 * DAY) };
185
+ }
186
+ const label = String(period || today.slice(0, 7)).trim();
187
+ let range = monthWindow(label);
188
+ if (!range) {
189
+ const iso = /^(\d{4})-W(\d{1,2})$/i.exec(label);
190
+ const local = /^第\s*(\d{1,2})\s*周$/.exec(label);
191
+ if (iso || local) {
192
+ const year = Number(iso ? iso[1] : today.slice(0, 4));
193
+ const week = Number(iso ? iso[2] : local[1]);
194
+ const start = firstWeek(year) + (week - 1) * 7 * DAY;
195
+ if (week > 0 && start < firstWeek(year + 1)) range = { start, end: start + 7 * DAY };
196
+ }
197
+ }
198
+ if (!range) throw Object.assign(new Error('期间请填写 YYYY-MM 或 YYYY-Www'), { status: 400 });
199
+ return { start: range.start, end: Math.min(range.end, now), calendarEnd: range.end, label };
200
+ }
201
+
202
+ function scopeFilters(scope) {
203
+ const term = String(scope || '').trim();
204
+ const project = store.col('projects').get(term);
205
+ const ch = store.col('spcChars').get(term);
206
+ const main = (row) => !term || row.model === term || row.workshop === term;
207
+ const context = (row, ref) => (!ref.model || row.model === ref.model) && (!ref.workshop || row.workshop === ref.workshop) && !!(ref.model || ref.workshop);
208
+ return {
209
+ term,
210
+ char: (row) => ch ? row.id === ch.id : project ? context(row, project) : main(row),
211
+ issue: (row) => project ? row.id === project.issueId || row.projectId === project.id : ch ? row.charId === ch.id || context(row, ch) : main(row),
212
+ project: (row) => project ? row.id === project.id : ch ? row.charId === ch.id || context(row, ch) : main(row),
213
+ defect: (row) => project ? context(row, project) : ch ? context(row, ch) : main(row),
214
+ };
215
+ }
216
+
217
+ function dashboardSnapshot(scope, window = spc.windowOf(7)) {
218
+ const filters = scopeFilters(scope);
219
+ const chars = store.col('spcChars').find(filters.char);
220
+ const series = new Map(chars.map((ch) => [ch.id, []]));
221
+ for (const row of store.col('measurements').all()) {
222
+ if (series.has(row.charId) && spc.valid(row.value) && spc.inWindow(row.ts, window)) series.get(row.charId).push(row);
223
+ }
224
+ const charRows = [], violationRows = [];
225
+ let measurements = 0, specSamples = 0, oos = 0, violations = 0;
226
+ for (const ch of chars) {
227
+ const rows = series.get(ch.id).sort((a, b) => Date.parse(a.ts) - Date.parse(b.ts));
228
+ const cap = spc.capability(rows, ch);
229
+ const result = spc.chartFor(rows, ch.controlMethod || 'Xbar-R');
230
+ const count = rows.filter((r) => isOutOfSpec(Number(r.value), ch)).length;
231
+ measurements += rows.length; oos += count; violations += result.hits.length;
232
+ if (hasUsableSpec(ch)) specSamples += rows.length;
233
+ if (result.hits.length) violationRows.push({
234
+ char: ch.id + ' ' + ch.name, rules: result.hits.map((h) => '准则' + h.rule).join('/'),
235
+ severity: result.hits.some((h) => h.severity === 'high') ? '高' : '中',
236
+ count: new Set(result.hits.flatMap((rule) => rule.indexes)).size,
237
+ limits: result.limits.lcl.toFixed(3) + '~' + result.limits.ucl.toFixed(3),
238
+ });
239
+ charRows.push({ id: ch.id, name: ch.name, workshop: ch.workshop, usl: ch.usl ?? '—', lsl: ch.lsl ?? '—',
240
+ mean: spc.round(cap.mean), cp: spc.round(cap.cp, 3), cpk: spc.round(cap.cpk, 3), ppk: spc.round(cap.ppk, 3),
241
+ withinSd: spc.round(cap.withinSd), overallSd: spc.round(cap.sd), basis: cap.sigmaBasis, oos: count, hits: result.hits.length, status: result.status });
242
+ }
243
+ const issues = store.col('issues').find(filters.issue);
244
+ const issuePeriod = issues.filter((i) => spc.inWindow(i.createdAt || i.ts, window));
245
+ const openAtEnd = (row) => isOpen(row,window.end);
246
+ const issueOpen = issues.filter(openAtEnd);
247
+ const frequencies = new Map();
248
+ for (const issue of issuePeriod) {
249
+ const kind = issue.category || issue.defectType || issue.type;
250
+ if (kind) frequencies.set(kind, (frequencies.get(kind) || 0) + 1);
251
+ }
252
+ const top = [...frequencies].sort((a, b) => b[1] - a[1])[0];
253
+ const projects = store.col('projects').find(filters.project);
254
+ const projectIds = new Set(projects.map((p) => p.id));
255
+ const validDue = (p) => Number.isFinite(deadlineTime(p.dueAt));
256
+ const open = projects.filter(openAtEnd).map((p) => projectTiming(p,window.end));
257
+ const closed = projects.filter((p) => spc.inWindow(p.closedAt, window));
258
+ const eligible = closed.filter(validDue);
259
+ const ledger = store.col('benefits').find((b) => {
260
+ if (filters.term && !projectIds.has(b.projectId) && b.model !== filters.term && b.workshop !== filters.term) return false;
261
+ if (monthWindow(b.period) && monthWindow(window.label)) {
262
+ return b.period === window.label && window.end > window.start && (!b.createdAt || Date.parse(b.createdAt) < window.end);
263
+ }
264
+ return spc.inWindow(b.createdAt || b.ts || b.period, window);
265
+ }).map((b) => b.status === 'verified' && b.verifiedAt && Date.parse(b.verifiedAt) >= window.end ? { ...b, status: 'pending' } : b);
266
+ const amount = (status) => spc.round(ledger.filter((b) => b.status === status).reduce((sum, b) => sum + (Number(b.amount) || 0), 0), 1);
267
+ return {
268
+ scope: filters.term, measurements, specSamples, unassessedMeasurements:measurements-specSamples, oos, violations, violationRows, charRows,
269
+ defects: store.col('defects').find((row) => filters.defect(row) && spc.inWindow(row.ts, window)).length,
270
+ ftt: specSamples ? (100 * (specSamples - oos) / specSamples).toFixed(2) + '%' : measurements ? '暂无可判定测量数据' : '暂无测量数据',
271
+ issueTotal: issuePeriod.length, issueOpen: issueOpen.length, issueA: issueOpen.filter((i) => i.severity === 'A').length,
272
+ topIssues: issuePeriod.slice().sort((a, b) => String(a.severity).localeCompare(String(b.severity)) || Date.parse(b.createdAt) - Date.parse(a.createdAt)).slice(0, 8),
273
+ topIssueType: top && { name: top[0], count: top[1] }, projOpen: open.length, projOverdue: open.filter((p) => p.overdue).length,
274
+ projClosed: closed.length, onTimeRate: eligible.length ? (100 * eligible.filter((p) => Date.parse(p.closedAt) <= deadlineTime(p.dueAt)).length / eligible.length).toFixed(1) + '%' : '—',
275
+ projects: open.slice(0, 12), benefitVerified: amount('verified'), benefitPending: amount('pending'), ledger,
276
+ dataAt: localStamp(new Date(window.end)),
277
+ };
278
+ }
279
+
280
+ function writeExport(bytes, base, ext, ctx) {
281
+ const filename = base + '_' + randomUUID() + '.' + ext;
282
+ fs.writeFileSync(path.join(outDir(ctx), filename), bytes, { flag: 'wx' });
283
+ return { 下载链接: '/qip-real-workbench/api/reports/download/' + encodeURIComponent(filename), 文件名: base + '.' + ext,
284
+ 文件大小: Math.round(bytes.length / 1024) + ' KB' };
285
+ }
286
+
287
+ define({
288
+ plugin: '@DOC', name: 'measurement_import_template', label: '下载测量导入模板',
289
+ description: '创建仅含导入表头的 Excel 测量模板。',
290
+ parameters: { type: 'object', properties: {} },
291
+ run(_args, ctx) {
292
+ const bytes = getOffice().xlsxWrite([{ name: '测量导入', headerRow: true, rows: [measurementFields] }]);
293
+ return { ok: true, ...writeExport(bytes, '导入模板_测量数据', 'xlsx', ctx) };
294
+ },
295
+ });
296
+
297
+ /* ------------------------------------------------------------------ */
298
+ define({
299
+ plugin: '@DOC', name: 'data_export', label: '导出真实数据(Excel/CSV)',
300
+ description: '把平台真实数据导出为真正的 Excel(.xlsx,多工作表)或 CSV 文件,返回下载链接。支持导出:问题库、改进项目、SPC 测量数据、判异结果、知识库、收益台账、AI 质检缺陷、全部。',
301
+ parameters: {
302
+ type: 'object',
303
+ properties: {
304
+ dataset: { type: 'string', enum: ['issues', 'projects', 'measurements', 'spc', 'knowledge', 'benefits', 'defects', 'all'], description: '数据集' },
305
+ format: { type: 'string', enum: ['xlsx', 'csv'], description: '默认 xlsx' },
306
+ charId: { type: 'string', description: '导出测量数据时可指定特性' },
307
+ days: { type: 'number', description: '时间窗天数' },
308
+ filename: { type: 'string' },
309
+ },
310
+ required: ['dataset'],
311
+ },
312
+ run(args, ctx) {
313
+ const ds = args.dataset;
314
+ const sheets = [];
315
+ const add = (name, rows) => { if (rows && rows.length) sheets.push({ name, rows }); };
316
+
317
+ if (ds === 'issues' || ds === 'all') add('质量问题库', [['编号', '产品', '车间', '工位', '问题描述', '来源', '等级', '状态', '责任人', '关联项目', '登记时间', '关闭时间']].concat(
318
+ store.col('issues').all().map((i) => [i.id, i.model, i.workshop, i.station, i.title, i.source, i.severity, i.status, i.owner, i.projectId || '', (i.createdAt || '').slice(0, 10), i.closedAt ? i.closedAt.slice(0, 10) : ''])));
319
+ if (ds === 'projects' || ds === 'all') add('改进项目', [['编号', '项目名称', '产品', '车间', '责任人', '等级', '当前阶段', '进度', '截止日期', '是否超期', '来源问题', '预估收益(万元)']].concat(
320
+ store.col('projects').all().map((row) => projectTiming(row)).map((p) => [p.id, p.title, p.model, p.workshop, p.owner, p.severity, p.stage, p.progress + '%', (p.dueAt || '').slice(0, 10), p.overdue ? '超期' : '正常', p.issueId, p.benefitEstimate])));
321
+ if (ds === 'measurements' || ds === 'all') {
322
+ const rows = [['特性编号', '特性名称', '产品', '车间', '工位', '时间', '班次', '测量值', '单位', '批次', '供应商', '操作者', 'VIN', '子组']];
323
+ let ms = store.col('measurements').all();
324
+ if (args.charId) ms = ms.filter((m) => m.charId === args.charId);
325
+ if (args.days) {
326
+ const window = spc.windowOf(args.days, args.asOf);
327
+ ms = ms.filter((m) => spc.inWindow(m.ts, window));
328
+ }
329
+ for (const m of ms) rows.push([m.charId, m.charName, m.model, m.workshop, m.station, m.ts, m.shift, m.value, m.unit, m.batch, m.supplier, m.operator, m.vin, m.subgroup]);
330
+ add('测量数据', rows);
331
+ }
332
+ if (ds === 'spc' || ds === 'all') {
333
+ const rows = [['特性编号', '名称', 'USL', 'LSL', '均值', '组内标准差', '整体标准差', '估计方法', 'Cp', 'Cpk', 'Ppk', '超差数', '判异数', '状态']];
334
+ const snap = dashboardSnapshot(args.charId, spc.windowOf(args.days ?? 7, args.asOf));
335
+ snap.charRows.forEach((c) => rows.push([c.id, c.name, c.usl, c.lsl, c.mean, c.withinSd, c.overallSd, c.basis, c.cp, c.cpk, c.ppk, c.oos, c.hits, c.status]));
336
+ add('SPC过程能力', rows);
337
+ }
338
+ if (ds === 'knowledge' || ds === 'all') add('知识库', [['编号', '类型', '类别', '标题', '问题', '原因', '对策', '效果', '标签', '出处', '作者', '浏览数']].concat(
339
+ store.col('knowledge').all().map((k) => [k.id, k.type, k.category, k.title, k.problem, k.cause, k.action, k.effect, (k.tags || []).join('/'), k.source, k.author, k.views])));
340
+ if (ds === 'benefits' || ds === 'all') add('收益台账', [['单号', '项目', '类型', '金额(万元)', '期间', '状态', '核定人', '口径']].concat(
341
+ store.col('benefits').all().map((b) => [b.id, b.projectId, b.type, b.amount, b.period, b.status === 'verified' ? '财务已核定' : '待核定', b.verifiedBy, b.formula])));
342
+ if (ds === 'defects' || ds === 'all') add('AI质检缺陷', [['时间', '产品', '车间', '工位', '缺陷类型', '置信度', '等级', '批次', '图片']].concat(
343
+ store.col('defects').all().map((d) => [d.ts.slice(0, 19), d.model, d.workshop, d.station, d.type, d.confidence, d.severity, d.batch, d.imageRef])));
344
+
345
+ if (!sheets.length) return { ok: false, error: '该数据集没有数据可导出' };
346
+ const base = safeName(args.filename || (brandName() + '_质量数据_' + ds + '_' + dayText(Date.now())));
347
+ const csv = args.format === 'csv';
348
+ if (!csv && sheets.some((sheet) => sheet.rows.length > 1048576)) {
349
+ return { ok: false, error: '数据超过 Excel 每表 1,048,576 行上限,请选择 CSV 导出或缩小时间范围。' };
350
+ }
351
+ const ext = csv ? sheets.length > 1 ? 'zip' : 'csv' : 'xlsx';
352
+ const office = getOffice();
353
+ const bytes = ext === 'zip'
354
+ ? office.zipWrite(sheets.map((sheet) => ({ name: sheet.name + '.csv', data: office.csvWrite(sheet.rows) })))
355
+ : csv ? office.csvWrite(sheets[0].rows) : office.xlsxWrite(sheets.map((s) => ({ ...s, headerRow: true })));
356
+ return {
357
+ ok: true, 数据集: ds, 格式: ext === 'zip' ? 'ZIP(各数据集 CSV)' : ext === 'csv' ? 'CSV' : 'Excel (.xlsx)',
358
+ 工作表: sheets.map((s) => s.name + '(' + (s.rows.length - 1) + ' 行)'),
359
+ ...writeExport(bytes, base, ext, ctx),
360
+ };
361
+
362
+ },
363
+ });
364
+
365
+ /* ------------------------------------------------------------------ */
366
+ define({
367
+ plugin: '@DOC', name: 'report_list', label: '报表清单',
368
+ description: '查看报表中心已生成的报告与导出文件清单。',
369
+ parameters: { type: 'object', properties: { limit: { type: 'number' } } },
370
+ run(args) {
371
+ const rows = store.col('reports').all().slice().sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
372
+ return { ok: true, 报表数: rows.length, 清单: rows.slice(0, args.limit || 20).map((r) => ({ 编号: r.id, 类型: r.type, 标题: r.title, 期间: r.period, 格式: r.format, 状态: r.status === 'published' ? '已发布' : '草稿', 生成时间: (r.createdAt || '').slice(0, 16).replace('T', ' '), 下载: r.downloadUrl })) };
373
+ },
374
+ });
375
+
376
+ /* ------------------------------------------------------------------ */
377
+ define({
378
+ plugin: '@DOC', name: 'qrqc_voice_report', label: '现场语音报问题',
379
+ description: '把车间现场语音/文字描述(如「四车间三线右后门关门声发闷,连续第三台」)结构化为标准质量问题单:自动识别产品/车间/工位/缺陷类别/等级,回填 MES 工位批次,并匹配相似历史案例。',
380
+ parameters: {
381
+ type: 'object',
382
+ properties: {
383
+ text: { type: 'string', description: '现场语音转写文本或口头描述' },
384
+ reporter: { type: 'string', description: '报告人' },
385
+ },
386
+ required: ['text'],
387
+ },
388
+ write: true,
389
+ run(args) {
390
+ const t = args.text || '';
391
+ const wsNames = (((store.db.settings || {}).naming || {}).workshops) || ['一车间', '二车间', '三车间', '四车间', '五车间'];
392
+ const workshop = wsNames.find((w) => t.indexOf(w) >= 0 || t.indexOf(w.replace(' ', '')) >= 0) || '';
393
+ const pdNames = (((store.db.settings || {}).naming || {}).products) || ['产品A', '产品B', '产品C'];
394
+ const modelHit = pdNames.find((p) => t.indexOf(p) >= 0) || '';
395
+ const modelMatch = modelHit ? null : t.match(/产品\s*([ABC])/);
396
+ const model = modelHit || (modelMatch ? '产品' + modelMatch[1] : '');
397
+ const stationMatch = t.match(/([\u4e00-\u9fa5]{0,4}(?:一线|二线|三线|线|工位|车间))/);
398
+ const station = stationMatch ? stationMatch[0] : (workshop ? workshop + '(工位待补)' : '');
399
+ const severity = /(安全|起火|断裂|失效|批量|出口|法规)/.test(t) ? 'A' : /(连续|第[三四五六七八九十]台|多台|批量)/.test(t) ? 'B' : 'C';
400
+ const rec = store.col('issues').insert({
401
+ title: t.slice(0, 40), description: '【现场语音报障】' + t, model, workshop, station,
402
+ source: '现场', severity, owner: '待指派', status: '整改中', projectId: null, tags: [],
403
+ quantity: 0, history: [{ ts: new Date().toISOString(), user: args.reporter || '现场报障', action: '语音报障登记', note: 'AI 结构化提取' }],
404
+ });
405
+ const retrieval = require('../lib/retrieval');
406
+ const { getKbIndex } = require('./business');
407
+ const kb = retrieval.search(getKbIndex(), t, 3).map((h) => ({ 编号: h.doc.id, 标题: h.doc.title, 相关度: h.score }));
408
+ return {
409
+ ok: true, 问题编号: rec.id,
410
+ 结构化结果: { 产品: model || '待确认', 车间: workshop || '待确认', 工位: station, 问题: t, 等级: severity, 定级依据: severity === 'A' ? '涉及安全/法规或已流出' : severity === 'B' ? '批量或重复发生' : '个案' },
411
+ 回填建议: { 批次: '可由 @MES 按工位+时间窗自动回填', 班次: '按报障时间自动关联' },
412
+ 相似历史案例: kb,
413
+ 下一步: '已写入问题库;如为重复发生,建议调用 project_create 立项',
414
+ };
415
+ },
416
+ });
417
+
418
+ module.exports = { dashboardSnapshot, monthWindow, outDir };
419
+
420
+ /** 平台显示名:初始设置里填了公司名称就用它(与 host.cjs 的 brandName 口径一致) */
421
+ function brandName() {
422
+ try {
423
+ const s = (store.db && store.db.settings) || {};
424
+ const b = typeof s.brand === 'string' ? s.brand.trim() : '';
425
+ return b || '全质开源质量平台';
426
+ } catch (e) {
427
+ return '全质开源质量平台';
428
+ }
429
+ }
430
+