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

+34 -2
View File
@@ -86,8 +86,11 @@ import {
loadContacts,
parseContactSkips,
removeContact,
saveManualContact,
walkInFromContact,
type ContactImportSummary,
type ContactManualErrors,
type ContactManualValues,
} from './contacts.js';
import { dateStamp, exportDateRange, exportEventRoster, exportShiftRoster } from './export.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/export'), (c) => submitExportRange(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/export'), (c) => submitExportContacts(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(
c: Context,
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);
if (session instanceof Response) return session;
@@ -362,12 +371,32 @@ function showContacts(
notice={options?.error ? undefined : knownNotice(c.req.query('notice'))}
summary={options?.error ? undefined : contactSummary(c)}
importError={options?.error}
manual={options?.manual}
confirm={options?.confirm}
/>,
{ 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> {
const session = await postedSession(c, services);
if (session instanceof Response) return session;
@@ -1452,7 +1481,10 @@ function knownNotice(value: string | undefined): string | undefined {
value === 'template-removed' ||
value === 'event-removed' ||
value === 'settings-saved' ||
value === 'contact-removed'
value === 'contact-removed' ||
value === 'contact-saved' ||
value === 'contact-updated' ||
value === 'contact-matched'
) {
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 { SettingsErrors, SettingsForm } from './settings.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 { addLocalDays, todayInZone } from './time.js';
import { appPath } from './url.js';
@@ -315,8 +323,10 @@ export function ContactsPage(props: {
notice?: string;
summary?: ContactImportSummary;
importError?: string;
manual?: { values: ContactManualValues; errors: ContactManualErrors };
confirm?: ConfirmPrompt;
}) {
const manual = props.manual ?? { values: { firstName: '', lastName: '', email: '', phone: '' }, errors: {} };
const heading =
props.total === 0
? 'Saved contacts'
@@ -343,13 +353,23 @@ export function ContactsPage(props: {
) : null}
{hiddenSkips > 0 ? <p class="panel-note">{hiddenSkips === 1 ? '1 more row was skipped.' : `${hiddenSkips} more rows were skipped.`}</p> : null}
<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>
<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">
<input type="hidden" name="csrf" value={props.csrf} />
<h2>Import a contact list</h2>
<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>
{props.importError ? <p class="error">{props.importError}</p> : null}
<label>
@@ -1330,7 +1350,7 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
))}
</select>
<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>
</label>
) : null}
@@ -1591,6 +1611,9 @@ const NOTICES: Record<string, string> = {
'event-removed': 'That event is removed.',
'settings-saved': 'Settings saved.',
'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;
+158 -27
View File
@@ -2,7 +2,9 @@ import type Database from 'better-sqlite3';
import { writeAudit } from './auth/audit.js';
import { EmailAddressError, normalizeEmail } from './email.js';
import { csvCell, csvImportedCell } from './export.js';
import { capitalizeName, formatPhone } from './person-format.js';
import type { SignupValues } from './signup-form.js';
import { isUniqueConstraint } from './sqlite-error.js';
const MAX_ROWS = 2000;
export const CONTACT_LIST_PAGE = 20;
@@ -48,6 +50,15 @@ type ReadyContact = {
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 = {
id: number;
first_name: string;
@@ -139,34 +150,14 @@ export function importContactCsv(
}
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 changed = 0;
let unchanged = 0;
for (const person of ready) {
const existing = find.get(person.email) as { first_name: string; last_name: string; phone: string | null } | undefined;
if (!existing) {
insert.run(person.firstName, person.lastName, person.email, person.email, person.phone, now, now);
added += 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;
const saved = applyContact(db, person, now);
if (saved.status === 'added') added += 1;
else if (saved.status === 'changed') changed += 1;
else unchanged += 1;
}
writeAudit(db, coordinatorId, 'contacts.import', { added, changed, unchanged, skipped: skips.length }, now);
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. */
export function walkInFromContact(contact: Contact, values: SignupValues): SignupValues {
return {
@@ -272,6 +307,98 @@ function columnIndex(cells: string[]): { first: number; last: number; email: num
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 } {
const firstName = cellAt(cells, columns.first);
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);
if (!firstName || !lastName) return { code: 'n' };
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' };
if (phoneRaw.length > MAX_PHONE) return { code: 'p' };
const first = capitalizeName(firstName);
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 {
const email = normalizeEmail(emailRaw);
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) {
if (err instanceof EmailAddressError) return { code: 'e' };
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 { EmailAddressError, normalizeEmail } from './email.js';
import { capitalizeName, formatPhone } from './person-format.js';
const NAME_MAX = 80;
const PHONE_MAX = 40;
@@ -58,11 +59,12 @@ export function parseSignupForm(
.safeParse(input);
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
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';
if (name.length === 0) errors.name = `Enter ${nameLabel}.`;
else if (name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`;
else if (controlChars.test(name)) errors.name = `Enter ${nameLabel} without line breaks.`;
if (nameRaw.length === 0 || name.length === 0) errors.name = `Enter ${nameLabel}.`;
else if (nameRaw.length > NAME_MAX || name.length > NAME_MAX) errors.name = `Use ${NAME_MAX} characters or fewer.`;
else if (controlChars.test(nameRaw)) errors.name = `Enter ${nameLabel} without line breaks.`;
let emailNorm = '';
try {
@@ -71,9 +73,10 @@ export function parseSignupForm(
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
}
const phone = parsed.data.phone.normalize('NFC').trim();
if (phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
else if (controlChars.test(phone)) errors.phone = 'Enter a phone number without line breaks.';
const phoneRaw = parsed.data.phone.normalize('NFC').trim();
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
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();
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 guardianEmailNorm: string | null = null;
if (parsed.data.under18) {
guardianName = parsed.data.guardianName.normalize('NFC').trim();
if (guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
else if (guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
else if (controlChars.test(guardianName)) errors.guardianName = 'Enter the guardian name without line breaks.';
const guardianRaw = parsed.data.guardianName.normalize('NFC').trim();
guardianName = capitalizeName(guardianRaw);
if (guardianRaw.length === 0 || guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
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() === '') {
errors.guardianEmail = 'Enter the guardian email.';
} else {
+2
View File
@@ -1,6 +1,7 @@
import { createHash, randomBytes } from 'node:crypto';
import { Temporal } from '@js-temporal/polyfill';
import type Database from 'better-sqlite3';
import { rememberSignupContact } from './contacts.js';
import { normalizeEmail } from './email.js';
import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
import type { MailIdentity } from './mail/types.js';
@@ -236,6 +237,7 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
mail: input.mail,
now: input.now,
});
rememberSignupContact(db, { name: input.name, email: emailNorm, phone: input.phone }, input.now);
input.onReserved?.(signupId);
return { ok: true, signupId, manageToken, replay: false };
}