diff --git a/.env.example b/.env.example index 174c90e..b924405 100644 --- a/.env.example +++ b/.env.example @@ -18,11 +18,12 @@ SESSION_SECRET=dev-only-change-me-not-for-production-use DEFAULT_TZ=America/Chicago -# console is development-only. postmark and ses need real credentials and are not enabled by this file. -# TODO(D1): The pantry chooses the email provider and checks the sender and reply-to. +# console is development-only. smtp2go is the mail provider. postmark and ses remain available. +# TODO(D1): Verify the SMTP2GO sender and the reply-to before real mail is enabled. MAIL_DRIVER=console MAIL_FROM="Hope Food Pantry " MAIL_REPLY_TO=volunteer@example.invalid +SMTP2GO_API_KEY= POSTMARK_TOKEN= SES_REGION= SES_ACCESS_KEY_ID= diff --git a/.env.production.example b/.env.production.example index ea67d92..2f5064f 100644 --- a/.env.production.example +++ b/.env.production.example @@ -1,6 +1,6 @@ # Copy to .env on the server that runs Docker Compose. Do not use the development .env. # Compose forces NODE_ENV=production, DATA_DIR=/data, BIND_HOST=0.0.0.0, and TRUST_PROXY=172.30.0.0/24. -# Fill the mail and Turnstile values before starting. Gmail is not a driver yet. +# Fill the SMTP2GO API key and Turnstile values before starting. Gmail is not a driver. # Generate a session secret with: # node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))" @@ -11,9 +11,10 @@ BASE_PATH= DATA_DIR=/data SESSION_SECRET= DEFAULT_TZ=America/Chicago -MAIL_DRIVER=postmark +MAIL_DRIVER=smtp2go MAIL_FROM=Hope Food Pantry MAIL_REPLY_TO=volunteer@example.org +SMTP2GO_API_KEY= POSTMARK_TOKEN= SES_REGION= SES_ACCESS_KEY_ID= diff --git a/README.md b/README.md index f1a5a39..db6f11e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ This program is distributed in the hope that it will be useful, but WITHOUT ANY You should have received a copy of the GNU General Public License along with this program. If not, see . -**This is not ready for a public launch, and it is not ready for real volunteer records.** Phase 1A has public browsing, individual signup, cancellation, queued email, and coordinator sign-in for events, one-off shifts, rosters, and cancellation. A coordinator can add a walk-in, mark attendance, and move a signup from a shift roster. A volunteer can switch shifts from their private link. An active weekly template fills shifts for the next eight weeks. A coordinator can add, change, or end a weekly template, and can remove a cancelled person, a finished empty shift, an ended template, or an event that is off the public list and already empty. A confirmed signup can receive a reminder 48 hours before the shift and again 2 hours before, and can turn reminders off without cancelling. A coordinator can download a roster for one shift, one event, or a local date range. A coordinator can set the two reminder times, the reply-to address, how many months to keep a signup, and the wording on the privacy page. After 1:00 AM Central Time, signups older than that many months lose their name and contact details in this app. After 2:30 AM Central Time, the app saves a database backup on this computer. A container can run that same app on this computer, on port 3020, without opening it to the network. This is not a public launch. Around 1:00 AM in each event's time zone, the app adds any missing weekly shifts for the next eight weeks, once that local day. Development prints mail in the server log. It does not send real email. +**This is not ready for a public launch, and it is not ready for real volunteer records.** Phase 1A has public browsing, individual signup, cancellation, queued email, and coordinator sign-in for events, one-off shifts, rosters, and cancellation. A coordinator can add a walk-in, mark attendance, and move a signup from a shift roster. A volunteer can switch shifts from their private link. An active weekly template fills shifts for the next eight weeks. A coordinator can add, change, or end a weekly template, and can remove a cancelled person, a finished empty shift, an ended template, or an event that is off the public list and already empty. A confirmed signup can receive a reminder 48 hours before the shift and again 2 hours before, and can turn reminders off without cancelling. A coordinator can download a roster for one shift, one event, or a local date range. A coordinator can import a contact list, download it, use a saved contact when adding a walk-in, and add a saved contact to an open shift. A coordinator can set the two reminder times, the reply-to address, how many months to keep a signup, and the wording on the privacy page. After 1:00 AM Central Time, signups older than that many months lose their name and contact details in this app. After 2:30 AM Central Time, the app saves a database backup on this computer. A container can run that same app on this computer, on port 3020, without opening it to the network. This is not a public launch. Around 1:00 AM in each event's time zone, the app adds any missing weekly shifts for the next eight weeks, once that local day. Development prints mail in the server log. It does not send real email. ## Current step @@ -32,6 +32,7 @@ You should have received a copy of the GNU General Public License along with thi | Remove a cancelled person, a finished shift, an ended template, or an empty hidden event | Done | | Reminder emails, 48 hours and 2 hours, with a way to stop them | Done | | Download a roster for a shift, an event, or a date range | Done | +| Import and download a contact list | Done | | Set reminder times, reply-to, privacy wording, and retention months | Done | | Refill weekly shifts around 1:00 AM in each event time zone | Done | | Remove personal details after the saved retention period | Done | @@ -44,7 +45,7 @@ The core tables for later steps are already in `migrations/001_init.sql`. Behavi Do not treat this repository as an approved privacy policy or an approved operating setup. -- [ ] **D1.** The pantry chooses the email provider and verifies the sender and reply-to. +- [ ] **D1.** SMTP2GO is the email provider. The pantry verifies the sender and the reply-to. - [ ] **D2.** Whether a group signup is essential. A shared email can already sign up more than one person on the same shift. Each person takes one spot and gets their own confirmation and private link. The same person, matched by name and email, cannot take a second spot on that shift. `group_size` stays 1. Group signup still needs its own decision: who the reservation is for, how minors work, what happens when the count changes, and who receives mail. - [ ] **D3.** The pantry approves privacy wording, minor and guardian requirements, and retention periods, including copies and exports. - [ ] **D4.** The pantry confirms the coordinator list, who owns the administrator account, and the recovery contact. @@ -53,7 +54,7 @@ Do not treat this repository as an approved privacy policy or an approved operat ## TODO(Phase 2) -SignUpGenius importer. Do not build this until an actual export file and the duplicate-handling rules are known. +SignUpGenius shift import. The people export is a contact list, and that list can be imported. A shift import still needs an export that includes the slot, date, and time, plus a rule for someone who is already signed up for that shift. Password login, waitlists, volunteer accounts, SMS, analytics, and payments are out of scope. @@ -74,7 +75,7 @@ Open `/` for the weekly pantry schedule. `/e/weekly-pantry` is the same seeded e An open shift has a signup form. It asks for one person. Another person can use the same email and takes another spot. The same person cannot take a second spot. It asks for a parent or guardian when the volunteer is under 18. The form needs JavaScript because of the Turnstile check. Wait a few seconds after the page loads before submitting. The confirmation page shows a private link and says a confirmation email is queued. That page works without JavaScript. Cancel this signup there to open the spot again. A cancellation email is queued, and a confirmation that has not been sent yet is dropped. That person can sign up again once the cancellation is saved. Someone else can use the email while the first signup is still confirmed. A cancelled signup stays on that private page until the link expires. A private link controls only that signup. Use the separate link for each signup. -With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. Postmark and SES are implemented and stay unselected until the pantry chooses a provider. +With `MAIL_DRIVER=console`, the development server tries to send queued mail every 30 seconds and prints each accepted message in its terminal. That is not delivery to a real inbox. `sent` means the driver accepted the message. A lost result is marked uncertain and is not sent again. SMTP2GO is the mail provider. Set `MAIL_DRIVER=smtp2go` and `SMTP2GO_API_KEY` to send through it. Postmark and SES remain available. Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password. @@ -102,11 +103,13 @@ 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. +**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. + **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. Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and **Add weekly shifts**, still fill the schedule as well. -After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, guardian, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. The minor answer is cleared. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. +After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, guardian, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift, the signup status, and attendance stay, so the count remains. The minor answer is cleared. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. The contact list is separate. Clearing an old signup does not remove that person from the contact list. Finished mail loses its recipient, subject, and body 30 days after it was sent, cancelled, or given up on. Mail that is still waiting after 30 days is cancelled and cleared, so it is not sent late. Mail for a signup is cleared in the same cleanup that removes that signup's details. A sign-in message is cleared once its link is used or expired. Every hour, the app clears those sign-in messages, finished mail past 30 days, expired sign-in sessions, used or expired sign-in links, and rate-limit counters older than about two days. Audit notes older than 24 months are deleted. Those notes are counts and ids. Starting the app runs this cleanup before it accepts requests. If 1:00 AM happens twice when the clocks change, the second hour does not run it again. A restart after 1:00 AM still runs it when that date was missed. @@ -130,10 +133,10 @@ Production startup rejects: - `http://` or a local hostname in `BASE_URL` - Cloudflare's documented Turnstile test keys - `MAIL_DRIVER=console` -- missing credentials for Postmark or SES when that driver is selected +- missing credentials for SMTP2GO, Postmark, or SES when that driver is selected - a session secret shorter than 32 characters, a placeholder, or a secret that does not look random -Development may use the console driver and the always-pass Turnstile test keys in `.env.example`. Those keys are not a launch setting. The console driver prints mail in the development server log and does not contact a provider. Choosing Postmark or SES is a separate decision, and this copy of the app must not send real mail until that is configured on purpose. +Development may use the console driver and the always-pass Turnstile test keys in `.env.example`. Those keys are not a launch setting. The console driver prints mail in the development server log and does not contact a provider. SMTP2GO is the provider for real mail. This copy of the app must not send real mail until `SMTP2GO_API_KEY` and a verified sender are configured on purpose. `DATA_DIR` defaults to `/data`. Local development uses `./data`. The database file is `app.db` inside that directory. @@ -184,7 +187,7 @@ sudo chown 1000:1000 data sudo chmod 700 data ``` -Copy `.env.production.example` to `.env` on the server and fill in the mail provider, Turnstile keys, public `https` address, and session secret. Protect the filled `.env` with `chmod 600 .env`. Then: +Copy `.env.production.example` to `.env` on the server and fill in the SMTP2GO API key, Turnstile keys, public `https` address, and session secret. Protect the filled `.env` with `chmod 600 .env`. Then: ```bash docker compose up -d @@ -194,7 +197,7 @@ docker compose up -d When Caddy is on the host and the app is in a container, `TRUST_PROXY` is the Compose subnet, not `loopback`. `compose.yaml` pins the network to `172.30.0.0/24` and sets `TRUST_PROXY=172.30.0.0/24`. Under Docker the peer is the gateway, `172.30.0.1`. Under rootless Podman 5 with pasta, the port forwarder connects from the container's own address on that network, such as `172.30.0.2`. Trusting the subnet covers both. Only this service is on that network, and the port is published on `127.0.0.1` only. Do not attach other containers to it. If that subnet is already used on the host, change the subnet, gateway, and `TRUST_PROXY` together. Check it once on the real host: send requests through Caddy from two clients and confirm one is not limited by the other's attempts. The Caddy snippets below stay on the host. They are not started by Compose. HTTPS ends at Caddy. The container does not obtain a certificate. -Gmail is not a mail driver. Production still expects Postmark or SES until that choice is built. +Gmail is not a mail driver. Production expects SMTP2GO. ```caddy volunteer.example.org { @@ -234,7 +237,7 @@ example.org { Every response has a Content Security Policy, `Referrer-Policy: no-referrer`, `X-Content-Type-Options: nosniff`, and a `Permissions-Policy` that turns off camera, microphone, location, payment, and USB. When `BASE_URL` is https, responses also send `Strict-Transport-Security: max-age=31536000` for this host only. It does not use `includeSubDomains`, so other pantry subdomains are not affected. -The app limits request bodies to 64 KiB before parsing. Caddy examples apply the same limit. Rejected origins and rate-limited signup/login requests do not parse and redisplay submitted fields. Turnstile has a 10-second deadline; Postmark and SES have 15-second deadlines. A mail timeout is an uncertain delivery, not an automatic resend. SES automatic retries are disabled to avoid duplicate sends after ambiguous failures. +The app limits request bodies to 64 KiB before parsing. Caddy examples apply the same limit. Rejected origins and rate-limited signup/login requests do not parse and redisplay submitted fields. Turnstile has a 10-second deadline; SMTP2GO, Postmark, and SES have 15-second deadlines. A mail timeout is an uncertain delivery, not an automatic resend. SES automatic retries are disabled to avoid duplicate sends after ambiguous failures. Compose uses a read-only root filesystem, drops all capabilities, prevents privilege escalation, and limits the container to 512 MiB memory, one CPU, and 100 processes. `/data` remains writable and `/tmp` is a bounded temporary filesystem. Adjust resource limits using measured usage. The app runs as uid 1000. Local snapshots remain on the same disk and are not an offsite backup. @@ -275,4 +278,4 @@ The command prints the coordinator id, not the address. It does not deactivate a ## What is still unverified -Real inbox delivery, a production host, and a public launch. The container was checked on this computer with a temporary database, separate from the development database: it starts, the weekly page loads, `/healthz` answers, a path prefix is included in that health address, and a restart keeps the database. The development settings were refused. This computer does not have the Docker daemon running, so that check used Podman. It has not been deployed. Decision D6 is still open. The console driver only prints mail. Gmail is not connected. The privacy page is waiting on decision D3 and is not a privacy policy. A real Turnstile hostname check still needs the production keys from decision D5. Development uses Cloudflare's always-pass test keys. Those keys succeed with hostname `example.com` and no action, so the hostname and action checks apply to real keys. Coordinator sign-in is covered here with the console driver, not with a real inbox. +Real inbox delivery, a production host, and a public launch. The container was checked on this computer with a temporary database, separate from the development database: it starts, the weekly page loads, `/healthz` answers, a path prefix is included in that health address, and a restart keeps the database. The development settings were refused. This computer does not have the Docker daemon running, so that check used Podman. It has not been deployed. Decision D6 is still open. The console driver only prints mail. SMTP2GO is the selected provider and is not connected on this computer yet. Gmail is not connected. The privacy page is waiting on decision D3 and is not a privacy policy. A real Turnstile hostname check still needs the production keys from decision D5. Development uses Cloudflare's always-pass test keys. Those keys succeed with hostname `example.com` and no action, so the hostname and action checks apply to real keys. Coordinator sign-in is covered here with the console driver, not with a real inbox. diff --git a/migrations/005_contacts.sql b/migrations/005_contacts.sql new file mode 100644 index 0000000..c5a02a5 --- /dev/null +++ b/migrations/005_contacts.sql @@ -0,0 +1,42 @@ +-- Coordinator contact list. A row is not a signup and does not take a spot. +-- The signup retention job does not clear this table. +-- Deletes do not cascade. Removing a contact leaves signups in place. + +CREATE TABLE contacts ( + 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 UNIQUE 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) +); diff --git a/public/css/app.css b/public/css/app.css index 7e706de..3b9f81d 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -974,6 +974,7 @@ article.shift-card { .signup-form input[type="text"], .signup-form input[type="email"], .signup-form input[type="tel"], +.signup-form input[type="search"], .signup-form input[type="date"], .signup-form input[type="time"], .signup-form input[type="number"], @@ -1823,6 +1824,50 @@ button.btn-quiet::before { max-width: 18rem; } +.signup-form input[type='file'] { + font: inherit; + max-width: 100%; +} + +.contact-list { + list-style: none; + margin: 1rem 0 0; + padding: 0; +} + +.contact-row { + display: grid; + grid-template-columns: minmax(10rem, 1.2fr) minmax(12rem, 1.6fr) minmax(7rem, 0.8fr) auto; + gap: 0.35rem 1rem; + align-items: baseline; + padding: 0.75rem 0; + border-top: 1px solid var(--hope-border-2); +} + +.contact-row p { + margin: 0; + overflow-wrap: anywhere; +} + +.contact-row[hidden] { + display: none; +} + +.contact-more { + margin: 0.35rem 0 0; +} + +#add-shift { + border-radius: 1.25rem; + padding-right: 2.5rem; +} + +@media (max-width: 42em) { + .contact-row { + grid-template-columns: 1fr; + } +} + /* Footer */ .site-footer { diff --git a/public/js/enhance.js b/public/js/enhance.js index 4e6c937..afbfb41 100644 --- a/public/js/enhance.js +++ b/public/js/enhance.js @@ -1,5 +1,7 @@ (function () { bindCalendar(); + document.querySelectorAll('[data-contact]').forEach(bindContact); + document.querySelectorAll('[data-see-more]').forEach(bindSeeMore); var boxes = document.querySelectorAll('[data-under-18]'); for (var i = 0; i < boxes.length; i += 1) bind(boxes[i]); @@ -38,6 +40,41 @@ } } + function bindSeeMore(link) { + var list = document.getElementById('contacts-list'); + if (!list) return; + var size = Number(link.getAttribute('data-see-more')); + if (!size || size < 1) size = 20; + link.addEventListener('click', function (event) { + var hidden = list.querySelectorAll('[data-contact-row][hidden]'); + if (!hidden.length) return; + event.preventDefault(); + var count = Math.min(size, hidden.length); + for (var i = 0; i < count; i += 1) hidden[i].hidden = false; + if (hidden.length <= count) { + var more = link.parentNode; + if (more && more.classList && more.classList.contains('contact-more')) more.hidden = true; + else link.hidden = true; + } + }); + } + + function bindContact(picker) { + picker.addEventListener('change', function () { + var form = picker.form; + var option = picker.options[picker.selectedIndex]; + if (!form || !option || !option.value) return; + setField(form, 'name', option.getAttribute('data-name') || ''); + setField(form, 'email', option.getAttribute('data-email') || ''); + setField(form, 'phone', option.getAttribute('data-phone') || ''); + }); + } + + function setField(form, name, value) { + var input = form.elements[name]; + if (input && 'value' in input) input.value = value; + } + function bind(box) { var form = box.form; if (!form) return; diff --git a/src/admin-http.tsx b/src/admin-http.tsx index a679e9c..546d065 100644 --- a/src/admin-http.tsx +++ b/src/admin-http.tsx @@ -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, + { account: session, status: options?.status ?? 200 }, + ); +} + +async function submitImportContacts(c: Context, services: AdminServices): Promise { + 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 { + 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`, + , + { 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 { + 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 { + 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= 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, 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 { + 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, name: string): number[] | null { const value = body[name]; if (value === undefined) return []; diff --git a/src/admin-pages.tsx b/src/admin-pages.tsx index f719b6f..eb8f9f9 100644 --- a/src/admin-pages.tsx +++ b/src/admin-pages.tsx @@ -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 { + 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: { New event + + Contacts + Settings @@ -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 ( + <> +

