@stamhoofd/backend-statistics-syncer 2.153.0 → 2.160.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/LICENSE.md +7 -7
- package/README.md +1 -1
- package/dist/index.js +5 -8
- package/dist/index.js.map +1 -0
- package/dist/migrations.js +19 -0
- package/dist/migrations.js.map +1 -0
- package/dist/src/boot.js +75 -0
- package/dist/src/boot.js.map +1 -0
- package/dist/src/crons.js +39 -0
- package/dist/src/crons.js.map +1 -0
- package/dist/src/database.js +88 -0
- package/dist/src/database.js.map +1 -0
- package/dist/src/migrate.js +38 -0
- package/dist/src/migrate.js.map +1 -0
- package/dist/src/migrations/1785958573-platform-statistics-schema.sql +382 -0
- package/dist/src/migrations/1786203367-postal-code-coordinates.sql +1203 -0
- package/dist/src/periods.js +86 -0
- package/dist/src/periods.js.map +1 -0
- package/dist/src/rows.js +209 -0
- package/dist/src/rows.js.map +1 -0
- package/dist/src/schema.js +28 -0
- package/dist/src/schema.js.map +1 -0
- package/dist/src/sources.js +10 -0
- package/dist/src/sources.js.map +1 -0
- package/dist/src/sync-state.js +36 -0
- package/dist/src/sync-state.js.map +1 -0
- package/dist/src/sync.js +608 -0
- package/dist/src/sync.js.map +1 -0
- package/dist/src/writer.js +63 -0
- package/dist/src/writer.js.map +1 -0
- package/dist-types/index.d.ts +2 -0
- package/dist-types/index.d.ts.map +1 -0
- package/dist-types/migrations.d.ts +2 -0
- package/dist-types/migrations.d.ts.map +1 -0
- package/dist-types/src/boot.d.ts +8 -0
- package/dist-types/src/boot.d.ts.map +1 -0
- package/dist-types/src/crons.d.ts +21 -0
- package/dist-types/src/crons.d.ts.map +1 -0
- package/dist-types/src/database.d.ts +28 -0
- package/dist-types/src/database.d.ts.map +1 -0
- package/dist-types/src/migrate.d.ts +2 -0
- package/dist-types/src/migrate.d.ts.map +1 -0
- package/dist-types/src/periods.d.ts +51 -0
- package/dist-types/src/periods.d.ts.map +1 -0
- package/dist-types/src/rows.d.ts +212 -0
- package/dist-types/src/rows.d.ts.map +1 -0
- package/dist-types/src/schema.d.ts +9 -0
- package/dist-types/src/schema.d.ts.map +1 -0
- package/dist-types/src/sources.d.ts +10 -0
- package/dist-types/src/sources.d.ts.map +1 -0
- package/dist-types/src/sync-state.d.ts +20 -0
- package/dist-types/src/sync-state.d.ts.map +1 -0
- package/dist-types/src/sync.d.ts +37 -0
- package/dist-types/src/sync.d.ts.map +1 -0
- package/dist-types/src/writer.d.ts +24 -0
- package/dist-types/src/writer.d.ts.map +1 -0
- package/index.ts +5 -8
- package/migrations.ts +16 -11
- package/package.json +37 -23
- package/src/boot.ts +7 -3
- package/src/crons.test.ts +33 -8
- package/src/crons.ts +7 -1
- package/src/database.test.ts +48 -11
- package/src/database.ts +30 -7
- package/src/migrate.ts +1 -1
- package/src/periods.ts +5 -2
- package/src/rows.test.ts +96 -16
- package/src/rows.ts +28 -6
- package/src/schema.test.ts +48 -19
- package/src/schema.ts +14 -4
- package/src/sync-state.test.ts +3 -1
- package/src/sync-state.ts +13 -4
- package/src/sync.test.ts +145 -32
- package/src/sync.ts +422 -91
- package/src/writer.ts +32 -10
- package/tsconfig.build.json +4 -11
- package/tsconfig.json +1 -1
- package/tsconfig.test.json +1 -3
- package/tsconfig.types.json +7 -0
- package/.gitignore +0 -221
- package/tests/vitest.global.setup.ts +0 -29
- package/tests/vitest.setup.ts +0 -24
- package/vitest.config.js +0 -18
package/src/sync.ts
CHANGED
|
@@ -1,10 +1,38 @@
|
|
|
1
|
-
import type { SQLResultNamespacedRow } from '@
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import type { SQLResultNamespacedRow } from '@stamhoofd/node-database';
|
|
2
|
+
import {
|
|
3
|
+
Group,
|
|
4
|
+
Member,
|
|
5
|
+
MemberPlatformMembership,
|
|
6
|
+
MemberResponsibilityRecord,
|
|
7
|
+
Organization,
|
|
8
|
+
Platform,
|
|
9
|
+
Registration,
|
|
10
|
+
RegistrationPeriod,
|
|
11
|
+
} from '@stamhoofd/models';
|
|
12
|
+
import { SQL, SQLSelect, SQLWhereSign } from '@stamhoofd/node-sql';
|
|
4
13
|
import { getStatisticsConnection } from './database.js';
|
|
5
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
applyImportedCutoff,
|
|
16
|
+
getImportedUntil,
|
|
17
|
+
isFrozen,
|
|
18
|
+
loadFrozenPeriodIds,
|
|
19
|
+
loadSettledPeriodIds,
|
|
20
|
+
releaseUnlockedPeriods,
|
|
21
|
+
settleLockedPeriods,
|
|
22
|
+
} from './periods.js';
|
|
6
23
|
import type { StatisticsRow } from './rows.js';
|
|
7
|
-
import {
|
|
24
|
+
import {
|
|
25
|
+
flattenDefaultAgeGroup,
|
|
26
|
+
flattenGroup,
|
|
27
|
+
flattenMember,
|
|
28
|
+
flattenMembership,
|
|
29
|
+
flattenNamedConfig,
|
|
30
|
+
flattenOrganization,
|
|
31
|
+
flattenPlatform,
|
|
32
|
+
flattenRegistration,
|
|
33
|
+
flattenRegistrationPeriod,
|
|
34
|
+
flattenResponsibilityRecord,
|
|
35
|
+
} from './rows.js';
|
|
8
36
|
import { syncSource } from './sources.js';
|
|
9
37
|
import { nextWatermark, readSyncState, writeSyncState } from './sync-state.js';
|
|
10
38
|
import { deleteRows, iterateIds, upsertRows } from './writer.js';
|
|
@@ -27,7 +55,11 @@ type IncrementalTable = {
|
|
|
27
55
|
* the id alone is what makes the cursor strictly advance; rows that move into the window while a
|
|
28
56
|
* run is going are picked up by the next one through the overlap.
|
|
29
57
|
*/
|
|
30
|
-
fetch: (
|
|
58
|
+
fetch: (
|
|
59
|
+
since: Date | null,
|
|
60
|
+
afterId: string,
|
|
61
|
+
limit: number,
|
|
62
|
+
) => Promise<{ rows: StatisticsRow[]; updatedAt: Date[]; lastId: string }>;
|
|
31
63
|
/** Which of these ids still exist in the source, used to reconcile deletes. */
|
|
32
64
|
existingIds: (ids: string[]) => Promise<Set<string>>;
|
|
33
65
|
/**
|
|
@@ -59,11 +91,11 @@ type IncrementalTable = {
|
|
|
59
91
|
export const sourceColumns = ['source'];
|
|
60
92
|
|
|
61
93
|
function withSource(rows: StatisticsRow[]): StatisticsRow[] {
|
|
62
|
-
return rows.map(row => ({ ...row, source: syncSource }));
|
|
94
|
+
return rows.map((row) => ({ ...row, source: syncSource }));
|
|
63
95
|
}
|
|
64
96
|
|
|
65
97
|
function idsOf(rows: { id: string }[]): string[] {
|
|
66
|
-
return rows.map(row => row.id);
|
|
98
|
+
return rows.map((row) => row.id);
|
|
67
99
|
}
|
|
68
100
|
|
|
69
101
|
function groupByPeriod(organizations: Organization[]): Map<string, Organization[]> {
|
|
@@ -96,7 +128,10 @@ async function existingModelIds(model: { select: () => any }, ids: string[]): Pr
|
|
|
96
128
|
* that has not been synced yet, and a row for it would be refused by the foreign key, which would
|
|
97
129
|
* stall the whole table over one row.
|
|
98
130
|
*/
|
|
99
|
-
async function periodIdsByRegistration(
|
|
131
|
+
async function periodIdsByRegistration(
|
|
132
|
+
column: 'memberId' | 'organizationId',
|
|
133
|
+
ids: string[],
|
|
134
|
+
): Promise<Map<string, Set<string>>> {
|
|
100
135
|
const byId = new Map<string, Set<string>>();
|
|
101
136
|
if (ids.length === 0) {
|
|
102
137
|
return byId;
|
|
@@ -114,7 +149,9 @@ async function periodIdsByRegistration(column: 'memberId' | 'organizationId', id
|
|
|
114
149
|
.where(SQL.column(column), ids)
|
|
115
150
|
.fetch();
|
|
116
151
|
|
|
117
|
-
const known = await existingPeriodIds(
|
|
152
|
+
const known = await existingPeriodIds(
|
|
153
|
+
rows.map((row) => row.periodId).filter((id): id is string => id !== null),
|
|
154
|
+
);
|
|
118
155
|
|
|
119
156
|
for (const row of rows) {
|
|
120
157
|
if (row.periodId !== null && known.has(row.periodId)) {
|
|
@@ -146,8 +183,12 @@ async function reducedPriceByMember(memberIds: string[]): Promise<Set<string>> {
|
|
|
146
183
|
return new Set();
|
|
147
184
|
}
|
|
148
185
|
|
|
149
|
-
const members = await Member.select().where(SQL.column('id'), unique).fetch() as Member[];
|
|
150
|
-
return new Set(
|
|
186
|
+
const members = (await Member.select().where(SQL.column('id'), unique).fetch()) as Member[];
|
|
187
|
+
return new Set(
|
|
188
|
+
members
|
|
189
|
+
.filter((member) => member.details.shouldApplyReducedPrice)
|
|
190
|
+
.map((member) => member.id),
|
|
191
|
+
);
|
|
151
192
|
}
|
|
152
193
|
|
|
153
194
|
/**
|
|
@@ -155,9 +196,13 @@ async function reducedPriceByMember(memberIds: string[]): Promise<Set<string>> {
|
|
|
155
196
|
* is recorded against that period, and a netwerk link to a unit that has no row yet is a link to
|
|
156
197
|
* nothing.
|
|
157
198
|
*/
|
|
158
|
-
async function periodIdsByOrganization(
|
|
199
|
+
async function periodIdsByOrganization(
|
|
200
|
+
organizations: Organization[],
|
|
201
|
+
): Promise<Map<string, Set<string>>> {
|
|
159
202
|
const byOrganization = await periodIdsByRegistration('organizationId', idsOf(organizations));
|
|
160
|
-
const known = await existingPeriodIds(
|
|
203
|
+
const known = await existingPeriodIds(
|
|
204
|
+
organizations.map((organization) => organization.periodId),
|
|
205
|
+
);
|
|
161
206
|
|
|
162
207
|
for (const organization of organizations) {
|
|
163
208
|
if (known.has(organization.periodId)) {
|
|
@@ -184,11 +229,20 @@ async function existingPeriodIds(ids: string[]): Promise<Set<string>> {
|
|
|
184
229
|
}
|
|
185
230
|
|
|
186
231
|
const connection = getStatisticsConnection();
|
|
187
|
-
const [rows] = await connection.select(
|
|
188
|
-
|
|
232
|
+
const [rows] = await connection.select(
|
|
233
|
+
'SELECT `id` FROM `registration_periods` WHERE `id` IN (?)',
|
|
234
|
+
[unique],
|
|
235
|
+
{ nestTables: false },
|
|
236
|
+
);
|
|
237
|
+
return new Set((rows as unknown as { id: string }[]).map((row) => row.id));
|
|
189
238
|
}
|
|
190
239
|
|
|
191
|
-
function incrementalQuery(
|
|
240
|
+
function incrementalQuery(
|
|
241
|
+
model: { select: () => any },
|
|
242
|
+
since: Date | null,
|
|
243
|
+
afterId: string,
|
|
244
|
+
limit: number,
|
|
245
|
+
) {
|
|
192
246
|
const query = model.select().where(SQL.column('id'), SQLWhereSign.Greater, afterId);
|
|
193
247
|
if (since) {
|
|
194
248
|
query.where(SQL.column('updatedAt'), SQLWhereSign.GreaterEqual, since);
|
|
@@ -204,8 +258,12 @@ function incrementalQuery(model: { select: () => any }, since: Date | null, afte
|
|
|
204
258
|
*/
|
|
205
259
|
async function loadIdSet(table: string): Promise<Set<string>> {
|
|
206
260
|
const connection = getStatisticsConnection();
|
|
207
|
-
const [rows] = await connection.select(
|
|
208
|
-
|
|
261
|
+
const [rows] = await connection.select(
|
|
262
|
+
`SELECT DISTINCT \`id\` FROM ${connection.escapeId(table)}`,
|
|
263
|
+
[],
|
|
264
|
+
{ nestTables: false },
|
|
265
|
+
);
|
|
266
|
+
return new Set((rows as unknown as { id: string }[]).map((row) => row.id));
|
|
209
267
|
}
|
|
210
268
|
|
|
211
269
|
/**
|
|
@@ -216,12 +274,33 @@ async function loadIdSet(table: string): Promise<Set<string>> {
|
|
|
216
274
|
function periodsTable(): IncrementalTable {
|
|
217
275
|
return {
|
|
218
276
|
table: 'registration_periods',
|
|
219
|
-
columns: [
|
|
277
|
+
columns: [
|
|
278
|
+
'id',
|
|
279
|
+
'startDate',
|
|
280
|
+
'endDate',
|
|
281
|
+
'locked',
|
|
282
|
+
'organizationId',
|
|
283
|
+
'previousPeriodId',
|
|
284
|
+
'nextPeriodId',
|
|
285
|
+
'customName',
|
|
286
|
+
'name',
|
|
287
|
+
'createdAt',
|
|
288
|
+
'updatedAt',
|
|
289
|
+
],
|
|
220
290
|
fetch: async (since, afterId, limit) => {
|
|
221
|
-
const periods = await incrementalQuery(
|
|
222
|
-
|
|
291
|
+
const periods = (await incrementalQuery(
|
|
292
|
+
RegistrationPeriod,
|
|
293
|
+
since,
|
|
294
|
+
afterId,
|
|
295
|
+
limit,
|
|
296
|
+
).fetch()) as RegistrationPeriod[];
|
|
297
|
+
return {
|
|
298
|
+
rows: periods.map(flattenRegistrationPeriod),
|
|
299
|
+
updatedAt: periods.map((period) => period.updatedAt),
|
|
300
|
+
lastId: periods.at(-1)?.id ?? afterId,
|
|
301
|
+
};
|
|
223
302
|
},
|
|
224
|
-
existingIds: ids => existingModelIds(RegistrationPeriod, ids),
|
|
303
|
+
existingIds: (ids) => existingModelIds(RegistrationPeriod, ids),
|
|
225
304
|
periodColumn: 'id',
|
|
226
305
|
// A period is what every historical figure hangs off, and everything else points at it with
|
|
227
306
|
// ON DELETE RESTRICT. Removing one would either be refused by the database or take a settled
|
|
@@ -231,75 +310,199 @@ function periodsTable(): IncrementalTable {
|
|
|
231
310
|
};
|
|
232
311
|
}
|
|
233
312
|
|
|
234
|
-
function buildIncrementalTables(
|
|
313
|
+
function buildIncrementalTables(
|
|
314
|
+
known: { ageGroups: Set<string>; membershipTypes: Set<string>; responsibilities: Set<string> },
|
|
315
|
+
frozen: Set<string>,
|
|
316
|
+
openPeriodIds: string[],
|
|
317
|
+
): IncrementalTable[] {
|
|
235
318
|
return [
|
|
236
319
|
{
|
|
237
320
|
table: 'organizations',
|
|
238
|
-
columns: [
|
|
321
|
+
columns: [
|
|
322
|
+
'id',
|
|
323
|
+
'periodId',
|
|
324
|
+
'name',
|
|
325
|
+
'uri',
|
|
326
|
+
'postalCode',
|
|
327
|
+
'city',
|
|
328
|
+
'active',
|
|
329
|
+
'createdAt',
|
|
330
|
+
'updatedAt',
|
|
331
|
+
],
|
|
239
332
|
fetch: async (since, afterId, limit) => {
|
|
240
|
-
const organizations = await incrementalQuery(
|
|
333
|
+
const organizations = (await incrementalQuery(
|
|
334
|
+
Organization,
|
|
335
|
+
since,
|
|
336
|
+
afterId,
|
|
337
|
+
limit,
|
|
338
|
+
).fetch()) as Organization[];
|
|
241
339
|
await syncOrganizationTagsAndResponsibilities(organizations, frozen, openPeriodIds);
|
|
242
340
|
const periodIds = await periodIdsByOrganization(organizations);
|
|
243
|
-
const rows = organizations.flatMap(
|
|
244
|
-
|
|
341
|
+
const rows = organizations.flatMap((organization) =>
|
|
342
|
+
[...(periodIds.get(organization.id) ?? [])].map((periodId) =>
|
|
343
|
+
flattenOrganization(organization, periodId),
|
|
344
|
+
),
|
|
345
|
+
);
|
|
346
|
+
return {
|
|
347
|
+
rows,
|
|
348
|
+
updatedAt: organizations.map((organization) => organization.updatedAt),
|
|
349
|
+
lastId: organizations.at(-1)?.id ?? afterId,
|
|
350
|
+
};
|
|
245
351
|
},
|
|
246
|
-
existingIds: ids => existingModelIds(Organization, ids),
|
|
352
|
+
existingIds: (ids) => existingModelIds(Organization, ids),
|
|
247
353
|
periodColumn: 'periodId',
|
|
248
354
|
keyColumns: ['id', 'periodId'],
|
|
249
355
|
neverDelete: true,
|
|
250
356
|
},
|
|
251
357
|
{
|
|
252
358
|
table: 'groups',
|
|
253
|
-
columns: [
|
|
359
|
+
columns: [
|
|
360
|
+
'id',
|
|
361
|
+
'type',
|
|
362
|
+
'name',
|
|
363
|
+
'organizationId',
|
|
364
|
+
'periodId',
|
|
365
|
+
'defaultAgeGroupId',
|
|
366
|
+
'status',
|
|
367
|
+
'deletedAt',
|
|
368
|
+
'createdAt',
|
|
369
|
+
'updatedAt',
|
|
370
|
+
],
|
|
254
371
|
fetch: async (since, afterId, limit) => {
|
|
255
|
-
const groups = await incrementalQuery(
|
|
372
|
+
const groups = (await incrementalQuery(
|
|
373
|
+
Group,
|
|
374
|
+
since,
|
|
375
|
+
afterId,
|
|
376
|
+
limit,
|
|
377
|
+
).fetch()) as Group[];
|
|
256
378
|
const rows = groups.map((group) => {
|
|
257
379
|
const row = flattenGroup(group);
|
|
258
|
-
if (
|
|
380
|
+
if (
|
|
381
|
+
typeof row.defaultAgeGroupId === 'string' &&
|
|
382
|
+
!known.ageGroups.has(row.defaultAgeGroupId)
|
|
383
|
+
) {
|
|
259
384
|
row.defaultAgeGroupId = null;
|
|
260
385
|
}
|
|
261
386
|
return row;
|
|
262
387
|
});
|
|
263
|
-
return {
|
|
388
|
+
return {
|
|
389
|
+
rows,
|
|
390
|
+
updatedAt: groups.map((group) => group.updatedAt),
|
|
391
|
+
lastId: groups.at(-1)?.id ?? afterId,
|
|
392
|
+
};
|
|
264
393
|
},
|
|
265
|
-
existingIds: ids => existingModelIds(Group, ids),
|
|
394
|
+
existingIds: (ids) => existingModelIds(Group, ids),
|
|
266
395
|
periodColumn: 'periodId',
|
|
267
396
|
},
|
|
268
397
|
{
|
|
269
398
|
table: 'members',
|
|
270
|
-
columns: [
|
|
399
|
+
columns: [
|
|
400
|
+
'id',
|
|
401
|
+
'periodId',
|
|
402
|
+
'birthDate',
|
|
403
|
+
'gender',
|
|
404
|
+
'postalCode',
|
|
405
|
+
'organizationId',
|
|
406
|
+
'createdAt',
|
|
407
|
+
'updatedAt',
|
|
408
|
+
'lastRegisteredAt',
|
|
409
|
+
],
|
|
271
410
|
fetch: async (since, afterId, limit) => {
|
|
272
|
-
const members = await incrementalQuery(
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
411
|
+
const members = (await incrementalQuery(
|
|
412
|
+
Member,
|
|
413
|
+
since,
|
|
414
|
+
afterId,
|
|
415
|
+
limit,
|
|
416
|
+
).fetch()) as Member[];
|
|
417
|
+
const periodIds = await periodIdsByMember(members.map((member) => member.id));
|
|
418
|
+
const rows = members.flatMap((member) =>
|
|
419
|
+
[...(periodIds.get(member.id) ?? [])].map((periodId) =>
|
|
420
|
+
flattenMember(member, periodId),
|
|
421
|
+
),
|
|
422
|
+
);
|
|
423
|
+
return {
|
|
424
|
+
rows,
|
|
425
|
+
updatedAt: members.map((member) => member.updatedAt),
|
|
426
|
+
lastId: members.at(-1)?.id ?? afterId,
|
|
427
|
+
};
|
|
276
428
|
},
|
|
277
|
-
existingIds: ids => existingModelIds(Member, ids),
|
|
429
|
+
existingIds: (ids) => existingModelIds(Member, ids),
|
|
278
430
|
periodColumn: 'periodId',
|
|
279
431
|
keyColumns: ['id', 'periodId'],
|
|
280
432
|
neverDelete: true,
|
|
281
433
|
},
|
|
282
434
|
{
|
|
283
435
|
table: 'registrations',
|
|
284
|
-
columns: [
|
|
436
|
+
columns: [
|
|
437
|
+
'id',
|
|
438
|
+
'organizationId',
|
|
439
|
+
'memberId',
|
|
440
|
+
'groupId',
|
|
441
|
+
'periodId',
|
|
442
|
+
'registeredAt',
|
|
443
|
+
'startDate',
|
|
444
|
+
'endDate',
|
|
445
|
+
'trialUntil',
|
|
446
|
+
'deactivatedAt',
|
|
447
|
+
'createdAt',
|
|
448
|
+
'updatedAt',
|
|
449
|
+
],
|
|
285
450
|
fetch: async (since, afterId, limit) => {
|
|
286
|
-
const registrations = await incrementalQuery(
|
|
287
|
-
|
|
451
|
+
const registrations = (await incrementalQuery(
|
|
452
|
+
Registration,
|
|
453
|
+
since,
|
|
454
|
+
afterId,
|
|
455
|
+
limit,
|
|
456
|
+
).fetch()) as Registration[];
|
|
457
|
+
return {
|
|
458
|
+
rows: registrations.map(flattenRegistration),
|
|
459
|
+
updatedAt: registrations.map((registration) => registration.updatedAt),
|
|
460
|
+
lastId: registrations.at(-1)?.id ?? afterId,
|
|
461
|
+
};
|
|
288
462
|
},
|
|
289
|
-
existingIds: ids => existingModelIds(Registration, ids),
|
|
463
|
+
existingIds: (ids) => existingModelIds(Registration, ids),
|
|
290
464
|
periodColumn: 'periodId',
|
|
291
465
|
},
|
|
292
466
|
{
|
|
293
467
|
table: 'member_platform_memberships',
|
|
294
|
-
columns: [
|
|
468
|
+
columns: [
|
|
469
|
+
'id',
|
|
470
|
+
'memberId',
|
|
471
|
+
'membershipTypeId',
|
|
472
|
+
'reducedPrice',
|
|
473
|
+
'organizationId',
|
|
474
|
+
'periodId',
|
|
475
|
+
'startDate',
|
|
476
|
+
'endDate',
|
|
477
|
+
'expireDate',
|
|
478
|
+
'trialUntil',
|
|
479
|
+
'deletedAt',
|
|
480
|
+
'createdAt',
|
|
481
|
+
'updatedAt',
|
|
482
|
+
],
|
|
295
483
|
fetch: async (since, afterId, limit) => {
|
|
296
|
-
const memberships = await incrementalQuery(
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
484
|
+
const memberships = (await incrementalQuery(
|
|
485
|
+
MemberPlatformMembership,
|
|
486
|
+
since,
|
|
487
|
+
afterId,
|
|
488
|
+
limit,
|
|
489
|
+
).fetch()) as MemberPlatformMembership[];
|
|
490
|
+
const kept = memberships.filter((membership) =>
|
|
491
|
+
known.membershipTypes.has(membership.membershipTypeId),
|
|
492
|
+
);
|
|
493
|
+
const reduced = await reducedPriceByMember(
|
|
494
|
+
kept.map((membership) => membership.memberId),
|
|
495
|
+
);
|
|
496
|
+
const rows = kept.map((membership) =>
|
|
497
|
+
flattenMembership(membership, reduced.has(membership.memberId)),
|
|
498
|
+
);
|
|
499
|
+
return {
|
|
500
|
+
rows,
|
|
501
|
+
updatedAt: kept.map((membership) => membership.updatedAt),
|
|
502
|
+
lastId: memberships.at(-1)?.id ?? afterId,
|
|
503
|
+
};
|
|
301
504
|
},
|
|
302
|
-
existingIds: ids => existingModelIds(MemberPlatformMembership, ids),
|
|
505
|
+
existingIds: (ids) => existingModelIds(MemberPlatformMembership, ids),
|
|
303
506
|
periodColumn: 'periodId',
|
|
304
507
|
},
|
|
305
508
|
];
|
|
@@ -318,24 +521,54 @@ async function syncPlatformConfig(openPeriodIds: string[]): Promise<void> {
|
|
|
318
521
|
const config = platform.config;
|
|
319
522
|
|
|
320
523
|
const perPeriod = <T>(items: T[], flatten: (item: T, periodId: string) => StatisticsRow) =>
|
|
321
|
-
openPeriodIds.flatMap(periodId => items.map(item => flatten(item, periodId)));
|
|
524
|
+
openPeriodIds.flatMap((periodId) => items.map((item) => flatten(item, periodId)));
|
|
322
525
|
|
|
323
526
|
// The platform record itself rather than its configuration, and therefore not per period: the
|
|
324
527
|
// reports read which organization it runs and what it calls its verlaagd lidgeld, and what they
|
|
325
528
|
// print of that organization comes from `organizations`, which is recorded per year like
|
|
326
529
|
// everything else.
|
|
327
|
-
await upsertRows(
|
|
530
|
+
await upsertRows(
|
|
531
|
+
'platform',
|
|
532
|
+
['id', 'name', 'membershipOrganizationId', 'reducedPriceName'],
|
|
533
|
+
[flattenPlatform(platform)],
|
|
534
|
+
['id'],
|
|
535
|
+
);
|
|
328
536
|
|
|
329
|
-
await upsertRows(
|
|
537
|
+
await upsertRows(
|
|
538
|
+
'organization_tags',
|
|
539
|
+
['id', 'periodId', 'name'],
|
|
540
|
+
perPeriod(config.tags, flattenNamedConfig),
|
|
541
|
+
namedConfigKey,
|
|
542
|
+
);
|
|
330
543
|
|
|
331
|
-
await upsertRows(
|
|
332
|
-
|
|
333
|
-
|
|
544
|
+
await upsertRows(
|
|
545
|
+
'default_age_groups',
|
|
546
|
+
['id', 'periodId', 'name', 'minAge', 'maxAge'],
|
|
547
|
+
perPeriod(config.defaultAgeGroups, (group, periodId) =>
|
|
548
|
+
flattenDefaultAgeGroup(
|
|
549
|
+
{ id: group.id, names: group.names, minAge: group.minAge, maxAge: group.maxAge },
|
|
550
|
+
periodId,
|
|
551
|
+
),
|
|
552
|
+
),
|
|
553
|
+
namedConfigKey,
|
|
554
|
+
);
|
|
555
|
+
await upsertRows(
|
|
556
|
+
'platform_membership_types',
|
|
557
|
+
['id', 'periodId', 'name'],
|
|
558
|
+
perPeriod(config.membershipTypes, flattenNamedConfig),
|
|
559
|
+
namedConfigKey,
|
|
560
|
+
);
|
|
561
|
+
await upsertRows(
|
|
562
|
+
'responsibilities',
|
|
563
|
+
['id', 'periodId', 'name'],
|
|
564
|
+
perPeriod(config.responsibilities, flattenNamedConfig),
|
|
565
|
+
namedConfigKey,
|
|
566
|
+
);
|
|
334
567
|
}
|
|
335
568
|
|
|
336
569
|
/** The periods the sync still writes into: everything the statistics database knows, minus the frozen ones. */
|
|
337
570
|
async function loadOpenPeriodIds(frozen: Set<string>): Promise<string[]> {
|
|
338
|
-
return [...await loadIdSet('registration_periods')].filter(id => !frozen.has(id));
|
|
571
|
+
return [...(await loadIdSet('registration_periods'))].filter((id) => !frozen.has(id));
|
|
339
572
|
}
|
|
340
573
|
|
|
341
574
|
const namedConfigKey = ['id', 'periodId'];
|
|
@@ -345,18 +578,36 @@ const namedConfigKey = ['id', 'periodId'];
|
|
|
345
578
|
* organization record, so they are written along with the batch of organizations they belong to
|
|
346
579
|
* rather than by scanning every organization again.
|
|
347
580
|
*/
|
|
348
|
-
async function syncOrganizationTagsAndResponsibilities(
|
|
581
|
+
async function syncOrganizationTagsAndResponsibilities(
|
|
582
|
+
organizations: Organization[],
|
|
583
|
+
frozen: Set<string>,
|
|
584
|
+
openPeriodIds: string[],
|
|
585
|
+
): Promise<void> {
|
|
349
586
|
if (organizations.length === 0) {
|
|
350
587
|
return;
|
|
351
588
|
}
|
|
352
589
|
|
|
353
|
-
const ownResponsibilities = organizations.flatMap(
|
|
354
|
-
|
|
590
|
+
const ownResponsibilities = organizations.flatMap(
|
|
591
|
+
(organization) => organization.privateMeta.responsibilities,
|
|
592
|
+
);
|
|
593
|
+
await upsertRows(
|
|
594
|
+
'responsibilities',
|
|
595
|
+
['id', 'periodId', 'name'],
|
|
596
|
+
openPeriodIds.flatMap((periodId) =>
|
|
597
|
+
ownResponsibilities.map((responsibility) =>
|
|
598
|
+
flattenNamedConfig(responsibility, periodId),
|
|
599
|
+
),
|
|
600
|
+
),
|
|
601
|
+
namedConfigKey,
|
|
602
|
+
);
|
|
355
603
|
|
|
356
604
|
// The source only knows the tags an organization carries now, so they are recorded against the
|
|
357
605
|
// period it is in. A frozen period keeps the netwerk it was recorded with while it was live.
|
|
358
606
|
const knownPeriods = await loadIdSet('registration_periods');
|
|
359
|
-
const live = organizations.filter(
|
|
607
|
+
const live = organizations.filter(
|
|
608
|
+
(organization) =>
|
|
609
|
+
knownPeriods.has(organization.periodId) && !isFrozen(frozen, organization.periodId),
|
|
610
|
+
);
|
|
360
611
|
if (live.length === 0) {
|
|
361
612
|
return;
|
|
362
613
|
}
|
|
@@ -373,10 +624,20 @@ async function syncOrganizationTagsAndResponsibilities(organizations: Organizati
|
|
|
373
624
|
);
|
|
374
625
|
}
|
|
375
626
|
|
|
376
|
-
const links = live.flatMap(organization =>
|
|
377
|
-
.
|
|
378
|
-
|
|
379
|
-
|
|
627
|
+
const links = live.flatMap((organization) =>
|
|
628
|
+
organization.meta.tags
|
|
629
|
+
.filter((tagId) => knownTags.has(tagId))
|
|
630
|
+
.map((tagId) => ({
|
|
631
|
+
organizationsId: organization.id,
|
|
632
|
+
organizationTagsId: tagId,
|
|
633
|
+
periodId: organization.periodId,
|
|
634
|
+
})),
|
|
635
|
+
);
|
|
636
|
+
await upsertRows(
|
|
637
|
+
'_organizations_organization_tags',
|
|
638
|
+
['organizationsId', 'organizationTagsId', 'periodId', ...sourceColumns],
|
|
639
|
+
withSource(links),
|
|
640
|
+
);
|
|
380
641
|
}
|
|
381
642
|
|
|
382
643
|
type PeriodRange = { id: string; organizationId: string | null; startDate: Date; endDate: Date };
|
|
@@ -385,7 +646,9 @@ type PeriodRange = { id: string; organizationId: string | null; startDate: Date;
|
|
|
385
646
|
* The years the sync still writes into, grouped by the unit holding them. Every unit keeps its own
|
|
386
647
|
* row per year; the platform's own years are the ones under no unit at all.
|
|
387
648
|
*/
|
|
388
|
-
async function loadOpenPeriodsByOrganization(
|
|
649
|
+
async function loadOpenPeriodsByOrganization(
|
|
650
|
+
frozen: Set<string>,
|
|
651
|
+
): Promise<Map<string | null, PeriodRange[]>> {
|
|
389
652
|
const connection = getStatisticsConnection();
|
|
390
653
|
const [rows] = await connection.select(
|
|
391
654
|
'SELECT `id`, `organizationId`, `startDate`, `endDate` FROM `registration_periods`',
|
|
@@ -417,32 +680,48 @@ async function loadOpenPeriodsByOrganization(frozen: Set<string>): Promise<Map<s
|
|
|
417
680
|
* A record with no end date runs until now rather than forever, so a functie someone still holds is
|
|
418
681
|
* not also recorded against the years that have not happened yet.
|
|
419
682
|
*/
|
|
420
|
-
function periodIdsOfRecord(
|
|
683
|
+
function periodIdsOfRecord(
|
|
684
|
+
record: MemberResponsibilityRecord,
|
|
685
|
+
byOrganization: Map<string | null, PeriodRange[]>,
|
|
686
|
+
now: Date,
|
|
687
|
+
): string[] {
|
|
421
688
|
const periods = byOrganization.get(record.organizationId) ?? byOrganization.get(null) ?? [];
|
|
422
689
|
const runsUntil = record.endDate !== null && record.endDate < now ? record.endDate : now;
|
|
423
690
|
|
|
424
691
|
return periods
|
|
425
|
-
.filter(period => period.startDate <= runsUntil && period.endDate >= record.startDate)
|
|
426
|
-
.map(period => period.id);
|
|
692
|
+
.filter((period) => period.startDate <= runsUntil && period.endDate >= record.startDate)
|
|
693
|
+
.map((period) => period.id);
|
|
427
694
|
}
|
|
428
695
|
|
|
429
696
|
/**
|
|
430
697
|
* Responsibility records carry no `updatedAt`, so there is no watermark to advance: they are written
|
|
431
698
|
* in full on every run. Records pointing at a responsibility that no longer exists are skipped.
|
|
432
699
|
*/
|
|
433
|
-
async function syncResponsibilityRecords(
|
|
434
|
-
|
|
700
|
+
async function syncResponsibilityRecords(
|
|
701
|
+
knownResponsibilities: Set<string>,
|
|
702
|
+
frozen: Set<string>,
|
|
703
|
+
): Promise<void> {
|
|
704
|
+
const columns = [
|
|
705
|
+
'id',
|
|
706
|
+
'periodId',
|
|
707
|
+
'memberId',
|
|
708
|
+
'groupId',
|
|
709
|
+
'organizationId',
|
|
710
|
+
'responsibilityId',
|
|
711
|
+
'startDate',
|
|
712
|
+
'endDate',
|
|
713
|
+
];
|
|
435
714
|
const byOrganization = await loadOpenPeriodsByOrganization(frozen);
|
|
436
715
|
const connection = getStatisticsConnection();
|
|
437
716
|
const now = new Date();
|
|
438
717
|
let afterId = '';
|
|
439
718
|
|
|
440
719
|
for (;;) {
|
|
441
|
-
const records = await MemberResponsibilityRecord.select()
|
|
720
|
+
const records = (await MemberResponsibilityRecord.select()
|
|
442
721
|
.where(SQL.column('id'), SQLWhereSign.Greater, afterId)
|
|
443
722
|
.orderBy(SQL.column('id'), 'ASC')
|
|
444
723
|
.limit(fetchBatchSize)
|
|
445
|
-
.fetch() as MemberResponsibilityRecord[];
|
|
724
|
+
.fetch()) as MemberResponsibilityRecord[];
|
|
446
725
|
|
|
447
726
|
if (records.length === 0) {
|
|
448
727
|
return;
|
|
@@ -452,14 +731,31 @@ async function syncResponsibilityRecords(knownResponsibilities: Set<string>, fro
|
|
|
452
731
|
// has to lose the years it no longer covers. Only outside the frozen ones: those are settled.
|
|
453
732
|
const ids = idsOf(records);
|
|
454
733
|
if (frozen.size > 0) {
|
|
455
|
-
await connection.delete(
|
|
734
|
+
await connection.delete(
|
|
735
|
+
'DELETE FROM `member_responsibility_records` WHERE `id` IN (?) AND `periodId` NOT IN (?)',
|
|
736
|
+
[ids, [...frozen]],
|
|
737
|
+
);
|
|
456
738
|
} else {
|
|
457
|
-
await connection.delete(
|
|
739
|
+
await connection.delete(
|
|
740
|
+
'DELETE FROM `member_responsibility_records` WHERE `id` IN (?)',
|
|
741
|
+
[ids],
|
|
742
|
+
);
|
|
458
743
|
}
|
|
459
744
|
|
|
460
|
-
await upsertRows(
|
|
461
|
-
|
|
462
|
-
|
|
745
|
+
await upsertRows(
|
|
746
|
+
'member_responsibility_records',
|
|
747
|
+
[...columns, ...sourceColumns],
|
|
748
|
+
withSource(
|
|
749
|
+
records
|
|
750
|
+
.filter((record) => knownResponsibilities.has(record.responsibilityId))
|
|
751
|
+
.flatMap((record) =>
|
|
752
|
+
periodIdsOfRecord(record, byOrganization, now).map((periodId) =>
|
|
753
|
+
flattenResponsibilityRecord(record, periodId),
|
|
754
|
+
),
|
|
755
|
+
),
|
|
756
|
+
),
|
|
757
|
+
['id', 'periodId'],
|
|
758
|
+
);
|
|
463
759
|
afterId = records[records.length - 1].id;
|
|
464
760
|
}
|
|
465
761
|
}
|
|
@@ -468,7 +764,12 @@ async function syncResponsibilityRecords(knownResponsibilities: Set<string>, fro
|
|
|
468
764
|
* Of these statistics rows, the ones that do not belong to a frozen period. A deleted source row in a
|
|
469
765
|
* settled year stays exactly as it was counted.
|
|
470
766
|
*/
|
|
471
|
-
async function withoutFrozen(
|
|
767
|
+
async function withoutFrozen(
|
|
768
|
+
table: string,
|
|
769
|
+
ids: string[],
|
|
770
|
+
frozen: Set<string>,
|
|
771
|
+
periodColumn: string,
|
|
772
|
+
): Promise<string[]> {
|
|
472
773
|
if (ids.length === 0 || frozen.size === 0) {
|
|
473
774
|
return ids;
|
|
474
775
|
}
|
|
@@ -480,10 +781,13 @@ async function withoutFrozen(table: string, ids: string[], frozen: Set<string>,
|
|
|
480
781
|
[ids, [...frozen]],
|
|
481
782
|
{ nestTables: false },
|
|
482
783
|
);
|
|
483
|
-
return (rows as unknown as { id: string }[]).map(row => row.id);
|
|
784
|
+
return (rows as unknown as { id: string }[]).map((row) => row.id);
|
|
484
785
|
}
|
|
485
786
|
|
|
486
|
-
async function syncIncrementalTable(
|
|
787
|
+
async function syncIncrementalTable(
|
|
788
|
+
definition: IncrementalTable,
|
|
789
|
+
frozen: Set<string>,
|
|
790
|
+
): Promise<void> {
|
|
487
791
|
const startedAt = new Date();
|
|
488
792
|
const state = await readSyncState(definition.table);
|
|
489
793
|
const since = state.watermark ? new Date(state.watermark.getTime() - watermarkOverlap) : null;
|
|
@@ -497,9 +801,16 @@ async function syncIncrementalTable(definition: IncrementalTable, frozen: Set<st
|
|
|
497
801
|
}
|
|
498
802
|
|
|
499
803
|
const live = definition.periodColumn
|
|
500
|
-
? rows.filter(
|
|
804
|
+
? rows.filter(
|
|
805
|
+
(row) => !isFrozen(frozen, row[definition.periodColumn!] as string | null),
|
|
806
|
+
)
|
|
501
807
|
: rows;
|
|
502
|
-
await upsertRows(
|
|
808
|
+
await upsertRows(
|
|
809
|
+
definition.table,
|
|
810
|
+
[...definition.columns, ...sourceColumns],
|
|
811
|
+
withSource(live),
|
|
812
|
+
definition.keyColumns,
|
|
813
|
+
);
|
|
503
814
|
seen.push(...updatedAt);
|
|
504
815
|
afterId = lastId;
|
|
505
816
|
}
|
|
@@ -511,14 +822,18 @@ async function syncIncrementalTable(definition: IncrementalTable, frozen: Set<st
|
|
|
511
822
|
}
|
|
512
823
|
|
|
513
824
|
function emptyKnownIds() {
|
|
514
|
-
return {
|
|
825
|
+
return {
|
|
826
|
+
ageGroups: new Set<string>(),
|
|
827
|
+
membershipTypes: new Set<string>(),
|
|
828
|
+
responsibilities: new Set<string>(),
|
|
829
|
+
};
|
|
515
830
|
}
|
|
516
831
|
|
|
517
832
|
/** The tables the delete reconciliation walks, which is every table it may take a row out of. */
|
|
518
833
|
export function reconciledTables(): string[] {
|
|
519
834
|
return [periodsTable(), ...buildIncrementalTables(emptyKnownIds(), new Set(), [])]
|
|
520
|
-
.filter(definition => !definition.neverDelete)
|
|
521
|
-
.map(definition => definition.table);
|
|
835
|
+
.filter((definition) => !definition.neverDelete)
|
|
836
|
+
.map((definition) => definition.table);
|
|
522
837
|
}
|
|
523
838
|
|
|
524
839
|
/**
|
|
@@ -569,22 +884,38 @@ export async function syncStatistics(): Promise<void> {
|
|
|
569
884
|
export async function syncStatisticsDeletes(): Promise<void> {
|
|
570
885
|
const frozen = await loadFrozenPeriodIds();
|
|
571
886
|
|
|
572
|
-
for (const definition of [
|
|
887
|
+
for (const definition of [
|
|
888
|
+
periodsTable(),
|
|
889
|
+
...buildIncrementalTables(emptyKnownIds(), frozen, []),
|
|
890
|
+
]) {
|
|
573
891
|
if (definition.neverDelete) {
|
|
574
892
|
continue;
|
|
575
893
|
}
|
|
576
894
|
|
|
577
895
|
for await (const ids of iterateIds(definition.table, syncSource)) {
|
|
578
896
|
const existing = await definition.existingIds(ids);
|
|
579
|
-
const missing = ids.filter(id => !existing.has(id));
|
|
580
|
-
await deleteRows(
|
|
897
|
+
const missing = ids.filter((id) => !existing.has(id));
|
|
898
|
+
await deleteRows(
|
|
899
|
+
definition.table,
|
|
900
|
+
definition.periodColumn
|
|
901
|
+
? await withoutFrozen(
|
|
902
|
+
definition.table,
|
|
903
|
+
missing,
|
|
904
|
+
frozen,
|
|
905
|
+
definition.periodColumn,
|
|
906
|
+
)
|
|
907
|
+
: missing,
|
|
908
|
+
);
|
|
581
909
|
}
|
|
582
910
|
await writeSyncState(definition.table, { lastReconciledAt: new Date() });
|
|
583
911
|
}
|
|
584
912
|
|
|
585
913
|
for await (const ids of iterateIds('member_responsibility_records', syncSource)) {
|
|
586
914
|
const existing = await existingModelIds(MemberResponsibilityRecord, ids);
|
|
587
|
-
await deleteRows(
|
|
915
|
+
await deleteRows(
|
|
916
|
+
'member_responsibility_records',
|
|
917
|
+
ids.filter((id) => !existing.has(id)),
|
|
918
|
+
);
|
|
588
919
|
}
|
|
589
920
|
await writeSyncState('member_responsibility_records', { lastReconciledAt: new Date() });
|
|
590
921
|
}
|