From fc0a4ad6a0c1dd136bbea307b7575dd5f16245c6 Mon Sep 17 00:00:00 2001 From: Joshua Oosthuizen Date: Tue, 1 Dec 2026 14:29:14 +0200 Subject: [PATCH] =?UTF-8?q?app:=20email=20and=20WhatsApp's=20screens,=20ch?= =?UTF-8?q?angelog=20and=20README=20(APP-1.0-PLAN=20=C2=A78)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- apps/app/CHANGELOG.md | 39 +++++- apps/app/README.md | 9 +- .../frontend/src/app/admin/messaging/page.tsx | 20 +++ apps/app/frontend/src/app/admin/page.tsx | 5 + .../src/app/me/notifications/page.tsx | 33 +++++ apps/app/frontend/src/app/me/page.tsx | 5 +- apps/app/frontend/src/app/page.tsx | 8 +- .../src/components/admin/AdminMessaging.tsx | 120 ++++++++++++++++++ .../notifications/DevotionalOffer.tsx | 47 +++++++ .../notifications/NotificationSettings.tsx | 92 ++++++++++++++ .../src/components/prayer/BookingSheet.tsx | 5 + apps/app/frontend/src/lib/notifications.ts | 38 ++++++ 12 files changed, 411 insertions(+), 10 deletions(-) create mode 100644 apps/app/frontend/src/app/admin/messaging/page.tsx create mode 100644 apps/app/frontend/src/app/me/notifications/page.tsx create mode 100644 apps/app/frontend/src/components/admin/AdminMessaging.tsx create mode 100644 apps/app/frontend/src/components/notifications/DevotionalOffer.tsx create mode 100644 apps/app/frontend/src/components/notifications/NotificationSettings.tsx create mode 100644 apps/app/frontend/src/lib/notifications.ts diff --git a/apps/app/CHANGELOG.md b/apps/app/CHANGELOG.md index 4f023e6..b6b4030 100644 --- a/apps/app/CHANGELOG.md +++ b/apps/app/CHANGELOG.md @@ -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`). diff --git a/apps/app/README.md b/apps/app/README.md index f811ca0..a1396ec 100644 --- a/apps/app/README.md +++ b/apps/app/README.md @@ -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 diff --git a/apps/app/frontend/src/app/admin/messaging/page.tsx b/apps/app/frontend/src/app/admin/messaging/page.tsx new file mode 100644 index 0000000..99bba5c --- /dev/null +++ b/apps/app/frontend/src/app/admin/messaging/page.tsx @@ -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 ( +
+
+ ← Dashboard +

Email and WhatsApp

+
+ +
+ ); +} diff --git a/apps/app/frontend/src/app/admin/page.tsx b/apps/app/frontend/src/app/admin/page.tsx index 8ea4783..b35731c 100644 --- a/apps/app/frontend/src/app/admin/page.tsx +++ b/apps/app/frontend/src/app/admin/page.tsx @@ -111,6 +111,11 @@ export default async function Admin() { Prayer requests: approval, escalations, replies, settings› )} + {me.activeRoles.some((r) => r === "owner" || r === "church_admin") && ( + + Email and WhatsApp: what the App sends with, Send a test, messages not sent› + + )} Back to the App ); diff --git a/apps/app/frontend/src/app/me/notifications/page.tsx b/apps/app/frontend/src/app/me/notifications/page.tsx new file mode 100644 index 0000000..d891284 --- /dev/null +++ b/apps/app/frontend/src/app/me/notifications/page.tsx @@ -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 ( + +

What the App sends me

+

Sign in to choose what the App sends you.

Sign in
+
+ ); + } + const data = await backendGet("/api/v1/me/notifications"); + const accounts = app.church?.links.accounts; + return ( + +

What the App sends me

+ {data ? ( + + ) : ( +

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

+ )} +
+ ); +} diff --git a/apps/app/frontend/src/app/me/page.tsx b/apps/app/frontend/src/app/me/page.tsx index 6bc313c..8691703 100644 --- a/apps/app/frontend/src/app/me/page.tsx +++ b/apps/app/frontend/src/app/me/page.tsx @@ -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") && ( My prayer requests› )} + What the App sends me› {roles.length > 0 && (

The App's admin

