@dynamatix/gb-schemas 2.3.237 → 2.3.238

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 (252) hide show
  1. package/README.md +309 -0
  2. package/dist/applicants/applicant-additional-income.model.d.ts +13 -12
  3. package/dist/applicants/applicant-additional-income.model.d.ts.map +1 -1
  4. package/dist/applicants/applicant-additional-income.model.js +3 -0
  5. package/dist/applicants/applicant-commitment-creditCard.model.d.ts +19 -18
  6. package/dist/applicants/applicant-commitment-creditCard.model.d.ts.map +1 -1
  7. package/dist/applicants/applicant-commitment-creditCard.model.js +3 -0
  8. package/dist/applicants/applicant-commitment-loan.model.d.ts +19 -18
  9. package/dist/applicants/applicant-commitment-loan.model.d.ts.map +1 -1
  10. package/dist/applicants/applicant-commitment-loan.model.js +3 -0
  11. package/dist/applicants/applicant-commitment-mortgage.model.d.ts +19 -18
  12. package/dist/applicants/applicant-commitment-mortgage.model.d.ts.map +1 -1
  13. package/dist/applicants/applicant-commitment-mortgage.model.js +3 -0
  14. package/dist/applicants/applicant-commitment-residence.model.d.ts +31 -30
  15. package/dist/applicants/applicant-commitment-residence.model.d.ts.map +1 -1
  16. package/dist/applicants/applicant-commitment-residence.model.js +3 -0
  17. package/dist/applicants/applicant-commitment-secureLoan.model.d.ts +19 -18
  18. package/dist/applicants/applicant-commitment-secureLoan.model.d.ts.map +1 -1
  19. package/dist/applicants/applicant-commitment-secureLoan.model.js +3 -0
  20. package/dist/applicants/applicant-commitment-unsecuredLoan.model.d.ts +19 -18
  21. package/dist/applicants/applicant-commitment-unsecuredLoan.model.d.ts.map +1 -1
  22. package/dist/applicants/applicant-commitment-unsecuredLoan.model.js +3 -0
  23. package/dist/applicants/applicant-credit-data.model.d.ts +3 -3
  24. package/dist/applicants/applicant-credit-report.model.d.ts +3754 -0
  25. package/dist/applicants/{applicant-income.model.d.ts.map → applicant-credit-report.model.d.ts.map} +1 -1
  26. package/dist/applicants/applicant-credit-report.model.js +116 -0
  27. package/dist/applicants/applicant-credit-report.type.d.ts +140 -0
  28. package/dist/applicants/applicant-credit-report.type.d.ts.map +1 -0
  29. package/dist/applicants/applicant-credit-report.type.js +1 -0
  30. package/dist/applicants/applicant-employment-income.model.d.ts +7 -6
  31. package/dist/applicants/applicant-employment-income.model.d.ts.map +1 -1
  32. package/dist/applicants/applicant-employment-income.model.js +3 -0
  33. package/dist/applicants/applicant-employment.model.d.ts +88 -87
  34. package/dist/applicants/applicant-employment.model.d.ts.map +1 -1
  35. package/dist/applicants/applicant-employment.model.js +19 -19
  36. package/dist/applicants/applicant-expenditure.model.d.ts +7 -0
  37. package/dist/applicants/applicant-expenditure.model.d.ts.map +1 -1
  38. package/dist/applicants/applicant-expenditure.model.js +77 -0
  39. package/dist/applicants/applicant-expenditure.type.d.ts +42 -0
  40. package/dist/applicants/applicant-expenditure.type.d.ts.map +1 -0
  41. package/dist/applicants/applicant-expenditure.type.js +1 -0
  42. package/dist/applicants/applicant-income-settings.model.d.ts.map +1 -1
  43. package/dist/applicants/applicant-income-settings.model.js +3 -0
  44. package/dist/applicants/applicant-income-settings.type.d.ts +40 -0
  45. package/dist/applicants/applicant-income-settings.type.d.ts.map +1 -0
  46. package/dist/applicants/applicant-income-settings.type.js +1 -0
  47. package/dist/applicants/applicant-income-summary.model.d.ts +73 -72
  48. package/dist/applicants/applicant-income-summary.model.d.ts.map +1 -1
  49. package/dist/applicants/applicant-income-summary.model.js +3 -0
  50. package/dist/applicants/applicant-income-summary.type.d.ts +60 -0
  51. package/dist/applicants/applicant-income-summary.type.d.ts.map +1 -0
  52. package/dist/applicants/applicant-income-summary.type.js +1 -0
  53. package/dist/applicants/applicant-pension-income.model.d.ts +19 -18
  54. package/dist/applicants/applicant-pension-income.model.d.ts.map +1 -1
  55. package/dist/applicants/applicant-pension-income.model.js +3 -0
  56. package/dist/applicants/applicant-pension-income.type.d.ts +40 -0
  57. package/dist/applicants/applicant-pension-income.type.d.ts.map +1 -0
  58. package/dist/applicants/applicant-pension-income.type.js +1 -0
  59. package/dist/applicants/applicant-property-income.model.d.ts +37 -36
  60. package/dist/applicants/applicant-property-income.model.d.ts.map +1 -1
  61. package/dist/applicants/applicant-property-income.model.js +3 -0
  62. package/dist/applicants/applicant-self-employed-income.model.d.ts +7 -6
  63. package/dist/applicants/applicant-self-employed-income.model.d.ts.map +1 -1
  64. package/dist/applicants/applicant-self-employed-income.model.js +3 -0
  65. package/dist/applicants/applicant-self-employed-income.type.d.ts +37 -0
  66. package/dist/applicants/applicant-self-employed-income.type.d.ts.map +1 -0
  67. package/dist/applicants/applicant-self-employed-income.type.js +1 -0
  68. package/dist/applicants/applicant-self-employment.model.d.ts +6 -6
  69. package/dist/applicants/applicant-self-employment.model.d.ts.map +1 -1
  70. package/dist/applicants/applicant-self-employment.model.js +4 -1
  71. package/dist/applicants/applicant-sole-trader-income.model.d.ts +7 -6
  72. package/dist/applicants/applicant-sole-trader-income.model.d.ts.map +1 -1
  73. package/dist/applicants/applicant-sole-trader-income.model.js +3 -0
  74. package/dist/applicants/applicant-sole-trader-income.type.d.ts +37 -0
  75. package/dist/applicants/applicant-sole-trader-income.type.d.ts.map +1 -0
  76. package/dist/applicants/applicant-sole-trader-income.type.js +1 -0
  77. package/dist/applicants/applicant-uk-tax-credits.model.d.ts +19 -18
  78. package/dist/applicants/applicant-uk-tax-credits.model.d.ts.map +1 -1
  79. package/dist/applicants/applicant-uk-tax-credits.model.js +3 -0
  80. package/dist/applicants/applicant-uk-tax-credits.type.d.ts +39 -0
  81. package/dist/applicants/applicant-uk-tax-credits.type.d.ts.map +1 -0
  82. package/dist/applicants/applicant-uk-tax-credits.type.js +1 -0
  83. package/dist/applicants/applicant-welcome-call.model.d.ts +288 -0
  84. package/dist/applicants/applicant-welcome-call.model.d.ts.map +1 -0
  85. package/dist/applicants/applicant-welcome-call.model.js +263 -0
  86. package/dist/applicants/applicant-welcome-call.type.d.ts +66 -0
  87. package/dist/applicants/applicant-welcome-call.type.d.ts.map +1 -0
  88. package/dist/applicants/applicant-welcome-call.type.js +1 -0
  89. package/dist/applicants/applicant.model.d.ts +49 -42
  90. package/dist/applicants/applicant.model.d.ts.map +1 -1
  91. package/dist/applicants/applicant.model.js +5 -1
  92. package/dist/applicants/applicant.type.d.ts +158 -0
  93. package/dist/applicants/applicant.type.d.ts.map +1 -0
  94. package/dist/applicants/applicant.type.js +1 -0
  95. package/dist/applicants/index.d.ts +14 -0
  96. package/dist/applicants/index.d.ts.map +1 -1
  97. package/dist/applicants/index.js +2 -0
  98. package/dist/applications/application-audit.model.d.ts +6 -6
  99. package/dist/applications/application-audit.model.d.ts.map +1 -1
  100. package/dist/applications/application-audit.model.js +3 -0
  101. package/dist/applications/application-checklist-Item.model.d.ts +6 -0
  102. package/dist/applications/application-checklist-Item.model.d.ts.map +1 -1
  103. package/dist/applications/application-checklist-Item.model.js +4 -0
  104. package/dist/applications/application-company-model.d.ts +64 -57
  105. package/dist/applications/application-company-model.d.ts.map +1 -1
  106. package/dist/applications/application-company-model.js +1 -0
  107. package/dist/applications/application-direct-debit.model.d.ts +29 -27
  108. package/dist/applications/application-direct-debit.model.d.ts.map +1 -1
  109. package/dist/applications/application-direct-debit.model.js +3 -0
  110. package/dist/applications/application-euc.model.d.ts.map +1 -1
  111. package/dist/applications/application-euc.model.js +3 -0
  112. package/dist/applications/application-fieldconfig.model.d.ts.map +1 -1
  113. package/dist/applications/application-fieldconfig.model.js +3 -0
  114. package/dist/applications/application-legal.model.d.ts.map +1 -1
  115. package/dist/applications/application-legal.model.js +3 -0
  116. package/dist/applications/application-mortgage.model.d.ts +1 -0
  117. package/dist/applications/application-mortgage.model.d.ts.map +1 -1
  118. package/dist/applications/application-mortgage.model.js +3 -0
  119. package/dist/applications/application-mortgage.type.d.ts +76 -0
  120. package/dist/applications/application-mortgage.type.d.ts.map +1 -0
  121. package/dist/applications/application-mortgage.type.js +1 -0
  122. package/dist/applications/application-note.model.d.ts +36 -24
  123. package/dist/applications/application-note.model.d.ts.map +1 -1
  124. package/dist/applications/application-note.model.js +12 -3
  125. package/dist/applications/application-note.type.d.ts +55 -0
  126. package/dist/applications/application-note.type.d.ts.map +1 -0
  127. package/dist/applications/application-note.type.js +1 -0
  128. package/dist/applications/application-offer.model.d.ts.map +1 -1
  129. package/dist/applications/application-offer.model.js +3 -0
  130. package/dist/applications/application-onboarding.model.d.ts.map +1 -1
  131. package/dist/applications/application-onboarding.model.js +3 -0
  132. package/dist/applications/application-product.model.d.ts +77 -13
  133. package/dist/applications/application-product.model.d.ts.map +1 -1
  134. package/dist/applications/application-product.model.js +16 -3
  135. package/dist/applications/application-product.type.d.ts +58 -0
  136. package/dist/applications/application-product.type.d.ts.map +1 -0
  137. package/dist/applications/application-product.type.js +1 -0
  138. package/dist/applications/application-productfeatures.model.d.ts +12 -6
  139. package/dist/applications/application-productfeatures.model.d.ts.map +1 -1
  140. package/dist/applications/application-productfeatures.model.js +5 -1
  141. package/dist/applications/application-productfeatures.type.d.ts +125 -0
  142. package/dist/applications/application-productfeatures.type.d.ts.map +1 -0
  143. package/dist/applications/application-productfeatures.type.js +1 -0
  144. package/dist/applications/application-rationale.model.d.ts +6 -12
  145. package/dist/applications/application-rationale.model.d.ts.map +1 -1
  146. package/dist/applications/application-rationale.model.js +11 -20
  147. package/dist/applications/application-rationale.type.d.ts +7 -7
  148. package/dist/applications/application-rationale.type.d.ts.map +1 -1
  149. package/dist/applications/application-risk-narrative.model.d.ts.map +1 -1
  150. package/dist/applications/application-risk-narrative.model.js +3 -0
  151. package/dist/applications/application-valuation-report.model.d.ts +1246 -0
  152. package/dist/applications/application-valuation-report.model.d.ts.map +1 -0
  153. package/dist/applications/application-valuation-report.model.js +269 -0
  154. package/dist/applications/application-valuation-report.type.d.ts +108 -0
  155. package/dist/applications/application-valuation-report.type.d.ts.map +1 -0
  156. package/dist/applications/application-valuation-report.type.js +1 -0
  157. package/dist/applications/application-valuation.model.d.ts +695 -18
  158. package/dist/applications/application-valuation.model.d.ts.map +1 -1
  159. package/dist/applications/application-valuation.model.js +33 -7
  160. package/dist/applications/application-valuation.type.d.ts +54 -0
  161. package/dist/applications/application-valuation.type.d.ts.map +1 -0
  162. package/dist/applications/application-valuation.type.js +1 -0
  163. package/dist/applications/application.model.d.ts +36 -30
  164. package/dist/applications/application.model.d.ts.map +1 -1
  165. package/dist/applications/application.model.js +17 -4
  166. package/dist/applications/applications-task.model.d.ts +171 -67
  167. package/dist/applications/applications-task.model.d.ts.map +1 -1
  168. package/dist/applications/applications-task.model.js +36 -45
  169. package/dist/applications/applications-task.type.d.ts +57 -0
  170. package/dist/applications/applications-task.type.d.ts.map +1 -0
  171. package/dist/applications/applications-task.type.js +1 -0
  172. package/dist/applications/broker.model.d.ts.map +1 -1
  173. package/dist/applications/broker.model.js +3 -0
  174. package/dist/applications/index.d.ts +10 -3
  175. package/dist/applications/index.d.ts.map +1 -1
  176. package/dist/applications/index.js +2 -3
  177. package/dist/applications/solicitor.model.d.ts +2 -0
  178. package/dist/applications/solicitor.model.d.ts.map +1 -1
  179. package/dist/applications/solicitor.model.js +3 -0
  180. package/dist/index.d.ts +1 -0
  181. package/dist/index.d.ts.map +1 -1
  182. package/dist/index.js +2 -0
  183. package/dist/product-catalogues/index.d.ts +3 -0
  184. package/dist/product-catalogues/index.d.ts.map +1 -1
  185. package/dist/product-catalogues/product-catalogue.type.d.ts +15 -0
  186. package/dist/product-catalogues/product-catalogue.type.d.ts.map +1 -0
  187. package/dist/product-catalogues/product-catalogue.type.js +1 -0
  188. package/dist/product-catalogues/product-definitions.type.d.ts +53 -0
  189. package/dist/product-catalogues/product-definitions.type.d.ts.map +1 -0
  190. package/dist/product-catalogues/product-definitions.type.js +1 -0
  191. package/dist/product-catalogues/product-variant.type.d.ts +38 -0
  192. package/dist/product-catalogues/product-variant.type.d.ts.map +1 -0
  193. package/dist/product-catalogues/product-variant.type.js +1 -0
  194. package/dist/properties/property.model.d.ts +52 -51
  195. package/dist/properties/property.model.d.ts.map +1 -1
  196. package/dist/properties/property.model.js +1 -2
  197. package/dist/properties/security.model.d.ts +6 -0
  198. package/dist/properties/security.model.d.ts.map +1 -1
  199. package/dist/properties/security.model.js +1 -0
  200. package/dist/shared/alert.model.d.ts +12 -12
  201. package/dist/shared/api-log.model.d.ts +118 -0
  202. package/dist/shared/api-log.model.d.ts.map +1 -0
  203. package/dist/shared/api-log.model.js +21 -0
  204. package/dist/shared/apprivo-sync-journey.model.d.ts +6 -6
  205. package/dist/shared/checklist.model.d.ts +6 -6
  206. package/dist/shared/index.d.ts +5 -1
  207. package/dist/shared/index.d.ts.map +1 -1
  208. package/dist/shared/index.js +4 -1
  209. package/dist/shared/job-setting.model.d.ts +6 -6
  210. package/dist/shared/lookup-group.model.d.ts +25 -25
  211. package/dist/shared/lookup-group.model.d.ts.map +1 -1
  212. package/dist/shared/lookup-group.model.js +3 -0
  213. package/dist/shared/schema-doc.model.d.ts +6 -6
  214. package/dist/shared/system-parameter.model.d.ts +6 -6
  215. package/dist/shared/task-document.model.d.ts +6 -6
  216. package/dist/shared/task.model.d.ts +6 -6
  217. package/dist/shared/{document-type-model.d.ts → webhook-event.model.d.ts} +6 -45
  218. package/dist/shared/webhook-event.model.d.ts.map +1 -0
  219. package/dist/shared/webhook-event.model.js +53 -0
  220. package/dist/shared/webhook-event.type.d.ts +15 -0
  221. package/dist/shared/webhook-event.type.d.ts.map +1 -0
  222. package/dist/shared/webhook-event.type.js +1 -0
  223. package/dist/shared/workflow-trigger.model.d.ts +32 -0
  224. package/dist/shared/workflow-trigger.model.d.ts.map +1 -0
  225. package/dist/shared/workflow-trigger.model.js +45 -0
  226. package/dist/shared/workflow-trigger.type.d.ts +59 -0
  227. package/dist/shared/workflow-trigger.type.d.ts.map +1 -0
  228. package/dist/shared/workflow-trigger.type.js +1 -0
  229. package/dist/shared/workflow.init.d.ts +21 -0
  230. package/dist/shared/workflow.init.d.ts.map +1 -0
  231. package/dist/shared/workflow.init.js +41 -0
  232. package/dist/shared/workflow.middleware.d.ts +107 -0
  233. package/dist/shared/workflow.middleware.d.ts.map +1 -0
  234. package/dist/shared/workflow.middleware.js +230 -0
  235. package/dist/shared/workflow.plugin.d.ts +46 -0
  236. package/dist/shared/workflow.plugin.d.ts.map +1 -0
  237. package/dist/shared/workflow.plugin.js +102 -0
  238. package/dist/shared/workflow.service.d.ts +39 -0
  239. package/dist/shared/workflow.service.d.ts.map +1 -0
  240. package/dist/shared/workflow.service.js +115 -0
  241. package/dist/value-objects/pound.d.ts.map +1 -1
  242. package/package.json +14 -3
  243. package/dist/applicants/applicant-income.model.d.ts +0 -2558
  244. package/dist/applicants/applicant-income.model.js +0 -82
  245. package/dist/applications/application-document.model.d.ts +0 -186
  246. package/dist/applications/application-document.model.d.ts.map +0 -1
  247. package/dist/applications/application-document.model.js +0 -35
  248. package/dist/applications/document.model.d.ts +0 -186
  249. package/dist/applications/document.model.d.ts.map +0 -1
  250. package/dist/applications/document.model.js +0 -35
  251. package/dist/shared/document-type-model.d.ts.map +0 -1
  252. package/dist/shared/document-type-model.js +0 -10
