@nexgen-os/ores 0.0.0-stage → 0.5.0
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/LICENSE +21 -0
- package/README.md +111 -2
- package/dist/index.d.ts +79 -0
- package/dist/index.js +200 -0
- package/package.json +36 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nexgen OS contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,112 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@nexgen-os/ores`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[ORES](https://www.ores.be), the main distribution operator of Wallonia, as
|
|
4
|
+
a meter data connector of Nexgen OS, on its **API for energy service
|
|
5
|
+
providers** (third-party data access,
|
|
6
|
+
`https://edap.ores.be/b2b/tpda/v1/api/external/v1`;
|
|
7
|
+
[guide](https://media.ores.be/ores-cms/i0ghhud2/utilisation-des-api-tpda-ores-2026.pdf)).
|
|
8
|
+
An energy service provider signs a data access contract with the operator
|
|
9
|
+
(a standard contract approved by the regulator; `tpda@ores.be`); the
|
|
10
|
+
customer then consents in their own My ORES space, and the operator opens
|
|
11
|
+
the quarter-hour energy of the meter, with up to three years of history.
|
|
12
|
+
The data arrives the day after it is measured: this is the reference curve
|
|
13
|
+
of a meter, not a live feed. MIT.
|
|
14
|
+
|
|
15
|
+
## The path of a load curve
|
|
16
|
+
|
|
17
|
+
1. **Consent.** `consentLink({ referenceNumber, flow, dataPeriodFrom })`
|
|
18
|
+
(`POST /shortUrlIdentifier`) gives the page of My ORES the customer
|
|
19
|
+
follows (`https://www.myores.be/tpda/<id>`), valid five days. One
|
|
20
|
+
reference serves one customer, who may share up to `numberOfEans`
|
|
21
|
+
metering points under it and may shorten the period asked. The
|
|
22
|
+
installation records a mandate on each meter (`grid.request_mandate()`)
|
|
23
|
+
with the `referenceNumber` as its `external_reference`.
|
|
24
|
+
2. **Follow it.** `mandates(referenceNumber, ean?)` (`GET /mandates`) lists
|
|
25
|
+
the mandates given under the reference, one per metering point,
|
|
26
|
+
direction and granularity; `oresMandateStatus()` says what the
|
|
27
|
+
operator's statuses mean for the mandate of the `grid` module:
|
|
28
|
+
`Approved` → `approved` (`grid.decide_mandate()`), `Rejected` →
|
|
29
|
+
`refused`, `Finished` → `expired`, and a renewal the customer let pass
|
|
30
|
+
(`renewalStatus` `Expired`) → `expired`. A mandate is renewed every
|
|
31
|
+
three years; the operator writes to the customer a month before. Only
|
|
32
|
+
the customer ends a mandate.
|
|
33
|
+
3. **Read.** `collectMeterReadings(db, ores({ … }), { connectorId, meterId,
|
|
34
|
+
from, to, step: 'PT15M' })` of `@nexgen-os/core` asks the one mandate
|
|
35
|
+
check (`grid.authorise_reading()`) first, then calls `readings()`,
|
|
36
|
+
which:
|
|
37
|
+
- refuses without the mandate the check returned (`mandate_missing`) or
|
|
38
|
+
without its reference (`mandate_reference_missing`), a step other than
|
|
39
|
+
the quarter hour (`step_unsupported`), an EAN that is not 18 digits
|
|
40
|
+
(`invalid_identifier`), and a hub without its zone
|
|
41
|
+
(`time_zone_required`);
|
|
42
|
+
- asks `GET /mandates/energy` by reference and EAN for the days `from`
|
|
43
|
+
to `to` (`to` excluded), each day from midnight in the hub's zone, by
|
|
44
|
+
the date of the reading (`periodType=readTime`), seven days per call
|
|
45
|
+
(`ORES_DAYS_PER_CALL`, the operator's limit): a year is 53 calls;
|
|
46
|
+
- returns the meter's `offtake_energy` and `injection_energy`, kWh per
|
|
47
|
+
quarter hour, each value dated at the start of its step in UTC, with
|
|
48
|
+
the quality the pack maps the value's `validationState` to.
|
|
49
|
+
|
|
50
|
+
| From the answer | Series of the meter |
|
|
51
|
+
|---|---|
|
|
52
|
+
| `quarterHourlyEnergy[].measurements[0].offtake.total` | `offtake_energy`, kWh, 15 minutes |
|
|
53
|
+
| `quarterHourlyEnergy[].measurements[0].injection.total` | `injection_energy`, kWh, 15 minutes |
|
|
54
|
+
|
|
55
|
+
The quarter hours sit under the physical meters of a digital meter and on
|
|
56
|
+
the metering point itself for a meter read remotely (AMR); both are read.
|
|
57
|
+
The answers have the shape of the API the Flemish operator runs, so one
|
|
58
|
+
reader serves both connectors: `energySeries()` of
|
|
59
|
+
[`@nexgen-os/fluvius`](../fluvius/README.md).
|
|
60
|
+
|
|
61
|
+
The hub's conventions are the be pack's row of the operator
|
|
62
|
+
(`grid.operators.meter_data` of `ores`): its zone, its step, its three
|
|
63
|
+
years of history and its quality table — `READ` and `VAL` a measured value,
|
|
64
|
+
`EST` an estimated one, `NVAL` a value not validated yet, kept under the
|
|
65
|
+
pack's own code. A state the table does not hold is refused by name
|
|
66
|
+
(`quality_unknown`) rather than guessed.
|
|
67
|
+
|
|
68
|
+
## Configuration
|
|
69
|
+
|
|
70
|
+
An organisation's `connectors` row names the source
|
|
71
|
+
`ores_service_provider_api` (the be pack's), its secrets by `secret_ref`
|
|
72
|
+
(the vault holds them; the caller resolves them and passes them as
|
|
73
|
+
`credentials`, the connector reads no environment), and in `config`:
|
|
74
|
+
|
|
75
|
+
| Key | What |
|
|
76
|
+
|---|---|
|
|
77
|
+
| `contract_number` | the service provider's data access contract number, which every consent link names |
|
|
78
|
+
| `return_url_success`, `return_url_failed` | where My ORES sends the customer back, on a domain the operator validated at the contract; a domain may not carry the operator's name |
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
const client = ores({
|
|
82
|
+
credentials: { subscriptionKey, certificate, privateKey }, // from the vault
|
|
83
|
+
contractNumber: config.contract_number,
|
|
84
|
+
returnUrlSuccess: config.return_url_success, returnUrlFailed: config.return_url_failed,
|
|
85
|
+
});
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Every call carries the gateway's subscription key
|
|
89
|
+
(`Ocp-Apim-Subscription-Key`). The operator asks the service provider for a
|
|
90
|
+
certificate of a recognised authority (DV, OV, EV or S/MIME, RSA 256 or
|
|
91
|
+
512, valid 398 days at most, allowing client authentication; never
|
|
92
|
+
self-signed) and registers it before the integration starts: given with its
|
|
93
|
+
key, it is presented on the connection (`certificateFetch()`). The operator
|
|
94
|
+
sends no reminder before a certificate lapses; renewing it in time is the
|
|
95
|
+
service provider's.
|
|
96
|
+
|
|
97
|
+
## What is not done yet
|
|
98
|
+
|
|
99
|
+
- The answers in `tests/fixtures` follow the shapes of the operator's
|
|
100
|
+
guide, with made-up identifiers and values, and the guide does not say
|
|
101
|
+
how the registered certificate is presented beyond its requirements:
|
|
102
|
+
record real answers at the onboarding, keep them beside these, and settle
|
|
103
|
+
the transport on what the operator confirms; the tests must pass
|
|
104
|
+
unchanged.
|
|
105
|
+
- Daily energy (`DAILY`, with its day and night registers), gas, the
|
|
106
|
+
reactive energy of a meter read remotely, and the reading by insertion
|
|
107
|
+
time (`periodType=insertTime`, the sliding window the guide advises once
|
|
108
|
+
the history is in) are not read yet.
|
|
109
|
+
|
|
110
|
+
## Licence
|
|
111
|
+
|
|
112
|
+
MIT ([`LICENSE`](LICENSE)).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { type MeterDataProvider } from '@nexgen-os/core';
|
|
2
|
+
import { type ConsentLink, type HttpFetch } from '@nexgen-os/fluvius';
|
|
3
|
+
export type { ConsentLink, HttpFetch };
|
|
4
|
+
/** What the operator gave the service provider at its onboarding, resolved by the caller from the connector's `secret_ref`; never stored. */
|
|
5
|
+
export interface OresCredentials {
|
|
6
|
+
/** The gateway's subscription key (`Ocp-Apim-Subscription-Key`). */
|
|
7
|
+
subscriptionKey: string;
|
|
8
|
+
/** The PEM of the certificate the operator registered, and of its private key: presented on the connection when given. */
|
|
9
|
+
certificate?: string;
|
|
10
|
+
privateKey?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface OresOptions {
|
|
13
|
+
credentials: OresCredentials;
|
|
14
|
+
/** The service provider's data access contract number, for the consent link; from `connectors.config`. */
|
|
15
|
+
contractNumber?: string;
|
|
16
|
+
/** Where My ORES sends the customer back, consent given or not; each on a domain the operator validated at the contract. From `connectors.config`. */
|
|
17
|
+
returnUrlSuccess?: string;
|
|
18
|
+
returnUrlFailed?: string;
|
|
19
|
+
/** Default `https://edap.ores.be`. */
|
|
20
|
+
baseUrl?: string;
|
|
21
|
+
/** Default the operator's page `https://www.myores.be/tpda/`, which the link's id is appended to. */
|
|
22
|
+
consentPageUrl?: string;
|
|
23
|
+
/** A stand-in for the transport; by default the connection presents the certificate when one is given. */
|
|
24
|
+
fetch?: HttpFetch;
|
|
25
|
+
}
|
|
26
|
+
/** The granularity a customer consents to, as the consent link asks it. */
|
|
27
|
+
export type OresDataService = 'HOURLY_QUARTER_HOURLY' | 'DAILY' | 'UNDEFINED';
|
|
28
|
+
/** What the consent link is asked for: the reference the mandates will carry, the customer's flow, the data and its period. */
|
|
29
|
+
export interface OresConsentRequest {
|
|
30
|
+
/** The reference the mandates carry at the operator, 35 characters at most, one customer per reference; kept as the mandate's `external_reference`. */
|
|
31
|
+
referenceNumber: string;
|
|
32
|
+
/** `B2C` for a household, `B2B` for a company. */
|
|
33
|
+
flow: 'B2C' | 'B2B';
|
|
34
|
+
/** `HOURLY_QUARTER_HOURLY` by default: quarter hours for electricity. */
|
|
35
|
+
dataServiceType?: OresDataService;
|
|
36
|
+
/** The readings the mandate covers, ISO 8601 instants; left out, the customer chooses. The start may reach three years back. */
|
|
37
|
+
dataPeriodFrom?: string;
|
|
38
|
+
dataPeriodTo?: string;
|
|
39
|
+
/** How many metering points the customer may share under this reference, 1 to 1000; the operator's default (1000) when absent. */
|
|
40
|
+
numberOfEans?: number;
|
|
41
|
+
}
|
|
42
|
+
/** A mandate as `GET /mandates` lists it: one per metering point, direction and granularity. */
|
|
43
|
+
export interface OresMandate {
|
|
44
|
+
referenceNumber: string;
|
|
45
|
+
/** `Approved`, `Rejected` or `Finished`. */
|
|
46
|
+
status: string;
|
|
47
|
+
/** `ToBeRenew`, `RenewalRequested` or `Expired`, when a renewal is under way; a mandate is renewed every three years. */
|
|
48
|
+
renewalStatus: string | null;
|
|
49
|
+
ean: string | null;
|
|
50
|
+
/** `E` electricity, `G` gas. */
|
|
51
|
+
energyType: string | null;
|
|
52
|
+
/** `HourlyQuarterHourly` or `Daily`. */
|
|
53
|
+
dataServiceType: string | null;
|
|
54
|
+
dataPeriodFrom: string | null;
|
|
55
|
+
dataPeriodTo: string | null;
|
|
56
|
+
mandateExpirationDate: string | null;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* What the operator's statuses mean for the mandate: `approved`, `refused`
|
|
60
|
+
* or `expired`; null for a status it does not know. A renewal the customer
|
|
61
|
+
* let pass (`Expired`) ends the mandate for new readings, whatever its
|
|
62
|
+
* status still says.
|
|
63
|
+
*/
|
|
64
|
+
export declare function oresMandateStatus(mandate: Pick<OresMandate, 'status' | 'renewalStatus'>): 'approved' | 'refused' | 'expired' | null;
|
|
65
|
+
export interface OresConnector extends MeterDataProvider {
|
|
66
|
+
readonly source_code: 'ores_service_provider_api';
|
|
67
|
+
/** The mandates given under a reference, every status; narrowed to one metering point when its EAN is given. */
|
|
68
|
+
mandates(referenceNumber: string, ean?: string): Promise<OresMandate[]>;
|
|
69
|
+
/** A link the customer follows to My ORES, valid five days; refuses `contract_number_required` without the contract number. */
|
|
70
|
+
consentLink(request: OresConsentRequest): Promise<ConsentLink>;
|
|
71
|
+
}
|
|
72
|
+
/** The longest period one call of the energy service answers, in days: the operator's limit. */
|
|
73
|
+
export declare const ORES_DAYS_PER_CALL = 7;
|
|
74
|
+
/** A connector on the operator's API for energy service providers. `source_code` is `ores_service_provider_api`. */
|
|
75
|
+
export declare function ores(options: OresOptions): OresConnector;
|
|
76
|
+
/** The days `[from, to)` cut into periods one call answers, each `[start, end)` in `YYYY-MM-DD`. */
|
|
77
|
+
export declare function windows(from: string, to: string, days?: number): [string, string][];
|
|
78
|
+
/** A transport that presents the registered certificate on the connection; a certificate that does not read is refused by name. */
|
|
79
|
+
export declare function certificateFetch(certificate: string, privateKey: string): HttpFetch;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
// ORES — the main Walloon distribution operator's API for energy service
|
|
2
|
+
// providers (third-party data access, `edap.ores.be/b2b/tpda`), as a
|
|
3
|
+
// connector. Source `ores_service_provider_api`, the be pack's.
|
|
4
|
+
//
|
|
5
|
+
// The path of a load curve: the service provider asks a consent link
|
|
6
|
+
// (`POST /shortUrlIdentifier`) under its data access contract; the customer
|
|
7
|
+
// follows it to My ORES and consents, per metering point, direction and
|
|
8
|
+
// granularity; the mandates appear in `GET /mandates` under the reference of
|
|
9
|
+
// the request, with the status `Approved`; the quarter-hour energy of the
|
|
10
|
+
// meter is read by reference and EAN (`GET /mandates/energy`), offtake and
|
|
11
|
+
// injection in one answer, seven days at most per call.
|
|
12
|
+
// `collectMeterReadings()` of `@nexgen-os/core` checks the mandate first and
|
|
13
|
+
// stores what comes back on the meter.
|
|
14
|
+
//
|
|
15
|
+
// The answers have the shape of the API the Flemish operator runs, so they
|
|
16
|
+
// are read by the same reader (`energySeries()` of `@nexgen-os/fluvius`).
|
|
17
|
+
// What differs is here: the paths, the reference every call carries, the
|
|
18
|
+
// seven-day window, and the authentication — the gateway's subscription key
|
|
19
|
+
// on every call and the certificate the operator registered, presented on
|
|
20
|
+
// the connection. Nothing here reads the environment or the database: the
|
|
21
|
+
// secrets are given by the caller, resolved from the `secret_ref` of the
|
|
22
|
+
// organisation's `connectors` row; the hub's conventions (its zone, its
|
|
23
|
+
// quality table, its steps) come from its pack row.
|
|
24
|
+
import { X509Certificate } from 'node:crypto';
|
|
25
|
+
import { Agent, request as httpsRequest } from 'node:https';
|
|
26
|
+
import { GestureError, requireMandate, } from '@nexgen-os/core';
|
|
27
|
+
import { energySeries, mandateStatusOf, seconds, startOfDay } from '@nexgen-os/fluvius';
|
|
28
|
+
/**
|
|
29
|
+
* What the operator's statuses mean for the mandate: `approved`, `refused`
|
|
30
|
+
* or `expired`; null for a status it does not know. A renewal the customer
|
|
31
|
+
* let pass (`Expired`) ends the mandate for new readings, whatever its
|
|
32
|
+
* status still says.
|
|
33
|
+
*/
|
|
34
|
+
export function oresMandateStatus(mandate) {
|
|
35
|
+
if (mandate.renewalStatus === 'Expired')
|
|
36
|
+
return 'expired';
|
|
37
|
+
return mandateStatusOf(mandate.status);
|
|
38
|
+
}
|
|
39
|
+
const SOURCE = 'ores_service_provider_api';
|
|
40
|
+
const QUARTER_HOUR = 'PT15M';
|
|
41
|
+
/** The longest period one call of the energy service answers, in days: the operator's limit. */
|
|
42
|
+
export const ORES_DAYS_PER_CALL = 7;
|
|
43
|
+
/** A connector on the operator's API for energy service providers. `source_code` is `ores_service_provider_api`. */
|
|
44
|
+
export function ores(options) {
|
|
45
|
+
const { credentials } = options;
|
|
46
|
+
if (!credentials?.subscriptionKey) {
|
|
47
|
+
throw new GestureError('secret_not_found: ores needs the subscription key its connectors row names');
|
|
48
|
+
}
|
|
49
|
+
if (Boolean(credentials.certificate) !== Boolean(credentials.privateKey)) {
|
|
50
|
+
throw new GestureError('secret_not_found: ores needs the certificate and its private key together');
|
|
51
|
+
}
|
|
52
|
+
const base = `${(options.baseUrl ?? 'https://edap.ores.be').replace(/\/+$/, '')}/b2b/tpda/v1/api/external/v1`;
|
|
53
|
+
const consentPage = (options.consentPageUrl ?? 'https://www.myores.be/tpda/').replace(/\/*$/, '/');
|
|
54
|
+
const doFetch = options.fetch
|
|
55
|
+
?? (credentials.certificate ? certificateFetch(credentials.certificate, credentials.privateKey) : globalThis.fetch);
|
|
56
|
+
const call = async (path, method = 'GET', body) => {
|
|
57
|
+
const headers = { 'Ocp-Apim-Subscription-Key': credentials.subscriptionKey, Accept: 'application/json' };
|
|
58
|
+
if (body !== undefined)
|
|
59
|
+
headers['Content-Type'] = 'application/json';
|
|
60
|
+
const response = await doFetch(`${base}${path}`, { method, headers, ...(body !== undefined ? { body: JSON.stringify(body) } : {}) });
|
|
61
|
+
if (response.status === 404 || response.status === 204)
|
|
62
|
+
return null;
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
const detail = (await response.text().catch(() => '')).slice(0, 300);
|
|
65
|
+
const where = path.replace(/\?.*$/, '');
|
|
66
|
+
if (response.status === 401 || response.status === 403)
|
|
67
|
+
throw new GestureError(`source_unauthorised: ores ${response.status} on ${where}: ${detail}`);
|
|
68
|
+
throw new GestureError(`source_unavailable: ores ${response.status} on ${method} ${where}: ${detail}`);
|
|
69
|
+
}
|
|
70
|
+
return response.json();
|
|
71
|
+
};
|
|
72
|
+
return {
|
|
73
|
+
source_code: SOURCE,
|
|
74
|
+
async mandates(referenceNumber, ean) {
|
|
75
|
+
const params = new URLSearchParams({ referenceNumber: reference(referenceNumber) });
|
|
76
|
+
if (ean)
|
|
77
|
+
params.set('ean', ean);
|
|
78
|
+
const data = await call(`/mandates?${params.toString()}`);
|
|
79
|
+
const list = (data?.data?.mandates ?? []);
|
|
80
|
+
const text = (value) => (typeof value === 'string' && value.trim() !== '' ? value.trim() : null);
|
|
81
|
+
return list.map((m) => ({
|
|
82
|
+
referenceNumber: String(m.referenceNumber ?? ''),
|
|
83
|
+
status: String(m.status ?? ''),
|
|
84
|
+
renewalStatus: text(m.renewalStatus),
|
|
85
|
+
ean: text(m.ean),
|
|
86
|
+
energyType: text(m.energyType),
|
|
87
|
+
dataServiceType: text(m.dataServiceType),
|
|
88
|
+
dataPeriodFrom: text(m.dataPeriodFrom),
|
|
89
|
+
dataPeriodTo: text(m.dataPeriodTo),
|
|
90
|
+
mandateExpirationDate: text(m.mandateExpirationDate),
|
|
91
|
+
}));
|
|
92
|
+
},
|
|
93
|
+
async consentLink(request) {
|
|
94
|
+
if (!options.contractNumber) {
|
|
95
|
+
throw new GestureError('contract_number_required: a consent link names the data access contract; set contract_number in the connectors row');
|
|
96
|
+
}
|
|
97
|
+
if (request.numberOfEans !== undefined && (!Number.isInteger(request.numberOfEans) || request.numberOfEans < 1 || request.numberOfEans > 1000)) {
|
|
98
|
+
throw new GestureError(`invalid_parameter: ores shares 1 to 1000 metering points under a reference, not ${request.numberOfEans}`);
|
|
99
|
+
}
|
|
100
|
+
const data = await call('/shortUrlIdentifier', 'POST', {
|
|
101
|
+
dataAccessContractNumber: options.contractNumber,
|
|
102
|
+
referenceNumber: reference(request.referenceNumber),
|
|
103
|
+
flow: request.flow,
|
|
104
|
+
dataServices: [{
|
|
105
|
+
dataServiceType: request.dataServiceType ?? 'HOURLY_QUARTER_HOURLY',
|
|
106
|
+
...(request.dataPeriodFrom ? { dataPeriodFrom: seconds(request.dataPeriodFrom) } : {}),
|
|
107
|
+
...(request.dataPeriodTo ? { dataPeriodTo: seconds(request.dataPeriodTo) } : {}),
|
|
108
|
+
}],
|
|
109
|
+
...(request.numberOfEans !== undefined ? { numberOfEans: request.numberOfEans } : {}),
|
|
110
|
+
...(options.returnUrlSuccess ? { returnUrlSuccess: options.returnUrlSuccess } : {}),
|
|
111
|
+
...(options.returnUrlFailed ? { returnUrlFailed: options.returnUrlFailed } : {}),
|
|
112
|
+
});
|
|
113
|
+
const answer = (data?.data ?? data ?? {});
|
|
114
|
+
const id = typeof answer.shortUrlIdentifier === 'string' ? answer.shortUrlIdentifier : '';
|
|
115
|
+
if (!id)
|
|
116
|
+
throw new GestureError('source_unavailable: ores answered no shortUrlIdentifier');
|
|
117
|
+
return { id, url: `${consentPage}${encodeURIComponent(id)}`, validTo: typeof answer.validTo === 'string' ? answer.validTo : null };
|
|
118
|
+
},
|
|
119
|
+
async readings(meter, from, to, readOptions = {}) {
|
|
120
|
+
const mandate = requireMandate(SOURCE, readOptions.mandate, readOptions.scope ?? 'load_curve');
|
|
121
|
+
if (readOptions.step && readOptions.step !== QUARTER_HOUR) {
|
|
122
|
+
throw new GestureError(`step_unsupported: ores reads quarter hours (${QUARTER_HOUR}), not ${readOptions.step}`);
|
|
123
|
+
}
|
|
124
|
+
if (!/^\d{18}$/.test(meter.identifier)) {
|
|
125
|
+
throw new GestureError(`invalid_identifier: ${meter.identifier} is not an EAN of 18 digits`);
|
|
126
|
+
}
|
|
127
|
+
if (!mandate.external_reference) {
|
|
128
|
+
throw new GestureError(`mandate_reference_missing: ores reads by the reference of the consent; mandate ${mandate.id} carries none`);
|
|
129
|
+
}
|
|
130
|
+
const hub = readOptions.hub ?? { time_zone: null, quality_codes: {} };
|
|
131
|
+
if (!hub.time_zone) {
|
|
132
|
+
throw new GestureError('time_zone_required: the days asked are the hub\'s; its pack row names no time_zone');
|
|
133
|
+
}
|
|
134
|
+
const merged = new Map();
|
|
135
|
+
for (const [start, end] of windows(from, to)) {
|
|
136
|
+
const params = new URLSearchParams({
|
|
137
|
+
referenceNumber: reference(mandate.external_reference), ean: meter.identifier, granularity: 'hourlyQuarterHourly',
|
|
138
|
+
periodType: 'readTime', from: startOfDay(start, hub.time_zone), to: startOfDay(end, hub.time_zone),
|
|
139
|
+
});
|
|
140
|
+
for (const series of energySeries(await call(`/mandates/energy?${params.toString()}`), meter, hub, 'ores')) {
|
|
141
|
+
const known = merged.get(series.quantity_code);
|
|
142
|
+
if (known)
|
|
143
|
+
known.values.push(...series.values);
|
|
144
|
+
else
|
|
145
|
+
merged.set(series.quantity_code, series);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return [...merged.values()];
|
|
149
|
+
},
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
/** The reference of a consent as the operator takes it: 35 characters at most. */
|
|
153
|
+
function reference(value) {
|
|
154
|
+
const text = String(value ?? '').trim();
|
|
155
|
+
if (text === '' || text.length > 35) {
|
|
156
|
+
throw new GestureError(`invalid_reference: ores takes a reference of 1 to 35 characters, not ${JSON.stringify(value)}`);
|
|
157
|
+
}
|
|
158
|
+
return text;
|
|
159
|
+
}
|
|
160
|
+
/** The days `[from, to)` cut into periods one call answers, each `[start, end)` in `YYYY-MM-DD`. */
|
|
161
|
+
export function windows(from, to, days = ORES_DAYS_PER_CALL) {
|
|
162
|
+
const day = (text) => {
|
|
163
|
+
const ms = /^\d{4}-\d{2}-\d{2}$/.test(text) ? Date.parse(`${text}T00:00:00Z`) : Number.NaN;
|
|
164
|
+
if (Number.isNaN(ms))
|
|
165
|
+
throw new GestureError(`date_unreadable: ${JSON.stringify(text)} is not YYYY-MM-DD`);
|
|
166
|
+
return ms;
|
|
167
|
+
};
|
|
168
|
+
const end = day(to);
|
|
169
|
+
const out = [];
|
|
170
|
+
for (let start = day(from); start < end; start += days * 86_400_000) {
|
|
171
|
+
const stop = Math.min(start + days * 86_400_000, end);
|
|
172
|
+
out.push([new Date(start).toISOString().slice(0, 10), new Date(stop).toISOString().slice(0, 10)]);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
/** A transport that presents the registered certificate on the connection; a certificate that does not read is refused by name. */
|
|
177
|
+
export function certificateFetch(certificate, privateKey) {
|
|
178
|
+
try {
|
|
179
|
+
new X509Certificate(certificate);
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
throw new GestureError('certificate_unreadable: ores needs the PEM of the certificate the operator registered');
|
|
183
|
+
}
|
|
184
|
+
const agent = new Agent({ cert: certificate, key: privateKey, keepAlive: true });
|
|
185
|
+
return (url, init = {}) => new Promise((resolve, reject) => {
|
|
186
|
+
const sent = httpsRequest(url, { method: init.method ?? 'GET', headers: init.headers, agent }, (response) => {
|
|
187
|
+
const chunks = [];
|
|
188
|
+
response.on('data', (chunk) => chunks.push(chunk));
|
|
189
|
+
response.on('end', () => {
|
|
190
|
+
const text = Buffer.concat(chunks).toString('utf8');
|
|
191
|
+
const status = response.statusCode ?? 0;
|
|
192
|
+
resolve({ ok: status >= 200 && status < 300, status, json: async () => JSON.parse(text), text: async () => text });
|
|
193
|
+
});
|
|
194
|
+
});
|
|
195
|
+
sent.on('error', reject);
|
|
196
|
+
if (init.body !== undefined)
|
|
197
|
+
sent.write(init.body);
|
|
198
|
+
sent.end();
|
|
199
|
+
});
|
|
200
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nexgen-os/ores",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "The ORES API for energy service providers as a Nexgen OS meter data connector: the customer's consent link signed in My ORES, the mandates, and the quarter-hour energy of a meter read under mandate.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/nexgen-os/nexgen-os.git",
|
|
9
|
+
"directory": "packages/connectors/ores"
|
|
10
|
+
},
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"engines": {
|
|
16
|
+
"node": ">=20"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist",
|
|
20
|
+
"README.md",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"main": "./dist/index.js",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"exports": {
|
|
26
|
+
".": {
|
|
27
|
+
"types": "./dist/index.d.ts",
|
|
28
|
+
"import": "./dist/index.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc -p tsconfig.build.json"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@nexgen-os/core": "^0.5.0",
|
|
36
|
+
"@nexgen-os/fluvius": "^0.5.0"
|
|
37
|
+
}
|
|
38
|
+
}
|