dt-common-device 3.0.10 → 3.0.12

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 (145) hide show
  1. package/dist/audit/AuditProperties.d.ts +16 -0
  2. package/dist/audit/AuditUtils.d.ts +2 -0
  3. package/dist/audit/AuditUtils.js +36 -0
  4. package/dist/config/config.d.ts +1 -2
  5. package/dist/config/config.js +4 -5
  6. package/dist/constants/Service.d.ts +1 -0
  7. package/dist/device/local/events/EventHandler.js +6 -6
  8. package/dist/device/local/events/Events.d.ts +33 -12
  9. package/dist/device/local/events/Events.js +33 -12
  10. package/dist/device/local/repository/Schedule.repository.d.ts +0 -1
  11. package/dist/device/local/repository/Schedule.repository.js +6 -6
  12. package/dist/queue/entities/HybridHttpQueue.d.ts +4 -14
  13. package/dist/queue/entities/HybridHttpQueue.js +31 -119
  14. package/dist/queue/interfaces/IHybridHttpQueue.d.ts +2 -12
  15. package/dist/queue/interfaces/IJobResult.d.ts +1 -8
  16. package/dist/queue/interfaces/index.d.ts +0 -1
  17. package/dist/queue/interfaces/index.js +0 -1
  18. package/dist/queue/services/QueueService.d.ts +2 -12
  19. package/dist/queue/types/http.types.d.ts +6 -4
  20. package/dist/queue/types/queue.types.d.ts +12 -29
  21. package/dist/queue/utils/jobUtils.d.ts +2 -4
  22. package/dist/queue/utils/jobUtils.js +0 -48
  23. package/dist/queue/utils/queueUtils.d.ts +7 -0
  24. package/dist/queue/utils/queueUtils.js +114 -4
  25. package/dist/queue/utils/rateLimit.utils.d.ts +1 -1
  26. package/dist/queue/utils/rateLimit.utils.js +38 -2
  27. package/package.json +6 -1
  28. package/.eslintrc.js +0 -44
  29. package/dist/device/cloud/interface.d.ts +0 -101
  30. package/dist/device/cloud/interface.js +0 -3
  31. package/dist/device/cloud/interfaces/IDeviceConnectionService.d.ts +0 -7
  32. package/dist/device/cloud/interfaces/IDeviceConnectionService.js +0 -3
  33. package/dist/device/cloud/interfaces/IDevicesService.d.ts +0 -9
  34. package/dist/device/cloud/services/Device.service.d.ts +0 -39
  35. package/dist/device/cloud/services/Device.service.js +0 -9
  36. package/dist/device/cloud/services/DeviceCloudService.d.ts +0 -42
  37. package/dist/device/cloud/services/DeviceCloudService.js +0 -59
  38. package/dist/device/cloud/services/DeviceHub.service.d.ts +0 -3
  39. package/dist/device/cloud/services/DeviceHub.service.js +0 -6
  40. package/dist/device/cloud/services/Hub.service.d.ts +0 -25
  41. package/dist/device/cloud/services/Hub.service.js +0 -9
  42. package/dist/device/cloud/services/SmartThingsDeviceService.d.ts +0 -38
  43. package/dist/device/cloud/services/SmartThingsDeviceService.js +0 -52
  44. package/dist/device/index.d.ts +0 -4
  45. package/dist/device/index.js +0 -20
  46. package/dist/device/local/interface.d.ts +0 -0
  47. package/dist/device/local/interface.js +0 -1
  48. package/dist/device/local/services/DeviceHub.service.d.ts +0 -11
  49. package/dist/device/local/services/DeviceHub.service.js +0 -40
  50. package/src/alerts/Alert.model.ts +0 -289
  51. package/src/alerts/Alert.repository.ts +0 -487
  52. package/src/alerts/Alert.service.ts +0 -711
  53. package/src/alerts/AlertBuilder.example.ts +0 -126
  54. package/src/alerts/AlertBuilder.ts +0 -208
  55. package/src/alerts/AlertService.example.ts +0 -232
  56. package/src/alerts/alert.types.ts +0 -64
  57. package/src/alerts/index.ts +0 -3
  58. package/src/config/config.ts +0 -202
  59. package/src/config/config.types.ts +0 -21
  60. package/src/connection/Connection.repository.ts +0 -52
  61. package/src/connection/Connection.service.ts +0 -39
  62. package/src/connection/IConnection.ts +0 -27
  63. package/src/connection/index.ts +0 -3
  64. package/src/constants/ConnectionProviders.ts +0 -11
  65. package/src/constants/Event.ts +0 -89
  66. package/src/constants/Service.ts +0 -17
  67. package/src/constants/index.ts +0 -3
  68. package/src/db/db.ts +0 -24
  69. package/src/db/index.ts +0 -2
  70. package/src/db/redis.ts +0 -20
  71. package/src/device/cloud/entities/CloudDevice.ts +0 -40
  72. package/src/device/cloud/entities/CloudDeviceService.ts +0 -8
  73. package/src/device/cloud/entities/DeviceFactory.ts +0 -27
  74. package/src/device/cloud/entities/index.ts +0 -3
  75. package/src/device/cloud/interfaces/ICloudDevice.ts +0 -14
  76. package/src/device/cloud/interfaces/ICloudDeviceService.ts +0 -6
  77. package/src/device/cloud/interfaces/IDeviceFactory.ts +0 -5
  78. package/src/device/cloud/interfaces/IRawDataTransformer.ts +0 -5
  79. package/src/device/cloud/interfaces/IRawDevice.ts +0 -19
  80. package/src/device/cloud/interfaces/index.ts +0 -5
  81. package/src/device/local/interfaces/IDevice.ts +0 -62
  82. package/src/device/local/interfaces/IDtDevice.ts +0 -16
  83. package/src/device/local/interfaces/ISchedule.ts +0 -40
  84. package/src/device/local/interfaces/index.ts +0 -3
  85. package/src/device/local/repository/Device.repository.ts +0 -368
  86. package/src/device/local/repository/Hub.repository.ts +0 -107
  87. package/src/device/local/repository/Schedule.repository.ts +0 -72
  88. package/src/device/local/services/Device.service.ts +0 -436
  89. package/src/device/local/services/Hub.service.ts +0 -57
  90. package/src/device/local/services/Schedule.service.ts +0 -26
  91. package/src/device/local/services/index.ts +0 -3
  92. package/src/docs/Alert.model.md +0 -319
  93. package/src/docs/Alerts&IssuesModel.md +0 -312
  94. package/src/docs/Issue.model.md +0 -386
  95. package/src/docs/SECURITY.md +0 -67
  96. package/src/docs/TROUBLESHOOTING.md +0 -184
  97. package/src/events/BaseEventHandler.ts +0 -145
  98. package/src/events/BaseEventTransformer.ts +0 -97
  99. package/src/events/DeviceEventHandler.ts +0 -213
  100. package/src/events/DeviceEventTransformerFactory.ts +0 -77
  101. package/src/events/EventHandler.ts +0 -124
  102. package/src/events/EventHandlerOrchestrator.ts +0 -119
  103. package/src/events/EventProcessingService.ts +0 -248
  104. package/src/events/InternalEventSubscription.ts +0 -194
  105. package/src/events/index.ts +0 -9
  106. package/src/events/interfaces/DeviceEvent.ts +0 -56
  107. package/src/events/interfaces/IEventHandler.ts +0 -28
  108. package/src/events/interfaces/IEventTransformer.ts +0 -8
  109. package/src/events/interfaces/IInternalEvent.ts +0 -33
  110. package/src/events/interfaces/index.ts +0 -4
  111. package/src/index.ts +0 -43
  112. package/src/issues/Issue.model.ts +0 -350
  113. package/src/issues/Issue.repository.ts +0 -517
  114. package/src/issues/Issue.service.ts +0 -932
  115. package/src/issues/IssueBuilder.example.ts +0 -210
  116. package/src/issues/IssueBuilder.ts +0 -263
  117. package/src/issues/IssueService.example.ts +0 -310
  118. package/src/issues/index.ts +0 -2
  119. package/src/issues/issue.types.ts +0 -98
  120. package/src/property/IProperty.ts +0 -30
  121. package/src/property/Property.repository.ts +0 -53
  122. package/src/property/Property.service.ts +0 -38
  123. package/src/property/index.ts +0 -2
  124. package/src/queue/entities/HybridHttpQueue.ts +0 -274
  125. package/src/queue/entities/index.ts +0 -1
  126. package/src/queue/index.ts +0 -6
  127. package/src/queue/interfaces/IHttpRequestJob.ts +0 -10
  128. package/src/queue/interfaces/IHybridHttpQueue.ts +0 -25
  129. package/src/queue/interfaces/IJobResult.ts +0 -15
  130. package/src/queue/interfaces/IRateLimitConfig.ts +0 -5
  131. package/src/queue/interfaces/index.ts +0 -4
  132. package/src/queue/services/QueueService.ts +0 -40
  133. package/src/queue/services/index.ts +0 -1
  134. package/src/queue/types/http.types.ts +0 -23
  135. package/src/queue/types/index.ts +0 -2
  136. package/src/queue/types/queue.types.ts +0 -21
  137. package/src/queue/utils/index.ts +0 -3
  138. package/src/queue/utils/jobUtils.ts +0 -79
  139. package/src/queue/utils/queueUtils.ts +0 -84
  140. package/src/queue/utils/rateLimit.utils.ts +0 -131
  141. package/src/utils/http.utils.ts +0 -143
  142. package/src/utils/index.ts +0 -2
  143. package/src/utils/redis.utils.ts +0 -74
  144. package/tsconfig.json +0 -20
  145. /package/dist/{device/cloud/interfaces/IDevicesService.js → audit/AuditProperties.js} +0 -0
