feat: add a coordinator contact list
Saved people can be imported and added to an open shift without becoming a signup on import. Real mail is set up to use SMTP2GO once the API key and sender are configured.
This commit is contained in:
1 parent
f1a46e2ba7
commit
e8a5f9e352
20 files changed
+1857
-40
No files matched your search
+294
-9
@@ -38,6 +38,7 @@ import {
|
||||
readSignupRemoval,
|
||||
readTemplateRemoval,
|
||||
listMoveTargets,
|
||||
listOpenShiftsForPerson,
|
||||
moveSignup,
|
||||
setAttendance,
|
||||
updateEvent,
|
||||
@@ -59,6 +60,9 @@ import {
|
||||
templateEndPrompt,
|
||||
templateRemovalPrompt,
|
||||
type ConfirmPrompt,
|
||||
contactRemovalPrompt,
|
||||
ContactPage,
|
||||
ContactsPage,
|
||||
SettingsPage,
|
||||
ShiftEditor,
|
||||
ShiftRoster,
|
||||
@@ -73,6 +77,18 @@ import type { AppConfig } from './config.js';
|
||||
import { normalizeEmail } from './email.js';
|
||||
import type { MailIdentity } from './mail/types.js';
|
||||
import { issueFormToken, newOperationId, readFormToken } from './form-token.js';
|
||||
import {
|
||||
contactListLimit,
|
||||
exportContacts,
|
||||
formatContactSkips,
|
||||
getContact,
|
||||
importContactCsv,
|
||||
loadContacts,
|
||||
parseContactSkips,
|
||||
removeContact,
|
||||
walkInFromContact,
|
||||
type ContactImportSummary,
|
||||
} from './contacts.js';
|
||||
import { dateStamp, exportDateRange, exportEventRoster, exportShiftRoster } from './export.js';
|
||||
import { originAllowed } from './origin.js';
|
||||
import {
|
||||
@@ -87,6 +103,7 @@ import {
|
||||
import { expandTemplates } from './recurrence.js';
|
||||
import { Layout } from './pages.js';
|
||||
import { EMPTY_SIGNUP, parseSignupForm, type SignupValues } from './signup-form.js';
|
||||
import { confirmedPersonOnShift } from './signup.js';
|
||||
import { recordInvalidLoginToken, recordLoginEmail, recordLoginIp } from './rate-limit.js';
|
||||
import { isBusy } from './sqlite-error.js';
|
||||
import { verifyTurnstile, type TurnstileCheck, type TurnstileVerdict } from './turnstile.js';
|
||||
@@ -121,6 +138,13 @@ export function registerAdmin(app: Hono, services: AdminServices): void {
|
||||
app.get(appPath(config, '/admin/settings'), (c) => showSettings(c, services));
|
||||
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/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));
|
||||
app.post(appPath(config, '/admin/contacts/:id/remove'), (c) => submitRemoveContact(c, services));
|
||||
app.post(appPath(config, '/admin/contacts/:id/add'), (c) => submitAddContactToShift(c, services));
|
||||
app.get(appPath(config, '/admin/contacts/:id'), (c) => showContact(c, services));
|
||||
app.get(appPath(config, '/admin/events/new'), (c) => showNewEvent(c, services));
|
||||
app.post(appPath(config, '/admin/events'), (c) => submitNewEvent(c, services));
|
||||
app.get(appPath(config, '/admin/events/:id/remove'), (c) => showRemoveEvent(c, services));
|
||||
@@ -316,6 +340,192 @@ async function submitExportShift(c: Context, services: AdminServices): Promise<R
|
||||
return csvDownload(c, `hope-shift-${shiftId}.csv`, exported.csv);
|
||||
}
|
||||
|
||||
function showContacts(
|
||||
c: Context,
|
||||
services: AdminServices,
|
||||
options?: { error?: string; status?: 200 | 400 | 403; confirm?: ConfirmPrompt },
|
||||
) {
|
||||
const session = requireSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const loaded = loadContacts(services.db, c.req.query('q') ?? '');
|
||||
return html(
|
||||
c,
|
||||
services,
|
||||
'Contacts · Hope Volunteer',
|
||||
<ContactsPage
|
||||
config={services.config}
|
||||
csrf={session.csrf}
|
||||
people={loaded.people}
|
||||
total={loaded.total}
|
||||
query={loaded.query}
|
||||
limit={contactListLimit(c.req.query('shown'))}
|
||||
notice={options?.error ? undefined : knownNotice(c.req.query('notice'))}
|
||||
summary={options?.error ? undefined : contactSummary(c)}
|
||||
importError={options?.error}
|
||||
confirm={options?.confirm}
|
||||
/>,
|
||||
{ account: session, status: options?.status ?? 200 },
|
||||
);
|
||||
}
|
||||
|
||||
async function submitImportContacts(c: Context, services: AdminServices): Promise<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const text = await csvFromField(session.body.file);
|
||||
if (text === null) return showContacts(c, services, { error: 'Choose a spreadsheet to import.', status: 400 });
|
||||
try {
|
||||
const imported = importContactCsv(services.db, session.coordinatorId, text, services.now());
|
||||
if (!imported.ok) return showContacts(c, services, { error: imported.error, status: 400 });
|
||||
return c.redirect(importLocation(services.config, imported.result), 303);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitExportContacts(c: Context, services: AdminServices): Promise<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const exported = exportContacts(services.db);
|
||||
writeAudit(services.db, session.coordinatorId, 'contacts.export', { rows: exported.rows }, services.now());
|
||||
return csvDownload(c, 'hope-contacts.csv', exported.csv);
|
||||
}
|
||||
|
||||
function showRemoveContact(c: Context, services: AdminServices, error?: string, status: 200 | 400 | 403 = 200) {
|
||||
const session = requireSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const contact = getContact(services.db, idFrom(c));
|
||||
if (!contact) return missing(c, services);
|
||||
const prompt = contactRemovalPrompt(contact);
|
||||
return showContacts(c, services, {
|
||||
status,
|
||||
confirm: {
|
||||
...prompt,
|
||||
body: error && error !== prompt.body ? error : prompt.body,
|
||||
submit: error ? undefined : prompt.submit,
|
||||
error: error && error !== prompt.body ? error : undefined,
|
||||
action: appPath(services.config, `/admin/contacts/${contact.id}/remove`),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function showContact(
|
||||
c: Context,
|
||||
services: AdminServices,
|
||||
state?: { error?: string; status?: 200 | 400; form?: WalkInState; shiftId?: string },
|
||||
) {
|
||||
const session = requireSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const contact = getContact(services.db, idFrom(c));
|
||||
if (!contact) return missing(c, services);
|
||||
return html(
|
||||
c,
|
||||
services,
|
||||
`${contact.name} · Hope Volunteer`,
|
||||
<ContactPage
|
||||
config={services.config}
|
||||
csrf={session.csrf}
|
||||
contact={contact}
|
||||
shifts={listOpenShiftsForPerson(services.db, { email: contact.email, name: contact.name }, services.now())}
|
||||
form={state?.form ?? blankWalkIn(services, contact.id)}
|
||||
shiftId={state?.shiftId ?? ''}
|
||||
error={state?.error}
|
||||
/>,
|
||||
{ account: session, status: state?.status ?? 200 },
|
||||
);
|
||||
}
|
||||
|
||||
function contactShiftUnavailable(c: Context, services: AdminServices, email: string, name: string, shiftId: number, form: WalkInState) {
|
||||
const already = shiftId > 0 && confirmedPersonOnShift(services.db, shiftId, email, name);
|
||||
return showContact(c, services, {
|
||||
error: already ? 'That person is already signed up for this shift.' : 'That shift is not open.',
|
||||
status: 400,
|
||||
form,
|
||||
shiftId: '',
|
||||
});
|
||||
}
|
||||
|
||||
async function submitAddContactToShift(c: Context, services: AdminServices): Promise<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const contact = getContact(services.db, idFrom(c));
|
||||
if (!contact) return missing(c, services);
|
||||
const shiftId = wholeId(textField(session.body, 'shift'));
|
||||
const entered = signupValuesFrom(session.body);
|
||||
const filled = walkInFromContact(contact, { ...entered, name: '', email: '', phone: '' });
|
||||
const postedToken = textField(session.body, 'form_token');
|
||||
if (shiftId === 0) {
|
||||
return showContact(c, services, {
|
||||
error: 'Choose a shift.',
|
||||
status: 400,
|
||||
form: blankWalkIn(services, contact.id, filled),
|
||||
shiftId: '',
|
||||
});
|
||||
}
|
||||
const shift = listOpenShiftsForPerson(services.db, { email: contact.email, name: contact.name }, services.now()).find(
|
||||
(choice) => choice.id === shiftId,
|
||||
);
|
||||
if (!shift) return contactShiftUnavailable(c, services, contact.email, contact.name, shiftId, blankWalkIn(services, contact.id, filled));
|
||||
// Bound to this contact. The shift is the Shift field, so one token covers every choice in the menu.
|
||||
const token = readFormToken(services.config.sessionSecret, postedToken, contact.id, Date.parse(services.now()), 0);
|
||||
if (!token.ok) {
|
||||
return showContact(c, services, {
|
||||
status: 400,
|
||||
form: blankWalkIn(services, contact.id, filled, {}, 'This form is out of date. Submit it again.'),
|
||||
shiftId: String(shiftId),
|
||||
});
|
||||
}
|
||||
const parsed = parseSignupForm(filled, 'coordinator');
|
||||
if (!parsed.ok) {
|
||||
return showContact(c, services, {
|
||||
status: 400,
|
||||
form: blankWalkIn(services, contact.id, filled, parsed.errors),
|
||||
shiftId: String(shiftId),
|
||||
});
|
||||
}
|
||||
try {
|
||||
const saved = addWalkIn(services.db, session.coordinatorId, {
|
||||
shiftId,
|
||||
name: parsed.draft.name,
|
||||
email: parsed.draft.emailNorm,
|
||||
phone: parsed.draft.phone,
|
||||
notes: parsed.draft.notes,
|
||||
isMinor: parsed.draft.isMinor,
|
||||
guardianName: parsed.draft.guardianName,
|
||||
guardianEmail: parsed.draft.guardianEmail,
|
||||
operationId: token.claims.operationId,
|
||||
now: services.now(),
|
||||
mail: mailIdentity(services.db, services.config),
|
||||
});
|
||||
if (saved.ok) return c.redirect(appPath(services.config, `/admin/shifts/${shiftId}?notice=walk-in`), 303);
|
||||
if (saved.reason === 'duplicate') {
|
||||
return showContact(c, services, { error: 'That person is already signed up for this shift.', status: 400 });
|
||||
}
|
||||
if (saved.reason === 'not_found' || saved.reason === 'closed' || saved.reason === 'full') {
|
||||
return showContact(c, services, { error: 'That shift is not open.', status: 400 });
|
||||
}
|
||||
return showContact(c, services, {
|
||||
status: 400,
|
||||
form: blankWalkIn(services, contact.id, filled, {}, 'This form was already used for a different signup. Submit it again.'),
|
||||
shiftId: String(shiftId),
|
||||
});
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
}
|
||||
|
||||
async function submitRemoveContact(c: Context, services: AdminServices): Promise<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
const id = idFrom(c);
|
||||
try {
|
||||
const removed = removeContact(services.db, session.coordinatorId, id, services.now());
|
||||
if (!removed) return missing(c, services);
|
||||
return c.redirect(appPath(services.config, '/admin/contacts?notice=contact-removed'), 303);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
}
|
||||
|
||||
function csvDownload(c: Context, filename: string, csv: string): Response {
|
||||
return c.body(new TextEncoder().encode(csv), 200, {
|
||||
'Cache-Control': 'no-store',
|
||||
@@ -870,6 +1080,7 @@ function showShift(
|
||||
const now = services.now();
|
||||
const ended = !shift.cancelled && shift.endsAtUtc <= now;
|
||||
const full = !ended && !shift.cancelled && shift.occupied >= shift.capacity;
|
||||
const showWalkIn = !shift.cancelled && !ended && !full;
|
||||
const walkInNote = ended ? 'This shift has ended.' : full ? 'This shift is full.' : undefined;
|
||||
const confirmed = shift.people.some((person) => person.status === 'confirmed');
|
||||
const targets = confirmed ? listMoveTargets(services.db, shift.eventId, shift.id, now) : [];
|
||||
@@ -895,8 +1106,9 @@ function showShift(
|
||||
removable={shift.cancelled || shift.endsAtUtc <= now}
|
||||
notice={knownNotice(c.req.query('notice'))}
|
||||
error={error}
|
||||
walkIn={!shift.cancelled && !ended && !full ? (walkIn ?? blankWalkIn(services, shift.id)) : undefined}
|
||||
walkIn={showWalkIn ? (walkIn ?? blankWalkIn(services, shift.id)) : undefined}
|
||||
walkInNote={walkInNote}
|
||||
contacts={showWalkIn ? loadContacts(services.db, '').people : []}
|
||||
moves={confirmed ? { targets, tokens } : undefined}
|
||||
confirm={confirm}
|
||||
/>,
|
||||
@@ -910,19 +1122,25 @@ async function submitWalkIn(c: Context, services: AdminServices): Promise<Respon
|
||||
const id = idFrom(c);
|
||||
const shift = getAdminShift(services.db, id);
|
||||
if (!shift) return missing(c, services);
|
||||
const values = signupValuesFrom(session.body);
|
||||
const contactId = textField(session.body, 'contact').trim();
|
||||
const entered = signupValuesFrom(session.body);
|
||||
if (shift.cancelled || shift.endsAtUtc <= services.now()) return showShift(c, services, undefined, 400);
|
||||
if (shift.occupied >= shift.capacity) return showShift(c, services, undefined, 400);
|
||||
const token = readFormToken(services.config.sessionSecret, textField(session.body, 'form_token'), id, Date.parse(services.now()), 0);
|
||||
if (!token.ok) {
|
||||
return showShift(c, services, undefined, 400, blankWalkIn(services, id, values, {}, 'This form is out of date. Submit it again.'));
|
||||
return showShift(c, services, undefined, 400, blankWalkIn(services, id, entered, {}, 'This form is out of date. Submit it again.', contactId));
|
||||
}
|
||||
const parsed = parseSignupForm(values, 'coordinator');
|
||||
const filled = applySavedContact(services.db, contactId, entered);
|
||||
if (!filled.ok) {
|
||||
return showShift(c, services, undefined, 400, blankWalkIn(services, id, entered, {}, 'That saved contact is not available.', contactId));
|
||||
}
|
||||
const parsed = parseSignupForm(filled.values, 'coordinator');
|
||||
if (!parsed.ok) {
|
||||
return showShift(c, services, undefined, 400, {
|
||||
token: textField(session.body, 'form_token'),
|
||||
values,
|
||||
values: filled.values,
|
||||
errors: parsed.errors,
|
||||
contactId,
|
||||
});
|
||||
}
|
||||
try {
|
||||
@@ -945,8 +1163,9 @@ async function submitWalkIn(c: Context, services: AdminServices): Promise<Respon
|
||||
if (saved.reason === 'duplicate') {
|
||||
return showShift(c, services, undefined, 400, {
|
||||
token: textField(session.body, 'form_token'),
|
||||
values,
|
||||
values: filled.values,
|
||||
errors: { email: 'That person is already signed up for this shift.' },
|
||||
contactId,
|
||||
});
|
||||
}
|
||||
return showShift(
|
||||
@@ -954,7 +1173,7 @@ async function submitWalkIn(c: Context, services: AdminServices): Promise<Respon
|
||||
services,
|
||||
undefined,
|
||||
400,
|
||||
blankWalkIn(services, id, values, {}, 'This form was already used for a different signup. Submit it again.'),
|
||||
blankWalkIn(services, id, filled.values, {}, 'This form was already used for a different signup. Submit it again.', contactId),
|
||||
);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
@@ -1232,14 +1451,22 @@ function knownNotice(value: string | undefined): string | undefined {
|
||||
value === 'shifts-removed' ||
|
||||
value === 'template-removed' ||
|
||||
value === 'event-removed' ||
|
||||
value === 'settings-saved'
|
||||
value === 'settings-saved' ||
|
||||
value === 'contact-removed'
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function blankWalkIn(services: AdminServices, shiftId: number, values: SignupValues = EMPTY_SIGNUP, errors: WalkInState['errors'] = {}, message?: string): WalkInState {
|
||||
function blankWalkIn(
|
||||
services: AdminServices,
|
||||
shiftId: number,
|
||||
values: SignupValues = EMPTY_SIGNUP,
|
||||
errors: WalkInState['errors'] = {},
|
||||
message?: string,
|
||||
contactId = '',
|
||||
): WalkInState {
|
||||
return {
|
||||
token: issueFormToken(services.config.sessionSecret, {
|
||||
shiftId,
|
||||
@@ -1249,6 +1476,7 @@ function blankWalkIn(services: AdminServices, shiftId: number, values: SignupVal
|
||||
values,
|
||||
errors,
|
||||
message,
|
||||
contactId,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1272,6 +1500,12 @@ function idFrom(c: Context): number {
|
||||
return paramId(c, 'id');
|
||||
}
|
||||
|
||||
function wholeId(value: string): number {
|
||||
if (!/^[1-9][0-9]*$/.test(value)) return 0;
|
||||
const id = Number(value);
|
||||
return Number.isSafeInteger(id) ? id : 0;
|
||||
}
|
||||
|
||||
function templateIdFrom(c: Context): number {
|
||||
return paramId(c, 'templateId');
|
||||
}
|
||||
@@ -1288,6 +1522,57 @@ function textField(body: Record<string, unknown>, name: string): string {
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function applySavedContact(
|
||||
db: Database.Database,
|
||||
contactId: string,
|
||||
values: SignupValues,
|
||||
): { ok: true; values: SignupValues } | { ok: false } {
|
||||
if (contactId === '') return { ok: true, values };
|
||||
if (!/^[1-9][0-9]*$/.test(contactId)) return { ok: false };
|
||||
const id = Number(contactId);
|
||||
if (!Number.isSafeInteger(id)) return { ok: false };
|
||||
const contact = getContact(db, id);
|
||||
if (!contact) return { ok: false };
|
||||
return { ok: true, values: walkInFromContact(contact, values) };
|
||||
}
|
||||
|
||||
function contactSummary(c: Context): ContactImportSummary | undefined {
|
||||
if (c.req.query('notice') !== 'contacts-imported') return undefined;
|
||||
const added = wholeNumber(c.req.query('added'));
|
||||
const changed = wholeNumber(c.req.query('changed'));
|
||||
const unchanged = wholeNumber(c.req.query('unchanged'));
|
||||
const skipped = wholeNumber(c.req.query('skipped'));
|
||||
if (added === null || changed === null || unchanged === null || skipped === null) return undefined;
|
||||
return { added, changed, unchanged, skipped, skips: parseContactSkips(c.req.query('skip')) };
|
||||
}
|
||||
|
||||
function wholeNumber(value: string | undefined): number | null {
|
||||
if (value === undefined || value === '') return 0;
|
||||
if (!/^\d{1,6}$/.test(value)) return null;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function importLocation(config: AppConfig, result: ContactImportSummary): string {
|
||||
const params = new URLSearchParams({
|
||||
notice: 'contacts-imported',
|
||||
added: String(result.added),
|
||||
changed: String(result.changed),
|
||||
unchanged: String(result.unchanged),
|
||||
skipped: String(result.skipped),
|
||||
});
|
||||
const skip = formatContactSkips(result.skips);
|
||||
if (skip) params.set('skip', skip);
|
||||
return appPath(config, `/admin/contacts?${params.toString()}`);
|
||||
}
|
||||
|
||||
async function csvFromField(value: unknown): Promise<string | null> {
|
||||
if (typeof value === 'string') return value;
|
||||
if (Array.isArray(value)) return csvFromField(value[0]);
|
||||
if (typeof Blob !== 'undefined' && value instanceof Blob) return value.text();
|
||||
return null;
|
||||
}
|
||||
|
||||
function idList(body: Record<string, unknown>, name: string): number[] | null {
|
||||
const value = body[name];
|
||||
if (value === undefined) return [];
|
||||
|
||||
+237
-5
@@ -4,6 +4,7 @@ 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 type { SignupErrors, SignupValues } from './signup-form.js';
|
||||
import { addLocalDays, todayInZone } from './time.js';
|
||||
import { appPath } from './url.js';
|
||||
@@ -13,6 +14,7 @@ export type WalkInState = {
|
||||
values: SignupValues;
|
||||
errors: SignupErrors;
|
||||
message?: string;
|
||||
contactId?: string;
|
||||
};
|
||||
|
||||
export type ConfirmPrompt = {
|
||||
@@ -118,6 +120,15 @@ export function templateEndPrompt(template: { role: string; weekday: number; act
|
||||
return { title, body: TEMPLATE_END_BODY, submit: 'End this template' };
|
||||
}
|
||||
|
||||
export function contactRemovalPrompt(contact: { name: string; email: string }): Omit<ConfirmPrompt, 'action'> {
|
||||
return {
|
||||
title: `Remove ${contact.name}`,
|
||||
detail: contact.email,
|
||||
body: 'This deletes their name, email, and phone from the contact list. It does not cancel a signup and it does not send email.',
|
||||
submit: 'Remove this contact',
|
||||
};
|
||||
}
|
||||
|
||||
export function templateRemovalPrompt(
|
||||
template: { role: string; weekday: number; active: boolean },
|
||||
error?: string,
|
||||
@@ -180,6 +191,9 @@ export function AdminHome(props: {
|
||||
<a class="btn" href={appPath(props.config, '/admin/events/new')} data-open-event>
|
||||
New event
|
||||
</a>
|
||||
<a class="btn btn-quiet" href={appPath(props.config, '/admin/contacts')}>
|
||||
Contacts
|
||||
</a>
|
||||
<a class="btn btn-quiet" href={appPath(props.config, '/admin/settings')}>
|
||||
Settings
|
||||
</a>
|
||||
@@ -284,6 +298,197 @@ export function SettingsPage(props: {
|
||||
);
|
||||
}
|
||||
|
||||
function contactListHref(config: AppConfig, query: string, shown: number): string {
|
||||
const params = new URLSearchParams();
|
||||
if (query) params.set('q', query);
|
||||
params.set('shown', String(shown));
|
||||
return `${appPath(config, '/admin/contacts')}?${params.toString()}#contact-more`;
|
||||
}
|
||||
|
||||
export function ContactsPage(props: {
|
||||
config: AppConfig;
|
||||
csrf: string;
|
||||
people: Contact[];
|
||||
total: number;
|
||||
query: string;
|
||||
limit: number;
|
||||
notice?: string;
|
||||
summary?: ContactImportSummary;
|
||||
importError?: string;
|
||||
confirm?: ConfirmPrompt;
|
||||
}) {
|
||||
const heading =
|
||||
props.total === 0
|
||||
? 'Saved contacts'
|
||||
: props.query
|
||||
? `${props.people.length} of ${props.total}`
|
||||
: props.total === 1
|
||||
? '1 person'
|
||||
: `${props.total} people`;
|
||||
const hiddenSkips = props.summary ? Math.max(0, props.summary.skipped - props.summary.skips.length) : 0;
|
||||
const moreHref = contactListHref(props.config, props.query, props.limit + CONTACT_LIST_PAGE);
|
||||
return (
|
||||
<>
|
||||
<p>
|
||||
<a href={appPath(props.config, '/admin')}>Coordinator</a>
|
||||
</p>
|
||||
<h1>Contacts</h1>
|
||||
{props.summary ? <Notice text={contactImportSentence(props.summary)} /> : <Notice notice={props.notice} />}
|
||||
{props.summary && props.summary.skips.length > 0 ? (
|
||||
<ul>
|
||||
{props.summary.skips.map((skip) => (
|
||||
<li key={skip.line}>{contactSkipSentence(skip)}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : 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.
|
||||
</p>
|
||||
<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.
|
||||
</p>
|
||||
{props.importError ? <p class="error">{props.importError}</p> : null}
|
||||
<label>
|
||||
Spreadsheet
|
||||
<input name="file" type="file" accept=".csv,text/csv,text/plain" required />
|
||||
</label>
|
||||
<button type="submit">Import this list</button>
|
||||
</form>
|
||||
<form method="post" action={appPath(props.config, '/admin/contacts/export')} class="signup-form desk-download">
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<h2>Download contacts</h2>
|
||||
<p>A downloaded copy stays on your computer. This app does not delete it later. The Address column is blank. A cell that would be a spreadsheet formula is saved as text.</p>
|
||||
<button type="submit">Download contacts</button>
|
||||
</form>
|
||||
<section class="desk-events" aria-labelledby="contacts-heading">
|
||||
<h2 id="contacts-heading">{heading}</h2>
|
||||
{props.total > 0 ? (
|
||||
<form method="get" action={appPath(props.config, '/admin/contacts')} class="signup-form desk-download">
|
||||
<div class="desk-range">
|
||||
<label>
|
||||
Find
|
||||
<input name="q" type="search" value={props.query} />
|
||||
</label>
|
||||
<button type="submit">Find</button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<p class="empty">No contacts yet.</p>
|
||||
)}
|
||||
{props.total > 0 && props.people.length === 0 ? <p class="empty">No contacts match.</p> : null}
|
||||
{props.people.length > 0 ? (
|
||||
<ul class="contact-list" id="contacts-list">
|
||||
{props.people.map((person, index) => (
|
||||
<li class="contact-row" data-contact-row="1" hidden={index >= props.limit ? true : undefined} key={person.id}>
|
||||
<p class="contact-name">
|
||||
<strong>
|
||||
<a href={appPath(props.config, `/admin/contacts/${person.id}`)}>{person.name}</a>
|
||||
</strong>
|
||||
</p>
|
||||
<p class="contact-email">{person.email}</p>
|
||||
<p class="contact-phone">{person.phone ?? ''}</p>
|
||||
<p class="contact-remove">
|
||||
<ConfirmAnchor href={appPath(props.config, `/admin/contacts/${person.id}/remove`)} prompt={contactRemovalPrompt(person)}>
|
||||
Remove
|
||||
</ConfirmAnchor>
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
) : null}
|
||||
{props.people.length > props.limit ? (
|
||||
<p class="contact-more" id="contact-more">
|
||||
<a class="btn btn-quiet" href={moreHref} data-see-more={String(CONTACT_LIST_PAGE)}>
|
||||
See more
|
||||
</a>
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
<ConfirmDialog config={props.config} csrf={props.csrf} prompt={props.confirm} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ContactPage(props: {
|
||||
config: AppConfig;
|
||||
csrf: string;
|
||||
contact: Contact;
|
||||
shifts: MoveTarget[];
|
||||
form: WalkInState;
|
||||
shiftId: string;
|
||||
error?: string;
|
||||
}) {
|
||||
const values = props.form.values;
|
||||
const errors = props.form.errors;
|
||||
const errorEntries = Object.entries(errors).filter((entry): entry is [string, string] => Boolean(entry[1]));
|
||||
return (
|
||||
<>
|
||||
<p>
|
||||
<a href={appPath(props.config, '/admin/contacts')}>Contacts</a>
|
||||
</p>
|
||||
<h1>{props.contact.name}</h1>
|
||||
<p>{props.contact.email}</p>
|
||||
{props.contact.phone ? <p>{props.contact.phone}</p> : null}
|
||||
{props.error ? <p class="error">{props.error}</p> : null}
|
||||
<h2>Add to a shift</h2>
|
||||
<p>Choose an open shift. This uses their saved name, email, and phone. It takes one spot and queues a confirmation email. Their name stays off the public list. Full, cancelled, and ended shifts are left off this list, and so is a shift they are already on.</p>
|
||||
{props.shifts.length > 0 ? (
|
||||
<form method="post" action={appPath(props.config, `/admin/contacts/${props.contact.id}/add`)} class="signup-form">
|
||||
{props.form.message ? <p class="error">{props.form.message}</p> : null}
|
||||
{errorEntries.length > 0 ? (
|
||||
<div class="error" role="alert">
|
||||
<p>Check these fields:</p>
|
||||
<ul>
|
||||
{errorEntries.map(([field, message]) => (
|
||||
<li key={field}>{message}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : null}
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<input type="hidden" name="form_token" value={props.form.token} />
|
||||
<label for="add-shift">
|
||||
Shift
|
||||
<select id="add-shift" name="shift" required>
|
||||
<option value="" selected={props.shiftId === '' ? true : undefined}>
|
||||
Choose a shift
|
||||
</option>
|
||||
{props.shifts.map((shift) => (
|
||||
<option value={String(shift.id)} key={shift.id} selected={props.shiftId === String(shift.id) ? true : undefined}>
|
||||
{shift.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label for="add-notes">
|
||||
Notes (optional)
|
||||
<textarea id="add-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined}>
|
||||
{values.notes}
|
||||
</textarea>
|
||||
{errors.notes ? <span class="field-error">{errors.notes}</span> : null}
|
||||
</label>
|
||||
<label class="check" for="add-under-18">
|
||||
<input id="add-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={values.under18 ? true : undefined} />
|
||||
They are under 18
|
||||
</label>
|
||||
<fieldset data-guardian="">
|
||||
<legend>Parent or guardian</legend>
|
||||
<WalkInField id="add-guardianName" label="Guardian name" name="guardianName" type="text" value={values.guardianName} error={errors.guardianName} />
|
||||
<WalkInField id="add-guardianEmail" label="Guardian email" name="guardianEmail" type="email" value={values.guardianEmail} error={errors.guardianEmail} />
|
||||
</fieldset>
|
||||
<button type="submit">Add to this shift</button>
|
||||
</form>
|
||||
) : (
|
||||
<p class="empty">No open shift is available.</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function EventEditor(props: {
|
||||
config: AppConfig;
|
||||
heading: string;
|
||||
@@ -422,6 +627,7 @@ export function ShiftRoster(props: {
|
||||
error?: string;
|
||||
walkIn?: WalkInState;
|
||||
walkInNote?: string;
|
||||
contacts?: Contact[];
|
||||
removable?: boolean;
|
||||
moves?: { targets: MoveTarget[]; tokens: Record<number, string> };
|
||||
confirm?: ConfirmPrompt;
|
||||
@@ -489,7 +695,7 @@ export function ShiftRoster(props: {
|
||||
</section>
|
||||
{props.walkIn ? (
|
||||
<section class="desk-events" aria-labelledby="walkin-heading">
|
||||
<WalkInForm config={props.config} csrf={props.csrf} shiftId={props.shift.id} form={props.walkIn} />
|
||||
<WalkInForm config={props.config} csrf={props.csrf} shiftId={props.shift.id} form={props.walkIn} contacts={props.contacts ?? []} />
|
||||
</section>
|
||||
) : props.walkInNote ? (
|
||||
<p class="panel-note">{props.walkInNote}</p>
|
||||
@@ -1079,10 +1285,11 @@ function ShiftEditorForm(props: { config: AppConfig; csrf: string; shift: AdminS
|
||||
);
|
||||
}
|
||||
|
||||
function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; form: WalkInState }) {
|
||||
function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; form: WalkInState; contacts: Contact[] }) {
|
||||
const values = props.form.values;
|
||||
const errors = props.form.errors;
|
||||
const errorEntries = Object.entries(errors).filter((entry): entry is [string, string] => Boolean(entry[1]));
|
||||
const contactId = props.form.contactId ?? '';
|
||||
return (
|
||||
<form method="post" action={appPath(props.config, `/admin/shifts/${props.shiftId}/walk-in`)} class="signup-form event-details-form">
|
||||
<h2 id="walkin-heading">Add a walk-in</h2>
|
||||
@@ -1102,6 +1309,31 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
|
||||
) : null}
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
<input type="hidden" name="form_token" value={props.form.token} />
|
||||
{props.contacts.length > 0 ? (
|
||||
<label for="walkin-contact">
|
||||
Saved contact
|
||||
<select id="walkin-contact" name="contact" data-contact="" aria-describedby="walkin-contact-hint">
|
||||
<option value="" selected={contactId === '' ? true : undefined}>
|
||||
Type their details
|
||||
</option>
|
||||
{props.contacts.map((person) => (
|
||||
<option
|
||||
value={String(person.id)}
|
||||
key={person.id}
|
||||
selected={contactId === String(person.id) ? true : undefined}
|
||||
data-name={person.name}
|
||||
data-email={person.email}
|
||||
data-phone={person.phone ?? ''}
|
||||
>
|
||||
{person.name}, {person.email}
|
||||
</option>
|
||||
))}
|
||||
</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.
|
||||
</span>
|
||||
</label>
|
||||
) : null}
|
||||
<WalkInField id="walkin-name" label="Name" name="name" type="text" value={values.name} error={errors.name} />
|
||||
<WalkInField id="walkin-email" label="Email" name="email" type="email" value={values.email} error={errors.email} />
|
||||
<WalkInField id="walkin-phone" label="Phone (optional)" name="phone" type="tel" value={values.phone} error={errors.phone} hint="We will not text you" />
|
||||
@@ -1142,7 +1374,6 @@ function WalkInField(props: { id: string; label: string; name: string; type: 'te
|
||||
name={props.name}
|
||||
type={props.type}
|
||||
value={props.value}
|
||||
required={props.name === 'name' || props.name === 'email' ? true : undefined}
|
||||
autocomplete="off"
|
||||
aria-invalid={props.error ? 'true' : undefined}
|
||||
aria-describedby={describedBy}
|
||||
@@ -1289,8 +1520,8 @@ function BackupNote(props: { text: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function Notice(props: { notice?: string }) {
|
||||
const text = props.notice ? NOTICES[props.notice] : undefined;
|
||||
function Notice(props: { notice?: string; text?: string }) {
|
||||
const text = props.text ?? (props.notice ? NOTICES[props.notice] : undefined);
|
||||
if (!text) return null;
|
||||
return (
|
||||
<p class="notice" data-notice>
|
||||
@@ -1359,6 +1590,7 @@ const NOTICES: Record<string, string> = {
|
||||
'template-removed': 'That weekly template is removed. Shifts already on the schedule stay, and they are no longer tied to the weekly pattern.',
|
||||
'event-removed': 'That event is removed.',
|
||||
'settings-saved': 'Settings saved.',
|
||||
'contact-removed': 'That person is removed from the contact list.',
|
||||
};
|
||||
|
||||
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] as const;
|
||||
|
||||
@@ -978,6 +978,49 @@ export function listMoveTargets(
|
||||
});
|
||||
}
|
||||
|
||||
/** Open shifts a coordinator can add this person to. Full, cancelled, ended, and already-confirmed shifts are omitted. A shift that is not on the public list is still included. */
|
||||
export function listOpenShiftsForPerson(
|
||||
db: Database.Database,
|
||||
person: { email: string; name: string },
|
||||
now: string,
|
||||
): MoveTarget[] {
|
||||
const blocked = new Set(confirmedPersonShiftIds(db, person.email, person.name));
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT s.id AS id, s.role AS role, s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc,
|
||||
s.capacity AS capacity, e.title AS title, e.tz AS tz, e.published AS published,
|
||||
COALESCE(SUM(CASE WHEN su.status = 'confirmed' THEN su.group_size ELSE 0 END), 0) AS occupied
|
||||
FROM shifts s
|
||||
JOIN events e ON e.id = s.event_id
|
||||
LEFT JOIN signups su ON su.shift_id = s.id
|
||||
WHERE s.cancelled = 0 AND s.ends_at_utc > ?
|
||||
GROUP BY s.id
|
||||
ORDER BY s.starts_at_utc, s.id`,
|
||||
)
|
||||
.all(now) as Array<{
|
||||
id: number;
|
||||
role: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
capacity: number;
|
||||
title: string;
|
||||
tz: string;
|
||||
published: number;
|
||||
occupied: number;
|
||||
}>;
|
||||
return rows.flatMap((row) => {
|
||||
if (blocked.has(row.id)) return [];
|
||||
if (Number(row.occupied) >= Number(row.capacity)) return [];
|
||||
const start = formatInstantInZone(row.starts_at_utc, row.tz);
|
||||
const end = formatInstantInZone(row.ends_at_utc, row.tz);
|
||||
const publicity = row.published === 1 ? '' : ' (not on the public list)';
|
||||
return [{
|
||||
id: row.id,
|
||||
label: `${row.title}: ${row.role}, ${start.dateLabel}, ${start.timeLabel} to ${end.timeLabel} ${end.abbreviation}${publicity}`,
|
||||
}];
|
||||
});
|
||||
}
|
||||
|
||||
export type MoveResult =
|
||||
| { ok: true; fromShiftId: number; toShiftId: number; newSignupId: number; replay: boolean; manageToken: string | null }
|
||||
| { ok: false; error: string; shiftId?: number };
|
||||
|
||||
+18
-8
@@ -45,7 +45,7 @@ export class ConfigError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type MailDriver = 'console' | 'postmark' | 'ses';
|
||||
export type MailDriver = 'console' | 'smtp2go' | 'postmark' | 'ses';
|
||||
|
||||
export type AppConfig = {
|
||||
nodeEnv: 'development' | 'test' | 'production';
|
||||
@@ -61,6 +61,7 @@ export type AppConfig = {
|
||||
driver: MailDriver;
|
||||
from: string;
|
||||
replyTo: string;
|
||||
smtp2goApiKey: string | null;
|
||||
postmarkToken: string | null;
|
||||
ses: { region: string; accessKeyId: string; secretAccessKey: string } | null;
|
||||
};
|
||||
@@ -82,11 +83,12 @@ const schema = z.object({
|
||||
DATA_DIR: z.string().min(1, 'DATA_DIR is required.'),
|
||||
SESSION_SECRET: z.string().min(32, 'SESSION_SECRET must be at least 32 characters.'),
|
||||
DEFAULT_TZ: z.string().min(1, 'DEFAULT_TZ is required.'),
|
||||
MAIL_DRIVER: z.enum(['console', 'postmark', 'ses'], {
|
||||
errorMap: () => ({ message: 'MAIL_DRIVER must be console, postmark, or ses.' }),
|
||||
MAIL_DRIVER: z.enum(['console', 'smtp2go', 'postmark', 'ses'], {
|
||||
errorMap: () => ({ message: 'MAIL_DRIVER must be console, smtp2go, postmark, or ses.' }),
|
||||
}),
|
||||
MAIL_FROM: z.string().min(1, 'MAIL_FROM is required.'),
|
||||
MAIL_REPLY_TO: z.string().min(1, 'MAIL_REPLY_TO is required.'),
|
||||
SMTP2GO_API_KEY: z.string(),
|
||||
POSTMARK_TOKEN: z.string(),
|
||||
SES_REGION: z.string(),
|
||||
SES_ACCESS_KEY_ID: z.string(),
|
||||
@@ -119,6 +121,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
MAIL_DRIVER: blank(env.MAIL_DRIVER),
|
||||
MAIL_FROM: blank(env.MAIL_FROM),
|
||||
MAIL_REPLY_TO: blank(env.MAIL_REPLY_TO),
|
||||
SMTP2GO_API_KEY: (env.SMTP2GO_API_KEY ?? '').trim(),
|
||||
POSTMARK_TOKEN: (env.POSTMARK_TOKEN ?? '').trim(),
|
||||
SES_REGION: (env.SES_REGION ?? '').trim(),
|
||||
SES_ACCESS_KEY_ID: (env.SES_ACCESS_KEY_ID ?? '').trim(),
|
||||
@@ -199,6 +202,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
|
||||
driver: input.MAIL_DRIVER,
|
||||
from,
|
||||
replyTo,
|
||||
smtp2goApiKey: mail.smtp2goApiKey,
|
||||
postmarkToken: mail.postmarkToken,
|
||||
ses: mail.ses,
|
||||
},
|
||||
@@ -316,15 +320,20 @@ function parseReplyTo(value: string, problems: string[]): string | null {
|
||||
function resolveMail(
|
||||
input: z.infer<typeof schema>,
|
||||
problems: string[],
|
||||
): { postmarkToken: string | null; ses: AppConfig['mail']['ses'] } | null {
|
||||
// TODO(D1): The pantry chooses the provider and verifies the sender and reply-to before real mail is enabled.
|
||||
): { smtp2goApiKey: string | null; postmarkToken: string | null; ses: AppConfig['mail']['ses'] } | null {
|
||||
// TODO(D1): SMTP2GO is the provider. Verify the sender and reply-to before real mail is enabled.
|
||||
if (input.NODE_ENV === 'production' && input.MAIL_DRIVER === 'console') {
|
||||
problems.push('MAIL_DRIVER=console is only for development. Choose postmark or ses after the pantry confirms the email provider.');
|
||||
problems.push('MAIL_DRIVER=console is only for development. Use smtp2go after the sender address is verified with SMTP2GO.');
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'smtp2go') {
|
||||
const apiKey = requireCredential(input.SMTP2GO_API_KEY, 'SMTP2GO_API_KEY', problems);
|
||||
if (!apiKey) return null;
|
||||
return { smtp2goApiKey: apiKey, postmarkToken: null, ses: null };
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'postmark') {
|
||||
const token = requireCredential(input.POSTMARK_TOKEN, 'POSTMARK_TOKEN', problems);
|
||||
if (!token) return null;
|
||||
return { postmarkToken: token, ses: null };
|
||||
return { smtp2goApiKey: null, postmarkToken: token, ses: null };
|
||||
}
|
||||
if (input.MAIL_DRIVER === 'ses') {
|
||||
if (!/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) {
|
||||
@@ -334,11 +343,12 @@ function resolveMail(
|
||||
const secretAccessKey = requireCredential(input.SES_SECRET_ACCESS_KEY, 'SES_SECRET_ACCESS_KEY', problems);
|
||||
if (!accessKeyId || !secretAccessKey || !/^[a-z]{2}-[a-z]+-\d+$/.test(input.SES_REGION)) return null;
|
||||
return {
|
||||
smtp2goApiKey: null,
|
||||
postmarkToken: null,
|
||||
ses: { region: input.SES_REGION, accessKeyId, secretAccessKey },
|
||||
};
|
||||
}
|
||||
return { postmarkToken: null, ses: null };
|
||||
return { smtp2goApiKey: null, postmarkToken: null, ses: null };
|
||||
}
|
||||
|
||||
function requireCredential(value: string, label: string, problems: string[]): string | null {
|
||||
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
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 type { SignupValues } from './signup-form.js';
|
||||
|
||||
const MAX_ROWS = 2000;
|
||||
export const CONTACT_LIST_PAGE = 20;
|
||||
const MAX_TEXT = 64 * 1024;
|
||||
const MAX_EMAIL = 254;
|
||||
const MAX_NAME = 80;
|
||||
const MAX_PHONE = 40;
|
||||
const MAX_SKIPS = 30;
|
||||
const CONTROL = /[\u0000-\u001F\u007F]/;
|
||||
|
||||
export const CONTACT_CSV_EMPTY = 'Choose a spreadsheet to import.';
|
||||
export const CONTACT_CSV_COLUMNS = 'This spreadsheet needs First Name, Last Name, and Email columns.';
|
||||
export const CONTACT_CSV_READ = 'This spreadsheet could not be read.';
|
||||
export const CONTACT_CSV_LARGE = 'This spreadsheet has more than 2000 people.';
|
||||
export const CONTACT_CSV_BINARY = 'Save the spreadsheet as CSV.';
|
||||
export const CONTACT_CSV_LIMIT = 'This spreadsheet has to be under 64 KB.';
|
||||
|
||||
export type ContactSkipCode = 'e' | 'n' | 'p' | 'l' | 'c';
|
||||
|
||||
export type ContactSkip = { line: number; code: ContactSkipCode };
|
||||
|
||||
export type ContactImportSummary = {
|
||||
added: number;
|
||||
changed: number;
|
||||
unchanged: number;
|
||||
skipped: number;
|
||||
skips: ContactSkip[];
|
||||
};
|
||||
|
||||
export type Contact = {
|
||||
id: number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
};
|
||||
|
||||
type ReadyContact = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
};
|
||||
|
||||
type ContactRow = {
|
||||
id: number;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
email: string;
|
||||
phone: string | null;
|
||||
};
|
||||
|
||||
const SKIP_REASON: Record<ContactSkipCode, string> = {
|
||||
e: 'the email is not an address',
|
||||
n: 'the name is missing',
|
||||
p: 'the phone is too long',
|
||||
l: 'the name is too long',
|
||||
c: 'a field has a line break',
|
||||
};
|
||||
|
||||
export function contactImportSentence(summary: Pick<ContactImportSummary, 'added' | 'changed' | 'unchanged' | 'skipped'>): string {
|
||||
const { added, changed, unchanged, skipped } = summary;
|
||||
if (added + changed + unchanged + skipped === 0) return 'That spreadsheet had no contacts.';
|
||||
const parts: string[] = [];
|
||||
if (added > 0) parts.push(added === 1 ? 'Saved 1 new contact.' : `Saved ${added} new contacts.`);
|
||||
if (changed > 0) parts.push(changed === 1 ? 'Updated 1 contact.' : `Updated ${changed} contacts.`);
|
||||
if (unchanged > 0) {
|
||||
parts.push(
|
||||
unchanged === 1
|
||||
? '1 contact already matched and was left as it is.'
|
||||
: `${unchanged} contacts already matched and were left as they are.`,
|
||||
);
|
||||
}
|
||||
if (skipped > 0) parts.push(skipped === 1 ? 'Skipped 1 row.' : `Skipped ${skipped} rows.`);
|
||||
if (added === 0 && changed === 0 && unchanged === 0) parts.unshift('No contacts were saved.');
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
export function contactSkipSentence(skip: ContactSkip): string {
|
||||
return `Row ${skip.line} was skipped because ${SKIP_REASON[skip.code]}.`;
|
||||
}
|
||||
|
||||
export function formatContactSkips(skips: ContactSkip[]): string {
|
||||
return skips
|
||||
.slice(0, MAX_SKIPS)
|
||||
.map((skip) => `${skip.line}${skip.code}`)
|
||||
.join('.');
|
||||
}
|
||||
|
||||
export function parseContactSkips(value: string | undefined): ContactSkip[] {
|
||||
if (!value) return [];
|
||||
const skips: ContactSkip[] = [];
|
||||
for (const part of value.split('.')) {
|
||||
const match = /^(\d+)([enplc])$/.exec(part);
|
||||
if (!match) continue;
|
||||
const line = Number(match[1]);
|
||||
const code = match[2];
|
||||
if (!Number.isSafeInteger(line) || line < 1 || !code || !isSkipCode(code)) continue;
|
||||
skips.push({ line, code });
|
||||
if (skips.length === MAX_SKIPS) break;
|
||||
}
|
||||
return skips;
|
||||
}
|
||||
|
||||
export function importContactCsv(
|
||||
db: Database.Database,
|
||||
coordinatorId: number | null,
|
||||
text: string,
|
||||
now: string,
|
||||
): { ok: true; result: ContactImportSummary } | { ok: false; error: string } {
|
||||
if (text.length > MAX_TEXT) return { ok: false, error: CONTACT_CSV_LIMIT };
|
||||
if (text.includes('\u0000')) return { ok: false, error: CONTACT_CSV_BINARY };
|
||||
if (text.trim() === '') return { ok: false, error: CONTACT_CSV_EMPTY };
|
||||
let table: { line: number; cells: string[] }[];
|
||||
try {
|
||||
table = parseCsv(text);
|
||||
} catch {
|
||||
return { ok: false, error: CONTACT_CSV_READ };
|
||||
}
|
||||
const header = table[0];
|
||||
if (!header) return { ok: false, error: CONTACT_CSV_COLUMNS };
|
||||
const columns = columnIndex(header.cells);
|
||||
if (!columns) return { ok: false, error: CONTACT_CSV_COLUMNS };
|
||||
const data = table.slice(1);
|
||||
if (data.length > MAX_ROWS) return { ok: false, error: CONTACT_CSV_LARGE };
|
||||
|
||||
const ready: ReadyContact[] = [];
|
||||
const skips: ContactSkip[] = [];
|
||||
for (const row of data) {
|
||||
const parsed = parsePerson(row.cells, columns);
|
||||
if ('code' in parsed) skips.push({ line: row.line, code: parsed.code });
|
||||
else ready.push(parsed);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
writeAudit(db, coordinatorId, 'contacts.import', { added, changed, unchanged, skipped: skips.length }, now);
|
||||
return { added, changed, unchanged };
|
||||
})();
|
||||
|
||||
return { ok: true, result: { ...applied, skipped: skips.length, skips } };
|
||||
}
|
||||
|
||||
export function exportContacts(db: Database.Database): { csv: string; rows: number } {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT first_name, last_name, email, phone
|
||||
FROM contacts
|
||||
ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE, id`,
|
||||
)
|
||||
.all() as { first_name: string; last_name: string; email: string; phone: string | null }[];
|
||||
const lines = [
|
||||
['First Name', 'Last Name', 'Email', 'Phone', 'Address'].map(csvCell).join(','),
|
||||
...rows.map((row) => [row.first_name, row.last_name, row.email, row.phone ?? '', ''].map(csvCell).join(',')),
|
||||
];
|
||||
return { csv: `\uFEFF${lines.join('\r\n')}\r\n`, rows: rows.length };
|
||||
}
|
||||
|
||||
/** How many contacts to show. A missing or small value starts at the first page. */
|
||||
export function contactListLimit(value: string | undefined): number {
|
||||
if (!value || !/^\d{1,6}$/.test(value)) return CONTACT_LIST_PAGE;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < CONTACT_LIST_PAGE) return CONTACT_LIST_PAGE;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function loadContacts(db: Database.Database, query: string): { total: number; query: string; people: Contact[] } {
|
||||
const cleaned = query.normalize('NFC').replace(CONTROL, '').trim().slice(0, MAX_NAME);
|
||||
const people = allContacts(db);
|
||||
const needle = cleaned.toLocaleLowerCase();
|
||||
if (!needle) return { total: people.length, query: cleaned, people };
|
||||
return {
|
||||
total: people.length,
|
||||
query: cleaned,
|
||||
people: people.filter(
|
||||
(person) =>
|
||||
person.name.toLocaleLowerCase().includes(needle) ||
|
||||
person.email.includes(needle) ||
|
||||
(person.phone ?? '').toLocaleLowerCase().includes(needle),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function getContact(db: Database.Database, id: number): Contact | null {
|
||||
if (!Number.isSafeInteger(id) || id < 1) return null;
|
||||
const row = db.prepare('SELECT id, first_name, last_name, email, phone FROM contacts WHERE id = ?').get(id) as ContactRow | undefined;
|
||||
return row ? present(row) : null;
|
||||
}
|
||||
|
||||
export function removeContact(db: Database.Database, coordinatorId: number, id: number, now: string): boolean {
|
||||
return db.transaction(() => {
|
||||
const deleted = db.prepare('DELETE FROM contacts WHERE id = ?').run(id);
|
||||
if (deleted.changes !== 1) return false;
|
||||
writeAudit(db, coordinatorId, 'contacts.remove', { id }, now);
|
||||
return true;
|
||||
})();
|
||||
}
|
||||
|
||||
/** Blank name, email, or phone on the form keeps the saved contact's value. */
|
||||
export function walkInFromContact(contact: Contact, values: SignupValues): SignupValues {
|
||||
return {
|
||||
...values,
|
||||
name: values.name.trim() ? values.name : contact.name,
|
||||
email: values.email.trim() ? values.email : contact.email,
|
||||
phone: values.phone.trim() ? values.phone : (contact.phone ?? ''),
|
||||
};
|
||||
}
|
||||
|
||||
function allContacts(db: Database.Database): Contact[] {
|
||||
const rows = db
|
||||
.prepare(
|
||||
`SELECT id, first_name, last_name, email, phone
|
||||
FROM contacts
|
||||
ORDER BY last_name COLLATE NOCASE, first_name COLLATE NOCASE, id`,
|
||||
)
|
||||
.all() as ContactRow[];
|
||||
return rows.map(present);
|
||||
}
|
||||
|
||||
function present(row: ContactRow): Contact {
|
||||
return {
|
||||
id: row.id,
|
||||
firstName: row.first_name,
|
||||
lastName: row.last_name,
|
||||
name: `${row.first_name} ${row.last_name}`,
|
||||
email: row.email,
|
||||
phone: row.phone,
|
||||
};
|
||||
}
|
||||
|
||||
function columnIndex(cells: string[]): { first: number; last: number; email: number; phone: number } | null {
|
||||
const names = cells.map((cell) => csvImportedCell(cell).toLowerCase());
|
||||
const first = names.indexOf('first name');
|
||||
const last = names.indexOf('last name');
|
||||
const email = names.indexOf('email');
|
||||
const phone = names.indexOf('phone');
|
||||
if (first < 0 || last < 0 || email < 0) return null;
|
||||
return { first, last, email, phone };
|
||||
}
|
||||
|
||||
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);
|
||||
const emailRaw = cellAt(cells, columns.email);
|
||||
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' };
|
||||
try {
|
||||
const email = normalizeEmail(emailRaw);
|
||||
if (email.length > MAX_EMAIL) return { code: 'e' };
|
||||
return { firstName, lastName, email, phone: phoneRaw.length === 0 ? null : phoneRaw };
|
||||
} catch (err) {
|
||||
if (err instanceof EmailAddressError) return { code: 'e' };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function cellAt(cells: string[], index: number): string {
|
||||
if (index < 0 || index >= cells.length) return '';
|
||||
return csvImportedCell(cells[index] ?? '');
|
||||
}
|
||||
|
||||
function parseCsv(text: string): { line: number; cells: string[] }[] {
|
||||
const source = text.replace(/^\uFEFF/, '');
|
||||
const rows: { line: number; cells: string[] }[] = [];
|
||||
let cells: string[] = [];
|
||||
let cell = '';
|
||||
let quoted = false;
|
||||
let line = 1;
|
||||
let rowLine = 1;
|
||||
let sawCell = false;
|
||||
|
||||
const finishRow = () => {
|
||||
cells.push(cell);
|
||||
if (cells.some((value) => value.trim() !== '')) rows.push({ line: rowLine, cells });
|
||||
cells = [];
|
||||
cell = '';
|
||||
sawCell = false;
|
||||
};
|
||||
|
||||
for (let i = 0; i < source.length; i += 1) {
|
||||
const ch = source[i] ?? '';
|
||||
if (quoted) {
|
||||
if (ch === '"') {
|
||||
if (source[i + 1] === '"') {
|
||||
cell += '"';
|
||||
sawCell = true;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
quoted = false;
|
||||
continue;
|
||||
}
|
||||
cell += ch;
|
||||
sawCell = true;
|
||||
if (ch === '\n') line += 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
quoted = true;
|
||||
sawCell = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === ',') {
|
||||
cells.push(cell);
|
||||
cell = '';
|
||||
sawCell = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === '\n' || ch === '\r') {
|
||||
if (ch === '\r' && source[i + 1] === '\n') i += 1;
|
||||
finishRow();
|
||||
line += 1;
|
||||
rowLine = line;
|
||||
continue;
|
||||
}
|
||||
cell += ch;
|
||||
sawCell = true;
|
||||
}
|
||||
if (quoted) throw new Error(CONTACT_CSV_READ);
|
||||
if (sawCell || cells.length > 0) finishRow();
|
||||
return rows;
|
||||
}
|
||||
|
||||
function isSkipCode(value: string): value is ContactSkipCode {
|
||||
return value === 'e' || value === 'n' || value === 'p' || value === 'l' || value === 'c';
|
||||
}
|
||||
@@ -59,6 +59,13 @@ export function csvCell(value: string): string {
|
||||
return safe;
|
||||
}
|
||||
|
||||
/** Drops the quote prefix csvCell adds, then trims. A name that merely starts with an apostrophe stays. */
|
||||
export function csvImportedCell(value: string): string {
|
||||
let text = value.normalize('NFC');
|
||||
if (text.startsWith("'") && FORMULA.test(text.slice(1))) text = text.slice(1);
|
||||
return text.trim();
|
||||
}
|
||||
|
||||
export function exportShiftRoster(db: Database.Database, shiftId: number): RosterExport | null {
|
||||
const shift = db.prepare('SELECT id FROM shifts WHERE id = ?').get(shiftId);
|
||||
if (!shift) return null;
|
||||
|
||||
@@ -2,10 +2,15 @@ import type { AppConfig } from '../config.js';
|
||||
import { createConsoleMailer } from './console.js';
|
||||
import { createPostmarkMailer } from './postmark.js';
|
||||
import { createSesMailer } from './ses.js';
|
||||
import { createSmtp2GoMailer } from './smtp2go.js';
|
||||
import type { Mailer } from './types.js';
|
||||
|
||||
export function createMailer(config: AppConfig): Mailer {
|
||||
if (config.mail.driver === 'console') return createConsoleMailer();
|
||||
if (config.mail.driver === 'smtp2go') {
|
||||
if (!config.mail.smtp2goApiKey) throw new Error('SMTP2GO_API_KEY is required for the smtp2go mail driver.');
|
||||
return createSmtp2GoMailer(config.mail.smtp2goApiKey);
|
||||
}
|
||||
if (config.mail.driver === 'postmark') {
|
||||
if (!config.mail.postmarkToken) throw new Error('POSTMARK_TOKEN is required for the postmark mail driver.');
|
||||
return createPostmarkMailer(config.mail.postmarkToken);
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { redactMailError } from './redact.js';
|
||||
import type { MailDelivery, Mailer, OutboundMail } from './types.js';
|
||||
|
||||
const ENDPOINT = 'https://api.smtp2go.com/v3/email/send';
|
||||
|
||||
type Smtp2GoPayload = {
|
||||
data?: {
|
||||
succeeded?: number;
|
||||
failed?: number;
|
||||
failures?: unknown[];
|
||||
email_id?: string;
|
||||
error?: string;
|
||||
error_code?: string;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* SMTP2GO's send API. A 200 response can still contain a failure, so the body is checked.
|
||||
* fastaccept stays off so a rejected sender is a failure here, not an accepted message
|
||||
* whose later result this app would never see. Acceptance is email_id, not proof of delivery.
|
||||
* The outbox dedupe key prevents a second send. SMTP2GO has no idempotency key.
|
||||
*/
|
||||
export function createSmtp2GoMailer(apiKey: string, fetchImpl: typeof fetch = fetch): Mailer {
|
||||
return {
|
||||
async send(message: OutboundMail): Promise<MailDelivery> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchImpl(ENDPOINT, {
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
redirect: 'error',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Smtp2go-Api-Key': apiKey,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
sender: message.from,
|
||||
to: [message.to],
|
||||
subject: message.subject,
|
||||
text_body: message.text,
|
||||
html_body: message.html,
|
||||
custom_headers: customHeaders(message),
|
||||
}),
|
||||
});
|
||||
} catch (err) {
|
||||
const messageText = err instanceof Error ? err.message : 'SMTP2GO request failed.';
|
||||
const uncertain = err instanceof Error && (err.name === 'AbortError' || err.name === 'TimeoutError');
|
||||
return {
|
||||
result: uncertain ? 'unknown' : 'retry',
|
||||
error: redactMailError(messageText),
|
||||
};
|
||||
}
|
||||
if (response.status === 408 || response.status === 504) {
|
||||
return { result: 'unknown', error: `SMTP2GO responded ${response.status}.` };
|
||||
}
|
||||
if (response.status === 429 || response.status >= 500) {
|
||||
return { result: 'retry', error: `SMTP2GO responded ${response.status}.` };
|
||||
}
|
||||
let payload: Smtp2GoPayload = {};
|
||||
try {
|
||||
payload = (await response.json()) as Smtp2GoPayload;
|
||||
} catch {
|
||||
return { result: response.ok ? 'unknown' : 'failed', error: `SMTP2GO responded ${response.status}.` };
|
||||
}
|
||||
const data = payload.data ?? {};
|
||||
if (!response.ok || data.error) {
|
||||
return { result: 'failed', error: redactMailError(data.error || `SMTP2GO responded ${response.status}.`) };
|
||||
}
|
||||
const failed = data.failed ?? 0;
|
||||
if (failed > 0 || (data.succeeded ?? 0) < 1) {
|
||||
return { result: 'failed', error: redactMailError(failureText(data.failures)) };
|
||||
}
|
||||
if (!data.email_id) {
|
||||
return { result: 'unknown', error: 'SMTP2GO accepted the request without an email id.' };
|
||||
}
|
||||
return { result: 'sent', providerId: data.email_id };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function customHeaders(message: OutboundMail): { header: string; value: string }[] {
|
||||
const headers = [{ header: 'Reply-To', value: message.replyTo }];
|
||||
for (const [header, value] of Object.entries(message.headers ?? {})) {
|
||||
if (header.toLowerCase() === 'reply-to') continue;
|
||||
headers.push({ header, value });
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
function failureText(failures: unknown[] | undefined): string {
|
||||
const parts = (failures ?? []).map((item) => {
|
||||
if (typeof item === 'string') return item;
|
||||
if (item && typeof item === 'object') {
|
||||
const record = item as { error?: unknown; message?: unknown };
|
||||
if (typeof record.error === 'string') return record.error;
|
||||
if (typeof record.message === 'string') return record.message;
|
||||
}
|
||||
return '';
|
||||
}).filter((part) => part !== '');
|
||||
return parts.join(' ') || 'SMTP2GO rejected the message.';
|
||||
}
|
||||
Reference in new issue
Block a user