plugin-document-understanding 1.1.16 → 2.0.0

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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -25
  3. package/dist/client/169.6888909107c553c3.js +10 -0
  4. package/dist/client/379.e29f5ced467ce23d.js +10 -0
  5. package/dist/client/867.3ed3b814115181ca.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
  8. package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
  9. package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/externalVersion.js +9 -7
  12. package/dist/locale/en-US.json +126 -0
  13. package/dist/locale/vi-VN.json +130 -2
  14. package/dist/locale/zh-CN.json +127 -1
  15. package/dist/node_modules/form-data/package.json +1 -1
  16. package/dist/node_modules/mime-types/package.json +1 -1
  17. package/dist/server/actions.js +211 -11
  18. package/dist/server/collections/api-keys.js +55 -0
  19. package/dist/server/collections/artifacts.js +59 -0
  20. package/dist/server/collections/config.js +9 -3
  21. package/dist/server/collections/endpoints.js +3 -0
  22. package/dist/server/collections/jobs.js +7 -4
  23. package/dist/server/collections/operations.js +76 -0
  24. package/dist/server/contracts/du-contracts.js +828 -0
  25. package/dist/server/dugate-seed.js +98 -340
  26. package/dist/server/plugin.js +49 -7
  27. package/dist/server/routes/du-gateway-router.js +443 -0
  28. package/dist/server/services/ArtifactStorageService.js +459 -0
  29. package/dist/server/services/AsyncJobManager.js +1 -1
  30. package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
  31. package/dist/server/services/DocumentUnderstandingService.js +151 -25
  32. package/dist/server/services/ExternalDuReworkClient.js +210 -0
  33. package/dist/server/services/OperationOrchestrator.js +1087 -0
  34. package/dist/server/services/PipelineExecutor.js +164 -43
  35. package/dist/server/tools/document-understanding-tool.js +49 -24
  36. package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
  37. package/package.json +8 -4
  38. package/src/client/index.tsx +11 -0
  39. package/src/client-v2/components/ApiKeysTab.tsx +198 -0
  40. package/src/client-v2/components/EndpointsTab.tsx +39 -2
  41. package/src/client-v2/components/JobsTab.tsx +136 -21
  42. package/src/client-v2/components/OperationsTab.tsx +586 -0
  43. package/src/client-v2/components/PluginSettings.tsx +12 -0
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +4 -0
  46. package/src/client-v2/locale.ts +1 -8
  47. package/src/client-v2/models/index.ts +1 -8
  48. package/src/client-v2/plugin.tsx +12 -8
  49. package/src/client-v2/types.ts +13 -1
  50. package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
  51. package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
  52. package/src/locale/en-US.json +126 -0
  53. package/src/locale/vi-VN.json +130 -2
  54. package/src/locale/zh-CN.json +127 -1
  55. package/src/server/__tests__/actions.test.ts +1 -8
  56. package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
  57. package/src/server/__tests__/dugate-integration.test.ts +79 -42
  58. package/src/server/__tests__/smoke.test.ts +1 -8
  59. package/src/server/__tests__/upload-security.test.ts +1 -8
  60. package/src/server/actions.ts +252 -36
  61. package/src/server/collections/api-keys.ts +35 -0
  62. package/src/server/collections/artifacts.ts +39 -0
  63. package/src/server/collections/config.ts +18 -2
  64. package/src/server/collections/endpoints.ts +12 -0
  65. package/src/server/collections/jobs.ts +16 -4
  66. package/src/server/collections/operations.ts +56 -0
  67. package/src/server/contracts/du-contracts.ts +1026 -0
  68. package/src/server/dugate-seed.ts +126 -453
  69. package/src/server/plugin.ts +64 -14
  70. package/src/server/routes/du-gateway-router.ts +465 -0
  71. package/src/server/services/ArtifactStorageService.ts +596 -0
  72. package/src/server/services/AsyncJobManager.ts +10 -1
  73. package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
  74. package/src/server/services/DocumentUnderstandingService.ts +186 -44
  75. package/src/server/services/ExternalDuReworkClient.ts +222 -0
  76. package/src/server/services/OperationOrchestrator.ts +1359 -0
  77. package/src/server/services/PipelineExecutor.ts +245 -108
  78. package/src/server/tools/document-understanding-tool.ts +63 -45
  79. package/src/server/types.ts +101 -16
  80. package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
  81. package/dist/client/345.277fbb2b97424db5.js +0 -10
  82. package/dist/client-v2/345.2fa9834b46dd4531.js +0 -10
