From 49b08580ed9fb649db435159d4fb3929e7ee4452 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:28:24 +0100 Subject: [PATCH 01/11] fix(events): read a publisher's assignments in one meeting in the programme's order MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A record's coming assignments, and the last one done, read several of one meeting in whatever order the table returned them, so the record — and the reference suite — could change from one run to the next. They now follow the programme: parts, then services, each in their order. --- ...ber-engagement.queries.integration.test.ts | 84 +++++++++++++++++++ .../server/member-engagement.queries.ts | 16 +++- 2 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 app/features/events/server/member-engagement.queries.integration.test.ts diff --git a/app/features/events/server/member-engagement.queries.integration.test.ts b/app/features/events/server/member-engagement.queries.integration.test.ts new file mode 100644 index 00000000..0f28c61d --- /dev/null +++ b/app/features/events/server/member-engagement.queries.integration.test.ts @@ -0,0 +1,84 @@ +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// A publisher's record names their assignments: the coming ones, and the last one done. Several in one meeting are +// read in the programme's order — parts, then services — not in whatever order the table returns them, so the record +// reads the same every time. + +const adapter = new PrismaPg({ + connectionString: process.env.DB_RUNTIME_URL ?? process.env.DB_URL, + max: 3, + connectionTimeoutMillis: 5000, +}) +const testDb = new PrismaClient({ adapter }) + +type Tx = Parameters[0]>[0] + +function withScope(congregationId: number, fn: (tx: Tx) => Promise): Promise { + return testDb.$transaction(async tx => { + await tx.$executeRawUnsafe(`SET LOCAL app.congregation_id = '${String(congregationId)}'`) + return fn(tx) + }) +} + +const { findLastAssignmentsForMembers, findUpcomingAssignmentsForMember } = await import('./member-engagement.queries') + +const ts = Date.now() +const ids = { cong: 0, member: 0 } +const NOW = new Date('2027-03-03T09:00:00Z') + +beforeAll(async () => { + ids.cong = ( + await testDb.congregation.create({ data: { name: `Engagement ${ts}`, slug: `engagement-${ts}`, active: true } }) + ).id + await withScope(ids.cong, async tx => { + const congregationId = ids.cong + ids.member = (await tx.member.create({ data: { firstname: 'Paul', lastname: 'MARTIN', congregationId } })).id + // One meeting done, one to come; each with two parts and a service created in an order the programme does not + // follow. + for (const day of ['2027-02-23T18:00:00Z', '2027-03-09T18:00:00Z']) { + const startDate = new Date(day) + const event = await tx.event.create({ + data: { name: 'Réunion', startDate, endDate: startDate, status: 'released', congregationId }, + }) + const held = { eventId: event.id, assigneeId: ids.member, congregationId } + await tx.eventServicePart.create({ data: { name: 'Sono', order: 0, ...held } }) + await tx.eventPart.create({ data: { name: 'Cantique de conclusion', order: 20, ...held } }) + await tx.eventPart.create({ data: { name: 'Cantique et prière', order: 0, ...held } }) + } + }) +}) + +afterAll(async () => { + if (ids.cong) { + await withScope(ids.cong, async tx => { + await tx.event.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.deleteMany({ where: { id: ids.cong } }) + } + await testDb.$disconnect() +}) + +describe('a publisher’s assignments within one meeting', () => { + it('lists the coming ones in the programme’s order: parts, then services', async () => { + const upcoming = await withScope(ids.cong, tx => + findUpcomingAssignmentsForMember(tx, ids.member as never, ids.cong as never, NOW), + ) + + expect(upcoming.map(assignment => assignment.partName)).toEqual([ + 'Cantique et prière', + 'Cantique de conclusion', + 'Sono', + ]) + }) + + it('names the first of the meeting’s parts as the last assignment done', async () => { + const last = await withScope(ids.cong, tx => + findLastAssignmentsForMembers(tx, [ids.member as never], ids.cong as never, NOW), + ) + + expect(last.get(ids.member as never)?.partName).toBe('Cantique et prière') + }) +}) diff --git a/app/features/events/server/member-engagement.queries.ts b/app/features/events/server/member-engagement.queries.ts index 5e2fe90e..39b6a29e 100644 --- a/app/features/events/server/member-engagement.queries.ts +++ b/app/features/events/server/member-engagement.queries.ts @@ -1,3 +1,4 @@ +import type { Prisma } from '~/database/generated/client' import { EventStatus } from '~/features/events/model/event-status.type' import { EventTemplateKey } from '~/features/events/model/event-template.type' import type { MemberAbsence, MemberAssignment } from '~/features/events/model/member-engagement.type' @@ -6,6 +7,15 @@ import type { CongregationId, MemberId } from '~/shared/types/branded' const MAX_ASSIGNMENTS = 5 +/** + * One meeting's assignments in the programme's order, so a record reads the same every time: the date sort below is + * stable, so parts then services, each in theirs; the last assignment done keeps the first of a meeting's. + */ +const PROGRAMME_ORDER = [{ event: { startDate: 'asc' } }, { order: 'asc' }, { id: 'asc' }] as const satisfies ( + | Prisma.EventPartOrderByWithRelationInput + | Prisma.EventServicePartOrderByWithRelationInput +)[] + /** * Upcoming released parts and service parts a member holds (as assignee or * assistant), for the publisher record page. Read-only companion to the @@ -34,13 +44,13 @@ export async function findUpcomingAssignmentsForMember( db.eventPart.findMany({ where: { OR: [{ assigneeId: memberId }, { assistantId: memberId }], event: eventFilter }, select, - orderBy: { event: { startDate: 'asc' } }, + orderBy: PROGRAMME_ORDER, take: MAX_ASSIGNMENTS, }), db.eventServicePart.findMany({ where: { assigneeId: memberId, event: eventFilter }, select, - orderBy: { event: { startDate: 'asc' } }, + orderBy: PROGRAMME_ORDER, take: MAX_ASSIGNMENTS, }), ]) @@ -118,10 +128,12 @@ export async function findLastAssignmentsForMembers( db.eventPart.findMany({ where: { OR: [{ assigneeId: { in: memberIds } }, { assistantId: { in: memberIds } }], event }, select: { name: true, assigneeId: true, assistantId: true, event: { select: { startDate: true } } }, + orderBy: PROGRAMME_ORDER, }), db.eventServicePart.findMany({ where: { assigneeId: { in: memberIds }, event }, select: { name: true, assigneeId: true, event: { select: { startDate: true } } }, + orderBy: PROGRAMME_ORDER, }), ]) From 14c469e5705fb1e35ce73e8a1380f60f447713ac Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:28:35 +0100 Subject: [PATCH 02/11] feat(db): record who created each event: the job, a person or a restore MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Event.origin (job, manual, import; CHECK, default manual). Events without an author and with nothing on them — the empty meetings the recurring-events job created — become the job's. --- .../migration.sql | 20 +++ .../add-event-origin.integration.test.ts | 116 ++++++++++++++++++ app/database/schema.prisma | 3 + app/features/events/index.ts | 1 + .../events/model/event-origin.type.ts | 20 +++ 5 files changed, 160 insertions(+) create mode 100644 app/database/migrations/20261119120000_add_event_origin/migration.sql create mode 100644 app/database/migrations/add-event-origin.integration.test.ts create mode 100644 app/features/events/model/event-origin.type.ts diff --git a/app/database/migrations/20261119120000_add_event_origin/migration.sql b/app/database/migrations/20261119120000_add_event_origin/migration.sql new file mode 100644 index 00000000..6dd1b1f0 --- /dev/null +++ b/app/database/migrations/20261119120000_add_event_origin/migration.sql @@ -0,0 +1,20 @@ +-- Who created an event: the recurring-events job (« job »), a person (« manual ») or a restore (« import »). Until now +-- an event without an author stood for one the job made, but deleting an account clears the author of what it +-- created, and a hand-made event must never become an empty meeting a template moves or deletes. No change in what +-- anyone may do. +-- +-- 1. The column. The previous image creates events with the default during the rollout; its empty meetings are given +-- « job » by a second run of step 2 in a later migration. +ALTER TABLE "Event" ADD COLUMN IF NOT EXISTS "origin" TEXT NOT NULL DEFAULT 'manual'; + +ALTER TABLE "Event" DROP CONSTRAINT IF EXISTS "Event_origin_check"; +ALTER TABLE "Event" ADD CONSTRAINT "Event_origin_check" CHECK ("origin" IN ('job', 'manual', 'import')); + +-- 2. The job's events: no author, no part, no service, no attendance — exactly what an empty meeting was until now. +UPDATE "Event" AS event +SET "origin" = 'job' +WHERE event."createdById" IS NULL + AND event."origin" = 'manual' + AND NOT EXISTS (SELECT 1 FROM "EventPart" part WHERE part."eventId" = event."id") + AND NOT EXISTS (SELECT 1 FROM "EventServicePart" service WHERE service."eventId" = event."id") + AND NOT EXISTS (SELECT 1 FROM "Attendance" attendance WHERE attendance."eventId" = event."id"); diff --git a/app/database/migrations/add-event-origin.integration.test.ts b/app/database/migrations/add-event-origin.integration.test.ts new file mode 100644 index 00000000..47d8496c --- /dev/null +++ b/app/database/migrations/add-event-origin.integration.test.ts @@ -0,0 +1,116 @@ +import { readFileSync } from 'node:fs' +import { join } from 'node:path' +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// Runs against DB_URL rather than DB_RUNTIME_URL: a migration executes as the schema owner. Its statements are read from +// the shipped file and run inside a rolled-back transaction. +const adapter = new PrismaPg({ connectionString: process.env.DB_URL, max: 3, connectionTimeoutMillis: 5000 }) +const testDb = new PrismaClient({ adapter }) + +const STATEMENTS = readFileSync(join(import.meta.dirname, '20261119120000_add_event_origin', 'migration.sql'), 'utf8') + .split('\n') + .filter(line => !line.trimStart().startsWith('--')) + .join('\n') + .split(';') + .map(statement => statement.trim()) + .filter(statement => statement.length > 0) + +class Rollback extends Error {} + +interface Result { + first: Record + second: Record + bogusRefused: boolean +} + +let memo: Promise | undefined + +/** Events in the shape the previous image leaves them: every one at the column's default, « manual ». */ +function snapshot(): Promise { + memo ??= (async () => { + let result: Result | undefined + try { + await testDb.$transaction(async tx => { + const stamp = `event-origin-${process.pid}-${globalThis.performance.now().toString().replace('.', '')}` + const congregationId = (await tx.congregation.create({ data: { name: stamp, slug: stamp, active: true } })).id + const author = await tx.userAccount.create({ + data: { email: `${stamp}@test.com`, password: 'x', congregationId }, + }) + const day = new Date('2026-12-03T18:00:00Z') + const event = (name: string, createdById: number | null) => + tx.event.create({ data: { name, startDate: day, endDate: day, createdById, congregationId } }) + + const ids = { + emptyJob: (await event('empty, no author', null)).id, + withPart: (await event('a part, no author', null)).id, + withService: (await event('a service, no author', null)).id, + withCounts: (await event('counts, no author', null)).id, + handMade: (await event('empty, an author', author.id)).id, + } + await tx.eventPart.create({ data: { name: 'Cantique', eventId: ids.withPart, congregationId } }) + await tx.eventServicePart.create({ data: { name: 'Sono', eventId: ids.withService, congregationId } }) + await tx.attendance.create({ data: { eventId: ids.withCounts, inPerson: 40, congregationId } }) + + const read = async () => { + const rows = await tx.event.findMany({ where: { congregationId }, select: { id: true, origin: true } }) + const byId = new Map(rows.map(row => [row.id, row.origin])) + return Object.fromEntries(Object.entries(ids).map(([name, id]) => [name, byId.get(id) ?? ''])) + } + + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + const first = await read() + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + const second = await read() + + let bogusRefused = false + try { + await tx.$executeRawUnsafe('SAVEPOINT bogus') + await tx.$executeRawUnsafe(`UPDATE "Event" SET "origin" = 'bogus' WHERE "id" = ${ids.handMade}`) + } catch { + bogusRefused = true + } finally { + await tx.$executeRawUnsafe('ROLLBACK TO SAVEPOINT bogus') + } + + result = { first, second, bogusRefused } + throw new Rollback() + }) + } catch (error) { + if (!(error instanceof Rollback)) throw error + } + return result as Result + })() + return memo +} + +afterAll(async () => { + await testDb.$disconnect() +}) + +describe('20261119120000_add_event_origin', () => { + it('marks as the job’s only the events that were empty meetings: no author, nothing on them', async () => { + const { first } = await snapshot() + + expect(first).toEqual({ + emptyJob: 'job', + withPart: 'manual', + withService: 'manual', + withCounts: 'manual', + handMade: 'manual', + }) + }) + + it('changes nothing when run twice', async () => { + const { first, second } = await snapshot() + + expect(second).toEqual(first) + }) + + it('refuses an origin it does not know', async () => { + const { bogusRefused } = await snapshot() + + expect(bogusRefused).toBe(true) + }) +}) diff --git a/app/database/schema.prisma b/app/database/schema.prisma index f131474e..ab712f40 100644 --- a/app/database/schema.prisma +++ b/app/database/schema.prisma @@ -1031,6 +1031,9 @@ model Event { // an account is deleted. createdBy UserAccount? @relation("createdBy", fields: [createdById], references: [id], onDelete: Restrict) createdById Int? + // Who created it: the recurring-events job (« job »), a person (« manual ») or a restore (« import »). Only the + // job's empty meetings move with their template or go with it; the author only says who prepared it. + origin String @default("manual") createdAt DateTime @default(now()) updatedAt DateTime @updatedAt diff --git a/app/features/events/index.ts b/app/features/events/index.ts index 13b70293..b3cb2ca5 100644 --- a/app/features/events/index.ts +++ b/app/features/events/index.ts @@ -17,6 +17,7 @@ export { parseAttendanceKind, } from './model/attendance-kind.type' export { dayLabel, dayLabelShort } from './model/day-label' +export { EVENT_ORIGINS, EventOrigin, isEventOrigin } from './model/event-origin.type' export { EventStatus } from './model/event-status.type' export { EventTemplateKey, isSystemTemplate } from './model/event-template.type' export { groupPartsBySlot } from './model/group-parts-by-slot' diff --git a/app/features/events/model/event-origin.type.ts b/app/features/events/model/event-origin.type.ts new file mode 100644 index 00000000..34906059 --- /dev/null +++ b/app/features/events/model/event-origin.type.ts @@ -0,0 +1,20 @@ +// Who created an event (Event.origin). Only the job's events, while empty, move with their template or go with it: an +// event someone made or prepared stays where it is, whatever happens to its author's account. A meeting the job made +// becomes « manual » once someone prepares it or moves it. + +export const EventOrigin = { + /** Created ahead by the recurring-events job. */ + Job: 'job', + /** Created by a person, or a job meeting someone prepared or moved. */ + Manual: 'manual', + /** Restored from an archive that did not say. */ + Import: 'import', +} as const + +export type EventOrigin = (typeof EventOrigin)[keyof typeof EventOrigin] + +export const EVENT_ORIGINS: readonly EventOrigin[] = [EventOrigin.Job, EventOrigin.Manual, EventOrigin.Import] + +export function isEventOrigin(value: unknown): value is EventOrigin { + return typeof value === 'string' && (EVENT_ORIGINS as readonly string[]).includes(value) +} From 71bf0a0079fe2e2899b767a1a932ae5c9e99c960 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:28:46 +0100 Subject: [PATCH 03/11] fix(events): tell the job's empty meetings by their origin, not by a missing author MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only the job's empty meetings move with their template or go with it. They were told apart by having no author, but clearing an author — deleting an account — would have turned a hand-made event into one. The job writes « job »; preparing a job meeting's programme or moving it by hand makes it « manual »; every check reads the origin. --- app/features/events/index.server.ts | 2 +- .../create-meeting-programme.server.test.ts | 2 +- .../server/create-meeting-programme.server.ts | 7 ++-- .../server/delete-template.server.test.ts | 2 +- .../server/empty-meetings.integration.test.ts | 36 +++++++++++++++++-- .../events/server/empty-meetings.queries.ts | 8 +++-- .../events/server/event-parts.server.test.ts | 4 +-- .../events/server/event-parts.server.ts | 6 +++- .../server/programme-creation.server.test.ts | 24 ++++++++++--- .../server/programme-creation.server.ts | 18 ++++++---- .../server/recurring-events.server.test.ts | 4 ++- .../events/server/recurring-events.server.ts | 8 ++--- .../server/template-page.queries.test.ts | 6 +++- .../settings/server/template-page.queries.ts | 4 +-- 14 files changed, 98 insertions(+), 33 deletions(-) diff --git a/app/features/events/index.server.ts b/app/features/events/index.server.ts index 6cfe443c..971532f9 100644 --- a/app/features/events/index.server.ts +++ b/app/features/events/index.server.ts @@ -4,7 +4,7 @@ export { type LastWeekMeeting, listLastWeekAttendance, listMeetingsUnderWay } fr export { getNextDaysOffs } from './server/days-off.server' export { deleteTemplate } from './server/delete-template.server' export { duplicateTemplate } from './server/duplicate-template.server' -export { countMeetingsToMove } from './server/empty-meetings.queries' +export { countMeetingsToMove, EMPTY_MEETING } from './server/empty-meetings.queries' export { deleteTemplatePart, deleteTemplateServicePart, diff --git a/app/features/events/server/create-meeting-programme.server.test.ts b/app/features/events/server/create-meeting-programme.server.test.ts index 3b8292c4..fd45aea1 100644 --- a/app/features/events/server/create-meeting-programme.server.test.ts +++ b/app/features/events/server/create-meeting-programme.server.test.ts @@ -55,7 +55,7 @@ describe('createMeetingProgramme', () => { expect(db.event.update).toHaveBeenCalledWith({ where: { id_congregationId: { id: 55, congregationId: 7 } }, - data: { createdById: 42 }, + data: { createdById: 42, origin: 'manual' }, }) }) diff --git a/app/features/events/server/create-meeting-programme.server.ts b/app/features/events/server/create-meeting-programme.server.ts index 7afd254b..4658e882 100644 --- a/app/features/events/server/create-meeting-programme.server.ts +++ b/app/features/events/server/create-meeting-programme.server.ts @@ -1,3 +1,4 @@ +import { EventOrigin } from '~/features/events/model/event-origin.type' import { isSystemTemplate } from '~/features/events/model/event-template.type' import { giveProgramme, lockTemplates, TEMPLATE_INCLUDE } from '~/features/events/server/give-programme.server' import { @@ -33,6 +34,7 @@ export async function createMeetingProgramme( templateId: true, startDate: true, createdById: true, + origin: true, _count: { select: { eventParts: true, eventServiceParts: true } }, }, }) @@ -45,10 +47,11 @@ export async function createMeetingProgramme( if (template.parts.length === 0 && template.serviceParts.length === 0) return null if (event._count.eventParts > 0 || event._count.eventServiceParts > 0) throw new ProgrammeExistsError(event.id) - if (event.createdById == null) { + // Whoever gives it its programme prepares it; a meeting the job made is theirs from then on. + if (event.createdById == null || event.origin === EventOrigin.Job) { await db.event.update({ where: { id_congregationId: { id: event.id, congregationId } }, - data: { createdById: ctx.actorId }, + data: { createdById: event.createdById ?? ctx.actorId, origin: EventOrigin.Manual }, }) } return giveProgramme(db, template, event.id, dayOf(event.startDate, ctx.timezone), ctx, { reused: true }) diff --git a/app/features/events/server/delete-template.server.test.ts b/app/features/events/server/delete-template.server.test.ts index ef3632b6..0e38bfef 100644 --- a/app/features/events/server/delete-template.server.test.ts +++ b/app/features/events/server/delete-template.server.test.ts @@ -52,7 +52,7 @@ describe('deleteTemplate', () => { const result = await deleteTemplate(db, 7, 1, 9) const empty = { - createdById: null, + origin: 'job', eventParts: { none: {} }, eventServiceParts: { none: {} }, attendance: { is: null }, diff --git a/app/features/events/server/empty-meetings.integration.test.ts b/app/features/events/server/empty-meetings.integration.test.ts index c79ee3b3..92ef325e 100644 --- a/app/features/events/server/empty-meetings.integration.test.ts +++ b/app/features/events/server/empty-meetings.integration.test.ts @@ -32,6 +32,7 @@ const { moveEmptyMeetings } = await import('./move-empty-meetings.server') const { createMeetingProgramme } = await import('./create-meeting-programme.server') const { listProgrammes } = await import('./programme-list.queries') const { ProgrammeExistsError } = await import('./programme-creation.server') +const { updateEvent } = await import('./event-parts.server') const PARIS = 'Europe/Paris' // Monday 16 November 2026, 10:00 in Paris. @@ -66,9 +67,18 @@ beforeAll(async () => { }, }) ).id + // The job's meetings: no author, nothing on them. const meeting = (day: string, extra: object = {}) => tx.event.create({ - data: { name: 'Réunion de semaine', templateId, status: 'draft', congregationId, ...tuesday(day), ...extra }, + data: { + name: 'Réunion de semaine', + templateId, + status: 'draft', + origin: 'job', + congregationId, + ...tuesday(day), + ...extra, + }, }) ids.week1 = (await meeting('2026-11-17')).id ids.week2 = (await meeting('2026-11-24')).id @@ -76,6 +86,8 @@ beforeAll(async () => { // Counted already: attendance keeps a meeting where it is. ids.counted = (await meeting('2026-12-08')).id await tx.attendance.create({ data: { eventId: ids.counted, inPerson: 80, congregationId } }) + // Made by hand, its author's account since deleted: empty and without an author, but nobody's to move or delete. + ids.handMade = (await meeting('2026-12-15', { origin: 'manual' })).id // The week of 30 November already has its programme on the Thursday. ids.prepared = ( await tx.event.create({ @@ -121,6 +133,22 @@ const days = () => ) describe('empty meetings against the database', () => { + it('makes a meeting the job created someone’s once they move it by hand', async () => { + const id = await withScope(congregationId, async tx => { + const meeting = await tx.event.create({ + data: { name: 'Réunion', templateId, status: 'draft', origin: 'job', congregationId, ...tuesday('2027-01-05') }, + }) + await updateEvent(tx, meeting.id, congregationId, tuesday('2027-01-06'), actorId) + return meeting.id + }) + + const moved = await withScope(congregationId, tx => + tx.event.findFirst({ where: { id }, select: { origin: true, createdById: true } }), + ) + expect(moved).toEqual({ origin: 'manual', createdById: actorId }) + await withScope(congregationId, tx => tx.event.delete({ where: { id } })) + }) + it('lists the empty meetings as waiting for their programme, and not the prepared or counted ones', async () => { const rows = await withScope(congregationId, tx => listProgrammes(tx, { congregationId, from: NOW, to: new Date('2026-12-31T00:00:00Z') }), @@ -142,6 +170,7 @@ describe('empty meetings against the database', () => { expect(after[ids.week3]).toBeUndefined() expect(after[ids.counted]).toBe('2026-12-08') expect(after[ids.prepared]).toBe('2026-12-03') + expect(after[ids.handMade]).toBe('2026-12-15') expect(await withScope(congregationId, tx => countMeetingsToMove(tx, templateId, ctx()))).toBe(0) }) @@ -154,10 +183,11 @@ describe('empty meetings against the database', () => { const event = await withScope(congregationId, tx => tx.event.findFirst({ where: { id: ids.week1 }, - select: { createdById: true, _count: { select: { eventParts: true } } }, + select: { createdById: true, origin: true, _count: { select: { eventParts: true } } }, }), ) - expect(event).toEqual({ createdById: actorId, _count: { eventParts: 1 } }) + // Prepared by someone: theirs from now on, even emptied again or once their account goes. + expect(event).toEqual({ createdById: actorId, origin: 'manual', _count: { eventParts: 1 } }) await expect( withScope(congregationId, tx => diff --git a/app/features/events/server/empty-meetings.queries.ts b/app/features/events/server/empty-meetings.queries.ts index fa49fea5..e5459e95 100644 --- a/app/features/events/server/empty-meetings.queries.ts +++ b/app/features/events/server/empty-meetings.queries.ts @@ -1,14 +1,16 @@ import { planMeetingMoves } from '~/features/events/model/empty-meetings' +import { EventOrigin } from '~/features/events/model/event-origin.type' import { EventStatus } from '~/features/events/model/event-status.type' import type { TransactionClient } from '~/shared/infra/db.server' import { addDays, dayOf, startOfDay } from '~/shared/utils/calendar-day' /** - * An empty meeting the recurring-events job created ahead: no author, no part, no service, no attendance. Every - * recurring template has some; they are the only events that move with it, or go with it. + * An empty meeting the recurring-events job created ahead: its origin, no part, no service, no attendance. Every + * recurring template has some; they are the only events that move with it, or go with it. Not its author: deleting an + * account clears the author of what it made, which must never turn into something a template may move or delete. */ export const EMPTY_MEETING = { - createdById: null, + origin: EventOrigin.Job, eventParts: { none: {} }, eventServiceParts: { none: {} }, attendance: { is: null }, diff --git a/app/features/events/server/event-parts.server.test.ts b/app/features/events/server/event-parts.server.test.ts index 80d22fdb..27520ebd 100644 --- a/app/features/events/server/event-parts.server.test.ts +++ b/app/features/events/server/event-parts.server.test.ts @@ -183,8 +183,8 @@ describe('updateEvent', () => { await updateEvent(mockDb as never, 2, 10, { startDate: new Date('2026-11-17T18:00:00Z') }, 99) expect(mockDb.event.updateMany).toHaveBeenCalledWith({ - where: { id: 2, congregationId: 10, createdById: null }, - data: { createdById: 99 }, + where: { id: 2, congregationId: 10, origin: 'job' }, + data: { origin: 'manual', createdById: 99 }, }) }) diff --git a/app/features/events/server/event-parts.server.ts b/app/features/events/server/event-parts.server.ts index 47f78264..c57fcea3 100644 --- a/app/features/events/server/event-parts.server.ts +++ b/app/features/events/server/event-parts.server.ts @@ -1,3 +1,4 @@ +import { EventOrigin } from '~/features/events/model/event-origin.type' import { EventTemplateKey } from '~/features/events/model/event-template.type' import { setPartAssignmentAllowedRoles, @@ -60,7 +61,10 @@ export async function updateEvent( // A meeting created ahead that someone moves is theirs from then on: the template's offer to move its upcoming // meetings, and the clean-ups of meetings nobody created, leave it where it was put. if (data.startDate !== undefined || data.endDate !== undefined) { - await db.event.updateMany({ where: { id, congregationId, createdById: null }, data: { createdById: actorId } }) + await db.event.updateMany({ + where: { id, congregationId, origin: EventOrigin.Job }, + data: { origin: EventOrigin.Manual, createdById: actorId }, + }) } const event = await db.event.update({ where: { id_congregationId: { id, congregationId } }, data }) audit({ diff --git a/app/features/events/server/programme-creation.server.test.ts b/app/features/events/server/programme-creation.server.test.ts index cec5796e..f2f660d7 100644 --- a/app/features/events/server/programme-creation.server.test.ts +++ b/app/features/events/server/programme-creation.server.test.ts @@ -105,7 +105,7 @@ const WITH_PART = { }, ], } -const BARE = { createdById: null, attendance: null, _count: { eventParts: 0, eventServiceParts: 0 } } +const BARE = { createdById: null, origin: 'job', attendance: null, _count: { eventParts: 0, eventServiceParts: 0 } } describe('bare events', () => { it('gives a bare event of the series its programme instead of creating a second one', async () => { @@ -184,7 +184,7 @@ describe('bare events, edge cases', () => { expect(vi.mocked(db.event.update).mock.calls[0]?.[0]).toMatchObject({ where: { id_congregationId: { id: 55, congregationId: 7 } }, - data: { name: 'Réunion de semaine', createdById: 42 }, + data: { name: 'Réunion de semaine', createdById: 42, origin: 'manual' }, }) expect(hour(vi.mocked(db.event.update).mock.calls[0]?.[0]?.data?.startDate as Date)).toBe('19:00') }) @@ -193,7 +193,14 @@ describe('bare events, edge cases', () => { it('fills a meeting whose programme was removed, and one with counts, when asked for the series', async () => { vi.mocked(db.eventTemplate.findMany).mockResolvedValue([WITH_PART] as never) vi.mocked(db.event.findMany).mockResolvedValue([ - { id: 55, templateId: 270, startDate: new Date('2026-11-19T23:00:00Z'), ...BARE, createdById: 9 }, + { + id: 55, + templateId: 270, + startDate: new Date('2026-11-19T23:00:00Z'), + ...BARE, + createdById: 9, + origin: 'manual', + }, { id: 56, templateId: 270, startDate: new Date('2026-11-26T23:00:00Z'), ...BARE, attendance: { id: 1 } }, ] as never) recordEvents() @@ -207,7 +214,14 @@ describe('bare events, edge cases', () => { it('keeps the author, name and hours of a meeting someone prepared before', async () => { vi.mocked(db.eventTemplate.findMany).mockResolvedValue([WITH_PART] as never) vi.mocked(db.event.findMany).mockResolvedValue([ - { id: 55, templateId: 270, startDate: new Date('2026-11-19T23:00:00Z'), ...BARE, createdById: 9 }, + { + id: 55, + templateId: 270, + startDate: new Date('2026-11-19T23:00:00Z'), + ...BARE, + createdById: 9, + origin: 'manual', + }, ] as never) recordEvents() @@ -238,7 +252,7 @@ describe('bare events, edge cases', () => { it('fills a counted meeting without a programme when created on its day', async () => { vi.mocked(db.eventTemplate.findFirst).mockResolvedValue(WITH_PART as never) vi.mocked(db.event.findMany).mockResolvedValue([ - { id: 56, ...BARE, createdById: 9, attendance: { id: 1 } }, + { id: 56, ...BARE, createdById: 9, origin: 'manual', attendance: { id: 1 } }, ] as never) recordEvents() diff --git a/app/features/events/server/programme-creation.server.ts b/app/features/events/server/programme-creation.server.ts index 162bbe40..4f061b85 100644 --- a/app/features/events/server/programme-creation.server.ts +++ b/app/features/events/server/programme-creation.server.ts @@ -1,3 +1,4 @@ +import { EventOrigin } from '~/features/events/model/event-origin.type' import { SYSTEM_TEMPLATE_KEYS } from '~/features/events/model/event-template.type' import { daysOnWeekday, programmeKey } from '~/features/events/model/programme-dates' import { @@ -153,20 +154,21 @@ async function removeEmptyMeeting(db: TransactionClient, eventId: number, ctx: C async function fillMeeting( db: TransactionClient, template: TemplateWithRelations, - event: { id: number; createdById?: number | null }, + event: { id: number; origin?: string }, day: string, ctx: CreationContext, ): Promise { const eventId = event.id - if (event.createdById != null) return giveProgramme(db, template, eventId, day, ctx, { reused: true }) + if (event.origin !== EventOrigin.Job) return giveProgramme(db, template, eventId, day, ctx, { reused: true }) await db.event.update({ where: { id_congregationId: { id: eventId, congregationId: ctx.congregationId } }, data: { name: template.name, startDate: combineLocalDateTime(day, template.startTime, ctx.timezone), endDate: combineLocalDateTime(day, template.endTime, ctx.timezone), - // Whoever gives it its programme prepares it: the meeting is no longer one nobody created. + // Whoever gives it its programme prepares it: the meeting is no longer the job’s. createdById: ctx.actorId, + origin: EventOrigin.Manual, }, }) return giveProgramme(db, template, eventId, day, ctx, { reused: true }) @@ -212,12 +214,14 @@ export async function createProgrammeOnDay( const EVENT_STATE = { id: true, createdById: true, + origin: true, attendance: { select: { id: true } }, _count: { select: { eventParts: true, eventServiceParts: true } }, } as const interface EventState { createdById?: number | null + origin?: string attendance?: { id: number } | null _count?: { eventParts: number; eventServiceParts: number } } @@ -228,11 +232,11 @@ function hasParts(event: EventState): boolean { } /** - * An empty meeting the recurring-events job created ahead: no author, no programme, no attendance. Only those may be - * deleted when a series passes their day — one someone prepared, or one with counts, stays. + * An empty meeting the recurring-events job created ahead (EMPTY_MEETING): its origin, no programme, no attendance. Only + * those may be deleted when a series passes their day — one someone made or prepared, or one with counts, stays. */ function isEmptyMeeting(event: EventState): boolean { - return event.createdById === null && event.attendance == null && !hasParts(event) + return event.origin === EventOrigin.Job && event.attendance == null && !hasParts(event) } /** The events the templates already have between two days, by `programmeKey`: whether each has a programme, and whether @@ -240,6 +244,7 @@ function isEmptyMeeting(event: EventState): boolean { interface ExistingEvent { id: number createdById: number | null + origin: string /** It has parts or services. */ programme: boolean /** An empty meeting created ahead, which a passed day deletes. */ @@ -271,6 +276,7 @@ async function existingProgrammes( byDay.set(key, { id: event.id, createdById: event.createdById, + origin: event.origin, programme: hasParts(event), empty: isEmptyMeeting(event), }) diff --git a/app/features/events/server/recurring-events.server.test.ts b/app/features/events/server/recurring-events.server.test.ts index 9df36dd1..bfbc2098 100644 --- a/app/features/events/server/recurring-events.server.test.ts +++ b/app/features/events/server/recurring-events.server.test.ts @@ -64,6 +64,7 @@ describe('extendRecurringEvents', () => { endDate: new Date('2027-01-07T19:45:00Z'), status: 'draft', createdById: null, + origin: 'job', congregationId: 1, }, { @@ -73,6 +74,7 @@ describe('extendRecurringEvents', () => { endDate: new Date('2027-01-14T19:45:00Z'), status: 'draft', createdById: null, + origin: 'job', congregationId: 1, }, ]) @@ -182,7 +184,7 @@ describe('reanchorEmptyMeetings', () => { const [[{ where }]] = mockDb.event.findMany.mock.calls expect(where).toMatchObject({ congregationId: 1, - createdById: null, + origin: 'job', eventParts: { none: {} }, eventServiceParts: { none: {} }, attendance: { is: null }, diff --git a/app/features/events/server/recurring-events.server.ts b/app/features/events/server/recurring-events.server.ts index 66c22386..103adff1 100644 --- a/app/features/events/server/recurring-events.server.ts +++ b/app/features/events/server/recurring-events.server.ts @@ -1,6 +1,8 @@ +import { EventOrigin } from '~/features/events/model/event-origin.type' import { EventStatus } from '~/features/events/model/event-status.type' import { SYSTEM_TEMPLATE_KEYS } from '~/features/events/model/event-template.type' import { planRecurringEvents } from '~/features/events/model/recurring-events' +import { EMPTY_MEETING } from '~/features/events/server/empty-meetings.queries' import { AuditAction, auditInTransaction } from '~/shared/domain/audit.server' import type { TransactionClient } from '~/shared/infra/db.server' import { createLogger } from '~/shared/infra/logger.server' @@ -36,6 +38,7 @@ export async function createEmptyMeetings( endDate: combineLocalDateTime(day, template.endTime, timeZone), status: EventStatus.Draft, createdById: null, + origin: EventOrigin.Job, congregationId, })), }) @@ -146,10 +149,7 @@ export async function reanchorEmptyMeetings( const meetings = await db.event.findMany({ where: { congregationId, - createdById: null, - eventParts: { none: {} }, - eventServiceParts: { none: {} }, - attendance: { is: null }, + ...EMPTY_MEETING, templateId: { not: null }, startDate: { gte: input.now }, }, diff --git a/app/features/settings/server/template-page.queries.test.ts b/app/features/settings/server/template-page.queries.test.ts index 20dfc0d9..e06cf729 100644 --- a/app/features/settings/server/template-page.queries.test.ts +++ b/app/features/settings/server/template-page.queries.test.ts @@ -1,6 +1,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -vi.mock('~/features/events/index.server', () => ({ getTemplateById: vi.fn(), listPartPresets: vi.fn() })) +vi.mock('~/features/events/index.server', async () => ({ + EMPTY_MEETING: (await import('~/features/events/server/empty-meetings.queries')).EMPTY_MEETING, + getTemplateById: vi.fn(), + listPartPresets: vi.fn(), +})) vi.mock('~/shared/domain/roles.server', () => ({ listRoles: vi.fn(), listDelegatableRoles: vi.fn() })) vi.mock('~/shared/auth/permissions.server', () => ({ findMembersWithAnyRole: vi.fn() })) diff --git a/app/features/settings/server/template-page.queries.ts b/app/features/settings/server/template-page.queries.ts index 903801aa..2ef08173 100644 --- a/app/features/settings/server/template-page.queries.ts +++ b/app/features/settings/server/template-page.queries.ts @@ -1,5 +1,5 @@ import { findResponsible, ResponsibilityScope } from '~/features/events' -import { getTemplateById, listPartPresets } from '~/features/events/index.server' +import { EMPTY_MEETING, getTemplateById, listPartPresets } from '~/features/events/index.server' import { findMembersWithAnyRole } from '~/shared/auth/permissions.server' import { listDelegatableRoles, listRoles } from '~/shared/domain/roles.server' import type { TransactionClient } from '~/shared/infra/db.server' @@ -69,7 +69,7 @@ export async function getTemplatePage( where: { templateId, congregationId, - NOT: { createdById: null, eventParts: { none: {} }, eventServiceParts: { none: {} }, attendance: { is: null } }, + NOT: EMPTY_MEETING, }, }), listRoles(db, congregationId), From 6115737172bb66eeee0475ae0cf72cbf6e916906 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:29:01 +0100 Subject: [PATCH 04/11] fix(settings): delete an account without failing on the events it created MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deleting an account ended in a foreign-key error on any event it had created. An account without a record now takes its absences with it, and its other events lose their author and keep their origin, so a hand-made one stays where it is. An account linked to a record that has absences is refused: « Ce compte a des absences », until they can be handed to the record. --- .../routes/_account-refusal.server.test.ts | 10 +- .../routes/_account-refusal.server.ts | 2 + .../delete-account.server.integration.test.ts | 134 ++++++++++++++++++ .../server/delete-account.server.test.ts | 6 +- .../settings/server/delete-account.server.ts | 23 ++- app/i18n/messages/en.json | 1 + app/i18n/messages/fr.json | 1 + app/i18n/messages/pt-PT.json | 1 + 8 files changed, 173 insertions(+), 5 deletions(-) create mode 100644 app/features/settings/server/delete-account.server.integration.test.ts diff --git a/app/features/settings/routes/_account-refusal.server.test.ts b/app/features/settings/routes/_account-refusal.server.test.ts index 3799e5b8..2aa60e55 100644 --- a/app/features/settings/routes/_account-refusal.server.test.ts +++ b/app/features/settings/routes/_account-refusal.server.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest' +import { AccountHasAbsencesError } from '~/features/settings/server/delete-account.server' import { LastAdminError } from '~/shared/auth/permissions.server' import { OwnAccountError } from '~/shared/domain/account-protection.server' import { GrantBeyondActorError } from '~/shared/domain/role-grant-limits.server' @@ -6,9 +7,14 @@ import { accountRefusal } from './_account-refusal.server' describe('accountRefusal', () => { it('says why an action on an account was refused', () => { - const refusals = [new OwnAccountError(), new LastAdminError(), new GrantBeyondActorError()].map(accountRefusal) + const refusals = [ + new OwnAccountError(), + new LastAdminError(), + new GrantBeyondActorError(), + new AccountHasAbsencesError(), + ].map(accountRefusal) expect(refusals.every(text => typeof text === 'string' && text.length > 0)).toBe(true) - expect(new Set(refusals).size).toBe(3) + expect(new Set(refusals).size).toBe(4) }) it('says nothing for an error that is not a refusal', () => { diff --git a/app/features/settings/routes/_account-refusal.server.ts b/app/features/settings/routes/_account-refusal.server.ts index 44bbcc74..0511ec46 100644 --- a/app/features/settings/routes/_account-refusal.server.ts +++ b/app/features/settings/routes/_account-refusal.server.ts @@ -1,3 +1,4 @@ +import { AccountHasAbsencesError } from '~/features/settings/server/delete-account.server' import * as m from '~/i18n/paraglide/messages' import { LastAdminError } from '~/shared/auth/permissions.server' import { OwnAccountError } from '~/shared/domain/account-protection.server' @@ -8,5 +9,6 @@ export function accountRefusal(error: unknown): string | null { if (error instanceof OwnAccountError) return m.settings_user_own_account() if (error instanceof LastAdminError) return m.settings_user_last_admin() if (error instanceof GrantBeyondActorError) return m.settings_user_admin_only() + if (error instanceof AccountHasAbsencesError) return m.settings_user_has_absences() return null } diff --git a/app/features/settings/server/delete-account.server.integration.test.ts b/app/features/settings/server/delete-account.server.integration.test.ts new file mode 100644 index 00000000..06c45e8c --- /dev/null +++ b/app/features/settings/server/delete-account.server.integration.test.ts @@ -0,0 +1,134 @@ +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// Deleting an account must not end in a foreign-key error on the events it created. Its absences go with it when it +// has no record: they belong to nobody else. An account linked to a record keeps them, so it is refused until they can +// be handed to the record. Its other events lose their author and stay what they were: a hand-made event never becomes +// an empty meeting a template may move or delete. + +const adapter = new PrismaPg({ + connectionString: process.env.DB_RUNTIME_URL ?? process.env.DB_URL, + max: 3, + connectionTimeoutMillis: 5000, +}) +const testDb = new PrismaClient({ adapter }) + +type Tx = Parameters[0]>[0] + +function withScope(congregationId: number, fn: (tx: Tx) => Promise): Promise { + return testDb.$transaction(async tx => { + await tx.$executeRawUnsafe(`SET LOCAL app.congregation_id = '${String(congregationId)}'`) + return fn(tx) + }) +} + +const { deleteAccount, AccountHasAbsencesError } = await import('./delete-account.server') +const { Permission } = await import('~/shared/types/permission') + +const ADMIN = new Set([Permission.CanDoAnything]) +const ts = Date.now() +const ids = { cong: 0, admin: 0, dayOffTemplate: 0, meetingTemplate: 0 } +const DAY = new Date('2027-01-12T18:00:00Z') + +beforeAll(async () => { + ids.cong = ( + await testDb.congregation.create({ data: { name: `Delete ${ts}`, slug: `delete-${ts}`, active: true } }) + ).id + await withScope(ids.cong, async tx => { + const congregationId = ids.cong + const adminRole = await tx.role.create({ data: { key: 'admin', isBuiltIn: true, congregationId } }) + ids.admin = ( + await tx.userAccount.create({ data: { email: `admin-${ts}@test.com`, password: 'x', congregationId } }) + ).id + await tx.userRoleAssignment.create({ data: { userId: ids.admin, roleId: adminRole.id, congregationId } }) + ids.dayOffTemplate = ( + await tx.eventTemplate.create({ data: { name: 'Absence', key: 'day-off', congregationId } }) + ).id + ids.meetingTemplate = ( + await tx.eventTemplate.create({ + data: { name: 'Réunion de semaine', key: 'midweek-meeting', weekDay: 2, congregationId }, + }) + ).id + }) +}) + +afterAll(async () => { + if (ids.cong) { + await withScope(ids.cong, async tx => { + await tx.event.deleteMany({}) + await tx.eventTemplate.deleteMany({}) + await tx.userRoleAssignment.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + await tx.role.deleteMany({}) + }) + await testDb.auditLog.deleteMany({ where: { congregationId: ids.cong } }) + await testDb.congregation.deleteMany({ where: { id: ids.cong } }) + } + await testDb.$disconnect() +}) + +/** An account, with a record when asked, an absence when asked, and an empty meeting it made by hand. */ +async function account(name: string, { record, absence }: { record: boolean; absence: boolean }) { + return withScope(ids.cong, async tx => { + const congregationId = ids.cong + const memberId = record + ? (await tx.member.create({ data: { firstname: name, lastname: 'TEST', congregationId } })).id + : null + const accountId = ( + await tx.userAccount.create({ + data: { email: `${name}-${ts}@test.com`, password: 'x', memberId, congregationId }, + }) + ).id + const event = (templateId: number, extra: object = {}) => + tx.event.create({ + data: { name, startDate: DAY, endDate: DAY, templateId, createdById: accountId, congregationId, ...extra }, + }) + const absenceId = absence ? (await event(ids.dayOffTemplate, { status: 'released' })).id : null + const meetingId = (await event(ids.meetingTemplate)).id + return { accountId, absenceId, meetingId } + }) +} + +const remove = (accountId: number) => + withScope(ids.cong, tx => deleteAccount(tx, accountId as never, ids.cong, ids.admin, ADMIN)) + +const eventsOf = (eventIds: (number | null)[]) => + withScope(ids.cong, tx => + tx.event.findMany({ + where: { id: { in: eventIds.filter((id): id is number => id != null) } }, + select: { id: true, createdById: true, origin: true }, + }), + ) + +describe('deleteAccount and the events the account created', () => { + it('deletes an account without a record with its absences, and clears its author elsewhere', async () => { + const { accountId, absenceId, meetingId } = await account('Sans-fiche', { record: false, absence: true }) + + await remove(accountId) + + const left = await withScope(ids.cong, tx => tx.userAccount.findFirst({ where: { id: accountId } })) + expect(left).toBeNull() + expect(await eventsOf([absenceId, meetingId])).toEqual([{ id: meetingId, createdById: null, origin: 'manual' }]) + }) + + it('refuses an account linked to a record that has absences, changing nothing', async () => { + const { accountId, absenceId, meetingId } = await account('Avec-fiche', { record: true, absence: true }) + + await expect(remove(accountId)).rejects.toBeInstanceOf(AccountHasAbsencesError) + + const left = await withScope(ids.cong, tx => tx.userAccount.findFirst({ where: { id: accountId } })) + expect(left).not.toBeNull() + expect(await eventsOf([absenceId, meetingId])).toHaveLength(2) + }) + + it('deletes an account linked to a record without absences, clearing its author', async () => { + const { accountId, meetingId } = await account('Fiche-sans-absence', { record: true, absence: false }) + + const result = await remove(accountId) + + expect(result.memberId).not.toBeNull() + expect(await eventsOf([meetingId])).toEqual([{ id: meetingId, createdById: null, origin: 'manual' }]) + }) +}) diff --git a/app/features/settings/server/delete-account.server.test.ts b/app/features/settings/server/delete-account.server.test.ts index ac89c71a..b496a8fc 100644 --- a/app/features/settings/server/delete-account.server.test.ts +++ b/app/features/settings/server/delete-account.server.test.ts @@ -21,10 +21,14 @@ const { isAccountAdmin } = await import('~/shared/auth/permissions.server') const mockDb = { userAccount: { findFirst: vi.fn(), delete: vi.fn() }, + event: { count: vi.fn(), deleteMany: vi.fn(), updateMany: vi.fn() }, } beforeEach(() => { vi.resetAllMocks() + mockDb.event.count.mockResolvedValue(0) + mockDb.event.deleteMany.mockResolvedValue({ count: 0 }) + mockDb.event.updateMany.mockResolvedValue({ count: 0 }) }) describe('deleteAccount', () => { @@ -64,7 +68,7 @@ describe('deleteAccount', () => { actorId: 99, entityType: 'UserAccount', entityId: 1, - metadata: { email: 'a@b.test', memberId: 42 }, + metadata: { email: 'a@b.test', memberId: 42, absencesDeleted: 0 }, }), ) }) diff --git a/app/features/settings/server/delete-account.server.ts b/app/features/settings/server/delete-account.server.ts index cc0e525e..4b6b9bf9 100644 --- a/app/features/settings/server/delete-account.server.ts +++ b/app/features/settings/server/delete-account.server.ts @@ -1,17 +1,28 @@ +import { EventTemplateKey } from '~/features/events' import { requireNotLastAdmin } from '~/shared/auth/permissions.server' import { assertMayActOnAccount } from '~/shared/domain/account-protection.server' import { AuditAction, audit } from '~/shared/domain/audit.server' import type { ActorPermissions } from '~/shared/domain/role-grant-limits.server' -import { NotFoundError } from '~/shared/errors/app-error.server' +import { ConflictError, NotFoundError } from '~/shared/errors/app-error.server' import type { TransactionClient } from '~/shared/infra/db.server' import type { AccountId } from '~/shared/types/branded' +/** + * Refused: the account is linked to a record and has absences. They are the person's, not the login's, and are kept + * until they can be handed to the record. + */ +export class AccountHasAbsencesError extends ConflictError {} + /** * Delete a UserAccount. If a Member is linked (`memberId != null`), the * Member row is preserved — the person stays in the congregation, they just * lose their login. Tokens, permissions, and `UserRoleAssignment` rows * cascade via FK `onDelete`. * + * The events it created: its absences go with an account that has no record (nobody else is away on them); an account + * with a record and absences is refused (AccountHasAbsencesError). Its other events lose their author and keep their + * origin, so a hand-made one never becomes an empty meeting a template may move or delete. + * * For anonymization (keep the row, scrub PII) call `anonymizeAccount` instead. * This service is the destructive variant. */ @@ -32,6 +43,14 @@ export async function deleteAccount( await assertMayActOnAccount({ accountId, actorId, congregationId, actorPermissions, action: 'delete' }) await requireNotLastAdmin(accountId, congregationId) + const absences = { congregationId, createdById: accountId, template: { key: EventTemplateKey.DayOff } } + if (account.memberId != null && (await db.event.count({ where: absences })) > 0) { + throw new AccountHasAbsencesError('The account has absences') + } + // An absence only flags the assignments of its person's record: one without a record has flagged nothing. + const absencesDeleted = (await db.event.deleteMany({ where: absences })).count + await db.event.updateMany({ where: { congregationId, createdById: accountId }, data: { createdById: null } }) + await db.userAccount.delete({ where: { id_congregationId: { id: accountId, congregationId } } }) audit({ @@ -40,7 +59,7 @@ export async function deleteAccount( actorId, entityType: 'UserAccount', entityId: accountId, - metadata: { email: account.email, memberId: account.memberId }, + metadata: { email: account.email, memberId: account.memberId, absencesDeleted }, }) return { accountId, memberId: account.memberId } diff --git a/app/i18n/messages/en.json b/app/i18n/messages/en.json index 618926e6..f2b3f231 100644 --- a/app/i18n/messages/en.json +++ b/app/i18n/messages/en.json @@ -5587,6 +5587,7 @@ "settings_user_admin_only": "An administrator’s account is handled by an administrator.", "settings_user_own_account": "You cannot do this to your own account: ask another manager.", "settings_user_last_admin": "This is the congregation’s last administrator: give the role to someone else first.", + "settings_user_has_absences": "This account has absences: they stay with the person, so it cannot be deleted for now.", "settings_users_views": "Accounts", "settings_users_view_all": "All", "settings_users_view_active": "Active", diff --git a/app/i18n/messages/fr.json b/app/i18n/messages/fr.json index 322694ae..25cfca32 100644 --- a/app/i18n/messages/fr.json +++ b/app/i18n/messages/fr.json @@ -5587,6 +5587,7 @@ "settings_user_admin_only": "Le compte d’un administrateur se gère par un administrateur.", "settings_user_own_account": "Vous ne pouvez pas faire cela sur votre propre compte : demandez-le à un autre gestionnaire.", "settings_user_last_admin": "C’est le dernier administrateur de l’assemblée : donnez d’abord le rôle à quelqu’un d’autre.", + "settings_user_has_absences": "Ce compte a des absences : elles restent avec la personne, il ne peut pas être supprimé pour l’instant.", "settings_users_views": "Comptes", "settings_users_view_all": "Tous", "settings_users_view_active": "Actifs", diff --git a/app/i18n/messages/pt-PT.json b/app/i18n/messages/pt-PT.json index 26e13f6c..25453d81 100644 --- a/app/i18n/messages/pt-PT.json +++ b/app/i18n/messages/pt-PT.json @@ -5587,6 +5587,7 @@ "settings_user_admin_only": "A conta de um administrador tem de ser gerida por um administrador.", "settings_user_own_account": "Não pode fazer isto na sua própria conta: peça a outro responsável.", "settings_user_last_admin": "É o último administrador da congregação: atribua primeiro essa função a outra pessoa.", + "settings_user_has_absences": "Esta conta tem ausências: ficam com a pessoa, por isso não pode ser eliminada por agora.", "settings_users_views": "Contas", "settings_users_view_all": "Todos", "settings_users_view_active": "Ativo", From 2dab43b6680cc5fe47e1cef125aefcf2e6f1a6a5 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:29:04 +0100 Subject: [PATCH 05/11] feat(settings): carry who created each event in the archive (2.18) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit events.ndjson gains origin. A 2.18 archive's origin is kept; an older archive's event without an author and with nothing on it comes back as the job's, by the migration's rule, so it still moves with its template, and any other as « import » — as does an origin this version does not know. --- .../server/data-transfer.integration.test.ts | 77 +++++++++++++++++++ .../server/data-transfer.type.test.ts | 8 +- .../settings/server/data-transfer.type.ts | 6 +- .../server/export-congregation.server.ts | 1 + .../server/import-congregation.server.ts | 12 +-- .../server/import-events.server.test.ts | 2 +- .../settings/server/import-events.server.ts | 53 ++++++++++--- docs/development/data-transfer.md | 2 +- 8 files changed, 138 insertions(+), 23 deletions(-) diff --git a/app/features/settings/server/data-transfer.integration.test.ts b/app/features/settings/server/data-transfer.integration.test.ts index 0196bdf5..334333c5 100644 --- a/app/features/settings/server/data-transfer.integration.test.ts +++ b/app/features/settings/server/data-transfer.integration.test.ts @@ -1826,3 +1826,80 @@ describe('the order of services on import', () => { } }) }) + +// v2.18 carries each event's `origin`. An older archive has none: an event without an author and with nothing on it — +// what an empty meeting was — comes back as the job's, so it still moves with its template; any other as « import ». +describe('the origin of restored events', () => { + it('keeps a 2.18 archive’s origin and gives an older one’s by the migration’s rule', async () => { + const { importEvents, importEventParts, settleImportedEventOrigins } = await import('./import-events.server') + const cong = await testDb.congregation.create({ + data: { name: `Origins ${ts}`, slug: `origins-${ts}`, active: true }, + }) + try { + const origins = await withScope(cong.id, async tx => { + const author = await tx.userAccount.create({ + data: { email: `origins-${ts}@test.com`, password: 'x', congregationId: cong.id }, + }) + const idMap = new EntityIdMap() + idMap.set('user-accounts', 70, author.id) + const day = '2027-02-02T18:00:00.000Z' + const event = (id: number, name: string, extra: object = {}) => ({ + id, + name, + description: '', + startDate: day, + endDate: day, + templateId: null, + createdById: null, + createdAt: day, + status: 'draft', + ...extra, + }) + const zip = new JsZip() + const dataDir = zip.folder('data')! + dataDir.file( + 'events.ndjson', + [ + event(1, 'old, empty, no author'), + event(2, 'old, an author', { createdById: 70 }), + event(3, 'old, a part'), + event(4, 'new, made by hand', { origin: 'manual' }), + event(5, 'new, the job’s', { origin: 'job' }), + event(6, 'new, unknown', { origin: 'bogus' }), + ] + .map(row => `${JSON.stringify(row)}\n`) + .join(''), + ) + dataDir.file( + 'programme-part-assignments.ndjson', + `${JSON.stringify({ + ...{ id: 1, topic: '', note: '', hasConflict: false, name: 'Cantique', section: '', track: '' }, + ...{ order: 0, durationMin: null, eventId: 3, partId: null, assigneeId: null, assistantId: null }, + })}\n`, + ) + + const withoutOrigin = await importEvents(zip, tx, idMap, cong.id) + await importEventParts(zip, tx, idMap, cong.id) + await settleImportedEventOrigins(tx, withoutOrigin, cong.id) + + const rows = await tx.event.findMany({ select: { name: true, origin: true } }) + return Object.fromEntries(rows.map(row => [row.name, row.origin])) + }) + + expect(origins).toEqual({ + 'old, empty, no author': 'job', + 'old, an author': 'import', + 'old, a part': 'import', + 'new, made by hand': 'manual', + 'new, the job’s': 'job', + 'new, unknown': 'import', + }) + } finally { + await withScope(cong.id, async tx => { + await tx.event.deleteMany({}) + await tx.userAccount.deleteMany({}) + }) + await testDb.congregation.delete({ where: { id: cong.id } }) + } + }) +}) diff --git a/app/features/settings/server/data-transfer.type.test.ts b/app/features/settings/server/data-transfer.type.test.ts index 37460418..5bc433ee 100644 --- a/app/features/settings/server/data-transfer.type.test.ts +++ b/app/features/settings/server/data-transfer.type.test.ts @@ -75,12 +75,12 @@ describe('EntityIdMap', () => { }) describe('ARCHIVE_VERSION', () => { - it('is the current 2.17 schema version', () => { - expect(ARCHIVE_VERSION).toBe('2.17') + it('is the current 2.18 schema version', () => { + expect(ARCHIVE_VERSION).toBe('2.18') }) - it('still imports 2.16 archives', () => { - expect(SUPPORTED_ARCHIVE_VERSIONS).toContain('2.16') + it('still imports 2.17 archives', () => { + expect(SUPPORTED_ARCHIVE_VERSIONS).toContain('2.17') }) }) diff --git a/app/features/settings/server/data-transfer.type.ts b/app/features/settings/server/data-transfer.type.ts index f273b147..a1590717 100644 --- a/app/features/settings/server/data-transfer.type.ts +++ b/app/features/settings/server/data-transfer.type.ts @@ -1,4 +1,4 @@ -export const ARCHIVE_VERSION = '2.17' +export const ARCHIVE_VERSION = '2.18' // Older archive versions an import will still accept. v1.0 archives miss every // post-shipping feature table (custom roles, allowed-roles, external speakers, @@ -64,6 +64,9 @@ export const ARCHIVE_VERSION = '2.17' // v2.17 gives services an order: `programme-template-service-roles.ndjson` and // `programme-service-role-assignments.ndjson` gain `order`. Pre-2.17 services are numbered by their id in the archive // (the order they were created in, the migration's rule), each template and each event from 0 in steps of 5. +// v2.18 carries who created each event: `events.ndjson` gains `origin` (`job`, `manual` or `import`). A pre-2.18 +// event without an author and with nothing on it comes back as the job's, by the migration's rule; any other as +// `import`, and so does one whose origin this version does not know. // v1.x archives are listed here so the import path reports them with a warning rather than rejecting outright; // `migrateLegacyUsersNdjson` splits their `users.ndjson` before the import runs. export const SUPPORTED_ARCHIVE_VERSIONS = [ @@ -87,6 +90,7 @@ export const SUPPORTED_ARCHIVE_VERSIONS = [ '2.15', '2.16', '2.17', + '2.18', ] as const export interface ManifestJson { diff --git a/app/features/settings/server/export-congregation.server.ts b/app/features/settings/server/export-congregation.server.ts index 5851528f..afa57d80 100644 --- a/app/features/settings/server/export-congregation.server.ts +++ b/app/features/settings/server/export-congregation.server.ts @@ -582,6 +582,7 @@ export function buildExportSteps(db: TransactionClient, congregationId: number, createdById: true, createdAt: true, status: true, + origin: true, }, }), }, diff --git a/app/features/settings/server/import-congregation.server.ts b/app/features/settings/server/import-congregation.server.ts index 37fe7f37..a8170223 100644 --- a/app/features/settings/server/import-congregation.server.ts +++ b/app/features/settings/server/import-congregation.server.ts @@ -45,6 +45,7 @@ import { importEventServicePartAllowedRoles, importEventServiceParts, importEvents, + settleImportedEventOrigins, } from './import-events.server' import * as speakers from './import-external-speakers.server' import { importPartPresets } from './import-part-presets.server' @@ -151,9 +152,8 @@ export async function runImport(job: Job): Promise { const zip = await JsZip.loadAsync(buffer) const manifest = await readManifest(zip) - // v1.x → v2.0 shim: split legacy users.ndjson into members + user-accounts - // so the rest of runImport reads the v2.0 layout. Idempotent if the - // archive is already v2.0. + // v1.x → v2.0 shim: split legacy users.ndjson into members + user-accounts so the rest of runImport reads the v2.0 + // layout. Idempotent if the archive is already v2.0. const shimWarnings = await migrateLegacyUsersNdjson(zip, manifest.version) if (shimWarnings.length > 0) { logger.info(`Imported legacy v${manifest.version} archive`, { congregationId, warnings: shimWarnings }) @@ -263,8 +263,7 @@ export async function runImport(job: Job): Promise { await importAttributions(zip, db, idMap, congregationId) await progress() - // Before the template parts and event parts, which carry a presetId that - // resolves through the map this fills. + // Before the template and event parts: their presetId resolves through the map this fills. await importPartPresets(zip, db, idMap, congregationId) await progress() @@ -286,7 +285,7 @@ export async function runImport(job: Job): Promise { await importTemplateResponsibles(zip, db, idMap, congregationId) await progress() - await importEvents(zip, db, idMap, congregationId) + const withoutOrigin = await importEvents(zip, db, idMap, congregationId) await importAttendance(zip, db, idMap, congregationId) await progress() @@ -297,6 +296,7 @@ export async function runImport(job: Job): Promise { await progress() await importEventServiceParts(zip, db, idMap, congregationId) + await settleImportedEventOrigins(db, withoutOrigin, congregationId) await progress() await importEventServicePartAllowedRoles(zip, db, idMap, congregationId) diff --git a/app/features/settings/server/import-events.server.test.ts b/app/features/settings/server/import-events.server.test.ts index 0c998340..a607911c 100644 --- a/app/features/settings/server/import-events.server.test.ts +++ b/app/features/settings/server/import-events.server.test.ts @@ -69,7 +69,7 @@ describe('importEvents', () => { expect(db.event.deleteMany).toHaveBeenCalledWith({ where: { congregationId: 1, - createdById: null, + origin: 'job', eventParts: { none: {} }, eventServiceParts: { none: {} }, attendance: { is: null }, diff --git a/app/features/settings/server/import-events.server.ts b/app/features/settings/server/import-events.server.ts index bfc3a77c..25895f08 100644 --- a/app/features/settings/server/import-events.server.ts +++ b/app/features/settings/server/import-events.server.ts @@ -1,5 +1,6 @@ import type JsZip from 'jszip' -import { EventStatus, EventTemplateKey } from '~/features/events' +import { EventOrigin, EventStatus, EventTemplateKey, isEventOrigin } from '~/features/events' +import { EMPTY_MEETING } from '~/features/events/index.server' import type { TransactionClient } from '~/shared/infra/db.server' import { createLogger } from '~/shared/infra/logger.server' import type { EntityIdMap } from './data-transfer.type' @@ -22,7 +23,7 @@ export async function importEvents( db: TransactionClient, idMap: EntityIdMap, congregationId: number, -): Promise { +): Promise { const records = await readNdjsonFile<{ id: number name: string @@ -34,8 +35,10 @@ export async function importEvents( createdAt: string // Since v2.16. status?: string + // Since v2.18. + origin?: string }>(zip, 'events') - if (records.length === 0) return + if (records.length === 0) return [] const dayOff = await db.eventTemplate.findFirst({ where: { key: EventTemplateKey.DayOff, congregationId }, @@ -46,18 +49,16 @@ export async function importEvents( // replace them all — never one with attendance — and every template's mark is reset, so the recurring-events job // starts again after the last imported meeting, on the archive's own weekdays. await db.event.deleteMany({ - where: { - congregationId, - createdById: null, - eventParts: { none: {} }, - eventServiceParts: { none: {} }, - attendance: { is: null }, - }, + where: { congregationId, ...EMPTY_MEETING }, }) await db.eventTemplate.updateMany({ where: { congregationId }, data: { generatedUntil: null } }) let ownerless = 0 let unknownStatus = 0 + // Restored from an archive without origins (before v2.18): settleImportedEventOrigins decides them once their parts and + // services are in. One whose origin this version does not know stays « import ». + let unknownOrigin = 0 + const withoutOrigin: number[] = [] for (const record of records) { const templateId = idMap.getOptional('programme-templates', record.templateId) const createdById = idMap.getOptional('user-accounts', record.createdById) @@ -76,10 +77,16 @@ export async function importEvents( templateId, createdById, status: importedStatus(record.status, () => unknownStatus++), + origin: isEventOrigin(record.origin) ? record.origin : EventOrigin.Import, congregationId, }, }) idMap.set('events', record.id, created.id) + if (record.origin == null) withoutOrigin.push(created.id) + else if (!isEventOrigin(record.origin)) unknownOrigin++ + } + if (unknownOrigin > 0) { + logger.warn(`Imported ${unknownOrigin} event(s) with an unknown origin as restored`, { congregationId }) } if (unknownStatus > 0) { logger.warn(`Imported ${unknownStatus} event(s) with an unknown status as drafts`, { congregationId }) @@ -87,6 +94,32 @@ export async function importEvents( if (ownerless > 0) { logger.warn(`Skipped ${ownerless} absence(s) whose owner was not imported`, { congregationId }) } + return withoutOrigin +} + +/** + * The origin of events an archive did not give one (before v2.18), by the migration's rule, once their parts, services + * and counts are in: one without an author and with nothing on it was an empty meeting, the job's — it still moves with + * its template. The others stay « import ». + */ +export async function settleImportedEventOrigins( + db: TransactionClient, + eventIds: number[], + congregationId: number, +): Promise { + if (eventIds.length === 0) return + await db.event.updateMany({ + where: { + id: { in: eventIds }, + congregationId, + origin: EventOrigin.Import, + createdById: null, + eventParts: { none: {} }, + eventServiceParts: { none: {} }, + attendance: { is: null }, + }, + data: { origin: EventOrigin.Job }, + }) } /** The status an event takes: the archive's when this version knows it, a draft otherwise. */ diff --git a/docs/development/data-transfer.md b/docs/development/data-transfer.md index d9897e8c..1c532c17 100644 --- a/docs/development/data-transfer.md +++ b/docs/development/data-transfer.md @@ -12,7 +12,7 @@ A `.unitae` archive is a ZIP with three top-level entries: | `data/.ndjson` | One file per entity type, in newline-delimited JSON. Each line is one row. Empty files are omitted from the archive | | `files/` | Uploaded user files (board PDFs, territory cards). Only present when the export was created with `includeFiles: true` | -The archive version is a constant at the top of `app/features/settings/server/data-transfer.type.ts` (`ARCHIVE_VERSION`, currently `2.17` — bumped from `2.16` when services got an order of their own: `programme-template-service-roles.ndjson` and `programme-service-role-assignments.ndjson` gain `order`; pre-2.17 services are numbered by their id in the archive (the order they were created in, the migration's rule), each template and each event from 0 in steps of 5 — the file's row order means nothing, since the export had no ORDER BY. `2.16` was bumped from `2.15` to carry what a restore lost: `events.ndjson` gains each event's `status` (`released` or `draft`; an unknown one imports as a draft), `programme-templates.ndjson` gains `startTime` and `endTime`, and `board-dynamic-document-settings.ndjson` gains `dynamicConfig` (the templates a programme document shows, read through the imported templates); every board dynamic document is now created rather than matched on its type and ref, which folded the programme documents into one; pre-2.16 events import as drafts, templates keep their hours (a new one gets the defaults) and documents have no configuration, as before. `2.15` was bumped from `2.14` for meeting attendance: `attendance.ndjson` carries each meeting's two counts (in the hall, by videoconference) with who entered them and when, keyed to its event, and `programme-templates.ndjson` gains `attendanceKind`; pre-2.15 archives import with no counts, an existing template keeps its kind and a new one gets the default of its key (`defaultAttendanceKind`, the migration's rule). `2.14` was bumped from `2.13` for « Notre liste », the speakers a congregation sends: `our-speakers.ndjson` carries each brother's entry keyed to his record (on the list or not, talks, how his phone and e-mail are shared, a note), and `speaker-congregations.ndjson` gains `ourListSentAt`, `ourListSentManually` and `ourListSentDigest` (a digest of the list as sent, compared with today's to tell who holds the current one); pre-2.14 archives import with no entry and every congregation never sent to. The two roles chosen in Réglages travel in `settings.ndjson` by role key. `2.13` was bumped from `2.12` when the congregations whose list of speakers is received became records: `speaker-congregations.ndjson` carries their name, two contacts and latest list date (not the list's PDF), and `external-speakers.ndjson` gains `speakerCongregationId`, `phone2`, `email2`, `talks` and `anonymizedAt`; pre-2.13 speakers only carry the free-text `congregationName`, and the importer builds one congregation per spelling by the same rule as the migration (`normalizeCongregationName`). `2.12` was bumped from `2.11` when the roles given by hand moved from logins onto records: `member-role-assignments.ndjson` carries them with their `kind`, and pre-2.12 archives hand a linked login's roles to its record on import, by the same rule as the migration. `2.11` was bumped from `2.10` for the members' `arrivedAt` and `lastPastoralVisitAt`, the pastoral follow-up dates; pre-2.11 rows import without them. `2.10` was bumped from `2.9` for the `locale` of user accounts, the interface language an account chose for itself; pre-2.10 rows create accounts that follow the congregation's language and leave existing accounts' choice alone. `2.9` was bumped from `2.8` for the `appearance` of board dynamic documents, their typeface, accent and layout; pre-2.9 rows import with the defaults. The comment on `ARCHIVE_VERSION` records each bump from `2.5` on. `2.4` was bumped from `2.3` for the `pioneer-enrolments.ndjson` entity; pre-2.4 archives have activity rows but no enrolments, so `import-congregation.server.ts` runs the pioneer-enrolment backfill (`backfillCongregationEnrolments`) as a post-import step to derive stints from the imported activity history, leaving those tenants with working pace. `2.3` was bumped from `2.2` for the `pioneer-goals.ndjson` entity (per-`(serviceYear, type)` monthly-hour overrides); pre-2.3 archives import fine with no overrides, so pioneers fall back to the built-in default rates. `pioneer-goals` is congregation-scoped with no cross-entity references — the importer skips id remapping and `upsert`s on the `(serviceYear, type, congregationId)` natural key, so re-importing into a congregation that already has overrides refreshes them rather than hitting the unique constraint. `2.2` was bumped from `2.1` for the `emergency-contacts.ndjson` entity and the two `Member` emergency flags (`dpaCardUpToDate`, `survivalBackpackReady`) that ride along in `members.ndjson`; pre-2.2 archives import fine with the emergency table left empty. `2.1` was bumped from `2.0` for the `AuditLog.entityType` rewrite shim that maps pre-rename `Programme*` model names to their current `Event*` / `Template*` / `EventServicePart` / `TemplateServicePart` counterparts on import; `2.0` itself was bumped from `1.1` when `User` was split into `Member` + `UserAccount`). The list of accepted versions on import lives in `SUPPORTED_ARCHIVE_VERSIONS` in the same file — versions outside that list are reported as a warning and skipped. Bump the constant when the on-disk shape changes; add the previous value to `SUPPORTED_ARCHIVE_VERSIONS` when the format remains compatible enough to import-with-warning. +The archive version is a constant at the top of `app/features/settings/server/data-transfer.type.ts` (`ARCHIVE_VERSION`, currently `2.18` — bumped from `2.17` to carry who created each event: `events.ndjson` gains `origin` (`job` for the recurring-events job's meetings, `manual` for a person's, `import` for a restored one whose origin was unknown); a pre-2.18 event without an author and with nothing on it comes back as the job's, by the migration's rule, so it still moves with its template, and any other as `import`. `2.17` was bumped from `2.16` when services got an order of their own: `programme-template-service-roles.ndjson` and `programme-service-role-assignments.ndjson` gain `order`; pre-2.17 services are numbered by their id in the archive (the order they were created in, the migration's rule), each template and each event from 0 in steps of 5 — the file's row order means nothing, since the export had no ORDER BY. `2.16` was bumped from `2.15` to carry what a restore lost: `events.ndjson` gains each event's `status` (`released` or `draft`; an unknown one imports as a draft), `programme-templates.ndjson` gains `startTime` and `endTime`, and `board-dynamic-document-settings.ndjson` gains `dynamicConfig` (the templates a programme document shows, read through the imported templates); every board dynamic document is now created rather than matched on its type and ref, which folded the programme documents into one; pre-2.16 events import as drafts, templates keep their hours (a new one gets the defaults) and documents have no configuration, as before. `2.15` was bumped from `2.14` for meeting attendance: `attendance.ndjson` carries each meeting's two counts (in the hall, by videoconference) with who entered them and when, keyed to its event, and `programme-templates.ndjson` gains `attendanceKind`; pre-2.15 archives import with no counts, an existing template keeps its kind and a new one gets the default of its key (`defaultAttendanceKind`, the migration's rule). `2.14` was bumped from `2.13` for « Notre liste », the speakers a congregation sends: `our-speakers.ndjson` carries each brother's entry keyed to his record (on the list or not, talks, how his phone and e-mail are shared, a note), and `speaker-congregations.ndjson` gains `ourListSentAt`, `ourListSentManually` and `ourListSentDigest` (a digest of the list as sent, compared with today's to tell who holds the current one); pre-2.14 archives import with no entry and every congregation never sent to. The two roles chosen in Réglages travel in `settings.ndjson` by role key. `2.13` was bumped from `2.12` when the congregations whose list of speakers is received became records: `speaker-congregations.ndjson` carries their name, two contacts and latest list date (not the list's PDF), and `external-speakers.ndjson` gains `speakerCongregationId`, `phone2`, `email2`, `talks` and `anonymizedAt`; pre-2.13 speakers only carry the free-text `congregationName`, and the importer builds one congregation per spelling by the same rule as the migration (`normalizeCongregationName`). `2.12` was bumped from `2.11` when the roles given by hand moved from logins onto records: `member-role-assignments.ndjson` carries them with their `kind`, and pre-2.12 archives hand a linked login's roles to its record on import, by the same rule as the migration. `2.11` was bumped from `2.10` for the members' `arrivedAt` and `lastPastoralVisitAt`, the pastoral follow-up dates; pre-2.11 rows import without them. `2.10` was bumped from `2.9` for the `locale` of user accounts, the interface language an account chose for itself; pre-2.10 rows create accounts that follow the congregation's language and leave existing accounts' choice alone. `2.9` was bumped from `2.8` for the `appearance` of board dynamic documents, their typeface, accent and layout; pre-2.9 rows import with the defaults. The comment on `ARCHIVE_VERSION` records each bump from `2.5` on. `2.4` was bumped from `2.3` for the `pioneer-enrolments.ndjson` entity; pre-2.4 archives have activity rows but no enrolments, so `import-congregation.server.ts` runs the pioneer-enrolment backfill (`backfillCongregationEnrolments`) as a post-import step to derive stints from the imported activity history, leaving those tenants with working pace. `2.3` was bumped from `2.2` for the `pioneer-goals.ndjson` entity (per-`(serviceYear, type)` monthly-hour overrides); pre-2.3 archives import fine with no overrides, so pioneers fall back to the built-in default rates. `pioneer-goals` is congregation-scoped with no cross-entity references — the importer skips id remapping and `upsert`s on the `(serviceYear, type, congregationId)` natural key, so re-importing into a congregation that already has overrides refreshes them rather than hitting the unique constraint. `2.2` was bumped from `2.1` for the `emergency-contacts.ndjson` entity and the two `Member` emergency flags (`dpaCardUpToDate`, `survivalBackpackReady`) that ride along in `members.ndjson`; pre-2.2 archives import fine with the emergency table left empty. `2.1` was bumped from `2.0` for the `AuditLog.entityType` rewrite shim that maps pre-rename `Programme*` model names to their current `Event*` / `Template*` / `EventServicePart` / `TemplateServicePart` counterparts on import; `2.0` itself was bumped from `1.1` when `User` was split into `Member` + `UserAccount`). The list of accepted versions on import lives in `SUPPORTED_ARCHIVE_VERSIONS` in the same file — versions outside that list are reported as a warning and skipped. Bump the constant when the on-disk shape changes; add the previous value to `SUPPORTED_ARCHIVE_VERSIONS` when the format remains compatible enough to import-with-warning. v1.x archives are importable through `migrateLegacyUsersNdjson` (defined in `migrate-legacy-users-ndjson.server.ts`, called from `import-congregation.server.ts`), which runs at the top of `validateImport` / `runImport` and synthesizes `members.ndjson` + `user-accounts.ndjson` from the legacy `users.ndjson` directly inside the in-memory zip. The split mirrors the schema migration heuristic: rows with publisher signals (`isPublisher`, baptism date, helder/servant/anointed flag, group membership) yield a Member, and rows whose email isn't `*.placeholder.unitae.app` yield a UserAccount linked to that Member via the preserved id space. Downstream import functions then read the v2.0 layout uniformly — no v1.x branch beyond the shim. Placeholder-email accounts are dropped, and the operator receives a warning summarising the split counts. From e85904d9f7aa1fffb60a23dafa25d79bdf4e1c36 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 00:29:07 +0100 Subject: [PATCH 06/11] test(events): the references carry each event's origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Changed on purpose: event rows read whole gain `origin` — « job » on the eleven meetings created ahead, « manual » on the others, the same after a restore. Nothing else moved: the other changed lines are the commas before it. --- .../__references__/archive-after-import.json | 63 +++++++++++++------ .../__references__/archive-export.json | 57 +++++++++++------ .../reference/__references__/assignments.json | 1 + .../__references__/board-by-date.json | 2 + .../__references__/board-by-template.json | 2 + .../__references__/board-midweek-parts.json | 1 + .../board-weekend-services.json | 1 + .../__references__/dashboard-hugo.json | 1 + .../__references__/programme-pages.json | 18 ++++++ 9 files changed, 108 insertions(+), 38 deletions(-) diff --git a/app/tests/reference/__references__/archive-after-import.json b/app/tests/reference/__references__/archive-after-import.json index 586d642a..3e2022a6 100644 --- a/app/tests/reference/__references__/archive-after-import.json +++ b/app/tests/reference/__references__/archive-after-import.json @@ -577,7 +577,8 @@ "templateId": "", "createdById": "", "createdAt": "