+ Coordinator +

+

Contacts

+ {props.summary ? : } + {props.summary && props.summary.skips.length > 0 ? ( +
    + {props.summary.skips.map((skip) => ( +
  • {contactSkipSentence(skip)}
  • + ))} +
+ ) : null} + {hiddenSkips > 0 ?

{hiddenSkips === 1 ? '1 more row was skipped.' : `${hiddenSkips} more rows were skipped.`}

: null} +

+ 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. +

+ + +
+

{heading}

+ {props.total > 0 ? ( + + ) : ( +

No contacts yet.

+ )} + {props.total > 0 && props.people.length === 0 ?

No contacts match.

: null} + {props.people.length > 0 ? ( +
    + {props.people.map((person, index) => ( + + ))} +
+ ) : null} + {props.people.length > props.limit ? ( +

+ + See more + +

+ ) : null} +
+ + + ); +} + +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 ( + <> +

+ Contacts +

+

{props.contact.name}

+

{props.contact.email}

+ {props.contact.phone ?

{props.contact.phone}

: null} + {props.error ?

{props.error}

: null} +

Add to a shift

+

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.

+ {props.shifts.length > 0 ? ( + + ) : ( +

No open shift is available.

+ )} + + ); +} + 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 }; confirm?: ConfirmPrompt; @@ -489,7 +695,7 @@ export function ShiftRoster(props: { {props.walkIn ? (
- +
) : props.walkInNote ? (

{props.walkInNote}

@@ -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 (