Compare commits
27
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b9dc559b6 | ||
|
|
ad488c3280 | ||
|
|
50ac7fab33 | ||
|
|
7032e16894 | ||
|
|
b720706143 | ||
|
|
5380a87be1 | ||
|
|
bd472ddc05 | ||
|
|
c22d7ecad6 | ||
|
|
514a6d8bc0 | ||
|
|
8372ef8c6b | ||
|
|
250c631fb4 | ||
|
|
753e2c4631 | ||
|
|
42684ed727 | ||
|
|
1e3004189a | ||
|
|
0c521ff614 | ||
|
|
4897489fb1 | ||
|
|
1c69b0cce9 | ||
|
|
b3318941ae | ||
|
|
2efafa166e | ||
|
|
e0c82fe314 | ||
|
|
a474cdcda6 | ||
|
|
8234bb3bc1 | ||
|
|
dd86021302 | ||
|
|
19c12ef09e | ||
|
|
a9215ac4e4 | ||
|
|
25100bd749 | ||
|
|
f68f695934 |
@@ -2,6 +2,92 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## accounts@1.9.0 + @crosscode/demo 1.0.0 + crosscode script - 2026-11-30
|
||||
|
||||
Church App 1.0.0 groundwork in Accounts (docs/APP-1.0-PLAN.md §8 and §12). One migration. Details
|
||||
in `apps/accounts/CHANGELOG.md`.
|
||||
|
||||
- **Accounts 1.9.0:** `messaging.get` and the `messaging.changed` hint (the App sends with the
|
||||
church's one set of email and WhatsApp settings); the WhatsApp opt-out for every product
|
||||
(`whatsapp.optout`, its own WAWP webhook for a church without Events, `whatsapp_opted_out` in
|
||||
`user.updated`, "Turn WhatsApp back on" on the account page); a demo scenario's church profile,
|
||||
logo, icon and people (`npm run demo -- --profile <scenario> --force`).
|
||||
- **`@crosscode/demo` 1.0.0** (new, `packages/demo`, not tagged): the eight scenarios' churches,
|
||||
people (same `sub` in every product) and SVG logos, for every product's demo loader.
|
||||
- **crosscode script:** `crosscode demo <church> accounts --profile <scenario>` (backup, load,
|
||||
reload); `--scenario <s>` on every demo (the profile must be the scenario's); Accounts installs
|
||||
and builds `packages/demo`.
|
||||
|
||||
## contracts@1.21.0 - 2026-11-30
|
||||
|
||||
Demo scenarios (docs/APP-1.0-PLAN.md §12, "Demo scenarios"): one choice on a demo client in the
|
||||
Hub loads every product with the same church. Additive for `seed-demo` jobs older Hubs send.
|
||||
|
||||
- **`agent.DEMO_SCENARIOS`**: eight, one per Website demo profile and keyed by it, each its own
|
||||
fictional church (St Columba's, Grace Cathedral, Ignite Church, Harbour City, Acacia Hill, Karoo
|
||||
Gemeenskapskerk, Northpoint, Riverside) with a label, description, campuses, language, the App's
|
||||
active-member band, and the profile each product loads. `demoScenario(key)`,
|
||||
`DEMO_SCENARIO_ORDER` (Accounts, Events, Website, App), `DEMO_SCENARIO_MIN_VERSIONS` (Accounts
|
||||
1.9.0, Events 3.8.0, Website 1.8.0, App 1.0.0).
|
||||
- **`seed-demo`** takes an optional `scenario`; its `profile` must then be the scenario's for the
|
||||
product. `accounts` joins `DEMO_PRODUCTS` (the scenario's church profile, logo, icon and people;
|
||||
no `adminEmail`). Events gets a profile per scenario next to its four (`EVENTS_DEMO_PROFILES`),
|
||||
so a scenario name with no `product` is an Events demo.
|
||||
- **`APP_DEMO_PROFILES`** is the eight scenarios. 1.20.0's `acacia-hill` is gone: it's the
|
||||
`community-family` scenario, and no App or Hub had used it.
|
||||
- `SEED_SCENARIO_MIN_AGENT` (1.7.0) and `SEED_DEMO_MIN_AGENT_BY_PRODUCT`. JSON Schema `agent-job`
|
||||
regenerated.
|
||||
|
||||
## contracts@1.20.0 - 2026-11-30
|
||||
|
||||
The contracts for Church App 1.0.0 (docs/APP-1.0-PLAN.md §12), the first step of phase 6. Additive:
|
||||
products on 1.19.0 keep working. Accounts refuses the two new requests (`INVALID_REQUEST`) until
|
||||
Accounts 1.9.0 answers them.
|
||||
|
||||
- **`crosscode.devotional/1`** (`src/devotional.ts`): `devotionalSchema` (date, title, the passage
|
||||
with its text and translation, body, prayer, author, `source` `crosscode` or `church`),
|
||||
`devotionalsReplySchema` (the Hub's `GET /api/v2/devotionals?from=`, Cross Code's only),
|
||||
`CROSSCODE_DEVOTIONALS_AHEAD_MONTHS` (3). **CSV import** shared by the Hub and the App:
|
||||
`DEVOTIONAL_CSV_COLUMNS`, `parseCsv` (quotes, line breaks, BOM, `;` files), `checkDevotionalCsv`
|
||||
(each row's errors by column, warnings, days already taken, a `latestDate` limit, dates twice in
|
||||
the file), `devotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`.
|
||||
- **Bible passages** (`src/bible.ts`): `BIBLE_TRANSLATIONS` (NLT, ESV, NIV, NKJV, KJV, AFR53, AFR83,
|
||||
each with its YouVersion id and copyright line), `BIBLE_BOOKS` (USFM codes, English and Afrikaans
|
||||
names, abbreviations, chapters), `parseBibleReference` ("Johannes 3:16–18", "1 Kor. 13:4-7",
|
||||
"Rom 8:38-9:1", "Jude 3"), `formatBibleReference`, `passageVerseCount`, `youVersionUrl`,
|
||||
`PASSAGE_WARN_VERSES` (25).
|
||||
- **Identity requests:** `messaging.get` (the church's SMTP and WAWP settings for the App, secrets
|
||||
sealed with the link's secret; `messagingGetReplySchema`) and the `messaging.changed` hint
|
||||
Accounts sends back (`MESSAGING_CHANGED_PATH`); `whatsapp.optout` (a STOP received by any
|
||||
product; `whatsappOptOutReplySchema`). `whatsapp_opted_out` (optional) in the profile that
|
||||
`user.updated` and the sign-in claims carry.
|
||||
- **App:** `APP_MODULES`; `hub.DEVOTIONALS_PATH` and its error codes; `agent.APP_DEMO_PROFILES`
|
||||
(`acacia-hill`), `app` in `DEMO_PRODUCTS`, `SEED_APP_DEMO_MIN_AGENT` (1.7.0, not released yet).
|
||||
- **Church export:** the `app` section (`exportAppSchema`: prayer wall rules, commitments as rules
|
||||
with their skips, "I prayed" marks, campaigns, testimonies, prayer requests with their
|
||||
moderation, emergency numbers, announcements, the church's own devotionals, simple events), and
|
||||
`people[].roles` (optional) for a person with several roles.
|
||||
- New samples: `devotionals-reply`, `messaging-get`, `messaging-get-reply`, `messaging-changed`,
|
||||
`whatsapp-optout`, `whatsapp-optout-reply`, `church-export-app`. New JSON Schemas: `devotional`,
|
||||
`devotionals-reply`, `messaging-get-reply`, `messaging-changed`, `whatsapp-optout-reply`.
|
||||
|
||||
## website@1.7.1 - 2026-11-28
|
||||
|
||||
Move and zoom for ministries', leaders' and events' photos (1.7.0 had it in page sections only).
|
||||
One migration: a nullable `framing` column on `Ministry`, `Leader` and `SimpleEvent`. Details in
|
||||
`apps/website/CHANGELOG.md`.
|
||||
|
||||
## website@1.7.0 - 2026-11-27
|
||||
|
||||
Photos can be moved and zoomed in their frame, and unused photos deleted. Details in
|
||||
`apps/website/CHANGELOG.md`. No migration.
|
||||
|
||||
- **Move and zoom:** a section's photo shows in its frame's shape for the template and layout,
|
||||
with a dialog to drag and zoom it; saved with the section (`data.framing`), a draft until
|
||||
published.
|
||||
- **Delete photos:** the media library says where each photo is used, and deletes one used nowhere
|
||||
(its files too); `DELETE /api/v1/admin/media/:id` refuses one in use.
|
||||
|
||||
## events@3.7.2 + website@1.6.1 - 2026-11-27
|
||||
|
||||
Events shown on the other product's site no longer show twice after a reseed, and the Website's
|
||||
|
||||
@@ -1,5 +1,57 @@
|
||||
# Changelog — Accounts
|
||||
|
||||
## [1.9.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and the new shared package `@crosscode/demo` (built with Accounts; the
|
||||
`crosscode` script on `main` builds it). **One migration** (`20261130000000_accounts_1_9`): two
|
||||
columns on `Account`, one on `ProductLink`, a `WhatsAppOptOut` table. No new .env variables. Part of
|
||||
Church App 1.0.0 (docs/APP-1.0-PLAN.md §8 and §12).
|
||||
|
||||
### Added
|
||||
|
||||
- **`messaging.get`** (contracts 1.20.0): a linked product gets the church's email (SMTP) and
|
||||
WhatsApp (WAWP) settings, the password and token sealed with the link's secret, and is
|
||||
remembered (`ProductLink.messagingWantedAt`). The reply is never kept in `ProductRequest`.
|
||||
- **`messaging.changed`**: when an admin changes the email or WhatsApp settings here, or a product
|
||||
saves them (`messaging.set`), each product that asked is sent the hint at
|
||||
`/api/accounts/v1/messaging-changed` (a `Delivery`, retried as the other calls), except the one
|
||||
that made the change.
|
||||
- **The WhatsApp opt-out for every product** (APP-1.0-PLAN decision 11):
|
||||
- `whatsapp.optout` from a product that received a STOP: the number is kept (`WhatsAppOptOut`),
|
||||
every account with it is opted out (`Account.whatsappOptedOut`), its news on WhatsApp turned
|
||||
off (a consent change, `whatsapp_stop`), and `user.updated` goes to every product with
|
||||
`whatsapp_opted_out: true`. A number without an account is kept too: an account that gets it
|
||||
later (sign-up, the account page, `people.ensure`, `people.update`, an import) starts opted out.
|
||||
- **Accounts' own WAWP webhook**, `POST /api/v2/webhooks/whatsapp?secret=…`, for a church without
|
||||
Cross Events: a STOP (English or Afrikaans: STOP, STOPP, UNSUBSCRIBE, OPT OUT, UITTEKEN) opts
|
||||
the number out and answers once with how to undo it. Admin → Email and WhatsApp → **WhatsApp
|
||||
replies (STOP)** shows the address to give WAWP and when it last called (or that Cross Events
|
||||
takes the replies).
|
||||
- Accounts sends an opted-out person no WhatsApp: sign-in codes go by email, setting WhatsApp up
|
||||
as the two-step method is refused, sign-in notices skip it.
|
||||
- **Turn WhatsApp back on** on the account page (Privacy), `POST /api/v2/me/whatsapp-on`: the
|
||||
number's STOP is forgotten and the products are told. News on WhatsApp stays off until ticked.
|
||||
- "Download my data" shows whether WhatsApp is off and since when.
|
||||
- **Demo scenarios** (contracts 1.21.0, APP-1.0-PLAN §12), for demo sites only:
|
||||
- `npm run demo -- --profile <scenario> --force` (`--list` for the eight), run by
|
||||
`crosscode demo <church> accounts --profile <scenario>` after a backup. The church profile
|
||||
becomes the scenario's church (name, short name, locale, colours, font pairing, corners,
|
||||
campuses, service times, contact, social links), and `church.changed` goes to the products.
|
||||
- Its **logo and icon**, drawn for the demo (`@crosscode/demo`), at
|
||||
`/api/demo-assets/<scenario>/logo.svg` and `icon.svg`.
|
||||
- Its **people** (54 to about 2 450, enough for the scenario's App band), at example.com with the
|
||||
password `Demo@1234`, each with the same account id on every load and in every product
|
||||
(`demoId`). Demo people from another scenario are anonymised; real people (any other address)
|
||||
and Accounts admins are never touched; loading a scenario again brings its people back with
|
||||
their ids.
|
||||
|
||||
### Checked on PostgreSQL 18
|
||||
|
||||
All three migrations on an empty database (the result matches the schema exactly); scenario loads
|
||||
(Acacia Hill 0.8 s, Riverside's 2 457 people 3.4 s, switching back 14.7 s), the people's ids kept,
|
||||
a real person untouched; the STOP opt-out, a known number on a new account, turning it back on;
|
||||
`messaging.changed` queued; `npm run demo` with and without `--force`.
|
||||
|
||||
## [1.8.0] - 2026-11-26
|
||||
|
||||
No migrations, no new settings, no backend changes. The admin redesigned as Cross Events' admin
|
||||
|
||||
@@ -3,6 +3,17 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.9.0
|
||||
|
||||
- **STOP works for every site.** Someone who replies STOP to your church's WhatsApp number gets no
|
||||
WhatsApp from any of your church's sites any more, reminders and sign-in codes included (codes
|
||||
come by email instead). They can turn WhatsApp back on from their account page. Without Cross
|
||||
Events, Admin → Email and WhatsApp shows the address to give WAWP, so the replies reach Accounts.
|
||||
- Getting ready for the **Church App**: it will send with the email and WhatsApp settings you
|
||||
already have, without asking for its own, and pick up any change you make here.
|
||||
- **Demo churches** for Cross Code's demo sites: a church's name, logo, colours, service times and
|
||||
people for each of eight demo scenarios. Never used on a real church's sign-in.
|
||||
|
||||
## 1.8.0
|
||||
|
||||
- **An easier admin.** Admin opens on an overview: how many people have an account, anything that
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
@@ -14,10 +14,12 @@
|
||||
"postinstall": "prisma generate",
|
||||
"prisma:generate": "prisma generate",
|
||||
"prisma:deploy": "prisma migrate deploy && prisma generate",
|
||||
"prisma:status": "prisma migrate status"
|
||||
"prisma:status": "prisma migrate status",
|
||||
"demo": "tsx scripts/demo.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the WhatsApp opt-out for every product, and the
|
||||
-- products that asked for the church's email and WhatsApp settings (messaging.get).
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "Account" ADD COLUMN "whatsappOptedOut" BOOLEAN NOT NULL DEFAULT false,
|
||||
ADD COLUMN "whatsappOptedOutAt" TIMESTAMP(3);
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "ProductLink" ADD COLUMN "messagingWantedAt" TIMESTAMP(3);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "WhatsAppOptOut" (
|
||||
"phone" TEXT NOT NULL,
|
||||
"keyword" TEXT NOT NULL,
|
||||
"source" TEXT NOT NULL,
|
||||
"receivedAt" TIMESTAMP(3) NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "WhatsAppOptOut_pkey" PRIMARY KEY ("phone")
|
||||
);
|
||||
@@ -58,6 +58,10 @@ model Account {
|
||||
// 1.1.0: moved in from a product with 2FA but without recovery codes (Events keys its codes with
|
||||
// its own secret, so they can't move): new ones are shown after the next sign-in's second step.
|
||||
recoveryCodesNeeded Boolean @default(false)
|
||||
// 1.9.0: replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8): no product sends them
|
||||
// WhatsApp until they turn it back on here. Sent to products as `whatsapp_opted_out`.
|
||||
whatsappOptedOut Boolean @default(false)
|
||||
whatsappOptedOutAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@ -201,20 +205,23 @@ model AppSetting {
|
||||
// A linked product (Connect, crosscode.link/1). Each is also an OIDC client (§4): client_id is
|
||||
// installId, the client secret is derived from `secret`, the addresses are fixed paths on `url`.
|
||||
model ProductLink {
|
||||
installId String @id
|
||||
product String // events | website | app
|
||||
url String
|
||||
publicKey String
|
||||
secret String // encrypted
|
||||
connectedAt DateTime
|
||||
connectedById String?
|
||||
installId String @id
|
||||
product String // events | website | app
|
||||
url String
|
||||
publicKey String
|
||||
secret String // encrypted
|
||||
connectedAt DateTime
|
||||
connectedById String?
|
||||
// 1.1.0: a move of this product's users into Accounts is under way (import.begin … finish).
|
||||
importStartedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries Delivery[]
|
||||
people ProductPerson[]
|
||||
requests ProductRequest[]
|
||||
importStartedAt DateTime?
|
||||
// 1.9.0: asked for the church's email and WhatsApp settings (messaging.get), so it's sent
|
||||
// messaging.changed when they change.
|
||||
messagingWantedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deliveries Delivery[]
|
||||
people ProductPerson[]
|
||||
requests ProductRequest[]
|
||||
}
|
||||
|
||||
// 1.1.0: the people a linked product knows (imported by it, added by it, or signed in through it).
|
||||
@@ -244,6 +251,16 @@ model ProductRequest {
|
||||
@@index([createdAt])
|
||||
}
|
||||
|
||||
// 1.9.0: numbers that replied STOP (APP-1.0-PLAN §8), kept with or without an account, so an
|
||||
// account that gets the number later starts opted out. Removed when the person turns WhatsApp on.
|
||||
model WhatsAppOptOut {
|
||||
phone String @id // E.164
|
||||
keyword String
|
||||
source String // the product that received it, or "accounts" (its own webhook)
|
||||
receivedAt DateTime
|
||||
createdAt DateTime @default(now())
|
||||
}
|
||||
|
||||
model LinkNonce {
|
||||
nonce String @id
|
||||
seenAt DateTime @default(now())
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Loads a demo scenario's church and people into Accounts (1.9.0, docs/APP-1.0-PLAN.md §12).
|
||||
*
|
||||
* npm run demo -- --profile <scenario> [--scenario <scenario>] --force
|
||||
* npm run demo -- --list
|
||||
*
|
||||
* It replaces the church profile and the demo people, so it needs --force. On a server,
|
||||
* `crosscode demo <church> accounts --profile …` runs it (backup first), for the Hub's demo sites;
|
||||
* Accounts loads first in a scenario, then Cross Events, the Website and the App.
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import { agent } from '@crosscode/contracts';
|
||||
import { PrismaClient } from '../src/generated/prisma/client.js';
|
||||
import { createCtx } from '../src/context.js';
|
||||
import { loadConfig } from '../src/lib/config.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
|
||||
const arg = (name: string) => {
|
||||
const i = process.argv.indexOf(`--${name}`);
|
||||
return i > 0 ? process.argv[i + 1] : undefined;
|
||||
};
|
||||
|
||||
if (process.argv.includes('--list')) {
|
||||
for (const s of agent.DEMO_SCENARIOS) console.log(`${s.key.padEnd(18)} ${s.label}`);
|
||||
process.exit(0);
|
||||
}
|
||||
const profile = agent.demoScenarioSchema.safeParse(arg('profile'));
|
||||
if (!profile.success) {
|
||||
console.error(`Usage: npm run demo -- --profile <scenario> --force (one of ${agent.DEMO_SCENARIO_KEYS.join(', ')}; --list)`);
|
||||
process.exit(2);
|
||||
}
|
||||
const scenario = arg('scenario');
|
||||
if (scenario !== undefined && scenario !== profile.data) {
|
||||
console.error(`--scenario ${scenario} loads ${agent.demoScenario(agent.demoScenarioSchema.parse(scenario)).profiles.accounts} in Accounts, not ${profile.data}.`);
|
||||
process.exit(2);
|
||||
}
|
||||
if (!process.argv.includes('--force')) {
|
||||
console.error('This replaces the church profile and the demo people. Add --force to do it (demo sites only).');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const db = new PrismaClient({ adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL! }) });
|
||||
const ctx = createCtx(loadConfig(), db);
|
||||
try {
|
||||
const r = await loadScenario(ctx, profile.data);
|
||||
console.log(`${r.church} loaded: ${r.people} people (${r.created} new, ${r.updated} brought back, ${r.removed} from before removed). The linked products are told the church changed.`);
|
||||
} finally {
|
||||
await db.$disconnect();
|
||||
}
|
||||
@@ -44,6 +44,8 @@ export function profileOf(a: Account): Profile {
|
||||
phone_number: a.phone,
|
||||
phone_number_verified: a.phoneVerified,
|
||||
news_consent: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||
// 1.9.0 (contracts 1.20.0): replied STOP; no product sends them WhatsApp.
|
||||
whatsapp_opted_out: a.whatsappOptedOut,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -112,7 +114,11 @@ export async function sendCode(ctx: Ctx, a: Account, method: 'email' | 'whatsapp
|
||||
const churchName = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'your church';
|
||||
const what = purpose === 'verify_email' ? 'confirm your email address' : 'sign in';
|
||||
const text = `Your code to ${what} at ${churchName} is ${code}. It works for ${CODE_MINUTES} minutes. If you didn't ask for it, you can ignore this message.`;
|
||||
if (method === 'whatsapp' && a.phone) {
|
||||
// 1.9.0: someone who replied STOP gets no WhatsApp, codes included: email instead.
|
||||
if (method === 'whatsapp' && a.phone && a.whatsappOptedOut && purpose !== 'sign_in') {
|
||||
throw new SendError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page, or choose another way to get your codes.', 'CODE_NOT_SENT');
|
||||
}
|
||||
if (method === 'whatsapp' && a.phone && !a.whatsappOptedOut) {
|
||||
try {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text });
|
||||
return { codeHash: hashToken(code), sentTo: maskedTarget(a, 'whatsapp') };
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function sendSignInNotice(ctx: Ctx, o: { accountId: string; ip: str
|
||||
const when = ctx.now().toLocaleString('en-ZA', { timeZone: ctx.config.timezone, dateStyle: 'medium', timeStyle: 'short' });
|
||||
const msg = await newSignInEmail(ctx, { name: a.name, when, location: await roughLocation(ctx, o.ip), device: describeDevice(o.userAgent), site });
|
||||
await ctx.messenger.email({ to: a.email, subject: msg.subject, text: msg.text, html: msg.html });
|
||||
if (a.phone && a.phoneVerified && (await ctx.messenger.whatsappReady())) {
|
||||
if (a.phone && a.phoneVerified && !a.whatsappOptedOut && (await ctx.messenger.whatsappReady())) {
|
||||
await ctx.messenger.whatsapp({ to: a.phone, text: msg.whatsapp }).catch((e: Error) => console.warn('[sign-in notice] WhatsApp:', e.message));
|
||||
}
|
||||
return 'sent';
|
||||
|
||||
@@ -42,6 +42,7 @@ export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?:
|
||||
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
|
||||
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
|
||||
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
|
||||
if (method === 'whatsapp' && a.whatsappOptedOut) throw new TwoFactorError('You turned WhatsApp messages off (you replied STOP). Turn them back on on your account page first.', 'BAD_METHOD');
|
||||
if (method === 'totp') {
|
||||
const secret = generateSecret();
|
||||
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
/**
|
||||
* The WhatsApp opt-out for every product (1.9.0, docs/APP-1.0-PLAN.md §8, decision 11). A STOP to
|
||||
* the church's WhatsApp number reaches Accounts (a product's `whatsapp.optout`, or Accounts' own
|
||||
* webhook for a church without Events). Accounts keeps it: the number in `WhatsAppOptOut`, and
|
||||
* `whatsappOptedOut` on each account with it. Every linked product is told (`user.updated` carries
|
||||
* `whatsapp_opted_out`) and sends that person no WhatsApp of any kind until they turn it back on
|
||||
* on their account page here. Accounts itself sends them none either (codes go by email).
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { Account } from '../generated/prisma/client.js';
|
||||
import { audit, loginEvent } from '../lib/audit.js';
|
||||
import { profileChanged, setNewsConsent } from './service.js';
|
||||
|
||||
/** What counts as STOP in a reply (English and Afrikaans), as Cross Events reads it. */
|
||||
export function isStopKeyword(text: unknown): boolean {
|
||||
return /^\s*(stop|stopp|unsubscribe|stop all|opt out|optout|uitteken)\s*[.!]?\s*$/i.test(String(text ?? ''));
|
||||
}
|
||||
|
||||
/** A WAWP chat id (`27821234567@c.us`) → `+27821234567`; null for groups, channels and LIDs. */
|
||||
export function phoneFromChatId(chatId: unknown): string | null {
|
||||
const m = /^(\d{8,15})@c\.us$/.exec(String(chatId ?? ''));
|
||||
return m ? `+${m[1]}` : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A STOP from `phone` (E.164): keeps the number, opts out every account with it (news on WhatsApp
|
||||
* off too) and tells the products. Returns how many accounts have the number.
|
||||
*/
|
||||
export async function optOutNumber(ctx: Ctx, phone: string, opts: { keyword: string; source: string; receivedAt: Date }): Promise<number> {
|
||||
await ctx.db.whatsAppOptOut.upsert({
|
||||
where: { phone },
|
||||
update: { keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt },
|
||||
create: { phone, keyword: opts.keyword, source: opts.source, receivedAt: opts.receivedAt, createdAt: ctx.now() },
|
||||
});
|
||||
const accounts = await ctx.db.account.findMany({ where: { phone, status: { not: 'deleted' } } });
|
||||
for (const a of accounts) await optOut(ctx, a, opts.source);
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'whatsapp_opt_out', targetType: 'phone', targetId: null, metadata: { source: opts.source, keyword: opts.keyword, accounts: accounts.length } });
|
||||
return accounts.length;
|
||||
}
|
||||
|
||||
async function optOut(ctx: Ctx, a: Account, source: string) {
|
||||
if (!a.whatsappOptedOut) {
|
||||
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: true, whatsappOptedOutAt: ctx.now() } });
|
||||
await loginEvent(ctx, a.id, 'whatsapp_opted_out', undefined, { detail: { source } });
|
||||
}
|
||||
await setNewsConsent(ctx, a, { whatsapp: false }, 'whatsapp_stop');
|
||||
await profileChanged(ctx, a.id);
|
||||
}
|
||||
|
||||
/** The person turns WhatsApp back on (their account page): the number's STOP is forgotten too. */
|
||||
export async function optBackIn(ctx: Ctx, a: Account): Promise<boolean> {
|
||||
if (!a.whatsappOptedOut) return false;
|
||||
await ctx.db.account.update({ where: { id: a.id }, data: { whatsappOptedOut: false, whatsappOptedOutAt: null } });
|
||||
if (a.phone) await ctx.db.whatsAppOptOut.deleteMany({ where: { phone: a.phone } });
|
||||
await loginEvent(ctx, a.id, 'whatsapp_opted_in');
|
||||
await profileChanged(ctx, a.id);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After an account's phone number is set or changed: a number that replied STOP starts opted out.
|
||||
* (A number without a STOP never turns an opt-out off: only the person does.) Returns whether it did.
|
||||
*/
|
||||
export async function applyKnownOptOut(ctx: Ctx, accountId: string): Promise<boolean> {
|
||||
const a = await ctx.db.account.findUnique({ where: { id: accountId } });
|
||||
if (!a?.phone || a.whatsappOptedOut) return false;
|
||||
const stop = await ctx.db.whatsAppOptOut.findUnique({ where: { phone: a.phone } });
|
||||
if (!stop) return false;
|
||||
await optOut(ctx, a, 'known_number');
|
||||
return true;
|
||||
}
|
||||
@@ -11,6 +11,8 @@ import { ApiError, handle, limit, sendError } from '../http.js';
|
||||
import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js';
|
||||
import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js';
|
||||
import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js';
|
||||
import { messagingChanged, messagingParts } from '../links/messaging.js';
|
||||
import { whatsappWebhookUrl } from '../links/whatsappWebhook.js';
|
||||
import { currentSession } from '../oidc/sessions.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
|
||||
@@ -195,6 +197,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
changed.push(key);
|
||||
}
|
||||
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
|
||||
// 1.9.0: products sending with the church's settings (the App) fetch them again.
|
||||
await messagingChanged(ctx, messagingParts(changed));
|
||||
return { changed };
|
||||
}));
|
||||
|
||||
@@ -209,6 +213,13 @@ export function adminRouter(ctx: Ctx, provider: Provider) {
|
||||
return { sent: true };
|
||||
}));
|
||||
|
||||
// 1.9.0: WAWP's webhook address for STOP replies (a church without Cross Events points WAWP here).
|
||||
r.get('/settings/whatsapp-webhook', handle(async (req, res) => {
|
||||
await admin(req, res);
|
||||
const linked = await ctx.db.productLink.findFirst({ where: { product: 'events' } });
|
||||
return { ...(await whatsappWebhookUrl(ctx)), eventsLinked: !!linked };
|
||||
}));
|
||||
|
||||
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
|
||||
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
|
||||
const me = await admin(req, res);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* /api/self/… the account page's own sign-in
|
||||
* /api/church/v1, /api/links/v1/… for the church's other products
|
||||
* /api/accounts/v1/requests what a linked product asks (import, people.*; contracts 1.8.0)
|
||||
* /api/v2/webhooks/whatsapp WAWP's webhook: STOP replies (1.9.0)
|
||||
* /api/v2/… the pages' API (sign-in steps, account, admin, setup)
|
||||
*/
|
||||
import express from 'express';
|
||||
@@ -19,6 +20,7 @@ import { meRouter } from './me/routes.js';
|
||||
import { LOGOUT_JS } from './oidc/pages.js';
|
||||
import { publicRouter } from './public/routes.js';
|
||||
import { requestsRouter } from './links/requests.js';
|
||||
import { whatsappWebhookRouter } from './links/whatsappWebhook.js';
|
||||
import { setupRouter } from './setup/routes.js';
|
||||
import { health } from './hub/client.js';
|
||||
import { appVersion } from './lib/version.js';
|
||||
@@ -50,6 +52,8 @@ export function createApp(ctx: Ctx, provider: Provider) {
|
||||
app.use('/api/self', selfRouter(ctx));
|
||||
app.use('/api', requestsRouter(ctx, provider));
|
||||
app.use('/api', publicRouter(ctx));
|
||||
// 1.9.0: WAWP's webhook (STOP replies), before the pages' API: no same-origin check, its own secret.
|
||||
app.use(whatsappWebhookRouter(ctx));
|
||||
|
||||
const v2 = express.Router();
|
||||
v2.use(express.json({ limit: '64kb' }));
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Accounts' part of a demo scenario (1.9.0, docs/APP-1.0-PLAN.md §12, "Demo scenarios"): the
|
||||
* scenario's church becomes the church profile (its own name, logo, icon, colours, campuses,
|
||||
* service times and contact details), and its people get accounts. Loaded first, so Cross Events,
|
||||
* the Website and the App then build their demo data around the same church and people.
|
||||
*
|
||||
* Only for demo sites (`crosscode demo <church> accounts --profile <scenario>`, which takes a backup
|
||||
* first). People keep the same account id on every load (`demoId`), so products' copies still match.
|
||||
* Demo people from before who aren't in this scenario are anonymised; real people (any address not at
|
||||
* example.com) and Accounts admins are never touched.
|
||||
*/
|
||||
import { agent, DEMO_EMAIL_DOMAIN } from '@crosscode/contracts';
|
||||
import { DEMO_PASSWORD, demoChurch, demoIconSvg, demoLogoSvg, demoPeople } from '@crosscode/demo';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { hashPassword } from '../lib/passwords.js';
|
||||
import { updateProfile } from '../church/profile.js';
|
||||
import { currentNoticeVersion } from '../privacy/notice.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
|
||||
/** Where Accounts serves the scenario's logo and icon (`/api/demo-assets/<scenario>/logo.svg`). */
|
||||
export const DEMO_ASSETS_PATH = '/api/demo-assets';
|
||||
const DEMO_ASSET_FILES = { 'logo.svg': demoLogoSvg, 'icon.svg': demoIconSvg } as const;
|
||||
|
||||
/** The SVG for a demo asset, or null for anything else. */
|
||||
export function demoAsset(scenario: string, file: string): string | null {
|
||||
const key = agent.demoScenarioSchema.safeParse(scenario);
|
||||
const draw = (DEMO_ASSET_FILES as Record<string, (s: agent.DemoScenarioKey) => string>)[file];
|
||||
return key.success && draw ? draw(key.data) : null;
|
||||
}
|
||||
|
||||
export interface ScenarioResult { scenario: agent.DemoScenarioKey; church: string; people: number; created: number; updated: number; removed: number }
|
||||
|
||||
const isDemo = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`);
|
||||
const CHUNK = 500;
|
||||
|
||||
export async function loadScenario(ctx: Ctx, scenario: agent.DemoScenarioKey): Promise<ScenarioResult> {
|
||||
const { profile } = demoChurch(scenario);
|
||||
const assets = `${ctx.config.publicUrl.replace(/\/$/, '')}${DEMO_ASSETS_PATH}/${scenario}`;
|
||||
|
||||
// The church: every shared field replaced, so nothing from the church before is left (tells the products: church.changed).
|
||||
await updateProfile(ctx, {
|
||||
name: profile.name, shortName: profile.shortName, timezone: profile.timezone, locale: profile.locale,
|
||||
branding: { logoUrl: `${assets}/logo.svg`, iconUrl: `${assets}/icon.svg`, colours: profile.colours, style: profile.style },
|
||||
campuses: profile.campuses, serviceTimes: profile.serviceTimes,
|
||||
contact: { ...profile.contact, phone: null, whatsapp: null }, social: profile.social,
|
||||
});
|
||||
|
||||
// The people.
|
||||
const people = demoPeople(scenario);
|
||||
const wanted = new Set(people.map((p) => p.id));
|
||||
const existing = new Map((await ctx.db.account.findMany({ where: { id: { in: [...wanted] } } })).map((a) => [a.id, a]));
|
||||
let removed = 0;
|
||||
for (const a of await ctx.db.account.findMany({ where: { email: { contains: `@${DEMO_EMAIL_DOMAIN}` }, status: { not: 'deleted' } } })) {
|
||||
if (wanted.has(a.id) || !isDemo(a.email) || a.role === 'admin') continue;
|
||||
await ctx.db.oidcPayload.deleteMany({ where: { accountId: a.id } });
|
||||
await anonymise(ctx, a.id);
|
||||
await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } });
|
||||
removed++;
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(DEMO_PASSWORD);
|
||||
const notice = await currentNoticeVersion(ctx);
|
||||
const now = ctx.now();
|
||||
const fields = (p: (typeof people)[number]) => ({
|
||||
name: p.name, givenName: p.givenName, familyName: p.familyName, email: p.email, emailVerified: true,
|
||||
phone: null, phoneVerified: false, passwordHash, role: 'member' as const, status: 'active' as const,
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: now,
|
||||
noticeVersionAccepted: notice, failedSignIns: 0, lockedUntil: null, deactivatedAt: null, anonymisedAt: null,
|
||||
whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
});
|
||||
let updated = 0;
|
||||
// Already here (this scenario loaded before, or anonymised when another was): brought back as they were.
|
||||
for (const p of people) {
|
||||
const a = existing.get(p.id);
|
||||
if (!a) continue;
|
||||
// Never take over a real person's account, nor an admin's.
|
||||
if (a.role === 'admin' || (a.status !== 'deleted' && !isDemo(a.email))) continue;
|
||||
const other = await ctx.db.account.findUnique({ where: { email: p.email } });
|
||||
if (other && other.id !== p.id) continue;
|
||||
await ctx.db.account.update({ where: { id: p.id }, data: fields(p) });
|
||||
updated++;
|
||||
}
|
||||
// New: in chunks, as the larger scenarios have a couple of thousand people.
|
||||
const taken = new Set((await ctx.db.account.findMany({ where: { email: { in: people.map((p) => p.email) } }, select: { email: true } })).map((a) => a.email));
|
||||
const fresh = people.filter((p) => !existing.has(p.id) && !taken.has(p.email));
|
||||
for (let i = 0; i < fresh.length; i += CHUNK) {
|
||||
await ctx.db.account.createMany({ data: fresh.slice(i, i + CHUNK).map((p) => ({ id: p.id, ...fields(p), createdAt: now })) });
|
||||
}
|
||||
|
||||
await audit(ctx, { actorId: null, actorRole: 'system', action: 'demo_scenario_loaded', targetType: 'setting', targetId: 'church_profile', metadata: { scenario, people: people.length, created: fresh.length, updated, removed } });
|
||||
await ctx.settings.set('demo_scenario', JSON.stringify({ scenario, loadedAt: now.toISOString() }));
|
||||
return { scenario, church: profile.name, people: people.length, created: fresh.length, updated, removed };
|
||||
}
|
||||
@@ -23,6 +23,7 @@ import { loginEvent } from '../lib/audit.js';
|
||||
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
|
||||
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
|
||||
import { productName } from '../oidc/clients.js';
|
||||
import { applyKnownOptOut } from '../accounts/whatsapp.js';
|
||||
|
||||
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
|
||||
|
||||
@@ -115,7 +116,7 @@ export async function describe(ctx: Ctx, details: Details, pending: PendingSignI
|
||||
}
|
||||
if (stage === 'setup_two_factor') {
|
||||
// Only the ways that can deliver a code now (1.2.0): an app always works.
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
|
||||
extra.methods = ['totp', ...((await ctx.messenger.emailReady()) ? ['email'] : []), ...((await ctx.messenger.whatsappReady()) && a.phone && !a.whatsappOptedOut ? ['whatsapp'] : [])];
|
||||
extra.why = a.role === 'admin' ? 'admin' : 'product';
|
||||
}
|
||||
if (stage === 'notice') {
|
||||
@@ -177,6 +178,7 @@ export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<str
|
||||
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
|
||||
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
|
||||
await loginEvent(ctx, a.id, 'account_created');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,8 @@ export async function audit(ctx: Ctx, entry: { actorId: string | null; actorRole
|
||||
|
||||
export type LoginEventType =
|
||||
| 'sign_in' | 'sign_in_failed' | 'locked' | 'password_reset' | 'password_changed' | 'two_factor_on' | 'two_factor_off'
|
||||
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created';
|
||||
| 'recovery_code_used' | 'recovery_codes_replaced' | 'signed_out_everywhere' | 'email_changed' | 'account_created'
|
||||
| 'whatsapp_opted_out' | 'whatsapp_opted_in';
|
||||
|
||||
export async function loginEvent(ctx: Ctx, accountId: string | null, type: LoginEventType, req?: Request, extra: { clientId?: string | null; detail?: object } = {}) {
|
||||
try {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import type { Ctx } from '../context.js';
|
||||
|
||||
/** Encrypted at rest; never sent to the browser. */
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks']);
|
||||
export const SECRET_SETTINGS = new Set(['smtp_pass', 'wawp_access_token', 'hub_install_secret', 'hub_private_key', 'oidc_jwks', 'wawp_webhook_secret']);
|
||||
|
||||
/** The settings an admin may read and change through the generic settings API. */
|
||||
export const ADMIN_SETTINGS = new Set([
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
/**
|
||||
* Back-channel calls to linked products (docs/ACCOUNTS-1.0-PLAN.md §6): `crosscode.identity/1`
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, and `church.changed`. Each is a
|
||||
* user.updated / user.deleted / user.export at `ACCOUNTS_CALL_PATH`, `church.changed` and (1.9.0) `messaging.changed`. Each is a
|
||||
* `Delivery`, signed with the link's secret (`LINK_HEADERS`), retried after 1 min, 5 min, 30 min,
|
||||
* 2 h, 12 h, then daily for a week. The reply is kept, and `onReply` acts on it (deletion,
|
||||
* export).
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { ACCOUNTS_CALL_PATH, CHURCH_PATHS, MESSAGING_CHANGED_PATH } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { callSibling, siblingUrl } from './http.js';
|
||||
@@ -14,7 +14,10 @@ import { callSibling, siblingUrl } from './http.js';
|
||||
const RETRY_MS = [60e3, 5 * 60e3, 30 * 60e3, 2 * 3600e3, 12 * 3600e3, ...Array(7).fill(24 * 3600e3)] as number[];
|
||||
export const MAX_ATTEMPTS = RETRY_MS.length + 1;
|
||||
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed';
|
||||
export type CallType = 'user.updated' | 'user.deleted' | 'user.export' | 'church.changed' | 'messaging.changed';
|
||||
|
||||
/** Where each call goes on the product. 1.9.0 adds messaging.changed (only to products that asked for the settings). */
|
||||
const PATHS: Partial<Record<CallType, string>> = { 'church.changed': CHURCH_PATHS.changed, 'messaging.changed': MESSAGING_CHANGED_PATH };
|
||||
|
||||
/** Queues a call to every linked product (or the ones given). Returns the deliveries made. */
|
||||
export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: string) => object, opts: { linkIds?: string[] } = {}) {
|
||||
@@ -23,7 +26,7 @@ export async function queueCall(ctx: Ctx, type: CallType, makeBody: (callId: str
|
||||
for (const link of links) {
|
||||
const callId = crypto.randomUUID();
|
||||
made.push(await ctx.db.delivery.create({
|
||||
data: { linkId: link.installId, callId, type, path: type === 'church.changed' ? CHURCH_PATHS.changed : ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
data: { linkId: link.installId, callId, type, path: PATHS[type] ?? ACCOUNTS_CALL_PATH, body: makeBody(callId) as never, nextAttemptAt: ctx.now() },
|
||||
}));
|
||||
}
|
||||
return made;
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 4): one set of email and WhatsApp settings per church,
|
||||
* kept here (or copied in from Cross Events). Products that asked for them (`messaging.get`, the
|
||||
* Church App) are sent `messaging.changed` when they change, so they fetch them again.
|
||||
*/
|
||||
import { IDENTITY_REQUEST_SCHEMA, type MessagingChanged } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { queueCall } from './deliveries.js';
|
||||
|
||||
/** The settings that make up the church's email and WhatsApp. */
|
||||
const EMAIL_KEYS = new Set(['smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass', 'smtp_from', 'smtp_secure']);
|
||||
const WHATSAPP_KEYS = new Set(['wawp_access_token', 'wawp_instance_id']);
|
||||
|
||||
/** Which parts the changed setting keys touch. */
|
||||
export function messagingParts(keys: string[]): { email: boolean; whatsapp: boolean } {
|
||||
return { email: keys.some((k) => EMAIL_KEYS.has(k)), whatsapp: keys.some((k) => WHATSAPP_KEYS.has(k)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the change and tells every product that asked for the settings, except the one that
|
||||
* made the change (`exceptLinkId`, e.g. Events saving its own into Accounts).
|
||||
*/
|
||||
export async function messagingChanged(ctx: Ctx, parts: { email: boolean; whatsapp: boolean }, exceptLinkId?: string) {
|
||||
if (!parts.email && !parts.whatsapp) return;
|
||||
const at = ctx.now().toISOString();
|
||||
await ctx.settings.set('messaging_updated_at', at);
|
||||
const wanted = await ctx.db.productLink.findMany({ where: { messagingWantedAt: { not: null } } });
|
||||
const linkIds = wanted.map((l) => l.installId).filter((id) => id !== exceptLinkId);
|
||||
if (!linkIds.length) return;
|
||||
await queueCall(ctx, 'messaging.changed', (): MessagingChanged => ({ schema: IDENTITY_REQUEST_SCHEMA, type: 'messaging.changed', occurredAt: at, ...parts }), { linkIds });
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema,
|
||||
type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult,
|
||||
} from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import { LINK_HEADERS, openLinkValue, sealLinkValue, verify } from '@crosscode/contracts/signing';
|
||||
import type { Ctx } from '../context.js';
|
||||
import type { ProductLink } from '../generated/prisma/client.js';
|
||||
import { limit } from '../http.js';
|
||||
@@ -32,6 +32,8 @@ import { turnOff } from '../accounts/twoFactor.js';
|
||||
import { signOutEverywhere } from '../oidc/sessions.js';
|
||||
import { anonymise } from '../privacy/deletion.js';
|
||||
import { ProfileChangedError, ProfileError, updateProfile } from '../church/profile.js';
|
||||
import { applyKnownOptOut, optOutNumber } from '../accounts/whatsapp.js';
|
||||
import { messagingChanged } from './messaging.js';
|
||||
|
||||
/** Products that may change the church profile with church.update (1.7.0, WEBSITE-1.0-PLAN decision 10). */
|
||||
const PROFILE_EDITORS = new Set(['website']);
|
||||
@@ -134,6 +136,7 @@ async function importOne(ctx: Ctx, link: ProductLink, secret: string, p: ImportP
|
||||
for (const c of p.consentChanges) await ctx.db.consentChange.create({ data: { accountId: a.id, channel: c.channel, granted: c.granted, source: 'events_import', createdAt: new Date(c.at) } });
|
||||
await knows(ctx, link.installId, a.id, 'import', { upgrade: true });
|
||||
await loginEvent(ctx, a.id, 'account_created', undefined, { clientId: link.installId, detail: { by: 'import', product: link.product } });
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
}
|
||||
return { id: p.id, outcome: 'created', sub: p.id, reason: null };
|
||||
}
|
||||
@@ -225,6 +228,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
}
|
||||
const a = await ctx.db.account.create({ data: { name: r.name, email, phone: r.phone, passwordHash: null, emailVerified: false } });
|
||||
await knows(ctx, link.installId, a.id, 'ensure');
|
||||
await applyKnownOptOut(ctx, a.id);
|
||||
const token = randomToken();
|
||||
// Only the product's own address: never somewhere else.
|
||||
const returnUrl = new URL(r.returnUrl).origin === new URL(link.url).origin ? r.returnUrl : link.url;
|
||||
@@ -259,7 +263,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
if (Object.keys(data).length) {
|
||||
await ctx.db.account.update({ where: { id: a.id }, data });
|
||||
if (data.email) await loginEvent(ctx, a.id, 'email_changed', req, { clientId: link.installId, detail: { by: 'product' } });
|
||||
await profileChanged(ctx, a.id);
|
||||
if (!(data.phone && (await applyKnownOptOut(ctx, a.id)))) await profileChanged(ctx, a.id);
|
||||
}
|
||||
await logRequest(ctx, link, r, 'person_updated_by_product', a.id, req, { fields: Object.keys(data) });
|
||||
return reply({ ok: true as const });
|
||||
@@ -323,6 +327,20 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
await logRequest(ctx, link, r, 'people_checked_by_product', null, req, { checked: people.length, deleted: count('deleted'), unknown: count('unknown') });
|
||||
return reply({ people });
|
||||
}
|
||||
case 'messaging.get': {
|
||||
// 1.9.0 (APP-1.0-PLAN §8, decision 4): the church's one set of email and WhatsApp settings,
|
||||
// secrets sealed with the link's secret. The product is sent messaging.changed from now on.
|
||||
await ctx.db.productLink.update({ where: { installId: link.installId }, data: { messagingWantedAt: ctx.now() } });
|
||||
const out = await messagingSettings(ctx, secret);
|
||||
await logRequest(ctx, link, r, 'messaging_settings_given', null, req, { email: !!out.email, whatsapp: !!out.whatsapp });
|
||||
return reply(out);
|
||||
}
|
||||
case 'whatsapp.optout': {
|
||||
// 1.9.0 (decision 11): a STOP the product received. Kept here for every product.
|
||||
const accounts = await optOutNumber(ctx, r.phone, { keyword: r.keyword, source: link.product, receivedAt: new Date(r.receivedAt) });
|
||||
await logRequest(ctx, link, r, 'whatsapp_stop_from_product', null, req, { accounts });
|
||||
return reply({ accounts });
|
||||
}
|
||||
case 'church.update': {
|
||||
// The product checked the person's role (Accounts doesn't know the Website's); Accounts
|
||||
// checks it's the Website, that the person signs in through it, and audits it as theirs.
|
||||
@@ -382,6 +400,7 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s
|
||||
whatsapp = { ok: false, error: String((e as Error).message || e).slice(0, 500), saved: false };
|
||||
}
|
||||
}
|
||||
if (save && (email?.saved || whatsapp?.saved)) await messagingChanged(ctx, { email: !!email?.saved, whatsapp: !!whatsapp?.saved }, link.installId);
|
||||
await logRequest(ctx, link, r, save ? 'messaging_set_by_product' : 'messaging_tested_by_product', null, req, { email: email && { ok: email.ok, saved: email.saved }, whatsapp: whatsapp && { ok: whatsapp.ok, saved: whatsapp.saved } });
|
||||
const status = await messagingStatus(ctx);
|
||||
return reply({ email, whatsapp, status: { email: status.email, whatsapp: status.whatsapp } });
|
||||
@@ -419,7 +438,8 @@ export function requestsRouter(ctx: Ctx, provider: Provider) {
|
||||
const out = await handle(ctx, provider, link, secret, request, req);
|
||||
// Checks write nothing, so they needn't be remembered.
|
||||
// people.check (1.5.0) only reads, and its reply holds profiles: never kept.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check';
|
||||
// messaging.get (1.9.0) carries sealed secrets: never kept either.
|
||||
const isCheck = ('check' in request && request.check) || request.type === 'people.check' || request.type === 'messaging.get';
|
||||
if (!isCheck) {
|
||||
await ctx.db.productRequest.create({ data: { requestId: request.requestId, linkId: link.installId, type: request.type, reply: out as never, createdAt: ctx.now() } }).catch(() => {});
|
||||
}
|
||||
@@ -465,6 +485,29 @@ async function messagingStatus(ctx: Ctx) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* messaging.get (1.9.0): what Accounts sends with (its saved settings, else the server's .env),
|
||||
* the password and token sealed with the link's secret. A part that isn't set up is null.
|
||||
*/
|
||||
async function messagingSettings(ctx: Ctx, secret: string) {
|
||||
const s = ctx.settings;
|
||||
const host = (await s.get('smtp_host')) || ctx.config.smtp?.host || null;
|
||||
const port = Number((await s.get('smtp_port')) || ctx.config.smtp?.port || 587);
|
||||
const pass = (await s.get('smtp_pass')) || ctx.config.smtp?.pass || '';
|
||||
const from = (await s.get('smtp_from')) || ctx.config.smtp?.from || '';
|
||||
const email = host && from ? {
|
||||
host, port,
|
||||
secure: (await s.get('smtp_secure')) === 'true' || (ctx.config.smtp?.secure ?? port === 465),
|
||||
user: (await s.get('smtp_user')) || ctx.config.smtp?.user || '',
|
||||
pass: pass ? sealLinkValue(secret, pass) : null,
|
||||
from,
|
||||
} : null;
|
||||
const token = (await s.get('wawp_access_token')) || ctx.config.wawp?.accessToken || null;
|
||||
const instanceId = (await s.get('wawp_instance_id')) || ctx.config.wawp?.instanceId || null;
|
||||
const whatsapp = token && instanceId ? { accessToken: sealLinkValue(secret, token), instanceId } : null;
|
||||
return { email, whatsapp, updatedAt: (await s.get('messaging_updated_at')) || null };
|
||||
}
|
||||
|
||||
/** Old remembered requests (the `cleanup` job). */
|
||||
export async function forgetOldRequests(ctx: Ctx) {
|
||||
return ctx.db.productRequest.deleteMany({ where: { createdAt: { lt: new Date(ctx.now().getTime() - KEEP_REQUESTS_DAYS * 86400e3) } } });
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* 1.9.0 (docs/APP-1.0-PLAN.md §8, decision 11): Accounts takes WAWP's webhook itself, for a church
|
||||
* without Cross Events (a WAWP number sends replies to one address; with Events, Events receives
|
||||
* them and passes a STOP on with `whatsapp.optout`).
|
||||
*
|
||||
* POST /api/v2/webhooks/whatsapp?secret=… (WAWP's `message` event)
|
||||
*
|
||||
* WAWP doesn't sign webhooks, so the address carries a secret only Accounts and WAWP know
|
||||
* (Admin → Email and WhatsApp shows it to paste into WAWP). Always answers 200 quickly, so WAWP
|
||||
* never retries; only a STOP from a phone number is acted on.
|
||||
*/
|
||||
import crypto from 'node:crypto';
|
||||
import express, { type Request, type Response } from 'express';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { isStopKeyword, optOutNumber, phoneFromChatId } from '../accounts/whatsapp.js';
|
||||
|
||||
export const WHATSAPP_WEBHOOK_PATH = '/api/v2/webhooks/whatsapp';
|
||||
|
||||
/** The secret in the webhook's address, made on first use. */
|
||||
async function webhookSecret(ctx: Ctx): Promise<string> {
|
||||
const saved = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (saved) return saved;
|
||||
const secret = crypto.randomBytes(24).toString('base64url');
|
||||
await ctx.settings.set('wawp_webhook_secret', secret);
|
||||
return secret;
|
||||
}
|
||||
|
||||
/** The address to paste into WAWP's webhook settings (event: message), and when it last called. */
|
||||
export async function whatsappWebhookUrl(ctx: Ctx) {
|
||||
return {
|
||||
url: `${ctx.config.publicUrl.replace(/\/$/, '')}${WHATSAPP_WEBHOOK_PATH}?secret=${encodeURIComponent(await webhookSecret(ctx))}`,
|
||||
lastSeenAt: await ctx.settings.get('wawp_webhook_last_seen'),
|
||||
};
|
||||
}
|
||||
|
||||
function secretMatches(given: string, secret: string) {
|
||||
return given.length === secret.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(secret));
|
||||
}
|
||||
|
||||
export async function handleWhatsappWebhook(ctx: Ctx, query: { secret?: unknown }, body: unknown): Promise<'ignored' | 'seen' | 'stopped'> {
|
||||
const secret = await ctx.settings.get('wawp_webhook_secret');
|
||||
if (!secret || !secretMatches(String(query.secret ?? ''), secret)) return 'ignored';
|
||||
await ctx.settings.set('wawp_webhook_last_seen', ctx.now().toISOString());
|
||||
const payload = ((body as { payload?: Record<string, unknown> })?.payload ?? {}) as { fromMe?: boolean; body?: unknown; from?: unknown };
|
||||
if (payload.fromMe || !isStopKeyword(payload.body)) return 'seen';
|
||||
const phone = phoneFromChatId(payload.from);
|
||||
// Groups, channels and senders WhatsApp only names by a "LID" have no number to opt out.
|
||||
if (!phone) return 'seen';
|
||||
await optOutNumber(ctx, phone, { keyword: String(payload.body).trim().toUpperCase().slice(0, 40), source: 'accounts', receivedAt: ctx.now() });
|
||||
// The one message after a STOP: what it did and how to undo it.
|
||||
const church = (await ctx.settings.json<{ name?: string }>('church_profile', {})).name || 'the church';
|
||||
await ctx.messenger.whatsapp({ to: phone, text: `You won't get WhatsApp messages from ${church} any more. To turn them back on, go to ${ctx.config.publicUrl.replace(/\/$/, '')}/account.` })
|
||||
.catch((e: Error) => console.warn('[whatsapp webhook] confirmation not sent:', e.message));
|
||||
return 'stopped';
|
||||
}
|
||||
|
||||
export function whatsappWebhookRouter(ctx: Ctx) {
|
||||
const r = express.Router();
|
||||
r.post(WHATSAPP_WEBHOOK_PATH, express.json({ limit: '256kb' }), async (req: Request, res: Response) => {
|
||||
try {
|
||||
await handleWhatsappWebhook(ctx, req.query as { secret?: unknown }, req.body);
|
||||
} catch (e) {
|
||||
console.error('[whatsapp webhook]', (e as Error).message);
|
||||
}
|
||||
res.json({ ok: true });
|
||||
});
|
||||
return r;
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { requestExport } from '../privacy/export.js';
|
||||
import { requestDeletion } from '../privacy/deletion.js';
|
||||
import { hashToken, randomToken } from '../lib/crypto.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { applyKnownOptOut, optBackIn } from '../accounts/whatsapp.js';
|
||||
|
||||
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
|
||||
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
|
||||
@@ -29,7 +30,9 @@ export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: numbe
|
||||
return {
|
||||
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
|
||||
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
|
||||
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
|
||||
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
|
||||
// 1.9.0: replied STOP to the church's WhatsApp number; turned back on here.
|
||||
whatsappOptedOut: a.whatsappOptedOut, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
|
||||
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
|
||||
};
|
||||
}
|
||||
@@ -80,7 +83,8 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
...(phone ? {} : { newsWhatsApp: false }),
|
||||
},
|
||||
});
|
||||
await profileChanged(ctx, s.account.id);
|
||||
// 1.9.0: a number that replied STOP starts opted out (which tells the products itself).
|
||||
if (!(phone !== s.account.phone && (await applyKnownOptOut(ctx, s.account.id)))) await profileChanged(ctx, s.account.id);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
@@ -175,11 +179,18 @@ export function meRouter(ctx: Ctx, provider: Provider) {
|
||||
|
||||
r.put('/me/news', handle(async (req, res) => {
|
||||
const s = await signedIn(req, res);
|
||||
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
|
||||
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone && !s.account.whatsappOptedOut }, 'account_page');
|
||||
if (changed) await profileChanged(ctx, s.account.id);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
// 1.9.0: WhatsApp back on after a STOP (every product may send it again; news stays off until chosen).
|
||||
r.post('/me/whatsapp-on', handle(async (req, res) => {
|
||||
const s = await signedIn(req, res);
|
||||
await optBackIn(ctx, s.account);
|
||||
return view(s);
|
||||
}));
|
||||
|
||||
r.get('/me/notice', handle(async (req, res) => {
|
||||
await signedIn(req, res);
|
||||
const n = await currentNotice(ctx);
|
||||
|
||||
@@ -27,7 +27,7 @@ async function ownPart(ctx: Ctx, accountId: string) {
|
||||
return {
|
||||
product: 'accounts',
|
||||
sections: [
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, whatsappOptedOut: a.whatsappOptedOut, whatsappOptedOutAt: a.whatsappOptedOutAt, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
|
||||
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
|
||||
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
|
||||
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
|
||||
|
||||
@@ -10,6 +10,7 @@ import { branding, church } from '../church/profile.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
|
||||
import { setupNeeded } from '../setup/routes.js';
|
||||
import { currentNotice } from '../privacy/notice.js';
|
||||
import { DEMO_ASSETS_PATH, demoAsset } from '../demo/scenario.js';
|
||||
|
||||
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||
|
||||
@@ -31,6 +32,14 @@ export function publicRouter(ctx: Ctx) {
|
||||
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||
}));
|
||||
|
||||
// 1.9.0: a demo scenario's logo and icon (drawn for the demo), which its church profile points at.
|
||||
r.get(`${strip(DEMO_ASSETS_PATH)}/:scenario/:file`, limit(600), (req, res) => {
|
||||
const svg = demoAsset(String(req.params.scenario), String(req.params.file));
|
||||
if (!svg) return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'There is no such demo image.' } });
|
||||
res.set({ 'Content-Type': 'image/svg+xml', 'Cache-Control': 'public, max-age=3600', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
|
||||
return res.send(svg);
|
||||
});
|
||||
|
||||
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
|
||||
res.set('Cache-Control', 'public, max-age=60');
|
||||
return church(ctx);
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Accounts 1.9.0: a demo scenario's church and people (docs/APP-1.0-PLAN.md §12, "Demo scenarios").
|
||||
import assert from 'node:assert/strict';
|
||||
import { after, before, describe, test } from 'node:test';
|
||||
import { CHURCH_PATHS, churchSchema } from '@crosscode/contracts';
|
||||
import { demoPeople } from '@crosscode/demo';
|
||||
import { startHarness, type Harness } from './support/harness.js';
|
||||
import { loadScenario } from '../src/demo/scenario.js';
|
||||
import { church } from '../src/church/profile.js';
|
||||
import { verifyPassword } from '../src/lib/passwords.js';
|
||||
|
||||
let h: Harness;
|
||||
before(async () => { h = await startHarness(); });
|
||||
after(async () => { await h.close(); });
|
||||
|
||||
const live = async () => h.db.account.findMany({ where: { status: { not: 'deleted' } } });
|
||||
|
||||
describe('loading a demo scenario', () => {
|
||||
test('the church becomes the scenario\'s, with its own logo and icon, and the products are told', async () => {
|
||||
const real = await h.makeAccount({ email: 'office@hope.test' });
|
||||
const admin = await h.makeAccount({ email: 'admin.demo@example.com', role: 'admin' });
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.church, 'Acacia Hill Church');
|
||||
const c = await church(h.ctx);
|
||||
assert.ok(churchSchema.safeParse(c).success);
|
||||
assert.equal(c.name, 'Acacia Hill Church');
|
||||
assert.equal(c.shortName, 'Acacia Hill');
|
||||
assert.equal(c.branding.colours.primary, '#2f6f4f');
|
||||
assert.deepEqual(c.branding.style, { fontPairing: 'warm', corners: 'soft' });
|
||||
assert.equal(c.branding.logoUrl, `${h.publicUrl}/api/demo-assets/community-family/logo.svg`);
|
||||
assert.equal(c.contact.email, 'office.acaciahill@example.com');
|
||||
assert.ok((await h.db.delivery.findMany({ where: { type: 'church.changed' } })).length >= 1);
|
||||
// Real people and admins are never touched.
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: real.id } }))!.status, 'active');
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: admin.id } }))!.status, 'active');
|
||||
});
|
||||
|
||||
test('every person has an account with the id the other products work out, and the demo password', async () => {
|
||||
const people = demoPeople('community-family');
|
||||
const ids = new Set((await live()).map((a) => a.id));
|
||||
for (const p of people) assert.ok(ids.has(p.id), p.email);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: people[0]!.id } }))!;
|
||||
assert.equal(pastor.name, 'Thabo Nkosi');
|
||||
assert.equal(pastor.emailVerified, true);
|
||||
assert.ok(await verifyPassword('Demo@1234', pastor.passwordHash as string));
|
||||
});
|
||||
|
||||
test('loading it again changes nobody\'s id', async () => {
|
||||
const r = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(r.created, 0);
|
||||
assert.equal(r.removed, 0);
|
||||
assert.equal(r.updated, demoPeople('community-family').length);
|
||||
});
|
||||
|
||||
test('another scenario replaces the demo people; switching back brings them back with the same ids', async () => {
|
||||
const before = demoPeople('community-family');
|
||||
const r = await loadScenario(h.ctx, 'bold-plant');
|
||||
assert.equal(r.church, 'Harbour City Church');
|
||||
assert.equal(r.removed, before.length);
|
||||
assert.equal(r.created, demoPeople('bold-plant').length);
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: before[0]!.id } }))!.status, 'deleted');
|
||||
assert.ok(await h.db.account.findUnique({ where: { email: 'office@hope.test' } }), 'a real person stays');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'admin.demo@example.com' } }))!.status, 'active', 'an admin stays');
|
||||
|
||||
const back = await loadScenario(h.ctx, 'community-family');
|
||||
assert.equal(back.updated, before.length);
|
||||
const pastor = (await h.db.account.findUnique({ where: { id: before[0]!.id } }))!;
|
||||
assert.equal(pastor.status, 'active');
|
||||
assert.equal(pastor.email, before[0]!.email);
|
||||
});
|
||||
|
||||
test('a scenario with campuses has them in the profile', async () => {
|
||||
await h.ctx.settings.set('church_profile', JSON.stringify({ name: 'Hope Family Church' }));
|
||||
// Riverside has about 2 450 people; only its profile is checked here.
|
||||
const c = await (async () => { await loadScenario(h.ctx, 'clean-campus'); return church(h.ctx); })();
|
||||
assert.deepEqual(c.campuses.map((x) => x.slug), ['stellenbosch', 'paarl', 'somerset-west']);
|
||||
assert.equal(c.serviceTimes.filter((s) => s.campus === 'stellenbosch').length, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('demo logos', () => {
|
||||
test('served as SVG for a scenario, 404 for anything else', async () => {
|
||||
const res = await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/icon.svg`);
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.headers.get('content-type'), 'image/svg+xml; charset=utf-8');
|
||||
assert.match(await res.text(), /^<svg[^>]*>.*#e4572e/);
|
||||
const logo = await (await fetch(`${h.publicUrl}/api/demo-assets/heritage-parish/logo.svg`)).text();
|
||||
assert.match(logo, /St Columba's Church/);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/nowhere/icon.svg`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}/api/demo-assets/bold-youth/secrets.txt`)).status, 404);
|
||||
assert.equal((await fetch(`${h.publicUrl}${CHURCH_PATHS.profile}`)).status, 200);
|
||||
});
|
||||
});
|
||||
@@ -12,7 +12,7 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
account: () => ({
|
||||
givenName: null, familyName: null, emailVerified: false, phone: null, phoneVerified: false, passwordHash: null, role: 'member', status: 'active',
|
||||
twoFactorMethod: null, totpSecret: null, totpLastStep: null, newsEmail: false, newsWhatsApp: false, newsAskedAt: null, noticeVersionAccepted: 0,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false,
|
||||
failedSignIns: 0, lockedUntil: null, lastSignInAt: null, deactivatedAt: null, anonymisedAt: null, recoveryCodesNeeded: false, whatsappOptedOut: false, whatsappOptedOutAt: null,
|
||||
}),
|
||||
recoveryCode: () => ({ usedAt: null }),
|
||||
pendingSignIn: () => ({ accountId: null, codeHash: null, codeSentAt: null, attempts: 0, amr: [], pendingTotpSecret: null, remember: false }),
|
||||
@@ -20,13 +20,13 @@ const DEFAULTS: Record<string, () => Row> = {
|
||||
loginEvent: () => ({ accountId: null, clientId: null, ip: null, userAgent: null, detail: null }),
|
||||
privacyNotice: () => ({ publishedById: null }),
|
||||
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null }),
|
||||
productLink: () => ({ connectedById: null, importStartedAt: null, messagingWantedAt: null }),
|
||||
oidcPayload: () => ({ grantId: null, userCode: null, uid: null, accountId: null, expiresAt: null, consumedAt: null }),
|
||||
delivery: () => ({ status: 'pending', attempts: 0, lastError: null, reply: null, deliveredAt: null }),
|
||||
dataExport: () => ({ status: 'collecting', parts: {}, file: null, readyAt: null }),
|
||||
deletionRequest: () => ({ status: 'waiting_approval', approvedAt: null, approvedById: null, products: {}, completedAt: null }),
|
||||
};
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId' };
|
||||
const KEYS: Record<string, string> = { appSetting: 'key', productLink: 'installId', linkNonce: 'nonce', pendingSignIn: 'uid', privacyNotice: 'version', productRequest: 'requestId', whatsAppOptOut: 'phone' };
|
||||
const UNIQUE: Record<string, string[]> = { account: ['email'], recoveryCode: ['codeHash'], emailToken: ['tokenHash'], delivery: ['callId'] };
|
||||
const HAS_UPDATED_AT = new Set(['account', 'appSetting', 'productLink']);
|
||||
|
||||
@@ -117,6 +117,10 @@ function model(name: string, tables: Map<string, Map<unknown, Row>>) {
|
||||
table().set(row[key], row);
|
||||
return clone(row);
|
||||
},
|
||||
createMany: async ({ data }: { data: Row[] }) => {
|
||||
for (const d of data) await api.create({ data: d });
|
||||
return { count: data.length };
|
||||
},
|
||||
update: async ({ where, data }: { where: Row; data: Row }) => {
|
||||
const r = findWhere(where);
|
||||
if (!r) throw prismaError('P2025', `Record to update not found (${name})`);
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
// Accounts 1.9.0 (docs/APP-1.0-PLAN.md §8): the church's email and WhatsApp settings for a product
|
||||
// that sends with them (messaging.get, messaging.changed), and the WhatsApp opt-out for every
|
||||
// product (whatsapp.optout, Accounts' own WAWP webhook, turning WhatsApp back on).
|
||||
import assert from 'node:assert/strict';
|
||||
import crypto from 'node:crypto';
|
||||
import { after, before, beforeEach, describe, test } from 'node:test';
|
||||
import { ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, MESSAGING_CHANGED_PATH, messagingChangedSchema, messagingGetReplySchema, userUpdatedSchema } from '@crosscode/contracts';
|
||||
import { LINK_HEADERS, openLinkValue, signedHeaders } from '@crosscode/contracts/signing';
|
||||
import { Browser, PRODUCT_ID, startHarness, type Harness } from './support/harness.js';
|
||||
import type { MemoryMessenger } from '../src/lib/messages.js';
|
||||
import { runDue } from '../src/links/deliveries.js';
|
||||
import { messagingChanged } from '../src/links/messaging.js';
|
||||
import { handleWhatsappWebhook, whatsappWebhookUrl } from '../src/links/whatsappWebhook.js';
|
||||
import { isStopKeyword, phoneFromChatId } from '../src/accounts/whatsapp.js';
|
||||
|
||||
let h: Harness;
|
||||
let messenger: MemoryMessenger;
|
||||
|
||||
before(async () => { h = await startHarness(); messenger = h.messenger as MemoryMessenger; });
|
||||
after(async () => { await h.close(); });
|
||||
beforeEach(async () => {
|
||||
h.received.length = 0;
|
||||
messenger.whatsappOn = true;
|
||||
messenger.whatsapps.length = 0;
|
||||
await h.db.delivery.deleteMany({});
|
||||
});
|
||||
|
||||
/** A request from the harness's linked product (signed with its link's secret). */
|
||||
async function ask(body: Record<string, unknown>) {
|
||||
const raw = JSON.stringify({ schema: IDENTITY_REQUEST_SCHEMA, requestId: crypto.randomUUID(), actor: null, ...body });
|
||||
const res = await fetch(`${h.publicUrl}${ACCOUNTS_REQUEST_PATH}`, { method: 'POST', body: raw, headers: { 'content-type': 'application/json', ...signedHeaders(LINK_HEADERS, { senderId: PRODUCT_ID, secret: h.linkSecret, rawBody: raw }) } });
|
||||
return { status: res.status, body: (await res.json()) as Record<string, unknown> };
|
||||
}
|
||||
|
||||
const sent = (path: string) => h.received.filter((r) => r.path === path).map((r) => JSON.parse(r.body) as Record<string, unknown>);
|
||||
|
||||
describe('messaging.get', () => {
|
||||
test('nothing set up: both parts null', async () => {
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.ok(messagingGetReplySchema.safeParse(r.body).success);
|
||||
assert.equal(r.body.email, null);
|
||||
assert.equal(r.body.whatsapp, null);
|
||||
});
|
||||
|
||||
test('gives the settings with the password and token sealed for this link only, and never keeps the reply', async () => {
|
||||
await h.ctx.settings.setMany({ smtp_host: 'smtp.hope.test', smtp_port: '587', smtp_user: 'hello@hope.test', smtp_pass: 'mail-pass', smtp_from: 'hello@hope.test', wawp_access_token: 'wa-token', wawp_instance_id: 'HOPE01' });
|
||||
const r = await ask({ type: 'messaging.get' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
const reply = messagingGetReplySchema.parse(r.body);
|
||||
assert.equal(reply.email?.host, 'smtp.hope.test');
|
||||
assert.equal(reply.email?.user, 'hello@hope.test');
|
||||
assert.notEqual(reply.email?.pass, 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.email!.pass!), 'mail-pass');
|
||||
assert.equal(openLinkValue(h.linkSecret, reply.whatsapp!.accessToken), 'wa-token');
|
||||
assert.equal(reply.whatsapp?.instanceId, 'HOPE01');
|
||||
assert.doesNotMatch(JSON.stringify(r.body), /mail-pass|wa-token/);
|
||||
const link = await h.db.productLink.findUnique({ where: { installId: PRODUCT_ID } });
|
||||
assert.ok(link?.messagingWantedAt, 'remembered as wanting messaging.changed');
|
||||
assert.equal((await h.db.productRequest.findMany({ where: { type: 'messaging.get' } })).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('messaging.changed', () => {
|
||||
test('an admin changing WhatsApp tells the products that asked', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
const calls = sent(MESSAGING_CHANGED_PATH);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.ok(messagingChangedSchema.safeParse(calls[0]).success);
|
||||
assert.equal(calls[0]!.whatsapp, true);
|
||||
assert.equal(calls[0]!.email, false);
|
||||
assert.ok(h.received.find((x) => x.path === MESSAGING_CHANGED_PATH && h.signedByLink(x)), 'signed with the link');
|
||||
assert.ok(await h.ctx.settings.get('messaging_updated_at'));
|
||||
});
|
||||
|
||||
test('not to the product that made the change, nor for unrelated settings', async () => {
|
||||
await ask({ type: 'messaging.get' });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: false }, PRODUCT_ID);
|
||||
await messagingChanged(h.ctx, { email: false, whatsapp: false });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
|
||||
test('a product that never asked isn\'t told', async () => {
|
||||
await h.db.productLink.update({ where: { installId: PRODUCT_ID }, data: { messagingWantedAt: null } });
|
||||
await messagingChanged(h.ctx, { email: true, whatsapp: true });
|
||||
await runDue(h.ctx);
|
||||
assert.equal(sent(MESSAGING_CHANGED_PATH).length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('whatsapp.optout', () => {
|
||||
test('opts out every account with the number, turns WhatsApp news off and tells the products', async () => {
|
||||
const a = await h.makeAccount({ email: 'stop1@hope.test', phone: '+27825550001', phoneVerified: true, newsWhatsApp: true });
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550001', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.status, 200, JSON.stringify(r.body));
|
||||
assert.equal(r.body.accounts, 1);
|
||||
const after = (await h.db.account.findUnique({ where: { id: a.id } }))!;
|
||||
assert.equal(after.whatsappOptedOut, true);
|
||||
assert.equal(after.newsWhatsApp, false);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).find((b) => b.type === 'user.updated' && b.sub === a.id);
|
||||
assert.ok(updated, 'user.updated sent');
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, true);
|
||||
});
|
||||
|
||||
test('keeps a number without an account: an account made with it later starts opted out', async () => {
|
||||
const r = await ask({ type: 'whatsapp.optout', phone: '+27825550002', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
assert.equal(r.body.accounts, 0);
|
||||
const ensured = await ask({ type: 'people.ensure', name: 'Later Person', email: 'later@hope.test', phone: '+27825550002', returnUrl: `${h.productUrl}/` });
|
||||
assert.equal(ensured.status, 200, JSON.stringify(ensured.body));
|
||||
const a = (await h.db.account.findUnique({ where: { id: ensured.body.sub as string } }))!;
|
||||
assert.equal(a.whatsappOptedOut, true);
|
||||
});
|
||||
|
||||
test('a code for someone who replied STOP goes by email, never WhatsApp', async () => {
|
||||
await h.makeAccount({ email: 'stop3@hope.test', password: 'Correct-horse-1', phone: '+27825550003', twoFactorMethod: 'whatsapp', whatsappOptedOut: true });
|
||||
const r = await h.signIn(new Browser(), 'stop3@hope.test', 'Correct-horse-1');
|
||||
assert.ok('pending' in r);
|
||||
assert.equal(r.pending.stage, 'two_factor');
|
||||
assert.match(String(r.pending.sentTo), /@hope\.test$/);
|
||||
assert.equal(messenger.whatsapps.filter((w) => w.to === '+27825550003').length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Accounts\' own WAWP webhook', () => {
|
||||
const message = (from: string, body: string, fromMe = false) => ({ event: 'message', payload: { from, body, fromMe } });
|
||||
|
||||
test('reads STOP and phone numbers as Cross Events does', () => {
|
||||
for (const s of ['STOP', ' stop ', 'Stop!', 'unsubscribe', 'STOPP', 'opt out']) assert.ok(isStopKeyword(s), s);
|
||||
for (const s of ['stop the music', 'please stop', '', 'STOPPED']) assert.ok(!isStopKeyword(s), s);
|
||||
assert.equal(phoneFromChatId('27825550004@c.us'), '+27825550004');
|
||||
assert.equal(phoneFromChatId('1234567890-123@g.us'), null);
|
||||
assert.equal(phoneFromChatId('12345@lid'), null);
|
||||
});
|
||||
|
||||
test('ignores a call without the secret', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
assert.match(url, /\/api\/v2\/webhooks\/whatsapp\?secret=/);
|
||||
await h.makeAccount({ email: 'stop4@hope.test', phone: '+27825550004' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret: 'wrong' }, message('27825550004@c.us', 'STOP')), 'ignored');
|
||||
const res = await fetch(`${h.publicUrl}/api/v2/webhooks/whatsapp`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550004@c.us', 'STOP')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop4@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
|
||||
test('a STOP through the real address opts the number out and answers once', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
await h.makeAccount({ email: 'stop5@hope.test', phone: '+27825550005' });
|
||||
const path = url.slice(url.indexOf('/api/'));
|
||||
const res = await fetch(`${h.publicUrl}${path}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(message('27825550005@c.us', 'Stop')) });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop5@hope.test' } }))!.whatsappOptedOut, true);
|
||||
assert.ok(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550005' } }));
|
||||
const replies = messenger.whatsapps.filter((w) => w.to === '+27825550005');
|
||||
assert.equal(replies.length, 1);
|
||||
assert.match(replies[0]!.text, /won't get WhatsApp messages from Hope Family Church/);
|
||||
assert.ok((await whatsappWebhookUrl(h.ctx)).lastSeenAt);
|
||||
});
|
||||
|
||||
test('other messages, and the church\'s own, change nothing', async () => {
|
||||
const { url } = await whatsappWebhookUrl(h.ctx);
|
||||
const secret = new URL(url).searchParams.get('secret');
|
||||
await h.makeAccount({ email: 'stop6@hope.test', phone: '+27825550006' });
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'Thanks!')), 'seen');
|
||||
assert.equal(await handleWhatsappWebhook(h.ctx, { secret }, message('27825550006@c.us', 'STOP', true)), 'seen');
|
||||
assert.equal((await h.db.account.findUnique({ where: { email: 'stop6@hope.test' } }))!.whatsappOptedOut, false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('turning WhatsApp back on', () => {
|
||||
test('on the account page: every product may send it again, and the number\'s STOP is forgotten', async () => {
|
||||
await ask({ type: 'whatsapp.optout', phone: '+27825550007', receivedAt: new Date().toISOString(), keyword: 'STOP' });
|
||||
const a = await h.makeAccount({ email: 'stop7@hope.test', password: 'Correct-horse-1', phone: '+27825550007', whatsappOptedOut: true, whatsappOptedOutAt: new Date() });
|
||||
const browser = new Browser();
|
||||
const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin');
|
||||
const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'stop7@hope.test', password: 'Correct-horse-1' });
|
||||
assert.equal(step.body.stage, 'done', JSON.stringify(step.body));
|
||||
await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account');
|
||||
const me = await h.api(browser, 'GET', '/api/v2/me');
|
||||
assert.equal(me.body.whatsappOptedOut, true);
|
||||
// News on WhatsApp can't be ticked while it's off.
|
||||
await h.api(browser, 'PUT', '/api/v2/me/news', { email: false, whatsapp: true });
|
||||
assert.equal((await h.db.account.findUnique({ where: { id: a.id } }))!.newsWhatsApp, false);
|
||||
const on = await h.api(browser, 'POST', '/api/v2/me/whatsapp-on');
|
||||
assert.equal(on.status, 200, JSON.stringify(on.body));
|
||||
assert.equal(on.body.whatsappOptedOut, false);
|
||||
assert.equal(await h.db.whatsAppOptOut.findUnique({ where: { phone: '+27825550007' } }), null);
|
||||
await runDue(h.ctx);
|
||||
const updated = h.received.map((x) => JSON.parse(x.body) as Record<string, unknown>).filter((b) => b.type === 'user.updated' && b.sub === a.id).at(-1);
|
||||
assert.equal(userUpdatedSchema.parse(updated).profile.whatsapp_opted_out, false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"private": true,
|
||||
"description": "Cross Code Accounts: the church's sign-in pages, the account page and admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -14,6 +14,7 @@ import { useExternalEffect } from "@/lib/hooks";
|
||||
type Me = {
|
||||
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
|
||||
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
|
||||
whatsappOptedOut?: boolean;
|
||||
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
|
||||
};
|
||||
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
|
||||
@@ -24,6 +25,7 @@ const EVENT: Record<string, string> = {
|
||||
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
|
||||
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
|
||||
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
|
||||
whatsapp_opted_out: "WhatsApp turned off (replied STOP)", whatsapp_opted_in: "WhatsApp turned back on",
|
||||
};
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
@@ -291,8 +293,17 @@ function Privacy({ me, onDone, onFail }: Props) {
|
||||
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
|
||||
}}>
|
||||
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone || me.whatsappOptedOut} hint={!me.phone ? "Add your mobile number first." : me.whatsappOptedOut ? "WhatsApp is off: see below." : undefined} />
|
||||
</form>
|
||||
{me.whatsappOptedOut && (
|
||||
<div className="mb-4 rounded border border-amber-300 bg-amber-50 p-3 text-sm">
|
||||
<p className="mb-2">You replied STOP to the church's WhatsApp number, so none of the church's sites send you WhatsApp messages (reminders and codes come by email instead).</p>
|
||||
<Button variant="secondary" onClick={async () => {
|
||||
const r = await call("POST", "/me/whatsapp-on");
|
||||
if (r.ok) onDone("WhatsApp is back on. Church news on WhatsApp stays off until you tick it."); else onFail(r.error.message);
|
||||
}}>Turn WhatsApp back on</Button>
|
||||
</div>
|
||||
)}
|
||||
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
|
||||
@@ -71,6 +71,7 @@ export function Admin({ section = "people" }: { section?: AdminSection }) {
|
||||
{section === "messages" && <>
|
||||
<Settings flash={flash} title="Email" icon={<Mail className="h-4 w-4" />} sub="The server Accounts sends email through (SMTP): sign-in codes, password links, security notices. Leave it empty to use the server's .env." keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure"]} />
|
||||
<Settings flash={flash} title="WhatsApp" icon={<MessageCircle className="h-4 w-4" />} sub="Optional: sign-in codes and notices on WhatsApp, through WAWP." keys={["wawp_access_token", "wawp_instance_id"]} />
|
||||
<WhatsAppReplies />
|
||||
</>}
|
||||
{section === "notice" && <NoticeTab flash={flash} />}
|
||||
{section === "backups" && <Backups flash={flash} />}
|
||||
@@ -446,6 +447,29 @@ function Settings({ flash, keys, title, icon, sub }: { flash: Flash; keys: strin
|
||||
);
|
||||
}
|
||||
|
||||
/** 1.9.0: where WAWP sends replies, so a STOP reaches Accounts (only needed without Cross Events). */
|
||||
function WhatsAppReplies() {
|
||||
const [data, setData] = useState<{ url: string; lastSeenAt: string | null; eventsLinked: boolean } | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<{ url: string; lastSeenAt: string | null; eventsLinked: boolean }>("GET", "/admin/settings/whatsapp-webhook").then((r) => { if (alive && r.ok) setData(r.data); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
if (!data) return null;
|
||||
return (
|
||||
<Card>
|
||||
<Heading icon={<MessageCircle className="h-4 w-4" />} sub="Someone who replies STOP to the church's WhatsApp number gets no WhatsApp from any of the church's sites until they turn it back on on their account page.">WhatsApp replies (STOP)</Heading>
|
||||
{data.eventsLinked
|
||||
? <p className="text-sm text-gray-600">Cross Events receives the replies and passes a STOP on to Accounts. Keep WAWP's webhook pointing at Cross Events.</p>
|
||||
: <>
|
||||
<p className="mb-2 text-sm text-gray-600">In WAWP, set the webhook (event: message) to this address:</p>
|
||||
<input readOnly className="mb-2 w-full rounded border bg-gray-50 px-2 py-1 font-mono text-xs" value={data.url} onFocus={(e) => e.currentTarget.select()} aria-label="Webhook address" />
|
||||
<p className="text-sm text-gray-600">{data.lastSeenAt ? `Last message received: ${new Date(data.lastSeenAt).toLocaleString("en-ZA")}.` : "No message received through it yet."}</p>
|
||||
</>}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
|
||||
|
||||
type NoticeVersion = { version: number; title: string; body: string };
|
||||
|
||||
@@ -1,5 +1,45 @@
|
||||
# Changelog — Church Website
|
||||
|
||||
## [1.7.1] — 2026-11-28
|
||||
|
||||
One migration (`20261128000000_photo_framing`: a nullable `framing` column on `Ministry`,
|
||||
`Leader` and `SimpleEvent`), run by `crosscode deploy`. No new environment settings.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Move and zoom everywhere a photo is framed, not only in page sections.** 1.7.0 had it in the
|
||||
page editor only. Ministries, Leadership and Events now have the same **Move and zoom** on their
|
||||
photo, shown in the frame the site uses for the current template and layouts (`frameFor` types
|
||||
`ministry`, `leader`, `event`; `RowFraming` in `admin/framing.tsx`). It's saved with the row as
|
||||
`framing` (`{ x, y, zoom }`, null for centred) and cleared when the photo is removed or changed.
|
||||
Ministries and leaders are drafts until Publish (in the snapshot, Discard and Restore, as
|
||||
`image.focus` / `photo.focus`); an event's shows once the event is published, like the rest of
|
||||
it. Versions published before this compare unchanged (no framing key), so nothing shows as a
|
||||
pending change after the update.
|
||||
|
||||
## [1.7.0] — 2026-11-27
|
||||
|
||||
No migration, no new environment settings.
|
||||
|
||||
### Added
|
||||
|
||||
- **Move and zoom a photo in its frame.** In a section's form (the top of the page, Welcome,
|
||||
Invitation, Image and text), a chosen photo shows in the shape of the frame the site puts it in
|
||||
for the current template and layout (`admin/framing.tsx`, `frameFor`), with **Move and zoom**:
|
||||
drag (or arrow keys) to choose what stays in view, zoom up to 300% to crop closer, Reset. It's
|
||||
saved with the section as `data.framing` (by media id: `{ x, y, zoom }`), so it's a draft
|
||||
like any other edit: the live preview shows it on Save, visitors after Publish. The site draws it
|
||||
with `object-position` and `scale()` around the same point (`focusStyle` in `site/parts.tsx`);
|
||||
the Bold split and collage frames now clip (`overflow-hidden`), and a zoomed photo in a
|
||||
Heritage frame stays inside its mat. Framing for a photo the section no longer shows is dropped
|
||||
when it's saved.
|
||||
- **Delete photos from the media library.** Each photo says where it's used (draft pages and
|
||||
their sections, ministries, leaders, series, events, the site icon, the live site, the church's
|
||||
logo); one used nowhere has **Delete** (Editors and up), which removes the row and its files
|
||||
(the photo and its responsive sizes, never outside the uploads folder) and frees the storage.
|
||||
`DELETE /api/v1/admin/media/:id` refuses one in use (409 `IN_USE`, saying where); audited as
|
||||
`media_deleted`.
|
||||
|
||||
## [1.6.1] — 2026-11-27
|
||||
|
||||
No migration, no new environment settings.
|
||||
|
||||
@@ -3,6 +3,22 @@
|
||||
What each version changes for the church, in plain language (read by the Hub like Cross Events'
|
||||
WHATS-NEW.md; a section shows once its version is tagged).
|
||||
|
||||
## 1.7.1
|
||||
|
||||
- **Move and zoom now works for ministries, your team and events too**, not only for page
|
||||
sections. Edit a ministry, a person or an event, and press **Move and zoom** on its photo.
|
||||
Ministries and people show it on your site once you publish; an event shows it once the event
|
||||
is published.
|
||||
|
||||
## 1.7.0
|
||||
|
||||
- **Move and zoom your photos.** When you choose a photo for a section, you now see it in the
|
||||
shape it has on your site. Press **Move and zoom** to drag it so the right part shows (faces,
|
||||
not the ceiling) and zoom in to crop closer. Save, and the preview shows it; publish, and
|
||||
visitors see it.
|
||||
- **Delete photos you don't need.** In the **Media library**, each photo says where it's used.
|
||||
Photos that aren't used anywhere have a **Delete** button, which frees up their storage.
|
||||
|
||||
## 1.6.1
|
||||
|
||||
- **The link to your Cross Events site is easier to tell apart** in your website's menu: it now
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.1",
|
||||
"description": "Church Website: the public site's content API, the admin API, publishing and uploads",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
-- Move and zoom for ministries', leaders' and events' photos (Website 1.7.1).
|
||||
ALTER TABLE "Ministry" ADD COLUMN "framing" JSONB;
|
||||
ALTER TABLE "Leader" ADD COLUMN "framing" JSONB;
|
||||
ALTER TABLE "SimpleEvent" ADD COLUMN "framing" JSONB;
|
||||
@@ -104,6 +104,8 @@ model Ministry {
|
||||
summary String?
|
||||
body String?
|
||||
imageId String?
|
||||
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
|
||||
framing Json?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -117,6 +119,8 @@ model Leader {
|
||||
role String?
|
||||
bio String?
|
||||
photoId String?
|
||||
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
|
||||
framing Json?
|
||||
position Int @default(0)
|
||||
archivedAt DateTime?
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -170,6 +174,8 @@ model SimpleEvent {
|
||||
location String?
|
||||
description String?
|
||||
imageId String?
|
||||
/// How the photo sits in its frame on the site: { x, y, zoom } (Move and zoom); null is centred.
|
||||
framing Json?
|
||||
link String?
|
||||
/// A ministry's event: its Ministry leader can add and edit it; an Editor publishes it (§10).
|
||||
ministryId String?
|
||||
|
||||
@@ -9,13 +9,17 @@
|
||||
import { z } from 'zod';
|
||||
import { websiteTemplateSchema } from '@crosscode/contracts';
|
||||
import type { Ctx } from '../context.js';
|
||||
import { Prisma } from '../generated/prisma/client.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { BLOCK_SCHEMAS, isBlockType, SECTION_SCHEMAS } from '../site/sections.js';
|
||||
import { BLOCK_SCHEMAS, isBlockType, rowFraming, SECTION_SCHEMAS } from '../site/sections.js';
|
||||
import { cleanDesign } from '../site/snapshot.js';
|
||||
import { BUTTONS, IMAGE_TREATMENTS, isVariant, SECTION_COLOURS, SECTION_TYPES, sectionTypeSchema, SPACINGS, switchTemplate, TEMPLATE_HEADERS, type SectionType } from '../site/variants.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
/** A row's photo framing to save: kept only while it has a photo (a new photo starts centred). */
|
||||
export const framingFor = (photo: string | null, f: { x: number; y: number; zoom: number } | null) => (photo && f ? f : Prisma.DbNull);
|
||||
|
||||
/** zod issues as `{ field: message }`, for the form. */
|
||||
function fieldsOf(e: z.ZodError): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
@@ -231,6 +235,7 @@ const ministrySchema = z.object({
|
||||
summary: z.string().trim().max(300).nullable().default(null),
|
||||
body: z.string().trim().max(8000).nullable().default(null),
|
||||
imageId: z.string().uuid().nullable().default(null),
|
||||
framing: rowFraming,
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
@@ -239,6 +244,7 @@ const leaderSchema = z.object({
|
||||
role: z.string().trim().max(120).nullable().default(null),
|
||||
bio: z.string().trim().max(4000).nullable().default(null),
|
||||
photoId: z.string().uuid().nullable().default(null),
|
||||
framing: rowFraming,
|
||||
position: z.int().min(0).max(1000).optional(),
|
||||
});
|
||||
|
||||
@@ -253,7 +259,7 @@ export async function saveMinistry(ctx: Ctx, id: string | null, body: unknown, b
|
||||
const slug = m.slug ?? slugify(m.name);
|
||||
const clash = await ctx.db.ministry.findFirst({ where: { slug, ...(id ? { NOT: { id } } : {}) } });
|
||||
if (clash) throw new ApiError(409, 'SLUG_TAKEN', 'Another ministry already has that name.', { name: 'Another ministry has it' });
|
||||
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
|
||||
const data = { name: m.name, slug, summary: m.summary, body: m.body, imageId: m.imageId, framing: framingFor(m.imageId, m.framing), ...(m.position !== undefined ? { position: m.position } : {}), updatedBy: by.id };
|
||||
if (id) {
|
||||
const row = await ctx.db.ministry.findUnique({ where: { id } });
|
||||
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That ministry doesn\'t exist.');
|
||||
@@ -274,7 +280,7 @@ export async function listLeaders(ctx: Ctx) {
|
||||
|
||||
export async function saveLeader(ctx: Ctx, id: string | null, body: unknown, by: Who) {
|
||||
const l = check(leaderSchema, body);
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, framing: framingFor(l.photoId, l.framing), ...(l.position !== undefined ? { position: l.position } : {}), updatedBy: by.id };
|
||||
if (id) {
|
||||
const row = await ctx.db.leader.findUnique({ where: { id } });
|
||||
if (!row || row.archivedAt) throw new ApiError(404, 'NOT_FOUND', 'That person isn\'t on the team.');
|
||||
|
||||
@@ -9,10 +9,11 @@ import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { youtubeId, spotifyEmbed, messageThumbnail } from '../site/content.js';
|
||||
import { rowFraming } from '../site/sections.js';
|
||||
import { mediaUrl } from '../site/snapshot.js';
|
||||
import { getSource, setSource, syncYoutube, uniqueSlug } from '../site/youtube.js';
|
||||
import { markRemoved, notifyLinks } from '../feed/feed.js';
|
||||
import { notChangedSince } from './content.js';
|
||||
import { framingFor, notChangedSince } from './content.js';
|
||||
|
||||
type Who = { id: string; role: string };
|
||||
|
||||
@@ -121,6 +122,7 @@ const eventSchema = z.object({
|
||||
location: optional(500),
|
||||
description: optional(8000),
|
||||
imageId: z.string().uuid().nullable().default(null),
|
||||
framing: rowFraming,
|
||||
ministryId: z.string().uuid().nullable().default(null),
|
||||
link: z.string().trim().max(500).nullable().default(null).refine((v) => !v || /^https:\/\//.test(v), 'An https:// address').transform((v) => v || null),
|
||||
}).refine((e) => !e.endsAt || new Date(e.endsAt) >= new Date(e.startsAt), { message: 'It ends before it starts', path: ['endsAt'] });
|
||||
@@ -130,7 +132,7 @@ export async function listEvents(ctx: Ctx) {
|
||||
const urls = new Map(media.map((m) => [m.id, mediaUrl(m.filename)]));
|
||||
return rows.map((e) => ({
|
||||
id: e.id, slug: e.slug, title: e.title, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null, allDay: e.allDay, location: e.location,
|
||||
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, link: e.link, ministryId: e.ministryId,
|
||||
description: e.description, imageId: e.imageId, image: e.imageId ? urls.get(e.imageId) ?? null : null, framing: e.framing, link: e.link, ministryId: e.ministryId,
|
||||
cancelled: e.cancelled, published: e.publishedAt !== null, updatedAt: e.updatedAt.toISOString(),
|
||||
}));
|
||||
}
|
||||
@@ -144,7 +146,7 @@ export async function saveEvent(ctx: Ctx, id: string | null, body: unknown, by:
|
||||
if (leader && (!leader.ministryId || e.ministryId !== leader.ministryId)) throw new ApiError(403, 'FORBIDDEN', OWN_ONLY);
|
||||
const data = {
|
||||
title: e.title, startsAt: new Date(e.startsAt), endsAt: e.endsAt ? new Date(e.endsAt) : null, allDay: e.allDay, location: e.location, description: e.description,
|
||||
imageId: e.imageId, link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
|
||||
imageId: e.imageId, framing: framingFor(e.imageId, e.framing), link: e.link, ministryId: e.ministryId, timezone: ctx.config.timezone, updatedBy: by.id,
|
||||
};
|
||||
if (id) {
|
||||
const row = await ctx.db.simpleEvent.findUnique({ where: { id } });
|
||||
|
||||
@@ -147,6 +147,63 @@ export async function processImage(body: Buffer, kind: Kind, basePath: string) {
|
||||
return { main, width, height, sizes, files };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where each photo is used, so one in use is never deleted (it would leave a hole on the site):
|
||||
* the draft pages and their sections, ministries, leaders, series, events, the site icon, the
|
||||
* live site (the latest published version) and the church's logo. Returns a lookup by media id.
|
||||
*/
|
||||
export async function mediaUsage(ctx: Ctx): Promise<(m: { id: string; filename: string }) => string[]> {
|
||||
const [pages, sections, ministries, leaders, series, events, settings, latest, church] = await Promise.all([
|
||||
ctx.db.page.findMany({ where: { archivedAt: null } }),
|
||||
ctx.db.section.findMany(),
|
||||
ctx.db.ministry.findMany({ where: { archivedAt: null } }),
|
||||
ctx.db.leader.findMany({ where: { archivedAt: null } }),
|
||||
ctx.db.messageSeries.findMany(),
|
||||
ctx.db.simpleEvent.findMany(),
|
||||
ctx.db.appSetting.findMany(),
|
||||
ctx.db.siteVersion.findFirst({ orderBy: { number: 'desc' }, select: { snapshot: true } }),
|
||||
import('../church/profile.js').then((p) => p.churchProfile(ctx)).catch(() => null),
|
||||
]);
|
||||
const titles = new Map(pages.map((p) => [p.id, p.title]));
|
||||
const places: { label: string; text: string }[] = [
|
||||
...pages.map((p) => ({ label: `${p.title} page`, text: String(p.imageId ?? '') })),
|
||||
...sections.filter((s) => titles.has(s.pageId)).map((s) => ({ label: `${titles.get(s.pageId)} page`, text: JSON.stringify(s.data ?? null) })),
|
||||
...ministries.map((m) => ({ label: `Ministry: ${m.name}`, text: String(m.imageId ?? '') })),
|
||||
...leaders.map((l) => ({ label: `Leader: ${l.name}`, text: String(l.photoId ?? '') })),
|
||||
...series.map((s) => ({ label: `Series: ${s.title}`, text: String(s.imageId ?? '') })),
|
||||
...events.map((e) => ({ label: `Event: ${e.title}`, text: String(e.imageId ?? '') })),
|
||||
...settings.filter((s) => !s.key.startsWith('hub_')).map((s) => ({ label: 'Site settings', text: s.value })),
|
||||
{ label: 'The live site', text: JSON.stringify(latest?.snapshot ?? null) },
|
||||
{ label: 'Church logo', text: JSON.stringify(church?.branding ?? null) },
|
||||
];
|
||||
return (m) => {
|
||||
const url = mediaUrl(m.filename);
|
||||
// A page's sections each name it: list each place once.
|
||||
return [...new Set(places.filter((p) => p.text.includes(m.id) || p.text.includes(url)).map((p) => p.label))];
|
||||
};
|
||||
}
|
||||
|
||||
/** Deletes a photo and its files, unless it's used somewhere (then says where). */
|
||||
export async function deleteMedia(ctx: Ctx, id: string, by: { id: string; role: string }) {
|
||||
const row = await ctx.db.mediaAsset.findUnique({ where: { id } });
|
||||
if (!row) throw new ApiError(404, 'NOT_FOUND', 'That image doesn\'t exist.');
|
||||
const usedIn = (await mediaUsage(ctx))(row);
|
||||
if (usedIn.length) {
|
||||
throw new ApiError(409, 'IN_USE', `That photo is still used (${usedIn.join(', ')}). Take it out there first; if it's on the live site, publish after.`);
|
||||
}
|
||||
await ctx.db.mediaAsset.delete({ where: { id } });
|
||||
const dir = uploadDir(ctx);
|
||||
const sub = path.dirname(row.filename);
|
||||
const sizes = Array.isArray(row.sizes) ? (row.sizes as Sizes) : [];
|
||||
const files = [row.filename, ...sizes.flatMap((s) => [path.join(sub, s.webp), path.join(sub, s.jpg)])];
|
||||
await Promise.all(files.map((f) => {
|
||||
const full = path.resolve(dir, f);
|
||||
// Never outside the uploads folder, whatever the row says.
|
||||
return full.startsWith(dir + path.sep) ? fs.rm(full, { force: true }).catch(() => undefined) : undefined;
|
||||
}));
|
||||
await audit(ctx, { actorId: by.id, actorRole: by.role, action: 'media_deleted', targetType: 'media', targetId: id, metadata: { alt: row.alt, bytes: row.bytes } });
|
||||
}
|
||||
|
||||
type StorageAsk = { at: string; steps: number; limitAtRequest: number };
|
||||
|
||||
/** The open "Get more storage" request, if any: open until the limit goes up. */
|
||||
|
||||
@@ -22,7 +22,7 @@ import { syncYoutube } from '../site/youtube.js';
|
||||
import { publishOn, syncLink } from '../feed/feed.js';
|
||||
import { connectTo, disconnectFrom } from '../links/connect.js';
|
||||
import { linkedProducts } from '../links/store.js';
|
||||
import { MAX_UPLOAD_BYTES, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
|
||||
import { deleteMedia, MAX_UPLOAD_BYTES, mediaUsage, requestMoreStorage, storage, storageRequestStatus, upload } from './media.js';
|
||||
import { createPreviewLink, listPreviewLinks, revokePreviewLink } from './previewLinks.js';
|
||||
import { maintenanceRouter } from './maintenance.js';
|
||||
|
||||
@@ -96,10 +96,10 @@ export function adminRouter(ctx: Ctx) {
|
||||
|
||||
// ─── Media library and storage ───
|
||||
r.get('/media', handle(async () => {
|
||||
const rows = await ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } });
|
||||
const s = await storage(ctx);
|
||||
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes })) };
|
||||
const [rows, s, usedIn] = await Promise.all([ctx.db.mediaAsset.findMany({ orderBy: { createdAt: 'desc' } }), storage(ctx), mediaUsage(ctx)]);
|
||||
return { storage: s, request: await storageRequestStatus(ctx, s.limitBytes), items: rows.map((m) => ({ id: m.id, url: mediaUrl(m.filename), alt: m.alt, width: m.width, height: m.height, bytes: m.bytes, usedIn: usedIn(m) })) };
|
||||
}));
|
||||
r.delete('/media/:id', editor, handle(async (req) => { await deleteMedia(ctx, param(req, 'id'), who(req)); return { ok: true }; }));
|
||||
r.post('/media', editor, express.raw({ type: () => true, limit: MAX_UPLOAD_BYTES + 1 }), handle((req) =>
|
||||
upload(ctx, Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0), String(req.query.alt ?? ''), who(req).id)));
|
||||
// Get more storage: it costs the church, so an Owner or Admin asks (decision 12).
|
||||
|
||||
@@ -8,7 +8,7 @@ import { TEMPLATE_FONT_PAIRINGS, type Church, type CrosscodeEvent, type WebsiteT
|
||||
import type { Ctx } from '../context.js';
|
||||
import { churchProfile } from '../church/profile.js';
|
||||
import { buildPalette, type Palette } from './palette.js';
|
||||
import { buildSnapshot, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { buildSnapshot, framed, imageOf, mediaUrl, publishedSnapshot, type Image, type Snapshot } from './snapshot.js';
|
||||
import { headerIsTransparent, TEMPLATE_STYLE, type Variant } from './variants.js';
|
||||
|
||||
export type SiteEvent = {
|
||||
@@ -139,7 +139,7 @@ async function liveEvents(ctx: Ctx): Promise<SiteEvent[]> {
|
||||
};
|
||||
const own: SiteEvent[] = simple.map((e) => ({
|
||||
title: e.title, summary: e.description ? e.description.slice(0, 200) : null, startsAt: e.startsAt.toISOString(), endsAt: e.endsAt?.toISOString() ?? null,
|
||||
allDay: e.allDay, location: e.location, image: image(e.imageId), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
|
||||
allDay: e.allDay, location: e.location, image: framed(image(e.imageId), e.framing), url: e.link || `/events/${e.slug}`, slug: e.slug, link: e.link, from: 'website', registration: null,
|
||||
}));
|
||||
const copies: SiteEvent[] = imported.flatMap((row) => {
|
||||
const e = row.data as unknown as CrosscodeEvent;
|
||||
|
||||
@@ -12,6 +12,26 @@ import type { SectionType } from './variants.js';
|
||||
const text = (max: number) => z.string().trim().max(max);
|
||||
const optional = (max: number) => text(max).nullable().default(null);
|
||||
const mediaId = z.string().uuid();
|
||||
/**
|
||||
* How each photo sits in its frame, by media id: the point kept in view (`x`, `y`, 0 to 100 from
|
||||
* the left and top, as CSS `object-position`) and how far it's zoomed in (1 fills the frame).
|
||||
*/
|
||||
export const focusSchema = z.object({ x: z.number().min(0).max(100), y: z.number().min(0).max(100), zoom: z.number().min(1).max(4) });
|
||||
/** A ministry's, leader's or event's one photo: how it sits in its frame, or null (centred). */
|
||||
export const rowFraming = focusSchema.nullable().default(null);
|
||||
const framing = z.record(z.string().uuid(), focusSchema).optional();
|
||||
/** Keeps framing only for the photos the section still shows (a removed photo's would hold it "in use"). */
|
||||
function pruneFraming<T extends { framing?: Record<string, unknown> }>(d: T): T {
|
||||
if (!d.framing) return d;
|
||||
const ids = new Set<string>();
|
||||
const walk = (x: unknown): void => {
|
||||
if (typeof x === 'string') ids.add(x);
|
||||
else if (Array.isArray(x)) x.forEach(walk);
|
||||
else if (x && typeof x === 'object') Object.values(x).forEach(walk);
|
||||
};
|
||||
walk({ ...d, framing: undefined });
|
||||
return { ...d, framing: Object.fromEntries(Object.entries(d.framing).filter(([id]) => ids.has(id))) };
|
||||
}
|
||||
/** A link on the site (`/visit`) or elsewhere (https only). */
|
||||
const href = z.string().trim().max(500).refine((v) => /^\/(?!\/)/.test(v) || /^https:\/\//.test(v), 'A page of this site (/visit) or an https:// address');
|
||||
const button = z.object({ label: text(60).min(1), href }).nullable().default(null);
|
||||
@@ -25,7 +45,8 @@ export const SECTION_SCHEMAS = {
|
||||
/** `video`: a short muted loop (an uploaded .mp4) shown over its still (the first image). */
|
||||
videoId: mediaId.nullable().default(null),
|
||||
button,
|
||||
}),
|
||||
framing,
|
||||
}).transform(pruneFraming),
|
||||
serviceTimes: z.object({
|
||||
heading: optional(80),
|
||||
/** E.g. "Kids church during the morning service". Times and address come from the church profile. */
|
||||
@@ -38,12 +59,13 @@ export const SECTION_SCHEMAS = {
|
||||
body: text(4000).default(''),
|
||||
imageId: mediaId.nullable().default(null),
|
||||
pastor: z.object({ name: text(120).min(1), role: optional(80), quote: optional(400), photoId: mediaId.nullable().default(null) }).nullable().default(null),
|
||||
}),
|
||||
framing,
|
||||
}).transform(pruneFraming),
|
||||
ministries: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
team: z.object({ heading: optional(80), intro: optional(400) }),
|
||||
events: z.object({ heading: optional(80), count: z.int().min(2).max(12).default(3) }),
|
||||
latestMessage: z.object({ heading: optional(80) }),
|
||||
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null) }),
|
||||
invitation: z.object({ heading: text(120).min(1), text: optional(400), button, imageId: mediaId.nullable().default(null), framing }).transform(pruneFraming),
|
||||
} as const satisfies Record<SectionType, z.ZodType>;
|
||||
|
||||
export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)[S]> };
|
||||
@@ -51,7 +73,7 @@ export type SectionData = { [S in SectionType]: z.infer<(typeof SECTION_SCHEMAS)
|
||||
/** Blocks for the other pages and custom pages (§3, "Pages from blocks"); more come with the admin. */
|
||||
export const BLOCK_SCHEMAS = {
|
||||
text: z.object({ heading: optional(120), body: text(20000) }),
|
||||
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button }),
|
||||
'image-text': z.object({ heading: optional(120), body: text(4000).default(''), imageId: mediaId.nullable().default(null), button, framing }).transform(pruneFraming),
|
||||
quote: z.object({ quote: text(600).min(1), by: optional(120) }),
|
||||
cta: z.object({ heading: text(120).min(1), text: optional(400), button }),
|
||||
} as const;
|
||||
|
||||
@@ -16,7 +16,21 @@ import { defaultDesign, isVariant, SECTION_TYPES, switchTemplate, type SectionTy
|
||||
export const SNAPSHOT_VERSION = 1;
|
||||
|
||||
/** An image to show: the photo, and its responsive sizes as `srcset`s when it has them (§3). */
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string }; focus?: Focus };
|
||||
/** How a photo sits in its frame (Move and zoom): the point kept in view and the zoom. */
|
||||
export type Focus = { x: number; y: number; zoom: number };
|
||||
|
||||
/** A row's saved framing, if it is one (a Json column: anything else is ignored). */
|
||||
export function focusOf(f: unknown): Focus | undefined {
|
||||
const x = f as Partial<Focus> | null | undefined;
|
||||
return x && typeof x.x === 'number' && typeof x.y === 'number' && typeof x.zoom === 'number' ? { x: x.x, y: x.y, zoom: x.zoom } : undefined;
|
||||
}
|
||||
|
||||
/** The image with its framing, when it has one. */
|
||||
export const framed = (img: Image | null, f: unknown): Image | null => {
|
||||
const focus = img ? focusOf(f) : undefined;
|
||||
return img && focus ? { ...img, focus } : img;
|
||||
};
|
||||
|
||||
type MediaRow = { id: string; filename: string; alt: string; width: number | null; height: number | null; sizes?: unknown };
|
||||
|
||||
@@ -89,8 +103,8 @@ export type Source = {
|
||||
inNav: boolean; position: number; imageId: string | null;
|
||||
sections: { id: string; type: string; variant: string | null; position: number; hidden: boolean; data: unknown }[];
|
||||
}[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; position: number }[];
|
||||
ministries: { id: string; slug: string; name: string; summary: string | null; body: string | null; imageId: string | null; framing?: unknown; position: number }[];
|
||||
leaders: { id: string; name: string; role: string | null; bio: string | null; photoId: string | null; framing?: unknown; position: number }[];
|
||||
};
|
||||
|
||||
/** Every page, section, ministry and leader that isn't archived, with who last changed it. */
|
||||
@@ -105,6 +119,9 @@ export async function readWorkingCopy(ctx: Ctx) {
|
||||
return { design, pages, ministries, leaders };
|
||||
}
|
||||
|
||||
/** Framing in a source row only when there is some: versions published before it compare equal. */
|
||||
const withFraming = (f: unknown) => (focusOf(f) ? { framing: focusOf(f) } : {});
|
||||
|
||||
export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source {
|
||||
return {
|
||||
design: w.design ? { template: w.design.template, variants: w.design.variants, home: w.design.home, style: w.design.style } : null,
|
||||
@@ -113,8 +130,8 @@ export function toSource(w: Awaited<ReturnType<typeof readWorkingCopy>>): Source
|
||||
position: p.position, imageId: p.imageId,
|
||||
sections: p.sections.map((x) => ({ id: x.id, type: x.type, variant: x.variant, position: x.position, hidden: x.hidden, data: x.data })),
|
||||
})),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position })),
|
||||
ministries: w.ministries.map((m) => ({ id: m.id, slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, ...withFraming(m.framing), position: m.position })),
|
||||
leaders: w.leaders.map((l) => ({ id: l.id, name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, ...withFraming(l.framing), position: l.position })),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -179,8 +196,8 @@ export function snapshotFrom(source: Source, media: MediaRow[]): Snapshot {
|
||||
v: SNAPSHOT_VERSION,
|
||||
design: d,
|
||||
pages: snapshotPages,
|
||||
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: image(m.imageId) })),
|
||||
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: image(l.photoId) })),
|
||||
ministries: source.ministries.map((m) => ({ slug: m.slug, name: m.name, summary: m.summary, body: m.body, image: framed(image(m.imageId), m.framing) })),
|
||||
leaders: source.leaders.map((l) => ({ name: l.name, role: l.role, bio: l.bio, photo: framed(image(l.photoId), l.framing) })),
|
||||
media: used,
|
||||
redirects: {},
|
||||
source,
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
*/
|
||||
import type { Ctx } from '../context.js';
|
||||
import { ApiError } from '../http.js';
|
||||
import { Prisma } from '../generated/prisma/client.js';
|
||||
import { audit } from '../lib/audit.js';
|
||||
import { publishedSnapshot, readWorkingCopy, toSource, type Source } from './snapshot.js';
|
||||
|
||||
@@ -103,14 +104,14 @@ async function apply(ctx: Ctx, key: string, source: Source | null, by: Who) {
|
||||
if (what === 'ministry') {
|
||||
const m = source?.ministries.find((x) => x.id === id);
|
||||
if (!m) return void (await db.ministry.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, position: m.position, archivedAt: null, ...stamp };
|
||||
const data = { slug: m.slug, name: m.name, summary: m.summary, body: m.body, imageId: m.imageId, framing: (m.framing ?? Prisma.DbNull) as never, position: m.position, archivedAt: null, ...stamp };
|
||||
await db.ministry.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
if (what === 'leader') {
|
||||
const l = source?.leaders.find((x) => x.id === id);
|
||||
if (!l) return void (await db.leader.update({ where: { id }, data: { archivedAt: ctx.now(), ...stamp } }));
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, position: l.position, archivedAt: null, ...stamp };
|
||||
const data = { name: l.name, role: l.role, bio: l.bio, photoId: l.photoId, framing: (l.framing ?? Prisma.DbNull) as never, position: l.position, archivedAt: null, ...stamp };
|
||||
await db.leader.upsert({ where: { id }, create: { id, ...data }, update: data });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -226,3 +226,39 @@ describe('uploads and storage (§10, decision 12)', () => {
|
||||
assert.equal((await as.get('/media')).body.storage.full, true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('move and zoom for ministries, leaders and events', () => {
|
||||
it('saves framing with the row, publishes it onto the photo, drops it with the photo, and leaves old versions unchanged', async () => {
|
||||
const { as, app } = await signedIn('editor');
|
||||
// Published before framing existed: nothing shows as changed.
|
||||
assert.deepEqual((await as.get('/changes')).body, []);
|
||||
const focus = { x: 20, y: 70, zoom: 1.6 };
|
||||
|
||||
const m = ((await as.get('/ministries')).body as { id: string; name: string; imageId: string; updatedAt: string }[])[0]!;
|
||||
assert.ok(m.imageId);
|
||||
assert.equal((await as.put(`/ministries/${m.id}`, { name: m.name, imageId: m.imageId, framing: focus })).status, 200);
|
||||
assert.equal((await as.put(`/ministries/${m.id}`, { name: m.name, imageId: m.imageId, framing: { x: 200, y: 0, zoom: 1 } })).status, 400);
|
||||
const l = ((await as.get('/leaders')).body as { id: string; name: string; photoId: string }[])[0]!;
|
||||
assert.equal((await as.put(`/leaders/${l.id}`, { name: l.name, photoId: l.photoId, framing: focus })).status, 200);
|
||||
assert.deepEqual(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, focus);
|
||||
assert.deepEqual((await as.get('/changes')).body.map((c: { what: string }) => c.what).sort(), ['leader', 'ministry']);
|
||||
|
||||
assert.equal((await as.post('/publish')).status, 200);
|
||||
const site = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.deepEqual(site.snapshot.ministries.find((x: { name: string }) => x.name === m.name).image.focus, focus);
|
||||
assert.deepEqual(site.snapshot.leaders.find((x: { name: string }) => x.name === l.name).photo.focus, focus);
|
||||
|
||||
// Discard puts the published framing back; a photo removed takes its framing with it.
|
||||
await as.put(`/leaders/${l.id}`, { name: l.name, photoId: null, framing: focus });
|
||||
assert.equal(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, null);
|
||||
assert.equal((await as.post('/discard', { key: `leader:${l.id}` })).status, 200);
|
||||
assert.deepEqual(((await as.get('/leaders')).body as { id: string; framing: unknown }[]).find((x) => x.id === l.id)!.framing, focus);
|
||||
|
||||
// Events: saved with the event, shown on the live site straight away once published.
|
||||
const e = ((await as.get('/events')).body as { id: string; title: string; startsAt: string; endsAt: string | null; imageId: string | null }[]).find((x) => x.imageId)!;
|
||||
assert.equal((await as.put(`/events/${e.id}`, { title: e.title, startsAt: e.startsAt, endsAt: e.endsAt, imageId: e.imageId, framing: focus })).status, 200);
|
||||
assert.deepEqual(((await as.get('/events')).body as { id: string; framing: unknown }[]).find((x) => x.id === e.id)!.framing, focus);
|
||||
const live = (await request(app).get('/api/v1/site/content')).body;
|
||||
assert.deepEqual(live.events.find((x: { title: string }) => x.title === e.title).image.focus, focus);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import request from 'supertest';
|
||||
import { hashToken } from '../src/lib/crypto.js';
|
||||
import { parseSectionData } from '../src/site/sections.js';
|
||||
import { harness, SITE } from './support/harness.js';
|
||||
|
||||
async function site() {
|
||||
const uploads = await fs.mkdtemp(path.join(os.tmpdir(), 'ccw-media-'));
|
||||
const h = await harness({ linked: false, env: { UPLOAD_DIR: uploads } });
|
||||
const id = '00000000-0000-4000-8000-00000000000a';
|
||||
await h.db.websiteUser.create({ data: { id, name: 'Ann', email: 'ann@hope.test', role: 'editor' } });
|
||||
await h.db.session.create({ data: { tokenHash: hashToken('ann'), userId: id, expiresAt: new Date(Date.now() + 864e5) } });
|
||||
const go = (m: 'get' | 'delete', p: string) => request(h.app)[m](`/api/v1/admin${p}`).set('Cookie', 'ccw_session=ann').set('Origin', SITE);
|
||||
return { ...h, go, uploads };
|
||||
}
|
||||
|
||||
describe('deleting photos', () => {
|
||||
it('deletes one that is not used, with its files, and refuses one that is, saying where', async () => {
|
||||
const { go, db, uploads, ctx } = await site();
|
||||
const dir = path.resolve(ctx.config.uploadDir ?? uploads);
|
||||
await fs.mkdir(path.join(dir, '2026/11'), { recursive: true });
|
||||
for (const f of ['old.jpg', 'old-480.webp', 'old-480.jpg']) await fs.writeFile(path.join(dir, '2026/11', f), 'x');
|
||||
const old = await db.mediaAsset.create({ data: { filename: '2026/11/old.jpg', mime: 'image/jpeg', bytes: 3, width: 960, sizes: [{ w: 480, webp: 'old-480.webp', jpg: 'old-480.jpg' }] } });
|
||||
const used = await db.mediaAsset.create({ data: { filename: '2026/11/used.jpg', mime: 'image/jpeg', bytes: 3 } });
|
||||
const page = await db.page.create({ data: { kind: 'home', slug: 'home', title: 'Home' } });
|
||||
await db.section.create({ data: { pageId: page.id, type: 'hero', data: { headline: 'Hi', images: [used.id] } } });
|
||||
|
||||
const list = (await go('get', '/media')).body.items as { id: string; usedIn: string[] }[];
|
||||
assert.deepEqual(list.find((m) => m.id === used.id)!.usedIn, ['Home page']);
|
||||
assert.deepEqual(list.find((m) => m.id === old.id)!.usedIn, []);
|
||||
|
||||
const refused = await go('delete', `/media/${used.id}`);
|
||||
assert.equal(refused.status, 409);
|
||||
assert.match(refused.body.error.message, /Home page/);
|
||||
assert.ok(await db.mediaAsset.findUnique({ where: { id: used.id } }));
|
||||
|
||||
assert.equal((await go('delete', `/media/${old.id}`)).status, 200);
|
||||
assert.equal(await db.mediaAsset.findUnique({ where: { id: old.id } }), null);
|
||||
assert.deepEqual(await fs.readdir(path.join(dir, '2026/11')), []);
|
||||
assert.equal((await go('delete', `/media/${old.id}`)).status, 404);
|
||||
});
|
||||
});
|
||||
|
||||
describe('framing a photo in its frame', () => {
|
||||
it('keeps where each photo sits and how far it is zoomed, and refuses nonsense', () => {
|
||||
const id = '11111111-1111-4111-8111-111111111111';
|
||||
const ok = parseSectionData('hero', { headline: 'Hi', images: [id], framing: { [id]: { x: 30, y: 60, zoom: 1.5 } } });
|
||||
assert.deepEqual(ok?.framing, { [id]: { x: 30, y: 60, zoom: 1.5 } });
|
||||
assert.equal(parseSectionData('image-text', {})?.framing, undefined);
|
||||
// A photo taken out of the section takes its framing with it (or it would count as "in use").
|
||||
assert.deepEqual(parseSectionData('hero', { headline: 'Hi', images: [], framing: { [id]: { x: 30, y: 60, zoom: 1 } } })?.framing, {});
|
||||
assert.equal(parseSectionData('hero', { headline: 'Hi', framing: { [id]: { x: 300, y: 0, zoom: 1 } } }), null);
|
||||
});
|
||||
});
|
||||
@@ -9,13 +9,13 @@ import crypto from 'node:crypto';
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
const DEFAULTS: Record<string, () => Row> = {
|
||||
ministry: () => ({ summary: null, body: null, imageId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
leader: () => ({ role: null, bio: null, photoId: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
ministry: () => ({ summary: null, body: null, imageId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
leader: () => ({ role: null, bio: null, photoId: null, framing: null, position: 0, archivedAt: null, updatedBy: null }),
|
||||
messageSeries: () => ({ summary: null, imageId: null }),
|
||||
page: () => ({ seoTitle: null, description: null, navLabel: null, inNav: true, position: 0, imageId: null, archivedAt: null, updatedBy: null }),
|
||||
section: () => ({ variant: null, position: 0, hidden: false, updatedBy: null }),
|
||||
message: () => ({ externalId: null, thumbnailUrl: null, speaker: null, passage: null, notes: null, seriesId: null, hidden: false, publishedAt: null, updatedBy: null }),
|
||||
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
||||
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageId: null, framing: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
|
||||
mediaAsset: () => ({ width: null, height: null, alt: '', sizes: null, uploadedBy: null }),
|
||||
siteVersion: () => ({ note: null }),
|
||||
websiteUser: () => ({ ministryId: null, lastSignInAt: null }),
|
||||
@@ -66,7 +66,9 @@ export function matches(row: Row, where: Row = {}): boolean {
|
||||
});
|
||||
}
|
||||
|
||||
const clone = <T>(x: T): T => structuredClone(x);
|
||||
/** Prisma.DbNull / JsonNull (a nullable Json field set to null) are stored as null, as Postgres does. */
|
||||
const nulls = (x: unknown) => (x && typeof x === 'object' && /^(Db|Json)Null$/.test(x.constructor?.name ?? '') ? null : x);
|
||||
const clone = <T>(x: T): T => structuredClone(x && typeof x === 'object' && !Array.isArray(x) && !(x instanceof Date) ? Object.fromEntries(Object.entries(x).map(([k, y]) => [k, nulls(y)])) as T : x);
|
||||
const pick = (row: Row, select?: Row) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||
|
||||
function order(rows: Row[], orderBy?: Row | Row[]) {
|
||||
|
||||
@@ -185,3 +185,63 @@ test("the admin's screens are accessible", async ({ page, context }) => {
|
||||
const axe = await new AxeBuilder({ page }).withTags(["wcag2a", "wcag2aa", "wcag21aa", "wcag22aa"]).analyze();
|
||||
expect(axe.violations.map((v) => `editor: ${v.id} (${v.nodes.length}) ${v.nodes[0]?.target}`)).toEqual([]);
|
||||
});
|
||||
|
||||
test("move and zoom a photo in its frame, then delete a photo nothing uses", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
await page.goto("/admin/pages");
|
||||
await page.getByRole("link", { name: /^Home\b/ }).first().click();
|
||||
await expect(page).toHaveURL(/\/admin\/pages\/[0-9a-f-]+$/);
|
||||
await page.getByRole("button", { name: /Top of the page/ }).click();
|
||||
await page.getByRole("button", { name: "Move and zoom" }).first().click();
|
||||
const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" });
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.getByRole("slider").fill("2");
|
||||
const box = (await dialog.getByLabel(/in its frame/).boundingBox())!;
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x + box.width / 2 + 80, box.y + box.height / 2 + 30, { steps: 5 });
|
||||
await page.mouse.up();
|
||||
await dialog.getByRole("button", { name: "Done" }).click();
|
||||
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||
await expect(page.getByText("Saved as a draft.")).toBeVisible();
|
||||
// The live preview draws it the same way.
|
||||
const frame = page.frameLocator('iframe[title="Live preview of this page"]');
|
||||
await expect(frame.locator(".cc-section-hero img").first()).toHaveAttribute("style", /scale\(2\)/);
|
||||
await page.screenshot({ path: "e2e/test-results/framing.png" });
|
||||
|
||||
// Upload one nothing uses, then delete it; one in use says where instead.
|
||||
await page.goto("/admin/media");
|
||||
// Count once the library has loaded (it can still be empty for a moment).
|
||||
await expect(page.locator("main li").first()).toBeVisible();
|
||||
const before = await page.locator("main li").count();
|
||||
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");
|
||||
await page.locator('input[type="file"]').setInputFiles({ name: "dot.png", mimeType: "image/png", buffer: png });
|
||||
await page.getByLabel("What the photo shows").fill("A dot to delete");
|
||||
await page.getByRole("button", { name: "Upload" }).click();
|
||||
await expect(page.locator("main li")).toHaveCount(before + 1);
|
||||
await expect(page.getByText("Used on:").first()).toBeVisible();
|
||||
page.once("dialog", (d) => d.accept());
|
||||
await page.locator("main li").filter({ has: page.locator('input[value="A dot to delete"]') }).getByRole("button", { name: "Delete" }).click();
|
||||
await expect(page.getByText("Deleted.")).toBeVisible();
|
||||
await expect(page.locator("main li")).toHaveCount(before);
|
||||
});
|
||||
|
||||
test("move and zoom a ministry's, a leader's and an event's photo", async ({ page, context }) => {
|
||||
await signIn(context);
|
||||
for (const [path, saved] of [["/admin/ministries", "Saved as a draft."], ["/admin/leaders", "Saved as a draft."], ["/admin/events", null]] as const) {
|
||||
await page.goto(path);
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).first().click();
|
||||
await page.getByRole("button", { name: "Move and zoom" }).first().click();
|
||||
const dialog = page.getByRole("dialog", { name: "Move and zoom the photo" });
|
||||
await dialog.getByRole("slider").fill("2");
|
||||
await dialog.getByRole("button", { name: "Done" }).click();
|
||||
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Save", exact: true }).click();
|
||||
if (saved) await expect(page.getByText(saved)).toBeVisible();
|
||||
else await expect(page.getByRole("button", { name: "Save", exact: true })).toHaveCount(0);
|
||||
// Saved with the row: it's there when the form opens again.
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).first().click();
|
||||
await expect(page.getByText("Moved and zoomed to 200%")).toBeVisible();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.1",
|
||||
"private": true,
|
||||
"description": "Church Website: the church's public site in its template, and the admin",
|
||||
"scripts": {
|
||||
|
||||
@@ -3,10 +3,15 @@
|
||||
/** A list of things the church keeps (ministries, its team): add, edit, remove. Drafts until Publish. */
|
||||
import { useState } from "react";
|
||||
import { api } from "./api";
|
||||
import type { Focus } from "@/site/types";
|
||||
import { RowFraming } from "./framing";
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string };
|
||||
export type ListField = { key: string; label: string; kind: "text" | "textarea" | "image"; max?: number; hint?: string;
|
||||
/** An image field: its photo can be moved and zoomed in this frame (saved as the row's `framing`). */
|
||||
frame?: "ministry" | "leader";
|
||||
};
|
||||
|
||||
type Row = Record<string, unknown> & { id: string };
|
||||
|
||||
@@ -14,7 +19,14 @@ function Editor({ fields, initial, onSave, onCancel, busy, errors }: { fields: L
|
||||
const [v, setV] = useState<Record<string, unknown>>(initial);
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{fields.map((f) => f.kind === "image"
|
||||
{fields.map((f) => f.kind === "image" && f.frame
|
||||
? (
|
||||
<RowFraming key={f.key} type={f.frame} value={v.framing as Focus | null} onChange={(framing) => setV({ ...v, framing })}>
|
||||
{/* Another photo starts centred. */}
|
||||
<ImagePicker label={f.label} slot={{ key: f.key }} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id, framing: null })} />
|
||||
</RowFraming>
|
||||
)
|
||||
: f.kind === "image"
|
||||
? <ImagePicker key={f.key} label={f.label} value={(v[f.key] as string) ?? null} onChange={(id) => setV({ ...v, [f.key]: id })} />
|
||||
: (
|
||||
<Field key={f.key} label={f.label} hint={f.hint} error={errors[f.key]}>
|
||||
@@ -36,7 +48,7 @@ export function ListEditor({ path, fields, nameKey, subKey, addLabel, canAdd }:
|
||||
const save = (id: string | null, v: Record<string, unknown>) => run(async () => {
|
||||
const row = id ? data.find((r) => r.id === id) : null;
|
||||
// When the form was loaded: someone else's save in between isn't overwritten (§4).
|
||||
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
|
||||
const body = { ...Object.fromEntries(fields.map((f) => [f.key, v[f.key] ?? null])), ...(fields.some((f) => f.frame) ? { framing: v.framing ?? null } : {}), ...(row?.updatedAt ? { ifUpdatedAt: row.updatedAt } : {}) };
|
||||
await api(id ? `${path}/${id}` : path, { method: id ? "PUT" : "POST", body });
|
||||
setEditing(null);
|
||||
await reload();
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
* The forms for each homepage section and block, from one description per type (the backend's
|
||||
* zod schemas in src/site/sections.ts check what's saved; field errors come back by path).
|
||||
*/
|
||||
import type { Focus } from "@/site/types";
|
||||
import { FramingContext, type Framing } from "./framing";
|
||||
import { ImagePicker } from "./media";
|
||||
import { Btn, Field, inputClass } from "./ui";
|
||||
|
||||
@@ -52,9 +54,13 @@ export const BLOCK_FIELDS: Record<string, { name: string; fields: Spec[] }> = {
|
||||
|
||||
type Data = Record<string, unknown>;
|
||||
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string }) {
|
||||
/**
|
||||
* A section's or block's fields. With `frame` (the top-level form of a section), its photos show in
|
||||
* the shape of their frame on the site and can be moved and zoomed (saved in `data.framing`).
|
||||
*/
|
||||
export function DataForm({ fields, value, onChange, errors, prefix = "", frame }: { fields: Spec[]; value: Data; onChange: (v: Data) => void; errors: Record<string, string>; prefix?: string; frame?: Framing["frame"] }) {
|
||||
const set = (k: string, v: unknown) => onChange({ ...value, [k]: v });
|
||||
return (
|
||||
const form = (
|
||||
<div className="space-y-4">
|
||||
{fields.map((f) => {
|
||||
const err = errors[`${prefix}${f.key}`];
|
||||
@@ -67,14 +73,14 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie
|
||||
case "number":
|
||||
return <Field key={f.key} label={f.label} error={err}><input type="number" className={`${inputClass} w-24`} min={f.min} max={f.max} value={(v as number) ?? f.min} onChange={(e) => set(f.key, Number(e.target.value))} /></Field>;
|
||||
case "image":
|
||||
return <div key={f.key}><ImagePicker label={f.label} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
return <div key={f.key}><ImagePicker label={f.label} slot={{ key: f.key }} value={(v as string) ?? null} onChange={(id) => set(f.key, id)} />{err && <p className="text-xs text-red-700">{err}</p>}</div>;
|
||||
case "images": {
|
||||
const list = Array.isArray(v) ? (v as string[]) : [];
|
||||
return (
|
||||
<div key={f.key} className="space-y-2">
|
||||
<p className="text-sm font-medium text-gray-800">{f.label}</p>
|
||||
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
|
||||
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
|
||||
{list.map((id, i) => <ImagePicker key={i} label={`Photo ${i + 1}`} slot={{ key: f.key, index: i }} value={id} onChange={(n) => set(f.key, n ? list.map((x, j) => (j === i ? n : x)) : list.filter((_, j) => j !== i))} />)}
|
||||
{list.length < f.max && <ImagePicker label={`Photo ${list.length + 1}`} slot={{ key: f.key, index: list.length }} value={null} onChange={(n) => n && set(f.key, [...list, n])} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -111,4 +117,16 @@ export function DataForm({ fields, value, onChange, errors, prefix = "" }: { fie
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
if (!frame) return form;
|
||||
const framing = (value.framing ?? {}) as Record<string, Focus>;
|
||||
const ctx: Framing = {
|
||||
get: (id) => framing[id],
|
||||
set: (id, f) => {
|
||||
const next = { ...framing };
|
||||
if (f) next[id] = f; else delete next[id];
|
||||
onChange({ ...value, framing: next });
|
||||
},
|
||||
frame,
|
||||
};
|
||||
return <FramingContext.Provider value={ctx}>{form}</FramingContext.Provider>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
"use client";
|
||||
|
||||
/**
|
||||
* Framing a photo: see it in the shape of the frame the site puts it in (the template and layout
|
||||
* chosen), drag it to move it and zoom in to crop. Saved with the section (`data.framing`, by media
|
||||
* id), so it's a draft like any other change: previewed, then published.
|
||||
*/
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import { focusStyle } from "@/site/parts";
|
||||
import type { Focus } from "@/site/types";
|
||||
import { Btn, cx, useAdmin } from "./ui";
|
||||
|
||||
export type Frame = { ratio: number; round?: boolean; label: string };
|
||||
|
||||
export const CENTRE: Focus = { x: 50, y: 50, zoom: 1 };
|
||||
|
||||
type Design = { template?: string; variants?: Record<string, string> } | null | undefined;
|
||||
|
||||
/**
|
||||
* The frame a section's photo is shown in, as wide as the site's desktop layout draws it
|
||||
* (site/sections). `key` is the field (images, imageId, photoId); `index` the photo in a list.
|
||||
*/
|
||||
export function frameFor(design: Design, type: string, key: string, index = 0): Frame {
|
||||
const t = design?.template ?? "heritage";
|
||||
const v = design?.variants?.[type];
|
||||
if (type === "hero") {
|
||||
if (v === "text") return { ratio: 16 / 9, label: "Not shown: the top of the page is set to Text only" };
|
||||
if (v === "split") return t === "bold" ? { ratio: 4 / 5, label: "Half the screen, beside the headline" } : { ratio: 4 / 3, label: "Beside the headline" };
|
||||
if (v === "collage") {
|
||||
if (t === "bold") return { ratio: 3 / 5, label: `Column ${index + 1} of 3, behind the headline` };
|
||||
if (t === "community") return { ratio: 1, round: index === 2, label: `Photo ${index + 1} of the overlapping three` };
|
||||
return { ratio: t === "heritage" ? 3 / 4 : 1, label: `Photo ${index + 1} of 3` };
|
||||
}
|
||||
if (t === "bold") return { ratio: 16 / 9, label: "The whole screen, behind the headline (taller on phones)" };
|
||||
if (t === "heritage") return { ratio: 16 / 7, label: "Wide, above the headline" };
|
||||
if (t === "community") return { ratio: 21 / 9, label: "Wide, behind the headline card (16:9 on phones)" };
|
||||
return { ratio: 16 / 9, label: "Below the headline" };
|
||||
}
|
||||
if (type === "welcome") {
|
||||
if (key === "photoId") return { ratio: 4 / 5, label: "The pastor's photo" };
|
||||
return t === "bold" ? { ratio: 1, label: "Beside the welcome" } : { ratio: 4 / 3, label: "Beside the welcome" };
|
||||
}
|
||||
// A ministry's, leader's or event's photo: the home page section's frame for the layout chosen.
|
||||
if (type === "ministry") {
|
||||
const vm = design?.variants?.ministries;
|
||||
if (vm === "bands") return t === "bold" ? { ratio: 4 / 3, label: "Beside its name on the home page (4:3 on the Ministries page)" } : { ratio: 16 / 10, label: "Beside its name on the home page (4:3 on the Ministries page)" };
|
||||
return { ratio: 4 / 3, label: "On its card on the home page and beside it on the Ministries page" };
|
||||
}
|
||||
if (type === "leader") {
|
||||
const round = t === "heritage" || t === "community";
|
||||
if (t === "bold") return { ratio: 3 / 4, label: "Their photo on the home page (square on the Leadership page)" };
|
||||
return { ratio: 1, round, label: round ? "Their photo, in a circle" : "Their photo" };
|
||||
}
|
||||
if (type === "event") return { ratio: 16 / 10, label: "On the event's card (a little taller on its own page)" };
|
||||
if (type === "invitation") return { ratio: 3, label: "Behind the invitation, darkened (the Image background layout)" };
|
||||
return { ratio: 4 / 3, label: "Beside the text" };
|
||||
}
|
||||
|
||||
/** What DataForm shares with each ImagePicker in a section: its framing, and the frame per field. */
|
||||
export type Framing = {
|
||||
get: (id: string) => Focus | undefined;
|
||||
set: (id: string, f: Focus | null) => void;
|
||||
frame: (key: string, index?: number) => Frame;
|
||||
};
|
||||
|
||||
export const FramingContext = createContext<Framing | null>(null);
|
||||
export const useFraming = () => useContext(FramingContext);
|
||||
|
||||
/**
|
||||
* Framing for a row with one photo (a ministry, a leader, an event): saved as the row's `framing`,
|
||||
* in the frame of `type` (frameFor) for the site's current template and layouts.
|
||||
*/
|
||||
export function RowFraming({ type, value, onChange, children }: { type: "ministry" | "leader" | "event"; value: Focus | null | undefined; onChange: (f: Focus | null) => void; children: React.ReactNode }) {
|
||||
const design = useAdmin<{ design: Design }>("/design");
|
||||
const ctx: Framing = { get: () => value ?? undefined, set: (_, f) => onChange(f), frame: (key, i) => frameFor(design.data?.design, type, key, i) };
|
||||
return <FramingContext.Provider value={ctx}>{children}</FramingContext.Provider>;
|
||||
}
|
||||
|
||||
/** The photo drawn in its frame, as the site draws it (object-cover, point kept in view, zoom). */
|
||||
export function Framed({ url, frame, focus, className, imgRef }: { url: string; frame: Frame; focus: Focus | undefined; className?: string; imgRef?: React.Ref<HTMLImageElement> }) {
|
||||
return (
|
||||
<div className={cx("relative overflow-hidden bg-gray-100", frame.round ? "rounded-full" : "rounded", className)} style={{ aspectRatio: String(frame.ratio) }}>
|
||||
<img ref={imgRef} src={url} alt="" draggable={false} className="pointer-events-none absolute inset-0 h-full w-full select-none object-cover" style={focusStyle(focus)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n));
|
||||
|
||||
/** Drag to move, slider (or wheel) to zoom; Done keeps it, Cancel leaves it as it was. */
|
||||
export function FramingDialog({ url, alt, frame, initial, onDone, onClose }: {
|
||||
url: string; alt: string; frame: Frame; initial: Focus | undefined; onDone: (f: Focus | null) => void; onClose: () => void;
|
||||
}) {
|
||||
const [f, setF] = useState<Focus>(initial ?? CENTRE);
|
||||
const box = useRef<HTMLDivElement>(null);
|
||||
const img = useRef<HTMLImageElement>(null);
|
||||
const drag = useRef<{ x: number; y: number; start: Focus } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const esc = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
|
||||
window.addEventListener("keydown", esc);
|
||||
return () => window.removeEventListener("keydown", esc);
|
||||
}, [onClose]);
|
||||
|
||||
/** How far the photo can move (px) across 0–100%: its drawn size, zoomed, less the frame's. */
|
||||
const room = () => {
|
||||
const b = box.current?.getBoundingClientRect();
|
||||
const i = img.current;
|
||||
if (!b || !i?.naturalWidth) return { x: 0, y: 0 };
|
||||
const cover = Math.max(b.width / i.naturalWidth, b.height / i.naturalHeight);
|
||||
return { x: i.naturalWidth * cover * f.zoom - b.width, y: i.naturalHeight * cover * f.zoom - b.height };
|
||||
};
|
||||
|
||||
const down = (e: React.PointerEvent) => {
|
||||
(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId);
|
||||
drag.current = { x: e.clientX, y: e.clientY, start: f };
|
||||
};
|
||||
const move = (e: React.PointerEvent) => {
|
||||
const d = drag.current;
|
||||
if (!d) return;
|
||||
const r = room();
|
||||
// Dragging the photo right shows more of its left: the point in view moves left.
|
||||
setF({
|
||||
...d.start,
|
||||
x: r.x > 1 ? clamp(d.start.x - ((e.clientX - d.x) / r.x) * 100, 0, 100) : d.start.x,
|
||||
y: r.y > 1 ? clamp(d.start.y - ((e.clientY - d.y) / r.y) * 100, 0, 100) : d.start.y,
|
||||
});
|
||||
};
|
||||
const key = (e: React.KeyboardEvent) => {
|
||||
const step = e.shiftKey ? 10 : 2;
|
||||
const by: Record<string, [number, number]> = { ArrowLeft: [step, 0], ArrowRight: [-step, 0], ArrowUp: [0, step], ArrowDown: [0, -step] };
|
||||
const m = by[e.key];
|
||||
if (!m) return;
|
||||
e.preventDefault();
|
||||
setF({ ...f, x: clamp(f.x + m[0], 0, 100), y: clamp(f.y + m[1], 0, 100) });
|
||||
};
|
||||
const round = (x: Focus): Focus => ({ x: Math.round(x.x * 10) / 10, y: Math.round(x.y * 10) / 10, zoom: Math.round(x.zoom * 100) / 100 });
|
||||
const centred = f.x === 50 && f.y === 50 && f.zoom === 1;
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/50 p-4" role="dialog" aria-modal="true" aria-label="Move and zoom the photo">
|
||||
<div className="max-h-[95vh] w-full max-w-2xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
|
||||
<h2 className="text-lg font-semibold">Move and zoom</h2>
|
||||
<p className="mt-1 text-sm text-gray-600">{frame.label}. Drag the photo to choose what shows; zoom in to crop closer.</p>
|
||||
<div
|
||||
ref={box}
|
||||
tabIndex={0}
|
||||
aria-label={`${alt || "The photo"} in its frame. Arrow keys move it.`}
|
||||
onPointerDown={down}
|
||||
onPointerMove={move}
|
||||
onPointerUp={() => { drag.current = null; }}
|
||||
onPointerCancel={() => { drag.current = null; }}
|
||||
onKeyDown={key}
|
||||
onWheel={(e) => setF((x) => ({ ...x, zoom: clamp(x.zoom - e.deltaY * 0.002, 1, 3) }))}
|
||||
className="mx-auto mt-4 cursor-grab touch-none outline-none ring-brand focus-visible:ring-2 active:cursor-grabbing"
|
||||
style={{ maxWidth: frame.ratio < 1 ? `${Math.round(360 * frame.ratio)}px` : undefined }}
|
||||
>
|
||||
<Framed url={url} frame={frame} focus={f} imgRef={img} />
|
||||
</div>
|
||||
<label className="mt-5 flex items-center gap-3 text-sm text-gray-700">
|
||||
Zoom
|
||||
<input type="range" min={1} max={3} step={0.01} value={f.zoom} onChange={(e) => setF({ ...f, zoom: Number(e.target.value) })} className="flex-1" />
|
||||
<span className="w-12 text-right tabular-nums">{Math.round(f.zoom * 100)}%</span>
|
||||
</label>
|
||||
<p className="mt-2 text-xs text-gray-500">On phones the frame can be a different shape; the part you chose stays in view.</p>
|
||||
<div className="mt-5 flex flex-wrap items-center gap-3">
|
||||
<Btn kind="primary" onClick={() => onDone(centred ? null : round(f))}>Done</Btn>
|
||||
<Btn onClick={onClose}>Cancel</Btn>
|
||||
<Btn kind="link" onClick={() => setF(CENTRE)} disabled={centred}>Reset</Btn>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
/** The media library: pick an image, or upload one (with its alt text) and pick it. */
|
||||
import { useRef, useState } from "react";
|
||||
import { Move } from "lucide-react";
|
||||
import { api } from "./api";
|
||||
import { Framed, FramingDialog, useFraming } from "./framing";
|
||||
import { Btn, cx, Field, inputClass, Notice, useAction, useAdmin } from "./ui";
|
||||
|
||||
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number };
|
||||
export type MediaItem = { id: string; url: string; alt: string; width: number | null; height: number | null; bytes: number; usedIn?: string[] };
|
||||
export type Storage = { usedBytes: number; limitBytes: number; full: boolean; percent: number };
|
||||
|
||||
export const gb = (n: number) => `${(n / 1024 ** 3).toFixed(n < 1024 ** 3 ? 2 : 1)} GB`;
|
||||
@@ -49,21 +51,41 @@ export function Uploader({ onUploaded, disabled }: { onUploaded: (m: MediaItem)
|
||||
);
|
||||
}
|
||||
|
||||
/** One image field: shows the chosen image, with Choose and Remove. */
|
||||
export function ImagePicker({ value, onChange, label }: { value: string | null; onChange: (id: string | null) => void; label: string }) {
|
||||
/**
|
||||
* One image field: shows the chosen image, with Choose and Remove. In a section (`slot` and a
|
||||
* FramingContext), it's shown in the shape of its frame on the site, with Move and zoom.
|
||||
*/
|
||||
export function ImagePicker({ value, onChange, label, slot }: { value: string | null; onChange: (id: string | null) => void; label: string; slot?: { key: string; index?: number } }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [framingOpen, setFramingOpen] = useState(false);
|
||||
const { data, reload } = useAdmin<{ storage: Storage; items: MediaItem[] }>(open || value ? "/media" : null);
|
||||
const chosen = data?.items.find((m) => m.id === value);
|
||||
const framing = useFraming();
|
||||
const frame = framing && slot ? framing.frame(slot.key, slot.index) : null;
|
||||
const focus = value ? framing?.get(value) : undefined;
|
||||
return (
|
||||
<div>
|
||||
<span className="block text-sm font-medium text-gray-800">{label}</span>
|
||||
<div className="mt-1 flex items-center gap-3">
|
||||
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
|
||||
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-3">
|
||||
{chosen && frame ? (
|
||||
<button type="button" onClick={() => setFramingOpen(true)} title="Move and zoom" className="shrink-0 rounded border border-gray-200"
|
||||
style={{ width: `${Math.round(Math.min(160, Math.max(48, 72 * frame.ratio)))}px` }}>
|
||||
<Framed url={chosen.url} frame={frame} focus={focus} />
|
||||
</button>
|
||||
) : (
|
||||
<div className="h-16 w-24 shrink-0 overflow-hidden rounded border border-gray-200 bg-gray-50">
|
||||
{chosen ? <img src={chosen.url} alt={chosen.alt} className="h-full w-full object-cover" /> : <span className="flex h-full items-center justify-center text-xs text-gray-600">No image</span>}
|
||||
</div>
|
||||
)}
|
||||
<Btn onClick={() => setOpen(true)}>{value ? "Change" : "Choose"}</Btn>
|
||||
{chosen && frame && <Btn onClick={() => setFramingOpen(true)}><Move className="h-4 w-4" aria-hidden />Move and zoom</Btn>}
|
||||
{value && <Btn kind="link" onClick={() => onChange(null)}>Remove</Btn>}
|
||||
</div>
|
||||
{chosen && frame && focus && <p className="mt-1 text-xs text-gray-500">Moved{focus.zoom > 1 ? ` and zoomed to ${Math.round(focus.zoom * 100)}%` : ""}. Save to see it in the preview.</p>}
|
||||
{framingOpen && chosen && frame && framing && (
|
||||
<FramingDialog url={chosen.url} alt={chosen.alt} frame={frame} initial={focus}
|
||||
onDone={(f) => { framing.set(chosen.id, f); setFramingOpen(false); }} onClose={() => setFramingOpen(false)} />
|
||||
)}
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" role="dialog" aria-modal="true" aria-label="Choose an image">
|
||||
<div className="max-h-[90vh] w-full max-w-3xl overflow-y-auto rounded-lg bg-white p-6 shadow-xl">
|
||||
|
||||
@@ -8,15 +8,17 @@
|
||||
*/
|
||||
import { useState } from "react";
|
||||
import { api, canEdit } from "@/admin/api";
|
||||
import { RowFraming } from "@/admin/framing";
|
||||
import { ImagePicker } from "@/admin/media";
|
||||
import type { Focus } from "@/site/types";
|
||||
import { Btn, Field, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
|
||||
import { CalendarDays } from "lucide-react";
|
||||
|
||||
type Ev = {
|
||||
id: string; slug: string; title: string; startsAt: string; endsAt: string | null; allDay: boolean; location: string | null; description: string | null;
|
||||
imageId: string | null; image: string | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
|
||||
imageId: string | null; image: string | null; framing: Focus | null; link: string | null; ministryId: string | null; cancelled: boolean; published: boolean; updatedAt: string;
|
||||
};
|
||||
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; link: string; ministryId: string | null };
|
||||
type Form = { title: string; date: string; time: string; endDate: string; endTime: string; allDay: boolean; location: string; description: string; imageId: string | null; framing: Focus | null; link: string; ministryId: string | null };
|
||||
type Me = { user: { role: string; ministryId: string | null } };
|
||||
|
||||
/** "2026-12-05" + "18:30" in the browser's time zone (the church's, for its admins) → ISO with offset. */
|
||||
@@ -53,11 +55,14 @@ function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { i
|
||||
</select>
|
||||
</Field>
|
||||
)}
|
||||
<ImagePicker label="Photo" value={v.imageId} onChange={(id) => set("imageId", id)} />
|
||||
<RowFraming type="event" value={v.framing} onChange={(f) => set("framing", f)}>
|
||||
{/* Another photo starts centred. */}
|
||||
<ImagePicker label="Photo" slot={{ key: "imageId" }} value={v.imageId} onChange={(id) => setV({ ...v, imageId: id, framing: null })} />
|
||||
</RowFraming>
|
||||
<div className="flex gap-2">
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave({
|
||||
title: v.title, startsAt: iso(v.date, v.allDay ? "00:00" : v.time), endsAt: v.endDate ? iso(v.endDate, v.allDay ? "23:59" : v.endTime) : null,
|
||||
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
|
||||
allDay: v.allDay, location: v.location || null, description: v.description || null, imageId: v.imageId, framing: v.framing, link: v.link || null, ministryId: fixedMinistry ?? v.ministryId,
|
||||
}))}>Save</Btn>
|
||||
<Btn onClick={onCancel}>Cancel</Btn>
|
||||
</div>
|
||||
@@ -66,7 +71,7 @@ function EventForm({ initial, ministries, fixedMinistry, onSave, onCancel }: { i
|
||||
);
|
||||
}
|
||||
|
||||
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, link: "", ministryId: null };
|
||||
const empty: Form = { title: "", date: "", time: "10:00", endDate: "", endTime: "", allDay: false, location: "", description: "", imageId: null, framing: null, link: "", ministryId: null };
|
||||
|
||||
export default function Events() {
|
||||
const me = useAdmin<Me>("/me");
|
||||
@@ -82,7 +87,7 @@ export default function Events() {
|
||||
const toForm = (e: Ev): Form => {
|
||||
const s = local(e.startsAt);
|
||||
const f = local(e.endsAt);
|
||||
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, link: e.link ?? "", ministryId: e.ministryId };
|
||||
return { title: e.title, date: s.d, time: s.t, endDate: f.d, endTime: f.t, allDay: e.allDay, location: e.location ?? "", description: e.description ?? "", imageId: e.imageId, framing: e.framing ?? null, link: e.link ?? "", ministryId: e.ministryId };
|
||||
};
|
||||
const state = (e: Ev, change: object, done: string) => run(async () => { await api(`/events/${e.id}/state`, { body: change }); await reload(); }, done);
|
||||
const form = (e: Ev | null) => (
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function Leaders() {
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "role", label: "Role", kind: "text", max: 120, hint: "E.g. “Lead pastor”." },
|
||||
{ key: "bio", label: "About them", kind: "textarea", max: 4000 },
|
||||
{ key: "photoId", label: "Photo", kind: "image" },
|
||||
{ key: "photoId", label: "Photo", kind: "image", frame: "leader" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { api } from "@/admin/api";
|
||||
import { api, canEdit } from "@/admin/api";
|
||||
import { gb, StorageMeter, Uploader, type MediaItem, type Storage } from "@/admin/media";
|
||||
import { Btn, inputClass, Loading, Notice, Panel, Title, useAction, useAdmin, when } from "@/admin/ui";
|
||||
import { Image as ImageIcon } from "lucide-react";
|
||||
import { Image as ImageIcon, Trash2 } from "lucide-react";
|
||||
|
||||
/** The media library (§10): uploads, what each photo shows (alt text), and storage used. */
|
||||
export default function Media() {
|
||||
@@ -15,6 +15,7 @@ export default function Media() {
|
||||
const { busy, message, run } = useAction();
|
||||
if (!data) return <Loading error={error} />;
|
||||
const manager = ["owner", "admin"].includes(me.data?.user.role ?? "");
|
||||
const editor = canEdit(me.data?.user.role ?? "");
|
||||
const s = data.storage;
|
||||
return (
|
||||
<>
|
||||
@@ -35,6 +36,15 @@ export default function Media() {
|
||||
)}
|
||||
{!m.alt && <p className="text-xs font-medium text-amber-800">Add what it shows, for people who can't see it.</p>}
|
||||
<p className="text-xs text-gray-500">{m.width && m.height ? `${m.width} × ${m.height}` : ""} · {gb(m.bytes)}</p>
|
||||
{m.usedIn?.length ? (
|
||||
<p className="text-xs text-gray-600">Used on: {m.usedIn.join(", ")}</p>
|
||||
) : editor && (
|
||||
<Btn kind="danger" busy={busy} onClick={() => {
|
||||
if (window.confirm(`Delete this photo${m.alt ? ` (“${m.alt}”)` : ""}? It isn't used anywhere. This can't be undone.`)) {
|
||||
void run(async () => { await api(`/media/${m.id}`, { method: "DELETE" }); await reload(); }, "Deleted.");
|
||||
}
|
||||
}}><Trash2 className="h-4 w-4" aria-hidden />Delete</Btn>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
@@ -15,7 +15,7 @@ export default function Ministries() {
|
||||
{ key: "name", label: "Name", kind: "text", max: 120 },
|
||||
{ key: "summary", label: "In one line", kind: "text", max: 300, hint: "E.g. “Ages 3 to 12, every Sunday at 10:00.”" },
|
||||
{ key: "body", label: "More about it", kind: "textarea", max: 8000 },
|
||||
{ key: "imageId", label: "Photo", kind: "image" },
|
||||
{ key: "imageId", label: "Photo", kind: "image", frame: "ministry" },
|
||||
]} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -15,13 +15,14 @@ import {
|
||||
} from "lucide-react";
|
||||
import { api } from "@/admin/api";
|
||||
import { BLOCK_FIELDS, DataForm, SECTION_FIELDS } from "@/admin/fields";
|
||||
import { frameFor, type Framing } from "@/admin/framing";
|
||||
import { WithPreview } from "@/admin/LivePreview";
|
||||
import { ImagePicker } from "@/admin/media";
|
||||
import { Btn, cx, Field, inputClass, Loading, Notice, Panel, Tabs, Title, useAction, useAdmin } from "@/admin/ui";
|
||||
|
||||
type Section = { id: string; type: string; variant: string | null; hidden: boolean; data: Record<string, unknown>; updatedAt: string };
|
||||
type PageData = { id: string; kind: string; slug: string; title: string; seoTitle: string | null; description: string | null; navLabel: string | null; inNav: boolean; imageId: string | null; updatedAt: string; sections: Section[] };
|
||||
type Design = { home: { section: string; hidden: boolean }[] };
|
||||
type Design = { template: string; variants: Record<string, string>; home: { section: string; hidden: boolean }[] };
|
||||
|
||||
const HOME_ORDER = ["hero", "serviceTimes", "welcome", "ministries", "team", "events", "latestMessage", "invitation"];
|
||||
const LISTS: Record<string, string> = {
|
||||
@@ -48,8 +49,8 @@ const summary = (data: Record<string, unknown>) => {
|
||||
return null;
|
||||
};
|
||||
|
||||
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }: {
|
||||
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>;
|
||||
function SectionEditor({ type, title, fields, initial, onSave, hidden, extra, frame }: {
|
||||
type: string; title: string; fields: Parameters<typeof DataForm>[0]["fields"]; initial: Record<string, unknown>; frame?: Framing["frame"];
|
||||
onSave: (data: Record<string, unknown>) => Promise<unknown>; hidden?: React.ReactNode; extra?: React.ReactNode;
|
||||
}) {
|
||||
const [value, setValue] = useState(initial);
|
||||
@@ -73,7 +74,7 @@ function SectionEditor({ type, title, fields, initial, onSave, hidden, extra }:
|
||||
</div>
|
||||
{open && (
|
||||
<div className="space-y-4 border-t border-gray-100 p-4">
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} />
|
||||
<DataForm fields={fields} value={value} onChange={setValue} errors={errors} frame={frame} />
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<Btn kind="primary" busy={busy} onClick={() => run(() => onSave(value), "Saved as a draft.")}>Save</Btn>
|
||||
<Btn onClick={() => setOpen(false)}>Close</Btn>
|
||||
@@ -134,7 +135,7 @@ export default function EditPage() {
|
||||
const router = useRouter();
|
||||
const { data: page, error, setData } = useAdmin<PageData>(`/pages/${id}`);
|
||||
const isHome = page?.kind === "home";
|
||||
const design = useAdmin<{ design: Design }>(isHome ? "/design" : null);
|
||||
const design = useAdmin<{ design: Design }>("/design");
|
||||
const blocks = useAction();
|
||||
const remove = useAction();
|
||||
const [tab, setTab] = useState<"content" | "details">("content");
|
||||
@@ -171,7 +172,7 @@ export default function EditPage() {
|
||||
const s = page.sections.find((x) => x.type === type);
|
||||
const spec = SECTION_FIELDS[type];
|
||||
if (!spec) return null;
|
||||
return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}}
|
||||
return <SectionEditor key={type} type={type} title={spec.name} fields={spec.fields} initial={s?.data ?? {}} frame={(key, i) => frameFor(design.data?.design, type, key, i)}
|
||||
hidden={hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Not shown</span>}
|
||||
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/home/${type}`, { method: "PUT", body: { data, ifUpdatedAt: s?.updatedAt } }))} />;
|
||||
})}
|
||||
@@ -184,7 +185,7 @@ export default function EditPage() {
|
||||
const spec = BLOCK_FIELDS[s.type];
|
||||
if (!spec) return null;
|
||||
return (
|
||||
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data}
|
||||
<SectionEditor key={s.id} type={s.type} title={spec.name} fields={spec.fields} initial={s.data} frame={(key, i) => frameFor(design.data?.design, s.type, key, i)}
|
||||
hidden={s.hidden && <span className="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600"><EyeOff className="h-3 w-3" aria-hidden />Hidden</span>}
|
||||
onSave={async (data) => setData(await api<PageData>(`/pages/${id}/blocks/${s.id}`, { method: "PUT", body: { data, ifUpdatedAt: s.updatedAt } }))}
|
||||
extra={<>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { cookies, headers } from "next/headers";
|
||||
import { cache } from "react";
|
||||
import type { Image, Published, SiteContent, Template } from "./types";
|
||||
import type { Focus, Image, Published, SiteContent, Template } from "./types";
|
||||
|
||||
const api = (process.env.WEBSITE_API_URL || "http://127.0.0.1:5300").replace(/\/+$/, "");
|
||||
|
||||
@@ -57,8 +57,12 @@ export async function loadPublished(): Promise<Published | null> {
|
||||
return c.mode === "published" ? c : null;
|
||||
}
|
||||
|
||||
/** An image from a section's data (a media id), or null. */
|
||||
export const media = (site: Published, id: unknown): Image | null => (typeof id === "string" ? site.snapshot.media[id] ?? null : null);
|
||||
/** An image from a section's data (a media id), or null; placed as the section frames it (`data.framing`). */
|
||||
export const media = (site: Published, id: unknown, data?: Record<string, unknown>): Image | null => {
|
||||
const img = typeof id === "string" ? site.snapshot.media[id] ?? null : null;
|
||||
const focus = img && (data?.framing as Record<string, Focus> | undefined)?.[id as string];
|
||||
return img && focus ? { ...img, focus } : img;
|
||||
};
|
||||
|
||||
/** Per-template class names: `t(template, { heritage: "…", bold: "…" }, "fallback")`. */
|
||||
export const t = (template: Template, by: Partial<Record<Template, string>>, otherwise = "") => by[template] ?? otherwise;
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
/** Small building blocks every template uses. */
|
||||
import type { Image } from "./types";
|
||||
import type { Focus, Image } from "./types";
|
||||
|
||||
export const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
|
||||
|
||||
/**
|
||||
* How a photo sits in its frame (object-cover): the chosen point kept in view, zoomed around that
|
||||
* point. The frame clips it (overflow hidden). The admin's framing dialog draws it the same way.
|
||||
*/
|
||||
export function focusStyle(f: Focus | undefined): React.CSSProperties | undefined {
|
||||
if (!f) return undefined;
|
||||
const at = `${f.x}% ${f.y}%`;
|
||||
return f.zoom > 1 ? { objectPosition: at, transform: `scale(${f.zoom})`, transformOrigin: at } : { objectPosition: at };
|
||||
}
|
||||
|
||||
/**
|
||||
* An uploaded image at the size the screen needs (§3: responsive sizes in WebP and JPEG): the
|
||||
* browser picks from the `srcset`s by `sizes`. `alt` overrides the image's own (e.g. "" when it's
|
||||
@@ -12,7 +22,7 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a
|
||||
const img = (
|
||||
<img src={image.url} srcSet={image.srcset?.jpg} sizes={image.srcset ? sizes : undefined} alt={alt ?? image.alt}
|
||||
width={image.width ?? undefined} height={image.height ?? undefined}
|
||||
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} />
|
||||
loading={priority ? "eager" : "lazy"} fetchPriority={priority ? "high" : undefined} decoding="async" className={className} style={focusStyle(image.focus)} />
|
||||
);
|
||||
return image.srcset ? <picture><source type="image/webp" srcSet={image.srcset.webp} sizes={sizes} />{img}</picture> : img;
|
||||
}
|
||||
@@ -21,7 +31,12 @@ export function Picture({ image, className, sizes = "100vw", priority = false, a
|
||||
export function Img({ image, className, sizes = "(min-width: 768px) 50vw, 100vw", priority = false, ratio = "aspect-[4/3]" }: { image: Image | null; className?: string; sizes?: string; priority?: boolean; ratio?: string }) {
|
||||
return (
|
||||
<div className={cx("cc-frame", ratio, className)}>
|
||||
{image ? (
|
||||
{image && (image.focus?.zoom ?? 1) > 1 ? (
|
||||
// Zoomed: clipped inside the frame's mat (Heritage pads its frames), not over it.
|
||||
<div className="h-full w-full overflow-hidden" style={{ borderRadius: "var(--cc-radius-sm, 0)" }}>
|
||||
<Picture image={image} sizes={sizes} priority={priority} className="cc-img" />
|
||||
</div>
|
||||
) : image ? (
|
||||
<Picture image={image} sizes={sizes} priority={priority} className="cc-img" />
|
||||
) : (
|
||||
<div aria-hidden="true" className="h-full w-full bg-gradient-to-br from-brand/25 via-brand-tint to-accent/30" />
|
||||
|
||||
@@ -49,9 +49,9 @@ function Fullbleed({ d, site, children }: { d: HeroData; site: SectionProps["sit
|
||||
export function Hero({ section, site, template }: SectionProps) {
|
||||
const d = section.data as unknown as HeroData;
|
||||
const variant = section.variant ?? "photo";
|
||||
const imgs = (d.images ?? []).map((id) => media(site, id));
|
||||
const imgs = (d.images ?? []).map((id) => media(site, id, section.data));
|
||||
const first = imgs[0] ?? null;
|
||||
const video = media(site, d.videoId);
|
||||
const video = media(site, d.videoId, section.data);
|
||||
const services = (site.church?.serviceTimes ?? []).filter((s) => s.day === "sunday").map((s) => s.time);
|
||||
|
||||
if (variant === "text") {
|
||||
@@ -79,7 +79,7 @@ export function Hero({ section, site, template }: SectionProps) {
|
||||
if (template === "bold") {
|
||||
return (
|
||||
<section className="cc-section-hero grid bg-gray-950 text-white md:min-h-[80vh] md:grid-cols-2">
|
||||
<div className="relative min-h-[50vh] md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
|
||||
<div className="relative min-h-[50vh] overflow-hidden md:order-2">{first && <Picture image={first} sizes="(min-width: 768px) 50vw, 100vw" priority className="cc-img absolute inset-0" />}</div>
|
||||
<div className="flex flex-col justify-center px-6 pb-16 pt-32 sm:px-12"><Words d={d} light /></div>
|
||||
</section>
|
||||
);
|
||||
@@ -100,7 +100,7 @@ export function Hero({ section, site, template }: SectionProps) {
|
||||
return (
|
||||
<Fullbleed d={d} site={site}>
|
||||
<div className="grid h-full grid-cols-3 gap-1">
|
||||
{three.map((im, i) => <div key={i} className="relative">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
|
||||
{three.map((im, i) => <div key={i} className="relative overflow-hidden">{im ? <Picture image={im} sizes="34vw" priority={i === 0} className="cc-img absolute inset-0" /> : <div className="absolute inset-0 bg-brand/60" />}</div>)}
|
||||
</div>
|
||||
</Fullbleed>
|
||||
);
|
||||
|
||||
@@ -106,7 +106,7 @@ function Welcome(p: SectionProps) {
|
||||
</div>
|
||||
);
|
||||
if (p.section.variant === "pastor" && d.pastor) {
|
||||
const photo = media(p.site, d.pastor.photoId);
|
||||
const photo = media(p.site, d.pastor.photoId, p.section.data);
|
||||
return (
|
||||
<Section>
|
||||
<div className="cc-wrap grid items-center gap-10 md:grid-cols-[2fr_3fr]">
|
||||
@@ -124,7 +124,7 @@ function Welcome(p: SectionProps) {
|
||||
return (
|
||||
<Section>
|
||||
<div className={cx("grid items-center gap-10 md:grid-cols-2", p.template === "bold" ? "px-0 md:gap-0" : "cc-wrap")}>
|
||||
<Img image={media(p.site, d.imageId)} ratio={p.template === "bold" ? "aspect-square md:aspect-auto md:h-full md:min-h-[28rem]" : "aspect-[4/3]"} className={cx(p.template === "community" && "rounded-[2rem]", p.template === "bold" && "rounded-none")} />
|
||||
<Img image={media(p.site, d.imageId, p.section.data)} ratio={p.template === "bold" ? "aspect-square md:aspect-auto md:h-full md:min-h-[28rem]" : "aspect-[4/3]"} className={cx(p.template === "community" && "rounded-[2rem]", p.template === "bold" && "rounded-none")} />
|
||||
<div className={cx(p.template === "bold" && "px-6 py-10 sm:px-12")}>{words}</div>
|
||||
</div>
|
||||
</Section>
|
||||
@@ -390,7 +390,7 @@ function LatestMessage(p: SectionProps) {
|
||||
function Invitation(p: SectionProps) {
|
||||
const d = p.section.data as { heading: string; text: string | null; button: ButtonData; imageId: string | null };
|
||||
if (p.section.variant === "image") {
|
||||
const img = media(p.site, d.imageId);
|
||||
const img = media(p.site, d.imageId, p.section.data);
|
||||
return (
|
||||
<section className="cc-section cc-own-bg cc-dark relative isolate overflow-hidden bg-gray-900 text-white">
|
||||
{img && <Picture image={img} alt="" className="cc-img absolute inset-0 -z-10" />}
|
||||
@@ -436,7 +436,7 @@ function ImageTextBlock(p: SectionProps) {
|
||||
return (
|
||||
<Section>
|
||||
<div className="cc-wrap grid items-center gap-10 md:grid-cols-2">
|
||||
<Img image={media(p.site, d.imageId)} className={cx(p.template === "community" && "rounded-[2rem]")} />
|
||||
<Img image={media(p.site, d.imageId, p.section.data)} className={cx(p.template === "community" && "rounded-[2rem]")} />
|
||||
<div>{d.heading && <h2 className="cc-h2 mb-6">{d.heading}</h2>}<Paragraphs text={d.body} /><div className="mt-6"><Button button={d.button} /></div></div>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
@@ -7,7 +7,10 @@ import type { Church } from "@crosscode/contracts";
|
||||
export type Template = "heritage" | "bold" | "community" | "clean";
|
||||
|
||||
/** An uploaded image; `srcset` lists its responsive sizes (WebP and JPEG) when it has them. */
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string } };
|
||||
/** Where a photo sits in its frame: the point kept in view (0 to 100 from left and top) and its zoom (1 fills the frame). */
|
||||
export type Focus = { x: number; y: number; zoom: number };
|
||||
|
||||
export type Image = { url: string; alt: string; width: number | null; height: number | null; srcset?: { webp: string; jpg: string }; focus?: Focus };
|
||||
|
||||
export type Section = { type: string; variant: string | null; data: Record<string, unknown> };
|
||||
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
# Church App 1.0.0 — House of Prayer and the church in your pocket
|
||||
|
||||
Phase **6** of [ROADMAP-v3.md](./ROADMAP-v3.md) (§7, §9, §10, §11; decisions 4, 5, 8, 12, 13, 14,
|
||||
16, 20). Written 2026-11-30. **Decisions confirmed by Joshua on 2026-11-30** (see [Decisions](#decisions);
|
||||
he changed devotionals, sign-in length, 2FA, roles and the shared email and WhatsApp).
|
||||
|
||||
**Mockup:** [Church App 1.0 mockup](https://claude.ai/artifact/4MUbYPv6WuP8kfY5gRUnnd) (a Design
|
||||
canvas on claude.ai; private to Joshua unless shared from its Share menu). Seven phone screens and
|
||||
the admin, in the demo church's colours and the Warm font pairing; Play moves between them:
|
||||
|
||||
| Screen | Shows |
|
||||
|---|---|
|
||||
| Home | Greeting, the campaign, your next slot, today's prayer clock with the next gap, today's devotional, a pinned announcement |
|
||||
| House of Prayer | The 24-hour clock (§3): tap an hour for its details, Cover it / Join, the open hours as buttons |
|
||||
| Book a slot | Just once / every week / every day, length, reminder and channel, the 8-hour rule |
|
||||
| Me: my prayer | Renew for another year, a slot locked within 8 hours, Skip / Change / Stop, "I prayed" |
|
||||
| Ask for prayer | Prayer team only (default) or members after approval, emergency numbers |
|
||||
| Devotional | The verse's text and translation, Read in YouVersion, sent by WhatsApp at 06:00 |
|
||||
| Events | An event from Cross Events with Register on the Events site, the App's own simple events |
|
||||
| Admin dashboard | The Website admin's layout: stat cards, the week's prayer wall, the approval queue, recent activity |
|
||||
|
||||
**What the App is:** a church-branded **web app** (PWA) at `app.<church's address>`, added to the
|
||||
home screen, with no app-store release. Anyone can browse its public content; personal actions
|
||||
(booking a prayer slot, a prayer request, notification settings) need sign-in through the church's
|
||||
Accounts. Its headline is the **House of Prayer**: a 24/7 prayer wall the church fills together.
|
||||
1.0 also has **announcements**, **devotionals** and **events** (simple events plus the feed). Its
|
||||
look comes from the church profile (colours, logo, fonts, corners) and it shares the footer and
|
||||
links with the Website and Cross Events, so the three feel like one church.
|
||||
|
||||
**Where things stand:** every earlier phase is released and rolled out, including the Church Website
|
||||
at Hope Family Church and a second church (confirmed by Joshua 2026-11-30).
|
||||
|
||||
**Who uses 1.0:** the demo church (cross-demo2, Acacia Hill) first, then Hope Family Church. Then
|
||||
it goes on sale (crosscode-site, ROADMAP §9).
|
||||
|
||||
**Done when:**
|
||||
|
||||
- `app@1.0.0`, `contracts@1.20.0` (released 2026-11-30), `contracts@1.21.0` (released 2026-11-30), `accounts@1.9.0`,
|
||||
`events@3.8.0`, `website@1.8.0`, `agent@1.7.0` and Hub `v2.26.0` are tagged; the Hub installs
|
||||
the App from New install (after Accounts) and lists its releases.
|
||||
- On a demo client, **Load a demo scenario** in the Hub loads Accounts, Events, the Website and
|
||||
the App with the same church, people and events, in one step (§12, "Demo scenarios").
|
||||
- The Hub holds 3 months of Cross Code devotionals (written or imported from CSV), and an App set to
|
||||
"From Cross Code" shows and sends them.
|
||||
- A member can add the App to their home screen (Android and iPhone), sign in once, book a one-off
|
||||
or recurring prayer slot, get its reminder by email or WhatsApp, and change or cancel it within
|
||||
the rules.
|
||||
- The coverage view updates live when someone else books, and never shows a name to anyone but
|
||||
the prayer team.
|
||||
- A prayer request stays private unless its submitter chose otherwise, and nothing shared reaches
|
||||
members before a coordinator approves it.
|
||||
- Public pages pass the §11 SEO checks; every prayer page is `noindex`; axe has no violations;
|
||||
Lighthouse (mobile): SEO 100, accessibility 95+, performance 90+.
|
||||
- The App reports its active-member band to the Hub, and the Hub bills the App tier from it.
|
||||
- crosscode-site sells it (ROADMAP §9, "Updating crosscode-site").
|
||||
|
||||
## Contents
|
||||
|
||||
1. [The shape](#1-the-shape)
|
||||
2. [Foundation: PWA, branding, sign-in](#2-foundation-pwa-branding-sign-in)
|
||||
3. [House of Prayer](#3-house-of-prayer)
|
||||
4. [Prayer requests](#4-prayer-requests)
|
||||
5. [Announcements](#5-announcements)
|
||||
6. [Devotionals](#6-devotionals)
|
||||
7. [Events](#7-events)
|
||||
8. [Notifications: email and WhatsApp](#8-notifications-email-and-whatsapp)
|
||||
9. [Content: shared, Website-owned and App-only](#9-content-shared-website-owned-and-app-only)
|
||||
10. [Admin, roles and active members](#10-admin-roles-and-active-members)
|
||||
11. [Privacy and POPIA](#11-privacy-and-popia)
|
||||
12. [Hub, licence and servers](#12-hub-licence-and-servers)
|
||||
13. [What changes in each repo](#13-what-changes-in-each-repo)
|
||||
14. [Testing](#14-testing)
|
||||
15. [Releasing and rolling it out](#15-releasing-and-rolling-it-out)
|
||||
16. [Decisions](#decisions)
|
||||
17. [Not in 1.0](#not-in-10)
|
||||
18. [Still open](#still-open)
|
||||
|
||||
## 1. The shape
|
||||
|
||||
`apps/app`, the same stack as the Website (roadmap decision 8): an **Express + Prisma + pg-boss
|
||||
backend** (TypeScript) and a **Next.js frontend**, one PostgreSQL database, on one address with
|
||||
`/api` to the backend (`location ^~ /api/` in FastPanel, HANDOVER "FastPanel sites").
|
||||
|
||||
```
|
||||
visitor ─► app.acaciahill.co.za ─► Next.js: public content (announcements, devotionals,
|
||||
events, coverage only), server-rendered, cached
|
||||
member ──► sign in through Accounts (@crosscode/auth-client) ─► book slots, requests, settings
|
||||
phone ───► manifest.webmanifest + service worker: home-screen icon, offline shell, last content
|
||||
|
||||
backend: public API (/api/v1/…), member API (/api/v1/me/…), admin API (/api/v1/admin/…),
|
||||
live coverage (/api/v1/prayer/stream, server-sent events), event feed (/api/links/v1/*),
|
||||
Hub client (protocol v2, product "app"), jobs (reminders, renewals, feed sync,
|
||||
active members, announcement and devotional sends)
|
||||
|
||||
Accounts ── crosscode.church/1 (name, short name, icon, colours, style, timezone, links)
|
||||
Events / Website ── crosscode.event/1 (the event feed, both directions)
|
||||
```
|
||||
|
||||
- **Mobile first.** Every member screen is designed at phone width first, with a bottom tab bar
|
||||
(Home, Prayer, Events, Devotional, Me) and the church's colours. On a desktop the same screens
|
||||
sit in a centred column. The admin (`/admin`) is designed for a laptop and works on a phone.
|
||||
- **Shared packages:** `@crosscode/ui` (brand style, fonts, `ChurchFooter`, product links),
|
||||
`@crosscode/seo`, `@crosscode/auth-client`, `@crosscode/contracts`. Ports
|
||||
`app` (web) and `app-api` in the frp port list, as the Website's.
|
||||
- **Timezone:** everything about prayer slots is in the **church's timezone** (`timezone` in the
|
||||
profile). Times are stored in UTC; slot boundaries are computed in the church's zone, so a
|
||||
church outside South Africa with daylight saving still gets whole hours.
|
||||
|
||||
## 2. Foundation: PWA, branding, sign-in
|
||||
|
||||
- **Installable** (P1): a `manifest.webmanifest` built from the profile: `name`, `short_name`
|
||||
(the profile's `shortName`, else the name cut to 12 characters), icons from `branding.iconUrl`
|
||||
(resized to 192 and 512, with a maskable version on the primary colour), `theme_color` = primary,
|
||||
`display: standalone`, `start_url: /?source=homescreen`. A church without an icon gets one made
|
||||
from its initials on its primary colour (the share-image generator from `packages/seo`).
|
||||
- **Add to home screen:** a dismissible card on Home for visitors who haven't installed it. Android
|
||||
and desktop Chrome use the browser's install prompt; on an iPhone the card shows the Share →
|
||||
"Add to Home Screen" steps (iOS has no prompt). Dismissing it hides it for 30 days.
|
||||
- **Offline** (P2): the service worker caches the app shell, the church's details, today's and
|
||||
the last 7 days' devotionals, the latest announcements, upcoming events and the member's own
|
||||
commitments. Offline, those show with "You're offline: showing what was saved"; booking,
|
||||
cancelling and requests need a connection and say so. Nothing personal is cached for someone
|
||||
who is signed out. **No push notifications** (decision 13), so the service worker never asks
|
||||
for notification permission.
|
||||
- **Branding:** colours, logo, font pairing and corners from the profile, through
|
||||
`@crosscode/ui`'s `brandAttributes` and the palette builder (contrast checked, as the Website).
|
||||
Header: the logo (or icon and short name) and the account menu. Footer on public pages:
|
||||
`ChurchFooter`, with links to the church's Website and Events.
|
||||
- **Sign-in through Accounts**, returning to the exact screen (ROADMAP §3): "Book this slot" when
|
||||
signed out goes to Accounts and comes back to the same slot with the sheet open.
|
||||
- **Staying signed in** (decision 7): a sign-in lasts **8 days**. Opening the App within those
|
||||
8 days renews it for another 8, up to **90 days** from the sign-in; after that, or after 8 days
|
||||
away, the member signs in again. (A rolling refresh token with an absolute limit; signing out
|
||||
anywhere, or a password change in Accounts, ends it.)
|
||||
- **2FA for every role above Member** (decision 7): Owner, Church admin, Content admin,
|
||||
Devotional writer, Prayer coordinator and Pastoral care must have 2FA (`acr_values=mfa`) to open
|
||||
the admin or anything their role adds. Someone given such a role without 2FA is asked to set it
|
||||
up in Accounts first. Members don't need it.
|
||||
- **Modules** (each can be switched off, ROADMAP §7): House of Prayer, Prayer requests,
|
||||
Announcements, Devotionals, Events. Home and the tab bar only show what's on. The list goes in
|
||||
the heartbeat (`modules`, already in `appStatsSchema`).
|
||||
|
||||
## 3. House of Prayer
|
||||
|
||||
### The prayer wall
|
||||
|
||||
One **prayer wall** for the whole church, prayed from anywhere (P4). The day is cut into slots of
|
||||
the church's slot length (**60 minutes** by default; 15 or 30 can be chosen, decision 12).
|
||||
|
||||
- **Coverage view: a 24-hour clock** (decision 2). One dial for the chosen day (today first, swipe
|
||||
or pick a date), midnight at the top and noon at the bottom, the night half drawn darker. Each
|
||||
slot is a segment of the ring, shaded by how many people have committed; open slots are drawn
|
||||
as dashed outlines; the member's own slots carry a gold edge; a hand points at the time now. The
|
||||
middle shows the time and "21 of 24 hours covered". Tapping a segment shows that slot under the
|
||||
dial (time, how many, **Cover it** or **Join**). The open slots are also listed below as buttons,
|
||||
so the view works with a keyboard and a screen reader. With 15- or 30-minute slots the ring has
|
||||
96 or 48 segments.
|
||||
- **Live:** the view subscribes to `/api/v1/prayer/stream` (server-sent events) and updates when
|
||||
anyone books or cancels. If the stream drops, it polls every 30 seconds. The backend sends
|
||||
`X-Accel-Buffering: no` and a comment every 25 seconds, so FastPanel's nginx and frp pass it on
|
||||
without buffering or timing out, with **no change to the FastPanel config**.
|
||||
- **People per slot** (P5): there's no limit on how many people commit to a slot. The church sets
|
||||
a **target** (1 by default); a slot counts as covered when it has at least one person, and the
|
||||
view shows "2 of 3" against the target where the target is more than 1.
|
||||
- **Names:** the public view and members see **counts only, never names** (ROADMAP §7). A member
|
||||
sees "You" on their own slots. Prayer coordinators see names in the admin, and every view of
|
||||
them goes in the access log.
|
||||
|
||||
### Commitments
|
||||
|
||||
| | Default (decision 12) | The church can |
|
||||
|---|---|---|
|
||||
| Slot length | 1 hour | choose 15, 30 or 60 minutes |
|
||||
| Book ahead | up to 12 months | shorten it |
|
||||
| Recurring | daily or weekly, up to 12 months from the day of booking | shorten the maximum |
|
||||
| Cancelling | up to 8 hours before the slot | change the hours (0–48) |
|
||||
|
||||
- **Booking:** tap a slot → a sheet: **Just this once**, **Every week** (on that weekday) or
|
||||
**Every day**, an end date (12 months at most, the default), several slots in a row (e.g. 02:00
|
||||
for 2 hours), a reminder (below) and an optional "where I'll pray" note for themselves.
|
||||
- **Changing:** one occurrence ("Skip 14 December") or the whole commitment (time, days, end
|
||||
date). The cancel rule applies to every occurrence inside the window: within 8 hours it can't
|
||||
be skipped or cancelled in the App, and the member sees who to contact (the prayer coordinator's
|
||||
name and how to reach them, from Settings → House of Prayer).
|
||||
- **Renewing:** 14 days before a recurring commitment ends, the member gets an email or WhatsApp
|
||||
(their choice of channel) with **Renew for another year**, one tap with no sign-in needed (a
|
||||
signed, single-use link that expires with the commitment). A second reminder 3 days before.
|
||||
- **Reminders** (P6): per commitment, *none*, *15 minutes before*, *1 hour before* (the default)
|
||||
or *the evening before at 20:00*, sent on the member's chosen channel for prayer reminders.
|
||||
Night-time slots are exactly where reminders matter, so they're sent at night too.
|
||||
- **"I prayed":** after a slot ends, the member can mark it in the App or from a link in the
|
||||
reminder. It's **self-reported**, labelled that way everywhere ("12 hours marked as prayed,
|
||||
self-reported"), shown to the member, and counted (as a number only) for the prayer team and
|
||||
campaigns. Never a ranking.
|
||||
- **Stored as rules, not rows:** a commitment is a rule (start, length, recurrence, end) plus its
|
||||
skips; the occurrences in any window are worked out from the rules, so a year of daily slots
|
||||
isn't 365 rows, and the coverage view is computed per day and cached until a booking changes it.
|
||||
|
||||
### Campaigns and testimonies
|
||||
|
||||
- **Campaigns** (P7): a time-bound focus, e.g. "21 days of prayer" from 5 to 25 January, with a
|
||||
title, description, image, optional target ("Every hour covered") and its own slot target. During
|
||||
it, Home and the Prayer tab lead with the campaign: days left, collective coverage, hours marked
|
||||
as prayed (self-reported). **No rankings, no individual totals** (ROADMAP §7).
|
||||
- **Testimonies:** members can share what God has done ("answered prayer"), optionally linked to a
|
||||
campaign. Every testimony is **moderated before anyone sees it**, shows the first name or
|
||||
"Anonymous" (the member's choice), and can be removed by its author at any time.
|
||||
|
||||
## 4. Prayer requests
|
||||
|
||||
- **Who sees it** (P8), chosen by the submitter, **private by default**:
|
||||
|
||||
| Choice | Who sees it |
|
||||
|---|---|
|
||||
| **The prayer team only** (default) | Prayer coordinators (and Pastoral care, for escalations) |
|
||||
| **Members of the church** | Signed-in members of the App, after a coordinator approves it |
|
||||
|
||||
Nothing is ever public to signed-out visitors, and no prayer page is indexable (ROADMAP §11).
|
||||
Groups come in 1.x with connect groups.
|
||||
- **Name or anonymous:** for "Members of the church", the submitter chooses whether their first
|
||||
name shows. The prayer team always sees who sent it (so they can follow up), unless the church
|
||||
turns on fully anonymous requests (P9, off by default).
|
||||
- **Moderation:** shared requests wait in a queue. A coordinator can **approve**, **redact** (edit
|
||||
out names or details, the submitter told what changed), or **remove** (with a reason sent to the
|
||||
submitter). Every action is in the audit log.
|
||||
- **Safeguarding:** any coordinator can **escalate** a request (danger, abuse, self-harm). It goes
|
||||
at once, by email and WhatsApp, to the church's safeguarding contacts (people with the Pastoral
|
||||
care role, Settings → Safeguarding), leaves the shared list, and shows the submitter nothing
|
||||
different. The App shows emergency numbers (set by the church; South African defaults:
|
||||
Lifeline 0861 322 322, SADAG 0800 567 567, Childline 116) on the request form.
|
||||
- **Praying for it:** members tap **I prayed** on shared requests; the submitter sees the count
|
||||
("14 people prayed"), not who.
|
||||
- **Updates and closing:** the submitter can add an update ("Answered!") or close it. Requests
|
||||
close themselves after **30 days** (the church can choose 7–90) and are deleted 12 months after
|
||||
closing (P10).
|
||||
- **Never used for analytics or AI** (ROADMAP §7): no AI buttons near prayer, no request text in
|
||||
stats or the heartbeat, no request text in emails beyond "You have a new prayer request" with a
|
||||
link.
|
||||
|
||||
## 5. Announcements
|
||||
|
||||
- Title, text (sanitised markdown), image, optional button (a link), campus (or all), **who sees
|
||||
it** (everyone, or signed-in members only), **pin** to the top, a publish time (now or later)
|
||||
and an end date.
|
||||
- **Also send it** (optional, per announcement): by email and/or WhatsApp to members who chose to
|
||||
receive announcements, at the publish time. Sends are queued and rate-limited as Events'
|
||||
scheduled emails.
|
||||
- Public announcements are server-rendered pages with the §11 baseline; members-only ones are
|
||||
`noindex` and not in the sitemap.
|
||||
|
||||
## 6. Devotionals
|
||||
|
||||
Decision 1: **two sources**, chosen in Settings → Devotionals:
|
||||
|
||||
1. **From Cross Code.** Devotionals written by Cross Code in the Hub, the same for every church that
|
||||
chooses them.
|
||||
2. **Our own.** The church's Devotional writers write them in the App's admin.
|
||||
|
||||
- **A devotional:** date, title, **Bible passage** (reference, translation and the passage's text),
|
||||
the devotional's text, an optional prayer and an author. The day's devotional shows on Home at
|
||||
midnight in the church's timezone. A day without one shows the most recent.
|
||||
- **The verse is shown and linked** (decision 5): the passage's text is shown in full above the
|
||||
devotional, with its translation and copyright line, and **Read in YouVersion** opens it at
|
||||
`bible.com` (the passage in that translation; YouVersion's app opens instead where it's
|
||||
installed). The YouVersion link is built from the reference and the translation's YouVersion id.
|
||||
- **Translations** (decision 10): each devotional, from Cross Code or the church's own, picks one
|
||||
of seven:
|
||||
|
||||
| Id | Translation | Language |
|
||||
|---|---|---|
|
||||
| `NLT` | New Living Translation | English |
|
||||
| `ESV` | English Standard Version | English |
|
||||
| `NIV` | New International Version | English |
|
||||
| `NKJV` | New King James Version | English |
|
||||
| `KJV` | King James Version | English |
|
||||
| `AFR53` | Afrikaans 1933/1953-vertaling | Afrikaans |
|
||||
| `AFR83` | Afrikaans 1983-vertaling | Afrikaans |
|
||||
|
||||
The list lives in the contracts with each one's YouVersion id and copyright line, so the Hub,
|
||||
the App and the CSV import agree; an id never changes once released, and more can be added.
|
||||
The Afrikaans pair is the proposal (the 2020-vertaling or the Nuwe Lewende Vertaling could
|
||||
replace one).
|
||||
- **Licensing:** every one but the KJV is under copyright (the Afrikaans ones with the Bible
|
||||
Society of South Africa). Each publisher lets its text be quoted within limits (a number of
|
||||
verses, never a whole book, with its notice), so a devotional quotes **the passage it's about,
|
||||
not whole chapters**, and the App always shows that translation's copyright line under the
|
||||
verse. The Hub and the App warn when a passage is longer than 25 verses. Before Cross Code's
|
||||
devotionals go out to churches, check each publisher's terms for use in an app (or ask for
|
||||
permission); the church is responsible for its own.
|
||||
- **The Hub** (Hub 2.26.0, decision 1): a **Devotionals** page to write and schedule Cross Code's
|
||||
devotionals **up to 3 months ahead**, with a calendar showing which days are filled, and an
|
||||
**Import CSV** button: upload, a preview with every row checked (date, required fields, a
|
||||
reference YouVersion understands, a date already taken), then import the valid rows, replacing
|
||||
or skipping days already filled. Columns: `date, title, passage, translation, passage_text,
|
||||
body, prayer, author`. A template CSV can be downloaded from the page.
|
||||
- **Getting them to the App:** an App on "From Cross Code" fetches the next 3 months from the Hub
|
||||
(`GET /api/v2/devotionals`, with its licence token) once a night and keeps them, so a Hub outage
|
||||
changes nothing (ROADMAP §1, rule 2). Edits in the Hub reach the App by the next night, or at
|
||||
once with **Sync now** in the App's settings. The format is `crosscode.devotional/1`
|
||||
(contracts 1.20.0), so a church's own and Cross Code's devotionals look the same.
|
||||
- **Our own:** the same fields and the same CSV import in the App's admin, scheduled as far ahead as
|
||||
the church likes.
|
||||
- **Sent out** (decision 5): by **email and WhatsApp**, at the time the member chooses (06:00 by
|
||||
default): the title, the verse (reference and text) and a link to the full devotional in the App.
|
||||
Members turn it on and pick the channel; the App offers it the first time they sign in.
|
||||
- Public by default, with `Article` JSON-LD; a devotional can be members-only.
|
||||
- An **archive** (by month) and "Today" always first.
|
||||
|
||||
## 7. Events
|
||||
|
||||
As the Website (WEBSITE-1.0-PLAN §8): **simple events** made in the App (title, date and time,
|
||||
place, description, image, optional link; roadmap decision 4), and **the event feed** (Settings →
|
||||
Linked products: "Publish my events", "Show events from"). Events from Cross Events show with
|
||||
**Register on the Events site**, which opens Cross Events; registering and paying stays there.
|
||||
Imported events carry `<link rel="canonical">` to their origin and aren't in the App's sitemap.
|
||||
|
||||
## 8. Notifications: email and WhatsApp
|
||||
|
||||
Email and WhatsApp only (decision 13). Each member chooses, per kind, **email, WhatsApp, both or
|
||||
off**:
|
||||
|
||||
| Kind | Default |
|
||||
|---|---|
|
||||
| Prayer slot reminders | the channel chosen when booking (WhatsApp if they have a verified number, else email) |
|
||||
| Renewing a recurring commitment | the same as reminders, and can't be turned off while they have one |
|
||||
| Prayer request updates (approved, someone prayed, a reply) | email |
|
||||
| Announcements the church sends | off until the member turns them on |
|
||||
| Today's devotional | offered at first sign-in; email, WhatsApp or both (§6) |
|
||||
|
||||
- **Sending** (decision 4): **one set of email and WhatsApp credentials for the whole church**, as
|
||||
Events and Accounts share them today (Events 3.1.0: Settings → Sign-in copies Events' SMTP and
|
||||
WAWP into Accounts through the signed link, `messaging.*` in `crosscode.identity-request/1`).
|
||||
The App never asks for its own: at Connect it takes the church's settings from Accounts over the
|
||||
same signed link (a new `messaging.get`, contracts 1.20.0, the password and token encrypted with
|
||||
the link's secret), and fetches them again when Accounts says they changed. Settings → Email and
|
||||
WhatsApp shows which address and number it sends from, with **Send a test**; changing them is
|
||||
done where they're kept (Events or Accounts). A church without Events sets them once in
|
||||
Accounts.
|
||||
- **STOP replies** (decision 11): a WAWP number sends replies to one webhook address, today Events'.
|
||||
**Accounts keeps the WhatsApp opt-out for every product**, as it already holds the consent:
|
||||
whichever site receives a STOP tells Accounts (a signed `whatsapp.optout` over the link), Accounts
|
||||
sends `user.updated` to every linked product, and none of them sends that person WhatsApp again
|
||||
until they turn it back on. A church without Events points the webhook at Accounts.
|
||||
- **Phone numbers and consent** come from Accounts (the verified number and the news consent);
|
||||
reminders and renewals are things the member asked for, so they don't need the news consent.
|
||||
- Every send is counted for the heartbeat (`messages.email30d`, `whatsapp30d`).
|
||||
|
||||
## 9. Content: shared, Website-owned and App-only
|
||||
|
||||
The Website plan left one question for this plan (WEBSITE-1.0-PLAN, "Still open"): whether
|
||||
leaders, ministries and giving move into `crosscode.church/1`. **Decision 6: nothing moves in App
|
||||
1.0; only the basic church details are shared.** None of 1.0's modules needs them. When the App gets sermons and giving links (1.x), it
|
||||
**reads them from the Website** through a feed, as events work today (the origin owns a record;
|
||||
ROADMAP §1 rule 4), and a church without a Website enters them in the App. The profile stays the
|
||||
place for facts every product shows (name, logo, colours, service times, contact).
|
||||
|
||||
| Shared: `crosscode.church/1` (Accounts) | App-only |
|
||||
|---|---|
|
||||
| Name, short name, icon, colours, style, timezone, contact, service times, links (the App's address arrives through Connect, as the Website's) | Prayer wall settings, commitments, campaigns, testimonies, prayer requests, announcements, devotionals, simple events, notification preferences, roles |
|
||||
|
||||
The App's admin links to Accounts → Church profile for shared facts (no editing them from the App
|
||||
in 1.0).
|
||||
|
||||
## 10. Admin, roles and active members
|
||||
|
||||
**Admin** (`/admin`): a dashboard with a setup checklist (check the church's details and icon,
|
||||
set the prayer wall rules, add prayer coordinators, a first announcement, **share the App**: its
|
||||
link and a printable poster with a QR code), this week's coverage and the gaps, requests waiting;
|
||||
House of Prayer (rules, coverage by day and week, bookings with names, campaigns, testimonies);
|
||||
Prayer requests (queue, escalations); Announcements; Devotionals; Events; Members; Settings
|
||||
(modules, email and WhatsApp, safeguarding contacts and emergency numbers, linked products,
|
||||
background jobs); Audit log; Access log.
|
||||
|
||||
**Roles** (held in the App; ROADMAP §7, decision 7). A person can have several. Every role but
|
||||
Member needs 2FA (§2):
|
||||
|
||||
| Role | Can |
|
||||
|---|---|
|
||||
| Owner | Everything, including roles and the licence |
|
||||
| Church admin | Everything but the licence and Owners |
|
||||
| Content admin | Announcements and events |
|
||||
| Devotional writer | Devotionals: write, schedule, import CSV, the source setting (§6) |
|
||||
| Prayer coordinator | The prayer wall (rules, bookings with names, booking on behalf of a member), campaigns, testimonies, prayer request moderation and escalation |
|
||||
| Pastoral care | Escalated prayer requests and the safeguarding contacts (pastoral care itself in 1.x); sees requests sent to the prayer team |
|
||||
| Member | Everyone signed in: book, request, testify, settings. No 2FA needed |
|
||||
|
||||
**The first Owner** as the Website (its decision 17): whoever signs in with the church's admin email
|
||||
from the Hub (`HUB_ADMIN_EMAIL`), verified in Accounts, while the App has no Owner.
|
||||
|
||||
**Active members** (ROADMAP §10, billing): an account that **used the App signed in** on any day
|
||||
in the last 90 days. The App records the date (at most one write per member per day) and reports
|
||||
the **band** in the heartbeat (`activeMembers90d`, already in contracts). Admins see the number and
|
||||
the band in Settings → Licence. Visitors browsing signed out never count.
|
||||
|
||||
## 11. Privacy and POPIA
|
||||
|
||||
- **Prayer requests are special personal information** (religious beliefs, often health: POPIA
|
||||
s26). The church may process them as a religious body for its members (s28), with the
|
||||
submitter's choice: the request form says who will see it, and the privacy notice (Accounts')
|
||||
gets an App paragraph. Coordinators' access is in the access log.
|
||||
- **Download my data** (`user.export`): the App's part has the member's commitments, "I prayed"
|
||||
marks, prayer requests and updates, testimonies and notification settings.
|
||||
- **Delete my account** (`user.deleted`): future commitments are removed (the slots open up),
|
||||
past ones stay only as counts in coverage history, requests and testimonies are deleted, and the
|
||||
member's roles go.
|
||||
- **Church export** (uninstall, `crosscode.church-export/1`): an `app` section with the content,
|
||||
commitments, campaigns and (encrypted with the rest, decision 31) prayer requests, plus uploads.
|
||||
- No analytics or third-party scripts; fonts self-hosted; YouTube or Spotify embeds (none in 1.0)
|
||||
would load only on click.
|
||||
|
||||
## 12. Hub, licence and servers
|
||||
|
||||
- **Hub protocol v2, product `app`.** `appStatsSchema` is already in the contracts (active-member
|
||||
band, modules, coverage of the last 7 days, active commitments, announcements, messages). An App
|
||||
licence needs the church's Accounts, installed first.
|
||||
- **Hub 2.26.0:** New install offers the App; release sync for `app@` tags and
|
||||
`apps/app/WHATS-NEW.md`; its env template; the App's tiers already in `tiers.ts` (Mustard Seed to
|
||||
Network) used for billing, with the band from the heartbeat shown on the install and a
|
||||
**renewal check** (the tier is checked once a year at renewal, ROADMAP §10) that flags an install
|
||||
whose band is above its tier; the FastPanel email for `app.`; the App in Jobs' product filter
|
||||
(already) and demo data; and **Devotionals** (§6): write and schedule up to 3 months ahead, the
|
||||
calendar, Import CSV with its preview, and `GET /api/v2/devotionals` for App installs (licence
|
||||
token, App licences only).
|
||||
- **Contracts 1.20.0:** `app` in `DEMO_PRODUCTS`; the `app` section of the church export; the
|
||||
App's modules list (`APP_MODULES`); `crosscode.devotional/1` and the devotionals reply; the CSV
|
||||
columns and row checks (shared by the Hub and the App); `messaging.get` for the App (§8); the
|
||||
translation list with YouVersion ids and copyright lines. Nothing breaking.
|
||||
- **Accounts 1.9.0:** answers `messaging.get` for a linked product, and tells linked products
|
||||
when the messaging settings change; keeps the **WhatsApp opt-out** for every product
|
||||
(`whatsapp.optout` in, `user.updated` out) and can take the WAWP webhook itself (§8).
|
||||
- **Events 3.8.0:** a STOP received by Events is passed to Accounts, and Events reads the opt-out
|
||||
from Accounts' `user.updated` (§8).
|
||||
- **`crosscode`:** `scripts/products/app.sh` with the same hooks as the Website (`app` is already
|
||||
in `PRODUCT_ORDER`), `app.env.template.json` (the env template in three places, HANDOVER "A new
|
||||
.env variable"), `crosscode add <church> app`.
|
||||
- **Agent 1.7.0:** `seed-demo` for `app` and `accounts` (1.6.0 only passes `website` on to
|
||||
`crosscode demo`), and demo scenarios (below).
|
||||
- **Accounts, otherwise:** Connect already accepts the App as a client (`CLIENT_PRODUCTS`) and the
|
||||
profile already has `links.app`. The Website's and Events' headers and `ChurchFooter` show "App"
|
||||
as soon as the link is there.
|
||||
- **Demo church:** `npm run demo` loads Acacia Hill (fictional people only): a prayer wall with
|
||||
three months of commitments and a few gaps, a campaign, testimonies, devotionals, announcements
|
||||
and events, for screenshots and the Hub's demo sites.
|
||||
|
||||
### Demo scenarios (requirement added by Joshua 2026-11-30)
|
||||
|
||||
Today each product loads its own demo on its own (Events: 4 profiles, the Website: 8 by template,
|
||||
the App: Acacia Hill), and nothing makes them the same church. A **demo scenario** is a preset
|
||||
combination: one choice on a demo client in the Hub loads **every product the client has** with
|
||||
data that describes **the same church**, so a demo shows the three products working together.
|
||||
|
||||
- **Each scenario is its own church** (Joshua, 2026-11-30): a scenario load **replaces the
|
||||
church profile in Accounts** with the scenario's own, which a single-product demo never does (the
|
||||
Website's demo keeps the profile and only uses the church's name). It's a demo client, so nothing
|
||||
real is lost; the profile before the load goes in the backup taken first. Each scenario has:
|
||||
- a name, short name and a **logo and icon** of its own (made for the demo, a simple mark and
|
||||
wordmark per church, never a real church's), drawn as SVG by `@crosscode/demo` (Accounts
|
||||
1.9.0). Accounts serves them itself (`/api/demo-assets/<scenario>/logo.svg`, `icon.svg`), since
|
||||
its profile holds addresses, not uploads;
|
||||
- its people, also in `@crosscode/demo` (`demoPeople`), with the same account id in every
|
||||
product (`demoId`), so each product's loader builds around the same people;
|
||||
- colours, font pairing, corners and the Website template's style that suit it;
|
||||
- a street address, campuses, service times, phone, email (`@example.com`) and social links
|
||||
(to `example.com` addresses), a timezone, and the product links to the client's installs;
|
||||
- photos from the Website's demo set for that profile (as now), used in Events and the App too.
|
||||
- **What "aligned" means:** in one scenario, every product has
|
||||
- the same church profile in Accounts, as above, which Events, the Website and the App all read;
|
||||
- the same people, one account each in Accounts (all at `@example.com`, password `Demo@1234`):
|
||||
the pastor who leads on the Website, runs an Events registration and is Owner in the App; a
|
||||
prayer coordinator who also serves on an Events roster; members who register for events and
|
||||
book prayer slots;
|
||||
- the same events: made in Events (and the App's or Website's simple events where the scenario
|
||||
has them), shown in the others through the event feed, never copied;
|
||||
- the same campuses throughout (one, or three for the multi-campus scenario);
|
||||
- content that fits the church: a prayer campaign before its conference, announcements about its
|
||||
events, messages from its pastor.
|
||||
- **The eight scenarios** (Joshua, 2026-11-30: one per Website demo profile; more in 1.x). The
|
||||
key is the Website profile's. Events' 4 profiles become 8, one per church (the column says which
|
||||
kind each is built from). All names are fictional:
|
||||
|
||||
| Scenario | Church | Website | Events (built from) | App |
|
||||
|---|---|---|---|---|
|
||||
| `heritage-parish` | **St Columba's**: a 120-year-old parish church, small and older, Sunday 09:00 | `heritage-parish` | `small`: carol service, harvest festival, a funeral-tea roster | a quiet wall (about 10 of 24 hours), Cross Code's devotionals in NKJV, a Lent campaign |
|
||||
| `heritage-city` | **Grace Cathedral**: city centre, three Sunday services, lunchtime prayer | `heritage-city` | `events`: a concert series, ticketed Easter services | full in office hours with gaps at night, a weekday lunchtime focus, announcements per service |
|
||||
| `bold-youth` | **Ignite Church**: young and music-led | `bold-youth` | `events`: a youth conference with paid registration, a worship night | a 21-day campaign before the conference, testimonies, WhatsApp reminders, NLT devotionals |
|
||||
| `bold-plant` | **Harbour City**: a 2-year-old plant in a school hall | `bold-plant` | `small`: launch Sunday, a newcomers' lunch | a wall still filling up (the admin's setup checklist half done), the pastor's own devotionals |
|
||||
| `community-family` | **Acacia Hill**: a family church (cross-demo2, the mockup's church) | `community-family` | `ministry`: kids' club, Alpha, family camp, volunteer rosters | full with a few gaps (as in the mockup), a 21-day campaign, members' requests waiting for approval |
|
||||
| `community-town` | **Karoo Gemeenskapskerk**: a country-town church, mostly Afrikaans | `community-town` | `small`: a bazaar, a prayer breakfast | AFR83 devotionals of its own, 30-minute slots, the area's emergency numbers |
|
||||
| `clean-modern` | **Northpoint**: a contemporary church of about 600 | `clean-modern` | `ministry`: courses, groups launch, serve teams | every hour covered, target 2 per slot, Cross Code's devotionals, announcements by WhatsApp |
|
||||
| `clean-campus` | **Riverside**: three campuses near the university | `clean-campus` | `multicampus`: student welcome week at one campus, a combined worship night | one wall for three campuses, announcements per campus, students on the 02:00 slots |
|
||||
|
||||
Between them, the App's active members cover every band from 0–100 to 2 001–5 000 and Events'
|
||||
income bands vary, so the scenarios also show the Hub's tiers and billing. Each scenario's people
|
||||
are sized to its band (the App's active-member count comes from them).
|
||||
- **Contracts 1.21.0 (released 2026-11-30):** `agent.DEMO_SCENARIOS`: each scenario's key, label, description, and the
|
||||
profile it uses for each product (`accounts`, `events`, `website`, `app`), so the Hub and the
|
||||
agent agree; a test checks every profile it names exists. `seed-demo` takes an optional
|
||||
`scenario`, and `accounts` joins `DEMO_PRODUCTS` (its demo is the church profile and the people).
|
||||
- **Agent 1.7.0:** runs `crosscode demo <church> <product> --profile <p> [--scenario <s>]` for
|
||||
every product, so a product can tell a scenario load from a single one.
|
||||
- **Hub 2.26.0:** on a demo client (every install marked as a demo site), **Load a demo
|
||||
scenario**: pick one from the list, see which installs it will replace (and any product the
|
||||
client has that the scenario doesn't cover), type the client's short name once, and the Hub
|
||||
queues one batch in order: **Accounts first** (profile and people), then **Events**, the
|
||||
**Website** and the **App**, each job starting only after the one before it succeeded; a failure
|
||||
stops the rest and says which product is now out of step. At the end the products sync the
|
||||
event feed, and one email reports the whole batch. The client page shows the scenario last
|
||||
loaded and when. Loading one product's demo on its own stays (as now), marked "out of step with
|
||||
the scenario" until a scenario is loaded again. The Hub refuses a scenario when an install
|
||||
needs a newer release (each scenario lists the minimum versions it needs).
|
||||
- **Products:** each product's demo loader takes `--scenario` and builds that scenario's data:
|
||||
Accounts (new: the profile and the people, replacing old demo people with `people.removeDemo`),
|
||||
Events 3.8.0 (its 4 profiles become 8, one per scenario's church and people), the Website 1.8.0
|
||||
(its profiles take the people and events of the scenario they're in) and the App 1.0.0. A
|
||||
product without the scenario's profile refuses the job, so a half-loaded demo is never silent.
|
||||
|
||||
## 13. What changes in each repo
|
||||
|
||||
| Repo | Change | Version |
|
||||
|------|--------|---------|
|
||||
| `crosscode-platform` `apps/app` | New (§1–§12), with `CHANGELOG.md`, `WHATS-NEW.md`, `env.template.json`, e2e, demo data | `app@1.0.0` |
|
||||
| `crosscode-platform` `packages/contracts` | `app` in `DEMO_PRODUCTS`, `APP_MODULES`, the `app` part of the church export, `crosscode.devotional/1` and its CSV rules, the translations, `messaging.get`, `whatsapp.optout` | `contracts@1.20.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `packages/contracts` | `agent.DEMO_SCENARIOS`, `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS` | `contracts@1.21.0` (**released 2026-11-30**) |
|
||||
| `crosscode-platform` `apps/accounts` | `messaging.get` for linked products, a hint when the messaging settings change, the WhatsApp opt-out for every product; demo data (the scenario's church profile with its logo and icon, and its people) | `accounts@1.9.0` |
|
||||
| `crosscode-platform` `apps/events` | STOP replies passed to Accounts; the opt-out read from Accounts; demo profiles reworked to the scenarios | `events@3.8.0` |
|
||||
| `crosscode-platform` `apps/website` | Demo profiles take the scenario's people and events (`--scenario`) | `website@1.8.0` |
|
||||
| `crosscode-platform` `apps/agent` | `seed-demo` for `app` and `accounts`, `--scenario` passed on | `agent@1.7.0` |
|
||||
| `crosscode-platform` `packages/ui` | The tab bar and bottom sheet, if worth sharing; otherwise nothing | workspace |
|
||||
| `crosscode-platform` `packages/seo` | `Article` builder for devotionals and announcements; the icon generator for the manifest | workspace |
|
||||
| `crosscode-platform` `scripts/` | `products/app.sh`, `app.env.template.json`, bats tests | — |
|
||||
| `events-hub` | App in New install, its releases, env template, billing on the band, renewal check, FastPanel email, Devotionals (write, schedule 3 months ahead, Import CSV, the endpoint for Apps), **Load a demo scenario** on a demo client (vendored contracts 1.21.0) | Hub `v2.26.0` |
|
||||
| `crosscode-site` | Church App on sale (ROADMAP §9): its page, the active-member tiers, House of Prayer screenshots, the bundle examples (§10), FAQ, `SoftwareApplication` JSON-LD | `v1.10.0` |
|
||||
|
||||
## 14. Testing
|
||||
|
||||
- **Unit (Jest):** slot boundaries in the church's timezone (including a zone with daylight
|
||||
saving), recurrence and the 12-month limits, skips, the cancel window, coverage and gaps, the
|
||||
target per slot, renewals (14 and 3 days before, the single-use link), reminders' times, "I
|
||||
prayed" only after the slot, **no name in any public or member response** (a test over every
|
||||
public route), request visibility and moderation, escalation, roles and 2FA for every role above
|
||||
Member, the 8-day sign-in renewed up to 90 days, active-member counting and the band, the export
|
||||
and delete hooks, the devotional CSV checks (a bad date, a missing field, a reference YouVersion
|
||||
can't open, a day already filled), the YouVersion links, the nightly Cross Code fetch (and the
|
||||
last copy kept when the Hub is down), `messaging.get`.
|
||||
- **Hub:** the Devotionals page, Import CSV with its preview, the 3-month limit, and the endpoint
|
||||
refusing anything but an App licence.
|
||||
- **Playwright** (phone, tablet and desktop): browse signed out; sign in from a slot and land back
|
||||
on it with the sheet open (through 2FA); book once, weekly and daily; skip, change and cancel;
|
||||
the 8-hour rule; two browsers, one books, the other's view updates live (and with the stream
|
||||
blocked, by polling); a shared request waits for approval; escalation; announcement and
|
||||
devotional publishing; offline Home; the manifest and service worker (installable); axe on every
|
||||
screen; the §11 checks on public pages and `noindex` on prayer pages.
|
||||
- **Demo scenarios:** contracts: every profile a scenario names exists. Hub: the batch runs in
|
||||
order, stops at the first failure and says what's out of step, refuses an install on too old a
|
||||
release. On cross-demo2, each scenario loaded end to end: the same church name, logo and people
|
||||
in all four products, Events' events on the Website and in the App, no leftover people from the
|
||||
scenario before.
|
||||
- **Lighthouse (mobile):** Home, an event and a devotional: SEO 100, accessibility 95+,
|
||||
performance 90+.
|
||||
- **The release checks** (ROADMAP §9) for the App, and a throwaway install from the Hub (New
|
||||
install → App, update it, uninstall it with its export) before Hope Family Church: the Website's
|
||||
VM test was skipped, and this is the one that catches FastPanel, DNS and SSE through frp.
|
||||
|
||||
## 15. Releasing and rolling it out
|
||||
|
||||
1. `contracts@1.20.0` (**released 2026-11-30**), then `accounts@1.9.0` (`messaging.get`, the
|
||||
WhatsApp opt-out) and `events@3.8.0` (STOP passed to Accounts), rolled out to every church.
|
||||
2. `contracts@1.21.0` (demo scenarios, **released 2026-11-30**), with the scenario demo loaders in Accounts 1.9.0, Events
|
||||
3.8.0, `website@1.8.0`, and `agent@1.7.0`.
|
||||
3. Hub `v2.26.0` (vendored contracts 1.21.0) deployed, and the first 3 months of Cross Code
|
||||
devotionals written or imported.
|
||||
4. `app@1.0.0` tagged after the e2e and Lighthouse runs.
|
||||
5. **cross-demo2** (Acacia Hill): New install → App, every demo scenario loaded once, the
|
||||
throwaway test above.
|
||||
6. **Hope Family Church:** New install → App; the prayer coordinators set the wall up before it's
|
||||
announced to the church.
|
||||
7. crosscode-site `v1.10.0`: the App on sale (prices already in the Hub).
|
||||
|
||||
## Decisions
|
||||
|
||||
Made by Joshua on 2026-11-30, after the first draft and the mockup:
|
||||
|
||||
1. **Devotionals have two sources:** from Cross Code (written in the Hub, scheduled up to 3 months
|
||||
ahead, with a CSV import) or the church's own (§6). Verses open in **YouVersion**.
|
||||
2. **The House of Prayer is a 24-hour clock**, not a grid (§3; mockup redrawn).
|
||||
3. **Ask for prayer as drawn**, and **every shared request is approved first** (§4).
|
||||
4. **One set of email and WhatsApp credentials per church,** shared by Events, Accounts and the
|
||||
App (§8). Replaces P14.
|
||||
5. **The devotional shows the verse's text and links to YouVersion,** and is **sent by email and
|
||||
WhatsApp**: the title, the verse and a link to the full devotional in the App (§6). Replaces
|
||||
P11 and P12.
|
||||
6. **Only the basic church details are shared in 1.0** (P15, §9).
|
||||
7. **A sign-in lasts 8 days, renewed by each visit, up to 90 days** (§2), and **every role above
|
||||
Member needs 2FA**, with a Devotional writer role next to the Prayer coordinator (§10).
|
||||
Replaces P3 and P17.
|
||||
8. **Campaigns and testimonies are in 1.0** (P7), **no cap per slot** (P5), **prayer team or
|
||||
members** is enough for requests (P8), **the tab bar as drawn** (P18), **a physical prayer room
|
||||
later** (P4).
|
||||
9. **The admin looks like the Website's and Events' admins** (white side menu, grey page, the same
|
||||
panels and stat cards), not a new style (§10; mockup redrawn).
|
||||
10. **Each devotional uses one of NLT, ESV, NIV, NKJV, KJV or two Afrikaans translations**
|
||||
(proposed: 1933/1953 and 1983), quoting only the passage, with its copyright line (§6).
|
||||
11. **Accounts keeps the WhatsApp opt-out for every product,** so a STOP to the shared number
|
||||
reaches the App, Events and Accounts alike (§8). Adds Events 3.8.0.
|
||||
12. **Home shows today's prayer clock** in small, as the House of Prayer does (mockup redrawn).
|
||||
13. **Demo scenarios** (added later on 2026-11-30): on a demo client, one choice in the Hub loads
|
||||
every product with the same church, people and events, from preset combinations (§12). Adds
|
||||
contracts 1.21.0, agent 1.7.0 and Website 1.8.0, and demo data in Accounts 1.9.0. Eight
|
||||
scenarios, one per Website demo profile, each its own church: a scenario load replaces the
|
||||
church profile with its own name, logo, icon, colours and details.
|
||||
|
||||
The other proposals as first written, confirmed:
|
||||
|
||||
1. **P1 Installable PWA** from the profile, with a generated icon when the church has none (§2).
|
||||
2. **P2 Offline:** the shell and recent content cached; actions need a connection (§2).
|
||||
3. ~~P3~~ (decision 7).
|
||||
4. **P4 One prayer wall per church,** prayed from anywhere; a physical prayer room with places is
|
||||
1.x (§3).
|
||||
5. **P5 No limit per slot,** a target (1 by default) for "covered" (§3).
|
||||
6. **P6 Reminders** none / 15 min / 1 hour (default) / the evening before (§3).
|
||||
7. **P7 Campaigns and testimonies in 1.0** (§3). They could move to 1.1 to ship sooner.
|
||||
8. **P8 Prayer requests: prayer team only (default) or members,** never public (§4).
|
||||
9. **P9 Fully anonymous requests** off by default (§4).
|
||||
10. **P10 Requests close after 30 days** and are deleted 12 months after closing (§4).
|
||||
11. ~~P11~~, 12. ~~P12~~ (decisions 1 and 5).
|
||||
13. **P13 Announcements by email or WhatsApp only when the member turns them on** (§8).
|
||||
14. ~~P14~~ (decision 4).
|
||||
15. **P15 Nothing moves into the church profile in 1.0;** sermons and giving read from the Website
|
||||
in 1.x (§9). Answers WEBSITE-1.0-PLAN's "Still open".
|
||||
16. **P16 Shared profile facts edited in Accounts,** not the App, in 1.0 (§9).
|
||||
17. ~~P17~~ (decision 7).
|
||||
18. **P18 Tab bar** Home, Prayer, Events, Devotional, Me (§1).
|
||||
19. **P19 Safeguarding contacts** are the Pastoral care role, with South African emergency numbers
|
||||
by default (§4).
|
||||
20. **P20 A throwaway install from the Hub** before Hope Family Church (§14).
|
||||
|
||||
## Not in 1.0
|
||||
|
||||
Reading plans, sermons, connect groups, pastoral care, serving, giving links and the directory
|
||||
(App 1.x, phase 7); push notifications (decision 13); a physical prayer room with places; prayer
|
||||
for a group; an app-store release; moving to the church's own domain (as the Website, decision 45).
|
||||
|
||||
## Still open
|
||||
|
||||
- ~~Which two Afrikaans translations~~: 1933/1953 and 1983, confirmed by Joshua 2026-11-30 (YouVersion ids checked, contracts 1.20.0).
|
||||
- **The publishers' terms** for quoting each translation in an app (§6), checked before Cross
|
||||
Code's devotionals go out; ask for permission where the terms don't cover it.
|
||||
- ~~The demo scenarios~~: eight, one per Website demo profile, each its own church with its own logo and details; Acacia Hill is `community-family` (Joshua, 2026-11-30).
|
||||
+12
-25
@@ -1,6 +1,6 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-26. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-11-30. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
@@ -34,8 +34,9 @@ every release).
|
||||
| 3 | Accounts 1.0.0 | **Released, rolled out and tested** (now `accounts@1.6.0`; [ACCOUNTS-1.0-PLAN.md](./ACCOUNTS-1.0-PLAN.md)) |
|
||||
| 4 | Cross Events 3.0.0: sign-in through Accounts | **Released, rolled out and tested** (now `events@3.7.0`; [EVENTS-3.0-PLAN.md](./EVENTS-3.0-PLAN.md)). Churches sign in through their Accounts; crosscode-site `v1.6.0` deployed |
|
||||
| 4+ | Running it: jobs from the dashboard, styled emails, .env from the Hub, sign-in health, the nightly people check; then frp config and one-product uninstalls, and the Hub's popups, pickers and port list | **Released, deployed and tested** 2026-11-20 and 2026-11-23 (below) |
|
||||
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26, not deployed yet. Left: deploy the site, Hope Family Church, a second church |
|
||||
| 6–7 | App 1.0.0 → App 1.x | Not started |
|
||||
| 5 | Church Website 1.0.0 | **Released 2026-11-26** (planned 2026-11-21: [WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md), all decisions confirmed). Font pairings confirmed 2026-11-24, section variants per template 2026-11-25 (§3). `contracts@1.17.0`, `accounts@1.7.0` and `events@3.7.0` released 2026-11-24, Hub `v2.21.0` 2026-11-25 (the Hub deployed 2026-11-25; the others not rolled out yet). `contracts@1.18.0` and Hub `v2.22.0` (Get more storage) released 2026-11-25, the Hub deployed 2026-11-26. **`website@1.0.0` and `1.0.1` released 2026-11-26**, crosscode-site `v1.7.0` (the Website on sale) released 2026-11-26. **Done** (confirmed by Joshua 2026-11-30): crosscode-site deployed, Hope Family Church and a second church live, the remaining release checks finished. Now `website@1.7.1` (VERSIONS.md) |
|
||||
| 6 | Church App 1.0.0 | **Being planned** (2026-11-30): [APP-1.0-PLAN.md](./APP-1.0-PLAN.md), decisions confirmed 2026-11-30 (two left in "Still open"); mockup on the Design canvas "Church App 1.0 mockup" |
|
||||
| 7 | App 1.x | Not started |
|
||||
|
||||
## Released 2026-11-23
|
||||
|
||||
@@ -95,29 +96,15 @@ before that need the change by hand, and so does the Hub's own site (`events-hub
|
||||
|
||||
## Next up
|
||||
|
||||
Everything up to and including the 2026-11-23 releases is deployed (VERSIONS.md, "Deployed / rolled
|
||||
out").
|
||||
Everything up to and including phase 5 (the Church Website) is released and rolled out: Hope
|
||||
Family Church and a second church are live on the Website, crosscode-site sells it (confirmed by
|
||||
Joshua 2026-11-30; VERSIONS.md, "Deployed / rolled out").
|
||||
|
||||
1. **Phase 5, Church Website 1.0.0** (ROADMAP §6, §9). Planned in
|
||||
[WEBSITE-1.0-PLAN.md](./WEBSITE-1.0-PLAN.md): decisions all confirmed 2026-11-21. Font pairings
|
||||
confirmed 2026-11-24 (§3). Order: ~~contracts 1.17.0~~ → ~~Accounts 1.7.0~~ (both released 2026-11-24; Accounts
|
||||
ships with contracts because it answers the new `church.update`) → ~~Events 3.7.0~~ (shared fonts and footer; released 2026-11-24) → ~~Hub 2.21.0~~ (released
|
||||
and deployed 2026-11-25; the plan said 2.13.0) → ~~`website@1.0.0`~~ (released 2026-11-26, with
|
||||
`contracts@1.18.0` and Hub `v2.22.0`, deployed 2026-11-26; the release checks are in
|
||||
WEBSITE-1.0-PLAN §13, "Where they are"; the VM test was skipped, so watch the first install
|
||||
closely) → ~~`website@1.0.1`~~ (released 2026-11-26: the messages' thumbnails served from the
|
||||
site, the Calendar dates; VERSIONS.md) → **Hope Family Church**: roll out Accounts 1.7.0 and
|
||||
Events 3.7.0 first (neither is rolled out yet), then New install → Website (1.0.1) → a second
|
||||
church on a different template. ~~crosscode-site 1.7.0~~ (the Website on sale, released 2026-11-26;
|
||||
the Hub already had its prices): **deploy it** (`deploy/deploy.sh` on the server) once Hope
|
||||
Family Church's Website is live, so the first church to buy it isn't the first install.
|
||||
The release checks are all run on 1.0.1's build (WEBSITE-1.0-PLAN §13, "Where they are"): every
|
||||
variant passes axe, the 312 screenshots have baselines (taken again with whole-pixel section
|
||||
heights), Lighthouse passes 12 of 12. Still to do:
|
||||
- **Look through the variant baselines** once (the contact sheet: Bold, Community and Clean were
|
||||
taken, not compared, the first time). A section drawn wrong there is the reference until then.
|
||||
- **The VM test was skipped**: before Hope Family Church, a throwaway install from the Hub (New
|
||||
install → Website 1.0.0, update it to 1.0.1, uninstall with its export) in its place.
|
||||
1. **Phase 6, Church App 1.0.0** (ROADMAP §7, §9). Planned in [APP-1.0-PLAN.md](./APP-1.0-PLAN.md)
|
||||
(2026-11-30, decisions confirmed): contracts 1.20.0 → Accounts 1.9.0 (shared email and
|
||||
WhatsApp for the App, the WhatsApp opt-out for every product) and Events 3.8.0 (STOP passed to
|
||||
Accounts) → Hub 2.26.0 (with Cross Code devotionals) → `app@1.0.0` → cross-demo2 (with a throwaway install from the Hub) → Hope Family
|
||||
Church → crosscode-site 1.10.0 (the App on sale).
|
||||
Done (confirmed by Joshua 2026-11-25): `hope-events` is archived, and every FastPanel site set up
|
||||
before Hub 2.10.0, and the Hub's own site, has `location ^~ /api/`.
|
||||
|
||||
|
||||
+57
-21
@@ -1,6 +1,6 @@
|
||||
# Versions — the latest release of everything
|
||||
|
||||
Last updated: 2026-11-27. Taken from the git tags, which is what a release is here (branch → merge →
|
||||
Last updated: 2026-11-30. Taken from the git tags, which is what a release is here (branch → merge →
|
||||
tag → push, see [HANDOVER.md](./HANDOVER.md) "Releasing"). **Update this file with every release.**
|
||||
|
||||
"Released" means tagged and pushed. Whether a release is **deployed** or rolled out is recorded
|
||||
@@ -11,13 +11,13 @@ separately below; the two often differ.
|
||||
| What | Repo | Latest | Tag | Released |
|
||||
|------|------|--------|-----|----------|
|
||||
| Cross Events | `crosscode-platform` (`apps/events`) | **3.7.2** | `events@3.7.2` | 2026-11-27 |
|
||||
| Church Website | `crosscode-platform` (`apps/website`) | **1.6.1** | `website@1.6.1` | 2026-11-27 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.8.0** | `accounts@1.8.0` | 2026-11-26 |
|
||||
| Church Website | `crosscode-platform` (`apps/website`) | **1.7.1** | `website@1.7.1` | 2026-11-28 |
|
||||
| Accounts | `crosscode-platform` (`apps/accounts`) | **1.9.0** | `accounts@1.9.0` | 2026-11-30 |
|
||||
| Server agent | `crosscode-platform` (`apps/agent`) | **1.6.0** | `agent@1.6.0` | 2026-11-27 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.19.0** | `contracts@1.19.0` | 2026-11-27 |
|
||||
| Cross Code Hub | `events-hub` | **2.25.0** | `v2.25.0` | 2026-11-27 |
|
||||
| Contracts | `crosscode-platform` (`packages/contracts`) | **1.21.0** | `contracts@1.21.0` | 2026-11-30 |
|
||||
| Cross Code Hub | `events-hub` | **2.25.1** | `v2.25.1` | 2026-11-27 |
|
||||
| crosscode.co.za | `crosscode-site` | **1.9.1** | `v1.9.1` | 2026-11-27 |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-27 (last change: an uninstall keeps the Website's backup snapshots shared, `rsync -aH`) |
|
||||
| `crosscode` script | `crosscode-platform` (`scripts/`) | `main` | none | 2026-11-30 (last change: `crosscode demo <church> accounts --profile <scenario>`, `--scenario` on every demo, Accounts builds `packages/demo`) |
|
||||
|
||||
The `crosscode` script has no version: every server's copy (`/opt/crosscode/tools`) pulls `main`
|
||||
on each run, so merging to `main` and pushing releases it. Its changes are listed in
|
||||
@@ -28,9 +28,10 @@ on each run, so merging to `main` and pushing releases it. Its changes are liste
|
||||
| What | Where | Version in package.json |
|
||||
|------|-------|-------------------------|
|
||||
| `@crosscode/auth-client` | `packages/auth-client` | 1.1.0 (released with Events 3.0.0 and Accounts 1.1.0) |
|
||||
| `@crosscode/demo` | `packages/demo` | 1.0.0 (the demo scenarios' churches, people and logos; ships with Accounts 1.9.0) |
|
||||
| `@crosscode/seo` | `packages/seo` | 1.0.0 (released with Events 2.4.0) |
|
||||
| `@crosscode/ui` | `packages/ui` | 0.3.0 (fonts, `ChurchFooter`; 0.2.0 with Accounts 1.7.0, 0.3.0 with Events 3.7.0) |
|
||||
| Website | `apps/website` | 1.6.1 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.6.1 on 2026-11-27; installed for the demo church cross-demo2 (1.6.0) only, Hope Family Church next) |
|
||||
| Website | `apps/website` | 1.7.1 (1.0.0–1.1.0 released 2026-11-26, 1.2.0–1.7.0 on 2026-11-27, 1.7.1 on 2026-11-28; installed for the demo church cross-demo2 (1.7.1) only, Hope Family Church next) |
|
||||
| App | `apps/app` | 0.0.0 (not started, phase 6) |
|
||||
|
||||
These shared packages ship inside the apps that use them, from the same checkout, so they don't
|
||||
@@ -38,15 +39,50 @@ need their own tags until something outside this repo depends on them.
|
||||
|
||||
## What each latest release was for
|
||||
|
||||
- **Accounts 1.9.0 + `@crosscode/demo` 1.0.0 + crosscode script (2026-11-30):** Church App
|
||||
groundwork (APP-1.0-PLAN §8, §12): `messaging.get` and `messaging.changed`; the WhatsApp opt-out
|
||||
for every product (`whatsapp.optout`, Accounts' own WAWP webhook, `whatsapp_opted_out`, "Turn
|
||||
WhatsApp back on"); a demo scenario's church profile, SVG logo and icon, and people
|
||||
(`crosscode demo <church> accounts --profile <scenario>`). **One migration.** Needs contracts
|
||||
1.21.0 and `packages/demo` (the `crosscode` script on `main` installs and builds it). Checked:
|
||||
Accounts' tests (99), `@crosscode/demo`'s (8), the script's bats (111), the workspace typecheck
|
||||
and lint, and on PostgreSQL 18 the migrations, scenario loads (2 457 people in 3.4 s), the
|
||||
opt-out and `npm run demo`. Not deployed yet.
|
||||
- **Contracts 1.21.0 (2026-11-30):** demo scenarios (APP-1.0-PLAN §12): `agent.DEMO_SCENARIOS`,
|
||||
eight fictional churches, one per Website demo profile, that load Accounts, Events, the Website
|
||||
and the App alike; `scenario` in `seed-demo`, `accounts` in `DEMO_PRODUCTS`, a profile per
|
||||
scenario for Events and the App (1.20.0's unused `acacia-hill` replaced by `community-family`),
|
||||
the minimum releases and agent. Checked: contracts tests (335), JSON Schemas, lint, the agent's
|
||||
tests. Nothing to deploy: the Hub vendors it with 2.26.0.
|
||||
- **Contracts 1.20.0 (2026-11-30):** the contracts for Church App 1.0.0 (APP-1.0-PLAN §12), the
|
||||
first step of phase 6: `crosscode.devotional/1` and the devotionals CSV checks shared by the Hub
|
||||
and the App, the Bible books and seven translations (YouVersion ids checked by Joshua),
|
||||
`messaging.get` / `messaging.changed`, `whatsapp.optout` and `whatsapp_opted_out`, `APP_MODULES`,
|
||||
the App's demo profile and the `app` part of the church export. Additive. Accounts refuses the
|
||||
two new requests until 1.9.0. Checked: contracts tests (329), JSON Schemas up to date, the
|
||||
workspace typecheck, Accounts' tests (80), the agent's tests. Nothing to deploy: the Hub vendors
|
||||
it with 2.26.0, and the products take it with their next release.
|
||||
- **Church Website 1.7.1 (2026-11-28):** Move and zoom for ministries', leaders' and events'
|
||||
photos too (1.7.0 had it in page sections only), saved with the row (`framing`). One migration
|
||||
(a nullable column on three tables). Checked: backend tests (136) and typecheck, frontend
|
||||
typecheck and lint, and the admin e2e suite in Chromium (12). Lighthouse not run. **Deployed**
|
||||
2026-11-30.
|
||||
- **Hub 2.25.1 (2026-11-27):** Jobs → Product filter lists every product. It offered only Cross
|
||||
Events and Accounts, so the Church Website's jobs couldn't be picked out; the list now comes from
|
||||
the frontend's products list (Events, Accounts, the Church Website, the App). Frontend only. No
|
||||
migration. Checked: the backend tests (283), frontend typecheck and lint. **Deployed** 2026-11-28.
|
||||
- **Church Website 1.7.0 (2026-11-27):** a section's photo shows in the shape of its frame and can
|
||||
be moved and zoomed (saved with the section, a draft until published); the media library says
|
||||
where each photo is used and deletes one used nowhere. **Deployed** 2026-11-27.
|
||||
- **Cross Events 3.7.2 + Church Website 1.6.1 (2026-11-27):** events from the other product no
|
||||
longer show twice after a reseed: the 15-minute feed poll and "Sync now" fetch the whole list and
|
||||
drop copies that are gone, and both demo loaders list the old events as removed and tell the
|
||||
other product at once (Events' `set-demo.js` also fetches the Website's events back in). The
|
||||
Website's header says "Events site" with an external-link icon instead of a second "Events".
|
||||
**Not deployed yet.**
|
||||
**Deployed** 2026-11-27.
|
||||
- **crosscode.co.za 1.9.1 (2026-11-27):** the web address examples (both product pages and the
|
||||
Church Website brochure) say yourchurch instead of a real church's name (hopefamily). **Not
|
||||
deployed yet.**
|
||||
Church Website brochure) say yourchurch instead of a real church's name (hopefamily). **Deployed**
|
||||
2026-11-28.
|
||||
- **crosscode.co.za 1.9.0 (2026-11-27):** a Church Website brochure (`church-website-brochure.pdf`,
|
||||
five A4 pages, from the site's data and the demo screenshots), linked from the Church Website
|
||||
page; `npm run brochure` renders both brochures. The Website's founding offer no longer mentions
|
||||
@@ -97,8 +133,8 @@ need their own tags until something outside this repo depends on them.
|
||||
`crosscode demo <church> website --profile <p>`. No migrations outside the Hub. Checked:
|
||||
contracts (271), agent (58), the Website's backend tests (115) and build, the script's bats
|
||||
tests (107), the Hub's backend tests (283), frontend typecheck and lint. **Hub 2.25.0 and agent
|
||||
1.6.0 deployed 2026-11-27.** Website 1.3.0 not yet (cross-demo2 reports 1.2.0), so the Website's
|
||||
demo data can't be loaded there until it's on 1.3.0 or later.
|
||||
1.6.0 deployed 2026-11-27.** The Website followed (cross-demo2 on 1.7.0 since 2026-11-27), so its
|
||||
demo data can be loaded there.
|
||||
- **Hub 2.24.1 (2026-11-27):** Servers → Updates offers every product. Its tabs were a fixed list of
|
||||
Cross Events and Accounts from before the Church Website, so Website installs couldn't be updated
|
||||
in a batch there; now Events, Accounts, the Church Website, and the App once it has an install.
|
||||
@@ -182,15 +218,15 @@ need their own tags until something outside this repo depends on them.
|
||||
church footer from its profile in Accounts (`GET /api/v2/church`, kept 10 minutes), with links to
|
||||
its other sites in the header; `church.changed` from Accounts is now accepted (it answered 404
|
||||
before). The dashboard and setup screens are unchanged. `@crosscode/ui` 0.3.0. No migrations.
|
||||
Requires Accounts 1.7.0 (the Hub updates it first). **On cross-demo2 only** (by 2026-11-26, now
|
||||
3.7.1); not rolled out to the churches yet.
|
||||
Requires Accounts 1.7.0 (the Hub updates it first). **Deployed:** on cross-demo2 first (2026-11-26), then
|
||||
the churches (all on 3.7.2 since 2026-11-27).
|
||||
- **Contracts 1.17.0 + Accounts 1.7.0 (2026-11-24):** the first piece of the Church Website. Contracts:
|
||||
the 8 font pairings, corner styles and template ids (`./style`), an optional `branding.style` on the
|
||||
church profile, `church.update` (the Website changes shared profile facts), an optional `website`
|
||||
part of the church export and an optional `limits.storageBytes` on the licence. Accounts: Brand
|
||||
style under Church profile, the church's fonts, corners and shared footer on its pages, and
|
||||
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **On cross-demo2
|
||||
only** (by 2026-11-26, now 1.7.1); not rolled out to the churches yet.
|
||||
`church.update`. No migrations. The Hub vendors contracts 1.17.0 with 2.21.0. **Deployed:** on
|
||||
cross-demo2 first (2026-11-26), then the churches (all on Accounts 1.8.0 since 2026-11-27).
|
||||
- **Hub 2.20.0 (2026-11-23):** the port list says what each port is for (church, product, web or API,
|
||||
linked to the install); a church server's hand-written frpc tunnels are listed as taken on each frp
|
||||
config read. frps's allow_ports is checked against the port list (the Hub's range plus listed ports
|
||||
@@ -367,11 +403,11 @@ you deploy one.
|
||||
|
||||
| What | Running | Since | Notes |
|
||||
|------|---------|-------|-------|
|
||||
| Hub | 2.25.0 | 2026-11-27 | Demo clients and demo data for the Website |
|
||||
| Hub | 2.25.1 | 2026-11-28 | Jobs → Product filter lists every product |
|
||||
| Agent on church-server1 | 1.6.0 | 2026-11-27 | |
|
||||
| Agent on the central server | 1.6.0 | 2026-11-27 | |
|
||||
| Cross Events (churches) | 3.7.1 | 2026-11-27 | |
|
||||
| Cross Events (churches) | 3.7.2 | 2026-11-27 | |
|
||||
| Accounts (churches) | 1.8.0 | 2026-11-27 | |
|
||||
| Church Website (cross-demo2, the demo church) | 1.6.0 | 2026-11-27 | Real demo photos; reload the demo to see them |
|
||||
| cross-demo2 (demo church) | Accounts 1.8.0, Cross Events 3.7.1, Church Website 1.6.0 | 2026-11-27 | The first Church Website install (`demo2.crosscode.co.za`) |
|
||||
| crosscode.co.za | 1.9.0 | 2026-11-27 | The Church Website brochure, every page of each template, screenshots that don't go stale |
|
||||
| Church Website (cross-demo2, the demo church) | 1.7.1 | 2026-11-30 | Photos move and zoom in their frame, ministries, leaders and events too |
|
||||
| cross-demo2 (demo church) | Accounts 1.8.0, Cross Events 3.7.2, Church Website 1.7.1 | 2026-11-30 | The first Church Website install (`demo2.crosscode.co.za`) |
|
||||
| crosscode.co.za | 1.9.1 | 2026-11-28 | Web address examples say yourchurch |
|
||||
|
||||
Generated
+18
-5
@@ -51,10 +51,11 @@
|
||||
},
|
||||
"apps/accounts/backend": {
|
||||
"name": "@crosscode/accounts-backend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/demo": "*",
|
||||
"@node-rs/argon2": "^2.2.2",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
@@ -88,7 +89,7 @@
|
||||
},
|
||||
"apps/accounts/frontend": {
|
||||
"name": "@crosscode/accounts-frontend",
|
||||
"version": "1.8.0",
|
||||
"version": "1.9.0",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/ui": "*",
|
||||
@@ -360,7 +361,7 @@
|
||||
},
|
||||
"apps/website/backend": {
|
||||
"name": "@crosscode/website-backend",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.1",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@crosscode/auth-client": "*",
|
||||
@@ -389,7 +390,7 @@
|
||||
},
|
||||
"apps/website/frontend": {
|
||||
"name": "@crosscode/website-frontend",
|
||||
"version": "1.6.1",
|
||||
"version": "1.7.1",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"@crosscode/seo": "*",
|
||||
@@ -1066,6 +1067,10 @@
|
||||
"resolved": "packages/contracts",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/demo": {
|
||||
"resolved": "packages/demo",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/events-backend": {
|
||||
"resolved": "apps/events/backend",
|
||||
"link": true
|
||||
@@ -23185,7 +23190,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.19.0",
|
||||
"version": "1.21.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
@@ -23219,6 +23224,14 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"packages/demo": {
|
||||
"name": "@crosscode/demo",
|
||||
"version": "1.0.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*"
|
||||
}
|
||||
},
|
||||
"packages/seo": {
|
||||
"name": "@crosscode/seo",
|
||||
"version": "1.0.0",
|
||||
|
||||
@@ -10,11 +10,14 @@ Events and the Hub, uses it, so the key fields are the same in every product's J
|
||||
| Event feed | `crosscode.event-feed/1` | `GET /api/feed/v1/events?updatedSince=` and the `event.changed` webhook | `src/event.ts` |
|
||||
| Church | `crosscode.church/1` | The church profile: name, branding, campuses, service times, contact details, product links | `src/church.ts` |
|
||||
| Identity | `crosscode.identity/1` | Accounts' sign-in claims and back-channel calls (`user.updated`, `user.deleted`, `user.export`) and their replies | `src/identity.ts` |
|
||||
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp) | `src/identity-request.ts` |
|
||||
| Identity requests | `crosscode.identity-request/1` | From 1.8.0: what a product asks of its Accounts at `POST /api/accounts/v1/requests`: moving its users in (`import.begin` / `batch` / `finish` / `abort`, secrets sealed with `sealLinkValue`) and `people.*` (ensure, update, reset 2FA, unlock, set active, news off); from 1.9.0 `messaging.*` (status, test, set Accounts' email and WhatsApp); from 1.20.0 `messaging.get` (the church's settings for the App, with the `messaging.changed` hint back) and `whatsapp.optout` (a STOP, kept by Accounts for every product) | `src/identity-request.ts` |
|
||||
| Sign-in return | — | The return-path check and OIDC `state` every product uses (ROADMAP-v3 §3) | `src/return-to.ts` |
|
||||
| Product link | `crosscode.link/1` | **Connect** under Settings → Linked products: the signed handshake that sets up a link's secret (`link.connect`, `link.connected`, `link.disconnect`) | `src/link.ts` |
|
||||
| Hub protocol v2 | `protocolVersion: 2` | Register, heartbeat (stats per product), linked products, update requests, AI, licence token | `src/hub.ts` (exported as `hub`) |
|
||||
| Env template | `crosscode.env-template/1` | Each product's `.env` variables by layer; `missingRequired` and, from 1.6.0, `checkEnvValue` / `invalidValues` (values an app can't start with, e.g. `TRUST_PROXY=TRUE`), which the Hub checks before a job | `src/agent.ts` (exported as `agent`) |
|
||||
| Devotional | `crosscode.devotional/1` | From 1.20.0: one day's devotional for the Church App (Cross Code's from the Hub at `GET /api/v2/devotionals`, or the church's own), the CSV import's columns and row checks (`checkDevotionalCsv`, `DEVOTIONAL_CSV_TEMPLATE`), shared by the Hub and the App | `src/devotional.ts` |
|
||||
| Bible passages | — | From 1.20.0: the 66 books (USFM codes, English and Afrikaans names), the seven translations with their YouVersion ids and copyright lines, `parseBibleReference`, `formatBibleReference`, `youVersionUrl` | `src/bible.ts` |
|
||||
| Demo scenarios | — | From 1.21.0: `agent.DEMO_SCENARIOS`, eight preset churches that load every product of a demo client alike (Accounts first, `DEMO_SCENARIO_ORDER`), each product's profiles, the minimum releases and agent; `seed-demo` takes `scenario` | `src/agent.ts` (exported as `agent`) |
|
||||
| Signing | — | HMAC request signing for the Hub and for product links (Node only) | `src/signing.ts` (`@crosscode/contracts/signing`) |
|
||||
|
||||
## Using it
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.19.0",
|
||||
"version": "1.21.0",
|
||||
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
|
||||
"license": "UNLICENSED",
|
||||
"type": "commonjs",
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
{
|
||||
"schema": "crosscode.church-export/1",
|
||||
"exportedAt": "2027-02-01T12:00:00.000Z",
|
||||
"product": "app",
|
||||
"productVersion": "1.0.0",
|
||||
"church": { "name": "Acacia Hill Church", "timezone": "Africa/Johannesburg" },
|
||||
"people": [
|
||||
{
|
||||
"ref": "p1",
|
||||
"name": "Lindiwe Example",
|
||||
"email": "lindiwe@example.com",
|
||||
"phone": "+27825550101",
|
||||
"role": "prayer-coordinator",
|
||||
"roles": ["prayer-coordinator", "devotional-writer"],
|
||||
"createdAt": "2026-12-10T08:00:00.000Z",
|
||||
"consent": { "email": true, "whatsapp": true, "privacyNoticeAcceptedAt": "2026-12-10T08:00:00.000Z" }
|
||||
},
|
||||
{
|
||||
"ref": "p2",
|
||||
"name": "Pieter Example",
|
||||
"email": "pieter@example.com",
|
||||
"phone": null,
|
||||
"role": "member",
|
||||
"createdAt": "2026-12-12T19:20:00.000Z",
|
||||
"consent": { "email": false, "whatsapp": null, "privacyNoticeAcceptedAt": "2026-12-12T19:20:00.000Z" }
|
||||
}
|
||||
],
|
||||
"events": [],
|
||||
"registrations": [],
|
||||
"payments": [],
|
||||
"checkIns": [],
|
||||
"rosters": [],
|
||||
"settings": { "name": "Acacia Hill Church" },
|
||||
"files": [{ "path": "uploads/campaigns/21-days.jpg", "bytes": 214380 }],
|
||||
"app": {
|
||||
"modules": ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"],
|
||||
"prayerWall": { "slotMinutes": 60, "slotTarget": 1, "bookAheadMonths": 12, "recurringMaxMonths": 12, "cancelHours": 8, "contact": "Lindiwe, 082 555 0101" },
|
||||
"commitments": [
|
||||
{
|
||||
"ref": "c1",
|
||||
"personRef": "p2",
|
||||
"startsAt": "2026-12-14T00:00:00.000Z",
|
||||
"minutes": 120,
|
||||
"repeats": "weekly",
|
||||
"until": "2027-12-13",
|
||||
"skipped": ["2026-12-28"],
|
||||
"reminder": "1h",
|
||||
"channel": "whatsapp",
|
||||
"note": null,
|
||||
"createdAt": "2026-12-12T19:30:00.000Z",
|
||||
"stoppedAt": null
|
||||
}
|
||||
],
|
||||
"prayed": [{ "personRef": "p2", "slotStartsAt": "2026-12-14T00:00:00.000Z", "at": "2026-12-14T02:05:00.000Z" }],
|
||||
"campaigns": [
|
||||
{ "ref": "k1", "title": "21 days of prayer", "description": "Every hour covered, together.", "image": "uploads/campaigns/21-days.jpg", "startsOn": "2027-01-05", "endsOn": "2027-01-25", "goal": "Every hour covered", "slotTarget": 2 }
|
||||
],
|
||||
"testimonies": [
|
||||
{ "personRef": "p2", "campaignRef": "k1", "text": "My father came home from hospital.", "showName": true, "status": "shown", "createdAt": "2027-01-20T07:00:00.000Z" }
|
||||
],
|
||||
"prayerRequests": [
|
||||
{
|
||||
"ref": "q1",
|
||||
"personRef": "p2",
|
||||
"visibility": "members",
|
||||
"showName": false,
|
||||
"text": "Please pray for my exams this week.",
|
||||
"status": "closed",
|
||||
"prayedCount": 14,
|
||||
"createdAt": "2027-01-10T06:00:00.000Z",
|
||||
"closedAt": "2027-01-18T12:00:00.000Z",
|
||||
"updates": [{ "text": "Answered! Thank you all.", "at": "2027-01-18T12:00:00.000Z" }],
|
||||
"moderation": [
|
||||
{ "action": "approved", "by": "Lindiwe Example", "reason": null, "at": "2027-01-10T07:10:00.000Z" },
|
||||
{ "action": "closed", "by": null, "reason": null, "at": "2027-01-18T12:00:00.000Z" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"safeguarding": {
|
||||
"emergencyNumbers": [
|
||||
{ "name": "Lifeline", "number": "0861 322 322" },
|
||||
{ "name": "SADAG", "number": "0800 567 567" },
|
||||
{ "name": "Childline", "number": "116" }
|
||||
]
|
||||
},
|
||||
"announcements": [
|
||||
{
|
||||
"title": "21 days of prayer starts on 5 January",
|
||||
"body": "Book your hour on the prayer wall.",
|
||||
"image": null,
|
||||
"button": { "label": "Book an hour", "url": "https://app.acaciahill.co.za/prayer" },
|
||||
"campus": null,
|
||||
"audience": "everyone",
|
||||
"pinned": true,
|
||||
"publishAt": "2026-12-20T06:00:00.000Z",
|
||||
"endsAt": "2027-01-25T22:00:00.000Z",
|
||||
"sent": { "email": true, "whatsapp": false }
|
||||
}
|
||||
],
|
||||
"devotionalSource": "church",
|
||||
"devotionals": [
|
||||
{
|
||||
"date": "2027-01-05",
|
||||
"title": "God het eerste liefgehad",
|
||||
"passage": {
|
||||
"reference": "Johannes 3:16",
|
||||
"location": { "book": "JHN", "chapter": 3, "verse": 16, "endChapter": 3, "endVerse": 16 },
|
||||
"translation": "AFR53",
|
||||
"text": "Want so lief het God die wêreld gehad, dat Hy sy eniggebore Seun gegee het, sodat elkeen wat in Hom glo, nie verlore mag gaan nie, maar die ewige lewe kan hê."
|
||||
},
|
||||
"body": "God het eerste liefgehad.",
|
||||
"prayer": null,
|
||||
"author": "Lindiwe Example",
|
||||
"membersOnly": false
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"ref": "w1",
|
||||
"title": "Prayer night",
|
||||
"description": "An evening of worship and prayer.",
|
||||
"startsAt": "2027-01-15T17:00:00.000Z",
|
||||
"endsAt": "2027-01-15T19:00:00.000Z",
|
||||
"location": "Acacia Hill Church hall",
|
||||
"link": null,
|
||||
"image": null,
|
||||
"published": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"schema": "crosscode.devotional/1",
|
||||
"from": "2027-01-05",
|
||||
"to": "2027-04-05",
|
||||
"devotionals": [
|
||||
{
|
||||
"schema": "crosscode.devotional/1",
|
||||
"id": "3b4c5d6e-7f8a-4b9c-8d0e-2f3a4b5c6d7e",
|
||||
"source": "crosscode",
|
||||
"date": "2027-01-05",
|
||||
"title": "Love that never gives up",
|
||||
"passage": {
|
||||
"reference": "1 Corinthians 13:4–7",
|
||||
"location": { "book": "1CO", "chapter": 13, "verse": 4, "endChapter": 13, "endVerse": 7 },
|
||||
"translation": "NLT",
|
||||
"text": "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance."
|
||||
},
|
||||
"body": "Paul wrote these words to a church that was proud of its gifts.\n\nLove is the gift that makes the others worth having.",
|
||||
"prayer": "Lord, teach me to love the way you love me.",
|
||||
"author": "Cross Code",
|
||||
"updatedAt": "2026-12-01T10:00:00.000Z"
|
||||
},
|
||||
{
|
||||
"schema": "crosscode.devotional/1",
|
||||
"id": "4c5d6e7f-8a9b-4c0d-9e1f-3a4b5c6d7e8f",
|
||||
"source": "crosscode",
|
||||
"date": "2027-01-06",
|
||||
"title": "Die Here is my herder",
|
||||
"passage": {
|
||||
"reference": "Psalms 23:1–3",
|
||||
"location": { "book": "PSA", "chapter": 23, "verse": 1, "endChapter": 23, "endVerse": 3 },
|
||||
"translation": "AFR83",
|
||||
"text": "Die Here is my herder, ek kom niks kort nie. Hy laat my rus in groen weivelde. Hy bring my by waters waar daar vrede is. Hy gee my nuwe krag. Hy lei my op die regte paaie tot eer van sy Naam."
|
||||
},
|
||||
"body": "Vandag herinner Dawid ons dat ons nie alleen loop nie.",
|
||||
"prayer": null,
|
||||
"author": null,
|
||||
"updatedAt": "2026-12-01T10:00:00.000Z"
|
||||
}
|
||||
],
|
||||
"generatedAt": "2027-01-05T00:30:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"type": "messaging.changed",
|
||||
"occurredAt": "2026-12-03T09:15:00.000Z",
|
||||
"email": false,
|
||||
"whatsapp": true
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"email": {
|
||||
"host": "smtp.acaciahill.co.za",
|
||||
"port": 587,
|
||||
"secure": false,
|
||||
"user": "hello@acaciahill.co.za",
|
||||
"pass": "sealed1.DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD",
|
||||
"from": "Acacia Hill Church <hello@acaciahill.co.za>"
|
||||
},
|
||||
"whatsapp": {
|
||||
"accessToken": "sealed1.EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE",
|
||||
"instanceId": "ACACIA01"
|
||||
},
|
||||
"updatedAt": "2026-12-02T07:30:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"requestId": "1f2a3b4c-5d6e-4f7a-8b9c-0d1e2f3a4b5c",
|
||||
"actor": null,
|
||||
"type": "messaging.get"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"accounts": 1
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schema": "crosscode.identity-request/1",
|
||||
"requestId": "2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d",
|
||||
"actor": null,
|
||||
"type": "whatsapp.optout",
|
||||
"phone": "+27825550123",
|
||||
"receivedAt": "2026-12-04T18:42:10.000Z",
|
||||
"keyword": "STOP"
|
||||
}
|
||||
@@ -95,6 +95,9 @@
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
},
|
||||
"whatsapp_opted_out": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -823,7 +823,9 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website"
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"profile": {
|
||||
@@ -834,7 +836,28 @@
|
||||
"small",
|
||||
"events",
|
||||
"ministry",
|
||||
"multicampus"
|
||||
"multicampus",
|
||||
"heritage-parish",
|
||||
"heritage-city",
|
||||
"bold-youth",
|
||||
"bold-plant",
|
||||
"community-family",
|
||||
"community-town",
|
||||
"clean-modern",
|
||||
"clean-campus"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"heritage-parish",
|
||||
"heritage-city",
|
||||
"bold-youth",
|
||||
"bold-plant",
|
||||
"community-family",
|
||||
"community-town",
|
||||
"clean-modern",
|
||||
"clean-campus"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -857,6 +880,19 @@
|
||||
"maxLength": 254,
|
||||
"format": "email",
|
||||
"pattern": "^(?:[A-Za-z0-9_'+\\-]+\\.)*[A-Za-z0-9_'+\\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$"
|
||||
},
|
||||
"scenario": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"heritage-parish",
|
||||
"heritage-city",
|
||||
"bold-youth",
|
||||
"bold-plant",
|
||||
"community-family",
|
||||
"community-town",
|
||||
"clean-modern",
|
||||
"clean-campus"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,215 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/devotional.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"passage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reference": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"location": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"book": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"GEN",
|
||||
"EXO",
|
||||
"LEV",
|
||||
"NUM",
|
||||
"DEU",
|
||||
"JOS",
|
||||
"JDG",
|
||||
"RUT",
|
||||
"1SA",
|
||||
"2SA",
|
||||
"1KI",
|
||||
"2KI",
|
||||
"1CH",
|
||||
"2CH",
|
||||
"EZR",
|
||||
"NEH",
|
||||
"EST",
|
||||
"JOB",
|
||||
"PSA",
|
||||
"PRO",
|
||||
"ECC",
|
||||
"SNG",
|
||||
"ISA",
|
||||
"JER",
|
||||
"LAM",
|
||||
"EZK",
|
||||
"DAN",
|
||||
"HOS",
|
||||
"JOL",
|
||||
"AMO",
|
||||
"OBA",
|
||||
"JON",
|
||||
"MIC",
|
||||
"NAM",
|
||||
"HAB",
|
||||
"ZEP",
|
||||
"HAG",
|
||||
"ZEC",
|
||||
"MAL",
|
||||
"MAT",
|
||||
"MRK",
|
||||
"LUK",
|
||||
"JHN",
|
||||
"ACT",
|
||||
"ROM",
|
||||
"1CO",
|
||||
"2CO",
|
||||
"GAL",
|
||||
"EPH",
|
||||
"PHP",
|
||||
"COL",
|
||||
"1TH",
|
||||
"2TH",
|
||||
"1TI",
|
||||
"2TI",
|
||||
"TIT",
|
||||
"PHM",
|
||||
"HEB",
|
||||
"JAS",
|
||||
"1PE",
|
||||
"2PE",
|
||||
"1JN",
|
||||
"2JN",
|
||||
"3JN",
|
||||
"JUD",
|
||||
"REV"
|
||||
]
|
||||
},
|
||||
"chapter": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 150
|
||||
},
|
||||
"verse": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 176
|
||||
},
|
||||
"endChapter": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 150
|
||||
},
|
||||
"endVerse": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 176
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"book",
|
||||
"chapter",
|
||||
"verse",
|
||||
"endChapter",
|
||||
"endVerse"
|
||||
]
|
||||
},
|
||||
"translation": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"NLT",
|
||||
"ESV",
|
||||
"NIV",
|
||||
"NKJV",
|
||||
"KJV",
|
||||
"AFR53",
|
||||
"AFR83"
|
||||
]
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 10000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"reference",
|
||||
"location",
|
||||
"translation",
|
||||
"text"
|
||||
]
|
||||
},
|
||||
"body": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 20000
|
||||
},
|
||||
"prayer": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 5000
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.devotional/1"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"crosscode",
|
||||
"church"
|
||||
]
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"date",
|
||||
"title",
|
||||
"passage",
|
||||
"body",
|
||||
"prayer",
|
||||
"author",
|
||||
"schema",
|
||||
"id",
|
||||
"source",
|
||||
"updatedAt"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/devotionals-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.devotional/1"
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"to": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"devotionals": {
|
||||
"maxItems": 100,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"date": {
|
||||
"type": "string",
|
||||
"format": "date",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))$"
|
||||
},
|
||||
"title": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
"passage": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reference": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 100
|
||||
},
|
||||
"location": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"book": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"GEN",
|
||||
"EXO",
|
||||
"LEV",
|
||||
"NUM",
|
||||
"DEU",
|
||||
"JOS",
|
||||
"JDG",
|
||||
"RUT",
|
||||
"1SA",
|
||||
"2SA",
|
||||
"1KI",
|
||||
"2KI",
|
||||
"1CH",
|
||||
"2CH",
|
||||
"EZR",
|
||||
"NEH",
|
||||
"EST",
|
||||
"JOB",
|
||||
"PSA",
|
||||
"PRO",
|
||||
"ECC",
|
||||
"SNG",
|
||||
"ISA",
|
||||
"JER",
|
||||
"LAM",
|
||||
"EZK",
|
||||
"DAN",
|
||||
"HOS",
|
||||
"JOL",
|
||||
"AMO",
|
||||
"OBA",
|
||||
"JON",
|
||||
"MIC",
|
||||
"NAM",
|
||||
"HAB",
|
||||
"ZEP",
|
||||
"HAG",
|
||||
"ZEC",
|
||||
"MAL",
|
||||
"MAT",
|
||||
"MRK",
|
||||
"LUK",
|
||||
"JHN",
|
||||
"ACT",
|
||||
"ROM",
|
||||
"1CO",
|
||||
"2CO",
|
||||
"GAL",
|
||||
"EPH",
|
||||
"PHP",
|
||||
"COL",
|
||||
"1TH",
|
||||
"2TH",
|
||||
"1TI",
|
||||
"2TI",
|
||||
"TIT",
|
||||
"PHM",
|
||||
"HEB",
|
||||
"JAS",
|
||||
"1PE",
|
||||
"2PE",
|
||||
"1JN",
|
||||
"2JN",
|
||||
"3JN",
|
||||
"JUD",
|
||||
"REV"
|
||||
]
|
||||
},
|
||||
"chapter": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 150
|
||||
},
|
||||
"verse": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 176
|
||||
},
|
||||
"endChapter": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 150
|
||||
},
|
||||
"endVerse": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 176
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"book",
|
||||
"chapter",
|
||||
"verse",
|
||||
"endChapter",
|
||||
"endVerse"
|
||||
]
|
||||
},
|
||||
"translation": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"NLT",
|
||||
"ESV",
|
||||
"NIV",
|
||||
"NKJV",
|
||||
"KJV",
|
||||
"AFR53",
|
||||
"AFR83"
|
||||
]
|
||||
},
|
||||
"text": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 10000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"reference",
|
||||
"location",
|
||||
"translation",
|
||||
"text"
|
||||
]
|
||||
},
|
||||
"body": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 20000
|
||||
},
|
||||
"prayer": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 5000
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"author": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.devotional/1"
|
||||
},
|
||||
"id": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"source": {
|
||||
"type": "string",
|
||||
"const": "crosscode"
|
||||
},
|
||||
"updatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"date",
|
||||
"title",
|
||||
"passage",
|
||||
"body",
|
||||
"prayer",
|
||||
"author",
|
||||
"schema",
|
||||
"id",
|
||||
"source",
|
||||
"updatedAt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"generatedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"from",
|
||||
"to",
|
||||
"devotionals",
|
||||
"generatedAt"
|
||||
]
|
||||
}
|
||||
@@ -68,6 +68,9 @@
|
||||
"whatsapp"
|
||||
]
|
||||
},
|
||||
"whatsapp_opted_out": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity/1"
|
||||
|
||||
@@ -1850,6 +1850,95 @@
|
||||
"type",
|
||||
"church"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"requestId": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"actor": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "messaging.get"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"requestId": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
"actor": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"pattern": "^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "whatsapp.optout"
|
||||
},
|
||||
"phone": {
|
||||
"type": "string",
|
||||
"pattern": "^\\+[1-9]\\d{6,14}$"
|
||||
},
|
||||
"receivedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"keyword": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 40
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"requestId",
|
||||
"actor",
|
||||
"type",
|
||||
"phone",
|
||||
"receivedAt",
|
||||
"keyword"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-changed.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "messaging.changed"
|
||||
},
|
||||
"occurredAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"email": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"type",
|
||||
"occurredAt",
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/messaging-get-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"host": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 253
|
||||
},
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 65535
|
||||
},
|
||||
"secure": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"user": {
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
"pass": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 320
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"host",
|
||||
"port",
|
||||
"secure",
|
||||
"user",
|
||||
"pass",
|
||||
"from"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accessToken": {
|
||||
"type": "string",
|
||||
"maxLength": 4096,
|
||||
"pattern": "^sealed1\\.[A-Za-z0-9_-]{40,}$"
|
||||
},
|
||||
"instanceId": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 200
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"accessToken",
|
||||
"instanceId"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"updatedAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"email",
|
||||
"whatsapp",
|
||||
"updatedAt"
|
||||
]
|
||||
}
|
||||
@@ -96,6 +96,9 @@
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
},
|
||||
"whatsapp_opted_out": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -93,6 +93,9 @@
|
||||
"email",
|
||||
"whatsapp"
|
||||
]
|
||||
},
|
||||
"whatsapp_opted_out": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/whatsapp-optout-reply.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.identity-request/1"
|
||||
},
|
||||
"accounts": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"accounts"
|
||||
]
|
||||
}
|
||||
@@ -71,6 +71,11 @@ function contracts(c) {
|
||||
"people-remove-demo-reply": c.peopleRemoveDemoReplySchema,
|
||||
"people-check-reply": c.peopleCheckReplySchema,
|
||||
"church-update-reply": c.churchUpdateReplySchema,
|
||||
"messaging-get-reply": c.messagingGetReplySchema,
|
||||
"messaging-changed": c.messagingChangedSchema,
|
||||
"whatsapp-optout-reply": c.whatsappOptOutReplySchema,
|
||||
"devotional": c.devotionalSchema,
|
||||
"devotionals-reply": c.devotionalsReplySchema,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, productSchema } from "./common";
|
||||
import type { ACTIVE_MEMBER_BANDS } from "./hub";
|
||||
|
||||
/**
|
||||
* The server agent (docs/AGENT-1.0-PLAN.md, ROADMAP-v3 phase 1d): what the Hub and the agent on
|
||||
@@ -72,13 +73,120 @@ export const WEBSITE_DEMO_PROFILES = [
|
||||
export const websiteDemoProfileSchema = z.enum(WEBSITE_DEMO_PROFILES);
|
||||
export type WebsiteDemoProfile = z.infer<typeof websiteDemoProfileSchema>;
|
||||
|
||||
/** The products with demo data (`seed-demo` jobs). */
|
||||
export const DEMO_PRODUCTS = ["events", "website"] as const;
|
||||
// ─── Demo scenarios (1.21.0, APP-1.0-PLAN §12 "Demo scenarios") ──────────────
|
||||
|
||||
/**
|
||||
* A demo scenario loads every product of a demo client with the same church: Accounts' church
|
||||
* profile (its own name, logo, icon, colours and details) and people, then Events, the Website and
|
||||
* the App, each with that church's data. One per Website demo profile, keyed by it.
|
||||
*/
|
||||
export const DEMO_SCENARIO_KEYS = WEBSITE_DEMO_PROFILES;
|
||||
export const demoScenarioSchema = z.enum(DEMO_SCENARIO_KEYS);
|
||||
export type DemoScenarioKey = z.infer<typeof demoScenarioSchema>;
|
||||
|
||||
/**
|
||||
* Cross Events' demo data sets: the four single-product ones (`set-demo.js`) and, from Events
|
||||
* 3.8.0, one per scenario, named after it.
|
||||
*/
|
||||
export const EVENTS_DEMO_PROFILES = [...DEMO_PROFILES, ...DEMO_SCENARIO_KEYS] as const;
|
||||
export const eventsDemoProfileSchema = z.enum(EVENTS_DEMO_PROFILES);
|
||||
|
||||
/**
|
||||
* The Church App's demo data sets: one per scenario (1.21.0; 1.20.0's `acacia-hill` is the
|
||||
* `community-family` scenario, and no App had shipped with it).
|
||||
*/
|
||||
export const APP_DEMO_PROFILES = DEMO_SCENARIO_KEYS;
|
||||
export const appDemoProfileSchema = z.enum(APP_DEMO_PROFILES);
|
||||
export type AppDemoProfile = z.infer<typeof appDemoProfileSchema>;
|
||||
|
||||
/** Accounts' demo data sets (1.21.0): a scenario's church profile and people. One per scenario. */
|
||||
export const ACCOUNTS_DEMO_PROFILES = DEMO_SCENARIO_KEYS;
|
||||
|
||||
/** The products with demo data (`seed-demo` jobs). 1.20.0 adds `app`, 1.21.0 `accounts`. */
|
||||
export const DEMO_PRODUCTS = ["events", "website", "app", "accounts"] as const;
|
||||
export const demoProductSchema = z.enum(DEMO_PRODUCTS);
|
||||
export type DemoProduct = z.infer<typeof demoProductSchema>;
|
||||
|
||||
/** Each demo product's profiles. */
|
||||
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = { events: DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES };
|
||||
export const DEMO_PROFILES_BY_PRODUCT: Record<DemoProduct, readonly string[]> = {
|
||||
events: EVENTS_DEMO_PROFILES, website: WEBSITE_DEMO_PROFILES, app: APP_DEMO_PROFILES, accounts: ACCOUNTS_DEMO_PROFILES,
|
||||
};
|
||||
|
||||
const DEMO_PRODUCT_NAMES: Record<DemoProduct, string> = { events: "Cross Events", website: "Website", app: "App", accounts: "Accounts" };
|
||||
|
||||
/** The order a scenario loads in: Accounts first (the profile and people the others read). */
|
||||
export const DEMO_SCENARIO_ORDER = ["accounts", "events", "website", "app"] as const satisfies readonly DemoProduct[];
|
||||
|
||||
/** The first release of each product that loads a scenario (`--scenario`). The Hub refuses a scenario for an older install. */
|
||||
export const DEMO_SCENARIO_MIN_VERSIONS: Record<DemoProduct, string> = { accounts: "1.9.0", events: "3.8.0", website: "1.8.0", app: "1.0.0" };
|
||||
|
||||
export interface DemoScenario {
|
||||
key: DemoScenarioKey;
|
||||
/** The church's name in the demo. */
|
||||
church: string;
|
||||
/** For the Hub's list. */
|
||||
label: string;
|
||||
description: string;
|
||||
/** The profile each product loads. */
|
||||
profiles: { accounts: string; events: string; website: string; app: string };
|
||||
/** Campuses in the church profile. */
|
||||
campuses: number;
|
||||
/** The demo's main language (Afrikaans content and devotionals for `af`). */
|
||||
language: "en" | "af";
|
||||
/** The App's active-member band its people give it, so the scenarios show the Hub's tiers. */
|
||||
appActiveMembers: (typeof ACTIVE_MEMBER_BANDS)[number];
|
||||
}
|
||||
|
||||
const scenario = (key: DemoScenarioKey, s: Omit<DemoScenario, "key" | "profiles">): DemoScenario =>
|
||||
({ key, ...s, profiles: { accounts: key, events: key, website: key, app: key } });
|
||||
|
||||
/** The eight scenarios (Joshua, 2026-11-30). Every church and person in them is fictional. */
|
||||
export const DEMO_SCENARIOS: readonly DemoScenario[] = [
|
||||
scenario("heritage-parish", {
|
||||
church: "St Columba's", label: "Heritage: St Columba's, a parish church",
|
||||
description: "A 120-year-old parish church, small and older, one Sunday service. Carols, a harvest festival, a quiet prayer wall and a Lent campaign.",
|
||||
campuses: 1, language: "en", appActiveMembers: "0–100",
|
||||
}),
|
||||
scenario("heritage-city", {
|
||||
church: "Grace Cathedral", label: "Heritage: Grace Cathedral, a city-centre church",
|
||||
description: "Three Sunday services and lunchtime prayer. A concert series, ticketed Easter services, a prayer wall full in office hours with gaps at night.",
|
||||
campuses: 1, language: "en", appActiveMembers: "301–750",
|
||||
}),
|
||||
scenario("bold-youth", {
|
||||
church: "Ignite Church", label: "Bold: Ignite Church, young and music-led",
|
||||
description: "A youth conference with paid registration and a worship night, a 21-day prayer campaign before it, testimonies and WhatsApp reminders.",
|
||||
campuses: 1, language: "en", appActiveMembers: "751–2 000",
|
||||
}),
|
||||
scenario("bold-plant", {
|
||||
church: "Harbour City", label: "Bold: Harbour City, a new church plant",
|
||||
description: "Two years old, meeting in a school hall. Launch Sunday, a newcomers' lunch, a prayer wall still filling up and the admin's setup half done.",
|
||||
campuses: 1, language: "en", appActiveMembers: "0–100",
|
||||
}),
|
||||
scenario("community-family", {
|
||||
church: "Acacia Hill", label: "Community: Acacia Hill, a family church",
|
||||
description: "The mockup's church (cross-demo2). Kids' club, Alpha, family camp and volunteer rosters, a 21-day campaign, prayer requests waiting for approval.",
|
||||
campuses: 1, language: "en", appActiveMembers: "101–300",
|
||||
}),
|
||||
scenario("community-town", {
|
||||
church: "Karoo Gemeenskapskerk", label: "Community: Karoo Gemeenskapskerk, a country-town church",
|
||||
description: "Mostly Afrikaans. A bazaar and a prayer breakfast, its own AFR83 devotionals, 30-minute prayer slots.",
|
||||
campuses: 1, language: "af", appActiveMembers: "101–300",
|
||||
}),
|
||||
scenario("clean-modern", {
|
||||
church: "Northpoint", label: "Clean: Northpoint, a contemporary church",
|
||||
description: "About 600 people. Courses, a groups launch and serve teams, every prayer hour covered twice, announcements by WhatsApp.",
|
||||
campuses: 1, language: "en", appActiveMembers: "301–750",
|
||||
}),
|
||||
scenario("clean-campus", {
|
||||
church: "Riverside", label: "Clean: Riverside, three campuses near the university",
|
||||
description: "Student welcome week at one campus and a combined worship night, one prayer wall for all three, announcements per campus.",
|
||||
campuses: 3, language: "en", appActiveMembers: "2 001–5 000",
|
||||
}),
|
||||
];
|
||||
|
||||
export function demoScenario(key: DemoScenarioKey): DemoScenario {
|
||||
return DEMO_SCENARIOS.find((s) => s.key === key)!;
|
||||
}
|
||||
|
||||
/** The first agent that runs `seed-demo` jobs (an older one refuses the unknown type). */
|
||||
export const SEED_DEMO_MIN_AGENT = "1.2.0";
|
||||
@@ -86,6 +194,20 @@ export const SEED_DEMO_MIN_AGENT = "1.2.0";
|
||||
/** The first agent that runs `seed-demo` jobs for the Website (`product: "website"`; an older one refuses the unknown key). */
|
||||
export const SEED_WEBSITE_DEMO_MIN_AGENT = "1.6.0";
|
||||
|
||||
/**
|
||||
* The first agent that runs `seed-demo` jobs for the App (`product: "app"`; an older one passes no
|
||||
* product to the script, so the Hub mustn't send it one). Agent 1.7.0 ships with App 1.0.0.
|
||||
*/
|
||||
export const SEED_APP_DEMO_MIN_AGENT = "1.7.0";
|
||||
|
||||
/** 1.21.0: the first agent that runs `seed-demo` for Accounts and with a `scenario` (passed on as `--scenario`). */
|
||||
export const SEED_SCENARIO_MIN_AGENT = "1.7.0";
|
||||
|
||||
/** The first agent that runs a product's `seed-demo` jobs. */
|
||||
export const SEED_DEMO_MIN_AGENT_BY_PRODUCT: Record<DemoProduct, string> = {
|
||||
events: SEED_DEMO_MIN_AGENT, website: SEED_WEBSITE_DEMO_MIN_AGENT, app: SEED_APP_DEMO_MIN_AGENT, accounts: SEED_SCENARIO_MIN_AGENT,
|
||||
};
|
||||
|
||||
/** The first agent that runs `env-read` and `env-set` jobs (an older one refuses the unknown types). */
|
||||
export const ENV_JOBS_MIN_AGENT = "1.3.0";
|
||||
|
||||
@@ -159,21 +281,29 @@ export const jobArgsSchemas = {
|
||||
/** `crosscode restart <church> [product] --json` (PM2 reload) */
|
||||
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
|
||||
/**
|
||||
* `crosscode demo <church> [website] --profile <profile> [--admin-email <email>] --json`: replaces
|
||||
* `crosscode demo <church> [website|app|accounts] --profile <profile> [--scenario <s>] [--admin-email <email>] --json`: replaces
|
||||
* Cross Events' data (or, 1.19.0 with `product: "website"`, the Website's content) with a demo
|
||||
* set (a backup is taken first). The Hub only makes it for installs marked as demo sites.
|
||||
* set (a backup is taken first); 1.20.0 adds `product: "app"` (the App's prayer wall, campaign,
|
||||
* testimonies, devotionals, announcements and events). The Hub only makes it for installs marked as demo sites.
|
||||
* `adminEmail` (Events only): the account kept (default: the release's own choice). No `product`
|
||||
* is Events, so older Hubs' jobs mean what they did.
|
||||
* is Events, so older Hubs' jobs mean what they did. 1.21.0: `product: "accounts"` (the
|
||||
* scenario's church profile, with its logo and icon, and its people) and `scenario`: one job per
|
||||
* product in `DEMO_SCENARIO_ORDER`, each with the scenario's profile for that product.
|
||||
*/
|
||||
"seed-demo": z.strictObject({
|
||||
church: shortNameSchema,
|
||||
product: demoProductSchema.optional(),
|
||||
profile: z.union([demoProfileSchema, websiteDemoProfileSchema]),
|
||||
profile: z.union([eventsDemoProfileSchema, websiteDemoProfileSchema, appDemoProfileSchema]),
|
||||
adminEmail: z.email().max(254).optional(),
|
||||
/** 1.21.0: part of loading this scenario (the profile must be the scenario's for the product). */
|
||||
scenario: demoScenarioSchema.optional(),
|
||||
}).superRefine((a, ctx) => {
|
||||
const product = a.product ?? "events";
|
||||
if (!DEMO_PROFILES_BY_PRODUCT[product].includes(a.profile)) ctx.addIssue({ code: "custom", path: ["profile"], message: `${a.profile} isn't a ${product} demo` });
|
||||
if (product === "website" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: "the Website's demo keeps every admin" });
|
||||
if (product !== "events" && a.adminEmail) ctx.addIssue({ code: "custom", path: ["adminEmail"], message: `the ${DEMO_PRODUCT_NAMES[product]}'s demo keeps every admin` });
|
||||
if (a.scenario && demoScenario(a.scenario).profiles[product] !== a.profile) {
|
||||
ctx.addIssue({ code: "custom", path: ["profile"], message: `the ${a.scenario} scenario loads ${demoScenario(a.scenario).profiles[product]} in ${DEMO_PRODUCT_NAMES[product]}` });
|
||||
}
|
||||
}),
|
||||
/**
|
||||
* `crosscode env <church> <product> --json`: the product's .env values, secrets hidden (only
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Bible passages for the Church App's devotionals (contracts 1.20.0, docs/APP-1.0-PLAN.md §6,
|
||||
* decisions 5 and 10): the books (USFM codes, as YouVersion uses them), the translations a
|
||||
* devotional can quote, reading a reference someone typed ("John 3:16-18", "Johannes 3:16–18",
|
||||
* "1 Kor 13:4-7"), and the "Read in YouVersion" link.
|
||||
*
|
||||
* Shared by the Hub and the App, so a CSV row the Hub accepts is one the App accepts.
|
||||
*/
|
||||
|
||||
// ─── Translations ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The translations a devotional can use. An id never changes once released; more can be added.
|
||||
* `youVersionId` is the version's number on bible.com (`bible.com/bible/<id>/JHN.3.16.<abbr>`).
|
||||
* `copyright` is shown under the verse wherever it's quoted. Check each publisher's terms for use
|
||||
* in an app before Cross Code's devotionals go out (APP-1.0-PLAN, "Still open").
|
||||
*/
|
||||
export const BIBLE_TRANSLATIONS = [
|
||||
{
|
||||
id: "NLT", name: "New Living Translation", language: "en", youVersionId: 116,
|
||||
copyright: "Scripture quotations are taken from the Holy Bible, New Living Translation, copyright © 1996, 2004, 2015 by Tyndale House Foundation. Used by permission of Tyndale House Publishers, Carol Stream, Illinois 60188. All rights reserved.",
|
||||
},
|
||||
{
|
||||
id: "ESV", name: "English Standard Version", language: "en", youVersionId: 59,
|
||||
copyright: "Scripture quotations are from the ESV® Bible (The Holy Bible, English Standard Version®), © 2001 by Crossway, a publishing ministry of Good News Publishers. Used by permission. All rights reserved.",
|
||||
},
|
||||
{
|
||||
id: "NIV", name: "New International Version", language: "en", youVersionId: 111,
|
||||
copyright: "Scripture quotations taken from The Holy Bible, New International Version® NIV®. Copyright © 1973, 1978, 1984, 2011 by Biblica, Inc.™ Used by permission. All rights reserved worldwide.",
|
||||
},
|
||||
{
|
||||
id: "NKJV", name: "New King James Version", language: "en", youVersionId: 114,
|
||||
copyright: "Scripture taken from the New King James Version®. Copyright © 1982 by Thomas Nelson. Used by permission. All rights reserved.",
|
||||
},
|
||||
{
|
||||
id: "KJV", name: "King James Version", language: "en", youVersionId: 1,
|
||||
copyright: "King James Version. Public domain.",
|
||||
},
|
||||
{
|
||||
id: "AFR53", name: "Afrikaans 1933/1953-vertaling", language: "af", youVersionId: 5,
|
||||
copyright: "Die Bybel in Afrikaans, 1933/1953-vertaling. © Bybelgenootskap van Suid-Afrika. Gebruik met toestemming.",
|
||||
},
|
||||
{
|
||||
id: "AFR83", name: "Afrikaans 1983-vertaling", language: "af", youVersionId: 6,
|
||||
copyright: "Die Bybel in Afrikaans, 1983-vertaling. © Bybelgenootskap van Suid-Afrika 1983. Gebruik met toestemming.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type BibleTranslation = (typeof BIBLE_TRANSLATIONS)[number];
|
||||
export const BIBLE_TRANSLATION_IDS = BIBLE_TRANSLATIONS.map((t) => t.id) as [BibleTranslation["id"], ...BibleTranslation["id"][]];
|
||||
export const bibleTranslationIdSchema = z.enum(BIBLE_TRANSLATION_IDS);
|
||||
export type BibleTranslationId = z.infer<typeof bibleTranslationIdSchema>;
|
||||
|
||||
export function bibleTranslation(id: BibleTranslationId): BibleTranslation {
|
||||
return BIBLE_TRANSLATIONS.find((t) => t.id === id)!;
|
||||
}
|
||||
|
||||
/** A passage longer than this gets a warning: quote the passage, not whole chapters (§6). */
|
||||
export const PASSAGE_WARN_VERSES = 25;
|
||||
|
||||
// ─── Books ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The 66 books in order: USFM code, English and Afrikaans names, chapters (English numbering) and
|
||||
* the other names and abbreviations a reference may use. Matching ignores case, accents, dots and
|
||||
* spaces, so "1 Kor.", "1kor" and "1 Korintiërs" are the same book.
|
||||
*/
|
||||
export const BIBLE_BOOKS = [
|
||||
{ code: "GEN", en: "Genesis", af: "Genesis", chapters: 50, aliases: ["Gen", "Ge", "Gn"] },
|
||||
{ code: "EXO", en: "Exodus", af: "Eksodus", chapters: 40, aliases: ["Exod", "Exo", "Ex", "Eks"] },
|
||||
{ code: "LEV", en: "Leviticus", af: "Levitikus", chapters: 27, aliases: ["Lev", "Le", "Lv"] },
|
||||
{ code: "NUM", en: "Numbers", af: "Numeri", chapters: 36, aliases: ["Num", "Nu", "Nm", "Nb"] },
|
||||
{ code: "DEU", en: "Deuteronomy", af: "Deuteronomium", chapters: 34, aliases: ["Deut", "Deu", "Dt", "Dtn"] },
|
||||
{ code: "JOS", en: "Joshua", af: "Josua", chapters: 24, aliases: ["Josh", "Jos", "Jsh"] },
|
||||
{ code: "JDG", en: "Judges", af: "Rigters", chapters: 21, aliases: ["Judg", "Jdg", "Jdgs", "Rig"] },
|
||||
{ code: "RUT", en: "Ruth", af: "Rut", chapters: 4, aliases: ["Rth", "Ru"] },
|
||||
{ code: "1SA", en: "1 Samuel", af: "1 Samuel", chapters: 31, aliases: ["1 Sam", "1 Sa", "1Sm"] },
|
||||
{ code: "2SA", en: "2 Samuel", af: "2 Samuel", chapters: 24, aliases: ["2 Sam", "2 Sa", "2Sm"] },
|
||||
{ code: "1KI", en: "1 Kings", af: "1 Konings", chapters: 22, aliases: ["1 Kgs", "1 Ki", "1 Kon"] },
|
||||
{ code: "2KI", en: "2 Kings", af: "2 Konings", chapters: 25, aliases: ["2 Kgs", "2 Ki", "2 Kon"] },
|
||||
{ code: "1CH", en: "1 Chronicles", af: "1 Kronieke", chapters: 29, aliases: ["1 Chron", "1 Chr", "1 Ch", "1 Kron", "1 Kr"] },
|
||||
{ code: "2CH", en: "2 Chronicles", af: "2 Kronieke", chapters: 36, aliases: ["2 Chron", "2 Chr", "2 Ch", "2 Kron", "2 Kr"] },
|
||||
{ code: "EZR", en: "Ezra", af: "Esra", chapters: 10, aliases: ["Ezr", "Esr"] },
|
||||
{ code: "NEH", en: "Nehemiah", af: "Nehemia", chapters: 13, aliases: ["Neh", "Ne"] },
|
||||
{ code: "EST", en: "Esther", af: "Ester", chapters: 10, aliases: ["Esth", "Est", "Es"] },
|
||||
{ code: "JOB", en: "Job", af: "Job", chapters: 42, aliases: ["Jb"] },
|
||||
{ code: "PSA", en: "Psalms", af: "Psalms", chapters: 150, aliases: ["Psalm", "Ps", "Psa", "Pss", "Psalmen"] },
|
||||
{ code: "PRO", en: "Proverbs", af: "Spreuke", chapters: 31, aliases: ["Prov", "Pro", "Prv", "Pr", "Spr"] },
|
||||
{ code: "ECC", en: "Ecclesiastes", af: "Prediker", chapters: 12, aliases: ["Eccl", "Ecc", "Ec", "Qoh", "Pred", "Pr"] },
|
||||
{ code: "SNG", en: "Song of Songs", af: "Hooglied", chapters: 8, aliases: ["Song of Solomon", "Song", "Sos", "Sng", "Hgl", "Hoogl"] },
|
||||
{ code: "ISA", en: "Isaiah", af: "Jesaja", chapters: 66, aliases: ["Isa", "Is", "Jes"] },
|
||||
{ code: "JER", en: "Jeremiah", af: "Jeremia", chapters: 52, aliases: ["Jer", "Je", "Jr"] },
|
||||
{ code: "LAM", en: "Lamentations", af: "Klaagliedere", chapters: 5, aliases: ["Lam", "La", "Klaagl", "Kla"] },
|
||||
{ code: "EZK", en: "Ezekiel", af: "Esegiël", chapters: 48, aliases: ["Ezek", "Eze", "Ezk", "Eseg", "Ese"] },
|
||||
{ code: "DAN", en: "Daniel", af: "Daniël", chapters: 12, aliases: ["Dan", "Da", "Dn"] },
|
||||
{ code: "HOS", en: "Hosea", af: "Hosea", chapters: 14, aliases: ["Hos", "Ho"] },
|
||||
{ code: "JOL", en: "Joel", af: "Joël", chapters: 3, aliases: ["Joe", "Jl"] },
|
||||
{ code: "AMO", en: "Amos", af: "Amos", chapters: 9, aliases: ["Am", "Amo"] },
|
||||
{ code: "OBA", en: "Obadiah", af: "Obadja", chapters: 1, aliases: ["Obad", "Ob", "Oba"] },
|
||||
{ code: "JON", en: "Jonah", af: "Jona", chapters: 4, aliases: ["Jnh", "Jon"] },
|
||||
{ code: "MIC", en: "Micah", af: "Miga", chapters: 7, aliases: ["Mic", "Mi", "Mig"] },
|
||||
{ code: "NAM", en: "Nahum", af: "Nahum", chapters: 3, aliases: ["Nah", "Na"] },
|
||||
{ code: "HAB", en: "Habakkuk", af: "Habakuk", chapters: 3, aliases: ["Hab", "Hb"] },
|
||||
{ code: "ZEP", en: "Zephaniah", af: "Sefanja", chapters: 3, aliases: ["Zeph", "Zep", "Zp", "Sef"] },
|
||||
{ code: "HAG", en: "Haggai", af: "Haggai", chapters: 2, aliases: ["Hag", "Hg"] },
|
||||
{ code: "ZEC", en: "Zechariah", af: "Sagaria", chapters: 14, aliases: ["Zech", "Zec", "Zc", "Sag"] },
|
||||
{ code: "MAL", en: "Malachi", af: "Maleagi", chapters: 4, aliases: ["Mal", "Ml"] },
|
||||
{ code: "MAT", en: "Matthew", af: "Matteus", chapters: 28, aliases: ["Matt", "Mat", "Mt", "Mattheus", "Matt."] },
|
||||
{ code: "MRK", en: "Mark", af: "Markus", chapters: 16, aliases: ["Mrk", "Mar", "Mk", "Mr", "Mark."] },
|
||||
{ code: "LUK", en: "Luke", af: "Lukas", chapters: 24, aliases: ["Luk", "Lk", "Lu"] },
|
||||
{ code: "JHN", en: "John", af: "Johannes", chapters: 21, aliases: ["Jhn", "Jn", "Joh"] },
|
||||
{ code: "ACT", en: "Acts", af: "Handelinge", chapters: 28, aliases: ["Act", "Ac", "Hand", "Hnd"] },
|
||||
{ code: "ROM", en: "Romans", af: "Romeine", chapters: 16, aliases: ["Rom", "Ro", "Rm"] },
|
||||
{ code: "1CO", en: "1 Corinthians", af: "1 Korintiërs", chapters: 16, aliases: ["1 Cor", "1 Co", "1 Kor", "1 Ko"] },
|
||||
{ code: "2CO", en: "2 Corinthians", af: "2 Korintiërs", chapters: 13, aliases: ["2 Cor", "2 Co", "2 Kor", "2 Ko"] },
|
||||
{ code: "GAL", en: "Galatians", af: "Galasiërs", chapters: 6, aliases: ["Gal", "Ga"] },
|
||||
{ code: "EPH", en: "Ephesians", af: "Efesiërs", chapters: 6, aliases: ["Eph", "Ephes", "Ef"] },
|
||||
{ code: "PHP", en: "Philippians", af: "Filippense", chapters: 4, aliases: ["Phil", "Php", "Pp", "Fil"] },
|
||||
{ code: "COL", en: "Colossians", af: "Kolossense", chapters: 4, aliases: ["Col", "Co", "Kol"] },
|
||||
{ code: "1TH", en: "1 Thessalonians", af: "1 Tessalonisense", chapters: 5, aliases: ["1 Thess", "1 Thes", "1 Th", "1 Tess", "1 Tes"] },
|
||||
{ code: "2TH", en: "2 Thessalonians", af: "2 Tessalonisense", chapters: 3, aliases: ["2 Thess", "2 Thes", "2 Th", "2 Tess", "2 Tes"] },
|
||||
{ code: "1TI", en: "1 Timothy", af: "1 Timoteus", chapters: 6, aliases: ["1 Tim", "1 Ti", "1 Tm"] },
|
||||
{ code: "2TI", en: "2 Timothy", af: "2 Timoteus", chapters: 4, aliases: ["2 Tim", "2 Ti", "2 Tm"] },
|
||||
{ code: "TIT", en: "Titus", af: "Titus", chapters: 3, aliases: ["Tit", "Ti"] },
|
||||
{ code: "PHM", en: "Philemon", af: "Filemon", chapters: 1, aliases: ["Philem", "Phm", "Pm", "Filem", "Flm"] },
|
||||
{ code: "HEB", en: "Hebrews", af: "Hebreërs", chapters: 13, aliases: ["Heb", "He"] },
|
||||
{ code: "JAS", en: "James", af: "Jakobus", chapters: 5, aliases: ["Jas", "Jm", "Jak"] },
|
||||
{ code: "1PE", en: "1 Peter", af: "1 Petrus", chapters: 5, aliases: ["1 Pet", "1 Pe", "1 Pt", "1 Petr"] },
|
||||
{ code: "2PE", en: "2 Peter", af: "2 Petrus", chapters: 3, aliases: ["2 Pet", "2 Pe", "2 Pt", "2 Petr"] },
|
||||
{ code: "1JN", en: "1 John", af: "1 Johannes", chapters: 5, aliases: ["1 Jn", "1 Jhn", "1 Joh"] },
|
||||
{ code: "2JN", en: "2 John", af: "2 Johannes", chapters: 1, aliases: ["2 Jn", "2 Jhn", "2 Joh"] },
|
||||
{ code: "3JN", en: "3 John", af: "3 Johannes", chapters: 1, aliases: ["3 Jn", "3 Jhn", "3 Joh"] },
|
||||
{ code: "JUD", en: "Jude", af: "Judas", chapters: 1, aliases: ["Jud", "Jd"] },
|
||||
{ code: "REV", en: "Revelation", af: "Openbaring", chapters: 22, aliases: ["Rev", "Re", "Rv", "Revelations", "Op", "Openb"] },
|
||||
] as const;
|
||||
|
||||
export type BibleBook = (typeof BIBLE_BOOKS)[number];
|
||||
export const BIBLE_BOOK_CODES = BIBLE_BOOKS.map((b) => b.code) as [BibleBook["code"], ...BibleBook["code"][]];
|
||||
export const bibleBookCodeSchema = z.enum(BIBLE_BOOK_CODES);
|
||||
export type BibleBookCode = z.infer<typeof bibleBookCodeSchema>;
|
||||
|
||||
export function bibleBook(code: BibleBookCode): BibleBook {
|
||||
return BIBLE_BOOKS.find((b) => b.code === code)!;
|
||||
}
|
||||
|
||||
/** "1 Korintiërs." → "1korintiers": lower case, no accents, dots or spaces. */
|
||||
function bookKey(name: string): string {
|
||||
return name.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[.\s]/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Name → book. An abbreviation two books share (`Pr`: Proverbs and Prediker, `Co`, `Ti`) goes to
|
||||
* the first, so the full names always work and the common short forms mostly do.
|
||||
*/
|
||||
const BOOK_BY_KEY: ReadonlyMap<string, BibleBook> = (() => {
|
||||
const map = new Map<string, BibleBook>();
|
||||
for (const book of BIBLE_BOOKS) {
|
||||
for (const name of [book.code, book.en, book.af, ...book.aliases]) {
|
||||
const key = bookKey(name);
|
||||
if (!map.has(key)) map.set(key, book);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
})();
|
||||
|
||||
/** The book a name or abbreviation means, or null. */
|
||||
export function findBibleBook(name: string): BibleBook | null {
|
||||
return BOOK_BY_KEY.get(bookKey(name)) ?? null;
|
||||
}
|
||||
|
||||
// ─── Passages ────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Where a passage is: a book, a start verse and an end verse (the same chapter or a later one).
|
||||
* A whole chapter isn't a passage here: devotionals quote the verses they're about (§6).
|
||||
*/
|
||||
export const passageLocationSchema = z.object({
|
||||
book: bibleBookCodeSchema,
|
||||
chapter: z.int().min(1).max(150),
|
||||
verse: z.int().min(1).max(176),
|
||||
endChapter: z.int().min(1).max(150),
|
||||
endVerse: z.int().min(1).max(176),
|
||||
}).refine((p) => p.endChapter > p.chapter || (p.endChapter === p.chapter && p.endVerse >= p.verse), "The passage ends before it starts")
|
||||
.refine((p) => p.endChapter <= bibleBook(p.book).chapters, "The book has fewer chapters");
|
||||
export type PassageLocation = z.infer<typeof passageLocationSchema>;
|
||||
|
||||
export type ParsedReference = { ok: true; passage: PassageLocation } | { ok: false; error: string };
|
||||
|
||||
/**
|
||||
* Reads a reference as people type it: `John 3:16`, `John 3:16-18`, `Johannes 3:16–18`,
|
||||
* `1 Kor. 13:4-7`, `Rom 8:38-9:1`, `Ps 23 1-3` (a space for the colon), `Jude 3` and `Jude 1:3`
|
||||
* (one-chapter books). Dashes may be `-`, `–` or `—`; `.` or `,` are taken for the colon too.
|
||||
*/
|
||||
export function parseBibleReference(input: string): ParsedReference {
|
||||
const text = input.trim().replace(/\s+/g, " ");
|
||||
const match = /^((?:[1-3]\s?)?[^\d\s][^\d]*?)\s*(\d+)(?:(?:\s*[:.,]\s*|\s+)(\d+))?(?:\s*[-–—]\s*(\d+)(?:\s*[:.,]\s*(\d+))?)?$/.exec(text);
|
||||
if (!match) return { ok: false, error: `"${input}" isn't a Bible reference (e.g. John 3:16-18)` };
|
||||
const [, name = "", a = "", b, c, d] = match;
|
||||
const book = findBibleBook(name);
|
||||
if (!book) return { ok: false, error: `"${name.trim()}" isn't a book of the Bible` };
|
||||
|
||||
let chapter: number, verse: number, endChapter: number, endVerse: number;
|
||||
if (b === undefined) {
|
||||
// "Jude 3" / "Jude 3-5": a verse in a one-chapter book. "John 3" alone is a whole chapter.
|
||||
if (book.chapters !== 1) return { ok: false, error: `Give the verses as well as the chapter (e.g. ${book.en} ${a}:1-12)` };
|
||||
if (d !== undefined) return { ok: false, error: `"${input}" isn't a Bible reference (e.g. ${book.en} 1:3-5)` };
|
||||
chapter = 1; verse = Number(a); endChapter = 1; endVerse = c === undefined ? verse : Number(c);
|
||||
} else {
|
||||
chapter = Number(a); verse = Number(b);
|
||||
if (d !== undefined) { endChapter = Number(c); endVerse = Number(d); }
|
||||
else { endChapter = chapter; endVerse = c === undefined ? verse : Number(c); }
|
||||
}
|
||||
if (chapter > book.chapters || endChapter > book.chapters) {
|
||||
return { ok: false, error: `${book.en} has ${book.chapters} chapter${book.chapters === 1 ? "" : "s"}` };
|
||||
}
|
||||
const parsed = passageLocationSchema.safeParse({ book: book.code, chapter, verse, endChapter, endVerse });
|
||||
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? "Not a passage" };
|
||||
return { ok: true, passage: parsed.data };
|
||||
}
|
||||
|
||||
/** `John 3:16–18`, `Johannes 3:16`, `Romans 8:38–9:1`, in the translation's language. */
|
||||
export function formatBibleReference(p: PassageLocation, language: "en" | "af" = "en"): string {
|
||||
const book = bibleBook(p.book);
|
||||
const start = `${language === "af" ? book.af : book.en} ${p.chapter}:${p.verse}`;
|
||||
if (p.endChapter !== p.chapter) return `${start}–${p.endChapter}:${p.endVerse}`;
|
||||
return p.endVerse === p.verse ? start : `${start}–${p.endVerse}`;
|
||||
}
|
||||
|
||||
/** How many verses, when the passage stays in one chapter (null across chapters: verse counts per chapter aren't kept). */
|
||||
export function passageVerseCount(p: PassageLocation): number | null {
|
||||
return p.endChapter === p.chapter ? p.endVerse - p.verse + 1 : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Read in YouVersion": `https://www.bible.com/bible/116/JHN.3.16-18.NLT`. YouVersion opens its
|
||||
* app instead where it's installed. Across chapters it opens at the first verse's chapter.
|
||||
*/
|
||||
export function youVersionUrl(p: PassageLocation, translation: BibleTranslationId): string {
|
||||
const t = bibleTranslation(translation);
|
||||
const verses = p.endChapter === p.chapter && p.endVerse !== p.verse ? `${p.verse}-${p.endVerse}` : `${p.verse}`;
|
||||
return `https://www.bible.com/bible/${t.youVersionId}/${p.book}.${p.chapter}.${verses}.${t.id}`;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, productSchema, timezoneSchema, urlSchema } from "./common";
|
||||
import { dateSchema, dateTimeSchema, productSchema, timezoneSchema, urlSchema } from "./common";
|
||||
import { devotionalContentSchema, devotionalSourceSchema } from "./devotional";
|
||||
import { websiteTemplateSchema } from "./style";
|
||||
|
||||
/**
|
||||
@@ -23,6 +24,8 @@ export const exportPersonSchema = z.object({
|
||||
email: text(254).nullable(),
|
||||
phone: text(40).nullable(),
|
||||
role: text(40),
|
||||
/** 1.20.0: every role, where a product gives a person several (the App). `role` is the highest. */
|
||||
roles: z.array(text(40)).optional(),
|
||||
createdAt: when,
|
||||
consent: z.object({ email: z.boolean().nullable(), whatsapp: z.boolean().nullable(), privacyNoticeAcceptedAt: when }),
|
||||
});
|
||||
@@ -134,6 +137,103 @@ export const exportWebsiteSchema = z.object({
|
||||
});
|
||||
export type ExportWebsite = z.infer<typeof exportWebsiteSchema>;
|
||||
|
||||
// The App's part (contracts 1.20.0, APP-1.0-PLAN §11): the prayer wall's rules, commitments as
|
||||
// the rules they are (not every occurrence), "I prayed" marks, campaigns, testimonies, prayer
|
||||
// requests (the whole export is encrypted, AGENT-1.0-PLAN §9), announcements, the church's own
|
||||
// devotionals (not Cross Code's) and simple events. Members' roles are in `people[].roles`.
|
||||
|
||||
export const exportAppCommitmentSchema = z.object({
|
||||
ref: ref("c"),
|
||||
personRef: ref("p").nullable(),
|
||||
/** The first slot, and its length (several slots in a row are one commitment). */
|
||||
startsAt: when,
|
||||
minutes: z.int().positive().max(24 * 60),
|
||||
repeats: z.enum(["once", "weekly", "daily"]),
|
||||
/** The last day of a recurring commitment (null for a one-off). */
|
||||
until: dateSchema.nullable(),
|
||||
/** Occurrences skipped, by the date they'd have started (in the church's timezone). */
|
||||
skipped: z.array(dateSchema),
|
||||
reminder: z.enum(["none", "15m", "1h", "evening"]),
|
||||
channel: z.enum(["email", "whatsapp", "both"]),
|
||||
/** The member's own "where I'll pray" note. */
|
||||
note: text(500).nullable(),
|
||||
createdAt: when,
|
||||
/** When it was stopped early (the slots opened up). */
|
||||
stoppedAt: when,
|
||||
});
|
||||
|
||||
export const exportAppCampaignSchema = z.object({
|
||||
ref: ref("k"),
|
||||
title: text(300),
|
||||
description: text().nullable(),
|
||||
image: uploadPath.nullable(),
|
||||
startsOn: dateSchema,
|
||||
endsOn: dateSchema,
|
||||
goal: text(300).nullable(),
|
||||
slotTarget: z.int().positive(),
|
||||
});
|
||||
|
||||
export const exportAppPrayerRequestSchema = z.object({
|
||||
ref: ref("q"),
|
||||
/** Null for a fully anonymous request (P9). */
|
||||
personRef: ref("p").nullable(),
|
||||
visibility: z.enum(["team", "members"]),
|
||||
showName: z.boolean(),
|
||||
text: text(5000),
|
||||
status: z.enum(["waiting", "shared", "team", "escalated", "removed", "closed"]),
|
||||
prayedCount: z.int().nonnegative(),
|
||||
createdAt: when,
|
||||
closedAt: when,
|
||||
updates: z.array(z.object({ text: text(5000), at: when })),
|
||||
/** Approve, redact, remove, escalate, close: who and why (the audit, in plain terms). */
|
||||
moderation: z.array(z.object({ action: z.enum(["approved", "redacted", "removed", "escalated", "closed"]), by: text(300).nullable(), reason: text(1000).nullable(), at: when })),
|
||||
});
|
||||
|
||||
export const exportAppSchema = z.object({
|
||||
modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)),
|
||||
prayerWall: z.object({
|
||||
slotMinutes: z.union([z.literal(15), z.literal(30), z.literal(60)]),
|
||||
slotTarget: z.int().positive(),
|
||||
bookAheadMonths: z.int().min(1).max(12),
|
||||
recurringMaxMonths: z.int().min(1).max(12),
|
||||
cancelHours: z.int().min(0).max(48),
|
||||
/** Who members contact inside the cancel window. */
|
||||
contact: text(500).nullable(),
|
||||
}),
|
||||
commitments: z.array(exportAppCommitmentSchema),
|
||||
/** "I prayed" (self-reported), per slot. */
|
||||
prayed: z.array(z.object({ personRef: ref("p").nullable(), slotStartsAt: when, at: when })),
|
||||
campaigns: z.array(exportAppCampaignSchema),
|
||||
testimonies: z.array(z.object({
|
||||
personRef: ref("p").nullable(),
|
||||
campaignRef: ref("k").nullable(),
|
||||
text: text(5000),
|
||||
showName: z.boolean(),
|
||||
status: z.enum(["waiting", "shown", "removed"]),
|
||||
createdAt: when,
|
||||
})),
|
||||
prayerRequests: z.array(exportAppPrayerRequestSchema),
|
||||
safeguarding: z.object({ emergencyNumbers: z.array(z.object({ name: text(200), number: text(40) })) }),
|
||||
announcements: z.array(z.object({
|
||||
title: text(500),
|
||||
body: text(),
|
||||
image: uploadPath.nullable(),
|
||||
button: z.object({ label: text(100), url: urlSchema }).nullable(),
|
||||
campus: text(200).nullable(),
|
||||
audience: z.enum(["everyone", "members"]),
|
||||
pinned: z.boolean(),
|
||||
publishAt: when,
|
||||
endsAt: when,
|
||||
sent: z.object({ email: z.boolean(), whatsapp: z.boolean() }),
|
||||
})),
|
||||
/** `crosscode`: the App showed Cross Code's devotionals (they aren't exported: they're Cross Code's). */
|
||||
devotionalSource: devotionalSourceSchema,
|
||||
/** The church's own devotionals. */
|
||||
devotionals: z.array(devotionalContentSchema.extend({ membersOnly: z.boolean() })),
|
||||
events: z.array(exportWebsiteEventSchema),
|
||||
});
|
||||
export type ExportApp = z.infer<typeof exportAppSchema>;
|
||||
|
||||
export const churchExportSchema = z.object({
|
||||
schema: z.literal("crosscode.church-export/1"),
|
||||
exportedAt: dateTimeSchema,
|
||||
@@ -152,6 +252,8 @@ export const churchExportSchema = z.object({
|
||||
files: z.array(z.object({ path: uploadPath, bytes: z.int().nonnegative() })),
|
||||
/** Only in the Website's export (contracts 1.17.0). Its editors are in `people`, with their roles. */
|
||||
website: exportWebsiteSchema.optional(),
|
||||
/** Only in the App's export (contracts 1.20.0). */
|
||||
app: exportAppSchema.optional(),
|
||||
});
|
||||
export type ChurchExport = z.infer<typeof churchExportSchema>;
|
||||
|
||||
|
||||
@@ -16,6 +16,15 @@ export const EVENT_PRODUCTS = ["events", "website", "app"] as const;
|
||||
export const eventProductSchema = z.enum(EVENT_PRODUCTS);
|
||||
export type EventProduct = z.infer<typeof eventProductSchema>;
|
||||
|
||||
/**
|
||||
* The Church App's modules (contracts 1.20.0, APP-1.0-PLAN §2): each can be switched off. The App
|
||||
* reports the ones that are on in its heartbeat (`hub.appStatsSchema.modules`, which takes any
|
||||
* slug so a later module never breaks an older Hub).
|
||||
*/
|
||||
export const APP_MODULES = ["house-of-prayer", "prayer-requests", "announcements", "devotionals", "events"] as const;
|
||||
export const appModuleSchema = z.enum(APP_MODULES);
|
||||
export type AppModule = z.infer<typeof appModuleSchema>;
|
||||
|
||||
/** Ids are UUIDs everywhere: records, installs, licences, customers and account `sub`s. */
|
||||
export const idSchema = z.uuid();
|
||||
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
import { z } from "zod";
|
||||
import { dateSchema, dateTimeSchema, idSchema } from "./common";
|
||||
import { schemaName } from "./schema-name";
|
||||
import {
|
||||
BIBLE_TRANSLATION_IDS, PASSAGE_WARN_VERSES, bibleTranslation, bibleTranslationIdSchema, formatBibleReference,
|
||||
parseBibleReference, passageLocationSchema, passageVerseCount, type BibleTranslationId,
|
||||
} from "./bible";
|
||||
|
||||
/**
|
||||
* `crosscode.devotional/1` (contracts 1.20.0, docs/APP-1.0-PLAN.md §6, decision 1): one day's
|
||||
* devotional, the same whether Cross Code wrote it in the Hub or the church's Devotional writers
|
||||
* wrote it in the App, so both show and send alike.
|
||||
*
|
||||
* Cross Code's reach an App set to "From Cross Code" from the Hub: `GET /api/v2/devotionals`
|
||||
* (`hub.DEVOTIONALS_PATH`), once a night, the next 3 months (`devotionalsReplySchema`).
|
||||
*
|
||||
* Both write them by hand or import a CSV (`DEVOTIONAL_CSV_COLUMNS`, `checkDevotionalCsv`), with
|
||||
* the same checks in the Hub and the App.
|
||||
*/
|
||||
|
||||
export const DEVOTIONAL_SCHEMA = schemaName("devotional", 1);
|
||||
|
||||
/** Who wrote it: Cross Code (in the Hub) or the church (in the App). */
|
||||
export const DEVOTIONAL_SOURCES = ["crosscode", "church"] as const;
|
||||
export const devotionalSourceSchema = z.enum(DEVOTIONAL_SOURCES);
|
||||
export type DevotionalSource = z.infer<typeof devotionalSourceSchema>;
|
||||
|
||||
/** How far ahead the Hub schedules Cross Code's devotionals, and how far ahead an App fetches them. */
|
||||
export const CROSSCODE_DEVOTIONALS_AHEAD_MONTHS = 3;
|
||||
|
||||
export const DEVOTIONAL_LIMITS = { title: 200, reference: 100, passageText: 10_000, body: 20_000, prayer: 5_000, author: 200 } as const;
|
||||
|
||||
/**
|
||||
* The passage a devotional is about: where it is, the translation, and its text as quoted (shown
|
||||
* in full above the devotional, with the translation's copyright line). `reference` is how it's
|
||||
* written for people (`formatBibleReference`, in the translation's language).
|
||||
*/
|
||||
export const devotionalPassageSchema = z.object({
|
||||
reference: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.reference),
|
||||
location: passageLocationSchema,
|
||||
translation: bibleTranslationIdSchema,
|
||||
text: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.passageText),
|
||||
});
|
||||
export type DevotionalPassage = z.infer<typeof devotionalPassageSchema>;
|
||||
|
||||
/** What a writer fills in (the Hub's and App's forms, and a CSV row). */
|
||||
export const devotionalContentSchema = z.object({
|
||||
/** The day it's for, in the church's timezone: it shows on Home from midnight. */
|
||||
date: dateSchema,
|
||||
title: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.title),
|
||||
passage: devotionalPassageSchema,
|
||||
/** Markdown (sanitised when shown). */
|
||||
body: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.body),
|
||||
prayer: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.prayer).nullable(),
|
||||
author: z.string().trim().min(1).max(DEVOTIONAL_LIMITS.author).nullable(),
|
||||
});
|
||||
export type DevotionalContent = z.infer<typeof devotionalContentSchema>;
|
||||
|
||||
export const devotionalSchema = devotionalContentSchema.extend({
|
||||
schema: z.literal(DEVOTIONAL_SCHEMA),
|
||||
id: idSchema,
|
||||
source: devotionalSourceSchema,
|
||||
updatedAt: dateTimeSchema,
|
||||
});
|
||||
export type Devotional = z.infer<typeof devotionalSchema>;
|
||||
|
||||
/**
|
||||
* The Hub's answer to `GET /api/v2/devotionals?from=YYYY-MM-DD`: Cross Code's devotionals from
|
||||
* `from` to `to` (3 months on), one per day at most, oldest first. The App replaces its copy of
|
||||
* that range with them (a day missing from the list was removed in the Hub).
|
||||
*/
|
||||
export const devotionalsReplySchema = z.object({
|
||||
schema: z.literal(DEVOTIONAL_SCHEMA),
|
||||
from: dateSchema,
|
||||
to: dateSchema,
|
||||
devotionals: z.array(devotionalSchema.extend({ source: z.literal("crosscode") })).max(100),
|
||||
generatedAt: dateTimeSchema,
|
||||
});
|
||||
export type DevotionalsReply = z.infer<typeof devotionalsReplySchema>;
|
||||
|
||||
/** The passage's copyright line, shown under the verse. */
|
||||
export function devotionalCopyright(passage: Pick<DevotionalPassage, "translation">): string {
|
||||
return bibleTranslation(passage.translation).copyright;
|
||||
}
|
||||
|
||||
// ─── CSV import ──────────────────────────────────────────────────────────────
|
||||
|
||||
/** The columns, in this order in the template. A file may order them differently. */
|
||||
export const DEVOTIONAL_CSV_COLUMNS = ["date", "title", "passage", "translation", "passage_text", "body", "prayer", "author"] as const;
|
||||
export type DevotionalCsvColumn = (typeof DEVOTIONAL_CSV_COLUMNS)[number];
|
||||
const REQUIRED_COLUMNS: readonly DevotionalCsvColumn[] = ["date", "title", "passage", "translation", "passage_text", "body"];
|
||||
|
||||
/** Rows per import (a year and a bit), and the file size the Hub and App accept. */
|
||||
export const DEVOTIONAL_CSV_MAX_ROWS = 400;
|
||||
export const DEVOTIONAL_CSV_MAX_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Reads CSV (RFC 4180: quoted fields, `""` for a quote, line breaks inside quotes), with or
|
||||
* without a byte-order mark, CRLF or LF. A header with semicolons and no commas means the file
|
||||
* uses `;` (Excel in some regions). Blank lines are skipped. Each row comes with its line number.
|
||||
*/
|
||||
export function parseCsv(text: string): { line: number; cells: string[] }[] {
|
||||
const src = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
||||
const firstLine = src.slice(0, src.search(/\r?\n|$/));
|
||||
const sep = firstLine.includes(";") && !firstLine.includes(",") ? ";" : ",";
|
||||
const rows: { line: number; cells: string[] }[] = [];
|
||||
let cells: string[] = [];
|
||||
let cell = "";
|
||||
let quoted = false;
|
||||
let line = 1;
|
||||
let rowLine = 1;
|
||||
const endRow = () => {
|
||||
cells.push(cell);
|
||||
if (cells.length > 1 || cells[0]!.trim() !== "") rows.push({ line: rowLine, cells });
|
||||
cells = []; cell = "";
|
||||
};
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
if (quoted) {
|
||||
if (ch === '"') {
|
||||
if (src[i + 1] === '"') { cell += '"'; i++; } else quoted = false;
|
||||
} else {
|
||||
if (ch === "\n") line++;
|
||||
cell += ch;
|
||||
}
|
||||
} else if (ch === '"' && cell === "") quoted = true;
|
||||
else if (ch === sep) { cells.push(cell); cell = ""; }
|
||||
else if (ch === "\r" && src[i + 1] === "\n") continue;
|
||||
else if (ch === "\n" || ch === "\r") { endRow(); line++; rowLine = line; }
|
||||
else cell += ch;
|
||||
}
|
||||
if (cell !== "" || cells.length > 0) endRow();
|
||||
return rows;
|
||||
}
|
||||
|
||||
export interface DevotionalCsvIssue { column: DevotionalCsvColumn | null; message: string }
|
||||
|
||||
export interface DevotionalCsvRow {
|
||||
/** The row's line in the file (the header is line 1). */
|
||||
line: number;
|
||||
/** Null when the row has errors. */
|
||||
devotional: DevotionalContent | null;
|
||||
errors: DevotionalCsvIssue[];
|
||||
/** Imported anyway, but shown in the preview (a long passage). */
|
||||
warnings: DevotionalCsvIssue[];
|
||||
/** The date already has a devotional: the importer chooses to replace or skip it. */
|
||||
taken: boolean;
|
||||
}
|
||||
|
||||
export interface DevotionalCsvResult {
|
||||
/** Set when the file can't be read at all (no header, a required column missing, too big). */
|
||||
fileError: string | null;
|
||||
rows: DevotionalCsvRow[];
|
||||
}
|
||||
|
||||
export interface DevotionalCsvOptions {
|
||||
/** Dates that already have a devotional. */
|
||||
taken?: Iterable<string>;
|
||||
/** The last date allowed (the Hub: 3 months from today). Later dates are errors. */
|
||||
latestDate?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks a devotionals CSV for the import preview: the header, then every row (a real date,
|
||||
* the required fields, a passage YouVersion can open, a known translation, the lengths, a date
|
||||
* twice in the file, a date already filled). Never throws.
|
||||
*/
|
||||
export function checkDevotionalCsv(text: string, options: DevotionalCsvOptions = {}): DevotionalCsvResult {
|
||||
if (text.length > DEVOTIONAL_CSV_MAX_BYTES) return { fileError: "The file is larger than 2 MB", rows: [] };
|
||||
const all = parseCsv(text);
|
||||
const header = all[0];
|
||||
if (!header) return { fileError: "The file is empty", rows: [] };
|
||||
const names = header.cells.map((c) => c.trim().toLowerCase());
|
||||
const index = new Map<DevotionalCsvColumn, number>();
|
||||
for (const column of DEVOTIONAL_CSV_COLUMNS) {
|
||||
const i = names.indexOf(column);
|
||||
if (i >= 0) index.set(column, i);
|
||||
}
|
||||
const missing = REQUIRED_COLUMNS.filter((c) => !index.has(c));
|
||||
if (missing.length) return { fileError: `Missing column${missing.length === 1 ? "" : "s"}: ${missing.join(", ")} (the first row must be the column names)`, rows: [] };
|
||||
const body = all.slice(1);
|
||||
if (body.length === 0) return { fileError: "The file has no devotionals under the column names", rows: [] };
|
||||
if (body.length > DEVOTIONAL_CSV_MAX_ROWS) return { fileError: `At most ${DEVOTIONAL_CSV_MAX_ROWS} devotionals per file (this one has ${body.length})`, rows: [] };
|
||||
|
||||
const taken = new Set(options.taken ?? []);
|
||||
const seen = new Map<string, number>();
|
||||
const rows = body.map(({ line, cells }): DevotionalCsvRow => {
|
||||
const get = (c: DevotionalCsvColumn) => {
|
||||
const i = index.get(c);
|
||||
return i === undefined ? "" : (cells[i] ?? "").trim();
|
||||
};
|
||||
const errors: DevotionalCsvIssue[] = [];
|
||||
const warnings: DevotionalCsvIssue[] = [];
|
||||
const required = (c: DevotionalCsvColumn, label: string) => {
|
||||
const v = get(c);
|
||||
if (!v) errors.push({ column: c, message: `${label} is empty` });
|
||||
return v;
|
||||
};
|
||||
const tooLong = (c: DevotionalCsvColumn, v: string, max: number, label: string) => {
|
||||
if (v.length > max) errors.push({ column: c, message: `${label} is longer than ${max.toLocaleString("en-ZA")} characters` });
|
||||
};
|
||||
|
||||
const date = required("date", "The date");
|
||||
if (date && !dateSchema.safeParse(date).success) errors.push({ column: "date", message: `"${date}" isn't a date (use YYYY-MM-DD, e.g. 2027-01-05)` });
|
||||
else if (date && options.latestDate && date > options.latestDate) errors.push({ column: "date", message: `${date} is more than ${CROSSCODE_DEVOTIONALS_AHEAD_MONTHS} months ahead (the last day is ${options.latestDate})` });
|
||||
else if (date && seen.has(date)) errors.push({ column: "date", message: `${date} is also on line ${seen.get(date)}` });
|
||||
if (date && !seen.has(date)) seen.set(date, line);
|
||||
|
||||
const title = required("title", "The title");
|
||||
tooLong("title", title, DEVOTIONAL_LIMITS.title, "The title");
|
||||
|
||||
const translationText = required("translation", "The translation");
|
||||
const translation = BIBLE_TRANSLATION_IDS.find((id) => id === translationText.toUpperCase().replace(/\s/g, "")) as BibleTranslationId | undefined;
|
||||
if (translationText && !translation) errors.push({ column: "translation", message: `"${translationText}" isn't one of ${BIBLE_TRANSLATION_IDS.join(", ")}` });
|
||||
|
||||
const reference = required("passage", "The passage");
|
||||
const parsed = reference ? parseBibleReference(reference) : null;
|
||||
if (parsed && !parsed.ok) errors.push({ column: "passage", message: parsed.error });
|
||||
if (parsed?.ok) {
|
||||
const verses = passageVerseCount(parsed.passage);
|
||||
if (verses !== null && verses > PASSAGE_WARN_VERSES) {
|
||||
warnings.push({ column: "passage", message: `${verses} verses: quote the passage it's about, not whole chapters (publishers limit how much may be quoted)` });
|
||||
}
|
||||
}
|
||||
|
||||
const passageText = required("passage_text", "The passage's text");
|
||||
tooLong("passage_text", passageText, DEVOTIONAL_LIMITS.passageText, "The passage's text");
|
||||
const text = required("body", "The devotional");
|
||||
tooLong("body", text, DEVOTIONAL_LIMITS.body, "The devotional");
|
||||
const prayer = get("prayer");
|
||||
tooLong("prayer", prayer, DEVOTIONAL_LIMITS.prayer, "The prayer");
|
||||
const author = get("author");
|
||||
tooLong("author", author, DEVOTIONAL_LIMITS.author, "The author");
|
||||
|
||||
const isTaken = !!date && taken.has(date);
|
||||
if (errors.length || !parsed?.ok || !translation) return { line, devotional: null, errors, warnings, taken: isTaken };
|
||||
const devotional: DevotionalContent = {
|
||||
date, title,
|
||||
passage: {
|
||||
reference: formatBibleReference(parsed.passage, bibleTranslation(translation).language),
|
||||
location: parsed.passage, translation, text: passageText,
|
||||
},
|
||||
body: text, prayer: prayer || null, author: author || null,
|
||||
};
|
||||
const check = devotionalContentSchema.safeParse(devotional);
|
||||
if (!check.success) return { line, devotional: null, errors: check.error.issues.map((i) => ({ column: null, message: i.message })), warnings, taken: isTaken };
|
||||
return { line, devotional: check.data, errors, warnings, taken: isTaken };
|
||||
});
|
||||
return { fileError: null, rows };
|
||||
}
|
||||
|
||||
/** One field for a CSV file: quoted when it has a separator, quote or line break. */
|
||||
function csvField(value: string): string {
|
||||
return /[",;\r\n]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
|
||||
}
|
||||
|
||||
/** Builds a devotionals CSV (the template, or an export) with the columns in order and CRLF line ends. */
|
||||
export function devotionalCsv(rows: Partial<Record<DevotionalCsvColumn, string>>[]): string {
|
||||
const lines = [DEVOTIONAL_CSV_COLUMNS.join(","), ...rows.map((r) => DEVOTIONAL_CSV_COLUMNS.map((c) => csvField(r[c] ?? "")).join(","))];
|
||||
return `${lines.join("\r\n")}\r\n`;
|
||||
}
|
||||
|
||||
/** The template the Hub and the App offer for download: the columns and one example row. */
|
||||
export const DEVOTIONAL_CSV_TEMPLATE = devotionalCsv([{
|
||||
date: "2027-01-05",
|
||||
title: "Love that never gives up",
|
||||
passage: "1 Corinthians 13:4-7",
|
||||
translation: "NLT",
|
||||
passage_text: "Love is patient and kind. Love is not jealous or boastful or proud or rude. It does not demand its own way. It is not irritable, and it keeps no record of being wronged. It does not rejoice about injustice but rejoices whenever the truth wins out. Love never gives up, never loses faith, is always hopeful, and endures through every circumstance.",
|
||||
body: "Paul wrote these words to a church that was proud of its gifts...\n\nA second paragraph after a blank line.",
|
||||
prayer: "Lord, teach me to love the way you love me.",
|
||||
author: "Cross Code",
|
||||
}]);
|
||||
@@ -222,6 +222,7 @@ export const websiteStatsSchema = z.object({
|
||||
/** Church App. `activeMembers90d` is what the App tier is billed on. */
|
||||
export const appStatsSchema = z.object({
|
||||
activeMembers90d: activeMemberBandSchema,
|
||||
/** The modules switched on (`APP_MODULES`; any slug, so a later module never breaks an older Hub). */
|
||||
modules: z.array(z.string().regex(/^[a-z][a-z0-9-]*$/)),
|
||||
prayer: z.object({
|
||||
/** Share of the last 7 days' hours with at least one commitment, 0–100. */
|
||||
@@ -324,6 +325,17 @@ export const storageRequestResponseSchema = z.object({
|
||||
});
|
||||
export type StorageRequestResponse = z.infer<typeof storageRequestResponseSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Cross Code's devotionals (contracts 1.20.0, Hub 2.26.0, APP-1.0-PLAN §6): an App set to "From
|
||||
// Cross Code" fetches the next 3 months once a night (and on "Sync now"), and keeps its copy, so a
|
||||
// Hub outage changes nothing. `GET /api/v2/devotionals?from=YYYY-MM-DD` with
|
||||
// `Authorization: Bearer <the install's licence token>`; App licences only (`403 NOT_AN_APP`),
|
||||
// active or in grace (`403 LICENCE_INACTIVE`). The answer is a `devotionalsReplySchema`.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
export const DEVOTIONALS_PATH = "/api/v2/devotionals";
|
||||
export const DEVOTIONALS_ERROR_CODES = ["NOT_AN_APP", "LICENCE_INACTIVE", "BAD_LICENCE", "INVALID_REQUEST"] as const;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// AI (as v1; usage is recorded per product on the Hub, the cap stays per customer)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -16,7 +16,11 @@ import { churchObjectSchema, churchSchema } from "./church";
|
||||
* (`sealLinkValue` in `@crosscode/contracts/signing`) on top of the request signature.
|
||||
* - **`messaging.*`** (1.9.0): whether Accounts can send email and WhatsApp (its sign-in codes and
|
||||
* links need them), and setting them up from a product: a test first, saved only if it worked.
|
||||
* The SMTP password and WAWP access token are sealed with the link's secret.
|
||||
* The SMTP password and WAWP access token are sealed with the link's secret. 1.20.0 adds
|
||||
* `messaging.get` (the App sends with the church's settings) and the `messaging.changed` hint
|
||||
* back to the product.
|
||||
* - **`whatsapp.optout`** (1.20.0): a STOP to the church's WhatsApp number, passed on to Accounts,
|
||||
* which keeps the opt-out for every product.
|
||||
* - **`people.*`**: what a product's admin can do to someone's account from the product (add a
|
||||
* person, change their name or email, reset 2FA, unlock, deactivate, news off from an
|
||||
* unsubscribe link). Accounts only acts on people the product knows (signed in through it or
|
||||
@@ -237,6 +241,32 @@ export const messagingTestSchema = base.extend({
|
||||
/** Tests the settings given as messaging.test does, and saves each part only if its test worked. */
|
||||
export const messagingSetSchema = messagingTestSchema.extend({ type: z.literal("messaging.set") });
|
||||
|
||||
/**
|
||||
* 1.20.0 (APP-1.0-PLAN §8, decision 4): the church's email and WhatsApp settings, for a product
|
||||
* that sends with them but never asks for its own (the Church App). One set per church: kept in
|
||||
* Events or Accounts, copied to the others. The SMTP password and WAWP token come sealed with the
|
||||
* link's secret. Accounts remembers who asked, and sends each a `messaging.changed` when they
|
||||
* change (`MESSAGING_CHANGED_PATH`), so it fetches them again.
|
||||
*/
|
||||
export const messagingGetSchema = base.extend({ type: z.literal("messaging.get") });
|
||||
|
||||
/**
|
||||
* 1.20.0 (APP-1.0-PLAN §8, decision 11): someone replied STOP to the church's WhatsApp number.
|
||||
* Whichever product's webhook received it tells Accounts, which keeps the opt-out for every
|
||||
* product: it sets `whatsapp_opted_out` on each account with that verified number and sends
|
||||
* `user.updated` to every linked product. Only ever turns WhatsApp off; turning it back on is the
|
||||
* person's own choice in Accounts. Accounts also keeps a number without an account, so an account
|
||||
* made with it later starts opted out.
|
||||
*/
|
||||
export const whatsappOptOutSchema = base.extend({
|
||||
type: z.literal("whatsapp.optout"),
|
||||
phone: phoneSchema,
|
||||
/** When the reply arrived. */
|
||||
receivedAt: dateTimeSchema,
|
||||
/** The word they sent (`STOP`, `UNSUBSCRIBE`, `STOPP`), for the audit. */
|
||||
keyword: z.string().trim().min(1).max(40),
|
||||
});
|
||||
|
||||
/**
|
||||
* 1.9.0: use the product's look (name, logo, colours) on Accounts' pages. `overwrite: false` only
|
||||
* fills what Accounts doesn't have yet; `true` replaces it (an admin pressing the button).
|
||||
@@ -277,6 +307,7 @@ export const identityRequestSchema = z.discriminatedUnion("type", [
|
||||
importBeginSchema, importBatchSchema, importFinishSchema, importAbortSchema,
|
||||
peopleEnsureSchema, peopleUpdateSchema, peopleResetTwoFactorSchema, peopleUnlockSchema, peopleSetActiveSchema, peopleNewsOffSchema,
|
||||
peopleRemoveDemoSchema, peopleCheckSchema, messagingStatusSchema, messagingTestSchema, messagingSetSchema, churchBrandingSchema, churchUpdateSchema,
|
||||
messagingGetSchema, whatsappOptOutSchema,
|
||||
]);
|
||||
export type IdentityRequest = z.infer<typeof identityRequestSchema>;
|
||||
export type IdentityRequestType = IdentityRequest["type"];
|
||||
@@ -356,6 +387,46 @@ export const messagingTestReplySchema = z.object({
|
||||
});
|
||||
export type MessagingTestReply = z.infer<typeof messagingTestReplySchema>;
|
||||
|
||||
/**
|
||||
* messaging.get: the settings, secrets sealed with the link's secret; null for a part that isn't
|
||||
* set up (or doesn't work: `ready` false in messaging.status). `email.pass` null: the server
|
||||
* takes no password. `updatedAt`: the last change to either part.
|
||||
*/
|
||||
export const messagingGetReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
email: smtpSettingsSchema.nullable(),
|
||||
whatsapp: wawpSettingsSchema.extend({ accessToken: sealedValueSchema }).nullable(),
|
||||
updatedAt: dateTimeSchema.nullable(),
|
||||
});
|
||||
export type MessagingGetReply = z.infer<typeof messagingGetReplySchema>;
|
||||
|
||||
/** whatsapp.optout: how many accounts have the number (0 is fine: the number is kept anyway). */
|
||||
export const whatsappOptOutReplySchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
accounts: z.int().nonnegative(),
|
||||
});
|
||||
export type WhatsappOptOutReply = z.infer<typeof whatsappOptOutReplySchema>;
|
||||
|
||||
// ─── Accounts → product: messaging.changed (1.20.0) ─────────────────────────
|
||||
|
||||
/** On the product's address. Signed with the link's secret (LINK_HEADERS). */
|
||||
export const MESSAGING_CHANGED_PATH = "/api/accounts/v1/messaging-changed";
|
||||
|
||||
/**
|
||||
* A hint, as `church.changed` is: the church's email or WhatsApp settings changed (in Accounts,
|
||||
* or copied in from Events), so send `messaging.get` again. Sent to the products that asked for
|
||||
* them. The product answers `{ ok: true }` (`okReplySchema`); Accounts retries otherwise.
|
||||
*/
|
||||
export const messagingChangedSchema = z.object({
|
||||
schema: z.literal(IDENTITY_REQUEST_SCHEMA),
|
||||
type: z.literal("messaging.changed"),
|
||||
occurredAt: dateTimeSchema,
|
||||
/** Which parts changed. */
|
||||
email: z.boolean(),
|
||||
whatsapp: z.boolean(),
|
||||
});
|
||||
export type MessagingChanged = z.infer<typeof messagingChangedSchema>;
|
||||
|
||||
/** church.update: the profile after the change. */
|
||||
export const churchUpdateReplySchema = z.object({ schema: z.literal(IDENTITY_REQUEST_SCHEMA), church: churchSchema });
|
||||
export type ChurchUpdateReply = z.infer<typeof churchUpdateReplySchema>;
|
||||
|
||||
@@ -35,6 +35,12 @@ export const profileSchema = z.object({
|
||||
phone_number_verified: z.boolean(),
|
||||
/** Whether the church may send this person news, per channel. */
|
||||
news_consent: newsConsentSchema,
|
||||
/**
|
||||
* 1.20.0: the person replied STOP to the church's WhatsApp number (APP-1.0-PLAN §8, decision
|
||||
* 11). No product sends them WhatsApp of any kind, reminders included, until they turn it back
|
||||
* on in Accounts. Accounts keeps it for every product. Absent (an older Accounts): false.
|
||||
*/
|
||||
whatsapp_opted_out: z.boolean().optional(),
|
||||
});
|
||||
export type Profile = z.infer<typeof profileSchema>;
|
||||
|
||||
|
||||
@@ -15,4 +15,6 @@ export * from "./oidc";
|
||||
export * as hub from "./hub";
|
||||
export * as agent from "./agent";
|
||||
export * from "./church-export";
|
||||
export * from "./bible";
|
||||
export * from "./devotional";
|
||||
export { canonicalJson } from "./canonical";
|
||||
|
||||
@@ -141,7 +141,7 @@ describe("exports", () => {
|
||||
expect(() => decryptExport(file, encryptExport(zip).key)).toThrow();
|
||||
});
|
||||
|
||||
it.each(["church-export.json", "church-export-website.json"])("%s has no internal ids", (file) => {
|
||||
it.each(["church-export.json", "church-export-website.json", "church-export-app.json"])("%s has no internal ids", (file) => {
|
||||
const data = sample(file);
|
||||
expect(churchExportSchema.safeParse(data).success).toBe(true);
|
||||
const keys: string[] = [];
|
||||
@@ -169,11 +169,65 @@ describe("seed-demo jobs", () => {
|
||||
expect(args({ church: "hope", product: "website", profile: "bold-plant" })).toBe(true);
|
||||
expect(args({ church: "hope", product: "events", profile: "small" })).toBe(true);
|
||||
expect(args({ church: "hope", product: "website", profile: "small" })).toBe(false);
|
||||
expect(args({ church: "hope", profile: "bold-plant" })).toBe(false);
|
||||
// 1.21.0: Events has a profile per scenario too, so a scenario name with no product is an Events demo.
|
||||
expect(args({ church: "hope", profile: "bold-plant" })).toBe(true);
|
||||
expect(args({ church: "hope", product: "website", profile: "clean-campus", adminEmail: "jane@hope.test" })).toBe(false);
|
||||
expect(args({ church: "hope", product: "accounts", profile: "small" })).toBe(false);
|
||||
expect(agent.WEBSITE_DEMO_PROFILES).toHaveLength(8);
|
||||
});
|
||||
it("1.20.0: an App demo names the product and takes only an App profile, without an admin email", () => {
|
||||
expect(agent.DEMO_PRODUCTS).toContain("app");
|
||||
expect(args({ church: "demo2", product: "app", profile: "community-family" })).toBe(true);
|
||||
expect(args({ church: "demo2", product: "app", profile: "small" })).toBe(false);
|
||||
expect(args({ church: "demo2", product: "app", profile: "acacia-hill" })).toBe(false);
|
||||
expect(args({ church: "demo2", product: "app", profile: "community-family", adminEmail: "jane@hope.test" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("demo scenarios (1.21.0)", () => {
|
||||
const args = (a: Record<string, unknown>) => agent.jobArgsSchemas["seed-demo"].safeParse(a).success;
|
||||
|
||||
it("has eight, one per Website demo profile, with unique churches", () => {
|
||||
expect(agent.DEMO_SCENARIOS.map((s) => s.key)).toEqual([...agent.WEBSITE_DEMO_PROFILES]);
|
||||
expect(new Set(agent.DEMO_SCENARIOS.map((s) => s.church)).size).toBe(8);
|
||||
});
|
||||
|
||||
it("names only profiles each product has", () => {
|
||||
for (const s of agent.DEMO_SCENARIOS) {
|
||||
for (const product of agent.DEMO_SCENARIO_ORDER) {
|
||||
expect(agent.DEMO_PROFILES_BY_PRODUCT[product]).toContain(s.profiles[product]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("loads Accounts first, every demo product once, each with a minimum release and agent", () => {
|
||||
expect(agent.DEMO_SCENARIO_ORDER[0]).toBe("accounts");
|
||||
expect([...agent.DEMO_SCENARIO_ORDER].sort()).toEqual([...agent.DEMO_PRODUCTS].sort());
|
||||
for (const p of agent.DEMO_PRODUCTS) {
|
||||
expect(agent.DEMO_SCENARIO_MIN_VERSIONS[p]).toMatch(/^\d+\.\d+\.\d+$/);
|
||||
expect(agent.SEED_DEMO_MIN_AGENT_BY_PRODUCT[p]).toMatch(/^\d+\.\d+\.\d+$/);
|
||||
}
|
||||
});
|
||||
|
||||
it("covers the App's bands from 0–100 to 2 001–5 000", () => {
|
||||
const bands = new Set(agent.DEMO_SCENARIOS.map((s) => s.appActiveMembers));
|
||||
for (const b of ["0–100", "101–300", "301–750", "751–2 000", "2 001–5 000"] as const) expect(bands).toContain(b);
|
||||
});
|
||||
|
||||
it("takes a scenario only with that scenario's profile for the product", () => {
|
||||
expect(args({ church: "demo2", product: "accounts", profile: "clean-campus", scenario: "clean-campus" })).toBe(true);
|
||||
expect(args({ church: "demo2", profile: "bold-youth", scenario: "bold-youth" })).toBe(true);
|
||||
expect(args({ church: "demo2", product: "website", profile: "bold-plant", scenario: "bold-youth" })).toBe(false);
|
||||
expect(args({ church: "demo2", profile: "events", scenario: "bold-youth" })).toBe(false);
|
||||
expect(args({ church: "demo2", product: "app", profile: "bold-youth", scenario: "nowhere" })).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps Events' four single-product demos, and Accounts takes no admin email or Events profile", () => {
|
||||
expect(args({ church: "hope", profile: "multicampus" })).toBe(true);
|
||||
expect(args({ church: "hope", profile: "clean-modern" })).toBe(true);
|
||||
expect(args({ church: "demo2", product: "accounts", profile: "small" })).toBe(false);
|
||||
expect(args({ church: "demo2", product: "accounts", profile: "clean-modern", adminEmail: "jane@hope.test" })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("env-read and env-set jobs (1.12.0)", () => {
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
BIBLE_BOOKS, BIBLE_TRANSLATIONS, DEVOTIONAL_CSV_COLUMNS, DEVOTIONAL_CSV_TEMPLATE, checkDevotionalCsv, devotionalCsv,
|
||||
devotionalsReplySchema, findBibleBook, formatBibleReference, parseBibleReference, parseCsv, passageVerseCount, youVersionUrl,
|
||||
type PassageLocation,
|
||||
} from "../src";
|
||||
import { sample } from "./helpers";
|
||||
|
||||
const ok = (input: string): PassageLocation => {
|
||||
const r = parseBibleReference(input);
|
||||
if (!r.ok) throw new Error(`${input}: ${r.error}`);
|
||||
return r.passage;
|
||||
};
|
||||
|
||||
describe("Bible books and translations", () => {
|
||||
it("has the 66 books with unique codes", () => {
|
||||
expect(BIBLE_BOOKS).toHaveLength(66);
|
||||
expect(new Set(BIBLE_BOOKS.map((b) => b.code)).size).toBe(66);
|
||||
});
|
||||
|
||||
it("finds every book by its English and Afrikaans name and its code", () => {
|
||||
for (const b of BIBLE_BOOKS) {
|
||||
expect(findBibleBook(b.en)?.code).toBe(b.code);
|
||||
expect(findBibleBook(b.af)?.code).toBe(b.code);
|
||||
expect(findBibleBook(b.code)?.code).toBe(b.code);
|
||||
}
|
||||
});
|
||||
|
||||
it("ignores case, accents, dots and spaces", () => {
|
||||
expect(findBibleBook("1 korintiers")?.code).toBe("1CO");
|
||||
expect(findBibleBook("1Kor.")?.code).toBe("1CO");
|
||||
expect(findBibleBook("ESEGIËL")?.code).toBe("EZK");
|
||||
expect(findBibleBook("Ps")?.code).toBe("PSA");
|
||||
expect(findBibleBook("Nowhere")).toBeNull();
|
||||
});
|
||||
|
||||
it("has the seven translations, with unique ids and YouVersion numbers", () => {
|
||||
expect(BIBLE_TRANSLATIONS.map((t) => t.id)).toEqual(["NLT", "ESV", "NIV", "NKJV", "KJV", "AFR53", "AFR83"]);
|
||||
expect(new Set(BIBLE_TRANSLATIONS.map((t) => t.youVersionId)).size).toBe(7);
|
||||
for (const t of BIBLE_TRANSLATIONS) expect(t.copyright.length).toBeGreaterThan(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseBibleReference", () => {
|
||||
it.each([
|
||||
["John 3:16", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }],
|
||||
["John 3:16-18", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 18 }],
|
||||
["Johannes 3:16–18", { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 18 }],
|
||||
["1 Kor. 13:4 - 7", { book: "1CO", chapter: 13, verse: 4, endChapter: 13, endVerse: 7 }],
|
||||
["Rom 8:38-9:1", { book: "ROM", chapter: 8, verse: 38, endChapter: 9, endVerse: 1 }],
|
||||
["Ps 23 1-3", { book: "PSA", chapter: 23, verse: 1, endChapter: 23, endVerse: 3 }],
|
||||
["Psalm 23.1", { book: "PSA", chapter: 23, verse: 1, endChapter: 23, endVerse: 1 }],
|
||||
["Jude 3", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 3 }],
|
||||
["Judas 3-5", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 5 }],
|
||||
["Jude 1:3", { book: "JUD", chapter: 1, verse: 3, endChapter: 1, endVerse: 3 }],
|
||||
["Song of Songs 2:4", { book: "SNG", chapter: 2, verse: 4, endChapter: 2, endVerse: 4 }],
|
||||
])("reads %s", (input, expected) => {
|
||||
expect(ok(input)).toEqual(expected);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["", "isn't a Bible reference"],
|
||||
["John", "isn't a Bible reference"],
|
||||
["John 3", "Give the verses"],
|
||||
["John 316", "Give the verses"],
|
||||
["Hezekiah 3:1", "isn't a book"],
|
||||
["John 22:1", "John has 21 chapters"],
|
||||
["John 3:18-16", "ends before it starts"],
|
||||
["Rom 9:1-8:38", "ends before it starts"],
|
||||
])("refuses %p", (input, message) => {
|
||||
const r = parseBibleReference(input);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.error).toContain(message);
|
||||
});
|
||||
|
||||
it("formats in the translation's language", () => {
|
||||
expect(formatBibleReference(ok("john 3:16-18"))).toBe("John 3:16–18");
|
||||
expect(formatBibleReference(ok("John 3:16-18"), "af")).toBe("Johannes 3:16–18");
|
||||
expect(formatBibleReference(ok("Rom 8:38-9:1"))).toBe("Romans 8:38–9:1");
|
||||
expect(formatBibleReference(ok("Jude 3"))).toBe("Jude 1:3");
|
||||
});
|
||||
|
||||
it("counts verses within a chapter only", () => {
|
||||
expect(passageVerseCount(ok("1 Cor 13:4-7"))).toBe(4);
|
||||
expect(passageVerseCount(ok("Rom 8:38-9:1"))).toBeNull();
|
||||
});
|
||||
|
||||
it("builds the YouVersion link", () => {
|
||||
expect(youVersionUrl(ok("John 3:16-18"), "NLT")).toBe("https://www.bible.com/bible/116/JHN.3.16-18.NLT");
|
||||
expect(youVersionUrl(ok("Johannes 3:16"), "AFR83")).toBe("https://www.bible.com/bible/6/JHN.3.16.AFR83");
|
||||
expect(youVersionUrl(ok("Rom 8:38-9:1"), "ESV")).toBe("https://www.bible.com/bible/59/ROM.8.38.ESV");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseCsv", () => {
|
||||
it("reads quotes, doubled quotes, line breaks in quotes, CRLF and a BOM", () => {
|
||||
const rows = parseCsv(String.fromCharCode(0xfeff) + 'a,b\r\n"x, y","say ""hi"""\r\n"two\nlines",z\r\n\r\nlast,row');
|
||||
expect(rows).toEqual([
|
||||
{ line: 1, cells: ["a", "b"] },
|
||||
{ line: 2, cells: ["x, y", 'say "hi"'] },
|
||||
{ line: 3, cells: ["two\nlines", "z"] },
|
||||
{ line: 6, cells: ["last", "row"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes semicolons when the header has them and no commas", () => {
|
||||
expect(parseCsv("a;b\n1,5;2\n")).toEqual([{ line: 1, cells: ["a", "b"] }, { line: 2, cells: ["1,5", "2"] }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("checkDevotionalCsv", () => {
|
||||
const row = (over: Partial<Record<(typeof DEVOTIONAL_CSV_COLUMNS)[number], string>> = {}) => ({
|
||||
date: "2027-01-05", title: "Love", passage: "1 Cor 13:4-7", translation: "NLT", passage_text: "Love is patient and kind.",
|
||||
body: "Text.", prayer: "", author: "", ...over,
|
||||
});
|
||||
|
||||
it("accepts the template", () => {
|
||||
const r = checkDevotionalCsv(DEVOTIONAL_CSV_TEMPLATE);
|
||||
expect(r.fileError).toBeNull();
|
||||
expect(r.rows).toHaveLength(1);
|
||||
expect(r.rows[0]!.errors).toEqual([]);
|
||||
expect(r.rows[0]!.devotional?.passage).toMatchObject({ reference: "1 Corinthians 13:4–7", translation: "NLT" });
|
||||
});
|
||||
|
||||
it("turns a good row into a devotional, in the translation's language, empty optional fields null", () => {
|
||||
const r = checkDevotionalCsv(devotionalCsv([row({ passage: "Joh 3:16", translation: "afr83" })]));
|
||||
expect(r.rows[0]!.devotional).toEqual({
|
||||
date: "2027-01-05", title: "Love",
|
||||
passage: { reference: "Johannes 3:16", location: { book: "JHN", chapter: 3, verse: 16, endChapter: 3, endVerse: 16 }, translation: "AFR83", text: "Love is patient and kind." },
|
||||
body: "Text.", prayer: null, author: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports each bad field with its column and line", () => {
|
||||
const r = checkDevotionalCsv(devotionalCsv([
|
||||
row({ date: "5 Jan 2027" }),
|
||||
row({ date: "2027-01-06", title: "" }),
|
||||
row({ date: "2027-01-07", passage: "Hezekiah 1:1" }),
|
||||
row({ date: "2027-01-08", translation: "MSG" }),
|
||||
row({ date: "2027-01-09", body: "x".repeat(20_001) }),
|
||||
row({ date: "2027-01-06" }),
|
||||
]));
|
||||
const errors = r.rows.map((x) => ({ line: x.line, columns: x.errors.map((e) => e.column), ok: x.devotional !== null }));
|
||||
expect(errors).toEqual([
|
||||
{ line: 2, columns: ["date"], ok: false },
|
||||
{ line: 3, columns: ["title"], ok: false },
|
||||
{ line: 4, columns: ["passage"], ok: false },
|
||||
{ line: 5, columns: ["translation"], ok: false },
|
||||
{ line: 6, columns: ["body"], ok: false },
|
||||
{ line: 7, columns: ["date"], ok: false },
|
||||
]);
|
||||
expect(r.rows[5]!.errors[0]!.message).toContain("also on line 3");
|
||||
});
|
||||
|
||||
it("marks taken days, refuses days past the limit and warns on long passages", () => {
|
||||
const r = checkDevotionalCsv(devotionalCsv([row(), row({ date: "2027-01-06", passage: "Ps 119:1-40" }), row({ date: "2027-05-01" })]), {
|
||||
taken: ["2027-01-05"], latestDate: "2027-03-31",
|
||||
});
|
||||
expect(r.rows[0]).toMatchObject({ taken: true, errors: [] });
|
||||
expect(r.rows[1]!.warnings[0]!.message).toContain("40 verses");
|
||||
expect(r.rows[1]!.devotional).not.toBeNull();
|
||||
expect(r.rows[2]!.errors[0]!.message).toContain("more than 3 months ahead");
|
||||
});
|
||||
|
||||
it("refuses a file without the required columns, or without rows", () => {
|
||||
expect(checkDevotionalCsv("").fileError).toBe("The file is empty");
|
||||
expect(checkDevotionalCsv("date,title\n2027-01-05,Love\n").fileError).toContain("passage, translation, passage_text, body");
|
||||
expect(checkDevotionalCsv(`${DEVOTIONAL_CSV_COLUMNS.join(",")}\n`).fileError).toContain("no devotionals");
|
||||
});
|
||||
|
||||
it("takes columns in any order, and without the optional ones", () => {
|
||||
const r = checkDevotionalCsv("body,passage_text,translation,passage,title,date\nText.,Words.,KJV,Gen 1:1,In the beginning,2027-02-01\n");
|
||||
expect(r.rows[0]!.devotional).toMatchObject({ date: "2027-02-01", prayer: null, passage: { reference: "Genesis 1:1", translation: "KJV" } });
|
||||
});
|
||||
});
|
||||
|
||||
describe("devotionals reply", () => {
|
||||
it("only carries Cross Code's devotionals", () => {
|
||||
const reply = sample<{ devotionals: { source: string }[] }>("devotionals-reply.json");
|
||||
expect(devotionalsReplySchema.safeParse(reply).success).toBe(true);
|
||||
reply.devotionals[0]!.source = "church";
|
||||
expect(devotionalsReplySchema.safeParse(reply).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -57,6 +57,13 @@ const SAMPLE_SCHEMA: Record<string, string> = {
|
||||
"people-check-reply.json": "people-check-reply",
|
||||
"church-update.json": "identity-request",
|
||||
"church-update-reply.json": "church-update-reply",
|
||||
"church-export-app.json": "church-export",
|
||||
"messaging-get.json": "identity-request",
|
||||
"messaging-get-reply.json": "messaging-get-reply",
|
||||
"messaging-changed.json": "messaging-changed",
|
||||
"whatsapp-optout.json": "identity-request",
|
||||
"whatsapp-optout-reply.json": "whatsapp-optout-reply",
|
||||
"devotionals-reply.json": "devotionals-reply",
|
||||
};
|
||||
|
||||
describe("JSON Schema (schemas/)", () => {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user