Files
crosscode-platform/apps/app/backend/tests/support/memoryDb.ts
T
joshuaandClaude Opus 5.5 acd3b259a1 app: the demo scenarios (APP-1.0-PLAN §12)
npm run demo loads Acacia Hill; --profile/--scenario any of the eight
demo churches, around @crosscode/demo's people (the same account ids
as Accounts), in the scenario's active-member band: a prayer wall with
three months of commitments and the scenario's gaps, a campaign,
testimonies, prayer requests, announcements, the church's own
devotionals or Cross Code's from the Hub, and events (Cross Events' or
the Website's through the feed when linked, else the App's own).

The devotionals' passages are copied word for word from the public-
domain KJV and BSB by scripts/demo-passages.ts (no Bible text written
by hand). The sender never sends anything to a demo person.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 15:43:48 +02:00

225 lines
15 KiB
TypeScript

/**
* An in-memory stand-in for the Prisma client (from the Website's tests/support/memoryDb.ts): every
* model the App uses, with the schema's defaults and unique fields, generic `where` matching
* (equality, in / notIn, gt / gte / lt / lte, not, contains, endsWith, has, AND / OR), `include` of the
* relations below and `aggregate` sums. Enough to run the whole app in tests. Each module adds its
* models' defaults here as it arrives.
*/
import crypto from 'node:crypto';
type Row = Record<string, unknown>;
const DEFAULTS: Record<string, () => Row> = {
member: () => ({ phone: null, whatsappOptedOut: false, newsEmail: false, newsWhatsApp: false, roles: [], lastActiveAt: null, lastSignInAt: null }),
session: () => ({ sid: null, mfa: false, idToken: null, lastSeenAt: new Date() }),
productLink: () => ({ connectedById: null, lastSyncError: null, showEvents: true, lastSyncAt: null, lastGoodAt: null }),
auditLog: () => ({ actorId: null, targetId: null, metadata: null, ip: null }),
prayerCommitment: () => ({ reminder: 'hour1', channel: 'email', note: null, bookedById: null, renewalNoticesSent: 0, renewedAt: null }),
prayedMark: () => ({ memberId: null }),
prayerCampaign: () => ({ imageUrl: null, goal: null, targetPerSlot: null, createdById: null }),
testimony: () => ({ campaignId: null, showName: false, status: 'pending', removedReason: null, moderatedById: null, moderatedAt: null }),
accessLog: () => ({ targetId: null, metadata: null, ip: null }),
outboxMessage: () => ({ sentAt: null, sentVia: null, failedAt: null, error: null, attempts: 0 }),
notificationSettings: () => ({ requestUpdates: 'email', announcements: 'off', devotional: 'off', devotionalTime: '06:00', devotionalOfferedAt: null, lastDevotionalDate: null }),
messageCount: () => ({ count: 0 }),
mediaAsset: () => ({ width: null, height: null, alt: '', uploadedBy: null }),
prayerRequest: () => ({ visibility: 'team', showName: false, anonymous: false, moderation: 'none', redactedAt: null, redactionNote: null, removedReason: null, moderatedById: null, moderatedAt: null, escalatedAt: null, escalatedById: null, escalationNote: null, closedAt: null }),
prayerRequestUpdate: () => ({ authorId: null }),
announcement: () => ({ imageUrl: null, buttonLabel: null, buttonUrl: null, campus: null, audience: 'everyone', pinned: false, publishAt: null, endsAt: null, sendEmail: false, sendWhatsApp: false, sentAt: null, createdById: null }),
devotional: () => ({ originId: null, prayer: null, author: null, membersOnly: false, createdById: null }),
simpleEvent: () => ({ endsAt: null, allDay: false, timezone: 'Africa/Johannesburg', location: null, description: null, imageUrl: null, link: null, cancelled: false, publishedAt: null, updatedBy: null }),
importedEvent: () => ({ syncedAt: new Date() }),
};
const KEYS: Record<string, string> = { appSetting: 'key', notificationSettings: 'memberId', messageCount: 'key', productLink: 'installId', linkNonce: 'nonce', feedRemoval: 'eventId' };
/** Unique fields: one field, or several together (`@@unique([a, b])`). */
const UNIQUE: Record<string, (string | string[])[]> = { mediaAsset: ['filename'], session: ['tokenHash'], outboxMessage: ['dedupeKey'], prayerSkip: [['commitmentId', 'date']], prayedMark: [['commitmentId', 'date']], requestPrayer: [['requestId', 'memberId']], devotional: [['source', 'date']], announcement: ['slug'], simpleEvent: ['slug'], importedEvent: [['originProduct', 'originId']] };
const HAS_UPDATED_AT = new Set(['notificationSettings', 'member', 'appSetting', 'productLink', 'prayerCommitment', 'prayerCampaign', 'prayerRequest', 'announcement', 'devotional', 'simpleEvent']);
/** `include` support: model → relation → [other model, foreign key on the other (many) or on this row (one)]. */
const RELATIONS: Record<string, Record<string, { model: string; many: boolean; key: string }>> = {
member: { sessions: { model: 'session', many: true, key: 'memberId' } },
outboxMessage: { member: { model: 'member', many: false, key: 'memberId' } },
prayerRequest: { updates: { model: 'prayerRequestUpdate', many: true, key: 'requestId' }, prayers: { model: 'requestPrayer', many: true, key: 'requestId' } },
prayerCommitment: { skips: { model: 'prayerSkip', many: true, key: 'commitmentId' }, marks: { model: 'prayedMark', many: true, key: 'commitmentId' } },
};
const v = (x: unknown) => (x instanceof Date ? x.getTime() : x);
function matchValue(actual: unknown, cond: unknown): boolean {
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
const c = cond as Record<string, unknown>;
const insensitive = c.mode === 'insensitive';
return Object.entries(c).every(([op, x]) => {
switch (op) {
case 'mode': return true;
case 'equals': return v(actual) === v(x);
case 'in': return (x as unknown[]).map(v).includes(v(actual));
case 'notIn': return !(x as unknown[]).map(v).includes(v(actual));
case 'gt': return actual != null && (v(actual) as number) > (v(x) as number);
case 'gte': return actual != null && (v(actual) as number) >= (v(x) as number);
case 'lt': return actual != null && (v(actual) as number) < (v(x) as number);
case 'lte': return actual != null && (v(actual) as number) <= (v(x) as number);
case 'not': return x === null ? actual != null : !matchValue(actual, x);
case 'isEmpty': return Array.isArray(actual) && (actual.length === 0) === x;
case 'has': return Array.isArray(actual) && actual.map(v).includes(v(x));
case 'endsWith': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().endsWith(String(x).toLowerCase()) : actual.endsWith(String(x)));
case 'contains': return typeof actual === 'string' && (insensitive ? actual.toLowerCase().includes(String(x).toLowerCase()) : actual.includes(String(x)));
default: throw new Error(`memoryDb: no operator ${op}`);
}
});
}
return v(actual) === v(cond);
}
export function matches(row: Row, where: Row = {}): boolean {
return Object.entries(where ?? {}).every(([k, cond]) => {
if (k === 'AND') return (cond as Row[]).every((w) => matches(row, w));
if (k === 'OR') return (cond as Row[]).some((w) => matches(row, w));
if (k === 'NOT') return !matches(row, cond as Row);
return matchValue(row[k], cond);
});
}
/** 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[]) {
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
return [...rows].sort((a, b) => {
for (const o of list) {
const [k, dir] = Object.entries(o)[0]!;
const x = v(a[k]) as number;
const y = v(b[k]) as number;
const d = x < y ? -1 : x > y ? 1 : 0;
if (d) return dir === 'desc' ? -d : d;
}
return 0;
});
}
function prismaError(code: string, message: string) {
return Object.assign(new Error(message), { code });
}
/** `data` for an update, with `{ increment: n }` worked out against the row. */
function applied(row: Row, data: Row): Row {
const out = clone(data);
for (const [k, x] of Object.entries(out)) {
if (x && typeof x === 'object' && !(x instanceof Date) && !Array.isArray(x) && 'increment' in (x as Row)) out[k] = Number(row[k] ?? 0) + Number((x as Row).increment);
}
return out;
}
function model(name: string, tables: Map<string, Map<unknown, Row>>) {
const key = KEYS[name] ?? 'id';
const table = () => {
if (!tables.has(name)) tables.set(name, new Map());
return tables.get(name)!;
};
const findWhere = (where: Row) => {
if (where && key in where && typeof where[key] !== 'object') return table().get(where[key]) ?? null;
// A compound unique (`source_date: { source, date }`) is looked up by its fields.
for (const u of UNIQUE[name] ?? []) if (Array.isArray(u) && where && u.join('_') in where) { const w = where[u.join('_')] as Row; return [...table().values()].find((r) => u.every((f) => v(r[f]) === v(w[f]))) ?? null; }
for (const u of UNIQUE[name] ?? []) if (typeof u === 'string' && where && u in where) return [...table().values()].find((r) => r[u] === where[u]) ?? null;
return [...table().values()].find((r) => matches(r, where)) ?? null;
};
const checkUnique = (row: Row, except?: unknown) => {
for (const u of UNIQUE[name] ?? []) {
const fields = typeof u === 'string' ? [u] : u;
if (fields.some((f) => row[f] == null)) continue;
if ([...table().values()].some((r) => r[key] !== except && fields.every((f) => v(r[f]) === v(row[f])))) throw prismaError('P2002', `Unique constraint failed on ${name}.${fields.join('_')}`);
}
};
const api = {
findUnique: async ({ where, select, include }: { where: Row; select?: Row; include?: Row }) => { const r = findWhere(where); return r ? withIncludes(pick(clone(r), select), include) : null; },
findUniqueOrThrow: async (args: { where: Row; select?: Row }) => { const r = await api.findUnique(args); if (!r) throw prismaError('P2025', `${name} not found`); return r; },
findFirst: async ({ where, orderBy, select, include }: { where?: Row; orderBy?: Row | Row[]; select?: Row; include?: Row } = {}) => { const r = order([...table().values()].filter((x) => matches(x, where)), orderBy)[0]; return r ? withIncludes(pick(clone(r), select), include) : null; },
findMany: async ({ where, orderBy, take, skip, select, include }: { where?: Row; orderBy?: Row | Row[]; take?: number; skip?: number; select?: Row; include?: Row } = {}) =>
order([...table().values()].filter((x) => matches(x, where)), orderBy).slice(skip ?? 0, (skip ?? 0) + (take ?? Infinity)).map((r) => withIncludes(pick(clone(r), select), include)),
aggregate: async ({ where, _sum }: { where?: Row; _sum: Row }) => {
const rows = [...table().values()].filter((x) => matches(x, where));
return { _sum: Object.fromEntries(Object.keys(_sum).map((k) => [k, rows.length ? rows.reduce((t, r) => t + Number(r[k] ?? 0), 0) : null])) };
},
count: async ({ where }: { where?: Row } = {}) => [...table().values()].filter((x) => matches(x, where)).length,
create: async ({ data }: { data: Row }) => {
const now = new Date();
const row: Row = { ...(DEFAULTS[name]?.() ?? {}), ...(key === 'id' ? { id: crypto.randomUUID() } : {}), createdAt: now, ...(HAS_UPDATED_AT.has(name) ? { updatedAt: now } : {}), ...clone(data) };
if (table().has(row[key])) throw prismaError('P2002', `Unique constraint failed on ${name}.${key}`);
checkUnique(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})`);
const next = { ...r, ...applied(r, data), ...(HAS_UPDATED_AT.has(name) ? { updatedAt: new Date() } : {}) };
checkUnique(next, r[key]);
table().set(r[key], next);
return clone(next);
},
updateMany: async ({ where, data }: { where?: Row; data: Row }) => {
let count = 0;
for (const [k, r] of table()) if (matches(r, where)) { table().set(k, { ...r, ...applied(r, data) }); count++; }
return { count };
},
upsert: async ({ where, create, update }: { where: Row; create: Row; update: Row }) => {
const r = findWhere(where);
return r ? api.update({ where, data: update }) : api.create({ data: create });
},
delete: async ({ where }: { where: Row }) => {
const r = findWhere(where);
if (!r) throw prismaError('P2025', `Record to delete does not exist (${name})`);
table().delete(r[key]);
cascade(name, r[key]);
return clone(r);
},
deleteMany: async ({ where }: { where?: Row } = {}) => {
let count = 0;
for (const [k, r] of [...table()]) if (matches(r, where)) { table().delete(k); cascade(name, k); count++; }
return { count };
},
};
const cascade = (from: string, id: unknown) => {
const drop = (model: string, field: string) => { for (const [k, r] of tables.get(model) ?? []) if (r[field] === id) tables.get(model)!.delete(k); };
const unset = (model: string, field: string) => { for (const r of tables.get(model)?.values() ?? []) if (r[field] === id) r[field] = null; };
if (from === 'member') { drop('session', 'memberId'); drop('testimony', 'memberId'); drop('outboxMessage', 'memberId'); drop('prayerRequest', 'memberId'); drop('notificationSettings', 'memberId'); unset('prayerCommitment', 'memberId'); }
if (from === 'prayerCommitment') { drop('prayerSkip', 'commitmentId'); drop('prayedMark', 'commitmentId'); }
if (from === 'prayerCampaign') unset('testimony', 'campaignId');
if (from === 'productLink') drop('importedEvent', 'linkId');
if (from === 'prayerRequest') { drop('prayerRequestUpdate', 'requestId'); drop('requestPrayer', 'requestId'); }
};
const withIncludes = (row: Row, include?: Row) => {
for (const [rel, on] of Object.entries(include ?? {})) {
const spec = RELATIONS[name]?.[rel];
if (!on || !spec) continue;
const other = [...(tables.get(spec.model)?.values() ?? [])];
const nested = typeof on === 'object' ? (on as { orderBy?: Row | Row[] }).orderBy : undefined;
row[rel] = spec.many ? order(other.filter((o) => o[spec.key] === row.id), nested).map(clone) : clone(other.find((o) => o.id === row[spec.key]) ?? null);
}
return row;
};
return api;
}
export type MemoryDb = Record<string, ReturnType<typeof model>> & { tables: Map<string, Map<unknown, Row>>; $queryRaw: () => Promise<unknown[]>; $disconnect: () => Promise<void> };
export function memoryDb(): MemoryDb {
const tables = new Map<string, Map<unknown, Row>>();
const models = new Map<string, ReturnType<typeof model>>();
return new Proxy({} as MemoryDb, {
get(_t, prop: string) {
if (prop === 'tables') return tables;
if (prop === '$queryRaw' || prop === '$queryRawUnsafe') return async () => [{ ok: 1 }];
if (prop === '$disconnect') return async () => {};
if (prop === 'then') return undefined;
if (!models.has(prop)) models.set(prop, model(prop, tables));
return models.get(prop);
},
});
}