@dynamatix/gb-schemas 1.3.334 → 1.3.336

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +22 -0
  2. package/dist/applications/application-note.model.d.ts +12 -6
  3. package/dist/applications/application-note.model.d.ts.map +1 -1
  4. package/dist/applications/application-note.model.js +3 -1
  5. package/dist/applications/application-note.type.d.ts +2 -1
  6. package/dist/applications/application-note.type.d.ts.map +1 -1
  7. package/dist/index.d.ts +1 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -0
  10. package/dist/shared/index.d.ts +1 -0
  11. package/dist/shared/index.d.ts.map +1 -1
  12. package/dist/shared/index.js +2 -0
  13. package/dist/shared/workflow-trigger.model.d.ts +32 -0
  14. package/dist/shared/workflow-trigger.model.d.ts.map +1 -0
  15. package/dist/shared/workflow-trigger.model.js +45 -0
  16. package/dist/shared/workflow-trigger.type.d.ts +59 -0
  17. package/dist/shared/workflow-trigger.type.d.ts.map +1 -0
  18. package/dist/shared/workflow-trigger.type.js +1 -0
  19. package/dist/shared/workflow.init.d.ts +21 -0
  20. package/dist/shared/workflow.init.d.ts.map +1 -0
  21. package/dist/shared/workflow.init.js +38 -0
  22. package/dist/shared/workflow.middleware.d.ts +100 -0
  23. package/dist/shared/workflow.middleware.d.ts.map +1 -0
  24. package/dist/shared/workflow.middleware.js +209 -0
  25. package/dist/shared/workflow.plugin.d.ts +46 -0
  26. package/dist/shared/workflow.plugin.d.ts.map +1 -0
  27. package/dist/shared/workflow.plugin.js +72 -0
  28. package/dist/shared/workflow.service.d.ts +39 -0
  29. package/dist/shared/workflow.service.d.ts.map +1 -0
  30. package/dist/shared/workflow.service.js +114 -0
  31. package/package.json +1 -1
package/README.md CHANGED
@@ -20,6 +20,7 @@ This package contains all the schemas and data models used in Gatehouse Bank's b
20
20
  - **TypeScript Support**: Full TypeScript definitions and type safety
21
21
  - **Mongoose Integration**: Built on Mongoose ODM for MongoDB
22
22
  - **Audit Middleware**: Built-in audit trail support via `@dynamatix/cat-shared`
23
+ - **Workflow Middleware**: Automatic workflow triggering based on database events
23
24
  - **Custom Value Objects**: Specialized types for financial data (Pound, Account Number, Sort Code)
24
25
  - **Modular Architecture**: Organized into logical domains (applications, applicants, properties, etc.)
25
26
  - **Migration Scripts**: Comprehensive data migration and maintenance tools