@@ -0,0 +1,230 @@
1
+ import WorkflowTriggerModel from './workflow-trigger.model.js';
2
+ import { WorkflowService } from './workflow.service.js';
3
+ // @ts-ignore - No type declarations available for @dynamatix/cat-shared/services
4
+ import { getContext as getSharedContext } from '@dynamatix/cat-shared/services';
5
+ export class WorkflowMiddleware {
6
+ constructor(options) {
7
+ // Read configuration from environment variables with fallbacks
8
+ this.options = {
9
+ workflowApiUrl: process.env.WORKFLOW_API_URL || 'https://your-workflow-api.com/api/v1/workflows/execute',
10
+ timeout: parseInt(process.env.WORKFLOW_TIMEOUT || '30000'),
11
+ retryAttempts: parseInt(process.env.WORKFLOW_RETRY_ATTEMPTS || '3'),
12
+ retryDelay: parseInt(process.env.WORKFLOW_RETRY_DELAY || '1000'),
13
+ ...options // Allow override of specific options
14
+ };
15
+ this.workflowService = new WorkflowService(this.options);
16
+ }
17
+ /**
18
+ * Safely gets the WorkflowTrigger model, handling potential registration issues
19
+ */
20
+ getWorkflowTriggerModel() {
21
+ try {
22
+ return WorkflowTriggerModel;
23
+ }
24
+ catch (error) {
25
+ console.error('Error accessing WorkflowTrigger model:', error);
26
+ throw new Error('WorkflowTrigger model is not properly registered');
27
+ }
28
+ }
29
+ /**
30
+ * Gets the current request context including application_id
31
+ * @returns The current context object or null if not available
32
+ */
33
+ getContext() {
34
+ const context = getSharedContext();
35
+ if (context) {
36
+ return { contextId: context.contextId };
37
+ }
38
+ return null;
39
+ }
40
+ /**
41
+ * Creates a Mongoose middleware function for a specific model
42
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
43
+ * @returns Mongoose middleware function
44
+ */
45
+ createMiddleware(recordType) {
46
+ return {
47
+ // Post-save middleware for create and update operations
48
+ postSave: async function (doc, next) {
49
+ try {
50
+ console.log('Post-save middleware for create and update operations');
51
+ const middleware = new WorkflowMiddleware(this.options || {});
52
+ await middleware.handleEvent({
53
+ recordType,
54
+ action: doc.isNew ? 'created' : 'updated',
55
+ triggerKey: `${recordType}.${doc.isNew ? 'created' : 'updated'}`
56
+ }, doc);
57
+ }
58
+ catch (error) {
59
+ console.error('Workflow middleware error:', error);
60
+ // Don't throw error to avoid breaking the main operation
61
+ }
62
+ next();
63
+ }.bind(this),
64
+ // Post-remove middleware for delete operations
65
+ postRemove: async function (doc, next) {
66
+ try {
67
+ console.log('Post-remove middleware for delete operations');
68
+ const middleware = new WorkflowMiddleware(this.options || {});
69
+ await middleware.handleEvent({
70
+ recordType,
71
+ action: 'deleted',
72
+ triggerKey: `${recordType}.deleted`
73
+ }, doc);
74
+ }
75
+ catch (error) {
76
+ console.error('Workflow middleware error:', error);
77
+ // Don't throw error to avoid breaking the main operation
78
+ }
79
+ next();
80
+ }.bind(this)
81
+ };
82
+ }
83
+ /**
84
+ * Handles a workflow trigger event
85
+ * @param event - The workflow trigger event
86
+ * @param document - The document that triggered the event
87
+ */
88
+ async handleEvent(event, document) {
89
+ try {
90
+ // Find active triggers for this event
91
+ console.log('Finding active triggers for this event');
92
+ const WorkflowTrigger = this.getWorkflowTriggerModel();
93
+ const triggers = await WorkflowTrigger.find({
94
+ triggerKey: event.triggerKey,
95
+ isActive: true
96
+ });
97
+ if (triggers.length === 0) {
98
+ console.log(`No active triggers found for ${event.triggerKey}`);
99
+ return;
100
+ }
101
+ // Process each trigger
102
+ console.log('Processing each trigger');
103
+ for (const trigger of triggers) {
104
+ await this.processTrigger(trigger, document, event);
105
+ }
106
+ }
107
+ catch (error) {
108
+ console.error(`Error handling workflow event ${event.triggerKey}:`, error);
109
+ }
110
+ }
111
+ /**
112
+ * Processes a single workflow trigger
113
+ * @param trigger - The workflow trigger configuration
114
+ * @param document - The document that triggered the event
115
+ * @param event - The workflow trigger event
116
+ */
117
+ async processTrigger(trigger, document, event) {
118
+ try {
119
+ console.log('Processing trigger');
120
+ // Check if condition is met (if specified)
121
+ if (trigger.condition && !this.evaluateCondition(trigger.condition, document)) {
122
+ console.log(`Condition not met for trigger ${trigger.triggerKey}`);
123
+ return;
124
+ }
125
+ // Extract variables from document
126
+ console.log('Extracting variables from document');
127
+ const variables = this.workflowService.extractVariables(trigger.requiredVariables, trigger.optionalVariables || [], document);
128
+ // Validate required variables
129
+ if (!this.workflowService.validateRequiredVariables(trigger.requiredVariables, variables)) {
130
+ console.warn(`Required variables missing for trigger ${trigger.triggerKey}`);
131
+ return;
132
+ }
133
+ // Add metadata
134
+ const enrichedVariables = {
135
+ ...variables,
136
+ ...this.extractMetadata(document, event)
137
+ };
138
+ // Create workflow payload
139
+ const payload = {
140
+ workflowKey: trigger.workflowKey,
141
+ version: 1, // Default version, could be made configurable
142
+ variables: enrichedVariables
143
+ };
144
+ // Trigger workflow in background
145
+ await this.workflowService.triggerWorkflow(payload);
146
+ console.log(`Workflow ${trigger.workflowKey} triggered for ${event.triggerKey}`);
147
+ }
148
+ catch (error) {
149
+ console.error(`Error processing trigger ${trigger.triggerKey}:`, error);
150
+ }
151
+ }
152
+ /**
153
+ * Evaluates a condition against a document
154
+ * @param condition - The condition string to evaluate
155
+ * @param document - The document to evaluate against
156
+ * @returns true if condition is met
157
+ */
158
+ evaluateCondition(condition, document) {
159
+ try {
160
+ // Simple condition evaluation - could be enhanced with a proper expression parser
161
+ // For now, supporting basic field checks like "status === 'active'"
162
+ if (condition.includes('===')) {
163
+ const [field, value] = condition.split('===').map(s => s.trim());
164
+ const fieldValue = this.workflowService['getNestedValue'](document, field);
165
+ return fieldValue === value.replace(/['"]/g, '');
166
+ }
167
+ // Default to true if condition format is not recognized
168
+ return true;
169
+ }
170
+ catch (error) {
171
+ console.error('Error evaluating condition:', error);
172
+ return false;
173
+ }
174
+ }
175
+ /**
176
+ * Extracts metadata from document and event
177
+ * @param document - The document
178
+ * @param event - The event
179
+ * @returns Metadata object
180
+ */
181
+ extractMetadata(document, event) {
182
+ const context = this.getContext();
183
+ return {
184
+ source: event.recordType,
185
+ action: event.action,
186
+ triggerKey: event.triggerKey,
187
+ sourceId: document._id?.toString(),
188
+ timestamp: new Date().toISOString(),
189
+ contextId: context?.contextId,
190
+ };
191
+ }
192
+ /**
193
+ * Manually trigger a workflow for a specific document
194
+ * @param triggerKey - The trigger key to use
195
+ * @param document - The document to process
196
+ * @param recordType - The record type
197
+ */
198
+ async manualTrigger(triggerKey, document, recordType) {
199
+ const event = {
200
+ recordType,
201
+ action: 'manual',
202
+ triggerKey
203
+ };
204
+ await this.handleEvent(event, document);
205
+ }
206
+ }
207
+ /**
208
+ * Factory function to create workflow middleware for a model
209
+ * @param recordType - The type of record (e.g., 'applications', 'products', 'tasks')
210
+ * @param options - Optional workflow middleware options (overrides env vars)
211
+ * @returns Mongoose middleware functions
212
+ */
213
+ export function createWorkflowMiddleware(recordType, options) {
214
+ const middleware = new WorkflowMiddleware(options);
215
+ return middleware.createMiddleware(recordType);
216
+ }
217
+ /**
218
+ * Utility function to apply workflow middleware to a Mongoose schema
219
+ * @param schema - The Mongoose schema
220
+ * @param recordType - The type of record
221
+ * @param options - Optional workflow middleware options (overrides env vars)
222
+ */
223
+ export function applyWorkflowMiddleware(schema, recordType, options) {
224
+ const middleware = createWorkflowMiddleware(recordType, options);
225
+ // Apply post-save middleware
226
+ schema.post('save', middleware.postSave);
227
+ // Apply post-remove middleware
228
+ schema.post(/^delete/, middleware.postRemove);
229
+ schema.post('findOneAndDelete', middleware.postRemove);
230
+ }
@@ -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.js" />
5
+ /// <reference types="mongoose/types/callback.js" />
6
+ /// <reference types="mongoose/types/collection.js" />
7
+ /// <reference types="mongoose/types/connection.js" />
8
+ /// <reference types="mongoose/types/cursor.js" />
9
+ /// <reference types="mongoose/types/document.js" />
10
+ /// <reference types="mongoose/types/error.js" />
11
+ /// <reference types="mongoose/types/expressions.js" />
12
+ /// <reference types="mongoose/types/helpers.js" />
13
+ /// <reference types="mongoose/types/middlewares.js" />
14
+ /// <reference types="mongoose/types/indexes.js" />
15
+ /// <reference types="mongoose/types/models.js" />
16
+ /// <reference types="mongoose/types/mongooseoptions.js" />
17
+ /// <reference types="mongoose/types/pipelinestage.js" />
18
+ /// <reference types="mongoose/types/populate.js" />
19
+ /// <reference types="mongoose/types/query.js" />
20
+ /// <reference types="mongoose/types/schemaoptions.js" />
21
+ /// <reference types="mongoose/types/session.js" />
22
+ /// <reference types="mongoose/types/types.js" />
23
+ /// <reference types="mongoose/types/utility.js" />
24
+ /// <reference types="mongoose/types/validation.js" />
25
+ /// <reference types="mongoose/types/virtuals.js" />
26
+ /// <reference types="mongoose/types/schematypes.js" />
27
+ /// <reference types="mongoose/types/inferschematype.js" />
28
+ /// <reference types="mongoose/types/inferrawdoctype.js" />
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,QAqFnE;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,102 @@
1
+ import mongoose from 'mongoose';
2
+ import { WorkflowMiddleware } from './workflow.middleware.js';
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
+ // For global plugins, we'll determine the record type when the middleware is triggered
9
+ // by looking at the document's constructor name
10
+ console.log(`🔌 Workflow plugin applied to schema`);
11
+ // Create workflow middleware instance
12
+ const middleware = new WorkflowMiddleware();
13
+ // Apply post-save middleware
14
+ schema.post('save', async function (doc, next) {
15
+ // Determine record type from document constructor name
16
+ const recordType = doc.constructor.modelName?.toLowerCase() || 'unknown';
17
+ console.log(`💾 Post-save middleware triggered for ${recordType}`);
18
+ console.log(` Document ID: ${doc._id}`);
19
+ console.log(` Is new: ${doc.isNew}`);
20
+ console.log(` Trigger key: ${recordType}.${doc.isNew ? 'created' : 'updated'}`);
21
+ try {
22
+ await middleware.handleEvent({
23
+ recordType,
24
+ action: doc.isNew ? 'created' : 'updated',
25
+ triggerKey: `${recordType}.${doc.isNew ? 'created' : 'updated'}`
26
+ }, doc);
27
+ }
28
+ catch (error) {
29
+ console.error('Workflow middleware error:', error);
30
+ // Don't throw error to avoid breaking the main operation
31
+ }
32
+ next();
33
+ });
34
+ // Apply post-findOneAndUpdate middleware
35
+ schema.post('findOneAndUpdate', async function (doc, next) {
36
+ const recordType = doc.constructor.modelName?.toLowerCase() || 'unknown';
37
+ console.log(`🔄 Post-findOneAndUpdate middleware triggered for ${recordType}`);
38
+ console.log(` Document ID: ${doc._id}`);
39
+ console.log(` Trigger key: ${recordType}.updated`);
40
+ try {
41
+ await middleware.handleEvent({
42
+ recordType,
43
+ action: 'updated',
44
+ triggerKey: `${recordType}.updated`
45
+ }, doc);
46
+ }
47
+ catch (error) {
48
+ console.error('Workflow middleware error:', error);
49
+ // Don't throw error to avoid breaking the main operation
50
+ }
51
+ next();
52
+ });
53
+ // Apply post-remove middleware
54
+ schema.post(/^delete/, async function (doc, next) {
55
+ const recordType = doc.constructor.modelName?.toLowerCase() || 'unknown';
56
+ console.log(`🗑️ Post-delete middleware triggered for ${recordType}`);
57
+ try {
58
+ await middleware.handleEvent({
59
+ recordType,
60
+ action: 'deleted',
61
+ triggerKey: `${recordType}.deleted`
62
+ }, doc);
63
+ }
64
+ catch (error) {
65
+ console.error('Workflow middleware error:', error);
66
+ // Don't throw error to avoid breaking the main operation
67
+ }
68
+ next();
69
+ });
70
+ schema.post('findOneAndDelete', async function (doc, next) {
71
+ const recordType = doc.constructor.modelName?.toLowerCase() || 'unknown';
72
+ console.log(`🗑️ Post-findOneAndDelete middleware triggered for ${recordType}`);
73
+ try {
74
+ await middleware.handleEvent({
75
+ recordType,
76
+ action: 'deleted',
77
+ triggerKey: `${recordType}.deleted`
78
+ }, doc);
79
+ }
80
+ catch (error) {
81
+ console.error('Workflow middleware error:', error);
82
+ // Don't throw error to avoid breaking the main operation
83
+ }
84
+ next();
85
+ });
86
+ }
87
+ /**
88
+ * Utility function to register the workflow plugin globally
89
+ * This will apply workflow middleware to all schemas automatically
90
+ */
91
+ export function registerWorkflowPlugin() {
92
+ // Register the plugin globally
93
+ mongoose.plugin(workflowPlugin);
94
+ }
95
+ /**
96
+ * Utility function to apply workflow plugin to a specific schema with custom record type
97
+ * @param schema - The Mongoose schema
98
+ * @param recordType - The record type (e.g., 'applications', 'applicants')
99
+ */
100
+ export function applyWorkflowPlugin(schema, recordType) {
101
+ schema.plugin(workflowPlugin, { recordType });
102
+ }
@@ -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;IAgDjC;;;;;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,115 @@
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
+ 'X-Solution-Key': process.env.SOLUTION_KEY || 'default'
35
+ };
36
+ // Get API key from environment variable
37
+ const workflowApiKey = process.env.WORKFLOW_API_KEY;
38
+ if (workflowApiKey) {
39
+ headers['Authorization'] = `Bearer ${workflowApiKey}`;
40
+ }
41
+ const requestOptions = {
42
+ method: 'POST',
43
+ headers,
44
+ body: JSON.stringify(payload),
45
+ signal: AbortSignal.timeout(this.options.timeout)
46
+ };
47
+ let lastError = null;
48
+ for (let attempt = 1; attempt <= this.options.retryAttempts; attempt++) {
49
+ try {
50
+ const response = await fetch(this.options.workflowApiUrl, requestOptions);
51
+ if (!response.ok) {
52
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
53
+ }
54
+ const result = await response.json();
55
+ console.log(`Workflow ${payload.workflowKey} triggered successfully:`, result);
56
+ return;
57
+ }
58
+ catch (error) {
59
+ lastError = error;
60
+ console.warn(`Workflow API call attempt ${attempt} failed:`, error);
61
+ if (attempt < this.options.retryAttempts) {
62
+ // Wait before retrying
63
+ await new Promise(resolve => setTimeout(resolve, this.options.retryDelay * attempt));
64
+ }
65
+ }
66
+ }
67
+ // All retry attempts failed
68
+ throw new Error(`Workflow API call failed after ${this.options.retryAttempts} attempts: ${lastError?.message}`);
69
+ }
70
+ /**
71
+ * Validates that required variables are present in the data
72
+ * @param requiredVariables - Array of required variable names
73
+ * @param data - The data object to validate
74
+ * @returns true if all required variables are present
75
+ */
76
+ validateRequiredVariables(requiredVariables, data) {
77
+ return requiredVariables.every(variable => {
78
+ const value = data[variable];
79
+ return value !== undefined && value !== null && value !== '';
80
+ });
81
+ }
82
+ /**
83
+ * Extracts variables from document data based on required and optional variables
84
+ * @param requiredVariables - Array of required variable names
85
+ * @param optionalVariables - Array of optional variable names
86
+ * @param document - The document to extract variables from
87
+ * @returns Object containing extracted variables
88
+ */
89
+ extractVariables(requiredVariables, optionalVariables, document) {
90
+ const variables = {};
91
+ // Extract required variables
92
+ requiredVariables.forEach(variable => {
93
+ variables[variable] = this.getNestedValue(document, variable);
94
+ });
95
+ // Extract optional variables
96
+ optionalVariables?.forEach(variable => {
97
+ const value = this.getNestedValue(document, variable);
98
+ if (value !== undefined && value !== null) {
99
+ variables[variable] = value;
100
+ }
101
+ });
102
+ return variables;
103
+ }
104
+ /**
105
+ * Gets a nested value from an object using dot notation
106
+ * @param obj - The object to extract from
107
+ * @param path - The dot notation path (e.g., 'user.id')
108
+ * @returns The value at the path or undefined
109
+ */
110
+ getNestedValue(obj, path) {
111
+ return path.split('.').reduce((current, key) => {
112
+ return current && current[key] !== undefined ? current[key] : undefined;
113
+ }, obj);
114
+ }
115
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"pound.d.ts","sourceRoot":"","sources":["../../value-objects/pound.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAGhC,OAAO,QAAQ,UAAU,CAAC;IACtB,UAAU,MAAM,CAAC;QACb,UAAU,KAAK,CAAC;YACZ,MAAM,KAAM,SAAQ,UAAU;aAAI;SACrC;KACJ;CACJ;AAED,cAAM,KAAM,SAAQ,QAAQ,CAAC,UAAU;gBACvB,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,SAAS,GAAG,SAAS;IAKhE,IAAI,CAAC,GAAG,EAAE,GAAG;CAgDhB;AAMD,wBAAgB,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,IAAI,CAMnD;AAED,OAAO,EAAE,KAAK,EAAE,CAAC"}
1
+ {"version":3,"file":"pound.d.ts","sourceRoot":"","sources":["../../value-objects/pound.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,OAAO,QAAQ,MAAM,UAAU,CAAC;AAGhC,OAAO,QAAQ,UAAU,CAAC;IACtB,UAAU,MAAM,CAAC;QACb,UAAU,KAAK,CAAC;YACZ,MAAM,KAAM,SAAQ,UAAU;aAAI;SACrC;KACJ;CACJ;AAED,cAAM,KAAM,SAAQ,QAAQ,CAAC,UAAU;gBACvB,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,CAAC,SAAS,GAAG,SAAS;IAKhE,IAAI,CAAC,GAAG,EAAE,GAAG;CAkDhB;AAMD,wBAAgB,WAAW,CAAC,GAAG,EAAE,GAAG,GAAG,MAAM,GAAG,IAAI,CAMnD;AAED,OAAO,EAAE,KAAK,EAAE,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dynamatix/gb-schemas",
3
- "version": "2.3.237",
3
+ "version": "2.3.238",
4
4
  "description": "All the schemas for gatehouse bank back-end",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,11 +8,21 @@
8
8
  "scripts": {
9
9
  "build": "tsc",
10
10
  "test": "echo \"Error: no test specified\" && exit 1",
11
+ "test:workflow": "npm run build && node test-workflow.js",
12
+ "test:workflow:env": "npm run build && WORKFLOW_API_KEY=test-key WORKFLOW_API_URL=http://localhost:3000/api/workflows node test-workflow-with-env.js",
13
+ "example:app": "npm run build && node example-app-usage.js",
14
+ "test:workflow:triggers": "npm run build && node test-workflow-with-triggers.js",
15
+ "test:workflow:direct": "npm run build && node test-direct-middleware.js",
16
+ "patch": "tsc && npm version patch && npm publish --access public && exit 0",
11
17
  "generate-docs": "NODE_OPTIONS='--loader ts-node/esm' ts-node schema-docs/docs.seeder.ts",
12
18
  "example:income": "NODE_OPTIONS='--loader ts-node/esm' ts-node examples/add-applicant-income.ts",
13
19
  "migrate:applicant-income": "node migrate-applicant-income.js",
14
20
  "migrate:self-employed-id": "node migrate-self-employed-id.js",
15
- "check:applicants-employment": "node check-applicants-without-employment.js"
21
+ "check:applicants-employment": "node check-applicants-without-employment.js",
22
+ "delete:applications-by-type": "node delete-applications-by-type.js",
23
+ "find:applications-many-audits": "node find-applications-with-many-audits.js",
24
+ "update:apiconfigs-paths": "node scripts/update-apiconfigs-paths.js",
25
+ "seed:property-metadata": "node scripts/seed-property-metadata.js"
16
26
  },
17
27
  "repository": {
18
28
  "type": "git",
@@ -25,7 +35,8 @@
25
35
  },
26
36
  "homepage": "https://github.com/DynamatixAnalyticsPvtLtd/gb-schemas#readme",
27
37
  "dependencies": {
28
- "@dynamatix/cat-shared": "^0.0.100",
38
+ "@dynamatix/cat-shared": "^0.0.124",
39
+ "@dynamatix/gb-schemas": "^1.3.256",
29
40
  "dotenv": "^16.4.5",
30
41
  "mongodb": "^6.14.2",
31
42
  "mongoose": "^8.9.5"