Files
crosscode-platform/apps/events/backend/src/utils/settingsCache.js
T
joshuaandClaude Opus 5.5 8055e1ec62 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>
2026-12-01 00:46:39 +02:00

120 lines
3.8 KiB
JavaScript

/**
* Lightweight in-process cache for AppSetting values.
* Refreshes every 60 seconds so changes made in the admin settings page
* take effect without a server restart.
* Falls back to environment variables when a key is not found in the DB.
*
* Encrypted keys (SMTP credentials, Yoco secrets) are automatically decrypted on read.
*/
const prisma = require('../config/db');
const { decrypt, isEncrypted } = require('./encryption');
// Keys stored encrypted in the DB — decrypted transparently on read.
const ENCRYPTED_KEYS = new Set(['smtp_user', 'smtp_pass', 'yoco_secret_key', 'yoco_webhook_secret', 'payfast_passphrase']);
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 = {};
for (const r of rows) fresh[r.key] = r.value;
_cache = fresh;
_lastFetch = now;
} catch {
// DB unreachable — keep existing cache; will retry next call
}
}
/**
* Internal getter that optionally decrypts encrypted keys.
* @param {string} key
* @param {string} [envFallback]
* @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)) {
try { return decrypt(raw); } catch { return ''; }
}
return raw;
}
/**
* Async getter — always checks for a stale cache before returning.
* @param {string} key
* @param {string} [envFallback]
* @returns {Promise<string>}
*/
async function getSetting(key, envFallback = '') {
await refreshIfStale();
return _getSync(key, envFallback);
}
/**
* Sync wrapper for use in synchronous functions.
* Uses the current in-memory snapshot; relies on the cache being warmed at startup.
*/
const getSettingSync = _getSync;
/**
* Call once at startup to pre-warm the cache so synchronous callers get DB values.
*/
async function warmCache() {
await refreshIfStale();
}
/** Invalidate the cache and immediately re-warm it in the background. */
function invalidate() {
_lastFetch = 0;
refreshIfStale().catch(() => {});
}
/** 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 };