@justair/justair-library 4.8.11 → 4.8.13

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 (35) hide show
  1. package/.github/workflows/publish.yml +28 -0
  2. package/README +146 -146
  3. package/package.json +27 -27
  4. package/src/config/db.js +116 -116
  5. package/src/config/logger.js +143 -143
  6. package/src/index.js +116 -116
  7. package/src/models/admin.js +27 -27
  8. package/src/models/alerts.js +219 -219
  9. package/src/models/announcements.js +31 -31
  10. package/src/models/apiKey.js +22 -22
  11. package/src/models/configurations.js +17 -17
  12. package/src/models/contexts.js +13 -13
  13. package/src/models/dataCompleteness.js +35 -35
  14. package/src/models/events.js +128 -128
  15. package/src/models/features.js +14 -14
  16. package/src/models/jobs.js +43 -43
  17. package/src/models/lightmonitors.js +30 -30
  18. package/src/models/measurements.js +263 -263
  19. package/src/models/monitorRequests.js +25 -25
  20. package/src/models/monitorSuppliers.js +49 -49
  21. package/src/models/monitors.js +394 -394
  22. package/src/models/networkMetrics.js +42 -42
  23. package/src/models/organizations.js +97 -97
  24. package/src/models/parameters.js +11 -11
  25. package/src/models/referenceMonitorInfo.js +18 -18
  26. package/src/models/tests/admin.test.js +42 -42
  27. package/src/models/tests/configurations.test.js +44 -44
  28. package/src/models/tests/measurements.test.js +46 -46
  29. package/src/models/tests/monitorRequests.test.js +46 -46
  30. package/src/models/tests/monitors.test.js +62 -62
  31. package/src/models/tests/organizations.test.js +51 -51
  32. package/src/models/tests/users.test.js +54 -54
  33. package/src/models/usageMetrics.js +28 -28
  34. package/src/models/users.js +55 -55
  35. package/tsconfig.json +10 -10
