@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.
Files changed (49) hide show
  1. package/README.md +2 -2
  2. package/dist/address.d.ts +3 -62
  3. package/dist/connectors/activations.d.ts +63 -0
  4. package/dist/connectors/activations.js +73 -0
  5. package/dist/connectors/devices.d.ts +132 -0
  6. package/dist/connectors/devices.js +125 -0
  7. package/dist/connectors/interfaces.d.ts +2 -104
  8. package/dist/connectors/interfaces.js +4 -11
  9. package/dist/connectors/measured.d.ts +12 -0
  10. package/dist/connectors/measured.js +44 -0
  11. package/dist/connectors/meter-data.d.ts +2 -39
  12. package/dist/connectors/meter-data.js +3 -13
  13. package/dist/connectors/settlement.js +2 -2
  14. package/dist/db.d.ts +8 -0
  15. package/dist/db.js +32 -1
  16. package/dist/files/dsmr.d.ts +1 -0
  17. package/dist/files/dsmr.js +5 -0
  18. package/dist/files/enedis-r6x.d.ts +1 -32
  19. package/dist/files/enedis-r6x.js +5 -86
  20. package/dist/files/energy-bill.d.ts +4 -3
  21. package/dist/files/energy-bill.js +11 -6
  22. package/dist/files/evcc.d.ts +102 -0
  23. package/dist/files/evcc.js +76 -0
  24. package/dist/files/geojson.d.ts +41 -2
  25. package/dist/files/geojson.js +61 -1
  26. package/dist/files/index.d.ts +6 -0
  27. package/dist/files/index.js +6 -0
  28. package/dist/files/project-sheet.d.ts +44 -0
  29. package/dist/files/project-sheet.js +102 -0
  30. package/dist/files/project.d.ts +108 -0
  31. package/dist/files/project.js +104 -0
  32. package/dist/files/pvsol.d.ts +64 -0
  33. package/dist/files/pvsol.js +99 -0
  34. package/dist/files/weather-files.d.ts +3 -2
  35. package/dist/files/weather-files.js +11 -7
  36. package/dist/files/wesmart-db.d.ts +229 -0
  37. package/dist/files/wesmart-db.js +412 -0
  38. package/dist/gestures.d.ts +135 -0
  39. package/dist/gestures.js +99 -1
  40. package/dist/index.d.ts +4 -1
  41. package/dist/index.js +12 -0
  42. package/dist/refusal.d.ts +2 -11
  43. package/dist/refusal.js +5 -29
  44. package/dist/series.d.ts +11 -6
  45. package/dist/series.js +6 -1
  46. package/dist/time.d.ts +1 -6
  47. package/dist/time.js +4 -25
  48. package/package.json +13 -6
  49. package/schema/geojson-export.1.json +605 -0
@@ -16,8 +16,13 @@
16
16
  * `open: true` is the export meant for the public: no street line, no
17
17
  * serial number, no metadata of a described object, and nothing that came from a source whose
18
18
  * licence forbids passing it on.
19
+ *
20
+ * `importGeoJsonParticipants()` reads the other way: the participants of a
21
+ * FeatureCollection — this export's, or any file whose features carry the
22
+ * same properties — join a project at their place.
19
23
  */
20
24
  import { writeGeoJson } from '@nexgen-os/geojson';
25
+ import { atomically } from '../db.js';
21
26
  /** Decimal places of the coordinates: 1 cm of longitude or latitude. */
22
27
  const PRECISION = 7;
23
28
  const ADDRESS_LINES = ['address_line1', 'address_line2'];
@@ -186,7 +191,7 @@ export async function exportGeoJson(db, target, options = {}) {
186
191
  kind,
187
192
  name,
188
193
  ...columns,
189
- ...(kind === 'participant' ? { location_source_code: source_code } : kind === 'site' || kind === 'building' || kind === 'surface' ? { source_code } : {}),
194
+ ...(kind === 'participant' ? { location_source_code: source_code } : kind === 'project' ? {} : { source_code }),
190
195
  attributes,
191
196
  identifiers: identifiers.map(({ scheme, value }) => ({ scheme, value })),
192
197
  calculations: calculations.get(id) ?? [],
@@ -217,3 +222,58 @@ export async function exportGeoJson(db, target, options = {}) {
217
222
  },
218
223
  });
219
224
  }
