app: prayer requests' screens (APP-1.0-PLAN §4)

Ask for prayer (who will see it said plainly, the prayer team by default; for
members the first name or Anonymous, approved first; fully anonymous when the
church allows it; the emergency numbers, signed out too), Pray for others (the
shared list with "I prayed"), My prayer requests (state, what the team changed
or why it wasn't shared, the team's private replies, "Answered!", close,
delete). The admin's Prayer requests: waiting, open, escalated and closed;
approve, edit out details, don't share, reply, escalate; the settings. Pastoral
care sees open and escalated requests. The Prayer tab shows with either prayer
module and opens requests when the House of Prayer is off.

Checked in a browser on a throwaway PostgreSQL: a member asks, a coordinator
edits out a name and approves, another member sees the edited text and prays,
the sender sees the note and the count but not who; no page errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 11:05:26 +02:00
co-authored by Claude Opus 5.5
parent 6425a6a30d
commit 09e98f6b56
13 changed files with 606 additions and 8 deletions
+5
View File
@@ -101,6 +101,11 @@ export default async function Admin() {
House of Prayer: the week, who prays when, rules, campaigns, testimonies<span aria-hidden>›</span> House of Prayer: the week, who prays when, rules, campaigns, testimonies<span aria-hidden>›</span>
</Link> </Link>
)} )}
{o?.modules.includes("prayer-requests") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator", "pastoral_care"].includes(r)) && (
<Link href="/admin/requests" className="cca-card flex items-center justify-between font-semibold">
Prayer requests: approval, escalations, replies, settings<span aria-hidden>›</span>
</Link>
)}
<Link href="/" className="cca-btn-quiet">Back to the App</Link> <Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page> </Page>
); );
@@ -0,0 +1,29 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AdminRequests } from "@/components/requests/AdminRequests";
import { loadApp, loadMe } from "@/lib/load";
export const metadata: Metadata = { title: "Prayer requests · Admin", robots: { index: false, follow: false } };
const COORDINATORS = ["owner", "church_admin", "prayer_coordinator"];
/** Prayer requests for the prayer team (APP-1.0-PLAN §4, §10): coordinators and Pastoral care, with 2FA. */
export default async function AdminRequestsPage({ searchParams }: { searchParams: Promise<{ view?: string }> }) {
const [me, app, q] = await Promise.all([loadMe(), loadApp(), searchParams]);
if (!me || !me.mfa || !me.member.roles.some((r) => [...COORDINATORS, "pastoral_care"].includes(r))) redirect("/admin");
const coordinator = me.member.roles.some((r) => COORDINATORS.includes(r));
return (
<main className="mx-auto max-w-5xl space-y-6 px-4 py-10">
<div>
<Link href="/admin" className="text-sm text-gray-600 underline-offset-4 hover:underline">← Dashboard</Link>
<h1 className="mt-1 text-2xl font-semibold">Prayer requests</h1>
</div>
{app.modules.includes("prayer-requests") ? (
<AdminRequests coordinator={coordinator} initialView={(["queue", "open", "escalated", "closed", "settings"].includes(q.view ?? "") ? q.view : "queue") as "queue"} />
) : (
<p className="text-gray-600">Prayer requests are switched off. An Owner or Church admin can switch them on in Settings → Modules.</p>
)}
</main>
);
}
+3
View File
@@ -34,6 +34,9 @@ export default async function Me() {
{app.modules.includes("house-of-prayer") && ( {app.modules.includes("house-of-prayer") && (
<Link href="/me/prayer" className="cca-card flex min-h-11 items-center justify-between font-semibold">My prayer<span aria-hidden>›</span></Link> <Link href="/me/prayer" className="cca-card flex min-h-11 items-center justify-between font-semibold">My prayer<span aria-hidden>›</span></Link>
)} )}
{app.modules.includes("prayer-requests") && (
<Link href="/me/requests" className="cca-card flex min-h-11 items-center justify-between font-semibold">My prayer requests<span aria-hidden>›</span></Link>
)}
{roles.length > 0 && ( {roles.length > 0 && (
<section className="cca-card space-y-2"> <section className="cca-card space-y-2">
<h2 className="cca-h2">The App&apos;s admin</h2> <h2 className="cca-h2">The App&apos;s admin</h2>
@@ -0,0 +1,37 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { MyRequests } from "@/components/requests/MyRequests";
import { loadMe, signInHref } from "@/lib/load";
import { requireModule } from "@/lib/module";
import type { MyRequest } from "@/lib/requests";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "My prayer requests", robots: { index: false, follow: false } };
/** The member's own prayer requests (APP-1.0-PLAN §4). */
export default async function MyRequestsPage() {
await requireModule("prayer-requests");
const me = await loadMe();
if (!me) {
return (
<AppShell footer={false}>
<h1 className="cca-h1">My prayer requests</h1>
<section className="cca-card space-y-3"><p>Sign in to see your prayer requests.</p><a href={signInHref("/me/requests")} className="cca-btn">Sign in</a></section>
</AppShell>
);
}
const data = await backendGet<{ requests: MyRequest[] }>("/api/v1/me/requests");
return (
<AppShell footer={false}>
<h1 className="cca-h1">My prayer requests</h1>
{!data ? (
<section className="cca-card"><p className="cca-muted">Your requests can&apos;t be loaded right now. Please try again in a minute.</p></section>
) : data.requests.length ? (
<MyRequests list={data.requests} />
) : (
<section className="cca-card space-y-3"><p>You haven&apos;t asked for prayer yet.</p><Link href="/prayer/ask" className="cca-btn">Ask for prayer</Link></section>
)}
</AppShell>
);
}
@@ -0,0 +1,38 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { AskForm } from "@/components/requests/AskForm";
import { firstName, loadMe, signInHref } from "@/lib/load";
import { requireModule } from "@/lib/module";
import type { RequestForm } from "@/lib/requests";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "Ask for prayer", robots: { index: false, follow: false } };
const FALLBACK: RequestForm = { anonymousAllowed: false, emergencyNumbers: [], closeAfterDays: 30 };
/** Ask for prayer (APP-1.0-PLAN §4). The emergency numbers show signed out too. */
export default async function Ask() {
await requireModule("prayer-requests");
const [me, form] = await Promise.all([loadMe(), backendGet<RequestForm>("/api/v1/requests/form")]);
return (
<AppShell footer={false}>
<h1 className="cca-h1">Ask for prayer</h1>
{me ? (
<AskForm form={form ?? FALLBACK} firstName={firstName(me.member.name)} />
) : (
<>
<section className="cca-card space-y-3">
<p>Sign in with your church account to ask for prayer. Only the people you choose will see it.</p>
<a href={signInHref("/prayer/ask")} className="cca-btn">Sign in</a>
</section>
{(form?.emergencyNumbers.length ?? 0) > 0 && (
<section className="cca-card space-y-1 border-amber-300 bg-amber-50">
<h2 className="font-semibold">If you or someone else is in danger, call:</h2>
{form!.emergencyNumbers.map((n) => <p key={n.number}><a className="font-semibold underline" href={`tel:${n.number.replace(/\s+/g, "")}`}>{n.label}: {n.number}</a></p>)}
</section>
)}
</>
)}
</AppShell>
);
}
+11 -1
View File
@@ -3,7 +3,8 @@ import Link from "next/link";
import { AppShell } from "@/components/AppShell"; import { AppShell } from "@/components/AppShell";
import { CampaignCard } from "@/components/prayer/CampaignCard"; import { CampaignCard } from "@/components/prayer/CampaignCard";
import { PrayerClock } from "@/components/prayer/PrayerClock"; import { PrayerClock } from "@/components/prayer/PrayerClock";
import { loadMe } from "@/lib/load"; import { redirect } from "next/navigation";
import { loadApp, loadMe } from "@/lib/load";
import { requireModule } from "@/lib/module"; import { requireModule } from "@/lib/module";
import { dayName } from "@/lib/prayer"; import { dayName } from "@/lib/prayer";
import { loadCampaign, loadDay, loadTestimonies } from "@/lib/prayerServer"; import { loadCampaign, loadDay, loadTestimonies } from "@/lib/prayerServer";
@@ -18,8 +19,11 @@ const DATE = /^\d{4}-\d{2}-\d{2}$/;
* (`?day=`; `&slot=` opens that slot's booking sheet, after a sign-in), testimonies. * (`?day=`; `&slot=` opens that slot's booking sheet, after a sign-in), testimonies.
*/ */
export default async function Prayer({ searchParams }: { searchParams: Promise<{ day?: string; slot?: string }> }) { export default async function Prayer({ searchParams }: { searchParams: Promise<{ day?: string; slot?: string }> }) {
const app = await loadApp();
if (!app.modules.includes("house-of-prayer") && app.modules.includes("prayer-requests")) redirect("/prayer/requests");
await requireModule("house-of-prayer"); await requireModule("house-of-prayer");
const q = await searchParams; const q = await searchParams;
const requests = app.modules.includes("prayer-requests");
const [me, day, campaign, testimonies] = await Promise.all([ const [me, day, campaign, testimonies] = await Promise.all([
loadMe(), loadMe(),
loadDay(q.day && DATE.test(q.day) ? q.day : null), loadDay(q.day && DATE.test(q.day) ? q.day : null),
@@ -34,6 +38,12 @@ export default async function Prayer({ searchParams }: { searchParams: Promise<{
{me && <Link href="/me/prayer" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">My prayer</Link>} {me && <Link href="/me/prayer" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">My prayer</Link>}
</div> </div>
{campaign && <CampaignCard campaign={campaign} />} {campaign && <CampaignCard campaign={campaign} />}
{requests && (
<nav aria-label="Prayer requests" className="grid grid-cols-2 gap-3">
<Link href="/prayer/ask" className="cca-btn">Ask for prayer</Link>
<Link href="/prayer/requests" className="cca-btn-quiet">Pray for others</Link>
</nav>
)}
{day ? ( {day ? (
<PrayerClock key={day.date} initial={day} signedIn={!!me} openSlot={slot} /> <PrayerClock key={day.date} initial={day} signedIn={!!me} openSlot={slot} />
) : ( ) : (
@@ -0,0 +1,38 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { SharedList } from "@/components/requests/SharedList";
import { loadMe, signInHref } from "@/lib/load";
import { requireModule } from "@/lib/module";
import type { SharedRequest } from "@/lib/requests";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "Pray for others", robots: { index: false, follow: false } };
/** Requests shared with members (APP-1.0-PLAN §4): signed-in members only, never public. */
export default async function Requests() {
await requireModule("prayer-requests");
const me = await loadMe();
const data = me ? await backendGet<{ requests: SharedRequest[] }>("/api/v1/requests") : null;
return (
<AppShell footer={false}>
<div className="flex items-end justify-between gap-3">
<h1 className="cca-h1">Pray for others</h1>
{me && <Link href="/me/requests" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">My requests</Link>}
</div>
<Link href="/prayer/ask" className="cca-btn w-full">Ask for prayer</Link>
{!me ? (
<section className="cca-card space-y-3">
<p>Prayer requests are shared only with the church&apos;s members. Sign in to see them and pray.</p>
<a href={signInHref("/prayer/requests")} className="cca-btn-quiet">Sign in</a>
</section>
) : !data ? (
<section className="cca-card"><p className="cca-muted">The requests can&apos;t be loaded right now. Please try again in a minute.</p></section>
) : data.requests.length ? (
<SharedList initial={data.requests} />
) : (
<p className="cca-muted">No requests are shared right now.</p>
)}
</AppShell>
);
}
+10 -7
View File
@@ -5,18 +5,21 @@ import { usePathname } from "next/navigation";
import { BookOpen, CalendarDays, Flame, Home, UserRound } from "lucide-react"; import { BookOpen, CalendarDays, Flame, Home, UserRound } from "lucide-react";
import type { AppModule } from "@/lib/load"; import type { AppModule } from "@/lib/load";
/** The bottom tab bar (APP-1.0-PLAN §1, P18): Home, Prayer, Events, Devotional, Me; only what's on. */ /**
* The bottom tab bar (APP-1.0-PLAN §1, P18): Home, Prayer, Events, Devotional, Me; only what's on.
* Prayer shows with the House of Prayer or prayer requests (it opens requests when only they are on).
*/
const TABS = [ const TABS = [
{ href: "/", label: "Home", icon: Home, module: null }, { href: "/", label: "Home", icon: Home, modules: null },
{ href: "/prayer", label: "Prayer", icon: Flame, module: "house-of-prayer" }, { href: "/prayer", label: "Prayer", icon: Flame, modules: ["house-of-prayer", "prayer-requests"] },
{ href: "/events", label: "Events", icon: CalendarDays, module: "events" }, { href: "/events", label: "Events", icon: CalendarDays, modules: ["events"] },
{ href: "/devotional", label: "Devotional", icon: BookOpen, module: "devotionals" }, { href: "/devotional", label: "Devotional", icon: BookOpen, modules: ["devotionals"] },
{ href: "/me", label: "Me", icon: UserRound, module: null }, { href: "/me", label: "Me", icon: UserRound, modules: null },
] as const; ] as const;
export function TabBar({ modules }: { modules: AppModule[] }) { export function TabBar({ modules }: { modules: AppModule[] }) {
const path = usePathname(); const path = usePathname();
const tabs = TABS.filter((t) => !t.module || modules.includes(t.module)); const tabs = TABS.filter((t) => !t.modules || t.modules.some((m) => modules.includes(m as AppModule)));
return ( return (
<nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-20 border-t border-gray-200 bg-white pb-[env(safe-area-inset-bottom)]"> <nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-20 border-t border-gray-200 bg-white pb-[env(safe-area-inset-bottom)]">
<ul className="mx-auto flex h-16 max-w-xl"> <ul className="mx-auto flex h-16 max-w-xl">
@@ -0,0 +1,175 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { errorMessage } from "@/lib/prayer";
import { shortDate, STATUS_NAMES, type RequestForm, type TeamRequest } from "@/lib/requests";
type View = "queue" | "open" | "escalated" | "closed" | "settings";
type Msg = { kind: "ok" | "error"; text: string } | null;
async function call<T>(method: string, path: string, body?: object): Promise<{ ok: true; data: T } | { ok: false; error: string }> {
try {
const res = await fetch(`/api/v1/admin/requests${path}`, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined, cache: "no-store" });
if (!res.ok) return { ok: false, error: await errorMessage(res) };
return { ok: true, data: (await res.json()) as T };
} catch {
return { ok: false, error: "The App's server can't be reached. Please try again." };
}
}
const input = "mt-1 block w-full rounded-md border border-gray-300 px-2 py-2 text-sm";
/**
* Prayer requests for the prayer team (APP-1.0-PLAN §4, §10): the approval queue, open requests,
* escalations and closed ones; approve, redact, don't share, escalate, reply; the settings. Every
* list here shows senders, so every load is in the access log. Pastoral care sees open (prayer team
* only) and escalated requests, and can reply and escalate.
*/
export function AdminRequests({ coordinator, initialView }: { coordinator: boolean; initialView: View }) {
const views: { key: View; label: string }[] = coordinator
? [{ key: "queue", label: "Waiting for approval" }, { key: "open", label: "Open" }, { key: "escalated", label: "Escalated" }, { key: "closed", label: "Closed" }, { key: "settings", label: "Settings" }]
: [{ key: "open", label: "Open" }, { key: "escalated", label: "Escalated" }];
const [view, setView] = useState<View>(views.some((v) => v.key === initialView) ? initialView : views[0]!.key);
const [rows, setRows] = useState<TeamRequest[] | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [version, setVersion] = useState(0);
const load = useCallback(() => setVersion((v) => v + 1), []);
useEffect(() => {
if (view === "settings") return;
let live = true;
call<{ requests: TeamRequest[] }>("GET", `?view=${view}`).then((r) => {
if (!live) return;
if (r.ok) setRows(r.data.requests);
else setMsg({ kind: "error", text: r.error });
});
return () => { live = false; };
}, [view, version]);
async function act(path: string, body: object, ok: string) {
const r = await call<{ notified?: number; fallback?: boolean }>("POST", path, body);
if (!r.ok) return setMsg({ kind: "error", text: r.error });
const extra = r.data.notified !== undefined ? ` ${r.data.notified} ${r.data.fallback ? "Owner or Church admin (nobody has the Pastoral care role)" : "in Pastoral care"} told by email and WhatsApp.` : "";
setMsg({ kind: "ok", text: ok + extra });
void load();
}
return (
<div className="space-y-5">
<div role="tablist" aria-label="Prayer requests" className="flex flex-wrap gap-1 border-b border-gray-200">
{views.map((v) => (
<button key={v.key} role="tab" aria-selected={view === v.key} onClick={() => { setMsg(null); setRows(null); setView(v.key); }} className={`-mb-px border-b-2 px-3 py-2 text-sm font-medium ${view === v.key ? "border-brand text-brand-text" : "border-transparent text-gray-600 hover:text-gray-900"}`}>
{v.label}
</button>
))}
</div>
{msg && <p role={msg.kind === "error" ? "alert" : "status"} className={`rounded-md p-3 text-sm ${msg.kind === "error" ? "bg-red-50 text-red-800" : "bg-green-50 text-green-800"}`}>{msg.text}</p>}
{view === "settings" ? (
<Settings onSaved={(text) => setMsg({ kind: "ok", text })} onError={(text) => setMsg({ kind: "error", text })} />
) : !rows ? (
<p className="text-sm text-gray-600">Loading…</p>
) : rows.length === 0 ? (
<p className="text-sm text-gray-600">{view === "queue" ? "Nothing waiting for approval." : "None."}</p>
) : (
<>
<p className="text-xs text-gray-600">Opening this list is recorded in the access log. Never copy a request elsewhere.</p>
<ul className="space-y-4">
{rows.map((r) => <RequestCard key={r.id} r={r} coordinator={coordinator} act={act} />)}
</ul>
</>
)}
</div>
);
}
function RequestCard({ r, coordinator, act }: { r: TeamRequest; coordinator: boolean; act: (path: string, body: object, ok: string) => Promise<unknown> }) {
const [mode, setMode] = useState<null | "redact" | "remove" | "escalate" | "reply">(null);
const [text, setText] = useState(r.text);
const [note, setNote] = useState("");
const base = `/${r.id}`;
const done = () => { setMode(null); setNote(""); };
return (
<li className={`rounded-lg border bg-white p-5 shadow-sm ${r.escalated ? "border-red-300" : "border-gray-200"}`}>
<div className="flex flex-wrap items-start justify-between gap-2 text-sm">
<p className="font-medium">{r.submitter ? `${r.submitter.name} · ${r.submitter.email}${r.submitter.phone ? ` · ${r.submitter.phone}` : ""}` : "Sent anonymously"}</p>
<p className="text-gray-600">{shortDate(r.createdAt)} · {r.visibility === "team" ? "Prayer team only" : `Members (${r.showName ? "first name" : "Anonymous"})`} · {STATUS_NAMES[r.status]}</p>
</div>
{r.escalated && <p className="mt-2 rounded-md bg-red-50 p-2 text-sm text-red-800">Escalated {shortDate(r.escalated.at)}{r.escalated.note ? `: ${r.escalated.note}` : ""}</p>}
<p className="mt-3 whitespace-pre-line">{r.text}</p>
{r.redacted && <p className="mt-1 text-xs text-gray-500">Edited by the prayer team{r.redactionNote ? `: ${r.redactionNote}` : ""}</p>}
{r.updates.map((u) => (
<p key={u.id} className={`mt-2 rounded-md p-2 text-sm ${u.author === "team" ? "bg-gray-50" : "bg-brand-tint"}`}><span className="font-semibold">{u.author === "team" ? "Prayer team (to the sender)" : "Sender"}:</span> {u.text}</p>
))}
{r.prayedCount > 0 && <p className="mt-2 text-sm text-gray-600">{r.prayedCount} prayed</p>}
{!r.closedAt && (
<div className="mt-4 flex flex-wrap gap-2">
{coordinator && r.visibility === "members" && r.moderation !== "approved" && !r.escalated && <button className="cca-btn !min-h-9" onClick={() => act(`${base}/approve`, {}, "Shared with members.")}>Approve</button>}
{coordinator && <button className="cca-btn-quiet !min-h-9" onClick={() => setMode("redact")}>Edit out details</button>}
{coordinator && r.visibility === "members" && r.moderation !== "removed" && <button className="cca-btn-quiet !min-h-9" onClick={() => setMode("remove")}>Don&apos;t share</button>}
<button className="cca-btn-quiet !min-h-9" onClick={() => setMode("reply")}>Reply to the sender</button>
{!r.escalated && <button className="cca-btn-quiet !min-h-9 !text-red-700" onClick={() => setMode("escalate")}>Escalate</button>}
</div>
)}
{mode && (
<form
className="mt-4 space-y-3 rounded-md bg-gray-50 p-4"
onSubmit={async (e) => {
e.preventDefault();
if (mode === "redact") await act(`${base}/redact`, { text, note }, "Saved; the sender is told what changed.");
if (mode === "remove") await act(`${base}/remove`, { reason: note }, "Not shared; the sender is told why.");
if (mode === "reply") await act(`${base}/reply`, { text: note }, "Reply sent to the sender.");
if (mode === "escalate") await act(`${base}/escalate`, { note }, "Escalated.");
done();
}}
>
{mode === "redact" && <label className="block text-sm font-medium">The request, with names or details taken out<textarea rows={4} value={text} onChange={(e) => setText(e.target.value)} className={input} /></label>}
{mode === "escalate" && <p className="text-sm">For danger, abuse or self-harm. Pastoral care is told at once by email and WhatsApp; it leaves the shared list; the sender sees nothing different.</p>}
<label className="block text-sm font-medium">
{mode === "redact" ? "What changed (the sender sees this)" : mode === "remove" ? "Why it isn't shared (the sender sees this)" : mode === "reply" ? "Your reply (only the sender sees it)" : "A note for Pastoral care (optional)"}
<textarea rows={2} value={note} onChange={(e) => setNote(e.target.value)} required={mode !== "escalate"} minLength={mode === "escalate" ? 0 : 2} maxLength={1000} className={input} />
</label>
<div className="flex gap-2">
<button className={mode === "escalate" ? "cca-btn !bg-red-700" : "cca-btn"}>{mode === "escalate" ? "Escalate now" : "Save"}</button>
<button type="button" className="cca-btn-quiet" onClick={done}>Cancel</button>
</div>
</form>
)}
</li>
);
}
function Settings({ onSaved, onError }: { onSaved: (t: string) => void; onError: (t: string) => void }) {
const [s, setS] = useState<RequestForm | null>(null);
useEffect(() => { call<{ settings: RequestForm }>("GET", "/settings").then((r) => r.ok && setS(r.data.settings)); }, []);
if (!s) return <p className="text-sm text-gray-600">Loading…</p>;
const setNumber = (i: number, k: "label" | "number", v: string) => setS({ ...s, emergencyNumbers: s.emergencyNumbers.map((n, j) => (j === i ? { ...n, [k]: v } : n)) });
return (
<form
className="space-y-4 rounded-lg border border-gray-200 bg-white p-5 shadow-sm"
onSubmit={async (e) => {
e.preventDefault();
const r = await call<{ settings: RequestForm }>("PUT", "/settings", { ...s, emergencyNumbers: s.emergencyNumbers.filter((n) => n.label.trim() && n.number.trim()) });
if (r.ok) { setS(r.data.settings); onSaved("Saved."); } else onError(r.error);
}}
>
<label className="block max-w-xs text-sm font-medium">Requests close by themselves after (days)<input type="number" min={7} max={90} value={s.closeAfterDays} onChange={(e) => setS({ ...s, closeAfterDays: Number(e.target.value) })} className={input} /></label>
<label className="flex items-start gap-3 text-sm"><input type="checkbox" checked={s.anonymousAllowed} onChange={(e) => setS({ ...s, anonymousAllowed: e.target.checked })} className="mt-1" /><span><span className="font-medium">Allow fully anonymous requests.</span> The prayer team won&apos;t see who sent them, so nobody can follow up.</span></label>
<fieldset className="space-y-2">
<legend className="text-sm font-semibold">Emergency numbers on the request form</legend>
{s.emergencyNumbers.map((n, i) => (
<div key={i} className="flex gap-2">
<input aria-label="Name" value={n.label} onChange={(e) => setNumber(i, "label", e.target.value)} className={`${input} !mt-0`} />
<input aria-label="Number" value={n.number} onChange={(e) => setNumber(i, "number", e.target.value)} className={`${input} !mt-0 max-w-[10rem]`} />
<button type="button" className="text-sm text-red-700" onClick={() => setS({ ...s, emergencyNumbers: s.emergencyNumbers.filter((_, j) => j !== i) })}>Remove</button>
</div>
))}
{s.emergencyNumbers.length < 8 && <button type="button" className="text-sm font-medium text-brand-text" onClick={() => setS({ ...s, emergencyNumbers: [...s.emergencyNumbers, { label: "", number: "" }] })}>Add a number</button>}
</fieldset>
<p className="text-xs text-gray-600">Requests are deleted a year after closing. Safeguarding contacts are the people with the Pastoral care role.</p>
<button className="cca-btn">Save</button>
</form>
);
}
@@ -0,0 +1,110 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { Phone } from "lucide-react";
import { errorMessage } from "@/lib/prayer";
import type { RequestForm } from "@/lib/requests";
/**
* Ask for prayer (APP-1.0-PLAN §4; mockup "Ask for prayer"): who will see it, said plainly (POPIA:
* the form says who sees it), the prayer team only by default; for members, the first name or
* "Anonymous" and approval first; fully anonymous when the church allows it; the emergency numbers.
*/
export function AskForm({ form, firstName }: { form: RequestForm; firstName: string }) {
const [text, setText] = useState("");
const [visibility, setVisibility] = useState<"team" | "members">("team");
const [showName, setShowName] = useState(false);
const [anonymous, setAnonymous] = useState(false);
const [busy, setBusy] = useState(false);
const [sent, setSent] = useState<"with_team" | "waiting" | null>(null);
const [error, setError] = useState<string | null>(null);
async function send(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const res = await fetch("/api/v1/me/requests", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, visibility, showName: visibility === "members" && showName, anonymous: form.anonymousAllowed && anonymous }),
});
if (!res.ok) setError(await errorMessage(res));
else setSent(((await res.json()) as { status: "with_team" | "waiting" }).status);
} catch {
setError("You're offline. Asking for prayer needs a connection.");
} finally {
setBusy(false);
}
}
if (sent) {
return (
<section className="cca-card space-y-3" role="status">
<h2 className="cca-h2">Thank you. We&apos;re praying with you.</h2>
<p>{sent === "waiting" ? "The prayer team will read it before it's shared with members. You'll hear when it is." : "The prayer team has it, and only they will see it."}</p>
<div className="flex flex-wrap gap-2">
<Link href="/me/requests" className="cca-btn">My requests</Link>
<Link href="/prayer" className="cca-btn-quiet">Back to prayer</Link>
</div>
</section>
);
}
const option = (value: "team" | "members", title: string, body: string) => (
<label className={`flex cursor-pointer gap-3 rounded-cc border p-3 ${visibility === value ? "border-brand bg-brand-tint" : "border-gray-200"}`}>
<input type="radio" name="visibility" value={value} checked={visibility === value} onChange={() => setVisibility(value)} className="mt-1" />
<span><span className="block font-semibold">{title}</span><span className="block text-sm text-gray-700">{body}</span></span>
</label>
);
return (
<form onSubmit={send} className="space-y-4">
<section className="cca-card space-y-4">
<label className="block">
<span className="font-semibold">What can we pray for?</span>
<textarea value={text} onChange={(e) => setText(e.target.value)} required minLength={5} maxLength={2000} rows={6} className="mt-1 block w-full rounded-cc border border-gray-300 p-3" />
</label>
<fieldset className="space-y-2">
<legend className="mb-1 font-semibold">Who will see it</legend>
{option("team", "The prayer team only", "The church's prayer coordinators, and its pastoral care team if they need to help.")}
{option("members", "Members of the church", "Members signed in to the App, after the prayer team has read it. Never anyone else.")}
</fieldset>
{visibility === "members" && (
<fieldset className="space-y-1">
<legend className="mb-1 text-sm font-semibold">Show it as</legend>
<label className="flex min-h-11 items-center gap-3"><input type="radio" name="name" checked={showName} onChange={() => setShowName(true)} />{firstName}</label>
<label className="flex min-h-11 items-center gap-3"><input type="radio" name="name" checked={!showName} onChange={() => setShowName(false)} />Anonymous</label>
</fieldset>
)}
{form.anonymousAllowed ? (
<label className="flex min-h-11 items-start gap-3 text-sm">
<input type="checkbox" checked={anonymous} onChange={(e) => setAnonymous(e.target.checked)} className="mt-1" />
<span>Don&apos;t tell the prayer team it&apos;s me. <span className="text-gray-600">They won&apos;t be able to follow up, but you can still read their replies here.</span></span>
</label>
) : (
<p className="text-sm text-gray-600">The prayer team sees that it&apos;s from you, so they can follow up.</p>
)}
<p className="text-xs text-gray-600">It closes by itself after {form.closeAfterDays} days and is deleted a year after closing. It&apos;s never used for statistics.</p>
{error && <p role="alert" className="rounded-cc bg-red-50 p-3 text-sm text-red-800">{error}</p>}
<button type="submit" disabled={busy} className="cca-btn w-full disabled:opacity-60">{busy ? "Sending…" : "Ask for prayer"}</button>
</section>
{form.emergencyNumbers.length > 0 && (
<section className="cca-card space-y-2 border-amber-300 bg-amber-50" aria-labelledby="emergency">
<h2 id="emergency" className="font-semibold">If you or someone else is in danger</h2>
<p className="text-sm">Please don&apos;t wait for the prayer team. Call:</p>
<ul className="space-y-1">
{form.emergencyNumbers.map((n) => (
<li key={n.number}>
<a href={`tel:${n.number.replace(/\s+/g, "")}`} className="flex min-h-11 items-center gap-2 font-semibold underline-offset-4 hover:underline">
<Phone className="h-4 w-4" aria-hidden />{n.label}: {n.number}
</a>
</li>
))}
</ul>
</section>
)}
</form>
);
}
@@ -0,0 +1,65 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { errorMessage } from "@/lib/prayer";
import { shortDate, STATUS_NAMES, type MyRequest } from "@/lib/requests";
/**
* My prayer requests (APP-1.0-PLAN §4): each with who sees it, its state, how many prayed, what the
* prayer team changed or why it wasn't shared, their private replies; add "Answered!", close, delete.
*/
export function MyRequests({ list }: { list: MyRequest[] }) {
const router = useRouter();
const [error, setError] = useState<string | null>(null);
async function act(method: string, path: string, body?: object) {
setError(null);
const res = await fetch(path, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined }).catch(() => null);
if (!res) setError("You're offline. This needs a connection.");
else if (!res.ok) setError(await errorMessage(res));
else router.refresh();
}
return (
<div className="space-y-3">
{error && <p role="alert" className="rounded-cc bg-red-50 p-3 text-sm text-red-800">{error}</p>}
{list.map((r) => (
<article key={r.id} className="cca-card space-y-3">
<p className="text-xs font-semibold uppercase tracking-wide text-gray-600">{STATUS_NAMES[r.status]} · {shortDate(r.createdAt)}</p>
<p className="whitespace-pre-line">{r.text}</p>
<p className="cca-muted">
{r.visibility === "team" ? "The prayer team only" : `Members, shown as ${r.showName ? "your first name" : "Anonymous"}`}
{r.anonymous && " · the team doesn't know it's you"}
{r.prayedCount > 0 && ` · ${r.prayedCount} ${r.prayedCount === 1 ? "person" : "people"} prayed`}
</p>
{r.redactionNote && <p className="rounded-cc bg-gray-50 p-3 text-sm">The prayer team edited it: {r.redactionNote}</p>}
{r.removedReason && <p className="rounded-cc bg-gray-50 p-3 text-sm">Not shared with members: {r.removedReason} The prayer team still prays for it.</p>}
{r.updates.map((u) => (
<p key={u.id} className={`rounded-cc p-3 text-sm ${u.author === "team" ? "bg-brand-tint" : "bg-gray-50"}`}>
<span className="font-semibold">{u.author === "team" ? "The prayer team" : "You"}, {shortDate(u.createdAt)}:</span> {u.text}
</p>
))}
{!r.closedAt && (
<form
className="flex gap-2"
onSubmit={(e) => {
e.preventDefault();
const input = e.currentTarget.elements.namedItem("text") as HTMLInputElement;
if (input.value.trim().length >= 2) void act("POST", `/api/v1/me/requests/${r.id}/updates`, { text: input.value }).then(() => { input.value = ""; });
}}
>
<label className="sr-only" htmlFor={`u-${r.id}`}>Add an update</label>
<input id={`u-${r.id}`} name="text" maxLength={1000} placeholder="Add an update, e.g. Answered!" className="min-h-11 min-w-0 flex-1 rounded-cc border border-gray-300 px-3" />
<button className="cca-btn-quiet">Add</button>
</form>
)}
<div className="flex flex-wrap gap-4 text-sm font-semibold">
{!r.closedAt && <button type="button" onClick={() => act("POST", `/api/v1/me/requests/${r.id}/close`)} className="text-brand-text underline-offset-4 hover:underline">Close it</button>}
<button type="button" onClick={() => window.confirm("Delete this request? It can't be undone.") && act("DELETE", `/api/v1/me/requests/${r.id}`)} className="text-red-700 underline-offset-4 hover:underline">Delete</button>
</div>
</article>
))}
</div>
);
}
@@ -0,0 +1,39 @@
"use client";
import { useState } from "react";
import { shortDate, type SharedRequest } from "@/lib/requests";
/** Members' shared requests (APP-1.0-PLAN §4) with **I prayed**: the sender sees how many, never who. */
export function SharedList({ initial }: { initial: SharedRequest[] }) {
const [list, setList] = useState(initial);
async function prayed(id: string) {
const res = await fetch(`/api/v1/requests/${id}/prayed`, { method: "POST" }).catch(() => null);
if (!res?.ok) return;
const body = (await res.json()) as { prayedCount: number };
setList((l) => l.map((r) => (r.id === id ? { ...r, iPrayed: true, prayedCount: body.prayedCount } : r)));
}
return (
<ul className="space-y-3">
{list.map((r) => (
<li key={r.id} className="cca-card space-y-3">
<p className="whitespace-pre-line">{r.text}</p>
{r.updates.map((u) => (
<p key={u.id} className="rounded-cc bg-brand-tint p-3 text-sm"><span className="font-semibold">Update, {shortDate(u.createdAt)}:</span> {u.text}</p>
))}
<div className="flex items-center justify-between gap-3">
<p className="cca-muted">{r.by} · {shortDate(r.createdAt)}{r.prayedCount > 0 && ` · ${r.prayedCount} prayed`}</p>
{r.mine ? (
<span className="text-sm text-gray-600">Yours</span>
) : r.iPrayed ? (
<span className="text-sm font-semibold text-brand-text">You prayed</span>
) : (
<button type="button" onClick={() => prayed(r.id)} className="cca-btn !min-h-10">I prayed</button>
)}
</div>
</li>
))}
</ul>
);
}
+46
View File
@@ -0,0 +1,46 @@
/** Prayer requests' shapes (backend/src/requests/*), for server and client components. */
export type RequestForm = { anonymousAllowed: boolean; emergencyNumbers: { label: string; number: string }[]; closeAfterDays: number };
export type Update = { id: string; author: "submitter" | "team"; text: string; createdAt: string };
/** GET /api/v1/requests: what members see. */
export type SharedRequest = { id: string; text: string; by: string; prayedCount: number; iPrayed: boolean; updates: Update[]; createdAt: string; mine: boolean };
export type RequestStatus = "closed" | "with_team" | "waiting" | "shared" | "not_shared";
/** GET /api/v1/me/requests: the sender's own. */
export type MyRequest = {
id: string;
text: string;
visibility: "team" | "members";
showName: boolean;
anonymous: boolean;
status: RequestStatus;
redactionNote: string | null;
removedReason: string | null;
prayedCount: number;
updates: Update[];
closesAt: string;
closedAt: string | null;
createdAt: string;
};
/** The prayer team's view. */
export type TeamRequest = MyRequest & {
moderation: "none" | "pending" | "approved" | "removed";
submitter: { name: string; email: string; phone: string | null } | null;
escalated: { at: string; note: string | null } | null;
redacted: boolean;
};
export const STATUS_NAMES: Record<RequestStatus, string> = {
with_team: "With the prayer team",
waiting: "Waiting for approval",
shared: "Shared with members",
not_shared: "Not shared",
closed: "Closed",
};
/** "3 December" from an ISO instant. */
export const shortDate = (iso: string) => new Intl.DateTimeFormat("en-ZA", { day: "numeric", month: "long" }).format(new Date(iso));