dt-common-device 4.0.11 → 5.0.2

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 (196) hide show
  1. package/dist/alerts/Alert.service.d.ts +1 -1
  2. package/dist/audit/AuditUtils.d.ts +26 -2
  3. package/dist/audit/AuditUtils.js +255 -32
  4. package/dist/audit/IAuditProperties.d.ts +5 -1
  5. package/dist/audit/IAuditProperties.js +2 -0
  6. package/dist/config/config.d.ts +10 -3
  7. package/dist/config/config.js +120 -47
  8. package/dist/config/config.types.d.ts +1 -8
  9. package/dist/db/db.d.ts +2 -0
  10. package/dist/db/db.js +23 -1
  11. package/dist/events/BaseEventHandler.d.ts +3 -3
  12. package/dist/events/BaseEventHandler.js +1 -1
  13. package/dist/events/DeviceEventHandler.d.ts +1 -1
  14. package/dist/events/DeviceEventHandler.js +6 -3
  15. package/dist/events/EventHandler.d.ts +10 -9
  16. package/dist/events/EventHandler.js +50 -9
  17. package/dist/events/InternalEventSubscription.js +1 -1
  18. package/dist/index.d.ts +9 -8
  19. package/dist/index.js +10 -8
  20. package/dist/issues/Issue.service.d.ts +1 -1
  21. package/dist/microservice/MicroServiceFactory.d.ts +1 -1
  22. package/dist/microservice/MicroServiceFactory.js +1 -1
  23. package/dist/queue/utils/rateLimit.utils.js +1 -1
  24. package/dist/utils/http.utils.d.ts +1 -2
  25. package/dist/utils/http.utils.js +5 -28
  26. package/package.json +1 -1
  27. package/dist/admin/Admin.repository.d.ts +0 -7
  28. package/dist/admin/Admin.repository.js +0 -182
  29. package/dist/admin/Admin.service.d.ts +0 -5
  30. package/dist/admin/Admin.service.js +0 -17
  31. package/dist/admin/index.d.ts +0 -1
  32. package/dist/admin/index.js +0 -17
  33. package/dist/audit/AuditProperties.d.ts +0 -16
  34. package/dist/audit/AuditProperties.js +0 -2
  35. package/dist/connection/Connection.repository.d.ts +0 -8
  36. package/dist/connection/Connection.repository.js +0 -92
  37. package/dist/connection/Connection.service.d.ts +0 -8
  38. package/dist/connection/Connection.service.js +0 -32
  39. package/dist/connection/IConnection.d.ts +0 -28
  40. package/dist/connection/IConnection.js +0 -16
  41. package/dist/connection/index.d.ts +0 -2
  42. package/dist/connection/index.js +0 -18
  43. package/dist/device/cloud/entities/CloudConnection.d.ts +0 -6
  44. package/dist/device/cloud/entities/CloudConnection.js +0 -6
  45. package/dist/device/cloud/entities/CloudDevice.d.ts +0 -16
  46. package/dist/device/cloud/entities/CloudDevice.js +0 -26
  47. package/dist/device/cloud/entities/CloudDeviceService.d.ts +0 -5
  48. package/dist/device/cloud/entities/CloudDeviceService.js +0 -9
  49. package/dist/device/cloud/entities/DeviceFactory.d.ts +0 -7
  50. package/dist/device/cloud/entities/DeviceFactory.js +0 -80
  51. package/dist/device/cloud/entities/index.d.ts +0 -3
  52. package/dist/device/cloud/entities/index.js +0 -19
  53. package/dist/device/cloud/interface.d.ts +0 -101
  54. package/dist/device/cloud/interface.js +0 -3
  55. package/dist/device/cloud/interfaces/ICloudConnection.d.ts +0 -5
  56. package/dist/device/cloud/interfaces/ICloudConnection.js +0 -2
  57. package/dist/device/cloud/interfaces/ICloudDevice.d.ts +0 -9
  58. package/dist/device/cloud/interfaces/ICloudDevice.js +0 -2
  59. package/dist/device/cloud/interfaces/ICloudDeviceService.d.ts +0 -4
  60. package/dist/device/cloud/interfaces/ICloudDeviceService.js +0 -2
  61. package/dist/device/cloud/interfaces/IConnectionService.d.ts +0 -7
  62. package/dist/device/cloud/interfaces/IConnectionService.js +0 -2
  63. package/dist/device/cloud/interfaces/IDeviceConnectionService.d.ts +0 -7
  64. package/dist/device/cloud/interfaces/IDeviceConnectionService.js +0 -3
  65. package/dist/device/cloud/interfaces/IDeviceFactory.d.ts +0 -4
  66. package/dist/device/cloud/interfaces/IDeviceFactory.js +0 -2
  67. package/dist/device/cloud/interfaces/IDeviceService.d.ts +0 -8
  68. package/dist/device/cloud/interfaces/IDeviceService.js +0 -2
  69. package/dist/device/cloud/interfaces/IDevicesService.d.ts +0 -9
  70. package/dist/device/cloud/interfaces/IDevicesService.js +0 -2
  71. package/dist/device/cloud/interfaces/IHubService.d.ts +0 -5
  72. package/dist/device/cloud/interfaces/IHubService.js +0 -2
  73. package/dist/device/cloud/interfaces/IRawDataTransformer.d.ts +0 -4
  74. package/dist/device/cloud/interfaces/IRawDataTransformer.js +0 -2
  75. package/dist/device/cloud/interfaces/IRawDevice.d.ts +0 -17
  76. package/dist/device/cloud/interfaces/IRawDevice.js +0 -11
  77. package/dist/device/cloud/interfaces/index.d.ts +0 -5
  78. package/dist/device/cloud/interfaces/index.js +0 -21
  79. package/dist/device/cloud/services/CloudDevice.service.d.ts +0 -5
  80. package/dist/device/cloud/services/CloudDevice.service.js +0 -9
  81. package/dist/device/cloud/services/Connection.service.d.ts +0 -8
  82. package/dist/device/cloud/services/Connection.service.js +0 -6
  83. package/dist/device/cloud/services/Device.service.d.ts +0 -39
  84. package/dist/device/cloud/services/Device.service.js +0 -9
  85. package/dist/device/cloud/services/DeviceCloudService.d.ts +0 -42
  86. package/dist/device/cloud/services/DeviceCloudService.js +0 -59
  87. package/dist/device/cloud/services/DeviceHub.service.d.ts +0 -3
  88. package/dist/device/cloud/services/DeviceHub.service.js +0 -6
  89. package/dist/device/cloud/services/Hub.service.d.ts +0 -25
  90. package/dist/device/cloud/services/Hub.service.js +0 -9
  91. package/dist/device/cloud/services/SmartThingsDeviceService.d.ts +0 -38
  92. package/dist/device/cloud/services/SmartThingsDeviceService.js +0 -52
  93. package/dist/device/cloud/services/index.d.ts +0 -2
  94. package/dist/device/cloud/services/index.js +0 -18
  95. package/dist/device/cloud/types.d.ts +0 -52
  96. package/dist/device/cloud/types.js +0 -15
  97. package/dist/device/index.d.ts +0 -4
  98. package/dist/device/index.js +0 -20
  99. package/dist/device/local/entities/AlertBuilder.d.ts +0 -87
  100. package/dist/device/local/entities/AlertBuilder.example.d.ts +0 -11
  101. package/dist/device/local/entities/AlertBuilder.example.js +0 -117
  102. package/dist/device/local/entities/AlertBuilder.js +0 -179
  103. package/dist/device/local/entities/IssueBuilder.d.ts +0 -109
  104. package/dist/device/local/entities/IssueBuilder.example.d.ts +0 -16
  105. package/dist/device/local/entities/IssueBuilder.example.js +0 -196
  106. package/dist/device/local/entities/IssueBuilder.js +0 -237
  107. package/dist/device/local/entities/index.d.ts +0 -2
  108. package/dist/device/local/entities/index.js +0 -7
  109. package/dist/device/local/events/EventHandler.d.ts +0 -11
  110. package/dist/device/local/events/EventHandler.js +0 -86
  111. package/dist/device/local/events/Events.d.ts +0 -54
  112. package/dist/device/local/events/Events.js +0 -57
  113. package/dist/device/local/events/index.d.ts +0 -2
  114. package/dist/device/local/events/index.js +0 -7
  115. package/dist/device/local/handler/EventHandler.d.ts +0 -7
  116. package/dist/device/local/handler/EventHandler.js +0 -44
  117. package/dist/device/local/interface.d.ts +0 -0
  118. package/dist/device/local/interface.js +0 -1
  119. package/dist/device/local/interfaces/IConnection.d.ts +0 -26
  120. package/dist/device/local/interfaces/IConnection.js +0 -14
  121. package/dist/device/local/interfaces/IDevice.d.ts +0 -68
  122. package/dist/device/local/interfaces/IDevice.js +0 -10
  123. package/dist/device/local/interfaces/IDtDevice.d.ts +0 -16
  124. package/dist/device/local/interfaces/IDtDevice.js +0 -2
  125. package/dist/device/local/interfaces/IHub.d.ts +0 -46
  126. package/dist/device/local/interfaces/IHub.js +0 -2
  127. package/dist/device/local/interfaces/IProperty.d.ts +0 -29
  128. package/dist/device/local/interfaces/IProperty.js +0 -2
  129. package/dist/device/local/interfaces/ISchedule.d.ts +0 -25
  130. package/dist/device/local/interfaces/ISchedule.js +0 -2
  131. package/dist/device/local/interfaces/index.d.ts +0 -3
  132. package/dist/device/local/interfaces/index.js +0 -19
  133. package/dist/device/local/models/Alert.model.d.ts +0 -28
  134. package/dist/device/local/models/Alert.model.js +0 -222
  135. package/dist/device/local/models/Issue.model.d.ts +0 -28
  136. package/dist/device/local/models/Issue.model.js +0 -260
  137. package/dist/device/local/repository/Alert.repository.d.ts +0 -106
  138. package/dist/device/local/repository/Alert.repository.js +0 -374
  139. package/dist/device/local/repository/Connection.repository.d.ts +0 -8
  140. package/dist/device/local/repository/Connection.repository.js +0 -92
  141. package/dist/device/local/repository/Device.repository.d.ts +0 -30
  142. package/dist/device/local/repository/Device.repository.js +0 -325
  143. package/dist/device/local/repository/Hub.repository.d.ts +0 -13
  144. package/dist/device/local/repository/Hub.repository.js +0 -139
  145. package/dist/device/local/repository/Issue.repository.d.ts +0 -113
  146. package/dist/device/local/repository/Issue.repository.js +0 -401
  147. package/dist/device/local/repository/Property.repository.d.ts +0 -8
  148. package/dist/device/local/repository/Property.repository.js +0 -95
  149. package/dist/device/local/repository/Schedule.repository.d.ts +0 -9
  150. package/dist/device/local/repository/Schedule.repository.js +0 -109
  151. package/dist/device/local/services/Alert.service.d.ts +0 -137
  152. package/dist/device/local/services/Alert.service.js +0 -475
  153. package/dist/device/local/services/AlertService.example.d.ts +0 -55
  154. package/dist/device/local/services/AlertService.example.js +0 -148
  155. package/dist/device/local/services/Connection.service.d.ts +0 -8
  156. package/dist/device/local/services/Connection.service.js +0 -32
  157. package/dist/device/local/services/Device.service.d.ts +0 -40
  158. package/dist/device/local/services/Device.service.js +0 -391
  159. package/dist/device/local/services/DeviceHub.service.d.ts +0 -11
  160. package/dist/device/local/services/DeviceHub.service.js +0 -40
  161. package/dist/device/local/services/Hub.service.d.ts +0 -12
  162. package/dist/device/local/services/Hub.service.js +0 -107
  163. package/dist/device/local/services/Issue.service.d.ts +0 -168
  164. package/dist/device/local/services/Issue.service.js +0 -642
  165. package/dist/device/local/services/IssueService.example.d.ts +0 -68
  166. package/dist/device/local/services/IssueService.example.js +0 -177
  167. package/dist/device/local/services/Property.service.d.ts +0 -8
  168. package/dist/device/local/services/Property.service.js +0 -36
  169. package/dist/device/local/services/Schedule.service.d.ts +0 -9
  170. package/dist/device/local/services/Schedule.service.js +0 -26
  171. package/dist/device/local/services/index.d.ts +0 -3
  172. package/dist/device/local/services/index.js +0 -19
  173. package/dist/pms/IPms.d.ts +0 -6
  174. package/dist/pms/IPms.js +0 -10
  175. package/dist/pms/index.d.ts +0 -1
  176. package/dist/pms/index.js +0 -17
  177. package/dist/property/IProperty.d.ts +0 -29
  178. package/dist/property/IProperty.js +0 -2
  179. package/dist/property/Property.repository.d.ts +0 -8
  180. package/dist/property/Property.repository.js +0 -109
  181. package/dist/property/Property.service.d.ts +0 -8
  182. package/dist/property/Property.service.js +0 -124
  183. package/dist/property/index.d.ts +0 -2
  184. package/dist/property/index.js +0 -18
  185. package/dist/queue/interfaces/IHttpRequestJob.d.ts +0 -9
  186. package/dist/queue/interfaces/IHttpRequestJob.js +0 -2
  187. package/dist/types/alert.types.d.ts +0 -57
  188. package/dist/types/alert.types.js +0 -22
  189. package/dist/types/config.types.d.ts +0 -19
  190. package/dist/types/config.types.js +0 -2
  191. package/dist/types/index.d.ts +0 -3
  192. package/dist/types/index.js +0 -19
  193. package/dist/types/issue.types.d.ts +0 -90
  194. package/dist/types/issue.types.js +0 -40
  195. package/dist/utils/http-utils.d.ts +0 -13
  196. package/dist/utils/http-utils.js +0 -117
