@nocobase/plugin-workflow-manual 2.2.0-beta.9 → 3.0.0-alpha.1

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.
@@ -41,7 +41,62 @@ __export(actions_exports, {
41
41
  });
42
42
  module.exports = __toCommonJS(actions_exports);
43
43
  var import_actions = __toESM(require("@nocobase/actions"));
44
+ var import_database = require("@nocobase/database");
44
45
  var import_plugin_workflow = __toESM(require("@nocobase/plugin-workflow"));
46
+ function getSubmittedRatio(tasks) {
47
+ if (!tasks.length) {
48
+ return 0;
49
+ }
50
+ const submitted = tasks.reduce((count, item) => item.status !== import_plugin_workflow.JOB_STATUS.PENDING ? count + 1 : count, 0);
51
+ return submitted / tasks.length;
52
+ }
53
+ function getSingleModeStatus(distribution) {
54
+ var _a;
55
+ return ((_a = distribution.find((item) => item.status !== import_plugin_workflow.JOB_STATUS.PENDING && item.count > 0)) == null ? void 0 : _a.status) ?? null;
56
+ }
57
+ function getAllModeStatus(distribution, assignees) {
58
+ const resolved = distribution.find((item) => item.status === import_plugin_workflow.JOB_STATUS.RESOLVED);
59
+ if ((resolved == null ? void 0 : resolved.count) === assignees.length) {
60
+ return import_plugin_workflow.JOB_STATUS.RESOLVED;
61
+ }
62
+ const rejected = distribution.find((item) => item.status < import_plugin_workflow.JOB_STATUS.PENDING);
63
+ return (rejected == null ? void 0 : rejected.count) ? rejected.status : null;
64
+ }
65
+ function getAnyModeStatus(distribution, assignees) {
66
+ const resolved = distribution.find((item) => item.status === import_plugin_workflow.JOB_STATUS.RESOLVED);
67
+ if (resolved == null ? void 0 : resolved.count) {
68
+ return import_plugin_workflow.JOB_STATUS.RESOLVED;
69
+ }
70
+ const rejectedCount = distribution.reduce(
71
+ (count, item) => item.status < import_plugin_workflow.JOB_STATUS.PENDING ? count + item.count : count,
72
+ 0
73
+ );
74
+ return rejectedCount === assignees.length ? import_plugin_workflow.JOB_STATUS.REJECTED : null;
75
+ }
76
+ async function updateJobByManualTasks(job, node, database, latestTask, transaction) {
77
+ const mode = node.config.mode ?? 0;
78
+ const tasks = await database.getModel("workflowManualTasks").findAll({
79
+ where: {
80
+ jobId: job.id
81
+ },
82
+ transaction
83
+ });
84
+ const assignees = [];
85
+ const distributionMap = /* @__PURE__ */ new Map();
86
+ for (const task of tasks) {
87
+ distributionMap.set(task.status, (distributionMap.get(task.status) ?? 0) + 1);
88
+ assignees.push(task.userId);
89
+ }
90
+ const distribution = Array.from(distributionMap.entries()).map(([status2, count]) => ({ status: status2, count }));
91
+ const status = mode === 1 ? getAllModeStatus(distribution, assignees) : mode === -1 ? getAnyModeStatus(distribution, assignees) : getSingleModeStatus(distribution);
92
+ await job.update(
93
+ {
94
+ status: status ?? import_plugin_workflow.JOB_STATUS.PENDING,
95
+ result: mode ? getSubmittedRatio(tasks) : latestTask.result ?? job.result
96
+ },
97
+ { transaction }
98
+ );
99
+ }
45
100
  async function submit(context, next) {
46
101
  var _a, _b, _c;
47
102
  const repository = import_actions.utils.getRepositoryFromParams(context);
@@ -78,48 +133,99 @@ async function submit(context, next) {
78
133
  return context.throw(400);
79
134
  }
80
135
  task.execution.workflow = task.workflow;
81
- const processor = plugin.createProcessor(task.execution);
82
- await processor.prepare();
83
- const assignees = processor.getParsedValue(task.node.config.assignees ?? [], task.nodeId).flat().filter(Boolean);
84
- if (!assignees.includes(currentUser.id) || task.userId !== currentUser.id) {
85
- return context.throw(403);
86
- }
87
- const presetValues = processor.getParsedValue(actionItem.values ?? {}, task.nodeId, {
88
- additionalScope: {
89
- // @deprecated
90
- currentUser,
91
- // @deprecated
92
- currentRecord: values.result[formKey],
93
- // @deprecated
94
- currentTime: /* @__PURE__ */ new Date(),
95
- $user: currentUser,
96
- $nForm: values.result[formKey],
97
- $nDate: {
98
- now: /* @__PURE__ */ new Date()
136
+ const formConfig = forms[formKey];
137
+ const handler = instruction.formTypes.get(formConfig.type);
138
+ const usesMainDataSource = (formConfig.dataSource ?? "main") === "main";
139
+ const transactionOptions = context.db.sequelize.getDialect() === "sqlite" ? { type: import_database.Transaction.TYPES.IMMEDIATE } : {};
140
+ const validateTask = () => {
141
+ if (task.status !== import_plugin_workflow.JOB_STATUS.PENDING || task.job.status !== import_plugin_workflow.JOB_STATUS.PENDING || task.execution.status !== import_plugin_workflow.EXECUTION_STATUS.STARTED) {
142
+ return context.throw(400);
143
+ }
144
+ };
145
+ const getPresetValues = (processor) => {
146
+ const assignees = processor.getParsedValue(task.node.config.assignees ?? [], task.nodeId).flat().filter(Boolean);
147
+ if (!assignees.includes(currentUser.id) || task.userId !== currentUser.id) {
148
+ return context.throw(403);
149
+ }
150
+ return processor.getParsedValue(actionItem.values ?? {}, task.nodeId, {
151
+ additionalScope: {
152
+ // @deprecated
153
+ currentUser,
154
+ // @deprecated
155
+ currentRecord: values.result[formKey],
156
+ // @deprecated
157
+ currentTime: /* @__PURE__ */ new Date(),
158
+ $user: currentUser,
159
+ $nForm: values.result[formKey],
160
+ $nDate: {
161
+ now: /* @__PURE__ */ new Date()
162
+ }
99
163
  }
164
+ });
165
+ };
166
+ const setTaskResult = (presetValues) => {
167
+ task.set({
168
+ status: actionItem.status,
169
+ result: actionItem.status ? { [formKey]: { ...values.result[formKey], ...presetValues }, _: actionKey } : { ...task.result ?? {}, ...values.result }
170
+ });
171
+ task.changed("result", true);
172
+ };
173
+ const handleFormSubmission = async (transaction) => {
174
+ const processor = plugin.createProcessor(task.execution, { transaction });
175
+ await processor.prepare();
176
+ const presetValues = getPresetValues(processor);
177
+ setTaskResult(presetValues);
178
+ if (handler && task.status) {
179
+ const { actions: actions2, ...formOptions } = formConfig;
180
+ const parsedFormConfig = {
181
+ ...processor.getParsedValue(formOptions, task.nodeId),
182
+ actions: actions2
183
+ };
184
+ await handler.call(instruction, task, parsedFormConfig, transaction);
100
185
  }
101
- });
102
- task.set({
103
- status: actionItem.status,
104
- result: actionItem.status ? { [formKey]: { ...values.result[formKey], ...presetValues }, _: actionKey } : { ...task.result ?? {}, ...values.result }
105
- });
106
- task.changed("result", true);
107
- const handler = instruction.formTypes.get(forms[formKey].type);
108
- if (handler && task.status) {
109
- await handler.call(instruction, task, forms[formKey], processor);
186
+ return presetValues;
187
+ };
188
+ let shouldResume = false;
189
+ try {
190
+ const lock = await context.app.lockManager.tryAcquire((0, import_plugin_workflow.getJobLockKey)(task.job.id));
191
+ await lock.runExclusive(async () => {
192
+ let presetValues = {};
193
+ if (!usesMainDataSource) {
194
+ await Promise.all([task.reload(), task.job.reload(), task.execution.reload()]);
195
+ validateTask();
196
+ presetValues = await handleFormSubmission();
197
+ }
198
+ await context.db.sequelize.transaction(transactionOptions, async (transaction) => {
199
+ await Promise.all([
200
+ task.reload({ transaction }),
201
+ task.job.reload({ transaction }),
202
+ task.execution.reload({ transaction })
203
+ ]);
204
+ validateTask();
205
+ if (usesMainDataSource) {
206
+ await handleFormSubmission(transaction);
207
+ } else {
208
+ setTaskResult(presetValues);
209
+ }
210
+ await task.save({ transaction });
211
+ await updateJobByManualTasks(task.job, task.node, context.db, task, transaction);
212
+ shouldResume = task.job.status !== import_plugin_workflow.JOB_STATUS.PENDING;
213
+ });
214
+ }, 6e4);
215
+ } catch (error) {
216
+ if ((0, import_plugin_workflow.isLockAcquireError)(error)) {
217
+ return context.throw(409);
218
+ }
219
+ throw error;
110
220
  }
111
- await task.save();
112
- await processor.exit();
113
221
  context.body = task;
114
222
  context.status = 202;
115
223
  await next();
116
- if (task.execution.status !== import_plugin_workflow.EXECUTION_STATUS.STARTED) {
224
+ if (!shouldResume) {
117
225
  return;
118
226
  }
119
- task.job.execution = task.execution;
120
- task.job.latestTask = task;
121
- processor.logger.info(`manual node (${task.nodeId}) action trigger execution (${task.execution.id}) to resume`);
122
- plugin.resume(task.job);
227
+ plugin.getLogger(task.execution.workflowId).info(`manual node (${task.nodeId}) action trigger execution (${task.execution.id}) to resume`);
228
+ plugin.resume(task.job).catch(() => void 0);
123
229
  }
124
230
  async function listMine(context, next) {
125
231
  context.action.mergeParams({
@@ -6,9 +6,9 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
- import { Processor } from '@nocobase/plugin-workflow';
9
+ import type { Transaction } from '@nocobase/database';
10
10
  import ManualInstruction from '../ManualInstruction';
11
11
  export default function (this: ManualInstruction, instance: any, { dataSource, collection }: {
12
12
  dataSource?: string;
13
13
  collection: any;
14
- }, processor: Processor): Promise<void>;
14
+ }, transaction?: Transaction): Promise<void>;
@@ -29,7 +29,7 @@ __export(create_exports, {
29
29
  default: () => create_default
30
30
  });
31
31
  module.exports = __toCommonJS(create_exports);
32
- async function create_default(instance, { dataSource = "main", collection }, processor) {
32
+ async function create_default(instance, { dataSource = "main", collection }, transaction) {
33
33
  const repo = this.workflow.app.dataSourceManager.dataSources.get(dataSource).collectionManager.getRepository(collection);
34
34
  if (!repo) {
35
35
  throw new Error(`collection ${collection} for create data on manual node not found`);
@@ -43,8 +43,8 @@ async function create_default(instance, { dataSource = "main", collection }, pro
43
43
  updatedBy: instance.userId
44
44
  },
45
45
  context: {
46
- executionId: processor.execution.id
46
+ executionId: instance.executionId
47
47
  },
48
- transaction: processor.transaction
48
+ transaction
49
49
  });
50
50
  }
@@ -6,9 +6,9 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
- import { Processor } from '@nocobase/plugin-workflow';
9
+ import type { Transaction } from '@nocobase/database';
10
10
  import ManualInstruction from '../ManualInstruction';
11
- export type FormHandler = (this: ManualInstruction, instance: any, formConfig: any, processor: Processor) => Promise<void>;
11
+ export type FormHandler = (this: ManualInstruction, instance: any, formConfig: any, transaction?: Transaction) => Promise<void>;
12
12
  export default function ({ formTypes }: {
13
13
  formTypes: any;
14
14
  }): void;
@@ -6,10 +6,10 @@
6
6
  * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
7
  * For more information, please refer to: https://www.nocobase.com/agreement.
8
8
  */
9
- import { Processor } from '@nocobase/plugin-workflow';
9
+ import type { Transaction } from '@nocobase/database';
10
10
  import ManualInstruction from '../ManualInstruction';
11
11
  export default function (this: ManualInstruction, instance: any, { dataSource, collection, filter }: {
12
12
  dataSource?: string;
13
13
  collection: any;
14
14
  filter?: {};
15
- }, processor: Processor): Promise<void>;
15
+ }, transaction?: Transaction): Promise<void>;
@@ -29,7 +29,7 @@ __export(update_exports, {
29
29
  default: () => update_default
30
30
  });
31
31
  module.exports = __toCommonJS(update_exports);
32
- async function update_default(instance, { dataSource = "main", collection, filter = {} }, processor) {
32
+ async function update_default(instance, { dataSource = "main", collection, filter = {} }, transaction) {
33
33
  const repo = this.workflow.app.dataSourceManager.dataSources.get(dataSource).collectionManager.getRepository(collection);
34
34
  if (!repo) {
35
35
  throw new Error(`collection ${collection} for update data on manual node not found`);
@@ -37,14 +37,14 @@ async function update_default(instance, { dataSource = "main", collection, filte
37
37
  const { _, ...form } = instance.result;
38
38
  const [values] = Object.values(form);
39
39
  await repo.update({
40
- filter: processor.getParsedValue(filter, instance.nodeId),
40
+ filter,
41
41
  values: {
42
42
  ...values ?? {},
43
43
  updatedBy: instance.userId
44
44
  },
45
45
  context: {
46
- executionId: processor.execution.id
46
+ executionId: instance.executionId
47
47
  },
48
- transaction: processor.transaction
48
+ transaction
49
49
  });
50
50
  }
@@ -0,0 +1,13 @@
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
+ */
9
+ import { Migration } from '@nocobase/server';
10
+ export default class extends Migration {
11
+ on: string;
12
+ up(): Promise<void>;
13
+ }
@@ -0,0 +1,51 @@
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
+ */
9
+
10
+ var __create = Object.create;
11
+ var __defProp = Object.defineProperty;
12
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
13
+ var __getOwnPropNames = Object.getOwnPropertyNames;
14
+ var __getProtoOf = Object.getPrototypeOf;
15
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
+ var rebuild_workflow_task_stats_exports = {};
38
+ __export(rebuild_workflow_task_stats_exports, {
39
+ default: () => rebuild_workflow_task_stats_default
40
+ });
41
+ module.exports = __toCommonJS(rebuild_workflow_task_stats_exports);
42
+ var import_plugin_workflow = __toESM(require("@nocobase/plugin-workflow"));
43
+ var import_server = require("@nocobase/server");
44
+ var import_constants = require("../../common/constants");
45
+ class rebuild_workflow_task_stats_default extends import_server.Migration {
46
+ on = "afterLoad";
47
+ async up() {
48
+ const workflowPlugin = this.pm.get(import_plugin_workflow.default);
49
+ await workflowPlugin.repairTaskStats({ types: [import_constants.TASK_TYPE_MANUAL], silent: true });
50
+ }
51
+ }
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "description": "Could be used for workflows which some of decisions are made by users.",
7
7
  "description.ru-RU": "Может использоваться в рабочих процессах, где какие-то решения принимаются пользователями.",
8
8
  "description.zh-CN": "用于人工控制部分决策的流程。",
9
- "version": "2.2.0-beta.9",
9
+ "version": "3.0.0-alpha.1",
10
10
  "license": "Apache-2.0",
11
11
  "main": "./dist/server/index.js",
12
12
  "homepage": "https://docs.nocobase.com/handbook/workflow-manual",
@@ -26,7 +26,9 @@
26
26
  },
27
27
  "peerDependencies": {
28
28
  "@nocobase/client": "2.x",
29
+ "@nocobase/client-v2": "2.x",
29
30
  "@nocobase/database": "2.x",
31
+ "@nocobase/flow-engine": "2.x",
30
32
  "@nocobase/plugin-data-source-main": "2.x",
31
33
  "@nocobase/plugin-mobile": "2.x",
32
34
  "@nocobase/plugin-users": "2.x",
@@ -35,7 +37,7 @@
35
37
  "@nocobase/test": "2.x",
36
38
  "@nocobase/utils": "2.x"
37
39
  },
38
- "gitHead": "60e3d7abbaa0c7cead76f71a4f3d5eedb6b8acdb",
40
+ "gitHead": "22d8be8ece179cfa5c8a4ebb2c896c92bd418e03",
39
41
  "keywords": [
40
42
  "Workflow"
41
43
  ]