From 1dd3aadb607fc7ab222b5605733327542f6e695a Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 1 Dec 2026 10:42:35 +0200 Subject: [PATCH] =?UTF-8?q?app:=20the=20House=20of=20Prayer's=20screens,?= =?UTF-8?q?=20changelog=20and=20README=20(APP-1.0-PLAN=20=C2=A73)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- apps/app/CHANGELOG.md | 33 +- apps/app/README.md | 8 +- apps/app/frontend/src/app/admin/page.tsx | 5 + .../frontend/src/app/admin/prayer/page.tsx | 39 ++ apps/app/frontend/src/app/me/page.tsx | 7 +- apps/app/frontend/src/app/me/prayer/page.tsx | 51 +++ apps/app/frontend/src/app/page.tsx | 8 +- apps/app/frontend/src/app/prayer/page.tsx | 56 ++- .../frontend/src/app/prayer/prayed/page.tsx | 21 + .../frontend/src/app/prayer/renew/page.tsx | 21 + .../src/app/prayer/testimony/page.tsx | 32 ++ .../src/components/prayer/BookingSheet.tsx | 136 ++++++ .../src/components/prayer/CampaignCard.tsx | 35 ++ .../src/components/prayer/ClockSvg.tsx | 113 +++++ .../src/components/prayer/MyPrayerList.tsx | 152 +++++++ .../src/components/prayer/PrayerClock.tsx | 184 ++++++++ .../src/components/prayer/PrayerHomeCard.tsx | 46 ++ .../src/components/prayer/TestimonyForm.tsx | 87 ++++ .../src/components/prayer/TokenAction.tsx | 44 ++ .../components/prayer/admin/AdminPrayer.tsx | 399 ++++++++++++++++++ apps/app/frontend/src/lib/links.ts | 2 + apps/app/frontend/src/lib/load.ts | 3 +- apps/app/frontend/src/lib/prayer.ts | 139 ++++++ apps/app/frontend/src/lib/prayerServer.ts | 23 + 24 files changed, 1631 insertions(+), 13 deletions(-) create mode 100644 apps/app/frontend/src/app/admin/prayer/page.tsx create mode 100644 apps/app/frontend/src/app/me/prayer/page.tsx create mode 100644 apps/app/frontend/src/app/prayer/prayed/page.tsx create mode 100644 apps/app/frontend/src/app/prayer/renew/page.tsx create mode 100644 apps/app/frontend/src/app/prayer/testimony/page.tsx create mode 100644 apps/app/frontend/src/components/prayer/BookingSheet.tsx create mode 100644 apps/app/frontend/src/components/prayer/CampaignCard.tsx create mode 100644 apps/app/frontend/src/components/prayer/ClockSvg.tsx create mode 100644 apps/app/frontend/src/components/prayer/MyPrayerList.tsx create mode 100644 apps/app/frontend/src/components/prayer/PrayerClock.tsx create mode 100644 apps/app/frontend/src/components/prayer/PrayerHomeCard.tsx create mode 100644 apps/app/frontend/src/components/prayer/TestimonyForm.tsx create mode 100644 apps/app/frontend/src/components/prayer/TokenAction.tsx create mode 100644 apps/app/frontend/src/components/prayer/admin/AdminPrayer.tsx create mode 100644 apps/app/frontend/src/lib/links.ts create mode 100644 apps/app/frontend/src/lib/prayer.ts create mode 100644 apps/app/frontend/src/lib/prayerServer.ts diff --git a/apps/app/CHANGELOG.md b/apps/app/CHANGELOG.md index b405e79..fbc7a8c 100644 --- a/apps/app/CHANGELOG.md +++ b/apps/app/CHANGELOG.md @@ -2,7 +2,8 @@ ## [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 @@ -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 (`/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. +- **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 in development). diff --git a/apps/app/README.md b/apps/app/README.md index 4844feb..97f85a9 100644 --- a/apps/app/README.md +++ b/apps/app/README.md @@ -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 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 (`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 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. +- **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 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. diff --git a/apps/app/frontend/src/app/admin/page.tsx b/apps/app/frontend/src/app/admin/page.tsx index ddccae3..4e15c25 100644 --- a/apps/app/frontend/src/app/admin/page.tsx +++ b/apps/app/frontend/src/app/admin/page.tsx @@ -96,6 +96,11 @@ export default async function Admin() { )} + {o?.modules.includes("house-of-prayer") && me.activeRoles.some((r) => ["owner", "church_admin", "prayer_coordinator"].includes(r)) && ( + + House of Prayer: the week, who prays when, rules, campaigns, testimonies› + + )} Back to the App ); diff --git a/apps/app/frontend/src/app/admin/prayer/page.tsx b/apps/app/frontend/src/app/admin/prayer/page.tsx new file mode 100644 index 0000000..21a8f38 --- /dev/null +++ b/apps/app/frontend/src/app/admin/prayer/page.tsx @@ -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 ( +
+