@@ -3,7 +3,7 @@ import { IAlertDocument } from "./Alert.model";
3
3
  import { CreateAlertData, UpdateAlertData, AlertCategory, AlertSeverity, EntityType } from "./alert.types";
4
4
  import { Source } from "../constants/Service";
5
5
  import { AlertBuilder } from "./AlertBuilder";
6
- import { IDevice } from "../device/local/interfaces";
6
+ import { IDevice } from "../entities/device/local/interfaces";
7
7
  export declare class AlertService {
8
8
  private readonly alertRepository;
9
9
  constructor(alertRepository: AlertRepository);
@@ -1,2 +1,26 @@
1
- import { AuditProperties } from "./AuditProperties";
2
- export declare function buildAuditProperties(input: AuditProperties): Record<string, any>;
1
+ import { IAuditProperties } from "./IAuditProperties";
2
+ export declare class AuditUtils {
3
+ private readonly redisUtils;
4
+ private readonly CACHE_TTL;
5
+ private readonly CACHE_PREFIX;
6
+ constructor();
7
+ private readonly AUDIT_FIELDS;
8
+ buildAuditProperties(input: IAuditProperties): Promise<IAuditProperties>;
9
+ private populateAuditFields;
10
+ /**
11
+ * Generic utility to get cached entity data from Redis using individual keys
12
+ */
13
+ private getCachedEntityData;
14
+ /**
15
+ * Utility to calculate schedule duration in days
16
+ */
17
+ private calculateScheduleDuration;
18
+ private getPropertyName;
19
+ private getPropertyIdFromDevice;
20
+ private getUserName;
21
+ private getGuestName;
22
+ private getDeviceName;
23
+ private getZoneName;
24
+ private getAccessGroupName;
25
+ private getScheduleDetails;
26
+ }
@@ -1,36 +1,259 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildAuditProperties = buildAuditProperties;
4
- const AUDIT_FIELDS = [
5
- "resource",
6
- "propertyId",
7
- "propertyName",
8
- "userId",
9
- "userName",
10
- "deviceId",
11
- "deviceName",
12
- "zoneId",
13
- "zoneName",
14
- "accessGroupId",
15
- "accessGroupName",
16
- "scheduleId",
17
- "scheduleName",
18
- ];
19
- function buildAuditProperties(input) {
20
- // Normalize keys to camelCase for matching
21
- const normalized = { ...input };
22
- // Build the audit object with all standard fields
23
- const audit = {};
24
- for (const field of AUDIT_FIELDS) {
25
- // Try to find a matching key in input (case-insensitive)
26
- const foundKey = Object.keys(normalized).find((k) => k.toLowerCase() === field.toLowerCase());
27
- audit[field] = foundKey ? normalized[foundKey] : undefined;
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
28
7
  }
29
- // Merge in all other event-specific data (but don't overwrite audit fields)
30
- for (const key of Object.keys(normalized)) {
31
- if (!audit.hasOwnProperty(key)) {
32
- audit[key] = normalized[key];
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
19
+ function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
20
+ var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
21
+ var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
22
+ var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
23
+ var _, done = false;
24
+ for (var i = decorators.length - 1; i >= 0; i--) {
25
+ var context = {};
26
+ for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
27
+ for (var p in contextIn.access) context.access[p] = contextIn.access[p];
28
+ context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
29
+ var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
30
+ if (kind === "accessor") {
31
+ if (result === void 0) continue;
32
+ if (result === null || typeof result !== "object") throw new TypeError("Object expected");
33
+ if (_ = accept(result.get)) descriptor.get = _;
34
+ if (_ = accept(result.set)) descriptor.set = _;
35
+ if (_ = accept(result.init)) initializers.unshift(_);
36
+ }
37
+ else if (_ = accept(result)) {
38
+ if (kind === "field") initializers.unshift(_);
39
+ else descriptor[key] = _;
33
40
  }
34
41
  }
35
- return audit;
36
- }
42
+ if (target) Object.defineProperty(target, contextIn.name, descriptor);
43
+ done = true;
44
+ };
45
+ var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
46
+ var useValue = arguments.length > 2;
47
+ for (var i = 0; i < initializers.length; i++) {
48
+ value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
49
+ }
50
+ return useValue ? value : void 0;
51
+ };
52
+ var __importStar = (this && this.__importStar) || (function () {
53
+ var ownKeys = function(o) {
54
+ ownKeys = Object.getOwnPropertyNames || function (o) {
55
+ var ar = [];
56
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
57
+ return ar;
58
+ };
59
+ return ownKeys(o);
60
+ };
61
+ return function (mod) {
62
+ if (mod && mod.__esModule) return mod;
63
+ var result = {};
64
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
65
+ __setModuleDefault(result, mod);
66
+ return result;
67
+ };
68
+ })();
69
+ var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
70
+ if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
71
+ return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
72
+ };
73
+ Object.defineProperty(exports, "__esModule", { value: true });
74
+ exports.AuditUtils = void 0;
75
+ const property_1 = require("../entities/property");
76
+ const redis_utils_1 = require("../utils/redis.utils");
77
+ const User_service_1 = require("../entities/user/User.service");
78
+ const services_1 = require("../entities/device/local/services");
79
+ const accessGroup_1 = require("../entities/accessGroup");
80
+ const zone_1 = require("../entities/zone");
81
+ const schedules_1 = require("../entities/schedules");
82
+ const guest_1 = require("../entities/guest");
83
+ const typedi_1 = __importStar(require("typedi"));
84
+ let AuditUtils = (() => {
85
+ let _classDecorators = [(0, typedi_1.Service)()];
86
+ let _classDescriptor;
87
+ let _classExtraInitializers = [];
88
+ let _classThis;
89
+ var AuditUtils = _classThis = class {
90
+ constructor() {
91
+ this.CACHE_TTL = 24 * 60 * 60; // 24 hours in seconds
92
+ this.CACHE_PREFIX = "audit:entity";
93
+ this.AUDIT_FIELDS = [
94
+ "resource",
95
+ "propertyId",
96
+ "propertyName",
97
+ "userId",
98
+ "userName",
99
+ "guestId",
100
+ "guestName",
101
+ "deviceId",
102
+ "deviceName",
103
+ "zoneId",
104
+ "zoneName",
105
+ "accessGroupId",
106
+ "accessGroupName",
107
+ "scheduleId",
108
+ "scheduleStartDate",
109
+ "scheduleEndDate",
110
+ "scheduleDuration",
111
+ "scheduleSource",
112
+ "scheduleStatus",
113
+ "eventData",
114
+ ];
115
+ this.redisUtils = new redis_utils_1.RedisUtils();
116
+ }
117
+ async buildAuditProperties(input) {
118
+ // Normalize keys to camelCase for matching
119
+ const normalized = { ...input };
120
+ // Build the audit object with all standard fields
121
+ const audit = {};
122
+ for (const field of this.AUDIT_FIELDS) {
123
+ // Try to find a matching key in input (case-insensitive)
124
+ const foundKey = Object.keys(normalized).find((k) => k.toLowerCase() === field.toLowerCase());
125
+ audit[field] = foundKey ? normalized[foundKey] : undefined;
126
+ }
127
+ // Merge in all other event-specific data (but don't overwrite audit fields)
128
+ for (const key of Object.keys(normalized)) {
129
+ if (!audit.hasOwnProperty(key)) {
130
+ audit[key] = normalized[key];
131
+ }
132
+ }
133
+ // Util Function that will take all id Fields and get related information from database and add to audit
134
+ await this.populateAuditFields(audit);
135
+ return audit;
136
+ }
137
+ async populateAuditFields(audit) {
138
+ const { propertyId, propertyName, userId, userName, guestId, guestName, deviceId, deviceName, zoneId, zoneName, accessGroupId, accessGroupName, scheduleId, } = audit;
139
+ if (propertyId && !propertyName)
140
+ audit.propertyName = await this.getPropertyName(propertyId);
141
+ if (!propertyId && deviceId) {
142
+ audit.propertyId = await this.getPropertyIdFromDevice(deviceId);
143
+ audit.propertyName = await this.getPropertyName(audit.propertyId);
144
+ }
145
+ if (userId && !userName)
146
+ audit.userName = await this.getUserName(userId);
147
+ if (guestId && !guestName)
148
+ audit.guestName = await this.getGuestName(guestId);
149
+ if (deviceId && !deviceName)
150
+ audit.deviceName = await this.getDeviceName(deviceId);
151
+ if (zoneId && !zoneName)
152
+ audit.zoneName = await this.getZoneName(zoneId);
153
+ if (accessGroupId && !accessGroupName)
154
+ audit.accessGroupName = await this.getAccessGroupName(accessGroupId);
155
+ if (scheduleId) {
156
+ const { scheduleStartDate, scheduleEndDate, scheduleDuration, scheduleSource, scheduleStatus, } = await this.getScheduleDetails(scheduleId);
157
+ audit.scheduleStartDate = scheduleStartDate;
158
+ audit.scheduleEndDate = scheduleEndDate;
159
+ audit.scheduleDuration = scheduleDuration;
160
+ audit.scheduleSource = scheduleSource;
161
+ audit.scheduleStatus = scheduleStatus;
162
+ }
163
+ }
164
+ /**
165
+ * Generic utility to get cached entity data from Redis using individual keys
166
+ */
167
+ async getCachedEntityData(entityType, entityId, fetchFunction) {
168
+ const cacheKey = `${this.CACHE_PREFIX}:${entityType}:${entityId}`;
169
+ // Try to get from cache first
170
+ const cachedData = await this.redisUtils.get(cacheKey);
171
+ if (cachedData) {
172
+ return JSON.parse(cachedData);
173
+ }
174
+ // If not in cache, fetch from database and cache it
175
+ const entityData = await fetchFunction();
176
+ await this.redisUtils.set(cacheKey, JSON.stringify(entityData), this.CACHE_TTL);
177
+ return entityData;
178
+ }
179
+ /**
180
+ * Utility to calculate schedule duration in days
181
+ */
182
+ calculateScheduleDuration(startTime, endTime) {
183
+ const duration = new Date(endTime).getTime() - new Date(startTime).getTime();
184
+ return Math.ceil(duration / (1000 * 60 * 60 * 24));
185
+ }
186
+ async getPropertyName(propertyId) {
187
+ return this.getCachedEntityData("property", propertyId, async () => {
188
+ const property = await typedi_1.default.get(property_1.LocalPropertyService).getProperty(propertyId);
189
+ return property?.name || "";
190
+ });
191
+ }
192
+ async getPropertyIdFromDevice(deviceId) {
193
+ const redisKey = `device:${deviceId}`;
194
+ const redisDevice = await this.redisUtils.hget(redisKey, "device");
195
+ if (redisDevice) {
196
+ return JSON.parse(redisDevice).propertyId;
197
+ }
198
+ else {
199
+ const device = await typedi_1.default.get(services_1.LocalDeviceService).getDevice(deviceId);
200
+ await this.redisUtils.hset(redisKey, "device", JSON.stringify(device));
201
+ await this.redisUtils.expire(redisKey, this.CACHE_TTL);
202
+ return device.propertyId;
203
+ }
204
+ }
205
+ async getUserName(userId) {
206
+ return this.getCachedEntityData("user", userId, async () => {
207
+ const user = await typedi_1.default.get(User_service_1.UserService).getUser(userId);
208
+ return `${user?.firstName || ""} ${user?.lastName || ""}`.trim();
209
+ });
210
+ }
211
+ async getGuestName(guestId) {
212
+ return this.getCachedEntityData("guest", guestId, async () => {
213
+ const guest = await typedi_1.default.get(guest_1.GuestService).getGuest(guestId);
214
+ return `${guest?.firstName || ""} ${guest?.lastName || ""}`.trim();
215
+ });
216
+ }
217
+ async getDeviceName(deviceId) {
218
+ return this.getCachedEntityData("device", deviceId, async () => {
219
+ const device = await typedi_1.default.get(services_1.LocalDeviceService).querySelect({ deviceId }, ["name"]);
220
+ return device?.name || "";
221
+ });
222
+ }
223
+ async getZoneName(zoneId) {
224
+ return this.getCachedEntityData("zone", zoneId, async () => {
225
+ const zone = await typedi_1.default.get(zone_1.ZoneService).getZone(zoneId);
226
+ return zone?.name || "";
227
+ });
228
+ }
229
+ async getAccessGroupName(accessGroupId) {
230
+ return this.getCachedEntityData("accessGroup", accessGroupId, async () => {
231
+ const accessGroup = await typedi_1.default.get(accessGroup_1.AccessGroupService).getAccessGroup(accessGroupId);
232
+ return accessGroup?.name || "";
233
+ });
234
+ }
235
+ async getScheduleDetails(scheduleId) {
236
+ return this.getCachedEntityData("schedule", scheduleId, async () => {
237
+ const schedule = await typedi_1.default.get(schedules_1.ScheduleService).getSchedule(scheduleId);
238
+ const scheduleDuration = this.calculateScheduleDuration(schedule.startTime, schedule.endTime);
239
+ return {
240
+ scheduleStartDate: schedule.startTime,
241
+ scheduleEndDate: schedule.endTime,
242
+ scheduleDuration,
243
+ scheduleSource: schedule.source,
244
+ scheduleStatus: schedule.status,
245
+ };
246
+ });
247
+ }
248
+ };
249
+ __setFunctionName(_classThis, "AuditUtils");
250
+ (() => {
251
+ const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
252
+ __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
253
+ AuditUtils = _classThis = _classDescriptor.value;
254
+ if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
255
+ __runInitializers(_classThis, _classExtraInitializers);
256
+ })();
257
+ return AuditUtils = _classThis;
258
+ })();
259
+ exports.AuditUtils = AuditUtils;
@@ -1,14 +1,18 @@
1
+ import { Source } from "../constants";
1
2
  export declare enum Resource {
2
3
  ORGANIZATION = "organization",
3
4
  PROPERTY = "property",
5
+ CONNECTION = "connection",
4
6
  ACCESS_GROUP = "accessGroup",
5
7
  ZONE = "zone",
6
8
  DEVICE = "device",
7
9
  SCHEDULE = "schedule",
8
- USER = "user"
10
+ USER = "user",
11
+ GUEST = "guest"
9
12
  }
