app: the House of Prayer's screens, changelog and README (APP-1.0-PLAN §3)

The 24-hour clock on the Prayer tab (midnight at the top, the night half darker,
open slots dashed, your own in gold, a hand at now), live over the stream with
polling as the fallback; tap an hour for Cover it / Join, the open hours as
buttons; signed out, back from Accounts with that slot's sheet open. The booking
sheet (once, every week, every day; length, end, reminder and channel, a note),
Me → My prayer (skip, add back, reminder, end date, stop, renew, "I prayed"),
the renew and "I prayed" link pages, sharing a testimony, Home's small clock
with the next gap and your next slot, the campaign card. The admin's House of
Prayer: the week, who prays when (names, access-logged), booking for a member,
the rules, campaigns, testimonies.

Checked in a browser on a throwaway PostgreSQL: one member books through the
sheet and a visitor's clock updates live; no page errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 10:42:35 +02:00
co-authored by Claude Opus 5.5
parent 5213bb36c0
commit 1dd3aadb60
24 changed files with 1631 additions and 13 deletions
+32 -1
View File
@@ -2,7 +2,8 @@
## [Unreleased] ## [Unreleased]
Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). One migration so far (`20261201000000_init`). Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). Two migrations so far (`20261201000000_init`,
`20261202000000_house_of_prayer`).
### Added ### Added
@@ -29,5 +30,35 @@ Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). One migration so far (`20261
- The frontend's shell: header, bottom tab bar, the church's footer, the manifest and icons - The frontend's shell: header, bottom tab bar, the church's footer, the manifest and icons
(`/app-icon/192|512|maskable|apple|favicon`), the service worker (`public/sw.js`), "Add to home (`/app-icon/192|512|maskable|apple|favicon`), the service worker (`public/sw.js`), "Add to home
screen", the offline notice and page, Me, the admin's first dashboard, the sign-in problem page. screen", the offline notice and page, Me, the admin's first dashboard, the sign-in problem page.
- **The House of Prayer** (plan §3):
- Slots of the church's length (60 minutes by default; 15 or 30) in its timezone, daylight saving
included (`src/lib/zoned.ts`). Commitments are rules (`PrayerCommitment`: start, length, once /
daily / weekly, end) plus skipped dates (`PrayerSkip`), never a row per occurrence
(`src/prayer/rules.ts`).
- The day's coverage as counts only (`GET /api/v1/prayer/day`; `mine` for the signed-in member),
cached until a booking changes; live over server-sent events (`/api/v1/prayer/stream`,
`X-Accel-Buffering: no`, a comment every 25 seconds), polling every 30 seconds without it.
- A member books just once, every week or every day (up to 12 months), several slots in a row, a
reminder and its channel; skips a date, changes or stops it outside the cancel window (8 hours by
default; inside it, who to contact); renews for another year; marks "I prayed" (self-reported)
for slots that ended in the last 14 days. A new time or days ends the old rule and starts a new
one, so the past stays as it was.
- Signed links that need no sign-in (`src/prayer/tokens.ts`): **Renew** (single use: signed over
the end date) and **I prayed**, each on a page that asks for the tap (`/prayer/renew`,
`/prayer/prayed`).
- Campaigns (`PrayerCampaign`: days left, coverage so far, hours prayed; their own target per slot)
and testimonies (`Testimony`: moderated first, first name or Anonymous, removable by the author,
the reason sent when one isn't shared).
- The admin (`/admin/prayer`; Prayer coordinator, Owner, Church admin): the week's coverage and
gaps, who prays when (names, each view in the new `AccessLog`), booking for a member, cancelling
any slot, the wall's rules (AppSetting `prayer_wall`), campaigns, testimonies.
- Jobs: `prayer-reminders` (every minute) and `prayer-renewals` (09:00; 14 and 3 days before the
end) queue messages in `OutboxMessage`; sending them by email and WhatsApp comes with plan §8.
- The heartbeat's `prayer` counts (last 7 days' coverage, active commitments); `user.export` and
`user.deleted` cover commitments, "I prayed" marks and testimonies (future slots open up, the
past stays as counts only).
- Screens: the 24-hour clock on the Prayer tab (tap an hour, Cover it / Join, the open hours as
buttons, back from signing in with the slot's sheet open), the booking sheet, Me → My prayer,
sharing a testimony, and Home's small clock with the next gap and your next slot.
- `env.template.json` (read by the Hub at the tag), `ecosystem.config.example.cjs` (ports 5400 / 3400 - `env.template.json` (read by the Hub at the tag), `ecosystem.config.example.cjs` (ports 5400 / 3400
in development). in development).
+6 -2
View File
@@ -8,7 +8,7 @@ and notification settings need a sign-in through the church's Accounts. The admi
**State:** being built (from 2026-12-01) on the branch `feat/app-scaffold`, which is merged into **State:** being built (from 2026-12-01) on the branch `feat/app-scaffold`, which is merged into
main only when `app@1.0.0` is done (main keeps a placeholder until then). Not released; main only when `app@1.0.0` is done (main keeps a placeholder until then). Not released;
`app@1.0.0` is tagged when the plan is built. Done so far (the foundation, plan §1, §2, §10, §12): `app@1.0.0` is tagged when the plan is built. Done so far (the foundation, plan §1, §2, §10, §12, and the House of Prayer, §3):
- **Backend:** Express + Prisma + pg-boss (ES modules, as the Website). Registers with the Hub - **Backend:** Express + Prisma + pg-boss (ES modules, as the Website). Registers with the Hub
(`CCP-` licence key, product `app`) and sends the heartbeat with the active-member band the App (`CCP-` licence key, product `app`) and sends the heartbeat with the active-member band the App
@@ -30,8 +30,12 @@ main only when `app@1.0.0` is done (main keeps a placeholder until then). Not re
shell, pages kept for offline, a signed-in member's pages forgotten once they're signed out, no shell, pages kept for offline, a signed-in member's pages forgotten once they're signed out, no
push); "Add to home screen" (Android's prompt, the iPhone's steps); Me; the admin's first push); "Add to home screen" (Android's prompt, the iPhone's steps); Me; the admin's first
dashboard. The modules' screens say what's coming. dashboard. The modules' screens say what's coming.
- **House of Prayer** (§3, `backend/src/prayer/`): the 24-hour clock, live; booking once, weekly or
daily with reminders; skip, change, stop within the 8-hour rule; the renew and "I prayed" links;
campaigns and moderated testimonies; the admin's week, names (access-logged), rules and campaigns.
Reminders and renewal notices wait in the outbox until email and WhatsApp (§8) send them.
**Still to come** (plan §3–§15): the House of Prayer, prayer requests, announcements, **Still to come** (plan §4–§15): prayer requests, announcements,
devotionals (Cross Code's from the Hub: the next 2 weeks, today included, fetched each night; and devotionals (Cross Code's from the Hub: the next 2 weeks, today included, fetched each night; and
the church's own), events and the feed, email and WhatsApp, the rest of the admin, the export, the church's own), events and the feed, email and WhatsApp, the rest of the admin, the export,
backups, the demo church and scenarios, `scripts/products/app.sh`, e2e and Lighthouse. backups, the demo church and scenarios, `scripts/products/app.sh`, e2e and Lighthouse.
+5
View File
@@ -96,6 +96,11 @@ export default async function Admin() {
</section> </section>
</div> </div>
)} )}
{o?.modules.includes("house-of-prayer") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator"].includes(r)) && (
<Link href="/admin/prayer" className="cca-card flex items-center justify-between font-semibold">
House of Prayer: the week, who prays when, rules, campaigns, testimonies<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,39 @@
import type { Metadata } from "next";
import Link from "next/link";
import { redirect } from "next/navigation";
import { AdminPrayer } from "@/components/prayer/admin/AdminPrayer";
import { loadApp, loadMe } from "@/lib/load";
import { localToday } from "@/lib/prayer";
export const metadata: Metadata = { title: "House of Prayer · Admin", robots: { index: false, follow: false } };
const CAN = ["owner", "church_admin", "prayer_coordinator"];
/**
* The House of Prayer in the admin (APP-1.0-PLAN §3, §10): the week's coverage and gaps, who
* prays when (names, access-logged), booking on a member's behalf, the wall's rules, campaigns and
* testimonies. Prayer coordinators, Owner and Church admin, with 2FA (the dashboard explains
* anything else).
*/
export default async function AdminPrayerPage() {
const [me, app] = await Promise.all([loadMe(), loadApp()]);
if (!me || !me.mfa || !me.member.roles.some((r) => CAN.includes(r))) redirect("/admin");
if (!app.modules.includes("house-of-prayer")) {
return (
<main className="mx-auto max-w-5xl space-y-4 px-4 py-10">
<h1 className="text-2xl font-semibold">House of Prayer</h1>
<p className="text-gray-600">The House of Prayer is switched off. An Owner or Church admin can switch it on in Settings → Modules.</p>
<Link href="/admin" className="cca-btn-quiet">Back to the dashboard</Link>
</main>
);
}
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">House of Prayer</h1>
</div>
<AdminPrayer today={localToday(app.timezone)} />
</main>
);
}
+5 -2
View File
@@ -1,7 +1,7 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import Link from "next/link"; import Link from "next/link";
import { AppShell } from "@/components/AppShell"; import { AppShell } from "@/components/AppShell";
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/load"; import { loadApp, loadMe, ROLE_NAMES, signInHref } from "@/lib/load";
export const metadata: Metadata = { title: "Me", robots: { index: false, follow: false } }; export const metadata: Metadata = { title: "Me", robots: { index: false, follow: false } };
@@ -11,7 +11,7 @@ export const metadata: Metadata = { title: "Me", robots: { index: false, follow:
* their modules (§3, §4, §8). * their modules (§3, §4, §8).
*/ */
export default async function Me() { export default async function Me() {
const me = await loadMe(); const [me, app] = await Promise.all([loadMe(), loadApp()]);
if (!me) { if (!me) {
return ( return (
<AppShell> <AppShell>
@@ -31,6 +31,9 @@ export default async function Me() {
<p className="cca-muted">{me.member.email}</p> <p className="cca-muted">{me.member.email}</p>
<p className="text-sm">{roles.length ? roles.map((r) => ROLE_NAMES[r]).join(", ") : "Member"}</p> <p className="text-sm">{roles.length ? roles.map((r) => ROLE_NAMES[r]).join(", ") : "Member"}</p>
</section> </section>
{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>
)}
{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,51 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { MyPrayerList } from "@/components/prayer/MyPrayerList";
import { loadMe, signInHref } from "@/lib/load";
import { requireModule } from "@/lib/module";
import { localToday } from "@/lib/prayer";
import { loadMyPrayer } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "My prayer", robots: { index: false, follow: false } };
/** Me: my prayer (APP-1.0-PLAN §3): the member's own slots, and what they've marked as prayed. */
export default async function MyPrayerPage() {
await requireModule("house-of-prayer");
const me = await loadMe();
if (!me) {
return (
<AppShell footer={false}>
<h1 className="cca-h1">My prayer</h1>
<section className="cca-card space-y-3">
<p>Sign in to see and change your prayer slots.</p>
<a href={signInHref("/me/prayer")} className="cca-btn">Sign in</a>
</section>
</AppShell>
);
}
const data = await loadMyPrayer();
return (
<AppShell footer={false}>
<h1 className="cca-h1">My prayer</h1>
{!data ? (
<section className="cca-card"><p className="cca-muted">Your prayer slots can&apos;t be loaded right now. Please try again in a minute.</p></section>
) : (
<>
{data.prayedTotal > 0 && (
<p className="cca-muted">{data.prayedTotal} {data.prayedTotal === 1 ? "time" : "times"} marked as prayed (self-reported).</p>
)}
{data.commitments.length ? (
<MyPrayerList data={data} today={localToday(data.timezone)} />
) : (
<section className="cca-card space-y-3">
<p>You haven&apos;t booked a prayer slot yet.</p>
<Link href="/prayer" className="cca-btn">Find an open hour</Link>
</section>
)}
<Link href="/prayer/testimony" className="cca-btn-quiet w-full">My testimonies</Link>
</>
)}
</AppShell>
);
}
+7 -1
View File
@@ -2,7 +2,10 @@ import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell"; import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon"; import { ComingSoon } from "@/components/ComingSoon";
import { InstallCard } from "@/components/InstallCard"; import { InstallCard } from "@/components/InstallCard";
import { CampaignCard } from "@/components/prayer/CampaignCard";
import { PrayerHomeCard } from "@/components/prayer/PrayerHomeCard";
import { firstName, greeting, loadApp, loadMe } from "@/lib/load"; import { firstName, greeting, loadApp, loadMe } from "@/lib/load";
import { loadCampaign, loadDay, loadMyPrayer } from "@/lib/prayerServer";
export async function generateMetadata(): Promise<Metadata> { export async function generateMetadata(): Promise<Metadata> {
const app = await loadApp(); const app = await loadApp();
@@ -18,6 +21,8 @@ export async function generateMetadata(): Promise<Metadata> {
export default async function Home() { export default async function Home() {
const [app, me] = await Promise.all([loadApp(), loadMe()]); const [app, me] = await Promise.all([loadApp(), loadMe()]);
const on = new Set(app.modules); const on = new Set(app.modules);
const prayer = on.has("house-of-prayer");
const [day, campaign, mine] = prayer ? await Promise.all([loadDay(), loadCampaign(), me ? loadMyPrayer() : null]) : [null, null, null];
const name = app.church?.name ?? "your church"; const name = app.church?.name ?? "your church";
return ( return (
<AppShell> <AppShell>
@@ -25,7 +30,8 @@ export default async function Home() {
{me ? `${greeting(app.timezone)}, ${firstName(me.member.name)}` : `Welcome to ${name}`} {me ? `${greeting(app.timezone)}, ${firstName(me.member.name)}` : `Welcome to ${name}`}
</h1> </h1>
<InstallCard name={app.shortName} /> <InstallCard name={app.shortName} />
{on.has("house-of-prayer") && <ComingSoon title="House of Prayer">Today&apos;s prayer clock and your next slot will show here.</ComingSoon>} {campaign && <CampaignCard campaign={campaign} compact />}
{day && <PrayerHomeCard day={day} mine={mine} />}
{on.has("devotionals") && <ComingSoon title="Today's devotional">Today&apos;s Bible passage and devotional will show here.</ComingSoon>} {on.has("devotionals") && <ComingSoon title="Today's devotional">Today&apos;s Bible passage and devotional will show here.</ComingSoon>}
{on.has("announcements") && <ComingSoon title="Announcements">News from {name} will show here.</ComingSoon>} {on.has("announcements") && <ComingSoon title="Announcements">News from {name} will show here.</ComingSoon>}
</AppShell> </AppShell>
+51 -5
View File
@@ -1,18 +1,64 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import Link from "next/link";
import { AppShell } from "@/components/AppShell"; import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon"; import { CampaignCard } from "@/components/prayer/CampaignCard";
import { PrayerClock } from "@/components/prayer/PrayerClock";
import { loadMe } from "@/lib/load";
import { requireModule } from "@/lib/module"; import { requireModule } from "@/lib/module";
import { dayName } from "@/lib/prayer";
import { loadCampaign, loadDay, loadTestimonies } from "@/lib/prayerServer";
// Every prayer page is noindex (APP-1.0-PLAN §4, §11; next.config.ts sends the header too). // Every prayer page is noindex (APP-1.0-PLAN §4, §11; next.config.ts sends the header too).
export const metadata: Metadata = { title: "House of Prayer", robots: { index: false, follow: false } }; export const metadata: Metadata = { title: "House of Prayer", robots: { index: false, follow: false } };
/** The House of Prayer (APP-1.0-PLAN §3): the 24-hour clock, booking, campaigns. */ const DATE = /^\d{4}-\d{2}-\d{2}$/;
export default async function Prayer() {
/**
* The House of Prayer (APP-1.0-PLAN §3): the campaign, the 24-hour clock for the chosen day
* (`?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 }> }) {
await requireModule("house-of-prayer"); await requireModule("house-of-prayer");
const q = await searchParams;
const [me, day, campaign, testimonies] = await Promise.all([
loadMe(),
loadDay(q.day && DATE.test(q.day) ? q.day : null),
loadCampaign(),
loadTestimonies(),
]);
const slot = q.slot !== undefined && /^\d{1,4}$/.test(q.slot) ? Number(q.slot) : null;
return ( return (
<AppShell> <AppShell>
<h1 className="cca-h1">House of Prayer</h1> <div className="flex items-end justify-between gap-3">
<ComingSoon title="The prayer wall">The 24-hour prayer clock, with the hours still open, will show here.</ComingSoon> <h1 className="cca-h1">House of Prayer</h1>
{me && <Link href="/me/prayer" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">My prayer</Link>}
</div>
{campaign && <CampaignCard campaign={campaign} />}
{day ? (
<PrayerClock key={day.date} initial={day} signedIn={!!me} openSlot={slot} />
) : (
<section className="cca-card"><p className="cca-muted">The prayer wall can&apos;t be loaded right now. Please try again in a minute.</p></section>
)}
<section className="space-y-3" aria-labelledby="testimonies">
<div className="flex items-end justify-between gap-3">
<h2 id="testimonies" className="cca-h2">What God has done</h2>
{me ? (
<Link href="/prayer/testimony" className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">Share yours</Link>
) : null}
</div>
{testimonies.length ? (
<ul className="space-y-3">
{testimonies.map((t) => (
<li key={t.id} className="cca-card">
<p className="whitespace-pre-line">{t.text}</p>
<p className="cca-muted mt-2">{t.by} · {dayName(t.createdAt.slice(0, 10), { day: "numeric", month: "long" })}</p>
</li>
))}
</ul>
) : (
<p className="cca-muted">Answered prayers shared by the church will show here.</p>
)}
</section>
</AppShell> </AppShell>
); );
} }
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { TokenAction } from "@/components/prayer/TokenAction";
import { requireModule } from "@/lib/module";
export const metadata: Metadata = { title: "I prayed", robots: { index: false, follow: false } };
/** "I prayed" from a reminder (APP-1.0-PLAN §3): self-reported, counted as a number only. */
export default async function Prayed({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
await requireModule("house-of-prayer");
const { token = "" } = await searchParams;
return (
<AppShell footer={false}>
<h1 className="cca-h1">Did you pray?</h1>
<section className="cca-card space-y-4">
<p>Mark your slot as prayed. It&apos;s only counted, never ranked, and only you see your own number.</p>
<TokenAction endpoint="prayed" token={token} button="I prayed" />
</section>
</AppShell>
);
}
@@ -0,0 +1,21 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { TokenAction } from "@/components/prayer/TokenAction";
import { requireModule } from "@/lib/module";
export const metadata: Metadata = { title: "Renew your prayer slot", robots: { index: false, follow: false } };
/** "Renew for another year" from a renewal notice (APP-1.0-PLAN §3): one tap, no sign-in. */
export default async function Renew({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
await requireModule("house-of-prayer");
const { token = "" } = await searchParams;
return (
<AppShell footer={false}>
<h1 className="cca-h1">Renew your prayer slot</h1>
<section className="cca-card space-y-4">
<p>Your recurring prayer slot is coming to an end. Renew it to keep praying at the same time for another year.</p>
<TokenAction endpoint="renew" token={token} button="Renew for another year" />
</section>
</AppShell>
);
}
@@ -0,0 +1,32 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { TestimonyForm, type MyTestimony } from "@/components/prayer/TestimonyForm";
import { firstName, loadMe, signInHref } from "@/lib/load";
import { requireModule } from "@/lib/module";
import { backendGet, loadCampaign } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "Share a testimony", robots: { index: false, follow: false } };
/** Share what God has done (APP-1.0-PLAN §3), and see your own testimonies' state. */
export default async function Testimony() {
await requireModule("house-of-prayer");
const me = await loadMe();
if (!me) {
return (
<AppShell footer={false}>
<h1 className="cca-h1">Share a testimony</h1>
<section className="cca-card space-y-3">
<p>Sign in to share what God has done.</p>
<a href={signInHref("/prayer/testimony")} className="cca-btn">Sign in</a>
</section>
</AppShell>
);
}
const [mine, campaign] = await Promise.all([backendGet<{ testimonies: MyTestimony[] }>("/api/v1/me/prayer/testimonies"), loadCampaign()]);
return (
<AppShell footer={false}>
<h1 className="cca-h1">Share a testimony</h1>
<TestimonyForm mine={mine?.testimonies ?? []} campaign={campaign?.started ? { id: campaign.id, title: campaign.title } : null} firstName={firstName(me.member.name)} />
</AppShell>
);
}
@@ -0,0 +1,136 @@
"use client";
import { useEffect, useId, useRef, useState } from "react";
import { X } from "lucide-react";
import { CHANNEL_NAMES, dayName, duration, errorMessage, REMINDER_NAMES, span, type Channel, type MyPrayer, type Recurrence, type Reminder } from "@/lib/prayer";
/**
* Book a slot (APP-1.0-PLAN §3; mockup "Book a slot"): just once, every week or every day, how
* long (several slots in a row), until when, the reminder and its channel, and a note for
* themselves. Says the cancel rule before booking.
*/
export function BookingSheet({ date, minute, slotMinutes, onClose, onBooked }: { date: string; minute: number; slotMinutes: number; onClose: () => void; onBooked: () => void }) {
const titleId = useId();
const first = useRef<HTMLInputElement>(null);
const [rules, setRules] = useState<MyPrayer["rules"] | null>(null);
const [recurrence, setRecurrence] = useState<Recurrence>("once");
const [length, setLength] = useState(slotMinutes >= 60 ? 60 : slotMinutes);
const [endDate, setEndDate] = useState("");
const [reminder, setReminder] = useState<Reminder>("hour1");
const [channel, setChannel] = useState<Channel>("email");
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
first.current?.focus();
const onKey = (e: KeyboardEvent) => e.key === "Escape" && onClose();
window.addEventListener("keydown", onKey);
fetch("/api/v1/me/prayer", { cache: "no-store" }).then(async (r) => r.ok && setRules(((await r.json()) as MyPrayer).rules)).catch(() => {});
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const lengths = Array.from({ length: Math.floor(240 / slotMinutes) }, (_, i) => (i + 1) * slotMinutes);
const weekday = dayName(date, { weekday: "long" });
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
const res = await fetch("/api/v1/me/prayer/commitments", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ startDate: date, startMinute: minute, durationMinutes: length, recurrence, endDate: recurrence !== "once" && endDate ? endDate : null, reminder, channel, note: note.trim() || null }),
});
if (!res.ok) {
setError(await errorMessage(res));
return;
}
onBooked();
} catch {
setError("You're offline. Booking needs a connection.");
} finally {
setBusy(false);
}
}
const choice = (value: Recurrence, label: string) => (
<label className={`flex min-h-11 cursor-pointer items-center gap-3 rounded-cc border px-3 ${recurrence === value ? "border-brand bg-brand-tint" : "border-gray-200"}`}>
<input ref={value === "once" ? first : undefined} type="radio" name="recurrence" value={value} checked={recurrence === value} onChange={() => setRecurrence(value)} className="accent-[rgb(var(--brand))]" />
<span className="text-sm font-medium">{label}</span>
</label>
);
return (
<div className="fixed inset-0 z-30 flex items-end justify-center bg-black/40 sm:items-center" onClick={onClose}>
<form
role="dialog"
aria-modal="true"
aria-labelledby={titleId}
onClick={(e) => e.stopPropagation()}
onSubmit={submit}
className="max-h-[90dvh] w-full max-w-xl space-y-4 overflow-y-auto rounded-t-2xl bg-white p-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] shadow-xl sm:rounded-2xl"
>
<div className="flex items-start justify-between gap-3">
<div>
<h2 id={titleId} className="cca-h2">Pray {span(minute, length)}</h2>
<p className="cca-muted">{dayName(date)}</p>
</div>
<button type="button" onClick={onClose} className="rounded-full p-2 hover:bg-gray-100" aria-label="Close">
<X className="h-5 w-5" aria-hidden />
</button>
</div>
<fieldset className="space-y-2">
<legend className="mb-1 text-sm font-semibold">How often</legend>
{choice("once", "Just this once")}
{choice("weekly", `Every week, on ${weekday}`)}
{choice("daily", "Every day")}
</fieldset>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block text-sm">
<span className="font-semibold">How long</span>
<select value={length} onChange={(e) => setLength(Number(e.target.value))} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2">
{lengths.map((l) => <option key={l} value={l}>{duration(l)}</option>)}
</select>
</label>
{recurrence !== "once" && (
<label className="block text-sm">
<span className="font-semibold">Until</span>
<input type="date" value={endDate} min={date} onChange={(e) => setEndDate(e.target.value)} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2" aria-describedby={`${titleId}-until`} />
<span id={`${titleId}-until`} className="mt-1 block text-xs text-gray-500">Leave empty for the longest: {rules?.recurringMaxMonths ?? 12} months from today.</span>
</label>
)}
</div>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block text-sm">
<span className="font-semibold">Reminder</span>
<select value={reminder} onChange={(e) => setReminder(e.target.value as Reminder)} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2">
{(Object.keys(REMINDER_NAMES) as Reminder[]).map((r) => <option key={r} value={r}>{REMINDER_NAMES[r]}</option>)}
</select>
</label>
<label className="block text-sm">
<span className="font-semibold">Send reminders by</span>
<select value={channel} onChange={(e) => setChannel(e.target.value as Channel)} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2">
{(Object.keys(CHANNEL_NAMES) as Channel[]).map((c) => <option key={c} value={c}>{CHANNEL_NAMES[c]}</option>)}
</select>
</label>
</div>
<label className="block text-sm">
<span className="font-semibold">Where I&apos;ll pray</span> <span className="text-gray-500">(optional, only for you)</span>
<input value={note} onChange={(e) => setNote(e.target.value)} maxLength={200} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-3" />
</label>
<p className="rounded-cc bg-gray-50 p-3 text-sm text-gray-700">
You can change or cancel a slot up to {rules?.cancelHours ?? 8} hours before it starts. After that, the prayer coordinator can help.
</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 ? "Booking…" : "Book this slot"}</button>
</form>
</div>
);
}
@@ -0,0 +1,35 @@
import type { Campaign } from "@/lib/prayer";
import { dayName } from "@/lib/prayer";
/**
* A campaign leads Home and the Prayer tab while it runs (APP-1.0-PLAN §3, P7): days left,
* collective coverage, hours marked as prayed (self-reported). No rankings, no one's own total.
*/
export function CampaignCard({ campaign, compact = false }: { campaign: Campaign; compact?: boolean }) {
const when = campaign.started
? `${campaign.daysLeft} ${campaign.daysLeft === 1 ? "day" : "days"} left`
: `Starts ${campaign.startsInDays === 1 ? "tomorrow" : `in ${campaign.startsInDays} days`}, ${dayName(campaign.startDate, { day: "numeric", month: "long" })}`;
return (
<section className="cca-card overflow-hidden !p-0" aria-labelledby={`campaign-${campaign.id}`}>
{campaign.imageUrl && !compact && <img src={campaign.imageUrl} alt="" className="h-36 w-full object-cover" />}
<div className="space-y-2 bg-brand p-4 text-brand-on">
<p className="text-xs font-semibold uppercase tracking-wide opacity-90">{when}</p>
<h2 id={`campaign-${campaign.id}`} className="font-heading text-xl font-semibold">{campaign.title}</h2>
{!compact && campaign.description && <p className="text-sm opacity-95">{campaign.description}</p>}
{campaign.goal && <p className="text-sm font-medium">Aim: {campaign.goal}</p>}
</div>
{campaign.started && (
<dl className="grid grid-cols-2 divide-x divide-gray-200 text-center">
<div className="p-3">
<dt className="text-xs text-gray-600">Covered so far</dt>
<dd className="text-lg font-semibold">{campaign.coveragePercent}%</dd>
</div>
<div className="p-3">
<dt className="text-xs text-gray-600">Hours prayed <span className="whitespace-nowrap">(self-reported)</span></dt>
<dd className="text-lg font-semibold">{campaign.hoursPrayed}</dd>
</div>
</dl>
)}
</section>
);
}
@@ -0,0 +1,113 @@
import type { Slot } from "@/lib/prayer";
/**
* The 24-hour prayer clock (APP-1.0-PLAN §3, decision 2; mockup "House of Prayer"): one ring for
* the day, midnight at the top and noon at the bottom, the night half (18:00–06:00) drawn darker.
* Each slot is a segment, shaded by how many have committed against the target; open slots are
* dashed outlines; the member's own carry a gold edge; a hand points at the time now.
*
* Pure SVG (no state), so Home can draw it small on the server and the Prayer tab interactively.
* The ring is decorative for screen readers: the page lists the open slots as buttons too.
*/
const SIZE = 300;
const C = SIZE / 2;
const OUTER = 140;
const INNER = 96;
const GOLD = "#c8961e";
const point = (minute: number, r: number) => {
const a = (minute / 1440) * 2 * Math.PI - Math.PI / 2;
return [C + r * Math.cos(a), C + r * Math.sin(a)] as const;
};
/** An annulus sector from `from` to `to` (minutes), with a small gap between segments. */
function sector(from: number, to: number, gapMinutes: number) {
const a = from + gapMinutes / 2;
const b = to - gapMinutes / 2;
const large = b - a > 720 ? 1 : 0;
const [x1, y1] = point(a, OUTER);
const [x2, y2] = point(b, OUTER);
const [x3, y3] = point(b, INNER);
const [x4, y4] = point(a, INNER);
return `M${x1.toFixed(2)} ${y1.toFixed(2)} A${OUTER} ${OUTER} 0 ${large} 1 ${x2.toFixed(2)} ${y2.toFixed(2)} L${x3.toFixed(2)} ${y3.toFixed(2)} A${INNER} ${INNER} 0 ${large} 0 ${x4.toFixed(2)} ${y4.toFixed(2)} Z`;
}
const isNight = (minute: number) => minute < 360 || minute >= 1080;
export type ClockProps = {
slots: Slot[];
slotMinutes: number;
target: number;
/** The hand (minutes after local midnight), on today's clock only. */
nowMinute: number | null;
selected?: number | null;
onSelect?: (minute: number) => void;
/** The middle: a big line and a small one. */
centre: { big: string; small: string };
label: string;
className?: string;
};
export function ClockSvg({ slots, slotMinutes, target, nowMinute, selected = null, onSelect, centre, label, className }: ClockProps) {
const gap = Math.min(4, slotMinutes / 6);
const byMinute = new Map(slots.map((s) => [s.minute, s]));
const segments = Array.from({ length: 1440 / slotMinutes }, (_, i) => i * slotMinutes);
return (
<svg viewBox={`0 0 ${SIZE} ${SIZE}`} role="img" aria-label={label} className={className}>
{/* The night half, darker behind the ring. */}
<path d={sector(1080, 1440, 0)} fill="#e5e7eb" />
<path d={sector(0, 360, 0)} fill="#e5e7eb" />
<path d={sector(360, 1080, 0)} fill="#f9fafb" />
{segments.map((minute) => {
const s = byMinute.get(minute);
// A slot the clocks jumped over (daylight saving) isn't on this day.
if (!s) return <path key={minute} d={sector(minute, minute + slotMinutes, gap)} fill="#d1d5db" opacity={0.4} />;
const strength = s.covered ? 0.4 + 0.6 * Math.min(1, s.count / Math.max(1, target)) : 0;
const isSelected = selected === minute;
return (
<path
key={minute}
d={sector(minute, minute + slotMinutes, gap)}
fill={s.covered ? "rgb(var(--brand))" : isNight(minute) ? "#e5e7eb" : "#ffffff"}
fillOpacity={s.covered ? strength : 1}
stroke={s.mine ? GOLD : isSelected ? "rgb(var(--brand-dark))" : s.covered ? "none" : "#9ca3af"}
strokeWidth={s.mine || isSelected ? 3 : 1.2}
strokeDasharray={!s.covered && !s.mine && !isSelected ? "4 3" : undefined}
onClick={onSelect ? () => onSelect(minute) : undefined}
className={onSelect ? "cursor-pointer" : undefined}
/>
);
})}
{/* Hours: 00, 06, 12, 18 inside the ring. */}
{[0, 360, 720, 1080].map((m) => {
const [x, y] = point(m, INNER - 14);
return (
<text key={m} x={x} y={y} textAnchor="middle" dominantBaseline="central" fontSize="11" fill="#4b5563">
{String(m / 60).padStart(2, "0")}
</text>
);
})}
{nowMinute !== null && (() => {
const [x, y] = point(nowMinute, OUTER + 4);
const [x0, y0] = point(nowMinute, INNER - 30);
return (
<g aria-hidden="true">
<line x1={x0} y1={y0} x2={x} y2={y} stroke="#111827" strokeWidth={2.5} strokeLinecap="round" />
<circle cx={x} cy={y} r={3.5} fill="#111827" />
</g>
);
})()}
<text x={C} y={C - 8} textAnchor="middle" fontSize="30" fontWeight="600" fill="#111827" style={{ fontFamily: "var(--cc-font-heading, inherit)" }}>
{centre.big}
</text>
<text x={C} y={C + 18} textAnchor="middle" fontSize="12" fill="#4b5563">
{centre.small}
</text>
</svg>
);
}
/** "21 of 24 hours covered" (or slots, with 15- or 30-minute slots). */
export const coveredLine = (covered: number, total: number, slotMinutes: number) =>
`${covered} of ${total} ${slotMinutes === 60 ? "hours" : "slots"} covered`;
@@ -0,0 +1,152 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { Lock } from "lucide-react";
import { CHANNEL_NAMES, dayName, errorMessage, REMINDER_NAMES, relativeDay, repeats, span, type Channel, type MyPrayer, type Reminder } from "@/lib/prayer";
type Commitment = MyPrayer["commitments"][number];
/**
* Me: my prayer (APP-1.0-PLAN §3; mockup "Me: my prayer"): each commitment with its next dates,
* **Skip** a date (or add it back), change the reminder or the end date, **Stop**, **Renew for
* another year** near the end, and **I prayed** for the slots that have ended. A date within the
* cancel window shows a lock and who to contact.
*/
export function MyPrayerList({ data, today }: { data: MyPrayer; today: string }) {
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const [message, setMessage] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
const contact = data.coordinator.name ? `${data.coordinator.name}${data.coordinator.contact ? ` (${data.coordinator.contact})` : ""}` : "the prayer coordinator";
async function act(key: string, method: string, path: string, body?: object, ok?: string) {
setBusy(key);
setMessage(null);
try {
const res = await fetch(path, { method, headers: body ? { "Content-Type": "application/json" } : undefined, body: body ? JSON.stringify(body) : undefined });
if (!res.ok) setMessage({ kind: "error", text: await errorMessage(res) });
else {
if (ok) setMessage({ kind: "ok", text: ok });
router.refresh();
}
} catch {
setMessage({ kind: "error", text: "You're offline. This needs a connection." });
} finally {
setBusy(null);
}
}
const base = (c: Commitment) => `/api/v1/me/prayer/commitments/${c.id}`;
return (
<div className="space-y-4">
<div aria-live="polite">
{message && <p role={message.kind === "error" ? "alert" : "status"} className={`rounded-cc p-3 text-sm ${message.kind === "error" ? "bg-red-50 text-red-800" : "bg-green-50 text-green-800"}`}>{message.text}</p>}
</div>
{data.commitments.map((c) => (
<section key={c.id} className="cca-card space-y-3" aria-labelledby={`c-${c.id}`}>
<div>
<h2 id={`c-${c.id}`} className="cca-h2">{span(c.startMinute, c.durationMinutes)}</h2>
<p className="cca-muted">
{repeats(c)}{c.recurrence !== "once" && ` until ${dayName(c.endDate, { day: "numeric", month: "long", year: "numeric" })}`}
</p>
{c.note && <p className="mt-1 text-sm text-gray-700">{c.note}</p>}
</div>
{c.toMark.length > 0 && (
<div className="space-y-2 rounded-cc bg-brand-tint p-3">
<p className="text-sm font-semibold">Did you pray?</p>
<div className="flex flex-wrap gap-2">
{c.toMark.slice(0, 1).map((d) => (
<button key={d} type="button" disabled={busy !== null} onClick={() => act(`p${c.id}${d}`, "POST", `${base(c)}/prayed`, { date: d }, "Marked as prayed. Thank you!")} className="cca-btn !min-h-10">
I prayed · {relativeDay(d, today)}
</button>
))}
</div>
</div>
)}
{c.active && c.upcoming.length > 0 && (
<div>
<h3 className="text-sm font-semibold">Next</h3>
<ul className="mt-1 divide-y divide-gray-100">
{c.upcoming.slice(0, 3).map((o) => (
<li key={o.date} className="flex min-h-11 items-center justify-between gap-3 py-1 text-sm">
<span className={o.skipped ? "text-gray-400 line-through" : undefined}>{relativeDay(o.date, today)}</span>
{o.locked ? (
<span className="flex items-center gap-1 text-xs text-gray-600" title={`Less than ${data.rules.cancelHours} hours away: contact ${contact}.`}>
<Lock className="h-3.5 w-3.5" aria-hidden />Within {data.rules.cancelHours} hours
</span>
) : c.recurrence === "once" ? null : o.skipped ? (
<button type="button" disabled={busy !== null} onClick={() => act(`u${c.id}${o.date}`, "DELETE", `${base(c)}/skip/${o.date}`)} className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">Add back</button>
) : (
<button type="button" disabled={busy !== null} onClick={() => act(`s${c.id}${o.date}`, "POST", `${base(c)}/skip`, { date: o.date }, `Skipped ${dayName(o.date, { day: "numeric", month: "long" })}.`)} className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline" aria-label={`Skip ${dayName(o.date)}`}>Skip</button>
)}
</li>
))}
</ul>
{c.upcoming.slice(0, 3).some((o) => o.locked) && <p className="mt-1 text-xs text-gray-600">To change a slot less than {data.rules.cancelHours} hours away, contact {contact}.</p>}
</div>
)}
{c.active && (
<details className="rounded-cc border border-gray-200">
<summary className="min-h-11 cursor-pointer px-3 py-2.5 text-sm font-semibold">Reminder and changes</summary>
<div className="space-y-3 border-t border-gray-200 p-3">
<div className="grid gap-3 sm:grid-cols-2">
<label className="block text-sm">
<span className="font-semibold">Reminder</span>
<select defaultValue={c.reminder} onChange={(e) => act(`r${c.id}`, "PATCH", base(c), { reminder: e.target.value as Reminder }, "Reminder saved.")} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2">
{(Object.keys(REMINDER_NAMES) as Reminder[]).map((r) => <option key={r} value={r}>{REMINDER_NAMES[r]}</option>)}
</select>
</label>
<label className="block text-sm">
<span className="font-semibold">By</span>
<select defaultValue={c.channel} onChange={(e) => act(`h${c.id}`, "PATCH", base(c), { channel: e.target.value as Channel }, "Saved.")} className="mt-1 block min-h-11 w-full rounded-cc border border-gray-300 px-2">
{(Object.keys(CHANNEL_NAMES) as Channel[]).map((ch) => <option key={ch} value={ch}>{CHANNEL_NAMES[ch]}</option>)}
</select>
</label>
</div>
{c.recurrence !== "once" && (
<form
className="flex flex-wrap items-end gap-2"
onSubmit={(e) => {
e.preventDefault();
const endDate = String(new FormData(e.currentTarget).get("endDate") ?? "");
if (endDate) void act(`e${c.id}`, "PATCH", base(c), { endDate }, "End date saved.");
}}
>
<label className="block text-sm">
<span className="font-semibold">Until</span>
<input name="endDate" type="date" defaultValue={c.endDate} min={today} className="mt-1 block min-h-11 rounded-cc border border-gray-300 px-2" />
</label>
<button type="submit" disabled={busy !== null} className="cca-btn-quiet">Save</button>
</form>
)}
<button
type="button"
disabled={busy !== null}
onClick={() => {
if (window.confirm(c.recurrence === "once" ? "Cancel this prayer slot?" : "Stop praying at this time? Slots already within the next hours stay booked.")) {
void act(`x${c.id}`, "DELETE", base(c), undefined, "Stopped. Thank you for praying.");
}
}}
className="cca-btn-quiet w-full !text-red-700"
>
{c.recurrence === "once" ? "Cancel this slot" : "Stop"}
</button>
</div>
</details>
)}
{c.canRenew && (
<div className="flex items-center justify-between gap-3 rounded-cc bg-amber-50 p-3">
<p className="text-sm">Ends {c.daysLeft <= 0 ? "today" : `in ${c.daysLeft} days`}.</p>
<button type="button" disabled={busy !== null} onClick={() => act(`n${c.id}`, "POST", `${base(c)}/renew`, undefined, "Renewed for another year. Thank you!")} className="cca-btn !min-h-10">Renew for another year</button>
</div>
)}
</section>
))}
</div>
);
}
@@ -0,0 +1,184 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { signInHref } from "@/lib/links";
import { addDays, dayName, hhmm, minuteIn, relativeDay, span, type Day } from "@/lib/prayer";
import { BookingSheet } from "./BookingSheet";
import { ClockSvg, coveredLine } from "./ClockSvg";
const POLL_MS = 30_000;
/**
* The House of Prayer's clock (APP-1.0-PLAN §3): pick a day, tap an hour for its details, then
* **Cover it** or **Join**. Live: it listens to /api/v1/prayer/stream and fetches the day again
* when anyone books or cancels; if the stream drops it polls every 30 seconds. The open slots are
* also listed as buttons, so it works with a keyboard and a screen reader.
*
* Signed out, "Cover it" goes to Accounts and comes back to this day with this slot's sheet open
* (`?day=…&slot=…`, ROADMAP-v3 §3).
*/
export function PrayerClock({ initial, signedIn, openSlot }: { initial: Day; signedIn: boolean; openSlot: number | null }) {
const router = useRouter();
const [day, setDay] = useState(initial);
const [selected, setSelected] = useState<number | null>(openSlot);
// Back from signing in, the slot's sheet opens, unless that slot has started meanwhile.
const [booking, setBooking] = useState<number | null>(() => {
const s = initial.slots.find((x) => x.minute === openSlot);
return signedIn && s && new Date(s.start) > new Date(initial.now) ? s.minute : null;
});
const [live, setLive] = useState<"live" | "polling">("live");
const dateRef = useRef(initial.date);
const load = useCallback(async (date: string) => {
try {
const res = await fetch(`/api/v1/prayer/day?date=${date}`, { cache: "no-store" });
if (res.ok && dateRef.current === date) setDay((await res.json()) as Day);
} catch {
// Offline: the last copy stays.
}
}, []);
const go = (date: string) => {
dateRef.current = date;
setSelected(null);
void load(date);
router.replace(`/prayer?day=${date}`, { scroll: false });
};
// Live updates, with polling when the stream isn't there.
useEffect(() => {
let poll: ReturnType<typeof setInterval> | null = null;
let timer: ReturnType<typeof setTimeout> | null = null;
const refresh = () => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => void load(dateRef.current), 300);
};
const startPolling = () => {
setLive("polling");
if (!poll) poll = setInterval(() => void load(dateRef.current), POLL_MS);
};
if (typeof EventSource === "undefined") {
startPolling();
return () => { if (poll) clearInterval(poll); };
}
const es = new EventSource("/api/v1/prayer/stream");
es.addEventListener("changed", (e) => {
const change = JSON.parse((e as MessageEvent).data) as { dates?: string[]; all?: boolean };
if (change.all || change.dates?.some((d) => d === dateRef.current || d === addDays(dateRef.current, -1))) refresh();
});
es.onopen = () => {
setLive("live");
if (poll) { clearInterval(poll); poll = null; }
};
es.onerror = () => startPolling();
return () => {
es.close();
if (poll) clearInterval(poll);
if (timer) clearTimeout(timer);
};
}, [load]);
const isToday = day.date === day.today;
const nowMinute = isToday ? minuteIn(day.now, day.timezone) : null;
const slot = selected === null ? null : day.slots.find((s) => s.minute === selected) ?? null;
const open = day.slots.filter((s) => !s.covered && (!isToday || new Date(s.end) > new Date(day.now)));
const past = (s: { start: string }) => new Date(s.start) <= new Date(day.now);
const countLine = (count: number) => (day.target > 1 ? `${count} of ${day.target}` : `${count} ${count === 1 ? "person" : "people"}`);
const cover = (minute: number) => {
if (!signedIn) {
window.location.href = signInHref(`/prayer?day=${day.date}&slot=${minute}`);
return;
}
setBooking(minute);
};
return (
<section className="cca-card space-y-4" aria-labelledby="clock-title">
<div className="flex items-center justify-between gap-2">
<button type="button" onClick={() => go(addDays(day.date, -1))} className="cca-btn-quiet !min-h-10 !px-2" aria-label="The day before">
<ChevronLeft className="h-5 w-5" aria-hidden />
</button>
<div className="text-center">
<h2 id="clock-title" className="cca-h2">{relativeDay(day.date, day.today)}</h2>
<p className="cca-muted">{dayName(day.date)}</p>
</div>
<button type="button" onClick={() => go(addDays(day.date, 1))} className="cca-btn-quiet !min-h-10 !px-2" aria-label="The day after">
<ChevronRight className="h-5 w-5" aria-hidden />
</button>
</div>
<ClockSvg
slots={day.slots}
slotMinutes={day.slotMinutes}
target={day.target}
nowMinute={nowMinute}
selected={selected}
onSelect={setSelected}
centre={{ big: nowMinute !== null ? hhmm(nowMinute) : dayName(day.date, { day: "numeric", month: "short" }), small: coveredLine(day.covered, day.total, day.slotMinutes) }}
label={`Prayer clock for ${dayName(day.date)}: ${coveredLine(day.covered, day.total, day.slotMinutes)}.`}
className="mx-auto w-full max-w-[20rem] select-none"
/>
<div className="flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-xs text-gray-600" aria-hidden>
<span className="flex items-center gap-1"><span className="h-3 w-3 rounded-sm bg-brand" />Covered</span>
<span className="flex items-center gap-1"><span className="h-3 w-3 rounded-sm border border-dashed border-gray-400" />Open</span>
<span className="flex items-center gap-1"><span className="h-3 w-3 rounded-sm border-2 border-[#c8961e]" />Yours</span>
</div>
<div aria-live="polite" className="min-h-[4.5rem]">
{slot ? (
<div className="flex items-center justify-between gap-3 rounded-cc bg-brand-tint p-3">
<div>
<p className="font-semibold">{span(slot.minute, day.slotMinutes)}</p>
<p className="cca-muted">
{slot.mine ? "You're praying" : slot.covered ? `${countLine(slot.count)} praying` : "Nobody yet"}
</p>
</div>
{past(slot) ? (
<span className="cca-muted">Already started</span>
) : slot.mine ? (
<a href="/me/prayer" className="cca-btn-quiet">My prayer</a>
) : (
<button type="button" className="cca-btn" onClick={() => cover(slot.minute)}>{slot.covered ? "Join" : "Cover it"}</button>
)}
</div>
) : (
<p className="cca-muted pt-3 text-center">Tap an hour to see it, or pick an open one below.</p>
)}
</div>
<div>
<h3 className="text-sm font-semibold">{open.length ? `Still open ${relativeDay(day.date, day.today).toLowerCase()}` : isToday ? "Every hour left today is covered" : "Every hour is covered"}</h3>
{open.length > 0 && (
<ul className="mt-2 flex flex-wrap gap-2">
{open.map((s) => (
<li key={s.minute}>
<button type="button" onClick={() => { setSelected(s.minute); if (!past(s)) cover(s.minute); }} className="cca-btn-quiet !min-h-10 !px-3" aria-label={`Cover ${span(s.minute, day.slotMinutes)}`}>
{hhmm(s.minute)}
</button>
</li>
))}
</ul>
)}
</div>
<p className="text-xs text-gray-500">{live === "live" ? "Updates live as people book." : "Updating every 30 seconds."} Only counts are shown, never names.</p>
{booking !== null && (
<BookingSheet
date={day.date}
minute={booking}
slotMinutes={day.slotMinutes}
onClose={() => setBooking(null)}
onBooked={() => {
setBooking(null);
void load(day.date);
router.refresh();
}}
/>
)}
</section>
);
}
@@ -0,0 +1,46 @@
import Link from "next/link";
import { hhmm, minuteIn, relativeDay, span, type Day, type MyPrayer } from "@/lib/prayer";
import { ClockSvg, coveredLine } from "./ClockSvg";
/**
* Home's House of Prayer card (APP-1.0-PLAN §3, decision 12; mockup "Home"): today's clock in
* small, the next open hour, and the member's next slot.
*/
export function PrayerHomeCard({ day, mine }: { day: Day; mine: MyPrayer | null }) {
const now = new Date(day.now);
const nextGap = day.slots.find((s) => !s.covered && new Date(s.start) > now);
const next = mine?.commitments
.flatMap((c) => c.upcoming.filter((o) => !o.skipped).map((o) => ({ ...o, minute: c.startMinute, length: c.durationMinutes })))
.sort((a, b) => a.start.localeCompare(b.start))[0];
return (
<section className="cca-card" aria-labelledby="home-prayer">
<div className="flex items-center gap-4">
<Link href="/prayer" className="w-32 shrink-0" aria-label="Open the House of Prayer">
<ClockSvg
slots={day.slots}
slotMinutes={day.slotMinutes}
target={day.target}
nowMinute={minuteIn(day.now, day.timezone)}
centre={{ big: `${day.covered}/${day.total}`, small: day.slotMinutes === 60 ? "hours" : "slots" }}
label={`Today's prayer clock: ${coveredLine(day.covered, day.total, day.slotMinutes)}.`}
className="w-full"
/>
</Link>
<div className="min-w-0 space-y-1">
<h2 id="home-prayer" className="cca-h2">House of Prayer</h2>
<p className="text-sm">{coveredLine(day.covered, day.total, day.slotMinutes)} today.</p>
{next ? (
<p className="text-sm font-medium">Your next slot: {relativeDay(next.date, day.today)}, {span(next.minute, next.length)}</p>
) : null}
{nextGap ? (
<Link href={`/prayer?day=${day.date}&slot=${nextGap.minute}`} className="inline-block text-sm font-semibold text-brand-text underline-offset-4 hover:underline">
Next gap: {hhmm(nextGap.minute)}. Cover it
</Link>
) : (
<Link href="/prayer" className="inline-block text-sm font-semibold text-brand-text underline-offset-4 hover:underline">Every hour left today is covered</Link>
)}
</div>
</div>
</section>
);
}
@@ -0,0 +1,87 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { errorMessage } from "@/lib/prayer";
export type MyTestimony = { id: string; text: string; showName: boolean; status: "pending" | "approved" | "removed"; removedReason: string | null; createdAt: string };
const STATUS = { pending: "Waiting for the prayer team", approved: "Shared with the church", removed: "Not shared" } as const;
/**
* Share a testimony (APP-1.0-PLAN §3): moderated before anyone sees it, the first name or
* "Anonymous", and the author can remove it at any time.
*/
export function TestimonyForm({ mine, campaign, firstName }: { mine: MyTestimony[]; campaign: { id: string; title: string } | null; firstName: string }) {
const router = useRouter();
const [text, setText] = useState("");
const [showName, setShowName] = useState(false);
const [forCampaign, setForCampaign] = useState(!!campaign);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
async function send(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setMessage(null);
try {
const res = await fetch("/api/v1/me/prayer/testimonies", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, showName, campaignId: forCampaign && campaign ? campaign.id : null }),
});
if (!res.ok) setMessage({ kind: "error", text: await errorMessage(res) });
else {
setText("");
setMessage({ kind: "ok", text: "Thank you! The prayer team will read it before it's shared." });
router.refresh();
}
} catch {
setMessage({ kind: "error", text: "You're offline. Sharing needs a connection." });
} finally {
setBusy(false);
}
}
async function remove(id: string) {
if (!window.confirm("Remove this testimony?")) return;
const res = await fetch(`/api/v1/me/prayer/testimonies/${id}`, { method: "DELETE" }).catch(() => null);
if (res?.ok) router.refresh();
else setMessage({ kind: "error", text: "It couldn't be removed. Please try again." });
}
return (
<div className="space-y-4">
<form onSubmit={send} className="cca-card space-y-3">
<label className="block">
<span className="font-semibold">What has God done?</span>
<textarea value={text} onChange={(e) => setText(e.target.value)} required minLength={10} maxLength={2000} rows={5} className="mt-1 block w-full rounded-cc border border-gray-300 p-3" />
</label>
<fieldset className="space-y-2">
<legend className="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>
{campaign && (
<label className="flex min-h-11 items-center gap-3 text-sm"><input type="checkbox" checked={forCampaign} onChange={(e) => setForCampaign(e.target.checked)} />Part of {campaign.title}</label>
)}
<p className="cca-muted">The prayer team reads every testimony before it&apos;s shared with the church.</p>
<div aria-live="polite">{message && <p role={message.kind === "error" ? "alert" : "status"} className={`rounded-cc p-3 text-sm ${message.kind === "error" ? "bg-red-50 text-red-800" : "bg-green-50 text-green-800"}`}>{message.text}</p>}</div>
<button type="submit" disabled={busy} className="cca-btn w-full disabled:opacity-60">{busy ? "Sending…" : "Share it"}</button>
</form>
{mine.length > 0 && (
<section className="space-y-3" aria-labelledby="mine">
<h2 id="mine" className="cca-h2">Yours</h2>
{mine.map((t) => (
<article key={t.id} className="cca-card space-y-2">
<p className="whitespace-pre-line">{t.text}</p>
<p className="cca-muted">{STATUS[t.status]}{t.status === "removed" && t.removedReason ? `: ${t.removedReason}` : ""}</p>
<button type="button" onClick={() => remove(t.id)} className="text-sm font-semibold text-red-700 underline-offset-4 hover:underline">Remove</button>
</article>
))}
</section>
)}
</div>
);
}
@@ -0,0 +1,44 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { dayName, errorMessage } from "@/lib/prayer";
const DONE = {
renew: (b: { endDate?: string }) => `Renewed for another year${b.endDate ? `, until ${dayName(b.endDate, { day: "numeric", month: "long", year: "numeric" })}` : ""}. Thank you for praying!`,
prayed: () => "Marked as prayed. Thank you!",
};
/**
* A link from a reminder or renewal notice (APP-1.0-PLAN §3): one tap, no sign-in. The page asks
* for the tap (a POST) rather than acting on opening, so a mail scanner opening the link changes
* nothing.
*/
export function TokenAction({ endpoint, token, button }: { endpoint: "renew" | "prayed"; token: string; button: string }) {
const [state, setState] = useState<{ kind: "idle" | "busy" } | { kind: "done" | "error"; text: string }>({ kind: "idle" });
async function go() {
setState({ kind: "busy" });
try {
const res = await fetch(`/api/v1/prayer/${endpoint}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token }) });
if (!res.ok) setState({ kind: "error", text: await errorMessage(res) });
else setState({ kind: "done", text: DONE[endpoint]((await res.json()) as { endDate?: string }) });
} catch {
setState({ kind: "error", text: "You're offline. Please try again with a connection." });
}
}
if (state.kind === "done" || state.kind === "error") {
return (
<div className="space-y-3" aria-live="polite">
<p role={state.kind === "error" ? "alert" : "status"} className={`rounded-cc p-3 ${state.kind === "error" ? "bg-red-50 text-red-800" : "bg-green-50 text-green-800"}`}>{state.text}</p>
<Link href="/prayer" className="cca-btn-quiet w-full">Go to the House of Prayer</Link>
</div>
);
}
return (
<button type="button" onClick={go} disabled={state.kind === "busy" || !token} className="cca-btn w-full disabled:opacity-60">
{state.kind === "busy" ? "One moment…" : button}
</button>
);
}
@@ -0,0 +1,399 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { addDays, dayName, duration, errorMessage, hhmm, span, type Recurrence } from "@/lib/prayer";
const TABS = [
{ key: "week", label: "This week" },
{ key: "bookings", label: "Who prays when" },
{ key: "rules", label: "Rules" },
{ key: "campaigns", label: "Campaigns" },
{ key: "testimonies", label: "Testimonies" },
] as const;
type Tab = (typeof TABS)[number]["key"];
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/prayer${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." };
}
}
function Panel({ title, children, aside }: { title: string; children: React.ReactNode; aside?: React.ReactNode }) {
return (
<section className="rounded-lg border border-gray-200 bg-white p-5 shadow-sm">
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
<h2 className="text-lg font-semibold">{title}</h2>
{aside}
</div>
{children}
</section>
);
}
function Notice({ msg }: { msg: { kind: "ok" | "error"; text: string } | null }) {
if (!msg) return null;
return <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>;
}
const input = "mt-1 block min-h-10 w-full rounded-md border border-gray-300 px-2 text-sm";
/** The admin's House of Prayer (APP-1.0-PLAN §3, §10), in the Website's and Events' admin style (decision 9). */
export function AdminPrayer({ today }: { today: string }) {
const [tab, setTab] = useState<Tab>("week");
return (
<div className="space-y-6">
<div role="tablist" aria-label="House of Prayer" className="flex flex-wrap gap-1 border-b border-gray-200">
{TABS.map((t) => (
<button
key={t.key}
role="tab"
id={`tab-${t.key}`}
aria-selected={tab === t.key}
aria-controls={`panel-${t.key}`}
onClick={() => setTab(t.key)}
className={`-mb-px border-b-2 px-3 py-2 text-sm font-medium ${tab === t.key ? "border-brand text-brand-text" : "border-transparent text-gray-600 hover:text-gray-900"}`}
>
{t.label}
</button>
))}
</div>
<div role="tabpanel" id={`panel-${tab}`} aria-labelledby={`tab-${tab}`}>
{tab === "week" && <Week today={today} />}
{tab === "bookings" && <Bookings today={today} />}
{tab === "rules" && <Rules />}
{tab === "campaigns" && <Campaigns today={today} />}
{tab === "testimonies" && <Testimonies />}
</div>
</div>
);
}
// ── This week ──
type WeekData = { slotMinutes: number; target: number; days: { date: string; covered: number; total: number; gaps: number[]; slots: number[] }[] };
function Week({ today }: { today: string }) {
const [from, setFrom] = useState(today);
const [data, setData] = useState<WeekData | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
call<WeekData>("GET", `/week?from=${from}`).then((r) => (r.ok ? (setData(r.data), setError(null)) : setError(r.error)));
}, [from]);
return (
<Panel
title={`Coverage from ${dayName(from, { day: "numeric", month: "long" })}`}
aside={
<div className="flex gap-2">
<button className="cca-btn-quiet !min-h-9" onClick={() => setFrom(addDays(from, -7))}>Week before</button>
<button className="cca-btn-quiet !min-h-9" onClick={() => setFrom(today)}>This week</button>
<button className="cca-btn-quiet !min-h-9" onClick={() => setFrom(addDays(from, 7))}>Week after</button>
</div>
}
>
{error && <Notice msg={{ kind: "error", text: error }} />}
{data && (
<div className="space-y-3">
{data.days.map((d) => (
<div key={d.date} className="grid grid-cols-[7rem_1fr_4.5rem] items-center gap-3 text-sm">
<span className="font-medium">{dayName(d.date, { weekday: "short", day: "numeric", month: "short" })}</span>
<div className="flex h-6 overflow-hidden rounded" aria-hidden>
{d.slots.map((count, i) => (
<span key={i} className="flex-1 border-r border-white last:border-0" style={{ background: count ? `rgb(var(--brand) / ${0.35 + 0.65 * Math.min(1, count / data.target)})` : "#e5e7eb" }} title={`${hhmm(i * data.slotMinutes)}: ${count}`} />
))}
</div>
<span className="text-right tabular-nums">{d.covered}/{d.total}</span>
<span className="sr-only">{d.covered} of {d.total} covered. {d.gaps.length ? `Open: ${d.gaps.map(hhmm).join(", ")}.` : "No gaps."}</span>
{d.gaps.length > 0 && <p className="col-span-3 -mt-1 text-xs text-gray-600" aria-hidden>Open: {d.gaps.map(hhmm).join(", ")}</p>}
</div>
))}
<p className="text-xs text-gray-500">Counts only. Names are under &quot;Who prays when&quot;, and every view of them is logged.</p>
</div>
)}
</Panel>
);
}
// ── Who prays when (names) and booking for a member ──
type Booking = { commitmentId: string; start: string; end: string; recurrence: Recurrence; member: { id: string; name: string; email: string; phone: string | null } | null };
function Bookings({ today }: { today: string }) {
const [date, setDate] = useState(today);
const [shown, setShown] = useState<{ date: string; timezone: string; people: Booking[] } | null>(null);
const [msg, setMsg] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
const show = useCallback(async () => {
const r = await call<{ date: string; timezone: string; people: Booking[] }>("GET", `/bookings?date=${date}`);
if (r.ok) setShown(r.data);
else setMsg({ kind: "error", text: r.error });
}, [date]);
async function cancelOne(b: Booking) {
if (!window.confirm(`Cancel ${b.member?.name ?? "this"}'s slot from now on? The 8-hour rule doesn't apply to you.`)) return;
const r = await call("DELETE", `/commitments/${b.commitmentId}`);
setMsg(r.ok ? { kind: "ok", text: "Cancelled." } : { kind: "error", text: r.error });
if (r.ok) void show();
}
const time = (iso: string, tz: string) => new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).format(new Date(iso));
return (
<div className="space-y-6">
<Panel title="Who prays when">
<div className="flex flex-wrap items-end gap-3">
<label className="text-sm font-medium">Day<input type="date" value={date} onChange={(e) => { setDate(e.target.value); setShown(null); }} className={input} /></label>
<button className="cca-btn" onClick={show}>Show names</button>
</div>
<p className="mt-2 text-xs text-gray-600">Showing names is recorded in the access log, with your name and the day.</p>
<div className="mt-4"><Notice msg={msg} /></div>
{shown && (
shown.people.length ? (
<table className="mt-4 w-full text-left text-sm">
<thead className="border-b border-gray-200 text-gray-600"><tr><th className="py-2">Time</th><th>Who</th><th className="hidden sm:table-cell">Contact</th><th /></tr></thead>
<tbody>
{shown.people.map((b) => (
<tr key={`${b.commitmentId}${b.start}`} className="border-b border-gray-100">
<td className="py-2 tabular-nums">{time(b.start, shown.timezone)}–{time(b.end, shown.timezone)}</td>
<td>{b.member?.name ?? "—"}<span className="block text-xs text-gray-500">{b.recurrence === "once" ? "Once" : b.recurrence === "daily" ? "Every day" : "Every week"}</span></td>
<td className="hidden sm:table-cell">{b.member?.email}{b.member?.phone && <span className="block text-xs text-gray-500">{b.member.phone}</span>}</td>
<td className="text-right"><button className="text-sm font-medium text-red-700 hover:underline" onClick={() => cancelOne(b)}>Cancel</button></td>
</tr>
))}
</tbody>
</table>
) : <p className="mt-4 text-sm text-gray-600">Nobody has booked this day yet.</p>
)}
</Panel>
<BookForMember today={today} onBooked={() => shown && void show()} />
</div>
);
}
function BookForMember({ today, onBooked }: { today: string; onBooked: () => void }) {
const [q, setQ] = useState("");
const [found, setFound] = useState<{ id: string; name: string; email: string }[]>([]);
const [member, setMember] = useState<{ id: string; name: string } | null>(null);
const [form, setForm] = useState({ startDate: addDays(today, 1), time: "02:00", durationMinutes: 60, recurrence: "once" as Recurrence });
const [msg, setMsg] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
async function search(e: React.FormEvent) {
e.preventDefault();
const r = await call<{ members: { id: string; name: string; email: string }[] }>("GET", `/members?q=${encodeURIComponent(q)}`);
if (r.ok) setFound(r.data.members);
}
async function book(e: React.FormEvent) {
e.preventDefault();
if (!member) return;
const [h, m] = form.time.split(":").map(Number);
const r = await call("POST", "/commitments", { memberId: member.id, startDate: form.startDate, startMinute: (h ?? 0) * 60 + (m ?? 0), durationMinutes: form.durationMinutes, recurrence: form.recurrence });
setMsg(r.ok ? { kind: "ok", text: `Booked for ${member.name}.` } : { kind: "error", text: r.error });
if (r.ok) onBooked();
}
return (
<Panel title="Book for a member">
<p className="mb-3 text-sm text-gray-600">For someone who asked the prayer team to book for them. They must have signed in to the App once.</p>
{!member ? (
<>
<form onSubmit={search} className="flex flex-wrap items-end gap-3">
<label className="min-w-[14rem] flex-1 text-sm font-medium">Name or email<input value={q} onChange={(e) => setQ(e.target.value)} minLength={2} className={input} /></label>
<button className="cca-btn-quiet">Find</button>
</form>
{found.length > 0 && (
<ul className="mt-3 divide-y divide-gray-100 text-sm">
{found.map((f) => (
<li key={f.id} className="flex items-center justify-between py-2">
<span>{f.name} <span className="text-gray-500">{f.email}</span></span>
<button className="font-medium text-brand-text hover:underline" onClick={() => setMember(f)}>Choose</button>
</li>
))}
</ul>
)}
</>
) : (
<form onSubmit={book} className="space-y-3">
<p className="text-sm">For <strong>{member.name}</strong> · <button type="button" className="text-brand-text hover:underline" onClick={() => setMember(null)}>someone else</button></p>
<div className="grid gap-3 sm:grid-cols-4">
<label className="text-sm font-medium">First day<input type="date" value={form.startDate} min={today} onChange={(e) => setForm({ ...form, startDate: e.target.value })} className={input} /></label>
<label className="text-sm font-medium">Time<input type="time" step={900} value={form.time} onChange={(e) => setForm({ ...form, time: e.target.value })} className={input} /></label>
<label className="text-sm font-medium">How long
<select value={form.durationMinutes} onChange={(e) => setForm({ ...form, durationMinutes: Number(e.target.value) })} className={input}>
{[15, 30, 60, 120, 180, 240].map((m) => <option key={m} value={m}>{duration(m)}</option>)}
</select>
</label>
<label className="text-sm font-medium">How often
<select value={form.recurrence} onChange={(e) => setForm({ ...form, recurrence: e.target.value as Recurrence })} className={input}>
<option value="once">Once</option><option value="weekly">Every week</option><option value="daily">Every day</option>
</select>
</label>
</div>
<Notice msg={msg} />
<button className="cca-btn">Book {span(Number(form.time.slice(0, 2)) * 60 + Number(form.time.slice(3, 5)), form.durationMinutes)}</button>
</form>
)}
</Panel>
);
}
// ── Rules ──
type Wall = { slotMinutes: 15 | 30 | 60; targetPerSlot: number; bookAheadMonths: number; recurringMaxMonths: number; cancelHours: number; coordinator: { name: string | null; contact: string | null } };
function Rules() {
const [wall, setWall] = useState<Wall | null>(null);
const [msg, setMsg] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
useEffect(() => { call<{ wall: Wall }>("GET", "/wall").then((r) => r.ok && setWall(r.data.wall)); }, []);
if (!wall) return <Panel title="The prayer wall's rules"><p className="text-sm text-gray-600">Loading…</p></Panel>;
const num = (k: keyof Wall) => (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => setWall({ ...wall, [k]: Number(e.target.value) });
async function save(e: React.FormEvent) {
e.preventDefault();
const r = await call<{ wall: Wall }>("PUT", "/wall", { ...wall, coordinator: { name: wall!.coordinator.name?.trim() || null, contact: wall!.coordinator.contact?.trim() || null } });
setMsg(r.ok ? { kind: "ok", text: "Saved." } : { kind: "error", text: r.error });
if (r.ok) setWall(r.data.wall);
}
return (
<Panel title="The prayer wall's rules">
<form onSubmit={save} className="space-y-4">
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<label className="text-sm font-medium">Slot length
<select value={wall.slotMinutes} onChange={num("slotMinutes")} className={input}>
<option value={60}>1 hour</option><option value={30}>30 minutes</option><option value={15}>15 minutes</option>
</select>
</label>
<label className="text-sm font-medium">People per slot (target)<input type="number" min={1} max={50} value={wall.targetPerSlot} onChange={num("targetPerSlot")} className={input} /></label>
<label className="text-sm font-medium">Changes allowed up to (hours before)<input type="number" min={0} max={48} value={wall.cancelHours} onChange={num("cancelHours")} className={input} /></label>
<label className="text-sm font-medium">Book up to (months ahead)<input type="number" min={1} max={12} value={wall.bookAheadMonths} onChange={num("bookAheadMonths")} className={input} /></label>
<label className="text-sm font-medium">Recurring slots last up to (months)<input type="number" min={1} max={12} value={wall.recurringMaxMonths} onChange={num("recurringMaxMonths")} className={input} /></label>
</div>
<fieldset className="grid gap-4 sm:grid-cols-2">
<legend className="mb-1 text-sm font-semibold">Who members contact inside the change window</legend>
<label className="text-sm font-medium">Name<input value={wall.coordinator.name ?? ""} maxLength={120} onChange={(e) => setWall({ ...wall, coordinator: { ...wall.coordinator, name: e.target.value } })} className={input} /></label>
<label className="text-sm font-medium">How to reach them<input value={wall.coordinator.contact ?? ""} maxLength={200} placeholder="082 555 0101 or an email" onChange={(e) => setWall({ ...wall, coordinator: { ...wall.coordinator, contact: e.target.value } })} className={input} /></label>
</fieldset>
<p className="text-xs text-gray-600">A slot counts as covered with one person; the target is what &quot;2 of 3&quot; is measured against. Changing the slot length keeps everyone&apos;s bookings.</p>
<Notice msg={msg} />
<button className="cca-btn">Save the rules</button>
</form>
</Panel>
);
}
// ── Campaigns ──
type CampaignRow = { id: string; title: string; description: string; imageUrl: string | null; startDate: string; endDate: string; goal: string | null; targetPerSlot: number | null };
const blank = (today: string): Omit<CampaignRow, "id"> => ({ title: "", description: "", imageUrl: null, startDate: addDays(today, 7), endDate: addDays(today, 27), goal: "Every hour covered", targetPerSlot: null });
function Campaigns({ today }: { today: string }) {
const [list, setList] = useState<CampaignRow[]>([]);
const [editing, setEditing] = useState<(Omit<CampaignRow, "id"> & { id?: string }) | null>(null);
const [msg, setMsg] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
const load = useCallback(() => call<{ campaigns: CampaignRow[] }>("GET", "/campaigns").then((r) => r.ok && setList(r.data.campaigns)), []);
useEffect(() => { void load(); }, [load]);
async function save(e: React.FormEvent) {
e.preventDefault();
if (!editing) return;
const { id, ...body } = editing;
const r = await call(id ? "PUT" : "POST", id ? `/campaigns/${id}` : "/campaigns", { ...body, imageUrl: body.imageUrl || null, goal: body.goal || null });
setMsg(r.ok ? { kind: "ok", text: "Saved." } : { kind: "error", text: r.error });
if (r.ok) { setEditing(null); void load(); }
}
async function remove(c: CampaignRow) {
if (!window.confirm(`Delete "${c.title}"? Its testimonies stay.`)) return;
const r = await call("DELETE", `/campaigns/${c.id}`);
if (r.ok) void load();
}
return (
<Panel title="Campaigns" aside={!editing && <button className="cca-btn !min-h-9" onClick={() => setEditing(blank(today))}>New campaign</button>}>
<Notice msg={msg} />
{editing ? (
<form onSubmit={save} className="space-y-3">
<label className="block text-sm font-medium">Title<input required minLength={3} maxLength={120} value={editing.title} onChange={(e) => setEditing({ ...editing, title: e.target.value })} className={input} placeholder="21 days of prayer" /></label>
<label className="block text-sm font-medium">Description<textarea rows={3} maxLength={4000} value={editing.description} onChange={(e) => setEditing({ ...editing, description: e.target.value })} className={`${input} py-2`} /></label>
<div className="grid gap-3 sm:grid-cols-4">
<label className="text-sm font-medium">From<input type="date" required value={editing.startDate} onChange={(e) => setEditing({ ...editing, startDate: e.target.value })} className={input} /></label>
<label className="text-sm font-medium">To<input type="date" required value={editing.endDate} min={editing.startDate} onChange={(e) => setEditing({ ...editing, endDate: e.target.value })} className={input} /></label>
<label className="text-sm font-medium">Aim<input maxLength={200} value={editing.goal ?? ""} onChange={(e) => setEditing({ ...editing, goal: e.target.value })} className={input} /></label>
<label className="text-sm font-medium">People per slot<input type="number" min={1} max={50} value={editing.targetPerSlot ?? ""} placeholder="As the wall" onChange={(e) => setEditing({ ...editing, targetPerSlot: e.target.value ? Number(e.target.value) : null })} className={input} /></label>
</div>
<label className="block text-sm font-medium">Image address (optional)<input type="url" value={editing.imageUrl ?? ""} onChange={(e) => setEditing({ ...editing, imageUrl: e.target.value })} className={input} /></label>
<p className="text-xs text-gray-600">During a campaign, Home and the Prayer tab lead with it: days left, coverage so far and hours prayed (self-reported). Never rankings or anyone&apos;s own total.</p>
<div className="flex gap-2"><button className="cca-btn">Save</button><button type="button" className="cca-btn-quiet" onClick={() => setEditing(null)}>Cancel</button></div>
</form>
) : list.length ? (
<ul className="divide-y divide-gray-100">
{list.map((c) => (
<li key={c.id} className="flex flex-wrap items-center justify-between gap-2 py-3 text-sm">
<div>
<p className="font-medium">{c.title}</p>
<p className="text-gray-600">{dayName(c.startDate, { day: "numeric", month: "short", year: "numeric" })} – {dayName(c.endDate, { day: "numeric", month: "short", year: "numeric" })}{c.startDate <= today && c.endDate >= today ? " · running now" : ""}</p>
</div>
<div className="flex gap-3"><button className="font-medium text-brand-text hover:underline" onClick={() => setEditing(c)}>Edit</button><button className="font-medium text-red-700 hover:underline" onClick={() => remove(c)}>Delete</button></div>
</li>
))}
</ul>
) : <p className="text-sm text-gray-600">No campaigns yet. A time-bound focus, such as 21 days of prayer before a conference, rallies the church.</p>}
</Panel>
);
}
// ── Testimonies ──
type TestimonyRow = { id: string; text: string; showName: boolean; status: string; removedReason: string | null; createdAt: string; author: string | null };
function Testimonies() {
const [status, setStatus] = useState<"pending" | "approved" | "removed">("pending");
const [rows, setRows] = useState<TestimonyRow[]>([]);
const [msg, setMsg] = useState<{ kind: "ok" | "error"; text: string } | null>(null);
const load = useCallback(() => call<{ testimonies: TestimonyRow[] }>("GET", `/testimonies?status=${status}`).then((r) => r.ok && setRows(r.data.testimonies)), [status]);
useEffect(() => { void load(); }, [load]);
async function approve(t: TestimonyRow) {
const r = await call("POST", `/testimonies/${t.id}/approve`);
setMsg(r.ok ? { kind: "ok", text: "Shared with the church." } : { kind: "error", text: r.error });
void load();
}
async function remove(t: TestimonyRow) {
const reason = window.prompt("Why isn't it being shared? Its author is told.");
if (!reason) return;
const r = await call("POST", `/testimonies/${t.id}/remove`, { reason });
setMsg(r.ok ? { kind: "ok", text: "Not shared; its author will be told why." } : { kind: "error", text: r.error });
void load();
}
return (
<Panel
title="Testimonies"
aside={
<select value={status} onChange={(e) => setStatus(e.target.value as typeof status)} className="min-h-9 rounded-md border border-gray-300 px-2 text-sm" aria-label="Show">
<option value="pending">Waiting</option><option value="approved">Shared</option><option value="removed">Not shared</option>
</select>
}
>
<Notice msg={msg} />
{rows.length ? (
<ul className="space-y-3">
{rows.map((t) => (
<li key={t.id} className="rounded-md border border-gray-200 p-4 text-sm">
<p className="whitespace-pre-line">{t.text}</p>
<p className="mt-2 text-gray-600">From {t.author ?? "a deleted account"} · shown as {t.showName ? "their first name" : "Anonymous"}{t.removedReason ? ` · not shared: ${t.removedReason}` : ""}</p>
<div className="mt-3 flex gap-2">
{t.status !== "approved" && <button className="cca-btn !min-h-9" onClick={() => approve(t)}>Share</button>}
{t.status !== "removed" && <button className="cca-btn-quiet !min-h-9" onClick={() => remove(t)}>Don&apos;t share</button>}
</div>
</li>
))}
</ul>
) : <p className="text-sm text-gray-600">{status === "pending" ? "Nothing waiting." : "None."}</p>}
</Panel>
);
}
+2
View File
@@ -0,0 +1,2 @@
/** Where "Sign in" goes: Accounts, and back to that exact page (ROADMAP-v3 §3). `mfa` for the admin. Safe in client components. */
export const signInHref = (returnTo: string, mfa = false) => `/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? "&mfa=1" : ""}`;
+1 -2
View File
@@ -93,8 +93,7 @@ export const loadMe = cache(async (): Promise<Me | null> => {
return null; return null;
}); });
/** Where "Sign in" goes: Accounts, and back to that exact page (ROADMAP-v3 §3). `mfa` for the admin. */ export { signInHref } from "./links";
export const signInHref = (returnTo: string, mfa = false) => `/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? "&mfa=1" : ""}`;
/** The first name for a greeting ("Good morning, Thandi"). */ /** The first name for a greeting ("Good morning, Thandi"). */
export const firstName = (name: string) => name.trim().split(/\s+/)[0] ?? name; export const firstName = (name: string) => name.trim().split(/\s+/)[0] ?? name;
+139
View File
@@ -0,0 +1,139 @@
/**
* The House of Prayer's shapes and formatting, for server and client components alike
* (backend/src/prayer/*). Times are shown in the church's timezone, never the phone's.
*/
export type Slot = { minute: number; start: string; end: string; count: number; covered: boolean; mine: boolean };
/** GET /api/v1/prayer/day */
export type Day = {
date: string;
slots: Slot[];
covered: number;
total: number;
timezone: string;
slotMinutes: number;
target: number;
today: string;
now: string;
};
/** GET /api/v1/prayer/campaign */
export type Campaign = {
id: string;
title: string;
description: string;
imageUrl: string | null;
goal: string | null;
startDate: string;
endDate: string;
targetPerSlot: number | null;
started: boolean;
daysLeft: number;
startsInDays: number;
coveragePercent: number;
hoursPrayed: number;
};
export type Testimony = { id: string; text: string; by: string; campaignId: string | null; createdAt: string };
export type Recurrence = "once" | "daily" | "weekly";
export type Reminder = "none" | "min15" | "hour1" | "evening";
export type Channel = "email" | "whatsapp" | "both";
/** GET /api/v1/me/prayer */
export type MyPrayer = {
timezone: string;
rules: { slotMinutes: number; cancelHours: number; bookAheadMonths: number; recurringMaxMonths: number };
coordinator: { name: string | null; contact: string | null };
commitments: {
id: string;
startDate: string;
startMinute: number;
durationMinutes: number;
recurrence: Recurrence;
endDate: string;
reminder: Reminder;
channel: Channel;
note: string | null;
active: boolean;
daysLeft: number;
canRenew: boolean;
upcoming: { date: string; start: string; end: string; skipped: boolean; locked: boolean }[];
toMark: string[];
}[];
prayedTotal: number;
};
export const REMINDER_NAMES: Record<Reminder, string> = {
none: "No reminder",
min15: "15 minutes before",
hour1: "1 hour before",
evening: "The evening before (20:00)",
};
export const CHANNEL_NAMES: Record<Channel, string> = { email: "Email", whatsapp: "WhatsApp", both: "Email and WhatsApp" };
/** "02:00" from minutes after midnight (wraps past midnight). */
export const hhmm = (minute: number) => {
const m = ((minute % 1440) + 1440) % 1440;
return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
};
/** "02:00–03:00" */
export const span = (minute: number, length: number) => `${hhmm(minute)}–${hhmm(minute + length)}`;
/** "2 hours", "30 minutes", "1 hour 30 minutes" */
export function duration(minutes: number): string {
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return [h ? `${h} hour${h === 1 ? "" : "s"}` : "", m ? `${m} minutes` : ""].filter(Boolean).join(" ");
}
const midday = (date: string) => new Date(`${date}T12:00:00Z`);
/** "Wednesday 2 December" for a local date (the date itself, no timezone shift). */
export const dayName = (date: string, opts: Intl.DateTimeFormatOptions = { weekday: "long", day: "numeric", month: "long" }) =>
new Intl.DateTimeFormat("en-ZA", { ...opts, timeZone: "UTC" }).format(midday(date));
/** "Today", "Tomorrow" or "Wed 2 Dec". */
export function relativeDay(date: string, today: string): string {
if (date === today) return "Today";
if (date === addDays(today, 1)) return "Tomorrow";
if (date === addDays(today, -1)) return "Yesterday";
return dayName(date, { weekday: "short", day: "numeric", month: "short" });
}
export function addDays(date: string, n: number): string {
const d = midday(date);
d.setUTCDate(d.getUTCDate() + n);
return d.toISOString().slice(0, 10);
}
/** "Every Wednesday", "Every day" or "Once, Wed 2 Dec". */
export function repeats(c: { recurrence: Recurrence; startDate: string }): string {
if (c.recurrence === "daily") return "Every day";
if (c.recurrence === "weekly") return `Every ${dayName(c.startDate, { weekday: "long" })}`;
return `Once, ${dayName(c.startDate, { weekday: "short", day: "numeric", month: "short" })}`;
}
/** The local minute of an ISO instant in `tz` (the clock's hand). */
export function minuteIn(iso: string, tz: string): number {
const p = new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(new Date(iso));
const n = (t: string) => Number(p.find((x) => x.type === t)?.value ?? 0);
return n("hour") * 60 + n("minute");
}
/** An API error's message, or a fallback. */
export async function errorMessage(res: Response, fallback = "That didn't work. Please try again."): Promise<string> {
try {
const body = (await res.json()) as { error?: { message?: string } };
return body.error?.message ?? fallback;
} catch {
return fallback;
}
}
/** Today's local date in `tz`. */
export const localToday = (tz: string, at = new Date()) =>
new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" }).format(at);
+23
View File
@@ -0,0 +1,23 @@
import { cookies } from "next/headers";
import { api, SESSION_COOKIE } from "./load";
import type { Campaign, Day, MyPrayer, Testimony } from "./prayer";
/** A backend GET with the member's session (if any); null when it can't answer. */
export async function backendGet<T>(path: string): Promise<T | null> {
const session = (await cookies()).get(SESSION_COOKIE)?.value;
try {
const res = await fetch(`${api}${path}`, {
headers: session ? { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(session)}` } : {},
cache: "no-store",
});
if (res.ok) return (await res.json()) as T;
} catch {
// The backend is starting or down.
}
return null;
}
export const loadDay = (date?: string | null) => backendGet<Day>(`/api/v1/prayer/day${date ? `?date=${encodeURIComponent(date)}` : ""}`);
export const loadCampaign = async () => (await backendGet<{ campaign: Campaign | null }>("/api/v1/prayer/campaign"))?.campaign ?? null;
export const loadTestimonies = async () => (await backendGet<{ testimonies: Testimony[] }>("/api/v1/prayer/testimonies"))?.testimonies ?? [];
export const loadMyPrayer = () => backendGet<MyPrayer>("/api/v1/me/prayer");