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
+714
-139
No files matched your search
@@ -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>
|
||||
|
||||
+161
-50
@@ -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 (
|
||||
<>
|
||||
|
||||
+148
-50
@@ -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, <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
|
||||
|
||||
Reference in new issue
Block a user