feat(logistics): external attendees self-select lunch dish via tokenized page
All checks were successful
Build and Push Docker Image / build (push) Successful in 7m51s

External lunch attendees had no way to pick their own dish — an admin had to set
it inline and no email was ever sent. (Marine added herself as an external
expecting a dish-selection link and never received one.)

Adds:
- ExternalAttendee.inviteSentAt + additive migration
- HMAC-signed external lunch token (mirrors finalist-token)
- Public no-login picker page /lunch/pick/[token] — dish + allergens + notes,
  gated by the lunch change deadline, read-only after
- tRPC getExternalByToken / setExternalPick (public) + sendExternalInvite (admin)
- Auto-send invite on createExternal when an email is present; per-row resend
  button + status chip (Invited / Picked / no email) in the logistics screen
- Unpicked externals chased by the lunch reminder cron + manual "Send reminders"
- sendExternalDishInviteEmail (branded). Page + email title use the configurable
  venue ("Lunch at {venue}") rather than "grand finale"

Tests: token roundtrip/tamper/expiry, selectUnpickedExternals filter,
get/set-by-token happy + deadline + bad-token, createExternal auto-send,
cron external reminders. Full suite 303 passing; build clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt
2026-06-05 12:04:13 +02:00
parent f2c8cc1e80
commit 8d4f0bac1e
15 changed files with 1292 additions and 4 deletions

View File