@@ -0,0 +1,462 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import * as crypto from 'crypto';
4
+ import { mkdirSync, rmSync, writeFileSync } from 'fs';
5
+ import { resolve } from 'path';
6
+ import { createMockServer, type MockServer } from '@nocobase/test';
7
+ import { JOB_STATUS } from '@nocobase/plugin-workflow';
8
+ import PluginDocumentUnderstandingServer from '../plugin';
9
+ import { DocumentUnderstandingWorkflowInstruction } from '../workflow/DocumentUnderstandingInstruction';
10
+
11
+ describe('Document Understanding du-rework Public Gateway & Built-in Business Engine', () => {
12
+ let app: MockServer;
13
+ let adminAgent: ReturnType<MockServer['agent']>;
14
+ let anonAgent: ReturnType<MockServer['agent']>;
15
+ let plugin: PluginDocumentUnderstandingServer;
16
+ const mockLlmInvoke = vi.fn();
17
+
18
+ beforeAll(async () => {
19
+ app = await createMockServer({
20
+ plugins: [
21
+ 'field-sort',
22
+ 'system-settings',
23
+ 'users',
24
+ 'auth',
25
+ 'acl',
26
+ 'data-source-manager',
27
+ 'data-source-main',
28
+ 'error-handler',
29
+ ],
30
+ acl: false,
31
+ });
32
+
33
+ // Attach mock @nocobase/plugin-ai aiManager to verify built-in AI & usage tracking
34
+ (app as unknown as Record<string, unknown>).aiManager = {
35
+ resolveModel: vi.fn().mockResolvedValue({ llmService: 'mock-openai', model: 'gpt-4o-mini' }),
36
+ listAllEnabledModels: vi.fn().mockResolvedValue([
37
+ {
38
+ llmService: 'mock-openai',
39
+ llmServiceTitle: 'Mock OpenAI',
40
+ provider: 'openai',
41
+ enabledModels: [{ label: 'gpt-4o-mini', value: 'gpt-4o-mini' }],
42
+ },
43
+ ]),
44
+ getLLMService: vi.fn().mockResolvedValue({
45
+ model: 'gpt-4o-mini',
46
+ provider: {
47
+ invoke: (...args: unknown[]) => mockLlmInvoke(...args),
48
+ },
49
+ }),
50
+ };
51
+
52
+ plugin = new PluginDocumentUnderstandingServer(app, { name: 'plugin-document-understanding' });
53
+ await plugin.beforeLoad();
54
+ await plugin.load();
55
+ await app.db.sync();
56
+ await plugin.afterStart();
57
+
58
+ const adminUser = await app.db.getRepository('users').findOne();
59
+ adminAgent = app.agent();
60
+ anonAgent = app.agent();
61
+ if (adminUser) {
62
+ await adminAgent.login(adminUser);
63
+ }
64
+ }, 120_000);
65
+
66
+ afterAll(async () => {
67
+ await plugin?.beforeStop();
68
+ await app?.destroy();
69
+ });
70
+
71
+ beforeEach(() => {
72
+ mockLlmInvoke.mockReset();
73
+ });
74
+
75
+ it('exposes /api/du/v1/health and enforces fail-closed authentication on protected gateway routes', async () => {
76
+ const healthRes = await anonAgent.get('/api/du/v1/health');
77
+ expect(healthRes.status).toBe(200);
78
+ expect(healthRes.body.status).toBe('ok');
79
+ expect(healthRes.body.businesses).toHaveLength(3);
80
+
81
+ const unauthRes = await anonAgent.post('/api/du/v1/uploads').send({
82
+ fileName: 'test.txt',
83
+ sizeBytes: 4,
84
+ });
85
+ expect(unauthRes.status).toBe(401);
86
+ expect(unauthRes.headers['content-type']).toContain('application/problem+json');
87
+ expect(unauthRes.body.code).toBe('UNAUTHENTICATED');
88
+ });
89
+
90
+ it('issues scoped x-api-key credentials, enforces business ACL (403), and isolates tenants with 404', async () => {
91
+ const keyARes = await adminAgent.resource('docUnderstanding').issueApiKey({
92
+ values: {
93
+ name: 'Tenant A Key',
94
+ tenantId: 'tenant-a',
95
+ allowedBusinesses: ['document-core'],
96
+ allowedActions: ['*'],
97
+ },
98
+ });
99
+ expect(keyARes.status).toBe(200);
100
+ const tenantAKey: string = keyARes.body.data.rawKey;
101
+ expect(tenantAKey.startsWith('du_live_')).toBe(true);
102
+
103
+ const keyBRes = await adminAgent.resource('docUnderstanding').issueApiKey({
104
+ values: {
105
+ name: 'Tenant B Key',
106
+ tenantId: 'tenant-b',
107
+ allowedBusinesses: ['document-core'],
108
+ },
109
+ });
110
+ const tenantBKey: string = keyBRes.body.data.rawKey;
111
+
112
+ // Tenant A cannot call lc-checker (403 PERMISSION_DENIED)
113
+ const deniedBiz = await anonAgent
114
+ .post('/api/du/v1/businesses/lc-checker/actions/lc-checker')
115
+ .set('x-api-key', tenantAKey)
116
+ .send({ input: {} });
117
+ expect(deniedBiz.status).toBe(403);
118
+ expect(deniedBiz.body.code).toBe('PERMISSION_DENIED');
119
+
120
+ // Tenant A creates an upload; Tenant B probing Tenant A's artifactId gets 404 NOT_FOUND
121
+ const uploadInit = await anonAgent
122
+ .post('/api/du/v1/uploads')
123
+ .set('x-api-key', tenantAKey)
124
+ .set('Idempotency-Key', 'idem-upload-tenant-a-1')
125
+ .send({
126
+ fileName: 'secret-a.txt',
127
+ mimeType: 'text/plain',
128
+ sizeBytes: 11,
129
+ });
130
+ expect(uploadInit.status).toBe(201);
131
+ const artifactId: string = uploadInit.body.artifactId;
132
+
133
+ // Idempotent replay with same metadata returns 200 replayed: true
134
+ const replayInit = await anonAgent
135
+ .post('/api/du/v1/uploads')
136
+ .set('x-api-key', tenantAKey)
137
+ .set('Idempotency-Key', 'idem-upload-tenant-a-1')
138
+ .send({
139
+ fileName: 'secret-a.txt',
140
+ mimeType: 'text/plain',
141
+ sizeBytes: 11,
142
+ });
143
+ expect(replayInit.status).toBe(200);
144
+ expect(replayInit.body.replayed).toBe(true);
145
+ expect(replayInit.body.artifactId).toBe(artifactId);
146
+
147
+ // Tenant B attempting to upload or download Tenant A's artifact gets 404
148
+ const crossTenantDownload = await anonAgent
149
+ .get(`/api/du/v1/artifacts/${artifactId}/download`)
150
+ .set('x-api-key', tenantBKey);
151
+ expect(crossTenantDownload.status).toBe(404);
152
+ expect(crossTenantDownload.body.code).toBe('NOT_FOUND');
153
+
154
+ // Revoking Tenant B key immediately blocks access with 401
155
+ await adminAgent.resource('docUnderstanding').revokeApiKey({ filterByTk: keyBRes.body.data.id });
156
+ const afterRevoke = await anonAgent.get('/api/du/v1/operations').set('x-api-key', tenantBKey);
157
+ expect(afterRevoke.status).toBe(401);
158
+ });
159
+
160
+ it('executes 2-step upload with SHA-256 check, DI-06 page selection, ingest:split, redact, and diff', async () => {
161
+ const keyRes = await adminAgent.resource('docUnderstanding').issueApiKey({
162
+ values: { name: 'Core Client', tenantId: 'tenant-core' },
163
+ });
164
+ const apiKey: string = keyRes.body.data.rawKey;
165
+
166
+ const multiPageContent = Buffer.from('Page One Header\fPage Two Contract Body\fPage Three Appendix', 'utf8');
167
+ const sha256 = crypto.createHash('sha256').update(multiPageContent).digest('hex');
168
+
169
+ const initRes = await anonAgent
170
+ .post('/api/v1/uploads')
171
+ .set('x-api-key', apiKey)
172
+ .send({ fileName: 'contract.txt', mimeType: 'text/plain', sizeBytes: multiPageContent.length });
173
+ expect(initRes.status).toBe(201);
174
+ const artId: string = initRes.body.artifactId;
175
+
176
+ // Bad SHA-256 is rejected with 422 CHECKSUM_MISMATCH
177
+ const badPut = await anonAgent
178
+ .put(`/api/v1/uploads/${artId}/content`)
179
+ .set('x-api-key', apiKey)
180
+ .set('Content-Type', 'text/plain')
181
+ .set('x-content-sha256', '0'.repeat(64))
182
+ .send(multiPageContent);
183
+ expect(badPut.status).toBe(422);
184
+ expect(badPut.body.code).toBe('CHECKSUM_MISMATCH');
185
+
186
+ // Valid SHA-256 transitions artifact to READY
187
+ const okPut = await anonAgent
188
+ .put(`/api/v1/uploads/${artId}/content`)
189
+ .set('x-api-key', apiKey)
190
+ .set('Content-Type', 'text/plain')
191
+ .set('x-content-sha256', sha256)
192
+ .send(multiPageContent);
193
+ expect(okPut.status).toBe(201);
194
+ expect(okPut.body.state).toBe('READY');
195
+
196
+ // Submit ingest:parse with DI-06 documentSelection for pages 1-2 only
197
+ const submitRes = await anonAgent
198
+ .post('/api/v1/businesses/document-core/actions/ingest')
199
+ .set('x-api-key', apiKey)
200
+ .set('Idempotency-Key', 'op-ingest-pages-1-2')
201
+ .send({
202
+ input: { mode: 'parse', outputFormat: 'md' },
203
+ artifacts: [{ artifactId: artId, role: 'input' }],
204
+ documentSelection: {
205
+ kind: 'requestSelection',
206
+ schemaVersion: 1,
207
+ mode: 'combined',
208
+ artifactIds: [artId],
209
+ pageSelections: [
210
+ {
211
+ artifactId: artId,
212
+ selection: { kind: 'ranges', ranges: [{ from: 1, to: 2 }] },
213
+ },
214
+ ],
215
+ },
216
+ });
217
+ expect(submitRes.status).toBe(202);
218
+ const opId: string = submitRes.body.operationId;
219
+
220
+ // Reusing Idempotency-Key with a DIFFERENT body returns 409 IDEMPOTENCY_CONFLICT
221
+ const conflictRes = await anonAgent
222
+ .post('/api/v1/businesses/document-core/actions/ingest')
223
+ .set('x-api-key', apiKey)
224
+ .set('Idempotency-Key', 'op-ingest-pages-1-2')
225
+ .send({
226
+ input: { mode: 'ocr' },
227
+ artifacts: [{ artifactId: artId, role: 'input' }],
228
+ });
229
+ expect(conflictRes.status).toBe(409);
230
+ expect(conflictRes.body.code).toBe('IDEMPOTENCY_CONFLICT');
231
+
232
+ // Wait for completion via ?wait=5
233
+ const opView = await anonAgent.get(`/api/v1/operations/${opId}?wait=5`).set('x-api-key', apiKey);
234
+ expect(opView.status).toBe(200);
235
+ expect(opView.body.state).toBe('SUCCEEDED');
236
+ expect(opView.body.documentInputCoverage.status).toBe('complete');
237
+
238
+ // Fetch ResultEnvelope & download output JSON artifact
239
+ const resultEnv = await anonAgent.get(`/api/v1/operations/${opId}/result`).set('x-api-key', apiKey);
240
+ expect(resultEnv.status).toBe(200);
241
+ expect(resultEnv.body.schemaVersion).toBe('1');
242
+ const resultRef: string = resultEnv.body.data.resultRef;
243
+ expect(resultRef.startsWith('artifact://')).toBe(true);
244
+
245
+ const outArtifactId = resultRef.slice('artifact://'.length);
246
+ const downloaded = await anonAgent.get(`/api/v1/artifacts/${outArtifactId}/download`).set('x-api-key', apiKey);
247
+ expect(downloaded.status).toBe(200);
248
+ expect(downloaded.body.version).toBe('document-core-result-v1');
249
+ expect(downloaded.body.text).toContain('Page One Header');
250
+ expect(downloaded.body.text).toContain('Page Two Contract Body');
251
+ expect(downloaded.body.text).not.toContain('Page Three Appendix');
252
+
253
+ // Test ingest:split creating multiple output artifacts
254
+ const splitSubmit = await anonAgent
255
+ .post('/api/v1/businesses/document-core/actions/ingest?sync=true')
256
+ .set('x-api-key', apiKey)
257
+ .send({
258
+ input: { mode: 'split', pages: '1-1,2-3' },
259
+ artifacts: [{ artifactId: artId, role: 'input' }],
260
+ });
261
+ expect(splitSubmit.status).toBe(202);
262
+ const splitEnv = await anonAgent
263
+ .get(`/api/v1/operations/${splitSubmit.body.operationId}/result`)
264
+ .set('x-api-key', apiKey);
265
+ expect(splitEnv.body.artifacts.filter((a: { role: string }) => a.role === 'output')).toHaveLength(3);
266
+
267
+ // Test transform:redact PII masking
268
+ const redactSubmit = await anonAgent
269
+ .post('/api/v1/businesses/document-core/actions/transform?sync=true')
270
+ .set('x-api-key', apiKey)
271
+ .send({
272
+ input: {
273
+ variant: 'redact',
274
+ text: 'Khách hàng Nguyễn Văn A, CCCD 001090012345, SĐT 0912345678.',
275
+ redactPatterns: ['CCCD', 'PHONE_NUMBER'],
276
+ },
277
+ });
278
+ const redactEnv = await anonAgent
279
+ .get(`/api/v1/operations/${redactSubmit.body.operationId}/result`)
280
+ .set('x-api-key', apiKey);
281
+ const redactOutId = String(redactEnv.body.data.resultRef).slice('artifact://'.length);
282
+ const redactPayload = await anonAgent.get(`/api/v1/artifacts/${redactOutId}/download`).set('x-api-key', apiKey);
283
+ expect(redactPayload.body.data.transformedText).toBe('Khách hàng Nguyễn Văn A, CCCD [REDACTED], SĐT [REDACTED].');
284
+ });
285
+
286
+ it('handles disbursement HITL WAITING_INPUT -> CAS resume and lc-checker UCP 600 safety invariants', async () => {
287
+ const keyRes = await adminAgent.resource('docUnderstanding').issueApiKey({
288
+ values: { name: 'Bank Trade & Credit', tenantId: 'tenant-bank' },
289
+ });
290
+ const apiKey: string = keyRes.body.data.rawKey;
291
+
292
+ // Upload sample document
293
+ const docBuf = Buffer.from('Khế ước nhận nợ số tiền 2.000.000.000 VND, TK thụ hưởng 19034567890012.', 'utf8');
294
+ const init = await anonAgent
295
+ .post('/api/du/v1/uploads')
296
+ .set('x-api-key', apiKey)
297
+ .send({ fileName: 'khe-uoc.txt', mimeType: 'text/plain', sizeBytes: docBuf.length });
298
+ await anonAgent
299
+ .put(`/api/du/v1/uploads/${init.body.artifactId}/content`)
300
+ .set('x-api-key', apiKey)
301
+ .set('Content-Type', 'text/plain')
302
+ .send(docBuf);
303
+
304
+ // 1. Disbursement with requireApproval: true -> WAITING_INPUT -> CAS resume -> SUCCEEDED
305
+ mockLlmInvoke
306
+ .mockResolvedValueOnce({
307
+ content: JSON.stringify({
308
+ docType: 'promissory_note',
309
+ extracted: { loanAmount: 2000000000, beneficiaryAccount: '19034567890012' },
310
+ }),
311
+ usage_metadata: { input_tokens: 120, output_tokens: 45 },
312
+ })
313
+ .mockResolvedValueOnce({
314
+ content: JSON.stringify({
315
+ findings: [{ key: 'loanAmount', status: 'match', detail: 'Khớp 2 tỷ VND' }],
316
+ report: '# BÁO CÁO ĐỐI CHIẾU HỒ SƠ GIẢI NGÂN',
317
+ }),
318
+ usage_metadata: { input_tokens: 200, output_tokens: 80 },
319
+ });
320
+
321
+ const disbSubmit = await anonAgent
322
+ .post('/api/du/v1/businesses/document-core/actions/disbursement')
323
+ .set('x-api-key', apiKey)
324
+ .send({
325
+ input: {
326
+ requireApproval: true,
327
+ referenceData: [{ key: 'loanAmount', expected: 2000000000 }],
328
+ },
329
+ artifacts: [{ artifactId: init.body.artifactId, role: 'input' }],
330
+ });
331
+ const disbOpId: string = disbSubmit.body.operationId;
332
+
333
+ const pausedView = await anonAgent.get(`/api/du/v1/operations/${disbOpId}?wait=5`).set('x-api-key', apiKey);
334
+ expect(pausedView.body.state).toBe('WAITING_INPUT');
335
+ expect(pausedView.body.wait.waitId).toBe('approval-wait');
336
+
337
+ // Wrong expectedStateVersion is rejected with 409 STATE_CONFLICT
338
+ const badResume = await anonAgent
339
+ .post(`/api/du/v1/operations/${disbOpId}/resume`)
340
+ .set('x-api-key', apiKey)
341
+ .send({
342
+ waitId: 'approval-wait',
343
+ expectedStateVersion: 999,
344
+ input: { approved: true },
345
+ });
346
+ expect(badResume.status).toBe(409);
347
+
348
+ // Valid CAS resume completes the workflow
349
+ const okResume = await anonAgent
350
+ .post(`/api/du/v1/operations/${disbOpId}/resume`)
351
+ .set('x-api-key', apiKey)
352
+ .send({
353
+ waitId: 'approval-wait',
354
+ expectedStateVersion: pausedView.body.stateVersion,
355
+ input: { approved: true, approver: 'checker@bank.vn', note: 'Đồng ý' },
356
+ });
357
+ expect(okResume.status).toBe(202);
358
+
359
+ const doneView = await anonAgent.get(`/api/du/v1/operations/${disbOpId}?wait=5`).set('x-api-key', apiKey);
360
+ expect(doneView.body.state).toBe('SUCCEEDED');
361
+
362
+ // 2. lc-checker: refuses COMPLIANT when outstandingVisualChecks remain & normalizes unregistered ruleId
363
+ mockLlmInvoke
364
+ .mockResolvedValueOnce({
365
+ content: JSON.stringify({
366
+ documentsPresent: ['MT700', 'BILL_OF_LADING'],
367
+ documentsMissing: [],
368
+ // Requests visual check on non-signed text -> will produce an outstandingVisualCheck!
369
+ visualRequests: [
370
+ { document: 'khe-uoc.txt', check: 'Verify manual carrier endorsement', ruleId: 'UCP600-ART20-A-I' },
371
+ ],
372
+ }),
373
+ usage_metadata: { input_tokens: 300, output_tokens: 90 },
374
+ })
375
+ .mockResolvedValueOnce({
376
+ content: JSON.stringify({
377
+ // Model tries to say COMPLIANT and invents a fake rule ID — engine must guard both!
378
+ verdict: 'COMPLIANT',
379
+ discrepancies: [
380
+ {
381
+ id: 'DISC-01',
382
+ severity: 'MINOR',
383
+ document: 'khe-uoc.txt',
384
+ field: 'Endorsement',
385
+ issue: 'Cần kiểm tra ký hậu',
386
+ ruleId: 'FAKE-NONEXISTENT-RULE',
387
+ },
388
+ ],
389
+ summary: 'Kiểm tra sơ bộ.',
390
+ report: '# BÁO CÁO L/C',
391
+ }),
392
+ usage_metadata: { input_tokens: 400, output_tokens: 110 },
393
+ });
394
+
395
+ const lcSubmit = await anonAgent
396
+ .post('/api/du/v1/businesses/lc-checker/actions/lc-checker?sync=true')
397
+ .set('x-api-key', apiKey)
398
+ .send({
399
+ input: { ruleSetVersion: 'ucp600-isbp821-v1' },
400
+ artifacts: [{ artifactId: init.body.artifactId, role: 'input' }],
401
+ });
402
+ const lcEnv = await anonAgent
403
+ .get(`/api/du/v1/operations/${lcSubmit.body.operationId}/result`)
404
+ .set('x-api-key', apiKey);
405
+ const lcOutId = String(lcEnv.body.data.resultRef).slice('artifact://'.length);
406
+ const lcPayload = await anonAgent.get(`/api/du/v1/artifacts/${lcOutId}/download`).set('x-api-key', apiKey);
407
+
408
+ expect(lcPayload.body.resultVersion).toBe('lc-checker-result-v1');
409
+ expect(lcPayload.body.verdict).toBe('DISCREPANT');
410
+ expect(lcPayload.body.humanSignOffRequired).toBe(true);
411
+ expect(lcPayload.body.outstandingVisualChecks.length).toBeGreaterThan(0);
412
+ expect(lcPayload.body.discrepancies[0].ruleId).toBe('UCP600-ART14-A');
413
+
414
+ // Usage summary reflects token consumption
415
+ const now = new Date();
416
+ const from = new Date(now.getTime() - 3600_000).toISOString();
417
+ const to = new Date(now.getTime() + 3600_000).toISOString();
418
+ const usageRes = await anonAgent
419
+ .get(`/api/du/v1/usage/summary?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`)
420
+ .set('x-api-key', apiKey);
421
+ expect(usageRes.status).toBe(200);
422
+ expect(usageRes.body.totalOperations).toBeGreaterThanOrEqual(2);
423
+ expect(usageRes.body.inputTokens).toBeGreaterThan(0);
424
+ });
425
+
426
+ it('executes the NocoBase workflow instruction node and returns structured variables', async () => {
427
+ const sampleDir = resolve(process.cwd(), 'storage', 'uploads', 'du-wf-test');
428
+ const sampleFile = resolve(sampleDir, 'memo.txt');
429
+ mkdirSync(sampleDir, { recursive: true });
430
+ writeFileSync(sampleFile, 'Hồ sơ của khách hàng SĐT 0987654321 và CCCD 012345678901.');
431
+
432
+ try {
433
+ const instruction = new DocumentUnderstandingWorkflowInstruction({ app } as never);
434
+ const node = {
435
+ id: 101,
436
+ key: 'du_node_1',
437
+ config: {
438
+ mode: 'business_action',
439
+ businessId: 'document-core',
440
+ action: 'transform',
441
+ variant: 'redact',
442
+ files: 'uploads/du-wf-test/memo.txt',
443
+ inputJson: { redactPatterns: ['CCCD', 'PHONE_NUMBER'] },
444
+ },
445
+ };
446
+ const processor = {
447
+ getParsedValue: (v: unknown) => v,
448
+ isInstructionSync: () => true,
449
+ };
450
+
451
+ const jobResult = await instruction.run(node as never, null as never, processor as never);
452
+ expect(jobResult?.status).toBe(JOB_STATUS.RESOLVED);
453
+ const resultObj = jobResult?.result as Record<string, unknown>;
454
+ expect(resultObj.state).toBe('SUCCEEDED');
455
+ expect((resultObj.data as Record<string, unknown>).transformedText).toBe(
456
+ 'Hồ sơ của khách hàng SĐT [REDACTED] và CCCD [REDACTED].',
457
+ );
458
+ } finally {
459
+ rmSync(sampleDir, { recursive: true, force: true });
460
+ }
461
+ });
462
+ });
@@ -1,7 +1,9 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { PipelineExecutor } from '../services/PipelineExecutor';
2
4
  import { ExternalApiClient } from '../services/ExternalApiClient';
