@dynamatix/cat-shared 0.0.125 → 0.0.127

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.
@@ -1,356 +1,356 @@
1
- import AuditConfigModel from '../models/audit-config.model.js';
2
- import AuditLog from '../models/audit.model.js';
3
- import ValueReferenceMap from '../models/value-reference-map.model.js';
4
- import { getContext } from '../services/request-context.service.js';
5
- import mongoose from 'mongoose';
6
- import FormConfigurationModel from '../models/form-configuration.model.js';
7
-
8
- let onAuditLogCreated = null;
9
-
10
- // Optionally, define custom resolvers here
11
- const customResolvers = {
12
- // Example:
13
- // expenditureRationale: (doc) => `Rationale for ${doc.type}: ${doc.rationale}`
14
- };
15
-
16
- // Expression-based description resolver: resolves ${fieldName} in the expression using doc, and via Lookup if needed
17
- async function resolveExpressionDescription(doc, expression, resolverType) {
18
- console.log("expression-", expression);
19
- console.log("resolverType-", resolverType);
20
- const matches = [...expression.matchAll(/\$\{([^}]+)\}/g)];
21
- let result = expression;
22
- for (const match of matches) {
23
- const fieldName = match[1];
24
- let value = doc[fieldName];
25
- if (resolverType === 'lookup' && value && mongoose.models['Lookup']) {
26
- const lookupDoc = await mongoose.models['Lookup'].findById(value).lean();
27
- value = lookupDoc?.name || value;
28
- }
29
- result = result.replace(match[0], value ?? '');
30
- }
31
- return result;
32
- }
33
-
34
- // Update resolveDescription to support expression-based descriptionField
35
- async function resolveDescription(field, doc) {
36
- const modelName = doc.constructor.modelName;
37
- const config = await ValueReferenceMap.findOne({ field, model: modelName });
38
- console.log("config-", config);
39
- if (!config) return field;
40
-
41
- if (config.descriptionField && config.descriptionField.includes('${')) {
42
- console.log("config.descriptionField", config.descriptionField);
43
- return await resolveExpressionDescription(doc, config.descriptionField, config.descriptionResolverType);
44
- }
45
- console.log("config.descriptionResolverType", config.descriptionResolverType);
46
- switch (config.descriptionResolverType) {
47
- case 'lookup': {
48
- const lookupId = doc[config.descriptionField];
49
- if (!lookupId) return '';
50
- const lookupDoc = await mongoose.models['Lookup'].findById(lookupId).lean();
51
- return lookupDoc?.name || '';
52
- }
53
- case 'direct':
54
- return doc[config.descriptionField] || '';
55
- case 'displayFieldReturn': // For case we just want to show display field value directly
56
- return config.displayField || '';
57
- case 'composite':
58
- return (config.descriptionFields || [])
59
- .map(f => doc[f])
60
- .filter(Boolean)
61
- .join(' ');
62
- case 'custom':
63
- if (typeof customResolvers?.[config.descriptionFunction] === 'function') {
64
- return await customResolvers[config.descriptionFunction](doc);
65
- }
66
- return '';
67
- default:
68
- return '';
69
- }
70
- }
71
-
72
- // Update resolveEntityDescription to support expression-based descriptionField
73
- async function resolveEntityDescription(doc, auditConfig) {
74
- if (!auditConfig.descriptionResolutorForExternalData) return '';
75
- const field = auditConfig.descriptionResolutorForExternalData;
76
- const value = doc[field];
77
- // Try to resolve via ValueReferenceMap
78
- console.log("field-", field);
79
- const map = await ValueReferenceMap.findOne({ field });
80
- console.log("map-", map);
81
- if (map?.descriptionResolverType === 'displayFieldReturn') {
82
- return map.descriptionField;
83
- }
84
- if (map && map.descriptionField && map.descriptionField.includes('${')) {
85
- return await resolveExpressionDescription(doc, map.descriptionField, map.descriptionResolverType);
86
- }
87
- if (map && value) {
88
- const Model = mongoose.models[map.model];
89
- if (Model) {
90
- const refDoc = await Model.findById(value).lean();
91
- return refDoc?.[map.displayField] || value;
92
- }
93
- }
94
- // Fallback: If it's an ObjectId and Lookup model exists, resolve to name
95
- if (mongoose.Types.ObjectId.isValid(value) && mongoose.models['Lookup']) {
96
- const lookupDoc = await mongoose.models['Lookup'].findById(value).lean();
97
- return lookupDoc?.name || value;
98
- }
99
- return value;
100
- }
101
-
102
- // Add new function to resolve deletion description
103
- async function resolveDeletionDescription(doc, auditConfig) {
104
- if (!auditConfig.descriptionResolutorForDeletion) return '';
105
- const expression = auditConfig.descriptionResolutorForDeletion;
106
- return await resolveExpressionDescription(doc, expression, 'direct');
107
- }
108
-
109
- // Utility to build a fieldName -> dataType map from multiple formConfig.sections
110
- function buildFieldTypeMapFromConfigs(formConfigs) {
111
- const map = {};
112
- function extractFields(sections) {
113
- for (const section of sections || []) {
114
- if (section.fields) {
115
- for (const f of section.fields) map[f.fieldName] = f.dataType;
116
- }
117
- if (section.sections) extractFields(section.sections);
118
- }
119
- }
120
- for (const config of formConfigs) {
121
- extractFields(config.sections);
122
- }
123
- return map;
124
- }
125
-
126
- function applyAuditMiddleware(schema, collectionName) {
127
- // Handle creation audit
128
- schema.post('save', async function (doc) {
129
- const auditConfig = await AuditConfigModel.findOne({ collectionName });
130
- if (!auditConfig?.trackCreation) return;
131
-
132
- // Fetch all form configs and build fieldTypeMap once
133
- const formConfigs = await FormConfigurationModel.find({ collectionName });
134
- const fieldTypeMap = buildFieldTypeMapFromConfigs(formConfigs);
135
-
136
- const context = getContext();
137
- const userId = context?.userId || null;
138
- const contextId = context?.contextId;
139
-
140
- const entityDescription = await resolveEntityDescription(doc, auditConfig);
141
- let logs = [];
142
-
143
- // Per-field logs
144
- if (auditConfig.fields?.length) {
145
- for (const field of auditConfig.fields) {
146
- let lookupName;
147
- const newValue = doc[field];
148
- if (field.endsWith('Lid')) {
149
- const newlookupDoc = await mongoose.models['Lookup'].findById(newValue).lean();
150
- if (newlookupDoc) {
151
- lookupName = newlookupDoc.name;
152
- } else {
153
- lookupName = '';
154
- }
155
- }
156
- const fieldDescription = await resolveDescription(field, doc);
157
- // --- Add pound prefix if needed ---
158
- let displayNewValue = lookupName || newValue;
159
- const dataType = fieldTypeMap[field];
160
- if (dataType === 'pound' && displayNewValue != null && displayNewValue !== '') {
161
- displayNewValue = `£${displayNewValue}`;
162
- }
163
- logs.push({
164
- name: fieldDescription,
165
- entity: entityDescription,
166
- recordId: contextId || doc._id,
167
- oldValue: null,
168
- newValue: displayNewValue,
169
- createdBy: userId,
170
- externalData: {
171
- description: entityDescription,
172
- contextId
173
- }
174
- });
175
- }
176
- }
177
- logs = logs.filter(log => {
178
- // Convert null/undefined to empty string for comparison
179
- const oldVal = log.oldValue ?? '';
180
- const newVal = log.newValue ?? '';
181
- return oldVal !== newVal;
182
- });
183
- if (logs.length) {
184
- await AuditLog.insertMany(logs);
185
- await updateContextAuditCount(contextId, logs.length);
186
- if (onAuditLogCreated) {
187
- await onAuditLogCreated(logs, contextId);
188
- }
189
- }
190
- });
191
-
192
- // Capture the original doc before update
193
- schema.pre(['findOneAndUpdate', 'findByIdAndUpdate'], async function (next) {
194
- this._originalDoc = await this.model.findOne(this.getQuery()).lean();
195
- next();
196
- });
197
-
198
- // Handle update audits
199
- schema.post(['findOneAndUpdate', 'findByIdAndUpdate'], async function (result) {
200
- if (!result) return;
201
-
202
- const auditConfig = await AuditConfigModel.findOne({ collectionName });
203
- if (!auditConfig?.fields?.length) return;
204
-
205
- // Fetch all form configs and build fieldTypeMap once
206
- const formConfigs = await FormConfigurationModel.find({ collectionName });
207
- const fieldTypeMap = buildFieldTypeMapFromConfigs(formConfigs);
208
-
209
- const update = this.getUpdate();
210
- let logs = [];
211
- const context = getContext();
212
- const userId = context?.userId || null;
213
- const contextId = context?.contextId;
214
-
215
- const entityDescription = await resolveEntityDescription(result, auditConfig);
216
-
217
- for (const field of auditConfig.fields) {
218
- console.log("field", field);
219
- const hasChanged =
220
- update?.$set?.hasOwnProperty(field) || update?.hasOwnProperty(field);
221
- console.log("hasChanged", hasChanged);
222
- if (hasChanged) {
223
- const newValue = update?.$set?.[field] ?? update?.[field];
224
- const oldValue = this._originalDoc ? this._originalDoc[field] : '';
225
- let lookupOldName;
226
- let lookupNewName;
227
- if (field.endsWith('Lid')) {
228
- const newlookupDoc = await mongoose.models['Lookup'].findById(newValue).lean();
229
- if (newlookupDoc) {
230
- lookupNewName = newlookupDoc.name;
231
- } else {
232
- lookupNewName = '';
233
- }
234
- const oldlookupDoc = await mongoose.models['Lookup'].findById(oldValue).lean();
235
- if (oldlookupDoc) {
236
- lookupOldName = oldlookupDoc.name;
237
- } else {
238
- lookupOldName = '';
239
- }
240
- }
241
- // Convert null/undefined to empty string for comparison
242
- let displayOldValue = lookupOldName ?? oldValue ?? '';
243
- let displayNewValue = lookupNewName ?? newValue ?? '';
244
- console.log("displayOldValue", displayOldValue);
245
- console.log("displayNewValue", displayNewValue);
246
- // --- Add pound prefix if needed ---
247
- const dataType = fieldTypeMap[field];
248
- if (dataType === 'pound') {
249
- if (displayOldValue != null && displayOldValue !== '') displayOldValue = `£${displayOldValue}`;
250
- if (displayNewValue != null && displayNewValue !== '') displayNewValue = `£${displayNewValue}`;
251
- }
252
- if (displayOldValue !== displayNewValue) {
253
- const fieldDescription = await resolveDescription(field, result);
254
- console.log("fieldDescription-", fieldDescription);
255
- logs.push({
256
- name: fieldDescription,
257
- entity: entityDescription,
258
- recordId: contextId || result._id,
259
- oldValue: displayOldValue,
260
- newValue: displayNewValue,
261
- createdBy: userId,
262
- externalData: {
263
- description: entityDescription,
264
- contextId: contextId || result._id
265
- }
266
- });
267
- }
268
- }
269
- }
270
- console.log("logs", logs);
271
- logs = logs.filter(log => {
272
- // Convert null/undefined to empty string for comparison
273
- const oldVal = log.oldValue ?? '';
274
- const newVal = log.newValue ?? '';
275
- return oldVal !== newVal;
276
- });
277
- console.log("logs.length", logs.length);
278
- if (logs.length) {
279
- console.log("logs.length", logs.length);
280
- await AuditLog.insertMany(logs);
281
- await updateContextAuditCount(contextId, logs.length);
282
- if (onAuditLogCreated) {
283
- await onAuditLogCreated(logs, contextId);
284
- }
285
- }
286
- });
287
-
288
- // Handle delete audits
289
- schema.pre(['findOneAndDelete', 'findByIdAndDelete', 'deleteOne', 'deleteMany'], async function (next) {
290
- try {
291
- // Fetch the document before deletion
292
- const docToDelete = await this.model.findOne(this.getQuery()).lean();
293
- if (docToDelete) {
294
- // Store the document for use in post middleware
295
- this._docToDelete = docToDelete;
296
- }
297
- next();
298
- } catch (error) {
299
- next(error);
300
- }
301
- });
302
-
303
- schema.post(['findOneAndDelete', 'findByIdAndDelete', 'deleteOne', 'deleteMany'], async function (result) {
304
- if (!result) return;
305
-
306
- const auditConfig = await AuditConfigModel.findOne({ collectionName });
307
- if (!auditConfig?.trackDeletion) return;
308
-
309
- const context = getContext();
310
- const userId = context?.userId || null;
311
- const contextId = context?.contextId;
312
-
313
- const entityDescription = await resolveEntityDescription(this._docToDelete, auditConfig);
314
- const deletionDescription = await resolveDeletionDescription(this._docToDelete, auditConfig);
315
-
316
- const log = {
317
- name: deletionDescription || 'Entity Deletion',
318
- entity: entityDescription,
319
- recordId: contextId || this._docToDelete._id,
320
- oldValue: '',
321
- newValue: 'Deleted',
322
- createdBy: userId,
323
- externalData: {
324
- description: entityDescription,
325
- contextId: contextId || this._docToDelete._id
326
- }
327
- };
328
- const oldVal = log.oldValue ?? '';
329
- const newVal = log.newValue ?? '';
330
- if (oldVal === newVal) {
331
- return;
332
- }
333
- await AuditLog.create(log);
334
- await updateContextAuditCount(contextId, 1);
335
- if (onAuditLogCreated) {
336
- await onAuditLogCreated([log], contextId);
337
- }
338
- });
339
- }
340
-
341
- async function updateContextAuditCount(contextId, count) {
342
- count = Number(count);
343
- if (!contextId || isNaN(count)) return;
344
- const model = mongoose.models['Application'];
345
- await model.findByIdAndUpdate(
346
- { _id: contextId },
347
- { $inc: { newAuditRecordsCount: count } },
348
- { new: true, upsert: true }
349
- );
350
- }
351
-
352
- export function registerAuditHook(callback) {
353
- onAuditLogCreated = callback;
354
- }
355
-
1
+ import AuditConfigModel from '../models/audit-config.model.js';
2
+ import AuditLog from '../models/audit.model.js';
3
+ import ValueReferenceMap from '../models/value-reference-map.model.js';
4
+ import { getContext } from '../services/request-context.service.js';
5
+ import mongoose from 'mongoose';
6
+ import FormConfigurationModel from '../models/form-configuration.model.js';
7
+
8
+ let onAuditLogCreated = null;
9
+
10
+ // Optionally, define custom resolvers here
11
+ const customResolvers = {
12
+ // Example:
13
+ // expenditureRationale: (doc) => `Rationale for ${doc.type}: ${doc.rationale}`
14
+ };
15
+
16
+ // Expression-based description resolver: resolves ${fieldName} in the expression using doc, and via Lookup if needed
17
+ async function resolveExpressionDescription(doc, expression, resolverType) {
18
+ console.log("expression-", expression);
19
+ console.log("resolverType-", resolverType);
20
+ const matches = [...expression.matchAll(/\$\{([^}]+)\}/g)];
21
+ let result = expression;
22
+ for (const match of matches) {
23
+ const fieldName = match[1];
24
+ let value = doc[fieldName];
25
+ if (resolverType === 'lookup' && value && mongoose.models['Lookup']) {
26
+ const lookupDoc = await mongoose.models['Lookup'].findById(value).lean();
27
+ value = lookupDoc?.name || value;
28
+ }
29
+ result = result.replace(match[0], value ?? '');
30
+ }
31
+ return result;
32
+ }
33
+
34
+ // Update resolveDescription to support expression-based descriptionField
35
+ async function resolveDescription(field, doc) {
36
+ const modelName = doc.constructor.modelName;
37
+ const config = await ValueReferenceMap.findOne({ field, model: modelName });
38
+ console.log("config-", config);
39
+ if (!config) return field;
40
+
41
+ if (config.descriptionField && config.descriptionField.includes('${')) {
42
+ console.log("config.descriptionField", config.descriptionField);
43
+ return await resolveExpressionDescription(doc, config.descriptionField, config.descriptionResolverType);
44
+ }
45
+ console.log("config.descriptionResolverType", config.descriptionResolverType);
46
+ switch (config.descriptionResolverType) {
47
+ case 'lookup': {
48
+ const lookupId = doc[config.descriptionField];
49
+ if (!lookupId) return '';
50
+ const lookupDoc = await mongoose.models['Lookup'].findById(lookupId).lean();
51
+ return lookupDoc?.name || '';
52
+ }
53
+ case 'direct':
54
+ return doc[config.descriptionField] || '';
55
+ case 'displayFieldReturn': // For case we just want to show display field value directly
56
+ return config.displayField || '';
57
+ case 'composite':
58
+ return (config.descriptionFields || [])
59
+ .map(f => doc[f])
60
+ .filter(Boolean)
61
+ .join(' ');
62
+ case 'custom':
63
+ if (typeof customResolvers?.[config.descriptionFunction] === 'function') {
64
+ return await customResolvers[config.descriptionFunction](doc);
65
+ }
66
+ return '';
67
+ default:
68
+ return '';
69
+ }
70
+ }
71
+
72
+ // Update resolveEntityDescription to support expression-based descriptionField
73
+ async function resolveEntityDescription(doc, auditConfig) {
74
+ if (!auditConfig.descriptionResolutorForExternalData) return '';
75
+ const field = auditConfig.descriptionResolutorForExternalData;
76
+ const value = doc[field];
77
+ // Try to resolve via ValueReferenceMap
78
+ console.log("field-", field);
79
+ const map = await ValueReferenceMap.findOne({ field });
80
+ console.log("map-", map);
81
+ if (map?.descriptionResolverType === 'displayFieldReturn') {
82
+ return map.descriptionField;
83
+ }
84
+ if (map && map.descriptionField && map.descriptionField.includes('${')) {
85
+ return await resolveExpressionDescription(doc, map.descriptionField, map.descriptionResolverType);
86
+ }
87
+ if (map && value) {
88
+ const Model = mongoose.models[map.model];
89
+ if (Model) {
90
+ const refDoc = await Model.findById(value).lean();
91
+ return refDoc?.[map.displayField] || value;
92
+ }
93
+ }
94
+ // Fallback: If it's an ObjectId and Lookup model exists, resolve to name
95
+ if (mongoose.Types.ObjectId.isValid(value) && mongoose.models['Lookup']) {
96
+ const lookupDoc = await mongoose.models['Lookup'].findById(value).lean();
97
+ return lookupDoc?.name || value;
98
+ }
99
+ return value;
100
+ }
101
+
102
+ // Add new function to resolve deletion description
103
+ async function resolveDeletionDescription(doc, auditConfig) {
104
+ if (!auditConfig.descriptionResolutorForDeletion) return '';
105
+ const expression = auditConfig.descriptionResolutorForDeletion;
106
+ return await resolveExpressionDescription(doc, expression, 'direct');
107
+ }
108
+
109
+ // Utility to build a fieldName -> dataType map from multiple formConfig.sections
110
+ function buildFieldTypeMapFromConfigs(formConfigs) {
111
+ const map = {};
112
+ function extractFields(sections) {
113
+ for (const section of sections || []) {
114
+ if (section.fields) {
115
+ for (const f of section.fields) map[f.fieldName] = f.dataType;
116
+ }
117
+ if (section.sections) extractFields(section.sections);
118
+ }
119
+ }
120
+ for (const config of formConfigs) {
121
+ extractFields(config.sections);
122
+ }
123
+ return map;
124
+ }
125
+
126
+ function applyAuditMiddleware(schema, collectionName) {
127
+ // Handle creation audit
128
+ schema.post('save', async function (doc) {
129
+ const auditConfig = await AuditConfigModel.findOne({ collectionName });
130
+ if (!auditConfig?.trackCreation) return;
131
+
132
+ // Fetch all form configs and build fieldTypeMap once
133
+ const formConfigs = await FormConfigurationModel.find({ collectionName });
134
+ const fieldTypeMap = buildFieldTypeMapFromConfigs(formConfigs);
135
+
136
+ const context = getContext();
137
+ const userId = context?.userId || null;
138
+ const contextId = context?.contextId;
139
+
140
+ const entityDescription = await resolveEntityDescription(doc, auditConfig);
141
+ let logs = [];
142
+
143
+ // Per-field logs
144
+ if (auditConfig.fields?.length) {
145
+ for (const field of auditConfig.fields) {
146
+ let lookupName;
147
+ const newValue = doc[field];
148
+ if (field.endsWith('Lid')) {
149
+ const newlookupDoc = await mongoose.models['Lookup'].findById(newValue).lean();
150
+ if (newlookupDoc) {
151
+ lookupName = newlookupDoc.name;
152
+ } else {
153
+ lookupName = '';
154
+ }
155
+ }
156
+ const fieldDescription = await resolveDescription(field, doc);
157
+ // --- Add pound prefix if needed ---
158
+ let displayNewValue = lookupName || newValue;
159
+ const dataType = fieldTypeMap[field];
160
+ if (dataType === 'pound' && displayNewValue != null && displayNewValue !== '') {
161
+ displayNewValue = `£${displayNewValue}`;
162
+ }
163
+ logs.push({
164
+ name: fieldDescription,
165
+ entity: entityDescription,
166
+ recordId: contextId || doc._id,
167
+ oldValue: null,
168
+ newValue: displayNewValue,
169
+ createdBy: userId,
170
+ externalData: {
171
+ description: entityDescription,
172
+ contextId
173
+ }
174
+ });
175
+ }
176
+ }
177
+ logs = logs.filter(log => {
178
+ // Convert null/undefined to empty string for comparison
179
+ const oldVal = log.oldValue ?? '';
180
+ const newVal = log.newValue ?? '';
181
+ return oldVal !== newVal;
182
+ });
183
+ if (logs.length) {
184
+ await AuditLog.insertMany(logs);
185
+ await updateContextAuditCount(contextId, logs.length);
186
+ if (onAuditLogCreated) {
187
+ await onAuditLogCreated(logs, contextId);
188
+ }
189
+ }
190
+ });
191
+
192
+ // Capture the original doc before update
193
+ schema.pre(['findOneAndUpdate', 'findByIdAndUpdate'], async function (next) {
194
+ this._originalDoc = await this.model.findOne(this.getQuery()).lean();
195
+ next();
196
+ });
197
+
198
+ // Handle update audits
199
+ schema.post(['findOneAndUpdate', 'findByIdAndUpdate'], async function (result) {
200
+ if (!result) return;
201
+
202
+ const auditConfig = await AuditConfigModel.findOne({ collectionName });
203
+ if (!auditConfig?.fields?.length) return;
204
+
205
+ // Fetch all form configs and build fieldTypeMap once
206
+ const formConfigs = await FormConfigurationModel.find({ collectionName });
207
+ const fieldTypeMap = buildFieldTypeMapFromConfigs(formConfigs);
208
+
209
+ const update = this.getUpdate();
210
+ let logs = [];
211
+ const context = getContext();
212
+ const userId = context?.userId || null;
213
+ const contextId = context?.contextId;
214
+
215
+ const entityDescription = await resolveEntityDescription(result, auditConfig);
216
+
217
+ for (const field of auditConfig.fields) {
218
+ console.log("field", field);
219
+ const hasChanged =
220
+ update?.$set?.hasOwnProperty(field) || update?.hasOwnProperty(field);
221
+ console.log("hasChanged", hasChanged);
222
+ if (hasChanged) {
223
+ const newValue = update?.$set?.[field] ?? update?.[field];
224
+ const oldValue = this._originalDoc ? this._originalDoc[field] : '';
225
+ let lookupOldName;
226
+ let lookupNewName;
227
+ if (field.endsWith('Lid')) {
228
+ const newlookupDoc = await mongoose.models['Lookup'].findById(newValue).lean();
229
+ if (newlookupDoc) {
230
+ lookupNewName = newlookupDoc.name;
231
+ } else {
232
+ lookupNewName = '';
233
+ }
234
+ const oldlookupDoc = await mongoose.models['Lookup'].findById(oldValue).lean();
235
+ if (oldlookupDoc) {
236
+ lookupOldName = oldlookupDoc.name;
237
+ } else {
238
+ lookupOldName = '';
239
+ }
240
+ }
241
+ // Convert null/undefined to empty string for comparison
242
+ let displayOldValue = lookupOldName ?? oldValue ?? '';
243
+ let displayNewValue = lookupNewName ?? newValue ?? '';
244
+ console.log("displayOldValue", displayOldValue);
245
+ console.log("displayNewValue", displayNewValue);
246
+ // --- Add pound prefix if needed ---
247
+ const dataType = fieldTypeMap[field];
248
+ if (dataType === 'pound') {
249
+ if (displayOldValue != null && displayOldValue !== '') displayOldValue = `£${displayOldValue}`;
250
+ if (displayNewValue != null && displayNewValue !== '') displayNewValue = `£${displayNewValue}`;
251
+ }
252
+ if (displayOldValue !== displayNewValue) {
253
+ const fieldDescription = await resolveDescription(field, result);
254
+ console.log("fieldDescription-", fieldDescription);
255
+ logs.push({
256
+ name: fieldDescription,
257
+ entity: entityDescription,
258
+ recordId: contextId || result._id,
259
+ oldValue: displayOldValue,
260
+ newValue: displayNewValue,
261
+ createdBy: userId,
262
+ externalData: {
263
+ description: entityDescription,
264
+ contextId: contextId || result._id
265
+ }
266
+ });
267
+ }
268
+ }
269
+ }
270
+ console.log("logs", logs);
271
+ logs = logs.filter(log => {
272
+ // Convert null/undefined to empty string for comparison
273
+ const oldVal = log.oldValue ?? '';
274
+ const newVal = log.newValue ?? '';
275
+ return oldVal !== newVal;
276
+ });
277
+ console.log("logs.length", logs.length);
278
+ if (logs.length) {
279
+ console.log("logs.length", logs.length);
280
+ await AuditLog.insertMany(logs);
281
+ await updateContextAuditCount(contextId, logs.length);
282
+ if (onAuditLogCreated) {
283
+ await onAuditLogCreated(logs, contextId);
284
+ }
285
+ }
286
+ });
287
+
288
+ // Handle delete audits
289
+ schema.pre(['findOneAndDelete', 'findByIdAndDelete', 'deleteOne', 'deleteMany'], async function (next) {
290
+ try {
291
+ // Fetch the document before deletion
292
+ const docToDelete = await this.model.findOne(this.getQuery()).lean();
293
+ if (docToDelete) {
294
+ // Store the document for use in post middleware
295
+ this._docToDelete = docToDelete;
296
+ }
297
+ next();
298
+ } catch (error) {
299
+ next(error);
300
+ }
301
+ });
302
+
303
+ schema.post(['findOneAndDelete', 'findByIdAndDelete', 'deleteOne', 'deleteMany'], async function (result) {
304
+ if (!result) return;
305
+
306
+ const auditConfig = await AuditConfigModel.findOne({ collectionName });
307
+ if (!auditConfig?.trackDeletion) return;
308
+
309
+ const context = getContext();
310
+ const userId = context?.userId || null;
311
+ const contextId = context?.contextId;
312
+
313
+ const entityDescription = await resolveEntityDescription(this._docToDelete, auditConfig);
314
+ const deletionDescription = await resolveDeletionDescription(this._docToDelete, auditConfig);
315
+
316
+ const log = {
317
+ name: deletionDescription || 'Entity Deletion',
318
+ entity: entityDescription,
319
+ recordId: contextId || this._docToDelete._id,
320
+ oldValue: '',
321
+ newValue: 'Deleted',
322
+ createdBy: userId,
323
+ externalData: {
324
+ description: entityDescription,
325
+ contextId: contextId || this._docToDelete._id
326
+ }
327
+ };
328
+ const oldVal = log.oldValue ?? '';
329
+ const newVal = log.newValue ?? '';
330
+ if (oldVal === newVal) {
331
+ return;
332
+ }
333
+ await AuditLog.create(log);
334
+ await updateContextAuditCount(contextId, 1);
335
+ if (onAuditLogCreated) {
336
+ await onAuditLogCreated([log], contextId);
337
+ }
338
+ });
339
+ }
340
+
341
+ async function updateContextAuditCount(contextId, count) {
342
+ count = Number(count);
343
+ if (!contextId || isNaN(count)) return;
344
+ const model = mongoose.models['Application'];
345
+ await model.findByIdAndUpdate(
346
+ { _id: contextId },
347
+ { $inc: { newAuditRecordsCount: count } },
348
+ { new: true, upsert: true }
349
+ );
350
+ }
351
+
352
+ export function registerAuditHook(callback) {
353
+ onAuditLogCreated = callback;
354
+ }
355
+
356
356
  export default applyAuditMiddleware;