feat: add volunteer shift signup app

Initial source, tests, migrations, and local Docker setup for the Hope Food Pantry volunteer scheduler.
This commit is contained in:
blake committed 2026-10-16 09:33:39 -05:00
commit f1a46e2ba7
129 files changed
+25290

No files matched your search

+203
View File
@@ -0,0 +1,203 @@
import { copyFile, mkdir, rename, rm } from 'node:fs/promises';
import { readdirSync, unlinkSync } from 'node:fs';
import path from 'node:path';
import { Temporal } from '@js-temporal/polyfill';
import Database from 'better-sqlite3';
import { writeAudit } from '../auth/audit.js';
import { backupDatabase } from '../db.js';
import { formatInstantInZone } from '../time.js';
/** Central Time. 2:30 is missing on the spring-forward morning, so the clock comparison is used. */
export const BACKUP_ZONE = 'America/Chicago';
export const BACKUP_LOCAL_TIME = '02:30';
export const DAILY_KEEP = 14;
export const WEEKLY_KEEP = 8;
export function backupDirectory(dataDir: string): string {
return path.join(dataDir, 'backups');
}
const JOB = 'backup';
const POLL_MS = 60 * 1000;
const SNAPSHOT = /^(daily|weekly)-(\d{4}-\d{2}-\d{2})\.db$/;
const MONTHS = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
] as const;
export type BackupCopy = (db: Database.Database, destination: string) => Promise<void>;
export type BackupResult = {
ran: boolean;
date: string;
weekly: boolean;
prunedDaily: number;
prunedWeekly: number;
};
export type BackupStatus = {
state: 'saved' | 'waiting' | 'behind';
text: string;
};
/**
* Saves one consistent database copy per Central Time date, after 2:30.
* A failed attempt does not remove older copies and does not record the day,
* so the next check can try again. Sunday's copy is also kept as a weekly file.
*/
export async function runDueBackup(
db: Database.Database,
backupsDir: string,
now: string,
copy: BackupCopy = backupDatabase,
): Promise<BackupResult> {
const skipped: BackupResult = { ran: false, date: '', weekly: false, prunedDaily: 0, prunedWeekly: 0 };
const clock = formatInstantInZone(now, BACKUP_ZONE);
if (clock.time24 < BACKUP_LOCAL_TIME || alreadyRan(db, clock.date)) return skipped;
const partial = path.join(backupsDir, `daily-${clock.date}.db.partial`);
const daily = path.join(backupsDir, `daily-${clock.date}.db`);
try {
await copy(db, partial);
await mkdir(backupsDir, { recursive: true });
await rename(partial, daily);
const weekly = clock.weekday === 0;
if (weekly) await copySnapshot(daily, path.join(backupsDir, `weekly-${clock.date}.db`));
const prunedDaily = pruneSnapshots(backupsDir, 'daily', DAILY_KEEP);
const prunedWeekly = pruneSnapshots(backupsDir, 'weekly', WEEKLY_KEEP);
markRan(db, clock.date, now);
try {
writeAudit(db, null, 'backup.save', { prunedDaily, prunedWeekly }, now);
} catch {
console.error('The database backup was saved, but the audit note was not recorded.');
}
return { ran: true, date: clock.date, weekly, prunedDaily, prunedWeekly };
} catch (err) {
await rm(partial, { force: true });
console.error(err instanceof Error ? err.message : 'Database backup failed.');
return skipped;
}
}
/** Newest daily copy, and whether today's backup is still expected later. */
export function describeBackup(backupsDir: string, now: string): BackupStatus {
const newest = newestSnapshot(backupsDir, 'daily');
const clock = formatInstantInZone(now, BACKUP_ZONE);
if (!newest) {
const state = clock.time24 < BACKUP_LOCAL_TIME ? 'waiting' : 'behind';
return { state, text: 'No database backup has been saved yet.' };
}
const label = prettyDate(newest);
const savedToday = newest >= clock.date;
const savedYesterday = newest >= previousDate(clock.date) && clock.time24 < BACKUP_LOCAL_TIME;
if (savedToday || savedYesterday) return { state: 'saved', text: `Database backup saved ${label}.` };
return { state: 'behind', text: `Database backup is behind. The newest saved copy is ${label}.` };
}
export function startBackupRunner(
db: Database.Database,
backupsDir: string,
now: () => string,
): { stop: () => void } {
let running = false;
let stopped = false;
const tick = () => {
if (running || stopped) return;
running = true;
void (async () => {
try {
const result = await runDueBackup(db, backupsDir, now());
if (result.ran) console.log(`Saved the database backup for ${result.date}.`);
} catch (err) {
console.error(err instanceof Error ? err.message : 'Database backup failed.');
} finally {
running = false;
}
})();
};
const timer = setInterval(tick, POLL_MS);
timer.unref();
tick();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}
async function copySnapshot(source: string, destination: string): Promise<void> {
const partial = `${destination}.partial`;
try {
await copyFile(source, partial);
const check = new Database(partial, { readonly: true, fileMustExist: true });
try {
const result = check.pragma('integrity_check', { simple: true });
if (result !== 'ok') throw new Error('Sunday backup failed the integrity check.');
} finally {
check.close();
}
await rename(partial, destination);
} catch (err) {
await rm(partial, { force: true });
throw err;
}
}
function pruneSnapshots(backupsDir: string, kind: 'daily' | 'weekly', keep: number): number {
const matched = listSnapshots(backupsDir, kind);
const extra = matched.slice(keep);
for (const file of extra) unlinkSync(path.join(backupsDir, file.name));
return extra.length;
}
function newestSnapshot(backupsDir: string, kind: 'daily' | 'weekly'): string | null {
return listSnapshots(backupsDir, kind)[0]?.date ?? null;
}
function listSnapshots(backupsDir: string, kind: 'daily' | 'weekly'): { name: string; date: string }[] {
let names: string[] = [];
try {
names = readdirSync(backupsDir);
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return [];
throw err;
}
return names
.map((name) => {
const match = SNAPSHOT.exec(name);
if (!match || match[1] !== kind || !match[2]) return null;
return { name, date: match[2] };
})
.filter((row): row is { name: string; date: string } => row !== null)
.sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0));
}
function prettyDate(iso: string): string {
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
const month = match ? MONTHS[Number(match[2]) - 1] : undefined;
if (!match || !month) return iso;
return `${month} ${Number(match[3])}, ${match[1]}`;
}
function previousDate(iso: string): string {
return Temporal.PlainDate.from(iso).subtract({ days: 1 }).toString();
}
function alreadyRan(db: Database.Database, localDate: string): boolean {
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, BACKUP_ZONE, localDate);
return row !== undefined;
}
function markRan(db: Database.Database, localDate: string, now: string): void {
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, BACKUP_ZONE, localDate, now);
}
+89
View File
@@ -0,0 +1,89 @@
import type Database from 'better-sqlite3';
import { expandTemplates } from '../recurrence.js';
import { formatInstantInZone } from '../time.js';
/** Local time after which that event's day gets its weekly fill. */
export const REFILL_LOCAL_TIME = '01:00';
const JOB = 'template.expand';
const INTERVAL_MS = 60 * 1000;
export type DailyExpandResult = {
zones: string[];
created: number;
skipped: string[];
};
/**
* Fills active weekly templates once each local date, after 01:00 in that
* event's time zone. A restart later the same day still fills if that date
* has not been recorded. The check uses the clock, not a 24-hour timer.
*/
export function runDueTemplateExpansion(db: Database.Database, now: string): DailyExpandResult {
const zones = db.prepare('SELECT DISTINCT tz AS tz FROM events ORDER BY tz').all() as { tz: string }[];
const ran: string[] = [];
let created = 0;
const skipped: string[] = [];
for (const zone of zones) {
let date = '';
let time = '';
try {
const clock = formatInstantInZone(now, zone.tz);
date = clock.date;
time = clock.time24;
} catch (err) {
console.error(err instanceof Error ? err.message : 'Weekly refill could not read an event time zone.');
continue;
}
if (time < REFILL_LOCAL_TIME || alreadyRan(db, zone.tz, date)) continue;
try {
const result = expandTemplates(db, now, { timeZone: zone.tz });
markRan(db, zone.tz, date, now);
created += result.created;
skipped.push(...result.skipped);
ran.push(zone.tz);
} catch (err) {
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
}
}
return { zones: ran, created, skipped };
}
/** Checks about once a minute. A check that is still running is not started again. */
export function startDailyExpansionRunner(db: Database.Database, now: () => string): { stop: () => void } {
let running = false;
let stopped = false;
const tick = () => {
if (running || stopped) return;
running = true;
try {
const result = runDueTemplateExpansion(db, now());
if (result.created > 0) {
console.log(`Added ${result.created} weekly shifts for the next eight weeks.`);
}
for (const skip of result.skipped) console.error(skip);
} catch (err) {
console.error(err instanceof Error ? err.message : 'Weekly refill failed.');
} finally {
running = false;
}
};
const timer = setInterval(tick, INTERVAL_MS);
timer.unref();
tick();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}
function alreadyRan(db: Database.Database, timeZone: string, localDate: string): boolean {
const row = db.prepare('SELECT 1 AS ok FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, timeZone, localDate);
return row !== undefined;
}
function markRan(db: Database.Database, timeZone: string, localDate: string, now: string): void {
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, timeZone, localDate, now);
}
+252
View File
@@ -0,0 +1,252 @@
import { Temporal } from '@js-temporal/polyfill';
import type Database from 'better-sqlite3';
import { writeAudit } from '../auth/audit.js';
import { purgeRateHits } from '../rate-limit.js';
import { readRetentionMonths } from '../settings.js';
import { formatInstantInZone, formatUtc } from '../time.js';
/** Central Time, once each local date, after the weekly refill hour. */
export const RETENTION_ZONE = 'America/Chicago';
export const RETENTION_LOCAL_TIME = '01:00';
/** Volunteer mail keeps its recipient and body this long after it is finished. */
export const OUTBOX_KEEP_DAYS = 30;
/** Audit rows are counts and ids. They are kept for two years, separate from signup retention. */
export const AUDIT_KEEP_MONTHS = 24;
const JOB = 'retention';
const POLL_MS = 60 * 1000;
const HOUR_MS = 60 * 60 * 1000;
export type RetentionResult = {
signups: number;
messages: number;
sessions: number;
loginTokens: number;
auditRows: number;
rateHits: number;
};
type OutboxRow = {
id: number;
signup_id: number | null;
kind: string;
status: string;
dedupe_key: string;
created_at: string;
sent_at: string | null;
delivery_unknown_at: string | null;
claimed_at: string | null;
lease_expires_at: string | null;
};
/**
* Removes personal details that are past their keep period. Safe to run more
* than once. A name is cleared in the live database only. Downloaded files,
* inboxes, and older copies of the database file are outside this cleanup.
*/
export function runRetention(db: Database.Database, now: string): RetentionResult {
const result = db.transaction((): RetentionResult => {
const signups = anonymizeSignups(db, now);
const login = purgeLoginPayloadsIn(db, now);
const auditRows = purgeAudit(db, now);
const rateHits = purgeRateHits(db, now);
const changed = signups + login.messages + login.sessions + login.loginTokens + auditRows;
if (changed > 0) {
writeAudit(db, null, 'retention.cleanup', {
signups,
messages: login.messages,
sessions: login.sessions,
loginTokens: login.loginTokens,
auditRows,
}, now);
}
return { signups, messages: login.messages, sessions: login.sessions, loginTokens: login.loginTokens, auditRows, rateHits };
}).immediate();
if (result.signups > 0) console.log(`Removed personal details from ${result.signups} old signups.`);
return result;
}
/** Sign-in links, expired sessions, and expired sign-in messages. The hourly check uses this. */
export function purgeLoginPayloads(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
return db.transaction(() => purgeLoginPayloadsIn(db, now)).immediate();
}
/**
* Runs the cleanup once per Central Time date, after 1:00. When 1:00 happens
* twice, the second hour does nothing. A start before 1:00 does not record
* the day, so the 1:00 run can still happen.
*/
export function runDueRetention(db: Database.Database, now: string): { ran: boolean; result: RetentionResult } {
const clock = formatInstantInZone(now, RETENTION_ZONE);
const empty = { signups: 0, messages: 0, sessions: 0, loginTokens: 0, auditRows: 0, rateHits: 0 };
if (clock.time24 < RETENTION_LOCAL_TIME || alreadyRan(db, clock.date)) return { ran: false, result: empty };
try {
const result = runRetention(db, now);
markRan(db, clock.date, now);
return { ran: true, result };
} catch (err) {
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
return { ran: false, result: empty };
}
}
export function startRetentionRunner(db: Database.Database, now: () => string): { stop: () => void } {
return startRunner(POLL_MS, () => {
const due = runDueRetention(db, now());
return due.ran ? due.result.messages : 0;
});
}
/** Expired sign-in messages, finished mail past 30 days, and rate-limit counters. Signup names stay on the daily run. */
export function startHourlyCleanupRunner(db: Database.Database, now: () => string): { stop: () => void } {
return startRunner(HOUR_MS, () => {
const login = purgeLoginPayloads(db, now());
purgeRateHits(db, now());
return login.messages;
});
}
function startRunner(intervalMs: number, tickBody: () => number): { stop: () => void } {
let running = false;
let stopped = false;
const tick = () => {
if (running || stopped) return;
running = true;
try {
const messages = tickBody();
if (messages > 0) console.log(`Removed personal details from ${messages} old messages.`);
} catch (err) {
console.error(err instanceof Error ? err.message : 'Retention cleanup failed.');
} finally {
running = false;
}
};
const timer = setInterval(tick, intervalMs);
timer.unref();
tick();
return {
stop() {
stopped = true;
clearInterval(timer);
},
};
}
function anonymizeSignups(db: Database.Database, now: string): number {
const months = readRetentionMonths(db);
const rows = db
.prepare(
`SELECT su.id AS id, s.ends_at_utc AS ends_at_utc, e.tz AS tz
FROM signups su
JOIN shifts s ON s.id = su.shift_id
JOIN events e ON e.id = s.event_id
WHERE su.anonymized_at IS NULL`,
)
.all() as { id: number; ends_at_utc: string; tz: string }[];
const update = 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 = ? AND anonymized_at IS NULL`,
);
let count = 0;
for (const row of rows) {
let due = false;
try {
const ended = Temporal.Instant.from(row.ends_at_utc).toZonedDateTimeISO(row.tz);
due = Temporal.Instant.compare(Temporal.Instant.from(now), ended.add({ months }).toInstant()) >= 0;
} catch {
console.error('Retention skipped a signup because its event time zone is not valid.');
continue;
}
if (!due) continue;
count += update.run(now, now, row.id).changes;
}
return count;
}
function purgeLoginPayloadsIn(db: Database.Database, now: string): Pick<RetentionResult, 'messages' | 'sessions' | 'loginTokens'> {
const messages = purgeOutbox(db, now);
const sessions = db.prepare('DELETE FROM sessions WHERE expires_at <= ?').run(now).changes;
const loginTokens = db
.prepare('DELETE FROM login_tokens WHERE used_at IS NOT NULL OR expires_at <= ?')
.run(now).changes;
return { messages, sessions, loginTokens };
}
function purgeOutbox(db: Database.Database, now: string): number {
const cutoff = formatUtc(Temporal.Instant.from(now).subtract({ hours: OUTBOX_KEEP_DAYS * 24 }));
const liveMagic = new Set(
(
db
.prepare(
`SELECT token_hash AS token_hash FROM login_tokens
WHERE used_at IS NULL AND expires_at > ?`,
)
.all(now) as { token_hash: string }[]
).map((row) => row.token_hash),
);
const anonymized = new Set(
(db.prepare('SELECT id AS id FROM signups WHERE anonymized_at IS NOT NULL').all() as { id: number }[]).map((row) => row.id),
);
const rows = db
.prepare(
`SELECT id AS id, signup_id AS signup_id, kind AS kind, status AS status, dedupe_key AS dedupe_key,
created_at AS created_at, sent_at AS sent_at, delivery_unknown_at AS delivery_unknown_at,
claimed_at AS claimed_at, lease_expires_at AS lease_expires_at
FROM outbox
WHERE dedupe_key NOT LIKE 'purged:%'`,
)
.all() as OutboxRow[];
const update = db.prepare(
`UPDATE outbox
SET dedupe_key = ?, to_email = '', subject = '', body_text = '', body_html = '',
headers_json = '{}', last_error = NULL,
status = CASE WHEN status IN ('pending', 'sending') THEN 'cancelled' ELSE status END
WHERE id = ?`,
);
let count = 0;
for (const row of rows) {
if (!messageDue(row, now, cutoff, liveMagic, anonymized)) continue;
count += update.run(`purged:${row.id}`, row.id).changes;
}
return count;
}
function messageDue(row: OutboxRow, now: string, cutoff: string, liveMagic: Set<string>, anonymized: Set<number>): boolean {
if (row.status === 'sending' && row.lease_expires_at && row.lease_expires_at > now) return false;
if (row.signup_id !== null && anonymized.has(row.signup_id)) return true;
if (row.kind === 'magic_link') {
const hash = row.dedupe_key.startsWith('magic_link:') ? row.dedupe_key.slice('magic_link:'.length) : '';
return hash.length === 0 || !liveMagic.has(hash);
}
const stamp = contentStamp(row);
return stamp !== null && stamp <= cutoff;
}
function contentStamp(row: OutboxRow): string | null {
if (row.status === 'sent') return row.sent_at ?? row.created_at;
if (row.status === 'delivery_unknown') return row.delivery_unknown_at ?? row.claimed_at ?? row.created_at;
if (row.status === 'pending' || row.status === 'sending' || row.status === 'failed' || row.status === 'cancelled') {
return row.claimed_at ?? row.created_at;
}
return row.created_at;
}
function purgeAudit(db: Database.Database, now: string): number {
const cutoff = formatUtc(
Temporal.Instant.from(now).toZonedDateTimeISO(RETENTION_ZONE).subtract({ months: AUDIT_KEEP_MONTHS }).toInstant(),
);
return db.prepare('DELETE FROM audit WHERE at <= ?').run(cutoff).changes;
}
function alreadyRan(db: Database.Database, localDate: string): boolean {
const row = db.prepare('SELECT 1 AS ready FROM job_runs WHERE job = ? AND scope = ? AND local_date = ?').get(JOB, RETENTION_ZONE, localDate);
return Boolean(row);
}
function markRan(db: Database.Database, localDate: string, now: string): void {
db.prepare('INSERT INTO job_runs (job, scope, local_date, ran_at) VALUES (?, ?, ?, ?)').run(JOB, RETENTION_ZONE, localDate, now);
}