app: email and WhatsApp's screens, changelog and README (APP-1.0-PLAN §8)

Me → What the App sends me (email, WhatsApp, both or off per kind, the
devotional's time; WhatsApp only to a verified number that hasn't replied
STOP), today's devotional offered once on Home after the first sign-in, the
booking sheet picking WhatsApp for reminders when it reaches the member, and
Admin → Email and WhatsApp (what it sends from, where it's changed, Fetch
again, Send me a test, messages waiting and not sent).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 14:29:14 +02:00
co-authored by Claude Opus 5.5
parent 8bfd0b767d
commit fc0a4ad6a0
12 changed files with 411 additions and 10 deletions
+34 -5
View File
@@ -2,8 +2,9 @@
## [Unreleased]
Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). Four migrations so far (`20261201000000_init`,
`20261202000000_house_of_prayer`, `20261203000000_prayer_requests`, `20261204000000_content`).
Being built for `app@1.0.0` (docs/APP-1.0-PLAN.md). Five migrations so far (`20261201000000_init`,
`20261202000000_house_of_prayer`, `20261203000000_prayer_requests`, `20261204000000_content`,
`20261205000000_messaging`).
Ships `@crosscode/seo` 1.1.0 (`articleJsonLd`, workspace).
### Added
@@ -54,7 +55,7 @@ Ships `@crosscode/seo` 1.1.0 (`articleJsonLd`, workspace).
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.
end) queue messages in `OutboxMessage`, sent by email and WhatsApp (plan §8, below).
- 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).
@@ -82,8 +83,8 @@ Ships `@crosscode/seo` 1.1.0 (`articleJsonLd`, workspace).
HTML, `react-markdown`), image, an optional button, a campus from the church profile, everyone or
members only, pinned, a publish time and an end. Public ones are pages of their own (canonical,
Article JSON-LD, in the sitemap); members-only ones ask for a sign-in and are noindex. Content
admins write them (`/admin/announcements`). "Also send it" by email or WhatsApp is saved, and
sent once at the publish time with §8. The heartbeat counts the last 30 days.
admins write them (`/admin/announcements`). "Also send it" by email or WhatsApp sends it once, at
the publish time (§8, below). The heartbeat counts the last 30 days.
- **Devotionals** (plan §6, `src/content/devotionals.ts`): Cross Code's from the Hub
(`crosscode-devotionals`, 01:15, and Sync now: the next 2 weeks from today in the church's
timezone, with the licence; exactly those days replaced, earlier ones kept, so a Hub outage
@@ -98,6 +99,34 @@ Ships `@crosscode/seo` 1.1.0 (`articleJsonLd`, workspace).
and read-only copies of Cross Events' and the Website's (`event-feed`, every 15 minutes and on
their `event.changed`) with Register on the Events site and a canonical to the origin. Event
JSON-LD on the App's own events only. Linked products: publish, and show events from each sibling.
- **Email and WhatsApp** (plan §8, `src/messaging/`):
- The church's one set of settings from Accounts (`messaging.get`; the SMTP password and WAWP
token sealed with the link's secret, kept encrypted in AppSetting `messaging_settings`): fetched
when the App links to Accounts, on Accounts' signed `messaging.changed`
(`/api/accounts/v1/messaging-changed`), once a day, and on **Fetch again**. The App never asks
for its own (decision 4); the last copy keeps working while Accounts can't be reached.
- `messages-send` (every minute, `MESSAGES_ENABLED`): the outbox, 100 a run, email (nodemailer)
and WhatsApp (WAWP), laid out as Accounts' and Events' emails with a plain-text version. **STOP
is checked before every WhatsApp** (the member's `whatsapp_opted_out` from Accounts, and anyone
in the App with the same number). What a member asked for (reminders, renewals, notices, the
devotional) goes by email when WhatsApp can't reach them; announcements never do. Tried again
after 2, 4, 8 and 16 minutes, then given up; a reminder never after its slot started, nothing
more than 3 days late; while the church has neither email nor WhatsApp, messages wait. No
prayer request's text in any message.
- `announcement-sends` (every minute): "Also send it" once at the publish time, to members who
turned announcements on, on the channels the admin chose and the member allows (their choice
and their news consent in Accounts, now kept as `Member.newsEmail` / `newsWhatsApp`).
- `devotional-sends` (every 5 minutes): today's devotional at each member's time (06:00 by
default), once a day, with the title, the verse and its translation's notice, and a link.
- Me → **What the App sends me** (`NotificationSettings`): email, WhatsApp, both or off for request
updates (email by default), announcements and the devotional (off), the devotional's time;
WhatsApp only to a verified number that hasn't replied STOP. Home offers the devotional once
after the first sign-in. Booking a slot picks WhatsApp for its reminder when it reaches them.
- Admin → **Email and WhatsApp** (Owner, Church admin): the address and WAWP instance it sends
from (no secrets), where they're changed (Cross Events or Accounts), Fetch again, **Send me a
test** (email or WhatsApp), what's waiting and what wasn't sent in 7 days.
- Counts per day and channel (`MessageCount`) for the heartbeat's `messages.email30d` /
`whatsapp30d`; `user.export` has the notification choices, deleted with the account.
- Home shows today's devotional, the latest announcements (pinned first) and what's on. A sitemap
of the public pages (`/sitemap.xml`, never prayer, members-only items or imported events), named
in robots.txt. `GET /api/v1/app` gives the App's own address (`url`).
+7 -2
View File
@@ -33,7 +33,7 @@ main only when `app@1.0.0` is done (main keeps a placeholder until then). Not re
- **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.
Reminders and renewal notices go by email or WhatsApp (§8).
- **Prayer requests** (§4, `backend/src/requests/`): private to the prayer team by default, or
shared with members after approval; redact, don't share, reply, escalate to Pastoral care; "I
prayed" counts; closing after 30 days, deleted a year later; every view of a sender access-logged.
@@ -42,7 +42,12 @@ main only when `app@1.0.0` is done (main keeps a placeholder until then). Not re
2 weeks) or the church's own with the CSV import, KJV and BSB only, Read in YouVersion; simple
events and the event feed both ways; Article and Event JSON-LD and a sitemap for the public pages.
**Still to come** (plan §8–§15): email and WhatsApp (sending the outbox), the rest of the admin, the export,
- **Email and WhatsApp** (§8, `backend/src/messaging/`): the church's one set of settings from
Accounts (`messaging.get`, refreshed on `messaging.changed`), the outbox sent every minute with STOP
checked before every WhatsApp, announcements and the day's devotional queued for those who asked,
Me → What the App sends me, and the admin's Email and WhatsApp page with Send a test.
**Still to come** (plan §10–§15): the rest of the admin, the export,
backups, the demo church and scenarios, `scripts/products/app.sh`, e2e and Lighthouse.
- `backend/`: `npm run dev`, `npm test` (Node's test runner through tsx), `npm run build`. The
@@ -0,0 +1,20 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AdminMessaging } from "@/components/admin/AdminMessaging";
import { requireAdmin } from "@/lib/admin";
export const metadata: Metadata = { title: "Email and WhatsApp · Admin", robots: { index: false, follow: false } };
/** Settings → Email and WhatsApp (APP-1.0-PLAN §8, §10): Owner and Church admin. */
export default async function AdminMessagingPage() {
const { app } = await requireAdmin([]);
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">Email and WhatsApp</h1>
</div>
<AdminMessaging timezone={app.timezone} />
</main>
);
}
+5
View File
@@ -111,6 +111,11 @@ export default async function Admin() {
Prayer requests: approval, escalations, replies, settings<span aria-hidden>›</span>
</Link>
)}
{me.activeRoles.some((r) => r === "owner" || r === "church_admin") && (
<Link href="/admin/messaging" className="cca-card flex items-center justify-between font-semibold">
Email and WhatsApp: what the App sends with, Send a test, messages not sent<span aria-hidden>›</span>
</Link>
)}
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page>
);
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { NotificationSettings } from "@/components/notifications/NotificationSettings";
import { loadApp, loadMe, signInHref } from "@/lib/load";
import type { Notifications } from "@/lib/notifications";
import { backendGet } from "@/lib/prayerServer";
export const metadata: Metadata = { title: "What the App sends me", robots: { index: false, follow: false } };
/** Me → What the App sends me (APP-1.0-PLAN §8): email, WhatsApp, both or off, per kind. */
export default async function NotificationsPage() {
const [me, app] = await Promise.all([loadMe(), loadApp()]);
if (!me) {
return (
<AppShell footer={false}>
<h1 className="cca-h1">What the App sends me</h1>
<section className="cca-card space-y-3"><p>Sign in to choose what the App sends you.</p><a href={signInHref("/me/notifications")} className="cca-btn">Sign in</a></section>
</AppShell>
);
}
const data = await backendGet<Notifications>("/api/v1/me/notifications");
const accounts = app.church?.links.accounts;
return (
<AppShell footer={false}>
<h1 className="cca-h1">What the App sends me</h1>
{data ? (
<NotificationSettings initial={data} accountUrl={accounts ? `${accounts.replace(/\/+$/, "")}/account` : null} />
) : (
<section className="cca-card"><p className="cca-muted">Your settings can&apos;t be loaded right now. Please try again in a minute.</p></section>
)}
</AppShell>
);
}
+3 -2
View File
@@ -7,8 +7,8 @@ export const metadata: Metadata = { title: "Me", robots: { index: false, follow:
/**
* Me (APP-1.0-PLAN §1): signed out, why and how to sign in; signed in, who they are, the admin for
* someone with a role, and signing out. Their prayer, requests and notification settings come with
* their modules (§3, §4, §8).
* someone with a role, and signing out; their prayer (§3), their requests (§4) and what the App
* sends them (§8).
*/
export default async function Me() {
const [me, app] = await Promise.all([loadMe(), loadApp()]);
@@ -37,6 +37,7 @@ export default async function Me() {
{app.modules.includes("prayer-requests") && (
<Link href="/me/requests" className="cca-card flex min-h-11 items-center justify-between font-semibold">My prayer requests<span aria-hidden>›</span></Link>
)}
<Link href="/me/notifications" className="cca-card flex min-h-11 items-center justify-between font-semibold">What the App sends me<span aria-hidden>›</span></Link>
{roles.length > 0 && (
<section className="cca-card space-y-2">
<h2 className="cca-h2">The App&apos;s admin</h2>
+7 -1
View File
@@ -8,6 +8,9 @@ import { PrayerHomeCard } from "@/components/prayer/PrayerHomeCard";
import { firstName, greeting, loadApp, loadMe } from "@/lib/load";
import { loadCampaign, loadDay, loadMyPrayer } from "@/lib/prayerServer";
import { loadAnnouncements, loadEvents, loadToday } from "@/lib/contentServer";
import { DevotionalOffer } from "@/components/notifications/DevotionalOffer";
import type { Notifications } from "@/lib/notifications";
import { backendGet } from "@/lib/prayerServer";
export async function generateMetadata(): Promise<Metadata> {
const app = await loadApp();
@@ -18,7 +21,8 @@ export async function generateMetadata(): Promise<Metadata> {
/**
* Home (APP-1.0-PLAN §1, mockup "Home"): the greeting, then what's on, in this order: the
* campaign, the member's next slot and today's prayer clock (House of Prayer), today's devotional,
* a pinned announcement. Each module fills its card as it arrives.
* a pinned announcement. Each module fills its card as it arrives. After the first sign-in, the
* offer of today's devotional by email or WhatsApp (§6), until it's answered.
*/
export default async function Home() {
const [app, me] = await Promise.all([loadApp(), loadMe()]);
@@ -30,6 +34,7 @@ export default async function Home() {
on.has("announcements") ? loadAnnouncements(2) : [],
on.has("events") ? loadEvents(3) : [],
]);
const notifications = me && on.has("devotionals") ? await backendGet<Notifications>("/api/v1/me/notifications") : null;
const name = app.church?.name ?? "your church";
return (
<AppShell>
@@ -39,6 +44,7 @@ export default async function Home() {
<InstallCard name={app.shortName} />
{campaign && <CampaignCard campaign={campaign} compact />}
{day && <PrayerHomeCard day={day} mine={mine} />}
{notifications?.offerDevotional && notifications.channels.email.ready && <DevotionalOffer initial={notifications} />}
{devotional && <DevotionalCard d={devotional} />}
{announcements.length > 0 && (
<section className="space-y-3" aria-labelledby="news">
@@ -0,0 +1,120 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { adminCall, Notice, Panel, type Msg } from "./kit";
/** GET /api/v1/admin/messaging (backend/src/messaging/routes.ts): never the secrets. */
type Status = {
email: { ready: boolean; from: string | null; host: string | null };
whatsapp: { ready: boolean; instanceId: string | null };
fetchedAt: string | null;
changedAt: string | null;
lastTry: { triedAt: string; error: string | null } | null;
keptIn: { product: "events" | "accounts"; url: string } | null;
outbox: {
waiting: number;
failedLast7d: number;
recentFailures: { kind: string; at: string; error: string | null }[];
sentLast30d: { email30d: number; whatsapp30d: number };
};
};
const KIND_NAMES: Record<string, string> = {
"prayer-reminder": "Prayer reminder",
"prayer-renewal": "Renewal notice",
"testimony-removed": "Testimony not shared",
"request-new": "New prayer request",
"request-update": "Prayer request update",
"request-escalated": "Escalated request",
announcement: "Announcement",
devotional: "Devotional",
};
/** Where the settings are changed: Cross Events' or Accounts' admin. */
function keptWhere(k: Status["keptIn"]) {
if (!k) return { name: "Accounts", href: null };
return k.product === "events"
? { name: "Cross Events (Admin → Settings)", href: `${k.url.replace(/\/+$/, "")}/dashboard/admin/settings` }
: { name: "Accounts (Admin → Email and WhatsApp)", href: `${k.url.replace(/\/+$/, "")}/admin/messages` };
}
/**
* Settings → Email and WhatsApp (APP-1.0-PLAN §8, decision 4): the App sends with the church's one
* set of settings, kept in Cross Events or Accounts, so this page only shows which address and
* number it sends from, fetches them again, sends a test to the admin, and says what's waiting or
* failed. Changing them is done where they're kept.
*/
export function AdminMessaging({ timezone }: { timezone: string }) {
const [s, setS] = useState<Status | null>(null);
const [msg, setMsg] = useState<Msg>(null);
const [busy, setBusy] = useState<string | null>(null);
const load = useCallback(() => {
adminCall<Status>("GET", "/messaging").then((r) => (r.ok ? setS(r.data) : setMsg({ kind: "error", text: r.error })));
}, []);
useEffect(load, [load]);
const when = (iso: string | null) => (iso ? new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, dateStyle: "medium", timeStyle: "short" }).format(new Date(iso)) : "never");
async function run(what: "fetch" | "email" | "whatsapp") {
setBusy(what);
setMsg(null);
const r = what === "fetch"
? await adminCall<{ email: boolean; whatsapp: boolean }>("POST", "/messaging/fetch", {})
: await adminCall<{ sentTo: string }>("POST", "/messaging/test", { channel: what });
setBusy(null);
if (!r.ok) {
setMsg({ kind: "error", text: r.error });
return;
}
setMsg({ kind: "ok", text: what === "fetch" ? "Fetched from Accounts." : `A test was sent to ${(r.data as { sentTo: string }).sentTo}.` });
load();
}
if (!s) return <Notice msg={msg} />;
const kept = keptWhere(s.keptIn);
return (
<div className="space-y-6">
<Notice msg={msg} />
<Panel title="What the App sends with" aside={<button type="button" className="cca-btn-quiet" disabled={busy !== null} onClick={() => run("fetch")}>{busy === "fetch" ? "Fetching…" : "Fetch again"}</button>}>
<dl className="grid gap-4 sm:grid-cols-2">
<div>
<dt className="text-sm text-gray-600">Email</dt>
<dd className="mt-1">{s.email.ready ? <><span className="font-semibold">{s.email.from}</span><span className="block text-sm text-gray-600">through {s.email.host}</span></> : <span className="text-amber-800">Not set up</span>}</dd>
<button type="button" className="cca-btn mt-3" disabled={!s.email.ready || busy !== null} onClick={() => run("email")}>{busy === "email" ? "Sending…" : "Send me a test email"}</button>
</div>
<div>
<dt className="text-sm text-gray-600">WhatsApp</dt>
<dd className="mt-1">{s.whatsapp.ready ? <><span className="font-semibold">WAWP instance {s.whatsapp.instanceId}</span><span className="block text-sm text-gray-600">the church&apos;s WhatsApp number</span></> : <span className="text-amber-800">Not set up</span>}</dd>
<button type="button" className="cca-btn mt-3" disabled={!s.whatsapp.ready || busy !== null} onClick={() => run("whatsapp")}>{busy === "whatsapp" ? "Sending…" : "Send me a test WhatsApp"}</button>
</div>
</dl>
<p className="mt-4 text-sm text-gray-600">
These are the church&apos;s own settings, shared by all its sites. Change them in {kept.href ? <a href={kept.href} className="font-semibold underline">{kept.name}</a> : kept.name}; the App fetches them again by itself.
Last fetched: {when(s.fetchedAt)}.
</p>
{s.lastTry?.error && <p className="mt-2 rounded-md bg-red-50 p-3 text-sm text-red-800">The last fetch failed ({when(s.lastTry.triedAt)}): {s.lastTry.error}</p>}
<p className="mt-2 text-sm text-gray-600">A STOP to the church&apos;s WhatsApp number stops every WhatsApp from the App to that person, reminders included. It&apos;s kept in Accounts for all the church&apos;s sites.</p>
</Panel>
<Panel title="Messages">
<div className="grid gap-4 sm:grid-cols-4">
<div><p className="text-sm text-gray-600">Emails (30 days)</p><p className="text-2xl font-semibold">{s.outbox.sentLast30d.email30d}</p></div>
<div><p className="text-sm text-gray-600">WhatsApp (30 days)</p><p className="text-2xl font-semibold">{s.outbox.sentLast30d.whatsapp30d}</p></div>
<div><p className="text-sm text-gray-600">Waiting</p><p className="text-2xl font-semibold">{s.outbox.waiting}</p></div>
<div><p className="text-sm text-gray-600">Not sent (7 days)</p><p className={`text-2xl font-semibold ${s.outbox.failedLast7d ? "text-red-700" : ""}`}>{s.outbox.failedLast7d}</p></div>
</div>
{s.outbox.recentFailures.length > 0 && (
<table className="mt-4 w-full text-left text-sm">
<thead><tr className="text-gray-600"><th className="py-1 font-medium">When</th><th className="py-1 font-medium">What</th><th className="py-1 font-medium">Why</th></tr></thead>
<tbody>
{s.outbox.recentFailures.map((f, i) => (
<tr key={i} className="border-t border-gray-100"><td className="py-1 pr-3 whitespace-nowrap">{when(f.at)}</td><td className="py-1 pr-3">{KIND_NAMES[f.kind] ?? f.kind}</td><td className="py-1">{f.error}</td></tr>
))}
</tbody>
</table>
)}
</Panel>
</div>
);
}
@@ -0,0 +1,47 @@
"use client";
import { useState } from "react";
import { errorMessage } from "@/lib/prayer";
import { CHOICE_NAMES, choicesFor, type Choice, type Notifications } from "@/lib/notifications";
/**
* Today's devotional, offered once after the first sign-in (APP-1.0-PLAN §6, §8): email, WhatsApp
* or both at 06:00 (the time can be changed in Me), or "Not now". Either answer hides it.
*/
export function DevotionalOffer({ initial }: { initial: Notifications }) {
const [done, setDone] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function answer(choice: Choice | null) {
setBusy(true);
setError(null);
try {
const res = await fetch("/api/v1/me/notifications/devotional-offer", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ choice }) });
if (!res.ok) {
setError(await errorMessage(res));
return;
}
setDone(choice ? `Done: today's devotional comes by ${CHOICE_NAMES[choice].toLowerCase()} at 06:00. Change it in Me.` : "");
} catch {
setError("The App can't be reached. Check your connection and try again.");
} finally {
setBusy(false);
}
}
if (done !== null) return done ? <p role="status" className="cca-card text-sm">{done}</p> : null;
return (
<section className="cca-card space-y-3" aria-labelledby="devotional-offer">
<h2 id="devotional-offer" className="cca-h2">Get today&apos;s devotional each morning?</h2>
<p className="cca-muted">The title, the verse and a link to read it, at 06:00.</p>
<div className="flex flex-wrap gap-2">
{choicesFor(initial, "off", false).map((c) => (
<button key={c} type="button" className="cca-btn" disabled={busy} onClick={() => answer(c)}>{CHOICE_NAMES[c]}</button>
))}
<button type="button" className="cca-btn-quiet" disabled={busy} onClick={() => answer(null)}>Not now</button>
</div>
{error && <p role="alert" className="text-sm text-red-800">{error}</p>}
</section>
);
}
@@ -0,0 +1,92 @@
"use client";
import { useId, useState } from "react";
import { errorMessage } from "@/lib/prayer";
import { CHOICE_NAMES, choicesFor, DEVOTIONAL_TIMES, whatsappUsable, type Choice, type Notifications } from "@/lib/notifications";
type Kind = "requestUpdates" | "announcements" | "devotional";
const KINDS: { kind: Kind; module: string; label: string; hint: string }[] = [
{ kind: "requestUpdates", module: "prayer-requests", label: "My prayer requests", hint: "When one is approved, someone prays for it or the prayer team replies. Never what it says." },
{ kind: "announcements", module: "announcements", label: "Announcements", hint: "News the church chooses to send." },
{ kind: "devotional", module: "devotionals", label: "Today's devotional", hint: "The title, the verse and a link to read it, each morning." },
];
/**
* Me → What the App sends me (APP-1.0-PLAN §8): email, WhatsApp, both or off for each kind. Prayer
* reminders are chosen per booking (My prayer). WhatsApp only to a verified number that hasn't
* replied STOP; announcements also need the news consent in the church account.
*/
export function NotificationSettings({ initial, accountUrl }: { initial: Notifications; accountUrl: string | null }) {
const [n, setN] = useState(initial);
const [busy, setBusy] = useState<Kind | "time" | null>(null);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const timeId = useId();
async function save(change: Partial<Record<Kind, Choice>> & { devotionalTime?: string }, what: Kind | "time") {
setBusy(what);
setMsg(null);
try {
const res = await fetch("/api/v1/me/notifications", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(change) });
if (!res.ok) {
setMsg({ ok: false, text: await errorMessage(res) });
return;
}
setN((await res.json()) as Notifications);
setMsg({ ok: true, text: "Saved." });
} catch {
setMsg({ ok: false, text: "The App can't be reached. Check your connection and try again." });
} finally {
setBusy(null);
}
}
const wa = n.channels.whatsapp;
const announcementsWithoutConsent = n.announcements !== "off"
&& !((n.announcements === "email" || n.announcements === "both") && n.news.email)
&& !((n.announcements === "whatsapp" || n.announcements === "both") && n.news.whatsapp);
return (
<div className="space-y-4">
{!wa.ready ? (
<p className="cca-muted">The church doesn&apos;t send WhatsApp messages from the App yet, so everything comes by email.</p>
) : wa.reach === "opted_out" ? (
<p className="cca-card text-sm">You replied STOP to the church&apos;s WhatsApp number, so nothing is sent to you on WhatsApp. {accountUrl && <>To turn it back on, go to <a href={accountUrl} className="font-semibold text-brand-text underline">your church account</a>.</>}</p>
) : wa.reach === "no_phone" ? (
<p className="cca-muted">To get messages on WhatsApp, add and verify your mobile number in {accountUrl ? <a href={accountUrl} className="font-semibold text-brand-text underline">your church account</a> : "your church account"}.</p>
) : null}
{!n.channels.email.ready && <p className="cca-muted">The church&apos;s email isn&apos;t set up yet, so nothing is sent for now. Your choices are kept.</p>}
{KINDS.filter((k) => n.modules.includes(k.module)).map((k) => (
<fieldset key={k.kind} className="cca-card space-y-2">
<legend className="float-left w-full font-semibold">{k.label}</legend>
<p className="cca-muted">{k.hint}</p>
<div className="flex flex-wrap gap-2">
{choicesFor(n, n[k.kind]).map((c) => (
<label key={c} className={`inline-flex min-h-11 cursor-pointer items-center gap-2 rounded-cc border px-3 text-sm ${n[k.kind] === c ? "border-brand bg-brand-tint font-semibold" : "border-gray-300"}`}>
<input type="radio" name={k.kind} value={c} checked={n[k.kind] === c} disabled={busy !== null} onChange={() => save({ [k.kind]: c }, k.kind)} className="accent-[rgb(var(--brand))]" />
{CHOICE_NAMES[c]}
</label>
))}
</div>
{k.kind === "announcements" && announcementsWithoutConsent && (
<p className="text-sm text-amber-800">Announcements only go on the channels you allowed news on in {accountUrl ? <a href={accountUrl} className="font-semibold underline">your church account</a> : "your church account"}. Turn news on there too.</p>
)}
{k.kind === "devotional" && n.devotional !== "off" && (
<label htmlFor={timeId} className="block text-sm font-medium">
At
<select id={timeId} value={n.devotionalTime} disabled={busy !== null} onChange={(e) => save({ devotionalTime: e.target.value }, "time")} className="ml-2 min-h-11 rounded-cc border border-gray-300 px-2">
{DEVOTIONAL_TIMES.map((t) => <option key={t} value={t}>{t}</option>)}
</select>
</label>
)}
</fieldset>
))}
{n.modules.includes("house-of-prayer") && (
<p className="cca-muted">Prayer slot reminders and renewal notices are chosen for each booking, in <a href="/me/prayer" className="font-semibold text-brand-text underline">My prayer</a>{whatsappUsable(n) ? "" : " (by email)"}.</p>
)}
{msg && <p role={msg.ok ? "status" : "alert"} className={`text-sm ${msg.ok ? "text-green-800" : "text-red-800"}`}>{msg.text}</p>}
</div>
);
}
@@ -2,6 +2,7 @@
import { useEffect, useId, useRef, useState } from "react";
import { X } from "lucide-react";
import { whatsappUsable, type Notifications } from "@/lib/notifications";
import { CHANNEL_NAMES, dayName, duration, errorMessage, REMINDER_NAMES, span, type Channel, type MyPrayer, type Recurrence, type Reminder } from "@/lib/prayer";
/**
@@ -27,6 +28,10 @@ export function BookingSheet({ date, minute, slotMinutes, onClose, onBooked }: {
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(() => {});
// Reminders by WhatsApp when it reaches them, else email (§8).
fetch("/api/v1/me/notifications", { cache: "no-store" }).then(async (r) => {
if (r.ok && whatsappUsable((await r.json()) as Notifications)) setChannel((c) => (c === "email" ? "whatsapp" : c));
}).catch(() => {});
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
@@ -0,0 +1,38 @@
/**
* What the App sends a member (APP-1.0-PLAN §8; backend/src/messaging/preferences.ts), for server
* and client components alike.
*/
export type Choice = "off" | "email" | "whatsapp" | "both";
/** GET /api/v1/me/notifications */
export type Notifications = {
requestUpdates: Choice;
announcements: Choice;
devotional: Choice;
devotionalTime: string;
offerDevotional: boolean;
channels: {
email: { ready: boolean };
whatsapp: { ready: boolean; reach: "ok" | "no_phone" | "opted_out" };
};
news: { email: boolean; whatsapp: boolean };
modules: string[];
};
export const CHOICE_NAMES: Record<Choice, string> = { off: "Off", email: "Email", whatsapp: "WhatsApp", both: "Email and WhatsApp" };
/** Whether WhatsApp can be chosen: the church has it, and the member has a verified number that hasn't replied STOP. */
export const whatsappUsable = (n: Notifications) => n.channels.whatsapp.ready && n.channels.whatsapp.reach === "ok";
/** The choices to offer: WhatsApp only when it can reach them (a saved WhatsApp choice stays listed). */
export function choicesFor(n: Notifications, current: Choice, withOff = true): Choice[] {
const all: Choice[] = withOff ? ["off", "email", "whatsapp", "both"] : ["email", "whatsapp", "both"];
return whatsappUsable(n) ? all : all.filter((c) => c === "off" || c === "email" || c === current);
}
/** Quarter hours from 04:00 to 22:00, for the devotional's time. */
export const DEVOTIONAL_TIMES = Array.from({ length: (22 - 4) * 4 + 1 }, (_, i) => {
const m = 4 * 60 + i * 15;
return `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`;
});