225
+ const PLACE_PROPERTIES = ['address_line1', 'address_line2', 'postal_code', 'city', 'region', 'municipality', 'country', 'location_precision', 'location_source_code'];
226
+ /**
227
+ * The participants of a FeatureCollection read by `@nexgen-os/geojson`
228
+ * join a project, each at its place: the feature's geometry, and its
229
+ * properties named as the export writes them — `name`, `category`,
230
+ * `country`, the address, `region`, `municipality`, `time_zone`,
231
+ * `location_precision`, `location_source_code`, `identifiers`. A feature
232
+ * without `kind`, or of kind `participant`, is one; the others are left
233
+ * out and listed. The file is attached to the project with its checksum
234
+ * and imported once (`already_imported`, decision 0036), whole or not at
235
+ * all. Refuses `checksum_required`, and by the index of the feature
236
+ * `name_required` and `country_required`: a country is never assumed.
237
+ */
238
+ export async function importGeoJsonParticipants(db, projectId, features, file) {
239
+ if (!/^sha256:[0-9a-f]{64}$/.test(file.checksum))
240
+ throw new Error('checksum_required: a file is imported with its checksum, sha256:<hex>');
241
+ const participants = [];
242
+ const skipped = [];
243
+ features.forEach((feature, index) => {
244
+ const kind = feature.properties?.kind;
245
+ if (kind === undefined || kind === null || kind === 'participant')
246
+ participants.push({ index, feature });
247
+ else
248
+ skipped.push({ index, kind: String(kind) });
249
+ });
250
+ for (const { index, feature } of participants) {
251
+ const p = (feature.properties ?? {});
252
+ if (typeof p.name !== 'string' || p.name.trim() === '')
253
+ throw new Error(`name_required: feature ${index} has no name`);
254
+ if (typeof p.country !== 'string' || p.country === '')
255
+ throw new Error(`country_required: feature ${index} (${p.name}) names no country`);
256
+ }
257
+ return atomically(db, async () => {
258
+ const existing = (await db.query(`select id from documents where object_kind = 'project' and object_id = $1 and checksum = $2`, [projectId, file.checksum])).rows[0];
259
+ if (existing)
260
+ throw new Error(`already_imported: the file is document ${existing.id} of the project`);
261
+ const documentId = (await db.query(`select attach_document('project', $1, $2, 'document', $3, 'application/geo+json', null, $4, null, $5, $6) id`, [projectId, file.name, file.uri, `GeoJSON file ${file.name}`, file.byteSize ?? null, file.checksum])).rows[0].id;
262
+ const joined = [];
263
+ for (const { index, feature } of participants) {
264
+ const p = (feature.properties ?? {});
265
+ const place = {};
266
+ for (const key of PLACE_PROPERTIES)
267
+ if (p[key] !== undefined && p[key] !== null)
268
+ place[key] = p[key];
269
+ if (feature.geometry)
270
+ place.geometry = feature.geometry;
271
+ if (Array.isArray(p.identifiers) && p.identifiers.length > 0) {
272
+ place.identifiers = p.identifiers.map((i) => ({ scheme: i.scheme, value: i.value }));
273
+ }
274
+ const { id } = (await db.query(`select join_project($1, $2, $3::jsonb, coalesce($4, 'consumer'), p_time_zone => $5) id`, [projectId, p.name, JSON.stringify(place), p.category ?? null, p.time_zone ?? null])).rows[0];
275
+ joined.push({ index, id, name: p.name });
276
+ }
277
+ return { documentId, participants: joined, skipped };
278
+ });
279
+ }
@@ -10,3 +10,9 @@ export * from './weather-files.js';
10
10
  export * from './parquet.js';
11
11
  export * from './energy-bill.js';
12
12
  export * from './enedis-r6x.js';
13
+ export * from './dsmr.js';
14
+ export * from './project.js';
15
+ export * from './project-sheet.js';
16
+ export * from './evcc.js';
17
+ export * from './pvsol.js';
18
+ export * from './wesmart-db.js';
@@ -10,3 +10,9 @@ export * from './weather-files.js';
10
10
  export * from './parquet.js';
11
11
  export * from './energy-bill.js';
12
12
  export * from './enedis-r6x.js';
