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
@@ -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")}`;
});