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
+3
-2
@@ -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 <volunteer@example.invalid>"
|
||||
MAIL_REPLY_TO=volunteer@example.invalid
|
||||
SMTP2GO_API_KEY=
|
||||
POSTMARK_TOKEN=
|
||||
SES_REGION=
|
||||
SES_ACCESS_KEY_ID=
|
||||
|
||||
@@ -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 <volunteer@example.org>
|
||||
MAIL_REPLY_TO=volunteer@example.org
|
||||
SMTP2GO_API_KEY=
|
||||
POSTMARK_TOKEN=
|
||||
SES_REGION=
|
||||
SES_ACCESS_KEY_ID=
|
||||
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
**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.
|
||||
@@ -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)
|
||||
);
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
+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.';
|
||||
}
|
||||
@@ -55,8 +55,8 @@ describe('loadConfig', () => {
|
||||
it('accepts a production configuration with real-looking keys', () => {
|
||||
const config = loadConfig(productionEnv('/tmp/hope-data'));
|
||||
expect(config.secureCookies).toBe(true);
|
||||
expect(config.mail.driver).toBe('postmark');
|
||||
expect(config.mail.postmarkToken).toBe('pm-server-token-9f3a2c1e5b8d4f70');
|
||||
expect(config.mail.driver).toBe('smtp2go');
|
||||
expect(config.mail.smtp2goApiKey).toBe('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6');
|
||||
expect(config.baseUrl).toBe('https://volunteer.example.org');
|
||||
});
|
||||
|
||||
@@ -79,6 +79,7 @@ describe('loadConfig', () => {
|
||||
});
|
||||
|
||||
it('requires credentials for the selected mail driver', () => {
|
||||
expect(() => loadConfig(devEnv({ MAIL_DRIVER: 'smtp2go', SMTP2GO_API_KEY: '' }))).toThrow(/SMTP2GO_API_KEY/);
|
||||
expect(() => loadConfig(devEnv({ MAIL_DRIVER: 'postmark', POSTMARK_TOKEN: '' }))).toThrow(/POSTMARK_TOKEN/);
|
||||
expect(() =>
|
||||
loadConfig(
|
||||
@@ -119,6 +120,7 @@ describe('loadConfig', () => {
|
||||
MAIL_DRIVER: process.env.MAIL_DRIVER,
|
||||
MAIL_FROM: process.env.MAIL_FROM,
|
||||
MAIL_REPLY_TO: process.env.MAIL_REPLY_TO,
|
||||
SMTP2GO_API_KEY: process.env.SMTP2GO_API_KEY ?? '',
|
||||
POSTMARK_TOKEN: process.env.POSTMARK_TOKEN ?? '',
|
||||
SES_REGION: process.env.SES_REGION ?? '',
|
||||
SES_ACCESS_KEY_ID: process.env.SES_ACCESS_KEY_ID ?? '',
|
||||
|
||||
@@ -0,0 +1,580 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { bootstrapAdmin } from '../src/auth/bootstrap.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import {
|
||||
CONTACT_CSV_BINARY,
|
||||
CONTACT_CSV_COLUMNS,
|
||||
CONTACT_CSV_EMPTY,
|
||||
CONTACT_CSV_LARGE,
|
||||
CONTACT_CSV_LIMIT,
|
||||
CONTACT_CSV_READ,
|
||||
CONTACT_LIST_PAGE,
|
||||
contactImportSentence,
|
||||
contactListLimit,
|
||||
exportContacts,
|
||||
importContactCsv,
|
||||
} from '../src/contacts.js';
|
||||
import { openAppDatabase } from '../src/db.js';
|
||||
import { devEnv } from './env.js';
|
||||
|
||||
const NOW = '2026-10-14T18:00:00.000Z';
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
const dirs: string[] = [];
|
||||
const databases: { close: () => void }[] = [];
|
||||
|
||||
const PEOPLE = [
|
||||
'First Name,Last Name,Email,Phone,Address',
|
||||
'Kristi ,Anderson,Kristi@Example.invalid,712441076,123 Main',
|
||||
'Kara,Acevedo,kara@example.invalid,,',
|
||||
'Kara,Acevedo,kara.other@example.invalid,7125550100,456 Oak',
|
||||
'Not An,Email,not-an-email,,',
|
||||
].join('\r\n');
|
||||
|
||||
afterEach(() => {
|
||||
for (const database of databases.splice(0)) database.close();
|
||||
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe('contact spreadsheet', () => {
|
||||
it('keeps two emails for one name, ignores address, and skips a bad email', async () => {
|
||||
const db = await openDb();
|
||||
const imported = importContactCsv(db, null, PEOPLE, NOW);
|
||||
expect(imported.ok).toBe(true);
|
||||
if (!imported.ok) return;
|
||||
expect(imported.result.added).toBe(3);
|
||||
expect(imported.result.skipped).toBe(1);
|
||||
expect(imported.result.skips).toEqual([{ line: 5, code: 'e' }]);
|
||||
expect(contactImportSentence(imported.result)).toBe('Saved 3 new contacts. Skipped 1 row.');
|
||||
const rows = db
|
||||
.prepare('SELECT first_name, last_name, email, phone FROM contacts ORDER BY id')
|
||||
.all() as { first_name: string; last_name: string; email: string; phone: string | null }[];
|
||||
expect(rows).toEqual([
|
||||
{ first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' },
|
||||
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null },
|
||||
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '7125550100' },
|
||||
]);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
|
||||
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.import'`).get() as { detail_json: string };
|
||||
expect(JSON.parse(audit.detail_json)).toEqual({ added: 3, changed: 0, unchanged: 0, skipped: 1 });
|
||||
expect(audit.detail_json).not.toContain('@');
|
||||
});
|
||||
|
||||
it('updates a name, replaces a phone, and leaves a blank phone in place', async () => {
|
||||
const db = await openDb();
|
||||
importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW);
|
||||
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW);
|
||||
expect(renamed.ok && renamed.result.changed).toBe(1);
|
||||
expect(db.prepare('SELECT last_name, phone FROM contacts').get()).toEqual({ last_name: 'Two', phone: '111' });
|
||||
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,222\n', NOW);
|
||||
expect(replaced.ok && replaced.result.changed).toBe(1);
|
||||
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '222' });
|
||||
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
|
||||
expect(same.ok && same.result.unchanged).toBe(1);
|
||||
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '222' });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1);
|
||||
});
|
||||
|
||||
it('round-trips a formula-looking name and a comma in the last name', async () => {
|
||||
const db = await openDb();
|
||||
const first = importContactCsv(
|
||||
db,
|
||||
null,
|
||||
'First Name,Last Name,Email,Phone,Address\n=Ada,"De Jong, Jr",ada@example.invalid,+1 712,\n',
|
||||
NOW,
|
||||
);
|
||||
expect(first.ok && first.result.added).toBe(1);
|
||||
const exported = exportContacts(db);
|
||||
expect(exported.csv.startsWith('\uFEFFFirst Name,Last Name,Email,Phone,Address\r\n')).toBe(true);
|
||||
expect(exported.csv).toContain("'=Ada");
|
||||
expect(exported.csv).toContain("'+1 712");
|
||||
expect(exported.csv).toContain('"De Jong, Jr"');
|
||||
const again = importContactCsv(db, null, exported.csv, NOW);
|
||||
expect(again.ok && again.result.unchanged).toBe(1);
|
||||
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts').get()).toEqual({
|
||||
first_name: '=Ada',
|
||||
last_name: 'De Jong, Jr',
|
||||
phone: '+1 712',
|
||||
});
|
||||
});
|
||||
|
||||
it('refuses a roster file, an empty file, a broken quote, and too many rows', async () => {
|
||||
const db = await openDb();
|
||||
expect(importContactCsv(db, null, 'Date,Start,Name,Email\n2026-10-15,9:00,Ada,ada@example.invalid\n', NOW)).toEqual({
|
||||
ok: false,
|
||||
error: CONTACT_CSV_COLUMNS,
|
||||
});
|
||||
expect(importContactCsv(db, null, ' ', NOW)).toEqual({ ok: false, error: CONTACT_CSV_EMPTY });
|
||||
expect(importContactCsv(db, null, 'First Name,Last Name,Email\n"Ada,One,ada@example.invalid\n', NOW)).toEqual({
|
||||
ok: false,
|
||||
error: CONTACT_CSV_READ,
|
||||
});
|
||||
expect(importContactCsv(db, null, 'First Name,Last Name,Email\0\n', NOW)).toEqual({ ok: false, error: CONTACT_CSV_BINARY });
|
||||
expect(importContactCsv(db, null, `First Name,Last Name,Email\n${'x'.repeat(64 * 1024)}`, NOW)).toEqual({
|
||||
ok: false,
|
||||
error: CONTACT_CSV_LIMIT,
|
||||
});
|
||||
const lines = ['First Name,Last Name,Email'];
|
||||
for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c`);
|
||||
expect(importContactCsv(db, null, lines.join('\n'), NOW)).toEqual({ ok: false, error: CONTACT_CSV_LARGE });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
|
||||
});
|
||||
|
||||
it('starts the list at one page and ignores a smaller shown count', () => {
|
||||
expect(contactListLimit(undefined)).toBe(CONTACT_LIST_PAGE);
|
||||
expect(contactListLimit('5')).toBe(CONTACT_LIST_PAGE);
|
||||
expect(contactListLimit('shown')).toBe(CONTACT_LIST_PAGE);
|
||||
expect(contactListLimit('40')).toBe(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contact pages', () => {
|
||||
it('shows the next page of contacts and keeps the search', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const lines = ['First Name,Last Name,Email'];
|
||||
for (let i = 0; i <= CONTACT_LIST_PAGE; i += 1) {
|
||||
const name = String(i).padStart(2, '0');
|
||||
lines.push(`Ada,N${name},n${name}@example.invalid`);
|
||||
}
|
||||
const imported = await postFile(app, cookie, lines.join('\n'));
|
||||
expect(imported.status).toBe(303);
|
||||
const first = await app.request('/admin/contacts', { headers: { cookie } });
|
||||
const firstHtml = await first.text();
|
||||
expect(firstHtml).toContain('Ada N00');
|
||||
expect(firstHtml).toContain(`Ada N${String(CONTACT_LIST_PAGE - 1).padStart(2, '0')}`);
|
||||
expect(rowMarkup(firstHtml, 'Ada N00')).not.toContain('hidden');
|
||||
expect(rowMarkup(firstHtml, `Ada N${String(CONTACT_LIST_PAGE).padStart(2, '0')}`)).toContain('hidden');
|
||||
expect(firstHtml).toContain('See more');
|
||||
expect(firstHtml).toContain(`data-see-more="${CONTACT_LIST_PAGE}"`);
|
||||
expect(firstHtml).toContain(`shown=${CONTACT_LIST_PAGE * 2}#contact-more`);
|
||||
expect(firstHtml).not.toContain('#contacts-list');
|
||||
expect(firstHtml).toMatch(/href="\/admin\/contacts\/\d+"/);
|
||||
|
||||
const searched = await app.request('/admin/contacts?q=ada', { headers: { cookie } });
|
||||
const searchedHtml = await searched.text();
|
||||
expect(searchedHtml).toContain('See more');
|
||||
expect(searchedHtml).toContain('q=ada');
|
||||
expect(searchedHtml).toContain(`shown=${CONTACT_LIST_PAGE * 2}`);
|
||||
|
||||
const rest = await app.request(`/admin/contacts?shown=${CONTACT_LIST_PAGE * 2}`, { headers: { cookie } });
|
||||
const restHtml = await rest.text();
|
||||
expect(rowMarkup(restHtml, `Ada N${String(CONTACT_LIST_PAGE).padStart(2, '0')}`)).not.toContain('hidden');
|
||||
expect(restHtml).not.toContain('See more');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(CONTACT_LIST_PAGE + 1);
|
||||
});
|
||||
|
||||
it('imports a file for a coordinator and keeps it off the public site', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const loggedOut = await app.request('/admin/contacts');
|
||||
expect(loggedOut.status).toBe(303);
|
||||
expect(await loggedOut.text()).not.toContain('example.invalid');
|
||||
|
||||
const cookie = await signIn(app, db);
|
||||
const home = await app.request('/admin', { headers: { cookie } });
|
||||
expect(await home.text()).toContain('href="/admin/contacts"');
|
||||
|
||||
const stale = await postFile(app, cookie, PEOPLE, 'nope');
|
||||
expect(stale.status).toBe(403);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
|
||||
|
||||
const imported = await postFile(app, cookie, PEOPLE);
|
||||
expect(imported.status).toBe(303);
|
||||
const page = await app.request(imported.headers.get('location') ?? '', { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('Saved 3 new contacts. Skipped 1 row.');
|
||||
expect(html).toContain('Row 5 was skipped because the email is not an address.');
|
||||
expect(html).toContain('Kristi Anderson');
|
||||
expect(html).toContain('kara.other@example.invalid');
|
||||
expect(html).not.toContain('not-an-email');
|
||||
expect(html).not.toContain('123 Main');
|
||||
expect(await (await app.request('/')).text()).not.toContain('kristi@example.invalid');
|
||||
expect(await (await app.request('/')).text()).not.toContain('Kristi Anderson');
|
||||
|
||||
const searched = await app.request('/admin/contacts?q=%3Cscript%3E', { headers: { cookie } });
|
||||
const searchHtml = await searched.text();
|
||||
expect(searchHtml).toContain('value="<script>"');
|
||||
expect(searchHtml).not.toContain('value="<script>"');
|
||||
expect(searchHtml).toContain('No contacts match.');
|
||||
|
||||
const found = await app.request('/admin/contacts?q=kristi', { headers: { cookie } });
|
||||
const foundHtml = await found.text();
|
||||
expect(foundHtml).toContain('Kristi Anderson');
|
||||
expect(foundHtml).not.toContain('kara@example.invalid');
|
||||
expect(foundHtml).not.toContain('See more');
|
||||
|
||||
const file = await postExport(app, cookie);
|
||||
expect(file.status).toBe(200);
|
||||
expect(file.headers.get('content-type')).toContain('text/csv');
|
||||
expect(file.headers.get('cache-control')).toBe('no-store');
|
||||
expect(file.headers.get('content-disposition')).toBe('attachment; filename="hope-contacts.csv"');
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
expect([...bytes.slice(0, 3)]).toEqual([0xef, 0xbb, 0xbf]);
|
||||
const csv = new TextDecoder().decode(bytes);
|
||||
expect(csv).toContain('kristi@example.invalid');
|
||||
expect(csv).not.toContain('123 Main');
|
||||
const exportAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.export'`).get() as {
|
||||
detail_json: string;
|
||||
};
|
||||
expect(exportAudit.detail_json).toBe('{"rows":3}');
|
||||
|
||||
const hidden = await app.request('/admin/contacts/export', { method: 'POST' });
|
||||
expect(hidden.status).toBe(303);
|
||||
expect(await hidden.text()).not.toContain('kristi@example.invalid');
|
||||
});
|
||||
|
||||
it('fills a walk-in from a saved contact and can remove the contact afterward', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
await postFile(app, cookie, 'First Name,Last Name,Email,Phone\nAda,Example,ada@example.invalid,7125550101\n');
|
||||
const shiftId = insertShift(db);
|
||||
const shift = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||
const shiftHtml = await shift.text();
|
||||
expect(shiftHtml).toContain('Saved contact');
|
||||
expect(shiftHtml).toContain('data-contact');
|
||||
const contactId = /value="(\d+)" data-name="Ada Example"/.exec(shiftHtml)?.[1] ?? '';
|
||||
expect(contactId).not.toBe('');
|
||||
|
||||
const added = await postWalkIn(app, cookie, shiftId, shiftHtml, { contact: contactId, name: '', email: '', phone: '' });
|
||||
expect(added.status).toBe(303);
|
||||
expect(added.headers.get('location')).toContain('notice=walk-in');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid' AND name = 'Ada Example'")).toBe(1);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND to_email = 'ada@example.invalid'")).toBe(1);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1);
|
||||
|
||||
const typedPage = await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } });
|
||||
const typed = await postWalkIn(app, cookie, shiftId, await typedPage.text(), {
|
||||
name: 'Pat Example',
|
||||
email: 'pat@example.invalid',
|
||||
phone: '7125550199',
|
||||
});
|
||||
expect(typed.status).toBe(303);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(1);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'pat@example.invalid'")).toBe(1);
|
||||
|
||||
const missing = await postWalkIn(app, cookie, shiftId, await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text(), {
|
||||
contact: '999',
|
||||
name: '',
|
||||
email: '',
|
||||
});
|
||||
expect(missing.status).toBe(400);
|
||||
expect(await missing.text()).toContain('That saved contact is not available.');
|
||||
|
||||
const asking = await app.request(`/admin/contacts/${contactId}/remove`, { headers: { cookie } });
|
||||
const askingHtml = await asking.text();
|
||||
expect(askingHtml).toContain('Remove Ada Example');
|
||||
expect(askingHtml).toContain('does not cancel a signup');
|
||||
const removed = await postRemove(app, cookie, `/admin/contacts/${contactId}/remove`);
|
||||
expect(removed.status).toBe(303);
|
||||
const after = await app.request(removed.headers.get('location') ?? '', { headers: { cookie } });
|
||||
expect(await after.text()).toContain('That person is removed from the contact list.');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid' AND status = 'confirmed'")).toBe(1);
|
||||
const removeAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.remove'`).get() as {
|
||||
detail_json: string;
|
||||
};
|
||||
expect(removeAudit.detail_json).toBe(`{"id":${contactId}}`);
|
||||
expect(removeAudit.detail_json).not.toContain('@');
|
||||
});
|
||||
|
||||
it('adds a contact to an open shift and leaves full, ended, and cancelled shifts off the list', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const openId = insertShift(db);
|
||||
const unpublishedId = insertShift(db, {
|
||||
slug: 'soup',
|
||||
title: 'Soup kitchen',
|
||||
role: 'Serving',
|
||||
published: 0,
|
||||
start: '2026-10-22T14:00:00.000Z',
|
||||
end: '2026-10-22T17:00:00.000Z',
|
||||
});
|
||||
insertShift(db, {
|
||||
slug: 'closed',
|
||||
title: 'Closed pantry',
|
||||
role: 'Closing',
|
||||
cancelled: 1,
|
||||
});
|
||||
insertShift(db, {
|
||||
slug: 'finished',
|
||||
title: 'Finished pantry',
|
||||
role: 'Finished',
|
||||
start: '2026-10-14T14:00:00.000Z',
|
||||
end: '2026-10-14T17:00:00.000Z',
|
||||
});
|
||||
const fullId = insertShift(db, {
|
||||
slug: 'packed',
|
||||
title: 'Packed pantry',
|
||||
role: 'Packing',
|
||||
capacity: 1,
|
||||
start: '2026-10-23T14:00:00.000Z',
|
||||
end: '2026-10-23T17:00:00.000Z',
|
||||
});
|
||||
db.prepare(
|
||||
`INSERT INTO signups (shift_id, name, email, email_norm, group_size, status, created_at, updated_at)
|
||||
VALUES (?, 'Other Person', 'other@example.invalid', 'other@example.invalid', 1, 'confirmed', ?, ?)`,
|
||||
).run(fullId, NOW, NOW);
|
||||
|
||||
const imported = await postFile(app, cookie, 'First Name,Last Name,Email,Phone\nAda,Example,ada@example.invalid,555-0100\n');
|
||||
expect(imported.status).toBe(303);
|
||||
const contactId = (db.prepare(`SELECT id AS id FROM contacts WHERE email = 'ada@example.invalid'`).get() as { id: number }).id;
|
||||
const loggedOut = await app.request(`/admin/contacts/${contactId}`);
|
||||
expect(loggedOut.status).toBe(303);
|
||||
|
||||
const list = await app.request('/admin/contacts', { headers: { cookie } });
|
||||
expect(await list.text()).toContain(`href="/admin/contacts/${contactId}"`);
|
||||
|
||||
const person = await app.request(`/admin/contacts/${contactId}`, { headers: { cookie } });
|
||||
const personHtml = await person.text();
|
||||
expect(person.status).toBe(200);
|
||||
expect(personHtml).toContain('555-0100');
|
||||
expect(personHtml).toContain('id="add-shift"');
|
||||
expect(personHtml).toContain('Choose a shift');
|
||||
expect(personHtml).toContain(`<option value="${openId}">`);
|
||||
expect(personHtml).toContain(`<option value="${unpublishedId}">`);
|
||||
expect(personHtml).toContain('Serving');
|
||||
expect(personHtml).toContain('(not on the public list)');
|
||||
expect(personHtml).not.toContain('Closing');
|
||||
expect(personHtml).not.toContain('Finished');
|
||||
expect(personHtml).not.toContain('Packing');
|
||||
expect(personHtml).toContain('Add to this shift');
|
||||
expect(personHtml).toContain('They are under 18');
|
||||
|
||||
const beforeMail = count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`);
|
||||
expect(beforeMail).toBe(0);
|
||||
|
||||
const minor = await postContactShift(app, cookie, contactId, openId, personHtml, { under18: 'yes' });
|
||||
expect(minor.status).toBe(400);
|
||||
const minorHtml = await minor.text();
|
||||
expect(minorHtml).toContain('Enter the guardian name.');
|
||||
expect(minorHtml).toContain(`<option value="${openId}" selected="">`);
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(0);
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`)).toBe(0);
|
||||
|
||||
const stale = await postContactShift(app, cookie, contactId, openId, personHtml.replace(/name="form_token" value="[^"]*"/, 'name="form_token" value="nope"'), {});
|
||||
expect(stale.status).toBe(400);
|
||||
expect(await stale.text()).toContain('This form is out of date. Submit it again.');
|
||||
|
||||
const full = await postContactShift(app, cookie, contactId, fullId, personHtml, {});
|
||||
expect(full.status).toBe(400);
|
||||
expect(await full.text()).toContain('That shift is not open.');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(0);
|
||||
|
||||
const added = await postContactShift(app, cookie, contactId, openId, personHtml, { notes: 'Came to the door' });
|
||||
expect(added.status).toBe(303);
|
||||
expect(added.headers.get('location')).toBe(`/admin/shifts/${openId}?notice=walk-in`);
|
||||
const roster = await app.request(added.headers.get('location') ?? '', { headers: { cookie } });
|
||||
const rosterHtml = await roster.text();
|
||||
expect(rosterHtml).toContain('They are on this shift. A confirmation email is queued.');
|
||||
expect(rosterHtml).toContain('Ada Example');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM contacts`)).toBe(1);
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid' AND status = 'confirmed'`)).toBe(1);
|
||||
expect((db.prepare(`SELECT phone AS phone, notes AS notes FROM signups WHERE email_norm = 'ada@example.invalid'`).get() as { phone: string; notes: string }).phone).toBe('555-0100');
|
||||
expect((db.prepare(`SELECT notes AS notes FROM signups WHERE email_norm = 'ada@example.invalid'`).get() as { notes: string }).notes).toBe('Came to the door');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`)).toBe(1);
|
||||
const walkInAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'signup.walkin'`).get() as { detail_json: string };
|
||||
expect(walkInAudit.detail_json).not.toContain('@');
|
||||
|
||||
const minorFile = await postFile(app, cookie, 'First Name,Last Name,Email\nBea,Minor,bea@example.invalid\n');
|
||||
expect(minorFile.status).toBe(303);
|
||||
const beaId = (db.prepare(`SELECT id AS id FROM contacts WHERE email = 'bea@example.invalid'`).get() as { id: number }).id;
|
||||
const beaPage = await app.request(`/admin/contacts/${beaId}`, { headers: { cookie } });
|
||||
const beaHtml = await beaPage.text();
|
||||
expect(beaPage.status).toBe(200);
|
||||
expect(beaHtml).toContain(`<option value="${unpublishedId}">`);
|
||||
const beaAdded = await postContactShift(app, cookie, beaId, unpublishedId, beaHtml, {
|
||||
under18: 'yes',
|
||||
guardianName: 'Pat Minor',
|
||||
guardianEmail: 'pat@example.invalid',
|
||||
});
|
||||
expect(beaAdded.status).toBe(303);
|
||||
const beaSignup = db.prepare(
|
||||
`SELECT is_minor AS is_minor, guardian_name AS guardian_name, guardian_email AS guardian_email
|
||||
FROM signups WHERE email_norm = 'bea@example.invalid'`,
|
||||
).get() as { is_minor: number; guardian_name: string; guardian_email: string };
|
||||
expect(beaSignup).toEqual({ is_minor: 1, guardian_name: 'Pat Minor', guardian_email: 'pat@example.invalid' });
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM contacts`)).toBe(2);
|
||||
const mailed = db
|
||||
.prepare(`SELECT to_email AS to_email FROM outbox WHERE kind = 'confirmation' ORDER BY to_email`)
|
||||
.all() as Array<{ to_email: string }>;
|
||||
expect(mailed.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid', 'pat@example.invalid']);
|
||||
|
||||
const againPage = await app.request(`/admin/contacts/${contactId}`, { headers: { cookie } });
|
||||
const againPageHtml = await againPage.text();
|
||||
expect(againPageHtml).not.toContain(`<option value="${openId}">`);
|
||||
const again = await postContactShift(app, cookie, contactId, openId, againPageHtml, {});
|
||||
expect(again.status).toBe(400);
|
||||
expect(await again.text()).toContain('That person is already signed up for this shift.');
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'`)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
async function openDb() {
|
||||
const root = mkdtempSync(path.join(tmpdir(), 'hope-contacts-'));
|
||||
dirs.push(root);
|
||||
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
|
||||
const db = await openAppDatabase(config);
|
||||
databases.push(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
async function buildApp() {
|
||||
const db = await openDb();
|
||||
bootstrapAdmin(db, 'coordinator@example.invalid', NOW);
|
||||
const config = loadConfig(devEnv({ DATA_DIR: path.join(path.dirname(path.dirname(db.name)), 'data') }));
|
||||
const app = createApp(config, db, {
|
||||
now: NOW,
|
||||
clientIp: () => '203.0.113.50',
|
||||
verifyTurnstile: async () => ({ ok: true }),
|
||||
});
|
||||
return { app, db };
|
||||
}
|
||||
|
||||
function insertShift(
|
||||
db: Awaited<ReturnType<typeof openDb>>,
|
||||
options?: {
|
||||
role?: string;
|
||||
start?: string;
|
||||
end?: string;
|
||||
capacity?: number;
|
||||
cancelled?: number;
|
||||
published?: number;
|
||||
title?: string;
|
||||
slug?: string;
|
||||
},
|
||||
): number {
|
||||
const eventId = Number(
|
||||
db.prepare(
|
||||
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
|
||||
VALUES (?, ?, '', 'Sioux Center, Iowa', 'America/Chicago', ?, ?)`,
|
||||
).run(options?.slug ?? 'weekly', options?.title ?? 'Weekly pantry', options?.published ?? 1, NOW).lastInsertRowid,
|
||||
);
|
||||
return Number(
|
||||
db.prepare(
|
||||
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
|
||||
VALUES (?, ?, ?, ?, ?, '', ?)`,
|
||||
).run(
|
||||
eventId,
|
||||
options?.role ?? 'Sorting',
|
||||
options?.start ?? '2026-10-21T14:00:00.000Z',
|
||||
options?.end ?? '2026-10-21T17:00:00.000Z',
|
||||
options?.capacity ?? 4,
|
||||
options?.cancelled ?? 0,
|
||||
).lastInsertRowid,
|
||||
);
|
||||
}
|
||||
|
||||
function rowMarkup(html: string, name: string): string {
|
||||
const at = html.indexOf(`>${name}<`);
|
||||
const li = html.lastIndexOf('<li', at);
|
||||
return li < 0 || at < 0 ? '' : html.slice(li, at);
|
||||
}
|
||||
|
||||
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string): number {
|
||||
return (db.prepare(sql).get() as { n: number }).n;
|
||||
}
|
||||
|
||||
async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awaited<ReturnType<typeof openDb>>) {
|
||||
await app.request('/login', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ email: 'coordinator@example.invalid', company_website: '', 'cf-turnstile-response': 'token' }),
|
||||
});
|
||||
const queued = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'magic_link'`).get() as { body_text: string };
|
||||
const token = /\/login\/link\/([A-Za-z0-9_-]+)/.exec(queued.body_text)?.[1] ?? '';
|
||||
const page = await app.request(`/login/link/${token}`);
|
||||
const proof = /name="proof"[^>]*value="([^"]*)"/.exec(await page.text())?.[1] ?? '';
|
||||
const signedIn = await app.request(`/login/link/${token}`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ proof }),
|
||||
});
|
||||
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
|
||||
return `hope_session=${cookie}`;
|
||||
}
|
||||
|
||||
async function postFile(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, csv: string, csrf?: string) {
|
||||
const current = await app.request('/admin/contacts', { headers: { cookie } });
|
||||
const token = csrf ?? (/name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? '');
|
||||
const body = new FormData();
|
||||
body.set('csrf', token);
|
||||
body.set('file', new File([csv], 'people.csv', { type: 'text/csv' }));
|
||||
return app.request('/admin/contacts/import', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, cookie },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
async function postExport(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string) {
|
||||
const current = await app.request('/admin/contacts', { headers: { cookie } });
|
||||
const token = /name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? '';
|
||||
return app.request('/admin/contacts/export', {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf: token }),
|
||||
});
|
||||
}
|
||||
|
||||
async function postWalkIn(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
shiftId: number,
|
||||
html: string,
|
||||
fields: { contact?: string; name?: string; email?: string; phone?: string },
|
||||
) {
|
||||
const csrf = /name="csrf" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||
const formToken = /name="form_token" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||
return app.request(`/admin/shifts/${shiftId}/walk-in`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({
|
||||
csrf,
|
||||
form_token: formToken,
|
||||
contact: fields.contact ?? '',
|
||||
name: fields.name ?? '',
|
||||
email: fields.email ?? '',
|
||||
phone: fields.phone ?? '',
|
||||
notes: '',
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function postContactShift(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
cookie: string,
|
||||
contactId: number,
|
||||
shiftId: number,
|
||||
html: string,
|
||||
fields: { under18?: string; guardianName?: string; guardianEmail?: string; notes?: string },
|
||||
) {
|
||||
const csrf = /name="csrf" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||
const formToken = /name="form_token" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||
return app.request(`/admin/contacts/${contactId}/add`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({
|
||||
csrf,
|
||||
form_token: formToken,
|
||||
shift: String(shiftId),
|
||||
notes: fields.notes ?? '',
|
||||
under18: fields.under18 ?? '',
|
||||
guardianName: fields.guardianName ?? '',
|
||||
guardianEmail: fields.guardianEmail ?? '',
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function postRemove(app: Awaited<ReturnType<typeof buildApp>>['app'], cookie: string, pathName: string) {
|
||||
const current = await app.request(pathName, { headers: { cookie } });
|
||||
const token = /name="csrf" value="([^"]*)"/.exec(await current.text())?.[1] ?? '';
|
||||
return app.request(pathName, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf: token }),
|
||||
});
|
||||
}
|
||||
@@ -44,6 +44,7 @@ describe('database startup', () => {
|
||||
expect(names).toEqual(
|
||||
[
|
||||
'audit',
|
||||
'contacts',
|
||||
'coordinators',
|
||||
'events',
|
||||
'job_runs',
|
||||
|
||||
+3
-1
@@ -10,6 +10,7 @@ export function devEnv(overrides: NodeJS.ProcessEnv = {}): NodeJS.ProcessEnv {
|
||||
MAIL_DRIVER: 'console',
|
||||
MAIL_FROM: 'Hope Food Pantry <volunteer@example.invalid>',
|
||||
MAIL_REPLY_TO: 'volunteer@example.invalid',
|
||||
SMTP2GO_API_KEY: '',
|
||||
POSTMARK_TOKEN: '',
|
||||
SES_REGION: '',
|
||||
SES_ACCESS_KEY_ID: '',
|
||||
@@ -29,9 +30,10 @@ export function productionEnv(dataDir: string, overrides: NodeJS.ProcessEnv = {}
|
||||
BASE_URL: 'https://volunteer.example.org',
|
||||
DATA_DIR: dataDir,
|
||||
SESSION_SECRET: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',
|
||||
MAIL_DRIVER: 'postmark',
|
||||
MAIL_DRIVER: 'smtp2go',
|
||||
MAIL_FROM: 'Hope Food Pantry <volunteer@example.org>',
|
||||
MAIL_REPLY_TO: 'volunteer@example.org',
|
||||
SMTP2GO_API_KEY: 'api-9f3a2c1e5b8d4f70a1b2c3d4e5f6',
|
||||
POSTMARK_TOKEN: 'pm-server-token-9f3a2c1e5b8d4f70',
|
||||
TURNSTILE_SITE_KEY: '0x4AAAAAAA8k2mRealishSiteKey00',
|
||||
TURNSTILE_SECRET_KEY: '0x4AAAAAAA8k2mRealishSecretKey00',
|
||||
|
||||
@@ -12,6 +12,7 @@ import { issueFormToken } from '../src/form-token.js';
|
||||
import { deliverDueMail } from '../src/mail/deliver.js';
|
||||
import { createPostmarkMailer } from '../src/mail/postmark.js';
|
||||
import { createSesMailer } from '../src/mail/ses.js';
|
||||
import { createSmtp2GoMailer } from '../src/mail/smtp2go.js';
|
||||
import { renderConfirmation } from '../src/mail/templates.js';
|
||||
import type { Mailer } from '../src/mail/types.js';
|
||||
import { reserveSignup, type ReserveInput } from '../src/signup.js';
|
||||
@@ -200,6 +201,48 @@ describe('transactional mail', () => {
|
||||
});
|
||||
|
||||
describe('mail drivers', () => {
|
||||
it('treats SMTP2GO acceptance, a rejected sender, and a lost connection differently', async () => {
|
||||
const message = sample();
|
||||
const accepted = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async (url, init) => {
|
||||
expect(String(url)).toBe('https://api.smtp2go.com/v3/email/send');
|
||||
const headers = init?.headers as Record<string, string>;
|
||||
expect(headers['X-Smtp2go-Api-Key']).toBe('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6');
|
||||
const body = JSON.parse(String(init?.body)) as {
|
||||
sender: string;
|
||||
to: string[];
|
||||
custom_headers: { header: string; value: string }[];
|
||||
fastaccept?: boolean;
|
||||
};
|
||||
expect(body.sender).toBe(message.from);
|
||||
expect(body.to).toEqual([message.to]);
|
||||
expect(body.fastaccept).toBeUndefined();
|
||||
expect(body.custom_headers).toContainEqual({ header: 'Reply-To', value: message.replyTo });
|
||||
expect(String(init?.body)).not.toContain('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6');
|
||||
return json({ data: { succeeded: 1, failed: 0, failures: [], email_id: 'smtp2go-1' } }, 200);
|
||||
});
|
||||
expect(await accepted.send(message)).toEqual({ result: 'sent', providerId: 'smtp2go-1' });
|
||||
|
||||
const rejected = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async () => json({
|
||||
data: { succeeded: 0, failed: 1, failures: ['From header sender domain not verified for pat@example.invalid'] },
|
||||
}, 200));
|
||||
const failed = await rejected.send(message);
|
||||
expect(failed.result).toBe('failed');
|
||||
if (failed.result === 'failed') expect(failed.error).not.toContain('pat@example.invalid');
|
||||
|
||||
const denied = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async () => json({
|
||||
data: { error: 'You do not have permission', error_code: 'E_ApiResponseCodes.ENDPOINT_PERMISSION_DENIED' },
|
||||
}, 400));
|
||||
expect((await denied.send(message)).result).toBe('failed');
|
||||
|
||||
const busy = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async () => new Response('no', { status: 429 }));
|
||||
expect((await busy.send(message)).result).toBe('retry');
|
||||
|
||||
const down = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async () => {
|
||||
throw Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' });
|
||||
});
|
||||
expect((await down.send(message)).result).toBe('retry');
|
||||
});
|
||||
|
||||
it('treats Postmark acceptance, rejection, and a lost connection differently', async () => {
|
||||
const message = sample();
|
||||
const accepted = createPostmarkMailer('server-token-value', async (_url, init) => {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { verifyTurnstile } from '../src/turnstile.js';
|
||||
import { createPostmarkMailer } from '../src/mail/postmark.js';
|
||||
import { createSesMailer } from '../src/mail/ses.js';
|
||||
import { createSmtp2GoMailer } from '../src/mail/smtp2go.js';
|
||||
|
||||
const timeout = AbortSignal.timeout.bind(AbortSignal);
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
@@ -47,6 +48,18 @@ describe('outbound request deadlines', () => {
|
||||
expect(result).toEqual({ok:false, reason:'unavailable'});
|
||||
});
|
||||
|
||||
it('marks an SMTP2GO timeout uncertain instead of retrying', async () => {
|
||||
shortDeadline(15_000);
|
||||
const driver = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async (_url, init) => stalled(init?.signal));
|
||||
expect((await driver.send(mail)).result).toBe('unknown');
|
||||
});
|
||||
|
||||
it('marks a stalled SMTP2GO success body uncertain', async () => {
|
||||
shortDeadline(15_000);
|
||||
const driver = createSmtp2GoMailer('api-9f3a2c1e5b8d4f70a1b2c3d4e5f6', async (_url, init) => Object.assign(new Response('{}'), { json: () => stalled(init?.signal) }));
|
||||
expect((await driver.send(mail)).result).toBe('unknown');
|
||||
});
|
||||
|
||||
it('marks a Postmark timeout uncertain instead of retrying', async () => {
|
||||
shortDeadline(15_000);
|
||||
const driver = createPostmarkMailer('test-token', async (_url, init) => stalled(init?.signal));
|
||||
|
||||
Reference in new issue
Block a user