diff --git a/app/database/migrations/20261120090000_add_absences/migration.sql b/app/database/migrations/20261120090000_add_absences/migration.sql new file mode 100644 index 00000000..68f8c2e8 --- /dev/null +++ b/app/database/migrations/20261120090000_add_absences/migration.sql @@ -0,0 +1,67 @@ +-- Absences become rows of their own, belonging to the person: their record when the account that declared them has +-- one, the account otherwise. No change in what anyone sees: every reader still reads the day-off events, and the new +-- image writes both until the readers move over. Each row keeps the event it was copied from until the events are +-- dropped. +-- +-- During the rollout the previous image keeps serving: it declares and deletes day-off events without their rows (a +-- later migration copies the missing ones and drops the rows whose event is gone, before the events are), and it +-- cannot delete an account without a record that has absences — its rows name the account, which is Restrict. The new +-- image lets go of them first. +-- +-- 1. The table, its CHECK and the standard tenant policy. +CREATE TABLE IF NOT EXISTS "Absence" ( + "id" SERIAL NOT NULL, + "startDate" TIMESTAMP(3) NOT NULL, + "endDate" TIMESTAMP(3) NOT NULL, + "note" TEXT NOT NULL DEFAULT '', + "memberId" INTEGER, + "accountId" INTEGER, + "legacyEventId" INTEGER, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "congregationId" INTEGER NOT NULL, + + CONSTRAINT "Absence_pkey" PRIMARY KEY ("id") +); + +-- Somebody's: the person's record, or the account that declared it when there is none. +ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_owner_check"; +ALTER TABLE "Absence" ADD CONSTRAINT "Absence_owner_check" CHECK ("memberId" IS NOT NULL OR "accountId" IS NOT NULL); + +CREATE UNIQUE INDEX IF NOT EXISTS "Absence_legacyEventId_key" ON "Absence"("legacyEventId"); +CREATE UNIQUE INDEX IF NOT EXISTS "Absence_id_congregationId_key" ON "Absence"("id", "congregationId"); +CREATE INDEX IF NOT EXISTS "Absence_congregationId_startDate_idx" ON "Absence"("congregationId", "startDate"); +CREATE INDEX IF NOT EXISTS "Absence_memberId_idx" ON "Absence"("memberId"); +CREATE INDEX IF NOT EXISTS "Absence_accountId_idx" ON "Absence"("accountId"); + +ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_memberId_fkey"; +ALTER TABLE "Absence" ADD CONSTRAINT "Absence_memberId_fkey" FOREIGN KEY ("memberId") REFERENCES "Member"("id") ON DELETE CASCADE ON UPDATE CASCADE; +-- Restrict: deleting an account lets go of its absences explicitly (releaseAccountEvents); any other path fails +-- clearly instead of breaking the CHECK. +ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_accountId_fkey"; +ALTER TABLE "Absence" ADD CONSTRAINT "Absence_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "UserAccount"("id") ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE "Absence" DROP CONSTRAINT IF EXISTS "Absence_congregationId_fkey"; +ALTER TABLE "Absence" ADD CONSTRAINT "Absence_congregationId_fkey" FOREIGN KEY ("congregationId") REFERENCES "Congregation"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE "Absence" ENABLE ROW LEVEL SECURITY; +ALTER TABLE "Absence" FORCE ROW LEVEL SECURITY; +DROP POLICY IF EXISTS tenant_isolation ON "Absence"; +CREATE POLICY tenant_isolation ON "Absence" FOR ALL + USING ( + CASE + WHEN NULLIF(current_setting('app.congregation_id', true), '') IS NULL THEN true + ELSE "congregationId" = current_setting('app.congregation_id', true)::int + END + ); + +-- 2. One row per day-off event, as it is: its dates and note, the account that declared it, that account's record when +-- it has one. No path leaves a day-off without its account (deleting one takes its absences or is refused); one +-- without would break the CHECK, so it is left out. Idempotent: run again, as the later catch-up does, it copies +-- only what it has not copied yet. +INSERT INTO "Absence" ("startDate", "endDate", "note", "memberId", "accountId", "legacyEventId", "createdAt", "congregationId") +SELECT event."startDate", event."endDate", event."description", account."memberId", event."createdById", event."id", + event."createdAt", event."congregationId" +FROM "Event" AS event +JOIN "EventTemplate" AS template + ON template."id" = event."templateId" AND template."congregationId" = event."congregationId" AND template."key" = 'day-off' +JOIN "UserAccount" AS account ON account."id" = event."createdById" +ON CONFLICT ("legacyEventId") DO NOTHING; diff --git a/app/database/migrations/20261120090100_catch_up_event_origin/migration.sql b/app/database/migrations/20261120090100_catch_up_event_origin/migration.sql new file mode 100644 index 00000000..bd902e26 --- /dev/null +++ b/app/database/migrations/20261120090100_catch_up_event_origin/migration.sql @@ -0,0 +1,29 @@ +-- The empty meetings the previous image created while 20261119120000_add_event_origin rolled out get their origin. +-- Contract: no event someone made or touched changes. +-- +-- That migration gave « job » to the empty meetings that existed, but the running image kept serving until the new one +-- rolled out, and its recurring-events job wrote the column's default, « manual »: those meetings stopped moving with +-- their template. Its backfill cannot simply run again: since then, deleting an account clears the author of what it +-- made, and a hand-made event left without an author looks the same. +-- +-- Only events that are all of: no author, nothing on them (no part, no service, no attendance), of a template (the job +-- only creates those), still +-- « manual », created after that migration finished, and never written since (`updatedAt` within seconds of +-- `createdAt`) — clearing an author is a write, so a hand-made event whose account went keeps « manual ». +UPDATE "Event" AS event +SET "origin" = 'job' +WHERE event."origin" = 'manual' + AND event."createdById" IS NULL + AND event."templateId" IS NOT NULL + 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") + -- max() over finished, not rolled-back rows: a migration that failed and was applied again leaves two rows. A + -- database with none (baselined history) gets no repair rather than a guess. + AND event."createdAt" >= ( + SELECT max(m."finished_at") FROM "_prisma_migrations" AS m + WHERE m."migration_name" = '20261119120000_add_event_origin' + AND m."finished_at" IS NOT NULL + AND m."rolled_back_at" IS NULL + ) + AND event."updatedAt" <= event."createdAt" + INTERVAL '5 seconds'; diff --git a/app/database/migrations/add-absences.integration.test.ts b/app/database/migrations/add-absences.integration.test.ts new file mode 100644 index 00000000..46a5a125 --- /dev/null +++ b/app/database/migrations/add-absences.integration.test.ts @@ -0,0 +1,243 @@ +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, '20261120090000_add_absences', '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 AbsenceRow { + legacyEventId: number | null + startDate: Date + endDate: Date + note: string + memberId: number | null + accountId: number | null + createdAt: Date +} + +interface Result { + ids: Record + first: AbsenceRow[] + second: AbsenceRow[] + /** The other congregation's rows after both runs, by event: its own absence, and nothing for the stray one. */ + otherCongregation: { legacyEventId: number | null; congregationId: number }[] + ownerlessRefused: boolean +} + +let memo: Promise | undefined + +/** + * Day-off events as the previous image leaves them, at the moment the migration runs: some declared from an account + * with a record, one from an account without, a meeting that is no absence, and one absence already copied — then a + * new absence declared before the second run. + */ +function snapshot(): Promise { + memo ??= (async () => { + let result: Result | undefined + try { + await testDb.$transaction(async tx => { + const stamp = `absences-${process.pid}-${globalThis.performance.now().toString().replace('.', '')}` + const congregationId = (await tx.congregation.create({ data: { name: stamp, slug: stamp, active: true } })).id + const dayOff = await tx.eventTemplate.create({ data: { name: 'Absence', key: 'day-off', congregationId } }) + const meeting = await tx.eventTemplate.create({ + data: { name: 'Réunion', key: `midweek-${stamp}`, congregationId }, + }) + const member = await tx.member.create({ data: { firstname: 'Paul', lastname: 'MARTIN', congregationId } }) + const withRecord = await tx.userAccount.create({ + data: { email: `paul-${stamp}@test.com`, password: 'x', memberId: member.id, congregationId }, + }) + const withoutRecord = await tx.userAccount.create({ + data: { email: `sans-${stamp}@test.com`, password: 'x', congregationId }, + }) + const event = ( + templateId: number, + createdById: number | null, + day: string, + description = '', + inCongregation = congregationId, + ) => + tx.event.create({ + data: { + name: 'Absence', + description, + startDate: new Date(`${day}T00:00:00Z`), + endDate: new Date(`${day}T23:59:00Z`), + status: 'released', + templateId, + createdById, + createdAt: new Date('2026-10-01T08:00:00Z'), + congregationId: inCongregation, + }, + }) + // Another congregation, with its own absence template and one genuine absence. + const otherId = ( + await tx.congregation.create({ data: { name: `${stamp}-b`, slug: `${stamp}-b`, active: true } }) + ).id + const otherDayOff = await tx.eventTemplate.create({ + data: { name: 'Absence', key: 'day-off', congregationId: otherId }, + }) + const otherAccount = await tx.userAccount.create({ + data: { email: `autre-${stamp}@test.com`, password: 'x', congregationId: otherId }, + }) + + const ids: Record = { + withRecord: (await event(dayOff.id, withRecord.id, '2027-01-04', 'Vacances')).id, + withoutRecord: (await event(dayOff.id, withoutRecord.id, '2027-01-11')).id, + meeting: (await event(meeting.id, withRecord.id, '2027-01-12')).id, + copied: (await event(dayOff.id, withRecord.id, '2027-02-01')).id, + // No author: it would break the CHECK, so it is left out (no path leaves one today). + noAuthor: (await event(dayOff.id, null, '2027-02-08')).id, + // An event of this congregation pointing at the other one's absence template: not an absence here. + stray: (await event(otherDayOff.id, withRecord.id, '2027-02-15')).id, + otherAbsence: (await event(otherDayOff.id, otherAccount.id, '2027-02-22', '', otherId)).id, + otherCongregation: otherId, + member: member.id, + withRecordAccount: withRecord.id, + withoutRecordAccount: withoutRecord.id, + } + // Copied already, with a note of its own: a run neither doubles nor overwrites it. + await tx.absence.create({ + data: { + startDate: new Date('2027-02-01T00:00:00Z'), + endDate: new Date('2027-02-01T23:59:00Z'), + note: 'déjà là', + accountId: withRecord.id, + legacyEventId: ids.copied, + congregationId, + }, + }) + + const read = () => + tx.absence.findMany({ + where: { congregationId }, + select: { + legacyEventId: true, + startDate: true, + endDate: true, + note: true, + memberId: true, + accountId: true, + createdAt: true, + }, + orderBy: { legacyEventId: 'asc' }, + }) + + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + const first = await read() + // Declared by the previous image after the first run: no Absence row of its own yet. + ids.late = (await event(dayOff.id, withoutRecord.id, '2027-03-01')).id + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + const second = await read() + + let ownerlessRefused = false + try { + await tx.$executeRawUnsafe('SAVEPOINT ownerless') + await tx.$executeRawUnsafe( + `INSERT INTO "Absence" ("startDate", "endDate", "congregationId") VALUES (now(), now(), ${congregationId})`, + ) + } catch { + ownerlessRefused = true + } finally { + await tx.$executeRawUnsafe('ROLLBACK TO SAVEPOINT ownerless') + } + + const otherCongregation = await tx.absence.findMany({ + where: { legacyEventId: { in: [ids.stray, ids.otherAbsence] } }, + select: { legacyEventId: true, congregationId: true }, + }) + result = { ids, first, second, otherCongregation, ownerlessRefused } + throw new Rollback() + }) + } catch (error) { + if (!(error instanceof Rollback)) throw error + } + return result as Result + })() + return memo +} + +afterAll(async () => { + await testDb.$disconnect() +}) + +describe('20261120090000_add_absences', () => { + it('copies every day-off once, as it is, with its owner’s record when the account has one', async () => { + const { ids, first } = await snapshot() + + expect(first).toEqual([ + { + legacyEventId: ids.withRecord, + startDate: new Date('2027-01-04T00:00:00Z'), + endDate: new Date('2027-01-04T23:59:00Z'), + note: 'Vacances', + memberId: ids.member, + accountId: ids.withRecordAccount, + createdAt: new Date('2026-10-01T08:00:00Z'), + }, + { + legacyEventId: ids.withoutRecord, + startDate: new Date('2027-01-11T00:00:00Z'), + endDate: new Date('2027-01-11T23:59:00Z'), + note: '', + memberId: null, + accountId: ids.withoutRecordAccount, + createdAt: new Date('2026-10-01T08:00:00Z'), + }, + expect.objectContaining({ legacyEventId: ids.copied, note: 'déjà là', memberId: null }), + ]) + }) + + it('leaves out an event that is no absence', async () => { + const { ids, first } = await snapshot() + + expect(first.map(row => row.legacyEventId)).not.toContain(ids.meeting) + }) + + it('copies on a second run only the absences declared since', async () => { + const { ids, first, second } = await snapshot() + + expect(second).toEqual([...first, expect.objectContaining({ legacyEventId: ids.late, memberId: null })]) + }) + + it('refuses an absence that is nobody’s', async () => { + const { ownerlessRefused } = await snapshot() + + expect(ownerlessRefused).toBe(true) + }) + + it('isolates absences by congregation', async () => { + const rows = await testDb.$queryRaw<{ forced: boolean; policies: bigint }[]>` + SELECT c.relforcerowsecurity AS forced, + (SELECT COUNT(*) FROM pg_policies p WHERE p.tablename = 'Absence' AND p.policyname = 'tenant_isolation') AS policies + FROM pg_class c WHERE c.relname = 'Absence'` + expect(rows).toEqual([{ forced: true, policies: 1n }]) + }) + + it('leaves out an absence without an author, and an event pointing at another congregation’s template', async () => { + const { ids, second } = await snapshot() + const copied = second.map(row => row.legacyEventId) + + expect(copied).not.toContain(ids.noAuthor) + expect(copied).not.toContain(ids.stray) + }) + + it('copies the other congregation’s absence under that congregation', async () => { + const { ids, otherCongregation } = await snapshot() + + expect(otherCongregation).toEqual([{ legacyEventId: ids.otherAbsence, congregationId: ids.otherCongregation }]) + }) +}) diff --git a/app/database/migrations/catch-up-event-origin.integration.test.ts b/app/database/migrations/catch-up-event-origin.integration.test.ts new file mode 100644 index 00000000..3c12ec28 --- /dev/null +++ b/app/database/migrations/catch-up-event-origin.integration.test.ts @@ -0,0 +1,117 @@ +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. Dates are written in SQL, so the test does not lean on +// Prisma's @updatedAt. +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, '20261120090100_catch_up_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 {} + +let memo: Promise<{ first: Record; second: Record }> | undefined + +function snapshot() { + memo ??= (async () => { + let result: { first: Record; second: Record } | undefined + try { + await testDb.$transaction(async tx => { + const finished = await tx.$queryRaw<{ finished_at: Date }[]>` + SELECT "finished_at" FROM "_prisma_migrations" WHERE "migration_name" = '20261119120000_add_event_origin'` + // The window starts there: a database without it would make the test prove nothing. + if (!finished[0]?.finished_at) throw new Error('20261119120000_add_event_origin has not been applied') + const inWindow = new Date(finished[0].finished_at.getTime() + 60_000) + const before = new Date('2020-01-01T00:00:00Z') + + const stamp = `catch-up-${process.pid}-${globalThis.performance.now().toString().replace('.', '')}` + const congregationId = (await tx.congregation.create({ data: { name: stamp, slug: stamp, active: true } })).id + const templateId = ( + await tx.eventTemplate.create({ data: { name: 'Réunion', key: `midweek-${stamp}`, congregationId } }) + ).id + const author = await tx.userAccount.create({ + data: { email: `${stamp}@test.com`, password: 'x', congregationId }, + }) + + const insert = async (name: string, createdAt: Date, updatedAt: Date, extra = '') => { + const rows = await tx.$queryRawUnsafe<{ id: number }[]>( + `INSERT INTO "Event" ("name", "startDate", "endDate", "templateId", "congregationId", "createdAt", "updatedAt"${extra ? ', "createdById"' : ''}) + VALUES ($1, $2, $2, $3, $4, $5, $6${extra ? `, ${extra}` : ''}) RETURNING "id"`, + name, + new Date('2027-01-05T18:00:00Z'), + templateId, + congregationId, + createdAt, + updatedAt, + ) + return rows[0].id + } + + const ids: Record = { + // The previous image's job, during the rollout: empty, no author, never written since. + rolloutJob: await insert('rollout job', inWindow, inWindow), + // Older than the window: 20261119120000_add_event_origin's own backfill already decided it. + beforeWindow: await insert('before the window', before, before), + // Made by hand in the window, its author's account deleted since: clearing the author was a write. + authorCleared: await insert('author cleared', inWindow, new Date(inWindow.getTime() + 3_600_000)), + // Made by hand, still with its author. + authored: await insert('authored', inWindow, inWindow, String(author.id)), + } + // Prepared during the window: a part on it. + ids.prepared = await insert('prepared', inWindow, inWindow) + await tx.eventPart.create({ data: { name: 'Cantique', eventId: ids.prepared, congregationId } }) + + const read = async () => { + const rows = await tx.event.findMany({ where: { congregationId }, select: { name: true, origin: true } }) + return Object.fromEntries(rows.map(row => [row.name, row.origin])) + } + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + const first = await read() + for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement) + result = { first, second: await read() } + throw new Rollback() + }) + } catch (error) { + if (!(error instanceof Rollback)) throw error + } + return result as { first: Record; second: Record } + })() + return memo +} + +afterAll(async () => { + await testDb.$disconnect() +}) + +describe('20261120090100_catch_up_event_origin', () => { + it('gives « job » to the previous image’s empty meetings of the rollout, and to nothing else', async () => { + const { first } = await snapshot() + + expect(first).toEqual({ + 'rollout job': 'job', + 'before the window': 'manual', + 'author cleared': 'manual', + authored: 'manual', + prepared: 'manual', + }) + }) + + it('changes nothing when run twice', async () => { + const { first, second } = await snapshot() + + expect(second).toEqual(first) + }) +}) diff --git a/app/database/schema.prisma b/app/database/schema.prisma index c54dd78c..62161343 100644 --- a/app/database/schema.prisma +++ b/app/database/schema.prisma @@ -160,6 +160,7 @@ model Congregation { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt + absences Absence[] } // A person currently part of this congregation. Holds identity, demographics, @@ -261,6 +262,7 @@ model Member { @@index([congregationId, leftAt]) @@index([congregationId, firstnameNormalized]) @@index([congregationId, lastnameNormalized]) + absences Absence[] } // A person to contact about a Member in an emergency — either to get @@ -357,6 +359,7 @@ model UserAccount { updatedAt DateTime @updatedAt @@unique([id, congregationId]) + absences Absence[] } model Permission { @@ -1616,6 +1619,35 @@ model NotificationPreference { @@unique([id, congregationId]) } +/// An absence: the days a person is away, so nobody assigns them a part then. It belongs to the person — their record +/// when the account that declared it had one when it was written, the account otherwise (CHECK: one of the two). Written alongside the +/// day-off event it was copied from until the readers move over and the events are dropped (legacyEventId). +model Absence { + id Int @id @default(autoincrement()) + // Copied as stored: legacy rows sit at midnight UTC (app/features/events/model/absence.ts). + startDate DateTime + endDate DateTime + note String @default("") + + member Member? @relation(fields: [memberId], references: [id], onDelete: Cascade) + memberId Int? + // Who declared it; the owner when there is no record. Restrict: deleting an account lets go of its absences first. + account UserAccount? @relation(fields: [accountId], references: [id], onDelete: Restrict) + accountId Int? + + legacyEventId Int? @unique + + createdAt DateTime @default(now()) + + congregation Congregation @relation(fields: [congregationId], references: [id], onDelete: Cascade) + congregationId Int + + @@unique([id, congregationId]) + @@index([congregationId, startDate]) + @@index([memberId]) + @@index([accountId]) +} + // The two counts of one meeting, entered while it runs: in the hall, and by videoconference (Zoom and phone together, as // the branch report counts them). Null = not entered yet, never 0; the meeting counts in averages only once both are // set. Each count keeps who entered or last changed it. diff --git a/app/database/seed-marketing.ts b/app/database/seed-marketing.ts index b861d131..5c4e4600 100644 --- a/app/database/seed-marketing.ts +++ b/app/database/seed-marketing.ts @@ -79,6 +79,8 @@ async function cleanCongregationData(congregationId: number) { await prisma.templateResponsible.deleteMany({ where }) await prisma.templateServicePart.deleteMany({ where }) await prisma.templatePart.deleteMany({ where }) + // Before the events and the accounts: an Absence row names its account (Restrict), not its event. + await prisma.absence.deleteMany({ where }) await prisma.event.deleteMany({ where }) await prisma.eventTemplate.deleteMany({ where }) // After the parts that point at them, before the congregation itself: the FK to Congregation restricts. @@ -664,7 +666,7 @@ async function main() { const dayOff = await prisma.eventTemplate.findFirstOrThrow({ where: { key: EventTemplateKey.DayOff, congregationId }, }) - await prisma.event.createMany({ + const absenceEvents = await prisma.event.createManyAndReturn({ data: absences.map(absence => ({ name: absence.name, startDate: absence.start, @@ -675,6 +677,18 @@ async function main() { createdById: accounts.get(absence.person) as number, congregationId, })), + select: { id: true }, + }) + // Written twice, as createDayOff does while the readers move over: the day-off event, and its Absence row. + await prisma.absence.createMany({ + data: absences.map((absence, index) => ({ + startDate: absence.start, + endDate: absence.end, + memberId: members[absence.person] as number, + accountId: accounts.get(absence.person) as number, + legacyEventId: absenceEvents[index]?.id as number, + congregationId, + })), }) console.log(` ✓ ${meetingCount} meetings, ${absences.length} absences, ${speakerRows.length} visiting speakers`) diff --git a/app/features/events/server/account-events.server.test.ts b/app/features/events/server/account-events.server.test.ts index 189d29c0..dd03bc56 100644 --- a/app/features/events/server/account-events.server.test.ts +++ b/app/features/events/server/account-events.server.test.ts @@ -4,6 +4,7 @@ const { releaseAccountEvents, AccountHasAbsencesError } = await import('./accoun const db = { event: { findMany: vi.fn(), deleteMany: vi.fn(), updateMany: vi.fn() }, + absence: { deleteMany: vi.fn() }, } const ABSENCE = { id: 31, startDate: new Date('2027-01-12T00:00:00Z'), endDate: new Date('2027-01-14T22:59:00Z') } @@ -13,6 +14,7 @@ beforeEach(() => { db.event.findMany.mockResolvedValue([]) db.event.deleteMany.mockResolvedValue({ count: 0 }) db.event.updateMany.mockResolvedValue({ count: 0 }) + db.absence.deleteMany.mockResolvedValue({ count: 0 }) }) describe('releaseAccountEvents', () => { @@ -39,6 +41,7 @@ describe('releaseAccountEvents', () => { ) expect(db.event.deleteMany).not.toHaveBeenCalled() expect(db.event.updateMany).not.toHaveBeenCalled() + expect(db.absence.deleteMany).not.toHaveBeenCalled() }) it('only clears the author of an account linked to a record without absences', async () => { diff --git a/app/features/events/server/account-events.server.ts b/app/features/events/server/account-events.server.ts index 9817c15b..a700c1dc 100644 --- a/app/features/events/server/account-events.server.ts +++ b/app/features/events/server/account-events.server.ts @@ -4,20 +4,22 @@ import type { TransactionClient } from '~/shared/infra/db.server' /** * Refused: the account is linked to a record and has absences. They are the person's, not the login's: an - * administrator cannot delete someone else's absences, so the account stays until it can hand them to its record. + * administrator cannot delete someone else's absences, and the readers still read the day-off events the account + * owns, so the account stays until the events are dropped — their Absence rows already name the record. */ export class AccountHasAbsencesError extends ConflictError {} export interface ReleasedAccountEvents { - /** The absences deleted with an account that has no record, for the audit trail. */ + /** The day-off events deleted with an account that has no record, for the audit trail. */ absencesDeleted: { id: number; startDate: Date; endDate: Date }[] /** How many of its other events lost their author. */ eventsUnattributed: number } /** - * Lets go of the events an account created, before the account is deleted (from Réglages, or by taking a login away - * from a record): `Event.createdBy` is Restrict, so the account could not go otherwise. + * Lets go of the events an account created, and of its Absence rows, before the account is deleted (from Réglages, or + * by taking a login away from a record): `Event.createdBy` and `Absence.accountId` are Restrict, so the account could + * not go otherwise. * * Its absences go with an account that has no record — nobody else is away on them, and they flagged no assignment, * since absences flag through the record. An account with a record and absences is refused (AccountHasAbsencesError). @@ -39,6 +41,9 @@ export async function releaseAccountEvents( if (absences.length > 0) { await db.event.deleteMany({ where: { congregationId, id: { in: absences.map(absence => absence.id) } } }) } + // Every Absence row still naming the account (accountId is Restrict): those of the absences just deleted, and any + // whose event went without them (the previous version, during the rollout). + await db.absence.deleteMany({ where: { congregationId, accountId: account.id } }) const unattributed = await db.event.updateMany({ where: { congregationId, createdById: account.id }, data: { createdById: null }, diff --git a/app/features/events/server/days-off.server.integration.test.ts b/app/features/events/server/days-off.server.integration.test.ts new file mode 100644 index 00000000..059a3e43 --- /dev/null +++ b/app/features/events/server/days-off.server.integration.test.ts @@ -0,0 +1,132 @@ +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// While the readers still read the day-off events, an absence is written twice, in one transaction: the event, and its +// Absence row — the person's record when the account has one. Deleting it removes both. + +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 { createDayOff, deleteDayOff } = await import('./days-off.server') + +const ts = Date.now() +const ids = { cong: 0, other: 0, member: 0, account: 0, accountWithoutRecord: 0 } +const START = new Date('2027-04-05T00:00:00Z') +const END = new Date('2027-04-09T23:59:00Z') + +beforeAll(async () => { + for (const key of ['cong', 'other'] as const) { + const congregationId = ( + await testDb.congregation.create({ + data: { name: `Days off ${key} ${ts}`, slug: `days-off-${key}-${ts}`, active: true }, + }) + ).id + ids[key] = congregationId + await withScope(congregationId, async tx => { + await tx.eventTemplate.create({ data: { name: 'Absence', key: 'day-off', congregationId } }) + const member = await tx.member.create({ data: { firstname: 'Paul', lastname: 'MARTIN', congregationId } }) + const account = await tx.userAccount.create({ + data: { email: `paul-${key}-${ts}@test.com`, password: 'x', memberId: member.id, congregationId }, + }) + const withoutRecord = await tx.userAccount.create({ + data: { email: `sans-${key}-${ts}@test.com`, password: 'x', congregationId }, + }) + if (key === 'cong') { + ids.member = member.id + ids.account = account.id + ids.accountWithoutRecord = withoutRecord.id + } + // One absence each before any test: the isolation test reads both sides. + await createDayOff(tx, account.id, member.id, START, END, congregationId) + }) + } +}) + +afterAll(async () => { + for (const congregationId of [ids.cong, ids.other]) { + if (!congregationId) continue + await withScope(congregationId, async tx => { + await tx.absence.deleteMany({}) + await tx.event.deleteMany({}) + await tx.eventTemplate.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.auditLog.deleteMany({ where: { congregationId } }) + await testDb.congregation.deleteMany({ where: { id: congregationId } }) + } + await testDb.$disconnect() +}) + +const absenceOf = (eventId: number) => + withScope(ids.cong, tx => + tx.absence.findFirst({ + where: { legacyEventId: eventId }, + select: { startDate: true, endDate: true, memberId: true, accountId: true, congregationId: true }, + }), + ) + +describe('an absence written twice', () => { + it('writes the event and its Absence row, with the person’s record', async () => { + const event = await withScope(ids.cong, tx => createDayOff(tx, ids.account, ids.member, START, END, ids.cong)) + + expect(await absenceOf(event?.id as number)).toEqual({ + startDate: START, + endDate: END, + memberId: ids.member, + accountId: ids.account, + congregationId: ids.cong, + }) + }) + + it('keeps the account as the owner when it has no record', async () => { + const event = await withScope(ids.cong, tx => + createDayOff(tx, ids.accountWithoutRecord, null, START, END, ids.cong), + ) + + expect(await absenceOf(event?.id as number)).toMatchObject({ memberId: null, accountId: ids.accountWithoutRecord }) + }) + + it('deletes the event and its Absence row together', async () => { + const event = await withScope(ids.cong, tx => createDayOff(tx, ids.account, ids.member, START, END, ids.cong)) + const eventId = event?.id as number + expect(await absenceOf(eventId)).not.toBeNull() + + await withScope(ids.cong, tx => + deleteDayOff(tx, { eventId, accountId: ids.account, memberId: ids.member, congregationId: ids.cong }), + ) + + expect(await absenceOf(eventId)).toBeNull() + expect(await withScope(ids.cong, tx => tx.event.findFirst({ where: { id: eventId } }))).toBeNull() + }) + + it('never shows another congregation’s absences, nor writes into them', async () => { + const ours = await withScope(ids.cong, tx => tx.absence.count({ where: { congregationId: ids.cong } })) + const seen = await withScope(ids.cong, tx => tx.absence.count()) + const theirs = await withScope(ids.other, tx => tx.absence.count()) + const intrusion = withScope(ids.cong, tx => + tx.absence.create({ + data: { startDate: START, endDate: END, accountId: ids.account, congregationId: ids.other }, + }), + ) + + expect(theirs).toBe(1) + expect(ours).toBeGreaterThan(0) + expect(seen).toBe(ours) + await expect(intrusion).rejects.toThrow() + }) +}) diff --git a/app/features/events/server/days-off.server.test.ts b/app/features/events/server/days-off.server.test.ts index 4194e791..c37e955d 100644 --- a/app/features/events/server/days-off.server.test.ts +++ b/app/features/events/server/days-off.server.test.ts @@ -8,6 +8,7 @@ vi.mock('~/shared/domain/audit.server', () => ({ vi.mock('~/shared/infra/db.server', () => ({ unscopedDb: { event: { findMany: vi.fn(), findFirst: vi.fn(), create: vi.fn(), delete: vi.fn() }, + absence: { create: vi.fn(), deleteMany: vi.fn() }, eventTemplate: { findFirst: vi.fn() }, eventPart: { updateMany: vi.fn() }, eventServicePart: { updateMany: vi.fn() }, @@ -22,6 +23,8 @@ beforeEach(() => { vi.resetAllMocks() // Default: no overlapping programme events for conflict refresh vi.mocked(db.event.findMany).mockResolvedValue([] as never) + vi.mocked(db.absence.create).mockResolvedValue({} as never) + vi.mocked(db.absence.deleteMany).mockResolvedValue({ count: 0 } as never) }) describe('createDayOff', () => { @@ -170,6 +173,8 @@ describe('deleteDayOff', () => { expect(result).toBeNull() expect(db.event.delete).not.toHaveBeenCalled() + // Nor its Absence row: the two copies stay together. + expect(db.absence.deleteMany).not.toHaveBeenCalled() }) it('records the deletion in the audit trail', async () => { diff --git a/app/features/events/server/days-off.server.ts b/app/features/events/server/days-off.server.ts index 1d602e12..6a39cde3 100644 --- a/app/features/events/server/days-off.server.ts +++ b/app/features/events/server/days-off.server.ts @@ -22,10 +22,10 @@ export function getNextDaysOffs(db: TransactionClient, userId: number, congregat }) } -// `accountId` writes Event.createdBy. `memberId` (nullable — admin / circuit -// overseer accounts with no linked member) is what refreshConflictFlags needs -// to reconcile assignments; when it's null there can be no assignments to -// conflict, so we skip the refresh entirely. +// `accountId` writes Event.createdBy and Absence.accountId. `memberId` (null for +// an account without a record — administrators, circuit overseers) makes the +// Absence row the person's and drives refreshConflictFlags; when it's null +// there can be no assignments to conflict, so the refresh is skipped. export async function createDayOff( db: TransactionClient, accountId: number, @@ -65,6 +65,11 @@ export async function createDayOff( status: EventStatus.Released, }, }) + // Written twice while the readers still read the event: the day-off event, and its Absence row (the person's record + // when the account has one). + await db.absence.create({ + data: { startDate, endDate, memberId, accountId, legacyEventId: event.id, congregationId }, + }) if (memberId != null) { await refreshConflictFlags(db, memberId, startDate, endDate, congregationId) @@ -100,6 +105,7 @@ export async function deleteDayOff( }) if (own == null) return null + await db.absence.deleteMany({ where: { legacyEventId: eventId, congregationId } }) const event = await db.event.delete({ where: { id_congregationId: { id: eventId, congregationId }, diff --git a/app/features/events/server/delete-events.server.test.ts b/app/features/events/server/delete-events.server.test.ts index b7f80e8e..ebbed5a7 100644 --- a/app/features/events/server/delete-events.server.test.ts +++ b/app/features/events/server/delete-events.server.test.ts @@ -18,6 +18,7 @@ const mockDb = { eventServicePart: { deleteMany: vi.fn(), findMany: vi.fn() }, attendance: { findMany: vi.fn() }, notificationEvent: { updateMany: vi.fn() }, + absence: { deleteMany: vi.fn() }, $queryRaw: vi.fn(), } @@ -40,6 +41,10 @@ describe('bulkDeleteEvents', () => { expect(mockDb.event.deleteMany).toHaveBeenCalledWith({ where: { id: { in: [1, 2, 3] }, congregationId: 42 }, }) + // An absence's event among them takes its Absence row with it: the two copies never drift. + expect(mockDb.absence.deleteMany).toHaveBeenCalledWith({ + where: { legacyEventId: { in: [1, 2, 3] }, congregationId: 42 }, + }) }) // Governance: the same auditInTransaction pattern release/unrelease use. @@ -176,6 +181,7 @@ describe('deleteEvent', () => { expect(mockDb.event.delete).toHaveBeenCalledWith({ where: { id_congregationId: { id: 3, congregationId: 10 } }, }) + expect(mockDb.absence.deleteMany).toHaveBeenCalledWith({ where: { legacyEventId: 3, congregationId: 10 } }) expect(vi.mocked(auditModule.auditInTransaction)).toHaveBeenCalledWith( mockDb, expect.objectContaining({ action: 'event.deleted', entityId: 3, actorId: 7 }), diff --git a/app/features/events/server/delete-events.server.ts b/app/features/events/server/delete-events.server.ts index 1b50c8a5..225a4017 100644 --- a/app/features/events/server/delete-events.server.ts +++ b/app/features/events/server/delete-events.server.ts @@ -66,6 +66,8 @@ export async function bulkDeleteEvents(db: TransactionClient, ids: number[], con if (toDelete.length > 0) await cancelNoticesOf(db, toDelete, congregationId) const result = toDelete.length > 0 ? await db.event.deleteMany({ where: { id: { in: toDelete }, congregationId } }) : { count: 0 } + // An absence's event among them takes its Absence row (written alongside it, no foreign key) with it. + if (toDelete.length > 0) await db.absence.deleteMany({ where: { legacyEventId: { in: toDelete }, congregationId } }) // auditInTransaction (not audit) so the audit rows roll back with the // delete if the surrounding tx aborts. Matches release/unrelease. One row @@ -98,6 +100,7 @@ export async function deleteEvent( } await cancelNoticesOf(db, [id], congregationId) await db.event.delete({ where: { id_congregationId: { id, congregationId } } }) + await db.absence.deleteMany({ where: { legacyEventId: id, congregationId } }) await auditInTransaction(db, { action: AuditAction.EventDeleted, congregationId, diff --git a/app/features/events/server/draft-conflict-flow.integration.test.ts b/app/features/events/server/draft-conflict-flow.integration.test.ts index 2139af4c..988ae417 100644 --- a/app/features/events/server/draft-conflict-flow.integration.test.ts +++ b/app/features/events/server/draft-conflict-flow.integration.test.ts @@ -124,6 +124,7 @@ async function provisionCongregation(suffix: string) { afterAll(async () => { for (const congId of createdCongIds) { await testDb.eventPart.deleteMany({ where: { congregationId: congId } }) + await testDb.absence.deleteMany({ where: { congregationId: congId } }) await testDb.event.deleteMany({ where: { congregationId: congId } }) await testDb.eventTemplate.deleteMany({ where: { congregationId: congId } }) await testDb.userAccount.deleteMany({ where: { congregationId: congId } }) diff --git a/app/features/settings/server/data-transfer.integration.test.ts b/app/features/settings/server/data-transfer.integration.test.ts index ccdf12e4..163f167d 100644 --- a/app/features/settings/server/data-transfer.integration.test.ts +++ b/app/features/settings/server/data-transfer.integration.test.ts @@ -1923,3 +1923,87 @@ describe('the origin of restored events', () => { } }) }) + +// While absences are written twice, a restored absence gets its Absence row too: the readers move to that table before +// the archive carries it. Its owner's record when the restored account has one, as the migration does. +describe('restored absences', () => { + it('gives each restored day-off its Absence row, with the owner’s record', async () => { + const { importEvents } = await import('./import-events.server') + const cong = await testDb.congregation.create({ + data: { name: `Restored absences ${ts}`, slug: `restored-absences-${ts}`, active: true }, + }) + try { + const rows = await withScope(cong.id, async tx => { + const dayOff = await tx.eventTemplate.create({ + data: { name: 'Absence', key: 'day-off', congregationId: cong.id }, + }) + const member = await tx.member.create({ + data: { firstname: 'Paul', lastname: 'MARTIN', congregationId: cong.id }, + }) + const withRecord = await tx.userAccount.create({ + data: { email: `paul-restored-${ts}@test.com`, password: 'x', memberId: member.id, congregationId: cong.id }, + }) + const withoutRecord = await tx.userAccount.create({ + data: { email: `sans-restored-${ts}@test.com`, password: 'x', congregationId: cong.id }, + }) + const idMap = new EntityIdMap() + idMap.set('programme-templates', 9, dayOff.id) + idMap.set('user-accounts', 70, withRecord.id) + idMap.set('user-accounts', 71, withoutRecord.id) + const absence = (id: number, createdById: number) => ({ + id, + name: 'Absence', + description: 'Vacances', + startDate: '2027-05-03T00:00:00.000Z', + endDate: '2027-05-07T23:59:00.000Z', + templateId: 9, + createdById, + createdAt: '2027-04-01T08:00:00.000Z', + status: 'released', + origin: 'manual', + }) + const zip = new JsZip() + zip + .folder('data')! + .file('events.ndjson', [absence(1, 70), absence(2, 71)].map(row => `${JSON.stringify(row)}\n`).join('')) + + await importEvents(zip, tx, idMap, cong.id) + + return { + ids: { member: member.id, withRecord: withRecord.id, withoutRecord: withoutRecord.id }, + absences: await tx.absence.findMany({ + select: { note: true, memberId: true, accountId: true, startDate: true, legacyEventId: true }, + orderBy: { accountId: 'asc' }, + }), + events: await tx.event.findMany({ select: { id: true }, orderBy: { id: 'asc' } }), + } + }) + + expect(rows.absences).toEqual([ + { + note: 'Vacances', + memberId: rows.ids.member, + accountId: rows.ids.withRecord, + startDate: new Date('2027-05-03T00:00:00.000Z'), + legacyEventId: rows.events[0].id, + }, + { + note: 'Vacances', + memberId: null, + accountId: rows.ids.withoutRecord, + startDate: new Date('2027-05-03T00:00:00.000Z'), + legacyEventId: rows.events[1].id, + }, + ]) + } finally { + await withScope(cong.id, async tx => { + await tx.absence.deleteMany({}) + await tx.event.deleteMany({}) + await tx.eventTemplate.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.delete({ where: { id: cong.id } }) + } + }) +}) diff --git a/app/features/settings/server/delete-account.server.integration.test.ts b/app/features/settings/server/delete-account.server.integration.test.ts index 4f9c444b..0eabc1d4 100644 --- a/app/features/settings/server/delete-account.server.integration.test.ts +++ b/app/features/settings/server/delete-account.server.integration.test.ts @@ -59,6 +59,7 @@ beforeAll(async () => { afterAll(async () => { if (ids.cong) { await withScope(ids.cong, async tx => { + await tx.absence.deleteMany({}) await tx.event.deleteMany({}) await tx.eventTemplate.deleteMany({}) await tx.userRoleAssignment.deleteMany({}) @@ -89,6 +90,12 @@ async function account(name: string, { record, absence }: { record: boolean; abs data: { name, startDate: DAY, endDate: DAY, templateId, createdById: accountId, congregationId, ...extra }, }) const absenceId = absence ? (await event(ids.dayOffTemplate, { status: 'released' })).id : null + // Written twice, as createDayOff does: the event and its Absence row. + if (absenceId != null) { + await tx.absence.create({ + data: { startDate: DAY, endDate: DAY, memberId, accountId, legacyEventId: absenceId, congregationId }, + }) + } const meetingId = (await event(ids.meetingTemplate)).id return { accountId, absenceId, meetingId } }) @@ -97,6 +104,8 @@ async function account(name: string, { record, absence }: { record: boolean; abs const remove = (accountId: number) => withScope(ids.cong, tx => deleteAccount(tx, accountId as never, ids.cong, ids.admin, ADMIN)) +const absencesOf = (accountId: number) => withScope(ids.cong, tx => tx.absence.count({ where: { accountId } })) + const eventsOf = (eventIds: (number | null)[]) => withScope(ids.cong, tx => tx.event.findMany({ @@ -114,6 +123,7 @@ describe('deleteAccount and the events the account created', () => { 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' }]) + expect(await absencesOf(accountId)).toBe(0) }) it('refuses an account linked to a record that has absences, changing nothing', async () => { @@ -124,6 +134,32 @@ describe('deleteAccount and the events the account created', () => { const left = await withScope(ids.cong, tx => tx.userAccount.findFirst({ where: { id: accountId } })) expect(left).not.toBeNull() expect(await eventsOf([absenceId, meetingId])).toHaveLength(2) + expect(await absencesOf(accountId)).toBe(1) + }) + + // An Absence row whose event a previous version deleted without it still names the account (Restrict). + it('deletes an account linked to a record whose only absence row lost its event', async () => { + const { accountId } = await account('Reste', { record: true, absence: false }) + await withScope(ids.cong, async tx => { + const { memberId } = await tx.userAccount.findFirstOrThrow({ + where: { id: accountId }, + select: { memberId: true }, + }) + await tx.absence.create({ + data: { + startDate: DAY, + endDate: DAY, + memberId, + accountId, + legacyEventId: 999_999_999, + congregationId: ids.cong, + }, + }) + }) + + await remove(accountId) + + expect(await absencesOf(accountId)).toBe(0) }) it('deletes an account linked to a record without absences, clearing its author', async () => { diff --git a/app/features/settings/server/delete-account.server.ts b/app/features/settings/server/delete-account.server.ts index bdf489dc..264d3f7d 100644 --- a/app/features/settings/server/delete-account.server.ts +++ b/app/features/settings/server/delete-account.server.ts @@ -13,7 +13,8 @@ import type { AccountId } from '~/shared/types/branded' * lose their login. Tokens, permissions, and `UserRoleAssignment` rows * cascade via FK `onDelete`. * - * The events it created are let go of first (releaseAccountEvents): an account with a record and absences is refused. + * The events and Absence rows it created are let go of first (releaseAccountEvents): an account with a record and + * absences is refused. * * For anonymization (keep the row, scrub PII) call `anonymizeAccount` instead. * This service is the destructive variant. diff --git a/app/features/settings/server/import-events.server.ts b/app/features/settings/server/import-events.server.ts index 663271d6..90bd4507 100644 --- a/app/features/settings/server/import-events.server.ts +++ b/app/features/settings/server/import-events.server.ts @@ -59,6 +59,7 @@ export async function importEvents( // services and counts are in. One whose origin this version does not know stays « import ». let unknownOrigin = 0 const withoutOrigin: number[] = [] + const recordOf = new Map() for (const record of records) { const templateId = idMap.getOptional('programme-templates', record.templateId) const createdById = idMap.getOptional('user-accounts', record.createdById) @@ -84,6 +85,9 @@ export async function importEvents( idMap.set('events', record.id, created.id) if (record.origin == null) withoutOrigin.push(created.id) else if (!isEventOrigin(record.origin)) unknownOrigin++ + if (createdById != null && templateId != null && templateId === dayOff?.id) { + await writeAbsenceOf(db, { eventId: created.id, accountId: createdById, record, congregationId }, recordOf) + } } if (unknownOrigin > 0) { logger.warn(`Imported ${unknownOrigin} event(s) with an unknown origin as restored`, { congregationId }) @@ -97,6 +101,47 @@ export async function importEvents( return withoutOrigin } +/** + * A restored absence's Absence row, written alongside its event while the readers move over: its owner's record when + * the restored account has one, as the migration does. `recordOf` keeps each account's record once looked up. + */ +async function writeAbsenceOf( + db: TransactionClient, + { + eventId, + accountId, + record, + congregationId, + }: { + eventId: number + accountId: number + record: { startDate: string; endDate: string; description: string; createdAt: string } + congregationId: number + }, + recordOf: Map, +): Promise { + if (!recordOf.has(accountId)) { + // Restored earlier in the same import: missing, the restore is broken — fail rather than mis-own the absence. + const account = await db.userAccount.findFirstOrThrow({ + where: { id: accountId, congregationId }, + select: { memberId: true }, + }) + recordOf.set(accountId, account.memberId) + } + await db.absence.create({ + data: { + startDate: new Date(record.startDate), + endDate: new Date(record.endDate), + note: record.description ?? '', + memberId: recordOf.get(accountId) ?? null, + accountId, + legacyEventId: eventId, + createdAt: new Date(record.createdAt), + congregationId, + }, + }) +} + /** * 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 diff --git a/app/features/settings/server/link-member-to-account.server.test.ts b/app/features/settings/server/link-member-to-account.server.test.ts index 774d6cc0..9357cba9 100644 --- a/app/features/settings/server/link-member-to-account.server.test.ts +++ b/app/features/settings/server/link-member-to-account.server.test.ts @@ -28,6 +28,7 @@ const mockDb = { // The roles given to the login, moved onto the new record. userRoleAssignment: { findMany: vi.fn(), deleteMany: vi.fn() }, memberRoleAssignment: { upsert: vi.fn() }, + absence: { updateMany: vi.fn() }, } // biome-ignore lint/suspicious/noExplicitAny: partial mocked transaction client const dbCast = mockDb as any @@ -37,6 +38,7 @@ const { linkMemberToAccount } = await import('./link-member-to-account.server') beforeEach(() => { vi.resetAllMocks() mockDb.userRoleAssignment.findMany.mockResolvedValue([]) + mockDb.absence.updateMany.mockResolvedValue({ count: 0 }) }) const baseParams = { @@ -71,6 +73,19 @@ describe('linkMemberToAccount', () => { await expect(linkMemberToAccount(dbCast, baseCongregation, baseParams)).rejects.toThrow(ConflictError) }) + // The absences the login declared before it had a record are the person's from now on, like its day-off events. + it('gives the record the absences the login declared without one', async () => { + mockDb.userAccount.findFirst.mockResolvedValue({ id: 5, memberId: null, firstname: 'A', lastname: 'B' }) + mockCreateDirect.mockResolvedValue({ id: 10 }) + + await linkMemberToAccount(dbCast, baseCongregation, baseParams) + + expect(mockDb.absence.updateMany).toHaveBeenCalledWith({ + where: { accountId: 5, congregationId: 42, memberId: null }, + data: { memberId: 10 }, + }) + }) + it('checks the members limit before creating the member', async () => { mockDb.userAccount.findFirst.mockResolvedValue({ id: 5, memberId: null, firstname: 'A', lastname: 'B' }) mockCreateDirect.mockResolvedValue({ id: 10 }) diff --git a/app/features/settings/server/link-member-to-account.server.ts b/app/features/settings/server/link-member-to-account.server.ts index 6a8f8d7f..4cffb882 100644 --- a/app/features/settings/server/link-member-to-account.server.ts +++ b/app/features/settings/server/link-member-to-account.server.ts @@ -75,6 +75,11 @@ export async function linkMemberToAccount( }) // The roles given to the login now belong to the person: they move onto the record. await moveGivenRolesOntoRecord(db, account.id, member.id, params.congregationId) + // So do the absences it declared without a record, as its day-off events follow it through the account. + await db.absence.updateMany({ + where: { accountId: account.id, congregationId: params.congregationId, memberId: null }, + data: { memberId: member.id }, + }) audit({ action: AuditAction.AccountLinkedToMember, diff --git a/app/tests/fixtures/events-reference.ts b/app/tests/fixtures/events-reference.ts index f92c7f60..a079d269 100644 --- a/app/tests/fixtures/events-reference.ts +++ b/app/tests/fixtures/events-reference.ts @@ -536,6 +536,7 @@ export async function deleteReferenceCongregation(congregationId: number) { await db.boardDynamicDocumentSettings.deleteMany({ where }) await db.boardSectionVisibilityRole.deleteMany({ where }) await db.boardSection.deleteMany({ where }) + await db.absence.deleteMany({ where }) await db.attendance.deleteMany({ where }) await db.eventServicePartAllowedRole.deleteMany({ where }) await db.eventPartAllowedRole.deleteMany({ where }) diff --git a/docs/development/row-level-security.md b/docs/development/row-level-security.md index e89c167f..16dba73c 100644 --- a/docs/development/row-level-security.md +++ b/docs/development/row-level-security.md @@ -74,7 +74,7 @@ The authoritative source is the set of `CREATE POLICY tenant_isolation` statemen **Tenant-scoped (RLS enforced):** -Attendance, Attribution, AuditLog, BoardDocument, BoardDocumentVersion, BoardDocumentView, BoardDynamicDocumentSettings, BoardSection, BoardSectionVisibilityRole, Building, BuildingAccess, BuildingEntrance, BuildingResidentialData, Campaign, CampaignTerritory, ConsentRecord, DataDeletionRecord, Event, EventPart, EventPartAllowedRole, EventServicePart, EventServicePartAllowedRole, EventTemplate, ExternalSpeaker, Member, MemberRoleAssignment, NotificationEvent, NotificationPreference, PublisherActivity, PublisherGroup, Role, RolePermission, Setting, TemplatePart, TemplatePartAllowedRole, TemplateResponsible, TemplateServicePart, TemplateServicePartAllowedRole, Territory, TerritoryCardOverlay, TerritoryPerimeter, UserAccount, UserRoleAssignment. +Absence, Attendance, Attribution, AuditLog, BoardDocument, BoardDocumentVersion, BoardDocumentView, BoardDynamicDocumentSettings, BoardSection, BoardSectionVisibilityRole, Building, BuildingAccess, BuildingEntrance, BuildingResidentialData, Campaign, CampaignTerritory, ConsentRecord, DataDeletionRecord, Event, EventPart, EventPartAllowedRole, EventServicePart, EventServicePartAllowedRole, EventTemplate, ExternalSpeaker, Member, MemberRoleAssignment, NotificationEvent, NotificationPreference, PublisherActivity, PublisherGroup, Role, RolePermission, Setting, TemplatePart, TemplatePartAllowedRole, TemplateResponsible, TemplateServicePart, TemplateServicePartAllowedRole, Territory, TerritoryCardOverlay, TerritoryPerimeter, UserAccount, UserRoleAssignment. **Global (no `congregationId`, RLS not applicable):** diff --git a/scripts/check-tenant-scoping.ts b/scripts/check-tenant-scoping.ts index 22bafeab..275b850f 100644 --- a/scripts/check-tenant-scoping.ts +++ b/scripts/check-tenant-scoping.ts @@ -47,6 +47,7 @@ import { join, relative, sep } from 'node:path' // mirroring how check-aggregate-boundaries.ts hardcodes AGGREGATE_MODELS. export const TENANT_MODELS = [ 'member', + 'absence', 'userAccount', 'role', 'rolePermission',