feat: email coordinators only for volunteer actions

A location change now sends one email per person and asks how many people that reaches before it is saved, without replacing their signup links.
This commit is contained in:
blake committed 2026-11-02 14:17:10 -06:00
1 parent a520352071
commit 77a9a0caff
12 files changed
+691 -50

No files matched your search

+2 -2
View File
@@ -76,11 +76,11 @@ An open shift has a signup form. It asks for one person. Another person can use
With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. SMTP2GO is the mail provider. Set `MAIL_DRIVER=smtp2go` and `SMTP2GO_API_KEY` to send through it. Postmark and SES remain available.
Each active coordinator gets an email when someone signs up, cancels, or changes a signup. Signing up includes a walk-in. A change is a switch, a move, or a new time, role, or place. Cancelling a shift sends one message for each person who was signed up. The message names the person, the email address, the phone number, and the shift, and it links to that shift. It does not include the private signup link. The same signup does not send a second copy of the same notice. A coordinator who has been removed, or whose sign-in address was replaced, does not receive a notice that is still waiting. Mail already accepted cannot be recalled.
Each active coordinator gets an email when a volunteer signs up, cancels, switches shifts, or changes how many people are coming. A walk-in, a roster move, a cancellation a coordinator records, and a change to the time, role, or place do not email coordinators. The message names the person, the email address, the phone number, and the shift, and it links to that shift. It does not include the private signup link. The same signup does not send a second copy of the same notice. A coordinator who has been removed, or whose sign-in address was replaced, does not receive a notice that is still waiting. Mail already accepted cannot be recalled.
Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. More administrators are added from **Administrators** after someone is signed in. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password.
After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling a shift marks each confirmed signup cancelled, queues a cancellation email, and takes that shift off the upcoming list. The shift stays stored, so a template does not add that date again. **Cancel selected**, on the event page, does this for each open shift that is checked. A shift that has already ended is left out of that batch. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued.
After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling a shift marks each confirmed signup cancelled, queues a cancellation email, and takes that shift off the upcoming list. The shift stays stored, so a template does not add that date again. **Cancel selected**, on the event page, does this for each open shift that is checked. A shift that has already ended is left out of that batch. A time or role change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued. A location change emails each person once, covering every shift of theirs that has not ended, and leaves those signup links in place. Saving shows how many people that email will reach before it is sent.
On an open shift, **Add a walk-in** records one person who is here. It takes one spot, uses the same person rule as the public form, and queues a confirmation email. The name is listed on the public sign-up page when that shift is posted there. Email and notes stay off that page. A full, cancelled, or ended shift does not take a walk-in.
+66
View File
@@ -0,0 +1,66 @@
-- foreign-keys: off
-- A location change uses outbox kind location: one letter per person, with no new private link.
-- Rebuilding outbox changes its CHECK list. reminders_sent references it, so foreign keys are off for this file.
CREATE TABLE outbox_next (
id INTEGER PRIMARY KEY,
dedupe_key TEXT NOT NULL UNIQUE,
signup_id INTEGER NULL REFERENCES signups (id) ON DELETE NO ACTION,
shift_id INTEGER NULL REFERENCES shifts (id) ON DELETE NO ACTION,
-- confirmation, changed, cancelled, reminder, magic_link, manage_recovery, notice, location
kind TEXT NOT NULL CHECK (
kind IN ('confirmation', 'changed', 'cancelled', 'reminder', 'magic_link', 'manage_recovery', 'notice', 'location')
),
-- Pending mail can contain raw manage or login links. Treat the row as sensitive.
to_email TEXT NOT NULL,
subject TEXT NOT NULL,
body_text TEXT NOT NULL,
body_html TEXT NOT NULL,
headers_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(headers_json)),
send_after TEXT NOT NULL CHECK (
send_after GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
),
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
status TEXT NOT NULL CHECK (
status IN ('pending', 'sending', 'sent', 'failed', 'cancelled', 'delivery_unknown')
),
provider_id TEXT NULL,
last_error TEXT NULL,
created_at TEXT NOT NULL CHECK (
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
),
claimed_at TEXT NULL CHECK (
claimed_at IS NULL
OR claimed_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
),
lease_expires_at TEXT NULL CHECK (
lease_expires_at IS NULL
OR lease_expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
),
-- sent_at means the provider accepted the message, not that the person received it.
sent_at TEXT NULL CHECK (
sent_at IS NULL
OR sent_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
),
delivery_unknown_at TEXT NULL CHECK (
delivery_unknown_at IS NULL
OR delivery_unknown_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
)
);
INSERT INTO outbox_next (
id, dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, provider_id, last_error, created_at,
claimed_at, lease_expires_at, sent_at, delivery_unknown_at
)
SELECT
id, dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, provider_id, last_error, created_at,
claimed_at, lease_expires_at, sent_at, delivery_unknown_at
FROM outbox;
DROP TABLE outbox;
ALTER TABLE outbox_next RENAME TO outbox;
CREATE INDEX outbox_by_status_send_after ON outbox (status, send_after);
+52 -4
View File
@@ -19,6 +19,7 @@ import {
cancelShift,
cancelShifts,
cancelSignupAsCoordinator,
countLocationRecipients,
createEvent,
createShift,
createTemplate,
@@ -49,6 +50,7 @@ import {
AdminHome,
EventEditor,
eventRemovalPrompt,
locationChangePrompt,
LoginConfirmPage,
LoginPage,
MessagePage,
@@ -762,6 +764,7 @@ function showEvent(
eventId = idFrom(c),
scheduleNote?: string,
notice?: string,
values?: EventValues,
) {
const session = requireSession(c, services);
if (session instanceof Response) return session;
@@ -776,14 +779,16 @@ function showEvent(
heading={event.title}
action={appPath(services.config, `/admin/events/${event.id}`)}
csrf={session.csrf}
values={{
values={
values ?? {
title: event.title,
slug: event.slug,
description: event.description,
location: event.location,
tz: event.tz,
published: event.published,
}}
}
}
event={event}
error={error}
notice={notice ?? knownNotice(c.req.query('notice'))}
@@ -803,10 +808,39 @@ async function submitEvent(c: Context, services: AdminServices): Promise<Respons
const values = eventValuesFrom(session.body, services.config.defaultTimeZone);
const parsed = parseEvent(values);
if (!parsed.ok) return showEventEditor(c, services, session, id, values, parsed.error);
const current = services.db.prepare('SELECT location AS location FROM events WHERE id = ?').get(id) as { location: string } | undefined;
if (!current) return missing(c, services);
if (current.location !== parsed.value.location && textField(session.body, 'confirm_location') !== 'yes') {
const people = countLocationRecipients(services.db, id, services.now());
return showEvent(
c,
services,
undefined,
200,
{
action: appPath(services.config, `/admin/events/${id}`),
...locationChangePrompt(people, parsed.value.location),
fields: locationConfirmFields(parsed.value),
},
id,
undefined,
undefined,
values,
);
}
try {
const saved = updateEvent(services.db, session.coordinatorId, id, parsed.value, services.now(), mailIdentity(services.db, services.config));
const saved = updateEvent(
services.db,
session.coordinatorId,
id,
parsed.value,
services.now(),
mailIdentity(services.db, services.config),
services.config.sessionSecret,
);
if (!saved.ok) return showEventEditor(c, services, session, id, values, saved.error);
return c.redirect(appPath(services.config, `/admin/events/${id}?notice=saved`), 303);
const notice = saved.mailed > 0 ? 'saved-location' : 'saved';
return c.redirect(appPath(services.config, `/admin/events/${id}?notice=${notice}`), 303);
} catch (err) {
return saveFailed(c, services, session, err);
}
@@ -1606,6 +1640,19 @@ function localToday(tz: string, now: string): string {
return Temporal.Instant.from(now).toZonedDateTimeISO(tz).toPlainDate().toString();
}
function locationConfirmFields(values: EventValues): Record<string, string> {
const fields: Record<string, string> = {
title: values.title,
slug: values.slug,
description: values.description,
location: values.location,
tz: values.tz,
confirm_location: 'yes',
};
if (values.published) fields.published = 'yes';
return fields;
}
function blankEvent(tz: string): EventValues {
return { title: '', slug: '', description: '', location: '', tz, published: false };
}
@@ -1614,6 +1661,7 @@ function knownNotice(value: string | undefined): string | undefined {
if (!value) return undefined;
if (
value === 'saved' ||
value === 'saved-location' ||
value === 'signup-cancelled' ||
value === 'already-cancelled' ||
value === 'shift-cancelled' ||
+27 -2
View File
@@ -38,6 +38,7 @@ export type ConfirmPrompt = {
note?: string;
submit?: string;
error?: string;
fields?: Record<string, string>;
};
const SHIFT_DELETE_BODY = 'This deletes the shift. It does not send email.';
@@ -103,6 +104,24 @@ export function signupCancelPrompt(signup: { name: string | null; status: string
};
}
export function locationChangePrompt(people: number, location: string): Omit<ConfirmPrompt, 'action'> {
const place = location.trim();
const count = people === 1 ? '1 person' : `${people} people`;
const body =
people === 0
? 'No one is signed up for a shift that has not ended. This does not send email.'
: people === 1
? 'This emails 1 person about the new location. Their signup link stays the same.'
: `This emails ${people} people about the new location. Each person gets one email. Their signup links stay the same.`;
return {
title: 'Change the location',
detail: count,
note: place ? `New location: ${place}` : 'The address will be removed.',
body,
submit: people === 0 ? 'Save location' : 'Save and email',
};
}
export function shiftCancelPrompt(shift: { role: string; whenLabel?: string; cancelled: boolean; confirmed: number }): Omit<ConfirmPrompt, 'action'> {
if (shift.cancelled) {
return { title: `Cancel ${shift.role}`, detail: whenDetail(shift.whenLabel), body: SHIFT_ALREADY };
@@ -897,7 +916,7 @@ export function EventEditor(props: {
<strong>Event details</strong>
<span>{event.location.trim() || 'No address yet'}</span>
</p>
<details class="event-edit" open={props.error ? true : undefined}>
<details class="event-edit" open={props.error || props.confirm ? true : undefined}>
<summary>
Edit details
<span class="edit-chevron" aria-hidden="true" />
@@ -1374,6 +1393,11 @@ function ConfirmDialog(props: { config: AppConfig; csrf: string; prompt?: Confir
</form>
<form method="post" id="confirm-form" class="confirm-form" action={prompt?.action ?? ''} data-keep-place="">
<input type="hidden" name="csrf" value={props.csrf} />
{prompt?.fields
? Object.entries(prompt.fields).map(([name, value]) => (
<input type="hidden" name={name} value={value} data-picked="" />
))
: null}
<h2 id="confirm-title">{prompt?.title ?? 'Remove'}</h2>
<p class="confirm-detail" id="confirm-detail" hidden={prompt?.detail ? undefined : true}>
{prompt?.detail ?? ''}
@@ -1787,7 +1811,7 @@ function EventForm(props: {
<label>
Location
<input name="location" type="text" value={props.values.location} />
<span class="hint">Changing the location emails people on shifts that have not ended.</span>
<span class="hint">Changing the location emails each person once, for every shift that has not ended. Signup links stay the same. Saving shows how many people that reaches.</span>
</label>
)}
<label class="check">
@@ -2142,6 +2166,7 @@ function spotLabel(shift: Pick<AdminShiftSummary, 'capacity' | 'occupied' | 'can
const NOTICES: Record<string, string> = {
saved: 'Saved.',
'saved-location': 'Saved. One email is queued for each person on a shift that has not ended. Their signup links still work.',
'signup-cancelled': 'The signup is cancelled. A cancellation email is queued.',
'already-cancelled': 'That signup was already cancelled.',
'shift-cancelled': 'The shift is cancelled and off this list. Cancellation emails are queued.',
+106 -27
View File
@@ -3,7 +3,8 @@ import { Temporal } from '@js-temporal/polyfill';
import type Database from 'better-sqlite3';
import type { EventInput, ShiftInput, TemplateInput } from './forms.js';
import { writeAudit } from '../auth/audit.js';
import { cancelPendingConfirmations, cancelPendingReminders, queueCancellation, queueChanged, queueCoordinatorNotices } from '../mail/queue.js';
import { cancelPendingConfirmations, cancelPendingReminders, queueCancellation, queueChanged, queueCoordinatorNotices, queueLocationChange, rewritePendingPlace } from '../mail/queue.js';
import { refreshPendingReminders } from '../reminders.js';
import type { MailShift } from '../mail/templates.js';
import type { MailIdentity } from '../mail/types.js';
import { confirmedPersonOnShift, confirmedPersonShiftIds, reserveSignup, type ReserveInput, type ReserveResult } from '../signup.js';
@@ -361,6 +362,7 @@ export function updateEvent(
input: EventInput,
now: string,
mail: MailIdentity,
reminderSecret?: string,
): SaveResult {
const zone = timeZone(input.tz);
if (!zone.ok) return zone;
@@ -377,10 +379,7 @@ export function updateEvent(
).run(input.slug, input.title, input.description, input.location, zone.tz, input.published ? 1 : 0, id);
let mailed = 0;
if (existing.location !== input.location) {
const shifts = db
.prepare('SELECT id AS id FROM shifts WHERE event_id = ? AND cancelled = 0 AND ends_at_utc > ?')
.all(id, now) as Array<{ id: number }>;
for (const shift of shifts) mailed += bumpAndNotify(db, shift.id, now, mail);
mailed = notifyLocationChange(db, id, existing.location, input.location, now, mail, reminderSecret);
}
writeAudit(db, coordinatorId, 'event.update', { eventId: id, published: input.published ? 1 : 0, mailed }, now);
return { ok: true as const, id, mailed };
@@ -1498,9 +1497,10 @@ function relocate(
},
options.audience === 'volunteer' ? 'switch' : 'move',
);
if (options.audience === 'volunteer') {
const previous = mailShift(db, source.shift_id);
queueCoordinatorNotices(db, {
action: options.audience === 'volunteer' ? 'switch' : 'move',
action: 'switch',
signupId: newSignupId,
shiftId: destination.id,
shiftVersion: shift.version,
@@ -1512,6 +1512,7 @@ function relocate(
mail,
now,
});
}
writeAudit(db, options.coordinatorId, options.action, {
signupId: source.id,
fromShiftId: source.shift_id,
@@ -1672,18 +1673,6 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
mail,
now,
});
queueCoordinatorNotices(db, {
action: 'change',
signupId: person.id,
shiftId: person.shift_id,
shiftVersion: shift.version,
volunteerName: person.name,
volunteerEmail: person.email_norm,
groupSize: Number(person.group_size),
shift: shift.facts,
mail,
now,
});
mailed += 1;
}
return mailed;
@@ -1731,19 +1720,109 @@ function cancelConfirmedPerson(db: Database.Database, person: PersonRow, now: st
now,
linkNote: REPLACED_LINK,
});
queueCoordinatorNotices(db, {
action: 'cancel',
signupId: person.id,
shiftId: person.shift_id,
shiftVersion: shift.version,
return issued.token;
}
/** People with a confirmed signup on a shift that has not ended. The same person on several weeks counts once. */
export function countLocationRecipients(db: Database.Database, eventId: number, now: string): number {
return locationRecipients(db, eventId, now).length;
}
function notifyLocationChange(
db: Database.Database,
eventId: number,
previousLocation: string,
nextLocation: string,
now: string,
mail: MailIdentity,
reminderSecret: string | undefined,
): number {
const people = locationRecipients(db, eventId, now);
const signupIds = people.flatMap((person) => person.signupIds);
rewritePendingPlace(db, signupIds, previousLocation, nextLocation);
if (reminderSecret) refreshPendingReminders(db, signupIds, mail, reminderSecret);
for (const person of people) {
const firstSignup = person.signupIds[0];
if (!firstSignup) continue;
queueLocationChange(db, {
eventId,
signupIds: person.signupIds,
signupId: firstSignup,
shiftId: person.shiftId,
volunteerName: person.name,
volunteerEmail: person.email_norm,
groupSize: Number(person.group_size),
shift: shift.facts,
volunteerEmail: person.email,
eventTitle: person.eventTitle,
location: nextLocation,
shifts: person.shifts,
mail,
now,
});
return issued.token;
}
return people.length;
}
type LocationRecipient = {
name: string;
email: string;
eventTitle: string;
signupIds: number[];
shiftId: number;
shifts: Array<{ role: string; whenLabel: string }>;
};
function locationRecipients(db: Database.Database, eventId: number, now: string): LocationRecipient[] {
const rows = db
.prepare(
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.shift_id AS shift_id,
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.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 s.event_id = ?
AND s.cancelled = 0
AND s.ends_at_utc > ?
AND su.status = 'confirmed'
AND su.anonymized_at IS NULL
AND su.name IS NOT NULL
AND su.email_norm IS NOT NULL
ORDER BY s.starts_at_utc, s.id, su.id`,
)
.all(eventId, now) as Array<{
id: number;
name: string;
email_norm: string;
shift_id: number;
role: string;
starts_at_utc: string;
ends_at_utc: string;
title: string;
tz: string;
}>;
const groups = new Map<string, LocationRecipient>();
for (const row of rows) {
const key = `${row.email_norm}\0${row.name.trim().toLowerCase()}`;
const start = formatInstantInZone(row.starts_at_utc, row.tz);
const end = formatInstantInZone(row.ends_at_utc, row.tz);
let group = groups.get(key);
if (!group) {
group = {
name: row.name,
email: row.email_norm,
eventTitle: row.title,
signupIds: [],
shiftId: row.shift_id,
shifts: [],
};
groups.set(key, group);
}
group.signupIds.push(row.id);
group.shifts.push({
role: row.role,
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
});
}
return [...groups.values()];
}
function replaceManageToken(db: Database.Database, signupId: number, endsAtUtc: string, now: string): string | null {
+31 -2
View File
@@ -22,7 +22,7 @@ type ClaimedRow = {
};
/**
* Claims due confirmation, change, cancellation, reminder, sign-in, and coordinator notice mail, then sends outside the database transaction.
* Claims due confirmation, change, cancellation, reminder, sign-in, coordinator notice, and location mail, then sends outside the database transaction.
* An expired sending lease becomes delivery_unknown and is not sent again.
* sent_at means the provider accepted the message.
*/
@@ -72,7 +72,7 @@ function claimNext(db: Database.Database, now: string): ClaimedRow | null {
.prepare(
`SELECT id AS id
FROM outbox
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link', 'notice')
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link', 'notice', 'location')
ORDER BY id
LIMIT 1`,
)
@@ -98,6 +98,7 @@ function claimNext(db: Database.Database, now: string): ClaimedRow | null {
function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
if (row.kind === 'magic_link') return magicLinkReason(db, row, now);
if (row.kind === 'notice') return noticeReason(db, row);
if (row.kind === 'location') return locationReason(db, row, now);
if (row.signup_id === null) return 'The signup is no longer available.';
const signup = db
.prepare(
@@ -164,6 +165,34 @@ function magicLinkReason(db: Database.Database, row: ClaimedRow, now: string): s
return null;
}
function locationReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
const ids = locationSignupIds(row.dedupe_key);
if (ids.length === 0) return 'The signup is no longer available.';
const marks = ids.map(() => '?').join(', ');
const left = db
.prepare(
`SELECT COUNT(*) AS n
FROM signups su
JOIN shifts s ON s.id = su.shift_id
WHERE su.id IN (${marks})
AND su.status = 'confirmed'
AND su.anonymized_at IS NULL
AND su.name IS NOT NULL
AND su.email_norm IS NOT NULL
AND s.cancelled = 0
AND s.ends_at_utc > ?`,
)
.get(...ids, now) as { n: number };
if (Number(left.n) === 0) return 'The signup is no longer available.';
return null;
}
function locationSignupIds(dedupeKey: string): number[] {
const match = /:s([1-9][0-9]*(?:\.[1-9][0-9]*)*)$/.exec(dedupeKey);
if (!match?.[1]) return [];
return match[1].split('.').map((value) => Number(value)).filter((id) => Number.isSafeInteger(id) && id > 0);
}
function reminderReason(
row: ClaimedRow,
signup: { status: string; reminders_off: number; shift_cancelled: number; version: number; starts_at_utc: string; token_expires_at: string | null },
+102
View File
@@ -1,10 +1,13 @@
import { createHash } from 'node:crypto';
import type Database from 'better-sqlite3';
import { absoluteUrl } from '../url.js';
import { escapeHtml } from './html.js';
import {
renderCancellation,
renderChanged,
renderConfirmation,
renderCoordinatorNotice,
renderLocationChange,
renderMagicLink,
renderMoved,
renderSwitched,
@@ -189,6 +192,105 @@ export function cancelPendingReminders(
).run(reason, signupId);
}
/**
* One location letter for every upcoming shift this person has on the event.
* A newer location letter for the same person replaces one that is still waiting.
* The private signup link is not included.
*/
export function queueLocationChange(
db: Database.Database,
input: {
eventId: number;
signupIds: number[];
signupId: number;
shiftId: number;
volunteerName: string;
volunteerEmail: string;
eventTitle: string;
location: string;
shifts: Array<{ role: string; whenLabel: string }>;
mail: MailIdentity;
now: string;
},
): void {
const ids = [...new Set(input.signupIds)].filter((id) => Number.isSafeInteger(id) && id > 0).sort((left, right) => left - right);
if (ids.length === 0) return;
const person = sha256(`${input.volunteerEmail}\0${input.volunteerName.trim().toLowerCase()}`).slice(0, 16);
const place = sha256(input.location).slice(0, 12);
const dedupe = `location:e${input.eventId}:${person}:${place}:${input.now}:s${ids.join('.')}`;
const queued = db.prepare('SELECT id AS id FROM outbox WHERE dedupe_key = ?').get(dedupe);
if (queued) return;
db.prepare(
`UPDATE outbox
SET status = 'cancelled', last_error = ?
WHERE kind = 'location' AND status = 'pending' AND to_email = ? AND dedupe_key LIKE ?`,
).run('A newer location email replaced this message.', input.volunteerEmail, `location:e${input.eventId}:${person}:%`);
const rendered = renderLocationChange({
volunteerName: input.volunteerName,
eventTitle: input.eventTitle,
location: input.location,
shifts: input.shifts,
replyTo: input.mail.replyTo,
});
db.prepare(
`INSERT INTO outbox (
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
headers_json, send_after, attempts, status, created_at
) VALUES (?, ?, ?, 'location', ?, ?, ?, ?, ?, ?, 0, 'pending', ?)`,
).run(
dedupe,
input.signupId,
input.shiftId,
input.volunteerEmail,
rendered.subject,
rendered.text,
rendered.html,
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
input.now,
input.now,
);
}
/** Pending letters still say the previous address. The signup link in each letter stays as it is. */
export function rewritePendingPlace(db: Database.Database, signupIds: number[], previous: string, next: string): void {
const from = previous.trim();
const to = next.trim();
const ids = [...new Set(signupIds)].filter((id) => Number.isSafeInteger(id) && id > 0);
if (!from || from === to || ids.length === 0) return;
const marks = ids.map(() => '?').join(', ');
const rows = db
.prepare(
`SELECT id AS id, body_text AS body_text, body_html AS body_html
FROM outbox
WHERE status = 'pending' AND kind IN ('confirmation', 'changed', 'cancelled') AND signup_id IN (${marks})`,
)
.all(...ids) as Array<{ id: number; body_text: string; body_html: string }>;
const update = db.prepare('UPDATE outbox SET body_text = ?, body_html = ? WHERE id = ? AND status = ?');
for (const row of rows) {
const text = replacePlaceLine(row.body_text, from, to);
const html = replacePlaceHtml(row.body_html, from, to);
if (text === row.body_text && html === row.body_html) continue;
update.run(text, html, row.id, 'pending');
}
}
function replacePlaceLine(text: string, from: string, to: string): string {
return text
.split('\n')
.flatMap((line) => (line === from ? (to ? [to] : []) : [line]))
.join('\n');
}
function replacePlaceHtml(html: string, from: string, to: string): string {
const old = `<br>${escapeHtml(from)}</p>`;
const next = to ? `<br>${escapeHtml(to)}</p>` : '</p>';
return html.replaceAll(old, next);
}
function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
function queue(
db: Database.Database,
kind: 'confirmation' | 'cancelled' | 'changed',
+46
View File
@@ -96,6 +96,52 @@ export function renderSwitched(input: {
return changedLetter(input, `Your signup was switched to ${role}`, 'You switched this signup to a different shift.');
}
/** One letter for every upcoming shift at a new place. It does not include a private signup link. */
export function renderLocationChange(input: {
volunteerName: string;
eventTitle: string;
location: string;
shifts: Array<{ role: string; whenLabel: string }>;
replyTo: string;
}): RenderedMail {
const name = singleLine(input.volunteerName);
const eventTitle = singleLine(input.eventTitle);
const place = singleLine(input.location);
const subject = `The location for ${eventTitle} has changed`;
const hello = place
? `The location for ${eventTitle} is now ${place}. This applies to the shifts below. Your signup links still work.`
: `The address for ${eventTitle} was removed. This applies to the shifts below. Your signup links still work.`;
const shifts = input.shifts.map((shift) => `${singleLine(shift.role)}: ${singleLine(shift.whenLabel)}`);
const greeting = `Hello ${name},`;
const lines = [
greeting,
'',
hello,
'',
...shifts,
'',
`Replies go to ${input.replyTo}.`,
'',
'Hope Food Pantry',
];
const items = shifts.map((line) => `<li>${escapeHtml(line)}</li>`).join('');
const html = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${escapeHtml(subject)}</title>
</head>
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
<p>${escapeHtml(greeting)}</p>
<p>${escapeHtml(hello)}</p>
<ul>${items}</ul>
<p>Replies go to ${escapeHtml(input.replyTo)}.</p>
<p>Hope Food Pantry</p>
</body>
</html>`;
return { subject, text: lines.join('\n'), html };
}
function changedLetter(
input: { volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string; groupSize?: number },
subject: string,
+56
View File
@@ -206,6 +206,62 @@ export function readReminderOffToken(secret: string, token: string): number | nu
return id;
}
/** A location change rewrites a reminder that is still waiting so it names the new place. */
export function refreshPendingReminders(
db: Database.Database,
signupIds: number[],
mail: MailIdentity,
secret: string,
): void {
const ids = [...new Set(signupIds)].filter((id) => Number.isSafeInteger(id) && id > 0);
if (ids.length === 0) return;
const marks = ids.map(() => '?').join(', ');
const rows = db
.prepare(
`SELECT o.id AS outbox_id, su.id AS id, su.name AS name, su.group_size AS group_size,
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 outbox o
JOIN signups su ON su.id = o.signup_id
JOIN shifts s ON s.id = su.shift_id
JOIN events e ON e.id = s.event_id
WHERE o.kind = 'reminder' AND o.status = 'pending' AND o.signup_id IN (${marks})
AND su.name IS NOT NULL AND su.anonymized_at IS NULL`,
)
.all(...ids) as Array<{
outbox_id: number;
id: number;
name: string;
group_size: number;
role: string;
starts_at_utc: string;
ends_at_utc: string;
title: string;
location: string;
tz: string;
}>;
const update = db.prepare(
`UPDATE outbox SET subject = ?, body_text = ?, body_html = ? WHERE id = ? AND kind = 'reminder' AND status = 'pending'`,
);
for (const row of rows) {
const start = formatInstantInZone(row.starts_at_utc, row.tz);
const end = formatInstantInZone(row.ends_at_utc, row.tz);
const rendered = renderReminder({
volunteerName: row.name,
shift: {
role: row.role,
eventTitle: row.title,
location: row.location,
whenLabel: `${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}`,
},
unsubscribeUrl: absoluteUrl(mail, `/u/${issueReminderOffToken(secret, row.id)}`),
replyTo: mail.replyTo,
groupSize: Number(row.group_size),
});
update.run(rendered.subject, rendered.text, rendered.html, row.outbox_id);
}
}
/** The later of the signup and the current shift version. A move starts a new signup. */
function reminderAnchor(createdAt: string, versionAt: string | null): Temporal.Instant {
const signedUp = Temporal.Instant.from(createdAt);
+2
View File
@@ -294,6 +294,7 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
mail: input.mail,
now: input.now,
});
if (input.audience !== 'coordinator') {
queueCoordinatorNotices(db, {
action: 'signup',
signupId,
@@ -306,6 +307,7 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
mail: input.mail,
now: input.now,
});
}
rememberSignupContact(db, { name: input.name, email: emailNorm, phone: input.phone }, input.now);
input.onReserved?.(signupId);
return { ok: true, signupId, manageToken, replay: false };
+72
View File
@@ -773,6 +773,78 @@ describe('coordinator screens', () => {
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(3);
});
it('shows how many people a location change emails before saving it', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
const created = await postForm(app, '/admin/events', cookie, {
title: 'Soup Night',
slug: 'soup-night',
description: 'Bring a spoon.',
location: 'Sioux Center, Iowa',
tz: 'America/Chicago',
published: 'yes',
});
const eventId = Number(/\/admin\/events\/(\d+)/.exec(created.headers.get('location') ?? '')?.[1]);
const shift = await postForm(app, `/admin/events/${eventId}/shifts`, cookie, {
role: 'Ladle',
date: '2026-10-15',
start: '09:00',
end: '12:00',
capacity: '4',
});
const shiftId = Number(/\/admin\/shifts\/(\d+)/.exec(shift.headers.get('location') ?? '')?.[1]);
const fields = {
title: 'Soup Night',
slug: 'soup-night',
description: 'Bring a spoon.',
tz: 'America/Chicago',
published: 'yes',
};
const empty = await postForm(app, `/admin/events/${eventId}`, cookie, { ...fields, location: 'Sioux Center, IA' });
expect(empty.status).toBe(200);
const emptyHtml = await empty.text();
expect(emptyHtml).toContain('No one is signed up for a shift that has not ended.');
expect(emptyHtml).toContain('0 people');
expect(emptyHtml).toContain('Save location');
expect(db.prepare('SELECT location AS location FROM events WHERE id = ?').get(eventId)).toEqual({ location: 'Sioux Center, Iowa' });
const savedEmpty = await postForm(app, `/admin/events/${eventId}`, cookie, {
...fields,
location: 'Sioux Center, IA',
confirm_location: 'yes',
});
expect(savedEmpty.status).toBe(303);
expect(savedEmpty.headers.get('location')).toBe(`/admin/events/${eventId}?notice=saved`);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'location'")).toBe(0);
const person = reserve(db, shiftId, 'Pat Example', 'pat@example.invalid', 'pat-location');
const hash = db.prepare('SELECT manage_token_hash AS hash FROM signups').get();
const preview = await postForm(app, `/admin/events/${eventId}`, cookie, { ...fields, location: '409 1st Ave NE' });
expect(preview.status).toBe(200);
const previewHtml = await preview.text();
expect(previewHtml).toContain('1 person');
expect(previewHtml).toContain('This emails 1 person about the new location.');
expect(previewHtml).toContain('Save and email');
expect(previewHtml).toContain('name="confirm_location"');
expect(db.prepare('SELECT location AS location FROM events WHERE id = ?').get(eventId)).toEqual({ location: 'Sioux Center, IA' });
const saved = await postForm(app, `/admin/events/${eventId}`, cookie, {
...fields,
location: '409 1st Ave NE',
confirm_location: 'yes',
});
expect(saved.status).toBe(303);
expect(saved.headers.get('location')).toBe(`/admin/events/${eventId}?notice=saved-location`);
expect(db.prepare('SELECT location AS location FROM events WHERE id = ?').get(eventId)).toEqual({ location: '409 1st Ave NE' });
expect(db.prepare('SELECT manage_token_hash AS hash FROM signups').get()).toEqual(hash);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'location' AND to_email = 'pat@example.invalid'")).toBe(1);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice' AND subject LIKE '%location%'")).toBe(0);
const page = await (await app.request(`/admin/events/${eventId}?notice=saved-location`, { headers: { cookie } })).text();
expect(page).toContain('One email is queued for each person');
expect(readManageSignup(db, person.manageToken ?? '', NOW)?.status).toBe('confirmed');
});
it('treats an expired session as signed out', async () => {
const { app, db } = await buildApp();
const cookie = await signIn(app, db);
+129 -13
View File
@@ -2,7 +2,8 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { moveSignup, switchSignup, updateShift } from '../src/admin/store.js';
import { addWalkIn, cancelShift, moveSignup, switchSignup, updateEvent, updateShift } from '../src/admin/store.js';
import { queueDueReminders } from '../src/reminders.js';
import { deactivateAdmin } from '../src/admins.js';
import { recoverCoordinator } from '../src/auth/recover.js';
import { loadConfig } from '../src/config.js';
@@ -92,7 +93,7 @@ describe('coordinator roster notices', () => {
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 2 });
});
it('tells coordinators when a signup is switched, moved, or the shift changes', async () => {
it('tells coordinators when a volunteer switches, and stays quiet when a coordinator moves or edits a shift', async () => {
const { db, eventId, shiftId } = await buildDb();
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
const other = insertShift(db, eventId, 'Distribution');
@@ -110,9 +111,8 @@ describe('coordinator roster notices', () => {
if (!movedSource.ok) throw new Error('Move signup was not saved.');
const moved = moveSignup(db, ada, movedSource.signupId, other, 'move-op', NOW, MAIL);
expect(moved.ok).toBe(true);
const moveNotice = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'notice' AND subject = 'Sam Example was moved to Distribution'`).get() as { body_text: string };
expect(moveNotice.body_text).toContain('was moved from Sorting (');
expect(moveNotice.body_text).toContain('to Distribution');
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice' AND subject = 'Sam Example was moved to Distribution'`).get()).toEqual({ n: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND to_email = 'sam@example.invalid'`).get()).toEqual({ n: 1 });
const changed = updateShift(db, ada, other, {
role: 'Packing',
@@ -122,11 +122,8 @@ describe('coordinator roster notices', () => {
capacity: 4,
}, NOW, MAIL);
expect(changed.ok).toBe(true);
const changeNotices = db.prepare(`SELECT subject AS subject FROM outbox WHERE kind = 'notice' AND subject LIKE '%shift changed' ORDER BY subject`).all();
expect(changeNotices).toEqual([
{ subject: "Pat Review's Packing shift changed" },
{ subject: "Sam Example's Packing shift changed" },
]);
expect(db.prepare(`SELECT subject AS subject FROM outbox WHERE kind = 'notice' AND subject LIKE '%shift changed'`).all()).toEqual([]);
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND subject LIKE 'Your Packing shift has changed'`).get()).toEqual({ n: 2 });
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'notice' AND subject = 'Pat Review signed up for Sorting'`).get()).toEqual({
status: 'pending',
});
@@ -218,6 +215,119 @@ describe('coordinator roster notices', () => {
});
});
it('does not email a coordinator about a walk-in or a shift they cancel', async () => {
const { db, shiftId } = await buildDb();
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
db.prepare('UPDATE shifts SET capacity = 6 WHERE id = ?').run(shiftId);
const added = addWalkIn(db, ada, {
shiftId,
name: 'Pat Review',
email: 'pat.review@example.invalid',
phone: '712-555-0100',
notes: null,
operationId: 'walk-in',
now: NOW,
mail: MAIL,
});
expect(added.ok).toBe(true);
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'pat.review@example.invalid'`).get()).toEqual({ n: 1 });
for (let index = 0; index < 5; index += 1) {
const saved = reserveSignup(db, reservation(shiftId, {
name: `Person ${index}`,
email: `person${index}@example.invalid`,
operationId: `person-${index}`,
}));
expect(saved.ok).toBe(true);
}
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 5 });
const cancelled = cancelShift(db, ada, shiftId, NOW, MAIL);
expect(cancelled).toEqual({ ok: true, already: false, mailed: 6 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 5 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled' AND status = 'pending'`).get()).toEqual({ n: 6 });
});
it('emails each person once when the location changes and leaves private links in place', async () => {
const { db, eventId, shiftId } = await buildDb();
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
const second = insertShift(db, eventId, 'Sorting', '2026-10-22T14:00:00.000Z', '2026-10-22T17:00:00.000Z');
const third = insertShift(db, eventId, 'Sorting', '2026-10-29T14:00:00.000Z', '2026-10-29T17:00:00.000Z');
const people = [
['Pat Review', 'pat@example.invalid'],
['Sam Example', 'sam@example.invalid'],
['Kim Example', 'kim@example.invalid'],
] as const;
const tokens = new Map<string, string>();
for (const shift of [shiftId, second, third]) {
for (const [name, email] of people) {
const saved = reserveSignup(db, reservation(shift, { name, email, operationId: `${email}-${shift}` }));
expect(saved.ok).toBe(true);
if (saved.ok && saved.manageToken && shift === shiftId) tokens.set(email, saved.manageToken);
}
}
const hashes = db.prepare('SELECT id, manage_token_hash AS hash FROM signups ORDER BY id').all();
expect(queueDueReminders(db, MAIL, 'location-secret', '2026-10-15T12:00:00.000Z')).toEqual({ queued: 3, suppressed: 0 });
const noticesBefore = db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get();
const saved = updateEvent(db, ada, eventId, {
title: 'Weekly pantry',
slug: 'weekly-pantry',
description: 'Bring a hat.',
location: 'Sioux Center, IA',
tz: 'America/Chicago',
published: true,
}, '2026-10-15T12:00:00.000Z', MAIL, 'location-secret');
expect(saved).toEqual({ ok: true, id: eventId, mailed: 3 });
expect(db.prepare('SELECT id, manage_token_hash AS hash FROM signups ORDER BY id').all()).toEqual(hashes);
expect(db.prepare('SELECT version AS version FROM shifts ORDER BY id').all()).toEqual([
{ version: 1 },
{ version: 1 },
{ version: 1 },
]);
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual(noticesBefore);
const letters = db.prepare(`SELECT to_email, body_text, body_html FROM outbox WHERE kind = 'location' ORDER BY to_email`).all() as Array<{
to_email: string;
body_text: string;
body_html: string;
}>;
expect(letters.map((row) => row.to_email)).toEqual(['kim@example.invalid', 'pat@example.invalid', 'sam@example.invalid']);
const pat = letters.find((row) => row.to_email === 'pat@example.invalid');
if (!pat) throw new Error('Pat did not get a location email.');
expect(pat.body_text).toContain('The location for Weekly pantry is now Sioux Center, IA.');
expect(pat.body_text).toContain('October 15, 2026');
expect(pat.body_text).toContain('October 22, 2026');
expect(pat.body_text).toContain('October 29, 2026');
expect(pat.body_text).not.toContain('/m/');
expect(pat.body_html).not.toContain('/m/');
expect(pat.body_text.match(/October/g)).toHaveLength(3);
const confirmation = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'confirmation' AND to_email = 'pat@example.invalid' ORDER BY id LIMIT 1`).get() as { body_text: string };
expect(confirmation.body_text).toContain('Sioux Center, IA');
expect(confirmation.body_text).toContain(`/m/${tokens.get('pat@example.invalid')}`);
expect(confirmation.body_text).not.toContain('Sioux Center, Iowa');
const reminder = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'reminder' AND status = 'pending' AND to_email = 'pat@example.invalid'`).get() as { body_text: string };
expect(reminder.body_text).toContain('Sioux Center, IA');
expect(reminder.body_text).not.toContain('Sioux Center, Iowa');
const again = updateEvent(db, ada, eventId, {
title: 'Weekly pantry',
slug: 'weekly-pantry',
description: 'Bring a hat.',
location: '409 1st Ave NE',
tz: 'America/Chicago',
published: true,
}, '2026-10-15T12:30:00.000Z', MAIL, 'location-secret');
expect(again).toEqual({ ok: true, id: eventId, mailed: 3 });
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'location' AND body_text LIKE '%Sioux Center, IA%' LIMIT 1`).get()).toEqual({
status: 'cancelled',
last_error: 'A newer location email replaced this message.',
});
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'location' AND status = 'pending'`).get()).toEqual({ n: 3 });
expect(db.prepare('SELECT id, manage_token_hash AS hash FROM signups ORDER BY id').all()).toEqual(hashes);
});
it('stops a waiting notice when an administrator is removed or the sign-in address is replaced', async () => {
const { db, shiftId } = await buildDb();
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
@@ -255,12 +365,18 @@ async function buildDb() {
return { db, eventId, shiftId: insertShift(db, eventId, 'Sorting') };
}
function insertShift(db: Awaited<ReturnType<typeof openAppDatabase>>, eventId: number, role: string): number {
function insertShift(
db: Awaited<ReturnType<typeof openAppDatabase>>,
eventId: number,
role: string,
startsAt = '2026-10-15T14:00:00.000Z',
endsAt = '2026-10-15T17:00:00.000Z',
): number {
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, ?, '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', 4, '', 0)`,
).run(eventId, role).lastInsertRowid,
VALUES (?, ?, ?, ?, 4, '', 0)`,
).run(eventId, role, startsAt, endsAt).lastInsertRowid,
);
}