@etainabl/nodejs-sdk 1.2.43 → 1.2.45
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.
- package/dist/cjs/package.json +3 -0
- package/dist/esm/package.json +3 -0
- package/dist/index.d.cts +782 -0
- package/dist/index.d.ts +782 -0
- package/dist/index.js +626 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +588 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +27 -26
- package/.prettierrc +0 -11
- package/__tests__/reporting.test.ts +0 -88
- package/dist/cjs/index.js +0 -59
- package/eslint.config.js +0 -60
- package/fixup.sh +0 -11
- package/package-lock.json +0 -6327
- package/src/api.ts +0 -382
- package/src/consumption.ts +0 -40
- package/src/db.ts +0 -69
- package/src/etainabl.ts +0 -10
- package/src/index.ts +0 -21
- package/src/logger.ts +0 -13
- package/src/monitoring.ts +0 -18
- package/src/reporting.ts +0 -78
- package/src/slack.ts +0 -16
- package/src/types/account.ts +0 -116
- package/src/types/address.ts +0 -12
- package/src/types/asset.ts +0 -142
- package/src/types/automation.ts +0 -35
- package/src/types/company.ts +0 -47
- package/src/types/dataIngest.ts +0 -8
- package/src/types/email.ts +0 -18
- package/src/types/entity.ts +0 -17
- package/src/types/index.ts +0 -20
- package/src/types/invoice.ts +0 -119
- package/src/types/log.ts +0 -10
- package/src/types/portal.ts +0 -9
- package/src/types/reading.ts +0 -17
- package/src/types/report.ts +0 -21
- package/src/types/scraperRun.ts +0 -15
- package/src/types/statusHistory.ts +0 -5
- package/src/types/supplier.ts +0 -31
- package/src/units.ts +0 -111
- package/tsconfig.base.json +0 -31
- package/tsconfig.cjs.json +0 -8
- package/tsconfig.json +0 -9
- package/tsconfig.test.json +0 -13
- package/vitest.config.js +0 -10
- 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
|
-
};
|
package/src/consumption.ts
DELETED
|
@@ -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
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
|
-
}
|