@etainabl/nodejs-sdk 1.2.42 → 1.2.44

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 (110) hide show
  1. package/dist/cjs/api.d.ts +111 -0
  2. package/dist/cjs/api.js +318 -0
  3. package/dist/cjs/consumption.d.ts +14 -0
  4. package/dist/cjs/consumption.js +32 -0
  5. package/dist/cjs/db.d.ts +6 -0
  6. package/dist/cjs/db.js +69 -0
  7. package/dist/cjs/etainabl.d.ts +10 -0
  8. package/dist/cjs/etainabl.js +2 -0
  9. package/dist/cjs/index.d.ts +10 -0
  10. package/dist/cjs/logger.d.ts +3 -0
  11. package/dist/cjs/logger.js +14 -0
  12. package/dist/cjs/monitoring.d.ts +1 -0
  13. package/dist/cjs/monitoring.js +31 -0
  14. package/dist/cjs/package.json +3 -0
  15. package/dist/cjs/reporting.d.ts +2 -0
  16. package/dist/cjs/reporting.js +69 -0
  17. package/dist/cjs/slack.d.ts +4 -0
  18. package/dist/cjs/slack.js +28 -0
  19. package/dist/cjs/types/account.d.ts +112 -0
  20. package/dist/cjs/types/account.js +2 -0
  21. package/dist/cjs/types/address.d.ts +11 -0
  22. package/dist/cjs/types/address.js +2 -0
  23. package/dist/cjs/types/asset.d.ts +122 -0
  24. package/dist/cjs/types/asset.js +3 -0
  25. package/dist/cjs/types/automation.d.ts +33 -0
  26. package/dist/cjs/types/automation.js +2 -0
  27. package/dist/cjs/types/company.d.ts +42 -0
  28. package/dist/cjs/types/company.js +2 -0
  29. package/dist/cjs/types/dataIngest.d.ts +8 -0
  30. package/dist/cjs/types/dataIngest.js +2 -0
  31. package/dist/cjs/types/email.d.ts +18 -0
  32. package/dist/cjs/types/email.js +2 -0
  33. package/dist/cjs/types/entity.d.ts +16 -0
  34. package/dist/cjs/types/entity.js +2 -0
  35. package/dist/cjs/types/index.d.ts +19 -0
  36. package/dist/cjs/types/index.js +2 -0
  37. package/dist/cjs/types/invoice.d.ts +118 -0
  38. package/dist/cjs/types/invoice.js +2 -0
  39. package/dist/cjs/types/log.d.ts +10 -0
  40. package/dist/cjs/types/log.js +2 -0
  41. package/dist/cjs/types/portal.d.ts +8 -0
  42. package/dist/cjs/types/portal.js +2 -0
  43. package/dist/cjs/types/reading.d.ts +17 -0
  44. package/dist/cjs/types/reading.js +2 -0
  45. package/dist/cjs/types/report.d.ts +21 -0
  46. package/dist/cjs/types/report.js +2 -0
  47. package/dist/cjs/types/scraperRun.d.ts +15 -0
  48. package/dist/cjs/types/scraperRun.js +2 -0
  49. package/dist/cjs/types/statusHistory.d.ts +5 -0
  50. package/dist/cjs/types/statusHistory.js +2 -0
  51. package/dist/cjs/types/supplier.d.ts +28 -0
  52. package/dist/cjs/types/supplier.js +3 -0
  53. package/dist/cjs/units.d.ts +22 -0
  54. package/dist/cjs/units.js +94 -0
  55. package/dist/mjs/api.d.ts +111 -0
  56. package/dist/mjs/api.js +308 -0
  57. package/dist/mjs/consumption.d.ts +14 -0
  58. package/dist/mjs/consumption.js +22 -0
  59. package/dist/mjs/db.d.ts +6 -0
  60. package/dist/mjs/db.js +53 -0
  61. package/dist/mjs/etainabl.d.ts +10 -0
  62. package/dist/mjs/etainabl.js +1 -0
  63. package/dist/mjs/index.d.ts +10 -0
  64. package/dist/mjs/index.js +10 -0
  65. package/dist/mjs/logger.d.ts +3 -0
  66. package/dist/mjs/logger.js +9 -0
  67. package/dist/mjs/monitoring.d.ts +1 -0
  68. package/dist/mjs/monitoring.js +15 -0
  69. package/dist/mjs/package.json +3 -0
  70. package/dist/mjs/reporting.d.ts +2 -0
  71. package/dist/mjs/reporting.js +62 -0
  72. package/dist/mjs/slack.d.ts +4 -0
  73. package/dist/mjs/slack.js +14 -0
  74. package/dist/mjs/types/account.d.ts +112 -0
  75. package/dist/mjs/types/account.js +1 -0
  76. package/dist/mjs/types/address.d.ts +11 -0
  77. package/dist/mjs/types/address.js +1 -0
  78. package/dist/mjs/types/asset.d.ts +122 -0
  79. package/dist/mjs/types/asset.js +2 -0
  80. package/dist/mjs/types/automation.d.ts +33 -0
  81. package/dist/mjs/types/automation.js +1 -0
  82. package/dist/mjs/types/company.d.ts +42 -0
  83. package/dist/mjs/types/company.js +1 -0
  84. package/dist/mjs/types/dataIngest.d.ts +8 -0
  85. package/dist/mjs/types/dataIngest.js +1 -0
  86. package/dist/mjs/types/email.d.ts +18 -0
  87. package/dist/mjs/types/email.js +1 -0
  88. package/dist/mjs/types/entity.d.ts +16 -0
  89. package/dist/mjs/types/entity.js +1 -0
  90. package/dist/mjs/types/index.d.ts +19 -0
  91. package/dist/mjs/types/index.js +1 -0
  92. package/dist/mjs/types/invoice.d.ts +118 -0
  93. package/dist/mjs/types/invoice.js +1 -0
  94. package/dist/mjs/types/log.d.ts +10 -0
  95. package/dist/mjs/types/log.js +1 -0
  96. package/dist/mjs/types/portal.d.ts +8 -0
  97. package/dist/mjs/types/portal.js +1 -0
  98. package/dist/mjs/types/reading.d.ts +17 -0
  99. package/dist/mjs/types/reading.js +1 -0
  100. package/dist/mjs/types/report.d.ts +21 -0
  101. package/dist/mjs/types/report.js +1 -0
  102. package/dist/mjs/types/scraperRun.d.ts +15 -0
  103. package/dist/mjs/types/scraperRun.js +1 -0
  104. package/dist/mjs/types/statusHistory.d.ts +5 -0
  105. package/dist/mjs/types/statusHistory.js +1 -0
  106. package/dist/mjs/types/supplier.d.ts +28 -0
  107. package/dist/mjs/types/supplier.js +2 -0
  108. package/dist/mjs/units.d.ts +22 -0
  109. package/dist/mjs/units.js +89 -0
  110. package/package.json +9 -4
