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
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- Who created an event: the recurring-events job (« job »), a person (« manual ») or a restore (« import »). Until now
-- an event without an author stood for one the job made; deleting an account will now clear the author of what it
-- created, and a hand-made event must never become an empty meeting a template moves or deletes. No change in what
-- anyone may do.
--
-- 1. The column. The previous image creates events with the default during the rollout: its empty meetings stay
-- « manual » and do not move with their template until a later migration gives them « job ». That one must keep to
-- the events created during the rollout: run again as it is, step 2 would also take a hand-made event whose
-- author's account was deleted since.
ALTER TABLE "Event" ADD COLUMN IF NOT EXISTS "origin" TEXT NOT NULL DEFAULT 'manual';

ALTER TABLE "Event" DROP CONSTRAINT IF EXISTS "Event_origin_check";
ALTER TABLE "Event" ADD CONSTRAINT "Event_origin_check" CHECK ("origin" IN ('job', 'manual', 'import'));

-- 2. The job's events: no author, no part, no service, no attendance — exactly what an empty meeting was until now.
UPDATE "Event" AS event
SET "origin" = 'job'
WHERE event."createdById" IS NULL
AND event."origin" = 'manual'
AND NOT EXISTS (SELECT 1 FROM "EventPart" part WHERE part."eventId" = event."id")
AND NOT EXISTS (SELECT 1 FROM "EventServicePart" service WHERE service."eventId" = event."id")
AND NOT EXISTS (SELECT 1 FROM "Attendance" attendance WHERE attendance."eventId" = event."id");
116 changes: 116 additions & 0 deletions app/database/migrations/add-event-origin.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { PrismaPg } from '@prisma/adapter-pg'
import { afterAll, describe, expect, it } from 'vitest'
import { PrismaClient } from '~/database/generated/client'

// Runs against DB_URL rather than DB_RUNTIME_URL: a migration executes as the schema owner. Its statements are read from
// the shipped file and run inside a rolled-back transaction.
const adapter = new PrismaPg({ connectionString: process.env.DB_URL, max: 3, connectionTimeoutMillis: 5000 })
const testDb = new PrismaClient({ adapter })

const STATEMENTS = readFileSync(join(import.meta.dirname, '20261119120000_add_event_origin', 'migration.sql'), 'utf8')
.split('\n')
.filter(line => !line.trimStart().startsWith('--'))
.join('\n')
.split(';')
.map(statement => statement.trim())
.filter(statement => statement.length > 0)

class Rollback extends Error {}

interface Result {
first: Record<string, string>
second: Record<string, string>
bogusRefused: boolean
}

let memo: Promise<Result> | undefined

/** Events in the shape the previous image leaves them: every one at the column's default, « manual ». */
function snapshot(): Promise<Result> {
memo ??= (async () => {
let result: Result | undefined
try {
await testDb.$transaction(async tx => {
const stamp = `event-origin-${process.pid}-${globalThis.performance.now().toString().replace('.', '')}`
const congregationId = (await tx.congregation.create({ data: { name: stamp, slug: stamp, active: true } })).id
const author = await tx.userAccount.create({
data: { email: `${stamp}@test.com`, password: 'x', congregationId },
})
const day = new Date('2026-12-03T18:00:00Z')
const event = (name: string, createdById: number | null) =>
tx.event.create({ data: { name, startDate: day, endDate: day, createdById, congregationId } })

const ids = {
emptyJob: (await event('empty, no author', null)).id,
withPart: (await event('a part, no author', null)).id,
withService: (await event('a service, no author', null)).id,
withCounts: (await event('counts, no author', null)).id,
handMade: (await event('empty, an author', author.id)).id,
}
await tx.eventPart.create({ data: { name: 'Cantique', eventId: ids.withPart, congregationId } })
await tx.eventServicePart.create({ data: { name: 'Sono', eventId: ids.withService, congregationId } })
await tx.attendance.create({ data: { eventId: ids.withCounts, inPerson: 40, congregationId } })

const read = async () => {
const rows = await tx.event.findMany({ where: { congregationId }, select: { id: true, origin: true } })
const byId = new Map(rows.map(row => [row.id, row.origin]))
return Object.fromEntries(Object.entries(ids).map(([name, id]) => [name, byId.get(id) ?? '']))
}

for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement)
const first = await read()
for (const statement of STATEMENTS) await tx.$executeRawUnsafe(statement)
const second = await read()

let bogusRefused = false
try {
await tx.$executeRawUnsafe('SAVEPOINT bogus')
await tx.$executeRawUnsafe(`UPDATE "Event" SET "origin" = 'bogus' WHERE "id" = ${ids.handMade}`)
} catch {
bogusRefused = true
} finally {
await tx.$executeRawUnsafe('ROLLBACK TO SAVEPOINT bogus')
}

result = { first, second, bogusRefused }
throw new Rollback()
})
} catch (error) {
if (!(error instanceof Rollback)) throw error
}
return result as Result
})()
return memo
}

