feat(media): primary media storage, growth goals, retention and delivery tools
CI / build (push) Has been cancelled

Event photos and videos are now stored only on the NFS/local share named in
Settings -> Media storage. Uploads, photo editing, video processing and the
per-event filing step refuse to run until that share is configured and
writable, so nothing is silently written inside the container. Video
originals, renditions, posters and sidecars share one folder on the share.

Also adds volunteer growth goals with a mentor queue, an admin retention and
storage sweep with a cron entry point, cached gallery thumbnails with
per-folder ZIP downloads, a server-rendered booth-sheet PDF, and in-app
confirm/release for every upcoming assignment.

Service reminders now ignore the one-off event reminder rule, which had been
queueing an extra bogus reminder for each published service.

Generated with Codebuff 🤖
Co-Authored-By: Codebuff <noreply@codebuff.com>
This commit is contained in:
2026-11-20 23:21:34 +00:00
parent cb5976edb2
commit f7a0c8618f
68 changed files with 3237 additions and 297 deletions
+2 -2
View File
@@ -472,8 +472,8 @@ export async function listAssignableUsers(): Promise<AssignableUser[]> {
/**
* 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.
* audit row; the route removes the bytes under `<archive root>/events/<id>`
* after the transaction commits.
*/
export async function deleteEvent(eventId: string) {
return db.transaction(async (tx) => {
+368
View File
@@ -0,0 +1,368 @@
/**
* Growth goals + the mentor queue.
*
* A volunteer asks to grow toward a skill level; a coordinator assigns a
* mentor who is actually mentor-ready for that skill, and the goal advances
* through C6's pure state machine (`nextGoalStatus`). Every move is written
* with its audit row in one transaction, so a goal can never change status
* without a record of who moved it.
*
* Verification of the target level stays in `verifySkillLevel` (C3); achieving
* a goal is a lifecycle step, not a silent level change.
*/
import { and, asc, eq, ne, sql } from "drizzle-orm";
import { alias } from "drizzle-orm/pg-core";
import { db } from "@/db";
import {
auditLog,
growthGoals,
skillCategories,
skills,
userSkills,
users,
type GoalStatus,
type SkillLevel,
} from "@/db/schema";
import { auditRow } from "@/db/audit";
import { levelRank } from "@/domain/assessments";
import {
nextGoalStatus,
validateGrowthGoal,
type GoalAction,
} from "@/domain/growthGoals";
import { isMentorReady } from "@/domain/mentor";
import { uuidv7 } from "@/lib/uuid";
const mentorUsers = alias(users, "goal_mentor");
const TERMINAL_STATUSES: GoalStatus[] = ["achieved", "declined"];
export class GrowthGoalError extends Error {
constructor(
readonly status: number,
message: string,
) {
super(message);
this.name = "GrowthGoalError";
}
}
export interface GrowthGoalRow {
id: string;
userId: string;
userName: string;
email: string;
skillId: string;
skillName: string;
categoryName: string | null;
targetLevel: SkillLevel;
targetDate: string | null;
status: GoalStatus;
mentorUserId: string | null;
mentorName: string | null;
shadowCount: number;
verifiedLevel: SkillLevel;
createdAt: Date;
}
export interface MentorCandidate {
userId: string;
displayName: string;
verifiedLevel: SkillLevel;
}
const goalColumns = {
id: growthGoals.id,
userId: growthGoals.userId,
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
email: users.email,
skillId: growthGoals.skillId,
skillName: skills.name,
categoryName: skillCategories.name,
targetLevel: growthGoals.targetLevel,
targetDate: sql<string | null>`${growthGoals.targetDate}::text`,
status: growthGoals.status,
mentorUserId: growthGoals.mentorUserId,
mentorName: sql<
string | null
>`coalesce(${mentorUsers.displayName}, ${mentorUsers.firstName} || ' ' || ${mentorUsers.lastName})`,
shadowCount: growthGoals.shadowCount,
verifiedLevel: sql<SkillLevel>`coalesce(${userSkills.verifiedLevel}, 'none')`,
createdAt: growthGoals.createdAt,
};
function goalsQuery() {
return db
.select(goalColumns)
.from(growthGoals)
.innerJoin(users, eq(users.id, growthGoals.userId))
.innerJoin(skills, eq(skills.id, growthGoals.skillId))
.leftJoin(skillCategories, eq(skillCategories.id, skills.categoryId))
.leftJoin(mentorUsers, eq(mentorUsers.id, growthGoals.mentorUserId))
.leftJoin(
userSkills,
and(
eq(userSkills.userId, growthGoals.userId),
eq(userSkills.skillId, growthGoals.skillId),
),
);
}
/** One volunteer's goals, open first then newest. */
export async function listGoalsForUser(userId: string): Promise<GrowthGoalRow[]> {
const rows = await goalsQuery()
.where(eq(growthGoals.userId, userId))
.orderBy(asc(growthGoals.createdAt));
return rows.sort((a, b) => {
const aOpen = TERMINAL_STATUSES.includes(a.status) ? 1 : 0;
const bOpen = TERMINAL_STATUSES.includes(b.status) ? 1 : 0;
return aOpen - bOpen;
});
}
/**
* Everything the coordinator/mentor queue needs: goals that are not finished,
* requested first, each with the people who are mentor-ready for its skill.
*/
export async function listGrowthQueue(): Promise<
(GrowthGoalRow & { mentorCandidates: MentorCandidate[] })[]
> {
const rows = await goalsQuery()
.where(and(ne(growthGoals.status, "achieved"), ne(growthGoals.status, "declined")))
.orderBy(asc(growthGoals.createdAt));
const bySkill = new Map<string, MentorCandidate[]>();
for (const skillId of new Set(rows.map((row) => row.skillId))) {
bySkill.set(skillId, await listMentorCandidates(skillId));
}
return rows
.sort((a, b) => {
const order: Record<string, number> = {
requested: 0,
mentor_assigned: 1,
in_progress: 2,
paused: 3,
};
return (order[a.status] ?? 9) - (order[b.status] ?? 9);
})
.map((row) => ({ ...row, mentorCandidates: bySkill.get(row.skillId) ?? [] }));
}
/**
* People who satisfy C5's rule for the skill: verified at or above the skill's
* `mentor_min_level`, opted in, and approved by an admin.
*/
export async function listMentorCandidates(
skillId: string,
): Promise<MentorCandidate[]> {
const [skill] = await db
.select({ mentorMinLevel: skills.mentorMinLevel })
.from(skills)
.where(eq(skills.id, skillId))
.limit(1);
if (!skill) return [];
const rows = await db
.select({
userId: userSkills.userId,
displayName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
verifiedLevel: userSkills.verifiedLevel,
mentorOptIn: userSkills.mentorOptIn,
mentorApprovedAt: userSkills.mentorApprovedAt,
})
.from(userSkills)
.innerJoin(users, eq(users.id, userSkills.userId))
.where(
and(
eq(userSkills.skillId, skillId),
eq(users.status, "active"),
eq(userSkills.mentorOptIn, true),
),
)
.orderBy(asc(users.lastName), asc(users.firstName));
return rows
.filter((row) =>
isMentorReady({
verifiedLevel: row.verifiedLevel,
mentorMinLevel: skill.mentorMinLevel,
mentorOptIn: row.mentorOptIn,
adminApproved: row.mentorApprovedAt !== null,
}),
)
.map((row) => ({
userId: row.userId,
displayName: row.displayName,
verifiedLevel: row.verifiedLevel,
}));
}
/** Volunteer-initiated request. One open goal per skill, and not for a level already held. */
export async function createGrowthGoal(input: {
userId: string;
skillId: string;
targetLevel: SkillLevel;
targetDate?: string | null;
}): Promise<{ id: string }> {
const problems = validateGrowthGoal({ targetLevel: input.targetLevel });
if (problems.length > 0) {
throw new GrowthGoalError(400, problems.join("; "));
}
const [skill] = await db
.select({ id: skills.id })
.from(skills)
.where(eq(skills.id, input.skillId))
.limit(1);
if (!skill) throw new GrowthGoalError(404, "unknown skill");
const [current] = await db
.select({ verifiedLevel: userSkills.verifiedLevel })
.from(userSkills)
.where(
and(
eq(userSkills.userId, input.userId),
eq(userSkills.skillId, input.skillId),
),
)
.limit(1);
const held = current?.verifiedLevel ?? "none";
if (levelRank(input.targetLevel) <= levelRank(held)) {
throw new GrowthGoalError(
409,
`you are already verified at ${held} — pick a higher target`,
);
}
const id = uuidv7();
try {
await db.insert(growthGoals).values({
id,
userId: input.userId,
skillId: input.skillId,
targetLevel: input.targetLevel,
targetDate: input.targetDate
? new Date(`${input.targetDate}T00:00:00Z`)
: null,
status: "requested",
createdBy: input.userId,
});
} catch (err) {
if (sqlState(err) === "23505") {
throw new GrowthGoalError(409, "you already have a goal for this skill");
}
if (sqlState(err) === "23503") {
throw new GrowthGoalError(400, "unknown skill");
}
throw err;
}
return { id };
}
/**
* Move one goal. `assignMentor` requires a mentor who is mentor-ready for the
* goal's skill; every other step is the pure C6 machine.
*/
export async function advanceGrowthGoal(input: {
goalId: string;
action: GoalAction;
actorId: string;
mentorUserId?: string | null;
}): Promise<{ status: GoalStatus; mentorUserId: string | null }> {
const [goal] = await db
.select({
id: growthGoals.id,
status: growthGoals.status,
skillId: growthGoals.skillId,
mentorUserId: growthGoals.mentorUserId,
mentorMinLevel: skills.mentorMinLevel,
})
.from(growthGoals)
.innerJoin(skills, eq(skills.id, growthGoals.skillId))
.where(eq(growthGoals.id, input.goalId))
.limit(1);
if (!goal) throw new GrowthGoalError(404, "growth goal not found");
const next = nextGoalStatus(goal.status, input.action);
if (!next) {
throw new GrowthGoalError(
409,
`cannot ${input.action.replace(/([A-Z])/g, " $1").toLowerCase()} a goal that is ${goal.status.replaceAll("_", " ")}`,
);
}
let mentorUserId = goal.mentorUserId;
if (input.action === "assignMentor") {
const candidateId = input.mentorUserId?.trim();
if (!candidateId) {
throw new GrowthGoalError(400, "choose a mentor");
}
const [candidate] = await db
.select({
verifiedLevel: userSkills.verifiedLevel,
mentorOptIn: userSkills.mentorOptIn,
mentorApprovedAt: userSkills.mentorApprovedAt,
})
.from(userSkills)
.where(
and(
eq(userSkills.userId, candidateId),
eq(userSkills.skillId, goal.skillId),
),
)
.limit(1);
if (
!candidate ||
!isMentorReady({
verifiedLevel: candidate.verifiedLevel,
mentorMinLevel: goal.mentorMinLevel,
mentorOptIn: candidate.mentorOptIn,
adminApproved: candidate.mentorApprovedAt !== null,
})
) {
throw new GrowthGoalError(
400,
"that person is not a mentor for this skill (level, opt-in and approval are all required)",
);
}
mentorUserId = candidateId;
}
const now = new Date();
await db.transaction(async (tx) => {
await tx
.update(growthGoals)
.set({
status: next,
...(input.action === "assignMentor" ? { mentorUserId } : {}),
...(input.action === "progressShadow"
? { shadowCount: sql`${growthGoals.shadowCount} + 1` }
: {}),
})
.where(eq(growthGoals.id, input.goalId));
await tx.insert(auditLog).values(
auditRow({
actorId: input.actorId,
action: `growth_goal.${input.action}`,
entityType: "growth_goal",
entityId: input.goalId,
before: { status: goal.status },
after: { status: next, mentorUserId },
now,
}),
);
});
return { status: next, mentorUserId };
}
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;
}
+5 -1
View File
@@ -127,7 +127,11 @@ export async function enqueueRemindersForInstance(
active: notificationRules.active,
appliesToServiceId: notificationRules.appliesToServiceId,
})
.from(notificationRules);
.from(notificationRules)
// Only assignment rules shape a service reminder. `event.reminder` belongs
// to the one-off event cron; applying it here sent volunteers an extra
// "event" reminder for every published Sunday.
.where(eq(notificationRules.event, "assignment.created"));
// Service scoping: null means every service; otherwise it must match.
const applicable = rules
.filter(
+300
View File
@@ -0,0 +1,300 @@
/**
* Retention: report what is growing and prune what is safe to delete.
*
* Three things accumulate without bound: the notification outbox, the
* single-use token tables, and upload bytes whose row was deleted (an orphan).
* Event photos and videos are owned by their event and never swept here — they
* are reported so the admin can see the real storage picture.
*
* Orphans are only files at the top level of `UPLOAD_DIR` (training
* attachments). Event photos and videos live in subdirectories and are left
* alone, so a bad sweep cannot take a whole event with it.
*/
import { and, inArray, lt, notInArray, sql } from "drizzle-orm";
import { readdir, stat, unlink } from "node:fs/promises";
import path from "node:path";
import { db } from "@/db";
import {
auditLog,
eventPhotos,
eventVideos,
notifications,
trainingResources,
usedMagicTokens,
usedTokens,
} from "@/db/schema";
import {
RETENTION_DEFAULTS,
formatBytes,
isOrphanCandidate,
retentionCutoff,
} from "@/lib/retention";
import { UPLOAD_DIR, uploadPath } from "@/lib/uploads";
const LIVE_NOTIFICATION_STATUSES = ["queued", "sending"] as const;
export interface RetentionSummary {
notifications: {
total: number;
live: number;
terminal: number;
prunable: number;
};
tokens: { used: number; magic: number; prunable: number };
auditLog: number;
training: { files: number; bytes: number };
eventPhotos: { files: number; bytes: number };
eventVideos: { files: number; bytes: number };
orphanFiles: { files: number; bytes: number };
thresholds: { notificationDays: number; tokenDays: number };
}
export interface RetentionSweepResult {
notifications: number;
tokens: number;
magicTokens: number;
orphanFiles: number;
orphanBytes: number;
}
function countRows() {
return sql<number>`count(*)::int`;
}
/** Bytes are summed as float8 so a big library stays a JS number. */
function byteSum(column: unknown) {
return sql<number>`coalesce(sum(${column})::float8, 0)`;
}
async function uploadTopLevel(): Promise<
{ name: string; bytes: number; modifiedAt: Date }[]
> {
let entries;
try {
entries = await readdir(UPLOAD_DIR, { withFileTypes: true });
} catch {
return [];
}
const files: { name: string; bytes: number; modifiedAt: Date }[] = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
try {
const info = await stat(path.join(UPLOAD_DIR, entry.name));
files.push({
name: entry.name,
bytes: info.size,
modifiedAt: info.mtime,
});
} catch {
// racing a delete — ignore
}
}
return files;
}
async function referencedTrainingNames(): Promise<Set<string>> {
const rows = await db
.select({ storedName: trainingResources.storedName })
.from(trainingResources);
return new Set(rows.map((row) => path.basename(row.storedName)));
}
async function findOrphanTrainingFiles(
now: Date,
): Promise<{ name: string; bytes: number }[]> {
const [files, referenced] = await Promise.all([
uploadTopLevel(),
referencedTrainingNames(),
]);
return files
.filter((file) => !referenced.has(file.name))
.filter((file) => isOrphanCandidate(file.modifiedAt, now))
.map((file) => ({ name: file.name, bytes: file.bytes }));
}
export async function retentionSummary(
now = new Date(),
): Promise<RetentionSummary> {
const notificationDays = RETENTION_DEFAULTS.notificationDays;
const tokenDays = RETENTION_DEFAULTS.tokenDays;
const notificationCutoff = retentionCutoff(now, notificationDays);
const tokenCutoff = retentionCutoff(now, tokenDays);
const [
notificationTotal,
notificationLive,
notificationPrunable,
usedTokenTotal,
usedTokenPrunable,
magicTokenTotal,
magicTokenPrunable,
auditTotal,
training,
photos,
videos,
orphans,
] = await Promise.all([
db
.select({ n: countRows() })
.from(notifications)
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(notifications)
.where(inArray(notifications.status, [...LIVE_NOTIFICATION_STATUSES]))
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(notifications)
.where(
and(
notInArray(notifications.status, [...LIVE_NOTIFICATION_STATUSES]),
lt(notifications.scheduledFor, notificationCutoff),
),
)
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(usedTokens)
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(usedTokens)
.where(lt(usedTokens.usedAt, tokenCutoff))
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(usedMagicTokens)
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(usedMagicTokens)
.where(lt(usedMagicTokens.usedAt, tokenCutoff))
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({ n: countRows() })
.from(auditLog)
.then((rows) => Number(rows[0]?.n ?? 0)),
db
.select({
n: sql<number>`count(*)::int`,
bytes: byteSum(trainingResources.sizeBytes),
})
.from(trainingResources)
.then((rows) => ({
files: Number(rows[0]?.n ?? 0),
bytes: Number(rows[0]?.bytes ?? 0),
})),
db
.select({
n: sql<number>`count(*)::int`,
bytes: byteSum(eventPhotos.sizeBytes),
})
.from(eventPhotos)
.then((rows) => ({
files: Number(rows[0]?.n ?? 0),
bytes: Number(rows[0]?.bytes ?? 0),
})),
db
.select({
n: sql<number>`count(*)::int`,
bytes: byteSum(eventVideos.sizeBytes),
})
.from(eventVideos)
.then((rows) => ({
files: Number(rows[0]?.n ?? 0),
bytes: Number(rows[0]?.bytes ?? 0),
})),
findOrphanTrainingFiles(now),
]);
return {
notifications: {
total: notificationTotal,
live: notificationLive,
terminal: notificationTotal - notificationLive,
prunable: notificationPrunable,
},
tokens: {
used: usedTokenTotal,
magic: magicTokenTotal,
prunable: usedTokenPrunable + magicTokenPrunable,
},
auditLog: auditTotal,
training,
eventPhotos: photos,
eventVideos: videos,
orphanFiles: {
files: orphans.length,
bytes: orphans.reduce((sum, file) => sum + file.bytes, 0),
},
thresholds: { notificationDays, tokenDays },
};
}
/**
* Apply both windows and sweep orphan training bytes. Safe to run repeatedly:
* every step only removes rows/files already past the cutoff.
*/
export async function pruneRetention(
input: { notificationDays?: number; tokenDays?: number } = {},
now = new Date(),
): Promise<RetentionSweepResult> {
const notificationDays =
input.notificationDays ?? RETENTION_DEFAULTS.notificationDays;
const tokenDays = input.tokenDays ?? RETENTION_DEFAULTS.tokenDays;
const tokenCutoff = retentionCutoff(now, tokenDays);
const deletedNotifications = await db
.delete(notifications)
.where(
and(
notInArray(notifications.status, [...LIVE_NOTIFICATION_STATUSES]),
lt(
notifications.scheduledFor,
retentionCutoff(now, notificationDays),
),
),
)
.returning({ id: notifications.id });
const deletedTokens = await db
.delete(usedTokens)
.where(lt(usedTokens.usedAt, tokenCutoff))
.returning({ jti: usedTokens.jti });
const deletedMagic = await db
.delete(usedMagicTokens)
.where(lt(usedMagicTokens.usedAt, tokenCutoff))
.returning({ jti: usedMagicTokens.jti });
const orphans = await findOrphanTrainingFiles(now);
let orphanBytes = 0;
let orphanFiles = 0;
for (const file of orphans) {
try {
await unlink(uploadPath(file.name));
orphanFiles += 1;
orphanBytes += file.bytes;
} catch (error) {
console.warn(`[retention] could not remove orphan ${file.name}`, error);
}
}
return {
notifications: deletedNotifications.length,
tokens: deletedTokens.length,
magicTokens: deletedMagic.length,
orphanFiles,
orphanBytes,
};
}
export function sweepSummaryText(result: RetentionSweepResult): string {
return [
`${result.notifications} notification${result.notifications === 1 ? "" : "s"}`,
`${result.tokens + result.magicTokens} token${result.tokens + result.magicTokens === 1 ? "" : "s"}`,
`${result.orphanFiles} orphan file${result.orphanFiles === 1 ? "" : "s"} (${formatBytes(result.orphanBytes)})`,
].join(", ");
}
+4 -4
View File
@@ -1016,8 +1016,8 @@ export const eventFolders = pgTable(
);
/**
* 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
* Photo metadata. Bytes live under `<archive root>/events/<eventId>/` on the
* configured NFS/local share; 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.
*/
@@ -1079,8 +1079,8 @@ 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`.
* Event video metadata. The camera original, browser derivatives and poster
* all live in one folder on the configured NFS/local media storage share.
* `trim_start_ms` / `trim_end_ms` are a non-destructive recipe applied when
* the web MP4 is rendered, so the original is never changed.
*/
+2 -2
View File
@@ -1,5 +1,5 @@
/**
* Runtime archive destination settings.
* Runtime media-storage settings: where original photos and videos live.
*
* 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
@@ -124,7 +124,7 @@ export async function checkArchiveDestination(
const detail = error instanceof Error ? error.message : "not accessible";
return {
ready: false,
message: `Archive destination is not available: ${detail}`,
message: `Media storage is not available: ${detail}`,
freeBytes: null,
};
}
+4 -4
View File
@@ -1,10 +1,10 @@
/**
* 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.
* Video bytes are never stored in Postgres: `originalStoredName`,
* `webStoredName` and `posterStoredName` all point into the video's folder on
* the configured media storage share. 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";