Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f75178de69 |
@@ -123,7 +123,7 @@ curl -fsS http://localhost:3000/api/health # dashboard
|
|||||||
curl -fsS http://localhost:8787/api/health # advanced editor
|
curl -fsS http://localhost:8787/api/health # advanced editor
|
||||||
```
|
```
|
||||||
|
|
||||||
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link prints it in the app log:
|
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose logs -f app
|
docker compose logs -f app
|
||||||
@@ -265,7 +265,7 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.
|
|||||||
| `APP_ORIGIN` | Fallback application origin. |
|
| `APP_ORIGIN` | Fallback application origin. |
|
||||||
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
|
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
|
||||||
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
|
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
|
||||||
| `MAGIC_LINK_DEV_TRANSPORT` | Returns/prints the sign-in link instead of emailing it; the login page never displays it. Defaults on outside production; compose sets `true` for first login. |
|
| `MAGIC_LINK_DEV_TRANSPORT` | Shows/prints the sign-in link instead of emailing it. Defaults on outside production; compose sets `true` for first login. |
|
||||||
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
|
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
|
||||||
| `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. |
|
| `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. |
|
||||||
| `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. |
|
| `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. |
|
||||||
@@ -470,7 +470,7 @@ Keep the app on loopback and use an SSH tunnel for this step:
|
|||||||
ssh -L 3000:127.0.0.1:3000 you@media.example.org
|
ssh -L 3000:127.0.0.1:3000 you@media.example.org
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from `docker compose logs app`. Then:
|
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from the page or from `docker compose logs app`. Then:
|
||||||
|
|
||||||
1. Admin → People: change the admin name and email to the real person, and create real accounts.
|
1. Admin → People: change the admin name and email to the real person, and create real accounts.
|
||||||
2. Admin → Services: set real service times, roles, and headcounts.
|
2. Admin → Services: set real service times, roles, and headcounts.
|
||||||
@@ -483,7 +483,7 @@ Only after that, set `MAGIC_LINK_DEV_TRANSPORT=false` in `.env` and restart:
|
|||||||
docker compose up -d app
|
docker compose up -d app
|
||||||
```
|
```
|
||||||
|
|
||||||
**Do not expose the app publicly while the dev transport is on:** it can return and log sign-in links during bootstrap. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
|
**Do not expose the app publicly while the dev transport is on:** it displays sign-in links in the browser. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
|
||||||
|
|
||||||
### 6. Reverse proxy and TLS with Caddy
|
### 6. Reverse proxy and TLS with Caddy
|
||||||
|
|
||||||
|
|||||||
@@ -91,25 +91,6 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# Notification dispatcher. The app only queues mail in the outbox; this loop
|
|
||||||
# drains it through the CRON_SECRET endpoint, so assignment, publish and
|
|
||||||
# reminder emails go out without anyone pressing a button.
|
|
||||||
cron:
|
|
||||||
image: curlimages/curl:8.10.1
|
|
||||||
environment:
|
|
||||||
CRON_SECRET: ${CRON_SECRET:-}
|
|
||||||
depends_on:
|
|
||||||
app:
|
|
||||||
condition: service_healthy
|
|
||||||
entrypoint: ["sh", "-c"]
|
|
||||||
command:
|
|
||||||
- 'while true; do echo "cron tick"; curl -fsS --max-time 30 -H "Authorization: Bearer $$CRON_SECRET" http://app:3000/api/dev/cron/notifications || echo "notification tick failed"; echo; sleep 60; done'
|
|
||||||
restart: unless-stopped
|
|
||||||
logging:
|
|
||||||
options:
|
|
||||||
max-size: "10m"
|
|
||||||
max-file: "3"
|
|
||||||
|
|
||||||
# Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone
|
# Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone
|
||||||
# and one `docker compose up -d --build` deploys both apps. Its catalog is
|
# and one `docker compose up -d --build` deploys both apps. Its catalog is
|
||||||
# temporary bridge data; originals stay on the app's media storage.
|
# temporary bridge data; originals stay on the app's media storage.
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
CREATE TABLE "assignment_proposals" (
|
|
||||||
"id" text PRIMARY KEY NOT NULL,
|
|
||||||
"assignment_id" text NOT NULL,
|
|
||||||
"user_id" text NOT NULL,
|
|
||||||
"proposed_instance_id" text NOT NULL,
|
|
||||||
"note" text,
|
|
||||||
"status" text DEFAULT 'pending' NOT NULL,
|
|
||||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
|
||||||
);
|
|
||||||
--> statement-breakpoint
|
|
||||||
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_assignment_id_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
|
||||||
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
|
||||||
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_proposed_instance_id_service_instances_id_fk" FOREIGN KEY ("proposed_instance_id") REFERENCES "public"."service_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
|
||||||
CREATE UNIQUE INDEX "assignment_proposals_pending_assignment_idx" ON "assignment_proposals" USING btree ("assignment_id") WHERE "assignment_proposals"."status" = 'pending';--> statement-breakpoint
|
|
||||||
CREATE INDEX "assignment_proposals_status_idx" ON "assignment_proposals" USING btree ("status","created_at");
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -162,13 +162,6 @@
|
|||||||
"when": 1795223283100,
|
"when": 1795223283100,
|
||||||
"tag": "0022_fixed_squadron_supreme",
|
"tag": "0022_fixed_squadron_supreme",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
},
|
|
||||||
{
|
|
||||||
"idx": 23,
|
|
||||||
"version": "7",
|
|
||||||
"when": 1795274972891,
|
|
||||||
"tag": "0023_assignment_proposals",
|
|
||||||
"breakpoints": true
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+7
-4
@@ -129,18 +129,21 @@ test.describe("event photo sharing", () => {
|
|||||||
await page.getByLabel("Exposure").focus();
|
await page.getByLabel("Exposure").focus();
|
||||||
await page.getByLabel("Exposure").press("ArrowRight");
|
await page.getByLabel("Exposure").press("ArrowRight");
|
||||||
await page.getByRole("button", { name: "Save edited JPEG" }).click();
|
await page.getByRole("button", { name: "Save edited JPEG" }).click();
|
||||||
// A successful save closes the editor and returns to the refreshed gallery.
|
await expect(page.getByText("Full-resolution JPEG saved.")).toBeVisible({
|
||||||
await expect(page.getByRole("dialog")).toBeHidden({ timeout: 30_000 });
|
timeout: 30_000,
|
||||||
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
|
});
|
||||||
|
|
||||||
const [download] = await Promise.all([
|
const [download] = await Promise.all([
|
||||||
page.waitForEvent("download"),
|
page.waitForEvent("download"),
|
||||||
page.getByRole("link", { name: "Download edited" }).click(),
|
page.getByRole("link", { name: "Download edited JPEG" }).click(),
|
||||||
]);
|
]);
|
||||||
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
|
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
|
||||||
const edited = await readFile((await download.path())!);
|
const edited = await readFile((await download.path())!);
|
||||||
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
|
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
|
||||||
expect(edited.equals(PHOTO)).toBe(false);
|
expect(edited.equals(PHOTO)).toBe(false);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: "Close photo editor" }).click();
|
||||||
|
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
|
||||||
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
|
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
|
||||||
"src",
|
"src",
|
||||||
/variant=edited/,
|
/variant=edited/,
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -4,11 +4,7 @@ import { Download, Printer } from "lucide-react";
|
|||||||
import { auth } from "@/auth/config";
|
import { auth } from "@/auth/config";
|
||||||
import { hasPermission } from "@/auth/permissions";
|
import { hasPermission } from "@/auth/permissions";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import {
|
import { listPendingCoverageRequests } from "@/db/coverage";
|
||||||
listPendingAlternativeProposals,
|
|
||||||
listPendingCoverageRequests,
|
|
||||||
} from "@/db/coverage";
|
|
||||||
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
|
|
||||||
import { listCoverageIntakes } from "@/db/intake";
|
import { listCoverageIntakes } from "@/db/intake";
|
||||||
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
|
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -28,10 +24,9 @@ export default async function CoveragePage() {
|
|||||||
if (!user?.id) return null;
|
if (!user?.id) return null;
|
||||||
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
|
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
|
||||||
|
|
||||||
const [requests, intakes, alternatives] = await Promise.all([
|
const [requests, intakes] = await Promise.all([
|
||||||
listPendingCoverageRequests(),
|
listPendingCoverageRequests(),
|
||||||
listCoverageIntakes("new"),
|
listCoverageIntakes("new"),
|
||||||
listPendingAlternativeProposals(),
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const views: CoverageRequestView[] = await Promise.all(
|
const views: CoverageRequestView[] = await Promise.all(
|
||||||
@@ -101,60 +96,6 @@ export default async function CoveragePage() {
|
|||||||
|
|
||||||
<CoverageBoard requests={views} intakes={intakeViews} />
|
<CoverageBoard requests={views} intakes={intakeViews} />
|
||||||
|
|
||||||
{alternatives.length > 0 && (
|
|
||||||
<section className="rounded-md border border-border">
|
|
||||||
<div className="border-b border-border bg-muted/30 px-3 py-2">
|
|
||||||
<h2 className="text-sm font-semibold">Proposed another Sunday</h2>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
These volunteers cannot serve their proposed date but offered an
|
|
||||||
alternative. Reassign them from the schedule, then clear the seat.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<ul className="divide-y divide-border">
|
|
||||||
{alternatives.map((proposal) => (
|
|
||||||
<li key={proposal.id} className="space-y-1 px-3 py-2 text-sm">
|
|
||||||
<p>
|
|
||||||
<span className="font-medium">{proposal.requesterName}</span>{" "}
|
|
||||||
({proposal.roleName}) can serve{" "}
|
|
||||||
<span className="font-medium">
|
|
||||||
{formatInTimezone(
|
|
||||||
proposal.proposedStartsAt,
|
|
||||||
CHURCH_TIMEZONE,
|
|
||||||
{
|
|
||||||
timeZone: CHURCH_TIMEZONE,
|
|
||||||
weekday: "short",
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
},
|
|
||||||
)}
|
|
||||||
</span>{" "}
|
|
||||||
instead of{" "}
|
|
||||||
{formatInTimezone(
|
|
||||||
proposal.currentStartsAt,
|
|
||||||
CHURCH_TIMEZONE,
|
|
||||||
{
|
|
||||||
timeZone: CHURCH_TIMEZONE,
|
|
||||||
weekday: "short",
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
},
|
|
||||||
)}
|
|
||||||
.
|
|
||||||
</p>
|
|
||||||
{proposal.note && (
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
“{proposal.note}”
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
{proposal.requesterEmail}
|
|
||||||
</p>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</section>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Share the public request form at{" "}
|
Share the public request form at{" "}
|
||||||
<Link href="/request-coverage" className="font-medium underline">
|
<Link href="/request-coverage" className="font-medium underline">
|
||||||
|
|||||||
@@ -109,13 +109,10 @@ export default function AdminGuidePage() {
|
|||||||
/>
|
/>
|
||||||
<GuideCallout title="Draft versus published" tone="note">
|
<GuideCallout title="Draft versus published" tone="note">
|
||||||
<p>
|
<p>
|
||||||
New service instances start as drafts, and volunteers do not see a
|
New service instances start as drafts. Volunteers only see the
|
||||||
draft on their schedule. Assigning a seat still sends the proposed
|
week, and only receive assignment email, after you publish it. A
|
||||||
email immediately so the volunteer can accept, decline, or propose
|
draft is safe to edit; a published week should be changed carefully
|
||||||
another Sunday. Publishing makes the week visible and queues the
|
because people have already been told about it.
|
||||||
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.
|
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
@@ -377,9 +374,7 @@ export default function AdminGuidePage() {
|
|||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Press <strong>Publish</strong> when the week is ready. Publishing
|
Press <strong>Publish</strong> when the week is ready. Publishing
|
||||||
makes the week visible and queues the published/reminder mail for
|
queues assignment email and reminder rules for that instance.
|
||||||
live assignments. Assignments made later still send their proposed
|
|
||||||
email immediately.
|
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Unpublish only when you intend to withdraw the week; volunteers may
|
Unpublish only when you intend to withdraw the week; volunteers may
|
||||||
@@ -448,20 +443,6 @@ export default function AdminGuidePage() {
|
|||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
|
|
||||||
<h3 className="pt-2 text-base font-semibold">
|
|
||||||
Volunteers who propose another Sunday
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
The proposed email also offers <strong>Propose another Sunday</strong>.
|
|
||||||
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 <strong>Coverage</strong> under{" "}
|
|
||||||
<strong>Proposed another Sunday</strong>. 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.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
|
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
|
||||||
<p className="text-sm leading-6">
|
<p className="text-sm leading-6">
|
||||||
Ministry leaders can submit the public form at{" "}
|
Ministry leaders can submit the public form at{" "}
|
||||||
@@ -723,14 +704,12 @@ export default function AdminGuidePage() {
|
|||||||
admins can remove them.
|
admins can remove them.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
<GuideCallout title="Role guides are built in" tone="tip">
|
<GuideCallout title="The two long guides are built in" tone="tip">
|
||||||
<p>
|
<p>
|
||||||
Training shows the guide for the signed-in role: the Platform
|
The Platform administration guide and the Volunteer guide appear at
|
||||||
administration guide for admins, the Coordinator guide for
|
the top of Training as web pages with screenshots and as downloadable
|
||||||
coordinators, and the Volunteer guide for volunteers and trainees.
|
PDFs. They are documentation for this deployment, not editable
|
||||||
The admin and volunteer guides also have downloadable PDFs. These
|
lessons, so they stay consistent for every admin.
|
||||||
are documentation for this deployment, not editable lessons, so they
|
|
||||||
stay consistent for everyone.
|
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
|
|||||||
@@ -1,393 +0,0 @@
|
|||||||
import type { Metadata } from "next";
|
|
||||||
import {
|
|
||||||
GuideCallout,
|
|
||||||
GuideFields,
|
|
||||||
GuideFigure,
|
|
||||||
GuideSection,
|
|
||||||
GuideShell,
|
|
||||||
GuideStep,
|
|
||||||
GuideSteps,
|
|
||||||
} from "@/components/app/training/guide";
|
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
|
||||||
title: "Coordinator guide",
|
|
||||||
};
|
|
||||||
|
|
||||||
const SECTIONS = [
|
|
||||||
{ id: "role", title: "Your coordinator role" },
|
|
||||||
{ id: "week", title: "Build and publish a week" },
|
|
||||||
{ id: "replies", title: "Assignment emails and replies" },
|
|
||||||
{ id: "coverage", title: "Coverage and swaps" },
|
|
||||||
{ id: "run-sheets", title: "Run sheets" },
|
|
||||||
{ id: "events", title: "Events and media" },
|
|
||||||
{ id: "announcements", title: "Announcements and training" },
|
|
||||||
{ id: "exports", title: "Print and CSV exports" },
|
|
||||||
{ id: "troubleshooting", title: "Troubleshooting" },
|
|
||||||
];
|
|
||||||
|
|
||||||
export default function CoordinatorGuidePage() {
|
|
||||||
return (
|
|
||||||
<GuideShell
|
|
||||||
title="Coordinator guide"
|
|
||||||
audience="Coordinators"
|
|
||||||
intro="The working guide for coordinating the media team: building and publishing the schedule, responding to assignment replies, resolving coverage, preparing run sheets, keeping events moving, and getting the week onto paper or into a spreadsheet."
|
|
||||||
pdfHref="/training/media-team-coordinator-guide.pdf"
|
|
||||||
pdfLabel="Download coordinator PDF"
|
|
||||||
sections={SECTIONS}
|
|
||||||
>
|
|
||||||
<GuideSection id="role" title="1. Your coordinator role">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
<GuideFields
|
|
||||||
rows={[
|
|
||||||
{
|
|
||||||
label: "You can",
|
|
||||||
value:
|
|
||||||
"Dashboard, Coverage, schedule assignment and publishing, auto-fill, run sheets, events and media, announcements, training viewing, print, and schedule/history CSV downloads.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Admins handle",
|
|
||||||
value:
|
|
||||||
"People and access, skill verification, positions and requirements, service templates, email credentials, reminder rules, backups, and training authoring. Ask an admin when one of those needs to change.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Everyone serves",
|
|
||||||
value:
|
|
||||||
"Coordinators can hold a seat too. Your own assignment, availability, profile, and notification settings work exactly like a volunteer’s.",
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<GuideFigure
|
|
||||||
src="/training/screens/admin-dashboard.png"
|
|
||||||
alt="Coverage dashboard with filled and open seats and the next service summary"
|
|
||||||
caption="Open Dashboard before planning a week: it shows open seats and unconfirmed assignments at a glance."
|
|
||||||
/>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="week" title="2. Build and publish a week">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
<GuideFigure
|
|
||||||
src="/training/screens/admin-schedule.png"
|
|
||||||
alt="Week schedule grid with position columns and assignment controls"
|
|
||||||
caption="Each column is a position and each row is a service. Press an empty seat to assign someone."
|
|
||||||
/>
|
|
||||||
<GuideSteps>
|
|
||||||
<GuideStep>
|
|
||||||
Open <strong>Schedule</strong> and use the arrows to reach the week
|
|
||||||
you are building.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Press an empty seat and choose a volunteer. The candidate list is
|
|
||||||
ranked by skills, availability, and conflicts.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Use <strong>Auto-fill</strong> for a first pass over open seats, then
|
|
||||||
review every suggestion. The ranking does not know the relational
|
|
||||||
context or the last-minute holiday.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Read any conflict before saving. A hard conflict blocks the
|
|
||||||
assignment; a soft warning, such as exceeding a monthly cap, can be
|
|
||||||
overridden.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Press <strong>Publish</strong> when the week is ready. Publishing
|
|
||||||
makes the schedule visible and queues the published/reminder mail for
|
|
||||||
the people already on it.
|
|
||||||
</GuideStep>
|
|
||||||
</GuideSteps>
|
|
||||||
<GuideCallout title="Assigning sends mail before publish" tone="note">
|
|
||||||
<p>
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
</GuideCallout>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="replies" title="3. Assignment emails and replies">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
Every proposed seat gets an email with three single-use links. The
|
|
||||||
volunteer does not need an account or a login to use them.
|
|
||||||
</p>
|
|
||||||
<GuideFields
|
|
||||||
rows={[
|
|
||||||
{
|
|
||||||
label: "Confirm",
|
|
||||||
value:
|
|
||||||
"The volunteer accepts the seat. The assignment moves to confirmed and the schedule shows it immediately.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Can’t make it",
|
|
||||||
value:
|
|
||||||
"The volunteer declines. The seat needs a replacement; use the schedule or Coverage to fill it.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Propose another Sunday",
|
|
||||||
value:
|
|
||||||
"Records a pending request for a different date. It does not release the original seat or change the assignment by itself.",
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
<GuideCallout title="What the volunteer sees" tone="tip">
|
|
||||||
<p>
|
|
||||||
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{" "}
|
|
||||||
<code>/respond</code> page the link opens.
|
|
||||||
</p>
|
|
||||||
</GuideCallout>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="coverage" title="4. Coverage and swaps">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
<GuideFigure
|
|
||||||
src="/training/screens/admin-coverage.png"
|
|
||||||
alt="Coverage page with pending swap requests and ranked replacements"
|
|
||||||
caption="Approve with a replacement, approve and release the seat, or decline and leave the volunteer in place."
|
|
||||||
/>
|
|
||||||
<h3 className="pt-2 text-base font-semibold">Handle a swap request</h3>
|
|
||||||
<GuideSteps>
|
|
||||||
<GuideStep>
|
|
||||||
Open <strong>Coverage</strong> and read the volunteer, seat, date,
|
|
||||||
and reason.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Review the ranked replacements and their warnings. Pick someone who
|
|
||||||
fits the skills and availability, not just the top score.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Choose <strong>Approve with replacement</strong> to cancel the
|
|
||||||
original assignment and place the replacement as proposed. The new
|
|
||||||
person receives the same accept/decline/propose email.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Choose <strong>Approve and release</strong> when nobody can take it.
|
|
||||||
The seat becomes open and the original assignment is kept in history.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Choose <strong>Decline</strong> when the request should not be
|
|
||||||
granted; the original volunteer stays on the seat.
|
|
||||||
</GuideStep>
|
|
||||||
</GuideSteps>
|
|
||||||
|
|
||||||
<h3 className="pt-2 text-base font-semibold">
|
|
||||||
Volunteers who propose another Sunday
|
|
||||||
</h3>
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
Proposals from the assignment email appear on Coverage under{" "}
|
|
||||||
<strong>Proposed another Sunday</strong>. 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.
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<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. Accepted requests
|
|
||||||
become events: choose <strong>Create event</strong> to open one with
|
|
||||||
the requester and ministry attached, or <strong>Decline</strong> if it
|
|
||||||
is not a fit.
|
|
||||||
</p>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="run-sheets" title="5. 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. Coordinators edit the details and cues; every
|
|
||||||
signed-in volunteer can tick checklist items.
|
|
||||||
</p>
|
|
||||||
<GuideFigure
|
|
||||||
src="/training/screens/admin-run-sheet.png"
|
|
||||||
alt="Run sheet editor with service details, cue list, and checklist"
|
|
||||||
caption="Prepare the sheet before the weekend, then let the team tick items as the service runs."
|
|
||||||
/>
|
|
||||||
<GuideSteps>
|
|
||||||
<GuideStep>
|
|
||||||
Open the run sheet from the schedule, Dashboard, or your own
|
|
||||||
next-serve card.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Fill in speaker, message title, stream link, slides link, and team
|
|
||||||
notes, then press <strong>Save details</strong>.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Edit cues inline and save each row. Add a cue at the bottom when the
|
|
||||||
service needs one.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Add pre-service or post-service checklist items for this service.
|
|
||||||
Defaults are seeded only once, so your edits stick.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Press <strong>Print</strong> for a clean booth copy.
|
|
||||||
</GuideStep>
|
|
||||||
</GuideSteps>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="events" title="6. Events and media">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
<GuideFigure
|
|
||||||
src="/training/screens/user-events.png"
|
|
||||||
alt="Events list with upcoming event cards and assignment counts"
|
|
||||||
caption="Open an event to see its brief, team, folders, and files."
|
|
||||||
/>
|
|
||||||
<GuideSteps>
|
|
||||||
<GuideStep>
|
|
||||||
Create the event with its date, time, location, and brief, or create
|
|
||||||
one from an accepted outside coverage request.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Assign the photographers and editors. Only assigned people and
|
|
||||||
managers can open the event and its files.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Create folders for originals and edited exports so the handoff is
|
|
||||||
obvious.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
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.
|
|
||||||
</GuideStep>
|
|
||||||
</GuideSteps>
|
|
||||||
<GuideCallout title="Original files live on the media share" tone="note">
|
|
||||||
<p>
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
</GuideCallout>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="announcements" title="7. Announcements and training">
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
Coordinators can write announcements. Training lessons are authored by
|
|
||||||
admins, but everyone can read the published lessons and the guide for
|
|
||||||
their role.
|
|
||||||
</p>
|
|
||||||
<GuideSteps>
|
|
||||||
<GuideStep>
|
|
||||||
Open <strong>Announcements</strong> and write a title and plain-text
|
|
||||||
message.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Keep <strong>Published</strong> ticked, or untick it to save a draft.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Use the row actions to publish, unpublish, or delete a post.
|
|
||||||
</GuideStep>
|
|
||||||
<GuideStep>
|
|
||||||
Open <strong>Training</strong> to read the coordinator guide and the
|
|
||||||
published lessons. If a lesson needs a correction, ask an admin.
|
|
||||||
</GuideStep>
|
|
||||||
</GuideSteps>
|
|
||||||
<GuideCallout title="Your guide is selected automatically" tone="tip">
|
|
||||||
<p>
|
|
||||||
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.
|
|
||||||
</p>
|
|
||||||
</GuideCallout>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="exports" title="8. Print and CSV exports">
|
|
||||||
<GuideFields
|
|
||||||
rows={[
|
|
||||||
{
|
|
||||||
label: "Printable roster",
|
|
||||||
value:
|
|
||||||
"Open /schedule/print from Dashboard or Coverage. It prints the current week by service with call times and confirmation state, without the app navigation.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Schedule CSV",
|
|
||||||
value:
|
|
||||||
"GET /api/export/schedule downloads assignments for a date range (four weeks by default).",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "Serving history CSV",
|
|
||||||
value:
|
|
||||||
"GET /api/export/history downloads completed and no-show assignments for 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 deliberately plain: no navigation, no controls, just the roster."
|
|
||||||
/>
|
|
||||||
</GuideSection>
|
|
||||||
|
|
||||||
<GuideSection id="troubleshooting" title="9. Troubleshooting">
|
|
||||||
<GuideFields
|
|
||||||
rows={[
|
|
||||||
{
|
|
||||||
label: "A volunteer did not get the assignment email",
|
|
||||||
value:
|
|
||||||
"Ask them to check spam and confirm the address on their profile. Ask an admin to check the notification log; failed messages show the provider error and can be retried after the cause is fixed.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "A confirmation link does not work",
|
|
||||||
value:
|
|
||||||
"The links are single-use and expire after 14 days. Do not forward another person’s link; ask an admin for help with the account, or recreate the assignment.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "A seat will not accept an assignment",
|
|
||||||
value:
|
|
||||||
"Read the conflict. A blackout, duplicate service assignment, or missing core skill is a hard block. A monthly cap is a soft warning you may override.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "A volunteer cannot see the week",
|
|
||||||
value:
|
|
||||||
"Confirm the instance is published. Draft weeks are hidden from the volunteer schedule, even though the proposed email may already have gone out.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "A proposed Sunday is not on the schedule",
|
|
||||||
value:
|
|
||||||
"The proposal queue is read-only. Review it on Coverage, then change the schedule yourself and confirm the new arrangement with the volunteer.",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: "A coverage request disappeared",
|
|
||||||
value:
|
|
||||||
"Check whether the seat was cleared directly from the schedule. Approval keeps the cancelled assignment in history; a direct clear removes it.",
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
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”.
|
|
||||||
</p>
|
|
||||||
</GuideSection>
|
|
||||||
</GuideShell>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,12 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -128,15 +128,6 @@ export default function VolunteerGuidePage() {
|
|||||||
the top for the two things volunteers change most often.
|
the top for the two things volunteers change most often.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
<GuideCallout title="Replying from email" tone="tip">
|
|
||||||
<p>
|
|
||||||
A proposed seat arrives by email with three links:{" "}
|
|
||||||
<strong>Confirm</strong>, <strong>Can’t make it</strong>, and{" "}
|
|
||||||
<strong>Propose another Sunday</strong>. 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.
|
|
||||||
</p>
|
|
||||||
</GuideCallout>
|
|
||||||
<GuideFigure
|
<GuideFigure
|
||||||
src="/training/screens/user-home-mobile.png"
|
src="/training/screens/user-home-mobile.png"
|
||||||
alt="Home page at phone width with the scrollable tab bar"
|
alt="Home page at phone width with the scrollable tab bar"
|
||||||
@@ -180,11 +171,9 @@ export default function VolunteerGuidePage() {
|
|||||||
/>
|
/>
|
||||||
<GuideCallout title="Draft weeks are invisible" tone="note">
|
<GuideCallout title="Draft weeks are invisible" tone="note">
|
||||||
<p>
|
<p>
|
||||||
A week that has not been published does not appear on your schedule.
|
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
|
and does not generate assignment email. If you expected a date and
|
||||||
is a draft, so reply to that email even if the date is not on the
|
cannot see it, the week is probably still a draft.
|
||||||
schedule yet. Publishing is what makes the week visible and triggers
|
|
||||||
the published and reminder mail.
|
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
@@ -269,14 +258,6 @@ export default function VolunteerGuidePage() {
|
|||||||
You will see the change on Home once it is resolved.
|
You will see the change on Home once it is resolved.
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
<h3 className="pt-2 text-base font-semibold">Propose another Sunday</h3>
|
|
||||||
<p className="text-sm leading-6">
|
|
||||||
If you cannot serve the date but could serve a different Sunday, use{" "}
|
|
||||||
<strong>Propose another Sunday</strong> 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.
|
|
||||||
</p>
|
|
||||||
<p className="text-sm leading-6">
|
<p className="text-sm leading-6">
|
||||||
Ministry leaders outside the team can request coverage through the
|
Ministry leaders outside the team can request coverage through the
|
||||||
public form at <code>/request-coverage</code>. If you are asked to
|
public form at <code>/request-coverage</code>. If you are asked to
|
||||||
@@ -414,24 +395,24 @@ export default function VolunteerGuidePage() {
|
|||||||
</p>
|
</p>
|
||||||
<GuideFigure
|
<GuideFigure
|
||||||
src="/training/screens/user-training.png"
|
src="/training/screens/user-training.png"
|
||||||
alt="Training page with the guide for your role at the top and published lessons below"
|
alt="Training page with the two full guides at the top and published lessons below"
|
||||||
caption="The guide for your role is at the top; use the shorter lessons for specific skills."
|
caption="Start with the two full guides, then use the shorter lessons for specific skills."
|
||||||
/>
|
/>
|
||||||
<GuideSteps>
|
<GuideSteps>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Open <strong>Training</strong> from the navigation.
|
Open <strong>Training</strong> from the navigation.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Read the guide at the top of the page once end to end; it is chosen
|
Read the <strong>Volunteer guide</strong> once end to end; it covers
|
||||||
for your role and covers every screen you can use.
|
every screen in this app.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Open an attachment to read or download it. Links open in a new tab so
|
Open an attachment to read or download it. Links open in a new tab so
|
||||||
you do not lose your place.
|
you do not lose your place.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Use the PDF download when the guide offers one, or print the page for
|
Use the PDF download on either guide for an offline copy you can keep
|
||||||
an offline copy you can keep on your phone.
|
on your phone.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
|
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
|
||||||
|
|||||||
@@ -4,36 +4,20 @@ import { hasPermission } from "@/auth/permissions";
|
|||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { listLessons } from "@/db/training";
|
import { listLessons } from "@/db/training";
|
||||||
import { trainingBodyToHtml } from "@/lib/rich-text";
|
import { trainingBodyToHtml } from "@/lib/rich-text";
|
||||||
import { trainingGuideForRole } from "@/lib/training-guides";
|
|
||||||
import { TrainingPanel } from "@/components/app/training-panel";
|
import { TrainingPanel } from "@/components/app/training-panel";
|
||||||
import {
|
import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
|
||||||
BookOpenCheck,
|
|
||||||
ClipboardList,
|
|
||||||
Download,
|
|
||||||
ShieldCheck,
|
|
||||||
UserRound,
|
|
||||||
} from "lucide-react";
|
|
||||||
|
|
||||||
export const metadata = { title: "Training" };
|
export const metadata = { title: "Training" };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Training content. Volunteers see published lessons and attachments; admins
|
* Training content. Volunteers see published lessons and attachments; admins
|
||||||
* can author, publish, upload, and delete. The full guide shown at the top is
|
* can author, publish, upload, and delete. Content is stored in Postgres and
|
||||||
* 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.
|
* attachments under the uploads volume, so it is editable with no deploy.
|
||||||
*/
|
*/
|
||||||
export default async function TrainingPage() {
|
export default async function TrainingPage() {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
const role = (session?.user as { systemRole?: SystemRole } | undefined)
|
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
|
||||||
?.systemRole;
|
|
||||||
const canEdit = hasPermission(role, "training.author");
|
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(
|
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
|
||||||
(lesson) => ({
|
(lesson) => ({
|
||||||
...lesson,
|
...lesson,
|
||||||
@@ -52,37 +36,67 @@ export default async function TrainingPage() {
|
|||||||
<section aria-labelledby="full-guides" className="space-y-3">
|
<section aria-labelledby="full-guides" className="space-y-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
|
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
|
||||||
Your guide
|
Full guides
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
The complete, illustrated walkthrough for your role. Read it here or
|
Complete, illustrated walkthroughs with screenshots. Read them here
|
||||||
download the PDF where one is available.
|
or download the PDF for printing and offline use.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="rounded-md border border-border p-4">
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
<div className="flex flex-col rounded-md border border-border p-4">
|
||||||
<GuideIcon className="h-4 w-4" aria-hidden="true" />
|
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||||
{guide.audience}
|
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
|
||||||
</div>
|
Admins
|
||||||
<h3 className="mt-2 text-base font-semibold">{guide.title}</h3>
|
</div>
|
||||||
<p className="mt-1 text-sm leading-6 text-muted-foreground">
|
<h3 className="mt-2 text-base font-semibold">
|
||||||
{guide.description}
|
Platform administration guide
|
||||||
</p>
|
</h3>
|
||||||
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
|
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
|
||||||
<Link href={guide.href} className="text-primary underline">
|
People and access, skill verification, positions, services and
|
||||||
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
|
publishing, coverage, run sheets, email, notifications, backups,
|
||||||
Read your guide
|
and exports.
|
||||||
</Link>
|
</p>
|
||||||
{guide.pdfHref && guide.pdfLabel ? (
|
<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
|
<a
|
||||||
href={guide.pdfHref}
|
href="/training/media-team-admin-guide.pdf"
|
||||||
download
|
download
|
||||||
className="inline-flex items-center gap-1 text-primary underline"
|
className="inline-flex items-center gap-1 text-primary underline"
|
||||||
>
|
>
|
||||||
<Download className="h-4 w-4" aria-hidden="true" />
|
<Download className="h-4 w-4" aria-hidden="true" />
|
||||||
{guide.pdfLabel}
|
Download PDF
|
||||||
</a>
|
</a>
|
||||||
) : null}
|
</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 & 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>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -8,13 +8,11 @@ const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
|
|||||||
function errorStatus(code: RespondError["code"]): number {
|
function errorStatus(code: RespondError["code"]): number {
|
||||||
switch (code) {
|
switch (code) {
|
||||||
case "unknown_assignment":
|
case "unknown_assignment":
|
||||||
case "unknown_instance":
|
|
||||||
return 404;
|
return 404;
|
||||||
case "wrong_volunteer":
|
case "wrong_volunteer":
|
||||||
return 403;
|
return 403;
|
||||||
case "not_actionable":
|
case "not_actionable":
|
||||||
case "already_used":
|
case "already_used":
|
||||||
case "invalid_alternative":
|
|
||||||
return 409;
|
return 409;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { NextRequest } from "next/server";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { auth } from "@/auth/config";
|
import { auth } from "@/auth/config";
|
||||||
import { requestOrigin } from "@/auth/magic-link";
|
|
||||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
@@ -17,10 +16,8 @@ import {
|
|||||||
AssignFactError,
|
AssignFactError,
|
||||||
resolveAssignFacts,
|
resolveAssignFacts,
|
||||||
} from "@/db/assignments";
|
} from "@/db/assignments";
|
||||||
import {
|
import { cancelAssignmentNotifications } from "@/db/outbox";
|
||||||
cancelAssignmentNotifications,
|
import { enqueuePublishNotifications } from "@/db/outbox";
|
||||||
enqueueAssignmentProposed,
|
|
||||||
} from "@/db/outbox";
|
|
||||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -198,8 +195,6 @@ export const POST = async (req: NextRequest) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
const assignmentId = uuidv7();
|
const assignmentId = uuidv7();
|
||||||
const now = new Date();
|
|
||||||
const appOrigin = requestOrigin(req);
|
|
||||||
await db.transaction(async (tx) => {
|
await db.transaction(async (tx) => {
|
||||||
await tx.insert(assignments).values({
|
await tx.insert(assignments).values({
|
||||||
id: assignmentId,
|
id: assignmentId,
|
||||||
@@ -208,7 +203,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
status: "proposed",
|
status: "proposed",
|
||||||
source: "manual",
|
source: "manual",
|
||||||
assignedBy: actorId,
|
assignedBy: actorId,
|
||||||
assignedAt: now,
|
assignedAt: new Date(),
|
||||||
});
|
});
|
||||||
await tx
|
await tx
|
||||||
.update(slots)
|
.update(slots)
|
||||||
@@ -229,12 +224,12 @@ export const POST = async (req: NextRequest) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// The proposed email always goes out, whether the week is draft or
|
// A published week's mail is written at publish time; a seat added later
|
||||||
// published: the volunteer has to accept, decline, or propose another
|
// would otherwise never be announced. Both enqueues are idempotent on
|
||||||
// Sunday. On a published week only the reminders need topping up.
|
// dedupe_key, so existing rows are untouched.
|
||||||
await enqueueAssignmentProposed(tx, assignmentId, { now, appOrigin });
|
|
||||||
if (instance?.status === "published") {
|
if (instance?.status === "published") {
|
||||||
await enqueueRemindersForInstance(tx, instance.id, { now, appOrigin });
|
await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
|
||||||
|
await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { NextRequest } from "next/server";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { approveUser } from "@/auth/invites";
|
import { approveUser } from "@/auth/invites";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { getUserById } from "@/db/users";
|
import { getUserById } from "@/db/users";
|
||||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||||
|
|
||||||
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
const approved = await getUserById(user.id);
|
const approved = await getUserById(user.id);
|
||||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||||
if (approved) {
|
if (approved) {
|
||||||
const token = await signMagicToken(approved.email);
|
const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -7,7 +7,6 @@ import {
|
|||||||
requestOrigin,
|
requestOrigin,
|
||||||
} from "@/auth/magic-link";
|
} from "@/auth/magic-link";
|
||||||
import { rateLimit } from "@/lib/rate-limit";
|
import { rateLimit } from "@/lib/rate-limit";
|
||||||
import { hasPasswordProtectedAdmin } from "@/db/users";
|
|
||||||
|
|
||||||
const JSON_HEADERS = { "content-type": "application/json" };
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
const bodySchema = z.object({ email: z.string().email() });
|
const bodySchema = z.object({ email: z.string().email() });
|
||||||
@@ -60,29 +59,11 @@ 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 {
|
try {
|
||||||
const result = await requestMagicLink(parsed.data.email, {
|
const result = await requestMagicLink(parsed.data.email, {
|
||||||
origin: requestOrigin(req),
|
origin: requestOrigin(req),
|
||||||
});
|
});
|
||||||
// Never expose account metadata to an unauthenticated caller. The dev
|
return new Response(JSON.stringify(result), {
|
||||||
// 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,
|
status: 200,
|
||||||
headers: JSON_HEADERS,
|
headers: JSON_HEADERS,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,12 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { validateUsername } from "@/auth/password";
|
import { validateUsername } from "@/auth/password";
|
||||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
@@ -128,8 +133,9 @@ export const POST = async (req: NextRequest) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||||
// link only works once the account is active.
|
// link only works once the account is active. It is an invite, not a
|
||||||
const token = await signMagicToken(user.email);
|
// just-requested sign-in, so it gets the invite lifetime.
|
||||||
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,110 +0,0 @@
|
|||||||
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,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -17,10 +17,8 @@ function errorStatus(code: RespondError["code"]): number {
|
|||||||
switch (code) {
|
switch (code) {
|
||||||
case "already_used":
|
case "already_used":
|
||||||
case "not_actionable":
|
case "not_actionable":
|
||||||
case "invalid_alternative":
|
|
||||||
return 409;
|
return 409;
|
||||||
case "unknown_assignment":
|
case "unknown_assignment":
|
||||||
case "unknown_instance":
|
|
||||||
return 404;
|
return 404;
|
||||||
case "wrong_volunteer":
|
case "wrong_volunteer":
|
||||||
return 403;
|
return 403;
|
||||||
|
|||||||
@@ -1,191 +0,0 @@
|
|||||||
"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 (
|
|
||||||
<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>
|
|
||||||
{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."}
|
|
||||||
</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>
|
|
||||||
|
|
||||||
{magicLinkEnabled && (
|
|
||||||
<>
|
|
||||||
<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"
|
|
||||||
type="email"
|
|
||||||
required
|
|
||||||
autoComplete="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
placeholder="you@church.local"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
variant="outline"
|
|
||||||
disabled={linkStatus.kind === "sending"}
|
|
||||||
>
|
|
||||||
{linkStatus.kind === "sending"
|
|
||||||
? "Sending link…"
|
|
||||||
: "Send sign-in link"}
|
|
||||||
</Button>
|
|
||||||
{linkStatus.kind === "sent" && (
|
|
||||||
<p className="rounded border border-border bg-muted p-3 text-sm">
|
|
||||||
If that address belongs to an active account, a single-use
|
|
||||||
sign-in link has been sent. 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>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+210
-8
@@ -1,13 +1,215 @@
|
|||||||
import { hasPasswordProtectedAdmin } from "@/db/users";
|
"use client";
|
||||||
import { LoginForm } from "./login-form";
|
|
||||||
|
|
||||||
export const dynamic = "force-dynamic";
|
import { useEffect, 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";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public sign-in. The email-link form is bootstrap-only: once an admin has a
|
* Sign in with the username/password set after the first magic link, or request
|
||||||
* password, anyone who knew that admin's email could otherwise request a full
|
* a new one-time link by email. The magic-link path remains the recovery path
|
||||||
* admin session from this page.
|
* when someone has not set credentials yet.
|
||||||
*/
|
*/
|
||||||
export default async function LoginPage() {
|
export default function LoginPage() {
|
||||||
return <LoginForm magicLinkEnabled={!(await hasPasswordProtectedAdmin())} />;
|
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 [linkNotice, setLinkNotice] = useState<string | null>(null);
|
||||||
|
const [linkStatus, setLinkStatus] = useState<{
|
||||||
|
kind: "idle" | "sending" | "sent" | "error";
|
||||||
|
message?: string;
|
||||||
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
|
// /api/dev/complete redirects here when a link is dead. Say why, instead of
|
||||||
|
// dropping people on a bare sign-in form after the link fails.
|
||||||
|
useEffect(() => {
|
||||||
|
const error = new URLSearchParams(window.location.search).get("error");
|
||||||
|
if (error === "invalid_link") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has expired or is invalid. Request a fresh email link below.",
|
||||||
|
);
|
||||||
|
} else if (error === "link_used") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has already been used. Request a fresh email link below.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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 (
|
||||||
|
<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">
|
||||||
|
{linkNotice && (
|
||||||
|
<p role="alert" className="rounded border border-border bg-muted p-3 text-sm">
|
||||||
|
{linkNotice}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<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"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="you@church.local"
|
||||||
|
/>
|
||||||
|
<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>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,12 @@
|
|||||||
import {
|
import { getRespondAssignment } from "@/db/respond";
|
||||||
alternativeOptionsForAssignment,
|
|
||||||
getRespondAssignment,
|
|
||||||
} from "@/db/respond";
|
|
||||||
import { verifyRespondToken } from "@/lib/respond";
|
import { verifyRespondToken } from "@/lib/respond";
|
||||||
import { RespondForm } from "@/components/app/respond-form";
|
import { RespondForm } from "@/components/app/respond-form";
|
||||||
import { AlternativeForm } from "@/components/app/alternative-form";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public respond page — unit E4 (ARCHITECTURE §5.6).
|
* Public respond page — unit E4 (ARCHITECTURE §5.6).
|
||||||
*
|
*
|
||||||
* `GET /respond?t=<token>` renders the assignment and the action the token was
|
* `GET /respond?t=<token>&a=confirm|decline` renders the assignment and the two
|
||||||
* minted for: confirm/decline, or the "propose another Sunday" form. It never
|
* buttons. It never mutates: the token is consumed only by the form's POST.
|
||||||
* mutates: the token is consumed only by the form's POST.
|
|
||||||
*/
|
*/
|
||||||
export default async function RespondPage({
|
export default async function RespondPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
@@ -46,10 +41,6 @@ export default async function RespondPage({
|
|||||||
|
|
||||||
const alreadyAnswered =
|
const alreadyAnswered =
|
||||||
assignment.status === "confirmed" || assignment.status === "declined";
|
assignment.status === "confirmed" || assignment.status === "declined";
|
||||||
const alternatives =
|
|
||||||
payload.action === "alternative" && !alreadyAnswered
|
|
||||||
? await alternativeOptionsForAssignment(payload.assignmentId)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-4 px-6">
|
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-4 px-6">
|
||||||
@@ -69,21 +60,6 @@ export default async function RespondPage({
|
|||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
You already responded — this assignment is {assignment.status}.
|
You already responded — this assignment is {assignment.status}.
|
||||||
</p>
|
</p>
|
||||||
) : payload.action === "alternative" ? (
|
|
||||||
alternatives && alternatives.length > 0 ? (
|
|
||||||
<AlternativeForm
|
|
||||||
token={t}
|
|
||||||
options={alternatives.map((option) => ({
|
|
||||||
id: option.id,
|
|
||||||
label: option.label,
|
|
||||||
}))}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
There are no other upcoming services for this position right now.
|
|
||||||
Please decline so a coordinator can help.
|
|
||||||
</p>
|
|
||||||
)
|
|
||||||
) : (
|
) : (
|
||||||
<RespondForm token={t} />
|
<RespondForm token={t} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
+8
-2
@@ -18,7 +18,13 @@ import { db } from "@/db";
|
|||||||
import { users } from "@/db/schema";
|
import { users } from "@/db/schema";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
getUser,
|
||||||
|
normalizeEmail,
|
||||||
|
signMagicToken,
|
||||||
|
} from "./magic-link";
|
||||||
import type { UserStatus } from "@/db/schema";
|
import type { UserStatus } from "@/db/schema";
|
||||||
|
|
||||||
export type UserAction = "invite" | "approve" | "deny";
|
export type UserAction = "invite" | "approve" | "deny";
|
||||||
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
|
|||||||
appOrigin?: string;
|
appOrigin?: string;
|
||||||
}) {
|
}) {
|
||||||
const user = await resolveOrCreateInvitee(input.email);
|
const user = await resolveOrCreateInvitee(input.email);
|
||||||
const token = await signMagicToken(user.email);
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = input.appOrigin ?? APP_ORIGIN;
|
const origin = input.appOrigin ?? APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,10 +1,25 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { requestOrigin } from "./magic-link";
|
import { decodeJwt } from "jose";
|
||||||
|
import { INVITE_LINK_TTL, requestOrigin, signMagicToken } from "./magic-link";
|
||||||
|
|
||||||
function req(url: string, headers: Record<string, string>) {
|
function req(url: string, headers: Record<string, string>) {
|
||||||
return { url, headers: new Headers(headers) };
|
return { url, headers: new Headers(headers) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe("magic token lifetimes", () => {
|
||||||
|
it("keeps a just-requested sign-in link short", async () => {
|
||||||
|
const payload = decodeJwt(await signMagicToken("person@example.com"));
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(10 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an invite link survive days in an inbox", async () => {
|
||||||
|
const payload = decodeJwt(
|
||||||
|
await signMagicToken("person@example.com", INVITE_LINK_TTL),
|
||||||
|
);
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(7 * 24 * 60 * 60);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("requestOrigin", () => {
|
describe("requestOrigin", () => {
|
||||||
it("uses the proxy's forwarded scheme and host", () => {
|
it("uses the proxy's forwarded scheme and host", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
+18
-14
@@ -44,18 +44,11 @@ export const MAGIC_LINK_DEV_TRANSPORT =
|
|||||||
? process.env.MAGIC_LINK_DEV_TRANSPORT === "true"
|
? process.env.MAGIC_LINK_DEV_TRANSPORT === "true"
|
||||||
: process.env.NODE_ENV !== "production";
|
: process.env.NODE_ENV !== "production";
|
||||||
|
|
||||||
/**
|
export const APP_ORIGIN =
|
||||||
* Canonical origin for links built outside a live request. PUBLIC_ORIGIN is the
|
process.env.AUTH_URL ??
|
||||||
* address volunteers actually receive, so it wins over the auth callback URL
|
process.env.NEXTAUTH_URL ??
|
||||||
* (which may be a LAN address used only for cookies).
|
process.env.APP_ORIGIN ??
|
||||||
*/
|
"http://localhost:3000";
|
||||||
export const APP_ORIGIN = (
|
|
||||||
process.env.PUBLIC_ORIGIN?.trim() ||
|
|
||||||
process.env.AUTH_URL?.trim() ||
|
|
||||||
process.env.NEXTAUTH_URL?.trim() ||
|
|
||||||
process.env.APP_ORIGIN?.trim() ||
|
|
||||||
"http://localhost:3000"
|
|
||||||
).replace(/\/+$/, "");
|
|
||||||
|
|
||||||
function firstHeaderValue(value: string | null): string | null {
|
function firstHeaderValue(value: string | null): string | null {
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
@@ -228,7 +221,18 @@ export async function getOrCreateUser(email: string) {
|
|||||||
return raced;
|
return raced;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function signMagicToken(email: string): Promise<string> {
|
/**
|
||||||
|
* Sign-in links are short-lived because they are requested and clicked in the
|
||||||
|
* same sitting. Invites and welcome mails are not: they land in an inbox and may
|
||||||
|
* be opened days later, so they get their own lifetime (still single use).
|
||||||
|
*/
|
||||||
|
export const SIGN_IN_LINK_TTL = "10m";
|
||||||
|
export const INVITE_LINK_TTL = "7d";
|
||||||
|
|
||||||
|
export async function signMagicToken(
|
||||||
|
email: string,
|
||||||
|
ttl: string = SIGN_IN_LINK_TTL,
|
||||||
|
): Promise<string> {
|
||||||
return new SignJWT({
|
return new SignJWT({
|
||||||
email,
|
email,
|
||||||
purpose: "magic-link",
|
purpose: "magic-link",
|
||||||
@@ -236,7 +240,7 @@ export async function signMagicToken(email: string): Promise<string> {
|
|||||||
.setProtectedHeader({ alg: "HS256" })
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
.setJti(uuidv7())
|
.setJti(uuidv7())
|
||||||
.setIssuedAt()
|
.setIssuedAt()
|
||||||
.setExpirationTime("10m")
|
.setExpirationTime(ttl)
|
||||||
.sign(SECRET);
|
.sign(SECRET);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* "Propose another Sunday" on the public `/respond` page.
|
|
||||||
*
|
|
||||||
* Only rendered for an `alternative` email link. Submitting records the
|
|
||||||
* volunteer's preferred Sunday for a coordinator; it does not change the
|
|
||||||
* assignment, so a proposal never silently opens a hole in the schedule.
|
|
||||||
*/
|
|
||||||
export function AlternativeForm({
|
|
||||||
token,
|
|
||||||
options,
|
|
||||||
}: {
|
|
||||||
token: string;
|
|
||||||
options: { id: string; label: string }[];
|
|
||||||
}) {
|
|
||||||
const [instanceId, setInstanceId] = useState(options[0]?.id ?? "");
|
|
||||||
const [note, setNote] = useState("");
|
|
||||||
const [state, setState] = useState<"idle" | "sending" | "done" | "error">(
|
|
||||||
"idle",
|
|
||||||
);
|
|
||||||
const [message, setMessage] = useState("");
|
|
||||||
|
|
||||||
async function submit(event: React.FormEvent<HTMLFormElement>) {
|
|
||||||
event.preventDefault();
|
|
||||||
setState("sending");
|
|
||||||
setMessage("");
|
|
||||||
try {
|
|
||||||
const res = await fetch("/api/respond/alternative", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ token, instanceId, note }),
|
|
||||||
});
|
|
||||||
const body = (await res.json().catch(() => ({}))) as {
|
|
||||||
error?: string;
|
|
||||||
};
|
|
||||||
if (!res.ok) {
|
|
||||||
setMessage(body.error ?? "Could not send your proposal.");
|
|
||||||
setState("error");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const picked =
|
|
||||||
options.find((option) => option.id === instanceId)?.label ??
|
|
||||||
"that Sunday";
|
|
||||||
setMessage(
|
|
||||||
`Thanks — your coordinator will see that you can serve on ${picked}.`,
|
|
||||||
);
|
|
||||||
setState("done");
|
|
||||||
} catch {
|
|
||||||
setMessage("Network error — please try again.");
|
|
||||||
setState("error");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state === "done") {
|
|
||||||
return (
|
|
||||||
<p role="status" className="text-sm text-muted-foreground">
|
|
||||||
{message}
|
|
||||||
</p>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form onSubmit={submit} className="space-y-3">
|
|
||||||
<label className="block space-y-1 text-sm">
|
|
||||||
<span className="font-medium">Which Sunday works instead?</span>
|
|
||||||
<select
|
|
||||||
value={instanceId}
|
|
||||||
onChange={(event) => setInstanceId(event.target.value)}
|
|
||||||
className="block min-h-11 w-full rounded-md border border-input bg-background px-3 text-sm"
|
|
||||||
>
|
|
||||||
{options.map((option) => (
|
|
||||||
<option key={option.id} value={option.id}>
|
|
||||||
{option.label}
|
|
||||||
</option>
|
|
||||||
))}
|
|
||||||
</select>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<label className="block space-y-1 text-sm">
|
|
||||||
<span className="font-medium">
|
|
||||||
Anything the coordinator should know?{" "}
|
|
||||||
<span className="font-normal text-muted-foreground">(optional)</span>
|
|
||||||
</span>
|
|
||||||
<textarea
|
|
||||||
value={note}
|
|
||||||
onChange={(event) => setNote(event.target.value)}
|
|
||||||
maxLength={500}
|
|
||||||
rows={3}
|
|
||||||
className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
|
||||||
/>
|
|
||||||
</label>
|
|
||||||
|
|
||||||
<button
|
|
||||||
type="submit"
|
|
||||||
disabled={state === "sending" || !instanceId}
|
|
||||||
className="inline-flex min-h-11 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
|
||||||
>
|
|
||||||
{state === "sending" ? "Sending…" : "Propose this Sunday"}
|
|
||||||
</button>
|
|
||||||
|
|
||||||
{state === "error" && (
|
|
||||||
<p role="alert" className="text-sm text-destructive">
|
|
||||||
{message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -66,6 +66,12 @@ const TABS: { id: EditorTab; label: string }[] = [
|
|||||||
|
|
||||||
const CLIPBOARD_KEY = "glenloch-photo-adjustments";
|
const CLIPBOARD_KEY = "glenloch-photo-adjustments";
|
||||||
|
|
||||||
|
function formatBytes(bytes: number | null): string {
|
||||||
|
if (!bytes) return "";
|
||||||
|
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
function cloneAdjustments(adjustments: PhotoAdjustments): PhotoAdjustments {
|
function cloneAdjustments(adjustments: PhotoAdjustments): PhotoAdjustments {
|
||||||
return {
|
return {
|
||||||
...adjustments,
|
...adjustments,
|
||||||
@@ -402,8 +408,9 @@ export function PhotoViewer({
|
|||||||
JSON.stringify(photo.adjustments) === JSON.stringify(defaultPhotoAdjustments());
|
JSON.stringify(photo.adjustments) === JSON.stringify(defaultPhotoAdjustments());
|
||||||
const autoSeed = showsAdvancedEdit && Boolean(advancedSeed) && quickLayerIsNeutral;
|
const autoSeed = showsAdvancedEdit && Boolean(advancedSeed) && quickLayerIsNeutral;
|
||||||
const [takeOverPending, setTakeOverPending] = useState(autoSeed);
|
const [takeOverPending, setTakeOverPending] = useState(autoSeed);
|
||||||
|
const [advancedRetired, setAdvancedRetired] = useState(false);
|
||||||
const autoSeeded = useRef(autoSeed);
|
const autoSeeded = useRef(autoSeed);
|
||||||
const showAdvancedPanel = showsAdvancedEdit;
|
const showAdvancedPanel = showsAdvancedEdit && !advancedRetired;
|
||||||
// Once the sliders take over they render from the original file, so the
|
// Once the sliders take over they render from the original file, so the
|
||||||
// preview must not keep the advanced render underneath them.
|
// preview must not keep the advanced render underneath them.
|
||||||
const basesOnAdvanced = showsAdvancedEdit && !takeOverPending;
|
const basesOnAdvanced = showsAdvancedEdit && !takeOverPending;
|
||||||
@@ -433,9 +440,17 @@ export function PhotoViewer({
|
|||||||
const [advancedBusy, setAdvancedBusy] = useState(false);
|
const [advancedBusy, setAdvancedBusy] = useState(false);
|
||||||
const [advancedError, setAdvancedError] = useState<string | null>(null);
|
const [advancedError, setAdvancedError] = useState<string | null>(null);
|
||||||
const [saveError, setSaveError] = useState<string | null>(null);
|
const [saveError, setSaveError] = useState<string | null>(null);
|
||||||
// Cache-buster for the saved JPEG links. The gallery remounts this viewer
|
const [saveResult, setSaveResult] = useState<{
|
||||||
// with fresh props after a save, so it is read once per opening.
|
editedAt: string;
|
||||||
const savedVersion = photo.editedAt ? Date.parse(photo.editedAt) : 0;
|
editedSizeBytes: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
/** Nothing was re-rendered because the saved edit is already this look. */
|
||||||
|
unchanged?: boolean;
|
||||||
|
} | null>(null);
|
||||||
|
const [savedVersion, setSavedVersion] = useState(() =>
|
||||||
|
photo.editedAt ? Date.parse(photo.editedAt) : 0,
|
||||||
|
);
|
||||||
const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
|
const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
|
||||||
const [takeOverMessage, setTakeOverMessage] = useState<string | null>(null);
|
const [takeOverMessage, setTakeOverMessage] = useState<string | null>(null);
|
||||||
const [hoverSetting, setHoverSetting] = useState<{
|
const [hoverSetting, setHoverSetting] = useState<{
|
||||||
@@ -718,6 +733,7 @@ export function PhotoViewer({
|
|||||||
setTakeOverPending(true);
|
setTakeOverPending(true);
|
||||||
setTab("light");
|
setTab("light");
|
||||||
setSaveError(null);
|
setSaveError(null);
|
||||||
|
setSaveResult(null);
|
||||||
setRecipeMessage(null);
|
setRecipeMessage(null);
|
||||||
setTakeOverMessage(
|
setTakeOverMessage(
|
||||||
"Advanced settings loaded. Review the sliders, then save to make this editor the source of truth.",
|
"Advanced settings loaded. Review the sliders, then save to make this editor the source of truth.",
|
||||||
@@ -746,15 +762,31 @@ export function PhotoViewer({
|
|||||||
const data = (await response.json().catch(() => ({}))) as {
|
const data = (await response.json().catch(() => ({}))) as {
|
||||||
error?: string;
|
error?: string;
|
||||||
editedAt?: string;
|
editedAt?: string;
|
||||||
|
editedSizeBytes?: number;
|
||||||
|
width?: number;
|
||||||
|
height?: number;
|
||||||
|
unchanged?: boolean;
|
||||||
|
tookOver?: boolean;
|
||||||
};
|
};
|
||||||
if (!response.ok || !data.editedAt) {
|
if (!response.ok || !data.editedAt) {
|
||||||
setSaveError(data.error ?? "The edited JPEG could not be saved.");
|
setSaveError(data.error ?? "The edited JPEG could not be saved.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// Saving is the end of the edit: refresh the gallery and close the
|
setSaveResult({
|
||||||
// window so the new thumbnail and Edited badge are visible immediately.
|
editedAt: data.editedAt,
|
||||||
|
editedSizeBytes: data.editedSizeBytes ?? 0,
|
||||||
|
width: data.width ?? 0,
|
||||||
|
height: data.height ?? 0,
|
||||||
|
unchanged: data.unchanged === true,
|
||||||
|
});
|
||||||
|
setSavedVersion(Date.now());
|
||||||
|
if (data.tookOver === true) {
|
||||||
|
setAdvancedRetired(true);
|
||||||
|
setTakeOverMessage(
|
||||||
|
"Saved from the original file. The advanced recipe is retired and these sliders are now the saved look.",
|
||||||
|
);
|
||||||
|
}
|
||||||
onSaved();
|
onSaved();
|
||||||
onClose();
|
|
||||||
} catch {
|
} catch {
|
||||||
setSaveError("Network error while saving the edit.");
|
setSaveError("Network error while saving the edit.");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -762,7 +794,7 @@ export function PhotoViewer({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasSavedEdit = Boolean(photo.editedAt);
|
const hasSavedEdit = Boolean(photo.editedAt || saveResult);
|
||||||
const editedHref = `${src}?variant=edited&download=1&v=${savedVersion}`;
|
const editedHref = `${src}?variant=edited&download=1&v=${savedVersion}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -1456,6 +1488,31 @@ export function PhotoViewer({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{saveResult &&
|
||||||
|
(saveResult.unchanged ? (
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
|
||||||
|
>
|
||||||
|
No changes to apply — the saved version is already the
|
||||||
|
advanced editor's render. Move a slider to save your own
|
||||||
|
adjustments on top of it.
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
role="status"
|
||||||
|
className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs"
|
||||||
|
>
|
||||||
|
<p className="font-medium">Full-resolution JPEG saved.</p>
|
||||||
|
<p className="text-muted-foreground">
|
||||||
|
{saveResult.width > 0 && saveResult.height > 0
|
||||||
|
? `${saveResult.width} × ${saveResult.height} · `
|
||||||
|
: ""}
|
||||||
|
{formatBytes(saveResult.editedSizeBytes)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
|
||||||
{hasSavedEdit && (
|
{hasSavedEdit && (
|
||||||
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
|
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
|
||||||
<p className="text-xs font-medium">Download JPEG</p>
|
<p className="text-xs font-medium">Download JPEG</p>
|
||||||
|
|||||||
@@ -26,9 +26,8 @@ export function GuideShell({
|
|||||||
title: string;
|
title: string;
|
||||||
intro: string;
|
intro: string;
|
||||||
audience: string;
|
audience: string;
|
||||||
/** Not every role guide has a PDF snapshot yet. */
|
pdfHref: string;
|
||||||
pdfHref?: string;
|
pdfLabel: string;
|
||||||
pdfLabel?: string;
|
|
||||||
sections: GuideSectionLink[];
|
sections: GuideSectionLink[];
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
@@ -44,14 +43,12 @@ export function GuideShell({
|
|||||||
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
|
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
All training
|
All training
|
||||||
</Link>
|
</Link>
|
||||||
{pdfHref && pdfLabel ? (
|
<Button asChild size="sm">
|
||||||
<Button asChild size="sm">
|
<a href={pdfHref} download>
|
||||||
<a href={pdfHref} download>
|
<Download aria-hidden="true" />
|
||||||
<Download aria-hidden="true" />
|
{pdfLabel}
|
||||||
{pdfLabel}
|
</a>
|
||||||
</a>
|
</Button>
|
||||||
</Button>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<header className="space-y-3">
|
<header className="space-y-3">
|
||||||
|
|||||||
+2
-6
@@ -32,7 +32,6 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
|
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
|
||||||
import { isMentorReady } from "@/domain/mentor";
|
import { isMentorReady } from "@/domain/mentor";
|
||||||
import { enqueueAssignmentProposed } from "@/db/outbox";
|
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
|
||||||
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
||||||
@@ -350,23 +349,20 @@ export async function applyAutoFill(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
if (existing.length > 0) continue;
|
if (existing.length > 0) continue;
|
||||||
|
|
||||||
const assignmentId = uuidv7();
|
|
||||||
const now = new Date();
|
|
||||||
await db.transaction(async (tx) => {
|
await db.transaction(async (tx) => {
|
||||||
await tx.insert(assignments).values({
|
await tx.insert(assignments).values({
|
||||||
id: assignmentId,
|
id: uuidv7(),
|
||||||
slotId: proposal.slotId,
|
slotId: proposal.slotId,
|
||||||
userId: proposal.userId,
|
userId: proposal.userId,
|
||||||
status: "proposed",
|
status: "proposed",
|
||||||
source: "auto",
|
source: "auto",
|
||||||
assignedBy: opts.actorId,
|
assignedBy: opts.actorId,
|
||||||
assignedAt: now,
|
assignedAt: new Date(),
|
||||||
});
|
});
|
||||||
await tx
|
await tx
|
||||||
.update(slots)
|
.update(slots)
|
||||||
.set({ status: "proposed" })
|
.set({ status: "proposed" })
|
||||||
.where(eq(slots.id, proposal.slotId));
|
.where(eq(slots.id, proposal.slotId));
|
||||||
await enqueueAssignmentProposed(tx, assignmentId, { now });
|
|
||||||
});
|
});
|
||||||
written++;
|
written++;
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-65
@@ -17,11 +17,9 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
|
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
|
||||||
import { alias } from "drizzle-orm/pg-core";
|
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
assignmentProposals,
|
|
||||||
auditLog,
|
auditLog,
|
||||||
coverageRequests,
|
coverageRequests,
|
||||||
roles,
|
roles,
|
||||||
@@ -32,10 +30,7 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { auditRow } from "@/db/audit";
|
import { auditRow } from "@/db/audit";
|
||||||
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
|
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
|
||||||
import {
|
import { cancelAssignmentNotifications, enqueuePublishNotifications } from "@/db/outbox";
|
||||||
cancelAssignmentNotifications,
|
|
||||||
enqueueAssignmentProposed,
|
|
||||||
} from "@/db/outbox";
|
|
||||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -348,71 +343,17 @@ export async function resolveCoverageRequest(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// The replacement is a proposed seat, so they get the same accept /
|
// A published week's mail was written at publish time; the replacement
|
||||||
// decline / propose-another-Sunday email as any other proposal. A
|
// needs its own rows. Both helpers are idempotent on dedupe_key.
|
||||||
// published week also needs its reminders topped up for the new seat.
|
if (replacementUserId && request.instanceStatus === "published") {
|
||||||
if (newAssignmentId) {
|
await enqueuePublishNotifications(tx, request.instanceId, { now });
|
||||||
await enqueueAssignmentProposed(tx, newAssignmentId, { now });
|
await enqueueRemindersForInstance(tx, request.instanceId, { now });
|
||||||
if (request.instanceStatus === "published") {
|
|
||||||
await enqueueRemindersForInstance(tx, request.instanceId, { now });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return { status: "approved", assignmentId: newAssignmentId };
|
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<string>`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 */
|
/* ------------------------------------------------------------------ utils */
|
||||||
|
|
||||||
function auditLogRow(actorId: string, requestId: string, status: string) {
|
function auditLogRow(actorId: string, requestId: string, status: string) {
|
||||||
|
|||||||
+4
-20
@@ -11,17 +11,13 @@
|
|||||||
* - a `published` instance is never modified here,
|
* - a `published` instance is never modified here,
|
||||||
* - past instances fall outside the window and are never deleted.
|
* - past instances fall outside the window and are never deleted.
|
||||||
*
|
*
|
||||||
* Each new instance's seats are materialized immediately via D3's
|
* Slot materialization from role requirements is D3; this unit only owns the
|
||||||
* `materializeSlotsForInstance`, so a generated week is assignable without
|
* instance rows.
|
||||||
* 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 { and, count, eq, gte } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { roles, services, serviceInstances } from "@/db/schema";
|
import { services, serviceInstances } from "@/db/schema";
|
||||||
import { materializeSlotsForInstance } from "@/db/slots";
|
|
||||||
import type { RolePlanInput } from "@/domain/slots";
|
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
import { localToUtc } from "@/lib/tz";
|
import { localToUtc } from "@/lib/tz";
|
||||||
import {
|
import {
|
||||||
@@ -56,13 +52,6 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise<Gen
|
|||||||
|
|
||||||
const active = await db.select().from(services).where(eq(services.active, true));
|
const active = await db.select().from(services).where(eq(services.active, true));
|
||||||
|
|
||||||
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
|
||||||
const rolesInput: RolePlanInput[] = roleRows.map((role) => ({
|
|
||||||
id: role.id,
|
|
||||||
callTimeOffsetMinutes: role.callTimeOffsetMinutes,
|
|
||||||
defaultHeadcount: role.defaultHeadcount,
|
|
||||||
}));
|
|
||||||
|
|
||||||
let created = 0;
|
let created = 0;
|
||||||
for (const service of active) {
|
for (const service of active) {
|
||||||
const plan: ServicePlanInput = {
|
const plan: ServicePlanInput = {
|
||||||
@@ -89,12 +78,7 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise<Gen
|
|||||||
target: [serviceInstances.serviceId, serviceInstances.startsAt],
|
target: [serviceInstances.serviceId, serviceInstances.startsAt],
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
if (row) {
|
if (row) created++;
|
||||||
created++;
|
|
||||||
if (row.startsAt) {
|
|
||||||
await materializeSlotsForInstance(row.id, row.startsAt, rolesInput);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+51
-176
@@ -24,10 +24,7 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { APP_ORIGIN } from "@/auth/magic-link";
|
import { APP_ORIGIN } from "@/auth/magic-link";
|
||||||
import { notificationDedupeKey } from "@/domain/notifications";
|
import { notificationDedupeKey } from "@/domain/notifications";
|
||||||
import {
|
import { renderAssignmentPublishedEmail } from "@/domain/templates";
|
||||||
renderAssignmentProposedEmail,
|
|
||||||
renderAssignmentPublishedEmail,
|
|
||||||
} from "@/domain/templates";
|
|
||||||
import { respondUrl, signRespondToken } from "@/lib/respond";
|
import { respondUrl, signRespondToken } from "@/lib/respond";
|
||||||
import { formatInTimezone } from "@/lib/tz";
|
import { formatInTimezone } from "@/lib/tz";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -88,7 +85,51 @@ export async function enqueuePublishNotifications(
|
|||||||
let enqueued = 0;
|
let enqueued = 0;
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (!row.startsAt) continue;
|
if (!row.startsAt) continue;
|
||||||
const email = await buildAssignmentEmail(row, origin, false);
|
const timeZone = row.timeZone;
|
||||||
|
const occursOnLabel = formatInTimezone(row.startsAt, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
weekday: "long",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
});
|
||||||
|
const startTimeLabel = formatInTimezone(row.startsAt, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
const callTimeLabel = row.callTime
|
||||||
|
? formatInTimezone(row.callTime, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
// Two single-purpose links per assignment (E4): confirm and decline.
|
||||||
|
const confirm = await signRespondToken({
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
userId: row.userId,
|
||||||
|
action: "confirm",
|
||||||
|
});
|
||||||
|
const decline = await signRespondToken({
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
userId: row.userId,
|
||||||
|
action: "decline",
|
||||||
|
});
|
||||||
|
const confirmUrl = respondUrl(origin, confirm.token, "confirm");
|
||||||
|
const declineUrl = respondUrl(origin, decline.token, "decline");
|
||||||
|
|
||||||
|
const rendered = renderAssignmentPublishedEmail({
|
||||||
|
volunteerFirstName: row.firstName,
|
||||||
|
roleName: row.roleName,
|
||||||
|
serviceName: row.serviceName,
|
||||||
|
occursOnLabel,
|
||||||
|
startTimeLabel,
|
||||||
|
callTimeLabel,
|
||||||
|
location: row.location ?? row.serviceName,
|
||||||
|
confirmUrl,
|
||||||
|
declineUrl,
|
||||||
|
});
|
||||||
|
|
||||||
const inserted = await executor
|
const inserted = await executor
|
||||||
.insert(notifications)
|
.insert(notifications)
|
||||||
@@ -102,12 +143,11 @@ export async function enqueuePublishNotifications(
|
|||||||
slotId: row.slotId,
|
slotId: row.slotId,
|
||||||
toAddress: row.email,
|
toAddress: row.email,
|
||||||
payloadJson: JSON.stringify({
|
payloadJson: JSON.stringify({
|
||||||
subject: email.subject,
|
subject: rendered.subject,
|
||||||
html: email.html,
|
html: rendered.html,
|
||||||
text: email.text,
|
text: rendered.text,
|
||||||
confirmUrl: email.confirmUrl,
|
confirmUrl,
|
||||||
declineUrl: email.declineUrl,
|
declineUrl,
|
||||||
alternativeUrl: email.alternativeUrl,
|
|
||||||
}),
|
}),
|
||||||
dedupeKey: notificationDedupeKey(
|
dedupeKey: notificationDedupeKey(
|
||||||
"assignment.published",
|
"assignment.published",
|
||||||
@@ -128,171 +168,6 @@ export async function enqueuePublishNotifications(
|
|||||||
return enqueued;
|
return enqueued;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The assignment fields every assignment email renders from. */
|
|
||||||
interface AssignmentEmailRow {
|
|
||||||
assignmentId: string;
|
|
||||||
slotId: string;
|
|
||||||
userId: string;
|
|
||||||
email: string;
|
|
||||||
firstName: string;
|
|
||||||
timeZone: string;
|
|
||||||
roleName: string;
|
|
||||||
serviceName: string;
|
|
||||||
location: string | null;
|
|
||||||
startsAt: Date | null;
|
|
||||||
callTime: Date | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Render an assignment email and mint its single-purpose links. */
|
|
||||||
async function buildAssignmentEmail(
|
|
||||||
row: AssignmentEmailRow,
|
|
||||||
origin: string,
|
|
||||||
includeAlternative: boolean,
|
|
||||||
): Promise<{
|
|
||||||
subject: string;
|
|
||||||
html: string;
|
|
||||||
text: string;
|
|
||||||
confirmUrl: string;
|
|
||||||
declineUrl: string;
|
|
||||||
alternativeUrl: string | null;
|
|
||||||
}> {
|
|
||||||
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<number> {
|
|
||||||
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
|
* 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
|
* "you're serving" reminder queued (§6.1 `cancel-if-declined`). Sent rows are
|
||||||
|
|||||||
+5
-202
@@ -8,11 +8,10 @@
|
|||||||
* and writes the audit row — all in one transaction.
|
* and writes the audit row — all in one transaction.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, asc, eq, gt, ne } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
assignmentProposals,
|
|
||||||
auditLog,
|
auditLog,
|
||||||
roles,
|
roles,
|
||||||
serviceInstances,
|
serviceInstances,
|
||||||
@@ -24,9 +23,8 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { auditRow } from "@/db/audit";
|
import { auditRow } from "@/db/audit";
|
||||||
import { cancelAssignmentNotifications } from "@/db/outbox";
|
import { cancelAssignmentNotifications } from "@/db/outbox";
|
||||||
import type { DecisionAction } from "@/lib/respond";
|
import type { RespondAction } from "@/lib/respond";
|
||||||
import { formatInTimezone } from "@/lib/tz";
|
import { formatInTimezone } from "@/lib/tz";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
|
||||||
|
|
||||||
/** Only a live assignment can be confirmed or declined. */
|
/** Only a live assignment can be confirmed or declined. */
|
||||||
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
|
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
|
||||||
@@ -35,9 +33,7 @@ export type RespondFailureCode =
|
|||||||
| "unknown_assignment"
|
| "unknown_assignment"
|
||||||
| "wrong_volunteer"
|
| "wrong_volunteer"
|
||||||
| "not_actionable"
|
| "not_actionable"
|
||||||
| "already_used"
|
| "already_used";
|
||||||
| "unknown_instance"
|
|
||||||
| "invalid_alternative";
|
|
||||||
|
|
||||||
export class RespondError extends Error {
|
export class RespondError extends Error {
|
||||||
readonly code: RespondFailureCode;
|
readonly code: RespondFailureCode;
|
||||||
@@ -128,7 +124,7 @@ export async function getRespondAssignment(
|
|||||||
export async function respondToAssignment(input: {
|
export async function respondToAssignment(input: {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
action: DecisionAction;
|
action: RespondAction;
|
||||||
via?: ConfirmedVia;
|
via?: ConfirmedVia;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||||
@@ -213,7 +209,7 @@ export async function respondToAssignment(input: {
|
|||||||
export async function applyRespond(input: {
|
export async function applyRespond(input: {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
action: DecisionAction;
|
action: RespondAction;
|
||||||
jti: string;
|
jti: string;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||||
@@ -305,196 +301,3 @@ export async function applyRespond(input: {
|
|||||||
|
|
||||||
return result;
|
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<AlternativeOption[] | null> {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1249,53 +1249,6 @@ 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 */
|
/* ------------------------------------------------------------ run sheet */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1535,7 +1488,6 @@ export const schema = {
|
|||||||
eventVideos,
|
eventVideos,
|
||||||
announcements,
|
announcements,
|
||||||
coverageRequests,
|
coverageRequests,
|
||||||
assignmentProposals,
|
|
||||||
serviceRunSheets,
|
serviceRunSheets,
|
||||||
runSheetItems,
|
runSheetItems,
|
||||||
serviceChecklistItems,
|
serviceChecklistItems,
|
||||||
|
|||||||
+14
-27
@@ -6,13 +6,11 @@
|
|||||||
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
|
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
|
||||||
* assignments on an existing seat.
|
* assignments on an existing seat.
|
||||||
*
|
*
|
||||||
* Per §5.1, a published week's slot set is owned by the publish flow, so
|
* Per §5.1, slots are created only for non-published instances: a published
|
||||||
* existing seats are never touched. The one exception is a published instance
|
* week's slot set is owned by the publish flow, not the generator.
|
||||||
* with zero seats: that week was published before any seats existed and can
|
|
||||||
* never become assignable unless the generator repairs it.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { eq, gte, sql } from "drizzle-orm";
|
import { and, gte, ne } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { roles, serviceInstances, slots } from "@/db/schema";
|
import { roles, serviceInstances, slots } from "@/db/schema";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -57,33 +55,22 @@ export async function materializeSlotsForInstance(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Materialize seats for every instance at or after `now`. A published instance
|
* Materialize slots for every non-published instance at or after `now`.
|
||||||
* with existing seats is left untouched (its slot set is owned by the publish
|
* Published instances are left untouched (their slot set is owned by the
|
||||||
* flow), but a published instance with no seats at all is repaired — otherwise
|
* publish flow).
|
||||||
* it stays permanently unassignable.
|
|
||||||
*/
|
*/
|
||||||
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
|
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
|
||||||
const reference = now ?? new Date();
|
const reference = now ?? new Date();
|
||||||
const instances = await db
|
const instances = await db
|
||||||
.select({
|
.select()
|
||||||
id: serviceInstances.id,
|
|
||||||
startsAt: serviceInstances.startsAt,
|
|
||||||
status: serviceInstances.status,
|
|
||||||
seatCount: sql<number>`count(${slots.id})`,
|
|
||||||
})
|
|
||||||
.from(serviceInstances)
|
.from(serviceInstances)
|
||||||
.leftJoin(slots, eq(slots.serviceInstanceId, serviceInstances.id))
|
.where(
|
||||||
.where(gte(serviceInstances.startsAt, reference))
|
and(
|
||||||
.groupBy(
|
gte(serviceInstances.startsAt, reference),
|
||||||
serviceInstances.id,
|
ne(serviceInstances.status, "published"),
|
||||||
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 roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
||||||
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
|
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
|
||||||
id: r.id,
|
id: r.id,
|
||||||
@@ -92,10 +79,10 @@ export async function materializeSlots(now?: Date): Promise<{ created: number; i
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
let created = 0;
|
let created = 0;
|
||||||
for (const inst of target) {
|
for (const inst of instances) {
|
||||||
if (!inst.startsAt) continue;
|
if (!inst.startsAt) continue;
|
||||||
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
|
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { created, instances: target.length };
|
return { created, instances: instances.length };
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-21
@@ -9,7 +9,7 @@
|
|||||||
* patch that omits a field (say, the phone) never nulls it out.
|
* patch that omits a field (say, the phone) never nulls it out.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, asc, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
|
import { and, asc, eq, isNull, ne, or, sql } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { assignments, userSkills, users } from "@/db/schema";
|
import { assignments, userSkills, users } from "@/db/schema";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
@@ -197,26 +197,6 @@ export async function hasAssignmentHistory(userId: string): Promise<boolean> {
|
|||||||
return Boolean(row);
|
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<boolean> {
|
|
||||||
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. */
|
/** Active admins who could still sign in, excluding the person being changed. */
|
||||||
export async function countOtherActiveAdmins(excludeUserId: string): Promise<number> {
|
export async function countOtherActiveAdmins(excludeUserId: string): Promise<number> {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
|
|||||||
@@ -1,9 +1,5 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import {
|
import { escapeHtml, renderAssignmentPublishedEmail } from "./templates";
|
||||||
escapeHtml,
|
|
||||||
renderAssignmentProposedEmail,
|
|
||||||
renderAssignmentPublishedEmail,
|
|
||||||
} from "./templates";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* E3 — email templates.
|
* E3 — email templates.
|
||||||
@@ -60,25 +56,6 @@ 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", () => {
|
describe("escapeHtml", () => {
|
||||||
it("escapes the five HTML-significant characters", () => {
|
it("escapes the five HTML-significant characters", () => {
|
||||||
expect(escapeHtml(`&<>"'`)).toBe("&<>"'");
|
expect(escapeHtml(`&<>"'`)).toBe("&<>"'");
|
||||||
|
|||||||
+3
-31
@@ -24,8 +24,6 @@ export interface AssignmentEmailContext {
|
|||||||
location: string;
|
location: string;
|
||||||
confirmUrl: string;
|
confirmUrl: string;
|
||||||
declineUrl: string;
|
declineUrl: string;
|
||||||
/** Present on the proposed email: "I can serve another Sunday". */
|
|
||||||
alternativeUrl?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RenderedEmail {
|
export interface RenderedEmail {
|
||||||
@@ -53,21 +51,6 @@ export function renderAssignmentPublishedEmail(
|
|||||||
return renderAssignmentEmail(ctx, `You're on ${ctx.roleName} — ${ctx.occursOnLabel}`);
|
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. */
|
/** A reminder for the same assignment (E7): same body, reminder subject. */
|
||||||
export function renderAssignmentReminderEmail(
|
export function renderAssignmentReminderEmail(
|
||||||
ctx: AssignmentEmailContext,
|
ctx: AssignmentEmailContext,
|
||||||
@@ -153,7 +136,6 @@ export function renderEventReminderEmail(
|
|||||||
function renderAssignmentEmail(
|
function renderAssignmentEmail(
|
||||||
ctx: AssignmentEmailContext,
|
ctx: AssignmentEmailContext,
|
||||||
subject: string,
|
subject: string,
|
||||||
proposed = false,
|
|
||||||
): RenderedEmail {
|
): RenderedEmail {
|
||||||
const callTime = ctx.callTimeLabel ?? CALL_TIME_UNSET;
|
const callTime = ctx.callTimeLabel ?? CALL_TIME_UNSET;
|
||||||
const firstName = escapeHtml(ctx.volunteerFirstName);
|
const firstName = escapeHtml(ctx.volunteerFirstName);
|
||||||
@@ -165,14 +147,11 @@ function renderAssignmentEmail(
|
|||||||
const location = escapeHtml(ctx.location);
|
const location = escapeHtml(ctx.location);
|
||||||
const confirmUrl = escapeHtml(ctx.confirmUrl);
|
const confirmUrl = escapeHtml(ctx.confirmUrl);
|
||||||
const declineUrl = escapeHtml(ctx.declineUrl);
|
const declineUrl = escapeHtml(ctx.declineUrl);
|
||||||
const alternativeUrl = ctx.alternativeUrl
|
|
||||||
? escapeHtml(ctx.alternativeUrl)
|
|
||||||
: null;
|
|
||||||
|
|
||||||
const html = `<!doctype html>
|
const html = `<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<body style="font-family: system-ui, sans-serif; line-height: 1.5; color: #111827;">
|
<body style="font-family: system-ui, sans-serif; line-height: 1.5; color: #111827;">
|
||||||
<h1 style="font-size: 20px;">${firstName}, ${proposed ? `can you serve on ${roleName}?` : `you're on ${roleName}`}</h1>
|
<h1 style="font-size: 20px;">${firstName}, you're on ${roleName}</h1>
|
||||||
<p>
|
<p>
|
||||||
${serviceName}<br />
|
${serviceName}<br />
|
||||||
${occursOn} at ${startTime}<br />
|
${occursOn} at ${startTime}<br />
|
||||||
@@ -183,21 +162,17 @@ function renderAssignmentEmail(
|
|||||||
<a href="${confirmUrl}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Confirm</a>
|
<a href="${confirmUrl}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Confirm</a>
|
||||||
|
|
||||||
<a href="${declineUrl}" style="display:inline-block;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Can't make it</a>
|
<a href="${declineUrl}" style="display:inline-block;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Can't make it</a>
|
||||||
${alternativeUrl ? `<a href="${alternativeUrl}" style="display:inline-block;margin-left:8px;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Propose another Sunday</a>` : ""}
|
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<p style="font-size: 12px; color: #6b7280;">
|
||||||
No login needed — the links above are single-use. If you can't serve,
|
No login needed — the links above are single-use. If you can't serve,
|
||||||
please decline so a coordinator can find cover, or propose another
|
please decline so a coordinator can find cover.
|
||||||
Sunday you are available.
|
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">Media Team Hub · Glenloch</p>
|
<p style="font-size: 12px; color: #6b7280;">Media Team Hub · Glenloch</p>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
|
|
||||||
const text = [
|
const text = [
|
||||||
proposed
|
`${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
|
||||||
? `${ctx.volunteerFirstName}, can you serve on ${ctx.roleName}?`
|
|
||||||
: `${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
|
|
||||||
"",
|
"",
|
||||||
ctx.serviceName,
|
ctx.serviceName,
|
||||||
`${ctx.occursOnLabel} at ${ctx.startTimeLabel}`,
|
`${ctx.occursOnLabel} at ${ctx.startTimeLabel}`,
|
||||||
@@ -206,9 +181,6 @@ function renderAssignmentEmail(
|
|||||||
"",
|
"",
|
||||||
"Confirm: " + ctx.confirmUrl,
|
"Confirm: " + ctx.confirmUrl,
|
||||||
"Can't make it: " + ctx.declineUrl,
|
"Can't make it: " + ctx.declineUrl,
|
||||||
...(ctx.alternativeUrl
|
|
||||||
? ["Propose another Sunday: " + ctx.alternativeUrl]
|
|
||||||
: []),
|
|
||||||
"",
|
"",
|
||||||
"No login needed — the links are single-use.",
|
"No login needed — the links are single-use.",
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|||||||
@@ -42,18 +42,4 @@ describe("respond tokens", () => {
|
|||||||
expect(url.startsWith("https://media.test/respond?t=")).toBe(true);
|
expect(url.startsWith("https://media.test/respond?t=")).toBe(true);
|
||||||
expect(url.endsWith("&a=decline")).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);
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|||||||
+4
-7
@@ -1,13 +1,11 @@
|
|||||||
/**
|
/**
|
||||||
* Signed respond tokens — unit E4 (ARCHITECTURE §5.6).
|
* Signed respond tokens — unit E4 (ARCHITECTURE §5.6).
|
||||||
*
|
*
|
||||||
* Every assignment email carries single-purpose links:
|
* Every assignment email carries two single-purpose links:
|
||||||
* /respond?t=<jwt>&a=confirm | &a=decline | &a=alternative
|
* /respond?t=<jwt>&a=confirm | /respond?t=<jwt>&a=decline
|
||||||
*
|
*
|
||||||
* The JWT binds the assignment and volunteer (`{ assignmentId, userId, action,
|
* The JWT binds the assignment and volunteer (`{ assignmentId, userId, action,
|
||||||
* jti }`, HS256, +14d) so a link cannot be re-pointed at another assignment.
|
* 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.
|
* Single use is recorded by `jti` in `used_tokens` by the data layer.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -21,8 +19,7 @@ const SECRET = new TextEncoder().encode(
|
|||||||
"media-team-hub-dev-insecure-secret",
|
"media-team-hub-dev-insecure-secret",
|
||||||
);
|
);
|
||||||
|
|
||||||
export type DecisionAction = "confirm" | "decline";
|
export type RespondAction = "confirm" | "decline";
|
||||||
export type RespondAction = DecisionAction | "alternative";
|
|
||||||
|
|
||||||
export interface RespondTokenPayload {
|
export interface RespondTokenPayload {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
@@ -69,7 +66,7 @@ export async function verifyRespondToken(
|
|||||||
if (
|
if (
|
||||||
typeof assignmentId !== "string" ||
|
typeof assignmentId !== "string" ||
|
||||||
typeof userId !== "string" ||
|
typeof userId !== "string" ||
|
||||||
(action !== "confirm" && action !== "decline" && action !== "alternative") ||
|
(action !== "confirm" && action !== "decline") ||
|
||||||
typeof jti !== "string"
|
typeof jti !== "string"
|
||||||
) {
|
) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
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");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
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<TrainingGuideKey, TrainingGuide> = {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
@@ -60,7 +60,7 @@ export async function sendWelcomeEmail(
|
|||||||
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<p style="font-size: 12px; color: #6b7280;">
|
||||||
The link expires in 10 minutes and works once. If it has expired, open the
|
The link expires in 7 days and works once. If it has expired, open the
|
||||||
sign-in page and request a fresh link with this email address. After
|
sign-in page and request a fresh link with this email address. After
|
||||||
signing in you can set a password from your profile.
|
signing in you can set a password from your profile.
|
||||||
</p>
|
</p>
|
||||||
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
|
|||||||
`Sign in: ${user.email}`,
|
`Sign in: ${user.email}`,
|
||||||
`Username: ${user.username || user.email}`,
|
`Username: ${user.username || user.email}`,
|
||||||
"",
|
"",
|
||||||
`Open this link to sign in (expires in 10 minutes, single use):`,
|
`Open this link to sign in (expires in 7 days, single use):`,
|
||||||
url,
|
url,
|
||||||
"",
|
"",
|
||||||
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
||||||
|
|||||||
Reference in New Issue
Block a user