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
@@ -1,327 +1,359 @@
1
- 'use strict';
2
-
3
- const fs = require('node:fs');
4
- const path = require('node:path');
5
- const os = require('node:os');
6
- const { createHash, randomUUID } = require('node:crypto');
7
- const { execFile } = require('node:child_process');
8
- const { promisify } = require('node:util');
9
- const { pathToFileURL } = require('node:url');
10
- const office = require('./office');
11
- const word = require('./qms-word');
12
- const { referenceKey } = require('./qms-procedure-review');
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const { createHash, randomUUID } = require('node:crypto');
7
+ const { execFile } = require('node:child_process');
8
+ const { promisify } = require('node:util');
9
+ const { pathToFileURL } = require('node:url');
10
+ const office = require('./office');
11
+ const word = require('./qms-word');
12
+ const { referenceKey } = require('./qms-procedure-review');
13
13
  const exec = promisify(execFile);
14
-
15
- const maxPackBytes = 96 * 1024 * 1024;
16
- const families = [
17
- { code: 'AAA', label: 'IATF 16949', cert: /(?:IATF|ISO)16949/ },
18
- { code: 'BBB', label: 'ISO 9001', cert: /ISO9001/ },
19
- { code: 'CCC', label: 'ISO 14001', cert: /ISO14001/ },
20
- { code: 'DDD', label: 'ISO 45001', cert: /ISO45001/ },
21
- ];
22
- const deptAliases = [
23
- /综合|人事|行政|办公室/, /研发|技术|工程|设计/, /采购|供应链/,
24
- /市场|销售|商务/, /财务|会计/, /制造|生产|车间/, /质量|品质|品保|质检/,
25
- ];
26
- const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
27
-
28
- function converterPath() {
29
- if (process.env.QMS_SOFFICE?.trim()) return process.env.QMS_SOFFICE.trim();
30
- if (process.platform !== 'win32') return 'soffice';
31
- for (const directory of [...(process.env.PATH || '').split(';'), process.env.ProgramFiles && path.join(process.env.ProgramFiles,'LibreOffice','program'),
32
- process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'],'LibreOffice','program')].filter(Boolean)) {
33
- const binary = path.join(directory.replace(/^"|"$/g,''),'soffice.com');
34
- if (fs.existsSync(binary)) return binary;
35
- }
36
- return 'soffice.com';
37
- }
38
-
39
- async function convertLegacy(folder, legacy) {
40
- const scratch = fs.mkdtempSync(path.join(os.tmpdir(),'qip-lo-'));
41
- try {
42
- const input = legacy.map(({item}) => {
43
- const short = path.join(scratch,item.id+'.doc');
44
- fs.copyFileSync(path.join(folder,item.id+'.doc'),short);
45
- return short;
46
- });
47
- try {
48
- await exec(converterPath(),['-env:UserInstallation='+pathToFileURL(path.join(scratch,'profile')).href,
49
- '--headless','--convert-to','docx','--outdir',scratch,...input],
50
- {timeout:180000,windowsHide:true,maxBuffer:2*1024*1024,cwd:scratch});
51
- } catch (error) {
52
- throw Object.assign(new Error(error.code === 'ENOENT' ? '找不到 LibreOffice。请安装或配置 QMS_SOFFICE 指向程序。'
53
- : error.killed ? '旧版 Word 转换超时。请尝试分批导入或另存为 DOCX。' : 'LibreOffice 执行转换失败。请检查文件或另存为 DOCX。'),{status:422});
54
- }
55
- for (const {item} of legacy) {
56
- try {
57
- const bytes = fs.readFileSync(path.join(scratch,item.id+'.docx'));
58
- word.readTemplate(bytes);
59
- fs.writeFileSync(path.join(folder,item.id+'.docx'),bytes);
60
- item.workingDigest = hash(bytes);
61
- } catch {
62
- throw Object.assign(new Error(item.filename+' 未生成可编辑的 DOCX,请检查原件或另存为 DOCX 后重新导入。'),{status:422});
63
- }
64
- }
65
- } finally { fs.rmSync(scratch,{recursive:true,force:true}); }
66
- }
67
-
68
- function familiesFor(survey) {
69
- const certs = [...(Array.isArray(survey.certs) ? survey.certs : [survey.certs]), survey.otherCert]
70
- .filter(Boolean).map((value) => String(value).toUpperCase().replace(/[^A-Z0-9]/g, ''));
71
- return families.filter((family) => certs.some((cert) => family.cert.test(cert)));
72
- }
73
-
74
- function department(source, survey) {
75
- if (!source) return { name: '', owner: '' };
76
- const orgs = (survey.orgs || []).filter((org) => org.dept);
77
- const role = deptAliases.find((aliases) => aliases.test(source));
78
- const match = orgs.find((org) => org.dept === source) ||
79
- (role && orgs.find((org) => role.test(org.duty || '') || role.test(org.dept)));
80
- return { name: match?.dept || source, owner: match?.owner || '' };
81
- }
82
-
83
- function archiveEntry(relativeName, bytes) {
84
- const segments = relativeName.normalize('NFC').split('/');
85
- if (segments.some((segment) => !segment || segment === '.' || segment === '..' || /[<>:"\\|?*\x00-\x1f]/.test(segment))) return null;
86
- const categoryIndex = segments.findIndex((segment) => /^(?:手册|质量手册|程序文件)$/.test(segment));
87
- if (categoryIndex < 0 || categoryIndex >= segments.length - 1) return null;
88
- const category = segments[categoryIndex] === '程序文件' ? 'procedure' : 'manual';
89
- const file = segments.at(-1);
90
- if (file.startsWith('~$') || !/\.(?:docx|doc|xlsx)$/i.test(file)) return null;
91
- const text = segments.slice(categoryIndex + 1).join('/');
92
- const family = /^(AAA|BBB|CCC|DDD)(?=$|[^A-Za-z0-9])/i.exec(file)?.[1].toUpperCase() ||
93
- segments.slice(categoryIndex + 1, -1).find((segment) => families.some(({ code }) => code === segment.toUpperCase()))?.toUpperCase();
94
- const format = path.extname(file).slice(1).toLowerCase();
95
- const id = hash(category + '/' + text).slice(0, 16);
96
- return {
97
- id, category, family: family || null, format, filename: file, digest: hash(bytes),
98
- sourceDepartment: category === 'procedure' ? segments[categoryIndex + 1] === file ? '未分类' : segments[categoryIndex + 1] : '',
99
- sourceFolders: category === 'procedure' ? segments.slice(categoryIndex + 2, -1) : [],
100
- };
101
- }
102
-
103
- const migrated = 'qms-files-in-knowledge-v2';
104
- const rootFolders = { manual:['manuals','手册'], procedure:['procedures','程序文件'] };
105
- const departments = ['制造部','市场部','研发部','综合部','质量部','采购部'];
106
- const normalize = value => String(value || '').normalize('NFKC').replace(/\s+/g,'').toUpperCase();
107
- const familyPrefix = /^(AAA|BBB|CCC|DDD)(?=$|[^A-Z0-9])/;
108
- const hashBuffer = (file) => hash(fs.readFileSync(file));
109
- const scopeMatches=(scope,actual)=>!scope || (normalize(actual) && normalize(actual).includes(normalize(scope)));
110
-
111
- function sourceFamilies(filename, ancestry) {
112
- for (const value of [filename,...ancestry]) {
113
- const explicit = normalize(value).match(familyPrefix);
114
- if (explicit) return [explicit[1]];
115
- }
116
- const known = families.filter(family => [filename,...ancestry].some(value => family.cert.test(normalize(value))));
117
- return known.map(family=>family.code);
118
- }
119
-
120
- function titleKey(value) {
121
- return normalize(value.replace(/\.(?:docx?|xlsx)$/i,'')).replace(/^(?:AAA|BBB|CCC|DDD)[-_-]+/,'')
122
- .replace(/[-_((](?:REV[._-]?|V)[A-Z0-9.]+[))]?$/,'').replace(/[与及]/g,'和');
123
- }
124
-
125
- function checkedTemplate(item, bytes) {
126
- if (bytes.length > 10*1024*1024 && item.format !== 'xlsx') throw new Error('Word 原件超过 10 MB');
127
- if (item.format === 'docx') word.readTemplate(bytes);
128
- if (item.format === 'doc' && bytes.subarray(0,8).toString('hex') !== 'd0cf11e0a1b11ae1') throw new Error('不是有效的旧版 Word 文件');
129
- if (item.format === 'xlsx' && !office.zipRead(bytes,{entries:2000,bytes:40*1024*1024})['xl/workbook.xml']) {
130
- throw new Error('不是有效的 Excel 工作簿');
131
- }
132
- }
133
-
134
- function createTemplateLibrary(root, getKnowledge) {
135
- function directory(knowledge,item) {
136
- const [id,name]=rootFolders[item.category];
137
- const branch=knowledge.ensureFolder('system',name,id);
138
- if (item.category==='manual') return knowledge.ensureFolder(branch,'质量手册','quality-manuals');
139
- const departmentName=item.sourceDepartment || '未分类';
140
- const slot=departments.indexOf(departmentName);
141
- let dest=knowledge.ensureFolder(branch,departmentName,slot>=0?'procedure-dept-'+slot:undefined);
142
- for (const label of item.sourceFolders || []) dest=knowledge.ensureFolder(dest,label);
143
- return dest;
144
- }
145
-
146
- async function migrateLegacy() {
147
- const knowledge=getKnowledge();
148
- if (knowledge.readMarker(migrated)) return;
149
- let pack;
150
- try { pack=JSON.parse(fs.readFileSync(path.join(root,'active.json'),'utf8')); }
151
- catch (error) { if (error.code!=='ENOENT') throw error; }
152
- if (pack) {
153
- for (const item of pack.items) {
154
- const dir=path.join(root,pack.id);
155
- const original=path.join(dir,item.id+'.'+item.format);
156
- if (hashBuffer(original)!==item.digest) throw new Error('原模板校验失败:'+item.filename);
157
- const indexBytes=item.format==='doc' && item.workingDigest ? fs.readFileSync(path.join(dir,item.id+'.docx')) : undefined;
158
- if (indexBytes && hash(indexBytes)!==item.workingDigest) throw new Error('旧 Word 转换副本校验失败:'+item.filename);
159
- const {document}=await knowledge.upload(directory(knowledge,item),item.filename,fs.createReadStream(original),{
160
- createdAt:'1970-01-01T00:00:00.000Z',indexBytes,
161
- });
162
- knowledge.saveLegacySource(document.id,pack.id+'/'+item.id);
163
- }
164
- }
165
- knowledge.writeMarker(migrated);
166
- }
167
-
168
- // Older clients can still import an archive. Each file becomes a knowledge-base document.
169
- async function install(zipBytes) {
170
- let entries;
171
- try {
172
- entries=office.zipRead(zipBytes,{entries:4000,bytes:360*1024*1024,
173
- include:name=>/\.(?:docx|doc|xlsx)$/i.test(name) && !/[/\\]~\$/.test(name)});
174
- } catch (cause) {
175
- throw Object.assign(new Error('无法读取 ZIP:'+cause.message),{status:400});
176
- }
177
- const pending=Object.entries(entries).flatMap(([name,bytes])=>{
178
- const item=archiveEntry(name,bytes);
179
- return item?[{item,bytes}]:[];
180
- });
181
- if (!pending.length) throw Object.assign(new Error('ZIP 内需有「手册」或「程序文件」目录和 Word、Excel 文件'),{status:400});
182
- for (const {item,bytes} of pending) {
183
- try { checkedTemplate(item,bytes); }
184
- catch (cause) { throw Object.assign(new Error(item.filename+':'+cause.message),{status:400}); }
185
- }
186
- const knowledge=getKnowledge();
187
- const {Readable}=require('node:stream');
188
- for (const {item,bytes} of pending) await knowledge.upload(directory(knowledge,item),item.filename,Readable.from([bytes]));
189
- return {manual:pending.filter(row=>row.item.category==='manual').length,procedure:pending.filter(row=>row.item.category==='procedure').length};
190
- }
191
-
192
- function candidates(type,survey) {
193
- const {folders,files}=getKnowledge().list();
194
- const map=new Map(folders.map(folder=>[folder.id,folder]));
195
- const [branchId,branchName]=rootFolders[type];
196
- const rows=[];
197
- for (const file of files) {
198
- const format=path.extname(file.name).toLowerCase().slice(1);
199
- if (!['docx','doc','xlsx'].includes(format) || type==='manual' && format==='xlsx' || file.name.startsWith('~$')) continue;
200
- if (!scopeMatches(file.product,survey.products) || !scopeMatches(file.process,[survey.processFlow,survey.scope].filter(Boolean).join(' '))) continue;
201
- const ancestry=[];
202
- let current=map.get(file.folderId);
203
- while (current && current.parentId!=='system') {
204
- ancestry.unshift(current.name);
205
- current=map.get(current.parentId);
206
- }
207
- if (!current || current.scope!=='company' || current.id!==branchId && current.name!==branchName ||
208
- ancestry.some(name=>/^已生成(?:质量)?(?:手册|程序文件)/.test(name))) continue;
209
- const normalized=titleKey(file.name);
210
- const sourceDepartment=type==='procedure' ? ancestry[0] || '未分类' : '';
211
- rows.push({file,format, normalized, ancestry, sourceDepartment, department:department(sourceDepartment,survey),
212
- families:sourceFamilies(file.name,ancestry)});
213
- }
214
- return rows;
215
- }
216
-
217
- function choose(rows,type,family) {
218
- const compatible=rows.filter(item=>!item.families.length || item.families.includes(family));
219
- const active=compatible.filter(({file})=>file.effective);
220
- const expired=compatible.filter(({file})=>file.revisionState==='withdrawn' || file.revisionState==='released' && !file.effective &&
221
- compatible.some(other=>other.file.supersedes===file.id && (other.file.effective || other.file.revisionState==='withdrawn')));
222
- const prioritized=active.filter(item=>item.file.revisionState==='released' || !expired.some(old=>
223
- old.normalized===item.normalized && old.department.name===item.department.name ||
224
- old.file.documentNumber && old.file.documentNumber===item.file.documentNumber));
225
- prioritized.sort((a,b)=>{
226
- const fit=Number(b.families.includes(family))-Number(a.families.includes(family));
227
- if (fit) return fit;
228
- const controlled=(b.file.revisionState==='released')-(a.file.revisionState==='released');
229
- if (controlled) return controlled;
230
- return b.file.createdAt.localeCompare(a.file.createdAt);
231
- });
232
- if (type==='manual') return prioritized.slice(0,1);
233
- const seenNames=new Set();
234
- const seenNumbers=new Set();
235
- return prioritized.filter(item=>{
236
- const name=item.department.name+'\0'+item.normalized;
237
- const number=item.file.documentNumber;
238
- if (seenNames.has(name) || number && seenNumbers.has(number)) return false;
239
- seenNames.add(name);
240
- if (number) seenNumbers.add(number);
241
- return true;
242
- });
243
- }
244
-
245
- function select(type,survey,target) {
246
- const rows=candidates(type,survey);
247
- const supported=familiesFor(survey);
248
- const options=supported.map(({code,label})=>({code,label,available:choose(rows,type,code).length>0}));
249
- const family=target ? options.find(item=>item.code===target) : options.find(item=>item.available);
250
- const selected=target && !family ? [] : choose(rows,type,family?.code);
251
- const issue=target && !family ? '目标体系不在已保存的调研中。' :
252
- !selected.length ? '企业知识库「体系文件 / '+rootFolders[type][1]+'」没有可用于本次生成的生效文件。请上传适用文件。' : '';
253
- const plan=selected.map(({file,format,ancestry,sourceDepartment,department:owner})=>({
254
- id:file.id, folderId:file.folderId, code:'T-'+hash(file.id).slice(0,16), filename:file.name, title:file.name.slice(0,-format.length-1),
255
- digest:file.sha, format, outputFormat:format==='doc'?'docx':format, sourceDepartment, department:owner,
256
- sourceFolders: type==='procedure'?ancestry.slice(1):[], sourcePath:['体系文件',rootFolders[type][1],...ancestry].join(' / '),
257
- revision:file.revision, documentNumber:file.documentNumber,
258
- })).sort((a,b)=>a.sourceDepartment.localeCompare(b.sourceDepartment,'zh-CN') || a.filename.localeCompare(b.filename,'zh-CN') ||
259
- a.id.localeCompare(b.id));
260
- return {options,family: family && {code:family.code,label:family.label},issue,plan,
261
- key:hash(JSON.stringify(plan.map(({id,digest,revision,sourcePath})=>[id,digest,revision,sourcePath])))};
262
- }
263
-
264
- async function read(item) {
265
- try {
266
- const original=getKnowledge().document(item.id);
267
- const maxSize=(item.format==='xlsx'?48:10)*1024*1024;
268
- if (original.size>maxSize) throw new Error('原件超过 '+maxSize/(1024*1024)+' MB');
269
- const bytes=fs.readFileSync(original.filename);
270
- if (hash(bytes)!==item.digest) throw new Error('文件内容已变更,请重新生成。');
271
- checkedTemplate(item,bytes);
272
- if (item.format!=='doc') return bytes;
273
- const work=fs.mkdtempSync(path.join(os.tmpdir(),'qip-kb-word-'));
274
- try {
275
- const legacy={id:'source',filename:item.filename};
276
- fs.writeFileSync(path.join(work,'source.doc'),bytes);
277
- await convertLegacy(work,[{item:legacy}]);
278
- return fs.readFileSync(path.join(work,'source.docx'));
279
- } finally { fs.rmSync(work,{recursive:true,force:true}); }
280
- } catch (cause) {
281
- throw Object.assign(new Error(item.filename+':'+cause.message),{status:422});
282
- }
283
- }
284
-
285
- function mapDepartments(survey) {
286
- const names=['综合部','研发部','技术部','采购部','市场部','财务部','制造部','生产部','质量部'];
287
- return Object.fromEntries(names.map(name=>[name,department(name,survey).name]));
288
- }
289
-
290
- function findSupporting(titles,survey,family) {
291
- const knowledge=getKnowledge();
292
- const {folders,files}=knowledge.list();
293
- const directories=new Map(folders.map(folder=>[folder.id,folder]));
294
- const wanted=new Set(titles.map(referenceKey));
295
- const found=new Map();
296
- let budget=40*1024*1024;
297
- const priority=files.filter(file=>file.effective).sort((a,b)=>
298
- Number(b.revisionState==='released')-Number(a.revisionState==='released'));
299
- for (const file of priority) {
300
- const key=referenceKey(file.name.replace(/\.(?:docx?|pdf|xlsx?|txt)$/i,''));
301
- if (!wanted.has(key) || found.has(key) || file.size>budget || file.size>12*1024*1024 ||
302
- !/\.(?:docx?|pdf|xlsx?|txt)$/i.test(file.name) || !scopeMatches(file.product,survey.products) ||
303
- !scopeMatches(file.process,[survey.processFlow,survey.scope].filter(Boolean).join(' '))) continue;
304
- const ancestry=[];
305
- let directory=directories.get(file.folderId);
306
- while (directory && directory.id!=='system') {
307
- ancestry.unshift(directory.name);
308
- directory=directories.get(directory.parentId);
309
- }
310
- const familyCodes=sourceFamilies(file.name,ancestry);
311
- if (!directory || ancestry.some(name=>/^已生成/.test(name)) || familyCodes.length && !familyCodes.includes(family)) continue;
312
- try {
313
- const bytes=fs.readFileSync(knowledge.document(file.id).filename);
314
- if (bytes.length!==file.size || hash(bytes)!==file.sha) continue;
315
- found.set(key,{id:file.id,name:file.name,revision:file.revision,path:['体系文件',...ancestry].join(' / '),bytes});
316
- budget-=bytes.length;
317
- } catch (error) {
318
- if (error.code!=='ENOENT' && error.status!==404) throw error;
319
- }
320
- }
321
- return found;
322
- }
323
-
324
- return {select,install,migrateLegacy,read,mapDepartments,findSupporting};
325
- }
326
-
327
- module.exports = { createTemplateLibrary, maxPackBytes, knowledgeMigrationMarker:migrated };
14
+ const platformRoot = path.join(__dirname, '../../resources/qms-templates');
15
+ const platformTemplates = require('../../resources/qms-templates/manifest.json');
16
+ const platformById = new Map(platformTemplates.map(item => [item.id, item]));
17
+ const platformOriginalDigests = new Set(platformTemplates.map(item => item.originalDigest));
18
+
19
+ const maxPackBytes = 96 * 1024 * 1024;
20
+ const families = [
21
+ { code: 'AAA', label: 'IATF 16949', cert: /(?:IATF|ISO)16949/ },
22
+ { code: 'BBB', label: 'ISO 9001', cert: /ISO9001/ },
23
+ { code: 'CCC', label: 'ISO 14001', cert: /ISO14001/ },
24
+ { code: 'DDD', label: 'ISO 45001', cert: /ISO45001/ },
25
+ ];
26
+ const deptAliases = [
27
+ /综合|人事|行政|办公室/, /研发|技术|工程|设计/, /采购|供应链/,
28
+ /市场|销售|商务/, /财务|会计/, /制造|生产|车间/, /质量|品质|品保|质检/,
29
+ ];
30
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
31
+
32
+ function converterPath() {
33
+ if (process.env.QMS_SOFFICE?.trim()) return process.env.QMS_SOFFICE.trim();
34
+ if (process.platform !== 'win32') return 'soffice';
35
+ for (const directory of [...(process.env.PATH || '').split(';'), process.env.ProgramFiles && path.join(process.env.ProgramFiles,'LibreOffice','program'),
36
+ process.env['ProgramFiles(x86)'] && path.join(process.env['ProgramFiles(x86)'],'LibreOffice','program')].filter(Boolean)) {
37
+ const binary = path.join(directory.replace(/^"|"$/g,''),'soffice.com');
38
+ if (fs.existsSync(binary)) return binary;
39
+ }
40
+ return 'soffice.com';
41
+ }
42
+
43
+ async function convertLegacy(folder, legacy) {
44
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(),'qip-lo-'));
45
+ try {
46
+ const input = legacy.map(({item}) => {
47
+ const short = path.join(scratch,item.id+'.doc');
48
+ fs.copyFileSync(path.join(folder,item.id+'.doc'),short);
49
+ return short;
50
+ });
51
+ try {
52
+ await exec(converterPath(),['-env:UserInstallation='+pathToFileURL(path.join(scratch,'profile')).href,
53
+ '--headless','--convert-to','docx','--outdir',scratch,...input],
54
+ {timeout:180000,windowsHide:true,maxBuffer:2*1024*1024,cwd:scratch});
55
+ } catch (error) {
56
+ throw Object.assign(new Error(error.code === 'ENOENT' ? '找不到 LibreOffice。请安装或配置 QMS_SOFFICE 指向程序。'
57
+ : error.killed ? '旧版 Word 转换超时。请尝试分批导入或另存为 DOCX。' : 'LibreOffice 执行转换失败。请检查文件或另存为 DOCX。'),{status:422});
58
+ }
59
+ for (const {item} of legacy) {
60
+ try {
61
+ const bytes = fs.readFileSync(path.join(scratch,item.id+'.docx'));
62
+ word.readTemplate(bytes);
63
+ fs.writeFileSync(path.join(folder,item.id+'.docx'),bytes);
64
+ item.workingDigest = hash(bytes);
65
+ } catch {
66
+ throw Object.assign(new Error(item.filename+' 未生成可编辑的 DOCX,请检查原件或另存为 DOCX 后重新导入。'),{status:422});
67
+ }
68
+ }
69
+ } finally { fs.rmSync(scratch,{recursive:true,force:true}); }
70
+ }
71
+
72
+ function familiesFor(survey) {
73
+ const certs = [...(Array.isArray(survey.certs) ? survey.certs : [survey.certs]), survey.otherCert]
74
+ .filter(Boolean).map((value) => String(value).toUpperCase().replace(/[^A-Z0-9]/g, ''));
75
+ return families.filter((family) => certs.some((cert) => family.cert.test(cert)));
76
+ }
77
+
78
+ function department(source, survey) {
79
+ if (!source) return { name: '', owner: '' };
80
+ const orgs = (survey.orgs || []).filter((org) => org.dept);
81
+ const role = deptAliases.find((aliases) => aliases.test(source));
82
+ const match = orgs.find((org) => org.dept === source) ||
83
+ (role && orgs.find((org) => role.test(org.duty || '') || role.test(org.dept)));
84
+ return { name: match?.dept || source, owner: match?.owner || '' };
85
+ }
86
+
87
+ function archiveEntry(relativeName, bytes) {
88
+ const segments = relativeName.normalize('NFC').split('/');
89
+ if (segments.some((segment) => !segment || segment === '.' || segment === '..' || /[<>:"\\|?*\x00-\x1f]/.test(segment))) return null;
90
+ const categoryIndex = segments.findIndex((segment) => /^(?:手册|质量手册|程序文件)$/.test(segment));
91
+ if (categoryIndex < 0 || categoryIndex >= segments.length - 1) return null;
92
+ const category = segments[categoryIndex] === '程序文件' ? 'procedure' : 'manual';
93
+ const file = segments.at(-1);
94
+ if (file.startsWith('~$') || !/\.(?:docx|doc|xlsx)$/i.test(file)) return null;
95
+ const text = segments.slice(categoryIndex + 1).join('/');
96
+ const family = /^(AAA|BBB|CCC|DDD)(?=$|[^A-Za-z0-9])/i.exec(file)?.[1].toUpperCase() ||
97
+ segments.slice(categoryIndex + 1, -1).find((segment) => families.some(({ code }) => code === segment.toUpperCase()))?.toUpperCase();
98
+ const format = path.extname(file).slice(1).toLowerCase();
99
+ const id = hash(category + '/' + text).slice(0, 16);
100
+ return {
101
+ id, category, family: family || null, format, filename: file, digest: hash(bytes),
102
+ sourceDepartment: category === 'procedure' ? segments[categoryIndex + 1] === file ? '未分类' : segments[categoryIndex + 1] : '',
103
+ sourceFolders: category === 'procedure' ? segments.slice(categoryIndex + 2, -1) : [],
104
+ };
105
+ }
106
+
107
+ const migrated = 'qms-files-in-knowledge-v2';
108
+ const rootFolders = { manual:['manuals','手册'], procedure:['procedures','程序文件'] };
109
+ const departments = ['制造部','市场部','研发部','综合部','质量部','采购部'];
110
+ const normalize = value => String(value || '').normalize('NFKC').replace(/\s+/g,'').toUpperCase();
111
+ const familyPrefix = /^(AAA|BBB|CCC|DDD)(?=$|[^A-Z0-9])/;
112
+ const hashBuffer = (file) => hash(fs.readFileSync(file));
113
+ const scopeMatches=(scope,actual)=>!scope || (normalize(actual) && normalize(actual).includes(normalize(scope)));
114
+
115
+ function sourceFamilies(filename, ancestry) {
116
+ for (const value of [filename,...ancestry]) {
117
+ const explicit = normalize(value).match(familyPrefix);
118
+ if (explicit) return [explicit[1]];
119
+ }
120
+ const known = families.filter(family => [filename,...ancestry].some(value => family.cert.test(normalize(value))));
121
+ return known.map(family=>family.code);
122
+ }
123
+
124
+ function titleKey(value) {
125
+ return normalize(value.replace(/\.(?:docx?|xlsx)$/i,'')).replace(/^(?:AAA|BBB|CCC|DDD)[-_-]+/,'')
126
+ .replace(/[-_((](?:REV[._-]?|V)[A-Z0-9.]+[))]?$/,'').replace(/[与及]/g,'和');
127
+ }
128
+
129
+ function checkedTemplate(item, bytes) {
130
+ if (bytes.length > 10*1024*1024 && item.format !== 'xlsx') throw new Error('Word 原件超过 10 MB');
131
+ if (item.format === 'docx') word.readTemplate(bytes);
132
+ if (item.format === 'doc' && bytes.subarray(0,8).toString('hex') !== 'd0cf11e0a1b11ae1') throw new Error('不是有效的旧版 Word 文件');
133
+ if (item.format === 'xlsx' && !office.zipRead(bytes,{entries:2000,bytes:40*1024*1024})['xl/workbook.xml']) {
134
+ throw new Error('不是有效的 Excel 工作簿');
135
+ }
136
+ }
137
+
138
+ function createTemplateLibrary(root, getKnowledge) {
139
+ function directory(knowledge,item) {
140
+ const [id,name]=rootFolders[item.category];
141
+ const branch=knowledge.ensureFolder('system',name,id);
142
+ if (item.category==='manual') return knowledge.ensureFolder(branch,'质量手册','quality-manuals');
143
+ const departmentName=item.sourceDepartment || '未分类';
144
+ const slot=departments.indexOf(departmentName);
145
+ let dest=knowledge.ensureFolder(branch,departmentName,slot>=0?'procedure-dept-'+slot:undefined);
146
+ for (const label of item.sourceFolders || []) dest=knowledge.ensureFolder(dest,label);
147
+ return dest;
148
+ }
149
+
150
+ async function migrateLegacy() {
151
+ const knowledge=getKnowledge();
152
+ if (knowledge.readMarker(migrated)) return;
153
+ let pack;
154
+ try { pack=JSON.parse(fs.readFileSync(path.join(root,'active.json'),'utf8')); }
155
+ catch (error) { if (error.code!=='ENOENT') throw error; }
156
+ if (pack) {
157
+ for (const item of pack.items) {
158
+ if (platformOriginalDigests.has(item.digest)) continue;
159
+ const dir=path.join(root,pack.id);
160
+ const original=path.join(dir,item.id+'.'+item.format);
161
+ if (hashBuffer(original)!==item.digest) throw new Error('原模板校验失败:'+item.filename);
162
+ const indexBytes=item.format==='doc' && item.workingDigest ? fs.readFileSync(path.join(dir,item.id+'.docx')) : undefined;
163
+ if (indexBytes && hash(indexBytes)!==item.workingDigest) throw new Error('旧 Word 转换副本校验失败:'+item.filename);
164
+ const {document}=await knowledge.upload(directory(knowledge,item),item.filename,fs.createReadStream(original),{
165
+ createdAt:'1970-01-01T00:00:00.000Z',indexBytes,
166
+ });
167
+ knowledge.saveLegacySource(document.id,pack.id+'/'+item.id);
168
+ }
169
+ }
170
+ knowledge.writeMarker(migrated);
171
+ }
172
+
173
+ // Older clients can still import an archive. Each file becomes a knowledge-base document.
174
+ async function install(zipBytes) {
175
+ let entries;
176
+ try {
177
+ entries=office.zipRead(zipBytes,{entries:4000,bytes:360*1024*1024,
178
+ include:name=>/\.(?:docx|doc|xlsx)$/i.test(name) && !/[/\\]~\$/.test(name)});
179
+ } catch (cause) {
180
+ throw Object.assign(new Error('无法读取 ZIP:'+cause.message),{status:400});
181
+ }
182
+ const pending=Object.entries(entries).flatMap(([name,bytes])=>{
183
+ const item=archiveEntry(name,bytes);
184
+ return item?[{item,bytes}]:[];
185
+ });
186
+ if (!pending.length) throw Object.assign(new Error('ZIP 内需有「手册」或「程序文件」目录和 Word、Excel 文件'),{status:400});
187
+ for (const {item,bytes} of pending) {
188
+ try { checkedTemplate(item,bytes); }
189
+ catch (cause) { throw Object.assign(new Error(item.filename+':'+cause.message),{status:400}); }
190
+ }
191
+ const knowledge=getKnowledge();
192
+ const {Readable}=require('node:stream');
193
+ for (const {item,bytes} of pending) await knowledge.upload(directory(knowledge,item),item.filename,Readable.from([bytes]));
194
+ return {manual:pending.filter(row=>row.item.category==='manual').length,procedure:pending.filter(row=>row.item.category==='procedure').length};
195
+ }
196
+
197
+ function candidates(type,survey) {
198
+ const {folders,files}=getKnowledge().list('company');
199
+ const map=new Map(folders.map(folder=>[folder.id,folder]));
200
+ const [branchId,branchName]=rootFolders[type];
201
+ const rows=[];
202
+ for (const file of files) {
203
+ const format=path.extname(file.name).toLowerCase().slice(1);
204
+ if (!['docx','doc','xlsx'].includes(format) || type==='manual' && format==='xlsx' || file.name.startsWith('~$')) continue;
205
+ if (!scopeMatches(file.product,survey.products) || !scopeMatches(file.process,[survey.processFlow,survey.scope].filter(Boolean).join(' '))) continue;
206
+ const ancestry=[];
207
+ let current=map.get(file.folderId);
208
+ while (current && current.parentId!=='system') {
209
+ ancestry.unshift(current.name);
210
+ current=map.get(current.parentId);
211
+ }
212
+ if (!current || current.scope!=='company' || current.id!==branchId && current.name!==branchName ||
213
+ ancestry.some(name=>/^已生成(?:质量)?(?:手册|程序文件)/.test(name))) continue;
214
+ const normalized=titleKey(file.name);
215
+ const sourceDepartment=type==='procedure' ? ancestry[0] || '未分类' : '';
216
+ rows.push({file,format, normalized, ancestry, sourceDepartment, department:department(sourceDepartment,survey),
217
+ families:sourceFamilies(file.name,ancestry)});
218
+ }
219
+ return rows;
220
+ }
221
+
222
+ function choose(rows,type,family) {
223
+ const compatible=rows.filter(item=>!item.families.length || item.families.includes(family));
224
+ const active=compatible.filter(({file})=>file.effective);
225
+ const expired=compatible.filter(({file})=>file.revisionState==='withdrawn' || file.revisionState==='released' && !file.effective &&
226
+ compatible.some(other=>other.file.supersedes===file.id && (other.file.effective || other.file.revisionState==='withdrawn')));
227
+ const prioritized=active.filter(item=>item.file.revisionState==='released' || !expired.some(old=>
228
+ old.normalized===item.normalized && old.department.name===item.department.name ||
229
+ old.file.documentNumber && old.file.documentNumber===item.file.documentNumber));
230
+ prioritized.sort((a,b)=>{
231
+ const fit=Number(b.families.includes(family))-Number(a.families.includes(family));
232
+ if (fit) return fit;
233
+ const controlled=(b.file.revisionState==='released')-(a.file.revisionState==='released');
234
+ if (controlled) return controlled;
235
+ return b.file.createdAt.localeCompare(a.file.createdAt);
236
+ });
237
+ if (type==='manual') return prioritized.slice(0,1);
238
+ const seenNames=new Set();
239
+ const seenNumbers=new Set();
240
+ return prioritized.filter(item=>{
241
+ const name=item.department.name+'\0'+item.normalized;
242
+ const number=item.file.documentNumber;
243
+ if (seenNames.has(name) || number && seenNumbers.has(number)) return false;
244
+ seenNames.add(name);
245
+ if (number) seenNumbers.add(number);
246
+ return true;
247
+ });
248
+ }
249
+
250
+ function select(type,survey,target) {
251
+ const rows=candidates(type,survey);
252
+ const supported=familiesFor(survey);
253
+ const entries = supported.map(({code,label}) => {
254
+ const company = choose(rows,type,code);
255
+ const platform = platformTemplates.filter(item => item.category===type && item.family===code);
256
+ return {code,label,company,platform};
257
+ });
258
+ const options = entries.map(({code,label,company,platform}) => ({code,label,available:company.length+platform.length>0}));
259
+ const family = target ? entries.find(item=>item.code===target) :
260
+ entries.find(item=>item.company.length) || entries.find(item=>item.platform.length);
261
+ const selected = target && !family ? [] : family?.company || choose(rows,type);
262
+ const plan=selected.map(({file,format,ancestry,sourceDepartment,department:owner})=>({
263
+ id:file.id, folderId:file.folderId, code:'T-'+hash(file.id).slice(0,16), filename:file.name, title:file.name.slice(0,-format.length-1),
264
+ digest:file.sha, format, outputFormat:format==='doc'?'docx':format, sourceDepartment, department:owner,
265
+ sourceFolders: type==='procedure'?ancestry.slice(1):[], sourcePath:['体系文件',rootFolders[type][1],...ancestry].join(' / '),
266
+ revision:file.revision, documentNumber:file.documentNumber,
267
+ }));
268
+ if (!plan.length && family) {
269
+ for (const item of family.platform) {
270
+ const {id,filename,digest,sourceDepartment,sourceFolders} = item;
271
+ plan.push({
272
+ id:'platform-'+id, folderId:null, code:'T-'+hash('platform/'+id).slice(0,16), filename,
273
+ title:filename.slice(0,-5).replace(/^(?:AAA|BBB|CCC|DDD)[-_-]+/,'').replace(/^9001(?=质量手册)/,'ISO 9001 '),
274
+ digest,format:'docx',outputFormat:'docx',platform:true,sourceDepartment,sourceFolders,
275
+ department:department(sourceDepartment,survey),sourcePath:['平台模板',rootFolders[type][1],sourceDepartment].filter(Boolean).join(' / '),
276
+ revision:'',documentNumber:'',
277
+ });
278
+ }
279
+ }
280
+ const issue=target && !family ? '目标体系不在已保存的调研中。' :
281
+ !plan.length ? '请选择受支持的体系,或在企业知识库「体系文件 / '+rootFolders[type][1]+'」上传适用文件。' : '';
282
+ plan.sort((a,b)=>a.sourceDepartment.localeCompare(b.sourceDepartment,'zh-CN') || a.filename.localeCompare(b.filename,'zh-CN') ||
283
+ a.id.localeCompare(b.id));
284
+ return {options,family: family && {code:family.code,label:family.label},issue,plan,
285
+ key:hash(JSON.stringify(plan.map(({id,digest,revision,sourcePath})=>[id,digest,revision,sourcePath])))};
286
+ }
287
+
288
+ async function read(item) {
289
+ try {
290
+ if (item.id.startsWith('platform-')) {
291
+ const template=platformById.get(item.id.slice('platform-'.length));
292
+ if (!template || template.digest!==item.digest) throw new Error('平台模板版本已变更,请重新生成');
293
+ const bytes=fs.readFileSync(path.join(platformRoot,template.id+'.docx'));
294
+ if (hash(bytes)!==item.digest) throw new Error('平台模板校验失败,请重新安装插件');
295
+ checkedTemplate(item,bytes);
296
+ return bytes;
297
+ }
298
+ const original=getKnowledge().document(item.id);
299
+ const maxSize=(item.format==='xlsx'?48:10)*1024*1024;
300
+ if (original.size>maxSize) throw new Error('原件超过 '+maxSize/(1024*1024)+' MB');
301
+ const bytes=fs.readFileSync(original.filename);
302
+ if (hash(bytes)!==item.digest) throw new Error('文件内容已变更,请重新生成。');
303
+ checkedTemplate(item,bytes);
304
+ if (item.format!=='doc') return bytes;
305
+ const work=fs.mkdtempSync(path.join(os.tmpdir(),'qip-kb-word-'));
306
+ try {
307
+ const legacy={id:'source',filename:item.filename};
308
+ fs.writeFileSync(path.join(work,'source.doc'),bytes);
309
+ await convertLegacy(work,[{item:legacy}]);
310
+ return fs.readFileSync(path.join(work,'source.docx'));
311
+ } finally { fs.rmSync(work,{recursive:true,force:true}); }
312
+ } catch (cause) {
313
+ throw Object.assign(new Error(item.filename+':'+cause.message),{status:422});
314
+ }
315
+ }
316
+
317
+ function mapDepartments(survey) {
318
+ const names=['综合部','研发部','技术部','采购部','市场部','财务部','制造部','生产部','质量部'];
319
+ return Object.fromEntries(names.map(name=>[name,department(name,survey).name]));
320
+ }
321
+
322
+ function findSupporting(titles,survey,family) {
323
+ const knowledge=getKnowledge();
324
+ const {folders,files}=knowledge.list('company');
325
+ const directories=new Map(folders.map(folder=>[folder.id,folder]));
326
+ const wanted=new Set(titles.map(referenceKey));
327
+ const found=new Map();
328
+ let budget=40*1024*1024;
329
+ const priority=files.filter(file=>file.effective).sort((a,b)=>
330
+ Number(b.revisionState==='released')-Number(a.revisionState==='released'));
331
+ for (const file of priority) {
332
+ const key=referenceKey(file.name.replace(/\.(?:docx?|pdf|xlsx?|txt)$/i,''));
333
+ if (!wanted.has(key) || found.has(key) || file.size>budget || file.size>12*1024*1024 ||
334
+ !/\.(?:docx?|pdf|xlsx?|txt)$/i.test(file.name) || !scopeMatches(file.product,survey.products) ||
335
+ !scopeMatches(file.process,[survey.processFlow,survey.scope].filter(Boolean).join(' '))) continue;
336
+ const ancestry=[];
337
+ let directory=directories.get(file.folderId);
338
+ while (directory && directory.id!=='system') {
339
+ ancestry.unshift(directory.name);
340
+ directory=directories.get(directory.parentId);
341
+ }
342
+ const familyCodes=sourceFamilies(file.name,ancestry);
343
+ if (!directory || ancestry.some(name=>/^已生成/.test(name)) || familyCodes.length && !familyCodes.includes(family)) continue;
344
+ try {
345
+ const bytes=fs.readFileSync(knowledge.document(file.id).filename);
346
+ if (bytes.length!==file.size || hash(bytes)!==file.sha) continue;
347
+ found.set(key,{id:file.id,name:file.name,revision:file.revision,path:['体系文件',...ancestry].join(' / '),bytes});
348
+ budget-=bytes.length;
349
+ } catch (error) {
350
+ if (error.code!=='ENOENT' && error.status!==404) throw error;
351
+ }
352
+ }
353
+ return found;
354
+ }
355
+
356
+ return {select,install,migrateLegacy,read,mapDepartments,findSupporting};
357
+ }
358
+
359
+ module.exports = { createTemplateLibrary, maxPackBytes, platformOriginalDigests, knowledgeMigrationMarker:migrated };