feat: save each name on the contact list

A confirmed signup is kept as a contact, and a coordinator can add one person by hand. The same name and email updates that contact. A different name stays separate even when the email matches. Names are capitalized, and a 10-digit phone is stored with dashes.
This commit is contained in:
blake committed 2026-10-16 15:28:39 -05:00
1 parent e8a5f9e352
commit ec259f58b2
11 files changed
+475 -60

No files matched your search

+1 -1
View File
@@ -103,7 +103,7 @@ A reminder is queued at each saved time before a confirmed signup, while the shi
**Download this roster**, on a shift, and **Download this event**, on an event, save a spreadsheet of the signups. **Download this date range**, on the coordinator page, uses each event's local shift date. The file includes cancelled signups and attendance. A cell that would be a spreadsheet formula is saved as text. The download is not cached. A copy on a coordinator's computer is outside this app, and the app does not delete it later. **Download this roster**, on a shift, and **Download this event**, on an event, save a spreadsheet of the signups. **Download this date range**, on the coordinator page, uses each event's local shift date. The file includes cancelled signups and attendance. A cell that would be a spreadsheet formula is saved as text. The download is not cached. A copy on a coordinator's computer is outside this app, and the app does not delete it later.
**Contacts**, on the coordinator page, keeps a list of people. Saving someone there does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same email updates that person. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. Typing a walk-in who is not on the list does not add them to it. **Contacts**, on the coordinator page, keeps a list of people. A confirmed signup is saved on this list. The name is split at the last space. A signup name with no space is saved with a hyphen as the last name. A different name is a separate contact, even when the email matches. The same name and email updates that contact. Cancelling the signup does not remove the contact. Saving someone here does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A word that already mixes upper and lower case stays as written. A phone number with ten digits is saved with dashes, like 712-555-0100. A leading 1 is left off. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. **Add a contact** saves one person who has not signed up. It does not take a spot and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Typing a walk-in who is not on the list saves them here too.
**Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration. **Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration.
+59
View File
@@ -0,0 +1,59 @@
-- A contact is one name at one email address.
-- Two different names can share an email and stay two contacts.
-- The signup retention job does not clear this table.
CREATE TABLE contacts_next (
id INTEGER PRIMARY KEY,
first_name TEXT NOT NULL CHECK (
length(trim(first_name)) > 0
AND length(first_name) <= 80
AND instr(first_name, char(10)) = 0
AND instr(first_name, char(13)) = 0
),
last_name TEXT NOT NULL CHECK (
length(trim(last_name)) > 0
AND length(last_name) <= 80
AND instr(last_name, char(10)) = 0
AND instr(last_name, char(13)) = 0
),
email TEXT NOT NULL,
email_norm TEXT NOT NULL CHECK (
email_norm = lower(email_norm)
AND instr(email_norm, ' ') = 0
AND instr(email_norm, '@') > 1
AND instr(email_norm, char(10)) = 0
AND instr(email_norm, char(13)) = 0
),
phone TEXT NULL CHECK (
phone IS NULL
OR (
length(phone) BETWEEN 1 AND 40
AND instr(phone, char(10)) = 0
AND instr(phone, char(13)) = 0
)
),
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'
),
updated_at TEXT NOT NULL CHECK (
updated_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'
),
CHECK (length(first_name) + length(last_name) + 1 <= 80)
);
INSERT INTO contacts_next (id, first_name, last_name, email, email_norm, phone, created_at, updated_at)
SELECT id, first_name, last_name, email, email_norm, phone, created_at, updated_at FROM contacts;
DROP TABLE contacts;
ALTER TABLE contacts_next RENAME TO contacts;
CREATE UNIQUE INDEX contacts_one_name_per_email
ON contacts (first_name COLLATE NOCASE, last_name COLLATE NOCASE, email_norm);
UPDATE contacts
SET phone = substr(phone, 1, 3) || '-' || substr(phone, 4, 3) || '-' || substr(phone, 7, 4)
WHERE phone GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]';
UPDATE contacts
SET phone = substr(phone, 2, 3) || '-' || substr(phone, 5, 3) || '-' || substr(phone, 8, 4)
WHERE phone GLOB '1[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]';
+34 -2
View File
@@ -86,8 +86,11 @@ import {
loadContacts, loadContacts,
parseContactSkips, parseContactSkips,
removeContact, removeContact,
saveManualContact,
walkInFromContact, walkInFromContact,
type ContactImportSummary, type ContactImportSummary,
type ContactManualErrors,
type ContactManualValues,
} from './contacts.js'; } from './contacts.js';
import { dateStamp, exportDateRange, exportEventRoster, exportShiftRoster } from './export.js'; import { dateStamp, exportDateRange, exportEventRoster, exportShiftRoster } from './export.js';
import { originAllowed } from './origin.js'; import { originAllowed } from './origin.js';
@@ -139,6 +142,7 @@ export function registerAdmin(app: Hono, services: AdminServices): void {
app.post(appPath(config, '/admin/settings'), (c) => submitSettings(c, services)); app.post(appPath(config, '/admin/settings'), (c) => submitSettings(c, services));
app.post(appPath(config, '/admin/export'), (c) => submitExportRange(c, services)); app.post(appPath(config, '/admin/export'), (c) => submitExportRange(c, services));
app.get(appPath(config, '/admin/contacts'), (c) => showContacts(c, services)); app.get(appPath(config, '/admin/contacts'), (c) => showContacts(c, services));
app.post(appPath(config, '/admin/contacts/new'), (c) => submitNewContact(c, services));
app.post(appPath(config, '/admin/contacts/import'), (c) => submitImportContacts(c, services)); app.post(appPath(config, '/admin/contacts/import'), (c) => submitImportContacts(c, services));
app.post(appPath(config, '/admin/contacts/export'), (c) => submitExportContacts(c, services)); app.post(appPath(config, '/admin/contacts/export'), (c) => submitExportContacts(c, services));
app.get(appPath(config, '/admin/contacts/:id/remove'), (c) => showRemoveContact(c, services)); app.get(appPath(config, '/admin/contacts/:id/remove'), (c) => showRemoveContact(c, services));
@@ -343,7 +347,12 @@ async function submitExportShift(c: Context, services: AdminServices): Promise<R
function showContacts( function showContacts(
c: Context, c: Context,
services: AdminServices, services: AdminServices,
options?: { error?: string; status?: 200 | 400 | 403; confirm?: ConfirmPrompt }, options?: {
error?: string;
status?: 200 | 400 | 403;
confirm?: ConfirmPrompt;
manual?: { values: ContactManualValues; errors: ContactManualErrors };
},
) { ) {
const session = requireSession(c, services); const session = requireSession(c, services);
if (session instanceof Response) return session; if (session instanceof Response) return session;
@@ -362,12 +371,32 @@ function showContacts(
notice={options?.error ? undefined : knownNotice(c.req.query('notice'))} notice={options?.error ? undefined : knownNotice(c.req.query('notice'))}
summary={options?.error ? undefined : contactSummary(c)} summary={options?.error ? undefined : contactSummary(c)}
importError={options?.error} importError={options?.error}
manual={options?.manual}
confirm={options?.confirm} confirm={options?.confirm}
/>, />,
{ account: session, status: options?.status ?? 200 }, { account: session, status: options?.status ?? 200 },
); );
} }
async function submitNewContact(c: Context, services: AdminServices): Promise<Response> {
const session = await postedSession(c, services);
if (session instanceof Response) return session;
const values = {
firstName: textField(session.body, 'first_name'),
lastName: textField(session.body, 'last_name'),
email: textField(session.body, 'email'),
phone: textField(session.body, 'phone'),
};
try {
const saved = saveManualContact(services.db, session.coordinatorId, values, services.now());
if (!saved.ok) return showContacts(c, services, { status: 400, manual: { values, errors: saved.errors } });
const notice = saved.status === 'added' ? 'contact-saved' : saved.status === 'changed' ? 'contact-updated' : 'contact-matched';
return c.redirect(appPath(services.config, `/admin/contacts?notice=${notice}`), 303);
} catch (err) {
return saveFailed(c, services, session, err);
}
}
async function submitImportContacts(c: Context, services: AdminServices): Promise<Response> { async function submitImportContacts(c: Context, services: AdminServices): Promise<Response> {
const session = await postedSession(c, services); const session = await postedSession(c, services);
if (session instanceof Response) return session; if (session instanceof Response) return session;
@@ -1452,7 +1481,10 @@ function knownNotice(value: string | undefined): string | undefined {
value === 'template-removed' || value === 'template-removed' ||
value === 'event-removed' || value === 'event-removed' ||
value === 'settings-saved' || value === 'settings-saved' ||
value === 'contact-removed' value === 'contact-removed' ||
value === 'contact-saved' ||
value === 'contact-updated' ||
value === 'contact-matched'
) { ) {
return value; return value;
} }
+27 -4
View File
@@ -4,7 +4,15 @@ import { spotsSentence } from './schedule.js';
import type { EventValues, ShiftValues, TemplateValues } from './admin/forms.js'; import type { EventValues, ShiftValues, TemplateValues } from './admin/forms.js';
import type { SettingsErrors, SettingsForm } from './settings.js'; import type { SettingsErrors, SettingsForm } from './settings.js';
import type { AppConfig } from './config.js'; import type { AppConfig } from './config.js';
import { CONTACT_LIST_PAGE, contactImportSentence, contactSkipSentence, type Contact, type ContactImportSummary } from './contacts.js'; import {
CONTACT_LIST_PAGE,
contactImportSentence,
contactSkipSentence,
type Contact,
type ContactImportSummary,
type ContactManualErrors,
type ContactManualValues,
} from './contacts.js';
import type { SignupErrors, SignupValues } from './signup-form.js'; import type { SignupErrors, SignupValues } from './signup-form.js';
import { addLocalDays, todayInZone } from './time.js'; import { addLocalDays, todayInZone } from './time.js';
import { appPath } from './url.js'; import { appPath } from './url.js';
@@ -315,8 +323,10 @@ export function ContactsPage(props: {
notice?: string; notice?: string;
summary?: ContactImportSummary; summary?: ContactImportSummary;
importError?: string; importError?: string;
manual?: { values: ContactManualValues; errors: ContactManualErrors };
confirm?: ConfirmPrompt; confirm?: ConfirmPrompt;
}) { }) {
const manual = props.manual ?? { values: { firstName: '', lastName: '', email: '', phone: '' }, errors: {} };
const heading = const heading =
props.total === 0 props.total === 0
? 'Saved contacts' ? 'Saved contacts'
@@ -343,13 +353,23 @@ export function ContactsPage(props: {
) : null} ) : null}
{hiddenSkips > 0 ? <p class="panel-note">{hiddenSkips === 1 ? '1 more row was skipped.' : `${hiddenSkips} more rows were skipped.`}</p> : null} {hiddenSkips > 0 ? <p class="panel-note">{hiddenSkips === 1 ? '1 more row was skipped.' : `${hiddenSkips} more rows were skipped.`}</p> : null}
<p> <p>
Saving someone here does not sign them up for a shift. Importing this list does not take a spot and does not send email. Choose a name to add that person to an open shift. Old signups lose their details after the retention period. This list stays until you remove someone. Someone who signs up is saved here. Cancelling that signup does not remove them. A different name is a separate contact, even when the email matches. To add someone who has not signed up, import a spreadsheet or save them below. That does not take a spot and does not send email. Choose a name to add that person to an open shift. Old signups lose their details after the retention period. This list stays until you remove someone.
</p> </p>
<form method="post" action={appPath(props.config, '/admin/contacts/new')} class="signup-form desk-download">
<input type="hidden" name="csrf" value={props.csrf} />
<h2>Add a contact</h2>
<p>This saves one person. It does not sign them up and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.</p>
<WalkInField id="contact-first" label="First name" name="first_name" type="text" value={manual.values.firstName} error={manual.errors.firstName} />
<WalkInField id="contact-last" label="Last name" name="last_name" type="text" value={manual.values.lastName} error={manual.errors.lastName} />
<WalkInField id="contact-email" label="Email" name="email" type="email" value={manual.values.email} error={manual.errors.email} />
<WalkInField id="contact-phone" label="Phone (optional)" name="phone" type="tel" value={manual.values.phone} error={manual.errors.phone} hint="We will not text them" />
<button type="submit">Save this contact</button>
</form>
<form method="post" action={appPath(props.config, '/admin/contacts/import')} class="signup-form desk-download" enctype="multipart/form-data"> <form method="post" action={appPath(props.config, '/admin/contacts/import')} class="signup-form desk-download" enctype="multipart/form-data">
<input type="hidden" name="csrf" value={props.csrf} /> <input type="hidden" name="csrf" value={props.csrf} />
<h2>Import a contact list</h2> <h2>Import a contact list</h2>
<p> <p>
Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same email updates that person. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Email addresses are stored in lowercase. The file has to be under 64 KB. Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. Email addresses are stored in lowercase. The file has to be under 64 KB.
</p> </p>
{props.importError ? <p class="error">{props.importError}</p> : null} {props.importError ? <p class="error">{props.importError}</p> : null}
<label> <label>
@@ -1330,7 +1350,7 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
))} ))}
</select> </select>
<span class="hint" id="walkin-contact-hint"> <span class="hint" id="walkin-contact-hint">
Optional. Choosing someone fills their name, email, and phone. A blank field uses the saved contact. Typing someone who is not on the list does not add them to it. Optional. Choosing someone fills their name, email, and phone. A blank field uses the saved contact. Typing someone who is not on the list saves them here when the walk-in is added.
</span> </span>
</label> </label>
) : null} ) : null}
@@ -1591,6 +1611,9 @@ const NOTICES: Record<string, string> = {
'event-removed': 'That event is removed.', 'event-removed': 'That event is removed.',
'settings-saved': 'Settings saved.', 'settings-saved': 'Settings saved.',
'contact-removed': 'That person is removed from the contact list.', 'contact-removed': 'That person is removed from the contact list.',
'contact-saved': 'That contact is saved.',
'contact-updated': 'That contact is updated.',
'contact-matched': 'That email is already on the contact list.',
}; };
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const; const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const;
+158 -27
View File
@@ -2,7 +2,9 @@ import type Database from 'better-sqlite3';
import { writeAudit } from './auth/audit.js'; import { writeAudit } from './auth/audit.js';
import { EmailAddressError, normalizeEmail } from './email.js'; import { EmailAddressError, normalizeEmail } from './email.js';
import { csvCell, csvImportedCell } from './export.js'; import { csvCell, csvImportedCell } from './export.js';
import { capitalizeName, formatPhone } from './person-format.js';
import type { SignupValues } from './signup-form.js'; import type { SignupValues } from './signup-form.js';
import { isUniqueConstraint } from './sqlite-error.js';
const MAX_ROWS = 2000; const MAX_ROWS = 2000;
export const CONTACT_LIST_PAGE = 20; export const CONTACT_LIST_PAGE = 20;
@@ -48,6 +50,15 @@ type ReadyContact = {
phone: string | null; phone: string | null;
}; };
export type ContactManualValues = {
firstName: string;
lastName: string;
email: string;
phone: string;
};
export type ContactManualErrors = Partial<Record<'firstName' | 'lastName' | 'email' | 'phone', string>>;
type ContactRow = { type ContactRow = {
id: number; id: number;
first_name: string; first_name: string;
@@ -139,34 +150,14 @@ export function importContactCsv(
} }
const applied = db.transaction(() => { const applied = db.transaction(() => {
const find = db.prepare('SELECT first_name, last_name, phone FROM contacts WHERE email_norm = ?');
const insert = db.prepare(
`INSERT INTO contacts (first_name, last_name, email, email_norm, phone, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
);
const update = db.prepare(
`UPDATE contacts
SET first_name = ?, last_name = ?, email = ?, phone = COALESCE(?, phone), updated_at = ?
WHERE email_norm = ?`,
);
let added = 0; let added = 0;
let changed = 0; let changed = 0;
let unchanged = 0; let unchanged = 0;
for (const person of ready) { for (const person of ready) {
const existing = find.get(person.email) as { first_name: string; last_name: string; phone: string | null } | undefined; const saved = applyContact(db, person, now);
if (!existing) { if (saved.status === 'added') added += 1;
insert.run(person.firstName, person.lastName, person.email, person.email, person.phone, now, now); else if (saved.status === 'changed') changed += 1;
added += 1; else unchanged += 1;
continue;
}
const phoneChanged = person.phone !== null && person.phone !== existing.phone;
const nameChanged = person.firstName !== existing.first_name || person.lastName !== existing.last_name;
if (!phoneChanged && !nameChanged) {
unchanged += 1;
continue;
}
update.run(person.firstName, person.lastName, person.email, person.phone, now, person.email);
changed += 1;
} }
writeAudit(db, coordinatorId, 'contacts.import', { added, changed, unchanged, skipped: skips.length }, now); writeAudit(db, coordinatorId, 'contacts.import', { added, changed, unchanged, skipped: skips.length }, now);
return { added, changed, unchanged }; return { added, changed, unchanged };
@@ -230,6 +221,50 @@ export function removeContact(db: Database.Database, coordinatorId: number, id:
})(); })();
} }
/**
* Saves the person from a confirmed signup.
* The same name and email updates that contact. A different name is a new contact, even with the same email.
* A blank phone does not erase a phone already saved.
*/
export function rememberSignupContact(
db: Database.Database,
input: { name: string; email: string; phone: string | null },
now: string,
): void {
let email: string;
try {
email = normalizeEmail(input.email);
} catch {
return;
}
if (email.length > MAX_EMAIL) return;
const parts = splitSignupName(input.name);
if (!parts) return;
const phone = input.phone?.normalize('NFC').trim() ?? '';
if (phone.length > MAX_PHONE || CONTROL.test(phone)) return;
applyContact(
db,
{ firstName: parts.firstName, lastName: parts.lastName, email, phone: phone.length === 0 ? null : formatPhone(phone) },
now,
);
}
export function saveManualContact(
db: Database.Database,
coordinatorId: number,
values: ContactManualValues,
now: string,
): { ok: true; status: 'added' | 'changed' | 'unchanged' } | { ok: false; errors: ContactManualErrors } {
const parsed = manualContact(values);
if (!parsed.ok) return parsed;
const status = db.transaction(() => {
const saved = applyContact(db, parsed.person, now);
if (saved.status !== 'unchanged') writeAudit(db, coordinatorId, 'contacts.manual', { id: saved.id }, now);
return saved.status;
})();
return { ok: true, status };
}
/** Blank name, email, or phone on the form keeps the saved contact's value. */ /** Blank name, email, or phone on the form keeps the saved contact's value. */
export function walkInFromContact(contact: Contact, values: SignupValues): SignupValues { export function walkInFromContact(contact: Contact, values: SignupValues): SignupValues {
return { return {
@@ -272,6 +307,98 @@ function columnIndex(cells: string[]): { first: number; last: number; email: num
return { first, last, email, phone }; return { first, last, email, phone };
} }
function splitSignupName(name: string): { firstName: string; lastName: string } | null {
if (CONTROL.test(name)) return null;
const trimmed = capitalizeName(name);
if (!trimmed) return null;
const space = trimmed.lastIndexOf(' ');
if (space > 0) {
const firstName = trimmed.slice(0, space);
const lastName = trimmed.slice(space + 1);
if (`${firstName} ${lastName}`.length > MAX_NAME) return null;
return { firstName, lastName };
}
if (trimmed.length + 2 > MAX_NAME) return null;
return { firstName: trimmed, lastName: '-' };
}
function manualContact(values: ContactManualValues): { ok: true; person: ReadyContact } | { ok: false; errors: ContactManualErrors } {
const errors: ContactManualErrors = {};
const firstRaw = values.firstName.normalize('NFC').trim();
const lastRaw = values.lastName.normalize('NFC').trim();
const firstName = capitalizeName(firstRaw);
const lastName = capitalizeName(lastRaw);
const phoneRaw = values.phone.normalize('NFC').trim();
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
if (!firstRaw || !firstName) errors.firstName = 'Enter a first name.';
else if (CONTROL.test(firstRaw)) errors.firstName = 'Enter a first name without line breaks.';
else if (firstRaw.length > MAX_NAME || firstName.length > MAX_NAME) errors.firstName = `Use ${MAX_NAME} characters or fewer.`;
if (!lastRaw || !lastName) errors.lastName = 'Enter a last name.';
else if (CONTROL.test(lastRaw)) errors.lastName = 'Enter a last name without line breaks.';
else if (lastRaw.length > MAX_NAME || lastName.length > MAX_NAME) errors.lastName = `Use ${MAX_NAME} characters or fewer.`;
if (firstName && lastName && !errors.firstName && !errors.lastName && `${firstName} ${lastName}`.length > MAX_NAME) {
errors.lastName = `Use ${MAX_NAME} characters or fewer for the full name.`;
}
if (CONTROL.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
else if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) errors.phone = `Use ${MAX_PHONE} characters or fewer.`;
let email = '';
const emailRaw = values.email.normalize('NFC').trim();
if (!emailRaw) errors.email = 'Enter an email address.';
else if (CONTROL.test(emailRaw)) errors.email = 'Enter an email address without line breaks.';
else {
try {
email = normalizeEmail(emailRaw);
if (email.length > MAX_EMAIL) errors.email = 'Enter an email address.';
} catch (err) {
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
}
}
if (Object.keys(errors).length > 0 || !email) return { ok: false, errors };
return { ok: true, person: { firstName, lastName, email, phone: phone.length === 0 ? null : phone } };
}
function findContact(
db: Database.Database,
person: Pick<ReadyContact, 'firstName' | 'lastName' | 'email'>,
): { id: number; first_name: string; last_name: string; phone: string | null } | undefined {
return db
.prepare(
`SELECT id, first_name, last_name, phone FROM contacts
WHERE first_name = ? COLLATE NOCASE AND last_name = ? COLLATE NOCASE AND email_norm = ?`,
)
.get(person.firstName, person.lastName, person.email) as
| { id: number; first_name: string; last_name: string; phone: string | null }
| undefined;
}
function applyContact(db: Database.Database, person: ReadyContact, now: string): { status: 'added' | 'changed' | 'unchanged'; id: number } {
const existing = findContact(db, person);
if (!existing) {
try {
const inserted = db
.prepare(
`INSERT INTO contacts (first_name, last_name, email, email_norm, phone, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
)
.run(person.firstName, person.lastName, person.email, person.email, person.phone, now, now);
return { status: 'added', id: Number(inserted.lastInsertRowid) };
} catch (err) {
if (!isUniqueConstraint(err)) throw err;
}
}
const current = existing ?? findContact(db, person);
if (!current) throw new Error('The contact could not be saved.');
const phoneChanged = person.phone !== null && person.phone !== current.phone;
const nameChanged = person.firstName !== current.first_name || person.lastName !== current.last_name;
if (!phoneChanged && !nameChanged) return { status: 'unchanged', id: current.id };
db.prepare(
`UPDATE contacts
SET first_name = ?, last_name = ?, email = ?, phone = COALESCE(?, phone), updated_at = ?
WHERE id = ?`,
).run(person.firstName, person.lastName, person.email, person.phone, now, current.id);
return { status: 'changed', id: current.id };
}
function parsePerson(cells: string[], columns: { first: number; last: number; email: number; phone: number }): ReadyContact | { code: ContactSkipCode } { function parsePerson(cells: string[], columns: { first: number; last: number; email: number; phone: number }): ReadyContact | { code: ContactSkipCode } {
const firstName = cellAt(cells, columns.first); const firstName = cellAt(cells, columns.first);
const lastName = cellAt(cells, columns.last); const lastName = cellAt(cells, columns.last);
@@ -279,12 +406,16 @@ function parsePerson(cells: string[], columns: { first: number; last: number; em
const phoneRaw = cellAt(cells, columns.phone); const phoneRaw = cellAt(cells, columns.phone);
if (!firstName || !lastName) return { code: 'n' }; if (!firstName || !lastName) return { code: 'n' };
if (CONTROL.test(firstName) || CONTROL.test(lastName) || CONTROL.test(phoneRaw) || CONTROL.test(emailRaw)) return { code: 'c' }; if (CONTROL.test(firstName) || CONTROL.test(lastName) || CONTROL.test(phoneRaw) || CONTROL.test(emailRaw)) return { code: 'c' };
if (firstName.length > MAX_NAME || lastName.length > MAX_NAME || `${firstName} ${lastName}`.length > MAX_NAME) return { code: 'l' }; const first = capitalizeName(firstName);
if (phoneRaw.length > MAX_PHONE) return { code: 'p' }; const last = capitalizeName(lastName);
if (!first || !last) return { code: 'n' };
if (first.length > MAX_NAME || last.length > MAX_NAME || `${first} ${last}`.length > MAX_NAME) return { code: 'l' };
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) return { code: 'p' };
try { try {
const email = normalizeEmail(emailRaw); const email = normalizeEmail(emailRaw);
if (email.length > MAX_EMAIL) return { code: 'e' }; if (email.length > MAX_EMAIL) return { code: 'e' };
return { firstName, lastName, email, phone: phoneRaw.length === 0 ? null : phoneRaw }; return { firstName: first, lastName: last, email, phone: phone.length === 0 ? null : phone };
} catch (err) { } catch (err) {
if (err instanceof EmailAddressError) return { code: 'e' }; if (err instanceof EmailAddressError) return { code: 'e' };
throw err; throw err;
+24
View File
@@ -0,0 +1,24 @@
/** Capitalizes a word that is all lower or all upper. A mixed-case word stays as written. */
export function capitalizeName(value: string): string {
const cleaned = value.normalize('NFC').trim().replace(/\s+/g, ' ');
return cleaned.replace(/\p{L}+/gu, (letters) => {
const lower = letters.toLocaleLowerCase('en-US');
const upper = letters.toLocaleUpperCase('en-US');
if (letters !== lower && letters !== upper) return letters;
const chars = [...lower];
const first = chars[0] ?? '';
return first.toLocaleUpperCase('en-US') + chars.slice(1).join('');
});
}
/**
* Writes a 10-digit number as 000-000-0000.
* A leading 1 is the country code and is dropped. Any other number stays as written.
*/
export function formatPhone(value: string): string {
const trimmed = value.normalize('NFC').trim();
const digits = trimmed.replace(/\D/g, '');
const national = digits.length === 11 && digits.startsWith('1') ? digits.slice(1) : digits;
if (national.length !== 10) return trimmed;
return `${national.slice(0, 3)}-${national.slice(3, 6)}-${national.slice(6)}`;
}
+15 -11
View File
@@ -1,5 +1,6 @@
import { z } from 'zod'; import { z } from 'zod';
import { EmailAddressError, normalizeEmail } from './email.js'; import { EmailAddressError, normalizeEmail } from './email.js';
import { capitalizeName, formatPhone } from './person-format.js';
const NAME_MAX = 80; const NAME_MAX = 80;
const PHONE_MAX = 40; const PHONE_MAX = 40;
@@ -58,11 +59,12 @@ export function parseSignupForm(
.safeParse(input); .safeParse(input);
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } }; if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
const errors: SignupErrors = {}; const errors: SignupErrors = {};
const name = parsed.data.name.normalize('NFC').trim(); const nameRaw = parsed.data.name.normalize('NFC').trim();
const name = capitalizeName(nameRaw);
const nameLabel = voice === 'coordinator' ? 'their name' : 'your name'; const nameLabel = voice === 'coordinator' ? 'their name' : 'your name';
if (name.length === 0) errors.name = `Enter ${nameLabel}.`; if (nameRaw.length === 0 || name.length === 0) errors.name = `Enter ${nameLabel}.`;
else if (name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`; else if (nameRaw.length > NAME_MAX || name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`;
else if (controlChars.test(name)) errors.name = `Enter ${nameLabel} without line breaks.`; else if (controlChars.test(nameRaw)) errors.name = `Enter ${nameLabel} without line breaks.`;
let emailNorm = ''; let emailNorm = '';
try { try {
@@ -71,9 +73,10 @@ export function parseSignupForm(
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.'; errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
} }
const phone = parsed.data.phone.normalize('NFC').trim(); const phoneRaw = parsed.data.phone.normalize('NFC').trim();
if (phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`; const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
else if (controlChars.test(phone)) errors.phone = 'Enter a phone number without line breaks.'; if (phoneRaw.length > PHONE_MAX || phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
else if (controlChars.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
const notes = parsed.data.notes.normalize('NFC').trim(); const notes = parsed.data.notes.normalize('NFC').trim();
if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`; if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`;
@@ -83,10 +86,11 @@ export function parseSignupForm(
let guardianEmail: string | null = null; let guardianEmail: string | null = null;
let guardianEmailNorm: string | null = null; let guardianEmailNorm: string | null = null;
if (parsed.data.under18) { if (parsed.data.under18) {
guardianName = parsed.data.guardianName.normalize('NFC').trim(); const guardianRaw = parsed.data.guardianName.normalize('NFC').trim();
if (guardianName.length === 0) errors.guardianName = 'Enter the guardian name.'; guardianName = capitalizeName(guardianRaw);
else if (guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`; if (guardianRaw.length === 0 || guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
else if (controlChars.test(guardianName)) errors.guardianName = 'Enter the guardian name without line breaks.'; else if (guardianRaw.length > NAME_MAX || guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
else if (controlChars.test(guardianRaw)) errors.guardianName = 'Enter the guardian name without line breaks.';
if (parsed.data.guardianEmail.trim() === '') { if (parsed.data.guardianEmail.trim() === '') {
errors.guardianEmail = 'Enter the guardian email.'; errors.guardianEmail = 'Enter the guardian email.';
} else { } else {
+2
View File
@@ -1,6 +1,7 @@
import { createHash, randomBytes } from 'node:crypto'; import { createHash, randomBytes } from 'node:crypto';
import { Temporal } from '@js-temporal/polyfill'; import { Temporal } from '@js-temporal/polyfill';
import type Database from 'better-sqlite3'; import type Database from 'better-sqlite3';
import { rememberSignupContact } from './contacts.js';
import { normalizeEmail } from './email.js'; import { normalizeEmail } from './email.js';
import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js'; import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
import type { MailIdentity } from './mail/types.js'; import type { MailIdentity } from './mail/types.js';
@@ -236,6 +237,7 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
mail: input.mail, mail: input.mail,
now: input.now, now: input.now,
}); });
rememberSignupContact(db, { name: input.name, email: emailNorm, phone: input.phone }, input.now);
input.onReserved?.(signupId); input.onReserved?.(signupId);
return { ok: true, signupId, manageToken, replay: false }; return { ok: true, signupId, manageToken, replay: false };
} }
+5
View File
@@ -55,6 +55,11 @@ describe('manage-link cancellation', () => {
expect(html).toContain('Pat Cancel'); expect(html).toContain('Pat Cancel');
expect(html).not.toContain('<form'); expect(html).not.toContain('<form');
expect(db.prepare('SELECT status FROM signups').all()).toEqual([{ status: 'cancelled' }]); expect(db.prepare('SELECT status FROM signups').all()).toEqual([{ status: 'cancelled' }]);
expect(db.prepare('SELECT first_name, last_name, email FROM contacts').get()).toEqual({
first_name: 'Pat',
last_name: 'Cancel',
email: 'pat.cancel@example.invalid',
});
expect(db.prepare("SELECT kind, status FROM outbox ORDER BY id").all()).toEqual([ expect(db.prepare("SELECT kind, status FROM outbox ORDER BY id").all()).toEqual([
{ kind: 'confirmation', status: 'cancelled' }, { kind: 'confirmation', status: 'cancelled' },
{ kind: 'cancelled', status: 'pending' }, { kind: 'cancelled', status: 'pending' },
+132 -11
View File
@@ -17,6 +17,7 @@ import {
contactListLimit, contactListLimit,
exportContacts, exportContacts,
importContactCsv, importContactCsv,
rememberSignupContact,
} from '../src/contacts.js'; } from '../src/contacts.js';
import { openAppDatabase } from '../src/db.js'; import { openAppDatabase } from '../src/db.js';
import { devEnv } from './env.js'; import { devEnv } from './env.js';
@@ -28,7 +29,7 @@ const databases: { close: () => void }[] = [];
const PEOPLE = [ const PEOPLE = [
'First Name,Last Name,Email,Phone,Address', 'First Name,Last Name,Email,Phone,Address',
'Kristi ,Anderson,Kristi@Example.invalid,712441076,123 Main', 'kristi ,ANDERSON,Kristi@Example.invalid,712441076,123 Main',
'Kara,Acevedo,kara@example.invalid,,', 'Kara,Acevedo,kara@example.invalid,,',
'Kara,Acevedo,kara.other@example.invalid,7125550100,456 Oak', 'Kara,Acevedo,kara.other@example.invalid,7125550100,456 Oak',
'Not An,Email,not-an-email,,', 'Not An,Email,not-an-email,,',
@@ -55,7 +56,7 @@ describe('contact spreadsheet', () => {
expect(rows).toEqual([ expect(rows).toEqual([
{ first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' }, { first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' },
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null }, { first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null },
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '7125550100' }, { first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '712-555-0100' },
]); ]);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0); expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0); expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
@@ -64,19 +65,37 @@ describe('contact spreadsheet', () => {
expect(audit.detail_json).not.toContain('@'); expect(audit.detail_json).not.toContain('@');
}); });
it('updates a name, replaces a phone, and leaves a blank phone in place', async () => { it('keeps two names that share an email and updates only the matching name', async () => {
const db = await openDb(); const db = await openDb();
importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW); importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW);
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW); const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW);
expect(renamed.ok && renamed.result.changed).toBe(1); expect(renamed.ok && renamed.result.added).toBe(1);
expect(db.prepare('SELECT last_name, phone FROM contacts').get()).toEqual({ last_name: 'Two', phone: '111' }); expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,222\n', NOW); { first_name: 'Ada', last_name: 'One', phone: '111' },
{ first_name: 'Ada', last_name: 'Two', phone: null },
]);
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nada,two,ada@example.invalid,(712) 555-0100\n', NOW);
expect(replaced.ok && replaced.result.changed).toBe(1); expect(replaced.ok && replaced.result.changed).toBe(1);
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '222' }); expect(db.prepare('SELECT phone FROM contacts ORDER BY id').all()).toEqual([{ phone: '111' }, { phone: '712-555-0100' }]);
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW); const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
expect(same.ok && same.result.unchanged).toBe(1); expect(same.ok && same.result.unchanged).toBe(1);
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '222' }); expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1); const shaped = importContactCsv(
db,
null,
'First Name,Last Name,Email,Phone\nMcDonald,O\'BRIEN,mac@example.invalid,17125550199\njohn,SMITH,john@example.invalid,712 555 0199\n',
NOW,
);
expect(shaped.ok && shaped.result.added).toBe(2);
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts WHERE email = ?').all('mac@example.invalid')).toEqual([
{ first_name: 'McDonald', last_name: "O'Brien", phone: '712-555-0199' },
]);
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts WHERE email = ?').get('john@example.invalid')).toEqual({
first_name: 'John',
last_name: 'Smith',
phone: '712-555-0199',
});
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(4);
}); });
it('round-trips a formula-looking name and a comma in the last name', async () => { it('round-trips a formula-looking name and a comma in the last name', async () => {
@@ -124,6 +143,33 @@ describe('contact spreadsheet', () => {
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
}); });
it('saves each signup name as its own contact and keeps a short phone as written', async () => {
const db = await openDb();
rememberSignupContact(db, { name: 'pat review', email: ' Pat@Example.invalid ', phone: '7125550199' }, NOW);
expect(db.prepare('SELECT first_name, last_name, email, phone FROM contacts').get()).toEqual({
first_name: 'Pat',
last_name: 'Review',
email: 'pat@example.invalid',
phone: '712-555-0199',
});
rememberSignupContact(db, { name: 'Pat', email: 'pat@example.invalid', phone: null }, NOW);
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
{ first_name: 'Pat', last_name: 'Review', phone: '712-555-0199' },
{ first_name: 'Pat', last_name: '-', phone: null },
]);
rememberSignupContact(db, { name: 'Sam', email: 'sam@example.invalid', phone: '' }, NOW);
rememberSignupContact(db, { name: 'sam other', email: 'sam@example.invalid', phone: null }, NOW);
expect(db.prepare("SELECT first_name, last_name, phone FROM contacts WHERE email = 'sam@example.invalid' ORDER BY id").all()).toEqual([
{ first_name: 'Sam', last_name: '-', phone: null },
{ first_name: 'Sam', last_name: 'Other', phone: null },
]);
rememberSignupContact(db, { name: 'PAT REVIEW', email: 'pat@example.invalid', phone: '555' }, NOW);
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Review'").get()).toEqual({ phone: '555' });
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(4);
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.manual'")).toBe(0);
});
it('starts the list at one page and ignores a smaller shown count', () => { it('starts the list at one page and ignores a smaller shown count', () => {
expect(contactListLimit(undefined)).toBe(CONTACT_LIST_PAGE); expect(contactListLimit(undefined)).toBe(CONTACT_LIST_PAGE);
expect(contactListLimit('5')).toBe(CONTACT_LIST_PAGE); expect(contactListLimit('5')).toBe(CONTACT_LIST_PAGE);
@@ -253,7 +299,12 @@ describe('contact pages', () => {
phone: '7125550199', phone: '7125550199',
}); });
expect(typed.status).toBe(303); expect(typed.status).toBe(303);
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
expect(db.prepare("SELECT first_name, last_name, phone FROM contacts WHERE email = 'pat@example.invalid'").get()).toEqual({
first_name: 'Pat',
last_name: 'Example',
phone: '712-555-0199',
});
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat@example.invalid'")).toBe(1); expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat@example.invalid'")).toBe(1);
const missing = await postWalkIn(app, cookie, shiftId, await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text(), { const missing = await postWalkIn(app, cookie, shiftId, await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text(), {
@@ -272,7 +323,7 @@ describe('contact pages', () => {
expect(removed.status).toBe(303); expect(removed.status).toBe(303);
const after = await app.request(removed.headers.get('location') ?? '', { headers: { cookie } }); const after = await app.request(removed.headers.get('location') ?? '', { headers: { cookie } });
expect(await after.text()).toContain('That person is removed from the contact list.'); expect(await after.text()).toContain('That person is removed from the contact list.');
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0); expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1);
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid' AND status = 'confirmed'")).toBe(1); expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid' AND status = 'confirmed'")).toBe(1);
const removeAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.remove'`).get() as { const removeAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.remove'`).get() as {
detail_json: string; detail_json: string;
@@ -411,6 +462,56 @@ describe('contact pages', () => {
expect(await again.text()).toContain('That person is already signed up for this shift.'); expect(await again.text()).toContain('That person is already signed up for this shift.');
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(1); expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(1);
}); });
it('saves one contact by hand and does not sign them up', async () => {
const { app, db } = await buildApp();
const loggedOut = await app.request('/admin/contacts/new', { method: 'POST' });
expect(loggedOut.status).toBe(303);
const cookie = await signIn(app, db);
const page = await app.request('/admin/contacts', { headers: { cookie } });
expect(await page.text()).toContain('Save this contact');
const saved = await postManual(app, cookie, { firstName: 'ada', lastName: 'example', email: 'Ada@Example.invalid', phone: '7125550100' });
expect(saved.status).toBe(303);
expect(saved.headers.get('location')).toBe('/admin/contacts?notice=contact-saved');
const after = await app.request(saved.headers.get('location') ?? '', { headers: { cookie } });
const afterHtml = await after.text();
expect(afterHtml).toContain('That contact is saved.');
expect(afterHtml).toContain('Ada Example');
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts').get()).toEqual({
first_name: 'Ada',
last_name: 'Example',
phone: '712-555-0100',
});
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'")).toBe(0);
const manualAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.manual'`).get() as { detail_json: string };
expect(manualAudit.detail_json).not.toContain('@');
const same = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Example', email: 'ada@example.invalid', phone: '' });
expect(same.headers.get('location')).toBe('/admin/contacts?notice=contact-matched');
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0100' });
const changed = await postManual(app, cookie, { firstName: 'ADA', lastName: 'EXAMPLE', email: 'ada@example.invalid', phone: '712-555-0199' });
expect(changed.status).toBe(303);
expect(changed.headers.get('location')).toBe('/admin/contacts?notice=contact-updated');
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0199' });
const other = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Other', email: 'ada@example.invalid', phone: '' });
expect(other.headers.get('location')).toBe('/admin/contacts?notice=contact-saved');
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
{ first_name: 'Ada', last_name: 'Example', phone: '712-555-0199' },
{ first_name: 'Ada', last_name: 'Other', phone: null },
]);
const invalid = await postManual(app, cookie, { firstName: '', lastName: 'Example', email: 'not-an-email', phone: '' });
expect(invalid.status).toBe(400);
const invalidHtml = await invalid.text();
expect(invalidHtml).toContain('Enter a first name.');
expect(invalidHtml).toContain('Enter an email address.');
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
expect(await (await app.request('/')).text()).not.toContain('ada@example.invalid');
});
}); });
async function openDb() { async function openDb() {
@@ -569,6 +670,26 @@ async function postContactShift(
}); });
} }
async function postManual(
app: Awaited<ReturnType<typeof buildApp>>['app'],
cookie: string,
fields: { firstName: string; lastName: string; email: string; phone?: string },
) {
const current = await app.request('/admin/contacts', { headers: { cookie } });
const token = /name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? '';
return app.request('/admin/contacts/new', {
method: 'POST',
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
body: new URLSearchParams({
csrf: token,
first_name: fields.firstName,
last_name: fields.lastName,
email: fields.email,
phone: fields.phone ?? '',
}),
});
}
async function postRemove(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, pathName: string) { async function postRemove(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, pathName: string) {
const current = await app.request(pathName, { headers: { cookie } }); const current = await app.request(pathName, { headers: { cookie } });
const token = /name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? ''; const token = /name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? '';
+18 -4
View File
@@ -28,7 +28,7 @@ afterEach(() => {
describe('capacity-safe signup', () => { describe('capacity-safe signup', () => {
it('saves one person, shows a private confirmation link, and does not send mail', async () => { it('saves one person, shows a private confirmation link, and does not send mail', async () => {
const { app, shiftId, db } = await buildApp(); const { app, shiftId, db } = await buildApp();
const response = await postSignup(app, shiftId, { name: 'Pat Review', email: ' Pat.Review@Example.invalid ', phone: '712-555-0199', notes: '<script>alert(1)</script>' }); const response = await postSignup(app, shiftId, { name: 'pat review', email: ' Pat.Review@Example.invalid ', phone: '7125550199', notes: '<script>alert(1)</script>' });
expect(response.status).toBe(303); expect(response.status).toBe(303);
const cookie = response.headers.get('set-cookie') ?? ''; const cookie = response.headers.get('set-cookie') ?? '';
expect(cookie).toContain('HttpOnly'); expect(cookie).toContain('HttpOnly');
@@ -53,7 +53,17 @@ describe('capacity-safe signup', () => {
expect(manageHtml).toContain('Cancel this signup'); expect(manageHtml).toContain('Cancel this signup');
expect(manageHtml).toContain('name="cancel_token"'); expect(manageHtml).toContain('name="cancel_token"');
expect(manageHtml).not.toContain('challenges.cloudflare.com'); expect(manageHtml).not.toContain('challenges.cloudflare.com');
expect(db.prepare("SELECT status FROM signups").get()).toEqual({ status: 'confirmed' }); expect(db.prepare('SELECT name, phone, status FROM signups').get()).toEqual({
name: 'Pat Review',
phone: '712-555-0199',
status: 'confirmed',
});
expect(db.prepare('SELECT first_name, last_name, email, phone FROM contacts').get()).toEqual({
first_name: 'Pat',
last_name: 'Review',
email: 'pat.review@example.invalid',
phone: '712-555-0199',
});
expect(manage.headers.get('cache-control')).toBe('no-store'); expect(manage.headers.get('cache-control')).toBe('no-store');
const again = await postSignup(app, shiftId, { name: 'Pat Review', email: 'pat.review@example.invalid' }, { ip: '203.0.113.21' }); const again = await postSignup(app, shiftId, { name: 'Pat Review', email: 'pat.review@example.invalid' }, { ip: '203.0.113.21' });
@@ -77,6 +87,10 @@ describe('capacity-safe signup', () => {
{ name: 'Sam Review', email_norm: 'home@example.invalid' }, { name: 'Sam Review', email_norm: 'home@example.invalid' },
]); ]);
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'home@example.invalid'").get()).toEqual({ n: 2 }); expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'home@example.invalid'").get()).toEqual({ n: 2 });
expect(db.prepare('SELECT first_name, last_name, email FROM contacts ORDER BY id').all()).toEqual([
{ first_name: 'Pat', last_name: 'Review', email: 'home@example.invalid' },
{ first_name: 'Sam', last_name: 'Review', email: 'home@example.invalid' },
]);
const again = await postSignup(app, shiftId, { name: 'sam review', email: 'home@example.invalid' }, { ip: '203.0.113.93' }); const again = await postSignup(app, shiftId, { name: 'sam review', email: 'home@example.invalid' }, { ip: '203.0.113.93' });
expect(again.status).toBe(409); expect(again.status).toBe(409);
expect(await again.text()).toContain('That person is already signed up for this shift.'); expect(await again.text()).toContain('That person is already signed up for this shift.');
@@ -112,10 +126,10 @@ describe('capacity-safe signup', () => {
app, app,
shiftId, shiftId,
{ {
name: 'Minor Pat', name: 'minor pat',
email: 'minor@example.invalid', email: 'minor@example.invalid',
under18: true, under18: true,
guardianName: 'Guardian Pat', guardianName: 'guardian pat',
guardianEmail: 'Guardian.Pat@Example.invalid', guardianEmail: 'Guardian.Pat@Example.invalid',
}, },
{ ip: '203.0.113.42' }, { ip: '203.0.113.42' },