afterAll(async () => {
await testDb.$disconnect()
})

describe('20261119120000_add_event_origin', () => {
it('marks as the job’s only the events that were empty meetings: no author, nothing on them', async () => {
const { first } = await snapshot()

expect(first).toEqual({
emptyJob: 'job',
withPart: 'manual',
withService: 'manual',
withCounts: 'manual',
handMade: 'manual',
})
})

it('changes nothing when run twice', async () => {
const { first, second } = await snapshot()

expect(second).toEqual(first)
})

it('refuses an origin it does not know', async () => {
const { bogusRefused } = await snapshot()

expect(bogusRefused).toBe(true)
})
})
7 changes: 6 additions & 1 deletion app/database/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -1026,11 +1026,16 @@ model Event {
eventServiceParts EventServicePart[]
attendance Attendance?

// Null = created by the recurring-events job. A day-off always has one: it is the absence's owner. onDelete is
// Who prepared it: null for a meeting the job created that nobody has prepared yet, or once its author's account is
// deleted (releaseAccountEvents clears it first). A day-off always has one: it is the absence's owner. onDelete is
// written out because an optional relation defaults to SetNull, which would empty the owner of every day-off when
// an account is deleted.
createdBy UserAccount? @relation("createdBy", fields: [createdById], references: [id], onDelete: Restrict)
createdById Int?
// Who created it: the recurring-events job (« job »), a person (« manual ») or a restore (« import »). Only the
// job's empty meetings move with their template or go with it; the author says who prepared it (for a day-off, whose
// absence it is).
origin String @default("manual")
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt

Expand Down
3 changes: 2 additions & 1 deletion app/features/events/index.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// Public server-only surface of the events feature.

export { AccountHasAbsencesError, releaseAccountEvents } from './server/account-events.server'
export { type LastWeekMeeting, listLastWeekAttendance, listMeetingsUnderWay } from './server/attendance.queries'
export { getNextDaysOffs } from './server/days-off.server'
export { deleteTemplate } from './server/delete-template.server'
export { duplicateTemplate } from './server/duplicate-template.server'
export { countMeetingsToMove } from './server/empty-meetings.queries'
export { countMeetingsToMove, EMPTY_MEETING } from './server/empty-meetings.queries'
export {
deleteTemplatePart,
deleteTemplateServicePart,
Expand Down
1 change: 1 addition & 0 deletions app/features/events/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export {
parseAttendanceKind,
} from './model/attendance-kind.type'
export { dayLabel, dayLabelShort } from './model/day-label'
export { EVENT_ORIGINS, EventOrigin, isEventOrigin } from './model/event-origin.type'
export { EventStatus } from './model/event-status.type'
export { EventTemplateKey, isSystemTemplate } from './model/event-template.type'
export { groupPartsBySlot } from './model/group-parts-by-slot'
Expand Down
21 changes: 21 additions & 0 deletions app/features/events/model/event-origin.type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Who created an event (Event.origin). Only the job's events, while empty, move with their template or go with it: an
// event someone made or prepared stays where it is, whatever happens to its author's account. A meeting the job made
// becomes « manual » once someone gives it its programme or moves it; adding a part by hand leaves it the job's.

export const EventOrigin = {
/** Created ahead by the recurring-events job. */
Job: 'job',
/** Created by a person, or a job meeting someone prepared or moved. */
Manual: 'manual',
/** Restored without a known origin: an older archive's event that was not an empty meeting, or an origin this
* version does not know. */
Import: 'import',
} as const

export type EventOrigin = (typeof EventOrigin)[keyof typeof EventOrigin]

export const EVENT_ORIGINS: readonly EventOrigin[] = [EventOrigin.Job, EventOrigin.Manual, EventOrigin.Import]

export function isEventOrigin(value: unknown): value is EventOrigin {
return typeof value === 'string' && (EVENT_ORIGINS as readonly string[]).includes(value)
}
52 changes: 52 additions & 0 deletions app/features/events/server/account-events.server.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const { releaseAccountEvents, AccountHasAbsencesError } = await import('./account-events.server')

const db = {
event: { findMany: vi.fn(), deleteMany: vi.fn(), updateMany: vi.fn() },
}

const ABSENCE = { id: 31, startDate: new Date('2027-01-12T00:00:00Z'), endDate: new Date('2027-01-14T22:59:00Z') }

beforeEach(() => {
vi.resetAllMocks()
db.event.findMany.mockResolvedValue([])
db.event.deleteMany.mockResolvedValue({ count: 0 })
db.event.updateMany.mockResolvedValue({ count: 0 })
})

describe('releaseAccountEvents', () => {
it('deletes the absences of an account without a record and clears its author elsewhere', async () => {
db.event.findMany.mockResolvedValue([ABSENCE])
db.event.deleteMany.mockResolvedValue({ count: 1 })
db.event.updateMany.mockResolvedValue({ count: 2 })

const released = await releaseAccountEvents(db as never, { id: 7, memberId: null }, 10)

expect(released).toEqual({ absencesDeleted: [ABSENCE], eventsUnattributed: 2 })
expect(db.event.deleteMany).toHaveBeenCalledWith({ where: { congregationId: 10, id: { in: [31] } } })
expect(db.event.updateMany).toHaveBeenCalledWith({
where: { congregationId: 10, createdById: 7 },
data: { createdById: null },
})
})

it('refuses, writing nothing, an account linked to a record that has absences', async () => {
db.event.findMany.mockResolvedValue([ABSENCE])

await expect(releaseAccountEvents(db as never, { id: 7, memberId: 42 }, 10)).rejects.toBeInstanceOf(
AccountHasAbsencesError,
)
expect(db.event.deleteMany).not.toHaveBeenCalled()
expect(db.event.updateMany).not.toHaveBeenCalled()
})

it('only clears the author of an account linked to a record without absences', async () => {
db.event.updateMany.mockResolvedValue({ count: 1 })

const released = await releaseAccountEvents(db as never, { id: 7, memberId: 42 }, 10)

expect(released).toEqual({ absencesDeleted: [], eventsUnattributed: 1 })
expect(db.event.deleteMany).not.toHaveBeenCalled()
})
})
47 changes: 47 additions & 0 deletions app/features/events/server/account-events.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { EventTemplateKey } from '~/features/events/model/event-template.type'
import { ConflictError } from '~/shared/errors/app-error.server'
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.
*/
export class AccountHasAbsencesError extends ConflictError {}

export interface ReleasedAccountEvents {
/** The absences 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.
*
* 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).
* Its other events lose their author and keep their origin, so a hand-made one never becomes an empty meeting a
* template may move or delete.
*/
export async function releaseAccountEvents(
db: TransactionClient,
account: { id: number; memberId: number | null },
congregationId: number,
): Promise<ReleasedAccountEvents> {
const absences = await db.event.findMany({
where: { congregationId, createdById: account.id, template: { key: EventTemplateKey.DayOff } },
select: { id: true, startDate: true, endDate: true },
orderBy: { id: 'asc' },
})
if (account.memberId != null && absences.length > 0) throw new AccountHasAbsencesError('The account has absences')

if (absences.length > 0) {
await db.event.deleteMany({ where: { congregationId, id: { in: absences.map(absence => absence.id) } } })
}
const unattributed = await db.event.updateMany({
where: { congregationId, createdById: account.id },
data: { createdById: null },
})
return { absencesDeleted: absences, eventsUnattributed: unattributed.count }
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ const MEETING = {
templateId: 270,
startDate: new Date('2026-11-19T23:30:00Z'),
createdById: null,
origin: 'job',
_count: { eventParts: 0, eventServiceParts: 0 },
}

Expand All @@ -55,7 +56,7 @@ describe('createMeetingProgramme', () => {

expect(db.event.update).toHaveBeenCalledWith({
where: { id_congregationId: { id: 55, congregationId: 7 } },
data: { createdById: 42 },
data: { createdById: 42, origin: 'manual' },
})
})

Expand Down
10 changes: 8 additions & 2 deletions app/features/events/server/create-meeting-programme.server.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { EventOrigin } from '~/features/events/model/event-origin.type'
import { isSystemTemplate } from '~/features/events/model/event-template.type'
import { giveProgramme, lockTemplates, TEMPLATE_INCLUDE } from '~/features/events/server/give-programme.server'
import {
Expand Down Expand Up @@ -33,6 +34,7 @@ export async function createMeetingProgramme(
templateId: true,
startDate: true,
createdById: true,
origin: true,
_count: { select: { eventParts: true, eventServiceParts: true } },
},
})
Expand All @@ -45,10 +47,14 @@ export async function createMeetingProgramme(
if (template.parts.length === 0 && template.serviceParts.length === 0) return null
if (event._count.eventParts > 0 || event._count.eventServiceParts > 0) throw new ProgrammeExistsError(event.id)

if (event.createdById == null) {
// Whoever gives it its programme prepares it when nobody is named; a meeting the job made is no longer the job's.
if (event.createdById == null || event.origin === EventOrigin.Job) {
await db.event.update({
where: { id_congregationId: { id: event.id, congregationId } },
data: { createdById: ctx.actorId },
data: {
createdById: event.createdById ?? ctx.actorId,
...(event.origin === EventOrigin.Job && { origin: EventOrigin.Manual }),
},
})
}
return giveProgramme(db, template, event.id, dayOf(event.startDate, ctx.timezone), ctx, { reused: true })
Expand Down
3 changes: 2 additions & 1 deletion app/features/events/server/days-off.queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ export async function listCongregationAbsences(
orderBy: [{ startDate: 'asc' }, { id: 'asc' }],
})
// Absences belong to the account that declared them; the person away is its member, when it has one. A day-off
// always has that account (Event.createdBy is Restrict); only events made by the recurring job have none.
// always has that account (Event.createdBy is Restrict, and deleting an account takes its absences with it or is
// refused); events without an author are never absences.
const absences = rows.flatMap(({ createdBy, createdAt, ...row }) =>
createdBy == null
? []
Expand Down
2 changes: 1 addition & 1 deletion app/features/events/server/delete-template.server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ describe('deleteTemplate', () => {
const result = await deleteTemplate(db, 7, 1, 9)

const empty = {
createdById: null,
origin: 'job',
eventParts: { none: {} },
eventServiceParts: { none: {} },
attendance: { is: null },
Expand Down
Loading
Loading