From a5203520714e06afb9f9035031824308307ce0dc Mon Sep 17 00:00:00 2001 From: blake Date: Mon, 2 Nov 2026 13:32:33 -0600 Subject: [PATCH] feat: implement reminder cancellation functionality and UI updates Added new features for managing reminder cancellations, including the ability to cancel signups directly from reminder emails. Introduced new components and styles for the ReminderOffPage and ReminderCancelPage, enhancing user experience with clear confirmation prompts and action buttons. Updated the reminder logic to handle cancellation tokens securely and ensure proper handling of signup statuses. Enhanced tests to cover new cancellation flows and UI elements, ensuring robust functionality across the application. --- public/css/app.css | 62 +++++++++++- src/cancel-token.ts | 9 ++ src/mail/queue.ts | 4 +- src/mail/templates.ts | 6 +- src/pages.tsx | 211 ++++++++++++++++++++++++++++++---------- src/reminder-http.tsx | 198 +++++++++++++++++++++++++++---------- src/reminders.ts | 65 ++++++++++++- src/signup.ts | 133 +++++++++++++++++++------ tests/reminders.test.ts | 165 ++++++++++++++++++++++++++++++- 9 files changed, 714 insertions(+), 139 deletions(-) diff --git a/public/css/app.css b/public/css/app.css index 49f3c6d..999516f 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -782,6 +782,55 @@ main a:hover { margin-top: 1rem; } +.manage > .cancel-form { + max-width: 36rem; +} + +.reminder-job { + display: grid; + gap: 1.15rem; + min-width: 0; +} + +.reminder-job h2 { + margin: 0; + font-size: 1.2rem; + line-height: 1.3; +} + +.reminder-cancel { + display: grid; + gap: 0.7rem; + justify-items: start; +} + +.reminder-job p, +.signup-reminders p { + margin: 0; +} + +.reminder-job .confirm-actions { + margin-top: 0.15rem; +} + +.signup-reminders button { + justify-self: start; +} + +.signup-reminders { + display: grid; + gap: 0.7rem; + margin: 0; + color: var(--hope-ink-2); + font-size: 0.95rem; + line-height: 1.45; +} + +.reminder-job .reminder-cancel + .signup-reminders { + padding-top: 1.15rem; + border-top: 1px solid var(--hope-border-2); +} + .manage .error { margin: 0.5rem 0 0; } @@ -1878,6 +1927,7 @@ article.shift-card { .signup-form button, .cancel-form button, +.cancel-form a.btn, .move-form button, .inline-form button { width: fit-content; @@ -1890,6 +1940,10 @@ article.shift-card { margin-top: 1.25rem; } +.cancel-form p { + margin: 0; +} + .manage-actions { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); @@ -4151,7 +4205,13 @@ button.btn-quiet::before { .signup-form button, .cancel-form button, - .move-form button { + .cancel-form a.btn, + .move-form button, + .reminder-cancel .btn, + .reminder-job .confirm-actions, + .reminder-job .confirm-actions .btn, + .reminder-job .confirm-actions button, + .signup-reminders button { width: 100%; } diff --git a/src/cancel-token.ts b/src/cancel-token.ts index d46bcb4..5d5ab71 100644 --- a/src/cancel-token.ts +++ b/src/cancel-token.ts @@ -20,6 +20,11 @@ export function issuePartyToken(secret: string, manageToken: string): string { return createHmac('sha256', secret).update(`hope-party-v1\0${manageToken}`).digest('base64url'); } +/** Binds a cancel POST to the reminder link. It is not the manage token, and a one-click unsubscribe does not send it. */ +export function issueReminderCancelToken(secret: string, unsubscribeToken: string): string { + return createHmac('sha256', secret).update(`hope-reminder-cancel-v1\0${unsubscribeToken}`).digest('base64url'); +} + export function cancelTokenMatches(secret: string, manageToken: string, received: string): boolean { return tokenMatches(issueCancelToken(secret, manageToken), received); } @@ -36,6 +41,10 @@ export function partyTokenMatches(secret: string, manageToken: string, received: return tokenMatches(issuePartyToken(secret, manageToken), received); } +export function reminderCancelTokenMatches(secret: string, unsubscribeToken: string, received: string): boolean { + return tokenMatches(issueReminderCancelToken(secret, unsubscribeToken), received); +} + function tokenMatches(expected: string, received: string): boolean { if (!/^[A-Za-z0-9_-]{20,128}$/.test(received)) return false; const left = Buffer.from(expected); diff --git a/src/mail/queue.ts b/src/mail/queue.ts index 9c0ca68..8fbbee1 100644 --- a/src/mail/queue.ts +++ b/src/mail/queue.ts @@ -25,6 +25,8 @@ export type QueuedSignup = { mail: MailIdentity; now: string; linkNote?: string; + /** Used when the letter cannot include the private /m/ link. The manage token is stored only as a hash. */ + pageUrl?: string; }; /** Inserts one row per recipient. The same logical message does not get a second row. */ @@ -216,5 +218,5 @@ function queue( } function manageUrl(input: QueuedSignup): string { - return absoluteUrl(input.mail, `/m/${input.token}`); + return input.pageUrl ?? absoluteUrl(input.mail, `/m/${input.token}`); } diff --git a/src/mail/templates.ts b/src/mail/templates.ts index 260804d..e6dbdbd 100644 --- a/src/mail/templates.ts +++ b/src/mail/templates.ts @@ -125,7 +125,8 @@ export function renderReminder(input: { const name = singleLine(input.volunteerName); const subject = `Reminder: ${role}`; const hello = `You are still signed up for ${role}.${partyNote(input.groupSize)}`; - const cancelNote = 'To cancel, use the link in your confirmation email.'; + const spots = input.groupSize && input.groupSize > 1 ? `these ${input.groupSize} spots open` : 'the spot opens'; + const cancelNote = `To cancel this signup, open ${input.unsubscribeUrl}. You confirm before ${spots} for someone else.`; const stopNote = `To stop reminder emails for this signup, open ${input.unsubscribeUrl}. The pantry reads mail sent to ${input.replyTo}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.`; const greeting = `Hello ${name},`; const when = input.shift.whenLabel; @@ -156,7 +157,8 @@ export function renderReminder(input: {

${escapeHtml(greeting)}

${escapeHtml(hello)}

${escapeHtml(input.shift.eventTitle)}
${escapeHtml(when)}${htmlPlace}

-

${escapeHtml(cancelNote)}

+

Cancel this signup

+

You confirm before ${escapeHtml(spots)} for someone else.

Stop reminder emails

The pantry reads mail sent to ${escapeHtml(input.replyTo)}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.

Hope Food Pantry

diff --git a/src/pages.tsx b/src/pages.tsx index 7d8558f..daf77f9 100644 --- a/src/pages.tsx +++ b/src/pages.tsx @@ -6,7 +6,9 @@ import { SIGNUP_TOO_EARLY, signupDeadlineLabel } from './signup-window.js'; import { partyChoiceLabel, partyChoices, type SignupErrors, type SignupValues } from './signup-form.js'; import type { MoveTarget } from './admin/store.js'; import { ShiftTargetOptions } from './shift-options.js'; +import type { ReminderPageSignup } from './reminders.js'; import type { ManageView } from './signup.js'; +import type { ZonedClock } from './time.js'; import { assetHref } from './static-assets.js'; import { appPath } from './url.js'; @@ -414,17 +416,7 @@ export function ManagePage(props: { const cancelled = signup.status !== 'confirmed'; return (
-
-

Your signup

-

{cancelled ? 'Cancelled' : 'Confirmed'}

-

{signup.eventTitle}

-

{signup.role}

-

- {signup.when.timeLabel} {signup.when.abbreviation} -

- {signup.location ?

{signup.location}

: null} - {!cancelled && signup.ended ?

This shift has ended.

: null} -
+ {props.note ?

{props.note}

: null} {props.notice ? (
-
-
Name
-
{signup.name}
-
-
-
People
-
{signup.groupSize}
-
-
-
Email
-
{signup.email}
-
- {signup.phone ? ( -
-
Phone
-
{signup.phone}
-
- ) : null} - {signup.notes ? ( -
-
Notes
-
{signup.notes}
-
- ) : null} -
+ {party || props.switches ? (
{party ? ( @@ -595,28 +562,172 @@ export function SwitchAlreadyPage() { ); } -export function ReminderOffPage(props: { config: AppConfig; token: string; replyTo: string; off: boolean; error?: string }) { +export function ReminderOffPage(props: { config: AppConfig; token: string; signup: ReminderPageSignup; error?: string }) { + const signup = props.signup; + const cancelled = signup.status !== 'confirmed'; + const canCancel = !cancelled && !signup.ended; return ( - <> -

Reminder emails

+
+ {props.error ? ( ) : null} - {props.off ? ( -

Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.

- ) : ( -
-

This turns off reminder emails for this signup. It does not cancel the signup. Confirmation, change, and cancellation emails still arrive.

-

The pantry reads mail sent to {props.replyTo}. This button turns reminders off immediately.

- -
- )} - +
+ + {cancelled ? null : ( +
+
+ {canCancel ? ( +
+

{openSpots(signup.groupSize)}

+ + Cancel this signup + +
+ ) : null} + +
+
+ )} +
+ {cancelled ?

{cancelledSignupCopy(signup.groupSize)}

: null} +
); } +export function ReminderCancelPage(props: { + config: AppConfig; + token: string; + signup: ReminderPageSignup; + cancelToken: string; + error?: string; +}) { + return ( +
+ + {props.error ? ( + + ) : null} +
+ +
+
+ +

Are you sure you want to cancel?

+

{cancelEffect(props.signup.groupSize)}

+
+ + + Go back + +
+
+
+
+
+ ); +} + +type SignupIdentity = { + name: string; + email: string; + phone: string | null; + notes: string | null; + groupSize: number; + status: 'confirmed' | 'cancelled'; + role: string; + location: string; + eventTitle: string; + when: ZonedClock; + ended: boolean; +}; + +function SignupIntro(props: { signup: SignupIdentity }) { + const signup = props.signup; + const cancelled = signup.status !== 'confirmed'; + return ( +
+

Your signup

+

{cancelled ? 'Cancelled' : 'Confirmed'}

+

{signup.eventTitle}

+

{signup.role}

+

+ {signup.when.timeLabel} {signup.when.abbreviation} +

+ {signup.location ?

{signup.location}

: null} + {!cancelled && signup.ended ?

This shift has ended.

: null} +
+ ); +} + +function SignupFacts(props: { signup: SignupIdentity }) { + const signup = props.signup; + return ( +
+
+
Name
+
{signup.name}
+
+
+
People
+
{signup.groupSize}
+
+
+
Email
+
{signup.email}
+
+ {signup.phone ? ( +
+
Phone
+
{signup.phone}
+
+ ) : null} + {signup.notes ? ( +
+
Notes
+
{signup.notes}
+
+ ) : null} +
+ ); +} + +function ReminderPreference(props: { config: AppConfig; token: string; off: boolean }) { + if (props.off) { + return ( + + ); + } + return ( + + ); +} + +function openSpots(groupSize: number): string { + return groupSize > 1 ? `Opens these ${groupSize} spots for someone else.` : 'Opens the spot for someone else.'; +} + +function cancelEffect(groupSize: number): string { + return groupSize > 1 + ? `Cancel this signup to open these ${groupSize} spots for someone else. A cancellation email is queued when you cancel.` + : 'Cancel this signup to open the spot for someone else. A cancellation email is queued when you cancel.'; +} + +function cancelledSignupCopy(groupSize: number): string { + return groupSize > 1 + ? `This signup is cancelled. The ${groupSize} spots it held are open for someone else. A cancellation email is queued.` + : 'This signup is cancelled. The spot is open for someone else. A cancellation email is queued.'; +} + export function NotFoundPage() { return ( <> diff --git a/src/reminder-http.tsx b/src/reminder-http.tsx index 04df153..e35dfd2 100644 --- a/src/reminder-http.tsx +++ b/src/reminder-http.tsx @@ -1,79 +1,164 @@ import { getConnInfo } from '@hono/node-server/conninfo'; import type { Context, Hono } from 'hono'; import type { Child } from 'hono/jsx'; +import type Database from 'better-sqlite3'; import { readSession } from './auth/session.js'; +import { issueReminderCancelToken, reminderCancelTokenMatches } from './cancel-token.js'; import { clientAddress } from './client-ip.js'; import type { AppConfig } from './config.js'; -import { Layout, NotFoundPage, ReminderOffPage, WaitPage } from './pages.js'; +import type { MailIdentity } from './mail/types.js'; +import { originAllowed } from './origin.js'; +import { Layout, NotFoundPage, ReminderCancelPage, ReminderOffPage, WaitPage } from './pages.js'; import { recordInvalidUnsubscribe } from './rate-limit.js'; -import { disableReminders, readReminderOffToken } from './reminders.js'; +import { disableReminders, readReminderOffToken, readReminderSignup, type ReminderPageSignup } from './reminders.js'; import { readReplyTo } from './settings.js'; +import { cancelSignupById } from './signup.js'; import { isBusy } from './sqlite-error.js'; -import { appPath } from './url.js'; -import type Database from 'better-sqlite3'; +import { absoluteUrl, appPath } from './url.js'; -export function registerReminderOff( - app: Hono, - services: { - config: AppConfig; - db: Database.Database; - now: () => string; - clientIp?: (c: Context) => string | null; - }, -): void { - app.get(appPath(services.config, '/u/:token'), (c) => showReminderOff(c, services)); - app.post(appPath(services.config, '/u/:token'), (c) => submitReminderOff(c, services)); +const CANCEL_ORIGIN = 'The cancellation could not be sent from this page.'; +const CANCEL_REJECTED = 'The cancellation could not be confirmed. Please try again.'; +const CANCEL_UNAVAILABLE = 'The cancellation could not be saved. Please try again in a little while.'; + +type ReminderServices = { + config: AppConfig; + db: Database.Database; + now: () => string; + clientIp?: (c: Context) => string | null; +}; + +/** + * The reminder link opens one signup. + * POST /u/:token only turns reminders off, because mail clients one-click unsubscribe to that address. + * Cancelling is a separate confirmed POST. + */ +export function registerReminderOff(app: Hono, services: ReminderServices): void { + const unsubscribe = appPath(services.config, '/u/:token'); + const cancel = appPath(services.config, '/u/:token/cancel'); + app.get(cancel, (c) => showCancel(c, services)); + app.post(cancel, (c) => submitCancel(c, services)); + app.get(unsubscribe, (c) => showReminderOff(c, services)); + app.post(unsubscribe, (c) => submitReminderOff(c, services)); } -function showReminderOff( - c: Context, - services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null }, -) { - const signupId = readReminderOffToken(services.config.sessionSecret, c.req.param('token') ?? ''); - if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services); - const off = remindersOff(services.db, signupId); - return page(c, services, ); +function showReminderOff(c: Context, services: ReminderServices) { + const loaded = loadSignup(c, services); + if (!loaded) return unavailable(c, services); + return page(c, services, 'Your signup · Hope Volunteer', ); } -async function submitReminderOff( - c: Context, - services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null }, -): Promise { - const token = c.req.param('token') ?? ''; - const signupId = readReminderOffToken(services.config.sessionSecret, token); - if (signupId === null || !reminderSignup(services.db, signupId)) return unavailable(c, services); +async function submitReminderOff(c: Context, services: ReminderServices): Promise { + const loaded = loadSignup(c, services); + if (!loaded) return unavailable(c, services); try { - const result = disableReminders(services.db, signupId, services.now()); + const result = disableReminders(services.db, loaded.signupId, services.now()); if (!result.ok) return unavailable(c, services); } catch (err) { if (!isBusy(err)) throw err; console.error('Reminder opt-out could not lock the database.'); - return page(c, services, , 503); + return page( + c, + services, + 'Your signup · Hope Volunteer', + , + 503, + ); } - return page(c, services, ); + const signup = readReminderSignup(services.db, loaded.signupId, services.now()) ?? { ...loaded.signup, remindersOff: true }; + return page(c, services, 'Your signup · Hope Volunteer', ); } -function reminderSignup(db: Database.Database, signupId: number): boolean { - const row = db.prepare('SELECT id FROM signups WHERE id = ? AND anonymized_at IS NULL').get(signupId); - return Boolean(row); +function showCancel(c: Context, services: ReminderServices) { + const loaded = loadSignup(c, services); + if (!loaded) return unavailable(c, services); + if (!canCancel(loaded.signup)) { + c.header('Cache-Control', 'no-store'); + return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303); + } + return confirmPage(c, services, loaded.token, loaded.signup); } -function remindersOff(db: Database.Database, signupId: number): boolean { - const row = db.prepare('SELECT reminders_off AS reminders_off FROM signups WHERE id = ?').get(signupId) as { reminders_off: number } | undefined; - return row?.reminders_off === 1; +async function submitCancel(c: Context, services: ReminderServices): Promise { + const loaded = loadSignup(c, services); + if (!loaded) return unavailable(c, services); + if (loaded.signup.status === 'cancelled') { + c.header('Cache-Control', 'no-store'); + return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303); + } + if (!canCancel(loaded.signup)) { + return page(c, services, 'Your signup · Hope Volunteer', , 400); + } + if (!originAllowed(c, services.config.baseUrl)) return confirmPage(c, services, loaded.token, loaded.signup, 403, CANCEL_ORIGIN); + const body = await c.req.parseBody(); + if (!reminderCancelTokenMatches(services.config.sessionSecret, loaded.token, textField(body, 'cancel_token'))) { + return confirmPage(c, services, loaded.token, loaded.signup, 400, CANCEL_REJECTED); + } + try { + const result = cancelSignupById( + services.db, + loaded.signupId, + services.now(), + mailIdentity(services), + absoluteUrl(services.config, `/u/${loaded.token}`), + ); + if (!result.ok && result.reason === 'ended') { + const signup = readReminderSignup(services.db, loaded.signupId, services.now()) ?? loaded.signup; + return page(c, services, 'Your signup · Hope Volunteer', , 400); + } + if (!result.ok) return unavailable(c, services); + } catch (err) { + if (!isBusy(err)) throw err; + console.error('Cancellation could not lock the database.'); + return confirmPage(c, services, loaded.token, loaded.signup, 503, CANCEL_UNAVAILABLE); + } + c.header('Cache-Control', 'no-store'); + return c.redirect(appPath(services.config, `/u/${loaded.token}`), 303); } -function unavailable( +function loadSignup(c: Context, services: ReminderServices): { token: string; signupId: number; signup: ReminderPageSignup } | null { + const token = c.req.param('token') ?? ''; + const signupId = readReminderOffToken(services.config.sessionSecret, token); + if (signupId === null) return null; + const signup = readReminderSignup(services.db, signupId, services.now()); + if (!signup) return null; + return { token, signupId, signup }; +} + +function canCancel(signup: ReminderPageSignup): boolean { + return signup.status === 'confirmed' && !signup.ended; +} + +function confirmPage( c: Context, - services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null }, + services: ReminderServices, + token: string, + signup: ReminderPageSignup, + status: 200 | 400 | 403 | 503 = 200, + error?: string, ) { + return page( + c, + services, + 'Cancel this signup · Hope Volunteer', + , + status, + ); +} + +function unavailable(c: Context, services: ReminderServices) { const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for')); const limit = recordInvalidUnsubscribe(services.db, services.config.sessionSecret, services.now(), ip); if (limit.limited) { c.header('Retry-After', String(limit.retryAfter)); - return page(c, services, , 429); + return page(c, services, 'Please wait · Hope Volunteer', , 429); } - return page(c, services, , 404); + return page(c, services, 'That page is not available · Hope Volunteer', , 404); } function peerAddress(c: Context, override?: (c: Context) => string | null): string | null { @@ -85,18 +170,31 @@ function peerAddress(c: Context, override?: (c: Context) => string | null): stri } } -function page( - c: Context, - services: { config: AppConfig; db: Database.Database; now: () => string }, - body: Child, - status: 200 | 404 | 429 | 503 = 200, -) { +function page(c: Context, services: ReminderServices, title: string, body: Child, status: 200 | 400 | 403 | 404 | 429 | 503 = 200) { c.header('Cache-Control', 'no-store'); const account = readSession(services.db, c.req.header('cookie'), services.now()); return c.html( - + {body} , status, ); } + +function mailIdentity(services: ReminderServices): MailIdentity { + return { + baseUrl: services.config.baseUrl, + basePath: services.config.basePath, + from: services.config.mail.from, + replyTo: replyTo(services), + }; +} + +function replyTo(services: ReminderServices): string { + return readReplyTo(services.db, services.config.mail.replyTo); +} + +function textField(body: Record, name: string): string { + const value = body[name]; + return typeof value === 'string' ? value : ''; +} diff --git a/src/reminders.ts b/src/reminders.ts index 1e5eb7b..71c2db8 100644 --- a/src/reminders.ts +++ b/src/reminders.ts @@ -5,7 +5,7 @@ import { cancelPendingReminders } from './mail/queue.js'; import { renderReminder } from './mail/templates.js'; import type { MailIdentity } from './mail/types.js'; import { readReminderOffsets, readReplyTo } from './settings.js'; -import { formatInstantInZone } from './time.js'; +import { formatInstantInZone, type ZonedClock } from './time.js'; import { absoluteUrl } from './url.js'; export type ReminderPass = { queued: number; suppressed: number }; @@ -132,6 +132,69 @@ export function issueReminderOffToken(secret: string, signupId: number): string return `${id}.${mac}`; } +export type ReminderPageSignup = { + name: string; + email: string; + phone: string | null; + notes: string | null; + role: string; + eventTitle: string; + location: string; + when: ZonedClock; + groupSize: number; + status: 'confirmed' | 'cancelled'; + ended: boolean; + remindersOff: boolean; +}; + +/** The signup a reminder link may show. An anonymized row, or a row without a name and email, is omitted. */ +export function readReminderSignup(db: Database.Database, signupId: number, now: string): ReminderPageSignup | null { + const row = db + .prepare( + `SELECT su.name AS name, su.email AS email, su.phone AS phone, su.notes AS notes, + su.group_size AS group_size, su.status AS status, su.reminders_off AS reminders_off, + s.role AS role, s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc, + e.title AS title, e.location AS location, e.tz AS tz + FROM signups su + JOIN shifts s ON s.id = su.shift_id + JOIN events e ON e.id = s.event_id + WHERE su.id = ? AND su.anonymized_at IS NULL`, + ) + .get(signupId) as + | { + name: string | null; + email: string | null; + phone: string | null; + notes: string | null; + group_size: number; + status: string; + reminders_off: number; + role: string; + starts_at_utc: string; + ends_at_utc: string; + title: string; + location: string; + tz: string; + } + | undefined; + if (!row || !row.name || !row.email) return null; + if (row.status !== 'confirmed' && row.status !== 'cancelled') return null; + return { + name: row.name, + email: row.email, + phone: row.phone, + notes: row.notes, + role: row.role, + eventTitle: row.title, + location: row.location.trim(), + when: formatInstantInZone(row.starts_at_utc, row.tz), + groupSize: Number(row.group_size), + status: row.status, + ended: row.ends_at_utc <= now, + remindersOff: row.reminders_off === 1, + }; +} + export function readReminderOffToken(secret: string, token: string): number | null { if (!/^([1-9][0-9]{0,15})\.([A-Za-z0-9_-]{20,128})$/.test(token)) return null; const id = Number(token.slice(0, token.indexOf('.'))); diff --git a/src/signup.ts b/src/signup.ts index 4f93d9d..e860612 100644 --- a/src/signup.ts +++ b/src/signup.ts @@ -101,6 +101,23 @@ export function cancelSignup(db: Database.Database, token: string, now: string, return db.transaction(() => cancelConfirmed(db, hash, token, now, mail)).immediate(); } +/** + * Cancels one signup from the reminder link. The private manage token is only stored as a hash, so this does not need it. + * The manage link keeps working. The cancellation letter links to pageUrl, which is the reminder page. + * Cancelling again does not queue a second letter. + * Once the shift has ended, a confirmed signup stays confirmed and no mail is queued. + */ +export function cancelSignupById( + db: Database.Database, + signupId: number, + now: string, + mail: MailIdentity, + pageUrl: string, +): CancelResult { + if (!Number.isSafeInteger(signupId) || signupId <= 0 || pageUrl.trim() === '') return { ok: false, reason: 'invalid' }; + return db.transaction(() => cancelConfirmedById(db, signupId, now, mail, pageUrl)).immediate(); +} + export type PartySizeResult = | { ok: true; groupSize: number; changed: boolean } | { ok: false; reason: 'invalid' | 'cancelled' | 'full' | 'ended'; spotsLeft?: number }; @@ -399,6 +416,92 @@ function writePartySize( return { ok: true, groupSize, changed: true }; } +type CancelMailRow = { + id: number; + status: string; + anonymized_at: string | null; + name: string | null; + email_norm: string | null; + shift_id: number; + group_size: number; +}; + +function cancelConfirmedById( + db: Database.Database, + signupId: number, + now: string, + mail: MailIdentity, + pageUrl: string, +): CancelResult { + const row = db + .prepare( + `SELECT su.id AS id, su.status AS status, su.anonymized_at AS anonymized_at, + su.name AS name, su.email_norm AS email_norm, su.shift_id AS shift_id, su.group_size AS group_size + FROM signups su + WHERE su.id = ?`, + ) + .get(signupId) as CancelMailRow | undefined; + if (!row || row.anonymized_at) return { ok: false, reason: 'invalid' }; + if (row.status === 'cancelled') return { ok: true, already: true }; + if (row.status !== 'confirmed' || !row.name || !row.email_norm) return { ok: false, reason: 'invalid' }; + const endsAt = shiftEndsAt(db, row.shift_id); + if (endsAt === null) return { ok: false, reason: 'invalid' }; + if (endsAt <= now) return { ok: false, reason: 'ended' }; + const updated = db + .prepare( + `UPDATE signups + SET status = 'cancelled', updated_at = ? + WHERE id = ? AND status = 'confirmed' AND anonymized_at IS NULL`, + ) + .run(now, signupId); + if (updated.changes === 1) { + queueVolunteerCancellation(db, row, now, mail, { token: '', pageUrl }); + return { ok: true, already: false }; + } + const again = db.prepare('SELECT status AS status FROM signups WHERE id = ?').get(signupId) as { status: string } | undefined; + if (again?.status === 'cancelled') return { ok: true, already: true }; + return { ok: false, reason: 'invalid' }; +} + +function queueVolunteerCancellation( + db: Database.Database, + row: CancelMailRow, + now: string, + mail: MailIdentity, + link: { token: string; pageUrl?: string }, +): void { + if (!row.name || !row.email_norm) return; + cancelPendingConfirmations(db, row.id); + cancelPendingReminders(db, row.id, 'The signup was cancelled before this reminder was sent.'); + const shift = loadShiftFacts(db, row.shift_id); + if (!shift) return; + queueCancellation(db, { + signupId: row.id, + shiftId: row.shift_id, + shiftVersion: shift.version, + token: link.token, + pageUrl: link.pageUrl, + volunteerName: row.name, + volunteerEmail: row.email_norm, + groupSize: Number(row.group_size), + shift: shift.facts, + mail, + now, + }); + queueCoordinatorNotices(db, { + action: 'cancel', + signupId: row.id, + shiftId: row.shift_id, + shiftVersion: shift.version, + volunteerName: row.name, + volunteerEmail: row.email_norm, + groupSize: Number(row.group_size), + shift: shift.facts, + mail, + now, + }); +} + function shiftEndsAt(db: Database.Database, shiftId: number): string | null { const shift = db.prepare('SELECT ends_at_utc AS ends_at_utc FROM shifts WHERE id = ?').get(shiftId) as | { ends_at_utc: string } @@ -460,35 +563,7 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now ) .run(now, hash, now); if (updated.changes === 1) { - cancelPendingConfirmations(db, row.id); - cancelPendingReminders(db, row.id, 'The signup was cancelled before this reminder was sent.'); - const shift = loadShiftFacts(db, row.shift_id); - if (shift) { - queueCancellation(db, { - signupId: row.id, - shiftId: row.shift_id, - shiftVersion: shift.version, - token, - volunteerName: row.name, - volunteerEmail: row.email_norm, - groupSize: Number(row.group_size), - shift: shift.facts, - mail, - now, - }); - queueCoordinatorNotices(db, { - action: 'cancel', - signupId: row.id, - shiftId: row.shift_id, - shiftVersion: shift.version, - volunteerName: row.name, - volunteerEmail: row.email_norm, - groupSize: Number(row.group_size), - shift: shift.facts, - mail, - now, - }); - } + queueVolunteerCancellation(db, row, now, mail, { token }); return { ok: true, already: false }; } const again = db diff --git a/tests/reminders.test.ts b/tests/reminders.test.ts index 7aefd95..a2fda5f 100644 --- a/tests/reminders.test.ts +++ b/tests/reminders.test.ts @@ -9,6 +9,8 @@ import { loadConfig } from '../src/config.js'; import { openAppDatabase } from '../src/db.js'; import { deliverDueMail } from '../src/mail/deliver.js'; import type { Mailer } from '../src/mail/types.js'; +import { issueReminderCancelToken } from '../src/cancel-token.js'; +import { renderReminder } from '../src/mail/templates.js'; import { issueReminderOffToken } from '../src/reminders.js'; import { queueDueReminders } from '../src/reminders.js'; import { reserveSignup, type ReserveInput } from '../src/signup.js'; @@ -45,14 +47,18 @@ describe('reminder mail', () => { it('queues the 48 hour reminder, sends it once, and records provider acceptance', async () => { const db = await openDb(); const shiftId = insertShift(db, LATER_START, LATER_END); - reserveSignup(db, reservation(shiftId, { name: 'Pat