Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 4 additions & 16 deletions app/features/events/routes/programs/events/publisher-info.tsx
Original file line number Diff line number Diff line change
@@ -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'
Expand Down Expand Up @@ -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,
Expand Down
187 changes: 187 additions & 0 deletions app/features/events/server/absence-conflicts.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
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 (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,
max: 3,
connectionTimeoutMillis: 5000,
})
const testDb = new PrismaClient({ adapter })

type Tx = Parameters<Parameters<typeof testDb.$transaction>[0]>[0]

function withScope<T>(congregationId: number, fn: (tx: Tx) => Promise<T>): Promise<T> {
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, 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')
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 image writes during a 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
// 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, 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({})
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, 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, stranger }).toEqual({ paul: true, marie: false, stranger: 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' },
}),
)

// 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() },
})
})
})
80 changes: 80 additions & 0 deletions app/features/events/server/absences.queries.integration.test.ts
Original file line number Diff line number Diff line change
@@ -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<Parameters<typeof testDb.$transaction>[0]>[0]

function withScope<T>(congregationId: number, fn: (tx: Tx) => Promise<T>): Promise<T> {
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'],
])
})
})
20 changes: 20 additions & 0 deletions app/features/events/server/absences.queries.ts
Original file line number Diff line number Diff line change
@@ -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' }],
})
}
4 changes: 2 additions & 2 deletions app/features/events/server/days-off.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
})
Expand Down
28 changes: 10 additions & 18 deletions app/features/events/server/draft-conflict-flow.integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 =>
Expand Down
Loading