@nexgen-os/core 0.4.2 → 0.5.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.
@@ -0,0 +1,76 @@
1
+ /**
2
+ * The device types evcc's templates are read as by default: a charging
3
+ * station; a heating template (heat pumps and heating rods) a heat pump; a
4
+ * switch socket a controller; a meter template serving `pv` an inverter
5
+ * (a hybrid inverter included), else `battery` a battery, else a meter.
6
+ * Vehicles are not devices of a place: no entry.
7
+ */
8
+ export const EVCC_DEVICE_TYPES = {
9
+ charger: { '': 'charger', heating: 'heat_pump', switchsockets: 'controller' },
10
+ meter: [['pv', 'inverter'], ['battery', 'battery'], ['grid', 'meter'], ['charge', 'meter'], ['aux', 'meter'], ['', 'meter']],
11
+ };
12
+ /** The device type of a template's products, or null when the table gives none. */
13
+ export function deviceTypeOfEvcc(template, table = EVCC_DEVICE_TYPES) {
14
+ const rule = table[template.class];
15
+ if (!rule)
16
+ return null;
17
+ if (Array.isArray(rule)) {
18
+ const usages = template.usages.length > 0 ? template.usages : [''];
19
+ return rule.find(([usage]) => usages.includes(usage))?.[1] ?? null;
20
+ }
21
+ return rule[template.group ?? ''] ?? null;
22
+ }
23
+ /**
24
+ * The catalogue entries the templates give: one per manufacturer and
25
+ * model, the device type of the first template naming it, every template
26
+ * naming it as its connectors. Left out: the products of a sponsored
27
+ * template, a brand named without a model, a template the table gives no
28
+ * device type.
29
+ */
30
+ export function catalogueOfEvcc(templates, options = {}) {
31
+ const entries = new Map();
32
+ const leftOut = [];
33
+ for (const t of templates) {
34
+ const deviceType = deviceTypeOfEvcc(t, options.deviceTypes);
35
+ for (const p of t.products) {
36
+ const reason = t.sponsored ? 'sponsored' : p.model === null ? 'model_missing' : deviceType === null ? 'device_type_unknown' : null;
37
+ if (reason) {
38
+ leftOut.push({ template: t.template, brand: p.brand, model: p.model, reason });
39
+ continue;
40
+ }
41
+ const key = `${p.brand}\u0000${p.model}`;
42
+ const entry = entries.get(key) ?? { manufacturer: p.brand, model: p.model, deviceType: deviceType, connectors: [] };
43
+ entries.set(key, entry);
44
+ if (!entry.connectors.some((c) => c.class === t.class && c.template === t.template)) {
45
+ entry.connectors.push({ class: t.class, template: t.template, group: t.group, capabilities: t.capabilities, usages: t.usages, discovery: t.discovery });
46
+ }
47
+ }
48
+ }
49
+ return { entries: [...entries.values()], leftOut };
50
+ }
51
+ /**
52
+ * Writes the catalogue entries of the templates: an organisation's own
53
+ * (`organisationId`), or shared by every organisation (null, for whoever
54
+ * installs). An entry the catalogue already holds by manufacturer and
55
+ * model keeps its values and gains `metadata.evcc`, replaced as a whole at
56
+ * each import, so importing the same templates again changes nothing. A
57
+ * new entry is published by `evcc`. Every entry says the commit it was
58
+ * read at and evcc's licence.
59
+ */
60
+ export async function importEvccCatalogue(db, templates, options) {
61
+ if (!options.revision?.commit)
62
+ throw new Error('revision_required: the commit of evcc the templates were read at');
63
+ const { entries, leftOut } = catalogueOfEvcc(templates, { deviceTypes: options.deviceTypes });
64
+ let created = 0;
65
+ for (const e of entries) {
66
+ const evcc = { connectors: e.connectors, repository: options.revision.repository, commit: options.revision.commit, licence: 'MIT' };
67
+ const row = (await db.query(`insert into products (organisation_id, device_type, manufacturer, model, metadata, published_by)
68
+ values ($1, $2, $3, $4, jsonb_build_object('evcc', $5::jsonb), 'evcc')
69
+ on conflict (organisation_id, manufacturer, model)
70
+ do update set metadata = products.metadata || jsonb_build_object('evcc', $5::jsonb)
71
+ returning (xmax = 0) as created`, [options.organisationId, e.deviceType, e.manufacturer, e.model, JSON.stringify(evcc)])).rows[0];
72
+ if (row.created)
73
+ created += 1;
74
+ }
75
+ return { created, updated: entries.length - created, leftOut };
76
+ }
@@ -16,9 +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
- import { type FeatureCollection } from '@nexgen-os/geojson';
21
- import type { Db } from '../db.js';
24
+ import { type Feature, type FeatureCollection } from '@nexgen-os/geojson';
25
+ import { type Db } from '../db.js';
22
26
  /** A figure a module computed on the object, as the module's table keeps it. */
23
27
  export interface CalculationSummary {
24
28
  id: string;
@@ -77,3 +81,38 @@ export interface GeoJsonExportOptions {
77
81
  calculations?: boolean;
78
82
  }
79
83
  export declare function exportGeoJson(db: Db, target: GeoJsonTarget, options?: GeoJsonExportOptions): Promise<GeoJsonExport>;
84
+ /** The file a collection was read from: where it is kept and its checksum, `sha256:<hex>`. */
85
+ export interface GeoJsonFile {
86
+ name: string;
87
+ uri: string;
88
+ checksum: string;
89
+ byteSize?: number | null;
90
+ }
91
+ export interface GeoJsonImport {
92
+ /** The file, a document of the project. */
93
+ documentId: string;
94
+ /** The participants that joined, by the index of their feature. */
95
+ participants: {
96
+ index: number;
97
+ id: string;
98
+ name: string;
99
+ }[];
100
+ /** The features of another kind (`project`, `building`, `device`…), left out. */
101
+ skipped: {
102
+ index: number;
103
+ kind: string;
104
+ }[];
105
+ }
106
+ /**
107
+ * The participants of a FeatureCollection read by `@nexgen-os/geojson`
108
+ * join a project, each at its place: the feature's geometry, and its
109
+ * properties named as the export writes them — `name`, `category`,
110
+ * `country`, the address, `region`, `municipality`, `time_zone`,
111
+ * `location_precision`, `location_source_code`, `identifiers`. A feature
112
+ * without `kind`, or of kind `participant`, is one; the others are left
113
+ * out and listed. The file is attached to the project with its checksum
114
+ * and imported once (`already_imported`, decision 0036), whole or not at
115
+ * all. Refuses `checksum_required`, and by the index of the feature
116
+ * `name_required` and `country_required`: a country is never assumed.
117
+ */
118
+ export declare function importGeoJsonParticipants(db: Db, projectId: string, features: Feature[], file: GeoJsonFile): Promise<GeoJsonImport>;
@@ -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,8 @@ 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';
@@ -10,3 +10,8 @@ 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';
@@ -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>;