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
@@ -1,10 +1,19 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import React, { useEffect, useState } from 'react';
2
- import { Form, Input, Select, Button, message, InputNumber, Spin, Alert } from 'antd';
3
- import { SaveOutlined, LinkOutlined } from '@ant-design/icons';
4
+ import { Form, Input, Select, Button, message, InputNumber, Spin, Alert, Switch, Space, Card, Tag } from 'antd';
5
+ import { SaveOutlined, LinkOutlined, CheckCircleOutlined, SyncOutlined } from '@ant-design/icons';
4
6
  import { useFlowContext } from '@nocobase/flow-engine';
5
7
  import { useT } from '../locale';
6
8
  import { ClientServiceConfig, ServiceConfig, errorMessage, unwrapData } from '../types';
7
9
 
10
+ interface LlmServiceOption {
11
+ llmService: string;
12
+ llmServiceTitle: string;
13
+ provider: string;
14
+ enabledModels: Array<{ label: string; value: string }>;
15
+ }
16
+
8
17
  export const ServiceConfigTab = () => {
9
18
  const [form] = Form.useForm<Partial<ServiceConfig>>();
10
19
  const ctx = useFlowContext();
@@ -12,15 +21,34 @@ export const ServiceConfigTab = () => {
12
21
  const t = useT();
13
22
  const [loading, setLoading] = useState(true);
14
23
  const [saving, setSaving] = useState(false);
24
+ const [checkingHealth, setCheckingHealth] = useState(false);
25
+ const [syncingCatalog, setSyncingCatalog] = useState(false);
15
26
  const [loadError, setLoadError] = useState<string>();
27
+ const [llmServices, setLlmServices] = useState<LlmServiceOption[]>([]);
28
+ const [healthInfo, setHealthInfo] = useState<Record<string, unknown> | null>(null);
29
+
30
+ const watchedEngineMode = Form.useWatch('engineMode', form) || 'builtin';
31
+ const watchedLlmService = Form.useWatch('llmService', form);
16
32
 
17
33
  useEffect(() => {
18
34
  let cancelled = false;
19
35
  const load = async () => {
20
36
  try {
21
- const response = await api.request({ url: 'docUnderstanding:getConfig' });
37
+ const [configRes, llmRes] = await Promise.all([
38
+ api.request({ url: 'docUnderstanding:getConfig' }),
39
+ api.request({ url: 'docUnderstanding:listLlmServices' }).catch(() => null),
40
+ ]);
22
41
  if (cancelled) return;
23
- form.setFieldsValue(unwrapData<Partial<ClientServiceConfig>>(response, {}));
42
+ form.setFieldsValue({
43
+ engineMode: 'builtin',
44
+ publicGatewayEnabled: true,
45
+ maxFileSizeBytes: 10485760,
46
+ maxFilesPerRequest: 20,
47
+ ...unwrapData<Partial<ClientServiceConfig>>(configRes, {}),
48
+ });
49
+ if (llmRes) {
50
+ setLlmServices(unwrapData<LlmServiceOption[]>(llmRes, []));
51
+ }
24
52
  } catch (error) {
25
53
  if (!cancelled) setLoadError(errorMessage(error));
26
54
  } finally {
@@ -49,85 +77,217 @@ export const ServiceConfigTab = () => {
49
77
  }
50
78
  };
51
79
 
80
+ const handleCheckHealth = async () => {
81
+ setCheckingHealth(true);
82
+ try {
83
+ const res = await api.request({ url: 'docUnderstanding:getHealth' });
84
+ const data = unwrapData<Record<string, unknown>>(res, {});
85
+ setHealthInfo(data);
86
+ message.success(t('Health check succeeded'));
87
+ } catch (error) {
88
+ message.error(`${t('Health check failed')}: ${errorMessage(error)}`);
89
+ } finally {
90
+ setCheckingHealth(false);
91
+ }
92
+ };
93
+
94
+ const handleSyncCatalog = async () => {
95
+ setSyncingCatalog(true);
96
+ try {
97
+ const res = await api.request({ url: 'docUnderstanding:syncCatalog', method: 'POST' });
98
+ const counts = unwrapData<{ endpoints?: number; pipelines?: number }>(res, {});
99
+ message.success(
100
+ `${t('Catalog synchronized')}: ${counts.endpoints ?? 36} endpoints / ${counts.pipelines ?? 36} pipelines`,
101
+ );
102
+ } catch (error) {
103
+ message.error(errorMessage(error));
104
+ } finally {
105
+ setSyncingCatalog(false);
106
+ }
107
+ };
108
+
52
109
  if (loading) return <Spin style={{ marginTop: 40 }} />;
53
110
 
111
+ const selectedServiceMeta = llmServices.find((s) => s.llmService === watchedLlmService);
112
+
54
113
  return (
55
- <Form form={form} layout="vertical" onFinish={onFinish} style={{ maxWidth: 600 }}>
114
+ <Form form={form} layout="vertical" onFinish={onFinish} style={{ maxWidth: 760 }}>
56
115
  {loadError && <Alert message={loadError} type="error" showIcon style={{ marginBottom: 16 }} />}
57
116
 
58
117
  <Alert
59
- message={t('Service Connection')}
60
- description={t('Configure the connection to your external document processing service')}
118
+ message={t('Document Understanding Service & Public API Gateway')}
119
+ description={
120
+ <div>
121
+ <div>
122
+ {t(
123
+ 'Provides built-in Document Understanding APIs (/api/du/v1/* and /api/v1/*) compatible with du-rework, with optional delegation to an external gateway.',
124
+ )}
125
+ </div>
126
+ <Space style={{ marginTop: 8 }} wrap>
127
+ <Tag color="blue">POST /api/du/v1/uploads</Tag>
128
+ <Tag color="blue">POST /api/du/v1/businesses/:id/actions/:action</Tag>
129
+ <Tag color="blue">GET /api/du/v1/operations/:id</Tag>
130
+ <Tag color="blue">GET /api/du/v1/artifacts/:id/download</Tag>
131
+ </Space>
132
+ </div>
133
+ }
61
134
  type="info"
62
135
  showIcon
63
- style={{ marginBottom: 24 }}
136
+ style={{ marginBottom: 16 }}
64
137
  />
65
138
 
66
- <Form.Item
67
- name="baseUrl"
68
- label={t('Base URL')}
69
- rules={[{ required: true, message: t('Base URL is required') }]}
70
- help={t('The root URL of your document processing API')}
71
- >
72
- <Input prefix={<LinkOutlined />} placeholder="http://my-ocr-service:8000" />
73
- </Form.Item>
139
+ <Space style={{ marginBottom: 16 }} wrap>
140
+ <Button icon={<CheckCircleOutlined />} onClick={handleCheckHealth} loading={checkingHealth}>
141
+ {t('Check Service Health')}
142
+ </Button>
143
+ <Button icon={<SyncOutlined />} onClick={handleSyncCatalog} loading={syncingCatalog}>
144
+ {t('Sync du-rework Catalog (36 profiles)')}
145
+ </Button>
146
+ </Space>
74
147
 
75
- <Form.Item name="authType" label={t('Authentication Type')} initialValue="none">
76
- <Select
77
- options={[
78
- { value: 'none', label: t('None') },
79
- { value: 'api_key', label: t('API Key') },
80
- { value: 'bearer', label: t('Bearer Token') },
81
- { value: 'custom_header', label: t('Custom Header') },
82
- ]}
83
- />
84
- </Form.Item>
148
+ {healthInfo && (
149
+ <Card size="small" style={{ marginBottom: 16 }} title={t('Runtime Health')}>
150
+ <pre style={{ margin: 0, fontSize: 12, overflow: 'auto' }}>{JSON.stringify(healthInfo, null, 2)}</pre>
151
+ </Card>
152
+ )}
85
153
 
86
- <Form.Item noStyle dependencies={['authType']}>
87
- {() => {
88
- const type = form.getFieldValue('authType');
89
- if (type === 'none') return null;
90
- return (
91
- <>
92
- {type === 'custom_header' && (
93
- <Form.Item name="authHeaderName" label={t('Custom Header Name')} rules={[{ required: true }]}>
94
- <Input placeholder="X-Api-Key" />
95
- </Form.Item>
154
+ <Card size="small" title={t('Execution Engine & Gateway Policy')} style={{ marginBottom: 16 }}>
155
+ <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: '0 16px' }}>
156
+ <Form.Item name="engineMode" label={t('Execution Engine Mode')} initialValue="builtin">
157
+ <Select
158
+ options={[
159
+ { value: 'builtin', label: t('Built-in NocoBase AI & Document Parser Engine') },
160
+ { value: 'hybrid', label: t('Hybrid (Built-in first, fallback to External Gateway)') },
161
+ { value: 'du_rework', label: t('External du-rework API Gateway') },
162
+ ]}
163
+ />
164
+ </Form.Item>
165
+ <Form.Item
166
+ name="publicGatewayEnabled"
167
+ label={t('Public API Gateway')}
168
+ valuePropName="checked"
169
+ initialValue={true}
170
+ >
171
+ <Switch checkedChildren={t('Enabled')} unCheckedChildren={t('Disabled')} />
172
+ </Form.Item>
173
+ </div>
174
+
175
+ {watchedEngineMode !== 'du_rework' && (
176
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
177
+ <Form.Item
178
+ name="llmService"
179
+ label={t('Reasoning LLM Service (@nocobase/plugin-ai)')}
180
+ help={t('Leave blank to auto-select the first enabled LLM service')}
181
+ >
182
+ <Select
183
+ allowClear
184
+ placeholder={t('Auto-select active LLM service')}
185
+ options={llmServices.map((s) => ({
186
+ value: s.llmService,
187
+ label: `${s.llmServiceTitle || s.llmService} (${s.provider})`,
188
+ }))}
189
+ />
190
+ </Form.Item>
191
+ <Form.Item name="llmModel" label={t('Reasoning Model')}>
192
+ {selectedServiceMeta ? (
193
+ <Select
194
+ allowClear
195
+ placeholder={t('Auto-select default model')}
196
+ options={selectedServiceMeta.enabledModels}
197
+ />
198
+ ) : (
199
+ <Input placeholder="gpt-4o / gemini-2.5-pro" />
96
200
  )}
97
- <Form.Item
98
- name="authKey"
99
- label={type === 'bearer' ? t('Bearer Token') : t('API Key')}
100
- rules={[{ required: true }]}
101
- >
102
- <Input.Password placeholder={t('Enter key or token')} />
103
- </Form.Item>
104
- </>
105
- );
106
- }}
107
- </Form.Item>
201
+ </Form.Item>
202
+ <Form.Item name="visionLlmService" label={t('Vision / OCR LLM Service (Optional)')}>
203
+ <Select
204
+ allowClear
205
+ placeholder={t('Same as Reasoning LLM Service')}
206
+ options={llmServices.map((s) => ({
207
+ value: s.llmService,
208
+ label: `${s.llmServiceTitle || s.llmService} (${s.provider})`,
209
+ }))}
210
+ />
211
+ </Form.Item>
212
+ <Form.Item name="visionLlmModel" label={t('Vision / OCR Model (Optional)')}>
213
+ <Input placeholder="gemini-2.5-flash / gpt-4o" />
214
+ </Form.Item>
215
+ </div>
216
+ )}
108
217
 
109
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
110
- <Form.Item name="defaultTimeout" label={t('Request Timeout (ms)')} initialValue={30000}>
111
- <InputNumber style={{ width: '100%' }} min={1000} step={1000} />
218
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
219
+ <Form.Item name="maxFilesPerRequest" label={t('Max Files per Operation (DI-06)')} initialValue={20}>
220
+ <InputNumber style={{ width: '100%' }} min={1} max={50} />
221
+ </Form.Item>
222
+ <Form.Item name="maxFileSizeBytes" label={t('Max File Size (bytes)')} initialValue={10485760}>
223
+ <InputNumber style={{ width: '100%' }} min={102400} step={1048576} />
224
+ </Form.Item>
225
+ </div>
226
+ </Card>
227
+
228
+ <Card size="small" title={t('External Gateway & Webhook Connection')} style={{ marginBottom: 16 }}>
229
+ <Form.Item
230
+ name="baseUrl"
231
+ label={t('Base URL')}
232
+ rules={[{ required: true, message: t('Base URL is required') }]}
233
+ help={t('Used when delegating to an external du-rework gateway or custom REST endpoints')}
234
+ >
235
+ <Input prefix={<LinkOutlined />} placeholder="http://du-orchestrator:3000" />
112
236
  </Form.Item>
113
- <Form.Item name="defaultRetries" label={t('Default Retries')} initialValue={2}>
114
- <InputNumber style={{ width: '100%' }} min={0} max={10} />
237
+
238
+ <Form.Item name="authType" label={t('Authentication Type')} initialValue="none">
239
+ <Select
240
+ options={[
241
+ { value: 'none', label: t('None') },
242
+ { value: 'api_key', label: t('API Key (x-api-key)') },
243
+ { value: 'bearer', label: t('Bearer Token') },
244
+ { value: 'custom_header', label: t('Custom Header') },
245
+ ]}
246
+ />
115
247
  </Form.Item>
116
- <Form.Item name="pollInterval" label={t('Poll Interval (ms)')} initialValue={5000}>
117
- <InputNumber style={{ width: '100%' }} min={1000} step={1000} />
248
+
249
+ <Form.Item noStyle dependencies={['authType']}>
250
+ {() => {
251
+ const type = form.getFieldValue('authType');
252
+ if (!type || type === 'none') return null;
253
+ return (
254
+ <>
255
+ {type === 'custom_header' && (
256
+ <Form.Item name="authHeaderName" label={t('Custom Header Name')} rules={[{ required: true }]}>
257
+ <Input placeholder="x-api-key" />
258
+ </Form.Item>
259
+ )}
260
+ <Form.Item name="authKey" label={type === 'bearer' ? t('Bearer Token') : t('API Key')}>
261
+ <Input.Password placeholder={t('Leave blank to keep existing secret')} />
262
+ </Form.Item>
263
+ </>
264
+ );
265
+ }}
118
266
  </Form.Item>
119
- <Form.Item name="pollTimeout" label={t('Poll Timeout (ms)')} initialValue={300000}>
120
- <InputNumber style={{ width: '100%' }} min={5000} step={5000} />
267
+
268
+ <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '0 16px' }}>
269
+ <Form.Item name="defaultTimeout" label={t('Request Timeout (ms)')} initialValue={30000}>
270
+ <InputNumber style={{ width: '100%' }} min={1000} step={1000} />
271
+ </Form.Item>
272
+ <Form.Item name="defaultRetries" label={t('Default Retries')} initialValue={2}>
273
+ <InputNumber style={{ width: '100%' }} min={0} max={10} />
274
+ </Form.Item>
275
+ <Form.Item name="pollInterval" label={t('Poll Interval (ms)')} initialValue={5000}>
276
+ <InputNumber style={{ width: '100%' }} min={1000} step={1000} />
277
+ </Form.Item>
278
+ <Form.Item name="pollTimeout" label={t('Poll Timeout (ms)')} initialValue={300000}>
279
+ <InputNumber style={{ width: '100%' }} min={5000} step={5000} />
280
+ </Form.Item>
281
+ </div>
282
+
283
+ <Form.Item
284
+ name="webhookSecret"
285
+ label={t('Webhook Secret')}
286
+ help={t('Signs outbound x-du-signature callbacks and verifies incoming webhooks')}
287
+ >
288
+ <Input.Password placeholder={t('Optional: secret for HMAC-SHA256 webhook signature')} />
121
289
  </Form.Item>
122
- </div>
123
-
124
- <Form.Item
125
- name="webhookSecret"
126
- label={t('Webhook Secret')}
127
- help={t('Used to verify HMAC-SHA256 signatures on incoming webhook callbacks')}
128
- >
129
- <Input.Password placeholder={t('Optional: secret for webhook signature verification')} />
130
- </Form.Item>
290
+ </Card>
131
291
 
132
292
  <Form.Item>
133
293
  <Button type="primary" htmlType="submit" icon={<SaveOutlined />} loading={saving}>
@@ -7,6 +7,8 @@ import { PluginSettings } from '../PluginSettings';
7
7
 
8
8
  vi.mock('../../locale', () => ({ useT: () => (key: string) => key }));
9
9
  vi.mock('../ServiceConfigTab', () => ({ ServiceConfigTab: () => <div>Service configuration content</div> }));
10
+ vi.mock('../OperationsTab', () => ({ OperationsTab: () => <div>Operations content</div> }));
11
+ vi.mock('../ApiKeysTab', () => ({ ApiKeysTab: () => <div>API Keys content</div> }));
10
12
  vi.mock('../EndpointsTab', () => ({ EndpointsTab: () => <div>Endpoint content</div> }));
11
13
  vi.mock('../PipelinesTab', () => ({ PipelinesTab: () => <div>Pipeline content</div> }));
12
14
  vi.mock('../JobsTab', () => ({ JobsTab: () => <div>Job content</div> }));
@@ -21,6 +23,8 @@ describe('Document Understanding plugin settings layout', () => {
21
23
  expect(root.style.minHeight).toBe('');
22
24
  expect(content.style.padding).toBe('0px');
23
25
  expect(screen.getByRole('tab', { name: 'Service Config' })).toBeTruthy();
26
+ expect(screen.getByRole('tab', { name: 'Operations' })).toBeTruthy();
27
+ expect(screen.getByRole('tab', { name: 'API Keys' })).toBeTruthy();
24
28
  expect(screen.getByRole('tab', { name: 'Endpoints' })).toBeTruthy();
25
29
  expect(screen.getByRole('tab', { name: 'Pipelines' })).toBeTruthy();
26
30
  expect(screen.getByRole('tab', { name: 'Jobs history' })).toBeTruthy();
@@ -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 { tExpr as _tExpr, useFlowEngine } from '@nocobase/flow-engine';
11
4
  // @ts-ignore
@@ -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 { ModelConstructor } from '@nocobase/flow-engine';
11
4
 
@@ -1,13 +1,12 @@
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 { Application, Plugin } from '@nocobase/client-v2';
4
+ import type { Instruction } from '@nocobase/plugin-workflow/client-v2';
5
+ import DocumentUnderstandingInstruction from './workflow/DocumentUnderstandingInstruction';
6
+
7
+ type WorkflowClientV2Like = {
8
+ registerInstruction?: (type: string, instruction: Instruction | { new (): Instruction }) => void;
9
+ };
11
10
 
12
11
  export class PluginDocumentUnderstandingClient extends Plugin<Record<string, never>, Application> {
13
12
  async load() {
@@ -25,6 +24,11 @@ export class PluginDocumentUnderstandingClient extends Plugin<Record<string, nev
25
24
  componentLoader: () => import('./components/PluginSettings'),
26
25
  aclSnippet: `pm.${this.options.name || 'document-understanding'}`,
27
26
  });
27
+
28
+ const workflow = (this.app.pm.get('workflow') || this.app.pm.get('@nocobase/plugin-workflow')) as
29
+ | WorkflowClientV2Like
30
+ | undefined;
31
+ workflow?.registerInstruction?.('document-understanding', DocumentUnderstandingInstruction);
28
32
  }
29
33
  }
30
34
 
@@ -1,3 +1,5 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  export type {
2
4
  ServiceConfig,
3
5
  ClientServiceConfig,
@@ -5,6 +7,17 @@ export type {
5
7
  PipelineStepDef,
6
8
  PipelineDef,
7
9
  JobState,
10
+ JobStatus,
11
+ EngineMode,
12
+ ProtocolMode,
13
+ DuApiKeySummary,
14
+ IssuedDuApiKey,
15
+ OperationView,
16
+ UsageSummaryView,
17
+ UsageMetrics,
18
+ WaitState,
19
+ DocumentInputCoverage,
20
+ DuOperationState,
8
21
  } from '../server/types';
9
22
 
10
23
  export interface ApiEnvelope<T> {
@@ -24,7 +37,6 @@ export function errorMessage(error: unknown): string {
24
37
  return error instanceof Error ? error.message : String(error);
25
38
  }
26
39
 
27
- /** Job timestamps are declared as `Date` server-side but arrive as ISO strings over the wire. */
28
40
  export function formatDateTime(value: string | Date | null | undefined): string {
29
41
  if (!value) return '-';
30
42
  const date = value instanceof Date ? value : new Date(value);
@@ -0,0 +1,122 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import React, { useEffect, useState } from 'react';
4
+ import { Checkbox, Form, Select } from 'antd';
5
+ import { useFlowContext } from '@nocobase/flow-engine';
6
+ import { WorkflowVariableInput, WorkflowVariableJsonTextArea } from '@nocobase/plugin-workflow/client-v2';
7
+ import { DU_BUSINESS_CATALOG } from '../../server/contracts/du-contracts';
8
+ import { PipelineDef, unwrapData } from '../types';
9
+ import { useT } from '../locale';
10
+
11
+ const BUSINESS_OPTIONS = [
12
+ { value: 'document-core', label: 'document-core (v2.0.0)' },
13
+ { value: 'lc-checker', label: 'lc-checker (v1.2.0 - UCP 600 / ISBP 821)' },
14
+ { value: 'example-review', label: 'example-review (v1.0.0)' },
15
+ ];
16
+
17
+ export const DocumentUnderstandingFieldset: React.FC = () => {
18
+ const t = useT();
19
+ const ctx = useFlowContext();
20
+ const form = Form.useFormInstance();
21
+ const mode = Form.useWatch(['config', 'mode'], form) || 'business_action';
22
+ const businessId = Form.useWatch(['config', 'businessId'], form) || 'document-core';
23
+ const action = Form.useWatch(['config', 'action'], form) || 'extract';
24
+ const [pipelines, setPipelines] = useState<PipelineDef[]>([]);
25
+
26
+ useEffect(() => {
27
+ if (mode !== 'pipeline' || !ctx?.api) return;
28
+ let cancelled = false;
29
+ ctx.api
30
+ .request({ url: 'docUnderstanding:listPipelines' })
31
+ .then((res: unknown) => {
32
+ if (!cancelled) {
33
+ setPipelines(unwrapData<PipelineDef[]>(res, []));
34
+ }
35
+ })
36
+ .catch(() => undefined);
37
+ return () => {
38
+ cancelled = true;
39
+ };
40
+ }, [ctx?.api, mode]);
41
+
42
+ const actionsForBusiness = Array.from(
43
+ new Set(DU_BUSINESS_CATALOG.filter((item) => item.businessId === businessId).map((item) => item.action)),
44
+ );
45
+ const variantsForAction = DU_BUSINESS_CATALOG.filter(
46
+ (item) => item.businessId === businessId && item.action === action && item.discriminatorValue,
47
+ );
48
+
49
+ return (
50
+ <div>
51
+ <Form.Item name={['config', 'mode']} label={t('Execution Mode')} initialValue="business_action">
52
+ <Select
53
+ options={[
54
+ { value: 'business_action', label: t('Canonical Business Action (du-rework)') },
55
+ { value: 'pipeline', label: t('Configured Pipeline') },
56
+ ]}
57
+ />
58
+ </Form.Item>
59
+
60
+ {mode === 'pipeline' ? (
61
+ <Form.Item
62
+ name={['config', 'pipelineId']}
63
+ label={t('Pipeline')}
64
+ rules={[{ required: true, message: t('Select a pipeline') }]}
65
+ >
66
+ <Select placeholder={t('Select pipeline')} options={pipelines.map((p) => ({ value: p.id, label: p.name }))} />
67
+ </Form.Item>
68
+ ) : (
69
+ <>
70
+ <Form.Item name={['config', 'businessId']} label={t('Business')} initialValue="document-core">
71
+ <Select options={BUSINESS_OPTIONS} />
72
+ </Form.Item>
73
+ <Form.Item name={['config', 'action']} label={t('Action')} initialValue="extract">
74
+ <Select options={actionsForBusiness.map((act) => ({ value: act, label: act }))} />
75
+ </Form.Item>
76
+ {variantsForAction.length > 0 && (
77
+ <Form.Item name={['config', 'variant']} label={t('Variant / Mode')}>
78
+ <Select
79
+ allowClear
80
+ placeholder={t('Select variant')}
81
+ options={variantsForAction.map((v) => ({
82
+ value: v.discriminatorValue as string,
83
+ label: `${v.discriminatorValue} — ${v.description}`,
84
+ }))}
85
+ />
86
+ </Form.Item>
87
+ )}
88
+ </>
89
+ )}
90
+
91
+ <Form.Item
92
+ name={['config', 'files']}
93
+ label={t('Document Files / Attachment Variable')}
94
+ extra={t('Bind an attachment field, file URL, or comma-separated upload paths from upstream nodes')}
95
+ >
96
+ <WorkflowVariableInput placeholder="uploads/invoice.pdf" />
97
+ </Form.Item>
98
+
99
+ <Form.Item
100
+ name={['config', 'pages']}
101
+ label={t('Page Selection (DI-06)')}
102
+ extra={t('Optional page ranges, e.g. "1-3, 5" (leave empty for all pages)')}
103
+ >
104
+ <WorkflowVariableInput placeholder="1-3" />
105
+ </Form.Item>
106
+
107
+ <Form.Item
108
+ name={['config', 'inputJson']}
109
+ label={t('Input Parameters (JSON)')}
110
+ extra={t('Additional action parameters (e.g. referenceData, questions, targetLanguage, ruleSetVersion)')}
111
+ >
112
+ <WorkflowVariableJsonTextArea rows={4} placeholder='{ "outputFormat": "json" }' />
113
+ </Form.Item>
114
+
115
+ <Form.Item name={['config', 'ignoreFail']} valuePropName="checked" initialValue={false}>
116
+ <Checkbox>{t('Continue workflow even if document processing fails')}</Checkbox>
117
+ </Form.Item>
118
+ </div>
119
+ );
120
+ };
121
+
122
+ export default DocumentUnderstandingFieldset;
@@ -0,0 +1,49 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import React from 'react';
4
+ import { FileSearchOutlined } from '@ant-design/icons';
5
+ import { Instruction } from '@nocobase/plugin-workflow/client-v2';
6
+ import { tExpr } from '../locale';
7
+
8
+ export default class DocumentUnderstandingInstruction extends Instruction {
9
+ type = 'document-understanding';
10
+ title = tExpr('Document Understanding');
11
+ group = 'extended';
12
+ description = tExpr(
13
+ 'Parse, OCR, extract, analyze, transform, compare, or audit L/C & disbursement documents via Document Understanding.',
14
+ );
15
+ icon = (<FileSearchOutlined />);
16
+
17
+ FieldsetLoader = () =>
18
+ import('./DocumentUnderstandingFieldset').then((module) => ({
19
+ default: module.DocumentUnderstandingFieldset,
20
+ }));
21
+
22
+ createDefaultConfig() {
23
+ return {
24
+ mode: 'business_action',
25
+ businessId: 'document-core',
26
+ action: 'extract',
27
+ variant: 'invoice',
28
+ ignoreFail: false,
29
+ };
30
+ }
31
+
32
+ useVariables({ key, title }: { key: string; title: string }) {
33
+ return {
34
+ value: key,
35
+ label: title,
36
+ children: [
37
+ { value: 'operationId', label: tExpr('Operation ID') },
38
+ { value: 'state', label: tExpr('State') },
39
+ { value: 'data', label: tExpr('Structured Data') },
40
+ { value: 'markdown', label: tExpr('Markdown Content') },
41
+ { value: 'text', label: tExpr('Plain Text') },
42
+ { value: 'report', label: tExpr('Report') },
43
+ { value: 'verdict', label: tExpr('Verdict') },
44
+ { value: 'discrepancies', label: tExpr('Discrepancies') },
45
+ { value: 'usage', label: tExpr('Token & Cost Usage') },
46
+ ],
47
+ };
48
+ }
49
+ }