push to maple-street
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Admin read models — the people list behind /admin and /roster.
|
||||
*
|
||||
* Server-only data layer (no JSX). The admin page is a server component that
|
||||
* fetches these rows and passes serialisable props to the client action
|
||||
* panels, so the roster and the admin table never disagree about a user.
|
||||
*/
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { users } from "@/db/schema";
|
||||
|
||||
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||
|
||||
export interface AdminUserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string;
|
||||
systemRole: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every user, with the ones that need attention first: pending invites, then
|
||||
* invited, active, inactive, and finally denied. Alphabetical within a group.
|
||||
*/
|
||||
export async function listUsers(): Promise<AdminUserRow[]> {
|
||||
const statusRank = sql`CASE ${users.status}
|
||||
WHEN 'pending_approval' THEN 0
|
||||
WHEN 'invited' THEN 1
|
||||
WHEN 'active' THEN 2
|
||||
WHEN 'inactive' THEN 3
|
||||
ELSE 4
|
||||
END`;
|
||||
|
||||
return db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
displayName: userName,
|
||||
systemRole: users.systemRole,
|
||||
status: users.status,
|
||||
})
|
||||
.from(users)
|
||||
.orderBy(statusRank, users.lastName, users.firstName);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Team announcements (admin/coordinator authored).
|
||||
*
|
||||
* Reads join the author for display; drafts are returned only to a caller that
|
||||
* holds `content.author`. Plain text bodies for now — the rich-text editor is a
|
||||
* separate phase, and rendering user text must never become raw HTML.
|
||||
*/
|
||||
|
||||
import { desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { announcements, users } from "@/db/schema";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||
|
||||
export interface AnnouncementRow {
|
||||
id: string;
|
||||
title: string;
|
||||
body: string;
|
||||
published: boolean;
|
||||
authorName: string | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date | null;
|
||||
}
|
||||
|
||||
export async function listAnnouncements(
|
||||
opts: { includeUnpublished?: boolean } = {},
|
||||
): Promise<AnnouncementRow[]> {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: announcements.id,
|
||||
title: announcements.title,
|
||||
body: announcements.body,
|
||||
published: announcements.published,
|
||||
authorName: userName,
|
||||
createdAt: announcements.createdAt,
|
||||
updatedAt: announcements.updatedAt,
|
||||
})
|
||||
.from(announcements)
|
||||
.leftJoin(users, eq(users.id, announcements.createdBy))
|
||||
.where(opts.includeUnpublished ? undefined : eq(announcements.published, true))
|
||||
.orderBy(desc(announcements.createdAt));
|
||||
|
||||
return rows.map((row) => ({
|
||||
...row,
|
||||
authorName: row.authorName ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function createAnnouncement(input: {
|
||||
title: string;
|
||||
body: string;
|
||||
published: boolean;
|
||||
createdBy: string;
|
||||
}) {
|
||||
const [row] = await db
|
||||
.insert(announcements)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
title: input.title,
|
||||
body: input.body,
|
||||
published: input.published,
|
||||
createdBy: input.createdBy,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateAnnouncement(
|
||||
id: string,
|
||||
patch: { title?: string; body?: string; published?: boolean },
|
||||
) {
|
||||
const values: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (patch.title !== undefined) values.title = patch.title;
|
||||
if (patch.body !== undefined) values.body = patch.body;
|
||||
if (patch.published !== undefined) values.published = patch.published;
|
||||
|
||||
const [row] = await db
|
||||
.update(announcements)
|
||||
.set(values)
|
||||
.where(eq(announcements.id, id))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function deleteAnnouncement(id: string) {
|
||||
const [row] = await db
|
||||
.delete(announcements)
|
||||
.where(eq(announcements.id, id))
|
||||
.returning({ id: announcements.id });
|
||||
return row ?? null;
|
||||
}
|
||||
+268
-7
@@ -1,8 +1,23 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { assignments } from "@/db/schema";
|
||||
import { and, eq, gte, inArray, lt, ne, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
positionSkills,
|
||||
serviceInstances,
|
||||
skills,
|
||||
slots,
|
||||
unavailability,
|
||||
userSkills,
|
||||
users,
|
||||
type SkillLevel,
|
||||
} from "@/db/schema";
|
||||
import { computeReadiness } from "@/domain/readiness";
|
||||
import { isMentorReady } from "@/domain/mentor";
|
||||
import type { ConflictInput } from "@/domain/conflicts";
|
||||
import { CHURCH_TIMEZONE, dateInTimezone, localToUtc } from "@/lib/tz";
|
||||
|
||||
/**
|
||||
* Assignment queries — unit D8.
|
||||
* Assignment queries — units D8/D5 integration.
|
||||
*
|
||||
* `activeAssignmentInInstance` returns a volunteer's single active assignment
|
||||
* within one service instance, or null. It keys on the instance id rather than
|
||||
@@ -10,7 +25,6 @@ import { assignments } from "@/db/schema";
|
||||
* instance", and a volunteer may serve two different instances on the same day
|
||||
* (e.g. both Sunday services). A date range would wrongly block that.
|
||||
*/
|
||||
|
||||
export interface ActiveAssignment {
|
||||
id: string;
|
||||
slotId: string;
|
||||
@@ -18,11 +32,13 @@ export interface ActiveAssignment {
|
||||
status: string;
|
||||
}
|
||||
|
||||
const ACTIVE_STATUSES = ["proposed", "confirmed", "completed"] as const;
|
||||
|
||||
export async function activeAssignmentInInstance(
|
||||
db: typeof import("@/db").db,
|
||||
dbc: typeof import("@/db").db,
|
||||
input: { userId: string; instanceId: string },
|
||||
): Promise<ActiveAssignment | null> {
|
||||
const rows = await db
|
||||
const rows = await dbc
|
||||
.select({
|
||||
id: assignments.id,
|
||||
slotId: assignments.slotId,
|
||||
@@ -34,9 +50,254 @@ export async function activeAssignmentInInstance(
|
||||
and(
|
||||
eq(assignments.userId, input.userId),
|
||||
sql`${assignments.slotId} IN (SELECT id FROM slots WHERE service_instance_id = ${input.instanceId})`,
|
||||
sql`${assignments.status} IN ('proposed','confirmed','completed')`,
|
||||
inArray(assignments.status, [...ACTIVE_STATUSES]),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export class AssignFactError extends Error {
|
||||
constructor(
|
||||
readonly code: "unknown_slot" | "slot_without_instance" | "unknown_user",
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "AssignFactError";
|
||||
}
|
||||
}
|
||||
|
||||
function isoDateUTC(date: Date | null): string {
|
||||
if (!date) return "";
|
||||
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve every fact the pure conflict engine needs for one (volunteer, slot)
|
||||
* pair. The route then calls `classifyConflicts` and rejects on hard conflicts,
|
||||
* so manual assignment enforces the same rules auto-fill does.
|
||||
*/
|
||||
export async function resolveAssignFacts(input: {
|
||||
userId: string;
|
||||
slotId: string;
|
||||
maxServicesPerMonth?: number;
|
||||
}): Promise<ConflictInput> {
|
||||
const slotRows = await db
|
||||
.select({
|
||||
slotId: slots.id,
|
||||
roleId: slots.roleId,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
pairedWithUserId: slots.pairedWithUserId,
|
||||
serviceInstanceId: slots.serviceInstanceId,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
})
|
||||
.from(slots)
|
||||
.leftJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(eq(slots.id, input.slotId))
|
||||
.limit(1);
|
||||
|
||||
const slot = slotRows[0];
|
||||
if (!slot) throw new AssignFactError("unknown_slot", "unknown slot");
|
||||
if (!slot.serviceInstanceId) {
|
||||
throw new AssignFactError(
|
||||
"slot_without_instance",
|
||||
"slot is not attached to a service instance",
|
||||
);
|
||||
}
|
||||
|
||||
const [user] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, input.userId))
|
||||
.limit(1);
|
||||
if (!user) throw new AssignFactError("unknown_user", "unknown user");
|
||||
|
||||
const positionRows = await db
|
||||
.select({
|
||||
skillId: positionSkills.skillId,
|
||||
requiredLevel: positionSkills.requiredLevel,
|
||||
isCore: positionSkills.isCore,
|
||||
weight: positionSkills.weight,
|
||||
skillName: skills.name,
|
||||
staleAfterDays: skills.staleAfterDays,
|
||||
mentorMinLevel: skills.mentorMinLevel,
|
||||
})
|
||||
.from(positionSkills)
|
||||
.innerJoin(skills, eq(skills.id, positionSkills.skillId))
|
||||
.where(eq(positionSkills.positionId, slot.roleId));
|
||||
|
||||
const compRows = await db
|
||||
.select({
|
||||
skillId: userSkills.skillId,
|
||||
verifiedLevel: userSkills.verifiedLevel,
|
||||
selfComfort: userSkills.selfComfort,
|
||||
lastServedOn: userSkills.lastServedOn,
|
||||
mentorOptIn: userSkills.mentorOptIn,
|
||||
mentorApprovedAt: userSkills.mentorApprovedAt,
|
||||
})
|
||||
.from(userSkills)
|
||||
.where(eq(userSkills.userId, input.userId));
|
||||
|
||||
const compBySkill = new Map(compRows.map((row) => [row.skillId, row]));
|
||||
|
||||
const occursOn = isoDateUTC(slot.occursOn);
|
||||
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
|
||||
|
||||
const blackouts = await db
|
||||
.select()
|
||||
.from(unavailability)
|
||||
.where(
|
||||
and(
|
||||
eq(unavailability.userId, input.userId),
|
||||
eq(unavailability.status, "active"),
|
||||
),
|
||||
);
|
||||
|
||||
const monthStart = new Date(`${occursOn}T00:00:00Z`);
|
||||
const monthEnd = new Date(`${occursOn}T00:00:00Z`);
|
||||
monthEnd.setUTCMonth(monthEnd.getUTCMonth() + 1);
|
||||
const [monthRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, input.userId),
|
||||
inArray(assignments.status, [...ACTIVE_STATUSES]),
|
||||
gte(serviceInstances.startsAt, monthStart),
|
||||
lt(serviceInstances.startsAt, monthEnd),
|
||||
),
|
||||
);
|
||||
|
||||
// "Already serves the other service that morning" — any other instance on
|
||||
// the same local date that starts before noon (church time).
|
||||
const noon = localToUtc(occursOn, "12:00", CHURCH_TIMEZONE);
|
||||
const [otherMorning] = await db
|
||||
.select({ id: serviceInstances.id })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, input.userId),
|
||||
inArray(assignments.status, [...ACTIVE_STATUSES]),
|
||||
ne(serviceInstances.id, slot.serviceInstanceId),
|
||||
eq(serviceInstances.occursOn, slot.occursOn!),
|
||||
lt(serviceInstances.startsAt, noon),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
const existing = await activeAssignmentInInstance(db, {
|
||||
userId: input.userId,
|
||||
instanceId: slot.serviceInstanceId,
|
||||
});
|
||||
|
||||
const coreSkills = positionRows
|
||||
.filter((row) => row.isCore)
|
||||
.map((row) => ({
|
||||
name: row.skillName,
|
||||
requiredLevel: (row.requiredLevel ?? "none") as SkillLevel,
|
||||
verifiedLevel: (compBySkill.get(row.skillId)?.verifiedLevel ??
|
||||
"none") as SkillLevel,
|
||||
}));
|
||||
|
||||
const coreComforts = positionRows
|
||||
.filter((row) => row.isCore)
|
||||
.map((row) => compBySkill.get(row.skillId)?.selfComfort)
|
||||
.filter((value): value is number => value != null);
|
||||
|
||||
const lastServed = positionRows
|
||||
.filter((row) => row.isCore)
|
||||
.map((row) => compBySkill.get(row.skillId)?.lastServedOn)
|
||||
.filter((value): value is string => value != null)
|
||||
.sort()
|
||||
.at(0);
|
||||
|
||||
const readiness = computeReadiness(
|
||||
positionRows.map((row) => ({
|
||||
name: row.skillName,
|
||||
isCore: row.isCore,
|
||||
requiredLevel: (row.requiredLevel ?? "none") as SkillLevel,
|
||||
weight: row.weight,
|
||||
verifiedLevel: (compBySkill.get(row.skillId)?.verifiedLevel ??
|
||||
"none") as SkillLevel,
|
||||
selfComfort: compBySkill.get(row.skillId)?.selfComfort ?? null,
|
||||
})),
|
||||
);
|
||||
|
||||
// Paired mentor readiness for the first core skill (the shadow rule).
|
||||
let pairedMentor: ConflictInput["pairedMentor"] = null;
|
||||
if (slot.pairedWithUserId) {
|
||||
const mentorSkill = positionRows.find((row) => row.isCore) ?? positionRows[0];
|
||||
if (mentorSkill) {
|
||||
const [mentor] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, slot.pairedWithUserId))
|
||||
.limit(1);
|
||||
const [mentorComp] = await db
|
||||
.select()
|
||||
.from(userSkills)
|
||||
.where(
|
||||
and(
|
||||
eq(userSkills.userId, slot.pairedWithUserId),
|
||||
eq(userSkills.skillId, mentorSkill.skillId),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (mentor) {
|
||||
pairedMentor = {
|
||||
verifiedLevel: (mentorComp?.verifiedLevel ?? "none") as SkillLevel,
|
||||
mentorMinLevel: mentorSkill.mentorMinLevel,
|
||||
mentorOptIn: mentorComp?.mentorOptIn ?? false,
|
||||
adminApproved:
|
||||
mentor.status === "active" &&
|
||||
!mentor.deactivatedAt &&
|
||||
mentorComp?.mentorApprovedAt != null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
userStatus: user.status,
|
||||
adminApproved: user.status === "active" && !user.deactivatedAt,
|
||||
alreadyAssignedInInstance: existing != null,
|
||||
coreSkills,
|
||||
isShadowSlot: slot.isTraineeSlot,
|
||||
pairedMentor,
|
||||
occursOn,
|
||||
unavailability: blackouts.map((rec) => ({
|
||||
id: rec.id,
|
||||
userId: rec.userId,
|
||||
kind: rec.kind,
|
||||
startsOn: rec.startsOn,
|
||||
endsOn: rec.endsOn,
|
||||
allDay: rec.allDay,
|
||||
reason: rec.reason,
|
||||
rrule: rec.rrule,
|
||||
status: rec.status,
|
||||
createdAt: rec.createdAt ?? new Date(),
|
||||
createdBy: rec.createdBy,
|
||||
})),
|
||||
monthlyServiceCount: Number(monthRow?.count ?? 0),
|
||||
maxServicesPerMonth: input.maxServicesPerMonth ?? 3,
|
||||
servesOtherServiceThatMorning: otherMorning != null,
|
||||
coreComfortLow: coreComforts.length ? Math.min(...coreComforts) : null,
|
||||
lastServedOn: lastServed ?? null,
|
||||
staleAfterDays: Math.min(
|
||||
...positionRows.map((row) => row.staleAfterDays ?? 120),
|
||||
),
|
||||
today,
|
||||
readinessScore: readiness.score,
|
||||
readinessWarnThreshold: 50,
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-export so callers can type-check the mentor flag consistently. */
|
||||
export { isMentorReady };
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
/**
|
||||
* Auto-fill data layer — unit D9.
|
||||
*
|
||||
* Resolves the facts the pure `autoFill()` (src/domain/autoFill.ts) needs for
|
||||
* one service instance and calls it. The domain module is pure; this module is
|
||||
* the only place that touches the DB, so the algorithm stays unit-testable and
|
||||
* the joins stay here.
|
||||
*
|
||||
* It resolves, per instance:
|
||||
* - the instance's open seats (slots with `status = 'open'`),
|
||||
* - each seat's role `position_skills` (the requirements),
|
||||
* - every active volunteer's competency (`user_skills`), active blackouts,
|
||||
* roster status, and how many services they already hold this month.
|
||||
*
|
||||
* The route (D9) calls `computeAutoFill()` for the preview and
|
||||
* `applyAutoFill()` for the write.
|
||||
*/
|
||||
|
||||
import { and, eq, gte, inArray, lt, notExists, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
positionSkills,
|
||||
roles,
|
||||
serviceInstances,
|
||||
skills,
|
||||
slots,
|
||||
unavailability,
|
||||
userSkills,
|
||||
users,
|
||||
type SkillLevel,
|
||||
} from "@/db/schema";
|
||||
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
|
||||
import { isMentorReady } from "@/domain/mentor";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
||||
|
||||
/** A slot the auto-filler can propose for, with its role's requirements. */
|
||||
interface AutoFillSlotRow {
|
||||
id: string;
|
||||
roleId: string;
|
||||
roleName: string;
|
||||
slotIndex: number;
|
||||
occursOn: string;
|
||||
isTraineeSlot: boolean;
|
||||
skills: {
|
||||
skillId: string;
|
||||
name: string;
|
||||
requiredLevel: string | null;
|
||||
isCore: boolean;
|
||||
weight: number;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** A volunteer's resolved competency for one skill. */
|
||||
interface CompetencyRow {
|
||||
skillId: string;
|
||||
verifiedLevel: string;
|
||||
selfComfort: number | null;
|
||||
lastServedOn: string | null;
|
||||
staleAfterDays: number;
|
||||
mentorReady: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* A `date`-mode column comes back as a UTC-midnight instant, so the calendar
|
||||
* date is its **UTC** date. Reading local getters here would shift a day early
|
||||
* in a negative-offset zone (the same trap D7 hit with the grid).
|
||||
*/
|
||||
function isoDateUTC(d: Date): string {
|
||||
return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
d.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute auto-fill proposals for one instance. Returns the proposals and the
|
||||
* unfilled seats. Throws when the instance id is unknown.
|
||||
*/
|
||||
export async function computeAutoFill(
|
||||
serviceInstanceId: string,
|
||||
opts: { maxServicesPerMonth?: number } = {},
|
||||
): Promise<AutoFillResult> {
|
||||
const instance = await db
|
||||
.select()
|
||||
.from(serviceInstances)
|
||||
.where(eq(serviceInstances.id, serviceInstanceId))
|
||||
.limit(1);
|
||||
if (instance.length === 0) {
|
||||
throw new Error(`unknown service instance: ${serviceInstanceId}`);
|
||||
}
|
||||
const instanceRow = instance[0];
|
||||
if (!instanceRow.occursOn) {
|
||||
throw new Error(`service instance has no occurs_on: ${serviceInstanceId}`);
|
||||
}
|
||||
const occursOn = isoDateUTC(instanceRow.occursOn);
|
||||
|
||||
// Open seats with their role requirements. A seat counts as open only when no
|
||||
// active assignment holds it: `slots.status` is derived and is not maintained
|
||||
// by the assignment writes (D8), so a confirmed seat can still read 'open'.
|
||||
// Without this the seed's pre-assigned Audio seat would be proposed again and
|
||||
// `applyAutoFill` would silently skip it (written < proposals).
|
||||
const slotRows = await db
|
||||
.select({
|
||||
id: slots.id,
|
||||
roleId: slots.roleId,
|
||||
slotIndex: slots.slotIndex,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
roleName: roles.name,
|
||||
skillId: positionSkills.skillId,
|
||||
skillName: skills.name,
|
||||
requiredLevel: positionSkills.requiredLevel,
|
||||
isCore: positionSkills.isCore,
|
||||
weight: positionSkills.weight,
|
||||
})
|
||||
.from(slots)
|
||||
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||
.leftJoin(positionSkills, eq(positionSkills.positionId, slots.roleId))
|
||||
.leftJoin(skills, eq(skills.id, positionSkills.skillId))
|
||||
.where(
|
||||
and(
|
||||
eq(slots.serviceInstanceId, serviceInstanceId),
|
||||
eq(slots.status, "open"),
|
||||
notExists(
|
||||
db
|
||||
.select({ one: sql`1` })
|
||||
.from(assignments)
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.slotId, slots.id),
|
||||
ACTIVE_ASSIGNMENT_STATUS,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.orderBy(slots.slotIndex);
|
||||
|
||||
const slotsBySlotId = new Map<string, AutoFillSlotRow>();
|
||||
for (const row of slotRows) {
|
||||
const entry = {
|
||||
skillId: row.skillId ?? "",
|
||||
name: row.skillName ?? "",
|
||||
requiredLevel: row.requiredLevel,
|
||||
isCore: row.isCore ?? false,
|
||||
weight: row.weight ?? 1,
|
||||
};
|
||||
const existing = slotsBySlotId.get(row.id);
|
||||
if (existing) {
|
||||
existing.skills.push(entry);
|
||||
continue;
|
||||
}
|
||||
slotsBySlotId.set(row.id, {
|
||||
id: row.id,
|
||||
roleId: row.roleId,
|
||||
roleName: row.roleName,
|
||||
slotIndex: row.slotIndex,
|
||||
occursOn,
|
||||
isTraineeSlot: row.isTraineeSlot,
|
||||
skills: row.skillId ? [entry] : [],
|
||||
});
|
||||
}
|
||||
const slotInputs = [...slotsBySlotId.values()];
|
||||
|
||||
// Active volunteers.
|
||||
const userRows = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.status, "active"))
|
||||
.orderBy(users.lastName, users.firstName);
|
||||
const userIds = userRows.map((u) => u.id);
|
||||
|
||||
// Competency per user, keyed by userId -> skillId. Joins user_skills to the
|
||||
// skill for stale_after_days and mentor_min_level (which drive the
|
||||
// CandidateSkill.staleAfterDays and mentorReady fields).
|
||||
const competencyByUser = new Map<string, Map<string, CompetencyRow>>();
|
||||
if (userIds.length) {
|
||||
const competencyRows = await db
|
||||
.select({
|
||||
userId: userSkills.userId,
|
||||
skillId: userSkills.skillId,
|
||||
verifiedLevel: userSkills.verifiedLevel,
|
||||
selfComfort: userSkills.selfComfort,
|
||||
lastServedOn: userSkills.lastServedOn,
|
||||
mentorOptIn: userSkills.mentorOptIn,
|
||||
mentorApprovedAt: userSkills.mentorApprovedAt,
|
||||
staleAfterDays: skills.staleAfterDays,
|
||||
mentorMinLevel: skills.mentorMinLevel,
|
||||
})
|
||||
.from(userSkills)
|
||||
.innerJoin(skills, eq(skills.id, userSkills.skillId))
|
||||
.where(inArray(userSkills.userId, userIds));
|
||||
for (const row of competencyRows) {
|
||||
let bySkill = competencyByUser.get(row.userId);
|
||||
if (!bySkill) {
|
||||
bySkill = new Map();
|
||||
competencyByUser.set(row.userId, bySkill);
|
||||
}
|
||||
bySkill.set(row.skillId, {
|
||||
skillId: row.skillId,
|
||||
verifiedLevel: row.verifiedLevel,
|
||||
selfComfort: row.selfComfort,
|
||||
// `last_served_on` is a date column in string mode (YYYY-MM-DD).
|
||||
lastServedOn: row.lastServedOn ?? null,
|
||||
staleAfterDays: row.staleAfterDays ?? 120,
|
||||
mentorReady: isMentorReady({
|
||||
verifiedLevel: row.verifiedLevel,
|
||||
mentorMinLevel: row.mentorMinLevel,
|
||||
mentorOptIn: row.mentorOptIn,
|
||||
// Explicit admin sign-off, persisted on the competency record (C5).
|
||||
adminApproved: row.mentorApprovedAt != null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Active blackouts per user.
|
||||
const unavailabilityByUser = new Map<string, (typeof unavailability.$inferSelect)[]>();
|
||||
if (userIds.length) {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(unavailability)
|
||||
.where(
|
||||
and(
|
||||
inArray(unavailability.userId, userIds),
|
||||
eq(unavailability.status, "active"),
|
||||
),
|
||||
);
|
||||
for (const rec of rows) {
|
||||
const list = unavailabilityByUser.get(rec.userId) ?? [];
|
||||
list.push(rec);
|
||||
unavailabilityByUser.set(rec.userId, list);
|
||||
}
|
||||
}
|
||||
|
||||
// Monthly service count per user in the instance's month. Join through the
|
||||
// slot to the instance so we count every service the volunteer holds that
|
||||
// month, not just seats in this instance. Month boundaries are computed in
|
||||
// JS (from the instance's local date) rather than EXTRACT, which the
|
||||
// timestamptz column rejects.
|
||||
const monthStart = new Date(`${occursOn}T00:00:00Z`);
|
||||
const monthEnd = new Date(`${occursOn}T00:00:00Z`);
|
||||
monthEnd.setMonth(monthEnd.getMonth() + 1);
|
||||
const countRows = await db
|
||||
.select({ userId: assignments.userId, count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
ACTIVE_ASSIGNMENT_STATUS,
|
||||
gte(serviceInstances.startsAt, monthStart),
|
||||
lt(serviceInstances.startsAt, monthEnd),
|
||||
),
|
||||
)
|
||||
.groupBy(assignments.userId);
|
||||
const countByUser = new Map(
|
||||
countRows.map((r) => [r.userId, Number(r.count ?? 0)]),
|
||||
);
|
||||
|
||||
// Build the candidate inputs.
|
||||
const candidates = userRows.map((user) => {
|
||||
const bySkill = competencyByUser.get(user.id) ?? new Map();
|
||||
const userName = user.displayName ?? `${user.firstName ?? ""} ${user.lastName ?? ""}`.trim();
|
||||
return {
|
||||
userId: user.id,
|
||||
displayName: userName,
|
||||
userStatus: user.status,
|
||||
// Approval is derived from the roster state. `approved_at` is an audit
|
||||
// timestamp, not the source of truth: an admin-created active account
|
||||
// (no approval step) must still be assignable.
|
||||
adminApproved: user.status === "active" && !user.deactivatedAt,
|
||||
competency: [...bySkill.values()].map((c) => ({
|
||||
skillId: c.skillId,
|
||||
verifiedLevel: c.verifiedLevel as SkillLevel,
|
||||
selfComfort: c.selfComfort,
|
||||
lastServedOn: c.lastServedOn,
|
||||
staleAfterDays: c.staleAfterDays,
|
||||
mentorReady: c.mentorReady,
|
||||
})),
|
||||
unavailability: (unavailabilityByUser.get(user.id) ?? []).map((rec) => ({
|
||||
id: rec.id,
|
||||
userId: rec.userId,
|
||||
kind: rec.kind,
|
||||
startsOn: rec.startsOn,
|
||||
endsOn: rec.endsOn,
|
||||
allDay: rec.allDay,
|
||||
reason: rec.reason,
|
||||
rrule: rec.rrule,
|
||||
status: rec.status,
|
||||
createdAt: rec.createdAt ?? new Date(),
|
||||
createdBy: rec.createdBy,
|
||||
})),
|
||||
monthlyServiceCount: countByUser.get(user.id) ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
const slotInputsForDomain = slotInputs.map((s) => ({
|
||||
slotId: s.id,
|
||||
roleId: s.roleId,
|
||||
roleName: s.roleName,
|
||||
slotIndex: s.slotIndex,
|
||||
occursOn: s.occursOn,
|
||||
isTraineeSlot: s.isTraineeSlot,
|
||||
skills: s.skills.map((sk) => ({
|
||||
skillId: sk.skillId,
|
||||
name: sk.name,
|
||||
requiredLevel: sk.requiredLevel as SkillLevel | null,
|
||||
isCore: sk.isCore,
|
||||
weight: sk.weight,
|
||||
})),
|
||||
}));
|
||||
|
||||
return autoFill({
|
||||
slots: slotInputsForDomain,
|
||||
candidates,
|
||||
maxServicesPerMonth: opts.maxServicesPerMonth,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply auto-fill proposals for one instance. Writes one `proposed`/`auto`
|
||||
* assignment per proposal that is still free (the slot's active assignment
|
||||
* unique index rejects a taken seat, so a re-run is a no-op on already-filled
|
||||
* seats). Returns the number of assignments written.
|
||||
*
|
||||
* Idempotent: a second run finds every seat already filled and writes 0 rows.
|
||||
*/
|
||||
export async function applyAutoFill(
|
||||
serviceInstanceId: string,
|
||||
opts: { actorId: string; maxServicesPerMonth?: number },
|
||||
): Promise<{ written: number; proposals: AutoFillProposal[]; unfilled: AutoFillResult["unfilled"] }> {
|
||||
const { proposals, unfilled } = await computeAutoFill(serviceInstanceId, {
|
||||
maxServicesPerMonth: opts.maxServicesPerMonth,
|
||||
});
|
||||
|
||||
let written = 0;
|
||||
for (const proposal of proposals) {
|
||||
const existing = await db
|
||||
.select({ id: assignments.id })
|
||||
.from(assignments)
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.slotId, proposal.slotId),
|
||||
ACTIVE_ASSIGNMENT_STATUS,
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (existing.length > 0) continue;
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(assignments).values({
|
||||
id: uuidv7(),
|
||||
slotId: proposal.slotId,
|
||||
userId: proposal.userId,
|
||||
status: "proposed",
|
||||
source: "auto",
|
||||
assignedBy: opts.actorId,
|
||||
assignedAt: new Date(),
|
||||
});
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: "proposed" })
|
||||
.where(eq(slots.id, proposal.slotId));
|
||||
});
|
||||
written++;
|
||||
}
|
||||
|
||||
return { written, proposals, unfilled };
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Calendar read model — instances in a date range with coverage counts.
|
||||
*
|
||||
* The week grid (D7) is the editing surface; month/year views only need an
|
||||
* overview: which services occur, their status, and how full each is. One
|
||||
* query with correlated counts avoids N+1 for a whole year.
|
||||
*/
|
||||
|
||||
import { and, asc, eq, gte, lte, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { serviceInstances, services } from "@/db/schema";
|
||||
|
||||
export interface CalendarInstance {
|
||||
id: string;
|
||||
serviceName: string;
|
||||
/** Church-local date, YYYY-MM-DD. */
|
||||
occursOn: string;
|
||||
startsAt: Date;
|
||||
status: string;
|
||||
/** Filled non-trainee seats. */
|
||||
filled: number;
|
||||
/** Total non-trainee seats. */
|
||||
seats: number;
|
||||
}
|
||||
|
||||
function occursOnISO(date: Date | null): string {
|
||||
if (!date) return "";
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
export async function calendarInstances(
|
||||
startISO: string,
|
||||
endISO: string,
|
||||
): Promise<CalendarInstance[]> {
|
||||
const start = new Date(`${startISO}T00:00:00Z`);
|
||||
const end = new Date(`${endISO}T00:00:00Z`);
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: serviceInstances.id,
|
||||
serviceName: services.name,
|
||||
titleOverride: serviceInstances.titleOverride,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
status: serviceInstances.status,
|
||||
filled: sql<number>`(
|
||||
SELECT count(*) FROM assignments a
|
||||
JOIN slots s ON s.id = a.slot_id
|
||||
WHERE s.service_instance_id = ${serviceInstances.id}
|
||||
AND s.is_trainee_slot = false
|
||||
AND a.status IN ('proposed','confirmed','completed')
|
||||
)`,
|
||||
seats: sql<number>`(
|
||||
SELECT count(*) FROM slots s
|
||||
WHERE s.service_instance_id = ${serviceInstances.id}
|
||||
AND s.is_trainee_slot = false
|
||||
)`,
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||
.where(
|
||||
and(
|
||||
gte(serviceInstances.occursOn, start),
|
||||
lte(serviceInstances.occursOn, end),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.occursOn), asc(serviceInstances.startsAt));
|
||||
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
serviceName: row.titleOverride ?? row.serviceName,
|
||||
occursOn: occursOnISO(row.occursOn),
|
||||
startsAt: row.startsAt ?? new Date(0),
|
||||
status: row.status,
|
||||
filled: Number(row.filled),
|
||||
seats: Number(row.seats),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* Orphan sweep for user-owned rows.
|
||||
*
|
||||
* Every table that hangs off `users` should cascade on delete, so a healthy
|
||||
* database reports zero. This exists anyway: rows outlive their user when a
|
||||
* delete happened outside the app (manual SQL, a restore, a truncated/restored
|
||||
* table), and those stale skill levels keep appearing in the competency views
|
||||
* with no person attached.
|
||||
*
|
||||
* Safe to run repeatedly: it only deletes rows whose `user_id` has no matching
|
||||
* `users` row. Nothing with a live owner is touched.
|
||||
*/
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
|
||||
/** Tables that carry a `user_id` pointing at `users`. */
|
||||
export const USER_OWNED_TABLES = [
|
||||
"user_skills",
|
||||
"skill_assessments",
|
||||
"growth_goals",
|
||||
"unavailability",
|
||||
"notifications",
|
||||
"notification_preferences",
|
||||
] as const;
|
||||
|
||||
export type UserOwnedTable = (typeof USER_OWNED_TABLES)[number];
|
||||
|
||||
export type PruneReport = Record<UserOwnedTable, number>;
|
||||
|
||||
/** `delete from <table> t where not exists (users with that id)`, counted. */
|
||||
async function pruneTable(
|
||||
tx: Parameters<Parameters<typeof db.transaction>[0]>[0],
|
||||
table: UserOwnedTable,
|
||||
): Promise<number> {
|
||||
const orphanFilter = `not exists (select 1 from users u where u.id = t.user_id)`;
|
||||
|
||||
const counted = (await tx.execute(
|
||||
sql.raw(`select count(*)::int as n from ${table} t where ${orphanFilter}`),
|
||||
)) as unknown as { n: number }[];
|
||||
const found = counted[0]?.n ?? 0;
|
||||
if (found === 0) return 0;
|
||||
|
||||
await tx.execute(sql.raw(`delete from ${table} t where ${orphanFilter}`));
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove every user-owned row whose user no longer exists, in one transaction.
|
||||
* Returns the number of rows removed per table.
|
||||
*/
|
||||
export async function pruneOrphanedUserData(): Promise<PruneReport> {
|
||||
return db.transaction(async (tx) => {
|
||||
const report = {} as PruneReport;
|
||||
for (const table of USER_OWNED_TABLES) {
|
||||
report[table] = await pruneTable(tx, table);
|
||||
}
|
||||
return report;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Post-service completion — the job that turns yesterday's schedule into
|
||||
* history. Without it nothing ever sets `assignment.completed`,
|
||||
* `user_skills.last_served_on` or `users.last_served_at`, so staleness,
|
||||
* readiness and fairness reports would stay frozen at seed values.
|
||||
*
|
||||
* Runs from `/api/dev/cron/complete`. Idempotent: only `proposed`/`confirmed`
|
||||
* assignments on a published instance that has already ended are touched, and
|
||||
* a completed assignment is never selected again.
|
||||
*/
|
||||
|
||||
import { and, eq, inArray, isNotNull, lt, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
positionSkills,
|
||||
serviceInstances,
|
||||
slots,
|
||||
userSkills,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
|
||||
export interface CompleteSummary {
|
||||
assignmentsCompleted: number;
|
||||
userSkillsUpdated: number;
|
||||
usersUpdated: number;
|
||||
}
|
||||
|
||||
function isoDateUTC(date: Date | null): string {
|
||||
if (!date) return "";
|
||||
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export async function completePastAssignments(
|
||||
opts: { now?: Date } = {},
|
||||
): Promise<CompleteSummary> {
|
||||
const now = opts.now ?? new Date();
|
||||
|
||||
return db.transaction(async (tx): Promise<CompleteSummary> => {
|
||||
const finished = await tx
|
||||
.select({
|
||||
assignmentId: assignments.id,
|
||||
userId: assignments.userId,
|
||||
slotId: slots.id,
|
||||
roleId: slots.roleId,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
endsAt: serviceInstances.endsAt,
|
||||
})
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
inArray(assignments.status, ["proposed", "confirmed"]),
|
||||
eq(serviceInstances.status, "published"),
|
||||
isNotNull(serviceInstances.endsAt),
|
||||
lt(serviceInstances.endsAt, now),
|
||||
),
|
||||
);
|
||||
|
||||
if (finished.length === 0) {
|
||||
return { assignmentsCompleted: 0, userSkillsUpdated: 0, usersUpdated: 0 };
|
||||
}
|
||||
|
||||
const completed = await tx
|
||||
.update(assignments)
|
||||
.set({ status: "completed" })
|
||||
.where(
|
||||
inArray(
|
||||
assignments.id,
|
||||
finished.map((row) => row.assignmentId),
|
||||
),
|
||||
)
|
||||
.returning({ id: assignments.id });
|
||||
|
||||
let userSkillsUpdated = 0;
|
||||
let usersUpdated = 0;
|
||||
|
||||
for (const row of finished) {
|
||||
const servedOn = isoDateUTC(row.occursOn);
|
||||
if (!servedOn) continue;
|
||||
|
||||
// Move the served date on every skill the position requires, but only
|
||||
// forward (a later service must not be overwritten by an older one).
|
||||
const skillRows = await tx
|
||||
.select({ skillId: positionSkills.skillId })
|
||||
.from(positionSkills)
|
||||
.where(eq(positionSkills.positionId, row.roleId));
|
||||
|
||||
for (const skill of skillRows) {
|
||||
const updated = await tx
|
||||
.update(userSkills)
|
||||
.set({ lastServedOn: servedOn })
|
||||
.where(
|
||||
and(
|
||||
eq(userSkills.userId, row.userId),
|
||||
eq(userSkills.skillId, skill.skillId),
|
||||
sql`(${userSkills.lastServedOn} IS NULL OR ${userSkills.lastServedOn} < ${servedOn})`,
|
||||
),
|
||||
)
|
||||
.returning({ id: userSkills.id });
|
||||
userSkillsUpdated += updated.length;
|
||||
}
|
||||
|
||||
const servedAt = row.endsAt ?? row.occursOn ?? now;
|
||||
const touched = await tx
|
||||
.update(users)
|
||||
.set({ lastServedAt: servedAt, updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(users.id, row.userId),
|
||||
sql`(${users.lastServedAt} IS NULL OR ${users.lastServedAt} < ${servedAt})`,
|
||||
),
|
||||
)
|
||||
.returning({ id: users.id });
|
||||
usersUpdated += touched.length;
|
||||
}
|
||||
|
||||
return {
|
||||
assignmentsCompleted: completed.length,
|
||||
userSkillsUpdated,
|
||||
usersUpdated,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* Coverage / swap requests.
|
||||
*
|
||||
* A volunteer asks for their seat to be released. Nothing changes until a
|
||||
* coordinator approves: the assignment stays live, so a pending request never
|
||||
* opens a silent hole in the schedule.
|
||||
*
|
||||
* Approval does one of two things in a single transaction:
|
||||
* - with a replacement: the old assignment becomes `cancelled`, a new
|
||||
* `proposed` assignment is created with source `swap`, and the slot moves
|
||||
* to `proposed` (the replacement still has to confirm);
|
||||
* - without one: the assignment is removed, its queued mail is cancelled,
|
||||
* and the slot reopens.
|
||||
*
|
||||
* Published instances re-enqueue mail + reminders for the new assignment. The
|
||||
* enqueue helpers are idempotent on dedupe_key, so an existing row is kept.
|
||||
*/
|
||||
|
||||
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
auditLog,
|
||||
coverageRequests,
|
||||
roles,
|
||||
serviceInstances,
|
||||
services,
|
||||
slots,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { auditRow } from "@/db/audit";
|
||||
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
|
||||
import { cancelAssignmentNotifications, enqueuePublishNotifications } from "@/db/outbox";
|
||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const ACTIVE_ASSIGNMENT = ["proposed", "confirmed"] as const;
|
||||
|
||||
export class CoverageError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "CoverageError";
|
||||
}
|
||||
}
|
||||
|
||||
export interface CoverageRequestRow {
|
||||
id: string;
|
||||
assignmentId: string;
|
||||
slotId: string;
|
||||
roleName: string;
|
||||
serviceName: string;
|
||||
startsAt: Date;
|
||||
callTime: Date | null;
|
||||
location: string | null;
|
||||
reason: string | null;
|
||||
requesterId: string;
|
||||
requesterName: string;
|
||||
requesterEmail: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
/** One person's own coverage requests, newest first (home + history). */
|
||||
export async function coverageRequestsForUser(
|
||||
userId: string,
|
||||
limit = 10,
|
||||
): Promise<
|
||||
{
|
||||
id: string;
|
||||
assignmentId: string;
|
||||
status: string;
|
||||
reason: string | null;
|
||||
createdAt: Date;
|
||||
}[]
|
||||
> {
|
||||
return db
|
||||
.select({
|
||||
id: coverageRequests.id,
|
||||
assignmentId: coverageRequests.assignmentId,
|
||||
status: coverageRequests.status,
|
||||
reason: coverageRequests.reason,
|
||||
createdAt: coverageRequests.createdAt,
|
||||
})
|
||||
.from(coverageRequests)
|
||||
.where(eq(coverageRequests.requestedBy, userId))
|
||||
.orderBy(desc(coverageRequests.createdAt))
|
||||
.limit(Math.min(Math.max(limit, 1), 50));
|
||||
}
|
||||
|
||||
/** Pending requests a coordinator must resolve, soonest service first. */
|
||||
export async function listPendingCoverageRequests(): Promise<
|
||||
CoverageRequestRow[]
|
||||
> {
|
||||
const rows = await db
|
||||
.select({
|
||||
id: coverageRequests.id,
|
||||
assignmentId: coverageRequests.assignmentId,
|
||||
slotId: slots.id,
|
||||
roleName: roles.name,
|
||||
serviceName: services.name,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
callTime: slots.callTime,
|
||||
location: services.location,
|
||||
reason: coverageRequests.reason,
|
||||
requesterId: users.id,
|
||||
requesterName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
requesterEmail: users.email,
|
||||
createdAt: coverageRequests.createdAt,
|
||||
})
|
||||
.from(coverageRequests)
|
||||
.innerJoin(assignments, eq(assignments.id, coverageRequests.assignmentId))
|
||||
.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, coverageRequests.requestedBy))
|
||||
.where(
|
||||
and(
|
||||
eq(coverageRequests.status, "pending"),
|
||||
gte(serviceInstances.startsAt, new Date()),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.startsAt), asc(roles.sortOrder));
|
||||
|
||||
// The WHERE clause already requires a future start, so a null start cannot
|
||||
// appear here; the fallback keeps the row type non-nullable for callers.
|
||||
return rows.map((row) => ({ ...row, startsAt: row.startsAt ?? new Date() }));
|
||||
}
|
||||
|
||||
/**
|
||||
* Volunteer-initiated request. Only the person holding the seat may ask for
|
||||
* coverage, and only before the service has started.
|
||||
*/
|
||||
export async function createCoverageRequest(input: {
|
||||
assignmentId: string;
|
||||
userId: string;
|
||||
reason?: string | null;
|
||||
}): Promise<{ id: string }> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
assignmentId: assignments.id,
|
||||
userId: assignments.userId,
|
||||
status: assignments.status,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
})
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(eq(assignments.id, input.assignmentId))
|
||||
.limit(1);
|
||||
|
||||
if (!row) throw new CoverageError(404, "assignment not found");
|
||||
if (row.userId !== input.userId) {
|
||||
throw new CoverageError(403, "you can only request coverage for your own assignment");
|
||||
}
|
||||
if (!(ACTIVE_ASSIGNMENT as readonly string[]).includes(row.status)) {
|
||||
throw new CoverageError(409, "this assignment is no longer active");
|
||||
}
|
||||
if (row.startsAt && row.startsAt.getTime() <= Date.now()) {
|
||||
throw new CoverageError(409, "this service has already started");
|
||||
}
|
||||
|
||||
try {
|
||||
const id = uuidv7();
|
||||
await db.insert(coverageRequests).values({
|
||||
id,
|
||||
assignmentId: input.assignmentId,
|
||||
requestedBy: input.userId,
|
||||
reason: input.reason?.trim() || null,
|
||||
status: "pending",
|
||||
});
|
||||
return { id };
|
||||
} catch (err) {
|
||||
if (sqlState(err) === "23505") {
|
||||
throw new CoverageError(409, "a coverage request is already open for this seat");
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ResolveCoverageInput {
|
||||
requestId: string;
|
||||
actorId: string;
|
||||
action: "approve" | "decline" | "cancel";
|
||||
replacementUserId?: string | null;
|
||||
}
|
||||
|
||||
export interface ResolveCoverageResult {
|
||||
status: "approved" | "declined" | "cancelled";
|
||||
assignmentId: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Coordinator decision. `decline` leaves the original assignment untouched;
|
||||
* `cancel` is the volunteer withdrawing the request. Both are history rows.
|
||||
*/
|
||||
export async function resolveCoverageRequest(
|
||||
input: ResolveCoverageInput,
|
||||
): Promise<ResolveCoverageResult> {
|
||||
const [request] = await db
|
||||
.select({
|
||||
id: coverageRequests.id,
|
||||
status: coverageRequests.status,
|
||||
assignmentId: coverageRequests.assignmentId,
|
||||
assignmentUserId: assignments.userId,
|
||||
slotId: slots.id,
|
||||
instanceId: serviceInstances.id,
|
||||
instanceStatus: serviceInstances.status,
|
||||
})
|
||||
.from(coverageRequests)
|
||||
.innerJoin(assignments, eq(assignments.id, coverageRequests.assignmentId))
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(eq(coverageRequests.id, input.requestId))
|
||||
.limit(1);
|
||||
|
||||
if (!request) throw new CoverageError(404, "coverage request not found");
|
||||
if (request.status !== "pending") {
|
||||
throw new CoverageError(409, "this request has already been resolved");
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
|
||||
if (input.action !== "approve") {
|
||||
const status = input.action === "cancel" ? "cancelled" : "declined";
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.update(coverageRequests)
|
||||
.set({ status, resolvedBy: input.actorId, resolvedAt: now })
|
||||
.where(eq(coverageRequests.id, input.requestId));
|
||||
await tx
|
||||
.insert(auditLog)
|
||||
.values(auditLogRow(input.actorId, input.requestId, status));
|
||||
});
|
||||
return { status, assignmentId: null };
|
||||
}
|
||||
|
||||
const replacementUserId = input.replacementUserId ?? null;
|
||||
if (replacementUserId && replacementUserId === request.assignmentUserId) {
|
||||
throw new CoverageError(409, "choose a different volunteer");
|
||||
}
|
||||
|
||||
// Resolve conflicts for the replacement before opening a transaction. The
|
||||
// hard rules are the same ones manual assignment uses.
|
||||
if (replacementUserId) {
|
||||
try {
|
||||
const facts = await resolveAssignFacts({
|
||||
userId: replacementUserId,
|
||||
slotId: request.slotId,
|
||||
});
|
||||
const hard = hardConflicts(classifyConflicts(facts));
|
||||
if (hard.length > 0) {
|
||||
throw new CoverageError(
|
||||
409,
|
||||
hard.map((conflict) => conflict.message).join(" "),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AssignFactError) {
|
||||
throw new CoverageError(404, err.message);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
const newAssignmentId = replacementUserId ? uuidv7() : null;
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
// Remove the old seat's pending mail first, so a cancelled assignment can
|
||||
// never still send "you're serving".
|
||||
await cancelAssignmentNotifications(request.assignmentId, now, tx);
|
||||
|
||||
if (replacementUserId && newAssignmentId) {
|
||||
await tx
|
||||
.update(assignments)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
respondedAt: now,
|
||||
declineReason: "Coverage approved for another volunteer",
|
||||
})
|
||||
.where(eq(assignments.id, request.assignmentId));
|
||||
|
||||
await tx.insert(assignments).values({
|
||||
id: newAssignmentId,
|
||||
slotId: request.slotId,
|
||||
userId: replacementUserId,
|
||||
status: "proposed",
|
||||
source: "swap",
|
||||
assignedBy: input.actorId,
|
||||
assignedAt: now,
|
||||
});
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: "proposed" })
|
||||
.where(eq(slots.id, request.slotId));
|
||||
} else {
|
||||
// Keep the row as history instead of deleting it: coverage_requests
|
||||
// cascades on assignment delete, so a hard delete would erase the very
|
||||
// audit trail this approval writes. A cancelled row is outside the
|
||||
// partial unique index, so the seat is free.
|
||||
await tx
|
||||
.update(assignments)
|
||||
.set({
|
||||
status: "cancelled",
|
||||
respondedAt: now,
|
||||
declineReason: "Coverage released by coordinator",
|
||||
})
|
||||
.where(eq(assignments.id, request.assignmentId));
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: "open" })
|
||||
.where(eq(slots.id, request.slotId));
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(coverageRequests)
|
||||
.set({
|
||||
status: "approved",
|
||||
replacementUserId,
|
||||
resolvedBy: input.actorId,
|
||||
resolvedAt: now,
|
||||
})
|
||||
.where(eq(coverageRequests.id, input.requestId));
|
||||
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: input.actorId,
|
||||
action: "coverage.approved",
|
||||
entityType: "coverage_request",
|
||||
entityId: input.requestId,
|
||||
before: {
|
||||
assignmentId: request.assignmentId,
|
||||
userId: request.assignmentUserId,
|
||||
},
|
||||
after: {
|
||||
assignmentId: newAssignmentId,
|
||||
userId: replacementUserId,
|
||||
slotId: request.slotId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
// A published week's mail was written at publish time; the replacement
|
||||
// needs its own rows. Both helpers are idempotent on dedupe_key.
|
||||
if (replacementUserId && request.instanceStatus === "published") {
|
||||
await enqueuePublishNotifications(tx, request.instanceId, { now });
|
||||
await enqueueRemindersForInstance(tx, request.instanceId, { now });
|
||||
}
|
||||
});
|
||||
|
||||
return { status: "approved", assignmentId: newAssignmentId };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ utils */
|
||||
|
||||
function auditLogRow(actorId: string, requestId: string, status: string) {
|
||||
return auditRow({
|
||||
actorId,
|
||||
action: `coverage.${status}`,
|
||||
entityType: "coverage_request",
|
||||
entityId: requestId,
|
||||
after: { status },
|
||||
});
|
||||
}
|
||||
|
||||
function sqlState(err: unknown): string | undefined {
|
||||
let node = err as { code?: string; cause?: unknown } | null;
|
||||
while (node) {
|
||||
if (node.code) return node.code;
|
||||
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* Manager dashboard read model. One snapshot for the next five weeks plus
|
||||
* operational queues that otherwise live in separate admin panels.
|
||||
*/
|
||||
|
||||
import { and, eq, gte, isNull, lte, notExists, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
eventPhotographers,
|
||||
events,
|
||||
notifications,
|
||||
serviceInstances,
|
||||
slots,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { calendarInstances, type CalendarInstance } from "@/db/calendar";
|
||||
import { addDaysISO, dateInTimezone, CHURCH_TIMEZONE } from "@/lib/tz";
|
||||
|
||||
export interface DashboardSnapshot {
|
||||
today: string;
|
||||
horizonEnd: string;
|
||||
instances: CalendarInstance[];
|
||||
nextService: CalendarInstance | null;
|
||||
seats: number;
|
||||
filled: number;
|
||||
open: number;
|
||||
proposed: number;
|
||||
confirmed: number;
|
||||
pendingApprovals: number;
|
||||
activePeople: number;
|
||||
upcomingEvents: number;
|
||||
eventsNeedingPhotographer: number;
|
||||
failedNotifications: number;
|
||||
unconfirmedNext: number;
|
||||
}
|
||||
|
||||
export async function dashboardSnapshot(): Promise<DashboardSnapshot> {
|
||||
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
|
||||
const horizonEnd = addDaysISO(today, 34);
|
||||
const instances = await calendarInstances(today, horizonEnd);
|
||||
const nextService = instances[0] ?? null;
|
||||
|
||||
const start = new Date(`${today}T00:00:00Z`);
|
||||
const end = new Date(`${horizonEnd}T23:59:59Z`);
|
||||
|
||||
const [proposedRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.status, "proposed"),
|
||||
gte(serviceInstances.startsAt, start),
|
||||
lte(serviceInstances.startsAt, end),
|
||||
),
|
||||
);
|
||||
|
||||
const [confirmedRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.status, "confirmed"),
|
||||
gte(serviceInstances.startsAt, start),
|
||||
lte(serviceInstances.startsAt, end),
|
||||
),
|
||||
);
|
||||
|
||||
const [pendingRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(users)
|
||||
.where(eq(users.status, "pending_approval"));
|
||||
|
||||
const [activeRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(users)
|
||||
.where(and(eq(users.status, "active"), isNull(users.deactivatedAt)));
|
||||
|
||||
const [eventsRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(events)
|
||||
.where(gte(events.startsAt, new Date()));
|
||||
|
||||
const [eventsMissingPhotoRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(events)
|
||||
.where(
|
||||
and(
|
||||
gte(events.startsAt, new Date()),
|
||||
notExists(
|
||||
db
|
||||
.select({ one: sql`1` })
|
||||
.from(eventPhotographers)
|
||||
.where(
|
||||
and(
|
||||
eq(eventPhotographers.eventId, events.id),
|
||||
eq(eventPhotographers.role, "photographer"),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const [failedRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(notifications)
|
||||
.where(eq(notifications.status, "failed"));
|
||||
|
||||
let unconfirmedNext = 0;
|
||||
if (nextService) {
|
||||
const [row] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.where(
|
||||
and(
|
||||
eq(slots.serviceInstanceId, nextService.id),
|
||||
eq(assignments.status, "proposed"),
|
||||
),
|
||||
);
|
||||
unconfirmedNext = Number(row?.count ?? 0);
|
||||
}
|
||||
|
||||
const seats = instances.reduce((sum, row) => sum + row.seats, 0);
|
||||
const filled = instances.reduce((sum, row) => sum + row.filled, 0);
|
||||
|
||||
return {
|
||||
today,
|
||||
horizonEnd,
|
||||
instances,
|
||||
nextService,
|
||||
seats,
|
||||
filled,
|
||||
open: Math.max(0, seats - filled),
|
||||
proposed: Number(proposedRow?.count ?? 0),
|
||||
confirmed: Number(confirmedRow?.count ?? 0),
|
||||
pendingApprovals: Number(pendingRow?.count ?? 0),
|
||||
activePeople: Number(activeRow?.count ?? 0),
|
||||
upcomingEvents: Number(eventsRow?.count ?? 0),
|
||||
eventsNeedingPhotographer: Number(eventsMissingPhotoRow?.count ?? 0),
|
||||
failedNotifications: Number(failedRow?.count ?? 0),
|
||||
unconfirmedNext,
|
||||
};
|
||||
}
|
||||
|
||||
/** Upcoming instances with an open seat, for the "needs attention" list. */
|
||||
export async function coverageGaps(limit = 6): Promise<CalendarInstance[]> {
|
||||
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
|
||||
const rows = await calendarInstances(today, addDaysISO(today, 34));
|
||||
return rows
|
||||
.filter((row) => row.seats > row.filled)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* Notification dispatcher — unit E2 (ARCHITECTURE §6.1).
|
||||
*
|
||||
* The cron tick: recover rows orphaned in `sending`, read due rows, apply the
|
||||
* pure guard plan (`planDispatch`), claim each row atomically, send through the
|
||||
* transport, and record the outcome. Retries follow the 5/30/120-minute backoff
|
||||
* and stop at 3 attempts (`failed`).
|
||||
*
|
||||
* Email is the launch channel. SMS rows are suppressed here until E5 wires the
|
||||
* Twilio transport — the pipeline is channel-agnostic, so that is a transport
|
||||
* swap, not a redesign.
|
||||
*/
|
||||
|
||||
import { and, eq, inArray, lte, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
notificationPreferences,
|
||||
notifications,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { planDispatch, planFailureRetry } from "@/domain/dispatch";
|
||||
import { getEmailTransportSettings } from "@/db/settings";
|
||||
import { resolveEmailTransport, type EmailTransport } from "@/lib/email";
|
||||
|
||||
export interface DispatchSummary {
|
||||
sent: number;
|
||||
rescheduled: number;
|
||||
suppressed: number;
|
||||
cancelled: number;
|
||||
failed: number;
|
||||
skipped: number;
|
||||
/** Rows recovered from a crashed/aborted `sending` state. */
|
||||
recovered: number;
|
||||
}
|
||||
|
||||
interface OutboxPayload {
|
||||
subject: string;
|
||||
html: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** A `sending` row older than this is assumed abandoned and requeued. */
|
||||
const STALE_SENDING_MINUTES = 10;
|
||||
|
||||
/** Drain due outbox rows once. Returns what happened, for the cron response. */
|
||||
export async function dispatchDue(
|
||||
opts: { now?: Date; limit?: number; transport?: EmailTransport } = {},
|
||||
): Promise<DispatchSummary> {
|
||||
const now = opts.now ?? new Date();
|
||||
const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
|
||||
const transport =
|
||||
opts.transport ?? resolveEmailTransport(await getEmailTransportSettings());
|
||||
|
||||
const summary: DispatchSummary = {
|
||||
sent: 0,
|
||||
rescheduled: 0,
|
||||
suppressed: 0,
|
||||
cancelled: 0,
|
||||
failed: 0,
|
||||
skipped: 0,
|
||||
recovered: 0,
|
||||
};
|
||||
|
||||
// A process that dies mid-send leaves the row in `sending`; nothing else
|
||||
// reads that state. Recover it before selecting work.
|
||||
const staleBefore = new Date(now.getTime() - STALE_SENDING_MINUTES * 60_000);
|
||||
const recovered = await db
|
||||
.update(notifications)
|
||||
.set({ status: "queued", updatedAt: now })
|
||||
.where(
|
||||
and(
|
||||
eq(notifications.status, "sending"),
|
||||
sql`coalesce(${notifications.updatedAt}, ${notifications.createdAt}) < ${staleBefore.toISOString()}::timestamptz`,
|
||||
),
|
||||
)
|
||||
.returning({ id: notifications.id });
|
||||
summary.recovered = recovered.length;
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
id: notifications.id,
|
||||
channel: notifications.channel,
|
||||
templateKey: notifications.templateKey,
|
||||
toAddress: notifications.toAddress,
|
||||
payloadJson: notifications.payloadJson,
|
||||
dedupeKey: notifications.dedupeKey,
|
||||
status: notifications.status,
|
||||
attempts: notifications.attempts,
|
||||
scheduledFor: notifications.scheduledFor,
|
||||
assignmentId: notifications.assignmentId,
|
||||
assignmentStatus: assignments.status,
|
||||
userStatus: users.status,
|
||||
userTimeZone: users.timezone,
|
||||
emailEnabled: notificationPreferences.emailEnabled,
|
||||
smsEnabled: notificationPreferences.smsEnabled,
|
||||
quietStart: notificationPreferences.quietHoursStart,
|
||||
quietEnd: notificationPreferences.quietHoursEnd,
|
||||
})
|
||||
.from(notifications)
|
||||
.innerJoin(users, eq(users.id, notifications.userId))
|
||||
.leftJoin(assignments, eq(assignments.id, notifications.assignmentId))
|
||||
.leftJoin(
|
||||
notificationPreferences,
|
||||
eq(notificationPreferences.userId, notifications.userId),
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
inArray(notifications.status, ["queued", "failed"]),
|
||||
lte(notifications.scheduledFor, now),
|
||||
),
|
||||
)
|
||||
.orderBy(notifications.scheduledFor)
|
||||
.limit(limit);
|
||||
|
||||
for (const row of rows) {
|
||||
const decision = planDispatch({
|
||||
status: row.status,
|
||||
channel: row.channel,
|
||||
// A null assignment id means the assignment row is gone (a cleared seat
|
||||
// or an unpublish/delete cascade). Event reminders are not assignment-
|
||||
// bound, so they carry no assignment guard; everything else with a null
|
||||
// assignment is stale and must be cancelled.
|
||||
assignmentStatus:
|
||||
row.assignmentId !== null
|
||||
? row.assignmentStatus
|
||||
: row.templateKey.startsWith("event.")
|
||||
? null
|
||||
: "cancelled",
|
||||
userStatus: row.userStatus,
|
||||
// A missing preferences row means the defaults: email on, SMS off.
|
||||
emailEnabled: row.emailEnabled ?? true,
|
||||
smsEnabled: row.smsEnabled ?? false,
|
||||
scheduledFor: row.scheduledFor,
|
||||
now,
|
||||
quietHours: {
|
||||
start: row.quietStart ?? "21:00",
|
||||
end: row.quietEnd ?? "08:00",
|
||||
timeZone: row.userTimeZone,
|
||||
},
|
||||
});
|
||||
|
||||
switch (decision.action) {
|
||||
case "skip":
|
||||
summary.skipped++;
|
||||
break;
|
||||
|
||||
case "cancel":
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({ status: "cancelled", updatedAt: now })
|
||||
.where(eq(notifications.id, row.id));
|
||||
summary.cancelled++;
|
||||
break;
|
||||
|
||||
case "suppress":
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({
|
||||
status: "suppressed",
|
||||
error: decision.reason,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(notifications.id, row.id));
|
||||
summary.suppressed++;
|
||||
break;
|
||||
|
||||
case "reschedule":
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({ scheduledFor: decision.until, updatedAt: now })
|
||||
.where(eq(notifications.id, row.id));
|
||||
summary.rescheduled++;
|
||||
break;
|
||||
|
||||
case "send": {
|
||||
// SMS is deferred to E5; suppress rather than fail forever.
|
||||
if (row.channel !== "email") {
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({
|
||||
status: "suppressed",
|
||||
error: "sms channel not enabled (E5 deferred)",
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(notifications.id, row.id));
|
||||
summary.suppressed++;
|
||||
break;
|
||||
}
|
||||
|
||||
// Claim atomically: only one tick can move a row out of queued/failed.
|
||||
// A concurrent tick's claim updates 0 rows and skips it.
|
||||
const [claimed] = await db
|
||||
.update(notifications)
|
||||
.set({
|
||||
status: "sending",
|
||||
attempts: sql`${notifications.attempts} + 1`,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(
|
||||
and(
|
||||
eq(notifications.id, row.id),
|
||||
inArray(notifications.status, ["queued", "failed"]),
|
||||
),
|
||||
)
|
||||
.returning({ attempts: notifications.attempts });
|
||||
|
||||
if (!claimed) {
|
||||
summary.skipped++;
|
||||
break;
|
||||
}
|
||||
|
||||
const attempt = claimed.attempts;
|
||||
try {
|
||||
const payload = JSON.parse(row.payloadJson) as OutboxPayload;
|
||||
const result = await transport.send({
|
||||
to: row.toAddress,
|
||||
subject: payload.subject,
|
||||
html: payload.html,
|
||||
text: payload.text,
|
||||
templateKey: row.templateKey,
|
||||
dedupeKey: row.dedupeKey,
|
||||
});
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({
|
||||
status: "sent",
|
||||
providerId: result.providerId,
|
||||
providerStatus: result.providerStatus,
|
||||
sentAt: now,
|
||||
error: null,
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(notifications.id, row.id));
|
||||
summary.sent++;
|
||||
} catch (e) {
|
||||
const retry = planFailureRetry({ attemptsAfterFailure: attempt, now });
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({
|
||||
status: retry.status,
|
||||
scheduledFor: retry.retryAt ?? row.scheduledFor,
|
||||
error: e instanceof Error ? e.message : "send failed",
|
||||
updatedAt: now,
|
||||
})
|
||||
.where(eq(notifications.id, row.id));
|
||||
if (retry.status === "failed") summary.failed++;
|
||||
else summary.rescheduled++;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
/**
|
||||
* Event reminders — the one-off shoot counterpart to E7's service reminders.
|
||||
*
|
||||
* Services get their reminders enqueued at publish time, because publishing is
|
||||
* the moment the schedule becomes real. Events have no publish step, so this
|
||||
* module is called from the notification cron tick instead: it looks at every
|
||||
* upcoming event with assigned photographers and queues one email per person at
|
||||
* the rule's lead time (2 days before, 9:00 local, by default).
|
||||
*
|
||||
* The lead time is a `notification_rules` row (event = `event.reminder`), so an
|
||||
* admin changes it in the Reminders panel without a deploy. When no row exists
|
||||
* yet, the default is used so reminders still go out.
|
||||
*
|
||||
* Idempotency is the outbox's `dedupe_key`
|
||||
* (`event.reminder:<eventId>:<userId>:email`): running the tick again queues
|
||||
* nothing. Rows are dispatched by the normal outbox guards.
|
||||
*/
|
||||
|
||||
import { and, asc, eq, gte, isNull } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
eventPhotographers,
|
||||
events,
|
||||
notificationRules,
|
||||
notifications,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { APP_ORIGIN } from "@/auth/magic-link";
|
||||
import { channelsFor, computeReminderSendAt } from "@/domain/reminders";
|
||||
import { renderEventReminderEmail } from "@/domain/templates";
|
||||
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
export const EVENT_REMINDER_EVENT = "event.reminder" as const;
|
||||
export const EVENT_REMINDER_KEY = "event_reminder";
|
||||
|
||||
export interface EventReminderRule {
|
||||
key: string;
|
||||
offsetDays: number;
|
||||
sendAtLocalTime: string;
|
||||
channelSet: string;
|
||||
active: boolean;
|
||||
/** True when this row came from the database, false for the fallback. */
|
||||
persisted: boolean;
|
||||
}
|
||||
|
||||
/** The default when the admin has never saved an event reminder rule. */
|
||||
export const DEFAULT_EVENT_REMINDER: EventReminderRule = {
|
||||
key: EVENT_REMINDER_KEY,
|
||||
offsetDays: -2,
|
||||
sendAtLocalTime: "09:00",
|
||||
channelSet: "email",
|
||||
active: true,
|
||||
persisted: false,
|
||||
};
|
||||
|
||||
export async function getEventReminderRule(): Promise<EventReminderRule> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
key: notificationRules.key,
|
||||
offsetDays: notificationRules.offsetDays,
|
||||
sendAtLocalTime: notificationRules.sendAtLocalTime,
|
||||
channelSet: notificationRules.channelSet,
|
||||
active: notificationRules.active,
|
||||
})
|
||||
.from(notificationRules)
|
||||
.where(eq(notificationRules.event, EVENT_REMINDER_EVENT))
|
||||
.orderBy(asc(notificationRules.offsetDays))
|
||||
.limit(1);
|
||||
return row ? { ...row, persisted: true } : DEFAULT_EVENT_REMINDER;
|
||||
}
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
photographer: "Photographer",
|
||||
second_shooter: "Second shooter",
|
||||
editor: "Editor",
|
||||
};
|
||||
|
||||
/**
|
||||
* Queue reminder emails for upcoming events. Returns the number of rows
|
||||
* inserted (0 on a re-run, when the rule is paused, when SMS-only, or when
|
||||
* every send time has already passed).
|
||||
*/
|
||||
export async function enqueueEventReminders(
|
||||
opts: { now?: Date; appOrigin?: string } = {},
|
||||
): Promise<number> {
|
||||
const now = opts.now ?? new Date();
|
||||
const origin = opts.appOrigin ?? APP_ORIGIN;
|
||||
|
||||
const rule = await getEventReminderRule();
|
||||
if (!rule.active || !channelsFor(rule.channelSet).includes("email")) return 0;
|
||||
|
||||
const rows = await db
|
||||
.select({
|
||||
eventId: events.id,
|
||||
title: events.title,
|
||||
eventType: events.eventType,
|
||||
startsAt: events.startsAt,
|
||||
location: events.location,
|
||||
userId: users.id,
|
||||
email: users.email,
|
||||
firstName: users.firstName,
|
||||
role: eventPhotographers.role,
|
||||
})
|
||||
.from(events)
|
||||
.innerJoin(eventPhotographers, eq(eventPhotographers.eventId, events.id))
|
||||
.innerJoin(users, eq(users.id, eventPhotographers.userId))
|
||||
.where(
|
||||
and(
|
||||
gte(events.startsAt, now),
|
||||
eq(users.status, "active"),
|
||||
isNull(users.deactivatedAt),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(events.startsAt));
|
||||
|
||||
let enqueued = 0;
|
||||
for (const row of rows) {
|
||||
const sendAt = computeReminderSendAt({
|
||||
startsAt: row.startsAt,
|
||||
offsetDays: rule.offsetDays,
|
||||
sendAtLocalTime: rule.sendAtLocalTime,
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
});
|
||||
// A reminder whose time has passed is skipped, never back-dated.
|
||||
if (sendAt.getTime() <= now.getTime()) continue;
|
||||
|
||||
const occursOnLabel = formatInTimezone(row.startsAt, CHURCH_TIMEZONE, {
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
weekday: "long",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
});
|
||||
const startTimeLabel = formatInTimezone(row.startsAt, CHURCH_TIMEZONE, {
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
const rendered = renderEventReminderEmail({
|
||||
volunteerFirstName: row.firstName,
|
||||
roleLabel: ROLE_LABELS[row.role] ?? "Photographer",
|
||||
eventTitle: row.title,
|
||||
eventType: row.eventType,
|
||||
occursOnLabel,
|
||||
startTimeLabel,
|
||||
location: row.location ?? "Location in the event brief",
|
||||
eventUrl: `${origin}/events/${row.eventId}`,
|
||||
leadDays: Math.abs(rule.offsetDays),
|
||||
});
|
||||
|
||||
const inserted = await db
|
||||
.insert(notifications)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
userId: row.userId,
|
||||
channel: "email",
|
||||
templateKey: EVENT_REMINDER_EVENT,
|
||||
ruleKey: rule.key,
|
||||
assignmentId: null,
|
||||
slotId: null,
|
||||
toAddress: row.email,
|
||||
payloadJson: JSON.stringify({
|
||||
subject: rendered.subject,
|
||||
html: rendered.html,
|
||||
text: rendered.text,
|
||||
eventId: row.eventId,
|
||||
}),
|
||||
dedupeKey: `${EVENT_REMINDER_EVENT}:${row.eventId}:${row.userId}:email`,
|
||||
scheduledFor: sendAt,
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
createdAt: now,
|
||||
})
|
||||
.onConflictDoNothing({ target: notifications.dedupeKey })
|
||||
.returning({ id: notifications.id });
|
||||
|
||||
enqueued += inserted.length;
|
||||
}
|
||||
|
||||
return enqueued;
|
||||
}
|
||||
@@ -0,0 +1,706 @@
|
||||
/**
|
||||
* Events, photographer assignments and shared photo folders.
|
||||
*
|
||||
* Access is checked here (not in the UI): `getEventAccess` returns null unless
|
||||
* the caller is a manager or one of the event's assigned photographers, so a
|
||||
* handler that forgets a check cannot accidentally stream someone else's
|
||||
* photos. Folder/photo lookups are separate so a download does not load a whole
|
||||
* event's metadata.
|
||||
*/
|
||||
|
||||
import { and, asc, desc, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
eventFolders,
|
||||
eventPhotographers,
|
||||
eventPhotos,
|
||||
events,
|
||||
notifications,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import type {
|
||||
EventFolderKind,
|
||||
EventPhotographerRole,
|
||||
} from "@/db/schema";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import {
|
||||
canContributeToEvent,
|
||||
canManageEvents,
|
||||
} from "@/lib/event-access";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||
|
||||
export interface EventPhotographerRow {
|
||||
eventId: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: EventPhotographerRole;
|
||||
}
|
||||
|
||||
export interface EventFolderRow {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: EventFolderKind;
|
||||
createdAt: Date;
|
||||
photoCount: number;
|
||||
totalBytes: number;
|
||||
}
|
||||
|
||||
export interface EventSummaryRow {
|
||||
id: string;
|
||||
title: string;
|
||||
eventType: string;
|
||||
startsAt: Date;
|
||||
endsAt: Date | null;
|
||||
location: string | null;
|
||||
description: string | null;
|
||||
photographers: EventPhotographerRow[];
|
||||
folderCount: number;
|
||||
photoCount: number;
|
||||
}
|
||||
|
||||
export interface EventPhotoRow {
|
||||
id: string;
|
||||
folderId: string;
|
||||
uploaderId: string;
|
||||
uploaderName: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
storedName: string;
|
||||
checksumSha256: string;
|
||||
kind: "raw" | "image";
|
||||
editJson: string | null;
|
||||
editedStoredName: string | null;
|
||||
editedSizeBytes: number | null;
|
||||
editedAt: Date | null;
|
||||
editedBy: string | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface EventAccess {
|
||||
event: EventSummaryRow;
|
||||
canManage: boolean;
|
||||
canContribute: boolean;
|
||||
}
|
||||
|
||||
export interface EventDetail extends EventAccess {
|
||||
folders: EventFolderRow[];
|
||||
}
|
||||
|
||||
export interface EventFolderDetail {
|
||||
folder: EventFolderRow;
|
||||
event: EventSummaryRow;
|
||||
photos: EventPhotoRow[];
|
||||
canManage: boolean;
|
||||
canContribute: boolean;
|
||||
}
|
||||
|
||||
export type StoredEventPhoto = Omit<EventPhotoRow, "uploaderName">;
|
||||
|
||||
export interface EventPhotoAccess {
|
||||
photo: StoredEventPhoto;
|
||||
eventId: string;
|
||||
canManage: boolean;
|
||||
}
|
||||
|
||||
export interface EventFolderAccess {
|
||||
folder: EventFolderRow;
|
||||
eventId: string;
|
||||
canManage: boolean;
|
||||
canContribute: boolean;
|
||||
}
|
||||
|
||||
export interface EventArchivePhotoRow {
|
||||
id: string;
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
filename: string;
|
||||
kind: "raw" | "image";
|
||||
storedName: string;
|
||||
editedStoredName: string | null;
|
||||
editedSizeBytes: number | null;
|
||||
editJson: string | null;
|
||||
sizeBytes: number;
|
||||
}
|
||||
|
||||
export interface AssignableUser {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
function numeric(value: number | string | null | undefined): number {
|
||||
return Number(value ?? 0);
|
||||
}
|
||||
|
||||
async function photographersFor(
|
||||
eventIds: readonly string[],
|
||||
): Promise<EventPhotographerRow[]> {
|
||||
if (eventIds.length === 0) return [];
|
||||
const rows = await db
|
||||
.select({
|
||||
eventId: eventPhotographers.eventId,
|
||||
userId: eventPhotographers.userId,
|
||||
role: eventPhotographers.role,
|
||||
name: userName,
|
||||
email: users.email,
|
||||
})
|
||||
.from(eventPhotographers)
|
||||
.innerJoin(users, eq(users.id, eventPhotographers.userId))
|
||||
.where(inArray(eventPhotographers.eventId, [...eventIds]))
|
||||
.orderBy(asc(users.lastName), asc(users.firstName));
|
||||
|
||||
return rows.map((row) => ({
|
||||
eventId: row.eventId,
|
||||
userId: row.userId,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
role: row.role,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Folder rows with photo counts, grouped by event. */
|
||||
async function foldersFor(
|
||||
eventIds: readonly string[],
|
||||
): Promise<Map<string, EventFolderRow[]>> {
|
||||
const byEvent = new Map<string, EventFolderRow[]>();
|
||||
if (eventIds.length === 0) return byEvent;
|
||||
|
||||
const counts = await db
|
||||
.select({
|
||||
folderId: eventFolders.id,
|
||||
eventId: eventFolders.eventId,
|
||||
name: eventFolders.name,
|
||||
kind: eventFolders.kind,
|
||||
createdAt: eventFolders.createdAt,
|
||||
photoCount: sql<number>`count(${eventPhotos.id})`,
|
||||
totalBytes: sql<number>`coalesce(sum(${eventPhotos.sizeBytes}), 0)`,
|
||||
})
|
||||
.from(eventFolders)
|
||||
.leftJoin(eventPhotos, eq(eventPhotos.folderId, eventFolders.id))
|
||||
.where(inArray(eventFolders.eventId, [...eventIds]))
|
||||
.groupBy(eventFolders.id)
|
||||
.orderBy(asc(eventFolders.createdAt));
|
||||
|
||||
for (const row of counts) {
|
||||
const list = byEvent.get(row.eventId) ?? [];
|
||||
list.push({
|
||||
id: row.folderId,
|
||||
name: row.name,
|
||||
kind: row.kind,
|
||||
createdAt: row.createdAt,
|
||||
photoCount: numeric(row.photoCount),
|
||||
totalBytes: numeric(row.totalBytes),
|
||||
});
|
||||
byEvent.set(row.eventId, list);
|
||||
}
|
||||
return byEvent;
|
||||
}
|
||||
|
||||
function summarise(
|
||||
row: typeof events.$inferSelect,
|
||||
photographers: EventPhotographerRow[],
|
||||
folders: EventFolderRow[],
|
||||
): EventSummaryRow {
|
||||
return {
|
||||
id: row.id,
|
||||
title: row.title,
|
||||
eventType: row.eventType,
|
||||
startsAt: row.startsAt,
|
||||
endsAt: row.endsAt,
|
||||
location: row.location,
|
||||
description: row.description,
|
||||
photographers,
|
||||
folderCount: folders.length,
|
||||
photoCount: folders.reduce((total, folder) => total + folder.photoCount, 0),
|
||||
};
|
||||
}
|
||||
|
||||
async function summaryFor(
|
||||
row: typeof events.$inferSelect,
|
||||
): Promise<EventSummaryRow> {
|
||||
const [photographers, folders] = await Promise.all([
|
||||
photographersFor([row.id]),
|
||||
foldersFor([row.id]),
|
||||
]);
|
||||
return summarise(row, photographers, folders.get(row.id) ?? []);
|
||||
}
|
||||
|
||||
/**
|
||||
* Events the caller can open: all events for a manager, only assigned events
|
||||
* for everyone else. Newest first, so the most recent shoot is on top.
|
||||
*/
|
||||
export async function listEventsForUser(
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventSummaryRow[]> {
|
||||
const rows: (typeof events.$inferSelect)[] = canManageEvents(role)
|
||||
? await db
|
||||
.select()
|
||||
.from(events)
|
||||
.orderBy(desc(events.startsAt), asc(events.title))
|
||||
: (
|
||||
await db
|
||||
.select({ event: events })
|
||||
.from(events)
|
||||
.innerJoin(
|
||||
eventPhotographers,
|
||||
and(
|
||||
eq(eventPhotographers.eventId, events.id),
|
||||
eq(eventPhotographers.userId, userId),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(events.startsAt), asc(events.title))
|
||||
).map((row) => row.event);
|
||||
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const ids = rows.map((row) => row.id);
|
||||
const [photographers, folders] = await Promise.all([
|
||||
photographersFor(ids),
|
||||
foldersFor(ids),
|
||||
]);
|
||||
|
||||
return rows.map((row) =>
|
||||
summarise(
|
||||
row,
|
||||
photographers.filter((person) => person.eventId === row.id),
|
||||
folders.get(row.id) ?? [],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Null when the event does not exist or the caller is not allowed to see it. */
|
||||
export async function getEventAccess(
|
||||
eventId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventAccess | null> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(events)
|
||||
.where(eq(events.id, eventId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
|
||||
const event = await summaryFor(row);
|
||||
const canManage = canManageEvents(role);
|
||||
const photographerIds = event.photographers.map((person) => person.userId);
|
||||
if (!canManage && !photographerIds.includes(userId)) return null;
|
||||
|
||||
return {
|
||||
event,
|
||||
canManage,
|
||||
canContribute: canContributeToEvent(role, userId, photographerIds),
|
||||
};
|
||||
}
|
||||
|
||||
/** As access, plus the folder list the detail page renders. */
|
||||
export async function getEventDetail(
|
||||
eventId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventDetail | null> {
|
||||
const access = await getEventAccess(eventId, userId, role);
|
||||
if (!access) return null;
|
||||
const folders = (await foldersFor([eventId])).get(eventId) ?? [];
|
||||
return { ...access, folders };
|
||||
}
|
||||
|
||||
/** Folder + access without loading every photo (the upload route uses this). */
|
||||
export async function getEventFolderAccess(
|
||||
folderId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventFolderAccess | null> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
folder: eventFolders,
|
||||
photoCount: sql<number>`(select count(*) from ${eventPhotos} where ${eventPhotos.folderId} = ${eventFolders.id})`,
|
||||
totalBytes: sql<number>`(select coalesce(sum(${eventPhotos.sizeBytes}), 0) from ${eventPhotos} where ${eventPhotos.folderId} = ${eventFolders.id})`,
|
||||
})
|
||||
.from(eventFolders)
|
||||
.where(eq(eventFolders.id, folderId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
|
||||
const access = await getEventAccess(row.folder.eventId, userId, role);
|
||||
if (!access) return null;
|
||||
|
||||
return {
|
||||
folder: {
|
||||
id: row.folder.id,
|
||||
name: row.folder.name,
|
||||
kind: row.folder.kind,
|
||||
createdAt: row.folder.createdAt,
|
||||
photoCount: numeric(row.photoCount),
|
||||
totalBytes: numeric(row.totalBytes),
|
||||
},
|
||||
eventId: row.folder.eventId,
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
};
|
||||
}
|
||||
|
||||
/** Null when the folder is unknown or its event is not visible to the caller. */
|
||||
export async function getFolderDetail(
|
||||
folderId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventFolderDetail | null> {
|
||||
const [folder] = await db
|
||||
.select()
|
||||
.from(eventFolders)
|
||||
.where(eq(eventFolders.id, folderId))
|
||||
.limit(1);
|
||||
if (!folder) return null;
|
||||
|
||||
const access = await getEventAccess(folder.eventId, userId, role);
|
||||
if (!access) return null;
|
||||
|
||||
const photos = await db
|
||||
.select({
|
||||
id: eventPhotos.id,
|
||||
folderId: eventPhotos.folderId,
|
||||
uploaderId: eventPhotos.uploaderId,
|
||||
uploaderName: userName,
|
||||
filename: eventPhotos.filename,
|
||||
mimeType: eventPhotos.mimeType,
|
||||
sizeBytes: eventPhotos.sizeBytes,
|
||||
storedName: eventPhotos.storedName,
|
||||
checksumSha256: eventPhotos.checksumSha256,
|
||||
kind: eventPhotos.kind,
|
||||
editJson: eventPhotos.editJson,
|
||||
editedStoredName: eventPhotos.editedStoredName,
|
||||
editedSizeBytes: eventPhotos.editedSizeBytes,
|
||||
editedAt: eventPhotos.editedAt,
|
||||
editedBy: eventPhotos.editedBy,
|
||||
createdAt: eventPhotos.createdAt,
|
||||
})
|
||||
.from(eventPhotos)
|
||||
.innerJoin(users, eq(users.id, eventPhotos.uploaderId))
|
||||
.where(eq(eventPhotos.folderId, folderId))
|
||||
.orderBy(asc(eventPhotos.createdAt));
|
||||
|
||||
const totalBytes = photos.reduce((sum, photo) => sum + photo.sizeBytes, 0);
|
||||
return {
|
||||
folder: {
|
||||
id: folder.id,
|
||||
name: folder.name,
|
||||
kind: folder.kind,
|
||||
createdAt: folder.createdAt,
|
||||
photoCount: photos.length,
|
||||
totalBytes,
|
||||
},
|
||||
event: access.event,
|
||||
photos,
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Every photo in an event with its folder name, for the whole-event ZIP. The
|
||||
* caller must check event access first; this query intentionally does not.
|
||||
*/
|
||||
export async function listEventPhotosForArchive(
|
||||
eventId: string,
|
||||
): Promise<EventArchivePhotoRow[]> {
|
||||
return db
|
||||
.select({
|
||||
id: eventPhotos.id,
|
||||
folderId: eventPhotos.folderId,
|
||||
folderName: eventFolders.name,
|
||||
filename: eventPhotos.filename,
|
||||
kind: eventPhotos.kind,
|
||||
storedName: eventPhotos.storedName,
|
||||
editedStoredName: eventPhotos.editedStoredName,
|
||||
editedSizeBytes: eventPhotos.editedSizeBytes,
|
||||
editJson: eventPhotos.editJson,
|
||||
sizeBytes: eventPhotos.sizeBytes,
|
||||
})
|
||||
.from(eventPhotos)
|
||||
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
|
||||
.where(eq(eventFolders.eventId, eventId))
|
||||
.orderBy(asc(eventFolders.createdAt), asc(eventPhotos.createdAt));
|
||||
}
|
||||
|
||||
/** Photo + access check in one call; used by the stream and delete routes. */
|
||||
export async function getEventPhotoAccess(
|
||||
photoId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventPhotoAccess | null> {
|
||||
const [row] = await db
|
||||
.select({ photo: eventPhotos, eventId: eventFolders.eventId })
|
||||
.from(eventPhotos)
|
||||
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
|
||||
.where(eq(eventPhotos.id, photoId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
|
||||
const access = await getEventAccess(row.eventId, userId, role);
|
||||
if (!access) return null;
|
||||
|
||||
return {
|
||||
photo: row.photo,
|
||||
eventId: row.eventId,
|
||||
canManage: access.canManage,
|
||||
};
|
||||
}
|
||||
|
||||
/** True when a person appears as an uploader on any event photo. */
|
||||
export async function hasEventUploads(userId: string): Promise<boolean> {
|
||||
const [row] = await db
|
||||
.select({ id: eventPhotos.id })
|
||||
.from(eventPhotos)
|
||||
.where(eq(eventPhotos.uploaderId, userId))
|
||||
.limit(1);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
export async function listAssignableUsers(): Promise<AssignableUser[]> {
|
||||
return db
|
||||
.select({ id: users.id, name: userName, email: users.email })
|
||||
.from(users)
|
||||
.where(and(eq(users.status, "active"), isNull(users.deactivatedAt)))
|
||||
.orderBy(asc(users.lastName), asc(users.firstName));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard-delete an event and its folders/photos. Returns the photo count for the
|
||||
* audit row; the route removes the bytes under `UPLOAD_DIR/events/<id>` after
|
||||
* the transaction commits.
|
||||
*/
|
||||
export async function deleteEvent(eventId: string) {
|
||||
return db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.select()
|
||||
.from(events)
|
||||
.where(eq(events.id, eventId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
|
||||
const [countRow] = await tx
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(eventPhotos)
|
||||
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
|
||||
.where(eq(eventFolders.eventId, eventId));
|
||||
|
||||
// Pending reminders for a deleted event must never be sent.
|
||||
await tx
|
||||
.update(notifications)
|
||||
.set({ status: "cancelled", updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
sql`${notifications.dedupeKey} LIKE ${`event.reminder:${eventId}:%`}`,
|
||||
inArray(notifications.status, ["queued", "failed"]),
|
||||
),
|
||||
);
|
||||
|
||||
await tx.delete(events).where(eq(events.id, eventId));
|
||||
return { event: row, photoCount: numeric(countRow?.count) };
|
||||
});
|
||||
}
|
||||
|
||||
export async function createEvent(input: {
|
||||
title: string;
|
||||
eventType: string;
|
||||
startsAt: Date;
|
||||
endsAt?: Date | null;
|
||||
location?: string | null;
|
||||
description?: string | null;
|
||||
createdBy: string;
|
||||
}) {
|
||||
const [row] = await db
|
||||
.insert(events)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
title: input.title,
|
||||
eventType: input.eventType,
|
||||
startsAt: input.startsAt,
|
||||
endsAt: input.endsAt ?? null,
|
||||
location: input.location ?? null,
|
||||
description: input.description ?? null,
|
||||
createdBy: input.createdBy,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add or re-role an assignee. Returns null when the person is not an active
|
||||
* account, so an admin cannot assign a pending or deactivated volunteer.
|
||||
*/
|
||||
export async function assignEventPhotographer(input: {
|
||||
eventId: string;
|
||||
userId: string;
|
||||
role: EventPhotographerRole;
|
||||
assignedBy: string;
|
||||
}) {
|
||||
const [person] = await db
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.id, input.userId),
|
||||
eq(users.status, "active"),
|
||||
isNull(users.deactivatedAt),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
if (!person) return null;
|
||||
|
||||
const [row] = await db
|
||||
.insert(eventPhotographers)
|
||||
.values({
|
||||
eventId: input.eventId,
|
||||
userId: input.userId,
|
||||
role: input.role,
|
||||
assignedBy: input.assignedBy,
|
||||
assignedAt: new Date(),
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [eventPhotographers.eventId, eventPhotographers.userId],
|
||||
set: {
|
||||
role: input.role,
|
||||
assignedBy: input.assignedBy,
|
||||
assignedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function removeEventPhotographer(eventId: string, userId: string) {
|
||||
const [row] = await db
|
||||
.delete(eventPhotographers)
|
||||
.where(
|
||||
and(
|
||||
eq(eventPhotographers.eventId, eventId),
|
||||
eq(eventPhotographers.userId, userId),
|
||||
),
|
||||
)
|
||||
.returning();
|
||||
if (row) {
|
||||
// Someone taken off the shoot should not receive its reminder.
|
||||
await db
|
||||
.update(notifications)
|
||||
.set({ status: "cancelled", updatedAt: new Date() })
|
||||
.where(
|
||||
and(
|
||||
eq(notifications.dedupeKey, `event.reminder:${eventId}:${userId}:email`),
|
||||
inArray(notifications.status, ["queued", "failed"]),
|
||||
),
|
||||
);
|
||||
}
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function createEventFolder(input: {
|
||||
eventId: string;
|
||||
name: string;
|
||||
kind: EventFolderKind;
|
||||
createdBy: string;
|
||||
}) {
|
||||
const [row] = await db
|
||||
.insert(eventFolders)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
eventId: input.eventId,
|
||||
name: input.name,
|
||||
kind: input.kind,
|
||||
createdBy: input.createdBy,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function addEventPhoto(input: {
|
||||
folderId: string;
|
||||
uploaderId: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
storedName: string;
|
||||
checksumSha256: string;
|
||||
kind: "raw" | "image";
|
||||
}) {
|
||||
const [row] = await db
|
||||
.insert(eventPhotos)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
folderId: input.folderId,
|
||||
uploaderId: input.uploaderId,
|
||||
filename: input.filename,
|
||||
mimeType: input.mimeType,
|
||||
sizeBytes: input.sizeBytes,
|
||||
storedName: input.storedName,
|
||||
checksumSha256: input.checksumSha256,
|
||||
kind: input.kind,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function findEventPhotoByChecksum(
|
||||
folderId: string,
|
||||
checksumSha256: string,
|
||||
) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(eventPhotos)
|
||||
.where(
|
||||
and(
|
||||
eq(eventPhotos.folderId, folderId),
|
||||
eq(eventPhotos.checksumSha256, checksumSha256),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function updateEventPhotoEdit(input: {
|
||||
photoId: string;
|
||||
editJson: string;
|
||||
editedStoredName: string;
|
||||
editedSizeBytes: number;
|
||||
editedBy: string;
|
||||
}) {
|
||||
const [row] = await db
|
||||
.update(eventPhotos)
|
||||
.set({
|
||||
editJson: input.editJson,
|
||||
editedStoredName: input.editedStoredName,
|
||||
editedSizeBytes: input.editedSizeBytes,
|
||||
editedAt: new Date(),
|
||||
editedBy: input.editedBy,
|
||||
})
|
||||
.where(eq(eventPhotos.id, input.photoId))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function deleteEventPhoto(id: string) {
|
||||
const [row] = await db
|
||||
.delete(eventPhotos)
|
||||
.where(eq(eventPhotos.id, id))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Postgres unique_violation, unwrapped from a Drizzle/pg error. */
|
||||
export function isUniqueViolation(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code?: string }).code === "23505"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/**
|
||||
* CSV exports for coordinators: the schedule in a date range and serving
|
||||
* history. Printing is handled by the browser's print dialog on the run sheet
|
||||
* and the printable schedule; these endpoints cover spreadsheet use.
|
||||
*/
|
||||
|
||||
import { and, asc, eq, gte, inArray, lte, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
roles,
|
||||
serviceInstances,
|
||||
services,
|
||||
slots,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
|
||||
import { toCsv } from "@/lib/csv";
|
||||
|
||||
export interface ScheduleExportRow {
|
||||
occursOn: Date | null;
|
||||
serviceName: string;
|
||||
startsAt: Date | null;
|
||||
callTime: Date | null;
|
||||
roleName: string;
|
||||
userName: string;
|
||||
email: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export async function scheduleExportRows(
|
||||
fromISO: string,
|
||||
toISO: string,
|
||||
): Promise<ScheduleExportRow[]> {
|
||||
const from = new Date(`${fromISO}T00:00:00Z`);
|
||||
const to = new Date(`${toISO}T23:59:59Z`);
|
||||
return db
|
||||
.select({
|
||||
occursOn: serviceInstances.occursOn,
|
||||
serviceName: services.name,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
callTime: slots.callTime,
|
||||
roleName: roles.name,
|
||||
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
email: users.email,
|
||||
status: assignments.status,
|
||||
})
|
||||
.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(
|
||||
gte(serviceInstances.occursOn, from),
|
||||
lte(serviceInstances.occursOn, to),
|
||||
inArray(assignments.status, [
|
||||
"proposed",
|
||||
"confirmed",
|
||||
"completed",
|
||||
"no_show",
|
||||
]),
|
||||
),
|
||||
)
|
||||
.orderBy(
|
||||
asc(serviceInstances.startsAt),
|
||||
asc(roles.sortOrder),
|
||||
asc(slots.slotIndex),
|
||||
);
|
||||
}
|
||||
|
||||
export async function scheduleCsv(fromISO: string, toISO: string): Promise<string> {
|
||||
const rows = await scheduleExportRows(fromISO, toISO);
|
||||
return toCsv(
|
||||
["Date", "Service", "Start", "Call time", "Role", "Volunteer", "Email", "Status"],
|
||||
rows.map((row) => [
|
||||
row.occursOn ? isoDateUTC(row.occursOn) : "",
|
||||
row.serviceName,
|
||||
row.startsAt
|
||||
? formatInTimezone(row.startsAt, CHURCH_TIMEZONE, {
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
: "",
|
||||
row.callTime
|
||||
? formatInTimezone(row.callTime, CHURCH_TIMEZONE, {
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
: "",
|
||||
row.roleName,
|
||||
row.userName,
|
||||
row.email,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
export async function servingHistoryCsv(userId?: string): Promise<string> {
|
||||
const rows = await db
|
||||
.select({
|
||||
occursOn: serviceInstances.occursOn,
|
||||
serviceName: services.name,
|
||||
roleName: roles.name,
|
||||
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
email: users.email,
|
||||
status: assignments.status,
|
||||
respondedAt: assignments.respondedAt,
|
||||
})
|
||||
.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(
|
||||
inArray(assignments.status, ["completed", "no_show"]),
|
||||
userId ? eq(assignments.userId, userId) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.startsAt), asc(roles.sortOrder));
|
||||
|
||||
return toCsv(
|
||||
["Date", "Service", "Role", "Volunteer", "Email", "Outcome"],
|
||||
rows.map((row) => [
|
||||
row.occursOn ? isoDateUTC(row.occursOn) : "",
|
||||
row.serviceName,
|
||||
row.roleName,
|
||||
row.userName,
|
||||
row.email,
|
||||
row.status,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
function isoDateUTC(date: Date): string {
|
||||
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
+123
-81
@@ -1,13 +1,18 @@
|
||||
/**
|
||||
* Grid data — unit D7 (ARCHITECTURE §5.8.4).
|
||||
*
|
||||
* The read-only scheduling grid: rows = service instances, cols = active
|
||||
* positions (roles, by `sort_order`), each cell = one slot with its
|
||||
* assignment. This module is the single data source for the grid — the page
|
||||
* fetches a week and the component renders it. Pure data, no JSX.
|
||||
* The scheduling grid: rows = service instances, columns = active positions
|
||||
* (roles, by `sort_order`), each cell = the seats for that position with their
|
||||
* active assignment. This module is the single data source for the grid — the
|
||||
* page fetches a week and the component renders it. Pure data, no JSX.
|
||||
*
|
||||
* One joined query per week (instances × slots × roles × active assignments ×
|
||||
* users) rather than per-instance/per-slot loops. Only `proposed`,
|
||||
* `confirmed` and `completed` assignments are returned, so a declined row that
|
||||
* shares a slot with its replacement never masks the live one.
|
||||
*/
|
||||
|
||||
import { and, eq, gte, lte } from "drizzle-orm";
|
||||
import { and, eq, gte, inArray, lte } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
@@ -34,6 +39,7 @@ export interface GridSlot {
|
||||
callTime: Date | null;
|
||||
status: string;
|
||||
isTraineeSlot: boolean;
|
||||
pairedWithUserId: string | null;
|
||||
assignments: GridAssignment[];
|
||||
}
|
||||
|
||||
@@ -62,17 +68,7 @@ export interface GridWeek {
|
||||
instances: GridInstance[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Grid data for one week (Sunday–Saturday). `weekStart` is a YYYY-MM-DD
|
||||
* Sunday. Instances are ordered by date then start time; slots within an
|
||||
* instance by slot index; positions by role sort order.
|
||||
*/
|
||||
function occursOnISO(d: Date): string {
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
const ACTIVE_ASSIGNMENT_STATUSES = ["proposed", "confirmed", "completed"] as const;
|
||||
|
||||
/**
|
||||
* The `occurs_on` column stores a church-local calendar date. Drizzle returns a
|
||||
@@ -82,93 +78,139 @@ function occursOnISO(d: Date): string {
|
||||
* clock in the church timezone and shift the date a day early (e.g. 2026-11-23
|
||||
* stored as 2026-11-23T00:00:00Z would render as 2026-11-22 in America/New_York).
|
||||
*/
|
||||
function occursOnISO(d: Date | null): string {
|
||||
if (!d) return "";
|
||||
const y = d.getUTCFullYear();
|
||||
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
||||
const day = String(d.getUTCDate()).padStart(2, "0");
|
||||
return `${y}-${m}-${day}`;
|
||||
}
|
||||
|
||||
/** Grid data for one week (Sunday–Saturday). `weekStart` is a YYYY-MM-DD Sunday. */
|
||||
export async function gridForWeek(weekStart: string): Promise<GridWeek> {
|
||||
const weekEnd = addDaysISO(weekStart, 6);
|
||||
const weekStartDate = new Date(`${weekStart}T00:00:00Z`);
|
||||
const weekEndDate = new Date(`${weekEnd}T00:00:00Z`);
|
||||
|
||||
const instances = await db
|
||||
.select()
|
||||
.from(serviceInstances)
|
||||
.where(
|
||||
and(
|
||||
gte(serviceInstances.occursOn, weekStartDate),
|
||||
lte(serviceInstances.occursOn, weekEndDate),
|
||||
),
|
||||
)
|
||||
.orderBy(serviceInstances.occursOn, serviceInstances.startsAt);
|
||||
|
||||
const roleRows = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(eq(roles.active, true))
|
||||
.orderBy(roles.sortOrder);
|
||||
|
||||
const positions: GridPosition[] = roleRows.map((r) => ({
|
||||
slug: r.slug,
|
||||
name: r.name,
|
||||
colorHex: r.colorHex,
|
||||
}));
|
||||
const roleById = new Map(roleRows.map((r) => [r.id, r]));
|
||||
|
||||
const serviceById = new Map(
|
||||
(await db.select().from(services)).map((s) => [s.id, s.name]),
|
||||
);
|
||||
const rows = await db
|
||||
.select({
|
||||
instanceId: serviceInstances.id,
|
||||
serviceId: serviceInstances.serviceId,
|
||||
serviceName: services.name,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
instanceStatus: serviceInstances.status,
|
||||
titleOverride: serviceInstances.titleOverride,
|
||||
slotId: slots.id,
|
||||
slotIndex: slots.slotIndex,
|
||||
callTime: slots.callTime,
|
||||
slotStatus: slots.status,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
pairedWithUserId: slots.pairedWithUserId,
|
||||
roleId: roles.id,
|
||||
roleSlug: roles.slug,
|
||||
roleName: roles.name,
|
||||
assignmentUserId: assignments.userId,
|
||||
assignmentStatus: assignments.status,
|
||||
assignmentUserName: users.displayName,
|
||||
assignmentFirstName: users.firstName,
|
||||
assignmentLastName: users.lastName,
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||
.leftJoin(slots, eq(slots.serviceInstanceId, serviceInstances.id))
|
||||
.leftJoin(roles, eq(roles.id, slots.roleId))
|
||||
.leftJoin(
|
||||
assignments,
|
||||
and(
|
||||
eq(assignments.slotId, slots.id),
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENT_STATUSES]),
|
||||
),
|
||||
)
|
||||
.leftJoin(users, eq(users.id, assignments.userId))
|
||||
.where(
|
||||
and(
|
||||
gte(serviceInstances.occursOn, weekStartDate),
|
||||
lte(serviceInstances.occursOn, weekEndDate),
|
||||
),
|
||||
)
|
||||
.orderBy(
|
||||
serviceInstances.occursOn,
|
||||
serviceInstances.startsAt,
|
||||
roles.sortOrder,
|
||||
slots.slotIndex,
|
||||
);
|
||||
|
||||
const result: GridInstance[] = [];
|
||||
for (const inst of instances) {
|
||||
const slotRows = await db
|
||||
.select()
|
||||
.from(slots)
|
||||
.where(eq(slots.serviceInstanceId, inst.id))
|
||||
.orderBy(slots.slotIndex);
|
||||
const instances = new Map<string, GridInstance>();
|
||||
const slotIndexes = new Map<string, Map<string, GridSlot>>();
|
||||
|
||||
const slotsOut: GridSlot[] = [];
|
||||
for (const slot of slotRows) {
|
||||
const role = roleById.get(slot.roleId);
|
||||
const assignRows = await db
|
||||
.select()
|
||||
.from(assignments)
|
||||
.where(eq(assignments.slotId, slot.id));
|
||||
const assignmentsOut: GridAssignment[] = [];
|
||||
for (const a of assignRows) {
|
||||
const [user] = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.id, a.userId));
|
||||
assignmentsOut.push({
|
||||
userId: a.userId,
|
||||
displayName: user?.displayName ?? "",
|
||||
status: a.status,
|
||||
});
|
||||
}
|
||||
slotsOut.push({
|
||||
id: slot.id,
|
||||
roleId: slot.roleId,
|
||||
roleSlug: role?.slug ?? "",
|
||||
roleName: role?.name ?? "",
|
||||
slotIndex: slot.slotIndex,
|
||||
callTime: slot.callTime,
|
||||
status: slot.status,
|
||||
isTraineeSlot: slot.isTraineeSlot,
|
||||
assignments: assignmentsOut,
|
||||
});
|
||||
for (const row of rows) {
|
||||
let instance = instances.get(row.instanceId);
|
||||
if (!instance) {
|
||||
instance = {
|
||||
id: row.instanceId,
|
||||
serviceId: row.serviceId,
|
||||
serviceName: row.serviceName,
|
||||
occursOn: occursOnISO(row.occursOn),
|
||||
startsAt: row.startsAt ?? new Date(0),
|
||||
titleOverride: row.titleOverride ?? null,
|
||||
status: row.instanceStatus,
|
||||
slots: [],
|
||||
};
|
||||
instances.set(row.instanceId, instance);
|
||||
slotIndexes.set(row.instanceId, new Map());
|
||||
}
|
||||
|
||||
result.push({
|
||||
id: inst.id,
|
||||
serviceId: inst.serviceId,
|
||||
serviceName: serviceById.get(inst.serviceId) ?? "",
|
||||
occursOn: inst.occursOn
|
||||
? occursOnISO(inst.occursOn)
|
||||
: "",
|
||||
startsAt: inst.startsAt ?? new Date(),
|
||||
titleOverride: inst.titleOverride ?? null,
|
||||
status: inst.status,
|
||||
slots: slotsOut,
|
||||
});
|
||||
if (!row.slotId) continue;
|
||||
|
||||
const bySlot = slotIndexes.get(row.instanceId)!;
|
||||
let slot = bySlot.get(row.slotId);
|
||||
if (!slot) {
|
||||
slot = {
|
||||
id: row.slotId,
|
||||
roleId: row.roleId ?? "",
|
||||
roleSlug: row.roleSlug ?? "",
|
||||
roleName: row.roleName ?? "",
|
||||
slotIndex: row.slotIndex ?? 1,
|
||||
callTime: row.callTime ?? null,
|
||||
status: row.slotStatus ?? "open",
|
||||
isTraineeSlot: row.isTraineeSlot ?? false,
|
||||
pairedWithUserId: row.pairedWithUserId ?? null,
|
||||
assignments: [],
|
||||
};
|
||||
bySlot.set(row.slotId, slot);
|
||||
instance.slots.push(slot);
|
||||
}
|
||||
|
||||
if (row.assignmentUserId) {
|
||||
slot.assignments.push({
|
||||
userId: row.assignmentUserId,
|
||||
displayName:
|
||||
row.assignmentUserName ??
|
||||
`${row.assignmentFirstName ?? ""} ${row.assignmentLastName ?? ""}`.trim(),
|
||||
status: row.assignmentStatus ?? "proposed",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { weekStart, weekEnd, positions, instances: result };
|
||||
return {
|
||||
weekStart,
|
||||
weekEnd,
|
||||
positions,
|
||||
instances: [...instances.values()],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Public media-coverage intake.
|
||||
*
|
||||
* A ministry leader describes an event; a coordinator reviews the queue and
|
||||
* converts an accepted request into an event, which already carries the
|
||||
* photographer assignment, folders and file-sharing workflow. Nothing is
|
||||
* scheduled automatically, so a public form cannot create seats or notify
|
||||
* volunteers on its own.
|
||||
*/
|
||||
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { auditLog, coverageIntakes, events } from "@/db/schema";
|
||||
import { auditRow } from "@/db/audit";
|
||||
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
export interface CoverageIntakeRow {
|
||||
id: string;
|
||||
requesterName: string;
|
||||
requesterEmail: string;
|
||||
requesterPhone: string | null;
|
||||
ministry: string | null;
|
||||
title: string;
|
||||
eventType: string;
|
||||
startsAt: Date;
|
||||
endsAt: Date | null;
|
||||
location: string | null;
|
||||
description: string | null;
|
||||
status: string;
|
||||
createdEventId: string | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export interface CoverageIntakeInput {
|
||||
requesterName: string;
|
||||
requesterEmail: string;
|
||||
requesterPhone?: string | null;
|
||||
ministry?: string | null;
|
||||
title: string;
|
||||
eventType?: string;
|
||||
/** Local calendar date + wall-clock time in the church timezone. */
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime?: string | null;
|
||||
location?: string | null;
|
||||
description?: string | null;
|
||||
}
|
||||
|
||||
export class IntakeError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "IntakeError";
|
||||
}
|
||||
}
|
||||
|
||||
export async function createCoverageIntake(
|
||||
input: CoverageIntakeInput,
|
||||
): Promise<{ id: string }> {
|
||||
const startsAt = localToUtc(input.date, input.startTime, CHURCH_TIMEZONE);
|
||||
const endsAt = input.endTime
|
||||
? localToUtc(input.date, input.endTime, CHURCH_TIMEZONE)
|
||||
: null;
|
||||
|
||||
if (Number.isNaN(startsAt.getTime())) {
|
||||
throw new IntakeError(400, "invalid start date or time");
|
||||
}
|
||||
if (endsAt && endsAt <= startsAt) {
|
||||
throw new IntakeError(400, "end time must be after the start time");
|
||||
}
|
||||
|
||||
const id = uuidv7();
|
||||
await db.insert(coverageIntakes).values({
|
||||
id,
|
||||
requesterName: input.requesterName.trim(),
|
||||
requesterEmail: input.requesterEmail.trim().toLowerCase(),
|
||||
requesterPhone: input.requesterPhone?.trim() || null,
|
||||
ministry: input.ministry?.trim() || null,
|
||||
title: input.title.trim(),
|
||||
eventType: input.eventType?.trim() || "coverage",
|
||||
startsAt,
|
||||
endsAt,
|
||||
location: input.location?.trim() || null,
|
||||
description: input.description?.trim() || null,
|
||||
status: "new",
|
||||
});
|
||||
return { id };
|
||||
}
|
||||
|
||||
export async function listCoverageIntakes(
|
||||
status?: string,
|
||||
): Promise<CoverageIntakeRow[]> {
|
||||
const query = db.select().from(coverageIntakes);
|
||||
const rows = status
|
||||
? await query
|
||||
.where(eq(coverageIntakes.status, status as "new"))
|
||||
.orderBy(desc(coverageIntakes.createdAt))
|
||||
: await query.orderBy(desc(coverageIntakes.createdAt));
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Convert an accepted request into an event the media team can staff. */
|
||||
export async function scheduleCoverageIntake(input: {
|
||||
id: string;
|
||||
actorId: string;
|
||||
}): Promise<{ eventId: string }> {
|
||||
const [intake] = await db
|
||||
.select()
|
||||
.from(coverageIntakes)
|
||||
.where(eq(coverageIntakes.id, input.id))
|
||||
.limit(1);
|
||||
if (!intake) throw new IntakeError(404, "request not found");
|
||||
if (intake.status !== "new") {
|
||||
throw new IntakeError(409, "this request has already been reviewed");
|
||||
}
|
||||
|
||||
const eventId = uuidv7();
|
||||
const contact = [
|
||||
`Requested by ${intake.requesterName} (${intake.requesterEmail}` +
|
||||
(intake.requesterPhone ? `, ${intake.requesterPhone}` : "") +
|
||||
")",
|
||||
intake.ministry ? `Ministry: ${intake.ministry}` : null,
|
||||
intake.description,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
const now = new Date();
|
||||
await db.transaction(async (tx) => {
|
||||
await tx.insert(events).values({
|
||||
id: eventId,
|
||||
title: intake.title,
|
||||
eventType: intake.eventType,
|
||||
startsAt: intake.startsAt,
|
||||
endsAt: intake.endsAt,
|
||||
location: intake.location,
|
||||
description: contact,
|
||||
createdBy: input.actorId,
|
||||
});
|
||||
await tx
|
||||
.update(coverageIntakes)
|
||||
.set({
|
||||
status: "scheduled",
|
||||
createdEventId: eventId,
|
||||
reviewedBy: input.actorId,
|
||||
reviewedAt: now,
|
||||
})
|
||||
.where(eq(coverageIntakes.id, input.id));
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: input.actorId,
|
||||
action: "coverage_intake.scheduled",
|
||||
entityType: "coverage_intake",
|
||||
entityId: input.id,
|
||||
after: { eventId, title: intake.title },
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return { eventId };
|
||||
}
|
||||
|
||||
export async function declineCoverageIntake(input: {
|
||||
id: string;
|
||||
actorId: string;
|
||||
}): Promise<void> {
|
||||
const now = new Date();
|
||||
const rows = await db
|
||||
.update(coverageIntakes)
|
||||
.set({
|
||||
status: "declined",
|
||||
reviewedBy: input.actorId,
|
||||
reviewedAt: now,
|
||||
})
|
||||
.where(eq(coverageIntakes.id, input.id))
|
||||
.returning({ id: coverageIntakes.id });
|
||||
if (rows.length === 0) throw new IntakeError(404, "request not found");
|
||||
await db.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: input.actorId,
|
||||
action: "coverage_intake.declined",
|
||||
entityType: "coverage_intake",
|
||||
entityId: input.id,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Cross-event media queries for the Media library page. Access is decided by
|
||||
* the caller: only event ids the signed-in account may open are passed in.
|
||||
*/
|
||||
|
||||
import { desc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { eventFolders, eventPhotos, events, users } from "@/db/schema";
|
||||
|
||||
export interface MediaPhotoRow {
|
||||
id: string;
|
||||
eventId: string;
|
||||
eventTitle: string;
|
||||
eventStartsAt: Date;
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
uploaderName: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
kind: "raw" | "image";
|
||||
editedStoredName: string | null;
|
||||
editedSizeBytes: number | null;
|
||||
editedAt: Date | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||
|
||||
export async function listMediaPhotosForEvents(
|
||||
eventIds: readonly string[],
|
||||
): Promise<MediaPhotoRow[]> {
|
||||
if (eventIds.length === 0) return [];
|
||||
|
||||
return db
|
||||
.select({
|
||||
id: eventPhotos.id,
|
||||
eventId: events.id,
|
||||
eventTitle: events.title,
|
||||
eventStartsAt: events.startsAt,
|
||||
folderId: eventFolders.id,
|
||||
folderName: eventFolders.name,
|
||||
uploaderName: userName,
|
||||
filename: eventPhotos.filename,
|
||||
mimeType: eventPhotos.mimeType,
|
||||
sizeBytes: eventPhotos.sizeBytes,
|
||||
kind: eventPhotos.kind,
|
||||
editedStoredName: eventPhotos.editedStoredName,
|
||||
editedSizeBytes: eventPhotos.editedSizeBytes,
|
||||
editedAt: eventPhotos.editedAt,
|
||||
createdAt: eventPhotos.createdAt,
|
||||
})
|
||||
.from(eventPhotos)
|
||||
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
|
||||
.innerJoin(events, eq(events.id, eventFolders.eventId))
|
||||
.innerJoin(users, eq(users.id, eventPhotos.uploaderId))
|
||||
.where(inArray(events.id, [...eventIds]))
|
||||
.orderBy(desc(eventPhotos.createdAt));
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
@@ -25,6 +25,14 @@ export type ProfilePatch = Partial<{
|
||||
|
||||
export type ConsentSourceInput = SmsConsentSource;
|
||||
|
||||
export type NotificationPreferencePatch = Partial<{
|
||||
emailEnabled: boolean;
|
||||
reminderLeadDays: number;
|
||||
digestOnly: boolean;
|
||||
quietHoursStart: string;
|
||||
quietHoursEnd: string;
|
||||
}>;
|
||||
|
||||
async function getUserById(userId: string) {
|
||||
const rows = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
return rows[0] ?? null;
|
||||
@@ -109,6 +117,16 @@ export async function setSmsConsent(
|
||||
return upsertPrefs(userId, buildConsent(input.source, input.ip, at));
|
||||
}
|
||||
|
||||
/** Update self-service notification preferences without touching consent fields. */
|
||||
export async function updateNotificationPreferences(
|
||||
userId: string,
|
||||
patch: NotificationPreferencePatch,
|
||||
) {
|
||||
const values: Record<string, unknown> = { ...patch };
|
||||
if (Object.keys(values).length === 0) return getPrefs(userId);
|
||||
return upsertPrefs(userId, values);
|
||||
}
|
||||
|
||||
/** Read a user's profile + preferences (for the profile screen / tests). */
|
||||
export async function getProfile(userId: string) {
|
||||
const [user, ...prefsRows] = await Promise.all([
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Clear stale user-owned rows: `pnpm db:prune`.
|
||||
*
|
||||
* Deletes skill levels (and the other user-owned rows) whose user no longer
|
||||
* exists. Run against whatever `DATABASE_URL` points at:
|
||||
*
|
||||
* DATABASE_URL=postgres://media:media@localhost:5434/media pnpm db:prune
|
||||
*/
|
||||
|
||||
import { pruneOrphanedUserData } from "./cleanup";
|
||||
|
||||
async function main() {
|
||||
const report = await pruneOrphanedUserData();
|
||||
const entries = Object.entries(report);
|
||||
const total = entries.reduce((sum, [, count]) => sum + count, 0);
|
||||
|
||||
for (const [table, count] of entries) {
|
||||
console.log(`${table}: ${count} orphaned row(s) removed`);
|
||||
}
|
||||
console.log(
|
||||
total === 0
|
||||
? "No orphaned user rows found — every row has a live owner."
|
||||
: `Removed ${total} orphaned row(s).`,
|
||||
);
|
||||
// The postgres.js pool keeps the process alive otherwise (same reason the
|
||||
// seed CLI exits explicitly).
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
void main().catch((err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
/**
|
||||
* Publish / unpublish data layer — unit D10 (ARCHITECTURE §5.5).
|
||||
*
|
||||
* One transaction per call: validate, move the instance's status, write the
|
||||
* audit row. D10 deliberately enqueues nothing — notifications are E1. That
|
||||
* separation is why an email outage can never block a schedule.
|
||||
*
|
||||
* No schema change: `service_instances.status`, `published_at` and
|
||||
* `published_by` already exist (A2), and the audit table landed in D8.
|
||||
*/
|
||||
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
auditLog,
|
||||
roles,
|
||||
serviceInstances,
|
||||
slots,
|
||||
} from "@/db/schema";
|
||||
import { auditRow } from "@/db/audit";
|
||||
import {
|
||||
cancelInstanceNotifications,
|
||||
enqueuePublishNotifications,
|
||||
} from "@/db/outbox";
|
||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||
import {
|
||||
validatePublish,
|
||||
validateUnpublish,
|
||||
type PublishGap,
|
||||
} from "@/domain/publish";
|
||||
|
||||
/** Why a publish / unpublish was refused, mapped to an HTTP status by the route. */
|
||||
export type PublishErrorCode =
|
||||
| "unknown_instance"
|
||||
| "instance_cancelled"
|
||||
| "open_slots"
|
||||
| "unpublish_blocked";
|
||||
|
||||
export class PublishError extends Error {
|
||||
readonly code: PublishErrorCode;
|
||||
/** The empty seats, for `open_slots`. */
|
||||
readonly gaps: PublishGap[];
|
||||
|
||||
constructor(code: PublishErrorCode, message: string, gaps: PublishGap[] = []) {
|
||||
super(message);
|
||||
this.name = "PublishError";
|
||||
this.code = code;
|
||||
this.gaps = gaps;
|
||||
}
|
||||
}
|
||||
|
||||
export interface PublishResult {
|
||||
published: boolean;
|
||||
/** True when the instance was already published — the call changed nothing. */
|
||||
alreadyPublished: boolean;
|
||||
/** Seats published empty (empty unless `allowGaps` was used). */
|
||||
gaps: PublishGap[];
|
||||
publishedAt: Date | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish one instance. Rejects with `open_slots` when a covering seat is empty
|
||||
* and `allowGaps` is false; a second publish of an already-published instance is
|
||||
* an idempotent no-op (no write, no second audit row).
|
||||
*/
|
||||
export async function publishInstance(
|
||||
instanceId: string,
|
||||
opts: { actorId: string; allowGaps?: boolean; appOrigin?: string },
|
||||
): Promise<PublishResult> {
|
||||
const allowGaps = opts.allowGaps ?? false;
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const instanceRows = await tx
|
||||
.select({
|
||||
id: serviceInstances.id,
|
||||
status: serviceInstances.status,
|
||||
publishedAt: serviceInstances.publishedAt,
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.where(eq(serviceInstances.id, instanceId))
|
||||
.limit(1);
|
||||
if (instanceRows.length === 0) {
|
||||
throw new PublishError(
|
||||
"unknown_instance",
|
||||
`unknown service instance: ${instanceId}`,
|
||||
);
|
||||
}
|
||||
const instance = instanceRows[0];
|
||||
|
||||
// Idempotent: re-publishing leaves the original publish instant and writes
|
||||
// no duplicate audit row (E1 will key notification dedupe off this).
|
||||
if (instance.status === "published") {
|
||||
return {
|
||||
published: false,
|
||||
alreadyPublished: true,
|
||||
gaps: [],
|
||||
publishedAt: instance.publishedAt,
|
||||
};
|
||||
}
|
||||
if (instance.status === "cancelled") {
|
||||
throw new PublishError(
|
||||
"instance_cancelled",
|
||||
"a cancelled service instance cannot be published",
|
||||
);
|
||||
}
|
||||
|
||||
// Coverage is read from active assignments, not `slots.status`: the slot
|
||||
// status is derived and is not maintained by the assignment writes (D8).
|
||||
const seats = await tx
|
||||
.select({
|
||||
slotId: slots.id,
|
||||
roleName: roles.name,
|
||||
slotIndex: slots.slotIndex,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
hasActiveAssignment: sql<boolean>`EXISTS (
|
||||
SELECT 1 FROM assignments
|
||||
WHERE assignments.slot_id = ${slots.id}
|
||||
AND assignments.status IN ('proposed','confirmed','completed')
|
||||
)`,
|
||||
})
|
||||
.from(slots)
|
||||
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||
.where(eq(slots.serviceInstanceId, instanceId))
|
||||
.orderBy(roles.sortOrder, slots.slotIndex);
|
||||
|
||||
const validation = validatePublish({ seats, allowGaps });
|
||||
if (!validation.ok) {
|
||||
throw new PublishError(
|
||||
"open_slots",
|
||||
`${validation.gaps.length} seat(s) have no volunteer; publish with gaps to override.`,
|
||||
validation.gaps,
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
await tx
|
||||
.update(serviceInstances)
|
||||
.set({ status: "published", publishedAt: now, publishedBy: opts.actorId })
|
||||
.where(eq(serviceInstances.id, instanceId));
|
||||
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: opts.actorId,
|
||||
action: "week.published",
|
||||
entityType: "service_instance",
|
||||
entityId: instanceId,
|
||||
before: { status: instance.status },
|
||||
after: {
|
||||
status: "published",
|
||||
allowGaps,
|
||||
gaps: validation.gaps.length,
|
||||
},
|
||||
now,
|
||||
}),
|
||||
);
|
||||
|
||||
// E1/E7: enqueue the assignment mail and the rule-based reminders in the
|
||||
// same transaction. Idempotent on dedupe_key, and nothing is sent here —
|
||||
// the dispatcher (E2) drains it.
|
||||
await enqueuePublishNotifications(tx, instanceId, {
|
||||
now,
|
||||
appOrigin: opts.appOrigin,
|
||||
});
|
||||
await enqueueRemindersForInstance(tx, instanceId, {
|
||||
now,
|
||||
appOrigin: opts.appOrigin,
|
||||
});
|
||||
|
||||
return {
|
||||
published: true,
|
||||
alreadyPublished: false,
|
||||
gaps: validation.gaps,
|
||||
publishedAt: now,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export interface UnpublishResult {
|
||||
unpublished: boolean;
|
||||
/** True when the instance was already not published — the call changed nothing. */
|
||||
alreadyUnpublished: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unpublish one instance back to draft. Refused with `unpublish_blocked` while a
|
||||
* volunteer has confirmed (§5.5: unassign first); a non-published instance is an
|
||||
* idempotent no-op.
|
||||
*/
|
||||
export async function unpublishInstance(
|
||||
instanceId: string,
|
||||
opts: { actorId: string },
|
||||
): Promise<UnpublishResult> {
|
||||
return db.transaction(async (tx) => {
|
||||
const instanceRows = await tx
|
||||
.select({ id: serviceInstances.id, status: serviceInstances.status })
|
||||
.from(serviceInstances)
|
||||
.where(eq(serviceInstances.id, instanceId))
|
||||
.limit(1);
|
||||
if (instanceRows.length === 0) {
|
||||
throw new PublishError(
|
||||
"unknown_instance",
|
||||
`unknown service instance: ${instanceId}`,
|
||||
);
|
||||
}
|
||||
const instance = instanceRows[0];
|
||||
if (instance.status !== "published") {
|
||||
return { unpublished: false, alreadyUnpublished: true };
|
||||
}
|
||||
|
||||
const confirmed = await tx
|
||||
.select({ id: assignments.id })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.where(
|
||||
and(
|
||||
eq(slots.serviceInstanceId, instanceId),
|
||||
inArray(assignments.status, ["confirmed", "completed"]),
|
||||
),
|
||||
);
|
||||
|
||||
const validation = validateUnpublish({
|
||||
confirmedAssignments: confirmed.length,
|
||||
});
|
||||
if (!validation.ok) {
|
||||
throw new PublishError(
|
||||
"unpublish_blocked",
|
||||
validation.reason ?? "unpublish is not allowed",
|
||||
);
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(serviceInstances)
|
||||
.set({ status: "draft", publishedAt: null, publishedBy: null })
|
||||
.where(eq(serviceInstances.id, instanceId));
|
||||
|
||||
// A draft week must not keep mail queued from its published state.
|
||||
await cancelInstanceNotifications(instanceId, new Date(), tx);
|
||||
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: opts.actorId,
|
||||
action: "week.unpublished",
|
||||
entityType: "service_instance",
|
||||
entityId: instanceId,
|
||||
before: { status: instance.status },
|
||||
after: { status: "draft" },
|
||||
}),
|
||||
);
|
||||
|
||||
return { unpublished: true, alreadyUnpublished: false };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Ranked candidates for one open seat.
|
||||
*
|
||||
* The pure ranking module decides eligibility and order. This data layer
|
||||
* resolves the same facts auto-fill uses (requirements, competency, blackouts,
|
||||
* monthly load) plus two soft warnings the picker can show before the write:
|
||||
* the monthly cap and a back-to-back morning.
|
||||
*/
|
||||
|
||||
import { and, eq, gte, inArray, lt, ne, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
positionSkills,
|
||||
roles,
|
||||
serviceInstances,
|
||||
services,
|
||||
skills,
|
||||
slots,
|
||||
unavailability,
|
||||
userSkills,
|
||||
users,
|
||||
type SkillLevel,
|
||||
} from "@/db/schema";
|
||||
import { isMentorReady } from "@/domain/mentor";
|
||||
import {
|
||||
rankCandidates,
|
||||
type CandidateSkill,
|
||||
type RankedCandidate,
|
||||
type RankingCandidateInput,
|
||||
} from "@/domain/ranking";
|
||||
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
|
||||
|
||||
const ACTIVE_ASSIGNMENTS = ["proposed", "confirmed", "completed"] as const;
|
||||
|
||||
function isoDateUTC(date: Date | null): string {
|
||||
if (!date) return "";
|
||||
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export interface PickerCandidate extends RankedCandidate {
|
||||
monthlyServiceCount: number;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export interface RankedSlotResult {
|
||||
slot: {
|
||||
id: string;
|
||||
roleName: string;
|
||||
serviceName: string;
|
||||
occursOn: string;
|
||||
startsAt: Date;
|
||||
location: string | null;
|
||||
isTraineeSlot: boolean;
|
||||
};
|
||||
eligible: PickerCandidate[];
|
||||
excluded: PickerCandidate[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Null when the slot is unknown or is an event seat with no service instance.
|
||||
* Event seats are not part of the scheduling pipeline yet.
|
||||
*/
|
||||
export async function rankedCandidatesForSlot(
|
||||
slotId: string,
|
||||
): Promise<RankedSlotResult | null> {
|
||||
const [slot] = await db
|
||||
.select({
|
||||
id: slots.id,
|
||||
roleId: slots.roleId,
|
||||
roleName: roles.name,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
serviceInstanceId: slots.serviceInstanceId,
|
||||
serviceName: services.name,
|
||||
location: services.location,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
})
|
||||
.from(slots)
|
||||
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||
.where(eq(slots.id, slotId))
|
||||
.limit(1);
|
||||
|
||||
if (!slot || !slot.serviceInstanceId || !slot.occursOn || !slot.startsAt) {
|
||||
return null;
|
||||
}
|
||||
const occursOn = isoDateUTC(slot.occursOn);
|
||||
|
||||
const requirements = await db
|
||||
.select({
|
||||
skillId: positionSkills.skillId,
|
||||
requiredLevel: positionSkills.requiredLevel,
|
||||
isCore: positionSkills.isCore,
|
||||
weight: positionSkills.weight,
|
||||
skillName: skills.name,
|
||||
staleAfterDays: skills.staleAfterDays,
|
||||
mentorMinLevel: skills.mentorMinLevel,
|
||||
})
|
||||
.from(positionSkills)
|
||||
.innerJoin(skills, eq(skills.id, positionSkills.skillId))
|
||||
.where(eq(positionSkills.positionId, slot.roleId));
|
||||
|
||||
const userRows = await db
|
||||
.select()
|
||||
.from(users)
|
||||
.where(eq(users.status, "active"))
|
||||
.orderBy(users.lastName, users.firstName);
|
||||
const userIds = userRows.map((row) => row.id);
|
||||
|
||||
const competencyByUser = new Map<string, Map<string, CandidateSkill>>();
|
||||
if (userIds.length > 0) {
|
||||
const rows = await db
|
||||
.select({
|
||||
userId: userSkills.userId,
|
||||
skillId: userSkills.skillId,
|
||||
verifiedLevel: userSkills.verifiedLevel,
|
||||
selfComfort: userSkills.selfComfort,
|
||||
lastServedOn: userSkills.lastServedOn,
|
||||
mentorOptIn: userSkills.mentorOptIn,
|
||||
mentorApprovedAt: userSkills.mentorApprovedAt,
|
||||
staleAfterDays: skills.staleAfterDays,
|
||||
mentorMinLevel: skills.mentorMinLevel,
|
||||
})
|
||||
.from(userSkills)
|
||||
.innerJoin(skills, eq(skills.id, userSkills.skillId))
|
||||
.where(inArray(userSkills.userId, userIds));
|
||||
|
||||
for (const row of rows) {
|
||||
let bySkill = competencyByUser.get(row.userId);
|
||||
if (!bySkill) {
|
||||
bySkill = new Map();
|
||||
competencyByUser.set(row.userId, bySkill);
|
||||
}
|
||||
bySkill.set(row.skillId, {
|
||||
skillId: row.skillId,
|
||||
verifiedLevel: row.verifiedLevel,
|
||||
selfComfort: row.selfComfort,
|
||||
lastServedOn: row.lastServedOn ?? null,
|
||||
staleAfterDays: row.staleAfterDays ?? 120,
|
||||
mentorReady: isMentorReady({
|
||||
verifiedLevel: row.verifiedLevel,
|
||||
mentorMinLevel: row.mentorMinLevel,
|
||||
mentorOptIn: row.mentorOptIn,
|
||||
adminApproved: row.mentorApprovedAt != null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const blackoutsByUser = new Map<string, RankingCandidateInput["unavailability"]>();
|
||||
if (userIds.length > 0) {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(unavailability)
|
||||
.where(
|
||||
and(
|
||||
inArray(unavailability.userId, userIds),
|
||||
eq(unavailability.status, "active"),
|
||||
),
|
||||
);
|
||||
for (const row of rows) {
|
||||
const list = blackoutsByUser.get(row.userId) ?? [];
|
||||
list.push({
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
kind: row.kind,
|
||||
startsOn: row.startsOn,
|
||||
endsOn: row.endsOn,
|
||||
allDay: row.allDay,
|
||||
reason: row.reason,
|
||||
rrule: row.rrule,
|
||||
status: row.status,
|
||||
createdAt: row.createdAt ?? new Date(),
|
||||
createdBy: row.createdBy,
|
||||
});
|
||||
blackoutsByUser.set(row.userId, list);
|
||||
}
|
||||
}
|
||||
|
||||
const monthStart = new Date(`${occursOn}T00:00:00Z`);
|
||||
const monthEnd = new Date(`${occursOn}T00:00:00Z`);
|
||||
monthEnd.setUTCMonth(monthEnd.getUTCMonth() + 1);
|
||||
const monthlyRows = await db
|
||||
.select({ userId: assignments.userId, count: sql<number>`count(*)` })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.innerJoin(users, eq(users.id, assignments.userId))
|
||||
.where(
|
||||
and(
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENTS]),
|
||||
gte(serviceInstances.startsAt, monthStart),
|
||||
lt(serviceInstances.startsAt, monthEnd),
|
||||
),
|
||||
)
|
||||
.groupBy(assignments.userId);
|
||||
const monthlyCounts = new Map<string, number>();
|
||||
for (const row of monthlyRows) {
|
||||
monthlyCounts.set(row.userId, Number(row.count ?? 0));
|
||||
}
|
||||
|
||||
const assignedRows = await db
|
||||
.select({ userId: assignments.userId })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.where(
|
||||
and(
|
||||
eq(slots.serviceInstanceId, slot.serviceInstanceId),
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENTS]),
|
||||
),
|
||||
);
|
||||
const assignedInInstance = new Set(assignedRows.map((row) => row.userId));
|
||||
|
||||
const noon = localToUtc(occursOn, "12:00", CHURCH_TIMEZONE);
|
||||
const morningRows = await db
|
||||
.select({ userId: assignments.userId })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(
|
||||
and(
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENTS]),
|
||||
eq(serviceInstances.occursOn, slot.occursOn),
|
||||
ne(serviceInstances.id, slot.serviceInstanceId),
|
||||
lt(serviceInstances.startsAt, noon),
|
||||
),
|
||||
);
|
||||
const backToBack = new Set(morningRows.map((row) => row.userId));
|
||||
|
||||
const candidates: RankingCandidateInput[] = userRows.map((user) => ({
|
||||
userId: user.id,
|
||||
displayName:
|
||||
user.displayName ?? `${user.firstName} ${user.lastName}`.trim(),
|
||||
userStatus: user.status,
|
||||
adminApproved: user.status === "active" && !user.deactivatedAt,
|
||||
competency: [...(competencyByUser.get(user.id)?.values() ?? [])],
|
||||
unavailability: blackoutsByUser.get(user.id) ?? [],
|
||||
alreadyAssignedInInstance: assignedInInstance.has(user.id),
|
||||
}));
|
||||
|
||||
const ranked = rankCandidates({
|
||||
position: {
|
||||
name: slot.roleName,
|
||||
occursOn,
|
||||
skills: requirements.map((row) => ({
|
||||
skillId: row.skillId,
|
||||
name: row.skillName,
|
||||
requiredLevel: (row.requiredLevel ?? "none") as SkillLevel,
|
||||
isCore: row.isCore,
|
||||
weight: row.weight,
|
||||
})),
|
||||
},
|
||||
candidates,
|
||||
});
|
||||
|
||||
const coreSkills = requirements.filter((row) => row.isCore);
|
||||
const withWarnings = (candidate: RankedCandidate): PickerCandidate => {
|
||||
const warnings: string[] = [];
|
||||
const count = monthlyCounts.get(candidate.userId) ?? 0;
|
||||
if (count >= 3) {
|
||||
warnings.push(
|
||||
`Already holds ${count} service${count === 1 ? "" : "s"} this month; assigning would exceed the 3-service cap.`,
|
||||
);
|
||||
}
|
||||
if (backToBack.has(candidate.userId)) {
|
||||
warnings.push("Already serving the other service that morning.");
|
||||
}
|
||||
const comfort = coreSkills
|
||||
.map(
|
||||
(skill) =>
|
||||
competencyByUser.get(candidate.userId)?.get(skill.skillId)?.selfComfort,
|
||||
)
|
||||
.filter((value): value is number => value != null);
|
||||
if (comfort.length > 0 && Math.min(...comfort) < 50) {
|
||||
warnings.push("Self-rated comfort is below 50% on a core skill.");
|
||||
}
|
||||
if (candidate.needsRefresher) {
|
||||
warnings.push("Needs refresher — no recent service on a core skill.");
|
||||
}
|
||||
if (candidate.score < 50) {
|
||||
warnings.push("Readiness is below the warning threshold.");
|
||||
}
|
||||
return {
|
||||
...candidate,
|
||||
monthlyServiceCount: count,
|
||||
warnings,
|
||||
};
|
||||
};
|
||||
|
||||
return {
|
||||
slot: {
|
||||
id: slot.id,
|
||||
roleName: slot.roleName,
|
||||
serviceName: slot.serviceName,
|
||||
occursOn,
|
||||
startsAt: slot.startsAt,
|
||||
location: slot.location,
|
||||
isTraineeSlot: slot.isTraineeSlot,
|
||||
},
|
||||
eligible: ranked.eligible.map(withWarnings),
|
||||
excluded: ranked.excluded.map(withWarnings),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* 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<ReminderRuleRow[]> {
|
||||
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<ReminderRuleRow, "id">,
|
||||
): Promise<ReminderRuleRow> {
|
||||
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<Omit<ReminderRuleRow, "id">>,
|
||||
): Promise<ReminderRuleRow | null> {
|
||||
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<number> {
|
||||
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);
|
||||
// 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;
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
/**
|
||||
* Respond links — unit E4 (ARCHITECTURE §5.6).
|
||||
*
|
||||
* The data half of the no-login confirm/decline flow:
|
||||
* - `getRespondAssignment` resolves the page summary (never mutates),
|
||||
* - `applyRespond` consumes the token's `jti` exactly once, moves the
|
||||
* assignment to `confirmed` / `declined`, cancels pending mail on a decline,
|
||||
* and writes the audit row — all in one transaction.
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
auditLog,
|
||||
roles,
|
||||
serviceInstances,
|
||||
services,
|
||||
slots,
|
||||
usedTokens,
|
||||
users,
|
||||
type ConfirmedVia,
|
||||
} from "@/db/schema";
|
||||
import { auditRow } from "@/db/audit";
|
||||
import { cancelAssignmentNotifications } from "@/db/outbox";
|
||||
import type { RespondAction } from "@/lib/respond";
|
||||
import { formatInTimezone } from "@/lib/tz";
|
||||
|
||||
/** Only a live assignment can be confirmed or declined. */
|
||||
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
|
||||
|
||||
export type RespondFailureCode =
|
||||
| "unknown_assignment"
|
||||
| "wrong_volunteer"
|
||||
| "not_actionable"
|
||||
| "already_used";
|
||||
|
||||
export class RespondError extends Error {
|
||||
readonly code: RespondFailureCode;
|
||||
|
||||
constructor(code: RespondFailureCode, message: string) {
|
||||
super(message);
|
||||
this.name = "RespondError";
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RespondAssignmentView {
|
||||
assignmentId: string;
|
||||
volunteerName: string;
|
||||
roleName: string;
|
||||
serviceName: string;
|
||||
occursOnLabel: string;
|
||||
startTimeLabel: string;
|
||||
callTimeLabel: string | null;
|
||||
location: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** Read-only summary for the respond page. */
|
||||
export async function getRespondAssignment(
|
||||
assignmentId: string,
|
||||
): Promise<RespondAssignmentView | null> {
|
||||
const rows = await db
|
||||
.select({
|
||||
assignmentId: assignments.id,
|
||||
status: assignments.status,
|
||||
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(eq(assignments.id, assignmentId))
|
||||
.limit(1);
|
||||
|
||||
const row = rows[0];
|
||||
if (!row) return null;
|
||||
if (!row.startsAt) return null;
|
||||
|
||||
const timeZone = row.timeZone;
|
||||
return {
|
||||
assignmentId: row.assignmentId,
|
||||
volunteerName: row.displayName ?? row.firstName,
|
||||
roleName: row.roleName,
|
||||
serviceName: row.serviceName,
|
||||
occursOnLabel: formatInTimezone(row.startsAt, timeZone, {
|
||||
timeZone,
|
||||
weekday: "long",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
}),
|
||||
startTimeLabel: formatInTimezone(row.startsAt, timeZone, {
|
||||
timeZone,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}),
|
||||
callTimeLabel: row.callTime
|
||||
? formatInTimezone(row.callTime, timeZone, {
|
||||
timeZone,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})
|
||||
: null,
|
||||
location: row.location,
|
||||
status: row.status,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm or decline from an authenticated surface (the volunteer home).
|
||||
* This shares the same state transition as the email link, but has no token to
|
||||
* consume; ownership is checked by `assignment.userId` inside the transaction.
|
||||
*/
|
||||
export async function respondToAssignment(input: {
|
||||
assignmentId: string;
|
||||
userId: string;
|
||||
action: RespondAction;
|
||||
via?: ConfirmedVia;
|
||||
now?: Date;
|
||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||
const now = input.now ?? new Date();
|
||||
const nextStatus = input.action === "confirm" ? "confirmed" : "declined";
|
||||
const via = input.via ?? "app";
|
||||
|
||||
const result = await db.transaction(
|
||||
async (tx): Promise<{ status: "confirmed" | "declined" }> => {
|
||||
const rows = await tx
|
||||
.select({
|
||||
id: assignments.id,
|
||||
userId: assignments.userId,
|
||||
slotId: assignments.slotId,
|
||||
status: assignments.status,
|
||||
})
|
||||
.from(assignments)
|
||||
.where(eq(assignments.id, input.assignmentId))
|
||||
.limit(1);
|
||||
if (rows.length === 0) {
|
||||
throw new RespondError("unknown_assignment", "unknown assignment");
|
||||
}
|
||||
const assignment = rows[0];
|
||||
if (assignment.userId !== input.userId) {
|
||||
throw new RespondError(
|
||||
"wrong_volunteer",
|
||||
"this assignment is not yours",
|
||||
);
|
||||
}
|
||||
if (!ACTIONABLE_STATUSES.has(assignment.status)) {
|
||||
throw new RespondError(
|
||||
"not_actionable",
|
||||
`assignment is already ${assignment.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(assignments)
|
||||
.set({
|
||||
status: nextStatus,
|
||||
respondedAt: now,
|
||||
confirmedVia: via,
|
||||
declineReason: null,
|
||||
})
|
||||
.where(eq(assignments.id, assignment.id));
|
||||
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: nextStatus === "confirmed" ? "confirmed" : "open" })
|
||||
.where(eq(slots.id, assignment.slotId));
|
||||
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: input.userId,
|
||||
action:
|
||||
nextStatus === "confirmed"
|
||||
? "assignment.confirmed"
|
||||
: "assignment.declined",
|
||||
entityType: "assignment",
|
||||
entityId: assignment.id,
|
||||
before: { status: assignment.status },
|
||||
after: { status: nextStatus, via },
|
||||
now,
|
||||
}),
|
||||
);
|
||||
|
||||
return { status: nextStatus };
|
||||
},
|
||||
);
|
||||
|
||||
if (nextStatus === "declined") {
|
||||
await cancelAssignmentNotifications(input.assignmentId, now);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a verified respond token. Single use is enforced by the `used_tokens`
|
||||
* primary key inside the same transaction as the status change, so two
|
||||
* concurrent clicks cannot both succeed and no state slips without its record.
|
||||
*/
|
||||
export async function applyRespond(input: {
|
||||
assignmentId: string;
|
||||
userId: string;
|
||||
action: RespondAction;
|
||||
jti: string;
|
||||
now?: Date;
|
||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||
const now = input.now ?? new Date();
|
||||
const nextStatus = input.action === "confirm" ? "confirmed" : "declined";
|
||||
|
||||
const result = await db.transaction(
|
||||
async (tx): Promise<{ status: "confirmed" | "declined" }> => {
|
||||
const consumed = await tx
|
||||
.insert(usedTokens)
|
||||
.values({
|
||||
jti: input.jti,
|
||||
assignmentId: input.assignmentId,
|
||||
action: input.action,
|
||||
usedAt: now,
|
||||
})
|
||||
.onConflictDoNothing({ target: usedTokens.jti })
|
||||
.returning({ jti: usedTokens.jti });
|
||||
if (consumed.length === 0) {
|
||||
throw new RespondError("already_used", "this link has already been used");
|
||||
}
|
||||
|
||||
const rows = await tx
|
||||
.select({
|
||||
id: assignments.id,
|
||||
userId: assignments.userId,
|
||||
slotId: assignments.slotId,
|
||||
status: assignments.status,
|
||||
})
|
||||
.from(assignments)
|
||||
.where(eq(assignments.id, input.assignmentId))
|
||||
.limit(1);
|
||||
if (rows.length === 0) {
|
||||
throw new RespondError("unknown_assignment", "unknown assignment");
|
||||
}
|
||||
const assignment = rows[0];
|
||||
if (assignment.userId !== input.userId) {
|
||||
throw new RespondError(
|
||||
"wrong_volunteer",
|
||||
"this link is not for this volunteer",
|
||||
);
|
||||
}
|
||||
if (!ACTIONABLE_STATUSES.has(assignment.status)) {
|
||||
throw new RespondError(
|
||||
"not_actionable",
|
||||
`assignment is already ${assignment.status}`,
|
||||
);
|
||||
}
|
||||
|
||||
await tx
|
||||
.update(assignments)
|
||||
.set({
|
||||
status: nextStatus,
|
||||
respondedAt: now,
|
||||
confirmedVia: "email_link",
|
||||
declineReason: null,
|
||||
})
|
||||
.where(eq(assignments.id, assignment.id));
|
||||
|
||||
// Keep the denormalised seat status aligned with the assignment. A decline
|
||||
// frees the seat again so the grid/auto-fill sees it as open.
|
||||
await tx
|
||||
.update(slots)
|
||||
.set({ status: nextStatus === "confirmed" ? "confirmed" : "open" })
|
||||
.where(eq(slots.id, assignment.slotId));
|
||||
|
||||
await tx.insert(auditLog).values(
|
||||
auditRow({
|
||||
actorId: input.userId,
|
||||
action: nextStatus === "confirmed"
|
||||
? "assignment.confirmed"
|
||||
: "assignment.declined",
|
||||
entityType: "assignment",
|
||||
entityId: assignment.id,
|
||||
before: { status: assignment.status },
|
||||
after: { status: nextStatus, via: "email_link" },
|
||||
now,
|
||||
}),
|
||||
);
|
||||
|
||||
return { status: nextStatus };
|
||||
},
|
||||
);
|
||||
|
||||
// A decline must not leave "you're serving" mail queued (§6.1).
|
||||
if (nextStatus === "declined") {
|
||||
await cancelAssignmentNotifications(input.assignmentId, now);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
/**
|
||||
* Per-service run sheet and pre/post checklist.
|
||||
*
|
||||
* A run sheet has three parts: a header (speaker, message, stream/slides
|
||||
* links, notes), an ordered list of cues (the order of service with optional
|
||||
* time labels), and a checklist split into before/after the service.
|
||||
*
|
||||
* Defaults are created once, the first time an instance's run sheet is opened.
|
||||
* After that the rows belong to the instance, so a coordinator can delete every
|
||||
* item without the template reappearing.
|
||||
*/
|
||||
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
roles,
|
||||
runSheetItems,
|
||||
serviceChecklistItems,
|
||||
serviceInstances,
|
||||
serviceRunSheets,
|
||||
services,
|
||||
slots,
|
||||
users,
|
||||
type ChecklistPhase,
|
||||
} from "@/db/schema";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
const DEFAULT_ITEMS: { timeLabel: string | null; title: string; owner: string | null }[] = [
|
||||
{ timeLabel: null, title: "Pre-service countdown", owner: "Media" },
|
||||
{ timeLabel: null, title: "Welcome & announcements", owner: "Host" },
|
||||
{ timeLabel: null, title: "Worship set", owner: "Worship" },
|
||||
{ timeLabel: null, title: "Sermon", owner: "Speaker" },
|
||||
{ timeLabel: null, title: "Response & closing", owner: "Host" },
|
||||
];
|
||||
|
||||
const DEFAULT_PRE = [
|
||||
"Confirm call times with every volunteer",
|
||||
"Charge and check camera batteries",
|
||||
"Format and insert media cards",
|
||||
"Test microphones and audio levels",
|
||||
"Load slides, lower thirds and graphics",
|
||||
"Verify stream key and internet connection",
|
||||
"Post the stream link",
|
||||
];
|
||||
|
||||
const DEFAULT_POST = [
|
||||
"Stop the stream and recordings",
|
||||
"Copy and back up media cards",
|
||||
"Power down and connect batteries to charge",
|
||||
"Note anything that broke for the debrief",
|
||||
];
|
||||
|
||||
export interface RunSheetItemRow {
|
||||
id: string;
|
||||
sortOrder: number;
|
||||
timeLabel: string | null;
|
||||
title: string;
|
||||
owner: string | null;
|
||||
notes: string | null;
|
||||
}
|
||||
|
||||
export interface ChecklistRow {
|
||||
id: string;
|
||||
label: string;
|
||||
sortOrder: number;
|
||||
doneAt: Date | null;
|
||||
doneBy: string | null;
|
||||
}
|
||||
|
||||
export interface RunSheetData {
|
||||
instance: {
|
||||
id: string;
|
||||
serviceName: string;
|
||||
location: string | null;
|
||||
startsAt: Date;
|
||||
endsAt: Date | null;
|
||||
status: string;
|
||||
notes: string | null;
|
||||
};
|
||||
header: {
|
||||
speaker: string | null;
|
||||
sermonTitle: string | null;
|
||||
streamUrl: string | null;
|
||||
slidesUrl: string | null;
|
||||
notes: string | null;
|
||||
updatedAt: Date | null;
|
||||
};
|
||||
items: RunSheetItemRow[];
|
||||
checklist: { pre: ChecklistRow[]; post: ChecklistRow[] };
|
||||
team: {
|
||||
roleName: string;
|
||||
userName: string;
|
||||
callTime: Date | null;
|
||||
status: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
/** Create the sheet and its defaults exactly once per instance. */
|
||||
async function ensureRunSheet(instanceId: string): Promise<void> {
|
||||
const [existing] = await db
|
||||
.select({ id: serviceRunSheets.serviceInstanceId })
|
||||
.from(serviceRunSheets)
|
||||
.where(eq(serviceRunSheets.serviceInstanceId, instanceId))
|
||||
.limit(1);
|
||||
if (existing) return;
|
||||
|
||||
await db.transaction(async (tx) => {
|
||||
await tx
|
||||
.insert(serviceRunSheets)
|
||||
.values({ serviceInstanceId: instanceId })
|
||||
.onConflictDoNothing();
|
||||
|
||||
if (DEFAULT_ITEMS.length > 0) {
|
||||
await tx.insert(runSheetItems).values(
|
||||
DEFAULT_ITEMS.map((item, index) => ({
|
||||
id: uuidv7(),
|
||||
serviceInstanceId: instanceId,
|
||||
sortOrder: (index + 1) * 10,
|
||||
timeLabel: item.timeLabel,
|
||||
title: item.title,
|
||||
owner: item.owner,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
const checklist = [
|
||||
...DEFAULT_PRE.map((label, index) => ({
|
||||
phase: "pre" as const,
|
||||
label,
|
||||
sortOrder: (index + 1) * 10,
|
||||
})),
|
||||
...DEFAULT_POST.map((label, index) => ({
|
||||
phase: "post" as const,
|
||||
label,
|
||||
sortOrder: (index + 1) * 10,
|
||||
})),
|
||||
];
|
||||
await tx.insert(serviceChecklistItems).values(
|
||||
checklist.map((row) => ({
|
||||
id: uuidv7(),
|
||||
serviceInstanceId: instanceId,
|
||||
phase: row.phase,
|
||||
label: row.label,
|
||||
sortOrder: row.sortOrder,
|
||||
})),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function getRunSheet(
|
||||
instanceId: string,
|
||||
): Promise<RunSheetData | null> {
|
||||
const [instance] = await db
|
||||
.select({
|
||||
id: serviceInstances.id,
|
||||
serviceName: services.name,
|
||||
location: services.location,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
endsAt: serviceInstances.endsAt,
|
||||
status: serviceInstances.status,
|
||||
notes: serviceInstances.notes,
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||
.where(eq(serviceInstances.id, instanceId))
|
||||
.limit(1);
|
||||
|
||||
const startsAt = instance?.startsAt;
|
||||
if (!instance || !startsAt) return null;
|
||||
|
||||
try {
|
||||
await ensureRunSheet(instanceId);
|
||||
} catch (err) {
|
||||
// A concurrent first view can race the default inserts (the checklist has
|
||||
// a unique key). The sheet is still readable, so log and continue.
|
||||
console.warn("[runSheet] could not seed defaults", err);
|
||||
}
|
||||
|
||||
const [header, items, checklist, team] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(serviceRunSheets)
|
||||
.where(eq(serviceRunSheets.serviceInstanceId, instanceId))
|
||||
.limit(1),
|
||||
db
|
||||
.select()
|
||||
.from(runSheetItems)
|
||||
.where(eq(runSheetItems.serviceInstanceId, instanceId))
|
||||
.orderBy(asc(runSheetItems.sortOrder), asc(runSheetItems.title)),
|
||||
db
|
||||
.select()
|
||||
.from(serviceChecklistItems)
|
||||
.where(eq(serviceChecklistItems.serviceInstanceId, instanceId))
|
||||
.orderBy(
|
||||
asc(serviceChecklistItems.phase),
|
||||
asc(serviceChecklistItems.sortOrder),
|
||||
),
|
||||
db
|
||||
.select({
|
||||
roleName: roles.name,
|
||||
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
callTime: slots.callTime,
|
||||
status: assignments.status,
|
||||
})
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||
.innerJoin(users, eq(users.id, assignments.userId))
|
||||
.where(
|
||||
and(
|
||||
eq(slots.serviceInstanceId, instanceId),
|
||||
inArray(assignments.status, ["proposed", "confirmed"]),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(roles.sortOrder), asc(slots.slotIndex)),
|
||||
]);
|
||||
|
||||
const row = header[0];
|
||||
return {
|
||||
instance: { ...instance, startsAt },
|
||||
header: {
|
||||
speaker: row?.speaker ?? null,
|
||||
sermonTitle: row?.sermonTitle ?? null,
|
||||
streamUrl: row?.streamUrl ?? null,
|
||||
slidesUrl: row?.slidesUrl ?? null,
|
||||
notes: row?.notes ?? null,
|
||||
updatedAt: row?.updatedAt ?? null,
|
||||
},
|
||||
items,
|
||||
checklist: {
|
||||
pre: checklist.filter((item) => item.phase === "pre"),
|
||||
post: checklist.filter((item) => item.phase === "post"),
|
||||
},
|
||||
team,
|
||||
};
|
||||
}
|
||||
|
||||
export async function saveRunSheetHeader(
|
||||
instanceId: string,
|
||||
actorId: string,
|
||||
patch: {
|
||||
speaker?: string | null;
|
||||
sermonTitle?: string | null;
|
||||
streamUrl?: string | null;
|
||||
slidesUrl?: string | null;
|
||||
notes?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
await db
|
||||
.insert(serviceRunSheets)
|
||||
.values({
|
||||
serviceInstanceId: instanceId,
|
||||
speaker: patch.speaker ?? null,
|
||||
sermonTitle: patch.sermonTitle ?? null,
|
||||
streamUrl: patch.streamUrl ?? null,
|
||||
slidesUrl: patch.slidesUrl ?? null,
|
||||
notes: patch.notes ?? null,
|
||||
updatedBy: actorId,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: serviceRunSheets.serviceInstanceId,
|
||||
set: {
|
||||
...(patch.speaker !== undefined ? { speaker: patch.speaker } : {}),
|
||||
...(patch.sermonTitle !== undefined
|
||||
? { sermonTitle: patch.sermonTitle }
|
||||
: {}),
|
||||
...(patch.streamUrl !== undefined ? { streamUrl: patch.streamUrl } : {}),
|
||||
...(patch.slidesUrl !== undefined
|
||||
? { slidesUrl: patch.slidesUrl }
|
||||
: {}),
|
||||
...(patch.notes !== undefined ? { notes: patch.notes } : {}),
|
||||
updatedBy: actorId,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function addRunSheetItem(
|
||||
instanceId: string,
|
||||
input: {
|
||||
title: string;
|
||||
timeLabel?: string | null;
|
||||
owner?: string | null;
|
||||
notes?: string | null;
|
||||
},
|
||||
): Promise<RunSheetItemRow> {
|
||||
const [maxRow] = await db
|
||||
.select({ max: sql<number>`coalesce(max(${runSheetItems.sortOrder}), 0)` })
|
||||
.from(runSheetItems)
|
||||
.where(eq(runSheetItems.serviceInstanceId, instanceId));
|
||||
|
||||
const [row] = await db
|
||||
.insert(runSheetItems)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
serviceInstanceId: instanceId,
|
||||
sortOrder: Number(maxRow?.max ?? 0) + 10,
|
||||
timeLabel: input.timeLabel?.trim() || null,
|
||||
title: input.title.trim(),
|
||||
owner: input.owner?.trim() || null,
|
||||
notes: input.notes?.trim() || null,
|
||||
})
|
||||
.returning();
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateRunSheetItem(
|
||||
itemId: string,
|
||||
patch: {
|
||||
title?: string;
|
||||
timeLabel?: string | null;
|
||||
owner?: string | null;
|
||||
notes?: string | null;
|
||||
sortOrder?: number;
|
||||
},
|
||||
): Promise<RunSheetItemRow | null> {
|
||||
const set: Record<string, unknown> = {};
|
||||
if (patch.title !== undefined) set.title = patch.title.trim();
|
||||
if (patch.timeLabel !== undefined) set.timeLabel = patch.timeLabel?.trim() || null;
|
||||
if (patch.owner !== undefined) set.owner = patch.owner?.trim() || null;
|
||||
if (patch.notes !== undefined) set.notes = patch.notes?.trim() || null;
|
||||
if (patch.sortOrder !== undefined) set.sortOrder = patch.sortOrder;
|
||||
if (Object.keys(set).length === 0) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(runSheetItems)
|
||||
.where(eq(runSheetItems.id, itemId))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
const [row] = await db
|
||||
.update(runSheetItems)
|
||||
.set(set)
|
||||
.where(eq(runSheetItems.id, itemId))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function deleteRunSheetItem(itemId: string): Promise<boolean> {
|
||||
const rows = await db
|
||||
.delete(runSheetItems)
|
||||
.where(eq(runSheetItems.id, itemId))
|
||||
.returning({ id: runSheetItems.id });
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
export async function toggleChecklistItem(
|
||||
itemId: string,
|
||||
userId: string,
|
||||
done: boolean,
|
||||
): Promise<ChecklistRow | null> {
|
||||
const [row] = await db
|
||||
.update(serviceChecklistItems)
|
||||
.set({ doneAt: done ? new Date() : null, doneBy: done ? userId : null })
|
||||
.where(eq(serviceChecklistItems.id, itemId))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function addChecklistItem(
|
||||
instanceId: string,
|
||||
phase: ChecklistPhase,
|
||||
label: string,
|
||||
): Promise<ChecklistRow> {
|
||||
const [maxRow] = await db
|
||||
.select({
|
||||
max: sql<number>`coalesce(max(${serviceChecklistItems.sortOrder}), 0)`,
|
||||
})
|
||||
.from(serviceChecklistItems)
|
||||
.where(
|
||||
and(
|
||||
eq(serviceChecklistItems.serviceInstanceId, instanceId),
|
||||
eq(serviceChecklistItems.phase, phase),
|
||||
),
|
||||
);
|
||||
|
||||
const [row] = await db
|
||||
.insert(serviceChecklistItems)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
serviceInstanceId: instanceId,
|
||||
phase,
|
||||
sortOrder: Number(maxRow?.max ?? 0) + 10,
|
||||
label: label.trim(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deleteChecklistItem(itemId: string): Promise<boolean> {
|
||||
const rows = await db
|
||||
.delete(serviceChecklistItems)
|
||||
.where(eq(serviceChecklistItems.id, itemId))
|
||||
.returning({ id: serviceChecklistItems.id });
|
||||
return rows.length > 0;
|
||||
}
|
||||
+697
-3
@@ -18,7 +18,7 @@
|
||||
*/
|
||||
|
||||
import { relations, sql } from "drizzle-orm";
|
||||
import { pgTable, text, integer, boolean, timestamp, date, numeric, index, uniqueIndex, check, primaryKey } from "drizzle-orm/pg-core";
|
||||
import { pgTable, text, integer, bigint, boolean, timestamp, date, numeric, index, uniqueIndex, check, primaryKey } from "drizzle-orm/pg-core";
|
||||
|
||||
/* ------------------------------------------------------------------ enums */
|
||||
|
||||
@@ -50,6 +50,31 @@ export type UnavailabilityStatus = (typeof UNAVAILABILITY_STATUSES)[number];
|
||||
export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const;
|
||||
export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
|
||||
|
||||
// Added in E1 (outbox). ARCHITECTURE §6.1 / §4 outbox table.
|
||||
export const NOTIFICATION_CHANNELS = ["email", "sms"] as const;
|
||||
export type NotificationChannel = (typeof NOTIFICATION_CHANNELS)[number];
|
||||
|
||||
// Added in E7 (reminder rules). ARCHITECTURE §6.2.
|
||||
export const NOTIFICATION_RULE_EVENTS = [
|
||||
"assignment.created",
|
||||
"assignment.unconfirmed",
|
||||
"slot.unfilled",
|
||||
/** One-off coverage events (photo shoots: the lead time before `startsAt`). */
|
||||
"event.reminder",
|
||||
] as const;
|
||||
export type NotificationRuleEvent = (typeof NOTIFICATION_RULE_EVENTS)[number];
|
||||
|
||||
/** Outbox status ladder; the domain ladder is drift-guarded against this. */
|
||||
export const NOTIFICATION_STATUSES = [
|
||||
"queued",
|
||||
"sending",
|
||||
"sent",
|
||||
"failed",
|
||||
"suppressed",
|
||||
"cancelled",
|
||||
] as const;
|
||||
export type NotificationStatus = (typeof NOTIFICATION_STATUSES)[number];
|
||||
|
||||
/** TCPA consent source recorded on SMS opt-in (ARCHITECTURE §4.76). */
|
||||
export const SMS_CONSENT_SOURCES = ["web_signup", "paper_form", "admin_import"] as const;
|
||||
export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[number];
|
||||
@@ -86,6 +111,10 @@ export const users = pgTable(
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
email: text("email").unique().notNull(),
|
||||
/** Login handle. Existing accounts backfill to their email address. */
|
||||
username: text("username").notNull(),
|
||||
/** Null until the person sets a password after their first magic link. */
|
||||
passwordHash: text("password_hash"),
|
||||
phoneE164: text("phone_e164"),
|
||||
firstName: text("first_name").notNull(),
|
||||
lastName: text("last_name").notNull(),
|
||||
@@ -94,6 +123,8 @@ export const users = pgTable(
|
||||
status: text("status", { enum: USER_STATUSES }).notNull().default("pending_approval"),
|
||||
avatarUrl: text("avatar_url"),
|
||||
timezone: text("timezone").notNull().default(DEFAULT_TIMEZONE),
|
||||
/** Secret token for the personal read-only ICS calendar feed. */
|
||||
calendarFeedToken: text("calendar_feed_token"),
|
||||
emergencyContact: text("emergency_contact"),
|
||||
approvedBy: text("approved_by"),
|
||||
approvedAt: timestamp("approved_at", { mode: "date", withTimezone: true }),
|
||||
@@ -107,8 +138,11 @@ export const users = pgTable(
|
||||
deactivatedAt: timestamp("deactivated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
// Case-insensitive unique login key.
|
||||
index("users_email_lower_idx").on(sql`lower(${table.email})`),
|
||||
// Case-insensitive unique login key. Enforced in the database as well as
|
||||
// the app so a second insertion path cannot create a case-variant duplicate.
|
||||
uniqueIndex("users_email_lower_key").on(sql`lower(${table.email})`),
|
||||
uniqueIndex("users_username_lower_key").on(sql`lower(${table.username})`),
|
||||
uniqueIndex("users_calendar_feed_token_key").on(table.calendarFeedToken),
|
||||
index("users_status_idx").on(table.status),
|
||||
index("users_system_role_idx").on(table.systemRole),
|
||||
],
|
||||
@@ -596,6 +630,16 @@ export const userSkills = pgTable(
|
||||
verifiedAt: timestamp("verified_at", { mode: "date", withTimezone: true }),
|
||||
/** Volunteer agrees to teach this skill (C5 mentor designation). */
|
||||
mentorOptIn: boolean("mentor_opt_in").notNull().default(false),
|
||||
/**
|
||||
* Admin sign-off on the mentor designation (C5). `isMentorReady` requires
|
||||
* it alongside the verified level and the volunteer's opt-in; the column
|
||||
* exists so the flag is persisted rather than inferred from the level.
|
||||
*/
|
||||
mentorApprovedAt: timestamp("mentor_approved_at", {
|
||||
mode: "date",
|
||||
withTimezone: true,
|
||||
}),
|
||||
mentorApprovedBy: text("mentor_approved_by"),
|
||||
/** Maintained by the system on assignment completion — never entered by hand. */
|
||||
lastServedOn: date("last_served_on"),
|
||||
notes: text("notes"),
|
||||
@@ -680,6 +724,638 @@ export const growthGoals = pgTable(
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------- notifications outbox (E1) */
|
||||
|
||||
/**
|
||||
* The notification outbox — the queue is a table (ARCHITECTURE §4 / §6.1).
|
||||
*
|
||||
* Enqueue is idempotent on `dedupe_key` (`template:ref:channel`), so publishing
|
||||
* twice or re-running a rule cannot double-send. `payload_json` is fully merged
|
||||
* at enqueue time (subject/html/text/links), making every row auditable and
|
||||
* replayable. The dispatcher (E2) drains it; the admin log reads from it.
|
||||
*/
|
||||
export const notifications = pgTable(
|
||||
"notifications",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
channel: text("channel", { enum: NOTIFICATION_CHANNELS })
|
||||
.notNull()
|
||||
.default("email"),
|
||||
templateKey: text("template_key").notNull(),
|
||||
ruleKey: text("rule_key"),
|
||||
assignmentId: text("assignment_id").references(() => assignments.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
slotId: text("slot_id").references(() => slots.id, { onDelete: "set null" }),
|
||||
/** Resolved destination at enqueue time (email address; E5 adds phone). */
|
||||
toAddress: text("to_address").notNull(),
|
||||
/** Fully merged message payload — exactly what will be sent. */
|
||||
payloadJson: text("payload_json").notNull().default(""),
|
||||
/** Unique per (template, reference, channel): the dedupe guarantee. */
|
||||
dedupeKey: text("dedupe_key").unique().notNull(),
|
||||
scheduledFor: timestamp("scheduled_for", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
status: text("status", { enum: NOTIFICATION_STATUSES })
|
||||
.notNull()
|
||||
.default("queued"),
|
||||
attempts: integer("attempts").notNull().default(0),
|
||||
providerId: text("provider_id"),
|
||||
providerStatus: text("provider_status"),
|
||||
error: text("error"),
|
||||
sentAt: timestamp("sent_at", { mode: "date", withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
// The dispatcher's only hot query: due rows in status order.
|
||||
index("notifications_status_scheduled_idx").on(table.status, table.scheduledFor),
|
||||
index("notifications_user_idx").on(table.userId),
|
||||
index("notifications_assignment_idx").on(table.assignmentId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Single-use record for magic-link sign-in tokens. The signed token carries a
|
||||
* `jti`; `/api/dev/complete` inserts it here before establishing a session, so
|
||||
* a replayed link is rejected. Rows are independent of assignments and are
|
||||
* safe to prune after the token expiry window (10 minutes).
|
||||
*/
|
||||
export const usedMagicTokens = pgTable("used_magic_tokens", {
|
||||
jti: text("jti").primaryKey(),
|
||||
email: text("email").notNull(),
|
||||
usedAt: timestamp("used_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Single-use record for respond links (ARCHITECTURE §5.6). The signed token
|
||||
* carries a `jti`; the first POST consumes it here, and a second POST with the
|
||||
* same token is rejected. Rows cascade with their assignment (history cleanup).
|
||||
*/
|
||||
export const usedTokens = pgTable("used_tokens", {
|
||||
jti: text("jti").primaryKey(),
|
||||
assignmentId: text("assignment_id")
|
||||
.notNull()
|
||||
.references(() => assignments.id, { onDelete: "cascade" }),
|
||||
action: text("action").notNull(),
|
||||
usedAt: timestamp("used_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
});
|
||||
|
||||
/* ------------------------------------------- notification rules (E7) */
|
||||
|
||||
/**
|
||||
* Offset-based reminder rules (ARCHITECTURE §6.2). "Friday before" is
|
||||
* `offset_days = -2` at 18:00 local — a row, not code, so the church can move
|
||||
* it to Thursday 20:00 without a deploy. `channel_set` is `email`, `sms` or
|
||||
* `email+sms`; SMS rows are suppressed until E5.
|
||||
*/
|
||||
export const notificationRules = pgTable(
|
||||
"notification_rules",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
key: text("key").unique().notNull(),
|
||||
event: text("event", { enum: NOTIFICATION_RULE_EVENTS })
|
||||
.notNull()
|
||||
.default("assignment.created"),
|
||||
/** Days from the instance start; -2 is the Friday-before-Sunday reminder. */
|
||||
offsetDays: integer("offset_days").notNull(),
|
||||
sendAtLocalTime: text("send_at_local_time").notNull().default("09:00"),
|
||||
channelSet: text("channel_set").notNull().default("email"),
|
||||
/** null = every service. */
|
||||
appliesToServiceId: text("applies_to_service_id").references(
|
||||
() => services.id,
|
||||
{ onDelete: "set null" },
|
||||
),
|
||||
active: boolean("active").notNull().default(true),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
index("notification_rules_active_idx").on(table.active),
|
||||
check(
|
||||
"chk_notification_rules_channel",
|
||||
sql`${table.channelSet} IN ('email','sms','email+sms')`,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------- app settings (runtime admin) */
|
||||
|
||||
/**
|
||||
* Small key/value store for settings an admin edits at runtime — currently the
|
||||
* email sender identity and where admin test/failure mail goes. Kept out of
|
||||
* the seed reset: these are deployment choices, not demo data.
|
||||
*/
|
||||
export const appSettings = pgTable("app_settings", {
|
||||
key: text("key").primaryKey(),
|
||||
value: text("value").notNull(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
});
|
||||
|
||||
/* --------------------------------------------------- training (lessons) */
|
||||
|
||||
/**
|
||||
* Training content authored in the app (F2). Lessons are ordered, can be
|
||||
* published/unpublished, and carry plain-text/Markdown-ish bodies. Attachments
|
||||
* live in `training_resources` (bytes on disk, metadata here).
|
||||
*/
|
||||
export const trainingLessons = pgTable(
|
||||
"training_lessons",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
summary: text("summary"),
|
||||
body: text("body").notNull().default(""),
|
||||
published: boolean("published").notNull().default(false),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [index("training_lessons_published_idx").on(table.published)],
|
||||
);
|
||||
|
||||
/** Attachment metadata; the file itself is stored under `UPLOAD_DIR`. */
|
||||
export const trainingResources = pgTable(
|
||||
"training_resources",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
lessonId: text("lesson_id")
|
||||
.notNull()
|
||||
.references(() => trainingLessons.id, { onDelete: "cascade" }),
|
||||
filename: text("filename").notNull(),
|
||||
mimeType: text("mime_type").notNull(),
|
||||
sizeBytes: integer("size_bytes").notNull(),
|
||||
/** Random on-disk name; never derived from user input. */
|
||||
storedName: text("stored_name").notNull(),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [index("training_resources_lesson_idx").on(table.lessonId)],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------ events & photo folders */
|
||||
|
||||
/** How an assigned person takes part in an event. */
|
||||
export const EVENT_PHOTOGRAPHER_ROLES = [
|
||||
"photographer",
|
||||
"second_shooter",
|
||||
"editor",
|
||||
] as const;
|
||||
export type EventPhotographerRole =
|
||||
(typeof EVENT_PHOTOGRAPHER_ROLES)[number];
|
||||
|
||||
/** What a folder is for; `mixed` is the honest default for ad-hoc uploads. */
|
||||
export const EVENT_FOLDER_KINDS = ["originals", "edited", "mixed"] as const;
|
||||
export type EventFolderKind = (typeof EVENT_FOLDER_KINDS)[number];
|
||||
|
||||
/** `raw` = camera original; `image` = browser-renderable JPEG/PNG/WebP/etc. */
|
||||
export const EVENT_PHOTO_KINDS = ["raw", "image"] as const;
|
||||
export type EventPhotoKind = (typeof EVENT_PHOTO_KINDS)[number];
|
||||
|
||||
/**
|
||||
* A one-off coverage event (wedding, portrait session, outreach night). This is
|
||||
* deliberately a lighter table than the full J-phase event model: it exists so
|
||||
* photographers can be assigned and share deliverables, and does not yet create
|
||||
* scheduling slots or go through the publish/confirm pipeline.
|
||||
*/
|
||||
export const events = pgTable(
|
||||
"events",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
/** Free-form: wedding, portrait, service, outreach… */
|
||||
eventType: text("event_type").notNull().default("photoshoot"),
|
||||
startsAt: timestamp("starts_at", { mode: "date", withTimezone: true }).notNull(),
|
||||
endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }),
|
||||
location: text("location"),
|
||||
/** Shot brief / what to capture, shown on the event page. */
|
||||
description: text("description"),
|
||||
createdBy: text("created_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
index("events_starts_at_idx").on(table.startsAt),
|
||||
index("events_created_by_idx").on(table.createdBy),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Who may see and contribute to an event. The UNIQUE (event, user) key means a
|
||||
* person holds one role per event; re-assigning updates the role rather than
|
||||
* creating a duplicate.
|
||||
*/
|
||||
export const eventPhotographers = pgTable(
|
||||
"event_photographers",
|
||||
{
|
||||
eventId: text("event_id")
|
||||
.notNull()
|
||||
.references(() => events.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "cascade" }),
|
||||
role: text("role", { enum: EVENT_PHOTOGRAPHER_ROLES })
|
||||
.notNull()
|
||||
.default("photographer"),
|
||||
assignedBy: text("assigned_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
assignedAt: timestamp("assigned_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({ name: "event_photographers_pk", columns: [table.eventId, table.userId] }),
|
||||
index("event_photographers_user_idx").on(table.userId),
|
||||
],
|
||||
);
|
||||
|
||||
/** A named folder inside an event: "Originals", "Edited selects", … */
|
||||
export const eventFolders = pgTable(
|
||||
"event_folders",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
eventId: text("event_id")
|
||||
.notNull()
|
||||
.references(() => events.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
kind: text("kind", { enum: EVENT_FOLDER_KINDS })
|
||||
.notNull()
|
||||
.default("originals"),
|
||||
createdBy: text("created_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("event_folders_event_name_idx").on(table.eventId, table.name),
|
||||
index("event_folders_event_idx").on(table.eventId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Photo metadata. Bytes live under `UPLOAD_DIR/events/<eventId>/`; only this
|
||||
* row is in Postgres. `checksum` is the SHA-256 of the bytes and is unique per
|
||||
* folder, so re-uploading the same frame is a no-op instead of a duplicate.
|
||||
* `storedName` is a generated relative path, never user input.
|
||||
*/
|
||||
export const eventPhotos = pgTable(
|
||||
"event_photos",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
folderId: text("folder_id")
|
||||
.notNull()
|
||||
.references(() => eventFolders.id, { onDelete: "cascade" }),
|
||||
uploaderId: text("uploader_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "restrict" }),
|
||||
filename: text("filename").notNull(),
|
||||
mimeType: text("mime_type").notNull(),
|
||||
sizeBytes: integer("size_bytes").notNull(),
|
||||
storedName: text("stored_name").unique().notNull(),
|
||||
checksumSha256: text("checksum_sha256").notNull(),
|
||||
kind: text("kind", { enum: EVENT_PHOTO_KINDS }).notNull(),
|
||||
/** Last saved adjustment recipe (JSON); the original is never overwritten. */
|
||||
editJson: text("edit_json"),
|
||||
/** Generated full-resolution JPEG. Null until the first edit is saved. */
|
||||
editedStoredName: text("edited_stored_name"),
|
||||
editedSizeBytes: integer("edited_size_bytes"),
|
||||
editedAt: timestamp("edited_at", { mode: "date", withTimezone: true }),
|
||||
editedBy: text("edited_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("event_photos_folder_checksum_idx").on(
|
||||
table.folderId,
|
||||
table.checksumSha256,
|
||||
),
|
||||
index("event_photos_folder_idx").on(table.folderId, table.createdAt),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------------- event videos */
|
||||
|
||||
/** Processing state for an uploaded event video. */
|
||||
export const EVENT_VIDEO_STATUSES = [
|
||||
"processing",
|
||||
"ready",
|
||||
"failed",
|
||||
] as const;
|
||||
export type EventVideoStatus = (typeof EVENT_VIDEO_STATUSES)[number];
|
||||
|
||||
/** `team` is private; `unlisted` is link-only; `public` can be discovered. */
|
||||
export const EVENT_VIDEO_VISIBILITIES = [
|
||||
"team",
|
||||
"unlisted",
|
||||
"public",
|
||||
] as const;
|
||||
export type EventVideoVisibility =
|
||||
(typeof EVENT_VIDEO_VISIBILITIES)[number];
|
||||
|
||||
/**
|
||||
* Event video metadata. The camera original is written to the configured NFS
|
||||
* archive; the browser derivative and poster live under `UPLOAD_DIR/videos`.
|
||||
* `trim_start_ms` / `trim_end_ms` are a non-destructive recipe applied when
|
||||
* the web MP4 is rendered, so the original is never changed.
|
||||
*/
|
||||
export const eventVideos = pgTable(
|
||||
"event_videos",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
eventId: text("event_id")
|
||||
.notNull()
|
||||
.references(() => events.id, { onDelete: "cascade" }),
|
||||
uploaderId: text("uploader_id")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "restrict" }),
|
||||
title: text("title").notNull(),
|
||||
description: text("description"),
|
||||
filename: text("filename").notNull(),
|
||||
mimeType: text("mime_type").notNull(),
|
||||
/** bigint: a 4 GB camera video does not fit a signed 32-bit integer. */
|
||||
sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
|
||||
checksumSha256: text("checksum_sha256").notNull(),
|
||||
/** Path relative to `<archivePath>/<archiveFolder>`, e.g. videos/…/original.mp4. */
|
||||
originalStoredName: text("original_stored_name").unique().notNull(),
|
||||
/** The archive folder in use at upload time, so a later settings change cannot orphan it. */
|
||||
archiveFolder: text("archive_folder").notNull(),
|
||||
durationMs: integer("duration_ms"),
|
||||
width: integer("width"),
|
||||
height: integer("height"),
|
||||
trimStartMs: integer("trim_start_ms").notNull().default(0),
|
||||
trimEndMs: integer("trim_end_ms"),
|
||||
webStoredName: text("web_stored_name"),
|
||||
posterStoredName: text("poster_stored_name"),
|
||||
status: text("status", { enum: EVENT_VIDEO_STATUSES })
|
||||
.notNull()
|
||||
.default("processing"),
|
||||
visibility: text("visibility", { enum: EVENT_VIDEO_VISIBILITIES })
|
||||
.notNull()
|
||||
.default("team"),
|
||||
errorMessage: text("error_message"),
|
||||
processedAt: timestamp("processed_at", { mode: "date", withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("event_videos_event_checksum_idx").on(
|
||||
table.eventId,
|
||||
table.checksumSha256,
|
||||
),
|
||||
index("event_videos_event_created_idx").on(
|
||||
table.eventId,
|
||||
table.createdAt,
|
||||
),
|
||||
index("event_videos_status_idx").on(table.status),
|
||||
],
|
||||
);
|
||||
|
||||
/* ---------------------------------------------------- announcements */
|
||||
|
||||
/**
|
||||
* Team announcements authored by admins/coordinators (`content.author`).
|
||||
* Plain text for now (the rich-text editor is F1); drafts are hidden from
|
||||
* volunteers and can be published/unpublished at any time.
|
||||
*/
|
||||
export const announcements = pgTable(
|
||||
"announcements",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
body: text("body").notNull().default(""),
|
||||
published: boolean("published").notNull().default(false),
|
||||
createdBy: text("created_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
},
|
||||
(table) => [
|
||||
index("announcements_published_created_idx").on(
|
||||
table.published,
|
||||
table.createdAt,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------ coverage (swap) requests */
|
||||
|
||||
export const COVERAGE_REQUEST_STATUSES = [
|
||||
"pending",
|
||||
"approved",
|
||||
"declined",
|
||||
"cancelled",
|
||||
] as const;
|
||||
export type CoverageRequestStatus =
|
||||
(typeof COVERAGE_REQUEST_STATUSES)[number];
|
||||
|
||||
/**
|
||||
* A volunteer asking for their seat to be released, with an optional
|
||||
* replacement chosen by a coordinator. The assignment stays live until the
|
||||
* request is approved, so a pending request never silently opens a hole.
|
||||
*
|
||||
* At most one pending request per assignment; resolved rows remain as history.
|
||||
*/
|
||||
export const coverageRequests = pgTable(
|
||||
"coverage_requests",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
assignmentId: text("assignment_id")
|
||||
.notNull()
|
||||
.references(() => assignments.id, { onDelete: "cascade" }),
|
||||
requestedBy: text("requested_by")
|
||||
.notNull()
|
||||
.references(() => users.id, { onDelete: "restrict" }),
|
||||
reason: text("reason"),
|
||||
status: text("status", { enum: COVERAGE_REQUEST_STATUSES })
|
||||
.notNull()
|
||||
.default("pending"),
|
||||
replacementUserId: text("replacement_user_id").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
resolvedBy: text("resolved_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
resolvedAt: timestamp("resolved_at", { mode: "date", withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("coverage_requests_pending_assignment_idx")
|
||||
.on(table.assignmentId)
|
||||
.where(sql`${table.status} = 'pending'`),
|
||||
index("coverage_requests_status_idx").on(table.status, table.createdAt),
|
||||
index("coverage_requests_requester_idx").on(table.requestedBy),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------------------ run sheet */
|
||||
|
||||
/**
|
||||
* One run sheet per service instance (PK = instance). Holds the service-wide
|
||||
* header: speaker, message title, stream/slides links, and free notes. Items
|
||||
* live in `run_sheet_items`; checklists in `service_checklist_items`.
|
||||
*/
|
||||
export const serviceRunSheets = pgTable("service_run_sheets", {
|
||||
serviceInstanceId: text("service_instance_id")
|
||||
.primaryKey()
|
||||
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
||||
speaker: text("speaker"),
|
||||
sermonTitle: text("sermon_title"),
|
||||
streamUrl: text("stream_url"),
|
||||
slidesUrl: text("slides_url"),
|
||||
notes: text("notes"),
|
||||
updatedBy: text("updated_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
||||
});
|
||||
|
||||
/**
|
||||
* An ordered cue in the service. `timeLabel` is free text ("10:58") so a
|
||||
* coordinator can write the booth sheet exactly as the service runs.
|
||||
*/
|
||||
export const runSheetItems = pgTable(
|
||||
"run_sheet_items",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
serviceInstanceId: text("service_instance_id")
|
||||
.notNull()
|
||||
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
timeLabel: text("time_label"),
|
||||
title: text("title").notNull(),
|
||||
owner: text("owner"),
|
||||
notes: text("notes"),
|
||||
},
|
||||
(table) => [
|
||||
index("run_sheet_items_instance_idx").on(
|
||||
table.serviceInstanceId,
|
||||
table.sortOrder,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
/** Checklist phase: before the service starts, or after it ends. */
|
||||
export const CHECKLIST_PHASES = ["pre", "post"] as const;
|
||||
export type ChecklistPhase = (typeof CHECKLIST_PHASES)[number];
|
||||
|
||||
/**
|
||||
* Per-instance checklist. Rows are copied from a default template the first
|
||||
* time the run sheet is opened, then owned by the instance so a coordinator can
|
||||
* add or remove steps for a special service without editing a global template.
|
||||
*/
|
||||
export const serviceChecklistItems = pgTable(
|
||||
"service_checklist_items",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
serviceInstanceId: text("service_instance_id")
|
||||
.notNull()
|
||||
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
||||
phase: text("phase", { enum: CHECKLIST_PHASES }).notNull().default("pre"),
|
||||
sortOrder: integer("sort_order").notNull().default(0),
|
||||
label: text("label").notNull(),
|
||||
doneAt: timestamp("done_at", { mode: "date", withTimezone: true }),
|
||||
doneBy: text("done_by").references(() => users.id, { onDelete: "set null" }),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("service_checklist_instance_label_idx").on(
|
||||
table.serviceInstanceId,
|
||||
table.phase,
|
||||
table.label,
|
||||
),
|
||||
index("service_checklist_instance_idx").on(
|
||||
table.serviceInstanceId,
|
||||
table.phase,
|
||||
table.sortOrder,
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------ coverage intake form */
|
||||
|
||||
export const COVERAGE_INTAKE_STATUSES = [
|
||||
"new",
|
||||
"scheduled",
|
||||
"declined",
|
||||
] as const;
|
||||
export type CoverageIntakeStatus =
|
||||
(typeof COVERAGE_INTAKE_STATUSES)[number];
|
||||
|
||||
/**
|
||||
* A media-coverage request from a ministry leader or member of the church.
|
||||
* Submitted from the public `/request-coverage` form, reviewed by a
|
||||
* coordinator, and converted into an event (which already carries the
|
||||
* photographer assignment and file-sharing workflow).
|
||||
*/
|
||||
export const coverageIntakes = pgTable(
|
||||
"coverage_intakes",
|
||||
{
|
||||
id: text("id").primaryKey(),
|
||||
requesterName: text("requester_name").notNull(),
|
||||
requesterEmail: text("requester_email").notNull(),
|
||||
requesterPhone: text("requester_phone"),
|
||||
ministry: text("ministry"),
|
||||
title: text("title").notNull(),
|
||||
eventType: text("event_type").notNull().default("coverage"),
|
||||
startsAt: timestamp("starts_at", { mode: "date", withTimezone: true })
|
||||
.notNull(),
|
||||
endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }),
|
||||
location: text("location"),
|
||||
description: text("description"),
|
||||
status: text("status", { enum: COVERAGE_INTAKE_STATUSES })
|
||||
.notNull()
|
||||
.default("new"),
|
||||
createdEventId: text("created_event_id").references(() => events.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
reviewedBy: text("reviewed_by").references(() => users.id, {
|
||||
onDelete: "set null",
|
||||
}),
|
||||
reviewedAt: timestamp("reviewed_at", { mode: "date", withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
index("coverage_intakes_status_idx").on(table.status, table.createdAt),
|
||||
index("coverage_intakes_starts_idx").on(table.startsAt),
|
||||
],
|
||||
);
|
||||
|
||||
/* ------------------------------------------------------------- relations */
|
||||
|
||||
/**
|
||||
@@ -771,6 +1447,24 @@ export const schema = {
|
||||
userSkills,
|
||||
skillAssessments,
|
||||
growthGoals,
|
||||
notifications,
|
||||
usedTokens,
|
||||
usedMagicTokens,
|
||||
notificationRules,
|
||||
appSettings,
|
||||
trainingLessons,
|
||||
trainingResources,
|
||||
events,
|
||||
eventPhotographers,
|
||||
eventFolders,
|
||||
eventPhotos,
|
||||
eventVideos,
|
||||
announcements,
|
||||
coverageRequests,
|
||||
serviceRunSheets,
|
||||
runSheetItems,
|
||||
serviceChecklistItems,
|
||||
coverageIntakes,
|
||||
};
|
||||
|
||||
export type Schema = typeof schema;
|
||||
|
||||
+170
-10
@@ -19,6 +19,12 @@ import {
|
||||
serviceInstances,
|
||||
slots,
|
||||
assignments,
|
||||
skillCategories,
|
||||
skills,
|
||||
positionSkills,
|
||||
userSkills,
|
||||
notificationRules,
|
||||
trainingLessons,
|
||||
} from "./schema";
|
||||
import { uuidv7 } from "../lib/uuid";
|
||||
import { localToUtc, nextSundaysInTz } from "../lib/tz";
|
||||
@@ -35,6 +41,21 @@ const RESET_TABLES = [
|
||||
"slots",
|
||||
"assignments",
|
||||
"notification_preferences",
|
||||
"skill_categories",
|
||||
"skills",
|
||||
"position_skills",
|
||||
"user_skills",
|
||||
"notifications",
|
||||
"used_tokens",
|
||||
"notification_rules",
|
||||
"training_resources",
|
||||
"training_lessons",
|
||||
"event_videos",
|
||||
"event_photos",
|
||||
"event_folders",
|
||||
"event_photographers",
|
||||
"events",
|
||||
"announcements",
|
||||
] as const;
|
||||
|
||||
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
||||
@@ -83,14 +104,17 @@ export async function seed() {
|
||||
}
|
||||
console.log(`services: ${serviceRows.length} seeded`);
|
||||
|
||||
/* 3. Instances — materialized occurrences (next 2 Sundays × each service) */
|
||||
/* 3. Instances — materialized occurrences (next 2 Sundays × each service).
|
||||
* The first Sunday is published so the grid opens on real data; the second
|
||||
* stays draft so the D10 publish flow has a week to publish. */
|
||||
// Re-fetch canonical rows: ON CONFLICT DO NOTHING keeps the first-run ids, so
|
||||
// downstream references must use DB ids, not the freshly-generated ones.
|
||||
const serviceRows2 = await db.select().from(services).orderBy(services.name);
|
||||
const sundays = nextSundaysInTz(2, CHURCH_TZ);
|
||||
let instanceCount = 0;
|
||||
for (const service of serviceRows2) {
|
||||
for (const dateStr of sundays) {
|
||||
for (const [weekIndex, dateStr] of sundays.entries()) {
|
||||
const isFirstWeek = weekIndex === 0;
|
||||
const startsAt = localToUtc(dateStr, service.startTimeLocal!, service.timezone!);
|
||||
const endsAt = new Date(startsAt.getTime() + service.durationMinutes! * 60000);
|
||||
await db.insert(serviceInstances).values({
|
||||
@@ -101,8 +125,8 @@ export async function seed() {
|
||||
endsAt,
|
||||
isSpecial: false,
|
||||
titleOverride: null,
|
||||
status: "published",
|
||||
publishedAt: new Date(),
|
||||
status: isFirstWeek ? "published" : "draft",
|
||||
publishedAt: isFirstWeek ? new Date() : null,
|
||||
publishedBy: null,
|
||||
notes: null,
|
||||
}).onConflictDoNothing({ target: [serviceInstances.serviceId, serviceInstances.startsAt] });
|
||||
@@ -150,12 +174,12 @@ export async function seed() {
|
||||
|
||||
/* 5. Users — admin, coordinator, volunteers */
|
||||
const userRows: (typeof users.$inferInsert)[] = [
|
||||
{ id: uuidv7(), email: "admin@glenloch.local", phoneE164: null, firstName: "Admin", lastName: "User", displayName: "Admin User", systemRole: "admin", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed admin", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "coordinator@glenloch.local", phoneE164: null, firstName: "Cole", lastName: "Coordinator", displayName: "Cole Coordinator", systemRole: "coordinator", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed coordinator", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "jordan@glenloch.local", phoneE164: "+15551230001", firstName: "Jordan", lastName: "Reyes", displayName: "Jordan Reyes", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: "M. Reyes +15551239999", approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "avery@glenloch.local", phoneE164: "+15551230002", firstName: "Avery", lastName: "Kim", displayName: "Avery Kim", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "sam@glenloch.local", phoneE164: "+15551230003", firstName: "Sam", lastName: "Okafor", displayName: "Sam Okafor", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "riley@glenloch.local", phoneE164: null, firstName: "Riley", lastName: "Parks", displayName: "Riley Parks", systemRole: "trainee", status: "pending_approval", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: null, lastServedAt: null, reliabilityScore: null, notes: "trainee — shadowing", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "admin@glenloch.local", username: "admin@glenloch.local", phoneE164: null, firstName: "Admin", lastName: "User", displayName: "Admin User", systemRole: "admin", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed admin", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "coordinator@glenloch.local", username: "coordinator@glenloch.local", phoneE164: null, firstName: "Cole", lastName: "Coordinator", displayName: "Cole Coordinator", systemRole: "coordinator", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed coordinator", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "jordan@glenloch.local", username: "jordan@glenloch.local", phoneE164: "+15551230001", firstName: "Jordan", lastName: "Reyes", displayName: "Jordan Reyes", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: "M. Reyes +15551239999", approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "avery@glenloch.local", username: "avery@glenloch.local", phoneE164: "+15551230002", firstName: "Avery", lastName: "Kim", displayName: "Avery Kim", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "sam@glenloch.local", username: "sam@glenloch.local", phoneE164: "+15551230003", firstName: "Sam", lastName: "Okafor", displayName: "Sam Okafor", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "riley@glenloch.local", username: "riley@glenloch.local", phoneE164: null, firstName: "Riley", lastName: "Parks", displayName: "Riley Parks", systemRole: "trainee", status: "pending_approval", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: null, lastServedAt: null, reliabilityScore: null, notes: "trainee — shadowing", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
];
|
||||
for (const u of userRows) {
|
||||
await db.insert(users).values(u).onConflictDoNothing({ target: users.email });
|
||||
@@ -221,6 +245,142 @@ export async function seed() {
|
||||
await db.insert(assignments).values(assignedRows);
|
||||
console.log(`assignments: ${assignedRows.length} seeded`);
|
||||
|
||||
/* 7. Skill taxonomy — one category + skill per position (Audio, Livestream,
|
||||
* Slides), each position's core requirement, and the volunteers' verified
|
||||
* levels so the auto-filler (D9) has competency to rank against. Each skill
|
||||
* gets its own category so the composed `dedupe_key` (category|technology|
|
||||
* function) stays unique.
|
||||
*/
|
||||
const categoryDefs = [
|
||||
{ slug: "audio", name: "Audio" },
|
||||
{ slug: "livestream", name: "Livestream" },
|
||||
{ slug: "slides", name: "Slides" },
|
||||
];
|
||||
await db
|
||||
.insert(skillCategories)
|
||||
.values(
|
||||
categoryDefs.map((c, i) => ({
|
||||
id: uuidv7(),
|
||||
slug: c.slug,
|
||||
name: c.name,
|
||||
description: `${c.name} skills`,
|
||||
colorHex: "#6b7280",
|
||||
icon: null,
|
||||
sortOrder: i,
|
||||
active: true,
|
||||
createdAt: new Date(),
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing({ target: skillCategories.slug });
|
||||
// Re-fetch canonical rows: ON CONFLICT DO NOTHING returns nothing on a
|
||||
// re-run, so downstream ids must come from the DB (the A2 lesson).
|
||||
const categoryRows = await db.select().from(skillCategories);
|
||||
const categoryBySlug = new Map(categoryRows.map((c) => [c.slug, c.id]));
|
||||
|
||||
const skillRows: (typeof skills.$inferInsert)[] = [
|
||||
{ id: uuidv7(), slug: "audio", name: "Audio", categoryId: categoryBySlug.get("audio")!, dedupeKey: `${categoryBySlug.get("audio")}|`, mentorMinLevel: "qualified", staleAfterDays: 120, recertRequired: false, sortOrder: 1, active: true, createdAt: new Date() },
|
||||
{ id: uuidv7(), slug: "livestream", name: "Livestream", categoryId: categoryBySlug.get("livestream")!, dedupeKey: `${categoryBySlug.get("livestream")}|`, mentorMinLevel: "qualified", staleAfterDays: 120, recertRequired: false, sortOrder: 2, active: true, createdAt: new Date() },
|
||||
{ id: uuidv7(), slug: "slides", name: "Slides", categoryId: categoryBySlug.get("slides")!, dedupeKey: `${categoryBySlug.get("slides")}|`, mentorMinLevel: "qualified", staleAfterDays: 120, recertRequired: false, sortOrder: 3, active: true, createdAt: new Date() },
|
||||
];
|
||||
for (const s of skillRows) {
|
||||
await db.insert(skills).values(s).onConflictDoNothing({ target: skills.slug });
|
||||
}
|
||||
console.log(`skills: ${skillRows.length} seeded`);
|
||||
const skillById = new Map(
|
||||
(await db.select().from(skills)).map((s) => [s.slug, s.id]),
|
||||
);
|
||||
|
||||
// Each position requires its matching skill (qualified, core).
|
||||
const positionSkillRows: (typeof positionSkills.$inferInsert)[] = [];
|
||||
for (const role of roleRows2) {
|
||||
const skillSlug = role.slug === "audio" ? "audio" : role.slug === "livestream" ? "livestream" : "slides";
|
||||
const skillId = skillById.get(skillSlug);
|
||||
if (!skillId) continue;
|
||||
positionSkillRows.push({
|
||||
positionId: role.id,
|
||||
skillId,
|
||||
weight: 2,
|
||||
requiredLevel: "qualified",
|
||||
isCore: true,
|
||||
});
|
||||
}
|
||||
await db.insert(positionSkills).values(positionSkillRows).onConflictDoNothing({
|
||||
target: [positionSkills.positionId, positionSkills.skillId],
|
||||
});
|
||||
console.log(`position_skills: ${positionSkillRows.length} seeded`);
|
||||
|
||||
// Volunteer verified levels — enough spread that the auto-filler ranks them.
|
||||
// verified_level is the gate (set by mentor/admin, never self-report).
|
||||
const [jordan, avery, sam] = volunteers;
|
||||
const verifiedRows: (typeof userSkills.$inferInsert)[] = [
|
||||
// user_id, skill_id, verified_level, self_comfort, mentor_opt_in
|
||||
{ id: uuidv7(), userId: jordan.id, skillId: skillById.get("audio")!, verifiedLevel: "qualified", selfComfort: 80, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: jordan.id, skillId: skillById.get("livestream")!, verifiedLevel: "assisted", selfComfort: 60, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: jordan.id, skillId: skillById.get("slides")!, verifiedLevel: "qualified", selfComfort: 75, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: avery.id, skillId: skillById.get("audio")!, verifiedLevel: "expert", selfComfort: 95, mentorOptIn: true, mentorApprovedAt: new Date() },
|
||||
{ id: uuidv7(), userId: avery.id, skillId: skillById.get("livestream")!, verifiedLevel: "assisted", selfComfort: 55, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: avery.id, skillId: skillById.get("slides")!, verifiedLevel: "qualified", selfComfort: 80, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: sam.id, skillId: skillById.get("audio")!, verifiedLevel: "assisted", selfComfort: 50, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: sam.id, skillId: skillById.get("livestream")!, verifiedLevel: "qualified", selfComfort: 78, mentorOptIn: false },
|
||||
{ id: uuidv7(), userId: sam.id, skillId: skillById.get("slides")!, verifiedLevel: "qualified", selfComfort: 82, mentorOptIn: false },
|
||||
];
|
||||
for (const r of verifiedRows) {
|
||||
await db.insert(userSkills).values(r).onConflictDoNothing({
|
||||
target: [userSkills.userId, userSkills.skillId],
|
||||
});
|
||||
}
|
||||
console.log(`user_skills: ${verifiedRows.length} seeded`);
|
||||
|
||||
/* 8. Reminder rules — the launch defaults (ARCHITECTURE §6.2). Sends are
|
||||
* computed from the instance start at publish time; SMS rules are seeded but
|
||||
* their email copy is what E1–E4 enqueues until E5 exists. */
|
||||
const ruleRows: (typeof notificationRules.$inferInsert)[] = [
|
||||
{ id: uuidv7(), key: "t_7", event: "assignment.created", offsetDays: -7, sendAtLocalTime: "09:00", channelSet: "email", appliesToServiceId: null, active: true },
|
||||
{ id: uuidv7(), key: "friday", event: "assignment.created", offsetDays: -2, sendAtLocalTime: "18:00", channelSet: "email+sms", appliesToServiceId: null, active: true },
|
||||
{ id: uuidv7(), key: "day_of", event: "assignment.created", offsetDays: 0, sendAtLocalTime: "06:30", channelSet: "sms", appliesToServiceId: null, active: true },
|
||||
// One-off shoots: email the assigned photographers two days out.
|
||||
{ id: uuidv7(), key: "event_reminder", event: "event.reminder", offsetDays: -2, sendAtLocalTime: "09:00", channelSet: "email", appliesToServiceId: null, active: true },
|
||||
];
|
||||
for (const r of ruleRows) {
|
||||
await db
|
||||
.insert(notificationRules)
|
||||
.values(r)
|
||||
.onConflictDoNothing({ target: notificationRules.key });
|
||||
}
|
||||
console.log(`notification_rules: ${ruleRows.length} seeded`);
|
||||
|
||||
/* 9. Training — two starter lessons so the Training tab is browsable. Only
|
||||
* inserted when the table is empty, so re-running the seed on a live DB
|
||||
* never duplicates an authored lesson. */
|
||||
const existingLessons = await db
|
||||
.select({ id: trainingLessons.id })
|
||||
.from(trainingLessons)
|
||||
.limit(1);
|
||||
if (existingLessons.length === 0) {
|
||||
await db.insert(trainingLessons).values([
|
||||
{
|
||||
id: uuidv7(),
|
||||
title: "Audio team basics",
|
||||
summary: "What to bring, how the booth is laid out, and the Sunday flow.",
|
||||
body: "Welcome to the audio team.\n\nBefore the service:\n- Arrive at call time (90 minutes before the service).\n- Check the schedule for your position and who you are serving with.\n- Power up the console and confirm the stage box is connected.\n\nDuring the service:\n- Keep the booth door closed and monitor the talkback.\n- Watch the service leader for cues.\n\nIf you cannot serve, open the confirmation email and decline so a coordinator can find cover.",
|
||||
published: true,
|
||||
sortOrder: 1,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
{
|
||||
id: uuidv7(),
|
||||
title: "Livestream checklist",
|
||||
summary: "Start the stream, check audio, and what to do if the encoder drops.",
|
||||
body: "Pre-service checklist\n- Confirm the encoder is on the correct stream key.\n- Verify the camera framing and lower-third graphics.\n- Monitor the stream on a second device for a full minute.\n\nIf the encoder drops: stay calm, restart the encoder, and tell the service leader. A gap in the recording is recoverable; a silent stream is not.",
|
||||
published: true,
|
||||
sortOrder: 2,
|
||||
createdAt: new Date(),
|
||||
},
|
||||
]);
|
||||
console.log("training_lessons: 2 seeded");
|
||||
}
|
||||
|
||||
|
||||
const [instanceCountRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(serviceInstances)
|
||||
|
||||
+55
-4
@@ -3,8 +3,9 @@
|
||||
* gathering template that instances (D2) and slots (D3) are built from.
|
||||
*
|
||||
* Integrity rules:
|
||||
* - Deactivate, never delete — `active` flips to false; the row persists so
|
||||
* historical instances and their assignments are preserved.
|
||||
* - Deactivate, never delete anything with history — `active` flips to false;
|
||||
* the row persists so historical instances and their assignments are
|
||||
* preserved. `deleteService` only removes a template that never ran.
|
||||
* - `rrule` is validated on write (RFC 5545 subset) so a malformed rule can
|
||||
* never reach the instance generator.
|
||||
* - `name` is unique and frozen on update (no update path accepts it).
|
||||
@@ -13,9 +14,9 @@
|
||||
* admin services list; `active: false` returns the full set (audit).
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { count, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { services } from "@/db/schema";
|
||||
import { assignments, services, serviceInstances, slots } from "@/db/schema";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { validateRecurrence } from "@/domain/recurrence";
|
||||
|
||||
@@ -102,3 +103,53 @@ export async function deactivateService(id: string) {
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export type ServiceDeleteResult =
|
||||
| { ok: true; removedInstances: number }
|
||||
| { ok: false; reason: "not_found" }
|
||||
| { ok: false; reason: "has_history"; instances: number; assignments: number };
|
||||
|
||||
/**
|
||||
* Hard delete for a template that never ran — the "created it by mistake" case.
|
||||
*
|
||||
* The deactivate-only rule still governs anything with history: if an instance
|
||||
* has started or is no longer a draft (published/cancelled), or any assignment
|
||||
* exists on the template's instances, the delete is refused and the caller
|
||||
* tells the admin to deactivate instead. Draft, future instances with no
|
||||
* assignments go with the template (their slots cascade).
|
||||
*/
|
||||
export async function deleteService(id: string): Promise<ServiceDeleteResult> {
|
||||
return db.transaction(async (tx) => {
|
||||
const [service] = await tx.select().from(services).where(eq(services.id, id));
|
||||
if (!service) return { ok: false, reason: "not_found" } as const;
|
||||
|
||||
const [instanceTally] = await tx
|
||||
.select({
|
||||
total: count(serviceInstances.id),
|
||||
// "History" is anything a volunteer may have seen or served.
|
||||
used: count(
|
||||
sql`case when ${serviceInstances.startsAt} <= now() or ${serviceInstances.status} <> 'draft' then 1 end`,
|
||||
),
|
||||
})
|
||||
.from(serviceInstances)
|
||||
.where(eq(serviceInstances.serviceId, id));
|
||||
|
||||
const [assignmentTally] = await tx
|
||||
.select({ total: count(assignments.id) })
|
||||
.from(assignments)
|
||||
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||
.where(eq(serviceInstances.serviceId, id));
|
||||
|
||||
const instances = Number(instanceTally?.total ?? 0);
|
||||
const assigned = Number(assignmentTally?.total ?? 0);
|
||||
if (Number(instanceTally?.used ?? 0) > 0 || assigned > 0) {
|
||||
return { ok: false, reason: "has_history", instances, assignments: assigned } as const;
|
||||
}
|
||||
|
||||
// Instances restrict the FK, so they go first; their slots cascade.
|
||||
await tx.delete(serviceInstances).where(eq(serviceInstances.serviceId, id));
|
||||
await tx.delete(services).where(eq(services.id, id));
|
||||
return { ok: true, removedInstances: instances } as const;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* Runtime app settings — admin-editable values that must not require a deploy.
|
||||
*
|
||||
* Backed by the `app_settings` key/value table:
|
||||
* - `email_from` / `notification_email`: the sender identity used for
|
||||
* outbound mail, and where admin test/failure mail should go.
|
||||
* - `smtp_user` / `smtp_app_password`: the Gmail account the app sends
|
||||
* through. The password is encrypted at rest (`encryptSecret`), and the
|
||||
* public read model only reports *whether* credentials are stored — the
|
||||
* secret never leaves the server.
|
||||
*
|
||||
* Missing rows mean "use the environment default".
|
||||
*/
|
||||
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { appSettings } from "@/db/schema";
|
||||
import { normalizeUserEmail } from "@/domain/users";
|
||||
import { decryptSecret, encryptSecret, normalizeAppPassword } from "@/lib/secret";
|
||||
|
||||
export interface EmailSettings {
|
||||
/** From address on outbound mail. */
|
||||
emailFrom: string;
|
||||
/** Optional admin inbox for test/failure mail; empty = the signed-in admin. */
|
||||
notificationEmail: string;
|
||||
/** Gmail account the app authenticates as; empty when not connected. */
|
||||
smtpUser: string;
|
||||
/** True when both the address and a decryptable app password are stored. */
|
||||
smtpConfigured: boolean;
|
||||
}
|
||||
|
||||
/** Server-only view: adds the decrypted password for the transport. */
|
||||
export interface EmailTransportSettings extends EmailSettings {
|
||||
smtpPassword: string | null;
|
||||
}
|
||||
|
||||
export interface EmailSettingsInput {
|
||||
emailFrom: string;
|
||||
notificationEmail: string;
|
||||
/** Empty string disconnects Gmail; undefined leaves it untouched. */
|
||||
smtpUser?: string;
|
||||
/** A new app password; blank/undefined keeps the stored one. */
|
||||
smtpAppPassword?: string;
|
||||
}
|
||||
|
||||
const KEY_FROM = "email_from";
|
||||
const KEY_NOTIFICATION = "notification_email";
|
||||
const KEY_SMTP_USER = "smtp_user";
|
||||
const KEY_SMTP_PASSWORD = "smtp_app_password";
|
||||
|
||||
const ALL_KEYS = [KEY_FROM, KEY_NOTIFICATION, KEY_SMTP_USER, KEY_SMTP_PASSWORD];
|
||||
|
||||
export function defaultEmailSettings(): EmailSettings {
|
||||
return {
|
||||
emailFrom: process.env.POSTMARK_FROM ?? "media@glenloch.local",
|
||||
notificationEmail: "",
|
||||
smtpUser: "",
|
||||
smtpConfigured: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function readValues(): Promise<Map<string, string>> {
|
||||
const rows = await db
|
||||
.select({ key: appSettings.key, value: appSettings.value })
|
||||
.from(appSettings)
|
||||
.where(inArray(appSettings.key, ALL_KEYS));
|
||||
return new Map(rows.map((row) => [row.key, row.value]));
|
||||
}
|
||||
|
||||
/** Settings including the decrypted app password — never send this to a client. */
|
||||
export async function getEmailTransportSettings(): Promise<EmailTransportSettings> {
|
||||
const values = await readValues();
|
||||
const defaults = defaultEmailSettings();
|
||||
const smtpUser = values.get(KEY_SMTP_USER) ?? "";
|
||||
const stored = values.get(KEY_SMTP_PASSWORD) ?? "";
|
||||
const smtpPassword = stored ? decryptSecret(stored) : null;
|
||||
|
||||
return {
|
||||
emailFrom: values.get(KEY_FROM) || defaults.emailFrom,
|
||||
notificationEmail: values.get(KEY_NOTIFICATION) ?? defaults.notificationEmail,
|
||||
smtpUser,
|
||||
smtpConfigured: Boolean(smtpUser && smtpPassword),
|
||||
smtpPassword,
|
||||
};
|
||||
}
|
||||
|
||||
/** Public settings — safe to return from a route or render into a page. */
|
||||
export async function getEmailSettings(): Promise<EmailSettings> {
|
||||
const full = await getEmailTransportSettings();
|
||||
return {
|
||||
emailFrom: full.emailFrom,
|
||||
notificationEmail: full.notificationEmail,
|
||||
smtpUser: full.smtpUser,
|
||||
smtpConfigured: full.smtpConfigured,
|
||||
};
|
||||
}
|
||||
|
||||
async function upsert(key: string, value: string): Promise<void> {
|
||||
await db
|
||||
.insert(appSettings)
|
||||
.values({ key, value, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: appSettings.key,
|
||||
set: { value, updatedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save email identity and (optionally) Gmail credentials. A blank app password
|
||||
* keeps the stored one, so an admin can change the From address or the inbox
|
||||
* without retyping the secret; clearing `smtpUser` deletes both Gmail rows.
|
||||
*/
|
||||
export async function saveEmailSettings(
|
||||
input: EmailSettingsInput,
|
||||
): Promise<EmailSettings> {
|
||||
await upsert(KEY_FROM, input.emailFrom);
|
||||
await upsert(KEY_NOTIFICATION, input.notificationEmail);
|
||||
|
||||
if (input.smtpUser !== undefined) {
|
||||
const smtpUser = input.smtpUser.trim();
|
||||
if (smtpUser === "") {
|
||||
await db
|
||||
.delete(appSettings)
|
||||
.where(inArray(appSettings.key, [KEY_SMTP_USER, KEY_SMTP_PASSWORD]));
|
||||
} else {
|
||||
await upsert(KEY_SMTP_USER, normalizeUserEmail(smtpUser));
|
||||
const password = normalizeAppPassword(input.smtpAppPassword ?? "");
|
||||
if (password !== "") {
|
||||
await upsert(KEY_SMTP_PASSWORD, encryptSecret(password));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return getEmailSettings();
|
||||
}
|
||||
|
||||
/** Restore a single setting to its environment default. */
|
||||
export async function clearEmailSetting(
|
||||
key: "email_from" | "notification_email" | "smtp_user" | "smtp_app_password",
|
||||
) {
|
||||
await db.delete(appSettings).where(eq(appSettings.key, key));
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* Runtime archive destination settings.
|
||||
*
|
||||
* NFS is a mounted filesystem, not an upload API. The app writes to a path that
|
||||
* must already be visible inside the container; the NFS export is mounted by
|
||||
* the Docker host and bind-mounted in (see docker-compose.yml). The stored
|
||||
* `nfsShare` is the human-readable export name so operators can confirm which
|
||||
* filesystem they are writing to, while `archivePath` is the actual mounted
|
||||
* path used by the archiver.
|
||||
*/
|
||||
|
||||
import { constants } from "node:fs";
|
||||
import { access, stat, statfs } from "node:fs/promises";
|
||||
import { inArray } from "drizzle-orm";
|
||||
import path from "node:path";
|
||||
import { db } from "@/db";
|
||||
import { appSettings } from "@/db/schema";
|
||||
|
||||
export interface StorageSettings {
|
||||
/** e.g. `nas.local:/volume1/church-media`; informational. */
|
||||
nfsShare: string;
|
||||
/** Absolute path inside the app container, e.g. `/archive`. */
|
||||
archivePath: string;
|
||||
/** Folder created under the mounted export for church archives. */
|
||||
archiveFolder: string;
|
||||
}
|
||||
|
||||
export interface StorageStatus {
|
||||
ready: boolean;
|
||||
message: string;
|
||||
freeBytes: number | null;
|
||||
}
|
||||
|
||||
const KEY_NFS_SHARE = "nfs_share";
|
||||
const KEY_ARCHIVE_PATH = "archive_path";
|
||||
const KEY_ARCHIVE_FOLDER = "archive_folder";
|
||||
|
||||
const ALL_KEYS = [KEY_NFS_SHARE, KEY_ARCHIVE_PATH, KEY_ARCHIVE_FOLDER];
|
||||
|
||||
const DEFAULT_ARCHIVE_PATH = process.env.ARCHIVE_DIR ?? "/archive";
|
||||
const DEFAULT_ARCHIVE_FOLDER = process.env.ARCHIVE_FOLDER ?? "Glenloch Media";
|
||||
|
||||
export function defaultStorageSettings(): StorageSettings {
|
||||
return {
|
||||
nfsShare: process.env.NFS_SHARE ?? "",
|
||||
archivePath: DEFAULT_ARCHIVE_PATH,
|
||||
archiveFolder: DEFAULT_ARCHIVE_FOLDER,
|
||||
};
|
||||
}
|
||||
|
||||
async function readValues(): Promise<Map<string, string>> {
|
||||
const rows = await db
|
||||
.select({ key: appSettings.key, value: appSettings.value })
|
||||
.from(appSettings)
|
||||
.where(inArray(appSettings.key, ALL_KEYS));
|
||||
return new Map(rows.map((row) => [row.key, row.value]));
|
||||
}
|
||||
|
||||
export async function getStorageSettings(): Promise<StorageSettings> {
|
||||
const values = await readValues();
|
||||
const defaults = defaultStorageSettings();
|
||||
return {
|
||||
nfsShare: values.get(KEY_NFS_SHARE) ?? defaults.nfsShare,
|
||||
archivePath: values.get(KEY_ARCHIVE_PATH) || defaults.archivePath,
|
||||
archiveFolder: values.get(KEY_ARCHIVE_FOLDER) || defaults.archiveFolder,
|
||||
};
|
||||
}
|
||||
|
||||
async function upsert(key: string, value: string): Promise<void> {
|
||||
await db
|
||||
.insert(appSettings)
|
||||
.values({ key, value, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: appSettings.key,
|
||||
set: { value, updatedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveStorageSettings(
|
||||
input: StorageSettings,
|
||||
): Promise<StorageSettings> {
|
||||
await upsert(KEY_NFS_SHARE, input.nfsShare.trim());
|
||||
await upsert(KEY_ARCHIVE_PATH, input.archivePath.trim());
|
||||
await upsert(KEY_ARCHIVE_FOLDER, input.archiveFolder.trim());
|
||||
return getStorageSettings();
|
||||
}
|
||||
|
||||
/** Check the mounted destination without creating it on a page render. */
|
||||
export async function checkArchiveDestination(
|
||||
settings: StorageSettings,
|
||||
): Promise<StorageStatus> {
|
||||
const archivePath = settings.archivePath.trim();
|
||||
if (!path.isAbsolute(archivePath)) {
|
||||
return {
|
||||
ready: false,
|
||||
message: "Archive path must be an absolute path inside the app container.",
|
||||
freeBytes: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const info = await stat(archivePath);
|
||||
if (!info.isDirectory()) {
|
||||
return {
|
||||
ready: false,
|
||||
message: `${archivePath} exists but is not a directory.`,
|
||||
freeBytes: null,
|
||||
};
|
||||
}
|
||||
await access(archivePath, constants.W_OK);
|
||||
let freeBytes: number | null = null;
|
||||
try {
|
||||
const filesystem = await statfs(archivePath);
|
||||
freeBytes = Number(filesystem.bavail) * Number(filesystem.bsize);
|
||||
} catch {
|
||||
// statfs is not available on every platform; write access is enough.
|
||||
}
|
||||
return {
|
||||
ready: true,
|
||||
message: `Ready to archive to ${archivePath}.`,
|
||||
freeBytes,
|
||||
};
|
||||
} catch (error) {
|
||||
const detail = error instanceof Error ? error.message : "not accessible";
|
||||
return {
|
||||
ready: false,
|
||||
message: `Archive destination is not available: ${detail}`,
|
||||
freeBytes: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/**
|
||||
* Training lessons + resource metadata.
|
||||
*
|
||||
* Lesson bodies are plain text (rendered with preserved whitespace); file bytes
|
||||
* live on disk under `UPLOAD_DIR` and only metadata is stored here. Listing
|
||||
* batches the resource fetch so a page with N lessons is still 2 queries.
|
||||
*/
|
||||
|
||||
import { asc, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { trainingLessons, trainingResources } from "@/db/schema";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
export interface TrainingResourceRow {
|
||||
id: string;
|
||||
lessonId: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
}
|
||||
|
||||
export interface TrainingLessonRow {
|
||||
id: string;
|
||||
title: string;
|
||||
summary: string | null;
|
||||
body: string;
|
||||
published: boolean;
|
||||
sortOrder: number;
|
||||
resources: TrainingResourceRow[];
|
||||
}
|
||||
|
||||
export interface LessonInput {
|
||||
title: string;
|
||||
summary?: string | null;
|
||||
body?: string;
|
||||
published?: boolean;
|
||||
sortOrder?: number;
|
||||
}
|
||||
|
||||
export async function listLessons(
|
||||
opts: { includeUnpublished?: boolean } = {},
|
||||
): Promise<TrainingLessonRow[]> {
|
||||
const lessons = await db
|
||||
.select()
|
||||
.from(trainingLessons)
|
||||
.where(
|
||||
opts.includeUnpublished ? undefined : eq(trainingLessons.published, true),
|
||||
)
|
||||
.orderBy(asc(trainingLessons.sortOrder), asc(trainingLessons.title));
|
||||
|
||||
if (lessons.length === 0) return [];
|
||||
|
||||
const resources = await db
|
||||
.select()
|
||||
.from(trainingResources)
|
||||
.where(
|
||||
inArray(
|
||||
trainingResources.lessonId,
|
||||
lessons.map((lesson) => lesson.id),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(trainingResources.createdAt));
|
||||
|
||||
return lessons.map((lesson) => ({
|
||||
id: lesson.id,
|
||||
title: lesson.title,
|
||||
summary: lesson.summary,
|
||||
body: lesson.body,
|
||||
published: lesson.published,
|
||||
sortOrder: lesson.sortOrder,
|
||||
resources: resources
|
||||
.filter((resource) => resource.lessonId === lesson.id)
|
||||
.map((resource) => ({
|
||||
id: resource.id,
|
||||
lessonId: resource.lessonId,
|
||||
filename: resource.filename,
|
||||
mimeType: resource.mimeType,
|
||||
sizeBytes: resource.sizeBytes,
|
||||
})),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getLesson(id: string): Promise<TrainingLessonRow | null> {
|
||||
const [lesson] = await db
|
||||
.select()
|
||||
.from(trainingLessons)
|
||||
.where(eq(trainingLessons.id, id))
|
||||
.limit(1);
|
||||
if (!lesson) return null;
|
||||
const resources = await db
|
||||
.select()
|
||||
.from(trainingResources)
|
||||
.where(eq(trainingResources.lessonId, id))
|
||||
.orderBy(asc(trainingResources.createdAt));
|
||||
return {
|
||||
id: lesson.id,
|
||||
title: lesson.title,
|
||||
summary: lesson.summary,
|
||||
body: lesson.body,
|
||||
published: lesson.published,
|
||||
sortOrder: lesson.sortOrder,
|
||||
resources: resources.map((resource) => ({
|
||||
id: resource.id,
|
||||
lessonId: resource.lessonId,
|
||||
filename: resource.filename,
|
||||
mimeType: resource.mimeType,
|
||||
sizeBytes: resource.sizeBytes,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createLesson(input: LessonInput) {
|
||||
const [row] = await db
|
||||
.insert(trainingLessons)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
title: input.title,
|
||||
summary: input.summary ?? null,
|
||||
body: input.body ?? "",
|
||||
published: input.published ?? false,
|
||||
sortOrder: input.sortOrder ?? 0,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateLesson(id: string, patch: Partial<LessonInput>) {
|
||||
const values: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (patch.title !== undefined) values.title = patch.title;
|
||||
if (patch.summary !== undefined) values.summary = patch.summary;
|
||||
if (patch.body !== undefined) values.body = patch.body;
|
||||
if (patch.published !== undefined) values.published = patch.published;
|
||||
if (patch.sortOrder !== undefined) values.sortOrder = patch.sortOrder;
|
||||
|
||||
const [row] = await db
|
||||
.update(trainingLessons)
|
||||
.set(values)
|
||||
.where(eq(trainingLessons.id, id))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Delete a lesson; resources cascade. Callers remove files from disk. */
|
||||
export async function deleteLesson(id: string) {
|
||||
const [row] = await db
|
||||
.delete(trainingLessons)
|
||||
.where(eq(trainingLessons.id, id))
|
||||
.returning({ id: trainingLessons.id });
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function addResource(input: {
|
||||
lessonId: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
storedName: string;
|
||||
}) {
|
||||
const [row] = await db
|
||||
.insert(trainingResources)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
lessonId: input.lessonId,
|
||||
filename: input.filename,
|
||||
mimeType: input.mimeType,
|
||||
sizeBytes: input.sizeBytes,
|
||||
storedName: input.storedName,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function getResource(id: string) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(trainingResources)
|
||||
.where(eq(trainingResources.id, id))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function deleteResource(id: string) {
|
||||
const [row] = await db
|
||||
.delete(trainingResources)
|
||||
.where(eq(trainingResources.id, id))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Stored file names for a lesson, so a delete can remove the bytes too. */
|
||||
export async function listResourceStoredNames(lessonId: string): Promise<string[]> {
|
||||
const rows = await db
|
||||
.select({ storedName: trainingResources.storedName })
|
||||
.from(trainingResources)
|
||||
.where(eq(trainingResources.lessonId, lessonId));
|
||||
return rows.map((row) => row.storedName);
|
||||
}
|
||||
+73
-1
@@ -13,7 +13,7 @@
|
||||
* key, which trips Drizzle 0.45.4's `one()` typing), so this queries directly.
|
||||
*/
|
||||
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { userSkills, skills } from "@/db/schema";
|
||||
|
||||
@@ -48,6 +48,77 @@ export async function setSelfComfort(
|
||||
return row;
|
||||
}
|
||||
|
||||
/** One competency record, or null when the volunteer has no entry for that skill. */
|
||||
export async function getUserSkill(userId: string, skillId: string) {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(userSkills)
|
||||
.where(and(eq(userSkills.userId, userId), eq(userSkills.skillId, skillId)))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a competency record at a level without an assessment. Used when an
|
||||
* admin adds a skill to someone: the default level is `none` (the bottom of
|
||||
* the ladder), and nothing has moved yet, so there is nothing to audit. Any
|
||||
* level above `none` goes through `verifySkillLevel` instead.
|
||||
*/
|
||||
export async function addUserSkill(
|
||||
userId: string,
|
||||
skillId: string,
|
||||
verifiedLevel: string = "none",
|
||||
) {
|
||||
const [row] = await db
|
||||
.insert(userSkills)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
userId,
|
||||
skillId,
|
||||
selfComfort: null,
|
||||
selfRatedAt: null,
|
||||
verifiedLevel: verifiedLevel as "none",
|
||||
})
|
||||
.onConflictDoNothing({ target: [userSkills.userId, userSkills.skillId] })
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a competency record. Assessment history is deliberately kept: it
|
||||
* records what was verified and when, which stays true after the current entry
|
||||
* is deleted.
|
||||
*/
|
||||
export async function deleteUserSkill(userId: string, skillId: string) {
|
||||
const [row] = await db
|
||||
.delete(userSkills)
|
||||
.where(and(eq(userSkills.userId, userId), eq(userSkills.skillId, skillId)))
|
||||
.returning({ id: userSkills.id });
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin sign-off on a mentor designation (C5). The verified level and opt-in
|
||||
* still have to be in place; this flag is the missing third input that
|
||||
* `isMentorReady` requires. Clearing it revokes the designation.
|
||||
*/
|
||||
export async function setMentorApproval(
|
||||
userId: string,
|
||||
skillId: string,
|
||||
approved: boolean,
|
||||
approvedBy: string,
|
||||
) {
|
||||
const [row] = await db
|
||||
.update(userSkills)
|
||||
.set({
|
||||
mentorApprovedAt: approved ? new Date() : null,
|
||||
mentorApprovedBy: approved ? approvedBy : null,
|
||||
})
|
||||
.where(and(eq(userSkills.userId, userId), eq(userSkills.skillId, skillId)))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** A user's competency records, joined to the skill for display. */
|
||||
export async function getUserSkills(userId: string) {
|
||||
return db
|
||||
@@ -61,6 +132,7 @@ export async function getUserSkills(userId: string) {
|
||||
verifiedBy: userSkills.verifiedBy,
|
||||
verifiedAt: userSkills.verifiedAt,
|
||||
mentorOptIn: userSkills.mentorOptIn,
|
||||
mentorApprovedAt: userSkills.mentorApprovedAt,
|
||||
lastServedOn: userSkills.lastServedOn,
|
||||
notes: userSkills.notes,
|
||||
name: skills.name,
|
||||
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
/**
|
||||
* User administration data layer — the read/write half of the People panel.
|
||||
*
|
||||
* `src/db/admin.ts` keeps the light roster read model; this module owns the
|
||||
* full records an admin edits, plus the two facts the removal rules need
|
||||
* (whether the person has served, and how many other active admins exist).
|
||||
*
|
||||
* Writes are partial: `updateUser` only writes the keys it is given, so a
|
||||
* patch that omits a field (say, the phone) never nulls it out.
|
||||
*/
|
||||
|
||||
import { and, asc, eq, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import { assignments, userSkills, users } from "@/db/schema";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { normalizeUsername } from "@/auth/password";
|
||||
import { CHURCH_TIMEZONE } from "@/lib/tz";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
import { displayNameFor, normalizeUserEmail } from "@/domain/users";
|
||||
|
||||
const userName = sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`;
|
||||
|
||||
export interface ManagedUserRow {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
displayName: string;
|
||||
systemRole: string;
|
||||
status: string;
|
||||
phoneE164: string | null;
|
||||
timezone: string;
|
||||
emergencyContact: string | null;
|
||||
notes: string | null;
|
||||
deactivatedAt: Date | null;
|
||||
createdAt: Date;
|
||||
/** Never expose the hash itself to an admin list or page. */
|
||||
passwordSet: boolean;
|
||||
}
|
||||
|
||||
/** Every user, with the ones that need attention first (pending, then active…). */
|
||||
export async function listUsersForAdmin(): Promise<ManagedUserRow[]> {
|
||||
const statusRank = sql`CASE ${users.status}
|
||||
WHEN 'pending_approval' THEN 0
|
||||
WHEN 'invited' THEN 1
|
||||
WHEN 'active' THEN 2
|
||||
WHEN 'inactive' THEN 3
|
||||
ELSE 4
|
||||
END`;
|
||||
|
||||
return db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
firstName: users.firstName,
|
||||
lastName: users.lastName,
|
||||
displayName: userName,
|
||||
systemRole: users.systemRole,
|
||||
status: users.status,
|
||||
phoneE164: users.phoneE164,
|
||||
timezone: users.timezone,
|
||||
emergencyContact: users.emergencyContact,
|
||||
notes: users.notes,
|
||||
deactivatedAt: users.deactivatedAt,
|
||||
createdAt: users.createdAt,
|
||||
passwordSet: sql<boolean>`${users.passwordHash} is not null`,
|
||||
})
|
||||
.from(users)
|
||||
.orderBy(statusRank, asc(users.lastName), asc(users.firstName));
|
||||
}
|
||||
|
||||
export async function getUserById(id: string): Promise<ManagedUserRow | null> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
firstName: users.firstName,
|
||||
lastName: users.lastName,
|
||||
displayName: userName,
|
||||
systemRole: users.systemRole,
|
||||
status: users.status,
|
||||
phoneE164: users.phoneE164,
|
||||
timezone: users.timezone,
|
||||
emergencyContact: users.emergencyContact,
|
||||
notes: users.notes,
|
||||
deactivatedAt: users.deactivatedAt,
|
||||
createdAt: users.createdAt,
|
||||
passwordSet: sql<boolean>`${users.passwordHash} is not null`,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, id))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** The fields credential checks need. Never send this row to a client. */
|
||||
export interface UserCredentialRow {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
displayName: string | null;
|
||||
passwordHash: string | null;
|
||||
systemRole: SystemRole;
|
||||
status: string;
|
||||
deactivatedAt: Date | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a login identifier. Usernames and emails are both accepted, and both
|
||||
* are stored lowercased. The default username is the person's email, so most
|
||||
* people can sign in with either interchangeably.
|
||||
*/
|
||||
export async function getUserByLogin(login: string): Promise<UserCredentialRow | null> {
|
||||
const normalized = normalizeUsername(login);
|
||||
if (!normalized) return null;
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
passwordHash: users.passwordHash,
|
||||
systemRole: users.systemRole,
|
||||
status: users.status,
|
||||
deactivatedAt: users.deactivatedAt,
|
||||
})
|
||||
.from(users)
|
||||
.where(or(eq(users.username, normalized), eq(users.email, normalized)))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** The signed-in user's own credential state for setup and password changes. */
|
||||
export async function getUserSecurity(id: string): Promise<UserCredentialRow | null> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
username: users.username,
|
||||
displayName: users.displayName,
|
||||
passwordHash: users.passwordHash,
|
||||
systemRole: users.systemRole,
|
||||
status: users.status,
|
||||
deactivatedAt: users.deactivatedAt,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, id))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** A username cannot collide with another account's username or email. */
|
||||
export async function credentialTaken(
|
||||
username: string,
|
||||
excludeUserId?: string,
|
||||
): Promise<boolean> {
|
||||
const normalized = normalizeUsername(username);
|
||||
if (!normalized) return false;
|
||||
const matches = or(
|
||||
eq(users.username, normalized),
|
||||
eq(users.email, normalized),
|
||||
);
|
||||
const [row] = await db
|
||||
.select({ id: users.id })
|
||||
.from(users)
|
||||
.where(excludeUserId ? and(matches, ne(users.id, excludeUserId)) : matches)
|
||||
.limit(1);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
export async function updateUserCredentials(
|
||||
id: string,
|
||||
patch: { username?: string; passwordHash?: string },
|
||||
) {
|
||||
const values: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (patch.username !== undefined)
|
||||
values.username = normalizeUsername(patch.username);
|
||||
if (patch.passwordHash !== undefined) values.passwordHash = patch.passwordHash;
|
||||
const [row] = await db
|
||||
.update(users)
|
||||
.set(values)
|
||||
.where(eq(users.id, id))
|
||||
.returning({ id: users.id, username: users.username });
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Has this person ever held a slot? Assignment rows restrict deletion. */
|
||||
export async function hasAssignmentHistory(userId: string): Promise<boolean> {
|
||||
const [row] = await db
|
||||
.select({ id: assignments.id })
|
||||
.from(assignments)
|
||||
.where(eq(assignments.userId, userId))
|
||||
.limit(1);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
/** Active admins who could still sign in, excluding the person being changed. */
|
||||
export async function countOtherActiveAdmins(excludeUserId: string): Promise<number> {
|
||||
const [row] = await db
|
||||
.select({ count: sql<number>`count(*)::int` })
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.systemRole, "admin"),
|
||||
eq(users.status, "active"),
|
||||
isNull(users.deactivatedAt),
|
||||
ne(users.id, excludeUserId),
|
||||
),
|
||||
);
|
||||
return row?.count ?? 0;
|
||||
}
|
||||
|
||||
export interface CreateUserInput {
|
||||
email: string;
|
||||
username?: string;
|
||||
firstName: string;
|
||||
lastName?: string;
|
||||
displayName?: string | null;
|
||||
phoneE164?: string | null;
|
||||
systemRole: SystemRole;
|
||||
status?: "invited" | "pending_approval" | "active" | "inactive" | "denied";
|
||||
timezone?: string;
|
||||
emergencyContact?: string | null;
|
||||
notes?: string | null;
|
||||
}
|
||||
|
||||
export async function createUser(input: CreateUserInput) {
|
||||
const status = input.status ?? "active";
|
||||
const [row] = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
id: uuidv7(),
|
||||
email: normalizeUserEmail(input.email),
|
||||
username: normalizeUsername(input.username ?? input.email),
|
||||
firstName: input.firstName,
|
||||
lastName: input.lastName ?? "",
|
||||
displayName: displayNameFor({
|
||||
firstName: input.firstName,
|
||||
lastName: input.lastName,
|
||||
displayName: input.displayName,
|
||||
}),
|
||||
phoneE164: input.phoneE164 ?? null,
|
||||
systemRole: input.systemRole,
|
||||
status,
|
||||
// An account created directly as active is approved by definition; keep
|
||||
// the audit column truthful so approval history is not blank.
|
||||
approvedAt: status === "active" ? new Date() : null,
|
||||
timezone: input.timezone ?? CHURCH_TIMEZONE,
|
||||
emergencyContact: input.emergencyContact ?? null,
|
||||
notes: input.notes ?? null,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row!;
|
||||
}
|
||||
|
||||
export interface UpdateUserInput {
|
||||
email?: string;
|
||||
username?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
displayName?: string | null;
|
||||
phoneE164?: string | null;
|
||||
systemRole?: SystemRole;
|
||||
status?: "invited" | "pending_approval" | "active" | "inactive" | "denied";
|
||||
timezone?: string;
|
||||
emergencyContact?: string | null;
|
||||
notes?: string | null;
|
||||
deactivatedAt?: Date | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Patch the given fields only. `undefined` means "leave it alone", `null` means
|
||||
* "clear it" — the distinction the profile update (B2) had to learn.
|
||||
*/
|
||||
export async function updateUser(id: string, patch: UpdateUserInput) {
|
||||
const values: Record<string, unknown> = { updatedAt: new Date() };
|
||||
if (patch.email !== undefined) values.email = normalizeUserEmail(patch.email);
|
||||
if (patch.username !== undefined)
|
||||
values.username = normalizeUsername(patch.username);
|
||||
if (patch.firstName !== undefined) values.firstName = patch.firstName;
|
||||
if (patch.lastName !== undefined) values.lastName = patch.lastName;
|
||||
if (patch.displayName !== undefined) values.displayName = patch.displayName;
|
||||
if (patch.phoneE164 !== undefined) values.phoneE164 = patch.phoneE164;
|
||||
if (patch.systemRole !== undefined) values.systemRole = patch.systemRole;
|
||||
if (patch.status !== undefined) {
|
||||
values.status = patch.status;
|
||||
// Keep `approved_at` aligned with an admin status transition. Approval is
|
||||
// still derived from `status` at read time, but the audit trail should
|
||||
// show when the account was activated.
|
||||
values.approvedAt = patch.status === "active" ? new Date() : null;
|
||||
}
|
||||
if (patch.timezone !== undefined) values.timezone = patch.timezone;
|
||||
if (patch.emergencyContact !== undefined)
|
||||
values.emergencyContact = patch.emergencyContact;
|
||||
if (patch.notes !== undefined) values.notes = patch.notes;
|
||||
if (patch.deactivatedAt !== undefined) values.deactivatedAt = patch.deactivatedAt;
|
||||
|
||||
const [row] = await db
|
||||
.update(users)
|
||||
.set(values)
|
||||
.where(eq(users.id, id))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard delete. Callers must check the removal rules first.
|
||||
*
|
||||
* The person's skill-level rows go with them — both explicitly here and via
|
||||
* `ON DELETE CASCADE`, so removal never leaves competency entries behind for an
|
||||
* account that no longer exists. Both writes share one transaction: if the
|
||||
* user row cannot be deleted, the skill rows are not touched either.
|
||||
*/
|
||||
export async function deleteUser(id: string) {
|
||||
return db.transaction(async (tx) => {
|
||||
await tx.delete(userSkills).where(eq(userSkills.userId, id));
|
||||
const [row] = await tx
|
||||
.delete(users)
|
||||
.where(eq(users.id, id))
|
||||
.returning({ id: users.id });
|
||||
return row ?? null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* Event video queries and access checks.
|
||||
*
|
||||
* Video bytes are never stored in Postgres: `originalStoredName` points into the
|
||||
* configured NFS archive and `webStoredName` / `posterStoredName` point into
|
||||
* `UPLOAD_DIR`. Every access check reuses the event access model, so a video is
|
||||
* private unless its visibility says otherwise.
|
||||
*/
|
||||
|
||||
import { and, asc, desc, eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
eventVideos,
|
||||
events,
|
||||
type EventVideoStatus,
|
||||
type EventVideoVisibility,
|
||||
} from "@/db/schema";
|
||||
import { getEventAccess, type EventSummaryRow } from "@/db/events";
|
||||
import type { SystemRole } from "@/auth/roles";
|
||||
import { uuidv7 } from "@/lib/uuid";
|
||||
|
||||
export type EventVideoRow = typeof eventVideos.$inferSelect;
|
||||
|
||||
export interface EventVideoWithEvent extends EventVideoRow {
|
||||
eventTitle: string;
|
||||
eventStartsAt: Date;
|
||||
}
|
||||
|
||||
export interface EventVideoAccess {
|
||||
video: EventVideoRow;
|
||||
event: EventSummaryRow;
|
||||
canManage: boolean;
|
||||
canContribute: boolean;
|
||||
}
|
||||
|
||||
export interface EventVideoPatch {
|
||||
title?: string;
|
||||
description?: string | null;
|
||||
visibility?: EventVideoVisibility;
|
||||
durationMs?: number | null;
|
||||
width?: number | null;
|
||||
height?: number | null;
|
||||
trimStartMs?: number;
|
||||
trimEndMs?: number | null;
|
||||
webStoredName?: string | null;
|
||||
posterStoredName?: string | null;
|
||||
status?: EventVideoStatus;
|
||||
errorMessage?: string | null;
|
||||
processedAt?: Date | null;
|
||||
updatedAt?: Date;
|
||||
}
|
||||
|
||||
function withEvent(row: {
|
||||
video: EventVideoRow;
|
||||
eventTitle: string;
|
||||
eventStartsAt: Date;
|
||||
}): EventVideoWithEvent {
|
||||
return {
|
||||
...row.video,
|
||||
eventTitle: row.eventTitle,
|
||||
eventStartsAt: row.eventStartsAt,
|
||||
};
|
||||
}
|
||||
|
||||
export async function listEventVideos(
|
||||
eventId: string,
|
||||
): Promise<EventVideoRow[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(eventVideos)
|
||||
.where(eq(eventVideos.eventId, eventId))
|
||||
.orderBy(desc(eventVideos.createdAt));
|
||||
}
|
||||
|
||||
export async function listEventVideosForEvents(
|
||||
eventIds: readonly string[],
|
||||
): Promise<EventVideoWithEvent[]> {
|
||||
if (eventIds.length === 0) return [];
|
||||
const rows = await db
|
||||
.select({
|
||||
video: eventVideos,
|
||||
eventTitle: events.title,
|
||||
eventStartsAt: events.startsAt,
|
||||
})
|
||||
.from(eventVideos)
|
||||
.innerJoin(events, eq(events.id, eventVideos.eventId))
|
||||
.where(inArray(eventVideos.eventId, [...eventIds]))
|
||||
.orderBy(desc(eventVideos.createdAt));
|
||||
return rows.map(withEvent);
|
||||
}
|
||||
|
||||
export async function getEventVideoRow(
|
||||
videoId: string,
|
||||
): Promise<EventVideoRow | null> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(eventVideos)
|
||||
.where(eq(eventVideos.id, videoId))
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function getEventVideoAccess(
|
||||
videoId: string,
|
||||
userId: string,
|
||||
role: SystemRole | null | undefined,
|
||||
): Promise<EventVideoAccess | null> {
|
||||
const [row] = await db
|
||||
.select({ video: eventVideos, eventId: events.id })
|
||||
.from(eventVideos)
|
||||
.innerJoin(events, eq(events.id, eventVideos.eventId))
|
||||
.where(eq(eventVideos.id, videoId))
|
||||
.limit(1);
|
||||
if (!row) return null;
|
||||
|
||||
const access = await getEventAccess(row.video.eventId, userId, role);
|
||||
if (!access) return null;
|
||||
return {
|
||||
video: row.video,
|
||||
event: access.event,
|
||||
canManage: access.canManage,
|
||||
canContribute: access.canContribute,
|
||||
};
|
||||
}
|
||||
|
||||
/** Ready, public/unlisted video with its event; used by watch and embed routes. */
|
||||
export async function getPublicEventVideo(
|
||||
videoId: string,
|
||||
): Promise<EventVideoWithEvent | null> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
video: eventVideos,
|
||||
eventTitle: events.title,
|
||||
eventStartsAt: events.startsAt,
|
||||
})
|
||||
.from(eventVideos)
|
||||
.innerJoin(events, eq(events.id, eventVideos.eventId))
|
||||
.where(
|
||||
and(
|
||||
eq(eventVideos.id, videoId),
|
||||
eq(eventVideos.status, "ready"),
|
||||
inArray(eventVideos.visibility, ["public", "unlisted"]),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ? withEvent(row) : null;
|
||||
}
|
||||
|
||||
export async function findEventVideoByChecksum(
|
||||
eventId: string,
|
||||
checksumSha256: string,
|
||||
): Promise<EventVideoRow | null> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(eventVideos)
|
||||
.where(
|
||||
and(
|
||||
eq(eventVideos.eventId, eventId),
|
||||
eq(eventVideos.checksumSha256, checksumSha256),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function addEventVideo(input: {
|
||||
id?: string;
|
||||
eventId: string;
|
||||
uploaderId: string;
|
||||
title: string;
|
||||
description: string | null;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
checksumSha256: string;
|
||||
originalStoredName: string;
|
||||
archiveFolder: string;
|
||||
visibility: EventVideoVisibility;
|
||||
}): Promise<EventVideoRow> {
|
||||
const [row] = await db
|
||||
.insert(eventVideos)
|
||||
.values({
|
||||
// The upload route reserves this id for the NFS path, so reuse it here.
|
||||
id: input.id ?? uuidv7(),
|
||||
eventId: input.eventId,
|
||||
uploaderId: input.uploaderId,
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
filename: input.filename,
|
||||
mimeType: input.mimeType,
|
||||
sizeBytes: input.sizeBytes,
|
||||
checksumSha256: input.checksumSha256,
|
||||
originalStoredName: input.originalStoredName,
|
||||
archiveFolder: input.archiveFolder,
|
||||
visibility: input.visibility,
|
||||
status: "processing",
|
||||
trimStartMs: 0,
|
||||
trimEndMs: null,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateEventVideo(
|
||||
videoId: string,
|
||||
patch: EventVideoPatch,
|
||||
): Promise<EventVideoRow | null> {
|
||||
const [row] = await db
|
||||
.update(eventVideos)
|
||||
.set({ ...patch, updatedAt: patch.updatedAt ?? new Date() })
|
||||
.where(eq(eventVideos.id, videoId))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function markVideoProcessing(
|
||||
videoId: string,
|
||||
): Promise<EventVideoRow | null> {
|
||||
return updateEventVideo(videoId, {
|
||||
status: "processing",
|
||||
errorMessage: null,
|
||||
});
|
||||
}
|
||||
|
||||
export async function markVideoReady(input: {
|
||||
videoId: string;
|
||||
durationMs: number;
|
||||
width: number;
|
||||
height: number;
|
||||
trimStartMs: number;
|
||||
trimEndMs: number;
|
||||
webStoredName: string;
|
||||
posterStoredName: string;
|
||||
}): Promise<EventVideoRow | null> {
|
||||
return updateEventVideo(input.videoId, {
|
||||
status: "ready",
|
||||
durationMs: input.durationMs,
|
||||
width: input.width,
|
||||
height: input.height,
|
||||
trimStartMs: input.trimStartMs,
|
||||
trimEndMs: input.trimEndMs,
|
||||
webStoredName: input.webStoredName,
|
||||
posterStoredName: input.posterStoredName,
|
||||
errorMessage: null,
|
||||
processedAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
export async function markVideoFailed(
|
||||
videoId: string,
|
||||
message: string,
|
||||
): Promise<EventVideoRow | null> {
|
||||
return updateEventVideo(videoId, {
|
||||
status: "failed",
|
||||
errorMessage: message.slice(0, 1000),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteEventVideo(
|
||||
videoId: string,
|
||||
): Promise<EventVideoRow | null> {
|
||||
const [row] = await db
|
||||
.delete(eventVideos)
|
||||
.where(eq(eventVideos.id, videoId))
|
||||
.returning();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function listVideosForEventOrdered(
|
||||
eventId: string,
|
||||
): Promise<EventVideoRow[]> {
|
||||
return db
|
||||
.select()
|
||||
.from(eventVideos)
|
||||
.where(eq(eventVideos.eventId, eventId))
|
||||
.orderBy(asc(eventVideos.createdAt));
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
/**
|
||||
* Volunteer-facing read models: the next serve, personal history, upcoming
|
||||
* event assignments, and the personal calendar feed.
|
||||
*
|
||||
* Scheduling rows are resolved here once so the home/availability/profile
|
||||
* screens do not each grow their own joins. Writes still live in their owning
|
||||
* modules (`respond.ts`, `unavailability.ts`, `profile.ts`).
|
||||
*/
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { and, asc, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
|
||||
import { db } from "@/db";
|
||||
import {
|
||||
assignments,
|
||||
eventPhotographers,
|
||||
events,
|
||||
roles,
|
||||
serviceInstances,
|
||||
services,
|
||||
slots,
|
||||
unavailability,
|
||||
users,
|
||||
} from "@/db/schema";
|
||||
import { CHURCH_TIMEZONE, dateInTimezone } from "@/lib/tz";
|
||||
|
||||
const ACTIVE_ASSIGNMENT = ["proposed", "confirmed"] as const;
|
||||
const HISTORY_ASSIGNMENT = ["proposed", "confirmed", "completed"] as const;
|
||||
|
||||
function isoDateUTC(date: Date | null): string {
|
||||
if (!date) return "";
|
||||
return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}-${String(
|
||||
date.getUTCDate(),
|
||||
).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export interface ServeRow {
|
||||
assignmentId: string;
|
||||
slotId: string;
|
||||
instanceId: string;
|
||||
roleName: string;
|
||||
serviceName: string;
|
||||
status: string;
|
||||
occursOn: string;
|
||||
startsAt: Date;
|
||||
endsAt: Date | null;
|
||||
callTime: Date | null;
|
||||
location: string | null;
|
||||
instanceStatus: string;
|
||||
isTraineeSlot: boolean;
|
||||
}
|
||||
|
||||
function serveSelect() {
|
||||
return {
|
||||
assignmentId: assignments.id,
|
||||
slotId: slots.id,
|
||||
instanceId: serviceInstances.id,
|
||||
roleName: roles.name,
|
||||
serviceName: services.name,
|
||||
status: assignments.status,
|
||||
occursOn: serviceInstances.occursOn,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
endsAt: serviceInstances.endsAt,
|
||||
callTime: slots.callTime,
|
||||
location: services.location,
|
||||
instanceStatus: serviceInstances.status,
|
||||
isTraineeSlot: slots.isTraineeSlot,
|
||||
};
|
||||
}
|
||||
|
||||
function toServe(row: {
|
||||
assignmentId: string;
|
||||
slotId: string;
|
||||
instanceId: string;
|
||||
roleName: string;
|
||||
serviceName: string;
|
||||
status: string;
|
||||
occursOn: Date | null;
|
||||
startsAt: Date | null;
|
||||
endsAt: Date | null;
|
||||
callTime: Date | null;
|
||||
location: string | null;
|
||||
instanceStatus: string;
|
||||
isTraineeSlot: boolean;
|
||||
}): ServeRow | null {
|
||||
if (!row.startsAt) return null;
|
||||
return {
|
||||
assignmentId: row.assignmentId,
|
||||
slotId: row.slotId,
|
||||
instanceId: row.instanceId,
|
||||
roleName: row.roleName,
|
||||
serviceName: row.serviceName,
|
||||
status: row.status,
|
||||
occursOn: isoDateUTC(row.occursOn),
|
||||
startsAt: row.startsAt,
|
||||
endsAt: row.endsAt,
|
||||
callTime: row.callTime,
|
||||
location: row.location,
|
||||
instanceStatus: row.instanceStatus,
|
||||
isTraineeSlot: row.isTraineeSlot,
|
||||
};
|
||||
}
|
||||
|
||||
/** The next few services the person is still expected to serve. */
|
||||
export async function upcomingServesForUser(
|
||||
userId: string,
|
||||
limit = 5,
|
||||
): Promise<ServeRow[]> {
|
||||
const rows = await db
|
||||
.select(serveSelect())
|
||||
.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))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, userId),
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENT]),
|
||||
gte(serviceInstances.startsAt, new Date()),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.startsAt), asc(roles.sortOrder))
|
||||
.limit(Math.min(Math.max(limit, 1), 20));
|
||||
|
||||
return rows.map(toServe).filter((row): row is ServeRow => row !== null);
|
||||
}
|
||||
|
||||
/** Recent completed service, newest first. */
|
||||
export async function pastServesForUser(
|
||||
userId: string,
|
||||
limit = 4,
|
||||
): Promise<ServeRow[]> {
|
||||
const rows = await db
|
||||
.select(serveSelect())
|
||||
.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))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, userId),
|
||||
inArray(assignments.status, [...HISTORY_ASSIGNMENT]),
|
||||
lt(serviceInstances.startsAt, new Date()),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(serviceInstances.startsAt))
|
||||
.limit(Math.min(Math.max(limit, 1), 20));
|
||||
|
||||
return rows.map(toServe).filter((row): row is ServeRow => row !== null);
|
||||
}
|
||||
|
||||
/** Active service assignments that overlap an inclusive local-date range. */
|
||||
export async function assignmentsInRangeForUser(
|
||||
userId: string,
|
||||
startsOn: string,
|
||||
endsOn: string,
|
||||
): Promise<ServeRow[]> {
|
||||
const start = new Date(`${startsOn}T00:00:00Z`);
|
||||
const end = new Date(`${endsOn}T00:00:00Z`);
|
||||
const rows = await db
|
||||
.select(serveSelect())
|
||||
.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))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, userId),
|
||||
inArray(assignments.status, [...HISTORY_ASSIGNMENT]),
|
||||
gte(serviceInstances.occursOn, start),
|
||||
lt(serviceInstances.occursOn, new Date(end.getTime() + 86_400_000)),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.startsAt), asc(roles.sortOrder));
|
||||
|
||||
return rows.map(toServe).filter((row): row is ServeRow => row !== null);
|
||||
}
|
||||
|
||||
/** Upcoming one-off events where the person is a photographer or editor. */
|
||||
export async function upcomingEventAssignmentsForUser(userId: string) {
|
||||
return db
|
||||
.select({
|
||||
eventId: events.id,
|
||||
title: events.title,
|
||||
role: eventPhotographers.role,
|
||||
startsAt: events.startsAt,
|
||||
endsAt: events.endsAt,
|
||||
location: events.location,
|
||||
})
|
||||
.from(eventPhotographers)
|
||||
.innerJoin(events, eq(events.id, eventPhotographers.eventId))
|
||||
.where(
|
||||
and(
|
||||
eq(eventPhotographers.userId, userId),
|
||||
gte(events.startsAt, new Date()),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(events.startsAt));
|
||||
}
|
||||
|
||||
export interface TeamBlackoutRow {
|
||||
id: string;
|
||||
userId: string;
|
||||
displayName: string;
|
||||
kind: string;
|
||||
startsOn: string;
|
||||
endsOn: string;
|
||||
reason: string | null;
|
||||
rrule: string | null;
|
||||
}
|
||||
|
||||
/** Managers' view of active blackouts across the team. */
|
||||
export async function activeTeamBlackouts(): Promise<TeamBlackoutRow[]> {
|
||||
return db
|
||||
.select({
|
||||
id: unavailability.id,
|
||||
userId: unavailability.userId,
|
||||
displayName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
kind: unavailability.kind,
|
||||
startsOn: unavailability.startsOn,
|
||||
endsOn: unavailability.endsOn,
|
||||
reason: unavailability.reason,
|
||||
rrule: unavailability.rrule,
|
||||
})
|
||||
.from(unavailability)
|
||||
.innerJoin(users, eq(users.id, unavailability.userId))
|
||||
.where(eq(unavailability.status, "active"))
|
||||
.orderBy(asc(unavailability.startsOn), asc(users.lastName), asc(users.firstName));
|
||||
}
|
||||
|
||||
export interface CalendarFeedAssignment {
|
||||
id: string;
|
||||
title: string;
|
||||
startsAt: Date;
|
||||
endsAt: Date;
|
||||
location: string | null;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/** Everything the personal feed publishes: future service and event assignments. */
|
||||
export async function calendarFeedForUser(
|
||||
userId: string,
|
||||
): Promise<CalendarFeedAssignment[]> {
|
||||
const now = new Date();
|
||||
const servicesRows = await db
|
||||
.select({
|
||||
id: assignments.id,
|
||||
roleName: roles.name,
|
||||
serviceName: services.name,
|
||||
startsAt: serviceInstances.startsAt,
|
||||
endsAt: serviceInstances.endsAt,
|
||||
callTime: slots.callTime,
|
||||
location: services.location,
|
||||
status: assignments.status,
|
||||
})
|
||||
.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))
|
||||
.where(
|
||||
and(
|
||||
eq(assignments.userId, userId),
|
||||
inArray(assignments.status, [...ACTIVE_ASSIGNMENT]),
|
||||
gte(serviceInstances.startsAt, now),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(serviceInstances.startsAt));
|
||||
|
||||
const eventRows = await db
|
||||
.select({
|
||||
id: events.id,
|
||||
title: events.title,
|
||||
role: eventPhotographers.role,
|
||||
startsAt: events.startsAt,
|
||||
endsAt: events.endsAt,
|
||||
location: events.location,
|
||||
})
|
||||
.from(eventPhotographers)
|
||||
.innerJoin(events, eq(events.id, eventPhotographers.eventId))
|
||||
.where(
|
||||
and(
|
||||
eq(eventPhotographers.userId, userId),
|
||||
gte(events.endsAt, now),
|
||||
),
|
||||
)
|
||||
.orderBy(asc(events.startsAt));
|
||||
|
||||
const output: CalendarFeedAssignment[] = [];
|
||||
for (const row of servicesRows) {
|
||||
if (!row.startsAt) continue;
|
||||
const start = row.startsAt;
|
||||
const end = row.endsAt ?? new Date(start.getTime() + 75 * 60_000);
|
||||
const call = row.callTime
|
||||
? ` Call time ${row.callTime.toLocaleTimeString("en-US", {
|
||||
timeZone: CHURCH_TIMEZONE,
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
})}.`
|
||||
: "";
|
||||
output.push({
|
||||
id: `service-${row.id}`,
|
||||
title: `${row.roleName} · ${row.serviceName}`,
|
||||
startsAt: start,
|
||||
endsAt: end,
|
||||
location: row.location,
|
||||
description: `Media team assignment (${row.status}).${call}`,
|
||||
});
|
||||
}
|
||||
for (const row of eventRows) {
|
||||
if (!row.startsAt) continue;
|
||||
const start = row.startsAt;
|
||||
const end = row.endsAt ?? new Date(start.getTime() + 2 * 60 * 60_000);
|
||||
output.push({
|
||||
id: `event-${row.id}-${userId}`,
|
||||
title: `${row.role.replaceAll("_", " ")} · ${row.title}`,
|
||||
startsAt: start,
|
||||
endsAt: end,
|
||||
location: row.location,
|
||||
description: "Media team event coverage.",
|
||||
});
|
||||
}
|
||||
return output.sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime());
|
||||
}
|
||||
|
||||
/** Personal feed token; created lazily the first time the profile is opened. */
|
||||
export async function getOrCreateCalendarFeedToken(userId: string): Promise<string> {
|
||||
const [existing] = await db
|
||||
.select({ token: users.calendarFeedToken })
|
||||
.from(users)
|
||||
.where(eq(users.id, userId))
|
||||
.limit(1);
|
||||
if (existing?.token) return existing.token;
|
||||
|
||||
const token = randomBytes(24).toString("base64url");
|
||||
const [updated] = await db
|
||||
.update(users)
|
||||
.set({ calendarFeedToken: token, updatedAt: new Date() })
|
||||
.where(eq(users.id, userId))
|
||||
.returning({ token: users.calendarFeedToken });
|
||||
return updated?.token ?? token;
|
||||
}
|
||||
|
||||
/** Revoke the old URL and return a fresh one. */
|
||||
export async function rotateCalendarFeedToken(userId: string): Promise<string> {
|
||||
const token = randomBytes(24).toString("base64url");
|
||||
await db
|
||||
.update(users)
|
||||
.set({ calendarFeedToken: token, updatedAt: new Date() })
|
||||
.where(eq(users.id, userId));
|
||||
return token;
|
||||
}
|
||||
|
||||
export async function getCalendarFeedOwner(token: string) {
|
||||
const [row] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
displayName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||
})
|
||||
.from(users)
|
||||
.where(
|
||||
and(
|
||||
eq(users.calendarFeedToken, token),
|
||||
eq(users.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** Manager dashboard date window starts today in the church timezone. */
|
||||
export function todayISO(): string {
|
||||
return dateInTimezone(new Date(), CHURCH_TIMEZONE);
|
||||
}
|
||||
Reference in New Issue
Block a user