House of Prayer

+

The House of Prayer is switched off. An Owner or Church admin can switch it on in Settings → Modules.

+ Back to the dashboard +
+ ); + } + return ( +
+
+ ← Dashboard +

House of Prayer

+
+ +
+ ); +} diff --git a/apps/app/frontend/src/app/me/page.tsx b/apps/app/frontend/src/app/me/page.tsx index 42a2400..63e1ab2 100644 --- a/apps/app/frontend/src/app/me/page.tsx +++ b/apps/app/frontend/src/app/me/page.tsx @@ -1,7 +1,7 @@ import type { Metadata } from "next"; import Link from "next/link"; 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 } }; @@ -11,7 +11,7 @@ export const metadata: Metadata = { title: "Me", robots: { index: false, follow: * their modules (§3, §4, §8). */ export default async function Me() { - const me = await loadMe(); + const [me, app] = await Promise.all([loadMe(), loadApp()]); if (!me) { return ( @@ -31,6 +31,9 @@ export default async function Me() {

{me.member.email}

{roles.length ? roles.map((r) => ROLE_NAMES[r]).join(", ") : "Member"}

+ {app.modules.includes("house-of-prayer") && ( + My prayer› + )} {roles.length > 0 && (

The App's admin

diff --git a/apps/app/frontend/src/app/me/prayer/page.tsx b/apps/app/frontend/src/app/me/prayer/page.tsx new file mode 100644 index 0000000..69f04ab --- /dev/null +++ b/apps/app/frontend/src/app/me/prayer/page.tsx @@ -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 ( + +

My prayer

+
+

Sign in to see and change your prayer slots.

+ Sign in +
+
+ ); + } + const data = await loadMyPrayer(); + return ( + +

My prayer

+ {!data ? ( +

Your prayer slots can't be loaded right now. Please try again in a minute.

+ ) : ( + <> + {data.prayedTotal > 0 && ( +

{data.prayedTotal} {data.prayedTotal === 1 ? "time" : "times"} marked as prayed (self-reported).

+ )} + {data.commitments.length ? ( + + ) : ( +
+

You haven't booked a prayer slot yet.

+ Find an open hour +
+ )} + My testimonies + + )} +
+ ); +} diff --git a/apps/app/frontend/src/app/page.tsx b/apps/app/frontend/src/app/page.tsx index bf4b9ac..d35ab5c 100644 --- a/apps/app/frontend/src/app/page.tsx +++ b/apps/app/frontend/src/app/page.tsx @@ -2,7 +2,10 @@ import type { Metadata } from "next"; import { AppShell } from "@/components/AppShell"; import { ComingSoon } from "@/components/ComingSoon"; 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 { loadCampaign, loadDay, loadMyPrayer } from "@/lib/prayerServer"; export async function generateMetadata(): Promise { const app = await loadApp(); @@ -18,6 +21,8 @@ export async function generateMetadata(): Promise { export default async function Home() { const [app, me] = await Promise.all([loadApp(), loadMe()]); 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"; return ( @@ -25,7 +30,8 @@ export default async function Home() { {me ? `${greeting(app.timezone)}, ${firstName(me.member.name)}` : `Welcome to ${name}`} - {on.has("house-of-prayer") && Today's prayer clock and your next slot will show here.} + {campaign && } + {day && } {on.has("devotionals") && Today's Bible passage and devotional will show here.} {on.has("announcements") && News from {name} will show here.} diff --git a/apps/app/frontend/src/app/prayer/page.tsx b/apps/app/frontend/src/app/prayer/page.tsx index 181ac2a..b8e40bd 100644 --- a/apps/app/frontend/src/app/prayer/page.tsx +++ b/apps/app/frontend/src/app/prayer/page.tsx @@ -1,18 +1,64 @@ import type { Metadata } from "next"; +import Link from "next/link"; 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 { 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). 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. */ -export default async function Prayer() { +const DATE = /^\d{4}-\d{2}-\d{2}$/; + +/** + * 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"); + 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 ( -

House of Prayer

- The 24-hour prayer clock, with the hours still open, will show here. +
+

House of Prayer

+ {me && My prayer} +
+ {campaign && } + {day ? ( + + ) : ( +

The prayer wall can't be loaded right now. Please try again in a minute.

+ )} +
+
+

What God has done

+ {me ? ( + Share yours + ) : null} +
+ {testimonies.length ? ( +
    + {testimonies.map((t) => ( +
  • +

    {t.text}

    +

    {t.by} · {dayName(t.createdAt.slice(0, 10), { day: "numeric", month: "long" })}

    +
  • + ))} +
+ ) : ( +

Answered prayers shared by the church will show here.

+ )} +
); } diff --git a/apps/app/frontend/src/app/prayer/prayed/page.tsx b/apps/app/frontend/src/app/prayer/prayed/page.tsx new file mode 100644 index 0000000..52b5b94 --- /dev/null +++ b/apps/app/frontend/src/app/prayer/prayed/page.tsx @@ -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 ( + +

Did you pray?

+
+

Mark your slot as prayed. It's only counted, never ranked, and only you see your own number.

+ +
+
+ ); +} diff --git a/apps/app/frontend/src/app/prayer/renew/page.tsx b/apps/app/frontend/src/app/prayer/renew/page.tsx new file mode 100644 index 0000000..75d1287 --- /dev/null +++ b/apps/app/frontend/src/app/prayer/renew/page.tsx @@ -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 ( + +

Renew your prayer slot

+
+

Your recurring prayer slot is coming to an end. Renew it to keep praying at the same time for another year.

+ +
+
+ ); +} diff --git a/apps/app/frontend/src/app/prayer/testimony/page.tsx b/apps/app/frontend/src/app/prayer/testimony/page.tsx new file mode 100644 index 0000000..a553a7a --- /dev/null +++ b/apps/app/frontend/src/app/prayer/testimony/page.tsx @@ -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 ( + +

Share a testimony

+
+

Sign in to share what God has done.

+ Sign in +
+
+ ); + } + const [mine, campaign] = await Promise.all([backendGet<{ testimonies: MyTestimony[] }>("/api/v1/me/prayer/testimonies"), loadCampaign()]); + return ( + +

Share a testimony

+ +
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/BookingSheet.tsx b/apps/app/frontend/src/components/prayer/BookingSheet.tsx new file mode 100644 index 0000000..c8175a5 --- /dev/null +++ b/apps/app/frontend/src/components/prayer/BookingSheet.tsx @@ -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(null); + const [rules, setRules] = useState(null); + const [recurrence, setRecurrence] = useState("once"); + const [length, setLength] = useState(slotMinutes >= 60 ? 60 : slotMinutes); + const [endDate, setEndDate] = useState(""); + const [reminder, setReminder] = useState("hour1"); + const [channel, setChannel] = useState("email"); + const [note, setNote] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(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) => ( + + ); + + return ( +
+
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" + > +
+
+

Pray {span(minute, length)}

+

{dayName(date)}

+
+ +
+ +
+ How often + {choice("once", "Just this once")} + {choice("weekly", `Every week, on ${weekday}`)} + {choice("daily", "Every day")} +
+ +
+ + {recurrence !== "once" && ( + + )} +
+ +
+ + +
+ + + +

+ You can change or cancel a slot up to {rules?.cancelHours ?? 8} hours before it starts. After that, the prayer coordinator can help. +

+ {error &&

{error}

} + +
+
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/CampaignCard.tsx b/apps/app/frontend/src/components/prayer/CampaignCard.tsx new file mode 100644 index 0000000..439d292 --- /dev/null +++ b/apps/app/frontend/src/components/prayer/CampaignCard.tsx @@ -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 ( +
+ {campaign.imageUrl && !compact && } +
+

{when}

+

{campaign.title}

+ {!compact && campaign.description &&

{campaign.description}

} + {campaign.goal &&

Aim: {campaign.goal}

} +
+ {campaign.started && ( +
+
+
Covered so far
+
{campaign.coveragePercent}%
+
+
+
Hours prayed (self-reported)
+
{campaign.hoursPrayed}
+
+
+ )} +
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/ClockSvg.tsx b/apps/app/frontend/src/components/prayer/ClockSvg.tsx new file mode 100644 index 0000000..ed7704f --- /dev/null +++ b/apps/app/frontend/src/components/prayer/ClockSvg.tsx @@ -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 ( + + {/* The night half, darker behind the ring. */} + + + + {segments.map((minute) => { + const s = byMinute.get(minute); + // A slot the clocks jumped over (daylight saving) isn't on this day. + if (!s) return ; + const strength = s.covered ? 0.4 + 0.6 * Math.min(1, s.count / Math.max(1, target)) : 0; + const isSelected = selected === minute; + return ( + 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 ( + + {String(m / 60).padStart(2, "0")} + + ); + })} + {nowMinute !== null && (() => { + const [x, y] = point(nowMinute, OUTER + 4); + const [x0, y0] = point(nowMinute, INNER - 30); + return ( + + ); + })()} + + {centre.big} + + + {centre.small} + + + ); +} + +/** "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`; diff --git a/apps/app/frontend/src/components/prayer/MyPrayerList.tsx b/apps/app/frontend/src/components/prayer/MyPrayerList.tsx new file mode 100644 index 0000000..a3e06d1 --- /dev/null +++ b/apps/app/frontend/src/components/prayer/MyPrayerList.tsx @@ -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(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 ( +
+
+ {message &&

{message.text}

} +
+ {data.commitments.map((c) => ( +
+
+

{span(c.startMinute, c.durationMinutes)}

+

+ {repeats(c)}{c.recurrence !== "once" && ` until ${dayName(c.endDate, { day: "numeric", month: "long", year: "numeric" })}`} +

+ {c.note &&

{c.note}

} +
+ + {c.toMark.length > 0 && ( +
+

Did you pray?

+
+ {c.toMark.slice(0, 1).map((d) => ( + + ))} +
+
+ )} + + {c.active && c.upcoming.length > 0 && ( +
+

Next

+
    + {c.upcoming.slice(0, 3).map((o) => ( +
  • + {relativeDay(o.date, today)} + {o.locked ? ( + + Within {data.rules.cancelHours} hours + + ) : c.recurrence === "once" ? null : o.skipped ? ( + + ) : ( + + )} +
  • + ))} +
+ {c.upcoming.slice(0, 3).some((o) => o.locked) &&

To change a slot less than {data.rules.cancelHours} hours away, contact {contact}.

} +
+ )} + + {c.active && ( +
+ Reminder and changes +
+
+ + +
+ {c.recurrence !== "once" && ( +
{ + 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."); + }} + > + + +
+ )} + +
+
+ )} + + {c.canRenew && ( +
+

Ends {c.daysLeft <= 0 ? "today" : `in ${c.daysLeft} days`}.

+ +
+ )} +
+ ))} +
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/PrayerClock.tsx b/apps/app/frontend/src/components/prayer/PrayerClock.tsx new file mode 100644 index 0000000..693fe20 --- /dev/null +++ b/apps/app/frontend/src/components/prayer/PrayerClock.tsx @@ -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(openSlot); + // Back from signing in, the slot's sheet opens, unless that slot has started meanwhile. + const [booking, setBooking] = useState(() => { + 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 | null = null; + let timer: ReturnType | 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 ( +
+
+ +
+

{relativeDay(day.date, day.today)}

+

{dayName(day.date)}

+
+ +
+ + + +
+ Covered + Open + Yours +
+ +
+ {slot ? ( +
+
+

{span(slot.minute, day.slotMinutes)}

+

+ {slot.mine ? "You're praying" : slot.covered ? `${countLine(slot.count)} praying` : "Nobody yet"} +

+
+ {past(slot) ? ( + Already started + ) : slot.mine ? ( + My prayer + ) : ( + + )} +
+ ) : ( +

Tap an hour to see it, or pick an open one below.

+ )} +
+ +
+

{open.length ? `Still open ${relativeDay(day.date, day.today).toLowerCase()}` : isToday ? "Every hour left today is covered" : "Every hour is covered"}

+ {open.length > 0 && ( +
    + {open.map((s) => ( +
  • + +
  • + ))} +
+ )} +
+

{live === "live" ? "Updates live as people book." : "Updating every 30 seconds."} Only counts are shown, never names.

+ + {booking !== null && ( + setBooking(null)} + onBooked={() => { + setBooking(null); + void load(day.date); + router.refresh(); + }} + /> + )} +
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/PrayerHomeCard.tsx b/apps/app/frontend/src/components/prayer/PrayerHomeCard.tsx new file mode 100644 index 0000000..9128c0d --- /dev/null +++ b/apps/app/frontend/src/components/prayer/PrayerHomeCard.tsx @@ -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 ( +
+
+ + + +
+

House of Prayer

+

{coveredLine(day.covered, day.total, day.slotMinutes)} today.

+ {next ? ( +

Your next slot: {relativeDay(next.date, day.today)}, {span(next.minute, next.length)}

+ ) : null} + {nextGap ? ( + + Next gap: {hhmm(nextGap.minute)}. Cover it + + ) : ( + Every hour left today is covered + )} +
+
+
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/TestimonyForm.tsx b/apps/app/frontend/src/components/prayer/TestimonyForm.tsx new file mode 100644 index 0000000..e2f477a --- /dev/null +++ b/apps/app/frontend/src/components/prayer/TestimonyForm.tsx @@ -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 ( +
+
+