@etainabl/nodejs-sdk 1.2.44 → 1.2.46

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 (154) hide show
  1. package/dist/index.d.cts +782 -0
  2. package/dist/index.d.ts +782 -0
  3. package/dist/index.js +626 -0
  4. package/dist/index.js.map +1 -0
  5. package/dist/index.mjs +588 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/package.json +28 -31
  8. package/.prettierrc +0 -11
  9. package/__tests__/reporting.test.ts +0 -88
  10. package/dist/cjs/api.d.ts +0 -111
  11. package/dist/cjs/api.js +0 -318
  12. package/dist/cjs/consumption.d.ts +0 -14
  13. package/dist/cjs/consumption.js +0 -32
  14. package/dist/cjs/db.d.ts +0 -6
  15. package/dist/cjs/db.js +0 -69
  16. package/dist/cjs/etainabl.d.ts +0 -10
  17. package/dist/cjs/etainabl.js +0 -2
  18. package/dist/cjs/index.d.ts +0 -10
  19. package/dist/cjs/index.js +0 -59
  20. package/dist/cjs/logger.d.ts +0 -3
  21. package/dist/cjs/logger.js +0 -14
  22. package/dist/cjs/monitoring.d.ts +0 -1
  23. package/dist/cjs/monitoring.js +0 -31
  24. package/dist/cjs/package.json +0 -3
  25. package/dist/cjs/reporting.d.ts +0 -2
  26. package/dist/cjs/reporting.js +0 -69
  27. package/dist/cjs/slack.d.ts +0 -4
  28. package/dist/cjs/slack.js +0 -28
  29. package/dist/cjs/types/account.d.ts +0 -112
  30. package/dist/cjs/types/account.js +0 -2
  31. package/dist/cjs/types/address.d.ts +0 -11
  32. package/dist/cjs/types/address.js +0 -2
  33. package/dist/cjs/types/asset.d.ts +0 -122
  34. package/dist/cjs/types/asset.js +0 -3
  35. package/dist/cjs/types/automation.d.ts +0 -33
  36. package/dist/cjs/types/automation.js +0 -2
  37. package/dist/cjs/types/company.d.ts +0 -42
  38. package/dist/cjs/types/company.js +0 -2
  39. package/dist/cjs/types/dataIngest.d.ts +0 -8
  40. package/dist/cjs/types/dataIngest.js +0 -2
  41. package/dist/cjs/types/email.d.ts +0 -18
  42. package/dist/cjs/types/email.js +0 -2
  43. package/dist/cjs/types/entity.d.ts +0 -16
  44. package/dist/cjs/types/entity.js +0 -2
  45. package/dist/cjs/types/index.d.ts +0 -19
  46. package/dist/cjs/types/index.js +0 -2
  47. package/dist/cjs/types/invoice.d.ts +0 -118
  48. package/dist/cjs/types/invoice.js +0 -2
  49. package/dist/cjs/types/log.d.ts +0 -10
  50. package/dist/cjs/types/log.js +0 -2
  51. package/dist/cjs/types/portal.d.ts +0 -8
  52. package/dist/cjs/types/portal.js +0 -2
  53. package/dist/cjs/types/reading.d.ts +0 -17
  54. package/dist/cjs/types/reading.js +0 -2
  55. package/dist/cjs/types/report.d.ts +0 -21
  56. package/dist/cjs/types/report.js +0 -2
  57. package/dist/cjs/types/scraperRun.d.ts +0 -15
  58. package/dist/cjs/types/scraperRun.js +0 -2
  59. package/dist/cjs/types/statusHistory.d.ts +0 -5
  60. package/dist/cjs/types/statusHistory.js +0 -2
  61. package/dist/cjs/types/supplier.d.ts +0 -28
  62. package/dist/cjs/types/supplier.js +0 -3
  63. package/dist/cjs/units.d.ts +0 -22
  64. package/dist/cjs/units.js +0 -94
  65. package/dist/mjs/api.d.ts +0 -111
  66. package/dist/mjs/api.js +0 -308
  67. package/dist/mjs/consumption.d.ts +0 -14
  68. package/dist/mjs/consumption.js +0 -22
  69. package/dist/mjs/db.d.ts +0 -6
  70. package/dist/mjs/db.js +0 -53
  71. package/dist/mjs/etainabl.d.ts +0 -10
  72. package/dist/mjs/etainabl.js +0 -1
  73. package/dist/mjs/index.d.ts +0 -10
  74. package/dist/mjs/index.js +0 -10
  75. package/dist/mjs/logger.d.ts +0 -3
  76. package/dist/mjs/logger.js +0 -9
  77. package/dist/mjs/monitoring.d.ts +0 -1
  78. package/dist/mjs/monitoring.js +0 -15
  79. package/dist/mjs/package.json +0 -3
  80. package/dist/mjs/reporting.d.ts +0 -2
  81. package/dist/mjs/reporting.js +0 -62
  82. package/dist/mjs/slack.d.ts +0 -4
  83. package/dist/mjs/slack.js +0 -14
  84. package/dist/mjs/types/account.d.ts +0 -112
  85. package/dist/mjs/types/account.js +0 -1
  86. package/dist/mjs/types/address.d.ts +0 -11
  87. package/dist/mjs/types/address.js +0 -1
  88. package/dist/mjs/types/asset.d.ts +0 -122
  89. package/dist/mjs/types/asset.js +0 -2
  90. package/dist/mjs/types/automation.d.ts +0 -33
  91. package/dist/mjs/types/automation.js +0 -1
  92. package/dist/mjs/types/company.d.ts +0 -42
  93. package/dist/mjs/types/company.js +0 -1
  94. package/dist/mjs/types/dataIngest.d.ts +0 -8
  95. package/dist/mjs/types/dataIngest.js +0 -1
  96. package/dist/mjs/types/email.d.ts +0 -18
  97. package/dist/mjs/types/email.js +0 -1
  98. package/dist/mjs/types/entity.d.ts +0 -16
  99. package/dist/mjs/types/entity.js +0 -1
  100. package/dist/mjs/types/index.d.ts +0 -19
  101. package/dist/mjs/types/index.js +0 -1
  102. package/dist/mjs/types/invoice.d.ts +0 -118
  103. package/dist/mjs/types/invoice.js +0 -1
  104. package/dist/mjs/types/log.d.ts +0 -10
  105. package/dist/mjs/types/log.js +0 -1
  106. package/dist/mjs/types/portal.d.ts +0 -8
  107. package/dist/mjs/types/portal.js +0 -1
  108. package/dist/mjs/types/reading.d.ts +0 -17
  109. package/dist/mjs/types/reading.js +0 -1
  110. package/dist/mjs/types/report.d.ts +0 -21
  111. package/dist/mjs/types/report.js +0 -1
  112. package/dist/mjs/types/scraperRun.d.ts +0 -15
  113. package/dist/mjs/types/scraperRun.js +0 -1
  114. package/dist/mjs/types/statusHistory.d.ts +0 -5
  115. package/dist/mjs/types/statusHistory.js +0 -1
  116. package/dist/mjs/types/supplier.d.ts +0 -28
  117. package/dist/mjs/types/supplier.js +0 -2
  118. package/dist/mjs/units.d.ts +0 -22
  119. package/dist/mjs/units.js +0 -89
  120. package/eslint.config.js +0 -60
  121. package/fixup.sh +0 -11
  122. package/src/api.ts +0 -382
  123. package/src/consumption.ts +0 -40
  124. package/src/db.ts +0 -69
  125. package/src/etainabl.ts +0 -10
  126. package/src/index.ts +0 -21
  127. package/src/logger.ts +0 -13
  128. package/src/monitoring.ts +0 -18
  129. package/src/reporting.ts +0 -78
  130. package/src/slack.ts +0 -16
  131. package/src/types/account.ts +0 -116
  132. package/src/types/address.ts +0 -12
  133. package/src/types/asset.ts +0 -142
  134. package/src/types/automation.ts +0 -35
  135. package/src/types/company.ts +0 -47
  136. package/src/types/dataIngest.ts +0 -8
  137. package/src/types/email.ts +0 -18
  138. package/src/types/entity.ts +0 -17
  139. package/src/types/index.ts +0 -20
  140. package/src/types/invoice.ts +0 -119
  141. package/src/types/log.ts +0 -10
  142. package/src/types/portal.ts +0 -9
  143. package/src/types/reading.ts +0 -17
  144. package/src/types/report.ts +0 -21
  145. package/src/types/scraperRun.ts +0 -15
  146. package/src/types/statusHistory.ts +0 -5
  147. package/src/types/supplier.ts +0 -31
  148. package/src/units.ts +0 -111
  149. package/tsconfig.base.json +0 -31
  150. package/tsconfig.cjs.json +0 -8
  151. package/tsconfig.json +0 -9
  152. package/tsconfig.test.json +0 -13
  153. package/vitest.config.js +0 -10
  154. package/vitest.workspace.js +0 -5