10
13
  export interface IAuditProperties {
11
14
  resource: Resource;
15
+ source: Source;
12
16
  propertyId: string;
13
17
  propertyName?: string;
14
18
  userId?: string;
@@ -5,9 +5,11 @@ var Resource;
5
5
  (function (Resource) {
6
6
  Resource["ORGANIZATION"] = "organization";
7
7
  Resource["PROPERTY"] = "property";
8
+ Resource["CONNECTION"] = "connection";
8
9
  Resource["ACCESS_GROUP"] = "accessGroup";
9
10
  Resource["ZONE"] = "zone";
10
11
  Resource["DEVICE"] = "device";
11
12
  Resource["SCHEDULE"] = "schedule";
12
13
  Resource["USER"] = "user";
14
+ Resource["GUEST"] = "guest";
13
15
  })(Resource || (exports.Resource = Resource = {}));
@@ -1,16 +1,23 @@
1
1
  import { InternalEventSubscription } from "../events";
2
- import { IConfig } from "./config.types";
2
+ import { IConfig, ILogger } from "./config.types";
3
3
  export declare function initialize(cfg: IConfig): Promise<void>;
4
4
  export declare function getConfig(): IConfig;
5
+ export declare function getDeviceServiceUrl(): string;
6
+ export declare function getAdminServiceUrl(): string;
7
+ export declare function getSqsQueueUrl(): string;
5
8
  export declare function getEventSubscription(): InternalEventSubscription | null;
6
- export declare function checkRequiredEnv(): void;
9
+ export declare function checkRequiredEnv(requiredEnvs: string[]): void;
7
10
  export declare function ensureAuditInitialized(): void;
11
+ export declare function getLogger(): ILogger;
8
12
  /**
9
13
  * Returns the PostgreSQL DB URI from environment variables.
10
14
  * Throws an error if not set.
11
15
  */
12
- export declare function getPostgresDbUri(): string;
16
+ export declare function getAdminPostgresDbUri(): string;
17
+ export declare function getAccessPostgresDbUri(): string;
18
+ export declare function getPmsPostgresDbUri(): string;
13
19
  export declare function getMongoUri(): string;
20
+ export declare function getDTApiKey(): string;
14
21
  /**
15
22
  * Returns the Redis DB Host and port from environment variables.
16
23
  * Throws an error if not set.
@@ -5,50 +5,50 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.initialize = initialize;
7
7
  exports.getConfig = getConfig;
8
+ exports.getDeviceServiceUrl = getDeviceServiceUrl;
9
+ exports.getAdminServiceUrl = getAdminServiceUrl;
10
+ exports.getSqsQueueUrl = getSqsQueueUrl;
8
11
  exports.getEventSubscription = getEventSubscription;
9
12
  exports.checkRequiredEnv = checkRequiredEnv;
10
13
  exports.ensureAuditInitialized = ensureAuditInitialized;
11
- exports.getPostgresDbUri = getPostgresDbUri;
14
+ exports.getLogger = getLogger;
15
+ exports.getAdminPostgresDbUri = getAdminPostgresDbUri;
16
+ exports.getAccessPostgresDbUri = getAccessPostgresDbUri;
17
+ exports.getPmsPostgresDbUri = getPmsPostgresDbUri;
12
18
  exports.getMongoUri = getMongoUri;
19
+ exports.getDTApiKey = getDTApiKey;
13
20
  exports.getRedisDbHostAndPort = getRedisDbHostAndPort;
14
21
  exports.shutdown = shutdown;
15
22
  const dt_audit_library_1 = require("dt-audit-library");
16
23
  const db_1 = require("../db/db");
17
24
  const dotenv_1 = __importDefault(require("dotenv"));
18
25
  const events_1 = require("../events");
19
- const http_utils_1 = require("../utils/http.utils");
26
+ const constants_1 = require("./constants");
20
27
  dotenv_1.default.config();
21
28
  let config = null;
22
29
  let auditInitialized = false;
23
30
  let eventSubscription = null;
31
+ let db_keys = null;
24
32
  async function initialize(cfg) {
33
+ // Check if required env variables are set
34
+ checkRequiredEnv(constants_1.CONFIG_KEYS.REQUIRED.envs);
25
35
  // Initialize config
26
36
  config = { ...cfg };
27
- // Validate service URLs if provided
28
- if (cfg.DEVICE_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.DEVICE_SERVICE)) {
29
- throw new Error(`Invalid DEVICE_SERVICE URL: ${cfg.DEVICE_SERVICE}`);
30
- }
31
- if (cfg.ADMIN_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ADMIN_SERVICE)) {
32
- throw new Error(`Invalid ADMIN_SERVICE URL: ${cfg.ADMIN_SERVICE}`);
37
+ if (cfg.SOURCE === "ACCESS_SERVICE") {
38
+ db_keys = constants_1.CONFIG_KEYS.ACCESS.db_keys;
39
+ await validateAccessConfig(cfg);
33
40
  }
34
- if (cfg.ACCESS_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ACCESS_SERVICE)) {
35
- throw new Error(`Invalid ACCESS_SERVICE URL: ${cfg.ACCESS_SERVICE}`);
41
+ if (cfg.SOURCE === "SCHEDULE_SERVICE") {
42
+ db_keys = constants_1.CONFIG_KEYS.SCHEDULE.db_keys;
43
+ await validateScheduleConfig(cfg);
36
44
  }
37
- if (cfg.ENERGY_SERVICE && !(0, http_utils_1.validateServiceUrl)(cfg.ENERGY_SERVICE)) {
38
- throw new Error(`Invalid ENERGY_SERVICE URL: ${cfg.ENERGY_SERVICE}`);
45
+ if (cfg.SOURCE === "ENERGY_SERVICE") {
46
+ db_keys = constants_1.CONFIG_KEYS.ENERGY.db_keys;
47
+ await validateEnergyConfig(cfg);
39
48
  }
40
- // Initialize internal event subscription if handler is provided
41
- if (cfg.INTERNAL_EVENT_HANDLER) {
42
- try {
43
- eventSubscription = new events_1.InternalEventSubscription(cfg.INTERNAL_EVENT_HANDLER);
44
- cfg.LOGGER.info("InternalEventSubscription initialized successfully");
45
- }
46
- catch (error) {
47
- cfg.LOGGER.error("Failed to initialize InternalEventSubscription", {
48
- error,
49
- });
50
- throw error;
51
- }
49
+ if (cfg.SOURCE === "REMOTE_SERVICE") {
50
+ db_keys = constants_1.CONFIG_KEYS.REMOTE.db_keys;
51
+ await validateRemoteConfig(cfg);
52
52
  }
53
53
  // Connect to databases
54
54
  try {
@@ -70,37 +70,86 @@ async function initialize(cfg) {
70
70
  // Don't throw here as the main setup should continue
71
71
  }
72
72
  }
73
- // Check if required env variables are set
74
- checkRequiredEnv();
75
73
  // Initialize audit
76
74
  ensureAuditInitialized();
77
75
  console.log("dt-common-device: Initialization completed successfully");
78
76
  }
77
+ async function validateInternalEventHandler(cfg) {
78
+ // Initialize internal event subscription if handler is provided
79
+ if (cfg.INTERNAL_EVENT_HANDLER) {
80
+ try {
81
+ eventSubscription = new events_1.InternalEventSubscription(cfg.INTERNAL_EVENT_HANDLER);
82
+ cfg.LOGGER.info("InternalEventSubscription initialized successfully");
83
+ }
84
+ catch (error) {
85
+ cfg.LOGGER.error("Failed to initialize InternalEventSubscription", {
86
+ error,
87
+ });
88
+ throw error;
89
+ }
90
+ }
91
+ }
92
+ async function validateAccessConfig(cfg) {
93
+ checkRequiredEnv(constants_1.CONFIG_KEYS.ACCESS.env);
94
+ if (constants_1.CONFIG_KEYS.ACCESS.INTERNAL_EVENT_HANDLER) {
95
+ await validateInternalEventHandler(cfg);
96
+ }
97
+ }
98
+ async function validateEnergyConfig(cfg) {
99
+ checkRequiredEnv(constants_1.CONFIG_KEYS.ENERGY.env);
100
+ if (constants_1.CONFIG_KEYS.ENERGY.INTERNAL_EVENT_HANDLER) {
101
+ await validateInternalEventHandler(cfg);
102
+ }
103
+ }
104
+ async function validateRemoteConfig(cfg) {
105
+ checkRequiredEnv(constants_1.CONFIG_KEYS.REMOTE.env);
106
+ if (constants_1.CONFIG_KEYS.REMOTE.INTERNAL_EVENT_HANDLER) {
107
+ await validateInternalEventHandler(cfg);
108
+ }
109
+ }
110
+ async function validateScheduleConfig(cfg) {
111
+ checkRequiredEnv(constants_1.CONFIG_KEYS.SCHEDULE.env);
112
+ if (constants_1.CONFIG_KEYS.SCHEDULE.INTERNAL_EVENT_HANDLER) {
113
+ await validateInternalEventHandler(cfg);
114
+ }
115
+ }
79
116
  function getConfig() {
80
117
  if (!config) {
81
118
  throw new Error("dt-common-device: Library not initialized. Call initialize() first.");
82
119
  }
83
120
  return config;
84
121
  }
122
+ function getDeviceServiceUrl() {
123
+ const deviceServiceUrl = process.env.DEVICE_SERVICE;
124
+ if (!deviceServiceUrl) {
125
+ getConfig().LOGGER.error("DEVICE_SERVICE must be set in environment variables");
126
+ throw new Error("dt-common-device: DEVICE_SERVICE must be set in environment variables");
127
+ }
128
+ return deviceServiceUrl;
129
+ }
130
+ function getAdminServiceUrl() {
131
+ const adminServiceUrl = process.env.ADMIN_SERVICE;
132
+ if (!adminServiceUrl) {
133
+ getConfig().LOGGER.error("ADMIN_SERVICE must be set in environment variables");
134
+ throw new Error("dt-common-device: ADMIN_SERVICE must be set in environment variables");
135
+ }
136
+ return adminServiceUrl;
137
+ }
138
+ function getSqsQueueUrl() {
139
+ const sqsQueueUrl = process.env.AWS_SQS_URL;
140
+ if (!sqsQueueUrl) {
141
+ getConfig().LOGGER.error("AWS_SQS_URL must be set in environment variables");
142
+ throw new Error("dt-common-device: AWS_SQS_URL must be set in environment variables");
143
+ }
144
+ return sqsQueueUrl;
145
+ }
85
146
  function getEventSubscription() {
86
147
  return eventSubscription;
87
148
  }
88
- function checkRequiredEnv() {
89
- const requiredEnv = [
90
- "AWS_SECRET_ACCESS_KEY",
91
- "AWS_REGION",
92
- "AWS_ACCESS_KEY_ID",
93
- "EVENT_BUS_NAME",
94
- "ADMIN_DB_URI",
95
- "MONGODB_URI",
96
- "REDIS_HOST",
97
- "REDIS_PORT",
98
- "POSTHOG_API_KEY",
99
- "POSTHOG_HOST",
100
- ];
101
- const missing = requiredEnv.filter((key) => !process.env[key]);
149
+ function checkRequiredEnv(requiredEnvs) {
150
+ const missing = requiredEnvs.filter((key) => !process.env[key]);
102
151
  if (missing.length > 0) {
103
- throw new Error(`Missing required AWS environment variables for dt-pub-sub: ${missing.join(", ")}`);
152
+ throw new Error(`Missing required environment variables: ${missing.join(", ")}`);
104
153
  }
105
154
  }
106
155
  function ensureAuditInitialized() {
@@ -115,22 +164,38 @@ function ensureAuditInitialized() {
115
164
  (0, dt_audit_library_1.initializeAudit)(apiKey, host);
116
165
  auditInitialized = true;
117
166
  }
118
- // // Direct logger export for easier usage
119
- // export function getLogger(): ILogger {
120
- // return getConfig().LOGGER;
121
- // }
167
+ // Direct logger export for easier usage
168
+ function getLogger() {
169
+ return getConfig().LOGGER;
170
+ }
122
171
  /**
123
172
  * Returns the PostgreSQL DB URI from environment variables.
124
173
  * Throws an error if not set.
125
174
  */
126
- function getPostgresDbUri() {
127
- const fullUri = process.env.ADMIN_DB_URI;
175
+ function getAdminPostgresDbUri() {
176
+ const fullUri = process.env[db_keys.admin];
128
177
  if (!fullUri) {
129
178
  getConfig().LOGGER.error("ADMIN_DB_URI must be set in environment variables or .env file");
130
179
  throw new Error("dt-common-device: ADMIN_DB_URI must be set in environment variables or .env file");
131
180
  }
132
181
  return fullUri;
133
182
  }
183
+ function getAccessPostgresDbUri() {
184
+ const fullUri = process.env[db_keys.access];
185
+ if (!fullUri) {
186
+ getConfig().LOGGER.error("ACCESS_DB_URI must be set in environment variables or .env file");
187
+ throw new Error("dt-common-device: ACCESS_DB_URI must be set in environment variables or .env file");
188
+ }
189
+ return fullUri;
190
+ }
191
+ function getPmsPostgresDbUri() {
192
+ const fullUri = process.env[db_keys.pms];
193
+ if (!fullUri) {
194
+ getConfig().LOGGER.error("PMS_DB_URI must be set in environment variables or .env file");
195
+ throw new Error("dt-common-device: PMS_DB_URI must be set in environment variables or .env file");
196
+ }
197
+ return fullUri;
198
+ }
134
199
  function getMongoUri() {
135
200
  const fullUri = process.env.MONGODB_URI;
136
201
  if (!fullUri) {
@@ -139,6 +204,14 @@ function getMongoUri() {
139
204
  }
140
205
  return fullUri;
141
206
  }
207
+ function getDTApiKey() {
208
+ const apiKey = process.env.DT_API_KEY;
209
+ if (!apiKey) {
210
+ getConfig().LOGGER.error("DT_API_KEY must be set in environment variables");
211
+ throw new Error("dt-common-device: DT_API_KEY must be set in environment variables");
212
+ }
213
+ return apiKey;
214
+ }
142
215
  /**
143
216
  * Returns the Redis DB Host and port from environment variables.
144
217
  * Throws an error if not set.
@@ -7,15 +7,8 @@ export interface ILogger {
7
7
  type AllowedSource = "ACCESS_SERVICE" | "ADMIN_SERVICE" | "ENERGY_SERVICE" | "REMOTE_SERVICE" | "SCHEDULE_SERVICE";
8
8
  export type IConfig = {
9
9
  SOURCE: AllowedSource;
10
- SQS_QUEUE_URL: string;
11
- DEVICE_SERVICE?: string;
12
- ADMIN_SERVICE?: string;
13
- ACCESS_SERVICE?: string;
14
- ENERGY_SERVICE?: string;
15
- REMOTE_SERVICE?: string;
16
- INTERNAL_EVENT_HANDLER: IInternalEvent;
10
+ INTERNAL_EVENT_HANDLER?: IInternalEvent;
17
11
  LOGGER: ILogger;
18
- CLOUD_SERVICE_API_KEY?: string;
19
12
  [key: string]: any;
20
13
  };
21
14
  export {};
package/dist/db/db.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import { Pool } from "pg";
2
2
  export declare function getPostgresClient(): Pool;
3
+ export declare function getAccessPostgresClient(): Pool;
4
+ export declare function getPmsPostgresClient(): Pool;
3
5
  export declare const connectDatabase: () => Promise<void>;