app: the Church App's foundation; docs for Hub 2.26.1 and two years of devotionals

apps/app (not released; app@1.0.0 is built in slices, APP-1.0-PLAN §15):
- backend (Express, Prisma, pg-boss, as the Website): the Hub client
  (CCP-, product app, the active-member band in the heartbeat), links
  and church.changed, sign-in through Accounts (everyone a Member; 8 days
  renewed up to 90; every role only with 2FA; the first Owner from
  HUB_ADMIN_EMAIL), Accounts' user.updated/export/deleted, active members
  once a day, modules on and off, GET /api/v1/app. Migration init.
- frontend (Next.js 16): header, tab bar, footer, manifest and icons from
  the church profile, service worker, Add to home screen, Me, the admin's
  first dashboard.
- env.template.json, PM2 template, README, CHANGELOG, WHATS-NEW; 27 tests.

Docs: the Hub runs 2.26.1 with two years of Cross Code's devotionals; an
App gets 2 weeks, today included. HANDOVER lists the App's slices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 00:20:07 +02:00
co-authored by Claude Opus 5.5
parent 74dee881e4
commit bb36e06fa4
85 changed files with 4479 additions and 53 deletions
+4
View File
@@ -0,0 +1,4 @@
node_modules/
.next/
next-env.d.ts
.env*
+9
View File
@@ -0,0 +1,9 @@
<!-- BEGIN:nextjs-agent-rules -->
## This is NOT the Next.js you know
This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.
This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.
<!-- END:nextjs-agent-rules -->
+16
View File
@@ -0,0 +1,16 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
// Next.js 16's own flat configs, as the Website. Run with `npm run lint`.
export default defineConfig([
...nextVitals,
...nextTs,
{
rules: {
// The church's logo comes from its profile (another address): no Next image server.
"@next/next/no-img-element": "off",
},
},
globalIgnores([".next/**", "out/**", "next-env.d.ts", "public/sw.js"]),
]);
+31
View File
@@ -0,0 +1,31 @@
import type { NextConfig } from "next";
// Everything under /api is the backend (docs/APP-1.0-PLAN.md §1). On a server nginx sends it
// there; in development (and when Next is reached directly) this rewrite does.
const api = (process.env.APP_API_URL || "http://127.0.0.1:5400").replace(/\/+$/, "");
const nextConfig: NextConfig = {
poweredByHeader: false,
transpilePackages: ["@crosscode/ui"],
async rewrites() {
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
},
async headers() {
// Public content is indexed (ROADMAP-v3 §11); the member's own pages, the admin and every
// prayer page never are (APP-1.0-PLAN §4, §11).
const common = [
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
{ key: "X-Content-Type-Options", value: "nosniff" },
];
const noindex = { key: "X-Robots-Tag", value: "noindex, nofollow" };
const never = ["/admin", "/admin/:path*", "/me", "/me/:path*", "/prayer", "/prayer/:path*", "/auth/:path*", "/offline"];
return [
{ source: "/:path*", headers: common },
...never.map((source) => ({ source, headers: [noindex] })),
// The service worker is checked for updates on every visit (§2).
{ source: "/sw.js", headers: [{ key: "Cache-Control", value: "no-cache" }, { key: "Service-Worker-Allowed", value: "/" }] },
];
},
};
export default nextConfig;
+34
View File
@@ -0,0 +1,34 @@
{
"name": "@crosscode/app-frontend",
"version": "0.1.0",
"private": true,
"description": "Church App: the church-branded web app (PWA) for members, and its admin",
"scripts": {
"dev": "next dev -p 3400",
"build": "next build",
"start": "next start",
"lint": "eslint src",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@crosscode/contracts": "*",
"@crosscode/seo": "*",
"@crosscode/ui": "*",
"lucide-react": "^0.536.0",
"next": "^16.4.6",
"react": "^19.3.1",
"react-dom": "^19.3.1"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@types/node": "^20",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"autoprefixer": "^10.4.21",
"eslint": "^10.13.0",
"eslint-config-next": "^16.4.6",
"postcss": "^8.5.6",
"tailwindcss": "3.4",
"typescript": "^5"
}
}
+1
View File
@@ -0,0 +1 @@
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
+75
View File
@@ -0,0 +1,75 @@
/*
* The Church App's service worker (APP-1.0-PLAN §2, P2). No push and no notification permission
* (decision 13): it only keeps the App usable offline.
*
* - Next's built files and the icons: from the cache, refreshed in the background.
* - Pages: from the network; a copy is kept for offline. Offline, the last copy of that page shows
* (the page says "You're offline"), else the offline page.
* - A page rendered for a signed-in member (the proxy marks it `x-cca-signed-in: 1`) is kept apart,
* and that cache is emptied as soon as a page comes back signed out or the member signs out, so
* nothing personal stays on the phone for someone signed out.
* - The API, the admin and signing in are never cached.
*/
const VERSION = "cca-v1";
const SHELL = `${VERSION}-shell`;
const PAGES = `${VERSION}-pages`;
const PERSONAL = `${VERSION}-personal`;
const OFFLINE = "/offline";
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(SHELL).then((c) => c.addAll([OFFLINE, "/manifest.webmanifest"])).then(() => self.skipWaiting()));
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys()
.then((keys) => Promise.all(keys.filter((k) => !k.startsWith(`${VERSION}-`)).map((k) => caches.delete(k))))
.then(() => self.clients.claim()),
);
});
const neverCached = (path) => path.startsWith("/api/") || path.startsWith("/admin") || path.startsWith("/auth/");
async function fromCacheThenRefresh(request) {
const cache = await caches.open(SHELL);
const hit = await cache.match(request);
const refresh = fetch(request).then((res) => {
if (res.ok) cache.put(request, res.clone());
return res;
});
return hit ?? refresh;
}
async function page(request) {
const url = new URL(request.url);
try {
const res = await fetch(request);
const signedIn = res.headers.get("x-cca-signed-in") === "1";
if (!signedIn) await caches.delete(PERSONAL);
if (res.ok && !neverCached(url.pathname)) {
const cache = await caches.open(signedIn ? PERSONAL : PAGES);
await cache.put(url.pathname, res.clone());
}
return res;
} catch {
const personal = await caches.open(PERSONAL).then((c) => c.match(url.pathname));
const saved = personal ?? (await caches.open(PAGES).then((c) => c.match(url.pathname)));
return saved ?? (await caches.open(SHELL).then((c) => c.match(OFFLINE))) ?? Response.error();
}
}
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") {
// Signing out: forget the member's pages at once.
if (new URL(request.url).pathname === "/api/auth/signout") event.waitUntil(caches.delete(PERSONAL));
return;
}
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (url.pathname.startsWith("/_next/static/") || url.pathname.startsWith("/app-icon/")) {
event.respondWith(fromCacheThenRefresh(request));
return;
}
if (request.mode === "navigate" && !neverCached(url.pathname)) event.respondWith(page(request));
});
+102
View File
@@ -0,0 +1,102 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import Link from "next/link";
import { api, loadMe, ROLE_NAMES, SESSION_COOKIE, signInHref } from "@/lib/load";
export const metadata: Metadata = { title: "Admin", robots: { index: false, follow: false } };
type Overview = {
activeMembers90d: { count: number; band: string };
modules: string[];
hub: { connected: boolean; state: string; lastHeartbeatAt: string | null };
accounts: { url: string; connectedAt: string } | null;
};
const MODULE_NAMES: Record<string, string> = {
"house-of-prayer": "House of Prayer",
"prayer-requests": "Prayer requests",
announcements: "Announcements",
devotionals: "Devotionals",
events: "Events",
};
async function loadOverview(): Promise<Overview | null> {
const session = (await cookies()).get(SESSION_COOKIE)?.value;
if (!session) return null;
try {
const res = await fetch(`${api}/api/v1/admin/overview`, { headers: { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(session)}` }, cache: "no-store" });
if (res.ok) return (await res.json()) as Overview;
} catch {
// The backend is starting or down.
}
return null;
}
function Page({ children }: { children: React.ReactNode }) {
return <main className="mx-auto max-w-4xl space-y-6 px-4 py-10">{children}</main>;
}
/**
* The admin's dashboard (APP-1.0-PLAN §10; the Website's and Events' layout, decision 9). For now
* the foundation: who's using the App, the modules on, and the links to the Hub and Accounts. The
* side menu, setup checklist and each module's pages come with the modules.
*/
export default async function Admin() {
const me = await loadMe();
if (!me) {
return (
<Page>
<h1 className="text-2xl font-semibold">The App&apos;s admin</h1>
<a href={signInHref("/admin", true)} className="cca-btn">Sign in</a>
</Page>
);
}
if (!me.member.roles.length) {
return (
<Page>
<h1 className="text-2xl font-semibold">No access to the admin</h1>
<p className="text-gray-600">Your account doesn&apos;t have a role in the App. Ask the App&apos;s Owner or a Church admin if you need one.</p>
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page>
);
}
if (!me.mfa) {
return (
<Page>
<h1 className="text-2xl font-semibold">Two-step sign-in needed</h1>
<p className="text-gray-600">Every role in the App needs a sign-in with your second step. Turn on two-step sign-in in your church account if it isn&apos;t yet, then sign in again.</p>
<a href={signInHref("/admin", true)} className="cca-btn">Sign in with two-step</a>
</Page>
);
}
const o = await loadOverview();
return (
<Page>
<div>
<h1 className="text-2xl font-semibold">Dashboard</h1>
<p className="text-sm text-gray-600">{me.member.name} · {me.member.roles.map((r) => ROLE_NAMES[r]).join(", ")}</p>
</div>
{!o ? (
<p className="text-gray-600">The dashboard can&apos;t be loaded right now. Please try again in a minute.</p>
) : (
<div className="grid gap-4 sm:grid-cols-3">
<section className="cca-card">
<h2 className="text-sm text-gray-600">Active members (90 days)</h2>
<p className="mt-1 text-3xl font-semibold">{o.activeMembers90d.count}</p>
<p className="text-sm text-gray-600">Band {o.activeMembers90d.band}</p>
</section>
<section className="cca-card">
<h2 className="text-sm text-gray-600">Modules on</h2>
<ul className="mt-1 text-sm">{o.modules.map((m) => <li key={m}>{MODULE_NAMES[m] ?? m}</li>)}</ul>
</section>
<section className="cca-card">
<h2 className="text-sm text-gray-600">Connections</h2>
<p className="mt-1 text-sm">Cross Code Hub: {o.hub.connected ? `connected (${o.hub.state})` : "not connected"}</p>
<p className="text-sm">Accounts: {o.accounts ? "linked" : "not linked yet"}</p>
</section>
</div>
)}
<Link href="/" className="cca-btn-quiet">Back to the App</Link>
</Page>
);
}
@@ -0,0 +1,32 @@
import { ImageResponse } from "next/og";
import { loadApp } from "@/lib/load";
import { churchIconUrl, ICON_SIZES, initials, rgb, type IconKind } from "@/lib/icon";
/**
* The App's icon as a PNG (APP-1.0-PLAN §2): the church's icon from its profile, on its primary
* colour, else its initials on its primary colour. `maskable` keeps everything inside the middle
* 80% (Android crops the rest); `apple` is the iPhone's home-screen icon. The manifest and layout
* link here with a version, so a new icon shows at once.
*/
export async function GET(_request: Request, { params }: { params: Promise<{ kind: string }> }) {
const { kind } = await params;
if (!(kind in ICON_SIZES)) return new Response("Not found", { status: 404 });
const size = ICON_SIZES[kind as IconKind];
const app = await loadApp();
const icon = churchIconUrl(app);
const maskable = kind === "maskable";
const inner = Math.round(size * (maskable ? 0.62 : icon ? 0.86 : 1));
const label = initials(app.church?.shortName || app.church?.name || "");
return new ImageResponse(
(
<div style={{ width: "100%", height: "100%", display: "flex", alignItems: "center", justifyContent: "center", background: rgb(app.palette.brand), color: rgb(app.palette.onBrand), borderRadius: kind === "favicon" ? size * 0.22 : 0 }}>
{icon ? (
<img src={icon} alt="" width={inner} height={inner} style={{ borderRadius: maskable ? 0 : size * 0.12 }} />
) : (
<div style={{ display: "flex", fontSize: Math.round(inner * (label.length > 1 ? 0.42 : 0.56)), fontWeight: 700, letterSpacing: label.length > 1 ? -size * 0.01 : 0 }}>{label}</div>
)}
</div>
),
{ width: size, height: size, headers: { "Cache-Control": "public, max-age=86400" } },
);
}
@@ -0,0 +1,40 @@
import type { Metadata } from "next";
import Link from "next/link";
import { signInHref } from "@/lib/load";
export const metadata: Metadata = { title: "Signing in", robots: { index: false, follow: false } };
/** What went wrong with a sign-in (the backend's auth/routes.ts sends people here with a code). */
const PROBLEMS: Record<string, { title: string; text: string }> = {
TWO_FACTOR_NEEDED: {
title: "Two-step sign-in needed",
text: "Your role in the App needs a sign-in with a second step. Turn on two-step sign-in in your church account, then try again.",
},
ACCOUNTS_NOT_LINKED: {
title: "The App isn't linked to your church's sign-in yet",
text: "It links by itself shortly after it's installed. Please try again in a minute. If this keeps happening, contact your church.",
},
ACCOUNTS_UNAVAILABLE: {
title: "Signing in isn't available right now",
text: "The App can't reach your church's sign-in at the moment. Please try again in a few minutes.",
},
EXPIRED: { title: "The sign-in took too long", text: "Please try again." },
SIGNIN_FAILED: { title: "That didn't work", text: "Something went wrong while signing you in. Please try again." },
};
export default async function Problem({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
const q = await searchParams;
const code = typeof q.code === "string" ? q.code : "";
const returnTo = typeof q.returnTo === "string" && q.returnTo.startsWith("/") && !q.returnTo.startsWith("//") ? q.returnTo : "/";
const p = PROBLEMS[code] ?? PROBLEMS.SIGNIN_FAILED!;
return (
<main className="mx-auto max-w-xl space-y-4 px-4 py-16">
<h1 className="cca-h1">{p.title}</h1>
<p className="text-gray-600">{p.text}</p>
<div className="flex gap-3">
<a href={signInHref(returnTo, code === "TWO_FACTOR_NEEDED")} className="cca-btn">Try again</a>
<Link href="/" className="cca-btn-quiet">Go to the App</Link>
</div>
</main>
);
}
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon";
import { requireModule } from "@/lib/module";
export const metadata: Metadata = { title: "Devotional" };
/** Today's devotional and the archive (APP-1.0-PLAN §6). */
export default async function Devotional() {
await requireModule("devotionals");
return (
<AppShell>
<h1 className="cca-h1">Devotional</h1>
<ComingSoon title="Today">Today&apos;s Bible passage and devotional will show here, with Read in YouVersion.</ComingSoon>
</AppShell>
);
}
+17
View File
@@ -0,0 +1,17 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon";
import { requireModule } from "@/lib/module";
export const metadata: Metadata = { title: "Events" };
/** Events (APP-1.0-PLAN §7): the App's simple events and those from Cross Events and the Website. */
export default async function Events() {
await requireModule("events");
return (
<AppShell>
<h1 className="cca-h1">Events</h1>
<ComingSoon title="What's on">The church&apos;s events will show here.</ComingSoon>
</AppShell>
);
}
+49
View File
@@ -0,0 +1,49 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/*
* The Church App (APP-1.0-PLAN §1, §2): mobile first, a centred column on a desktop, the bottom tab
* bar. The layout sets the church's colours as CSS variables (--brand, --on-brand, --brand-text,
* --brand-tint, --accent, …) and its fonts and corners as attributes (data-cc-fonts /
* data-cc-corners, @crosscode/ui).
*/
:root {
--brand: 31 78 121;
--brand-dark: 25 62 97;
--on-brand: 255 255 255;
--brand-text: 31 78 121;
--brand-tint: 241 244 248;
--accent: 87 113 148;
--on-accent: 255 255 255;
/* The tab bar's height, above the iPhone's home indicator. */
--cca-tabs: calc(4rem + env(safe-area-inset-bottom));
}
body {
@apply bg-gray-50 text-gray-900 antialiased;
font-family: var(--cc-font-body, ui-sans-serif, system-ui, sans-serif);
}
h1, h2, h3 {
font-family: var(--cc-font-heading, inherit);
font-variation-settings: var(--cc-heading-variation, normal);
}
@layer components {
/* The member screens: phone width first, a centred column on anything wider. */
.cca-column { @apply mx-auto w-full max-w-xl px-4; }
.cca-card { @apply rounded-cc border border-gray-200 bg-white p-4 shadow-sm; }
.cca-btn {
@apply inline-flex min-h-11 items-center justify-center gap-2 rounded-cc bg-brand px-4 py-2 text-sm font-semibold text-brand-on hover:bg-brand-dark;
@apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand;
}
.cca-btn-quiet {
@apply inline-flex min-h-11 items-center justify-center gap-2 rounded-cc border border-gray-300 bg-white px-4 py-2 text-sm font-semibold text-gray-800 hover:bg-gray-50;
@apply focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand;
}
.cca-h1 { @apply font-heading text-2xl font-semibold text-gray-900; }
.cca-h2 { @apply font-heading text-lg font-semibold text-gray-900; }
.cca-muted { @apply text-sm text-gray-600; }
}
+47
View File
@@ -0,0 +1,47 @@
import type { Metadata, Viewport } from "next";
import "@crosscode/ui/fonts.css";
import "./globals.css";
import { brandAttributes } from "@crosscode/ui";
import { loadApp } from "@/lib/load";
import { iconHref, rgb } from "@/lib/icon";
import { RegisterServiceWorker } from "@/components/RegisterServiceWorker";
export async function generateMetadata(): Promise<Metadata> {
const app = await loadApp();
const name = app.church?.name ?? "Church App";
return {
title: { default: name, template: `%s · ${name}` },
applicationName: app.shortName,
manifest: "/manifest.webmanifest",
icons: { icon: iconHref("favicon", app), apple: iconHref("apple", app) },
// iPhone: opened from the home screen it runs full screen, with this name under the icon (§2).
appleWebApp: { capable: true, title: app.shortName, statusBarStyle: "default" },
formatDetection: { telephone: false },
};
}
export async function generateViewport(): Promise<Viewport> {
const app = await loadApp();
return { themeColor: rgb(app.palette.brand), width: "device-width", initialScale: 1, viewportFit: "cover" };
}
/**
* Every page: the church's fonts and corners (shared brand style, @crosscode/ui) and its colours,
* made safe by the backend, as variables (APP-1.0-PLAN §2).
*/
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const app = await loadApp();
const p = app.palette;
const vars = `:root{--brand:${p.brand};--brand-dark:${p.brandDark};--on-brand:${p.onBrand};--brand-text:${p.brandText};--brand-tint:${p.brandTint};--accent:${p.accent};--on-accent:${p.onAccent}}`;
return (
<html lang={app.church?.locale ?? "en-ZA"} {...brandAttributes(app.style)}>
<head>
<style>{vars.replace(/[<>]/g, "")}</style>
</head>
<body>
{children}
<RegisterServiceWorker />
</body>
</html>
);
}
@@ -0,0 +1,37 @@
import { loadApp } from "@/lib/load";
import { iconHref, rgb } from "@/lib/icon";
/**
* The web app manifest (APP-1.0-PLAN §2, P1), built from the church profile: its name, short name
* (the profile's, else the name cut to 12 characters), icons (192, 512 and a maskable one on the
* primary colour), the primary colour as the theme, standalone, and a start address that says the
* App was opened from the home screen. Made per request: the church's name, colours and icon can
* change at any time, and are never baked in at build.
*/
export const dynamic = "force-dynamic";
export async function GET() {
const app = await loadApp();
const name = app.church?.name ?? "Church App";
const manifest = {
name,
short_name: app.shortName,
description: `${name}: prayer, news, devotionals and events.`,
id: "/",
start_url: "/?source=homescreen",
scope: "/",
display: "standalone",
orientation: "portrait",
background_color: "#ffffff",
theme_color: rgb(app.palette.brand),
lang: app.church?.locale ?? "en-ZA",
icons: [
{ src: iconHref("192", app), sizes: "192x192", type: "image/png", purpose: "any" },
{ src: iconHref("512", app), sizes: "512x512", type: "image/png", purpose: "any" },
{ src: iconHref("maskable", app), sizes: "512x512", type: "image/png", purpose: "maskable" },
],
};
return new Response(JSON.stringify(manifest), {
headers: { "Content-Type": "application/manifest+json", "Cache-Control": "public, max-age=300" },
});
}
+52
View File
@@ -0,0 +1,52 @@
import type { Metadata } from "next";
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
import { loadMe, ROLE_NAMES, signInHref } from "@/lib/load";
export const metadata: Metadata = { title: "Me", robots: { index: false, follow: false } };
/**
* 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).
*/
export default async function Me() {
const me = await loadMe();
if (!me) {
return (
<AppShell>
<h1 className="cca-h1">Me</h1>
<section className="cca-card space-y-3">
<p>Sign in with your church account to book a prayer slot, ask for prayer and choose what the App sends you.</p>
<a href={signInHref("/me")} className="cca-btn">Sign in</a>
</section>
</AppShell>
);
}
const roles = me.member.roles;
return (
<AppShell>
<h1 className="cca-h1">{me.member.name}</h1>
<section className="cca-card space-y-1">
<p className="cca-muted">{me.member.email}</p>
<p className="text-sm">{roles.length ? roles.map((r) => ROLE_NAMES[r]).join(", ") : "Member"}</p>
</section>
{roles.length > 0 && (
<section className="cca-card space-y-2">
<h2 className="cca-h2">The App&apos;s admin</h2>
{me.mfa ? (
<Link href="/admin" className="cca-btn">Open the admin</Link>
) : (
<>
<p className="cca-muted">Your role needs a sign-in with your second step (two-factor).</p>
<a href={signInHref("/admin", true)} className="cca-btn">Sign in to the admin</a>
</>
)}
</section>
)}
<form action="/api/auth/signout" method="post">
<button type="submit" className="cca-btn-quiet w-full">Sign out</button>
</form>
</AppShell>
);
}
+12
View File
@@ -0,0 +1,12 @@
import Link from "next/link";
import { AppShell } from "@/components/AppShell";
export default function NotFound() {
return (
<AppShell>
<h1 className="cca-h1">Page not found</h1>
<p className="cca-muted">That page isn&apos;t here. It may have moved, or the church has switched it off.</p>
<Link href="/" className="cca-btn">Go to Home</Link>
</AppShell>
);
}
@@ -0,0 +1,15 @@
import type { Metadata } from "next";
import Link from "next/link";
export const metadata: Metadata = { title: "Offline", robots: { index: false, follow: false } };
/** What the service worker shows for a page it never saved, while there's no connection (§2). */
export default function Offline() {
return (
<main className="mx-auto max-w-xl space-y-4 px-4 py-16 text-center">
<h1 className="cca-h1">You&apos;re offline</h1>
<p className="text-gray-600">This page wasn&apos;t saved on your phone. Connect to the internet and try again.</p>
<Link href="/" className="cca-btn">Go to Home</Link>
</main>
);
}
+33
View File
@@ -0,0 +1,33 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon";
import { InstallCard } from "@/components/InstallCard";
import { firstName, greeting, loadApp, loadMe } from "@/lib/load";
export async function generateMetadata(): Promise<Metadata> {
const app = await loadApp();
const name = app.church?.name ?? "Church App";
return { title: { absolute: name }, description: `${name}: prayer, news, devotionals and events, on your phone.` };
}
/**
* 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.
*/
export default async function Home() {
const [app, me] = await Promise.all([loadApp(), loadMe()]);
const on = new Set(app.modules);
const name = app.church?.name ?? "your church";
return (
<AppShell>
<h1 className="cca-h1">
{me ? `${greeting(app.timezone)}, ${firstName(me.member.name)}` : `Welcome to ${name}`}
</h1>
<InstallCard name={app.shortName} />
{on.has("house-of-prayer") && <ComingSoon title="House of Prayer">Today&apos;s prayer clock and your next slot will show here.</ComingSoon>}
{on.has("devotionals") && <ComingSoon title="Today's devotional">Today&apos;s Bible passage and devotional will show here.</ComingSoon>}
{on.has("announcements") && <ComingSoon title="Announcements">News from {name} will show here.</ComingSoon>}
</AppShell>
);
}
+18
View File
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { AppShell } from "@/components/AppShell";
import { ComingSoon } from "@/components/ComingSoon";
import { requireModule } from "@/lib/module";
// 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() {
await requireModule("house-of-prayer");
return (
<AppShell>
<h1 className="cca-h1">House of Prayer</h1>
<ComingSoon title="The prayer wall">The 24-hour prayer clock, with the hours still open, will show here.</ComingSoon>
</AppShell>
);
}
+7
View File
@@ -0,0 +1,7 @@
import type { MetadataRoute } from "next";
// Public content is indexed; the member's pages, the admin, prayer and the API never are
// (APP-1.0-PLAN §4, §11; ROADMAP-v3 §11). The sitemap grows with the public modules.
export default function robots(): MetadataRoute.Robots {
return { rules: [{ userAgent: "*", allow: "/", disallow: ["/admin", "/me", "/prayer", "/auth", "/offline", "/api"] }] };
}
@@ -0,0 +1,57 @@
import Link from "next/link";
import { headers } from "next/headers";
import { ChurchFooter } from "@crosscode/ui";
import { loadApp, loadMe, signInHref, type AppInfo } from "@/lib/load";
import { OfflineNotice } from "./OfflineNotice";
import { TabBar } from "./TabBar";
function Brand({ app }: { app: AppInfo }) {
const logo = app.church?.branding.logoUrl;
const icon = app.church?.branding.iconUrl;
return (
<Link href="/" className="flex min-w-0 items-center gap-2 rounded-cc-sm focus-visible:outline focus-visible:outline-2 focus-visible:outline-brand">
{logo ? (
<img src={logo} alt={app.church?.name ?? ""} className="h-9 w-auto max-w-[11rem] object-contain" />
) : (
<>
{icon && <img src={icon} alt="" className="h-8 w-8 rounded-cc-sm" />}
<span className="truncate font-heading text-lg font-semibold">{app.shortName}</span>
</>
)}
</Link>
);
}
/**
* Every member screen (APP-1.0-PLAN §1, §2): the header (logo, or icon and short name, and the
* account), the page in a centred column, the church's footer on public pages, and the tab bar
* with only the modules that are on.
*/
export async function AppShell({ children, footer = true }: { children: React.ReactNode; footer?: boolean }) {
const [app, me] = await Promise.all([loadApp(), loadMe()]);
const path = (await headers()).get("x-cca-path") ?? "/";
return (
<div className="min-h-dvh pb-[var(--cca-tabs)]">
<header className="sticky top-0 z-10 border-b border-gray-200 bg-white/95 pt-[env(safe-area-inset-top)] backdrop-blur">
<div className="cca-column flex h-14 items-center justify-between gap-3">
<Brand app={app} />
{me ? (
<Link href="/me" className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-brand text-sm font-semibold text-brand-on" aria-label={`Your account: ${me.member.name}`}>
{me.member.name.trim().charAt(0).toUpperCase()}
</Link>
) : (
<a href={signInHref(path)} className="text-sm font-semibold text-brand-text underline-offset-4 hover:underline">
Sign in
</a>
)}
</div>
</header>
<OfflineNotice />
<main id="main" className="cca-column space-y-4 py-5">
{children}
</main>
{footer && app.church && <ChurchFooter church={app.church} current="app" className="mt-8" />}
<TabBar modules={app.modules} />
</div>
);
}
@@ -0,0 +1,9 @@
/** A module's place on a screen until it's built (removed as each arrives, APP-1.0-PLAN §3–§7). */
export function ComingSoon({ title, children }: { title: string; children: React.ReactNode }) {
return (
<section className="cca-card">
<h2 className="cca-h2">{title}</h2>
<p className="cca-muted mt-1">{children}</p>
</section>
);
}
@@ -0,0 +1,94 @@
"use client";
import { useEffect, useState } from "react";
import { Share, X } from "lucide-react";
/** Chrome's install prompt (not in TypeScript's DOM types). */
type InstallPrompt = Event & { prompt: () => Promise<void>; userChoice: Promise<{ outcome: "accepted" | "dismissed" }> };
const DISMISSED_KEY = "cca-install-dismissed";
const HIDE_DAYS = 30;
function dismissedRecently(): boolean {
try {
const at = Number(localStorage.getItem(DISMISSED_KEY));
return Number.isFinite(at) && at > 0 && Date.now() - at < HIDE_DAYS * 86400e3;
} catch {
return false;
}
}
/**
* "Add to home screen" (APP-1.0-PLAN §2): a card on Home for someone who hasn't installed the App.
* Android and desktop Chrome get the browser's install prompt; an iPhone (no prompt) gets the
* Share → "Add to Home Screen" steps. Dismissing it hides it for 30 days. Never shown once the App
* runs from the home screen.
*/
export function InstallCard({ name }: { name: string }) {
const [mode, setMode] = useState<"hidden" | "prompt" | "ios">("hidden");
const [prompt, setPrompt] = useState<InstallPrompt | null>(null);
useEffect(() => {
const standalone = window.matchMedia("(display-mode: standalone)").matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
if (standalone || dismissedRecently()) return;
const ios = /iphone|ipad|ipod/i.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
// Set after the page has rendered (the server can't know the device), so no hydration mismatch.
const t = ios ? setTimeout(() => setMode("ios"), 0) : undefined;
const onPrompt = (e: Event) => {
e.preventDefault();
setPrompt(e as InstallPrompt);
setMode("prompt");
};
window.addEventListener("beforeinstallprompt", onPrompt);
return () => {
clearTimeout(t);
window.removeEventListener("beforeinstallprompt", onPrompt);
};
}, []);
if (mode === "hidden") return null;
const dismiss = () => {
try {
localStorage.setItem(DISMISSED_KEY, String(Date.now()));
} catch {
// Private browsing: hidden for this visit only.
}
setMode("hidden");
};
return (
<section aria-labelledby="install-title" className="cca-card relative border-brand/30 bg-brand-tint">
<button type="button" onClick={dismiss} className="absolute right-2 top-2 rounded-cc-sm p-2 text-gray-600 hover:bg-white" aria-label="Not now">
<X aria-hidden className="h-4 w-4" />
</button>
<h2 id="install-title" className="cca-h2 pr-8">Add {name} to your home screen</h2>
{mode === "prompt" ? (
<>
<p className="cca-muted mt-1">Open it like any other app, with one tap.</p>
<button
type="button"
className="cca-btn mt-3"
onClick={async () => {
if (!prompt) return;
await prompt.prompt();
await prompt.userChoice.catch(() => null);
setMode("hidden");
}}
>
Add to home screen
</button>
</>
) : (
<ol className="cca-muted mt-2 list-decimal space-y-1 pl-5">
<li>
Tap <Share aria-label="Share" className="inline h-4 w-4 align-text-bottom" /> <strong>Share</strong> at the bottom of Safari.
</li>
<li>
Choose <strong>Add to Home Screen</strong>, then <strong>Add</strong>.
</li>
</ol>
)}
</section>
);
}
@@ -0,0 +1,23 @@
"use client";
import { useSyncExternalStore } from "react";
const subscribe = (onChange: () => void) => {
window.addEventListener("online", onChange);
window.addEventListener("offline", onChange);
return () => {
window.removeEventListener("online", onChange);
window.removeEventListener("offline", onChange);
};
};
/** "You're offline" above a page the service worker kept (APP-1.0-PLAN §2). */
export function OfflineNotice() {
const offline = useSyncExternalStore(subscribe, () => !navigator.onLine, () => false);
if (!offline) return null;
return (
<p role="status" className="bg-amber-100 px-4 py-2 text-center text-sm text-amber-900">
You&apos;re offline: showing what was saved. Booking, cancelling and requests need a connection.
</p>
);
}
@@ -0,0 +1,18 @@
"use client";
import { useEffect } from "react";
/**
* Registers the service worker (public/sw.js, APP-1.0-PLAN §2): the App's shell and the last
* content saved for offline. It never asks for notification permission (no push, decision 13).
* Not in development, where Next's own reloading would fight a cache.
*/
export function RegisterServiceWorker() {
useEffect(() => {
if (process.env.NODE_ENV !== "production" || !("serviceWorker" in navigator)) return;
navigator.serviceWorker.register("/sw.js", { scope: "/" }).catch(() => {
// Without it the App still works online; nothing to tell the member.
});
}, []);
return null;
}
@@ -0,0 +1,42 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { BookOpen, CalendarDays, Flame, Home, UserRound } from "lucide-react";
import type { AppModule } from "@/lib/load";
/** The bottom tab bar (APP-1.0-PLAN §1, P18): Home, Prayer, Events, Devotional, Me; only what's on. */
const TABS = [
{ href: "/", label: "Home", icon: Home, module: null },
{ href: "/prayer", label: "Prayer", icon: Flame, module: "house-of-prayer" },
{ href: "/events", label: "Events", icon: CalendarDays, module: "events" },
{ href: "/devotional", label: "Devotional", icon: BookOpen, module: "devotionals" },
{ href: "/me", label: "Me", icon: UserRound, module: null },
] as const;
export function TabBar({ modules }: { modules: AppModule[] }) {
const path = usePathname();
const tabs = TABS.filter((t) => !t.module || modules.includes(t.module));
return (
<nav aria-label="Main" className="fixed inset-x-0 bottom-0 z-20 border-t border-gray-200 bg-white pb-[env(safe-area-inset-bottom)]">
<ul className="mx-auto flex h-16 max-w-xl">
{tabs.map((t) => {
const current = t.href === "/" ? path === "/" : path === t.href || path.startsWith(`${t.href}/`);
const Icon = t.icon;
return (
<li key={t.href} className="flex-1">
<Link
href={t.href}
aria-current={current ? "page" : undefined}
className={`flex h-full flex-col items-center justify-center gap-0.5 text-xs font-medium focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-brand ${current ? "text-brand-text" : "text-gray-600 hover:text-gray-900"}`}
>
<Icon aria-hidden className="h-5 w-5" strokeWidth={current ? 2.4 : 1.8} />
{t.label}
</Link>
</li>
);
})}
</ul>
</nav>
);
}
+31
View File
@@ -0,0 +1,31 @@
import type { AppInfo } from "./load";
/** The sizes the App's icon is drawn at (APP-1.0-PLAN §2): the manifest's, Apple's and the favicon. */
export const ICON_SIZES = { "192": 192, "512": 512, maskable: 512, apple: 180, favicon: 64 } as const;
export type IconKind = keyof typeof ICON_SIZES;
/** "Acacia Hill" → "AH", "Northpoint" → "N": the icon of a church without one of its own. */
export function initials(name: string): string {
const words = name.replace(/[^\p{L}\p{N}\s]/gu, " ").trim().split(/\s+/).filter(Boolean);
const letters = words.length > 1 ? [words[0]!, words[1]!].map((w) => [...w][0]!) : [...(words[0] ?? "")].slice(0, 1);
return letters.join("").toUpperCase() || "+";
}
/** The church's own icon when the image renderer can draw it (https, not SVG), else null. */
export function churchIconUrl(app: AppInfo): string | null {
const url = app.church?.branding.iconUrl;
return url && /^https:\/\//.test(url) && !/\.svg(\?|$)/i.test(url) ? url : null;
}
/** A short, stable version for the icons' addresses, so a new icon shows at once. */
export function iconVersion(app: AppInfo): string {
const s = `${app.church?.branding.iconUrl ?? ""}|${app.palette.brand}|${app.palette.onBrand}|${app.church?.shortName ?? app.church?.name ?? ""}`;
let h = 0;
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
return (h >>> 0).toString(36);
}
export const iconHref = (kind: IconKind, app: AppInfo) => `/app-icon/${kind}?v=${iconVersion(app)}`;
/** "31 78 121" → "rgb(31,78,121)". */
export const rgb = (triple: string) => `rgb(${triple.split(" ").join(",")})`;
+106
View File
@@ -0,0 +1,106 @@
import { cookies } from "next/headers";
import { cache } from "react";
/** The backend on this server (APP_API_URL; 5400 in development). */
export const api = (process.env.APP_API_URL || "http://127.0.0.1:5400").replace(/\/+$/, "");
export type AppModule = "house-of-prayer" | "prayer-requests" | "announcements" | "devotionals" | "events";
export type Church = {
name: string;
shortName: string | null;
timezone: string;
locale: string;
branding: { logoUrl: string | null; iconUrl: string | null; colours: { primary: string; accent: string | null } };
serviceTimes: { day: string; time: string; label: string | null }[];
contact: {
email: string | null;
phone: string | null;
whatsapp: string | null;
address: { line1: string; line2: string | null; suburb: string | null; city: string; postalCode: string | null } | null;
};
social: { network: string; url: string }[];
links: { website: string | null; events: string | null; app: string | null; accounts: string };
};
export type Palette = { brand: string; brandDark: string; onBrand: string; brandText: string; brandTint: string; accent: string; onAccent: string };
/** What the backend's /api/v1/app answers (backend/src/public/app.ts). */
export type AppInfo = {
church: Church | null;
shortName: string;
palette: Palette;
style: { fontPairing: string; corners: string };
modules: AppModule[];
timezone: string;
};
const FALLBACK: AppInfo = {
church: null,
shortName: "Church App",
palette: { brand: "31 78 121", brandDark: "25 62 97", onBrand: "255 255 255", brandText: "31 78 121", brandTint: "241 244 248", accent: "87 113 148", onAccent: "255 255 255" },
style: { fontPairing: "warm", corners: "soft" },
modules: ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"],
timezone: "Africa/Johannesburg",
};
/**
* The church, its colours and the modules on: one fetch per request (React `cache`), kept by Next
* for 30 seconds in production. While the backend can't answer, the App still shows (in Cross
* Code's colours), never an error page.
*/
export const loadApp = cache(async (): Promise<AppInfo> => {
try {
const res = await fetch(`${api}/api/v1/app`, process.env.NODE_ENV === "production" ? { next: { revalidate: 30 } } : { cache: "no-store" });
if (res.ok) return (await res.json()) as AppInfo;
} catch {
// Starting or down.
}
return FALLBACK;
});
export const ROLE_NAMES = {
owner: "Owner",
church_admin: "Church admin",
content_admin: "Content admin",
devotional_writer: "Devotional writer",
prayer_coordinator: "Prayer coordinator",
pastoral_care: "Pastoral care",
} as const;
export type Role = keyof typeof ROLE_NAMES;
/** The signed-in member (the backend's /api/auth/me). */
export type Me = {
member: { id: string; name: string; email: string; roles: Role[] };
/** Whether this sign-in had a second step: every role needs it (APP-1.0-PLAN §2). */
mfa: boolean;
activeRoles: Role[];
};
export const SESSION_COOKIE = "cca_session";
/** Null when signed out (or the backend can't say). */
export const loadMe = cache(async (): Promise<Me | null> => {
const session = (await cookies()).get(SESSION_COOKIE)?.value;
if (!session) return null;
try {
const res = await fetch(`${api}/api/auth/me`, { headers: { Cookie: `${SESSION_COOKIE}=${encodeURIComponent(session)}` }, cache: "no-store" });
if (res.ok) return (await res.json()) as Me;
} catch {
// The backend is starting or down: treated as signed out.
}
return null;
});
/** Where "Sign in" goes: Accounts, and back to that exact page (ROADMAP-v3 §3). `mfa` for the admin. */
export const signInHref = (returnTo: string, mfa = false) => `/api/auth/signin?returnTo=${encodeURIComponent(returnTo)}${mfa ? "&mfa=1" : ""}`;
/** The first name for a greeting ("Good morning, Thandi"). */
export const firstName = (name: string) => name.trim().split(/\s+/)[0] ?? name;
/** Morning, afternoon or evening in the church's timezone. */
export function greeting(timezone: string, now = new Date()): string {
const hour = Number(new Intl.DateTimeFormat("en-ZA", { timeZone: timezone, hour: "numeric", hourCycle: "h23" }).format(now));
return hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening";
}
@@ -0,0 +1,11 @@
import { NextResponse } from "next/server";
/**
* A 303 to a page of the App with a relative Location ("/me"), so the browser stays on the address
* it's on. `new URL(path, request.url)` would use the address the request reached Next.js on, which
* behind the proxy is the server's own (http://localhost:<web port>), as the Website found in 1.0.2.
*/
export function localRedirect(path: string): NextResponse {
if (!path.startsWith("/") || path.startsWith("//")) throw new Error(`Not a path on this site: ${path}`);
return new NextResponse(null, { status: 303, headers: { Location: path } });
}
+7
View File
@@ -0,0 +1,7 @@
import { notFound } from "next/navigation";
import { loadApp, type AppModule } from "./load";
/** A module's pages are "not found" while the church has it switched off (APP-1.0-PLAN §2). */
export async function requireModule(module: AppModule): Promise<void> {
if (!(await loadApp()).modules.includes(module)) notFound();
}
+22
View File
@@ -0,0 +1,22 @@
import { NextResponse, type NextRequest } from "next/server";
const SESSION_COOKIE = "cca_session";
/**
* The address a page was asked for, for the layouts: so "Sign in" comes back to that exact page
* (ROADMAP-v3 §3, "Sign-in always returns you to where you came from").
*
* Each page also says whether it was asked for signed in (`x-cca-signed-in`), so the service
* worker keeps a signed-in member's pages apart and forgets them once they're signed out
* (public/sw.js, APP-1.0-PLAN §2).
*/
export function proxy(request: NextRequest) {
const headers = new Headers(request.headers);
headers.set("x-cca-path", `${request.nextUrl.pathname}${request.nextUrl.search}`);
const res = NextResponse.next({ request: { headers } });
res.headers.set("x-cca-signed-in", request.cookies.has(SESSION_COOKIE) ? "1" : "0");
return res;
}
// Never Next's own paths, the API, the service worker or the icons.
export const config = { matcher: ["/((?!api|_next|sw.js|app-icon|manifest.webmanifest|favicon.ico).*)"] };
+20
View File
@@ -0,0 +1,20 @@
/** @type {import('tailwindcss').Config} */
// The church's colours are CSS variables set per request in layout.tsx (from its profile, made
// safe by the backend's palette, APP-1.0-PLAN §2). Each is an "r g b" triple.
const v = (name) => `rgb(var(--${name}) / <alpha-value>)`;
module.exports = {
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
theme: {
extend: {
colors: {
brand: { DEFAULT: v("brand"), dark: v("brand-dark"), text: v("brand-text"), tint: v("brand-tint"), on: v("on-brand") },
accent: { DEFAULT: v("accent"), on: v("on-accent") },
ink: "#111827",
},
borderRadius: { cc: "var(--cc-radius, 0.5rem)", "cc-sm": "var(--cc-radius-sm, 0.25rem)" },
fontFamily: { heading: "var(--cc-font-heading, inherit)" },
},
},
plugins: [],
};
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./src/*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
"exclude": ["node_modules"]
}