@etainabl/nodejs-sdk 1.2.15 → 1.2.17

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.
@@ -0,0 +1,99 @@
1
+ import type { AxiosRequestConfig, AxiosInstance, CreateAxiosDefaults } from 'axios';
2
+ import type { Account, Asset, Company, Invoice, Log, Reading, Supplier } from '../types/index.js';
3
+ export interface ETNPagedResponse<T = any> {
4
+ data: T[];
5
+ total: number;
6
+ limit: number;
7
+ skip: number;
8
+ }
9
+ export interface ETNReq {
10
+ method: string;
11
+ url: string;
12
+ }
13
+ interface AuthOptions {
14
+ key?: string;
15
+ token?: string;
16
+ }
17
+ declare const _default: (auth: AuthOptions, instanceOptions?: CreateAxiosDefaults) => {
18
+ instance: AxiosInstance;
19
+ getAccount: (id: string, options?: AxiosRequestConfig<any>) => Promise<Account>;
20
+ listAccounts: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Account>>;
21
+ updateAccount: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
22
+ createAccount: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
23
+ removeAccount: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
24
+ getAccountSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
25
+ getAsset: (id: string, options?: AxiosRequestConfig<any>) => Promise<Asset>;
26
+ listAssets: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Asset>>;
27
+ updateAsset: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
28
+ createAsset: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
29
+ removeAsset: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
30
+ getAssetSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
31
+ getAssetGroup: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
32
+ listAssetGroups: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
33
+ updateAssetGroup: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
34
+ createAssetGroup: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
35
+ removeAssetGroup: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
36
+ getAssetGroupAssets: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
37
+ getAssetGroupSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
38
+ getAutomation: (id: string, options?: AxiosRequestConfig<any>) => Promise<Automation>;
39
+ listAutomations: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Automation>>;
40
+ updateAutomation: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
41
+ createAutomation: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
42
+ removeAutomation: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
43
+ createAutomationLog: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
44
+ updateAutomationLog: (id: string, subId: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
45
+ removeAutomationLog: (id: string, subId: string, options?: AxiosRequestConfig<any>) => Promise<any>;
46
+ getCompany: (id: string, options?: AxiosRequestConfig<any>) => Promise<Company>;
47
+ getConsumption: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
48
+ listConsumptions: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
49
+ updateConsumption: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
50
+ createConsumption: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
51
+ removeConsumption: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
52
+ getConsumptionSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
53
+ getEmail: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
54
+ listEmails: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
55
+ updateEmail: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
56
+ createEmail: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
57
+ removeEmail: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
58
+ getEmissionFactor: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
59
+ listEmissionFactors: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
60
+ updateEmissionFactor: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
61
+ createEmissionFactor: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
62
+ removeEmissionFactor: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
63
+ getLog: (id: string, options?: AxiosRequestConfig<any>) => Promise<Log>;
64
+ listLogs: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Log>>;
65
+ updateLog: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
66
+ createLog: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
67
+ removeLog: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
68
+ getReading: (id: string, options?: AxiosRequestConfig<any>) => Promise<Reading>;
69
+ listReadings: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Reading>>;
70
+ updateReading: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
71
+ createReading: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
72
+ removeReading: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
73
+ getReadingSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
74
+ getReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
75
+ listReports: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
76
+ updateReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
77
+ createReport: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
78
+ removeReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
79
+ sendReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
80
+ getReportTemplate: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
81
+ listReportTemplates: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
82
+ updateReportTemplate: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
83
+ createReportTemplate: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
84
+ removeReportTemplate: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
85
+ getScheduledReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
86
+ listScheduledReports: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<any>>;
87
+ updateScheduledReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
88
+ createScheduledReport: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
89
+ removeScheduledReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
90
+ sendScheduledReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
91
+ getInvoice: (id: string, options?: AxiosRequestConfig<any>) => Promise<Invoice>;
92
+ listInvoices: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse<Invoice>>;
93
+ updateInvoice: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
94
+ createInvoice: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
95
+ removeInvoice: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
96
+ getInvoiceSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
97
+ getSupplierSchema: (options?: AxiosRequestConfig<any>) => Promise<Supplier>;
98
+ };
99
+ export default _default;
@@ -0,0 +1,303 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const axios_1 = __importDefault(require("axios"));
16
+ const https_1 = __importDefault(require("https"));
17
+ const logger_js_1 = __importDefault(require("./logger.js"));
18
+ const log = (0, logger_js_1.default)('etainablApi');
19
+ function _handleResponse(req, res, isPaged = false) {
20
+ if (!res) {
21
+ throw new Error(`No response from API (${req.method} ${req.url})`);
22
+ }
23
+ if (res.status !== 200) {
24
+ throw new Error(`${res.status} ${res.statusText} response from API (${req.method} ${req.url})`);
25
+ }
26
+ if (!res.data) {
27
+ throw new Error(`No data from API (${req.method} ${req.url})`);
28
+ }
29
+ if (isPaged && !res.data.data) {
30
+ throw new Error(`No data from API (${req.method} ${req.url})`);
31
+ }
32
+ return res;
33
+ }
34
+ const factory = {
35
+ getWithId: (etainablApi, endpoint, postEndpoint) => (id, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
36
+ var _a;
37
+ const req = {
38
+ method: 'GET',
39
+ url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
40
+ };
41
+ log.info(`API Request: ${req.method} ${process.env.ETAsINABL_API_URL}/${req.url}`);
42
+ let res;
43
+ try {
44
+ res = yield etainablApi.get(req.url, options);
45
+ }
46
+ catch (e) {
47
+ if ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data)
48
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
49
+ throw e;
50
+ }
51
+ console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
52
+ _handleResponse(req, res);
53
+ return res.data;
54
+ }),
55
+ get: (etainablApi, endpoint, postEndpoint) => (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
56
+ var _b;
57
+ const req = {
58
+ method: 'GET',
59
+ url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
60
+ };
61
+ log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
62
+ let res;
63
+ try {
64
+ res = yield etainablApi.get(req.url, options);
65
+ }
66
+ catch (e) {
67
+ if ((_b = e.response) === null || _b === void 0 ? void 0 : _b.data)
68
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
69
+ throw e;
70
+ }
71
+ console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
72
+ _handleResponse(req, res);
73
+ return res.data;
74
+ }),
75
+ list: (etainablApi, endpoint, postEndpoint) => (options = {}) => __awaiter(void 0, void 0, void 0, function* () {
76
+ var _c;
77
+ const req = {
78
+ method: 'GET',
79
+ url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
80
+ };
81
+ log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
82
+ let res;
83
+ try {
84
+ res = yield etainablApi.get(req.url, options);
85
+ }
86
+ catch (e) {
87
+ if ((_c = e.response) === null || _c === void 0 ? void 0 : _c.data)
88
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
89
+ throw e;
90
+ }
91
+ console.log(`API Response: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
92
+ _handleResponse(req, res, true);
93
+ return res.data;
94
+ }),
95
+ update: (etainablApi, endpoint, postEndpoint) => (id, data, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
96
+ var _d;
97
+ const req = {
98
+ method: 'PATCH',
99
+ url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
100
+ };
101
+ log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
102
+ let res;
103
+ try {
104
+ res = yield etainablApi.patch(req.url, data, options);
105
+ }
106
+ catch (e) {
107
+ if ((_d = e.response) === null || _d === void 0 ? void 0 : _d.data)
108
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
109
+ throw e;
110
+ }
111
+ _handleResponse(req, res);
112
+ return res.data;
113
+ }),
114
+ create: (etainablApi, endpoint, postEndpoint) => (data, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
115
+ var _e;
116
+ const req = {
117
+ method: 'POST',
118
+ url: `${endpoint}${postEndpoint ? `/${postEndpoint}` : ''}`
119
+ };
120
+ log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
121
+ let res;
122
+ try {
123
+ res = yield etainablApi.post(req.url, data, options);
124
+ }
125
+ catch (e) {
126
+ if ((_e = e.response) === null || _e === void 0 ? void 0 : _e.data)
127
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
128
+ throw e;
129
+ }
130
+ _handleResponse(req, res);
131
+ return res.data;
132
+ }),
133
+ remove: (etainablApi, endpoint, postEndpoint) => (id, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
134
+ var _f;
135
+ const req = {
136
+ method: 'DELETE',
137
+ url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`
138
+ };
139
+ let res;
140
+ log.info(`API Request: ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
141
+ try {
142
+ res = yield etainablApi.delete(req.url, options);
143
+ }
144
+ catch (e) {
145
+ if ((_f = e.response) === null || _f === void 0 ? void 0 : _f.data)
146
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
147
+ throw e;
148
+ }
149
+ _handleResponse(req, res);
150
+ return res.data;
151
+ }),
152
+ customWithId: (etainablApi, method, endpoint, postEndpoint) => (id, data, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
153
+ var _g;
154
+ const req = Object.assign({ method: method, url: `${endpoint}/${id}${postEndpoint ? `/${postEndpoint}` : ''}`, data }, options);
155
+ log.info(`API Request (Custom): ${req.method} ${process.env.ETAINABL_API_URL}/${req.url}`);
156
+ let res;
157
+ try {
158
+ res = yield etainablApi.request(req);
159
+ }
160
+ catch (e) {
161
+ if ((_g = e.response) === null || _g === void 0 ? void 0 : _g.data)
162
+ throw new Error(`API error response: ${JSON.stringify(e.response.data)}`);
163
+ throw e;
164
+ }
165
+ _handleResponse(req, res);
166
+ return res.data;
167
+ })
168
+ };
169
+ // ETN Sub Endpoints
170
+ // e.g. /assets/:id/documents/:documentId
171
+ const subFactory = {
172
+ // e.g. POST /assets/:id/documents
173
+ create: (etainablApi, endpoint, subEndpoint) => (id, data, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
174
+ const subUrl = `${id}/${subEndpoint}`;
175
+ return factory.create(etainablApi, endpoint, subUrl)(data, options);
176
+ }),
177
+ // e.g. PATCH /assets/:id/documents/:documentId
178
+ update: (etainablApi, endpoint, subEndpoint) => (id, subId, data, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
179
+ const subUrl = `${subEndpoint}/${subId}`;
180
+ return factory.update(etainablApi, endpoint, subUrl)(id, data, options);
181
+ }),
182
+ // e.g. DELETE /assets/:id/documents/:documentId
183
+ remove: (etainablApi, endpoint, subEndpoint) => (id, subId, options = {}) => __awaiter(void 0, void 0, void 0, function* () {
184
+ const subUrl = `${subEndpoint}/${subId}`;
185
+ return factory.remove(etainablApi, endpoint, subUrl)(id, options);
186
+ })
187
+ };
188
+ exports.default = (auth, instanceOptions = {}) => {
189
+ try {
190
+ const headers = {};
191
+ if (auth.key) {
192
+ headers['x-key'] = auth.key;
193
+ }
194
+ else if (auth.token) {
195
+ headers['Authorization'] = auth.token;
196
+ }
197
+ else {
198
+ headers['x-key'] = process.env.ETAINABL_API_KEY;
199
+ }
200
+ const etainablApi = axios_1.default.create(Object.assign({ baseURL: process.env.ETAINABL_API_URL, timeout: 300000, httpsAgent: new https_1.default.Agent({ keepAlive: true }), headers }, instanceOptions));
201
+ return {
202
+ instance: etainablApi,
203
+ // accounts
204
+ getAccount: factory.getWithId(etainablApi, 'accounts'),
205
+ listAccounts: factory.list(etainablApi, 'accounts'),
206
+ updateAccount: factory.update(etainablApi, 'accounts'),
207
+ createAccount: factory.create(etainablApi, 'accounts'),
208
+ removeAccount: factory.remove(etainablApi, 'accounts'),
209
+ getAccountSchema: factory.get(etainablApi, 'accounts', 'schema'),
210
+ // assets
211
+ getAsset: factory.getWithId(etainablApi, 'assets'),
212
+ listAssets: factory.list(etainablApi, 'assets'),
213
+ updateAsset: factory.update(etainablApi, 'assets'),
214
+ createAsset: factory.create(etainablApi, 'assets'),
215
+ removeAsset: factory.remove(etainablApi, 'assets'),
216
+ getAssetSchema: factory.get(etainablApi, 'assets', 'schema'),
217
+ // assetGroups
218
+ getAssetGroup: factory.getWithId(etainablApi, 'asset-groups'),
219
+ listAssetGroups: factory.list(etainablApi, 'asset-groups'),
220
+ updateAssetGroup: factory.update(etainablApi, 'asset-groups'),
221
+ createAssetGroup: factory.create(etainablApi, 'asset-groups'),
222
+ removeAssetGroup: factory.remove(etainablApi, 'asset-groups'),
223
+ getAssetGroupAssets: factory.getWithId(etainablApi, 'asset-groups', 'assets'),
224
+ getAssetGroupSchema: factory.get(etainablApi, 'asset-groups', 'schema'),
225
+ // automation
226
+ getAutomation: factory.getWithId(etainablApi, 'automation'),
227
+ listAutomations: factory.list(etainablApi, 'automation'),
228
+ updateAutomation: factory.update(etainablApi, 'automation'),
229
+ createAutomation: factory.create(etainablApi, 'automation'),
230
+ removeAutomation: factory.remove(etainablApi, 'automation'),
231
+ createAutomationLog: subFactory.create(etainablApi, 'automation', 'logs'),
232
+ updateAutomationLog: subFactory.update(etainablApi, 'automation', 'logs'),
233
+ removeAutomationLog: subFactory.remove(etainablApi, 'automation', 'logs'),
234
+ // company
235
+ getCompany: factory.getWithId(etainablApi, 'companies'),
236
+ // consumption
237
+ getConsumption: factory.getWithId(etainablApi, 'consumptions'),
238
+ listConsumptions: factory.list(etainablApi, 'consumptions'),
239
+ updateConsumption: factory.update(etainablApi, 'consumptions'),
240
+ createConsumption: factory.create(etainablApi, 'consumptions'),
241
+ removeConsumption: factory.remove(etainablApi, 'consumptions'),
242
+ getConsumptionSchema: factory.get(etainablApi, 'consumptions', 'schema'),
243
+ // emails
244
+ getEmail: factory.getWithId(etainablApi, 'emails'),
245
+ listEmails: factory.list(etainablApi, 'emails'),
246
+ updateEmail: factory.update(etainablApi, 'emails'),
247
+ createEmail: factory.create(etainablApi, 'emails'),
248
+ removeEmail: factory.remove(etainablApi, 'emails'),
249
+ // emission factors
250
+ getEmissionFactor: factory.getWithId(etainablApi, 'emission-factors'),
251
+ listEmissionFactors: factory.list(etainablApi, 'emission-factors'),
252
+ updateEmissionFactor: factory.update(etainablApi, 'emission-factors'),
253
+ createEmissionFactor: factory.create(etainablApi, 'emission-factors'),
254
+ removeEmissionFactor: factory.remove(etainablApi, 'emission-factors'),
255
+ // logs
256
+ getLog: factory.getWithId(etainablApi, 'logs'),
257
+ listLogs: factory.list(etainablApi, 'logs'),
258
+ updateLog: factory.update(etainablApi, 'logs'),
259
+ createLog: factory.create(etainablApi, 'logs'),
260
+ removeLog: factory.remove(etainablApi, 'logs'),
261
+ // readings
262
+ getReading: factory.getWithId(etainablApi, 'readings'),
263
+ listReadings: factory.list(etainablApi, 'readings'),
264
+ updateReading: factory.update(etainablApi, 'readings'),
265
+ createReading: factory.create(etainablApi, 'readings'),
266
+ removeReading: factory.remove(etainablApi, 'readings'),
267
+ getReadingSchema: factory.get(etainablApi, 'readings', 'schema'),
268
+ // reports
269
+ getReport: factory.getWithId(etainablApi, 'reports'),
270
+ listReports: factory.list(etainablApi, 'reports'),
271
+ updateReport: factory.update(etainablApi, 'reports'),
272
+ createReport: factory.create(etainablApi, 'reports'),
273
+ removeReport: factory.remove(etainablApi, 'reports'),
274
+ sendReport: factory.customWithId(etainablApi, 'post', 'reports', 'send'),
275
+ // report templates
276
+ getReportTemplate: factory.getWithId(etainablApi, 'report-templates'),
277
+ listReportTemplates: factory.list(etainablApi, 'report-templates'),
278
+ updateReportTemplate: factory.update(etainablApi, 'report-templates'),
279
+ createReportTemplate: factory.create(etainablApi, 'report-templates'),
280
+ removeReportTemplate: factory.remove(etainablApi, 'report-templates'),
281
+ // scheduled reports
282
+ getScheduledReport: factory.getWithId(etainablApi, 'scheduled-reports'),
283
+ listScheduledReports: factory.list(etainablApi, 'scheduled-reports'),
284
+ updateScheduledReport: factory.update(etainablApi, 'scheduled-reports'),
285
+ createScheduledReport: factory.create(etainablApi, 'scheduled-reports'),
286
+ removeScheduledReport: factory.remove(etainablApi, 'scheduled-reports'),
287
+ sendScheduledReport: factory.customWithId(etainablApi, 'post', 'scheduled-reports', 'send'),
288
+ // invoices
289
+ getInvoice: factory.getWithId(etainablApi, 'invoices'),
290
+ listInvoices: factory.list(etainablApi, 'invoices'),
291
+ updateInvoice: factory.update(etainablApi, 'invoices'),
292
+ createInvoice: factory.create(etainablApi, 'invoices'),
293
+ removeInvoice: factory.remove(etainablApi, 'invoices'),
294
+ getInvoiceSchema: factory.get(etainablApi, 'invoices', 'schema'),
295
+ //suppliers
296
+ getSupplierSchema: factory.get(etainablApi, 'suppliers', 'schema')
297
+ };
298
+ }
299
+ catch (e) {
300
+ log.error(e);
301
+ throw e;
302
+ }
303
+ };
@@ -0,0 +1,14 @@
1
+ import moment from 'moment';
2
+ interface ConsumptionData {
3
+ date: Date;
4
+ consumption: number;
5
+ }
6
+ export declare const dayNightConsumption: (data: ConsumptionData[]) => {
7
+ dayConsumption: number;
8
+ nightConsumption: number;
9
+ consumption: number;
10
+ };
11
+ export declare const calcMaxConsumptionValue: (data: ConsumptionData[]) => number;
12
+ export declare const calcMaxDemand: (data: ConsumptionData[]) => number;
13
+ export declare const calcPeakLoad: (consumption: number, maxDemand: number, startDate: string | moment.Moment, endDate: string | moment.Moment) => number;
14
+ export {};
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.calcPeakLoad = exports.calcMaxDemand = exports.calcMaxConsumptionValue = exports.dayNightConsumption = void 0;
7
+ const moment_1 = __importDefault(require("moment"));
8
+ const dayNightConsumption = (data) => data.reduce((acc, item) => {
9
+ const hour = moment_1.default.utc(item.date).hour(); // End Time of HH consumption period
10
+ if (hour >= 0 && hour < 7) {
11
+ acc.nightConsumption += item.consumption;
12
+ }
13
+ else {
14
+ acc.dayConsumption += item.consumption;
15
+ }
16
+ acc.consumption += item.consumption;
17
+ return acc;
18
+ }, {
19
+ dayConsumption: 0,
20
+ nightConsumption: 0,
21
+ consumption: 0
22
+ });
23
+ exports.dayNightConsumption = dayNightConsumption;
24
+ const calcMaxConsumptionValue = (data) => Math.max(...data.map((item) => item.consumption));
25
+ exports.calcMaxConsumptionValue = calcMaxConsumptionValue;
26
+ const calcMaxDemand = (data) => (0, exports.calcMaxConsumptionValue)(data) * 2;
27
+ exports.calcMaxDemand = calcMaxDemand;
28
+ const calcPeakLoad = (consumption, maxDemand, startDate, endDate) => {
29
+ const days = Math.ceil((0, moment_1.default)(endDate).diff((0, moment_1.default)(startDate), 'days', true));
30
+ return maxDemand === 0 ? 0 : ((consumption / (maxDemand * 24 * days)) * 100);
31
+ };
32
+ exports.calcPeakLoad = calcPeakLoad;
@@ -0,0 +1,6 @@
1
+ import { Db } from 'mongodb';
2
+ declare function connectToDatabase(): Promise<Db>;
3
+ declare const _default: {
4
+ connectToDatabase: typeof connectToDatabase;
5
+ };
6
+ export default _default;
package/dist/cjs/db.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const mongodb_1 = require("mongodb");
16
+ const logger_js_1 = __importDefault(require("./logger.js"));
17
+ const log = (0, logger_js_1.default)('dbHelpers');
18
+ let cachedDb;
19
+ function connectToDatabase() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ if (!process.env.ETAINABL_DB_URL)
22
+ throw new Error("ETAINABL_DB_URL is not set");
23
+ if (!process.env.AWS_ACCESS_KEY_ID)
24
+ throw new Error("AWS_ACCESS_KEY_ID is not set");
25
+ if (!process.env.AWS_SECRET_ACCESS_KEY)
26
+ throw new Error("AWS_SECRET_ACCESS_KEY is not set");
27
+ if (cachedDb) {
28
+ log.debug('Using cached MongoDB connection.');
29
+ return Promise.resolve(cachedDb);
30
+ }
31
+ log.debug('Connecting to MongoDB server...');
32
+ const uri = `mongodb+srv://${process.env.ETAINABL_DB_URL}`;
33
+ const client = new mongodb_1.MongoClient(uri, {
34
+ auth: {
35
+ username: process.env.AWS_ACCESS_KEY_ID,
36
+ password: process.env.AWS_SECRET_ACCESS_KEY
37
+ },
38
+ authSource: '$external',
39
+ authMechanism: 'MONGODB-AWS'
40
+ });
41
+ yield client.connect();
42
+ log.debug('Connected successfully to MongoDB server!');
43
+ cachedDb = client.db('etainabl');
44
+ return cachedDb;
45
+ });
46
+ }
47
+ exports.default = {
48
+ connectToDatabase
49
+ };
@@ -0,0 +1,10 @@
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
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,11 @@
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
+ import type { Account, Asset, Automation, Company, Invoice, Log, Reading, Supplier } from '../types/index.d.js';
10
+ export { api, logger, consumption, monitoring, db, slack, units, reporting };
11
+ export type { Account, Asset, Automation, Company, Invoice, Log, Reading, Supplier };
@@ -0,0 +1,45 @@
1
+ "use strict";
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]; } };
7
+ }
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 __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.reporting = exports.units = exports.slack = exports.db = exports.monitoring = exports.consumption = exports.logger = exports.api = void 0;
30
+ const api_js_1 = __importDefault(require("./api.js"));
31
+ exports.api = api_js_1.default;
32
+ const logger_js_1 = __importDefault(require("./logger.js"));
33
+ exports.logger = logger_js_1.default;
34
+ const db_js_1 = __importDefault(require("./db.js"));
35
+ exports.db = db_js_1.default;
36
+ const slack_js_1 = __importDefault(require("./slack.js"));
37
+ exports.slack = slack_js_1.default;
38
+ const units = __importStar(require("./units.js"));
39
+ exports.units = units;
40
+ const consumption = __importStar(require("./consumption.js"));
41
+ exports.consumption = consumption;
42
+ const monitoring = __importStar(require("./monitoring.js"));
43
+ exports.monitoring = monitoring;
44
+ const reporting = __importStar(require("./reporting.js"));
45
+ exports.reporting = reporting;
@@ -0,0 +1,3 @@
1
+ import winston from 'winston';
2
+ declare const _default: (namespace: string) => winston.Logger;
3
+ export default _default;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const winston_1 = __importDefault(require("winston"));
7
+ exports.default = (namespace) => winston_1.default.createLogger({
8
+ level: 'debug',
9
+ format: winston_1.default.format.combine(winston_1.default.format.timestamp(), winston_1.default.format.json()),
10
+ defaultMeta: { service: process.env.AWS_LAMBDA_FUNCTION_NAME, script: namespace },
11
+ transports: [
12
+ new winston_1.default.transports.Console()
13
+ ]
14
+ });
@@ -0,0 +1 @@
1
+ export declare const sendHeartbeat: () => Promise<boolean>;
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.sendHeartbeat = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const logger_js_1 = __importDefault(require("./logger.js"));
18
+ const log = (0, logger_js_1.default)('monitoring');
19
+ const sendHeartbeat = () => __awaiter(void 0, void 0, void 0, function* () {
20
+ if (!process.env.HEARTBEAT_URL || process.env.HEARTBEAT_URL.endsWith('/'))
21
+ return false;
22
+ try {
23
+ yield axios_1.default.post(process.env.HEARTBEAT_URL);
24
+ return true;
25
+ }
26
+ catch (e) {
27
+ log.warn(`Failed to send heartbeat: ${e.message || e}`);
28
+ return false;
29
+ }
30
+ });
31
+ exports.sendHeartbeat = sendHeartbeat;
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -0,0 +1,2 @@
1
+ import moment from 'moment';
2
+ export declare const getScheduledReportRunTimes: (schedule: any, limit?: number, taskTime?: moment.Moment) => moment.Moment[];