@nexgen-os/enedis-sge 0.0.0-stage → 0.4.1

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 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,95 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/enedis-sge`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The web services Enedis opens to a third party under contract with it (SGE, its
4
+ exchange management system), as a meter data connector of Nexgen OS,
5
+ for an installation whose organisation holds its own contract with the
6
+ operator. Source `enedis_sge`, the fr pack's. MIT.
7
+
8
+ **A skeleton until homologation.** The requests, the readers of the answers,
9
+ the refusals and the mapping to series run now, offline, on an injected
10
+ transport. What only the contract and the homologation settle is listed
11
+ [below](#after-homologation).
12
+
13
+ ## What it speaks
14
+
15
+ | Method | Web service | Notes |
16
+ |---|---|---|
17
+ | `searchPoint()` | `RecherchePoint` v2.0 | a point by its holder and address, outside the third party's perimeter (`rechercheHorsPerimetre`) |
18
+ | `technicalData()` | `ConsultationDonneesTechniquesContractuelles` v1.0 | segment, state, subscribed power, grid tariff; under mandate (`technical_data`) |
19
+ | `detailedMeasures()`, `readings()` | `ConsultationMesuresDetaillees` v2.0 | the load curve (`COURBE`, `PA`), offtake and injection, in windows of 7 days; under mandate (`load_curve`), the customer's agreement declared (`accordClient`) |
20
+ | `orderCollection()` | `CommandeCollectePublicationMesures` v3.0 | turns the collection of a load curve on and subscribes its publication; refuses without the mandate and without the holder it declares (`declarationAccordClient`) |
21
+
22
+ Names, paths and namespaces follow the public homologation samples of
23
+ [consometers/sge-tiers](https://github.com/consometers/sge-tiers) (EUPL-1.2;
24
+ cited, not copied: the answers in `tests/answers.ts` take their shape and
25
+ invent their content). Where they differ from earlier assumptions, the
26
+ samples are followed: the path is `/RecherchePoint/v2.0`; detailed measures
27
+ are v2.0 and their points are `<mesure>` elements (`<points>` is read too);
28
+ authentication is a client certificate **and** HTTP Basic.
29
+
30
+ ## Time: the web services' convention
31
+
32
+ **A web service answer dates a step at its END, with an offset**: the first
33
+ half hour of a winter day is `d = 2026-01-15T00:30:00+01:00`. The connector
34
+ subtracts the step (`p`) and gives every point at the start of its step in
35
+ UTC. A stamp without an offset is refused (`date_offset_required`): that is
36
+ the convention of the R63 **file** (start of the step, legal time, no
37
+ offset), which [`@nexgen-os/enedis-r6x`](../../formats/enedis-r6x/README.md)
38
+ reads. The two are never shared.
39
+
40
+ ## Under mandate
41
+
42
+ The third party collects, keeps and proves the customer's authorisation
43
+ itself (the operator checks it). `collectMeterReadings()` of
44
+ `@nexgen-os/core` asks the one check (`grid.authorise_reading()`) and hands
45
+ the connector the mandate it returned; `readings()`, `technicalData()` and
46
+ `orderCollection()` refuse without it (`mandate_missing`, `mandate_scope`).
47
+ Quality letters are mapped by the hub's table of the pack
48
+ (`grid.operators.meter_data.quality_codes`), a missing step kept missing.
49
+
50
+ ## Configuration
51
+
52
+ An organisation's `connectors` row names the source `enedis_sge`; `config`
53
+ holds `base_url` (no default: homologation and production are two worlds)
54
+ and `contract_id` (not a secret); `secret_ref` names one bundle in the vault
55
+ holding the login, the password, the certificate and its key. The caller
56
+ resolves it and builds the transport:
57
+
58
+ ```ts
59
+ const sge = enedisSge({ baseUrl: config.base_url, login: secret.login, transport: mutualTlsTransport(secret) });
60
+ ```
61
+
62
+ `mutualTlsTransport()` is HTTPS from Node with the client certificate and
63
+ HTTP Basic; a runtime that cannot present a client certificate needs a
64
+ proxy that can.
65
+
66
+ ## Refusals
67
+
68
+ `connector_config_required`, `secret_not_found`, `mandate_missing`,
69
+ `mandate_scope`, `mandate_holder_required`, `date_offset_required`,
70
+ `quality_unknown`, `source_unavailable`, and `source_refused: enedis_sge
71
+ <code>` with the gateway's own code (`SGT4L8`, the period beyond the history
72
+ allowed) or the HTTP status.
73
+
74
+ ## After homologation
75
+
76
+ What the contract with the operator and the homologation campaign settle,
77
+ in `src/services.ts` and `src/answers.ts` only:
78
+
79
+ - the production endpoint, and the homologation one confirmed;
80
+ - the versions in force (detailed measures v2.0 or v3, and whether v3 reads
81
+ `points`), the exact element names and their order;
82
+ - the `SGT*` error codes and what each one means for a retry;
83
+ - the call limits: the days per call of detailed measures (7 here), the
84
+ calls per second, the history allowed;
85
+ - the asynchronous history order (`CommandeTransmissionHistoriqueMesures`,
86
+ object `HDM`) and the channel its files and the recurring publications
87
+ (R63, R64, R50, R151, R4Q, R171) arrive by, with their decryption;
88
+ - reactive power (`PRI`, `PRC`) and voltage through detailed measures;
89
+ - the renewal of the client certificate;
90
+ - an hour-by-hour comparison with another source on a few points before any
91
+ installation relies on it.
92
+
93
+ ## Licence
94
+
95
+ MIT.
@@ -0,0 +1,55 @@
1
+ import { type XmlNode } from '@nexgen-os/enedis-r6x';
2
+ /** A refusal of the gateway, by its own code when it gives one (`SGT4L8`), else by HTTP status. */
3
+ export declare class SgeRefusal extends Error {
4
+ readonly code: string;
5
+ constructor(code: string, detail: string);
6
+ }
7
+ /** The SOAP body of an answer; a fault, an HTTP error or a result code other than SGT200 refused by name. */
8
+ export declare function soapBody(status: number, xml: string): XmlNode;
9
+ export interface MeasurePoint {
10
+ /** The start of the step in UTC, ISO 8601. */
11
+ start: string;
12
+ /** NaN when the gateway gives no value. */
13
+ value: number;
14
+ /** The nature letter (`n`), mapped by the hub's table of the pack. */
15
+ nature: string | null;
16
+ /** The step (`p`), an ISO 8601 duration. */
17
+ step: string | null;
18
+ }
19
+ export interface MeasureSeries {
20
+ pointId: string | null;
21
+ business: string | null;
22
+ physical: string | null;
23
+ unit: string | null;
24
+ points: MeasurePoint[];
25
+ }
26
+ /**
27
+ * The series of a `ConsultationMesuresDetaillees` answer. Its points are the
28
+ * `<mesure>` elements of the v2.0 samples (`<points>` read too, for the next
29
+ * version), each `d` the END of its step with an offset: the start is `d`
30
+ * minus `p`. A stamp without an offset is refused (`date_offset_required`):
31
+ * that would be the file convention, not the web services'.
32
+ */
33
+ export declare function detailedMeasures(status: number, xml: string): MeasureSeries[];
34
+ export interface FoundPoint {
35
+ pointId: string;
36
+ holder: string | null;
37
+ addressLines: string[];
38
+ state: string | null;
39
+ }
40
+ /** The points of a `RecherchePoint` answer. */
41
+ export declare function foundPoints(status: number, xml: string): FoundPoint[];
42
+ export interface TechnicalData {
43
+ pointId: string | null;
44
+ segment: string | null;
45
+ state: string | null;
46
+ subscribedPower: {
47
+ value: number;
48
+ unit: string;
49
+ } | null;
50
+ gridTariff: string | null;
51
+ }
52
+ /** What a `ConsultationDonneesTechniquesContractuelles` answer says of a point. */
53
+ export declare function technicalData(status: number, xml: string): TechnicalData;
54
+ /** The case number of a `CommandeCollectePublicationMesures` answer. */
55
+ export declare function collectionCase(status: number, xml: string): string;
@@ -0,0 +1,108 @@
1
+ // Reading the SOAP answers of the gateway. The web services date a step at
2
+ // its END, with an offset (`d = 00:30+01:00` closes the first half hour of a
3
+ // day): that is the web services' convention, kept here and never mixed with
4
+ // the R63 file's, which dates the start in legal time without an offset
5
+ // (`@nexgen-os/enedis-r6x`). Every point comes back at the start of its step
6
+ // in UTC.
7
+ import { childText, durationMs, findAll, findFirst, parseXml } from '@nexgen-os/enedis-r6x';
8
+ /** A refusal of the gateway, by its own code when it gives one (`SGT4L8`), else by HTTP status. */
9
+ export class SgeRefusal extends Error {
10
+ code;
11
+ constructor(code, detail) {
12
+ super(`source_refused: enedis_sge ${code}: ${detail}`);
13
+ this.code = code;
14
+ }
15
+ }
16
+ /** The SOAP body of an answer; a fault, an HTTP error or a result code other than SGT200 refused by name. */
17
+ export function soapBody(status, xml) {
18
+ let root;
19
+ try {
20
+ root = parseXml(xml);
21
+ }
22
+ catch (error) {
23
+ throw new SgeRefusal(`HTTP_${status}`, `unreadable answer (${error.message})`);
24
+ }
25
+ const body = findFirst(root, 'Body');
26
+ if (!body)
27
+ throw new SgeRefusal(`HTTP_${status}`, 'an answer without a SOAP body');
28
+ const fault = findFirst(body, 'Fault');
29
+ if (fault) {
30
+ const result = findFirst(fault, 'resultat');
31
+ throw new SgeRefusal(result?.attributes.code || childText(fault, 'faultcode') || `HTTP_${status}`, result?.text.trim() || childText(fault, 'faultstring') || 'SOAP fault');
32
+ }
33
+ if (status < 200 || status >= 300)
34
+ throw new SgeRefusal(`HTTP_${status}`, 'an HTTP error without a SOAP fault');
35
+ const ack = findFirst(body, 'resultat');
36
+ if (ack?.attributes.code && ack.attributes.code !== 'SGT200')
37
+ throw new SgeRefusal(ack.attributes.code, ack.text.trim() || 'refused');
38
+ return body;
39
+ }
40
+ /**
41
+ * The series of a `ConsultationMesuresDetaillees` answer. Its points are the
42
+ * `<mesure>` elements of the v2.0 samples (`<points>` read too, for the next
43
+ * version), each `d` the END of its step with an offset: the start is `d`
44
+ * minus `p`. A stamp without an offset is refused (`date_offset_required`):
45
+ * that would be the file convention, not the web services'.
46
+ */
47
+ export function detailedMeasures(status, xml) {
48
+ const body = soapBody(status, xml);
49
+ const pointId = findFirst(body, 'pointId')?.text.trim() || null;
50
+ return findAll(body, 'grandeur').map((g) => ({
51
+ pointId,
52
+ business: childText(g, 'grandeurMetier'),
53
+ physical: childText(g, 'grandeurPhysique'),
54
+ unit: childText(g, 'unite'),
55
+ points: [...findAll(g, 'mesure'), ...findAll(g, 'points')].map((p) => {
56
+ const end = childText(p, 'd');
57
+ if (!end)
58
+ throw new SgeRefusal('INVALID_ANSWER', 'a measure without a date');
59
+ const step = childText(p, 'p');
60
+ const raw = childText(p, 'v');
61
+ return { start: new Date(endToStart(end, step)).toISOString(), value: raw === null ? Number.NaN : Number(raw), nature: childText(p, 'n'), step };
62
+ }).sort((a, b) => Date.parse(a.start) - Date.parse(b.start)),
63
+ }));
64
+ }
65
+ function endToStart(end, step) {
66
+ if (!/(Z|[+-]\d{2}:?\d{2})$/.test(end.trim())) {
67
+ throw new SgeRefusal('date_offset_required', `${end}: a web service answer dates the end of a step with its offset`);
68
+ }
69
+ const at = Date.parse(end.trim().replace(' ', 'T'));
70
+ const ms = step ? durationMs(step) : 0;
71
+ if (Number.isNaN(at) || ms === null)
72
+ throw new SgeRefusal('INVALID_ANSWER', `${end} ${step ?? ''}`);
73
+ return at - ms;
74
+ }
75
+ /** The points of a `RecherchePoint` answer. */
76
+ export function foundPoints(status, xml) {
77
+ const body = soapBody(status, xml);
78
+ return findAll(body, 'point').filter((p) => p.attributes.id).map((p) => {
79
+ const address = findFirst(p, 'adresseInstallationNormalisee');
80
+ return {
81
+ pointId: p.attributes.id,
82
+ holder: childText(p, 'nomClientFinalOuDenominationSociale'),
83
+ addressLines: address ? address.children.map((c) => c.text.trim()).filter(Boolean) : [],
84
+ state: childText(p, 'etatContractuelCode'),
85
+ };
86
+ });
87
+ }
88
+ /** What a `ConsultationDonneesTechniquesContractuelles` answer says of a point. */
89
+ export function technicalData(status, xml) {
90
+ const body = soapBody(status, xml);
91
+ const power = findFirst(body, 'puissanceSouscriteMax');
92
+ const value = power ? Number(childText(power, 'valeur')) : Number.NaN;
93
+ return {
94
+ pointId: findFirst(body, 'point')?.attributes.id ?? null,
95
+ segment: findFirst(body, 'segment')?.attributes.code ?? null,
96
+ state: findFirst(body, 'etatContractuel')?.attributes.code ?? null,
97
+ subscribedPower: power && !Number.isNaN(value) ? { value, unit: childText(power, 'unite') ?? '' } : null,
98
+ gridTariff: findFirst(body, 'formuleTarifaireAcheminement')?.attributes.code ?? null,
99
+ };
100
+ }
101
+ /** The case number of a `CommandeCollectePublicationMesures` answer. */
102
+ export function collectionCase(status, xml) {
103
+ const body = soapBody(status, xml);
104
+ const id = findFirst(body, 'affaireId')?.text.trim();
105
+ if (!id)
106
+ throw new SgeRefusal('INVALID_ANSWER', 'a collection order without its case number');
107
+ return id;
108
+ }
@@ -0,0 +1,59 @@
1
+ import { type MeterDataProvider, type MeterMandate } from '@nexgen-os/core';
2
+ import { type Holder, type PointSearch, type SgeDirection } from './services.js';
3
+ import { type FoundPoint, type MeasureSeries, type TechnicalData } from './answers.js';
4
+ export * from './services.js';
5
+ export * from './answers.js';
6
+ /** One SOAP call: where, which action, the envelope. */
7
+ export interface SoapCall {
8
+ url: string;
9
+ soapAction: string;
10
+ body: string;
11
+ }
12
+ /** Sends one call and answers the HTTP status and body; a test passes a recorder, an installation `mutualTlsTransport()`. */
13
+ export type SoapTransport = (call: SoapCall) => Promise<{
14
+ status: number;
15
+ body: string;
16
+ }>;
17
+ /** The credentials of the gateway, resolved by the caller from the connector's `secret_ref`; never stored. */
18
+ export interface SgeCredentials {
19
+ login: string;
20
+ password: string;
21
+ /** PEM of the client certificate the operator recognises, and of its key. */
22
+ certificate: string;
23
+ privateKey: string;
24
+ }
25
+ /**
26
+ * The transport an installation uses: HTTPS from Node with the client
27
+ * certificate and HTTP Basic. Built lazily: nothing connects before the
28
+ * first call.
29
+ */
30
+ export declare function mutualTlsTransport(credentials: SgeCredentials): SoapTransport;
31
+ /** The homologation gateway, as the public samples name it; the production one comes with the contract. */
32
+ export declare const SGE_HOMOLOGATION_URL = "https://sge-homologation-b2b.enedis.fr";
33
+ export interface EnedisSgeOptions {
34
+ /** The gateway, from `connectors.config.base_url`: no default, homologation and production are two worlds. */
35
+ baseUrl: string;
36
+ /** The login, repeated in the body of each call (`initiateurLogin`, `loginUtilisateur`). */
37
+ login: string;
38
+ transport: SoapTransport;
39
+ /** The days asked per call of detailed measures; 7 until homologation says otherwise. */
40
+ windowDays?: number;
41
+ }
42
+ export interface EnedisSgeConnector extends MeterDataProvider {
43
+ readonly source_code: 'enedis_sge';
44
+ searchPoint(criteria: PointSearch): Promise<FoundPoint[]>;
45
+ technicalData(pointId: string, mandate: MeterMandate | null | undefined): Promise<TechnicalData>;
46
+ /** Turns on the collection of a load curve and subscribes its publication; refuses without the mandate and its holder. */
47
+ orderCollection(order: {
48
+ pointId: string;
49
+ contractId: string;
50
+ to: string;
51
+ from: string;
52
+ holder: Holder;
53
+ direction: SgeDirection;
54
+ }, mandate: MeterMandate | null | undefined): Promise<string>;
55
+ /** The raw series of one call of detailed measures, steps at their start in UTC. */
56
+ detailedMeasures(pointId: string, from: string, to: string, direction: SgeDirection, physical?: 'PA' | 'PRI' | 'PRC'): Promise<MeasureSeries[]>;
57
+ }
58
+ /** A connector on the operator's gateway. `source_code` is `enedis_sge`. */
59
+ export declare function enedisSge(options: EnedisSgeOptions): EnedisSgeConnector;
package/dist/index.js ADDED
@@ -0,0 +1,140 @@
1
+ // Enedis SGE — the operator's own web services for a third party under
2
+ // contract with it, as a connector. Source `enedis_sge` (the fr pack's).
3
+ //
4
+ // A skeleton until homologation: the SOAP requests and the readers of the
5
+ // answers follow the public homologation samples; the endpoints, the
6
+ // versions in force, the error codes, the call limits and the channel of
7
+ // the files are named in the README as what the contract and homologation
8
+ // settle. Everything else runs now, offline, on an injected transport.
9
+ //
10
+ // Authentication is a client certificate (mutual TLS) and the gateway's
11
+ // login and password (HTTP Basic), the login repeated in the body. Every
12
+ // call declares the customer's agreement, which the third party collects,
13
+ // keeps and proves itself: `readings()` refuses without the mandate the one
14
+ // check returned, and the collection order without the holder it names.
15
+ import { GestureError, requireMandate, } from '@nexgen-os/core';
16
+ import { durationMs } from '@nexgen-os/enedis-r6x';
17
+ import { SGE_SERVICES, collectionOrderRequest, detailedMeasuresRequest, searchPointRequest, technicalDataRequest, } from './services.js';
18
+ import { collectionCase, detailedMeasures, foundPoints, technicalData } from './answers.js';
19
+ export * from './services.js';
20
+ export * from './answers.js';
21
+ /**
22
+ * The transport an installation uses: HTTPS from Node with the client
23
+ * certificate and HTTP Basic. Built lazily: nothing connects before the
24
+ * first call.
25
+ */
26
+ export function mutualTlsTransport(credentials) {
27
+ return async (call) => {
28
+ const { request } = await import('node:https');
29
+ const basic = Buffer.from(`${credentials.login}:${credentials.password}`).toString('base64');
30
+ return new Promise((resolve, reject) => {
31
+ const req = request(call.url, {
32
+ method: 'POST', cert: credentials.certificate, key: credentials.privateKey,
33
+ headers: { 'Content-Type': 'text/xml; charset=utf-8', SOAPAction: call.soapAction, Authorization: `Basic ${basic}` },
34
+ }, (res) => {
35
+ const chunks = [];
36
+ res.on('data', (c) => chunks.push(c));
37
+ res.on('end', () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') }));
38
+ });
39
+ req.on('error', (error) => reject(new GestureError(`source_unavailable: enedis_sge ${error.message}`)));
40
+ req.end(call.body);
41
+ });
42
+ };
43
+ }
44
+ /** The homologation gateway, as the public samples name it; the production one comes with the contract. */
45
+ export const SGE_HOMOLOGATION_URL = 'https://sge-homologation-b2b.enedis.fr';
46
+ const DAY = 86_400_000;
47
+ /** A connector on the operator's gateway. `source_code` is `enedis_sge`. */
48
+ export function enedisSge(options) {
49
+ if (!options.baseUrl)
50
+ throw new GestureError('connector_config_required: enedis_sge needs base_url in its connectors row');
51
+ if (!options.login)
52
+ throw new GestureError('secret_not_found: enedis_sge needs the login its connectors row names');
53
+ const base = options.baseUrl.replace(/\/+$/, '');
54
+ const windowDays = options.windowDays ?? 7;
55
+ const send = async (service, body) => options.transport({ url: `${base}${service.path}`, soapAction: service.operation, body });
56
+ const connector = {
57
+ source_code: 'enedis_sge',
58
+ async searchPoint(criteria) {
59
+ const answer = await send(SGE_SERVICES.searchPoint, searchPointRequest(options.login, criteria));
60
+ return foundPoints(answer.status, answer.body);
61
+ },
62
+ async technicalData(pointId, mandate) {
63
+ requireMandate('enedis_sge', mandate, 'technical_data');
64
+ const answer = await send(SGE_SERVICES.technicalData, technicalDataRequest(options.login, pointId));
65
+ return technicalData(answer.status, answer.body);
66
+ },
67
+ async orderCollection(order, mandate) {
68
+ requireMandate('enedis_sge', mandate, 'load_curve');
69
+ const named = order.holder.kind === 'company' ? order.holder.name : order.holder.lastName;
70
+ if (!named?.trim())
71
+ throw new GestureError('mandate_holder_required: the operator is told who gave the agreement');
72
+ const answer = await send(SGE_SERVICES.collectionOrder, collectionOrderRequest(options.login, order));
73
+ return collectionCase(answer.status, answer.body);
74
+ },
75
+ async detailedMeasures(pointId, from, to, direction, physical = 'PA') {
76
+ const answer = await send(SGE_SERVICES.detailedMeasures, detailedMeasuresRequest(options.login, {
77
+ pointId, measureType: 'COURBE', physicalQuantity: physical, from, to, direction,
78
+ }));
79
+ return detailedMeasures(answer.status, answer.body);
80
+ },
81
+ async readings(meter, from, to, readOptions = {}) {
82
+ requireMandate('enedis_sge', readOptions.mandate, readOptions.scope ?? 'load_curve');
83
+ const hub = readOptions.hub ?? { quality_codes: {} };
84
+ const directions = meter.direction === 'both' ? ['SOUTIRAGE', 'INJECTION'] : meter.direction === 'injection' ? ['INJECTION'] : ['SOUTIRAGE'];
85
+ const out = [];
86
+ for (const direction of directions) {
87
+ const points = [];
88
+ let unit = null;
89
+ for (let start = Date.parse(from); start < Date.parse(to); start += windowDays * DAY) {
90
+ const end = Math.min(start + windowDays * DAY, Date.parse(to));
91
+ for (const s of await connector.detailedMeasures(meter.identifier, day(start), day(end), direction)) {
92
+ unit ??= s.unit;
93
+ points.push(...s.points);
94
+ }
95
+ }
96
+ if (points.length === 0)
97
+ continue;
98
+ out.push(toSeries(direction === 'INJECTION' ? 'injection_power' : 'offtake_power', unit, points, hub.quality_codes));
99
+ }
100
+ return out;
101
+ },
102
+ };
103
+ return connector;
104
+ }
105
+ /** One curve of the gateway as the series of a meter: missing steps kept as missing, letters by the hub's table. */
106
+ function toSeries(quantity, unit, points, codes) {
107
+ const steps = new Set(points.map((p) => p.step).filter(Boolean));
108
+ const step = steps.size === 1 ? [...steps][0] : null;
109
+ const ms = step ? durationMs(step) : null;
110
+ const quality = (p) => {
111
+ const code = Number.isNaN(p.value) ? codes.missing : p.nature === null ? codes.none : codes[p.nature];
112
+ if (code === undefined)
113
+ throw new GestureError(`quality_unknown: nature ${JSON.stringify(p.nature)} of enedis_sge is not in the hub's table`);
114
+ return code;
115
+ };
116
+ const byStart = new Map(points.map((p) => [Date.parse(p.start), p]));
117
+ const values = [];
118
+ if (ms) {
119
+ const first = Math.min(...byStart.keys());
120
+ const last = Math.max(...byStart.keys());
121
+ for (let t = first; t <= last; t += ms) {
122
+ const p = byStart.get(t);
123
+ if (p)
124
+ values.push({ at: p.start, value: p.value, quality: quality(p) });
125
+ else if (codes.missing !== undefined)
126
+ values.push({ at: new Date(t).toISOString(), value: Number.NaN, quality: codes.missing });
127
+ }
128
+ }
129
+ else {
130
+ for (const p of points)
131
+ values.push({ at: p.start, value: p.value, quality: quality(p) });
132
+ }
133
+ return {
134
+ quantity_code: quantity, value_kind: 'interval', step: ms ? `${ms / 60_000} minutes` : null,
135
+ ...(unit ? { unit } : {}), values,
136
+ };
137
+ }
138
+ function day(ms) {
139
+ return new Date(ms).toISOString().slice(0, 10);
140
+ }
@@ -0,0 +1,97 @@
1
+ export interface SgeService {
2
+ /** The service in the operator's catalogue. */
3
+ name: string;
4
+ /** Its path under the base URL, `/<Service>/v<version>`. */
5
+ path: string;
6
+ /** The namespace of its operation element. */
7
+ namespace: string;
8
+ /** The operation element, also its SOAPAction. */
9
+ operation: string;
10
+ }
11
+ export declare const SGE_SERVICES: {
12
+ /** A point found by its address and its holder, outside the third party's own perimeter. */
13
+ readonly searchPoint: {
14
+ readonly name: "RecherchePoint";
15
+ readonly path: "/RecherchePoint/v2.0";
16
+ readonly namespace: "http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0";
17
+ readonly operation: "rechercherPoint";
18
+ };
19
+ /** Technical and contractual data of a point: segment, subscribed power, tariff, state. */
20
+ readonly technicalData: {
21
+ readonly name: "ConsultationDonneesTechniquesContractuelles";
22
+ readonly path: "/ConsultationDonneesTechniquesContractuelles/v1.0";
23
+ readonly namespace: "http://www.enedis.fr/sge/b2b/services/consultationdonneestechniquescontractuelles/v1.0";
24
+ readonly operation: "consulterDonneesTechniquesContractuelles";
25
+ };
26
+ /** Detailed measures over a few days: load curve (PA, PRI, PRC), energy, maximum power. */
27
+ readonly detailedMeasures: {
28
+ readonly name: "ConsultationMesuresDetaillees";
29
+ readonly path: "/ConsultationMesuresDetaillees/v2.0";
30
+ readonly namespace: "http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0";
31
+ readonly operation: "consulterMesuresDetaillees";
32
+ };
33
+ /** The collection of a load curve turned on, and its recurring publication subscribed. */
34
+ readonly collectionOrder: {
35
+ readonly name: "CommandeCollectePublicationMesures";
36
+ readonly path: "/CommandeCollectePublicationMesures/v3.0";
37
+ readonly namespace: "http://www.enedis.fr/sge/b2b/commandecollectepublicationmesures/v3.0";
38
+ readonly operation: "commanderCollectePublicationMesures";
39
+ };
40
+ };
41
+ export declare const SOAP_ENVELOPE_NS = "http://schemas.xmlsoap.org/soap/envelope/";
42
+ /** A value of an element tree: nested objects are nested elements, arrays repeat, null is left out. */
43
+ export type XmlValue = string | number | boolean | null | undefined | {
44
+ [element: string]: XmlValue;
45
+ } | XmlValue[];
46
+ /** The elements of an object, in its key order, every text escaped. */
47
+ export declare function toXml(value: {
48
+ [element: string]: XmlValue;
49
+ }): string;
50
+ /** A SOAP 1.1 envelope around the operation of a service. */
51
+ export declare function soapEnvelope(service: SgeService, payload: {
52
+ [element: string]: XmlValue;
53
+ }): string;
54
+ export type SgeDirection = 'SOUTIRAGE' | 'INJECTION';
55
+ export interface DetailedMeasuresQuery {
56
+ pointId: string;
57
+ /** `COURBE` a load curve, `ENERGIE` energy per day, `PMAX` maximum power per day. */
58
+ measureType: 'COURBE' | 'ENERGIE' | 'PMAX';
59
+ /** `PA` active power, `PRI` / `PRC` reactive power, `EA` active energy, `PMA` maximum power. */
60
+ physicalQuantity: 'PA' | 'PRI' | 'PRC' | 'EA' | 'PMA';
61
+ /** `YYYY-MM-DD`, the first day; `to` the day after the last. */
62
+ from: string;
63
+ to: string;
64
+ direction: SgeDirection;
65
+ corrected?: boolean;
66
+ }
67
+ /** The request of detailed measures, declaring the customer's agreement (`accordClient`). */
68
+ export declare function detailedMeasuresRequest(login: string, q: DetailedMeasuresQuery): string;
69
+ export declare function technicalDataRequest(login: string, pointId: string): string;
70
+ export interface PointSearch {
71
+ holderName: string;
72
+ street?: string;
73
+ postalCode?: string;
74
+ /** The municipality in the country's own code. */
75
+ municipalityCode?: string;
76
+ }
77
+ export declare function searchPointRequest(login: string, c: PointSearch): string;
78
+ /** Who gave the agreement, as declared to the operator: a company by its name, a person by their last name. */
79
+ export type Holder = {
80
+ kind: 'company';
81
+ name: string;
82
+ } | {
83
+ kind: 'person';
84
+ lastName: string;
85
+ title?: string;
86
+ };
87
+ export interface CollectionOrder {
88
+ pointId: string;
89
+ /** The third party's contract with the operator (`connectors.config.contract_id`; not a secret). */
90
+ contractId: string;
91
+ from: string;
92
+ /** The end of the customer's agreement. */
93
+ to: string;
94
+ holder: Holder;
95
+ direction: SgeDirection;
96
+ }
97
+ export declare function collectionOrderRequest(login: string, o: CollectionOrder): string;
@@ -0,0 +1,110 @@
1
+ // The web services of the operator's third-party gateway (SGE) this
2
+ // connector speaks, and the SOAP requests it sends. Names, paths and
3
+ // namespaces follow the public homologation samples of consometers/sge-tiers
4
+ // (https://github.com/consometers/sge-tiers, EUPL-1.2, cited, not copied);
5
+ // what only the contract and the homologation pin down — the production
6
+ // endpoints, the versions in force, the order of elements — is confirmed
7
+ // there, in this file only.
8
+ import { escapeXml } from '@nexgen-os/enedis-r6x';
9
+ export const SGE_SERVICES = {
10
+ /** A point found by its address and its holder, outside the third party's own perimeter. */
11
+ searchPoint: {
12
+ name: 'RecherchePoint',
13
+ path: '/RecherchePoint/v2.0',
14
+ namespace: 'http://www.enedis.fr/sge/b2b/services/rechercherpoint/v2.0',
15
+ operation: 'rechercherPoint',
16
+ },
17
+ /** Technical and contractual data of a point: segment, subscribed power, tariff, state. */
18
+ technicalData: {
19
+ name: 'ConsultationDonneesTechniquesContractuelles',
20
+ path: '/ConsultationDonneesTechniquesContractuelles/v1.0',
21
+ namespace: 'http://www.enedis.fr/sge/b2b/services/consultationdonneestechniquescontractuelles/v1.0',
22
+ operation: 'consulterDonneesTechniquesContractuelles',
23
+ },
24
+ /** Detailed measures over a few days: load curve (PA, PRI, PRC), energy, maximum power. */
25
+ detailedMeasures: {
26
+ name: 'ConsultationMesuresDetaillees',
27
+ path: '/ConsultationMesuresDetaillees/v2.0',
28
+ namespace: 'http://www.enedis.fr/sge/b2b/services/consultationmesuresdetaillees/v2.0',
29
+ operation: 'consulterMesuresDetaillees',
30
+ },
31
+ /** The collection of a load curve turned on, and its recurring publication subscribed. */
32
+ collectionOrder: {
33
+ name: 'CommandeCollectePublicationMesures',
34
+ path: '/CommandeCollectePublicationMesures/v3.0',
35
+ namespace: 'http://www.enedis.fr/sge/b2b/commandecollectepublicationmesures/v3.0',
36
+ operation: 'commanderCollectePublicationMesures',
37
+ },
38
+ };
39
+ export const SOAP_ENVELOPE_NS = 'http://schemas.xmlsoap.org/soap/envelope/';
40
+ /** The elements of an object, in its key order, every text escaped. */
41
+ export function toXml(value) {
42
+ return Object.entries(value).map(([name, v]) => element(name, v)).join('');
43
+ }
44
+ function element(name, value) {
45
+ if (value === null || value === undefined)
46
+ return '';
47
+ if (Array.isArray(value))
48
+ return value.map((v) => element(name, v)).join('');
49
+ if (typeof value === 'object')
50
+ return `<${name}>${toXml(value)}</${name}>`;
51
+ return `<${name}>${escapeXml(String(value))}</${name}>`;
52
+ }
53
+ /** A SOAP 1.1 envelope around the operation of a service. */
54
+ export function soapEnvelope(service, payload) {
55
+ return '<?xml version="1.0" encoding="UTF-8"?>'
56
+ + `<soapenv:Envelope xmlns:soapenv="${SOAP_ENVELOPE_NS}" xmlns:sge="${service.namespace}">`
57
+ + '<soapenv:Header/>'
58
+ + `<soapenv:Body><sge:${service.operation}>${toXml(payload)}</sge:${service.operation}></soapenv:Body>`
59
+ + '</soapenv:Envelope>';
60
+ }
61
+ /** The request of detailed measures, declaring the customer's agreement (`accordClient`). */
62
+ export function detailedMeasuresRequest(login, q) {
63
+ return soapEnvelope(SGE_SERVICES.detailedMeasures, {
64
+ demande: {
65
+ initiateurLogin: login,
66
+ pointId: q.pointId,
67
+ mesuresTypeCode: q.measureType,
68
+ grandeurPhysique: q.physicalQuantity,
69
+ soutirage: q.direction === 'SOUTIRAGE',
70
+ injection: q.direction === 'INJECTION',
71
+ dateDebut: q.from,
72
+ dateFin: q.to,
73
+ mesuresCorrigees: q.corrected ?? false,
74
+ accordClient: true,
75
+ },
76
+ });
77
+ }
78
+ export function technicalDataRequest(login, pointId) {
79
+ return soapEnvelope(SGE_SERVICES.technicalData, { pointId, loginUtilisateur: login, autorisationClient: true });
80
+ }
81
+ export function searchPointRequest(login, c) {
82
+ const address = c.street || c.postalCode || c.municipalityCode
83
+ ? { numeroEtNomVoie: c.street, codePostal: c.postalCode, codeInseeCommune: c.municipalityCode }
84
+ : undefined;
85
+ return soapEnvelope(SGE_SERVICES.searchPoint, {
86
+ criteres: { adresseInstallation: address, nomClientFinalOuDenominationSociale: c.holderName, rechercheHorsPerimetre: true },
87
+ loginUtilisateur: login,
88
+ });
89
+ }
90
+ export function collectionOrderRequest(login, o) {
91
+ const holder = o.holder.kind === 'company'
92
+ ? { personneMorale: { denominationSociale: o.holder.name } }
93
+ : { personnePhysique: { civilite: o.holder.title, nom: o.holder.lastName } };
94
+ return soapEnvelope(SGE_SERVICES.collectionOrder, {
95
+ demande: {
96
+ donneesGenerales: { objetCode: 'AME', pointId: o.pointId, initiateurLogin: login, contratId: o.contractId },
97
+ accesMesures: {
98
+ dateDebut: o.from,
99
+ dateFin: o.to,
100
+ declarationAccordClient: { accord: true, ...holder },
101
+ mesuresTypeCode: 'CDC',
102
+ soutirage: o.direction === 'SOUTIRAGE',
103
+ injection: o.direction === 'INJECTION',
104
+ mesuresCorrigees: false,
105
+ transmissionRecurrente: true,
106
+ periodiciteTransmission: 'P1D',
107
+ },
108
+ },
109
+ });
110
+ }
package/package.json CHANGED
@@ -1,6 +1,38 @@
1
1
  {
2
2
  "name": "@nexgen-os/enedis-sge",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.1",
4
+ "description": "Enedis SGE, the operator's web services for a third party under contract, as a Nexgen OS meter data connector: point search, technical data, detailed measures, collection orders, under mandate. A skeleton until homologation.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/connectors/enedis-sge"
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.4.0",
36
+ "@nexgen-os/enedis-r6x": "^0.4.0"
37
+ }
38
+ }