push to maple-street

This commit is contained in:
Tiel Coder
2026-11-20 04:07:02 +00:00
parent 2cec220a24
commit 5adf1cef1f
345 changed files with 86105 additions and 1079 deletions
+289
View File
@@ -0,0 +1,289 @@
import { redirect } from "next/navigation";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listUsersForAdmin } from "@/db/users";
import { listSkillsMatrix } from "@/db/assessments";
import { getPositionSkills, listPositions, listSkills } from "@/db/positions";
import { listServices } from "@/db/services";
import { listNotifications } from "@/db/outbox";
import { listRules } from "@/db/reminders";
import { getEmailSettings } from "@/db/settings";
import { ASSESSMENT_KINDS, USER_STATUSES } from "@/db/schema";
import { SYSTEM_ROLES } from "@/auth/roles";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import {
PeoplePanel,
type ManagedUser,
} from "@/components/app/admin/people-panel";
import { ServicesPanel } from "@/components/app/admin/services-panel";
import { RemindersPanel } from "@/components/app/admin/reminders-panel";
import {
NotificationsPanel,
type NotificationRow,
} from "@/components/app/admin/notifications-panel";
import { EmailPanel } from "@/components/app/admin/email-panel";
import { BackupPanel } from "@/components/app/admin/backup-panel";
import {
SkillsMatrixPanel,
type MatrixRow,
} from "@/components/app/admin/skills-matrix-panel";
import {
PositionsPanel,
type PositionSummary,
type RequirementDraft,
} from "@/components/app/admin/positions-panel";
export const metadata = { title: "Admin" };
function stamp(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
month: "short",
day: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
/**
* Admin hub. Server-rendered data, client action panels:
* - People: invite + approve/deny (B1)
* - Skill levels: the competency matrix + verify-level form (C3)
* - Positions: seats and their requirements editor (B4)
* - Services: recurring templates + the idempotent instance generator (D1/D2)
* - Reminder rules: offset sends used at publish time (E7)
* - Notification log: outbox state, retry, send-test (E6)
*
* Guarded by `admin.settings`, the admin-only permission; coordinators and
* volunteers are sent back to the schedule.
*/
export default async function AdminPage() {
const session = await auth();
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 requirementSets = await Promise.all(
positions.map((position) => getPositionSkills(position.id)),
);
const requirementsByPosition: Record<string, RequirementDraft[]> = {};
positions.forEach((position, index) => {
requirementsByPosition[position.id] = requirementSets[index].map((row) => ({
skillId: row.skillId,
weight: row.weight,
requiredLevel: row.requiredLevel,
isCore: row.isCore,
}));
});
const matrixRows: MatrixRow[] = matrix.map((row) => ({
userId: row.userId,
userName: row.userName,
email: row.email,
skillId: row.skillId,
skillName: row.skillName,
categoryName: row.categoryName ?? "Uncategorized",
selfComfort: row.selfComfort,
verifiedLevel: row.verifiedLevel,
lastServedOn: row.lastServedOn ?? null,
}));
const managedUsers: ManagedUser[] = users.map((user) => ({
id: user.id,
email: user.email,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
displayName: user.displayName,
systemRole: user.systemRole,
status: user.status,
phoneE164: user.phoneE164,
timezone: user.timezone,
emergencyContact: user.emergencyContact,
notes: user.notes,
deactivatedAt: user.deactivatedAt ? user.deactivatedAt.toISOString() : null,
passwordSet: user.passwordSet,
}));
const positionRows: PositionSummary[] = positions.map((position) => ({
id: position.id,
name: position.name,
defaultHeadcount: position.defaultHeadcount,
callTimeOffsetMinutes: position.callTimeOffsetMinutes,
active: position.active,
}));
const rows: NotificationRow[] = log.map((n) => ({
id: n.id,
templateKey: n.templateKey,
subject: typeof n.payload.subject === "string" ? n.payload.subject : null,
toAddress: n.toAddress,
status: n.status,
attempts: n.attempts,
scheduledFor: stamp(n.scheduledFor),
sentAt: n.sentAt ? stamp(n.sentAt) : null,
error: n.error,
}));
return (
<div className="space-y-6">
<div>
<h1 className="text-lg font-semibold tracking-tight">Admin</h1>
<p className="text-sm text-muted-foreground">
People, competency, positions, and outbound messages for the media
team.
</p>
</div>
<Card>
<CardHeader>
<CardTitle className="text-lg">People</CardTitle>
<CardDescription>
Add people, approve pending sign-ups, and edit every profile and
access field. Deactivate to keep a person&apos;s history; delete only
removes accounts with no scheduling history.
</CardDescription>
</CardHeader>
<CardContent>
<PeoplePanel
users={managedUsers}
roles={SYSTEM_ROLES}
statuses={USER_STATUSES}
skills={skillRows.map((skill) => ({ id: skill.id, name: skill.name }))}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Skill levels</CardTitle>
<CardDescription>
Who is signed off on what. Verifying records who moved the level and
why; the volunteer&apos;s own comfort rating is never changed here.
</CardDescription>
</CardHeader>
<CardContent>
<SkillsMatrixPanel rows={matrixRows} kinds={ASSESSMENT_KINDS} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Positions &amp; requirements</CardTitle>
<CardDescription>
The seats each service needs and the skills they require. A position
saved as publishable needs at least one core skill.
</CardDescription>
</CardHeader>
<CardContent>
<PositionsPanel
positions={positionRows}
skills={skillRows.map((skill) => ({ id: skill.id, name: skill.name }))}
requirementsByPosition={requirementsByPosition}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Services &amp; schedule</CardTitle>
<CardDescription>
Recurring service templates, and instance generation for the weeks
volunteers will be scheduled into.
</CardDescription>
</CardHeader>
<CardContent>
<ServicesPanel
services={services.map((service) => ({
id: service.id,
name: service.name,
startTimeLocal: service.startTimeLocal,
durationMinutes: service.durationMinutes,
location: service.location ?? null,
active: service.active,
}))}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Reminder rules</CardTitle>
<CardDescription>
Offsets are relative to each service or event start; negative days
are before. Service reminders are queued when a week is published,
event reminders by the notification cron. Every offset and time is
editable.
</CardDescription>
</CardHeader>
<CardContent>
<RemindersPanel rules={rules} />
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Email delivery</CardTitle>
<CardDescription>
Send through the team&apos;s Gmail account with an app password.
Nothing is stored in plain text, and the password is never shown
again after saving.
</CardDescription>
</CardHeader>
<CardContent>
<EmailPanel
emailFrom={emailSettings.emailFrom}
notificationEmail={emailSettings.notificationEmail}
smtpUser={emailSettings.smtpUser}
smtpConfigured={emailSettings.smtpConfigured}
/>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg">Backup &amp; restore</CardTitle>
<CardDescription>
Download every database record and uploaded file in one portable
ZIP, or restore a backup after a redeploy. Restores are admin-only
and require an explicit confirmation.
</CardDescription>
</CardHeader>
<CardContent>
<BackupPanel />
</CardContent>
</Card>
<Card id="notifications">
<CardHeader>
<CardTitle className="text-lg">Notifications</CardTitle>
<CardDescription>
The outbox log, newest first, with retry for anything that failed.
</CardDescription>
</CardHeader>
<CardContent>
<NotificationsPanel rows={rows} />
</CardContent>
</Card>
</div>
);
}
+47 -10
View File
@@ -1,16 +1,53 @@
import { StateMessage } from "@/components/app/state-message";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listAnnouncements } from "@/db/announcements";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import {
AnnouncementsPanel,
type AnnouncementItem,
} from "@/components/app/announcements-panel";
export const metadata = { title: "Announcements" };
export default function AnnouncementsPage() {
/**
* Team feed. Published posts are visible to every signed-in volunteer; authors
* (`content.author` = admin/coordinator) see drafts and can create, publish and
* delete. Admin access to the authoring controls lives here rather than a
* duplicate panel in the admin hub.
*/
export default async function AnnouncementsPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)
?.systemRole;
const canEdit = hasPermission(role, "content.author");
const rows = await listAnnouncements({ includeUnpublished: canEdit });
const announcements: AnnouncementItem[] = rows.map((row) => ({
id: row.id,
title: row.title,
body: row.body,
published: row.published,
authorName: row.authorName,
createdLabel: formatInTimezone(row.createdAt, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
}),
}));
return (
<>
<h1 className="text-lg font-semibold tracking-tight">Announcements</h1>
<p className="text-sm text-muted-foreground">News and notes from the media team.</p>
<StateMessage
title="No announcements"
description="Team announcements will appear here as rich-text posts."
/>
</>
<div className="space-y-4">
<div>
<h1 className="text-lg font-semibold tracking-tight">Announcements</h1>
<p className="text-sm text-muted-foreground">
News and notes from the media team.
</p>
</div>
<AnnouncementsPanel announcements={announcements} canEdit={canEdit} />
</div>
);
}
+126
View File
@@ -0,0 +1,126 @@
import Link from "next/link";
import { AlertTriangle } from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listUnavailability } from "@/db/unavailability";
import {
activeTeamBlackouts,
upcomingServesForUser,
} from "@/db/volunteer";
import { isUnavailable, type UnavailabilityRecord } from "@/domain/availability";
import { formatInTimezone, CHURCH_TIMEZONE } from "@/lib/tz";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
AvailabilityManager,
type BlackoutRow,
} from "@/components/app/availability/availability-manager";
export const metadata = { title: "Availability" };
export default async function AvailabilityPage() {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) return null;
const [rows, upcoming] = await Promise.all([
listUnavailability({ userId: user.id }),
upcomingServesForUser(user.id, 20),
]);
const active = rows.filter((row) => row.status === "active");
const records = active as unknown as UnavailabilityRecord[];
const conflicts = upcoming.filter((serve) => isUnavailable(records, serve.occursOn));
const canManage = hasPermission(user.systemRole, "schedule.publish");
const team = canManage ? await activeTeamBlackouts() : [];
const initialRows: BlackoutRow[] = active.map((row) => ({
id: row.id,
kind: row.kind,
startsOn: row.startsOn,
endsOn: row.endsOn,
reason: row.reason,
rrule: row.rrule,
}));
return (
<div className="space-y-5">
<div>
<h1 className="text-lg font-semibold tracking-tight">Availability</h1>
<p className="text-sm text-muted-foreground">
Add vacations, work trips, and recurring commitments. Coordinators see
these dates when building the schedule.
</p>
</div>
{conflicts.length > 0 && (
<div className="rounded-md border border-amber-500/40 bg-amber-500/10 p-4 text-sm">
<p className="flex items-center gap-2 font-semibold text-amber-900 dark:text-amber-200">
<AlertTriangle className="h-4 w-4" aria-hidden="true" />
You have {conflicts.length} assignment
{conflicts.length === 1 ? "" : "s"} inside an unavailable range
</p>
<ul className="mt-2 space-y-1 text-amber-900/90 dark:text-amber-100/90">
{conflicts.map((serve) => (
<li key={serve.assignmentId}>
{serve.roleName} · {serve.serviceName} —{" "}
{formatInTimezone(serve.startsAt, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "short",
month: "short",
day: "numeric",
})}{" "}
·{" "}
<Link href="/schedule" className="font-medium underline">
review the schedule
</Link>
</li>
))}
</ul>
</div>
)}
<AvailabilityManager userId={user.id} rows={initialRows} />
{canManage && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Team availability</CardTitle>
<p className="text-xs text-muted-foreground">
Active blackouts across the roster, soonest first.
</p>
</CardHeader>
<CardContent>
{team.length === 0 ? (
<p className="text-sm text-muted-foreground">
No active blackout dates on the team.
</p>
) : (
<ul className="divide-y divide-border">
{team.map((row) => (
<li
key={row.id}
className="flex flex-wrap items-start justify-between gap-2 py-2 first:pt-0 last:pb-0"
>
<div>
<p className="text-sm font-medium">{row.displayName}</p>
<p className="text-xs text-muted-foreground">
{row.startsOn === row.endsOn
? row.startsOn
: `${row.startsOn} → ${row.endsOn}`}
{row.reason ? ` · ${row.reason}` : ""}
</p>
</div>
<Badge variant="outline">{row.kind}</Badge>
</li>
))}
</ul>
)}
</CardContent>
</Card>
)}
</div>
);
}
+108
View File
@@ -0,0 +1,108 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { Download, Printer } from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listPendingCoverageRequests } from "@/db/coverage";
import { listCoverageIntakes } from "@/db/intake";
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
import { Button } from "@/components/ui/button";
import {
CoverageBoard,
type CoverageRequestView,
type IntakeView,
} from "@/components/app/coverage/coverage-board";
export const metadata = { title: "Coverage" };
export default async function CoveragePage() {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) return null;
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
const [requests, intakes] = await Promise.all([
listPendingCoverageRequests(),
listCoverageIntakes("new"),
]);
const views: CoverageRequestView[] = await Promise.all(
requests.map(async (request) => {
const ranked = await rankedCandidatesForSlot(request.slotId);
return {
id: request.id,
assignmentId: request.assignmentId,
slotId: request.slotId,
roleName: request.roleName,
serviceName: request.serviceName,
startsAt: request.startsAt,
callTime: request.callTime,
location: request.location,
reason: request.reason,
requesterName: request.requesterName,
requesterEmail: request.requesterEmail,
eligible: (ranked?.eligible ?? []).map((candidate) => ({
userId: candidate.userId,
displayName: candidate.displayName,
score: candidate.score,
warnings: candidate.warnings,
})),
excludedCount: ranked?.excluded.length ?? 0,
};
}),
);
const intakeViews: IntakeView[] = intakes.map((intake) => ({
id: intake.id,
title: intake.title,
requesterName: intake.requesterName,
requesterEmail: intake.requesterEmail,
ministry: intake.ministry,
startsAt: intake.startsAt,
location: intake.location,
description: intake.description,
}));
return (
<div className="space-y-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-lg font-semibold tracking-tight">Coverage</h1>
<p className="text-sm text-muted-foreground">
Approve swaps, release seats, and turn church requests into events.
</p>
</div>
<div className="flex flex-wrap gap-2 print:hidden">
<Button asChild variant="outline" size="sm">
<a href="/api/export/schedule">
<Download aria-hidden="true" /> Schedule CSV
</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href="/api/export/history">
<Download aria-hidden="true" /> History CSV
</a>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/schedule/print">
<Printer aria-hidden="true" /> Print roster
</Link>
</Button>
</div>
</div>
<CoverageBoard requests={views} intakes={intakeViews} />
<p className="text-xs text-muted-foreground">
Share the public request form at{" "}
<Link href="/request-coverage" className="font-medium underline">
/request-coverage
</Link>
. It does not require an account.
</p>
</div>
);
}
+301
View File
@@ -0,0 +1,301 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import {
AlertTriangle,
ArrowRight,
CalendarCheck,
CalendarX,
CircleHelp,
MailWarning,
UserCheck,
Users,
} from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { coverageGaps, dashboardSnapshot } from "@/db/dashboard";
import { CHURCH_TIMEZONE, formatInTimezone, weekStartOn } from "@/lib/tz";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
export const metadata = { title: "Coverage dashboard" };
function dateLabel(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "short",
month: "short",
day: "numeric",
});
}
function Stat({
label,
value,
detail,
tone = "normal",
}: {
label: string;
value: number;
detail: string;
tone?: "normal" | "warning";
}) {
return (
<Card>
<CardContent className="p-4">
<p className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
{label}
</p>
<p
className={`mt-1 text-2xl font-semibold ${
tone === "warning" ? "text-amber-700 dark:text-amber-300" : ""
}`}
>
{value}
</p>
<p className="mt-1 text-xs text-muted-foreground">{detail}</p>
</CardContent>
</Card>
);
}
export default async function DashboardPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)
?.systemRole;
if (!hasPermission(role, "schedule.publish")) redirect("/home");
const [snapshot, gaps] = await Promise.all([
dashboardSnapshot(),
coverageGaps(6),
]);
const next = snapshot.nextService;
return (
<div className="space-y-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-lg font-semibold tracking-tight">
Coverage dashboard
</h1>
<p className="text-sm text-muted-foreground">
The next five weeks at a glance, plus the queues that need a
coordinator.
</p>
</div>
<Button asChild size="sm" variant="outline">
<Link href="/schedule">
Open schedule <ArrowRight aria-hidden="true" />
</Link>
</Button>
</div>
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
<Stat
label="Seats filled"
value={snapshot.filled}
detail={`of ${snapshot.seats} seats in the next five weeks`}
/>
<Stat
label="Open seats"
value={snapshot.open}
detail={snapshot.open > 0 ? "Needs a volunteer" : "All seats covered"}
tone={snapshot.open > 0 ? "warning" : "normal"}
/>
<Stat
label="Unconfirmed"
value={snapshot.proposed}
detail="Proposed assignments waiting for a response"
tone={snapshot.proposed > 0 ? "warning" : "normal"}
/>
<Stat
label="Pending people"
value={snapshot.pendingApprovals}
detail={`${snapshot.activePeople} active team members`}
tone={snapshot.pendingApprovals > 0 ? "warning" : "normal"}
/>
</div>
<div className="grid gap-5 lg:grid-cols-[minmax(0,1fr)_360px]">
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<CalendarCheck className="h-4 w-4" aria-hidden="true" />
Next service
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{next ? (
<>
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<p className="text-lg font-semibold">{next.serviceName}</p>
<p className="text-sm text-muted-foreground">
{dateLabel(next.startsAt)} ·{" "}
{formatInTimezone(next.startsAt, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
hour: "numeric",
minute: "2-digit",
})}
</p>
</div>
<Badge variant={next.status === "published" ? "default" : "secondary"}>
{next.status}
</Badge>
</div>
<div className="flex flex-wrap gap-4 text-sm">
<span>
<strong>{next.filled}</strong> / {next.seats} filled
</span>
<span className="text-muted-foreground">
{Math.max(0, next.seats - next.filled)} open
</span>
{snapshot.unconfirmedNext > 0 && (
<span className="text-amber-700 dark:text-amber-300">
{snapshot.unconfirmedNext} unconfirmed
</span>
)}
</div>
<Button asChild variant="outline" size="sm">
<Link
href={`/schedule?week=${weekStartOn(next.occursOn, CHURCH_TIMEZONE)}`}
>
Build this service
</Link>
</Button>
</>
) : (
<p className="text-sm text-muted-foreground">
No service instances in the next five weeks. Generate instances
from Admin → Services.
</p>
)}
</CardContent>
</Card>
<div className="space-y-3">
<Card>
<CardContent className="space-y-3 p-4">
<p className="flex items-center gap-2 text-sm font-semibold">
<CalendarX className="h-4 w-4" aria-hidden="true" />
Event coverage
</p>
<p className="text-sm text-muted-foreground">
{snapshot.upcomingEvents} upcoming event
{snapshot.upcomingEvents === 1 ? "" : "s"} ·{" "}
{snapshot.eventsNeedingPhotographer} without a lead photographer
</p>
<Link
href="/events"
className="inline-flex items-center gap-1 text-sm font-medium text-primary underline"
>
Review events <ArrowRight className="h-3.5 w-3.5" />
</Link>
</CardContent>
</Card>
<Card>
<CardContent className="space-y-3 p-4">
<p className="flex items-center gap-2 text-sm font-semibold">
<MailWarning className="h-4 w-4" aria-hidden="true" />
Notification health
</p>
<p className="text-sm text-muted-foreground">
{snapshot.failedNotifications === 0
? "No failed messages."
: `${snapshot.failedNotifications} failed message${
snapshot.failedNotifications === 1 ? "" : "s"
} need attention.`}
</p>
<Link
href="/admin#notifications"
className="inline-flex items-center gap-1 text-sm font-medium text-primary underline"
>
Open notification log <ArrowRight className="h-3.5 w-3.5" />
</Link>
</CardContent>
</Card>
</div>
</div>
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<CircleHelp className="h-4 w-4" aria-hidden="true" />
Seats that still need someone
</CardTitle>
</CardHeader>
<CardContent>
{gaps.length === 0 ? (
<p className="text-sm text-muted-foreground">
Every seat in the next five weeks is filled. Nice work.
</p>
) : (
<ul className="divide-y divide-border">
{gaps.map((gap) => (
<li
key={gap.id}
className="flex flex-wrap items-center justify-between gap-2 py-2 first:pt-0 last:pb-0"
>
<div>
<p className="text-sm font-medium">{gap.serviceName}</p>
<p className="text-xs text-muted-foreground">
{dateLabel(gap.startsAt)}
</p>
</div>
<div className="flex items-center gap-2">
<Badge variant="outline">
{gap.seats - gap.filled} open
</Badge>
<Link
href={`/schedule?week=${weekStartOn(gap.occursOn, CHURCH_TIMEZONE)}`}
className="text-xs font-medium text-primary underline"
>
Fill
</Link>
</div>
</li>
))}
</ul>
)}
</CardContent>
</Card>
<div className="flex flex-wrap gap-2">
<Button asChild variant="outline" size="sm">
<Link href="/coverage">Coverage requests</Link>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/schedule/print">Print roster</Link>
</Button>
<Button asChild variant="outline" size="sm">
<a href="/api/export/schedule">Schedule CSV</a>
</Button>
<Button asChild variant="outline" size="sm">
<a href="/api/export/history">Serving history CSV</a>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/admin">
<UserCheck aria-hidden="true" /> People &amp; admin
</Link>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/availability">
<Users aria-hidden="true" /> Team availability
</Link>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/schedule?view=month">
<AlertTriangle aria-hidden="true" /> Month overview
</Link>
</Button>
</div>
</div>
);
}
@@ -0,0 +1,102 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getFolderDetail } from "@/db/events";
import {
isBrowserRenderablePhoto,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { Badge } from "@/components/ui/badge";
import {
PhotoGallery,
type GalleryPhoto,
} from "@/components/app/events/photo-gallery";
const KIND_LABELS: Record<string, string> = {
originals: "RAW / originals",
edited: "Edited exports",
mixed: "Mixed",
};
function sizeLabel(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
/**
* A folder's gallery. Every assigned photographer can see and download every
* file; only the uploader or an event manager can delete one.
*/
export default async function EventFolderPage({
params,
}: {
params: Promise<{ id: string; folderId: string }>;
}) {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) redirect("/login");
const { id, folderId } = await params;
const detail = await getFolderDetail(folderId, user.id, user.systemRole);
if (!detail || detail.event.id !== id) notFound();
const photos: GalleryPhoto[] = detail.photos.map((photo) => ({
id: photo.id,
filename: photo.filename,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
uploaderId: photo.uploaderId,
uploaderName: photo.uploaderName,
previewable: isBrowserRenderablePhoto(photo.filename),
editable: isEditableEventPhoto(photo.filename),
adjustments: parseStoredPhotoAdjustments(photo.editJson),
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
editedSizeBytes: photo.editedSizeBytes,
}));
return (
<div className="space-y-5">
<div>
<Link
href={`/events/${detail.event.id}`}
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
{detail.event.title}
</Link>
</div>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">
{detail.folder.name}
</h1>
<p className="text-sm text-muted-foreground">
{detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "}
· {sizeLabel(detail.folder.totalBytes)}
</p>
</div>
<Badge variant="secondary">
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
</Badge>
</div>
<PhotoGallery
eventId={detail.event.id}
folderId={detail.folder.id}
photos={photos}
canContribute={detail.canContribute}
canManage={detail.canManage}
currentUserId={user.id}
/>
</div>
);
}
+325
View File
@@ -0,0 +1,325 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, Camera, Download, Film, FolderOpen, MapPin, Play } from "lucide-react";
import { auth } from "@/auth/config";
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 { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
PhotographerPanel,
type EventPhotographer,
} from "@/components/app/events/photographer-panel";
import { FolderCreateForm } from "@/components/app/events/folder-create-form";
import { DeleteEventButton } from "@/components/app/events/delete-event-button";
import { ArchiveEventButton } from "@/components/app/events/archive-event-button";
import { VideoUploadForm } from "@/components/app/media/video-upload-form";
import { Button } from "@/components/ui/button";
const KIND_LABELS: Record<string, string> = {
originals: "RAW / originals",
edited: "Edited exports",
mixed: "Mixed",
};
function when(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "long",
month: "long",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
function sizeLabel(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
/**
* One event: brief, assigned photographers, and the shared folders. Managers
* assign people; any assignee can create folders. Folder pages own uploads;
* the event header downloads every photo as one ZIP.
*/
export default async function EventDetailPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) redirect("/login");
const { id } = await params;
const event = await getEventDetail(id, user.id, user.systemRole);
if (!event) notFound();
const users = event.canManage ? await listAssignableUsers() : [];
const archiveSettings = await getStorageSettings();
const archiveStatus = await checkArchiveDestination(archiveSettings);
const videos = await listEventVideos(event.event.id);
const photographers: EventPhotographer[] = event.event.photographers.map(
(person) => ({
userId: person.userId,
name: person.name,
email: person.email,
role: person.role,
}),
);
return (
<div className="space-y-6">
<div>
<Link
href="/events"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
All events
</Link>
</div>
<div className="space-y-2">
<div className="flex flex-wrap items-center gap-2">
<h1 className="text-xl font-semibold tracking-tight">
{event.event.title}
</h1>
<Badge variant="outline">{event.event.eventType}</Badge>
<div className="ml-auto flex flex-wrap items-center justify-end gap-2">
{event.event.photoCount > 0 && (
<Button asChild variant="outline" size="sm">
<a href={`/api/events/${event.event.id}/download`}>
<Download className="h-3.5 w-3.5" aria-hidden="true" />
Download all ({event.event.photoCount})
</a>
</Button>
)}
{event.canManage && archiveStatus.ready && (
<ArchiveEventButton
eventId={event.event.id}
title={event.event.title}
photoCount={event.event.photoCount}
archivePath={archiveSettings.archivePath}
/>
)}
{event.canManage && (
<DeleteEventButton
eventId={event.event.id}
title={event.event.title}
/>
)}
</div>
</div>
<p className="text-sm text-muted-foreground">
{when(event.event.startsAt)}
</p>
{event.event.location && (
<p className="flex items-center gap-1 text-sm text-muted-foreground">
<MapPin className="h-3.5 w-3.5" aria-hidden="true" />
{event.event.location}
</p>
)}
{event.event.description && (
<p className="max-w-3xl whitespace-pre-line text-sm">
{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.
</p>
)}
</div>
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<Camera className="h-4 w-4" aria-hidden="true" />
Photographers
</CardTitle>
</CardHeader>
<CardContent>
<PhotographerPanel
eventId={event.event.id}
photographers={photographers}
users={users.map((person) => ({
id: person.id,
name: person.name,
email: person.email,
}))}
canManage={event.canManage}
/>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<FolderOpen className="h-4 w-4" aria-hidden="true" />
Folders
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
{event.folders.length === 0 ? (
<p className="text-sm text-muted-foreground">
No folders yet. Create one for originals, dumps, or edited selects.
</p>
) : (
<ul className="grid gap-3 sm:grid-cols-2">
{event.folders.map((folder) => (
<li key={folder.id}>
<Link
href={`/events/${event.event.id}/folders/${folder.id}`}
className="block rounded-md border border-border p-3 transition-colors hover:border-primary/60 hover:bg-muted/30"
>
<div className="flex items-start justify-between gap-2">
<p className="truncate text-sm font-medium">
{folder.name}
</p>
<Badge variant="secondary">
{KIND_LABELS[folder.kind] ?? folder.kind}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
{folder.photoCount} photo
{folder.photoCount === 1 ? "" : "s"} ·{" "}
{sizeLabel(folder.totalBytes)}
</p>
</Link>
</li>
))}
</ul>
)}
{event.canContribute ? (
<FolderCreateForm eventId={event.event.id} />
) : (
<p className="text-xs text-muted-foreground">
Only assigned photographers, coordinators and admins can add
folders or upload.
</p>
)}
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<Film className="h-4 w-4" aria-hidden="true" />
Videos
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
{videos.length === 0 ? (
<p className="text-sm text-muted-foreground">
No videos yet. The camera original is archived on NFS and a web
MP4 is generated for playback.
</p>
) : (
<ul className="grid gap-3 sm:grid-cols-2">
{videos.map((video) => {
const version = (
video.processedAt ?? video.updatedAt
).getTime();
return (
<li key={video.id}>
<Link
href={`/media/${video.id}`}
className="group block overflow-hidden rounded-md border border-border transition-colors hover:border-primary/60"
>
<div className="relative aspect-video bg-black">
{video.posterStoredName ? (
// Frames are private; the serving route applies the
// event access check.
// eslint-disable-next-line @next/next/no-img-element
<img
src={`/api/media/${video.id}/poster?v=${version}`}
alt=""
loading="lazy"
className="h-full w-full object-cover opacity-90 group-hover:opacity-100"
/>
) : (
<div className="flex h-full items-center justify-center text-white/50">
<Film className="h-8 w-8" aria-hidden="true" />
</div>
)}
<span className="absolute bottom-2 right-2 rounded bg-black/75 px-1.5 py-0.5 font-mono text-[11px] text-white">
{formatVideoDuration(video.durationMs)}
</span>
{video.status === "processing" && (
<span className="absolute left-2 top-2 rounded bg-black/75 px-1.5 py-0.5 text-[10px] font-medium text-white">
Processing
</span>
)}
{video.status === "failed" && (
<span className="absolute left-2 top-2 rounded bg-destructive px-1.5 py-0.5 text-[10px] font-medium text-destructive-foreground">
Failed
</span>
)}
{video.status === "ready" && (
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
<span className="flex h-10 w-10 items-center justify-center rounded-full bg-black/70 text-white">
<Play className="h-4 w-4 fill-current" aria-hidden="true" />
</span>
</span>
)}
</div>
<div className="space-y-0.5 p-2.5">
<p className="truncate text-sm font-medium">
{video.title}
</p>
<p className="text-[11px] text-muted-foreground">
{video.visibility === "team"
? "Media team only"
: video.visibility === "unlisted"
? "Unlisted link"
: "Public"}{" "}
· {sizeLabel(video.sizeBytes)} original
</p>
</div>
</Link>
</li>
);
})}
</ul>
)}
{event.canContribute && (
<VideoUploadForm
events={[{ id: event.event.id, title: event.event.title }]}
canManage={event.canManage}
archiveReady={archiveStatus.ready}
defaultEventId={event.event.id}
compact
/>
)}
{!event.canContribute && (
<p className="text-xs text-muted-foreground">
Only assigned photographers, coordinators and admins can upload
videos.
</p>
)}
</CardContent>
</Card>
</div>
);
}
+148
View File
@@ -0,0 +1,148 @@
import Link from "next/link";
import { CalendarDays, MapPin, Users } from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listEventsForUser } from "@/db/events";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { Badge } from "@/components/ui/badge";
import { StateMessage } from "@/components/app/state-message";
import { EventCreateForm } from "@/components/app/events/event-create-form";
export const metadata = { title: "Events" };
function when(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "2-digit",
});
}
function EventCard({
event,
}: {
event: Awaited<ReturnType<typeof listEventsForUser>>[number];
}) {
return (
<Link
href={`/events/${event.id}`}
className="block rounded-md border border-border p-4 transition-colors hover:border-primary/60 hover:bg-muted/30"
>
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<h2 className="truncate text-sm font-semibold">{event.title}</h2>
<p className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
<CalendarDays className="h-3.5 w-3.5" aria-hidden="true" />
{when(event.startsAt)}
</p>
{event.location && (
<p className="mt-1 flex items-center gap-1 text-xs text-muted-foreground">
<MapPin className="h-3.5 w-3.5" aria-hidden="true" />
{event.location}
</p>
)}
</div>
<Badge variant="outline">{event.eventType}</Badge>
</div>
<div className="mt-3 flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span className="flex items-center gap-1">
<Users className="h-3.5 w-3.5" aria-hidden="true" />
{event.photographers.length} assigned
</span>
<span>
{event.folderCount} folder{event.folderCount === 1 ? "" : "s"}
</span>
<span>
{event.photoCount} photo{event.photoCount === 1 ? "" : "s"}
</span>
</div>
</Link>
);
}
/**
* Event photography hub. Managers (coordinators/admins) see every event and
* can create one; photographers see only events they are assigned to. Opening
* an event shows its shared folders, where any assignee can upload originals and
* download someone else's files to edit.
*/
export default async function EventsPage() {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
const role = user?.systemRole;
const events = await listEventsForUser(user?.id ?? "", role);
const canManage = hasPermission(role, "schedule.publish");
const now = Date.now();
const upcoming = events
.filter((event) => event.startsAt.getTime() >= now)
.sort((a, b) => a.startsAt.getTime() - b.startsAt.getTime());
const past = events.filter((event) => event.startsAt.getTime() < now);
return (
<div className="space-y-6">
<div>
<h1 className="text-lg font-semibold tracking-tight">Events</h1>
<p className="text-sm text-muted-foreground">
Photographers assigned to an event share originals and edited files in
its folders. Anyone assigned can download from the folder to edit.
</p>
</div>
{canManage && (
<details open className="rounded-md border border-border p-4">
<summary className="cursor-pointer text-sm font-medium">
Create an event
</summary>
<div className="mt-3">
<EventCreateForm />
</div>
</details>
)}
{events.length === 0 ? (
<StateMessage
title="No events yet"
description={
canManage
? "Create an event, then assign the photographers who will cover it."
: "A coordinator will assign you to an event. It will appear here."
}
/>
) : (
<div className="space-y-8">
{upcoming.length > 0 && (
<section className="space-y-3">
<h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Upcoming
</h2>
<div className="grid gap-3 md:grid-cols-2">
{upcoming.map((event) => (
<EventCard key={event.id} event={event} />
))}
</div>
</section>
)}
{past.length > 0 && (
<section className="space-y-3">
<h2 className="text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Past
</h2>
<div className="grid gap-3 md:grid-cols-2">
{past.map((event) => (
<EventCard key={event.id} event={event} />
))}
</div>
</section>
)}
</div>
)}
</div>
);
}
+310
View File
@@ -0,0 +1,310 @@
import Link from "next/link";
import {
ArrowRight,
CalendarDays,
CalendarPlus,
ClipboardCheck,
MapPin,
UserRound,
} from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { getUserById } from "@/db/users";
import {
pastServesForUser,
upcomingEventAssignmentsForUser,
upcomingServesForUser,
} from "@/db/volunteer";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { AssignmentActions } from "@/components/app/assignment-actions";
import { CoverageRequestButton } from "@/components/app/coverage/coverage-request-button";
import { coverageRequestsForUser } from "@/db/coverage";
export const metadata = { title: "Home" };
function when(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
weekday: "long",
month: "long",
day: "numeric",
});
}
function time(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
hour: "numeric",
minute: "2-digit",
});
}
function roleLabel(role: string): string {
return role.replaceAll("_", " ");
}
export default async function HomePage() {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) return null;
const profile = await getUserById(user.id);
const [upcoming, past, events, coverage] = await Promise.all([
upcomingServesForUser(user.id, 6),
pastServesForUser(user.id, 3),
upcomingEventAssignmentsForUser(user.id),
coverageRequestsForUser(user.id),
]);
const pendingCoverage = new Set(
coverage.filter((row) => row.status === "pending").map((row) => row.assignmentId),
);
const next = upcoming[0] ?? null;
const canManage = hasPermission(user.systemRole, "schedule.publish");
const firstName = profile?.firstName || "there";
return (
<div className="space-y-6">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-xl font-semibold tracking-tight">
Hi, {firstName}
</h1>
<p className="text-sm text-muted-foreground">
Your next serving date, assignments, and the things that need a
response.
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button asChild variant="outline" size="sm">
<Link href="/availability">
<CalendarPlus aria-hidden="true" />
Availability
</Link>
</Button>
<Button asChild variant="outline" size="sm">
<Link href="/profile">
<UserRound aria-hidden="true" />
My profile
</Link>
</Button>
</div>
</div>
{next ? (
<Card className="border-primary/30">
<CardHeader className="pb-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div className="flex items-center gap-2">
<span className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/10 text-primary">
<CalendarDays className="h-4 w-4" aria-hidden="true" />
</span>
<div>
<p className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Your next serve
</p>
<CardTitle className="text-xl">
{next.roleName} · {next.serviceName}
</CardTitle>
</div>
</div>
<Badge
variant={next.status === "confirmed" ? "default" : "secondary"}
>
{next.status}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid gap-2 text-sm sm:grid-cols-2">
<p className="font-medium">{when(next.startsAt)}</p>
<p className="text-muted-foreground">
Service {time(next.startsAt)}
{next.callTime ? ` · call time ${time(next.callTime)}` : ""}
</p>
{next.location && (
<p className="flex items-center gap-1.5 text-muted-foreground sm:col-span-2">
<MapPin className="h-3.5 w-3.5" aria-hidden="true" />
{next.location}
</p>
)}
</div>
<AssignmentActions
assignmentId={next.assignmentId}
status={next.status}
/>
<div className="flex flex-wrap items-start gap-2">
<Button asChild variant="outline" size="sm">
<Link href={`/run-sheet/${next.instanceId}`}>
<ClipboardCheck aria-hidden="true" />
Run sheet
</Link>
</Button>
<CoverageRequestButton
assignmentId={next.assignmentId}
alreadyRequested={pendingCoverage.has(next.assignmentId)}
/>
</div>
{next.status === "proposed" && (
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<ClipboardCheck className="h-3.5 w-3.5" aria-hidden="true" />
Confirm so the coordinator knows the seat is covered.
</p>
)}
</CardContent>
</Card>
) : (
<Card>
<CardContent className="py-10 text-center">
<p className="text-sm font-medium">No upcoming serving dates</p>
<p className="mt-1 text-sm text-muted-foreground">
When a coordinator puts you on the schedule, it will appear here.
</p>
<Button asChild variant="outline" size="sm" className="mt-4">
<Link href="/schedule">View the schedule</Link>
</Button>
</CardContent>
</Card>
)}
<div className="grid gap-5 lg:grid-cols-2">
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Coming up</CardTitle>
</CardHeader>
<CardContent>
{upcoming.length <= 1 ? (
<p className="text-sm text-muted-foreground">
Nothing else scheduled yet.
</p>
) : (
<ul className="divide-y divide-border">
{upcoming.slice(1).map((serve) => (
<li
key={serve.assignmentId}
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">
{serve.roleName} · {serve.serviceName}
</p>
<p className="text-xs text-muted-foreground">
{when(serve.startsAt)}
{serve.callTime ? ` · call ${time(serve.callTime)}` : ""}
</p>
</div>
<Badge
variant={
serve.status === "confirmed" ? "default" : "secondary"
}
>
{serve.status}
</Badge>
</li>
))}
</ul>
)}
<Link
href="/schedule"
className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-primary underline"
>
Full schedule <ArrowRight className="h-3.5 w-3.5" />
</Link>
</CardContent>
</Card>
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Event coverage</CardTitle>
</CardHeader>
<CardContent>
{events.length === 0 ? (
<p className="text-sm text-muted-foreground">
No upcoming photography or editing assignments.
</p>
) : (
<ul className="divide-y divide-border">
{events.map((event) => (
<li
key={`${event.eventId}:${event.role}`}
className="py-3 first:pt-0 last:pb-0"
>
<Link
href={`/events/${event.eventId}`}
className="text-sm font-medium text-primary underline"
>
{event.title}
</Link>
<p className="text-xs capitalize text-muted-foreground">
{roleLabel(event.role)} · {when(event.startsAt)}
{event.location ? ` · ${event.location}` : ""}
</p>
</li>
))}
</ul>
)}
<Link
href="/events"
className="mt-3 inline-flex items-center gap-1 text-sm font-medium text-primary underline"
>
All events <ArrowRight className="h-3.5 w-3.5" />
</Link>
</CardContent>
</Card>
</div>
{past.length > 0 && (
<Card>
<CardHeader className="pb-3">
<CardTitle className="text-base">Recently served</CardTitle>
</CardHeader>
<CardContent>
<ul className="divide-y divide-border">
{past.map((serve) => (
<li
key={serve.assignmentId}
className="flex flex-wrap items-center justify-between gap-2 py-2 first:pt-0 last:pb-0"
>
<span className="text-sm">
{serve.roleName} · {serve.serviceName}
</span>
<span className="text-xs text-muted-foreground">
{when(serve.startsAt)}
</span>
</li>
))}
</ul>
</CardContent>
</Card>
)}
{canManage && (
<Card>
<CardContent className="flex flex-wrap items-center justify-between gap-3 py-4">
<div>
<p className="text-sm font-semibold">Coordinator tools</p>
<p className="text-xs text-muted-foreground">
Coverage, open seats, approvals, and notification health.
</p>
</div>
<Button asChild size="sm">
<Link href="/dashboard">
Open coverage dashboard <ArrowRight aria-hidden="true" />
</Link>
</Button>
</CardContent>
</Card>
)}
</div>
);
}
+14 -3
View File
@@ -1,11 +1,14 @@
import { auth } from "@/auth/config";
import { redirect } from "next/navigation";
import { auth } from "@/auth/config";
import { getUserSecurity } from "@/db/users";
import { AppLayout } from "@/components/app/app-layout";
import type { SystemRole } from "@/auth/roles";
/**
* Authenticated shell wrapper. Any route under the `(app)` group requires a
* session; unauthenticated visitors are sent to /login. The visible shell
* (header, nav, main, footer) is provided by AppLayout.
* (header, nav, main, footer) is provided by AppLayout, which receives the
* role so the admin-only tab is only rendered for admins.
*/
export default async function AppGroupLayout({
children,
@@ -14,5 +17,13 @@ export default async function AppGroupLayout({
}) {
const session = await auth();
if (!session?.user) redirect("/login");
return <AppLayout>{children}</AppLayout>;
const userId = (session.user as { id?: string }).id;
if (!userId) redirect("/login");
// A magic-link session is enough to reach the setup page, but not the rest
// of the app until the person has chosen credentials.
const security = await getUserSecurity(userId);
if (!security) redirect("/login");
if (!security.passwordHash) redirect("/welcome");
const role = (session.user as { systemRole?: SystemRole }).systemRole;
return <AppLayout role={role}>{children}</AppLayout>;
}
+78
View File
@@ -0,0 +1,78 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { ArrowLeft, CalendarDays } from "lucide-react";
import { auth } from "@/auth/config";
import type { SystemRole } from "@/auth/roles";
import { getEventVideoAccess } from "@/db/videos";
import { mediaOrigin } from "@/lib/media-url";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { videoView } from "@/lib/video-view";
import { VideoEditor } from "@/components/app/media/video-editor";
export const metadata = { title: "Video" };
export const dynamic = "force-dynamic";
export default async function MediaVideoPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) redirect("/login");
const { id } = await params;
const access = await getEventVideoAccess(id, user.id, user.systemRole);
if (!access) notFound();
const origin = await mediaOrigin();
const video = videoView(
{
...access.video,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
},
origin,
);
return (
<div className="space-y-5">
<Link
href="/media"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
All media
</Link>
<div className="space-y-1">
<h1 className="text-xl font-semibold tracking-tight">{video.title}</h1>
<p className="flex flex-wrap items-center gap-2 text-sm text-muted-foreground">
<Link
href={`/events/${video.eventId}`}
className="font-medium text-primary underline"
>
{video.eventTitle}
</Link>
<span className="inline-flex items-center gap-1">
<CalendarDays className="h-3.5 w-3.5" aria-hidden="true" />
{formatInTimezone(new Date(video.eventStartsAt), CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
month: "long",
day: "numeric",
year: "numeric",
})}
</span>
</p>
</div>
<VideoEditor
initialVideo={video}
canManage={access.canManage}
canDelete={access.canManage || video.uploaderId === user.id}
/>
</div>
);
}
+263
View File
@@ -0,0 +1,263 @@
import Link from "next/link";
import {
Clock3,
FileImage,
Film,
Image as ImageIcon,
Play,
} from "lucide-react";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
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 { formatVideoDuration } from "@/lib/event-videos";
import { isBrowserRenderablePhoto } from "@/lib/event-photos";
import { mediaOrigin } from "@/lib/media-url";
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
import { videoView } from "@/lib/video-view";
import { Badge } from "@/components/ui/badge";
import { StateMessage } from "@/components/app/state-message";
import { VideoUploadForm } from "@/components/app/media/video-upload-form";
export const metadata = { title: "Media" };
export const dynamic = "force-dynamic";
function day(date: Date): string {
return formatInTimezone(date, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
month: "short",
day: "numeric",
year: "numeric",
});
}
function bytesLabel(bytes: number): string {
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
/**
* The media library: every event photo and video the signed-in user can open.
* Photos remain protected by event access; video cards link to the watch/editor
* page where managers can publish an unlisted/public version.
*/
export default async function MediaPage() {
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
const role = user?.systemRole;
const events = await listEventsForUser(user?.id ?? "", role);
const eventIds = events.map((event) => event.id);
const origin = await mediaOrigin();
const [videos, photos, storage] = await Promise.all([
listEventVideosForEvents(eventIds),
listMediaPhotosForEvents(eventIds),
getStorageSettings(),
]);
const archiveStatus = await checkArchiveDestination(storage);
const canManage = hasPermission(role, "schedule.publish");
const videoCards = videos.map((video) => videoView(video, origin));
return (
<div className="space-y-8">
<div>
<h1 className="text-lg font-semibold tracking-tight">Media</h1>
<p className="text-sm text-muted-foreground">
An ad-free library of every event photo and video you can access.
Videos stay private to the team until a manager publishes an unlisted
or public version.
</p>
</div>
<section className="space-y-3">
<div className="flex flex-wrap items-end justify-between gap-2">
<div>
<h2 className="flex items-center gap-2 text-base font-semibold">
<Film className="h-4 w-4" aria-hidden="true" />
Videos
</h2>
<p className="text-xs text-muted-foreground">
Camera originals live on the NFS archive; playback uses a generated
MP4.
</p>
</div>
<span className="text-xs text-muted-foreground">
{videoCards.length} video{videoCards.length === 1 ? "" : "s"}
</span>
</div>
<VideoUploadForm
events={events.map((event) => ({
id: event.id,
title: event.title,
}))}
canManage={canManage}
archiveReady={archiveStatus.ready}
/>
{videoCards.length === 0 ? (
<StateMessage
title="No videos yet"
description="Upload a service recap, testimony, or event clip from an event you can access."
/>
) : (
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
{videoCards.map((video) => (
<Link
key={video.id}
href={`/media/${video.id}`}
className="group overflow-hidden rounded-lg border border-border bg-background transition-colors hover:border-primary/60"
>
<div className="relative aspect-video bg-black">
{video.posterUrl && video.status !== "failed" ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={video.posterUrl}
alt=""
loading="lazy"
className="h-full w-full object-cover opacity-90 transition-opacity group-hover:opacity-100"
/>
) : (
<div className="flex h-full items-center justify-center text-white/50">
<Film className="h-10 w-10" aria-hidden="true" />
</div>
)}
<span className="absolute bottom-2 right-2 rounded bg-black/75 px-1.5 py-0.5 font-mono text-[11px] text-white">
{formatVideoDuration(video.durationMs)}
</span>
{(video.status !== "ready" || video.isShareable) && (
<div className="absolute left-2 top-2 flex flex-wrap gap-1">
{video.status !== "ready" && (
<Badge variant="secondary">
{video.status === "failed" ? "Failed" : "Processing"}
</Badge>
)}
{video.isShareable && (
<Badge variant="outline" className="bg-background/90">
{video.visibility}
</Badge>
)}
</div>
)}
<span className="absolute inset-0 flex items-center justify-center opacity-0 transition-opacity group-hover:opacity-100">
<span className="flex h-12 w-12 items-center justify-center rounded-full bg-black/70 text-white">
<Play className="h-5 w-5 fill-current" aria-hidden="true" />
</span>
</span>
</div>
<div className="space-y-1 p-3">
<h3 className="line-clamp-2 text-sm font-semibold">
{video.title}
</h3>
<p className="truncate text-xs text-muted-foreground">
{video.eventTitle} · {day(new Date(video.eventStartsAt))}
</p>
<p className="text-[11px] text-muted-foreground">
{bytesLabel(video.sizeBytes)} original
</p>
</div>
</Link>
))}
</div>
)}
</section>
<section className="space-y-3">
<div className="flex flex-wrap items-end justify-between gap-2">
<div>
<h2 className="flex items-center gap-2 text-base font-semibold">
<ImageIcon className="h-4 w-4" aria-hidden="true" />
Photos
</h2>
<p className="text-xs text-muted-foreground">
Every photo in the event folders you can open. Download originals
from the event folder.
</p>
</div>
<span className="text-xs text-muted-foreground">
{photos.length} photo{photos.length === 1 ? "" : "s"}
</span>
</div>
{photos.length === 0 ? (
<StateMessage
title="No photos yet"
description="When photographers upload to an event you are assigned to, the frames appear here."
/>
) : (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-5">
{photos.map((photo) => {
const previewable =
Boolean(photo.editedAt) ||
isBrowserRenderablePhoto(photo.filename);
const version = photo.editedAt
? Date.parse(photo.editedAt.toISOString())
: 0;
const src = `/api/events/${photo.eventId}/folders/${photo.folderId}/photos/${photo.id}${
photo.editedAt ? `?variant=edited&v=${version}` : ""
}`;
return (
<Link
key={photo.id}
href={`/events/${photo.eventId}/folders/${photo.folderId}`}
className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60"
>
<div className="flex aspect-square items-center justify-center bg-muted/40">
{previewable ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={src}
alt={photo.filename}
loading="lazy"
decoding="async"
className="h-full w-full object-cover"
/>
) : (
<span className="flex flex-col items-center gap-1 text-muted-foreground">
<FileImage className="h-8 w-8" aria-hidden="true" />
<span className="text-[11px] font-medium">
{photo.filename.split(".").pop()?.toUpperCase() ??
"FILE"}
</span>
</span>
)}
</div>
<div className="space-y-0.5 p-2">
<p className="truncate text-xs font-medium" title={photo.filename}>
{photo.filename}
</p>
<p className="truncate text-[11px] text-muted-foreground">
{photo.eventTitle} · {photo.folderName}
</p>
<p className="text-[10px] text-muted-foreground">
{bytesLabel(photo.sizeBytes)}
</p>
</div>
</Link>
);
})}
</div>
)}
</section>
<p className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Clock3 className="h-3.5 w-3.5" aria-hidden="true" />
Video originals are kept under{" "}
<span className="font-mono">
{storage.archivePath}/{storage.archiveFolder}/videos/
</span>
.
</p>
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
import Link from "next/link";
import { redirect } from "next/navigation";
import { ArrowLeft } from "lucide-react";
import { auth } from "@/auth/config";
import { getProfile } from "@/db/profile";
import { getUserSkills } from "@/db/userSkills";
import { listSkills } from "@/db/positions";
import { getOrCreateCalendarFeedToken } from "@/db/volunteer";
import { mediaOrigin } from "@/lib/media-url";
import { ProfilePanel } from "@/components/app/profile-panel";
export const metadata = { title: "My profile" };
export const dynamic = "force-dynamic";
export default async function ProfilePage() {
const session = await auth();
const user = session?.user as { id?: string } | undefined;
if (!user?.id) redirect("/login");
const [profile, skillRows, allSkills, token, origin] = await Promise.all([
getProfile(user.id),
getUserSkills(user.id),
listSkills({ active: true }),
getOrCreateCalendarFeedToken(user.id),
mediaOrigin(),
]);
const bySkill = new Map(skillRows.map((row) => [row.skillId, row]));
return (
<div className="space-y-5">
<div>
<Link
href="/settings"
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
>
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
Settings
</Link>
<h1 className="mt-2 text-lg font-semibold tracking-tight">My profile</h1>
<p className="text-sm text-muted-foreground">
Contact details, reminders, skill comfort, and your personal calendar.
</p>
</div>
<ProfilePanel
userId={user.id}
initial={{
firstName: profile.user.firstName,
lastName: profile.user.lastName,
displayName: profile.user.displayName ?? profile.user.firstName,
email: profile.user.email,
phoneE164: profile.user.phoneE164 ?? "",
emergencyContact: profile.user.emergencyContact ?? "",
timezone: profile.user.timezone,
}}
preferences={{
emailEnabled: profile.preferences?.emailEnabled ?? true,
reminderLeadDays: profile.preferences?.reminderLeadDays ?? 7,
digestOnly: profile.preferences?.digestOnly ?? false,
quietHoursStart: profile.preferences?.quietHoursStart ?? "21:00",
quietHoursEnd: profile.preferences?.quietHoursEnd ?? "08:00",
}}
skills={allSkills.map((skill) => ({
id: skill.id,
name: skill.name,
verifiedLevel: bySkill.get(skill.id)?.verifiedLevel ?? "none",
selfComfort: bySkill.get(skill.id)?.selfComfort ?? null,
}))}
feedUrl={`${origin}/api/calendar/${token}`}
/>
</div>
);
}
+71 -9
View File
@@ -1,16 +1,78 @@
import Link from "next/link";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listUsers } from "@/db/admin";
import { Badge } from "@/components/ui/badge";
import { StateMessage } from "@/components/app/state-message";
export const metadata = { title: "Roster" };
export default function RosterPage() {
/**
* The team list. Everyone signed in can see who serves on the team and their
* role; admins additionally get a link to the people controls in /admin.
*/
export default async function RosterPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
const isAdmin = hasPermission(role, "admin.settings");
const team = (await listUsers()).filter((u) => u.status === "active");
return (
<>
<h1 className="text-lg font-semibold tracking-tight">Roster</h1>
<p className="text-sm text-muted-foreground">The team, their roles, and how to reach them.</p>
<StateMessage
title="No one on the roster yet"
description="Volunteers appear here once an admin invites and approves them."
/>
</>
<div className="space-y-4">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="text-lg font-semibold tracking-tight">Roster</h1>
<p className="text-sm text-muted-foreground">
The team, their roles, and how to reach them.
</p>
</div>
{isAdmin && (
<Link href="/admin" className="text-sm font-medium text-primary underline">
Manage people
</Link>
)}
</div>
{team.length === 0 ? (
<StateMessage
title="No one on the roster yet"
description="Approved volunteers appear here once an admin invites and approves them."
/>
) : (
<div className="overflow-x-auto rounded-md border border-border">
<table className="min-w-full text-sm">
<thead className="border-b border-border bg-muted/40">
<tr>
<th scope="col" className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Name
</th>
<th scope="col" className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Role
</th>
<th scope="col" className="px-3 py-2 text-left text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Email
</th>
</tr>
</thead>
<tbody>
{team.map((person) => (
<tr key={person.id} className="border-b border-border last:border-b-0">
<td className="px-3 py-2 font-medium text-foreground">
{person.displayName}
</td>
<td className="px-3 py-2">
<Badge variant={person.systemRole === "admin" ? "default" : "outline"}>
{person.systemRole}
</Badge>
</td>
<td className="px-3 py-2 text-muted-foreground">{person.email}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
);
}
@@ -0,0 +1,28 @@
import { notFound } from "next/navigation";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { getRunSheet } from "@/db/runSheet";
import { RunSheetEditor } from "@/components/app/run-sheet/run-sheet-editor";
export const metadata = { title: "Run sheet" };
export default async function RunSheetPage({
params,
}: {
params: Promise<{ instanceId: string }>;
}) {
const { instanceId } = await params;
const session = await auth();
const user = session?.user as
| { id?: string; systemRole?: SystemRole }
| undefined;
if (!user?.id) return null;
const data = await getRunSheet(instanceId);
if (!data) notFound();
const canEdit = hasPermission(user.systemRole, "schedule.publish");
return <RunSheetEditor data={data} canEdit={canEdit} />;
}
+109 -21
View File
@@ -1,51 +1,139 @@
import { gridForWeek, defaultWeekStart } from "@/db/grid";
import { calendarInstances } from "@/db/calendar";
import { activeVolunteers } from "@/db/volunteers";
import { WeekNav } from "@/components/app/week-nav";
import { ScheduleAdminBar } from "@/components/app/schedule-admin-bar";
import { ScheduleGrid } from "@/components/app/schedule-grid";
import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor";
import {
MonthNav,
ScheduleViewToggle,
YearNav,
} from "@/components/app/calendar-nav";
import { MonthCalendar } from "@/components/app/month-calendar";
import { YearCalendar } from "@/components/app/year-calendar";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { db } from "@/db";
import { CHURCH_TIMEZONE, dateInTimezone } from "@/lib/tz";
import {
isValidMonth,
isValidYear,
monthRange,
yearRange,
} from "@/domain/calendar";
export const metadata = { title: "Schedule" };
type ScheduleView = "week" | "month" | "year";
/**
* Scheduling grid (unit D7, extended by D8). Read-only for volunteers; the
* interactive optimistic editor for anyone with `schedule.publish`
* (coordinator + admin). Week via `?week=YYYY-MM-DD` (a Sunday); defaults to
* the week of the earliest upcoming published instance so a seeded DB shows
* data at once.
* Schedule with three lenses:
* - week: the editable grid (assign/clear), admin publish + auto-fill;
* - month: an overview grid of services, linking into the week;
* - year: twelve month cards with build-out counts.
*
* `?view=` selects the lens; `?week=`/`?month=`/`?year=` anchor it. Month and
* year are read-only by design — editing happens where the seats are visible.
*/
export default async function SchedulePage({
searchParams,
}: {
searchParams: Promise<{ week?: string }>;
searchParams: Promise<{
view?: string;
week?: string;
month?: string;
year?: string;
}>;
}) {
const { week: paramWeek } = await searchParams;
// Validate the param is a YYYY-MM-DD string; fall back to the default week.
const weekStart =
typeof paramWeek === "string" && /^\d{4}-\d{2}-\d{2}$/.test(paramWeek)
? paramWeek
: await defaultWeekStart();
const params = await searchParams;
const view: ScheduleView =
params.view === "month" ? "month" : params.view === "year" ? "year" : "week";
const week = await gridForWeek(weekStart);
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
const weekStart =
typeof params.week === "string" && /^\d{4}-\d{2}-\d{2}$/.test(params.week)
? params.week
: await defaultWeekStart();
const month =
typeof params.month === "string" && isValidMonth(params.month)
? params.month
: today.slice(0, 7);
const year =
typeof params.year === "string" && isValidYear(params.year)
? Number(params.year)
: Number(today.slice(0, 4));
const session = await auth();
const role = (session?.user as { systemRole: SystemRole } | null | undefined)
const role = (session?.user as { systemRole?: SystemRole } | null | undefined)
?.systemRole;
const canEdit = role ? hasPermission(role, "schedule.publish") : false;
const header = (
<div>
<h1 className="text-lg font-semibold tracking-tight">Schedule</h1>
<p className="text-sm text-muted-foreground">
{view === "week"
? "Service instances for the week and who is on each position."
: view === "month"
? "Every service this month. Open a week to edit assignments."
: "A year at a glance — how much of the schedule is built and published."}
</p>
</div>
);
const toggle = (
<ScheduleViewToggle
view={view}
week={weekStart}
month={month}
year={year}
/>
);
if (view === "month") {
const range = monthRange(month);
const instances = await calendarInstances(range.start, range.end);
return (
<div className="space-y-4">
{header}
{toggle}
<MonthNav month={month} />
<MonthCalendar month={month} instances={instances} />
</div>
);
}
if (view === "year") {
const range = yearRange(year);
const instances = await calendarInstances(range.start, range.end);
return (
<div className="space-y-4">
{header}
{toggle}
<YearNav year={year} />
<YearCalendar year={year} instances={instances} />
</div>
);
}
const week = await gridForWeek(weekStart);
return (
<div className="space-y-4">
<div>
<h1 className="text-lg font-semibold tracking-tight">Schedule</h1>
<p className="text-sm text-muted-foreground">
Service instances for the week and who is on each position.
</p>
</div>
{header}
{toggle}
<WeekNav weekStart={weekStart} />
{canEdit && (
<ScheduleAdminBar
instances={week.instances.map((inst) => ({
id: inst.id,
label: `${inst.occursOn} · ${inst.serviceName}`,
status: inst.status,
}))}
/>
)}
{canEdit ? (
<ScheduleGridEditor week={week} volunteers={await activeVolunteers(db)} />
) : (
+154
View File
@@ -0,0 +1,154 @@
import Link from "next/link";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { scheduleExportRows, type ScheduleExportRow } from "@/db/exports";
import {
addDaysISO,
CHURCH_TIMEZONE,
dateInTimezone,
formatInTimezone,
weekStartOn,
} from "@/lib/tz";
import { PrintButton } from "@/components/app/print-button";
import { Button } from "@/components/ui/button";
export const metadata = { title: "Printable roster" };
function shortDate(iso: string): string {
return new Date(`${iso}T00:00:00Z`).toLocaleDateString("en-US", {
timeZone: "UTC",
weekday: "long",
month: "long",
day: "numeric",
});
}
interface Group {
key: string;
date: string;
serviceName: string;
startTime: string;
rows: ScheduleExportRow[];
}
function group(rows: ScheduleExportRow[]): Group[] {
const groups = new Map<string, Group>();
for (const row of rows) {
const date = row.occursOn
? `${row.occursOn.getUTCFullYear()}-${String(row.occursOn.getUTCMonth() + 1).padStart(2, "0")}-${String(row.occursOn.getUTCDate()).padStart(2, "0")}`
: "";
const key = `${date}:${row.serviceName}`;
let group = groups.get(key);
if (!group) {
group = {
key,
date,
serviceName: row.serviceName,
startTime: row.startsAt
? formatInTimezone(row.startsAt, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
hour: "numeric",
minute: "2-digit",
})
: "",
rows: [],
};
groups.set(key, group);
}
group.rows.push(row);
}
return [...groups.values()];
}
export default async function PrintSchedulePage({
searchParams,
}: {
searchParams: Promise<{ week?: string }>;
}) {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)
?.systemRole;
if (!session?.user) return null;
if (!hasPermission(role, "schedule.publish")) return null;
const params = await searchParams;
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
const weekStart =
params.week && /^\d{4}-\d{2}-\d{2}$/.test(params.week)
? params.week
: weekStartOn(today, CHURCH_TIMEZONE);
const rows = await scheduleExportRows(weekStart, addDaysISO(weekStart, 6));
const groups = group(rows);
return (
<div className="space-y-5 text-black dark:text-foreground">
<div className="flex flex-wrap items-start justify-between gap-3 print:hidden">
<div>
<h1 className="text-lg font-semibold tracking-tight">Printable roster</h1>
<p className="text-sm text-muted-foreground">
Week of {shortDate(weekStart)} — includes every assignment and its
confirmation state.
</p>
</div>
<div className="flex gap-2">
<Button asChild variant="outline" size="sm">
<Link href={`/schedule?week=${weekStart}`}>Back to schedule</Link>
</Button>
<PrintButton label="Print roster" />
</div>
</div>
<div className="hidden print:block">
<h1 className="text-xl font-semibold">Media team roster</h1>
<p className="text-sm">Week of {shortDate(weekStart)}</p>
</div>
{groups.length === 0 ? (
<p className="text-sm text-muted-foreground">
No assignments in this week.
</p>
) : (
<div className="space-y-6">
{groups.map((item) => (
<section key={item.key} className="break-inside-avoid">
<h2 className="border-b border-border pb-1 text-sm font-semibold">
{item.date ? shortDate(item.date) : ""} · {item.serviceName} ·{" "}
{item.startTime}
</h2>
<table className="mt-2 w-full border-collapse text-sm">
<thead>
<tr className="text-left text-xs uppercase tracking-wide text-muted-foreground">
<th className="py-1 pr-2 font-medium">Role</th>
<th className="py-1 pr-2 font-medium">Volunteer</th>
<th className="py-1 pr-2 font-medium">Call</th>
<th className="py-1 font-medium">Status</th>
</tr>
</thead>
<tbody>
{item.rows.map((row, index) => (
<tr key={`${row.roleName}:${row.userName}:${index}`} className="border-t border-border/60">
<td className="py-1.5 pr-2">{row.roleName}</td>
<td className="py-1.5 pr-2 font-medium">{row.userName}</td>
<td className="py-1.5 pr-2">
{row.callTime
? formatInTimezone(row.callTime, CHURCH_TIMEZONE, {
timeZone: CHURCH_TIMEZONE,
hour: "numeric",
minute: "2-digit",
})
: "—"}
</td>
<td className="py-1.5 capitalize">{row.status}</td>
</tr>
))}
</tbody>
</table>
</section>
))}
</div>
)}
</div>
);
}
+167 -10
View File
@@ -1,16 +1,173 @@
import { StateMessage } from "@/components/app/state-message";
import Link from "next/link";
import { auth } from "@/auth/config";
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 { CHURCH_TIMEZONE } from "@/lib/tz";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { SettingsForm } from "@/components/app/settings-form";
import { StoragePanel } from "@/components/app/storage-panel";
import { PasswordForm } from "@/components/app/password-form";
export const metadata = { title: "Settings" };
export default function SettingsPage() {
/**
* Deployment facts plus the admin-editable email identity. The From address
* and admin notification inbox live in the database, so changing them does not
* require a deploy or a container restart.
*/
export default async function SettingsPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
const userId = (session?.user as { id?: string } | undefined)?.id;
const security = userId ? await getUserSecurity(userId) : null;
const isAdmin = hasPermission(role, "admin.settings");
const emailSettings = isAdmin ? await getEmailSettings() : null;
const storageSettings = isAdmin ? await getStorageSettings() : null;
const storageStatus = storageSettings
? await checkArchiveDestination(storageSettings)
: null;
const emailTransport = emailSettings?.smtpConfigured
? "Gmail (SMTP)"
: process.env.POSTMARK_SERVER_TOKEN
? "Postmark"
: "Console outbox (dev)";
return (
<>
<h1 className="text-lg font-semibold tracking-tight">Settings</h1>
<p className="text-sm text-muted-foreground">Church details, timezone, and scheduling rules.</p>
<StateMessage
title="No settings to show"
description="Church and scheduling settings appear here. Branding and admin settings are restricted to admins."
/>
</>
<div className="space-y-4">
<div>
<h1 className="text-lg font-semibold tracking-tight">Settings</h1>
<p className="text-sm text-muted-foreground">
Church details and how the app is configured.
</p>
</div>
{security && (
<Card>
<CardHeader>
<CardTitle className="text-lg">My account</CardTitle>
<CardDescription>
Your username and password for signing in. Changing either does
not sign you out of this session.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Link
href="/profile"
className="inline-flex text-sm font-medium text-primary underline"
>
Edit profile, notifications, skill comfort and calendar feed
</Link>
<PasswordForm
initialUsername={security.username}
hasPassword={Boolean(security.passwordHash)}
/>
</CardContent>
</Card>
)}
<Card>
<CardHeader>
<CardTitle className="text-lg">Church</CardTitle>
<CardDescription>
Values that drive scheduling and message delivery.
</CardDescription>
</CardHeader>
<CardContent>
<dl className="grid gap-4 sm:grid-cols-2">
<div>
<dt className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Timezone
</dt>
<dd className="mt-1 text-sm text-foreground">{CHURCH_TIMEZONE}</dd>
</div>
<div>
<dt className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Week starts
</dt>
<dd className="mt-1 text-sm text-foreground">Sunday</dd>
</div>
<div>
<dt className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Email delivery
</dt>
<dd className="mt-1 text-sm text-foreground">{emailTransport}</dd>
</div>
<div>
<dt className="text-xs font-semibold uppercase tracking-tight text-muted-foreground">
Signed in as
</dt>
<dd className="mt-1 text-sm text-foreground">
{session?.user?.email ?? "—"}
{security && (
<span className="block text-xs text-muted-foreground">
Username: {security.username}
</span>
)}
</dd>
</div>
</dl>
</CardContent>
</Card>
{isAdmin && emailSettings && (
<Card>
<CardHeader>
<CardTitle className="text-lg">Email &amp; notifications</CardTitle>
<CardDescription>
Sender identity for assignment mail and where admin test messages
are delivered.
</CardDescription>
</CardHeader>
<CardContent>
<SettingsForm
emailFrom={emailSettings.emailFrom}
notificationEmail={emailSettings.notificationEmail}
/>
</CardContent>
</Card>
)}
{isAdmin && storageSettings && storageStatus && (
<Card>
<CardHeader>
<CardTitle className="text-lg">Media archive (NFS)</CardTitle>
<CardDescription>
Mount an NFS export into this container. Finished event photos are
archived here, and every uploaded video keeps its camera original
on this mount. Photo archives include originals, saved edits, and a
manifest.
</CardDescription>
</CardHeader>
<CardContent>
<StoragePanel
initial={storageSettings}
initialStatus={storageStatus}
/>
</CardContent>
</Card>
)}
{isAdmin && (
<p className="text-sm text-muted-foreground">
People, services, reminder rules, and the notification log live in{" "}
<Link href="/admin" className="font-medium text-primary underline">
Admin
</Link>
.
</p>
)}
</div>
);
}
@@ -0,0 +1,779 @@
import type { Metadata } from "next";
import {
GuideCallout,
GuideFields,
GuideFigure,
GuideSection,
GuideShell,
GuideStep,
GuideSteps,
} from "@/components/app/training/guide";
export const metadata: Metadata = {
title: "Platform administration guide",
};
const SECTIONS = [
{ id: "before-you-start", title: "Before you start" },
{ id: "admin-hub", title: "The admin hub" },
{ id: "people", title: "People and access" },
{ id: "skills", title: "Skill levels" },
{ id: "positions", title: "Positions and requirements" },
{ id: "services-schedule", title: "Services and the schedule" },
{ id: "coverage", title: "Coverage and swaps" },
{ id: "run-sheets", title: "Run sheets" },
{ id: "messages", title: "Reminders and notifications" },
{ id: "email-settings", title: "Email and deployment settings" },
{ id: "backup", title: "Backup and restore" },
{ id: "content", title: "Announcements and training" },
{ id: "exports", title: "Print and CSV exports" },
{ id: "troubleshooting", title: "Troubleshooting" },
];
export default function AdminGuidePage() {
return (
<GuideShell
title="Platform administration guide"
audience="Admins"
intro="Everything needed to run the Media Team Hub: adding people, verifying skills, defining positions, building and publishing the schedule, handling swaps, preparing run sheets, and keeping email and backups healthy. Written for the church admin who is comfortable with ordinary web forms but is not a developer."
pdfHref="/training/media-team-admin-guide.pdf"
pdfLabel="Download admin PDF"
sections={SECTIONS}
>
<GuideSection id="before-you-start" title="1. Before you start">
<p className="text-sm leading-6">
The hub has three working roles. Your role decides which tabs and
buttons exist for you, so a missing control usually means a missing
permission rather than a broken page.
</p>
<GuideFields
rows={[
{
label: "Admin",
value:
"Everything, including the Admin tab, people management, skill verification, email credentials, and backup/restore. Only admins can open /admin.",
},
{
label: "Coordinator",
value:
"Dashboard, Coverage, schedule editing and publishing, events, run sheets, announcements, and exports. No Admin tab and no access to email or backup settings.",
},
{
label: "Volunteer / trainee",
value:
"Home, schedule, events and media they are assigned to, roster, training, announcements, profile, and settings. Trainees do not see the roster.",
},
]}
/>
<GuideSteps>
<GuideStep>
Open the site and sign in at <code>/login</code> with your username
(email by default) and password, or request a one-time sign-in link
by email.
</GuideStep>
<GuideStep>
After signing in you land on <strong>Schedule</strong>. Admins and
coordinators also see <strong>Dashboard</strong> and{" "}
<strong>Coverage</strong> in the navigation; admins see{" "}
<strong>Admin</strong> at the end of the rail.
</GuideStep>
<GuideStep>
Use the same account for desktop and phone. The layout adapts, and
the mobile tab bar scrolls horizontally when there are more tabs
than fit.
</GuideStep>
</GuideSteps>
<GuideCallout title="Two safety rules worth knowing now" tone="warning">
<p>
You cannot demote or delete the last active admin, and you cannot
delete a person who has scheduling history — deactivate them
instead. Both protections are deliberate; the app will explain the
refusal rather than silently changing the record.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="admin-hub" title="2. The admin hub">
<p className="text-sm leading-6">
<strong>Admin</strong> is one long page of cards, in the order you
normally use them: People, Skill levels, Positions &amp; requirements,
Services &amp; schedule, Reminder rules, Email delivery, Backup &amp;
restore, and Notifications. Changes save immediately; there is no
page-level Save button. Reload the page if another admin may have
changed something while you were working.
</p>
<GuideFigure
src="/training/screens/admin-overview.png"
alt="Top of the Admin page showing the People card and the Add a person form"
caption="The Admin hub. Each card owns one job, and each action reports its result inline."
/>
<GuideCallout title="Draft versus published" tone="note">
<p>
New service instances start as drafts. Volunteers only see the
week, and only receive assignment email, after you publish it. A
draft is safe to edit; a published week should be changed carefully
because people have already been told about it.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="people" title="3. People and access">
<p className="text-sm leading-6">
The People card is the church directory and the access control panel
at the same time. The table lists everyone, including pending and
deactivated accounts, with their role, status, phone, and actions.
</p>
<GuideFigure
src="/training/screens/admin-people.png"
alt="People card with the add-person form and the team table"
caption="Add a person at the top; approve, edit, deactivate, or delete from the row actions."
/>
<h3 className="pt-2 text-base font-semibold">Add someone</h3>
<GuideSteps>
<GuideStep>
Enter first name, last name, email, and optionally a phone number in
E.164 form (for example <code>+15551234567</code>).
</GuideStep>
<GuideStep>
Choose the role: <strong>volunteer</strong>,{" "}
<strong>trainee</strong>, <strong>coordinator</strong>, or{" "}
<strong>admin</strong>. Default to volunteer unless the person
genuinely needs scheduling or admin powers.
</GuideStep>
<GuideStep>
Leave <strong>Needs approval before signing in</strong> ticked when
you are not yet sure about the person. They will appear as pending
until you approve them.
</GuideStep>
<GuideStep>
Press <strong>Add user</strong>. The app shows a one-time sign-in
link; copy it and send it to the person through a channel you trust.
The link only works once the account is active.
</GuideStep>
</GuideSteps>
<h3 className="pt-2 text-base font-semibold">Approve or deny sign-ups</h3>
<p className="text-sm leading-6">
People can request access with their email. Pending rows show{" "}
<strong>Approve</strong> and <strong>Deny</strong>. Approving makes the
account active and lets the person set a password; denying keeps them
out but leaves the record for your notes.
</p>
<h3 className="pt-2 text-base font-semibold">Edit a person</h3>
<p className="text-sm leading-6">
<strong>Edit</strong> expands an inline panel. Save with{" "}
<strong>Save changes</strong> at the bottom of the panel.
</p>
<GuideFields
rows={[
{
label: "Profile",
value:
"First and last name, display name, email, username, phone, timezone, emergency contact, and free-form notes. Notes are for coordinators and admins.",
},
{
label: "Role and status",
value:
"Change the role or set the account status (active, invited, pending approval, denied, inactive). Use deactivation for someone who has left the team.",
},
{
label: "Login & password",
value:
"Set a temporary password directly, or create a reset link valid for one hour. Setting a password does not change the role or status.",
},
{
label: "Emergency sign-in",
value:
"Show a magic link to copy, or resend it by email. Magic links expire after ten minutes and only work for active, non-deactivated accounts.",
},
{
label: "Skill levels",
value:
"Add a skill (it starts at none), change a level, mark someone as a mentor for a skill, or remove an entry. Higher levels should go through the Skill levels card so the assessment history is recorded.",
},
]}
/>
<GuideCallout title="Deactivate, do not delete" tone="tip">
<p>
Deactivating blocks sign-in but keeps the person’s assignment,
training, and audit history intact. Delete is reserved for accounts
created by mistake; the server refuses to delete anyone with
scheduling history and tells you to deactivate instead.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="skills" title="4. Skill levels">
<p className="text-sm leading-6">
The Skill levels card answers “who is signed off on what?”. Each row is
one person and one skill, with the volunteer’s own comfort rating, the
verified level, and the last date they served that skill.
</p>
<GuideFigure
src="/training/screens/admin-skills.png"
alt="Skill levels matrix with a verified level filter and verify controls"
caption="Filter by verified level to find gaps, then verify from the row."
/>
<p className="text-sm leading-6">
The ladder is <strong>none → observer → assisted → qualified →
expert</strong>. Use the filter at the top to show only one level when
you are auditing a position.
</p>
<GuideSteps>
<GuideStep>
Find the person and skill, then open the verify control on that row.
</GuideStep>
<GuideStep>
Choose the new level. The app preselects the next rung, which is the
usual case.
</GuideStep>
<GuideStep>
Choose the assessment kind (for example admin, mentor, or practical)
and add a short note explaining the evidence.
</GuideStep>
<GuideStep>
Save. The change writes an audited assessment and moves the verified
level in one transaction.
</GuideStep>
</GuideSteps>
<GuideCallout title="Self-ratings are not yours to edit" tone="warning">
<p>
The comfort percentage is the volunteer’s own signal from their
profile. Verification changes only the verified level, so a
coordinator cannot quietly rewrite how confident someone feels.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="positions" title="5. Positions and requirements">
<p className="text-sm leading-6">
A position is a seat on a service — Audio, Livestream, Slides, and
anything else you add. The table shows seats, call time, required
skills, and whether the position is active.
</p>
<GuideFigure
src="/training/screens/admin-positions.png"
alt="Positions and requirements card with the position table and editor"
caption="Edit requirements opens an inline editor for one position at a time."
/>
<GuideFields
rows={[
{
label: "Seats",
value:
"How many people the position needs per service. The schedule creates that many slots for each instance.",
},
{
label: "Call time",
value:
"Minutes before the service that the team should arrive. Negative values mean before; “at start” means no offset.",
},
{
label: "Skill",
value:
"Each requirement names a skill. Add every skill that should count when ranking candidates.",
},
{
label: "Weight (1–5)",
value:
"How strongly the skill influences the ranking score. Reserve 5 for skills that genuinely decide who can do the job.",
},
{
label: "Required level",
value:
"The minimum verified level, or “no threshold” when any level is acceptable. A required level is enforced when candidates are ranked.",
},
{
label: "Core",
value:
"A core skill is non-negotiable. A position marked publishable must have at least one core skill; the server refuses to save it otherwise.",
},
]}
/>
<GuideSteps>
<GuideStep>
Press <strong>Edit requirements</strong> on a row.
</GuideStep>
<GuideStep>
Change an existing requirement, press <strong>Remove</strong> to drop
one, or <strong>Add skill</strong> to append another.
</GuideStep>
<GuideStep>
Leave <strong>Publishable</strong> ticked only when the requirement
set is complete enough to schedule against.
</GuideStep>
<GuideStep>
Press <strong>Save requirements</strong>. The whole set is saved
together, so what you see is exactly what is stored.
</GuideStep>
</GuideSteps>
</GuideSection>
<GuideSection id="services-schedule" title="6. Services and the schedule">
<p className="text-sm leading-6">
A service is the repeating template (for example Sunday 9:00 AM). An
instance is one dated occurrence of that template, and the schedule is
built from instances.
</p>
<GuideFigure
src="/training/screens/admin-services.png"
alt="Services and schedule card with the template form and service table"
caption="Create a template once, then generate the upcoming instances."
/>
<h3 className="pt-2 text-base font-semibold">Create a service template</h3>
<GuideSteps>
<GuideStep>
Enter a clear name (“Sunday 9:00 AM”, “Sunday 5:00 PM”), start time,
length in minutes, and location.
</GuideStep>
<GuideStep>
Press <strong>Add service</strong>. New templates use the weekly
Sunday recurrence by default.
</GuideStep>
<GuideStep>
Press <strong>Generate upcoming Sundays</strong> to create the
rolling window of instances. Generation is idempotent — running it
twice does not duplicate weeks.
</GuideStep>
<GuideStep>
Deactivate a template when it stops running. Existing instances are
untouched; future generation skips it.
</GuideStep>
<GuideStep>
<strong>Delete</strong> removes a template permanently — use it for
one you added by mistake. It only works while the template has no
published, past, or assigned instances; anything with history has
to be deactivated instead, so the schedule record survives.
</GuideStep>
</GuideSteps>
<h3 className="pt-2 text-base font-semibold">Build and publish a week</h3>
<GuideFigure
src="/training/screens/admin-schedule.png"
alt="Week schedule grid with role columns and assignment controls"
caption="The week view is the only editable lens; month and year are read-only overviews."
/>
<GuideSteps>
<GuideStep>
Open <strong>Schedule</strong>. The toggle switches between week,
month, and year; the arrows move one week, month, or year at a time.
</GuideStep>
<GuideStep>
In week view, each column is a position and each row is a service
instance. Press an empty seat to assign someone, or use the row
actions to clear a seat.
</GuideStep>
<GuideStep>
<strong>Auto-fill</strong> proposes ranked volunteers for the open
seats. Review every suggestion; the ranking respects skills,
availability, and conflicts, but it does not know the relational
context.
</GuideStep>
<GuideStep>
Press <strong>Publish</strong> when the week is ready. Publishing
queues assignment email and reminder rules for that instance.
</GuideStep>
<GuideStep>
Unpublish only when you intend to withdraw the week; volunteers may
already have received mail.
</GuideStep>
</GuideSteps>
<GuideCallout title="Hard and soft conflicts" tone="note">
<p>
A hard conflict blocks an assignment (already serving elsewhere in
the same service, a blackout, or a missing core skill). A soft
conflict is a warning you may override, such as exceeding a monthly
serving cap. The app shows which is which before you save.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="coverage" title="7. Coverage and swaps">
<p className="text-sm leading-6">
The Coverage dashboard summarises the next five weeks: filled and open
seats, unconfirmed assignments, pending people, and the queues that
need a coordinator. <strong>Coverage</strong> is the working queue for
swaps and outside requests.
</p>
<GuideFigure
src="/training/screens/admin-dashboard.png"
alt="Coverage dashboard with seat statistics and next-service summary"
caption="Dashboard: the health check you open before planning the next week."
/>
<GuideFigure
src="/training/screens/admin-coverage.png"
alt="Coverage page showing pending swap requests and the public intake queue"
caption="Coverage: approve a swap with a suggested replacement, release the seat, or convert a church request into an event."
/>
<h3 className="pt-2 text-base font-semibold">Handle a swap request</h3>
<GuideSteps>
<GuideStep>
Open <strong>Coverage</strong>. Each request names the volunteer,
the seat, and the service, with the reason they gave.
</GuideStep>
<GuideStep>
Review the ranked eligible replacements and their warnings. Pick
someone whose skills and availability fit, not just the top score.
</GuideStep>
<GuideStep>
Choose <strong>Approve with replacement</strong>. The original
assignment is cancelled, the new person is placed as a proposed
swap, and the seat stays covered. If the week is published, the new
person is emailed.
</GuideStep>
<GuideStep>
Choose <strong>Approve and release</strong> when nobody can take it.
The seat becomes open and the original assignment is cancelled but
kept in history.
</GuideStep>
<GuideStep>
Choose <strong>Decline</strong> if the request should not be granted;
the original volunteer stays on the seat.
</GuideStep>
</GuideSteps>
<GuideCallout title="The seat is never left in limbo" tone="tip">
<p>
A pending request does not remove the volunteer. They remain
responsible until you approve something, so the service always has a
named owner.
</p>
</GuideCallout>
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
<p className="text-sm leading-6">
Ministry leaders can submit the public form at{" "}
<code>/request-coverage</code> without an account. Submissions are
rate-limited and appear under Coverage as new requests. Read the brief,
then either <strong>Create event</strong> (which opens an event with
the requester and ministry attached) or <strong>Decline</strong>. The
event is where you assign photographers and folders.
</p>
</GuideSection>
<GuideSection id="run-sheets" title="8. Run sheets">
<p className="text-sm leading-6">
Every service instance has one run sheet: speaker, message title,
stream and slides links, team notes, an ordered cue list, and a pre/post
checklist. Open it from the Home page’s next-serve card or from the
schedule/dashboard links.
</p>
<GuideFigure
src="/training/screens/admin-run-sheet.png"
alt="Run sheet editor with service details, cue list, and checklist"
caption="Coordinators and admins edit the sheet; every signed-in volunteer can tick checklist items."
/>
<GuideSteps>
<GuideStep>
Fill in speaker, message title, stream link, slides link, and notes
for the team, then press <strong>Save details</strong>.
</GuideStep>
<GuideStep>
Edit a cue’s time, title, or owner inline and press the save icon on
that row. Use the trash icon to remove a cue, or the add row at the
bottom to insert one.
</GuideStep>
<GuideStep>
Tick checklist items as they are completed. The sheet records who
ticked each item and when.
</GuideStep>
<GuideStep>
Add checklist items for this service with{" "}
<strong>Add pre-service item</strong> or{" "}
<strong>Add post-service item</strong>. Delete custom items you no
longer need.
</GuideStep>
<GuideStep>
Press <strong>Print</strong> for a clean booth copy with the app
chrome removed.
</GuideStep>
</GuideSteps>
<GuideCallout title="Defaults are seeded once" tone="note">
<p>
A new instance receives five standard cues and a seven-step
pre-service / four-step post-service checklist the first time the
sheet is opened. Deleting rows does not re-seed them, so the team can
shape a sheet without it resetting.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="messages" title="9. Reminders and notifications">
<p className="text-sm leading-6">
Reminder rules decide when assignment email goes out relative to the
service. They are data, not code: a change here affects the next
publish with no deploy.
</p>
<GuideFigure
src="/training/screens/admin-reminders.png"
alt="Reminder rules card with the add-rule form and rule table"
caption="Negative day values are before the service; the seeded Friday reminder is two days before."
/>
<GuideSteps>
<GuideStep>
Give the rule a short key (for example <code>friday</code>).
</GuideStep>
<GuideStep>
Set days from the service and the local send time. Use{" "}
<code>-2</code> for two days before, <code>0</code> for the day of.
</GuideStep>
<GuideStep>
Choose the channels: email, SMS, or both. SMS depends on the
deployment having an SMS transport configured.
</GuideStep>
<GuideStep>
Press <strong>Add rule</strong>. Disable a rule instead of deleting
it when you want to pause sends without losing the configuration.
</GuideStep>
</GuideSteps>
<h3 className="pt-2 text-base font-semibold">The notification log</h3>
<p className="text-sm leading-6">
Every message the app queues lands in the Notifications card, newest
first. Publishing and reminder rules write here; a background
dispatcher drains the queue.
</p>
<GuideFigure
src="/training/screens/admin-notifications.png"
alt="Notification log with statuses, recipients, and retry actions"
caption="Failed or suppressed messages can be re-queued after you fix the cause."
/>
<GuideFields
rows={[
{
label: "queued / sending",
value: "Waiting for the dispatcher. Normal shortly after a publish.",
},
{
label: "sent",
value: "Accepted by the configured transport, with a sent timestamp.",
},
{
label: "failed / suppressed",
value:
"The transport rejected it or preferences blocked it. The provider error is shown; press Retry after fixing the address or credentials.",
},
]}
/>
<p className="text-sm leading-6">
<strong>Send test email</strong> sends a message to the signed-in admin
through the configured transport. Use it before publishing a large
week and after changing Gmail settings.
</p>
</GuideSection>
<GuideSection id="email-settings" title="10. Email and deployment settings">
<p className="text-sm leading-6">
Outbound mail is sent through the team’s Gmail account with an app
password, so messages come from a real church address and land in
recipients’ normal inboxes.
</p>
<GuideFigure
src="/training/screens/admin-email.png"
alt="Email delivery card with Gmail address and app password fields"
caption="The app password is write-only: the saved value is never shown again."
/>
<GuideSteps>
<GuideStep>
Turn on 2-Step Verification for the Google account.
</GuideStep>
<GuideStep>
Create an app password in the Google Account security settings.
</GuideStep>
<GuideStep>
Paste the Gmail address and the 16-character app password here and
press Save. The password is encrypted at rest and never returned to
the browser.
</GuideStep>
<GuideStep>
Send a test email from the Notifications card to confirm delivery.
</GuideStep>
<GuideStep>
Use <strong>Disconnect Gmail</strong> only when switching transports;
mail then falls back to Postmark (if configured) or the console
outbox.
</GuideStep>
</GuideSteps>
<p className="text-sm leading-6">
On <strong>Settings</strong>, admins also see the From address, the
admin notification inbox, church timezone, and the media archive
destination with a readiness check. Change the From address only to a
mailbox the Gmail account is allowed to send as.
</p>
<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."
/>
</GuideSection>
<GuideSection id="backup" title="11. Backup and restore">
<p className="text-sm leading-6">
The backup ZIP contains the Postgres database, training and event
uploads, video derivatives, and the mounted NFS media archive,
including original videos. It does not contain the environment file.
</p>
<GuideFigure
src="/training/screens/admin-backup.png"
alt="Backup and restore card with download and restore controls"
caption="Download before upgrades or risky edits; restore only with a verified ZIP."
/>
<GuideSteps>
<GuideStep>
Press <strong>Download backup</strong> and wait for the ZIP to
finish. Large libraries can take a while.
</GuideStep>
<GuideStep>
Store the ZIP somewhere safe and keep the deployment’s{" "}
<code>NEXTAUTH_SECRET</code> with it — that secret decrypts stored
settings such as the Gmail app password.
</GuideStep>
<GuideStep>
To restore, choose the ZIP, type <code>RESTORE</code>, and confirm.
This replaces the database, uploads, and archive on this deployment.
</GuideStep>
</GuideSteps>
<GuideCallout title="Restore is destructive" tone="warning">
<p>
Restoring replaces current data; it is not a merge. Database changes
are transactional, so a failed SQL load leaves the database as it
was, but files and the archive are replaced as part of the restore.
Take a fresh backup first if the current state matters.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="content" title="12. Announcements and training">
<p className="text-sm leading-6">
Announcements and training lessons are authored in the app, so the team
does not need a deploy to publish news or a new how-to.
</p>
<h3 className="pt-2 text-base font-semibold">Announcements</h3>
<GuideSteps>
<GuideStep>
Open <strong>Announcements</strong>. Admins and coordinators see the
authoring form; volunteers see published posts only.
</GuideStep>
<GuideStep>
Write a title and message. Bodies are plain text, never HTML, so
pasted formatting will not run.
</GuideStep>
<GuideStep>
Keep <strong>Published</strong> ticked to make it visible, or untick
it to save a draft.
</GuideStep>
<GuideStep>
Use the row actions to publish/unpublish or delete a post.
</GuideStep>
</GuideSteps>
<h3 className="pt-2 text-base font-semibold">Training lessons</h3>
<GuideSteps>
<GuideStep>
Open <strong>Training</strong>. Admins get the New lesson form above
the published lessons.
</GuideStep>
<GuideStep>
Add a title, one-line summary, and the lesson body. Line breaks are
preserved, so numbered steps stay readable.
</GuideStep>
<GuideStep>
Set a sort order to control the list position. Lower numbers appear
first.
</GuideStep>
<GuideStep>
Publish when ready. Drafts are visible only to admins.
</GuideStep>
<GuideStep>
Attach a PDF, image, or document with the file control on the lesson,
then <strong>Upload</strong>. Volunteers open attachments from the
lesson; admins can remove them.
</GuideStep>
</GuideSteps>
<GuideCallout title="The two long guides are built in" tone="tip">
<p>
The Platform administration guide and the Volunteer guide appear at
the top of Training as web pages with screenshots and as downloadable
PDFs. They are documentation for this deployment, not editable
lessons, so they stay consistent for every admin.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="exports" title="13. Print and CSV exports">
<p className="text-sm leading-6">
Three exports cover the notice board, the booth, and a spreadsheet.
</p>
<GuideFields
rows={[
{
label: "Printable roster",
value:
"Open /schedule/print from the dashboard or Coverage. It prints the current week grouped by service, with call times and confirmation state; the app chrome is hidden.",
},
{
label: "Schedule CSV",
value:
"GET /api/export/schedule downloads the assignments for a date range (four weeks by default). Useful for mail merges and planning.",
},
{
label: "Serving history CSV",
value:
"GET /api/export/history downloads completed and no-show assignments. Useful for annual reviews and fairness checks.",
},
]}
/>
<GuideFigure
src="/training/screens/admin-print.png"
alt="Printable weekly roster with services, roles, and call times"
caption="The print view is intentionally plain: no navigation, no controls, just the roster."
/>
</GuideSection>
<GuideSection id="troubleshooting" title="14. Troubleshooting">
<GuideFields
rows={[
{
label: "A volunteer cannot sign in",
value:
"Check status (active, not pending) and that the account is not deactivated. Set a temporary password or send a magic link from Edit. If they never set credentials, the magic link takes them to the welcome screen.",
},
{
label: "Email did not arrive",
value:
"Open Notifications and find the row. Failed/suppressed rows show the provider error and offer Retry. Confirm the recipient address and run Send test email. Check spam before resending.",
},
{
label: "A seat will not accept an assignment",
value:
"Read the conflict message. A blackout, missing core skill, or duplicate service assignment is a hard block and needs a different person or a corrected availability entry. A monthly cap is a soft warning you may override.",
},
{
label: "A week is not visible to volunteers",
value:
"Confirm the instance is published. Draft instances are hidden from the volunteer schedule and do not send assignment mail.",
},
{
label: "A coverage request disappeared",
value:
"Approving a release keeps the cancelled assignment as history, but clearing a seat directly from the schedule removes the assignment and its linked request. Check the schedule row and the audit trail before assuming data loss.",
},
{
label: "The Admin tab is missing",
value:
"Your role is coordinator or volunteer. Only admins see /admin; ask an admin to make the change for you.",
},
]}
/>
<p className="text-sm leading-6">
If something looks wrong, take a screenshot and note the time. Most
cards show the exact server error inline, which is far more useful than
“it didn’t work”.
</p>
</GuideSection>
</GuideShell>
);
}
+591
View File
@@ -0,0 +1,591 @@
import type { Metadata } from "next";
import {
GuideCallout,
GuideFields,
GuideFigure,
GuideSection,
GuideShell,
GuideStep,
GuideSteps,
} from "@/components/app/training/guide";
export const metadata: Metadata = {
title: "Volunteer guide",
};
const SECTIONS = [
{ id: "sign-in", title: "Signing in" },
{ id: "home", title: "Your home page" },
{ id: "schedule", title: "Reading the schedule" },
{ id: "availability", title: "Telling us when you are away" },
{ id: "coverage", title: "Swaps and coverage" },
{ id: "run-sheet", title: "The run sheet and checklist" },
{ id: "events", title: "Events and photo folders" },
{ id: "media", title: "The media library" },
{ id: "training", title: "Training" },
{ id: "announcements", title: "Announcements" },
{ id: "profile", title: "Your profile and reminders" },
{ id: "settings", title: "Settings and password" },
{ id: "roster", title: "The roster" },
{ id: "help", title: "When you need help" },
];
export default function VolunteerGuidePage() {
return (
<GuideShell
title="Volunteer guide"
audience="Volunteers and trainees"
intro="A practical walkthrough of the Media Team Hub on a phone or computer: finding your next serve, confirming it, blocking dates you are away, requesting a swap, using the run sheet, and keeping your contact details and notifications current."
pdfHref="/training/media-team-user-guide.pdf"
pdfLabel="Download volunteer PDF"
sections={SECTIONS}
>
<GuideSection id="sign-in" title="1. Signing in">
<p className="text-sm leading-6">
The hub is private to the media team. There is no public sign-up form
inside the app; a coordinator adds you, and you receive a one-time
sign-in link by email.
</p>
<GuideFigure
src="/training/screens/user-login.png"
alt="Sign-in page with username and password fields and the email link option"
caption="Sign in with your username and password, or ask for a one-time link by email."
/>
<GuideSteps>
<GuideStep>
Open the site and go to <strong>Sign in</strong>. Your username is
your email address unless an admin told you otherwise.
</GuideStep>
<GuideStep>
Enter your password. If you do not have one yet, use the email-link
option: type your email and the app sends a one-time sign-in link.
</GuideStep>
<GuideStep>
The first time you follow a link, the app asks you to choose a
username and password. Use at least eight characters and keep it
somewhere safe.
</GuideStep>
<GuideStep>
After that, you land on <strong>Schedule</strong>. Use the same
account on your phone; there is no separate app to install.
</GuideStep>
</GuideSteps>
<GuideCallout title="Links expire" tone="note">
<p>
Magic links work once and expire after ten minutes. If yours has
expired, request a new one. Never forward a sign-in link to someone
else.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="home" title="2. Your home page">
<p className="text-sm leading-6">
Home answers three questions: when am I serving next, what do I need to
respond to, and what else is coming up.
</p>
<GuideFigure
src="/training/screens/user-home.png"
alt="Home page showing the next serve card, confirm and decline buttons, and upcoming serves"
caption="The next-serve card is the first thing to check after a new schedule is published."
/>
<GuideFields
rows={[
{
label: "Your next serve",
value:
"The position, service, date, call time, and location. Confirm or decline from here, open the run sheet, or request coverage.",
},
{
label: "Upcoming serves",
value:
"The next few assignments so you can plan around them. Each row shows the confirmation state.",
},
{
label: "Event assignments",
value:
"Photography or video events you are on, with a link to the event brief and folders.",
},
{
label: "Past serves",
value:
"A short history of recent assignments and how they were recorded.",
},
]}
/>
<GuideSteps>
<GuideStep>
Press <strong>Confirm</strong> as soon as you know you can serve. The
coordinator sees the confirmation immediately.
</GuideStep>
<GuideStep>
Press <strong>Can’t make it</strong> if you cannot serve. Tell a
coordinator as well if the service is close; a declined seat needs a
replacement.
</GuideStep>
<GuideStep>
Use <strong>Availability</strong> and <strong>My profile</strong> at
the top for the two things volunteers change most often.
</GuideStep>
</GuideSteps>
<GuideFigure
src="/training/screens/user-home-mobile.png"
alt="Home page at phone width with the scrollable tab bar"
caption="On a phone the navigation becomes a scrollable tab bar; the next-serve card stays first."
/>
</GuideSection>
<GuideSection id="schedule" title="3. Reading the schedule">
<p className="text-sm leading-6">
The schedule has three lenses. Week is the detailed view; month and
year are overviews for planning.
</p>
<GuideFigure
src="/training/screens/user-schedule.png"
alt="Week schedule with position columns, service rows, and assigned names"
caption="Week view: each column is a position, each row is a service. Your name is on the seat you hold."
/>
<GuideSteps>
<GuideStep>
Open <strong>Schedule</strong>. Use the arrows beside the week to
move one week at a time.
</GuideStep>
<GuideStep>
Read across the row for your service: each position column shows who
is assigned and whether they have confirmed.
</GuideStep>
<GuideStep>
The call time is earlier than the service start. Arrive at the call
time on your next-serve card, not at the service time.
</GuideStep>
<GuideStep>
Switch to <strong>Month</strong> to see every service in a month, or{" "}
<strong>Year</strong> to see how much of the year is built and
published.
</GuideStep>
</GuideSteps>
<GuideFigure
src="/training/screens/user-schedule-month.png"
alt="Month calendar view of services with links back to each week"
caption="Month view is read-only: open a week to see the full seat details."
/>
<GuideCallout title="Draft weeks are invisible" tone="note">
<p>
A week that has not been published does not appear on your schedule
and does not generate assignment email. If you expected a date and
cannot see it, the week is probably still a draft.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="availability" title="4. Telling us when you are away">
<p className="text-sm leading-6">
Availability is the most useful thing you can keep current. It feeds
the ranked candidate list, so blocking a date keeps you from being
suggested while you are away.
</p>
<GuideFigure
src="/training/screens/user-availability.png"
alt="Availability page with the add-unavailable-dates form and the active list"
caption="Add a range once, choose whether it repeats, and keep the note short and useful."
/>
<GuideSteps>
<GuideStep>
Open <strong>Availability</strong> from Home or the navigation.
</GuideStep>
<GuideStep>
Choose a type: vacation, away, recurring commitment, or preference.
The type is a label for coordinators, not a different calculation.
</GuideStep>
<GuideStep>
Pick the first and last unavailable date. A single day uses the same
date twice.
</GuideStep>
<GuideStep>
Choose a repeat pattern if the commitment is regular: every week,
every other week, every four weeks, the 1st and 3rd of the month, or
the last of the month. The pattern is anchored to the weekday of the
start date.
</GuideStep>
<GuideStep>
Add a short note (“work travel”, “school term”) and press{" "}
<strong>Add unavailable dates</strong>.
</GuideStep>
</GuideSteps>
<p className="text-sm leading-6">
Active ranges appear on the right with their repeat label. Use{" "}
<strong>Edit</strong> to change one, or <strong>Remove</strong> to end
it. Removing a recurring entry stops the whole pattern.
</p>
<GuideCallout title="Availability does not change an existing seat" tone="warning">
<p>
If you are already scheduled for a date, blocking it afterwards does
not remove you. Use <strong>Request coverage</strong> on that
assignment and tell a coordinator.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="coverage" title="5. Swaps and coverage">
<p className="text-sm leading-6">
When life changes, request coverage rather than simply not showing up.
The request keeps you on the seat until a coordinator resolves it, so
the team is never left guessing.
</p>
<GuideSteps>
<GuideStep>
On Home, find the serve under <strong>Your next serve</strong> or{" "}
<strong>Upcoming serves</strong>.
</GuideStep>
<GuideStep>
Press <strong>Request coverage</strong> and add a short reason. A
specific reason helps the coordinator find the right replacement.
</GuideStep>
<GuideStep>
The button changes to a pending state. You are still responsible for
the seat until you hear that the request was resolved.
</GuideStep>
<GuideStep>
If the service is within 48 hours, also message a coordinator
directly. The app does not page anyone.
</GuideStep>
</GuideSteps>
<GuideCallout title="What the coordinator sees" tone="note">
<p>
They see the request with a ranked list of eligible replacements.
Approving places someone else and cancels your assignment; approving
without a replacement releases the seat; declining leaves you on it.
You will see the change on Home once it is resolved.
</p>
</GuideCallout>
<p className="text-sm leading-6">
Ministry leaders outside the team can request coverage through the
public form at <code>/request-coverage</code>. If you are asked to
share a link, that is the one to send.
</p>
<GuideFigure
src="/training/screens/user-request-coverage.png"
alt="Public request coverage form with contact, ministry, event, date, and time fields"
caption="The public intake form needs no account; coordinators turn accepted requests into events."
/>
</GuideSection>
<GuideSection id="run-sheet" title="6. The run sheet and checklist">
<p className="text-sm leading-6">
The run sheet is the shared plan for one service: speaker, message,
links, cues, and the pre/post checklist. Open it from the next-serve
card on Home.
</p>
<GuideFigure
src="/training/screens/user-run-sheet.png"
alt="Run sheet as seen by a volunteer, with service details, cues, and checklists"
caption="Volunteers see the details read-only but can tick checklist items as they are done."
/>
<GuideSteps>
<GuideStep>
Read the speaker, message title, stream and slides links, and the
team notes before the service.
</GuideStep>
<GuideStep>
Follow the cue list in time order. The owner column says who is
responsible for each cue.
</GuideStep>
<GuideStep>
Tick pre-service items as you complete them. Tick post-service items
during teardown. The app records who ticked each item and when.
</GuideStep>
<GuideStep>
Press <strong>Print</strong> if you want a paper copy for the booth.
</GuideStep>
</GuideSteps>
<GuideCallout title="Tick honestly, tick together" tone="tip">
<p>
The checklist is shared in real time. Two people ticking the same
item is harmless; an unticked item is the signal that something still
needs doing.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="events" title="7. Events and photo folders">
<p className="text-sm leading-6">
Events are photoshoots, weddings, outreach nights, and other coverage
outside the weekly services. You see the events you are assigned to;
coordinators see all of them.
</p>
<GuideFigure
src="/training/screens/user-events.png"
alt="Events list with upcoming event cards and assignment counts"
caption="Events you are assigned to appear first, with the date, location, and folder count."
/>
<GuideSteps>
<GuideStep>
Open <strong>Events</strong> and choose an event.
</GuideStep>
<GuideStep>
Read the shot brief, location, time, and assigned team before you
arrive.
</GuideStep>
<GuideStep>
Open a folder to upload originals or edited files. Use the folder
kind as a guide: RAW/originals, edited exports, or mixed.
</GuideStep>
<GuideStep>
Download individual files, or use{" "}
<strong>Download all</strong> on the event to get every photo in one
ZIP.
</GuideStep>
<GuideStep>
After the event, upload your selects and tell the coordinator the
folder is ready. Archived events remain readable but stop accepting
new uploads.
</GuideStep>
</GuideSteps>
<GuideFigure
src="/training/screens/user-event.png"
alt="Event detail page with brief, assigned photographers, and shared folders"
caption="The event page is the handoff point: brief at the top, folders and files below."
/>
</GuideSection>
<GuideSection id="media" title="8. The media library">
<p className="text-sm leading-6">
Media collects the event photos and videos you can access in one
ad-free library. It is a convenience view, not a second copy: access
still follows event assignment.
</p>
<GuideFigure
src="/training/screens/user-media.png"
alt="Media library with video cards and event photo thumbnails"
caption="Videos play from the generated MP4; originals stay on the church archive."
/>
<GuideFields
rows={[
{
label: "Videos",
value:
"Play a video, see its duration and status, and open the watch page. Videos stay private to the team until a manager publishes an unlisted or public version.",
},
{
label: "Photos",
value:
"Browse event photos you can access and open one to view or download. The photo’s event controls who can see it.",
},
{
label: "Uploading",
value:
"Video upload starts from the Media page or an event page. Large files upload in chunks; keep the tab open until it finishes.",
},
]}
/>
<GuideCallout title="Do not share private links" tone="warning">
<p>
A media link only works for someone with access. Do not post a
private event photo or video publicly; ask a manager to publish an
approved version if the church needs it public.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="training" title="9. Training">
<p className="text-sm leading-6">
Training is the team’s how-to library. Lessons are written by admins
and can carry attachments such as PDFs, checklists, or reference
images.
</p>
<GuideFigure
src="/training/screens/user-training.png"
alt="Training page with the two full guides at the top and published lessons below"
caption="Start with the two full guides, then use the shorter lessons for specific skills."
/>
<GuideSteps>
<GuideStep>
Open <strong>Training</strong> from the navigation.
</GuideStep>
<GuideStep>
Read the <strong>Volunteer guide</strong> once end to end; it covers
every screen in this app.
</GuideStep>
<GuideStep>
Open an attachment to read or download it. Links open in a new tab so
you do not lose your place.
</GuideStep>
<GuideStep>
Use the PDF download on either guide for an offline copy you can keep
on your phone.
</GuideStep>
</GuideSteps>
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
<p>
The run sheet and checklist are the two things new volunteers most
often ask about. Reading that section once saves a lot of questions
on a Sunday morning.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="announcements" title="10. Announcements">
<p className="text-sm leading-6">
Announcements carry team news: schedule changes, gear notes, training
dates, and reminders. Everyone signed in can read published posts;
coordinators and admins can write them.
</p>
<GuideFigure
src="/training/screens/user-announcements.png"
alt="Announcements feed with a published post and author information"
caption="Check the feed before a busy weekend; last-minute changes are posted here."
/>
<p className="text-sm leading-6">
Posts are plain text, so links are shown as text rather than clickable
formatting. If a post raises a question, reply through your normal team
channel.
</p>
</GuideSection>
<GuideSection id="profile" title="11. Your profile and reminders">
<p className="text-sm leading-6">
Your profile is where the team gets your contact details and where you
control how the app talks to you.
</p>
<GuideFigure
src="/training/screens/user-profile.png"
alt="Profile page with contact details, notification preferences, comfort ratings, and calendar feed"
caption="Keep phone and emergency contact current; they matter on a serve day."
/>
<GuideFields
rows={[
{
label: "Contact details",
value:
"Name, display name, email, phone, timezone, and emergency contact. Use the international phone format, for example +15551234567.",
},
{
label: "Notifications",
value:
"Turn email on or off, set how many days ahead a reminder should arrive, choose digest-only mail, and set quiet hours so reminders do not arrive overnight.",
},
{
label: "Skill comfort",
value:
"Rate how comfortable you feel with each skill. This is your own signal; it is separate from the verified level a coordinator records and is never overwritten by verification.",
},
{
label: "Calendar feed",
value:
"Copy your personal calendar URL into Google Calendar, Apple Calendar, or Outlook to see your serves automatically. Reset the link if it was shared by mistake; the old URL stops working.",
},
]}
/>
<GuideSteps>
<GuideStep>
Open <strong>My profile</strong> from Home or Settings.
</GuideStep>
<GuideStep>
Edit contact details and press <strong>Save profile</strong>.
</GuideStep>
<GuideStep>
Adjust reminder preferences and press{" "}
<strong>Save preferences</strong>.
</GuideStep>
<GuideStep>
Move the comfort sliders and press <strong>Save comfort ratings</strong>{" "}
when you have changed several.
</GuideStep>
<GuideStep>
Press <strong>Copy calendar link</strong> and add it as a subscribed
calendar in your calendar app. Press <strong>Reset link</strong> only
if the old link needs to stop working.
</GuideStep>
</GuideSteps>
</GuideSection>
<GuideSection id="settings" title="12. Settings and password">
<p className="text-sm leading-6">
Settings holds your account credentials and the church facts the app
uses for scheduling and messages.
</p>
<GuideFigure
src="/training/screens/user-settings.png"
alt="Settings page with account password form and church details"
caption="Changing your username or password does not sign you out of the current session."
/>
<GuideSteps>
<GuideStep>
Open <strong>Settings</strong>.
</GuideStep>
<GuideStep>
Change your username if the email-as-username default does not suit
you. It must stay unique.
</GuideStep>
<GuideStep>
Enter a new password twice and save. Use at least eight characters.
</GuideStep>
<GuideStep>
If you have forgotten the current password, sign out and use the
email-link option on the sign-in page instead.
</GuideStep>
</GuideSteps>
<GuideCallout title="Your timezone matters" tone="note">
<p>
The church schedules in its own timezone. Your profile timezone
controls how times appear to you, so keep it correct when you travel
or move.
</p>
</GuideCallout>
</GuideSection>
<GuideSection id="roster" title="13. The roster">
<p className="text-sm leading-6">
The roster lists active team members with their role and email, so you
can put a name to a seat and reach the right person.
</p>
<GuideFigure
src="/training/screens/user-roster.png"
alt="Roster table with active team members, roles, and email addresses"
caption="The roster shows active people only; deactivated accounts are hidden."
/>
<p className="text-sm leading-6">
Trainees do not see the roster. If you need a contact and cannot see
one, ask a coordinator.
</p>
</GuideSection>
<GuideSection id="help" title="14. When you need help">
<GuideFields
rows={[
{
label: "Cannot sign in",
value:
"Request a new email link from the sign-in page. If the link never arrives, ask an admin to check your account status or send a magic link.",
},
{
label: "Cannot serve a date",
value:
"Use Request coverage on Home, then message a coordinator if the date is close. Do not simply leave the seat unconfirmed.",
},
{
label: "Wrong dates on the schedule",
value:
"Check that your availability is current, then tell a coordinator. Only coordinators and admins can edit assignments.",
},
{
label: "Trouble with a photo or video upload",
value:
"Keep the tab open until the upload finishes, check your connection, and try a smaller file. Ask a coordinator before retrying a very large video repeatedly.",
},
{
label: "A page looks out of date",
value:
"Pull to refresh or reload. The schedule and checklists are shared, so a reload picks up someone else’s change.",
},
]}
/>
<p className="text-sm leading-6">
The team’s rule is simple: communicate early. A covered seat and a
clear run sheet are worth far more than a perfect attendance record
nobody knew about.
</p>
</GuideSection>
</GuideShell>
);
}
+95 -10
View File
@@ -1,16 +1,101 @@
import { StateMessage } from "@/components/app/state-message";
import Link from "next/link";
import { auth } from "@/auth/config";
import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listLessons } from "@/db/training";
import { TrainingPanel } from "@/components/app/training-panel";
import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
export const metadata = { title: "Training" };
export default function TrainingPage() {
/**
* Training content. Volunteers see published lessons and attachments; admins
* can author, publish, upload, and delete. Content is stored in Postgres and
* attachments under the uploads volume, so it is editable with no deploy.
*/
export default async function TrainingPage() {
const session = await auth();
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
const canEdit = hasPermission(role, "training.author");
const lessons = await listLessons({ includeUnpublished: canEdit });
return (
<>
<h1 className="text-lg font-semibold tracking-tight">Training</h1>
<p className="text-sm text-muted-foreground">How-tos and tutorials, with progress tied to your roles.</p>
<StateMessage
title="No courses available"
description="Training lessons will appear here. Some are required before you can serve certain roles."
/>
</>
<div className="space-y-4">
<div>
<h1 className="text-lg font-semibold tracking-tight">Training</h1>
<p className="text-sm text-muted-foreground">
How-tos and checklists for serving on the media team.
</p>
</div>
<section aria-labelledby="full-guides" className="space-y-3">
<div>
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
Full guides
</h2>
<p className="text-sm text-muted-foreground">
Complete, illustrated walkthroughs with screenshots. Read them here
or download the PDF for printing and offline use.
</p>
</div>
<div className="grid gap-3 md:grid-cols-2">
<div className="flex flex-col rounded-md border border-border p-4">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
Admins
</div>
<h3 className="mt-2 text-base font-semibold">
Platform administration guide
</h3>
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
People and access, skill verification, positions, services and
publishing, coverage, run sheets, email, notifications, backups,
and exports.
</p>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
<Link href="/training/guides/admin" className="text-primary underline">
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
Read the guide
</Link>
<a
href="/training/media-team-admin-guide.pdf"
download
className="inline-flex items-center gap-1 text-primary underline"
>
<Download className="h-4 w-4" aria-hidden="true" />
Download PDF
</a>
</div>
</div>
<div className="flex flex-col rounded-md border border-border p-4">
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
<UserRound className="h-4 w-4" aria-hidden="true" />
Volunteers &amp; trainees
</div>
<h3 className="mt-2 text-base font-semibold">Volunteer guide</h3>
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
Signing in, your next serve, the schedule, availability, swaps,
run sheets, events and media, training, profile, and reminders.
</p>
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
<Link href="/training/guides/user" className="text-primary underline">
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
Read the guide
</Link>
<a
href="/training/media-team-user-guide.pdf"
download
className="inline-flex items-center gap-1 text-primary underline"
>
<Download className="h-4 w-4" aria-hidden="true" />
Download PDF
</a>
</div>
</div>
</div>
</section>
<TrainingPanel lessons={lessons} canEdit={canEdit} />
</div>
);
}
@@ -0,0 +1,20 @@
import { z } from "zod";
import { gateSession } from "@/auth/api";
import { rotateCalendarFeedToken } from "@/db/volunteer";
import { requestOrigin } from "@/auth/magic-link";
import { jsonResponse, errorResponse } from "@/lib/http";
const bodySchema = z.object({ action: z.literal("rotate") });
/** POST /api/account/calendar-feed { action: "rotate" } */
export async function POST(req: Request) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) return errorResponse(400, "invalid action");
const token = await rotateCalendarFeedToken(gate.id);
const origin = requestOrigin(req as Request & { headers: Headers });
return jsonResponse({ token, url: `${origin}/api/calendar/${token}` });
}
+95
View File
@@ -0,0 +1,95 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateSession } from "@/auth/api";
import {
hashPassword,
normalizeUsername,
validatePassword,
validateUsername,
verifyPassword,
} from "@/auth/password";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import {
credentialTaken,
getUserSecurity,
updateUserCredentials,
} from "@/db/users";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (payload: unknown, status = 200) =>
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
const bad = (message: string) => json({ error: message }, 400);
const conflict = (message: string) => json({ error: message }, 409);
const bodySchema = z.object({
username: z.string().min(1).max(100).optional(),
currentPassword: z.string().max(200).optional(),
newPassword: z.string().min(1).max(200),
});
/**
* Set or change the signed-in person's password.
*
* A magic-link session is enough for the first-time setup, where no password
* exists yet. Once one exists, the current password is required so a borrowed
* browser session cannot silently lock the owner out.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
let body: unknown;
try {
body = await req.json();
} catch {
return bad("A JSON body is required.");
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
const account = await getUserSecurity(gate.id);
if (!account) return json({ error: "unknown user" }, 404);
if (account.passwordHash) {
if (!parsed.data.currentPassword) {
return bad("Enter your current password.");
}
if (!(await verifyPassword(parsed.data.currentPassword, account.passwordHash))) {
return bad("Your current password is incorrect.");
}
}
const passwordError = validatePassword(parsed.data.newPassword);
if (passwordError) return bad(passwordError);
const nextUsername = parsed.data.username
? normalizeUsername(parsed.data.username)
: account.username;
if (parsed.data.username) {
const usernameError = validateUsername(nextUsername);
if (usernameError) return bad(usernameError);
if (await credentialTaken(nextUsername, gate.id)) {
return conflict("That username is already in use.");
}
}
const passwordHash = await hashPassword(parsed.data.newPassword);
const updated = await updateUserCredentials(gate.id, {
username: nextUsername,
passwordHash,
});
if (!updated) return json({ error: "unknown user" }, 404);
await writeAudit(db, {
actorId: gate.id,
action: account.passwordHash
? "user.password_changed"
: "user.password_set",
entityType: "user",
entityId: gate.id,
after: { username: updated.username, passwordSet: true },
});
return json({ ok: true, username: updated.username, passwordSet: true });
};
+90
View File
@@ -0,0 +1,90 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser, gateSession } from "@/auth/api";
import { hasPermission } from "@/auth/permissions";
import {
createAnnouncement,
deleteAnnouncement,
listAnnouncements,
updateAnnouncement,
} from "@/db/announcements";
import { errorResponse, jsonResponse } from "@/lib/http";
const createSchema = z.object({
title: z.string().trim().min(1).max(200),
body: z.string().max(20_000).optional(),
published: z.boolean().optional(),
});
const patchSchema = z.object({
id: z.string().min(1),
title: z.string().trim().min(1).max(200).optional(),
body: z.string().max(20_000).optional(),
published: z.boolean().optional(),
});
/**
* Announcements. Any signed-in user reads published posts; authors
* (`content.author` = admin/coordinator) also see drafts and can write.
*
* GET -> { announcements }
* POST -> { announcement }
* PATCH -> { announcement } edit or publish/unpublish
* DELETE ?id= -> { ok }
*/
export const GET = async () => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const canAuthor = hasPermission(gate.systemRole, "content.author");
return jsonResponse({
announcements: await listAnnouncements({
includeUnpublished: canAuthor,
}),
});
};
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("content.author");
if (gate instanceof Response) return gate;
const parsed = createSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post");
}
const announcement = await createAnnouncement({
title: parsed.data.title,
body: parsed.data.body ?? "",
published: parsed.data.published ?? false,
createdBy: gate.id,
});
return jsonResponse({ announcement }, 201);
};
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("content.author");
if (gate instanceof Response) return gate;
const parsed = patchSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid post");
}
const { id, ...patch } = parsed.data;
const announcement = await updateAnnouncement(id, patch);
if (!announcement) return errorResponse(404, "unknown announcement");
return jsonResponse({ announcement });
};
export const DELETE = async (req: NextRequest) => {
const gate = await gateOrUser("content.author");
if (gate instanceof Response) return gate;
const id = req.nextUrl.searchParams.get("id");
if (!id) return errorResponse(400, "an id is required");
const deleted = await deleteAnnouncement(id);
if (!deleted) return errorResponse(404, "unknown announcement");
return jsonResponse({ ok: true });
};
@@ -0,0 +1,47 @@
import { z } from "zod";
import { gateSession } from "@/auth/api";
import { RespondError, respondToAssignment } from "@/db/respond";
import { errorResponse, jsonResponse } from "@/lib/http";
const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
function errorStatus(code: RespondError["code"]): number {
switch (code) {
case "unknown_assignment":
return 404;
case "wrong_volunteer":
return 403;
case "not_actionable":
case "already_used":
return 409;
}
}
/** POST /api/assignments/:id/respond { action: "confirm" | "decline" } */
export async function POST(
req: Request,
{ params }: { params: Promise<{ id: string }> },
) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) return errorResponse(400, "invalid action");
const { id } = await params;
try {
const result = await respondToAssignment({
assignmentId: id,
userId: gate.id,
action: parsed.data.action,
via: "app",
});
return jsonResponse({ ok: true, ...result });
} catch (error) {
if (error instanceof RespondError) {
return errorResponse(errorStatus(error.code), error.message, error.code);
}
console.error("[assignment-respond] ERROR", error);
return errorResponse(500, "failed to update the assignment");
}
}
@@ -0,0 +1,16 @@
import { gateOrUser } from "@/auth/api";
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
import { errorResponse, jsonResponse } from "@/lib/http";
/** GET /api/assignments/candidates?slotId=... — ranked eligible/excluded list. */
export async function GET(req: Request) {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const slotId = new URL(req.url).searchParams.get("slotId")?.trim();
if (!slotId) return errorResponse(400, "a slotId is required");
const result = await rankedCandidatesForSlot(slotId);
if (!result) return errorResponse(404, "slot not found");
return jsonResponse(result);
}
+136 -71
View File
@@ -1,14 +1,25 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { and, eq, sql } from "drizzle-orm";
import { and, eq, inArray } from "drizzle-orm";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { db } from "@/db";
import { assignments, slots } from "@/db/schema";
import { writeAudit } from "@/db/audit";
import { activeAssignmentInInstance } from "@/db/assignments";
import { assignHardConflicts } from "@/domain/assign";
import {
assignments,
auditLog,
serviceInstances,
slots,
} from "@/db/schema";
import { auditRow } from "@/db/audit";
import {
AssignFactError,
resolveAssignFacts,
} from "@/db/assignments";
import { cancelAssignmentNotifications } from "@/db/outbox";
import { enqueuePublishNotifications } from "@/db/outbox";
import { enqueueRemindersForInstance } from "@/db/reminders";
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
import { uuidv7 } from "@/lib/uuid";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -19,6 +30,8 @@ const bodySchema = z.object({
userId: z.string().min(1).optional(),
});
const ACTIVE_STATUSES = ["proposed", "confirmed", "completed"] as const;
/** Walk an error's cause chain to its SQLSTATE (23505 = unique, 23503 = FK). */
function sqlStateCode(err: unknown): string | undefined {
let node = err as { code?: string; cause?: unknown } | null;
@@ -30,18 +43,21 @@ function sqlStateCode(err: unknown): string | undefined {
}
/**
* Assign / clear an assignment (unit D8).
* Assign / clear an assignment (units D8 + D5/D9 integration).
*
* POST { action: "assign"|"clear", slotId, userId? }
*
* - assign -> creates a `proposed`/`manual` assignment after the rule-1
* duplicate-in-instance gate; writes an `assignment.created`
* audit row.
* - clear -> deletes the active assignment on the slot; writes an
* `assignment.cleared` audit row.
* - assign -> runs the full conflict engine (roster, one-per-instance,
* core-skill level, shadow pairing, blackout, cap, back-to-back)
* and rejects on any HARD conflict. Soft conflicts are returned
* as warnings. Creates `proposed`/`manual`, syncs the slot
* status, audits, and re-enqueues mail when the week is already
* published.
* - clear -> cancels that assignment's pending mail BEFORE deleting it (so
* a removed seat cannot still send "you're serving"), reopens the
* slot, audits.
*
* Guarded by `schedule.publish` (coordinator + admin). Hard conflicts reject
* 409; a DB unique violation on the slot rejects 409 (rule 2).
* Guarded by `schedule.publish` (coordinator + admin).
*/
export const POST = async (req: NextRequest) => {
let action: string | undefined;
@@ -70,7 +86,10 @@ export const POST = async (req: NextRequest) => {
try {
const session = await auth();
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
const user = session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
if (!user) {
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
status: 401,
@@ -81,32 +100,45 @@ export const POST = async (req: NextRequest) => {
const actorId = user.id;
if (parsed.data.action === "clear") {
const active = await db
.select({ id: assignments.id })
const [active] = await db
.select({
id: assignments.id,
slotId: assignments.slotId,
})
.from(assignments)
.where(
and(
eq(assignments.slotId, parsed.data.slotId),
sql`${assignments.status} IN ('proposed','confirmed','completed')`,
inArray(assignments.status, [...ACTIVE_STATUSES]),
),
)
.limit(1);
if (active.length === 0) {
if (!active) {
return new Response(JSON.stringify({ error: "no active assignment on this slot" }), {
status: 404,
headers: JSON_HEADERS,
});
}
await db.delete(assignments).where(eq(assignments.id, active[0].id));
await writeAudit(db, {
actorId,
action: "assignment.cleared",
entityType: "assignment",
entityId: active[0].id,
after: { slotId: parsed.data.slotId },
await db.transaction(async (tx) => {
await cancelAssignmentNotifications(active.id, new Date(), tx);
await tx.delete(assignments).where(eq(assignments.id, active.id));
await tx
.update(slots)
.set({ status: "open" })
.where(eq(slots.id, active.slotId));
await tx.insert(auditLog).values(
auditRow({
actorId,
action: "assignment.cleared",
entityType: "assignment",
entityId: active.id,
after: { slotId: parsed.data.slotId },
}),
);
});
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: JSON_HEADERS,
@@ -114,70 +146,102 @@ export const POST = async (req: NextRequest) => {
}
// assign
if (!parsed.data.userId) {
const assignUserId = parsed.data.userId;
if (!assignUserId) {
return new Response(JSON.stringify({ error: "a userId is required to assign" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const slotRows = await db
.select({ id: slots.id, serviceInstanceId: slots.serviceInstanceId })
let facts;
try {
facts = await resolveAssignFacts({
userId: assignUserId,
slotId: parsed.data.slotId,
});
} catch (e) {
if (e instanceof AssignFactError) {
const status = e.code === "unknown_slot" || e.code === "unknown_user" ? 404 : 400;
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status,
headers: JSON_HEADERS,
});
}
throw e;
}
const conflicts = classifyConflicts(facts);
const hard = hardConflicts(conflicts);
if (hard.length > 0) {
return new Response(
JSON.stringify({
error: hard.map((conflict) => conflict.message).join(" "),
code: hard[0].code,
conflicts: hard,
}),
{ status: 409, headers: JSON_HEADERS },
);
}
const [instance] = await db
.select({
id: serviceInstances.id,
status: serviceInstances.status,
})
.from(slots)
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
.where(eq(slots.id, parsed.data.slotId))
.limit(1);
if (slotRows.length === 0) {
return new Response(JSON.stringify({ error: "unknown slot" }), {
status: 404,
headers: JSON_HEADERS,
});
}
const instanceId = slotRows[0].serviceInstanceId;
if (!instanceId) {
return new Response(JSON.stringify({ error: "slot is not attached to a service instance" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const existing = await activeAssignmentInInstance(db, {
userId: parsed.data.userId,
instanceId,
});
const conflicts = assignHardConflicts({ alreadyAssignedInInstance: existing != null });
if (conflicts.length > 0) {
return new Response(JSON.stringify({ error: conflicts[0].message, code: conflicts[0].code }), {
status: 409,
headers: JSON_HEADERS,
});
}
const result = await db
.insert(assignments)
.values({
id: uuidv7(),
const assignmentId = uuidv7();
await db.transaction(async (tx) => {
await tx.insert(assignments).values({
id: assignmentId,
slotId: parsed.data.slotId,
userId: parsed.data.userId,
userId: assignUserId,
status: "proposed",
source: "manual",
assignedBy: actorId,
assignedAt: new Date(),
})
.returning({ id: assignments.id, status: assignments.status });
});
await tx
.update(slots)
.set({ status: "proposed" })
.where(eq(slots.id, parsed.data.slotId));
await tx.insert(auditLog).values(
auditRow({
actorId,
action: "assignment.created",
entityType: "assignment",
entityId: assignmentId,
before: { slotId: parsed.data.slotId },
after: {
slotId: parsed.data.slotId,
userId: assignUserId,
status: "proposed",
},
}),
);
await writeAudit(db, {
actorId,
action: "assignment.created",
entityType: "assignment",
entityId: result[0].id,
before: { slotId: parsed.data.slotId },
after: { slotId: parsed.data.slotId, userId: parsed.data.userId, status: "proposed" },
// A published week's mail is written at publish time; a seat added later
// would otherwise never be announced. Both enqueues are idempotent on
// dedupe_key, so existing rows are untouched.
if (instance?.status === "published") {
await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
}
});
return new Response(JSON.stringify({ ok: true, id: result[0].id, status: result[0].status }), {
status: 201,
headers: JSON_HEADERS,
});
return new Response(
JSON.stringify({
ok: true,
id: assignmentId,
status: "proposed",
warnings: conflicts.filter((conflict) => conflict.severity === "soft"),
}),
{ status: 201, headers: JSON_HEADERS },
);
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
@@ -191,6 +255,7 @@ export const POST = async (req: NextRequest) => {
headers: JSON_HEADERS,
});
}
console.error("[assignments] ERROR", e);
return new Response(JSON.stringify({ error: "failed to assign" }), {
status: 500,
headers: JSON_HEADERS,
+68
View File
@@ -0,0 +1,68 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import {
consumeMagicToken,
getUser,
verifyPasswordResetToken,
} from "@/auth/magic-link";
import { hashPassword, validatePassword } from "@/auth/password";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { updateUserCredentials } from "@/db/users";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (payload: unknown, status = 200) =>
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
const bodySchema = z.object({
token: z.string().min(1),
newPassword: z.string().min(1).max(200),
});
/**
* Complete an admin-issued password reset. The token is single-use and is
* consumed before the new hash is written, so replaying the same link cannot
* reset the account twice.
*/
export const POST = async (req: NextRequest) => {
let body: unknown;
try {
body = await req.json();
} catch {
return json({ error: "A JSON body is required." }, 400);
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return json({ error: parsed.error.message }, 400);
const passwordError = validatePassword(parsed.data.newPassword);
if (passwordError) return json({ error: passwordError }, 400);
const payload = await verifyPasswordResetToken(parsed.data.token);
if (!payload) {
return json({ error: "This reset link is invalid or has expired." }, 400);
}
const user = await getUser(payload.email);
if (!user || user.status !== "active" || user.deactivatedAt) {
return json({ error: "This account cannot reset its password." }, 400);
}
const consumed = await consumeMagicToken(payload);
if (!consumed) {
return json({ error: "This reset link has already been used." }, 409);
}
const passwordHash = await hashPassword(parsed.data.newPassword);
const updated = await updateUserCredentials(user.id, { passwordHash });
if (!updated) return json({ error: "unknown user" }, 404);
await writeAudit(db, {
actorId: user.id,
action: "user.password_reset",
entityType: "user",
entityId: user.id,
after: { passwordSet: true },
});
return json({ ok: true });
};
+39
View File
@@ -0,0 +1,39 @@
import {
calendarFeedForUser,
getCalendarFeedOwner,
} from "@/db/volunteer";
import { buildCalendar } from "@/lib/ics";
export const dynamic = "force-dynamic";
/**
* Public, bearer-by-URL calendar feed. The token is long and random; it is not
* an account session and grants read-only access to that person's assignments.
*/
export async function GET(
_req: Request,
{ params }: { params: Promise<{ token: string }> },
) {
const { token } = await params;
if (!token || token.length < 20 || token.length > 128) {
return new Response("Calendar not found", { status: 404 });
}
const owner = await getCalendarFeedOwner(token);
if (!owner) return new Response("Calendar not found", { status: 404 });
const events = await calendarFeedForUser(owner.id);
const body = buildCalendar({
calendarName: `${owner.displayName} — Media Team`,
events,
});
return new Response(body, {
status: 200,
headers: {
"content-type": "text/calendar; charset=utf-8",
"content-disposition": 'inline; filename="media-team.ics"',
"cache-control": "private, no-store, max-age=0",
},
});
}
+100
View File
@@ -0,0 +1,100 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { clientIp, gateOrUser } from "@/auth/api";
import { rateLimit } from "@/lib/rate-limit";
import {
IntakeError,
createCoverageIntake,
declineCoverageIntake,
scheduleCoverageIntake,
} from "@/db/intake";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
const intakeSchema = z.object({
requesterName: z.string().min(2).max(120),
requesterEmail: z.string().email().max(200),
requesterPhone: z.string().max(40).nullable().optional(),
ministry: z.string().max(120).nullable().optional(),
title: z.string().min(3).max(200),
eventType: z.string().max(60).optional(),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
startTime: z.string().regex(/^\d{2}:\d{2}$/),
endTime: z.string().regex(/^\d{2}:\d{2}$/).nullable().optional(),
location: z.string().max(200).nullable().optional(),
description: z.string().max(2000).nullable().optional(),
});
const reviewSchema = z.object({
id: z.string().min(1),
action: z.enum(["schedule", "decline"]),
});
async function body(req: NextRequest): Promise<unknown> {
try {
return await req.json();
} catch {
return null;
}
}
/**
* Public submission endpoint. Rate-limited per IP; the response never reveals
* whether an identical request already exists.
*/
export const POST = async (req: NextRequest) => {
const limit = rateLimit(`coverage-intake:${clientIp(req)}`, 5, 60 * 60 * 1000);
if (!limit.ok) {
return new Response(
JSON.stringify({ error: "Too many requests. Please try again later." }),
{
status: 429,
headers: {
...JSON_HEADERS,
"retry-after": String(limit.retryAfterSeconds),
},
},
);
}
const parsed = intakeSchema.safeParse(await body(req));
if (!parsed.success) {
return json({ error: parsed.error.issues[0]?.message ?? "Invalid request" }, 400);
}
try {
await createCoverageIntake(parsed.data);
return json({ ok: true }, 201);
} catch (err) {
if (err instanceof IntakeError) return json({ error: err.message }, err.status);
console.error("[coverage-intake] submit failed", err);
return json({ error: "Could not submit the request." }, 500);
}
};
/** Coordinator review: turn an accepted request into an event, or decline it. */
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const parsed = reviewSchema.safeParse(await body(req));
if (!parsed.success) return json({ error: parsed.error.message }, 400);
try {
if (parsed.data.action === "schedule") {
const row = await scheduleCoverageIntake({
id: parsed.data.id,
actorId: gate.id,
});
return json({ ok: true, ...row });
}
await declineCoverageIntake({ id: parsed.data.id, actorId: gate.id });
return json({ ok: true });
} catch (err) {
if (err instanceof IntakeError) return json({ error: err.message }, err.status);
console.error("[coverage-intake] review failed", err);
return json({ error: "Could not review the request." }, 500);
}
};
+81
View File
@@ -0,0 +1,81 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser, gateSession } from "@/auth/api";
import {
CoverageError,
createCoverageRequest,
resolveCoverageRequest,
} from "@/db/coverage";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
const createSchema = z.object({
assignmentId: z.string().min(1),
reason: z.string().max(500).nullable().optional(),
});
const resolveSchema = z.object({
id: z.string().min(1),
action: z.enum(["approve", "decline", "cancel"]),
replacementUserId: z.string().min(1).nullable().optional(),
});
async function body(req: NextRequest): Promise<unknown> {
try {
return await req.json();
} catch {
return null;
}
}
/** A volunteer asks for coverage on their own assignment. */
export const POST = async (req: NextRequest) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const parsed = createSchema.safeParse(await body(req));
if (!parsed.success) return json({ error: parsed.error.message }, 400);
try {
const row = await createCoverageRequest({
assignmentId: parsed.data.assignmentId,
userId: gate.id,
reason: parsed.data.reason ?? null,
});
return json({ ok: true, ...row }, 201);
} catch (err) {
if (err instanceof CoverageError) {
return json({ error: err.message }, err.status);
}
console.error("[coverage] create failed", err);
return json({ error: "could not create the coverage request" }, 500);
}
};
/** A coordinator approves (with or without a replacement) or declines. */
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const parsed = resolveSchema.safeParse(await body(req));
if (!parsed.success) return json({ error: parsed.error.message }, 400);
try {
const result = await resolveCoverageRequest({
requestId: parsed.data.id,
actorId: gate.id,
action: parsed.data.action,
replacementUserId: parsed.data.replacementUserId ?? null,
});
return json({ ok: true, ...result });
} catch (err) {
if (err instanceof CoverageError) {
return json({ error: err.message }, err.status);
}
console.error("[coverage] resolve failed", err);
return json({ error: "could not update the coverage request" }, 500);
}
};
+26 -5
View File
@@ -1,6 +1,10 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { approveUser } from "@/auth/invites";
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
import { getUserById } from "@/db/users";
import { sendWelcomeEmail } from "@/lib/welcome-email";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({
@@ -12,6 +16,9 @@ const bodySchema = z.object({
* Approve a pending user -> active. POST { userId, approvedBy? }.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
let userId: string | undefined;
let approvedBy: string | undefined;
try {
@@ -33,12 +40,26 @@ export const POST = async (req: NextRequest) => {
try {
const user = await approveUser({
userId: parsed.data.userId,
approvedBy: parsed.data.approvedBy ?? "admin",
});
return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), {
status: 200,
headers: JSON_HEADERS,
// Server-owned: a caller cannot attribute the approval to someone else.
approvedBy: gate.id,
});
// The account can now sign in, so this is the moment to send its details.
const approved = await getUserById(user.id);
let welcome: { delivered: boolean; transport: string | null } | null = null;
if (approved) {
const token = await signMagicToken(approved.email);
const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token,
)}&email=${encodeURIComponent(approved.email)}`;
welcome = await sendWelcomeEmail(approved, url);
}
return new Response(
JSON.stringify({ ok: true, id: user.id, status: user.status, welcome }),
{ status: 200, headers: JSON_HEADERS },
);
} catch {
return new Response(JSON.stringify({ error: "failed to approve user" }), {
status: 500,
+193
View File
@@ -0,0 +1,193 @@
import { NextRequest } from "next/server";
import { constants } from "node:fs";
import {
access,
mkdir,
mkdtemp,
readFile,
rm,
stat,
} from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { getStorageSettings } from "@/db/storage-settings";
import {
BACKUP_DATABASE_FILE,
BACKUP_MANIFEST_FILE,
assertRegularFile,
type BackupManifest,
backupManifestSchema,
backupTempRoot,
extractZip,
listZipEntries,
replaceDirectoryContents,
restoreDatabaseFromFile,
sha256File,
validateBackupEntries,
writeRequestBodyToFile,
} from "@/lib/backup";
import { errorResponse, jsonResponse } from "@/lib/http";
import { UPLOAD_DIR } from "@/lib/uploads";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* POST /api/dev/backup/restore
*
* Body: the backup ZIP bytes. Header: `x-restore-confirm: RESTORE`.
*
* The ZIP is validated before anything is changed. The database is loaded with
* `psql --single-transaction`, so a bad dump rolls back. Uploads and the archive
* are only replaced when the manifest says they were included. The signed-in
* admin should keep the same NEXTAUTH_SECRET if they need to retain encrypted
* settings such as the Gmail app password.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
if (req.headers.get("x-restore-confirm") !== "RESTORE") {
return errorResponse(
400,
'Type "RESTORE" in the confirmation field before restoring.',
);
}
if (!req.body) return errorResponse(400, "A backup ZIP is required.");
const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-restore-"));
const zipPath = path.join(temp, "backup.zip");
const extractDir = path.join(temp, "unpacked");
let databaseRestored = false;
try {
await writeRequestBodyToFile(req.body, zipPath);
const zipInfo = await stat(zipPath);
if (!zipInfo.isFile() || zipInfo.size === 0) {
return errorResponse(400, "The uploaded backup is empty.");
}
const entries = await listZipEntries(zipPath);
const entriesCheck = validateBackupEntries(entries);
if (!entriesCheck.ok) {
return errorResponse(400, entriesCheck.error);
}
await mkdir(extractDir, { recursive: true });
await extractZip(zipPath, extractDir);
const manifestPath = path.join(extractDir, BACKUP_MANIFEST_FILE);
const dumpPath = path.join(extractDir, BACKUP_DATABASE_FILE);
await assertRegularFile(manifestPath);
await assertRegularFile(dumpPath);
let manifest: BackupManifest;
try {
manifest = backupManifestSchema.parse(
JSON.parse(await readFile(manifestPath, "utf8")),
);
} catch (error) {
const detail =
error instanceof z.ZodError
? error.issues[0]?.message ?? "invalid manifest"
: error instanceof Error
? error.message
: "invalid manifest";
return errorResponse(400, `Invalid backup manifest: ${detail}`);
}
const dumpInfo = await stat(dumpPath);
if (dumpInfo.size !== manifest.database.bytes) {
return errorResponse(
400,
"The database dump size does not match the backup manifest.",
);
}
const checksum = await sha256File(dumpPath);
if (checksum !== manifest.database.sha256) {
return errorResponse(
400,
"The database dump checksum does not match the backup manifest.",
);
}
// Resolve the current archive destination before the database is replaced;
// the restored app_settings may point at a path that is not mounted here.
const storage = await getStorageSettings();
if (manifest.includes.archive) {
const archiveRoot = path.parse(storage.archivePath).root;
if (
!path.isAbsolute(storage.archivePath) ||
path.resolve(storage.archivePath) === archiveRoot
) {
return errorResponse(
400,
"This backup contains an archive, but the current archive path is not safe. Fix it in Settings first.",
);
}
await mkdir(storage.archivePath, { recursive: true });
await access(storage.archivePath, constants.W_OK);
}
if (manifest.includes.uploads) {
await mkdir(UPLOAD_DIR, { recursive: true });
await access(UPLOAD_DIR, constants.W_OK);
}
await restoreDatabaseFromFile(dumpPath);
databaseRestored = true;
if (manifest.includes.uploads) {
const source = path.join(extractDir, "uploads");
await mkdir(source, { recursive: true });
await replaceDirectoryContents(source, UPLOAD_DIR);
}
if (manifest.includes.archive) {
const source = path.join(extractDir, "archive");
await mkdir(source, { recursive: true });
await replaceDirectoryContents(source, storage.archivePath);
}
try {
await writeAudit(db, {
actorId: gate.id,
action: "backup.restored",
entityType: "backup",
after: {
manifestCreatedAt: manifest.createdAt,
appVersion: manifest.appVersion,
databaseBytes: manifest.database.bytes,
includes: manifest.includes,
},
});
} catch (error) {
// The restore already succeeded; do not turn an audit failure into one.
console.error("backup restore: could not write audit row", error);
}
return jsonResponse({
ok: true,
restored: {
createdAt: manifest.createdAt,
appVersion: manifest.appVersion,
databaseBytes: manifest.database.bytes,
uploads: manifest.includes.uploads,
archive: manifest.includes.archive,
},
});
} catch (error) {
console.error("backup restore failed", error);
const detail =
error instanceof Error ? error.message : "restore could not be completed";
return errorResponse(
500,
databaseRestored
? `The database was restored, but the files could not be replaced: ${detail}`
: detail,
);
} finally {
await rm(temp, { recursive: true, force: true }).catch(() => undefined);
}
};
+143
View File
@@ -0,0 +1,143 @@
import { ZipArchive } from "archiver";
import { mkdtemp, rm } from "node:fs/promises";
import { PassThrough, Readable } from "node:stream";
import path from "node:path";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { getStorageSettings } from "@/db/storage-settings";
import {
BACKUP_FORMAT,
BACKUP_FORMAT_VERSION,
BACKUP_DATABASE_FILE,
BACKUP_MANIFEST_FILE,
backupFilename,
backupManifestSchema,
backupTempRoot,
directoryExists,
dumpDatabaseToFile,
} from "@/lib/backup";
import { errorResponse } from "@/lib/http";
import { UPLOAD_DIR } from "@/lib/uploads";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
/**
* GET /api/dev/backup
*
* Streams one complete ZIP: manifest, full Postgres dump, uploads volume, and
* the mounted photo archive. Admin-only. The dump is written to a private temp
* folder first so the archive can include a checksum of the exact SQL bytes.
*/
export const GET = async () => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
const temp = await mkdtemp(path.join(backupTempRoot(), "glenloch-backup-"));
const dumpPath = path.join(temp, BACKUP_DATABASE_FILE);
let keepTemp = true;
try {
const dump = await dumpDatabaseToFile(dumpPath);
const storage = await getStorageSettings();
const uploadsIncluded = await directoryExists(UPLOAD_DIR);
const archivePath = storage.archivePath;
const archiveIncluded =
(await directoryExists(archivePath)) &&
path.resolve(archivePath) !== path.resolve(UPLOAD_DIR) &&
!isInside(path.resolve(UPLOAD_DIR), path.resolve(archivePath));
const manifest = backupManifestSchema.parse({
format: BACKUP_FORMAT,
formatVersion: BACKUP_FORMAT_VERSION,
createdAt: new Date().toISOString(),
appVersion: process.env.npm_package_version ?? "unknown",
database: {
file: BACKUP_DATABASE_FILE,
bytes: dump.bytes,
sha256: dump.sha256,
},
includes: {
uploads: uploadsIncluded,
archive: archiveIncluded,
},
});
try {
await writeAudit(db, {
actorId: gate.id,
action: "backup.created",
entityType: "backup",
after: {
databaseBytes: dump.bytes,
uploads: uploadsIncluded,
archive: archiveIncluded,
},
});
} catch (error) {
// A failed audit row must not stop an otherwise valid backup.
console.error("backup: could not write audit row", error);
}
const output = new PassThrough();
const archive = new ZipArchive({ zlib: { level: 6 } });
const cleanup = () => {
if (!keepTemp) return;
keepTemp = false;
void rm(temp, { recursive: true, force: true }).catch(() => undefined);
};
output.on("close", cleanup);
output.on("error", cleanup);
archive.on("warning", (error) => {
console.warn("backup: zip warning", error);
});
archive.on("error", (error) => {
console.error("backup: zip failed", error);
output.destroy(error);
});
archive.pipe(output);
archive.append(JSON.stringify(manifest, null, 2), {
name: BACKUP_MANIFEST_FILE,
});
archive.file(dumpPath, { name: BACKUP_DATABASE_FILE });
if (uploadsIncluded) archive.directory(UPLOAD_DIR, "uploads");
if (archiveIncluded) archive.directory(archivePath, "archive");
void archive.finalize().catch((error) => output.destroy(error));
const filename = backupFilename();
return new Response(
Readable.toWeb(output) as unknown as ReadableStream<Uint8Array>,
{
status: 200,
headers: {
"content-type": "application/zip",
"content-disposition": `attachment; filename="${filename}"`,
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
},
},
);
} catch (error) {
if (keepTemp) {
keepTemp = false;
await rm(temp, { recursive: true, force: true }).catch(() => undefined);
}
const detail =
error instanceof Error ? error.message : "backup could not be created";
console.error("backup: creation failed", error);
return errorResponse(500, detail);
}
};
function isInside(parent: string, candidate: string): boolean {
const relative = path.relative(parent, candidate);
return (
relative !== "" &&
!relative.startsWith("..") &&
!path.isAbsolute(relative)
);
}
+10
View File
@@ -1,5 +1,6 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import {
listCatalog,
deactivateCatalog,
@@ -158,6 +159,9 @@ const dbError = (err: unknown) => {
/** GET /api/dev/catalog?type=categories&active=true — list pickers rows. */
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const type = typeSchema.safeParse(req.nextUrl.searchParams.get("type"));
if (!type.success) {
return new Response(JSON.stringify({ error: "invalid type" }), {
@@ -175,6 +179,9 @@ export const GET = async (req: NextRequest) => {
/** POST /api/dev/catalog { type, ...createFields } — create (slug generated). */
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return new Response(JSON.stringify({ error: "invalid body" }), {
@@ -223,6 +230,9 @@ export const POST = async (req: NextRequest) => {
* `slug` is never accepted here: it freezes after creation.
*/
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return new Response(JSON.stringify({ error: "invalid body" }), {
+34 -22
View File
@@ -1,36 +1,48 @@
import { NextRequest } from "next/server";
import { NextRequest, NextResponse } from "next/server";
import { signIn } from "@/auth/config";
import { verifyMagicToken } from "@/auth/magic-link";
const JSON_HEADERS = { "content-type": "application/json" };
import {
consumeMagicToken,
getUser,
requestOrigin,
verifyMagicToken,
} from "@/auth/magic-link";
/**
* Completes a magic-link sign-in. GET /api/dev/complete?token=... verifies the
* one-time token and establishes the Auth.js session.
* one-time token, establishes the Auth.js session, and redirects into the app.
*
* This is a browser endpoint (the link in the dev console transport / invite
* email is clicked), so it must answer with a redirect rather than JSON: the
* session cookie is set on the redirect response and the follow-up request
* arrives signed in.
*/
export const GET = async (req: NextRequest) => {
const token = new URL(req.url, "http://localhost").searchParams.get(
"token",
) ?? undefined;
const origin = requestOrigin(req);
const token = new URL(req.url, origin).searchParams.get("token") ?? undefined;
const payload = await verifyMagicToken(token);
if (!payload) {
return new Response(
JSON.stringify({ error: "invalid or expired link" }),
{ status: 400, headers: JSON_HEADERS },
);
// Expired or tampered link: send the person back to sign-in rather than
// dumping an error object in the browser.
return NextResponse.redirect(new URL("/login?error=invalid_link", origin));
}
// Single use: the jti is consumed before a session is created, so a link
// forwarded or leaked after first use cannot sign anyone in again.
const consumed = await consumeMagicToken(payload);
if (!consumed) {
return NextResponse.redirect(new URL("/login?error=link_used", origin));
}
try {
const result = await signIn("magic-link", { token, redirect: false });
return new Response(JSON.stringify({ ok: true, url: result.url }), {
status: 200,
headers: JSON_HEADERS,
});
await signIn("magic-link", { token, redirect: false });
// The first successful link opens credential setup; returning users go
// straight into the app.
const user = await getUser(payload.email);
return NextResponse.redirect(
new URL(user?.passwordHash ? "/schedule" : "/welcome", origin),
);
} catch (err) {
console.error("[complete] signIn failed:", (err as Error).message, (err as Error).stack);
return new Response(JSON.stringify({ error: "failed to sign in" }), {
status: 500,
headers: JSON_HEADERS,
});
return NextResponse.redirect(new URL("/login", origin));
}
};
};
+34
View File
@@ -0,0 +1,34 @@
import type { NextRequest } from "next/server";
import { gateCron } from "@/auth/api";
import { completePastAssignments } from "@/db/complete";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* GET /api/dev/cron/complete — close assignments for services that have ended.
*
* Marks past published assignments `completed` and updates the volunteer's
* `last_served_on` / `last_served_at`, which drive staleness and fairness.
* Idempotent: a second run has nothing left to complete.
*
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
* scheduler, otherwise a session with `schedule.publish`.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateCron(req);
if (gate instanceof Response) return gate;
try {
const summary = await completePastAssignments();
return new Response(JSON.stringify(summary), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
const message = e instanceof Error ? e.message : "completion failed";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+31 -7
View File
@@ -1,15 +1,39 @@
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { generateInstances } from "@/db/instances";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* Daily instance generator (ARCHITECTURE §5.1). Cron `0 6 * * *` (church-local
* 06:00, expressed in UTC) calls this. Idempotent — a re-run creates 0 rows.
* Instance generator (ARCHITECTURE §5.1). Idempotent — a re-run creates 0 rows.
* Callable from the admin services panel; also safe for an external cron once
* it is given a service credential. Here it is guarded by `schedule.publish`.
*
* GET /api/dev/cron/instances
*/
export const GET = async () => {
const result = await generateInstances();
return new Response(JSON.stringify({ result }), {
status: 200,
headers: { "content-type": "application/json" },
});
try {
const session = await auth();
requirePermission(
(session?.user as { systemRole: SystemRole } | null | undefined),
"schedule.publish",
);
const result = await generateInstances();
return new Response(JSON.stringify({ result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ error: "failed to generate instances" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
@@ -0,0 +1,37 @@
import type { NextRequest } from "next/server";
import { gateCron } from "@/auth/api";
import { dispatchDue } from "@/db/dispatcher";
import { enqueueEventReminders } from "@/db/eventReminders";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* GET /api/dev/cron/notifications — the dispatcher tick (cron every 5 min).
*
* Queues any event reminders that are now inside their lead window, then drains
* due outbox rows through the guards (assignment active, volunteer active,
* channel consent, quiet hours) and the configured transport. Returns what
* happened; running it again with nothing due is a no-op.
*
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
* scheduler, otherwise a session with `schedule.publish`.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateCron(req);
if (gate instanceof Response) return gate;
try {
const eventRemindersQueued = await enqueueEventReminders();
const summary = await dispatchDue();
return new Response(JSON.stringify({ ...summary, eventRemindersQueued }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
const message = e instanceof Error ? e.message : "dispatch failed";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+23 -6
View File
@@ -1,15 +1,32 @@
import type { NextRequest } from "next/server";
import { gateCron } from "@/auth/api";
import { materializeSlots } from "@/db/slots";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* Slot materialization (ARCHITECTURE §5.2). Drives `materializeSlots()` —
* idempotent on (instance, role, seat). Re-runs create 0 rows.
*
* GET /api/dev/cron/slots
* Auth: `Authorization: Bearer $CRON_SECRET` (or `?secret=`) for an external
* scheduler, otherwise a session with `schedule.publish`.
*/
export const GET = async () => {
const result = await materializeSlots();
return new Response(JSON.stringify({ result }), {
status: 200,
headers: { "content-type": "application/json" },
});
export const GET = async (req: NextRequest) => {
const gate = await gateCron(req);
if (gate instanceof Response) return gate;
try {
const result = await materializeSlots();
return new Response(JSON.stringify({ result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
const message = e instanceof Error ? e.message : "slot materialization failed";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+5 -1
View File
@@ -1,5 +1,6 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { denyUser } from "@/auth/invites";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -12,6 +13,9 @@ const bodySchema = z.object({
* Deny a pending user -> denied (cannot sign in). POST { userId, deniedBy? }.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
let userId: string | undefined;
let deniedBy: string | undefined;
try {
@@ -33,7 +37,7 @@ export const POST = async (req: NextRequest) => {
try {
const user = await denyUser({
userId: parsed.data.userId,
deniedBy: parsed.data.deniedBy ?? "admin",
deniedBy: gate.id,
});
return new Response(JSON.stringify({ ok: true, id: user.id, status: user.status }), {
status: 200,
+8 -1
View File
@@ -1,6 +1,8 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { inviteUser } from "@/auth/invites";
import { requestOrigin } from "@/auth/magic-link";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({
@@ -14,6 +16,9 @@ const bodySchema = z.object({
* signs a magic-link token, and enqueues an invite to the console outbox.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
let email: string | undefined;
let invitedBy: string | undefined;
try {
@@ -35,7 +40,9 @@ export const POST = async (req: NextRequest) => {
try {
const result = await inviteUser({
email: parsed.data.email,
invitedBy: parsed.data.invitedBy ?? "admin",
// Server-owned: the signed-in admin is the inviter.
invitedBy: gate.id,
appOrigin: requestOrigin(req),
});
return new Response(JSON.stringify(result), {
status: 200,
+35 -2
View File
@@ -1,6 +1,12 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { requestMagicLink } from "@/auth/magic-link";
import { clientIp } from "@/auth/api";
import {
MAGIC_LINK_DEV_TRANSPORT,
requestMagicLink,
requestOrigin,
} from "@/auth/magic-link";
import { rateLimit } from "@/lib/rate-limit";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({ email: z.string().email() });
@@ -28,8 +34,35 @@ export const POST = async (req: NextRequest) => {
});
}
// Production: 5 requests per address and 20 per IP per 10 minutes blunts
// link spam and email enumeration. The console transport (local/dev/e2e) is
// deliberately not throttled, since the test harness signs in repeatedly.
const ip = clientIp(req);
const emailKey = parsed.data.email.trim().toLowerCase();
const byAddress = MAGIC_LINK_DEV_TRANSPORT
? { ok: true, retryAfterSeconds: 0 }
: rateLimit(`magic:${ip}:${emailKey}`, 5, 10 * 60_000);
const byIp = MAGIC_LINK_DEV_TRANSPORT
? { ok: true, retryAfterSeconds: 0 }
: rateLimit(`magic-ip:${ip}`, 20, 10 * 60_000);
if (!byAddress.ok || !byIp.ok) {
const retry = Math.max(byAddress.retryAfterSeconds, byIp.retryAfterSeconds);
return new Response(
JSON.stringify({
error: "too many sign-in requests; try again later",
code: "RATE_LIMITED",
}),
{
status: 429,
headers: { ...JSON_HEADERS, "retry-after": String(retry) },
},
);
}
try {
const result = await requestMagicLink(parsed.data.email);
const result = await requestMagicLink(parsed.data.email, {
origin: requestOrigin(req),
});
return new Response(JSON.stringify(result), {
status: 200,
headers: JSON_HEADERS,
+153
View File
@@ -0,0 +1,153 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { createRule, listRules, updateRule } from "@/db/reminders";
import { NOTIFICATION_RULE_EVENTS } from "@/db/schema";
const JSON_HEADERS = { "content-type": "application/json" };
const createSchema = z.object({
key: z.string().min(1),
event: z.enum(NOTIFICATION_RULE_EVENTS).optional(),
offsetDays: z.number().int().min(-30).max(30),
sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/),
channelSet: z.enum(["email", "sms", "email+sms"]),
appliesToServiceId: z.string().nullable().optional(),
active: z.boolean().optional(),
});
const patchSchema = z.object({
id: z.string().min(1),
offsetDays: z.number().int().min(-30).max(30).optional(),
sendAtLocalTime: z.string().regex(/^\d{2}:\d{2}$/).optional(),
channelSet: z.enum(["email", "sms", "email+sms"]).optional(),
appliesToServiceId: z.string().nullable().optional(),
active: z.boolean().optional(),
});
async function requireActor() {
const session = await auth();
const user = session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
if (!user) {
return new Response(
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
{ status: 401, headers: JSON_HEADERS },
);
}
requirePermission(user, "schedule.publish");
return user;
}
/**
* Reminder rules CRUD — unit E7 (ARCHITECTURE §6.2).
*
* GET -> all rules
* POST -> create a rule ({ key, offsetDays, sendAtLocalTime, channelSet })
* PATCH -> edit a rule (partial)
*
* Guarded by `schedule.publish`. Reminder sends are computed from these rows at
* publish time, so changing an offset changes `scheduled_for` with no deploy.
*/
export const GET = async () => {
try {
const actor = await requireActor();
if (actor instanceof Response) return actor;
return new Response(JSON.stringify({ rules: await listRules() }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ error: "failed to list rules" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const POST = async (req: NextRequest) => {
try {
const actor = await requireActor();
if (actor instanceof Response) return actor;
const body = await req.json().catch(() => null);
const parsed = createSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
const rule = await createRule({
key: parsed.data.key,
event: parsed.data.event ?? "assignment.created",
offsetDays: parsed.data.offsetDays,
sendAtLocalTime: parsed.data.sendAtLocalTime,
channelSet: parsed.data.channelSet,
appliesToServiceId: parsed.data.appliesToServiceId ?? null,
active: parsed.data.active ?? true,
});
return new Response(JSON.stringify({ rule }), {
status: 201,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ error: "failed to create rule" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const PATCH = async (req: NextRequest) => {
try {
const actor = await requireActor();
if (actor instanceof Response) return actor;
const body = await req.json().catch(() => null);
const parsed = patchSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
const { id, ...patch } = parsed.data;
const rule = await updateRule(id, patch);
if (!rule) {
return new Response(JSON.stringify({ error: "unknown rule" }), {
status: 404,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ rule }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ error: "failed to update rule" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+170
View File
@@ -0,0 +1,170 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listNotifications, retryNotification } from "@/db/outbox";
import { db } from "@/db";
import { users } from "@/db/schema";
import { resolveEmailTransport } from "@/lib/email";
import { getEmailTransportSettings } from "@/db/settings";
import { eq } from "drizzle-orm";
import { NOTIFICATION_STATUSES, type NotificationStatus } from "@/db/schema";
const JSON_HEADERS = { "content-type": "application/json" };
function isStatus(value: string | null): value is NotificationStatus {
return (
value !== null &&
(NOTIFICATION_STATUSES as readonly string[]).includes(value)
);
}
/**
* GET /api/dev/notifications?status=&limit= — the admin notification log
* (newest first), read straight from the outbox table (ARCHITECTURE §4/§6.1).
* Guarded by `schedule.publish`.
*/
export const GET = async (req: NextRequest) => {
try {
const session = await auth();
const user = session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
if (!user) {
return new Response(
JSON.stringify({
error: "Authentication required",
code: "UNAUTHORIZED",
}),
{ status: 401, headers: JSON_HEADERS },
);
}
requirePermission(user, "schedule.publish");
const statusParam = req.nextUrl.searchParams.get("status");
if (statusParam !== null && !isStatus(statusParam)) {
return new Response(
JSON.stringify({ error: `unknown status: ${statusParam}` }),
{ status: 400, headers: JSON_HEADERS },
);
}
const limitParam = Number(req.nextUrl.searchParams.get("limit") ?? "50");
const notifications = await listNotifications({
status: isStatus(statusParam) ? statusParam : undefined,
limit: Number.isFinite(limitParam) ? limitParam : 50,
});
return new Response(JSON.stringify({ notifications }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
const actionSchema = z.object({
action: z.enum(["retry", "send_test"]),
id: z.string().min(1).optional(),
});
/**
* POST /api/dev/notifications — the admin log's actions (E6).
* { action: "retry", id } -> requeue a failed/suppressed row for the next tick
* { action: "send_test" } -> send a test email to the signed-in admin
*/
export const POST = async (req: NextRequest) => {
try {
const session = await auth();
const user = session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
if (!user) {
return new Response(
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
{ status: 401, headers: JSON_HEADERS },
);
}
requirePermission(user, "schedule.publish");
const body = await req.json().catch(() => null);
const parsed = actionSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
if (parsed.data.action === "retry") {
if (!parsed.data.id) {
return new Response(JSON.stringify({ error: "an id is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const row = await retryNotification(parsed.data.id);
if (!row) {
return new Response(JSON.stringify({ error: "unknown notification" }), {
status: 404,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ ok: true, notification: row }), {
status: 200,
headers: JSON_HEADERS,
});
}
const [actor] = await db
.select({ email: users.email, firstName: users.firstName })
.from(users)
.where(eq(users.id, user.id))
.limit(1);
if (!actor) {
return new Response(JSON.stringify({ error: "unknown user" }), {
status: 404,
headers: JSON_HEADERS,
});
}
const settings = await getEmailTransportSettings();
const transport = resolveEmailTransport(settings);
const result = await transport.send({
to: settings.notificationEmail || actor.email,
subject: "Media Team Hub — test message",
html: `<p>${actor.firstName}, this is a test from Media Team Hub.</p><p>If you can read this, ${transport.name} delivery works.</p>`,
text: `${actor.firstName}, this is a test from Media Team Hub. If you can read this, ${transport.name} delivery works.`,
templateKey: "admin.send_test",
dedupeKey: `admin.send_test:${user.id}:${Date.now()}`,
});
return new Response(JSON.stringify({ ok: true, transport: transport.name, ...result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { z } from "zod";
import { getPositionSkills, setPositionSkills } from "@/db/positions";
import { validateRequirements } from "@/domain/positions";
import { gateOrUser } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -44,6 +45,9 @@ const ok = (row: unknown) =>
* core flag).
*/
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const positionId = req.nextUrl.searchParams.get("positionId");
if (!positionId) return bad("missing positionId");
const row = await getPositionSkills(positionId);
@@ -61,6 +65,9 @@ export const GET = async (req: NextRequest) => {
* "weight": 3, "requiredLevel": "qualified" } ], "published": true }
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
+10
View File
@@ -6,6 +6,7 @@ import {
updatePosition,
deactivatePosition,
} from "@/db/positions";
import { gateOrUser } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -85,6 +86,9 @@ const dbError = (err: unknown) => {
/** GET /api/dev/positions?active=true — list picker rows. */
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const active = req.nextUrl.searchParams.get("active") !== "false";
const rows = await listPositions({ active });
return new Response(JSON.stringify({ rows }), {
@@ -95,6 +99,9 @@ export const GET = async (req: NextRequest) => {
/** POST /api/dev/positions { ...createFields } — create (slug generated). */
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return bad("invalid body");
@@ -114,6 +121,9 @@ export const POST = async (req: NextRequest) => {
* `slug` is never accepted here: it freezes after creation.
*/
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return bad("invalid body");
+38 -3
View File
@@ -1,7 +1,12 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { updateProfile, setSmsConsent } from "@/db/profile";
import type { ProfilePatch } from "@/db/profile";
import { clientIp, gateSelfOr } from "@/auth/api";
import {
updateProfile,
setSmsConsent,
updateNotificationPreferences,
} from "@/db/profile";
import type { ProfilePatch, NotificationPreferencePatch } from "@/db/profile";
import type { SmsConsentSource } from "@/db/schema";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -14,6 +19,11 @@ const profileSchema = z.object({
phoneE164: z.string().nullable().optional(),
emergencyContact: z.string().nullable().optional(),
timezone: z.string().optional(),
emailEnabled: z.boolean().optional(),
reminderLeadDays: z.number().int().min(1).max(14).optional(),
digestOnly: z.boolean().optional(),
quietHoursStart: z.string().regex(/^\d{2}:\d{2}$/).optional(),
quietHoursEnd: z.string().regex(/^\d{2}:\d{2}$/).optional(),
});
const consentSchema = z.object({
@@ -45,6 +55,9 @@ export const PATCH = async (req: NextRequest) => {
});
}
const gate = await gateSelfOr("users.manage", parsed.data.userId);
if (gate instanceof Response) return gate;
try {
// Only update fields actually present in the body — a PATCH must not null
// out unspecified fields (e.g. omitting phoneE164 must not wipe the phone).
@@ -56,7 +69,25 @@ export const PATCH = async (req: NextRequest) => {
if (parsed.data.emergencyContact !== undefined) patch.emergencyContact = parsed.data.emergencyContact;
if (parsed.data.timezone !== undefined) patch.timezone = parsed.data.timezone;
const prefPatch: NotificationPreferencePatch = {};
if (parsed.data.emailEnabled !== undefined)
prefPatch.emailEnabled = parsed.data.emailEnabled;
if (parsed.data.reminderLeadDays !== undefined)
prefPatch.reminderLeadDays = parsed.data.reminderLeadDays;
if (parsed.data.digestOnly !== undefined)
prefPatch.digestOnly = parsed.data.digestOnly;
if (parsed.data.quietHoursStart !== undefined)
prefPatch.quietHoursStart = parsed.data.quietHoursStart;
if (parsed.data.quietHoursEnd !== undefined)
prefPatch.quietHoursEnd = parsed.data.quietHoursEnd;
const result = await updateProfile(parsed.data.userId, patch);
if (Object.keys(prefPatch).length > 0) {
result.preferences = await updateNotificationPreferences(
parsed.data.userId,
prefPatch,
);
}
return new Response(JSON.stringify(result), {
status: 200,
headers: JSON_HEADERS,
@@ -91,12 +122,16 @@ export const POST = async (req: NextRequest) => {
});
}
const gate = await gateSelfOr("users.manage", parsed.data.userId);
if (gate instanceof Response) return gate;
try {
const preferences = await setSmsConsent(
parsed.data.userId,
{
source: parsed.data.source as SmsConsentSource,
ip: parsed.data.ip ?? null,
// TCPA evidence is recorded from the request, never from the client body.
ip: clientIp(req),
},
);
return new Response(JSON.stringify({ ok: true, preferences }), {
+28 -19
View File
@@ -1,35 +1,44 @@
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { gateOrUser } from "@/auth/api";
import { resetAndSeed } from "@/db/seed";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* Dev console reset. Admin-only (admin.settings): truncates the seed-owned
* tables and repopulates them, so E2E tests start from a known-clean state on
* every run instead of accumulating the mutations of prior runs. Not wired into
* any UI — it exists only for test harnesses.
* Test-only database reset.
*
* Two gates, both required:
* 1. `ALLOW_DEV_RESET=true` must be set explicitly. This keeps a destructive
* truncate + reseed out of any deployment that did not ask for it.
* 2. The caller must be a signed-in admin (`admin.settings`).
*
* E2E sets `ALLOW_DEV_RESET=true` in `playwright.config.ts`; production
* compose does not.
*/
export const POST = async () => {
try {
const session = await auth();
requirePermission(
(session?.user as { systemRole: SystemRole } | null | undefined),
"admin.settings",
if (process.env.ALLOW_DEV_RESET !== "true") {
return new Response(
JSON.stringify({
error: "database reset is disabled in this environment",
code: "RESET_DISABLED",
}),
{ status: 403, headers: JSON_HEADERS },
);
}
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
try {
await resetAndSeed();
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
throw e;
const message = e instanceof Error ? e.message : "reset failed";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
@@ -0,0 +1,138 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { writeAudit } from "@/db/audit";
import { db } from "@/db";
import { applyAutoFill, computeAutoFill } from "@/db/autoFill";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z
.object({
maxServicesPerMonth: z.number().int().positive().optional(),
})
.optional();
/**
* Auto-fill proposals for one service instance (unit D9).
*
* GET /api/dev/schedule/:instanceId/auto-fill
* -> { proposals, unfilled } computed from the instance's open seats and
* the active volunteer pool. Nothing is written.
*
* POST /api/dev/schedule/:instanceId/auto-fill
* { maxServicesPerMonth? }
* -> writes one `proposed`/`auto` assignment per still-free proposal and
* an audit row. Idempotent: a re-run finds every seat already filled
* and writes 0 rows.
*
* Guarded by `schedule.publish` (coordinator + admin).
*/
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ instanceId: string }> },
) => {
try {
const session = await auth();
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
if (!user) {
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
status: 401,
headers: JSON_HEADERS,
});
}
requirePermission(user, "schedule.publish");
const { instanceId } = await params;
const result = await computeAutoFill(instanceId);
return new Response(JSON.stringify(result), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 404,
headers: JSON_HEADERS,
});
}
};
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ instanceId: string }> },
) => {
let maxServicesPerMonth: number | undefined;
try {
const body = await req.json().catch(() => null);
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
maxServicesPerMonth = parsed.data?.maxServicesPerMonth;
} catch {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
try {
const session = await auth();
const user = (session?.user as { id: string; systemRole: SystemRole } | null | undefined);
if (!user) {
return new Response(JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }), {
status: 401,
headers: JSON_HEADERS,
});
}
requirePermission(user, "schedule.publish");
const actorId = user.id;
const { instanceId } = await params;
const result = await applyAutoFill(instanceId, {
actorId,
maxServicesPerMonth,
});
await writeAudit(db, {
actorId,
action: "schedule.autofill",
entityType: "service_instance",
entityId: instanceId,
after: {
proposals: result.proposals.length,
written: result.written,
unfilled: result.unfilled.length,
},
});
return new Response(JSON.stringify(result), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
@@ -0,0 +1,147 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { auth } from "@/auth/config";
import { requestOrigin } from "@/auth/magic-link";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { PublishError, publishInstance, unpublishInstance } from "@/db/publish";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({
allowGaps: z.boolean().optional(),
});
/** Map a refused publish/unpublish to its HTTP status. */
function errorStatus(code: PublishError["code"]): number {
switch (code) {
case "unknown_instance":
return 404;
case "instance_cancelled":
case "open_slots":
case "unpublish_blocked":
return 409;
}
}
function jsonError(e: PublishError): Response {
return new Response(
JSON.stringify({ error: e.message, code: e.code, gaps: e.gaps }),
{ status: errorStatus(e.code), headers: JSON_HEADERS },
);
}
function authFailure(e: AuthError): Response {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
/** Resolve the session user or return the 401 response. */
async function requireActor(): Promise<
{ id: string; systemRole: SystemRole } | Response
> {
const session = await auth();
const user = session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
if (!user) {
return new Response(
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
{ status: 401, headers: JSON_HEADERS },
);
}
requirePermission(user, "schedule.publish");
return user;
}
/**
* Publish / unpublish one service instance (unit D10, ARCHITECTURE §5.5).
*
* POST /api/dev/schedule/:instanceId/publish { allowGaps? }
* -> one transaction: validate coverage, set `status='published'` +
* `published_at`/`published_by`, write the `week.published` audit
* row. Blocked 409 with `gaps` when a covering seat is empty and
* `allowGaps` is false. Re-publishing is an idempotent no-op.
*
* DELETE /api/dev/schedule/:instanceId/publish
* -> back to draft, `week.unpublished` audit row. Refused 409 while a
* volunteer has confirmed.
*
* D10 sends nothing — notification wiring is E1.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ instanceId: string }> },
) => {
let allowGaps: boolean | undefined;
try {
const body = await req.json().catch(() => null);
const parsed = bodySchema.safeParse(body ?? {});
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
allowGaps = parsed.data.allowGaps;
} catch {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
try {
const actor = await requireActor();
if (actor instanceof Response) return actor;
const { instanceId } = await params;
const result = await publishInstance(instanceId, {
actorId: actor.id,
allowGaps,
// Confirmation links in the publish/reminder emails must point at the
// origin the schedule is being managed from (LAN IP or public domain).
appOrigin: requestOrigin(req),
});
return new Response(JSON.stringify({ ok: true, ...result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
if (e instanceof PublishError) return jsonError(e);
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const DELETE = async (
_req: NextRequest,
{ params }: { params: Promise<{ instanceId: string }> },
) => {
try {
const actor = await requireActor();
if (actor instanceof Response) return actor;
const { instanceId } = await params;
const result = await unpublishInstance(instanceId, { actorId: actor.id });
return new Response(JSON.stringify({ ok: true, ...result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
if (e instanceof PublishError) return jsonError(e);
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
@@ -0,0 +1,51 @@
import type { NextRequest } from "next/server";
import { eq } from "drizzle-orm";
import { db } from "@/db";
import { serviceInstances, services } from "@/db/schema";
import { gateCron } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
/**
* GET /api/dev/schedule/instances — the list of service instances (id,
* occursOn, serviceName) for the admin helper routes. Guarded by
* `schedule.publish` (coordinator + admin).
*/
export const GET = async (req: NextRequest) => {
const gate = await gateCron(req);
if (gate instanceof Response) return gate;
try {
// `serviceName` is the instance's title override when set, else the service
// template's name. Ordering includes `startsAt` so two instances on the same
// date (both Sunday services) always come back in the same order.
const rows = await db
.select({
id: serviceInstances.id,
occursOn: serviceInstances.occursOn,
titleOverride: serviceInstances.titleOverride,
name: services.name,
status: serviceInstances.status,
})
.from(serviceInstances)
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
.orderBy(serviceInstances.occursOn, serviceInstances.startsAt);
const instances = rows.map((r) => ({
id: r.id,
occursOn: r.occursOn,
serviceName: r.titleOverride ?? r.name,
status: r.status,
}));
return new Response(JSON.stringify({ instances }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+68
View File
@@ -1,14 +1,38 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import {
listServices,
createService,
updateService,
deactivateService,
deleteService,
} from "@/db/services";
const JSON_HEADERS = { "content-type": "application/json" };
/** Services are schedule data: only `schedule.publish` roles may change them. */
async function requireEditor(): Promise<Response | null> {
const session = await auth();
try {
requirePermission(
(session?.user as { systemRole: SystemRole } | null | undefined),
"schedule.publish",
);
return null;
} catch (e) {
if (e instanceof AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
throw e;
}
}
const idSchema = z.string().min(1);
const serviceCreateSchema = z.object({
@@ -85,6 +109,8 @@ const constraintError = (err: unknown): Response | null => {
/** GET /api/dev/services?active=true — list service templates. */
export const GET = async (req: NextRequest) => {
const failure = await requireEditor();
if (failure) return failure;
const active = req.nextUrl.searchParams.get("active") !== "false";
const rows = await listServices({ active });
return new Response(JSON.stringify({ rows }), {
@@ -95,6 +121,8 @@ export const GET = async (req: NextRequest) => {
/** POST /api/dev/services { ...fields } — create a service template. */
export const POST = async (req: NextRequest) => {
const failure = await requireEditor();
if (failure) return failure;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return bad("invalid body");
@@ -110,12 +138,52 @@ export const POST = async (req: NextRequest) => {
}
};
/**
* DELETE /api/dev/services?id=… — permanently remove a template that never ran.
* Refused (409) once an instance has started, been published, or carries an
* assignment; those must be deactivated so schedule history survives.
*/
export const DELETE = async (req: NextRequest) => {
const failure = await requireEditor();
if (failure) return failure;
const id = idSchema.safeParse(req.nextUrl.searchParams.get("id"));
if (!id.success) return bad("a valid id is required");
const result = await deleteService(id.data);
if (result.ok) {
return new Response(
JSON.stringify({ ok: true, removedInstances: result.removedInstances }),
{ status: 200, headers: JSON_HEADERS },
);
}
if (result.reason === "not_found") {
return new Response(JSON.stringify({ error: "unknown service" }), {
status: 404,
headers: JSON_HEADERS,
});
}
const history =
result.assignments > 0
? `${result.instances} instance(s) and ${result.assignments} assignment(s)`
: `${result.instances} published or past instance(s)`;
return new Response(
JSON.stringify({
error: `This service has ${history}. Deactivate it instead so the schedule history is preserved.`,
code: "HAS_HISTORY",
}),
{ status: 409, headers: JSON_HEADERS },
);
};
/**
* PATCH /api/dev/services { id, ...fields } — edit.
* PATCH { id, active: false } — deactivate (soft delete).
* `name` is never accepted here: it freezes after creation.
*/
export const PATCH = async (req: NextRequest) => {
const failure = await requireEditor();
if (failure) return failure;
const body = await readBody(req);
if (!body || typeof body !== "object") {
return bad("invalid body");
+109
View File
@@ -0,0 +1,109 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import {
getEmailSettings,
saveEmailSettings,
type EmailSettings,
} from "@/db/settings";
import { normalizeAppPassword } from "@/lib/secret";
const JSON_HEADERS = { "content-type": "application/json" };
const settingsSchema = z.object({
emailFrom: z.string().email(),
notificationEmail: z.string().email().or(z.literal("")),
/** Empty string disconnects Gmail; omitted leaves the stored credentials. */
smtpUser: z.union([z.literal(""), z.string().email()]).optional(),
/** Omitted/blank keeps the stored app password. */
smtpAppPassword: z.string().max(200).optional(),
});
/** What goes in the audit trail — never the password. */
function summary(settings: EmailSettings) {
return {
emailFrom: settings.emailFrom,
notificationEmail: settings.notificationEmail,
smtpUser: settings.smtpUser,
smtpConfigured: settings.smtpConfigured,
};
}
const bad = (message: string, status = 400) =>
new Response(JSON.stringify({ error: message }), {
status,
headers: JSON_HEADERS,
});
/**
* GET /api/dev/settings — email identity, and whether a Gmail account is
* connected (the app password itself is never returned).
*/
export const GET = async () => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
return new Response(JSON.stringify({ settings: await getEmailSettings() }), {
status: 200,
headers: JSON_HEADERS,
});
};
/**
* PUT /api/dev/settings
* { emailFrom, notificationEmail, smtpUser?, smtpAppPassword? }
*
* Saves the sender identity and, when given, the Gmail credentials. A blank
* app password keeps the stored one; `smtpUser: ""` disconnects Gmail and
* deletes both credential rows. Every save writes an audit row with the
* address but never the secret.
*/
export const PUT = async (req: NextRequest) => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
const body = await req.json().catch(() => null);
const parsed = settingsSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
const before = await getEmailSettings();
const smtpUser = parsed.data.smtpUser;
const password = normalizeAppPassword(parsed.data.smtpAppPassword ?? "");
if (smtpUser !== undefined && smtpUser !== "") {
if (password !== "" && password.length < 8) {
return bad(
"That does not look like a Google app password — it should be 16 characters.",
);
}
if (password === "" && !before.smtpConfigured) {
return bad("Enter the 16-character app password for this Gmail account.");
}
if (password === "" && smtpUser !== before.smtpUser) {
return bad("Enter the app password for the new Gmail account.");
}
}
const settings = await saveEmailSettings({
emailFrom: parsed.data.emailFrom,
notificationEmail: parsed.data.notificationEmail,
smtpUser,
smtpAppPassword: password,
});
await writeAudit(db, {
actorId: gate.id,
action: "settings.email.updated",
entityType: "app_settings",
entityId: "email",
before: summary(before),
after: summary(settings),
});
return new Response(JSON.stringify({ ok: true, settings }), {
status: 200,
headers: JSON_HEADERS,
});
};
@@ -1,4 +1,5 @@
import { NextRequest } from "next/server";
import { gateOrUser } from "@/auth/api";
import { listAssessments } from "@/db/assessments";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -16,6 +17,9 @@ const bad = (message: string) =>
* the verify modal. There is intentionally no update or delete endpoint.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const params = req.nextUrl.searchParams;
const rawLimit = params.get("limit");
let limit: number | undefined;
+4
View File
@@ -1,5 +1,6 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { composeSkillName } from "@/domain/skills";
import { dedupeKey } from "@/db/positions";
@@ -39,6 +40,9 @@ const bad = (message: string) =>
* technologyName?, functionId?, functionName? } -> { name, dedupeKey }.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
const parsed = composeSchema.safeParse(body);
+4
View File
@@ -1,6 +1,7 @@
import { NextRequest } from "next/server";
import { listSkillsMatrix } from "@/db/assessments";
import { isSkillLevel, SKILL_LEVELS, type SkillLevel } from "@/domain/assessments";
import { gateOrUser } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -19,6 +20,9 @@ const bad = (message: string) =>
* compose, so `?level=qualified` answers "who is currently signed off?".
*/
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const params = req.nextUrl.searchParams;
const level = params.get("level");
if (level !== null && !isSkillLevel(level)) {
+10
View File
@@ -6,6 +6,7 @@ import {
updateSkill,
deactivateSkill,
} from "@/db/positions";
import { gateOrUser } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -95,6 +96,9 @@ const dbError = (err: unknown) => {
/** GET /api/dev/skills?active=true — list picker rows. */
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const active = req.nextUrl.searchParams.get("active") !== "false";
const rows = await listSkills({ active });
return new Response(JSON.stringify({ rows }), {
@@ -105,6 +109,9 @@ export const GET = async (req: NextRequest) => {
/** POST /api/dev/skills { ...createFields } — create (slug + dedupe_key generated). */
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
const parsed = skillCreateSchema.safeParse(body);
@@ -122,6 +129,9 @@ export const POST = async (req: NextRequest) => {
* `slug` and the composing FKs are never accepted here: they freeze after creation.
*/
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
const id = idSchema.safeParse((body as { id?: unknown }).id);
+8 -4
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { AssessmentError, verifySkillLevel } from "@/db/assessments";
import { ASSESSMENT_KINDS } from "@/db/schema";
import { SKILL_LEVELS } from "@/domain/assessments";
import { gateOrUser } from "@/auth/api";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -11,7 +12,6 @@ const verifySchema = z.object({
skillId: z.string().min(1),
/** The level being signed off — validated again by the domain rule. */
level: z.enum(SKILL_LEVELS),
assessorId: z.string().min(1).nullable().optional(),
kind: z.enum(ASSESSMENT_KINDS).optional(),
notes: z.string().nullable().optional(),
});
@@ -66,20 +66,24 @@ const dbError = (err: unknown) => {
};
/**
* POST /api/dev/skills/verify { userId, skillId, level, assessorId?, kind?, notes? }
* POST /api/dev/skills/verify { userId, skillId, level, kind?, notes? }
*
* The verify-level modal's save: appends a `skill_assessments` row and moves
* `user_skills.verified_level` in one transaction. The volunteer's
* `self_comfort` is untouched (C2's signal is not the gate).
* `self_comfort` is untouched (C2's signal is not the gate). The assessor is
* the signed-in admin — the client cannot name someone else as the sign-off.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("training.author");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
const parsed = verifySchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
try {
const result = await verifySkillLevel(parsed.data);
const result = await verifySkillLevel({ ...parsed.data, assessorId: gate.id });
return ok(result);
} catch (err) {
if (err instanceof AssessmentError) return bad(err.problems.join("; "));
+95
View File
@@ -0,0 +1,95 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import {
checkArchiveDestination,
getStorageSettings,
saveStorageSettings,
type StorageSettings,
} from "@/db/storage-settings";
import { errorResponse, jsonResponse } from "@/lib/http";
const storageSchema = z.object({
nfsShare: z
.string()
.trim()
.max(255)
.refine((value) => !/[\r\n]/.test(value), "Invalid NFS share"),
archivePath: z
.string()
.trim()
.min(1)
.max(500)
.refine((value) => value.startsWith("/"), "Archive path must be absolute"),
archiveFolder: z
.string()
.trim()
.min(1)
.max(120)
.refine(
(value) => !value.includes("/") && !value.includes("\\") && value !== "..",
"Archive folder must be one safe folder name",
),
});
function publicSettings(settings: StorageSettings) {
return {
nfsShare: settings.nfsShare,
archivePath: settings.archivePath,
archiveFolder: settings.archiveFolder,
};
}
/** GET /api/dev/storage — NFS/archive destination and mount readiness. */
export const GET = async () => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
const settings = await getStorageSettings();
return jsonResponse({
settings: publicSettings(settings),
status: await checkArchiveDestination(settings),
});
};
/**
* PUT /api/dev/storage
* { nfsShare, archivePath, archiveFolder }
*
* The path must already be mounted into the container. Saving does not mount
* NFS; it records the operator's chosen export and the visible mount path, then
* verifies the path is a writable directory.
*/
export const PUT = async (req: NextRequest) => {
const gate = await gateOrUser("admin.settings");
if (gate instanceof Response) return gate;
const parsed = storageSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(
400,
parsed.error.issues[0]?.message ?? "Invalid storage settings",
);
}
const before = await getStorageSettings();
const settings = await saveStorageSettings(parsed.data);
const status = await checkArchiveDestination(settings);
await writeAudit(db, {
actorId: gate.id,
action: "settings.storage.updated",
entityType: "app_settings",
entityId: "storage",
before: publicSettings(before),
after: { ...publicSettings(settings), ready: status.ready },
});
return jsonResponse({
ok: true,
settings: publicSettings(settings),
status,
});
};
+160
View File
@@ -0,0 +1,160 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { unlink } from "node:fs/promises";
import { auth } from "@/auth/config";
import { AuthError, hasPermission, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import {
createLesson,
deleteLesson,
listLessons,
listResourceStoredNames,
updateLesson,
} from "@/db/training";
import { uploadPath } from "@/lib/uploads";
const JSON_HEADERS = { "content-type": "application/json" };
const lessonCreateSchema = z.object({
title: z.string().min(1).max(200),
summary: z.string().max(1000).nullable().optional(),
body: z.string().max(100_000).optional(),
published: z.boolean().optional(),
sortOrder: z.number().int().min(0).max(999).optional(),
});
const lessonPatchSchema = lessonCreateSchema.partial().extend({
id: z.string().min(1),
});
function authFailure(e: AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
async function sessionUser() {
const session = await auth();
return session?.user as
| { id: string; systemRole: SystemRole }
| null
| undefined;
}
/**
* Training lessons (F2 authoring). Reads are for any signed-in volunteer and
* hide unpublished drafts unless the caller can author. Writes require
* `training.author` (admin).
*
* GET -> { lessons }
* POST -> { lesson } create
* PATCH -> { lesson } edit / publish toggle
* DELETE ?id= -> { ok } removes the lesson, its rows, and its files
*/
export const GET = async () => {
const user = await sessionUser();
if (!user) {
return new Response(
JSON.stringify({ error: "Authentication required", code: "UNAUTHORIZED" }),
{ status: 401, headers: JSON_HEADERS },
);
}
const canAuthor = hasPermission(user.systemRole, "training.author");
return new Response(
JSON.stringify({ lessons: await listLessons({ includeUnpublished: canAuthor }) }),
{ status: 200, headers: JSON_HEADERS },
);
};
export const POST = async (req: NextRequest) => {
try {
await requirePermission(await sessionUser(), "training.author");
const body = await req.json().catch(() => null);
const parsed = lessonCreateSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
const lesson = await createLesson(parsed.data);
return new Response(JSON.stringify({ lesson }), {
status: 201,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
return new Response(JSON.stringify({ error: "failed to create lesson" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const PATCH = async (req: NextRequest) => {
try {
await requirePermission(await sessionUser(), "training.author");
const body = await req.json().catch(() => null);
const parsed = lessonPatchSchema.safeParse(body);
if (!parsed.success) {
return new Response(JSON.stringify({ error: parsed.error.message }), {
status: 400,
headers: JSON_HEADERS,
});
}
const { id, ...patch } = parsed.data;
const lesson = await updateLesson(id, patch);
if (!lesson) {
return new Response(JSON.stringify({ error: "unknown lesson" }), {
status: 404,
headers: JSON_HEADERS,
});
}
return new Response(JSON.stringify({ lesson }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
return new Response(JSON.stringify({ error: "failed to update lesson" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const DELETE = async (req: NextRequest) => {
try {
await requirePermission(await sessionUser(), "training.author");
const id = req.nextUrl.searchParams.get("id");
if (!id) {
return new Response(JSON.stringify({ error: "an id is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const files = await listResourceStoredNames(id);
const deleted = await deleteLesson(id);
if (!deleted) {
return new Response(JSON.stringify({ error: "unknown lesson" }), {
status: 404,
headers: JSON_HEADERS,
});
}
// Metadata cascades; remove the bytes best-effort.
for (const storedName of files) {
await unlink(uploadPath(storedName)).catch(() => undefined);
}
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
return new Response(JSON.stringify({ error: "failed to delete lesson" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+146
View File
@@ -0,0 +1,146 @@
import { NextRequest } from "next/server";
import { unlink, writeFile } from "node:fs/promises";
import { auth } from "@/auth/config";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { addResource, deleteResource, getLesson, getResource } from "@/db/training";
import {
MAX_UPLOAD_BYTES,
ensureUploadDir,
isAllowedUpload,
storedNameFor,
uploadPath,
uploadSignatureMatches,
} from "@/lib/uploads";
import { uuidv7 } from "@/lib/uuid";
const JSON_HEADERS = { "content-type": "application/json" };
function authFailure(e: AuthError) {
return new Response(JSON.stringify({ error: e.message, code: e.code }), {
status: e.status,
headers: JSON_HEADERS,
});
}
async function requireAuthor() {
const session = await auth();
return requirePermission(
(session?.user as { id: string; systemRole: SystemRole } | null | undefined),
"training.author",
);
}
/**
* Training attachments. Bytes go to `UPLOAD_DIR` (a named volume in the
* deployment) and only metadata is stored in Postgres, so the database never
* carries binaries.
*
* POST multipart { lessonId, file } -> { resource }
* DELETE ?id= -> { ok }
*/
export const POST = async (req: NextRequest) => {
try {
const user = await requireAuthor();
const form = await req.formData();
const lessonId = form.get("lessonId");
const file = form.get("file");
if (typeof lessonId !== "string" || !lessonId) {
return new Response(JSON.stringify({ error: "a lessonId is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
if (!file || typeof file === "string") {
return new Response(JSON.stringify({ error: "a file is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
if (!(await getLesson(lessonId))) {
return new Response(JSON.stringify({ error: "unknown lesson" }), {
status: 404,
headers: JSON_HEADERS,
});
}
if (file.size > MAX_UPLOAD_BYTES) {
return new Response(JSON.stringify({ error: "file is larger than 5 MB" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const mimeType = file.type || "application/octet-stream";
if (!isAllowedUpload(mimeType)) {
return new Response(
JSON.stringify({ error: `file type not allowed: ${mimeType}` }),
{ status: 400, headers: JSON_HEADERS },
);
}
const bytes = new Uint8Array(await file.arrayBuffer());
if (!uploadSignatureMatches(mimeType, bytes)) {
return new Response(
JSON.stringify({
error: `file contents do not match the declared type: ${mimeType}`,
}),
{ status: 400, headers: JSON_HEADERS },
);
}
await ensureUploadDir();
const storedName = storedNameFor(file.name, uuidv7());
await writeFile(uploadPath(storedName), bytes);
const resource = await addResource({
lessonId,
filename: file.name || storedName,
mimeType,
sizeBytes: file.size,
storedName,
});
void user;
return new Response(JSON.stringify({ resource }), {
status: 201,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
return new Response(JSON.stringify({ error: "failed to upload file" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
export const DELETE = async (req: NextRequest) => {
try {
await requireAuthor();
const id = req.nextUrl.searchParams.get("id");
if (!id) {
return new Response(JSON.stringify({ error: "an id is required" }), {
status: 400,
headers: JSON_HEADERS,
});
}
const resource = await getResource(id);
if (!resource) {
return new Response(JSON.stringify({ error: "unknown resource" }), {
status: 404,
headers: JSON_HEADERS,
});
}
await deleteResource(id);
await unlink(uploadPath(resource.storedName)).catch(() => undefined);
return new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof AuthError) return authFailure(e);
return new Response(JSON.stringify({ error: "failed to delete file" }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+36 -4
View File
@@ -1,7 +1,10 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateSelfOr, gateSession } from "@/auth/api";
import { hasPermission } from "@/auth/permissions";
import {
listUnavailability,
getUnavailability,
createUnavailability,
updateUnavailability,
cancelUnavailability,
@@ -87,10 +90,27 @@ const constraintError = (err: unknown): Response | null => {
return null;
};
/** GET /api/dev/unavailability?userId=... — list blackouts (one per user). */
/**
* GET /api/dev/unavailability?userId=... — list blackouts.
* A volunteer sees their own; a leader (`schedule.publish`) may see anyone's
* or, with no `userId`, the whole team's.
*/
export const GET = async (req: NextRequest) => {
const userId = req.nextUrl.searchParams.get("userId") ?? undefined;
const rows = await listUnavailability({ userId });
const gate = await gateSession();
if (gate instanceof Response) return gate;
const requested = req.nextUrl.searchParams.get("userId") ?? undefined;
const canManage = hasPermission(gate.systemRole, "schedule.publish");
if (requested && requested !== gate.id && !canManage) {
return new Response(
JSON.stringify({ error: "not permitted to view another person's blackouts" }),
{ status: 403, headers: JSON_HEADERS },
);
}
const rows = await listUnavailability({
userId: requested ?? (canManage ? undefined : gate.id),
});
return new Response(JSON.stringify({ rows }), {
status: 200,
headers: JSON_HEADERS,
@@ -105,8 +125,14 @@ export const POST = async (req: NextRequest) => {
}
const parsed = unavailabilityCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
const gate = await gateSelfOr("schedule.publish", parsed.data.userId);
if (gate instanceof Response) return gate;
try {
return created(await createUnavailability(parsed.data));
return created(
await createUnavailability({ ...parsed.data, createdBy: gate.id }),
);
} catch (err) {
const constraint = constraintError(err);
if (constraint) return constraint;
@@ -126,6 +152,12 @@ export const PATCH = async (req: NextRequest) => {
const id = idSchema.safeParse((body as { id?: unknown }).id);
if (!id.success) return bad("invalid id");
const existing = await getUnavailability(id.data);
if (!existing) return bad("blackout not found");
const gate = await gateSelfOr("schedule.publish", existing.userId);
if (gate instanceof Response) return gate;
// Cancel path: explicit status cancelled.
if ((body as { status?: unknown }).status === "cancelled") {
const row = await cancelUnavailability(id.data);
+133 -5
View File
@@ -1,6 +1,16 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { getUserSkills, setSelfComfort } from "@/db/userSkills";
import { gateOrUser, gateSelfOr } from "@/auth/api";
import { AssessmentError, verifySkillLevel } from "@/db/assessments";
import {
addUserSkill,
deleteUserSkill,
getUserSkill,
getUserSkills,
setMentorApproval,
setSelfComfort,
} from "@/db/userSkills";
import { SKILL_LEVELS } from "@/domain/assessments";
import { validateSelfComfort } from "@/domain/userSkills";
const JSON_HEADERS = { "content-type": "application/json" };
@@ -15,6 +25,19 @@ const selfComfortCreateSchema = z.object({
selfComfort: z.number().int().nullable().optional(),
});
/** An admin setting one person's verified level and/or mentor sign-off. */
const levelPatchSchema = z
.object({
userId: z.string().min(1),
skillId: z.string().min(1),
verifiedLevel: z.enum(SKILL_LEVELS).optional(),
mentorApproved: z.boolean().optional(),
})
.refine(
(value) => value.verifiedLevel !== undefined || value.mentorApproved !== undefined,
{ message: "nothing to update" },
);
async function readBody(req: NextRequest) {
try {
return await req.json();
@@ -70,8 +93,23 @@ const dbError = (err: unknown) => {
});
};
/** GET /api/dev/user-skills?userId=<id> — a volunteer's competency records. */
/**
* Competency records (`user_skills`).
*
* GET ?userId= -> { rows } (signed in)
* POST { userId, skillId, selfComfort } -> { row } volunteer slider: comfort only
* PATCH { userId, skillId, verifiedLevel } -> { row } admin: audited level move
* DELETE ?userId= &skillId= -> { row } admin: remove the entry
*
* The level path never writes `verified_level` directly: an existing record
* moves through `verifySkillLevel`, which appends a `skill_assessments` row in
* the same transaction. The one exception is adding a skill at `none` — the
* bottom of the ladder — which creates the record with nothing to audit.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.view");
if (gate instanceof Response) return gate;
const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId"));
if (!userId.success) return bad("invalid userId");
const rows = await getUserSkills(userId.data);
@@ -79,15 +117,22 @@ export const GET = async (req: NextRequest) => {
};
/**
* POST /api/dev/user-skills { userId, skillId, selfComfort } — set a
* volunteer's self-reported comfort (the profile slider). Only
* self_comfort / self_rated_at change; verified_level is never touched.
* POST { userId, skillId, selfComfort } — set a volunteer's self-reported
* comfort (the profile slider). Only self_comfort / self_rated_at change;
* verified_level is never touched.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.view");
if (gate instanceof Response) return gate;
const body = await readBody(req);
if (!body || typeof body !== "object") return bad("invalid body");
const parsed = selfComfortCreateSchema.safeParse(body);
if (!parsed.success) return bad(parsed.error.message);
// A volunteer may rate only their own comfort; admins may correct another
// person's record through this same path when needed.
const selfGate = await gateSelfOr("users.manage", parsed.data.userId);
if (selfGate instanceof Response) return selfGate;
const selfComfort = parsed.data.selfComfort ?? null;
const problems = validateSelfComfort(selfComfort);
if (problems.length > 0) return bad(problems[0]);
@@ -98,3 +143,86 @@ export const POST = async (req: NextRequest) => {
return dbError(err);
}
};
/**
* PATCH { userId, skillId, verifiedLevel } — the admin's per-person level edit.
*
* A missing record is created at `none` (the default level) or, when a higher
* level is requested, through the audited verify path. An existing record always
* moves through the verify path, so demotions are recorded too.
*/
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
const parsed = levelPatchSchema.safeParse(await readBody(req));
if (!parsed.success) return bad(parsed.error.message);
const { userId, skillId, verifiedLevel, mentorApproved } = parsed.data;
try {
const existing = await getUserSkill(userId, skillId);
let row = existing;
if (!existing) {
if (!verifiedLevel || verifiedLevel === "none") {
row = await addUserSkill(userId, skillId);
} else {
const result = await verifySkillLevel({
userId,
skillId,
level: verifiedLevel,
assessorId: gate.id,
kind: "admin",
});
row = result.userSkill;
}
} else if (verifiedLevel !== undefined) {
if (existing.verifiedLevel === verifiedLevel) {
return bad("level is unchanged — nothing to assess");
}
const result = await verifySkillLevel({
userId,
skillId,
level: verifiedLevel,
assessorId: gate.id,
kind: "admin",
});
row = result.userSkill;
}
if (mentorApproved !== undefined) {
row = await setMentorApproval(
userId,
skillId,
mentorApproved,
gate.id,
);
}
return ok(row);
} catch (err) {
if (err instanceof AssessmentError) return bad(err.problems.join("; "));
return dbError(err);
}
};
/** DELETE ?userId= &skillId= — remove one competency record. */
export const DELETE = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
const userId = idSchema.safeParse(req.nextUrl.searchParams.get("userId"));
const skillId = idSchema.safeParse(req.nextUrl.searchParams.get("skillId"));
if (!userId.success || !skillId.success) {
return bad("userId and skillId are required");
}
const row = await deleteUserSkill(userId.data, skillId.data);
if (!row) {
return new Response(JSON.stringify({ error: "unknown competency record" }), {
status: 404,
headers: JSON_HEADERS,
});
}
return ok({ ok: true });
};
+88
View File
@@ -0,0 +1,88 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import {
APP_ORIGIN,
requestOrigin,
sendMagicLinkEmail,
signMagicToken,
} from "@/auth/magic-link";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { getUserById } from "@/db/users";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (payload: unknown, status = 200) =>
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
const bodySchema = z.object({
userId: z.string().min(1),
deliver: z.boolean().optional(),
});
/**
* Admin emergency magic link (`users.manage`).
*
* { userId, deliver?: false } -> return a fresh 10-minute sign-in URL
* { userId, deliver: true } -> also send that URL through the configured
* email transport
*
* The URL is always returned so an admin can copy it when mail delivery is
* unavailable. Only active, non-deactivated accounts are eligible; otherwise
* the link would be rejected by the sign-in provider anyway.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
let body: unknown;
try {
body = await req.json();
} catch {
return json({ error: "A JSON body is required." }, 400);
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return json({ error: parsed.error.message }, 400);
const user = await getUserById(parsed.data.userId);
if (!user) return json({ error: "unknown user" }, 404);
if (user.status !== "active" || user.deactivatedAt !== null) {
return json(
{ error: "This account is not active — activate it first." },
409,
);
}
const token = await signMagicToken(user.email);
const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token,
)}&email=${encodeURIComponent(user.email)}`;
const delivery = parsed.data.deliver
? await sendMagicLinkEmail(user, url)
: null;
await writeAudit(db, {
actorId: gate.id,
action: parsed.data.deliver
? "user.magic_link_sent_by_admin"
: "user.magic_link_created_by_admin",
entityType: "user",
entityId: user.id,
after: {
expiresInMinutes: 10,
delivered: delivery?.delivered ?? false,
transport: delivery?.transport ?? null,
},
});
return json({
ok: true,
email: user.email,
url,
expiresInMinutes: 10,
delivered: delivery?.delivered ?? false,
transport: delivery?.transport ?? null,
});
};
+87
View File
@@ -0,0 +1,87 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import {
APP_ORIGIN,
requestOrigin,
signPasswordResetToken,
} from "@/auth/magic-link";
import { hashPassword, validatePassword } from "@/auth/password";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { getUserById, updateUserCredentials } from "@/db/users";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (payload: unknown, status = 200) =>
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
const bodySchema = z.discriminatedUnion("action", [
z.object({
action: z.literal("set"),
userId: z.string().min(1),
password: z.string().min(1).max(200),
}),
z.object({
action: z.literal("reset-link"),
userId: z.string().min(1),
}),
]);
/**
* Admin password controls (`users.manage`).
*
* { action: "set", userId, password } -> change the password directly
* { action: "reset-link", userId } -> mint a one-hour single-use link
*
* The link is returned to the admin to hand over; it is deliberately not
* emailed automatically so an admin can verify the destination first.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
let body: unknown;
try {
body = await req.json();
} catch {
return json({ error: "A JSON body is required." }, 400);
}
const parsed = bodySchema.safeParse(body);
if (!parsed.success) return json({ error: parsed.error.message }, 400);
const before = await getUserById(parsed.data.userId);
if (!before) return json({ error: "unknown user" }, 404);
if (parsed.data.action === "set") {
const passwordError = validatePassword(parsed.data.password);
if (passwordError) return json({ error: passwordError }, 400);
const passwordHash = await hashPassword(parsed.data.password);
const updated = await updateUserCredentials(before.id, { passwordHash });
if (!updated) return json({ error: "unknown user" }, 404);
await writeAudit(db, {
actorId: gate.id,
action: "user.password_set_by_admin",
entityType: "user",
entityId: before.id,
after: { passwordSet: true },
});
return json({ ok: true });
}
const token = await signPasswordResetToken(before.email);
const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/reset-password?token=${encodeURIComponent(token)}`;
await writeAudit(db, {
actorId: gate.id,
action: "user.password_reset_link_created",
entityType: "user",
entityId: before.id,
after: { expiresInMinutes: 60 },
});
return json({ ok: true, url, expiresInMinutes: 60 });
};
+276
View File
@@ -0,0 +1,276 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
import { validateUsername } from "@/auth/password";
import { SYSTEM_ROLES } from "@/auth/roles";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { USER_STATUSES } from "@/db/schema";
import { hasEventUploads } from "@/db/events";
import {
countOtherActiveAdmins,
createUser,
credentialTaken,
deleteUser,
getUserById,
hasAssignmentHistory,
listUsersForAdmin,
updateUser,
} from "@/db/users";
import { isActiveAdmin, removalPlan, wouldLeaveNoAdmin } from "@/domain/users";
import { sendWelcomeEmail } from "@/lib/welcome-email";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (payload: unknown, status = 200) =>
new Response(JSON.stringify(payload), { status, headers: JSON_HEADERS });
const bad = (message: string) => json({ error: message }, 400);
const conflict = (message: string) => json({ error: message }, 409);
const userCreateSchema = z.object({
email: z.string().email(),
username: z.string().min(1).max(100).optional(),
firstName: z.string().min(1).max(80),
lastName: z.string().max(80).optional(),
displayName: z.string().max(120).nullable().optional(),
phoneE164: z.string().max(32).nullable().optional(),
systemRole: z.enum(SYSTEM_ROLES),
status: z.enum(USER_STATUSES).optional(),
timezone: z.string().min(1).max(64).optional(),
emergencyContact: z.string().max(200).nullable().optional(),
notes: z.string().max(2000).nullable().optional(),
});
const userPatchSchema = z.object({
id: z.string().min(1),
email: z.string().email().optional(),
username: z.string().min(1).max(100).optional(),
firstName: z.string().min(1).max(80).optional(),
lastName: z.string().max(80).optional(),
displayName: z.string().max(120).nullable().optional(),
phoneE164: z.string().max(32).nullable().optional(),
systemRole: z.enum(SYSTEM_ROLES).optional(),
status: z.enum(USER_STATUSES).optional(),
timezone: z.string().min(1).max(64).optional(),
emergencyContact: z.string().max(200).nullable().optional(),
notes: z.string().max(2000).nullable().optional(),
/** Convenience flag: true sets `deactivated_at`, false clears it. */
deactivated: z.boolean().optional(),
});
async function readBody(req: NextRequest) {
try {
return await req.json();
} catch {
return null;
}
}
/** Walk the cause chain for a Postgres SQLSTATE (pg nests it under `cause`). */
function pgCode(err: unknown): string | undefined {
let node = err as { code?: string; cause?: unknown } | null;
while (node) {
if (typeof node.code === "string") return node.code;
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
}
return undefined;
}
/**
* User administration (admin-only, `users.manage`).
*
* GET -> { users } every account, full editable record
* POST -> { user, url, welcome } create (active, or pending approval)
* PATCH -> { user } edit any field / deactivate
* DELETE ?id= -> { ok } hard delete when the person has no
* scheduling history
*
* Every mutation writes an audit row. Two safety rules live in
* `src/domain/users.ts` and are enforced here: the last active admin can never
* be demoted, deactivated or deleted, and someone who has served is
* deactivated rather than deleted so past weeks stay readable.
*/
export const GET = async () => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
return json({ users: await listUsersForAdmin() });
};
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
const parsed = userCreateSchema.safeParse(await readBody(req));
if (!parsed.success) return bad(parsed.error.message);
if (parsed.data.username) {
const usernameError = validateUsername(parsed.data.username);
if (usernameError) return bad(usernameError);
if (await credentialTaken(parsed.data.username)) {
return conflict("that username is already in use");
}
}
try {
const user = await createUser(parsed.data);
await writeAudit(db, {
actorId: gate.id,
action: "user.created",
entityType: "user",
entityId: user.id,
after: {
email: user.email,
systemRole: user.systemRole,
status: user.status,
},
});
// Hand the admin a sign-in link, exactly like the invite flow does. The
// link only works once the account is active.
const token = await signMagicToken(user.email);
const origin = requestOrigin(req) || APP_ORIGIN;
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
token,
)}&email=${encodeURIComponent(user.email)}`;
// A new active account gets its sign-in details by email. Pending accounts
// are mailed when they are approved, when the link can actually work.
const welcome =
user.status === "active" && user.deactivatedAt === null
? await sendWelcomeEmail(user, url)
: null;
return json({ user, url, welcome }, 201);
} catch (err) {
if (pgCode(err) === "23505") {
return conflict("a user with this email already exists");
}
return json({ error: "failed to create user" }, 500);
}
};
export const PATCH = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
const parsed = userPatchSchema.safeParse(await readBody(req));
if (!parsed.success) return bad(parsed.error.message);
const { id, deactivated, ...fields } = parsed.data;
const before = await getUserById(id);
if (!before) return json({ error: "unknown user" }, 404);
if (fields.username !== undefined) {
const usernameError = validateUsername(fields.username);
if (usernameError) return bad(usernameError);
if (await credentialTaken(fields.username, id)) {
return conflict("that username is already in use");
}
}
if (fields.email !== undefined && fields.email !== before.email) {
if (await credentialTaken(fields.email, id)) {
return conflict("that email is already used as a username or email");
}
}
const nextRole = fields.systemRole ?? before.systemRole;
const nextStatus = fields.status ?? before.status;
const nextDeactivated =
deactivated === undefined ? before.deactivatedAt !== null : deactivated;
const nextEligible = nextStatus === "active" && !nextDeactivated;
const otherActiveAdmins = await countOtherActiveAdmins(id);
if (
wouldLeaveNoAdmin({
targetIsActiveAdmin: isActiveAdmin(before),
nextRole,
nextEligible,
otherActiveAdmins,
})
) {
return conflict("the last active admin cannot be demoted or deactivated");
}
const patch = {
...fields,
...(deactivated === undefined
? {}
: { deactivatedAt: deactivated ? new Date() : null }),
};
try {
const user = await updateUser(id, patch);
if (!user) return json({ error: "unknown user" }, 404);
await writeAudit(db, {
actorId: gate.id,
action: "user.updated",
entityType: "user",
entityId: id,
before: {
email: before.email,
systemRole: before.systemRole,
status: before.status,
deactivated: before.deactivatedAt !== null,
},
after: {
email: user.email,
systemRole: user.systemRole,
status: user.status,
deactivated: user.deactivatedAt !== null,
},
});
return json({ user });
} catch (err) { if (pgCode(err) === "23505") {
return conflict("a user with this email or username already exists");
}
return json({ error: "failed to update user" }, 500);
}
};
export const DELETE = async (req: NextRequest) => {
const gate = await gateOrUser("users.manage");
if (gate instanceof Response) return gate;
const id = req.nextUrl.searchParams.get("id");
if (!id) return bad("an id is required");
const before = await getUserById(id);
if (!before) return json({ error: "unknown user" }, 404);
if (isActiveAdmin(before) && (await countOtherActiveAdmins(id)) === 0) {
return conflict("the last active admin cannot be deleted");
}
const plan = removalPlan({
hasAssignmentHistory: await hasAssignmentHistory(id),
hasEventUploads: await hasEventUploads(id),
});
if (!plan.allowed) return conflict(plan.reason);
try {
await deleteUser(id);
await writeAudit(db, {
actorId: gate.id,
action: "user.deleted",
entityType: "user",
entityId: id,
before: {
email: before.email,
systemRole: before.systemRole,
status: before.status,
},
});
return json({ ok: true });
} catch (err) {
// Assignment/upload rows are ON DELETE RESTRICT; the checks above should
// have caught this, but the database is the last word.
if (pgCode(err) === "23503") {
return conflict("this person has history and cannot be deleted — deactivate them instead");
}
return json({ error: "failed to delete user" }, 500);
}
};
+120
View File
@@ -0,0 +1,120 @@
import { NextRequest } from "next/server";
import { rm } from "node:fs/promises";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import {
deleteEvent,
getEventAccess,
listEventPhotosForArchive,
} from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { eventVideoUploadDir } from "@/lib/event-videos";
import {
checkArchiveDestination,
getStorageSettings,
} from "@/db/storage-settings";
import {
archiveEventPhotos,
EventArchiveError,
} from "@/lib/event-nfs-archive";
import { eventPhotoDir } from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
* POST /api/events/:id/archive
*
* Manager-only. Copies every original and saved edit to the configured NFS
* mount, writes a manifest, then deletes the database rows and the live upload
* directory. The event is only removed after the archive rename succeeds.
*/
export const POST = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!access.canManage) {
return errorResponse(403, "only an event manager may archive this event");
}
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 photos = await listEventPhotosForArchive(id);
const videos = await listEventVideos(id);
let archived;
try {
archived = await archiveEventPhotos({
eventId: id,
title: access.event.title,
startsAt: access.event.startsAt,
endsAt: access.event.endsAt,
location: access.event.location,
description: access.event.description,
archivePath: storage.archivePath,
archiveFolder: storage.archiveFolder,
nfsShare: storage.nfsShare,
photos,
});
} catch (error) {
if (error instanceof EventArchiveError) {
return errorResponse(409, error.message);
}
console.error(`event ${id}: archive failed`, error);
return errorResponse(500, "the event could not be archived");
}
const deleted = await deleteEvent(id);
if (!deleted) {
return errorResponse(
500,
"the archive was written, but the event rows could not be removed",
);
}
try {
await rm(eventPhotoDir(id), { recursive: true, force: true });
await rm(eventVideoUploadDir(id), { recursive: true, force: true });
} catch (error) {
console.error(`event ${id}: archived but live files remain`, error);
}
await writeAudit(db, {
actorId: gate.id,
action: "event.archived",
entityType: "event",
entityId: id,
before: {
title: deleted.event.title,
startsAt: deleted.event.startsAt.toISOString(),
photoCount: deleted.photoCount,
videoCount: videos.length,
},
after: {
archivePath: archived.archivePath,
nfsShare: storage.nfsShare || null,
files: archived.files,
bytes: archived.bytes,
deleted: true,
videoOriginalsKeptOnNfs: videos.length,
},
});
return jsonResponse({
ok: true,
archivePath: archived.archivePath,
files: archived.files,
bytes: archived.bytes,
});
};
+122
View File
@@ -0,0 +1,122 @@
import { ZipArchive } from "archiver";
import { NextRequest } from "next/server";
import { stat } from "node:fs/promises";
import { PassThrough, Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { getEventAccess, listEventPhotosForArchive } from "@/db/events";
import { assignArchivePaths, eventArchiveFilename } from "@/lib/event-archive";
import {
editedPhotoFilename,
eventPhotoPath,
photoContentDisposition,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
/**
* GET /api/events/:id/download
*
* Streams every photo on the event as one ZIP, preserving folder names. Saved
* edits are included beside their originals as `<name>-edited.jpg`. The
* archive is store-only: JPEGs and camera RAW files are already compressed, so
* deflating them would add CPU and latency without shrinking the download.
* Anyone assigned to the event (or a manager) can download it.
*/
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const photos = await listEventPhotosForArchive(id);
if (photos.length === 0) {
return errorResponse(404, "this event has no photos");
}
// Originals claim their names first, then generated edits join the same
// folder. A real upload named `photo-edited.jpg` therefore keeps its name and
// the generated version is numbered instead.
const entries: {
key: string;
folderName: string;
filename: string;
storedName: string;
}[] = [];
for (const photo of photos) {
entries.push({
key: `${photo.id}:original`,
folderName: photo.folderName,
filename: photo.filename,
storedName: photo.storedName,
});
}
for (const photo of photos) {
if (!photo.editedStoredName) continue;
entries.push({
key: `${photo.id}:edited`,
folderName: photo.folderName,
filename: editedPhotoFilename(photo.filename),
storedName: photo.editedStoredName,
});
}
const names = assignArchivePaths(
entries.map((entry) => ({
id: entry.key,
folderName: entry.folderName,
filename: entry.filename,
})),
);
const available: { path: string; name: string }[] = [];
for (const entry of entries) {
const filePath = eventPhotoPath(entry.storedName);
try {
const info = await stat(filePath);
if (!info.isFile()) continue;
available.push({ path: filePath, name: names.get(entry.key)! });
} catch {
console.warn(`event ${id}: skipping missing archive entry ${entry.key}`);
}
}
if (available.length === 0) {
return errorResponse(404, "the event photos are missing from storage");
}
// archiver uses readable-stream, so bridge through a core PassThrough before
// handing the response to the Web Streams API.
const output = new PassThrough();
const archive = new ZipArchive({ store: true });
archive.on("warning", (error) => {
console.warn(`event ${id}: zip warning`, error);
});
archive.on("error", (error) => {
console.error(`event ${id}: zip failed`, error);
output.destroy(error);
});
archive.pipe(output);
for (const file of available) {
archive.file(file.path, { name: file.name });
}
void archive.finalize().catch((error) => output.destroy(error));
return new Response(
Readable.toWeb(output) as unknown as ReadableStream<Uint8Array>,
{
status: 200,
headers: {
"content-type": "application/zip",
"content-disposition": photoContentDisposition(
eventArchiveFilename(access.event.title),
false,
),
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
},
},
);
};
@@ -0,0 +1,130 @@
import { NextRequest } from "next/server";
import { randomUUID } from "node:crypto";
import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { gateSession } from "@/auth/api";
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
import {
editedPhotoFilename,
editedStoredNameForEventPhoto,
eventPhotoPath,
isEditableEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
const MAX_EDIT_BODY_BYTES = 32 * 1024;
/**
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit
* Body: { adjustments: PhotoAdjustments }
*
* Saves the recipe and renders a fresh full-resolution JPEG beside the
* original. The original file is never changed, so an edit can always be
* reopened and adjusted again.
*/
export const POST = async (
req: NextRequest,
{
params,
}: {
params: Promise<{ id: string; folderId: string; photoId: string }>;
},
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
if (Number(req.headers.get("content-length") ?? 0) > MAX_EDIT_BODY_BYTES) {
return errorResponse(413, "the edit settings are too large");
}
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");
}
if (!isEditableEventPhoto(access.photo.filename)) {
return errorResponse(415, "this photo format cannot be edited");
}
const body = (await req.json().catch(() => null)) as
| { adjustments?: unknown }
| null;
const adjustments = normalizePhotoAdjustments(body?.adjustments);
if (!adjustments) {
return errorResponse(400, "invalid photo adjustments");
}
const sourcePath = eventPhotoPath(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");
}
const editedStoredName = editedStoredNameForEventPhoto(
access.eventId,
access.photo.id,
);
const editedPath = eventPhotoPath(editedStoredName);
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
try {
rendered = await renderPhotoJpeg({
filePath: sourcePath,
kind: access.photo.kind,
adjustments,
});
} catch (error) {
if (error instanceof PhotoRenderError) {
return errorResponse(422, error.message);
}
console.error("photo edit render failed", error);
return errorResponse(500, "the edited JPEG could not be generated");
}
await mkdir(path.dirname(editedPath), { recursive: true });
const temporary = `${editedPath}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, rendered.data);
await rename(temporary, editedPath);
} catch (error) {
await unlink(temporary).catch(() => undefined);
console.error("photo edit write failed", error);
return errorResponse(500, "the edited JPEG could not be saved");
}
try {
const updated = await updateEventPhotoEdit({
photoId: access.photo.id,
editJson: JSON.stringify(adjustments),
editedStoredName,
editedSizeBytes: rendered.data.byteLength,
editedBy: gate.id,
});
if (!updated) {
await unlink(editedPath).catch(() => undefined);
return errorResponse(404, "unknown photo");
}
return jsonResponse({
ok: true,
adjustments,
editedFilename: editedPhotoFilename(access.photo.filename),
editedSizeBytes: rendered.data.byteLength,
editedAt: updated.editedAt,
width: rendered.width,
height: rendered.height,
});
} catch (error) {
await unlink(editedPath).catch(() => undefined);
console.error("photo edit metadata failed", error);
return errorResponse(500, "the edit was rendered but could not be recorded");
}
};
@@ -0,0 +1,99 @@
import { NextRequest } from "next/server";
import { stat } from "node:fs/promises";
import sharp from "sharp";
import { gateSession } from "@/auth/api";
import { getEventPhotoAccess } from "@/db/events";
import {
eventPhotoPath,
photoContentDisposition,
} from "@/lib/event-photos";
import {
photoExportFilename,
photoExportPresetFor,
} from "@/lib/photo-exports";
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
import { errorResponse } from "@/lib/http";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId/export?size=2048
*
* Renders a delivery-sized JPEG from the saved edit. The saved full-resolution
* JPEG is resized rather than re-decoded from RAW; if it is missing, the
* original is rendered from the stored recipe as a fallback. Only the four
* delivery sizes advertised by the editor are accepted.
*/
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 preset = photoExportPresetFor(req.nextUrl.searchParams.get("size"));
if (!preset) {
return errorResponse(400, "unknown export size");
}
let data: Buffer;
try {
if (access.photo.editedStoredName) {
const editedPath = eventPhotoPath(access.photo.editedStoredName);
const info = await stat(editedPath);
if (!info.isFile()) throw new Error("missing edit");
data = await sharp(editedPath)
.resize({
width: preset.maxDimension,
height: preset.maxDimension,
fit: "inside",
withoutEnlargement: true,
})
.jpeg({ quality: 90, mozjpeg: true, chromaSubsampling: "4:4:4" })
.toBuffer();
} else if (access.photo.editJson) {
const rendered = await renderPhotoJpeg({
filePath: eventPhotoPath(access.photo.storedName),
kind: access.photo.kind,
adjustments: parseStoredPhotoAdjustments(access.photo.editJson),
maxDimension: preset.maxDimension,
});
data = rendered.data;
} else {
return errorResponse(
409,
"Save an edit before exporting a delivery-sized JPEG.",
);
}
} catch (error) {
if (error instanceof PhotoRenderError) {
return errorResponse(422, error.message);
}
console.error("photo export failed", error);
return errorResponse(500, "the exported JPEG could not be generated");
}
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": "image/jpeg",
"content-length": String(data.byteLength),
"content-disposition": photoContentDisposition(
photoExportFilename(access.photo.filename, preset),
false,
),
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
"content-security-policy": "default-src 'none'; sandbox",
},
});
};
@@ -0,0 +1,102 @@
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 { gateSession } from "@/auth/api";
import { getEventPhotoAccess } from "@/db/events";
import {
eventPhotoPath,
isEditableEventPhoto,
previewStoredNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse } from "@/lib/http";
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId/preview
*
* A browser-sized JPEG of the untouched original. RAW files are decoded through
* LibRaw; the result is cached on disk because the original never changes.
* The client applies the live adjustment LUT to this proxy.
*/
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");
}
if (!isEditableEventPhoto(access.photo.filename)) {
return errorResponse(415, "this photo format cannot be previewed in the editor");
}
const sourcePath = eventPhotoPath(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");
}
const previewPath = eventPhotoPath(
previewStoredNameForEventPhoto(access.eventId, access.photo.id),
);
try {
const cached = await stat(previewPath);
if (cached.isFile() && cached.size > 0) {
return imageResponse(await readFile(previewPath));
}
} catch {
// Not generated yet.
}
try {
const rendered = await renderPhotoJpeg({
filePath: sourcePath,
kind: access.photo.kind,
adjustments: defaultPhotoAdjustments(),
maxDimension: 1800,
});
await mkdir(path.dirname(previewPath), { recursive: true });
const temporary = `${previewPath}.${randomUUID()}.tmp`;
await writeFile(temporary, rendered.data);
await rename(temporary, previewPath);
return imageResponse(rendered.data);
} catch (error) {
if (error instanceof PhotoRenderError) {
return errorResponse(422, error.message);
}
console.error("photo preview failed", error);
return errorResponse(500, "the preview could not be generated");
}
};
function imageResponse(data: Buffer): Response {
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": "image/jpeg",
"content-length": String(data.byteLength),
"content-disposition": "inline",
"cache-control": "private, max-age=86400, immutable",
"x-content-type-options": "nosniff",
"content-security-policy": "default-src 'none'; sandbox",
},
});
}
@@ -0,0 +1,125 @@
import { NextRequest } from "next/server";
import { createReadStream } from "node:fs";
import { stat, unlink } from "node:fs/promises";
import { Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
import { canDeleteEventPhoto } from "@/lib/event-access";
import {
editedPhotoFilename,
eventPhotoPath,
isBrowserRenderablePhoto,
photoContentDisposition,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
* GET /api/events/:id/folders/:folderId/photos/:photoId[?download=1|variant=edited]
*
* Streams the original bytes to anyone assigned to the event (or a manager).
* `variant=edited` serves the generated full-resolution JPEG instead, so the
* gallery can show the saved look without replacing the original. RAW files
* always download; `?download=1` forces an attachment for JPEGs too.
*/
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 wantsEdited = req.nextUrl.searchParams.get("variant") === "edited";
if (wantsEdited && !access.photo.editedStoredName) {
return errorResponse(404, "this photo has no saved edit");
}
const filePath = eventPhotoPath(
wantsEdited
? access.photo.editedStoredName!
: access.photo.storedName,
);
const filename = wantsEdited
? editedPhotoFilename(access.photo.filename)
: access.photo.filename;
let size: number;
try {
size = (await stat(filePath)).size;
} catch {
return errorResponse(404, "the file is missing from storage");
}
const inline =
req.nextUrl.searchParams.get("download") !== "1" &&
(wantsEdited || isBrowserRenderablePhoto(access.photo.filename));
const stream = createReadStream(filePath);
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
status: 200,
headers: {
"content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType,
"content-length": String(size),
"content-disposition": photoContentDisposition(filename, inline),
"cache-control": "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
"content-security-policy": "default-src 'none'; sandbox",
},
},
);
};
/** DELETE — the uploader or an event manager can remove a photo. */
export const DELETE = 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");
}
if (
!canDeleteEventPhoto({
role: gate.systemRole,
userId: gate.id,
uploaderId: access.photo.uploaderId,
})
) {
return errorResponse(403, "only the uploader or a coordinator may delete this photo");
}
await deleteEventPhoto(photoId);
await unlink(eventPhotoPath(access.photo.storedName)).catch(() => undefined);
if (access.photo.editedStoredName) {
await unlink(eventPhotoPath(access.photo.editedStoredName)).catch(
() => undefined,
);
}
return jsonResponse({ ok: true });
};
@@ -0,0 +1,156 @@
import { NextRequest } from "next/server";
import { createHash } from "node:crypto";
import { createWriteStream } from "node:fs";
import { mkdir, unlink } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
import { pipeline } from "node:stream/promises";
import { gateSession } from "@/auth/api";
import {
addEventPhoto,
findEventPhotoByChecksum,
getEventFolderAccess,
isUniqueViolation,
} from "@/db/events";
import {
MAX_EVENT_PHOTO_BYTES,
eventPhotoKindFor,
eventPhotoMimeFor,
eventPhotoPath,
sanitizePhotoFilename,
storedNameForEventPhoto,
} from "@/lib/event-photos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { uuidv7 } from "@/lib/uuid";
class PhotoTooLarge extends Error {}
function publicPhoto(photo: {
id: string;
folderId: string;
filename: string;
mimeType: string;
sizeBytes: number;
kind: "raw" | "image";
createdAt: Date;
}) {
return {
id: photo.id,
folderId: photo.folderId,
filename: photo.filename,
mimeType: photo.mimeType,
sizeBytes: photo.sizeBytes,
kind: photo.kind,
createdAt: photo.createdAt,
};
}
/**
* POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3
*
* A single photo is the raw request body (not multipart), so a 100 MB RAW file
* streams straight to disk instead of being buffered in memory. The filename is
* passed as a query parameter because headers cannot carry arbitrary Unicode.
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string; folderId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, folderId } = await params;
const access = await getEventFolderAccess(folderId, gate.id, gate.systemRole);
if (!access || access.eventId !== id) {
return errorResponse(404, "unknown folder");
}
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizePhotoFilename(suppliedName);
const kind = eventPhotoKindFor(filename);
if (!kind) {
return errorResponse(
415,
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
);
}
const declaredLength = Number(req.headers.get("content-length") ?? 0);
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
return errorResponse(413, "that photo is larger than 200 MB");
}
if (!req.body) return errorResponse(400, "a file body is required");
const photoId = uuidv7();
const storedName = storedNameForEventPhoto(id, photoId, filename);
const destination = eventPhotoPath(storedName);
await mkdir(path.dirname(destination), { recursive: true });
const hash = createHash("sha256");
let size = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length;
if (size > MAX_EVENT_PHOTO_BYTES) {
callback(new PhotoTooLarge());
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
try {
await pipeline(
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
meter,
createWriteStream(destination, { flags: "wx" }),
);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (error instanceof PhotoTooLarge) {
return errorResponse(413, "that photo is larger than 200 MB");
}
return errorResponse(500, "the upload did not complete");
}
if (size === 0) {
await unlink(destination).catch(() => undefined);
return errorResponse(400, "the uploaded file was empty");
}
const checksumSha256 = hash.digest("hex");
const existing = await findEventPhotoByChecksum(folderId, checksumSha256);
if (existing) {
await unlink(destination).catch(() => undefined);
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
}
try {
const photo = await addEventPhoto({
folderId,
uploaderId: gate.id,
filename,
mimeType: eventPhotoMimeFor(filename),
sizeBytes: size,
storedName,
checksumSha256,
kind,
});
return jsonResponse({ photo: publicPhoto(photo) }, 201);
} catch (error) {
await unlink(destination).catch(() => undefined);
if (isUniqueViolation(error)) {
const raced = await findEventPhotoByChecksum(folderId, checksumSha256);
if (raced) {
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
}
}
throw error;
}
};
+53
View File
@@ -0,0 +1,53 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateSession } from "@/auth/api";
import {
createEventFolder,
getEventAccess,
isUniqueViolation,
} from "@/db/events";
import { errorResponse, jsonResponse } from "@/lib/http";
const folderSchema = z.object({
name: z.string().trim().min(1).max(80),
kind: z.enum(["originals", "edited", "mixed"]).optional(),
});
/**
* POST /api/events/:id/folders — create a folder inside an event.
* Any assigned photographer, coordinator or admin may create one.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
const parsed = folderSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid folder");
}
try {
const folder = await createEventFolder({
eventId: id,
name: parsed.data.name,
kind: parsed.data.kind ?? "originals",
createdBy: gate.id,
});
return jsonResponse({ folder }, 201);
} catch (error) {
if (isUniqueViolation(error)) {
return errorResponse(409, "a folder with that name already exists");
}
throw error;
}
};
@@ -0,0 +1,67 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import {
assignEventPhotographer,
getEventAccess,
removeEventPhotographer,
} from "@/db/events";
import { EVENT_PHOTOGRAPHER_ROLES } from "@/db/schema";
import { errorResponse, jsonResponse } from "@/lib/http";
const assignmentSchema = z.object({
userId: z.string().min(1),
role: z.enum(EVENT_PHOTOGRAPHER_ROLES).optional(),
});
/**
* POST /api/events/:id/photographers — assign a photographer/editor.
* DELETE ?userId= — remove them. Managers only (`schedule.publish`).
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const parsed = assignmentSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid assignment");
}
const assignment = await assignEventPhotographer({
eventId: id,
userId: parsed.data.userId,
role: parsed.data.role ?? "photographer",
assignedBy: gate.id,
});
if (!assignment) {
return errorResponse(400, "that account is not an active team member");
}
return jsonResponse({ assignment }, 201);
};
export const DELETE = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const userId = req.nextUrl.searchParams.get("userId");
if (!userId) return errorResponse(400, "a userId is required");
const removed = await removeEventPhotographer(id, userId);
if (!removed) return errorResponse(404, "that person is not assigned");
return jsonResponse({ ok: true });
};
+77
View File
@@ -0,0 +1,77 @@
import { NextRequest } from "next/server";
import { rm } from "node:fs/promises";
import { gateOrUser } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import { deleteEvent, getEventAccess } from "@/db/events";
import { listEventVideos } from "@/db/videos";
import { getStorageSettings } from "@/db/storage-settings";
import { eventPhotoDir } from "@/lib/event-photos";
import {
eventVideoArchiveDir,
eventVideoUploadDir,
} from "@/lib/event-videos";
import { errorResponse, jsonResponse } from "@/lib/http";
/**
* DELETE /api/events/:id — manager-only. Removes the event, its folders/photos
* and the event's directory on the uploads volume. The database cascade commits
* first; bytes are then removed best-effort so a storage hiccup cannot leave a
* half-deleted event row. Any orphaned bytes are reported in the server log.
*/
export const DELETE = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const videos = await listEventVideos(id);
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);
}
// 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.
try {
const storage = await getStorageSettings();
for (const video of videos) {
await rm(
eventVideoArchiveDir(
storage.archivePath,
video.archiveFolder,
id,
video.id,
),
{ recursive: true, force: true },
);
}
} catch (error) {
console.error(`event ${id}: NFS video originals were not removed`, error);
}
await writeAudit(db, {
actorId: gate.id,
action: "event.deleted",
entityType: "event",
entityId: id,
before: {
title: deleted.event.title,
startsAt: deleted.event.startsAt.toISOString(),
photoCount: deleted.photoCount,
videoCount: videos.length,
},
});
return jsonResponse({ ok: true });
};
@@ -0,0 +1,152 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateSession } from "@/auth/api";
import { db } from "@/db";
import { writeAudit } from "@/db/audit";
import {
getEventVideoAccess,
updateEventVideo,
type EventVideoPatch,
} from "@/db/videos";
import { EVENT_VIDEO_VISIBILITIES } from "@/db/schema";
import { errorResponse, jsonResponse } from "@/lib/http";
import { processEventVideo } from "@/lib/video-processing";
import { videoView } from "@/lib/video-view";
const MAX_BODY_BYTES = 64 * 1024;
const editSchema = z.object({
title: z.string().trim().min(1).max(200).optional(),
description: z.string().max(5000).nullable().optional(),
visibility: z.enum(EVENT_VIDEO_VISIBILITIES).optional(),
trimStartMs: z.number().int().min(0).optional(),
trimEndMs: z.number().int().min(0).nullable().optional(),
});
/**
* POST /api/events/:id/videos/:videoId/edit
*
* Metadata is saved immediately. A changed trim marks the video processing and
* re-renders the web MP4 with FFmpeg; the NFS original is never altered. Only a
* manager may publish a video as unlisted/public.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) {
return errorResponse(413, "the video edit is too large");
}
const { id, videoId } = await params;
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
if (!access || access.video.eventId !== id) {
return errorResponse(404, "unknown video");
}
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
const parsed = editSchema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(
400,
parsed.error.issues[0]?.message ?? "invalid video edit",
);
}
const body = parsed.data;
if (Object.keys(body).length === 0) {
return errorResponse(400, "no changes were supplied");
}
if (
body.visibility &&
body.visibility !== "team" &&
!access.canManage
) {
return errorResponse(
403,
"only a coordinator or admin can publish a video publicly",
);
}
const video = access.video;
const patch: EventVideoPatch = {};
if (body.title !== undefined) patch.title = body.title;
if (body.description !== undefined) {
patch.description = body.description?.trim() || null;
}
if (body.visibility !== undefined) patch.visibility = body.visibility;
let trimChanged = false;
if (body.trimStartMs !== undefined || body.trimEndMs !== undefined) {
if (!video.durationMs || video.durationMs <= 0) {
return errorResponse(
409,
"this video is still being processed; wait until it is ready before trimming",
);
}
const duration = video.durationMs;
const minimum = Math.min(1000, duration);
const currentEnd = video.trimEndMs ?? duration;
const requestedStart = body.trimStartMs ?? video.trimStartMs;
const requestedEnd = body.trimEndMs ?? currentEnd;
const start = Math.min(
Math.max(0, requestedStart),
Math.max(0, duration - minimum),
);
const end = Math.min(
Math.max(requestedEnd, start + minimum),
duration,
);
trimChanged = start !== video.trimStartMs || end !== currentEnd;
patch.trimStartMs = start;
patch.trimEndMs = end;
}
if (trimChanged) {
patch.status = "processing";
patch.errorMessage = null;
}
const updated = await updateEventVideo(video.id, patch);
if (!updated) return errorResponse(404, "unknown video");
if (trimChanged) {
void processEventVideo(updated.id).catch((error) => {
console.error(`video ${updated.id}: background trim failed`, error);
});
}
await writeAudit(db, {
actorId: gate.id,
action: "video.edited",
entityType: "event_video",
entityId: video.id,
before: {
title: video.title,
visibility: video.visibility,
trimStartMs: video.trimStartMs,
trimEndMs: video.trimEndMs,
},
after: {
title: updated.title,
visibility: updated.visibility,
trimStartMs: updated.trimStartMs,
trimEndMs: updated.trimEndMs,
processing: trimChanged,
},
});
return jsonResponse({
video: videoView({
...updated,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
}),
canManage: access.canManage,
canContribute: access.canContribute,
});
};
@@ -0,0 +1,77 @@
import { NextRequest } from "next/server";
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 } from "@/db/videos";
import {
eventVideoArchivePath,
videoContentDisposition,
} from "@/lib/event-videos";
import { errorResponse } from "@/lib/http";
import { parseByteRange } from "@/lib/range";
/** Download the untouched camera original from the NFS archive. */
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, videoId } = await params;
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
if (!access || access.video.eventId !== id) {
return errorResponse(404, "unknown video");
}
let filePath: string;
try {
const storage = await getStorageSettings();
filePath = eventVideoArchivePath(
storage.archivePath,
access.video.archiveFolder,
access.video.originalStoredName,
);
} catch {
return errorResponse(404, "the NFS archive 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");
}
const range = parseByteRange(req.headers.get("range"), info.size);
if (range === "invalid") {
return new Response(null, {
status: 416,
headers: { "content-range": `bytes */${info.size}` },
});
}
const start = range?.start ?? 0;
const end = range?.end ?? info.size - 1;
const stream = createReadStream(filePath, { start, end });
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
status: range ? 206 : 200,
headers: {
"content-type": access.video.mimeType,
"content-length": String(end - start + 1),
"accept-ranges": "bytes",
...(range
? { "content-range": `bytes ${start}-${end}/${info.size}` }
: {}),
"content-disposition": videoContentDisposition(
access.video.filename,
false,
),
"cache-control": "private, no-store",
"x-content-type-options": "nosniff",
},
},
);
};
@@ -0,0 +1,47 @@
import { NextRequest } from "next/server";
import { gateSession } from "@/auth/api";
import {
getEventVideoAccess,
markVideoProcessing,
} from "@/db/videos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { processEventVideo } from "@/lib/video-processing";
import { videoView } from "@/lib/video-view";
/** Retry a failed encode; the NFS original is still intact. */
export const POST = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, videoId } = await params;
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
if (!access || access.video.eventId !== id) {
return errorResponse(404, "unknown video");
}
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
if (access.video.status === "processing") {
return errorResponse(409, "this video is already processing");
}
if (access.video.status === "ready") {
return errorResponse(409, "this video is already ready; save an edit to re-render it");
}
const updated = await markVideoProcessing(videoId);
if (!updated) return errorResponse(404, "unknown video");
void processEventVideo(videoId).catch((error) => {
console.error(`video ${videoId}: retry failed`, error);
});
return jsonResponse({
video: videoView({
...updated,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
}),
});
};
@@ -0,0 +1,104 @@
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";
import {
deleteEventVideo,
getEventVideoAccess,
} from "@/db/videos";
import { getStorageSettings } from "@/db/storage-settings";
import {
eventVideoArchiveDir,
eventVideoUploadPath,
webStoredNameForEventVideo,
} from "@/lib/event-videos";
import { errorResponse, jsonResponse } from "@/lib/http";
import { videoView } from "@/lib/video-view";
/** GET /api/events/:id/videos/:videoId — metadata + processing status. */
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, videoId } = await params;
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
if (!access || access.video.eventId !== id) {
return errorResponse(404, "unknown video");
}
return jsonResponse({
video: videoView({
...access.video,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
}),
canManage: access.canManage,
canContribute: access.canContribute,
});
};
/** DELETE — uploader or an event manager; removes NFS original + derivatives. */
export const DELETE = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string; videoId: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id, videoId } = await params;
const access = await getEventVideoAccess(videoId, gate.id, gate.systemRole);
if (!access || access.video.eventId !== id) {
return errorResponse(404, "unknown video");
}
if (!access.canManage && access.video.uploaderId !== gate.id) {
return errorResponse(403, "only the uploader or a coordinator may delete this video");
}
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);
});
try {
const storage = await getStorageSettings();
await rm(
eventVideoArchiveDir(
storage.archivePath,
removed.archiveFolder,
removed.eventId,
removed.id,
),
{ recursive: true, force: true },
);
} catch (error) {
console.error(`video ${videoId}: NFS original was not removed`, error);
}
await writeAudit(db, {
actorId: gate.id,
action: "video.deleted",
entityType: "event_video",
entityId: videoId,
before: {
eventId: removed.eventId,
title: removed.title,
filename: removed.filename,
sizeBytes: removed.sizeBytes,
},
});
return jsonResponse({ ok: true });
};
@@ -0,0 +1,257 @@
import { NextRequest } from "next/server";
import { createWriteStream } from "node:fs";
import { mkdir, stat, truncate, unlink } from "node:fs/promises";
import path from "node:path";
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 {
EVENT_VIDEO_VISIBILITIES,
type EventVideoVisibility,
} from "@/db/schema";
import { finalizeEventVideo, checksumFile } from "@/lib/event-video-finalize";
import {
eventVideoArchivePath,
isAllowedEventVideo,
originalStoredNameForEventVideo,
sanitizeVideoFilename,
} from "@/lib/event-videos";
import { uuidv7 } from "@/lib/uuid";
import { errorResponse, jsonResponse } from "@/lib/http";
import {
EVENT_VIDEO_CHUNK_BYTES,
MAX_EVENT_VIDEO_BYTES,
MAX_EVENT_VIDEO_LABEL,
} from "@/lib/video-limits";
import { videoView } from "@/lib/video-view";
const UPLOAD_ID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function integerParam(value: string | null): number | null {
if (!value || !/^\d+$/.test(value)) return null;
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
function isMissing(error: unknown): boolean {
return (
typeof error === "object" &&
error !== null &&
"code" in error &&
(error as { code?: string }).code === "ENOENT"
);
}
/**
* POST /api/events/:id/videos/chunk
* ?uploadId=<uuid>&offset=<bytes>&size=<total bytes>
* &name=...&title=...&visibility=team
*
* Raw body, one slice of the file at a time. Cloudflare rejects bodies over
* 100 MB, so the browser sends 50 MB slices and this route appends them to the
* NFS temporary original. The final slice hashes the complete file, inserts the
* metadata row, and starts FFmpeg through the same finalizer as the single-shot
* upload route.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
const uploadId = req.nextUrl.searchParams.get("uploadId") ?? "";
if (!UPLOAD_ID_PATTERN.test(uploadId)) {
return errorResponse(400, "a valid upload id is required");
}
const offset = integerParam(req.nextUrl.searchParams.get("offset"));
const total = integerParam(req.nextUrl.searchParams.get("size"));
if (offset === null || total === null) {
return errorResponse(400, "the upload offset and total size are required");
}
if (total <= 0 || total > MAX_EVENT_VIDEO_BYTES) {
return errorResponse(
413,
`that video is larger than ${MAX_EVENT_VIDEO_LABEL}`,
);
}
if (offset >= total) {
return errorResponse(400, "the upload offset is outside the video");
}
const declaredLength = Number(req.headers.get("content-length") ?? 0);
if (!Number.isSafeInteger(declaredLength) || declaredLength <= 0) {
return errorResponse(400, "the chunk has no content length");
}
if (declaredLength > EVENT_VIDEO_CHUNK_BYTES) {
return errorResponse(
413,
"upload chunks must be 50 MB or smaller",
);
}
if (offset + declaredLength > total) {
return errorResponse(400, "the chunk extends past the end of the video");
}
const isFinal = offset + declaredLength === total;
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizeVideoFilename(suppliedName);
if (!isAllowedEventVideo(filename)) {
return errorResponse(
415,
"unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP",
);
}
const visibilityText =
req.nextUrl.searchParams.get("visibility") ?? "team";
if (
!EVENT_VIDEO_VISIBILITIES.includes(
visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number],
)
) {
return errorResponse(400, "invalid video visibility");
}
const visibility = visibilityText as EventVideoVisibility;
if (visibility !== "team" && !access.canManage) {
return errorResponse(
403,
"only a coordinator or admin can publish a video publicly",
);
}
const title =
(req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) ||
path.parse(filename).name.slice(0, 200);
const description =
(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.`,
);
}
// 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
// cannot overwrite another video's original by guessing its id.
const stagingDir = eventVideoArchivePath(
storage.archivePath,
storage.archiveFolder,
`videos/${id}/.uploads`,
);
const temporary = path.join(stagingDir, `${uploadId}.upload`);
await mkdir(stagingDir, { recursive: true });
let existingSize = 0;
try {
existingSize = (await stat(temporary)).size;
} catch (error) {
if (!isMissing(error)) throw error;
}
if (existingSize !== offset) {
return errorResponse(
409,
"the upload offset does not match the bytes already received; restart the upload",
"UPLOAD_OFFSET_MISMATCH",
);
}
if (!req.body) return errorResponse(400, "a video body is required");
const writeStream = createWriteStream(
temporary,
existingSize === 0
? { flags: "w", mode: 0o640 }
: { flags: "r+", start: offset, mode: 0o640 },
);
try {
await pipeline(
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
writeStream,
);
} catch (error) {
if (existingSize === 0) {
await unlink(temporary).catch(() => undefined);
} else {
await truncate(temporary, offset).catch(() => undefined);
}
console.error(`event ${id}: video chunk upload failed`, error);
return errorResponse(500, "the video chunk did not complete");
}
const written = (await stat(temporary)).size;
if (written !== offset + declaredLength) {
if (existingSize === 0) {
await unlink(temporary).catch(() => undefined);
} else {
await truncate(temporary, offset).catch(() => undefined);
}
return errorResponse(
400,
"the video chunk was incomplete; restart the upload",
);
}
if (!isFinal) {
return jsonResponse({ complete: false, receivedBytes: written });
}
try {
const checksumSha256 = await checksumFile(temporary);
const videoId = uuidv7();
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
const destination = eventVideoArchivePath(
storage.archivePath,
storage.archiveFolder,
storedName,
);
await mkdir(path.dirname(destination), { recursive: true });
const result = await finalizeEventVideo({
eventId: id,
videoId,
temporary,
destination,
checksumSha256,
sizeBytes: total,
filename,
title,
description,
originalStoredName: storedName,
archiveFolder: storage.archiveFolder,
visibility,
uploaderId: gate.id,
event: access.event,
});
return jsonResponse(
result.duplicate
? { video: videoView(result.video), duplicate: true }
: { video: videoView(result.video) },
result.duplicate ? 200 : 201,
);
} catch (error) {
await unlink(temporary).catch(() => undefined);
console.error(`event ${id}: video finalization failed`, error);
return errorResponse(500, "the video could not be finalized");
}
};
+213
View File
@@ -0,0 +1,213 @@
import { NextRequest } from "next/server";
import { createHash } from "node:crypto";
import { createWriteStream } from "node:fs";
import { mkdir, unlink } from "node:fs/promises";
import path from "node:path";
import { Readable, Transform } from "node:stream";
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 {
MAX_EVENT_VIDEO_BYTES,
eventVideoArchivePath,
isAllowedEventVideo,
originalStoredNameForEventVideo,
sanitizeVideoFilename,
} from "@/lib/event-videos";
import { finalizeEventVideo } from "@/lib/event-video-finalize";
import { errorResponse, jsonResponse } from "@/lib/http";
import { uuidv7 } from "@/lib/uuid";
import { videoView } from "@/lib/video-view";
import {
EVENT_VIDEO_VISIBILITIES,
type EventVideoVisibility,
} from "@/db/schema";
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
* 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.
*/
export const POST = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
if (!access.canContribute) {
return errorResponse(403, "you are not assigned to this event");
}
const suppliedName = req.nextUrl.searchParams.get("name");
if (!suppliedName) return errorResponse(400, "a filename is required");
const filename = sanitizeVideoFilename(suppliedName);
if (!isAllowedEventVideo(filename)) {
return errorResponse(
415,
"unsupported video type; upload MP4, MOV, M4V, WebM, MKV, AVI, MPEG, MTS or 3GP",
);
}
const visibilityText =
req.nextUrl.searchParams.get("visibility") ?? "team";
if (
!EVENT_VIDEO_VISIBILITIES.includes(
visibilityText as (typeof EVENT_VIDEO_VISIBILITIES)[number],
)
) {
return errorResponse(400, "invalid video visibility");
}
const visibility = visibilityText as EventVideoVisibility;
if (visibility !== "team" && !access.canManage) {
return errorResponse(
403,
"only a coordinator or admin can publish a video publicly",
);
}
const title =
(req.nextUrl.searchParams.get("title") ?? "").trim().slice(0, 200) ||
path.parse(filename).name.slice(0, 200);
const description =
(req.nextUrl.searchParams.get("description") ?? "").trim().slice(0, 5000) ||
null;
const declaredLength = Number(req.headers.get("content-length") ?? 0);
if (declaredLength > MAX_EVENT_VIDEO_BYTES) {
return errorResponse(413, "that video is larger than 4 GB");
}
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.`,
);
}
const videoId = uuidv7();
const storedName = originalStoredNameForEventVideo(id, videoId, filename);
const destination = eventVideoArchivePath(
storage.archivePath,
storage.archiveFolder,
storedName,
);
await mkdir(path.dirname(destination), { recursive: true });
const temporary = `${destination}.${uuidv7()}.upload`;
const hash = createHash("sha256");
let size = 0;
const meter = new Transform({
transform(chunk: Buffer, _encoding, callback) {
size += chunk.length;
if (size > MAX_EVENT_VIDEO_BYTES) {
callback(new VideoTooLarge());
return;
}
hash.update(chunk);
callback(null, chunk);
},
});
try {
await pipeline(
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
meter,
createWriteStream(temporary, { flags: "wx", mode: 0o640 }),
);
} catch (error) {
await unlink(temporary).catch(() => undefined);
if (error instanceof VideoTooLarge) {
return errorResponse(413, "that video is larger than 4 GB");
}
console.error(`event ${id}: video upload failed`, error);
return errorResponse(500, "the video upload did not complete");
}
if (size === 0) {
await unlink(temporary).catch(() => undefined);
return errorResponse(400, "the uploaded video was empty");
}
// Never accept a short body as an original. A proxy or middleware body limit
// used to truncate large uploads while still returning 201, which produced a
// corrupt NFS file and a video that could not be processed.
if (declaredLength > 0 && size !== declaredLength) {
await unlink(temporary).catch(() => undefined);
return errorResponse(
400,
"the video upload did not complete; check your connection and try again",
);
}
const checksumSha256 = hash.digest("hex");
try {
const result = await finalizeEventVideo({
eventId: id,
videoId,
temporary,
destination,
checksumSha256,
sizeBytes: size,
filename,
title,
description,
originalStoredName: storedName,
archiveFolder: storage.archiveFolder,
visibility,
uploaderId: gate.id,
event: access.event,
});
return jsonResponse(
result.duplicate
? { video: videoView(result.video), duplicate: true }
: { video: videoView(result.video) },
result.duplicate ? 200 : 201,
);
} catch (error) {
await unlink(temporary).catch(() => undefined);
console.error(`event ${id}: video finalization failed`, error);
return errorResponse(500, "the video could not be finalized");
}
};
/** GET /api/events/:id/videos — video list for one event. */
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const { id } = await params;
const access = await getEventAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown event");
const videos = await listEventVideos(id);
return jsonResponse({
videos: videos.map((video) =>
videoView({
...video,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
}),
),
canManage: access.canManage,
canContribute: access.canContribute,
});
};
+72
View File
@@ -0,0 +1,72 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser, gateSession } from "@/auth/api";
import { createEvent, listEventsForUser } from "@/db/events";
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
import { errorResponse, jsonResponse } from "@/lib/http";
const LOCAL_DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/;
const createSchema = z.object({
title: z.string().trim().min(1).max(200),
eventType: z.string().trim().min(1).max(50).optional(),
startsAtLocal: z.string().regex(LOCAL_DATE_TIME, "invalid start time"),
endsAtLocal: z
.string()
.regex(LOCAL_DATE_TIME, "invalid end time")
.nullable()
.optional(),
location: z.string().trim().max(300).nullable().optional(),
description: z.string().max(5000).nullable().optional(),
});
function localDate(value: string): Date {
const [date, time] = value.split("T");
return localToUtc(date, time, CHURCH_TIMEZONE);
}
/** GET /api/events — events the signed-in user may open. */
export const GET = async () => {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const events = await listEventsForUser(gate.id, gate.systemRole);
return jsonResponse({ events });
};
/**
* POST /api/events — create an event (coordinator/admin).
*
* Times are sent as church-local wall clock (`YYYY-MM-DDTHH:mm`), so the server
* — not the browser's timezone — decides the UTC instant.
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const body = await req.json().catch(() => null);
const parsed = createSchema.safeParse(body);
if (!parsed.success) {
return errorResponse(400, parsed.error.issues[0]?.message ?? "invalid event");
}
const startsAt = localDate(parsed.data.startsAtLocal);
const endsAt = parsed.data.endsAtLocal
? localDate(parsed.data.endsAtLocal)
: null;
if (endsAt && endsAt <= startsAt) {
return errorResponse(400, "the end time must be after the start time");
}
const event = await createEvent({
title: parsed.data.title,
eventType: parsed.data.eventType ?? "photoshoot",
startsAt,
endsAt,
location: parsed.data.location ?? null,
description: parsed.data.description ?? null,
createdBy: gate.id,
});
return jsonResponse({ event }, 201);
};
+18
View File
@@ -0,0 +1,18 @@
import { gateOrUser } from "@/auth/api";
import { servingHistoryCsv } from "@/db/exports";
/** GET /api/export/history — completed / no-show assignments as CSV. */
export const GET = async () => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const csv = await servingHistoryCsv();
return new Response(csv, {
status: 200,
headers: {
"content-type": "text/csv; charset=utf-8",
"content-disposition": 'attachment; filename="serving-history.csv"',
"cache-control": "no-store",
},
});
};
+34
View File
@@ -0,0 +1,34 @@
import { NextRequest } from "next/server";
import { gateOrUser } from "@/auth/api";
import { scheduleCsv } from "@/db/exports";
import { addDaysISO, dateInTimezone, CHURCH_TIMEZONE } from "@/lib/tz";
/**
* GET /api/export/schedule?from=YYYY-MM-DD&to=YYYY-MM-DD
* Defaults to the next four weeks. CSV only — printing is a browser action.
*/
export const GET = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const today = dateInTimezone(new Date(), CHURCH_TIMEZONE);
const from = req.nextUrl.searchParams.get("from") ?? today;
const to = req.nextUrl.searchParams.get("to") ?? addDaysISO(from, 27);
if (!/^\d{4}-\d{2}-\d{2}$/.test(from) || !/^\d{4}-\d{2}-\d{2}$/.test(to)) {
return new Response(JSON.stringify({ error: "invalid date" }), {
status: 400,
headers: { "content-type": "application/json" },
});
}
const csv = await scheduleCsv(from, to);
return new Response(csv, {
status: 200,
headers: {
"content-type": "text/csv; charset=utf-8",
"content-disposition": `attachment; filename="schedule-${from}-to-${to}.csv"`,
"cache-control": "no-store",
},
});
};
+57
View File
@@ -0,0 +1,57 @@
import { NextRequest } from "next/server";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
import { eventVideoUploadPath } from "@/lib/event-videos";
import { errorResponse } from "@/lib/http";
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const { id } = await params;
let video = await getPublicEventVideo(id);
let publicVideo = Boolean(video);
if (!video) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const access = await getEventVideoAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown video");
video = {
...access.video,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
};
publicVideo = false;
}
if (!video.posterStoredName) {
return errorResponse(404, "this video has no poster yet");
}
let filePath: string;
try {
filePath = eventVideoUploadPath(video.posterStoredName);
} catch {
return errorResponse(404, "unknown poster");
}
const info = await stat(filePath).catch(() => null);
if (!info?.isFile()) return errorResponse(404, "the poster is missing");
const stream = createReadStream(filePath);
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
headers: {
"content-type": "image/jpeg",
"content-length": String(info.size),
"cache-control": publicVideo
? "public, max-age=86400"
: "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
},
},
);
};
+110
View File
@@ -0,0 +1,110 @@
import { NextRequest } from "next/server";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { Readable } from "node:stream";
import { gateSession } from "@/auth/api";
import { getEventVideoAccess, getPublicEventVideo } from "@/db/videos";
import {
eventVideoUploadPath,
sanitizeVideoFilename,
videoContentDisposition,
webRenditionStoredNameForEventVideo,
} from "@/lib/event-videos";
import { errorResponse } from "@/lib/http";
import { parseByteRange } from "@/lib/range";
/**
* GET /api/media/:id/stream
*
* Serves the processed web MP4 or a lower-resolution rendition via
* `?quality=720|480`. Public/unlisted ready videos need no session; team videos
* reuse event access. Byte ranges keep browser seeking and mobile social embeds
* working.
*/
export const GET = async (
req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const { id } = await params;
let video = await getPublicEventVideo(id);
let publicVideo = Boolean(video);
if (!video) {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const access = await getEventVideoAccess(id, gate.id, gate.systemRole);
if (!access) return errorResponse(404, "unknown video");
video = {
...access.video,
eventTitle: access.event.title,
eventStartsAt: access.event.startsAt,
};
publicVideo = false;
}
if (video.status !== "ready" || !video.webStoredName) {
return errorResponse(409, "this video is still processing");
}
let filePath: string;
let info: Awaited<ReturnType<typeof stat>> | null = null;
try {
filePath = eventVideoUploadPath(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(
webRenditionStoredNameForEventVideo(
video.eventId,
video.id,
Number(quality),
),
);
const renditionInfo = await stat(renditionPath).catch(() => null);
if (renditionInfo?.isFile()) {
filePath = renditionPath;
info = renditionInfo;
}
}
} catch {
return errorResponse(404, "unknown video");
}
if (!info?.isFile()) {
return errorResponse(404, "the processed video is missing");
}
const range = parseByteRange(req.headers.get("range"), info.size);
if (range === "invalid") {
return new Response(null, {
status: 416,
headers: { "content-range": `bytes */${info.size}` },
});
}
const start = range?.start ?? 0;
const end = range?.end ?? info.size - 1;
const stream = createReadStream(filePath, { start, end });
return new Response(
Readable.toWeb(stream) as unknown as ReadableStream<Uint8Array>,
{
status: range ? 206 : 200,
headers: {
"content-type": "video/mp4",
"content-length": String(end - start + 1),
"accept-ranges": "bytes",
...(range
? { "content-range": `bytes ${start}-${end}/${info.size}` }
: {}),
"content-disposition": videoContentDisposition(
`${sanitizeVideoFilename(video.title).replace(/\.mp4$/i, "")}.mp4`,
true,
),
"cache-control": publicVideo
? "public, max-age=3600"
: "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
},
},
);
};
+55
View File
@@ -0,0 +1,55 @@
import { NextRequest } from "next/server";
import { getPublicEventVideo } from "@/db/videos";
import { requestOrigin } from "@/auth/magic-link";
import { errorResponse } from "@/lib/http";
import { videoView } from "@/lib/video-view";
/**
* GET /api/oembed?url=https://host/watch/:id&format=json
*
* A standard oEmbed video response for WordPress, LMS pages, and other
* consumers that do not read Open Graph tags. Only public/unlisted ready videos
* are exposed.
*/
export const GET = async (req: NextRequest) => {
const rawUrl = req.nextUrl.searchParams.get("url");
if (!rawUrl) return errorResponse(400, "a url parameter is required");
let parsed: URL;
try {
parsed = new URL(rawUrl);
} catch {
return errorResponse(400, "invalid url");
}
const match = /^\/(?:watch|embed)\/([A-Za-z0-9_-]+)\/?$/.exec(parsed.pathname);
if (!match) return errorResponse(404, "no embeddable media at that url");
const video = await getPublicEventVideo(match[1]);
if (!video) return errorResponse(404, "no embeddable media at that url");
const origin = requestOrigin(req);
const view = videoView(video, origin);
const payload = {
version: "1.0",
type: "video",
provider_name: "Glenloch Baptist Church",
provider_url: origin,
title: video.title,
author_name: video.eventTitle,
url: view.watchUrl,
html: view.embedCode,
width: view.embedWidth,
height: view.embedHeight,
thumbnail_url: view.posterUrl,
thumbnail_width: Math.min(1280, video.width ?? 1280),
thumbnail_height: Math.min(720, video.height ?? 720),
};
return new Response(JSON.stringify(payload), {
headers: {
"content-type": "application/json; charset=utf-8",
"access-control-allow-origin": "*",
"cache-control": "public, max-age=300",
},
});
};
+117
View File
@@ -0,0 +1,117 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { clientIp } from "@/auth/api";
import { RespondError, applyRespond } from "@/db/respond";
import { verifyRespondToken } from "@/lib/respond";
import { rateLimit } from "@/lib/rate-limit";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({
token: z.string().min(1),
action: z.enum(["confirm", "decline"]),
});
/** Map a refused respond action to its HTTP status. */
function errorStatus(code: RespondError["code"]): number {
switch (code) {
case "already_used":
case "not_actionable":
return 409;
case "unknown_assignment":
return 404;
case "wrong_volunteer":
return 403;
}
}
/**
* POST /api/respond — { token, action: "confirm" | "decline" }
*
* The no-login confirm/decline endpoint (ARCHITECTURE §5.6). The signed token
* carries the assignment, volunteer, action and `jti`; the `jti` is consumed
* exactly once. `GET /respond` renders the page and never mutates, so a link
* preview cannot accept a shift.
*/
export const POST = async (req: NextRequest) => {
let parsedBody: z.infer<typeof bodySchema>;
try {
const body = await req.json().catch(() => null);
const parsed = bodySchema.safeParse(body);
if (!parsed.success) {
return new Response(
JSON.stringify({ error: "a token and action are required" }),
{ status: 400, headers: JSON_HEADERS },
);
}
parsedBody = parsed.data;
} catch {
return new Response(JSON.stringify({ error: "invalid body" }), {
status: 400,
headers: JSON_HEADERS,
});
}
// Public endpoint: cap attempts per IP so tokens cannot be brute-forced.
const limit = rateLimit(`respond:${clientIp(req)}`, 30, 60_000);
if (!limit.ok) {
return new Response(
JSON.stringify({
error: "too many attempts; try again shortly",
code: "RATE_LIMITED",
}),
{
status: 429,
headers: {
...JSON_HEADERS,
"retry-after": String(limit.retryAfterSeconds),
},
},
);
}
const payload = await verifyRespondToken(parsedBody.token);
if (!payload) {
return new Response(
JSON.stringify({
error: "this link is invalid or has expired",
code: "invalid_token",
}),
{ status: 400, headers: JSON_HEADERS },
);
}
if (payload.action !== parsedBody.action) {
return new Response(
JSON.stringify({
error: "this link is for a different action",
code: "action_mismatch",
}),
{ status: 400, headers: JSON_HEADERS },
);
}
try {
const result = await applyRespond({
assignmentId: payload.assignmentId,
userId: payload.userId,
action: payload.action,
jti: payload.jti,
});
return new Response(JSON.stringify({ ok: true, ...result }), {
status: 200,
headers: JSON_HEADERS,
});
} catch (e) {
if (e instanceof RespondError) {
return new Response(
JSON.stringify({ error: e.message, code: e.code }),
{ status: errorStatus(e.code), headers: JSON_HEADERS },
);
}
const message = e instanceof Error ? e.message : "internal error";
return new Response(JSON.stringify({ error: message }), {
status: 500,
headers: JSON_HEADERS,
});
}
};
+165
View File
@@ -0,0 +1,165 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser, gateSession } from "@/auth/api";
import {
addChecklistItem,
addRunSheetItem,
deleteChecklistItem,
deleteRunSheetItem,
saveRunSheetHeader,
toggleChecklistItem,
updateRunSheetItem,
} from "@/db/runSheet";
const JSON_HEADERS = { "content-type": "application/json" };
const json = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: JSON_HEADERS });
const headerSchema = z.object({
action: z.literal("save-header"),
instanceId: z.string().min(1),
speaker: z.string().max(200).nullable().optional(),
sermonTitle: z.string().max(300).nullable().optional(),
streamUrl: z.string().max(500).nullable().optional(),
slidesUrl: z.string().max(500).nullable().optional(),
notes: z.string().max(4000).nullable().optional(),
});
const itemAddSchema = z.object({
action: z.literal("add-item"),
instanceId: z.string().min(1),
title: z.string().min(1).max(200),
timeLabel: z.string().max(20).nullable().optional(),
owner: z.string().max(120).nullable().optional(),
notes: z.string().max(1000).nullable().optional(),
});
const itemUpdateSchema = z.object({
action: z.literal("update-item"),
id: z.string().min(1),
title: z.string().min(1).max(200).optional(),
timeLabel: z.string().max(20).nullable().optional(),
owner: z.string().max(120).nullable().optional(),
notes: z.string().max(1000).nullable().optional(),
sortOrder: z.number().int().optional(),
});
const itemDeleteSchema = z.object({
action: z.literal("delete-item"),
id: z.string().min(1),
});
const checkToggleSchema = z.object({
action: z.literal("toggle-check"),
id: z.string().min(1),
done: z.boolean(),
});
const checkAddSchema = z.object({
action: z.literal("add-check"),
instanceId: z.string().min(1),
phase: z.enum(["pre", "post"]),
label: z.string().min(1).max(200),
});
const checkDeleteSchema = z.object({
action: z.literal("delete-check"),
id: z.string().min(1),
});
const bodySchema = z.discriminatedUnion("action", [
headerSchema,
itemAddSchema,
itemUpdateSchema,
itemDeleteSchema,
checkToggleSchema,
checkAddSchema,
checkDeleteSchema,
]);
async function body(req: NextRequest): Promise<unknown> {
try {
return await req.json();
} catch {
return null;
}
}
/**
* Run-sheet mutations. Anyone signed in can tick a checklist item (the team
* shares the Sunday checklist); editing the sheet, adding or deleting rows is a
* coordinator action.
*/
export const POST = async (req: NextRequest) => {
const parsed = bodySchema.safeParse(await body(req));
if (!parsed.success) return json({ error: parsed.error.message }, 400);
if (parsed.data.action === "toggle-check") {
const gate = await gateSession();
if (gate instanceof Response) return gate;
const row = await toggleChecklistItem(
parsed.data.id,
gate.id,
parsed.data.done,
);
if (!row) return json({ error: "checklist item not found" }, 404);
return json({ ok: true, row });
}
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
switch (parsed.data.action) {
case "save-header": {
const data = parsed.data;
await saveRunSheetHeader(data.instanceId, gate.id, {
speaker: data.speaker,
sermonTitle: data.sermonTitle,
streamUrl: data.streamUrl,
slidesUrl: data.slidesUrl,
notes: data.notes,
});
return json({ ok: true });
}
case "add-item": {
const data = parsed.data;
const row = await addRunSheetItem(data.instanceId, {
title: data.title,
timeLabel: data.timeLabel,
owner: data.owner,
notes: data.notes,
});
return json({ ok: true, row }, 201);
}
case "update-item": {
const data = parsed.data;
const row = await updateRunSheetItem(data.id, {
title: data.title,
timeLabel: data.timeLabel,
owner: data.owner,
notes: data.notes,
sortOrder: data.sortOrder,
});
if (!row) return json({ error: "run sheet item not found" }, 404);
return json({ ok: true, row });
}
case "delete-item": {
const deleted = await deleteRunSheetItem(parsed.data.id);
if (!deleted) return json({ error: "run sheet item not found" }, 404);
return json({ ok: true });
}
case "add-check": {
const row = await addChecklistItem(
parsed.data.instanceId,
parsed.data.phase,
parsed.data.label,
);
return json({ ok: true, row }, 201);
}
case "delete-check": {
const deleted = await deleteChecklistItem(parsed.data.id);
if (!deleted) return json({ error: "checklist item not found" }, 404);
return json({ ok: true });
}
}
};
+49
View File
@@ -0,0 +1,49 @@
import { NextRequest } from "next/server";
import { readFile } from "node:fs/promises";
import { auth } from "@/auth/config";
import { getResource } from "@/db/training";
import { uploadPath } from "@/lib/uploads";
/**
* Serve a training attachment to a signed-in team member.
*
* GET /api/training/files/:id
*
* Files are private (no public/ directory), so authoring uploads cannot be
* fetched without a session. Content is served inline; the original filename is
* preserved for downloads.
*/
export const GET = async (
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> },
) => {
const session = await auth();
if (!session?.user) {
return new Response("Authentication required", { status: 401 });
}
const { id } = await params;
const resource = await getResource(id);
if (!resource) {
return new Response("Not found", { status: 404 });
}
try {
const data = await readFile(uploadPath(resource.storedName));
const safeName = resource.filename.replaceAll('"', "");
return new Response(new Uint8Array(data), {
status: 200,
headers: {
"content-type": resource.mimeType,
"content-length": String(data.length),
// Only images render inline; everything else is a download, so an
// uploaded HTML/SVG payload cannot execute in this origin.
"content-disposition": `${resource.mimeType.startsWith("image/") ? "inline" : "attachment"}; filename="${safeName}"; filename*=UTF-8''${encodeURIComponent(resource.filename)}`,
"cache-control": "private, max-age=0, must-revalidate",
"x-content-type-options": "nosniff",
},
});
} catch {
return new Response("Not found", { status: 404 });
}
};
+42
View File
@@ -0,0 +1,42 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getPublicEventVideo } from "@/db/videos";
import { mediaOrigin } from "@/lib/media-url";
import { videoView } from "@/lib/video-view";
import { availableRenditionHeights } from "@/lib/video-renditions";
import { AdaptiveVideo } from "@/components/public/adaptive-video";
export const dynamic = "force-dynamic";
export const metadata: Metadata = {
robots: { index: false, follow: false },
title: "Video",
};
/** Minimal iframe player. No app shell, no ads, no navigation. */
export default async function EmbedPage({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const video = await getPublicEventVideo(id);
if (!video) notFound();
const origin = await mediaOrigin();
const view = videoView(video, origin);
const renditions = await availableRenditionHeights(video);
return (
<div className="fixed inset-0 bg-black">
<AdaptiveVideo
src={view.streamUrl}
poster={view.posterUrl}
title={video.title}
renditions={renditions}
containerClassName="h-full w-full"
className="h-full w-full object-contain"
/>
</div>
);
}
+71 -64
View File
@@ -2,74 +2,77 @@
@plugin "tailwindcss-animate";
:root {
color-scheme: light;
--radius: 0.625rem;
--background: oklab(1 0 0);
--foreground: oklab(0.145 0 0);
--card: oklab(1 0 0);
--card-foreground: oklab(0.145 0 0);
--popover: oklab(1 0 0);
--popover-foreground: oklab(0.145 0 0);
--primary: oklab(0.205 0 0);
--primary-foreground: oklab(0.985 0 0);
--secondary: oklab(0.97 0.006 0.015);
--secondary-foreground: oklab(0.205 0 0);
--muted: oklab(0.97 0.006 0.015);
--muted-foreground: oklab(0.451 0 0);
--accent: oklab(0.97 0.006 0.015);
--accent-foreground: oklab(0.205 0 0);
--destructive: oklab(0.583 0.185 -0.047);
--destructive-foreground: oklab(0.985 0 0);
--border: oklab(0.922 0.005 0.082);
--input: oklab(0.922 0.005 0.082);
--ring: oklab(0.708 0 0);
--chart-1: oklab(0.646 0.222 0.107);
--chart-2: oklab(0.6 0.115 -0.064);
--chart-3: oklab(0.398 0.063 0.064);
--chart-4: oklab(0.826 0.185 -0.024);
--chart-5: oklab(0.89 0.049 0.344);
--sidebar: oklab(0.985 0 0);
--sidebar-foreground: oklab(0.145 0 0);
--sidebar-primary: oklab(0.205 0 0);
--sidebar-primary-foreground: oklab(0.985 0 0);
--sidebar-accent: oklab(0.97 0.006 0.015);
--sidebar-accent-foreground: oklab(0.205 0 0);
--sidebar-border: oklab(0.922 0.005 0.082);
--sidebar-ring: oklab(0.708 0 0);
/* Glenloch Baptist Church: logo maroon, charcoal, white, warm grey. */
--background: #fbfaf8;
--foreground: #231f20;
--card: #ffffff;
--card-foreground: #231f20;
--popover: #ffffff;
--popover-foreground: #231f20;
--primary: #932822;
--primary-foreground: #ffffff;
--secondary: #f3f1ee;
--secondary-foreground: #231f20;
--muted: #f3f1ee;
--muted-foreground: #6e6664;
--accent: #f6e7e4;
--accent-foreground: #6d1e19;
--destructive: #b42318;
--destructive-foreground: #ffffff;
--border: #e5e0dc;
--input: #e5e0dc;
--ring: #932822;
--chart-1: #932822;
--chart-2: #c1685d;
--chart-3: #6e6664;
--chart-4: #d9b3ad;
--chart-5: #3f3534;
--sidebar: #ffffff;
--sidebar-foreground: #231f20;
--sidebar-primary: #932822;
--sidebar-primary-foreground: #ffffff;
--sidebar-accent: #f6e7e4;
--sidebar-accent-foreground: #6d1e19;
--sidebar-border: #e5e0dc;
--sidebar-ring: #932822;
}
.dark {
--background: oklab(0.145 0 0);
--foreground: oklab(0.985 0 0);
--card: oklab(0.205 0 0);
--card-foreground: oklab(0.985 0 0);
--popover: oklab(0.205 0 0);
--popover-foreground: oklab(0.985 0 0);
--primary: oklab(0.985 0 0);
--primary-foreground: oklab(0.205 0 0);
--secondary: oklab(0.269 0 0);
--secondary-foreground: oklab(0.985 0 0);
--muted: oklab(0.269 0 0);
--muted-foreground: oklab(0.637 0 0);
--accent: oklab(0.269 0 0);
--accent-foreground: oklab(0.985 0 0);
--destructive: oklab(0.396 0.141 -0.093);
--destructive-foreground: oklab(0.985 0 0);
--border: oklab(0.269 0 0);
--input: oklab(0.269 0 0);
--ring: oklab(0.544 0 0);
--chart-1: oklab(0.488 0.24 -0.021);
--chart-2: oklab(0.617 0.229 -0.111);
--chart-3: oklab(0.395 0.124 0.174);
--chart-4: oklab(0.714 0.203 -0.028);
--chart-5: oklab(0.691 0.128 -0.042);
--sidebar: oklab(0.205 0 0);
--sidebar-foreground: oklab(0.985 0 0);
--sidebar-primary: oklab(0.488 0.24 -0.021);
--sidebar-primary-foreground: oklab(0.985 0 0);
--sidebar-accent: oklab(0.269 0 0);
--sidebar-accent-foreground: oklab(0.985 0 0);
--sidebar-border: oklab(0.269 0 0);
--sidebar-ring: oklab(0.544 0 0);
color-scheme: dark;
--background: #171314;
--foreground: #f7f2ef;
--card: #211c1d;
--card-foreground: #f7f2ef;
--popover: #211c1d;
--popover-foreground: #f7f2ef;
--primary: #df8a80;
--primary-foreground: #2a1210;
--secondary: #2c2627;
--secondary-foreground: #f7f2ef;
--muted: #2b2526;
--muted-foreground: #b9aaa6;
--accent: #3b2321;
--accent-foreground: #f3d7d2;
--destructive: #f27a70;
--destructive-foreground: #2a0e0b;
--border: #3a3132;
--input: #3a3132;
--ring: #df8a80;
--chart-1: #df8a80;
--chart-2: #c1685d;
--chart-3: #b9aaa6;
--chart-4: #d9b3ad;
--chart-5: #8f7a75;
--sidebar: #1d1819;
--sidebar-foreground: #f7f2ef;
--sidebar-primary: #df8a80;
--sidebar-primary-foreground: #2a1210;
--sidebar-accent: #3b2321;
--sidebar-accent-foreground: #f3d7d2;
--sidebar-border: #3a3132;
--sidebar-ring: #df8a80;
}
@theme inline {
@@ -118,4 +121,8 @@
@apply bg-background text-foreground;
font-family: var(--font-sans);
}
::selection {
background: var(--primary);
color: var(--primary-foreground);
}
}
+5 -1
View File
@@ -1,4 +1,4 @@
import type { Metadata } from "next";
import type { Metadata, Viewport } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
@@ -17,6 +17,10 @@ export const metadata: Metadata = {
description: "Church media team scheduling and training platform.",
};
export const viewport: Viewport = {
themeColor: "#932822",
};
export default function RootLayout({
children,
}: Readonly<{
+156 -42
View File
@@ -1,54 +1,149 @@
"use client";
import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { signIn } from "next-auth/react";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
/**
* Magic-link sign-in (v1, no passwords). Enter an email; the dev console
* transport prints a sign-in link. Clicking it completes the Auth.js session.
* At launch there is no email/SMS delivery, so the link is shown here as a
* fallback and printed to the console (see /api/dev/magic-link).
* Sign in with the username/password set after the first magic link, or request
* a new one-time link by email. The magic-link path remains the recovery path
* when someone has not set credentials yet.
*/
export default function LoginPage() {
const [email, setEmail] = useState("");
const [status, setStatus] = useState<{ kind: "idle" | "sending" | "sent" | "error"; message?: string }>({
kind: "idle",
});
const [login, setLogin] = useState("");
const [password, setPassword] = useState("");
const [passwordStatus, setPasswordStatus] = useState<{
kind: "idle" | "signing" | "error";
message?: string;
}>({ kind: "idle" });
async function onSubmit(e: React.FormEvent) {
const [email, setEmail] = useState("");
const [linkStatus, setLinkStatus] = useState<{
kind: "idle" | "sending" | "sent" | "error";
message?: string;
}>({ kind: "idle" });
async function onPasswordSubmit(e: React.FormEvent) {
e.preventDefault();
setStatus({ kind: "sending" });
setPasswordStatus({ kind: "signing" });
try {
const result = await signIn("password", {
login,
password,
redirect: false,
});
if (!result || result.error) {
setPasswordStatus({
kind: "error",
message: "That username or password did not match an active account.",
});
return;
}
// Full navigation lets the server layout read the new session cookie.
window.location.assign("/schedule");
} catch {
setPasswordStatus({ kind: "error", message: "Network error." });
}
}
async function onLinkSubmit(e: React.FormEvent) {
e.preventDefault();
setLinkStatus({ kind: "sending" });
try {
const res = await fetch("/api/dev/magic-link", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ email }),
});
const body = (await res.json()) as { ok?: boolean; url?: string; error?: string };
if (res.ok && body.url) {
setStatus({ kind: "sent", message: body.url });
const body = (await res.json()) as {
ok?: boolean;
url?: string;
error?: string;
};
if (res.ok) {
setLinkStatus({ kind: "sent", message: body.url });
} else {
setStatus({ kind: "error", message: body.error ?? "Something went wrong." });
setLinkStatus({
kind: "error",
message: body.error ?? "Something went wrong.",
});
}
} catch {
setStatus({ kind: "error", message: "Network error." });
setLinkStatus({ kind: "error", message: "Network error." });
}
}
return (
<div className="flex min-h-screen items-center justify-center px-4">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>Sign in</CardTitle>
<CardDescription>Enter your work email — no password required.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={onSubmit} className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="email">Email</Label>
<div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-accent/50 via-background to-background px-4 py-8">
<div className="w-full max-w-sm space-y-4">
<div className="text-center">
<p className="text-xs font-semibold uppercase tracking-[0.22em] text-primary">
Glenloch Baptist Church
</p>
<p className="mt-1 text-2xl font-semibold tracking-tight">
Media Team Hub
</p>
</div>
<Card className="w-full border-t-4 border-t-primary shadow-sm">
<CardHeader>
<CardTitle>Sign in</CardTitle>
<CardDescription>
Use your username and password, or request a one-time email link.
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="login">Username or email</Label>
<Input
id="login"
name="login"
required
autoComplete="username"
value={login}
onChange={(e) => setLogin(e.target.value)}
placeholder="you@church.local"
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="password">Password</Label>
<Input
id="password"
name="password"
type="password"
required
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<Button type="submit" disabled={passwordStatus.kind === "signing"}>
{passwordStatus.kind === "signing" ? "Signing in…" : "Sign in"}
</Button>
{passwordStatus.kind === "error" && passwordStatus.message && (
<p role="alert" className="text-sm text-destructive">
{passwordStatus.message}
</p>
)}
</form>
<div className="flex items-center gap-3 text-xs uppercase tracking-wide text-muted-foreground">
<span className="h-px flex-1 bg-border" />
or
<span className="h-px flex-1 bg-border" />
</div>
<form onSubmit={onLinkSubmit} className="flex flex-col gap-3">
<Label htmlFor="email">Email a one-time sign-in link</Label>
<Input
id="email"
name="email"
@@ -59,22 +154,41 @@ export default function LoginPage() {
onChange={(e) => setEmail(e.target.value)}
placeholder="you@church.local"
/>
</div>
<Button type="submit" disabled={status.kind === "sending"}>
{status.kind === "sending" ? "Sending link…" : "Send sign-in link"}
</Button>
{status.kind === "sent" && status.message && (
<p className="rounded border border-border bg-muted p-3 text-sm break-all">
Sign-in link (dev console transport):<br />
<span className="text-foreground underline">{status.message}</span>
</p>
)}
{status.kind === "error" && status.message && (
<p className="text-sm text-destructive">{status.message}</p>
)}
</form>
</CardContent>
</Card>
<Button
type="submit"
variant="outline"
disabled={linkStatus.kind === "sending"}
>
{linkStatus.kind === "sending" ? "Sending link…" : "Send sign-in link"}
</Button>
{linkStatus.kind === "sent" &&
(linkStatus.message ? (
<p className="rounded border border-border bg-muted p-3 text-sm break-all">
Sign-in link (dev console transport):<br />
<span className="text-foreground underline">
{linkStatus.message}
</span>
</p>
) : (
<p className="rounded border border-border bg-muted p-3 text-sm">
Check your email for a single-use sign-in link. It expires in
10 minutes.
</p>
))}
{linkStatus.kind === "error" && linkStatus.message && (
<p role="alert" className="text-sm text-destructive">
{linkStatus.message}
</p>
)}
</form>
<p className="text-xs text-muted-foreground">
First time here? The magic link will ask you to set a username and
password. If you are locked out, ask an admin for a reset link.
</p>
</CardContent>
</Card>
</div>
</div>
);
}
+8 -100
View File
@@ -1,103 +1,11 @@
import Image from "next/image";
import { redirect } from "next/navigation";
/**
* Root route. The app lives under the authenticated `(app)` group, so `/`
* simply forwards into the schedule; that layout redirects a visitor without a
* session to `/login`. (The create-next-app starter page that used to live here
* was the "Deploy now" screen users landed on.)
*/
export default function Home() {
return (
<div className="font-sans grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20">
<main className="flex flex-col gap-[32px] row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="font-mono list-inside list-decimal text-sm/6 text-center sm:text-left">
<li className="mb-2 tracking-[-.01em]">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] font-mono font-semibold px-1 py-0.5 rounded">
src/app/page.tsx
</code>
.
</li>
<li className="tracking-[-.01em]">
Save and see your changes instantly.
</li>
</ol>
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:w-auto"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent font-medium text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 w-full sm:w-auto md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-[24px] flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org →
</a>
</footer>
</div>
);
redirect("/home");
}
+42
View File
@@ -0,0 +1,42 @@
import Link from "next/link";
import { CoverageIntakeForm } from "@/components/app/requests/coverage-intake-form";
export const metadata = {
title: "Request media coverage",
description: "Ask the media team to cover an event.",
};
/**
* Public, unauthenticated intake. Kept outside the `(app)` group so no session
* is required; submission is rate-limited server-side.
*/
export default function RequestCoveragePage() {
return (
<div className="mx-auto min-h-screen w-full max-w-3xl px-4 py-10">
<header className="mb-6">
<p className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Glenloch Baptist Church
</p>
<h1 className="mt-1 text-2xl font-semibold tracking-tight">
Request media coverage
</h1>
<p className="mt-2 text-sm text-muted-foreground">
Weddings, baptisms, outreach nights, productions, and other events.
Tell us what is happening and a media coordinator will follow up.
</p>
</header>
<div className="rounded-md border border-border p-5">
<CoverageIntakeForm />
</div>
<p className="mt-6 text-xs text-muted-foreground">
Media team member?{" "}
<Link href="/login" className="font-medium underline">
Sign in
</Link>
.
</p>
</div>
);
}
+62
View File
@@ -0,0 +1,62 @@
import Link from "next/link";
import { verifyPasswordResetToken } from "@/auth/magic-link";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ResetPasswordForm } from "@/components/app/reset-password-form";
export const metadata = { title: "Reset password" };
export default async function ResetPasswordPage({
searchParams,
}: {
searchParams: Promise<{ token?: string }>;
}) {
const { token } = await searchParams;
const payload = await verifyPasswordResetToken(token);
return (
<div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-accent/50 via-background to-background px-4 py-8">
<div className="w-full max-w-md space-y-4">
<div className="text-center">
<p className="text-xs font-semibold uppercase tracking-[0.22em] text-primary">
Glenloch Baptist Church
</p>
<p className="mt-1 text-2xl font-semibold tracking-tight">
Media Team Hub
</p>
</div>
<Card className="border-t-4 border-t-primary shadow-sm">
<CardHeader>
<CardTitle className="text-xl" role="heading" aria-level={1}>
Reset password
</CardTitle>
<CardDescription>
Choose a new password for your Media Team Hub account.
</CardDescription>
</CardHeader>
<CardContent>
{payload && token ? (
<ResetPasswordForm token={token} email={payload.email} />
) : (
<div className="space-y-4 text-sm">
<p role="alert" className="text-destructive">
This reset link is invalid or has expired. Ask an admin for a
new link.
</p>
<Button asChild variant="outline">
<Link href="/login">Back to sign in</Link>
</Button>
</div>
)}
</CardContent>
</Card>
</div>
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
import { getRespondAssignment } from "@/db/respond";
import { verifyRespondToken } from "@/lib/respond";
import { RespondForm } from "@/components/app/respond-form";
/**
* Public respond page — unit E4 (ARCHITECTURE §5.6).
*
* `GET /respond?t=<token>&a=confirm|decline` renders the assignment and the two
* buttons. It never mutates: the token is consumed only by the form's POST.
*/
export default async function RespondPage({
searchParams,
}: {
searchParams: Promise<{ t?: string }>;
}) {
const { t } = await searchParams;
const payload = await verifyRespondToken(t);
if (!payload || !t) {
return (
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-3 px-6">
<h1 className="text-xl font-semibold">This link isn&apos;t valid</h1>
<p className="text-sm text-muted-foreground">
It may have expired. Ask a coordinator to send a new one.
</p>
</main>
);
}
const assignment = await getRespondAssignment(payload.assignmentId);
if (!assignment) {
return (
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-3 px-6">
<h1 className="text-xl font-semibold">Assignment not found</h1>
<p className="text-sm text-muted-foreground">
It may have been removed. Ask a coordinator to check the schedule.
</p>
</main>
);
}
const alreadyAnswered =
assignment.status === "confirmed" || assignment.status === "declined";
return (
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-4 px-6">
<p className="text-sm text-muted-foreground">Hi {assignment.volunteerName}</p>
<h1 className="text-2xl font-semibold">
{assignment.roleName} — {assignment.serviceName}
</h1>
<p className="text-sm">
{assignment.occursOnLabel} at {assignment.startTimeLabel}
{assignment.callTimeLabel ? ` · call time ${assignment.callTimeLabel}` : ""}
</p>
{assignment.location && (
<p className="text-sm text-muted-foreground">{assignment.location}</p>
)}
{alreadyAnswered ? (
<p className="text-sm text-muted-foreground">
You already responded — this assignment is {assignment.status}.
</p>
) : (
<RespondForm token={t} />
)}
<p className="text-xs text-muted-foreground">
No login needed. The links are single-use; if you can&apos;t serve, decline
so a coordinator can find cover.
</p>
</main>
);
}

Some files were not shown because too many files have changed in this diff Show More