feat: enhance signup functionality to support multiple date selections

Updated the signup form to allow users to select multiple dates for signups, improving flexibility for event participation. Introduced new styles for displaying selected dates and updated the backend logic to handle multiple date reservations. Enhanced confirmation messages to reflect the number of dates signed up for, ensuring clear communication with users. Added tests to verify the new multi-date signup functionality and its integration with existing features.
This commit is contained in:
blake committed 2026-11-02 14:51:19 -06:00
1 parent 77a9a0caff
commit e6f072dcac
11 files changed
+963 -27

No files matched your search

+1
View File
@@ -8,3 +8,4 @@ data/
npm-debug.log*
*.log
.cursor
.verify-data/
+146
View File
@@ -665,6 +665,33 @@ main a:hover {
text-decoration: none;
}
.receipt-dates {
display: grid;
margin: 0;
padding: 0.35rem 0 0;
list-style: none;
}
.receipt-dates > li {
display: grid;
gap: 0.45rem;
padding: 0.85rem 1.25rem 0.35rem;
}
.receipt-dates > li + li {
margin-top: 0.35rem;
border-top: 1px solid var(--hope-border);
}
.receipt-dates .receipt-link {
margin-top: 0.2rem;
border-radius: 1rem;
}
.receipt-dates + .receipt-note {
padding: 0.35rem 1.25rem 1.2rem;
}
.manage {
display: grid;
gap: 0.35rem 0;
@@ -1890,6 +1917,125 @@ article.shift-card {
padding: 0 0.35rem;
}
.signup-form .more-dates {
border: 0;
padding: 0;
background: transparent;
}
.signup-form .more-dates > summary {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
min-height: 48px;
padding: 0.7rem 1rem;
list-style: none;
cursor: pointer;
background: var(--hope-blue-50);
border-radius: 999px;
box-shadow: var(--hope-shadow);
font-weight: 650;
}
.signup-form .more-dates > summary::-webkit-details-marker {
display: none;
}
.signup-form .more-dates > summary::marker {
content: "";
}
.signup-form .more-dates > summary::after {
content: "";
width: 0.45rem;
height: 0.45rem;
margin-left: auto;
border-right: 2px solid currentColor;
border-bottom: 2px solid currentColor;
transform: translateY(-0.12rem) rotate(45deg);
flex: none;
}
.signup-form .more-dates[open] > summary {
border-radius: 1.25rem 1.25rem 0 0;
}
.signup-form .more-dates[open] > summary::after {
transform: translateY(0.12rem) rotate(225deg);
}
.signup-form .more-dates-count {
color: var(--hope-ink-2);
font-size: 0.92rem;
font-weight: 500;
}
.signup-form .more-dates-count[hidden] {
display: none;
}
.signup-form .more-dates-panel {
display: grid;
gap: 0.55rem;
padding: 0.75rem 0.85rem 0.9rem;
background: var(--hope-blue-50);
border-radius: 0 0 1.25rem 1.25rem;
box-shadow: var(--hope-shadow);
}
.signup-form .more-dates-panel .signup-note {
font-weight: 500;
}
.signup-form .date-choices {
display: grid;
gap: 0.15rem;
max-height: 16.5rem;
margin: 0;
padding: 0;
overflow: auto;
list-style: none;
}
.signup-form .date-choice {
display: flex;
align-items: flex-start;
gap: 0.7rem;
margin: 0;
padding: 0.4rem 0.15rem;
font-weight: 650;
}
.signup-form .date-choice input {
width: 1.15rem;
height: 1.15rem;
margin-top: 0.2rem;
accent-color: var(--hope-gold);
flex: none;
}
.signup-form .date-choice time,
.signup-form .date-choice-role,
.signup-form .date-choice-event,
.signup-form .date-choice-clock {
display: block;
}
.signup-form .date-choice-clock {
margin-top: 0.1rem;
color: var(--hope-ink-2);
font-weight: 500;
}
.signup-form .date-choice-spots {
display: block;
margin-top: 0.1rem;
color: var(--hope-ink-2);
font-size: 0.92rem;
font-weight: 500;
}
.signup-form input,
.signup-form select,
.signup-form textarea,
+47
View File
@@ -3,6 +3,7 @@
bindCalendar();
bindViewMenu();
bindManage();
bindSignupDates();
document.querySelectorAll('[data-contact]').forEach(bindContact);
document.querySelectorAll('[data-see-more]').forEach(bindSeeMore);
@@ -117,6 +118,52 @@
});
}
function bindSignupDates() {
document.addEventListener('click', function (event) {
var openMenus = document.querySelectorAll('details.more-dates[open]');
for (var j = 0; j < openMenus.length; j += 1) {
if (!openMenus[j].contains(event.target)) openMenus[j].open = false;
}
});
document.addEventListener('change', function (event) {
var box = event.target;
if (!box || box.name !== 'dates' || !box.form) return;
syncSignupDates(box.form);
});
}
function syncSignupDates(form) {
var boxes = form.querySelectorAll('input[name="dates"]');
if (!boxes.length) return;
var pageRoom = Number(form.getAttribute('data-page-remaining'));
var min = pageRoom > 0 ? pageRoom : Infinity;
var checked = 0;
for (var i = 0; i < boxes.length; i += 1) {
if (!boxes[i].checked) continue;
checked += 1;
var room = Number(boxes[i].getAttribute('data-remaining'));
if (room > 0 && room < min) min = room;
}
var select = form.querySelector('select[name="party_size"]');
if (select && min < Infinity) {
for (var j = 0; j < select.options.length; j += 1) {
var option = select.options[j];
option.disabled = Number(option.value) > min;
}
if (select.selectedOptions.length && select.selectedOptions[0].disabled) select.value = String(min);
}
var count = form.querySelector('[data-more-dates-count]');
if (count) {
count.hidden = checked === 0;
count.textContent = checked === 1 ? '1 selected' : checked + ' selected';
}
var button = form.querySelector('button[type="submit"]');
if (button && form.getAttribute('data-sending') !== 'true') {
var total = pageRoom > 0 ? checked + 1 : checked;
button.textContent = total > 1 ? 'Sign up for ' + total + ' dates' : 'Sign up';
}
}
function bindContact(picker) {
picker.addEventListener('change', function () {
var form = picker.form;
+3 -1
View File
@@ -177,7 +177,9 @@
form.removeAttribute('data-sending');
if (submit) {
submit.disabled = false;
submit.textContent = 'Sign up';
var chosen = form.querySelectorAll('input[name="dates"]:checked').length;
var total = form.hasAttribute('data-page-remaining') ? chosen + 1 : chosen;
submit.textContent = total > 1 ? 'Sign up for ' + total + ' dates' : 'Sign up';
}
var alert = form.querySelector('[data-signup-send-error]');
if (!alert) {
+33 -1
View File
@@ -3,17 +3,31 @@ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:
const COOKIE = 'hope_confirm';
const MAX_AGE_SECONDS = 900;
export type ConfirmationCompanion = {
signupId: number;
shiftId: number;
token: string;
};
export type ConfirmationSeal = {
signupId: number;
shiftId: number;
token: string;
expiresAtMs: number;
companions?: ConfirmationCompanion[];
};
export function sealConfirmation(secret: string, payload: ConfirmationSeal): string {
const iv = randomBytes(12);
const cipher = createCipheriv('aes-256-gcm', cookieKey(secret), iv);
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(payload), 'utf8'), cipher.final()]);
const stored = {
signupId: payload.signupId,
shiftId: payload.shiftId,
token: payload.token,
expiresAtMs: payload.expiresAtMs,
...(payload.companions && payload.companions.length > 0 ? { companions: payload.companions } : {}),
};
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(stored), 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
return Buffer.concat([iv, tag, ciphertext]).toString('base64url');
}
@@ -34,11 +48,14 @@ export function openConfirmation(secret: string, cookieHeader: string | undefine
if (!parsed || typeof parsed.signupId !== 'number' || typeof parsed.shiftId !== 'number') return null;
if (typeof parsed.token !== 'string' || typeof parsed.expiresAtMs !== 'number') return null;
if (parsed.expiresAtMs <= nowMs) return null;
const companions = readCompanions(parsed.companions);
if (!companions) return null;
return {
signupId: parsed.signupId,
shiftId: parsed.shiftId,
token: parsed.token,
expiresAtMs: parsed.expiresAtMs,
...(companions.length > 0 ? { companions } : {}),
};
} catch {
return null;
@@ -57,6 +74,21 @@ export function confirmationCookie(value: string, path: string, secure: boolean)
return parts.join('; ');
}
function readCompanions(value: unknown): ConfirmationCompanion[] | null {
if (value === undefined) return [];
if (!Array.isArray(value) || value.length > 24) return null;
const companions: ConfirmationCompanion[] = [];
for (const item of value) {
if (!item || typeof item !== 'object') return null;
const record = item as Record<string, unknown>;
if (typeof record.signupId !== 'number' || !Number.isSafeInteger(record.signupId) || record.signupId <= 0) return null;
if (typeof record.shiftId !== 'number' || !Number.isSafeInteger(record.shiftId) || record.shiftId <= 0) return null;
if (typeof record.token !== 'string' || !/^[A-Za-z0-9_-]{20,200}$/.test(record.token)) return null;
companions.push({ signupId: record.signupId, shiftId: record.shiftId, token: record.token });
}
return companions;
}
function cookieKey(secret: string): Buffer {
return createHash('sha256').update(`hope-confirm-v1\0${secret}`).digest();
}
+169 -9
View File
@@ -1,7 +1,7 @@
import type { Child } from 'hono/jsx';
import type { AppConfig } from './config.js';
import { WEEKDAY_SHORT, calendarMonth, calendarToday, chooseCalendarMonth, monthStep, type CalendarDay } from './calendar.js';
import { spotsSentence, type PublicEvent, type PublicShift } from './schedule.js';
import { spotsSentence, type PublicEvent, type PublicShift, type SignupDateChoice } from './schedule.js';
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';
@@ -298,6 +298,8 @@ export type SignupFormView = {
siteKey: string;
values: SignupValues;
errors: SignupErrors;
dates: SignupDateChoice[];
selectedDateIds: number[];
};
export function ShiftPage(props: {
@@ -320,12 +322,17 @@ export function ShiftPage(props: {
</p>
) : null}
{props.signup ? (
<SignupForm config={props.config} shiftId={props.shift.id} remaining={props.shift.remaining} form={props.signup} />
<SignupForm config={props.config} shiftId={props.shift.id} eventId={props.shift.event.id} remaining={props.shift.remaining} form={props.signup} />
) : null}
</>
);
}
export type ConfirmationEntry = {
shift: PublicShift;
managePath: string | null;
};
export function ConfirmationPage(props: {
config: AppConfig;
shift: PublicShift;
@@ -333,7 +340,23 @@ export function ConfirmationPage(props: {
managePath: string | null;
groupSize?: number;
cancelled?: boolean;
also?: ConfirmationEntry[];
}) {
const also = props.also ?? [];
if (also.length > 0 && !props.cancelled) {
const entries = [{ shift: props.shift, managePath: props.managePath }, ...also].sort((left, right) => {
const byTime = left.shift.startsAtUtc.localeCompare(right.shift.startsAtUtc);
return byTime === 0 ? left.shift.id - right.shift.id : byTime;
});
return (
<SeveralDatesReceipt
config={props.config}
name={props.name}
groupSize={props.groupSize ?? 1}
entries={entries}
/>
);
}
const shift = props.shift;
const cancelled = Boolean(props.cancelled);
const summary = cancelled
@@ -387,6 +410,57 @@ export function ConfirmationPage(props: {
);
}
function SeveralDatesReceipt(props: {
config: AppConfig;
name: string | null;
groupSize: number;
entries: ConfirmationEntry[];
}) {
const count = props.entries.length;
const summary = props.name
? `${props.name} is signed up for ${count} dates.`
: `These ${count} dates are saved.`;
return (
<article class="receipt">
<header class="receipt-head">
<span class="receipt-mark" aria-hidden="true">
<svg viewBox="0 0 24 24" focusable="false">
<path d="M5 12.5 9.2 16.7 19 7" />
</svg>
</span>
<div>
<h1>You're signed up</h1>
<p class="receipt-summary">{summary}</p>
{props.groupSize > 1 ? (
<p class="spots is-open">Each date holds {props.groupSize} spots.</p>
) : null}
</div>
</header>
<section class="receipt-card">
<h2 class="receipt-banner">Shift information</h2>
<ul class="receipt-dates">
{props.entries.map((entry) => {
const location = entry.shift.event.location.trim();
return (
<li key={entry.shift.id}>
<p class="receipt-role">{entry.shift.role}</p>
<ShiftWhen shift={entry.shift} />
{location ? <p class="receipt-where">{location}</p> : null}
{entry.managePath ? (
<a class="receipt-link" href={entry.managePath}>{`${props.config.baseUrl}${entry.managePath}`}</a>
) : null}
</li>
);
})}
</ul>
<p class="receipt-note">
A confirmation email is on the way for each date. This browser keeps the links above for a few minutes. Use a link to cancel that date or switch it.
</p>
</section>
</article>
);
}
export type SwitchForm = {
action: string;
token: string;
@@ -1148,12 +1222,24 @@ function Spots(props: { shift: PublicShift }) {
return <p class={props.shift.full ? 'spots is-full' : 'spots is-open'}>{spotsSentence(props.shift)}</p>;
}
function SignupForm(props: { config: AppConfig; shiftId: number; remaining: number; form: SignupFormView }) {
function SignupForm(props: { config: AppConfig; shiftId: number; eventId: number; remaining: number; form: SignupFormView }) {
const form = props.form;
const errors = form.errors;
const errorEntries = Object.entries(errors).filter((entry): entry is [string, string] => Boolean(entry[1]));
const selected = new Set(form.selectedDateIds);
const chosen = form.dates.filter((date) => selected.has(date.id));
const selectedRoom = chosen.length > 0 ? Math.min(...chosen.map((date) => date.remaining)) : props.remaining;
const choiceRoom = form.dates.length > 0 ? Math.max(selectedRoom, ...form.dates.map((date) => date.remaining)) : props.remaining;
const moreDates = form.dates.filter((date) => date.id !== props.shiftId);
const severalDates = moreDates.length > 0;
const extraCount = moreDates.filter((date) => selected.has(date.id)).length;
return (
<form class="signup-form" method="post" action={appPath(props.config, `/s/${props.shiftId}`)}>
<form
class="signup-form"
method="post"
action={appPath(props.config, `/s/${props.shiftId}`)}
data-page-remaining={severalDates ? String(props.remaining) : undefined}
>
<h2>Sign up</h2>
<div class="signup-lead">
<p>Choose how many people are coming, including you. This signup holds that many spots under your name. Another person can use the same email address.</p>
@@ -1203,7 +1289,18 @@ function SignupForm(props: { config: AppConfig; shiftId: number; remaining: numb
required
/>
</div>
<PartySizeField idPrefix="signup" value={form.values.partySize} error={errors.partySize} remaining={props.remaining} />
<PartySizeField
idPrefix="signup"
value={form.values.partySize}
error={errors.partySize}
remaining={severalDates ? choiceRoom : props.remaining}
limit={severalDates ? selectedRoom : undefined}
hint={
severalDates
? "Including you. This number applies to the date you opened and every date you add. You don't need to add their names."
: undefined
}
/>
<Field id="signup-email" label="Email" name="email" type="email" value={form.values.email} error={errors.email} autoComplete="email" />
<Field
id="signup-phone"
@@ -1226,14 +1323,72 @@ function SignupForm(props: { config: AppConfig; shiftId: number; remaining: numb
</span>
) : null}
</label>
{severalDates ? (
<MoreDates dates={moreDates} eventId={props.eventId} selected={selected} count={extraCount} error={errors.dates} />
) : null}
<div class="cf-turnstile" data-sitekey={form.siteKey} data-action="signup" />
<p class="signup-note" id="signup-turnstile-hint">This check confirms the signup came from a browser.</p>
<button type="submit">Sign up</button>
<button type="submit">{extraCount > 0 ? `Sign up for ${extraCount + 1} dates` : 'Sign up'}</button>
</form>
);
}
export function PartySizeField(props: { idPrefix: string; value: string; error?: string; remaining: number }) {
function MoreDates(props: { dates: SignupDateChoice[]; eventId: number; selected: Set<number>; count: number; error?: string }) {
const open = Boolean(props.error) || props.count > 0;
return (
<details class="more-dates" id="signup-dates" open={open ? true : undefined} aria-invalid={props.error ? 'true' : undefined} aria-describedby={props.error ? 'signup-dates-error' : undefined}>
<summary>
<span data-more-dates-label>More Dates?</span>
<span class="more-dates-count" data-more-dates-count hidden={props.count > 0 ? undefined : true}>
{props.count === 1 ? '1 selected' : props.count > 1 ? `${props.count} selected` : ''}
</span>
</summary>
<div class="more-dates-panel">
<p class="signup-note">The shift you opened is already included. You can add any open shift. Each one is its own signup, with the same name and number of people.</p>
<ul class="date-choices">
{props.dates.map((date) => {
const checked = props.selected.has(date.id);
const spots = date.remaining === 1 ? '1 spot left' : `${date.remaining} spots left`;
return (
<li key={date.id}>
<label class="date-choice">
<input type="checkbox" name="dates" value={String(date.id)} checked={checked ? true : undefined} data-remaining={String(date.remaining)} />
<span>
{date.eventId === props.eventId ? null : <span class="date-choice-event">{date.eventTitle}</span>}
<span class="date-choice-role">{date.role}</span>
<time dateTime={date.date}>{date.dateLabel}</time>
<span class="date-choice-clock">{dateClock(date)}</span>
<span class="date-choice-spots">{spots}</span>
</span>
</label>
</li>
);
})}
</ul>
</div>
{props.error ? (
<span class="field-error" id="signup-dates-error">
{props.error}
</span>
) : null}
</details>
);
}
function dateClock(date: SignupDateChoice): string {
const endDate = date.sameDay ? '' : `${date.endDateLabel} `;
return `${date.startLabel} to ${endDate}${date.endLabel} ${date.abbreviation}`;
}
export function PartySizeField(props: {
idPrefix: string;
value: string;
error?: string;
remaining: number;
/** Options above this stay visible and disabled. Omitted means every listed choice can be selected. */
limit?: number;
hint?: string;
}) {
const id = `${props.idPrefix}-partySize`;
const hintId = `${id}-hint`;
const errorId = `${id}-error`;
@@ -1247,13 +1402,18 @@ export function PartySizeField(props: { idPrefix: string; value: string; error?:
aria-describedby={props.error ? `${hintId} ${errorId}` : hintId}
>
{partyChoices(props.remaining).map((count) => (
<option key={count} value={String(count)} selected={props.value === String(count) ? true : undefined}>
<option
key={count}
value={String(count)}
selected={props.value === String(count) ? true : undefined}
disabled={props.limit !== undefined && count > props.limit ? true : undefined}
>
{partyChoiceLabel(count)}
</option>
))}
</select>
<span class="hint" id={hintId}>
Including you. This signup holds that many spots. You don't need to add their names.
{props.hint ?? "Including you. This signup holds that many spots. You don't need to add their names."}
</span>
{props.error ? (
<span class="field-error" id={errorId}>
+72
View File
@@ -160,6 +160,78 @@ export function getPublicShift(db: Database.Database, id: number, now: string):
return presentShift(row, now, names.get(row.id) ?? []);
}
export type SignupDateChoice = {
id: number;
role: string;
eventId: number;
eventTitle: string;
date: string;
dateLabel: string;
startLabel: string;
endLabel: string;
endDateLabel: string;
sameDay: boolean;
abbreviation: string;
remaining: number;
};
/**
* Open shifts a volunteer can still join, on any published event.
* The shift they opened is included. Full, ended, cancelled, and not-yet-open shifts are left out.
*/
export function listSignupDates(db: Database.Database, shift: PublicShift, now: string): SignupDateChoice[] {
return listSignupChoices(db, shift, now, false);
}
/** Shifts the form may accept, including one that filled after the form was shown. */
export function listSignupSlot(db: Database.Database, shift: PublicShift, now: string): SignupDateChoice[] {
return listSignupChoices(db, shift, now, true);
}
function listSignupChoices(db: Database.Database, shift: PublicShift, now: string, includeFull: boolean): SignupDateChoice[] {
const rows = db
.prepare(
`SELECT ${SHIFT_COLUMNS}
${SHIFT_FROM}
WHERE e.published = 1 AND s.cancelled = 0 AND s.ends_at_utc > ?
GROUP BY s.id
ORDER BY s.starts_at_utc, s.role COLLATE NOCASE, s.id`,
)
.all(now) as ShiftRow[];
const choices: SignupDateChoice[] = [];
for (const row of rows) {
const candidate = presentShift(row, now, []);
if (candidate.ended || candidate.cancelled || candidate.tooEarly) continue;
if (!includeFull && candidate.full) continue;
choices.push(dateChoice(candidate));
}
if (!choices.some((choice) => choice.id === shift.id) && (includeFull || openForSignup(shift))) {
choices.unshift(dateChoice(shift));
}
return choices;
}
function openForSignup(shift: PublicShift): boolean {
return !shift.ended && !shift.full && !shift.cancelled && !shift.tooEarly;
}
function dateChoice(shift: PublicShift): SignupDateChoice {
return {
id: shift.id,
role: shift.role,
eventId: shift.event.id,
eventTitle: shift.event.title,
date: shift.when.date,
dateLabel: shift.when.dateLabel,
startLabel: shift.when.startLabel,
endLabel: shift.when.endLabel,
endDateLabel: shift.when.endDateLabel,
sameDay: shift.when.sameDay,
abbreviation: shift.when.abbreviation,
remaining: shift.remaining,
};
}
export function spotsSentence(shift: Pick<PublicShift, 'occupied' | 'capacity'>): string {
const filled = Math.min(shift.capacity, Math.max(0, shift.occupied));
return `${filled}/${shift.capacity} spots filled`;
+4 -1
View File
@@ -9,6 +9,9 @@ const NOTES_MAX = 500;
/** One signup can hold this many spots. The database check uses the same bound. */
export const MAX_PARTY_SIZE = 20;
/** One form can reserve this many dates. Each date is still its own signup. */
export const MAX_SIGNUP_DATES = 24;
export type SignupValues = {
name: string;
firstName: string;
@@ -20,7 +23,7 @@ export type SignupValues = {
};
export type SignupErrors = Partial<
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'partySize' | 'form', string>
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'partySize' | 'dates' | 'form', string>
>;
export type SignupDraft = {
+181 -12
View File
@@ -8,7 +8,7 @@ import { listMoveTargets, switchSignup } from './admin/store.js';
import { readSession } from './auth/session.js';
import { cancelTokenMatches, issueCancelToken, issuePartyToken, issueReminderPageToken, issueSwitchToken, partyTokenMatches, reminderPageTokenMatches, switchTokenMatches } from './cancel-token.js';
import { clientAddress } from './client-ip.js';
import { confirmationCookie, openConfirmation, sealConfirmation } from './confirm-cookie.js';
import { confirmationCookie, openConfirmation, sealConfirmation, type ConfirmationCompanion } from './confirm-cookie.js';
import type { AppConfig } from './config.js';
import { issueFormToken, newOperationId, openFormToken, readFormToken } from './form-token.js';
import { originAllowed } from './origin.js';
@@ -26,12 +26,12 @@ import {
type SwitchForm,
} from './pages.js';
import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
import { getPublicShift, type PublicShift } from './schedule.js';
import { getPublicShift, listSignupDates, listSignupSlot, type PublicShift, type SignupDateChoice } from './schedule.js';
import { SIGNUP_TOO_EARLY } from './signup-window.js';
import { EMPTY_SIGNUP, parsePartySize, parseSignupForm, spotsLeftMessage, type SignupErrors, type SignupValues } from './signup-form.js';
import { EMPTY_SIGNUP, MAX_SIGNUP_DATES, parsePartySize, parseSignupForm, spotsLeftMessage, type SignupErrors, type SignupValues } from './signup-form.js';
import type { MailIdentity } from './mail/types.js';
import { disableReminders, enableReminders, queueDueReminders } from './reminders.js';
import { cancelSignup, changePartySize, confirmedOperationShift, findSignupByOperation, managePartyLimit, readManageSignup, reserveSignup } from './signup.js';
import { cancelSignup, changePartySize, confirmedOperationShift, findSignupByOperation, groupedOperationSignups, managePartyLimit, readManageSignup, reserveSignup, reserveSignups } from './signup.js';
import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js';
import { appPath, cookiePath } from './url.js';
@@ -87,6 +87,7 @@ export function registerPublicSignup(app: Hono, services: SignupServices): void
const manage = seal && seal.shiftId === shift.id ? readManageSignup(services.db, seal.token, services.now()) : null;
const matches = Boolean(manage && seal && manage.signupId === seal.signupId);
const cancelled = matches && manage?.status === 'cancelled';
const also = matches && seal && !cancelled ? confirmedCompanions(services, seal) : [];
return html(
c,
services,
@@ -98,6 +99,7 @@ export function registerPublicSignup(app: Hono, services: SignupServices): void
managePath={matches && seal ? appPath(config, `/m/${seal.token}`) : null}
groupSize={matches && manage ? manage.groupSize : undefined}
cancelled={cancelled}
also={also}
/>,
);
});
@@ -124,7 +126,7 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
if (ipLimit.limited) {
return shiftResponse(c, services, shift, 429, blankForm(services, shift), TOO_MANY, ipLimit.retryAfter);
}
const body = await c.req.parseBody();
const body = await c.req.parseBody({ all: true });
const values = valuesFrom(body);
if (textField(body, 'company_website').trim() !== '') {
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
@@ -135,16 +137,26 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
const token = tokenResult.reason === 'too_fast' ? textField(body, 'form_token') : null;
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, {}, token), notice);
}
const selection = readDateSelection(body, shift.id, listSignupSlot(db, shift, now));
const parsed = parseSignupForm(values);
if (!parsed.ok) {
return shiftResponse(c, services, shift, 400, formFor(services, shift, values, parsed.errors, textField(body, 'form_token')), undefined);
if (!parsed.ok || !selection.ok) {
const errors: SignupErrors = parsed.ok ? {} : parsed.errors;
if (!selection.ok) errors.dates = selection.error;
return shiftResponse(
c,
services,
shift,
400,
formFor(services, shift, values, errors, textField(body, 'form_token'), selection.shiftIds),
);
}
const several = selection.shiftIds.length > 1 || selection.shiftIds[0] !== shift.id;
const existing = findSignupByOperation(db, tokenResult.claims.operationId);
if (existing && existing.shiftId === shift.id && existing.emailNorm === parsed.draft.emailNorm) {
if (!several && existing && existing.shiftId === shift.id && existing.emailNorm === parsed.draft.emailNorm) {
return redirectConfirmed(c, services, shift.id, null);
}
if (existing) {
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null), COULD_NOT_SAVE);
return shiftResponse(c, services, shift, 409, formFor(services, shift, values, {}, null, selection.shiftIds), COULD_NOT_SAVE);
}
const turnstileToken = textField(body, 'cf-turnstile-response').trim();
const verdict = turnstileToken === ''
@@ -152,17 +164,67 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
: await checkTurnstile(services, turnstileToken, ip);
if (!verdict.ok) {
if (verdict.reason === 'duplicate') {
if (!several) {
const again = findSignupByOperation(db, tokenResult.claims.operationId);
if (again && again.shiftId === shift.id && again.emailNorm === parsed.draft.emailNorm) {
return redirectConfirmed(c, services, shift.id, null);
}
} else {
const again = groupedOperationSignups(db, tokenResult.claims.operationId, selection.shiftIds);
if (again?.every((row) => row.emailNorm === parsed.draft.emailNorm)) {
return redirectGrouped(c, services, shift.id, again);
}
}
}
const notice = verdict.reason === 'unavailable' ? CHECK_UNAVAILABLE : CHECK_AGAIN;
return shiftResponse(c, services, shift, verdict.reason === 'unavailable' ? 503 : 400, formFor(services, shift, values, {}, textField(body, 'form_token')), notice);
return shiftResponse(
c,
services,
shift,
verdict.reason === 'unavailable' ? 503 : 400,
formFor(services, shift, values, {}, textField(body, 'form_token'), selection.shiftIds),
notice,
);
}
const emailLimit = recordSignupEmail(db, config.sessionSecret, now, config.defaultTimeZone, parsed.draft.emailNorm);
if (emailLimit.limited) {
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, emailLimit.retryAfter);
return shiftResponse(
c,
services,
shift,
429,
formFor(services, shift, values, {}, textField(body, 'form_token'), selection.shiftIds),
TOO_MANY,
emailLimit.retryAfter,
);
}
if (several) {
try {
const reserved = reserveSignups(db, {
shiftIds: selection.shiftIds,
name: parsed.draft.name,
email: parsed.draft.emailNorm,
phone: parsed.draft.phone,
notes: parsed.draft.notes,
groupSize: parsed.draft.groupSize,
operationId: tokenResult.claims.operationId,
now,
mail: mailIdentity(db, config),
});
if (reserved.ok) return redirectGrouped(c, services, shift.id, reserved.signups);
return groupFailure(c, services, shift, values, textField(body, 'form_token'), selection.shiftIds, reserved.reason, reserved.shiftId);
} catch (err) {
if (!isBusy(err)) throw err;
console.error('Signup could not lock the database.');
return shiftResponse(
c,
services,
shift,
503,
formFor(services, shift, values, {}, textField(body, 'form_token'), selection.shiftIds),
CHECK_UNAVAILABLE,
);
}
}
try {
const reserved = reserveSignup(db, {
@@ -208,7 +270,7 @@ function redirectConfirmed(
c: Context,
services: SignupServices,
shiftId: number,
issued: { signupId: number; token: string } | null,
issued: { signupId: number; token: string; companions?: ConfirmationCompanion[] } | null,
): Response {
if (issued) {
const sealed = sealConfirmation(services.config.sessionSecret, {
@@ -216,6 +278,7 @@ function redirectConfirmed(
shiftId,
token: issued.token,
expiresAtMs: epochMs(services.now()) + 900 * 1000,
companions: issued.companions,
});
c.header('Set-Cookie', confirmationCookie(sealed, cookiePath(services.config), services.config.secureCookies));
}
@@ -223,6 +286,106 @@ function redirectConfirmed(
return c.redirect(appPath(services.config, `/s/${shiftId}/confirmed`), 303);
}
function redirectGrouped(
c: Context,
services: SignupServices,
pageShiftId: number,
signups: Array<{ signupId: number; shiftId: number; manageToken: string | null }>,
): Response {
const primary = signups.find((row) => row.shiftId === pageShiftId) ?? signups[0];
if (!primary) return html(c, services, 'That page is not available · Hope Volunteer', <NotFoundPage />, 404);
const issued = signups.every((row) => row.manageToken)
? {
signupId: primary.signupId,
token: primary.manageToken ?? '',
companions: signups
.filter((row) => row.shiftId !== primary.shiftId && row.manageToken)
.map((row) => ({ signupId: row.signupId, shiftId: row.shiftId, token: row.manageToken ?? '' })),
}
: null;
return redirectConfirmed(c, services, primary.shiftId, issued);
}
function groupFailure(
c: Context,
services: SignupServices,
shift: PublicShift,
values: SignupValues,
token: string,
selectedDateIds: number[],
reason: 'not_found' | 'closed' | 'early' | 'full' | 'duplicate' | 'conflict',
shiftId: number,
): Response {
const failed = getPublicShift(services.db, shiftId, services.now());
const label = failed ? shiftChoiceLabel(failed, shift) : undefined;
const errors: SignupErrors = {};
let notice: string | undefined;
if (!failed || !label || reason === 'conflict') notice = COULD_NOT_SAVE;
else if (reason === 'not_found') errors.dates = 'Choose a date from the list.';
else if (reason === 'duplicate') errors.dates = `You're already signed up for ${label}. Leave that date unchecked.`;
else if (reason === 'closed') errors.dates = `${label} is closed. Leave that date unchecked.`;
else if (reason === 'early') errors.dates = `${label} is not open for signup yet. Leave that date unchecked.`;
else if (reason === 'full' && failed.remaining > 0) {
const spots = failed.remaining === 1 ? '1 spot left' : `${failed.remaining} spots left`;
errors.dates = `${label} has ${spots}. Choose fewer people or leave that date unchecked.`;
} else if (reason === 'full') errors.dates = `${label} is full. Leave that date unchecked.`;
else notice = COULD_NOT_SAVE;
return shiftResponse(
c,
services,
loadShift(services, String(shift.id)) ?? shift,
409,
formFor(services, shift, values, errors, token, selectedDateIds),
notice,
);
}
function confirmedCompanions(
services: SignupServices,
seal: { companions?: ConfirmationCompanion[] },
): Array<{ shift: PublicShift; managePath: string | null }> {
const views: Array<{ shift: PublicShift; managePath: string | null }> = [];
for (const companion of seal.companions ?? []) {
const shift = getPublicShift(services.db, companion.shiftId, services.now());
const manage = readManageSignup(services.db, companion.token, services.now());
if (!shift || !manage) continue;
if (manage.signupId !== companion.signupId || manage.shiftId !== shift.id || manage.status !== 'confirmed') continue;
views.push({ shift, managePath: appPath(services.config, `/m/${companion.token}`) });
}
return views;
}
function shiftChoiceLabel(shift: PublicShift, page: PublicShift): string {
const endDate = shift.when.sameDay ? '' : `${shift.when.endDateLabel} `;
const event = shift.event.id === page.event.id ? '' : `${shift.event.title}, `;
return `${event}${shift.role}, ${shift.when.dateLabel}, ${shift.when.startLabel} to ${endDate}${shift.when.endLabel} ${shift.when.abbreviation}`;
}
type DateSelection = { ok: true; shiftIds: number[] } | { ok: false; error: string; shiftIds: number[] };
function readDateSelection(body: Record<string, unknown>, pageShiftId: number, choices: SignupDateChoice[]): DateSelection {
const raw = body.dates;
const asked = raw !== undefined || textField(body, 'dates_present') === '1';
if (!asked) return { ok: true, shiftIds: [pageShiftId] };
const allowed = new Set(choices.map((choice) => choice.id));
const values = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw];
const picked: number[] = [];
for (const value of values) {
if (typeof value !== 'string' || !/^[1-9]\d*$/.test(value)) {
return { ok: false, error: 'Choose a date from the list.', shiftIds: picked };
}
const id = Number(value);
if (!allowed.has(id)) return { ok: false, error: 'Choose a date from the list.', shiftIds: picked };
if (!picked.includes(id)) picked.push(id);
}
if (allowed.has(pageShiftId) && !picked.includes(pageShiftId)) picked.unshift(pageShiftId);
if (picked.length === 0) return { ok: false, error: 'Choose at least one date.', shiftIds: [] };
if (picked.length > MAX_SIGNUP_DATES) {
return { ok: false, error: `Choose ${MAX_SIGNUP_DATES} dates or fewer.`, shiftIds: picked.slice(0, MAX_SIGNUP_DATES) };
}
return { ok: true, shiftIds: choices.filter((choice) => picked.includes(choice.id)).map((choice) => choice.id) };
}
function shiftResponse(
c: Context,
services: SignupServices,
@@ -256,7 +419,11 @@ function formFor(
values: SignupValues,
errors: SignupErrors,
token: string | null,
selectedDateIds?: number[],
): SignupFormView {
const dates = listSignupDates(services.db, shift, services.now());
const allowed = new Set(dates.map((date) => date.id));
const picked = (selectedDateIds ?? [shift.id]).filter((id) => allowed.has(id));
return {
token: token && token.length > 0 ? token : issueFormToken(services.config.sessionSecret, {
shiftId: shift.id,
@@ -266,6 +433,8 @@ function formFor(
siteKey: services.config.turnstile.siteKey,
values,
errors,
dates,
selectedDateIds: picked,
};
}
+83 -1
View File
@@ -5,7 +5,7 @@ import { rememberSignupContact } from './contacts.js';
import { normalizeEmail } from './email.js';
import { queueCancellation, queueConfirmation, queueCoordinatorNotices, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
import type { MailIdentity } from './mail/types.js';
import { MAX_PARTY_SIZE } from './signup-form.js';
import { MAX_PARTY_SIZE, MAX_SIGNUP_DATES } from './signup-form.js';
import { isWithinSignupWindow } from './signup-window.js';
import { formatInstantInZone, formatUtc, todayInZone, type ZonedClock } from './time.js';
@@ -80,6 +80,88 @@ export function findSignupByOperation(
return findOperation(db, sha256(operationId));
}
export type GroupedSignup = {
signupId: number;
shiftId: number;
manageToken: string | null;
replay: boolean;
};
export type ReserveGroupResult =
| { ok: true; signups: GroupedSignup[] }
| { ok: false; reason: 'not_found' | 'closed' | 'early' | 'full' | 'duplicate' | 'conflict'; shiftId: number };
/**
* Reserves the same person on several shifts, or on none of them.
* A date that is full, closed, or already has this person rolls the whole form back.
* Repeating the same form reuses each date instead of taking another spot.
*/
export function reserveSignups(
db: Database.Database,
input: Omit<ReserveInput, 'shiftId'> & { shiftIds: number[] },
): ReserveGroupResult {
const emailNorm = normalizeEmail(input.email);
const shiftIds = [...new Set(input.shiftIds)];
if (shiftIds.length === 0 || shiftIds.length > MAX_SIGNUP_DATES) {
return { ok: false, reason: 'conflict', shiftId: shiftIds[0] ?? 0 };
}
try {
return db
.transaction(() => {
const signups: GroupedSignup[] = [];
for (const shiftId of shiftIds) {
const reserved = placeReservation(db, { ...input, shiftId }, emailNorm, groupOperationKey(input.operationId, shiftId));
if (!reserved.ok) throw new GroupRollback({ ok: false, reason: reserved.reason, shiftId });
signups.push({
signupId: reserved.signupId,
shiftId,
manageToken: reserved.manageToken,
replay: reserved.replay,
});
}
return { ok: true as const, signups };
})
.immediate();
} catch (err) {
if (err instanceof GroupRollback) return err.failure;
if (!isUniqueConstraint(err)) throw err;
const signups: GroupedSignup[] = [];
for (const shiftId of shiftIds) {
const existing = findOperation(db, groupOperationKey(input.operationId, shiftId));
if (!existing || existing.shiftId !== shiftId || existing.emailNorm !== emailNorm) {
return { ok: false, reason: 'conflict', shiftId };
}
signups.push({ signupId: existing.id, shiftId, manageToken: null, replay: true });
}
return { ok: true, signups };
}
}
/** Signups already stored for this form, one per selected date. Null when any date is missing. */
export function groupedOperationSignups(
db: Database.Database,
operationId: string,
shiftIds: number[],
): Array<GroupedSignup & { emailNorm: string }> | null {
const signups: Array<GroupedSignup & { emailNorm: string }> = [];
for (const shiftId of shiftIds) {
const existing = findOperation(db, groupOperationKey(operationId, shiftId));
if (!existing || existing.shiftId !== shiftId) return null;
signups.push({ signupId: existing.id, shiftId, manageToken: null, replay: true, emailNorm: existing.emailNorm });
}
return signups;
}
function groupOperationKey(operationId: string, shiftId: number): string {
return sha256(`${operationId}\0${shiftId}`);
}
class GroupRollback extends Error {
constructor(readonly failure: Extract<ReserveGroupResult, { ok: false }>) {
super('Signup dates rolled back');
}
}
export function confirmedOperationShift(db: Database.Database, operationId: string): number | null {
const found = findOperation(db, sha256(operationId));
if (!found) return null;
+224 -2
View File
@@ -295,6 +295,7 @@ describe('capacity-safe signup', () => {
expect(formHtml).toContain('This signup holds that many spots.');
expect(formHtml).toContain('Your full name is listed on the public sign-up page.');
expect(formHtml).toContain('value="4"');
expect(formHtml).not.toContain('name="dates"');
const saved = await postSignup(
app,
@@ -392,6 +393,186 @@ describe('capacity-safe signup', () => {
expect(await missing.text()).toContain('That page is not available');
expect(db.prepare("SELECT status FROM signups WHERE email_norm = 'link@example.invalid'").get()).toEqual({ status: 'confirmed' });
});
it('saves several dates from one signup form', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 4 });
const secondId = insertExtraShift(db, { capacity: 4, starts: '2026-10-22T14:00:00.000Z', ends: '2026-10-22T17:00:00.000Z' });
const thirdId = insertExtraShift(db, { capacity: 4, starts: '2026-10-29T14:00:00.000Z', ends: '2026-10-29T17:00:00.000Z' });
const otherHours = insertExtraShift(db, { capacity: 4, starts: '2026-10-22T16:00:00.000Z', ends: '2026-10-22T19:00:00.000Z' });
const otherRole = insertExtraShift(db, {
capacity: 4,
role: 'Intake',
starts: '2026-11-05T14:00:00.000Z',
ends: '2026-11-05T17:00:00.000Z',
});
const fullId = insertExtraShift(db, { capacity: 1, starts: '2026-11-05T14:00:00.000Z', ends: '2026-11-05T17:00:00.000Z' });
db.prepare(
`INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
) VALUES (?, 'Full Person', 'full.person@example.invalid', 'full.person@example.invalid', 0, 1, 'confirmed', 0, ?, ?)`,
).run(fullId, NOW, NOW);
const closedId = insertExtraShift(db, {
cancelled: 1,
starts: '2026-11-12T14:00:00.000Z',
ends: '2026-11-12T17:00:00.000Z',
});
const elsewhereId = insertEventShift(db, {
slug: 'holiday-pantry',
title: 'Holiday pantry',
published: 1,
role: 'Delivery',
starts: '2026-11-19T15:00:00.000Z',
ends: '2026-11-19T18:00:00.000Z',
});
const unpublishedId = insertEventShift(db, {
slug: 'draft-pantry',
title: 'Draft pantry',
published: 0,
role: 'Hidden',
starts: '2026-11-19T15:00:00.000Z',
ends: '2026-11-19T18:00:00.000Z',
});
const form = await app.request(`/s/${shiftId}`);
const formHtml = await form.text();
expect(formHtml.indexOf('name="notes"')).toBeLessThan(formHtml.indexOf('More Dates?'));
expect(formHtml).toContain('More Dates?');
expect(formHtml).not.toContain('Select all dates');
expect(formHtml).toContain('Thursday, October 15, 2026');
expect(formHtml).toContain('Thursday, October 22, 2026');
expect(formHtml).toContain('Thursday, October 29, 2026');
expect(formHtml).toContain('9:00 AM to 12:00 PM');
expect(dateBox(formHtml, shiftId)).toBe('');
expect(dateBox(formHtml, secondId)).not.toContain('checked');
expect(dateBox(formHtml, secondId)).toContain('name="dates"');
expect(dateChoice(formHtml, secondId)).toContain('Sorting');
expect(dateBox(formHtml, thirdId)).not.toContain('checked');
expect(dateBox(formHtml, otherHours)).toContain('name="dates"');
expect(dateChoice(formHtml, otherHours)).toContain('11:00 AM to 2:00 PM');
expect(dateBox(formHtml, otherRole)).toContain('name="dates"');
expect(dateChoice(formHtml, otherRole)).toContain('Intake');
expect(dateBox(formHtml, elsewhereId)).toContain('name="dates"');
expect(dateChoice(formHtml, elsewhereId)).toContain('Holiday pantry');
expect(dateChoice(formHtml, elsewhereId)).toContain('Delivery');
expect(dateBox(formHtml, fullId)).toBe('');
expect(dateBox(formHtml, closedId)).toBe('');
expect(dateBox(formHtml, unpublishedId)).toBe('');
const token = issueFormToken('dev-only-change-me-not-for-production-use', {
shiftId,
issuedAt: NOW_MS - 10_000,
operationId: 'several-dates-0001',
});
const saved = await postSignup(
app,
shiftId,
{ email: 'pat.dates@example.invalid', partySize: '2', dates: [shiftId, thirdId, otherHours, otherRole, elsewhereId] },
{ token, ip: '203.0.113.201' },
);
expect(saved.status).toBe(303);
expect(locationOf(saved)).toBe(`/s/${shiftId}/confirmed`);
const confirmed = await app.request(locationOf(saved), { headers: { cookie: cookiePair(saved.headers.get('set-cookie') ?? '') } });
const confirmedHtml = await confirmed.text();
expect(confirmedHtml).toContain('Pat Review is signed up for 5 dates.');
expect(confirmedHtml).toContain('Each date holds 2 spots.');
expect(confirmedHtml).toContain('Thursday, October 15, 2026');
expect(confirmedHtml).toContain('Thursday, October 22, 2026');
expect(confirmedHtml).toContain('Thursday, October 29, 2026');
expect(confirmedHtml).toContain('dateTime="2026-10-22T16:00:00.000Z"');
expect(confirmedHtml).toContain('Intake');
expect(confirmedHtml).toContain('Delivery');
expect(confirmedHtml).toContain('A confirmation email is on the way for each date.');
const links = [...confirmedHtml.matchAll(/href="(\/m\/[^"]+)"/g)].map((match) => match[1]);
expect(links).toHaveLength(5);
expect((await app.request(links[0] ?? '/m/missing')).status).toBe(200);
expect((await app.request(links[4] ?? '/m/missing')).status).toBe(200);
expect(db.prepare(
`SELECT shift_id, group_size FROM signups WHERE email_norm = 'pat.dates@example.invalid' AND status = 'confirmed' ORDER BY shift_id`,
).all()).toEqual([
{ shift_id: shiftId, group_size: 2 },
{ shift_id: thirdId, group_size: 2 },
{ shift_id: otherHours, group_size: 2 },
{ shift_id: otherRole, group_size: 2 },
{ shift_id: elsewhereId, group_size: 2 },
]);
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'pat.dates@example.invalid'").get()).toEqual({ n: 5 });
expect(db.prepare('SELECT COUNT(*) AS n FROM contacts WHERE email = ?').get('pat.dates@example.invalid')).toEqual({ n: 1 });
const replay = await postSignup(
app,
shiftId,
{ email: 'pat.dates@example.invalid', partySize: '2', dates: [shiftId, thirdId, otherHours, otherRole, elsewhereId] },
{ token, ip: '203.0.113.202' },
);
expect(replay.status).toBe(303);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat.dates@example.invalid'").get()).toEqual({ n: 5 });
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'pat.dates@example.invalid'").get()).toEqual({ n: 5 });
const none = await postSignup(app, shiftId, { email: 'nobody.dates@example.invalid', dates: [] }, { ip: '203.0.113.203' });
expect(none.status).toBe(303);
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'nobody.dates@example.invalid'").get()).toEqual({ n: 1 });
const foreign = await postSignup(
app,
shiftId,
{ email: 'foreign.dates@example.invalid', dates: [shiftId, closedId, unpublishedId] },
{ ip: '203.0.113.204' },
);
expect(foreign.status).toBe(400);
expect(await foreign.text()).toContain('Choose a date from the list.');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'foreign.dates@example.invalid'").get()).toEqual({ n: 0 });
});
it('keeps every date unsigned when one selected date cannot be saved', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 4 });
const tightId = insertExtraShift(db, { capacity: 2, starts: '2026-10-22T14:00:00.000Z', ends: '2026-10-22T17:00:00.000Z' });
const taken = await postSignup(
app,
tightId,
{ name: 'Pat Review', email: 'pat.taken@example.invalid' },
{ ip: '203.0.113.211' },
);
expect(taken.status).toBe(303);
const duplicate = await postSignup(
app,
shiftId,
{ name: 'Pat Review', email: 'pat.taken@example.invalid', dates: [shiftId, tightId] },
{ ip: '203.0.113.212' },
);
expect(duplicate.status).toBe(409);
const duplicateHtml = await duplicate.text();
expect(duplicateHtml).toContain('You&#39;re already signed up for Sorting, Thursday, October 22, 2026, 9:00 AM to 12:00 PM');
expect(duplicateHtml).toContain('Leave that date unchecked.');
expect(duplicateHtml).not.toContain('/m/');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat.taken@example.invalid'").get()).toEqual({ n: 1 });
const crowded = await postSignup(
app,
shiftId,
{ email: 'pat.crowd@example.invalid', partySize: '2', dates: [shiftId, tightId] },
{ ip: '203.0.113.213' },
);
expect(crowded.status).toBe(409);
const crowdedHtml = await crowded.text();
expect(crowdedHtml).toContain('Sorting, Thursday, October 22, 2026, 9:00 AM to 12:00 PM');
expect(crowdedHtml).toContain('has 1 spot left.');
expect(db.prepare("SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat.crowd@example.invalid'").get()).toEqual({ n: 0 });
});
it('counts one form as one signup attempt no matter how many dates it saves', async () => {
const { app, db, shiftId } = await buildApp({ capacity: 4 });
const extra = ['2026-10-22', '2026-10-29', '2026-11-05', '2026-11-12'].map((date) =>
insertExtraShift(db, { capacity: 4, starts: `${date}T14:00:00.000Z`, ends: `${date}T17:00:00.000Z` }),
);
const [firstDate, secondDate, thirdDate, fourthDate] = extra;
if (!firstDate || !secondDate || !thirdDate || !fourthDate) throw new Error('Expected four later shifts.');
const email = 'daily.dates@example.invalid';
expect((await postSignup(app, shiftId, { email, dates: [shiftId, firstDate] }, { ip: '203.0.113.221' })).status).toBe(303);
expect((await postSignup(app, secondDate, { email }, { ip: '203.0.113.222' })).status).toBe(303);
expect((await postSignup(app, thirdDate, { email }, { ip: '203.0.113.223' })).status).toBe(303);
expect((await postSignup(app, fourthDate, { email }, { ip: '203.0.113.224' })).status).toBe(429);
expect(SIGNUP_EMAIL_LIMIT).toBe(3);
});
});
describe('Turnstile siteverify', () => {
@@ -435,7 +616,7 @@ async function buildApp(options?: { capacity?: number; verify?: (input: unknown)
function insertExtraShift(
db: import('better-sqlite3').Database,
options?: { capacity?: number; starts?: string; ends?: string; cancelled?: number },
options?: { capacity?: number; starts?: string; ends?: string; cancelled?: number; role?: string },
): number {
const event = db.prepare("SELECT id FROM events WHERE slug = 'weekly-pantry'").get() as { id: number } | undefined;
const eventId = event?.id ?? Number(
@@ -447,10 +628,11 @@ function insertExtraShift(
const result = db
.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Sorting', ?, ?, ?, '', ?)`,
VALUES (?, ?, ?, ?, ?, '', ?)`,
)
.run(
eventId,
options?.role ?? 'Sorting',
options?.starts ?? '2026-10-15T14:00:00.000Z',
options?.ends ?? '2026-10-15T17:00:00.000Z',
options?.capacity ?? 3,
@@ -459,6 +641,26 @@ function insertExtraShift(
return Number(result.lastInsertRowid);
}
function insertEventShift(
db: import('better-sqlite3').Database,
options: { slug: string; title: string; published: number; role: string; starts: string; ends: string },
): number {
const existing = db.prepare('SELECT id AS id FROM events WHERE slug = ?').get(options.slug) as { id: number } | undefined;
const eventId = existing?.id ?? Number(
db.prepare(
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
VALUES (?, ?, '', '', 'America/Chicago', ?, ?)`,
).run(options.slug, options.title, options.published, NOW).lastInsertRowid,
);
const result = db
.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, ?, ?, ?, 4, '', 0)`,
)
.run(eventId, options.role, options.starts, options.ends);
return Number(result.lastInsertRowid);
}
async function postSignup(
app: ReturnType<typeof createApp>,
shiftId: number,
@@ -471,6 +673,7 @@ async function postSignup(
notes: string;
company: string;
partySize: string;
dates: number[];
}>,
options?: { token?: string; issuedAt?: number; ip?: string; origin?: string; forwardedFor?: string; site?: string },
) {
@@ -493,6 +696,10 @@ async function postSignup(
company_website: fields.company ?? '',
'cf-turnstile-response': 'widget-token',
});
if (fields.dates) {
body.append('dates_present', '1');
for (const id of fields.dates) body.append('dates', String(id));
}
return app.request(`/s/${shiftId}`, {
method: 'POST',
headers: {
@@ -506,6 +713,21 @@ async function postSignup(
});
}
function dateBox(html: string, id: number): string {
const inputs = html.match(/<input\b[^>]*>/g) ?? [];
const value = new RegExp(`value="${id}"(?!\\d)`);
return inputs.find((input) => input.includes('name="dates"') && value.test(input)) ?? '';
}
function dateChoice(html: string, id: number): string {
const at = html.search(new RegExp(`name="dates" value="${id}"(?!\\d)`));
if (at === -1) return '';
const start = html.lastIndexOf('<li', at);
const end = html.indexOf('</li>', at);
if (start === -1 || end === -1) return '';
return html.slice(start, end);
}
function locationOf(response: Response): string {
return response.headers.get('location') ?? '';
}