@etainabl/nodejs-sdk 1.2.15 → 1.2.16
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/api.d.ts +98 -0
- package/dist/cjs/api.js +303 -0
- package/dist/cjs/consumption.d.ts +14 -0
- package/dist/cjs/consumption.js +32 -0
- package/dist/cjs/db.d.ts +6 -0
- package/dist/cjs/db.js +49 -0
- package/dist/cjs/etainabl.d.ts +10 -0
- package/dist/cjs/etainabl.js +2 -0
- package/dist/cjs/index.d.ts +9 -0
- package/dist/cjs/index.js +45 -0
- package/dist/cjs/logger.d.ts +3 -0
- package/dist/cjs/logger.js +14 -0
- package/dist/cjs/monitoring.d.ts +1 -0
- package/dist/cjs/monitoring.js +31 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/reporting.d.ts +2 -0
- package/dist/cjs/reporting.js +69 -0
- package/dist/cjs/slack.d.ts +4 -0
- package/dist/cjs/slack.js +28 -0
- package/dist/cjs/units.d.ts +22 -0
- package/dist/cjs/units.js +92 -0
- package/dist/mjs/package.json +3 -0
- package/package.json +1 -1
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { AxiosRequestConfig, AxiosInstance, CreateAxiosDefaults } from 'axios';
|
|
2
|
+
export interface ETNPagedResponse {
|
|
3
|
+
data: any[];
|
|
4
|
+
total: number;
|
|
5
|
+
limit: number;
|
|
6
|
+
skip: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ETNReq {
|
|
9
|
+
method: string;
|
|
10
|
+
url: string;
|
|
11
|
+
}
|
|
12
|
+
interface AuthOptions {
|
|
13
|
+
key?: string;
|
|
14
|
+
token?: string;
|
|
15
|
+
}
|
|
16
|
+
declare const _default: (auth: AuthOptions, instanceOptions?: CreateAxiosDefaults) => {
|
|
17
|
+
instance: AxiosInstance;
|
|
18
|
+
getAccount: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
19
|
+
listAccounts: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
20
|
+
updateAccount: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
21
|
+
createAccount: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
22
|
+
removeAccount: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
23
|
+
getAccountSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
24
|
+
getAsset: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
25
|
+
listAssets: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
26
|
+
updateAsset: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
27
|
+
createAsset: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
28
|
+
removeAsset: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
29
|
+
getAssetSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
30
|
+
getAssetGroup: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
31
|
+
listAssetGroups: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
32
|
+
updateAssetGroup: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
33
|
+
createAssetGroup: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
34
|
+
removeAssetGroup: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
35
|
+
getAssetGroupAssets: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
36
|
+
getAssetGroupSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
37
|
+
getAutomation: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
38
|
+
listAutomations: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
39
|
+
updateAutomation: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
40
|
+
createAutomation: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
41
|
+
removeAutomation: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
42
|
+
createAutomationLog: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
43
|
+
updateAutomationLog: (id: string, subId: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
44
|
+
removeAutomationLog: (id: string, subId: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
45
|
+
getCompany: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
46
|
+
getConsumption: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
47
|
+
listConsumptions: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
48
|
+
updateConsumption: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
49
|
+
createConsumption: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
50
|
+
removeConsumption: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
51
|
+
getConsumptionSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
52
|
+
getEmail: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
53
|
+
listEmails: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
54
|
+
updateEmail: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
55
|
+
createEmail: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
56
|
+
removeEmail: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
57
|
+
getEmissionFactor: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
58
|
+
listEmissionFactors: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
59
|
+
updateEmissionFactor: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
60
|
+
createEmissionFactor: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
61
|
+
removeEmissionFactor: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
62
|
+
getLog: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
63
|
+
listLogs: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
64
|
+
updateLog: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
65
|
+
createLog: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
66
|
+
removeLog: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
67
|
+
getReading: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
68
|
+
listReadings: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
69
|
+
updateReading: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
70
|
+
createReading: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
71
|
+
removeReading: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
72
|
+
getReadingSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
73
|
+
getReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
74
|
+
listReports: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
75
|
+
updateReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
76
|
+
createReport: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
77
|
+
removeReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
78
|
+
sendReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
79
|
+
getReportTemplate: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
80
|
+
listReportTemplates: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
81
|
+
updateReportTemplate: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
82
|
+
createReportTemplate: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
83
|
+
removeReportTemplate: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
84
|
+
getScheduledReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
85
|
+
listScheduledReports: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
86
|
+
updateScheduledReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
87
|
+
createScheduledReport: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
88
|
+
removeScheduledReport: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
89
|
+
sendScheduledReport: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
90
|
+
getInvoice: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
91
|
+
listInvoices: (options?: AxiosRequestConfig<any>) => Promise<ETNPagedResponse>;
|
|
92
|
+
updateInvoice: (id: string, data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
93
|
+
createInvoice: (data: any, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
94
|
+
removeInvoice: (id: string, options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
95
|
+
getInvoiceSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
96
|
+
getSupplierSchema: (options?: AxiosRequestConfig<any>) => Promise<any>;
|
|
97
|
+
};
|
|
98
|
+
export default _default;
|
package/dist/cjs/api.js
ADDED
|
@@ -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.ETAINABL_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;
|
package/dist/cjs/db.d.ts
ADDED
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,9 @@
|
|
|
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 };
|
|
@@ -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,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,69 @@
|
|
|
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.getScheduledReportRunTimes = void 0;
|
|
7
|
+
const moment_1 = __importDefault(require("moment"));
|
|
8
|
+
moment_1.default.locale('en', {
|
|
9
|
+
week: {
|
|
10
|
+
dow: 1
|
|
11
|
+
}
|
|
12
|
+
});
|
|
13
|
+
const getNextRunTime = (startDate, schedule, taskTime) => {
|
|
14
|
+
const [num, freq] = schedule.frequency.split('|');
|
|
15
|
+
const targetDate = (0, moment_1.default)(startDate).add(num, freq);
|
|
16
|
+
if (schedule.frequencyPeriod === 'first') {
|
|
17
|
+
targetDate.startOf(freq);
|
|
18
|
+
}
|
|
19
|
+
else if (schedule.frequencyPeriod === 'last') {
|
|
20
|
+
targetDate.endOf(freq);
|
|
21
|
+
}
|
|
22
|
+
const isWeekday = targetDate.isoWeekday() > 0 && targetDate.isoWeekday() < 6;
|
|
23
|
+
const isSaturday = targetDate.isoWeekday() === 6;
|
|
24
|
+
// The weekday or weekend chosen should be within the same month as the target date
|
|
25
|
+
if (schedule.frequencyDay === 'weekdays' && !isWeekday) {
|
|
26
|
+
if ((targetDate.date() / 7) < 2) {
|
|
27
|
+
targetDate.add(isSaturday ? 2 : 1, 'days');
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
targetDate.subtract(isSaturday ? 1 : 2, 'days');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
else if (schedule.frequencyDay === 'weekends' && isWeekday) {
|
|
34
|
+
if ((targetDate.date() / 7) < 2) {
|
|
35
|
+
targetDate.isoWeekday(6);
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
targetDate.isoWeekday(0);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (taskTime.isAfter(targetDate, 'minute')) {
|
|
42
|
+
return getNextRunTime(targetDate, schedule, taskTime);
|
|
43
|
+
}
|
|
44
|
+
return targetDate;
|
|
45
|
+
};
|
|
46
|
+
const getScheduledReportRunTimes = (schedule, limit = 1, taskTime = (0, moment_1.default)()) => {
|
|
47
|
+
if (!schedule.startDate || !schedule.enabled)
|
|
48
|
+
return [];
|
|
49
|
+
const originalStartDate = moment_1.default.utc(schedule.startDate);
|
|
50
|
+
let startDate = originalStartDate;
|
|
51
|
+
const includeStartDate = taskTime.isSameOrBefore(originalStartDate, 'minute');
|
|
52
|
+
let runTimes = [];
|
|
53
|
+
if (includeStartDate) {
|
|
54
|
+
runTimes = [originalStartDate];
|
|
55
|
+
}
|
|
56
|
+
const [, freq] = schedule.frequency.split('|');
|
|
57
|
+
if (freq === 'once') {
|
|
58
|
+
const nextRunTime = runTimes[0];
|
|
59
|
+
// If this is now beyond the start date, return an empty array
|
|
60
|
+
return taskTime.isAfter(nextRunTime, 'minute') ? [] : runTimes;
|
|
61
|
+
}
|
|
62
|
+
const scheduleRunTimes = Array.from(Array(includeStartDate ? limit - 1 : limit).keys()).map(() => {
|
|
63
|
+
const nextRunTime = getNextRunTime(startDate, schedule, taskTime);
|
|
64
|
+
startDate = nextRunTime.hour(originalStartDate.hour()).minute(originalStartDate.minute());
|
|
65
|
+
return nextRunTime;
|
|
66
|
+
});
|
|
67
|
+
return [...runTimes, ...scheduleRunTimes];
|
|
68
|
+
};
|
|
69
|
+
exports.getScheduledReportRunTimes = getScheduledReportRunTimes;
|
|
@@ -0,0 +1,28 @@
|
|
|
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 postMessage = (message) => __awaiter(void 0, void 0, void 0, function* () {
|
|
17
|
+
const url = 'https://hooks.slack.com/services/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';
|
|
18
|
+
const data = {
|
|
19
|
+
text: `[${(process.env.ENV || '').toUpperCase()}][${process.env.AWS_LAMBDA_FUNCTION_NAME}] ${message}`
|
|
20
|
+
};
|
|
21
|
+
const headers = {
|
|
22
|
+
'Content-Type': 'application/json'
|
|
23
|
+
};
|
|
24
|
+
return axios_1.default.post(url, data, { headers });
|
|
25
|
+
});
|
|
26
|
+
exports.default = {
|
|
27
|
+
postMessage
|
|
28
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
interface Item {
|
|
2
|
+
units?: string | null;
|
|
3
|
+
unit?: string | null;
|
|
4
|
+
factor?: number | null;
|
|
5
|
+
value: number;
|
|
6
|
+
[key: string]: any;
|
|
7
|
+
}
|
|
8
|
+
export type AccountType = 'electricity' | 'gas' | 'water' | 'waste' | 'solar' | 'heating' | 'flow' | 'cooling' | 'temperature' | 'other';
|
|
9
|
+
export type ETNUnit = 'kwh' | 'kg' | 'm3' | 'lbs' | 'tonnes' | 'wh' | 'mwh' | 'ft3' | 'hcf' | 'm3/h' | 'qty' | 'l' | 'C' | 'mcuf' | 'hcuf' | 'tcuf' | 'ocuf' | 'hm3' | 'tm3' | 'nm3';
|
|
10
|
+
export type BaseUnit = 'kwh' | 'm3' | 'C' | 'kg' | 'm3/h';
|
|
11
|
+
export declare const accountTypeMap: {
|
|
12
|
+
[key: string]: BaseUnit;
|
|
13
|
+
};
|
|
14
|
+
export declare const accountTypeUnitMap: {
|
|
15
|
+
[key: string]: ETNUnit[];
|
|
16
|
+
};
|
|
17
|
+
export declare const convertItems: (items: Item[], type: AccountType, defaultUnits: ETNUnit | undefined, accountFactor: number | undefined) => any;
|
|
18
|
+
export declare const checkAccountTypeVsUnits: (type: string, unit: string, additionalLog?: number | '') => {
|
|
19
|
+
type: AccountType;
|
|
20
|
+
unit: ETNUnit;
|
|
21
|
+
};
|
|
22
|
+
export {};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.checkAccountTypeVsUnits = exports.convertItems = exports.accountTypeUnitMap = exports.accountTypeMap = void 0;
|
|
4
|
+
exports.accountTypeMap = {
|
|
5
|
+
electricity: 'kwh',
|
|
6
|
+
gas: 'kwh',
|
|
7
|
+
water: 'm3',
|
|
8
|
+
waste: 'kg',
|
|
9
|
+
solar: 'kwh',
|
|
10
|
+
heating: 'kwh',
|
|
11
|
+
flow: 'm3/h',
|
|
12
|
+
cooling: 'kwh',
|
|
13
|
+
temperature: 'C'
|
|
14
|
+
};
|
|
15
|
+
const unitConversionFactors = {
|
|
16
|
+
kwh: {
|
|
17
|
+
kwh: 1,
|
|
18
|
+
mwh: 1000,
|
|
19
|
+
wh: 0.001,
|
|
20
|
+
m3: (39 * 1.02264) / 3.6,
|
|
21
|
+
ft3: (0.0283 * 39 * 1.02264) / 3.6,
|
|
22
|
+
hcf: (2.83 * 39 * 1.02264) / 3.6
|
|
23
|
+
},
|
|
24
|
+
m3: {
|
|
25
|
+
m3: 1,
|
|
26
|
+
l: 0.001
|
|
27
|
+
},
|
|
28
|
+
C: {
|
|
29
|
+
C: 1
|
|
30
|
+
},
|
|
31
|
+
kg: {
|
|
32
|
+
kg: 1,
|
|
33
|
+
lbs: 0.45359237,
|
|
34
|
+
tonnes: 1000
|
|
35
|
+
},
|
|
36
|
+
'm3/h': {
|
|
37
|
+
'm3/h': 1
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
exports.accountTypeUnitMap = {
|
|
41
|
+
electricity: ['kwh', 'mwh', 'wh'],
|
|
42
|
+
gas: ['kwh', 'm3', 'ft3', 'hcf'],
|
|
43
|
+
water: ['m3', 'l'],
|
|
44
|
+
waste: ['kg', 'lbs', 'tonnes'],
|
|
45
|
+
solar: ['kwh', 'mwh', 'wh'],
|
|
46
|
+
heating: ['kwh', 'mwh', 'wh'],
|
|
47
|
+
flow: ['m3/h'],
|
|
48
|
+
cooling: ['kwh', 'mwh', 'wh'],
|
|
49
|
+
temperature: ['C']
|
|
50
|
+
};
|
|
51
|
+
// Convert units to base format
|
|
52
|
+
const convertItems = (items, type, defaultUnits, accountFactor) => {
|
|
53
|
+
if (!type)
|
|
54
|
+
throw new Error('Account type is required');
|
|
55
|
+
const baseUnit = exports.accountTypeMap[type];
|
|
56
|
+
if (!baseUnit)
|
|
57
|
+
throw new Error(`Account type ${type} is not supported`);
|
|
58
|
+
const convertedItems = items.map(item => {
|
|
59
|
+
const factor = item.factor || accountFactor || 1;
|
|
60
|
+
const units = item.units || item.unit || defaultUnits || baseUnit;
|
|
61
|
+
const convertedValue = item.value * _getConversionFactor(units, baseUnit) * factor;
|
|
62
|
+
return Object.assign(Object.assign({}, item), { value: convertedValue, units: baseUnit });
|
|
63
|
+
});
|
|
64
|
+
return convertedItems;
|
|
65
|
+
};
|
|
66
|
+
exports.convertItems = convertItems;
|
|
67
|
+
const _getConversionFactor = (fromUnit = 'kwh', toUnit) => {
|
|
68
|
+
const conversionFactors = unitConversionFactors[toUnit];
|
|
69
|
+
if (!conversionFactors) {
|
|
70
|
+
throw new Error(`Conversion factor base unit ${toUnit} is not defined`);
|
|
71
|
+
}
|
|
72
|
+
if (!conversionFactors[fromUnit]) {
|
|
73
|
+
throw new Error(`Conversion factor from unit ${fromUnit} is not defined`);
|
|
74
|
+
}
|
|
75
|
+
return conversionFactors[fromUnit];
|
|
76
|
+
};
|
|
77
|
+
const checkAccountTypeVsUnits = (type, unit, additionalLog = '') => {
|
|
78
|
+
if (!type)
|
|
79
|
+
throw new Error('Account type is required');
|
|
80
|
+
if (!unit)
|
|
81
|
+
throw new Error('Unit is required');
|
|
82
|
+
const parsedType = type.toLowerCase().trim();
|
|
83
|
+
const accountTypeUnits = exports.accountTypeUnitMap[parsedType];
|
|
84
|
+
if (!accountTypeUnits)
|
|
85
|
+
throw new Error(`Account type "${parsedType}" is not supported ${additionalLog}`);
|
|
86
|
+
const parsedUnit = unit.toLowerCase().trim();
|
|
87
|
+
if (!accountTypeUnits.includes(parsedUnit)) {
|
|
88
|
+
throw new Error(`Account type "${parsedType}" does not support unit "${parsedUnit}" ${additionalLog}`);
|
|
89
|
+
}
|
|
90
|
+
return { type: parsedType, unit: parsedUnit };
|
|
91
|
+
};
|
|
92
|
+
exports.checkAccountTypeVsUnits = checkAccountTypeVsUnits;
|