@@ -0,0 +1,111 @@
1
+ import type { AxiosRequestConfig, AxiosInstance, CreateAxiosDefaults } from 'axios';
2
+ import type { Account, Asset, Automation, Entity, Company, DataIngest, Invoice, Log, Reading, Report, 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) => Promise<Account>;
20
+ listAccounts: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Account>>;
21
+ updateAccount: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
22
+ createAccount: (data: any, options?: AxiosRequestConfig) => Promise<any>;
23
+ removeAccount: (id: string, options?: AxiosRequestConfig) => Promise<any>;
24
+ getAccountSchema: (options?: AxiosRequestConfig) => Promise<any>;
25
+ invalidateAccountCache: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
26
+ getAsset: (id: string, options?: AxiosRequestConfig) => Promise<Asset>;
27
+ listAssets: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Asset>>;
28
+ updateAsset: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
29
+ createAsset: (data: any, options?: AxiosRequestConfig) => Promise<any>;
30
+ removeAsset: (id: string, options?: AxiosRequestConfig) => Promise<any>;
31
+ getAssetSchema: (options?: AxiosRequestConfig) => Promise<any>;
32
+ getAssetGroup: (id: string, options?: AxiosRequestConfig) => Promise<any>;
33
+ listAssetGroups: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
34
+ updateAssetGroup: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
35
+ createAssetGroup: (data: any, options?: AxiosRequestConfig) => Promise<any>;
36
+ removeAssetGroup: (id: string, options?: AxiosRequestConfig) => Promise<any>;
37
+ getAssetGroupAssets: (id: string, options?: AxiosRequestConfig) => Promise<any>;
38
+ getAssetGroupSchema: (options?: AxiosRequestConfig) => Promise<any>;
39
+ getAutomation: (id: string, options?: AxiosRequestConfig) => Promise<Automation>;
40
+ listAutomations: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Automation>>;
41
+ updateAutomation: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
42
+ createAutomation: (data: any, options?: AxiosRequestConfig) => Promise<any>;
43
+ removeAutomation: (id: string, options?: AxiosRequestConfig) => Promise<any>;
44
+ createAutomationLog: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
45
+ updateAutomationLog: (id: string, subId: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
46
+ removeAutomationLog: (id: string, subId: string, options?: AxiosRequestConfig) => Promise<any>;
47
+ getCompany: (id: string, options?: AxiosRequestConfig) => Promise<Company>;
48
+ getConsumption: (id: string, options?: AxiosRequestConfig) => Promise<any>;
49
+ listConsumptions: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
50
+ updateConsumption: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
51
+ createConsumption: (data: any, options?: AxiosRequestConfig) => Promise<any>;
52
+ removeConsumption: (id: string, options?: AxiosRequestConfig) => Promise<any>;
53
+ getConsumptionSchema: (options?: AxiosRequestConfig) => Promise<any>;
54
+ getEmail: (id: string, options?: AxiosRequestConfig) => Promise<any>;
55
+ listEmails: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
56
+ updateEmail: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
57
+ createEmail: (data: any, options?: AxiosRequestConfig) => Promise<any>;
58
+ removeEmail: (id: string, options?: AxiosRequestConfig) => Promise<any>;
59
+ getEmissionFactor: (id: string, options?: AxiosRequestConfig) => Promise<any>;
60
+ listEmissionFactors: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
61
+ updateEmissionFactor: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
62
+ createEmissionFactor: (data: any, options?: AxiosRequestConfig) => Promise<any>;
63
+ removeEmissionFactor: (id: string, options?: AxiosRequestConfig) => Promise<any>;
64
+ getEntity: (id: string, options?: AxiosRequestConfig) => Promise<Entity>;
65
+ listEntities: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Entity>>;
66
+ updateEntity: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
67
+ createEntity: (data: any, options?: AxiosRequestConfig) => Promise<any>;
68
+ removeEntity: (id: string, options?: AxiosRequestConfig) => Promise<any>;
69
+ getEntitiesSchema: (options?: AxiosRequestConfig) => Promise<any>;
70
+ getLog: (id: string, options?: AxiosRequestConfig) => Promise<Log>;
71
+ listLogs: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Log>>;
72
+ updateLog: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
73
+ createLog: (data: any, options?: AxiosRequestConfig) => Promise<any>;
74
+ removeLog: (id: string, options?: AxiosRequestConfig) => Promise<any>;
75
+ getReading: (id: string, options?: AxiosRequestConfig) => Promise<Reading>;
76
+ listReadings: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Reading>>;
77
+ updateReading: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
78
+ createReading: (data: any, options?: AxiosRequestConfig) => Promise<any>;
79
+ removeReading: (id: string, options?: AxiosRequestConfig) => Promise<any>;
80
+ getReadingSchema: (options?: AxiosRequestConfig) => Promise<any>;
81
+ getReport: (id: string, options?: AxiosRequestConfig) => Promise<Report>;
82
+ listReports: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Report>>;
83
+ updateReport: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
84
+ createReport: (data: any, options?: AxiosRequestConfig) => Promise<any>;
85
+ removeReport: (id: string, options?: AxiosRequestConfig) => Promise<any>;
86
+ sendReport: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
87
+ getReportTemplate: (id: string, options?: AxiosRequestConfig) => Promise<any>;
88
+ listReportTemplates: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
89
+ updateReportTemplate: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
90
+ createReportTemplate: (data: any, options?: AxiosRequestConfig) => Promise<any>;
91
+ removeReportTemplate: (id: string, options?: AxiosRequestConfig) => Promise<any>;
92
+ getScheduledReport: (id: string, options?: AxiosRequestConfig) => Promise<any>;
93
+ listScheduledReports: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<any>>;
94
+ updateScheduledReport: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
95
+ createScheduledReport: (data: any, options?: AxiosRequestConfig) => Promise<any>;
96
+ removeScheduledReport: (id: string, options?: AxiosRequestConfig) => Promise<any>;
97
+ sendScheduledReport: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
98
+ getInvoice: (id: string, options?: AxiosRequestConfig) => Promise<Invoice>;
99
+ listInvoices: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Invoice>>;
100
+ updateInvoice: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
101
+ createInvoice: (data: any, options?: AxiosRequestConfig) => Promise<any>;
102
+ removeInvoice: (id: string, options?: AxiosRequestConfig) => Promise<any>;
103
+ getInvoiceSchema: (options?: AxiosRequestConfig) => Promise<any>;
104
+ listSuppliers: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<Supplier>>;
105
+ getSupplierSchema: (options?: AxiosRequestConfig) => Promise<any>;
106
+ getImportTemplate: (id: string, options?: AxiosRequestConfig) => Promise<any>;
107
+ updateDataIngest: (id: string, data: any, options?: AxiosRequestConfig) => Promise<any>;
108
+ createDataIngest: (data: any, options?: AxiosRequestConfig) => Promise<any>;
109
+ listDataIngest: (options?: AxiosRequestConfig) => Promise<ETNPagedResponse<DataIngest>>;
110
+ };
111
+ export default _default;
@@ -0,0 +1,318 @@
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_1, ...args_1) => __awaiter(void 0, [id_1, ...args_1], void 0, function* (id, options = {}) {
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) => (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (options = {}) {
56
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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) => (...args_1) => __awaiter(void 0, [...args_1], void 0, function* (options = {}) {
76
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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_1, data_1, ...args_1) => __awaiter(void 0, [id_1, data_1, ...args_1], void 0, function* (id, data, options = {}) {
96
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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_1, ...args_1) => __awaiter(void 0, [data_1, ...args_1], void 0, function* (data, options = {}) {
115
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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_1, ...args_1) => __awaiter(void 0, [id_1, ...args_1], void 0, function* (id, options = {}) {
134
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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_1, data_1, ...args_1) => __awaiter(void 0, [id_1, data_1, ...args_1], void 0, function* (id, data, options = {}) {
153
+ var _a;
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 ((_a = e.response) === null || _a === void 0 ? void 0 : _a.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_1, data_1, ...args_1) => __awaiter(void 0, [id_1, data_1, ...args_1], void 0, function* (id, data, options = {}) {
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_1, subId_1, data_1, ...args_1) => __awaiter(void 0, [id_1, subId_1, data_1, ...args_1], void 0, function* (id, subId, data, options = {}) {
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_1, subId_1, ...args_1) => __awaiter(void 0, [id_1, subId_1, ...args_1], void 0, function* (id, subId, options = {}) {
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
+ invalidateAccountCache: factory.customWithId(etainablApi, 'put', 'accounts', 'invalidate-cache'),
211
+ // assets
212
+ getAsset: factory.getWithId(etainablApi, 'assets'),
213
+ listAssets: factory.list(etainablApi, 'assets'),
214
+ updateAsset: factory.update(etainablApi, 'assets'),
215
+ createAsset: factory.create(etainablApi, 'assets'),
216
+ removeAsset: factory.remove(etainablApi, 'assets'),
217
+ getAssetSchema: factory.get(etainablApi, 'assets', 'schema'),
218
+ // assetGroups
219
+ getAssetGroup: factory.getWithId(etainablApi, 'asset-groups'),
220
+ listAssetGroups: factory.list(etainablApi, 'asset-groups'),
221
+ updateAssetGroup: factory.update(etainablApi, 'asset-groups'),
222
+ createAssetGroup: factory.create(etainablApi, 'asset-groups'),
223
+ removeAssetGroup: factory.remove(etainablApi, 'asset-groups'),
224
+ getAssetGroupAssets: factory.getWithId(etainablApi, 'asset-groups', 'assets'),
225
+ getAssetGroupSchema: factory.get(etainablApi, 'asset-groups', 'schema'),
226
+ // automation
227
+ getAutomation: factory.getWithId(etainablApi, 'automation'),
228
+ listAutomations: factory.list(etainablApi, 'automation'),
229
+ updateAutomation: factory.update(etainablApi, 'automation'),
230
+ createAutomation: factory.create(etainablApi, 'automation'),
231
+ removeAutomation: factory.remove(etainablApi, 'automation'),
232
+ createAutomationLog: subFactory.create(etainablApi, 'automation', 'logs'),
233
+ updateAutomationLog: subFactory.update(etainablApi, 'automation', 'logs'),
234
+ removeAutomationLog: subFactory.remove(etainablApi, 'automation', 'logs'),
235
+ // company
236
+ getCompany: factory.getWithId(etainablApi, 'companies'),
237
+ // consumption
238
+ getConsumption: factory.getWithId(etainablApi, 'consumptions'),
239
+ listConsumptions: factory.list(etainablApi, 'consumptions'),
240
+ updateConsumption: factory.update(etainablApi, 'consumptions'),
241
+ createConsumption: factory.create(etainablApi, 'consumptions'),
242
+ removeConsumption: factory.remove(etainablApi, 'consumptions'),
243
+ getConsumptionSchema: factory.get(etainablApi, 'consumptions', 'schema'),
244
+ // emails
245
+ getEmail: factory.getWithId(etainablApi, 'emails'),
246
+ listEmails: factory.list(etainablApi, 'emails'),
247
+ updateEmail: factory.update(etainablApi, 'emails'),
248
+ createEmail: factory.create(etainablApi, 'emails'),
249
+ removeEmail: factory.remove(etainablApi, 'emails'),
250
+ // emission factors
251
+ getEmissionFactor: factory.getWithId(etainablApi, 'emission-factors'),
252
+ listEmissionFactors: factory.list(etainablApi, 'emission-factors'),
253
+ updateEmissionFactor: factory.update(etainablApi, 'emission-factors'),
254
+ createEmissionFactor: factory.create(etainablApi, 'emission-factors'),
255
+ removeEmissionFactor: factory.remove(etainablApi, 'emission-factors'),
256
+ // entity
257
+ getEntity: factory.getWithId(etainablApi, 'entities'),
258
+ listEntities: factory.list(etainablApi, 'entities'),
259
+ updateEntity: factory.update(etainablApi, 'entities'),
260
+ createEntity: factory.create(etainablApi, 'entities'),
261
+ removeEntity: factory.remove(etainablApi, 'entities'),
262
+ getEntitiesSchema: factory.get(etainablApi, 'entities', 'schema'),
263
+ // logs
264
+ getLog: factory.getWithId(etainablApi, 'logs'),
265
+ listLogs: factory.list(etainablApi, 'logs'),
266
+ updateLog: factory.update(etainablApi, 'logs'),
267
+ createLog: factory.create(etainablApi, 'logs'),
268
+ removeLog: factory.remove(etainablApi, 'logs'),
269
+ // readings
270
+ getReading: factory.getWithId(etainablApi, 'readings'),
271
+ listReadings: factory.list(etainablApi, 'readings'),
272
+ updateReading: factory.update(etainablApi, 'readings'),
273
+ createReading: factory.create(etainablApi, 'readings'),
274
+ removeReading: factory.remove(etainablApi, 'readings'),
275
+ getReadingSchema: factory.get(etainablApi, 'readings', 'schema'),
276
+ // reports
277
+ getReport: factory.getWithId(etainablApi, 'reports'),
278
+ listReports: factory.list(etainablApi, 'reports'),
279
+ updateReport: factory.update(etainablApi, 'reports'),
280
+ createReport: factory.create(etainablApi, 'reports'),
281
+ removeReport: factory.remove(etainablApi, 'reports'),
282
+ sendReport: factory.customWithId(etainablApi, 'post', 'reports', 'send'),
283
+ // report templates
284
+ getReportTemplate: factory.getWithId(etainablApi, 'report-templates'),
285
+ listReportTemplates: factory.list(etainablApi, 'report-templates'),
286
+ updateReportTemplate: factory.update(etainablApi, 'report-templates'),
287
+ createReportTemplate: factory.create(etainablApi, 'report-templates'),
288
+ removeReportTemplate: factory.remove(etainablApi, 'report-templates'),
289
+ // scheduled reports
290
+ getScheduledReport: factory.getWithId(etainablApi, 'scheduled-reports'),
291
+ listScheduledReports: factory.list(etainablApi, 'scheduled-reports'),
292
+ updateScheduledReport: factory.update(etainablApi, 'scheduled-reports'),
293
+ createScheduledReport: factory.create(etainablApi, 'scheduled-reports'),
294
+ removeScheduledReport: factory.remove(etainablApi, 'scheduled-reports'),
295
+ sendScheduledReport: factory.customWithId(etainablApi, 'post', 'scheduled-reports', 'send'),
296
+ // invoices
297
+ getInvoice: factory.getWithId(etainablApi, 'invoices'),
298
+ listInvoices: factory.list(etainablApi, 'invoices'),
299
+ updateInvoice: factory.update(etainablApi, 'invoices'),
300
+ createInvoice: factory.create(etainablApi, 'invoices'),
301
+ removeInvoice: factory.remove(etainablApi, 'invoices'),
302
+ getInvoiceSchema: factory.get(etainablApi, 'invoices', 'schema'),
303
+ //suppliers
304
+ listSuppliers: factory.list(etainablApi, 'suppliers'),
305
+ getSupplierSchema: factory.get(etainablApi, 'suppliers', 'schema'),
306
+ // import templates
307
+ getImportTemplate: factory.getWithId(etainablApi, 'import-templates'),
308
+ //data imports
309
+ updateDataIngest: factory.update(etainablApi, 'data-ingests'),
310
+ createDataIngest: factory.create(etainablApi, 'data-ingests'),
311
+ listDataIngest: factory.list(etainablApi, 'data-ingests'),
312
+ };
313
+ }
314
+ catch (e) {
315
+ log.error(e);
316
+ throw e;
317
+ }
318
+ };
@@ -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(retryAttempt?: number): Promise<Db>;
3
+ declare const _default: {
4
+ connectToDatabase: typeof connectToDatabase;
5
+ };
6
+ export default _default;
package/dist/cjs/db.js ADDED
@@ -0,0 +1,69 @@
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, arguments, void 0, function* (retryAttempt = 1) {
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
+ const uri = `mongodb+srv://${process.env.ETAINABL_DB_URL}`;
32
+ try {
33
+ if (process.env.DB_BASIC_AUTH === 'true') {
34
+ log.debug('Connecting to MongoDB server... (Auth: Basic)');
35
+ const client = new mongodb_1.MongoClient(uri);
36
+ yield client.connect();
37
+ log.debug('Connected successfully to MongoDB server! (Auth: Basic)');
38
+ cachedDb = client.db('etainabl');
39
+ return cachedDb;
40
+ }
41
+ log.debug('Connecting to MongoDB server... (Auth: AWS)');
42
+ const client = new mongodb_1.MongoClient(uri, {
43
+ auth: {
44
+ username: process.env.AWS_ACCESS_KEY_ID,
45
+ password: process.env.AWS_SECRET_ACCESS_KEY
46
+ },
47
+ authSource: '$external',
48
+ authMechanism: 'MONGODB-AWS'
49
+ });
50
+ yield client.connect();
51
+ log.debug('Connected successfully to MongoDB server! (Auth: AWS)');
52
+ cachedDb = client.db('etainabl');
53
+ return cachedDb;
54
+ }
55
+ catch (e) {
56
+ // Retry
57
+ if (retryAttempt > 5) {
58
+ console.log(`Error connecting to MongoDB server after 5 attempts...`);
59
+ throw e;
60
+ }
61
+ console.log(`MongoDB Connection error: ${e.message}`);
62
+ console.log(`Error connecting to MongoDB server... Retrying in 3 seconds... (Attempt ${retryAttempt})`);
63
+ return connectToDatabase(retryAttempt + 1);
64
+ }
65
+ });
66
+ }
67
+ exports.default = {
68
+ connectToDatabase
69
+ };
@@ -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,10 @@
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
+ export { api, logger, consumption, monitoring, db, slack, units, reporting };
10
+ export * from './types/index.js';
@@ -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[];