Since 06-02, the dashboard only knows about drafts. As soon as the administrators publish an event, its organizer loses control over it: they can't fix a typo, they don't know who's coming and, if the band falls ill, they have to phone someone to go and touch the database.
In this lesson you'll complete the dashboard with the three missing operations: correcting what's published without breaking bookings, viewing and downloading the attendee list, and canceling while notifying everyone. It's only a few screens and a lot of responsibility: here you handle other people's data and operations that can't be undone. You'll see why an audit entry that used to fit in after now has to be written before responding, and you'll close off the permission matrix.
- What organizers can do
The table from 08-04 grows. The difference between editing and correcting is the event's status:
| Operation | Statuses | Also |
|---|---|---|
| Edit everything | draft, review |
No bookings yet |
| Correct the summary, description, capacity and poster | published, not yet started |
Capacity can't drop below what's booked |
| Cancel | published, not yet started |
Final; notifies bookings and the waitlist |
| View and download attendees | published, canceled |
Only what's needed; the download is audited |
| Change title, category, date or venue | None after publishing | Cancel and create another one (decision 10) |
The title is left out for a less obvious reason than the date: it's the event's identity. Changing it completely would turn a booking for one thing into a booking for another. The administrators don't gain permissions either: they review and publish, and they don't cancel other people's events. If that were ever needed, it would be a different function, with a different audit entry.
All the new screens hang from one, the management page:
app/(dashboard)/dashboard/events/
├── page.tsx List: links to Edit or Manage, depending on the status
├── loading.tsx
├── new/page.tsx
└── [id]/
├── page.tsx NEW: occupancy, attendees and actions
├── attendees.csv/route.ts NEW: download
├── _components/ NEW
└── edit/page.tsx Drafts and review, as before
- The data
// lib/data/dashboard.ts (addition; import count, gt, or, users, bookings, venues, waitlist, allocateSpots…)
function isOwnedBy(organizerId: string, id: string) {
return and(eq(events.id, id), eq(events.organizerId, organizerId))
}
// Published and not yet started: what can still be corrected or canceled
function isManageableBy(organizerId: string, id: string) {
return and(
isOwnedBy(organizerId, id),
eq(events.status, 'published'),
gt(events.startsAt, new Date()),
)
}
export async function getOwnEvent(id: string): Promise<AgendaEvent | null> {
const organizer = await ensureRole('organizer')
const db = await getDb()
const [event] = await db.select().from(events).where(isOwnedBy(organizer.id, id)).limit(1)
return event ?? null
}
export interface Attendee {
name: string
spots: number
bookedAt: Date
}
// null if the event doesn't exist or isn't theirs
export async function listAttendees(id: string): Promise<Attendee[] | null> {
const organizer = await ensureRole('organizer')
const db = await getDb()
const [own] = await db
.select({ id: events.id })
.from(events)
.where(isOwnedBy(organizer.id, id))
if (!own) return null
return db
.select({
name: users.name,
spots: bookings.spots,
bookedAt: bookings.createdAt,
})
.from(bookings)
.innerJoin(users, eq(bookings.userId, users.id))
.where(eq(bookings.eventId, id))
.orderBy(asc(users.name), asc(bookings.createdAt))
}Attendee doesn't include the person's email address or identifier. In the 08-04 exercise the door list included the email, and now that it's being designed for real the question is what for. To let people in, the name and the spots are enough; to tell them something, there's the application, which writes on the organizer's behalf without handing over the addresses. Data that isn't handed over doesn't leak, isn't reused for an advertising list and doesn't have to be deleted from someone else's laptop. If the client asks for it, they should state the purpose and have compliance look at it.
The function makes two queries instead of one with all the tables joined. With a single one, "own event with no bookings" and "someone else's event" would give the same thing, zero rows, and we couldn't tell an empty list from a refusal.
2.1. Correcting
// lib/data/dashboard.ts (addition)
export type CorrectionData = Pick<AgendaEvent, 'summary' | 'description' | 'capacity'>
export type CorrectionResult =
| { status: 'corrected'; slug: string; spotsBefore: number; spotsAfter: number; assigned: number }
| { status: 'capacity-too-low'; booked: number }
| { status: 'capacity-too-high'; max: number }
| { status: 'unavailable' }
export async function correctPublished(
id: string,
data: CorrectionData,
): Promise<CorrectionResult> {
const organizer = await ensureRole('organizer')
const db = await getDb()
return db.transaction(async (tx): Promise<CorrectionResult> => {
const [current] = await tx
.select({
slug: events.slug,
capacity: events.capacity,
spotsLeft: events.spotsLeft,
venueId: events.venueId,
})
.from(events)
.where(isManageableBy(organizer.id, id))
.for('update')
if (!current) return { status: 'unavailable' }
const booked = current.capacity - current.spotsLeft
if (data.capacity < booked) return { status: 'capacity-too-low', booked }
const [venue] = await tx
.select({ capacity: venues.capacity })
.from(venues)
.where(eq(venues.id, current.venueId))
// An external notification may have left the event above its venue (07-03)
const max = Math.max(venue.capacity, booked)
if (data.capacity > max) return { status: 'capacity-too-high', max }
await tx
.update(events)
.set({ ...data, spotsLeft: data.capacity - booked })
.where(eq(events.id, id))
const allocation = await allocateSpots(tx, id)
return {
status: 'corrected',
slug: current.slug,
spotsBefore: current.spotsLeft,
spotsAfter: allocation.spotsLeft,
assigned: allocation.assigned,
}
})
}This is the case 06-02 left pending: there, spotsLeft: data.capacity was enough, because a draft has no bookings. Here the spots left are derived from what's booked, with the row locked, so nobody books between the read and the write. And if the capacity goes up, the waitlist is served in the same transaction, with a single line.
The rules that can change between checking and writing are inside the transaction, not in lib/rules/ (06-03). The venue case shows why a seemingly simple rule, "the capacity doesn't exceed the venue's", needs an exception: if the venue reduced its capacity below what's already booked, without the Math.max you couldn't even fix a misplaced comma.
2.2. Canceling
// lib/db/schema.ts: NOTIFICATION_TYPES = ['spot-assigned', 'event-canceled'] as const
// lib/data/dashboard.ts (addition)
export async function cancelEvent(
id: string,
): Promise<{ slug: string; notified: number } | null> {
const organizer = await ensureRole('organizer')
const db = await getDb()
return db.transaction(async (tx) => {
const [canceled] = await tx
.update(events)
.set({ status: 'canceled' })
.where(isManageableBy(organizer.id, id))
.returning({ slug: events.slug })
if (!canceled) return null
const withBooking = await tx
.select({ userId: bookings.userId })
.from(bookings)
.where(eq(bookings.eventId, id))
const waiting = await tx
.delete(waitlist)
.where(eq(waitlist.eventId, id))
.returning({ userId: waitlist.userId })
const people = [...withBooking, ...waiting]
if (people.length > 0) {
await tx.insert(pendingNotifications).values(
people.map(({ userId }) => ({ type: 'event-canceled' as const, eventId: id, userId })),
)
}
return { slug: canceled.slug, notified: people.length }
})
}- The transition is in the
where. You can only leavepublished, and only towardscanceled. Canceling twice doesn't notify twice: the second one doesn't find a row. - Bookings aren't deleted (decision 8). They're the record of who was going, they make it possible to show "Canceled" in "My bookings", and they avoid a locking problem:
cancelBookinglocks its booking row first and then the event. If canceling an event locked in the opposite order and touched the same rows, the two could wait for each other forever (a deadlock). PostgreSQL detects it and aborts one, but it's better not to cause it. - The check for new bookings isn't repeated. The
UPDATEholds the event's row: a booking in progress has either finished and shows up in the query, or is waiting and will findcanceled. - The notifications are born with the cancellation. Three hundred rows are inserted in milliseconds; three hundred emails aren't. It's case (c) from the 07-04 exercise, solved.
When you add the type, lib/compose-notification.ts stops compiling until it's handled:
// lib/compose-notification.ts (added to the switch)
case 'event-canceled':
return {
subject: `Canceled: ${notification.title}`,
text: [
`We've canceled "${notification.title}", scheduled for ${when}`,
notification.spots === null
? "You were on the waitlist. You don't need to do anything."
: "Your booking has been voided. You don't need to do anything.",
eventUrl,
SITE_NAME,
].join('\n\n'),
}
- The actions
// lib/schemas/correction.ts
import * as z from 'zod'
import { EVENT_LIMITS } from '@/lib/schemas/limits'
import { integer, text } from '@/lib/schemas/common'
export const CORRECTION_FIELDS = ['summary', 'description', 'capacity'] as const
export type CorrectionField = (typeof CORRECTION_FIELDS)[number]
export const correctionSchema = z.object({
summary: text(EVENT_LIMITS.summary),
description: text({ ...EVENT_LIMITS.description, min: 80 }), // What's required to publish
capacity: integer(EVENT_LIMITS.capacity),
})// actions/published.ts
'use server'
// imports as in actions/events.ts, plus cancelEvent, correctPublished,
// notifyIfAvailabilityChanges, invalidateEvent, sendNotifications and afterResponse
export type CorrectionState = FormState<CorrectionField>
export type CancellationState = FormState<never>
export async function correctEvent(
eventId: string,
_previous: CorrectionState,
formData: FormData,
): Promise<CorrectionState> {
const values = readTextFields(formData, CORRECTION_FIELDS)
const reject = (
message: string,
errors: FieldErrors<CorrectionField> = {},
): CorrectionState => ({ status: 'error', message, errors, values })
const permission = await checkRole('organizer')
if (!permission.granted) return reject(DENIAL_MESSAGES[permission.reason])
if (!identifier.safeParse(eventId).success) return reject('Invalid event.')
const parsed = correctionSchema.safeParse(values)
if (!parsed.success) {
return reject('Check the highlighted fields.', z.flattenError(parsed.error).fieldErrors)
}
if (!(await withinLimits(writeLimits(permission.user.id)))) {
return reject("You're going too fast. Please wait a minute.")
}
const result = await correctPublished(eventId, parsed.data)
switch (result.status) {
case 'corrected':
invalidateEvent(result.slug)
audit(permission.user.id, 'event.corrected', eventId)
if (result.assigned > 0) afterResponse('send notifications', () => sendNotifications(5))
return { status: 'success', message: 'Your changes are now live.' }
case 'capacity-too-low':
refresh()
return reject('Check the capacity.', {
capacity: [`Bookings already cover ${formatSpots(result.booked)}: the capacity can't be lower.`],
})
case 'capacity-too-high':
return reject('Check the capacity.', { capacity: [`The venue holds ${result.max} at most.`] })
case 'unavailable':
refresh()
return reject('This event can no longer be corrected.')
}
}
export async function cancelMyEvent(
eventId: string,
_previous: CancellationState,
formData: FormData,
): Promise<CancellationState> {
const reject = (message: string): CancellationState => ({
status: 'error', message, errors: {}, values: {},
})
const permission = await checkRole('organizer')
if (!permission.granted) return reject(DENIAL_MESSAGES[permission.reason])
if (!identifier.safeParse(eventId).success) return reject('Invalid event.')
if (formData.get('confirm') !== 'yes') return reject('Check the box to confirm.')
const canceled = await cancelEvent(eventId)
if (!canceled) {
refresh()
return reject('This event can no longer be canceled.')
}
invalidateEvent(canceled.slug)
audit(permission.user.id, 'event.canceled', eventId)
afterResponse('send notifications', () => sendNotifications(5))
return {
status: 'success',
message: `Event canceled. ${canceled.notified} people will be notified by email.`,
}
}invalidateEventexpires the listings and the event page, and with them the metadata ("Canceled: …"), the JSON-LD, the social image, the calendar and the sitemap. There's no need to name them: they read the same tags.- It also refreshes the screen, because
updateTagre-renders the current route (06-01). The dashboard isn't cached, so it's read again along with it. That's why the success cases don't callrefresh, and the rejection cases do when the screen was out of date. - "Will be notified", in the future tense. The emails go out in batches of five; the rest, with the scheduler's task.
- It's confirmed with a checkbox the server checks. A
window.confirmonly protects people who have JavaScript, and not someone who repeats a request. The checkbox isn't security; it's a second chance.
Add event.corrected, event.canceled and attendees.downloaded to AuditedAction.
3.1. The poster of a published event
06-05 left another promise: changing the poster of a published event must invalidate. changeImage now accepts all three statuses and returns what's needed:
// lib/data/dashboard.ts, in changeImage: returns { previous, slug, status } | null
.where(
or(
isEditableBy(organizer.id, eventId),
isManageableBy(organizer.id, eventId),
),
)
// actions/images.ts, in uploadImage and removeImage
// – the preliminary check moves to getOwnEvent
// – after changing the key:
if (change.status === 'published') invalidateEvent(change.slug)
else refresh()The preliminary check only saves work; the one that guarantees anything is the transaction's where, which is still there. And since every upload uses a new key, no image cache serves the old poster (09-02).
- The management page
// app/(dashboard)/dashboard/events/[id]/page.tsx
import type { Metadata } from 'next'
import { Suspense } from 'react'
import { notFound } from 'next/navigation'
// … components, data and formatting
type Props = PageProps<'/dashboard/events/[id]'>
export const metadata: Metadata = { title: 'Manage event' }
export const maxDuration = 30 // The actions send notifications in after
export default async function ManageEventPage({ params }: Props) {
const { id } = await params
await requireRole(`/dashboard/events/${id}`, 'organizer')
const event = await getOwnEvent(id)
if (!event) notFound()
const manageable = event.status === 'published' && event.startsAt > new Date()
return (
<>
<h1 className="text-2xl font-bold">{event.title}</h1>
<p className="mb-6">
<StatusBadge status={event.status} /> {formatDateTime(event.startsAt)}.{' '}
{formatSpots(event.capacity - event.spotsLeft)} of {event.capacity}.
</p>
<section aria-labelledby="attendees">
<h2 id="attendees" className="text-xl font-semibold">Attendees</h2>
<Suspense fallback={<ListSkeleton items={5} />}>
<AttendeeList eventId={event.id} />
</Suspense>
</section>
{manageable && (
<>
<CorrectionForm
eventId={event.id}
initial={{
summary: event.summary,
description: event.description,
capacity: String(event.capacity),
}}
/>
<ImageForm eventId={event.id} image={event.image} />
</>
)}
<CancellationForm eventId={event.id} cancelable={manageable} />
</>
)
}
async function AttendeeList({ eventId }: { eventId: string }) {
const attendees = await listAttendees(eventId)
if (!attendees || attendees.length === 0) return <p>No bookings yet.</p>
return (
<>
{/* <a> rather than <Link>: it's a download and mustn't be prefetched */}
<a href={`/dashboard/events/${eventId}/attendees.csv`} className="underline" download>
Download the list (CSV)
</a>
<table className="mt-4 w-full text-left">
<caption className="sr-only">People with a booking, by name</caption>
<thead>
<tr><th scope="col">Name</th><th scope="col">Spots</th><th scope="col">Booked</th></tr>
</thead>
<tbody>
{attendees.map(({ name, spots, bookedAt }) => (
<tr key={`${name}-${bookedAt.toISOString()}`}>
<td>{name}</td><td>{spots}</td><td>{formatDateTime(bookedAt)}</td>
</tr>
))}
</tbody>
</table>
</>
)
}// app/(dashboard)/dashboard/events/[id]/_components/cancellation-form.tsx
'use client'
export function CancellationForm({ eventId, cancelable }: Props) {
const [state, formAction] = useActionState(cancelMyEvent.bind(null, eventId), INITIAL_STATE)
return (
<section aria-label="Cancellation" className="mt-10">
<FormMessage state={state} />
{cancelable && (
<details className="border border-danger p-4">
<summary>Cancel this event</summary>
<form action={formAction}>
<p>
Everyone with a booking or on the waitlist will be notified by email. This can't be
undone.
</p>
<label className="my-3 block">
<input type="checkbox" name="confirm" value="yes" required /> I understand this is final
</label>
<SubmitButton pendingText="Canceling…" className={BUTTON.danger}>
Cancel the event
</SubmitButton>
</form>
</details>
)}
</section>
)
}CancellationFormis always in place, withcancelableas a prop. If it were removed on canceling, it would take the message with it: that's the lesson from 06-04.<details>hides the dangerous operation without a line of JavaScript. The browser's confirmation (required) and the server's complement each other.new Date()is allowed: the session and the query have already stopped prerendering, andloading.tsxacts as the boundary.- The rows use a composite key because the DTO carries no identifiers. For a read-only list, that's enough.
CorrectionForm repeats the EventForm pattern with three fields and correctEvent. In DashboardEventsPage, each row's link depends on the status: "Edit" for editable events and "Manage" for the rest. And in lib/metrics.ts you have to add the new pattern, or the page will fall into other:
The public side needs one more adjustment. listMyBookings must also return events.status, so that "My bookings" shows the "Canceled" badge and stops offering the link as if nothing had happened. The event page already said so since 02-02, and EventBooking stopped rendering the form in the previous lesson.
- The download
// lib/csv.ts — pure
const DANGEROUS = /^[=+\-@\t\r\n]/
function cell(value: string): string {
const safe = DANGEROUS.test(value) ? `'${value}` : value
return `"${safe.replaceAll('"', '""')}"`
}
export function createCsv(header: string[], rows: string[][]): string {
const lines = [header, ...rows].map((row) => row.map(cell).join(';'))
return `${lines.join('\r\n')}\r\n` // The leading mark makes it read as UTF-8
}// app/(dashboard)/dashboard/events/[id]/attendees.csv/route.ts
export async function GET(
request: Request,
{ params }: RouteContext<'/dashboard/events/[id]/attendees.csv'>,
) {
const { id } = await params
const permission = await checkRole('organizer') // Reads cookies: outside guarded (07-01)
if (!permission.granted) {
return permission.reason === 'no-session'
? errorResponse('unauthorized', 'Sign in.')
: errorResponse('forbidden', "You don't have permission.")
}
return guarded(async () => {
const [event, attendees] = identifier.safeParse(id).success
? await Promise.all([getOwnEvent(id), listAttendees(id)])
: [null, null]
if (!event || !attendees) return errorResponse('not-found', "The event doesn't exist.")
// Awaited: if it can't be recorded, it isn't downloaded
await addAuditEntry({
userId: permission.user.id,
action: 'attendees.downloaded',
entityId: id,
requestId: request.headers.get(REQUEST_ID_HEADER),
occurredAt: new Date(),
})
const rows = attendees.map(({ name, spots, bookedAt }) => [
name, String(spots), formatLocalDateTime(bookedAt),
])
return new Response(createCsv(['Name', 'Spots', 'Booked'], rows), {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${event.slug}.csv"`,
'Cache-Control': 'private, no-store',
},
})
})
}Add forbidden: 403 to the codes in lib/api/responses.ts.
- Formula injection. Anyone types their own name when signing up. If someone is called
=HYPERLINK("https://…"), the spreadsheet that opens the file will run the formula with the permissions of whoever opens it. The leading apostrophe turns it into text. It's annoying for anyone called-Ana, and it's the right price. ;separator and byte order mark. It's what spreadsheets set up for locales with a decimal comma, such as Spain's, expect. If the destination were another program, a comma and no mark: the format depends on who reads it.no-storeandprivate: nobody in between should store names.- The file name is the slug, which only has letters, digits and hyphens. Putting the title there would allow someone to break the header with a pair of quotes.
- 401, 403 and 404 are told apart, but "doesn't exist" and "isn't yours" are the same 404 (08-04).
The audit entry deserves a comment. In 07-04 two kinds were separated: the kind that helps investigate, which goes in after, and the kind that's a condition for doing something. Handing over a list of people is the second kind. If there's ever a leak, the first question will be who downloaded it and when, and "some rows may be missing" isn't an answer. That's why it's awaited, and if it fails, guarded responds with a 500 and no data goes out. It seems to contradict the "no GET writes" rule from 08-06: that rule protects against a crawler changing the state of the business, and recording an access doesn't change it. Note it down as an exception on the list anyway.
The proxy helps in the common case: without a cookie, GET /dashboard/… redirects to /sign-in. Anyone calling with an expired cookie will get the 401.
- Occupancy
The /dashboard overview gave a total. Organizers care about each event and, above all, which ones need something:
// lib/data/dashboard.ts (addition)
export async function listOccupancy() {
const organizer = await ensureRole('organizer')
const db = await getDb()
const waiting = db
.select({ eventId: waitlist.eventId, people: count().as('people') })
.from(waitlist)
.groupBy(waitlist.eventId)
.as('waiting')
return db
.select({
id: events.id,
title: events.title,
startsAt: events.startsAt,
capacity: events.capacity,
spotsLeft: events.spotsLeft,
onWaitlist: sql`coalesce(${waiting.people}, 0)`.mapWith(Number),
})
.from(events)
.leftJoin(waiting, eq(waiting.eventId, events.id))
.where(
and(
eq(events.organizerId, organizer.id),
eq(events.status, 'published'),
gt(events.endsAt, new Date()),
),
)
.orderBy(asc(events.startsAt))
}// app/(dashboard)/dashboard/(overview)/@occupancy/page.tsx
export default async function DashboardOccupancy() {
await requireRole('/dashboard', 'organizer')
const events = await listOccupancy()
return (
<>
<h2 className="text-lg font-semibold">Occupancy</h2>
{events.length === 0 && <p>You don't have any published events.</p>}
<ul className="mt-2 grid gap-4">
{events.map(({ id, title, capacity, spotsLeft, onWaitlist }) => {
const booked = capacity - spotsLeft
return (
<li key={id}>
<Link href={`/dashboard/events/${id}`} className="underline">{title}</Link>
<progress max={capacity} value={booked} aria-label={`Occupancy of ${title}`} className="block w-full" />
<p className="text-muted">
{booked} of {capacity}
{onWaitlist > 0 && `. ${onWaitlist} on the waitlist`}
</p>
</li>
)
})}
</ul>
</>
)
}The queue is grouped in a subquery before joining it. Joining directly and grouping afterwards would multiply rows as soon as another table was added, which is the classic mistake in summaries: the numbers come out, and they come out wrong. <progress> is a native element with its own semantics; the text gives the same information to anyone who can't make out the bar. getOccupancy is no longer used: delete it.
- The tests
Each operation has its table of rejections. In the database, with two organizers (ana, owner of event e, and bruno):
// tests/db/dashboard.test.ts (ensureRole mocked; actingAs() same as in the previous ones)
const CORRECTION = { summary: 'Another summary', description: 'Another description', capacity: 10 }
test.each([
['correct', () => correctPublished('e', CORRECTION), { status: 'unavailable' }],
['cancel', () => cancelEvent('e'), null],
['view attendees', () => listAttendees('e'), null],
['read', () => getOwnEvent('e'), null],
])("someone else's event doesn't exist: %s", async (_name, operation, expected) => {
expect(await actingAs('bruno', operation)).toEqual(expected)
})
test("capacity doesn't drop below what's booked", async () => {
await actingAs('carla', () => createBooking('e', 1)) // 1 of 10 was left
expect(await actingAs('ana', () => correctPublished('e', { ...CORRECTION, capacity: 9 }))).toEqual({
status: 'capacity-too-low',
booked: 10,
})
})
test('canceling notifies each person once and closes the waitlist', async () => {
await actingAs('carla', () => createBooking('e', 1))
await actingAs('bruno', () => addToWaitlist('e', 1))
const [first, second] = await Promise.all([
actingAs('ana', () => cancelEvent('e')),
actingAs('ana', () => cancelEvent('e')),
])
expect([first, second].filter(Boolean)).toEqual([{ slug: 'e', notified: 2 }])
const db = await getDb()
expect(await db.select().from(pendingNotifications)).toHaveLength(2)
expect(await db.select().from(waitlist)).toHaveLength(0)
expect(await db.select().from(bookings)).toHaveLength(1) // It's kept
})
test("a canceled event can't be booked, even when clicked at the same time", async () => {
const [, booking] = await Promise.all([
actingAs('ana', () => cancelEvent('e')),
actingAs('carla', () => createBooking('e', 1)),
])
const db = await getDb()
const notifications = await db.select().from(pendingNotifications)
// If the booking went through, it came first: and then the person has been notified
expect(notifications).toHaveLength(booking.status === 'booked' ? 1 : 0)
})// lib/csv.test.ts
test.each([
['Ana', '"Ana"'],
['Ana "at the door"', '"Ana ""at the door"""'],
['=1+1', `"'=1+1"`],
['@sum', `"'@sum"`],
['one;two', '"one;two"'],
])('cell %s', (value, expected) => {
expect(createCsv(['x'], [[value]])).toContain(expected)
})The last concurrency test is the one that really matters: there's no order in which someone holds a booking for a canceled event without having been notified. In e2e/permissions.spec.ts, add /dashboard/events/evt-08 to the list, since it belongs to another organizer; with request and the same session, check that /dashboard/events/evt-08/attendees.csv responds with a 404; and add a final leg to the publishing flow: the visitor books, the organizer sees their name and cancels, and the anonymous event page says "canceled" and no longer appears in the listing.
And there's something the tests don't tell you. Rehearse a real cancellation in the staging environment with the mail simulator failing (FAILURES=20), and watch the outbox: the notifications are postponed, the scheduler picks them up and in the end they all go out. It's the "100% in under 30 minutes" requirement seen with your own eyes.
Common Mistakes and Tips
- Setting the spots left equal to the capacity when editing something with bookings.
- Checking the capacity outside the transaction.
- Deleting the bookings on canceling, and with them the record.
- Locking rows in different orders in two operations.
- Sending the emails inside the action, or entrusting them to
afteralone. - Handing over the attendees' email addresses because they were at hand.
- CSV without neutralizing formulas, or with the title in the header.
- A
<Link>to a download. - Auditing in
afterwhat must be recorded. - Removing from the tree the form whose message needs to be read.
- Confirming only in the browser.
- Joining and then grouping with several tables.
Exercises
Exercise 1: the reason
Make canceling accept an optional reason of up to 200 characters, shown on the event page and in the email. Where is it stored? Which three places do you need to review because "a row is an AgendaEvent"? What risk does free text add to the email?
Solution
A cancellation_reason text column in events, and cancellationReason: string | null in the AgendaEvent type, so that the row is still an AgendaEvent. When you extend the type, you have to review the seed data, the test objects (testEvent) and the column selections that build an AgendaEvent, such as withVenueColumns: TypeScript points them out. toPublicEvent does not change on its own, and that's fine: the API doesn't publish a new field by accident.
cancelEvent(id, reason) writes it in the same UPDATE, after passing it through text({ min: 0, max: 200 }). The migration is compatible with the previous version of the code, because the column accepts nulls (11-04).
The risk: the organizer writes a text that goes out with our sender address to people who didn't choose to receive it. Since it's an identified and audited account, it's acceptable, but it's worth blocking web addresses in the reason and sending it as plain text, never as HTML.
Exercise 2: finding the flaw
A colleague proposes this "simpler" version. List the problems, in order of severity.
export async function cancel(event: AgendaEvent) {
const user = await getCurrentUser()
if (event.organizerId !== user?.id) throw new Error('No')
await db.update(events).set({ status: 'canceled' }).where(eq(events.id, event.id))
const list = await db.select().from(bookings).where(eq(bookings.eventId, event.id))
await Promise.all(list.map((b) => sendEmail({ to: b.email, subject: 'Canceled', text: '…', key: event.id })))
await db.delete(bookings).where(eq(bookings.eventId, event.id))
redirect('/dashboard/events')
invalidateEvent(event.slug)
}Solution
- The browser says who the owner is: it receives the whole event, so anyone can put their own identifier in
organizerIdand cancel whatever they like. - It doesn't check the status: it cancels drafts, finished events and events already canceled, and in that last case it repeats the notifications.
- There's no transaction: if it fails halfway, the event is canceled and half the people don't know.
- A booking can slip in between the query and the delete, and it will be deleted without notice. And deleting destroys the record.
- Three hundred sends at once inside the action: the provider rejects them, the person waits and the route's duration runs out.
- The same idempotency key for everyone: the provider will send one email.
invalidateEventcomes afterredirect: it never runs, and the event page will keep offering spots.b.emaildoesn't exist inbookings; andselect()brings back too many columns.- No validation, rate limit or audit entry.
Exercise 3: checking people in at the door
They ask to be able to mark from a phone who has come in. Design the table or column, the action, what it does without coverage, and what privacy problem keeping that information raises.
Solution
A checked_in_at timestamptz column in bookings, null until the person comes in. The action, markCheckIn(bookingId, present: boolean), sets a value instead of toggling it, so that repeating it is harmless (06-04), and puts ownership in the where through the event. The list now needs the booking's identifier, which is why the DTO changes: it's another function, listForCheckIn, with its own permission. useOptimistic fits very well here: it's frequent, reversible and done by someone in a hurry.
Without coverage, the actions fail and the mark reverts. For a venue with poor signal you'd need to store the marks in the browser and send them later, with conflicts if there are two people at the door; with a fixed value and the device's time they can be merged, but by then it's an application with a different level of complexity. The first thing is to ask whether the printed list isn't enough.
Privacy: you go from "booked" to "was there at such a time". For capacity purposes there's no need to keep it with the name after the event: the count is enough. The proposal would be to delete the marks the next day with a scheduled task and keep only the total, and to have compliance validate it.
Conclusion
Correcting what's published means deriving the spots from what's booked, with the row locked; canceling is a transition in the where, with the notifications written in the same transaction and the bookings kept; viewing attendees means deciding which data is really needed. The download neutralizes formulas, isn't stored anywhere and is recorded before it's handed over. The tests don't say who wins a race, but which endings are impossible. With this, AgendaViva meets the scope of 1.0.
It's complete, and it's still on your machine. It's time someone else saw it. The next lesson looks at what Next.js asks of a platform, what needs preparing in the application and how to publish it on one that takes care of the rest: Deploying to a Managed Platform.