@@ -1,59 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DeviceCloudService = void 0;
4
- /**
5
- * Device Cloud Service Class
6
- * Implements IDeviceCloudService interface with empty implementations
7
- * Implementation will be provided by the consuming project
8
- */
9
- class DeviceCloudService {
10
- /**
11
- * Creates a new connection for device management
12
- * @param data - Connection data
13
- * @param userId - User identifier
14
- * @returns Promise with connection result
15
- */
16
- async createConnection(data, userId) {
17
- // Implementation will be provided by the consuming project
18
- throw new Error("createConnection method not implemented");
19
- }
20
- /**
21
- * Gets device account information for a connection
22
- * @param connection - Connection object
23
- * @returns Promise with device account response
24
- */
25
- async getDeviceAccount(connection) {
26
- // Implementation will be provided by the consuming project
27
- throw new Error("getDeviceAccount method not implemented");
28
- }
29
- /**
30
- * Gets all devices for a connection
31
- * @param connection - Connection object
32
- * @returns Promise with array of devices
33
- */
34
- async getDevices(connection) {
35
- // Implementation will be provided by the consuming project
36
- throw new Error("getDevices method not implemented");
37
- }
38
- /**
39
- * Filters devices based on connection and device list
40
- * @param connection - Connection object
41
- * @param devices - Array of devices to filter
42
- * @returns Promise with filtered devices
43
- */
44
- async filterDevices(connection, devices) {
45
- // Implementation will be provided by the consuming project
46
- throw new Error("filterDevices method not implemented");
47
- }
48
- /**
49
- * Connects to a device service
50
- * @param connection - Connection object
51
- * @param connectionConnect - Connection parameters
52
- * @returns Promise with connection result
53
- */
54
- async connect(connection, connectionConnect) {
55
- // Implementation will be provided by the consuming project
56
- throw new Error("connect method not implemented");
57
- }
58
- }
59
- exports.DeviceCloudService = DeviceCloudService;
@@ -1,3 +0,0 @@
1
- export declare abstract class DeviceHubService {
2
- abstract getHubs(): Promise<any>;
3
- }
@@ -1,6 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DeviceHubService = void 0;
4
- class DeviceHubService {
5
- }
6
- exports.DeviceHubService = DeviceHubService;
@@ -1,25 +0,0 @@
1
- import { IHubService } from "../interfaces";
2
- import { IConnection, IDevice } from "../types";
3
- export declare abstract class HubService implements IHubService {
4
- deviceId: string;
5
- propertyId: string;
6
- name: string;
7
- deviceType: {
8
- id: string;
9
- type: string;
10
- };
11
- status: {
12
- online: boolean;
13
- error?: {
14
- type?: string;
15
- message?: string;
16
- };
17
- lastUpdated?: string;
18
- };
19
- metaData?: Record<string, any>;
20
- connection: IConnection;
21
- constructor(hub: IDevice);
22
- abstract getHubs(connectionId: string): Promise<any[] | null>;
23
- abstract getHub(connectionId: string, hubId: string): Promise<Record<string, any>>;
24
- abstract getStatus(connectionId: string, hubId: string): Promise<string>;
25
- }
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.HubService = void 0;
4
- class HubService {
5
- constructor(hub) {
6
- Object.assign(this, hub);
7
- }
8
- }
9
- exports.HubService = HubService;
@@ -1,38 +0,0 @@
1
- import { ISmartthingsDeviceCommandManager } from "../interface";
2
- import { IDeviceCommand, ISmartthingsDeviceCommand, ICommandResponse } from "../types";
3
- /**
4
- * SmartThings Device Service Class
5
- * Implements ISmartthingsDeviceCommandManager interface with empty implementations
6
- * Implementation will be provided by the consuming project
7
- */
8
- export declare class SmartThingsDeviceService implements ISmartthingsDeviceCommandManager {
9
- /**
10
- * Invokes a command on a device
11
- * @param command - Device command to execute
12
- * @param deviceId - Device identifier
13
- * @returns Promise with command response
14
- */
15
- invokeCommand(command: IDeviceCommand, deviceId: string): Promise<ICommandResponse>;
16
- /**
17
- * Performs device action for SmartThings
18
- * @param commands - Array of SmartThings device commands
19
- * @param deviceId - Device identifier
20
- * @param accessToken - Access token for authentication
21
- * @returns Promise with action result
22
- */
23
- performDeviceAction(commands: ISmartthingsDeviceCommand[], deviceId: string, accessToken: string): Promise<any>;
24
- /**
25
- * Gets device status for SmartThings
26
- * @param deviceId - Device identifier
27
- * @param accessToken - Access token for authentication
28
- * @returns Promise with device status
29
- */
30
- getDeviceStatus(deviceId: string, accessToken: string): Promise<any>;
31
- /**
32
- * Gets device lock status for SmartThings
33
- * @param deviceId - Device identifier
34
- * @param accessToken - Access token for authentication
35
- * @returns Promise with lock status
36
- */
37
- getDeviceLockStatus(deviceId: string, accessToken: string): Promise<any>;
38
- }
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SmartThingsDeviceService = void 0;
4
- /**
5
- * SmartThings Device Service Class
6
- * Implements ISmartthingsDeviceCommandManager interface with empty implementations
7
- * Implementation will be provided by the consuming project
8
- */
9
- class SmartThingsDeviceService {
10
- /**
11
- * Invokes a command on a device
12
- * @param command - Device command to execute
13
- * @param deviceId - Device identifier
14
- * @returns Promise with command response
15
- */
16
- async invokeCommand(command, deviceId) {
17
- // Implementation will be provided by the consuming project
18
- throw new Error("invokeCommand method not implemented");
19
- }
20
- /**
21
- * Performs device action for SmartThings
22
- * @param commands - Array of SmartThings device commands
23
- * @param deviceId - Device identifier
24
- * @param accessToken - Access token for authentication
25
- * @returns Promise with action result
26
- */
27
- async performDeviceAction(commands, deviceId, accessToken) {
28
- // Implementation will be provided by the consuming project
29
- throw new Error("performDeviceAction method not implemented");
30
- }
31
- /**
32
- * Gets device status for SmartThings
33
- * @param deviceId - Device identifier
34
- * @param accessToken - Access token for authentication
35
- * @returns Promise with device status
36
- */
37
- async getDeviceStatus(deviceId, accessToken) {
38
- // Implementation will be provided by the consuming project
39
- throw new Error("getDeviceStatus method not implemented");
40
- }
41
- /**
42
- * Gets device lock status for SmartThings
43
- * @param deviceId - Device identifier
44
- * @param accessToken - Access token for authentication
45
- * @returns Promise with lock status
46
- */
47
- async getDeviceLockStatus(deviceId, accessToken) {
48
- // Implementation will be provided by the consuming project
49
- throw new Error("getDeviceLockStatus method not implemented");
50
- }
51
- }
52
- exports.SmartThingsDeviceService = SmartThingsDeviceService;
@@ -1,4 +0,0 @@
1
- export * from "./cloud/interface";
2
- export * from "./cloud/types";
3
- export type { IConnection, IConnectionConnectParams, IDevice, IDeviceAccountResponse, } from "./cloud/types";
4
- export type { IDeviceCloudService } from "./cloud/interface";
@@ -1,20 +0,0 @@
1
- "use strict";
2
- // DeviceThread Common Library - Device Module
3
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
- if (k2 === undefined) k2 = k;
5
- var desc = Object.getOwnPropertyDescriptor(m, k);
6
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
- desc = { enumerable: true, get: function() { return m[k]; } };
8
- }
9
- Object.defineProperty(o, k2, desc);
10
- }) : (function(o, m, k, k2) {
11
- if (k2 === undefined) k2 = k;
12
- o[k2] = m[k];
13
- }));
14
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
- };
17
- Object.defineProperty(exports, "__esModule", { value: true });
18
- // Export cloud device interfaces
19
- __exportStar(require("./cloud/interface"), exports);
20
- __exportStar(require("./cloud/types"), exports);
File without changes
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,11 +0,0 @@
1
- import { IHubCreateParams } from "../interfaces";
2
- export declare class DeviceHubService {
3
- private readonly baseUrl;
4
- constructor();
5
- addHub(body: IHubCreateParams): Promise<any>;
6
- getHubs(hubIds: string[]): Promise<any>;
7
- getHub(hubId: string): Promise<any>;
8
- updateHub(hubId: string, body: any): Promise<any>;
9
- deleteHub(hubId: string): Promise<any>;
10
- deleteAllHubs(hubIds: string[]): Promise<any>;
11
- }
@@ -1,40 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.DeviceHubService = void 0;
7
- const axios_1 = __importDefault(require("axios"));
8
- const config_1 = require("../../../config/config");
9
- class DeviceHubService {
10
- constructor() {
11
- const { DEVICE_SERVICE } = (0, config_1.getConfig)();
12
- if (!DEVICE_SERVICE) {
13
- throw new Error("DEVICE_SERVICE is not configured. Call initialize() first with DEVICE_SERVICE.");
14
- }
15
- this.baseUrl = DEVICE_SERVICE;
16
- }
17
- async addHub(body) {
18
- return await axios_1.default.post(`${this.baseUrl}/devices/hubs`, body);
19
- }
20
- //get hubs takes an array of hub ids as query params
21
- async getHubs(hubIds) {
22
- const query = hubIds && hubIds.length ? `?ids=${hubIds.join(",")}` : "";
23
- return await axios_1.default.get(`${this.baseUrl}/devices/hubs${query}`);
24
- }
25
- //get hub takes a hub id in params
26
- async getHub(hubId) {
27
- return await axios_1.default.get(`${this.baseUrl}/devices/hubs/${hubId}`);
28
- }
29
- async updateHub(hubId, body) {
30
- return await axios_1.default.put(`${this.baseUrl}/devices/hubs/${hubId}`, body);
31
- }
32
- async deleteHub(hubId) {
33
- return await axios_1.default.delete(`${this.baseUrl}/devices/hubs/${hubId}`);
34
- }
35
- async deleteAllHubs(hubIds) {
36
- const query = hubIds.length ? `?ids=${hubIds.join(",")}` : "";
37
- return await axios_1.default.delete(`${this.baseUrl}/devices/hubs${query}`);
38
- }
39
- }
40
- exports.DeviceHubService = DeviceHubService;
@@ -1,289 +0,0 @@
1
- import mongoose, { Schema, Model } from "mongoose";
2
- import {
3
- AlertCategory,
4
- AlertSeverity,
5
- EntityType,
6
- AlertDocument as IAlertDocument,
7
- CreateAlertData,
8
- UpdateAlertData,
9
- } from "./alert.types";
10
-
11
- // Interface for instance methods
12
- interface IAlertMethods {
13
- markAsRead(updatedBy: string): void;
14
- markAsUnread(updatedBy: string): void;
15
- activate(updatedBy: string): void;
16
- deactivate(updatedBy: string): void;
17
- snooze(until: Date, updatedBy: string): void;
18
- unsnooze(updatedBy: string): void;
19
- }
20
-
21
- // Interface for static methods
22
- interface IAlertModel extends Model<IAlertDocument, {}, IAlertMethods> {
23
- findByProperty(
24
- propertyId: string,
25
- includeDeleted?: boolean
26
- ): Promise<IAlertDocument[]>;
27
- findByEntity(
28
- entityId: string,
29
- entityType: EntityType,
30
- includeDeleted?: boolean
31
- ): Promise<IAlertDocument[]>;
32
- findByCategory(
33
- category: AlertCategory,
34
- includeDeleted?: boolean
35
- ): Promise<IAlertDocument[]>;
36
- findBySeverity(
37
- severity: AlertSeverity,
38
- includeDeleted?: boolean
39
- ): Promise<IAlertDocument[]>;
40
- findActive(includeDeleted?: boolean): Promise<IAlertDocument[]>;
41
- findUnread(includeDeleted?: boolean): Promise<IAlertDocument[]>;
42
- findSnoozed(includeDeleted?: boolean): Promise<IAlertDocument[]>;
43
- findExpiredSnooze(includeDeleted?: boolean): Promise<IAlertDocument[]>;
44
- }
45
-
46
- // Main Alert schema
47
- const AlertSchema = new Schema<IAlertDocument, IAlertModel, IAlertMethods>(
48
- {
49
- category: {
50
- type: [String],
51
- enum: Object.values(AlertCategory),
52
- required: true,
53
- validate: {
54
- validator: function (categories: string[]) {
55
- return categories && categories.length > 0;
56
- },
57
- message: "At least one category is required",
58
- },
59
- },
60
- propertyId: {
61
- type: String,
62
- required: true,
63
- index: true,
64
- },
65
- title: {
66
- type: String,
67
- required: true,
68
- trim: true,
69
- },
70
- description: {
71
- type: String,
72
- required: true,
73
- trim: true,
74
- },
75
- entityId: {
76
- type: String,
77
- index: true,
78
- },
79
- entityType: {
80
- type: String,
81
- enum: Object.values(EntityType),
82
- required: true,
83
- index: true,
84
- },
85
- severity: {
86
- type: String,
87
- enum: Object.values(AlertSeverity),
88
- default: AlertSeverity.MEDIUM,
89
- },
90
- isRead: {
91
- type: Boolean,
92
- default: false,
93
- index: true,
94
- },
95
- isActive: {
96
- type: Boolean,
97
- default: true,
98
- index: true,
99
- },
100
- isDeleted: {
101
- type: Boolean,
102
- default: false,
103
- },
104
- snoozeUntil: {
105
- type: Date,
106
- },
107
- createdBy: {
108
- type: String,
109
- },
110
- updatedBy: {
111
- type: String,
112
- },
113
- createdAt: {
114
- type: Date,
115
- default: Date.now,
116
- },
117
- updatedAt: {
118
- type: Date,
119
- default: Date.now,
120
- },
121
- },
122
- {
123
- timestamps: true,
124
- collection: "dt_alerts",
125
- }
126
- );
127
-
128
- // Compound indexes to match Prisma schema
129
- AlertSchema.index({ propertyId: 1, isActive: 1, isRead: 1 });
130
- AlertSchema.index({ entityId: 1, entityType: 1 });
131
- AlertSchema.index({ createdAt: 1 });
132
-
133
- // Pre-save middleware to update the updatedAt field
134
- AlertSchema.pre("save", function (next) {
135
- this.updatedAt = new Date();
136
- next();
137
- });
138
-
139
- // Pre-update middleware to update the updatedAt field
140
- AlertSchema.pre(
141
- ["updateOne", "findOneAndUpdate", "updateMany"],
142
- function (next) {
143
- this.set({ updatedAt: new Date() });
144
- next();
145
- }
146
- );
147
-
148
- // Instance methods
149
- AlertSchema.methods.markAsRead = function (updatedBy: string): void {
150
- this.isRead = true;
151
- this.updatedBy = updatedBy;
152
- };
153
-
154
- AlertSchema.methods.markAsUnread = function (updatedBy: string): void {
155
- this.isRead = false;
156
- this.updatedBy = updatedBy;
157
- };
158
-
159
- AlertSchema.methods.activate = function (updatedBy: string): void {
160
- this.isActive = true;
161
- this.updatedBy = updatedBy;
162
- };
163
-
164
- AlertSchema.methods.deactivate = function (updatedBy: string): void {
165
- this.isActive = false;
166
- this.updatedBy = updatedBy;
167
- };
168
-
169
- AlertSchema.methods.snooze = function (until: Date, updatedBy: string): void {
170
- this.snoozeUntil = until;
171
- this.updatedBy = updatedBy;
172
- };
173
-
174
- AlertSchema.methods.unsnooze = function (updatedBy: string): void {
175
- this.snoozeUntil = undefined;
176
- this.updatedBy = updatedBy;
177
- };
178
-
179
- // Static methods
180
- AlertSchema.statics.findByProperty = function (
181
- propertyId: string,
182
- includeDeleted = false
183
- ) {
184
- const query: any = { propertyId };
185
- if (!includeDeleted) {
186
- query.isDeleted = false;
187
- }
188
- return this.find(query).sort({ createdAt: -1 });
189
- };
190
-
191
- AlertSchema.statics.findByEntity = function (
192
- entityId: string,
193
- entityType: EntityType,
194
- includeDeleted = false
195
- ) {
196
- const query: any = { entityId, entityType };
197
- if (!includeDeleted) {
198
- query.isDeleted = false;
199
- }
200
- return this.find(query).sort({ createdAt: -1 });
201
- };
202
-
203
- AlertSchema.statics.findByCategory = function (
204
- category: AlertCategory,
205
- includeDeleted = false
206
- ) {
207
- const query: any = { category: { $in: [category] } };
208
- if (!includeDeleted) {
209
- query.isDeleted = false;
210
- }
211
- return this.find(query).sort({ createdAt: -1 });
212
- };
213
-
214
- AlertSchema.statics.findBySeverity = function (
215
- severity: AlertSeverity,
216
- includeDeleted = false
217
- ) {
218
- const query: any = { severity };
219
- if (!includeDeleted) {
220
- query.isDeleted = false;
221
- }
222
- return this.find(query).sort({ severity: -1, createdAt: -1 });
223
- };
224
-
225
- AlertSchema.statics.findActive = function (includeDeleted = false) {
226
- const query: any = { isActive: true };
227
- if (!includeDeleted) {
228
- query.isDeleted = false;
229
- }
230
- return this.find(query).sort({ severity: -1, createdAt: -1 });
231
- };
232
-
233
- AlertSchema.statics.findUnread = function (includeDeleted = false) {
234
- const query: any = { isRead: false };
235
- if (!includeDeleted) {
236
- query.isDeleted = false;
237
- }
238
- return this.find(query).sort({ severity: -1, createdAt: -1 });
239
- };
240
-
241
- AlertSchema.statics.findSnoozed = function (includeDeleted = false) {
242
- const query: any = { snoozeUntil: { $exists: true, $ne: null } };
243
- if (!includeDeleted) {
244
- query.isDeleted = false;
245
- }
246
- return this.find(query).sort({ snoozeUntil: 1 });
247
- };
248
-
249
- AlertSchema.statics.findExpiredSnooze = function (includeDeleted = false) {
250
- const query: any = {
251
- snoozeUntil: { $lt: new Date() },
252
- isActive: true,
253
- };
254
- if (!includeDeleted) {
255
- query.isDeleted = false;
256
- }
257
- return this.find(query).sort({ snoozeUntil: 1 });
258
- };
259
-
260
- // Virtual for snooze status
261
- AlertSchema.virtual("isSnoozed").get(function () {
262
- return this.snoozeUntil && this.snoozeUntil > new Date();
263
- });
264
-
265
- AlertSchema.virtual("isSnoozeExpired").get(function () {
266
- return this.snoozeUntil && this.snoozeUntil <= new Date();
267
- });
268
-
269
- // Ensure virtuals are serialized
270
- AlertSchema.set("toJSON", { virtuals: true });
271
- AlertSchema.set("toObject", { virtuals: true });
272
-
273
- // Create and export the model
274
- export const AlertModel = mongoose.model<IAlertDocument, IAlertModel>(
275
- "Alert",
276
- AlertSchema
277
- );
278
-
279
- // Export the schema for potential reuse
280
- export { AlertSchema };
281
-
282
- // Export types for external use
283
- export type {
284
- IAlertDocument,
285
- CreateAlertData,
286
- UpdateAlertData,
287
- IAlertMethods,
288
- IAlertModel,
289
- };