@justair/justair-library 4.7.21 → 4.7.22

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