@nocobase/app-skills 0.1.0-beta.65 → 0.1.0-beta.66
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.
- package/LICENSE.txt +24 -26
- package/package.json +1 -1
- package/skills/nocobase-app-development/SKILL.md +3 -0
- package/skills/nocobase-app-development/assets/business-examples/index.json +2 -0
- package/skills/nocobase-app-development/assets/business-examples/onboarding/database/main/migrations/202611130005_onboarding_definition_binding.ts +37 -0
- package/skills/nocobase-app-development/assets/business-examples/onboarding/server/lifecycles/onboarding.ts +3 -0
- package/skills/nocobase-app-development/assets/business-examples/onboarding/server/providers/onboarding.ts +19 -9
- package/skills/nocobase-app-development/assets/business-examples/onboarding/tests/database/onboarding.test.ts +46 -0
- package/skills/nocobase-app-development/assets/business-examples/procurement/database/main/migrations/202611130004_procurement_definition_binding.ts +37 -0
- package/skills/nocobase-app-development/assets/business-examples/procurement/server/lifecycles/procurement.ts +3 -0
- package/skills/nocobase-app-development/assets/business-examples/procurement/server/providers/procurement.ts +19 -9
- package/skills/nocobase-app-development/assets/business-examples/procurement/tests/database/procurement.test.ts +44 -0
- package/skills/nocobase-app-development/references/business-administration.md +1 -1
- package/skills/nocobase-app-development/references/lifecycle-parameters.md +44 -67
- package/skills/nocobase-app-development/references/lifecycle-ui.md +14 -6
- package/skills/nocobase-app-development/references/lifecycle-versions.md +83 -0
- package/skills/nocobase-app-development/references/lifecycle.md +19 -9
- package/skills/nocobase-app-development/references/system-settings.md +2 -2
- package/skills/nocobase-app-upgrade/SKILL.md +2 -0
- package/skills/nocobase-app-upgrade/references/lifecycle-versioning-upgrade.md +47 -0
package/LICENSE.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Updated Date: November
|
|
1
|
+
Updated Date: November 16, 2026
|
|
2
2
|
|
|
3
3
|
NocoBase License Agreement
|
|
4
4
|
|
|
@@ -14,27 +14,21 @@ The Company reserves the right to formulate and modify this Agreement from time
|
|
|
14
14
|
1. Definitions
|
|
15
15
|
==============
|
|
16
16
|
|
|
17
|
-
1.1 "Software" refers to NocoBase,
|
|
17
|
+
1.1 "Software" refers to NocoBase, including its application foundation (Core), its workspace for people and agents building software together (Studio), and the application templates, development standards, and development skills that come with them, together with their source code, installation packages, images, and all their modifications, updates, and upgrades.
|
|
18
18
|
|
|
19
|
-
1.2 "
|
|
19
|
+
1.2 "Community Edition" refers to the free version of the Software provided to the User as open source through public channels.
|
|
20
20
|
|
|
21
|
-
1.3 "
|
|
21
|
+
1.3 "Commercial Edition" refers to the paid version of the Software purchased by the User from the Company or its agents, downloaded through exclusive channels, with additional features and benefits. It consists of two versions: Professional Edition and Enterprise Edition.
|
|
22
22
|
|
|
23
|
-
1.4 "
|
|
23
|
+
1.4 "Application" refers to a specific business use case application serving internal or external customers of the User, developed based on the Software, such as ERP/CRM. Studio is a development tool and is not part of any Application.
|
|
24
24
|
|
|
25
|
-
1.5 "
|
|
25
|
+
1.5 "Customer" refers to the clients who commission the User to develop Applications or purchase the User's Applications.
|
|
26
26
|
|
|
27
|
-
1.6 "
|
|
27
|
+
1.6 "Agent" refers to an AI agent that works with the Software, including the coding agents the User uses to develop Applications and the business agents in Applications.
|
|
28
28
|
|
|
29
|
-
1.7 "
|
|
29
|
+
1.7 "Third-Party Services" refers to the large models, coding agents, cloud services, and other third-party products and services that the User chooses to use with the Software.
|
|
30
30
|
|
|
31
|
-
1.8 "
|
|
32
|
-
|
|
33
|
-
1.9 "Agent" refers to an AI agent that works with the Software, including the coding agents the User uses to develop Applications and the business agents in Applications.
|
|
34
|
-
|
|
35
|
-
1.10 "Third-Party Services" refers to the large models, coding agents, cloud services, and other third-party products and services that the User chooses to use with the Software.
|
|
36
|
-
|
|
37
|
-
1.11 "Third-Party Open Source Software" refers to open source software provided with the Software. They are licensed through various published open source software licenses or copyright notices accompanying such software.
|
|
31
|
+
1.8 "Third-Party Open Source Software" refers to open source software provided with the Software. They are licensed through various published open source software licenses or copyright notices accompanying such software.
|
|
38
32
|
|
|
39
33
|
===================================
|
|
40
34
|
2. Intellectual Property Protection
|
|
@@ -62,9 +56,9 @@ The Company claims no intellectual property rights in the business code written
|
|
|
62
56
|
|
|
63
57
|
4.1 This Agreement serves as the unified license agreement for NocoBase Software, applying to both the Community Edition and the Commercial Editions.
|
|
64
58
|
|
|
65
|
-
4.2
|
|
59
|
+
4.2 The Community Edition is open source software. This Agreement incorporates and references the full text of the Apache License, Version 2.0 ("Apache-2.0", available at: https://www.apache.org/licenses/LICENSE-2.0 ). Users of the Community Edition must comply with the Apache-2.0 License as well as the supplementary terms set forth in this Agreement. In case of any inconsistency between Apache-2.0 and this Agreement, the supplementary terms of this Agreement shall prevail.
|
|
66
60
|
|
|
67
|
-
4.3
|
|
61
|
+
4.3 The features that the Commercial Edition adds to the Community Edition are commercial software of the Company and are not licensed under Apache-2.0. They can only be used under the Commercial License and in accordance with this Agreement.
|
|
68
62
|
|
|
69
63
|
================================================
|
|
70
64
|
5. Rights and Obligations of Open Source License
|
|
@@ -76,7 +70,9 @@ The Company claims no intellectual property rights in the business code written
|
|
|
76
70
|
|
|
77
71
|
5.3 It is not allowed to remove or change all intellectual property statements about NocoBase in the code.
|
|
78
72
|
|
|
79
|
-
5.4 It is not allowed to provide to the public any form of AI application development platform or agent development platform SaaS/PaaS products using the original or modified Software.
|
|
73
|
+
5.4 It is not allowed to provide to the public any form of AI application development platform or agent development platform SaaS/PaaS products using the original or modified Software, including Studio.
|
|
74
|
+
|
|
75
|
+
5.5 It is not allowed to publicly release any plugin, skill, application template, or other extension that provides features identical or substantially similar to those of the Commercial Edition, whether free or paid and whether open source or not, including by publishing it to public code repositories, package registries, marketplaces, or websites, or by providing it to the public as a hosted service. The features of the Commercial Edition are as published on the Company's website. Developing and using such features for the User's own business, or providing them within Applications delivered to Customers, is not subject to this restriction.
|
|
80
76
|
|
|
81
77
|
===============================
|
|
82
78
|
6. Rights of Commercial License
|
|
@@ -84,11 +80,11 @@ The Company claims no intellectual property rights in the business code written
|
|
|
84
80
|
|
|
85
81
|
6.1 Obtain a permanent commercial license of the Software.
|
|
86
82
|
|
|
87
|
-
6.2 Can develop Applications for Customers, deploy the completed Applications, including the Commercial
|
|
83
|
+
6.2 Can develop Applications for Customers, deploy the completed Applications, including the Commercial Edition features they use, on Customers' servers, or host them and provide them to Customers as a service.
|
|
88
84
|
|
|
89
|
-
6.3 Customers can use the Commercial
|
|
85
|
+
6.3 Customers can use the Commercial Edition features in the Applications delivered to them, within those Applications only, and can continue to develop those Applications on their own or through others.
|
|
90
86
|
|
|
91
|
-
6.4 Get software upgrades and exclusive technical support during the upgrade validity period. Upgrades and technical support are provided to the User only, and the User can upgrade the
|
|
87
|
+
6.4 Get software upgrades and exclusive technical support during the upgrade validity period. Upgrades and technical support are provided to the User only, and the User can upgrade the Applications delivered to Customers during this period.
|
|
92
88
|
|
|
93
89
|
6.5 The licensed Software can be used for commercial purposes with no restrictions on the number of Applications, Customers, users, and Agents.
|
|
94
90
|
|
|
@@ -106,15 +102,17 @@ The Company claims no intellectual property rights in the business code written
|
|
|
106
102
|
|
|
107
103
|
7.3 It is not allowed to sell, transfer, lease, share, or distribute any form of AI application development platform, agent development platform, or developer tools developed based on Software.
|
|
108
104
|
|
|
109
|
-
7.4 It is not allowed to provide any form of AI application development platform or agent development platform SaaS/PaaS products to the public using the original or modified Software.
|
|
105
|
+
7.4 It is not allowed to provide any form of AI application development platform or agent development platform SaaS/PaaS products to the public using the original or modified Software, including Studio.
|
|
106
|
+
|
|
107
|
+
7.5 It is not allowed to publicly release any plugin, skill, application template, or other extension that provides features identical or substantially similar to those of the Commercial Edition, whether free or paid and whether open source or not, including by publishing it to public code repositories, package registries, marketplaces, or websites, or by providing it to the public as a hosted service. The features of the Commercial Edition are as published on the Company's website. Developing and using such features for the User's own business, or providing them within Applications delivered to Customers, is not subject to this restriction.
|
|
110
108
|
|
|
111
|
-
7.
|
|
109
|
+
7.6 The Commercial Edition can only be used by the User holding the Commercial License, on servers owned or rented by the User. Except for delivering Applications under 6.2, it is not allowed to deploy the Commercial Edition for Customers, or to provide it to Customers or any third party in any form, including as a hosted service. Customers that need the Commercial Edition shall purchase their own Commercial License.
|
|
112
110
|
|
|
113
|
-
7.
|
|
111
|
+
7.7 Customer personnel can take part in requirement confirmation, acceptance, and release approval in the User's Studio for the Applications the User develops for them. This is not considered providing the Commercial Edition to Customers, but it is not allowed to let Customers use the User's Studio to develop their own projects.
|
|
114
112
|
|
|
115
|
-
7.
|
|
113
|
+
7.8 If there is a violation of the above obligations or the terms of this Agreement, the rights owned by the User will be immediately terminated, the paid fees will not be refunded, and the Company reserves the right to pursue the User's legal responsibility.
|
|
116
114
|
|
|
117
|
-
7.
|
|
115
|
+
7.9 If there are other agreements in the contract for the above obligations, the contract agreement shall prevail.
|
|
118
116
|
|
|
119
117
|
=============================================================
|
|
120
118
|
8. Legal Jurisdiction, Interpretation, and Dispute Resolution
|
package/package.json
CHANGED
|
@@ -81,6 +81,8 @@ For approval requirements, check `@nocobase/app-plugin-approval` first and follo
|
|
|
81
81
|
|
|
82
82
|
When the stages of a business record are fixed by developers rather than drawn by administrators — an expense report, a ticket, a contract, an order — build it with `@nocobase/lifecycle` as [record lifecycles](references/lifecycle.md) describes: the state stays in the record's own field and changes only through declared transitions. Declare only required business paths with precise sources and destinations; the diagram expands every `from × to` pair rather than analyzing routing logic. Follow [readable process graphs](references/lifecycle-ui.md#keep-process-graphs-readable) before rendering dense definitions.
|
|
83
83
|
|
|
84
|
+
Before changing lifecycle behavior or removing a version, read [versions of a process](references/lifecycle-versions.md): behavior freezes against the target main branch, unmerged new versions can be edited continuously, and deleting a frozen version requires explicit user retirement confirmation.
|
|
85
|
+
|
|
84
86
|
For notification configuration or sending, follow the notification plugin Skill: `notification.channels` maps each name to one flat channel configuration with `type` (`provider` remains a compatibility alias), and `send({ idempotencyKey, messages })` supplies a complete message per Channel. Use native addresses; email and in-app arrays create independent deliveries, while Webhooks forbid `to`.
|
|
85
87
|
|
|
86
88
|
Install, update and customize plugins, and remove a direct NocoBase package, as [plugins](references/plugins.md) describes: `pnpm nocobase plugin register`, `plugin update` and `package remove` keep the manifest, the lockfile, the composition roots and the synchronized Skills consistent, so never hand-edit only one of them.
|
|
@@ -164,6 +166,7 @@ Read the page for the task in front of you. Do not read all of them.
|
|
|
164
166
|
| A record that moves through stages defined in code: simple confirmations, tickets, orders, timeouts, effects after a state change | [record lifecycles](references/lifecycle.md) |
|
|
165
167
|
| Administrator-adjustable approval departments, reviewers, thresholds or business values in a code-defined lifecycle | [configurable lifecycle parameters](references/lifecycle-parameters.md); keep workflow structure in source. For management forms and optional diagram-bound editing, see [Lifecycle UI](references/lifecycle-ui.md). |
|
|
166
168
|
| Lifecycle definition catalogs, execution lists, process details, history or parameter settings | [Lifecycle UI](references/lifecycle-ui.md) |
|
|
169
|
+
| Changing lifecycle behavior, adding or deleting a version, or choosing an entry point's version | [versions of a process](references/lifecycle-versions.md) |
|
|
167
170
|
| Flowcharts, process diagrams or lifecycle state diagrams | Use UI Library `@nocobase/flow-diagram` for generic graphs and `@nocobase/lifecycle-diagram` for lifecycle descriptions; see [diagram guidance](references/lifecycle.md#draw-an-interactive-lifecycle-diagram) and the [UI catalog](references/frontend/references/ui-library.md#diagrams). Preserve their application theme tokens. |
|
|
168
171
|
| Use `@nocobase/app-testing` for database, server, client or CLI tests; verify before finishing | [testing and verification](references/testing.md) |
|
|
169
172
|
| Run a CLI command: configure, migrate, manage plugins, read the data model | [the command line](references/cli.md) |
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
"server/providers/procurement-reset.ts",
|
|
16
16
|
"server/lifecycles/procurement.ts",
|
|
17
17
|
"database/main/migrations/202611040001_create_procurement.ts",
|
|
18
|
+
"database/main/migrations/202611130004_procurement_definition_binding.ts",
|
|
18
19
|
"database/main/seeds/202611040001_procurement.ts",
|
|
19
20
|
"database/main/seeds/202611040002_procurement_samples.ts",
|
|
20
21
|
"cli/commands/procurement-reset.ts",
|
|
@@ -127,6 +128,7 @@
|
|
|
127
128
|
"server/providers/onboarding-reset.ts",
|
|
128
129
|
"server/lifecycles/onboarding.ts",
|
|
129
130
|
"database/main/migrations/202611050001_create_onboarding.ts",
|
|
131
|
+
"database/main/migrations/202611130005_onboarding_definition_binding.ts",
|
|
130
132
|
"database/main/seeds/202611050001_onboarding.ts",
|
|
131
133
|
"database/main/seeds/202611050002_onboarding_samples.ts",
|
|
132
134
|
"cli/commands/onboarding-reset.ts",
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { defineMigration, type MigrationDefinition } from '@nocobase/db';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Each record names the lifecycle definition that created it, so a second
|
|
5
|
+
* version of a process can run on the same table without either version
|
|
6
|
+
* reading or moving the other's records. Every record here was created by
|
|
7
|
+
* the only definition its table has ever had, so that name is the reliable
|
|
8
|
+
* binding; a value already present is kept.
|
|
9
|
+
*/
|
|
10
|
+
const BINDINGS: readonly (readonly [collection: string, definition: string])[] =
|
|
11
|
+
[
|
|
12
|
+
['onboardingCases', 'onboarding'],
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
const migration: MigrationDefinition = defineMigration({
|
|
16
|
+
name: '202611130005_onboarding_definition_binding',
|
|
17
|
+
async up({ builder, query }) {
|
|
18
|
+
for (const [collection, definition] of BINDINGS) {
|
|
19
|
+
await builder.alterCollection(collection, (table) => {
|
|
20
|
+
table.string('lifecycleDefinition').nullable();
|
|
21
|
+
});
|
|
22
|
+
await query
|
|
23
|
+
.updateTable(collection)
|
|
24
|
+
.set({ lifecycleDefinition: definition })
|
|
25
|
+
.where('lifecycleDefinition', 'is', null)
|
|
26
|
+
.execute();
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
async down({ builder }) {
|
|
30
|
+
for (const [collection] of [...BINDINGS].reverse())
|
|
31
|
+
await builder.alterCollection(collection, (table) => {
|
|
32
|
+
table.dropField('lifecycleDefinition');
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export default migration;
|
|
@@ -7,6 +7,9 @@ export const onboardingLifecycle = defineLifecycle<{
|
|
|
7
7
|
state: 'draft' | 'submitted';
|
|
8
8
|
}>({
|
|
9
9
|
name: 'onboarding',
|
|
10
|
+
key: 'onboarding',
|
|
11
|
+
version: 1,
|
|
12
|
+
definitionField: 'lifecycleDefinition',
|
|
10
13
|
collection: 'onboardingCases',
|
|
11
14
|
initial: 'draft',
|
|
12
15
|
states: ['draft', { name: 'submitted', final: true }],
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import type { DatabaseConnection, Row, FilterBuilder } from '@nocobase/db';
|
|
3
3
|
import type { AppAuthorization } from '@nocobase/app-plugin-authorization';
|
|
4
|
-
import type { LifecycleRuntime } from '@nocobase/lifecycle';
|
|
4
|
+
import type { LifecycleRecord, LifecycleRuntime } from '@nocobase/lifecycle';
|
|
5
5
|
import { ApiError } from '@nocobase/app-server/router';
|
|
6
6
|
import {
|
|
7
7
|
ONBOARDING_ACCESS,
|
|
@@ -160,7 +160,12 @@ export class OnboardingService {
|
|
|
160
160
|
.repository('onboardingEmployees')
|
|
161
161
|
.findOne({ filter: { caseId: id } })
|
|
162
162
|
: null,
|
|
163
|
-
|
|
163
|
+
// The version the case is bound to, whichever is the latest.
|
|
164
|
+
this.runtime.view(
|
|
165
|
+
this.runtime.recordLifecycle('onboarding', row as LifecycleRecord),
|
|
166
|
+
id,
|
|
167
|
+
{ id: actor.id },
|
|
168
|
+
),
|
|
164
169
|
]);
|
|
165
170
|
const editable =
|
|
166
171
|
actor.coordinate &&
|
|
@@ -345,13 +350,18 @@ export class OnboardingService {
|
|
|
345
350
|
);
|
|
346
351
|
await this.validateDepartment(parsed.data.departmentId, actor, tx);
|
|
347
352
|
// Native lifecycle version checks serialize edits/submissions of this case.
|
|
348
|
-
await this.runtime.fire(
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
353
|
+
await this.runtime.fire(
|
|
354
|
+
this.runtime.recordLifecycle('onboarding', row as LifecycleRecord),
|
|
355
|
+
id,
|
|
356
|
+
'submit',
|
|
357
|
+
{
|
|
358
|
+
actor: { id: actor.id },
|
|
359
|
+
manual: true,
|
|
360
|
+
expect: { version },
|
|
361
|
+
requestId: key,
|
|
362
|
+
transaction: tx,
|
|
363
|
+
},
|
|
364
|
+
);
|
|
355
365
|
email = parsed.data.workEmail;
|
|
356
366
|
if (
|
|
357
367
|
await tx
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { describeMigration } from '@nocobase/app-testing/server';
|
|
3
|
+
import { expect } from 'vitest';
|
|
3
4
|
|
|
4
5
|
describeMigration('202611050001_create_onboarding', {
|
|
5
6
|
sources: [
|
|
@@ -52,3 +53,48 @@ describeMigration('202611050001_create_onboarding', {
|
|
|
52
53
|
await expectCollection(name).not.toExist();
|
|
53
54
|
},
|
|
54
55
|
});
|
|
56
|
+
|
|
57
|
+
// A case written before the binding column belongs to the only definition
|
|
58
|
+
// the table has had.
|
|
59
|
+
describeMigration('202611130005_onboarding_definition_binding', {
|
|
60
|
+
sources: [
|
|
61
|
+
{
|
|
62
|
+
packageName: 'onboarding-test',
|
|
63
|
+
directory: path.resolve(
|
|
64
|
+
import.meta.dirname,
|
|
65
|
+
'../../database/main/migrations',
|
|
66
|
+
),
|
|
67
|
+
},
|
|
68
|
+
],
|
|
69
|
+
async before({ connection }) {
|
|
70
|
+
await connection.repository('onboardingCases').createOne({
|
|
71
|
+
values: {
|
|
72
|
+
id: 'case-before-binding',
|
|
73
|
+
fullName: 'Lin Wei',
|
|
74
|
+
workEmail: 'lin@example.com',
|
|
75
|
+
nationality: 'CN',
|
|
76
|
+
jobTitle: 'Engineer',
|
|
77
|
+
startDate: '2026-12-01',
|
|
78
|
+
contractEndDate: '2027-12-01',
|
|
79
|
+
coordinatorId: 'chen',
|
|
80
|
+
status: 'draft',
|
|
81
|
+
statusChangedAt: '2026-11-01T00:00:00.000Z',
|
|
82
|
+
lifecycleVersion: 1,
|
|
83
|
+
createdAt: '2026-11-01T00:00:00.000Z',
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
async up({ connection, expectCollection }) {
|
|
88
|
+
await expectCollection('onboardingCases').toHaveField(
|
|
89
|
+
'lifecycleDefinition',
|
|
90
|
+
{ type: 'string', nullable: true },
|
|
91
|
+
);
|
|
92
|
+
const rows = await connection.repository('onboardingCases').findMany({});
|
|
93
|
+
expect(rows.map((row) => row.lifecycleDefinition)).toEqual(['onboarding']);
|
|
94
|
+
},
|
|
95
|
+
async down({ expectCollection }) {
|
|
96
|
+
await expectCollection('onboardingCases').not.toHaveField(
|
|
97
|
+
'lifecycleDefinition',
|
|
98
|
+
);
|
|
99
|
+
},
|
|
100
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { defineMigration, type MigrationDefinition } from '@nocobase/db';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Each record names the lifecycle definition that created it, so a second
|
|
5
|
+
* version of a process can run on the same table without either version
|
|
6
|
+
* reading or moving the other's records. Every record here was created by
|
|
7
|
+
* the only definition its table has ever had, so that name is the reliable
|
|
8
|
+
* binding; a value already present is kept.
|
|
9
|
+
*/
|
|
10
|
+
const BINDINGS: readonly (readonly [collection: string, definition: string])[] =
|
|
11
|
+
[
|
|
12
|
+
['procurementRequests', 'procurement'],
|
|
13
|
+
];
|
|
14
|
+
|
|
15
|
+
const migration: MigrationDefinition = defineMigration({
|
|
16
|
+
name: '202611130004_procurement_definition_binding',
|
|
17
|
+
async up({ builder, query }) {
|
|
18
|
+
for (const [collection, definition] of BINDINGS) {
|
|
19
|
+
await builder.alterCollection(collection, (table) => {
|
|
20
|
+
table.string('lifecycleDefinition').nullable();
|
|
21
|
+
});
|
|
22
|
+
await query
|
|
23
|
+
.updateTable(collection)
|
|
24
|
+
.set({ lifecycleDefinition: definition })
|
|
25
|
+
.where('lifecycleDefinition', 'is', null)
|
|
26
|
+
.execute();
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
async down({ builder }) {
|
|
30
|
+
for (const [collection] of [...BINDINGS].reverse())
|
|
31
|
+
await builder.alterCollection(collection, (table) => {
|
|
32
|
+
table.dropField('lifecycleDefinition');
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
export default migration;
|
|
@@ -23,6 +23,9 @@ const reviewer = ({
|
|
|
23
23
|
// Capability checks and transaction-bound reference/amount checks belong to the service.
|
|
24
24
|
export const procurementLifecycle = defineLifecycle<Types>({
|
|
25
25
|
name: 'procurement',
|
|
26
|
+
key: 'procurement',
|
|
27
|
+
version: 1,
|
|
28
|
+
definitionField: 'lifecycleDefinition',
|
|
26
29
|
collection: 'procurementRequests',
|
|
27
30
|
initial: 'draft',
|
|
28
31
|
states: ['draft', 'submitted', 'rejected', { name: 'approved', final: true }],
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import type { DatabaseConnection, Row } from '@nocobase/db';
|
|
3
3
|
import type { AppAuthorization } from '@nocobase/app-plugin-authorization';
|
|
4
|
-
import type { LifecycleRuntime } from '@nocobase/lifecycle';
|
|
4
|
+
import type { LifecycleRecord, LifecycleRuntime } from '@nocobase/lifecycle';
|
|
5
5
|
import { ApiError } from '@nocobase/app-server/router';
|
|
6
6
|
import {
|
|
7
7
|
amount,
|
|
@@ -194,7 +194,12 @@ export class ProcurementService {
|
|
|
194
194
|
filter: { requestId: id },
|
|
195
195
|
sort: (s) => s.field('position').asc(),
|
|
196
196
|
});
|
|
197
|
-
|
|
197
|
+
// The version the request is bound to, whichever is the latest.
|
|
198
|
+
const view = await this.runtime.view(
|
|
199
|
+
this.runtime.recordLifecycle('procurement', row as LifecycleRecord),
|
|
200
|
+
id,
|
|
201
|
+
{ id: actor.id },
|
|
202
|
+
);
|
|
198
203
|
const editable =
|
|
199
204
|
actor.request &&
|
|
200
205
|
row.applicantId === actor.id &&
|
|
@@ -475,13 +480,18 @@ export class ProcurementService {
|
|
|
475
480
|
'Only the designated reviewer can decide.',
|
|
476
481
|
'PERMISSION_DENIED',
|
|
477
482
|
);
|
|
478
|
-
const result = await this.runtime.fire(
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
483
|
+
const result = await this.runtime.fire(
|
|
484
|
+
this.runtime.recordLifecycle('procurement', row as LifecycleRecord),
|
|
485
|
+
id,
|
|
486
|
+
transition,
|
|
487
|
+
{
|
|
488
|
+
actor: { id: actor.id },
|
|
489
|
+
manual: true,
|
|
490
|
+
expect: { version },
|
|
491
|
+
requestId,
|
|
492
|
+
transaction: tx,
|
|
493
|
+
},
|
|
494
|
+
);
|
|
485
495
|
return { id, replayed: result.replayed === true };
|
|
486
496
|
});
|
|
487
497
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
2
|
import { describeMigration } from '@nocobase/app-testing/server';
|
|
3
|
+
import { expect } from 'vitest';
|
|
3
4
|
|
|
4
5
|
describeMigration('202611040001_create_procurement', {
|
|
5
6
|
sources: [
|
|
@@ -46,3 +47,46 @@ describeMigration('202611040001_create_procurement', {
|
|
|
46
47
|
await expectCollection(name).not.toExist();
|
|
47
48
|
},
|
|
48
49
|
});
|
|
50
|
+
|
|
51
|
+
// A request written before the binding column belongs to the only
|
|
52
|
+
// definition the table has had.
|
|
53
|
+
describeMigration('202611130004_procurement_definition_binding', {
|
|
54
|
+
sources: [
|
|
55
|
+
{
|
|
56
|
+
packageName: 'procurement-test',
|
|
57
|
+
directory: path.resolve(
|
|
58
|
+
import.meta.dirname,
|
|
59
|
+
'../../database/main/migrations',
|
|
60
|
+
),
|
|
61
|
+
},
|
|
62
|
+
],
|
|
63
|
+
async before({ connection }) {
|
|
64
|
+
await connection.repository('procurementRequests').createOne({
|
|
65
|
+
values: {
|
|
66
|
+
id: 'request-before-binding',
|
|
67
|
+
title: 'Notebooks',
|
|
68
|
+
applicantId: 'lin',
|
|
69
|
+
status: 'draft',
|
|
70
|
+
statusChangedAt: '2026-11-01T00:00:00.000Z',
|
|
71
|
+
lifecycleVersion: 1,
|
|
72
|
+
totalMinor: 1250,
|
|
73
|
+
createdAt: '2026-11-01T00:00:00.000Z',
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
},
|
|
77
|
+
async up({ connection, expectCollection }) {
|
|
78
|
+
await expectCollection('procurementRequests').toHaveField(
|
|
79
|
+
'lifecycleDefinition',
|
|
80
|
+
{ type: 'string', nullable: true },
|
|
81
|
+
);
|
|
82
|
+
const rows = await connection
|
|
83
|
+
.repository('procurementRequests')
|
|
84
|
+
.findMany({});
|
|
85
|
+
expect(rows.map((row) => row.lifecycleDefinition)).toEqual(['procurement']);
|
|
86
|
+
},
|
|
87
|
+
async down({ expectCollection }) {
|
|
88
|
+
await expectCollection('procurementRequests').not.toHaveField(
|
|
89
|
+
'lifecycleDefinition',
|
|
90
|
+
);
|
|
91
|
+
},
|
|
92
|
+
});
|
|
@@ -15,7 +15,7 @@ Use these recipes with [system settings delivery](system-settings.md) whenever a
|
|
|
15
15
|
|
|
16
16
|
Extract administrator-owned values from actual business rules even without a configurability request: amounts, quantities, validity windows, warnings, supported switches or shared defaults. Keep authorization guards, workflow structure, technical constants and secrets source-owned. Infer administrator ownership from the business purpose and expected maintenance rather than requiring explicit "configurable" wording. Fixed technical/application invariants remain source-owned.
|
|
17
17
|
|
|
18
|
-
For a lifecycle, use [configurable lifecycle parameters](lifecycle-parameters.md), including explicit groups/bindings, complete-
|
|
18
|
+
For a lifecycle, use [configurable lifecycle parameters](lifecycle-parameters.md), including explicit groups/bindings, complete-version saves, server validation, explicit startup snapshots and usage history. For policy outside a lifecycle, inspect the application's existing service; otherwise implement an application-owned settings record with a stable key, typed payload, scope and revision. Use documented Repository/transaction contracts, reject undeclared fields, and compare the revision atomically when saving. The update response returns the effective saved values and revision; a stale write reports a conflict without overwriting either editor's work. This recipe does not add a generic platform configuration API.
|
|
19
19
|
|
|
20
20
|
Choose defaults from the requested policy or existing authoritative configuration and preserve them when the page is first enabled. Show units, bounds, dependent constraints and effective timing. Resolve the saved values in the real server-side calculation, route or task construction; shared caches must be invalidated consistently. A form over an unchanged hard-coded condition is incomplete. Decide whether documents retain the policy used when created/submitted or use current policy later; financial amounts and historical facts must not be silently recalculated.
|
|
21
21
|
|
|
@@ -1,103 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Versioned parameter contracts and creation snapshots
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A definition version's parameter contract includes its field set, types, meaning, units, validation and defaults; it freezes when the version reaches the target main branch. Administrators edit one complete configuration revision for that concrete definition name. Different versions may reuse field names with different contracts; they never implicitly share configuration. A contract change to a frozen version requires a new definition version; a version newly introduced on the current branch can be revised until merged. Check compatibility with any saved configuration and snapshots when editing an unmerged contract, which may already have been deployed or used. Editing configuration values under the declared contract is separate: it affects future records and never replaces an existing instance snapshot.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
`LifecycleRuntime.create()` binds the concrete definition and freezes all effective parameters in the business transaction, including for an initial business state named `draft`. Draft is a business state, not a parameter mode. Later edits, submissions, withdrawals, returns, reopening, retries, continuations and worker restarts always use the same snapshot. To use new parameters, create a new record; there is no instance parameter replacement or rebinding API.
|
|
6
6
|
|
|
7
|
-
##
|
|
8
|
-
|
|
9
|
-
Declare defaults in `parameters` and a code-owned `parameterConfiguration` with groups. Every group has key, title, schemaVersion and fields; every field has type, title and a parse function returning its complete normalized JSON value. Optional field bindings name a state or transition. The flow declares readMode and snapshotTransition, and individual fields can override readMode. Groups can declare a validate function and sameReadMode arrays for joint invariants.
|
|
7
|
+
## Declare a configurable definition
|
|
10
8
|
|
|
11
9
|
```ts
|
|
12
|
-
import { StoredLifecycleParameters, type ParameterGroup } from '@nocobase/lifecycle';
|
|
13
|
-
import { z } from 'zod';
|
|
14
|
-
|
|
15
10
|
const thresholds: ParameterGroup = {
|
|
16
|
-
key: '
|
|
11
|
+
key: 'thresholds', title: 'Approval amounts (yuan)', schemaVersion: 1,
|
|
17
12
|
fields: {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
},
|
|
23
|
-
financeLimit: {
|
|
24
|
-
type: 'number', title: 'Finance review limit',
|
|
25
|
-
parse: (value) => z.number().finite().nonnegative().parse(value),
|
|
26
|
-
bindings: [{ state: 'financeReview' }],
|
|
27
|
-
},
|
|
28
|
-
},
|
|
29
|
-
sameReadMode: [['automaticLimit', 'financeLimit']],
|
|
30
|
-
validate: (values) => {
|
|
31
|
-
if (Number(values.automaticLimit) > Number(values.financeLimit))
|
|
32
|
-
throw new Error('Automatic approval cannot exceed the finance limit.');
|
|
13
|
+
limit: { type: 'number', title: 'Limit (yuan)', parse(value) {
|
|
14
|
+
if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) throw new Error('Expected a non-negative amount.');
|
|
15
|
+
return value;
|
|
16
|
+
} },
|
|
33
17
|
},
|
|
34
18
|
};
|
|
35
|
-
|
|
36
19
|
// In the definition:
|
|
37
|
-
parameters: {
|
|
38
|
-
parameterConfiguration: {
|
|
39
|
-
readMode: 'snapshot', snapshotTransition: 'submit', groups: [thresholds],
|
|
40
|
-
},
|
|
41
|
-
|
|
42
|
-
// Register on the application's existing lifecycle runtime:
|
|
43
|
-
runtime.register(expenseLifecycle, {
|
|
44
|
-
parameterConfiguration: {
|
|
45
|
-
store: new StoredLifecycleParameters(lifecycleStore, collectionNames),
|
|
46
|
-
scope: ({ record }) => scopeFromAuthoritativeRecord(record),
|
|
47
|
-
legacyRecord: (record) => record.parameterContract !== 1,
|
|
48
|
-
snapshotRequired: (record) => record.status !== 'draft',
|
|
49
|
-
},
|
|
50
|
-
});
|
|
20
|
+
parameters: { limit: 5000 },
|
|
21
|
+
parameterConfiguration: { groups: [thresholds] },
|
|
51
22
|
```
|
|
52
23
|
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
Resolve scope and record identity from server-owned context. Authenticate and authorize configuration read/write before validators or record lookup. In the save transaction validate referenced entities in that scope, then call `store.save({ scope, group, values, expectedRevision, requestId, actorId, at }, transactionHandle)`. Save exactly the complete declared group: never accept undeclared fields, schemaVersion, modes, workflow structure or client-provided effective values. A stale revision is a 409 configuration conflict; the same request and values replay its immutable version. Reused request IDs with different input fail. Only an absent configuration uses code defaults; read errors and incompatible schemas fail.
|
|
24
|
+
Register `parameterConfiguration: { store, scope }`. Scope is authoritative server context, not form input. `LifecycleParameterStore.readConfiguration(scope, lifecycle, transaction)` reads one complete immutable revision for the concrete definition; do not independently read mutable group heads. Save all groups as one revision with `configurationGroup(definition.name, definition.parameterConfiguration.groups)` and `store.save(...)`; groups organize the editor, not separate revisions. `WorkflowParameterStore` uses one CAS-protected row per definition.
|
|
56
25
|
|
|
57
|
-
|
|
26
|
+
Creation merges defaults with that revision and validates complete values and cross-field constraints once. The record, immutable definition binding, complete snapshot, creation entry, optional creation receipt and persisted execution facts share the transaction. Creation validation, state hooks and nested same-record operations reuse that resolution. A failure rolls back everything; asynchronous effects read the committed snapshot. No independent startup marker or deferred snapshot boundary exists.
|
|
58
27
|
|
|
59
|
-
|
|
28
|
+
With an existing record identity, `view`, `available`, `can`, `fire`, actions, triggers, effects, retries, continuations, recovery and instance diagrams read only its snapshot. A missing snapshot raises `PARAMETER_SNAPSHOT_MISSING`, including in draft. Invalid values, identity, timestamp, revision, or field provenance raise `PARAMETER_SNAPSHOT_INVALID`. Current configuration is never a fallback, and corrupt or unreadable current configuration cannot block an instance with a valid snapshot. Identity-free configuration previews still read current configuration and write nothing.
|
|
60
29
|
|
|
61
|
-
|
|
30
|
+
The snapshot contains scope, concrete lifecycle name, record identity, revision, fixed time, all values including defaults, and field sources. Sources identify the group, schema version, nonnegative revision and origin: `default`, `configuration` or `upgrade`. The last denotes one-time upgrade supplementation, never a claim about creation-time history. A new definition may explicitly copy compatible fields as unsaved inputs, validate against its own contract, then save independently. A never-saved version uses its own defaults.
|
|
62
31
|
|
|
63
|
-
|
|
32
|
+
Legacy synchronous `parameters` and asynchronous `parameterProvider` readers remain supported only for definitions without `parameterConfiguration`; do not combine them with configured snapshots. Parameterless definitions do not require parameter storage. Custom `LifecycleStore` adapters must implement `findRecords(collection, ids)` as a bounded primary-key batch read: preserve transaction and visibility semantics, omit missing IDs, issue no query for an empty list, split at dialect parameter limits and avoid individual per-ID reads. Rebuild approval-extension adapters during upgrade.
|
|
64
33
|
|
|
65
|
-
|
|
34
|
+
## Creation idempotency
|
|
66
35
|
|
|
67
|
-
|
|
36
|
+
Use `create(..., { requestId })` to retry one creation. The configurable `creationRequestsCollection` has string key `id` and fields `status`, `revision`, `actorId`, `fingerprint`, nullable `recordId` and `entryId`, and `at`. It is needed when using creation request IDs, not merely because a configured definition has a draft state. A savepoint-protected unique claim joins the business transaction. Concurrent retries return the original record and snapshot; changed input is refused. Scope, concrete definition and actor participate in the identity. `requestInput` contains trusted normalized business input, not an independently unvalidated body.
|
|
68
37
|
|
|
69
|
-
|
|
38
|
+
Use `fire(..., { requestId })` for transition replay. Same-record actions may use `withParameterExecution` to share values and facts with nested `tx.fire` calls. Caller-owned action replay checks precede execution. Effects keep their concrete definition, record identity and external idempotency key across retry and recovery.
|
|
70
39
|
|
|
71
|
-
|
|
40
|
+
## State deadlines
|
|
72
41
|
|
|
73
|
-
|
|
42
|
+
A configured definition declares triggers only when the business needs them, with an indexed nullable `dueAtField`. Parameters such as waiting duration freeze at creation. Each transition calculates its destination state's earliest deadline from the time that state is entered, using the same creation snapshot, and writes it atomically with state and concurrency fields. An initial-state timer uses creation as that state's entry time. Delayed submission does not move the baseline back to record creation. Self-transitions restart the wait under the existing state-entry convention; withdrawal and later reentry calculate a new deadline using the original duration. Configuration edits never recalculate existing deadlines.
|
|
74
43
|
|
|
75
|
-
|
|
44
|
+
Index `(stateField, dueAtField)`. Sweeps filter state, concrete definition binding and due time, page by `(dueAt, id)`, batch-load snapshots and recheck concurrency before firing the transition declared by that version. Keep the successful-fire budget and resume refused backlogs. Corrupt snapshots are reported without stopping other candidates. No implicit automatic submission, cancellation or closure is added.
|
|
76
45
|
|
|
77
|
-
##
|
|
46
|
+
## References and current facts
|
|
78
47
|
|
|
79
|
-
|
|
48
|
+
Snapshots fix parameter values, selected reference IDs and rule groups. Current organization membership, personnel eligibility, inventory and other external facts follow their existing business contracts. Deleted references yield no candidates, and the editor displays missing references. Required assignments reject empty eligible results. Never refresh the snapshot or substitute another reference implicitly.
|
|
80
49
|
|
|
81
|
-
|
|
50
|
+
## Administration and instance details
|
|
82
51
|
|
|
83
|
-
|
|
52
|
+
Configuration edits affect only records created afterward in the selected version; existing drafts are unaffected. Require a concrete save target and reject mismatches. Preserve Save, Discard and Cancel during version changes or navigation, keep failed saves on the original form, and discard late responses from unmounted versions. Show the selected version once. Instance details, diagrams and parameter history display the actual snapshot values, revision, sources and fixed time, including for drafts. Current configuration is shown only on identity-free definition editors/previews.
|
|
84
53
|
|
|
85
|
-
|
|
54
|
+
| Creation entry | Handling |
|
|
55
|
+
| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
|
|
56
|
+
| Expenses v1/v2, tickets and durable example flows | Services call `runtime.create()` with their explicit concrete definition; all configurable records freeze immediately |
|
|
57
|
+
| Example sample records | Use the same services and runtime, including sample drafts |
|
|
58
|
+
| Office incoming documents and data requests | Services create through the runtime; holidays freeze with the data request |
|
|
59
|
+
| Office clerk/team/executor dispatch | Claim, runtime creation, binding, snapshot where configured, child link and assignees share the parent transaction |
|
|
60
|
+
| Office scheduled/manual extractions | Use runtime creation in the request's transaction; extraction is parameterless and requires no snapshot |
|
|
61
|
+
| Procurement and onboarding templates | Existing runtime creation is retained; these parameterless definitions add no parameter storage |
|
|
62
|
+
| Imports, batches and custom child creation | Route through `runtime.create()`; direct insertion cannot satisfy the configured contract |
|
|
86
63
|
|
|
87
|
-
|
|
64
|
+
## Historical inventory, preflight and rollback
|
|
88
65
|
|
|
89
|
-
|
|
66
|
+
Stop every writer, worker and scheduler, take complete database/storage backups, inventory retained snapshots and creation usage, then run the migration. Keep old definitions needed for retained records and tasks, together with immutable revisions, usage and creation receipts. Definition code removal follows explicit user retirement confirmation; merged migrations and historical data remain preserved. Do not mix old and new processes.
|
|
90
67
|
|
|
91
|
-
|
|
68
|
+
The full read-only preflight validates every final payload before any configuration or schema write: values, scope/name/record identity, timestamp, revision, and every source's group, schema version, revision and origin. Preserve valid snapshots exactly. Invalid snapshots, unknown bindings and invalid configuration remain conflicts. An absent snapshot for parameters that were already required to be fixed is a conflict too; do not mask lost evidence by supplementing it.
|
|
92
69
|
|
|
93
|
-
|
|
70
|
+
Prefer reliable complete usage linked to the unique valid version-one `$create` entry, with matching scope, record, definition and attempt zero. Preserve its actual timestamp and sources; the fact may follow its entry within the transaction. Released usage without a top-level revision uses the maximum historical source revision, retaining original group revisions in `recoveredFrom.groupRevisions`. Never use later submit usage as creation evidence.
|
|
94
71
|
|
|
95
|
-
|
|
72
|
+
Only parameters the released definition previously read live may be supplemented once from that bound definition's effective configuration at upgrade, using self-contained frozen defaults and the released parsing/fallback rules. Mark each supplemented field's `origin` as `upgrade`, with its group/schema version and configuration revision. This records upgrade-time values, not historical creation values, including completed records. Match the released reader for early records: expenses with `parameterContract != 1` bypassed administrator configuration and used code defaults. Without reliable creation evidence, freeze the migration's historical defaults (5000 / 50000 / 3) with `origin: upgrade` and revision 0; existing valid snapshots and verified creation usage still take precedence. Other example definitions that read configuration live continue to use their bound version's effective upgrade-time configuration. Office's released live parameters include dispatch rules, management groups and holidays; preserve the released fallback to reference tables where applicable. Current membership and personnel eligibility remain external facts.
|
|
96
73
|
|
|
97
|
-
|
|
74
|
+
Released submitted expenses retain their original threshold values, source revisions and submission time; fill only the missing live waiting duration, preferring verified creation usage and preserving its original source. Only fields without such evidence use upgrade-time configuration with origin `upgrade`. This mixed snapshot is not relabeled as creation history. Preserve historical usage, logs, effects, business deadlines and notifications. Compute newly introduced state deadlines from state-entry time plus the now-fixed duration. Later administrator changes never refresh any of these snapshots or recalculate deadlines.
|
|
98
75
|
|
|
99
|
-
|
|
76
|
+
Keep old definitions and their dependencies available for retained records and tasks until the user explicitly confirms retirement and permits definition code deletion. New process definitions or versions cannot replace parameter migration for old records. After supplementation, old records can be viewed and continue in the same database without waiting for completion. To change a frozen version's future behavior, create an independent new version and explicitly switch chosen creation entry points, listing switched and retained entries at delivery. Newly introduced unmerged versions can continue to be edited under the Git freezing rule. There is no runtime fallback, compatibility switch, instance parameter editing or implicit rebinding.
|
|
100
77
|
|
|
101
|
-
|
|
78
|
+
After a clean preflight, apply bounded batches with writers still stopped. The lifecycle example uses two scan passes rather than an unbounded in-memory write plan. A data conflict leaves configuration, schema and snapshots unchanged even without transactional DDL. MySQL's DDL is not generally transactional; an unrelated DDL failure still needs the backup/recovery procedure. After new records exist, rollback to old code requires restoring the pre-upgrade backup. Do not erase snapshots or receipts to manufacture rollback. Unmerged migration renames require recreating temporary preview databases or restoring their matching source/database backup, not editing execution history.
|
|
102
79
|
|
|
103
|
-
|
|
80
|
+
For the full edit decision and deletion boundaries, follow [versions of a process](lifecycle-versions.md).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Lifecycle UI
|
|
2
2
|
|
|
3
|
-
Use this reference for management pages built around `@nocobase/lifecycle`. Read [record lifecycles](lifecycle.md) for runtime integration, [configurable parameters](lifecycle-parameters.md) for storage and snapshot
|
|
3
|
+
Use this reference for management pages built around `@nocobase/lifecycle`. Read [record lifecycles](lifecycle.md) for runtime integration, [configurable parameters](lifecycle-parameters.md) for storage and creation snapshot semantics, and the [frontend workflow](frontend/ui-workflow.md) for UI implementation. Whenever application requirements include a process to develop, deliver its workflow management pages by default, even if the user mentions only business operations. Extend existing management pages when present. Follow the scope exceptions in [system administration](system-administration.md#default-delivery); these defaults do not add a console to API-only work or explicitly excluded UI.
|
|
4
4
|
|
|
5
5
|
## Default management structure
|
|
6
6
|
|
|
@@ -14,7 +14,7 @@ Register Workflow management as one module card in the Business configuration ca
|
|
|
14
14
|
|
|
15
15
|
Check `client/extensions/nocobase-workflow-management/` for an installed copy first. If missing, read `@nocobase/workflow-management-demo` with `pnpm exec shadcn view @nocobase/workflow-management-demo`, then install with `yes n | pnpm exec shadcn add @nocobase/workflow-management`. Follow the [UI Library installation guidance](frontend/references/styling.md#3-use-shadcn) for dependency placement. Read the installed README for component props and route integration. The block supplies source files; it registers no route, server service, database or permission.
|
|
16
16
|
|
|
17
|
-
Use `WorkflowManagementLayout` for the shared header and URL-controlled tabs, `WorkflowDefinitionList` and `WorkflowExecutionList` for lists, `WorkflowDefinitionDetail` for diagram/parameter cards, and `WorkflowExecutionDetail` for the diagram/history/effects composition. Pass translated labels, adapted display rows with application router links, category/search controls, loading/error/empty content and controlled callbacks. The application owns API requests, URL query state, IME-aware search, server pagination, category CRUD, breadcrumbs and authorization. Keep parameter schemas, complete-
|
|
17
|
+
Use `WorkflowManagementLayout` for the shared header and URL-controlled tabs, `WorkflowDefinitionList` and `WorkflowExecutionList` for lists, `WorkflowDefinitionDetail` for diagram/parameter cards, and `WorkflowExecutionDetail` for the diagram/history/effects composition. Pass translated labels, adapted display rows with application router links, category/search controls, loading/error/empty content and controlled callbacks. The application owns API requests, URL query state, IME-aware search, server pagination, category CRUD, breadcrumbs and authorization. Keep parameter schemas, complete-version persistence, CAS conflict handling and effective timing in the application's editor, inserted into the definition detail's parameter slot.
|
|
18
18
|
|
|
19
19
|
Render the preinstalled `LifecycleDiagram` through the diagram slot/callback by default. Preserve its standard React Flow + ELK visual language unless the user explicitly requests a different diagram style; an existing Mermaid renderer is not a compatible default. If neither is installed, add the diagram with `yes n | pnpm exec shadcn add @nocobase/lifecycle-diagram`; the block accepts a caller-supplied diagram. `WorkflowExecutionDetail` supplies the selected history prefix and resulting state to `renderDiagram`; selection is display-only. Keep recorded parameters separate from current settings and pass their display through the parameter slot. Do not add business actions or recovery requests to history selection. Remount the detail on record changes or explicit refresh to clear historical selection, following the example adapter.
|
|
20
20
|
|
|
@@ -44,10 +44,18 @@ Use one PageHeader with the business title, compact category assignment and exec
|
|
|
44
44
|
|
|
45
45
|
Place the diagram and Parameter settings in two columns on wide screens, stacking on smaller screens. Use min-w-0 children, a consistent gap and items-start so cards size independently. Give each card a heading and keep wide tables or structured values scrollable within it.
|
|
46
46
|
|
|
47
|
-
Prefer a visible parameter form beside the diagram. Group fields by business state or transition; render shared fields once in a deterministic section, with unbound fields under a workflow-level section. Visual regrouping must preserve configuration group identities, complete-
|
|
47
|
+
Prefer a visible parameter form beside the diagram. Group fields by business state or transition; render shared fields once in a deterministic section, with unbound fields under a workflow-level section. Visual regrouping must preserve configuration group identities, complete-version saves and revisions. Show an explicit empty state when there are no parameters.
|
|
48
48
|
|
|
49
49
|
Provide contextual controls for declared, authorized bindings by default, sharing the same editor and save contract. Keep node configuration controls as compact icon-only buttons with translated accessible names and hover hints; reserve the main node area for its title. Keep full configuration labels in the parameter panel or chooser, never inline beside the node title. Make settings discoverable through the visible parameter panel or a clearly labelled configuration entry outside the graph when using contextual-only editors. Inspection and editing clicks never execute transitions.
|
|
50
50
|
|
|
51
|
+
## Versions
|
|
52
|
+
|
|
53
|
+
A process with several [versions](lifecycle-versions.md) is one catalog row: group definitions by `key`, describe the row by the latest version, the largest number, and show that number beside the title only when the process has more than one version. Execution counts and the latest execution time cover every version; state and transition counts are the latest version's. Never present the latest as the version in use: entry points in code choose which version new records start, and the page has no enabled state.
|
|
54
|
+
|
|
55
|
+
The definition detail offers a version switch in the header, kept in a `version` query parameter so a reload or a shared link shows the same version; the diagram, description and per-version execution count follow the selection, and the execution link filters by that version. The switch is the header's only mention of the version: label the execution link with its count alone, not the version again. The parameter panel configures the selected definition version independently. Label its version, preserve unsaved inputs through Save/Discard/Cancel before switching, wait for successful saves and reject stale responses or mismatched save targets. Keep links that name an old definition by its own name working: resolve them to the process and that version, and replace the URL with the process address.
|
|
56
|
+
|
|
57
|
+
The execution list shows each record's version and, for a selected process with several versions, filters by version. Count and page a shared table by each record's definition field, so no record appears under two versions or two processes. An execution detail always describes the record's own version, never the latest, and links to that version's definition. Search matches the key and every version's name.
|
|
58
|
+
|
|
51
59
|
## Keep process graphs readable
|
|
52
60
|
|
|
53
61
|
Aim for a readable business process with its necessary branches, not a diagram of every implementation operation. Start with the main forward path, then include required approval, rejection, withdrawal, resubmission, timeout and recovery paths. Do not invent extra transitions for symmetry or connect each state to every other state. A technically automatic transition can still be an essential business step; do not hide it merely because it is automatic.
|
|
@@ -85,7 +93,7 @@ Show effect status, attempts and errors separately: a completed transition and a
|
|
|
85
93
|
|
|
86
94
|
## Parameter form behavior
|
|
87
95
|
|
|
88
|
-
Use business labels, units, validation and effective timing. Distinguish
|
|
96
|
+
Use business labels, units, validation and effective timing. Distinguish unsaved configuration inputs, saved configuration and immutable instance values. Follow [parameter consistency rules](lifecycle-parameters.md#creation-idempotency) for creation snapshots and existing task candidates rather than inventing UI-specific semantics.
|
|
89
97
|
|
|
90
98
|
Preserve drafts on revision conflicts and incidental refreshes; require a deliberate reload/retry or confirmation before discarding them. Read-only administrators see configured values without active save controls. Use the runtime's complete-group validation and concurrency contract even when the page visually regroups fields.
|
|
91
99
|
|
|
@@ -136,10 +144,10 @@ Use `LifecycleDiagram.configuration` to derive contextual controls from `descrip
|
|
|
136
144
|
|
|
137
145
|
`permissions` and `openParameterEditor` above are application-owned adapters, not framework exports. Implement them against the installed authenticated parameter service/editor. Preserve fields outside the selected binding when saving a complete group; fetch the authorized save context and revision rather than sending the filtered selection as a replacement. If partial group editing cannot preserve restricted fields safely, require group update permission and expose no edit control until the server supports it. Handle validation errors and revision conflicts without discarding drafts; read the saved version back and refresh the current policy summary. Use the field's native `number`, `boolean`, `string`, `reviewers` or declared object schema with appropriate business controls, not a JSON textarea for approver identities. Configuration updates require independent server authorization and audit.
|
|
138
146
|
|
|
139
|
-
On every process-building iteration, identify administrator-owned business policy: approval thresholds and reviewer selection are typical defaults, even if the request never says configurable. Declare their native parameter metadata, meaningful state/transition bindings, validation, permissions, storage and actual runtime consumers together. Use existing organization relationships for direct supervisors. When reviewer resolution is owned by member profiles or role membership rather than workflow parameters, expose an authorized, translated `stateActions` link/button on the corresponding approval node to open those authoritative settings. Check the destination's read/update permissions; hide mutation entries from read-only and history views. Reuse that editor and service, explain when changes affect new versus existing records/tasks, and preserve return navigation. Do not invent a duplicate workflow parameter merely to get a configuration button. Do not add fake editable fields for secrets, topology, unsupported timing or code-only constants. Preserve snapshot
|
|
147
|
+
On every process-building iteration, identify administrator-owned business policy: approval thresholds and reviewer selection are typical defaults, even if the request never says configurable. Declare their native parameter metadata, meaningful state/transition bindings, validation, permissions, storage and actual runtime consumers together. Use existing organization relationships for direct supervisors. When reviewer resolution is owned by member profiles or role membership rather than workflow parameters, expose an authorized, translated `stateActions` link/button on the corresponding approval node to open those authoritative settings. Check the destination's read/update permissions; hide mutation entries from read-only and history views. Reuse that editor and service, explain when changes affect new versus existing records/tasks, and preserve return navigation. Do not invent a duplicate workflow parameter merely to get a configuration button. Do not add fake editable fields for secrets, topology, unsupported timing or code-only constants. Preserve creation snapshot timing and historical task candidates as [parameter configuration](lifecycle-parameters.md) defines.
|
|
140
148
|
|
|
141
149
|
## Acceptance against the original requirement
|
|
142
150
|
|
|
143
151
|
A design approval does not prove component availability or authorize a fallback based on an npm 404. Reviewers must compare the implementation to this default contract and the user's original requirements, not just the amended design. Inspect actual rendered component imports, the canvas and the bound editor. Business tests alone do not establish standard component reuse.
|
|
144
152
|
|
|
145
|
-
For release acceptance, start a clean published-template app and use only business prompts (no hints to use React Flow, system settings or configurable nodes). Verify Home-only before business work; then the single management entry, definition directory even for one process, standard graph, authorized bound controls and execution history. Save a threshold/reviewer through a node's editor (or its authoritative organization-settings entry), reload it, submit a new record and verify the actual branch/candidate change. Verify organization-derived reviewer nodes link to the real profile/role editor, not just a descriptive label or a second identity store. Check an earlier
|
|
153
|
+
For release acceptance, start a clean published-template app and use only business prompts (no hints to use React Flow, system settings or configurable nodes). Verify Home-only before business work; then the single management entry, definition directory even for one process, standard graph, authorized bound controls and execution history. Save a threshold/reviewer through a node's editor (or its authoritative organization-settings entry), reload it, create and submit a new record and verify the actual branch/candidate change. Verify organization-derived reviewer nodes link to the real profile/role editor, not just a descriptive label or a second identity store. Check an earlier-created record, including a business draft, retains its snapshot, a read-only user has no mutation controls, and direct unauthorized API writes fail. Check light/dark, narrow layouts and long labels. Record any untested browser or Agent-generation behavior explicitly; never call it passed on static imports alone.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Versions of a process
|
|
2
|
+
|
|
3
|
+
A lifecycle definition lives in source. The target main branch determines when its behavior is frozen; user confirmation determines when a frozen version may be deleted. Records keep their concrete definition binding. This page covers the edit decision, creating and deleting versions, entry points and delivery. [Record lifecycles](lifecycle.md) covers the definition itself; `packages/libs/lifecycle/docs/design.md#versions-of-a-process` in the NocoBase repository has the runtime contract.
|
|
4
|
+
|
|
5
|
+
## Identity
|
|
6
|
+
|
|
7
|
+
| Property | Meaning |
|
|
8
|
+
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
9
|
+
| `name` | One definition, for good. Records, the transition log, effect runs and parameter snapshots refer to it. Never rename it. |
|
|
10
|
+
| `key` | The process the definition is a version of. Every version of a process has the same key; the first version's key is normally its name. Plugins use a namespaced key so two processes never group by accident. |
|
|
11
|
+
| `version` | A positive integer, unique within the key. The largest is the latest, which says nothing about which version new records start with. |
|
|
12
|
+
| `collection` | The business table. Every version of a key uses the same one; write it explicitly in a copy, since it defaults to the name. |
|
|
13
|
+
| `definitionField` | The record field holding the name of the definition that created the record. The same field in every version of a key; one field per lifecycle when a record carries several (`approvalDefinition`, `paymentDefinition`). |
|
|
14
|
+
| `versionField` | `lifecycleVersion`, the record's concurrency counter. It is unrelated to the definition's `version`. |
|
|
15
|
+
|
|
16
|
+
Once merged into the target main branch, a definition permanently reserves its `name` and `key` + `version`, even after its code is deleted. Never reuse either identity for a new definition. Removing an entire process does not release its `key` for a different process. These source-maintenance rules protect retained records, logs, effect runs and snapshots from being interpreted by a new definition; runtime registration checks only the currently registered definitions.
|
|
17
|
+
|
|
18
|
+
A definition without `key` or `version` registers as its name and 1, and one without `definitionField` registers while its key has one version; both print a warning in this release and become required in the next minor release. Write all three in source anyway.
|
|
19
|
+
|
|
20
|
+
## Before changing behavior
|
|
21
|
+
|
|
22
|
+
1. Identify the current branch's target main branch from available Git refs, the PR target and repository conventions. Compare definitions by `key`, `version` and `name` against that target branch's current contents and history, including local plugins. A filename, an uncommitted diff or an old merge-base snapshot alone does not establish version ownership. If the target or ownership remains uncertain after those checks, ask the user before changing behavior; do not assume an in-place edit is allowed.
|
|
23
|
+
2. A version already present in the target main branch is frozen. Changing execution requires a new definition version beside it, retaining the old definition and its original behavior. Execution includes states, transition conditions and destinations, guards, `route`, `validate`, `set`, `accept`, hooks, triggers, effects and their failure/retry behavior, and parameter contracts (fields, types, meaning, units, validation and defaults).
|
|
24
|
+
3. A version introduced on the current branch and not yet merged into the target main branch can be edited repeatedly in place. Further edits, commits, restarts and resumed development do not require another version. This also applies to the first version of a new process. Once merged into the target main branch, that version freezes and its next behavior change needs another version.
|
|
25
|
+
4. If the working tree already changes a frozen version's behavior, move only those behavior changes into a new version and restore the frozen version's original behavior. Preserve unrelated working-tree changes.
|
|
26
|
+
5. Titles, descriptions, translations and metadata used only for display can be edited in place. Inspect shared guards, effects, services and helpers too: preserve behavior for every frozen version that calls them, using a separate implementation or an explicit new-version argument where needed. Copying the outer definition while changing a shared dependency does not preserve old behavior.
|
|
27
|
+
6. Editing values of already-declared parameters follows the existing configuration and instance snapshot mechanism; it is not a parameter contract change. Never rewrite existing snapshots. See [parameter contracts and snapshots](lifecycle-parameters.md).
|
|
28
|
+
|
|
29
|
+
Git merge is the development boundary for freezing a version. Local execution records and guesses about production usage do not decide whether to increment it. An unmerged version may already have been deployed or used; permission to edit it is no claim of data compatibility, and existing instance snapshots remain immutable. Check actual compatibility where such data is known, and follow the deletion confirmation rule below when removing a deployed or used version.
|
|
30
|
+
|
|
31
|
+
For example, the target main branch contains v1. The first behavior change on a feature branch creates v2; v2 can be revised throughout that branch without creating v3 for each commit or resumed session. After v2 merges into the target main branch, the next behavior change creates v3.
|
|
32
|
+
|
|
33
|
+
## Creating a version
|
|
34
|
+
|
|
35
|
+
1. Find every current definition with this key, including those in local plugins, and inspect the target main branch's history for every version of that key, including deleted definitions. Take the largest `version` across both the current definitions and that history, plus one; use 1 for a new process only when neither contains a version of that key. Choose a `name` unused by current definitions and never reserved by a merged definition, and never reuse a merged `key` + `version`, even after deletion. If history is insufficient to establish these identities, inspect available Git refs, PRs and repository conventions, then ask the user if still uncertain; do not assume a deleted version or name is available. Write the number into source; never compute it at runtime from registration order or time. Two branches that both add a version resolve the clash before merging.
|
|
36
|
+
2. Copy the definition into a new file with a new `name` (`expenses-v2`), the same `key`, the new `version`, and the same `collection`, `stateField`, `changedAtField`, `versionField` and `definitionField`. Reuse unchanged transitions and hooks by reference rather than duplicating them.
|
|
37
|
+
3. Register the new definition on the same runtime, with the same effects, in every process and worker that may run it. Keep the old one registered.
|
|
38
|
+
4. Follow the parameter rules below.
|
|
39
|
+
5. Check the copy's own references: hooks and effects that name the definition, child processes it creates, permission bindings, scheduled jobs, notification scenarios and services that read its states. Each of these either keeps naming the old version or moves deliberately.
|
|
40
|
+
6. Decide the entry points as described below.
|
|
41
|
+
7. Test both versions: an old record still follows the old graph, a new record follows the new one, each version's trigger handles only its own records, and a record of one version is refused by the other with `DEFINITION_MISMATCH`.
|
|
42
|
+
|
|
43
|
+
For example, if v3 was merged and later deleted while v1 and v2 remain, the next new version is v4 with an unused name; the deleted v3's name and `key` + `version` stay reserved. This numbering step applies when creating a new version, not when continuing to edit an unmerged version.
|
|
44
|
+
|
|
45
|
+
## Parameters belong to the definition version
|
|
46
|
+
|
|
47
|
+
A definition version's contract, including meaning, units, validation and defaults, freezes when it reaches the target main branch, following the decision above. Configuration is stored independently by concrete definition name. A group can evolve independently in a new version; there is no cross-version group freezing rule. Editing an unmerged contract still requires checking any saved configuration and existing snapshots for compatibility; it never authorizes changing instance snapshots.
|
|
48
|
+
|
|
49
|
+
Administrators edit values only. An explicit copy from a previous version must validate against the target contract and becomes independent. When the runtime creates a record, including a business draft, it atomically saves complete effective values, revision and fixed time. All later execution uses that immutable instance snapshot. Return, withdrawal and resubmission of the same instance retain it. Use runtime creation for every configured entry, seed, import, batch and child record; see [parameter contracts and snapshots](lifecycle-parameters.md).
|
|
50
|
+
|
|
51
|
+
## Entry points
|
|
52
|
+
|
|
53
|
+
Records start through entry points: a user creating a record, an event subscriber, a scheduled creation, an outside API or webhook, an import, a batch, a command, or another process creating a child process. Each names the definition it starts; there is no "latest version" default, and the runtime never routes creation to the largest version.
|
|
54
|
+
|
|
55
|
+
Move the entry points that should start the new behavior, and only those. Keep the choice in one place where possible, such as the business service that creates records, rather than scattering names. An old version that deliberately creates an old child process keeps doing so: moving the current entry point must preserve the behavior of a frozen version. Rolling back means pointing the entry points at the old definition again; records already created by the new version keep running it.
|
|
56
|
+
|
|
57
|
+
Everything about an existing record follows its binding, never the entry points: viewing, firing, retrying or continuing an effect, a callback, a trigger and a child process the record's version creates. Routes and pages address the process by key and let the server resolve the record's definition with `boundLifecycle()`.
|
|
58
|
+
|
|
59
|
+
At delivery, list every entry point of the process: those that now start the new version, those that keep the old one and why, and any you could not find an owner for. Check imports, batches, commands and background services explicitly.
|
|
60
|
+
|
|
61
|
+
## Pages for several versions on one table
|
|
62
|
+
|
|
63
|
+
- A business list filters and labels states by the union of every version's states (`runtime.groupStates(key)`), so a filter offers states only one version has. The status column's options and labels cover the union too.
|
|
64
|
+
- A record's actions, diagram and history come from the record's own version: the record view's `lifecycle` and `definitionVersion` say which, and `useLifecycle` describes that definition rather than the latest.
|
|
65
|
+
- Management lists show one row per key, described by the latest version, with execution counts over every version and a version switch on the detail page; follow [Lifecycle UI](lifecycle-ui.md#versions).
|
|
66
|
+
|
|
67
|
+
## Deployment
|
|
68
|
+
|
|
69
|
+
A new version is available in every process and worker before any entry point starts it: deploy the definition first, move the entry points in a later release or behind a coordinated switch, so an old worker never receives an effect run of a definition it does not register. Retain old definitions and their behavior dependencies for bound records, history, recovery and pending work until the retirement confirmation in [Deleting versions](#deleting-versions) permits removal. Schema changes a new version needs are compatible with the old version's code.
|
|
70
|
+
|
|
71
|
+
## Deleting versions
|
|
72
|
+
|
|
73
|
+
Freezing behavior does not prohibit deletion. Before deleting a version already merged into the target main branch, obtain the user's explicit confirmation in the conversation that, in all relevant deployment environments, the version is no longer used, there are no instances, historical records or pending execution/continuation tasks that need to be retained, executed, viewed or recovered, and deleting its definition code is allowed. A local database cannot establish retirement across those environments.
|
|
74
|
+
|
|
75
|
+
A suitable question is: "Please confirm: in all relevant deployment environments, this workflow version is no longer used; there are no instances, historical records or pending execution or continuation tasks that need to be retained, processed, viewed or recovered; and you allow deletion of its definition code."
|
|
76
|
+
|
|
77
|
+
An equivalent explicit confirmation already given in the conversation is sufficient. Once confirmed, proceed with deletion; do not require production access, database query results or another confirmation. If inspection reveals a concrete fact contradicting that confirmation, or another version still has a valid dependency, explain and resolve the conflict before removing the dependency.
|
|
78
|
+
|
|
79
|
+
- Remove the selected definition code, its registration, creation entry points and related references. Check pages, APIs, scheduled jobs, event subscribers, webhooks, imports, batches, commands, background services and child-process entry points so no path still targets the deleted version.
|
|
80
|
+
- Preserve other versions and shared code they still depend on. Preserve merged database migrations. Permission to delete definition code does not authorize production database cleanup or historical data deletion.
|
|
81
|
+
- Deleting a previously merged version never releases its `name` or `key` + `version` for reuse by a new definition. Include deleted versions when choosing the next version from current definitions and the target main branch's history. If the entire process is removed, never assign its `key` to a different process.
|
|
82
|
+
- A version added on the current branch and not yet merged can be removed as a development undo. If the user says it has been deployed or used, apply the same retirement confirmation rule.
|
|
83
|
+
- For a single-version deletion, retain the other versions. For removal of an entire process, apply these checks and confirmation to all its versions and entry points.
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Use `@nocobase/lifecycle` when a business record moves through stages that developers define in source: an expense report, a ticket, a contract, an order, a leave request. The record keeps its state in one of its own fields, every change is a transition declared in a definition, and the work a transition owes outside the database — mail, payments, calls to other systems — runs as effects after the transaction commits. There is no separate process instance, so the state is never kept in two places.
|
|
4
4
|
|
|
5
|
-
Administrators can adjust code-declared business parameters without editing workflow structure. Proactively declare suitable approval departments, reviewer choices and thresholds as business parameters, even without an explicit configurability request. For declarations,
|
|
5
|
+
Administrators can adjust code-declared business parameters without editing workflow structure. Proactively declare suitable approval departments, reviewer choices and thresholds as business parameters, even without an explicit configurability request. For declarations, atomic creation snapshots and version-specific configuration editors, read [configurable lifecycle parameters](lifecycle-parameters.md).
|
|
6
6
|
|
|
7
7
|
## Approval requests: check the Pro plugin first
|
|
8
8
|
|
|
@@ -45,6 +45,7 @@ The business record's page may show a diagram, state/actions/history, or a compa
|
|
|
45
45
|
6. **Guards are business rules, not permissions.** Routes still authenticate and authorize: at least `read`, `fire` and `operate`, ahead of the validators.
|
|
46
46
|
7. **Inside a transaction, go through `tx`.** In `onTransition`, `onEnterState`, `onLeaveState` or `runtime.transaction()`, call `tx.fire()` / `tx.create()` or pass `transaction: context.transactionHandle`. A bare `runtime.fire()` there hangs forever on SQLite and commits separately on PostgreSQL or MySQL.
|
|
47
47
|
8. **Services that read other tables are a factory bound to the transaction:** `services: (handle) => ({ … })`. Reading through the database manager from a guard deadlocks on SQLite.
|
|
48
|
+
9. **A record runs the definition that created it.** Every definition declares `key`, `version` and `definitionField`; `runtime.create()` writes the definition's name into that field, and nothing else ever writes it. Before editing behavior, compare `key`, `version` and `name` with the target main branch: versions there are frozen, while versions newly added on this branch can continue to be edited until merged. Follow [versions of a process](lifecycle-versions.md) for the full decision and retirement confirmation before deletion.
|
|
48
49
|
|
|
49
50
|
## Where the files go
|
|
50
51
|
|
|
@@ -119,6 +120,9 @@ const approverOnly = ({ record, actor }: TransitionContext<LeaveTypes>) =>
|
|
|
119
120
|
export const leaveLifecycle: Lifecycle<LeaveTypes> =
|
|
120
121
|
defineLifecycle<LeaveTypes>({
|
|
121
122
|
name: 'leaves', // also the default collection name; stored in the log: never rename
|
|
123
|
+
key: 'leaves', // the process all versions of this definition belong to
|
|
124
|
+
version: 1, // the next version of this key is a new definition with version 2
|
|
125
|
+
definitionField: 'lifecycleDefinition', // the record field runtime.create() binds
|
|
122
126
|
initial: 'draft',
|
|
123
127
|
states: [
|
|
124
128
|
'draft',
|
|
@@ -202,7 +206,8 @@ The record table needs, besides its business fields:
|
|
|
202
206
|
|
|
203
207
|
- the state field, `status` by default, `string` not null;
|
|
204
208
|
- `statusChangedAt`, `datetimeTz` not null;
|
|
205
|
-
- `lifecycleVersion`, `integer` not null, default `0`;
|
|
209
|
+
- `lifecycleVersion`, `integer` not null, default `0`; it orders concurrent changes of one record and is not the definition's version;
|
|
210
|
+
- the definition field, `lifecycleDefinition` here, `string` and nullable: `runtime.create()` writes the definition's name, and a record no process has started leaves it empty. A record carrying two lifecycles, say an approval and a payment, has one such field per lifecycle (`approvalDefinition`, `paymentDefinition`);
|
|
206
211
|
- an index on `(status, statusChangedAt)`, which the trigger sweep reads.
|
|
207
212
|
|
|
208
213
|
The two log tables, created once for every lifecycle in the application:
|
|
@@ -320,7 +325,7 @@ The library ships no routes. Write them in `server/routes/` like every other `/a
|
|
|
320
325
|
| `POST <lifecycle>/{id}/effectRuns/{runId}/continue` | the record view |
|
|
321
326
|
| `POST <lifecycle>/{id}/effectRuns/{runId}/cancel` | the record view |
|
|
322
327
|
|
|
323
|
-
Lists and creation are ordinary routes of the application; creation calls `runtime.create(name, values, { actor })`. The fire route passes `manual: true`, so a transition marked `manual: false` is refused with `NOT_MANUAL`:
|
|
328
|
+
Lists and creation are ordinary routes of the application; creation calls `runtime.create(name, values, { actor })` with the definition this entry starts. `<lifecycle>` in these paths is the process's key: the page never names a version. Each record route first asks `runtime.boundLifecycle(key, id)` which definition the record is bound to and calls the runtime with that name, so one page serves the records of every version; a list or a route that has read the record already uses `runtime.recordLifecycle(key, record)`. The description route takes an optional `?definition=<name>` and describes the latest version without one. A record no version started is refused with `DEFINITION_MISMATCH`, which `lifecycleErrorFields()` maps to `400 FAILED_PRECONDITION`; never fall back to the latest version. The fire route passes `manual: true`, so a transition marked `manual: false` is refused with `NOT_MANUAL`:
|
|
324
329
|
|
|
325
330
|
```ts
|
|
326
331
|
import { ApiError, apiErrorHandler } from '@nocobase/app-server/router';
|
|
@@ -338,7 +343,9 @@ router.onError((error, c) => apiErrorHandler(toApiError(error), c));
|
|
|
338
343
|
// inside the POST /leaves/:leaveId/fire handler, after auth, authorization and validators:
|
|
339
344
|
const actor = { id: String(signedInUserId) };
|
|
340
345
|
try {
|
|
341
|
-
|
|
346
|
+
// The version this record runs, whichever is the latest.
|
|
347
|
+
const name = await runtime.boundLifecycle('leaves', leaveId);
|
|
348
|
+
const result = await runtime.fire(name, leaveId, body.transition, {
|
|
342
349
|
actor,
|
|
343
350
|
manual: true,
|
|
344
351
|
input: body.input,
|
|
@@ -347,7 +354,7 @@ try {
|
|
|
347
354
|
? {}
|
|
348
355
|
: { expect: { version: body.expectVersion } }),
|
|
349
356
|
});
|
|
350
|
-
const view = await runtime.view(
|
|
357
|
+
const view = await runtime.view(name, leaveId, actor);
|
|
351
358
|
return c.json({ data: { ...view, replayed: result.replayed === true } });
|
|
352
359
|
} catch (error) {
|
|
353
360
|
throw toApiError(error, 'input'); // field problems are reported under `input`
|
|
@@ -432,12 +439,15 @@ it('expires a request nobody handles', async () => {
|
|
|
432
439
|
- Every external call receives `idempotencyKey`, or the business fact's own key.
|
|
433
440
|
- `prune()` runs in `onSweep`.
|
|
434
441
|
- Routes authorize read, fire and operate separately; guards are not the only check.
|
|
435
|
-
-
|
|
442
|
+
- Every definition declares `key`, `version` and `definitionField`, the record table has the definition field, and record routes resolve the definition through `boundLifecycle()`.
|
|
443
|
+
- No code outside the runtime writes the state, `statusChangedAt`, `lifecycleVersion` or the definition field. An edit that a transition must not race, such as changing an amount a guard reads, may only increment `lifecycleVersion` conditionally on the version it read.
|
|
436
444
|
- Effect runs that are `failed`, `dead`, or hold a waiting or abandoned continuation are visible to an operator: `listEffectRuns({ status: 'failed' })`, `listEffectRuns({ continuationPending: true })`, `listEffectRuns({ continuationAbandoned: true })`.
|
|
437
445
|
|
|
438
|
-
## Changing a definition
|
|
446
|
+
## Changing a definition
|
|
439
447
|
|
|
440
|
-
|
|
448
|
+
Before changing execution behavior or a parameter contract, follow the [Git freezing decision](lifecycle-versions.md#before-changing-behavior). A version present in the target main branch needs a new definition with the same `key` and the next `version`, preserving the old behavior; a version newly added on the current branch can continue to be edited until it merges. Shared dependencies follow the same rule. Titles, descriptions, translations and pure display metadata may change in place. Parameter configuration value edits follow [configuration and instance snapshots](lifecycle-parameters.md), independently of contract changes. The version guide also covers registrations, explicit entry point switches and validation of both versions.
|
|
449
|
+
|
|
450
|
+
States, transition, lifecycle and effect names are stored in the database. Never rename a definition. A merged definition's `name` and `key` + `version` remain reserved after deletion, and a removed process's `key` cannot identify a different process. Choose a new version above the maximum in both current definitions and the target main branch's history, including deleted definitions; see [Creating a version](lifecycle-versions.md#creating-a-version). Retain definitions and their dependencies for bound records, history, recovery and pending work until the user confirms retirement under [Deleting versions](lifecycle-versions.md#deleting-versions). That confirmation permits deleting definition code; it does not permit deleting historical data or merged migrations. Keep a removed or renamed effect registered for any queued, running or pending continuation work that still needs it. Renaming the state, timestamp, version or definition field needs a migration in the same release.
|
|
441
451
|
|
|
442
452
|
## Troubleshooting
|
|
443
453
|
|
|
@@ -475,4 +485,4 @@ Adapt the translation key prefix to the feature.
|
|
|
475
485
|
|
|
476
486
|
Preserve the component’s application theme tokens: `--primary` for current, visited and available highlights, subdued neutral strokes for other edges, and card/foreground/border tokens for the canvas and labels. Current nodes use an accent border and ring, visited nodes a subtler accent border, and both retain the upstream textual status and icon so execution state does not rely on color alone. Labels stay on the routes; automatic transitions remain solid and may show `⚙` through `transitionLabel`. Do not introduce a separate palette or hard-coded accent color. Check light/dark themes and a changed application primary color when customizing the rendering.
|
|
477
487
|
|
|
478
|
-
For narrow layouts, use `initialMinZoom={0.8}` to preserve readable node content, with pan and a full-graph Fit control. Do not add a minimap to standard process pages by default; `showMiniMap` remains opt-in for consumers that need it. `configuration` on LifecycleDiagram automatically exposes declared, authorized bindings through the real editor; `stateActions` (or `nodeActions` on FlowDiagram) adds custom controls; `nodeDescription` adds real policy summaries. Supply enough fixed node height for the content. Definition views show the latest configured policy, while record views identify their
|
|
488
|
+
For narrow layouts, use `initialMinZoom={0.8}` to preserve readable node content, with pan and a full-graph Fit control. Do not add a minimap to standard process pages by default; `showMiniMap` remains opt-in for consumers that need it. `configuration` on LifecycleDiagram automatically exposes declared, authorized bindings through the real editor; `stateActions` (or `nodeActions` on FlowDiagram) adds custom controls; `nodeDescription` adds real policy summaries. Supply enough fixed node height for the content. Definition views show the latest configured policy, while record views identify their creation snapshot. Never invent reviewer names, policy values or execution highlights. Standard business process pages omit system-only technical edit paths without adding a technical display toggle; retain every business approval, rejection, withdrawal and resubmission path. Technical diagnostic views may expose the complete source description separately when explicitly needed.
|
|
@@ -57,7 +57,7 @@ For an application-owned lifecycle, register the real descriptions explicitly in
|
|
|
57
57
|
|
|
58
58
|
Catalogue entries must explicitly bind their runtime definition, record collection, read permissions and execution adapter. Validate the process identifier on definition, parameter and execution endpoints; reject unknown identifiers and never fall back to another process's records. Filter by the selected process and enforce its business scope before counting or paging. Do not fabricate enable/disable, publish, edit-topology or delete controls when the installed runtime does not support them.
|
|
59
59
|
|
|
60
|
-
Definition read, parameter update and execution visibility are distinct permissions. Execution queries must preserve the owning business record's data scope. Link definitions to their authorized executions and executions back to their real records. Reuse revision checks,
|
|
60
|
+
Definition read, parameter update and execution visibility are distinct permissions. Execution queries must preserve the owning business record's data scope. Link definitions to their authorized executions and executions back to their real records. Reuse revision checks, immutable startup snapshots and parameter editors. An application with no process runtime has no empty workflow administration API or menu. If a workflow/approval plugin supplies its own catalogue contracts, read its installed Skill and adapt those contracts instead of assuming lifecycle APIs apply to it.
|
|
61
61
|
|
|
62
62
|
### Default process presentation
|
|
63
63
|
|
|
@@ -76,7 +76,7 @@ Whenever building or changing business behavior, inspect its conditions, limits,
|
|
|
76
76
|
| Business windows such as a reopening period | A bounded duration with explicit units and effective timing, where the installed runtime supports updating it |
|
|
77
77
|
| Notification copy or an existing supported business switch | The declared editable text or boolean, with the actual delivery or decision path reading the saved value |
|
|
78
78
|
|
|
79
|
-
For lifecycles, use the installed runtime's `parameterConfiguration`, store, service and editor contracts; read [configurable lifecycle parameters](lifecycle-parameters.md). For policy outside a lifecycle, use the application's existing configuration service or implement the application-owned contract in [business administration recipes](business-administration.md#business-parameters); lifecycle-only APIs are not a generic settings service. Declare defaults, schema, validation, bindings, authorization and
|
|
79
|
+
For lifecycles, use the installed runtime's `parameterConfiguration`, store, service and editor contracts; read [configurable lifecycle parameters](lifecycle-parameters.md). For policy outside a lifecycle, use the application's existing configuration service or implement the application-owned contract in [business administration recipes](business-administration.md#business-parameters); lifecycle-only APIs are not a generic settings service. Declare defaults, schema, validation, bindings, authorization and explicit start boundaries and immutable complete snapshots together. The server's actual route, reviewer resolver or business decision must consume the saved values. An editable form over a hard-coded condition does not satisfy this requirement. Reuse authoritative organization and account data; never guess an approver or substitute demonstration people. A single-assignee workflow must keep its decision semantics unless multi-candidate decisions are implemented and verified.
|
|
80
80
|
|
|
81
81
|
For lifecycles, deliver the workflow management entry and visible parameter forms as [Lifecycle UI](lifecycle-ui.md) describes. Provide diagram-bound Configure controls for declared, authorized bindings by default through `LifecycleDiagram.configuration`, opening the same editor or authoritative relationship settings. Configuration read without update permission remains read-only, and unbound elements retain ordinary inspection. The same stored configuration powers the inline form and any diagram entry. Respect explicit API-only scope and omitted interfaces.
|
|
82
82
|
|
|
@@ -213,4 +213,6 @@ When the target adds or changes the standard process UI sources, also follow [st
|
|
|
213
213
|
|
|
214
214
|
When the target introduces standard submission protection, follow [submission source upgrades](references/submission-upgrade.md) during planning and reconciliation. Dependency or version-marker changes alone do not update copied forms, custom actions or the application's receipt migrations. Verify both a fresh application and retained customized data.
|
|
215
215
|
|
|
216
|
+
When the application defines lifecycles (`defineLifecycle()`) and the target adds definition versions, follow [lifecycle definition versions upgrade](references/lifecycle-versioning-upgrade.md) in the same upgrade: give every definition `key` and `version`, add and backfill each process's definition field from its creation log with a conflict list, move category assignments to the key, and plan the write window and deployment order. Missing values only warn in this release and are required in the next minor release. For lifecycle behavior changes or deletion during an upgrade, follow the [Git freezing decision and user-confirmed retirement rules](../nocobase-app-development/references/lifecycle-versions.md); an upgrade does not itself authorize deleting definition code, merged migrations or historical data.
|
|
217
|
+
|
|
216
218
|
For a target that adds notification template administration, follow [notification template source reconciliation](references/notification-template-upgrade.md) in the same version-selected upgrade, preserving business renderers, workflows, permissions and channel configuration.
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# Lifecycle definition versions upgrade
|
|
2
|
+
|
|
3
|
+
The target release identifies each lifecycle definition by `key` and `version` and binds every record to the definition that created it through a record field named by `definitionField`; see [versions of a process](../../nocobase-app-development/references/lifecycle-versions.md). Installing the new packages rewrites no application source. A definition without `key` or `version` still registers as its name and 1, and one without `definitionField` still registers while its key has one version, each with a warning; the next minor release requires all three. Do this migration in the upgrade that brings the target, not later.
|
|
4
|
+
|
|
5
|
+
Adding `key` and `version` is metadata: it creates no second version and moves no entry point. Do not create a v2, rename a definition, change a `collection` or switch an entry point as part of this upgrade.
|
|
6
|
+
|
|
7
|
+
## Steps
|
|
8
|
+
|
|
9
|
+
1. **Inventory.** List every `defineLifecycle()` in the application and its local plugins, where each is registered, and every entry point that creates its records: pages, event subscribers, scheduled jobs, outside APIs and webhooks, imports, batches, commands and processes that create child processes. List the routes and services that read or move its records.
|
|
10
|
+
2. **Identity.** For each definition without them, add `key` equal to its current `name` and `version: 1`. Keep existing values; running the upgrade again changes nothing. Keep `name`, `collection`, the state field and every transition and effect name as they are, and write `collection` explicitly where it relied on the name default. Definitions the application already treats as versions of one process, such as `orders` and `orders2`, get one key only after you have confirmed from the code and its history that they are the same process and in which order they were introduced; never group by name similarity alone.
|
|
11
|
+
3. **Binding field.** For each process pick its definition field: reuse an existing column that already holds the definition name with that meaning, otherwise add a nullable `string` column, `lifecycleDefinition` by default. A table carrying two lifecycles gets one field per lifecycle (`approvalDefinition`, `paymentDefinition`). Every version of a key uses the same field. Declare it in the definition (`definitionField`), the Collection declaration and the record types. Index it only where list queries need it.
|
|
12
|
+
4. **Backfill migration.** Write one new, self-contained migration per table, after the newest existing migration of that source (names sort across every source, so check the application's and each plugin's latest name before choosing one). It never imports a live definition. Record in the migration whether the field is a column it adds or an existing column it reuses: an added column is created here and only then filled; a reused column is neither created nor altered, and only its empty values are filled. It fills the field for records a definition started:
|
|
13
|
+
- A table that only ever had one definition: set the field to that definition's name on every record the lifecycle started. When a table also holds records no process started, select the started ones by their `$create` entry in `lifecycleTransitions` (`lifecycle`, `recordId`, `transition = '$create'`), or by another reliable fact of the model; leave the rest empty.
|
|
14
|
+
- A table that has had several definitions: take each record's definition from its `$create` entry in `lifecycleTransitions`. A record whose entries name more than one definition, a started record with no `$create` entry, and an entry naming an unknown definition are conflicts.
|
|
15
|
+
- Keep a field that already holds a valid definition name. Never derive the binding from the current state, the record's age or the latest definition, and never default the column to an old name: that hides an entry point the upgrade missed.
|
|
16
|
+
- On any conflict, make the migration fail with the list of table, record id and the definitions found, so the upgrade stops before completion. Resolve each record with the user, record the decision and backfill it in a further migration; never pick one automatically.
|
|
17
|
+
- `down` undoes only what `up` did. For a column this migration added, it drops the column. For a reused column it drops nothing and changes no value the column held before; leave the backfilled values in place, since the reused column already carried that meaning, or clear exactly the values `up` wrote when they can be told apart, such as through a record of the ids it filled.
|
|
18
|
+
5. **Categories and other groupings.** Where the application classifies definitions (a workflow catalog, category assignments, dashboards), the grouping now belongs to the process key. Move each definition's assignment to its key. Two definitions of one key with different categories are a conflict: list them and ask; do not overwrite one with the other.
|
|
19
|
+
6. **Code paths.**
|
|
20
|
+
- Every `runtime.create()` names its definition explicitly.
|
|
21
|
+
- Routes and services that act on one record resolve its definition with `runtime.boundLifecycle(key, id)`, or `recordLifecycle(key, record)` for a record already read, then call `view()`, `fire()`, retries and continuations with that name. A page keeps calling the process's path; it never names a version.
|
|
22
|
+
- Seeds, imports, batches and child creation of configured flows must call `runtime.create()` so binding and complete parameters commit with the record. Parameterless legacy paths need no snapshot storage.
|
|
23
|
+
- No form, generic update endpoint, `set` or `accept` writes the definition field.
|
|
24
|
+
- Lists that filter by state use the union of the versions' states, and management pages count and page by the binding.
|
|
25
|
+
7. **Parameter snapshots.** Inventory all bound records, including completed records. Preserve valid snapshots and prefer verified creation usage. Only fields the released definition read live may be supplemented once from that bound version's effective upgrade-time configuration; freeze them with `origin: upgrade`, configuration revision and group/schema metadata. Keep submitted expense thresholds, source revisions and submission time; supplement only missing live timing fields. Missing or damaged formerly fixed snapshots, ambiguous bindings and invalid configuration still stop the full read-only preflight before writes. Match released defaults, parsing and reference-table fallbacks inside self-contained migrations; never import live definitions. Validate the final complete payload and repeat migration without overwriting valid snapshots. Stop writers/workers/schedulers and take complete backups through both preflight and application; restore the backup before rollback after new records exist.
|
|
26
|
+
8. **Write window and deployment.** Old code may create records between the migration and the new code starting. Deploy so that no record is created unbound: stop writers during the migration, or run a follow-up backfill after the new code is serving, or deploy the code that writes the binding first while the field is nullable. New definitions are available in every process and worker before an entry point starts them.
|
|
27
|
+
|
|
28
|
+
## Verify
|
|
29
|
+
|
|
30
|
+
- Every definition registers without the missing `key`, `version` or `definitionField` warning, and the key and version of each are what step 2 recorded.
|
|
31
|
+
- Running the upgrade steps again leaves every key, version and binding unchanged.
|
|
32
|
+
- A reused column is still there, with every value it held before the migration; only a column the migration added is dropped by its `down`.
|
|
33
|
+
- Every started record is bound to its original definition; records no process started remain empty; the migration failed with a list for every conflict, and each conflict has a recorded decision.
|
|
34
|
+
- An existing record still opens, shows its history and accepts its transitions; a new record from each entry point is bound to the expected definition; a record of one lifecycle never receives another's binding on a table that carries two.
|
|
35
|
+
- Triggers, effect retries and continuations of existing records still run.
|
|
36
|
+
- Parameter values resolved for an existing record are unchanged.
|
|
37
|
+
- Report each definition's key and version, its binding field, the backfill rule used per table, every conflict and its decision, and any entry point or customized path you could not verify.
|
|
38
|
+
|
|
39
|
+
Office previously read its configurable parameters live, so its bound records can receive one-time upgrade snapshots, including completed records. Preserve actual submitted snapshots and historical execution facts; never claim upgrade values were creation-time facts.
|
|
40
|
+
|
|
41
|
+
Custom adapters implement `LifecycleStore.findRecords(collection, ids)` as bounded transactional primary-key batch reads, with no query for empty IDs and no loop of individual reads. Include approval-extension adapters in the same rebuild/typecheck. Stop all writers, workers and schedulers through full preflight and application; keep complete backups and preserve snapshot/receipt evidence during rollback.
|
|
42
|
+
|
|
43
|
+
A new process or version does not replace supplementing old records: instance details and execution still need their own complete snapshots. Keep old definitions registered and their behavior dependencies intact for retained records and tasks until explicit user retirement confirmation permits code removal; old records can continue in the same database without waiting for completion.
|
|
44
|
+
|
|
45
|
+
For future behavior changes to a frozen version, create a new version and explicitly switch selected new-record entry points, listing switched and retained entries. Use the target main branch and `key`/`version`/`name` to determine freezing; newly introduced unmerged versions can continue to be edited. Parameter value edits follow configuration and snapshot rules rather than contract versioning.
|
|
46
|
+
|
|
47
|
+
Follow the [edit decision and deletion procedure](../../nocobase-app-development/references/lifecycle-versions.md) for ambiguity, shared dependencies and retirement. Reuse equivalent explicit user confirmation without requiring production access, query evidence or another confirmation; preserve merged migrations and historical data. Do not add instance rebinding, runtime dynamic supplementation, an archive requirement or a compatibility switch.
|