332 lines
9.9 KiB
TypeScript
332 lines
9.9 KiB
TypeScript
/**
|
|
* Notification outbox — unit E1 (ARCHITECTURE §6.1).
|
|
*
|
|
* The queue is a table. `enqueuePublishNotifications` is called inside the D10
|
|
* publish transaction, so a published week and its mail succeed or fail
|
|
* together. Enqueue is idempotent on `dedupe_key`: the same event twice is one
|
|
* row (`ON CONFLICT DO NOTHING`), which is what makes a re-run safe.
|
|
*
|
|
* Nothing is sent here; the dispatcher (E2) drains the table.
|
|
*/
|
|
|
|
import { and, desc, eq, inArray, sql } from "drizzle-orm";
|
|
import { db } from "@/db";
|
|
import {
|
|
assignments,
|
|
notificationPreferences,
|
|
notifications,
|
|
roles,
|
|
serviceInstances,
|
|
services,
|
|
slots,
|
|
users,
|
|
type NotificationStatus,
|
|
} from "@/db/schema";
|
|
import { APP_ORIGIN } from "@/auth/magic-link";
|
|
import { notificationDedupeKey } from "@/domain/notifications";
|
|
import { renderAssignmentPublishedEmail } from "@/domain/templates";
|
|
import { respondUrl, signRespondToken } from "@/lib/respond";
|
|
import { formatInTimezone } from "@/lib/tz";
|
|
import { uuidv7 } from "@/lib/uuid";
|
|
|
|
/**
|
|
* Minimal query surface shared by the Drizzle client and a transaction, so the
|
|
* enqueue can run inside the publish transaction without a second connection.
|
|
*/
|
|
export interface OutboxDb {
|
|
readonly insert: typeof db.insert;
|
|
readonly select: typeof db.select;
|
|
readonly update: typeof db.update;
|
|
}
|
|
|
|
const ACTIVE_ASSIGNMENT_SQL = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
|
|
|
/**
|
|
* Enqueue the `assignment.published` email for every live assignment on an
|
|
* instance. Returns the number of rows actually inserted (0 on a re-run).
|
|
*/
|
|
export async function enqueuePublishNotifications(
|
|
executor: OutboxDb,
|
|
serviceInstanceId: string,
|
|
opts: { now?: Date; appOrigin?: string } = {},
|
|
): Promise<number> {
|
|
const now = opts.now ?? new Date();
|
|
const origin = opts.appOrigin ?? APP_ORIGIN;
|
|
|
|
const rows = await executor
|
|
.select({
|
|
assignmentId: assignments.id,
|
|
slotId: slots.id,
|
|
userId: users.id,
|
|
email: users.email,
|
|
firstName: users.firstName,
|
|
displayName: users.displayName,
|
|
timeZone: users.timezone,
|
|
roleName: roles.name,
|
|
serviceName: services.name,
|
|
location: services.location,
|
|
startsAt: serviceInstances.startsAt,
|
|
callTime: slots.callTime,
|
|
})
|
|
.from(assignments)
|
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
|
.innerJoin(roles, eq(roles.id, slots.roleId))
|
|
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
|
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
|
.innerJoin(users, eq(users.id, assignments.userId))
|
|
.where(
|
|
and(
|
|
eq(slots.serviceInstanceId, serviceInstanceId),
|
|
ACTIVE_ASSIGNMENT_SQL,
|
|
),
|
|
)
|
|
.orderBy(slots.slotIndex);
|
|
|
|
let enqueued = 0;
|
|
for (const row of rows) {
|
|
if (!row.startsAt) continue;
|
|
const timeZone = row.timeZone;
|
|
const occursOnLabel = formatInTimezone(row.startsAt, timeZone, {
|
|
timeZone,
|
|
weekday: "long",
|
|
month: "short",
|
|
day: "numeric",
|
|
});
|
|
const startTimeLabel = formatInTimezone(row.startsAt, timeZone, {
|
|
timeZone,
|
|
hour: "numeric",
|
|
minute: "2-digit",
|
|
});
|
|
const callTimeLabel = row.callTime
|
|
? formatInTimezone(row.callTime, timeZone, {
|
|
timeZone,
|
|
hour: "numeric",
|
|
minute: "2-digit",
|
|
})
|
|
: null;
|
|
|
|
// Two single-purpose links per assignment (E4): confirm and decline.
|
|
const confirm = await signRespondToken({
|
|
assignmentId: row.assignmentId,
|
|
userId: row.userId,
|
|
action: "confirm",
|
|
});
|
|
const decline = await signRespondToken({
|
|
assignmentId: row.assignmentId,
|
|
userId: row.userId,
|
|
action: "decline",
|
|
});
|
|
const confirmUrl = respondUrl(origin, confirm.token, "confirm");
|
|
const declineUrl = respondUrl(origin, decline.token, "decline");
|
|
|
|
const rendered = renderAssignmentPublishedEmail({
|
|
volunteerFirstName: row.firstName,
|
|
roleName: row.roleName,
|
|
serviceName: row.serviceName,
|
|
occursOnLabel,
|
|
startTimeLabel,
|
|
callTimeLabel,
|
|
location: row.location ?? row.serviceName,
|
|
confirmUrl,
|
|
declineUrl,
|
|
});
|
|
|
|
const inserted = await executor
|
|
.insert(notifications)
|
|
.values({
|
|
id: uuidv7(),
|
|
userId: row.userId,
|
|
channel: "email",
|
|
templateKey: "assignment.published",
|
|
ruleKey: null,
|
|
assignmentId: row.assignmentId,
|
|
slotId: row.slotId,
|
|
toAddress: row.email,
|
|
payloadJson: JSON.stringify({
|
|
subject: rendered.subject,
|
|
html: rendered.html,
|
|
text: rendered.text,
|
|
confirmUrl,
|
|
declineUrl,
|
|
}),
|
|
dedupeKey: notificationDedupeKey(
|
|
"assignment.published",
|
|
row.assignmentId,
|
|
"email",
|
|
),
|
|
scheduledFor: now,
|
|
status: "queued",
|
|
attempts: 0,
|
|
createdAt: now,
|
|
})
|
|
.onConflictDoNothing({ target: notifications.dedupeKey })
|
|
.returning({ id: notifications.id });
|
|
|
|
enqueued += inserted.length;
|
|
}
|
|
|
|
return enqueued;
|
|
}
|
|
|
|
/**
|
|
* Cancel an assignment's pending mail — a declined assignment must not keep a
|
|
* "you're serving" reminder queued (§6.1 `cancel-if-declined`). Sent rows are
|
|
* left alone. Returns the number of rows cancelled.
|
|
*/
|
|
export async function cancelAssignmentNotifications(
|
|
assignmentId: string,
|
|
now: Date = new Date(),
|
|
executor: OutboxDb = db,
|
|
): Promise<number> {
|
|
const cancelled = await executor
|
|
.update(notifications)
|
|
.set({ status: "cancelled", updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(notifications.assignmentId, assignmentId),
|
|
inArray(notifications.status, ["queued", "failed"]),
|
|
),
|
|
)
|
|
.returning({ id: notifications.id });
|
|
return cancelled.length;
|
|
}
|
|
|
|
/**
|
|
* Cancel every pending message for an instance's assignments. Used when a week
|
|
* is unpublished: its queued reminders and assignment mail must not fire for a
|
|
* schedule that is no longer published.
|
|
*/
|
|
export async function cancelInstanceNotifications(
|
|
instanceId: string,
|
|
now: Date = new Date(),
|
|
executor: OutboxDb = db,
|
|
): Promise<number> {
|
|
const rows = await executor
|
|
.select({ assignmentId: assignments.id })
|
|
.from(assignments)
|
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
|
.where(eq(slots.serviceInstanceId, instanceId));
|
|
if (rows.length === 0) return 0;
|
|
|
|
const cancelled = await executor
|
|
.update(notifications)
|
|
.set({ status: "cancelled", updatedAt: now })
|
|
.where(
|
|
and(
|
|
inArray(
|
|
notifications.assignmentId,
|
|
rows.map((row) => row.assignmentId),
|
|
),
|
|
inArray(notifications.status, ["queued", "failed"]),
|
|
),
|
|
)
|
|
.returning({ id: notifications.id });
|
|
return cancelled.length;
|
|
}
|
|
|
|
export interface NotificationLogRow {
|
|
id: string;
|
|
userId: string;
|
|
channel: string;
|
|
templateKey: string;
|
|
status: NotificationStatus;
|
|
attempts: number;
|
|
toAddress: string;
|
|
dedupeKey: string;
|
|
scheduledFor: Date;
|
|
sentAt: Date | null;
|
|
error: string | null;
|
|
assignmentId: string | null;
|
|
assignmentStatus: string | null;
|
|
payload: Record<string, unknown>;
|
|
}
|
|
|
|
/** The admin notification log (newest first), with the assignment's status. */
|
|
export async function listNotifications(
|
|
opts: { status?: NotificationStatus; limit?: number } = {},
|
|
): Promise<NotificationLogRow[]> {
|
|
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
|
|
const rows = await db
|
|
.select({
|
|
id: notifications.id,
|
|
userId: notifications.userId,
|
|
channel: notifications.channel,
|
|
templateKey: notifications.templateKey,
|
|
status: notifications.status,
|
|
attempts: notifications.attempts,
|
|
toAddress: notifications.toAddress,
|
|
dedupeKey: notifications.dedupeKey,
|
|
scheduledFor: notifications.scheduledFor,
|
|
sentAt: notifications.sentAt,
|
|
error: notifications.error,
|
|
assignmentId: notifications.assignmentId,
|
|
assignmentStatus: assignments.status,
|
|
payloadJson: notifications.payloadJson,
|
|
})
|
|
.from(notifications)
|
|
.leftJoin(assignments, eq(assignments.id, notifications.assignmentId))
|
|
.where(opts.status ? eq(notifications.status, opts.status) : undefined)
|
|
.orderBy(desc(notifications.createdAt))
|
|
.limit(limit);
|
|
|
|
return rows.map((row) => ({
|
|
id: row.id,
|
|
userId: row.userId,
|
|
channel: row.channel,
|
|
templateKey: row.templateKey,
|
|
status: row.status,
|
|
attempts: row.attempts,
|
|
toAddress: row.toAddress,
|
|
dedupeKey: row.dedupeKey,
|
|
scheduledFor: row.scheduledFor,
|
|
sentAt: row.sentAt,
|
|
error: row.error,
|
|
assignmentId: row.assignmentId,
|
|
assignmentStatus: row.assignmentStatus,
|
|
payload: safeParsePayload(row.payloadJson),
|
|
}));
|
|
}
|
|
|
|
function safeParsePayload(json: string): Record<string, unknown> {
|
|
try {
|
|
return JSON.parse(json) as Record<string, unknown>;
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Re-queue a failed (or suppressed) row for an immediate retry — the admin
|
|
* log's "retry" action (E6). Terminal `sent`/`cancelled` rows are left alone.
|
|
* Returns null when the row does not exist.
|
|
*/
|
|
export async function retryNotification(
|
|
id: string,
|
|
now: Date = new Date(),
|
|
): Promise<{ id: string; status: string } | null> {
|
|
// Only recoverable states can be retried. `sent` and `cancelled` are
|
|
// terminal — requeuing them would send a message twice or resurrect one the
|
|
// team deliberately cancelled.
|
|
const [row] = await db
|
|
.update(notifications)
|
|
.set({ status: "queued", scheduledFor: now, error: null, updatedAt: now })
|
|
.where(
|
|
and(
|
|
eq(notifications.id, id),
|
|
inArray(notifications.status, ["failed", "suppressed"]),
|
|
),
|
|
)
|
|
.returning({ id: notifications.id, status: notifications.status });
|
|
return row ?? null;
|
|
}
|
|
|
|
/** Read one user's notification preferences (defaults when absent). */
|
|
export async function getNotificationPrefs(userId: string) {
|
|
const rows = await db
|
|
.select()
|
|
.from(notificationPreferences)
|
|
.where(eq(notificationPreferences.userId, userId))
|
|
.limit(1);
|
|
return rows[0] ?? null;
|
|
}
|