3
5
  import { seedDugateEndpoints } from '../dugate-seed';
4
- import { EndpointDef, PipelineDef, PipelineStepDef, JobState } from '../types';
6
+ import { EndpointDef, PipelineDef, PipelineStepDef } from '../types';
5
7
 
6
8
  function endpoint(overrides: Partial<EndpointDef> = {}): EndpointDef {
7
9
  return {
@@ -13,6 +15,7 @@ function endpoint(overrides: Partial<EndpointDef> = {}): EndpointDef {
13
15
  fileFieldName: 'files[]',
14
16
  maxFiles: 1,
15
17
  executionMode: 'sync',
18
+ protocolMode: 'legacy_rest',
16
19
  discriminatorField: 'mode',
17
20
  discriminatorValue: 'parse',
18
21
  syncQueryParam: 'sync',
@@ -44,7 +47,7 @@ function pipelineWithStep(stepEndpoint: EndpointDef): PipelineDef {
44
47
  return { id: 1, name: 'dugate-pipeline', enabled: true, steps: [step] };
45
48
  }
46
49
 
47
- describe('DUGate sync-202 fallback', () => {
50
+ describe('Legacy DUGate sync-202 fallback compatibility', () => {
48
51
  it('starts polling when a sync request returns 202 with an operation id', async () => {
49
52
  const jobsRepo = {
50
53
  create: vi.fn().mockResolvedValue({ id: 42, externalTaskIds: {} }),
@@ -61,14 +64,13 @@ describe('DUGate sync-202 fallback', () => {
61
64
  data: { name: 'operations/op_123', done: false, metadata: { state: 'RUNNING' } },
62
65
  }),
63
66
  } as unknown as ExternalApiClient;
64
- const jobManager = { startPolling: vi.fn().mockResolvedValue(undefined) } as any;
65
- const executor = new PipelineExecutor(db as never, apiClient, jobManager, { error: vi.fn() }, 'node-a');
67
+ const jobManager = { startPolling: vi.fn().mockResolvedValue(undefined) };
68
+ const executor = new PipelineExecutor(db as never, apiClient, jobManager as never, { error: vi.fn() }, 'node-a');
66
69
 
67
70
  const job = await executor.execute(1, { file_url: 'uploads/du-test/sample.txt' });
68
71
  expect(job.id).toBe(42);
69
72
  await vi.waitFor(() => expect(jobManager.startPolling).toHaveBeenCalled());
70
73
 
71
- // Polling started with the extracted operation id
72
74
  expect(jobManager.startPolling).toHaveBeenCalledWith(
73
75
  42,
74
76
  expect.objectContaining({ name: 'dugate-test' }),
@@ -100,8 +102,8 @@ describe('DUGate sync-202 fallback', () => {
100
102
  data: { done: true, result: { content: 'parsed', extracted_data: null } },
101
103
  }),
102
104
  } as unknown as ExternalApiClient;
103
- const jobManager = { startPolling: vi.fn() } as any;
104
- const executor = new PipelineExecutor(db as never, apiClient, jobManager, { error: vi.fn() }, 'node-a');
105
+ const jobManager = { startPolling: vi.fn() };
106
+ const executor = new PipelineExecutor(db as never, apiClient, jobManager as never, { error: vi.fn() }, 'node-a');
105
107
 
106
108
  await executor.execute(1, { file_url: 'uploads/du-test/sample.txt' });
107
109
  await vi.waitFor(() => expect(apiClient.call).toHaveBeenCalled());
@@ -126,13 +128,7 @@ describe('DUGate sync-202 fallback', () => {
126
128
  pollInterval: 1000,
127
129
  pollTimeout: 5000,
128
130
  });
129
- const requestSpy = vi
130
- .spyOn(client as any, 'client')
131
- .mockReturnValue({ request: vi.fn().mockResolvedValue({ status: 200, data: { ok: true }, headers: {} }) });
132
-
133
- // The discriminator merge happens before axios sends the request, so mock
134
- // the axios adapter and assert on what would be sent.
135
- const http = (client as any).client;
131
+ const http = (client as unknown as { client: { request: ReturnType<typeof vi.fn> } }).client;
136
132
  http.request = vi.fn().mockResolvedValue({ status: 200, data: { ok: true }, headers: {} });
137
133
 
138
134
  await client.call({
@@ -147,29 +143,39 @@ describe('DUGate sync-202 fallback', () => {
147
143
  });
148
144
  });
149
145
 
150
- describe('DUGate seed data', () => {
151
- function makeRepo() {
152
- const store: any[] = [];
146
+ describe('Canonical du-rework catalog seed & automatic legacy migration', () => {
147
+ interface MockRecord {
148
+ id: number;
149
+ name?: string;
150
+ pipelineId?: number;
151
+ [key: string]: unknown;
152
+ }
153
+
154
+ function makeRepo(initial: MockRecord[] = []) {
155
+ const store: MockRecord[] = [...initial];
153
156
  return {
154
157
  store,
155
- findOne: vi.fn(async ({ filter }: any) => store.find((r) => r.name === filter?.name) ?? null),
156
- create: vi.fn(async ({ values }: any) => {
157
- const record = { id: store.length + 1, ...values };
158
+ findOne: vi.fn(
159
+ async ({ filter }: { filter?: { name?: string } }) => store.find((r) => r.name === filter?.name) ?? null,
160
+ ),
161
+ create: vi.fn(async ({ values }: { values: Record<string, unknown> }) => {
162
+ const record: MockRecord = { id: store.length + 1, ...values };
158
163
  store.push(record);
159
164
  return record;
160
165
  }),
161
- update: vi.fn(async ({ filterByTk, values }: any) => {
166
+ update: vi.fn(async ({ filterByTk, values }: { filterByTk: number; values: Record<string, unknown> }) => {
162
167
  const rec = store.find((r) => r.id === filterByTk);
163
168
  if (rec) Object.assign(rec, values);
164
169
  }),
165
- destroy: vi.fn(async ({ filter }: any) => {
166
- const idx = store.findIndex((r) => r.pipelineId === filter?.pipelineId);
167
- if (idx >= 0) store.splice(idx, 1);
170
+ destroy: vi.fn(async ({ filter }: { filter?: { pipelineId?: number } }) => {
171
+ for (let i = store.length - 1; i >= 0; i -= 1) {
172
+ if (store[i].pipelineId === filter?.pipelineId) store.splice(i, 1);
173
+ }
168
174
  }),
169
175
  };
170
176
  }
171
177
 
172
- it('seeds endpoints, workflows and convenience pipelines', async () => {
178
+ it('seeds all 36 canonical du-rework profiles across document-core, lc-checker, and example-review', async () => {
173
179
  const endpointsRepo = makeRepo();
174
180
  const pipelinesRepo = makeRepo();
175
181
  const stepsRepo = makeRepo();
@@ -182,25 +188,47 @@ describe('DUGate seed data', () => {
182
188
  }),
183
189
  };
184
190
 
185
- await seedDugateEndpoints(db as never);
191
+ const result = await seedDugateEndpoints(db as never);
192
+ expect(result).toEqual({ endpoints: 36, pipelines: 36 });
186
193
 
187
- // 31 core endpoints + 3 workflows
188
- expect(endpointsRepo.store).toHaveLength(34);
189
- expect(endpointsRepo.store.filter((e) => e.subpath.includes('/workflows'))).toHaveLength(3);
190
- expect(endpointsRepo.store.find((e) => e.name === 'dugate-extract-invoice')?.discriminatorValue).toBe('invoice');
191
- expect(endpointsRepo.store.find((e) => e.name === 'dugate-ingest-parse')?.discriminatorValue).toBe('parse');
192
- expect(endpointsRepo.store.find((e) => e.name === 'dugate-workflow-disbursement')?.discriminatorField).toBe(
193
- 'process',
194
- );
194
+ expect(endpointsRepo.store).toHaveLength(36);
195
+ expect(endpointsRepo.store.find((e) => e.name === 'du-extract-invoice')).toMatchObject({
196
+ subpath: '/api/v1/businesses/document-core/actions/extract',
197
+ protocolMode: 'builtin_du',
198
+ businessId: 'document-core',
199
+ actionName: 'extract',
200
+ discriminatorField: 'type',
201
+ discriminatorValue: 'invoice',
202
+ });
203
+ expect(endpointsRepo.store.find((e) => e.name === 'du-transform-redact')?.discriminatorField).toBe('variant');
204
+ expect(endpointsRepo.store.find((e) => e.name === 'du-lc-checker')).toMatchObject({
205
+ subpath: '/api/v1/businesses/lc-checker/actions/lc-checker',
206
+ businessId: 'lc-checker',
207
+ actionName: 'lc-checker',
208
+ });
209
+ expect(endpointsRepo.store.find((e) => e.name === 'du-example-review')?.businessId).toBe('example-review');
195
210
 
196
- expect(pipelinesRepo.store).toHaveLength(34);
197
- expect(stepsRepo.store).toHaveLength(34);
198
- const firstStep = stepsRepo.store[0];
199
- expect(firstStep).toMatchObject({ stepOrder: 1, outputAlias: 'result' });
211
+ expect(pipelinesRepo.store).toHaveLength(36);
212
+ expect(stepsRepo.store).toHaveLength(36);
200
213
  });
201
214
 
202
- it('is idempotent when run twice', async () => {
203
- const endpointsRepo = makeRepo();
215
+ it('upgrades pre-existing legacy dugate-* endpoints in-place and stays idempotent', async () => {
216
+ const endpointsRepo = makeRepo([
217
+ {
218
+ id: 1,
219
+ name: 'dugate-extract-invoice',
220
+ subpath: '/api/v1/docs/extract',
221
+ discriminatorField: 'type',
222
+ discriminatorValue: 'invoice',
223
+ },
224
+ {
225
+ id: 2,
226
+ name: 'dugate-workflow-lc-checker',
227
+ subpath: '/api/v1/docs/workflows',
228
+ discriminatorField: 'process',
229
+ discriminatorValue: 'lc-checker',
230
+ },
231
+ ]);
204
232
  const pipelinesRepo = makeRepo();
205
233
  const stepsRepo = makeRepo();
206
234
  const db = {
@@ -215,7 +243,16 @@ describe('DUGate seed data', () => {
215
243
  await seedDugateEndpoints(db as never);
216
244
  await seedDugateEndpoints(db as never);
217
245
 
218
- expect(endpointsRepo.store).toHaveLength(34);
219
- expect(pipelinesRepo.store).toHaveLength(34);
246
+ expect(endpointsRepo.store).toHaveLength(36);
247
+ expect(endpointsRepo.store.find((e) => e.id === 1)).toMatchObject({
248
+ name: 'du-extract-invoice',
249
+ subpath: '/api/v1/businesses/document-core/actions/extract',
250
+ protocolMode: 'builtin_du',
251
+ });
252
+ expect(endpointsRepo.store.find((e) => e.id === 2)).toMatchObject({
253
+ name: 'du-lc-checker',
254
+ subpath: '/api/v1/businesses/lc-checker/actions/lc-checker',
255
+ businessId: 'lc-checker',
256
+ });
220
257
  });
221
258
  });
@@ -1,11 +1,4 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
1
+ // SPDX-License-Identifier: Apache-2.0
9
2
 
10
3
  import { createMockServer, type MockServer } from '@nocobase/test';
11
4
  import PluginDocumentUnderstandingServer from '../plugin';