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
+82 -11
View File
@@ -40,6 +40,16 @@ import {
type PositionSummary,
type RequirementDraft,
} from "@/components/app/admin/positions-panel";
import { listGrowthQueue } from "@/db/growthGoals";
import { retentionSummary } from "@/db/retention";
import {
RetentionPanel,
type RetentionSummaryView,
} from "@/components/app/admin/retention-panel";
import {
MentorQueuePanel,
type QueueGoalView,
} from "@/components/app/growth/mentor-queue-panel";
export const metadata = { title: "Admin" };
@@ -70,17 +80,29 @@ export default async function AdminPage() {
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
if (!hasPermission(role, "admin.settings")) redirect("/schedule");
const [users, rules, log, services, matrix, positions, skillRows, emailSettings] =
await Promise.all([
listUsersForAdmin(),
listRules(),
listNotifications({ limit: 25 }),
listServices({ active: false }),
listSkillsMatrix(),
listPositions({ active: false }),
listSkills({ active: true }),
getEmailSettings(),
]);
const [
users,
rules,
log,
services,
matrix,
positions,
skillRows,
emailSettings,
growthQueue,
retention,
] = await Promise.all([
listUsersForAdmin(),
listRules(),
listNotifications({ limit: 25 }),
listServices({ active: false }),
listSkillsMatrix(),
listPositions({ active: false }),
listSkills({ active: true }),
getEmailSettings(),
listGrowthQueue(),
retentionSummary(),
]);
const requirementSets = await Promise.all(
positions.map((position) => getPositionSkills(position.id)),
@@ -107,6 +129,27 @@ export default async function AdminPage() {
lastServedOn: row.lastServedOn ?? null,
}));
const retentionView: RetentionSummaryView = retention;
const queueGoals: QueueGoalView[] = growthQueue.map((goal) => ({
id: goal.id,
userName: goal.userName,
email: goal.email,
skillName: goal.skillName,
targetLevel: goal.targetLevel,
targetDate: goal.targetDate,
status: goal.status,
mentorUserId: goal.mentorUserId,
mentorName: goal.mentorName,
shadowCount: goal.shadowCount,
verifiedLevel: goal.verifiedLevel,
mentorCandidates: goal.mentorCandidates.map((candidate) => ({
userId: candidate.userId,
displayName: candidate.displayName,
verifiedLevel: candidate.verifiedLevel,
})),
}));
const managedUsers: ManagedUser[] = users.map((user) => ({
id: user.id,
email: user.email,
@@ -186,6 +229,20 @@ export default async function AdminPage() {
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Mentor queue</CardTitle>
<CardDescription>
Volunteers asking to grow. Assign a mentor who is already
mentor-ready for that skill, then log shadows and sign the goal off.
Levels themselves are verified in the matrix above.
</CardDescription>
</CardHeader>
<CardContent>
<MentorQueuePanel goals={queueGoals} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Positions &amp; requirements</CardTitle>
@@ -259,6 +316,20 @@ export default async function AdminPage() {
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Retention &amp; storage</CardTitle>
<CardDescription>
What the database and the upload volume are holding, and what the
next sweep would remove. Sent mail and used tokens past their window
are deleted; queued mail never is.
</CardDescription>
</CardHeader>
<CardContent>
<RetentionPanel summary={retentionView} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Backup &amp; restore</CardTitle>
@@ -1,6 +1,6 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { ArrowLeft, Download } from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getFolderDetail } from "@/db/events";
@@ -8,8 +8,10 @@ import {
isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { mediaStorage } from "@/lib/media-storage";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
PhotoGallery,
type GalleryPhoto,
@@ -48,6 +50,10 @@ export default async function EventFolderPage({
const detail = await getFolderDetail(folderId, user.id, user.systemRole);
if (!detail || detail.event.id !== id) notFound();
// Photos live only on the configured media storage share, so the uploader and
// editor stay disabled (with the reason) until that destination is ready.
const storage = await mediaStorage();
const photos: GalleryPhoto[] = detail.photos.map((photo) => ({
id: photo.id,
filename: photo.filename,
@@ -84,9 +90,21 @@ export default async function EventFolderPage({
· {sizeLabel(detail.folder.totalBytes)}
</p>
</div>
<Badge variant="secondary">
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
</Badge>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="secondary">
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
</Badge>
{detail.photos.length > 0 && (
<Button asChild variant="outline" size="sm">
<a
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}`}
>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download folder ({detail.photos.length})
</a>
</Button>
)}
</div>
</div>
<PhotoGallery
@@ -96,6 +114,12 @@ export default async function EventFolderPage({
canContribute={detail.canContribute}
canManage={detail.canManage}
currentUserId={user.id}
storageReady={storage.ok}
storageMessage={
storage.ok
? ""
: storage.message
}
/>
</div>
);
+16 -15
View File
@@ -6,10 +6,8 @@ import type { SystemRole } from "@/auth/roles";
import { getEventDetail, listAssignableUsers } from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { formatVideoDuration } from "@/lib/event-videos";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@@ -71,7 +69,7 @@ export default async function EventDetailPage({
const users = event.canManage ? await listAssignableUsers() : [];
const archiveSettings = await getStorageSettings();
const archiveStatus = await checkArchiveDestination(archiveSettings);
const archiveStatus = await mediaStorage();
const videos = await listEventVideos(event.event.id);
const photographers: EventPhotographer[] = event.event.photographers.map(
(person) => ({
@@ -109,12 +107,12 @@ export default async function EventDetailPage({
</a>
</Button>
)}
{event.canManage && archiveStatus.ready && (
{event.canManage && archiveStatus.ok && (
<ArchiveEventButton
eventId={event.event.id}
title={event.event.title}
photoCount={event.event.photoCount}
archivePath={archiveSettings.archivePath}
archivePath={`${archiveSettings.archivePath}/${archiveSettings.archiveFolder}`}
/>
)}
{event.canManage && (
@@ -139,13 +137,16 @@ export default async function EventDetailPage({
{event.event.description}
</p>
)}
{event.canManage && !archiveStatus.ready && (
<p className="max-w-3xl text-xs text-muted-foreground">
NFS archive is not ready. {archiveStatus.message}{" "}
<Link href="/settings" className="font-medium text-primary underline">
Configure archive
</Link>{" "}
before deleting finished events.
{!archiveStatus.ok && (
<p
role="alert"
className="max-w-3xl rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-900 dark:text-amber-200"
>
Photo and video uploads are disabled. {archiveStatus.message}{" "}
<Link href="/settings" className="font-medium underline">
Configure media storage
</Link>
.
</p>
)}
</div>
@@ -307,7 +308,7 @@ export default async function EventDetailPage({
<VideoUploadForm
events={[{ id: event.event.id, title: event.event.title }]}
canManage={event.canManage}
archiveReady={archiveStatus.ready}
archiveReady={archiveStatus.ok}
defaultEventId={event.event.id}
compact
/>
+19 -7
View File
@@ -203,13 +203,25 @@ export default async function HomePage() {
{serve.callTime ? ` · call ${time(serve.callTime)}` : ""}
</p>
</div>
<Badge
variant={
serve.status === "confirmed" ? "default" : "secondary"
}
>
{serve.status}
</Badge>
<div className="flex flex-col items-end gap-1">
<Badge
variant={
serve.status === "confirmed" ? "default" : "secondary"
}
>
{serve.status}
</Badge>
{pendingCoverage.has(serve.assignmentId) && (
<span className="text-[11px] text-muted-foreground">
Coverage requested
</span>
)}
<AssignmentActions
assignmentId={serve.assignmentId}
status={serve.status}
compact
/>
</div>
</li>
))}
</ul>
+57 -8
View File
@@ -3,6 +3,7 @@ import {
Clock3,
FileImage,
Film,
HardDrive,
Image as ImageIcon,
Play,
} from "lucide-react";
@@ -12,10 +13,8 @@ import type { SystemRole } from "@/auth/roles";
import { listEventsForUser } from "@/db/events";
import { listMediaPhotosForEvents } from "@/db/media";
import { listEventVideosForEvents } from "@/db/videos";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import { formatVideoDuration } from "@/lib/event-videos";
import { isBrowserRenderablePhoto } from "@/lib/event-photos";
import { mediaOrigin } from "@/lib/media-url";
@@ -64,7 +63,19 @@ export default async function MediaPage() {
listMediaPhotosForEvents(eventIds),
getStorageSettings(),
]);
const archiveStatus = await checkArchiveDestination(storage);
const archiveStatus = await mediaStorage();
const archiveUsedBytes =
archiveStatus.ok &&
archiveStatus.totalBytes !== null &&
archiveStatus.freeBytes !== null
? Math.max(0, archiveStatus.totalBytes - archiveStatus.freeBytes)
: null;
const archiveUsedPercent =
archiveUsedBytes !== null &&
archiveStatus.ok &&
archiveStatus.totalBytes
? Math.min(100, Math.round((archiveUsedBytes / archiveStatus.totalBytes) * 100))
: null;
const canManage = hasPermission(role, "schedule.publish");
const videoCards = videos.map((video) => videoView(video, origin));
@@ -79,6 +90,44 @@ export default async function MediaPage() {
</p>
</div>
{archiveStatus.ok && (
<section className="space-y-2 rounded-lg border border-border bg-muted/30 p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="flex items-center gap-1.5 text-sm font-medium">
<HardDrive className="h-4 w-4" aria-hidden="true" />
Original media storage
</p>
<p className="text-xs text-muted-foreground">
{archiveStatus.settings.nfsShare} ·{" "}
{archiveStatus.settings.archiveFolder}
</p>
</div>
{archiveUsedBytes !== null && archiveStatus.totalBytes !== null ? (
<>
<div
className="h-2 overflow-hidden rounded-full bg-muted"
role="img"
aria-label={`Media storage ${archiveUsedPercent}% used`}
>
<div
className="h-full bg-primary"
style={{ width: `${archiveUsedPercent ?? 0}%` }}
/>
</div>
<p className="text-xs text-muted-foreground">
{bytesLabel(archiveUsedBytes)} used of{" "}
{bytesLabel(archiveStatus.totalBytes)} ·{" "}
{bytesLabel(archiveStatus.freeBytes ?? 0)} free
</p>
</>
) : (
<p className="text-xs text-muted-foreground">
Free space could not be read from this filesystem.
</p>
)}
</section>
)}
<section className="space-y-3">
<div className="flex flex-wrap items-end justify-between gap-2">
<div>
@@ -87,8 +136,8 @@ export default async function MediaPage() {
Videos
</h2>
<p className="text-xs text-muted-foreground">
Camera originals live on the NFS archive; playback uses a generated
MP4.
Camera originals are stored on the media storage share; playback
uses a generated MP4.
</p>
</div>
<span className="text-xs text-muted-foreground">
@@ -102,7 +151,7 @@ export default async function MediaPage() {
title: event.title,
}))}
canManage={canManage}
archiveReady={archiveStatus.ready}
archiveReady={archiveStatus.ok}
/>
{videoCards.length === 0 ? (
+43 -1
View File
@@ -8,6 +8,16 @@ import { listSkills } from "@/db/positions";
import { getOrCreateCalendarFeedToken } from "@/db/volunteer";
import { mediaOrigin } from "@/lib/media-url";
import { ProfilePanel } from "@/components/app/profile-panel";
import { listGoalsForUser } from "@/db/growthGoals";
import { SKILL_LEVELS } from "@/db/schema";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { GrowthGoalsPanel } from "@/components/app/growth/growth-goals-panel";
export const metadata = { title: "My profile" };
export const dynamic = "force-dynamic";
@@ -17,12 +27,13 @@ export default async function ProfilePage() {
const user = session?.user as { id?: string } | undefined;
if (!user?.id) redirect("/login");
const [profile, skillRows, allSkills, token, origin] = await Promise.all([
const [profile, skillRows, allSkills, token, origin, goals] = await Promise.all([
getProfile(user.id),
getUserSkills(user.id),
listSkills({ active: true }),
getOrCreateCalendarFeedToken(user.id),
mediaOrigin(),
listGoalsForUser(user.id),
]);
const bySkill = new Map(skillRows.map((row) => [row.skillId, row]));
@@ -68,6 +79,37 @@ export default async function ProfilePage() {
}))}
feedUrl={`${origin}/api/calendar/${token}`}
/>
<Card>
<CardHeader>
<CardTitle className="text-base">Growth goals</CardTitle>
<CardDescription>
Ask to grow toward a level on a skill. A coordinator pairs you with
a mentor who is signed off for that skill; the verified level itself
still changes in the skills matrix.
</CardDescription>
</CardHeader>
<CardContent>
<GrowthGoalsPanel
goals={goals.map((goal) => ({
id: goal.id,
skillName: goal.skillName,
targetLevel: goal.targetLevel,
targetDate: goal.targetDate,
status: goal.status,
mentorName: goal.mentorName,
shadowCount: goal.shadowCount,
verifiedLevel: goal.verifiedLevel,
}))}
skills={allSkills.map((skill) => ({
id: skill.id,
name: skill.name,
verifiedLevel: bySkill.get(skill.id)?.verifiedLevel ?? "none",
}))}
levels={SKILL_LEVELS}
/>
</CardContent>
</Card>
</div>
);
}
+18 -1
View File
@@ -1,4 +1,6 @@
import { notFound } from "next/navigation";
import { Download } from "lucide-react";
import { Button } from "@/components/ui/button";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
@@ -24,5 +26,20 @@ export default async function RunSheetPage({
const canEdit = hasPermission(user.systemRole, "schedule.publish");
return <RunSheetEditor data={data} canEdit={canEdit} />;
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="text-sm text-muted-foreground">
{data.instance.serviceName} · {data.instance.status}
</p>
<Button asChild variant="outline" size="sm">
<a href={`/api/run-sheet/${instanceId}/pdf`}>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download booth sheet PDF
</a>
</Button>
</div>
<RunSheetEditor data={data} canEdit={canEdit} />
</div>
);
}
+14 -7
View File
@@ -4,10 +4,8 @@ import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { getEmailSettings } from "@/db/settings";
import { getUserSecurity } from "@/db/users";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import { CHURCH_TIMEZONE } from "@/lib/tz";
import {
Card,
@@ -34,9 +32,18 @@ export default async function SettingsPage() {
const security = userId ? await getUserSecurity(userId) : null;
const isAdmin = hasPermission(role, "admin.settings");
const emailSettings = isAdmin ? await getEmailSettings() : null;
// Keep the form populated even while the destination is unusable, so an
// admin can see and fix what is saved.
const storageSettings = isAdmin ? await getStorageSettings() : null;
const storageStatus = storageSettings
? await checkArchiveDestination(storageSettings)
const media = isAdmin ? await mediaStorage() : null;
const storageStatus = media
? {
ready: media.ok,
message: media.ok
? `Event photos and videos are stored in ${media.root}.`
: media.message,
freeBytes: media.ok ? media.freeBytes : null,
}
: null;
const emailTransport = emailSettings?.smtpConfigured
? "Gmail (SMTP)"
@@ -142,7 +149,7 @@ export default async function SettingsPage() {
{isAdmin && storageSettings && storageStatus && (
<Card>
<CardHeader>
<CardTitle className="text-lg">Media archive (NFS)</CardTitle>
<CardTitle className="text-lg">Media storage (NFS / local path)</CardTitle>
<CardDescription>
Mount an NFS export into this container. Finished event photos are
archived here, and every uploaded video keeps its camera original
+1 -1
View File
@@ -606,7 +606,7 @@ export default function AdminGuidePage() {
<GuideFigure
src="/training/screens/admin-settings.png"
alt="Settings page with church details and admin-only email and storage cards"
caption="Settings: deployment facts and the archive destination, visible in full only to admins."
caption="Settings: deployment facts and the media storage destination, visible in full only to admins."
/>
</GuideSection>
+32
View File
@@ -0,0 +1,32 @@
import type { NextRequest } from "next/server";
import { gateCron } from "@/auth/api";
import { pruneRetention } from "@/db/retention";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* GET /api/dev/cron/retention — monthly housekeeping (cron `0 4 1 * *`).
*
* Deletes terminal notification rows and consumed tokens past their window and
* sweeps orphan training attachments. Auth: `Authorization: Bearer
* $CRON_SECRET` (or `?secret=`) for a scheduler, otherwise a coordinator
* session. Running it twice is harmless.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateCron(req);
if (gate instanceof Response) return gate;
try {
const removed = await pruneRetention();
return new Response(JSON.stringify({ ok: true, removed }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (error) {
const message = error instanceof Error ? error.message : "retention failed";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+50
View File
@@ -0,0 +1,50 @@
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { pruneRetention, retentionSummary } from "@/db/retention";
import { errorResponse, jsonResponse } from "@/lib/http";
import { RETENTION_LIMITS } from "@/lib/retention";
const sweepSchema = z.object({
notificationDays: z
.number()
.int()
.min(RETENTION_LIMITS.minDays)
.max(RETENTION_LIMITS.maxDays)
.optional(),
tokenDays: z
.number()
.int()
.min(RETENTION_LIMITS.minDays)
.max(RETENTION_LIMITS.maxDays)
.optional(),
});
/** GET /api/dev/retention — counts, sizes, and what the next sweep would remove. */
export async function GET() {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
try {
return jsonResponse({ summary: await retentionSummary() });
} catch (error) {
console.error("[retention] summary failed", error);
return errorResponse(500, "could not read retention counts");
}
}
/** POST /api/dev/retention — sweep old mail, tokens and orphan training files. */
export async function POST(req: Request) {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
const parsed = sweepSchema.safeParse(await req.json().catch(() => ({})));
if (!parsed.success) return errorResponse(400, "invalid retention window");
try {
const result = await pruneRetention(parsed.data);
return jsonResponse({ ok: true, removed: result, summary: await retentionSummary() });
} catch (error) {
console.error("[retention] sweep failed", error);
return errorResponse(500, "retention sweep failed");
}
}
+1 -1
View File
@@ -42,7 +42,7 @@ function publicSettings(settings: StorageSettings) {
};
}
/** GET /api/dev/storage — NFS/archive destination and mount readiness. */
/** GET /api/dev/storage — media storage destination and mount readiness. */
export const GET = async () => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
+9 -15
View File
@@ -9,11 +9,8 @@ import {
listEventPhotosForArchive,
} from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { eventVideoUploadDir } from "@/lib/event-videos";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import {
archiveEventPhotos,
EventArchiveError,
@@ -42,14 +39,12 @@ export const POST = async (
return errorResponse(403, "only an event manager may archive this event");
}
// Archiving copies live photos into the dated folder on the same configured
// share; without a named share there is no archive to write to.
const media = await mediaStorage();
if (!media.ok) return errorResponse(409, media.message);
const storage = await getStorageSettings();
const status = await checkArchiveDestination(storage);
if (!status.ready) {
return errorResponse(
409,
`${status.message} Configure the NFS archive in Settings first.`,
);
}
const uploadRoot = media.root;
const photos = await listEventPhotosForArchive(id);
const videos = await listEventVideos(id);
@@ -84,10 +79,9 @@ export const POST = async (
}
try {
await rm(eventPhotoDir(id), { recursive: true, force: true });
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
await rm(eventPhotoDir(uploadRoot, id), { recursive: true, force: true });
} catch (error) {
console.error(`event ${id}: archived but live files remain`, error);
console.error(`event ${id}: archived but live photos remain`, error);
}
await writeAudit(db, {
+21 -5
View File
@@ -11,6 +11,7 @@ import {
photoContentDisposition,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
/**
* GET /api/events/:id/download
@@ -22,7 +23,7 @@ import { errorResponse } from "@/lib/http";
* Anyone assigned to the event (or a manager) can download it.
*/
export const GET = async (
_req: NextRequest,
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
@@ -32,9 +33,17 @@ export const GET = async (
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const photos = await listEventPhotosForArchive(id);
// `?folderId=` narrows the archive to one folder, so a photographer can pull
// just the shots they need without downloading the whole event.
const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null;
const photos = (await listEventPhotosForArchive(id)).filter(
(photo) => !folderId || photo.folderId === folderId,
);
if (photos.length === 0) {
return errorResponse(404, "this event has no photos");
return errorResponse(
404,
folderId ? "this folder has no photos" : "this event has no photos",
);
}
// Originals claim their names first, then generated edits join the same
@@ -71,9 +80,12 @@ export const GET = async (
filename: entry.filename,
})),
);
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const available: { path: string; name: string }[] = [];
for (const entry of entries) {
const filePath = eventPhotoPath(entry.storedName);
const filePath = eventPhotoPath(storage.root, entry.storedName);
try {
const info = await stat(filePath);
if (!info.isFile()) continue;
@@ -111,7 +123,11 @@ export const GET = async (
headers: {
"content-type": "application/zip",
"content-disposition": photoContentDisposition(
eventArchiveFilename(access.event.title),
eventArchiveFilename(
folderId
? `${access.event.title} - ${photos[0].folderName}`
: access.event.title,
),
false,
),
"cache-control": "private, no-store",
@@ -11,6 +11,7 @@ import {
isEditableEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
@@ -52,6 +53,11 @@ export const POST = async (
return errorResponse(415, "this photo format cannot be edited");
}
// The rendered JPEG is written beside the original on the media share.
// Editing must never fall back to container storage.
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const body = (await req.json().catch(() => null)) as
| { adjustments?: unknown }
| null;
@@ -60,7 +66,7 @@ export const POST = async (
return errorResponse(400, "invalid photo adjustments");
}
const sourcePath = eventPhotoPath(access.photo.storedName);
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
try {
const source = await stat(sourcePath);
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
@@ -72,7 +78,7 @@ export const POST = async (
access.eventId,
access.photo.id,
);
const editedPath = eventPhotoPath(editedStoredName);
const editedPath = eventPhotoPath(storage.root, editedStoredName);
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
try {
@@ -14,6 +14,7 @@ import {
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048
@@ -45,10 +46,16 @@ export const GET = async (
return errorResponse(400, "unknown export size");
}
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
let data: Buffer;
try {
if (access.photo.editedStoredName) {
const editedPath = eventPhotoPath(access.photo.editedStoredName);
const editedPath = eventPhotoPath(
storage.root,
access.photo.editedStoredName,
);
const info = await stat(editedPath);
if (!info.isFile()) throw new Error("missing edit");
data = await sharp(editedPath)
@@ -62,7 +69,7 @@ export const GET = async (
.toBuffer();
} else if (access.photo.editJson) {
const rendered = await renderPhotoJpeg({
filePath: eventPhotoPath(access.photo.storedName),
filePath: eventPhotoPath(storage.root, access.photo.storedName),
kind: access.photo.kind,
adjustments: parseStoredPhotoAdjustments(access.photo.editJson),
maxDimension: preset.maxDimension,
@@ -10,6 +10,7 @@ import {
previewStoredNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
@@ -44,7 +45,10 @@ export const GET = async (
return errorResponse(415, "this photo format cannot be previewed in the editor");
}
const sourcePath = eventPhotoPath(access.photo.storedName);
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
try {
const source = await stat(sourcePath);
if (!source.isFile()) return errorResponse(404, "the file is missing from storage");
@@ -53,6 +57,7 @@ export const GET = async (
}
const previewPath = eventPhotoPath(
storage.root,
previewStoredNameForEventPhoto(access.eventId, access.photo.id),
);
@@ -12,6 +12,7 @@ import {
photoContentDisposition,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited]
@@ -47,7 +48,11 @@ export const GET = async (
return errorResponse(404, "this photo has no saved edit");
}
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const filePath = eventPhotoPath(
storage.root,
wantsEdited
? access.photo.editedStoredName!
: access.photo.storedName,
@@ -115,11 +120,16 @@ export const DELETE = async (
}
await deleteEventPhoto(photoId);
await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined);
if (access.photo.editedStoredName) {
await unlink(eventPhotoPath(access.photo.editedStoredName)).catch(
const storage = await mediaStorage();
if (storage.ok) {
await unlink(eventPhotoPath(storage.root, access.photo.storedName)).catch(
() => undefined,
);
if (access.photo.editedStoredName) {
await unlink(
eventPhotoPath(storage.root, access.photo.editedStoredName),
).catch(() => undefined);
}
}
return jsonResponse({ ok: true });
};
@@ -0,0 +1,118 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
import { gateSession } from "@/auth/api";
import { getEventPhotoAccess } from "@/db/events";
import {
eventPhotoPath,
isBrowserRenderablePhoto,
thumbStoredNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
*
* A 640px square-croppable JPEG of the original for the gallery grid. Without
* it a 400-photo event ships hundreds of megabytes of camera originals to a
* phone. Cached on disk (the original never changes) and safe to cache in the
* browser, since the URL is keyed by photo id.
*/
export const GET = async (
_req: NextRequest,
{
params,
}: {
params: Promise<{ id: string; folderId: string; photoId: string }>;
},
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, folderId, photoId } = await params;
const access = await getEventPhotoAccess(photoId, gate.id, gate.systemRole);
if (!access || access.photo.folderId !== folderId || access.eventId !== id) {
return errorResponse(404, "unknown photo");
}
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const thumbPath = eventPhotoPath(
storage.root,
thumbStoredNameForEventPhoto(access.eventId, access.photo.id),
);
try {
const cached = await stat(thumbPath);
if (cached.isFile()) {
return imageResponse(await readFile(thumbPath));
}
} catch {
// not cached yet
}
const sourcePath = eventPhotoPath(storage.root, access.photo.storedName);
try {
const source = await stat(sourcePath);
if (!source.isFile()) {
return errorResponse(404, "the file is missing from storage");
}
} catch {
return errorResponse(404, "the file is missing from storage");
}
let data: Buffer;
try {
if (access.photo.kind === "raw") {
const rendered = await renderPhotoJpeg({
filePath: sourcePath,
kind: "raw",
adjustments: defaultPhotoAdjustments(),
maxDimension: 640,
});
data = rendered.data;
} else if (isBrowserRenderablePhoto(access.photo.filename)) {
data = await sharp(sourcePath, { failOn: "none", limitInputPixels: 500_000_000 })
.autoOrient()
.resize(640, 640, { fit: "inside", withoutEnlargement: true })
.jpeg({ quality: 72 })
.toBuffer();
} else {
return errorResponse(415, "this photo format has no thumbnail");
}
} catch (error) {
if (error instanceof PhotoRenderError) {
return errorResponse(415, error.message);
}
console.warn(`event photo ${photoId}: thumbnail failed`, error);
return errorResponse(500, "could not build a thumbnail");
}
await mkdir(path.dirname(thumbPath), { recursive: true });
const tempPath = `${thumbPath}.${randomUUID()}.tmp`;
try {
await writeFile(tempPath, data);
await rename(tempPath, thumbPath);
} catch (error) {
console.warn(`event photo ${photoId}: thumbnail cache write failed`, error);
}
return imageResponse(data);
};
function imageResponse(data: Buffer): Response {
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": "image/jpeg",
"cache-control": "private, max-age=31536000, immutable",
"x-content-type-options": "nosniff",
},
});
}
@@ -21,6 +21,7 @@ import {
storedNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { mediaStorage } from "@/lib/media-storage";
import { uuidv7 } from "@/lib/uuid";
class PhotoTooLarge extends Error {}
@@ -69,6 +70,11 @@ export const POST = async (
return errorResponse(403, "you are not assigned to this event");
}
// Photos are only ever written to the configured media storage share, so refuse
// before reading a single byte when that destination is not ready.
const storage = await mediaStorage();
if (!storage.ok) return errorResponse(503, storage.message);
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizePhotoFilename(suppliedName);
@@ -88,7 +94,7 @@ export const POST = async (
const photoId = uuidv7();
const storedName = storedNameForEventPhoto(id, photoId, filename);
const destination = eventPhotoPath(storedName);
const destination = eventPhotoPath(storage.root, storedName);
await mkdir(path.dirname(destination), { recursive: true });
const hash = createHash("sha256");
+19 -22
View File
@@ -6,11 +6,9 @@ import { writeAudit } from "@/db/audit";
import { deleteEvent, getEventAccess } from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import { eventPhotoDir } from "@/lib/event-photos";
import {
eventVideoArchiveDir,
eventVideoUploadDir,
} from "@/lib/event-videos";
import { eventVideoArchiveDir } from "@/lib/event-videos";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
@@ -34,30 +32,29 @@ export const DELETE = async (
const deleted = await deleteEvent(id);
if (!deleted) return errorResponse(404, "unknown event");
try {
await rm(eventPhotoDir(id), { recursive: true, force: true });
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
} catch (error) {
console.error(`event ${id}: database deleted but files remain`, error);
const media = await mediaStorage();
if (media.ok) {
try {
await rm(eventPhotoDir(media.root, id), { recursive: true, force: true });
} catch (error) {
console.error(`event ${id}: database deleted but photos remain`, error);
}
}
// Video originals are the largest files; remove each one from the archive
// after the cascade has removed its row, so a deletion cannot orphan GBs.
// Video originals are the largest files; remove the whole event video folder
// on the archive after the cascade has removed the rows, so a deletion cannot
// orphan GBs. Originals and derivatives share one folder per video.
try {
const storage = await getStorageSettings();
for (const video of videos) {
await rm(
eventVideoArchiveDir(
storage.archivePath,
video.archiveFolder,
id,
video.id,
),
{ recursive: true, force: true },
);
const folders = new Set(videos.map((video) => video.archiveFolder));
for (const folder of folders) {
await rm(eventVideoArchiveDir(storage.archivePath, folder, id), {
recursive: true,
force: true,
});
}
} catch (error) {
console.error(`event ${id}: NFS video originals were not removed`, error);
console.error(`event ${id}: NFS video files were not removed`, error);
}
await writeAudit(db, {
@@ -12,7 +12,7 @@ import {
import { errorResponse } from "@/lib/http";
import { parseByteRange } from "@/lib/range";
/** Download the untouched camera original from the NFS archive. */
/** Download the untouched camera original from media storage. */
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
@@ -35,12 +35,12 @@ export const GET = async (
access.video.originalStoredName,
);
} catch {
return errorResponse(404, "the NFS archive is not configured");
return errorResponse(404, "media storage is not configured");
}
const info = await stat(filePath).catch(() => null);
if (!info?.isFile()) {
return errorResponse(404, "the original video is missing from the NFS archive");
return errorResponse(404, "the original video is missing from media storage");
}
const range = parseByteRange(req.headers.get("range"), info.size);
@@ -1,6 +1,5 @@
import { NextRequest } from "next/server";
import { rm } from "node:fs/promises";
import path from "node:path";
import { gateSession } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
@@ -9,11 +8,7 @@ import {
getEventVideoAccess,
} from "@/db/videos";
import { getStorageSettings } from "@/db/storage-settings";
import {
eventVideoArchiveDir,
eventVideoUploadPath,
webStoredNameForEventVideo,
} from "@/lib/event-videos";
import { eventVideoArchiveDir } from "@/lib/event-videos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { videoView } from "@/lib/video-view";
@@ -62,16 +57,7 @@ export const DELETE = async (
const removed = await deleteEventVideo(videoId);
if (!removed) return errorResponse(404, "unknown video");
const derivativeDir = path.dirname(
eventVideoUploadPath(
removed.webStoredName ??
webStoredNameForEventVideo(removed.eventId, removed.id),
),
);
await rm(derivativeDir, { recursive: true, force: true }).catch((error) => {
console.error(`video ${videoId}: derivatives were not removed`, error);
});
// One folder on the share holds the original, renditions, poster and sidecar.
try {
const storage = await getStorageSettings();
await rm(
@@ -84,7 +70,7 @@ export const DELETE = async (
{ recursive: true, force: true },
);
} catch (error) {
console.error(`video ${videoId}: NFS original was not removed`, error);
console.error(`video ${videoId}: NFS files were not removed`, error);
}
await writeAudit(db, {
+5 -12
View File
@@ -6,10 +6,7 @@ import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import { gateSession } from "@/auth/api";
import { getEventAccess } from "@/db/events";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import {
EVENT_VIDEO_VISIBILITIES,
type EventVideoVisibility,
@@ -142,14 +139,10 @@ export const POST = async (
(req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) ||
null;
const storage = await getStorageSettings();
const archiveStatus = await checkArchiveDestination(storage);
if (!archiveStatus.ready) {
return errorResponse(
409,
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
);
}
// Staging chunks also land on the media storage share, never in the container.
const media = await mediaStorage();
if (!media.ok) return errorResponse(409, media.message);
const storage = media.settings;
// Stage under a client-scoped name, never under a final video id. The final
// id is generated by the server when the last chunk arrives, so a caller
+7 -10
View File
@@ -8,7 +8,7 @@ import { pipeline } from "node:stream/promises";
import { gateSession } from "@/auth/api";
import { getEventAccess } from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { checkArchiveDestination, getStorageSettings } from "@/db/storage-settings";
import { mediaStorage } from "@/lib/media-storage";
import {
MAX_EVENT_VIDEO_BYTES,
eventVideoArchivePath,
@@ -30,7 +30,7 @@ class VideoTooLarge extends Error {}
/**
* POST /api/events/:id/videos?name=service.mp4&title=Sunday&visibility=team
*
* Raw request body. The camera original streams straight to the NFS archive and
* Raw request body. The camera original streams straight to media storage and
* is hashed while it writes, so a 4 GB file never sits in memory. The stored
* row starts as `processing`; FFmpeg creates the web MP4/poster in the
* background and the browser polls the video endpoint for readiness.
@@ -89,14 +89,11 @@ export const POST = async (
}
if (!req.body) return errorResponse(400, "a video body is required");
const storage = await getStorageSettings();
const archiveStatus = await checkArchiveDestination(storage);
if (!archiveStatus.ready) {
return errorResponse(
409,
`${archiveStatus.message} Configure the NFS archive in Settings before uploading video.`,
);
}
// Videos are written only to the configured media storage share. No share, no
// upload: the app must never fall back to container-local storage.
const media = await mediaStorage();
if (!media.ok) return errorResponse(409, media.message);
const storage = media.settings;
const videoId = uuidv7();
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
+107
View File
@@ -0,0 +1,107 @@
import { z } from "zod";
import { gateSession } from "@/auth/api";
import { hasPermission } from "@/auth/permissions";
import {
advanceGrowthGoal,
createGrowthGoal,
GrowthGoalError,
listGoalsForUser,
listGrowthQueue,
} from "@/db/growthGoals";
import { SKILL_LEVELS } from "@/db/schema";
import { errorResponse, jsonResponse } from "@/lib/http";
const createSchema = z.object({
skillId: z.string().min(1),
targetLevel: z.enum(SKILL_LEVELS),
targetDate: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional()
.nullable(),
});
const actionSchema = z.object({
id: z.string().min(1),
action: z.enum([
"assignMentor",
"decline",
"startShadow",
"progressShadow",
"achieve",
"pause",
"resume",
]),
mentorUserId: z.string().min(1).optional().nullable(),
});
/**
* GET /api/growth-goals — the signed-in volunteer's goals
* GET /api/growth-goals?scope=queue — coordinator/mentor queue (+ candidates)
*/
export async function GET(req: Request) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const scope = new URL(req.url).searchParams.get("scope");
if (scope === "queue") {
if (!hasPermission(gate.systemRole, "schedule.publish")) {
return errorResponse(403, "coordinators only");
}
return jsonResponse({ goals: await listGrowthQueue() });
}
return jsonResponse({ goals: await listGoalsForUser(gate.id) });
}
/** POST /api/growth-goals — ask to grow toward a level for one skill. */
export async function POST(req: Request) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const parsed = createSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) return errorResponse(400, "invalid growth goal");
try {
const goal = await createGrowthGoal({
userId: gate.id,
skillId: parsed.data.skillId,
targetLevel: parsed.data.targetLevel,
targetDate: parsed.data.targetDate ?? null,
});
return jsonResponse({ ok: true, ...goal }, 201);
} catch (error) {
if (error instanceof GrowthGoalError) {
return errorResponse(error.status, error.message);
}
console.error("[growth-goals] create failed", error);
return errorResponse(500, "failed to create the goal");
}
}
/** PATCH /api/growth-goals — advance a goal (coordinator). */
export async function PATCH(req: Request) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
if (!hasPermission(gate.systemRole, "schedule.publish")) {
return errorResponse(403, "coordinators only");
}
const parsed = actionSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) return errorResponse(400, "invalid action");
try {
const result = await advanceGrowthGoal({
goalId: parsed.data.id,
action: parsed.data.action,
actorId: gate.id,
mentorUserId: parsed.data.mentorUserId ?? null,
});
return jsonResponse({ ok: true, ...result });
} catch (error) {
if (error instanceof GrowthGoalError) {
return errorResponse(error.status, error.message);
}
console.error("[growth-goals] action failed", error);
return errorResponse(500, "failed to update the goal");
}
}
+8 -2
View File
@@ -3,8 +3,9 @@ import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { getStorageSettings } from "@/db/storage-settings";
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
import { eventVideoUploadPath } from "@/lib/event-videos";
import { eventVideoArchivePath } from "@/lib/event-videos";
import { errorResponse } from "@/lib/http";
export const GET = async (
@@ -33,7 +34,12 @@ export const GET = async (
}
let filePath: string;
try {
filePath = eventVideoUploadPath(video.posterStoredName);
const storage = await getStorageSettings();
filePath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
video.posterStoredName,
);
} catch {
return errorResponse(404, "unknown poster");
}
+11 -3
View File
@@ -3,9 +3,10 @@ import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { getStorageSettings } from "@/db/storage-settings";
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
import {
eventVideoUploadPath,
eventVideoArchivePath,
sanitizeVideoFilename,
videoContentDisposition,
webRenditionStoredNameForEventVideo,
@@ -49,12 +50,19 @@ export const GET = async (
let filePath: string;
let info: Awaited<ReturnType<typeof stat>> | null = null;
try {
filePath = eventVideoUploadPath(video.webStoredName);
const storage = await getStorageSettings();
filePath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
video.webStoredName,
);
info = await stat(filePath).catch(() => null);
const quality = req.nextUrl.searchParams.get("quality");
if ((quality === "720" || quality === "480") && info?.isFile()) {
const renditionPath = eventVideoUploadPath(
const renditionPath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
webRenditionStoredNameForEventVideo(
video.eventId,
video.id,
@@ -0,0 +1,41 @@
import type { NextRequest } from "next/server";
import { gateSession } from "@/auth/api";
import { getRunSheet } from "@/db/runSheet";
import { boothSheetFilename, buildBoothSheetPdf } from "@/lib/booth-sheet-pdf";
import { errorResponse } from "@/lib/http";
/**
* GET /api/run-sheet/:instanceId/pdf
*
* The printable booth sheet as a real PDF. Any signed-in team member can pull
* it (the run sheet itself is team-visible); it is generated from the current
* database state each time, so it can never show a stale team.
*/
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ instanceId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { instanceId } = await params;
const sheet = await getRunSheet(instanceId);
if (!sheet) return errorResponse(404, "unknown run sheet");
try {
const pdf = await buildBoothSheetPdf(sheet);
const filename = boothSheetFilename(sheet).replace(/[^A-Za-z0-9._-]/g, "_");
return new Response(new Uint8Array(pdf), {
status: 200,
headers: {
"content-type": "application/pdf",
"content-disposition": `attachment; filename="${filename}"`,
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
},
});
} catch (error) {
console.error("[run-sheet-pdf] build failed", error);
return errorResponse(500, "could not build the booth sheet");
}
};
@@ -0,0 +1,199 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Database, HardDrive } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { formatBytes } from "@/lib/retention";
export interface RetentionSummaryView {
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 };
}
function Row({ label, value }: { label: string; value: string }) {
return (
<div className="flex items-baseline justify-between gap-3 border-b border-border py-1.5 last:border-b-0">
<dt className="text-xs text-muted-foreground">{label}</dt>
<dd className="text-sm font-medium">{value}</dd>
</div>
);
}
/**
* Retention + storage report. The numbers come from the database (rows) and
* the upload volume (orphan files). Running the sweep is explicit — nothing is
* deleted on a page view.
*/
export function RetentionPanel({ summary }: { summary: RetentionSummaryView }) {
const router = useRouter();
const [notificationDays, setNotificationDays] = useState(
summary.thresholds.notificationDays,
);
const [tokenDays, setTokenDays] = useState(summary.thresholds.tokenDays);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
async function sweep() {
setBusy(true);
setMessage(null);
setError(null);
try {
const res = await fetch("/api/dev/retention", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ notificationDays, tokenDays }),
});
const data = (await res.json().catch(() => ({}))) as {
error?: string;
removed?: {
notifications: number;
tokens: number;
magicTokens: number;
orphanFiles: number;
orphanBytes: number;
};
};
if (!res.ok) {
setError(data.error ?? "The sweep failed.");
return;
}
const removed = data.removed;
setMessage(
removed
? `Removed ${removed.notifications} notification rows, ${removed.tokens + removed.magicTokens} tokens, and ${removed.orphanFiles} orphan files (${formatBytes(removed.orphanBytes)}).`
: "Sweep complete.",
);
router.refresh();
} catch {
setError("Network error.");
} finally {
setBusy(false);
}
}
const totalBytes =
summary.training.bytes +
summary.eventPhotos.bytes +
summary.eventVideos.bytes;
return (
<div className="space-y-5">
<div className="grid gap-4 sm:grid-cols-2">
<div className="rounded-md border border-border p-3">
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-tight text-muted-foreground">
<Database className="h-3.5 w-3.5" aria-hidden="true" />
Database rows
</p>
<dl className="mt-2">
<Row
label="Notifications (total)"
value={`${summary.notifications.total} · ${summary.notifications.live} live`}
/>
<Row
label="Notifications past the window"
value={`${summary.notifications.prunable}`}
/>
<Row
label="Consumed tokens"
value={`${summary.tokens.used} respond · ${summary.tokens.magic} magic`}
/>
<Row
label="Tokens past the window"
value={`${summary.tokens.prunable}`}
/>
<Row label="Audit log (kept)" value={`${summary.auditLog}`} />
</dl>
</div>
<div className="rounded-md border border-border p-3">
<p className="flex items-center gap-1.5 text-xs font-semibold uppercase tracking-tight text-muted-foreground">
<HardDrive className="h-3.5 w-3.5" aria-hidden="true" />
Upload volume
</p>
<dl className="mt-2">
<Row
label="Training attachments"
value={`${summary.training.files} · ${formatBytes(summary.training.bytes)}`}
/>
<Row
label="Event photos"
value={`${summary.eventPhotos.files} · ${formatBytes(summary.eventPhotos.bytes)}`}
/>
<Row
label="Event videos"
value={`${summary.eventVideos.files} · ${formatBytes(summary.eventVideos.bytes)}`}
/>
<Row
label="Orphan files"
value={`${summary.orphanFiles.files} · ${formatBytes(summary.orphanFiles.bytes)}`}
/>
<Row label="Total reported" value={formatBytes(totalBytes)} />
</dl>
</div>
</div>
<div className="flex flex-wrap items-end gap-3">
<div className="flex flex-col gap-1">
<Label htmlFor="notification-days" className="text-xs">
Keep sent mail for (days)
</Label>
<Input
id="notification-days"
type="number"
min={1}
max={3650}
value={notificationDays}
onChange={(event) => setNotificationDays(Number(event.target.value))}
className="h-9 w-28"
/>
</div>
<div className="flex flex-col gap-1">
<Label htmlFor="token-days" className="text-xs">
Keep used tokens for (days)
</Label>
<Input
id="token-days"
type="number"
min={1}
max={3650}
value={tokenDays}
onChange={(event) => setTokenDays(Number(event.target.value))}
className="h-9 w-28"
/>
</div>
<Button type="button" disabled={busy} onClick={sweep}>
{busy ? "Sweeping…" : "Prune now"}
</Button>
</div>
<p className="text-xs text-muted-foreground">
Only finished mail and already-used tokens are removed; queued mail is
never touched. Orphan files are uploads whose record is gone and that are
more than a day old. Event photos and videos are owned by their event and
are reported, not swept. The same sweep runs monthly from
<code className="mx-1 font-mono">/api/dev/cron/retention</code>.
</p>
{message && (
<p role="status" className="text-sm text-muted-foreground">
{message}
</p>
)}
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
</div>
);
}
@@ -6,9 +6,10 @@ import { Archive } from "lucide-react";
import { Button } from "@/components/ui/button";
/**
* Manager-only "copy then delete" action. The server writes a complete archive
* first, including a manifest, and only then removes the event. A failure leaves
* the live event untouched.
* Manager-only "file then delete" action for a finished event. Originals and
* edits already live on the media storage share; this copies them into a dated
* delivery folder with a manifest, then removes the event rows and the working
* copies. A failure leaves the live event untouched.
*/
export function ArchiveEventButton({
eventId,
@@ -27,7 +28,7 @@ export function ArchiveEventButton({
async function archive() {
const confirmed = window.confirm(
`Archive ${photoCount} photo${photoCount === 1 ? "" : "s"} from "${title}" to ${archivePath}, then delete the event?\n\nThe originals and saved edits are copied first. The event is removed only if the archive succeeds.`,
`File ${photoCount} photo${photoCount === 1 ? "" : "s"} from "${title}" into a dated folder under ${archivePath}, then delete the event?\n\nOriginals and saved edits are copied first; they stay on media storage either way. The event is removed only if the copy succeeds.`,
);
if (!confirmed) return;
@@ -67,7 +68,7 @@ export function ArchiveEventButton({
onClick={archive}
>
<Archive className="h-3.5 w-3.5" aria-hidden="true" />
{busy ? "Archiving…" : "Archive & delete"}
{busy ? "Filing…" : "File & delete"}
</Button>
{error && (
<p role="alert" className="max-w-xs text-right text-xs text-destructive">
+28 -9
View File
@@ -85,6 +85,8 @@ export function PhotoGallery({
canContribute,
canManage,
currentUserId,
storageReady,
storageMessage,
}: {
eventId: string;
folderId: string;
@@ -92,6 +94,9 @@ export function PhotoGallery({
canContribute: boolean;
canManage: boolean;
currentUserId: string;
/** Photos are stored only on the configured media storage share. */
storageReady: boolean;
storageMessage: string;
}) {
const router = useRouter();
const inputRef = useRef<HTMLInputElement>(null);
@@ -105,7 +110,9 @@ export function PhotoGallery({
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [viewing, setViewing] = useState<GalleryPhoto | null>(null);
const editablePhotos = photos.filter((photo) => photo.editable);
const editablePhotos = photos.filter(
(photo) => photo.editable && storageReady,
);
const viewingIndex = viewing
? editablePhotos.findIndex((photo) => photo.id === viewing.id)
: -1;
@@ -196,6 +203,15 @@ export function PhotoGallery({
return (
<div className="space-y-4">
{canContribute && !storageReady && (
<p
role="alert"
className="rounded-md border border-amber-500/40 bg-amber-500/10 p-3 text-xs text-amber-900 dark:text-amber-200"
>
Photo uploads and editing are disabled. {storageMessage}
</p>
)}
{canContribute && (
<div className="space-y-2 rounded-md border border-border p-3">
<p className="text-sm font-medium">Upload photos to this folder</p>
@@ -207,7 +223,7 @@ export function PhotoGallery({
accept={ACCEPT}
aria-label="Choose photos to upload"
className="h-9 max-w-md text-xs"
disabled={uploading}
disabled={uploading || !storageReady}
onChange={(event) => {
setFiles(Array.from(event.target.files ?? []));
setNotice(null);
@@ -217,7 +233,7 @@ export function PhotoGallery({
<Button
type="button"
size="sm"
disabled={uploading || files.length === 0}
disabled={uploading || files.length === 0 || !storageReady}
onClick={upload}
>
{uploading ? "Uploading…" : `Upload ${files.length || ""}`.trim()}
@@ -262,11 +278,14 @@ export function PhotoGallery({
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
{photos.map((photo) => {
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
const editable = photo.editable && storageReady;
const canRemove = canManage || photo.uploaderId === currentUserId;
const version = photo.editedAt ? Date.parse(photo.editedAt) : 0;
// The grid uses the cached 640px thumbnail; a saved edit is shown
// from the full-resolution export so the badge and the image agree.
const displaySrc = photo.editedAt
? `${src}?variant=edited&v=${version}`
: src;
: `${src}/thumb`;
return (
<li
key={photo.id}
@@ -276,14 +295,14 @@ export function PhotoGallery({
type="button"
className="group relative flex aspect-square w-full items-center justify-center bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
aria-label={
photo.editable
editable
? `View and edit ${photo.filename}`
: `View ${photo.filename}`
}
disabled={!photo.editable}
disabled={!editable}
onClick={() => setViewing(photo)}
>
{photo.previewable || photo.editedAt ? (
{photo.previewable || photo.editedAt || photo.kind === "raw" ? (
// Frames are private; the serving route sets the cache policy.
// eslint-disable-next-line @next/next/no-img-element
<img
@@ -301,7 +320,7 @@ export function PhotoGallery({
</span>
</div>
)}
{photo.editable && (
{editable && (
<span className="absolute inset-x-0 bottom-0 translate-y-full bg-black/70 px-2 py-1 text-[11px] font-medium text-white transition-transform group-hover:translate-y-0 group-focus-visible:translate-y-0">
<Pencil className="mr-1 inline h-3 w-3" aria-hidden="true" />
View &amp; edit
@@ -341,7 +360,7 @@ export function PhotoGallery({
<Download className="h-3 w-3" aria-hidden="true" />
Download
</a>
{photo.editable && (
{editable && (
<button
type="button"
onClick={() => setViewing(photo)}
@@ -0,0 +1,207 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { ArrowRight, Target } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export interface GrowthGoalView {
id: string;
skillName: string;
targetLevel: string;
targetDate: string | null;
status: string;
mentorName: string | null;
shadowCount: number;
verifiedLevel: string;
}
export const GOAL_STATUS_LABEL: Record<string, string> = {
requested: "Waiting for a mentor",
mentor_assigned: "Mentor assigned",
in_progress: "In progress",
paused: "Paused",
achieved: "Achieved",
declined: "Declined",
};
export const LEVEL_LABEL: Record<string, string> = {
none: "Not started",
observer: "Observer",
assisted: "Assisted",
qualified: "Qualified",
expert: "Expert",
};
/**
* Volunteer-facing growth goals. Asking is the only action here; a coordinator
* assigns the mentor and moves the goal, so a volunteer cannot certify
* themselves. Verification of the level still happens in the skills matrix.
*/
export function GrowthGoalsPanel({
goals,
skills,
levels,
}: {
goals: GrowthGoalView[];
skills: { id: string; name: string; verifiedLevel: string }[];
levels: readonly string[];
}) {
const router = useRouter();
const [skillId, setSkillId] = useState("");
const [targetLevel, setTargetLevel] = useState("qualified");
const [targetDate, setTargetDate] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const chosen = skills.find((skill) => skill.id === skillId);
async function submit(event: React.FormEvent) {
event.preventDefault();
setBusy(true);
setError(null);
setNotice(null);
try {
const res = await fetch("/api/growth-goals", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
skillId,
targetLevel,
targetDate: targetDate || null,
}),
});
const data = (await res.json().catch(() => ({}))) as { error?: string };
if (!res.ok) {
setError(data.error ?? "Could not create the goal.");
return;
}
setNotice("Goal requested. A coordinator will pair you with a mentor.");
setSkillId("");
setTargetDate("");
router.refresh();
} catch {
setError("Network error.");
} finally {
setBusy(false);
}
}
return (
<div className="space-y-5">
<form onSubmit={submit} className="space-y-3">
<div className="grid gap-3 sm:grid-cols-3">
<div className="flex flex-col gap-2 sm:col-span-1">
<Label htmlFor="goal-skill">Skill</Label>
<select
id="goal-skill"
required
value={skillId}
onChange={(event) => setSkillId(event.target.value)}
className="h-9 rounded-md border border-border bg-background px-2 text-sm"
>
<option value="">Choose a skill…</option>
{skills.map((skill) => (
<option key={skill.id} value={skill.id}>
{skill.name} ({LEVEL_LABEL[skill.verifiedLevel] ?? skill.verifiedLevel})
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="goal-level">Target level</Label>
<select
id="goal-level"
value={targetLevel}
onChange={(event) => setTargetLevel(event.target.value)}
className="h-9 rounded-md border border-border bg-background px-2 text-sm"
>
{levels
.filter((level) => level !== "none")
.map((level) => (
<option key={level} value={level}>
{LEVEL_LABEL[level] ?? level}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="goal-date">By (optional)</Label>
<Input
id="goal-date"
type="date"
value={targetDate}
onChange={(event) => setTargetDate(event.target.value)}
/>
</div>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" size="sm" disabled={busy || !skillId}>
<Target aria-hidden="true" />
{busy ? "Requesting…" : "Request goal"}
</Button>
{chosen && (
<p className="text-xs text-muted-foreground">
Currently {LEVEL_LABEL[chosen.verifiedLevel] ?? chosen.verifiedLevel}{" "}
<ArrowRight className="inline h-3 w-3" aria-hidden="true" />{" "}
{LEVEL_LABEL[targetLevel] ?? targetLevel}
</p>
)}
</div>
{notice && (
<p role="status" className="text-xs text-muted-foreground">
{notice}
</p>
)}
{error && (
<p role="alert" className="text-xs text-destructive">
{error}
</p>
)}
</form>
{goals.length === 0 ? (
<p className="text-sm text-muted-foreground">
No growth goals yet. Pick a skill above to ask for a mentor.
</p>
) : (
<ul className="divide-y divide-border">
{goals.map((goal) => (
<li
key={goal.id}
className="flex flex-wrap items-start justify-between gap-2 py-3 first:pt-0 last:pb-0"
>
<div>
<p className="text-sm font-medium">{goal.skillName}</p>
<p className="text-xs text-muted-foreground">
{LEVEL_LABEL[goal.verifiedLevel] ?? goal.verifiedLevel} →{" "}
{LEVEL_LABEL[goal.targetLevel] ?? goal.targetLevel}
{goal.mentorName ? ` · mentor ${goal.mentorName}` : ""}
{goal.shadowCount > 0
? ` · ${goal.shadowCount} shadow${goal.shadowCount === 1 ? "" : "s"}`
: ""}
{goal.targetDate ? ` · by ${goal.targetDate}` : ""}
</p>
</div>
<Badge
variant={
goal.status === "achieved"
? "default"
: goal.status === "declined"
? "outline"
: "secondary"
}
>
{GOAL_STATUS_LABEL[goal.status] ?? goal.status}
</Badge>
</li>
))}
</ul>
)}
</div>
);
}
@@ -0,0 +1,242 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
GOAL_STATUS_LABEL,
LEVEL_LABEL,
} from "@/components/app/growth/growth-goals-panel";
export interface QueueGoalView {
id: string;
userName: string;
email: string;
skillName: string;
targetLevel: string;
targetDate: string | null;
status: string;
mentorUserId: string | null;
mentorName: string | null;
shadowCount: number;
verifiedLevel: string;
mentorCandidates: { userId: string; displayName: string; verifiedLevel: string }[];
}
/**
* Coordinator/mentor queue. Assigning a mentor only offers people who satisfy
* the mentor rule for that skill (level, opt-in, approval), so an assignment
* cannot silently skip C5.
*/
export function MentorQueuePanel({ goals }: { goals: QueueGoalView[] }) {
const router = useRouter();
const [mentorFor, setMentorFor] = useState<Record<string, string>>({});
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
async function act(
goal: QueueGoalView,
action:
| "assignMentor"
| "decline"
| "startShadow"
| "progressShadow"
| "achieve"
| "pause"
| "resume",
) {
const key = `${goal.id}:${action}`;
setBusy(key);
setError(null);
setNotice(null);
try {
const res = await fetch("/api/growth-goals", {
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({
id: goal.id,
action,
mentorUserId:
action === "assignMentor" ? mentorFor[goal.id] ?? null : undefined,
}),
});
const data = (await res.json().catch(() => ({}))) as { error?: string };
if (!res.ok) {
setError(data.error ?? "Could not update the goal.");
return;
}
setNotice(`${goal.userName} · ${goal.skillName}: ${action} saved.`);
router.refresh();
} catch {
setError("Network error.");
} finally {
setBusy(null);
}
}
if (goals.length === 0) {
return (
<p className="text-sm text-muted-foreground">
No open growth goals. Volunteers can request one from their profile.
</p>
);
}
return (
<div className="space-y-4">
{notice && (
<p role="status" className="rounded-md border border-border bg-muted/40 p-2 text-xs">
{notice}
</p>
)}
{error && (
<p role="alert" className="rounded-md border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
{error}
</p>
)}
<ul className="space-y-3">
{goals.map((goal) => {
const selection = mentorFor[goal.id] ?? "";
const terminal = goal.status === "achieved" || goal.status === "declined";
return (
<li key={goal.id} className="rounded-md border border-border p-4">
<div className="flex flex-wrap items-start justify-between gap-2">
<div>
<p className="text-sm font-semibold">
{goal.userName} · {goal.skillName}
</p>
<p className="text-xs text-muted-foreground">
{LEVEL_LABEL[goal.verifiedLevel] ?? goal.verifiedLevel} →{" "}
{LEVEL_LABEL[goal.targetLevel] ?? goal.targetLevel}
{goal.mentorName ? ` · mentor ${goal.mentorName}` : ""}
{goal.shadowCount > 0
? ` · ${goal.shadowCount} shadow${goal.shadowCount === 1 ? "" : "s"}`
: ""}
{goal.targetDate ? ` · by ${goal.targetDate}` : ""}
</p>
<p className="text-xs text-muted-foreground">{goal.email}</p>
</div>
<Badge variant={terminal ? "outline" : "secondary"}>
{GOAL_STATUS_LABEL[goal.status] ?? goal.status}
</Badge>
</div>
{goal.status === "requested" && (
<div className="mt-3 flex flex-wrap items-end gap-2">
{goal.mentorCandidates.length === 0 ? (
<p className="text-xs text-amber-700 dark:text-amber-300">
No one is mentor-ready for this skill yet. Decline, or have
a qualified volunteer opt in and get approved first.
</p>
) : (
<>
<label className="flex flex-col gap-1 text-xs">
<span className="font-medium text-muted-foreground">
Mentor
</span>
<select
value={selection}
onChange={(event) =>
setMentorFor((prev) => ({
...prev,
[goal.id]: event.target.value,
}))
}
className="h-9 rounded-md border border-border bg-background px-2 text-sm"
>
<option value="">Choose…</option>
{goal.mentorCandidates.map((candidate) => (
<option key={candidate.userId} value={candidate.userId}>
{candidate.displayName} (
{LEVEL_LABEL[candidate.verifiedLevel] ??
candidate.verifiedLevel}
)
</option>
))}
</select>
</label>
<Button
size="sm"
disabled={busy !== null || !selection}
onClick={() => act(goal, "assignMentor")}
>
{busy === `${goal.id}:assignMentor`
? "Assigning…"
: "Assign mentor"}
</Button>
</>
)}
<Button
size="sm"
variant="ghost"
disabled={busy !== null}
onClick={() => act(goal, "decline")}
>
Decline
</Button>
</div>
)}
{goal.status !== "requested" && !terminal && (
<div className="mt-3 flex flex-wrap gap-2">
{goal.status === "mentor_assigned" && (
<Button
size="sm"
disabled={busy !== null}
onClick={() => act(goal, "startShadow")}
>
Start shadowing
</Button>
)}
{goal.status === "in_progress" && (
<>
<Button
size="sm"
disabled={busy !== null}
onClick={() => act(goal, "progressShadow")}
>
Log a shadow
</Button>
<Button
size="sm"
variant="outline"
disabled={busy !== null}
onClick={() => act(goal, "achieve")}
>
Mark achieved
</Button>
</>
)}
{goal.status === "paused" ? (
<Button
size="sm"
disabled={busy !== null}
onClick={() => act(goal, "resume")}
>
Resume
</Button>
) : (
<Button
size="sm"
variant="ghost"
disabled={busy !== null}
onClick={() => act(goal, "pause")}
>
Pause
</Button>
)}
<p className="text-xs text-muted-foreground">
Verified levels still change in the skills matrix.
</p>
</div>
)}
</li>
);
})}
</ul>
</div>
);
}
+11 -5
View File
@@ -265,16 +265,22 @@ export function VideoUploadForm({
<div>
<h3 className="text-sm font-semibold">Upload a video</h3>
<p className="text-xs text-muted-foreground">
The camera original goes to the NFS archive untouched. A web MP4 and
poster are generated for playback and embedding.
Original videos are stored only on the configured media share —
never in the app container. The camera original is kept untouched; a
web MP4 and poster are generated beside it for playback and
embedding.
</p>
</div>
)}
{!archiveReady && (
<p className="rounded border border-amber-500/40 bg-amber-500/10 p-2 text-xs text-amber-900 dark:text-amber-200">
The NFS archive is not ready. Video uploads are disabled until an
admin fixes Settings → Media archive (NFS).
<p
role="alert"
className="rounded border border-amber-500/40 bg-amber-500/10 p-2 text-xs text-amber-900 dark:text-amber-200"
>
No usable media storage share is configured. Video uploads are
disabled until an admin sets the NFS export or local path in Settings
→ Media storage. Nothing is stored inside the app container.
</p>
)}
+17 -8
View File
@@ -53,11 +53,11 @@ export function StoragePanel({
status?: typeof status;
};
if (!res.ok) {
setError(data.error ?? "Could not save the archive destination.");
setError(data.error ?? "Could not save the media storage location.");
return;
}
if (data.status) setStatus(data.status);
setMessage("Archive destination saved and tested.");
setMessage("Media storage saved and tested.");
router.refresh();
} catch {
setError("Network error.");
@@ -72,7 +72,9 @@ export function StoragePanel({
<HardDrive className="mt-0.5 h-4 w-4 shrink-0" aria-hidden="true" />
<div className="space-y-1 text-sm">
<p className="font-medium">
{status.ready ? "Archive destination is ready" : "Archive destination is not ready"}
{status.ready
? "Media storage is ready"
: "Media storage is not ready — media uploads and photo editing are blocked"}
</p>
<p className="text-muted-foreground">{status.message}</p>
{status.ready && status.freeBytes !== null && (
@@ -85,13 +87,19 @@ export function StoragePanel({
<div className="grid gap-4 sm:grid-cols-2">
<div className="flex flex-col gap-2">
<Label htmlFor="nfs-share">NFS share (optional label)</Label>
<Label htmlFor="nfs-share">NFS share or local path (required)</Label>
<Input
id="nfs-share"
value={nfsShare}
onChange={(event) => setNfsShare(event.target.value)}
placeholder="nas.local:/volume1/church-media"
placeholder="nas.local:/volume1/church-media or /mnt/church-media"
required
/>
<p className="text-xs text-muted-foreground">
Names the share that holds all event photos and videos. Uploads,
photo editing and video processing stay disabled while this is
empty; nothing is ever written inside the app container.
</p>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="archive-path">Mounted path in this container</Label>
@@ -104,7 +112,7 @@ export function StoragePanel({
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="archive-folder">Folder on the archive</Label>
<Label htmlFor="archive-folder">Folder on the share</Label>
<Input
id="archive-folder"
value={archiveFolder}
@@ -116,7 +124,8 @@ export function StoragePanel({
</div>
<p className="text-xs text-muted-foreground">
NFS is a mounted filesystem, not an upload API. Mount the export on the
This is primary storage for original photos and videos, not a backup.
NFS is a mounted filesystem, not an upload API: mount the export on the
Docker host, set <code className="font-mono">MEDIA_ARCHIVE_DIR</code> to
that host path, then restart this stack. The path above must be the
directory visible inside the app container (normally{" "}
@@ -125,7 +134,7 @@ export function StoragePanel({
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={busy}>
{busy ? "Saving & testing…" : "Save archive destination"}
{busy ? "Saving & testing…" : "Save media storage"}
</Button>
{message && (
<p role="status" className="text-sm text-muted-foreground">
+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";
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from "vitest";
import { PDFDocument } from "pdf-lib";
import type { RunSheetData } from "@/db/runSheet";
import { boothSheetFilename, buildBoothSheetPdf } from "./booth-sheet-pdf";
function sheet(overrides: Partial<RunSheetData["instance"]> = {}): RunSheetData {
return {
instance: {
id: "instance-1",
serviceName: "Sunday Gathering",
location: "Main Auditorium",
startsAt: new Date("2026-11-22T16:00:00Z"),
endsAt: new Date("2026-11-22T17:30:00Z"),
status: "published",
notes: null,
...overrides,
},
header: {
speaker: "Pastor Jane",
sermonTitle: "The Long Road — Part 2",
streamUrl: "https://example.com/live",
slidesUrl: null,
notes: "Cue the loop before the countdown.",
updatedAt: null,
},
items: [
{ id: "a", sortOrder: 10, timeLabel: "10:28", title: "Countdown", owner: "Media", notes: null },
{ id: "b", sortOrder: 20, timeLabel: "10:30", title: "Worship set", owner: "Worship", notes: null },
],
checklist: {
pre: [{ id: "p1", label: "Test microphones", sortOrder: 10, doneAt: new Date(), doneBy: "u1" }],
post: [{ id: "q1", label: "Copy media cards", sortOrder: 10, doneAt: null, doneBy: null }],
},
team: [
{
roleName: "Audio",
userName: "Jordan Lee",
callTime: new Date("2026-11-22T15:00:00Z"),
status: "confirmed",
},
],
};
}
describe("booth sheet PDF", () => {
it("renders a real PDF for one service", async () => {
const bytes = await buildBoothSheetPdf(sheet());
expect(new TextDecoder().decode(bytes.slice(0, 5))).toBe("%PDF-");
const doc = await PDFDocument.load(bytes);
expect(doc.getPageCount()).toBe(1);
});
it("paginates when the order of service is long", async () => {
const long = sheet();
long.items = Array.from({ length: 90 }, (_, index) => ({
id: `item-${index}`,
sortOrder: (index + 1) * 10,
timeLabel: null,
title: `Cue ${index + 1}`,
owner: "Media",
notes: index % 10 === 0 ? "A longer note that should wrap on the page." : null,
}));
const bytes = await buildBoothSheetPdf(long);
const doc = await PDFDocument.load(bytes);
expect(doc.getPageCount()).toBeGreaterThan(1);
});
it("names the download after the service date and name", () => {
expect(boothSheetFilename(sheet())).toBe(
"booth-sheet-2026-11-22-sunday-gathering.pdf",
);
});
});
+360
View File
@@ -0,0 +1,360 @@
/**
* Server-rendered booth sheet (PDF).
*
* Browser print-to-PDF depends on the machine and its margins; the Sunday
* printout should look the same from the church laptop, a phone, or a fresh
* volunteer's browser. This builds a one-page-per-section letter PDF with the
* service header, the assigned team and call times, the order of service, and
* the pre/post checklists.
*
* Pure rendering: the caller supplies the run-sheet data.
*/
import { PDFDocument, StandardFonts, rgb, type PDFFont, type PDFPage } from "pdf-lib";
import type { RunSheetData } from "@/db/runSheet";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
const PAGE_WIDTH = 612;
const PAGE_HEIGHT = 792;
const MARGIN = 48;
const CONTENT_WIDTH = PAGE_WIDTH - MARGIN * 2;
const INK = rgb(0.07, 0.08, 0.1);
const MUTED = rgb(0.4, 0.43, 0.48);
const RULE = rgb(0.82, 0.84, 0.87);
interface TextStyle {
font?: PDFFont;
size?: number;
color?: ReturnType<typeof rgb>;
x?: number;
width?: number;
gap?: number;
}
/** Helvetica is WinAnsi; strip/replace what it cannot encode. */
function pdfSafe(value: string): string {
return value
.replaceAll("\u2192", "->")
.replaceAll("\u2013", "-")
.replaceAll("\u2014", "-")
.replaceAll("\u2019", "'")
.replaceAll("\u2018", "'")
.replaceAll("\u201c", '"')
.replaceAll("\u201d", '"')
.replaceAll("\u2026", "...")
.replace(/[^\t\n\r\x20-\x7e\u00a0-\u00ff]/g, "");
}
function wrapText(
value: string,
font: PDFFont,
size: number,
maxWidth: number,
): string[] {
const words = pdfSafe(value).replace(/\s+/g, " ").trim().split(" ");
if (words.length === 0 || (words.length === 1 && words[0] === "")) return [];
const lines: string[] = [];
let line = "";
for (const word of words) {
const candidate = line ? `${line} ${word}` : word;
if (font.widthOfTextAtSize(candidate, size) <= maxWidth) {
line = candidate;
continue;
}
if (line) lines.push(line);
let rest = word;
while (font.widthOfTextAtSize(rest, size) > maxWidth) {
let cut = rest.length;
while (cut > 1 && font.widthOfTextAtSize(rest.slice(0, cut), size) > maxWidth) {
cut -= 1;
}
lines.push(rest.slice(0, cut));
rest = rest.slice(cut);
}
line = rest;
}
if (line) lines.push(line);
return lines;
}
function clip(value: string, font: PDFFont, size: number, maxWidth: number): string {
const text = pdfSafe(value);
if (font.widthOfTextAtSize(text, size) <= maxWidth) return text;
let cut = text.length;
while (cut > 1 && font.widthOfTextAtSize(`${text.slice(0, cut)}…`, size) > maxWidth) {
cut -= 1;
}
return `${text.slice(0, cut)}-`;
}
function timeLabel(date: Date | null): string {
if (!date) return "";
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
hour: "numeric",
minute: "2-digit",
});
}
function dateLabel(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "long",
month: "long",
day: "numeric",
year: "numeric",
});
}
export function boothSheetFilename(sheet: RunSheetData): string {
const stamp = formatInTimezone(sheet.instance.startsAt, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
});
const slug = sheet.instance.serviceName
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
const [month, day, year] = stamp.split("/");
return `booth-sheet-${year}-${month}-${day}${slug ? `-${slug}` : ""}.pdf`;
}
export async function buildBoothSheetPdf(sheet: RunSheetData): Promise<Uint8Array> {
const doc = await PDFDocument.create();
const font = await doc.embedFont(StandardFonts.Helvetica);
const bold = await doc.embedFont(StandardFonts.HelveticaBold);
const pages: PDFPage[] = [];
let page: PDFPage = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
pages.push(page);
let y = PAGE_HEIGHT - MARGIN;
function newPage() {
page = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT]);
pages.push(page);
y = PAGE_HEIGHT - MARGIN;
}
function ensure(needed: number) {
if (y - needed < MARGIN + 12) newPage();
}
function drawLines(
value: string,
style: TextStyle = {},
): void {
const activeFont = style.font ?? font;
const size = style.size ?? 10;
const x = style.x ?? MARGIN;
const width = style.width ?? CONTENT_WIDTH;
const gap = style.gap ?? 3;
for (const line of wrapText(value, activeFont, size, width)) {
ensure(size + gap);
page.drawText(line, {
x,
y: y - size,
size,
font: activeFont,
color: style.color ?? INK,
});
y -= size + gap;
}
}
function heading(value: string) {
ensure(34);
y -= 10;
page.drawText(pdfSafe(value.toUpperCase()), {
x: MARGIN,
y: y - 9,
size: 9,
font: bold,
color: MUTED,
});
y -= 14;
}
function rule() {
ensure(10);
page.drawLine({
start: { x: MARGIN, y },
end: { x: PAGE_WIDTH - MARGIN, y },
thickness: 0.6,
color: RULE,
});
y -= 10;
}
function field(label: string, value: string | null) {
if (!value) return;
ensure(18);
page.drawText(pdfSafe(label.toUpperCase()), {
x: MARGIN,
y: y - 8,
size: 7.5,
font: bold,
color: MUTED,
});
const startY = y;
y -= 2;
drawLines(value, { x: MARGIN + 92, width: CONTENT_WIDTH - 92, size: 10, gap: 3 });
if (y > startY - 16) y = startY - 16;
}
function tableRow(
columns: { value: string; x: number; width: number; bold?: boolean }[],
size = 9.5,
) {
ensure(size + 6);
for (const column of columns) {
page.drawText(
clip(column.value, column.bold ? bold : font, size, column.width),
{
x: column.x,
y: y - size,
size,
font: column.bold ? bold : font,
color: INK,
},
);
}
y -= size + 6;
}
const service = sheet.instance;
drawLines(service.serviceName, { font: bold, size: 20, gap: 4 });
drawLines(
[dateLabel(service.startsAt), timeLabel(service.startsAt)]
.filter(Boolean)
.join(" · "),
{ size: 11, color: MUTED, gap: 3 },
);
if (service.location) {
drawLines(service.location, { size: 10, color: MUTED });
}
y -= 4;
rule();
heading("Service");
field("Speaker", sheet.header.speaker);
field("Message", sheet.header.sermonTitle);
field("Stream", sheet.header.streamUrl);
field("Slides", sheet.header.slidesUrl);
field("Notes", sheet.header.notes ?? service.notes);
if (service.status !== "published") {
field("Status", `${service.status} — not published`);
}
heading("Team");
if (sheet.team.length === 0) {
drawLines("No one is assigned yet.", { size: 10, color: MUTED });
} else {
tableRow(
[
{ value: "Role", x: MARGIN, width: 150, bold: true },
{ value: "Volunteer", x: MARGIN + 160, width: 170, bold: true },
{ value: "Call", x: MARGIN + 336, width: 60, bold: true },
{ value: "Status", x: MARGIN + 400, width: 116, bold: true },
],
8,
);
rule();
for (const member of sheet.team) {
tableRow([
{ value: member.roleName, x: MARGIN, width: 150 },
{ value: member.userName, x: MARGIN + 160, width: 170 },
{ value: timeLabel(member.callTime), x: MARGIN + 336, width: 60 },
{ value: member.status, x: MARGIN + 400, width: 116 },
]);
}
}
heading("Order of service");
if (sheet.items.length === 0) {
drawLines("No cues yet.", { size: 10, color: MUTED });
} else {
sheet.items.forEach((item, index) => {
tableRow(
[
{
value: item.timeLabel ?? `${index + 1}.`,
x: MARGIN,
width: 70,
bold: true,
},
{ value: item.title, x: MARGIN + 78, width: 260 },
{ value: item.owner ?? "", x: MARGIN + 346, width: 170 },
],
10,
);
if (item.notes) {
drawLines(item.notes, {
x: MARGIN + 78,
width: CONTENT_WIDTH - 78,
size: 8.5,
color: MUTED,
gap: 2,
});
}
});
}
for (const phase of [
{ key: "pre" as const, title: "Before the service" },
{ key: "post" as const, title: "After the service" },
]) {
heading(phase.title);
const items = sheet.checklist[phase.key];
if (items.length === 0) {
drawLines("Nothing listed.", { size: 10, color: MUTED });
continue;
}
for (const item of items) {
ensure(18);
const boxSize = 8;
page.drawRectangle({
x: MARGIN,
y: y - boxSize - 1,
width: boxSize,
height: boxSize,
borderColor: MUTED,
borderWidth: 0.7,
color: undefined,
});
if (item.doneAt) {
page.drawLine({
start: { x: MARGIN + 1.5, y: y - boxSize / 2 - 1 },
end: { x: MARGIN + boxSize - 1.5, y: y - boxSize / 2 - 1 },
thickness: 0.9,
color: MUTED,
});
}
drawLines(item.label, {
x: MARGIN + 16,
width: CONTENT_WIDTH - 16,
size: 10,
gap: 2,
});
y -= 2;
}
}
const generated = `${dateLabel(new Date())} at ${timeLabel(new Date())}`;
pages.forEach((rendered, index) => {
const footer = `Media Team Hub · generated ${generated} · page ${index + 1} of ${pages.length}`;
rendered.drawText(pdfSafe(footer), {
x: MARGIN,
y: MARGIN / 2,
size: 7.5,
font,
color: MUTED,
});
});
return doc.save();
}
+5 -2
View File
@@ -162,10 +162,13 @@ export async function archiveEventPhotos(
})),
);
// The live photos already sit on the same share, under `<root>/events`.
const liveRoot = archiveRoot(input);
// Preflight every source before creating the destination. This is what makes
// "archive succeeded, then delete the event" safe.
for (const photo of input.photos) {
const originalSource = eventPhotoPath(photo.storedName);
const originalSource = eventPhotoPath(liveRoot, photo.storedName);
const originalInfo = await stat(originalSource).catch(() => null);
if (!originalInfo?.isFile()) {
throw new EventArchiveError(
@@ -174,7 +177,7 @@ export async function archiveEventPhotos(
}
let editedSource: string | null = null;
if (photo.editedStoredName) {
editedSource = eventPhotoPath(photo.editedStoredName);
editedSource = eventPhotoPath(liveRoot, photo.editedStoredName);
const editedInfo = await stat(editedSource).catch(() => null);
if (!editedInfo?.isFile()) {
throw new EventArchiveError(
+9 -8
View File
@@ -1,6 +1,5 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { UPLOAD_DIR } from "./uploads";
import {
eventPhotoDir,
eventPhotoKindFor,
@@ -13,6 +12,8 @@ import {
storedNameForEventPhoto,
} from "./event-photos";
const ARCHIVE_ROOT = path.resolve("/srv/glenloch-media");
describe("event photo formats", () => {
it("classifies camera RAW files separately from edited images", () => {
expect(eventPhotoKindFor("IMG_0421.CR3")).toBe("raw");
@@ -55,21 +56,21 @@ describe("event photo filenames and paths", () => {
it("generates a path under the event directory", () => {
const stored = storedNameForEventPhoto("evt_1", "photo-2", "IMG_1.CR3");
expect(stored).toBe("events/evt_1/photo-2.cr3");
expect(eventPhotoPath(stored)).toBe(
path.resolve(UPLOAD_DIR, "events/evt_1/photo-2.cr3"),
expect(eventPhotoPath(ARCHIVE_ROOT, stored)).toBe(
path.resolve(ARCHIVE_ROOT, "events/evt_1/photo-2.cr3"),
);
});
it("refuses traversal and malformed ids", () => {
expect(() => eventPhotoPath("events/../../secret")).toThrow();
expect(() => eventPhotoPath("other/events/x.jpg")).toThrow();
expect(() => eventPhotoPath(ARCHIVE_ROOT, "events/../../secret")).toThrow();
expect(() => eventPhotoPath(ARCHIVE_ROOT, "other/events/x.jpg")).toThrow();
expect(() => storedNameForEventPhoto("../evt", "photo", "a.jpg")).toThrow();
expect(() => eventPhotoDir("../evt")).toThrow();
expect(() => eventPhotoDir(ARCHIVE_ROOT, "../evt")).toThrow();
});
it("targets the event directory for a bulk delete", () => {
expect(eventPhotoDir("evt_1")).toBe(
path.resolve(UPLOAD_DIR, "events/evt_1"),
expect(eventPhotoDir(ARCHIVE_ROOT, "evt_1")).toBe(
path.resolve(ARCHIVE_ROOT, "events/evt_1"),
);
});
+27 -11
View File
@@ -5,11 +5,12 @@
* Browsers can only preview a few formats, so the allow-list is extension-based
* (RAW files frequently report `application/octet-stream`) and the served MIME
* type is derived from the extension, never trusted from the client. Bytes live
* under `UPLOAD_DIR/events/<eventId>/`; Postgres only stores metadata.
* under `<archive root>/events/<eventId>/` on the configured NFS/local share
* (see `media-storage.ts`), never on container-local storage; Postgres only
* stores metadata.
*/
import path from "node:path";
import { UPLOAD_DIR } from "./uploads";
/** One photo may be a large RAW frame; 200 MB covers current full-frame files. */
export const MAX_EVENT_PHOTO_BYTES = 200 * 1024 * 1024;
@@ -127,7 +128,7 @@ export function sanitizePhotoFilename(input: string): string {
}
/**
* A generated on-disk path, relative to `UPLOAD_DIR`: an event folder, the
* A generated on-disk path, relative to the archive root: an event folder, the
* photo UUID as the basename. `eventId`/`photoId` are server-generated UUIDs;
* their shape is still checked so a future caller cannot inject a path.
*/
@@ -159,6 +160,15 @@ export function editedStoredNameForEventPhoto(
return `events/${eventId}/edits/${photoId}.jpg`;
}
/** Lazily generated small grid thumbnail of the untouched original. */
export function thumbStoredNameForEventPhoto(
eventId: string,
photoId: string,
): string {
assertEventPhotoIds(eventId, photoId);
return `events/${eventId}/thumbs/${photoId}.jpg`;
}
/** Lazily generated browser preview of the untouched original. */
export function previewStoredNameForEventPhoto(
eventId: string,
@@ -175,12 +185,15 @@ function assertEventPhotoIds(eventId: string, photoId: string): void {
}
}
/** The event's photo directory; used when deleting an event and its bytes. */
export function eventPhotoDir(eventId: string): string {
/**
* The event's photo directory inside the configured archive root; used when
* deleting an event and its bytes.
*/
export function eventPhotoDir(archiveRoot: string, eventId: string): string {
if (!/^[A-Za-z0-9_-]+$/.test(eventId)) {
throw new Error("invalid event id");
}
const root = path.resolve(UPLOAD_DIR, "events");
const root = path.resolve(archiveRoot, "events");
const dir = path.resolve(root, eventId);
if (dir !== root && !dir.startsWith(`${root}${path.sep}`)) {
throw new Error("invalid event photo path");
@@ -190,12 +203,15 @@ export function eventPhotoDir(eventId: string): string {
}
/**
* Resolve a stored photo path inside `UPLOAD_DIR/events`, refusing traversal.
* The returned path is absolute (or relative to cwd if UPLOAD_DIR is relative).
* Resolve a stored photo path inside `<archiveRoot>/events`, refusing traversal.
* The archive root comes from `mediaStorage()`; it is never a container path.
*/
export function eventPhotoPath(storedName: string): string {
const root = path.resolve(UPLOAD_DIR, "events");
const candidate = path.resolve(UPLOAD_DIR, storedName);
export function eventPhotoPath(
archiveRoot: string,
storedName: string,
): string {
const root = path.resolve(archiveRoot, "events");
const candidate = path.resolve(archiveRoot, storedName);
if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) {
throw new Error("invalid event photo path");
}
+12 -28
View File
@@ -1,14 +1,14 @@
/**
* Event video storage rules.
*
* Originals are written to the mounted NFS archive under
* Originals, browser derivatives, posters and the sidecar all live together in
* one folder on the mounted archive:
* `<archivePath>/<archiveFolder>/videos/<eventId>/<videoId>/`.
* Browser derivatives live under `UPLOAD_DIR/videos/<eventId>/<videoId>/`.
* Every path helper validates generated ids and refuses traversal.
* Nothing is written to container-local storage. Every path helper validates
* generated ids and refuses traversal.
*/
import path from "node:path";
import { UPLOAD_DIR } from "./uploads";
export { formatVideoDuration } from "./video-format";
@@ -111,7 +111,7 @@ export function originalStoredNameForEventVideo(
return `videos/${eventId}/${videoId}/original${ext}`;
}
/** The browser MP4 path relative to `UPLOAD_DIR`. */
/** The browser MP4 path relative to the archive folder. */
export function webStoredNameForEventVideo(
eventId: string,
videoId: string,
@@ -121,7 +121,7 @@ export function webStoredNameForEventVideo(
return `videos/${eventId}/${videoId}/web.mp4`;
}
/** A lower-resolution browser MP4 path relative to `UPLOAD_DIR`. */
/** A lower-resolution browser MP4 path relative to the archive folder. */
export function webRenditionStoredNameForEventVideo(
eventId: string,
videoId: string,
@@ -135,7 +135,7 @@ export function webRenditionStoredNameForEventVideo(
return `videos/${eventId}/${videoId}/web-${height}.mp4`;
}
/** The poster path relative to `UPLOAD_DIR`. */
/** The poster path relative to the archive folder. */
export function posterStoredNameForEventVideo(
eventId: string,
videoId: string,
@@ -145,7 +145,10 @@ export function posterStoredNameForEventVideo(
return `videos/${eventId}/${videoId}/poster.jpg`;
}
/** Resolve an NFS-relative original, refusing traversal. */
/**
* Resolve any stored video file (original, rendition, poster) inside the
* configured archive folder, refusing traversal.
*/
export function eventVideoArchivePath(
archivePath: string,
archiveFolder: string,
@@ -166,26 +169,7 @@ export function eventVideoArchivePath(
return inside(root, path.join(root, relative));
}
/** Resolve a web derivative/poster inside `UPLOAD_DIR/videos`. */
export function eventVideoUploadPath(storedName: string): string {
const root = path.resolve(UPLOAD_DIR, "videos");
const candidate = path.resolve(UPLOAD_DIR, storedName);
if (candidate === root || !candidate.startsWith(`${root}${path.sep}`)) {
throw new EventVideoPathError("invalid event video upload path");
}
return candidate;
}
/** Remove every derivative and poster for one event. */
export function eventVideoUploadDir(eventId: string): string {
safeId(eventId);
const root = path.resolve(UPLOAD_DIR, "videos");
const dir = inside(root, path.resolve(root, eventId));
if (dir === root) throw new EventVideoPathError("invalid event video path");
return dir;
}
/** Remove the NFS folder holding one original video. */
/** Remove the archive folder holding one original video and its derivatives. */
export function eventVideoArchiveDir(
archivePath: string,
archiveFolder: string,
+40
View File
@@ -0,0 +1,40 @@
import path from "node:path";
import { describe, expect, it } from "vitest";
import { archiveRootFor, MEDIA_STORAGE_RULE } from "./media-storage";
const settings = {
nfsShare: "nas.local:/volume1/church-media",
archivePath: "/srv/archive",
archiveFolder: "Glenloch Media",
};
describe("archiveRootFor", () => {
it("resolves the folder under the mounted share", () => {
expect(archiveRootFor(settings)).toBe(
path.resolve("/srv/archive", "Glenloch Media"),
);
expect(archiveRootFor({ ...settings, archiveFolder: " Media " })).toBe(
path.resolve("/srv/archive", "Media"),
);
});
it("refuses relative or escaping destinations", () => {
expect(archiveRootFor({ ...settings, archivePath: "archive" })).toBeNull();
expect(archiveRootFor({ ...settings, archiveFolder: "" })).toBeNull();
expect(archiveRootFor({ ...settings, archiveFolder: ".." })).toBeNull();
expect(archiveRootFor({ ...settings, archiveFolder: "." })).toBeNull();
expect(
archiveRootFor({ ...settings, archiveFolder: "../outside" }),
).toBeNull();
expect(
archiveRootFor({ ...settings, archiveFolder: "nested/folder" }),
).toBeNull();
});
});
describe("media storage rule", () => {
it("states that media never lives in the container", () => {
expect(MEDIA_STORAGE_RULE).toContain("media storage share");
expect(MEDIA_STORAGE_RULE).toContain("container");
});
});
+138
View File
@@ -0,0 +1,138 @@
/**
* The one place event photos and videos are allowed to live.
*
* Media is written to `<archivePath>/<archiveFolder>` on the NFS export (or
* local path) configured under Settings → Media storage. This is the primary
* home of the originals, not a backup copy. It is never written to
* container-local storage: a Docker container can be recreated at any time, and
* a church cannot lose a Sunday's photos because the volume was attached to the
* wrong thing. Every upload, edit and file read therefore resolves the archive
* root here first, and every UI that can write media asks whether it is ready.
*
* The gate needs a named share *and* a mounted, writable destination. A path
* that merely happens to exist inside the container (for example `/tmp` or a
* Docker named volume) is not enough: the admin must say which share holds the
* archive, and the folder must be usable.
*/
import { constants } from "node:fs";
import { access, mkdir, statfs } from "node:fs/promises";
import path from "node:path";
import {
checkArchiveDestination,
getStorageSettings,
type StorageSettings,
} from "@/db/storage-settings";
/** Shown wherever a media action is blocked. */
export const MEDIA_STORAGE_RULE =
"Event photos and videos are stored only on the media storage share configured in Settings → Media storage; nothing is kept inside the app container.";
export class MediaStorageError extends Error {
constructor(message: string) {
super(message);
this.name = "MediaStorageError";
}
}
export interface MediaStorageReady {
ok: true;
/** `<archivePath>/<archiveFolder>`, validated and writable. */
root: string;
settings: StorageSettings;
freeBytes: number | null;
/** Size of the filesystem holding the archive, when it can be read. */
totalBytes: number | null;
}
export interface MediaStorageBlocked {
ok: false;
message: string;
}
export type MediaStorage = MediaStorageReady | MediaStorageBlocked;
/**
* Resolve `<archivePath>/<archiveFolder>`, or null when the pair cannot describe
* a safe directory. Callers still verify the mount is writable.
*/
export function archiveRootFor(settings: StorageSettings): string | null {
const archivePath = settings.archivePath.trim();
const folder = settings.archiveFolder.trim();
if (!path.isAbsolute(archivePath)) return null;
if (
!folder ||
folder === "." ||
folder === ".." ||
/[/\\\u0000]/.test(folder)
) {
return null;
}
const root = path.resolve(archivePath, folder);
if (root === path.resolve(archivePath)) return null;
return root;
}
/**
* Whether event media can be written right now. Cheap enough to call on a page
* render: one settings read, one statfs and a writability check.
*/
export async function mediaStorage(): Promise<MediaStorage> {
const settings = await getStorageSettings();
if (!settings.nfsShare.trim()) {
return {
ok: false,
message: `No media storage share is configured. ${MEDIA_STORAGE_RULE} Ask an admin to set the NFS export or local path in Settings → Media storage.`,
};
}
const root = archiveRootFor(settings);
if (!root) {
return {
ok: false,
message:
"The media storage path or folder in Settings → Media storage is invalid. The path must be absolute and the folder must be one directory name.",
};
}
const status = await checkArchiveDestination(settings);
if (!status.ready) {
return {
ok: false,
message: `${status.message} ${MEDIA_STORAGE_RULE}`,
};
}
try {
await mkdir(root, { recursive: true });
await access(root, constants.W_OK);
} catch (error) {
const detail = error instanceof Error ? error.message : "not writable";
return {
ok: false,
message: `The media storage folder ${root} cannot be written: ${detail}. ${MEDIA_STORAGE_RULE}`,
};
}
// Report the archive folder's own filesystem, which is what photos and
// videos will consume (status above measured the mount root).
let freeBytes = status.freeBytes;
let totalBytes: number | null = null;
try {
const filesystem = await statfs(root);
freeBytes = Number(filesystem.bavail) * Number(filesystem.bsize);
totalBytes = Number(filesystem.blocks) * Number(filesystem.bsize);
} catch {
// statfs is unavailable on some platforms; the destination check is enough.
}
return { ok: true, root, settings, freeBytes, totalBytes };
}
/** Throwing form for background work that cannot return an HTTP response. */
export async function requireMediaStorage(): Promise<MediaStorageReady> {
const storage = await mediaStorage();
if (!storage.ok) throw new MediaStorageError(storage.message);
return storage;
}
+46
View File
@@ -0,0 +1,46 @@
import { describe, expect, it } from "vitest";
import {
ORPHAN_GRACE_MS,
RETENTION_DEFAULTS,
RETENTION_LIMITS,
formatBytes,
isOrphanCandidate,
isPastRetention,
retentionCutoff,
} from "./retention";
describe("retention", () => {
const now = new Date("2026-11-20T12:00:00Z");
it("puts the default notification cutoff 90 days back", () => {
expect(retentionCutoff(now, RETENTION_DEFAULTS.notificationDays)).toEqual(
new Date("2026-08-22T12:00:00Z"),
);
});
it("treats older rows as past retention and newer rows as kept", () => {
expect(isPastRetention(new Date("2026-08-22T11:59:59Z"), now, 90)).toBe(true);
expect(isPastRetention(new Date("2026-08-22T12:00:00Z"), now, 90)).toBe(false);
});
it("clamps absurd day windows instead of deleting everything", () => {
expect(retentionCutoff(now, 0)).toEqual(retentionCutoff(now, 1));
expect(retentionCutoff(now, 99_999)).toEqual(
retentionCutoff(now, RETENTION_LIMITS.maxDays),
);
});
it("keeps recent upload files out of the orphan sweep", () => {
const fresh = new Date(now.getTime() - 60 * 60 * 1000);
const stale = new Date(now.getTime() - ORPHAN_GRACE_MS - 1000);
expect(isOrphanCandidate(fresh, now)).toBe(false);
expect(isOrphanCandidate(stale, now)).toBe(true);
});
it("formats byte sizes for the admin card", () => {
expect(formatBytes(512)).toBe("512 B");
expect(formatBytes(2048)).toBe("2 KB");
expect(formatBytes(5 * 1024 * 1024)).toBe("5.0 MB");
expect(formatBytes(3 * 1024 ** 3)).toBe("3.00 GB");
});
});
+54
View File
@@ -0,0 +1,54 @@
/**
* Retention rules (pure). No database, no filesystem.
*
* Two windows cover everything that accumulates: sent mail and consumed
* single-use tokens. The job that applies them lives in `src/db/retention.ts`;
* keeping the thresholds and the date comparison here makes them testable and
* keeps the destructive code a thin loop over these decisions.
*/
export const RETENTION_DEFAULTS = {
/** Sent/failed notification rows are kept this long for the admin log. */
notificationDays: 90,
/** Consumed magic-link and respond tokens are kept this long. */
tokenDays: 30,
} as const;
export const RETENTION_LIMITS = {
minDays: 1,
maxDays: 3650,
} as const;
/** Rows older than this are eligible. `days` is clamped to a sane window. */
export function retentionCutoff(now: Date, days: number): Date {
const safe = Math.min(
Math.max(Math.floor(days), RETENTION_LIMITS.minDays),
RETENTION_LIMITS.maxDays,
);
return new Date(now.getTime() - safe * 24 * 60 * 60 * 1000);
}
export function isPastRetention(at: Date, now: Date, days: number): boolean {
return at.getTime() < retentionCutoff(now, days).getTime();
}
/**
* Files are only considered orphans after a grace period, so an upload that is
* being written right now (row not inserted yet) is never swept.
*/
export const ORPHAN_GRACE_MS = 24 * 60 * 60 * 1000;
export function isOrphanCandidate(
modifiedAt: Date,
now: Date,
graceMs = ORPHAN_GRACE_MS,
): boolean {
return now.getTime() - modifiedAt.getTime() > graceMs;
}
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
if (bytes < 1024 ** 3) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
return `${(bytes / 1024 ** 3).toFixed(2)} GB`;
}
+4 -3
View File
@@ -1,7 +1,8 @@
/**
* Upload storage helpers. Files are written under `UPLOAD_DIR`
* (default `/tmp/uploads`, a named Docker volume in the deployment) and only
* metadata is stored in Postgres.
* Training-attachment storage. Files are written under `UPLOAD_DIR` (default
* `/tmp/uploads`, a named Docker volume in the deployment) and only metadata is
* stored in Postgres. Event photos and videos use the configured media storage
* instead (see `media-storage.ts`); they are never written here.
*/
import path from "node:path";
+15 -4
View File
@@ -16,7 +16,6 @@ import {
} from "@/db/videos";
import {
eventVideoArchivePath,
eventVideoUploadPath,
posterStoredNameForEventVideo,
webRenditionStoredNameForEventVideo,
webStoredNameForEventVideo,
@@ -36,11 +35,21 @@ export async function processEventVideo(videoId: string): Promise<void> {
video.eventId,
video.id,
);
const webPath = eventVideoUploadPath(webStoredName);
const posterPath = eventVideoUploadPath(posterStoredName);
try {
const storage = await getStorageSettings();
// Originals, renditions and posters all sit in the video's folder on the
// media storage share. Derivatives never touch container-local storage.
const webPath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
webStoredName,
);
const posterPath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
posterStoredName,
);
const originalPath = eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
@@ -71,7 +80,9 @@ export async function processEventVideo(videoId: string): Promise<void> {
outputPath:
index === 0
? webPath
: eventVideoUploadPath(
: eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
webRenditionStoredNameForEventVideo(
video.eventId,
video.id,
+1 -1
View File
@@ -267,7 +267,7 @@ export async function renderVideoDerivative(input: {
}): Promise<void> {
const source = await stat(input.inputPath).catch(() => null);
if (!source?.isFile()) {
throw new VideoRenderError("The original video is missing from the NFS archive.");
throw new VideoRenderError("The original video is missing from media storage.");
}
const trimStartMs = Math.max(0, Math.min(input.trimStartMs, input.durationMs - 1));
+7 -2
View File
@@ -7,8 +7,9 @@
*/
import { stat } from "node:fs/promises";
import { getStorageSettings } from "@/db/storage-settings";
import {
eventVideoUploadPath,
eventVideoArchivePath,
webRenditionStoredNameForEventVideo,
} from "@/lib/event-videos";
import { renditionHeightsForSource } from "@/lib/video-quality";
@@ -16,6 +17,7 @@ import { renditionHeightsForSource } from "@/lib/video-quality";
export async function availableRenditionHeights(video: {
id: string;
eventId: string;
archiveFolder: string;
height: number | null;
webStoredName: string | null;
status: "processing" | "ready" | "failed";
@@ -23,11 +25,14 @@ export async function availableRenditionHeights(video: {
const heights = renditionHeightsForSource(video.height ?? 1080);
if (video.status !== "ready" || !video.webStoredName) return [];
const storage = await getStorageSettings();
const lower = await Promise.all(
heights.slice(1).map(async (height) => {
try {
const info = await stat(
eventVideoUploadPath(
eventVideoArchivePath(
storage.archivePath,
video.archiveFolder,
webRenditionStoredNameForEventVideo(
video.eventId,
video.id,