From 9300f79619551e287a8fc7f668f9b635ff27c8dd Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 11:46:30 +0100 Subject: [PATCH 1/5] refactor(events): read conflicts from the absences table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Whether someone is away when assigned, the conflict flags on their assignments and the absences named while picking a person now read Absence by the person's record, instead of day-off events through the declaring account's record. Same answers: the references are unchanged. An absence row is enough on its own; a day-off event without one, as the previous version wrote during the rollout, no longer counts — the catch-up before the events are dropped copies it. --- .../absence-conflicts.integration.test.ts | 151 ++++++++++++++++++ .../event-part-assignments.server.test.ts | 68 ++++---- .../server/event-part-assignments.server.ts | 20 +-- .../refresh-conflict-flags.server.test.ts | 52 +++--- .../server/refresh-conflict-flags.server.ts | 11 +- ...candidate-facts.server.integration.test.ts | 14 +- .../server/slot-candidate-facts.server.ts | 12 +- 7 files changed, 232 insertions(+), 96 deletions(-) create mode 100644 app/features/events/server/absence-conflicts.integration.test.ts diff --git a/app/features/events/server/absence-conflicts.integration.test.ts b/app/features/events/server/absence-conflicts.integration.test.ts new file mode 100644 index 000000000..9d85a7b46 --- /dev/null +++ b/app/features/events/server/absence-conflicts.integration.test.ts @@ -0,0 +1,151 @@ +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// The conflict readers read absences from their own table, by the person's record: whether someone is away when they +// are assigned, the conflict flags on their assignments, and what the list of people to pick from says. An absence +// row is enough; the day-off event written alongside it no longer counts on its own. + +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 { checkDayOffConflict } = await import('./event-part-assignments.server') +const { refreshConflictFlags } = await import('./refresh-conflict-flags.server') +const { listSlotCandidateFacts } = await import('./slot-candidate-facts.server') + +const ts = Date.now() +const ids = { cong: 0, paul: 0, marie: 0, meeting: 0, paulPart: 0, mariePart: 0, service: 0 } +const MEETING_START = new Date('2027-06-08T17:00:00Z') +const MEETING_END = new Date('2027-06-08T19:00:00Z') +const AWAY_START = new Date('2027-06-07T00:00:00Z') +const AWAY_END = new Date('2027-06-10T23:59:00Z') + +beforeAll(async () => { + ids.cong = ( + await testDb.congregation.create({ + data: { name: `Conflicts ${ts}`, slug: `absence-conflicts-${ts}`, active: true }, + }) + ).id + await withScope(ids.cong, async tx => { + const congregationId = ids.cong + const dayOff = await tx.eventTemplate.create({ data: { name: 'Absence', key: 'day-off', congregationId } }) + const person = async (firstname: string) => { + const member = await tx.member.create({ data: { firstname, lastname: 'TEST', congregationId } }) + const account = await tx.userAccount.create({ + data: { email: `${firstname}-${ts}@test.com`, password: 'x', memberId: member.id, congregationId }, + }) + return { member: member.id, account: account.id } + } + const paul = await person('paul') + const marie = await person('marie') + ids.paul = paul.member + ids.marie = marie.member + + // Paul: an absence row only. Marie: a day-off event only, as the previous version wrote during the rollout. + await tx.absence.create({ + data: { + startDate: AWAY_START, + endDate: AWAY_END, + memberId: paul.member, + accountId: paul.account, + congregationId, + }, + }) + await tx.event.create({ + data: { + name: 'Absence', + startDate: AWAY_START, + endDate: AWAY_END, + status: 'released', + templateId: dayOff.id, + createdById: marie.account, + congregationId, + }, + }) + + const meeting = await tx.event.create({ + data: { name: 'Réunion', startDate: MEETING_START, endDate: MEETING_END, status: 'released', congregationId }, + }) + ids.meeting = meeting.id + ids.paulPart = ( + await tx.eventPart.create({ + data: { name: 'Lecture', eventId: meeting.id, assigneeId: paul.member, congregationId }, + }) + ).id + ids.mariePart = ( + await tx.eventPart.create({ + data: { name: 'Prière', eventId: meeting.id, assigneeId: marie.member, congregationId }, + }) + ).id + ids.service = (await tx.eventServicePart.create({ data: { name: 'Sono', eventId: meeting.id, congregationId } })).id + }) +}) + +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.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.deleteMany({ where: { id: ids.cong } }) + } + await testDb.$disconnect() +}) + +describe('the conflict readers and the absences table', () => { + it('says someone is away from their absence row', async () => { + const [paul, marie] = await withScope(ids.cong, tx => + Promise.all([ + checkDayOffConflict(tx, ids.paul, MEETING_START, MEETING_END, ids.cong), + checkDayOffConflict(tx, ids.marie, MEETING_START, MEETING_END, ids.cong), + ]), + ) + + expect({ paul, marie }).toEqual({ paul: true, marie: false }) + }) + + it('flags the assignments an absence row covers', async () => { + await withScope(ids.cong, async tx => { + await refreshConflictFlags(tx, ids.paul, AWAY_START, AWAY_END, ids.cong) + await refreshConflictFlags(tx, ids.marie, AWAY_START, AWAY_END, ids.cong) + }) + const flags = await withScope(ids.cong, tx => + tx.eventPart.findMany({ where: { eventId: ids.meeting }, select: { id: true, hasConflict: true } }), + ) + + expect(Object.fromEntries(flags.map(part => [part.id, part.hasConflict]))).toEqual({ + [ids.paulPart]: true, + [ids.mariePart]: false, + }) + }) + + it('names the absence in the facts about the people to pick from', async () => { + const facts = await withScope(ids.cong, tx => + listSlotCandidateFacts(tx, { + event: { id: ids.meeting, templateId: null, startDate: MEETING_START, endDate: MEETING_END }, + congregationId: ids.cong, + target: { kind: 'service', assignmentId: ids.service, serviceName: 'Sono' }, + }), + ) + + expect(facts.absences).toEqual({ + [ids.paul]: { startDate: AWAY_START.toISOString(), endDate: AWAY_END.toISOString() }, + }) + }) +}) diff --git a/app/features/events/server/event-part-assignments.server.test.ts b/app/features/events/server/event-part-assignments.server.test.ts index abc8b012b..07a689892 100644 --- a/app/features/events/server/event-part-assignments.server.test.ts +++ b/app/features/events/server/event-part-assignments.server.test.ts @@ -1,9 +1,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' -import { EventTemplateKey } from '~/features/events/model/event-template.type' vi.mock('~/shared/infra/db.server', () => ({ unscopedDb: { event: { findFirst: vi.fn(), findMany: vi.fn() }, + absence: { findFirst: vi.fn() }, eventPart: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn(), updateMany: vi.fn() }, eventServicePart: { findFirst: vi.fn(), @@ -44,33 +44,29 @@ beforeEach(() => { describe('checkDayOffConflict', () => { it('returns true when a day-off overlaps', async () => { - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 1 } as never) + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 1 } as never) const result = await checkDayOffConflict(db, 1, new Date(2026, 3, 14), new Date(2026, 3, 14), 1) expect(result).toBe(true) }) it('returns false when no day-off overlaps', async () => { - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) const result = await checkDayOffConflict(db, 1, new Date(2026, 3, 14), new Date(2026, 3, 14), 1) expect(result).toBe(false) }) - // Regression pin — the ID passed in is a Member.id (all call sites resolve - // participants via Member); day-off events store the creator's UserAccount.id - // in Event.createdById. Filtering by `createdBy: { memberId }` is the only - // shape that correctly joins the two. A prior version filtered by - // `createdById: memberId` which silently returned no results whenever the - // member's linked account.id differed from the member.id. - it('joins day-offs through Event.createdBy.memberId (not createdById)', async () => { - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + // Regression pin — the ID passed in is a Member.id (all call sites resolve participants via Member), and an absence + // belongs to that record. A prior version matched it against the declaring account's id, which silently found nothing + // whenever the account's id differed from the record's. + it('finds absences by the person’s record (not the declaring account)', async () => { + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) const memberId = 5000 await checkDayOffConflict(db, memberId, new Date(2026, 3, 14), new Date(2026, 3, 14), 1) - const firstCall = vi.mocked(db.event.findFirst).mock.calls[0][0] - const where = firstCall?.where as Record - expect(where.createdBy).toEqual({ memberId }) - expect(where).not.toHaveProperty('createdById') + const where = vi.mocked(db.absence.findFirst).mock.calls[0][0]?.where as Record + expect(where.memberId).toBe(memberId) + expect(where).not.toHaveProperty('accountId') }) }) @@ -86,7 +82,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1 } as never) await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -106,7 +102,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) // day-off found + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) // day-off found vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -126,7 +122,7 @@ describe('assignPart', () => { // the day-off checks rather than short-circuiting on eligibility. vi.mocked(allowedRoles.resolveEligibleUserIds).mockResolvedValue([5, 7]) // Speaker check: no day-off. Assistant check: day-off found. - vi.mocked(db.event.findFirst) + vi.mocked(db.absence.findFirst) .mockResolvedValueOnce(null as never) .mockResolvedValueOnce({ id: 99 } as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1 } as never) @@ -142,7 +138,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) // no day-off + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) // no day-off vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -159,7 +155,7 @@ describe('assignPart', () => { id: 1, event: { status: 'released', startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) // day-off found + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) // day-off found const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -174,7 +170,7 @@ describe('assignPart', () => { } as never) vi.mocked(allowedRoles.resolveEligibleUserIds).mockResolvedValue([5, 7]) // Speaker: no day-off. Reader: day-off found. - vi.mocked(db.event.findFirst) + vi.mocked(db.absence.findFirst) .mockResolvedValueOnce(null as never) .mockResolvedValueOnce({ id: 99 } as never) @@ -189,7 +185,7 @@ describe('assignPart', () => { id: 1, event: { status: 'draft', startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -209,7 +205,7 @@ describe('assignPart', () => { assistantId: 9, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -223,7 +219,7 @@ describe('assignPart', () => { assistantId: null, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -263,7 +259,7 @@ describe('assignPart', () => { // Reader fetch (asKind: 'reader') → restrictive list, eligible = [42] vi.mocked(allowedRoles.getPartAssignmentAllowedRoleIds).mockResolvedValueOnce([]).mockResolvedValueOnce([99]) vi.mocked(allowedRoles.resolveEligibleUserIds).mockResolvedValueOnce([5]).mockResolvedValueOnce([42]) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) const result = await assignPart(db, 1, 5, 7, null, 'Topic', 1) expect(result).toHaveProperty('error') @@ -324,7 +320,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1 } as never) await assignPart(db, 1, 5, null, null, 'Topic', 1, 12) @@ -352,7 +348,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1 } as never) await assignPart(db, 1, 5, null, null, 'Topic', 1, null) @@ -366,7 +362,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventPart.update).mockResolvedValue({ id: 1 } as never) await assignPart(db, 1, 5, null, null, 'Topic', 1) @@ -385,7 +381,7 @@ describe('assignPart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(allowedRoles.resolveEligibleUserIds).mockResolvedValue([5]) const result = await assignPart(db, 1, 5, 5, null, 'Topic', 1) @@ -407,7 +403,7 @@ describe('assignServicePart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1 } as never) await assignServicePart(db, 1, 5, 1) @@ -425,7 +421,7 @@ describe('assignServicePart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignServicePart(db, 1, 5, 1) @@ -440,7 +436,7 @@ describe('assignServicePart', () => { id: 1, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignServicePart(db, 1, 5, 1) @@ -455,7 +451,7 @@ describe('assignServicePart', () => { id: 1, event: { status: 'released', startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) const result = await assignServicePart(db, 1, 5, 1) @@ -468,7 +464,7 @@ describe('assignServicePart', () => { id: 1, event: { status: 'draft', startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue({ id: 99 } as never) + vi.mocked(db.absence.findFirst).mockResolvedValue({ id: 99 } as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignServicePart(db, 1, 5, 1) @@ -484,7 +480,7 @@ describe('assignServicePart', () => { assigneeId: 8, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignServicePart(db, 1, 5, 1) @@ -497,7 +493,7 @@ describe('assignServicePart', () => { assigneeId: null, event: { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, } as never) - vi.mocked(db.event.findFirst).mockResolvedValue(null as never) + vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) vi.mocked(db.eventServicePart.update).mockResolvedValue({ id: 1, assigneeId: 5 } as never) const result = await assignServicePart(db, 1, 5, 1) diff --git a/app/features/events/server/event-part-assignments.server.ts b/app/features/events/server/event-part-assignments.server.ts index a482f7506..b4530a71a 100644 --- a/app/features/events/server/event-part-assignments.server.ts +++ b/app/features/events/server/event-part-assignments.server.ts @@ -1,5 +1,4 @@ import { EventStatus } from '~/features/events/model/event-status.type' -import { EventTemplateKey } from '~/features/events/model/event-template.type' import { getPartAssignmentAllowedRoleIds, getServicePartAssignmentAllowedRoleIds, @@ -253,10 +252,8 @@ export async function unassignServicePart(db: TransactionClient, assignmentId: n return { assignment, previousAssigneeId: existing.assigneeId } } -// The `memberId` here is Member.id. Day-off events store the creator's -// UserAccount.id in Event.createdById, so we join through -// Event.createdBy.memberId to resolve the absence back to the same Member -// that carries assignments (assigneeId / assistantId reference Member). +// The `memberId` here is Member.id, the one that carries assignments (assigneeId / assistantId reference Member): an +// absence belongs to that record. One declared from an account without a record is nobody's assignment to block. export async function checkDayOffConflict( db: TransactionClient, memberId: number, @@ -264,15 +261,10 @@ export async function checkDayOffConflict( endDate: Date, congregationId: number, ): Promise { - const conflictingDayOff = await db.event.findFirst({ - where: { - congregationId, - createdBy: { memberId }, - template: { key: EventTemplateKey.DayOff }, - startDate: { lte: endDate }, - endDate: { gte: startDate }, - }, + const conflictingAbsence = await db.absence.findFirst({ + where: { congregationId, memberId, startDate: { lte: endDate }, endDate: { gte: startDate } }, + select: { id: true }, }) - return conflictingDayOff != null + return conflictingAbsence != null } diff --git a/app/features/events/server/refresh-conflict-flags.server.test.ts b/app/features/events/server/refresh-conflict-flags.server.test.ts index 2c2154a33..9b312de1b 100644 --- a/app/features/events/server/refresh-conflict-flags.server.test.ts +++ b/app/features/events/server/refresh-conflict-flags.server.test.ts @@ -4,6 +4,7 @@ import { EventTemplateKey } from '~/features/events/model/event-template.type' vi.mock('~/shared/infra/db.server', () => ({ unscopedDb: { event: { findMany: vi.fn() }, + absence: { findMany: vi.fn() }, eventPart: { findMany: vi.fn(), updateMany: vi.fn() }, eventServicePart: { findMany: vi.fn(), updateMany: vi.fn() }, }, @@ -17,29 +18,21 @@ beforeEach(() => { }) describe('refreshConflictFlags', () => { - // `db.event.findMany` now serves two distinct queries: the overlapping-events lookup and - // the single batched absence lookup. Route on the day-off template filter, exactly as the - // real shapes differ, so one mock can stand in for both. + // The overlapping events come from `db.event.findMany`, the absences from `db.absence.findMany` in one batched query. // // `absentMemberIds` are the members who HAVE an overlapping absence. Their stub absence // spans a deliberately wide range so it overlaps every event in the fixture — matching the // old per-(member, event) stub, which reported a conflict regardless of the event's dates. function stubEventsAndAbsences(events: unknown[], absentMemberIds: number[]) { const absent = new Set(absentMemberIds) + vi.mocked(db.event.findMany).mockResolvedValue(events as never) // biome-ignore lint/suspicious/noExplicitAny: mock signature needs to match Prisma's generated overloads - vi.mocked(db.event.findMany).mockImplementation(((args: any) => { - const where = args?.where ?? {} - if (where.template?.key !== EventTemplateKey.DayOff) return Promise.resolve(events) - - const requested = (where.createdBy?.memberId?.in ?? []) as number[] + vi.mocked(db.absence.findMany).mockImplementation(((args: any) => { + const requested = (args?.where?.memberId?.in ?? []) as number[] return Promise.resolve( requested .filter(id => absent.has(id)) - .map(id => ({ - startDate: new Date(2000, 0, 1), - endDate: new Date(2100, 0, 1), - createdBy: { memberId: id }, - })), + .map(id => ({ startDate: new Date(2000, 0, 1), endDate: new Date(2100, 0, 1), memberId: id })), ) }) as never) } @@ -121,13 +114,14 @@ describe('refreshConflictFlags', () => { await refreshConflictFlags(db, 5, new Date(2026, 3, 13), new Date(2026, 3, 16), 1) - // Exactly two event.findMany calls: overlapping events, then all absences at once. - const calls = vi.mocked(db.event.findMany).mock.calls - expect(calls).toHaveLength(2) + // One events query, then all absences at once. + expect(vi.mocked(db.event.findMany).mock.calls).toHaveLength(1) + const calls = vi.mocked(db.absence.findMany).mock.calls + expect(calls).toHaveLength(1) - // …and that second call asks for every distinct participant in one `in` clause. - const absenceWhere = calls[1][0]?.where as { createdBy?: { memberId?: { in?: number[] } } } - expect([...(absenceWhere.createdBy?.memberId?.in ?? [])].sort()).toEqual([5, 6, 7]) + // …asking for every distinct participant in one `in` clause. + const absenceWhere = calls[0][0]?.where as { memberId?: { in?: number[] } } + expect([...(absenceWhere.memberId?.in ?? [])].sort()).toEqual([5, 6, 7]) // The per-row outcome still respects each row's own participants. expect( @@ -149,19 +143,13 @@ describe('refreshConflictFlags', () => { // a regression there would mark every event conflicted once any absence existed. it('only flags the events an absence actually overlaps', async () => { // Absence covers 14 Apr only; event 1 is on the 14th, event 2 on the 20th. - // biome-ignore lint/suspicious/noExplicitAny: mock signature needs to match Prisma's generated overloads - vi.mocked(db.event.findMany).mockImplementation(((args: any) => { - const where = args?.where ?? {} - if (where.template?.key !== EventTemplateKey.DayOff) { - return Promise.resolve([ - { id: 1, startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, - { id: 2, startDate: new Date(2026, 3, 20), endDate: new Date(2026, 3, 20) }, - ]) - } - return Promise.resolve([ - { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14), createdBy: { memberId: 5 } }, - ]) - }) as never) + vi.mocked(db.event.findMany).mockResolvedValue([ + { id: 1, startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14) }, + { id: 2, startDate: new Date(2026, 3, 20), endDate: new Date(2026, 3, 20) }, + ] as never) + vi.mocked(db.absence.findMany).mockResolvedValue([ + { startDate: new Date(2026, 3, 14), endDate: new Date(2026, 3, 14), memberId: 5 }, + ] as never) vi.mocked(db.eventPart.findMany).mockResolvedValue([ { id: 100, eventId: 1, assigneeId: 5, assistantId: null }, { id: 101, eventId: 2, assigneeId: 5, assistantId: null }, diff --git a/app/features/events/server/refresh-conflict-flags.server.ts b/app/features/events/server/refresh-conflict-flags.server.ts index 00bab5311..6aa25536c 100644 --- a/app/features/events/server/refresh-conflict-flags.server.ts +++ b/app/features/events/server/refresh-conflict-flags.server.ts @@ -82,21 +82,20 @@ export async function refreshConflictFlags( const dayOffs = participantIds.size === 0 ? [] - : await db.event.findMany({ + : await db.absence.findMany({ where: { congregationId, - template: { key: EventTemplateKey.DayOff }, - createdBy: { memberId: { in: [...participantIds] } }, + memberId: { in: [...participantIds] }, startDate: { lte: windowEnd }, endDate: { gte: windowStart }, }, - // Absences resolve to a Member through Event.createdBy — see checkDayOffConflict. - select: { startDate: true, endDate: true, createdBy: { select: { memberId: true } } }, + // An absence belongs to the person's record — see checkDayOffConflict. + select: { startDate: true, endDate: true, memberId: true }, }) const dayOffsByMember = new Map() for (const dayOff of dayOffs) { - const absentMemberId = dayOff.createdBy?.memberId + const absentMemberId = dayOff.memberId if (absentMemberId == null) continue const ranges = dayOffsByMember.get(absentMemberId) ?? [] ranges.push({ start: dayOff.startDate.getTime(), end: dayOff.endDate.getTime() }) diff --git a/app/features/events/server/slot-candidate-facts.server.integration.test.ts b/app/features/events/server/slot-candidate-facts.server.integration.test.ts index 3b2316301..e00e92da9 100644 --- a/app/features/events/server/slot-candidate-facts.server.integration.test.ts +++ b/app/features/events/server/slot-candidate-facts.server.integration.test.ts @@ -128,7 +128,8 @@ beforeAll(async () => { data: { name: 'Sono', eventId: lastSummer.id, assigneeId: members.sono, congregationId }, }) - await tx.event.create({ + // Written twice, as createDayOff does: the day-off event and its Absence row, the person's. + const absence = await tx.event.create({ data: { name: 'Absence', templateId: dayOff.id, @@ -138,6 +139,16 @@ beforeAll(async () => { congregationId, }, }) + await tx.absence.create({ + data: { + startDate: absence.startDate, + endDate: absence.endDate, + memberId: members.away, + accountId: awayAccount.id, + legacyEventId: absence.id, + congregationId, + }, + }) }) }) @@ -146,6 +157,7 @@ afterAll(async () => { await withScope(congregationId, async tx => { await tx.eventServicePart.deleteMany({}) await tx.eventPart.deleteMany({}) + await tx.absence.deleteMany({}) await tx.event.deleteMany({}) await tx.externalSpeaker.deleteMany({}) await tx.eventTemplate.deleteMany({}) diff --git a/app/features/events/server/slot-candidate-facts.server.ts b/app/features/events/server/slot-candidate-facts.server.ts index 4789fc2a2..2164ff586 100644 --- a/app/features/events/server/slot-candidate-facts.server.ts +++ b/app/features/events/server/slot-candidate-facts.server.ts @@ -1,4 +1,3 @@ -import { EventTemplateKey } from '~/features/events/model/event-template.type' import { normalize, type PartSlot } from '~/features/events/server/cadence-shared.server' import type { TransactionClient } from '~/shared/infra/db.server' @@ -107,20 +106,19 @@ async function absencesOverEvent( event: Options['event'], congregationId: number, ): Promise { - const rows = await db.event.findMany({ + const rows = await db.absence.findMany({ where: { congregationId, - template: { key: EventTemplateKey.DayOff }, startDate: { lte: event.endDate }, endDate: { gte: event.startDate }, - createdBy: { memberId: { not: null } }, + memberId: { not: null }, }, - orderBy: { startDate: 'asc' }, - select: { startDate: true, endDate: true, createdBy: { select: { memberId: true } } }, + orderBy: [{ startDate: 'asc' }, { id: 'asc' }], + select: { startDate: true, endDate: true, memberId: true }, }) const absences: SlotCandidateFacts['absences'] = {} for (const row of rows) { - const memberId = row.createdBy?.memberId + const memberId = row.memberId if (memberId != null && absences[memberId] == null) { absences[memberId] = { startDate: row.startDate.toISOString(), endDate: row.endDate.toISOString() } } From 7a48e388369f7d728e8acb683e4ce55920bbe62d Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 12:07:10 +0100 Subject: [PATCH 2/5] refactor(events): read the person panel's absences from the absences table The panel beside the list of people to pick from still read day-off events through the person's account, while the list itself reads Absence rows: the two could disagree. Both read the same table, by the person's record, with the same overlap rule (bounds included). --- .../routes/programs/events/publisher-info.tsx | 20 +---- .../absences.queries.integration.test.ts | 80 +++++++++++++++++++ .../events/server/absences.queries.ts | 20 +++++ 3 files changed, 104 insertions(+), 16 deletions(-) create mode 100644 app/features/events/server/absences.queries.integration.test.ts create mode 100644 app/features/events/server/absences.queries.ts diff --git a/app/features/events/routes/programs/events/publisher-info.tsx b/app/features/events/routes/programs/events/publisher-info.tsx index b9b1a2c44..d718fe938 100644 --- a/app/features/events/routes/programs/events/publisher-info.tsx +++ b/app/features/events/routes/programs/events/publisher-info.tsx @@ -1,4 +1,4 @@ -import { EventTemplateKey } from '~/features/events/model/event-template.type' +import { listAbsencesOverRange } from '~/features/events/server/absences.queries' import type { PartSlot } from '~/features/events/server/cadence-shared.server' import { mayReadSlotFacts } from '~/features/events/server/events-auth.server' import { listUserSameEventAssignments } from '~/features/events/server/list-user-same-event-assignments.server' @@ -56,24 +56,12 @@ export function loader({ request, params, context }: Route.LoaderArgs) { // Publisher profile const user = await db.member.findFirst({ where: { id: userId, congregationId }, - include: { publisherGroup: true, account: { select: { id: true } }, pioneerEnrolments: true }, + include: { publisherGroup: true, pioneerEnrolments: true }, }) if (!user) return Response.json(null) - // Days-off overlapping this event — created by the publisher's account - const accountId = user.account?.id - const daysOff = accountId - ? await db.event.findMany({ - where: { - congregationId, - createdById: accountId, - template: { key: EventTemplateKey.DayOff }, - startDate: { lte: event.endDate }, - endDate: { gte: event.startDate }, - }, - select: { id: true, startDate: true, endDate: true }, - }) - : [] + // The publisher's absences over this event, read as the list of people to pick from reads them. + const daysOff = await listAbsencesOverRange(db, userId, event.startDate, event.endDate, congregationId) const sameEventAssignments = await listUserSameEventAssignments(db, { userId, diff --git a/app/features/events/server/absences.queries.integration.test.ts b/app/features/events/server/absences.queries.integration.test.ts new file mode 100644 index 000000000..eb9675912 --- /dev/null +++ b/app/features/events/server/absences.queries.integration.test.ts @@ -0,0 +1,80 @@ +import { PrismaPg } from '@prisma/adapter-pg' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { PrismaClient } from '~/database/generated/client' + +// The absences of one person over a meeting, for the panel beside the list of people to pick from: the same table and +// the same overlap rule as the list itself, so the two never disagree. + +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 { listAbsencesOverRange } = await import('./absences.queries') + +const ts = Date.now() +const ids = { cong: 0, paul: 0, account: 0 } +const START = new Date('2027-06-08T17:00:00Z') +const END = new Date('2027-06-08T19:00:00Z') + +beforeAll(async () => { + ids.cong = ( + await testDb.congregation.create({ data: { name: `Absences ${ts}`, slug: `absences-queries-${ts}`, active: true } }) + ).id + await withScope(ids.cong, async tx => { + const congregationId = ids.cong + ids.paul = (await tx.member.create({ data: { firstname: 'Paul', lastname: 'MARTIN', congregationId } })).id + ids.account = ( + await tx.userAccount.create({ + data: { email: `paul-queries-${ts}@test.com`, password: 'x', memberId: ids.paul, congregationId }, + }) + ).id + const absence = (startDate: string, endDate: string) => + tx.absence.create({ + data: { + startDate: new Date(startDate), + endDate: new Date(endDate), + memberId: ids.paul, + accountId: ids.account, + congregationId, + }, + }) + await absence('2027-06-07T00:00:00Z', '2027-06-08T17:00:00Z') // ends as the meeting starts: covers it + await absence('2027-06-08T19:00:00Z', '2027-06-09T23:59:00Z') // starts as it ends: covers it + await absence('2027-06-01T00:00:00Z', '2027-06-08T16:59:59Z') // ends a second before: does not + }) +}) + +afterAll(async () => { + if (ids.cong) { + await withScope(ids.cong, async tx => { + await tx.absence.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.deleteMany({ where: { id: ids.cong } }) + } + await testDb.$disconnect() +}) + +describe('listAbsencesOverRange', () => { + it('gives the person’s absences touching the range, bounds included, in order', async () => { + const rows = await withScope(ids.cong, tx => listAbsencesOverRange(tx, ids.paul, START, END, ids.cong)) + + expect(rows.map(row => [row.startDate.toISOString(), row.endDate.toISOString()])).toEqual([ + ['2027-06-07T00:00:00.000Z', '2027-06-08T17:00:00.000Z'], + ['2027-06-08T19:00:00.000Z', '2027-06-09T23:59:00.000Z'], + ]) + }) +}) diff --git a/app/features/events/server/absences.queries.ts b/app/features/events/server/absences.queries.ts new file mode 100644 index 000000000..8aa0c91f0 --- /dev/null +++ b/app/features/events/server/absences.queries.ts @@ -0,0 +1,20 @@ +import type { TransactionClient } from '~/shared/infra/db.server' + +/** + * One person's absences touching a range, bounds included — the overlap rule checkDayOffConflict applies, so the + * panel beside the list of people to pick from never disagrees with the list. By the person's record: an absence + * declared from an account without one is nobody's. + */ +export function listAbsencesOverRange( + db: TransactionClient, + memberId: number, + startDate: Date, + endDate: Date, + congregationId: number, +) { + return db.absence.findMany({ + where: { congregationId, memberId, startDate: { lte: endDate }, endDate: { gte: startDate } }, + select: { id: true, startDate: true, endDate: true }, + orderBy: [{ startDate: 'asc' }, { id: 'asc' }], + }) +} From 5f1cf352c26f09b823dbe8482aa5e4b3d3bb027f Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 12:07:15 +0100 Subject: [PATCH 3/5] fix(settings): move an account's absences to the record a restore gives it Restoring an archive can link an existing account to a record from it, or unlink it. Its Absence rows now follow, as linking an account by hand already does, so conflicts keep following the person. --- .../server/data-transfer.integration.test.ts | 60 +++++++++++++++++++ .../server/import-user-accounts.server.ts | 7 +++ 2 files changed, 67 insertions(+) diff --git a/app/features/settings/server/data-transfer.integration.test.ts b/app/features/settings/server/data-transfer.integration.test.ts index 163f167d9..1b9f798d1 100644 --- a/app/features/settings/server/data-transfer.integration.test.ts +++ b/app/features/settings/server/data-transfer.integration.test.ts @@ -2007,3 +2007,63 @@ describe('restored absences', () => { } }) }) + +// A restore can link an existing account to a record from the archive. Its absences are the person's: their rows move +// to that record, as when an account is linked by hand, so conflicts keep following them. +describe('an existing account linked to a record by a restore', () => { + it('moves the account’s absences to the record the archive gives it', async () => { + const { importUserAccounts } = await import('./import-user-accounts.server') + const cong = await testDb.congregation.create({ + data: { name: `Relinked ${ts}`, slug: `relinked-${ts}`, active: true }, + }) + try { + const result = await withScope(cong.id, async tx => { + const account = await tx.userAccount.create({ + data: { email: `relinked-${ts}@test.com`, password: 'x', congregationId: cong.id }, + }) + // Declared before the restore, from an account without a record. + await tx.absence.create({ + data: { startDate: new Date(), endDate: new Date(), accountId: account.id, congregationId: cong.id }, + }) + const member = await tx.member.create({ + data: { firstname: 'Paul', lastname: 'MARTIN', congregationId: cong.id }, + }) + const idMap = new EntityIdMap() + idMap.set('members', 5, member.id) + const zip = new JsZip() + zip.folder('data')!.file( + 'user-accounts.ndjson', + `${JSON.stringify({ + id: 50, + email: `relinked-${ts}@test.com`, + firstname: null, + lastname: null, + active: true, + memberId: 5, + emailVerifiedAt: null, + anonymizedAt: null, + createdAt: '2026-01-01T00:00:00.000Z', + updatedAt: '2026-01-01T00:00:00.000Z', + })}\n`, + ) + + await importUserAccounts(zip, tx, idMap, cong.id) + + const absence = await tx.absence.findFirstOrThrow({ + where: { accountId: account.id }, + select: { memberId: true }, + }) + return { memberId: absence.memberId, expected: member.id } + }) + + expect(result.memberId).toBe(result.expected) + } finally { + await withScope(cong.id, async tx => { + await tx.absence.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.delete({ where: { id: cong.id } }) + } + }) +}) diff --git a/app/features/settings/server/import-user-accounts.server.ts b/app/features/settings/server/import-user-accounts.server.ts index 727434df9..8caa2550c 100644 --- a/app/features/settings/server/import-user-accounts.server.ts +++ b/app/features/settings/server/import-user-accounts.server.ts @@ -133,6 +133,13 @@ export async function importUserAccounts( ...(record.locale !== undefined && { locale: record.locale }), }, }) + // Its absences are the person's: they follow the record the archive gives the account, as linking it by hand does. + if (existing.memberId !== newMemberId) { + await db.absence.updateMany({ + where: { accountId: existing.id, congregationId }, + data: { memberId: newMemberId }, + }) + } idMap.set('user-accounts', record.id, existing.id) } else { logger.warn(`Skipping account ${record.email}: exists in another congregation`, { congregationId }) From c45298ac587742cc4ed0d612ae2060d50323d641 Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 12:07:20 +0100 Subject: [PATCH 4/5] test(events): prove the conflict readers ignore other congregations and absences without a record Someone of another congregation away the same days, and an absence declared from an account without a record, count for nobody; a flag set before a refresh must clear. The co-participant test writes and removes Alice's absence through createDayOff and deleteDayOff, so it still tests what it says. --- .../absence-conflicts.integration.test.ts | 50 ++++++++++++++++--- .../draft-conflict-flow.integration.test.ts | 28 ++++------- ...candidate-facts.server.integration.test.ts | 10 ++-- 3 files changed, 58 insertions(+), 30 deletions(-) diff --git a/app/features/events/server/absence-conflicts.integration.test.ts b/app/features/events/server/absence-conflicts.integration.test.ts index 9d85a7b46..bfa9b730b 100644 --- a/app/features/events/server/absence-conflicts.integration.test.ts +++ b/app/features/events/server/absence-conflicts.integration.test.ts @@ -3,8 +3,9 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest' import { PrismaClient } from '~/database/generated/client' // The conflict readers read absences from their own table, by the person's record: whether someone is away when they -// are assigned, the conflict flags on their assignments, and what the list of people to pick from says. An absence -// row is enough; the day-off event written alongside it no longer counts on its own. +// are assigned (checkDayOffConflict), the conflict flags on their assignments (refreshConflictFlags), and the absences +// named in the list of people to pick from (listSlotCandidateFacts). An absence row is enough; a day-off event without +// one, as the previous image writes during a rollout, no longer counts on its own — the later catch-up copies those. const adapter = new PrismaPg({ connectionString: process.env.DB_RUNTIME_URL ?? process.env.DB_URL, @@ -27,7 +28,7 @@ const { refreshConflictFlags } = await import('./refresh-conflict-flags.server') const { listSlotCandidateFacts } = await import('./slot-candidate-facts.server') const ts = Date.now() -const ids = { cong: 0, paul: 0, marie: 0, meeting: 0, paulPart: 0, mariePart: 0, service: 0 } +const ids = { cong: 0, other: 0, stranger: 0, paul: 0, marie: 0, meeting: 0, paulPart: 0, mariePart: 0, service: 0 } const MEETING_START = new Date('2027-06-08T17:00:00Z') const MEETING_END = new Date('2027-06-08T19:00:00Z') const AWAY_START = new Date('2027-06-07T00:00:00Z') @@ -54,7 +55,7 @@ beforeAll(async () => { ids.paul = paul.member ids.marie = marie.member - // Paul: an absence row only. Marie: a day-off event only, as the previous version wrote during the rollout. + // Paul: an absence row only. Marie: a day-off event only, as the previous image writes during a rollout. await tx.absence.create({ data: { startDate: AWAY_START, @@ -85,16 +86,48 @@ beforeAll(async () => { data: { name: 'Lecture', eventId: meeting.id, assigneeId: paul.member, congregationId }, }) ).id + // Flagged already: a day-off event alone must clear it, not merely leave the default. ids.mariePart = ( await tx.eventPart.create({ - data: { name: 'Prière', eventId: meeting.id, assigneeId: marie.member, congregationId }, + data: { name: 'Prière', eventId: meeting.id, assigneeId: marie.member, hasConflict: true, congregationId }, }) ).id + // Declared from an account without a record: nobody's assignment to block, nobody to name. + const withoutRecord = await tx.userAccount.create({ + data: { email: `sans-${ts}@test.com`, password: 'x', congregationId }, + }) + await tx.absence.create({ + data: { startDate: AWAY_START, endDate: AWAY_END, accountId: withoutRecord.id, congregationId }, + }) ids.service = (await tx.eventServicePart.create({ data: { name: 'Sono', eventId: meeting.id, congregationId } })).id }) + // Another congregation, with someone away over the same days. + ids.other = ( + await testDb.congregation.create({ + data: { name: `Elsewhere ${ts}`, slug: `absence-elsewhere-${ts}`, active: true }, + }) + ).id + await withScope(ids.other, async tx => { + const congregationId = ids.other + ids.stranger = (await tx.member.create({ data: { firstname: 'Jean', lastname: 'AILLEURS', congregationId } })).id + const account = await tx.userAccount.create({ + data: { email: `ailleurs-${ts}@test.com`, password: 'x', memberId: ids.stranger, congregationId }, + }) + await tx.absence.create({ + data: { startDate: AWAY_START, endDate: AWAY_END, memberId: ids.stranger, accountId: account.id, congregationId }, + }) + }) }) afterAll(async () => { + if (ids.other) { + await withScope(ids.other, async tx => { + await tx.absence.deleteMany({}) + await tx.userAccount.deleteMany({}) + await tx.member.deleteMany({}) + }) + await testDb.congregation.deleteMany({ where: { id: ids.other } }) + } if (ids.cong) { await withScope(ids.cong, async tx => { await tx.absence.deleteMany({}) @@ -110,14 +143,16 @@ afterAll(async () => { describe('the conflict readers and the absences table', () => { it('says someone is away from their absence row', async () => { - const [paul, marie] = await withScope(ids.cong, tx => + const [paul, marie, stranger] = await withScope(ids.cong, tx => Promise.all([ checkDayOffConflict(tx, ids.paul, MEETING_START, MEETING_END, ids.cong), checkDayOffConflict(tx, ids.marie, MEETING_START, MEETING_END, ids.cong), + // Someone of another congregation, asked about in this one. + checkDayOffConflict(tx, ids.stranger, MEETING_START, MEETING_END, ids.cong), ]), ) - expect({ paul, marie }).toEqual({ paul: true, marie: false }) + expect({ paul, marie, stranger }).toEqual({ paul: true, marie: false, stranger: false }) }) it('flags the assignments an absence row covers', async () => { @@ -144,6 +179,7 @@ describe('the conflict readers and the absences table', () => { }), ) + // Only Paul: not Marie's lone event, not the absence without a record, not the other congregation's. expect(facts.absences).toEqual({ [ids.paul]: { startDate: AWAY_START.toISOString(), endDate: AWAY_END.toISOString() }, }) 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 988ae4173..25b92f555 100644 --- a/app/features/events/server/draft-conflict-flow.integration.test.ts +++ b/app/features/events/server/draft-conflict-flow.integration.test.ts @@ -12,9 +12,8 @@ import { PrismaPg } from '@prisma/adapter-pg' import { afterAll, describe, expect, it } from 'vitest' import { PrismaClient } from '~/database/generated/client' -import { createDayOff } from '~/features/events/server/days-off.server' +import { createDayOff, deleteDayOff } from '~/features/events/server/days-off.server' import { releaseEvent } from '~/features/events/server/event-status.server' -import { refreshConflictFlags } from '~/features/events/server/refresh-conflict-flags.server' const adapter = new PrismaPg({ connectionString: process.env.DB_RUNTIME_URL ?? process.env.DB_URL, @@ -177,32 +176,25 @@ describe('refreshConflictFlags co-participant preservation (integration)', () => // Then Alice adds and immediately removes an absence, refreshing for her. // A refresh keyed on Alice must NOT clear the flag that Bob's absence // still legitimately owns. + // Through the real paths, so her absence is written and removed as « Mes absences » does: both refresh for her. await withScope(congId, async tx => { - const template = await tx.eventTemplate.findFirstOrThrow({ - where: { key: 'day-off', congregationId: congId }, - }) const aliceAccount = await tx.userAccount.findFirstOrThrow({ where: { memberId: aliceId, congregationId: congId }, }) - await tx.event.create({ - data: { - name: `Alice absence ${congId}`, - templateId: template.id, - startDate: new Date('2027-08-10T00:00:00Z'), - endDate: new Date('2027-08-11T00:00:00Z'), - createdById: aliceAccount.id, - congregationId: congId, - status: 'released', - }, - }) - await tx.event.deleteMany({ where: { name: `Alice absence ${congId}`, congregationId: congId } }) - await refreshConflictFlags( + const absence = await createDayOff( tx, + aliceAccount.id, aliceId, new Date('2027-08-10T00:00:00Z'), new Date('2027-08-11T00:00:00Z'), congId, ) + await deleteDayOff(tx, { + eventId: absence?.id as number, + accountId: aliceAccount.id, + memberId: aliceId, + congregationId: congId, + }) }) const still = await withScope(congId, tx => diff --git a/app/features/events/server/slot-candidate-facts.server.integration.test.ts b/app/features/events/server/slot-candidate-facts.server.integration.test.ts index e00e92da9..749ca58c3 100644 --- a/app/features/events/server/slot-candidate-facts.server.integration.test.ts +++ b/app/features/events/server/slot-candidate-facts.server.integration.test.ts @@ -128,8 +128,8 @@ beforeAll(async () => { data: { name: 'Sono', eventId: lastSummer.id, assigneeId: members.sono, congregationId }, }) - // Written twice, as createDayOff does: the day-off event and its Absence row, the person's. - const absence = await tx.event.create({ + // Written twice, as createDayOff does: the day-off event and its Absence row on the person's record. + const dayOffEvent = await tx.event.create({ data: { name: 'Absence', templateId: dayOff.id, @@ -141,11 +141,11 @@ beforeAll(async () => { }) await tx.absence.create({ data: { - startDate: absence.startDate, - endDate: absence.endDate, + startDate: dayOffEvent.startDate, + endDate: dayOffEvent.endDate, memberId: members.away, accountId: awayAccount.id, - legacyEventId: absence.id, + legacyEventId: dayOffEvent.id, congregationId, }, }) From f26077f2a76be6c20a7c520486dc20a9716f451e Mon Sep 17 00:00:00 2001 From: mindsers Date: Thu, 19 Nov 2026 12:07:25 +0100 Subject: [PATCH 5/5] docs(events): name what now reads the absences table createDayOff says why it still writes the event; the refresh's variables are absences, not day-offs; checkDayOffConflict says which record an absence carries. --- app/features/events/server/days-off.server.ts | 4 ++-- .../event-part-assignments.server.test.ts | 2 +- .../server/event-part-assignments.server.ts | 5 +++-- .../refresh-conflict-flags.server.test.ts | 3 +-- .../server/refresh-conflict-flags.server.ts | 21 +++++++++---------- 5 files changed, 17 insertions(+), 18 deletions(-) diff --git a/app/features/events/server/days-off.server.ts b/app/features/events/server/days-off.server.ts index 6a39cde3b..f9591d0cc 100644 --- a/app/features/events/server/days-off.server.ts +++ b/app/features/events/server/days-off.server.ts @@ -65,8 +65,8 @@ 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). + // Written twice until the events are dropped: the conflict readers use the Absence row (the person's record when the + // account has one), while the lists, the delete and account deletion still go through the day-off event. await db.absence.create({ data: { startDate, endDate, memberId, accountId, legacyEventId: event.id, congregationId }, }) diff --git a/app/features/events/server/event-part-assignments.server.test.ts b/app/features/events/server/event-part-assignments.server.test.ts index 07a689892..a3fca7485 100644 --- a/app/features/events/server/event-part-assignments.server.test.ts +++ b/app/features/events/server/event-part-assignments.server.test.ts @@ -58,7 +58,7 @@ describe('checkDayOffConflict', () => { // Regression pin — the ID passed in is a Member.id (all call sites resolve participants via Member), and an absence // belongs to that record. A prior version matched it against the declaring account's id, which silently found nothing // whenever the account's id differed from the record's. - it('finds absences by the person’s record (not the declaring account)', async () => { + it("finds absences by the person's record (not the declaring account)", async () => { vi.mocked(db.absence.findFirst).mockResolvedValue(null as never) const memberId = 5000 diff --git a/app/features/events/server/event-part-assignments.server.ts b/app/features/events/server/event-part-assignments.server.ts index b4530a71a..d779c8951 100644 --- a/app/features/events/server/event-part-assignments.server.ts +++ b/app/features/events/server/event-part-assignments.server.ts @@ -252,8 +252,9 @@ export async function unassignServicePart(db: TransactionClient, assignmentId: n return { assignment, previousAssigneeId: existing.assigneeId } } -// The `memberId` here is Member.id, the one that carries assignments (assigneeId / assistantId reference Member): an -// absence belongs to that record. One declared from an account without a record is nobody's assignment to block. +// `memberId` is Member.id, the id assignments carry (assigneeId / assistantId). An absence declared from an account +// without a record has memberId null and never matches: such an account holds no assignments. The record is the one +// the row was written with; linking an account to a record, by hand or by a restore, moves its rows. export async function checkDayOffConflict( db: TransactionClient, memberId: number, diff --git a/app/features/events/server/refresh-conflict-flags.server.test.ts b/app/features/events/server/refresh-conflict-flags.server.test.ts index 9b312de1b..3cbecdb02 100644 --- a/app/features/events/server/refresh-conflict-flags.server.test.ts +++ b/app/features/events/server/refresh-conflict-flags.server.test.ts @@ -21,8 +21,7 @@ describe('refreshConflictFlags', () => { // The overlapping events come from `db.event.findMany`, the absences from `db.absence.findMany` in one batched query. // // `absentMemberIds` are the members who HAVE an overlapping absence. Their stub absence - // spans a deliberately wide range so it overlaps every event in the fixture — matching the - // old per-(member, event) stub, which reported a conflict regardless of the event's dates. + // spans a deliberately wide range so it overlaps every event in the fixture. function stubEventsAndAbsences(events: unknown[], absentMemberIds: number[]) { const absent = new Set(absentMemberIds) vi.mocked(db.event.findMany).mockResolvedValue(events as never) diff --git a/app/features/events/server/refresh-conflict-flags.server.ts b/app/features/events/server/refresh-conflict-flags.server.ts index 6aa25536c..2e3de4541 100644 --- a/app/features/events/server/refresh-conflict-flags.server.ts +++ b/app/features/events/server/refresh-conflict-flags.server.ts @@ -41,7 +41,7 @@ export async function refreshConflictFlags( // Fetch every affected row up front rather than per event. The previous shape issued // one parts query, one services query and two absence lookups PER EVENT PER ROW, so a - // single day-off edit could fan out into dozens of round trips. + // single absence edit could fan out into dozens of round trips. const parts = await db.eventPart.findMany({ where: { eventId: { in: eventIds }, @@ -79,7 +79,7 @@ export async function refreshConflictFlags( const windowStart = overlappingEvents.reduce((min, e) => (e.startDate < min ? e.startDate : min), startDate) const windowEnd = overlappingEvents.reduce((max, e) => (e.endDate > max ? e.endDate : max), endDate) - const dayOffs = + const absences = participantIds.size === 0 ? [] : await db.absence.findMany({ @@ -89,26 +89,25 @@ export async function refreshConflictFlags( startDate: { lte: windowEnd }, endDate: { gte: windowStart }, }, - // An absence belongs to the person's record — see checkDayOffConflict. select: { startDate: true, endDate: true, memberId: true }, }) - const dayOffsByMember = new Map() - for (const dayOff of dayOffs) { - const absentMemberId = dayOff.memberId + const absencesByMember = new Map() + for (const absence of absences) { + const absentMemberId = absence.memberId if (absentMemberId == null) continue - const ranges = dayOffsByMember.get(absentMemberId) ?? [] - ranges.push({ start: dayOff.startDate.getTime(), end: dayOff.endDate.getTime() }) - dayOffsByMember.set(absentMemberId, ranges) + const ranges = absencesByMember.get(absentMemberId) ?? [] + ranges.push({ start: absence.startDate.getTime(), end: absence.endDate.getTime() }) + absencesByMember.set(absentMemberId, ranges) } const eventById = new Map(overlappingEvents.map(event => [event.id, event])) // Mirrors checkDayOffConflict's SQL predicate exactly: - // dayOff.startDate <= event.endDate AND dayOff.endDate >= event.startDate. + // absence.startDate <= event.endDate AND absence.endDate >= event.startDate. function isAbsent(participantId: number | null, eventId: number): boolean { if (participantId == null) return false - const ranges = dayOffsByMember.get(participantId) + const ranges = absencesByMember.get(participantId) if (ranges == null) return false const event = eventById.get(eventId) if (event == null) return false