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.
This commit is contained in:
1 parent
a53389d7a8
commit
a520352071
9 files changed
+709
-134
No files matched your search
+61
-1
@@ -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%;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
+3
-1
@@ -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}`);
|
||||
}
|
||||
@@ -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: {
|
||||
<p>${escapeHtml(greeting)}</p>
|
||||
<p>${escapeHtml(hello)}</p>
|
||||
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||
<p>${escapeHtml(cancelNote)}</p>
|
||||
<p><a href="${escapeHtml(input.unsubscribeUrl)}" style="color:#222">Cancel this signup</a></p>
|
||||
<p>You confirm before ${escapeHtml(spots)} for someone else.</p>
|
||||
<p><a href="${escapeHtml(input.unsubscribeUrl)}" style="color:#222">Stop reminder emails</a></p>
|
||||
<p>The pantry reads mail sent to ${escapeHtml(input.replyTo)}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>Hope Food Pantry</p>
|
||||
|
||||
+160
-49
@@ -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 (
|
||||
<article class="manage">
|
||||
<header class="manage-intro">
|
||||
<h1>Your signup</h1>
|
||||
<p class={cancelled ? 'status is-cancelled' : 'status is-confirmed'}>{cancelled ? 'Cancelled' : 'Confirmed'}</p>
|
||||
<p>{signup.eventTitle}</p>
|
||||
<h2>{signup.role}</h2>
|
||||
<p class="when">
|
||||
<time dateTime={signup.when.date}>{signup.when.dateLabel}</time> {signup.when.timeLabel} {signup.when.abbreviation}
|
||||
</p>
|
||||
{signup.location ? <p class="location">{signup.location}</p> : null}
|
||||
{!cancelled && signup.ended ? <p>This shift has ended.</p> : null}
|
||||
</header>
|
||||
<SignupIntro signup={signup} />
|
||||
{props.note ? <p class="status">{props.note}</p> : null}
|
||||
{props.notice ? (
|
||||
<p class="error" role="alert">
|
||||
@@ -445,32 +437,7 @@ export function ManagePage(props: {
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
<dl class="details">
|
||||
<div>
|
||||
<dt>Name</dt>
|
||||
<dd>{signup.name}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>People</dt>
|
||||
<dd>{signup.groupSize}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Email</dt>
|
||||
<dd>{signup.email}</dd>
|
||||
</div>
|
||||
{signup.phone ? (
|
||||
<div>
|
||||
<dt>Phone</dt>
|
||||
<dd>{signup.phone}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.notes ? (
|
||||
<div class="is-wide">
|
||||
<dt>Notes</dt>
|
||||
<dd class="description">{signup.notes}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
<SignupFacts signup={signup} />
|
||||
{party || props.switches ? (
|
||||
<div class="manage-follow">
|
||||
{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 (
|
||||
<>
|
||||
<h1>Reminder emails</h1>
|
||||
<article class="manage">
|
||||
<SignupIntro signup={signup} />
|
||||
{props.error ? (
|
||||
<p class="error" role="alert">
|
||||
{props.error}
|
||||
</p>
|
||||
) : null}
|
||||
{props.off ? (
|
||||
<p>Reminder emails for this signup are off. The signup stays. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
) : (
|
||||
<form method="post" action={appPath(props.config, `/u/${props.token}`)} class="cancel-form">
|
||||
<p>This turns off reminder emails for this signup. It does not cancel the signup. Confirmation, change, and cancellation emails still arrive.</p>
|
||||
<p>The pantry reads mail sent to {props.replyTo}. This button turns reminders off immediately.</p>
|
||||
<button type="submit">Stop reminder emails</button>
|
||||
</form>
|
||||
<section class="manage-record">
|
||||
<SignupFacts signup={signup} />
|
||||
{cancelled ? null : (
|
||||
<div class="manage-follow">
|
||||
<div class="reminder-job">
|
||||
{canCancel ? (
|
||||
<div class="reminder-cancel">
|
||||
<p>{openSpots(signup.groupSize)}</p>
|
||||
<a class="btn" href={appPath(props.config, `/u/${props.token}/cancel`)}>
|
||||
Cancel this signup
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
<ReminderPreference config={props.config} token={props.token} off={signup.remindersOff} />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</section>
|
||||
{cancelled ? <p>{cancelledSignupCopy(signup.groupSize)}</p> : null}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReminderCancelPage(props: {
|
||||
config: AppConfig;
|
||||
token: string;
|
||||
signup: ReminderPageSignup;
|
||||
cancelToken: string;
|
||||
error?: string;
|
||||
}) {
|
||||
return (
|
||||
<article class="manage">
|
||||
<SignupIntro signup={props.signup} />
|
||||
{props.error ? (
|
||||
<p class="error" role="alert">
|
||||
{props.error}
|
||||
</p>
|
||||
) : null}
|
||||
<section class="manage-record">
|
||||
<SignupFacts signup={props.signup} />
|
||||
<div class="manage-follow">
|
||||
<form method="post" action={appPath(props.config, `/u/${props.token}/cancel`)} class="reminder-job">
|
||||
<input type="hidden" name="cancel_token" value={props.cancelToken} />
|
||||
<h2>Are you sure you want to cancel?</h2>
|
||||
<p>{cancelEffect(props.signup.groupSize)}</p>
|
||||
<div class="confirm-actions">
|
||||
<button type="submit">Cancel this signup</button>
|
||||
<a class="btn btn-quiet" href={appPath(props.config, `/u/${props.token}`)}>
|
||||
Go back
|
||||
</a>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<header class="manage-intro">
|
||||
<h1>Your signup</h1>
|
||||
<p class={cancelled ? 'status is-cancelled' : 'status is-confirmed'}>{cancelled ? 'Cancelled' : 'Confirmed'}</p>
|
||||
<p>{signup.eventTitle}</p>
|
||||
<h2>{signup.role}</h2>
|
||||
<p class="when">
|
||||
<time dateTime={signup.when.date}>{signup.when.dateLabel}</time> {signup.when.timeLabel} {signup.when.abbreviation}
|
||||
</p>
|
||||
{signup.location ? <p class="location">{signup.location}</p> : null}
|
||||
{!cancelled && signup.ended ? <p>This shift has ended.</p> : null}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
function SignupFacts(props: { signup: SignupIdentity }) {
|
||||
const signup = props.signup;
|
||||
return (
|
||||
<dl class="details">
|
||||
<div>
|
||||
<dt>Name</dt>
|
||||
<dd>{signup.name}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>People</dt>
|
||||
<dd>{signup.groupSize}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Email</dt>
|
||||
<dd>{signup.email}</dd>
|
||||
</div>
|
||||
{signup.phone ? (
|
||||
<div>
|
||||
<dt>Phone</dt>
|
||||
<dd>{signup.phone}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
{signup.notes ? (
|
||||
<div class="is-wide">
|
||||
<dt>Notes</dt>
|
||||
<dd class="description">{signup.notes}</dd>
|
||||
</div>
|
||||
) : null}
|
||||
</dl>
|
||||
);
|
||||
}
|
||||
|
||||
function ReminderPreference(props: { config: AppConfig; token: string; off: boolean }) {
|
||||
if (props.off) {
|
||||
return (
|
||||
<p class="signup-reminders">Reminder emails are off. This signup stays.</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form method="post" action={appPath(props.config, `/u/${props.token}`)} class="signup-reminders">
|
||||
<p>Reminder emails are on. Stopping them does not cancel this signup.</p>
|
||||
<button class="btn-quiet" type="submit">
|
||||
Stop reminder emails
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<>
|
||||
|
||||
+144
-46
@@ -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: {
|
||||
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;
|
||||
},
|
||||
): void {
|
||||
app.get(appPath(services.config, '/u/:token'), (c) => showReminderOff(c, services));
|
||||
app.post(appPath(services.config, '/u/:token'), (c) => submitReminderOff(c, services));
|
||||
};
|
||||
|
||||
/**
|
||||
* 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, <ReminderOffPage config={services.config} token={c.req.param('token') ?? ''} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={off} />);
|
||||
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', <ReminderOffPage config={services.config} token={loaded.token} signup={loaded.signup} />);
|
||||
}
|
||||
|
||||
async function submitReminderOff(
|
||||
c: Context,
|
||||
services: { config: AppConfig; db: Database.Database; now: () => string; clientIp?: (c: Context) => string | null },
|
||||
): Promise<Response> {
|
||||
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<Response> {
|
||||
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, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off={false} error="This could not be saved. Please try again." />, 503);
|
||||
return page(
|
||||
c,
|
||||
services,
|
||||
'Your signup · Hope Volunteer',
|
||||
<ReminderOffPage config={services.config} token={loaded.token} signup={loaded.signup} error="This could not be saved. Please try again." />,
|
||||
503,
|
||||
);
|
||||
}
|
||||
return page(c, services, <ReminderOffPage config={services.config} token={token} replyTo={readReplyTo(services.db, services.config.mail.replyTo)} off />);
|
||||
const signup = readReminderSignup(services.db, loaded.signupId, services.now()) ?? { ...loaded.signup, remindersOff: true };
|
||||
return page(c, services, 'Your signup · Hope Volunteer', <ReminderOffPage config={services.config} token={loaded.token} signup={signup} />);
|
||||
}
|
||||
|
||||
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<Response> {
|
||||
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', <ReminderOffPage config={services.config} token={loaded.token} signup={loaded.signup} />, 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', <ReminderOffPage config={services.config} token={loaded.token} signup={signup} />, 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',
|
||||
<ReminderCancelPage
|
||||
config={services.config}
|
||||
token={token}
|
||||
signup={signup}
|
||||
cancelToken={issueReminderCancelToken(services.config.sessionSecret, token)}
|
||||
error={error}
|
||||
/>,
|
||||
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, <WaitPage />, 429);
|
||||
return page(c, services, 'Please wait · Hope Volunteer', <WaitPage />, 429);
|
||||
}
|
||||
return page(c, services, <NotFoundPage />, 404);
|
||||
return page(c, services, 'That page is not available · Hope Volunteer', <NotFoundPage />, 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(
|
||||
<Layout config={services.config} title="Reminder emails · Hope Volunteer" path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
<Layout config={services.config} title={title} path={c.req.path} account={account ? { csrf: account.csrf } : null}>
|
||||
{body}
|
||||
</Layout>,
|
||||
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<string, unknown>, name: string): string {
|
||||
const value = body[name];
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
+64
-1
@@ -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('.')));
|
||||
|
||||
+104
-29
@@ -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
|
||||
|
||||
+160
-5
@@ -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 <script>', now: EARLY }));
|
||||
const saved = reserveSignup(db, reservation(shiftId, { name: 'Pat <script>', now: EARLY }));
|
||||
expect(saved.ok).toBe(true);
|
||||
if (!saved.ok) return;
|
||||
const reminderToken = issueReminderOffToken(SECRET, saved.signupId);
|
||||
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 });
|
||||
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
|
||||
|
||||
const reminders = db.prepare(`SELECT kind, status, subject, body_html, headers_json FROM outbox WHERE kind = 'reminder'`).all() as Array<{
|
||||
const reminders = db.prepare(`SELECT kind, status, subject, body_text, body_html, headers_json FROM outbox WHERE kind = 'reminder'`).all() as Array<{
|
||||
kind: string;
|
||||
status: string;
|
||||
subject: string;
|
||||
body_text: string;
|
||||
body_html: string;
|
||||
headers_json: string;
|
||||
}>;
|
||||
@@ -61,8 +67,16 @@ describe('reminder mail', () => {
|
||||
]);
|
||||
expect(reminders[0]?.body_html).toContain('Pat <script>');
|
||||
expect(reminders[0]?.body_html).not.toContain('<script>');
|
||||
expect(reminders[0]?.body_html).toContain('use the link in your confirmation email');
|
||||
expect(reminders[0]?.body_html).not.toContain('use the link in your confirmation email');
|
||||
expect(reminders[0]?.body_html).toContain(`href="http://127.0.0.1:3000/u/${reminderToken}"`);
|
||||
expect(reminders[0]?.body_html).toContain('>Cancel this signup</a>');
|
||||
expect(reminders[0]?.body_html).toContain('You confirm before the spot opens for someone else.');
|
||||
expect(reminders[0]?.body_html).not.toContain('/cancel');
|
||||
expect(reminders[0]?.body_text).toContain(`http://127.0.0.1:3000/u/${reminderToken}`);
|
||||
expect(reminders[0]?.body_text).toContain('You confirm before the spot opens for someone else.');
|
||||
const headers = JSON.parse(reminders[0]?.headers_json ?? '{}') as Record<string, string>;
|
||||
expect(headers['List-Unsubscribe']).toContain(`/u/${reminderToken}`);
|
||||
expect(headers['List-Unsubscribe']).not.toContain('/cancel');
|
||||
expect(headers['List-Unsubscribe']).toContain('mailto:volunteer@example.invalid?subject=Stop%20reminder%20emails');
|
||||
expect(headers['List-Unsubscribe-Post']).toBe('List-Unsubscribe=One-Click');
|
||||
expect(db.prepare(`SELECT kind, sent_at FROM reminders_sent`).get()).toEqual({ kind: '48h', sent_at: null });
|
||||
@@ -213,12 +227,15 @@ describe('reminder mail', () => {
|
||||
|
||||
const visit = await app.request(`/u/${token}`);
|
||||
expect(visit.status).toBe(200);
|
||||
expect(await visit.text()).toContain('Stop reminder emails');
|
||||
const visitHtml = await visit.text();
|
||||
expect(visitHtml).toContain('Stop reminder emails');
|
||||
expect(visitHtml).toContain('Cancel this signup');
|
||||
expect(visitHtml).toContain(`/u/${token}/cancel`);
|
||||
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 0, status: 'confirmed' });
|
||||
|
||||
const stopped = await app.request(`/u/${token}`, { method: 'POST' });
|
||||
expect(stopped.status).toBe(200);
|
||||
expect(await stopped.text()).toContain('Reminder emails for this signup are off.');
|
||||
expect(await stopped.text()).toContain('Reminder emails are off. This signup stays.');
|
||||
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 1, status: 'confirmed' });
|
||||
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'reminder' AND status = 'pending'`).get()).toBeUndefined();
|
||||
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'confirmation'`).get()).toEqual({ status: 'pending' });
|
||||
@@ -230,6 +247,128 @@ describe('reminder mail', () => {
|
||||
const missing = await app.request('/u/1.not-a-real-mac-value-here');
|
||||
expect(missing.status).toBe(404);
|
||||
expect(db.prepare(`SELECT reminders_off FROM signups`).get()).toEqual({ reminders_off: 1 });
|
||||
|
||||
const oneClick = await app.request(`/u/${token}`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ 'List-Unsubscribe': 'One-Click' }),
|
||||
});
|
||||
expect(oneClick.status).toBe(200);
|
||||
expect(db.prepare(`SELECT reminders_off, status FROM signups`).get()).toEqual({ reminders_off: 1, status: 'confirmed' });
|
||||
});
|
||||
|
||||
it('cancels from the reminder page after a confirmation, and keeps the signup link', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
bootstrapAdmin(db, 'coordinator@example.invalid', EARLY);
|
||||
const shiftId = insertShift(db, LATER_START, LATER_END);
|
||||
const saved = reserveSignup(db, reservation(shiftId, { now: EARLY, groupSize: 1 }));
|
||||
expect(saved.ok && saved.manageToken).toBeTruthy();
|
||||
if (!saved.ok || !saved.manageToken) return;
|
||||
queueDueReminders(db, MAIL, SECRET, NOW);
|
||||
const signupId = saved.signupId;
|
||||
const token = issueReminderOffToken(SECRET, signupId);
|
||||
|
||||
const confirm = await app.request(`/u/${token}/cancel`);
|
||||
expect(confirm.status).toBe(200);
|
||||
const confirmHtml = await confirm.text();
|
||||
expect(confirmHtml).toContain('Are you sure you want to cancel?');
|
||||
expect(confirmHtml).toContain('Cancel this signup to open the spot for someone else.');
|
||||
expect(confirmHtml).toContain('Pat Review');
|
||||
expect(confirmHtml).toContain('Sorting');
|
||||
expect(db.prepare(`SELECT status FROM signups`).get()).toEqual({ status: 'confirmed' });
|
||||
const cancelToken = /name="cancel_token" value="([^"]*)"/.exec(confirmHtml)?.[1] ?? '';
|
||||
expect(cancelToken).toBe(issueReminderCancelToken(SECRET, token));
|
||||
|
||||
const crossSite = await postReminderCancel(app, token, cancelToken, { origin: 'https://evil.example' });
|
||||
expect(crossSite.status).toBe(403);
|
||||
expect(await crossSite.text()).toContain('could not be sent from this page');
|
||||
const missingToken = await postReminderCancel(app, token, '');
|
||||
expect(missingToken.status).toBe(400);
|
||||
expect(await missingToken.text()).toContain('could not be confirmed');
|
||||
const oneClick = await app.request(`/u/${token}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ 'List-Unsubscribe': 'One-Click' }),
|
||||
});
|
||||
expect(oneClick.status).toBe(403);
|
||||
expect(db.prepare(`SELECT status, reminders_off FROM signups`).get()).toEqual({ status: 'confirmed', reminders_off: 0 });
|
||||
|
||||
const cancelled = await postReminderCancel(app, token, cancelToken);
|
||||
expect(cancelled.status).toBe(303);
|
||||
expect(cancelled.headers.get('location')).toBe(`/u/${token}`);
|
||||
const after = await app.request(`/u/${token}`);
|
||||
const afterHtml = await after.text();
|
||||
expect(after.status).toBe(200);
|
||||
expect(afterHtml).toContain('This signup is cancelled');
|
||||
expect(afterHtml).toContain('The spot is open for someone else.');
|
||||
expect(afterHtml).not.toContain('name="cancel_token"');
|
||||
expect(afterHtml).not.toContain('Stop reminder emails');
|
||||
expect(db.prepare(`SELECT status FROM signups`).get()).toEqual({ status: 'cancelled' });
|
||||
expect(db.prepare(`SELECT COALESCE(SUM(group_size), 0) AS n FROM signups WHERE status = 'confirmed'`).get()).toEqual({ n: 0 });
|
||||
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'confirmation'`).get()).toEqual({ status: 'cancelled' });
|
||||
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'reminder'`).get()).toEqual({
|
||||
status: 'cancelled',
|
||||
last_error: 'The signup was cancelled before this reminder was sent.',
|
||||
});
|
||||
const letter = db.prepare(`SELECT subject, body_text FROM outbox WHERE kind = 'cancelled'`).get() as { subject: string; body_text: string };
|
||||
expect(letter.subject).toBe('Your signup for Sorting is cancelled');
|
||||
expect(letter.body_text).toContain(`http://127.0.0.1:3000/u/${token}`);
|
||||
expect(letter.body_text).toContain('That link opens the cancelled signup.');
|
||||
expect(letter.body_text).not.toContain('/m/');
|
||||
expect(db.prepare(`SELECT subject FROM outbox WHERE kind = 'notice' ORDER BY id`).all()).toEqual([
|
||||
{ subject: 'Pat Review signed up for Sorting' },
|
||||
{ subject: "Pat Review's signup for Sorting was cancelled" },
|
||||
]);
|
||||
const manage = await app.request(`/m/${saved.manageToken}`);
|
||||
expect(manage.status).toBe(200);
|
||||
expect(await manage.text()).toContain('Cancelled');
|
||||
|
||||
const again = await postReminderCancel(app, token, cancelToken);
|
||||
expect(again.status).toBe(303);
|
||||
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'`).get()).toEqual({ n: 1 });
|
||||
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 2 });
|
||||
});
|
||||
|
||||
it('does not cancel a reminder signup after the shift has ended', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const shiftId = insertShift(db, LATER_START, LATER_END);
|
||||
const saved = reserveSignup(db, reservation(shiftId, { now: EARLY }));
|
||||
expect(saved.ok).toBe(true);
|
||||
if (!saved.ok) return;
|
||||
const token = issueReminderOffToken(SECRET, saved.signupId);
|
||||
db.prepare(`UPDATE shifts SET starts_at_utc = ?, ends_at_utc = ? WHERE id = ?`).run(
|
||||
'2026-10-14T15:00:00.000Z',
|
||||
'2026-10-14T17:00:00.000Z',
|
||||
shiftId,
|
||||
);
|
||||
|
||||
const confirm = await app.request(`/u/${token}/cancel`);
|
||||
expect(confirm.status).toBe(303);
|
||||
expect(confirm.headers.get('location')).toBe(`/u/${token}`);
|
||||
const page = await app.request(`/u/${token}`);
|
||||
const html = await page.text();
|
||||
expect(html).toContain('This shift has ended.');
|
||||
expect(html).not.toContain('/cancel');
|
||||
const posted = await postReminderCancel(app, token, issueReminderCancelToken(SECRET, token));
|
||||
expect(posted.status).toBe(400);
|
||||
expect(await posted.text()).toContain('This shift has ended.');
|
||||
expect(db.prepare(`SELECT status FROM signups`).get()).toEqual({ status: 'confirmed' });
|
||||
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'`).get()).toEqual({ n: 0 });
|
||||
});
|
||||
|
||||
it('names every spot when a reminder is for more than one person', () => {
|
||||
const letter = renderReminder({
|
||||
volunteerName: 'Pat',
|
||||
shift: { role: 'Sorting', eventTitle: 'Weekly pantry', location: 'Sioux Center, Iowa', whenLabel: 'Thursday, October 15, 2026, 9:00 AM to 12:00 PM CDT' },
|
||||
unsubscribeUrl: 'https://example.invalid/u/1.token',
|
||||
replyTo: 'volunteer@example.invalid',
|
||||
groupSize: 3,
|
||||
});
|
||||
expect(letter.text).toContain('open https://example.invalid/u/1.token');
|
||||
expect(letter.text).toContain('You confirm before these 3 spots open for someone else.');
|
||||
expect(letter.text).not.toContain('use the link in your confirmation email');
|
||||
expect(letter.html).toContain('href="https://example.invalid/u/1.token"');
|
||||
expect(letter.html).toContain('these 3 spots');
|
||||
});
|
||||
|
||||
it('turns reminders off from the private signup page and keeps the signup', async () => {
|
||||
@@ -323,6 +462,22 @@ function insertConfirmed(db: Awaited<ReturnType<typeof openDb>>, shiftId: number
|
||||
).run(shiftId, email, email, NOW, NOW, '2026-10-22T17:00:00.000Z');
|
||||
}
|
||||
|
||||
function postReminderCancel(
|
||||
app: ReturnType<typeof createApp>,
|
||||
token: string,
|
||||
cancelToken: string,
|
||||
options?: { origin?: string },
|
||||
) {
|
||||
return app.request(`/u/${token}/cancel`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
origin: options?.origin ?? ORIGIN,
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: new URLSearchParams({ cancel_token: cancelToken }),
|
||||
});
|
||||
}
|
||||
|
||||
function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): ReserveInput {
|
||||
return {
|
||||
shiftId,
|
||||
|
||||
Reference in new issue
Block a user