feat: require phone and drop under-18 signup
Phone is required on public and coordinator forms, and the under-18 guardian flow, mail copies, and export columns are removed.
This commit is contained in:
1 parent
7cfb984d63
commit
58da832bac
27 files changed
+207
-544
No files matched your search
@@ -46,8 +46,8 @@ 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.
|
Do not treat this repository as an approved privacy policy or an approved operating setup.
|
||||||
|
|
||||||
- [ ] **D1.** SMTP2GO is the email provider. The pantry verifies the sender and the 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.
|
- [ ] **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, 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.
|
- [ ] **D3.** The pantry approves privacy wording and retention periods, including copies and exports.
|
||||||
- [ ] **D4.** The pantry confirms the coordinator list, who owns the administrator account, and the recovery contact.
|
- [ ] **D4.** The pantry confirms the coordinator list, who owns the administrator account, and the recovery contact.
|
||||||
- [ ] **D5.** Configure production Turnstile keys and the allowed hostname.
|
- [ ] **D5.** Configure production Turnstile keys and the allowed hostname.
|
||||||
- [ ] **D6.** The host owner confirms the offsite backup destination, who owns it, the recovery target, and a restore test.
|
- [ ] **D6.** The host owner confirms the offsite backup destination, who owns it, the recovery target, and a restore test.
|
||||||
@@ -73,7 +73,7 @@ npm run seed
|
|||||||
|
|
||||||
Open `/` for the weekly pantry schedule. `/e/weekly-pantry` is the same seeded event. `/privacy` is the unapproved privacy notice. `/healthz` returns `{"ok":true,"database":"ok"}` and nothing else. Volunteer names, emails, and notes are not on the public list. A shift shows how many spots are filled, such as 3/5 spots filled. A shift with space left uses a soft green label. A full shift uses a soft red label.
|
Open `/` for the weekly pantry schedule. `/e/weekly-pantry` is the same seeded event. `/privacy` is the unapproved privacy notice. `/healthz` returns `{"ok":true,"database":"ok"}` and nothing else. Volunteer names, emails, and notes are not on the public list. A shift shows how many spots are filled, such as 3/5 spots filled. A shift with space left uses a soft green label. A full shift uses a soft red label.
|
||||||
|
|
||||||
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 on the way. 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.
|
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. 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 on the way. 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. SMTP2GO is the mail provider. Set `MAIL_DRIVER=smtp2go` and `SMTP2GO_API_KEY` to send through it. Postmark and SES remain available.
|
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.
|
||||||
|
|
||||||
@@ -89,9 +89,9 @@ On a confirmed signup, **Attended** and **No-show** record whether that person c
|
|||||||
|
|
||||||
On the private signup page, **Switch to** does the same thing for the volunteer. The next page has the new link. A full, cancelled, ended, or unpublished shift is not offered. A switch is rejected if that name and email already occupy the destination shift. The destination list does not reveal which other shifts match those details. If the switch cannot be saved, the original signup stays.
|
On the private signup page, **Switch to** does the same thing for the volunteer. The next page has the new link. A full, cancelled, ended, or unpublished shift is not offered. A switch is rejected if that name and email already occupy the destination shift. The destination list does not reveal which other shifts match those details. If the switch cannot be saved, the original signup stays.
|
||||||
|
|
||||||
Public switching permits 10 validated attempts per IP per 10-minute window and 5 per recipient per local calendar day (`DEFAULT_TZ`). Volunteer and guardian addresses share the same recipient counter; a shared address is counted once. These HMAC-keyed counters live in SQLite and survive link changes, new signup IDs, and restarts. A blocked request returns HTTP 429 with `Retry-After`, leaves the signup unchanged, and queues no email. Invalid origins, invalid proofs, and completed replays do not spend recipient allowances. Valid attempts that fail because a destination is full or unavailable still count. Viewing or cancelling a signup remains available when switching is limited. Coordinator roster moves use their authenticated workflow and are not subject to these public switch limits.
|
Public switching permits 10 validated attempts per IP per 10-minute window and 5 per recipient per local calendar day (`DEFAULT_TZ`). These HMAC-keyed counters live in SQLite and survive link changes, new signup IDs, and restarts. A blocked request returns HTTP 429 with `Retry-After`, leaves the signup unchanged, and queues no email. Invalid origins, invalid proofs, and completed replays do not spend recipient allowances. Valid attempts that fail because a destination is full or unavailable still count. Viewing or cancelling a signup remains available when switching is limited. Coordinator roster moves use their authenticated workflow and are not subject to these public switch limits.
|
||||||
|
|
||||||
**Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies, email, and guardian copies. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately.
|
**Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies and email. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately.
|
||||||
|
|
||||||
**Add weekly shifts**, on a coordinator event page, fills the next eight weeks from that event's active weekly templates. Starting the app does the same thing for every event. A shift that is already on that date stays as it is, including a cancelled one, so the template cannot recreate it. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped.
|
**Add weekly shifts**, on a coordinator event page, fills the next eight weeks from that event's active weekly templates. Starting the app does the same thing for every event. A shift that is already on that date stays as it is, including a cancelled one, so the template cannot recreate it. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped.
|
||||||
|
|
||||||
@@ -103,13 +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.
|
**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. A confirmed signup is saved on this list. The name is split at the last space. A signup name with no space is saved with a hyphen as the last name. A different name is a separate contact, even when the email matches. The same name and email updates that contact. Cancelling the signup does not remove the contact. Saving someone here does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A word that already mixes upper and lower case stays as written. A phone number with ten digits is saved with dashes, like 712-555-0100. A leading 1 is left off. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Correct this contact**, on that page, saves a corrected name, email, or phone on the same person. A phone typo can be replaced. A hyphen saved as the last name can be replaced with the real last name. Changing the name does not create a second person, even when the email stays the same. A blank phone removes the saved number. It does not change a signup, take a spot, or send email. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. **Add a contact** saves one person who has not signed up. It does not take a spot and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Typing a walk-in who is not on the list saves them here too.
|
**Contacts**, on the coordinator page, keeps a list of people. A confirmed signup is saved on this list. The name is split at the last space. A signup name with no space is saved with a hyphen as the last name. A different name is a separate contact, even when the email matches. The same name and email updates that contact. Cancelling the signup does not remove the contact. Saving someone here does not sign them up for a shift. **Import this list** reads a spreadsheet with First Name, Last Name, Email, and Phone, including the SignUpGenius people export. An Address column is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A row without a phone is skipped. Names are capitalized. A word that already mixes upper and lower case stays as written. A phone number with ten digits is saved with dashes, like 712-555-0100. A leading 1 is left off. Email addresses are stored in lowercase. Importing does not take a spot and does not send email. **Download contacts** saves that list. A cell that would be a spreadsheet formula is saved as text. A downloaded copy stays on the coordinator's computer. The signup retention job does not clear this list. The list is the contacts table in `app.db`. The list shows 20 people. **See more** shows the next 20 on this page, without returning to the top, and keeps a search. **Choose a name**, then choose the shift from **Shift**. That takes one spot and queues a confirmation email. A full, cancelled, or ended shift is not in that list, and a shift they are already on is not in that list. A shift that is not on the public list can still be chosen. **Correct this contact**, on that page, saves a corrected name, email, or phone on the same person. A phone typo can be replaced. A hyphen saved as the last name can be replaced with the real last name. Changing the name does not create a second person, even when the email stays the same. Phone is required. It does not change a signup, take a spot, or send email. **Remove** deletes that person from the list only. On an open shift, **Saved contact** fills a walk-in. The walk-in still takes one spot and queues a confirmation email. **Add a contact** saves one person who has not signed up. It does not take a spot and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Typing a walk-in who is not on the list saves them here too.
|
||||||
|
|
||||||
**Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration.
|
**Settings**, on the coordinator page, saves the two reminder times, the reply-to address, the privacy-page wording, and how many months to keep a signup after the shift ends. The defaults are 48 hours, 2 hours, the reply-to address from the server configuration, a blank privacy notice, and 24 months. The two reminder times have to be different whole hours from 1 to 336. The month count is a whole number from 1 to 120. A blank privacy notice leaves the public page saying a notice is not approved yet. Saved wording is shown on `/privacy` as written. Saving it does not by itself make that wording an approved privacy policy. New mail uses the saved reply-to address. Mail already queued keeps the address it was given. The sending address stays in the server configuration.
|
||||||
|
|
||||||
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.
|
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. The contact list is separate. Clearing an old signup does not remove that person from the contact list.
|
After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, 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. Legacy guardian columns, when present, are cleared too. 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.
|
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.
|
||||||
|
|
||||||
@@ -156,7 +156,7 @@ SQLite runs in WAL mode with foreign keys on. Migrations in `migrations/` are ap
|
|||||||
|
|
||||||
There is no cascade delete. A shift that still has signups cannot be deleted out from under the roster. A coordinator cancels a signup or a shift first. Removing a cancelled person, then an empty finished shift, is a separate step. Removing an ended template leaves its shifts in place. An event can be removed only when it is off the public list and nothing remains on it.
|
There is no cascade delete. A shift that still has signups cannot be deleted out from under the roster. A coordinator cancels a signup or a shift first. Removing a cancelled person, then an empty finished shift, is a separate step. Removing an ended template leaves its shifts in place. An event can be removed only when it is off the public list and nothing remains on it.
|
||||||
|
|
||||||
Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. A minor who is not anonymized needs a guardian name and email. `group_size` cannot be anything but 1.
|
Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. New signups always store `is_minor` as 0 with null guardian fields; legacy columns remain for older rows. `group_size` cannot be anything but 1.
|
||||||
|
|
||||||
`reminders_sent.queued_at` means the reminder was queued. `sent_at` means a provider accepted it. Queueing mail is not delivery. A closer reminder that replaces an older overdue one is stored as not sent.
|
`reminders_sent.queued_at` means the reminder was queued. `sent_at` means a provider accepted it. Queueing mail is not delivery. A closer reminder that replaces an older overdue one is stored as not sent.
|
||||||
|
|
||||||
|
|||||||
@@ -1003,11 +1003,6 @@ article.shift-card {
|
|||||||
background: var(--hope-blue-75);
|
background: var(--hope-blue-75);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Parent or guardian stays closed until Under 18 is checked, on every signup form. */
|
|
||||||
.signup-form:not(:has([data-under-18]:checked)) [data-guardian] {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.signup-form legend {
|
.signup-form legend {
|
||||||
padding: 0 0.35rem;
|
padding: 0 0.35rem;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,6 @@
|
|||||||
bindCalendar();
|
bindCalendar();
|
||||||
document.querySelectorAll('[data-contact]').forEach(bindContact);
|
document.querySelectorAll('[data-contact]').forEach(bindContact);
|
||||||
document.querySelectorAll('[data-see-more]').forEach(bindSeeMore);
|
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]);
|
|
||||||
|
|
||||||
function bindNav() {
|
function bindNav() {
|
||||||
var header = document.querySelector('.header');
|
var header = document.querySelector('.header');
|
||||||
@@ -94,18 +92,4 @@
|
|||||||
var input = form.elements[name];
|
var input = form.elements[name];
|
||||||
if (input && 'value' in input) input.value = value;
|
if (input && 'value' in input) input.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
function bind(box) {
|
|
||||||
var form = box.form;
|
|
||||||
if (!form) return;
|
|
||||||
var guardian = form.querySelector('[data-guardian]');
|
|
||||||
if (!guardian) return;
|
|
||||||
var inputs = guardian.querySelectorAll('input');
|
|
||||||
var sync = function () {
|
|
||||||
var on = box.checked;
|
|
||||||
for (var j = 0; j < inputs.length; j += 1) inputs[j].required = on;
|
|
||||||
};
|
|
||||||
box.addEventListener('change', sync);
|
|
||||||
sync();
|
|
||||||
}
|
|
||||||
})();
|
})();
|
||||||
@@ -556,9 +556,6 @@ async function submitAddContactToShift(c: Context, services: AdminServices): Pro
|
|||||||
email: parsed.draft.emailNorm,
|
email: parsed.draft.emailNorm,
|
||||||
phone: parsed.draft.phone,
|
phone: parsed.draft.phone,
|
||||||
notes: parsed.draft.notes,
|
notes: parsed.draft.notes,
|
||||||
isMinor: parsed.draft.isMinor,
|
|
||||||
guardianName: parsed.draft.guardianName,
|
|
||||||
guardianEmail: parsed.draft.guardianEmail,
|
|
||||||
operationId: token.claims.operationId,
|
operationId: token.claims.operationId,
|
||||||
now: services.now(),
|
now: services.now(),
|
||||||
mail: mailIdentity(services.db, services.config),
|
mail: mailIdentity(services.db, services.config),
|
||||||
@@ -1224,9 +1221,6 @@ async function submitWalkIn(c: Context, services: AdminServices): Promise<Respon
|
|||||||
email: parsed.draft.emailNorm,
|
email: parsed.draft.emailNorm,
|
||||||
phone: parsed.draft.phone,
|
phone: parsed.draft.phone,
|
||||||
notes: parsed.draft.notes,
|
notes: parsed.draft.notes,
|
||||||
isMinor: parsed.draft.isMinor,
|
|
||||||
guardianName: parsed.draft.guardianName,
|
|
||||||
guardianEmail: parsed.draft.guardianEmail,
|
|
||||||
operationId: token.claims.operationId,
|
operationId: token.claims.operationId,
|
||||||
now: services.now(),
|
now: services.now(),
|
||||||
mail: mailIdentity(services.db, services.config),
|
mail: mailIdentity(services.db, services.config),
|
||||||
@@ -1571,9 +1565,6 @@ function signupValuesFrom(body: Record<string, unknown>): SignupValues {
|
|||||||
email: textField(body, 'email'),
|
email: textField(body, 'email'),
|
||||||
phone: textField(body, 'phone'),
|
phone: textField(body, 'phone'),
|
||||||
notes: textField(body, 'notes'),
|
notes: textField(body, 'notes'),
|
||||||
under18: textField(body, 'under18') === 'yes',
|
|
||||||
guardianName: textField(body, 'guardianName'),
|
|
||||||
guardianEmail: textField(body, 'guardianEmail'),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+20
-34
@@ -42,7 +42,7 @@ const SHIFT_PEOPLE_BODY = 'Remove everyone on this roster first.';
|
|||||||
const SHIFT_WAIT_BODY = 'Cancel this shift, or wait until it has ended, before removing it.';
|
const SHIFT_WAIT_BODY = 'Cancel this shift, or wait until it has ended, before removing it.';
|
||||||
const SHIFT_WEEKLY_NOTE =
|
const SHIFT_WEEKLY_NOTE =
|
||||||
'This date came from a weekly template that is still active. Add weekly shifts can put this date back. End that template first if the date should stay gone.';
|
'This date came from a weekly template that is still active. Add weekly shifts can put this date back. End that template first if the date should stay gone.';
|
||||||
const PERSON_DELETE_BODY = 'This deletes their name, email, phone, guardian details, and notes from the roster. It does not send email.';
|
const PERSON_DELETE_BODY = 'This deletes their name, email, phone, and notes from the roster. It does not send email.';
|
||||||
const PERSON_WAIT_BODY = 'Cancel this signup before removing it.';
|
const PERSON_WAIT_BODY = 'Cancel this signup before removing it.';
|
||||||
const PERSON_CANCEL_BODY = 'Cancelling a signup emails them. Their old private link stops working, and the email includes a new one.';
|
const PERSON_CANCEL_BODY = 'Cancelling a signup emails them. Their old private link stops working, and the email includes a new one.';
|
||||||
const SHIFT_CANCEL_EMPTY = 'No one is signed up. Cancelling closes the shift and does not send email.';
|
const SHIFT_CANCEL_EMPTY = 'No one is signed up. Cancelling closes the shift and does not send email.';
|
||||||
@@ -341,7 +341,7 @@ export function SettingsPage(props: {
|
|||||||
<label>
|
<label>
|
||||||
Keep signups for, months
|
Keep signups for, months
|
||||||
<input name="retention_months" type="number" min="1" max="120" required value={props.values.retentionMonths} />
|
<input name="retention_months" type="number" min="1" max="120" required value={props.values.retentionMonths} />
|
||||||
<span class="hint">The default is 24, counted after the shift ends. After 1:00 AM Central Time, signups older than this lose their name, email, phone, guardian, and notes in this app. A spreadsheet already downloaded is left as it is.</span>
|
<span class="hint">The default is 24, counted after the shift ends. After 1:00 AM Central Time, signups older than this lose their name, email, phone, and notes in this app. A spreadsheet already downloaded is left as it is.</span>
|
||||||
{errors.retentionMonths ? <span class="error">{errors.retentionMonths}</span> : null}
|
{errors.retentionMonths ? <span class="error">{errors.retentionMonths}</span> : null}
|
||||||
</label>
|
</label>
|
||||||
<label>
|
<label>
|
||||||
@@ -406,18 +406,18 @@ export function ContactsPage(props: {
|
|||||||
<form method="post" action={appPath(props.config, '/admin/contacts/new')} class="signup-form desk-download">
|
<form method="post" action={appPath(props.config, '/admin/contacts/new')} class="signup-form desk-download">
|
||||||
<input type="hidden" name="csrf" value={props.csrf} />
|
<input type="hidden" name="csrf" value={props.csrf} />
|
||||||
<h2>Add a contact</h2>
|
<h2>Add a contact</h2>
|
||||||
<p>This saves one person. It does not sign them up and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.</p>
|
<p>This saves one person. It does not sign them up and does not send email. The same name and email updates that person. A different name is saved separately, even with the same email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.</p>
|
||||||
<WalkInField id="contact-first" label="First name" name="first_name" type="text" value={manual.values.firstName} error={manual.errors.firstName} />
|
<WalkInField id="contact-first" label="First name" name="first_name" type="text" value={manual.values.firstName} error={manual.errors.firstName} />
|
||||||
<WalkInField id="contact-last" label="Last name" name="last_name" type="text" value={manual.values.lastName} error={manual.errors.lastName} />
|
<WalkInField id="contact-last" label="Last name" name="last_name" type="text" value={manual.values.lastName} error={manual.errors.lastName} />
|
||||||
<WalkInField id="contact-email" label="Email" name="email" type="email" value={manual.values.email} error={manual.errors.email} />
|
<WalkInField id="contact-email" label="Email" name="email" type="email" value={manual.values.email} error={manual.errors.email} />
|
||||||
<WalkInField id="contact-phone" label="Phone (optional)" name="phone" type="tel" value={manual.values.phone} error={manual.errors.phone} hint="We will not text them" />
|
<WalkInField id="contact-phone" label="Phone" name="phone" type="tel" value={manual.values.phone} error={manual.errors.phone} required />
|
||||||
<button type="submit">Save this contact</button>
|
<button type="submit">Save this contact</button>
|
||||||
</form>
|
</form>
|
||||||
<form method="post" action={appPath(props.config, '/admin/contacts/import')} class="signup-form desk-download" enctype="multipart/form-data">
|
<form method="post" action={appPath(props.config, '/admin/contacts/import')} class="signup-form desk-download" enctype="multipart/form-data">
|
||||||
<input type="hidden" name="csrf" value={props.csrf} />
|
<input type="hidden" name="csrf" value={props.csrf} />
|
||||||
<h2>Import a contact list</h2>
|
<h2>Import a contact list</h2>
|
||||||
<p>
|
<p>
|
||||||
Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A blank phone does not erase a phone already saved. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. Email addresses are stored in lowercase. The file has to be under 64 KB.
|
Use a spreadsheet with First Name, Last Name, Email, and Phone. The SignUpGenius people export works. Address is ignored. The same name and email updates that person. A different name stays a separate person, even when the email matches. A different email stays a separate person, even when the name matches. A row without a phone is skipped. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. Email addresses are stored in lowercase. The file has to be under 64 KB.
|
||||||
</p>
|
</p>
|
||||||
{props.importError ? <p class="error">{props.importError}</p> : null}
|
{props.importError ? <p class="error">{props.importError}</p> : null}
|
||||||
<label>
|
<label>
|
||||||
@@ -521,19 +521,19 @@ export function ContactPage(props: {
|
|||||||
<input type="hidden" name="csrf" value={props.csrf} />
|
<input type="hidden" name="csrf" value={props.csrf} />
|
||||||
<h2>Correct this contact</h2>
|
<h2>Correct this contact</h2>
|
||||||
<p>
|
<p>
|
||||||
This changes the saved person. A different name stays this contact and does not create a second person. It does not change a signup, take a spot, or send email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100. A blank phone removes the saved number.
|
This changes the saved person. A different name stays this contact and does not create a second person. It does not change a signup, take a spot, or send email. Names are capitalized. A 10-digit phone is saved with dashes, like 712-555-0100.
|
||||||
</p>
|
</p>
|
||||||
<WalkInField id="correct-first" label="First name" name="first_name" type="text" value={correction.values.firstName} error={correction.errors.firstName} />
|
<WalkInField id="correct-first" label="First name" name="first_name" type="text" value={correction.values.firstName} error={correction.errors.firstName} />
|
||||||
<WalkInField id="correct-last" label="Last name" name="last_name" type="text" value={correction.values.lastName} error={correction.errors.lastName} />
|
<WalkInField id="correct-last" label="Last name" name="last_name" type="text" value={correction.values.lastName} error={correction.errors.lastName} />
|
||||||
<WalkInField id="correct-email" label="Email" name="email" type="email" value={correction.values.email} error={correction.errors.email} />
|
<WalkInField id="correct-email" label="Email" name="email" type="email" value={correction.values.email} error={correction.errors.email} />
|
||||||
<WalkInField
|
<WalkInField
|
||||||
id="correct-phone"
|
id="correct-phone"
|
||||||
label="Phone (optional)"
|
label="Phone"
|
||||||
name="phone"
|
name="phone"
|
||||||
type="tel"
|
type="tel"
|
||||||
value={correction.values.phone}
|
value={correction.values.phone}
|
||||||
error={correction.errors.phone}
|
error={correction.errors.phone}
|
||||||
hint="We will not text them"
|
required
|
||||||
/>
|
/>
|
||||||
<button type="submit">Save this correction</button>
|
<button type="submit">Save this correction</button>
|
||||||
</form>
|
</form>
|
||||||
@@ -568,15 +568,6 @@ export function ContactPage(props: {
|
|||||||
</textarea>
|
</textarea>
|
||||||
{errors.notes ? <span class="field-error">{errors.notes}</span> : null}
|
{errors.notes ? <span class="field-error">{errors.notes}</span> : null}
|
||||||
</label>
|
</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>
|
<button type="submit">Add to this shift</button>
|
||||||
</form>
|
</form>
|
||||||
) : (
|
) : (
|
||||||
@@ -1559,7 +1550,7 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
|
|||||||
) : null}
|
) : null}
|
||||||
<WalkInField id="walkin-name" label="Name" name="name" type="text" value={values.name} error={errors.name} />
|
<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-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" />
|
<WalkInField id="walkin-phone" label="Phone" name="phone" type="tel" value={values.phone} error={errors.phone} required />
|
||||||
<label for="walkin-notes">
|
<label for="walkin-notes">
|
||||||
Notes (optional)
|
Notes (optional)
|
||||||
<textarea id="walkin-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined} aria-describedby={errors.notes ? 'walkin-notes-error' : undefined}>
|
<textarea id="walkin-notes" name="notes" aria-invalid={errors.notes ? 'true' : undefined} aria-describedby={errors.notes ? 'walkin-notes-error' : undefined}>
|
||||||
@@ -1571,21 +1562,21 @@ function WalkInForm(props: { config: AppConfig; csrf: string; shiftId: number; f
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
</label>
|
</label>
|
||||||
<label class="check" for="walkin-under-18">
|
|
||||||
<input id="walkin-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="walkin-guardianName" label="Guardian name" name="guardianName" type="text" value={values.guardianName} error={errors.guardianName} />
|
|
||||||
<WalkInField id="walkin-guardianEmail" label="Guardian email" name="guardianEmail" type="email" value={values.guardianEmail} error={errors.guardianEmail} />
|
|
||||||
</fieldset>
|
|
||||||
<button type="submit">Add to this shift</button>
|
<button type="submit">Add to this shift</button>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function WalkInField(props: { id: string; label: string; name: string; type: 'text' | 'email' | 'tel'; value: string; error?: string; hint?: string }) {
|
function WalkInField(props: {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
name: string;
|
||||||
|
type: 'text' | 'email' | 'tel';
|
||||||
|
value: string;
|
||||||
|
error?: string;
|
||||||
|
hint?: string;
|
||||||
|
required?: boolean;
|
||||||
|
}) {
|
||||||
const errorId = `${props.id}-error`;
|
const errorId = `${props.id}-error`;
|
||||||
const hintId = `${props.id}-hint`;
|
const hintId = `${props.id}-hint`;
|
||||||
const describedBy = [props.hint ? hintId : '', props.error ? errorId : ''].filter(Boolean).join(' ') || undefined;
|
const describedBy = [props.hint ? hintId : '', props.error ? errorId : ''].filter(Boolean).join(' ') || undefined;
|
||||||
@@ -1598,6 +1589,7 @@ function WalkInField(props: { id: string; label: string; name: string; type: 'te
|
|||||||
type={props.type}
|
type={props.type}
|
||||||
value={props.value}
|
value={props.value}
|
||||||
autocomplete="off"
|
autocomplete="off"
|
||||||
|
required={props.required ? true : undefined}
|
||||||
aria-invalid={props.error ? 'true' : undefined}
|
aria-invalid={props.error ? 'true' : undefined}
|
||||||
aria-describedby={describedBy}
|
aria-describedby={describedBy}
|
||||||
/>
|
/>
|
||||||
@@ -1631,12 +1623,6 @@ function Roster(props: { config: AppConfig; csrf: string; people: RosterPerson[]
|
|||||||
</p>
|
</p>
|
||||||
<p>{person.email}</p>
|
<p>{person.email}</p>
|
||||||
{person.phone ? <p>{person.phone}</p> : null}
|
{person.phone ? <p>{person.phone}</p> : null}
|
||||||
{person.minor ? <p>Under 18</p> : null}
|
|
||||||
{person.guardianName || person.guardianEmail ? (
|
|
||||||
<p>
|
|
||||||
Guardian: {person.guardianName} {person.guardianEmail}
|
|
||||||
</p>
|
|
||||||
) : null}
|
|
||||||
{person.notes ? <p>Note: {person.notes}</p> : null}
|
{person.notes ? <p>Note: {person.notes}</p> : null}
|
||||||
<p>{person.status === 'confirmed' ? 'Confirmed' : 'Cancelled'}</p>
|
<p>{person.status === 'confirmed' ? 'Confirmed' : 'Cancelled'}</p>
|
||||||
{person.status === 'cancelled' ? (
|
{person.status === 'cancelled' ? (
|
||||||
|
|||||||
+4
-17
@@ -85,9 +85,6 @@ export type RosterPerson = {
|
|||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
minor: boolean;
|
|
||||||
guardianName: string | null;
|
|
||||||
guardianEmail: string | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
status: 'confirmed' | 'cancelled';
|
status: 'confirmed' | 'cancelled';
|
||||||
attendance: 'attended' | 'no-show' | null;
|
attendance: 'attended' | 'no-show' | null;
|
||||||
@@ -294,7 +291,7 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
|||||||
if (!row) return null;
|
if (!row) return null;
|
||||||
const people = db
|
const people = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id, name, email, phone, is_minor, guardian_name, guardian_email, notes, status, attended
|
`SELECT id, name, email, phone, notes, status, attended
|
||||||
FROM signups
|
FROM signups
|
||||||
WHERE shift_id = ? AND anonymized_at IS NULL AND name IS NOT NULL AND email IS NOT NULL
|
WHERE shift_id = ? AND anonymized_at IS NULL AND name IS NOT NULL AND email IS NOT NULL
|
||||||
ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, id`,
|
ORDER BY CASE status WHEN 'confirmed' THEN 0 ELSE 1 END, id`,
|
||||||
@@ -304,9 +301,6 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
|||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
is_minor: number;
|
|
||||||
guardian_name: string | null;
|
|
||||||
guardian_email: string | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
attended: number | null;
|
attended: number | null;
|
||||||
@@ -324,9 +318,6 @@ export function getAdminShift(db: Database.Database, id: number): AdminShift | n
|
|||||||
name: person.name,
|
name: person.name,
|
||||||
email: person.email,
|
email: person.email,
|
||||||
phone: person.phone,
|
phone: person.phone,
|
||||||
minor: person.is_minor === 1,
|
|
||||||
guardianName: person.guardian_name,
|
|
||||||
guardianEmail: person.guardian_email,
|
|
||||||
notes: person.notes,
|
notes: person.notes,
|
||||||
status: person.status,
|
status: person.status,
|
||||||
attendance: person.attended === 1 ? 'attended' : person.attended === 0 ? 'no-show' : null,
|
attendance: person.attended === 1 ? 'attended' : person.attended === 0 ? 'no-show' : null,
|
||||||
@@ -1286,7 +1277,6 @@ function relocate(
|
|||||||
token: issued.token,
|
token: issued.token,
|
||||||
volunteerName: source.name,
|
volunteerName: source.name,
|
||||||
volunteerEmail: source.email_norm,
|
volunteerEmail: source.email_norm,
|
||||||
guardianEmail: source.is_minor === 1 ? source.guardian_email : null,
|
|
||||||
shift: shift.facts,
|
shift: shift.facts,
|
||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
@@ -1419,7 +1409,7 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
|||||||
if (!shift) return 0;
|
if (!shift) return 0;
|
||||||
const people = db
|
const people = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
`SELECT id, name, email_norm, shift_id, status
|
||||||
FROM signups
|
FROM signups
|
||||||
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
||||||
)
|
)
|
||||||
@@ -1435,7 +1425,6 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
|||||||
token,
|
token,
|
||||||
volunteerName: person.name,
|
volunteerName: person.name,
|
||||||
volunteerEmail: person.email_norm,
|
volunteerEmail: person.email_norm,
|
||||||
guardianEmail: person.guardian_email,
|
|
||||||
shift: shift.facts,
|
shift: shift.facts,
|
||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
@@ -1448,7 +1437,7 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
|||||||
function cancelConfirmedOnShift(db: Database.Database, shiftId: number, now: string, mail: MailIdentity): number {
|
function cancelConfirmedOnShift(db: Database.Database, shiftId: number, now: string, mail: MailIdentity): number {
|
||||||
const people = db
|
const people = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
`SELECT id, name, email_norm, shift_id, status
|
||||||
FROM signups
|
FROM signups
|
||||||
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
WHERE shift_id = ? AND status = 'confirmed' AND anonymized_at IS NULL AND name IS NOT NULL AND email_norm IS NOT NULL`,
|
||||||
)
|
)
|
||||||
@@ -1481,7 +1470,6 @@ function cancelConfirmedPerson(db: Database.Database, person: PersonRow, now: st
|
|||||||
token: issued.token,
|
token: issued.token,
|
||||||
volunteerName: person.name,
|
volunteerName: person.name,
|
||||||
volunteerEmail: person.email_norm,
|
volunteerEmail: person.email_norm,
|
||||||
guardianEmail: person.guardian_email,
|
|
||||||
shift: shift.facts,
|
shift: shift.facts,
|
||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
@@ -1546,7 +1534,7 @@ function mailShift(db: Database.Database, shiftId: number): { version: number; e
|
|||||||
function loadPerson(db: Database.Database, signupId: number): PersonRow | null {
|
function loadPerson(db: Database.Database, signupId: number): PersonRow | null {
|
||||||
const row = db
|
const row = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id, name, email_norm, guardian_email, shift_id, status
|
`SELECT id, name, email_norm, shift_id, status
|
||||||
FROM signups
|
FROM signups
|
||||||
WHERE id = ? AND anonymized_at IS NULL`,
|
WHERE id = ? AND anonymized_at IS NULL`,
|
||||||
)
|
)
|
||||||
@@ -1692,7 +1680,6 @@ type PersonRow = {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string | null;
|
name: string | null;
|
||||||
email_norm: string | null;
|
email_norm: string | null;
|
||||||
guardian_email: string | null;
|
|
||||||
shift_id: number;
|
shift_id: number;
|
||||||
status: string;
|
status: string;
|
||||||
};
|
};
|
||||||
|
|||||||
+19
-14
@@ -16,13 +16,13 @@ const MAX_SKIPS = 30;
|
|||||||
const CONTROL = /[\u0000-\u001F\u007F]/;
|
const CONTROL = /[\u0000-\u001F\u007F]/;
|
||||||
|
|
||||||
export const CONTACT_CSV_EMPTY = 'Choose a spreadsheet to import.';
|
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_COLUMNS = 'This spreadsheet needs First Name, Last Name, Email, and Phone columns.';
|
||||||
export const CONTACT_CSV_READ = 'This spreadsheet could not be read.';
|
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_LARGE = 'This spreadsheet has more than 2000 people.';
|
||||||
export const CONTACT_CSV_BINARY = 'Save the spreadsheet as CSV.';
|
export const CONTACT_CSV_BINARY = 'Save the spreadsheet as CSV.';
|
||||||
export const CONTACT_CSV_LIMIT = 'This spreadsheet has to be under 64 KB.';
|
export const CONTACT_CSV_LIMIT = 'This spreadsheet has to be under 64 KB.';
|
||||||
|
|
||||||
export type ContactSkipCode = 'e' | 'n' | 'p' | 'l' | 'c';
|
export type ContactSkipCode = 'e' | 'n' | 'p' | 'm' | 'l' | 'c';
|
||||||
|
|
||||||
export type ContactSkip = { line: number; code: ContactSkipCode };
|
export type ContactSkip = { line: number; code: ContactSkipCode };
|
||||||
|
|
||||||
@@ -71,6 +71,7 @@ const SKIP_REASON: Record<ContactSkipCode, string> = {
|
|||||||
e: 'the email is not an address',
|
e: 'the email is not an address',
|
||||||
n: 'the name is missing',
|
n: 'the name is missing',
|
||||||
p: 'the phone is too long',
|
p: 'the phone is too long',
|
||||||
|
m: 'the phone is missing',
|
||||||
l: 'the name is too long',
|
l: 'the name is too long',
|
||||||
c: 'a field has a line break',
|
c: 'a field has a line break',
|
||||||
};
|
};
|
||||||
@@ -108,7 +109,7 @@ export function parseContactSkips(value: string | undefined): ContactSkip[] {
|
|||||||
if (!value) return [];
|
if (!value) return [];
|
||||||
const skips: ContactSkip[] = [];
|
const skips: ContactSkip[] = [];
|
||||||
for (const part of value.split('.')) {
|
for (const part of value.split('.')) {
|
||||||
const match = /^(\d+)([enplc])$/.exec(part);
|
const match = /^(\d+)([enplcm])$/.exec(part);
|
||||||
if (!match) continue;
|
if (!match) continue;
|
||||||
const line = Number(match[1]);
|
const line = Number(match[1]);
|
||||||
const code = match[2];
|
const code = match[2];
|
||||||
@@ -224,7 +225,7 @@ export function removeContact(db: Database.Database, coordinatorId: number, id:
|
|||||||
/**
|
/**
|
||||||
* Saves the person from a confirmed signup.
|
* Saves the person from a confirmed signup.
|
||||||
* The same name and email updates that contact. A different name is a new contact, even with the same email.
|
* The same name and email updates that contact. A different name is a new contact, even with the same email.
|
||||||
* A blank phone does not erase a phone already saved.
|
* A blank phone does not erase a phone already saved (legacy or cleared records).
|
||||||
*/
|
*/
|
||||||
export function rememberSignupContact(
|
export function rememberSignupContact(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
@@ -267,7 +268,7 @@ export function saveManualContact(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Replaces the name, email, and phone on one saved contact.
|
* Replaces the name, email, and phone on one saved contact.
|
||||||
* A different name stays this contact. A blank phone removes the saved number.
|
* A different name stays this contact. Phone is required.
|
||||||
*/
|
*/
|
||||||
export function correctContact(
|
export function correctContact(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
@@ -346,7 +347,7 @@ function columnIndex(cells: string[]): { first: number; last: number; email: num
|
|||||||
const last = names.indexOf('last name');
|
const last = names.indexOf('last name');
|
||||||
const email = names.indexOf('email');
|
const email = names.indexOf('email');
|
||||||
const phone = names.indexOf('phone');
|
const phone = names.indexOf('phone');
|
||||||
if (first < 0 || last < 0 || email < 0) return null;
|
if (first < 0 || last < 0 || email < 0 || phone < 0) return null;
|
||||||
return { first, last, email, phone };
|
return { first, last, email, phone };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -382,7 +383,8 @@ function manualContact(values: ContactManualValues): { ok: true; person: ReadyCo
|
|||||||
if (firstName && lastName && !errors.firstName && !errors.lastName && `${firstName} ${lastName}`.length > MAX_NAME) {
|
if (firstName && lastName && !errors.firstName && !errors.lastName && `${firstName} ${lastName}`.length > MAX_NAME) {
|
||||||
errors.lastName = `Use ${MAX_NAME} characters or fewer for the full name.`;
|
errors.lastName = `Use ${MAX_NAME} characters or fewer for the full name.`;
|
||||||
}
|
}
|
||||||
if (CONTROL.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
if (!phoneRaw || !phone) errors.phone = 'Enter a phone number.';
|
||||||
|
else if (CONTROL.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
||||||
else if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) errors.phone = `Use ${MAX_PHONE} characters or fewer.`;
|
else if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) errors.phone = `Use ${MAX_PHONE} characters or fewer.`;
|
||||||
let email = '';
|
let email = '';
|
||||||
const emailRaw = values.email.normalize('NFC').trim();
|
const emailRaw = values.email.normalize('NFC').trim();
|
||||||
@@ -396,8 +398,8 @@ function manualContact(values: ContactManualValues): { ok: true; person: ReadyCo
|
|||||||
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
|
errors.email = err instanceof EmailAddressError ? err.message : 'Enter an email address.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (Object.keys(errors).length > 0 || !email) return { ok: false, errors };
|
if (Object.keys(errors).length > 0 || !email || !phone) return { ok: false, errors };
|
||||||
return { ok: true, person: { firstName, lastName, email, phone: phone.length === 0 ? null : phone } };
|
return { ok: true, person: { firstName, lastName, email, phone } };
|
||||||
}
|
}
|
||||||
|
|
||||||
function findContact(
|
function findContact(
|
||||||
@@ -453,16 +455,19 @@ function parsePerson(cells: string[], columns: { first: number; last: number; em
|
|||||||
const last = capitalizeName(lastName);
|
const last = capitalizeName(lastName);
|
||||||
if (!first || !last) return { code: 'n' };
|
if (!first || !last) return { code: 'n' };
|
||||||
if (first.length > MAX_NAME || last.length > MAX_NAME || `${first} ${last}`.length > MAX_NAME) return { code: 'l' };
|
if (first.length > MAX_NAME || last.length > MAX_NAME || `${first} ${last}`.length > MAX_NAME) return { code: 'l' };
|
||||||
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
|
let email = '';
|
||||||
if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) return { code: 'p' };
|
|
||||||
try {
|
try {
|
||||||
const email = normalizeEmail(emailRaw);
|
email = normalizeEmail(emailRaw);
|
||||||
if (email.length > MAX_EMAIL) return { code: 'e' };
|
if (email.length > MAX_EMAIL) return { code: 'e' };
|
||||||
return { firstName: first, lastName: last, email, phone: phone.length === 0 ? null : phone };
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof EmailAddressError) return { code: 'e' };
|
if (err instanceof EmailAddressError) return { code: 'e' };
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
if (!phoneRaw) return { code: 'm' };
|
||||||
|
const phone = formatPhone(phoneRaw);
|
||||||
|
if (!phone) return { code: 'm' };
|
||||||
|
if (phoneRaw.length > MAX_PHONE || phone.length > MAX_PHONE) return { code: 'p' };
|
||||||
|
return { firstName: first, lastName: last, email, phone };
|
||||||
}
|
}
|
||||||
|
|
||||||
function cellAt(cells: string[], index: number): string {
|
function cellAt(cells: string[], index: number): string {
|
||||||
@@ -533,5 +538,5 @@ function parseCsv(text: string): { line: number; cells: string[] }[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function isSkipCode(value: string): value is ContactSkipCode {
|
function isSkipCode(value: string): value is ContactSkipCode {
|
||||||
return value === 'e' || value === 'n' || value === 'p' || value === 'l' || value === 'c';
|
return value === 'e' || value === 'n' || value === 'p' || value === 'm' || value === 'l' || value === 'c';
|
||||||
}
|
}
|
||||||
+2
-14
@@ -122,19 +122,13 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
|||||||
name: 'Fake Volunteer Ada',
|
name: 'Fake Volunteer Ada',
|
||||||
email: `ada.fake@${SEED_EMAIL_DOMAIN}`,
|
email: `ada.fake@${SEED_EMAIL_DOMAIN}`,
|
||||||
phone: '712-555-0101',
|
phone: '712-555-0101',
|
||||||
isMinor: 0,
|
|
||||||
guardianName: null,
|
|
||||||
guardianEmail: null,
|
|
||||||
notes: 'Fake note for development.',
|
notes: 'Fake note for development.',
|
||||||
status: 'confirmed',
|
status: 'confirmed',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Fake Volunteer Ben',
|
name: 'Fake Volunteer Ben',
|
||||||
email: `ben.fake@${SEED_EMAIL_DOMAIN}`,
|
email: `ben.fake@${SEED_EMAIL_DOMAIN}`,
|
||||||
phone: null,
|
phone: '712-555-0102',
|
||||||
isMinor: 1,
|
|
||||||
guardianName: 'Fake Guardian Pat',
|
|
||||||
guardianEmail: `pat.fake@${SEED_EMAIL_DOMAIN}`,
|
|
||||||
notes: null,
|
notes: null,
|
||||||
status: 'confirmed',
|
status: 'confirmed',
|
||||||
},
|
},
|
||||||
@@ -142,9 +136,6 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
|||||||
name: 'Fake Volunteer Cam',
|
name: 'Fake Volunteer Cam',
|
||||||
email: `cam.fake@${SEED_EMAIL_DOMAIN}`,
|
email: `cam.fake@${SEED_EMAIL_DOMAIN}`,
|
||||||
phone: null,
|
phone: null,
|
||||||
isMinor: 0,
|
|
||||||
guardianName: null,
|
|
||||||
guardianEmail: null,
|
|
||||||
notes: null,
|
notes: null,
|
||||||
status: 'cancelled',
|
status: 'cancelled',
|
||||||
},
|
},
|
||||||
@@ -154,7 +145,7 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
|||||||
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
shift_id, name, email, email_norm, phone, is_minor, guardian_name, guardian_email,
|
||||||
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
group_size, notes, status, manage_token_hash, token_expires_at, reminders_off,
|
||||||
attended, created_at, updated_at, anonymized_at
|
attended, created_at, updated_at, anonymized_at
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
) VALUES (?, ?, ?, ?, ?, 0, NULL, NULL, 1, ?, ?, NULL, NULL, 0, NULL, ?, ?, NULL)`,
|
||||||
);
|
);
|
||||||
return people.map((person) =>
|
return people.map((person) =>
|
||||||
insertId(
|
insertId(
|
||||||
@@ -164,9 +155,6 @@ function insertFakeSignups(db: Database.Database, shiftId: number, createdAt: st
|
|||||||
person.email,
|
person.email,
|
||||||
normalizeEmail(person.email),
|
normalizeEmail(person.email),
|
||||||
person.phone,
|
person.phone,
|
||||||
person.isMinor,
|
|
||||||
person.guardianName,
|
|
||||||
person.guardianEmail,
|
|
||||||
person.notes,
|
person.notes,
|
||||||
person.status,
|
person.status,
|
||||||
createdAt,
|
createdAt,
|
||||||
|
|||||||
@@ -16,9 +16,6 @@ const COLUMNS = [
|
|||||||
'Email',
|
'Email',
|
||||||
'Phone',
|
'Phone',
|
||||||
'Group size',
|
'Group size',
|
||||||
'Minor',
|
|
||||||
'Guardian name',
|
|
||||||
'Guardian email',
|
|
||||||
'Notes',
|
'Notes',
|
||||||
'Status',
|
'Status',
|
||||||
'Attended',
|
'Attended',
|
||||||
@@ -35,9 +32,6 @@ type RosterRecord = {
|
|||||||
email: string | null;
|
email: string | null;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
group_size: number;
|
group_size: number;
|
||||||
is_minor: number;
|
|
||||||
guardian_name: string | null;
|
|
||||||
guardian_email: string | null;
|
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
status: string;
|
status: string;
|
||||||
attended: number | null;
|
attended: number | null;
|
||||||
@@ -46,7 +40,6 @@ type RosterRecord = {
|
|||||||
|
|
||||||
const ROSTER_SQL = `SELECT s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc, e.tz AS tz, s.role AS role,
|
const ROSTER_SQL = `SELECT s.starts_at_utc AS starts_at_utc, s.ends_at_utc AS ends_at_utc, e.tz AS tz, s.role AS role,
|
||||||
su.name AS name, su.email AS email, su.phone AS phone, su.group_size AS group_size,
|
su.name AS name, su.email AS email, su.phone AS phone, su.group_size AS group_size,
|
||||||
su.is_minor AS is_minor, su.guardian_name AS guardian_name, su.guardian_email AS guardian_email,
|
|
||||||
su.notes AS notes, su.status AS status, su.attended AS attended, su.anonymized_at AS anonymized_at
|
su.notes AS notes, su.status AS status, su.attended AS attended, su.anonymized_at AS anonymized_at
|
||||||
FROM signups su
|
FROM signups su
|
||||||
JOIN shifts s ON s.id = su.shift_id
|
JOIN shifts s ON s.id = su.shift_id
|
||||||
@@ -136,9 +129,6 @@ function present(row: RosterRecord): string[] {
|
|||||||
row.email ?? '',
|
row.email ?? '',
|
||||||
row.phone ?? '',
|
row.phone ?? '',
|
||||||
String(row.group_size),
|
String(row.group_size),
|
||||||
row.anonymized_at ? '' : row.is_minor === 1 ? 'Yes' : 'No',
|
|
||||||
row.guardian_name ?? '',
|
|
||||||
row.guardian_email ?? '',
|
|
||||||
row.notes ?? '',
|
row.notes ?? '',
|
||||||
row.status === 'cancelled' ? 'Cancelled' : 'Confirmed',
|
row.status === 'cancelled' ? 'Cancelled' : 'Confirmed',
|
||||||
row.attended === 1 ? 'Attended' : row.attended === 0 ? 'No-show' : '',
|
row.attended === 1 ? 'Attended' : row.attended === 0 ? 'No-show' : '',
|
||||||
|
|||||||
+7
-19
@@ -10,7 +10,6 @@ export type QueuedSignup = {
|
|||||||
token: string;
|
token: string;
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
volunteerEmail: string;
|
volunteerEmail: string;
|
||||||
guardianEmail: string | null;
|
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
mail: MailIdentity;
|
mail: MailIdentity;
|
||||||
now: string;
|
now: string;
|
||||||
@@ -19,8 +18,7 @@ export type QueuedSignup = {
|
|||||||
|
|
||||||
/** Inserts one row per recipient. The same logical message does not get a second row. */
|
/** Inserts one row per recipient. The same logical message does not get a second row. */
|
||||||
export function queueConfirmation(db: Database.Database, input: QueuedSignup): void {
|
export function queueConfirmation(db: Database.Database, input: QueuedSignup): void {
|
||||||
queue(db, 'confirmation', input, (audience) => renderConfirmation({
|
queue(db, 'confirmation', input, () => renderConfirmation({
|
||||||
audience,
|
|
||||||
volunteerName: input.volunteerName,
|
volunteerName: input.volunteerName,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
manageUrl: manageUrl(input),
|
manageUrl: manageUrl(input),
|
||||||
@@ -29,8 +27,7 @@ export function queueConfirmation(db: Database.Database, input: QueuedSignup): v
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queueCancellation(db: Database.Database, input: QueuedSignup): void {
|
export function queueCancellation(db: Database.Database, input: QueuedSignup): void {
|
||||||
queue(db, 'cancelled', input, (audience) => renderCancellation({
|
queue(db, 'cancelled', input, () => renderCancellation({
|
||||||
audience,
|
|
||||||
volunteerName: input.volunteerName,
|
volunteerName: input.volunteerName,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
manageUrl: manageUrl(input),
|
manageUrl: manageUrl(input),
|
||||||
@@ -40,9 +37,8 @@ export function queueCancellation(db: Database.Database, input: QueuedSignup): v
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function queueChanged(db: Database.Database, input: QueuedSignup, reason: 'edit' | 'move' | 'switch' = 'edit'): void {
|
export function queueChanged(db: Database.Database, input: QueuedSignup, reason: 'edit' | 'move' | 'switch' = 'edit'): void {
|
||||||
queue(db, 'changed', input, (audience) => {
|
queue(db, 'changed', input, () => {
|
||||||
const letter = {
|
const letter = {
|
||||||
audience,
|
|
||||||
volunteerName: input.volunteerName,
|
volunteerName: input.volunteerName,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
manageUrl: manageUrl(input),
|
manageUrl: manageUrl(input),
|
||||||
@@ -110,11 +106,9 @@ function queue(
|
|||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
kind: 'confirmation' | 'cancelled' | 'changed',
|
kind: 'confirmation' | 'cancelled' | 'changed',
|
||||||
input: QueuedSignup,
|
input: QueuedSignup,
|
||||||
render: (audience: 'volunteer' | 'guardian') => { subject: string; text: string; html: string },
|
render: () => { subject: string; text: string; html: string },
|
||||||
): void {
|
): void {
|
||||||
for (const recipient of recipients(input.volunteerEmail, input.guardianEmail)) {
|
const rendered = render();
|
||||||
const audience = recipient === input.volunteerEmail ? 'volunteer' : 'guardian';
|
|
||||||
const rendered = render(audience);
|
|
||||||
db.prepare(
|
db.prepare(
|
||||||
`INSERT INTO outbox (
|
`INSERT INTO outbox (
|
||||||
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||||
@@ -122,11 +116,11 @@ function queue(
|
|||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
||||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||||
).run(
|
).run(
|
||||||
`${kind}:v${input.shiftVersion}:${input.signupId}:${recipient}`,
|
`${kind}:v${input.shiftVersion}:${input.signupId}:${input.volunteerEmail}`,
|
||||||
input.signupId,
|
input.signupId,
|
||||||
input.shiftId,
|
input.shiftId,
|
||||||
kind,
|
kind,
|
||||||
recipient,
|
input.volunteerEmail,
|
||||||
rendered.subject,
|
rendered.subject,
|
||||||
rendered.text,
|
rendered.text,
|
||||||
rendered.html,
|
rendered.html,
|
||||||
@@ -135,12 +129,6 @@ function queue(
|
|||||||
input.now,
|
input.now,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
function recipients(volunteerEmail: string, guardianEmail: string | null): string[] {
|
|
||||||
if (!guardianEmail || guardianEmail === volunteerEmail) return [volunteerEmail];
|
|
||||||
return [volunteerEmail, guardianEmail];
|
|
||||||
}
|
|
||||||
|
|
||||||
function manageUrl(input: QueuedSignup): string {
|
function manageUrl(input: QueuedSignup): string {
|
||||||
return absoluteUrl(input.mail, `/m/${input.token}`);
|
return absoluteUrl(input.mail, `/m/${input.token}`);
|
||||||
|
|||||||
+13
-46
@@ -19,7 +19,6 @@ export type RenderedMail = {
|
|||||||
* ink and blue from public/brand/tokens.css.
|
* ink and blue from public/brand/tokens.css.
|
||||||
*/
|
*/
|
||||||
export function renderConfirmation(input: {
|
export function renderConfirmation(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
manageUrl: string;
|
manageUrl: string;
|
||||||
@@ -27,14 +26,10 @@ export function renderConfirmation(input: {
|
|||||||
}): RenderedMail {
|
}): RenderedMail {
|
||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
const name = singleLine(input.volunteerName);
|
||||||
const subject = input.audience === 'guardian' ? `${name} is signed up for ${role}` : `You're signed up for ${role}`;
|
|
||||||
const hello = input.audience === 'guardian'
|
|
||||||
? `${name} is signed up for ${role}. You are listed as the parent or guardian.`
|
|
||||||
: `You are signed up for ${role}.`;
|
|
||||||
return render({
|
return render({
|
||||||
subject,
|
subject: `You're signed up for ${role}`,
|
||||||
hello,
|
hello: `You are signed up for ${role}.`,
|
||||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
greeting: `Hello ${name},`,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
linkLabel: 'Open this signup',
|
linkLabel: 'Open this signup',
|
||||||
linkNote: 'You can cancel or switch this signup from that link. Use the separate link for each signup.',
|
linkNote: 'You can cancel or switch this signup from that link. Use the separate link for each signup.',
|
||||||
@@ -44,7 +39,6 @@ export function renderConfirmation(input: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function renderCancellation(input: {
|
export function renderCancellation(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
manageUrl: string;
|
manageUrl: string;
|
||||||
@@ -53,16 +47,10 @@ export function renderCancellation(input: {
|
|||||||
}): RenderedMail {
|
}): RenderedMail {
|
||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
const name = singleLine(input.volunteerName);
|
||||||
const subject = input.audience === 'guardian'
|
|
||||||
? `${name}'s signup for ${role} is cancelled`
|
|
||||||
: `Your signup for ${role} is cancelled`;
|
|
||||||
const hello = input.audience === 'guardian'
|
|
||||||
? `${name}'s signup for ${role} is cancelled. The spot is open for someone else.`
|
|
||||||
: `Your signup for ${role} is cancelled. The spot is open for someone else.`;
|
|
||||||
return render({
|
return render({
|
||||||
subject,
|
subject: `Your signup for ${role} is cancelled`,
|
||||||
hello,
|
hello: `Your signup for ${role} is cancelled. The spot is open for someone else.`,
|
||||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
greeting: `Hello ${name},`,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
linkLabel: 'Open this signup',
|
linkLabel: 'Open this signup',
|
||||||
linkNote: input.linkNote ?? 'That link opens the cancelled signup.',
|
linkNote: input.linkNote ?? 'That link opens the cancelled signup.',
|
||||||
@@ -72,55 +60,37 @@ export function renderCancellation(input: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function renderChanged(input: {
|
export function renderChanged(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
manageUrl: string;
|
manageUrl: string;
|
||||||
replyTo: string;
|
replyTo: string;
|
||||||
}): RenderedMail {
|
}): RenderedMail {
|
||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
return changedLetter(input, `Your ${role} shift has changed`, `The time or place for your ${role} shift has changed.`);
|
||||||
const subject = input.audience === 'guardian' ? `${name}'s ${role} shift has changed` : `Your ${role} shift has changed`;
|
|
||||||
const hello = input.audience === 'guardian'
|
|
||||||
? `The time or place for ${name}'s ${role} shift has changed.`
|
|
||||||
: `The time or place for your ${role} shift has changed.`;
|
|
||||||
return changedLetter(input, subject, hello);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderMoved(input: {
|
export function renderMoved(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
manageUrl: string;
|
manageUrl: string;
|
||||||
replyTo: string;
|
replyTo: string;
|
||||||
}): RenderedMail {
|
}): RenderedMail {
|
||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
return changedLetter(input, `Your signup was moved to ${role}`, 'A coordinator moved your signup to a different shift.');
|
||||||
const subject = input.audience === 'guardian' ? `${name}'s signup was moved to ${role}` : `Your signup was moved to ${role}`;
|
|
||||||
const hello = input.audience === 'guardian'
|
|
||||||
? `A coordinator moved ${name}'s signup to a different shift.`
|
|
||||||
: 'A coordinator moved your signup to a different shift.';
|
|
||||||
return changedLetter(input, subject, hello);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function renderSwitched(input: {
|
export function renderSwitched(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
manageUrl: string;
|
manageUrl: string;
|
||||||
replyTo: string;
|
replyTo: string;
|
||||||
}): RenderedMail {
|
}): RenderedMail {
|
||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
return changedLetter(input, `Your signup was switched to ${role}`, 'You switched this signup to a different shift.');
|
||||||
const subject = input.audience === 'guardian' ? `${name}'s signup was switched to ${role}` : `Your signup was switched to ${role}`;
|
|
||||||
const hello = input.audience === 'guardian'
|
|
||||||
? `${name} switched this signup to a different shift.`
|
|
||||||
: 'You switched this signup to a different shift.';
|
|
||||||
return changedLetter(input, subject, hello);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function changedLetter(
|
function changedLetter(
|
||||||
input: { audience: 'volunteer' | 'guardian'; volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
input: { volunteerName: string; shift: MailShift; manageUrl: string; replyTo: string },
|
||||||
subject: string,
|
subject: string,
|
||||||
hello: string,
|
hello: string,
|
||||||
): RenderedMail {
|
): RenderedMail {
|
||||||
@@ -128,7 +98,7 @@ function changedLetter(
|
|||||||
return render({
|
return render({
|
||||||
subject,
|
subject,
|
||||||
hello,
|
hello,
|
||||||
greeting: input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`,
|
greeting: `Hello ${name},`,
|
||||||
shift: input.shift,
|
shift: input.shift,
|
||||||
linkLabel: 'Open this signup',
|
linkLabel: 'Open this signup',
|
||||||
linkNote: 'This link replaces the earlier one. The previous link no longer works.',
|
linkNote: 'This link replaces the earlier one. The previous link no longer works.',
|
||||||
@@ -138,7 +108,6 @@ function changedLetter(
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function renderReminder(input: {
|
export function renderReminder(input: {
|
||||||
audience: 'volunteer' | 'guardian';
|
|
||||||
volunteerName: string;
|
volunteerName: string;
|
||||||
shift: MailShift;
|
shift: MailShift;
|
||||||
unsubscribeUrl: string;
|
unsubscribeUrl: string;
|
||||||
@@ -147,12 +116,10 @@ export function renderReminder(input: {
|
|||||||
const role = singleLine(input.shift.role);
|
const role = singleLine(input.shift.role);
|
||||||
const name = singleLine(input.volunteerName);
|
const name = singleLine(input.volunteerName);
|
||||||
const subject = `Reminder: ${role}`;
|
const subject = `Reminder: ${role}`;
|
||||||
const hello = input.audience === 'guardian'
|
const hello = `You are still signed up for ${role}.`;
|
||||||
? `${name} is still signed up for ${role}. You are listed as the parent or guardian.`
|
|
||||||
: `You are still signed up for ${role}.`;
|
|
||||||
const cancelNote = 'To cancel, use the link in your confirmation email.';
|
const cancelNote = 'To cancel, use the link in your confirmation email.';
|
||||||
const stopNote = `To stop reminder emails for this signup, open ${input.unsubscribeUrl}. The pantry reads mail sent to ${input.replyTo}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.`;
|
const stopNote = `To stop reminder emails for this signup, open ${input.unsubscribeUrl}. The pantry reads mail sent to ${input.replyTo}. Stopping reminders does not cancel the signup. Confirmation, change, and cancellation emails still arrive.`;
|
||||||
const greeting = input.audience === 'guardian' ? 'Hello,' : `Hello ${name},`;
|
const greeting = `Hello ${name},`;
|
||||||
const when = input.shift.whenLabel;
|
const when = input.shift.whenLabel;
|
||||||
const place = input.shift.location.trim();
|
const place = input.shift.location.trim();
|
||||||
const lines = [
|
const lines = [
|
||||||
|
|||||||
+3
-37
@@ -353,15 +353,6 @@ export function ManagePage(props: {
|
|||||||
<dd>{signup.phone}</dd>
|
<dd>{signup.phone}</dd>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
{signup.isMinor ? (
|
|
||||||
<div>
|
|
||||||
<dt>Guardian</dt>
|
|
||||||
<dd>
|
|
||||||
{signup.guardianName}
|
|
||||||
{signup.guardianEmail ? ` (${signup.guardianEmail})` : ''}
|
|
||||||
</dd>
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
{signup.notes ? (
|
{signup.notes ? (
|
||||||
<div>
|
<div>
|
||||||
<dt>Notes</dt>
|
<dt>Notes</dt>
|
||||||
@@ -713,7 +704,7 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
|||||||
return (
|
return (
|
||||||
<form class="signup-form" method="post" action={appPath(props.config, `/s/${props.shiftId}`)}>
|
<form class="signup-form" method="post" action={appPath(props.config, `/s/${props.shiftId}`)}>
|
||||||
<h2>Sign up</h2>
|
<h2>Sign up</h2>
|
||||||
<p>Each signup is for one person and takes one spot. Another person can use the same email address. If you are under 18, add a parent or guardian.</p>
|
<p>Each signup is for one person and takes one spot. Another person can use the same email address.</p>
|
||||||
<noscript>
|
<noscript>
|
||||||
<p class="error">Signing up needs JavaScript for the abuse check. The pantry has not published a contact method for help with signup.</p>
|
<p class="error">Signing up needs JavaScript for the abuse check. The pantry has not published a contact method for help with signup.</p>
|
||||||
</noscript>
|
</noscript>
|
||||||
@@ -761,13 +752,13 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
|||||||
<Field id="signup-email" label="Email" name="email" type="email" value={form.values.email} error={errors.email} autoComplete="email" />
|
<Field id="signup-email" label="Email" name="email" type="email" value={form.values.email} error={errors.email} autoComplete="email" />
|
||||||
<Field
|
<Field
|
||||||
id="signup-phone"
|
id="signup-phone"
|
||||||
label="Phone (optional)"
|
label="Phone"
|
||||||
name="phone"
|
name="phone"
|
||||||
type="tel"
|
type="tel"
|
||||||
value={form.values.phone}
|
value={form.values.phone}
|
||||||
error={errors.phone}
|
error={errors.phone}
|
||||||
autoComplete="tel"
|
autoComplete="tel"
|
||||||
hint="We will not text you"
|
required
|
||||||
/>
|
/>
|
||||||
<label for="signup-notes">
|
<label for="signup-notes">
|
||||||
Notes (optional)
|
Notes (optional)
|
||||||
@@ -780,31 +771,6 @@ function SignupForm(props: { config: AppConfig; shiftId: number; form: SignupFor
|
|||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
</label>
|
</label>
|
||||||
<label class="check" for="signup-under-18">
|
|
||||||
<input id="signup-under-18" name="under18" type="checkbox" value="yes" data-under-18="" checked={form.values.under18 ? true : undefined} />
|
|
||||||
I am under 18
|
|
||||||
</label>
|
|
||||||
<fieldset data-guardian="">
|
|
||||||
<legend>Parent or guardian</legend>
|
|
||||||
<Field
|
|
||||||
id="signup-guardianName"
|
|
||||||
label="Guardian name"
|
|
||||||
name="guardianName"
|
|
||||||
type="text"
|
|
||||||
value={form.values.guardianName}
|
|
||||||
error={errors.guardianName}
|
|
||||||
autoComplete="name"
|
|
||||||
/>
|
|
||||||
<Field
|
|
||||||
id="signup-guardianEmail"
|
|
||||||
label="Guardian email"
|
|
||||||
name="guardianEmail"
|
|
||||||
type="email"
|
|
||||||
value={form.values.guardianEmail}
|
|
||||||
error={errors.guardianEmail}
|
|
||||||
autoComplete="email"
|
|
||||||
/>
|
|
||||||
</fieldset>
|
|
||||||
<div class="cf-turnstile" data-sitekey={form.siteKey} data-action="signup" />
|
<div class="cf-turnstile" data-sitekey={form.siteKey} data-action="signup" />
|
||||||
<p id="signup-turnstile-hint">This check confirms the signup came from a browser.</p>
|
<p id="signup-turnstile-hint">This check confirms the signup came from a browser.</p>
|
||||||
<button type="submit">Sign up</button>
|
<button type="submit">Sign up</button>
|
||||||
|
|||||||
+2
-23
@@ -8,8 +8,6 @@ import { formatUtc } from './time.js';
|
|||||||
export const SIGNUP_IP_LIMIT = 5;
|
export const SIGNUP_IP_LIMIT = 5;
|
||||||
export const SIGNUP_IP_WINDOW_MS = 10 * 60 * 1000;
|
export const SIGNUP_IP_WINDOW_MS = 10 * 60 * 1000;
|
||||||
export const SIGNUP_EMAIL_LIMIT = 3;
|
export const SIGNUP_EMAIL_LIMIT = 3;
|
||||||
/** A guardian can have several children signed up, so this allowance is a little wider. */
|
|
||||||
export const SIGNUP_GUARDIAN_LIMIT = 5;
|
|
||||||
export const SWITCH_IP_LIMIT = 10;
|
export const SWITCH_IP_LIMIT = 10;
|
||||||
export const SWITCH_RECIPIENT_LIMIT = 5;
|
export const SWITCH_RECIPIENT_LIMIT = 5;
|
||||||
export const MANAGE_TOKEN_LIMIT = 20;
|
export const MANAGE_TOKEN_LIMIT = 20;
|
||||||
@@ -30,8 +28,8 @@ export type RateDecision = { limited: false } | { limited: true; retryAfter: num
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Counts validated public switch attempts, not the rotating signup id or token.
|
* Counts validated public switch attempts, not the rotating signup id or token.
|
||||||
* Both recipient roles share one daily allowance. Check and charge every bucket
|
* Check and charge every bucket atomically so a blocked recipient cannot consume
|
||||||
* atomically so a blocked recipient cannot consume another person's allowance.
|
* another person's allowance.
|
||||||
*/
|
*/
|
||||||
export function recordSwitchAttempt(
|
export function recordSwitchAttempt(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
@@ -144,25 +142,6 @@ export function recordSignupEmail(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Counts signups that mail a guardian address. Without it, someone could rotate
|
|
||||||
* volunteer addresses and keep sending mail to one guardian.
|
|
||||||
*/
|
|
||||||
export function recordSignupGuardian(
|
|
||||||
db: Database.Database,
|
|
||||||
secret: string,
|
|
||||||
now: string,
|
|
||||||
timeZone: string,
|
|
||||||
guardianEmailNorm: string,
|
|
||||||
): RateDecision {
|
|
||||||
return record(db, secret, now, {
|
|
||||||
kind: 'signup-guardian',
|
|
||||||
id: guardianEmailNorm,
|
|
||||||
limit: SIGNUP_GUARDIAN_LIMIT,
|
|
||||||
window: dayWindow(now, timeZone),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function record(
|
function record(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
secret: string,
|
secret: string,
|
||||||
|
|||||||
+5
-13
@@ -14,7 +14,6 @@ type DueSignup = {
|
|||||||
id: number;
|
id: number;
|
||||||
name: string;
|
name: string;
|
||||||
email_norm: string;
|
email_norm: string;
|
||||||
guardian_email: string | null;
|
|
||||||
version: number;
|
version: number;
|
||||||
starts_at_utc: string;
|
starts_at_utc: string;
|
||||||
ends_at_utc: string;
|
ends_at_utc: string;
|
||||||
@@ -38,7 +37,7 @@ export function queueDueReminders(db: Database.Database, mail: MailIdentity, sec
|
|||||||
const activeMail = { ...mail, replyTo: readReplyTo(db, mail.replyTo) };
|
const activeMail = { ...mail, replyTo: readReplyTo(db, mail.replyTo) };
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email,
|
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm,
|
||||||
su.shift_id AS shift_id, s.version AS version, s.starts_at_utc AS starts_at_utc,
|
su.shift_id AS shift_id, s.version AS version, s.starts_at_utc AS starts_at_utc,
|
||||||
s.ends_at_utc AS ends_at_utc, s.role AS role,
|
s.ends_at_utc AS ends_at_utc, s.role AS role,
|
||||||
e.title AS title, e.location AS location, e.tz AS tz
|
e.title AS title, e.location AS location, e.tz AS tz
|
||||||
@@ -129,7 +128,7 @@ function insertReminder(
|
|||||||
): boolean {
|
): boolean {
|
||||||
const unsubscribeUrl = absoluteUrl(mail, `/u/${issueReminderOffToken(secret, row.id)}`);
|
const unsubscribeUrl = absoluteUrl(mail, `/u/${issueReminderOffToken(secret, row.id)}`);
|
||||||
const headers = reminderHeaders(mail, unsubscribeUrl);
|
const headers = reminderHeaders(mail, unsubscribeUrl);
|
||||||
const volunteerId = insertOutbox(db, row, kind, row.email_norm, 'volunteer', mail, headers, unsubscribeUrl, now, mode);
|
const volunteerId = insertOutbox(db, row, kind, mail, headers, unsubscribeUrl, now, mode);
|
||||||
if (volunteerId === null) return false;
|
if (volunteerId === null) return false;
|
||||||
const saved = db
|
const saved = db
|
||||||
.prepare(
|
.prepare(
|
||||||
@@ -138,19 +137,13 @@ function insertReminder(
|
|||||||
ON CONFLICT (signup_id, kind, shift_version) DO NOTHING`,
|
ON CONFLICT (signup_id, kind, shift_version) DO NOTHING`,
|
||||||
)
|
)
|
||||||
.run(row.id, kind, row.version, volunteerId, now);
|
.run(row.id, kind, row.version, volunteerId, now);
|
||||||
if (saved.changes !== 1) return false;
|
return saved.changes === 1;
|
||||||
if (mode === 'pending' && row.guardian_email && row.guardian_email !== row.email_norm) {
|
|
||||||
insertOutbox(db, row, kind, row.guardian_email, 'guardian', mail, headers, unsubscribeUrl, now, 'pending');
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function insertOutbox(
|
function insertOutbox(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
row: DueSignup,
|
row: DueSignup,
|
||||||
kind: string,
|
kind: string,
|
||||||
recipient: string,
|
|
||||||
audience: 'volunteer' | 'guardian',
|
|
||||||
mail: MailIdentity,
|
mail: MailIdentity,
|
||||||
headers: Record<string, string>,
|
headers: Record<string, string>,
|
||||||
unsubscribeUrl: string,
|
unsubscribeUrl: string,
|
||||||
@@ -159,7 +152,6 @@ function insertOutbox(
|
|||||||
): number | null {
|
): number | null {
|
||||||
const rendered = mode === 'pending'
|
const rendered = mode === 'pending'
|
||||||
? renderReminder({
|
? renderReminder({
|
||||||
audience,
|
|
||||||
volunteerName: row.name,
|
volunteerName: row.name,
|
||||||
shift: shiftFacts(row),
|
shift: shiftFacts(row),
|
||||||
unsubscribeUrl,
|
unsubscribeUrl,
|
||||||
@@ -175,10 +167,10 @@ function insertOutbox(
|
|||||||
ON CONFLICT (dedupe_key) DO NOTHING`,
|
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||||
)
|
)
|
||||||
.run(
|
.run(
|
||||||
`reminder:v${row.version}:${row.id}:${kind}:${recipient}`,
|
`reminder:v${row.version}:${row.id}:${kind}:${row.email_norm}`,
|
||||||
row.id,
|
row.id,
|
||||||
row.shift_id,
|
row.shift_id,
|
||||||
recipient,
|
row.email_norm,
|
||||||
rendered.subject,
|
rendered.subject,
|
||||||
rendered.text,
|
rendered.text,
|
||||||
rendered.html,
|
rendered.html,
|
||||||
|
|||||||
+7
-43
@@ -13,25 +13,18 @@ export type SignupValues = {
|
|||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
notes: string;
|
notes: string;
|
||||||
under18: boolean;
|
|
||||||
guardianName: string;
|
|
||||||
guardianEmail: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SignupErrors = Partial<
|
export type SignupErrors = Partial<
|
||||||
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'guardianName' | 'guardianEmail' | 'form', string>
|
Record<'name' | 'firstName' | 'lastName' | 'email' | 'phone' | 'notes' | 'form', string>
|
||||||
>;
|
>;
|
||||||
|
|
||||||
export type SignupDraft = {
|
export type SignupDraft = {
|
||||||
name: string;
|
name: string;
|
||||||
email: string;
|
email: string;
|
||||||
emailNorm: string;
|
emailNorm: string;
|
||||||
phone: string | null;
|
phone: string;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
isMinor: boolean;
|
|
||||||
guardianName: string | null;
|
|
||||||
guardianEmail: string | null;
|
|
||||||
guardianEmailNorm: string | null;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const EMPTY_SIGNUP: SignupValues = {
|
export const EMPTY_SIGNUP: SignupValues = {
|
||||||
@@ -41,9 +34,6 @@ export const EMPTY_SIGNUP: SignupValues = {
|
|||||||
email: '',
|
email: '',
|
||||||
phone: '',
|
phone: '',
|
||||||
notes: '',
|
notes: '',
|
||||||
under18: false,
|
|
||||||
guardianName: '',
|
|
||||||
guardianEmail: '',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const controlChars = /[\u0000-\u001F\u007F]/;
|
const controlChars = /[\u0000-\u001F\u007F]/;
|
||||||
@@ -69,9 +59,6 @@ export function parseSignupForm(
|
|||||||
email: z.string(),
|
email: z.string(),
|
||||||
phone: z.string(),
|
phone: z.string(),
|
||||||
notes: z.string(),
|
notes: z.string(),
|
||||||
under18: z.boolean(),
|
|
||||||
guardianName: z.string(),
|
|
||||||
guardianEmail: z.string(),
|
|
||||||
})
|
})
|
||||||
.safeParse(input);
|
.safeParse(input);
|
||||||
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
|
if (!parsed.success) return { ok: false, errors: { form: 'Check the signup fields and try again.' } };
|
||||||
@@ -103,47 +90,24 @@ export function parseSignupForm(
|
|||||||
|
|
||||||
const phoneRaw = parsed.data.phone.normalize('NFC').trim();
|
const phoneRaw = parsed.data.phone.normalize('NFC').trim();
|
||||||
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
|
const phone = phoneRaw.length === 0 ? '' : formatPhone(phoneRaw);
|
||||||
if (phoneRaw.length > PHONE_MAX || phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
if (phoneRaw.length === 0 || phone.length === 0) {
|
||||||
|
errors.phone = voice === 'coordinator' ? 'Enter their phone number.' : 'Enter your phone number.';
|
||||||
|
} else if (phoneRaw.length > PHONE_MAX || phone.length > PHONE_MAX) errors.phone = `Use ${PHONE_MAX} characters or fewer.`;
|
||||||
else if (controlChars.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
else if (controlChars.test(phoneRaw)) errors.phone = 'Enter a phone number without line breaks.';
|
||||||
|
|
||||||
const notes = parsed.data.notes.normalize('NFC').trim();
|
const notes = parsed.data.notes.normalize('NFC').trim();
|
||||||
if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`;
|
if (notes.length > NOTES_MAX) errors.notes = `Use ${NOTES_MAX} characters or fewer.`;
|
||||||
else if (controlChars.test(notes)) errors.notes = 'Enter notes without control characters.';
|
else if (controlChars.test(notes)) errors.notes = 'Enter notes without control characters.';
|
||||||
|
|
||||||
let guardianName: string | null = null;
|
if (Object.keys(errors).length > 0 || emailNorm.length === 0 || phone.length === 0) return { ok: false, errors };
|
||||||
let guardianEmail: string | null = null;
|
|
||||||
let guardianEmailNorm: string | null = null;
|
|
||||||
if (parsed.data.under18) {
|
|
||||||
const guardianRaw = parsed.data.guardianName.normalize('NFC').trim();
|
|
||||||
guardianName = capitalizeName(guardianRaw);
|
|
||||||
if (guardianRaw.length === 0 || guardianName.length === 0) errors.guardianName = 'Enter the guardian name.';
|
|
||||||
else if (guardianRaw.length > NAME_MAX || guardianName.length > NAME_MAX) errors.guardianName = `Use ${NAME_MAX} characters or fewer.`;
|
|
||||||
else if (controlChars.test(guardianRaw)) errors.guardianName = 'Enter the guardian name without line breaks.';
|
|
||||||
if (parsed.data.guardianEmail.trim() === '') {
|
|
||||||
errors.guardianEmail = 'Enter the guardian email.';
|
|
||||||
} else {
|
|
||||||
try {
|
|
||||||
guardianEmailNorm = normalizeEmail(parsed.data.guardianEmail);
|
|
||||||
guardianEmail = guardianEmailNorm;
|
|
||||||
} catch (err) {
|
|
||||||
errors.guardianEmail = err instanceof EmailAddressError ? err.message : 'Enter the guardian email.';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Object.keys(errors).length > 0 || emailNorm.length === 0) return { ok: false, errors };
|
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
draft: {
|
draft: {
|
||||||
name,
|
name,
|
||||||
email: emailNorm,
|
email: emailNorm,
|
||||||
emailNorm,
|
emailNorm,
|
||||||
phone: phone.length === 0 ? null : phone,
|
phone,
|
||||||
notes: notes.length === 0 ? null : notes,
|
notes: notes.length === 0 ? null : notes,
|
||||||
isMinor: parsed.data.under18,
|
|
||||||
guardianName: parsed.data.under18 ? guardianName : null,
|
|
||||||
guardianEmail: parsed.data.under18 ? guardianEmail : null,
|
|
||||||
guardianEmailNorm: parsed.data.under18 ? guardianEmailNorm : null,
|
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
+2
-17
@@ -24,7 +24,7 @@ import {
|
|||||||
type SignupFormView,
|
type SignupFormView,
|
||||||
type SwitchForm,
|
type SwitchForm,
|
||||||
} from './pages.js';
|
} from './pages.js';
|
||||||
import { recordInvalidManageToken, recordSignupEmail, recordSignupGuardian, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
import { recordInvalidManageToken, recordSignupEmail, recordSignupIp, recordSwitchAttempt } from './rate-limit.js';
|
||||||
import { getPublicShift, type PublicShift } from './schedule.js';
|
import { getPublicShift, type PublicShift } from './schedule.js';
|
||||||
import { EMPTY_SIGNUP, parseSignupForm, type SignupErrors, type SignupValues } from './signup-form.js';
|
import { EMPTY_SIGNUP, parseSignupForm, type SignupErrors, type SignupValues } from './signup-form.js';
|
||||||
import type { MailIdentity } from './mail/types.js';
|
import type { MailIdentity } from './mail/types.js';
|
||||||
@@ -154,13 +154,6 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
|
|||||||
if (emailLimit.limited) {
|
if (emailLimit.limited) {
|
||||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, emailLimit.retryAfter);
|
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, emailLimit.retryAfter);
|
||||||
}
|
}
|
||||||
const guardianEmail = parsed.draft.guardianEmailNorm;
|
|
||||||
if (guardianEmail && guardianEmail !== parsed.draft.emailNorm) {
|
|
||||||
const guardianLimit = recordSignupGuardian(db, config.sessionSecret, now, config.defaultTimeZone, guardianEmail);
|
|
||||||
if (guardianLimit.limited) {
|
|
||||||
return shiftResponse(c, services, shift, 429, formFor(services, shift, values, {}, textField(body, 'form_token')), TOO_MANY, guardianLimit.retryAfter);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
try {
|
try {
|
||||||
const reserved = reserveSignup(db, {
|
const reserved = reserveSignup(db, {
|
||||||
shiftId: shift.id,
|
shiftId: shift.id,
|
||||||
@@ -168,9 +161,6 @@ async function submitSignup(c: Context, services: SignupServices): Promise<Respo
|
|||||||
email: parsed.draft.emailNorm,
|
email: parsed.draft.emailNorm,
|
||||||
phone: parsed.draft.phone,
|
phone: parsed.draft.phone,
|
||||||
notes: parsed.draft.notes,
|
notes: parsed.draft.notes,
|
||||||
isMinor: parsed.draft.isMinor,
|
|
||||||
guardianName: parsed.draft.guardianName,
|
|
||||||
guardianEmail: parsed.draft.guardianEmail,
|
|
||||||
operationId: tokenResult.claims.operationId,
|
operationId: tokenResult.claims.operationId,
|
||||||
now,
|
now,
|
||||||
mail: mailIdentity(db, config),
|
mail: mailIdentity(db, config),
|
||||||
@@ -284,9 +274,6 @@ function valuesFrom(body: Record<string, unknown>): SignupValues {
|
|||||||
email: textField(body, 'email'),
|
email: textField(body, 'email'),
|
||||||
phone: textField(body, 'phone'),
|
phone: textField(body, 'phone'),
|
||||||
notes: textField(body, 'notes'),
|
notes: textField(body, 'notes'),
|
||||||
under18: textField(body, 'under18') === 'yes',
|
|
||||||
guardianName: textField(body, 'guardianName'),
|
|
||||||
guardianEmail: textField(body, 'guardianEmail'),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,10 +368,8 @@ async function submitSwitch(c: Context, services: SignupServices): Promise<Respo
|
|||||||
if (!formToken.ok) return showManage(c, services, token, 400, SWITCH_STALE);
|
if (!formToken.ok) return showManage(c, services, token, 400, SWITCH_STALE);
|
||||||
try {
|
try {
|
||||||
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
const ip = clientAddress(services.config.trustProxy, peerAddress(c, services.clientIp), c.req.header('x-forwarded-for'));
|
||||||
const recipients = [signup.emailNorm];
|
|
||||||
if (signup.isMinor && signup.guardianEmail) recipients.push(signup.guardianEmail);
|
|
||||||
const limit = recordSwitchAttempt(
|
const limit = recordSwitchAttempt(
|
||||||
services.db, services.config.sessionSecret, services.now(), services.config.defaultTimeZone, ip, recipients,
|
services.db, services.config.sessionSecret, services.now(), services.config.defaultTimeZone, ip, [signup.emailNorm],
|
||||||
);
|
);
|
||||||
if (limit.limited) {
|
if (limit.limited) {
|
||||||
c.header('Retry-After', String(limit.retryAfter));
|
c.header('Retry-After', String(limit.retryAfter));
|
||||||
|
|||||||
+4
-22
@@ -15,9 +15,6 @@ export type ReserveInput = {
|
|||||||
email: string;
|
email: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
isMinor: boolean;
|
|
||||||
guardianName: string | null;
|
|
||||||
guardianEmail: string | null;
|
|
||||||
operationId: string;
|
operationId: string;
|
||||||
now: string;
|
now: string;
|
||||||
mail: MailIdentity;
|
mail: MailIdentity;
|
||||||
@@ -36,9 +33,6 @@ export type ManageView = {
|
|||||||
email: string;
|
email: string;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
isMinor: boolean;
|
|
||||||
guardianName: string | null;
|
|
||||||
guardianEmail: string | null;
|
|
||||||
status: 'confirmed' | 'cancelled';
|
status: 'confirmed' | 'cancelled';
|
||||||
remindersOff: boolean;
|
remindersOff: boolean;
|
||||||
emailNorm: string;
|
emailNorm: string;
|
||||||
@@ -109,9 +103,6 @@ export function readManageSignup(db: Database.Database, token: string, now: stri
|
|||||||
su.email AS email,
|
su.email AS email,
|
||||||
su.phone AS phone,
|
su.phone AS phone,
|
||||||
su.notes AS notes,
|
su.notes AS notes,
|
||||||
su.is_minor AS is_minor,
|
|
||||||
su.guardian_name AS guardian_name,
|
|
||||||
su.guardian_email AS guardian_email,
|
|
||||||
su.status AS status,
|
su.status AS status,
|
||||||
su.reminders_off AS reminders_off,
|
su.reminders_off AS reminders_off,
|
||||||
su.email_norm AS email_norm,
|
su.email_norm AS email_norm,
|
||||||
@@ -138,9 +129,6 @@ export function readManageSignup(db: Database.Database, token: string, now: stri
|
|||||||
email: row.email,
|
email: row.email,
|
||||||
phone: row.phone,
|
phone: row.phone,
|
||||||
notes: row.notes,
|
notes: row.notes,
|
||||||
isMinor: row.is_minor === 1,
|
|
||||||
guardianName: row.guardian_name,
|
|
||||||
guardianEmail: row.guardian_email,
|
|
||||||
status: row.status,
|
status: row.status,
|
||||||
remindersOff: row.reminders_off === 1,
|
remindersOff: row.reminders_off === 1,
|
||||||
emailNorm: row.email_norm,
|
emailNorm: row.email_norm,
|
||||||
@@ -214,9 +202,9 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
|||||||
emailNorm,
|
emailNorm,
|
||||||
emailNorm,
|
emailNorm,
|
||||||
input.phone,
|
input.phone,
|
||||||
input.isMinor ? 1 : 0,
|
0,
|
||||||
input.isMinor ? input.guardianName : null,
|
null,
|
||||||
input.isMinor ? input.guardianEmail : null,
|
null,
|
||||||
input.notes,
|
input.notes,
|
||||||
sha256(manageToken),
|
sha256(manageToken),
|
||||||
expiresAt,
|
expiresAt,
|
||||||
@@ -232,7 +220,6 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
|||||||
token: manageToken,
|
token: manageToken,
|
||||||
volunteerName: input.name,
|
volunteerName: input.name,
|
||||||
volunteerEmail: emailNorm,
|
volunteerEmail: emailNorm,
|
||||||
guardianEmail: input.isMinor ? input.guardianEmail : null,
|
|
||||||
shift: shiftFacts(shift).facts,
|
shift: shiftFacts(shift).facts,
|
||||||
mail: input.mail,
|
mail: input.mail,
|
||||||
now: input.now,
|
now: input.now,
|
||||||
@@ -282,7 +269,7 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
|||||||
const row = db
|
const row = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT su.id AS id, su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
`SELECT su.id AS id, su.status AS status, su.token_expires_at AS token_expires_at, su.anonymized_at AS anonymized_at,
|
||||||
su.name AS name, su.email_norm AS email_norm, su.guardian_email AS guardian_email, su.shift_id AS shift_id
|
su.name AS name, su.email_norm AS email_norm, su.shift_id AS shift_id
|
||||||
FROM signups su
|
FROM signups su
|
||||||
WHERE su.manage_token_hash = ?`,
|
WHERE su.manage_token_hash = ?`,
|
||||||
)
|
)
|
||||||
@@ -294,7 +281,6 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
|||||||
anonymized_at: string | null;
|
anonymized_at: string | null;
|
||||||
name: string | null;
|
name: string | null;
|
||||||
email_norm: string | null;
|
email_norm: string | null;
|
||||||
guardian_email: string | null;
|
|
||||||
shift_id: number;
|
shift_id: number;
|
||||||
}
|
}
|
||||||
| undefined;
|
| undefined;
|
||||||
@@ -322,7 +308,6 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
|||||||
token,
|
token,
|
||||||
volunteerName: row.name,
|
volunteerName: row.name,
|
||||||
volunteerEmail: row.email_norm,
|
volunteerEmail: row.email_norm,
|
||||||
guardianEmail: row.guardian_email,
|
|
||||||
shift: shift.facts,
|
shift: shift.facts,
|
||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
@@ -405,9 +390,6 @@ type ManageRow = {
|
|||||||
email_norm: string | null;
|
email_norm: string | null;
|
||||||
phone: string | null;
|
phone: string | null;
|
||||||
notes: string | null;
|
notes: string | null;
|
||||||
is_minor: number;
|
|
||||||
guardian_name: string | null;
|
|
||||||
guardian_email: string | null;
|
|
||||||
status: string;
|
status: string;
|
||||||
reminders_off: number;
|
reminders_off: number;
|
||||||
token_expires_at: string | null;
|
token_expires_at: string | null;
|
||||||
|
|||||||
+13
-32
@@ -384,9 +384,9 @@ describe('coordinator screens', () => {
|
|||||||
const html = await page.text();
|
const html = await page.text();
|
||||||
expect(html).toContain('Add a walk-in');
|
expect(html).toContain('Add a walk-in');
|
||||||
expect(html).toContain('src="/js/enhance.js?v=');
|
expect(html).toContain('src="/js/enhance.js?v=');
|
||||||
expect(html).toContain('data-under-18');
|
expect(html).not.toContain('data-under-18');
|
||||||
expect(html).toContain('data-guardian');
|
expect(html).not.toContain('data-guardian');
|
||||||
expect(html).not.toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
expect(html).not.toContain('They are under 18');
|
||||||
expect(html).not.toContain('cf-turnstile');
|
expect(html).not.toContain('cf-turnstile');
|
||||||
const body = walkInBody(html, {
|
const body = walkInBody(html, {
|
||||||
name: 'Dee Example',
|
name: 'Dee Example',
|
||||||
@@ -420,26 +420,16 @@ describe('coordinator screens', () => {
|
|||||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed'")).toBe(2);
|
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'dee@example.invalid' AND status = 'confirmed'")).toBe(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps a walk-in off a full, closed, or ended shift and asks for a guardian', async () => {
|
it('keeps a walk-in off a full, closed, or ended shift', async () => {
|
||||||
const { app, db } = await buildApp();
|
const { app, db } = await buildApp();
|
||||||
const cookie = await signIn(app, db);
|
const cookie = await signIn(app, db);
|
||||||
const shiftId = await openShift(app, cookie, { published: true, capacity: '1', role: 'Sorting', date: '2026-10-21' });
|
const shiftId = await openShift(app, cookie, { published: true, capacity: '1', role: 'Sorting', date: '2026-10-21' });
|
||||||
const minor = await postWalkIn(app, cookie, shiftId, { name: 'Kim Example', email: 'kim@example.invalid', under18: 'yes' });
|
|
||||||
expect(minor.status).toBe(400);
|
|
||||||
const minorHtml = await minor.text();
|
|
||||||
expect(minorHtml).toContain('Enter the guardian name.');
|
|
||||||
expect(minorHtml).toMatch(/id="walkin-under-18"[^>]*\schecked/);
|
|
||||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
|
|
||||||
|
|
||||||
const added = await postWalkIn(app, cookie, shiftId, {
|
const added = await postWalkIn(app, cookie, shiftId, {
|
||||||
name: 'Kim Example',
|
name: 'Kim Example',
|
||||||
email: 'kim@example.invalid',
|
email: 'kim@example.invalid',
|
||||||
under18: 'yes',
|
|
||||||
guardianName: 'Pat Example',
|
|
||||||
guardianEmail: 'pat@example.invalid',
|
|
||||||
});
|
});
|
||||||
expect(added.status).toBe(303);
|
expect(added.status).toBe(303);
|
||||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(2);
|
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation' AND status = 'pending'")).toBe(1);
|
||||||
const full = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
const full = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
||||||
expect(full).toContain('This shift is full.');
|
expect(full).toContain('This shift is full.');
|
||||||
expect(full).not.toContain('Add a walk-in');
|
expect(full).not.toContain('Add a walk-in');
|
||||||
@@ -558,9 +548,6 @@ describe('coordinator screens', () => {
|
|||||||
const added = await postWalkIn(app, cookie, sourceId, {
|
const added = await postWalkIn(app, cookie, sourceId, {
|
||||||
name: 'Kim Example',
|
name: 'Kim Example',
|
||||||
email: 'kim@example.invalid',
|
email: 'kim@example.invalid',
|
||||||
under18: 'yes',
|
|
||||||
guardianName: 'Pat Example',
|
|
||||||
guardianEmail: 'pat@example.invalid',
|
|
||||||
});
|
});
|
||||||
expect(added.status).toBe(303);
|
expect(added.status).toBe(303);
|
||||||
const signupId = signupIdFor(db, 'kim@example.invalid');
|
const signupId = signupIdFor(db, 'kim@example.invalid');
|
||||||
@@ -600,8 +587,8 @@ describe('coordinator screens', () => {
|
|||||||
notes: string;
|
notes: string;
|
||||||
reminders_off: number;
|
reminders_off: number;
|
||||||
is_minor: number;
|
is_minor: number;
|
||||||
guardian_name: string;
|
guardian_name: string | null;
|
||||||
guardian_email: string;
|
guardian_email: string | null;
|
||||||
shift_id: number;
|
shift_id: number;
|
||||||
};
|
};
|
||||||
expect(created).toMatchObject({
|
expect(created).toMatchObject({
|
||||||
@@ -610,15 +597,15 @@ describe('coordinator screens', () => {
|
|||||||
phone: '712-555-0199',
|
phone: '712-555-0199',
|
||||||
notes: 'Blue shirt',
|
notes: 'Blue shirt',
|
||||||
reminders_off: 1,
|
reminders_off: 1,
|
||||||
is_minor: 1,
|
is_minor: 0,
|
||||||
guardian_name: 'Pat Example',
|
guardian_name: null,
|
||||||
guardian_email: 'pat@example.invalid',
|
guardian_email: null,
|
||||||
shift_id: destinationId,
|
shift_id: destinationId,
|
||||||
});
|
});
|
||||||
expect(shiftVersions(db)).toEqual(versions);
|
expect(shiftVersions(db)).toEqual(versions);
|
||||||
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(2);
|
expect(counted(db, signupId, 'confirmation', 'cancelled')).toBe(1);
|
||||||
expect(db.prepare("SELECT status AS status FROM outbox WHERE kind = 'reminder'").get()).toEqual({ status: 'cancelled' });
|
expect(db.prepare("SELECT status AS status FROM outbox WHERE kind = 'reminder'").get()).toEqual({ status: 'cancelled' });
|
||||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(2);
|
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(1);
|
||||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'")).toBe(0);
|
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled'")).toBe(0);
|
||||||
const letter = db.prepare("SELECT subject, body_text FROM outbox WHERE kind = 'changed' AND to_email = 'kim@example.invalid'").get() as {
|
const letter = db.prepare("SELECT subject, body_text FROM outbox WHERE kind = 'changed' AND to_email = 'kim@example.invalid'").get() as {
|
||||||
subject: string;
|
subject: string;
|
||||||
@@ -848,9 +835,6 @@ function reserve(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: number
|
|||||||
email,
|
email,
|
||||||
phone: '712-555-0100',
|
phone: '712-555-0100',
|
||||||
notes: 'Bring gloves',
|
notes: 'Bring gloves',
|
||||||
isMinor: false,
|
|
||||||
guardianName: null,
|
|
||||||
guardianEmail: null,
|
|
||||||
operationId,
|
operationId,
|
||||||
now: NOW,
|
now: NOW,
|
||||||
mail: MAIL,
|
mail: MAIL,
|
||||||
@@ -999,11 +983,8 @@ function walkInBody(html: string, fields: Record<string, string>) {
|
|||||||
form_token: field(html, 'form_token'),
|
form_token: field(html, 'form_token'),
|
||||||
name: fields.name ?? '',
|
name: fields.name ?? '',
|
||||||
email: fields.email ?? '',
|
email: fields.email ?? '',
|
||||||
phone: fields.phone ?? '',
|
phone: fields.phone ?? '712-555-0100',
|
||||||
notes: fields.notes ?? '',
|
notes: fields.notes ?? '',
|
||||||
guardianName: fields.guardianName ?? '',
|
|
||||||
guardianEmail: fields.guardianEmail ?? '',
|
|
||||||
...(fields.under18 ? { under18: fields.under18 } : {}),
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -371,10 +371,8 @@ async function postSignup(
|
|||||||
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
|
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
|
||||||
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
|
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
|
||||||
email: fields.email,
|
email: fields.email,
|
||||||
phone: '',
|
phone: '712-555-0100',
|
||||||
notes: '',
|
notes: '',
|
||||||
guardianName: '',
|
|
||||||
guardianEmail: '',
|
|
||||||
company_website: '',
|
company_website: '',
|
||||||
'cf-turnstile-response': 'widget-token',
|
'cf-turnstile-response': 'widget-token',
|
||||||
});
|
});
|
||||||
|
|||||||
+53
-50
@@ -41,43 +41,49 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('contact spreadsheet', () => {
|
describe('contact spreadsheet', () => {
|
||||||
it('keeps two emails for one name, ignores address, and skips a bad email', async () => {
|
it('keeps two emails for one name, ignores address, and skips a bad email or blank phone', async () => {
|
||||||
const db = await openDb();
|
const db = await openDb();
|
||||||
const imported = importContactCsv(db, null, PEOPLE, NOW);
|
const imported = importContactCsv(db, null, PEOPLE, NOW);
|
||||||
expect(imported.ok).toBe(true);
|
expect(imported.ok).toBe(true);
|
||||||
if (!imported.ok) return;
|
if (!imported.ok) return;
|
||||||
expect(imported.result.added).toBe(3);
|
expect(imported.result.added).toBe(2);
|
||||||
expect(imported.result.skipped).toBe(1);
|
expect(imported.result.skipped).toBe(2);
|
||||||
expect(imported.result.skips).toEqual([{ line: 5, code: 'e' }]);
|
expect(imported.result.skips).toEqual([
|
||||||
expect(contactImportSentence(imported.result)).toBe('Saved 3 new contacts. Skipped 1 row.');
|
{ line: 3, code: 'm' },
|
||||||
|
{ line: 5, code: 'e' },
|
||||||
|
]);
|
||||||
|
expect(contactImportSentence(imported.result)).toBe('Saved 2 new contacts. Skipped 2 rows.');
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare('SELECT first_name, last_name, email, phone FROM contacts ORDER BY id')
|
.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 }[];
|
.all() as { first_name: string; last_name: string; email: string; phone: string | null }[];
|
||||||
expect(rows).toEqual([
|
expect(rows).toEqual([
|
||||||
{ first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' },
|
{ first_name: 'Kristi', last_name: 'Anderson', email: 'kristi@example.invalid', phone: '712441076' },
|
||||||
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara@example.invalid', phone: null },
|
|
||||||
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '712-555-0100' },
|
{ first_name: 'Kara', last_name: 'Acevedo', email: 'kara.other@example.invalid', phone: '712-555-0100' },
|
||||||
]);
|
]);
|
||||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
|
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(0);
|
||||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
|
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
|
||||||
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.import'`).get() as { detail_json: string };
|
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(JSON.parse(audit.detail_json)).toEqual({ added: 2, changed: 0, unchanged: 0, skipped: 2 });
|
||||||
expect(audit.detail_json).not.toContain('@');
|
expect(audit.detail_json).not.toContain('@');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('keeps two names that share an email and updates only the matching name', async () => {
|
it('keeps two names that share an email and updates only the matching name', async () => {
|
||||||
const db = await openDb();
|
const db = await openDb();
|
||||||
importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW);
|
importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,One,ada@example.invalid,111\n', NOW);
|
||||||
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,\n', NOW);
|
const renamed = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ADA@example.invalid,222\n', NOW);
|
||||||
expect(renamed.ok && renamed.result.added).toBe(1);
|
expect(renamed.ok && renamed.result.added).toBe(1);
|
||||||
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
|
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
|
||||||
{ first_name: 'Ada', last_name: 'One', phone: '111' },
|
{ first_name: 'Ada', last_name: 'One', phone: '111' },
|
||||||
{ first_name: 'Ada', last_name: 'Two', phone: null },
|
{ first_name: 'Ada', last_name: 'Two', phone: '222' },
|
||||||
]);
|
]);
|
||||||
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nada,two,ada@example.invalid,(712) 555-0100\n', NOW);
|
const replaced = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nada,two,ada@example.invalid,(712) 555-0100\n', NOW);
|
||||||
expect(replaced.ok && replaced.result.changed).toBe(1);
|
expect(replaced.ok && replaced.result.changed).toBe(1);
|
||||||
expect(db.prepare('SELECT phone FROM contacts ORDER BY id').all()).toEqual([{ phone: '111' }, { phone: '712-555-0100' }]);
|
expect(db.prepare('SELECT phone FROM contacts ORDER BY id').all()).toEqual([{ phone: '111' }, { phone: '712-555-0100' }]);
|
||||||
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
|
const blankPhone = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,\n', NOW);
|
||||||
|
expect(blankPhone.ok && blankPhone.result.skipped).toBe(1);
|
||||||
|
expect(blankPhone.ok && blankPhone.result.skips).toEqual([{ line: 2, code: 'm' }]);
|
||||||
|
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
|
||||||
|
const same = importContactCsv(db, null, 'First Name,Last Name,Email,Phone\nAda,Two,ada@example.invalid,712-555-0100\n', NOW);
|
||||||
expect(same.ok && same.result.unchanged).toBe(1);
|
expect(same.ok && same.result.unchanged).toBe(1);
|
||||||
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
|
expect(db.prepare("SELECT phone FROM contacts WHERE last_name = 'Two'").get()).toEqual({ phone: '712-555-0100' });
|
||||||
const shaped = importContactCsv(
|
const shaped = importContactCsv(
|
||||||
@@ -128,17 +134,21 @@ describe('contact spreadsheet', () => {
|
|||||||
error: CONTACT_CSV_COLUMNS,
|
error: CONTACT_CSV_COLUMNS,
|
||||||
});
|
});
|
||||||
expect(importContactCsv(db, null, ' ', NOW)).toEqual({ ok: false, error: CONTACT_CSV_EMPTY });
|
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({
|
expect(importContactCsv(db, null, 'First Name,Last Name,Email\nAda,One,ada@example.invalid\n', NOW)).toEqual({
|
||||||
|
ok: false,
|
||||||
|
error: CONTACT_CSV_COLUMNS,
|
||||||
|
});
|
||||||
|
expect(importContactCsv(db, null, 'First Name,Last Name,Email,Phone\n"Ada,One,ada@example.invalid,555\n', NOW)).toEqual({
|
||||||
ok: false,
|
ok: false,
|
||||||
error: CONTACT_CSV_READ,
|
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,Phone\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({
|
expect(importContactCsv(db, null, `First Name,Last Name,Email,Phone\n${'x'.repeat(64 * 1024)}`, NOW)).toEqual({
|
||||||
ok: false,
|
ok: false,
|
||||||
error: CONTACT_CSV_LIMIT,
|
error: CONTACT_CSV_LIMIT,
|
||||||
});
|
});
|
||||||
const lines = ['First Name,Last Name,Email'];
|
const lines = ['First Name,Last Name,Email,Phone'];
|
||||||
for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c`);
|
for (let i = 0; i < 2001; i += 1) lines.push(`A,B,a${i}@b.c,555`);
|
||||||
expect(importContactCsv(db, null, lines.join('\n'), NOW)).toEqual({ ok: false, error: CONTACT_CSV_LARGE });
|
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);
|
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(0);
|
||||||
});
|
});
|
||||||
@@ -182,10 +192,10 @@ describe('contact pages', () => {
|
|||||||
it('shows the next page of contacts and keeps the search', async () => {
|
it('shows the next page of contacts and keeps the search', async () => {
|
||||||
const { app, db } = await buildApp();
|
const { app, db } = await buildApp();
|
||||||
const cookie = await signIn(app, db);
|
const cookie = await signIn(app, db);
|
||||||
const lines = ['First Name,Last Name,Email'];
|
const lines = ['First Name,Last Name,Email,Phone'];
|
||||||
for (let i = 0; i <= CONTACT_LIST_PAGE; i += 1) {
|
for (let i = 0; i <= CONTACT_LIST_PAGE; i += 1) {
|
||||||
const name = String(i).padStart(2, '0');
|
const name = String(i).padStart(2, '0');
|
||||||
lines.push(`Ada,N${name},n${name}@example.invalid`);
|
lines.push(`Ada,N${name},n${name}@example.invalid,712-555-${name}00`);
|
||||||
}
|
}
|
||||||
const imported = await postFile(app, cookie, lines.join('\n'));
|
const imported = await postFile(app, cookie, lines.join('\n'));
|
||||||
expect(imported.status).toBe(303);
|
expect(imported.status).toBe(303);
|
||||||
@@ -232,7 +242,8 @@ describe('contact pages', () => {
|
|||||||
expect(imported.status).toBe(303);
|
expect(imported.status).toBe(303);
|
||||||
const page = await app.request(imported.headers.get('location') ?? '', { headers: { cookie } });
|
const page = await app.request(imported.headers.get('location') ?? '', { headers: { cookie } });
|
||||||
const html = await page.text();
|
const html = await page.text();
|
||||||
expect(html).toContain('Saved 3 new contacts. Skipped 1 row.');
|
expect(html).toContain('Saved 2 new contacts. Skipped 2 rows.');
|
||||||
|
expect(html).toContain('Row 3 was skipped because the phone is missing.');
|
||||||
expect(html).toContain('Row 5 was skipped because the email is not an address.');
|
expect(html).toContain('Row 5 was skipped because the email is not an address.');
|
||||||
expect(html).toContain('Kristi Anderson');
|
expect(html).toContain('Kristi Anderson');
|
||||||
expect(html).toContain('kara.other@example.invalid');
|
expect(html).toContain('kara.other@example.invalid');
|
||||||
@@ -266,7 +277,7 @@ describe('contact pages', () => {
|
|||||||
const exportAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.export'`).get() as {
|
const exportAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.export'`).get() as {
|
||||||
detail_json: string;
|
detail_json: string;
|
||||||
};
|
};
|
||||||
expect(exportAudit.detail_json).toBe('{"rows":3}');
|
expect(exportAudit.detail_json).toBe('{"rows":2}');
|
||||||
|
|
||||||
const hidden = await app.request('/admin/contacts/export', { method: 'POST' });
|
const hidden = await app.request('/admin/contacts/export', { method: 'POST' });
|
||||||
expect(hidden.status).toBe(303);
|
expect(hidden.status).toBe(303);
|
||||||
@@ -400,19 +411,11 @@ describe('contact pages', () => {
|
|||||||
expect(personHtml).not.toContain('Finished');
|
expect(personHtml).not.toContain('Finished');
|
||||||
expect(personHtml).not.toContain('Packing');
|
expect(personHtml).not.toContain('Packing');
|
||||||
expect(personHtml).toContain('Add to this shift');
|
expect(personHtml).toContain('Add to this shift');
|
||||||
expect(personHtml).toContain('They are under 18');
|
expect(personHtml).not.toContain('They are under 18');
|
||||||
|
|
||||||
const beforeMail = count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`);
|
const beforeMail = count(db, `SELECT COUNT(*) AS n FROM outbox WHERE kind = 'confirmation'`);
|
||||||
expect(beforeMail).toBe(0);
|
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"'), {});
|
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(stale.status).toBe(400);
|
||||||
expect(await stale.text()).toContain('This form is out of date. Submit it again.');
|
expect(await stale.text()).toContain('This form is out of date. Submit it again.');
|
||||||
@@ -437,29 +440,25 @@ describe('contact pages', () => {
|
|||||||
const walkInAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'signup.walkin'`).get() as { detail_json: string };
|
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('@');
|
expect(walkInAudit.detail_json).not.toContain('@');
|
||||||
|
|
||||||
const minorFile = await postFile(app, cookie, 'First Name,Last Name,Email\nBea,Minor,bea@example.invalid\n');
|
const beaFile = await postFile(app, cookie, 'First Name,Last Name,Email,Phone\nBea,Example,bea@example.invalid,712-555-0102\n');
|
||||||
expect(minorFile.status).toBe(303);
|
expect(beaFile.status).toBe(303);
|
||||||
const beaId = (db.prepare(`SELECT id AS id FROM contacts WHERE email = 'bea@example.invalid'`).get() as { id: number }).id;
|
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 beaPage = await app.request(`/admin/contacts/${beaId}`, { headers: { cookie } });
|
||||||
const beaHtml = await beaPage.text();
|
const beaHtml = await beaPage.text();
|
||||||
expect(beaPage.status).toBe(200);
|
expect(beaPage.status).toBe(200);
|
||||||
expect(beaHtml).toContain(`<option value="${unpublishedId}">`);
|
expect(beaHtml).toContain(`<option value="${unpublishedId}">`);
|
||||||
const beaAdded = await postContactShift(app, cookie, beaId, unpublishedId, beaHtml, {
|
const beaAdded = await postContactShift(app, cookie, beaId, unpublishedId, beaHtml, {});
|
||||||
under18: 'yes',
|
|
||||||
guardianName: 'Pat Minor',
|
|
||||||
guardianEmail: 'pat@example.invalid',
|
|
||||||
});
|
|
||||||
expect(beaAdded.status).toBe(303);
|
expect(beaAdded.status).toBe(303);
|
||||||
const beaSignup = db.prepare(
|
const beaSignup = db.prepare(
|
||||||
`SELECT is_minor AS is_minor, guardian_name AS guardian_name, guardian_email AS guardian_email
|
`SELECT is_minor AS is_minor, guardian_name AS guardian_name, guardian_email AS guardian_email
|
||||||
FROM signups WHERE email_norm = 'bea@example.invalid'`,
|
FROM signups WHERE email_norm = 'bea@example.invalid'`,
|
||||||
).get() as { is_minor: number; guardian_name: string; guardian_email: string };
|
).get() as { is_minor: number; guardian_name: string | null; guardian_email: string | null };
|
||||||
expect(beaSignup).toEqual({ is_minor: 1, guardian_name: 'Pat Minor', guardian_email: 'pat@example.invalid' });
|
expect(beaSignup).toEqual({ is_minor: 0, guardian_name: null, guardian_email: null });
|
||||||
expect(count(db, `SELECT COUNT(*) AS n FROM contacts`)).toBe(2);
|
expect(count(db, `SELECT COUNT(*) AS n FROM contacts`)).toBe(2);
|
||||||
const mailed = db
|
const mailed = db
|
||||||
.prepare(`SELECT to_email AS to_email FROM outbox WHERE kind = 'confirmation' ORDER BY to_email`)
|
.prepare(`SELECT to_email AS to_email FROM outbox WHERE kind = 'confirmation' ORDER BY to_email`)
|
||||||
.all() as Array<{ to_email: string }>;
|
.all() as Array<{ to_email: string }>;
|
||||||
expect(mailed.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid', 'pat@example.invalid']);
|
expect(mailed.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid']);
|
||||||
|
|
||||||
const againPage = await app.request(`/admin/contacts/${contactId}`, { headers: { cookie } });
|
const againPage = await app.request(`/admin/contacts/${contactId}`, { headers: { cookie } });
|
||||||
const againPageHtml = await againPage.text();
|
const againPageHtml = await againPage.text();
|
||||||
@@ -495,7 +494,7 @@ describe('contact pages', () => {
|
|||||||
const manualAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.manual'`).get() as { detail_json: string };
|
const manualAudit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'contacts.manual'`).get() as { detail_json: string };
|
||||||
expect(manualAudit.detail_json).not.toContain('@');
|
expect(manualAudit.detail_json).not.toContain('@');
|
||||||
|
|
||||||
const same = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Example', email: 'ada@example.invalid', phone: '' });
|
const same = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Example', email: 'ada@example.invalid', phone: '712-555-0100' });
|
||||||
expect(same.headers.get('location')).toBe('/admin/contacts?notice=contact-matched');
|
expect(same.headers.get('location')).toBe('/admin/contacts?notice=contact-matched');
|
||||||
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0100' });
|
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0100' });
|
||||||
|
|
||||||
@@ -504,18 +503,24 @@ describe('contact pages', () => {
|
|||||||
expect(changed.headers.get('location')).toBe('/admin/contacts?notice=contact-updated');
|
expect(changed.headers.get('location')).toBe('/admin/contacts?notice=contact-updated');
|
||||||
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0199' });
|
expect(db.prepare('SELECT phone FROM contacts').get()).toEqual({ phone: '712-555-0199' });
|
||||||
|
|
||||||
const other = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Other', email: 'ada@example.invalid', phone: '' });
|
const other = await postManual(app, cookie, { firstName: 'Ada', lastName: 'Other', email: 'ada@example.invalid', phone: '712-555-0111' });
|
||||||
expect(other.headers.get('location')).toBe('/admin/contacts?notice=contact-saved');
|
expect(other.headers.get('location')).toBe('/admin/contacts?notice=contact-saved');
|
||||||
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
|
expect(db.prepare('SELECT first_name, last_name, phone FROM contacts ORDER BY id').all()).toEqual([
|
||||||
{ first_name: 'Ada', last_name: 'Example', phone: '712-555-0199' },
|
{ first_name: 'Ada', last_name: 'Example', phone: '712-555-0199' },
|
||||||
{ first_name: 'Ada', last_name: 'Other', phone: null },
|
{ first_name: 'Ada', last_name: 'Other', phone: '712-555-0111' },
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const blankPhone = await postManual(app, cookie, { firstName: 'Sam', lastName: 'Example', email: 'sam@example.invalid', phone: '' });
|
||||||
|
expect(blankPhone.status).toBe(400);
|
||||||
|
expect(await blankPhone.text()).toContain('Enter a phone number.');
|
||||||
|
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
|
||||||
|
|
||||||
const invalid = await postManual(app, cookie, { firstName: '', lastName: 'Example', email: 'not-an-email', phone: '' });
|
const invalid = await postManual(app, cookie, { firstName: '', lastName: 'Example', email: 'not-an-email', phone: '' });
|
||||||
expect(invalid.status).toBe(400);
|
expect(invalid.status).toBe(400);
|
||||||
const invalidHtml = await invalid.text();
|
const invalidHtml = await invalid.text();
|
||||||
expect(invalidHtml).toContain('Enter a first name.');
|
expect(invalidHtml).toContain('Enter a first name.');
|
||||||
expect(invalidHtml).toContain('Enter an email address.');
|
expect(invalidHtml).toContain('Enter an email address.');
|
||||||
|
expect(invalidHtml).toContain('Enter a phone number.');
|
||||||
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
|
expect(count(db, 'SELECT COUNT(*) AS n FROM contacts')).toBe(2);
|
||||||
expect(await (await app.request('/')).text()).not.toContain('ada@example.invalid');
|
expect(await (await app.request('/')).text()).not.toContain('ada@example.invalid');
|
||||||
});
|
});
|
||||||
@@ -639,8 +644,9 @@ describe('contact pages', () => {
|
|||||||
email: 'patrick@example.invalid',
|
email: 'patrick@example.invalid',
|
||||||
phone: '',
|
phone: '',
|
||||||
});
|
});
|
||||||
expect(cleared.status).toBe(303);
|
expect(cleared.status).toBe(400);
|
||||||
expect(db.prepare('SELECT phone FROM contacts WHERE id = ?').get(contactId)).toEqual({ phone: null });
|
expect(await cleared.text()).toContain('Enter a phone number.');
|
||||||
|
expect(db.prepare('SELECT phone FROM contacts WHERE id = ?').get(contactId)).toEqual({ phone: '712-555-0199' });
|
||||||
expect(db.prepare(`SELECT phone AS phone FROM signups WHERE email_norm = 'pat@example.invalid'`).get()).toEqual({
|
expect(db.prepare(`SELECT phone AS phone FROM signups WHERE email_norm = 'pat@example.invalid'`).get()).toEqual({
|
||||||
phone: '712-555-0199',
|
phone: '712-555-0199',
|
||||||
});
|
});
|
||||||
@@ -658,17 +664,17 @@ describe('contact pages', () => {
|
|||||||
expect(db.prepare('SELECT first_name, email, phone FROM contacts WHERE id = ?').get(contactId)).toEqual({
|
expect(db.prepare('SELECT first_name, email, phone FROM contacts WHERE id = ?').get(contactId)).toEqual({
|
||||||
first_name: 'Pat',
|
first_name: 'Pat',
|
||||||
email: 'patrick@example.invalid',
|
email: 'patrick@example.invalid',
|
||||||
phone: null,
|
phone: '712-555-0199',
|
||||||
});
|
});
|
||||||
|
|
||||||
const missing = await postCorrect(app, cookie, 999, {
|
const missing = await postCorrect(app, cookie, 999, {
|
||||||
firstName: 'Pat',
|
firstName: 'Pat',
|
||||||
lastName: 'Review',
|
lastName: 'Review',
|
||||||
email: 'patrick@example.invalid',
|
email: 'patrick@example.invalid',
|
||||||
phone: '',
|
phone: '712-555-0199',
|
||||||
});
|
});
|
||||||
expect(missing.status).toBe(404);
|
expect(missing.status).toBe(404);
|
||||||
expect(count(db, `SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.correct'`)).toBe(3);
|
expect(count(db, `SELECT COUNT(*) AS n FROM audit WHERE action = 'contacts.correct'`)).toBe(2);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -809,7 +815,7 @@ async function postContactShift(
|
|||||||
contactId: number,
|
contactId: number,
|
||||||
shiftId: number,
|
shiftId: number,
|
||||||
html: string,
|
html: string,
|
||||||
fields: { under18?: string; guardianName?: string; guardianEmail?: string; notes?: string },
|
fields: { notes?: string },
|
||||||
) {
|
) {
|
||||||
const csrf = /name="csrf" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
const csrf = /name="csrf" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||||
const formToken = /name="form_token" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
const formToken = /name="form_token" value="([^"]*)"/.exec(html)?.[1] ?? '';
|
||||||
@@ -821,9 +827,6 @@ async function postContactShift(
|
|||||||
form_token: formToken,
|
form_token: formToken,
|
||||||
shift: String(shiftId),
|
shift: String(shiftId),
|
||||||
notes: fields.notes ?? '',
|
notes: fields.notes ?? '',
|
||||||
under18: fields.under18 ?? '',
|
|
||||||
guardianName: fields.guardianName ?? '',
|
|
||||||
guardianEmail: fields.guardianEmail ?? '',
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-16
@@ -36,7 +36,6 @@ afterEach(() => {
|
|||||||
describe('transactional mail', () => {
|
describe('transactional mail', () => {
|
||||||
it('escapes the person\'s name in HTML and keeps the subject on one line', () => {
|
it('escapes the person\'s name in HTML and keeps the subject on one line', () => {
|
||||||
const rendered = renderConfirmation({
|
const rendered = renderConfirmation({
|
||||||
audience: 'volunteer',
|
|
||||||
volunteerName: 'Pat <script>\nReview',
|
volunteerName: 'Pat <script>\nReview',
|
||||||
shift: { role: 'Sorting', eventTitle: 'Weekly pantry', location: 'Sioux Center, Iowa', whenLabel: 'Thursday, October 15, 2026, 9:00 AM to 12:00 PM CDT' },
|
shift: { role: 'Sorting', eventTitle: 'Weekly pantry', location: 'Sioux Center, Iowa', whenLabel: 'Thursday, October 15, 2026, 9:00 AM to 12:00 PM CDT' },
|
||||||
manageUrl: 'http://127.0.0.1:3000/m/token-value-abcdefghijk',
|
manageUrl: 'http://127.0.0.1:3000/m/token-value-abcdefghijk',
|
||||||
@@ -49,22 +48,21 @@ describe('transactional mail', () => {
|
|||||||
expect(rendered.text).toContain('http://127.0.0.1:3000/m/token-value-abcdefghijk');
|
expect(rendered.text).toContain('http://127.0.0.1:3000/m/token-value-abcdefghijk');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('queues one confirmation, a guardian copy when the address differs, and no second copy on replay', async () => {
|
it('queues one confirmation and no second copy on replay', async () => {
|
||||||
const { db, shiftId } = await buildDb();
|
const { db, shiftId } = await buildDb();
|
||||||
const saved = reserveSignup(db, reservation(shiftId, { email: 'minor@example.invalid', isMinor: true, guardianEmail: 'guardian@example.invalid', name: 'Minor Pat' }));
|
const saved = reserveSignup(db, reservation(shiftId, { email: 'pat@example.invalid', name: 'Pat Review' }));
|
||||||
expect(saved.ok).toBe(true);
|
expect(saved.ok).toBe(true);
|
||||||
const rows = db.prepare('SELECT to_email, kind, status FROM outbox ORDER BY id').all();
|
const rows = db.prepare('SELECT to_email, kind, status FROM outbox ORDER BY id').all();
|
||||||
expect(rows).toEqual([
|
expect(rows).toEqual([
|
||||||
{ to_email: 'minor@example.invalid', kind: 'confirmation', status: 'pending' },
|
{ to_email: 'pat@example.invalid', kind: 'confirmation', status: 'pending' },
|
||||||
{ to_email: 'guardian@example.invalid', kind: 'confirmation', status: 'pending' },
|
|
||||||
]);
|
]);
|
||||||
const same = reserveSignup(db, reservation(shiftId, { email: 'minor@example.invalid', isMinor: true, guardianEmail: 'guardian@example.invalid', name: 'Minor Pat', operationId: 'same-operation' }));
|
const same = reserveSignup(db, reservation(shiftId, { email: 'pat@example.invalid', name: 'Pat Review', operationId: 'same-operation' }));
|
||||||
expect(same.ok && same.replay).toBe(true);
|
expect(same.ok && same.replay).toBe(true);
|
||||||
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox').get()).toEqual({ n: 2 });
|
expect(db.prepare('SELECT COUNT(*) AS n FROM outbox').get()).toEqual({ n: 1 });
|
||||||
|
|
||||||
const shared = reserveSignup(db, reservation(shiftId, { email: 'shared@example.invalid', isMinor: true, guardianEmail: 'shared@example.invalid', operationId: 'shared-operation' }));
|
const other = reserveSignup(db, reservation(shiftId, { email: 'other@example.invalid', operationId: 'other-operation' }));
|
||||||
expect(shared.ok).toBe(true);
|
expect(other.ok).toBe(true);
|
||||||
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'shared@example.invalid'").get()).toEqual({ n: 1 });
|
expect(db.prepare("SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'other@example.invalid'").get()).toEqual({ n: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('sends the queued letter once and does not send it again', async () => {
|
it('sends the queued letter once and does not send it again', async () => {
|
||||||
@@ -181,10 +179,8 @@ describe('transactional mail', () => {
|
|||||||
first_name: 'Listed',
|
first_name: 'Listed',
|
||||||
last_name: 'Person',
|
last_name: 'Person',
|
||||||
email: 'listed@example.invalid',
|
email: 'listed@example.invalid',
|
||||||
phone: '',
|
phone: '712-555-0100',
|
||||||
notes: '',
|
notes: '',
|
||||||
guardianName: '',
|
|
||||||
guardianEmail: '',
|
|
||||||
company_website: '',
|
company_website: '',
|
||||||
'cf-turnstile-response': 'widget-token',
|
'cf-turnstile-response': 'widget-token',
|
||||||
});
|
});
|
||||||
@@ -340,9 +336,6 @@ function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): Re
|
|||||||
email: 'pat.review@example.invalid',
|
email: 'pat.review@example.invalid',
|
||||||
phone: null,
|
phone: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
isMinor: false,
|
|
||||||
guardianName: overrides.isMinor ? 'Guardian Pat' : null,
|
|
||||||
guardianEmail: null,
|
|
||||||
operationId: 'same-operation',
|
operationId: 'same-operation',
|
||||||
now: NOW,
|
now: NOW,
|
||||||
mail: MAIL,
|
mail: MAIL,
|
||||||
|
|||||||
@@ -173,10 +173,8 @@ async function postSignup(
|
|||||||
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
|
first_name: fields.name.slice(0, fields.name.indexOf(' ')),
|
||||||
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
|
last_name: fields.name.slice(fields.name.indexOf(' ') + 1),
|
||||||
email: fields.email,
|
email: fields.email,
|
||||||
phone: '',
|
phone: '712-555-0100',
|
||||||
notes: '',
|
notes: '',
|
||||||
guardianName: '',
|
|
||||||
guardianEmail: '',
|
|
||||||
company_website: '',
|
company_website: '',
|
||||||
'cf-turnstile-response': 'widget-token',
|
'cf-turnstile-response': 'widget-token',
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -117,13 +117,13 @@ describe('public pages', () => {
|
|||||||
expect(shiftHtml).toContain('name="last_name"');
|
expect(shiftHtml).toContain('name="last_name"');
|
||||||
expect(shiftHtml).toContain('First name');
|
expect(shiftHtml).toContain('First name');
|
||||||
expect(shiftHtml).toContain('Last name');
|
expect(shiftHtml).toContain('Last name');
|
||||||
expect(shiftHtml).toContain('We will not text you');
|
|
||||||
expect(shiftHtml).toContain('https://challenges.cloudflare.com/turnstile/v0/api.js');
|
expect(shiftHtml).toContain('https://challenges.cloudflare.com/turnstile/v0/api.js');
|
||||||
expect(shiftHtml).toContain('data-under-18');
|
expect(shiftHtml).not.toContain('data-under-18');
|
||||||
expect(shiftHtml).toContain('data-guardian');
|
expect(shiftHtml).not.toContain('data-guardian');
|
||||||
expect(shiftHtml).not.toMatch(/id="signup-under-18"[^>]*\schecked/);
|
expect(shiftHtml).not.toContain('I am under 18');
|
||||||
const css = await (await app.request('/css/app.css')).text();
|
const css = await (await app.request('/css/app.css')).text();
|
||||||
expect(css).toContain('.signup-form:not(:has([data-under-18]:checked)) [data-guardian]');
|
expect(css).not.toContain('data-under-18');
|
||||||
|
expect(css).not.toContain('data-guardian');
|
||||||
expect(shiftHtml).not.toContain('SECRET-SHIFT-NOTE');
|
expect(shiftHtml).not.toContain('SECRET-SHIFT-NOTE');
|
||||||
expect(shiftHtml).not.toContain('Secret Person');
|
expect(shiftHtml).not.toContain('Secret Person');
|
||||||
|
|
||||||
|
|||||||
@@ -245,9 +245,6 @@ function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): Re
|
|||||||
email: 'pat.review@example.invalid',
|
email: 'pat.review@example.invalid',
|
||||||
phone: null,
|
phone: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
isMinor: false,
|
|
||||||
guardianName: null,
|
|
||||||
guardianEmail: null,
|
|
||||||
operationId: 'reminder-operation',
|
operationId: 'reminder-operation',
|
||||||
now: NOW,
|
now: NOW,
|
||||||
mail: MAIL,
|
mail: MAIL,
|
||||||
|
|||||||
+2
-2
@@ -61,9 +61,9 @@ describe('development seed', () => {
|
|||||||
for (const signup of signups) {
|
for (const signup of signups) {
|
||||||
expect(signup.email.endsWith(`@${SEED_EMAIL_DOMAIN}`)).toBe(true);
|
expect(signup.email.endsWith(`@${SEED_EMAIL_DOMAIN}`)).toBe(true);
|
||||||
expect(signup.group_size).toBe(1);
|
expect(signup.group_size).toBe(1);
|
||||||
|
expect(signup.is_minor).toBe(0);
|
||||||
|
expect(signup.guardian_email).toBeNull();
|
||||||
}
|
}
|
||||||
const minor = signups.find((signup) => signup.is_minor === 1);
|
|
||||||
expect(minor?.guardian_email).toBe(`pat.fake@${SEED_EMAIL_DOMAIN}`);
|
|
||||||
expect(signups.some((signup) => signup.status === 'cancelled')).toBe(true);
|
expect(signups.some((signup) => signup.status === 'cancelled')).toBe(true);
|
||||||
expect(db.prepare('SELECT COUNT(*) AS n FROM coordinators').get()).toEqual({ n: 0 });
|
expect(db.prepare('SELECT COUNT(*) AS n FROM coordinators').get()).toEqual({ n: 0 });
|
||||||
expect(() => seedDevelopment(db, config, { today: '2026-10-14' })).toThrow(/already has events/);
|
expect(() => seedDevelopment(db, config, { today: '2026-10-14' })).toThrow(/already has events/);
|
||||||
|
|||||||
+18
-70
@@ -10,7 +10,7 @@ import { createApp } from '../src/app.js';
|
|||||||
import { loadConfig } from '../src/config.js';
|
import { loadConfig } from '../src/config.js';
|
||||||
import { openAppDatabase } from '../src/db.js';
|
import { openAppDatabase } from '../src/db.js';
|
||||||
import { issueFormToken, MIN_FILL_MS } from '../src/form-token.js';
|
import { issueFormToken, MIN_FILL_MS } from '../src/form-token.js';
|
||||||
import { SIGNUP_EMAIL_LIMIT, SIGNUP_GUARDIAN_LIMIT, SIGNUP_IP_LIMIT } from '../src/rate-limit.js';
|
import { SIGNUP_EMAIL_LIMIT, SIGNUP_IP_LIMIT } from '../src/rate-limit.js';
|
||||||
import type { ReserveInput } from '../src/signup.js';
|
import type { ReserveInput } from '../src/signup.js';
|
||||||
import { verifyTurnstile, type TurnstileVerdict } from '../src/turnstile.js';
|
import { verifyTurnstile, type TurnstileVerdict } from '../src/turnstile.js';
|
||||||
import { devEnv } from './env.js';
|
import { devEnv } from './env.js';
|
||||||
@@ -26,7 +26,7 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('capacity-safe signup', () => {
|
describe('capacity-safe signup', () => {
|
||||||
it('requires a first name and a last name', async () => {
|
it('requires a first name, a last name, and a phone number', async () => {
|
||||||
const { app, shiftId } = await buildApp();
|
const { app, shiftId } = await buildApp();
|
||||||
const missingLast = await postSignup(app, shiftId, { firstName: 'Pat', lastName: '', email: 'pat.only@example.invalid' }, { ip: '203.0.113.11' });
|
const missingLast = await postSignup(app, shiftId, { firstName: 'Pat', lastName: '', email: 'pat.only@example.invalid' }, { ip: '203.0.113.11' });
|
||||||
expect(missingLast.status).toBe(400);
|
expect(missingLast.status).toBe(400);
|
||||||
@@ -36,6 +36,14 @@ describe('capacity-safe signup', () => {
|
|||||||
const missingFirst = await postSignup(app, shiftId, { firstName: ' ', lastName: 'Review', email: 'review.only@example.invalid' }, { ip: '203.0.113.12' });
|
const missingFirst = await postSignup(app, shiftId, { firstName: ' ', lastName: 'Review', email: 'review.only@example.invalid' }, { ip: '203.0.113.12' });
|
||||||
expect(missingFirst.status).toBe(400);
|
expect(missingFirst.status).toBe(400);
|
||||||
expect(await missingFirst.text()).toContain('Enter your first name.');
|
expect(await missingFirst.text()).toContain('Enter your first name.');
|
||||||
|
const missingPhone = await postSignup(
|
||||||
|
app,
|
||||||
|
shiftId,
|
||||||
|
{ firstName: 'Pat', lastName: 'Review', email: 'pat.phone@example.invalid', phone: '' },
|
||||||
|
{ ip: '203.0.113.13' },
|
||||||
|
);
|
||||||
|
expect(missingPhone.status).toBe(400);
|
||||||
|
expect(await missingPhone.text()).toContain('Enter your phone number.');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('saves one person, shows a private confirmation link, and does not send mail', async () => {
|
it('saves one person, shows a private confirmation link, and does not send mail', async () => {
|
||||||
@@ -131,39 +139,16 @@ describe('capacity-safe signup', () => {
|
|||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('requires a guardian for a minor and ignores guardian fields for an adult', async () => {
|
it('stores new signups as adults with null guardian fields', async () => {
|
||||||
const { app, shiftId, db } = await buildApp({ capacity: 2 });
|
const { app, shiftId, db } = await buildApp({ capacity: 2 });
|
||||||
const missing = await postSignup(app, shiftId, { under18: true, email: 'minor@example.invalid' }, { ip: '203.0.113.41' });
|
const first = await postSignup(app, shiftId, { email: 'one@example.invalid' }, { ip: '203.0.113.41' });
|
||||||
expect(missing.status).toBe(400);
|
expect(first.status).toBe(303);
|
||||||
const missingHtml = await missing.text();
|
const second = await postSignup(app, shiftId, { email: 'two@example.invalid' }, { ip: '203.0.113.42' });
|
||||||
expect(missingHtml).toContain('Enter the guardian name.');
|
expect(second.status).toBe(303);
|
||||||
expect(missingHtml).toMatch(/id="signup-under-18"[^>]*\schecked/);
|
|
||||||
expect(db.prepare('SELECT COUNT(*) AS n FROM signups').get()).toEqual({ n: 0 });
|
|
||||||
|
|
||||||
const minor = await postSignup(
|
|
||||||
app,
|
|
||||||
shiftId,
|
|
||||||
{
|
|
||||||
name: 'minor pat',
|
|
||||||
email: 'minor@example.invalid',
|
|
||||||
under18: true,
|
|
||||||
guardianName: 'guardian pat',
|
|
||||||
guardianEmail: 'Guardian.Pat@Example.invalid',
|
|
||||||
},
|
|
||||||
{ ip: '203.0.113.42' },
|
|
||||||
);
|
|
||||||
expect(minor.status).toBe(303);
|
|
||||||
const adult = await postSignup(
|
|
||||||
app,
|
|
||||||
shiftId,
|
|
||||||
{ email: 'adult@example.invalid', guardianName: 'Should Not Store', guardianEmail: 'nope@example.invalid' },
|
|
||||||
{ ip: '203.0.113.43' },
|
|
||||||
);
|
|
||||||
expect(adult.status).toBe(303);
|
|
||||||
const stored = db.prepare('SELECT email_norm, is_minor, guardian_name, guardian_email, group_size FROM signups ORDER BY id').all();
|
const stored = db.prepare('SELECT email_norm, is_minor, guardian_name, guardian_email, group_size FROM signups ORDER BY id').all();
|
||||||
expect(stored).toEqual([
|
expect(stored).toEqual([
|
||||||
{ email_norm: 'minor@example.invalid', is_minor: 1, guardian_name: 'Guardian Pat', guardian_email: 'guardian.pat@example.invalid', group_size: 1 },
|
{ email_norm: 'one@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
|
||||||
{ email_norm: 'adult@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
|
{ email_norm: 'two@example.invalid', is_minor: 0, guardian_name: null, guardian_email: null, group_size: 1 },
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -225,34 +210,6 @@ describe('capacity-safe signup', () => {
|
|||||||
expect(JSON.stringify(keys)).not.toContain('198.51.100.10');
|
expect(JSON.stringify(keys)).not.toContain('198.51.100.10');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('limits signups that mail one guardian, even from different volunteer addresses', async () => {
|
|
||||||
const { app, db } = await buildApp({ capacity: 8 });
|
|
||||||
const shiftId = insertExtraShift(db, { capacity: 8 });
|
|
||||||
const minor = (index: number) => ({
|
|
||||||
name: `Minor ${index}`,
|
|
||||||
email: `minor-${index}@example.invalid`,
|
|
||||||
under18: true,
|
|
||||||
guardianName: 'Guardian Pat',
|
|
||||||
guardianEmail: 'target@example.invalid',
|
|
||||||
});
|
|
||||||
for (let index = 0; index < SIGNUP_GUARDIAN_LIMIT; index += 1) {
|
|
||||||
const response = await postSignup(app, shiftId, minor(index), { ip: `198.51.100.${120 + index}` });
|
|
||||||
expect(response.status).toBe(303);
|
|
||||||
}
|
|
||||||
const blocked = await postSignup(app, shiftId, minor(99), { ip: '198.51.100.140' });
|
|
||||||
expect(blocked.status).toBe(429);
|
|
||||||
expect(Number(blocked.headers.get('retry-after'))).toBeGreaterThan(0);
|
|
||||||
expect(JSON.stringify(db.prepare('SELECT key FROM rate_hits').all())).not.toContain('target@example.invalid');
|
|
||||||
|
|
||||||
const sameAddress = await postSignup(
|
|
||||||
app,
|
|
||||||
shiftId,
|
|
||||||
{ name: 'Own Guardian', email: 'family@example.invalid', under18: true, guardianName: 'Parent', guardianEmail: 'family@example.invalid' },
|
|
||||||
{ ip: '198.51.100.141' },
|
|
||||||
);
|
|
||||||
expect(sameAddress.status).toBe(303);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not let a cross-site signup post use up the network allowance', async () => {
|
it('does not let a cross-site signup post use up the network allowance', async () => {
|
||||||
const { app, shiftId } = await buildApp({ capacity: 2 });
|
const { app, shiftId } = await buildApp({ capacity: 2 });
|
||||||
for (let index = 0; index < SIGNUP_IP_LIMIT; index += 1) {
|
for (let index = 0; index < SIGNUP_IP_LIMIT; index += 1) {
|
||||||
@@ -311,9 +268,6 @@ describe('capacity-safe signup', () => {
|
|||||||
email: `person-${index}@example.invalid`,
|
email: `person-${index}@example.invalid`,
|
||||||
phone: null,
|
phone: null,
|
||||||
notes: null,
|
notes: null,
|
||||||
isMinor: false,
|
|
||||||
guardianName: null,
|
|
||||||
guardianEmail: null,
|
|
||||||
operationId: `operation-${index}-abcdef`,
|
operationId: `operation-${index}-abcdef`,
|
||||||
now: NOW,
|
now: NOW,
|
||||||
mail: {
|
mail: {
|
||||||
@@ -421,9 +375,6 @@ async function postSignup(
|
|||||||
email: string;
|
email: string;
|
||||||
phone: string;
|
phone: string;
|
||||||
notes: string;
|
notes: string;
|
||||||
under18: boolean;
|
|
||||||
guardianName: string;
|
|
||||||
guardianEmail: string;
|
|
||||||
company: string;
|
company: string;
|
||||||
}>,
|
}>,
|
||||||
options?: { token?: string; issuedAt?: number; ip?: string; origin?: string; forwardedFor?: string; site?: string },
|
options?: { token?: string; issuedAt?: number; ip?: string; origin?: string; forwardedFor?: string; site?: string },
|
||||||
@@ -441,14 +392,11 @@ async function postSignup(
|
|||||||
first_name: fields.firstName ?? (splitAt === -1 ? postedName : postedName.slice(0, splitAt)),
|
first_name: fields.firstName ?? (splitAt === -1 ? postedName : postedName.slice(0, splitAt)),
|
||||||
last_name: fields.lastName ?? (splitAt === -1 ? '' : postedName.slice(splitAt + 1).trim()),
|
last_name: fields.lastName ?? (splitAt === -1 ? '' : postedName.slice(splitAt + 1).trim()),
|
||||||
email: fields.email ?? 'pat.review@example.invalid',
|
email: fields.email ?? 'pat.review@example.invalid',
|
||||||
phone: fields.phone ?? '',
|
phone: fields.phone ?? '712-555-0100',
|
||||||
notes: fields.notes ?? '',
|
notes: fields.notes ?? '',
|
||||||
guardianName: fields.guardianName ?? '',
|
|
||||||
guardianEmail: fields.guardianEmail ?? '',
|
|
||||||
company_website: fields.company ?? '',
|
company_website: fields.company ?? '',
|
||||||
'cf-turnstile-response': 'widget-token',
|
'cf-turnstile-response': 'widget-token',
|
||||||
});
|
});
|
||||||
if (fields.under18) body.set('under18', 'yes');
|
|
||||||
return app.request(`/s/${shiftId}`, {
|
return app.request(`/s/${shiftId}`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
|
|||||||
@@ -24,8 +24,7 @@ afterEach(() => {
|
|||||||
describe('public switch limits', () => {
|
describe('public switch limits', () => {
|
||||||
it('stops the repeated-switch mail attack despite new tokens, ids, IPs, and a reopened database', async () => {
|
it('stops the repeated-switch mail attack despite new tokens, ids, IPs, and a reopened database', async () => {
|
||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
// A shared volunteer/guardian mailbox must count only once per switch.
|
let link = f.signup('target@example.invalid');
|
||||||
let link = f.signup('target@example.invalid', 'target@example.invalid');
|
|
||||||
let app = f.app();
|
let app = f.app();
|
||||||
let accepted = 0;
|
let accepted = 0;
|
||||||
const mailer = { send: async () => { accepted++; return { result: 'sent' as const, providerId: 'mock' }; } };
|
const mailer = { send: async () => { accepted++; return { result: 'sent' as const, providerId: 'mock' }; } };
|
||||||
@@ -59,21 +58,19 @@ describe('public switch limits', () => {
|
|||||||
expect((await switchTo(tomorrow, link, f.shifts[0]!)).status).toBe(303);
|
expect((await switchTo(tomorrow, link, f.shifts[0]!)).status).toBe(303);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('shares guardian limits across children, IPs, and recipient roles without charging blocked co-recipients', async () => {
|
it('shares recipient limits across different people at the same email without charging blocked co-recipients', async () => {
|
||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
const app = f.app();
|
const app = f.app();
|
||||||
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
|
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
|
||||||
const link = f.signup(`child${i}@example.invalid`, 'guardian@example.invalid');
|
const link = f.signup('shared@example.invalid', `Person ${i}`);
|
||||||
expect((await switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`)).status).toBe(303);
|
expect((await switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`)).status).toBe(303);
|
||||||
}
|
}
|
||||||
const blocked = f.signup('new-child@example.invalid', 'guardian@example.invalid');
|
const blocked = f.signup('shared@example.invalid', 'Blocked Person');
|
||||||
const before = records(f.db);
|
const before = records(f.db);
|
||||||
expect((await switchTo(app, blocked, f.shifts[1]!, '203.0.113.99')).status).toBe(429);
|
expect((await switchTo(app, blocked, f.shifts[1]!, '203.0.113.99')).status).toBe(429);
|
||||||
expect(records(f.db)).toEqual(before);
|
expect(records(f.db)).toEqual(before);
|
||||||
const reversed = f.signup('guardian@example.invalid', 'other@example.invalid');
|
// Rejection must not spend this person's allowance on an otherwise valid link.
|
||||||
expect((await switchTo(app, reversed, f.shifts[1]!, '203.0.113.98')).status).toBe(429);
|
let ownLink = f.signup('other@example.invalid', 'Other Person');
|
||||||
// Rejection must not spend this child's allowance on otherwise valid links.
|
|
||||||
let ownLink = f.signup('new-child@example.invalid', null, 'Another person');
|
|
||||||
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
|
for (let i = 0; i < SWITCH_RECIPIENT_LIMIT; i++) {
|
||||||
const response = await switchTo(app, ownLink, f.shifts[(i + 1) % 2]!, '203.0.113.97');
|
const response = await switchTo(app, ownLink, f.shifts[(i + 1) % 2]!, '203.0.113.97');
|
||||||
expect(response.status).toBe(303);
|
expect(response.status).toBe(303);
|
||||||
@@ -117,7 +114,7 @@ describe('public switch limits', () => {
|
|||||||
const f = await fixture();
|
const f = await fixture();
|
||||||
const app = f.app();
|
const app = f.app();
|
||||||
const requests = Array.from({ length: SWITCH_RECIPIENT_LIMIT + 1 }, (_, i) => {
|
const requests = Array.from({ length: SWITCH_RECIPIENT_LIMIT + 1 }, (_, i) => {
|
||||||
const link = f.signup(`parallel${i}@example.invalid`, 'shared@example.invalid');
|
const link = f.signup('shared@example.invalid', `Parallel ${i}`);
|
||||||
return switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`);
|
return switchTo(app, link, f.shifts[1]!, `203.0.113.${i + 1}`);
|
||||||
});
|
});
|
||||||
const responses = await Promise.all(requests);
|
const responses = await Promise.all(requests);
|
||||||
@@ -169,10 +166,9 @@ async function fixture() {
|
|||||||
return {
|
return {
|
||||||
db, config, shifts,
|
db, config, shifts,
|
||||||
app: (now = NOW) => createApp(config, db, { now, clientIp: (c) => c.req.header('x-test-ip') ?? null }),
|
app: (now = NOW) => createApp(config, db, { now, clientIp: (c) => c.req.header('x-test-ip') ?? null }),
|
||||||
signup: (email: string, guardianEmail: string | null = null, name = 'Test Person') => {
|
signup: (email: string, name = 'Test Person') => {
|
||||||
const result = reserveSignup(db, {
|
const result = reserveSignup(db, {
|
||||||
shiftId: shifts[0]!, name, email, guardianEmail, isMinor: guardianEmail !== null,
|
shiftId: shifts[0]!, name, email, phone: null, notes: null,
|
||||||
guardianName: guardianEmail ? 'Guardian' : null, phone: null, notes: null,
|
|
||||||
operationId: randomBytes(16).toString('hex'), now: NOW, mail,
|
operationId: randomBytes(16).toString('hex'), now: NOW, mail,
|
||||||
});
|
});
|
||||||
if (!result.ok || !result.manageToken) throw new Error('Fixture signup failed');
|
if (!result.ok || !result.manageToken) throw new Error('Fixture signup failed');
|
||||||
|
|||||||
Reference in new issue
Block a user