feat: implement coordinator notifications for signup changes and cancellations
Added functionality to send notifications to active coordinators when a volunteer signs up, cancels, or changes their signup details. This includes updates to the mail queue and templates to handle coordinator notices, ensuring they receive relevant information without including private signup links. Enhanced the database schema to support these notifications and updated tests to verify the new behavior.
This commit is contained in:
1 parent
208f08753e
commit
e9bc80cd95
12 files changed
+668
-10
No files matched your search
@@ -76,6 +76,8 @@ An open shift has a signup form. It asks for one person. Another person can use
|
|||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
Each active coordinator gets an email when someone signs up, cancels, or changes a signup. Signing up includes a walk-in. A change is a switch, a move, or a new time, role, or place. Cancelling a shift sends one message for each person who was signed up. The message names the person, the email address, the phone number, and the shift, and it links to that shift. It does not include the private signup link. The same signup does not send a second copy of the same notice. A coordinator who has been removed, or whose sign-in address was replaced, does not receive a notice that is still waiting. Mail already accepted cannot be recalled.
|
||||||
|
|
||||||
Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. More administrators are added from **Administrators** after someone is signed in. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password.
|
Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. More administrators are added from **Administrators** after someone is signed in. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password.
|
||||||
|
|
||||||
After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling keeps the roster. It does not delete the shift or the signup. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued.
|
After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling keeps the roster. It does not delete the shift or the signup. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued.
|
||||||
@@ -104,7 +106,7 @@ A reminder is queued at each saved time before a confirmed signup, while the shi
|
|||||||
|
|
||||||
**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.
|
||||||
|
|
||||||
**Administrators**, on the coordinator page, lists who can sign in. **Add an administrator** saves a name and email. It does not send email. That person requests a sign-in link at `/login`. Saving an address that was removed earlier gives that person access again and updates the name. **Remove** takes away access, signs that person out, and stops unused sign-in links. It does not send email. The last administrator cannot be removed. Any administrator can add or remove the others, including themselves when someone else still has access.
|
**Administrators**, on the coordinator page, lists who can sign in. **Add an administrator** saves a name and email. It does not send email. That person requests a sign-in link at `/login`. Saving an address that was removed earlier gives that person access again and updates the name. **Remove** takes away access, signs that person out, and stops unused sign-in links. It does not send email. A roster notice that has not been sent yet is not sent to that address. The last administrator cannot be removed. Any administrator can add or remove the others, including themselves when someone else still has access.
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- foreign-keys: off
|
||||||
|
-- Coordinator roster notices use outbox kind notice.
|
||||||
|
-- Rebuilding outbox changes its CHECK list. reminders_sent references it, so foreign keys are off for this file.
|
||||||
|
|
||||||
|
CREATE TABLE outbox_next (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
dedupe_key TEXT NOT NULL UNIQUE,
|
||||||
|
signup_id INTEGER NULL REFERENCES signups (id) ON DELETE NO ACTION,
|
||||||
|
shift_id INTEGER NULL REFERENCES shifts (id) ON DELETE NO ACTION,
|
||||||
|
-- confirmation, changed, cancelled, reminder, magic_link, manage_recovery, notice
|
||||||
|
kind TEXT NOT NULL CHECK (
|
||||||
|
kind IN ('confirmation', 'changed', 'cancelled', 'reminder', 'magic_link', 'manage_recovery', 'notice')
|
||||||
|
),
|
||||||
|
-- Pending mail can contain raw manage or login links. Treat the row as sensitive.
|
||||||
|
to_email TEXT NOT NULL,
|
||||||
|
subject TEXT NOT NULL,
|
||||||
|
body_text TEXT NOT NULL,
|
||||||
|
body_html TEXT NOT NULL,
|
||||||
|
headers_json TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(headers_json)),
|
||||||
|
send_after TEXT NOT NULL CHECK (
|
||||||
|
send_after GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
),
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
|
||||||
|
status TEXT NOT NULL CHECK (
|
||||||
|
status IN ('pending', 'sending', 'sent', 'failed', 'cancelled', 'delivery_unknown')
|
||||||
|
),
|
||||||
|
provider_id TEXT NULL,
|
||||||
|
last_error TEXT NULL,
|
||||||
|
created_at TEXT NOT NULL CHECK (
|
||||||
|
created_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
),
|
||||||
|
claimed_at TEXT NULL CHECK (
|
||||||
|
claimed_at IS NULL
|
||||||
|
OR claimed_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
),
|
||||||
|
lease_expires_at TEXT NULL CHECK (
|
||||||
|
lease_expires_at IS NULL
|
||||||
|
OR lease_expires_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
),
|
||||||
|
-- sent_at means the provider accepted the message, not that the person received it.
|
||||||
|
sent_at TEXT NULL CHECK (
|
||||||
|
sent_at IS NULL
|
||||||
|
OR sent_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
),
|
||||||
|
delivery_unknown_at TEXT NULL CHECK (
|
||||||
|
delivery_unknown_at IS NULL
|
||||||
|
OR delivery_unknown_at GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]Z'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
INSERT INTO outbox_next (
|
||||||
|
id, dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||||
|
headers_json, send_after, attempts, status, provider_id, last_error, created_at,
|
||||||
|
claimed_at, lease_expires_at, sent_at, delivery_unknown_at
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
id, dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||||
|
headers_json, send_after, attempts, status, provider_id, last_error, created_at,
|
||||||
|
claimed_at, lease_expires_at, sent_at, delivery_unknown_at
|
||||||
|
FROM outbox;
|
||||||
|
|
||||||
|
DROP TABLE outbox;
|
||||||
|
|
||||||
|
ALTER TABLE outbox_next RENAME TO outbox;
|
||||||
|
|
||||||
|
CREATE INDEX outbox_by_status_send_after ON outbox (status, send_after);
|
||||||
+40
-2
@@ -3,7 +3,7 @@ import { Temporal } from '@js-temporal/polyfill';
|
|||||||
import type Database from 'better-sqlite3';
|
import type Database from 'better-sqlite3';
|
||||||
import type { EventInput, ShiftInput, TemplateInput } from './forms.js';
|
import type { EventInput, ShiftInput, TemplateInput } from './forms.js';
|
||||||
import { writeAudit } from '../auth/audit.js';
|
import { writeAudit } from '../auth/audit.js';
|
||||||
import { cancelPendingConfirmations, cancelPendingReminders, queueCancellation, queueChanged } from '../mail/queue.js';
|
import { cancelPendingConfirmations, cancelPendingReminders, queueCancellation, queueChanged, queueCoordinatorNotices } from '../mail/queue.js';
|
||||||
import type { MailShift } from '../mail/templates.js';
|
import type { MailShift } from '../mail/templates.js';
|
||||||
import type { MailIdentity } from '../mail/types.js';
|
import type { MailIdentity } from '../mail/types.js';
|
||||||
import { confirmedPersonOnShift, confirmedPersonShiftIds, reserveSignup, type ReserveInput, type ReserveResult } from '../signup.js';
|
import { confirmedPersonOnShift, confirmedPersonShiftIds, reserveSignup, type ReserveInput, type ReserveResult } from '../signup.js';
|
||||||
@@ -1265,6 +1265,20 @@ function relocate(
|
|||||||
},
|
},
|
||||||
options.audience === 'volunteer' ? 'switch' : 'move',
|
options.audience === 'volunteer' ? 'switch' : 'move',
|
||||||
);
|
);
|
||||||
|
const previous = mailShift(db, source.shift_id);
|
||||||
|
queueCoordinatorNotices(db, {
|
||||||
|
action: options.audience === 'volunteer' ? 'switch' : 'move',
|
||||||
|
signupId: newSignupId,
|
||||||
|
shiftId: destination.id,
|
||||||
|
shiftVersion: shift.version,
|
||||||
|
volunteerName: source.name,
|
||||||
|
volunteerEmail: source.email_norm,
|
||||||
|
groupSize,
|
||||||
|
shift: shift.facts,
|
||||||
|
fromShift: previous?.facts,
|
||||||
|
mail,
|
||||||
|
now,
|
||||||
|
});
|
||||||
writeAudit(db, options.coordinatorId, options.action, {
|
writeAudit(db, options.coordinatorId, options.action, {
|
||||||
signupId: source.id,
|
signupId: source.id,
|
||||||
fromShiftId: source.shift_id,
|
fromShiftId: source.shift_id,
|
||||||
@@ -1418,6 +1432,18 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
|
|||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
});
|
});
|
||||||
|
queueCoordinatorNotices(db, {
|
||||||
|
action: 'change',
|
||||||
|
signupId: person.id,
|
||||||
|
shiftId: person.shift_id,
|
||||||
|
shiftVersion: shift.version,
|
||||||
|
volunteerName: person.name,
|
||||||
|
volunteerEmail: person.email_norm,
|
||||||
|
groupSize: Number(person.group_size),
|
||||||
|
shift: shift.facts,
|
||||||
|
mail,
|
||||||
|
now,
|
||||||
|
});
|
||||||
mailed += 1;
|
mailed += 1;
|
||||||
}
|
}
|
||||||
return mailed;
|
return mailed;
|
||||||
@@ -1465,6 +1491,18 @@ function cancelConfirmedPerson(db: Database.Database, person: PersonRow, now: st
|
|||||||
now,
|
now,
|
||||||
linkNote: REPLACED_LINK,
|
linkNote: REPLACED_LINK,
|
||||||
});
|
});
|
||||||
|
queueCoordinatorNotices(db, {
|
||||||
|
action: 'cancel',
|
||||||
|
signupId: person.id,
|
||||||
|
shiftId: person.shift_id,
|
||||||
|
shiftVersion: shift.version,
|
||||||
|
volunteerName: person.name,
|
||||||
|
volunteerEmail: person.email_norm,
|
||||||
|
groupSize: Number(person.group_size),
|
||||||
|
shift: shift.facts,
|
||||||
|
mail,
|
||||||
|
now,
|
||||||
|
});
|
||||||
return issued.token;
|
return issued.token;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1524,7 +1562,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, shift_id, status
|
`SELECT id, name, email_norm, shift_id, status, group_size
|
||||||
FROM signups
|
FROM signups
|
||||||
WHERE id = ? AND anonymized_at IS NULL`,
|
WHERE id = ? AND anonymized_at IS NULL`,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -92,6 +92,11 @@ export function deactivateAdmin(
|
|||||||
SET status = 'cancelled', last_error = ?
|
SET status = 'cancelled', last_error = ?
|
||||||
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
|
WHERE kind = 'magic_link' AND status = 'pending' AND to_email = ?`,
|
||||||
).run('An administrator removed this sign-in link.', admin.email);
|
).run('An administrator removed this sign-in link.', admin.email);
|
||||||
|
db.prepare(
|
||||||
|
`UPDATE outbox
|
||||||
|
SET status = 'cancelled', last_error = ?
|
||||||
|
WHERE kind = 'notice' AND status = 'pending' AND to_email = ?`,
|
||||||
|
).run('That coordinator no longer has access.', admin.email);
|
||||||
writeAudit(db, actorId, 'admins.remove', { coordinatorId: id }, now);
|
writeAudit(db, actorId, 'admins.remove', { coordinatorId: id }, now);
|
||||||
return { ok: true as const };
|
return { ok: true as const };
|
||||||
}).immediate();
|
}).immediate();
|
||||||
|
|||||||
@@ -19,6 +19,11 @@ export function recoverCoordinator(
|
|||||||
const taken = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(next);
|
const taken = db.prepare('SELECT id AS id FROM coordinators WHERE email = ?').get(next);
|
||||||
if (taken) throw new Error('Another coordinator already uses the new address.');
|
if (taken) throw new Error('Another coordinator already uses the new address.');
|
||||||
db.prepare('UPDATE coordinators SET email = ? WHERE id = ?').run(next, row.id);
|
db.prepare('UPDATE coordinators SET email = ? WHERE id = ?').run(next, row.id);
|
||||||
|
db.prepare(
|
||||||
|
`UPDATE outbox
|
||||||
|
SET status = 'cancelled', last_error = ?
|
||||||
|
WHERE kind = 'notice' AND status = 'pending' AND to_email = ?`,
|
||||||
|
).run('That coordinator no longer has access.', email);
|
||||||
}
|
}
|
||||||
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(row.id);
|
db.prepare('DELETE FROM sessions WHERE coordinator_id = ?').run(row.id);
|
||||||
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, row.id);
|
db.prepare('UPDATE login_tokens SET used_at = ? WHERE coordinator_id = ? AND used_at IS NULL').run(input.now, row.id);
|
||||||
|
|||||||
+14
-2
@@ -22,7 +22,7 @@ type ClaimedRow = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Claims due confirmation, change, cancellation, reminder, and sign-in mail, then sends outside the database transaction.
|
* Claims due confirmation, change, cancellation, reminder, sign-in, and coordinator notice mail, then sends outside the database transaction.
|
||||||
* An expired sending lease becomes delivery_unknown and is not sent again.
|
* An expired sending lease becomes delivery_unknown and is not sent again.
|
||||||
* sent_at means the provider accepted the message.
|
* sent_at means the provider accepted the message.
|
||||||
*/
|
*/
|
||||||
@@ -72,7 +72,7 @@ function claimNext(db: Database.Database, now: string): ClaimedRow | null {
|
|||||||
.prepare(
|
.prepare(
|
||||||
`SELECT id AS id
|
`SELECT id AS id
|
||||||
FROM outbox
|
FROM outbox
|
||||||
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link')
|
WHERE status = 'pending' AND send_after <= ? AND kind IN ('confirmation', 'cancelled', 'changed', 'reminder', 'magic_link', 'notice')
|
||||||
ORDER BY id
|
ORDER BY id
|
||||||
LIMIT 1`,
|
LIMIT 1`,
|
||||||
)
|
)
|
||||||
@@ -97,6 +97,7 @@ function claimNext(db: Database.Database, now: string): ClaimedRow | null {
|
|||||||
|
|
||||||
function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||||
if (row.kind === 'magic_link') return magicLinkReason(db, row, now);
|
if (row.kind === 'magic_link') return magicLinkReason(db, row, now);
|
||||||
|
if (row.kind === 'notice') return noticeReason(db, row);
|
||||||
if (row.signup_id === null) return 'The signup is no longer available.';
|
if (row.signup_id === null) return 'The signup is no longer available.';
|
||||||
const signup = db
|
const signup = db
|
||||||
.prepare(
|
.prepare(
|
||||||
@@ -134,6 +135,17 @@ function obsoleteReason(db: Database.Database, row: ClaimedRow, now: string): st
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function noticeReason(db: Database.Database, row: ClaimedRow): string | null {
|
||||||
|
if (row.signup_id === null) return 'The signup is no longer available.';
|
||||||
|
const signup = db.prepare('SELECT anonymized_at AS anonymized_at FROM signups WHERE id = ?').get(row.signup_id) as
|
||||||
|
| { anonymized_at: string | null }
|
||||||
|
| undefined;
|
||||||
|
if (!signup || signup.anonymized_at) return 'The signup is no longer available.';
|
||||||
|
const coordinator = db.prepare('SELECT id AS id FROM coordinators WHERE email = ? AND active = 1').get(row.to_email);
|
||||||
|
if (!coordinator) return 'That coordinator no longer has access.';
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function magicLinkReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
function magicLinkReason(db: Database.Database, row: ClaimedRow, now: string): string | null {
|
||||||
const match = /^magic_link:([a-f0-9]{64})$/.exec(row.dedupe_key);
|
const match = /^magic_link:([a-f0-9]{64})$/.exec(row.dedupe_key);
|
||||||
const hash = match?.[1];
|
const hash = match?.[1];
|
||||||
|
|||||||
+79
-1
@@ -1,6 +1,16 @@
|
|||||||
import type Database from 'better-sqlite3';
|
import type Database from 'better-sqlite3';
|
||||||
import { absoluteUrl } from '../url.js';
|
import { absoluteUrl } from '../url.js';
|
||||||
import { renderCancellation, renderChanged, renderConfirmation, renderMagicLink, renderMoved, renderSwitched, type MailShift } from './templates.js';
|
import {
|
||||||
|
renderCancellation,
|
||||||
|
renderChanged,
|
||||||
|
renderConfirmation,
|
||||||
|
renderCoordinatorNotice,
|
||||||
|
renderMagicLink,
|
||||||
|
renderMoved,
|
||||||
|
renderSwitched,
|
||||||
|
type CoordinatorNoticeAction,
|
||||||
|
type MailShift,
|
||||||
|
} from './templates.js';
|
||||||
import type { MailIdentity } from './types.js';
|
import type { MailIdentity } from './types.js';
|
||||||
|
|
||||||
export type QueuedSignup = {
|
export type QueuedSignup = {
|
||||||
@@ -54,6 +64,74 @@ export function queueChanged(db: Database.Database, input: QueuedSignup, reason:
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One roster notice per active coordinator.
|
||||||
|
* The private signup link is not included. The same signup and change does not add a second row.
|
||||||
|
*/
|
||||||
|
export function queueCoordinatorNotices(
|
||||||
|
db: Database.Database,
|
||||||
|
input: {
|
||||||
|
action: CoordinatorNoticeAction;
|
||||||
|
signupId: number;
|
||||||
|
shiftId: number;
|
||||||
|
shiftVersion: number;
|
||||||
|
volunteerName: string;
|
||||||
|
volunteerEmail: string;
|
||||||
|
groupSize?: number;
|
||||||
|
shift: MailShift;
|
||||||
|
fromShift?: MailShift;
|
||||||
|
mail: MailIdentity;
|
||||||
|
now: string;
|
||||||
|
},
|
||||||
|
): void {
|
||||||
|
const coordinators = db
|
||||||
|
.prepare(
|
||||||
|
`SELECT name AS name, email AS email
|
||||||
|
FROM coordinators
|
||||||
|
WHERE active = 1
|
||||||
|
ORDER BY id`,
|
||||||
|
)
|
||||||
|
.all() as { name: string; email: string }[];
|
||||||
|
if (coordinators.length === 0) return;
|
||||||
|
const phoneRow = db.prepare('SELECT phone AS phone FROM signups WHERE id = ?').get(input.signupId) as
|
||||||
|
| { phone: string | null }
|
||||||
|
| undefined;
|
||||||
|
const rosterUrl = absoluteUrl(input.mail, `/admin/shifts/${input.shiftId}`);
|
||||||
|
const insert = db.prepare(
|
||||||
|
`INSERT INTO outbox (
|
||||||
|
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html,
|
||||||
|
headers_json, send_after, attempts, status, created_at
|
||||||
|
) VALUES (?, ?, ?, 'notice', ?, ?, ?, ?, ?, ?, 0, 'pending', ?)
|
||||||
|
ON CONFLICT (dedupe_key) DO NOTHING`,
|
||||||
|
);
|
||||||
|
for (const coordinator of coordinators) {
|
||||||
|
const rendered = renderCoordinatorNotice({
|
||||||
|
coordinatorName: coordinator.name,
|
||||||
|
volunteerName: input.volunteerName,
|
||||||
|
volunteerEmail: input.volunteerEmail,
|
||||||
|
phone: phoneRow?.phone ?? null,
|
||||||
|
groupSize: input.groupSize,
|
||||||
|
action: input.action,
|
||||||
|
shift: input.shift,
|
||||||
|
fromShift: input.fromShift,
|
||||||
|
rosterUrl,
|
||||||
|
replyTo: input.mail.replyTo,
|
||||||
|
});
|
||||||
|
insert.run(
|
||||||
|
`notice:${input.action}:v${input.shiftVersion}:${input.signupId}:${coordinator.email}`,
|
||||||
|
input.signupId,
|
||||||
|
input.shiftId,
|
||||||
|
coordinator.email,
|
||||||
|
rendered.subject,
|
||||||
|
rendered.text,
|
||||||
|
rendered.html,
|
||||||
|
JSON.stringify({ From: input.mail.from, 'Reply-To': input.mail.replyTo }),
|
||||||
|
input.now,
|
||||||
|
input.now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function queueMagicLink(
|
export function queueMagicLink(
|
||||||
db: Database.Database,
|
db: Database.Database,
|
||||||
input: { email: string; token: string; tokenHash: string; mail: MailIdentity; now: string },
|
input: { email: string; token: string; tokenHash: string; mail: MailIdentity; now: string },
|
||||||
|
|||||||
@@ -165,6 +165,66 @@ export function renderReminder(input: {
|
|||||||
return { subject, text: lines.join('\n'), html };
|
return { subject, text: lines.join('\n'), html };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type CoordinatorNoticeAction = 'signup' | 'cancel' | 'switch' | 'move' | 'change';
|
||||||
|
|
||||||
|
/** A roster notice for coordinators. It names the person and links to the shift. It does not include the private signup link. */
|
||||||
|
export function renderCoordinatorNotice(input: {
|
||||||
|
coordinatorName: string;
|
||||||
|
volunteerName: string;
|
||||||
|
volunteerEmail: string;
|
||||||
|
phone: string | null;
|
||||||
|
groupSize?: number;
|
||||||
|
action: CoordinatorNoticeAction;
|
||||||
|
shift: MailShift;
|
||||||
|
fromShift?: MailShift;
|
||||||
|
rosterUrl: string;
|
||||||
|
replyTo: string;
|
||||||
|
}): RenderedMail {
|
||||||
|
const copy = noticeCopy(input);
|
||||||
|
const greeting = `Hello ${singleLine(input.coordinatorName)},`;
|
||||||
|
const phone = input.phone ? singleLine(input.phone) : '';
|
||||||
|
const contact = [singleLine(input.volunteerName), singleLine(input.volunteerEmail), ...(phone ? [phone] : [])];
|
||||||
|
const when = input.shift.whenLabel;
|
||||||
|
const place = input.shift.location.trim();
|
||||||
|
const lines = [
|
||||||
|
greeting,
|
||||||
|
'',
|
||||||
|
copy.hello,
|
||||||
|
'',
|
||||||
|
...contact,
|
||||||
|
'',
|
||||||
|
input.shift.eventTitle,
|
||||||
|
when,
|
||||||
|
...(place ? [place] : []),
|
||||||
|
'',
|
||||||
|
'Open this shift:',
|
||||||
|
input.rosterUrl,
|
||||||
|
'',
|
||||||
|
'That page lists the roster. Sign in if you are not already.',
|
||||||
|
`Replies go to ${input.replyTo}.`,
|
||||||
|
'',
|
||||||
|
'Hope Food Pantry',
|
||||||
|
];
|
||||||
|
const htmlPlace = place ? `<br>${escapeHtml(place)}` : '';
|
||||||
|
const html = `<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>${escapeHtml(copy.subject)}</title>
|
||||||
|
</head>
|
||||||
|
<body style="margin:0;padding:24px;background:#f4fafd;color:#222;font-family:sans-serif;line-height:1.5">
|
||||||
|
<p>${escapeHtml(greeting)}</p>
|
||||||
|
<p>${escapeHtml(copy.hello)}</p>
|
||||||
|
<p>${contact.map((line) => escapeHtml(line)).join('<br>')}</p>
|
||||||
|
<p>${escapeHtml(input.shift.eventTitle)}<br>${escapeHtml(when)}${htmlPlace}</p>
|
||||||
|
<p><a href="${escapeHtml(input.rosterUrl)}" style="color:#222">Open this shift</a></p>
|
||||||
|
<p>That page lists the roster. Sign in if you are not already. Replies go to ${escapeHtml(input.replyTo)}.</p>
|
||||||
|
<p>Hope Food Pantry</p>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
return { subject: copy.subject, text: lines.join('\n'), html };
|
||||||
|
}
|
||||||
|
|
||||||
export function renderMagicLink(input: { signInUrl: string; replyTo: string }): RenderedMail {
|
export function renderMagicLink(input: { signInUrl: string; replyTo: string }): RenderedMail {
|
||||||
const subject = 'Sign in to Hope Volunteer';
|
const subject = 'Sign in to Hope Volunteer';
|
||||||
const hello = 'Use this link to sign in. It expires in 15 minutes and works once.';
|
const hello = 'Use this link to sign in. It expires in 15 minutes and works once.';
|
||||||
@@ -187,6 +247,44 @@ export function renderMagicLink(input: { signInUrl: string; replyTo: string }):
|
|||||||
return { subject, text, html };
|
return { subject, text, html };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function noticeCopy(input: {
|
||||||
|
volunteerName: string;
|
||||||
|
groupSize?: number;
|
||||||
|
action: CoordinatorNoticeAction;
|
||||||
|
shift: MailShift;
|
||||||
|
fromShift?: MailShift;
|
||||||
|
}): { subject: string; hello: string } {
|
||||||
|
const name = singleLine(input.volunteerName);
|
||||||
|
const role = singleLine(input.shift.role);
|
||||||
|
const party = partyNote(input.groupSize);
|
||||||
|
const from = input.fromShift
|
||||||
|
? ` from ${singleLine(input.fromShift.role)} (${singleLine(input.fromShift.whenLabel)})`
|
||||||
|
: '';
|
||||||
|
if (input.action === 'signup') {
|
||||||
|
return { subject: `${name} signed up for ${role}`, hello: `${name} signed up for ${role}.${party}` };
|
||||||
|
}
|
||||||
|
if (input.action === 'cancel') {
|
||||||
|
const spots =
|
||||||
|
input.groupSize && input.groupSize > 1
|
||||||
|
? `The ${input.groupSize} spots this signup held are open for someone else.`
|
||||||
|
: 'The spot is open for someone else.';
|
||||||
|
return {
|
||||||
|
subject: `${name}'s signup for ${role} was cancelled`,
|
||||||
|
hello: `${name}'s signup for ${role} is cancelled. ${spots}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (input.action === 'switch') {
|
||||||
|
return { subject: `${name} switched to ${role}`, hello: `${name} switched${from} to ${role}.${party}` };
|
||||||
|
}
|
||||||
|
if (input.action === 'move') {
|
||||||
|
return { subject: `${name} was moved to ${role}`, hello: `${name} was moved${from} to ${role}.${party}` };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
subject: `${name}'s ${role} shift changed`,
|
||||||
|
hello: `The time or place for ${name}'s ${role} shift has changed.${party}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function partyNote(groupSize: number | undefined): string {
|
function partyNote(groupSize: number | undefined): string {
|
||||||
if (!groupSize || groupSize <= 1) return '';
|
if (!groupSize || groupSize <= 1) return '';
|
||||||
return ` This signup holds ${groupSize} spots.`;
|
return ` This signup holds ${groupSize} spots.`;
|
||||||
|
|||||||
+28
-3
@@ -3,7 +3,7 @@ import { Temporal } from '@js-temporal/polyfill';
|
|||||||
import type Database from 'better-sqlite3';
|
import type Database from 'better-sqlite3';
|
||||||
import { rememberSignupContact } from './contacts.js';
|
import { rememberSignupContact } from './contacts.js';
|
||||||
import { normalizeEmail } from './email.js';
|
import { normalizeEmail } from './email.js';
|
||||||
import { queueCancellation, queueConfirmation, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
|
import { queueCancellation, queueConfirmation, queueCoordinatorNotices, cancelPendingConfirmations, cancelPendingReminders } from './mail/queue.js';
|
||||||
import type { MailIdentity } from './mail/types.js';
|
import type { MailIdentity } from './mail/types.js';
|
||||||
import { MAX_PARTY_SIZE } from './signup-form.js';
|
import { MAX_PARTY_SIZE } from './signup-form.js';
|
||||||
import { isWithinSignupWindow } from './signup-window.js';
|
import { isWithinSignupWindow } from './signup-window.js';
|
||||||
@@ -229,15 +229,28 @@ function placeReservation(db: Database.Database, input: ReserveInput, emailNorm:
|
|||||||
operationKey,
|
operationKey,
|
||||||
);
|
);
|
||||||
const signupId = Number(inserted.lastInsertRowid);
|
const signupId = Number(inserted.lastInsertRowid);
|
||||||
|
const facts = shiftFacts(shift);
|
||||||
queueConfirmation(db, {
|
queueConfirmation(db, {
|
||||||
signupId,
|
signupId,
|
||||||
shiftId: input.shiftId,
|
shiftId: input.shiftId,
|
||||||
shiftVersion: shift.version,
|
shiftVersion: facts.version,
|
||||||
token: manageToken,
|
token: manageToken,
|
||||||
volunteerName: input.name,
|
volunteerName: input.name,
|
||||||
volunteerEmail: emailNorm,
|
volunteerEmail: emailNorm,
|
||||||
groupSize,
|
groupSize,
|
||||||
shift: shiftFacts(shift).facts,
|
shift: facts.facts,
|
||||||
|
mail: input.mail,
|
||||||
|
now: input.now,
|
||||||
|
});
|
||||||
|
queueCoordinatorNotices(db, {
|
||||||
|
action: 'signup',
|
||||||
|
signupId,
|
||||||
|
shiftId: input.shiftId,
|
||||||
|
shiftVersion: facts.version,
|
||||||
|
volunteerName: input.name,
|
||||||
|
volunteerEmail: emailNorm,
|
||||||
|
groupSize,
|
||||||
|
shift: facts.facts,
|
||||||
mail: input.mail,
|
mail: input.mail,
|
||||||
now: input.now,
|
now: input.now,
|
||||||
});
|
});
|
||||||
@@ -331,6 +344,18 @@ function cancelConfirmed(db: Database.Database, hash: string, token: string, now
|
|||||||
mail,
|
mail,
|
||||||
now,
|
now,
|
||||||
});
|
});
|
||||||
|
queueCoordinatorNotices(db, {
|
||||||
|
action: 'cancel',
|
||||||
|
signupId: row.id,
|
||||||
|
shiftId: row.shift_id,
|
||||||
|
shiftVersion: shift.version,
|
||||||
|
volunteerName: row.name,
|
||||||
|
volunteerEmail: row.email_norm,
|
||||||
|
groupSize: Number(row.group_size),
|
||||||
|
shift: shift.facts,
|
||||||
|
mail,
|
||||||
|
now,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
return { ok: true, already: false };
|
return { ok: true, already: false };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
|
import { moveSignup, switchSignup, updateShift } from '../src/admin/store.js';
|
||||||
|
import { deactivateAdmin } from '../src/admins.js';
|
||||||
|
import { recoverCoordinator } from '../src/auth/recover.js';
|
||||||
|
import { loadConfig } from '../src/config.js';
|
||||||
|
import { openAppDatabase } from '../src/db.js';
|
||||||
|
import { deliverDueMail } from '../src/mail/deliver.js';
|
||||||
|
import type { Mailer } from '../src/mail/types.js';
|
||||||
|
import { cancelSignup, reserveSignup, type ReserveInput } from '../src/signup.js';
|
||||||
|
import { devEnv } from './env.js';
|
||||||
|
|
||||||
|
const NOW = '2026-10-14T18:00:00.000Z';
|
||||||
|
const MAIL = {
|
||||||
|
baseUrl: 'http://127.0.0.1:3000',
|
||||||
|
basePath: '',
|
||||||
|
from: 'Hope Food Pantry <volunteer@example.invalid>',
|
||||||
|
replyTo: 'volunteer@example.invalid',
|
||||||
|
};
|
||||||
|
const dirs: string[] = [];
|
||||||
|
const databases: { close: () => void }[] = [];
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
for (const database of databases.splice(0)) database.close();
|
||||||
|
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('coordinator roster notices', () => {
|
||||||
|
it('tells each active coordinator when someone signs up, and does not repeat that notice', async () => {
|
||||||
|
const { db, shiftId } = await buildDb();
|
||||||
|
insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1, 'admin');
|
||||||
|
insertCoordinator(db, 'bea@example.invalid', 'Bea Coordinator', 1, 'coordinator');
|
||||||
|
insertCoordinator(db, 'cam@example.invalid', 'Cam Inactive', 0, 'admin');
|
||||||
|
const saved = reserveSignup(db, reservation(shiftId, {
|
||||||
|
name: 'Pat <script>\nReview',
|
||||||
|
email: 'pat@example.invalid',
|
||||||
|
phone: '712-555-0199',
|
||||||
|
groupSize: 3,
|
||||||
|
}));
|
||||||
|
expect(saved.ok).toBe(true);
|
||||||
|
|
||||||
|
const notices = db
|
||||||
|
.prepare(`SELECT to_email, subject, body_text, body_html, status FROM outbox WHERE kind = 'notice' ORDER BY to_email`)
|
||||||
|
.all() as Array<{ to_email: string; subject: string; body_text: string; body_html: string; status: string }>;
|
||||||
|
expect(notices.map((row) => row.to_email)).toEqual(['ada@example.invalid', 'bea@example.invalid']);
|
||||||
|
expect(notices[0]).toEqual(expect.objectContaining({
|
||||||
|
status: 'pending',
|
||||||
|
subject: 'Pat <script> Review signed up for Sorting',
|
||||||
|
}));
|
||||||
|
expect(notices[0]?.subject).not.toContain('\n');
|
||||||
|
const letter = notices[0];
|
||||||
|
if (!letter) throw new Error('Ada did not get a notice.');
|
||||||
|
expect(letter.body_html).toContain('Hello Ada Admin,');
|
||||||
|
expect(letter.body_html).toContain('Pat <script> Review');
|
||||||
|
expect(letter.body_html).not.toContain('<script>');
|
||||||
|
expect(letter.body_text).toContain('pat@example.invalid');
|
||||||
|
expect(letter.body_text).toContain('712-555-0199');
|
||||||
|
expect(letter.body_text).toContain('This signup holds 3 spots.');
|
||||||
|
expect(letter.body_text).toContain(`http://127.0.0.1:3000/admin/shifts/${shiftId}`);
|
||||||
|
expect(letter.body_text).not.toContain('/m/');
|
||||||
|
expect(letter.body_html).not.toContain('/m/');
|
||||||
|
expect(db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'confirmation'`).get()).toEqual(
|
||||||
|
expect.objectContaining({ body_text: expect.stringContaining('/m/') }),
|
||||||
|
);
|
||||||
|
|
||||||
|
const again = reserveSignup(db, reservation(shiftId, {
|
||||||
|
name: 'Pat <script>\nReview',
|
||||||
|
email: 'pat@example.invalid',
|
||||||
|
phone: '712-555-0199',
|
||||||
|
groupSize: 3,
|
||||||
|
operationId: 'same-operation',
|
||||||
|
}));
|
||||||
|
expect(again.ok && again.replay).toBe(true);
|
||||||
|
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells coordinators about a cancellation without dropping the signup notice', async () => {
|
||||||
|
const { db, shiftId } = await buildDb();
|
||||||
|
insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
const saved = reserveSignup(db, reservation(shiftId));
|
||||||
|
if (!saved.ok || !saved.manageToken) throw new Error('Signup was not saved.');
|
||||||
|
expect(cancelSignup(db, saved.manageToken, NOW, MAIL)).toEqual({ ok: true, already: false });
|
||||||
|
const notices = db.prepare(`SELECT subject, status FROM outbox WHERE kind = 'notice' ORDER BY subject`).all();
|
||||||
|
expect(notices).toEqual([
|
||||||
|
{ subject: 'Pat Review signed up for Sorting', status: 'pending' },
|
||||||
|
{ subject: "Pat Review's signup for Sorting was cancelled", status: 'pending' },
|
||||||
|
]);
|
||||||
|
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'confirmation'`).get()).toEqual({ status: 'cancelled' });
|
||||||
|
expect(cancelSignup(db, saved.manageToken, NOW, MAIL)).toEqual({ ok: true, already: true });
|
||||||
|
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'notice'`).get()).toEqual({ n: 2 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tells coordinators when a signup is switched, moved, or the shift changes', async () => {
|
||||||
|
const { db, eventId, shiftId } = await buildDb();
|
||||||
|
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
const other = insertShift(db, eventId, 'Distribution');
|
||||||
|
const saved = reserveSignup(db, reservation(shiftId, { email: 'pat@example.invalid', operationId: 'switch-source' }));
|
||||||
|
if (!saved.ok) throw new Error('Signup was not saved.');
|
||||||
|
const switched = switchSignup(db, saved.signupId, other, 'switch-op', NOW, MAIL);
|
||||||
|
expect(switched.ok).toBe(true);
|
||||||
|
const switchNotice = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'notice' AND subject = 'Pat Review switched to Distribution'`).get() as { body_text: string };
|
||||||
|
expect(switchNotice.body_text).toContain('switched from Sorting (');
|
||||||
|
expect(switchNotice.body_text).toContain('to Distribution');
|
||||||
|
expect(switchNotice.body_text).toContain(`/admin/shifts/${other}`);
|
||||||
|
expect(switchNotice.body_text).not.toContain('/m/');
|
||||||
|
|
||||||
|
const movedSource = reserveSignup(db, reservation(shiftId, { name: 'Sam Example', email: 'sam@example.invalid', operationId: 'move-source' }));
|
||||||
|
if (!movedSource.ok) throw new Error('Move signup was not saved.');
|
||||||
|
const moved = moveSignup(db, ada, movedSource.signupId, other, 'move-op', NOW, MAIL);
|
||||||
|
expect(moved.ok).toBe(true);
|
||||||
|
const moveNotice = db.prepare(`SELECT body_text AS body_text FROM outbox WHERE kind = 'notice' AND subject = 'Sam Example was moved to Distribution'`).get() as { body_text: string };
|
||||||
|
expect(moveNotice.body_text).toContain('was moved from Sorting (');
|
||||||
|
expect(moveNotice.body_text).toContain('to Distribution');
|
||||||
|
|
||||||
|
const changed = updateShift(db, ada, other, {
|
||||||
|
role: 'Packing',
|
||||||
|
date: '2026-10-15',
|
||||||
|
start: '10:00',
|
||||||
|
end: '13:00',
|
||||||
|
capacity: 4,
|
||||||
|
}, NOW, MAIL);
|
||||||
|
expect(changed.ok).toBe(true);
|
||||||
|
const changeNotices = db.prepare(`SELECT subject AS subject FROM outbox WHERE kind = 'notice' AND subject LIKE '%shift changed' ORDER BY subject`).all();
|
||||||
|
expect(changeNotices).toEqual([
|
||||||
|
{ subject: "Pat Review's Packing shift changed" },
|
||||||
|
{ subject: "Sam Example's Packing shift changed" },
|
||||||
|
]);
|
||||||
|
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'notice' AND subject = 'Pat Review signed up for Sorting'`).get()).toEqual({
|
||||||
|
status: 'pending',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sends a signup notice after the person cancels, and does not send it once the coordinator or the signup is gone', async () => {
|
||||||
|
const { db, shiftId } = await buildDb();
|
||||||
|
insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
const saved = reserveSignup(db, reservation(shiftId));
|
||||||
|
if (!saved.ok || !saved.manageToken) throw new Error('Signup was not saved.');
|
||||||
|
cancelSignup(db, saved.manageToken, NOW, MAIL);
|
||||||
|
const sent: string[] = [];
|
||||||
|
const mailer: Mailer = {
|
||||||
|
async send(message) {
|
||||||
|
sent.push(message.subject);
|
||||||
|
return { result: 'sent', providerId: 'notice-1' };
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(await deliverDueMail(db, mailer, NOW)).toBe(3);
|
||||||
|
expect(sent).toEqual([
|
||||||
|
'Pat Review signed up for Sorting',
|
||||||
|
'Your signup for Sorting is cancelled',
|
||||||
|
"Pat Review's signup for Sorting was cancelled",
|
||||||
|
]);
|
||||||
|
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'notice' AND subject = 'Pat Review signed up for Sorting'`).get()).toEqual({
|
||||||
|
status: 'sent',
|
||||||
|
});
|
||||||
|
|
||||||
|
const quiet = await buildDb();
|
||||||
|
insertCoordinator(quiet.db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
reserveSignup(quiet.db, reservation(quiet.shiftId, { operationId: 'quiet-operation' }));
|
||||||
|
quiet.db.prepare(`UPDATE coordinators SET active = 0 WHERE email = 'ada@example.invalid'`).run();
|
||||||
|
const calls: string[] = [];
|
||||||
|
expect(await deliverDueMail(quiet.db, { async send(message) { calls.push(message.to); return { result: 'sent', providerId: null }; } }, NOW)).toBe(1);
|
||||||
|
expect(calls).toEqual(['pat.review@example.invalid']);
|
||||||
|
expect(quiet.db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'notice'`).get()).toEqual({
|
||||||
|
status: 'cancelled',
|
||||||
|
last_error: 'That coordinator no longer has access.',
|
||||||
|
});
|
||||||
|
|
||||||
|
const forgotten = await buildDb();
|
||||||
|
insertCoordinator(forgotten.db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
const old = reserveSignup(forgotten.db, reservation(forgotten.shiftId, { operationId: 'old-operation' }));
|
||||||
|
if (!old.ok) throw new Error('Old signup was not saved.');
|
||||||
|
forgotten.db.prepare(
|
||||||
|
`UPDATE signups
|
||||||
|
SET name = NULL, email = NULL, email_norm = NULL, phone = NULL, is_minor = 0,
|
||||||
|
guardian_name = NULL, guardian_email = NULL, notes = NULL,
|
||||||
|
manage_token_hash = NULL, token_expires_at = NULL,
|
||||||
|
anonymized_at = ?, updated_at = ?
|
||||||
|
WHERE id = ?`,
|
||||||
|
).run(NOW, NOW, old.signupId);
|
||||||
|
let anonymizedCalls = 0;
|
||||||
|
expect(await deliverDueMail(forgotten.db, { async send() { anonymizedCalls += 1; return { result: 'sent', providerId: null }; } }, NOW)).toBe(0);
|
||||||
|
expect(anonymizedCalls).toBe(0);
|
||||||
|
expect(forgotten.db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'notice'`).get()).toEqual({
|
||||||
|
status: 'cancelled',
|
||||||
|
last_error: 'The signup is no longer available.',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops a waiting notice when an administrator is removed or the sign-in address is replaced', async () => {
|
||||||
|
const { db, shiftId } = await buildDb();
|
||||||
|
const ada = insertCoordinator(db, 'ada@example.invalid', 'Ada Admin', 1);
|
||||||
|
const bea = insertCoordinator(db, 'bea@example.invalid', 'Bea Admin', 1);
|
||||||
|
reserveSignup(db, reservation(shiftId));
|
||||||
|
expect(deactivateAdmin(db, ada, bea, NOW)).toEqual({ ok: true });
|
||||||
|
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'notice' AND to_email = 'bea@example.invalid'`).get()).toEqual({
|
||||||
|
status: 'cancelled',
|
||||||
|
last_error: 'That coordinator no longer has access.',
|
||||||
|
});
|
||||||
|
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'notice' AND to_email = 'ada@example.invalid'`).get()).toEqual({
|
||||||
|
status: 'pending',
|
||||||
|
});
|
||||||
|
|
||||||
|
recoverCoordinator(db, { email: 'ada@example.invalid', replaceWith: 'ada.next@example.invalid', now: NOW });
|
||||||
|
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'notice' AND to_email = 'ada@example.invalid'`).get()).toEqual({
|
||||||
|
status: 'cancelled',
|
||||||
|
last_error: 'That coordinator no longer has access.',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
async function buildDb() {
|
||||||
|
const root = mkdtempSync(path.join(tmpdir(), 'hope-notice-'));
|
||||||
|
dirs.push(root);
|
||||||
|
const config = loadConfig(devEnv({ DATA_DIR: path.join(root, 'data') }));
|
||||||
|
const db = await openAppDatabase(config);
|
||||||
|
databases.push(db);
|
||||||
|
const eventId = Number(
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO events (slug, title, description, location, tz, published, created_at)
|
||||||
|
VALUES ('weekly-pantry', 'Weekly pantry', 'Bring a hat.', 'Sioux Center, Iowa', 'America/Chicago', 1, ?)`,
|
||||||
|
).run(NOW).lastInsertRowid,
|
||||||
|
);
|
||||||
|
return { db, eventId, shiftId: insertShift(db, eventId, 'Sorting') };
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertShift(db: Awaited<ReturnType<typeof openAppDatabase>>, eventId: number, role: string): number {
|
||||||
|
return Number(
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
|
||||||
|
VALUES (?, ?, '2026-10-15T14:00:00.000Z', '2026-10-15T17:00:00.000Z', 4, '', 0)`,
|
||||||
|
).run(eventId, role).lastInsertRowid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertCoordinator(
|
||||||
|
db: Awaited<ReturnType<typeof openAppDatabase>>,
|
||||||
|
email: string,
|
||||||
|
name: string,
|
||||||
|
active: number,
|
||||||
|
role: 'admin' | 'coordinator' = 'admin',
|
||||||
|
): number {
|
||||||
|
return Number(
|
||||||
|
db.prepare(
|
||||||
|
`INSERT INTO coordinators (email, name, role, password_hash, active, created_at)
|
||||||
|
VALUES (?, ?, ?, NULL, ?, ?)`,
|
||||||
|
).run(email, name, role, active, NOW).lastInsertRowid,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function reservation(shiftId: number, overrides: Partial<ReserveInput> = {}): ReserveInput {
|
||||||
|
return {
|
||||||
|
shiftId,
|
||||||
|
name: 'Pat Review',
|
||||||
|
email: 'pat.review@example.invalid',
|
||||||
|
phone: '712-555-0100',
|
||||||
|
notes: null,
|
||||||
|
operationId: 'same-operation',
|
||||||
|
now: NOW,
|
||||||
|
mail: MAIL,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -242,6 +242,70 @@ describe('signup and shift constraints', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('keeps queued mail when coordinator notices are added', async () => {
|
||||||
|
const root = makeDir();
|
||||||
|
const migrations = path.join(root, 'migrations');
|
||||||
|
const dataDir = path.join(root, 'data');
|
||||||
|
mkdirSync(migrations);
|
||||||
|
const real = defaultMigrationsDir();
|
||||||
|
for (const name of readdirSync(real)) {
|
||||||
|
if (name.startsWith('009')) continue;
|
||||||
|
copyFileSync(path.join(real, name), path.join(migrations, name));
|
||||||
|
}
|
||||||
|
const config = loadConfig(devEnv({ DATA_DIR: dataDir }));
|
||||||
|
const first = await openAppDatabase(config, { migrationsDir: migrations });
|
||||||
|
const parents = insertParents(first);
|
||||||
|
insertSignup(first, parents.shiftId, { email: 'ada@example.invalid', emailNorm: 'ada@example.invalid' });
|
||||||
|
const signupId = Number((first.prepare('SELECT id AS id FROM signups').get() as { id: number }).id);
|
||||||
|
const outboxId = Number(
|
||||||
|
first
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO outbox (
|
||||||
|
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html, send_after, status, created_at
|
||||||
|
) VALUES ('keep', ?, ?, 'confirmation', 'ada@example.invalid', 'Hi', 'Hi', '<p>Hi</p>', ?, 'pending', ?)`,
|
||||||
|
)
|
||||||
|
.run(signupId, parents.shiftId, INSTANT, INSTANT).lastInsertRowid,
|
||||||
|
);
|
||||||
|
first
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO reminders_sent (signup_id, kind, shift_version, outbox_id, queued_at)
|
||||||
|
VALUES (?, '48h', 1, ?, ?)`,
|
||||||
|
)
|
||||||
|
.run(signupId, outboxId, INSTANT);
|
||||||
|
first.close();
|
||||||
|
|
||||||
|
copyFileSync(path.join(real, '009_coordinator_notice.sql'), path.join(migrations, '009_coordinator_notice.sql'));
|
||||||
|
const second = await openAppDatabase(config, { migrationsDir: migrations });
|
||||||
|
try {
|
||||||
|
expect(second.pragma('foreign_keys', { simple: true })).toBe(1);
|
||||||
|
expect(second.prepare('PRAGMA foreign_key_check').all()).toEqual([]);
|
||||||
|
expect(second.prepare('SELECT to_email AS to_email, kind AS kind FROM outbox WHERE dedupe_key = ?').get('keep')).toEqual({
|
||||||
|
to_email: 'ada@example.invalid',
|
||||||
|
kind: 'confirmation',
|
||||||
|
});
|
||||||
|
expect(second.prepare('SELECT outbox_id AS outbox_id FROM reminders_sent').get()).toEqual({ outbox_id: outboxId });
|
||||||
|
second
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO outbox (
|
||||||
|
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html, send_after, status, created_at
|
||||||
|
) VALUES ('notice', ?, ?, 'notice', 'coordinator@example.invalid', 'Hi', 'Hi', '<p>Hi</p>', ?, 'pending', ?)`,
|
||||||
|
)
|
||||||
|
.run(signupId, parents.shiftId, INSTANT, INSTANT);
|
||||||
|
expect(() =>
|
||||||
|
second
|
||||||
|
.prepare(
|
||||||
|
`INSERT INTO outbox (
|
||||||
|
dedupe_key, signup_id, shift_id, kind, to_email, subject, body_text, body_html, send_after, status, created_at
|
||||||
|
) VALUES ('nope', ?, ?, 'nope', 'ada@example.invalid', 'Hi', 'Hi', '<p>Hi</p>', ?, 'pending', ?)`,
|
||||||
|
)
|
||||||
|
.run(signupId, parents.shiftId, INSTANT, INSTANT),
|
||||||
|
).toThrow(/CHECK/);
|
||||||
|
expect(second.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'outbox_next'").get()).toBeUndefined();
|
||||||
|
} finally {
|
||||||
|
second.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('enforces capacity, party size, duplicates, anonymization, and history', async () => {
|
it('enforces capacity, party size, duplicates, anonymization, and history', async () => {
|
||||||
const dataDir = path.join(makeDir(), 'data');
|
const dataDir = path.join(makeDir(), 'data');
|
||||||
const db = await openAppDatabase(loadConfig(devEnv({ DATA_DIR: dataDir })));
|
const db = await openAppDatabase(loadConfig(devEnv({ DATA_DIR: dataDir })));
|
||||||
|
|||||||
@@ -116,7 +116,8 @@ describe('reminder mail', () => {
|
|||||||
queueDueReminders(db, MAIL, SECRET, NOW);
|
queueDueReminders(db, MAIL, SECRET, NOW);
|
||||||
db.prepare(`UPDATE signups SET reminders_off = 1 WHERE email_norm = 'pat.review@example.invalid'`).run();
|
db.prepare(`UPDATE signups SET reminders_off = 1 WHERE email_norm = 'pat.review@example.invalid'`).run();
|
||||||
const mailer: Mailer = { async send() { return { result: 'sent', providerId: null }; } };
|
const mailer: Mailer = { async send() { return { result: 'sent', providerId: null }; } };
|
||||||
expect(await deliverDueMail(db, mailer, NOW)).toBe(1);
|
expect(await deliverDueMail(db, mailer, NOW)).toBe(2);
|
||||||
|
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'notice'`).get()).toEqual({ status: 'sent' });
|
||||||
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'reminder'`).get()).toEqual({
|
expect(db.prepare(`SELECT status, last_error FROM outbox WHERE kind = 'reminder'`).get()).toEqual({
|
||||||
status: 'cancelled',
|
status: 'cancelled',
|
||||||
last_error: 'Reminders were turned off before this message was sent.',
|
last_error: 'Reminders were turned off before this message was sent.',
|
||||||
|
|||||||
Reference in new issue
Block a user