feat: enhance reminder functionality with version tracking for shifts

Introduced a new column `version_at` in the shifts table to track the last change time of a shift's version. Updated reminder logic to skip reminders that are due before the shift's version change or the signup time. Modified related functions and tests to ensure correct behavior when managing reminders for shifts and signups, including scenarios for late signups and shift changes.
This commit is contained in:
blake committed 2026-11-02 12:00:42 -06:00
1 parent 71130c3e8e
commit 17ca2f9dfb
6 files changed
+116 -16

No files matched your search

+1 -1
View File
@@ -98,7 +98,7 @@ Saving a weekly template updates shifts from that template that have not ended,
**Remove from roster** deletes a cancelled signup, including the name, email, and notes. A confirmed signup has to be cancelled first. **Remove this shift** deletes a cancelled or ended shift after the roster is empty. If that date came from a weekly template that is still active, saving that template can add the date again. **Remove this template** deletes an ended template. Any shifts left are no longer tied to that weekly pattern. Cancelled shifts stay off the upcoming list. **Remove this event** asks for confirmation, then deletes that event and the shifts, weekly templates, and signups on it, including names and emails. An event on the public list comes off that list. It does not send email. Other events stay. **Remove from roster** deletes a cancelled signup, including the name, email, and notes. A confirmed signup has to be cancelled first. **Remove this shift** deletes a cancelled or ended shift after the roster is empty. If that date came from a weekly template that is still active, saving that template can add the date again. **Remove this template** deletes an ended template. Any shifts left are no longer tied to that weekly pattern. Cancelled shifts stay off the upcoming list. **Remove this event** asks for confirmation, then deletes that event and the shifts, weekly templates, and signups on it, including names and emails. An event on the public list comes off that list. It does not send email. Other events stay.
A reminder is queued at each saved time before a confirmed signup, while the shift has not started. The defaults are 48 hours before and 2 hours before. The check runs every five minutes. If the app was off and more than one reminder is already due, only the closest one is sent. A person who signs up after an earlier reminder was due does not get that missed reminder. A reminder is not sent after the shift starts. Changing the shift, moving the signup, or cancelling it drops a reminder that has not been sent yet. Mail that was already accepted cannot be recalled. **Stop reminder emails**, on the private signup page or in the reminder itself, turns reminders off for that signup. The signup stays. Confirmation, change, and cancellation emails still arrive. The reminder asks the person to use the link in the confirmation email to cancel. Mail sent to the reply-to address is read by the pantry. A reminder is queued at each saved time before a confirmed signup, while the shift has not started. The defaults are 48 hours before and 2 hours before. The check runs every five minutes. If the app was off and more than one reminder is already due, only the closest one is sent. A person who signs up after an earlier reminder was due does not get that missed reminder. The same applies after a shift change or a move: a reminder that was already due is not sent. A reminder is not sent after the shift starts. Changing the shift, moving the signup, or cancelling it drops a reminder that has not been sent yet. Mail that was already accepted cannot be recalled. **Stop reminder emails**, on the private signup page or in the reminder itself, turns reminders off for that signup. The signup stays. Confirmation, change, and cancellation emails still arrive. The reminder asks the person to use the link in the confirmation email to cancel. Mail sent to the reply-to address is read by the pantry.
**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. 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. 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.
+14
View File
@@ -0,0 +1,14 @@
-- version_at is when this shift's version last changed.
-- A reminder due before that time, or before the signup, is not sent.
ALTER TABLE shifts ADD COLUMN version_at TEXT NULL CHECK (
version_at IS NULL
OR version_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'
);
UPDATE shifts
SET version_at = (
SELECT MAX(created_at)
FROM outbox
WHERE outbox.shift_id = shifts.id AND outbox.kind = 'changed'
)
WHERE version > 1;
+3 -3
View File
@@ -1626,10 +1626,10 @@ function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail
const bumped = db const bumped = db
.prepare( .prepare(
manual manual
? 'UPDATE shifts SET version = version + 1, manually_modified = 1 WHERE id = ? AND cancelled = 0' ? 'UPDATE shifts SET version = version + 1, version_at = ?, manually_modified = 1 WHERE id = ? AND cancelled = 0'
: 'UPDATE shifts SET version = version + 1 WHERE id = ? AND cancelled = 0 AND manually_modified = 0', : 'UPDATE shifts SET version = version + 1, version_at = ? WHERE id = ? AND cancelled = 0 AND manually_modified = 0',
) )
.run(shiftId); .run(now, shiftId);
if (bumped.changes !== 1) return 0; if (bumped.changes !== 1) return 0;
db.prepare( db.prepare(
`UPDATE outbox `UPDATE outbox
+18 -3
View File
@@ -14,7 +14,9 @@ type DueSignup = {
id: number; id: number;
name: string; name: string;
email_norm: string; email_norm: string;
created_at: string;
version: number; version: number;
version_at: string | null;
starts_at_utc: string; starts_at_utc: string;
ends_at_utc: string; ends_at_utc: string;
role: string; role: string;
@@ -27,8 +29,9 @@ type DueSignup = {
/** /**
* Queues reminders that are due and still before the shift starts. * Queues reminders that are due and still before the shift starts.
* A reminder whose due time was before the signup, or before this shift version, is skipped.
* When more than one offset is already due, only the closest one is sent. * When more than one offset is already due, only the closest one is sent.
* Older offsets are recorded as not sent, so a late signup does not get every missed reminder. * Older offsets are recorded as not sent.
* The same signup, offset, and shift version is not queued twice. * The same signup, offset, and shift version is not queued twice.
* Offset hours and the reply-to address come from coordinator settings, or the defaults when none are saved. * Offset hours and the reply-to address come from coordinator settings, or the defaults when none are saved.
*/ */
@@ -39,7 +42,8 @@ export function queueDueReminders(db: Database.Database, mail: MailIdentity, sec
const rows = db const rows = db
.prepare( .prepare(
`SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.group_size AS group_size, `SELECT su.id AS id, su.name AS name, su.email_norm AS email_norm, su.group_size AS group_size,
su.shift_id AS shift_id, s.version AS version, s.starts_at_utc AS starts_at_utc, su.created_at AS created_at, su.shift_id AS shift_id, s.version AS version,
s.version_at AS version_at, 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
FROM signups su FROM signups su
@@ -59,9 +63,12 @@ export function queueDueReminders(db: Database.Database, mail: MailIdentity, sec
const nowInstant = Temporal.Instant.from(now); const nowInstant = Temporal.Instant.from(now);
for (const row of rows) { for (const row of rows) {
const start = Temporal.Instant.from(row.starts_at_utc); const start = Temporal.Instant.from(row.starts_at_utc);
const anchor = reminderAnchor(row.created_at, row.version_at);
const due = offsets.filter((offset) => { const due = offsets.filter((offset) => {
const dueAt = start.subtract({ hours: offset.hours }); const dueAt = start.subtract({ hours: offset.hours });
return Temporal.Instant.compare(nowInstant, dueAt) >= 0 && !alreadyQueued(db, row.id, offset.kind, row.version); return Temporal.Instant.compare(dueAt, anchor) >= 0
&& Temporal.Instant.compare(nowInstant, dueAt) >= 0
&& !alreadyQueued(db, row.id, offset.kind, row.version);
}); });
if (due.length === 0) continue; if (due.length === 0) continue;
const nearest = due.reduce((closest, offset) => (offset.hours < closest.hours ? offset : closest)); const nearest = due.reduce((closest, offset) => (offset.hours < closest.hours ? offset : closest));
@@ -136,6 +143,14 @@ export function readReminderOffToken(secret: string, token: string): number | nu
return id; return id;
} }
/** The later of the signup and the current shift version. A move starts a new signup. */
function reminderAnchor(createdAt: string, versionAt: string | null): Temporal.Instant {
const signedUp = Temporal.Instant.from(createdAt);
if (!versionAt) return signedUp;
const changed = Temporal.Instant.from(versionAt);
return Temporal.Instant.compare(changed, signedUp) > 0 ? changed : signedUp;
}
function alreadyQueued(db: Database.Database, signupId: number, kind: string, version: number): boolean { function alreadyQueued(db: Database.Database, signupId: number, kind: string, version: number): boolean {
const row = db const row = db
.prepare('SELECT signup_id FROM reminders_sent WHERE signup_id = ? AND kind = ? AND shift_version = ?') .prepare('SELECT signup_id FROM reminders_sent WHERE signup_id = ? AND kind = ? AND shift_version = ?')
+79 -8
View File
@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import path from 'node:path'; import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest'; import { afterEach, describe, expect, it } from 'vitest';
import { updateShift } from '../src/admin/store.js'; import { moveSignup, updateShift } from '../src/admin/store.js';
import { createApp } from '../src/app.js'; import { createApp } from '../src/app.js';
import { bootstrapAdmin } from '../src/auth/bootstrap.js'; import { bootstrapAdmin } from '../src/auth/bootstrap.js';
import { loadConfig } from '../src/config.js'; import { loadConfig } from '../src/config.js';
@@ -15,6 +15,10 @@ import { reserveSignup, type ReserveInput } from '../src/signup.js';
import { devEnv } from './env.js'; import { devEnv } from './env.js';
const NOW = '2026-10-14T18:00:00.000Z'; const NOW = '2026-10-14T18:00:00.000Z';
const EARLY = '2026-10-01T15:00:00.000Z';
const INSIDE_START = '2026-10-16T00:00:00.000Z';
const INSIDE_END = '2026-10-16T03:00:00.000Z';
const INSIDE_NEAR = '2026-10-15T22:00:00.000Z';
const SOON = '2026-10-14T18:30:00.000Z'; const SOON = '2026-10-14T18:30:00.000Z';
const SOON_END = '2026-10-14T20:00:00.000Z'; const SOON_END = '2026-10-14T20:00:00.000Z';
const LATER_START = '2026-10-15T14:00:00.000Z'; const LATER_START = '2026-10-15T14:00:00.000Z';
@@ -41,7 +45,7 @@ describe('reminder mail', () => {
it('queues the 48 hour reminder, sends it once, and records provider acceptance', async () => { it('queues the 48 hour reminder, sends it once, and records provider acceptance', async () => {
const db = await openDb(); const db = await openDb();
const shiftId = insertShift(db, LATER_START, LATER_END); const shiftId = insertShift(db, LATER_START, LATER_END);
reserveSignup(db, reservation(shiftId, { name: 'Pat <script>' })); reserveSignup(db, reservation(shiftId, { name: 'Pat <script>', now: EARLY }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 }); expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 });
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 }); expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
@@ -83,7 +87,7 @@ describe('reminder mail', () => {
it('sends only the closest reminder when several are already due', async () => { it('sends only the closest reminder when several are already due', async () => {
const db = await openDb(); const db = await openDb();
const shiftId = insertShift(db, SOON, SOON_END); const shiftId = insertShift(db, SOON, SOON_END);
reserveSignup(db, reservation(shiftId, { email: 'late@example.invalid', operationId: 'late-signup' })); reserveSignup(db, reservation(shiftId, { email: 'late@example.invalid', operationId: 'late-signup', now: EARLY }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 1 }); expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 1 });
const rows = db.prepare(`SELECT status, body_text FROM outbox WHERE kind = 'reminder' ORDER BY id`).all() as Array<{ status: string; body_text: string }>; const rows = db.prepare(`SELECT status, body_text FROM outbox WHERE kind = 'reminder' ORDER BY id`).all() as Array<{ status: string; body_text: string }>;
expect(rows.map((row) => row.status)).toEqual(['pending', 'cancelled']); expect(rows.map((row) => row.status)).toEqual(['pending', 'cancelled']);
@@ -93,6 +97,18 @@ describe('reminder mail', () => {
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 2 }); expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 2 });
}); });
it('does not queue a reminder that was already due before the signup', async () => {
const db = await openDb();
const shiftId = insertShift(db, INSIDE_START, INSIDE_END);
reserveSignup(db, reservation(shiftId, { email: 'thirty@example.invalid', operationId: 'thirty-hours' }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(db.prepare(`SELECT kind FROM outbox`).all()).toEqual([{ kind: 'confirmation' }]);
expect(queueDueReminders(db, MAIL, SECRET, INSIDE_NEAR)).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare(`SELECT kind FROM reminders_sent`).get()).toEqual({ kind: '2h' });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 1 });
});
it('does not queue a reminder after the shift has started, or when reminders are off', async () => { it('does not queue a reminder after the shift has started, or when reminders are off', async () => {
const db = await openDb(); const db = await openDb();
const started = insertShift(db, '2026-10-14T14:00:00.000Z', '2026-10-14T17:00:00.000Z'); const started = insertShift(db, '2026-10-14T14:00:00.000Z', '2026-10-14T17:00:00.000Z');
@@ -112,7 +128,7 @@ describe('reminder mail', () => {
const db = await openDb(); const db = await openDb();
bootstrapAdmin(db, 'coordinator@example.invalid', NOW); bootstrapAdmin(db, 'coordinator@example.invalid', NOW);
const shiftId = insertShift(db, LATER_START, LATER_END); const shiftId = insertShift(db, LATER_START, LATER_END);
reserveSignup(db, reservation(shiftId)); reserveSignup(db, reservation(shiftId, { now: EARLY }));
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 }; } };
@@ -125,10 +141,11 @@ describe('reminder mail', () => {
expect(db.prepare(`SELECT sent_at FROM reminders_sent`).get()).toEqual({ sent_at: null }); expect(db.prepare(`SELECT sent_at FROM reminders_sent`).get()).toEqual({ sent_at: null });
db.prepare(`UPDATE signups SET reminders_off = 0 WHERE email_norm = 'pat.review@example.invalid'`).run(); db.prepare(`UPDATE signups SET reminders_off = 0 WHERE email_norm = 'pat.review@example.invalid'`).run();
const changed = updateShift(db, 1, shiftId, { role: 'Intake', date: '2026-10-15', start: '09:00', end: '12:00', capacity: 4 }, NOW, MAIL); const changed = updateShift(db, 1, shiftId, { role: 'Intake', date: '2026-10-17', start: '09:00', end: '12:00', capacity: 4 }, NOW, MAIL);
expect(changed.ok).toBe(true); expect(changed.ok).toBe(true);
expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'reminder' AND subject = 'Reminder: Sorting'`).get()).toEqual({ status: 'cancelled' }); expect(db.prepare(`SELECT status FROM outbox WHERE kind = 'reminder' AND subject = 'Reminder: Sorting'`).get()).toEqual({ status: 'cancelled' });
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 1, suppressed: 0 }); expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(queueDueReminders(db, MAIL, SECRET, '2026-10-15T14:00:00.000Z')).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare(`SELECT subject, status FROM outbox WHERE kind = 'reminder' AND status = 'pending'`).get()).toEqual({ expect(db.prepare(`SELECT subject, status FROM outbox WHERE kind = 'reminder' AND status = 'pending'`).get()).toEqual({
subject: 'Reminder: Intake', subject: 'Reminder: Intake',
status: 'pending', status: 'pending',
@@ -139,10 +156,55 @@ describe('reminder mail', () => {
]); ]);
}); });
it('does not queue a reminder that was already due before the shift changed', async () => {
const db = await openDb();
bootstrapAdmin(db, 'coordinator@example.invalid', EARLY);
const shiftId = insertShift(db, FAR_START, FAR_END);
reserveSignup(db, reservation(shiftId, { now: EARLY, operationId: 'before-change' }));
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
const changed = updateShift(
db,
1,
shiftId,
{ role: 'Sorting', date: '2026-10-15', start: '19:00', end: '22:00', capacity: 4 },
NOW,
MAIL,
);
expect(changed.ok).toBe(true);
expect(db.prepare(`SELECT starts_at_utc AS starts_at_utc FROM shifts WHERE id = ?`).get(shiftId)).toEqual({
starts_at_utc: INSIDE_START,
});
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 0 });
expect(queueDueReminders(db, MAIL, SECRET, INSIDE_NEAR)).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare(`SELECT kind, shift_version FROM reminders_sent`).get()).toEqual({ kind: '2h', shift_version: 2 });
});
it('does not queue a reminder that was already due before the signup moved', async () => {
const db = await openDb();
bootstrapAdmin(db, 'coordinator@example.invalid', EARLY);
const sourceId = insertShift(db, FAR_START, FAR_END, 'source-shift');
const eventId = (db.prepare(`SELECT event_id AS event_id FROM shifts WHERE id = ?`).get(sourceId) as { event_id: number }).event_id;
const destinationId = insertShiftOnEvent(db, eventId, INSIDE_START, INSIDE_END);
const saved = reserveSignup(db, reservation(sourceId, { now: EARLY, operationId: 'before-move' }));
expect(saved.ok).toBe(true);
if (!saved.ok) return;
const moved = moveSignup(db, 1, saved.signupId, destinationId, 'move-inside', NOW, MAIL);
expect(moved.ok).toBe(true);
expect(queueDueReminders(db, MAIL, SECRET, NOW)).toEqual({ queued: 0, suppressed: 0 });
expect(db.prepare(`SELECT COUNT(*) AS n FROM outbox WHERE kind = 'reminder'`).get()).toEqual({ n: 0 });
expect(queueDueReminders(db, MAIL, SECRET, INSIDE_NEAR)).toEqual({ queued: 1, suppressed: 0 });
expect(db.prepare(`SELECT kind, shift_version FROM reminders_sent`).get()).toEqual({ kind: '2h', shift_version: 1 });
});
it('turns reminders off from the email link without cancelling, and leaves a visit unchanged', async () => { it('turns reminders off from the email link without cancelling, and leaves a visit unchanged', async () => {
const { app, db } = await buildApp(); const { app, db } = await buildApp();
const shiftId = insertShift(db, LATER_START, LATER_END); const shiftId = insertShift(db, LATER_START, LATER_END);
const saved = reserveSignup(db, reservation(shiftId)); const saved = reserveSignup(db, reservation(shiftId, { now: EARLY }));
expect(saved.ok).toBe(true); expect(saved.ok).toBe(true);
if (!saved.ok) return; if (!saved.ok) return;
queueDueReminders(db, MAIL, SECRET, NOW); queueDueReminders(db, MAIL, SECRET, NOW);
@@ -173,7 +235,7 @@ describe('reminder mail', () => {
it('turns reminders off from the private signup page and keeps the signup', async () => { it('turns reminders off from the private signup page and keeps the signup', async () => {
const { app, db } = await buildApp(); const { app, db } = await buildApp();
const shiftId = insertShift(db, LATER_START, LATER_END); const shiftId = insertShift(db, LATER_START, LATER_END);
const saved = reserveSignup(db, reservation(shiftId)); const saved = reserveSignup(db, reservation(shiftId, { now: EARLY }));
expect(saved.ok && saved.manageToken).toBeTruthy(); expect(saved.ok && saved.manageToken).toBeTruthy();
if (!saved.ok || !saved.manageToken) return; if (!saved.ok || !saved.manageToken) return;
queueDueReminders(db, MAIL, SECRET, NOW); queueDueReminders(db, MAIL, SECRET, NOW);
@@ -228,6 +290,15 @@ function rootOf(db: { name: string }): string {
return path.dirname(path.dirname(db.name)); return path.dirname(path.dirname(db.name));
} }
function insertShiftOnEvent(db: Awaited<ReturnType<typeof openDb>>, eventId: number, start: string, end: string): number {
return Number(
db.prepare(
`INSERT INTO shifts (event_id, role, starts_at_utc, ends_at_utc, capacity, notes, cancelled)
VALUES (?, 'Intake', ?, ?, 4, '', 0)`,
).run(eventId, start, end).lastInsertRowid,
);
}
function insertShift(db: Awaited<ReturnType<typeof openDb>>, start: string, end: string, slug = 'weekly'): number { function insertShift(db: Awaited<ReturnType<typeof openDb>>, start: string, end: string, slug = 'weekly'): number {
const eventId = Number( const eventId = Number(
db.prepare( db.prepare(
+1 -1
View File
@@ -216,7 +216,7 @@ function insertSignup(db: Awaited<ReturnType<typeof buildApp>>['db'], shiftId: n
`INSERT INTO signups ( `INSERT INTO signups (
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
) VALUES (?, 'Ada', 'ada@example.invalid', 'ada@example.invalid', 0, 1, 'confirmed', 0, ?, ?)`, ) VALUES (?, 'Ada', 'ada@example.invalid', 'ada@example.invalid', 0, 1, 'confirmed', 0, ?, ?)`,
).run(shiftId, NOW, NOW); ).run(shiftId, '2026-10-13T18:00:00.000Z', '2026-10-13T18:00:00.000Z');
} }
function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db']): string { function magicToken(db: Awaited<ReturnType<typeof buildApp>>['db']): string {