@@ -1,394 +1,394 @@
1
- import mongoose from "mongoose";
2
- const parametersEnum = [
3
- "NO2",
4
- "SO2",
5
- "PM2.5",
6
- "PM10",
7
- "Temperature",
8
- "Humidity",
9
- "OZONE",
10
- "VOC",
11
- "CO",
12
- "NO",
13
- "PM1",
14
- "WS And Direction",
15
- "DP",
16
- "CO2",
17
- "CH4",
18
- ];
19
-
20
- const noteSchema = mongoose.Schema({
21
- note: {
22
- type: String,
23
- required: true,
24
- },
25
- type: {
26
- type: String,
27
- required: true,
28
- },
29
- monitorState: {
30
- type: String,
31
- required: true,
32
- },
33
- adminId: {
34
- type: mongoose.Types.ObjectId,
35
- ref: "Admin",
36
- required: true,
37
- },
38
- adminName: {
39
- type: String,
40
- },
41
- date: {
42
- type: Date,
43
- default: Date.now,
44
- },
45
- });
46
-
47
- const correctionSchema = mongoose.Schema(
48
- {
49
- equationType: {
50
- type: String,
51
- enum: ["linear", "custom"],
52
- required: true,
53
- },
54
- equation: {
55
- type: String,
56
- required: function () {
57
- return this.equationType === "custom";
58
- },
59
- validate: {
60
- validator: function (value) {
61
- if (!value) return true; // Allow empty for non-custom types
62
- if (value.includes("\0")) return false;
63
- try {
64
- const encoder = new TextEncoder();
65
- const decoder = new TextDecoder("utf-8", { fatal: true });
66
- decoder.decode(encoder.encode(value));
67
- return true;
68
- } catch (e) {
69
- return false;
70
- }
71
- },
72
- message: "Equation contains invalid UTF-8 characters",
73
- },
74
- },
75
- context: {
76
- type: String,
77
- enum: ["field", "colocation"],
78
- required: false,
79
- },
80
- variables: {
81
- required: function () {
82
- return this.equationType === "linear";
83
- },
84
- type: Object,
85
- },
86
- dateCreated: {
87
- type: Date,
88
- default: Date.now,
89
- },
90
- applyCorrection: { type: Boolean, default: true },
91
- },
92
- { _id: false } // no separate _id for sub-docs
93
- );
94
-
95
- const correctionHistorySchema = mongoose.Schema(
96
- {
97
- pollutant: {
98
- type: String,
99
- required: true,
100
- validate: {
101
- validator: function (value) {
102
- // Check for null bytes and validate UTF-8
103
- if (value.includes("\0")) return false;
104
- try {
105
- const encoder = new TextEncoder();
106
- const decoder = new TextDecoder("utf-8", { fatal: true });
107
- decoder.decode(encoder.encode(value));
108
- return true;
109
- } catch (e) {
110
- return false;
111
- }
112
- },
113
- message: "Pollutant contains invalid UTF-8 characters",
114
- },
115
- },
116
- oldValue: {
117
- type: correctionSchema,
118
- default: undefined,
119
- },
120
- newValue: {
121
- type: correctionSchema,
122
- default: undefined,
123
- },
124
- changedAt: {
125
- type: Date,
126
- default: Date.now,
127
- },
128
- },
129
- { _id: false }
130
- );
131
-
132
- // Monitor Audit Schema
133
- const monitorAuditSchema = mongoose.Schema(
134
- {
135
- monitorId: { type: mongoose.Types.ObjectId, ref: "Monitors" },
136
- orgId: { type: mongoose.Types.ObjectId, ref: "Organizations" },
137
- timeUpdated: Date,
138
- deletedAt: { type: Date, default: Date.now }, // Only populated on delete
139
- monitorProperties: Object, // Stores properties of the monitor
140
- monitorState: String, // Tracks the state of the monitor (e.g., "Deployed", "Maintenance")
141
- monitorLocation: {
142
- // Monitor GPS location (lat, lon)
143
- type: { type: String, enum: ["Point"], required: true },
144
- coordinates: { type: [Number], required: true },
145
- },
146
- parameterThresholds: Object,
147
- corrections: {
148
- type: Map,
149
- of: correctionSchema,
150
- default: {},
151
- },
152
- correctionHistory: {
153
- type: [correctionHistorySchema],
154
- default: [],
155
- },
156
- },
157
- {
158
- timestamps: true,
159
- }
160
- );
161
-
162
- // Create the MonitorAudit model
163
- const MonitorAudit = mongoose.model("MonitorAudit", monitorAuditSchema);
164
-
165
- // Monitors Schema
166
- const monitorsSchema = mongoose.Schema(
167
- {
168
- monitorCode: String,
169
- monitorSupplier: {
170
- type: String,
171
- enum: [
172
- "clarity",
173
- "aeroqual",
174
- "purple air",
175
- "reference monitor",
176
- "earthview",
177
- "sensit",
178
- "blue sky",
179
- "aq mesh",
180
- "quant aq",
181
- "airGradient",
182
- "oizom",
183
- "metOne",
184
- "aqMesh",
185
- "kunak",
186
- ],
187
- },
188
- monitorType: String,
189
- monitorIdFromSupplier: String,
190
- measurementUpdate: Date,
191
- monitorProperties: Object,
192
- isPrivate: { type: Boolean, default: false, required: true },
193
- monitorState: {
194
- type: String,
195
- enum: ["Collocation", "Deployed", "Maintenance", "Pending Deployment"],
196
- },
197
- monitorStateHistory: [Object],
198
- monitorAlertStatus: {
199
- type: String,
200
- enum: [
201
- "Good",
202
- "Moderate",
203
- "Unhealthy for SG",
204
- "Unhealthy",
205
- "Very Unhealthy",
206
- "Hazardous",
207
- "Bad",
208
- ],
209
- default: "Good",
210
- },
211
- sponsor: { type: mongoose.Types.ObjectId, ref: "Organizations" },
212
- sponsorName: String,
213
- monitorLatitude: Number,
214
- monitorLongitude: Number,
215
- gpsLocation: {
216
- type: { type: String, enum: ["Point"], required: true },
217
- coordinates: { type: [Number], required: true },
218
- },
219
- location: Object,
220
- context: [String],
221
- colocationDate: Date,
222
- deploymentDate: Date,
223
- subscriptionDate: Date,
224
- parameters: [
225
- {
226
- type: String,
227
- enum: parametersEnum,
228
- },
229
- ],
230
- latestPM2_5: Number,
231
- latestAQI_PM2_5: Number,
232
- notes: [noteSchema],
233
- calculatedAverages: [Object],
234
- images: [String],
235
- isActive: { type: Boolean, default: true },
236
- parameterThresholds: Object,
237
- completionPercentageThresholds: Object,
238
- anomalyPercentageThresholds: Object,
239
- // A Map, keyed by pollutant (e.g. "PM2_5"), storing Correction sub-docs
240
- corrections: {
241
- type: Map,
242
- of: correctionSchema,
243
- default: {},
244
- },
245
- correctionHistory: {
246
- type: [correctionHistorySchema],
247
- default: [],
248
- },
249
- applyCorrections: { type: Boolean, default: false },
250
- pausedParameters: {
251
- type: [{ parameter: String, timestamp: Date, isPaused: Boolean }],
252
- default: [],
253
- },
254
- },
255
- {
256
- timestamps: true,
257
- }
258
- );
259
-
260
- // Geographic queries - already exists
261
- monitorsSchema.index({ gpsLocation: "2dsphere" });
262
-
263
- // Sponsor-based queries
264
- monitorsSchema.index({ sponsor: 1, isPrivate: 1, isActive: 1 });
265
-
266
- // Location-based filtering
267
- monitorsSchema.index({ "location.city": 1, "location.state": 1 });
268
- monitorsSchema.index({ "location.neighborhood": 1 });
269
- monitorsSchema.index({ "location.county": 1 });
270
-
271
- // Query parameter filtering
272
- monitorsSchema.index({ monitorSupplier: 1, monitorState: 1 });
273
- monitorsSchema.index({ context: 1 });
274
- monitorsSchema.index({ parameters: 1 });
275
-
276
- //network metrics for anomalies
277
- monitorsSchema.index({ sponsor: 1, isActive: 1, monitorSupplier: 1 });
278
-
279
- // Pre-hook to log single document deletions
280
- monitorsSchema.pre("findOneAndDelete", async function () {
281
- const docToDelete = await this.model.findOne(this.getFilter()).lean();
282
- if (docToDelete) {
283
- console.log("Logging findOneAndDelete to monitor audit", docToDelete);
284
- const auditLog = new MonitorAudit({
285
- monitorId: docToDelete._id,
286
- orgId: docToDelete.sponsor,
287
- timeUpdated: docToDelete.updatedAt,
288
- monitorProperties: docToDelete.monitorProperties,
289
- monitorState: docToDelete.monitorState,
290
- monitorLocation: {
291
- type: "Point",
292
- coordinates: [
293
- docToDelete.monitorLongitude,
294
- docToDelete.monitorLatitude,
295
- ],
296
- },
297
- parameterThresholds: docToDelete.parameterThresholds,
298
- corrections: docToDelete.corrections,
299
- correctionHistory: docToDelete.correctionHistory,
300
- applyCorrections: docToDelete.applyCorrections,
301
- deletedAt: new Date(),
302
- });
303
- await auditLog.save();
304
- }
305
- });
306
-
307
- // Pre-hook to log multiple document deletions
308
- monitorsSchema.pre("deleteMany", async function () {
309
- console.log("deleteMany pre-hook triggered for monitors");
310
- const docsToDelete = await this.model.find(this.getFilter()).lean();
311
-
312
- if (docsToDelete.length) {
313
- console.log(`Logging ${docsToDelete.length} monitor documents to audit`);
314
- const auditLogs = docsToDelete.map((doc) => ({
315
- monitorId: doc._id,
316
- orgId: doc.sponsor,
317
- timeUpdated: doc.updatedAt,
318
- monitorProperties: doc.monitorProperties,
319
- monitorState: doc.monitorState,
320
- monitorLocation: {
321
- type: "Point",
322
- coordinates: [doc.monitorLongitude, doc.monitorLatitude],
323
- },
324
- parameterThresholds: doc.parameterThresholds,
325
- corrections: doc.corrections,
326
- correctionHistory: doc.correctionHistory,
327
- applyCorrections: doc.applyCorrections,
328
- deletedAt: new Date(),
329
- }));
330
-
331
- await MonitorAudit.insertMany(auditLogs);
332
- }
333
- });
334
-
335
- // Pre-hook to log a single document deletion (for deleteOne)
336
- monitorsSchema.pre("deleteOne", async function () {
337
- console.log("deleteOne pre-hook triggered for monitors");
338
- const docToDelete = await this.model.findOne(this.getFilter()).lean();
339
-
340
- if (docToDelete) {
341
- console.log("Logging deleteOne to monitor audit", docToDelete);
342
- const auditLog = new MonitorAudit({
343
- monitorId: docToDelete._id,
344
- orgId: docToDelete.sponsor,
345
- timeUpdated: docToDelete.updatedAt,
346
- monitorProperties: docToDelete.monitorProperties,
347
- monitorState: docToDelete.monitorState,
348
- monitorLocation: {
349
- type: "Point",
350
- coordinates: [
351
- docToDelete.monitorLongitude,
352
- docToDelete.monitorLatitude,
353
- ],
354
- },
355
- parameterThresholds: docToDelete.parameterThresholds,
356
- corrections: docToDelete.corrections,
357
- correctionHistory: docToDelete.correctionHistory,
358
- applyCorrections: docToDelete.applyCorrections,
359
- deletedAt: new Date(),
360
- });
361
- await auditLog.save();
362
- }
363
- });
364
-
365
- // Pre-hook to log multiple document updates
366
- monitorsSchema.pre("updateMany", async function () {
367
- const docsToUpdate = await this.model.find(this.getFilter()).lean();
368
- if (docsToUpdate.length) {
369
- console.log(`Logging ${docsToUpdate.length} monitor documents to audit`);
370
- const auditLogs = docsToUpdate.map((doc) => ({
371
- monitorId: doc._id,
372
- orgId: doc.sponsor,
373
- timeUpdated: doc.updatedAt,
374
- monitorProperties: doc.monitorProperties,
375
- monitorState: doc.monitorState,
376
- monitorLocation: {
377
- type: "Point",
378
- coordinates: [doc.monitorLongitude, doc.monitorLatitude],
379
- },
380
- parameterThresholds: doc.parameterThresholds,
381
- corrections: doc.corrections,
382
- correctionHistory: doc.correctionHistory,
383
- applyCorrections: doc.applyCorrections,
384
- deletedAt: null, // Not a deletion, so this field is null
385
- }));
386
-
387
- await MonitorAudit.insertMany(auditLogs);
388
- }
389
- });
390
-
391
- // Create the Monitors model
392
- const Monitors = mongoose.model("Monitors", monitorsSchema);
393
-
394
- export { monitorsSchema, Monitors, monitorAuditSchema, MonitorAudit };
1
+ import mongoose from "mongoose";
2
+ const parametersEnum = [
3
+ "NO2",
4
+ "SO2",
5
+ "PM2.5",
6
+ "PM10",
7
+ "Temperature",
8
+ "Humidity",
9
+ "OZONE",
10
+ "VOC",
11
+ "CO",
12
+ "NO",
13
+ "PM1",
14
+ "WS And Direction",
15
+ "DP",
16
+ "CO2",
17
+ "CH4",
18
+ ];
19
+
20
+ const noteSchema = mongoose.Schema({
21
+ note: {
22
+ type: String,
23
+ required: true,
24
+ },
25
+ type: {
26
+ type: String,
27
+ required: true,
28
+ },
29
+ monitorState: {
30
+ type: String,
31
+ required: true,
32
+ },
33
+ adminId: {
34
+ type: mongoose.Types.ObjectId,
35
+ ref: "Admin",
36
+ required: true,
37
+ },
38
+ adminName: {
39
+ type: String,
40
+ },
41
+ date: {
42
+ type: Date,
43
+ default: Date.now,
44
+ },
45
+ });
46
+
47
+ const correctionSchema = mongoose.Schema(
48
+ {
49
+ equationType: {
50
+ type: String,
51
+ enum: ["linear", "custom"],
52
+ required: true,
53
+ },
54
+ equation: {
55
+ type: String,
56
+ required: function () {
57
+ return this.equationType === "custom";
58
+ },
59
+ validate: {
60
+ validator: function (value) {
61
+ if (!value) return true; // Allow empty for non-custom types
62
+ if (value.includes("\0")) return false;
63
+ try {
64
+ const encoder = new TextEncoder();
65
+ const decoder = new TextDecoder("utf-8", { fatal: true });
66
+ decoder.decode(encoder.encode(value));
67
+ return true;
68
+ } catch (e) {
69
+ return false;
70
+ }
71
+ },
72
+ message: "Equation contains invalid UTF-8 characters",
73
+ },
74
+ },
75
+ context: {
76
+ type: String,
77
+ enum: ["field", "colocation"],
78
+ required: false,
79
+ },
80
+ variables: {
81
+ required: function () {
82
+ return this.equationType === "linear";
83
+ },
84
+ type: Object,
85
+ },
86
+ dateCreated: {
87
+ type: Date,
88
+ default: Date.now,
89
+ },
90
+ applyCorrection: { type: Boolean, default: true },
91
+ },
92
+ { _id: false } // no separate _id for sub-docs
93
+ );
94
+
95
+ const correctionHistorySchema = mongoose.Schema(
96
+ {
97
+ pollutant: {
98
+ type: String,
99
+ required: true,
100
+ validate: {
101
+ validator: function (value) {
102
+ // Check for null bytes and validate UTF-8
103
+ if (value.includes("\0")) return false;
104
+ try {
105
+ const encoder = new TextEncoder();
106
+ const decoder = new TextDecoder("utf-8", { fatal: true });
107
+ decoder.decode(encoder.encode(value));
108
+ return true;
109
+ } catch (e) {
110
+ return false;
111
+ }
112
+ },
113
+ message: "Pollutant contains invalid UTF-8 characters",
114
+ },
115
+ },
116
+ oldValue: {
117
+ type: correctionSchema,
118
+ default: undefined,
119
+ },
120
+ newValue: {
121
+ type: correctionSchema,
122
+ default: undefined,
123
+ },
124
+ changedAt: {
125
+ type: Date,
126
+ default: Date.now,
127
+ },
128
+ },
129
+ { _id: false }
130
+ );
131
+
132
+ // Monitor Audit Schema
133
+ const monitorAuditSchema = mongoose.Schema(
134
+ {
135
+ monitorId: { type: mongoose.Types.ObjectId, ref: "Monitors" },
136
+ orgId: { type: mongoose.Types.ObjectId, ref: "Organizations" },
137
+ timeUpdated: Date,
138
+ deletedAt: { type: Date, default: Date.now }, // Only populated on delete
139
+ monitorProperties: Object, // Stores properties of the monitor
140
+ monitorState: String, // Tracks the state of the monitor (e.g., "Deployed", "Maintenance")
141
+ monitorLocation: {
142
+ // Monitor GPS location (lat, lon)
143
+ type: { type: String, enum: ["Point"], required: true },
144
+ coordinates: { type: [Number], required: true },
145
+ },
146
+ parameterThresholds: Object,
147
+ corrections: {
148
+ type: Map,
149
+ of: correctionSchema,
150
+ default: {},
151
+ },
152
+ correctionHistory: {
153
+ type: [correctionHistorySchema],
154
+ default: [],
155
+ },
156
+ },
157
+ {
158
+ timestamps: true,
159
+ }
160
+ );
161
+
162
+ // Create the MonitorAudit model
163
+ const MonitorAudit = mongoose.model("MonitorAudit", monitorAuditSchema);
164
+
165
+ // Monitors Schema
166
+ const monitorsSchema = mongoose.Schema(
167
+ {
168
+ monitorCode: String,
169
+ monitorSupplier: {
170
+ type: String,
171
+ enum: [
172
+ "clarity",
173
+ "aeroqual",
174
+ "purple air",
175
+ "reference monitor",
176
+ "earthview",
177
+ "sensit",
178
+ "blue sky",
179
+ "aq mesh",
180
+ "quant aq",
181
+ "airGradient",
182
+ "oizom",
183
+ "metOne",
184
+ "aqMesh",
185
+ "kunak",
186
+ ],
187
+ },
188
+ monitorType: String,
189
+ monitorIdFromSupplier: String,
190
+ measurementUpdate: Date,
191
+ monitorProperties: Object,
192
+ isPrivate: { type: Boolean, default: false, required: true },
193
+ monitorState: {
194
+ type: String,
195
+ enum: ["Collocation", "Deployed", "Maintenance", "Pending Deployment"],
196
+ },
197
+ monitorStateHistory: [Object],
198
+ monitorAlertStatus: {
199
+ type: String,
200
+ enum: [
201
+ "Good",
202
+ "Moderate",
203
+ "Unhealthy for SG",
204
+ "Unhealthy",
205
+ "Very Unhealthy",
206
+ "Hazardous",
207
+ "Bad",
208
+ ],
209
+ default: "Good",
210
+ },
211
+ sponsor: { type: mongoose.Types.ObjectId, ref: "Organizations" },
212
+ sponsorName: String,
213
+ monitorLatitude: Number,
214
+ monitorLongitude: Number,
215
+ gpsLocation: {
216
+ type: { type: String, enum: ["Point"], required: true },
217
+ coordinates: { type: [Number], required: true },
218
+ },
219
+ location: Object,
220
+ context: [String],
221
+ colocationDate: Date,
222
+ deploymentDate: Date,
223
+ subscriptionDate: Date,
224
+ parameters: [
225
+ {
226
+ type: String,
227
+ enum: parametersEnum,
228
+ },
229
+ ],
230
+ latestPM2_5: Number,
231
+ latestAQI_PM2_5: Number,
232
+ notes: [noteSchema],
233
+ calculatedAverages: [Object],
234
+ images: [String],
235
+ isActive: { type: Boolean, default: true },
236
+ parameterThresholds: Object,
237
+ completionPercentageThresholds: Object,
238
+ anomalyPercentageThresholds: Object,
239
+ // A Map, keyed by pollutant (e.g. "PM2_5"), storing Correction sub-docs
240
+ corrections: {
241
+ type: Map,
242
+ of: correctionSchema,
243
+ default: {},
244
+ },
245
+ correctionHistory: {
246
+ type: [correctionHistorySchema],
247
+ default: [],
248
+ },
249
+ applyCorrections: { type: Boolean, default: false },
250
+ pausedParameters: {
251
+ type: [{ parameter: String, timestamp: Date, isPaused: Boolean }],
252
+ default: [],
253
+ },
254
+ },
255
+ {
256
+ timestamps: true,
257
+ }
258
+ );
259
+
260
+ // Geographic queries - already exists
261
+ monitorsSchema.index({ gpsLocation: "2dsphere" });
262
+
263
+ // Sponsor-based queries
264
+ monitorsSchema.index({ sponsor: 1, isPrivate: 1, isActive: 1 });
265
+
266
+ // Location-based filtering
267
+ monitorsSchema.index({ "location.city": 1, "location.state": 1 });
268
+ monitorsSchema.index({ "location.neighborhood": 1 });
269
+ monitorsSchema.index({ "location.county": 1 });
270
+
271
+ // Query parameter filtering
272
+ monitorsSchema.index({ monitorSupplier: 1, monitorState: 1 });
273
+ monitorsSchema.index({ context: 1 });
274
+ monitorsSchema.index({ parameters: 1 });
275
+
276
+ //network metrics for anomalies
277
+ monitorsSchema.index({ sponsor: 1, isActive: 1, monitorSupplier: 1 });
278
+
279
+ // Pre-hook to log single document deletions
280
+ monitorsSchema.pre("findOneAndDelete", async function () {
281
+ const docToDelete = await this.model.findOne(this.getFilter()).lean();
282
+ if (docToDelete) {
283
+ console.log("Logging findOneAndDelete to monitor audit", docToDelete);
284
+ const auditLog = new MonitorAudit({
285
+ monitorId: docToDelete._id,
286
+ orgId: docToDelete.sponsor,
287
+ timeUpdated: docToDelete.updatedAt,
288
+ monitorProperties: docToDelete.monitorProperties,
289
+ monitorState: docToDelete.monitorState,
290
+ monitorLocation: {
291
+ type: "Point",
292
+ coordinates: [
293
+ docToDelete.monitorLongitude,
294
+ docToDelete.monitorLatitude,
295
+ ],
296
+ },
297
+ parameterThresholds: docToDelete.parameterThresholds,
298
+ corrections: docToDelete.corrections,
299
+ correctionHistory: docToDelete.correctionHistory,
300
+ applyCorrections: docToDelete.applyCorrections,
301
+ deletedAt: new Date(),
302
+ });
303
+ await auditLog.save();
304
+ }
305
+ });
306
+
307
+ // Pre-hook to log multiple document deletions
308
+ monitorsSchema.pre("deleteMany", async function () {
309
+ console.log("deleteMany pre-hook triggered for monitors");
310
+ const docsToDelete = await this.model.find(this.getFilter()).lean();
311
+
312
+ if (docsToDelete.length) {
313
+ console.log(`Logging ${docsToDelete.length} monitor documents to audit`);
314
+ const auditLogs = docsToDelete.map((doc) => ({
315
+ monitorId: doc._id,
316
+ orgId: doc.sponsor,
317
+ timeUpdated: doc.updatedAt,
318
+ monitorProperties: doc.monitorProperties,
319
+ monitorState: doc.monitorState,
320
+ monitorLocation: {
321
+ type: "Point",
322
+ coordinates: [doc.monitorLongitude, doc.monitorLatitude],
323
+ },
324
+ parameterThresholds: doc.parameterThresholds,
325
+ corrections: doc.corrections,
326
+ correctionHistory: doc.correctionHistory,
327
+ applyCorrections: doc.applyCorrections,
328
+ deletedAt: new Date(),
329
+ }));
330
+
331
+ await MonitorAudit.insertMany(auditLogs);
332
+ }
333
+ });
334
+
335
+ // Pre-hook to log a single document deletion (for deleteOne)
336
+ monitorsSchema.pre("deleteOne", async function () {
337
+ console.log("deleteOne pre-hook triggered for monitors");
338
+ const docToDelete = await this.model.findOne(this.getFilter()).lean();
339
+
340
+ if (docToDelete) {
341
+ console.log("Logging deleteOne to monitor audit", docToDelete);
342
+ const auditLog = new MonitorAudit({
343
+ monitorId: docToDelete._id,
344
+ orgId: docToDelete.sponsor,
345
+ timeUpdated: docToDelete.updatedAt,
346
+ monitorProperties: docToDelete.monitorProperties,
347
+ monitorState: docToDelete.monitorState,
348
+ monitorLocation: {
349
+ type: "Point",
350
+ coordinates: [
351
+ docToDelete.monitorLongitude,
352
+ docToDelete.monitorLatitude,
353
+ ],
354
+ },
355
+ parameterThresholds: docToDelete.parameterThresholds,
356
+ corrections: docToDelete.corrections,
357
+ correctionHistory: docToDelete.correctionHistory,
358
+ applyCorrections: docToDelete.applyCorrections,
359
+ deletedAt: new Date(),
360
+ });
361
+ await auditLog.save();
362
+ }
363
+ });
364
+
365
+ // Pre-hook to log multiple document updates
366
+ monitorsSchema.pre("updateMany", async function () {
367
+ const docsToUpdate = await this.model.find(this.getFilter()).lean();
368
+ if (docsToUpdate.length) {
369
+ console.log(`Logging ${docsToUpdate.length} monitor documents to audit`);
370
+ const auditLogs = docsToUpdate.map((doc) => ({
371
+ monitorId: doc._id,
372
+ orgId: doc.sponsor,
373
+ timeUpdated: doc.updatedAt,
374
+ monitorProperties: doc.monitorProperties,
375
+ monitorState: doc.monitorState,
376
+ monitorLocation: {
377
+ type: "Point",
378
+ coordinates: [doc.monitorLongitude, doc.monitorLatitude],
379
+ },
380
+ parameterThresholds: doc.parameterThresholds,
381
+ corrections: doc.corrections,
382
+ correctionHistory: doc.correctionHistory,
383
+ applyCorrections: doc.applyCorrections,
384
+ deletedAt: null, // Not a deletion, so this field is null
385
+ }));
386
+
387
+ await MonitorAudit.insertMany(auditLogs);
388
+ }
389
+ });
390
+
391
+ // Create the Monitors model
392
+ const Monitors = mongoose.model("Monitors", monitorsSchema);
393
+
394
+ export { monitorsSchema, Monitors, monitorAuditSchema, MonitorAudit };