@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,39 @@
1
+ import { TestUtils } from '@stamhoofd/test-utils';
2
+ import { getImportedUntil, isFrozen } from './periods.js';
3
+
4
+ describe('getImportedUntil', () => {
5
+ it('reads the boundary of a platform that has external history', () => {
6
+ TestUtils.setEnvironment('IMPORTED_UNTIL', '2024-09-01');
7
+
8
+ expect(getImportedUntil()).toEqual(new Date('2024-09-01'));
9
+ });
10
+
11
+ it('has no boundary for a platform without external history, so nothing is frozen up front', () => {
12
+ TestUtils.setEnvironment('IMPORTED_UNTIL', undefined);
13
+
14
+ expect(getImportedUntil()).toBeNull();
15
+ });
16
+
17
+ it('refuses a boundary it cannot read rather than silently freezing nothing', () => {
18
+ TestUtils.setEnvironment('IMPORTED_UNTIL', 'last september');
19
+
20
+ expect(() => getImportedUntil()).toThrow('not a valid date');
21
+ });
22
+ });
23
+
24
+ describe('isFrozen', () => {
25
+ const frozen = new Set(['period-2023']);
26
+
27
+ it('freezes a row of a settled period', () => {
28
+ expect(isFrozen(frozen, 'period-2023')).toBe(true);
29
+ });
30
+
31
+ it('leaves a row of a live period alone', () => {
32
+ expect(isFrozen(frozen, 'period-2026')).toBe(false);
33
+ });
34
+
35
+ it('treats a row without a period as live, since it is part of no settled year', () => {
36
+ expect(isFrozen(frozen, null)).toBe(false);
37
+ expect(isFrozen(frozen, undefined)).toBe(false);
38
+ });
39
+ });
package/src/periods.ts ADDED
@@ -0,0 +1,112 @@
1
+ import { getStatisticsConnection } from './database.js';
2
+
3
+ /**
4
+ * The date up to which this platform's statistics come from an imported external source. Periods
5
+ * ending before it are frozen the first time the sync sees them, so the import owns those years.
6
+ * Unset means the platform has no external history and nothing is frozen up front.
7
+ */
8
+ export function getImportedUntil(): Date | null {
9
+ const configured = STAMHOOFD.IMPORTED_UNTIL;
10
+ if (!configured) {
11
+ return null;
12
+ }
13
+
14
+ const parsed = new Date(configured);
15
+ if (Number.isNaN(parsed.getTime())) {
16
+ throw new Error(`STAMHOOFD.IMPORTED_UNTIL is not a valid date: ${configured}`);
17
+ }
18
+
19
+ return parsed;
20
+ }
21
+
22
+ /**
23
+ * How long after a period ended unlocking it in the administration still brings it back into the
24
+ * sync. A period is unlocked to correct something, and beyond this an old year would have all of its
25
+ * numbers written again from what the administration says today rather than the one thing corrected.
26
+ */
27
+ export const releaseWindow = 365 * 24 * 60 * 60 * 1000;
28
+
29
+ /**
30
+ * Give periods that ended before the imported history a cutoff, once. Only ever fills a cutoff that
31
+ * is still empty, so a date set by hand afterwards stays put.
32
+ */
33
+ export async function applyImportedCutoff(importedUntil: Date | null): Promise<void> {
34
+ if (!importedUntil) {
35
+ return;
36
+ }
37
+
38
+ const connection = getStatisticsConnection();
39
+ await connection.update(
40
+ 'UPDATE `registration_periods` SET `cutoffAt` = ? WHERE `cutoffAt` IS NULL AND `endDate` < ?',
41
+ [importedUntil, importedUntil],
42
+ );
43
+ }
44
+
45
+ async function loadPeriodIds(where: string, params: unknown[]): Promise<Set<string>> {
46
+ const connection = getStatisticsConnection();
47
+ const [rows] = await connection.select(
48
+ `SELECT \`id\` FROM \`registration_periods\` WHERE ${where}`,
49
+ params,
50
+ { nestTables: false },
51
+ );
52
+
53
+ return new Set((rows as unknown as { id: string }[]).map(row => row.id));
54
+ }
55
+
56
+ const settledWhere = '`cutoffAt` IS NOT NULL AND `cutoffAt` <= ?';
57
+
58
+ /**
59
+ * The periods left alone entirely, their own row included: the years an import owns and the ones
60
+ * settled by hand. The sync never wrote those rows, so it does not rewrite them either.
61
+ */
62
+ export function loadSettledPeriodIds(): Promise<Set<string>> {
63
+ return loadPeriodIds(settledWhere, [new Date()]);
64
+ }
65
+
66
+ /**
67
+ * The periods whose statistics are settled. Rows belonging to them are left exactly as they are: not
68
+ * written by the sync, and not excluded by the reconciliation either.
69
+ *
70
+ * Either because their cutoff has passed, or because the administration locked them and a full run
71
+ * has carried in what happened up to that lock.
72
+ */
73
+ export function loadFrozenPeriodIds(): Promise<Set<string>> {
74
+ return loadPeriodIds(`(${settledWhere}) OR \`lockedAt\` IS NOT NULL`, [new Date()]);
75
+ }
76
+
77
+ /**
78
+ * Stop following the periods the administration has locked.
79
+ *
80
+ * Called once a whole run has come through, incremental pass and delete reconciliation both: the day
81
+ * a period is locked is a day like any other until then, and its changes and its deletions have to be
82
+ * written before it is settled. A run that failed never reaches this, so the next one reads that
83
+ * period again and settles it only once it succeeds.
84
+ */
85
+ export async function settleLockedPeriods(): Promise<void> {
86
+ const connection = getStatisticsConnection();
87
+ await connection.update(
88
+ 'UPDATE `registration_periods` SET `lockedAt` = ? WHERE `lockedAt` IS NULL AND `locked` = 1',
89
+ [new Date()],
90
+ );
91
+ }
92
+
93
+ /**
94
+ * Follow a period the administration unlocked again, as long as it ended less than `releaseWindow`
95
+ * ago. An older year keeps the numbers it was settled with: what its rows would be written from is
96
+ * the administration of today, which no longer describes that year.
97
+ */
98
+ export async function releaseUnlockedPeriods(): Promise<void> {
99
+ const connection = getStatisticsConnection();
100
+ await connection.update(
101
+ 'UPDATE `registration_periods` SET `lockedAt` = NULL WHERE `lockedAt` IS NOT NULL AND `locked` = 0 AND `endDate` > ?',
102
+ [new Date(Date.now() - releaseWindow)],
103
+ );
104
+ }
105
+
106
+ /**
107
+ * MySQL cannot be handed an empty IN list, and "belongs to no period" is never frozen: a row without
108
+ * a period is not part of any year's settled numbers.
109
+ */
110
+ export function isFrozen(frozenPeriodIds: Set<string>, periodId: string | null | undefined): boolean {
111
+ return typeof periodId === 'string' && frozenPeriodIds.has(periodId);
112
+ }
@@ -0,0 +1,237 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { flattenDefaultAgeGroup, flattenGroup, flattenMember, flattenMembership, flattenOrganization, flattenPlatform, flattenRegistration } from './rows.js';
3
+
4
+ describe('flattenMember', () => {
5
+ const member = {
6
+ id: 'member-1',
7
+ details: { birthDay: new Date(2011, 4, 17), gender: 'Female', address: { postalCode: '9000' } },
8
+ organizationId: 'org-1',
9
+ createdAt: new Date(2025, 0, 1),
10
+ updatedAt: new Date(2026, 0, 1),
11
+ lastRegisteredAt: new Date(2025, 8, 1),
12
+ };
13
+
14
+ it('carries the date of birth, which is what makes an age exact', () => {
15
+ expect(flattenMember(member, 'period-1').birthDate).toBe('2011-05-17');
16
+ });
17
+
18
+ /**
19
+ * A birth date is held as midnight in Europe/Brussels. Writing that instant into a date column
20
+ * from a process running in UTC would land on the day before.
21
+ */
22
+ it('writes the calendar date the application means, not the instant behind it', () => {
23
+ const brusselsMidnight = new Date('2011-05-16T22:00:00.000Z');
24
+
25
+ expect(flattenMember({ ...member, details: { ...member.details, birthDay: brusselsMidnight } }, 'period-1').birthDate).toBe('2011-05-17');
26
+ });
27
+
28
+ it('never carries a name or a way to contact the member', () => {
29
+ const row = flattenMember({ ...member, details: { ...member.details, firstName: 'Jan', lastName: 'Jansen', email: 'jan@example.com' } as any }, 'period-1');
30
+
31
+ expect(Object.keys(row).sort()).toEqual(['birthDate', 'createdAt', 'gender', 'id', 'lastRegisteredAt', 'organizationId', 'periodId', 'postalCode', 'updatedAt']);
32
+ expect(JSON.stringify(row)).not.toContain('Jan');
33
+ expect(JSON.stringify(row)).not.toContain('example.com');
34
+ });
35
+
36
+ /**
37
+ * The same member in two years is two rows, so that correcting a gender or moving house changes
38
+ * the year it happened in rather than every year the member was ever counted in.
39
+ */
40
+ it('describes the member in one period, which is part of what identifies the row', () => {
41
+ const first = flattenMember(member, 'period-1');
42
+ const second = flattenMember(member, 'period-2');
43
+
44
+ expect(first.periodId).toBe('period-1');
45
+ expect(second.periodId).toBe('period-2');
46
+ expect(first.id).toBe(second.id);
47
+ });
48
+
49
+ it('keeps a member without a birth date', () => {
50
+ expect(flattenMember({ ...member, details: { birthDay: null, gender: 'Other', address: null } }, 'period-1').birthDate).toBeNull();
51
+ });
52
+
53
+ it('keeps the postal code the member map needs, and nothing else of the address', () => {
54
+ const row = flattenMember({ ...member, details: { ...member.details, address: { postalCode: '9000', street: 'Somewhere', city: 'Gent' } as any } }, 'period-1');
55
+
56
+ expect(row.postalCode).toBe('9000');
57
+ expect(JSON.stringify(row)).not.toContain('Somewhere');
58
+ expect(JSON.stringify(row)).not.toContain('Gent');
59
+ });
60
+
61
+ it('has no postal code for a member without an address', () => {
62
+ expect(flattenMember({ ...member, details: { ...member.details, address: null } }, 'period-1').postalCode).toBeNull();
63
+ });
64
+ });
65
+
66
+ describe('flattenOrganization', () => {
67
+ const organization = {
68
+ id: 'org-1',
69
+ name: 'Scouts Test',
70
+ uri: 'scouts-test',
71
+ address: { postalCode: '9000', city: 'Gent', street: 'Somewhere' } as any,
72
+ periodId: 'period-1',
73
+ active: true,
74
+ createdAt: new Date(2025, 0, 1),
75
+ updatedAt: new Date(2026, 0, 1),
76
+ };
77
+
78
+ it('keeps the postal code the map needs and the city the ULDK table lists, and no more', () => {
79
+ const row = flattenOrganization(organization, 'period-1');
80
+
81
+ expect(row.postalCode).toBe('9000');
82
+ expect(row.city).toBe('Gent');
83
+ expect(Object.keys(row)).not.toContain('address');
84
+ expect(JSON.stringify(row)).not.toContain('Somewhere');
85
+ });
86
+
87
+ it('stores a missing postal code as null rather than an empty string', () => {
88
+ expect(flattenOrganization({ ...organization, address: { postalCode: '', city: '' } }, 'period-1').postalCode).toBeNull();
89
+ });
90
+
91
+ /**
92
+ * A unit that is renamed or moves keeps the name and the place it was counted under in the years
93
+ * already settled, so the year is what the row describes rather than the period it is in now.
94
+ */
95
+ it('describes the unit in one period, not the period the unit is in now', () => {
96
+ expect(flattenOrganization(organization, 'period-2').periodId).toBe('period-2');
97
+ });
98
+ });
99
+
100
+ describe('flattenPlatform', () => {
101
+ const platform = {
102
+ id: 'platform-1',
103
+ config: { name: 'Scouts en Gidsen Vlaanderen', financialSupport: { priceName: 'SOMkort' } },
104
+ membershipOrganizationId: 'org-1',
105
+ };
106
+
107
+ /**
108
+ * The organization the koepel runs itself is what the jeugdbewegingen report delivers as the
109
+ * bovenlokale ondersteuningsstructuur, and nothing else in the administration tells it apart from
110
+ * a local group.
111
+ */
112
+ it('keeps the name and the organization the platform runs itself', () => {
113
+ expect(flattenPlatform(platform)).toEqual({
114
+ id: 'platform-1',
115
+ name: 'Scouts en Gidsen Vlaanderen',
116
+ membershipOrganizationId: 'org-1',
117
+ reducedPriceName: 'SOMkort',
118
+ });
119
+ });
120
+
121
+ it('stores no organization for a platform that runs none', () => {
122
+ expect(flattenPlatform({ ...platform, membershipOrganizationId: null }).membershipOrganizationId).toBeNull();
123
+ });
124
+
125
+ /**
126
+ * What a koepel calls its verlaagd lidgeld is a name it sets itself -- SOMkort, kansentarief --
127
+ * and the reports print it beside the standaardtarief. A platform that names none leaves it to
128
+ * the report to word, rather than being given a name here that nobody uses.
129
+ */
130
+ it('keeps what the platform calls its verlaagd lidgeld, and nothing when it names none', () => {
131
+ expect(flattenPlatform({ ...platform, config: { ...platform.config, financialSupport: null } }).reducedPriceName).toBeNull();
132
+ });
133
+ });
134
+
135
+ describe('flattenMembership', () => {
136
+ const membership = {
137
+ id: 'membership-1',
138
+ memberId: 'member-1',
139
+ membershipTypeId: 'type-1',
140
+ organizationId: 'org-1',
141
+ periodId: 'period-1',
142
+ startDate: new Date(2025, 8, 1),
143
+ endDate: new Date(2026, 7, 31),
144
+ expireDate: null,
145
+ trialUntil: null,
146
+ deletedAt: null,
147
+ createdAt: new Date(2025, 8, 1),
148
+ updatedAt: new Date(2025, 8, 1),
149
+ };
150
+
151
+ /**
152
+ * Which tarief a lidgeld was charged at is the one thing about its price that reaches this
153
+ * database, and it is not on the record: the source keeps the amount, not what it was made of.
154
+ * The caller reads the member's status, which is the input that made it.
155
+ */
156
+ it('records the tarief the lidgeld was charged at, and none of its prices', () => {
157
+ expect(flattenMembership(membership, true).reducedPrice).toBe(true);
158
+ expect(flattenMembership(membership, false).reducedPrice).toBe(false);
159
+ expect(Object.keys(flattenMembership(membership, false)).filter(key => /price/i.test(key))).toEqual(['reducedPrice']);
160
+ });
161
+ });
162
+
163
+ describe('flattenGroup', () => {
164
+ it('resolves the translated name in a fixed language, not whatever the process is set to', () => {
165
+ const row = flattenGroup({
166
+ id: 'group-1',
167
+ type: 'Membership',
168
+ settings: { name: { get: language => language === 'nl' ? 'Bevers' : 'Beavers' } },
169
+ organizationId: 'org-1',
170
+ periodId: 'period-1',
171
+ defaultAgeGroupId: 'age-1',
172
+ status: 'Open',
173
+ deletedAt: null,
174
+ createdAt: new Date(2025, 0, 1),
175
+ updatedAt: new Date(2026, 0, 1),
176
+ });
177
+
178
+ expect(row.name).toBe('Bevers');
179
+ expect(Object.keys(row)).not.toContain('settings');
180
+ });
181
+ });
182
+
183
+ describe('flattenDefaultAgeGroup', () => {
184
+ const group = { id: 'age-1', names: ['Kapoenen'], minAge: 6, maxAge: 8 };
185
+
186
+ it('keeps a single name as it is', () => {
187
+ expect(flattenDefaultAgeGroup(group, 'period-1')).toEqual({
188
+ id: 'age-1',
189
+ periodId: 'period-1',
190
+ name: 'Kapoenen',
191
+ minAge: 6,
192
+ maxAge: 8,
193
+ });
194
+ });
195
+
196
+ /**
197
+ * The structure joins the names with a translated separator, which resolves to its own
198
+ * translation key in the sync because this service loads no locales.
199
+ */
200
+ it('joins several names with a real word, never a translation key', () => {
201
+ const row = flattenDefaultAgeGroup({ ...group, names: ['Kapoenen', 'Welpen'] }, 'period-1');
202
+
203
+ expect(row.name).toBe('Kapoenen of Welpen');
204
+ expect(row.name).not.toContain('%');
205
+ });
206
+
207
+ it('separates all but the last two with a comma', () => {
208
+ expect(flattenDefaultAgeGroup({ ...group, names: ['Kapoenen', 'Welpen', 'Jonggivers'] }, 'period-1').name).toBe('Kapoenen, Welpen of Jonggivers');
209
+ });
210
+ });
211
+
212
+ describe('flattenRegistration', () => {
213
+ it('keeps the member and group it links, and drops the answers and prices', () => {
214
+ const row = flattenRegistration({
215
+ id: 'registration-1',
216
+ organizationId: 'org-1',
217
+ memberId: 'member-1',
218
+ groupId: 'group-1',
219
+ periodId: 'period-1',
220
+ registeredAt: new Date(2025, 8, 1),
221
+ startDate: null,
222
+ endDate: null,
223
+ trialUntil: null,
224
+ deactivatedAt: null,
225
+ waitingList: false,
226
+ cycle: 0,
227
+ createdAt: new Date(2025, 0, 1),
228
+ updatedAt: new Date(2026, 0, 1),
229
+ });
230
+
231
+ expect(row.memberId).toBe('member-1');
232
+ expect(row.groupId).toBe('group-1');
233
+ for (const dropped of ['recordAnswers', 'price', 'pricePaid', 'groupPrice', 'paymentId', 'options']) {
234
+ expect(Object.keys(row)).not.toContain(dropped);
235
+ }
236
+ });
237
+ });