@nexgen-os/core 0.4.2 → 0.6.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/README.md +2 -2
- package/dist/address.d.ts +3 -62
- package/dist/connectors/activations.d.ts +63 -0
- package/dist/connectors/activations.js +73 -0
- package/dist/connectors/devices.d.ts +132 -0
- package/dist/connectors/devices.js +125 -0
- package/dist/connectors/interfaces.d.ts +2 -104
- package/dist/connectors/interfaces.js +4 -11
- package/dist/connectors/measured.d.ts +12 -0
- package/dist/connectors/measured.js +44 -0
- package/dist/connectors/meter-data.d.ts +2 -39
- package/dist/connectors/meter-data.js +3 -13
- package/dist/connectors/settlement.js +2 -2
- package/dist/db.d.ts +8 -0
- package/dist/db.js +32 -1
- package/dist/files/dsmr.d.ts +1 -0
- package/dist/files/dsmr.js +5 -0
- package/dist/files/enedis-r6x.d.ts +1 -32
- package/dist/files/enedis-r6x.js +5 -86
- package/dist/files/energy-bill.d.ts +4 -3
- package/dist/files/energy-bill.js +11 -6
- package/dist/files/evcc.d.ts +102 -0
- package/dist/files/evcc.js +76 -0
- package/dist/files/geojson.d.ts +41 -2
- package/dist/files/geojson.js +61 -1
- package/dist/files/index.d.ts +6 -0
- package/dist/files/index.js +6 -0
- package/dist/files/project-sheet.d.ts +44 -0
- package/dist/files/project-sheet.js +102 -0
- package/dist/files/project.d.ts +108 -0
- package/dist/files/project.js +104 -0
- package/dist/files/pvsol.d.ts +64 -0
- package/dist/files/pvsol.js +99 -0
- package/dist/files/weather-files.d.ts +3 -2
- package/dist/files/weather-files.js +11 -7
- package/dist/files/wesmart-db.d.ts +229 -0
- package/dist/files/wesmart-db.js +412 -0
- package/dist/gestures.d.ts +135 -0
- package/dist/gestures.js +99 -1
- package/dist/index.d.ts +4 -1
- package/dist/index.js +12 -0
- package/dist/refusal.d.ts +2 -11
- package/dist/refusal.js +5 -29
- package/dist/series.d.ts +11 -6
- package/dist/series.js +6 -1
- package/dist/time.d.ts +1 -6
- package/dist/time.js +4 -25
- package/package.json +13 -6
- package/schema/geojson-export.1.json +605 -0
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* `writeEpw()` writes.
|
|
10
10
|
*/
|
|
11
11
|
import { WEATHER_QUANTITIES } from '@nexgen-os/weather-files';
|
|
12
|
+
import { atomically } from '../db.js';
|
|
12
13
|
import { storeSeries } from '../connectors/interfaces.js';
|
|
13
14
|
const HOUR_MS = 3_600_000;
|
|
14
15
|
/**
|
|
@@ -17,17 +18,20 @@ const HOUR_MS = 3_600_000;
|
|
|
17
18
|
* station network, a licensed model). A typical year is `simulated` and
|
|
18
19
|
* named after its years (`typical year 2005-2020`); real years are
|
|
19
20
|
* `measured` and unnamed, unless told otherwise. Importing the same file
|
|
20
|
-
* again replaces the values.
|
|
21
|
+
* again replaces the values. The file is stored whole or not at all: one
|
|
22
|
+
* series refused leaves none of the others.
|
|
21
23
|
*/
|
|
22
24
|
export async function importWeatherFile(db, target, file, options) {
|
|
23
25
|
const kind = options.kind ?? (file.typical ? 'simulated' : 'measured');
|
|
24
26
|
const name = options.name !== undefined ? options.name : file.typical ? `typical year ${file.years[0]}-${file.years[file.years.length - 1]}` : null;
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
return atomically(db, async () => {
|
|
28
|
+
const series = [];
|
|
29
|
+
for (const s of file.series) {
|
|
30
|
+
const stored = await storeSeries(db, { organisationId: target.organisationId, objectKind: target.objectKind, objectId: target.objectId, sourceCode: options.sourceCode, kind, name }, s);
|
|
31
|
+
series.push({ quantity_code: s.quantity_code, ...stored });
|
|
32
|
+
}
|
|
33
|
+
return { series, warnings: file.warnings };
|
|
34
|
+
});
|
|
31
35
|
}
|
|
32
36
|
/**
|
|
33
37
|
* The weather series of an object for one calendar year in the location's
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The history of a WeSmart Database, imported table to table into the core.
|
|
3
|
+
*
|
|
4
|
+
* The WeSmart Database keeps, for each project, the participants with the
|
|
5
|
+
* meter they carry in a column (`participants.smart_meter_id`) and their
|
|
6
|
+
* address beside it (`participants.address`, `latitude`, `longitude`), and
|
|
7
|
+
* the devices behind each participant (`devices.participant_id`). The core
|
|
8
|
+
* has the same hierarchy with the meter as an object of its own
|
|
9
|
+
* (decision 0043):
|
|
10
|
+
*
|
|
11
|
+
* | WeSmart Database | Core |
|
|
12
|
+
* |---|---|
|
|
13
|
+
* | `organisations` | `organisations` (`create_organisation()`) |
|
|
14
|
+
* | `projects` | `projects` (`create_project()`), its country and status |
|
|
15
|
+
* | `participants` | `participants` (`join_project()`), with its place |
|
|
16
|
+
* | `participants.address`, `postal_code`, `city`, `latitude`, `longitude`, `country` | the participant's place, in the one standard shape |
|
|
17
|
+
* | `participants.smart_meter_id` | `meters` (`declare_meter()`), carried by the participant |
|
|
18
|
+
* | `devices.participant_id` | `devices.participant_id` (`install_device()`), unchanged |
|
|
19
|
+
*
|
|
20
|
+
* Two steps. `planWesmartImport()` is pure: it reads the rows and names, for
|
|
21
|
+
* each, the gesture that writes it, or why it cannot be written (a refusal
|
|
22
|
+
* by name, with its table and its id); a value it does not carry is counted
|
|
23
|
+
* by its column, never dropped without a word. `importWesmartHistory()`
|
|
24
|
+
* writes a plan through the schema's own gestures, acting as the person, and
|
|
25
|
+
* records on every object the row it came from (`identifiers`, scheme
|
|
26
|
+
* `imported_row`, `wesmart_db:<table>:<id>`): a second import finds the
|
|
27
|
+
* object and writes nothing again.
|
|
28
|
+
*
|
|
29
|
+
* Nothing is guessed. A meter's scheme is the one the grid operators of the
|
|
30
|
+
* participant's country issue and whose pattern its number matches
|
|
31
|
+
* (`meterSchemesOf()`); a placeholder number (`VIRTUAL-…`) names no
|
|
32
|
+
* connection point and declares no meter. The series of the WeSmart Database
|
|
33
|
+
* (its `flows`, profiles and imported readings) are the next step, not this
|
|
34
|
+
* one: they are counted as not carried.
|
|
35
|
+
*/
|
|
36
|
+
import type { Db } from '../db.js';
|
|
37
|
+
/** The database the rows come from, as the prefix of the identifier of every object imported. */
|
|
38
|
+
export declare const WESMART_DB = "wesmart_db";
|
|
39
|
+
/** The identifier scheme that records the row an object was imported from. */
|
|
40
|
+
export declare const IMPORTED_ROW_SCHEME = "imported_row";
|
|
41
|
+
/** A row as read from the database: its columns, any of them null. Numbers may come as text (`numeric`). */
|
|
42
|
+
type Row = Record<string, unknown> & {
|
|
43
|
+
id: string;
|
|
44
|
+
};
|
|
45
|
+
export interface WesmartOrganisation extends Row {
|
|
46
|
+
name?: string | null;
|
|
47
|
+
}
|
|
48
|
+
export interface WesmartProject extends Row {
|
|
49
|
+
name?: string | null;
|
|
50
|
+
organisation_id?: string | null;
|
|
51
|
+
owner_id?: string | null;
|
|
52
|
+
country?: string | null;
|
|
53
|
+
status?: string | null;
|
|
54
|
+
start_date?: string | null;
|
|
55
|
+
created_at?: string | null;
|
|
56
|
+
}
|
|
57
|
+
export interface WesmartParticipant extends Row {
|
|
58
|
+
project_id?: string | null;
|
|
59
|
+
name?: string | null;
|
|
60
|
+
status?: string | null;
|
|
61
|
+
address?: string | null;
|
|
62
|
+
postal_code?: string | null;
|
|
63
|
+
city?: string | null;
|
|
64
|
+
country?: string | null;
|
|
65
|
+
latitude?: number | string | null;
|
|
66
|
+
longitude?: number | string | null;
|
|
67
|
+
smart_meter_id?: string | null;
|
|
68
|
+
power?: number | string | null;
|
|
69
|
+
consumption?: number | string | null;
|
|
70
|
+
join_date?: string | null;
|
|
71
|
+
leave_date?: string | null;
|
|
72
|
+
archived_at?: string | null;
|
|
73
|
+
created_at?: string | null;
|
|
74
|
+
}
|
|
75
|
+
export interface WesmartDevice extends Row {
|
|
76
|
+
participant_id?: string | null;
|
|
77
|
+
name?: string | null;
|
|
78
|
+
device_type?: string | null;
|
|
79
|
+
manufacturer?: string | null;
|
|
80
|
+
model?: string | null;
|
|
81
|
+
power?: number | string | null;
|
|
82
|
+
installation_date?: string | null;
|
|
83
|
+
status?: string | null;
|
|
84
|
+
created_at?: string | null;
|
|
85
|
+
}
|
|
86
|
+
/** The tables read, as rows (`select * from <table>`). */
|
|
87
|
+
export interface WesmartSnapshot {
|
|
88
|
+
organisations?: WesmartOrganisation[];
|
|
89
|
+
projects: WesmartProject[];
|
|
90
|
+
participants: WesmartParticipant[];
|
|
91
|
+
devices?: WesmartDevice[];
|
|
92
|
+
}
|
|
93
|
+
export type WesmartTable = 'organisations' | 'projects' | 'participants' | 'devices';
|
|
94
|
+
/** A row that is not written, by the name of the reason. */
|
|
95
|
+
export interface ImportRefusal {
|
|
96
|
+
code: string;
|
|
97
|
+
table: WesmartTable;
|
|
98
|
+
id: string;
|
|
99
|
+
detail: string;
|
|
100
|
+
}
|
|
101
|
+
/** A column of a table whose values this import does not carry, with the rows that hold one. */
|
|
102
|
+
export interface NotCarried {
|
|
103
|
+
table: WesmartTable;
|
|
104
|
+
column: string;
|
|
105
|
+
rows: number;
|
|
106
|
+
}
|
|
107
|
+
export interface PlannedOrganisation {
|
|
108
|
+
key: string;
|
|
109
|
+
name: string;
|
|
110
|
+
}
|
|
111
|
+
export interface PlannedProject {
|
|
112
|
+
key: string;
|
|
113
|
+
/** The planned organisation it is in, or the id of an organisation of the core. */
|
|
114
|
+
organisation: {
|
|
115
|
+
key: string;
|
|
116
|
+
} | {
|
|
117
|
+
id: string;
|
|
118
|
+
};
|
|
119
|
+
name: string;
|
|
120
|
+
country: string;
|
|
121
|
+
status: string | null;
|
|
122
|
+
start_date: string | null;
|
|
123
|
+
}
|
|
124
|
+
export interface PlannedPlace {
|
|
125
|
+
country: string;
|
|
126
|
+
address_line1?: string;
|
|
127
|
+
postal_code?: string;
|
|
128
|
+
city?: string;
|
|
129
|
+
geometry?: {
|
|
130
|
+
type: 'Point';
|
|
131
|
+
coordinates: [number, number, number];
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
export interface PlannedParticipant {
|
|
135
|
+
key: string;
|
|
136
|
+
project_key: string;
|
|
137
|
+
name: string;
|
|
138
|
+
category: 'consumer' | 'producer' | 'prosumer';
|
|
139
|
+
status: string;
|
|
140
|
+
join_date: string | null;
|
|
141
|
+
leave_date: string | null;
|
|
142
|
+
place: PlannedPlace;
|
|
143
|
+
}
|
|
144
|
+
export interface PlannedMeter {
|
|
145
|
+
key: string;
|
|
146
|
+
participant_key: string;
|
|
147
|
+
identifier: string;
|
|
148
|
+
scheme: string;
|
|
149
|
+
}
|
|
150
|
+
export interface PlannedDevice {
|
|
151
|
+
key: string;
|
|
152
|
+
participant_key: string;
|
|
153
|
+
device_type: string;
|
|
154
|
+
name: string;
|
|
155
|
+
rated_power_kw: number | null;
|
|
156
|
+
installed_on: string | null;
|
|
157
|
+
status: string | null;
|
|
158
|
+
nameplate: {
|
|
159
|
+
manufacturer?: string;
|
|
160
|
+
model?: string;
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
export interface WesmartImportPlan {
|
|
164
|
+
organisations: PlannedOrganisation[];
|
|
165
|
+
projects: PlannedProject[];
|
|
166
|
+
participants: PlannedParticipant[];
|
|
167
|
+
meters: PlannedMeter[];
|
|
168
|
+
devices: PlannedDevice[];
|
|
169
|
+
refusals: ImportRefusal[];
|
|
170
|
+
notCarried: NotCarried[];
|
|
171
|
+
}
|
|
172
|
+
/** A scheme a meter number may be in: the grid operators of a country issue it, its pattern says which numbers. */
|
|
173
|
+
export interface MeterScheme {
|
|
174
|
+
country: string;
|
|
175
|
+
scheme: string;
|
|
176
|
+
pattern: string | null;
|
|
177
|
+
}
|
|
178
|
+
export interface WesmartPlanOptions {
|
|
179
|
+
/** The schemes of the connection points, by country (`meterSchemesOf()`). */
|
|
180
|
+
meterSchemes: MeterScheme[];
|
|
181
|
+
/**
|
|
182
|
+
* The organisation of the core a project without an organisation goes
|
|
183
|
+
* into (a project its owner kept alone). Without it such a project is
|
|
184
|
+
* refused, `project_organisation_required`.
|
|
185
|
+
*/
|
|
186
|
+
organisationForOwnProjects?: string;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* The device types of the WeSmart Database, by the core's `device_types`
|
|
190
|
+
* code. A type absent here is refused, `device_type_unmapped`.
|
|
191
|
+
*/
|
|
192
|
+
export declare const WESMART_DEVICE_TYPES: Readonly<Record<string, string>>;
|
|
193
|
+
/** The identifier an object imported from a row is recorded under. */
|
|
194
|
+
export declare function importedRowKey(table: WesmartTable, id: string): string;
|
|
195
|
+
/** The meter number as the WeSmart Database compares it: spaces removed (`normalizeMeterId`). */
|
|
196
|
+
export declare function normaliseMeterNumber(value: string): string;
|
|
197
|
+
/**
|
|
198
|
+
* What every row of a WeSmart Database becomes in the core, or why it does
|
|
199
|
+
* not. Pure: reads the rows and the options, touches nothing.
|
|
200
|
+
*
|
|
201
|
+
* A refused row refuses what hangs from it (`parent_refused`): the
|
|
202
|
+
* participants of a refused project, the meter and the devices of a refused
|
|
203
|
+
* participant. Two participants of one project carrying one meter
|
|
204
|
+
* number are one connection point: the first entered carries the meter, the
|
|
205
|
+
* others are refused theirs (`meter_shared`) and keep their own row.
|
|
206
|
+
*/
|
|
207
|
+
export declare function planWesmartImport(snapshot: WesmartSnapshot, options: WesmartPlanOptions): WesmartImportPlan;
|
|
208
|
+
export interface WesmartImportResult {
|
|
209
|
+
/** The id in the core of every object of the plan, by its key. */
|
|
210
|
+
ids: Record<string, string>;
|
|
211
|
+
/** What was written now, and what a previous import had written already, by kind. */
|
|
212
|
+
created: Record<'organisations' | 'projects' | 'participants' | 'meters' | 'devices', number>;
|
|
213
|
+
alreadyImported: Record<'organisations' | 'projects' | 'participants' | 'meters' | 'devices', number>;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* The schemes of the connection points by country: those the grid operators
|
|
217
|
+
* of the `grid` module issue, with their pattern. Refuses
|
|
218
|
+
* `module_not_installed` when the module is not.
|
|
219
|
+
*/
|
|
220
|
+
export declare function meterSchemesOf(db: Db): Promise<MeterScheme[]>;
|
|
221
|
+
/**
|
|
222
|
+
* Writes a plan, as the person the connection acts as, each object through
|
|
223
|
+
* the gesture of its kind; finds first, by the row it came from, what a
|
|
224
|
+
* previous import wrote, and writes it no second time. Run it in one
|
|
225
|
+
* transaction (`Session.run()`): a refusal of the database stops it whole,
|
|
226
|
+
* with the name of the refusal and the row it was writing.
|
|
227
|
+
*/
|
|
228
|
+
export declare function importWesmartHistory(db: Db, plan: WesmartImportPlan): Promise<WesmartImportResult>;
|
|
229
|
+
export {};
|
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
import { GestureError } from '../refusal.js';
|
|
2
|
+
/** The database the rows come from, as the prefix of the identifier of every object imported. */
|
|
3
|
+
export const WESMART_DB = 'wesmart_db';
|
|
4
|
+
/** The identifier scheme that records the row an object was imported from. */
|
|
5
|
+
export const IMPORTED_ROW_SCHEME = 'imported_row';
|
|
6
|
+
/**
|
|
7
|
+
* The device types of the WeSmart Database, by the core's `device_types`
|
|
8
|
+
* code. A type absent here is refused, `device_type_unmapped`.
|
|
9
|
+
*/
|
|
10
|
+
export const WESMART_DEVICE_TYPES = {
|
|
11
|
+
solar: 'solar',
|
|
12
|
+
parking_canopy: 'parking_canopy',
|
|
13
|
+
wind: 'wind',
|
|
14
|
+
hydro: 'hydro',
|
|
15
|
+
chp: 'cogeneration',
|
|
16
|
+
biomass: 'biomass',
|
|
17
|
+
geothermal: 'geothermal',
|
|
18
|
+
hydrogen: 'hydrogen',
|
|
19
|
+
battery: 'battery',
|
|
20
|
+
inverter: 'inverter',
|
|
21
|
+
heatpump: 'heat_pump',
|
|
22
|
+
heat_pump: 'heat_pump',
|
|
23
|
+
ev: 'charger',
|
|
24
|
+
ev_charger: 'charger',
|
|
25
|
+
};
|
|
26
|
+
/** The device types that produce, as the WeSmart Database lists them (`PRODUCTION_DEVICE_TYPES`). */
|
|
27
|
+
const PRODUCING = new Set(['solar', 'parking_canopy', 'wind', 'chp', 'hydro', 'geothermal', 'biomass']);
|
|
28
|
+
/** A device's status, by the core's (`devices_status`). Null keeps the core's rule: planned until installed. */
|
|
29
|
+
const DEVICE_STATUSES = {
|
|
30
|
+
active: 'in_service',
|
|
31
|
+
inactive: 'out_of_service',
|
|
32
|
+
planned: 'planned',
|
|
33
|
+
};
|
|
34
|
+
/** The statuses both databases share, word for word. */
|
|
35
|
+
const PROJECT_STATUSES = new Set(['simulation', 'creation', 'active', 'inactive', 'archived']);
|
|
36
|
+
const PARTICIPANT_STATUSES = new Set(['simulation', 'creation', 'active', 'inactive']);
|
|
37
|
+
/** The columns each table's mapping reads; any other column holding a value is counted as not carried. */
|
|
38
|
+
const CARRIED = {
|
|
39
|
+
organisations: new Set(['id', 'name']),
|
|
40
|
+
projects: new Set(['id', 'name', 'organisation_id', 'owner_id', 'country', 'status', 'start_date']),
|
|
41
|
+
participants: new Set(['id', 'project_id', 'name', 'status', 'address', 'postal_code', 'city', 'country', 'latitude',
|
|
42
|
+
'longitude', 'smart_meter_id', 'power', 'consumption', 'join_date', 'leave_date', 'archived_at']),
|
|
43
|
+
devices: new Set(['id', 'participant_id', 'name', 'device_type', 'manufacturer', 'model', 'power', 'installation_date', 'status']),
|
|
44
|
+
};
|
|
45
|
+
/** Bookkeeping columns: the database's, not a description. */
|
|
46
|
+
const BOOKKEEPING = new Set(['created_at', 'updated_at']);
|
|
47
|
+
/** The identifier an object imported from a row is recorded under. */
|
|
48
|
+
export function importedRowKey(table, id) {
|
|
49
|
+
return `${WESMART_DB}:${table}:${id}`;
|
|
50
|
+
}
|
|
51
|
+
/** The key of the meter a participant's `smart_meter_id` becomes. */
|
|
52
|
+
function meterKey(participantId) {
|
|
53
|
+
return `${importedRowKey('participants', participantId)}:smart_meter_id`;
|
|
54
|
+
}
|
|
55
|
+
/** The meter number as the WeSmart Database compares it: spaces removed (`normalizeMeterId`). */
|
|
56
|
+
export function normaliseMeterNumber(value) {
|
|
57
|
+
return value.replace(/\s/g, '');
|
|
58
|
+
}
|
|
59
|
+
/** A placeholder for a number not known yet: `VIRTUAL-` and letters, digits, dashes. */
|
|
60
|
+
const VIRTUAL_METER = /^VIRTUAL-[A-Z0-9][A-Z0-9-]*$/i;
|
|
61
|
+
function text(v) {
|
|
62
|
+
if (typeof v !== 'string')
|
|
63
|
+
return null;
|
|
64
|
+
const t = v.trim();
|
|
65
|
+
return t === '' ? null : t;
|
|
66
|
+
}
|
|
67
|
+
/** A number as `numeric` comes: a number or its text. Null when neither. */
|
|
68
|
+
function number(v) {
|
|
69
|
+
if (typeof v === 'number')
|
|
70
|
+
return Number.isFinite(v) ? v : null;
|
|
71
|
+
if (typeof v === 'string' && v.trim() !== '' && Number.isFinite(Number(v)))
|
|
72
|
+
return Number(v);
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
/** A date as `YYYY-MM-DD`, from a date or the date part of a timestamp. */
|
|
76
|
+
function day(v) {
|
|
77
|
+
const t = text(v);
|
|
78
|
+
const m = t === null ? null : /^(\d{4}-\d{2}-\d{2})/.exec(t);
|
|
79
|
+
return m ? m[1] : null;
|
|
80
|
+
}
|
|
81
|
+
function byCreation(rows) {
|
|
82
|
+
return [...rows].sort((a, b) => String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')) || a.id.localeCompare(b.id));
|
|
83
|
+
}
|
|
84
|
+
function held(v) {
|
|
85
|
+
if (v === null || v === undefined)
|
|
86
|
+
return false;
|
|
87
|
+
if (typeof v === 'string')
|
|
88
|
+
return v.trim() !== '';
|
|
89
|
+
if (Array.isArray(v))
|
|
90
|
+
return v.length > 0;
|
|
91
|
+
if (typeof v === 'object')
|
|
92
|
+
return Object.keys(v).length > 0;
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* What every row of a WeSmart Database becomes in the core, or why it does
|
|
97
|
+
* not. Pure: reads the rows and the options, touches nothing.
|
|
98
|
+
*
|
|
99
|
+
* A refused row refuses what hangs from it (`parent_refused`): the
|
|
100
|
+
* participants of a refused project, the meter and the devices of a refused
|
|
101
|
+
* participant. Two participants of one project carrying one meter
|
|
102
|
+
* number are one connection point: the first entered carries the meter, the
|
|
103
|
+
* others are refused theirs (`meter_shared`) and keep their own row.
|
|
104
|
+
*/
|
|
105
|
+
export function planWesmartImport(snapshot, options) {
|
|
106
|
+
const plan = { organisations: [], projects: [], participants: [], meters: [], devices: [], refusals: [], notCarried: [] };
|
|
107
|
+
const refuse = (code, table, id, detail) => plan.refusals.push({ code, table, id, detail });
|
|
108
|
+
const notCarried = new Map();
|
|
109
|
+
const count = (table, column) => {
|
|
110
|
+
const k = `${table}.${column}`;
|
|
111
|
+
const entry = notCarried.get(k) ?? { table, column, rows: 0 };
|
|
112
|
+
entry.rows += 1;
|
|
113
|
+
notCarried.set(k, entry);
|
|
114
|
+
};
|
|
115
|
+
const audit = (table, row) => {
|
|
116
|
+
for (const [column, value] of Object.entries(row)) {
|
|
117
|
+
if (!CARRIED[table].has(column) && !BOOKKEEPING.has(column) && held(value))
|
|
118
|
+
count(table, column);
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
const seen = new Map();
|
|
122
|
+
const firstTime = (table, row) => {
|
|
123
|
+
const ids = seen.get(table) ?? new Set();
|
|
124
|
+
seen.set(table, ids);
|
|
125
|
+
if (typeof row.id !== 'string' || row.id === '') {
|
|
126
|
+
refuse('row_id_required', table, String(row.id ?? ''), 'a row without its id cannot be found again');
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
if (ids.has(row.id)) {
|
|
130
|
+
refuse('row_duplicated', table, row.id, 'the snapshot holds this row twice');
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
ids.add(row.id);
|
|
134
|
+
return true;
|
|
135
|
+
};
|
|
136
|
+
// Organisations.
|
|
137
|
+
const organisations = new Set();
|
|
138
|
+
for (const o of byCreation(snapshot.organisations ?? [])) {
|
|
139
|
+
if (!firstTime('organisations', o))
|
|
140
|
+
continue;
|
|
141
|
+
audit('organisations', o);
|
|
142
|
+
const name = text(o.name);
|
|
143
|
+
if (name === null) {
|
|
144
|
+
refuse('organisation_name_required', 'organisations', o.id, 'an organisation has a name');
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
plan.organisations.push({ key: importedRowKey('organisations', o.id), name });
|
|
148
|
+
organisations.add(o.id);
|
|
149
|
+
}
|
|
150
|
+
// Projects.
|
|
151
|
+
const projects = new Map();
|
|
152
|
+
for (const p of byCreation(snapshot.projects)) {
|
|
153
|
+
if (!firstTime('projects', p))
|
|
154
|
+
continue;
|
|
155
|
+
audit('projects', p);
|
|
156
|
+
const name = text(p.name);
|
|
157
|
+
const country = text(p.country)?.toUpperCase() ?? null;
|
|
158
|
+
const status = text(p.status);
|
|
159
|
+
const organisationId = text(p.organisation_id);
|
|
160
|
+
let organisation;
|
|
161
|
+
if (organisationId !== null) {
|
|
162
|
+
if (!organisations.has(organisationId)) {
|
|
163
|
+
const known = (snapshot.organisations ?? []).some((o) => o.id === organisationId);
|
|
164
|
+
refuse(known ? 'parent_refused' : 'organisation_not_found', 'projects', p.id, `its organisation ${organisationId} is ${known ? 'refused' : 'not in the snapshot'}`);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
organisation = { key: importedRowKey('organisations', organisationId) };
|
|
168
|
+
}
|
|
169
|
+
else if (options.organisationForOwnProjects !== undefined) {
|
|
170
|
+
organisation = { id: options.organisationForOwnProjects };
|
|
171
|
+
}
|
|
172
|
+
else {
|
|
173
|
+
refuse('project_organisation_required', 'projects', p.id, 'the project is in no organisation, and none was given for such projects');
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (name === null) {
|
|
177
|
+
refuse('project_name_required', 'projects', p.id, 'a project has a name');
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
if (country === null || !/^[A-Z]{2}$/.test(country)) {
|
|
181
|
+
refuse('country_required', 'projects', p.id, `a project names the ISO 3166-1 alpha-2 country whose rules apply; it has ${JSON.stringify(p.country ?? null)}`);
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (status !== null && !PROJECT_STATUSES.has(status)) {
|
|
185
|
+
refuse('project_status_unknown', 'projects', p.id, `${status} is not a status of a project`);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const planned = { key: importedRowKey('projects', p.id), organisation, name, country, status, start_date: day(p.start_date) };
|
|
189
|
+
plan.projects.push(planned);
|
|
190
|
+
projects.set(p.id, planned);
|
|
191
|
+
}
|
|
192
|
+
// Devices, by participant, so that a participant knows whether it produces.
|
|
193
|
+
const devicesOf = new Map();
|
|
194
|
+
for (const d of snapshot.devices ?? []) {
|
|
195
|
+
const pid = text(d.participant_id);
|
|
196
|
+
if (pid === null)
|
|
197
|
+
continue;
|
|
198
|
+
devicesOf.set(pid, [...(devicesOf.get(pid) ?? []), d]);
|
|
199
|
+
}
|
|
200
|
+
// Participants, their place and their meter.
|
|
201
|
+
const participants = new Map();
|
|
202
|
+
const meterCarriers = new Map();
|
|
203
|
+
for (const p of byCreation(snapshot.participants)) {
|
|
204
|
+
if (!firstTime('participants', p))
|
|
205
|
+
continue;
|
|
206
|
+
audit('participants', p);
|
|
207
|
+
const projectId = text(p.project_id);
|
|
208
|
+
const project = projectId === null ? undefined : projects.get(projectId);
|
|
209
|
+
if (project === undefined) {
|
|
210
|
+
const known = snapshot.projects.some((r) => r.id === projectId);
|
|
211
|
+
refuse(known ? 'parent_refused' : 'project_not_found', 'participants', p.id, `its project ${projectId ?? 'is not given'}${projectId === null ? '' : known ? ' is refused' : ' is not in the snapshot'}`);
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const name = text(p.name);
|
|
215
|
+
if (name === null) {
|
|
216
|
+
refuse('participant_name_required', 'participants', p.id, 'a participant has a name');
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const status = p.archived_at ? 'inactive' : (text(p.status) ?? 'simulation');
|
|
220
|
+
if (!PARTICIPANT_STATUSES.has(status)) {
|
|
221
|
+
refuse('participant_status_unknown', 'participants', p.id, `${status} is not a status of a participant`);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
// The place: what the row says, in the country of the participant, or
|
|
225
|
+
// of its project when the row names none.
|
|
226
|
+
const country = text(p.country)?.toUpperCase() ?? project.country;
|
|
227
|
+
if (!/^[A-Z]{2}$/.test(country)) {
|
|
228
|
+
refuse('country_invalid', 'participants', p.id, `${JSON.stringify(p.country)} is not an ISO 3166-1 alpha-2 code`);
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
const place = { country };
|
|
232
|
+
const line = text(p.address);
|
|
233
|
+
const postal = text(p.postal_code);
|
|
234
|
+
const city = text(p.city);
|
|
235
|
+
if (line !== null)
|
|
236
|
+
place.address_line1 = line;
|
|
237
|
+
if (postal !== null)
|
|
238
|
+
place.postal_code = postal;
|
|
239
|
+
if (city !== null)
|
|
240
|
+
place.city = city;
|
|
241
|
+
const lat = number(p.latitude);
|
|
242
|
+
const lon = number(p.longitude);
|
|
243
|
+
if (lat !== null && lon !== null && Math.abs(lat) <= 90 && Math.abs(lon) <= 180) {
|
|
244
|
+
place.geometry = { type: 'Point', coordinates: [lon, lat, 0] };
|
|
245
|
+
}
|
|
246
|
+
else if (held(p.latitude) || held(p.longitude)) {
|
|
247
|
+
count('participants', 'latitude, longitude (not a point)');
|
|
248
|
+
}
|
|
249
|
+
// What it does: it produces when it carries a power or a producing
|
|
250
|
+
// device, it consumes when it carries a consumption.
|
|
251
|
+
const devices = devicesOf.get(p.id) ?? [];
|
|
252
|
+
const produces = (number(p.power) ?? 0) > 0 || devices.some((d) => PRODUCING.has(text(d.device_type) ?? ''));
|
|
253
|
+
const consumes = (number(p.consumption) ?? 0) > 0;
|
|
254
|
+
const category = produces ? (consumes ? 'prosumer' : 'producer') : 'consumer';
|
|
255
|
+
const planned = {
|
|
256
|
+
key: importedRowKey('participants', p.id), project_key: project.key, name, category, status,
|
|
257
|
+
join_date: day(p.join_date), leave_date: day(p.leave_date), place,
|
|
258
|
+
};
|
|
259
|
+
plan.participants.push(planned);
|
|
260
|
+
participants.set(p.id, planned);
|
|
261
|
+
// Its meter.
|
|
262
|
+
const raw = text(p.smart_meter_id);
|
|
263
|
+
if (raw === null)
|
|
264
|
+
continue;
|
|
265
|
+
const number_ = normaliseMeterNumber(raw);
|
|
266
|
+
if (VIRTUAL_METER.test(number_)) {
|
|
267
|
+
refuse('meter_virtual', 'participants', p.id, `${number_} is a placeholder, not a connection point an operator knows`);
|
|
268
|
+
continue;
|
|
269
|
+
}
|
|
270
|
+
const schemes = options.meterSchemes.filter((s) => s.country.toUpperCase() === country && (s.pattern === null || new RegExp(s.pattern).test(number_)));
|
|
271
|
+
const distinct = [...new Set(schemes.map((s) => s.scheme))];
|
|
272
|
+
if (distinct.length !== 1) {
|
|
273
|
+
refuse(distinct.length === 0 ? 'meter_scheme_unknown' : 'meter_scheme_ambiguous', 'participants', p.id, distinct.length === 0
|
|
274
|
+
? `${number_} matches no scheme of the connection points of ${country}`
|
|
275
|
+
: `${number_} matches ${distinct.join(', ')} in ${country}`);
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
// One open participant per connection point within a project.
|
|
279
|
+
const point = `${project.key}|${distinct[0]}|${number_}`;
|
|
280
|
+
const carrier = meterCarriers.get(point);
|
|
281
|
+
if (carrier !== undefined) {
|
|
282
|
+
refuse('meter_shared', 'participants', p.id, `${number_} is carried by ${carrier} in the same project; one connection point is one meter`);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
meterCarriers.set(point, planned.key);
|
|
286
|
+
plan.meters.push({ key: meterKey(p.id), participant_key: planned.key, identifier: number_, scheme: distinct[0] });
|
|
287
|
+
}
|
|
288
|
+
// Devices: each stays with its participant.
|
|
289
|
+
for (const d of byCreation(snapshot.devices ?? [])) {
|
|
290
|
+
if (!firstTime('devices', d))
|
|
291
|
+
continue;
|
|
292
|
+
audit('devices', d);
|
|
293
|
+
const pid = text(d.participant_id);
|
|
294
|
+
const participant = pid === null ? undefined : participants.get(pid);
|
|
295
|
+
if (participant === undefined) {
|
|
296
|
+
const known = snapshot.participants.some((r) => r.id === pid);
|
|
297
|
+
refuse(known ? 'parent_refused' : 'participant_not_found', 'devices', d.id, `its participant ${pid ?? 'is not given'}${pid === null ? '' : known ? ' is refused' : ' is not in the snapshot'}`);
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
const source = text(d.device_type);
|
|
301
|
+
const type = source === null ? undefined : WESMART_DEVICE_TYPES[source];
|
|
302
|
+
if (type === undefined) {
|
|
303
|
+
refuse('device_type_unmapped', 'devices', d.id, `${JSON.stringify(source)} has no device type of the core`);
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const manufacturer = text(d.manufacturer);
|
|
307
|
+
const model = text(d.model);
|
|
308
|
+
const name = text(d.name) ?? ([manufacturer, model].filter(Boolean).join(' ') || null);
|
|
309
|
+
if (name === null) {
|
|
310
|
+
refuse('device_name_required', 'devices', d.id, 'a device has a name, or a manufacturer and a model');
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
const status = text(d.status);
|
|
314
|
+
if (status !== null && DEVICE_STATUSES[status] === undefined) {
|
|
315
|
+
refuse('device_status_unknown', 'devices', d.id, `${status} is not a status of a device`);
|
|
316
|
+
continue;
|
|
317
|
+
}
|
|
318
|
+
const power = number(d.power);
|
|
319
|
+
if (power !== null && power < 0) {
|
|
320
|
+
refuse('device_power_negative', 'devices', d.id, `${power} kW`);
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
plan.devices.push({
|
|
324
|
+
key: importedRowKey('devices', d.id), participant_key: participant.key, device_type: type, name,
|
|
325
|
+
rated_power_kw: power, installed_on: day(d.installation_date), status: status === null ? null : DEVICE_STATUSES[status],
|
|
326
|
+
nameplate: { ...(manufacturer ? { manufacturer } : {}), ...(model ? { model } : {}) },
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
plan.notCarried = [...notCarried.values()].sort((a, b) => a.table.localeCompare(b.table) || a.column.localeCompare(b.column));
|
|
330
|
+
return plan;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* The schemes of the connection points by country: those the grid operators
|
|
334
|
+
* of the `grid` module issue, with their pattern. Refuses
|
|
335
|
+
* `module_not_installed` when the module is not.
|
|
336
|
+
*/
|
|
337
|
+
export async function meterSchemesOf(db) {
|
|
338
|
+
const { rows: [installed] } = await db.query(`select to_regclass('grid.operators') is not null ok`);
|
|
339
|
+
if (!installed?.ok)
|
|
340
|
+
throw new GestureError('module_not_installed: grid — the schemes of the connection points are those its operators issue');
|
|
341
|
+
const { rows } = await db.query(`select distinct o.country, o.identifier_scheme scheme, s.pattern
|
|
342
|
+
from grid.operators o join identifier_schemes s on s.code = o.identifier_scheme
|
|
343
|
+
order by 1, 2`);
|
|
344
|
+
return rows;
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Writes a plan, as the person the connection acts as, each object through
|
|
348
|
+
* the gesture of its kind; finds first, by the row it came from, what a
|
|
349
|
+
* previous import wrote, and writes it no second time. Run it in one
|
|
350
|
+
* transaction (`Session.run()`): a refusal of the database stops it whole,
|
|
351
|
+
* with the name of the refusal and the row it was writing.
|
|
352
|
+
*/
|
|
353
|
+
export async function importWesmartHistory(db, plan) {
|
|
354
|
+
const ids = {};
|
|
355
|
+
const zero = () => ({ organisations: 0, projects: 0, participants: 0, meters: 0, devices: 0 });
|
|
356
|
+
const result = { ids, created: zero(), alreadyImported: zero() };
|
|
357
|
+
const found = async (key) => {
|
|
358
|
+
const { rows } = await db.query('select object_id from identifiers where scheme = $1 and value = $2', [IMPORTED_ROW_SCHEME, key]);
|
|
359
|
+
return rows[0]?.object_id;
|
|
360
|
+
};
|
|
361
|
+
const idOf = (key) => {
|
|
362
|
+
const id = ids[key];
|
|
363
|
+
if (id === undefined)
|
|
364
|
+
throw new GestureError(`parent_not_imported: ${key} is not in the plan`);
|
|
365
|
+
return id;
|
|
366
|
+
};
|
|
367
|
+
const write = async (kind, key, sql, params, after) => {
|
|
368
|
+
const existing = await found(key);
|
|
369
|
+
if (existing !== undefined) {
|
|
370
|
+
ids[key] = existing;
|
|
371
|
+
result.alreadyImported[kind] += 1;
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
try {
|
|
375
|
+
const { rows: [row] } = await db.query(sql, params);
|
|
376
|
+
ids[key] = row.id;
|
|
377
|
+
if (after)
|
|
378
|
+
await after(row.id);
|
|
379
|
+
}
|
|
380
|
+
catch (error) {
|
|
381
|
+
throw new GestureError(`${String(error?.message ?? error)} (while importing ${key})`);
|
|
382
|
+
}
|
|
383
|
+
result.created[kind] += 1;
|
|
384
|
+
};
|
|
385
|
+
// `add_identifier()` records the row in the statement that creates the
|
|
386
|
+
// object, so that an object is never written without it.
|
|
387
|
+
for (const o of plan.organisations) {
|
|
388
|
+
await write('organisations', o.key, `with c as (select create_organisation($1) id) select c.id, add_identifier('organisation', c.id, $2, $3) from c`, [o.name, IMPORTED_ROW_SCHEME, o.key]);
|
|
389
|
+
}
|
|
390
|
+
for (const p of plan.projects) {
|
|
391
|
+
const organisation = 'id' in p.organisation ? p.organisation.id : idOf(p.organisation.key);
|
|
392
|
+
await write('projects', p.key, `with c as (select create_project($1, $2, $3, null, $4) id) select c.id, add_identifier('project', c.id, $5, $6) from c`, [organisation, p.name, p.country, p.start_date, IMPORTED_ROW_SCHEME, p.key], async (id) => {
|
|
393
|
+
if (p.status !== null)
|
|
394
|
+
await db.query('update projects set status = $2 where id = $1', [id, p.status]);
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
for (const p of plan.participants) {
|
|
398
|
+
const place = { ...p.place, identifiers: [{ scheme: IMPORTED_ROW_SCHEME, value: p.key }] };
|
|
399
|
+
await write('participants', p.key, `select join_project($1, $2, $3::jsonb, $4, null, $5, $6) id`, [idOf(p.project_key), p.name, JSON.stringify(place), p.category, p.join_date, p.status], async (id) => {
|
|
400
|
+
if (p.leave_date !== null)
|
|
401
|
+
await db.query('select leave_project($1, $2)', [id, p.leave_date]);
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
for (const m of plan.meters) {
|
|
405
|
+
await write('meters', m.key, `with c as (select declare_meter($1, $2, $3, 'electricity', 'both', null, null) id) select c.id, add_identifier('meter', c.id, $4, $5) from c`, [idOf(m.participant_key), m.identifier, m.scheme, IMPORTED_ROW_SCHEME, m.key]);
|
|
406
|
+
}
|
|
407
|
+
for (const d of plan.devices) {
|
|
408
|
+
await write('devices', d.key, `with c as (select install_device($1, $2, $3, null, $4, $5, null, 1, $6::jsonb, $7) id) select c.id, add_identifier('device', c.id, $8, $9) from c`, [idOf(d.participant_key), d.device_type, d.name, d.rated_power_kw, d.installed_on, JSON.stringify(d.nameplate), d.status,
|
|
409
|
+
IMPORTED_ROW_SCHEME, d.key]);
|
|
410
|
+
}
|
|
411
|
+
return result;
|
|
412
|
+
}
|