@@ -1,10 +1,12 @@
import { z } from 'zod'
import { TRPCError } from '@trpc/server'
import { router, adminProcedure, protectedProcedure } from '../trpc'
import { router, adminProcedure, protectedProcedure, publicProcedure } from '../trpc'
import { logAudit } from '../utils/audit'
import { buildManifest, buildRecapPayload } from '../services/lunch-recap'
import { selectUnpickedAttendees } from '../services/lunch-reminders'
import { selectUnpickedAttendees, selectUnpickedExternals } from '../services/lunch-reminders'
import { sendExternalDishInvite } from '../services/lunch-external-invite'
import { sendLunchRecapEmail, sendLunchReminderEmail } from '@/lib/email'
import { verifyExternalLunchToken } from '@/lib/external-lunch-token'
import { csvCell } from '@/lib/csv'
// ─── Shared zod schemas ──────────────────────────────────────────────────────
@@ -179,6 +181,19 @@ export const lunchRouter = router({
entityId: ext.id,
detailsJson: { name: ext.name, projectId: ext.projectId },
})
// Auto-send the dish-selection invite when an email is on file. Never throws
// — a failed send leaves inviteSentAt null so the admin can resend.
if (ext.email) {
try {
const event = await ctx.prisma.lunchEvent.findUnique({
where: { id: input.lunchEventId },
select: { eventAt: true, venue: true, notes: true, changeCutoffHours: true },
})
if (event) await sendExternalDishInvite(ctx.prisma, ext, event)
} catch (e) {
console.error('[lunch.createExternal] dish invite send failed', e)
}
}
return ext
}),
@@ -229,6 +244,159 @@ export const lunchRouter = router({
return { ok: true as const }
}),
/**
* Send (or resend) the dish-selection invite to one external attendee.
* Stamps `inviteSentAt` and audit-logs. Fails if the attendee has no email.
*/
sendExternalInvite: adminProcedure
.input(z.object({ externalId: z.string() }))
.mutation(async ({ ctx, input }) => {
const external = await ctx.prisma.externalAttendee.findUnique({
where: { id: input.externalId },
include: {
lunchEvent: {
select: { eventAt: true, venue: true, notes: true, changeCutoffHours: true },
},
},
})
if (!external) throw new TRPCError({ code: 'NOT_FOUND' })
if (!external.email) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: 'This attendee has no email address. Add one first.',
})
}
try {
await sendExternalDishInvite(ctx.prisma, external, external.lunchEvent)
} catch (e) {
throw new TRPCError({
code: 'INTERNAL_SERVER_ERROR',
message: `Failed to send invite: ${e instanceof Error ? e.message : String(e)}`,
cause: e,
})
}
await logAudit({
prisma: ctx.prisma,
userId: ctx.user.id,
action: 'LUNCH_EXTERNAL_INVITE_SENT',
entityType: 'ExternalAttendee',
entityId: external.id,
detailsJson: { email: external.email },
})
return { ok: true as const }
}),
// ─── Public tokenized external dish picker ───────────────────────────────
/**
* Read an external attendee + their event + dishes by a signed, no-login token.
* Token verification throws on bad signature / expiry; the page maps those to
* friendly states.
*/
getExternalByToken: publicProcedure
.input(z.object({ token: z.string() }))
.query(async ({ ctx, input }) => {
const payload = verifyExternalLunchToken(input.token) // throws on bad sig / expired
const external = await ctx.prisma.externalAttendee.findUnique({
where: { id: payload.externalId },
include: {
lunchEvent: {
select: {
id: true,
eventAt: true,
endAt: true,
venue: true,
notes: true,
changeCutoffHours: true,
},
},
},
})
if (!external) throw new TRPCError({ code: 'NOT_FOUND' })
const dishes = await ctx.prisma.dish.findMany({
where: { lunchEventId: external.lunchEventId },
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
})
const eventAt = external.lunchEvent.eventAt
const changeDeadline = eventAt
? new Date(eventAt.getTime() - external.lunchEvent.changeCutoffHours * 3_600_000)
: null
return {
external: {
id: external.id,
name: external.name,
dishId: external.dishId,
allergens: external.allergens,
allergenOther: external.allergenOther,
},
event: {
eventAt,
endAt: external.lunchEvent.endAt,
venue: external.lunchEvent.venue,
notes: external.lunchEvent.notes,
},
dishes,
changeDeadline,
}
}),
/**
* Save an external attendee's dish pick via their signed token. Enforces the
* lunch change cutoff (eventAt changeCutoffHours); past it, the attendee must
* contact an admin.
*/
setExternalPick: publicProcedure
.input(
z.object({
token: z.string(),
dishId: z.string().nullable(),
allergens,
allergenOther: z.string().max(500).nullable(),
}),
)
.mutation(async ({ ctx, input }) => {
const payload = verifyExternalLunchToken(input.token)
const external = await ctx.prisma.externalAttendee.findUnique({
where: { id: payload.externalId },
include: {
lunchEvent: { select: { eventAt: true, changeCutoffHours: true } },
},
})
if (!external) throw new TRPCError({ code: 'NOT_FOUND' })
const eventAt = external.lunchEvent.eventAt
if (eventAt) {
const deadline = new Date(
eventAt.getTime() - external.lunchEvent.changeCutoffHours * 3_600_000,
)
if (new Date() > deadline) {
throw new TRPCError({
code: 'PRECONDITION_FAILED',
message: 'Past the lunch change deadline. Please contact an admin.',
})
}
}
// Dish must belong to this attendee's event (defends against cross-event ids).
if (input.dishId) {
const dish = await ctx.prisma.dish.findFirst({
where: { id: input.dishId, lunchEventId: external.lunchEventId },
select: { id: true },
})
if (!dish) throw new TRPCError({ code: 'BAD_REQUEST', message: 'Unknown dish' })
}
const updated = await ctx.prisma.externalAttendee.update({
where: { id: external.id },
data: {
dishId: input.dishId,
allergens: input.allergens,
allergenOther: input.allergenOther,
},
})
return { ok: true as const, dishId: updated.dishId }
}),
// ─── Single-row pick read (used by per-row picker UI) ────────────────────
/**
@@ -611,6 +779,19 @@ export const lunchRouter = router({
console.error('[lunch.sendReminders] send failed for', am.user.email, e)
}
}
// External attendees: chase the ones with an email and no dish yet, via
// their own tokenized pick page.
const externals = await selectUnpickedExternals(ctx.prisma, { id: event.id })
for (const ext of externals) {
if (!ext.email) continue
try {
await sendExternalDishInvite(ctx.prisma, ext, event)
sent++
} catch (e) {
console.error('[lunch.sendReminders] external send failed for', ext.email, e)
}
}
return { sent }
}),