goblin-swiss 0.2.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/.editorconfig ADDED
@@ -0,0 +1,9 @@
1
+ root = true
2
+
3
+ [*.{js,jsx,json}]
4
+ indent_style = space
5
+ indent_size = 2
6
+ charset = utf-8
7
+ trim_trailing_whitespace = true
8
+ insert_final_newline = true
9
+ max_line_length = 80
package/.zou-flow ADDED
@@ -0,0 +1,2 @@
1
+ [update-version]
2
+ package-json = package.json
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 Xcraft, Epsitec SA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ **goblin-swiss** brings Swiss domain logic to the Goblin actor ecosystem — with a clear, local-first model of the entities and specifics that make Switzerland unique.
2
+
3
+ It provides a proud, pragmatic foundation for working with Swiss administrative concepts (like _Commune_ and _Canton_), identifiers, formats, and conventions — packaged as clean, reusable actors you can plug into your apps.
4
+
5
+ Built for Swiss software, by people who care about getting Switzerland right. 🇨🇭
package/canton.js ADDED
@@ -0,0 +1,4 @@
1
+ const {Elf} = require('xcraft-core-goblin');
2
+ const {Canton, CantonLogic} = require('goblin-swiss/lib/canton.js');
3
+
4
+ exports.xcraftCommands = Elf.birth(Canton, CantonLogic);
package/cantonAdmin.js ADDED
@@ -0,0 +1,7 @@
1
+ const {Elf} = require('xcraft-core-goblin');
2
+ const {
3
+ CantonAdmin,
4
+ CantonAdminLogic,
5
+ } = require('goblin-swiss/lib/cantonAdmin.js');
6
+
7
+ exports.xcraftCommands = Elf.birth(CantonAdmin, CantonAdminLogic);
package/commune.js ADDED
@@ -0,0 +1,4 @@
1
+ const {Elf} = require('xcraft-core-goblin');
2
+ const {Commune, CommuneLogic} = require('goblin-swiss/lib/commune.js');
3
+
4
+ exports.xcraftCommands = Elf.birth(Commune, CommuneLogic);
package/config.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = [];
package/doc/sources.md ADDED
@@ -0,0 +1,28 @@
1
+ # Sources de données
2
+
3
+ ## https://data.geo.admin.ch
4
+
5
+ Cette route permet de trouver les "assets" des couches liées au NPA :
6
+
7
+ https://data.geo.admin.ch/api/stac/v0.9/collections/ch.swisstopo-vd.ortschaftenverzeichnis_plz/items
8
+
9
+ On peux trouver cette entrée qui contient le csv zippé avec toutes les données utiles pour nos entités :
10
+
11
+ ```json
12
+ {
13
+ "assets": {
14
+ "ortschaftenverzeichnis_plz_4326.csv.zip": {
15
+ "type": "application/x.csv+zip",
16
+ "href": "https://data.geo.admin.ch/ch.swisstopo-vd.ortschaftenverzeichnis_plz/ortschaftenverzeichnis_plz/ortschaftenverzeichnis_plz_4326.csv.zip",
17
+ "created": "2023-05-17T05:30:59.121922Z",
18
+ "updated": "2026-03-01T03:14:24.717956Z",
19
+ "proj:epsg": 4326,
20
+ "checksum:multihash": "12209DE52BDA4BB2805EBBDDD6989536F96DA0572F7C504C39328E3572278210F43D"
21
+ }
22
+ }
23
+ }
24
+ ```
25
+
26
+ ## https://sms.bfs.admin.ch/
27
+
28
+ Cette source fournis les cantons, admin (district) et communes de Suisse sous forme d'un fichier CSV hiérarchisé.
package/lib/canton.js ADDED
@@ -0,0 +1,80 @@
1
+ // @ts-check
2
+ const {id} = require('xcraft-core-goblin/lib/types.js');
3
+ const {Elf} = require('xcraft-core-goblin');
4
+ const {string, option, array} = require('xcraft-core-stones');
5
+
6
+ class MetaShape {
7
+ index = string;
8
+ status = string;
9
+ locale = string;
10
+ scope = string;
11
+ }
12
+
13
+ class CantonShape {
14
+ id = id('canton');
15
+ name = string;
16
+ code = string;
17
+ cantonAdminIds = array(id('cantonAdminId'));
18
+ communeIds = array(id('commune'));
19
+ meta = MetaShape;
20
+ }
21
+
22
+ class CantonState extends Elf.Sculpt(CantonShape) {}
23
+
24
+ class CantonLogic extends Elf.Archetype {
25
+ static db = 'swiss';
26
+ static indices = [];
27
+
28
+ state = new CantonState();
29
+
30
+ create(id, porfolio) {
31
+ const {state} = this;
32
+ for (const [k, v] of Object.entries(porfolio)) {
33
+ state[k] = v;
34
+ }
35
+ state.id = id;
36
+ }
37
+
38
+ patch(patch) {
39
+ const {state} = this;
40
+ state._state.merge('', patch);
41
+ }
42
+
43
+ index(index) {
44
+ this.state.meta.index = index;
45
+ }
46
+ }
47
+
48
+ class Canton extends Elf {
49
+ logic = Elf.getLogic(CantonLogic);
50
+ state = new CantonState();
51
+
52
+ async create(id, desktopId, porfolio) {
53
+ this.logic.create(id, porfolio);
54
+ await this.index();
55
+ return this;
56
+ }
57
+
58
+ /**
59
+ * @param {Partial<this['state']>} patch
60
+ */
61
+ async patch(patch) {
62
+ this.logic.patch(patch);
63
+ await this.index();
64
+ }
65
+
66
+ async index() {
67
+ const index = `${this.state.code} ${this.state.name}`;
68
+ this.logic.index(index);
69
+ await this.persist();
70
+ }
71
+
72
+ delete() {}
73
+ }
74
+
75
+ module.exports = {
76
+ Canton,
77
+ CantonLogic,
78
+ CantonShape,
79
+ CantonState,
80
+ };
@@ -0,0 +1,81 @@
1
+ // @ts-check
2
+ const {id} = require('xcraft-core-goblin/lib/types.js');
3
+ const {Elf} = require('xcraft-core-goblin');
4
+ const {string, array} = require('xcraft-core-stones');
5
+
6
+ class MetaShape {
7
+ index = string;
8
+ status = string;
9
+ locale = string;
10
+ scope = string;
11
+ }
12
+
13
+ class CantonAdminShape {
14
+ id = id('cantonAdmin');
15
+ name = string;
16
+ cantonId = id('canton');
17
+ cantonCode = string;
18
+ cantonName = string;
19
+ communeIds = array(id('commune'));
20
+ meta = MetaShape;
21
+ }
22
+
23
+ class CantonAdminState extends Elf.Sculpt(CantonAdminShape) {}
24
+
25
+ class CantonAdminLogic extends Elf.Archetype {
26
+ static db = 'swiss';
27
+ static indices = [];
28
+
29
+ state = new CantonAdminState();
30
+
31
+ create(id, porfolio) {
32
+ const {state} = this;
33
+ for (const [k, v] of Object.entries(porfolio)) {
34
+ state[k] = v;
35
+ }
36
+ state.id = id;
37
+ }
38
+
39
+ patch(patch) {
40
+ const {state} = this;
41
+ state._state.merge('', patch);
42
+ }
43
+
44
+ index(index) {
45
+ this.state.meta.index = index;
46
+ }
47
+ }
48
+
49
+ class CantonAdmin extends Elf {
50
+ logic = Elf.getLogic(CantonAdminLogic);
51
+ state = new CantonAdminState();
52
+
53
+ async create(id, desktopId, porfolio) {
54
+ this.logic.create(id, porfolio);
55
+ await this.index();
56
+ return this;
57
+ }
58
+
59
+ /**
60
+ * @param {Partial<this['state']>} patch
61
+ */
62
+ async patch(patch) {
63
+ this.logic.patch(patch);
64
+ await this.index();
65
+ }
66
+
67
+ async index() {
68
+ const index = `${this.state.name}`;
69
+ this.logic.index(index);
70
+ await this.persist();
71
+ }
72
+
73
+ delete() {}
74
+ }
75
+
76
+ module.exports = {
77
+ CantonAdmin,
78
+ CantonAdminLogic,
79
+ CantonAdminShape,
80
+ CantonAdminState,
81
+ };
package/lib/commune.js ADDED
@@ -0,0 +1,84 @@
1
+ // @ts-check
2
+ const {id} = require('xcraft-core-goblin/lib/types.js');
3
+ const {Elf} = require('xcraft-core-goblin');
4
+ const {string, option, array} = require('xcraft-core-stones');
5
+
6
+ class MetaShape {
7
+ index = string;
8
+ status = string;
9
+ locale = string;
10
+ scope = string;
11
+ }
12
+
13
+ class CommuneShape {
14
+ id = id('commune');
15
+ name = string;
16
+ cantonId = option(id('canton'));
17
+ cantonCode = string;
18
+ cantonName = string;
19
+ cantonAdminId = option(id('cantonAdmin'));
20
+ cantonAdminName = string;
21
+ postalCodeIds = array(id('postalCode'));
22
+ languages = array(string);
23
+ meta = MetaShape;
24
+ }
25
+
26
+ class CommuneState extends Elf.Sculpt(CommuneShape) {}
27
+
28
+ class CommuneLogic extends Elf.Archetype {
29
+ static db = 'swiss';
30
+ static indices = [];
31
+
32
+ state = new CommuneState();
33
+
34
+ create(id, porfolio) {
35
+ const {state} = this;
36
+ for (const [k, v] of Object.entries(porfolio)) {
37
+ state[k] = v;
38
+ }
39
+ state.id = id;
40
+ }
41
+
42
+ patch(patch) {
43
+ const {state} = this;
44
+ state._state.merge('', patch);
45
+ }
46
+
47
+ index(index) {
48
+ this.state.meta.index = index;
49
+ }
50
+ }
51
+
52
+ class Commune extends Elf {
53
+ logic = Elf.getLogic(CommuneLogic);
54
+ state = new CommuneState();
55
+
56
+ async create(id, desktopId, porfolio) {
57
+ this.logic.create(id, porfolio);
58
+ await this.index();
59
+ return this;
60
+ }
61
+
62
+ /**
63
+ * @param {Partial<this['state']>} patch
64
+ */
65
+ async patch(patch) {
66
+ this.logic.patch(patch);
67
+ await this.index();
68
+ }
69
+
70
+ async index() {
71
+ const index = `${this.state.name}`;
72
+ this.logic.index(index);
73
+ await this.persist();
74
+ }
75
+
76
+ delete() {}
77
+ }
78
+
79
+ module.exports = {
80
+ Commune,
81
+ CommuneLogic,
82
+ CommuneShape,
83
+ CommuneState,
84
+ };
@@ -0,0 +1,70 @@
1
+ const BASE_URL = 'https://api3.geo.admin.ch/rest/services/ech/MapServer/find';
2
+
3
+ const LAYER = 'ch.swisstopo.amtliches-gebaeudeadressverzeichnis';
4
+
5
+ /**
6
+ * Resolve a structured address from a GeoAdmin SearchServer featureId.
7
+ *
8
+ * @param {string} featureId - SearchServer featureId, e.g. "1487827_0".
9
+ * @param {AbortSignal} [signal] - Optional abort signal.
10
+ * @returns {Promise<{
11
+ * street: string|null,
12
+ * houseNumber: string|null,
13
+ * zip: string|null,
14
+ * city: string|null,
15
+ * municipality: string|null,
16
+ * municipalityId: number|null,
17
+ * egid: number|null,
18
+ * edid: number|null,
19
+ * egaid: number|null
20
+ * }|null>}
21
+ */
22
+ async function getAddress(featureId, signal) {
23
+ const [egid, edid = '0'] = String(featureId).split('_');
24
+
25
+ const params = new URLSearchParams({
26
+ layer: LAYER,
27
+ searchText: egid,
28
+ searchField: 'bdg_egid',
29
+ contains: 'false',
30
+ returnGeometry: 'false',
31
+ lang: 'fr',
32
+ });
33
+
34
+ const response = await fetch(`${BASE_URL}?${params}`, {
35
+ signal,
36
+ });
37
+
38
+ if (!response.ok) {
39
+ throw new Error(
40
+ `GeoAdmin lookup failed: ${response.status} ${response.statusText}`
41
+ );
42
+ }
43
+
44
+ const data = await response.json();
45
+
46
+ const candidates = data.results ?? [];
47
+
48
+ const result =
49
+ candidates.find(
50
+ ({attributes}) => String(attributes?.adr_edid ?? '0') === edid
51
+ ) ?? candidates[0];
52
+
53
+ if (!result) {
54
+ return null;
55
+ }
56
+
57
+ const attrs = result.attributes ?? {};
58
+
59
+ return {
60
+ street: attrs.stn_label ?? attrs.str_label ?? null,
61
+ houseNumber: attrs.adr_number ?? null,
62
+ municipality: attrs.com_name ?? null,
63
+ municipalityId: attrs.com_fosnr ?? null,
64
+ egid: attrs.bdg_egid ?? null,
65
+ edid: attrs.adr_edid ?? null,
66
+ egaid: attrs.adr_egaid ?? null,
67
+ };
68
+ }
69
+
70
+ module.exports = getAddress;
@@ -0,0 +1,87 @@
1
+ // @ts-check
2
+ const {id} = require('xcraft-core-goblin/lib/types.js');
3
+ const {Elf} = require('xcraft-core-goblin');
4
+ const {string, option} = require('xcraft-core-stones');
5
+
6
+ class MetaShape {
7
+ index = string;
8
+ status = string;
9
+ locale = string;
10
+ scope = string;
11
+ }
12
+
13
+ class PostalCodeShape {
14
+ id = id('postalCode');
15
+ zipId = string;
16
+ zipCode = string;
17
+ zipCodeAddon = string;
18
+ name = string;
19
+ lat = string;
20
+ long = string;
21
+ language = string;
22
+ coverage = string;
23
+ communeId = option(id('commune'));
24
+ cantonAdminId = option(id('cantonAdmin'));
25
+ cantonId = option(id('canton'));
26
+ meta = MetaShape;
27
+ }
28
+
29
+ class PostalCodeState extends Elf.Sculpt(PostalCodeShape) {}
30
+
31
+ class PostalCodeLogic extends Elf.Archetype {
32
+ static db = 'swiss';
33
+ static indices = ['communeId', 'cantonId'];
34
+
35
+ state = new PostalCodeState();
36
+
37
+ create(id, porfolio) {
38
+ const {state} = this;
39
+ for (const [k, v] of Object.entries(porfolio)) {
40
+ state[k] = v;
41
+ }
42
+ state.id = id;
43
+ }
44
+
45
+ patch(patch) {
46
+ const {state} = this;
47
+ state._state.merge('', patch);
48
+ }
49
+
50
+ index(index) {
51
+ this.state.meta.index = index;
52
+ }
53
+ }
54
+
55
+ class PostalCode extends Elf {
56
+ logic = Elf.getLogic(PostalCodeLogic);
57
+ state = new PostalCodeState();
58
+
59
+ async create(id, desktopId, porfolio) {
60
+ this.logic.create(id, porfolio);
61
+ await this.index();
62
+ return this;
63
+ }
64
+
65
+ /**
66
+ * @param {Partial<this['state']>} patch
67
+ */
68
+ async patch(patch) {
69
+ this.logic.patch(patch);
70
+ await this.index();
71
+ }
72
+
73
+ async index() {
74
+ const index = `${this.state.zipCode} ${this.state.name}`;
75
+ this.logic.index(index);
76
+ await this.persist();
77
+ }
78
+
79
+ delete() {}
80
+ }
81
+
82
+ module.exports = {
83
+ PostalCode,
84
+ PostalCodeLogic,
85
+ PostalCodeShape,
86
+ PostalCodeState,
87
+ };
@@ -0,0 +1,73 @@
1
+ const BASE_URL = 'https://api3.geo.admin.ch/rest/services/ech/SearchServer';
2
+
3
+ /**
4
+ * Search for Swiss addresses using the GeoAdmin SearchServer API.
5
+ *
6
+ * The search can be narrowed by postal code and city.
7
+ *
8
+ * @param {string} searchText - Partial or complete address to search for.
9
+ * @param {Object} [options={}] - Search options.
10
+ * @param {string} [options.zip] - Swiss postal code (NPA), e.g. "2560".
11
+ * @param {string} [options.city] - City name, e.g. "Nidau".
12
+ * @param {string} [options.lang="fr"] - Result language.
13
+ * @param {AbortSignal} [options.signal] - Optional signal used to abort the request.
14
+ *
15
+ * @returns {Promise<Array<{
16
+ * id: string|number,
17
+ * lat: number,
18
+ * lng: number,
19
+ * label: string
20
+ * }>>} Matching addresses.
21
+ *
22
+ * @throws {Error} If the GeoAdmin request fails.
23
+ */
24
+ async function searchAddresses(
25
+ searchText,
26
+ {zip, city, lang = 'fr', signal} = {}
27
+ ) {
28
+ if (!searchText?.trim()) {
29
+ return [];
30
+ }
31
+
32
+ const location = [searchText, zip, city].filter(Boolean).join(' ');
33
+
34
+ const params = new URLSearchParams({
35
+ searchText: location,
36
+ type: 'locations',
37
+ origins: 'address',
38
+ lang,
39
+ });
40
+
41
+ const response = await fetch(`${BASE_URL}?${params}`, {
42
+ method: 'GET',
43
+ signal,
44
+ });
45
+
46
+ if (!response.ok) {
47
+ throw new Error(
48
+ `GeoAdmin search failed: ${response.status} ${response.statusText}`
49
+ );
50
+ }
51
+
52
+ const data = await response.json();
53
+
54
+ return parseResults(data);
55
+ }
56
+
57
+ function parseResults(data) {
58
+ return (data.results ?? []).map(({id, attrs}) => ({
59
+ id: attrs.featureId,
60
+ lat: attrs.lat,
61
+ lon: attrs.lon,
62
+ label: cleanLabel(attrs.label),
63
+ }));
64
+ }
65
+
66
+ function cleanLabel(label = '') {
67
+ return label
68
+ .replace(/<[^>]+>/g, '')
69
+ .replace(/\s+/g, ' ')
70
+ .trim();
71
+ }
72
+
73
+ module.exports = searchAddresses;
package/lib/swiss.js ADDED
@@ -0,0 +1,406 @@
1
+ // @ts-check
2
+ const {Elf} = require('xcraft-core-goblin');
3
+ const {id} = require('xcraft-core-goblin/lib/types.js');
4
+ const {pipeline} = require('node:stream/promises');
5
+ const {
6
+ createSwissAdminCsvTransform,
7
+ createGeoDataEntryConsumer,
8
+ } = require('./utils.js');
9
+ const Batcher = require('xcraft-core-utils/lib/batcher.js');
10
+ const {
11
+ PostalCodeLogic,
12
+ PostalCode,
13
+ PostalCodeShape,
14
+ } = require('./postalCode.js');
15
+ const {Canton} = require('./canton.js');
16
+ const {Commune, CommuneLogic} = require('./commune.js');
17
+ const {CantonAdmin} = require('./cantonAdmin.js');
18
+
19
+ function parseAutocompleteInput(input) {
20
+ const q = String(input ?? '')
21
+ .normalize('NFKD')
22
+ .replace(/[\u0300-\u036f]/g, '')
23
+ .toLowerCase()
24
+ .trim();
25
+
26
+ if (!q) {
27
+ return null;
28
+ }
29
+
30
+ const tokens = q
31
+ .split(/\s+/)
32
+ .map((token) => token.replace(/[^a-z0-9]/g, ''))
33
+ .filter(Boolean)
34
+ .slice(0, 5);
35
+
36
+ if (!tokens.length) {
37
+ return null;
38
+ }
39
+
40
+ return tokens.map((token) => `${token}*`).join(' ');
41
+ }
42
+
43
+ class SwissShape {
44
+ id = id;
45
+ }
46
+
47
+ class SwissState extends Elf.Sculpt(SwissShape) {}
48
+
49
+ class SwissLogic extends Elf.Spirit {
50
+ state = new SwissState({
51
+ id: 'swiss',
52
+ });
53
+ }
54
+
55
+ class Swiss extends Elf.Alone {
56
+ logic = Elf.getLogic(SwissLogic);
57
+ state = new SwissState();
58
+ /** @type {Set<Batcher>} */ _batchers = new Set();
59
+
60
+ async init() {
61
+ this.log.dbg('Pain, fromage et viande séchée...');
62
+ const bestCommuneOfSwitzerlandExist = await this.cryo.isPersisted(
63
+ CommuneLogic.db,
64
+ 'commune@6512'
65
+ );
66
+ if (!bestCommuneOfSwitzerlandExist) {
67
+ await this.loadEntities();
68
+ }
69
+ }
70
+
71
+ async searchPostalCode(input) {
72
+ const query = parseAutocompleteInput(input);
73
+ if (!query) {
74
+ return [];
75
+ }
76
+ const searchResults = await this.cryo.search2(
77
+ PostalCodeLogic.db,
78
+ query,
79
+ ['fr'],
80
+ ['postalCode'],
81
+ 10
82
+ );
83
+ const results = [];
84
+ for (const result of searchResults) {
85
+ const postalCode = await this.cryo.getState(
86
+ PostalCodeLogic.db,
87
+ result.documentId,
88
+ PostalCodeShape
89
+ );
90
+ results.push(postalCode);
91
+ }
92
+
93
+ return results;
94
+ }
95
+
96
+ async loadEntities() {
97
+ this.log.dbg('Loading swiss entities...');
98
+ const postalCodesByCommuneId = await this.loadSwissGeoData();
99
+
100
+ const {communes, admins, cantons} = await this.loadSwissAdmin();
101
+ const communesToInsert = [];
102
+ const adminsToInsert = [];
103
+ const cantonsToInsert = [];
104
+
105
+ const communesById = {};
106
+ const communesByAdminId = {};
107
+ const communesByCantonId = {};
108
+ const adminsByCantonId = {};
109
+
110
+ this.log.dbg('Make federalism great again...');
111
+ for (const commune of Object.values(communes)) {
112
+ const admin = admins[commune.cantonAdminId];
113
+ if (!admin) {
114
+ throw new Error('Data loading error');
115
+ }
116
+ const canton = cantons[admin.cantonId];
117
+ if (!canton) {
118
+ throw new Error('Data loading error');
119
+ }
120
+
121
+ if (!communesByAdminId[commune.cantonAdminId]) {
122
+ communesByAdminId[commune.cantonAdminId] = [];
123
+ }
124
+ communesByAdminId[commune.cantonAdminId].push(commune.id);
125
+
126
+ if (!communesByCantonId[canton.id]) {
127
+ communesByCantonId[canton.id] = [];
128
+ }
129
+ communesByCantonId[canton.id].push(commune.id);
130
+
131
+ let postalCodeIds = [];
132
+ let languages = [];
133
+ const postalCodes = postalCodesByCommuneId[commune.id];
134
+ if (postalCodes) {
135
+ postalCodeIds = postalCodes.map((p) => p.id);
136
+ languages = postalCodes.reduce((languages, p) => {
137
+ if (!languages.includes(p.lang)) {
138
+ languages.push(p.lang);
139
+ }
140
+ return languages;
141
+ }, []);
142
+ }
143
+
144
+ const communeState = {
145
+ id: commune.id,
146
+ name: commune.name,
147
+ cantonId: canton.id,
148
+ cantonCode: canton.code,
149
+ cantonName: canton.name,
150
+ cantonAdminId: commune.cantonAdminId,
151
+ cantonAdminName: admin.name,
152
+ postalCodeIds,
153
+ languages,
154
+ meta: {
155
+ status: 'published',
156
+ index: commune.name,
157
+ locale: 'fr',
158
+ scope: 'commune',
159
+ },
160
+ };
161
+ communesById[commune.id] = communeState;
162
+ communesToInsert.push(communeState);
163
+ }
164
+
165
+ for (const admin of Object.values(admins)) {
166
+ const canton = cantons[admin.cantonId];
167
+ if (!adminsByCantonId[admin.cantonId]) {
168
+ adminsByCantonId[admin.cantonId] = [];
169
+ }
170
+ adminsByCantonId[admin.cantonId].push(admin.id);
171
+ adminsToInsert.push({
172
+ id: admin.id,
173
+ name: admin.name,
174
+ cantonId: canton.id,
175
+ cantonCode: canton.code,
176
+ cantonName: canton.name,
177
+ communeIds: communesByAdminId[admin.id],
178
+ meta: {
179
+ status: 'published',
180
+ index: admin.name,
181
+ locale: 'fr',
182
+ scope: 'admin',
183
+ },
184
+ });
185
+ }
186
+
187
+ for (const canton of Object.values(cantons)) {
188
+ cantonsToInsert.push({
189
+ id: canton.id,
190
+ name: canton.name,
191
+ code: canton.code,
192
+ cantonAdminIds: adminsByCantonId[canton.id],
193
+ communeIds: communesByCantonId[canton.id],
194
+ meta: {
195
+ status: 'published',
196
+ index: `${canton.code} ${canton.name}`,
197
+ locale: 'fr',
198
+ scope: 'canton',
199
+ },
200
+ });
201
+ }
202
+
203
+ this.log.dbg('Adressing switzerland ...');
204
+ const postalCodeToInsert = [];
205
+ for (const postalCodes of Object.values(postalCodesByCommuneId)) {
206
+ for (const postalCode of postalCodes) {
207
+ const commune = communesById[postalCode.communeId];
208
+ let cantonId = null;
209
+ let cantonAdminId = null;
210
+ if (commune) {
211
+ cantonId = commune.cantonId;
212
+ cantonAdminId = commune.cantonAdminId;
213
+ }
214
+
215
+ postalCodeToInsert.push({
216
+ id: postalCode.id,
217
+ zipId: postalCode.zipId,
218
+ zipCode: postalCode.zip,
219
+ zipCodeAddon: postalCode.zipAddon,
220
+ name: postalCode.name,
221
+ lat: postalCode.lat,
222
+ long: postalCode.long,
223
+ language: postalCode.lang,
224
+ coverage: postalCode.coverage,
225
+ communeId: postalCode.communeId,
226
+ cantonAdminId,
227
+ cantonId,
228
+ meta: {
229
+ status: 'published',
230
+ index: `${postalCode.zip} ${postalCode.name}`,
231
+ locale: 'fr',
232
+ scope: 'postalCode',
233
+ },
234
+ });
235
+ }
236
+ }
237
+
238
+ const cryo = this.quest.getAPI('cryo');
239
+ const batcher = new Batcher(
240
+ async () => {
241
+ this.log.dbg(`Swiss entities begin transaction`);
242
+ await cryo.begin({db: PostalCodeLogic.db});
243
+ },
244
+ async (batch) => {
245
+ this.log.dbg(`Swiss entities commit transaction (batch of ${batch})`);
246
+ await cryo.commit({db: PostalCodeLogic.db});
247
+ }
248
+ );
249
+ this._batchers.add(batcher);
250
+
251
+ await batcher.start();
252
+ this.quest.defer(async () => {
253
+ this._batchers.delete(batcher);
254
+ await batcher.stop();
255
+ this.log.dbg(`End load entities`);
256
+ });
257
+
258
+ const feedId = await this.newQuestFeed();
259
+ for (const postalCode of postalCodeToInsert) {
260
+ if (!(await batcher.pump())) {
261
+ break;
262
+ }
263
+
264
+ await new PostalCode(this).insertOrReplace(
265
+ postalCode.id,
266
+ feedId,
267
+ postalCode
268
+ );
269
+
270
+ if (!(await batcher.bump())) {
271
+ break;
272
+ }
273
+ }
274
+
275
+ for (const canton of cantonsToInsert) {
276
+ if (!(await batcher.pump())) {
277
+ break;
278
+ }
279
+
280
+ await new Canton(this).insertOrReplace(canton.id, feedId, canton);
281
+
282
+ if (!(await batcher.bump())) {
283
+ break;
284
+ }
285
+ }
286
+
287
+ for (const commune of communesToInsert) {
288
+ if (!(await batcher.pump())) {
289
+ break;
290
+ }
291
+
292
+ await new Commune(this).insertOrReplace(commune.id, feedId, commune);
293
+
294
+ if (!(await batcher.bump())) {
295
+ break;
296
+ }
297
+ }
298
+
299
+ for (const admin of adminsToInsert) {
300
+ if (!(await batcher.pump())) {
301
+ break;
302
+ }
303
+
304
+ await new CantonAdmin(this).insertOrReplace(admin.id, feedId, admin);
305
+
306
+ if (!(await batcher.bump())) {
307
+ break;
308
+ }
309
+ }
310
+
311
+ this.log.dbg('Swiss entities loaded !');
312
+ }
313
+
314
+ async loadSwissGeoData() {
315
+ const url =
316
+ 'https://data.geo.admin.ch/ch.swisstopo-vd.ortschaftenverzeichnis_plz/ortschaftenverzeichnis_plz/ortschaftenverzeichnis_plz_4326.csv.zip';
317
+ const res = await fetch(url);
318
+ if (!res.ok) {
319
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
320
+ }
321
+
322
+ if (!res.body) {
323
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
324
+ }
325
+
326
+ this.log.dbg('Fetching and unzipping swiss geo data...');
327
+ const unzipper = require('unzipper');
328
+ const geoData = [];
329
+ try {
330
+ await pipeline(
331
+ res.body,
332
+ unzipper.Parse(),
333
+ createGeoDataEntryConsumer(geoData)
334
+ );
335
+ } catch (err) {
336
+ this.log.err(err);
337
+ }
338
+ geoData.splice(0, 1);
339
+ return geoData.reduce((state, z) => {
340
+ const key = z.communeId || 'ext'; //communeId can be null (ex. lichtenstein zip codes)
341
+ if (!state[key]) {
342
+ state[key] = [];
343
+ }
344
+ state[key].push(z);
345
+ return state;
346
+ }, {});
347
+ }
348
+
349
+ async loadSwissAdmin() {
350
+ const communes = [];
351
+ const cantons = [];
352
+ const admins = [];
353
+ const n = new Date();
354
+ const snapshotDate = `${n.getDate()}-${
355
+ n.getMonth() + 1
356
+ }-${n.getFullYear()}`;
357
+ const url = `https://sms.bfs.admin.ch/WcfBFSSpecificService.svc/AnonymousRest/communes/snapshots?format=Csv&useBfsCode=true&startPeriod=${snapshotDate}&endPeriod=${snapshotDate}`;
358
+ const res = await fetch(url);
359
+
360
+ if (!res.ok) {
361
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
362
+ }
363
+
364
+ try {
365
+ this.log.dbg('Fetching and unzipping swiss admin data...');
366
+ await pipeline(
367
+ res.body,
368
+ createSwissAdminCsvTransform(communes, admins, cantons)
369
+ );
370
+ } catch (err) {
371
+ this.log.err(err);
372
+ }
373
+
374
+ return {
375
+ communes: communes.reduce((state, c) => {
376
+ if (!state[c.id]) {
377
+ state[c.id] = c;
378
+ } else {
379
+ throw new Error('Duplicate commune infos');
380
+ }
381
+
382
+ return state;
383
+ }, {}),
384
+ admins: admins.reduce((state, c) => {
385
+ if (!state[c.id]) {
386
+ state[c.id] = c;
387
+ } else {
388
+ throw new Error('Duplicate admin infos');
389
+ }
390
+
391
+ return state;
392
+ }, {}),
393
+ cantons: cantons.reduce((state, c) => {
394
+ if (!state[c.id]) {
395
+ state[c.id] = c;
396
+ } else {
397
+ throw new Error('Duplicate canton infos');
398
+ }
399
+
400
+ return state;
401
+ }, {}),
402
+ };
403
+ }
404
+ }
405
+
406
+ module.exports = {Swiss, SwissLogic};
package/lib/utils.js ADDED
@@ -0,0 +1,204 @@
1
+ const {Transform} = require('node:stream');
2
+ const {pipeline} = require('node:stream/promises');
3
+
4
+ const isOutside = (c) => ['FL', 'IT', 'DE', ''].includes(c);
5
+
6
+ function createGeoDataCsvParser(geoData) {
7
+ let leftover = '';
8
+
9
+ const buildRow = (geoData, columns) => {
10
+ const [
11
+ name,
12
+ zip,
13
+ zipAddon,
14
+ zipId,
15
+ communeName,
16
+ communeSourceId,
17
+ cantonCode,
18
+ coverage,
19
+ lat,
20
+ long,
21
+ lang,
22
+ validity,
23
+ ] = columns;
24
+
25
+ const communeId = isOutside(cantonCode)
26
+ ? null
27
+ : `commune@${communeSourceId}`;
28
+
29
+ geoData.push({
30
+ id: communeId
31
+ ? `postalCode@${communeId}@${zipId}` //swiss postalCode
32
+ : `postalCode@ext@${zipId}`, //non-swiss
33
+ name,
34
+ zip,
35
+ zipAddon,
36
+ zipId,
37
+ communeName,
38
+ communeId,
39
+ cantonCode,
40
+ coverage,
41
+ lat,
42
+ long,
43
+ lang,
44
+ validity,
45
+ });
46
+ };
47
+
48
+ return new Transform({
49
+ transform(chunk, _enc, cb) {
50
+ try {
51
+ let data = chunk.toString('utf8');
52
+ if (leftover) {
53
+ data = leftover + data;
54
+ leftover = '';
55
+ }
56
+
57
+ const lines = data.split(/\n/);
58
+ leftover = lines.pop() ?? '';
59
+
60
+ for (let line of lines) {
61
+ line = line.replace(/\r$/, '');
62
+ if (!line) continue;
63
+
64
+ const columns = line.split(';');
65
+ buildRow(geoData, columns);
66
+ }
67
+
68
+ cb();
69
+ } catch (err) {
70
+ cb(err);
71
+ }
72
+ },
73
+
74
+ flush(cb) {
75
+ try {
76
+ const line = leftover.replace(/\r$/, '');
77
+ leftover = '';
78
+ if (!line) return cb();
79
+
80
+ const columns = line.split(';');
81
+ if (columns.length === 16 && columns[0] === '01') {
82
+ buildRow(geoData, columns);
83
+ }
84
+
85
+ cb();
86
+ } catch (err) {
87
+ cb(err);
88
+ }
89
+ },
90
+ });
91
+ }
92
+
93
+ function createGeoDataEntryConsumer(geoData) {
94
+ return new Transform({
95
+ objectMode: true,
96
+
97
+ async transform(entry, _enc, cb) {
98
+ try {
99
+ if (!entry?.path) {
100
+ entry.autodrain?.();
101
+ return cb();
102
+ }
103
+ await pipeline(entry, createGeoDataCsvParser(geoData));
104
+ cb();
105
+ } catch (err) {
106
+ entry?.autodrain?.();
107
+ cb(err);
108
+ }
109
+ },
110
+ });
111
+ }
112
+
113
+ function createSwissAdminCsvTransform(communes, admins, cantons) {
114
+ let leftover = '';
115
+
116
+ const clean = (s) => {
117
+ if (!s) return s;
118
+ if (s.length >= 2 && s[0] === '"' && s[s.length - 1] === '"') {
119
+ return s.slice(1, -1);
120
+ }
121
+ return s;
122
+ };
123
+
124
+ const handleLine = (line) => {
125
+ line = line.replace(/\r$/, '');
126
+ if (!line) return;
127
+
128
+ const columns = line.split(',');
129
+ if (columns.length !== 29) return;
130
+
131
+ const [
132
+ id,
133
+ _vf,
134
+ _vt,
135
+ lvl,
136
+ _p,
137
+ _nameEn,
138
+ nameFr,
139
+ nameDe,
140
+ nameIt,
141
+ abbEn,
142
+ abbFr,
143
+ ] = columns;
144
+
145
+ if (id !== 'Identifier' && lvl === '"1"') {
146
+ cantons.push({
147
+ id: `canton@${clean(id)}`,
148
+ name: clean(nameFr),
149
+ code: clean(abbFr),
150
+ });
151
+ }
152
+
153
+ if (id !== 'Identifier' && lvl === '"2"') {
154
+ admins.push({
155
+ id: `cantonAdmin@${clean(id)}`,
156
+ name: clean(nameFr),
157
+ cantonId: `canton@${clean(_p)}`,
158
+ });
159
+ }
160
+
161
+ if (id !== 'Identifier' && lvl === '"3"') {
162
+ communes.push({
163
+ id: `commune@${clean(id)}`,
164
+ name: clean(nameFr),
165
+ cantonAdminId: `cantonAdmin@${clean(_p)}`,
166
+ });
167
+ }
168
+ };
169
+
170
+ return new Transform({
171
+ transform(chunk, _enc, cb) {
172
+ try {
173
+ let data = chunk.toString();
174
+ if (leftover) {
175
+ data = leftover + data;
176
+ leftover = '';
177
+ }
178
+
179
+ const lines = data.split(/\n/);
180
+ leftover = lines.pop() || '';
181
+
182
+ for (const line of lines) handleLine(line);
183
+ cb();
184
+ } catch (err) {
185
+ cb(err);
186
+ }
187
+ },
188
+
189
+ flush(cb) {
190
+ try {
191
+ if (leftover) handleLine(leftover);
192
+ leftover = '';
193
+ cb();
194
+ } catch (err) {
195
+ cb(err);
196
+ }
197
+ },
198
+ });
199
+ }
200
+
201
+ module.exports = {
202
+ createGeoDataEntryConsumer,
203
+ createSwissAdminCsvTransform,
204
+ };
package/package.json ADDED
@@ -0,0 +1,28 @@
1
+ {
2
+ "name": "goblin-swiss",
3
+ "version": "0.2.0",
4
+ "description": "Swiss stuff",
5
+ "author": "Epsitec SA",
6
+ "contributors": [
7
+ "Samuel Loup <loup@epsitec.ch>"
8
+ ],
9
+ "license": "MIT",
10
+ "config": {
11
+ "xcraft": {
12
+ "commands": true
13
+ }
14
+ },
15
+ "scripts": {
16
+ "test": "echo \"Error: no test specified\" && exit 1"
17
+ },
18
+ "dependencies": {
19
+ "xcraft-core-goblin": "^5.8.0",
20
+ "xcraft-core-utils": "^4.14.0",
21
+ "unzipper": "^0.12.3"
22
+ },
23
+ "devDependencies": {
24
+ "xcraft-dev-prettier": "^2.0.0",
25
+ "xcraft-dev-rules": "^4.4.2"
26
+ },
27
+ "prettier": "xcraft-dev-prettier"
28
+ }
package/postalCode.js ADDED
@@ -0,0 +1,4 @@
1
+ const {Elf} = require('xcraft-core-goblin');
2
+ const {PostalCode, PostalCodeLogic} = require('goblin-swiss/lib/postalCode.js');
3
+
4
+ exports.xcraftCommands = Elf.birth(PostalCode, PostalCodeLogic);
package/swiss.js ADDED
@@ -0,0 +1,4 @@
1
+ const {Elf} = require('xcraft-core-goblin');
2
+ const {Swiss, SwissLogic} = require('goblin-swiss/lib/swiss.js');
3
+
4
+ exports.xcraftCommands = Elf.birth(Swiss, SwissLogic);
@@ -0,0 +1,32 @@
1
+ 'use strict';
2
+
3
+ const {expect} = require('chai');
4
+ const {Elf} = require('xcraft-core-goblin/lib/test.js');
5
+ const {Swiss} = require('../lib/swiss.js');
6
+
7
+ describe('goblin.swiss', function () {
8
+ let runner;
9
+
10
+ this.beforeAll(function () {
11
+ runner = new Elf.Runner();
12
+ runner.init();
13
+ });
14
+
15
+ this.afterAll(function () {
16
+ runner.dispose();
17
+ });
18
+
19
+ it.skip('load swisspost zips', async function () {
20
+ this.timeout(process.env.NODE_ENV === 'development' ? 1000000 : 40000);
21
+
22
+ /** @this {Elf} */
23
+ async function testLoad() {
24
+ const swiss = new Swiss(this);
25
+ await swiss.boot();
26
+ const results = await swiss.searchPostalCode('z*');
27
+ this.log.dbg(results);
28
+ }
29
+
30
+ await runner.it(testLoad);
31
+ });
32
+ });