@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.
@@ -0,0 +1,55 @@
1
+ import { getStatisticsConnection } from './database.js';
2
+
3
+ export const syncStateTable = 'stats_sync_state';
4
+
5
+ export type SyncState = {
6
+ tableName: string;
7
+ watermark: Date | null;
8
+ lastSucceededAt: Date | null;
9
+ lastReconciledAt: Date | null;
10
+ };
11
+
12
+ /**
13
+ * The watermark to store after a run: the highest `updatedAt` that was seen, but never beyond the
14
+ * moment the run started.
15
+ *
16
+ * Source rows can carry an `updatedAt` in the future — periods in this database do. Following one
17
+ * would park the watermark weeks ahead, and every row written in the meantime would fall below it and
18
+ * be skipped. Capping costs one row that is read again on every run until the clock catches up, and
19
+ * repairs a watermark that a previous run already pushed into the future.
20
+ */
21
+ export function nextWatermark(previous: Date | null, seen: Date[], runStartedAt: Date): Date | null {
22
+ let watermark = previous;
23
+
24
+ for (const date of seen) {
25
+ if (!watermark || date > watermark) {
26
+ watermark = date;
27
+ }
28
+ }
29
+
30
+ return watermark && watermark > runStartedAt ? runStartedAt : watermark;
31
+ }
32
+
33
+ export async function readSyncState(tableName: string): Promise<SyncState> {
34
+ const connection = getStatisticsConnection();
35
+ const [rows] = await connection.select(
36
+ `SELECT \`tableName\`, \`watermark\`, \`lastSucceededAt\`, \`lastReconciledAt\` FROM ${connection.escapeId(syncStateTable)} WHERE \`tableName\` = ?`,
37
+ [tableName],
38
+ { nestTables: false },
39
+ );
40
+ const row = (rows as unknown as SyncState[])[0];
41
+
42
+ return row ?? { tableName, watermark: null, lastSucceededAt: null, lastReconciledAt: null };
43
+ }
44
+
45
+ export async function writeSyncState(tableName: string, state: Partial<Omit<SyncState, 'tableName'>>): Promise<void> {
46
+ const connection = getStatisticsConnection();
47
+ const columns = ['tableName', 'updatedAt', ...Object.keys(state)];
48
+ const values = [tableName, new Date(), ...Object.values(state)];
49
+ const assignments = columns.filter(column => column !== 'tableName').map(column => `${connection.escapeId(column)} = new.${connection.escapeId(column)}`);
50
+
51
+ await connection.insert(
52
+ `INSERT INTO ${connection.escapeId(syncStateTable)} (${columns.map(column => connection.escapeId(column)).join(', ')}) VALUES (?) AS new ON DUPLICATE KEY UPDATE ${assignments.join(', ')}`,
53
+ [values],
54
+ );
55
+ }
@@ -0,0 +1,544 @@
1
+ import type { Organization, Registration, RegistrationPeriod } from '@stamhoofd/models';
2
+ import { GroupFactory, Member, MemberFactory, MemberPlatformMembership, OrganizationFactory, OrganizationTagFactory, Platform, RegistrationFactory, RegistrationPeriodFactory } from '@stamhoofd/models';
3
+ import { BooleanStatus, DefaultAgeGroup, FinancialSupportSettings, Gender, PlatformMembershipType } from '@stamhoofd/structures';
4
+ import { getStatisticsConnection } from './database.js';
5
+ import { runStatisticsCycle, syncStatistics, syncStatisticsDeletes } from './sync.js';
6
+ import { readSyncState } from './sync-state.js';
7
+
8
+ async function statisticsRows(table: string, id?: string): Promise<Record<string, any>[]> {
9
+ const connection = getStatisticsConnection();
10
+ const [rows] = await connection.select(
11
+ `SELECT * FROM ${connection.escapeId(table)}` + (id ? ' WHERE `id` = ?' : ''),
12
+ id ? [id] : [],
13
+ { nestTables: false },
14
+ );
15
+ return rows as unknown as Record<string, any>[];
16
+ }
17
+
18
+ describe('statistics sync', () => {
19
+ let organization: Organization;
20
+ let member: Member;
21
+ let registration: Registration;
22
+ let period: RegistrationPeriod;
23
+ let ageGroup: DefaultAgeGroup;
24
+
25
+ beforeAll(async () => {
26
+ // A tak on the platform, so there is a piece of configuration for the reports to group by.
27
+ const platform = await Platform.getForEditing();
28
+ ageGroup = DefaultAgeGroup.create({ names: ['Welpen'], minAge: 7, maxAge: 10 });
29
+ platform.config.defaultAgeGroups = [ageGroup];
30
+ await platform.save();
31
+ await Platform.clearCache();
32
+
33
+ period = await new RegistrationPeriodFactory({}).create();
34
+ organization = await new OrganizationFactory({ period }).create();
35
+ const group = await new GroupFactory({ organization }).create();
36
+ member = await new MemberFactory({ organization, birthDay: { year: 2011, month: 5, day: 17 } }).create();
37
+ registration = await new RegistrationFactory({ member, group }).create();
38
+
39
+ await syncStatistics();
40
+ });
41
+
42
+ it('copies a member without any of its personal data', async () => {
43
+ const [row] = await statisticsRows('members', member.id);
44
+
45
+ expect(row).toBeDefined();
46
+ expect(row.birthDate).toEqual(new Date(Date.UTC(2011, 4, 17)));
47
+ expect(Object.keys(row).sort()).toEqual(['birthDate', 'createdAt', 'gender', 'id', 'lastRegisteredAt', 'organizationId', 'periodId', 'postalCode', 'source', 'updatedAt']);
48
+ expect(JSON.stringify(row)).not.toContain(member.details.firstName);
49
+ });
50
+
51
+ it('writes the member against the period their registration is in', async () => {
52
+ const rows = await statisticsRows('members', member.id);
53
+
54
+ expect(rows.map(row => row.periodId)).toContain(registration.periodId);
55
+ });
56
+
57
+ it('writes no member row for a member without a registration, since nothing counts one', async () => {
58
+ const orphan = await new MemberFactory({ organization }).create();
59
+
60
+ await syncStatistics();
61
+
62
+ expect(await statisticsRows('members', orphan.id)).toHaveLength(0);
63
+ });
64
+
65
+ it('copies the registration, so a member can hold several', async () => {
66
+ const [row] = await statisticsRows('registrations', registration.id);
67
+
68
+ expect(row).toBeDefined();
69
+ expect(row.memberId).toBe(member.id);
70
+ expect(row.groupId).toBe(registration.groupId);
71
+ });
72
+
73
+ it('copies the organization with only its postal code', async () => {
74
+ const [row] = await statisticsRows('organizations', organization.id);
75
+
76
+ expect(row).toBeDefined();
77
+ expect(row.name).toBe(organization.name);
78
+ expect(row.postalCode).toBe(organization.address.postalCode);
79
+ expect(row.city).toBe(organization.address.city);
80
+ expect(JSON.stringify(row)).not.toContain(organization.address.street);
81
+ });
82
+
83
+ /**
84
+ * The koepel's own organization, which the jeugdbewegingen report delivers as the bovenlokale
85
+ * ondersteuningsstructuur. Nothing else in the administration tells that organization apart from
86
+ * a local group, so the pointer on the platform record is what the report has to read.
87
+ */
88
+ it('writes the platform with the organization it runs itself', async () => {
89
+ const platform = await Platform.getForEditing();
90
+ platform.membershipOrganizationId = organization.id;
91
+ await platform.save();
92
+ await Platform.clearCache();
93
+
94
+ await syncStatistics();
95
+
96
+ const [row] = await statisticsRows('platform', platform.id);
97
+ expect(row).toBeDefined();
98
+ expect(row.name).toBe(platform.config.name);
99
+ expect(row.membershipOrganizationId).toBe(organization.id);
100
+ });
101
+
102
+ /**
103
+ * What a tak counts as -- kinderen, leiding or volwassenen -- is not in this database at all. The
104
+ * platform configuration has no such field and the ages do not answer it, so the reports name
105
+ * their takken by id themselves, in `report/includes/<env>/tak-categorie.sql`.
106
+ */
107
+ it('records no category for a tak, which the reports decide themselves', async () => {
108
+ const columns = Object.keys((await statisticsRows('default_age_groups', ageGroup.id))[0]);
109
+
110
+ expect(columns).not.toContain('category');
111
+ });
112
+
113
+ /**
114
+ * A tak with several names has them joined by the structure with a translated separator. This
115
+ * service loads no locales, so reading that getter writes the translation key into the database
116
+ * instead of the word.
117
+ */
118
+ it('writes a tak with several names as words, not as a translation key', async () => {
119
+ const platform = await Platform.getForEditing();
120
+ const combined = DefaultAgeGroup.create({ names: ['Kapoenen', 'Welpen'], minAge: 6, maxAge: 10 });
121
+ platform.config.defaultAgeGroups = [...platform.config.defaultAgeGroups, combined];
122
+ await platform.save();
123
+ await Platform.clearCache();
124
+
125
+ await syncStatistics();
126
+
127
+ const rows = await statisticsRows('default_age_groups', combined.id);
128
+ expect(rows.length).toBeGreaterThan(0);
129
+ for (const row of rows) {
130
+ expect(row.name).toBe('Kapoenen of Welpen');
131
+ }
132
+ });
133
+
134
+ /**
135
+ * The platform configuration holds one name per tak, netwerk, lidgeldtype and functie and no
136
+ * history at all, so the name it carries now is written against each year still open.
137
+ */
138
+ it('writes the platform configuration against every period that is still open', async () => {
139
+ const now = new Date();
140
+ const periods = await statisticsRows('registration_periods');
141
+ const open = new Set(periods.filter(row => (row.cutoffAt === null || row.cutoffAt > now) && row.lockedAt === null).map(row => row.id));
142
+ const written = new Set((await statisticsRows('default_age_groups', ageGroup.id)).map(row => row.periodId));
143
+
144
+ expect(open.size).toBeGreaterThan(0);
145
+ expect([...open].filter(periodId => !written.has(periodId))).toEqual([]);
146
+ });
147
+
148
+ it('records a watermark it can resume from', async () => {
149
+ const state = await readSyncState('members');
150
+
151
+ expect(state.watermark).toBeInstanceOf(Date);
152
+ expect(state.lastSucceededAt).toBeInstanceOf(Date);
153
+ });
154
+
155
+ it('picks up an update to a row it already synced', async () => {
156
+ member.details.birthDay = new Date(2009, 2, 3);
157
+ await member.save();
158
+
159
+ await syncStatistics();
160
+
161
+ expect((await statisticsRows('members', member.id))[0].birthDate).toEqual(new Date(Date.UTC(2009, 2, 3)));
162
+ });
163
+
164
+ it('writes the same rows again without complaining, so a repeated run is harmless', async () => {
165
+ await syncStatistics();
166
+ await syncStatistics();
167
+
168
+ expect(await statisticsRows('members', member.id)).toHaveLength(1);
169
+ expect(await statisticsRows('registrations', registration.id)).toHaveLength(1);
170
+ });
171
+
172
+ it('marks every row it writes as its own', async () => {
173
+ expect((await statisticsRows('members', member.id))[0].source).toBe('sync');
174
+ });
175
+
176
+ it('removes a row of a live period once its source row is gone', async () => {
177
+ const deletedId = registration.id;
178
+ await registration.delete();
179
+
180
+ // An incremental pass has nothing to notice: the row is simply gone from the source.
181
+ await syncStatistics();
182
+ expect(await statisticsRows('registrations', deletedId)).toHaveLength(1);
183
+
184
+ await syncStatisticsDeletes();
185
+
186
+ expect(await statisticsRows('registrations', deletedId)).toHaveLength(0);
187
+ });
188
+
189
+ it('keeps a member whose source row is gone, because deleting one cascades into settled years', async () => {
190
+ const orphan = await new MemberFactory({ organization }).create();
191
+ await new RegistrationFactory({ member: orphan, group: await new GroupFactory({ organization }).create() }).create();
192
+ await syncStatistics();
193
+ await orphan.delete();
194
+
195
+ await syncStatisticsDeletes();
196
+
197
+ expect(await statisticsRows('members', orphan.id)).toHaveLength(1);
198
+ });
199
+
200
+ /**
201
+ * Organizations, groups and registrations all point at a period with ON DELETE RESTRICT, so
202
+ * removing one is either refused outright or takes a settled year's numbers with it.
203
+ */
204
+ it('keeps a period whose source row is gone, since every figure hangs off it', async () => {
205
+ const orphan = await new RegistrationPeriodFactory({}).create();
206
+ await syncStatistics();
207
+ await orphan.delete();
208
+
209
+ await syncStatisticsDeletes();
210
+
211
+ expect(await statisticsRows('registration_periods', orphan.id)).toHaveLength(1);
212
+ });
213
+
214
+ describe('a frozen period', () => {
215
+ let frozenPeriod: RegistrationPeriod;
216
+ let frozenRegistration: Registration;
217
+ let settledMember: Member;
218
+
219
+ beforeAll(async () => {
220
+ frozenPeriod = await new RegistrationPeriodFactory({}).create();
221
+ const group = await new GroupFactory({ organization }).create();
222
+ group.periodId = frozenPeriod.id;
223
+ await group.save();
224
+ frozenRegistration = await new RegistrationFactory({ member, group }).create();
225
+ frozenRegistration.periodId = frozenPeriod.id;
226
+ await frozenRegistration.save();
227
+
228
+ // Someone registered in both the year about to settle and the one still running.
229
+ settledMember = await new MemberFactory({ organization }).create();
230
+ settledMember.details.gender = Gender.Female;
231
+ await settledMember.save();
232
+ await new RegistrationFactory({ member: settledMember, group }).create();
233
+ await new RegistrationFactory({ member: settledMember, group: await new GroupFactory({ organization }).create() }).create();
234
+
235
+ await syncStatistics();
236
+ // Settle the period, as an operator would once its numbers are final.
237
+ await getStatisticsConnection().update('UPDATE `registration_periods` SET `cutoffAt` = ? WHERE `id` = ?', [new Date(Date.now() - 1000), frozenPeriod.id]);
238
+ });
239
+
240
+ /**
241
+ * The whole reason a member is recorded per period: their details are what they are now, and
242
+ * a settled year has to keep the ones it was counted with.
243
+ */
244
+ it('keeps the member as they were counted, while the year still running follows the source', async () => {
245
+ const genderPerPeriod = async () => Object.fromEntries((await statisticsRows('members', settledMember.id)).map(row => [row.periodId, row.gender]));
246
+ const before = await genderPerPeriod();
247
+
248
+ settledMember.details.gender = Gender.Male;
249
+ await settledMember.save();
250
+ await syncStatistics();
251
+
252
+ const after = await genderPerPeriod();
253
+ expect(before[frozenPeriod.id]).toBe(Gender.Female);
254
+ expect(after[frozenPeriod.id]).toBe(Gender.Female);
255
+ expect(after[organization.periodId]).toBe(Gender.Male);
256
+ });
257
+
258
+ /**
259
+ * The same rule as for the member, applied to the two things the source keeps no history for
260
+ * at all: a unit's own name, and a tak's name from the platform configuration.
261
+ */
262
+ it('keeps the unit and the tak named as they were counted, while the year still running follows the source', async () => {
263
+ const nameOf = async (table: string, id: string) =>
264
+ Object.fromEntries((await statisticsRows(table, id)).map(row => [row.periodId, row.name]));
265
+
266
+ const ageGroupId = ageGroup.id;
267
+ const before = { unit: await nameOf('organizations', organization.id), tak: await nameOf('default_age_groups', ageGroupId) };
268
+
269
+ organization.name = 'Hernoemde eenheid';
270
+ await organization.save();
271
+
272
+ const platform = await Platform.getForEditing();
273
+ platform.config.defaultAgeGroups.find(group => group.id === ageGroupId)!.names = ['Hernoemde tak'];
274
+ await platform.save();
275
+ await Platform.clearCache();
276
+
277
+ await syncStatistics();
278
+
279
+ const after = { unit: await nameOf('organizations', organization.id), tak: await nameOf('default_age_groups', ageGroupId) };
280
+ expect(after.unit[frozenPeriod.id]).toBe(before.unit[frozenPeriod.id]);
281
+ expect(after.tak[frozenPeriod.id]).toBe(before.tak[frozenPeriod.id]);
282
+ expect(after.unit[organization.periodId]).toBe('Hernoemde eenheid');
283
+ expect(after.tak[organization.periodId]).toBe('Hernoemde tak');
284
+ });
285
+
286
+ it('is not rewritten by the sync when the source changes', async () => {
287
+ frozenRegistration.deactivatedAt = new Date(2025, 0, 15);
288
+ await frozenRegistration.save();
289
+ await syncStatistics();
290
+
291
+ expect((await statisticsRows('registrations', frozenRegistration.id))[0].deactivatedAt).toBeNull();
292
+ });
293
+
294
+ it('keeps its rows when the source is deleted, so the settled numbers stay', async () => {
295
+ await frozenRegistration.delete();
296
+
297
+ await syncStatistics();
298
+ await syncStatisticsDeletes();
299
+
300
+ expect(await statisticsRows('registrations', frozenRegistration.id)).toHaveLength(1);
301
+ });
302
+ });
303
+
304
+ /**
305
+ * Locking a period in the administration says its year is done. The sync keeps writing it for one
306
+ * more run -- the changes and the deletions of the day it was locked have to land somewhere -- and
307
+ * leaves it alone from the run after that.
308
+ */
309
+ describe('a period the administration locked', () => {
310
+ const day = 24 * 60 * 60 * 1000;
311
+
312
+ async function periodRow(period: RegistrationPeriod): Promise<Record<string, any>> {
313
+ return (await statisticsRows('registration_periods', period.id))[0];
314
+ }
315
+
316
+ /**
317
+ * A year with a registration in it, synced and then locked: the state the sync finds on the
318
+ * night it first sees the lock. Ends in a month unless told otherwise, so unlocking it again
319
+ * falls inside the window that reopens a period.
320
+ */
321
+ async function lockedYear(endDate = new Date(Date.now() + 30 * day)): Promise<{ period: RegistrationPeriod; registration: Registration }> {
322
+ const period = await new RegistrationPeriodFactory({ startDate: new Date(endDate.getTime() - 365 * day), endDate }).create();
323
+ const group = await new GroupFactory({ organization }).create();
324
+ group.periodId = period.id;
325
+ await group.save();
326
+ const registration = await new RegistrationFactory({ member, group }).create();
327
+ registration.periodId = period.id;
328
+ await registration.save();
329
+
330
+ await runStatisticsCycle();
331
+
332
+ period.locked = true;
333
+ await period.save();
334
+
335
+ return { period, registration };
336
+ }
337
+
338
+ async function deactivate(registration: Registration, at: Date | null): Promise<void> {
339
+ registration.deactivatedAt = at;
340
+ await registration.save();
341
+ }
342
+
343
+ async function deactivatedAt(registration: Registration): Promise<Date | null> {
344
+ return (await statisticsRows('registrations', registration.id))[0].deactivatedAt;
345
+ }
346
+
347
+ it('still writes what changed on the day it was locked', async () => {
348
+ const { period, registration } = await lockedYear();
349
+ const changed = new Date(2025, 5, 1);
350
+
351
+ await deactivate(registration, changed);
352
+ await runStatisticsCycle();
353
+
354
+ expect(await deactivatedAt(registration)).toEqual(changed);
355
+ expect((await periodRow(period)).lockedAt).toBeInstanceOf(Date);
356
+ });
357
+
358
+ /**
359
+ * Deletes are noticed by the reconciliation and nothing else, so a registration removed on the
360
+ * day of the lock is only taken out if that pass runs before the period is settled.
361
+ */
362
+ it('still removes what was deleted on the day it was locked', async () => {
363
+ const { registration } = await lockedYear();
364
+ const deletedId = registration.id;
365
+
366
+ await registration.delete();
367
+ await runStatisticsCycle();
368
+
369
+ expect(await statisticsRows('registrations', deletedId)).toHaveLength(0);
370
+ });
371
+
372
+ it('is left alone from the run after that', async () => {
373
+ const { registration } = await lockedYear();
374
+ await runStatisticsCycle();
375
+
376
+ await deactivate(registration, new Date(2025, 5, 2));
377
+ await runStatisticsCycle();
378
+
379
+ expect(await deactivatedAt(registration)).toBeNull();
380
+ });
381
+
382
+ /**
383
+ * A run that threw never settles the period, so the night it was locked is repeated until one
384
+ * comes through in full rather than skipped.
385
+ */
386
+ it('is written again by the next run when a run did not come through', async () => {
387
+ const { period, registration } = await lockedYear();
388
+ const changed = new Date(2025, 5, 3);
389
+
390
+ // The incremental pass came through and the reconciliation after it threw.
391
+ await syncStatistics();
392
+ expect((await periodRow(period)).lockedAt).toBeNull();
393
+
394
+ await deactivate(registration, changed);
395
+ await runStatisticsCycle();
396
+
397
+ expect(await deactivatedAt(registration)).toEqual(changed);
398
+ expect((await periodRow(period)).lockedAt).toBeInstanceOf(Date);
399
+ });
400
+
401
+ it('is followed again from the same run it is unlocked in', async () => {
402
+ const { period, registration } = await lockedYear();
403
+ await runStatisticsCycle();
404
+ const changed = new Date(2025, 5, 4);
405
+
406
+ period.locked = false;
407
+ await period.save();
408
+ await deactivate(registration, changed);
409
+ await runStatisticsCycle();
410
+
411
+ expect(await deactivatedAt(registration)).toEqual(changed);
412
+ expect((await periodRow(period)).lockedAt).toBeNull();
413
+ expect((await periodRow(period)).locked).toBe(0);
414
+ });
415
+
416
+ /**
417
+ * Unlocking a year that is long over is not a correction to make in the reports: what its rows
418
+ * would be written from is the administration of today, which no longer describes that year.
419
+ */
420
+ it('stays settled when a year that ended long ago is unlocked', async () => {
421
+ const { period, registration } = await lockedYear(new Date(Date.now() - 2 * 365 * day));
422
+ await runStatisticsCycle();
423
+
424
+ period.locked = false;
425
+ await period.save();
426
+ await deactivate(registration, new Date(2025, 5, 5));
427
+ await runStatisticsCycle();
428
+
429
+ expect(await deactivatedAt(registration)).toBeNull();
430
+ expect((await periodRow(period)).lockedAt).toBeInstanceOf(Date);
431
+ });
432
+ });
433
+
434
+ describe('netwerk membership', () => {
435
+ it('is recorded against the period the organization is in', async () => {
436
+ const tag = await new OrganizationTagFactory({}).create();
437
+ organization.meta.tags = [tag.id];
438
+ await organization.save();
439
+
440
+ await syncStatistics();
441
+
442
+ const links = await statisticsRows('_organizations_organization_tags');
443
+ const link = links.find(row => row.organizationsId === organization.id && row.organizationTagsId === tag.id);
444
+ expect(link).toBeDefined();
445
+ expect(link!.periodId).toBe(organization.periodId);
446
+ });
447
+
448
+ it('leaves the netwerk of a settled year alone when the organization moves', async () => {
449
+ const settledPeriod = await new RegistrationPeriodFactory({}).create();
450
+ const tag = await new OrganizationTagFactory({}).create();
451
+ const connection = getStatisticsConnection();
452
+
453
+ // Get the period and the tag into the statistics database first: the link points at both.
454
+ await syncStatistics();
455
+
456
+ // A link as it was recorded while that year was still live, then the year is settled.
457
+ await connection.insert(
458
+ 'INSERT INTO `_organizations_organization_tags` (`organizationsId`, `organizationTagsId`, `periodId`, `source`) VALUES (?, ?, ?, ?)',
459
+ [organization.id, tag.id, settledPeriod.id, 'sync'],
460
+ );
461
+ await connection.update('UPDATE `registration_periods` SET `cutoffAt` = ? WHERE `id` = ?', [new Date(Date.now() - 1000), settledPeriod.id]);
462
+
463
+ // The organization moves to another netwerk entirely.
464
+ const moved = await new OrganizationTagFactory({}).create();
465
+ organization.meta.tags = [moved.id];
466
+ await organization.save();
467
+ await syncStatistics();
468
+
469
+ const links = await statisticsRows('_organizations_organization_tags');
470
+ expect(links.some(row => row.periodId === settledPeriod.id && row.organizationTagsId === tag.id)).toBe(true);
471
+ expect(links.some(row => row.periodId === organization.periodId && row.organizationTagsId === moved.id)).toBe(true);
472
+ });
473
+ });
474
+
475
+ /**
476
+ * Which tarief a lidgeld was charged at is what the reports split the lidgelden by, and nothing in
477
+ * the administration records it per lidgeld: the price is worked out from whether the member has
478
+ * financiële ondersteuning or an active UITPAS, and only the amount is kept. The sync reads that
479
+ * same status off the member, so a lidgeld carries the tarief it was made at.
480
+ */
481
+ describe('the tarief of a lidgeld', () => {
482
+ async function membershipOf(member: Member, type: PlatformMembershipType): Promise<MemberPlatformMembership> {
483
+ const membership = new MemberPlatformMembership();
484
+ membership.memberId = member.id;
485
+ membership.membershipTypeId = type.id;
486
+ membership.organizationId = organization.id;
487
+ membership.periodId = period.id;
488
+ membership.startDate = period.startDate;
489
+ membership.endDate = period.endDate;
490
+ await membership.save();
491
+ return membership;
492
+ }
493
+
494
+ it('marks the lidgeld of a member with financiële ondersteuning as the verlaagd tarief', async () => {
495
+ const type = PlatformMembershipType.create({ name: 'Volledig scoutsjaar' });
496
+ const platform = await Platform.getForEditing();
497
+ platform.config.membershipTypes = [type];
498
+ platform.config.financialSupport = FinancialSupportSettings.create({ priceName: 'SOMkort' });
499
+ await platform.save();
500
+ await Platform.clearCache();
501
+
502
+ const supported = await new MemberFactory({ organization }).create();
503
+ supported.details.requiresFinancialSupport = BooleanStatus.create({ value: true });
504
+ await supported.save();
505
+
506
+ const standard = await membershipOf(member, type);
507
+ const reduced = await membershipOf(supported, type);
508
+
509
+ await syncStatistics();
510
+
511
+ expect((await statisticsRows('member_platform_memberships', standard.id))[0].reducedPrice).toBe(0);
512
+ expect((await statisticsRows('member_platform_memberships', reduced.id))[0].reducedPrice).toBe(1);
513
+ });
514
+
515
+ /**
516
+ * The name of that tarief is the koepel's own -- SOMkort, kansentarief -- so the reports print
517
+ * what the platform calls it instead of a wording of their own.
518
+ */
519
+ it('writes what the platform calls its verlaagd tarief', async () => {
520
+ const platform = await Platform.getForEditing();
521
+ platform.config.financialSupport = FinancialSupportSettings.create({ priceName: 'SOMkort' });
522
+ await platform.save();
523
+ await Platform.clearCache();
524
+
525
+ await syncStatistics();
526
+
527
+ expect((await statisticsRows('platform', platform.id))[0].reducedPriceName).toBe('SOMkort');
528
+ });
529
+ });
530
+
531
+ it('never deletes rows that came from an import, which have no source row to check against', async () => {
532
+ const connection = getStatisticsConnection();
533
+ // The statistics database is kept between runs, so start from a known state.
534
+ await connection.delete('DELETE FROM `members` WHERE `id` = ?', ['imported-member-1']);
535
+ await connection.insert(
536
+ 'INSERT INTO `members` (`id`, `periodId`, `birthDate`, `gender`, `createdAt`, `updatedAt`, `source`) VALUES (?, ?, ?, ?, ?, ?, ?)',
537
+ ['imported-member-1', period.id, new Date(Date.UTC(2004, 0, 15)), 'Female', new Date(), new Date(), 'import'],
538
+ );
539
+
540
+ await syncStatisticsDeletes();
541
+
542
+ expect(await statisticsRows('members', 'imported-member-1')).toHaveLength(1);
543
+ });
544
+ });