package/src/api.ts DELETED
@@ -1,382 +0,0 @@
1
- import axios from 'axios';
2
- import type { AxiosRequestConfig, AxiosInstance, CreateAxiosDefaults, AxiosResponse } from 'axios';
3
- import https from 'https';
4
-
5
- import logger from './logger.js';
6
-
7
- import type { Account, Asset, Automation, Entity, Company, DataIngest, Invoice, Log, Reading, Report, Supplier } from './types/index.js'
8
-
9
- const log = logger('etainablApi');
10
-
11
- export interface ETNPagedResponse<T = any> {
12
- data: T[];
13
- total: number;
14
- limit: number;
15
- skip: number;
16
- }
17
-
18
- export interface ETNReq {
19
- method: string;
20
- url: string;
21
- }
22
-
23
- function _handleResponse(req: ETNReq, res: AxiosResponse, isPaged = false) {
24
- if (!res) {
25
- throw new Error(`No response from API (${req.method} ${req.url})`);
26
- }
27
-
28
- if (res.status !== 200) {
29
- throw new Error(`${res.status} ${res.statusText} response from API (${req.method} ${req.url})`);
30
- }
31
-
32
- if (!res.data) {
33
- throw new Error(`No data from API (${req.method} ${req.url})`);
34
- }
35
-
36
- if (isPaged && !res.data.data) {
37
- throw new Error(`No data from API (${req.method} ${req.url})`);
38
- }
39
-
40
- return res;
41
- }
42
-
43
- const factory = {
44
- getWithId: <T = any> (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (id: string, options: AxiosRequestConfig = {}): Promise<T> => {
45
- const req = {
46
- method: 'GET',
47
- url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
48
- };
49
-
50
- log.info(`API Request: ${req.method} ${process.env.ETAsINABL_API_URL}/${req.url}`);
51
-
52
- let res: AxiosResponse;
53
-
54
- try {
55
- res = await etainablApi.get(req.url, options);
56
- } catch (e: any) {
57
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
58
- throw e;
59
- }
60
-
61
- console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
62
-
63
- _handleResponse(req, res)
64
-
65
- return res.data;
66
- },
67
- get: <T = any> (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (options: AxiosRequestConfig = {}): Promise<T> => {
68
- const req = {
69
- method: 'GET',
70
- url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
71
- };
72
-
73
- log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
74
-
75
- let res: AxiosResponse;
76
-
77
- try {
78
- res = await etainablApi.get(req.url, options);
79
- } catch (e: any) {
80
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
81
- throw e;
82
- }
83
-
84
- console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
85
- _handleResponse(req, res)
86
-
87
- return res.data;
88
- },
89
- list: <T = any> (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (options: AxiosRequestConfig = {}): Promise<ETNPagedResponse<T>> => {
90
- const req = {
91
- method: 'GET',
92
- url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
93
- };
94
-
95
- log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
96
-
97
- let res: AxiosResponse;
98
-
99
- try {
100
- res = await etainablApi.get(req.url, options);
101
- } catch (e: any) {
102
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
103
- throw e;
104
- }
105
-
106
- console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
107
- _handleResponse(req, res, true)
108
-
109
- return res.data;
110
- },
111
- update: (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (id: string, data: any, options: AxiosRequestConfig = {}) => {
112
- const req = {
113
- method: 'PATCH',
114
- url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
115
- };
116
-
117
- log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
118
-
119
- let res: AxiosResponse;
120
-
121
- try {
122
- res = await etainablApi.patch(req.url, data, options);
123
- } catch (e: any) {
124
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
125
- throw e;
126
- }
127
-
128
- _handleResponse(req, res)
129
-
130
- return res.data;
131
- },
132
- create: (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (data: any, options: AxiosRequestConfig = {}) => {
133
- const req = {
134
- method: 'POST',
135
- url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
136
- };
137
-
138
- log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
139
-
140
- let res: AxiosResponse;
141
-
142
- try {
143
- res = await etainablApi.post(req.url, data, options);
144
- } catch (e: any) {
145
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
146
- throw e;
147
- }
148
-
149
- _handleResponse(req, res)
150
-
151
- return res.data;
152
- },
153
- remove: (etainablApi: AxiosInstance, endpoint: string, postEndpoint?: string) => async (id: string, options: AxiosRequestConfig = {}) => {
154
- const req = {
155
- method: 'DELETE',
156
- url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
157
- };
158
-
159
- let res: AxiosResponse;
160
-
161
- log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
162
-
163
- try {
164
- res = await etainablApi.delete(req.url, options);
165
- } catch (e: any) {
166
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
167
- throw e;
168
- }
169
-
170
- _handleResponse(req, res);
171
-
172
- return res.data;
173
- },
174
- customWithId: (etainablApi: AxiosInstance, method: string, endpoint: string, postEndpoint?: string) => async (id: string, data: any, options: AxiosRequestConfig = {}) => {
175
- const req = {
176
- method: method,
177
- url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`,
178
- data,
179
- ...options
180
- };
181
-
182
- log.info(`API Request (Custom): ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
183
-
184
- let res: AxiosResponse;
185
-
186
- try {
187
- res = await etainablApi.request(req);
188
- } catch (e: any) {
189
- if (e.response?.data) throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
190
- throw e;
191
- }
192
-
193
- _handleResponse(req, res)
194
-
195
- return res.data;
196
- }
197
- };
198
-
199
- // ETN Sub Endpoints
200
- // e.g. /assets/:id/documents/:documentId
201
- const subFactory = {
202
- // e.g. POST /assets/:id/documents
203
- create: (etainablApi: AxiosInstance, endpoint: string, subEndpoint: string) => async (id: string, data: any, options: AxiosRequestConfig = {}) => {
204
- const subUrl = `${id}/${subEndpoint}`;
205
- return factory.create(etainablApi, endpoint, subUrl)(data, options);
206
- },
207
- // e.g. PATCH /assets/:id/documents/:documentId
208
- update: (etainablApi: AxiosInstance, endpoint: string, subEndpoint: string) => async (id: string, subId: string, data: any, options: AxiosRequestConfig = {}) => {
209
- const subUrl = `${subEndpoint}/${subId}`;
210
-
211
- return factory.update(etainablApi, endpoint, subUrl)(id, data, options);
212
- },
213
- // e.g. DELETE /assets/:id/documents/:documentId
214
- remove: (etainablApi: AxiosInstance, endpoint: string, subEndpoint: string) => async (id: string, subId: string, options: AxiosRequestConfig = {}) => {
215
- const subUrl = `${subEndpoint}/${subId}`;
216
-
217
- return factory.remove(etainablApi, endpoint, subUrl)(id, options);
218
- }
219
- }
220
-
221
- interface AuthOptions {
222
- key?: string;
223
- token?: string;
224
- }
225
-
226
- export default (auth: AuthOptions, instanceOptions: CreateAxiosDefaults = {}) => {
227
- try {
228
- const headers: any = {};
229
-
230
- if (auth.key) {
231
- headers['x-key'] = auth.key;
232
- } else if (auth.token) {
233
- headers['Authorization'] = auth.token;
234
- } else {
235
- headers['x-key'] = process.env.ETAINABL_API_KEY;
236
- }
237
-
238
- const etainablApi = axios.create({
239
- baseURL: process.env.ETAINABL_API_URL,
240
- timeout: 300000,
241
- httpsAgent: new https.Agent({ keepAlive: true }),
242
- headers,
243
- ...instanceOptions
244
- });
245
-
246
- return {
247
- instance: etainablApi,
248
-
249
- // accounts
250
- getAccount: factory.getWithId<Account>(etainablApi, 'accounts'),
251
- listAccounts: factory.list<Account>(etainablApi, 'accounts'),
252
- updateAccount: factory.update(etainablApi, 'accounts'),
253
- createAccount: factory.create(etainablApi, 'accounts'),
254
- removeAccount: factory.remove(etainablApi, 'accounts'),
255
- getAccountSchema: factory.get(etainablApi, 'accounts', 'schema'),
256
- invalidateAccountCache: factory.customWithId(etainablApi, 'put', 'accounts', 'invalidate-cache'),
257
-
258
- // assets
259
- getAsset: factory.getWithId<Asset>(etainablApi, 'assets'),
260
- listAssets: factory.list<Asset>(etainablApi, 'assets'),
261
- updateAsset: factory.update(etainablApi, 'assets'),
262
- createAsset: factory.create(etainablApi, 'assets'),
263
- removeAsset: factory.remove(etainablApi, 'assets'),
264
- getAssetSchema: factory.get(etainablApi, 'assets', 'schema'),
265
-
266
- // assetGroups
267
- getAssetGroup: factory.getWithId(etainablApi, 'asset-groups'),
268
- listAssetGroups: factory.list(etainablApi, 'asset-groups'),
269
- updateAssetGroup: factory.update(etainablApi, 'asset-groups'),
270
- createAssetGroup: factory.create(etainablApi, 'asset-groups'),
271
- removeAssetGroup: factory.remove(etainablApi, 'asset-groups'),
272
- getAssetGroupAssets: factory.getWithId(etainablApi, 'asset-groups', 'assets'),
273
- getAssetGroupSchema: factory.get(etainablApi, 'asset-groups', 'schema'),
274
-
275
- // automation
276
- getAutomation: factory.getWithId<Automation>(etainablApi, 'automation'),
277
- listAutomations: factory.list<Automation>(etainablApi, 'automation'),
278
- updateAutomation: factory.update(etainablApi, 'automation'),
279
- createAutomation: factory.create(etainablApi, 'automation'),
280
- removeAutomation: factory.remove(etainablApi, 'automation'),
281
- createAutomationLog: subFactory.create(etainablApi, 'automation', 'logs'),
282
- updateAutomationLog: subFactory.update(etainablApi, 'automation', 'logs'),
283
- removeAutomationLog: subFactory.remove(etainablApi, 'automation', 'logs'),
284
-
285
- // company
286
- getCompany: factory.getWithId<Company>(etainablApi, 'companies'),
287
-
288
- // consumption
289
- getConsumption: factory.getWithId(etainablApi, 'consumptions'),
290
- listConsumptions: factory.list(etainablApi, 'consumptions'),
291
- updateConsumption: factory.update(etainablApi, 'consumptions'),
292
- createConsumption: factory.create(etainablApi, 'consumptions'),
293
- removeConsumption: factory.remove(etainablApi, 'consumptions'),
294
- getConsumptionSchema: factory.get(etainablApi, 'consumptions', 'schema'),
295
-
296
- // emails
297
- getEmail: factory.getWithId(etainablApi, 'emails'),
298
- listEmails: factory.list(etainablApi, 'emails'),
299
- updateEmail: factory.update(etainablApi, 'emails'),
300
- createEmail: factory.create(etainablApi, 'emails'),
301
- removeEmail: factory.remove(etainablApi, 'emails'),
302
-
303
- // emission factors
304
- getEmissionFactor: factory.getWithId(etainablApi, 'emission-factors'),
305
- listEmissionFactors: factory.list(etainablApi, 'emission-factors'),
306
- updateEmissionFactor: factory.update(etainablApi, 'emission-factors'),
307
- createEmissionFactor: factory.create(etainablApi, 'emission-factors'),
308
- removeEmissionFactor: factory.remove(etainablApi, 'emission-factors'),
309
-
310
- // entity
311
- getEntity: factory.getWithId<Entity>(etainablApi, 'entities'),
312
- listEntities: factory.list<Entity>(etainablApi, 'entities'),
313
- updateEntity: factory.update(etainablApi, 'entities'),
314
- createEntity: factory.create(etainablApi, 'entities'),
315
- removeEntity: factory.remove(etainablApi, 'entities'),
316
- getEntitiesSchema: factory.get(etainablApi, 'entities', 'schema'),
317
-
318
-
319
- // logs
320
- getLog: factory.getWithId<Log>(etainablApi, 'logs'),
321
- listLogs: factory.list<Log>(etainablApi, 'logs'),
322
- updateLog: factory.update(etainablApi, 'logs'),
323
- createLog: factory.create(etainablApi, 'logs'),
324
- removeLog: factory.remove(etainablApi, 'logs'),
325
-
326
- // readings
327
- getReading: factory.getWithId<Reading>(etainablApi, 'readings'),
328
- listReadings: factory.list<Reading>(etainablApi, 'readings'),
329
- updateReading: factory.update(etainablApi, 'readings'),
330
- createReading: factory.create(etainablApi, 'readings'),
331
- removeReading: factory.remove(etainablApi, 'readings'),
332
- getReadingSchema: factory.get(etainablApi, 'readings', 'schema'),
333
-
334
- // reports
335
- getReport: factory.getWithId<Report>(etainablApi, 'reports'),
336
- listReports: factory.list<Report>(etainablApi, 'reports'),
337
- updateReport: factory.update(etainablApi, 'reports'),
338
- createReport: factory.create(etainablApi, 'reports'),
339
- removeReport: factory.remove(etainablApi, 'reports'),
340
- sendReport: factory.customWithId(etainablApi, 'post', 'reports', 'send'),
341
-
342
- // report templates
343
- getReportTemplate: factory.getWithId(etainablApi, 'report-templates'),
344
- listReportTemplates: factory.list(etainablApi, 'report-templates'),
345
- updateReportTemplate: factory.update(etainablApi, 'report-templates'),
346
- createReportTemplate: factory.create(etainablApi, 'report-templates'),
347
- removeReportTemplate: factory.remove(etainablApi, 'report-templates'),
348
-
349
- // scheduled reports
350
- getScheduledReport: factory.getWithId(etainablApi, 'scheduled-reports'),
351
- listScheduledReports: factory.list(etainablApi, 'scheduled-reports'),
352
- updateScheduledReport: factory.update(etainablApi, 'scheduled-reports'),
353
- createScheduledReport: factory.create(etainablApi, 'scheduled-reports'),
354
- removeScheduledReport: factory.remove(etainablApi, 'scheduled-reports'),
355
- sendScheduledReport: factory.customWithId(etainablApi, 'post', 'scheduled-reports', 'send'),
356
-
357
- // invoices
358
- getInvoice: factory.getWithId<Invoice>(etainablApi, 'invoices'),
359
- listInvoices: factory.list<Invoice>(etainablApi, 'invoices'),
360
- updateInvoice: factory.update(etainablApi, 'invoices'),
361
- createInvoice: factory.create(etainablApi, 'invoices'),
362
- removeInvoice: factory.remove(etainablApi, 'invoices'),
363
- getInvoiceSchema: factory.get(etainablApi, 'invoices', 'schema'),
364
-
365
- //suppliers
366
- listSuppliers: factory.list<Supplier>(etainablApi, 'suppliers'),
367
- getSupplierSchema: factory.get(etainablApi, 'suppliers', 'schema'),
368
-
369
- // import templates
370
- getImportTemplate: factory.getWithId(etainablApi, 'import-templates'),
371
-
372
- //data imports
373
- updateDataIngest: factory.update(etainablApi, 'data-ingests'),
374
- createDataIngest: factory.create(etainablApi, 'data-ingests'),
375
- listDataIngest: factory.list<DataIngest>(etainablApi, 'data-ingests'),
376
-
377
- }
378
- } catch (e) {
379
- log.error(e);
380
- throw e;
381
- }
382
- };
@@ -1,40 +0,0 @@
1
- import moment from 'moment';
2
-
3
- interface ConsumptionData {
4
- date: Date;
5
- consumption: number;
6
- }
7
-
8
- interface DayNightConsumption {
9
- dayConsumption: number,
10
- nightConsumption: number,
11
- consumption: number
12
- }
13
-
14
- export const dayNightConsumption = (data: ConsumptionData[]) => data.reduce((acc: DayNightConsumption, item: ConsumptionData): DayNightConsumption => {
15
- const hour = moment.utc(item.date).hour(); // End Time of HH consumption period
16
-
17
- if (hour >= 0 && hour < 7) {
18
- acc.nightConsumption += item.consumption;
19
- } else {
20
- acc.dayConsumption += item.consumption;
21
- }
22
-
23
- acc.consumption += item.consumption;
24
-
25
- return acc;
26
- }, {
27
- dayConsumption: 0,
28
- nightConsumption: 0,
29
- consumption: 0
30
- });
31
-
32
- export const calcMaxConsumptionValue = (data: ConsumptionData[]) => Math.max(...data.map((item: ConsumptionData) => item.consumption));
33
-
34
- export const calcMaxDemand = (data: ConsumptionData[]) => calcMaxConsumptionValue(data) * 2;
35
-
36
- export const calcPeakLoad = (consumption: number, maxDemand: number, startDate: string | moment.Moment, endDate: string | moment.Moment) => {
37
- const days = Math.ceil(moment(endDate).diff(moment(startDate), 'days', true));
38
-
39
- return maxDemand === 0 ? 0 : ((consumption / (maxDemand * 24 * days)) * 100);
40
- };
package/src/db.ts DELETED
@@ -1,69 +0,0 @@
1
- import { MongoClient, Db } from 'mongodb';
2
- import logger from './logger.js';
3
-
4
- const log = logger('dbHelpers');
5
-
6
- let cachedDb: Db;
7
-
8
- async function connectToDatabase(retryAttempt: number = 1): Promise<Db> {
9
- if (!process.env.ETAINABL_DB_URL) throw new Error("ETAINABL_DB_URL is not set");
10
- if (!process.env.AWS_ACCESS_KEY_ID) throw new Error("AWS_ACCESS_KEY_ID is not set");
11
- if (!process.env.AWS_SECRET_ACCESS_KEY) throw new Error("AWS_SECRET_ACCESS_KEY is not set");
12
-
13
- if (cachedDb) {
14
- log.debug('Using cached MongoDB connection.');
15
- return Promise.resolve(cachedDb);
16
- }
17
-
18
- const uri = `mongodb+srv://${process.env.ETAINABL_DB_URL}`;
19
-
20
- try {
21
- if (process.env.DB_BASIC_AUTH === 'true') {
22
- log.debug('Connecting to MongoDB server... (Auth: Basic)');
23
-
24
- const client = new MongoClient(uri);
25
- await client.connect();
26
-
27
- log.debug('Connected successfully to MongoDB server! (Auth: Basic)');
28
-
29
- cachedDb = client.db('etainabl');
30
-
31
- return cachedDb;
32
- }
33
-
34
- log.debug('Connecting to MongoDB server... (Auth: AWS)');
35
-
36
- const client = new MongoClient(uri, {
37
- auth: {
38
- username: process.env.AWS_ACCESS_KEY_ID,
39
- password: process.env.AWS_SECRET_ACCESS_KEY
40
- },
41
- authSource: '$external',
42
- authMechanism: 'MONGODB-AWS'
43
- });
44
-
45
- await client.connect();
46
-
47
- log.debug('Connected successfully to MongoDB server! (Auth: AWS)');
48
-
49
- cachedDb = client.db('etainabl');
50
-
51
- return cachedDb;
52
-
53
- } catch (e: any) {
54
- // Retry
55
- if (retryAttempt > 5) {
56
- console.log(`Error connecting to MongoDB server after 5 attempts...`);
57
- throw e;
58
- }
59
-
60
- console.log(`MongoDB Connection error: ${e.message}`);
61
-
62
- console.log(`Error connecting to MongoDB server... Retrying in 3 seconds... (Attempt ${retryAttempt})`);
63
- return connectToDatabase(retryAttempt + 1);
64
- }
65
- }
66
-
67
- export default {
68
- connectToDatabase
69
- };
package/src/etainabl.ts DELETED
@@ -1,10 +0,0 @@
1
- export interface AuthorizerContext {
2
- companyId: string,
3
- isAdmin: boolean,
4
- isKiosk: boolean,
5
- isPublicApiRequest: boolean,
6
- isService: boolean,
7
- scope: string,
8
- sub: string,
9
- token: string
10
- }
package/src/index.ts DELETED
@@ -1,21 +0,0 @@
1
- import api from './api.js';
2
- import logger from './logger.js';
3
- import db from './db.js';
4
- import slack from './slack.js';
5
- import * as units from './units.js';
6
- import * as consumption from './consumption.js';
7
- import * as monitoring from './monitoring.js';
8
- import * as reporting from './reporting.js';
9
-
10
- export {
11
- api,
12
- logger,
13
- consumption,
14
- monitoring,
15
- db,
16
- slack,
17
- units,
18
- reporting
19
- }
20
-
21
- export * from './types/index.js';
package/src/logger.ts DELETED
@@ -1,13 +0,0 @@
1
- import winston from 'winston';
2
-
3
- export default (namespace: string) => winston.createLogger({
4
- level: 'debug',
5
- format: winston.format.combine(
6
- winston.format.timestamp(),
7
- winston.format.json()
8
- ),
9
- defaultMeta: { service: process.env.AWS_LAMBDA_FUNCTION_NAME, script: namespace },
10
- transports: [
11
- new winston.transports.Console()
12
- ]
13
- });
package/src/monitoring.ts DELETED
@@ -1,18 +0,0 @@
1
- import axios from 'axios';
2
-
3
- import logger from './logger.js';
4
-
5
- const log = logger('monitoring');
6
-
7
- export const sendHeartbeat = async () => {
8
- if (!process.env.HEARTBEAT_URL || process.env.HEARTBEAT_URL.endsWith('/')) return false;
9
-
10
- try {
11
- await axios.post(process.env.HEARTBEAT_URL);
12
-
13
- return true;
14
- } catch (e: any) {
15
- log.warn(`Failed to send heartbeat: ${e.message || e}`);
16
- return false;
17
- }
18
- }
package/src/reporting.ts DELETED
@@ -1,78 +0,0 @@
1
- import moment from 'moment';
2
-
3
- moment.locale('en', {
4
- week: {
5
- dow: 1
6
- }
7
- });
8
-
9
- const getNextRunTime = (startDate: moment.Moment, schedule: any, taskTime: moment.Moment): moment.Moment => {
10
- const [num, freq] = schedule.frequency.split('|');
11
- const targetDate = moment(startDate).add(num, freq as moment.unitOfTime.Base);
12
-
13
- if (schedule.frequencyPeriod === 'first') {
14
- targetDate.startOf(freq as moment.unitOfTime.StartOf);
15
- } else if (schedule.frequencyPeriod === 'last') {
16
- targetDate.endOf(freq as moment.unitOfTime.StartOf);
17
- }
18
-
19
- const isWeekday = targetDate.isoWeekday() > 0 && targetDate.isoWeekday() < 6;
20
- const isSaturday = targetDate.isoWeekday() === 6;
21
-
22
- // The weekday or weekend chosen should be within the same month as the target date
23
- if (schedule.frequencyDay === 'weekdays' && !isWeekday) {
24
- if ((targetDate.date() / 7) < 2) {
25
- targetDate.add(isSaturday ? 2 : 1, 'days');
26
- } else {
27
- targetDate.subtract(isSaturday ? 1 : 2, 'days');
28
- }
29
- } else if (schedule.frequencyDay === 'weekends' && isWeekday) {
30
- if ((targetDate.date() / 7) < 2) {
31
- targetDate.isoWeekday(6);
32
- } else {
33
- targetDate.isoWeekday(0);
34
- }
35
- }
36
-
37
- if (taskTime.isAfter(targetDate, 'minute')) {
38
- return getNextRunTime(targetDate, schedule, taskTime);
39
- }
40
-
41
- return targetDate;
42
- };
43
-
44
- export const getScheduledReportRunTimes = (schedule: any, limit = 1, taskTime = moment()): moment.Moment[] => {
45
- if (!schedule.startDate || !schedule.enabled) return [];
46
-
47
- const originalStartDate = moment.utc(schedule.startDate);
48
-
49
- let startDate = originalStartDate;
50
-
51
- const includeStartDate = taskTime.isSameOrBefore(originalStartDate, 'minute');
52
-
53
- let runTimes = [] as moment.Moment[];
54
-
55
- if (includeStartDate) {
56
- runTimes = [originalStartDate];
57
- }
58
-
59
- const [, freq] = schedule.frequency.split('|');
60
-
61
- if (freq === 'once') {
62
- const nextRunTime = runTimes[0];
63
-
64
- // If this is now beyond the start date, return an empty array
65
- return taskTime.isAfter(nextRunTime, 'minute') ? [] : runTimes;
66
- }
67
-
68
-
69
- const scheduleRunTimes = Array.from(Array(includeStartDate ? limit - 1 : limit).keys()).map(() => {
70
- const nextRunTime = getNextRunTime(startDate, schedule, taskTime);
71
-
72
- startDate = nextRunTime.hour(originalStartDate.hour()).minute(originalStartDate.minute());
73
-
74
- return nextRunTime;
75
- });
76
-
77
- return [...runTimes, ...scheduleRunTimes];
78
- };
package/src/slack.ts DELETED
@@ -1,16 +0,0 @@
1
- import axios from 'axios';
2
-
3
- const postMessage = async (message: string) => {
4
- const url = 'https://hooks.slack.com/services/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';
5
- const data = {
6
- text: `[${(process.env.ENV || '').toUpperCase()}][${process.env.AWS_LAMBDA_FUNCTION_NAME}] ${message}`
7
- };
8
- const headers = {
9
- 'Content-Type': 'application/json'
10
- };
11
- return axios.post(url, data, { headers });
12
- };
13
-
14
- export default {
15
- postMessage
16
- }