@dynamatix/cat-shared 0.0.120 → 0.0.122

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