@stamhoofd/backend-statistics-syncer 2.148.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/src/rows.ts ADDED
@@ -0,0 +1,327 @@
1
+ import { Formatter } from '@stamhoofd/utility';
2
+
3
+ /**
4
+ * Turns source records into the rows of the statistics database.
5
+ *
6
+ * Every function here is pure and drops most of the personal data on the way: a member arrives with a
7
+ * full `MemberDetails` and leaves as a date of birth, a gender and a postal code. Nothing in this
8
+ * file may start returning a name, an email address or a phone number — the statistics database has
9
+ * no columns for them, and the schema test would fail if it did.
10
+ *
11
+ * The inputs are described structurally rather than as model classes, so the models satisfy them
12
+ * without this package depending on how they are loaded.
13
+ */
14
+
15
+ export type StatisticsRow = Record<string, string | number | boolean | Date | null>;
16
+
17
+ /**
18
+ * The language translated names are resolved in. The statistics database holds one name per group,
19
+ * and the sync has no request to take a language from, so it picks the platform's own rather than
20
+ * whatever language happens to be set on the process.
21
+ */
22
+ export const statisticsLanguage = 'nl';
23
+
24
+ export type RegistrationPeriodSource = {
25
+ id: string;
26
+ startDate: Date;
27
+ endDate: Date;
28
+ locked: boolean;
29
+ organizationId: string | null;
30
+ previousPeriodId: string | null;
31
+ nextPeriodId: string | null;
32
+ customName: string | null;
33
+ createdAt: Date;
34
+ updatedAt: Date;
35
+ };
36
+
37
+ export type OrganizationSource = {
38
+ id: string;
39
+ name: string;
40
+ uri: string;
41
+ address: { postalCode: string; city: string };
42
+ periodId: string;
43
+ active: boolean;
44
+ createdAt: Date;
45
+ updatedAt: Date;
46
+ };
47
+
48
+ export type GroupSource = {
49
+ id: string;
50
+ type: string;
51
+ settings: { name: { get: (language: string) => string } };
52
+ organizationId: string;
53
+ periodId: string | null;
54
+ defaultAgeGroupId: string | null;
55
+ status: string;
56
+ deletedAt: Date | null;
57
+ createdAt: Date;
58
+ updatedAt: Date;
59
+ };
60
+
61
+ export type MemberSource = {
62
+ id: string;
63
+ details: { birthDay: Date | null; gender: string; address: { postalCode: string } | null };
64
+ organizationId: string | null;
65
+ createdAt: Date;
66
+ updatedAt: Date;
67
+ lastRegisteredAt: Date | null;
68
+ };
69
+
70
+ export type RegistrationSource = {
71
+ id: string;
72
+ organizationId: string;
73
+ memberId: string;
74
+ groupId: string;
75
+ periodId: string | null;
76
+ registeredAt: Date | null;
77
+ startDate: Date | null;
78
+ endDate: Date | null;
79
+ trialUntil: Date | null;
80
+ deactivatedAt: Date | null;
81
+ waitingList: boolean;
82
+ cycle: number;
83
+ createdAt: Date;
84
+ updatedAt: Date;
85
+ };
86
+
87
+ export type MembershipSource = {
88
+ id: string;
89
+ memberId: string;
90
+ membershipTypeId: string;
91
+ organizationId: string;
92
+ periodId: string;
93
+ startDate: Date;
94
+ endDate: Date;
95
+ expireDate: Date | null;
96
+ trialUntil: Date | null;
97
+ deletedAt: Date | null;
98
+ createdAt: Date;
99
+ updatedAt: Date;
100
+ };
101
+
102
+ export type ResponsibilityRecordSource = {
103
+ id: string;
104
+ memberId: string;
105
+ groupId: string | null;
106
+ organizationId: string | null;
107
+ responsibilityId: string;
108
+ startDate: Date;
109
+ endDate: Date | null;
110
+ };
111
+
112
+ export type NamedConfigSource = { id: string; name: string };
113
+
114
+ export type PlatformSource = {
115
+ id: string;
116
+ config: { name: string; financialSupport: { priceName: string } | null };
117
+ membershipOrganizationId: string | null;
118
+ };
119
+
120
+ /**
121
+ * The label the reports show for a period, mirroring `RegistrationPeriodBase.nameShort`: the custom
122
+ * name when there is one, otherwise the years it spans.
123
+ *
124
+ * Reimplemented here rather than read off the model because the model's getter runs `$t`, which needs
125
+ * a request to take a language from and throws in the sync. The years are resolved in the application
126
+ * timezone, so a period starting at midnight in Brussels does not fall back into the previous year.
127
+ */
128
+ export function periodName(period: { customName: string | null; startDate: Date; endDate: Date }): string {
129
+ const customName = period.customName?.trim();
130
+ if (customName) {
131
+ return customName;
132
+ }
133
+
134
+ const startYear = Formatter.year(period.startDate);
135
+ const endYear = Formatter.year(period.endDate);
136
+ return startYear === endYear ? `${startYear}` : `${startYear} - ${endYear}`;
137
+ }
138
+
139
+ export function flattenRegistrationPeriod(period: RegistrationPeriodSource): StatisticsRow {
140
+ return {
141
+ id: period.id,
142
+ startDate: period.startDate,
143
+ endDate: period.endDate,
144
+ locked: period.locked,
145
+ organizationId: period.organizationId,
146
+ previousPeriodId: period.previousPeriodId,
147
+ nextPeriodId: period.nextPeriodId,
148
+ customName: period.customName,
149
+ name: periodName(period),
150
+ createdAt: period.createdAt,
151
+ updatedAt: period.updatedAt,
152
+ };
153
+ }
154
+
155
+ /**
156
+ * One row per unit per period: the unit as it was that year. A unit that is renamed or moves keeps
157
+ * the name and the place it was counted under in the years already settled.
158
+ *
159
+ * `periodId` is the year this row describes, not the period the unit is in now — the latter lives on
160
+ * the source record and is what the netwerk links are recorded against.
161
+ *
162
+ * Only the postal code and city of the address survive: the report maps units by postal code and
163
+ * lists them by city. An organization is a legal entity rather than a natural person.
164
+ */
165
+ export function flattenOrganization(organization: OrganizationSource, periodId: string): StatisticsRow {
166
+ return {
167
+ id: organization.id,
168
+ periodId,
169
+ name: organization.name,
170
+ uri: organization.uri,
171
+ postalCode: emptyToNull(organization.address.postalCode),
172
+ city: emptyToNull(organization.address.city),
173
+ active: organization.active,
174
+ createdAt: organization.createdAt,
175
+ updatedAt: organization.updatedAt,
176
+ };
177
+ }
178
+
179
+ export function flattenGroup(group: GroupSource): StatisticsRow {
180
+ return {
181
+ id: group.id,
182
+ type: group.type,
183
+ name: group.settings.name.get(statisticsLanguage),
184
+ organizationId: group.organizationId,
185
+ periodId: group.periodId,
186
+ defaultAgeGroupId: group.defaultAgeGroupId,
187
+ status: group.status,
188
+ deletedAt: group.deletedAt,
189
+ createdAt: group.createdAt,
190
+ updatedAt: group.updatedAt,
191
+ };
192
+ }
193
+
194
+ /**
195
+ * One row per member per period: what was true of this member in that year. The source holds only
196
+ * what is true of them now, so every open period gets the current details and a frozen one keeps the
197
+ * row it was counted with.
198
+ *
199
+ * The date of birth and the postal code are carried over because the report needs them: it charts
200
+ * members by age, which is only exact with the date behind it, and maps them by postal code. The
201
+ * rest of the address and everything that names or reaches the member stays behind.
202
+ *
203
+ * The birth date is written as the calendar date the application means, not as an instant. A member
204
+ * born on 17 May is held as midnight in Europe/Brussels, which a process running in UTC would write
205
+ * to a date column as 16 May — a day early for every member.
206
+ */
207
+ export function flattenMember(member: MemberSource, periodId: string): StatisticsRow {
208
+ return {
209
+ id: member.id,
210
+ periodId,
211
+ birthDate: member.details.birthDay ? Formatter.dateIso(member.details.birthDay) : null,
212
+ gender: member.details.gender,
213
+ postalCode: member.details.address ? emptyToNull(member.details.address.postalCode) : null,
214
+ organizationId: member.organizationId,
215
+ createdAt: member.createdAt,
216
+ updatedAt: member.updatedAt,
217
+ lastRegisteredAt: member.lastRegisteredAt,
218
+ };
219
+ }
220
+
221
+ export function flattenRegistration(registration: RegistrationSource): StatisticsRow {
222
+ return {
223
+ id: registration.id,
224
+ organizationId: registration.organizationId,
225
+ memberId: registration.memberId,
226
+ groupId: registration.groupId,
227
+ periodId: registration.periodId,
228
+ registeredAt: registration.registeredAt,
229
+ startDate: registration.startDate,
230
+ endDate: registration.endDate,
231
+ trialUntil: registration.trialUntil,
232
+ deactivatedAt: registration.deactivatedAt,
233
+ waitingList: registration.waitingList,
234
+ cycle: registration.cycle,
235
+ createdAt: registration.createdAt,
236
+ updatedAt: registration.updatedAt,
237
+ };
238
+ }
239
+
240
+ /**
241
+ * `reducedPrice` is not on the source record: the price of a lidgeld is worked out from whether the
242
+ * member has financiële ondersteuning or an active UITPAS and only the amount is kept, so the caller
243
+ * passes that same status here. It is what the reports split the lidgelden by.
244
+ */
245
+ export function flattenMembership(membership: MembershipSource, reducedPrice: boolean): StatisticsRow {
246
+ return {
247
+ id: membership.id,
248
+ memberId: membership.memberId,
249
+ membershipTypeId: membership.membershipTypeId,
250
+ reducedPrice,
251
+ organizationId: membership.organizationId,
252
+ periodId: membership.periodId,
253
+ startDate: membership.startDate,
254
+ endDate: membership.endDate,
255
+ expireDate: membership.expireDate,
256
+ trialUntil: membership.trialUntil,
257
+ deletedAt: membership.deletedAt,
258
+ createdAt: membership.createdAt,
259
+ updatedAt: membership.updatedAt,
260
+ };
261
+ }
262
+
263
+ /**
264
+ * One row per period the record runs through: it carries a date range rather than a year, and a
265
+ * functie held for three years was held in each of them.
266
+ */
267
+ export function flattenResponsibilityRecord(record: ResponsibilityRecordSource, periodId: string): StatisticsRow {
268
+ return {
269
+ id: record.id,
270
+ periodId,
271
+ memberId: record.memberId,
272
+ groupId: record.groupId,
273
+ organizationId: record.organizationId,
274
+ responsibilityId: record.responsibilityId,
275
+ startDate: record.startDate,
276
+ endDate: record.endDate,
277
+ };
278
+ }
279
+
280
+ /**
281
+ * The platform configuration holds one name per tak, netwerk, lidgeldtype and functie: the one it
282
+ * carries today. Written per period, so renaming one changes what the years still open are reported
283
+ * under and leaves the settled ones saying what they said.
284
+ */
285
+ export function flattenNamedConfig(config: NamedConfigSource, periodId: string): StatisticsRow {
286
+ return { id: config.id, periodId, name: config.name };
287
+ }
288
+
289
+ /**
290
+ * The platform itself, which the reports need for two things: which organization it runs on its own,
291
+ * and what it calls its verlaagd lidgeld. The first is the koepel rather than one of its local
292
+ * groups, which the jeugdbewegingen report delivers as the bovenlokale ondersteuningsstructuur.
293
+ *
294
+ * Not written per period, so the name here is the one the platform carries today. Nothing is reported
295
+ * per year out of it -- the name a sheet prints is the organization's own, per period.
296
+ *
297
+ * `reducedPriceName` is the label the platform gives its lower lidgeld, which the reports print
298
+ * beside the standaardtarief. Null when the platform names none, and the report says it in words of
299
+ * its own rather than inventing a name here.
300
+ */
301
+ export function flattenPlatform(platform: PlatformSource): StatisticsRow {
302
+ return {
303
+ id: platform.id,
304
+ name: platform.config.name,
305
+ membershipOrganizationId: platform.membershipOrganizationId,
306
+ reducedPriceName: platform.config.financialSupport?.priceName ?? null,
307
+ };
308
+ }
309
+
310
+ /**
311
+ * The label a tak carries, mirroring `DefaultAgeGroup.name`: its names joined, the last two with
312
+ * "of".
313
+ *
314
+ * Reimplemented here rather than read off the structure because the structure's getter runs `$t` on
315
+ * the separator, which resolves to the translation key in the sync.
316
+ */
317
+ export function defaultAgeGroupName(names: string[]): string {
318
+ return Formatter.joinLast(names, ', ', ' of ');
319
+ }
320
+
321
+ export function flattenDefaultAgeGroup(group: { id: string; names: string[]; minAge: number | null; maxAge: number | null }, periodId: string): StatisticsRow {
322
+ return { id: group.id, periodId, name: defaultAgeGroupName(group.names), minAge: group.minAge, maxAge: group.maxAge };
323
+ }
324
+
325
+ function emptyToNull(value: string): string | null {
326
+ return value.length === 0 ? null : value;
327
+ }
@@ -0,0 +1,250 @@
1
+ import { getStatisticsConnection, getStatisticsDatabaseConfig } from './database.js';
2
+ import { reconciledTables } from './sync.js';
3
+
4
+ /**
5
+ * Column names that would mean a natural person ended up in the statistics database. This guards
6
+ * every table in it, not only the ones the first migration created: the database is handed to
7
+ * reporting tools that must never reach the main database.
8
+ */
9
+ const personalDataColumns = [
10
+ 'firstname',
11
+ 'lastname',
12
+ 'birthday',
13
+ 'birthdate',
14
+ 'dateofbirth',
15
+ 'email',
16
+ 'phone',
17
+ 'address',
18
+ 'street',
19
+ 'postalcode',
20
+ 'nationalregister',
21
+ 'securitycode',
22
+ 'membernumber',
23
+ 'details',
24
+ 'recordanswers',
25
+ ];
26
+
27
+ /**
28
+ * Deliberate exceptions to the list above, as `table.column`.
29
+ *
30
+ * An organization is a legal entity, so where it is located is not personal data. A member's date of
31
+ * birth and postal code are, and are here because the report charts members by age and maps them by
32
+ * postal code. They are listed per table rather than removed from the list, so the same column
33
+ * appearing on a third table still fails.
34
+ */
35
+ const allowedPersonalDataColumns = new Set([
36
+ 'organizations.postalCode',
37
+ 'members.postalCode',
38
+ 'members.birthDate',
39
+ // The lookup of where a postal code is. It describes an area, not anyone living in it.
40
+ 'postal_codes.postalCode',
41
+ ]);
42
+
43
+ describe('migration.platform-statistics-schema', () => {
44
+ async function getColumns(): Promise<{ tableName: string; columnName: string; dataType: string }[]> {
45
+ const [rows] = await getStatisticsConnection().select(
46
+ 'SELECT TABLE_NAME as tableName, COLUMN_NAME as columnName, COLUMN_TYPE as dataType FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ?',
47
+ [getStatisticsDatabaseConfig().DB_DATABASE],
48
+ { nestTables: false },
49
+ );
50
+ return rows as unknown as { tableName: string; columnName: string; dataType: string }[];
51
+ }
52
+
53
+ it('creates every table the member reports read from', async () => {
54
+ const tables = new Set((await getColumns()).map(column => column.tableName));
55
+
56
+ expect([...tables].sort()).toEqual([
57
+ '_organizations_organization_tags',
58
+ 'default_age_groups',
59
+ 'groups',
60
+ 'member_platform_memberships',
61
+ 'member_responsibility_records',
62
+ 'members',
63
+ 'migrations',
64
+ 'organization_tags',
65
+ 'organizations',
66
+ 'platform',
67
+ 'platform_membership_types',
68
+ 'postal_codes',
69
+ 'registration_periods',
70
+ 'registrations',
71
+ 'responsibilities',
72
+ 'stats_sync_state',
73
+ ]);
74
+ });
75
+
76
+ it('keeps members and registrations at their source grain, so a member can hold several registrations', async () => {
77
+ const columns = await getColumns();
78
+ const registrations = columns.filter(column => column.tableName === 'registrations').map(column => column.columnName);
79
+
80
+ expect(registrations).toContain('memberId');
81
+ expect(registrations).toContain('groupId');
82
+ expect(columns.filter(column => column.tableName === 'members').map(column => column.columnName)).toContain('id');
83
+
84
+ // Nothing is pre-aggregated: no counts are stored, every figure is computed at query time.
85
+ expect(columns.filter(column => /count$/i.test(column.columnName))).toEqual([]);
86
+ });
87
+
88
+ async function compositeKeyTables(): Promise<string[]> {
89
+ const [rows] = await getStatisticsConnection().select(
90
+ 'SELECT TABLE_NAME as tableName FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND INDEX_NAME = ? GROUP BY TABLE_NAME HAVING COUNT(*) > 1',
91
+ [getStatisticsDatabaseConfig().DB_DATABASE, 'PRIMARY'],
92
+ { nestTables: false },
93
+ );
94
+ return (rows as unknown as { tableName: string }[]).map(row => row.tableName).sort();
95
+ }
96
+
97
+ /**
98
+ * Everything the source keeps only one current answer for -- a member's gender, a unit's name, a
99
+ * tak, a netwerk, a lidgeldtype, a functie -- is recorded per period instead, so that a settled
100
+ * year keeps the answer it was counted with and a correction lands in the year it belongs to.
101
+ */
102
+ it('keys everything the source holds no history for on its period as well as its id', async () => {
103
+ expect(await compositeKeyTables()).toEqual([
104
+ 'default_age_groups',
105
+ 'member_responsibility_records',
106
+ 'members',
107
+ 'organization_tags',
108
+ 'organizations',
109
+ 'platform_membership_types',
110
+ 'responsibilities',
111
+ ]);
112
+ });
113
+
114
+ it('puts the member before the period in the key, which is how the reports read a member across the years', async () => {
115
+ const [rows] = await getStatisticsConnection().select(
116
+ 'SELECT COLUMN_NAME as columnName FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND INDEX_NAME = ? ORDER BY SEQ_IN_INDEX',
117
+ [getStatisticsDatabaseConfig().DB_DATABASE, 'members', 'PRIMARY'],
118
+ { nestTables: false },
119
+ );
120
+
121
+ expect((rows as unknown as { columnName: string }[]).map(row => row.columnName)).toEqual(['id', 'periodId']);
122
+ });
123
+
124
+ /**
125
+ * The delete reconciliation walks a table by id and asks the source which ids are still there. A
126
+ * table holding several rows per id has no way to say which of them a surviving id stands for,
127
+ * so it must be one the reconciliation never walks.
128
+ */
129
+ it('reconciles deletes only for the tables keyed on their id alone', async () => {
130
+ const composite = new Set(await compositeKeyTables());
131
+
132
+ expect(reconciledTables().filter(table => composite.has(table))).toEqual([]);
133
+ });
134
+
135
+ /**
136
+ * `id` no longer identifies a row in those tables, so nothing can point at one. The period is the
137
+ * exception: it is the one dimension the source does keep history for.
138
+ */
139
+ it('leaves no foreign key pointing at a table keyed on more than its id', async () => {
140
+ const [rows] = await getStatisticsConnection().select(
141
+ 'SELECT DISTINCT REFERENCED_TABLE_NAME as tableName FROM information_schema.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = ? AND REFERENCED_TABLE_NAME IS NOT NULL',
142
+ [getStatisticsDatabaseConfig().DB_DATABASE],
143
+ { nestTables: false },
144
+ );
145
+ const composite = new Set(await compositeKeyTables());
146
+
147
+ expect((rows as unknown as { tableName: string }[]).map(row => row.tableName).filter(table => composite.has(table))).toEqual([]);
148
+ });
149
+
150
+ it('mirrors the column types of the main database', async () => {
151
+ const columns = await getColumns();
152
+ const typeOf = (tableName: string, columnName: string) => columns.find(column => column.tableName === tableName && column.columnName === columnName)?.dataType;
153
+
154
+ expect(typeOf('members', 'id')).toBe('varchar(36)');
155
+ expect(typeOf('registrations', 'memberId')).toBe('varchar(36)');
156
+ expect(typeOf('registrations', 'registeredAt')).toBe('datetime');
157
+ expect(typeOf('organizations', 'name')).toBe('varchar(100)');
158
+ expect(typeOf('organizations', 'postalCode')).toBe('varchar(36)');
159
+ expect(typeOf('organizations', 'city')).toBe('varchar(100)');
160
+ expect(typeOf('members', 'postalCode')).toBe('varchar(36)');
161
+ expect(typeOf('members', 'birthDate')).toBe('date');
162
+ expect(typeOf('registration_periods', 'cutoffAt')).toBe('datetime');
163
+ // Both replaced by the per-period cutoff: a settled year is protected by freezing it, not by
164
+ // a validity window on every row.
165
+ expect(typeOf('members', 'includeSince')).toBeUndefined();
166
+ expect(typeOf('members', 'excludeSince')).toBeUndefined();
167
+ // Netwerk membership is a fact of a period, so a settled year keeps the one it was recorded with.
168
+ expect(typeOf('_organizations_organization_tags', 'periodId')).toBe('varchar(36)');
169
+ });
170
+
171
+ /**
172
+ * `locked` is copied from the administration and says what it holds now; `lockedAt` says the sync
173
+ * has acted on it. Both are needed: the row keeps following the administration while the period is
174
+ * locked, which is the only way an unlock reaches this database.
175
+ */
176
+ it('records when a locked period stopped being followed, next to the lock itself', async () => {
177
+ const columns = await getColumns();
178
+ const periodColumn = (columnName: string) => columns.find(column => column.tableName === 'registration_periods' && column.columnName === columnName)?.dataType;
179
+
180
+ expect(periodColumn('locked')).toBe('tinyint');
181
+ expect(periodColumn('lockedAt')).toBe('datetime');
182
+ });
183
+
184
+ it('holds no personally identifiable information in any table', async () => {
185
+ const offending = (await getColumns()).filter((column) => {
186
+ if (allowedPersonalDataColumns.has(`${column.tableName}.${column.columnName}`)) {
187
+ return false;
188
+ }
189
+ const name = column.columnName.toLowerCase();
190
+ return personalDataColumns.some(forbidden => name.includes(forbidden));
191
+ });
192
+
193
+ expect(offending).toEqual([]);
194
+ });
195
+ });
196
+
197
+ describe('migration.postal-code-coordinates', () => {
198
+ async function getPostalCodes(): Promise<{ postalCode: string; latitude: number; longitude: number }[]> {
199
+ // Its own connection: the main database has a `postal_codes` table of its own, which is what
200
+ // the shared one would reach.
201
+ const [rows] = await getStatisticsConnection().select(
202
+ 'SELECT `postalCode`, `latitude` + 0E0 AS `latitude`, `longitude` + 0E0 AS `longitude` FROM `postal_codes`',
203
+ [],
204
+ { nestTables: false },
205
+ );
206
+ return rows as unknown as { postalCode: string; latitude: number; longitude: number }[];
207
+ }
208
+
209
+ it('loads a point for every Belgian postal code', async () => {
210
+ const rows = await getPostalCodes();
211
+
212
+ // Belgian postal codes run from 1000 to 9992. A handful are missing from any published list
213
+ // and the count shifts when bpost adds one, so this only guards against a partly loaded table.
214
+ expect(rows.length).toBeGreaterThan(1100);
215
+ expect(rows.every(row => /^\d{4}$/.test(row.postalCode))).toBe(true);
216
+ expect(new Set(rows.map(row => row.postalCode)).size).toBe(rows.length);
217
+ });
218
+
219
+ it('places every point inside Belgium', async () => {
220
+ const outside = (await getPostalCodes()).filter(row =>
221
+ row.latitude < 49.4 || row.latitude > 51.6 || row.longitude < 2.5 || row.longitude > 6.5);
222
+
223
+ expect(outside).toEqual([]);
224
+ });
225
+
226
+ it('puts the largest cities where they belong', async () => {
227
+ const byPostalCode = new Map((await getPostalCodes()).map(row => [row.postalCode, row]));
228
+
229
+ // Kilometres between the loaded point and where the city actually is. A postal code covers an
230
+ // area, so its centre is only ever near the city, not on it.
231
+ function distanceTo(postalCode: string, latitude: number, longitude: number): number {
232
+ const row = byPostalCode.get(postalCode);
233
+ if (!row) {
234
+ throw new Error(`Postal code ${postalCode} was not loaded`);
235
+ }
236
+ const north = (row.latitude - latitude) * 111;
237
+ const east = (row.longitude - longitude) * 111 * Math.cos((latitude * Math.PI) / 180);
238
+ return Math.sqrt(north * north + east * east);
239
+ }
240
+
241
+ expect(distanceTo('1000', 50.85, 4.35)).toBeLessThan(5);
242
+ expect(distanceTo('2000', 51.22, 4.40)).toBeLessThan(5);
243
+ expect(distanceTo('9000', 51.05, 3.72)).toBeLessThan(5);
244
+ expect(distanceTo('8000', 51.21, 3.22)).toBeLessThan(5);
245
+ expect(distanceTo('3500', 50.93, 5.34)).toBeLessThan(5);
246
+ expect(distanceTo('4000', 50.63, 5.57)).toBeLessThan(5);
247
+ expect(distanceTo('5000', 50.46, 4.87)).toBeLessThan(5);
248
+ expect(distanceTo('6000', 50.41, 4.44)).toBeLessThan(5);
249
+ });
250
+ });
package/src/schema.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { DatabaseInstance, Migration } from '@simonbackx/simple-database';
2
+ import path from 'node:path';
3
+ import { getStatisticsConnection, getStatisticsDatabaseConfig, getStatisticsPoolOptions } from './database.js';
4
+
5
+ export function getStatisticsMigrationsPath(): string {
6
+ return path.join(import.meta.dirname, 'migrations');
7
+ }
8
+
9
+ /**
10
+ * Run the migrations of the platform statistics database.
11
+ *
12
+ * That database keeps its own migration history, in its own `migrations` table, so it can be moved
13
+ * to another server without dragging the main database along.
14
+ */
15
+ export async function runStatisticsMigrations(): Promise<void> {
16
+ const database = getStatisticsDatabaseConfig().DB_DATABASE;
17
+ const globalDatabase = new DatabaseInstance({ ...getStatisticsPoolOptions(), database: null });
18
+
19
+ try {
20
+ await globalDatabase.statement(`CREATE DATABASE IF NOT EXISTS ${globalDatabase.escapeId(database)} DEFAULT CHARACTER SET = \`utf8mb4\` DEFAULT COLLATE = \`utf8mb4_0900_ai_ci\``);
21
+ } finally {
22
+ await globalDatabase.end();
23
+ }
24
+
25
+ if (!await Migration.runAll(getStatisticsMigrationsPath(), { database: getStatisticsConnection() })) {
26
+ throw new Error('Platform statistics migrations failed');
27
+ }
28
+ }
package/src/sources.ts ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Which pipeline wrote a statistics row.
3
+ *
4
+ * The reconciliation checks statistics rows against the main database, so it has to know which rows
5
+ * came from there: imported rows have no counterpart to find and would all be excluded on the first
6
+ * night.
7
+ */
8
+ export const syncSource = 'sync';
9
+ export const importSource = 'import';
@@ -0,0 +1,36 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { nextWatermark } from './sync-state.js';
3
+
4
+ describe('nextWatermark', () => {
5
+ const runStartedAt = new Date(2026, 7, 6, 12, 0, 0);
6
+
7
+ it('advances to the highest updatedAt it saw', () => {
8
+ const seen = [new Date(2026, 7, 1), new Date(2026, 7, 5), new Date(2026, 7, 3)];
9
+
10
+ expect(nextWatermark(new Date(2026, 6, 1), seen, runStartedAt)).toEqual(new Date(2026, 7, 5));
11
+ });
12
+
13
+ it('keeps the previous watermark when nothing changed', () => {
14
+ const previous = new Date(2026, 6, 1);
15
+
16
+ expect(nextWatermark(previous, [], runStartedAt)).toEqual(previous);
17
+ });
18
+
19
+ it('starts from nothing on a first run', () => {
20
+ expect(nextWatermark(null, [], runStartedAt)).toBeNull();
21
+ });
22
+
23
+ /**
24
+ * Registration periods carry an updatedAt in the future. Following one would put the watermark
25
+ * weeks ahead and silently skip everything written until the clock caught up.
26
+ */
27
+ it('never moves past the start of the run, even when a source row is dated in the future', () => {
28
+ const seen = [new Date(2026, 7, 5), new Date(2026, 8, 31)];
29
+
30
+ expect(nextWatermark(null, seen, runStartedAt)).toEqual(runStartedAt);
31
+ });
32
+
33
+ it('repairs a watermark an earlier run already pushed into the future', () => {
34
+ expect(nextWatermark(new Date(2026, 8, 31), [], runStartedAt)).toEqual(runStartedAt);
35
+ });
36
+ });