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:
1 parent
a520352071
commit
77a9a0caff
12 files changed
+725
-84
No files matched your search
+58
-10
@@ -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={{
|
||||
title: event.title,
|
||||
slug: event.slug,
|
||||
description: event.description,
|
||||
location: event.location,
|
||||
tz: event.tz,
|
||||
published: event.published,
|
||||
}}
|
||||
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
@@ -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.',
|
||||
|
||||
+122
-43
@@ -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,20 +1497,22 @@ function relocate(
|
||||
},
|
||||
options.audience === 'volunteer' ? 'switch' : 'move',
|
||||
);
|
||||
const previous = mailShift(db, source.shift_id);
|
||||
queueCoordinatorNotices(db, {
|
||||
action: options.audience === 'volunteer' ? 'switch' : 'move',
|
||||
signupId: newSignupId,
|
||||
shiftId: destination.id,
|
||||
shiftVersion: shift.version,
|
||||
volunteerName: source.name,
|
||||
volunteerEmail: source.email_norm,
|
||||
groupSize,
|
||||
shift: shift.facts,
|
||||
fromShift: previous?.facts,
|
||||
mail,
|
||||
now,
|
||||
});
|
||||
if (options.audience === 'volunteer') {
|
||||
const previous = mailShift(db, source.shift_id);
|
||||
queueCoordinatorNotices(db, {
|
||||
action: 'switch',
|
||||
signupId: newSignupId,
|
||||
shiftId: destination.id,
|
||||
shiftVersion: shift.version,
|
||||
volunteerName: source.name,
|
||||
volunteerEmail: source.email_norm,
|
||||
groupSize,
|
||||
shift: shift.facts,
|
||||
fromShift: previous?.facts,
|
||||
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,21 +1720,111 @@ 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,
|
||||
volunteerName: person.name,
|
||||
volunteerEmail: person.email_norm,
|
||||
groupSize: Number(person.group_size),
|
||||
shift: shift.facts,
|
||||
mail,
|
||||
now,
|
||||
});
|
||||
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,
|
||||
eventTitle: person.eventTitle,
|
||||
location: nextLocation,
|
||||
shifts: person.shifts,
|
||||
mail,
|
||||
now,
|
||||
});
|
||||
}
|
||||
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 {
|
||||
const issued = issueManageToken(endsAtUtc);
|
||||
const updated = db
|
||||
|
||||
+31
-2
@@ -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 },
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
+14
-12
@@ -294,18 +294,20 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
||||
mail: input.mail,
|
||||
now: input.now,
|
||||
});
|
||||
queueCoordinatorNotices(db, {
|
||||
action: 'signup',
|
||||
signupId,
|
||||
shiftId: input.shiftId,
|
||||
shiftVersion: facts.version,
|
||||
volunteerName: input.name,
|
||||
volunteerEmail: emailNorm,
|
||||
groupSize,
|
||||
shift: facts.facts,
|
||||
mail: input.mail,
|
||||
now: input.now,
|
||||
});
|
||||
if (input.audience !== 'coordinator') {
|
||||
queueCoordinatorNotices(db, {
|
||||
action: 'signup',
|
||||
signupId,
|
||||
shiftId: input.shiftId,
|
||||
shiftVersion: facts.version,
|
||||
volunteerName: input.name,
|
||||
volunteerEmail: emailNorm,
|
||||
groupSize,
|
||||
shift: facts.facts,
|
||||
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 };
|
||||
|
||||
Reference in new issue
Block a user