events 3.9.0, website 1.9.0, accounts 1.10.0: the church's details from Accounts everywhere
- Events: the Accounts profile's name, logo, icon, colours and contact details win over Events' own settings while Accounts is connected (pages, emails, WhatsApp, PDFs); Settings shows them read-only with a link to Accounts. The Accounts logo is copied for PDFs (PNG and JPEG). Fixes Events keeping its old church after a demo scenario load. - Website: a background per homepage section in the church's colours; "More info" instead of "Register" for events without registration; the shared colour field. - Accounts: the shared colour field in Church profile. - @crosscode/ui 0.4.0: ColourField and isHexColour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,39 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [3.9.0] - 2026-12-01
|
||||
|
||||
No migration, no new settings or environment variables. Works with any Accounts; nothing changes
|
||||
on a site without Accounts.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **The church's details come from Accounts.** The church profile set only the fonts, corners and
|
||||
footer, so after a change in Accounts (or a demo scenario loaded on a new church) Events kept its
|
||||
own old name, logo and colours while the Website showed the new ones. Now, while Accounts is
|
||||
connected, the profile's name, logo, icon, main and accent colours, email, phone and address win
|
||||
over `org_name`, `logo_url`, `favicon_url`, `primary_color`, `accent_color`, `org_email`,
|
||||
`org_phone` and `org_address` everywhere: the public settings (`GET /api/v2/settings`), and
|
||||
everything that reads the settings cache (emails, WhatsApp, PDFs, 2FA labels). Only what the
|
||||
profile has: no icon or accent there keeps this site's own. `org_tagline` and `secondary_color`
|
||||
stay this site's (`src/accounts/church.ts` `churchSettings`, `utils/settingsCache.js`
|
||||
`setAccountsOverrides`). `church.changed` fetches the profile straight away; disconnecting
|
||||
Accounts brings the site's own back. The look sent to Accounts on a move stays this site's own
|
||||
(`getStoredSetting`).
|
||||
- **PDFs with the church's logo from Accounts.** Tickets, invoices, receipts, certificates and
|
||||
privacy exports could only draw a logo uploaded here. The logo from Accounts is copied into
|
||||
`uploads/accounts` (once per address, when the profile arrives or the first PDF needs it; old
|
||||
copies removed; 2 MB at most; `utils/logoCopy.js`). Only PNG and JPEG can be drawn in a PDF; an
|
||||
SVG logo (the demo churches') isn't copied and the PDFs show the church's name, as before.
|
||||
- A logo address on another `localhost` port (Accounts in development) is no longer rewritten to
|
||||
the API's address; only this site's own uploads are (`resolveToApiOrigin`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **Settings → Organisation and Branding** show the fields Accounts sets read-only, with a link to
|
||||
the church profile in Accounts, and never send them back (`GET /api/v2/settings/all` adds
|
||||
`accounts_managed`, the keys Accounts sets, with Accounts' values).
|
||||
|
||||
## [3.8.0] - 2026-11-30
|
||||
|
||||
Needs contracts 1.21.0 and `@crosscode/demo` 1.1.0 (built with Events; the `crosscode` script on
|
||||
|
||||
@@ -12,6 +12,18 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 3.9.0
|
||||
|
||||
- **Your church's name, logo, colours and contact details now come from your church profile in
|
||||
Accounts**, as they do on your website. Change them once in Accounts and your Events site shows
|
||||
the change within moments, in its pages, emails and WhatsApp messages too. Before, Events kept
|
||||
the details it had been given when it was set up.
|
||||
- In **Site settings → Organisation and Branding**, those details are shown but can't be changed
|
||||
there any more; a link takes you to your church profile in Accounts. Your tagline and secondary
|
||||
colour are still set in Events.
|
||||
- **Tickets, invoices and certificates show your church's logo from Accounts** when it's a PNG or
|
||||
JPEG picture.
|
||||
|
||||
## 3.8.0
|
||||
|
||||
- **STOP now means no WhatsApp at all.** Someone who replies STOP to your church's WhatsApp number
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
/**
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9): the brand
|
||||
* style (fonts and corners) and what the shared footer shows (service times, address, contact,
|
||||
* social, the church's other sites). Accounts owns it and serves it publicly at
|
||||
* `GET /api/church/v1`; this keeps a copy in memory for the public pages (`GET /api/v2/church`).
|
||||
* The church profile from the church's Accounts (3.7.0, docs/WEBSITE-1.0-PLAN.md §9). Accounts owns
|
||||
* it and serves it publicly at `GET /api/church/v1`; this keeps a copy in memory for the public
|
||||
* pages (`GET /api/v2/church`: the brand style and the shared footer).
|
||||
*
|
||||
* The church's own details in it (name, logo, icon, colours, contact details) also win over
|
||||
* this site's settings of the same name (`churchSettings`, through utils/settingsCache), so a change
|
||||
* in Accounts (or a new demo church) shows here as it does on the church's Website.
|
||||
*
|
||||
* Fetched again after 10 minutes, or at once when Accounts sends `church.changed`
|
||||
* (`POST /api/church/v1/changed`, src/links/routes.ts). While Accounts can't be reached the last
|
||||
@@ -12,6 +15,11 @@
|
||||
import { CHURCH_PATHS, churchSchema, type Church } from '@crosscode/contracts';
|
||||
import { accountsLink } from './client';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { setAccountsOverrides } = require('../utils/settingsCache') as { setAccountsOverrides(map: Record<string, string>): void };
|
||||
const { pdfLogoPath } = require('../utils/logoCopy') as { pdfLogoPath(url: string): Promise<string | null> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const FRESH_MS = 10 * 60e3;
|
||||
const RETRY_MS = 60e3;
|
||||
const TIMEOUT_MS = 5000;
|
||||
@@ -20,6 +28,28 @@ type Cached = { url: string; church: Church | null; at: number; ok: boolean };
|
||||
let cached: Cached | null = null;
|
||||
let pending: Promise<Church | null> | null = null;
|
||||
|
||||
/**
|
||||
* This site's settings that the church profile sets, with its values. Only what the profile has:
|
||||
* a church without an icon keeps this site's favicon, without an accent its accent colour.
|
||||
* `secondary_color` and `org_tagline` aren't in the profile, so they stay this site's own.
|
||||
*/
|
||||
export function churchSettings(church: Church | null): Record<string, string> {
|
||||
if (!church) return {};
|
||||
const a = church.contact.address;
|
||||
const address = a ? [a.line1, a.line2, a.suburb, a.city, a.province, a.postalCode].filter((x) => x && x.trim()).join(', ') : null;
|
||||
const out: Record<string, string | null> = {
|
||||
org_name: church.name,
|
||||
logo_url: church.branding.logoUrl,
|
||||
favicon_url: church.branding.iconUrl,
|
||||
primary_color: church.branding.colours.primary,
|
||||
accent_color: church.branding.colours.accent,
|
||||
org_email: church.contact.email,
|
||||
org_phone: church.contact.phone,
|
||||
org_address: address,
|
||||
};
|
||||
return Object.fromEntries(Object.entries(out).filter((e): e is [string, string] => typeof e[1] === 'string' && e[1] !== ''));
|
||||
}
|
||||
|
||||
async function fetchProfile(accountsUrl: string): Promise<Church> {
|
||||
const res = await fetch(`${accountsUrl.replace(/\/+$/, '')}${CHURCH_PATHS.profile}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`Accounts answered ${res.status}`);
|
||||
@@ -36,7 +66,12 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
} catch {
|
||||
return cached?.church ?? null;
|
||||
}
|
||||
if (!link) return null;
|
||||
if (!link) {
|
||||
// Disconnected from Accounts: this site's own settings again.
|
||||
if (cached) cached = null;
|
||||
setAccountsOverrides({});
|
||||
return null;
|
||||
}
|
||||
const url = link.url;
|
||||
if (cached && cached.url === url && Date.now() - cached.at < (cached.ok ? FRESH_MS : RETRY_MS)) return cached.church;
|
||||
if (!pending) {
|
||||
@@ -44,10 +79,14 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
pending = fetchProfile(url)
|
||||
.then((church) => {
|
||||
cached = { url, church, at: Date.now(), ok: true };
|
||||
setAccountsOverrides(churchSettings(church));
|
||||
// A copy of the logo for PDFs, made now rather than while a ticket is being sent.
|
||||
if (church.branding.logoUrl) pdfLogoPath(church.branding.logoUrl).catch(() => {});
|
||||
return church;
|
||||
}, (e: Error) => {
|
||||
console.warn('[church] profile not fetched from Accounts:', e.message);
|
||||
cached = { url, church: last, at: Date.now(), ok: false };
|
||||
setAccountsOverrides(churchSettings(last));
|
||||
return last;
|
||||
})
|
||||
.finally(() => { pending = null; });
|
||||
@@ -55,13 +94,23 @@ export async function churchProfile(): Promise<Church | null> {
|
||||
return pending;
|
||||
}
|
||||
|
||||
/** `church.changed`: the next `churchProfile()` fetches it again (the last copy is shown meanwhile). */
|
||||
/** This site's settings the church profile sets right now (fetching it when it's due). Never throws. */
|
||||
export async function churchSettingsNow(): Promise<Record<string, string>> {
|
||||
return churchSettings(await churchProfile());
|
||||
}
|
||||
|
||||
/**
|
||||
* `church.changed`: fetched again straight away, so emails and pages that read the settings
|
||||
* without waiting get the new details within moments (the last copy is used meanwhile).
|
||||
*/
|
||||
export function churchChanged(): void {
|
||||
if (cached) cached = { ...cached, at: 0 };
|
||||
churchProfile().catch(() => {});
|
||||
}
|
||||
|
||||
/** Tests: start with nothing. */
|
||||
export function resetChurchProfile(): void {
|
||||
cached = null;
|
||||
pending = null;
|
||||
setAccountsOverrides({});
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ import type { ChurchLook } from '@crosscode/contracts';
|
||||
import { siteUrl } from '../feed/context';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { getSetting } = require('../utils/settingsCache') as { getSetting(k: string, f?: string): Promise<string> };
|
||||
// This site's own values: they fill what Accounts doesn't have, so never Accounts' own (settingsCache).
|
||||
const { getStoredSetting: getSetting } = require('../utils/settingsCache') as { getStoredSetting(k: string, f?: string): Promise<string> };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const hex = (v: string) => (/^#[0-9a-fA-F]{6}$/.test(v) ? v : null);
|
||||
|
||||
@@ -41,11 +41,22 @@ const PUBLIC_KEYS = [
|
||||
// @desc Get public app settings
|
||||
// @route GET /api/settings
|
||||
// @access Public
|
||||
// The church's own details from its Accounts profile (name, logo, colours, contact): they win over
|
||||
// this site's settings of the same name while Accounts is connected (src/accounts/church.ts).
|
||||
async function fromAccounts() {
|
||||
try {
|
||||
return await require('../accounts/church').churchSettingsNow();
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
const getSettings = async (req, res) => {
|
||||
try {
|
||||
const rows = await prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } });
|
||||
const [rows, accounts] = await Promise.all([prisma.appSetting.findMany({ where: { key: { in: PUBLIC_KEYS } } }), fromAccounts()]);
|
||||
const settings = {};
|
||||
for (const r of rows) settings[r.key] = r.value;
|
||||
for (const [k, v] of Object.entries(accounts)) if (PUBLIC_KEYS.includes(k)) settings[k] = v;
|
||||
res.json(settings);
|
||||
} catch (e) {
|
||||
res.status(500).json({ message: safeErrorMessage(e) });
|
||||
@@ -79,6 +90,11 @@ const getAllSettings = async (req, res) => {
|
||||
settings[r.key] = r.value;
|
||||
}
|
||||
}
|
||||
// What the site uses for the keys Accounts sets, and which they are, so Settings shows them
|
||||
// read-only with a link to change them in Accounts.
|
||||
const accounts = await fromAccounts();
|
||||
Object.assign(settings, accounts);
|
||||
settings.accounts_managed = Object.keys(accounts).join(',');
|
||||
res.json(settings);
|
||||
} catch (e) {
|
||||
res.status(500).json({ message: safeErrorMessage(e) });
|
||||
@@ -96,7 +112,7 @@ const updateSettings = async (req, res) => {
|
||||
}
|
||||
|
||||
const ops = Object.entries(updates)
|
||||
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k))
|
||||
.filter(([k, v]) => v !== undefined && v !== null && !PRIVATE_KEYS.has(k) && k !== 'accounts_managed')
|
||||
.map(([key, value]) => {
|
||||
let storedValue = String(value);
|
||||
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// The logo for PDFs (tickets, invoices, receipts, certificates, privacy exports). PDFs need a file
|
||||
// on disk. A logo uploaded here already is one; the church's logo from its Accounts profile is an
|
||||
// address on another site, so a copy is kept in uploads/accounts (one per address, made the first
|
||||
// time it's needed and when Accounts says the church changed; older copies are removed).
|
||||
//
|
||||
// Only PNG and JPEG can be drawn into a PDF, so another kind of logo (SVG, WebP) isn't copied and
|
||||
// the PDFs show the church's name without it, as before.
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { UPLOADS_DIR, uploadsDir } = require('./uploads');
|
||||
|
||||
const MAX_BYTES = 2 * 1024 * 1024;
|
||||
const TIMEOUT_MS = 5000;
|
||||
const KINDS = { png: 'png', jpeg: 'jpg' };
|
||||
|
||||
/** PNG or JPEG by its first bytes (never by what the server says it is), else null. */
|
||||
function rasterKind(buf) {
|
||||
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
|
||||
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
|
||||
return null;
|
||||
}
|
||||
|
||||
const nameFor = (url) => `logo-${crypto.createHash('sha256').update(url).digest('hex').slice(0, 16)}`;
|
||||
|
||||
/** An outside address the site may fetch the logo from: https, or http while developing. */
|
||||
function fetchable(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
return u.protocol === 'https:' || (u.protocol === 'http:' && process.env.NODE_ENV !== 'production');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function existingCopy(url) {
|
||||
const base = nameFor(url);
|
||||
for (const ext of Object.values(KINDS)) {
|
||||
const p = path.join(UPLOADS_DIR, 'accounts', `${base}.${ext}`);
|
||||
if (fs.existsSync(p)) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Addresses tried lately that gave no usable logo: not fetched again for 10 minutes.
|
||||
const misses = new Map();
|
||||
const MISS_MS = 10 * 60e3;
|
||||
const pending = new Map();
|
||||
|
||||
async function download(url) {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS), redirect: 'follow' });
|
||||
if (!res.ok) throw new Error(`answered ${res.status}`);
|
||||
if (Number(res.headers.get('content-length') || 0) > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const buf = Buffer.from(await res.arrayBuffer());
|
||||
if (buf.length > MAX_BYTES) throw new Error('is larger than 2 MB');
|
||||
const kind = rasterKind(buf);
|
||||
if (!kind) return null; // SVG, WebP…: not drawable in a PDF
|
||||
const dir = uploadsDir('accounts');
|
||||
const base = nameFor(url);
|
||||
const file = path.join(dir, `${base}.${KINDS[kind]}`);
|
||||
fs.writeFileSync(file, buf);
|
||||
// The church changed its logo: the copies of the old ones go.
|
||||
for (const f of fs.readdirSync(dir)) if (f.startsWith('logo-') && !f.startsWith(`${base}.`)) fs.rmSync(path.join(dir, f), { force: true });
|
||||
return file;
|
||||
}
|
||||
|
||||
/**
|
||||
* The logo as a file a PDF can draw, or null. `logoUrl` is the logo_url setting: a path on this
|
||||
* site (/uploads/…) or the church's logo address from Accounts. Never throws.
|
||||
*/
|
||||
async function pdfLogoPath(logoUrl) {
|
||||
const url = String(logoUrl || '').trim();
|
||||
if (!url) return null;
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
const p = path.join(UPLOADS_DIR, '..', url.replace(/^\//, ''));
|
||||
return fs.existsSync(p) && rasterKind(fs.readFileSync(p).subarray(0, 8)) ? p : null;
|
||||
}
|
||||
if (!fetchable(url)) return null;
|
||||
const have = existingCopy(url);
|
||||
if (have) return have;
|
||||
const missed = misses.get(url);
|
||||
if (missed && Date.now() - missed < MISS_MS) return null;
|
||||
if (!pending.has(url)) {
|
||||
pending.set(url, download(url)
|
||||
.catch((e) => {
|
||||
console.warn(`[logo] the church's logo couldn't be copied for PDFs: ${url} ${e.message}`);
|
||||
return null;
|
||||
})
|
||||
.then((file) => {
|
||||
if (!file) misses.set(url, Date.now());
|
||||
return file;
|
||||
})
|
||||
.finally(() => pending.delete(url)));
|
||||
}
|
||||
return pending.get(url);
|
||||
}
|
||||
|
||||
/** Tests: forget the addresses that gave nothing. */
|
||||
function resetLogoCopies() {
|
||||
misses.clear();
|
||||
}
|
||||
|
||||
module.exports = { pdfLogoPath, resetLogoCopies, rasterKind };
|
||||
@@ -55,11 +55,8 @@ async function getBranding() {
|
||||
getSetting('logo_url', ''),
|
||||
]);
|
||||
const url = (process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001').replace(/\/$/, '');
|
||||
let logoPath = null;
|
||||
if (logoUrl) {
|
||||
const p = path.join(__dirname, '..', '..', 'public', logoUrl.replace(/^\//, ''));
|
||||
if (fs.existsSync(p)) logoPath = p;
|
||||
}
|
||||
// An uploaded logo, or a copy of the church's logo from Accounts (utils/logoCopy.js).
|
||||
const logoPath = await require('./logoCopy').pdfLogoPath(logoUrl);
|
||||
return { name, address, email, phone, brandColor: primary || accent || '#1e3a5f', url, logoPath };
|
||||
}
|
||||
|
||||
|
||||
@@ -17,9 +17,37 @@ let _cache = {};
|
||||
let _lastFetch = 0;
|
||||
const TTL_MS = 60 * 1000;
|
||||
|
||||
/**
|
||||
* The church's own details from its Accounts profile (src/accounts/church.ts): name, logo, icon,
|
||||
* colours and contact details. Accounts owns them, so while it's connected they win over this
|
||||
* site's own settings everywhere (pages, emails, PDFs). Empty without Accounts.
|
||||
*/
|
||||
let _fromAccounts = {};
|
||||
|
||||
/** Set by src/accounts/church.ts whenever it has (or loses) the church profile. */
|
||||
function setAccountsOverrides(map) {
|
||||
_fromAccounts = { ...(map || {}) };
|
||||
}
|
||||
|
||||
/** The keys Accounts sets right now, with their values. */
|
||||
function accountsOverrides() {
|
||||
return { ..._fromAccounts };
|
||||
}
|
||||
|
||||
/** The church profile is kept fresh as the settings are (it caches itself for 10 minutes). */
|
||||
function refreshChurchProfile() {
|
||||
try {
|
||||
const p = require('../accounts/church').churchProfile();
|
||||
if (p && typeof p.catch === 'function') p.catch(() => {});
|
||||
} catch {
|
||||
// No Accounts code in this context (some tests): the site's own settings stand.
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshIfStale() {
|
||||
const now = Date.now();
|
||||
if (now - _lastFetch < TTL_MS && _lastFetch > 0) return;
|
||||
refreshChurchProfile();
|
||||
try {
|
||||
const rows = await prisma.appSetting.findMany();
|
||||
const fresh = {};
|
||||
@@ -38,6 +66,13 @@ async function refreshIfStale() {
|
||||
* @returns {string}
|
||||
*/
|
||||
function _getSync(key, envFallback = '') {
|
||||
const a = _fromAccounts[key];
|
||||
if (typeof a === 'string' && a !== '') return a;
|
||||
return _getStoredSync(key, envFallback);
|
||||
}
|
||||
|
||||
/** This site's own value, ignoring Accounts (for sending this site's look to Accounts, src/accounts/look.ts). */
|
||||
function _getStoredSync(key, envFallback = '') {
|
||||
const v = _cache[key];
|
||||
const raw = (v !== undefined && v !== null && v !== '') ? v : (envFallback || '');
|
||||
if (ENCRYPTED_KEYS.has(key) && isEncrypted(raw)) {
|
||||
@@ -76,4 +111,10 @@ function invalidate() {
|
||||
refreshIfStale().catch(() => {});
|
||||
}
|
||||
|
||||
module.exports = { getSetting, getSettingSync, warmCache, invalidate, ENCRYPTED_KEYS };
|
||||
/** As getSetting, but this site's own value even when Accounts sets the key. */
|
||||
async function getStoredSetting(key, envFallback = '') {
|
||||
await refreshIfStale();
|
||||
return _getStoredSync(key, envFallback);
|
||||
}
|
||||
|
||||
module.exports = { getSetting, getSettingSync, getStoredSetting, warmCache, invalidate, setAccountsOverrides, accountsOverrides, ENCRYPTED_KEYS };
|
||||
@@ -37,8 +37,9 @@ const realFetch = global.fetch;
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = (async (url: string) => {
|
||||
// The logo, copied for PDFs (utils/logoCopy.js): not part of these tests.
|
||||
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 });
|
||||
fetches++;
|
||||
expect(url).toBe(`https://accounts.hope.test${CHURCH_PATHS.profile}`);
|
||||
const next = answers.shift() ?? 200;
|
||||
if (next === 'down') throw new Error('connect ECONNREFUSED');
|
||||
return new Response(JSON.stringify(profile), { status: next, headers: { 'content-type': 'application/json' } });
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
// The church's own details from Accounts (name, logo, icon, colours, contact) win over this site's
|
||||
// settings of the same name: on the public settings, in Settings (read-only), and for everything
|
||||
// that reads them through the settings cache (emails, PDFs). Without Accounts, the site's own stand.
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
type Link = { installId: string; product: string; url: string; secret: string; updatedAt: Date };
|
||||
const mockLinks: Link[] = [];
|
||||
const mockRows: { key: string; value: string }[] = [];
|
||||
jest.mock('../src/config/db', () => ({
|
||||
productLink: {
|
||||
findFirst: async ({ where }: { where: { product: string } }) => mockLinks.find((l) => l.product === where.product) ?? null,
|
||||
},
|
||||
appSetting: {
|
||||
findMany: async (q?: { where?: { key?: { in?: string[] } } }) => mockRows.filter((r) => !q?.where?.key?.in || q.where.key.in.includes(r.key)),
|
||||
},
|
||||
}));
|
||||
|
||||
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
|
||||
|
||||
import { CHURCH_PATHS } from '@crosscode/contracts';
|
||||
import { churchProfile, churchSettings, resetChurchProfile } from '../src/accounts/church';
|
||||
import { churchLook } from '../src/accounts/look';
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const settingsCache = require('../src/utils/settingsCache');
|
||||
const { getSettings, getAllSettings } = require('../src/controllers/settingsController');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
|
||||
const sample = () => JSON.parse(fs.readFileSync(path.join(SAMPLES, 'church.json'), 'utf8'));
|
||||
let profile = sample();
|
||||
const realFetch = global.fetch;
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = (async (url: string) => {
|
||||
if (url !== `https://accounts.hope.test${CHURCH_PATHS.profile}`) return new Response('', { status: 404 }); // the logo (logoCopy tests)
|
||||
return new Response(JSON.stringify(profile), { status: 200, headers: { 'content-type': 'application/json' } });
|
||||
}) as typeof fetch;
|
||||
});
|
||||
afterAll(() => { global.fetch = realFetch; });
|
||||
|
||||
beforeEach(() => {
|
||||
resetChurchProfile();
|
||||
mockLinks.length = 0;
|
||||
mockRows.length = 0;
|
||||
mockRows.push(
|
||||
{ key: 'org_name', value: 'Old Demo Church' },
|
||||
{ key: 'org_tagline', value: 'Our own tagline' },
|
||||
{ key: 'primary_color', value: '#111111' },
|
||||
{ key: 'secondary_color', value: '#222222' },
|
||||
{ key: 'logo_url', value: '/uploads/old-logo.png' },
|
||||
);
|
||||
settingsCache.invalidate();
|
||||
profile = sample();
|
||||
});
|
||||
|
||||
const connectAccounts = () => mockLinks.push({ installId: 'acc', product: 'accounts', url: 'https://accounts.hope.test/', secret: 'x', updatedAt: new Date() });
|
||||
|
||||
async function call(handler: (req: unknown, res: unknown) => Promise<void>): Promise<Record<string, string>> {
|
||||
let body: Record<string, string> = {};
|
||||
await handler({}, { json: (b: Record<string, string>) => { body = b; }, status() { return this; } });
|
||||
return body;
|
||||
}
|
||||
|
||||
describe("the church's details from Accounts", () => {
|
||||
test('only what the profile has', () => {
|
||||
profile.branding.iconUrl = null;
|
||||
profile.branding.colours.accent = null;
|
||||
const s = churchSettings(profile);
|
||||
expect(s.org_name).toBe(profile.name);
|
||||
expect(s.primary_color).toBe(profile.branding.colours.primary);
|
||||
expect('favicon_url' in s).toBe(false);
|
||||
expect('accent_color' in s).toBe(false);
|
||||
expect(churchSettings(null)).toEqual({});
|
||||
});
|
||||
|
||||
test('without Accounts, the site keeps its own', async () => {
|
||||
const s = await call(getSettings);
|
||||
expect(s.org_name).toBe('Old Demo Church');
|
||||
expect((await call(getAllSettings)).accounts_managed).toBe('');
|
||||
});
|
||||
|
||||
test("with Accounts, the public settings show the church's, and keep what the profile doesn't set", async () => {
|
||||
connectAccounts();
|
||||
const s = await call(getSettings);
|
||||
expect(s.org_name).toBe(profile.name);
|
||||
expect(s.primary_color).toBe(profile.branding.colours.primary);
|
||||
expect(s.logo_url).toBe(profile.branding.logoUrl);
|
||||
expect(s.org_tagline).toBe('Our own tagline');
|
||||
expect(s.secondary_color).toBe('#222222');
|
||||
});
|
||||
|
||||
test('Settings marks the ones Accounts sets', async () => {
|
||||
connectAccounts();
|
||||
const all = await call(getAllSettings);
|
||||
expect(all.org_name).toBe(profile.name);
|
||||
expect(all.accounts_managed.split(',')).toEqual(expect.arrayContaining(['org_name', 'primary_color', 'logo_url']));
|
||||
expect(all.accounts_managed.split(',')).not.toContain('secondary_color');
|
||||
});
|
||||
|
||||
test('the settings cache (emails, PDFs) uses them once the profile is in, and the look sent to Accounts stays the site\'s own', async () => {
|
||||
connectAccounts();
|
||||
await settingsCache.warmCache();
|
||||
await churchProfile();
|
||||
expect(settingsCache.getSettingSync('org_name', 'Cross Code')).toBe(profile.name);
|
||||
expect(await settingsCache.getStoredSetting('org_name')).toBe('Old Demo Church');
|
||||
expect((await churchLook()).name).toBe('Old Demo Church');
|
||||
});
|
||||
|
||||
test('a church that changes its name in Accounts (a new demo church) is shown after church.changed', async () => {
|
||||
connectAccounts();
|
||||
await churchProfile();
|
||||
profile.name = 'Grace Fellowship';
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
require('../src/accounts/church').churchChanged();
|
||||
await churchProfile();
|
||||
expect(settingsCache.getSettingSync('org_name')).toBe('Grace Fellowship');
|
||||
expect((await call(getSettings)).org_name).toBe('Grace Fellowship');
|
||||
});
|
||||
|
||||
test('disconnected from Accounts: back to the site\'s own', async () => {
|
||||
connectAccounts();
|
||||
await churchProfile();
|
||||
mockLinks.length = 0;
|
||||
await churchProfile();
|
||||
expect(settingsCache.getSettingSync('org_name')).toBe('Old Demo Church');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
// The logo for PDFs: an uploaded one is used as it is; the church's logo from Accounts (an address
|
||||
// on another site) is copied into uploads/accounts once, and only when it's a PNG or JPEG.
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||
const { pdfLogoPath, resetLogoCopies } = require('../src/utils/logoCopy') as { pdfLogoPath(u: string): Promise<string | null>; resetLogoCopies(): void };
|
||||
const { UPLOADS_DIR } = require('../src/utils/uploads') as { UPLOADS_DIR: string };
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(32)]);
|
||||
const SVG = Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"/>');
|
||||
const COPIES = path.join(UPLOADS_DIR, 'accounts');
|
||||
const realFetch = global.fetch;
|
||||
let served: Record<string, Buffer | number> = {};
|
||||
let fetched: string[] = [];
|
||||
|
||||
beforeAll(() => {
|
||||
global.fetch = (async (url: string) => {
|
||||
fetched.push(url);
|
||||
const body = served[url];
|
||||
if (body === undefined || typeof body === 'number') return new Response('', { status: typeof body === 'number' ? body : 404 });
|
||||
return new Response(new Uint8Array(body), { status: 200 });
|
||||
}) as typeof fetch;
|
||||
});
|
||||
afterAll(() => {
|
||||
global.fetch = realFetch;
|
||||
fs.rmSync(COPIES, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(() => {
|
||||
fs.rmSync(COPIES, { recursive: true, force: true });
|
||||
resetLogoCopies();
|
||||
served = {};
|
||||
fetched = [];
|
||||
jest.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
});
|
||||
afterEach(() => { jest.restoreAllMocks(); });
|
||||
|
||||
test("the church's PNG logo from Accounts is copied once, and used from the copy after", async () => {
|
||||
served['https://accounts.hope.test/logo.png'] = PNG;
|
||||
const p = await pdfLogoPath('https://accounts.hope.test/logo.png');
|
||||
expect(p && path.dirname(p)).toBe(COPIES);
|
||||
expect(fs.readFileSync(p!)).toEqual(PNG);
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.png')).toBe(p);
|
||||
expect(fetched).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('a new logo replaces the copy of the old one', async () => {
|
||||
served['https://accounts.hope.test/old.png'] = PNG;
|
||||
served['https://accounts.hope.test/new.png'] = PNG;
|
||||
const old = await pdfLogoPath('https://accounts.hope.test/old.png');
|
||||
const next = await pdfLogoPath('https://accounts.hope.test/new.png');
|
||||
expect(next).not.toBe(old);
|
||||
expect(fs.existsSync(old!)).toBe(false);
|
||||
expect(fs.readdirSync(COPIES)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("an SVG logo or one that can't be fetched gives none (the PDF shows the name), and isn't fetched again at once", async () => {
|
||||
served['https://accounts.hope.test/logo.svg'] = SVG;
|
||||
served['https://accounts.hope.test/gone.png'] = 404;
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.svg')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/gone.png')).toBeNull();
|
||||
expect(await pdfLogoPath('https://accounts.hope.test/logo.svg')).toBeNull();
|
||||
expect(fetched).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('a logo uploaded here is used as it is; nothing for no logo', async () => {
|
||||
const dir = path.join(UPLOADS_DIR, 'accounts');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, 'own.png'), PNG);
|
||||
expect(await pdfLogoPath('/uploads/accounts/own.png')).toBe(path.join(dir, 'own.png'));
|
||||
expect(await pdfLogoPath('')).toBeNull();
|
||||
expect(await pdfLogoPath('/uploads/accounts/missing.png')).toBeNull();
|
||||
expect(fetched).toHaveLength(0);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "3.8.0",
|
||||
"version": "3.9.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
|
||||
@@ -26,6 +26,7 @@ import { errorMessage } from "@/lib/utils";
|
||||
import { BackLink } from "@/components/shared/BackLink";
|
||||
import { uploadImage } from "@/lib/eventSetup";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
import { useChurch } from "@/contexts/ChurchContext";
|
||||
|
||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "signin" | "backups" | "jobs" | "licence" | "ai";
|
||||
|
||||
@@ -48,7 +49,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||
];
|
||||
|
||||
const inputCls =
|
||||
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
|
||||
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500";
|
||||
|
||||
/** The code from Search Console's verification meta tag; accepts the whole tag or just the code. */
|
||||
function googleVerificationCode(input: string): string {
|
||||
@@ -56,6 +57,20 @@ function googleVerificationCode(input: string): string {
|
||||
return (m ? m[1] : input).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown above Organisation and Branding while the church's Accounts sets some of their fields:
|
||||
* those come from the church profile (on all the church's sites) and are changed there.
|
||||
*/
|
||||
function FromAccountsNotice({ what, href }: { what: string; href: string | null }) {
|
||||
return (
|
||||
<div className="rounded-lg border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900">
|
||||
Your church's {what} come from its church profile in Accounts, so every one of its sites shows the same.
|
||||
They can't be changed here.{" "}
|
||||
{href ? <a href={href} className="font-medium underline">Change them in Accounts ↗</a> : "Change them in Accounts, under Church profile."}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({
|
||||
label, hint, required, children,
|
||||
}: {
|
||||
@@ -146,6 +161,14 @@ function SiteSettingsPageInner() {
|
||||
const [faviconPreview, setFaviconPreview] = useState<string | null>(null);
|
||||
const faviconRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
// ── From Accounts ── the settings the church profile sets (name, logo, colours, contact): shown,
|
||||
// not editable, and never sent back. The church profile's own page in Accounts changes them.
|
||||
const [managed, setManaged] = useState<Set<string>>(new Set());
|
||||
const church = useChurch();
|
||||
const accountsChurchUrl = church ? `${church.links.accounts.replace(/\/+$/, "")}/admin/church` : null;
|
||||
const fromAccounts = (key: string) => managed.has(key);
|
||||
const ownOnly = (updates: Record<string, string>) => Object.fromEntries(Object.entries(updates).filter(([k]) => !managed.has(k)));
|
||||
|
||||
// ── Notifications ──
|
||||
const [notifEmails, setNotifEmails] = useState("");
|
||||
|
||||
@@ -206,6 +229,7 @@ function SiteSettingsPageInner() {
|
||||
setLegalEffectiveDate(s.legal_effective_date || "");
|
||||
setConsentRetentionDays(s.consent_medical_retention_days || "30");
|
||||
setNotifyOnImpersonation(s.notify_user_on_impersonation === "true");
|
||||
setManaged(new Set((s.accounts_managed || "").split(",").filter(Boolean)));
|
||||
})
|
||||
.catch((e: unknown) => setResult({ ok: false, message: errorMessage(e) || "Failed to load settings" }))
|
||||
.finally(() => setLoadingInitial(false));
|
||||
@@ -220,7 +244,7 @@ function SiteSettingsPageInner() {
|
||||
setSaving(true);
|
||||
setResult(null);
|
||||
try {
|
||||
await apiV2Data("put", "/settings", { authToken: token, body: updates });
|
||||
await apiV2Data("put", "/settings", { authToken: token, body: ownOnly(updates) });
|
||||
setResult({ ok: true, message: "Saved." });
|
||||
reloadSettings();
|
||||
} catch (e) {
|
||||
@@ -271,13 +295,13 @@ function SiteSettingsPageInner() {
|
||||
|
||||
await apiV2Data("put", "/settings", {
|
||||
authToken: token,
|
||||
body: {
|
||||
body: ownOnly({
|
||||
primary_color: primaryColor,
|
||||
secondary_color: secondaryColor,
|
||||
accent_color: accentColor,
|
||||
logo_url: finalLogoUrl,
|
||||
favicon_url: finalFaviconUrl,
|
||||
},
|
||||
}),
|
||||
});
|
||||
setLogoUrl(finalLogoUrl);
|
||||
setLogoFile(null);
|
||||
@@ -303,13 +327,13 @@ function SiteSettingsPageInner() {
|
||||
try {
|
||||
await apiV2Data("put", "/settings", {
|
||||
authToken: token,
|
||||
body: { primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" },
|
||||
body: ownOnly({ primary_color: "", secondary_color: "", accent_color: "", logo_url: "", favicon_url: "" }),
|
||||
});
|
||||
setPrimaryColor("#4F46E5");
|
||||
if (!fromAccounts("primary_color")) setPrimaryColor("#4F46E5");
|
||||
setSecondaryColor("#8B5CF6");
|
||||
setAccentColor("#EC4899");
|
||||
setLogoUrl(""); setLogoFile(null); setLogoPreview(null);
|
||||
setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null);
|
||||
if (!fromAccounts("accent_color")) setAccentColor("#EC4899");
|
||||
if (!fromAccounts("logo_url")) { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); }
|
||||
if (!fromAccounts("favicon_url")) { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); }
|
||||
setSuggestedColors([]);
|
||||
setResult({ ok: true, message: "Reset to defaults." });
|
||||
reloadSettings();
|
||||
@@ -433,9 +457,10 @@ function SiteSettingsPageInner() {
|
||||
{activeTab === "organisation" && (
|
||||
<div className="space-y-4">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Organisation details</h2>
|
||||
{["org_name", "org_email", "org_phone", "org_address"].some(fromAccounts) && <FromAccountsNotice what="name and contact details" href={accountsChurchUrl} />}
|
||||
<Field label="Organisation name" required>
|
||||
<input className={inputCls} placeholder="Your Organisation"
|
||||
value={orgName} onChange={e => setOrgName(e.target.value)} />
|
||||
value={orgName} disabled={fromAccounts("org_name")} onChange={e => setOrgName(e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Tagline">
|
||||
<input className={inputCls} placeholder="Connecting community through events"
|
||||
@@ -444,16 +469,16 @@ function SiteSettingsPageInner() {
|
||||
<div className="grid sm:grid-cols-2 gap-4">
|
||||
<Field label="Contact email">
|
||||
<input type="email" className={inputCls} placeholder="admin@yourchurch.org"
|
||||
value={orgEmail} onChange={e => setOrgEmail(e.target.value)} />
|
||||
value={orgEmail} disabled={fromAccounts("org_email")} onChange={e => setOrgEmail(e.target.value)} />
|
||||
</Field>
|
||||
<Field label="Phone">
|
||||
<input className={inputCls} placeholder="+27 12 345 6789"
|
||||
value={orgPhone} onChange={e => setOrgPhone(e.target.value)} />
|
||||
value={orgPhone} disabled={fromAccounts("org_phone")} onChange={e => setOrgPhone(e.target.value)} />
|
||||
</Field>
|
||||
</div>
|
||||
<Field label="Address" hint="Used as the default location for new events.">
|
||||
<input className={inputCls} placeholder="123 Church St, City"
|
||||
value={orgAddress} onChange={e => setOrgAddress(e.target.value)} />
|
||||
value={orgAddress} disabled={fromAccounts("org_address")} onChange={e => setOrgAddress(e.target.value)} />
|
||||
{orgAddress.trim() && (
|
||||
<a href={mapsSearchUrl(orgAddress.trim())} target="_blank" rel="noopener noreferrer"
|
||||
className="inline-block text-xs text-brand-600 hover:underline mt-1">
|
||||
@@ -477,14 +502,15 @@ function SiteSettingsPageInner() {
|
||||
{activeTab === "branding" && (
|
||||
<div className="space-y-5">
|
||||
<h2 className="text-lg font-semibold text-gray-900">Branding</h2>
|
||||
{["primary_color", "accent_color", "logo_url", "favicon_url"].some(fromAccounts) && <FromAccountsNotice what="logo and colours" href={accountsChurchUrl} />}
|
||||
|
||||
<div className="grid sm:grid-cols-3 gap-4">
|
||||
<ColorPickerField label="Primary" hint="Buttons, links, nav highlights, and the email header/CTA."
|
||||
value={primaryColor} onChange={setPrimaryColor} />
|
||||
value={primaryColor} onChange={setPrimaryColor} disabled={fromAccounts("primary_color")} />
|
||||
<ColorPickerField label="Secondary" hint="Subtle backgrounds and outline-button borders/text."
|
||||
value={secondaryColor} onChange={setSecondaryColor} />
|
||||
<ColorPickerField label="Accent" hint="Hover states and highlight chips/badges."
|
||||
value={accentColor} onChange={setAccentColor} />
|
||||
value={accentColor} onChange={setAccentColor} disabled={fromAccounts("accent_color")} />
|
||||
</div>
|
||||
|
||||
<Field label="Site logo" hint="PNG, JPG, SVG or WebP, max 2 MB. Displayed in the navigation bar.">
|
||||
@@ -492,16 +518,16 @@ function SiteSettingsPageInner() {
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={currentLogoSrc} alt="Current logo" className="h-16 object-contain border rounded p-1 bg-gray-50" />
|
||||
<button
|
||||
{!fromAccounts("logo_url") && <button
|
||||
type="button"
|
||||
className="text-xs text-red-500 hover:text-red-700"
|
||||
onClick={() => { setLogoUrl(""); setLogoFile(null); setLogoPreview(null); setSuggestedColors([]); if (fileRef.current) fileRef.current.value = ""; }}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</button>}
|
||||
</div>
|
||||
)}
|
||||
<input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" />
|
||||
{!fromAccounts("logo_url") && <input ref={fileRef} type="file" accept="image/*" onChange={e => handleLogoFileChange(e.target.files?.[0])} className="text-sm" />}
|
||||
{suggestedColors.length > 0 && (
|
||||
<div className="mt-3 border rounded-lg p-3 bg-gray-50">
|
||||
<p className="text-xs font-medium text-gray-600 mb-2">Suggested from your logo — click a swatch to apply it</p>
|
||||
@@ -524,21 +550,21 @@ function SiteSettingsPageInner() {
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={currentFaviconSrc} alt="Current favicon" className="h-8 w-8 object-contain border rounded p-1 bg-gray-50" />
|
||||
<button
|
||||
{!fromAccounts("favicon_url") && <button
|
||||
type="button"
|
||||
className="text-xs text-red-500 hover:text-red-700"
|
||||
onClick={() => { setFaviconUrl(""); setFaviconFile(null); setFaviconPreview(null); if (faviconRef.current) faviconRef.current.value = ""; }}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</button>}
|
||||
</div>
|
||||
)}
|
||||
<input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => {
|
||||
{!fromAccounts("favicon_url") && <input ref={faviconRef} type="file" accept=".ico,.png,.svg,image/x-icon,image/png,image/svg+xml" onChange={e => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
setFaviconFile(file);
|
||||
setFaviconPreview(URL.createObjectURL(file));
|
||||
}} className="text-sm" />
|
||||
}} className="text-sm" />}
|
||||
</Field>
|
||||
|
||||
<div className="flex items-center justify-between pt-4 border-t mt-6 flex-wrap gap-3">
|
||||
|
||||
@@ -5,12 +5,14 @@ import { isValidHex } from "@/lib/colorScale";
|
||||
|
||||
/** A native color swatch + hex text input, shared by the admin Branding tab and the setup wizard's Branding step. */
|
||||
export function ColorPickerField({
|
||||
label, hint, value, onChange,
|
||||
label, hint, value, onChange, disabled,
|
||||
}: {
|
||||
label: string;
|
||||
hint?: string;
|
||||
value: string;
|
||||
onChange: (hex: string) => void;
|
||||
/** Set elsewhere (the church profile in Accounts): shown, not changed here. */
|
||||
disabled?: boolean;
|
||||
}) {
|
||||
const valid = isValidHex(value);
|
||||
return (
|
||||
@@ -19,13 +21,15 @@ export function ColorPickerField({
|
||||
<div className="flex items-center gap-3">
|
||||
<input
|
||||
type="color"
|
||||
className="h-10 w-20 border rounded cursor-pointer shrink-0"
|
||||
disabled={disabled}
|
||||
className="h-10 w-20 border rounded cursor-pointer shrink-0 disabled:cursor-not-allowed"
|
||||
value={valid ? value : "#000000"}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 ${valid ? "" : "border-red-300"}`}
|
||||
className={`w-full border rounded-lg px-3 py-2 text-sm font-mono focus:outline-none focus:ring-2 focus:ring-brand-400 disabled:bg-gray-50 disabled:text-gray-500 ${valid ? "" : "border-red-300"}`}
|
||||
placeholder="#2563eb"
|
||||
disabled={disabled}
|
||||
value={value}
|
||||
onChange={e => onChange(e.target.value)}
|
||||
/>
|
||||
|
||||
@@ -52,15 +52,18 @@ function computeApiBase(): string {
|
||||
export const API_BASE = computeApiBase();
|
||||
|
||||
// Resolve a URL or path to use the API origin. If it's a relative path, prefix with API_BASE.
|
||||
// If it's an absolute URL but points to localhost/127.0.0.1/::1, rewrite its origin to API_BASE.
|
||||
// If it's an absolute URL to this site's own uploads on localhost/127.0.0.1/::1, rewrite its
|
||||
// origin to API_BASE. Another localhost address (the church's Accounts in development, whose logo
|
||||
// the site now shows) is left as it is.
|
||||
export function resolveToApiOrigin(urlOrPath: string | null | undefined): string | null {
|
||||
const raw = (urlOrPath || "").trim();
|
||||
if (!raw) return null;
|
||||
try {
|
||||
if (raw.startsWith("http")) {
|
||||
const u = new URL(raw);
|
||||
const isLocal = ["localhost", "127.0.0.1", "::1"].includes(u.hostname);
|
||||
if (isLocal && API_BASE) {
|
||||
const isLocal = ["localhost", "127.0.0.1", "::1", "[::1]"].includes(u.hostname);
|
||||
const ownUpload = /^\/(api\/)?uploads\//.test(u.pathname);
|
||||
if (isLocal && ownUpload && API_BASE) {
|
||||
const api = new URL(API_BASE);
|
||||
u.protocol = api.protocol;
|
||||
u.hostname = api.hostname;
|
||||
|
||||
Reference in New Issue
Block a user