diff --git a/apps/app/frontend/src/app/page.tsx b/apps/app/frontend/src/app/page.tsx index 4038e07..4ddce83 100644 --- a/apps/app/frontend/src/app/page.tsx +++ b/apps/app/frontend/src/app/page.tsx @@ -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 { const app = await loadApp(); @@ -18,7 +21,8 @@ export async function generateMetadata(): Promise { /** * 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("/api/v1/me/notifications") : null; const name = app.church?.name ?? "your church"; return ( @@ -39,6 +44,7 @@ export default async function Home() { {campaign && } {day && } + {notifications?.offerDevotional && notifications.channels.email.ready && } {devotional && } {announcements.length > 0 && (
diff --git a/apps/app/frontend/src/components/admin/AdminMessaging.tsx b/apps/app/frontend/src/components/admin/AdminMessaging.tsx new file mode 100644 index 0000000..2c396aa --- /dev/null +++ b/apps/app/frontend/src/components/admin/AdminMessaging.tsx @@ -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 = { + "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(null); + const [msg, setMsg] = useState(null); + const [busy, setBusy] = useState(null); + + const load = useCallback(() => { + adminCall("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 ; + const kept = keptWhere(s.keptIn); + return ( +
+ + run("fetch")}>{busy === "fetch" ? "Fetching…" : "Fetch again"}}> +
+
+
Email
+
{s.email.ready ? <>{s.email.from}through {s.email.host} : Not set up}
+ +
+
+
WhatsApp
+
{s.whatsapp.ready ? <>WAWP instance {s.whatsapp.instanceId}the church's WhatsApp number : Not set up}
+ +
+
+

+ These are the church's own settings, shared by all its sites. Change them in {kept.href ? {kept.name} : kept.name}; the App fetches them again by itself. + Last fetched: {when(s.fetchedAt)}. +

+ {s.lastTry?.error &&

The last fetch failed ({when(s.lastTry.triedAt)}): {s.lastTry.error}

} +

A STOP to the church's WhatsApp number stops every WhatsApp from the App to that person, reminders included. It's kept in Accounts for all the church's sites.

+
+ + +
+

Emails (30 days)

{s.outbox.sentLast30d.email30d}

+

WhatsApp (30 days)

{s.outbox.sentLast30d.whatsapp30d}

+

Waiting

{s.outbox.waiting}

+

Not sent (7 days)

{s.outbox.failedLast7d}

+
+ {s.outbox.recentFailures.length > 0 && ( + + + + {s.outbox.recentFailures.map((f, i) => ( + + ))} + +
WhenWhatWhy
{when(f.at)}{KIND_NAMES[f.kind] ?? f.kind}{f.error}
+ )} +
+
+ ); +} diff --git a/apps/app/frontend/src/components/notifications/DevotionalOffer.tsx b/apps/app/frontend/src/components/notifications/DevotionalOffer.tsx new file mode 100644 index 0000000..24c1622 --- /dev/null +++ b/apps/app/frontend/src/components/notifications/DevotionalOffer.tsx @@ -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(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(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 ?

{done}

: null; + return ( +
+

Get today's devotional each morning?

+

The title, the verse and a link to read it, at 06:00.

+
+ {choicesFor(initial, "off", false).map((c) => ( + + ))} + +
+ {error &&

{error}

} +
+ ); +} diff --git a/apps/app/frontend/src/components/notifications/NotificationSettings.tsx b/apps/app/frontend/src/components/notifications/NotificationSettings.tsx new file mode 100644 index 0000000..886bbc0 --- /dev/null +++ b/apps/app/frontend/src/components/notifications/NotificationSettings.tsx @@ -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(null); + const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null); + const timeId = useId(); + + async function save(change: Partial> & { 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 ( +
+ {!wa.ready ? ( +

The church doesn't send WhatsApp messages from the App yet, so everything comes by email.

+ ) : wa.reach === "opted_out" ? ( +

You replied STOP to the church's WhatsApp number, so nothing is sent to you on WhatsApp. {accountUrl && <>To turn it back on, go to your church account.}

+ ) : wa.reach === "no_phone" ? ( +

To get messages on WhatsApp, add and verify your mobile number in {accountUrl ? your church account : "your church account"}.

+ ) : null} + {!n.channels.email.ready &&

The church's email isn't set up yet, so nothing is sent for now. Your choices are kept.

} + + {KINDS.filter((k) => n.modules.includes(k.module)).map((k) => ( +
+ {k.label} +

{k.hint}

+
+ {choicesFor(n, n[k.kind]).map((c) => ( + + ))} +
+ {k.kind === "announcements" && announcementsWithoutConsent && ( +

Announcements only go on the channels you allowed news on in {accountUrl ? your church account : "your church account"}. Turn news on there too.

+ )} + {k.kind === "devotional" && n.devotional !== "off" && ( + + )} +
+ ))} + + {n.modules.includes("house-of-prayer") && ( +

Prayer slot reminders and renewal notices are chosen for each booking, in My prayer{whatsappUsable(n) ? "" : " (by email)"}.

+ )} + {msg &&

{msg.text}

} +
+ ); +} diff --git a/apps/app/frontend/src/components/prayer/BookingSheet.tsx b/apps/app/frontend/src/components/prayer/BookingSheet.tsx index c8175a5..abd2ea3 100644 --- a/apps/app/frontend/src/components/prayer/BookingSheet.tsx +++ b/apps/app/frontend/src/components/prayer/BookingSheet.tsx @@ -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]); diff --git a/apps/app/frontend/src/lib/notifications.ts b/apps/app/frontend/src/lib/notifications.ts new file mode 100644 index 0000000..9a16a7c --- /dev/null +++ b/apps/app/frontend/src/lib/notifications.ts @@ -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 = { 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")}`; +});