/** * Reminder rules data layer — unit E7 (ARCHITECTURE §6.2 / §5.5 step 4). * * `enqueueRemindersForInstance` runs inside the publish transaction: for every * live assignment and every active rule, it computes `send_at` from the * instance start and enqueues the email(s). Rules whose send instant has * already passed are skipped, never back-dated. * * Enqueue is idempotent on `dedupe_key` (`reminder.friday:{assignmentId}:email`), * so republishing or a retry cannot double-book a reminder. */ import { and, eq, inArray } from "drizzle-orm"; import { db } from "@/db"; import { assignments, notificationRules, notifications, roles, serviceInstances, services, slots, users, type NotificationRuleEvent, } from "@/db/schema"; import { APP_ORIGIN } from "@/auth/magic-link"; import { notificationDedupeKey } from "@/domain/notifications"; import { planReminderSends } from "@/domain/reminders"; import { renderAssignmentReminderEmail } from "@/domain/templates"; import type { OutboxDb } from "@/db/outbox"; import { respondUrl, signRespondToken } from "@/lib/respond"; import { formatInTimezone } from "@/lib/tz"; import { uuidv7 } from "@/lib/uuid"; export interface ReminderRuleRow { id: string; key: string; event: NotificationRuleEvent; offsetDays: number; sendAtLocalTime: string; channelSet: string; appliesToServiceId: string | null; active: boolean; } /** All rules, active and inactive (the admin CRUD view). */ export async function listRules(): Promise { return db .select({ id: notificationRules.id, key: notificationRules.key, event: notificationRules.event, offsetDays: notificationRules.offsetDays, sendAtLocalTime: notificationRules.sendAtLocalTime, channelSet: notificationRules.channelSet, appliesToServiceId: notificationRules.appliesToServiceId, active: notificationRules.active, }) .from(notificationRules) .orderBy(notificationRules.offsetDays); } export async function createRule( input: Omit, ): Promise { const [row] = await db .insert(notificationRules) .values({ id: uuidv7(), key: input.key, event: input.event, offsetDays: input.offsetDays, sendAtLocalTime: input.sendAtLocalTime, channelSet: input.channelSet, appliesToServiceId: input.appliesToServiceId, active: input.active, }) .returning(); return row; } /** Patch only the fields present — no nulling out omitted columns. */ export async function updateRule( id: string, patch: Partial>, ): Promise { const [row] = await db .update(notificationRules) .set({ ...patch, updatedAt: new Date() }) .where(eq(notificationRules.id, id)) .returning(); return row ?? null; } /** * Enqueue the reminders for one instance's live assignments. Returns the number * of rows inserted (0 on a re-run or when every rule is already past). */ export async function enqueueRemindersForInstance( executor: OutboxDb, serviceInstanceId: string, opts: { now?: Date; appOrigin?: string } = {}, ): Promise { const now = opts.now ?? new Date(); const origin = opts.appOrigin ?? APP_ORIGIN; const instanceRows = await executor .select({ id: serviceInstances.id, serviceId: serviceInstances.serviceId, startsAt: serviceInstances.startsAt, timeZone: services.timezone, }) .from(serviceInstances) .innerJoin(services, eq(services.id, serviceInstances.serviceId)) .where(eq(serviceInstances.id, serviceInstanceId)) .limit(1); const instance = instanceRows[0]; if (!instance || !instance.startsAt) return 0; const rules = await executor .select({ key: notificationRules.key, offsetDays: notificationRules.offsetDays, sendAtLocalTime: notificationRules.sendAtLocalTime, channelSet: notificationRules.channelSet, active: notificationRules.active, appliesToServiceId: notificationRules.appliesToServiceId, }) .from(notificationRules) // Only assignment rules shape a service reminder. `event.reminder` belongs // to the one-off event cron; applying it here sent volunteers an extra // "event" reminder for every published Sunday. .where(eq(notificationRules.event, "assignment.created")); // Service scoping: null means every service; otherwise it must match. const applicable = rules .filter( (rule) => rule.active && (rule.appliesToServiceId === null || rule.appliesToServiceId === instance.serviceId), ) .map((rule) => ({ key: rule.key, offsetDays: rule.offsetDays, sendAtLocalTime: rule.sendAtLocalTime, channelSet: rule.channelSet, active: rule.active, })); if (applicable.length === 0) return 0; const seats = await executor .select({ assignmentId: assignments.id, slotId: slots.id, userId: users.id, email: users.email, firstName: users.firstName, timeZone: users.timezone, roleName: roles.name, serviceName: services.name, location: services.location, callTime: slots.callTime, }) .from(assignments) .innerJoin(slots, eq(slots.id, assignments.slotId)) .innerJoin(roles, eq(roles.id, slots.roleId)) .innerJoin(services, eq(services.id, instance.serviceId)) .innerJoin(users, eq(users.id, assignments.userId)) .where( and( eq(slots.serviceInstanceId, serviceInstanceId), inArray(assignments.status, ["proposed", "confirmed", "completed"]), ), ); let enqueued = 0; for (const seat of seats) { const timeZone = seat.timeZone; const planned = planReminderSends({ startsAt: instance.startsAt, timeZone, now, rules: applicable, }); const occursOnLabel = formatInTimezone(instance.startsAt, timeZone, { timeZone, weekday: "long", month: "short", day: "numeric", }); const startTimeLabel = formatInTimezone(instance.startsAt, timeZone, { timeZone, hour: "numeric", minute: "2-digit", }); const callTimeLabel = seat.callTime ? formatInTimezone(seat.callTime, timeZone, { timeZone, hour: "numeric", minute: "2-digit", }) : null; const confirm = await signRespondToken({ assignmentId: seat.assignmentId, userId: seat.userId, action: "confirm", }); const decline = await signRespondToken({ assignmentId: seat.assignmentId, userId: seat.userId, action: "decline", }); const confirmUrl = respondUrl(origin, confirm.token, "confirm"); const declineUrl = respondUrl(origin, decline.token, "decline"); const rendered = renderAssignmentReminderEmail({ volunteerFirstName: seat.firstName, roleName: seat.roleName, serviceName: seat.serviceName, occursOnLabel, startTimeLabel, callTimeLabel, location: seat.location ?? seat.serviceName, confirmUrl, declineUrl, }); for (const send of planned) { // Email is the launch channel; SMS rules wait for E5. if (!send.channels.includes("email")) continue; const inserted = await executor .insert(notifications) .values({ id: uuidv7(), userId: seat.userId, channel: "email", templateKey: `reminder.${send.ruleKey}`, ruleKey: send.ruleKey, assignmentId: seat.assignmentId, slotId: seat.slotId, toAddress: seat.email, payloadJson: JSON.stringify({ subject: rendered.subject, html: rendered.html, text: rendered.text, confirmUrl, declineUrl, }), dedupeKey: notificationDedupeKey( `reminder.${send.ruleKey}`, seat.assignmentId, "email", ), scheduledFor: send.sendAt, status: "queued", attempts: 0, createdAt: now, }) .onConflictDoNothing({ target: notifications.dedupeKey }) .returning({ id: notifications.id }); enqueued += inserted.length; } } return enqueued; }