Share the public request form at{" "}
diff --git a/src/app/(app)/training/guides/admin/page.tsx b/src/app/(app)/training/guides/admin/page.tsx
index a9a57a6..7672691 100644
--- a/src/app/(app)/training/guides/admin/page.tsx
+++ b/src/app/(app)/training/guides/admin/page.tsx
@@ -109,10 +109,13 @@ export default function AdminGuidePage() {
/>
- 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.
+ New service instances start as drafts, and volunteers do not see a
+ draft on their schedule. Assigning a seat still sends the proposed
+ email immediately so the volunteer can accept, decline, or propose
+ another Sunday. Publishing makes the week visible and queues the
+ published/reminder mail for every live assignment. A draft is safe
+ to edit; a published week should be changed carefully because people
+ have already been told about it.
@@ -374,7 +377,9 @@ export default function AdminGuidePage() {
Press Publish when the week is ready. Publishing
- queues assignment email and reminder rules for that instance.
+ makes the week visible and queues the published/reminder mail for
+ live assignments. Assignments made later still send their proposed
+ email immediately.
Unpublish only when you intend to withdraw the week; volunteers may
@@ -443,6 +448,20 @@ export default function AdminGuidePage() {
+
+ Volunteers who propose another Sunday
+
+
+ The proposed email also offers Propose another Sunday.
+ That link records a pending proposal for a coordinator but leaves the
+ original assignment live, so the seat remains covered while you
+ decide. Pending proposals appear on Coverage under{" "}
+ Proposed another Sunday. This queue is read-only for
+ now: review the date and note, then change the schedule yourself
+ (assign a replacement or clear the seat) and confirm the change with
+ the volunteer.
+
+
Requests from outside the team
Ministry leaders can submit the public form at{" "}
@@ -704,12 +723,14 @@ export default function AdminGuidePage() {
admins can remove them.
-
+
- 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.
+ Training shows the guide for the signed-in role: the Platform
+ administration guide for admins, the Coordinator guide for
+ coordinators, and the Volunteer guide for volunteers and trainees.
+ The admin and volunteer guides also have downloadable PDFs. These
+ are documentation for this deployment, not editable lessons, so they
+ stay consistent for everyone.
+ Coordinators run the week. You can edit and publish the schedule,
+ handle coverage and swaps, edit run sheets, manage events, author
+ announcements, and use the print and CSV exports. You do not need the
+ Admin tab for any of that.
+
+
+
+
+
+
+
+ The week view is the only editable schedule lens. Month and year are
+ read-only overviews. A week starts as a draft; publishing makes it
+ visible to volunteers and starts the published/reminder mail.
+
+
+
+
+ Open Schedule and use the arrows to reach the week
+ you are building.
+
+
+ Press an empty seat and choose a volunteer. The candidate list is
+ ranked by skills, availability, and conflicts.
+
+
+ Use Auto-fill for a first pass over open seats, then
+ review every suggestion. The ranking does not know the relational
+ context or the last-minute holiday.
+
+
+ Read any conflict before saving. A hard conflict blocks the
+ assignment; a soft warning, such as exceeding a monthly cap, can be
+ overridden.
+
+
+ Press Publish when the week is ready. Publishing
+ makes the schedule visible and queues the published/reminder mail for
+ the people already on it.
+
+
+
+
+ A proposed assignment sends its “Can you serve on …?” email as soon
+ as you create it, even while the week is still a draft. Publishing
+ does not send that email again; it adds the published/reminder mail
+ for seats that are already filled. Draft weeks stay hidden from the
+ volunteer schedule until you publish.
+
+
+
+
+
+
+ Every proposed seat gets an email with three single-use links. The
+ volunteer does not need an account or a login to use them.
+
+
+
+ Links are good for 14 days and work once. If a volunteer says the link
+ expired or was already used, do not forward someone else’s link; ask an
+ admin to help with the account or create the assignment again.
+
+
+
+ The subject reads “Can you serve on [position] — [date]?” and the
+ body shows the service, call time, and location, followed by the
+ three buttons. The same reply buttons also appear on the{" "}
+ /respond page the link opens.
+
+
+
+
+
+
+ Coverage is the working queue for changes. A pending request never
+ removes the volunteer: they stay responsible until you approve a
+ replacement or release the seat.
+
+
+
Handle a swap request
+
+
+ Open Coverage and read the volunteer, seat, date,
+ and reason.
+
+
+ Review the ranked replacements and their warnings. Pick someone who
+ fits the skills and availability, not just the top score.
+
+
+ Choose Approve with replacement to cancel the
+ original assignment and place the replacement as proposed. The new
+ person receives the same accept/decline/propose email.
+
+
+ Choose Approve and release when nobody can take it.
+ The seat becomes open and the original assignment is kept in history.
+
+
+ Choose Decline when the request should not be
+ granted; the original volunteer stays on the seat.
+
+
+
+
+ Volunteers who propose another Sunday
+
+
+ Proposals from the assignment email appear on Coverage under{" "}
+ Proposed another Sunday. The queue is read-only: it
+ records the volunteer, the current date, the proposed date, and any
+ note. Review it, then make the change yourself — assign a replacement,
+ move the seat, or clear it — and confirm the arrangement with the
+ volunteer. The original assignment stays live until you do.
+
+
+
+ Requests from outside the team
+
+
+ Ministry leaders can submit the public form at{" "}
+ /request-coverage without an account. Accepted requests
+ become events: choose Create event to open one with
+ the requester and ministry attached, or Decline if it
+ is not a fit.
+
+
+
+
+
+ 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. Coordinators edit the details and cues; every
+ signed-in volunteer can tick checklist items.
+
+
+
+
+ Open the run sheet from the schedule, Dashboard, or your own
+ next-serve card.
+
+
+ Fill in speaker, message title, stream link, slides link, and team
+ notes, then press Save details.
+
+
+ Edit cues inline and save each row. Add a cue at the bottom when the
+ service needs one.
+
+
+ Add pre-service or post-service checklist items for this service.
+ Defaults are seeded only once, so your edits stick.
+
+
+ Press Print for a clean booth copy.
+
+
+
+
+
+
+ Events cover photoshoots, weddings, outreach nights, and other
+ coverage outside the weekly services. As a coordinator you see every
+ event and can assign photographers and editors; assigned volunteers see
+ only their events.
+
+
+
+
+ Create the event with its date, time, location, and brief, or create
+ one from an accepted outside coverage request.
+
+
+ Assign the photographers and editors. Only assigned people and
+ managers can open the event and its files.
+
+
+ Create folders for originals and edited exports so the handoff is
+ obvious.
+
+
+ After the event, confirm the selects are uploaded and the folder is
+ ready. Archive the event when the work is finished; archived events
+ stay readable but stop accepting uploads.
+
+
+
+
+ Event originals are stored on the configured church media share, not
+ in the database. The Media page is a convenience view and still
+ follows event assignment, so do not treat a copied link as public.
+
+
+
+
+
+
+ Coordinators can write announcements. Training lessons are authored by
+ admins, but everyone can read the published lessons and the guide for
+ their role.
+
+
+
+ Open Announcements and write a title and plain-text
+ message.
+
+
+ Keep Published ticked, or untick it to save a draft.
+
+
+ Use the row actions to publish, unpublish, or delete a post.
+
+
+ Open Training to read the coordinator guide and the
+ published lessons. If a lesson needs a correction, ask an admin.
+
+
+
+
+ Training shows the guide for your role. Admins see the Platform
+ administration guide, coordinators see this guide, and volunteers and
+ trainees see the Volunteer guide.
+
+
+
+
+
+
+
+
+
+
+
+
+ When something looks wrong, note the date and service, take a
+ screenshot, and include the exact error text. That is far more useful
+ than “it didn’t work”.
+
+
+
+ );
+}
diff --git a/src/app/(app)/training/guides/page.tsx b/src/app/(app)/training/guides/page.tsx
new file mode 100644
index 0000000..a1ee175
--- /dev/null
+++ b/src/app/(app)/training/guides/page.tsx
@@ -0,0 +1,12 @@
+import { redirect } from "next/navigation";
+import { auth } from "@/auth/config";
+import type { SystemRole } from "@/auth/roles";
+import { trainingGuideForRole } from "@/lib/training-guides";
+
+/** `/training/guides` opens the guide for the signed-in person's role. */
+export default async function TrainingGuidesPage() {
+ const session = await auth();
+ const role = (session?.user as { systemRole?: SystemRole } | undefined)
+ ?.systemRole;
+ redirect(trainingGuideForRole(role).href);
+}
diff --git a/src/app/(app)/training/guides/user/page.tsx b/src/app/(app)/training/guides/user/page.tsx
index dda6951..93b439b 100644
--- a/src/app/(app)/training/guides/user/page.tsx
+++ b/src/app/(app)/training/guides/user/page.tsx
@@ -128,6 +128,15 @@ export default function VolunteerGuidePage() {
the top for the two things volunteers change most often.
+
+
+ A proposed seat arrives by email with three links:{" "}
+ Confirm, Can’t make it, and{" "}
+ Propose another Sunday. No login is needed and each
+ link works once. If you propose another Sunday, the coordinator sees
+ the request but the seat stays yours until they change it.
+
+
- 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.
+ A week that has not been published does not appear on your schedule.
+ Assigning a seat can still send you a proposed email while the week
+ is a draft, so reply to that email even if the date is not on the
+ schedule yet. Publishing is what makes the week visible and triggers
+ the published and reminder mail.
@@ -258,6 +269,14 @@ export default function VolunteerGuidePage() {
You will see the change on Home once it is resolved.
+
Propose another Sunday
+
+ If you cannot serve the date but could serve a different Sunday, use{" "}
+ Propose another Sunday in the assignment email (or the
+ alternative link on the respond page). Tell the coordinator which date
+ works and why. This does not release the original seat: it stays yours
+ until a coordinator acts on the proposal and confirms the change.
+
Ministry leaders outside the team can request coverage through the
public form at /request-coverage. If you are asked to
@@ -395,24 +414,24 @@ export default function VolunteerGuidePage() {
Open Training from the navigation.
- Read the Volunteer guide once end to end; it covers
- every screen in this app.
+ Read the guide at the top of the page once end to end; it is chosen
+ for your role and covers every screen you can use.
Open an attachment to read or download it. Links open in a new tab so
you do not lose your place.
- Use the PDF download on either guide for an offline copy you can keep
- on your phone.
+ Use the PDF download when the guide offers one, or print the page for
+ an offline copy you can keep on your phone.
diff --git a/src/app/(app)/training/page.tsx b/src/app/(app)/training/page.tsx
index 123957d..9128a98 100644
--- a/src/app/(app)/training/page.tsx
+++ b/src/app/(app)/training/page.tsx
@@ -4,20 +4,36 @@ import { hasPermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { listLessons } from "@/db/training";
import { trainingBodyToHtml } from "@/lib/rich-text";
+import { trainingGuideForRole } from "@/lib/training-guides";
import { TrainingPanel } from "@/components/app/training-panel";
-import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
+import {
+ BookOpenCheck,
+ ClipboardList,
+ Download,
+ ShieldCheck,
+ UserRound,
+} from "lucide-react";
export const metadata = { title: "Training" };
/**
* Training content. Volunteers see published lessons and attachments; admins
- * can author, publish, upload, and delete. Content is stored in Postgres and
+ * can author, publish, upload, and delete. The full guide shown at the top is
+ * chosen from the signed-in person's role. 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 role = (session?.user as { systemRole?: SystemRole } | undefined)
+ ?.systemRole;
const canEdit = hasPermission(role, "training.author");
+ const guide = trainingGuideForRole(role);
+ const GuideIcon =
+ guide.key === "admin"
+ ? ShieldCheck
+ : guide.key === "coordinator"
+ ? ClipboardList
+ : UserRound;
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
(lesson) => ({
...lesson,
@@ -36,67 +52,37 @@ export default async function TrainingPage() {
- Full guides
+ Your guide
- Complete, illustrated walkthroughs with screenshots. Read them here
- or download the PDF for printing and offline use.
+ The complete, illustrated walkthrough for your role. Read it here or
+ download the PDF where one is available.
-
-
-
-
- Admins
-
-
- Platform administration guide
-
-
- People and access, skill verification, positions, services and
- publishing, coverage, run sheets, email, notifications, backups,
- and exports.
-
diff --git a/src/app/api/assignments/[id]/respond/route.ts b/src/app/api/assignments/[id]/respond/route.ts
index e0d0b9f..eb17774 100644
--- a/src/app/api/assignments/[id]/respond/route.ts
+++ b/src/app/api/assignments/[id]/respond/route.ts
@@ -8,11 +8,13 @@ const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
function errorStatus(code: RespondError["code"]): number {
switch (code) {
case "unknown_assignment":
+ case "unknown_instance":
return 404;
case "wrong_volunteer":
return 403;
case "not_actionable":
case "already_used":
+ case "invalid_alternative":
return 409;
}
}
diff --git a/src/app/api/assignments/route.ts b/src/app/api/assignments/route.ts
index 82ea2d3..31591b4 100644
--- a/src/app/api/assignments/route.ts
+++ b/src/app/api/assignments/route.ts
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
import { z } from "zod";
import { and, eq, inArray } from "drizzle-orm";
import { auth } from "@/auth/config";
+import { requestOrigin } from "@/auth/magic-link";
import { AuthError, requirePermission } from "@/auth/permissions";
import type { SystemRole } from "@/auth/roles";
import { db } from "@/db";
@@ -16,8 +17,10 @@ import {
AssignFactError,
resolveAssignFacts,
} from "@/db/assignments";
-import { cancelAssignmentNotifications } from "@/db/outbox";
-import { enqueuePublishNotifications } from "@/db/outbox";
+import {
+ cancelAssignmentNotifications,
+ enqueueAssignmentProposed,
+} from "@/db/outbox";
import { enqueueRemindersForInstance } from "@/db/reminders";
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
import { uuidv7 } from "@/lib/uuid";
@@ -195,6 +198,8 @@ export const POST = async (req: NextRequest) => {
.limit(1);
const assignmentId = uuidv7();
+ const now = new Date();
+ const appOrigin = requestOrigin(req);
await db.transaction(async (tx) => {
await tx.insert(assignments).values({
id: assignmentId,
@@ -203,7 +208,7 @@ export const POST = async (req: NextRequest) => {
status: "proposed",
source: "manual",
assignedBy: actorId,
- assignedAt: new Date(),
+ assignedAt: now,
});
await tx
.update(slots)
@@ -224,12 +229,12 @@ export const POST = async (req: NextRequest) => {
}),
);
- // 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.
+ // The proposed email always goes out, whether the week is draft or
+ // published: the volunteer has to accept, decline, or propose another
+ // Sunday. On a published week only the reminders need topping up.
+ await enqueueAssignmentProposed(tx, assignmentId, { now, appOrigin });
if (instance?.status === "published") {
- await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
- await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
+ await enqueueRemindersForInstance(tx, instance.id, { now, appOrigin });
}
});
diff --git a/src/app/api/dev/magic-link/route.ts b/src/app/api/dev/magic-link/route.ts
index d856765..392a91d 100644
--- a/src/app/api/dev/magic-link/route.ts
+++ b/src/app/api/dev/magic-link/route.ts
@@ -7,6 +7,7 @@ import {
requestOrigin,
} from "@/auth/magic-link";
import { rateLimit } from "@/lib/rate-limit";
+import { hasPasswordProtectedAdmin } from "@/db/users";
const JSON_HEADERS = { "content-type": "application/json" };
const bodySchema = z.object({ email: z.string().email() });
@@ -59,11 +60,29 @@ export const POST = async (req: NextRequest) => {
);
}
+ // Bootstrap only. Once an admin has a real password, a public request for
+ // that admin's email must not mint a session link. New-account and recovery
+ // links are still issued by signed-in admins from the People panel.
+ if (await hasPasswordProtectedAdmin()) {
+ return new Response(
+ JSON.stringify({
+ error:
+ "Use your username and password to sign in. Contact an admin if you need help.",
+ }),
+ { status: 403, headers: JSON_HEADERS },
+ );
+ }
+
try {
const result = await requestMagicLink(parsed.data.email, {
origin: requestOrigin(req),
});
- return new Response(JSON.stringify(result), {
+ // Never expose account metadata to an unauthenticated caller. The dev
+ // transport may still return the URL for local bootstrap/tests; production
+ // turns that transport off and the login UI never renders a URL anyway.
+ const payload: { ok: true; url?: string } = { ok: true };
+ if ("url" in result && result.url) payload.url = result.url;
+ return new Response(JSON.stringify(payload), {
status: 200,
headers: JSON_HEADERS,
});
diff --git a/src/app/api/respond/alternative/route.ts b/src/app/api/respond/alternative/route.ts
new file mode 100644
index 0000000..60fc3ba
--- /dev/null
+++ b/src/app/api/respond/alternative/route.ts
@@ -0,0 +1,110 @@
+import { NextRequest } from "next/server";
+import { z } from "zod";
+import { clientIp } from "@/auth/api";
+import { RespondError, applyAlternativeProposal } 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),
+ instanceId: z.string().min(1),
+ note: z.string().max(500).optional(),
+});
+
+/** Map a refused proposal to its HTTP status. */
+function errorStatus(code: RespondError["code"]): number {
+ switch (code) {
+ case "unknown_assignment":
+ case "unknown_instance":
+ return 404;
+ case "wrong_volunteer":
+ return 403;
+ case "not_actionable":
+ case "already_used":
+ case "invalid_alternative":
+ return 409;
+ }
+}
+
+/**
+ * POST /api/respond/alternative — { token, instanceId, note? }
+ *
+ * The no-login "propose another Sunday" endpoint. The token must be an
+ * `alternative` link; its `jti` is consumed exactly once, so the same email
+ * link cannot file two proposals. The assignment itself is left live for a
+ * coordinator to reassign.
+ */
+export const POST = async (req: NextRequest) => {
+ const parsed = bodySchema.safeParse(await req.json().catch(() => null));
+ if (!parsed.success) {
+ return new Response(
+ JSON.stringify({ error: "a token and service date are required" }),
+ { status: 400, headers: JSON_HEADERS },
+ );
+ }
+
+ const limit = rateLimit(`respond-alternative:${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(parsed.data.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 !== "alternative") {
+ 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 applyAlternativeProposal({
+ assignmentId: payload.assignmentId,
+ userId: payload.userId,
+ jti: payload.jti,
+ proposedInstanceId: parsed.data.instanceId,
+ note: parsed.data.note ?? null,
+ });
+ 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 },
+ );
+ }
+ console.error("[respond-alternative] ERROR", e);
+ return new Response(JSON.stringify({ error: "failed to save the proposal" }), {
+ status: 500,
+ headers: JSON_HEADERS,
+ });
+ }
+};
diff --git a/src/app/api/respond/route.ts b/src/app/api/respond/route.ts
index 8204e73..d515dac 100644
--- a/src/app/api/respond/route.ts
+++ b/src/app/api/respond/route.ts
@@ -17,8 +17,10 @@ function errorStatus(code: RespondError["code"]): number {
switch (code) {
case "already_used":
case "not_actionable":
+ case "invalid_alternative":
return 409;
case "unknown_assignment":
+ case "unknown_instance":
return 404;
case "wrong_volunteer":
return 403;
diff --git a/src/app/login/login-form.tsx b/src/app/login/login-form.tsx
new file mode 100644
index 0000000..f0a0e5d
--- /dev/null
+++ b/src/app/login/login-form.tsx
@@ -0,0 +1,191 @@
+"use client";
+
+import { useState } from "react";
+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";
+
+/**
+ * Sign in with username/password. The email-link form is only available while
+ * the deployment has no password-protected admin (first-run bootstrap). It
+ * never renders a sign-in URL, even when the dev console transport returns one.
+ */
+export function LoginForm({ magicLinkEnabled }: { magicLinkEnabled: boolean }) {
+ const [login, setLogin] = useState("");
+ const [password, setPassword] = useState("");
+ const [passwordStatus, setPasswordStatus] = useState<{
+ kind: "idle" | "signing" | "error";
+ message?: string;
+ }>({ kind: "idle" });
+
+ 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();
+ 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().catch(() => ({}))) as { error?: string };
+ if (res.ok) {
+ setLinkStatus({ kind: "sent" });
+ } else {
+ setLinkStatus({
+ kind: "error",
+ message: body.error ?? "Something went wrong.",
+ });
+ }
+ } catch {
+ setLinkStatus({ kind: "error", message: "Network error." });
+ }
+ }
+
+ return (
+
+
+
+
+ Glenloch Baptist Church
+
+
+ Media Team Hub
+
+
+
+
+ Sign in
+
+ {magicLinkEnabled
+ ? "Use your username and password, or request a one-time email link."
+ : "Sign in with your username and password. Contact a media team admin if you need help."}
+
+
+
+
+
+ {magicLinkEnabled && (
+ <>
+
+
+ or
+
+
+
+
+
+
+ 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.
+
+ >
+ )}
+
+
+
+
+ );
+}
diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx
index a345eda..32827a2 100644
--- a/src/app/login/page.tsx
+++ b/src/app/login/page.tsx
@@ -1,194 +1,13 @@
-"use client";
+import { hasPasswordProtectedAdmin } from "@/db/users";
+import { LoginForm } from "./login-form";
-import { useState } from "react";
-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";
+export const dynamic = "force-dynamic";
/**
- * 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.
+ * Public sign-in. The email-link form is bootstrap-only: once an admin has a
+ * password, anyone who knew that admin's email could otherwise request a full
+ * admin session from this page.
*/
-export default function LoginPage() {
- const [login, setLogin] = useState("");
- const [password, setPassword] = useState("");
- const [passwordStatus, setPasswordStatus] = useState<{
- kind: "idle" | "signing" | "error";
- message?: string;
- }>({ kind: "idle" });
-
- 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();
- 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) {
- setLinkStatus({ kind: "sent", message: body.url });
- } else {
- setLinkStatus({
- kind: "error",
- message: body.error ?? "Something went wrong.",
- });
- }
- } catch {
- setLinkStatus({ kind: "error", message: "Network error." });
- }
- }
-
- return (
-
-
-
-
- Glenloch Baptist Church
-
-
- Media Team Hub
-
-
-
-
- Sign in
-
- Use your username and password, or request a one-time email link.
-
-
-
-
-
-
-
- or
-
-
-
-
-
-
- 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.
-
-
-
-
-
- );
+export default async function LoginPage() {
+ return ;
}
diff --git a/src/app/respond/page.tsx b/src/app/respond/page.tsx
index cc9181a..218e858 100644
--- a/src/app/respond/page.tsx
+++ b/src/app/respond/page.tsx
@@ -1,12 +1,17 @@
-import { getRespondAssignment } from "@/db/respond";
+import {
+ alternativeOptionsForAssignment,
+ getRespondAssignment,
+} from "@/db/respond";
import { verifyRespondToken } from "@/lib/respond";
import { RespondForm } from "@/components/app/respond-form";
+import { AlternativeForm } from "@/components/app/alternative-form";
/**
* Public respond page — unit E4 (ARCHITECTURE §5.6).
*
- * `GET /respond?t=&a=confirm|decline` renders the assignment and the two
- * buttons. It never mutates: the token is consumed only by the form's POST.
+ * `GET /respond?t=` renders the assignment and the action the token was
+ * minted for: confirm/decline, or the "propose another Sunday" form. It never
+ * mutates: the token is consumed only by the form's POST.
*/
export default async function RespondPage({
searchParams,
@@ -41,6 +46,10 @@ export default async function RespondPage({
const alreadyAnswered =
assignment.status === "confirmed" || assignment.status === "declined";
+ const alternatives =
+ payload.action === "alternative" && !alreadyAnswered
+ ? await alternativeOptionsForAssignment(payload.assignmentId)
+ : null;
return (
@@ -60,6 +69,21 @@ export default async function RespondPage({
You already responded — this assignment is {assignment.status}.
diff --git a/src/components/app/training/guide.tsx b/src/components/app/training/guide.tsx
index 5dfae7d..88e4a2d 100644
--- a/src/components/app/training/guide.tsx
+++ b/src/components/app/training/guide.tsx
@@ -26,8 +26,9 @@ export function GuideShell({
title: string;
intro: string;
audience: string;
- pdfHref: string;
- pdfLabel: string;
+ /** Not every role guide has a PDF snapshot yet. */
+ pdfHref?: string;
+ pdfLabel?: string;
sections: GuideSectionLink[];
children: React.ReactNode;
}) {
@@ -43,12 +44,14 @@ export function GuideShell({
All training
-
+ {pdfHref && pdfLabel ? (
+
+ ) : null}
diff --git a/src/db/autoFill.ts b/src/db/autoFill.ts
index dea95f1..2ae366d 100644
--- a/src/db/autoFill.ts
+++ b/src/db/autoFill.ts
@@ -32,6 +32,7 @@ import {
} from "@/db/schema";
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
import { isMentorReady } from "@/domain/mentor";
+import { enqueueAssignmentProposed } from "@/db/outbox";
import { uuidv7 } from "@/lib/uuid";
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
@@ -349,20 +350,23 @@ export async function applyAutoFill(
.limit(1);
if (existing.length > 0) continue;
+ const assignmentId = uuidv7();
+ const now = new Date();
await db.transaction(async (tx) => {
await tx.insert(assignments).values({
- id: uuidv7(),
+ id: assignmentId,
slotId: proposal.slotId,
userId: proposal.userId,
status: "proposed",
source: "auto",
assignedBy: opts.actorId,
- assignedAt: new Date(),
+ assignedAt: now,
});
await tx
.update(slots)
.set({ status: "proposed" })
.where(eq(slots.id, proposal.slotId));
+ await enqueueAssignmentProposed(tx, assignmentId, { now });
});
written++;
}
diff --git a/src/db/coverage.ts b/src/db/coverage.ts
index 0b3a64e..836f095 100644
--- a/src/db/coverage.ts
+++ b/src/db/coverage.ts
@@ -17,9 +17,11 @@
*/
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
+import { alias } from "drizzle-orm/pg-core";
import { db } from "@/db";
import {
assignments,
+ assignmentProposals,
auditLog,
coverageRequests,
roles,
@@ -30,7 +32,10 @@ import {
} from "@/db/schema";
import { auditRow } from "@/db/audit";
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
-import { cancelAssignmentNotifications, enqueuePublishNotifications } from "@/db/outbox";
+import {
+ cancelAssignmentNotifications,
+ enqueueAssignmentProposed,
+} from "@/db/outbox";
import { enqueueRemindersForInstance } from "@/db/reminders";
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
import { uuidv7 } from "@/lib/uuid";
@@ -343,17 +348,71 @@ export async function resolveCoverageRequest(
}),
);
- // A published week's mail was written at publish time; the replacement
- // needs its own rows. Both helpers are idempotent on dedupe_key.
- if (replacementUserId && request.instanceStatus === "published") {
- await enqueuePublishNotifications(tx, request.instanceId, { now });
- await enqueueRemindersForInstance(tx, request.instanceId, { now });
+ // The replacement is a proposed seat, so they get the same accept /
+ // decline / propose-another-Sunday email as any other proposal. A
+ // published week also needs its reminders topped up for the new seat.
+ if (newAssignmentId) {
+ await enqueueAssignmentProposed(tx, newAssignmentId, { now });
+ if (request.instanceStatus === "published") {
+ await enqueueRemindersForInstance(tx, request.instanceId, { now });
+ }
}
});
return { status: "approved", assignmentId: newAssignmentId };
}
+/** A volunteer's "another Sunday" proposal, for the coordinator queue. */
+export interface AlternativeProposalRow {
+ id: string;
+ requesterName: string;
+ requesterEmail: string;
+ roleName: string;
+ serviceName: string;
+ currentStartsAt: Date;
+ proposedStartsAt: Date;
+ note: string | null;
+ createdAt: Date;
+}
+
+/** Pending alternative-date proposals, soonest proposed Sunday first. */
+export async function listPendingAlternativeProposals(): Promise<
+ AlternativeProposalRow[]
+> {
+ const proposedInstance = alias(serviceInstances, "proposed_instance");
+ const rows = await db
+ .select({
+ id: assignmentProposals.id,
+ requesterName: sql`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
+ requesterEmail: users.email,
+ roleName: roles.name,
+ serviceName: services.name,
+ currentStartsAt: serviceInstances.startsAt,
+ proposedStartsAt: proposedInstance.startsAt,
+ note: assignmentProposals.note,
+ createdAt: assignmentProposals.createdAt,
+ })
+ .from(assignmentProposals)
+ .innerJoin(assignments, eq(assignments.id, assignmentProposals.assignmentId))
+ .innerJoin(slots, eq(slots.id, assignments.slotId))
+ .innerJoin(roles, eq(roles.id, slots.roleId))
+ .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
+ .innerJoin(services, eq(services.id, serviceInstances.serviceId))
+ .innerJoin(
+ proposedInstance,
+ eq(proposedInstance.id, assignmentProposals.proposedInstanceId),
+ )
+ .innerJoin(users, eq(users.id, assignmentProposals.userId))
+ .where(eq(assignmentProposals.status, "pending"))
+ .orderBy(asc(proposedInstance.startsAt), asc(users.lastName));
+
+ return rows.map((row) => ({
+ ...row,
+ currentStartsAt: row.currentStartsAt ?? new Date(0),
+ proposedStartsAt: row.proposedStartsAt ?? new Date(0),
+ }));
+}
+
/* ------------------------------------------------------------------ utils */
function auditLogRow(actorId: string, requestId: string, status: string) {
diff --git a/src/db/instances.ts b/src/db/instances.ts
index fcad9f6..42216ed 100644
--- a/src/db/instances.ts
+++ b/src/db/instances.ts
@@ -11,13 +11,17 @@
* - a `published` instance is never modified here,
* - past instances fall outside the window and are never deleted.
*
- * Slot materialization from role requirements is D3; this unit only owns the
- * instance rows.
+ * Each new instance's seats are materialized immediately via D3's
+ * `materializeSlotsForInstance`, so a generated week is assignable without
+ * waiting for the separate slot cron. Seat creation is idempotent per
+ * (instance, role, seat), so re-runs remain no-ops.
*/
import { and, count, eq, gte } from "drizzle-orm";
import { db } from "@/db";
-import { services, serviceInstances } from "@/db/schema";
+import { roles, services, serviceInstances } from "@/db/schema";
+import { materializeSlotsForInstance } from "@/db/slots";
+import type { RolePlanInput } from "@/domain/slots";
import { uuidv7 } from "@/lib/uuid";
import { localToUtc } from "@/lib/tz";
import {
@@ -52,6 +56,13 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise ({
+ id: role.id,
+ callTimeOffsetMinutes: role.callTimeOffsetMinutes,
+ defaultHeadcount: role.defaultHeadcount,
+ }));
+
let created = 0;
for (const service of active) {
const plan: ServicePlanInput = {
@@ -78,7 +89,12 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise {
+ if (!row.startsAt) throw new Error("assignment has no start time");
+ const timeZone = row.timeZone;
+ const occursOnLabel = formatInTimezone(row.startsAt, timeZone, {
+ timeZone,
+ weekday: "long",
+ month: "short",
+ day: "numeric",
+ });
+ const startTimeLabel = formatInTimezone(row.startsAt, timeZone, {
+ timeZone,
+ hour: "numeric",
+ minute: "2-digit",
+ });
+ const callTimeLabel = row.callTime
+ ? formatInTimezone(row.callTime, timeZone, {
+ timeZone,
+ hour: "numeric",
+ minute: "2-digit",
+ })
+ : null;
+
+ const confirm = await signRespondToken({
+ assignmentId: row.assignmentId,
+ userId: row.userId,
+ action: "confirm",
+ });
+ const decline = await signRespondToken({
+ assignmentId: row.assignmentId,
+ userId: row.userId,
+ action: "decline",
+ });
+ const alternative = includeAlternative
+ ? await signRespondToken({
+ assignmentId: row.assignmentId,
+ userId: row.userId,
+ action: "alternative",
+ })
+ : null;
+
+ const confirmUrl = respondUrl(origin, confirm.token, "confirm");
+ const declineUrl = respondUrl(origin, decline.token, "decline");
+ const alternativeUrl = alternative
+ ? respondUrl(origin, alternative.token, "alternative")
+ : null;
+
+ const ctx = {
+ volunteerFirstName: row.firstName,
+ roleName: row.roleName,
+ serviceName: row.serviceName,
+ occursOnLabel,
+ startTimeLabel,
+ callTimeLabel,
+ location: row.location ?? row.serviceName,
+ confirmUrl,
+ declineUrl,
+ };
+ const rendered = alternativeUrl
+ ? renderAssignmentProposedEmail({ ...ctx, alternativeUrl })
+ : renderAssignmentPublishedEmail(ctx);
+
+ return { ...rendered, confirmUrl, declineUrl, alternativeUrl };
+}
+
+/**
+ * Enqueue the `assignment.proposed` email for one new assignment. The seat is
+ * proposed, not confirmed, so the volunteer is asked to accept, decline, or
+ * propose another Sunday. Draft and published weeks both get this email: a
+ * proposed seat always needs a response. Idempotent per assignment.
+ */
+export async function enqueueAssignmentProposed(
+ executor: OutboxDb,
+ assignmentId: string,
+ opts: { now?: Date; appOrigin?: string } = {},
+): Promise {
+ const now = opts.now ?? new Date();
+ const origin = opts.appOrigin ?? APP_ORIGIN;
+
+ const [row] = await executor
+ .select({
+ assignmentId: assignments.id,
+ slotId: assignments.slotId,
+ userId: users.id,
+ email: users.email,
+ firstName: users.firstName,
+ timeZone: users.timezone,
+ roleName: roles.name,
+ serviceName: services.name,
+ location: services.location,
+ startsAt: serviceInstances.startsAt,
+ callTime: slots.callTime,
+ })
+ .from(assignments)
+ .innerJoin(slots, eq(slots.id, assignments.slotId))
+ .innerJoin(roles, eq(roles.id, slots.roleId))
+ .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
+ .innerJoin(services, eq(services.id, serviceInstances.serviceId))
+ .innerJoin(users, eq(users.id, assignments.userId))
+ .where(eq(assignments.id, assignmentId))
+ .limit(1);
+ if (!row?.startsAt) return 0;
+
+ const email = await buildAssignmentEmail(row, origin, true);
+ const inserted = await executor
+ .insert(notifications)
+ .values({
+ id: uuidv7(),
+ userId: row.userId,
+ channel: "email",
+ templateKey: "assignment.proposed",
+ ruleKey: null,
+ assignmentId: row.assignmentId,
+ slotId: row.slotId,
+ toAddress: row.email,
+ payloadJson: JSON.stringify({
+ subject: email.subject,
+ html: email.html,
+ text: email.text,
+ confirmUrl: email.confirmUrl,
+ declineUrl: email.declineUrl,
+ alternativeUrl: email.alternativeUrl,
+ }),
+ dedupeKey: notificationDedupeKey(
+ "assignment.proposed",
+ row.assignmentId,
+ "email",
+ ),
+ scheduledFor: now,
+ status: "queued",
+ attempts: 0,
+ createdAt: now,
+ })
+ .onConflictDoNothing({ target: notifications.dedupeKey })
+ .returning({ id: notifications.id });
+
+ return inserted.length;
+}
+
/**
* Cancel an assignment's pending mail — a declined assignment must not keep a
* "you're serving" reminder queued (§6.1 `cancel-if-declined`). Sent rows are
diff --git a/src/db/respond.ts b/src/db/respond.ts
index 9f41b36..c0f061f 100644
--- a/src/db/respond.ts
+++ b/src/db/respond.ts
@@ -8,10 +8,11 @@
* and writes the audit row — all in one transaction.
*/
-import { eq } from "drizzle-orm";
+import { and, asc, eq, gt, ne } from "drizzle-orm";
import { db } from "@/db";
import {
assignments,
+ assignmentProposals,
auditLog,
roles,
serviceInstances,
@@ -23,8 +24,9 @@ import {
} from "@/db/schema";
import { auditRow } from "@/db/audit";
import { cancelAssignmentNotifications } from "@/db/outbox";
-import type { RespondAction } from "@/lib/respond";
+import type { DecisionAction } from "@/lib/respond";
import { formatInTimezone } from "@/lib/tz";
+import { uuidv7 } from "@/lib/uuid";
/** Only a live assignment can be confirmed or declined. */
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
@@ -33,7 +35,9 @@ export type RespondFailureCode =
| "unknown_assignment"
| "wrong_volunteer"
| "not_actionable"
- | "already_used";
+ | "already_used"
+ | "unknown_instance"
+ | "invalid_alternative";
export class RespondError extends Error {
readonly code: RespondFailureCode;
@@ -124,7 +128,7 @@ export async function getRespondAssignment(
export async function respondToAssignment(input: {
assignmentId: string;
userId: string;
- action: RespondAction;
+ action: DecisionAction;
via?: ConfirmedVia;
now?: Date;
}): Promise<{ status: "confirmed" | "declined" }> {
@@ -209,7 +213,7 @@ export async function respondToAssignment(input: {
export async function applyRespond(input: {
assignmentId: string;
userId: string;
- action: RespondAction;
+ action: DecisionAction;
jti: string;
now?: Date;
}): Promise<{ status: "confirmed" | "declined" }> {
@@ -301,3 +305,196 @@ export async function applyRespond(input: {
return result;
}
+
+export interface AlternativeOption {
+ id: string;
+ startsAt: Date;
+ label: string;
+}
+
+/**
+ * Upcoming instances of the same service after the seat's own date — the
+ * choices behind "propose another Sunday". Null when the assignment or its
+ * start time is unknown.
+ */
+export async function alternativeOptionsForAssignment(
+ assignmentId: string,
+): Promise {
+ const [current] = await db
+ .select({
+ instanceId: serviceInstances.id,
+ serviceId: serviceInstances.serviceId,
+ startsAt: serviceInstances.startsAt,
+ timeZone: users.timezone,
+ })
+ .from(assignments)
+ .innerJoin(slots, eq(slots.id, assignments.slotId))
+ .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
+ .innerJoin(users, eq(users.id, assignments.userId))
+ .where(eq(assignments.id, assignmentId))
+ .limit(1);
+ if (!current?.startsAt) return null;
+
+ const rows = await db
+ .select({ id: serviceInstances.id, startsAt: serviceInstances.startsAt })
+ .from(serviceInstances)
+ .where(
+ and(
+ eq(serviceInstances.serviceId, current.serviceId),
+ gt(serviceInstances.startsAt, current.startsAt),
+ ne(serviceInstances.id, current.instanceId),
+ ),
+ )
+ .orderBy(asc(serviceInstances.startsAt))
+ .limit(24);
+
+ return rows
+ .filter(
+ (row): row is { id: string; startsAt: Date } => row.startsAt != null,
+ )
+ .map((row) => ({
+ id: row.id,
+ startsAt: row.startsAt,
+ label: formatInTimezone(row.startsAt, current.timeZone, {
+ timeZone: current.timeZone,
+ weekday: "long",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ }),
+ }));
+}
+
+/**
+ * Record "I can't serve that Sunday, but I can serve this one." The assignment
+ * is left live (like a coverage request) until a coordinator acts; the token is
+ * consumed exactly once in the same transaction as the proposal.
+ */
+export async function applyAlternativeProposal(input: {
+ assignmentId: string;
+ userId: string;
+ jti: string;
+ proposedInstanceId: string;
+ note?: string | null;
+ now?: Date;
+}): Promise<{ proposalId: string; proposedInstanceId: string }> {
+ const now = input.now ?? new Date();
+ const proposalId = uuidv7();
+
+ return db.transaction(async (tx) => {
+ const consumed = await tx
+ .insert(usedTokens)
+ .values({
+ jti: input.jti,
+ assignmentId: input.assignmentId,
+ action: "alternative",
+ usedAt: now,
+ })
+ .onConflictDoNothing({ target: usedTokens.jti })
+ .returning({ jti: usedTokens.jti });
+ if (consumed.length === 0) {
+ throw new RespondError("already_used", "this link has already been used");
+ }
+
+ const [assignment] = await tx
+ .select({
+ userId: assignments.userId,
+ status: assignments.status,
+ instanceId: serviceInstances.id,
+ serviceId: serviceInstances.serviceId,
+ startsAt: serviceInstances.startsAt,
+ })
+ .from(assignments)
+ .innerJoin(slots, eq(slots.id, assignments.slotId))
+ .innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
+ .where(eq(assignments.id, input.assignmentId))
+ .limit(1);
+ if (!assignment) {
+ throw new RespondError("unknown_assignment", "unknown assignment");
+ }
+ if (assignment.userId !== input.userId) {
+ throw new RespondError(
+ "wrong_volunteer",
+ "this link is not for this volunteer",
+ );
+ }
+ if (!ACTIONABLE_STATUSES.has(assignment.status)) {
+ throw new RespondError(
+ "not_actionable",
+ `assignment is already ${assignment.status}`,
+ );
+ }
+
+ const [proposed] = await tx
+ .select({
+ id: serviceInstances.id,
+ serviceId: serviceInstances.serviceId,
+ startsAt: serviceInstances.startsAt,
+ })
+ .from(serviceInstances)
+ .where(eq(serviceInstances.id, input.proposedInstanceId))
+ .limit(1);
+ if (!proposed) {
+ throw new RespondError("unknown_instance", "that service date was not found");
+ }
+ if (proposed.serviceId !== assignment.serviceId) {
+ throw new RespondError(
+ "invalid_alternative",
+ "choose another date for this service",
+ );
+ }
+ if (
+ !proposed.startsAt ||
+ !assignment.startsAt ||
+ proposed.id === assignment.instanceId ||
+ proposed.startsAt <= assignment.startsAt ||
+ proposed.startsAt <= now
+ ) {
+ throw new RespondError("invalid_alternative", "choose a later service date");
+ }
+
+ try {
+ await tx.insert(assignmentProposals).values({
+ id: proposalId,
+ assignmentId: input.assignmentId,
+ userId: input.userId,
+ proposedInstanceId: proposed.id,
+ note: input.note?.trim() || null,
+ status: "pending",
+ createdAt: now,
+ });
+ } catch (err) {
+ if (sqlState(err) === "23505") {
+ throw new RespondError(
+ "invalid_alternative",
+ "you already proposed another Sunday for this assignment",
+ );
+ }
+ throw err;
+ }
+
+ await tx.insert(auditLog).values(
+ auditRow({
+ actorId: input.userId,
+ action: "assignment.alternative_proposed",
+ entityType: "assignment",
+ entityId: input.assignmentId,
+ after: { proposedInstanceId: proposed.id },
+ now,
+ }),
+ );
+
+ return { proposalId, proposedInstanceId: proposed.id };
+ });
+}
+
+/** Walk an error's cause chain to its SQLSTATE. */
+function sqlState(err: unknown): string | undefined {
+ let node = err as { code?: string; cause?: unknown } | null;
+ while (node) {
+ if (node.code) return node.code;
+ node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
+ }
+ return undefined;
+}
diff --git a/src/db/schema.ts b/src/db/schema.ts
index 607a45a..a0cfb88 100644
--- a/src/db/schema.ts
+++ b/src/db/schema.ts
@@ -1249,6 +1249,53 @@ export const coverageRequests = pgTable(
],
);
+/* ------------------------------- assignment alternative-date proposals */
+
+export const ASSIGNMENT_PROPOSAL_STATUSES = [
+ "pending",
+ "accepted",
+ "declined",
+] as const;
+export type AssignmentProposalStatus =
+ (typeof ASSIGNMENT_PROPOSAL_STATUSES)[number];
+
+/**
+ * A volunteer's answer to a proposed seat when they cannot serve that date but
+ * can serve another Sunday. The assignment stays live (like a coverage
+ * request) until a coordinator acts, so a proposal never silently opens a hole
+ * in the schedule.
+ *
+ * At most one pending proposal per assignment; resolved rows remain history.
+ */
+export const assignmentProposals = pgTable(
+ "assignment_proposals",
+ {
+ id: text("id").primaryKey(),
+ assignmentId: text("assignment_id")
+ .notNull()
+ .references(() => assignments.id, { onDelete: "cascade" }),
+ userId: text("user_id")
+ .notNull()
+ .references(() => users.id, { onDelete: "restrict" }),
+ proposedInstanceId: text("proposed_instance_id")
+ .notNull()
+ .references(() => serviceInstances.id, { onDelete: "cascade" }),
+ note: text("note"),
+ status: text("status", { enum: ASSIGNMENT_PROPOSAL_STATUSES })
+ .notNull()
+ .default("pending"),
+ createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
+ .notNull()
+ .defaultNow(),
+ },
+ (table) => [
+ uniqueIndex("assignment_proposals_pending_assignment_idx")
+ .on(table.assignmentId)
+ .where(sql`${table.status} = 'pending'`),
+ index("assignment_proposals_status_idx").on(table.status, table.createdAt),
+ ],
+);
+
/* ------------------------------------------------------------ run sheet */
/**
@@ -1488,6 +1535,7 @@ export const schema = {
eventVideos,
announcements,
coverageRequests,
+ assignmentProposals,
serviceRunSheets,
runSheetItems,
serviceChecklistItems,
diff --git a/src/db/slots.ts b/src/db/slots.ts
index b660596..08b44f9 100644
--- a/src/db/slots.ts
+++ b/src/db/slots.ts
@@ -6,11 +6,13 @@
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
* assignments on an existing seat.
*
- * Per §5.1, slots are created only for non-published instances: a published
- * week's slot set is owned by the publish flow, not the generator.
+ * Per §5.1, a published week's slot set is owned by the publish flow, so
+ * existing seats are never touched. The one exception is a published instance
+ * with zero seats: that week was published before any seats existed and can
+ * never become assignable unless the generator repairs it.
*/
-import { and, gte, ne } from "drizzle-orm";
+import { eq, gte, sql } from "drizzle-orm";
import { db } from "@/db";
import { roles, serviceInstances, slots } from "@/db/schema";
import { uuidv7 } from "@/lib/uuid";
@@ -55,22 +57,33 @@ export async function materializeSlotsForInstance(
}
/**
- * Materialize slots for every non-published instance at or after `now`.
- * Published instances are left untouched (their slot set is owned by the
- * publish flow).
+ * Materialize seats for every instance at or after `now`. A published instance
+ * with existing seats is left untouched (its slot set is owned by the publish
+ * flow), but a published instance with no seats at all is repaired — otherwise
+ * it stays permanently unassignable.
*/
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
const reference = now ?? new Date();
const instances = await db
- .select()
+ .select({
+ id: serviceInstances.id,
+ startsAt: serviceInstances.startsAt,
+ status: serviceInstances.status,
+ seatCount: sql`count(${slots.id})`,
+ })
.from(serviceInstances)
- .where(
- and(
- gte(serviceInstances.startsAt, reference),
- ne(serviceInstances.status, "published"),
- ),
+ .leftJoin(slots, eq(slots.serviceInstanceId, serviceInstances.id))
+ .where(gte(serviceInstances.startsAt, reference))
+ .groupBy(
+ serviceInstances.id,
+ serviceInstances.startsAt,
+ serviceInstances.status,
);
+ const target = instances.filter(
+ (inst) => inst.status !== "published" || Number(inst.seatCount) === 0,
+ );
+
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
id: r.id,
@@ -79,10 +92,10 @@ export async function materializeSlots(now?: Date): Promise<{ created: number; i
}));
let created = 0;
- for (const inst of instances) {
+ for (const inst of target) {
if (!inst.startsAt) continue;
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
}
- return { created, instances: instances.length };
+ return { created, instances: target.length };
}
diff --git a/src/db/users.ts b/src/db/users.ts
index 72e9141..c14fc7b 100644
--- a/src/db/users.ts
+++ b/src/db/users.ts
@@ -9,7 +9,7 @@
* patch that omits a field (say, the phone) never nulls it out.
*/
-import { and, asc, eq, isNull, ne, or, sql } from "drizzle-orm";
+import { and, asc, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
import { db } from "@/db";
import { assignments, userSkills, users } from "@/db/schema";
import type { SystemRole } from "@/auth/roles";
@@ -197,6 +197,26 @@ export async function hasAssignmentHistory(userId: string): Promise {
return Boolean(row);
}
+/**
+ * Whether any admin has real credentials. Once this is true, public
+ * magic-link sign-in is closed: anyone who knew an admin's email could
+ * otherwise mint a full admin session from the login page. New-account and
+ * recovery links remain available to signed-in admins.
+ */
+export async function hasPasswordProtectedAdmin(): Promise {
+ const [row] = await db
+ .select({ id: users.id })
+ .from(users)
+ .where(
+ and(
+ eq(users.systemRole, "admin"),
+ isNotNull(users.passwordHash),
+ ),
+ )
+ .limit(1);
+ return Boolean(row);
+}
+
/** Active admins who could still sign in, excluding the person being changed. */
export async function countOtherActiveAdmins(excludeUserId: string): Promise {
const [row] = await db
diff --git a/src/domain/templates.test.ts b/src/domain/templates.test.ts
index bad5029..64a0221 100644
--- a/src/domain/templates.test.ts
+++ b/src/domain/templates.test.ts
@@ -1,5 +1,9 @@
import { describe, it, expect } from "vitest";
-import { escapeHtml, renderAssignmentPublishedEmail } from "./templates";
+import {
+ escapeHtml,
+ renderAssignmentProposedEmail,
+ renderAssignmentPublishedEmail,
+} from "./templates";
/**
* E3 — email templates.
@@ -56,6 +60,25 @@ describe("renderAssignmentPublishedEmail", () => {
});
});
+describe("renderAssignmentProposedEmail", () => {
+ const proposed = {
+ ...ctx,
+ alternativeUrl: "https://media.test/respond?t=abc&a=alternative",
+ };
+
+ it("asks for a response and offers all three links", () => {
+ const { subject } = renderAssignmentProposedEmail(proposed);
+ expect(subject).toBe("Can you serve on Slides — Sunday, Nov 22?");
+ const { html, text } = renderAssignmentProposedEmail(proposed);
+ expect(html).toContain("a=confirm");
+ expect(html).toContain("a=decline");
+ expect(html).toContain("a=alternative");
+ expect(html).toContain("Propose another Sunday");
+ expect(html).toContain("can you serve on Slides?");
+ expect(text).toContain("Propose another Sunday: ");
+ });
+});
+
describe("escapeHtml", () => {
it("escapes the five HTML-significant characters", () => {
expect(escapeHtml(`&<>"'`)).toBe("&<>"'");
diff --git a/src/domain/templates.ts b/src/domain/templates.ts
index ff03bdd..5a3b520 100644
--- a/src/domain/templates.ts
+++ b/src/domain/templates.ts
@@ -24,6 +24,8 @@ export interface AssignmentEmailContext {
location: string;
confirmUrl: string;
declineUrl: string;
+ /** Present on the proposed email: "I can serve another Sunday". */
+ alternativeUrl?: string;
}
export interface RenderedEmail {
@@ -51,6 +53,21 @@ export function renderAssignmentPublishedEmail(
return renderAssignmentEmail(ctx, `You're on ${ctx.roleName} — ${ctx.occursOnLabel}`);
}
+/**
+ * The assignment.proposed email: the seat is not confirmed until the volunteer
+ * responds, so it offers all three choices — accept, decline, or propose a
+ * different Sunday.
+ */
+export function renderAssignmentProposedEmail(
+ ctx: AssignmentEmailContext & { alternativeUrl: string },
+): RenderedEmail {
+ return renderAssignmentEmail(
+ ctx,
+ `Can you serve on ${ctx.roleName} — ${ctx.occursOnLabel}?`,
+ true,
+ );
+}
+
/** A reminder for the same assignment (E7): same body, reminder subject. */
export function renderAssignmentReminderEmail(
ctx: AssignmentEmailContext,
@@ -136,6 +153,7 @@ export function renderEventReminderEmail(
function renderAssignmentEmail(
ctx: AssignmentEmailContext,
subject: string,
+ proposed = false,
): RenderedEmail {
const callTime = ctx.callTimeLabel ?? CALL_TIME_UNSET;
const firstName = escapeHtml(ctx.volunteerFirstName);
@@ -147,11 +165,14 @@ function renderAssignmentEmail(
const location = escapeHtml(ctx.location);
const confirmUrl = escapeHtml(ctx.confirmUrl);
const declineUrl = escapeHtml(ctx.declineUrl);
+ const alternativeUrl = ctx.alternativeUrl
+ ? escapeHtml(ctx.alternativeUrl)
+ : null;
const html = `
-
${firstName}, you're on ${roleName}
+
${firstName}, ${proposed ? `can you serve on ${roleName}?` : `you're on ${roleName}`}
${serviceName}
${occursOn} at ${startTime}
@@ -162,17 +183,21 @@ function renderAssignmentEmail(
ConfirmCan't make it
+ ${alternativeUrl ? `Propose another Sunday` : ""}
No login needed — the links above are single-use. If you can't serve,
- please decline so a coordinator can find cover.
+ please decline so a coordinator can find cover, or propose another
+ Sunday you are available.
Media Team Hub · Glenloch
`;
const text = [
- `${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
+ proposed
+ ? `${ctx.volunteerFirstName}, can you serve on ${ctx.roleName}?`
+ : `${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
"",
ctx.serviceName,
`${ctx.occursOnLabel} at ${ctx.startTimeLabel}`,
@@ -181,6 +206,9 @@ function renderAssignmentEmail(
"",
"Confirm: " + ctx.confirmUrl,
"Can't make it: " + ctx.declineUrl,
+ ...(ctx.alternativeUrl
+ ? ["Propose another Sunday: " + ctx.alternativeUrl]
+ : []),
"",
"No login needed — the links are single-use.",
].join("\n");
diff --git a/src/lib/respond.test.ts b/src/lib/respond.test.ts
index 066726a..11c318d 100644
--- a/src/lib/respond.test.ts
+++ b/src/lib/respond.test.ts
@@ -42,4 +42,18 @@ describe("respond tokens", () => {
expect(url.startsWith("https://media.test/respond?t=")).toBe(true);
expect(url.endsWith("&a=decline")).toBe(true);
});
+
+ it("accepts the alternative-Sunday action", async () => {
+ const { token } = await signRespondToken({
+ ...input,
+ action: "alternative",
+ });
+ const payload = await verifyRespondToken(token);
+ expect(payload?.action).toBe("alternative");
+ expect(
+ respondUrl("https://media.test", token, "alternative").endsWith(
+ "&a=alternative",
+ ),
+ ).toBe(true);
+ });
});
diff --git a/src/lib/respond.ts b/src/lib/respond.ts
index 6cb0a0f..ff18b26 100644
--- a/src/lib/respond.ts
+++ b/src/lib/respond.ts
@@ -1,11 +1,13 @@
/**
* Signed respond tokens — unit E4 (ARCHITECTURE §5.6).
*
- * Every assignment email carries two single-purpose links:
- * /respond?t=&a=confirm | /respond?t=&a=decline
+ * Every assignment email carries single-purpose links:
+ * /respond?t=&a=confirm | &a=decline | &a=alternative
*
* The JWT binds the assignment and volunteer (`{ assignmentId, userId, action,
* jti }`, HS256, +14d) so a link cannot be re-pointed at another assignment.
+ * `alternative` opens the "propose another Sunday" page; it never changes the
+ * assignment, it records a proposal for a coordinator.
* Single use is recorded by `jti` in `used_tokens` by the data layer.
*/
@@ -19,7 +21,8 @@ const SECRET = new TextEncoder().encode(
"media-team-hub-dev-insecure-secret",
);
-export type RespondAction = "confirm" | "decline";
+export type DecisionAction = "confirm" | "decline";
+export type RespondAction = DecisionAction | "alternative";
export interface RespondTokenPayload {
assignmentId: string;
@@ -66,7 +69,7 @@ export async function verifyRespondToken(
if (
typeof assignmentId !== "string" ||
typeof userId !== "string" ||
- (action !== "confirm" && action !== "decline") ||
+ (action !== "confirm" && action !== "decline" && action !== "alternative") ||
typeof jti !== "string"
) {
return null;
diff --git a/src/lib/training-guides.test.ts b/src/lib/training-guides.test.ts
new file mode 100644
index 0000000..cd2a290
--- /dev/null
+++ b/src/lib/training-guides.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+import { trainingGuideForRole } from "./training-guides";
+
+describe("trainingGuideForRole", () => {
+ it("shows the administration guide to admins", () => {
+ expect(trainingGuideForRole("admin").key).toBe("admin");
+ });
+
+ it("shows the coordinator guide to coordinators", () => {
+ expect(trainingGuideForRole("coordinator").key).toBe("coordinator");
+ });
+
+ it("shows the volunteer guide to volunteers and trainees", () => {
+ expect(trainingGuideForRole("volunteer").key).toBe("user");
+ expect(trainingGuideForRole("trainee").key).toBe("user");
+ });
+
+ it("falls back to the volunteer guide without a role", () => {
+ expect(trainingGuideForRole(null).key).toBe("user");
+ expect(trainingGuideForRole(undefined).key).toBe("user");
+ });
+});
diff --git a/src/lib/training-guides.ts b/src/lib/training-guides.ts
new file mode 100644
index 0000000..6ac60b8
--- /dev/null
+++ b/src/lib/training-guides.ts
@@ -0,0 +1,56 @@
+import type { SystemRole } from "@/auth/roles";
+
+export type TrainingGuideKey = "admin" | "coordinator" | "user";
+
+export interface TrainingGuide {
+ key: TrainingGuideKey;
+ href: string;
+ title: string;
+ audience: string;
+ description: string;
+ /** Not every guide has a PDF snapshot yet. */
+ pdfHref?: string;
+ pdfLabel?: string;
+}
+
+export const TRAINING_GUIDES: Record = {
+ admin: {
+ key: "admin",
+ href: "/training/guides/admin",
+ title: "Platform administration guide",
+ audience: "Admins",
+ description:
+ "People and access, skill verification, positions, services and publishing, coverage, run sheets, email, notifications, backups, and exports.",
+ pdfHref: "/training/media-team-admin-guide.pdf",
+ pdfLabel: "Download admin PDF",
+ },
+ coordinator: {
+ key: "coordinator",
+ href: "/training/guides/coordinator",
+ title: "Coordinator guide",
+ audience: "Coordinators",
+ description:
+ "Building and publishing weeks, assignment replies, coverage and swaps, run sheets, events, announcements, and exports.",
+ pdfHref: "/training/media-team-coordinator-guide.pdf",
+ pdfLabel: "Download coordinator PDF",
+ },
+ user: {
+ key: "user",
+ href: "/training/guides/user",
+ title: "Volunteer guide",
+ audience: "Volunteers and trainees",
+ description:
+ "Signing in, your next serve, the schedule, availability, swaps, run sheets, events and media, training, profile, and reminders.",
+ pdfHref: "/training/media-team-user-guide.pdf",
+ pdfLabel: "Download volunteer PDF",
+ },
+};
+
+/** Admins get the admin guide, coordinators theirs, everyone else the volunteer guide. */
+export function trainingGuideForRole(
+ role: SystemRole | null | undefined,
+): TrainingGuide {
+ if (role === "admin") return TRAINING_GUIDES.admin;
+ if (role === "coordinator") return TRAINING_GUIDES.coordinator;
+ return TRAINING_GUIDES.user;
+}