13
+ export * from './dsmr.js';
14
+ export * from './project.js';
15
+ export * from './project-sheet.js';
16
+ export * from './evcc.js';
17
+ export * from './pvsol.js';
18
+ export * from './wesmart-db.js';
@@ -0,0 +1,44 @@
1
+ /**
2
+ * A project sheet into the model: `@nexgen-os/project-sheet` reads the table
3
+ * a spreadsheet saves, as CSV or as its .xlsx workbook — a project, its participants with their place, the
4
+ * meters they carry, the devices behind them — and this file gives each
5
+ * project of it to `importProject()`, the one way a project described as
6
+ * data becomes rows. So a sheet written again finds what is there and adds
7
+ * only what is new, as any description does.
8
+ *
9
+ * A sheet the reader could not read whole is refused before anything is
10
+ * written, `sheet_unreadable`, with the line and the name of each problem:
11
+ * an importer never guesses what a cell meant. A column the sheet does not
12
+ * know is left aside and given back as a warning.
13
+ */
14
+ import { type ProjectSheet, type SheetProblem, type SheetProject } from '@nexgen-os/project-sheet';
15
+ import type { Db } from '../db.js';
16
+ import { type ProjectDescription, type ProjectImport, type ProjectImportOptions } from './project.js';
17
+ /** How a sheet is imported: as a project is, and, for a workbook, which of its worksheets. */
18
+ export interface ProjectSheetImportOptions extends ProjectImportOptions {
19
+ /** The worksheet of an .xlsx workbook that holds the sheet, by its name; the first one otherwise. */
20
+ worksheet?: string;
21
+ }
22
+ export interface ProjectSheetImport {
23
+ dry_run: boolean;
24
+ /** What the reader left aside: the columns it does not know. */
25
+ warnings: SheetProblem[];
26
+ /** One import per project of the sheet, in the order of the sheet. */
27
+ projects: ProjectImport[];
28
+ }
29
+ /**
30
+ * A project of a sheet as the description `importProject()` takes. A place
31
+ * carries its point when the sheet gives one (longitude, latitude, at
32
+ * height 0, as `placeFields()` writes it).
33
+ */
34
+ export declare function projectOfSheet(project: SheetProject): ProjectDescription;
35
+ /**
36
+ * Writes the projects of a sheet — its text (CSV), the bytes of an .xlsx
37
+ * workbook, or the sheet already read — into an organisation, or finds them there: see the head of this file.
38
+ * Refuses `sheet_unreadable` with every problem the reader named,
39
+ * `sheet_empty` for a sheet that describes no project, `workbook_unreadable`
40
+ * for bytes that are not an .xlsx workbook, `sheet_not_found` for a
41
+ * worksheet the workbook does not have, and `worksheet_without_workbook`
42
+ * for a worksheet named beside a sheet that is no workbook.
43
+ */
44
+ export declare function importProjectSheet(db: Db, organisationId: string, sheet: string | Uint8Array | ProjectSheet, options?: ProjectSheetImportOptions): Promise<ProjectSheetImport>;
@@ -0,0 +1,102 @@
1
+ /**
2
+ * A project sheet into the model: `@nexgen-os/project-sheet` reads the table
3
+ * a spreadsheet saves, as CSV or as its .xlsx workbook — a project, its participants with their place, the
4
+ * meters they carry, the devices behind them — and this file gives each
5
+ * project of it to `importProject()`, the one way a project described as
6
+ * data becomes rows. So a sheet written again finds what is there and adds
7
+ * only what is new, as any description does.
8
+ *
9
+ * A sheet the reader could not read whole is refused before anything is
10
+ * written, `sheet_unreadable`, with the line and the name of each problem:
11
+ * an importer never guesses what a cell meant. A column the sheet does not
12
+ * know is left aside and given back as a warning.
13
+ */
14
+ import { readProjectSheet, readProjectWorkbook } from '@nexgen-os/project-sheet';
15
+ import { GestureError } from '../refusal.js';
16
+ import { importProject } from './project.js';
17
+ const ids = (list) => list.length === 0 ? undefined : list.map((i) => ({ scheme: i.scheme, value: i.value }));
18
+ /** The fields of an object that the sheet gives, and none it leaves empty. */
19
+ function given(fields) {
20
+ return Object.fromEntries(Object.entries(fields).filter(([, v]) => v !== undefined));
21
+ }
22
+ /**
23
+ * A project of a sheet as the description `importProject()` takes. A place
24
+ * carries its point when the sheet gives one (longitude, latitude, at
25
+ * height 0, as `placeFields()` writes it).
26
+ */
27
+ export function projectOfSheet(project) {
28
+ return {
29
+ name: project.name,
30
+ country: project.country ?? '',
31
+ ...given({ kind: project.kind, start_date: project.start_date, identifiers: ids(project.identifiers) }),
32
+ participants: project.participants.map((p) => ({
33
+ name: p.name,
34
+ ...given({
35
+ category: p.category,
36
+ time_zone: p.time_zone,
37
+ identifiers: ids(p.identifiers),
38
+ place: p.place === undefined ? undefined : given({
39
+ address_line1: p.place.address_line1,
40
+ address_line2: p.place.address_line2,
41
+ postal_code: p.place.postal_code,
42
+ city: p.place.city,
43
+ region: p.place.region,
44
+ country: p.place.country,
45
+ geometry: p.place.latitude === undefined || p.place.longitude === undefined ? undefined
46
+ : { type: 'Point', coordinates: [p.place.longitude, p.place.latitude, 0] },
47
+ location_precision: p.place.location_precision,
48
+ }),
49
+ }),
50
+ meters: p.meters.map((m) => ({
51
+ identifier: m.identifier, scheme: m.scheme,
52
+ ...given({ name: m.name, resource: m.resource, direction: m.direction, valid_from: m.valid_from }),
53
+ })),
54
+ devices: p.devices.map((d) => ({
55
+ device_type: d.device_type, name: d.name,
56
+ ...given({ rated_power_kw: d.rated_power_kw, unit_count: d.unit_count, installed_on: d.installed_on, identifiers: ids(d.identifiers) }),
57
+ })),
58
+ })),
59
+ };
60
+ }
61
+ /** One problem as a person reads it: `line 4 invalid_number device_rated_power_kw "12,5"`. */
62
+ function said(p) {
63
+ return [`line ${p.line}`, p.code, p.column, p.value === undefined ? undefined : JSON.stringify(p.value)].filter(Boolean).join(' ');
64
+ }
65
+ /**
66
+ * Writes the projects of a sheet — its text (CSV), the bytes of an .xlsx
67
+ * workbook, or the sheet already read — into an organisation, or finds them there: see the head of this file.
68
+ * Refuses `sheet_unreadable` with every problem the reader named,
69
+ * `sheet_empty` for a sheet that describes no project, `workbook_unreadable`
70
+ * for bytes that are not an .xlsx workbook, `sheet_not_found` for a
71
+ * worksheet the workbook does not have, and `worksheet_without_workbook`
72
+ * for a worksheet named beside a sheet that is no workbook.
73
+ */
74
+ export async function importProjectSheet(db, organisationId, sheet, options = {}) {
75
+ const { worksheet, ...importOptions } = options;
76
+ if (worksheet !== undefined && !(sheet instanceof Uint8Array)) {
77
+ throw new GestureError(`worksheet_without_workbook: ${worksheet} names a worksheet, and only an .xlsx workbook has worksheets`);
78
+ }
79
+ const read = typeof sheet === 'string' ? readProjectSheet(sheet)
80
+ : sheet instanceof Uint8Array ? workbook(sheet, worksheet) : sheet;
81
+ const errors = read.problems.filter((p) => p.level === 'error');
82
+ if (errors.length > 0)
83
+ throw new GestureError(`sheet_unreadable: ${errors.map(said).join('; ')}`);
84
+ if (read.projects.length === 0)
85
+ throw new GestureError('sheet_empty: the sheet describes no project');
86
+ const projects = [];
87
+ for (const project of read.projects)
88
+ projects.push(await importProject(db, organisationId, projectOfSheet(project), importOptions));
89
+ return { dry_run: importOptions.dryRun ?? false, warnings: read.problems.filter((p) => p.level === 'warning'), projects };
90
+ }
91
+ /** A workbook read, what its reader refuses given back as a refusal of the gesture, by the reader's name. */
92
+ function workbook(bytes, worksheet) {
93
+ try {
94
+ return readProjectWorkbook(bytes, worksheet === undefined ? {} : { sheet: worksheet });
95
+ }
96
+ catch (e) {
97
+ const message = e instanceof Error ? e.message : String(e);
98
+ if (/^(workbook_unreadable|sheet_not_found):/.test(message))
99
+ throw new GestureError(message);
100
+ throw new GestureError(`workbook_unreadable: ${message}`);
101
+ }
102
+ }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * A project described as data — its participants, the meters they carry and
3
+ * the devices behind them — written into the model through the gestures of
4
+ * the core, and written again without a duplicate.
5
+ *
6
+ * What another system holds about a project (a database of an older
7
+ * platform, a spreadsheet, a description tool) is read by its own reader into
8
+ * this one plain shape; `importProject()` is the one way it becomes rows.
9
+ * Nothing is inserted directly: a project is created by `create_project()`,
10
+ * a participant joins by `join_project()`, a meter is declared by
11
+ * `declare_meter()`, a device installed by `install_device()`, an identifier
12
+ * added by `add_identifier()`, so row level security and every refusal of the
13
+ * schema apply as they do to a person typing the same gestures.
14
+ *
15
+ * An import is replayed as often as the other system changes. Each object is
16
+ * looked for before it is written: by an identifier it carries, which names
17
+ * one object of the organisation, then by what names it in its parent — a
18
+ * project by its name in the organisation, a participant by its name in the
19
+ * project, a meter by its scheme and identifier in the project, a device by
20
+ * its name at its participant. What is found is reused and given the
21
+ * identifiers it lacks; what is not is created. A dry run looks for
22
+ * everything and writes nothing.
23
+ *
24
+ * The surfaces run a gesture in one transaction acting as the person
25
+ * (`personSession()`): there an import is written whole or not at all. A
26
+ * caller with a connection of its own holds the transaction itself; an
27
+ * import cut half way is completed by running it again.
28
+ */
29
+ import type { Db } from '../db.js';
30
+ /** An identifier the object is known by elsewhere, in a scheme of `identifier_schemes`. */
31
+ export interface IdentifierDescription {
32
+ scheme: string;
33
+ value: string;
34
+ }
35
+ export interface DeviceDescription {
36
+ /** A code of `device_types`. */
37
+ device_type: string;
38
+ name: string;
39
+ rated_power_kw?: number;
40
+ unit_count?: number;
41
+ installed_on?: string;
42
+ /** Where the description comes from, a code of `sources`. */
43
+ source_code?: string;
44
+ identifiers?: IdentifierDescription[];
45
+ }
46
+ export interface MeterDescription {
47
+ /** The metering point identifier, in its numbering scheme. */
48
+ identifier: string;
49
+ scheme: string;
50
+ resource?: string;
51
+ direction?: string;
52
+ valid_from?: string;
53
+ name?: string;
54
+ identifiers?: IdentifierDescription[];
55
+ }
56
+ export interface ParticipantDescription {
57
+ name: string;
58
+ /** producer, consumer or prosumer; consumer when not given. */
59
+ category?: string;
60
+ time_zone?: string;
61
+ /** Its place in the standard shape (`placeFields()`). */
62
+ place?: Record<string, unknown>;
63
+ identifiers?: IdentifierDescription[];
64
+ meters?: MeterDescription[];
65
+ devices?: DeviceDescription[];
66
+ }
67
+ export interface ProjectDescription {
68
+ name: string;
69
+ /** The ISO 3166-1 alpha-2 country whose rules apply: never assumed. */
70
+ country: string;
71
+ kind?: string;
72
+ start_date?: string;
73
+ identifiers?: IdentifierDescription[];
74
+ participants?: ParticipantDescription[];
75
+ }
76
+ export type ImportedKind = 'project' | 'participant' | 'meter' | 'device';
77
+ /** What became of one object of the description. */
78
+ export interface ImportedObject {
79
+ kind: ImportedKind;
80
+ /** Where it is in the description: `participants[2].meters[0]`. */
81
+ path: string;
82
+ name: string;
83
+ /** Found: it was there already. Created: written now. To create: a dry run would write it. */
84
+ outcome: 'found' | 'created' | 'to_create';
85
+ /** Its id; null for an object a dry run would create. */
86
+ id: string | null;
87
+ /** The identifiers added to it (or that a dry run would add). */
88
+ identifiers_added: IdentifierDescription[];
89
+ }
90
+ export interface ProjectImport {
91
+ dry_run: boolean;
92
+ project_id: string | null;
93
+ objects: ImportedObject[];
94
+ /** Per kind, how many were found and how many created (or would be). */
95
+ counts: Record<ImportedKind, {
96
+ found: number;
97
+ created: number;
98
+ }>;
99
+ }
100
+ export interface ProjectImportOptions {
101
+ /** Look for everything, write nothing. Default: false. */
102
+ dryRun?: boolean;
103
+ }
104
+ /**
105
+ * Writes a project described as data into an organisation, or finds it
106
+ * there: see the head of this file. Returns what became of each object.
107
+ */
108
+ export declare function importProject(db: Db, organisationId: string, description: ProjectDescription, options?: ProjectImportOptions): Promise<ProjectImport>;
@@ -0,0 +1,104 @@
1
+ import { GestureError } from '../refusal.js';
2
+ const KINDS = ['project', 'participant', 'meter', 'device'];
3
+ async function rows(db, sql, params) {
4
+ return (await db.query(sql, params)).rows;
5
+ }
6
+ async function idOf(db, sql, params) {
7
+ const [row] = await rows(db, sql, params);
8
+ return row?.id ?? null;
9
+ }
10
+ /**
11
+ * The object of this kind one of the identifiers names in the organisation,
12
+ * or null. Two identifiers naming two different objects refuse the import:
13
+ * the description says two things of one object.
14
+ */
15
+ async function byIdentifiers(db, organisationId, kind, ids, path) {
16
+ if (ids.length === 0)
17
+ return null;
18
+ const found = await rows(db, `select distinct object_kind, object_id::text from identifiers
19
+ where organisation_id = $1 and (scheme, value) in (select * from unnest($2::text[], $3::text[]))`, [organisationId, ids.map((i) => i.scheme), ids.map((i) => i.value)]);
20
+ if (found.length === 0)
21
+ return null;
22
+ if (found.length > 1 || found[0].object_kind !== kind) {
23
+ throw new GestureError(`identifiers_disagree: the identifiers of ${path} name ${found.map((f) => `${f.object_kind} ${f.object_id}`).join(' and ')}`);
24
+ }
25
+ return found[0].object_id;
26
+ }
27
+ /** The identifiers of the description the object does not carry yet. */
28
+ async function missingIdentifiers(db, kind, id, ids) {
29
+ if (id === null || ids.length === 0)
30
+ return ids;
31
+ const held = await rows(db, 'select scheme, value from identifiers where object_kind = $1 and object_id = $2', [kind, id]);
32
+ return ids.filter((i) => !held.some((h) => h.scheme === i.scheme && h.value === i.value));
33
+ }
34
+ /** Refuses a description that cannot be written, before anything is: by the path of what is missing. */
35
+ function check(d) {
36
+ const need = (value, code, path) => {
37
+ if (typeof value !== 'string' || value.trim() === '')
38
+ throw new GestureError(`${code}: ${path} has none`);
39
+ };
40
+ need(d.name, 'name_required', 'project');
41
+ need(d.country, 'country_required', 'project');
42
+ (d.participants ?? []).forEach((p, i) => {
43
+ need(p.name, 'name_required', `participants[${i}]`);
44
+ (p.meters ?? []).forEach((m, j) => {
45
+ need(m.identifier, 'identifier_required', `participants[${i}].meters[${j}]`);
46
+ need(m.scheme, 'scheme_required', `participants[${i}].meters[${j}]`);
47
+ });
48
+ (p.devices ?? []).forEach((v, j) => {
49
+ need(v.name, 'name_required', `participants[${i}].devices[${j}]`);
50
+ need(v.device_type, 'device_type_required', `participants[${i}].devices[${j}]`);
51
+ });
52
+ });
53
+ }
54
+ /**
55
+ * Writes a project described as data into an organisation, or finds it
56
+ * there: see the head of this file. Returns what became of each object.
57
+ */
58
+ export async function importProject(db, organisationId, description, options = {}) {
59
+ check(description);
60
+ const dryRun = options.dryRun ?? false;
61
+ const objects = [];
62
+ /** Finds an object, or creates it; then gives it the identifiers it lacks. */
63
+ async function settle(kind, path, name, ids, find, create) {
64
+ const identifiers = ids ?? [];
65
+ let id = await byIdentifiers(db, organisationId, kind, identifiers, path) ?? await find();
66
+ const outcome = id !== null ? 'found' : dryRun ? 'to_create' : 'created';
67
+ const added = await missingIdentifiers(db, kind, id, identifiers);
68
+ if (!dryRun) {
69
+ id ??= await create();
70
+ for (const i of added)
71
+ await db.query('select add_identifier($1, $2, $3, $4)', [kind, id, i.scheme, i.value]);
72
+ }
73
+ objects.push({ kind, path, name, outcome, id, identifiers_added: added });
74
+ return id;
75
+ }
76
+ const p = description;
77
+ const projectId = await settle('project', 'project', p.name, p.identifiers, () => idOf(db, 'select id from projects where organisation_id = $1 and name = $2 order by created_at limit 1', [organisationId, p.name]), () => idOf(db, 'select create_project($1, $2, $3, $4, $5) id', [organisationId, p.name, p.country, p.kind ?? null, p.start_date ?? null]));
78
+ for (const [i, participant] of (p.participants ?? []).entries()) {
79
+ const at = `participants[${i}]`;
80
+ const participantId = await settle('participant', at, participant.name, participant.identifiers, async () => projectId === null ? null
81
+ : idOf(db, 'select id from participants where project_id = $1 and name = $2 order by created_at limit 1', [projectId, participant.name]), () => idOf(db, `select join_project($1, $2, $3::jsonb, coalesce($4, 'consumer'), p_time_zone => $5) id`, [projectId, participant.name, participant.place === undefined ? null : JSON.stringify(participant.place),
82
+ participant.category ?? null, participant.time_zone ?? null]));
83
+ for (const [j, m] of (participant.meters ?? []).entries()) {
84
+ await settle('meter', `${at}.meters[${j}]`, m.name ?? m.identifier, m.identifiers, async () => {
85
+ if (projectId === null)
86
+ return null;
87
+ const [open] = await rows(db, 'select id, participant_id from meters where project_id = $1 and scheme = $2 and identifier = $3 and valid_to is null', [projectId, m.scheme, m.identifier]);
88
+ if (open !== undefined && open.participant_id !== participantId) {
89
+ throw new GestureError(`meter_carried_elsewhere: ${m.scheme} ${m.identifier} of ${at} is carried by participant ${open.participant_id} of the project`);
90
+ }
91
+ return open?.id ?? null;
92
+ }, () => idOf(db, `select declare_meter($1, $2, $3, coalesce($4, 'electricity'), coalesce($5, 'both'), $6, $7) id`, [participantId, m.identifier, m.scheme, m.resource ?? null, m.direction ?? null, m.valid_from ?? null, m.name ?? null]));
93
+ }
94
+ for (const [j, d] of (participant.devices ?? []).entries()) {
95
+ await settle('device', `${at}.devices[${j}]`, d.name, d.identifiers, async () => participantId === null ? null
96
+ : idOf(db, 'select id from devices where participant_id = $1 and name = $2 order by created_at limit 1', [participantId, d.name]), () => idOf(db, 'select install_device($1, $2, $3, null, $4, $5, $6, coalesce($7, 1)) id', [participantId, d.device_type, d.name, d.rated_power_kw ?? null, d.installed_on ?? null, d.source_code ?? null, d.unit_count ?? null]));
97
+ }
98
+ }
99
+ const counts = Object.fromEntries(KINDS.map((k) => [k, {
100
+ found: objects.filter((o) => o.kind === k && o.outcome === 'found').length,
101
+ created: objects.filter((o) => o.kind === k && o.outcome !== 'found').length,
102
+ }]));
103
+ return { dry_run: dryRun, project_id: projectId, objects, counts };
104
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A PV*SOL study into the model: `@nexgen-os/pvsol` reads the .pvprj file,
3
+ * and this file gives what it describes to the gestures of the core — the
4
+ * project, its participant and the inverters through `importProject()`, the
5
+ * PV system and its arrays, each with its own orientation, through
6
+ * `describePvSystem()` of the `solar` module. So a study imported again finds
7
+ * what is there and adds only what is new: the PV system is found by its
8
+ * name at its participant.
9
+ *
10
+ * What a study describes is a design: nothing is dated as installed, and the
11
+ * country is the caller's, never assumed. The load profile and the results
12
+ * PV*SOL simulated stay in the study read (`study`) for the module that
13
+ * compares or keeps them; nothing of them is written here.
14
+ *
15
+ * A study whose arrays lack a power or an orientation is refused before
16
+ * anything is written, `pvsol_incomplete`: an importer never guesses a
17
+ * figure. What the reader named stays as warnings.
18
+ */
19
+ import { type PvsolProblem, type PvsolStudy } from '@nexgen-os/pvsol';
20
+ import type { Db } from '../db.js';
21
+ import { type ProjectDescription, type ProjectImport, type ProjectImportOptions } from './project.js';
22
+ export interface PvsolImportOptions extends ProjectImportOptions {
23
+ /** The ISO 3166-1 alpha-2 country whose rules apply: a study does not say it. */
24
+ country: string;
25
+ /** The project's name; the study's title when not given. */
26
+ project?: string;
27
+ /** The participant's name; the study's customer company, then its title, when not given. */
28
+ participant?: string;
29
+ /** The participant's IANA time zone, when the caller knows it. */
30
+ time_zone?: string;
31
+ }
32
+ export interface PvsolImport {
33
+ dry_run: boolean;
34
+ /** What became of the project, its participant and the inverters. */
35
+ project: ProjectImport;
36
+ /** The PV system: found by its name at the participant, created, or to create on a dry run. */
37
+ pv_system: {
38
+ name: string;
39
+ outcome: 'found' | 'created' | 'to_create';
40
+ device_id: string | null;
41
+ arrays: string[];
42
+ };
43
+ /** What the reader named in the study. */
44
+ warnings: PvsolProblem[];
45
+ /** The study as read, its load profile and results included. */
46
+ study: PvsolStudy;
47
+ }
48
+ /**
49
+ * A study as the description `importProject()` takes: the project in the
50
+ * caller's country, one participant — a prosumer when the study carries a
51
+ * consumption, a producer otherwise — at the address of the system as the
52
+ * study writes it, in one line for a geocoder to place, and its inverters by
53
+ * manufacturer and model, with their count.
54
+ */
55
+ export declare function projectOfPvsolStudy(study: PvsolStudy, options: PvsolImportOptions): ProjectDescription;
56
+ /**
57
+ * Writes a PV*SOL study — the bytes of its .pvprj file or the study already
58
+ * read — into an organisation, or finds it there: see the head of this file.
59
+ * Refuses `pvsol_unreadable` (not a PV*SOL study), `pvsol_incomplete` (an
60
+ * array without a power or an orientation, or no array at all),
61
+ * `module_not_installed` (the `solar` module holds the arrays), and what
62
+ * `importProject()` and `describePvSystem()` refuse.
63
+ */
64
+ export declare function importPvsolStudy(db: Db, organisationId: string, file: Uint8Array | PvsolStudy, options: PvsolImportOptions): Promise<PvsolImport>;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * A PV*SOL study into the model: `@nexgen-os/pvsol` reads the .pvprj file,
3
+ * and this file gives what it describes to the gestures of the core — the
4
+ * project, its participant and the inverters through `importProject()`, the
5
+ * PV system and its arrays, each with its own orientation, through
6
+ * `describePvSystem()` of the `solar` module. So a study imported again finds
7
+ * what is there and adds only what is new: the PV system is found by its
8
+ * name at its participant.
9
+ *
10
+ * What a study describes is a design: nothing is dated as installed, and the
11
+ * country is the caller's, never assumed. The load profile and the results
12
+ * PV*SOL simulated stay in the study read (`study`) for the module that
13
+ * compares or keeps them; nothing of them is written here.
14
+ *
15
+ * A study whose arrays lack a power or an orientation is refused before
16
+ * anything is written, `pvsol_incomplete`: an importer never guesses a
17
+ * figure. What the reader named stays as warnings.
18
+ */
19
+ import { readPvsolStudy } from '@nexgen-os/pvsol';
20
+ import { describePvSystem, requireModule } from '../gestures.js';
21
+ import { GestureError } from '../refusal.js';
22
+ import { importProject } from './project.js';
23
+ /** The name a study gives its PV system, its project and its participant, unless the caller names them. */
24
+ function names(study, options) {
25
+ const title = study.project.title ?? 'PV*SOL study';
26
+ return { project: options.project ?? title, participant: options.participant ?? study.project.customer_company ?? title, system: title };
27
+ }
28
+ /**
29
+ * A study as the description `importProject()` takes: the project in the
30
+ * caller's country, one participant — a prosumer when the study carries a
31
+ * consumption, a producer otherwise — at the address of the system as the
32
+ * study writes it, in one line for a geocoder to place, and its inverters by
33
+ * manufacturer and model, with their count.
34
+ */
35
+ export function projectOfPvsolStudy(study, options) {
36
+ const named = names(study, options);
37
+ const consumes = study.load_profile !== null || (study.results?.consumption_kwh ?? 0) > 0;
38
+ return {
39
+ name: named.project,
40
+ country: options.country,
41
+ participants: [{
42
+ name: named.participant,
43
+ category: consumes ? 'prosumer' : 'producer',
44
+ place: { country: options.country, ...(study.project.site_address ? { address_line1: study.project.site_address } : {}) },
45
+ ...(options.time_zone ? { time_zone: options.time_zone } : {}),
46
+ devices: study.inverters.map((i) => ({
47
+ device_type: 'inverter',
48
+ name: [i.manufacturer, i.model].filter(Boolean).join(' ') || 'Inverter',
49
+ unit_count: i.count,
50
+ })),
51
+ }],
52
+ };
53
+ }
54
+ /**
55
+ * Writes a PV*SOL study — the bytes of its .pvprj file or the study already
56
+ * read — into an organisation, or finds it there: see the head of this file.
57
+ * Refuses `pvsol_unreadable` (not a PV*SOL study), `pvsol_incomplete` (an
58
+ * array without a power or an orientation, or no array at all),
59
+ * `module_not_installed` (the `solar` module holds the arrays), and what
60
+ * `importProject()` and `describePvSystem()` refuse.
61
+ */
62
+ export async function importPvsolStudy(db, organisationId, file, options) {
63
+ let study;
64
+ try {
65
+ study = file instanceof Uint8Array ? readPvsolStudy(file) : file;
66
+ }
67
+ catch (e) {
68
+ throw new GestureError(e.message);
69
+ }
70
+ if (study.arrays.length === 0)
71
+ throw new GestureError('pvsol_incomplete: the study holds no array with modules');
72
+ const arrays = study.arrays.map((a) => {
73
+ if (a.power_kwp === null || a.azimuth_deg === null || a.tilt_deg === null) {
74
+ const missing = [a.power_kwp === null && 'power', a.azimuth_deg === null && 'azimuth', a.tilt_deg === null && 'tilt'].filter(Boolean).join(', ');
75
+ throw new GestureError(`pvsol_incomplete: the array ${a.name} has no ${missing}`);
76
+ }
77
+ return { name: a.name, azimuth_deg: a.azimuth_deg, tilt_deg: a.tilt_deg, kwp: a.power_kwp };
78
+ });
79
+ await requireModule(db, 'solar');
80
+ const named = names(study, options);
81
+ const project = await importProject(db, organisationId, projectOfPvsolStudy(study, options), options);
82
+ const participantId = project.objects.find((o) => o.kind === 'participant')?.id ?? null;
83
+ const found = participantId === null ? undefined
84
+ : (await db.query(`select id from devices where participant_id = $1 and name = $2 and device_type = 'solar'`, [participantId, named.system])).rows[0];
85
+ let pvSystem;
86
+ if (found) {
87
+ const rows = (await db.query('select id from solar.pv_arrays where device_id = $1 order by name', [found.id])).rows;
88
+ pvSystem = { name: named.system, outcome: 'found', device_id: found.id, arrays: rows.map((r) => r.id) };
89
+ }
90
+ else if (options.dryRun || participantId === null) {
91
+ pvSystem = { name: named.system, outcome: 'to_create', device_id: null, arrays: [] };
92
+ }
93
+ else {
94
+ const kwp = Math.round(arrays.reduce((s, a) => s + a.kwp, 0) * 1e6) / 1e6;
95
+ const made = await describePvSystem(db, { participant_id: participantId, name: named.system, kwp, arrays });
96
+ pvSystem = { name: named.system, outcome: 'created', device_id: made.device_id, arrays: made.arrays };
97
+ }
98
+ return { dry_run: options.dryRun ?? false, project, pv_system: pvSystem, warnings: study.problems, study };
99
+ }
@@ -9,7 +9,7 @@
9
9
  * `writeEpw()` writes.
10
10
  */
11
11
  import { type WeatherFile, type WeatherFileLocation, type WeatherFileWarning, type WeatherYear } from '@nexgen-os/weather-files';
12
- import type { Db } from '../db.js';
12
+ import { type Db } from '../db.js';
13
13
  export interface WeatherTarget {
14
14
  organisationId: string;
15
15
  /** The object the weather is about, by its kind and its id: a weather point, a participant. */
@@ -22,7 +22,8 @@ export interface WeatherTarget {
22
22
  * station network, a licensed model). A typical year is `simulated` and
23
23
  * named after its years (`typical year 2005-2020`); real years are
24
24
  * `measured` and unnamed, unless told otherwise. Importing the same file
25
- * again replaces the values.
25
+ * again replaces the values. The file is stored whole or not at all: one
26
+ * series refused leaves none of the others.
26
27
  */
27
28
  export declare function importWeatherFile(db: Db, target: WeatherTarget, file: WeatherFile, options: {
28
29
  sourceCode: string;