@@ -88,6 +89,26 @@ const newIncome = new ApplicantIncomeModel({
88
89
  const savedIncome = await newIncome.save();
89
90
  ```
90
91
 
92
+ ### Workflow Middleware
93
+
94
+ The library includes a powerful workflow middleware system that automatically triggers workflows based on database events.
95
+
96
+ ```typescript
97
+ import { initializeWorkflowMiddlewareWithCheck } from '@dynamatix/gb-schemas';
98
+
99
+ // Initialize workflow middleware for ALL schemas with one call
100
+ initializeWorkflowMiddlewareWithCheck();
101
+ ```
102
+
103
+ **Environment Variables:**
104
+ - `WORKFLOW_API_KEY`: Required API key for workflow service authentication
105
+ - `WORKFLOW_API_URL`: Optional workflow API URL (default: https://your-workflow-api.com/api/v1/workflows/execute)
106
+ - `WORKFLOW_TIMEOUT`: Optional timeout in milliseconds (default: 30000)
107
+ - `WORKFLOW_RETRY_ATTEMPTS`: Optional retry attempts (default: 3)
108
+ - `WORKFLOW_RETRY_DELAY`: Optional retry delay in milliseconds (default: 1000)
109
+
110
+ For detailed documentation, see [Workflow Middleware Guide](./docs/WORKFLOW_MIDDLEWARE.md).
111
+
91
112
  ## 🏛️ Core Schemas
92
113
 
93
114
  ### Applicants
@@ -118,6 +139,7 @@ const savedIncome = await newIncome.save();
118
139
  - **System Parameters**: Configuration and system settings
119
140
  - **Tasks**: Workflow task management
120
141
  - **Alerts**: System notification system
142
+ - **Workflow Triggers**: Configuration for automatic workflow execution
121
143
 
122
144
  ## 💰 Custom Value Objects
123
145
 
@@ -37,7 +37,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
37
37
  subject: string;
38
38
  note: string;
39
39
  reminderDate: string;
40
- attachmentDocumentId: string;
41
40
  assignedOperation: string;
42
41
  autoCreated: string;
43
42
  additionalData: any;
@@ -49,6 +48,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
49
48
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
50
49
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
51
50
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
51
+ attachmentDocumentId?: string | null | undefined;
52
+ documentName?: string | null | undefined;
52
53
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
53
54
  }, {}, {}, {}, mongoose.Document<unknown, {}, {
54
55
  comment: string;
@@ -60,7 +61,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
60
61
  subject: string;
61
62
  note: string;
62
63
  reminderDate: string;
63
- attachmentDocumentId: string;
64
64
  assignedOperation: string;
65
65
  autoCreated: string;
66
66
  additionalData: any;
@@ -72,6 +72,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
72
72
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
73
73
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
74
74
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
75
+ attachmentDocumentId?: string | null | undefined;
76
+ documentName?: string | null | undefined;
75
77
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
76
78
  }, {}> & {
77
79
  comment: string;
@@ -83,7 +85,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
83
85
  subject: string;
84
86
  note: string;
85
87
  reminderDate: string;
86
- attachmentDocumentId: string;
87
88
  assignedOperation: string;
88
89
  autoCreated: string;
89
90
  additionalData: any;
@@ -95,6 +96,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
95
96
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
96
97
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
97
98
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
99
+ attachmentDocumentId?: string | null | undefined;
100
+ documentName?: string | null | undefined;
98
101
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
99
102
  } & {
100
103
  _id: mongoose.Types.ObjectId;
@@ -110,7 +113,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
110
113
  subject: string;
111
114
  note: string;
112
115
  reminderDate: string;
113
- attachmentDocumentId: string;
114
116
  assignedOperation: string;
115
117
  autoCreated: string;
116
118
  additionalData: any;
@@ -122,6 +124,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
122
124
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
123
125
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
124
126
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
127
+ attachmentDocumentId?: string | null | undefined;
128
+ documentName?: string | null | undefined;
125
129
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
126
130
  }, mongoose.Document<unknown, {}, mongoose.FlatRecord<{
127
131
  comment: string;
@@ -133,7 +137,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
133
137
  subject: string;
134
138
  note: string;
135
139
  reminderDate: string;
136
- attachmentDocumentId: string;
137
140
  assignedOperation: string;
138
141
  autoCreated: string;
139
142
  additionalData: any;
@@ -145,6 +148,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
145
148
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
146
149
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
147
150
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
151
+ attachmentDocumentId?: string | null | undefined;
152
+ documentName?: string | null | undefined;
148
153
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
149
154
  }>, {}> & mongoose.FlatRecord<{
150
155
  comment: string;
@@ -156,7 +161,6 @@ declare const ApplictionNoteModel: mongoose.Model<{
156
161
  subject: string;
157
162
  note: string;
158
163
  reminderDate: string;
159
- attachmentDocumentId: string;
160
164
  assignedOperation: string;
161
165
  autoCreated: string;
162
166
  additionalData: any;
@@ -168,6 +172,8 @@ declare const ApplictionNoteModel: mongoose.Model<{
168
172
  createdByUserId?: mongoose.Types.ObjectId | null | undefined;
169
173
  noteTypeLid?: mongoose.Types.ObjectId | null | undefined;
170
174
  noteSubTypeLid?: mongoose.Types.ObjectId | null | undefined;
175
+ attachmentDocumentId?: string | null | undefined;
176
+ documentName?: string | null | undefined;
171
177
  assignedByUserId?: mongoose.Types.ObjectId | null | undefined;
172
178
  }> & {
173
179
  _id: mongoose.Types.ObjectId;
@@ -1 +1 @@
1
- {"version":3,"file":"application-note.model.d.ts","sourceRoot":"","sources":["../../applications/application-note.model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAmFhC,QAAA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA+C,CAAC;AACzE,eAAe,mBAAmB,CAAC"}
1
+ {"version":3,"file":"application-note.model.d.ts","sourceRoot":"","sources":["../../applications/application-note.model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAqFhC,QAAA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAA+C,CAAC;AACzE,eAAe,mBAAmB,CAAC"}
@@ -36,7 +36,9 @@ const noteSchema = new mongoose.Schema({
36
36
  },
37
37
  attachmentDocumentId: {
38
38
  type: String,
39
- default: null
39
+ },
40
+ documentName: {
41
+ type: String,
40
42
  },
41
43
  assignedOperation: {
42
44
  type: String,
@@ -40,7 +40,8 @@ export default interface IApplicationNoteType extends IBaseType {
40
40
  subject?: string | null;
41
41
  note: string;
42
42
  reminderDate?: string | null;
43
- attachmentDocumentId?: string | null;
43
+ attachmentDocumentId?: string;
44
+ documentName?: string;
44
45
  assignedOperation?: string;
45
46
  autoCreated?: boolean;
46
47
  additionalData?: any;
@@ -1 +1 @@
1
- {"version":3,"file":"application-note.type.d.ts","sourceRoot":"","sources":["../../applications/application-note.type.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhD,MAAM,CAAC,OAAO,WAAW,oBAAqB,SAAQ,SAAS;IAC3D,aAAa,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,eAAe,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACxC,WAAW,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACpC,cAAc,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,cAAc,CAAC,EAAE,GAAG,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACzC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B"}
1
+ {"version":3,"file":"application-note.type.d.ts","sourceRoot":"","sources":["../../applications/application-note.type.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,UAAU,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAEhD,MAAM,CAAC,OAAO,WAAW,oBAAqB,SAAQ,SAAS;IAC3D,aAAa,EAAE,KAAK,CAAC,QAAQ,CAAC;IAC9B,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,eAAe,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACxC,WAAW,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACpC,cAAc,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,cAAc,CAAC,EAAE,GAAG,CAAC;IACrB,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,gBAAgB,CAAC,EAAE,KAAK,CAAC,QAAQ,GAAG,IAAI,CAAC;IACzC,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B"}
package/dist/index.d.ts CHANGED
@@ -5,4 +5,5 @@ export * from './applicants/index.js';
5
5
  export * from './users/index.js';
6
6
  export * from './product-catalogues/index.js';
7
7
  export * from './underwriter/index.js';
8
+ export { initializeWorkflowMiddleware, initializeWorkflowMiddlewareWithCheck, isWorkflowMiddlewareConfigured } from './shared/index.js';
8
9
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,mBAAmB,CAAC;AAClC,cAAc,uBAAuB,CAAC;AACtC,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,+BAA+B,CAAC;AAC9C,cAAc,wBAAwB,CAAC;AAGvC,OAAO,EACH,4BAA4B,EAC5B,qCAAqC,EACrC,8BAA8B,EACjC,MAAM,mBAAmB,CAAC"}
package/dist/index.js CHANGED
@@ -5,3 +5,5 @@ export * from './applicants/index.js';
5
5
  export * from './users/index.js';
6
6
  export * from './product-catalogues/index.js';
7
7
  export * from './underwriter/index.js';
8
+ // Re-export workflow middleware initialization for easy access
9
+ export { initializeWorkflowMiddleware, initializeWorkflowMiddlewareWithCheck, isWorkflowMiddlewareConfigured } from './shared/index.js';
@@ -13,4 +13,5 @@ export { default as TaskDocumentTypeModel } from './task-document.model';
13
13
  export { default as SchemaDocModel } from './schema-doc.model';
14
14
  export { default as ApiLogModel } from './api-log.model';
15
15
  export { default as IWebhookEvent } from './webhook-event.type';
16
+ export { initializeWorkflowMiddleware, initializeWorkflowMiddlewareWithCheck, isWorkflowMiddlewareConfigured } from './workflow.init';
16
17
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../shared/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,qBAAqB,CAAA;AAChE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../shared/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,OAAO,IAAI,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,OAAO,IAAI,UAAU,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAE,OAAO,IAAI,eAAe,EAAE,MAAM,qBAAqB,CAAA;AAChE,OAAO,EAAE,OAAO,IAAI,SAAS,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAAE,OAAO,IAAI,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAClF,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,OAAO,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACnE,OAAO,EAAE,OAAO,IAAI,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AACzE,OAAO,EAAE,OAAO,IAAI,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAAE,OAAO,IAAI,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGhE,OAAO,EAAE,4BAA4B,EAAE,qCAAqC,EAAE,8BAA8B,EAAE,MAAM,iBAAiB,CAAC"}
@@ -11,3 +11,5 @@ export { default as WebhookEventModel } from './webhook-event.model';
11
11
  export { default as TaskDocumentTypeModel } from './task-document.model';
12
12
  export { default as SchemaDocModel } from './schema-doc.model';
13
13
  export { default as ApiLogModel } from './api-log.model';
14
+ // Workflow middleware initialization exports
15
+ export { initializeWorkflowMiddleware, initializeWorkflowMiddlewareWithCheck, isWorkflowMiddlewareConfigured } from './workflow.init';
@@ -0,0 +1,32 @@
1
+ /// <reference path="../value-objects/pound.d.ts" />
2
+ /// <reference path="../value-objects/account-number.d.ts" />
3
+ /// <reference path="../value-objects/sort-code.d.ts" />
4
+ /// <reference types="mongoose/types/aggregate" />
5
+ /// <reference types="mongoose/types/callback" />
6
+ /// <reference types="mongoose/types/collection" />
7
+ /// <reference types="mongoose/types/connection" />
8
+ /// <reference types="mongoose/types/cursor" />
9
+ /// <reference types="mongoose/types/document" />
10
+ /// <reference types="mongoose/types/error" />
11
+ /// <reference types="mongoose/types/expressions" />
12
+ /// <reference types="mongoose/types/helpers" />
13
+ /// <reference types="mongoose/types/middlewares" />
14
+ /// <reference types="mongoose/types/indexes" />
15
+ /// <reference types="mongoose/types/models" />
16
+ /// <reference types="mongoose/types/mongooseoptions" />
17
+ /// <reference types="mongoose/types/pipelinestage" />
18
+ /// <reference types="mongoose/types/populate" />
19
+ /// <reference types="mongoose/types/query" />
20
+ /// <reference types="mongoose/types/schemaoptions" />
21
+ /// <reference types="mongoose/types/session" />
22
+ /// <reference types="mongoose/types/types" />
23
+ /// <reference types="mongoose/types/utility" />
24
+ /// <reference types="mongoose/types/validation" />
25
+ /// <reference types="mongoose/types/virtuals" />
26
+ /// <reference types="mongoose/types/schematypes" />
27
+ /// <reference types="mongoose/types/inferschematype" />
28
+ /// <reference types="mongoose/types/inferrawdoctype" />
29
+ import mongoose from 'mongoose';
30
+ declare const _default: mongoose.Model<any, {}, {}, {}, any, any>;
31
+ export default _default;
32
+ //# sourceMappingURL=workflow-trigger.model.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-trigger.model.d.ts","sourceRoot":"","sources":["../../shared/workflow-trigger.model.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAoB,MAAM,UAAU,CAAC;;AAmD5C,wBAA6H"}
@@ -0,0 +1,45 @@
1
+ import mongoose, { Schema } from 'mongoose';
2
+ const WorkflowTriggerSchema = new Schema({
3
+ triggerKey: {
4
+ type: String,
5
+ required: true,
6
+ unique: true,
7
+ index: true
8
+ },
9
+ description: {
10
+ type: String,
11
+ required: true
12
+ },
13
+ isActive: {
14
+ type: Boolean,
15
+ default: true,
16
+ index: true
17
+ },
18
+ condition: {
19
+ type: String,
20
+ required: true
21
+ },
22
+ workflowKey: {
23
+ type: String,
24
+ required: true,
25
+ index: true
26
+ },
27
+ requiredVariables: [{
28
+ type: String,
29
+ required: true
30
+ }],
31
+ optionalVariables: [{
32
+ type: String
33
+ }],
34
+ validationRules: {
35
+ type: Schema.Types.Mixed
36
+ },
37
+ metadata: {
38
+ type: Schema.Types.Mixed
39
+ }
40
+ }, { timestamps: true });
41
+ // Index for efficient querying
42
+ WorkflowTriggerSchema.index({ triggerKey: 1, isActive: 1 });
43
+ WorkflowTriggerSchema.index({ workflowKey: 1, isActive: 1 });
44
+ // Conditional model registration to avoid "Cannot overwrite model" errors
45
+ export default mongoose.models.WorkflowTrigger || mongoose.model('WorkflowTrigger', WorkflowTriggerSchema);
@@ -0,0 +1,59 @@
1
+ /// <reference path="../value-objects/pound.d.ts" />
2
+ /// <reference path="../value-objects/account-number.d.ts" />
3
+ /// <reference path="../value-objects/sort-code.d.ts" />
4
+ /// <reference types="mongoose/types/aggregate" />
5
+ /// <reference types="mongoose/types/callback" />
6
+ /// <reference types="mongoose/types/collection" />
7
+ /// <reference types="mongoose/types/connection" />
8
+ /// <reference types="mongoose/types/cursor" />
9
+ /// <reference types="mongoose/types/document" />
10
+ /// <reference types="mongoose/types/error" />
11
+ /// <reference types="mongoose/types/expressions" />
12
+ /// <reference types="mongoose/types/helpers" />
13
+ /// <reference types="mongoose/types/middlewares" />
14
+ /// <reference types="mongoose/types/indexes" />
15
+ /// <reference types="mongoose/types/models" />
16
+ /// <reference types="mongoose/types/mongooseoptions" />
17
+ /// <reference types="mongoose/types/pipelinestage" />
18
+ /// <reference types="mongoose/types/populate" />
19
+ /// <reference types="mongoose/types/query" />
20
+ /// <reference types="mongoose/types/schemaoptions" />
21
+ /// <reference types="mongoose/types/session" />
22
+ /// <reference types="mongoose/types/types" />
23
+ /// <reference types="mongoose/types/utility" />
24
+ /// <reference types="mongoose/types/validation" />
25
+ /// <reference types="mongoose/types/virtuals" />
26
+ /// <reference types="mongoose/types/schematypes" />
27
+ /// <reference types="mongoose/types/inferschematype" />
28
+ /// <reference types="mongoose/types/inferrawdoctype" />
29
+ import { Document } from 'mongoose';
30
+ export default interface IWorkflowTrigger extends Document {
31
+ triggerKey: string;
32
+ description: string;
33
+ isActive: boolean;
34
+ condition: string;
35
+ workflowKey: string;
36
+ requiredVariables: string[];
37
+ optionalVariables?: string[];
38
+ validationRules?: any;
39
+ metadata?: any;
40
+ createdAt: Date;
41
+ updatedAt: Date;
42
+ }
43
+ export interface WorkflowTriggerEvent {
44
+ recordType: string;
45
+ action: string;
46
+ triggerKey: string;
47
+ }
48
+ export interface WorkflowApiPayload {
49
+ workflowKey: string;
50
+ version: number;
51
+ variables: Record<string, any>;
52
+ }
53
+ export interface WorkflowMiddlewareOptions {
54
+ workflowApiUrl: string;
55
+ timeout?: number;
56
+ retryAttempts?: number;
57
+ retryDelay?: number;
58
+ }
59
+ //# sourceMappingURL=workflow-trigger.type.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-trigger.type.d.ts","sourceRoot":"","sources":["../../shared/workflow-trigger.type.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAEpC,MAAM,CAAC,OAAO,WAAW,gBAAiB,SAAQ,QAAQ;IACtD,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,iBAAiB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC7B,eAAe,CAAC,EAAE,GAAG,CAAC;IACtB,QAAQ,CAAC,EAAE,GAAG,CAAC;IACf,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,EAAE,IAAI,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACjC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,kBAAkB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;CAClC;AAED,MAAM,WAAW,yBAAyB;IACtC,cAAc,EAAE,MAAM,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,UAAU,CAAC,EAAE,MAAM,CAAC;CACvB"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Initialize workflow middleware for all schemas
3
+ * Call this function once in your application startup to enable workflow middleware globally
4
+ *
5
+ * This will automatically apply workflow middleware to all Mongoose schemas
6
+ * The record type will be inferred from the model name (e.g., 'Application' -> 'applications')
7
+ */
8
+ export declare function initializeWorkflowMiddleware(): void;
9
+ /**
10
+ * Check if workflow middleware is properly configured
11
+ * @returns true if all required environment variables are set
12
+ */
13
+ export declare function isWorkflowMiddlewareConfigured(): boolean;
14
+ /**
15
+ * Initialize workflow middleware with configuration check
16
+ * @param options - Optional configuration options
17
+ */
18
+ export declare function initializeWorkflowMiddlewareWithCheck(options?: {
19
+ skipConfigCheck?: boolean;
20
+ }): boolean;
21
+ //# sourceMappingURL=workflow.init.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.init.d.ts","sourceRoot":"","sources":["../../shared/workflow.init.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,wBAAgB,4BAA4B,SAI3C;AAED;;;GAGG;AACH,wBAAgB,8BAA8B,IAAI,OAAO,CAUxD;AAED;;;GAGG;AACH,wBAAgB,qCAAqC,CAAC,OAAO,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAA;CAAE,WAQ5F"}
@@ -0,0 +1,38 @@
1
+ import { registerWorkflowPlugin } from './workflow.plugin';
2
+ /**
3
+ * Initialize workflow middleware for all schemas
4
+ * Call this function once in your application startup to enable workflow middleware globally
5
+ *
6
+ * This will automatically apply workflow middleware to all Mongoose schemas
7
+ * The record type will be inferred from the model name (e.g., 'Application' -> 'applications')
8
+ */
9
+ export function initializeWorkflowMiddleware() {
10
+ console.log('Initializing workflow middleware for all schemas...');
11
+ registerWorkflowPlugin();
12
+ console.log('Workflow middleware initialized successfully');
13
+ }
14
+ /**
15
+ * Check if workflow middleware is properly configured
16
+ * @returns true if all required environment variables are set
17
+ */
18
+ export function isWorkflowMiddlewareConfigured() {
19
+ const requiredEnvVars = ['WORKFLOW_API_KEY'];
20
+ const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
21
+ if (missingVars.length > 0) {
22
+ console.warn(`Missing required environment variables for workflow middleware: ${missingVars.join(', ')}`);
23
+ return false;
24
+ }
25
+ return true;
26
+ }
27
+ /**
28
+ * Initialize workflow middleware with configuration check
29
+ * @param options - Optional configuration options
30
+ */
31
+ export function initializeWorkflowMiddlewareWithCheck(options) {
32
+ if (!options?.skipConfigCheck && !isWorkflowMiddlewareConfigured()) {
33
+ console.warn('Workflow middleware configuration incomplete. Middleware will be disabled.');
34
+ return false;
35
+ }
36
+ initializeWorkflowMiddleware();
37
+ return true;
38
+ }
@@ -0,0 +1,100 @@
1
+ /// <reference path="../value-objects/pound.d.ts" />
2
+ /// <reference path="../value-objects/account-number.d.ts" />
3
+ /// <reference path="../value-objects/sort-code.d.ts" />
4
+ /// <reference types="mongoose/types/aggregate" />
5
+ /// <reference types="mongoose/types/callback" />
6
+ /// <reference types="mongoose/types/collection" />
7
+ /// <reference types="mongoose/types/connection" />
8
+ /// <reference types="mongoose/types/cursor" />
9
+ /// <reference types="mongoose/types/document" />
10
+ /// <reference types="mongoose/types/error" />
11
+ /// <reference types="mongoose/types/expressions" />
12
+ /// <reference types="mongoose/types/helpers" />
13
+ /// <reference types="mongoose/types/middlewares" />
14
+ /// <reference types="mongoose/types/indexes" />
15
+ /// <reference types="mongoose/types/models" />
16
+ /// <reference types="mongoose/types/mongooseoptions" />
17
+ /// <reference types="mongoose/types/pipelinestage" />
18
+ /// <reference types="mongoose/types/populate" />
19
+ /// <reference types="mongoose/types/query" />
20
+ /// <reference types="mongoose/types/schemaoptions" />
21
+ /// <reference types="mongoose/types/session" />
22
+ /// <reference types="mongoose/types/types" />
23
+ /// <reference types="mongoose/types/utility" />
24
+ /// <reference types="mongoose/types/validation" />
25
+ /// <reference types="mongoose/types/virtuals" />
26
+ /// <reference types="mongoose/types/schematypes" />
27
+ /// <reference types="mongoose/types/inferschematype" />
28
+ /// <reference types="mongoose/types/inferrawdoctype" />
29
+ import mongoose from 'mongoose';
30
+ import { WorkflowTriggerEvent, WorkflowMiddlewareOptions } from './workflow-trigger.type';
31
+ export declare class WorkflowMiddleware {
32
+ private workflowService;
33
+ private options;
34
+ constructor(options?: Partial<WorkflowMiddlewareOptions>);
35
+ /**
36
+ * Safely gets the WorkflowTrigger model, handling potential registration issues
37
+ */
38
+ private getWorkflowTriggerModel;
39
+ /**
40
+ * Creates a Mongoose middleware function for a specific model
41
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
42
+ * @returns Mongoose middleware function
43
+ */
44
+ createMiddleware(recordType: string): {
45
+ postSave: (this: any, doc: any, next: Function) => Promise<void>;
46
+ postRemove: (this: any, doc: any, next: Function) => Promise<void>;
47
+ };
48
+ /**
49
+ * Handles a workflow trigger event
50
+ * @param event - The workflow trigger event
51
+ * @param document - The document that triggered the event
52
+ */
53
+ handleEvent(event: WorkflowTriggerEvent, document: any): Promise<void>;
54
+ /**
55
+ * Processes a single workflow trigger
56
+ * @param trigger - The workflow trigger configuration
57
+ * @param document - The document that triggered the event
58
+ * @param event - The workflow trigger event
59
+ */
60
+ private processTrigger;
61
+ /**
62
+ * Evaluates a condition against a document
63
+ * @param condition - The condition string to evaluate
64
+ * @param document - The document to evaluate against
65
+ * @returns true if condition is met
66
+ */
67
+ private evaluateCondition;
68
+ /**
69
+ * Extracts metadata from document and event
70
+ * @param document - The document
71
+ * @param event - The event
72
+ * @returns Metadata object
73
+ */
74
+ private extractMetadata;
75
+ /**
76
+ * Manually trigger a workflow for a specific document
77
+ * @param triggerKey - The trigger key to use
78
+ * @param document - The document to process
79
+ * @param recordType - The record type
80
+ */
81
+ manualTrigger(triggerKey: string, document: any, recordType: string): Promise<void>;
82
+ }
83
+ /**
84
+ * Factory function to create workflow middleware for a model
85
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
86
+ * @param options - Optional workflow middleware options (overrides env vars)
87
+ * @returns Mongoose middleware functions
88
+ */
89
+ export declare function createWorkflowMiddleware(recordType: string, options?: Partial<WorkflowMiddlewareOptions>): {
90
+ postSave: (this: any, doc: any, next: Function) => Promise<void>;
91
+ postRemove: (this: any, doc: any, next: Function) => Promise<void>;
92
+ };
93
+ /**
94
+ * Utility function to apply workflow middleware to a Mongoose schema
95
+ * @param schema - The Mongoose schema
96
+ * @param recordType - The type of record
97
+ * @param options - Optional workflow middleware options (overrides env vars)
98
+ */
99
+ export declare function applyWorkflowMiddleware(schema: mongoose.Schema, recordType: string, options?: Partial<WorkflowMiddlewareOptions>): void;
100
+ //# sourceMappingURL=workflow.middleware.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.middleware.d.ts","sourceRoot":"","sources":["../../shared/workflow.middleware.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAGhC,OAAO,EACH,oBAAoB,EAEpB,yBAAyB,EAC5B,MAAM,yBAAyB,CAAC;AAEjC,qBAAa,kBAAkB;IAC3B,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,OAAO,CAA4B;gBAE/B,OAAO,CAAC,EAAE,OAAO,CAAC,yBAAyB,CAAC;IAYxD;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAS/B;;;;OAIG;IACH,gBAAgB,CAAC,UAAU,EAAE,MAAM;yBAGK,GAAG,OAAO,GAAG,QAAQ,QAAQ;2BAgB3B,GAAG,OAAO,GAAG,QAAQ,QAAQ;;IAiBvE;;;;OAIG;IACG,WAAW,CAAC,KAAK,EAAE,oBAAoB,EAAE,QAAQ,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC;IAwB5E;;;;;OAKG;YACW,cAAc;IA4C5B;;;;;OAKG;IACH,OAAO,CAAC,iBAAiB;IAkBzB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAUvB;;;;;OAKG;IACG,aAAa,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;CAS5F;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,yBAAyB,CAAC;;;EAGxG;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,yBAAyB,CAAC,QAShI"}
@@ -0,0 +1,209 @@
1
+ import WorkflowTriggerModel from './workflow-trigger.model';
2
+ import { WorkflowService } from './workflow.service';
3
+ export class WorkflowMiddleware {
4
+ constructor(options) {
5
+ // Read configuration from environment variables with fallbacks
6
+ this.options = {
7
+ workflowApiUrl: process.env.WORKFLOW_API_URL || 'https://your-workflow-api.com/api/v1/workflows/execute',
8
+ timeout: parseInt(process.env.WORKFLOW_TIMEOUT || '30000'),
9
+ retryAttempts: parseInt(process.env.WORKFLOW_RETRY_ATTEMPTS || '3'),
10
+ retryDelay: parseInt(process.env.WORKFLOW_RETRY_DELAY || '1000'),
11
+ ...options // Allow override of specific options
12
+ };
13
+ this.workflowService = new WorkflowService(this.options);
14
+ }
15
+ /**
16
+ * Safely gets the WorkflowTrigger model, handling potential registration issues
17
+ */
18
+ getWorkflowTriggerModel() {
19
+ try {
20
+ return WorkflowTriggerModel;
21
+ }
22
+ catch (error) {
23
+ console.error('Error accessing WorkflowTrigger model:', error);
24
+ throw new Error('WorkflowTrigger model is not properly registered');
25
+ }
26
+ }
27
+ /**
28
+ * Creates a Mongoose middleware function for a specific model
29
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
30
+ * @returns Mongoose middleware function
31
+ */
32
+ createMiddleware(recordType) {
33
+ return {
34
+ // Post-save middleware for create and update operations
35
+ postSave: async function (doc, next) {
36
+ try {
37
+ const middleware = new WorkflowMiddleware(this.options || {});
38
+ await middleware.handleEvent({
39
+ recordType,
40
+ action: doc.isNew ? 'created' : 'updated',
41
+ triggerKey: `${recordType}.${doc.isNew ? 'created' : 'updated'}`
42
+ }, doc);
43
+ }
44
+ catch (error) {
45
+ console.error('Workflow middleware error:', error);
46
+ // Don't throw error to avoid breaking the main operation
47
+ }
48
+ next();
49
+ }.bind(this),
50
+ // Post-remove middleware for delete operations
51
+ postRemove: async function (doc, next) {
52
+ try {
53
+ const middleware = new WorkflowMiddleware(this.options || {});
54
+ await middleware.handleEvent({
55
+ recordType,
56
+ action: 'deleted',
57
+ triggerKey: `${recordType}.deleted`
58
+ }, doc);
59
+ }
60
+ catch (error) {
61
+ console.error('Workflow middleware error:', error);
62
+ // Don't throw error to avoid breaking the main operation
63
+ }
64
+ next();
65
+ }.bind(this)
66
+ };
67
+ }
68
+ /**
69
+ * Handles a workflow trigger event
70
+ * @param event - The workflow trigger event
71
+ * @param document - The document that triggered the event
72
+ */
73
+ async handleEvent(event, document) {
74
+ try {
75
+ // Find active triggers for this event
76
+ const WorkflowTrigger = this.getWorkflowTriggerModel();
77
+ const triggers = await WorkflowTrigger.find({
78
+ triggerKey: event.triggerKey,
79
+ isActive: true
80
+ });
81
+ if (triggers.length === 0) {
82
+ console.log(`No active triggers found for ${event.triggerKey}`);
83
+ return;
84
+ }
85
+ // Process each trigger
86
+ for (const trigger of triggers) {
87
+ await this.processTrigger(trigger, document, event);
88
+ }
89
+ }
90
+ catch (error) {
91
+ console.error(`Error handling workflow event ${event.triggerKey}:`, error);
92
+ }
93
+ }
94
+ /**
95
+ * Processes a single workflow trigger
96
+ * @param trigger - The workflow trigger configuration
97
+ * @param document - The document that triggered the event
98
+ * @param event - The workflow trigger event
99
+ */
100
+ async processTrigger(trigger, document, event) {
101
+ try {
102
+ // Check if condition is met (if specified)
103
+ if (trigger.condition && !this.evaluateCondition(trigger.condition, document)) {
104
+ console.log(`Condition not met for trigger ${trigger.triggerKey}`);
105
+ return;
106
+ }
107
+ // Extract variables from document
108
+ const variables = this.workflowService.extractVariables(trigger.requiredVariables, trigger.optionalVariables || [], document);
109
+ // Validate required variables
110
+ if (!this.workflowService.validateRequiredVariables(trigger.requiredVariables, variables)) {
111
+ console.warn(`Required variables missing for trigger ${trigger.triggerKey}`);
112
+ return;
113
+ }
114
+ // Add metadata
115
+ const enrichedVariables = {
116
+ ...variables,
117
+ ...this.extractMetadata(document, event)
118
+ };
119
+ // Create workflow payload
120
+ const payload = {
121
+ workflowKey: trigger.workflowKey,
122
+ version: 1, // Default version, could be made configurable
123
+ variables: enrichedVariables
124
+ };
125
+ // Trigger workflow in background
126
+ await this.workflowService.triggerWorkflow(payload);
127
+ console.log(`Workflow ${trigger.workflowKey} triggered for ${event.triggerKey}`);
128
+ }
129
+ catch (error) {
130
+ console.error(`Error processing trigger ${trigger.triggerKey}:`, error);
131
+ }
132
+ }
133
+ /**
134
+ * Evaluates a condition against a document
135
+ * @param condition - The condition string to evaluate
136
+ * @param document - The document to evaluate against
137
+ * @returns true if condition is met
138
+ */
139
+ evaluateCondition(condition, document) {
140
+ try {
141
+ // Simple condition evaluation - could be enhanced with a proper expression parser
142
+ // For now, supporting basic field checks like "status === 'active'"
143
+ if (condition.includes('===')) {
144
+ const [field, value] = condition.split('===').map(s => s.trim());
145
+ const fieldValue = this.workflowService['getNestedValue'](document, field);
146
+ return fieldValue === value.replace(/['"]/g, '');
147
+ }
148
+ // Default to true if condition format is not recognized
149
+ return true;
150
+ }
151
+ catch (error) {
152
+ console.error('Error evaluating condition:', error);
153
+ return false;
154
+ }
155
+ }
156
+ /**
157
+ * Extracts metadata from document and event
158
+ * @param document - The document
159
+ * @param event - The event
160
+ * @returns Metadata object
161
+ */
162
+ extractMetadata(document, event) {
163
+ return {
164
+ recordType: event.recordType,
165
+ action: event.action,
166
+ triggerKey: event.triggerKey,
167
+ documentId: document._id?.toString(),
168
+ timestamp: new Date().toISOString()
169
+ };
170
+ }
171
+ /**
172
+ * Manually trigger a workflow for a specific document
173
+ * @param triggerKey - The trigger key to use
174
+ * @param document - The document to process
175
+ * @param recordType - The record type
176
+ */
177
+ async manualTrigger(triggerKey, document, recordType) {
178
+ const event = {
179
+ recordType,
180
+ action: 'manual',
181
+ triggerKey
182
+ };
183
+ await this.handleEvent(event, document);
184
+ }
185
+ }
186
+ /**
187
+ * Factory function to create workflow middleware for a model
188
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
189
+ * @param options - Optional workflow middleware options (overrides env vars)
190
+ * @returns Mongoose middleware functions
191
+ */
192
+ export function createWorkflowMiddleware(recordType, options) {
193
+ const middleware = new WorkflowMiddleware(options);
194
+ return middleware.createMiddleware(recordType);
195
+ }
196
+ /**
197
+ * Utility function to apply workflow middleware to a Mongoose schema
198
+ * @param schema - The Mongoose schema
199
+ * @param recordType - The type of record
200
+ * @param options - Optional workflow middleware options (overrides env vars)
201
+ */
202
+ export function applyWorkflowMiddleware(schema, recordType, options) {
203
+ const middleware = createWorkflowMiddleware(recordType, options);
204
+ // Apply post-save middleware
205
+ schema.post('save', middleware.postSave);
206
+ // Apply post-remove middleware
207
+ schema.post(/^delete/, middleware.postRemove);
208
+ schema.post('findOneAndDelete', middleware.postRemove);
209
+ }
@@ -0,0 +1,46 @@
1
+ /// <reference path="../value-objects/pound.d.ts" />
2
+ /// <reference path="../value-objects/account-number.d.ts" />
3
+ /// <reference path="../value-objects/sort-code.d.ts" />
4
+ /// <reference types="mongoose/types/aggregate" />
5
+ /// <reference types="mongoose/types/callback" />
6
+ /// <reference types="mongoose/types/collection" />
7
+ /// <reference types="mongoose/types/connection" />
8
+ /// <reference types="mongoose/types/cursor" />
9
+ /// <reference types="mongoose/types/document" />
10
+ /// <reference types="mongoose/types/error" />
11
+ /// <reference types="mongoose/types/expressions" />
12
+ /// <reference types="mongoose/types/helpers" />
13
+ /// <reference types="mongoose/types/middlewares" />
14
+ /// <reference types="mongoose/types/indexes" />
15
+ /// <reference types="mongoose/types/models" />
16
+ /// <reference types="mongoose/types/mongooseoptions" />
17
+ /// <reference types="mongoose/types/pipelinestage" />
18
+ /// <reference types="mongoose/types/populate" />
19
+ /// <reference types="mongoose/types/query" />
20
+ /// <reference types="mongoose/types/schemaoptions" />
21
+ /// <reference types="mongoose/types/session" />
22
+ /// <reference types="mongoose/types/types" />
23
+ /// <reference types="mongoose/types/utility" />
24
+ /// <reference types="mongoose/types/validation" />
25
+ /// <reference types="mongoose/types/virtuals" />
26
+ /// <reference types="mongoose/types/schematypes" />
27
+ /// <reference types="mongoose/types/inferschematype" />
28
+ /// <reference types="mongoose/types/inferrawdoctype" />
29
+ import mongoose from 'mongoose';
30
+ /**
31
+ * Workflow plugin that automatically applies workflow middleware to schemas
32
+ * This plugin reads the record type from schema options and applies the appropriate middleware
33
+ */
34
+ export declare function workflowPlugin(schema: mongoose.Schema, options: any): void;
35
+ /**
36
+ * Utility function to register the workflow plugin globally
37
+ * This will apply workflow middleware to all schemas automatically
38
+ */
39
+ export declare function registerWorkflowPlugin(): void;
40
+ /**
41
+ * Utility function to apply workflow plugin to a specific schema with custom record type
42
+ * @param schema - The Mongoose schema
43
+ * @param recordType - The record type (e.g., 'applications', 'applicants')
44
+ */
45
+ export declare function applyWorkflowPlugin(schema: mongoose.Schema, recordType: string): void;
46
+ //# sourceMappingURL=workflow.plugin.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.plugin.d.ts","sourceRoot":"","sources":["../../shared/workflow.plugin.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAGhC;;;GAGG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,QAkDnE;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,SAGrC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,UAAU,EAAE,MAAM,QAE9E"}
@@ -0,0 +1,72 @@
1
+ import mongoose from 'mongoose';
2
+ import { WorkflowMiddleware } from './workflow.middleware';
3
+ /**
4
+ * Workflow plugin that automatically applies workflow middleware to schemas
5
+ * This plugin reads the record type from schema options and applies the appropriate middleware
6
+ */
7
+ export function workflowPlugin(schema, options) {
8
+ // Get record type from schema options or infer from model name
9
+ const recordType = options.recordType || options.modelName?.toLowerCase() || 'unknown';
10
+ // Create workflow middleware instance
11
+ const middleware = new WorkflowMiddleware();
12
+ // Apply post-save middleware
13
+ schema.post('save', async function (doc, next) {
14
+ try {
15
+ await middleware.handleEvent({
16
+ recordType,
17
+ action: doc.isNew ? 'created' : 'updated',
18
+ triggerKey: `${recordType}.${doc.isNew ? 'created' : 'updated'}`
19
+ }, doc);
20
+ }
21
+ catch (error) {
22
+ console.error('Workflow middleware error:', error);
23
+ // Don't throw error to avoid breaking the main operation
24
+ }
25
+ next();
26
+ });
27
+ // Apply post-remove middleware
28
+ schema.post(/^delete/, async function (doc, next) {
29
+ try {
30
+ await middleware.handleEvent({
31
+ recordType,
32
+ action: 'deleted',
33
+ triggerKey: `${recordType}.deleted`
34
+ }, doc);
35
+ }
36
+ catch (error) {
37
+ console.error('Workflow middleware error:', error);
38
+ // Don't throw error to avoid breaking the main operation
39
+ }
40
+ next();
41
+ });
42
+ schema.post('findOneAndDelete', async function (doc, next) {
43
+ try {
44
+ await middleware.handleEvent({
45
+ recordType,
46
+ action: 'deleted',
47
+ triggerKey: `${recordType}.deleted`
48
+ }, doc);
49
+ }
50
+ catch (error) {
51
+ console.error('Workflow middleware error:', error);
52
+ // Don't throw error to avoid breaking the main operation
53
+ }
54
+ next();
55
+ });
56
+ }
57
+ /**
58
+ * Utility function to register the workflow plugin globally
59
+ * This will apply workflow middleware to all schemas automatically
60
+ */
61
+ export function registerWorkflowPlugin() {
62
+ // Register the plugin globally
63
+ mongoose.plugin(workflowPlugin);
64
+ }
65
+ /**
66
+ * Utility function to apply workflow plugin to a specific schema with custom record type
67
+ * @param schema - The Mongoose schema
68
+ * @param recordType - The record type (e.g., 'applications', 'applicants')
69
+ */
70
+ export function applyWorkflowPlugin(schema, recordType) {
71
+ schema.plugin(workflowPlugin, { recordType });
72
+ }
@@ -0,0 +1,39 @@
1
+ import { WorkflowApiPayload, WorkflowMiddlewareOptions } from './workflow-trigger.type';
2
+ export declare class WorkflowService {
3
+ private options;
4
+ constructor(options: WorkflowMiddlewareOptions);
5
+ /**
6
+ * Triggers a workflow execution in the background
7
+ * @param payload - The workflow payload to send
8
+ * @returns Promise that resolves when the request is initiated (not when it completes)
9
+ */
10
+ triggerWorkflow(payload: WorkflowApiPayload): Promise<void>;
11
+ /**
12
+ * Executes the actual workflow API call with retry logic
13
+ * @param payload - The workflow payload to send
14
+ */
15
+ private executeWorkflowCall;
16
+ /**
17
+ * Validates that required variables are present in the data
18
+ * @param requiredVariables - Array of required variable names
19
+ * @param data - The data object to validate
20
+ * @returns true if all required variables are present
21
+ */
22
+ validateRequiredVariables(requiredVariables: string[], data: Record<string, any>): boolean;
23
+ /**
24
+ * Extracts variables from document data based on required and optional variables
25
+ * @param requiredVariables - Array of required variable names
26
+ * @param optionalVariables - Array of optional variable names
27
+ * @param document - The document to extract variables from
28
+ * @returns Object containing extracted variables
29
+ */
30
+ extractVariables(requiredVariables: string[], optionalVariables: string[], document: any): Record<string, any>;
31
+ /**
32
+ * Gets a nested value from an object using dot notation
33
+ * @param obj - The object to extract from
34
+ * @param path - The dot notation path (e.g., 'user.id')
35
+ * @returns The value at the path or undefined
36
+ */
37
+ private getNestedValue;
38
+ }
39
+ //# sourceMappingURL=workflow.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow.service.d.ts","sourceRoot":"","sources":["../../shared/workflow.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AAExF,qBAAa,eAAe;IACxB,OAAO,CAAC,OAAO,CAA4B;gBAE/B,OAAO,EAAE,yBAAyB;IAS9C;;;;OAIG;IACG,eAAe,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,IAAI,CAAC;IAYjE;;;OAGG;YACW,mBAAmB;IA+CjC;;;;;OAKG;IACH,yBAAyB,CAAC,iBAAiB,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,OAAO;IAO1F;;;;;;OAMG;IACH,gBAAgB,CACZ,iBAAiB,EAAE,MAAM,EAAE,EAC3B,iBAAiB,EAAE,MAAM,EAAE,EAC3B,QAAQ,EAAE,GAAG,GACd,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC;IAmBtB;;;;;OAKG;IACH,OAAO,CAAC,cAAc;CAKzB"}
@@ -0,0 +1,114 @@
1
+ export class WorkflowService {
2
+ constructor(options) {
3
+ this.options = {
4
+ timeout: 30000,
5
+ retryAttempts: 3,
6
+ retryDelay: 1000,
7
+ ...options
8
+ };
9
+ }
10
+ /**
11
+ * Triggers a workflow execution in the background
12
+ * @param payload - The workflow payload to send
13
+ * @returns Promise that resolves when the request is initiated (not when it completes)
14
+ */
15
+ async triggerWorkflow(payload) {
16
+ // Execute in background without waiting for completion
17
+ setImmediate(async () => {
18
+ try {
19
+ await this.executeWorkflowCall(payload);
20
+ }
21
+ catch (error) {
22
+ console.error('Workflow execution failed:', error);
23
+ // Could implement retry logic or error reporting here
24
+ }
25
+ });
26
+ }
27
+ /**
28
+ * Executes the actual workflow API call with retry logic
29
+ * @param payload - The workflow payload to send
30
+ */
31
+ async executeWorkflowCall(payload) {
32
+ const headers = {
33
+ 'Content-Type': 'application/json',
34
+ };
35
+ // Get API key from environment variable
36
+ const workflowApiKey = process.env.WORKFLOW_API_KEY;
37
+ if (workflowApiKey) {
38
+ headers['Authorization'] = `Bearer ${workflowApiKey}`;
39
+ }
40
+ const requestOptions = {
41
+ method: 'POST',
42
+ headers,
43
+ body: JSON.stringify(payload),
44
+ signal: AbortSignal.timeout(this.options.timeout)
45
+ };
46
+ let lastError = null;
47
+ for (let attempt = 1; attempt <= this.options.retryAttempts; attempt++) {
48
+ try {
49
+ const response = await fetch(this.options.workflowApiUrl, requestOptions);
50
+ if (!response.ok) {
51
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
52
+ }
53
+ const result = await response.json();
54
+ console.log(`Workflow ${payload.workflowKey} triggered successfully:`, result);
55
+ return;
56
+ }
57
+ catch (error) {
58
+ lastError = error;
59
+ console.warn(`Workflow API call attempt ${attempt} failed:`, error);
60
+ if (attempt < this.options.retryAttempts) {
61
+ // Wait before retrying
62
+ await new Promise(resolve => setTimeout(resolve, this.options.retryDelay * attempt));
63
+ }
64
+ }
65
+ }
66
+ // All retry attempts failed
67
+ throw new Error(`Workflow API call failed after ${this.options.retryAttempts} attempts: ${lastError?.message}`);
68
+ }
69
+ /**
70
+ * Validates that required variables are present in the data
71
+ * @param requiredVariables - Array of required variable names
72
+ * @param data - The data object to validate
73
+ * @returns true if all required variables are present
74
+ */
75
+ validateRequiredVariables(requiredVariables, data) {
76
+ return requiredVariables.every(variable => {
77
+ const value = data[variable];
78
+ return value !== undefined && value !== null && value !== '';
79
+ });
80
+ }
81
+ /**
82
+ * Extracts variables from document data based on required and optional variables
83
+ * @param requiredVariables - Array of required variable names
84
+ * @param optionalVariables - Array of optional variable names
85
+ * @param document - The document to extract variables from
86
+ * @returns Object containing extracted variables
87
+ */
88
+ extractVariables(requiredVariables, optionalVariables, document) {
89
+ const variables = {};
90
+ // Extract required variables
91
+ requiredVariables.forEach(variable => {
92
+ variables[variable] = this.getNestedValue(document, variable);
93
+ });
94
+ // Extract optional variables
95
+ optionalVariables?.forEach(variable => {
96
+ const value = this.getNestedValue(document, variable);
97
+ if (value !== undefined && value !== null) {
98
+ variables[variable] = value;
99
+ }
100
+ });
101
+ return variables;
102
+ }
103
+ /**
104
+ * Gets a nested value from an object using dot notation
105
+ * @param obj - The object to extract from
106
+ * @param path - The dot notation path (e.g., 'user.id')
107
+ * @returns The value at the path or undefined
108
+ */
109
+ getNestedValue(obj, path) {
110
+ return path.split('.').reduce((current, key) => {
111
+ return current && current[key] !== undefined ? current[key] : undefined;
112
+ }, obj);
113
+ }
114
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynamatix/gb-schemas",
3
- "version": "1.3.334",
3
+ "version": "1.3.336",
4
4
  "description": "All the schemas for gatehouse bank back-end",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",